Skip to content

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

overall confidence added in the response

matthew-heartfuld6c8ba00f75d
diff --git a/screenpipe-integrations/src/unstructured_ocr.rs b/screenpipe-integrations/src/unstructured_ocr.rs
index 055637469..1e63bfb62 100644
--- a/screenpipe-integrations/src/unstructured_ocr.rs
+++ b/screenpipe-integrations/src/unstructured_ocr.rs
@@ -11,7 +11,7 @@ use serde_json::Value;
use tempfile::NamedTempFile;
use anyhow::{Result, anyhow};
-pub async fn perform_ocr_cloud(image: &Arc<DynamicImage>) -> Result<(String, String), String> {
+pub async fn perform_ocr_cloud(image: &Arc<DynamicImage>) -> Result<(String, String, Option<f64>), String> {
let api_key = "ZUxfTRkf6lRgHZDXPHlFaSoOKAEbwV".to_string();
let api_url = "https://api.unstructuredapp.io/general/v0/general".to_string();
@@ -64,7 +64,22 @@ pub async fn perform_ocr_cloud(image: &Arc<DynamicImage>) -> Result<(String, Str
.collect::<Vec<&str>>()
.join(" ");
- Ok((text, json_output))
+ let overall_confidence = calculate_overall_confidence(&parsed_response);
+
+ Ok((text, json_output, Some(overall_confidence)))
+}
+
+fn calculate_overall_confidence(parsed_response: &Vec<HashMap<String, serde_json::Value>>) -> f64 {
+ let confidence_sum: f64 = parsed_response
+ .iter()
+ .filter_map(|item| item.get("confidence").and_then(|v| v.as_f64()))
+ .sum();
+ let count = parsed_response.len();
+ if count > 0 {
+ confidence_sum / count as f64
+ } else {
+ 0.0
+ }
}
pub fn unstructured_chunking(text: &str) -> Result<Vec<String>> {
diff --git a/screenpipe-vision/lib/libscreenpipe.dylib b/screenpipe-vision/lib/libscreenpipe.dylib
index a41e3c86b..92343a892 100755
Binary files a/screenpipe-vision/lib/libscreenpipe.dylib and b/screenpipe-vision/lib/libscreenpipe.dylib differ
diff --git a/screenpipe-vision/lib/libscreenpipe_arm64.dylib b/screenpipe-vision/lib/libscreenpipe_arm64.dylib
index 8f318eaca..40861250b 100755
Binary files a/screenpipe-vision/lib/libscreenpipe_arm64.dylib and b/screenpipe-vision/lib/libscreenpipe_arm64.dylib differ
diff --git a/screenpipe-vision/lib/libscreenpipe_x86_64.dylib b/screenpipe-vision/lib/libscreenpipe_x86_64.dylib
index 4fd95e313..65b30a782 100755
Binary files a/screenpipe-vision/lib/libscreenpipe_x86_64.dylib and b/screenpipe-vision/lib/libscreenpipe_x86_64.dylib differ
diff --git a/screenpipe-vision/src/apple.rs b/screenpipe-vision/src/apple.rs
index 3838e507e..679e0dee8 100644
--- a/screenpipe-vision/src/apple.rs
+++ b/screenpipe-vision/src/apple.rs
@@ -33,7 +33,7 @@ pub fn perform_ocr_apple(image: &DynamicImage) -> String {
}
#[cfg(target_os = "macos")]
-pub fn parse_apple_ocr_result(json_result: &str) -> (String, String) {
+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!({
@@ -51,6 +51,8 @@ pub fn parse_apple_ocr_result(json_result: &str) -> (String, String) {
.as_array()
.unwrap_or(&vec![])
.clone();
+ let overall_confidence = parsed_result["overallConfidence"]
+ .as_f64();
let json_output: Vec<serde_json::Value> = text_elements
.iter()
@@ -77,5 +79,5 @@ pub fn parse_apple_ocr_result(json_result: &str) -> (String, String) {
"[]".to_string()
});
- (text, json_output_string)
-}
+ (text, json_output_string, overall_confidence)
+}
\ No newline at end of file
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index c21c0d6c2..f79c9099a 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -35,6 +35,7 @@ pub struct WindowOcrResult {
pub text: String,
pub text_json: Vec<HashMap<String, String>>,
pub focused: bool,
+ pub confidence: f64,
}
pub struct OcrTaskData {
@@ -183,7 +184,6 @@ pub async fn process_ocr_task(
ocr_engine: Arc<OcrEngine>,
) -> Result<(), std::io::Error> {
let start_time = Instant::now();
-
debug!(
"Performing OCR for frame number since beginning of program {}",
frame_number
@@ -191,9 +191,12 @@ pub async fn process_ocr_task(
// Perform OCR on window images
let 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) = match &*ocr_engine {
+ let (window_text, window_json_output, confidence) = match &*ocr_engine {
OcrEngine::Unstructured => perform_ocr_cloud(&window_image_arc)
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,
@@ -210,6 +213,11 @@ pub async fn process_ocr_task(
}
};
+ if let Some(conf) = confidence {
+ total_confidence += conf;
+ window_count += 1;
+ }
+
window_ocr_results.push(WindowOcrResult {
window_name,
app_name: window_app_name,
@@ -217,6 +225,7 @@ pub async fn process_ocr_task(
text: window_text,
text_json: parse_json_output(&window_json_output),
focused,
+ confidence: confidence.unwrap_or(0.0),
});
}
@@ -249,11 +258,13 @@ pub async fn process_ocr_task(
}
let duration = start_time.elapsed();
+ let avg_confidence = if window_count > 0 { total_confidence / window_count as f64 } else { 0.0 };
debug!(
- "OCR task processed frame {} with {} windows in {:?}",
+ "OCR task processed frame {} with {} windows in {:?}, average confidence: {:.2}",
frame_number,
window_ocr_results.len(),
- duration
+ duration,
+ avg_confidence
);
Ok(())
}
@@ -266,4 +277,4 @@ fn parse_json_output(json_output: &str) -> Vec<HashMap<String, String>> {
});
parsed_output
-}
+}
\ No newline at end of file
diff --git a/screenpipe-vision/src/microsoft.rs b/screenpipe-vision/src/microsoft.rs
index 38e3b77f8..c6c12e780 100644
--- a/screenpipe-vision/src/microsoft.rs
+++ b/screenpipe-vision/src/microsoft.rs
@@ -1,6 +1,6 @@
use image::DynamicImage;
#[cfg(target_os = "windows")]
-pub async fn perform_ocr_windows(image: &DynamicImage) -> (String, String) {
+pub async fn perform_ocr_windows(image: &DynamicImage) -> (String, String, Option<f64>) {
use std::io::Cursor;
use windows::{
Graphics::Imaging::BitmapDecoder,
@@ -34,9 +34,9 @@ pub async fn perform_ocr_windows(image: &DynamicImage) -> (String, 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
+ "confidence": null // Windows OCR doesn't provide confidence scores
}])
.to_string();
- (text, json_output)
-}
+ (text, json_output, None)
+}
\ No newline at end of file
diff --git a/screenpipe-vision/src/ocr.swift b/screenpipe-vision/src/ocr.swift
index 516d91287..63670e151 100644
--- a/screenpipe-vision/src/ocr.swift
+++ b/screenpipe-vision/src/ocr.swift
@@ -32,14 +32,11 @@ public func performOCR(imageData: UnsafePointer<UInt8>, length: Int, width: Int,
let ciImage = CIImage(cgImage: cgImage)
let context = CIContext(options: nil)
- // Apply preprocessing filters
- let processed =
- ciImage
- .applyingFilter(
- "CIColorControls", parameters: [kCIInputSaturationKey: 0, kCIInputContrastKey: 1.1]
- )
- .applyingFilter(
- "CIUnsharpMask", parameters: [kCIInputRadiusKey: 1.0, kCIInputIntensityKey: 0.5])
+ // 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")
}
@@ -67,9 +64,9 @@ public func performOCR(imageData: UnsafePointer<UInt8>, length: Int, width: Int,
let text = topCandidate.string
let confidence = topCandidate.confidence
- // Implement early stopping for low-confidence results
- if confidence < 0.3 {
- continue // Skip low-confidence results to save compute
+ // Reduced threshold for including results
+ if confidence < 0.2 {
+ continue // Skip very low-confidence results
}
let boundingBox = observation.boundingBox
textElements.append([
@@ -89,7 +86,7 @@ public func performOCR(imageData: UnsafePointer<UInt8>, length: Int, width: Int,
}
}
- textRequest.recognitionLevel = .accurate
+ textRequest.recognitionLevel = .accurate // Keep accurate recognition
let handler = VNImageRequestHandler(cgImage: preprocessedCGImage, options: [:])
do {
@@ -99,8 +96,9 @@ public func performOCR(imageData: UnsafePointer<UInt8>, length: Int, width: Int,
}
let overallConfidence = observationCount > 0 ? totalConfidence / Float(observationCount) : 0.0
+ print("Overall confidence: \(overallConfidence)")
let result: [String: Any] = [
- "ocrResult": ocrResult.isEmpty ? "No text found" : ocrResult,
+ "ocrResult": ocrResult.isEmpty ? NSNull() : ocrResult,
"textElements": textElements,
"overallConfidence": overallConfidence
]
@@ -125,4 +123,4 @@ How to optimise this code:
1. run cargo bench --bench ocr_benchmark
2. change the code & compile again
3. 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/tesseract.rs b/screenpipe-vision/src/tesseract.rs
index f20abe8cd..063ed5d5b 100644
--- a/screenpipe-vision/src/tesseract.rs
+++ b/screenpipe-vision/src/tesseract.rs
@@ -3,7 +3,7 @@ use std::collections::HashMap;
use image::DynamicImage;
use rusty_tesseract::{Args, DataOutput, Image};
-pub fn perform_ocr_tesseract(image: &DynamicImage) -> (String, String) {
+pub fn perform_ocr_tesseract(image: &DynamicImage) -> (String, String, Option<f64>) {
let args = Args {
lang: "eng".to_string(),
config_variables: HashMap::from([("tessedit_create_tsv".into(), "1".into())]),
@@ -22,7 +22,9 @@ pub fn perform_ocr_tesseract(image: &DynamicImage) -> (String, String) {
let text = data_output_to_text(&data_output);
let json_output = data_output_to_json(&data_output);
- (text, json_output)
+ let overall_confidence = calculate_overall_confidence(&data_output);
+
+ (text, json_output, Some(overall_confidence))
}
fn data_output_to_text(data_output: &DataOutput) -> String {
@@ -89,3 +91,13 @@ fn data_output_to_json(data_output: &DataOutput) -> String {
serde_json::to_string_pretty(&lines).unwrap()
}
+
+fn calculate_overall_confidence(data_output: &DataOutput) -> f64 {
+ let total_conf: f32 = data_output.data.iter().map(|record| record.conf).sum();
+ let count = data_output.data.len();
+ if count > 0 {
+ (total_conf / count as f32) as f64
+ } else {
+ 0.0
+ }
+}
\ No newline at end of file