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: apple native ocr in pure rust (#829)
Mahesh Vagicherla4ccd43beb53d
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.tomlindex 93c58f47f..a43030d5d 100644--- a/screenpipe-vision/Cargo.toml+++ b/screenpipe-vision/Cargo.toml@@ -41,6 +41,7 @@ screenpipe-core = { path = "../screenpipe-core" }tracing-subscriber = { workspace = true }tracing = { workspace = true }which = "6.0"+serde = "1.0.200"once_cell = { workspace = true }@@ -93,6 +94,7 @@ xcap = "0.0.12"[target.'cfg(target_os = "macos")'.dependencies]libc = "=0.2.164"xcap-macos = { package = "xcap", git = "https://github.com/mediar-ai/xcap", rev = "965bc99" }+cidre = { git = "https://github.com/yury/cidre.git", version = "0.5.0" }[target.'cfg(target_os = "linux")'.dependencies]libc = "=0.2.164"diff --git a/screenpipe-vision/benches/apple_leak_bench.rs b/screenpipe-vision/benches/apple_leak_bench.rsindex 545758e94..07452038c 100644--- a/screenpipe-vision/benches/apple_leak_bench.rs+++ b/screenpipe-vision/benches/apple_leak_bench.rs@@ -40,7 +40,7 @@ fn apple_ocr_benchmark(c: &mut Criterion) {let result = perform_ocr_apple(&image, vec![]);assert!(- result.contains("receiver_count"),+ result.0.contains("receiver_count"),"OCR failed: {:?}",result);diff --git a/screenpipe-vision/benches/ocr_benchmark.rs b/screenpipe-vision/benches/ocr_benchmark.rsindex dea55d44f..1b15fa677 100644--- a/screenpipe-vision/benches/ocr_benchmark.rs+++ b/screenpipe-vision/benches/ocr_benchmark.rs@@ -75,6 +75,8 @@ fn load_test_image() -> image::DynamicImage {// Apple Vision OCR benchmark (macOS only)#[cfg(target_os = "macos")]fn bench_apple_vision_ocr(c: &mut Criterion) {+ use cidre::ns;+let image = load_test_image();let mut group = c.benchmark_group("Apple Vision OCR");group.sample_size(10);@@ -82,8 +84,11 @@ fn bench_apple_vision_ocr(c: &mut Criterion) {group.bench_function(BenchmarkId::new("Performance", ""), |b| {b.iter(|| {- let result = perform_ocr_apple(black_box(&image), vec![]);- assert!(!result.is_empty(), "OCR failed");+ let result = perform_ocr_apple(+ black_box(&image),+ &ns::ArrayMut::<ns::String>::with_capacity(0),+ );+ assert!(!result.0.is_empty(), "OCR failed");})});@@ -92,6 +97,8 @@ fn bench_apple_vision_ocr(c: &mut Criterion) {#[cfg(target_os = "macos")]fn bench_apple_vision_ocr_with_accuracy(c: &mut Criterion) {+ use cidre::ns;+let image = load_test_image();let mut group = c.benchmark_group("Apple Vision OCR with Accuracy");group.sample_size(10);@@ -104,10 +111,13 @@ fn bench_apple_vision_ocr_with_accuracy(c: &mut Criterion) {for _ in 0..iters {let start = std::time::Instant::now();- let result = perform_ocr_apple(black_box(&image), vec![]);+ let result = perform_ocr_apple(+ black_box(&image),+ &ns::ArrayMut::<ns::String>::with_capacity(0),+ );total_duration += start.elapsed();- let accuracy = calculate_accuracy(&result, EXPECTED_KEYWORDS);+ let accuracy = calculate_accuracy(&result.0.as_str(), EXPECTED_KEYWORDS);total_accuracy += accuracy;}diff --git a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwinindex 27dc6d78e..6eb0da298 100755Binary files a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin and b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin differdiff --git a/screenpipe-vision/lib/libscreenpipe_arm64.dylib b/screenpipe-vision/lib/libscreenpipe_arm64.dylibindex d936a8fe0..abd2e1192 100755Binary files a/screenpipe-vision/lib/libscreenpipe_arm64.dylib and b/screenpipe-vision/lib/libscreenpipe_arm64.dylib differdiff --git a/screenpipe-vision/src/apple.rs b/screenpipe-vision/src/apple.rsindex d2fb4dd2b..e32977ab6 100644--- a/screenpipe-vision/src/apple.rs+++ b/screenpipe-vision/src/apple.rs@@ -1,138 +1,142 @@+#[cfg(target_os = "macos")]+use cidre::{+ cv::{PixelBuf, PixelFormat},+ ns,+ vn::{self, ImageRequestHandler, RecognizeTextRequest},+};use image::DynamicImage;+use image::GenericImageView;use log::error;-use std::ffi::CStr;-use std::os::raw::{c_char, c_uchar};+use serde::{Deserialize, Serialize};+use std::{ffi::c_void, ptr::null_mut};-use std::ops::Drop;+#[derive(Serialize, Deserialize, Debug)]+struct OcrResultBBox {+ x: f64,+ y: f64,+ height: f64,+ width: f64,+}-struct OcrResultGuard(*mut c_char);+#[derive(Serialize, Deserialize, Debug)]+struct OcrTextElement {+ bounding_box: Vec<OcrResultBBox>,+ confidence: f32,+ text: String,+}-impl Drop for OcrResultGuard {- fn drop(&mut self) {- unsafe {- if !self.0.is_null() {- free_string(self.0);- }- }- }+#[derive(Serialize, Deserialize, Debug)]+struct OcrResult {+ ocr_result: String,+ text_elements: Vec<OcrTextElement>,+ overall_confidence: f32,}+#[no_mangle]#[cfg(target_os = "macos")]-#[link(name = "screenpipe")]-extern "C" {- fn perform_ocr(- image_data: *const c_uchar,- length: usize,- width: i32,- height: i32,- languages: *const *const c_char,- languages_count: i32,- ) -> *mut c_char;- fn free_string(ptr: *mut c_char);+extern "C" fn release_callback(_refcon: *mut c_void, _data_ptr: *const *const c_void) {+ // Implement your release logic here}+#[cfg(target_os = "macos")]pub fn perform_ocr_apple(image: &DynamicImage,- languages: Vec<screenpipe_core::Language>,-) -> String {- let rgba = image.to_rgba8();- let (width, height) = rgba.dimensions();- let raw_data = rgba.as_raw();-- let languages = get_apple_languages(languages);-- let c_languages: Vec<*const c_char> = languages- .iter()- .map(|s| s.as_ptr() as *const c_char)- .collect();-- unsafe {- let result_ptr = perform_ocr(- raw_data.as_ptr(),- raw_data.len(),- width as i32,- height as i32,- c_languages.as_ptr(),- c_languages.len() as i32,- );- let _guard = OcrResultGuard(result_ptr);- let result = CStr::from_ptr(result_ptr).to_string_lossy().into_owned();- result+ languages: &ns::ArrayMut<ns::String>,+) -> (String, String, Option<f64>) {+ let (width, height) = image.dimensions();+ let rgb = image.grayscale().to_luma8();+ let raw_data = rgb.as_raw();+ // let pixels = image.pixels();++ let mut overall_confidence = 0.0;+ let default_ocr_result = (+ String::from(""),+ String::from("[]"),+ Some(overall_confidence),+ );++ let width = usize::try_from(width).unwrap();+ let height = usize::try_from(height).unwrap();++ let mut pixel_buf_out = None;++ let pixel_buf = unsafe {+ PixelBuf::create_with_bytes_in(+ width,+ height,+ PixelFormat::ONE_COMPONENT_8,+ raw_data.as_ptr() as *mut c_void,+ width,+ release_callback,+ null_mut(),+ None,+ &mut pixel_buf_out,+ None,+ )+ .to_result_unchecked(pixel_buf_out)}-}+ .unwrap();-#[cfg(target_os = "macos")]-pub fn parse_apple_ocr_result(json_result: &str) -> (String, String, Option<f64>) {- let parsed_result: serde_json::Value = serde_json::from_str(json_result).unwrap_or_else(|e| {- error!("Failed to parse JSON output: {}", e);- serde_json::json!({- "ocrResult": "",- "textElements": [],- "overallConfidence": 0.0- })- });-- let text = parsed_result["ocrResult"]- .as_str()- .unwrap_or("")- .to_string();- let text_elements = parsed_result["textElements"]- .as_array()- .unwrap_or(&vec![])- .clone();- let overall_confidence = parsed_result["overallConfidence"].as_f64();-- let json_output: Vec<serde_json::Value> = text_elements- .iter()- .map(|element| {- serde_json::json!({- "level": "0",- "page_num": "0",- "block_num": "0",- "par_num": "0",- "line_num": "0",- "word_num": "0",- "left": element["boundingBox"]["x"].as_f64().unwrap_or(0.0).to_string(),- "top": element["boundingBox"]["y"].as_f64().unwrap_or(0.0).to_string(),- "width": element["boundingBox"]["width"].as_f64().unwrap_or(0.0).to_string(),- "height": element["boundingBox"]["height"].as_f64().unwrap_or(0.0).to_string(),- "conf": element["confidence"].as_f64().unwrap_or(0.0).to_string(),- "text": element["text"].as_str().unwrap_or("").to_string()- })- })- .collect();-- let json_output_string = serde_json::to_string(&json_output).unwrap_or_else(|e| {- error!("Failed to serialize JSON output: {}", e);- "[]".to_string()- });-- (text, json_output_string, overall_confidence)-}+ let handler = ImageRequestHandler::with_cv_pixel_buf(&pixel_buf, None).unwrap();+ let mut request = RecognizeTextRequest::new();+ // Recognize all languages+ request.set_recognition_langs(&languages);+ request.set_uses_lang_correction(false);+ let requests = ns::Array::<vn::Request>::from_slice(&[&request]);+ let result = handler.perform(&requests);-#[cfg(target_os = "macos")]-fn get_apple_languages(languages: Vec<screenpipe_core::Language>) -> Vec<String> {- use screenpipe_core::Language;-- let mut langs: Vec<String> = Vec::new();- for lang in languages {- let lang_str = match lang {- Language::English => "en-US",- Language::Spanish => "es-ES",- Language::French => "fr-FR",- Language::German => "de-DE",- Language::Italian => "it-IT",- Language::Portuguese => "pt-BR",- Language::Russian => "ru-RU",- Language::Chinese => "zh-Hans",- Language::Korean => "ko-KR",- Language::Japanese => "ja-JP",- Language::Ukrainian => "uk-UA",- Language::Thai => "th-TH",- Language::Arabic => "ar-SA",- _ => continue,- };- langs.push(lang_str.to_string());+ if result.is_err() {+ drop(pixel_buf);+ return default_ocr_result;}- langs++ if let Some(results) = request.results() {+ if !results.is_empty() {+ let mut ocr_results_vec: Vec<serde_json::Value> = Vec::new();+ let mut ocr_text: String = String::new();+ results.iter().for_each(|result| {+ let observation_result = result.top_candidates(1).get(0).unwrap();+ let text = observation_result.string();+ let confidence = observation_result.confidence() as f64;+ let bbox = observation_result+ .bounding_box_for_range(ns::Range::new(0, text.len()))+ .unwrap()+ .bounding_box();+ let x = bbox.origin.x;+ let y = bbox.origin.y;+ let height = bbox.size.height;+ let width = bbox.size.width;++ ocr_results_vec.push(serde_json::json!({+ "level": "0",+ "page_num": "0",+ "block_num": "0",+ "par_num": "0",+ "line_num": "0",+ "word_num": "0",+ "left": x.to_string(),+ "top": y.to_string(),+ "width": width.to_string(),+ "height": height.to_string(),+ "conf": confidence.to_string(),+ "text": text.to_string(),+ }));++ overall_confidence += confidence;+ ocr_text.push_str(text.to_string().as_str());+ });++ let json_output_string = serde_json::to_string(&ocr_results_vec).unwrap_or_else(|e| {+ error!("Failed to serialize JSON output: {}", e);+ "[]".to_string()+ });++ drop(pixel_buf);++ return (ocr_text, json_output_string, Some(overall_confidence));+ }+ }++ drop(pixel_buf);+ return default_ocr_result;}diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex b0c46743a..154dd8428 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -1,6 +1,4 @@#[cfg(target_os = "macos")]-use crate::apple::parse_apple_ocr_result;-#[cfg(target_os = "macos")]use crate::apple::perform_ocr_apple;use crate::capture_screenshot_by_window::CapturedWindow;use crate::capture_screenshot_by_window::WindowFilters;@@ -11,6 +9,7 @@ use crate::tesseract::perform_ocr_tesseract;use crate::utils::OcrEngine;use crate::utils::{capture_screenshot, compare_with_previous_image};use anyhow::{anyhow, Result};+use cidre::ns;use image::DynamicImage;use log::{debug, error};use screenpipe_core::Language;@@ -205,6 +204,14 @@ pub async fn process_ocr_task(let mut total_confidence = 0.0;let mut window_count = 0;+ #[cfg(target_os = "macos")]+ use ns;+ let apple_languages = get_apple_languages(languages.clone());+ let mut languages_slice = ns::ArrayMut::<ns::String>::with_capacity(apple_languages.len());+ apple_languages.iter().for_each(|language| {+ languages_slice.push(&ns::String::with_str(language.as_str()));+ });+for captured_window in window_images {let (window_text, window_json_output, confidence) = match ocr_engine {OcrEngine::Unstructured => perform_ocr_cloud(&captured_window.image, languages.clone())@@ -218,10 +225,7 @@ pub async fn process_ocr_task(.await.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,#[cfg(target_os = "macos")]- OcrEngine::AppleNative => parse_apple_ocr_result(&perform_ocr_apple(- &captured_window.image,- languages.clone(),- )),+ OcrEngine::AppleNative => perform_ocr_apple(&captured_window.image, &languages_slice),_ => {return Err(std::io::Error::new(std::io::ErrorKind::Other,@@ -296,4 +300,30 @@ pub fn trigger_screen_capture_permission() -> Result<()> {Ok(())}-\ No newline at end of file++#[cfg(target_os = "macos")]+fn get_apple_languages(languages: Vec<screenpipe_core::Language>) -> Vec<String> {+ use screenpipe_core::Language;++ let mut langs: Vec<String> = Vec::new();+ for lang in languages {+ let lang_str = match lang {+ Language::English => "en-US",+ Language::Spanish => "es-ES",+ Language::French => "fr-FR",+ Language::German => "de-DE",+ Language::Italian => "it-IT",+ Language::Portuguese => "pt-BR",+ Language::Russian => "ru-RU",+ Language::Chinese => "zh-Hans",+ Language::Korean => "ko-KR",+ Language::Japanese => "ja-JP",+ Language::Ukrainian => "uk-UA",+ Language::Thai => "th-TH",+ Language::Arabic => "ar-SA",+ _ => continue,+ };+ langs.push(lang_str.to_string());+ }+ langs+}diff --git a/screenpipe-vision/src/lib.rs b/screenpipe-vision/src/lib.rsindex d277160f1..7d26c1566 100644--- a/screenpipe-vision/src/lib.rs+++ b/screenpipe-vision/src/lib.rs@@ -8,7 +8,7 @@ pub mod monitor;pub mod tesseract;pub mod utils;#[cfg(target_os = "macos")]-pub use apple::{parse_apple_ocr_result, perform_ocr_apple};+pub use apple::perform_ocr_apple;pub use core::{continuous_capture, process_ocr_task, CaptureResult};pub use utils::OcrEngine;pub mod capture_screenshot_by_window;