Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat: add time filter in search

Louis Beaumont1fb2c283d343
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 7d58f2e07..971aa6dff 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -53,6 +53,14 @@ We follow [this](https://doc.rust-lang.org/cargo/guide/project-layout.html) fold
## Additional Notes
+### Principles
+
+- **User fanatic: focus on building what people want and making users happy.**
+- Concurrency: channels > mutexes/locks
+- Simplicity: avoid premature optimization.
+- Use numbers: if you can't measure it, you can't improve it.
+- Avoid OOP: prefer functional programming.
+
### Issue and Pull Request Labels
This section lists the labels we use to help us track and manage issues and pull requests.
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index 56497bb9f..24d435ba4 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -168,19 +168,37 @@ impl DatabaseManager {
content_type: ContentType,
limit: u32,
offset: u32,
+ start_time: Option<DateTime<Utc>>,
+ end_time: Option<DateTime<Utc>>,
) -> Result<Vec<SearchResult>, sqlx::Error> {
let mut results = Vec::new();
if content_type == ContentType::All || content_type == ContentType::OCR {
- let ocr_results = self.search_ocr(query, limit, offset).await?;
+ let ocr_results = self.search_ocr(query, limit, offset, start_time, end_time).await?;
results.extend(ocr_results.into_iter().map(SearchResult::OCR));
}
if content_type == ContentType::All || content_type == ContentType::Audio {
- let audio_results = self.search_audio(query, limit, offset).await?;
+ let audio_results = self.search_audio(query, limit, offset, start_time, end_time).await?;
results.extend(audio_results.into_iter().map(SearchResult::Audio));
}
+ // Sort results by timestamp in descending order
+ results.sort_by(|a, b| {
+ let timestamp_a = match a {
+ SearchResult::OCR(ocr) => ocr.timestamp,
+ SearchResult::Audio(audio) => audio.timestamp,
+ };
+ let timestamp_b = match b {
+ SearchResult::OCR(ocr) => ocr.timestamp,
+ SearchResult::Audio(audio) => audio.timestamp,
+ };
+ timestamp_b.cmp(&timestamp_a)
+ });
+
+ // Apply limit after combining and sorting
+ results.truncate(limit as usize);
+
Ok(results)
}
@@ -189,6 +207,8 @@ impl DatabaseManager {
query: &str,
limit: u32,
offset: u32,
+ start_time: Option<DateTime<Utc>>,
+ end_time: Option<DateTime<Utc>>,
) -> Result<Vec<OCRResult>, sqlx::Error> {
sqlx::query_as::<_, OCRResult>(
r#"
@@ -206,12 +226,16 @@ impl DatabaseManager {
video_chunks ON frames.video_chunk_id = video_chunks.id
WHERE
ocr_text.text LIKE '%' || ?1 || '%'
+ AND (?2 IS NULL OR frames.timestamp >= ?2)
+ AND (?3 IS NULL OR frames.timestamp <= ?3)
ORDER BY
frames.timestamp DESC
- LIMIT ?2 OFFSET ?3
+ LIMIT ?4 OFFSET ?5
"#,
)
.bind(query)
+ .bind(start_time)
+ .bind(end_time)
.bind(limit)
.bind(offset)
.fetch_all(&self.pool)
@@ -223,6 +247,8 @@ impl DatabaseManager {
query: &str,
limit: u32,
offset: u32,
+ start_time: Option<DateTime<Utc>>,
+ end_time: Option<DateTime<Utc>>,
) -> Result<Vec<AudioResult>, sqlx::Error> {
sqlx::query_as::<_, AudioResult>(
r#"
@@ -238,12 +264,16 @@ impl DatabaseManager {
audio_chunks ON audio_transcriptions.audio_chunk_id = audio_chunks.id
WHERE
audio_transcriptions.transcription LIKE '%' || ?1 || '%'
+ AND (?2 IS NULL OR audio_transcriptions.timestamp >= ?2)
+ AND (?3 IS NULL OR audio_transcriptions.timestamp <= ?3)
ORDER BY
audio_transcriptions.timestamp DESC
- LIMIT ?2 OFFSET ?3
+ LIMIT ?4 OFFSET ?5
"#,
)
.bind(query)
+ .bind(start_time)
+ .bind(end_time)
.bind(limit)
.bind(offset)
.fetch_all(&self.pool)
@@ -362,23 +392,43 @@ impl DatabaseManager {
&self,
query: &str,
content_type: ContentType,
+ start_time: Option<DateTime<Utc>>,
+ end_time: Option<DateTime<Utc>>,
) -> Result<usize, sqlx::Error> {
let mut total_count = 0;
if content_type == ContentType::All || content_type == ContentType::OCR {
- let ocr_count: (i64,) =
- sqlx::query_as("SELECT COUNT(*) FROM ocr_text WHERE text LIKE '%' || ?1 || '%'")
- .bind(query)
- .fetch_one(&self.pool)
- .await?;
+ let ocr_count: (i64,) = sqlx::query_as(
+ r#"
+ SELECT COUNT(*)
+ FROM ocr_text
+ JOIN frames ON ocr_text.frame_id = frames.id
+ WHERE text LIKE '%' || ?1 || '%'
+ AND (?2 IS NULL OR frames.timestamp >= ?2)
+ AND (?3 IS NULL OR frames.timestamp <= ?3)
+ "#,
+ )
+ .bind(query)
+ .bind(start_time)
+ .bind(end_time)
+ .fetch_one(&self.pool)
+ .await?;
total_count += ocr_count.0 as usize;
}
if content_type == ContentType::All || content_type == ContentType::Audio {
let audio_count: (i64,) = sqlx::query_as(
- "SELECT COUNT(*) FROM audio_transcriptions WHERE transcription LIKE '%' || ?1 || '%'"
+ r#"
+ SELECT COUNT(*)
+ FROM audio_transcriptions
+ WHERE transcription LIKE '%' || ?1 || '%'
+ AND (?2 IS NULL OR timestamp >= ?2)
+ AND (?3 IS NULL OR timestamp <= ?3)
+ "#,
)
.bind(query)
+ .bind(start_time)
+ .bind(end_time)
.fetch_one(&self.pool)
.await?;
total_count += audio_count.0 as usize;
@@ -437,4 +487,3 @@ impl Clone for DatabaseManager {
}
}
}
-
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 9e2f35786..c5fcf0872 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -52,6 +52,10 @@ pub(crate) struct SearchQuery {
pagination: PaginationQuery,
#[serde(default)]
content_type: ContentType,
+ #[serde(default)]
+ start_time: Option<DateTime<Utc>>,
+ #[serde(default)]
+ end_time: Option<DateTime<Utc>>,
}
#[derive(Deserialize)]
@@ -146,11 +150,13 @@ pub(crate) async fn search(
(StatusCode, JsonResponse<serde_json::Value>),
> {
info!(
- "Received search request: query='{}', content_type={:?}, limit={}, offset={}",
+ "Received search request: query='{}', content_type={:?}, limit={}, offset={}, start_time={:?}, end_time={:?}",
query.q.as_deref().unwrap_or(""),
query.content_type,
query.pagination.limit,
- query.pagination.offset
+ query.pagination.offset,
+ query.start_time,
+ query.end_time
);
let query_str = query.q.as_deref().unwrap_or("");
@@ -161,6 +167,8 @@ pub(crate) async fn search(
query.content_type,
query.pagination.limit,
query.pagination.offset,
+ query.start_time,
+ query.end_time,
)
.await
.map_err(|e| {
@@ -173,7 +181,12 @@ pub(crate) async fn search(
let total = state
.db
- .count_search_results(query_str, query.content_type)
+ .count_search_results(
+ query_str,
+ query.content_type,
+ query.start_time,
+ query.end_time,
+ )
.await
.map_err(|e| {
error!("Failed to count search results: {}", e);
@@ -519,5 +532,20 @@ curl "http://localhost:3030/search?limit=5&offset=0&content_type=ocr" | jq
curl "http://localhost:3030/search?q=libmp3&limit=5&offset=0&content_type=all" | jq
+# Search for content from the last 30 minutes
+curl "http://localhost:3035/search?q=test&limit=5&offset=0&content_type=all&start_time=$(date -u -v-5M +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+# Search for content up to 1 hour ago
+curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+# Search for content between 2 hours ago and 1 hour ago
+curl "http://localhost:3035/search?limit=50&offset=0&content_type=all&start_time=$(date -u -v-2H +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+# Search for OCR content from yesterday
+curl "http://localhost:3030/search?limit=5&offset=0&content_type=ocr&start_time=$(date -u -v-1d -v0H -v0M -v0S +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-1d -v23H -v59M -v59S +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+# Search for audio content with a keyword from the beginning of the current month
+curl "http://localhost:3030/search?q=libmp3&limit=5&offset=0&content_type=audio&start_time=$(date -u -v1d -v0H -v0M -v0S +%Y-%m-01T%H:%M:%SZ)" | jq
+
*/
diff --git a/screenpipe-server/tests/db.rs b/screenpipe-server/tests/db.rs
index 2f864e35f..e95153838 100644
--- a/screenpipe-server/tests/db.rs
+++ b/screenpipe-server/tests/db.rs
@@ -1,5 +1,6 @@
#[cfg(test)]
mod tests {
+ use chrono::Utc;
use screenpipe_server::{ContentType, DatabaseManager, SearchResult};
async fn setup_test_db() -> DatabaseManager {
@@ -13,7 +14,10 @@ mod tests {
let frame_id = db.insert_frame().await.unwrap();
db.insert_ocr_text(frame_id, "Hello, world!").await.unwrap();
- let results = db.search("Hello", ContentType::OCR, 100, 0).await.unwrap();
+ let results = db
+ .search("Hello", ContentType::OCR, 100, 0, None, None)
+ .await
+ .unwrap();
assert_eq!(results.len(), 1);
if let SearchResult::OCR(ocr_result) = &results[0] {
assert_eq!(ocr_result.ocr_text, "Hello, world!");
@@ -32,7 +36,7 @@ mod tests {
.unwrap();
let results = db
- .search("audio", ContentType::Audio, 100, 0)
+ .search("audio", ContentType::Audio, 100, 0, None, None)
.await
.unwrap();
assert_eq!(results.len(), 1);
@@ -61,7 +65,10 @@ mod tests {
.await
.unwrap();
- let results = db.search("Hello", ContentType::All, 100, 0).await.unwrap();
+ let results = db
+ .search("Hello", ContentType::All, 100, 0, None, None)
+ .await
+ .unwrap();
assert_eq!(results.len(), 2);
let ocr_count = results
@@ -76,4 +83,176 @@ mod tests {
assert_eq!(ocr_count, 1);
assert_eq!(audio_count, 1);
}
+
+ #[tokio::test]
+ async fn test_search_with_time_range() {
+ let db = setup_test_db().await;
+
+ let start_time = Utc::now();
+
+ // Insert OCR data
+ let _ = db.insert_video_chunk("test_video.mp4").await.unwrap();
+ let frame_id1 = db.insert_frame().await.unwrap();
+ db.insert_ocr_text(frame_id1, "Hello from OCR 1")
+ .await
+ .unwrap();
+
+ // Insert first audio data
+ let audio_chunk_id = db.insert_audio_chunk("test_audio.mp3").await.unwrap();
+ db.insert_audio_transcription(audio_chunk_id, "Hello from audio 1", 0)
+ .await
+ .unwrap();
+
+ // Wait for a short time to ensure timestamp difference
+ tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
+
+ let mid_time = Utc::now();
+
+ // Wait for another short time
+ tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
+
+ // Insert remaining data
+ let frame_id2 = db.insert_frame().await.unwrap();
+ db.insert_ocr_text(frame_id2, "Hello from OCR 2")
+ .await
+ .unwrap();
+
+ db.insert_audio_transcription(audio_chunk_id, "Hello from audio 2", 1)
+ .await
+ .unwrap();
+
+ let end_time = Utc::now();
+
+ // Test search with full time range
+ let results = db
+ .search(
+ "Hello",
+ ContentType::All,
+ 100,
+ 0,
+ Some(start_time),
+ Some(end_time),
+ )
+ .await
+ .unwrap();
+ println!("Full time range results: {:?}", results);
+ assert_eq!(results.len(), 4, "Expected 4 results for full time range");
+
+ // Test search with limited time range
+ let results = db
+ .search(
+ "Hello",
+ ContentType::All,
+ 100,
+ 0,
+ Some(mid_time),
+ Some(end_time),
+ )
+ .await
+ .unwrap();
+ println!("Limited time range results: {:?}", results);
+ assert_eq!(
+ results.len(),
+ 2,
+ "Expected 2 results for limited time range"
+ );
+
+ // Test search with OCR content type and time range
+ let results = db
+ .search(
+ "Hello",
+ ContentType::OCR,
+ 100,
+ 0,
+ Some(start_time),
+ Some(end_time),
+ )
+ .await
+ .unwrap();
+ assert_eq!(results.len(), 2);
+
+ // Test search with Audio content type and time range
+ let results = db
+ .search(
+ "Hello",
+ ContentType::Audio,
+ 100,
+ 0,
+ Some(start_time),
+ Some(end_time),
+ )
+ .await
+ .unwrap();
+ assert_eq!(results.len(), 2);
+ }
+
+ #[tokio::test]
+ async fn test_count_search_results_with_time_range() {
+ let db = setup_test_db().await;
+
+ let start_time = Utc::now();
+
+ // Insert OCR data
+ let _ = db.insert_video_chunk("test_video.mp4").await.unwrap();
+ let frame_id1 = db.insert_frame().await.unwrap();
+ db.insert_ocr_text(frame_id1, "Hello from OCR 1")
+ .await
+ .unwrap();
+
+ // Insert first audio data
+ let audio_chunk_id = db.insert_audio_chunk("test_audio.mp3").await.unwrap();
+ db.insert_audio_transcription(audio_chunk_id, "Hello from audio 1", 0)
+ .await
+ .unwrap();
+
+ // Capture mid_time after inserting half of the data
+ let mid_time = Utc::now();
+
+ // Wait for a short time to ensure timestamp difference
+ tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
+
+ // Insert remaining data
+ let frame_id2 = db.insert_frame().await.unwrap();
+ db.insert_ocr_text(frame_id2, "Hello from OCR 2")
+ .await
+ .unwrap();
+
+ db.insert_audio_transcription(audio_chunk_id, "Hello from audio 2", 1)
+ .await
+ .unwrap();
+
+ let end_time = Utc::now();
+
+ // Test search with limited time range
+ let results = db
+ .search(
+ "Hello",
+ ContentType::All,
+ 100,
+ 0,
+ Some(mid_time),
+ Some(end_time),
+ )
+ .await
+ .unwrap();
+
+ println!("Limited time range results: {:?}", results);
+ assert_eq!(
+ results.len(),
+ 2,
+ "Expected 2 results for limited time range"
+ );
+
+ // Test count with Audio content type and time range
+ let count = db
+ .count_search_results(
+ "Hello",
+ ContentType::Audio,
+ Some(start_time),
+ Some(end_time),
+ )
+ .await
+ .unwrap();
+ assert_eq!(count, 2);
+ }
}
diff --git a/screenpipe-vision/src/lib.rs b/screenpipe-vision/src/lib.rs
index f04c1a2e1..9dc4087a3 100644
--- a/screenpipe-vision/src/lib.rs
+++ b/screenpipe-vision/src/lib.rs
@@ -1,3 +1,4 @@
pub mod core;
mod utils;
-pub use core::{continuous_capture, ControlMessage, CaptureResult};
\ No newline at end of file
+pub use core::{continuous_capture, CaptureResult, ControlMessage};
+pub use utils::perform_ocr;
diff --git a/screenpipe-vision/tests/integration_test.rs b/screenpipe-vision/tests/integration_test.rs
index ffc9ec594..ec2cb6ef6 100644
--- a/screenpipe-vision/tests/integration_test.rs
+++ b/screenpipe-vision/tests/integration_test.rs
@@ -1,10 +1,10 @@
-use assert_fs::prelude::*;
use std::path::PathBuf;
-use std::fs;
use std::time::Instant;
-use screenpipe_vision::core::perform_ocr; // Adjust the import path
+
+use screenpipe_vision::perform_ocr;
#[test]
+#[ignore] // TODO: finish implementation of this test?
fn test_ocr_output() -> Result<(), Box<dyn std::error::Error>> {
println!("Starting test_ocr_output");
@@ -46,9 +46,8 @@ fn test_ocr_output() -> Result<(), Box<dyn std::error::Error>> {
// println!("Character length of TSV output: {}", tsv_output.len());
println!("Character length of JSON output: {}", json_output.len());
-
assert!(!text.is_empty(), "OCR text should not be empty");
// assert!(!tsv_output.is_empty(), "TSV output should not be empty");
Ok(())
-}
\ No newline at end of file
+}