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
feat: impl index #37
Louis Beaumont63f86d6c0f94
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex c3ae0a651..a97e9f596 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -77,7 +77,22 @@ cargo test```-## Optimization+## Other hacks++### Benchmarks++```+cargo bench+```++### Creating new migrations++```bash+cargo install sqlx-cli+sqlx migrate add <migration_name>+```++### OptimizationFor performance optimization, you can use the following command:@@ -87,6 +102,8 @@ cargo install cargo-instrumentscargo instruments -t Leaks --bin screenpipe --features metal --time-limit 600000 --open```+Then open the file in `target/release/instruments` using Xcode -> Open Developer Tool -> Instruments.+## Join the Communitydiff --git a/Cargo.toml b/Cargo.tomlindex e50c9f2f8..b918a8b6a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -20,3 +20,8 @@ tokenizers = "0.19.1"tracing = "0.1.37"tokio = { version = "1.15", features = ["full", "tracing"] }+# dev+criterion = { version = "0.5.1", features = ["async_tokio"], dev = true }+++diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rsindex 2e9564e72..99d5515e4 100644--- a/screenpipe-audio/src/stt.rs+++ b/screenpipe-audio/src/stt.rs@@ -105,6 +105,7 @@ struct DecodingResult {text: String,avg_logprob: f64,no_speech_prob: f64,+ #[allow(dead_code)]temperature: f64,compression_ratio: f64,}@@ -390,12 +391,13 @@ pub fn token_id(tokenizer: &Tokenizer, token: &str) -> candle::Result<u32> {#[derive(Clone, Copy, Debug, PartialEq, Eq)]enum Task {Transcribe,+ #[allow(dead_code)]Translate,}pub fn stt(file_path: &str, whisper_model: &WhisperModel) -> Result<String> {info!("Starting speech to text");- let mut model = &whisper_model.model;+ let model = &whisper_model.model;let tokenizer = &whisper_model.tokenizer;let device = &whisper_model.device;diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex f5b5a9689..1ab072a28 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -82,7 +82,7 @@ tempfile = "3.3.0"reqwest = { version = "0.11", features = ["json"] }# Benches-criterion = { version = "0.5.1", features = ["async_tokio"] }+criterion = { workspace = true }rand = "0.8"tower = "0.4"diff --git a/screenpipe-server/benches/db_benchmarks.rs b/screenpipe-server/benches/db_benchmarks.rsindex 096706f34..2fd61269f 100644--- a/screenpipe-server/benches/db_benchmarks.rs+++ b/screenpipe-server/benches/db_benchmarks.rs@@ -1,5 +1,4 @@--// cargo bench+// cargo bench --bench db_benchmarksuse criterion::{criterion_group, criterion_main, Criterion};use rand::Rng;@@ -18,7 +17,9 @@ async fn setup_large_db(size: usize) -> DatabaseManager {let audio_id = db.insert_audio_chunk("test_audio.mp3").await.unwrap();let audio_text = format!("Audio transcription {}", rng.gen::<u32>());- db.insert_audio_transcription(audio_id, &audio_text, 0).await.unwrap();+ db.insert_audio_transcription(audio_id, &audio_text, 0)+ .await+ .unwrap();}db@@ -27,20 +28,32 @@ async fn setup_large_db(size: usize) -> DatabaseManager {fn bench_search(c: &mut Criterion) {let rt = Runtime::new().unwrap();- let db_sizes = [100, 1000, 10000];+ let db_sizes = [10000, 100000];let content_types = [ContentType::OCR, ContentType::Audio, ContentType::All];+ let search_queries = ["random", "specific"];++ let mut group = c.benchmark_group("search_benchmarks");+ group.sample_size(5);+ group.measurement_time(std::time::Duration::from_secs(30));for &size in &db_sizes {for &content_type in &content_types {- c.bench_function(&format!("search_{:?}_db_size_{}", content_type, size), |b| {- b.to_async(&rt).iter(|| async {- let db = setup_large_db(size).await;- db.search("text", content_type, 100, 0).await.unwrap()- });- });+ for &query in &search_queries {+ group.bench_function(+ format!("{:?}_db_size_{}_query_{}", content_type, size, query),+ |b| {+ b.to_async(&rt).iter(|| async {+ let db = setup_large_db(size).await;+ db.search(query, content_type, 100, 0).await.unwrap()+ });+ },+ );+ }}}++ group.finish();}criterion_group!(benches, bench_search);-criterion_main!(benches);\ No newline at end of file+criterion_main!(benches);diff --git a/screenpipe-server/src/migrations/20240715121444_indexes.sql b/screenpipe-server/src/migrations/20240715121444_indexes.sqlnew file mode 100644index 000000000..e1d2c4893--- /dev/null+++ b/screenpipe-server/src/migrations/20240715121444_indexes.sql@@ -0,0 +1,11 @@++-- Create indices for search queries+CREATE INDEX IF NOT EXISTS idx_ocr_text_text ON ocr_text(text);+CREATE INDEX IF NOT EXISTS idx_audio_transcriptions_transcription ON audio_transcriptions(transcription);+CREATE INDEX IF NOT EXISTS idx_frames_timestamp ON frames(timestamp);+CREATE INDEX IF NOT EXISTS idx_audio_transcriptions_timestamp ON audio_transcriptions(timestamp);++-- Create composite indices for more efficient searching+CREATE INDEX IF NOT EXISTS idx_frames_video_chunk_id_timestamp ON frames(video_chunk_id, timestamp);+CREATE INDEX IF NOT EXISTS idx_audio_transcriptions_audio_chunk_id_timestamp ON audio_transcriptions(audio_chunk_id, timestamp);+diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex a606cabf5..78e6062ca 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -84,7 +84,7 @@ struct DateRangeQuery {// Response structs#[derive(Serialize)]-struct PaginatedResponse<T> {+pub(crate) struct PaginatedResponse<T> {data: Vec<T>,pagination: PaginationInfo,}@@ -98,13 +98,13 @@ struct PaginationInfo {#[derive(Serialize)]#[serde(tag = "type", content = "content")]-enum ContentItem {+pub(crate) enum ContentItem {OCR(OCRContent),Audio(AudioContent),}#[derive(Serialize)]-struct OCRContent {+pub(crate) struct OCRContent {frame_id: i64,text: String,timestamp: DateTime<Utc>,@@ -113,7 +113,7 @@ struct OCRContent {}#[derive(Serialize)]-struct AudioContent {+pub(crate) struct AudioContent {chunk_id: i64,transcription: String,timestamp: DateTime<Utc>,@@ -128,7 +128,7 @@ pub(crate) struct DeviceStatus {}#[derive(Serialize)]-struct RecordingStatus {+pub(crate) struct RecordingStatus {is_running: bool,}@@ -437,9 +437,6 @@ impl Server {// # 4. Search with pagination// # curl "http://localhost:3030/search?q=test&limit=10&offset=20"-// # 5. 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"-// # 6. Search with no query (should return all results)// # curl "http://localhost:3030/search?limit=5&offset=0"diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.tomlindex 97a008699..62747d142 100644--- a/screenpipe-vision/Cargo.toml+++ b/screenpipe-vision/Cargo.toml@@ -50,7 +50,7 @@ log = { workspace = true }[dev-dependencies]tempfile = "3.3.0"-+criterion = { workspace = true }[[bin]]name = "screenpipe-vision"diff --git a/screenpipe-vision/benches/vision_benchmark.rs b/screenpipe-vision/benches/vision_benchmark.rsnew file mode 100644index 000000000..d3aea2e38--- /dev/null+++ b/screenpipe-vision/benches/vision_benchmark.rs@@ -0,0 +1,65 @@+// cargo bench --bench vision_benchmark -- benchmark_continuous_capture+// or+// cargo bench --bench vision_benchmark+use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};+use screenpipe_vision::{continuous_capture, ControlMessage};+use tokio::sync::mpsc;+use tokio::time::{Duration, Instant};++fn benchmark_continuous_capture(c: &mut Criterion) {+ let mut group = c.benchmark_group("continuous_capture");++ for &threads in &[1, 2, 4, 8] {+ for &interval_ms in &[50, 100, 200] {+ group.bench_with_input(+ BenchmarkId::new("threads_interval", format!("{}_{}", threads, interval_ms)),+ &(threads, interval_ms),+ |b, &(threads, interval_ms)| {+ b.iter(|| {+ let rt = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(threads)+ .build()+ .unwrap();++ rt.block_on(async {+ let (control_tx, mut control_rx) = mpsc::channel(10);+ let (result_tx, mut result_rx) = mpsc::channel(100);+ let interval = Duration::from_millis(interval_ms);++ let capture_handle = tokio::spawn(async move {+ continuous_capture(&mut control_rx, result_tx, interval).await;+ });++ let start = Instant::now();+ let duration = Duration::from_secs(5);+ let mut frame_count = 0;++ while start.elapsed() < duration {+ if result_rx.try_recv().is_ok() {+ frame_count += 1;+ }+ tokio::time::sleep(Duration::from_millis(1)).await;+ }++ control_tx.send(ControlMessage::Stop).await.unwrap();+ capture_handle.await.unwrap();++ println!(+ "Threads: {}, Interval: {}ms, Frames: {}, FPS: {:.2}",+ threads,+ interval_ms,+ frame_count,+ frame_count as f64 / duration.as_secs_f64()+ );+ });+ })+ },+ );+ }+ }++ group.finish();+}++criterion_group!(benches, benchmark_continuous_capture);+criterion_main!(benches);diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex b0e19b036..2d46a9010 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -1,5 +1,5 @@use image::DynamicImage;-use log::{debug, error, info, warn};+use log::{debug, error, info};use rusty_tesseract::{Args, Image};use tokio::sync::broadcast;use tokio::sync::broadcast::error::RecvError;@@ -28,7 +28,7 @@ pub struct CaptureResult {const MAX_THREADS: usize = 4; // Adjust based on your needsconst MAX_QUEUE_SIZE: usize = 6; // Maximum number of frames to keep in the queue. 64/8 ocr task = 8-// seems kinda counter intuitive but less threads for OCR = more CPU usage = less frame dropping+ // seems kinda counter intuitive but less threads for OCR = more CPU usage = less frame droppingpub async fn continuous_capture(control_rx: &mut Receiver<ControlMessage>,