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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
add add endpoint to database
cparish312cb22f00a5cc5
diff --git a/screenpipe-server/benches/db_benchmarks.rs b/screenpipe-server/benches/db_benchmarks.rsindex 996e087d3..dbf7674dd 100644--- a/screenpipe-server/benches/db_benchmarks.rs+++ b/screenpipe-server/benches/db_benchmarks.rs@@ -14,7 +14,7 @@ async fn setup_large_db(size: usize) -> DatabaseManager {for _ in 0..size {let _video_id = db.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id = db.insert_frame().await.unwrap();+ let frame_id = db.insert_frame("test_device", None).await.unwrap();let ocr_text = format!("OCR text {}", rng.gen::<u32>());let text_json = format!(r#"{{"text": "{}"}}"#, ocr_text);db.insert_ocr_text(diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex e6f347c9a..5d4474a5c 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -224,7 +224,7 @@ async fn record_video(while is_running.load(Ordering::SeqCst) {if let Some(frame) = video_capture.ocr_frame_queue.pop() {for window_result in &frame.window_ocr_results {- match db.insert_frame(&device_name).await {+ match db.insert_frame(&device_name, None).await {Ok(frame_id) => {let text_json =serde_json::to_string(&window_result.text_json).unwrap_or_default();diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rsindex 6a20f419b..a771b0f30 100644--- a/screenpipe-server/src/db.rs+++ b/screenpipe-server/src/db.rs@@ -238,6 +238,7 @@ impl DatabaseManager {Ok(id)}+pub async fn update_audio_transcription(&self,audio_chunk_id: i64,@@ -272,7 +273,10 @@ impl DatabaseManager {Ok(id)}- pub async fn insert_frame(&self, device_name: &str) -> Result<i64, sqlx::Error> {+ pub async fn insert_frame(&self,+ device_name: &str,+ timestamp: Option<DateTime<Utc>>,+ ) -> Result<i64, sqlx::Error> {let mut tx = self.pool.begin().await?;debug!("insert_frame Transaction started");@@ -302,6 +306,8 @@ impl DatabaseManager {.fetch_one(&mut *tx).await?;debug!("insert_frame Calculated offset_index: {}", offset_index);++ let timestamp = timestamp.unwrap_or_else(Utc::now);// Insert the new framelet id = sqlx::query(@@ -309,7 +315,7 @@ impl DatabaseManager {).bind(video_chunk_id).bind(offset_index)- .bind(Utc::now())+ .bind(timestamp).execute(&mut *tx).await?.last_insert_rowid();@@ -329,14 +335,12 @@ impl DatabaseManager {text_json: &str,app_name: &str,window_name: &str,- ocr_engine: impl Into<OcrEngine>,+ ocr_engine: Arc<OcrEngine>,focused: bool,) -> Result<(), sqlx::Error> {const MAX_RETRIES: u32 = 3;const TIMEOUT_DURATION: TokioDuration = TokioDuration::from_secs(10);- let ocr_engine_str = ocr_engine.into().to_string();-for attempt in 1..=MAX_RETRIES {match timeout(TIMEOUT_DURATION,@@ -346,7 +350,7 @@ impl DatabaseManager {text_json,app_name,window_name,- &ocr_engine_str,+ Arc::clone(&ocr_engine),focused,),)@@ -396,7 +400,7 @@ impl DatabaseManager {text_json: &str,app_name: &str,window_name: &str,- ocr_engine: &str,+ ocr_engine: Arc<OcrEngine>,focused: bool,) -> Result<(), sqlx::Error> {let display_window_name = if window_name.chars().count() > 20 {@@ -421,7 +425,7 @@ impl DatabaseManager {.bind(text).bind(text_json).bind(app_name)- .bind(ocr_engine)+ .bind(format!("{:?}", *ocr_engine)).bind(window_name).bind(focused).execute(&mut *tx)diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex e96097116..2415e054a 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -12,13 +12,15 @@ use screenpipe_core::LLM;#[cfg(feature = "llm")]use screenpipe_core::{ChatRequest, ChatResponse};use screenpipe_vision::monitor::list_monitors;+use screenpipe_vision::OcrEngine;+use image::ImageFormat::{self};use crate::{db::TagContentType,pipe_manager::{PipeInfo, PipeManager},video_utils::{merge_videos, MergeVideosRequest, MergeVideosResponse},ContentType, DatabaseManager, SearchResult,- video::{start_ffmpeg_process, write_frame_to_ffmpeg, finish_ffmpeg_process}+ video::{start_ffmpeg_process, write_frame_to_ffmpeg, finish_ffmpeg_process, MAX_FPS}};use crate::{plugin::ApiPluginLayer, video_utils::extract_frame};use chrono::{DateTime, Utc};@@ -898,7 +900,6 @@ pub struct OCRResult {#[derive(Deserialize)]pub struct AudioTranscription {pub transcription: String,- pub timestamp: Option<DateTime<Utc>>,pub transcription_engine: String,}@@ -916,37 +917,35 @@ async fn add_frame_to_db(let db = &state.db;let frame_id = db.insert_frame(- device_name.to_string(),- frame.file_path.clone(),- frame.timestamp.unwrap_or_else(Utc::now),- frame.app_name.clone(),- frame.window_name.clone(),+ &device_name,+ Some(frame.timestamp.unwrap_or_else(Utc::now)),).await?;- if let Some(ocr_results) = frame.ocr_results {+ if let Some(ocr_results) = &frame.ocr_results {for ocr in ocr_results {db.insert_ocr_text(frame_id,- ocr.text,- ocr.text_json,- frame.app_name,- frame.window_name,- ocr.ocr_engine,+ &ocr.text,+ &ocr.text_json.as_deref().unwrap_or(""),+ &frame.app_name.as_deref().unwrap_or(""),+ &frame.window_name.as_deref().unwrap_or(""),+ Arc::new(OcrEngine::default()), // Ideally could pass any str as ocr_engine since can be run outside of screenpipefalse).await?;}}- if let Some(tags) = frame.tags {- db.add_tags(frame_id, TagContentType::Vision, tags).await?;+ if let Some(tags) = &frame.tags {+ db.add_tags(frame_id, TagContentType::Vision, tags.clone()).await?;}Ok(())}-fn encode_frame_from_file_path(file_path: &str) -> Result<Vec<u8>> {+fn encode_frame_from_file_path(file_path: &str) -> Result<Vec<u8>, anyhow::Error> {let image = image::open(file_path)?;let mut buffer = Vec::new();+ image.write_to(&mut std::io::Cursor::new(&mut buffer), ImageFormat::Png)?;Ok(buffer)}@@ -954,7 +953,7 @@ async fn write_frames_to_video(frames: &Vec<FrameContent>,video_file_path: &str,fps: f64,-) -> Result<()> {+) -> Result<(), anyhow::Error> {let mut ffmpeg_child = start_ffmpeg_process(video_file_path, fps).await?;let mut ffmpeg_stdin = ffmpeg_child.stdin.take().expect("Failed to open stdin for FFmpeg");@@ -977,12 +976,17 @@ async fn add_transcription_to_db() -> Result<(), anyhow::Error> {let db = &state.db;+ let device = AudioDevice {+ name: device_name.to_string(),+ device_type: DeviceType::Input,+ };+db.insert_audio_transcription(-1, // No associated audio chunk&transcription.transcription,-1,- transcription.transcription_engine,- device_name,+ &transcription.transcription_engine,+ &device,).await?;Ok(())@@ -998,9 +1002,10 @@ pub(crate) async fn add_to_database(match &payload.content {AddContentData::Frames(frames) => {if !frames.is_empty() {+ let output_dir = state.screenpipe_dir.join("videos");let time = Utc::now();let formatted_time = time.format("%Y-%m-%d_%H-%M-%S").to_string();- let video_file_path = PathBuf::from(output_path)+ let video_file_path = PathBuf::from(output_dir).join(format!("{}_{}.mp4", device_name, formatted_time)).to_str().expect("Failed to create valid path")@@ -1014,7 +1019,7 @@ pub(crate) async fn add_to_database());}- if let Err(e) = write_frames_to_video(frames.clone(), &video_file_path, MAX_FPS).await {+ if let Err(e) = write_frames_to_video(frames, &video_file_path, MAX_FPS).await {error!("Failed to write frames to video file {}: {}", video_file_path, e);return Err((StatusCode::INTERNAL_SERVER_ERROR,diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex d3d4ab6b3..6184bf981 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -16,7 +16,7 @@ use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command};use tokio::sync::mpsc::channel;use tokio::time::sleep;-const MAX_FPS: f64 = 30.0; // Adjust based on your needs+pub(crate) const MAX_FPS: f64 = 30.0; // Adjust based on your needsconst MAX_QUEUE_SIZE: usize = 10;pub struct VideoCapture {diff --git a/screenpipe-server/tests/db.rs b/screenpipe-server/tests/db.rsindex 0f925b3e6..16f5520f1 100644--- a/screenpipe-server/tests/db.rs+++ b/screenpipe-server/tests/db.rs@@ -15,7 +15,7 @@ mod tests {async fn test_insert_and_search_ocr() {let db = setup_test_db().await;let _ = db.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id = db.insert_frame("test_device").await.unwrap();+ let frame_id = db.insert_frame("test_device", None).await.unwrap();db.insert_ocr_text(frame_id,"Hello, world!",@@ -141,7 +141,7 @@ mod tests {// Insert OCR datalet _ = db.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id = db.insert_frame("test_device").await.unwrap();+ let frame_id = db.insert_frame("test_device", None).await.unwrap();db.insert_ocr_text(frame_id,"Hello from OCR",@@ -204,7 +204,7 @@ mod tests {// Insert OCR datalet _ = db.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id1 = db.insert_frame("test_device").await.unwrap();+ let frame_id1 = db.insert_frame("test_device", None).await.unwrap();db.insert_ocr_text(frame_id1,"Hello from OCR 1",@@ -238,7 +238,7 @@ mod tests {tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;// Insert remaining data- let frame_id2 = db.insert_frame("test_device").await.unwrap();+ let frame_id2 = db.insert_frame("test_device", None).await.unwrap();db.insert_ocr_text(frame_id2,"Hello from OCR 2",@@ -356,7 +356,7 @@ mod tests {// Insert OCR datalet _ = db.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id1 = db.insert_frame("test_device").await.unwrap();+ let frame_id1 = db.insert_frame("test_device", None).await.unwrap();db.insert_ocr_text(frame_id1,"Hello from OCR 1",@@ -388,7 +388,7 @@ mod tests {tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;// Insert remaining data- let frame_id2 = db.insert_frame("test_device").await.unwrap();+ let frame_id2 = db.insert_frame("test_device", None).await.unwrap();db.insert_ocr_text(frame_id2,"Hello from OCR 2",diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rsindex 4fa32cb5d..9b0a894fa 100644--- a/screenpipe-server/tests/endpoint_test.rs+++ b/screenpipe-server/tests/endpoint_test.rs@@ -120,7 +120,7 @@ mod tests {// Insert some recent datalet _ = db.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id = db.insert_frame("test_device").await.unwrap();+ let frame_id = db.insert_frame("test_device", None).await.unwrap();let _ = db.insert_ocr_text(frame_id,@@ -180,7 +180,7 @@ mod tests {// Insert some stale data (more than 60 seconds old)let stale_time = Utc::now() - Duration::seconds(61);let _ = db.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id = db.insert_frame("test_device").await.unwrap();+ let frame_id = db.insert_frame("test_device", None).await.unwrap();let _ = db.insert_ocr_text(frame_id,@@ -352,8 +352,8 @@ mod tests {// Insert some test datalet _ = db.insert_video_chunk("test_video1.mp4", "test_device").await.unwrap();- let frame_id1 = db.insert_frame("test_device").await.unwrap();- let frame_id2 = db.insert_frame("test_device").await.unwrap();+ let frame_id1 = db.insert_frame("test_device", None).await.unwrap();+ let frame_id2 = db.insert_frame("test_device", None).await.unwrap();let _ = db.insert_ocr_text(frame_id1,@@ -504,7 +504,7 @@ mod tests {// insert test data with different timestampslet _ = db.insert_video_chunk("test_video1.mp4", "test_device").await.unwrap();- let frame_id1 = db.insert_frame("test_device").await.unwrap();+ let frame_id1 = db.insert_frame("test_device", None).await.unwrap();let audio_chunk_id1 = db.insert_audio_chunk("test_audio1.wav").await.unwrap();let now = DateTime::parse_from_rfc3339("2024-09-21T10:49:23.240367Z")diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rsindex bb1761286..d829efcf0 100644--- a/screenpipe-server/tests/tags_test.rs+++ b/screenpipe-server/tests/tags_test.rs@@ -360,7 +360,7 @@ async fn insert_test_data(db: &Arc<DatabaseManager>) {let _video_chunk_id = db.insert_video_chunk("test_video_file.mp4", "test_device").await.unwrap();// Insert test frame- let frame_id = db.insert_frame("test_device").await.unwrap();+ let frame_id = db.insert_frame("test_device", None).await.unwrap();// Insert test OCR datadb.insert_ocr_text(