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(vision): add window OCR caching to reduce CPU usage
Louis Beaumont640fa577261f
diff --git a/Cargo.lock b/Cargo.lockindex 200ab6792..19f92afb0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6583,7 +6583,6 @@ dependencies = ["serde","serde_json","tempfile",- "thiserror 2.0.12","tokenizers","tokio","tracing",diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex 3ef3eb9aa..bdc568be2 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -6,6 +6,7 @@ use crate::custom_ocr::perform_ocr_custom;#[cfg(target_os = "windows")]use crate::microsoft::perform_ocr_windows;use crate::monitor::get_monitor_by_id;+use crate::ocr_cache::{WindowCacheKey, WindowOcrCache};use crate::tesseract::perform_ocr_tesseract;use crate::utils::OcrEngine;use crate::utils::{capture_screenshot, compare_with_previous_image};@@ -27,6 +28,7 @@ use std::{collections::HashMap,time::{Duration, Instant, UNIX_EPOCH},};+use tokio::sync::Mutex;use tokio::sync::mpsc::Sender;use tracing::{debug, error, warn};@@ -156,6 +158,13 @@ pub async fn continuous_capture(let mut max_average: Option<MaxAverageFrame> = None;let mut max_avg_value = 0.0;+ // Initialize OCR cache for skipping unchanged windows+ // Cache entries expire after 5 minutes, max 100 windows cached+ let ocr_cache = Arc::new(Mutex::new(WindowOcrCache::new(+ Duration::from_secs(300),+ 100,+ )));+debug!("continuous_capture: Starting using monitor: {:?}",monitor_id@@ -209,8 +218,13 @@ pub async fn continuous_capture(// 5. Process max average frame if availableif let Some(max_avg_frame) = max_average.take() {- if let Err(e) =- process_max_average_frame(max_avg_frame, &ocr_engine, languages.clone()).await+ if let Err(e) = process_max_average_frame(+ max_avg_frame,+ &ocr_engine,+ languages.clone(),+ ocr_cache.clone(),+ )+ .await{error!("Error processing max average frame: {}", e);}@@ -284,6 +298,7 @@ async fn process_max_average_frame(max_avg_frame: MaxAverageFrame,ocr_engine: &OcrEngine,languages: Vec<Language>,+ ocr_cache: Arc<Mutex<WindowOcrCache>>,) -> Result<(), ContinuousCaptureError> {let ocr_task_data = OcrTaskData {image: max_avg_frame.image,@@ -294,7 +309,7 @@ async fn process_max_average_frame(result_tx: max_avg_frame.result_tx,};- if let Err(e) = process_ocr_task(ocr_task_data, ocr_engine, languages).await {+ if let Err(e) = process_ocr_task(ocr_task_data, ocr_engine, languages, ocr_cache).await {error!("Error processing OCR task: {}", e);return Err(ContinuousCaptureError::ErrorProcessingOcr(e.to_string()));}@@ -318,6 +333,7 @@ pub async fn process_ocr_task(ocr_task_data: OcrTaskData,ocr_engine: &OcrEngine,languages: Vec<Language>,+ ocr_cache: Arc<Mutex<WindowOcrCache>>,) -> Result<(), ContinuousCaptureError> {let OcrTaskData {image,@@ -337,26 +353,108 @@ pub async fn process_ocr_task(let mut window_ocr_results = Vec::new();let mut total_confidence = 0.0;let mut window_count = 0;+ let mut cache_hits = 0;+ let mut cache_misses = 0;// Get screen dimensions for coordinate transformationlet (screen_width, screen_height) = image.dimensions();for captured_window in window_images {- let ocr_result = process_window_ocr(- captured_window,- ocr_engine,- &languages,- &mut total_confidence,- &mut window_count,- screen_width,- screen_height,- )- .await- .map_err(|e| ContinuousCaptureError::ErrorProcessingOcr(e.to_string()))?;+ // Calculate hash for this window's image+ let window_image_hash = WindowOcrCache::calculate_image_hash(captured_window.image.as_bytes());+ let window_id = WindowOcrCache::make_window_id(&captured_window.app_name, &captured_window.window_name);+ let cache_key = WindowCacheKey {+ window_id: window_id.clone(),+ image_hash: window_image_hash,+ };++ // Check cache first+ let cached_result = {+ let mut cache = ocr_cache.lock().await;+ cache.get(&cache_key)+ };++ let ocr_result = if let Some(cached) = cached_result {+ // Cache hit - reuse previous OCR result+ cache_hits += 1;+ debug!(+ "OCR cache hit for window '{}' (hash: {})",+ window_id, window_image_hash+ );++ // Still need to transform coordinates for the current position+ let parsed_json = parse_json_output(&cached.text_json);+ let transformed_json = transform_ocr_coordinates_to_screen(+ parsed_json,+ captured_window.window_x,+ captured_window.window_y,+ captured_window.window_width,+ captured_window.window_height,+ screen_width,+ screen_height,+ );++ total_confidence += cached.confidence;+ window_count += 1;++ WindowOcrResult {+ image: captured_window.image,+ window_name: captured_window.window_name,+ app_name: captured_window.app_name,+ text: cached.text.clone(),+ text_json: transformed_json,+ focused: captured_window.is_focused,+ confidence: cached.confidence,+ browser_url: captured_window.browser_url,+ }+ } else {+ // Cache miss - perform OCR+ cache_misses += 1;+ let result = process_window_ocr(+ captured_window,+ ocr_engine,+ &languages,+ &mut total_confidence,+ &mut window_count,+ screen_width,+ screen_height,+ )+ .await+ .map_err(|e| ContinuousCaptureError::ErrorProcessingOcr(e.to_string()))?;++ // Cache the result for future use (serialize JSON for storage)+ {+ let mut cache = ocr_cache.lock().await;+ let json_str = serde_json::to_string(&result.text_json).unwrap_or_default();+ cache.insert(+ cache_key,+ result.text.clone(),+ json_str,+ result.confidence,+ );+ }++ result+ };window_ocr_results.push(ocr_result);}+ // Log cache performance+ if cache_hits > 0 || cache_misses > 0 {+ debug!(+ "OCR cache stats for frame {}: {} hits, {} misses ({:.1}% hit rate)",+ frame_number,+ cache_hits,+ cache_misses,+ if cache_hits + cache_misses > 0 {+ (cache_hits as f64 / (cache_hits + cache_misses) as f64) * 100.0+ } else {+ 0.0+ }+ );+ }+// Create and send the resultlet capture_result = CaptureResult {image,diff --git a/screenpipe-vision/src/lib.rs b/screenpipe-vision/src/lib.rsindex e3c1bd106..000e40e16 100644--- a/screenpipe-vision/src/lib.rs+++ b/screenpipe-vision/src/lib.rs@@ -5,6 +5,7 @@ pub mod custom_ocr;#[cfg(target_os = "windows")]pub mod microsoft;pub mod monitor;+pub mod ocr_cache;pub mod tesseract;pub mod utils;#[cfg(target_os = "macos")]diff --git a/screenpipe-vision/src/ocr_cache.rs b/screenpipe-vision/src/ocr_cache.rsnew file mode 100644index 000000000..981dbf3be--- /dev/null+++ b/screenpipe-vision/src/ocr_cache.rs@@ -0,0 +1,393 @@+use std::collections::HashMap;+use std::hash::{DefaultHasher, Hash, Hasher};+use std::time::{Duration, Instant};++/// Cached OCR result for a window+#[derive(Clone, Debug)]+pub struct CachedOcrResult {+ pub text: String,+ pub text_json: String,+ pub confidence: f64,+ pub cached_at: Instant,+}++/// Key for identifying a window's content+#[derive(Hash, Eq, PartialEq, Clone, Debug)]+pub struct WindowCacheKey {+ /// Window identifier (app_name + window_name combination)+ pub window_id: String,+ /// Hash of the window's image content+ pub image_hash: u64,+}++/// Cache for window OCR results to avoid re-processing unchanged windows+pub struct WindowOcrCache {+ cache: HashMap<WindowCacheKey, CachedOcrResult>,+ /// Maximum age before a cached result is considered stale+ max_age: Duration,+ /// Maximum number of entries to prevent unbounded memory growth+ max_entries: usize,+ /// Stats for monitoring cache effectiveness+ hits: u64,+ misses: u64,+}++impl WindowOcrCache {+ pub fn new(max_age: Duration, max_entries: usize) -> Self {+ Self {+ cache: HashMap::new(),+ max_age,+ max_entries,+ hits: 0,+ misses: 0,+ }+ }++ /// Create with default settings (5 minute max age, 100 entries)+ pub fn default() -> Self {+ Self::new(Duration::from_secs(300), 100)+ }++ /// Calculate hash for an image's raw bytes+ pub fn calculate_image_hash(image_bytes: &[u8]) -> u64 {+ let mut hasher = DefaultHasher::new();+ image_bytes.hash(&mut hasher);+ hasher.finish()+ }++ /// Create a window ID from app name and window name+ pub fn make_window_id(app_name: &str, window_name: &str) -> String {+ format!("{}::{}", app_name, window_name)+ }++ /// Try to get a cached OCR result for a window+ /// Returns Some(result) if cache hit and not stale, None otherwise+ pub fn get(&mut self, key: &WindowCacheKey) -> Option<CachedOcrResult> {+ if let Some(cached) = self.cache.get(key) {+ // Check if cache entry is still fresh+ if cached.cached_at.elapsed() < self.max_age {+ self.hits += 1;+ return Some(cached.clone());+ }+ // Entry is stale, will be replaced on next insert+ }+ self.misses += 1;+ None+ }++ /// Store an OCR result in the cache+ pub fn insert(&mut self, key: WindowCacheKey, text: String, text_json: String, confidence: f64) {+ // Evict oldest entries if at capacity+ if self.cache.len() >= self.max_entries {+ self.evict_oldest();+ }++ self.cache.insert(+ key,+ CachedOcrResult {+ text,+ text_json,+ confidence,+ cached_at: Instant::now(),+ },+ );+ }++ /// Remove the oldest cache entry+ fn evict_oldest(&mut self) {+ if let Some(oldest_key) = self+ .cache+ .iter()+ .min_by_key(|(_, v)| v.cached_at)+ .map(|(k, _)| k.clone())+ {+ self.cache.remove(&oldest_key);+ }+ }++ /// Clear all cached entries+ pub fn clear(&mut self) {+ self.cache.clear();+ self.hits = 0;+ self.misses = 0;+ }++ /// Get cache statistics+ pub fn stats(&self) -> CacheStats {+ CacheStats {+ entries: self.cache.len(),+ hits: self.hits,+ misses: self.misses,+ hit_rate: if self.hits + self.misses > 0 {+ self.hits as f64 / (self.hits + self.misses) as f64+ } else {+ 0.0+ },+ }+ }++ /// Remove stale entries (older than max_age)+ pub fn cleanup_stale(&mut self) {+ let now = Instant::now();+ self.cache+ .retain(|_, v| now.duration_since(v.cached_at) < self.max_age);+ }+}++#[derive(Debug, Clone)]+pub struct CacheStats {+ pub entries: usize,+ pub hits: u64,+ pub misses: u64,+ pub hit_rate: f64,+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::thread::sleep;++ #[test]+ fn test_cache_hit_on_same_content() {+ let mut cache = WindowOcrCache::new(Duration::from_secs(60), 10);++ let key = WindowCacheKey {+ window_id: "VSCode::main.rs".to_string(),+ image_hash: 12345,+ };++ // Insert OCR result+ cache.insert(+ key.clone(),+ "fn main() {}".to_string(),+ r#"[{"text": "fn main() {}"}]"#.to_string(),+ 0.95,+ );++ // Should hit cache with same key+ let result = cache.get(&key);+ assert!(result.is_some());+ let cached = result.unwrap();+ assert_eq!(cached.text, "fn main() {}");+ assert_eq!(cached.confidence, 0.95);++ let stats = cache.stats();+ assert_eq!(stats.hits, 1);+ assert_eq!(stats.misses, 0);+ }++ #[test]+ fn test_cache_miss_on_different_hash() {+ let mut cache = WindowOcrCache::new(Duration::from_secs(60), 10);++ let key1 = WindowCacheKey {+ window_id: "VSCode::main.rs".to_string(),+ image_hash: 12345,+ };+ let key2 = WindowCacheKey {+ window_id: "VSCode::main.rs".to_string(),+ image_hash: 67890, // Different hash = content changed+ };++ cache.insert(+ key1.clone(),+ "fn main() {}".to_string(),+ "[]".to_string(),+ 0.95,+ );++ // Same window, different content hash = cache miss+ let result = cache.get(&key2);+ assert!(result.is_none());++ let stats = cache.stats();+ assert_eq!(stats.hits, 0);+ assert_eq!(stats.misses, 1);+ }++ #[test]+ fn test_cache_miss_on_different_window() {+ let mut cache = WindowOcrCache::new(Duration::from_secs(60), 10);++ let key1 = WindowCacheKey {+ window_id: "VSCode::main.rs".to_string(),+ image_hash: 12345,+ };+ let key2 = WindowCacheKey {+ window_id: "Terminal::zsh".to_string(), // Different window+ image_hash: 12345,+ };++ cache.insert(key1, "code".to_string(), "[]".to_string(), 0.9);++ // Different window = cache miss+ let result = cache.get(&key2);+ assert!(result.is_none());+ }++ #[test]+ fn test_cache_expiry() {+ // Very short max age for testing+ let mut cache = WindowOcrCache::new(Duration::from_millis(50), 10);++ let key = WindowCacheKey {+ window_id: "Test::window".to_string(),+ image_hash: 111,+ };++ cache.insert(key.clone(), "text".to_string(), "[]".to_string(), 0.9);++ // Should hit immediately+ assert!(cache.get(&key).is_some());++ // Wait for expiry+ sleep(Duration::from_millis(60));++ // Should miss after expiry+ assert!(cache.get(&key).is_none());+ }++ #[test]+ fn test_cache_eviction_at_capacity() {+ let mut cache = WindowOcrCache::new(Duration::from_secs(60), 3);++ // Fill cache to capacity+ for i in 0..3 {+ let key = WindowCacheKey {+ window_id: format!("Window{}", i),+ image_hash: i as u64,+ };+ cache.insert(key, format!("text{}", i), "[]".to_string(), 0.9);+ }++ assert_eq!(cache.stats().entries, 3);++ // Add one more - should evict oldest+ let new_key = WindowCacheKey {+ window_id: "Window3".to_string(),+ image_hash: 3,+ };+ cache.insert(new_key, "text3".to_string(), "[]".to_string(), 0.9);++ // Still at capacity+ assert_eq!(cache.stats().entries, 3);++ // Oldest (Window0) should be evicted+ let old_key = WindowCacheKey {+ window_id: "Window0".to_string(),+ image_hash: 0,+ };+ assert!(cache.get(&old_key).is_none());+ }++ #[test]+ fn test_multiple_windows_cached() {+ let mut cache = WindowOcrCache::new(Duration::from_secs(60), 100);++ // Simulate multiple windows+ let windows = vec![+ ("VSCode", "main.rs", 111, "fn main()"),+ ("Chrome", "GitHub", 222, "Pull Requests"),+ ("Terminal", "zsh", 333, "$ cargo build"),+ ("Slack", "general", 444, "Hello team"),+ ];++ for (app, window, hash, text) in &windows {+ let key = WindowCacheKey {+ window_id: format!("{}::{}", app, window),+ image_hash: *hash,+ };+ cache.insert(key, text.to_string(), "[]".to_string(), 0.9);+ }++ // All should be cached+ for (app, window, hash, text) in &windows {+ let key = WindowCacheKey {+ window_id: format!("{}::{}", app, window),+ image_hash: *hash,+ };+ let result = cache.get(&key);+ assert!(result.is_some(), "Should find cached result for {}::{}", app, window);+ assert_eq!(result.unwrap().text, *text);+ }++ let stats = cache.stats();+ assert_eq!(stats.hits, 4);+ assert_eq!(stats.entries, 4);+ }++ #[test]+ fn test_cleanup_stale() {+ let mut cache = WindowOcrCache::new(Duration::from_millis(50), 10);++ let key1 = WindowCacheKey {+ window_id: "Old".to_string(),+ image_hash: 1,+ };+ cache.insert(key1, "old".to_string(), "[]".to_string(), 0.9);++ sleep(Duration::from_millis(60));++ let key2 = WindowCacheKey {+ window_id: "New".to_string(),+ image_hash: 2,+ };+ cache.insert(key2.clone(), "new".to_string(), "[]".to_string(), 0.9);++ // Both in cache before cleanup+ assert_eq!(cache.cache.len(), 2);++ cache.cleanup_stale();++ // Only new entry remains+ assert_eq!(cache.cache.len(), 1);+ assert!(cache.get(&key2).is_some());+ }++ #[test]+ fn test_hit_rate_calculation() {+ let mut cache = WindowOcrCache::new(Duration::from_secs(60), 10);++ let key = WindowCacheKey {+ window_id: "Test".to_string(),+ image_hash: 1,+ };+ cache.insert(key.clone(), "text".to_string(), "[]".to_string(), 0.9);++ // 2 hits+ cache.get(&key);+ cache.get(&key);++ // 1 miss+ let miss_key = WindowCacheKey {+ window_id: "Other".to_string(),+ image_hash: 2,+ };+ cache.get(&miss_key);++ let stats = cache.stats();+ assert_eq!(stats.hits, 2);+ assert_eq!(stats.misses, 1);+ assert!((stats.hit_rate - 0.666).abs() < 0.01); // ~66.6% hit rate+ }++ #[test]+ fn test_image_hash_consistency() {+ let bytes1 = b"hello world image bytes";+ let bytes2 = b"hello world image bytes";+ let bytes3 = b"different image bytes";++ let hash1 = WindowOcrCache::calculate_image_hash(bytes1);+ let hash2 = WindowOcrCache::calculate_image_hash(bytes2);+ let hash3 = WindowOcrCache::calculate_image_hash(bytes3);++ assert_eq!(hash1, hash2, "Same content should have same hash");+ assert_ne!(hash1, hash3, "Different content should have different hash");+ }++ #[test]+ fn test_make_window_id() {+ let id = WindowOcrCache::make_window_id("VSCode", "main.rs - screenpipe");+ assert_eq!(id, "VSCode::main.rs - screenpipe");+ }+}