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
fix: memory leak on apple native OCR #278
Louis Beaumontb0c023f9f730
diff --git a/Cargo.toml b/Cargo.tomlindex c5b25c394..277ccf58d 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -5,12 +5,9 @@ members = ["screenpipe-audio","screenpipe-server","screenpipe-integrations",-]exclude = ["examples/apps/screenpipe-app-tauri/src-tauri",--]resolver = "2"@@ -30,7 +27,7 @@ candle-nn = { package = "candle-nn", version = "0.6.0" }candle-transformers = { package = "candle-transformers", version = "0.6.0" }tokenizers = "0.19.1"tracing = "0.1.40"-tracing-subscriber = "0.3.18"+tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }tokio = { version = "1.15", features = ["full", "tracing"] }hf-hub = "0.3.0"crossbeam = "0.8.4"diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 605d1fe4e..11435c4f0 100644--- a/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "screenpipe-app"-version = "0.1.86"+version = "0.1.87"description = ""authors = ["you"]license = ""diff --git a/screenpipe-integrations/src/unstructured_ocr.rs b/screenpipe-integrations/src/unstructured_ocr.rsindex f24ebc52b..81816aa88 100644--- a/screenpipe-integrations/src/unstructured_ocr.rs+++ b/screenpipe-integrations/src/unstructured_ocr.rs@@ -5,7 +5,6 @@ use std::collections::HashMap;use std::env;use std::io::Cursor;use std::io::Write;-use std::sync::Arc;use tokio::time::{timeout, Duration};use reqwest::blocking::Client;use serde_json::Value;@@ -13,7 +12,7 @@ use tempfile::NamedTempFile;use anyhow::{Result, anyhow};use log::error;-pub async fn perform_ocr_cloud(image: &Arc<DynamicImage>) -> Result<(String, String, Option<f64>)> {+pub async fn perform_ocr_cloud(image: &DynamicImage) -> Result<(String, String, Option<f64>)> {let api_key = match env::var("UNSTRUCTURED_API_KEY") {Ok(key) => key,Err(_) => {diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 0ea6fca42..8d941dc96 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -46,7 +46,7 @@ impl VideoCapture {result_sender,Duration::from_secs_f64(1.0 / fps),save_text_files,- ocr_engine,+ *ocr_engine,monitor_id,).await;diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.tomlindex 77c3e1b87..9be6089d9 100644--- a/screenpipe-vision/Cargo.toml+++ b/screenpipe-vision/Cargo.toml@@ -35,6 +35,9 @@ clap = { version = "4.0", features = ["derive"] }# Integrationsscreenpipe-integrations = { path = "../screenpipe-integrations" }+tracing-subscriber = { workspace = true }+tracing = { workspace = true }+[dev-dependencies]tempfile = "3.3.0"criterion = { workspace = true }@@ -42,6 +45,8 @@ assert_cmd = "2.0.14"predicates = "3.1.0"assert_fs = "1.1.1"strsim = "0.10.0"+memory-stats = "1.2.0"+[build-dependencies]cc = "1.0"@@ -61,6 +66,10 @@ harness = falsename = "ocr_benchmark"harness = false+[[bench]]+name = "apple_leak_bench"+harness = false+[target.'cfg(target_os = "windows")'.dependencies]windows = { version = "0.58", features = ["Graphics_Imaging", "Media_Ocr", "Storage", "Storage_Streams"] }diff --git a/screenpipe-vision/benches/apple_leak_bench.rs b/screenpipe-vision/benches/apple_leak_bench.rsnew file mode 100644index 000000000..f26f9bff3--- /dev/null+++ b/screenpipe-vision/benches/apple_leak_bench.rs@@ -0,0 +1,96 @@+use criterion::{criterion_group, criterion_main, Criterion};+use image::GenericImageView;+use memory_stats::memory_stats;+use screenpipe_vision::perform_ocr_apple;+use std::path::PathBuf;++fn bytes_to_mb(bytes: usize) -> f64 {+ bytes as f64 / (1024.0 * 1024.0)+}++fn bytes_to_gb(bytes: usize) -> f64 {+ bytes as f64 / (1024.0 * 1024.0 * 1024.0)+}++fn apple_ocr_benchmark(c: &mut Criterion) {+ let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ path.push("tests");+ path.push("testing_OCR.png");++ let image = image::open(&path).expect("Failed to open image");+ println!("Image dimensions: {:?}", image.dimensions());++ let mut group = c.benchmark_group("apple_ocr");+ group.sample_size(100); // Increased sample size+ group.measurement_time(std::time::Duration::from_secs(60)); // Run for at least 60 seconds+ group.bench_function("perform_ocr_apple", |b| {+ b.iter_custom(|iters| {+ let start = std::time::Instant::now();+ let mut initial_memory = 0;+ let mut final_memory = 0;+ let mut max_memory = 0;++ for i in 0..iters {+ if i == 0 {+ if let Some(usage) = memory_stats() {+ initial_memory = usage.physical_mem;+ max_memory = initial_memory;+ }+ }++ let result = perform_ocr_apple(&image);+ assert!(+ result.contains("receiver_count"),+ "OCR failed: {:?}",+ result+ );++ if let Some(usage) = memory_stats() {+ final_memory = usage.physical_mem;+ max_memory = max_memory.max(final_memory);+ }++ if i % 10 == 0 {+ println!(+ "Iteration {}: Current memory usage: {:.2} MB ({:.3} GB)",+ i,+ bytes_to_mb(final_memory),+ bytes_to_gb(final_memory)+ );+ }+ }++ println!(+ "Initial memory usage: {:.2} MB ({:.3} GB)",+ bytes_to_mb(initial_memory),+ bytes_to_gb(initial_memory)+ );+ println!(+ "Final memory usage: {:.2} MB ({:.3} GB)",+ bytes_to_mb(final_memory),+ bytes_to_gb(final_memory)+ );+ println!(+ "Max memory usage: {:.2} MB ({:.3} GB)",+ bytes_to_mb(max_memory),+ bytes_to_gb(max_memory)+ );+ println!(+ "Total memory difference: {:.2} MB ({:.3} GB)",+ bytes_to_mb(final_memory - initial_memory),+ bytes_to_gb(final_memory - initial_memory)+ );+ println!(+ "Max memory difference: {:.2} MB ({:.3} GB)",+ bytes_to_mb(max_memory - initial_memory),+ bytes_to_gb(max_memory - initial_memory)+ );++ start.elapsed()+ });+ });+ group.finish();+}++criterion_group!(benches, apple_ocr_benchmark);+criterion_main!(benches);diff --git a/screenpipe-vision/lib/libscreenpipe.dylib b/screenpipe-vision/lib/libscreenpipe.dylibindex 853fbf369..06c4f1e1b 100755Binary files a/screenpipe-vision/lib/libscreenpipe.dylib and b/screenpipe-vision/lib/libscreenpipe.dylib differdiff --git a/screenpipe-vision/lib/libscreenpipe_arm64.dylib b/screenpipe-vision/lib/libscreenpipe_arm64.dylibindex cdcefde2e..6edc908a9 100755Binary files a/screenpipe-vision/lib/libscreenpipe_arm64.dylib and b/screenpipe-vision/lib/libscreenpipe_arm64.dylib differdiff --git a/screenpipe-vision/lib/libscreenpipe_x86_64.dylib b/screenpipe-vision/lib/libscreenpipe_x86_64.dylibindex 7f2136a00..66bb8f0a3 100755Binary files a/screenpipe-vision/lib/libscreenpipe_x86_64.dylib and b/screenpipe-vision/lib/libscreenpipe_x86_64.dylib differdiff --git a/screenpipe-vision/src/apple.rs b/screenpipe-vision/src/apple.rsindex 679e0dee8..dfe28bbfb 100644--- a/screenpipe-vision/src/apple.rs+++ b/screenpipe-vision/src/apple.rs@@ -3,6 +3,20 @@ use log::error;use std::ffi::CStr;use std::os::raw::{c_char, c_uchar};+use std::ops::Drop;++struct OcrResultGuard(*mut c_char);++impl Drop for OcrResultGuard {+ fn drop(&mut self) {+ unsafe {+ if !self.0.is_null() {+ free_string(self.0);+ }+ }+ }+}+#[cfg(target_os = "macos")]#[link(name = "screenpipe")]extern "C" {@@ -12,6 +26,7 @@ extern "C" {width: i32,height: i32,) -> *mut c_char;+ fn free_string(ptr: *mut c_char);}#[cfg(target_os = "macos")]pub fn perform_ocr_apple(image: &DynamicImage) -> String {@@ -26,8 +41,8 @@ pub fn perform_ocr_apple(image: &DynamicImage) -> String {width as i32,height as i32,);+ let _guard = OcrResultGuard(result_ptr);let result = CStr::from_ptr(result_ptr).to_string_lossy().into_owned();- libc::free(result_ptr as *mut libc::c_void);result}}@@ -51,8 +66,7 @@ pub fn parse_apple_ocr_result(json_result: &str) -> (String, String, Option<f64>.as_array().unwrap_or(&vec![]).clone();- let overall_confidence = parsed_result["overallConfidence"]- .as_f64();+ let overall_confidence = parsed_result["overallConfidence"].as_f64();let json_output: Vec<serde_json::Value> = text_elements.iter()@@ -80,4 +94,4 @@ pub fn parse_apple_ocr_result(json_result: &str) -> (String, String, Option<f64>});(text, json_output_string, overall_confidence)-}\ No newline at end of file+}diff --git a/screenpipe-vision/src/bin/screenpipe-vision.rs b/screenpipe-vision/src/bin/screenpipe-vision.rsindex 27b6f5cfb..d2a2bc648 100644--- a/screenpipe-vision/src/bin/screenpipe-vision.rs+++ b/screenpipe-vision/src/bin/screenpipe-vision.rs@@ -1,7 +1,8 @@use clap::Parser;use screenpipe_vision::{continuous_capture, monitor::get_default_monitor, OcrEngine};-use std::{sync::Arc, time::Duration};+use std::time::Duration;use tokio::sync::mpsc::channel;+use tracing_subscriber::{fmt::format::FmtSpan, EnvFilter};#[derive(Parser)]#[command(author, version, about, long_about = None)]@@ -17,6 +18,14 @@ struct Cli {#[tokio::main]async fn main() {+ tracing_subscriber::fmt()+ .with_env_filter(+ EnvFilter::from_default_env()+ .add_directive(tracing::Level::DEBUG.into())+ .add_directive("tokenizers=error".parse().unwrap()),+ )+ .with_span_events(FmtSpan::CLOSE)+ .init();let cli = Cli::parse();let (result_tx, mut result_rx) = channel(512);@@ -31,11 +40,7 @@ async fn main() {result_tx,Duration::from_secs_f32(1.0 / cli.fps),save_text_files,- Arc::new(if cfg!(target_os = "macos") {- OcrEngine::AppleNative- } else {- OcrEngine::Tesseract- }),+ OcrEngine::AppleNative,id,).awaitdiff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex 838f42344..f4745f3cc 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -4,7 +4,6 @@ use screenpipe_integrations::unstructured_ocr::perform_ocr_cloud;use serde_json;use std::{collections::HashMap,- sync::{Arc, Weak},time::{Duration, Instant},};use tokio::sync::mpsc::Sender;@@ -19,19 +18,17 @@ use crate::monitor::get_monitor_by_id;use crate::tesseract::perform_ocr_tesseract;use crate::utils::OcrEngine;use crate::utils::{capture_screenshot, compare_with_previous_image, save_text_files};-#[derive(Clone)]+pub struct CaptureResult {- pub image: Arc<DynamicImage>,+ pub image: DynamicImage,pub frame_number: u64,pub timestamp: Instant,pub window_ocr_results: Vec<WindowOcrResult>,}-#[derive(Clone)]pub struct WindowOcrResult {pub window_name: String,pub app_name: String,- pub image: Arc<DynamicImage>,pub text: String,pub text_json: Vec<HashMap<String, String>>,pub focused: bool,@@ -39,7 +36,7 @@ pub struct WindowOcrResult {}pub struct OcrTaskData {- pub image: Arc<DynamicImage>,+ pub image: DynamicImage,pub window_images: Vec<(DynamicImage, String, String, bool)>,pub frame_number: u64,pub timestamp: Instant,@@ -50,7 +47,7 @@ pub async fn continuous_capture(result_tx: Sender<CaptureResult>,interval: Duration,save_text_files_flag: bool,- ocr_engine: Arc<OcrEngine>,+ ocr_engine: OcrEngine,monitor_id: u32,) {debug!(@@ -58,18 +55,14 @@ pub async fn continuous_capture(monitor_id);let mut frame_counter: u64 = 0;- let mut previous_image: Option<Arc<DynamicImage>> = None;+ let mut previous_image: Option<DynamicImage> = None;let mut max_average: Option<MaxAverageFrame> = None;let mut max_avg_value = 0.0;let monitor = get_monitor_by_id(monitor_id).await.unwrap();- let arc_monitor = Arc::new(monitor);- let weak_monitor = Arc::downgrade(&arc_monitor);- let weak_ocr_engine = Arc::downgrade(&ocr_engine);loop {- let weak_monitor = weak_monitor.clone();- let capture_result = match capture_screenshot(weak_monitor).await {+ let capture_result = match capture_screenshot(&monitor).await {Ok((image, window_images, image_hash, _capture_duration)) => {Some((image, window_images, image_hash))}@@ -81,7 +74,7 @@ pub async fn continuous_capture(if let Some((image, window_images, image_hash)) = capture_result {let current_average = match compare_with_previous_image(- &previous_image,+ previous_image.as_ref(),&image,&mut max_average,frame_counter,@@ -92,18 +85,16 @@ pub async fn continuous_capture(Ok(avg) => avg,Err(e) => {error!("Error comparing images: {}", e);- 0.0 // or some default value+ 0.0}};- // Account for situation when there is no previous imagelet current_average = if previous_image.is_none() {- 1.0 // Default value to ensure the frame is processed+ 1.0} else {current_average};- // Skip the frame if the current average difference is less than 0.006if current_average < 0.006 {debug!("Skipping frame {} due to low average difference: {:.3}",@@ -116,7 +107,7 @@ pub async fn continuous_capture(if current_average > max_avg_value {max_average = Some(MaxAverageFrame {- image: Arc::new(image.clone()),+ image: image.clone(),window_images: window_images.clone(),image_hash,frame_number: frame_counter,@@ -127,29 +118,19 @@ pub async fn continuous_capture(max_avg_value = current_average;}- previous_image = Some(Arc::new(image.clone()));+ previous_image = Some(image);if let Some(max_avg_frame) = max_average.take() {let ocr_task_data = OcrTaskData {- image: max_avg_frame.image.clone(),- window_images: max_avg_frame.window_images.clone(),+ image: max_avg_frame.image,+ window_images: max_avg_frame.window_images,frame_number: max_avg_frame.frame_number,timestamp: max_avg_frame.timestamp,- result_tx: max_avg_frame.result_tx.clone(),+ result_tx: max_avg_frame.result_tx,};- let ocr_engine_clone = weak_ocr_engine.clone();-- if let Err(e) = process_ocr_task(- ocr_task_data.image,- ocr_task_data.window_images,- ocr_task_data.frame_number,- ocr_task_data.timestamp,- ocr_task_data.result_tx,- save_text_files_flag,- ocr_engine_clone,- )- .await+ if let Err(e) =+ process_ocr_task(ocr_task_data, save_text_files_flag, &ocr_engine).await{error!("Error processing OCR task: {}", e);}@@ -158,7 +139,6 @@ pub async fn continuous_capture(max_avg_value = 0.0;}} else {- // Skip this iteration if capture faileddebug!("Skipping frame {} due to capture failure", frame_counter);}@@ -166,8 +146,9 @@ pub async fn continuous_capture(tokio::time::sleep(interval).await;}}+pub struct MaxAverageFrame {- pub image: Arc<DynamicImage>,+ pub image: DynamicImage,pub window_images: Vec<(DynamicImage, String, String, bool)>,pub image_hash: u64,pub frame_number: u64,@@ -177,51 +158,43 @@ pub struct MaxAverageFrame {}pub async fn process_ocr_task(- image_arc: Arc<DynamicImage>,- window_images: Vec<(DynamicImage, String, String, bool)>,- frame_number: u64,- timestamp: Instant,- result_tx: Sender<CaptureResult>,+ ocr_task_data: OcrTaskData,save_text_files_flag: bool,- ocr_engine: Weak<OcrEngine>,+ ocr_engine: &OcrEngine,) -> Result<(), std::io::Error> {+ let OcrTaskData {+ image,+ window_images,+ frame_number,+ timestamp,+ result_tx,+ } = ocr_task_data;+let start_time = Instant::now();debug!("Performing OCR for frame number since beginning of program {}",frame_number);- // Perform OCR on window imageslet mut window_ocr_results = Vec::new();let mut total_confidence = 0.0;let mut window_count = 0;for (window_image, window_app_name, window_name, focused) in window_images {- let window_image_arc = Arc::new(window_image);- let (window_text, window_json_output, confidence) = match ocr_engine.upgrade() {- Some(engine) => match &*engine {- OcrEngine::Unstructured => perform_ocr_cloud(&window_image_arc)- .await- .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,- OcrEngine::Tesseract => perform_ocr_tesseract(&window_image_arc),- #[cfg(target_os = "windows")]- OcrEngine::WindowsNative => perform_ocr_windows(&window_image_arc).await,- #[cfg(target_os = "macos")]- OcrEngine::AppleNative => {- parse_apple_ocr_result(&perform_ocr_apple(&window_image_arc))- }- _ => {- return Err(std::io::Error::new(- std::io::ErrorKind::Other,- "Unsupported OCR engine",- ))- }- },- None => {+ let (window_text, window_json_output, confidence) = match ocr_engine {+ OcrEngine::Unstructured => perform_ocr_cloud(&window_image)+ .await+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,+ OcrEngine::Tesseract => perform_ocr_tesseract(&window_image),+ #[cfg(target_os = "windows")]+ OcrEngine::WindowsNative => perform_ocr_windows(&window_image).await,+ #[cfg(target_os = "macos")]+ OcrEngine::AppleNative => parse_apple_ocr_result(&perform_ocr_apple(&window_image)),+ _ => {return Err(std::io::Error::new(std::io::ErrorKind::Other,- "OCR engine not found",- ));+ "Unsupported OCR engine",+ ))}};@@ -233,7 +206,6 @@ pub async fn process_ocr_task(window_ocr_results.push(WindowOcrResult {window_name,app_name: window_app_name,- image: window_image_arc,text: window_text,text_json: parse_json_output(&window_json_output),focused,@@ -242,10 +214,9 @@ pub async fn process_ocr_task(}if save_text_files_flag {- // Save text files for window OCR results if neededfor (index, window_result) in window_ocr_results.iter().enumerate() {save_text_files(- frame_number * 1000 + index as u64, // Unique ID for each window+ frame_number * 1000 + index as u64,&window_result.text_json,&window_result.text_json,&None,@@ -255,10 +226,10 @@ pub async fn process_ocr_task(}let capture_result = CaptureResult {- image: image_arc,+ image,frame_number,timestamp,- window_ocr_results: window_ocr_results.clone(),+ window_ocr_results,};if let Err(e) = result_tx.send(capture_result).await {@@ -277,16 +248,12 @@ pub async fn process_ocr_task(};debug!("OCR task processed frame {} with {} windows in {:?}, average confidence: {:.2}",- frame_number,- window_ocr_results.len(),- duration,- avg_confidence+ frame_number, window_count, duration, avg_confidence);Ok(())}fn parse_json_output(json_output: &str) -> Vec<HashMap<String, String>> {- // TODO: this function uses a TONN of memory and is not efficient and we should use binary serialization insteadlet parsed_output: Vec<HashMap<String, String>> = serde_json::from_str(json_output).unwrap_or_else(|e| {error!("Failed to parse JSON output: {}", e);diff --git a/screenpipe-vision/src/ocr.swift b/screenpipe-vision/src/ocr.swiftindex ead7bc4e6..ac33ca165 100644--- a/screenpipe-vision/src/ocr.swift+++ b/screenpipe-vision/src/ocr.swift@@ -9,105 +9,125 @@ import Vision@_cdecl("perform_ocr")public func performOCR(imageData: UnsafePointer<UInt8>, length: Int, width: Int, height: Int)-> UnsafeMutablePointer<CChar>? {-- guard let dataProvider = CGDataProvider(data: Data(bytes: imageData, count: length) as CFData),- let cgImage = CGImage(- width: width,- height: height,- bitsPerComponent: 8,- bitsPerPixel: 32,- bytesPerRow: width * 4,- space: CGColorSpaceCreateDeviceRGB(),- bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),- provider: dataProvider,- decode: nil,- shouldInterpolate: false,- intent: .defaultIntent- )- else {- return strdup("Error: Failed to create CGImage")- }-- // Preprocess the image- let ciImage = CIImage(cgImage: cgImage)- let context = CIContext(options: nil)-- // Apply preprocessing filters (slightly reduced contrast compared to original)- let processed = ciImage- .applyingFilter("CIColorControls", parameters: [kCIInputSaturationKey: 0, kCIInputContrastKey: 1.08])- .applyingFilter("CIUnsharpMask", parameters: [kCIInputRadiusKey: 0.8, kCIInputIntensityKey: 0.4])-- guard let preprocessedCGImage = context.createCGImage(processed, from: processed.extent) else {- return strdup("Error: Failed to create preprocessed image")- }-- var ocrResult = ""- var textElements: [[String: Any]] = []- var totalConfidence: Float = 0.0- var observationCount: Int = 0-- let textRequest = VNRecognizeTextRequest { request, error in- if let error = error {- print("Error: \(error.localizedDescription)")- return+ return autoreleasepool {++ guard let dataProvider = CGDataProvider(data: Data(bytes: imageData, count: length) as CFData),+ let cgImage = CGImage(+ width: width,+ height: height,+ bitsPerComponent: 8,+ bitsPerPixel: 32,+ bytesPerRow: width * 4,+ space: CGColorSpaceCreateDeviceRGB(),+ bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),+ provider: dataProvider,+ decode: nil,+ shouldInterpolate: false,+ intent: .defaultIntent+ )+ else {+ return strdup("Error: Failed to create CGImage")}- guard let observations = request.results as? [VNRecognizedTextObservation] else {- print("Error: Failed to process image or no text found")- return+ // Preprocess the image+ let ciImage = CIImage(cgImage: cgImage)+ let context = CIContext(options: nil)++ // Apply preprocessing filters (slightly reduced contrast compared to original)+ let processed =+ ciImage+ .applyingFilter(+ "CIColorControls", parameters: [kCIInputSaturationKey: 0, kCIInputContrastKey: 1.08]+ )+ .applyingFilter(+ "CIUnsharpMask", parameters: [kCIInputRadiusKey: 0.8, kCIInputIntensityKey: 0.4])++ guard let preprocessedCGImage = context.createCGImage(processed, from: processed.extent) else {+ return strdup("Error: Failed to create preprocessed image")}- for observation in observations {- guard let topCandidate = observation.topCandidates(1).first else {- continue+ var ocrResult = ""+ var textElements: [[String: Any]] = []+ var totalConfidence: Float = 0.0+ var observationCount: Int = 0++ let textRequest = VNRecognizeTextRequest { request, error in+ if let error = error {+ print("Error: \(error.localizedDescription)")+ return+ }++ guard let observations = request.results as? [VNRecognizedTextObservation] else {+ print("Error: Failed to process image or no text found")+ return}- let text = topCandidate.string- let confidence = topCandidate.confidence- // Reduced threshold for including results- if confidence < 0.2 {- continue // Skip very low-confidence results+ for observation in observations {+ guard let topCandidate = observation.topCandidates(1).first else {+ continue+ }+ let text = topCandidate.string+ let confidence = topCandidate.confidence++ // Reduced threshold for including results+ if confidence < 0.2 {+ continue // Skip very low-confidence results+ }+ let boundingBox = observation.boundingBox+ textElements.append([+ "text": text,+ "confidence": confidence,+ "boundingBox": [+ "x": boundingBox.origin.x,+ "y": boundingBox.origin.y,+ "width": boundingBox.size.width,+ "height": boundingBox.size.height+ ]+ ])++ ocrResult += "\(text)\n"+ totalConfidence += confidence+ observationCount += 1}- let boundingBox = observation.boundingBox- textElements.append([- "text": text,- "confidence": confidence,- "boundingBox": [- "x": boundingBox.origin.x,- "y": boundingBox.origin.y,- "width": boundingBox.size.width,- "height": boundingBox.size.height- ]- ])-- ocrResult += "\(text)\n"- totalConfidence += confidence- observationCount += 1}- }- textRequest.recognitionLevel = .accurate // Keep accurate recognition+ textRequest.recognitionLevel = .accurate // Keep accurate recognition- let handler = VNImageRequestHandler(cgImage: preprocessedCGImage, options: [:])- do {- try handler.perform([textRequest])- } catch {- print("Error: Failed to perform OCR - \(error.localizedDescription)")+ let handler = VNImageRequestHandler(cgImage: preprocessedCGImage, options: [:])+ do {+ try handler.perform([textRequest])+ } catch {+ print("Error: Failed to perform OCR - \(error.localizedDescription)")+ }++ let overallConfidence = observationCount > 0 ? totalConfidence / Float(observationCount) : 0.0+ // print("Overall confidence: \(overallConfidence)")+ let result: [String: Any] = [+ "ocrResult": ocrResult.isEmpty ? NSNull() : ocrResult,+ "textElements": textElements,+ "overallConfidence": overallConfidence+ ]++ if let jsonData = try? JSONSerialization.data(withJSONObject: result, options: []),+ let jsonString = String(data: jsonData, encoding: .utf8) {+ let cString = jsonString.cString(using: .utf8)+ let buffer = UnsafeMutablePointer<Int8>.allocate(capacity: cString!.count)+ buffer.initialize(from: cString!, count: cString!.count)+ return buffer+ } else {+ let errorString = "Error: Failed to serialize result to JSON"+ let cString = errorString.cString(using: .utf8)!+ let buffer = UnsafeMutablePointer<Int8>.allocate(capacity: cString.count)+ buffer.initialize(from: cString, count: cString.count)+ return buffer+ }}+}- let overallConfidence = observationCount > 0 ? totalConfidence / Float(observationCount) : 0.0- // print("Overall confidence: \(overallConfidence)")- let result: [String: Any] = [- "ocrResult": ocrResult.isEmpty ? NSNull() : ocrResult,- "textElements": textElements,- "overallConfidence": overallConfidence- ]-- if let jsonData = try? JSONSerialization.data(withJSONObject: result, options: []),- let jsonString = String(data: jsonData, encoding: .utf8) {- return strdup(jsonString)- } else {- return strdup("Error: Failed to serialize result to JSON")+@_cdecl("free_string")+public func freeString(_ ptr: UnsafeMutablePointer<Int8>?) {+ if let ptr = ptr {+ ptr.deallocate()}}@@ -123,4 +143,4 @@ How to optimise this code:1. run cargo bench --bench ocr_benchmark2. change the code & compile again3. run cargo bench --bench ocr_benchmark again to see if it's faster or more accurate-*/\ No newline at end of file+*/diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rsindex 82d48c1bd..13897c499 100644--- a/screenpipe-vision/src/utils.rs+++ b/screenpipe-vision/src/utils.rs@@ -8,11 +8,10 @@ use std::fs::{self, File};use std::hash::{DefaultHasher, Hash, Hasher};use std::io::Write;use std::path::PathBuf;-use std::sync::{Arc, Weak};use std::time::{Duration, Instant};use xcap::Monitor;-#[derive(Clone, Debug)]+#[derive(Clone, Debug, Copy)]pub enum OcrEngine {Unstructured,Tesseract,@@ -51,7 +50,7 @@ pub fn compare_images_ssim(image1: &DynamicImage, image2: &DynamicImage) -> f64}pub async fn capture_screenshot(- weak_monitor: Weak<Monitor>,+ monitor: &Monitor,) -> Result<(DynamicImage,@@ -61,10 +60,6 @@ pub async fn capture_screenshot(),anyhow::Error,> {- let monitor = weak_monitor- .upgrade()- .ok_or("Monitor no longer exists")- .unwrap();// info!("Starting screenshot capture for monitor: {:?}", monitor);let capture_start = Instant::now();let buffer = monitor.capture_image().map_err(|e| {@@ -94,7 +89,7 @@ pub async fn capture_screenshot(}pub async fn compare_with_previous_image(- previous_image: &Option<Arc<DynamicImage>>,+ previous_image: Option<&DynamicImage>,current_image: &DynamicImage,max_average: &mut Option<MaxAverageFrame>,frame_number: u64,