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
new logic to preprocess and slice images, also to calculate confidence score
matthew-heartful3948661ce664
diff --git a/screenpipe-vision/src/ocr.swift b/screenpipe-vision/src/ocr.swiftindex f63b10f01..090611c04 100644--- a/screenpipe-vision/src/ocr.swift+++ b/screenpipe-vision/src/ocr.swift@@ -1,88 +1,104 @@import CoreGraphicsimport Foundationimport Vision+import CoreImage-// ! TODO long term we should use core_foundation or objc crate to be 100% rust-+@available(macOS 10.15, *)@_cdecl("perform_ocr")public func performOCR(imageData: UnsafePointer<UInt8>, length: Int, width: Int, height: Int)-> UnsafeMutablePointer<CChar>? {- // print("Attempting to create image from raw data")- // print("Image dimensions: \(width)x\(height)")-- guard let dataProvider = CGDataProvider(data: Data(bytes: imageData, count: length) as CFData)- else {- // print("Failed to create CGDataProvider.")- return strdup("Error: Failed to create CGDataProvider")- }-- guard- 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- )+ 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 {- // print("Failed to create CGImage.")return strdup("Error: Failed to create CGImage")}- // print("CGImage created successfully.")+ // Preprocess the image+ 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("CIGaussianBlur", parameters: [kCIInputRadiusKey: 1])+ .applyingFilter("CIColorControls", parameters: [kCIInputBrightnessKey: 0.1])++ guard let preprocessedCGImage = context.createCGImage(processed, from: processed.extent) else {+ return strdup("Error: Failed to create preprocessed image")+ }let semaphore = DispatchSemaphore(value: 0)- var ocrResult = ""-- let request = VNRecognizeTextRequest { request, error in- defer { semaphore.signal() }-- if let error = error {- // print("Error in text recognition request: \(error)")- ocrResult = "Error: \(error.localizedDescription)"- return+ var result = ""+ var textConfidences: [Float] = []++ // Slice the image horizontally with overlap+ let sliceCount = 5 // Adjust this number based on your needs+ let sliceHeight = height / sliceCount+ let overlap = Int(Float(sliceHeight) * 0.1) // 10% overlap++ for i in 0..<sliceCount {+ let sliceY = max(0, i * sliceHeight - overlap)+ let sliceHeight = min(height - sliceY, sliceHeight + overlap)+ let sliceRect = CGRect(x: 0, y: sliceY, width: width, height: sliceHeight)+ guard let sliceCGImage = preprocessedCGImage.cropping(to: sliceRect) else {+ continue}- guard let observations = request.results as? [VNRecognizedTextObservation] else {- // print("Failed to process image or no text found.")- ocrResult = "Error: Failed to process image or no text found"- return- }-- // print("Number of text observations: \(observations.count)")-- for (_, observation) in observations.enumerated() {- guard let topCandidate = observation.topCandidates(1).first else {- // print("No top candidate for observation \(index)")- continue+ let textRequest = VNRecognizeTextRequest()+ let requestHandler = VNImageRequestHandler(cgImage: sliceCGImage, options: [:])++ do {+ try requestHandler.perform([textRequest])++ if let textObservations = textRequest.results {+ for observation in textObservations {+ if let topCandidate = observation.topCandidates(1).first {+ let adjustedBoundingBox = CGRect(+ x: observation.boundingBox.origin.x,+ y: (CGFloat(sliceY) + observation.boundingBox.origin.y * CGFloat(sliceHeight)) / CGFloat(height),+ width: observation.boundingBox.width,+ height: observation.boundingBox.height * CGFloat(sliceHeight) / CGFloat(height)+ )+ result += "\(topCandidate.string)\n" // Text: \+ // result += "Bounding Box: \(adjustedBoundingBox)\n"+ // result += "Confidence: \(topCandidate.confidence)\n\n"+ textConfidences.append(topCandidate.confidence)+ }+ }}- ocrResult += "\(topCandidate.string)\n"+ } catch {+ print("Error processing slice \(i): \(error.localizedDescription)")}}- request.recognitionLevel = .accurate+ // Calculate and add average confidence score for text+ let textAvg = textConfidences.isEmpty ? 0 : textConfidences.reduce(0, +) / Float(textConfidences.count)- let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])- do {- // print("Performing OCR...")- try handler.perform([request])- } catch {- // print("Failed to perform OCR: \(error)")- return strdup("Error: Failed to perform OCR - \(error.localizedDescription)")- }+ result += "Average Text Confidence: \(textAvg)\n"+ // Print average+ print("Text Average Confidence: \(textAvg)")++ semaphore.signal()semaphore.wait()- return strdup(ocrResult.isEmpty ? "No text found" : ocrResult)+ return strdup(result.isEmpty ? "No content found" : result)}+// # Compile for x86_64// swiftc -emit-library -target x86_64-apple-macosx10.15 -o screenpipe-vision/lib/libscreenpipe_x86_64.dylib screenpipe-vision/src/ocr.swift@@ -90,6 +106,4 @@ public func performOCR(imageData: UnsafePointer<UInt8>, length: Int, width: Int,// swiftc -emit-library -target arm64-apple-macosx11.0 -o screenpipe-vision/lib/libscreenpipe_arm64.dylib screenpipe-vision/src/ocr.swift// # Combine into a universal binary-// lipo -create screenpipe-vision/lib/libscreenpipe_x86_64.dylib screenpipe-vision/lib/libscreenpipe_arm64.dylib -output screenpipe-vision/lib/libscreenpipe.dylib--+// lipo -create screenpipe-vision/lib/libscreenpipe_x86_64.dylib screenpipe-vision/lib/libscreenpipe_arm64.dylib -output screenpipe-vision/lib/libscreenpipe.dylib\ No newline at end of file