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

index external folders of mp4 using OCR (and multimodal embeddings later) (#1152)

Louis Beaumont05e1ded6b8a7
diff --git a/.gitignore b/.gitignore
index dc5c8d335..36913e538 100644
--- a/.gitignore
+++ b/.gitignore
@@ -45,3 +45,17 @@ node_modules/
cn
+# Python stuff
+venv/
+app.py
+*.pyc
+*.pyo
+*.pyd
+*.py
+*.pyw
+*.pyz
+*.py3
+*.py3w
+*.py3z
+__pycache__/
+
diff --git a/metadata.json b/metadata.json
new file mode 100644
index 000000000..bb46b7d37
--- /dev/null
+++ b/metadata.json
@@ -0,0 +1,31 @@
+{
+ "overrides": [
+ {
+ "file_path": "/Users/louisbeaumont/Downloads/tmpvideos/video1.mp4",
+ "metadata": {
+ "creation_time": "2024-03-20T10:00:00Z",
+ "fps": 30.0,
+ "duration": 300.0,
+ "device_name": "MacBook Pro"
+ }
+ },
+ {
+ "file_path": "/Users/louisbeaumont/Downloads/tmpvideos/video2.mp4",
+ "metadata": {
+ "creation_time": "2024-03-21T15:30:00Z",
+ "fps": 24.0,
+ "duration": 400.0,
+ "device_name": "External Monitor"
+ }
+ },
+ {
+ "file_path": "/Users/louisbeaumont/Downloads/tmpvideos/video3.mp4",
+ "metadata": {
+ "creation_time": "2024-03-22T09:15:00Z",
+ "fps": 60.0,
+ "duration": 200.0,
+ "device_name": "iPad Screen"
+ }
+ }
+ ]
+}
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index f1c388bf9..cc538992b 100755
--- a/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -5165,7 +5165,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "0.25.3"
+version = "0.25.4"
dependencies = [
"anyhow",
"axum",
diff --git a/screenpipe-app-tauri/src-tauri/capabilities/main.json b/screenpipe-app-tauri/src-tauri/capabilities/main.json
index ef218fc32..ebbf06e63 100644
--- a/screenpipe-app-tauri/src-tauri/capabilities/main.json
+++ b/screenpipe-app-tauri/src-tauri/capabilities/main.json
@@ -16,6 +16,7 @@
"core:menu:default",
"core:tray:default",
"shell:default",
+ "shell:allow-open",
"store:default",
"shell:allow-open",
"fs:allow-watch",
diff --git a/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json b/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
index 4dd9757e1..500305642 100644
--- a/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
+++ b/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
@@ -1 +1 @@
-{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["*"],"permissions":["core:event:allow-listen","core:event:default","core:app:allow-version","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","store:default","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir","fs:allow-remove","global-shortcut:allow-is-registered","global-shortcut:allow-register","global-shortcut:allow-unregister","global-shortcut:allow-unregister-all","global-shortcut:default","sentry:default",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/pipes/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","purge","-y"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["setup"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["migrate"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["serve"],"cmd":"ollama","name":"ollama","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["run",{"validator":"\\S*"}],"cmd":"ollama","name":"ollama-run","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","core:webview:allow-internal-toggle-devtools",{"identifier":"shell:allow-execute","allow":[{"args":["pipe","list","--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-list","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","download",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-download","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","enable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-enable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","disable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-disable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","update",{"validator":"\\S+"},{"validator":"\\{.*\\}"}],"cmd":"screenpipe","name":"screenpipe-pipe-update","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","delete",{"validator":"\\S+"},"--yes"],"cmd":"screenpipe","name":"screenpipe-pipe-delete","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","info",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-info","sidecar":true}]},{"identifier":"http:default","allow":[{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"http://**/*"},{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"https://**/*"}]},"deep-link:default"]}}
\ No newline at end of file
+{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["*"],"permissions":["core:event:allow-listen","core:event:default","core:app:allow-version","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","shell:allow-open","store:default","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir","fs:allow-remove","global-shortcut:allow-is-registered","global-shortcut:allow-register","global-shortcut:allow-unregister","global-shortcut:allow-unregister-all","global-shortcut:default","sentry:default",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/pipes/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","purge","-y"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["setup"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["migrate"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["serve"],"cmd":"ollama","name":"ollama","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["run",{"validator":"\\S*"}],"cmd":"ollama","name":"ollama-run","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","core:webview:allow-internal-toggle-devtools",{"identifier":"shell:allow-execute","allow":[{"args":["pipe","list","--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-list","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","download",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-download","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","enable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-enable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","disable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-disable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","update",{"validator":"\\S+"},{"validator":"\\{.*\\}"}],"cmd":"screenpipe","name":"screenpipe-pipe-update","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","delete",{"validator":"\\S+"},"--yes"],"cmd":"screenpipe","name":"screenpipe-pipe-delete","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","info",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-info","sidecar":true}]},{"identifier":"http:default","allow":[{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"http://**/*"},{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"https://**/*"}]},"deep-link:default"]}}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/src-tauri/src/commands.rs b/screenpipe-app-tauri/src-tauri/src/commands.rs
index 832e69cfd..0f5b73e6f 100644
--- a/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -270,7 +270,7 @@ pub async fn open_pipe_window(
)
.title(title)
.inner_size(1200.0, 850.0)
- .always_on_top(true)
+ // .always_on_top(true)
.visible_on_all_workspaces(true)
.build()
{
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 1b62caf97..b4f7f4e49 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -127,6 +127,10 @@ libsqlite3-sys = { version = "0.26", features = ["bundled"] }
zerocopy = { version = "0.7.32" }
port_check = "0.2.1"
+walkdir = "2.3.4"
+
+regex = "1.10.0"
+
[dev-dependencies]
env_logger = "0.10"
tempfile = "3.3.0"
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 59a03cf62..754a1ff9b 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -12,6 +12,7 @@ use screenpipe_audio::{
use screenpipe_core::find_ffmpeg_path;
use screenpipe_server::{
cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, OutputFormat, PipeCommand},
+ handle_index_command,
highlight::{Highlight, HighlightConfig},
pipe_manager::PipeInfo,
start_continuous_recording, watch_pid, DatabaseManager, PipeManager, ResourceMonitor, Server,
@@ -158,9 +159,6 @@ async fn main() -> anyhow::Result<()> {
PipeCommand::List {
output: OutputFormat::Text,
..
- } | PipeCommand::Download {
- output: OutputFormat::Text,
- ..
} | PipeCommand::Install {
output: OutputFormat::Text,
..
@@ -174,6 +172,10 @@ async fn main() -> anyhow::Result<()> {
| PipeCommand::Delete { .. }
)
}
+ Some(Command::Index {
+ output: OutputFormat::Text,
+ ..
+ }) => true,
_ => true,
};
@@ -277,6 +279,30 @@ async fn main() -> anyhow::Result<()> {
info!("database migrations completed successfully");
return Ok(());
}
+ Command::Index {
+ path,
+ output,
+ data_dir,
+ pattern,
+ ocr_engine,
+ metadata_override,
+ } => {
+ let local_data_dir = get_base_dir(&data_dir)?;
+ let db = Arc::new(
+ DatabaseManager::new(&format!(
+ "{}/db.sqlite",
+ local_data_dir.to_string_lossy()
+ ))
+ .await
+ .map_err(|e| {
+ error!("failed to initialize database: {:?}", e);
+ e
+ })?,
+ );
+ handle_index_command(path, pattern, db, output, ocr_engine, metadata_override)
+ .await?;
+ return Ok(());
+ }
}
}
diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rs
index a552e2c9c..23e270b7b 100644
--- a/screenpipe-server/src/cli.rs
+++ b/screenpipe-server/src/cli.rs
@@ -1,6 +1,8 @@
+use std::path::PathBuf;
+
use clap::{Parser, Subcommand};
use screenpipe_audio::{vad_engine::VadSensitivity, AudioTranscriptionEngine as CoreAudioTranscriptionEngine};
-use screenpipe_vision::utils::OcrEngine as CoreOcrEngine;
+use screenpipe_vision::{custom_ocr::CustomOcrConfig, utils::OcrEngine as CoreOcrEngine};
use clap::ValueEnum;
use screenpipe_audio::vad_engine::VadEngineEnum;
use screenpipe_core::Language;
@@ -41,6 +43,7 @@ pub enum CliOcrEngine {
WindowsNative,
#[cfg(target_os = "macos")]
AppleNative,
+ Custom,
}
impl From<CliOcrEngine> for CoreOcrEngine {
@@ -53,6 +56,20 @@ impl From<CliOcrEngine> for CoreOcrEngine {
CliOcrEngine::WindowsNative => CoreOcrEngine::WindowsNative,
#[cfg(target_os = "macos")]
CliOcrEngine::AppleNative => CoreOcrEngine::AppleNative,
+ CliOcrEngine::Custom => {
+ // Try to read config from environment variable
+ if let Ok(config_str) = std::env::var("SCREENPIPE_CUSTOM_OCR_CONFIG") {
+ match serde_json::from_str(&config_str) {
+ Ok(config) => CoreOcrEngine::Custom(config),
+ Err(e) => {
+ log::warn!("failed to parse custom ocr config from env: {}", e);
+ CoreOcrEngine::Custom(CustomOcrConfig::default())
+ }
+ }
+ } else {
+ CoreOcrEngine::Custom(CustomOcrConfig::default())
+ }
+ }
}
}
}
@@ -281,6 +298,26 @@ pub enum Command {
#[command(subcommand)]
subcommand: PipeCommand,
},
+ /// Index video files for search
+ Index {
+ /// Path to folder containing video files
+ path: String,
+ /// Data directory. Default to $HOME/.screenpipe
+ #[arg(long)]
+ data_dir: Option<String>,
+ /// Output format
+ #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)]
+ output: OutputFormat,
+ /// Regex pattern to filter files (e.g. "monitor.*\.mp4$")
+ #[arg(long)]
+ pattern: Option<String>,
+ /// OCR engine to use
+ #[arg(short = 'o', long, value_enum)]
+ ocr_engine: Option<CliOcrEngine>,
+ /// Path to JSON file containing metadata overrides
+ #[arg(long)]
+ metadata_override: Option<PathBuf>,
+ },
/// Setup screenpipe environment
Setup {
/// Enable beta features
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index e2f6955f5..111915aac 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -1,4 +1,5 @@
use chrono::{DateTime, Utc};
+use image::DynamicImage;
use libsqlite3_sys::sqlite3_auto_extension;
use log::{debug, error, warn};
use screenpipe_audio::{AudioDevice, DeviceType};
@@ -6,11 +7,11 @@ use screenpipe_vision::OcrEngine;
use sqlite_vec::sqlite3_vec_init;
use sqlx::migrate::MigrateDatabase;
use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};
-use sqlx::Column;
use sqlx::Error as SqlxError;
use sqlx::Row;
use sqlx::TypeInfo;
use sqlx::ValueRef;
+use sqlx::{Column, QueryBuilder};
use std::sync::Arc;
use std::time::Duration;
use tracing::info;
@@ -26,6 +27,7 @@ use crate::db_types::{
};
use crate::db_types::{ContentType, UiContent};
use crate::db_types::{SearchResult, TimeSeriesChunk};
+use crate::video_utils::VideoMetadata;
use futures::future::try_join_all;
@@ -1822,4 +1824,95 @@ impl DatabaseManager {
Ok(())
}
+
+ pub async fn batch_insert_ocr(
+ &self,
+ frames: Vec<(i64, String, String, String, String, Arc<OcrEngine>, bool)>,
+ ) -> Result<(), sqlx::Error> {
+ let mut tx = self.pool.begin().await?;
+
+ // Prepare batch insert statement
+ let mut query_builder = QueryBuilder::new(
+ "INSERT INTO ocr_text (frame_id, text, text_json, app_name, window_name, ocr_engine, focused) "
+ );
+
+ query_builder.push_values(
+ &frames,
+ |mut b, (frame_id, text, text_json, app_name, window_name, engine, focused)| {
+ b.push_bind(frame_id)
+ .push_bind(text)
+ .push_bind(text_json)
+ .push_bind(app_name)
+ .push_bind(window_name)
+ .push_bind(format!("{:?}", *engine))
+ .push_bind(focused);
+ },
+ );
+
+ query_builder.build().execute(&mut *tx).await?;
+
+ // Also update FTS table in batch
+ let mut fts_query_builder = QueryBuilder::new("INSERT INTO ocr_text_fts (frame_id, text) ");
+
+ fts_query_builder.push_values(&frames, |mut b, (frame_id, text, ..)| {
+ b.push_bind(frame_id).push_bind(text);
+ });
+
+ fts_query_builder.build().execute(&mut *tx).await?;
+
+ tx.commit().await?;
+ Ok(())
+ }
+
+ pub async fn process_video_frames(
+ &self,
+ file_path: &str,
+ frames: Vec<DynamicImage>,
+ metadata: VideoMetadata,
+ ) -> Result<(), sqlx::Error> {
+ let mut tx = self.pool.begin().await?;
+
+ // 1. Create new video chunk - REMOVE timestamp from INSERT
+ let video_chunk_id =
+ sqlx::query("INSERT INTO video_chunks (device_name, file_path) VALUES (?1, ?2)")
+ .bind(metadata.device_name)
+ .bind(file_path)
+ .execute(&mut *tx)
+ .await?
+ .last_insert_rowid();
+
+ debug!("created video chunk: {} for {}", video_chunk_id, file_path);
+
+ // 2. Create frames with correct timestamps
+ let mut frame_ids = Vec::with_capacity(frames.len());
+
+ for (i, _frame) in frames.iter().enumerate() {
+ // Calculate timestamp for this frame based on creation time and frame number
+ let frame_timestamp = metadata.creation_time
+ + chrono::Duration::milliseconds((i as f64 * (1000.0 / metadata.fps)) as i64);
+
+ debug!("frame timestamp: {}", frame_timestamp);
+
+ let frame_id = sqlx::query(
+ "INSERT INTO frames (video_chunk_id, offset_index, timestamp) VALUES (?1, ?2, ?3)",
+ )
+ .bind(video_chunk_id)
+ .bind(i as i64)
+ .bind(frame_timestamp)
+ .execute(&mut *tx)
+ .await?
+ .last_insert_rowid();
+
+ frame_ids.push(frame_id);
+ }
+
+ tx.commit().await?;
+ debug!(
+ "created {} frames for video chunk {}",
+ frames.len(),
+ video_chunk_id
+ );
+
+ Ok(())
+ }
}
diff --git a/screenpipe-server/src/index.rs b/screenpipe-server/src/index.rs
new file mode 100644
index 000000000..78f923d06
--- /dev/null
+++ b/screenpipe-server/src/index.rs
@@ -0,0 +1,265 @@
+use anyhow::Result;
+use image::DynamicImage;
+use regex::Regex;
+use screenpipe_vision::{
+ perform_ocr_apple, perform_ocr_tesseract,
+ utils::{compare_with_previous_image, OcrEngine},
+};
+use serde_json::json;
+use std::path::PathBuf;
+use std::sync::Arc;
+use tokio::sync::mpsc;
+use tracing::{debug, error, info};
+use walkdir::WalkDir;
+
+use crate::{
+ cli::CliOcrEngine,
+ video_utils::{extract_frames_from_video, get_video_metadata, VideoMetadataOverrides},
+ DatabaseManager,
+};
+
+pub async fn handle_index_command(
+ path: String,
+ pattern: Option<String>,
+ db: Arc<DatabaseManager>,
+ output_format: crate::cli::OutputFormat,
+ ocr_engine: Option<CliOcrEngine>,
+ metadata_override: Option<PathBuf>,
+) -> Result<()> {
+ // Load metadata override if provided
+ let metadata_overrides = if let Some(path) = metadata_override {
+ let content = tokio::fs::read_to_string(path).await?;
+ Some(serde_json::from_str::<VideoMetadataOverrides>(&content)?)
+ } else {
+ None
+ };
+
+ // Get list of video files
+ let video_files = find_video_files(&path, pattern.as_deref())?;
+ info!("found {} video files to process", video_files.len());
+
+ // Validate that we have metadata for all files if overrides are provided
+ if let Some(ref overrides) = metadata_overrides {
+ let mut unmatched_files = Vec::new();
+
+ for video_path in &video_files {
+ let file_str = video_path.to_string_lossy();
+ let matched = overrides
+ .overrides
+ .iter()
+ .any(|override_item| override_item.file_path == file_str);
+
+ if !matched {
+ unmatched_files.push(video_path.clone());
+ }
+ }
+
+ if !unmatched_files.is_empty() {
+ return Err(anyhow::anyhow!(
+ "Missing metadata overrides for files: {:?}",
+ unmatched_files
+ ));
+ }
+ }
+
+ let mut total_frames = 0;
+ let mut total_text = 0;
+
+ // Setup channel for OCR results
+ let (tx, mut rx) = mpsc::channel::<(i64, String, f64)>(100);
+
+ for video_path in video_files {
+ info!("processing video: {}", video_path.display());
+
+ let video_path = &video_path;
+ let mut metadata = get_video_metadata(video_path.to_str().unwrap()).await?;
+
+ // Apply metadata override if provided and matches the file
+ if let Some(ref overrides) = metadata_overrides {
+ let file_str = video_path.to_string_lossy();
+
+ if let Some(override_item) = overrides
+ .overrides
+ .iter()
+ .find(|item| item.file_path == file_str)
+ {
+ override_item.metadata.apply_to(&mut metadata);
+ }
+ }
+
+ let frames = extract_frames_from_video(&video_path, None).await?;
+
+ // Create video chunk and frames first
+ db.process_video_frames(
+ video_path.to_str().unwrap(),
+ frames.clone(),
+ metadata.clone(),
+ )
+ .await?;
+
+ let mut previous_image: Option<DynamicImage> = None;
+ let mut frame_counter: i64 = 0;
+ let mut ocr_batch = Vec::new();
+
+ for (_, frame) in frames.iter().enumerate() {
+ // Compare with previous frame to skip similar ones
+ let current_average = if let Some(prev) = &previous_image {
+ compare_with_previous_image(
+ Some(prev),
+ &frame,
+ &mut None,
+ frame_counter as u64,
+ &mut 0.0,
+ )
+ .await?
+ } else {
+ 1.0
+ };
+
+ // Skip if frames are too similar (threshold from core.rs)
+ if current_average < 0.006 && previous_image.is_some() {
+ info!(
+ "skipping frame {} due to low average difference: {:.3}",
+ frame_counter, current_average
+ );
+ frame_counter += 1;
+ continue;
+ }
+
+ previous_image = Some(frame.clone());
+
+ // Use specified OCR engine or fall back to platform default
+ let engine = match ocr_engine {
+ Some(ref cli_engine) => cli_engine.clone().into(),
+ None => {
+ #[cfg(target_os = "macos")]
+ let engine = OcrEngine::AppleNative;
+ #[cfg(target_os = "windows")]
+ let engine = OcrEngine::WindowsNative;
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
+ let engine = OcrEngine::Tesseract;
+ engine
+ }
+ };
+
+ let tx = tx.clone();
+ let frame_num = frame_counter;
+ let frame = frame.clone();
+ let engine_clone = engine.clone();
+
+ let engine_arc = Arc::new(engine_clone);
+ tokio::spawn(async move {
+ let engine_clone = engine.clone();
+
+ let (text, _, confidence) = match engine_clone.clone() {
+ #[cfg(target_os = "macos")]
+ OcrEngine::AppleNative => perform_ocr_apple(&frame, &[]),
+ #[cfg(target_os = "windows")]
+ OcrEngine::WindowsNative => perform_ocr_windows(&frame).await?,
+ _ => perform_ocr_tesseract(&frame, vec![]),
+ };
+
+ if let Ok(()) = tx.send((frame_num, text, confidence.unwrap_or(0.0))).await {
+ debug!("processed frame {}", frame_num);
+ } else {
+ error!("error sending ocr result for frame {}", frame_num);
+ }
+ });
+
+ // Handle OCR results
+ while let Ok((frame_num, text, confidence)) = rx.try_recv() {
+ total_frames += 1;
+ total_text += text.len();
+
+ ocr_batch.push((
+ frame_num as i64,
+ text.clone(),
+ "{}".to_string(), // empty json
+ "".to_string(), // no app name
+ "".to_string(), // no window name
+ engine_arc.clone(),
+ true, // focused
+ ));
+
+ // Process OCR batch when it reaches size 100
+ if ocr_batch.len() >= 100 {
+ if let Err(e) = db.batch_insert_ocr(ocr_batch).await {
+ info!("error batch inserting ocr text: {}", e);
+ }
+ ocr_batch = Vec::new();
+ }
+
+ match output_format {
+ crate::cli::OutputFormat::Json => {
+ println!(
+ "{}",
+ serde_json::to_string(&json!({
+ "frame": frame_num,
+ "text": text,
+ "confidence": confidence
+ }))?
+ );
+ }
+ crate::cli::OutputFormat::Text => {
+ if !text.is_empty() {
+ debug!("frame {}: {}", frame_num, text);
+ }
+ }
+ }
+ }
+
+ frame_counter += 1;
+ }
+
+ // Process remaining OCR batch
+ if !ocr_batch.is_empty() {
+ if let Err(e) = db.batch_insert_ocr(ocr_batch).await {
+ info!("error batch inserting remaining ocr text: {}", e);
+ }
+ }
+ }
+
+ // wait few seconds for remaining OCR tasks
+ tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
+
+ // Process remaining results
+ while let Ok((_, text, _)) = rx.try_recv() {
+ total_frames += 1;
+ total_text += text.len();
+ }
+
+ info!(
+ "processed {} frames, extracted {} characters of text",
+ total_frames, total_text
+ );
+
+ Ok(())
+}
+
+fn find_video_files(root: &str, pattern: Option<&str>) -> Result<Vec<PathBuf>> {
+ let mut video_files = Vec::new();
+ let regex = pattern.map(|p| Regex::new(p)).transpose()?;
+
+ for entry in WalkDir::new(root)
+ .follow_links(true)
+ .into_iter()
+ .filter_map(|e| e.ok())
+ {
+ let path = entry.path();
+ if path.is_file() {
+ if let Some(ext) = path.extension() {
+ if ext == "mp4" || ext == "mov" || ext == "avi" {
+ if let Some(ref regex) = regex {
+ if regex.is_match(&path.to_string_lossy()) {
+ video_files.push(path.to_path_buf());
+ }
+ } else {
+ video_files.push(path.to_path_buf());
+ }
+ }
+ }
+ }
+ }
+
+ Ok(video_files)
+}
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index ff9039110..d8c51cbd4 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -6,6 +6,7 @@ pub mod db;
pub mod db_types;
pub mod filtering;
pub mod highlight;
+mod index;
pub mod pipe_manager;
mod plugin;
mod resource_monitor;
@@ -13,13 +14,14 @@ mod server;
mod video;
pub mod video_cache;
mod video_db;
-mod video_utils;
+pub mod video_utils;
pub use auto_destruct::watch_pid;
pub use cli::Cli;
pub use core::start_continuous_recording;
pub use db::DatabaseManager;
pub use highlight::Highlight;
+pub use index::handle_index_command;
pub use pipe_manager::PipeManager;
pub use resource_monitor::{ResourceMonitor, RestartSignal};
pub use screenpipe_core::Language;
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index 4a5095e5a..ab61fb7f9 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -61,7 +61,7 @@ impl VideoCapture {
continuous_capture(
result_sender,
interval,
- *ocr_engine,
+ (*ocr_engine).clone(),
monitor_id,
window_filters_clone,
languages.clone(),
diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rs
index d61303f23..adce0d110 100644
--- a/screenpipe-server/src/video_utils.rs
+++ b/screenpipe-server/src/video_utils.rs
@@ -1,13 +1,39 @@
use anyhow::Result;
use base64::{engine::general_purpose, Engine as _};
+use chrono::NaiveDateTime;
+use chrono::{DateTime, Utc};
+use image::DynamicImage;
use screenpipe_core::find_ffmpeg_path;
use serde::{Deserialize, Serialize};
+use std::path::Path;
use std::path::PathBuf;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
-use tracing::{debug, info, error};
+use tracing::{debug, error, info};
use uuid::Uuid;
+#[derive(Debug, Deserialize)]
+struct FFprobeOutput {
+ format: Format,
+ streams: Vec<Stream>,
+}
+
+#[derive(Debug, Deserialize)]
+struct Format {
+ duration: Option<String>,
+ tags: Option<Tags>,
+}
+
+#[derive(Debug, Deserialize)]
+struct Tags {
+ creation_time: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct Stream {
+ r_frame_rate: String,
+}
+
pub async fn extract_frame(file_path: &str, offset_index: i64) -> Result<String> {
let ffmpeg_path = find_ffmpeg_path().expect("failed to find ffmpeg path");
@@ -73,7 +99,7 @@ pub struct MergeVideosResponse {
#[derive(Deserialize)]
pub struct ValidateMediaParams {
- pub file_path: String,
+ pub file_path: String,
}
pub async fn validate_media(file_path: &str) -> Result<()> {
@@ -85,17 +111,9 @@ pub async fn validate_media(file_path: &str) -> Result<()> {
let ffmpeg_path = find_ffmpeg_path().expect("failed to find ffmpeg path");
let status = Command::new(ffmpeg_path)
- .args(&[
- "-v",
- "error",
- "-i",
- file_path,
- "-f",
- "null",
- "-",
- ])
+ .args(&["-v", "error", "-i", file_path, "-f", "null", "-"])
.output()
- .await?;
+ .await?;
if status.status.success() {
Ok(())
@@ -112,7 +130,10 @@ pub async fn merge_videos(
if let Err(e) = tokio::fs::create_dir_all(&output_dir).await {
error!("failed to create output directory: {:?}", e);
- return Err(anyhow::anyhow!("failed to create output directory: {:?}", e));
+ return Err(anyhow::anyhow!(
+ "failed to create output directory: {:?}",
+ e
+ ));
}
let output_filename = format!("output_{}.mp4", Uuid::new_v4());
@@ -123,7 +144,7 @@ pub async fn merge_videos(
let mut file = tokio::fs::File::create(&temp_file).await?;
for video_path in &request.video_paths {
// video validation before writing in txt
- if let Err(e) = validate_media(video_path).await{
+ if let Err(e) = validate_media(video_path).await {
error!("invalid file in merging, skipping: {:?}", e);
continue;
}
@@ -186,3 +207,297 @@ pub async fn merge_videos(
))
}
}
+
+pub async fn extract_frames_from_video(
+ video_path: &std::path::Path,
+ output_path: Option<PathBuf>,
+) -> Result<Vec<DynamicImage>> {
+ let ffmpeg_path = find_ffmpeg_path().expect("failed to find ffmpeg path");
+ let temp_dir = tempfile::tempdir()?;
+ let output_pattern = temp_dir.path().join("frame%d.jpg");
+
+ debug!(
+ "extracting frames from {} to {}",
+ video_path.display(),
+ output_pattern.display()
+ );
+
+ // Ensure video file exists
+ if !video_path.exists() {
+ return Err(anyhow::anyhow!(
+ "video file does not exist: {}",
+ video_path.display()
+ ));
+ }
+
+ // Get source FPS and calculate target FPS
+ let source_fps = match get_video_fps(&ffmpeg_path, video_path.to_str().unwrap()).await {
+ Ok(fps) => fps,
+ Err(e) => {
+ debug!("failed to get video fps, using default 1fps: {}", e);
+ 1.0
+ }
+ };
+
+ let target_fps = if source_fps > 10.0 { 1.0 } else { source_fps };
+ let fps_filter = format!("fps={}", target_fps);
+
+ // Extract frames using ffmpeg
+ let status = Command::new(&ffmpeg_path)
+ .args(&[
+ "-i",
+ video_path.to_str().unwrap(),
+ "-vf",
+ &fps_filter,
+ "-strict",
+ "unofficial",
+ "-c:v",
+ "mjpeg",
+ "-q:v",
+ "2",
+ "-qmin",
+ "2",
+ "-qmax",
+ "4",
+ "-vsync",
+ "0",
+ "-threads",
+ "2",
+ "-y",
+ output_pattern.to_str().unwrap(),
+ ])
+ .output()
+ .await?;
+
+ if !status.status.success() {
+ let stderr = String::from_utf8_lossy(&status.stderr);
+ return Err(anyhow::anyhow!("ffmpeg failed: {}", stderr));
+ }
+
+ // Collect all frames into a vector
+ let mut frames = Vec::new();
+ let mut entries = tokio::fs::read_dir(&temp_dir.path()).await?;
+
+ while let Some(entry) = entries.next_entry().await? {
+ let path = entry.path();
+ let frame_data = tokio::fs::read(&path).await?;
+ let img = image::load_from_memory(&frame_data)?;
+
+ if let Some(out_dir) = &output_path {
+ let frame_name = entry.file_name();
+ let dest_path = out_dir.join(frame_name);
+ debug!("saving frame to disk: {}", dest_path.display());
+ img.save(&dest_path)?;
+ }
+
+ frames.push(img);
+ }
+
+ if frames.is_empty() {
+ return Err(anyhow::anyhow!("no frames were extracted"));
+ }
+
+ debug!("extracted {} frames", frames.len());
+ Ok(frames)
+}
+
+async fn get_video_fps(ffmpeg_path: &PathBuf, video_path: &str) -> Result<f64> {
+ let output = Command::new(ffmpeg_path)
+ .args(&["-i", video_path])
+ .output()
+ .await?;
+
+ let metadata = String::from_utf8_lossy(&output.stderr);
+ let fps = metadata
+ .lines()
+ .find(|line| line.contains("fps") && !line.contains("Stream"))
+ .and_then(|line| {
+ line.split_whitespace()
+ .find(|&word| word.parse::<f64>().is_ok())
+ .and_then(|n| n.parse::<f64>().ok())
+ })
+ .unwrap_or(1.0);
+
+ debug!("detected fps from video metadata: {}", fps);
+ Ok(fps)
+}
+
+fn parse_time_from_filename(path: &str) -> Option<DateTime<Utc>> {
+ let path = Path::new(path);
+ let filename = path.file_name()?.to_str()?;
+
+ // Assuming format: monitor_1_2024-10-19_02-51-20.mp4
+ let parts: Vec<&str> = filename.split('_').collect();
+ if parts.len() >= 4 {
+ let date = parts[2];
+ let time = parts[3].split('.').next()?;
+ let datetime_str = format!("{} {}", date, time.replace('-', ":"));
+
+ // Parse with format "2024-10-19 02:51:20"
+ NaiveDateTime::parse_from_str(&datetime_str, "%Y-%m-%d %H:%M:%S")
+ .ok()?
+ .and_local_timezone(Utc)
+ .earliest()
+ } else {
+ None
+ }
+}
+
+pub async fn get_video_metadata(video_path: &str) -> Result<VideoMetadata> {
+ let ffmpeg_path = find_ffmpeg_path().expect("failed to find ffmpeg path");
+ let ffprobe_path = ffmpeg_path.with_file_name("ffprobe");
+
+ // Try ffprobe first
+ let creation_time = match Command::new(&ffprobe_path)
+ .args(&[
+ "-v",
+ "quiet",
+ "-print_format",
+ "json",
+ "-show_format",
+ "-show_streams",
+ "-show_entries",
+ "format_tags=creation_time",
+ video_path,
+ ])
+ .output()
+ .await
+ {
+ Ok(output) if output.status.success() => {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let metadata: FFprobeOutput = serde_json::from_str(&stdout)?;
+
+ metadata
+ .format
+ .tags
+ .and_then(|t| t.creation_time)
+ .and_then(|t| {
+ DateTime::parse_from_rfc3339(&t)
+ .or_else(|_| DateTime::parse_from_str(&t, "%Y-%m-%d %H:%M:%S%.f %z"))
+ .or_else(|_| DateTime::parse_from_str(&t, "%Y-%m-%d %H:%M:%S"))
+ .ok()
+ })
+ .map(|t| t.with_timezone(&Utc))
+ }
+ _ => None,
+ };
+
+ // Try filename if ffprobe failed
+ let creation_time = creation_time.or_else(|| parse_time_from_filename(video_path));
+
+ // Try filesystem metadata if everything else failed
+ let creation_time = match creation_time {
+ Some(time) => time,
+ None => {
+ if let Ok(metadata) = tokio::fs::metadata(video_path).await {
+ if let Ok(created) = metadata.created() {
+ DateTime::<Utc>::from(created)
+ } else {
+ debug!("falling back to current time for creation_time");
+ Utc::now()
+ }
+ } else {
+ debug!("falling back to current time for creation_time");
+ Utc::now()
+ }
+ }
+ };
+
+ // Rest of the metadata gathering (fps, duration) remains the same...
+ let (fps, duration) = get_video_technical_metadata(&ffprobe_path, video_path).await?;
+
+ Ok(VideoMetadata {
+ creation_time,
+ fps,
+ duration,
+ device_name: None,
+ })
+}
+
+// Helper function to get fps and duration
+async fn get_video_technical_metadata(ffprobe_path: &Path, video_path: &str) -> Result<(f64, f64)> {
+ let output = Command::new(ffprobe_path)
+ .args(&[
+ "-v",
+ "quiet",
+ "-print_format",
+ "json",
+ "-show_format",
+ "-show_streams",
+ video_path,
+ ])
+ .output()
+ .await?;
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let metadata: FFprobeOutput = serde_json::from_str(&stdout)?;
+
+ let fps = metadata
+ .streams
+ .first()
+ .and_then(|s| {
+ let parts: Vec<f64> = s
+ .r_frame_rate
+ .split('/')
+ .filter_map(|n| n.parse().ok())
+ .collect();
+ if parts.len() == 2 && parts[1] != 0.0 {
+ Some(parts[0] / parts[1])
+ } else {
+ None
+ }
+ })
+ .unwrap_or(30.0);
+
+ let duration = metadata
+ .format
+ .duration
+ .and_then(|d| d.parse::<f64>().ok())
+ .unwrap_or(0.0);
+
+ Ok((fps, duration))
+}
+
+#[derive(Debug, Clone)]
+pub struct VideoMetadata {
+ pub creation_time: DateTime<Utc>,
+ pub fps: f64,
+ pub duration: f64,
+ pub device_name: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct VideoMetadataOverrides {
+ pub overrides: Vec<VideoMetadataItem>,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct VideoMetadataItem {
+ pub file_path: String, // Direct file path
+ pub metadata: VideoMetadataOverride,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct VideoMetadataOverride {
+ pub creation_time: Option<DateTime<Utc>>,
+ pub fps: Option<f64>,
+ pub duration: Option<f64>,
+ pub device_name: Option<String>,
+}
+
+impl VideoMetadataOverride {
+ pub fn apply_to(&self, metadata: &mut VideoMetadata) {
+ if let Some(creation_time) = self.creation_time {
+ metadata.creation_time = creation_time;
+ }
+ if let Some(fps) = self.fps {
+ metadata.fps = fps;
+ }
+ if let Some(duration) = self.duration {
+ metadata.duration = duration;
+ }
+ if let Some(ref device_name) = self.device_name {
+ metadata.device_name = Some(device_name.clone());
+ }
+ }
+}
diff --git a/screenpipe-server/tests/index_test.rs b/screenpipe-server/tests/index_test.rs
new file mode 100644
index 000000000..6418d8e76
--- /dev/null
+++ b/screenpipe-server/tests/index_test.rs
@@ -0,0 +1,158 @@
+use std::{
+ path::{Path, PathBuf},
+ sync::Arc,
+};
+
+use anyhow::Result;
+use dirs::home_dir;
+use screenpipe_server::{cli::OutputFormat, handle_index_command, DatabaseManager};
+use tempfile::tempdir;
+use tokio::fs;
+use tracing::debug;
+
+async fn setup_test_env() -> Result<()> {
+ tracing_subscriber::fmt()
+ .with_max_level(tracing::Level::DEBUG)
+ .init();
+ Ok(())
+}
+
+async fn setup_test_db() -> Result<(tempfile::TempDir, Arc<DatabaseManager>)> {
+ let temp_dir = tempdir()?;
+ let db_path = temp_dir.path().join("test.db");
+ let db = Arc::new(DatabaseManager::new(&db_path.to_string_lossy()).await?);
+ Ok((temp_dir, db))
+}
+
+async fn copy_test_video(temp_dir: &Path) -> Result<PathBuf> {
+ // Find a small video file from .screenpipe
+ let screenpipe_dir = home_dir()
+ .expect("couldn't find home dir")
+ .join(".screenpipe")
+ .join("data");
+
+ let mut entries = fs::read_dir(&screenpipe_dir).await?;
+ let mut source_video = None;
+
+ while let Some(entry) = entries.next_entry().await? {
+ let path = entry.path();
+ if let Some(ext) = path.extension() {
+ if ext == "mp4"
+ && fs::metadata(&path).await?.len() < 100_000_000
+ && path.to_string_lossy().to_lowercase().contains("monitor")
+ {
+ source_video = Some(path);
+ break;
+ }
+ }
+ }
+
+ let source_path =
+ source_video.ok_or_else(|| anyhow::anyhow!("no suitable test video found"))?;
+ let target_path = temp_dir.join("test_video.mp4");
+
+ fs::copy(&source_path, &target_path).await?;
+ println!("copied test video to {}", target_path.display());
+ Ok(target_path)
+}
+
+#[tokio::test]
+async fn test_index_command_with_sql() -> Result<()> {
+ setup_test_env().await?;
+
+ let (temp_dir, db) = setup_test_db().await?;
+ let video_path = copy_test_video(temp_dir.path()).await?;
+
+ debug!("testing indexing with video at {}", video_path.display());
+
+ // Run indexing
+ handle_index_command(
+ temp_dir.path().to_string_lossy().to_string(),
+ None,
+ db.clone(),
+ OutputFormat::Text,
+ )
+ .await?;
+
+ // Check video_chunks table
+ let video_chunks = db
+ .execute_raw_sql("SELECT * FROM video_chunks WHERE file_path LIKE '%test_video.mp4'")
+ .await?;
+ debug!(
+ "video chunks: {}",
+ serde_json::to_string_pretty(&video_chunks)?
+ );
+ assert!(
+ !video_chunks.as_array().unwrap().is_empty(),
+ "should have video chunk entry"
+ );
+
+ // Check frames table
+ let frames = db
+ .execute_raw_sql(
+ "SELECT COUNT(*) as frame_count FROM frames f
+ JOIN video_chunks vc ON f.video_chunk_id = vc.id
+ WHERE vc.file_path LIKE '%test_video.mp4'",
+ )
+ .await?;
+ debug!("frames: {}", serde_json::to_string_pretty(&frames)?);
+ assert!(
+ frames.as_array().unwrap()[0]["frame_count"]
+ .as_i64()
+ .unwrap()
+ > 0,
+ "should have frames"
+ );
+
+ // Check OCR results
+ let ocr_results = db
+ .execute_raw_sql(
+ "SELECT COUNT(*) as ocr_count FROM ocr_text ot
+ JOIN frames f ON ot.frame_id = f.id
+ JOIN video_chunks vc ON f.video_chunk_id = vc.id
+ WHERE vc.file_path LIKE '%test_video.mp4'",
+ )
+ .await?;
+ debug!(
+ "ocr results: {}",
+ serde_json::to_string_pretty(&ocr_results)?
+ );
+ assert!(
+ ocr_results.as_array().unwrap()[0]["ocr_count"]
+ .as_i64()
+ .unwrap()
+ > 0,
+ "should have OCR results"
+ );
+
+ // Check timestamps are valid
+ let timestamps = db
+ .execute_raw_sql(
+ "SELECT f.timestamp FROM frames f
+ JOIN video_chunks vc ON f.video_chunk_id = vc.id
+ WHERE vc.file_path LIKE '%test_video.mp4'",
+ )
+ .await?;
+ debug!("timestamps: {}", serde_json::to_string_pretty(&timestamps)?);
+ assert!(
+ !timestamps.as_array().unwrap().is_empty(),
+ "should have timestamps"
+ );
+
+ // Check OCR text content
+ let ocr_text = db
+ .execute_raw_sql(
+ "SELECT ot.text, ot.app_name, ot.window_name FROM ocr_text ot
+ JOIN frames f ON ot.frame_id = f.id
+ JOIN video_chunks vc ON f.video_chunk_id = vc.id
+ WHERE vc.file_path LIKE '%test_video.mp4'
+ LIMIT 5",
+ )
+ .await?;
+ debug!(
+ "sample ocr text: {}",
+ serde_json::to_string_pretty(&ocr_text)?
+ );
+
+ Ok(())
+}
diff --git a/screenpipe-server/tests/video_utils_test.rs b/screenpipe-server/tests/video_utils_test.rs
new file mode 100644
index 000000000..169757ecf
--- /dev/null
+++ b/screenpipe-server/tests/video_utils_test.rs
@@ -0,0 +1,175 @@
+use anyhow::Result;
+use dirs::{self, home_dir};
+use screenpipe_core::Language;
+use screenpipe_server::video_utils::extract_frames_from_video;
+use screenpipe_vision::{capture_screenshot_by_window::CapturedWindow, perform_ocr_apple};
+use std::path::PathBuf;
+use tokio::fs;
+use tracing::info;
+
+async fn setup_test_env() -> Result<()> {
+ // enable tracing logging
+ tracing_subscriber::fmt()
+ .with_max_level(tracing::Level::DEBUG)
+ .init();
+ Ok(())
+}
+
+async fn create_test_video() -> Result<PathBuf> {
+ let screenpipe_dir = dirs::home_dir()
+ .expect("couldn't find home dir")
+ .join(".screenpipe")
+ .join("data");
+
+ info!("looking for monitor video in {}", screenpipe_dir.display());
+
+ // Read directory and find first video containing "monitor"
+ let mut entries = tokio::fs::read_dir(&screenpipe_dir).await?;
+
+ while let Some(entry) = entries.next_entry().await? {
+ let path = entry.path();
+ if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
+ if filename.contains("monitor") {
+ info!("found monitor video: {}", path.display());
+ return Ok(path);
+ }
+ }
+ }
+
+ Err(anyhow::anyhow!(
+ "no monitor video found in screenpipe data dir"
+ ))
+}
+
+#[tokio::test]
+async fn test_extract_frames() -> Result<()> {
+ setup_test_env().await?;
+ let video_path = create_test_video().await?;
+
+ println!("testing frame extraction from {}", video_path.display());
+
+ // Test both write_to_disk modes
+ for write_to_disk in [true, false] {
+ println!("testing with write_to_disk = {}", write_to_disk);
+
+ let output_path = if write_to_disk {
+ Some(PathBuf::from(home_dir().unwrap()).join("Downloads"))
+ } else {
+ None
+ };
+
+ let frames = extract_frames_from_video(&video_path, output_path).await?;
+ println!("extracted {} frames", frames.len());
+
+ // Verify we got some frames
+ assert!(!frames.is_empty(), "should extract at least one frame");
+
+ // Check frame dimensions
+ let first_frame = &frames[0];
+ println!(
+ "frame dimensions: {}x{}",
+ first_frame.width(),
+ first_frame.height()
+ );
+
+ // If write_to_disk is true, verify files exist
+ if write_to_disk {
+ if let Some(parent) = video_path.parent() {
+ let mut entries = fs::read_dir(parent).await?;
+ let mut jpg_count = 0;
+ while let Some(entry) = entries.next_entry().await? {
+ if entry
+ .path()
+ .extension()
+ .and_then(|ext| ext.to_str())
+ .map(|ext| ext == "jpg")
+ .unwrap_or(false)
+ {
+ jpg_count += 1;
+ }
+ }
+
+ println!("found {} jpg files in temp dir", jpg_count);
+ assert!(
+ jpg_count > 0,
+ "should find jpg files when write_to_disk is true"
+ );
+ }
+ }
+ }
+
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_extract_frames_and_ocr() -> Result<()> {
+ setup_test_env().await?;
+ let video_path = create_test_video().await?;
+
+ println!(
+ "testing frame extraction and ocr from {}",
+ video_path.display()
+ );
+
+ // extract frames
+ let frames = extract_frames_from_video(
+ &video_path,
+ Some(PathBuf::from(home_dir().unwrap()).join("Downloads")),
+ )
+ .await?;
+
+ // verify we got frames
+ assert!(!frames.is_empty(), "should extract at least one frame");
+
+ // take first frame
+ let first_frame = &frames[0];
+
+ // create a mock captured window for ocr
+ let captured_window = CapturedWindow {
+ image: first_frame.clone(),
+ window_name: "test_window".to_string(),
+ app_name: "test_app".to_string(),
+ is_focused: true,
+ };
+
+ // perform ocr using apple native (macos only)
+ let (text, _, confidence) = perform_ocr_apple(&captured_window.image, &vec![Language::English]);
+
+ println!("ocr confidence: {}", confidence.unwrap_or(0.0));
+ println!("extracted text: {}", text);
+
+ // basic validation
+ assert!(!text.is_empty(), "ocr should extract some text");
+ assert!(
+ confidence.unwrap_or(0.0) > 0.0,
+ "confidence should be greater than 0"
+ );
+
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_get_video_metadata() -> Result<()> {
+ setup_test_env().await?;
+ let video_path = create_test_video().await?;
+
+ println!("testing metadata extraction from {}", video_path.display());
+
+ let metadata =
+ screenpipe_server::video_utils::get_video_metadata(video_path.to_str().unwrap()).await?;
+
+ println!(
+ "extracted metadata: creation_time={}, fps={}, duration={}s",
+ metadata.creation_time, metadata.fps, metadata.duration
+ );
+
+ // basic validation
+ assert!(metadata.fps > 0.0, "fps should be positive");
+ assert!(metadata.duration > 0.0, "duration should be positive");
+ assert!(
+ metadata.creation_time <= chrono::Utc::now(),
+ "creation time should not be in the future"
+ );
+
+ Ok(())
+}
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index 262637789..aebc8628a 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -46,6 +46,8 @@ once_cell = { workspace = true }
chrono = { version = "0.4.39", features = ["serde"] }
base64 = "0.22.1"
+reqwest = { workspace = true }
+
[dev-dependencies]
tempfile = "3.3.0"
criterion = { workspace = true }
diff --git a/screenpipe-vision/bin/ui_monitor b/screenpipe-vision/bin/ui_monitor
index c3419888e..602bde837 100755
Binary files a/screenpipe-vision/bin/ui_monitor and b/screenpipe-vision/bin/ui_monitor differ
diff --git a/screenpipe-vision/src/apple.rs b/screenpipe-vision/src/apple.rs
index 726d15d17..dcf1c62d7 100644
--- a/screenpipe-vision/src/apple.rs
+++ b/screenpipe-vision/src/apple.rs
@@ -7,9 +7,39 @@ use cidre::{
use image::DynamicImage;
use image::GenericImageView;
use log::error;
+use screenpipe_core::Language;
use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::sync::OnceLock;
use std::{ffi::c_void, ptr::null_mut};
+static APPLE_LANGUAGE_MAP: OnceLock<HashMap<Language, &'static str>> = OnceLock::new();
+
+pub fn get_apple_languages(languages: &[Language]) -> Vec<String> {
+ let map = APPLE_LANGUAGE_MAP.get_or_init(|| {
+ let mut m = HashMap::new();
+ m.insert(Language::English, "en-US");
+ m.insert(Language::Spanish, "es-ES");
+ m.insert(Language::French, "fr-FR");
+ m.insert(Language::German, "de-DE");
+ m.insert(Language::Italian, "it-IT");
+ m.insert(Language::Portuguese, "pt-BR");
+ m.insert(Language::Russian, "ru-RU");
+ m.insert(Language::Chinese, "zh-Hans");
+ m.insert(Language::Korean, "ko-KR");
+ m.insert(Language::Japanese, "ja-JP");
+ m.insert(Language::Ukrainian, "uk-UA");
+ m.insert(Language::Thai, "th-TH");
+ m.insert(Language::Arabic, "ar-SA");
+ m
+ });
+
+ languages
+ .iter()
+ .filter_map(|lang| map.get(lang).map(|&s| s.to_string()))
+ .collect()
+}
+
#[derive(Serialize, Deserialize, Debug)]
struct OcrResultBBox {
x: f64,
@@ -41,9 +71,16 @@ extern "C" fn release_callback(_refcon: *mut c_void, _data_ptr: *const *const c_
#[cfg(target_os = "macos")]
pub fn perform_ocr_apple(
image: &DynamicImage,
- languages: &ns::ArrayMut<ns::String>,
+ languages: &[Language],
) -> (String, String, Option<f64>) {
cidre::objc::ar_pool(|| {
+ // Convert languages to Apple format and create ns::Array
+ let apple_languages = get_apple_languages(languages);
+ let mut languages_array = ns::ArrayMut::<ns::String>::with_capacity(apple_languages.len());
+ apple_languages.iter().for_each(|language| {
+ languages_array.push(&ns::String::with_str(language));
+ });
+
let (width, height) = image.dimensions();
let rgb = image.grayscale().to_luma8();
let raw_data = rgb.as_raw();
@@ -79,8 +116,7 @@ pub fn perform_ocr_apple(
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_recognition_langs(&languages_array);
request.set_uses_lang_correction(false);
let requests = ns::Array::<vn::Request>::from_slice(&[&request]);
let result = handler.perform(&requests);
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index 45d490ac1..6640f38d2 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -2,6 +2,7 @@
use crate::apple::perform_ocr_apple;
use crate::capture_screenshot_by_window::CapturedWindow;
use crate::capture_screenshot_by_window::WindowFilters;
+use crate::custom_ocr::perform_ocr_custom;
#[cfg(target_os = "windows")]
use crate::microsoft::perform_ocr_windows;
use crate::monitor::get_monitor_by_id;
@@ -10,8 +11,6 @@ use crate::utils::OcrEngine;
use crate::utils::{capture_screenshot, compare_with_previous_image};
use anyhow::{anyhow, Result};
use base64::{engine::general_purpose, Engine as _};
-#[cfg(target_os = "macos")]
-use cidre::ns;
use image::codecs::jpeg::JpegEncoder;
use image::DynamicImage;
use log::{debug, error};
@@ -35,15 +34,9 @@ use tokio::time::sleep;
#[cfg(target_os = "macos")]
use xcap_macos::Monitor;
-#[cfg(target_os = "macos")]
-use std::sync::OnceLock;
-
#[cfg(not(target_os = "macos"))]
use xcap::Monitor;
-#[cfg(target_os = "macos")]
-static APPLE_LANGUAGE_MAP: OnceLock<HashMap<Language, &'static str>> = OnceLock::new();
-
fn serialize_image<S>(image: &Option<DynamicImage>, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
@@ -287,17 +280,6 @@ pub async fn process_ocr_task(
let mut total_confidence = 0.0;
let mut window_count = 0;
- #[cfg(target_os = "macos")]
- let languages_slice = {
- use ns;
- let apple_languages = get_apple_languages(languages.clone());
- let mut slice = ns::ArrayMut::<ns::String>::with_capacity(apple_languages.len());
- apple_languages.iter().for_each(|language| {
- slice.push(&ns::String::with_str(language.as_str()));
- });
- slice
- };
-
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())
@@ -311,7 +293,12 @@ 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 => perform_ocr_apple(&captured_window.image, &languages_slice),
+ OcrEngine::AppleNative => perform_ocr_apple(&captured_window.image, &languages),
+ OcrEngine::Custom(config) => {
+ perform_ocr_custom(&captured_window.image, languages.clone(), config)
+ .await
+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?
+ }
_ => {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
@@ -394,32 +381,6 @@ pub fn trigger_screen_capture_permission() -> Result<()> {
Ok(())
}
-#[cfg(target_os = "macos")]
-pub fn get_apple_languages(languages: Vec<screenpipe_core::Language>) -> Vec<String> {
- let map = APPLE_LANGUAGE_MAP.get_or_init(|| {
- let mut m = HashMap::new();
- m.insert(Language::English, "en-US");
- m.insert(Language::Spanish, "es-ES");
- m.insert(Language::French, "fr-FR");
- m.insert(Language::German, "de-DE");
- m.insert(Language::Italian, "it-IT");
- m.insert(Language::Portuguese, "pt-BR");
- m.insert(Language::Russian, "ru-RU");
- m.insert(Language::Chinese, "zh-Hans");
- m.insert(Language::Korean, "ko-KR");
- m.insert(Language::Japanese, "ja-JP");
- m.insert(Language::Ukrainian, "uk-UA");
- m.insert(Language::Thai, "th-TH");
- m.insert(Language::Arabic, "ar-SA");
- m
- });
-
- languages
- .iter()
- .filter_map(|lang| map.get(lang).map(|&s| s.to_string()))
- .collect()
-}
-
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RealtimeVisionEvent {
Ocr(WindowOcr),
diff --git a/screenpipe-vision/src/custom_ocr.rs b/screenpipe-vision/src/custom_ocr.rs
new file mode 100644
index 000000000..bfd077ecd
--- /dev/null
+++ b/screenpipe-vision/src/custom_ocr.rs
@@ -0,0 +1,74 @@
+use anyhow::Result;
+use base64::{engine::general_purpose, Engine as _};
+use image::DynamicImage;
+use screenpipe_core::Language;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CustomOcrConfig {
+ pub api_url: String,
+ pub api_key: String,
+ pub timeout_ms: u64,
+}
+
+impl Default for CustomOcrConfig {
+ fn default() -> Self {
+ CustomOcrConfig {
+ api_url: "http://localhost:8000/ocr".to_string(),
+ api_key: "".to_string(),
+ timeout_ms: 5000,
+ }
+ }
+}
+
+pub async fn perform_ocr_custom(
+ image: &DynamicImage,
+ languages: Vec<Language>,
+ config: &CustomOcrConfig,
+) -> Result<(String, String, Option<f64>)> {
+ // Convert image to RGB before encoding to JPEG
+ let rgb_image = image.to_rgb8();
+
+ // Convert image to base64 JPEG
+ let mut buffer = Vec::new();
+ rgb_image.write_to(
+ &mut std::io::Cursor::new(&mut buffer),
+ image::ImageFormat::Jpeg,
+ )?;
+ let base64_image = general_purpose::STANDARD.encode(buffer);
+
+ // Prepare the request payload
+ let payload = serde_json::json!({
+ "image": base64_image,
+ "languages": languages.iter().map(|l| l.to_string()).collect::<Vec<_>>(),
+ });
+
+ // Create client with timeout
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_millis(config.timeout_ms))
+ .build()?;
+
+ // Make the API request
+ let response = client
+ .post(&config.api_url)
+ .header("Authorization", format!("Bearer {}", config.api_key))
+ .json(&payload)
+ .send()
+ .await?;
+
+ // Handle the response
+ let ocr_result: OcrResponse = response.json().await?;
+
+ Ok((
+ ocr_result.text,
+ ocr_result.structured_data.to_string(),
+ Some(ocr_result.confidence),
+ ))
+}
+
+#[derive(Debug, Deserialize)]
+struct OcrResponse {
+ text: String,
+ structured_data: serde_json::Value,
+ confidence: f64,
+}
diff --git a/screenpipe-vision/src/lib.rs b/screenpipe-vision/src/lib.rs
index 4783bd87d..6461555f3 100644
--- a/screenpipe-vision/src/lib.rs
+++ b/screenpipe-vision/src/lib.rs
@@ -1,6 +1,7 @@
#[cfg(target_os = "macos")]
pub mod apple;
pub mod core;
+pub mod custom_ocr;
#[cfg(target_os = "windows")]
pub mod microsoft;
pub mod monitor;
@@ -14,6 +15,7 @@ pub use core::{continuous_capture, process_ocr_task, CaptureResult, RealtimeVisi
// pub use types::CaptureResult;
pub use utils::OcrEngine;
pub mod capture_screenshot_by_window;
+pub use custom_ocr::perform_ocr_custom;
#[cfg(target_os = "windows")]
pub use microsoft::perform_ocr_windows;
#[cfg(target_os = "macos")]
diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rs
index 75a1eb828..c22c64400 100644
--- a/screenpipe-vision/src/utils.rs
+++ b/screenpipe-vision/src/utils.rs
@@ -2,6 +2,7 @@ use crate::capture_screenshot_by_window::{
capture_all_visible_windows, CapturedWindow, WindowFilters,
};
use crate::core::MaxAverageFrame;
+use crate::custom_ocr::CustomOcrConfig;
use image::DynamicImage;
use image_compare::{Algorithm, Metric, Similarity};
use log::{debug, error, warn};
@@ -14,12 +15,13 @@ use xcap_macos::Monitor;
#[cfg(not(target_os = "macos"))]
use xcap::Monitor;
-#[derive(Clone, Debug, Copy)]
+#[derive(Clone, Debug)]
pub enum OcrEngine {
Unstructured,
Tesseract,
WindowsNative,
AppleNative,
+ Custom(CustomOcrConfig),
}
impl Default for OcrEngine {
diff --git a/screenpipe-vision/tests/apple_vision_test.rs b/screenpipe-vision/tests/apple_vision_test.rs
index c750b85a5..e0a95e24f 100644
--- a/screenpipe-vision/tests/apple_vision_test.rs
+++ b/screenpipe-vision/tests/apple_vision_test.rs
@@ -1,10 +1,9 @@
#[cfg(target_os = "macos")]
#[cfg(test)]
mod tests {
- use cidre::ns;
use image::GenericImageView;
use screenpipe_core::Language;
- use screenpipe_vision::{core::get_apple_languages, perform_ocr_apple};
+ use screenpipe_vision::perform_ocr_apple;
use std::path::PathBuf;
#[tokio::test]
@@ -27,8 +26,7 @@ mod tests {
let rgb_image = image.to_rgb8();
println!("RGB image dimensions: {:?}", rgb_image.dimensions());
- let (ocr_text, _, _) =
- perform_ocr_apple(&image, &ns::ArrayMut::<ns::String>::with_capacity(0));
+ let (ocr_text, _, _) = perform_ocr_apple(&image, &[]);
println!("OCR text: {:?}", ocr_text);
assert!(
@@ -48,16 +46,7 @@ mod tests {
let image = image::open(&path).expect("Failed to open Chinese test image");
println!("Image dimensions: {:?}", image.dimensions());
- let languages_slice = {
- use ns;
- let apple_languages = get_apple_languages(vec![Language::Chinese]);
- let mut slice = ns::ArrayMut::<ns::String>::with_capacity(apple_languages.len());
- apple_languages.iter().for_each(|language| {
- slice.push(&ns::String::with_str(language.as_str()));
- });
- slice
- };
- let (ocr_text, _, _) = perform_ocr_apple(&image, &languages_slice);
+ let (ocr_text, _, _) = perform_ocr_apple(&image, &[Language::Chinese]);
println!("OCR text: {:?}", ocr_text);
assert!(
diff --git a/screenpipe-vision/tests/custom_ocr_test.rs b/screenpipe-vision/tests/custom_ocr_test.rs
new file mode 100644
index 000000000..701e5c9eb
--- /dev/null
+++ b/screenpipe-vision/tests/custom_ocr_test.rs
@@ -0,0 +1,159 @@
+/*
+# Python code snippet to run a custom OCR API using EasyOCR
+
+# Create new venv
+python -m venv venv
+source venv/bin/activate
+
+# Install dependencies
+pip install fastapi uvicorn easyocr pillow numpy
+
+# Create a simple FastAPI server (app.py) that uses EasyOCR to process images:
+
+from fastapi import FastAPI, HTTPException
+import base64
+import io
+from PIL import Image
+import numpy as np
+import time
+import easyocr
+
+app = FastAPI()
+reader = easyocr.Reader(['en', 'ch_sim']) # Initialize once
+
+async def read_ocr(payload: dict):
+ image_b64 = payload.get("image")
+
+ if not image_b64:
+ raise HTTPException(status_code=400, detail="No image data provided")
+
+ try:
+ start = time.time()
+ image_data = base64.b64decode(image_b64)
+ image = Image.open(io.BytesIO(image_data))
+ image_np = np.array(image)
+
+ result = reader.readtext(image_np)
+
+ text = "\n".join([item[1] for item in result])
+ confidence = sum([item[2] for item in result]) / len(result) if result else 0.0
+
+ print(f"OCR took {time.time() - start:.2f} seconds")
+
+ return {
+ "text": text,
+ "structured_data": {},
+ "confidence": confidence
+ }
+
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=f"OCR processing error: {str(e)}")
+
+# Run the server:
+# uvicorn app:app --host 0.0.0.0 --port 8000
+#
+# Configure your "CustomOcrConfig" in Rust to point to http://localhost:8000/ocr
+
+# Clean up
+deactivate
+rm -rf venv app.py
+*/
+
+#[cfg(test)]
+mod tests {
+ use image::GenericImageView;
+ use screenpipe_core::Language;
+ use screenpipe_vision::custom_ocr::{perform_ocr_custom, CustomOcrConfig};
+ use screenpipe_vision::utils::OcrEngine;
+ use std::path::PathBuf;
+
+ #[tokio::test]
+ async fn test_custom_ocr() {
+ println!("Starting custom OCR test...");
+
+ // Load a sample image.
+ let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ path.push("tests");
+ path.push("testing_OCR.png");
+ println!("Path to testing_OCR.png: {:?}", path);
+
+ // Check if file exists.
+ if let Ok(metadata) = std::fs::metadata(&path) {
+ println!("File size: {} bytes", metadata.len());
+ }
+
+ // Open the image.
+ let image = image::open(&path).expect("Failed to open test image");
+ println!("Image dimensions: {:?}", image.dimensions());
+
+ // Configure our custom OCR engine.
+ let config = CustomOcrConfig {
+ api_url: "http://localhost:8000/ocr".to_string(),
+ api_key: "".to_string(),
+ timeout_ms: 5000,
+ };
+ let ocr_engine = OcrEngine::Custom(config);
+
+ // Perform the custom OCR.
+ let (ocr_text, structured_data, confidence) = match ocr_engine {
+ OcrEngine::Custom(ref config) => {
+ perform_ocr_custom(&image, vec![Language::English], config)
+ .await
+ .expect("Custom OCR failed")
+ }
+ _ => panic!("Unexpected OCR engine"),
+ };
+
+ println!("OCR text: {:?}", ocr_text);
+ println!("Structured data: {:?}", structured_data);
+ println!("Confidence: {:?}", confidence);
+
+ // Check some basic assumption about the output
+ assert!(
+ !ocr_text.is_empty(),
+ "Custom OCR did not return any recognized text."
+ );
+ }
+
+ #[tokio::test]
+ async fn test_custom_ocr_chinese() {
+ println!("Starting custom OCR Chinese test...");
+
+ let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ path.push("tests");
+ path.push("testing_OCR_chinese.png");
+
+ println!("Path to testing_OCR_chinese.png: {:?}", path);
+
+ if let Ok(metadata) = std::fs::metadata(&path) {
+ println!("File size: {} bytes", metadata.len());
+ }
+
+ let image = image::open(&path).expect("Failed to open Chinese test image");
+ println!("Image dimensions: {:?}", image.dimensions());
+
+ let config = CustomOcrConfig {
+ api_url: "http://localhost:8000/ocr".to_string(),
+ api_key: "".to_string(),
+ timeout_ms: 30000000,
+ };
+ let ocr_engine = OcrEngine::Custom(config);
+
+ let (ocr_text, _, _) = match ocr_engine {
+ OcrEngine::Custom(ref config) => {
+ perform_ocr_custom(&image, vec![Language::Chinese], config)
+ .await
+ .expect("Custom OCR failed")
+ }
+ _ => panic!("Unexpected OCR engine"),
+ };
+
+ println!("OCR text: {:?}", ocr_text);
+ assert!(
+ ocr_text.contains("管理分支"),
+ "OCR failed to recognize Chinese text: {:?}",
+ ocr_text
+ );
+ }
+}