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
refactor: separate concerns cleanly, and bench every OCR engine
Louis Beaumont410326db180e
diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.ymlindex f21ef4ac6..cf8394faf 100644--- a/.github/workflows/benchmark.yml+++ b/.github/workflows/benchmark.yml@@ -8,8 +8,8 @@ env:CARGO_TERM_COLOR: alwaysjobs:- benchmark:- name: Run Rust benchmark+ benchmark_pcm:+ name: Run PCM benchmarkruns-on: ubuntu-lateststeps:- uses: actions/checkout@v3@@ -20,37 +20,27 @@ jobs:sudo apt-get updatesudo apt-get install -y libavformat-dev libavfilter-dev libavdevice-dev ffmpeg libasound2-dev- - name: Run benchmarks+ - name: Run PCM benchmarksrun: |- cargo bench --bench pcm_decode_benchmark -- --output-format bencher | tee output.txt+ cargo bench --bench pcm_decode_benchmark -- --output-format bencher | tee pcm_output.txt- - name: Download previous benchmark data- uses: actions/cache@v4- with:- path: ./cache- key: ${{ runner.os }}-benchmark-- - name: Store benchmark result+ - name: Store PCM benchmark resultuses: benchmark-action/github-action-benchmark@v1with:- name: Rust Benchmark+ name: PCM Benchmarktool: "cargo"- output-file-path: output.txt- external-data-json-path: ./cache/benchmark-data.json- fail-on-alert: true- # GitHub API token to make a commit comment+ output-file-path: pcm_output.txt+ external-data-json-path: ./cache/pcm-benchmark-data.jsongithub-token: ${{ secrets.GITHUB_TOKEN }}- # Enable alert commit comment- comment-on-alert: true- # Enable Job Summary for PRs- summary-always: true- alert-comment-cc-users: "@louis030195"+ auto-push: false+ comment-always: false+ save-data-file: true- - name: Upload benchmark results+ - name: Upload PCM benchmark artifactuses: actions/upload-artifact@v3with:- name: benchmark-results- path: output.txt+ name: pcm-benchmark-data+ path: ./cache/pcm-benchmark-data.jsonapple_ocr_benchmark:name: Run OCR benchmark@@ -69,27 +59,113 @@ jobs:run: |cargo bench --bench ocr_benchmark -- --output-format bencher | tee ocr_output.txt- - name: Download previous OCR benchmark data- uses: actions/cache@v4- with:- path: ./ocr_cache- key: ${{ runner.os }}-ocr-benchmark-- name: Store OCR benchmark resultuses: benchmark-action/github-action-benchmark@v1with:name: OCR Benchmarktool: "cargo"output-file-path: ocr_output.txt- external-data-json-path: ./ocr_cache/ocr-benchmark-data.json- fail-on-alert: true+ external-data-json-path: ./cache/ocr-benchmark-data.jsongithub-token: ${{ secrets.GITHUB_TOKEN }}- comment-on-alert: true- summary-always: true- alert-comment-cc-users: "@louis030195"+ auto-push: false+ comment-always: false+ save-data-file: true++ - name: Upload OCR benchmark artifact+ uses: actions/upload-artifact@v3+ with:+ name: ocr-benchmark-data+ path: ./cache/ocr-benchmark-data.json++ tesseract_ocr_benchmark:+ name: Run Tesseract OCR benchmark+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v3+ - uses: dtolnay/rust-toolchain@stable++ - name: Install dependencies+ run: |+ sudo apt-get update+ sudo apt-get install -y libleptonica-dev libtesseract-dev tesseract-ocr-eng++ - name: Run Tesseract OCR benchmarks+ run: |+ cargo bench --bench ocr_benchmark -- --output-format bencher | tee tesseract_ocr_output.txt++ - name: Store Tesseract OCR benchmark result+ uses: benchmark-action/github-action-benchmark@v1+ with:+ name: Tesseract OCR Benchmark+ tool: "cargo"+ output-file-path: tesseract_ocr_output.txt+ external-data-json-path: ./cache/tesseract-ocr-benchmark-data.json+ github-token: ${{ secrets.GITHUB_TOKEN }}+ auto-push: false+ comment-always: false+ save-data-file: true- - name: Upload OCR benchmark results+ - name: Upload Tesseract OCR benchmark artifactuses: actions/upload-artifact@v3with:- name: ocr-benchmark-results- path: ocr_output.txt+ name: tesseract-ocr-benchmark-data+ path: ./cache/tesseract-ocr-benchmark-data.json++ windows_ocr_benchmark:+ name: Run Windows OCR benchmark+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v3+ - uses: dtolnay/rust-toolchain@stable++ - name: Run Windows OCR benchmarks+ run: |+ cargo bench --bench ocr_benchmark -- --output-format bencher | Tee-Object -FilePath windows_ocr_output.txt++ - name: Store Windows OCR benchmark result+ uses: benchmark-action/github-action-benchmark@v1+ with:+ name: Windows OCR Benchmark+ tool: "cargo"+ output-file-path: windows_ocr_output.txt+ external-data-json-path: ./cache/windows-ocr-benchmark-data.json+ github-token: ${{ secrets.GITHUB_TOKEN }}+ auto-push: false+ comment-always: false+ save-data-file: true++ - name: Upload Windows OCR benchmark artifact+ uses: actions/upload-artifact@v3+ with:+ name: windows-ocr-benchmark-data+ path: ./cache/windows-ocr-benchmark-data.json++ analyze_benchmarks:+ needs:+ [+ benchmark_pcm,+ apple_ocr_benchmark,+ tesseract_ocr_benchmark,+ windows_ocr_benchmark,+ ]+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v3++ - name: Download benchmark data+ uses: actions/download-artifact@v3+ with:+ path: ./cache++ - name: Analyze benchmarks+ uses: benchmark-action/github-action-benchmark@v1+ with:+ tool: "cargo"+ output-file-path: ./cache/pcm-benchmark-data/pcm-benchmark-data.json,./cache/ocr-benchmark-data/ocr-benchmark-data.json,./cache/tesseract-ocr-benchmark-data/tesseract-ocr-benchmark-data.json,./cache/windows-ocr-benchmark-data/windows-ocr-benchmark-data.json+ github-token: ${{ secrets.GITHUB_TOKEN }}+ auto-push: true+ comment-on-alert: true+ fail-on-alert: true+ alert-threshold: "200%"+ comment-always: true+ alert-comment-cc-users: "@louis030195"diff --git a/screenpipe-vision/benches/ocr_benchmark.rs b/screenpipe-vision/benches/ocr_benchmark.rsindex 4530a8c1d..93ef8a523 100644--- a/screenpipe-vision/benches/ocr_benchmark.rs+++ b/screenpipe-vision/benches/ocr_benchmark.rs@@ -2,9 +2,14 @@ use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criteriuse std::path::PathBuf;use std::time::Duration;+use screenpipe_vision::perform_ocr_tesseract;+#[cfg(target_os = "macos")]use screenpipe_vision::perform_ocr_apple;+#[cfg(target_os = "windows")]+use screenpipe_vision::perform_ocr_windows;+const EXPECTED_KEYWORDS: &[&str] = &["ocr_handles","Vec",@@ -52,8 +57,8 @@ fn load_test_image() -> image::DynamicImage {fn bench_apple_vision_ocr(c: &mut Criterion) {let image = load_test_image();let mut group = c.benchmark_group("Apple Vision OCR");- group.sample_size(10); // Reduce sample size to address warning- group.measurement_time(Duration::from_secs(10)); // Increase measurement time+ group.sample_size(10);+ group.measurement_time(Duration::from_secs(10));group.bench_function(BenchmarkId::new("Performance", ""), |b| {b.iter(|| {@@ -83,16 +88,16 @@ fn test_apple_vision_ocr_accuracy() {matched_keywords,EXPECTED_KEYWORDS.len());- assert!(accuracy > 0.3, "Accuracy below threshold"); // Adjusted threshold based on observed results+ assert!(accuracy > 0.3, "Accuracy below threshold");}-// Combined performance and accuracy test+// Combined performance and accuracy test for Apple Vision OCR#[cfg(target_os = "macos")]fn bench_apple_vision_ocr_with_accuracy(c: &mut Criterion) {let image = load_test_image();let mut group = c.benchmark_group("Apple Vision OCR with Accuracy");- group.sample_size(10); // Reduce sample size to address warning- group.measurement_time(Duration::from_secs(10)); // Increase measurement time+ group.sample_size(10);+ group.measurement_time(Duration::from_secs(10));group.bench_function(BenchmarkId::new("Performance and Accuracy", ""), |b| {b.iter_custom(|iters| {@@ -120,17 +125,112 @@ fn bench_apple_vision_ocr_with_accuracy(c: &mut Criterion) {group.finish();}+// Tesseract OCR benchmark+fn bench_tesseract_ocr(c: &mut Criterion) {+ let image = load_test_image();+ let mut group = c.benchmark_group("Tesseract OCR");+ group.sample_size(10);+ group.measurement_time(Duration::from_secs(10));++ group.bench_function(BenchmarkId::new("Performance", ""), |b| {+ b.iter(|| {+ let (result, _) = perform_ocr_tesseract(black_box(&image));+ assert!(!result.is_empty(), "OCR failed");+ })+ });++ group.finish();+}++// Tesseract OCR accuracy test+fn test_tesseract_ocr_accuracy() {+ let image = load_test_image();+ let (result, _) = perform_ocr_tesseract(&image);++ let matched_keywords = EXPECTED_KEYWORDS+ .iter()+ .filter(|&&keyword| result.contains(keyword))+ .count();+ let accuracy = matched_keywords as f32 / EXPECTED_KEYWORDS.len() as f32;++ println!("Tesseract OCR Accuracy: {:.2}", accuracy);+ println!(+ "Matched keywords: {}/{}",+ matched_keywords,+ EXPECTED_KEYWORDS.len()+ );+ assert!(accuracy > 0.3, "Accuracy below threshold");+}++// Windows OCR benchmark (only on Windows)+#[cfg(target_os = "windows")]+fn bench_windows_ocr(c: &mut Criterion) {+ let image = load_test_image();+ let mut group = c.benchmark_group("Windows OCR");+ group.sample_size(10);+ group.measurement_time(Duration::from_secs(10));++ group.bench_function(BenchmarkId::new("Performance", ""), |b| {+ b.to_async(tokio::runtime::Runtime::new().unwrap())+ .iter(|| async {+ let (result, _) = perform_ocr_windows(black_box(&image)).await;+ assert!(!result.is_empty(), "OCR failed");+ });+ });++ group.finish();+}++// Windows OCR accuracy test (only on Windows)+#[cfg(target_os = "windows")]+async fn test_windows_ocr_accuracy() {+ let image = load_test_image();+ let (result, _) = perform_ocr_windows(&image).await;++ let matched_keywords = EXPECTED_KEYWORDS+ .iter()+ .filter(|&&keyword| result.contains(keyword))+ .count();+ let accuracy = matched_keywords as f32 / EXPECTED_KEYWORDS.len() as f32;++ println!("Windows OCR Accuracy: {:.2}", accuracy);+ println!(+ "Matched keywords: {}/{}",+ matched_keywords,+ EXPECTED_KEYWORDS.len()+ );+ assert!(accuracy > 0.3, "Accuracy below threshold");+}+#[cfg(target_os = "macos")]criterion_group!(benches,bench_apple_vision_ocr,- bench_apple_vision_ocr_with_accuracy+ bench_apple_vision_ocr_with_accuracy,+ bench_tesseract_ocr);-#[cfg(target_os = "macos")]++#[cfg(target_os = "windows")]+criterion_group!(benches, bench_tesseract_ocr, bench_windows_ocr);++#[cfg(not(any(target_os = "macos", target_os = "windows")))]+criterion_group!(benches, bench_tesseract_ocr);+criterion_main!(benches);#[cfg(target_os = "macos")]#[test]-fn run_accuracy_test() {+fn run_apple_accuracy_test() {test_apple_vision_ocr_accuracy();}++#[test]+fn run_tesseract_accuracy_test() {+ test_tesseract_ocr_accuracy();+}++#[cfg(target_os = "windows")]+#[tokio::test]+async fn run_windows_accuracy_test() {+ test_windows_ocr_accuracy().await;+}diff --git a/screenpipe-vision/src/apple.rs b/screenpipe-vision/src/apple.rsindex 540dc14d0..3838e507e 100644--- a/screenpipe-vision/src/apple.rs+++ b/screenpipe-vision/src/apple.rs@@ -1,4 +1,5 @@use image::DynamicImage;+use log::error;use std::ffi::CStr;use std::os::raw::{c_char, c_uchar};@@ -30,3 +31,51 @@ pub fn perform_ocr_apple(image: &DynamicImage) -> String {result}}++#[cfg(target_os = "macos")]+pub fn parse_apple_ocr_result(json_result: &str) -> (String, String) {+ 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 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)+}diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex ec71d677b..c21c0d6c2 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -9,16 +9,16 @@ use std::{};use tokio::sync::mpsc::Sender;+#[cfg(target_os = "macos")]+use crate::apple::parse_apple_ocr_result;#[cfg(target_os = "macos")]use crate::apple::perform_ocr_apple;-use crate::monitor::get_monitor_by_id;#[cfg(target_os = "windows")]-use crate::utils::perform_ocr_windows;+use crate::microsoft::perform_ocr_windows;+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, perform_ocr_tesseract, save_text_files,-};-+use crate::utils::{capture_screenshot, compare_with_previous_image, save_text_files};#[derive(Clone)]pub struct CaptureResult {pub image: Arc<DynamicImage>,@@ -267,51 +267,3 @@ fn parse_json_output(json_output: &str) -> Vec<HashMap<String, String>> {parsed_output}--#[cfg(target_os = "macos")]-fn parse_apple_ocr_result(json_result: &str) -> (String, String) {- 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 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)-}diff --git a/screenpipe-vision/src/lib.rs b/screenpipe-vision/src/lib.rsindex 74bf046b8..92166859e 100644--- a/screenpipe-vision/src/lib.rs+++ b/screenpipe-vision/src/lib.rs@@ -1,10 +1,16 @@#[cfg(target_os = "macos")]pub mod apple;pub mod core;+#[cfg(target_os = "windows")]+pub mod microsoft;pub mod monitor;+pub mod tesseract;pub mod utils;#[cfg(target_os = "macos")]-pub use apple::perform_ocr_apple;+pub use apple::{parse_apple_ocr_result, perform_ocr_apple};pub use core::{continuous_capture, process_ocr_task, CaptureResult};-pub use utils::{perform_ocr_tesseract, OcrEngine};-pub mod capture_screenshot_by_window;\ No newline at end of file+pub use utils::OcrEngine;+pub mod capture_screenshot_by_window;+#[cfg(target_os = "windows")]+pub use microsoft::perform_ocr_windows;+pub use tesseract::perform_ocr_tesseract;diff --git a/screenpipe-vision/src/microsoft.rs b/screenpipe-vision/src/microsoft.rsnew file mode 100644index 000000000..1749a3bed--- /dev/null+++ b/screenpipe-vision/src/microsoft.rs@@ -0,0 +1,41 @@+#[cfg(target_os = "windows")]+pub async fn perform_ocr_windows(image: &DynamicImage) -> (String, String) {+ use std::io::Cursor;+ use windows::{+ Graphics::Imaging::BitmapDecoder,+ Media::Ocr::OcrEngine as WindowsOcrEngine,+ Storage::Streams::{DataWriter, InMemoryRandomAccessStream},+ };++ let mut buffer = Vec::new();+ image+ .write_to(&mut Cursor::new(&mut buffer), image::ImageFormat::Png)+ .unwrap();++ let stream = InMemoryRandomAccessStream::new().unwrap();+ let writer = DataWriter::CreateDataWriter(&stream).unwrap();+ writer.WriteBytes(&buffer).unwrap();+ writer.StoreAsync().unwrap().get().unwrap();+ writer.FlushAsync().unwrap().get().unwrap();+ stream.Seek(0).unwrap();++ let decoder = BitmapDecoder::CreateWithIdAsync(BitmapDecoder::PngDecoderId().unwrap(), &stream)+ .unwrap()+ .get()+ .unwrap();++ let bitmap = decoder.GetSoftwareBitmapAsync().unwrap().get().unwrap();++ let engine = WindowsOcrEngine::TryCreateFromUserProfileLanguages().unwrap();+ let result = engine.RecognizeAsync(&bitmap).unwrap().get().unwrap();++ let text = result.Text().unwrap().to_string();++ let json_output = serde_json::json!([{+ "text": text,+ "confidence": "n/a" // Windows OCR doesn't provide confidence scores, so we use a default high value+ }])+ .to_string();++ (text, json_output)+}diff --git a/screenpipe-vision/src/tesseract.rs b/screenpipe-vision/src/tesseract.rsnew file mode 100644index 000000000..f20abe8cd--- /dev/null+++ b/screenpipe-vision/src/tesseract.rs@@ -0,0 +1,91 @@+use std::collections::HashMap;++use image::DynamicImage;+use rusty_tesseract::{Args, DataOutput, Image};++pub fn perform_ocr_tesseract(image: &DynamicImage) -> (String, String) {+ let args = Args {+ lang: "eng".to_string(),+ config_variables: HashMap::from([("tessedit_create_tsv".into(), "1".into())]),+ dpi: Some(600), // 150 is a balanced option, 600 seems faster surprisingly, the bigger the number the more granualar result+ psm: Some(1), // PSM 1: Automatic page segmentation with OSD. PSM 3: Automatic page segmentation with OSD+ oem: Some(1), //1: Neural nets LSTM engine only, 3: Default, based on what is available. (Default)+ };++ let ocr_image = Image::from_dynamic_image(image).unwrap();++ // Extract data output+ let data_output = rusty_tesseract::image_to_data(&ocr_image, &args).unwrap();+ // let tsv_output = data_output_to_tsv(&data_output);++ // Extract text from data output+ let text = data_output_to_text(&data_output);+ let json_output = data_output_to_json(&data_output);++ (text, json_output)+}++fn data_output_to_text(data_output: &DataOutput) -> String {+ let mut text = String::new();+ for record in &data_output.data {+ if !record.text.is_empty() {+ if !text.is_empty() {+ text.push(' ');+ }+ text.push_str(&record.text);+ }+ }+ text+}++fn data_output_to_json(data_output: &DataOutput) -> String {+ let mut lines: Vec<HashMap<String, String>> = Vec::new();+ let mut current_line = String::new();+ let mut current_conf = 0.0;+ let mut word_count = 0;+ let mut last_word_num = 0;++ for record in &data_output.data {+ if record.word_num == 0 {+ if !current_line.is_empty() {+ let avg_conf = current_conf / word_count as f32;+ let mut line_data = HashMap::new();+ line_data.insert("text".to_string(), current_line.clone());+ line_data.insert("confidence".to_string(), format!("{:.2}", avg_conf));+ line_data.insert(+ "line_position".to_string(),+ format!(+ "level{}page_num{}block_num{}par_num{}line_num{}",+ record.level,+ record.page_num,+ record.block_num,+ record.par_num,+ record.line_num+ ),+ );+ lines.push(line_data);+ current_line.clear();+ current_conf = 0.0;+ word_count = 0;+ }+ }+ if record.word_num > last_word_num {+ if !current_line.is_empty() {+ current_line.push(' ');+ }+ current_line.push_str(&record.text);+ current_conf += record.conf;+ word_count += 1;+ }+ last_word_num = record.word_num;+ }+ if !current_line.is_empty() {+ let avg_conf = current_conf / word_count as f32;+ let mut line_data = HashMap::new();+ line_data.insert("text".to_string(), current_line);+ line_data.insert("confidence".to_string(), format!("{:.2}", avg_conf));+ lines.push(line_data);+ }++ serde_json::to_string_pretty(&lines).unwrap()+}diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rsindex ad2e9d528..fdae8281f 100644--- a/screenpipe-vision/src/utils.rs+++ b/screenpipe-vision/src/utils.rs@@ -3,8 +3,6 @@ use crate::core::MaxAverageFrame;use image::DynamicImage;use image_compare::{Algorithm, Metric, Similarity};use log::{debug, error};-use rusty_tesseract::{Args, DataOutput, Image};-use serde_json;use std::collections::HashMap;use std::fs::{self, File};use std::hash::{DefaultHasher, Hash, Hasher};@@ -52,93 +50,6 @@ pub fn compare_images_ssim(image1: &DynamicImage, image2: &DynamicImage) -> f64result.score}-pub fn perform_ocr_tesseract(image: &DynamicImage) -> (String, String) {- let args = Args {- lang: "eng".to_string(),- config_variables: HashMap::from([("tessedit_create_tsv".into(), "1".into())]),- dpi: Some(600), // 150 is a balanced option, 600 seems faster surprisingly, the bigger the number the more granualar result- psm: Some(1), // PSM 1: Automatic page segmentation with OSD. PSM 3: Automatic page segmentation with OSD- oem: Some(1), //1: Neural nets LSTM engine only, 3: Default, based on what is available. (Default)- };-- let ocr_image = Image::from_dynamic_image(image).unwrap();-- // Extract data output- let data_output = rusty_tesseract::image_to_data(&ocr_image, &args).unwrap();- // let tsv_output = data_output_to_tsv(&data_output);-- // Extract text from data output- let text = data_output_to_text(&data_output);- let json_output = data_output_to_json(&data_output);-- (text, json_output)-}--fn data_output_to_text(data_output: &DataOutput) -> String {- let mut text = String::new();- for record in &data_output.data {- if !record.text.is_empty() {- if !text.is_empty() {- text.push(' ');- }- text.push_str(&record.text);- }- }- text-}--fn data_output_to_json(data_output: &DataOutput) -> String {- let mut lines: Vec<HashMap<String, String>> = Vec::new();- let mut current_line = String::new();- let mut current_conf = 0.0;- let mut word_count = 0;- let mut last_word_num = 0;-- for record in &data_output.data {- if record.word_num == 0 {- if !current_line.is_empty() {- let avg_conf = current_conf / word_count as f32;- let mut line_data = HashMap::new();- line_data.insert("text".to_string(), current_line.clone());- line_data.insert("confidence".to_string(), format!("{:.2}", avg_conf));- line_data.insert(- "line_position".to_string(),- format!(- "level{}page_num{}block_num{}par_num{}line_num{}",- record.level,- record.page_num,- record.block_num,- record.par_num,- record.line_num- ),- );- lines.push(line_data);- current_line.clear();- current_conf = 0.0;- word_count = 0;- }- }- if record.word_num > last_word_num {- if !current_line.is_empty() {- current_line.push(' ');- }- current_line.push_str(&record.text);- current_conf += record.conf;- word_count += 1;- }- last_word_num = record.word_num;- }- if !current_line.is_empty() {- let avg_conf = current_conf / word_count as f32;- let mut line_data = HashMap::new();- line_data.insert("text".to_string(), current_line);- line_data.insert("confidence".to_string(), format!("{:.2}", avg_conf));- lines.push(line_data);- }-- serde_json::to_string_pretty(&lines).unwrap()-}-pub async fn capture_screenshot(monitor: Arc<Monitor>,) -> Result<@@ -256,45 +167,3 @@ pub async fn save_text_files(}}}--#[cfg(target_os = "windows")]-pub async fn perform_ocr_windows(image: &DynamicImage) -> (String, String) {- use std::io::Cursor;- use windows::{- Graphics::Imaging::BitmapDecoder,- Media::Ocr::OcrEngine as WindowsOcrEngine,- Storage::Streams::{DataWriter, InMemoryRandomAccessStream},- };-- let mut buffer = Vec::new();- image- .write_to(&mut Cursor::new(&mut buffer), image::ImageFormat::Png)- .unwrap();-- let stream = InMemoryRandomAccessStream::new().unwrap();- let writer = DataWriter::CreateDataWriter(&stream).unwrap();- writer.WriteBytes(&buffer).unwrap();- writer.StoreAsync().unwrap().get().unwrap();- writer.FlushAsync().unwrap().get().unwrap();- stream.Seek(0).unwrap();-- let decoder = BitmapDecoder::CreateWithIdAsync(BitmapDecoder::PngDecoderId().unwrap(), &stream)- .unwrap()- .get()- .unwrap();-- let bitmap = decoder.GetSoftwareBitmapAsync().unwrap().get().unwrap();-- let engine = WindowsOcrEngine::TryCreateFromUserProfileLanguages().unwrap();- let result = engine.RecognizeAsync(&bitmap).unwrap().get().unwrap();-- let text = result.Text().unwrap().to_string();-- let json_output = serde_json::json!([{- "text": text,- "confidence": "n/a" // Windows OCR doesn't provide confidence scores, so we use a default high value- }])- .to_string();-- (text, json_output)-}