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
fix inverted transcription and ocr in api stream
Louis Beaumontd48cb3150d06
diff --git a/screenpipe-app-tauri/app/timeline/page.tsx b/screenpipe-app-tauri/app/timeline/page.tsxindex d3276c037..866eabf17 100644--- a/screenpipe-app-tauri/app/timeline/page.tsx+++ b/screenpipe-app-tauri/app/timeline/page.tsx@@ -284,15 +284,27 @@ export default function Timeline() {// Calculate times for both points in local timeconst totalMinutesInDay = 24 * 60;- const startMinutes = (Math.min(dragStart, percentage) / 100) * totalMinutesInDay;- const endMinutes = (Math.max(dragStart, percentage) / 100) * totalMinutesInDay;+ const startMinutes =+ (Math.min(dragStart, percentage) / 100) * totalMinutesInDay;+ const endMinutes =+ (Math.max(dragStart, percentage) / 100) * totalMinutesInDay;// Create local datesconst startLocal = new Date();- startLocal.setHours(Math.floor(startMinutes / 60), Math.floor(startMinutes % 60), 0, 0);-+ startLocal.setHours(+ Math.floor(startMinutes / 60),+ Math.floor(startMinutes % 60),+ 0,+ 0+ );+const endLocal = new Date();- endLocal.setHours(Math.floor(endMinutes / 60), Math.floor(endMinutes % 60), 0, 0);+ endLocal.setHours(+ Math.floor(endMinutes / 60),+ Math.floor(endMinutes % 60),+ 0,+ 0+ );// Convert to UTC for storageconst utcStartDate = new Date(@@ -357,7 +369,7 @@ export default function Timeline() {const relevantFrames = frames.filter((frame) => {const frameTime = new Date(frame.timestamp);- console.log("frameTime", frameTime);+ // console.log("frameTime", frameTime);return (frameTime >= selectionRange.start && frameTime <= selectionRange.end);@@ -413,6 +425,11 @@ export default function Timeline() {},];+ console.log(+ "messages",+ messages.findLast((m) => m.role === "user")?.content+ );+abortControllerRef.current = new AbortController();setIsStreaming(true);@@ -640,12 +657,13 @@ export default function Timeline() {className="absolute top-0 h-full bg-[#0f0] opacity-20"style={{left: `${- ((new Date(selectionRange.start).getHours() * 3600 ++ (new Date(selectionRange.start).getHours() * 3600 +new Date(selectionRange.start).getMinutes() * 60) /- 864)+ 864}%`,width: `${- ((selectionRange.end.getTime() - selectionRange.start.getTime()) /+ ((selectionRange.end.getTime() -+ selectionRange.start.getTime()) /(24 * 3600 * 1000)) *100}%`,diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 44f539c08..216beac6e 100644--- a/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "screenpipe-app"-version = "0.8.4"+version = "0.8.5"description = ""authors = ["you"]license = ""diff --git a/screenpipe-server/examples/timeline_ui_simple/index.html b/screenpipe-server/examples/timeline_ui_simple/index.htmlindex 2b42c3356..1771a12ba 100644--- a/screenpipe-server/examples/timeline_ui_simple/index.html+++ b/screenpipe-server/examples/timeline_ui_simple/index.html@@ -54,6 +54,49 @@background: #222;cursor: pointer;}++ .frame-metadata {+ display: none;+ color: #666;+ white-space: pre-wrap;+ font-size: 12px;+ max-width: 100%;+ overflow-wrap: break-word;+ }++ .frame-container:hover .frame-metadata {+ display: block;+ }++ .metadata-icons {+ display: flex;+ gap: 8px;+ color: #666;+ }++ .icon {+ position: relative;+ cursor: pointer;+ font-size: 14px;+ }++ .tooltip {+ display: none;+ position: absolute;+ bottom: 100%;+ left: 0;+ background: #111;+ padding: 8px;+ border: 1px solid #333;+ border-radius: 4px;+ white-space: pre-wrap;+ max-width: 300px;+ z-index: 1000;+ }++ .icon:hover .tooltip {+ display: block;+ }</style></head><body>@@ -72,7 +115,10 @@function setDefaultTimes() {const end = new Date();- const start = new Date(end - 5 * 60 * 1000);+ end.setMinutes(end.getMinutes() - 2);++ const start = new Date();+ start.setHours(0, 1, 0, 0);document.getElementById('startTime').value = start.toISOString().slice(0, -1);document.getElementById('endTime').value = end.toISOString().slice(0, -1);@@ -82,10 +128,7 @@document.getElementById('frames').innerHTML = '';}- function appendFrame(frame, timestamp) {- console.log('Frame data length:', frame.length);- console.log('First 100 chars:', frame.substring(0, 100));-+ function appendFrame(frame, timestamp, data) {const container = document.createElement('div');container.className = 'frame-container';@@ -102,9 +145,38 @@const ts = document.createElement('div');ts.className = 'frame-timestamp';ts.innerText = new Date(timestamp).toLocaleString();++ const metadata = document.createElement('div');+ metadata.className = 'metadata-icons';++ metadata.innerHTML = `+ <span>window: ${(data && data.window_name) || 'N/A'}</span>+ <span>app: ${(data && data.app_name) || 'N/A'}</span>+ `;++ if (data && data.ocr_text) {+ const ocrIcon = document.createElement('div');+ ocrIcon.className = 'icon';+ ocrIcon.innerHTML = `+ 📝+ <div class="tooltip">OCR: ${data.ocr_text}</div>+ `;+ metadata.appendChild(ocrIcon);+ }++ if (data && data.transcription) {+ const transcriptionIcon = document.createElement('div');+ transcriptionIcon.className = 'icon';+ transcriptionIcon.innerHTML = `+ 🎤+ <div class="tooltip">Transcription: ${data.transcription}</div>+ `;+ metadata.appendChild(transcriptionIcon);+ }container.appendChild(img);container.appendChild(ts);+ container.appendChild(metadata);const frames = document.getElementById('frames');frames.appendChild(container);@@ -116,10 +188,10 @@eventSource.close();}- const startTime = document.getElementById('startTime').value;- const endTime = document.getElementById('endTime').value;+ const startTime = new Date(document.getElementById('startTime').value).toISOString();+ const endTime = new Date(document.getElementById('endTime').value).toISOString();- const url = `http://localhost:3030/stream/frames?start_time=${startTime}Z&end_time=${endTime}Z`;+ const url = `http://localhost:3030/stream/frames?start_time=${encodeURIComponent(startTime)}&end_time=${encodeURIComponent(endTime)}`;console.log('starting stream:', url);eventSource = new EventSource(url);@@ -132,8 +204,8 @@}if (data.frame && data.timestamp) {- console.log('appending frame from:', data.timestamp);- appendFrame(data.frame, data.timestamp);+ console.log('appending frame from:', data.timestamp, data);+ appendFrame(data.frame, data.timestamp, data);}} catch (e) {console.error('Failed to parse frame data:', e);@@ -141,8 +213,8 @@};eventSource.onerror = (error) => {- console.error('sse error:', error);- eventSource.close();+ // console.error('sse error:', error);+ // eventSource.close();};}diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex a60b372db..480bafb17 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -1270,7 +1270,7 @@ async fn stream_frames_handler(let response = StreamFramesResponse {timestamp: frame_info.timestamp,frame: BASE64_STANDARD.encode(&frame_info.data),- file_path: String::new(),+ file_path: frame_info.metadata.file_path,app_name: frame_info.metadata.app_name,window_name: frame_info.metadata.window_name,transcription: frame_info.metadata.transcription,diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rsindex c810cf746..cebc68e41 100644--- a/screenpipe-server/src/video_cache.rs+++ b/screenpipe-server/src/video_cache.rs@@ -32,7 +32,7 @@ use std::num::NonZeroUsize;use std::path::{Path, PathBuf};use std::sync::Arc;use std::time::SystemTime;-use tokio::io::AsyncReadExt;+use tokio::io::{AsyncRead, AsyncReadExt};use tokio::process::Command;use tokio::sync::mpsc::{channel, Sender};use tokio::sync::RwLock;@@ -50,6 +50,7 @@ type FrameChannel = Sender<(DateTime<Utc>, Vec<u8>, FrameMetadata)>;#[derive(Debug, Clone)]pub struct FrameMetadata {+ pub file_path: String,pub app_name: String,pub window_name: String,pub transcription: String,@@ -294,6 +295,10 @@ impl FrameCache {.stderr(std::process::Stdio::piped()).spawn()?;+ // Set 30s timeout for frame extraction+ let extraction_timeout = tokio::time::sleep(tokio::time::Duration::from_secs(30));+ tokio::pin!(extraction_timeout);+let stdout = child.stdout.take()@@ -304,12 +309,8 @@ impl FrameCache {.take().ok_or_else(|| anyhow::anyhow!("failed to get stderr"))?;- tokio::spawn(async move {- let mut reader = BufReader::new(stderr).lines();- while let Ok(Some(line)) = reader.next_line().await {- debug!("ffmpeg: {}", line);- }- });+ // Handle stderr in background+ let stderr_handle = tokio::spawn(Self::log_ffmpeg_output(stderr));let mut reader = BufReader::new(stdout);let frame_extraction = async {@@ -348,12 +349,13 @@ impl FrameCache {window_name: metadata.get(frame_count).map_or("".to_string(), |(_, _, win, _, _)| win.clone()),- transcription: metadata- .get(frame_count)- .map_or("".to_string(), |(_, _, _, trans, _)| trans.clone()),ocr_text: metadata.get(frame_count)- .map_or("".to_string(), |(_, _, _, _, ocr)| ocr.clone()),+ .map_or("".to_string(), |(_, _, _, ocr, _)| ocr.clone()),+ transcription: metadata+ .get(frame_count)+ .map_or("".to_string(), |(_, _, _, _, trans)| trans.clone()),+ file_path: file_path.to_string(),};if let Err(e) = frame_tx@@ -365,7 +367,7 @@ impl FrameCache {if error_count >= MAX_ERRORS {debug!("channel appears closed, stopping extraction");- return Ok(());+ return Ok::<(), anyhow::Error>(());}}@@ -380,13 +382,20 @@ impl FrameCache {Ok(())};- match tokio::time::timeout(std::time::Duration::from_secs(30), frame_extraction).await {- Ok(result) => result,- Err(_) => {- let _ = child.kill().await;- Err(anyhow::anyhow!("frame extraction timed out"))+ tokio::select! {+ _ = &mut extraction_timeout => {+ // Kill the ffmpeg process+ if let Err(e) = child.kill().await {+ error!("failed to kill ffmpeg process: {}", e);+ }+ stderr_handle.abort();+ return Err(anyhow::anyhow!("frame extraction timed out"));}- }?;+ result = frame_extraction => {+ stderr_handle.abort();+ drop(result);+ }+ }let status = child.wait().await?;if !status.success() {@@ -395,6 +404,13 @@ impl FrameCache {Ok(())}+ async fn log_ffmpeg_output(stderr: impl AsyncRead + Unpin) -> Result<()> {+ let mut lines = BufReader::new(stderr).lines();+ while let Some(line) = lines.next_line().await? {+ debug!("ffmpeg: {}", line);+ }+ Ok(())+ }async fn is_video_file_complete(&self, file_path: &str) -> bool {if let Ok(metadata) = tokio::fs::metadata(file_path).await {diff --git a/screenpipe-server/tests/video_cache_test.rs b/screenpipe-server/tests/video_cache_test.rsindex 7840d982c..2f2f90b4e 100644--- a/screenpipe-server/tests/video_cache_test.rs+++ b/screenpipe-server/tests/video_cache_test.rs@@ -36,7 +36,7 @@ async fn setup_test_env() -> Result<(FrameCache, TempDir, Arc<DatabaseManager>)>home_dir().unwrap().join(".screenpipe")- .join("sqlite.db")+ .join("db.sqlite").to_str().unwrap(),)@@ -58,7 +58,7 @@ async fn test_high_speed_streaming() -> Result<()> {let (tx, mut rx) = tokio::sync::mpsc::channel(100);// First, request the frames- cache.get_frames(start_time, 1, tx).await?;+ cache.get_frames(start_time, 1, tx, true).await?;// Then use try_recv in a loop with timeout to collect frameslet timeout = tokio::time::sleep(std::time::Duration::from_secs(5));@@ -97,7 +97,7 @@ async fn test_frame_jpeg_integrity() -> Result<()> {debug!("hi");let (tx, mut rx) = tokio::sync::mpsc::channel(100);- cache.get_frames(target_time, 1, tx).await?;+ cache.get_frames(target_time, 1, tx, true).await?;debug!("bye");let frame = rx.recv().await;@@ -173,7 +173,9 @@ async fn measure_frame_retrieval(let (tx, mut rx) = tokio::sync::mpsc::channel(100);let timer = std::time::Instant::now();- cache.get_frames(start_time, duration_minutes, tx).await?;+ cache+ .get_frames(start_time, duration_minutes, tx, true)+ .await?;// Collect frames with timeoutlet timeout = tokio::time::sleep(std::time::Duration::from_secs(30));@@ -319,3 +321,61 @@ async fn test_extended_time_range_retrieval() -> Result<()> {Ok(())}++#[tokio::test]+async fn test_frame_metadata_integrity() -> Result<()> {+ let (cache, _temp_dir, _db) = setup_test_env().await?;++ // Get frames from last 5 minutes with a 1-minute duration window+ let target_time = Utc::now() - Duration::minutes(5);+ let (tx, mut rx) = tokio::sync::mpsc::channel(100);++ // Request frames with a 1-minute duration+ cache.get_frames(target_time, 2, tx, false).await?;++ let mut found_metadata = false;+ let timeout = tokio::time::sleep(std::time::Duration::from_secs(50));+ tokio::pin!(timeout);++ println!("\nChecking frames for metadata:");+ println!("----------------------------");++ loop {+ tokio::select! {+ frame = rx.recv() => {+ match frame {+ Some(frame) => {+ println!("Frame at: {}", frame.timestamp);+ println!("- App: {}", frame.metadata.app_name);+ println!("- Window: {}", frame.metadata.window_name);+ println!("- Transcription: {}", frame.metadata.transcription);+ println!("- OCR: {}", frame.metadata.ocr_text);+ println!("----------------------------");++ // Check that at least one field has content+ if !frame.metadata.app_name.is_empty()+ || !frame.metadata.window_name.is_empty()+ || !frame.metadata.transcription.is_empty()+ || !frame.metadata.ocr_text.is_empty() {+ found_metadata = true;+ break;+ }+ },+ None => {+ println!("No more frames");+ break;+ }+ }+ }+ _ = &mut timeout => {+ println!("Timeout reached after 5s");+ break;+ }+ }+ }+ assert!(+ found_metadata,+ "should find at least one frame with non-empty metadata"+ );+ Ok(())+}