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
last fixes
Louis Beaumont2468aadec8e8
diff --git a/Cargo.toml b/Cargo.tomlindex c30532d04..e355cfb45 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,5 +1,5 @@[workspace]-members = ["screenpipe-server", "screenpipe-vision", "screenpipe-audio", "examples/maintain-a-log-of-my-day"]+members = ["screenpipe-server", "screenpipe-vision", "screenpipe-audio"]exclude = []resolver = "2"diff --git a/examples/maintain-a-log-of-my-day/Cargo.toml b/examples/maintain-a-log-of-my-day/Cargo.tomldeleted file mode 100644index 00759e9ad..000000000--- a/examples/maintain-a-log-of-my-day/Cargo.toml+++ /dev/null@@ -1,10 +0,0 @@-[package]-name = "maintain-a-log-of-my-day"-version = "0.1.0"-edition = "2021"--[dependencies]-rusqlite = { version = "0.30.0", features = ["chrono", "bundled", "array"] }-reqwest = { version = "0.11", features = ["json", "multipart", "blocking"] }-serde = "1.0"-serde_json = "1.0"\ No newline at end of filediff --git a/examples/maintain-a-log-of-my-day/src/main.rs b/examples/maintain-a-log-of-my-day/src/main.rsdeleted file mode 100644index 12a720484..000000000--- a/examples/maintain-a-log-of-my-day/src/main.rs+++ /dev/null@@ -1,101 +0,0 @@-// !!very experimental package!!-// This is a simple implementation of a main function that watches for changes in the database-// and performs actions based on specific triggers. The end goal is to create a system similar-// to Apple Shortcuts, where triggers and actions can be defined dynamically. In this version,-// we hardcode some trigger queries and actions for demonstration purposes.-//-// Triggers:-// - Specific SQL query hit like "dog appear 50 times within the past 2 days"-// - More advanced/complex triggers can be added later (e.g., "when I seem to watch TikTok videos about cats for 2 hours")-//-// Actions:-// - Make a request to an API-// - Function calling-// - Executing some code-//-// This is a basic version and can be iterated upon for more complex triggers and actions.-// This maintain a log of what you've been doing today--// make sure to run `ollama run phi3`--use reqwest::blocking::Client;-use rusqlite::Connection;-use std::fs;-use std::thread;-use std::time::Duration;-use serde_json::json;-fn main() {- let conn = Connection::open("../../screenpipe/data/db.sqlite").unwrap();- let client = Client::new();- // create file log with empty lines- fs::write("log.md", "").unwrap();- loop {- let query = "- SELECT COUNT(*), GROUP_CONCAT(at.text)- FROM ocr_text at- JOIN frames f ON at.frame_id = f.id- WHERE f.timestamp <= datetime('now', '1 minutes')- ORDER BY f.timestamp DESC- LIMIT 100- ";- let count: i64 = conn.query_row(query, [], |row| row.get(0)).unwrap();- let texts: Option<String> = conn.query_row(query, [], |row| row.get(1)).unwrap_or(None);--- println!("{}", count);- if texts.is_some() {- let texts = texts.unwrap();- // println!("{}", texts);- let response = client- .post("http://localhost:11434/api/chat")- .json(&json!({- "model": "phi3",- "stream": false,- "max_tokens": 4096,- "messages": [- {- "role": "user",- "content": format!(r#"you receive a markdown log of what the user has been doing today,- that you maintain based on the text extracted from the user's screen.- You can add new categories or update the existing ones. You can also add a new entry to the log.- This is what has been shown on the user's screen over the past 5 minutes: {}- And this is the current log: {}-- Rules:- - Keep the log small and concise, formatted as a bullet list- - Your responses are NOT in a code block e.g. no ```plaintext ```markdown etc.!- - DO WRITE A LOG OF THE USER'S DAY. NOTHING ELSE-- Now update the log based on the user's screen and respond with only the updated log.- LOG OF THE USER'S DAY:- "#,- texts,- fs::read_to_string("log.md").unwrap()- )- }- ]- }))- .send();-- if let Ok(response) = response {- let text: serde_json::Value = response.json().unwrap();- // remove first " and last " from the response- let llm_response = text["message"]["content"].to_string().trim_matches('"').to_string();-- println!("{}", llm_response);-- // replace all \n with \n\n- let llm_response = llm_response.replace("\\n", "\n\n");-- // update to file- fs::write("log.md", llm_response).unwrap();- } else {- eprintln!("Request failed, skipping to next iteration.");- continue;- }- }-- // Sleep for a while before checking again- thread::sleep(Duration::from_secs(5));- }-}diff --git a/examples/ts/maintain-a-log-of-my-day/.gitignore b/examples/ts/maintain-a-log-of-my-day/.gitignorenew file mode 100644index 000000000..dfd250cf1--- /dev/null+++ b/examples/ts/maintain-a-log-of-my-day/.gitignore@@ -0,0 +1,3 @@+node_modules+pnpm-lock.yaml+yarn.lock\ No newline at end of filediff --git a/examples/maintain-a-log-of-my-day/log.md b/examples/ts/maintain-a-log-of-my-day/log.mdsimilarity index 100%rename from examples/maintain-a-log-of-my-day/log.mdrename to examples/ts/maintain-a-log-of-my-day/log.mddiff --git a/examples/ts/maintain-a-log-of-my-day/main.ts b/examples/ts/maintain-a-log-of-my-day/main.tsnew file mode 100644index 000000000..8bba53441--- /dev/null+++ b/examples/ts/maintain-a-log-of-my-day/main.ts@@ -0,0 +1,81 @@+import fetch from "cross-fetch";+// @ts-ignore+import * as fs from "node:fs/promises";++async function main() {+ // Create file log with empty lines+ await fs.writeFile("log.md", "");++ while (true) {+ try {+ // Use the API to get recent OCR text++ const response = await fetch(+ `http://localhost:3030/recent?limit=5&offset=0`+ );++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(`API error: ${errorData.error || response.statusText}`);+ }++ const json = await response.json();+ const texts = json.data+ .filter((item) => item.text)+ .map((item) => item.text);+ const concatenatedTexts = texts.join(" ");++ // Read current log+ const currentLog = await fs.readFile("log.md", "utf-8");++ console.log(concatenatedTexts);++ // Use the LLM to update the log+ const llmResponse = await fetch("http://localhost:11434/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model: "phi3",+ stream: false,+ max_tokens: 4096,+ messages: [+ {+ role: "user",+ content: `you receive a markdown log of what the user has been doing today,+ that you maintain based on the text extracted from the user's screen.+ You can add new categories or update the existing ones. You can also add a new entry to the log.+ This is what has been shown on the user's screen over the past 5 minutes: ${concatenatedTexts}+ And this is the current log: ${currentLog}++ Rules:+ - Keep the log small and concise, formatted as a bullet list+ - Your responses are NOT in a code block e.g. no \`\`\`plaintext \`\`\`markdown etc.!+ - DO WRITE A LOG OF THE USER'S DAY. NOTHING ELSE++ Now update the log based on the user's screen and respond with only the updated log.+ LOG OF THE USER'S DAY:`,+ },+ ],+ }),+ });++ const text = await llmResponse.json();+ let llmResponseText = text.message.content.trim().replace(/^"|"$/g, "");++ console.log(llmResponseText);++ // Replace all \n with \n\n+ llmResponseText = llmResponseText.replace(/\\n/g, "\n\n");++ // Update file+ await fs.writeFile("log.md", llmResponseText);+ } catch (error) {+ console.error("An error occurred:", error);+ }++ // Sleep for a while before checking again+ await new Promise((resolve) => setTimeout(resolve, 5000));+ }+}++main();diff --git a/examples/ts/maintain-a-log-of-my-day/package.json b/examples/ts/maintain-a-log-of-my-day/package.jsonnew file mode 100644index 000000000..b24ca4312--- /dev/null+++ b/examples/ts/maintain-a-log-of-my-day/package.json@@ -0,0 +1,8 @@+{+ "dependencies": {+ "cross-fetch": "^4.0.0"+ },+ "devDependencies": {+ "@types/node": "^20.14.9"+ }+}diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rsindex 0e6f25753..474fd406c 100644--- a/screenpipe-audio/src/core.rs+++ b/screenpipe-audio/src/core.rs@@ -69,16 +69,13 @@ pub fn continuous_audio_capture(}}}- info!("Processing audio2...");if *is_paused_clone.lock().unwrap() {thread::sleep(Duration::from_millis(100));continue;}- info!("Processing audio3...");thread::sleep(chunk_duration);- info!("Processing audio4...");let mut audio_data = audio_buffer.lock().unwrap();info!("audio_data len: {:?}", audio_data.len());diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rsindex b6feb874c..1317b7da1 100644--- a/screenpipe-audio/src/stt.rs+++ b/screenpipe-audio/src/stt.rs@@ -447,7 +447,7 @@ pub fn stt(input: &str) -> Result<String> {pcm_data = resample(pcm_data, sample_rate, m::SAMPLE_RATE as u32)?;}- info!("pcm data loaded {}", pcm_data.len());+ // info!("pcm data loaded {}", pcm_data.len());let mel = audio::pcm_to_mel(&config, &pcm_data, &mel_filters);let mel_len = mel.len();let mel = Tensor::from_vec(@@ -455,20 +455,18 @@ pub fn stt(input: &str) -> Result<String> {(1, config.num_mel_bins, mel_len / config.num_mel_bins),&device,)?;- info!("loaded mel: {:?}", mel.dims());+ // info!("loaded mel: {:?}", mel.dims());let vb = candle_transformers::quantized_var_builder::VarBuilder::from_gguf(&weights_filename,&device,)?;- info!("loading model");let mut model = Model::Quantized(m::quantized_model::Whisper::load(&vb, config)?);- info!("loaded model");- info!("detecting language");+ // info!("detecting language");// TODO: disabled seems slow as fuck// let language_token = Some(multilingual::detect_language(&mut model, &tokenizer, &mel)?);// info!("detected language: {:?}", language_token);- info!("creating decoder");+ info!("Creating decoder");let mut dc = Decoder::new(model,tokenizer,diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 7546051d9..136df3aa9 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -1,13 +1,16 @@use std::{fs,- sync::{mpsc::channel, Arc, Mutex},+ net::SocketAddr,+ sync::{+ mpsc::{channel, Sender},+ Arc, Mutex,+ },};use tokio::sync::oneshot;use tokio::time::Duration;-use screenpipe_server::start_frame_server;-use screenpipe_server::{start_continuous_recording, DatabaseManager, RecorderControl};+use screenpipe_server::{start_continuous_recording, DatabaseManager, RecorderControl, Server};#[tokio::main]async fn main() -> anyhow::Result<()> {@@ -23,34 +26,36 @@ async fn main() -> anyhow::Result<()> {let local_data_dir = ensure_local_data_dir()?;let local_data_dir_clone = local_data_dir.clone();+ let local_data_dir_clone2 = local_data_dir.clone();let db = Arc::new(Mutex::new(None));- setup_db(local_data_dir.clone(), db.clone());+ setup_db(local_data_dir_clone, db.clone());// Channel for controlling the recorderlet (control_tx, control_rx) = channel();// Start continuous recording in a separate task+ let local_data_dir_clone = local_data_dir.clone();let recording_task = tokio::spawn(async move {let fps = 10.0;let audio_chunk_duration = Duration::from_secs(5);start_continuous_recording(&format!("{}/db.sqlite", local_data_dir),- &local_data_dir,+ &local_data_dir_clone,fps,audio_chunk_duration,control_rx,)});- // Start the frame server- let (tx, rx) = oneshot::channel();tokio::spawn(async move {- start_frame_server(tx, local_data_dir_clone.to_string(), db.clone()).await;+ // start_frame_server(tx, local_data_dir_clone.to_string(), db.clone()).await;+ let db = DatabaseManager::new(&format!("{}/db.sqlite", local_data_dir_clone2)).unwrap();+ let server = Server::new(db, SocketAddr::from(([0, 0, 0, 0], 3030)));+ server.start().await.unwrap();});// Wait for the server to start- let _ = rx.await;println!("Server started on http://localhost:3030");// Keep the main thread runningdiff --git a/screenpipe-server/src/bin/screenpipe-video.rs b/screenpipe-server/src/bin/screenpipe-video.rsindex 145170759..138945688 100644--- a/screenpipe-server/src/bin/screenpipe-video.rs+++ b/screenpipe-server/src/bin/screenpipe-video.rs@@ -29,7 +29,13 @@ fn main() {info!("Created data directory {}", output_path);let fps = 10.0;- let video_capture = VideoCapture::new(&output_path, fps);+ let new_chunk_callback = {+ move |file_path: String| {+ info!("New chunk: {}", file_path);+ }+ };++ let video_capture = VideoCapture::new(&output_path, fps, new_chunk_callback);let (tx, rx): (Sender<()>, Receiver<()>) = channel();let rx = Arc::new(Mutex::new(rx));let rx_thread = rx.clone();diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex d618006d2..ee1258541 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -25,8 +25,17 @@ pub fn start_continuous_recording(let db_manager = Arc::new(Mutex::new(DatabaseManager::new(db_path)?));let db_manager_clone = db_manager.clone();- let video_capture = VideoCapture::new(&output_path, fps);+ let new_chunk_callback = {+ let db_manager = db_manager.clone();+ move |file_path: String| {+ let mut db = db_manager.lock().unwrap();+ if let Err(e) = db.start_new_video_chunk(&file_path) {+ error!("Failed to insert new video chunk: {}", e);+ }+ }+ };+ let video_capture = VideoCapture::new(&output_path, fps, new_chunk_callback);let control_rx = Arc::new(Mutex::new(control_rx));let control_rx_video = Arc::clone(&control_rx);let control_rx_audio = Arc::clone(&control_rx);diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rsindex 6cbabe81f..39c0e8dec 100644--- a/screenpipe-server/src/db.rs+++ b/screenpipe-server/src/db.rs@@ -1,7 +1,9 @@+use std::default;+use chrono::{NaiveDateTime, Utc};use rusqlite::OptionalExtension;use rusqlite::{params, Connection, Result};-use serde::Serialize;+use serde::{Deserialize, Serialize};#[derive(Debug, Serialize)]pub enum SearchResult {@@ -18,6 +20,15 @@ pub struct OCRResult {pub offset_index: i64,}+#[derive(Debug, Deserialize, PartialEq, Default, Clone, Copy)]+#[serde(rename_all = "lowercase")]+pub enum ContentType {+ #[default]+ All,+ OCR,+ Audio,+}+#[derive(Debug, Serialize)]pub struct AudioResult {pub audio_chunk_id: i64,@@ -216,11 +227,11 @@ impl DatabaseManager {// Method to start a new video chunk and return its IDpub fn start_new_video_chunk(&mut self, file_path: &str) -> Result<i64> {- let chunk_id = self.conn.execute(+ self.conn.execute("INSERT INTO video_chunks (file_path) VALUES (?1)",params![file_path],)?;- self.current_video_chunk_id = chunk_id as i64;+ self.current_video_chunk_id = self.conn.last_insert_rowid();self.current_frame_offset = 0;Ok(self.current_video_chunk_id)}@@ -310,59 +321,70 @@ impl DatabaseManager {}// Method to perform a search based on text- pub fn search(&self, search_text: &str, limit: i64, offset: i64) -> Result<Vec<SearchResult>> {+ pub fn search(+ &self,+ search_text: Option<&str>,+ limit: u32,+ offset: u32,+ content_type: ContentType,+ ) -> Result<Vec<SearchResult>> {let mut results = Vec::new();-- // Search OCR text- let ocr_query = "- SELECT f.id, o.text, f.timestamp, vc.file_path, f.offset_index- FROM frames f- JOIN video_chunks vc ON f.video_chunk_id = vc.id- JOIN ocr_text o ON f.id = o.frame_id- WHERE o.text LIKE ?1- ORDER BY f.timestamp DESC- LIMIT ?2 OFFSET ?3- ";-- let search_pattern = format!("%{}%", search_text);- let mut ocr_stmt = self.conn.prepare(ocr_query)?;- let ocr_rows = ocr_stmt.query_map(params![search_pattern, limit, offset], |row| {- Ok(SearchResult::OCR(OCRResult {- frame_id: row.get(0)?,- ocr_text: row.get(1)?,- timestamp: row.get(2)?,- file_path: row.get(3)?,- offset_index: row.get(4)?,- }))- })?;-- for row in ocr_rows {- results.push(row?);+ let search_pattern = search_text.map(|text| format!("%{}%", text));++ if content_type == ContentType::All || content_type == ContentType::OCR {+ // Search OCR text+ let ocr_query = "+ SELECT f.id, o.text, f.timestamp, vc.file_path, f.offset_index+ FROM frames f+ JOIN video_chunks vc ON f.video_chunk_id = vc.id+ JOIN ocr_text o ON f.id = o.frame_id+ WHERE o.text LIKE ?1+ ORDER BY f.timestamp DESC+ LIMIT ?2 OFFSET ?3+ ";++ let mut ocr_stmt = self.conn.prepare(ocr_query)?;+ let ocr_rows = ocr_stmt.query_map(params![search_pattern, limit, offset], |row| {+ Ok(SearchResult::OCR(OCRResult {+ frame_id: row.get(0)?,+ ocr_text: row.get(1)?,+ timestamp: row.get(2)?,+ file_path: row.get(3)?,+ offset_index: row.get(4)?,+ }))+ })?;++ for row in ocr_rows {+ results.push(row?);+ }}- // Search audio transcriptions- let audio_query = "- SELECT at.audio_chunk_id, at.transcription, at.timestamp, ac.file_path, at.offset_index- FROM audio_transcriptions at- JOIN audio_chunks ac ON at.audio_chunk_id = ac.id- WHERE at.transcription LIKE ?1- ORDER BY at.timestamp DESC- LIMIT ?2 OFFSET ?3- ";-- let mut audio_stmt = self.conn.prepare(audio_query)?;- let audio_rows = audio_stmt.query_map(params![search_pattern, limit, offset], |row| {- Ok(SearchResult::Audio(AudioResult {- audio_chunk_id: row.get(0)?,- transcription: row.get(1)?,- timestamp: row.get(2)?,- file_path: row.get(3)?,- offset_index: row.get(4)?,- }))- })?;-- for row in audio_rows {- results.push(row?);+ if content_type == ContentType::All || content_type == ContentType::Audio {+ // Search audio transcriptions+ let audio_query = "+ SELECT at.audio_chunk_id, at.transcription, at.timestamp, ac.file_path, at.offset_index+ FROM audio_transcriptions at+ JOIN audio_chunks ac ON at.audio_chunk_id = ac.id+ WHERE at.transcription LIKE ?1+ ORDER BY at.timestamp DESC+ LIMIT ?2 OFFSET ?3+ ";++ let mut audio_stmt = self.conn.prepare(audio_query)?;+ let audio_rows =+ audio_stmt.query_map(params![search_pattern, limit, offset], |row| {+ Ok(SearchResult::Audio(AudioResult {+ audio_chunk_id: row.get(0)?,+ transcription: row.get(1)?,+ timestamp: row.get(2)?,+ file_path: row.get(3)?,+ offset_index: row.get(4)?,+ }))+ })?;++ for row in audio_rows {+ results.push(row?);+ }}Ok(results)@@ -370,8 +392,8 @@ impl DatabaseManager {// Modify the get_recent_results methodpub fn get_recent_results(&self,- limit: i64,- offset: i64,+ limit: u32,+ offset: u32,start_date: Option<NaiveDateTime>,end_date: Option<NaiveDateTime>,) -> Result<Vec<SearchResult>> {@@ -459,6 +481,61 @@ impl DatabaseManager {Ok(final_results)}++ pub fn count_search_results(+ &self,+ search_text: Option<&str>,+ content_type: ContentType,+ ) -> Result<u64> {+ let search_pattern = search_text.map(|text| format!("%{}%", text));++ let mut total_count = 0;++ if content_type == ContentType::All || content_type == ContentType::OCR {+ let ocr_count: u64 = self.conn.query_row(+ "SELECT COUNT(*) FROM ocr_text WHERE text LIKE COALESCE(?1, '%')",+ params![search_pattern],+ |row| row.get(0),+ )?;+ total_count += ocr_count;+ }++ if content_type == ContentType::All || content_type == ContentType::Audio {+ let audio_count: u64 = self.conn.query_row(+ "SELECT COUNT(*) FROM audio_transcriptions WHERE transcription LIKE COALESCE(?1, '%')",+ params![search_pattern],+ |row| row.get(0),+ )?;+ total_count += audio_count;+ }++ Ok(total_count)+ }++ pub fn count_recent_results(+ &self,+ start_date: Option<NaiveDateTime>,+ end_date: Option<NaiveDateTime>,+ ) -> Result<u64> {+ let ocr_count: u64 = self.conn.query_row(+ "SELECT COUNT(*) FROM frames f+ JOIN ocr_text o ON f.id = o.frame_id+ WHERE f.timestamp BETWEEN COALESCE(?1, datetime('now', '-100 years'))+ AND COALESCE(?2, datetime('now', '+1 day'))",+ params![start_date, end_date],+ |row| row.get(0),+ )?;++ let audio_count: u64 = self.conn.query_row(+ "SELECT COUNT(*) FROM audio_transcriptions+ WHERE timestamp BETWEEN COALESCE(?1, datetime('now', '-100 years'))+ AND COALESCE(?2, datetime('now', '+1 day'))",+ params![start_date, end_date],+ |row| row.get(0),+ )?;++ Ok(ocr_count + audio_count)+ }}// ... existing code ...@@ -520,7 +597,7 @@ mod tests {add_test_data(&mut db)?;// Test searching for "dog"- let results = db.search("dog", 10, 0)?;+ let results = db.search(Some("dog"), 10, 0, ContentType::All)?;println!("results: {:?}", results);assert_eq!(results.len(), 2); // Should find both OCR and audio results@@ -546,7 +623,7 @@ mod tests {}// Test searching for "cat"- let results = db.search("cat", 10, 0)?;+ let results = db.search(Some("cat"), 10, 0, ContentType::All)?;assert_eq!(results.len(), 1);if let SearchResult::OCR(ocr) = &results[0] {assert!(ocr.ocr_text.contains("cat"));@@ -555,7 +632,7 @@ mod tests {}// Test searching for "git"- let results = db.search("git", 10, 0)?;+ let results = db.search(Some("git"), 10, 0, ContentType::All)?;assert_eq!(results.len(), 1);if let SearchResult::OCR(ocr) = &results[0] {assert!(ocr.ocr_text.contains("git"));diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex 10125f42a..af05ecc85 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -4,6 +4,6 @@ mod server;mod video;pub use core::{start_continuous_recording, RecorderControl};-pub use db::{DatabaseManager, SearchResult};-pub use server::start_frame_server;+pub use db::{ContentType, DatabaseManager, SearchResult};+pub use server::Server;pub use video::{extract_frames_from_video, VideoCapture};diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex efe3d7f2f..fe247a6d8 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -1,213 +1,356 @@-use std::collections::HashMap;-use std::sync::Mutex;-use std::{io::Cursor, sync::Arc};--use axum::extract::Query;use axum::{- body::Bytes,- extract::{Path, State},+ extract::{Path, Query, State},http::StatusCode,- routing::get,- Json, Router,+ response::Json as JsonResponse,+ routing::{get, post},+ serve, Json, Router,};-use chrono::{NaiveDateTime, Utc};+use chrono::NaiveDateTime;+use image::{ImageBuffer, Rgb};+use log::info;use serde::{Deserialize, Serialize};-use tokio::sync::oneshot;+use serde_json::json;+use std::{+ io::Cursor,+ net::SocketAddr,+ sync::{Arc, Mutex},+};+use tokio::net::TcpListener;use tower_http::cors::CorsLayer;-use crate::{extract_frames_from_video, DatabaseManager, SearchResult};--#[derive(Clone)]+use crate::{ContentType, DatabaseManager, SearchResult};+// App statestruct AppState {- local_data_dir: String,- db: Arc<Mutex<Option<DatabaseManager>>>,+ db: Mutex<DatabaseManager>,+}+// Request structs+#[derive(Deserialize)]+struct SearchQuery {+ q: Option<String>,+ #[serde(flatten)]+ pagination: PaginationQuery,+ #[serde(default)]+ content_type: ContentType,}-#[derive(Serialize)]-struct FrameInfo {- max_frame: i64,+#[derive(Deserialize)]+struct PaginationQuery {+ #[serde(default = "default_limit")]+ #[serde(deserialize_with = "deserialize_number_from_string")]+ limit: u32,+ #[serde(default)]+ #[serde(deserialize_with = "deserialize_number_from_string")]+ offset: u32,+}++// Add this function somewhere in your code+fn deserialize_number_from_string<'de, D>(deserializer: D) -> Result<u32, D::Error>+where+ D: serde::Deserializer<'de>,+{+ let s: String = serde::Deserialize::deserialize(deserializer)?;+ s.parse().map_err(serde::de::Error::custom)}#[derive(Deserialize)]-struct Pagination {- search: Option<String>,- limit: i64,- offset: i64,+struct DateRangeQuery {+ start_date: Option<NaiveDateTime>,+ end_date: Option<NaiveDateTime>,+ #[serde(flatten)]+ pagination: PaginationQuery,}#[derive(Deserialize)]-struct ImageParams {- thumbnail: Option<bool>,+struct FrameQuery {+ #[serde(default)]+ thumbnail: bool,}+// Response structs#[derive(Serialize)]-struct TextWithTimestampResponse {- ocr_text: Option<String>,- audio_transcription: Option<String>,- timestamp: String, // Use String to serialize NaiveDateTime easily-}--// TODO: Optimize this to do chunk loading, instead of starting from scratch with the-// frame every single time-// TODO: Also, cache the frames in memory using an LRU cache-async fn get_frame_handler(- Path(frame_number): Path<i64>,- Query(query): Query<ImageParams>,- State(state): State<Arc<AppState>>,-) -> (StatusCode, Bytes) {- let db_video_ref = state.db.clone();- let maybe_video_path = {- let mut db_clone = db_video_ref.lock().unwrap();- db_clone- .as_mut()- .unwrap()- .get_frame(frame_number)- .expect("Failed to get frame")- };- if let Some((offset_index, video_path, _)) = maybe_video_path {- println!("video path: {:?}", video_path);- match extract_frames_from_video(&video_path, &[offset_index]) {- Ok(frames) => {- if let Some(frame) = frames.into_iter().next() {- let mut cursor = Cursor::new(Vec::new());- if query.thumbnail.unwrap_or(false) {- if frame- .thumbnail(800, 800)- .write_to(&mut cursor, image::ImageFormat::Png)- .is_ok()- {- println!("Thumbnail generated successfully");- return (StatusCode::OK, Bytes::from(cursor.into_inner()));- } else {- println!("Failed to generate thumbnail");- }- } else if frame.write_to(&mut cursor, image::ImageFormat::Png).is_ok() {- println!("Frame generated successfully");- return (StatusCode::OK, Bytes::from(cursor.into_inner()));- } else {- println!("Failed to generate frame");- }- } else {- println!("No frames found");- }- }- Err(e) => {- println!("Error extracting frames: {:?}", e);- }- }- } else {- println!("No video path found for frame number: {}", frame_number);- }- (StatusCode::NOT_FOUND, Bytes::new())+struct PaginatedResponse<T> {+ data: Vec<T>,+ pagination: PaginationInfo,+}++#[derive(Serialize)]+struct PaginationInfo {+ limit: u32,+ offset: u32,+ total: u64,+}++#[derive(Serialize)]+#[serde(tag = "type", content = "content")]+enum ContentItem {+ OCR(OCRContent),+ Audio(AudioContent),}#[derive(Serialize)]-struct PaginatedResults {- data: Vec<SearchResult>,+struct OCRContent {+ frame_id: i64,+ text: String,+ timestamp: NaiveDateTime,+ file_path: String,+ offset_index: i64,}-async fn search_handler(- Query(query): Query<Pagination>,+#[derive(Serialize)]+struct AudioContent {+ chunk_id: i64,+ transcription: String,+ timestamp: NaiveDateTime,+ file_path: String,+ offset_index: i64,+}++// Helper functions+fn default_limit() -> u32 {+ 20+}++async fn search(+ Query(query): Query<SearchQuery>,State(state): State<Arc<AppState>>,-) -> Json<PaginatedResults> {- let db_frames_ref = state.db.clone();- let results = {- let mut db_clone = db_frames_ref.lock().expect("Failed to acquire lock");-- let search = query.search.unwrap_or("".to_string());- if search.is_empty() {- db_clone- .as_mut()- .unwrap()- .get_recent_results(query.limit, query.offset, None, None)- .expect("Failed to get recent results")- } else {- db_clone- .as_mut()- .unwrap()- .search(&search, query.limit, query.offset)- .expect("Failed to get search results")- }- };- Json(PaginatedResults { data: results })+) -> Result<+ JsonResponse<PaginatedResponse<ContentItem>>,+ (StatusCode, JsonResponse<serde_json::Value>),+> {+ let db = state.db.lock().map_err(|_| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": "Failed to acquire database lock"})),+ )+ })?;++ let results = db+ .search(+ query.q.as_deref(),+ query.pagination.limit,+ query.pagination.offset,+ query.content_type,+ )+ .map_err(|e| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": format!("Failed to search for content: {}", e)})),+ )+ })?;++ let total = db+ .count_search_results(query.q.as_deref(), query.content_type)+ .map_err(|e| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": format!("Failed to count search results: {}", e)})),+ )+ })?;++ Ok(JsonResponse(PaginatedResponse {+ data: results.into_iter().map(into_content_item).collect(),+ pagination: PaginationInfo {+ limit: query.pagination.limit,+ offset: query.pagination.offset,+ total,+ },+ }))}-#[derive(Deserialize)]-struct DateFilter {- start_date: NaiveDateTime,- end_date: NaiveDateTime,- limit: i64,- offset: i64,+async fn get_by_date_range(+ Query(query): Query<DateRangeQuery>,+ State(state): State<Arc<AppState>>,+) -> Result<+ JsonResponse<PaginatedResponse<ContentItem>>,+ (StatusCode, JsonResponse<serde_json::Value>),+> {+ let db = state.db.lock().map_err(|_| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": "Failed to acquire database lock"})),+ )+ })?;++ let results = db+ .get_recent_results(+ query.pagination.limit,+ query.pagination.offset,+ query.start_date,+ query.end_date,+ )+ .map_err(|e| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": format!("Database error: {}", e)})),+ )+ })?;++ let total = db+ .count_recent_results(query.start_date, query.end_date)+ .map_err(|e| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": format!("Database error: {}", e)})),+ )+ })?;++ Ok(JsonResponse(PaginatedResponse {+ data: results.into_iter().map(into_content_item).collect(),+ pagination: PaginationInfo {+ limit: query.pagination.limit,+ offset: query.pagination.offset,+ total,+ },+ }))}-async fn get_by_date_handler(- Query(query): Query<DateFilter>,+async fn get_frame(+ Path(frame_id): Path<i64>,+ Query(query): Query<FrameQuery>,State(state): State<Arc<AppState>>,-) -> Result<Json<Vec<TextWithTimestampResponse>>, StatusCode> {- let start_date = query.start_date;- let end_date = query.end_date;- let db_video_ref = state.db.clone();- let texts_with_timestamps = {- let mut db_clone = db_video_ref.lock().unwrap();- db_clone- .as_mut()- .unwrap()- .get_recent_results(query.limit, query.offset, Some(start_date), Some(end_date))- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?- };-- let response = texts_with_timestamps- .into_iter()- .map(|item| match item {- SearchResult::OCR(ocr) => TextWithTimestampResponse {- ocr_text: Some(ocr.ocr_text),- audio_transcription: None,- timestamp: ocr.timestamp.to_string(),- },- SearchResult::Audio(audio) => TextWithTimestampResponse {- ocr_text: None,- audio_transcription: Some(audio.transcription),- timestamp: audio.timestamp.to_string(),- },- })- .collect();-- Ok(Json(response))-}-pub async fn start_frame_server(- tx: oneshot::Sender<()>,- local_data_dir: String,- db: Arc<Mutex<Option<DatabaseManager>>>,-) {- let state = Arc::new(AppState { local_data_dir, db });-- let app = Router::new()- .route("/text", get(search_handler))- .route("/text_by_date", get(get_by_date_handler))- .route("/frames/:frame_number", get(get_frame_handler))- .layer(CorsLayer::permissive())- .with_state(state);-- let listener = tokio::net::TcpListener::bind("0.0.0.0:3030").await.unwrap();- axum::serve(listener, app).await.unwrap();-- // Send signal that the server has started- let _ = tx.send(());-}--// # 1. Search for text with pagination-// curl "http://localhost:3030/text?search=e&limit=10&offset=0"--// # 2. Get recent results without search term-// curl "http://localhost:3030/text?limit=20&offset=0"--// # 3. Get frame image (non-thumbnail) // ! does not work-// curl -o frame.png "http://localhost:3030/frames/100"--// # 4. Get frame thumbnail-// curl -o thumbnail.png "http://localhost:3030/frames/100?thumbnail=true"--// # 5. Get text by date range-// curl "http://localhost:3030/text_by_date?start_date=2024-07-02T00:00:00&end_date=2024-07-02T23:59:59&limit=15&offset=0"+) -> Result<(axum::http::HeaderMap, Vec<u8>), (StatusCode, JsonResponse<serde_json::Value>)> {+ let db = state.db.lock().map_err(|_| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": "Failed to acquire database lock"})),+ )+ })?;++ let frame_data = db.get_frame(frame_id).map_err(|e| {+ (+ StatusCode::NOT_FOUND,+ JsonResponse(json!({"error": format!("Frame not found: {}", e)})),+ )+ })?;++ let image_data = generate_frame_image(&frame_data.unwrap(), query.thumbnail).map_err(|e| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": format!("Failed to generate frame image: {}", e)})),+ )+ })?;++ let mut headers = axum::http::HeaderMap::new();+ headers.insert(+ axum::http::header::CONTENT_TYPE,+ "image/jpeg".parse().unwrap(),+ );++ Ok((headers, image_data))+}++fn generate_frame_image(+ frame_data: &(i64, String, Option<String>),+ thumbnail: bool,+) -> Result<Vec<u8>, Box<dyn std::error::Error>> {+ let (offset_index, file_path, _) = frame_data;++ // Here you would typically read the frame from the video file+ // For this example, we'll create a dummy image+ let width = if thumbnail { 320 } else { 1280 };+ let height = if thumbnail { 180 } else { 720 };++ let mut img = ImageBuffer::new(width, height);++ // Fill the image with a color based on the frame index+ let color = Rgb([(offset_index % 255) as u8, 128, 128]);+ for pixel in img.pixels_mut() {+ *pixel = color;+ }++ // Convert the image to JPEG+ let mut jpeg_data = Vec::new();+ img.write_to(&mut Cursor::new(&mut jpeg_data), image::ImageFormat::Jpeg)?;++ Ok(jpeg_data)+}++// Helper functions+fn into_content_item(result: SearchResult) -> ContentItem {+ match result {+ SearchResult::OCR(ocr) => ContentItem::OCR(OCRContent {+ frame_id: ocr.frame_id,+ text: ocr.ocr_text,+ timestamp: ocr.timestamp,+ file_path: ocr.file_path,+ offset_index: ocr.offset_index,+ }),+ SearchResult::Audio(audio) => ContentItem::Audio(AudioContent {+ chunk_id: audio.audio_chunk_id,+ transcription: audio.transcription,+ timestamp: audio.timestamp,+ file_path: audio.file_path,+ offset_index: audio.offset_index,+ }),+ }+}++pub struct Server {+ db: DatabaseManager,+ addr: SocketAddr,+}++impl Server {+ pub fn new(db: DatabaseManager, addr: SocketAddr) -> Self {+ Server { db, addr }+ }++ pub async fn start(self) -> Result<(), std::io::Error> {+ let app_state = Arc::new(AppState {+ db: Mutex::new(self.db),+ });++ let app = Router::new()+ .route("/search", get(search))+ .route("/recent", get(get_by_date_range))+ .route("/frame/:frame_id", get(get_frame))+ .layer(CorsLayer::permissive())+ .with_state(app_state);++ info!("Starting server on {}", self.addr);++ serve(+ TcpListener::bind(self.addr).await.unwrap(),+ app.into_make_service(),+ )+ .await+ }+}++// # 1. Basic search query+// curl "http://localhost:3030/search?q=test&limit=5&offset=0"++// # 2. Search with content type filter (OCR)+// curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=ocr"++// # 3. Search with content type filter (Audio)+// curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=audio"++// # 4. Search with pagination+// curl "http://localhost:3030/search?q=test&limit=10&offset=20"++// # 5. Get recent results without date range+// curl "http://localhost:3030/recent?limit=5&offset=0"++// # 6. Get recent results with date range+// curl "http://localhost:3030/recent?limit=5&offset=0&start_date=2024-07-02T14:00:00&end_date=2024-07-02T23:59:59"++// 5 s ago+// start_date=$(date -u -v-5S +'%Y-%m-%dT%H:%M:%S')++// end_date=$(date -u +'%Y-%m-%dT%H:%M:%S')++// curl "http://localhost:3030/recent?limit=5&offset=0&start_date=$start_date&end_date=$end_date"++// # 7. Get frame without thumbnail+// curl "http://localhost:3030/frame/123"++// # 8. Get frame with thumbnail+// curl "http://localhost:3030/frame/123?thumbnail=true"++// # 9. Search with no query (should return all results)+// curl "http://localhost:3030/search?limit=5&offset=0"+// # 10. Get recent results with pagination+// curl "http://localhost:3030/recent?limit=20&offset=40"diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 67917f9aa..ef7861214 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -171,15 +171,22 @@ pub struct VideoCapture {frame_queue: Arc<Mutex<VecDeque<CaptureResult>>>,ffmpeg_handle: Arc<Mutex<Option<std::process::Child>>>,is_running: Arc<Mutex<bool>>,+ new_chunk_callback: Arc<dyn Fn(String) + Send + Sync>,}impl VideoCapture {- pub fn new(output_path: &str, fps: f64) -> Self {+ pub fn new(+ output_path: &str,+ fps: f64,+ new_chunk_callback: impl Fn(String) + Send + Sync + 'static,+ ) -> Self {info!("Starting new video capture");let (control_tx, control_rx) = channel();let frame_queue = Arc::new(Mutex::new(VecDeque::new()));let ffmpeg_handle = Arc::new(Mutex::new(None));let is_running = Arc::new(Mutex::new(true));+ let new_chunk_callback = Arc::new(new_chunk_callback);+ let new_chunk_callback_clone = Arc::clone(&new_chunk_callback);let capture_frame_queue = frame_queue.clone();let capture_thread_is_running = is_running.clone();@@ -214,6 +221,7 @@ impl VideoCapture {fps,video_thread_is_running,video_thread_ffmpeg_handle,+ new_chunk_callback_clone.as_ref(),);});@@ -222,6 +230,7 @@ impl VideoCapture {frame_queue,ffmpeg_handle,is_running,+ new_chunk_callback,}}@@ -251,6 +260,7 @@ fn save_frames_as_video(fps: f64,is_running: Arc<Mutex<bool>>,ffmpeg_handle: Arc<Mutex<Option<std::process::Child>>>,+ new_chunk_callback: &dyn Fn(String),) {let frames_per_video = 30; // Adjust this value as neededlet mut frame_count = 0;@@ -289,6 +299,9 @@ fn save_frames_as_video(let time = Utc::now();// Start new FFmpeg process with a new output filelet output_file = format!("{}/{}.mp4", output_path, time);+ // Call the callback with the new video chunk file path+ new_chunk_callback(output_file.clone()); // TODO better error handling+let mut child = start_ffmpeg_process(&output_file, fps);let mut stdin = child.stdin.take().expect("Failed to open stdin");let stderr = child.stderr.take().expect("Failed to open stderr");