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
80% #32
Louis Beaumont050aed5111cb
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.tomlindex c6944a374..ebea93c27 100644--- a/screenpipe-audio/Cargo.toml+++ b/screenpipe-audio/Cargo.toml@@ -62,6 +62,7 @@ bytemuck = "1.16.1"[dev-dependencies]tempfile = "3.3.0"infer = "0.15"+tokio = { version = "1.0", features = ["full"] }[features]metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rsindex 627d1e6a7..18bb445f5 100644--- a/screenpipe-audio/src/bin/screenpipe-audio.rs+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs@@ -8,7 +8,12 @@ use screenpipe_audio::list_audio_devices;use screenpipe_audio::parse_device_spec;use screenpipe_audio::record_and_transcribe;use screenpipe_audio::AudioDevice;+use screenpipe_audio::DeviceControl;+use std::collections::HashMap;use std::path::PathBuf;+use std::sync::atomic::AtomicBool;+use std::sync::Arc;+use std::sync::RwLock;use std::thread;use std::time::Duration;@@ -64,9 +69,15 @@ fn main() -> Result<()> {return Err(anyhow!("No audio input devices found"));}- let chunk_duration = Duration::from_secs(30);+ // delete .mp3 files (output*.mp3)+ std::fs::remove_file("output_0.mp3").unwrap_or_default();+ std::fs::remove_file("output_1.mp3").unwrap_or_default();++ let chunk_duration = Duration::from_secs(5);let output_path = PathBuf::from("output.mp3");let (whisper_sender, whisper_receiver) = create_whisper_channel()?;+ let device_controls: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>> =+ Arc::new(RwLock::new(HashMap::new()));// Spawn threads for each devicelet recording_threads: Vec<_> = devices@@ -75,8 +86,25 @@ fn main() -> Result<()> {.map(|(i, device)| {let whisper_sender = whisper_sender.clone();let output_path = output_path.with_file_name(format!("output_{}.mp3", i));+ let device_control = Arc::new(DeviceControl {+ is_running: Arc::new(AtomicBool::new(true)),+ is_paused: Arc::new(AtomicBool::new(false)),+ });++ device_controls+ .write()+ .unwrap()+ .insert(device.to_string(), Arc::clone(&device_control));thread::spawn(move || {- record_and_transcribe(&device, chunk_duration, output_path, whisper_sender)+ let device_control_clone = Arc::clone(&device_control);++ record_and_transcribe(+ &device,+ chunk_duration,+ output_path,+ whisper_sender,+ device_control_clone,+ )})}).collect();diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rsindex 5e9bbd1c3..b2276e795 100644--- a/screenpipe-audio/src/core.rs+++ b/screenpipe-audio/src/core.rs@@ -1,16 +1,22 @@use anyhow::{anyhow, Result};use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};use crossbeam::channel::{Receiver, Sender};-use log::{debug, error, info};+use log::{debug, error, info, warn};use serde::Serialize;use std::fmt;use std::path::PathBuf;-use std::sync::{Arc, Mutex};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;use std::thread;use std::time::Duration;use crate::AudioInput;+pub struct DeviceControl {+ pub is_running: Arc<AtomicBool>,+ pub is_paused: Arc<AtomicBool>,+}+pub struct AudioCaptureResult {pub text: String,}@@ -80,12 +86,9 @@ pub fn parse_device_spec(name: &str) -> Result<DeviceSpec> {use std::io::Write;use std::process::{Command, Stdio};-pub fn record_and_transcribe(+fn get_device_and_config(device_spec: &DeviceSpec,- duration: Duration,- output_path: PathBuf,- whisper_sender: Sender<AudioInput>,-) -> Result<PathBuf> {+) -> Result<(cpal::Device, cpal::SupportedStreamConfig)> {let host = match device_spec {#[cfg(target_os = "macos")]DeviceSpec::Output(_) => cpal::host_from_id(cpal::HostId::ScreenCaptureKit)?,@@ -111,6 +114,17 @@ pub fn record_and_transcribe(.ok_or_else(|| anyhow!("Audio device not found"))?;let config = audio_device.default_input_config()?;+ Ok((audio_device, config))+}++pub fn record_and_transcribe(+ device_spec: &DeviceSpec,+ duration: Duration,+ output_path: PathBuf,+ whisper_sender: Sender<AudioInput>,+ device_control: Arc<DeviceControl>,+) -> Result<PathBuf> {+ let (audio_device, config) = get_device_and_config(device_spec)?;info!("Recording audio device: {}, Config: {:?}",audio_device.name()?,@@ -122,10 +136,18 @@ pub fn record_and_transcribe(let (audio_sender, audio_receiver): (Sender<Vec<u8>>, Receiver<Vec<u8>>) =crossbeam::channel::unbounded();- let is_running = Arc::new(Mutex::new(true));- let is_running_clone = is_running.clone();+ let audio_sender_clone = audio_sender.clone();+ let is_running_clone = Arc::clone(&device_control.is_running);+ let is_running_clone_4 = Arc::clone(&device_control.is_running);+ // TODO what the diff between pause/stop ?+ let _is_paused_clone = Arc::clone(&device_control.is_paused);let output_path_clone = output_path.clone();+ let output_path_clone_2 = output_path.clone();+ let device_spec_clone = device_spec.clone();++ let start_time = std::time::Instant::now();+// Spawn FFmpeg process in a separate threadlet ffmpeg_handle = thread::spawn(move || {let mut ffmpeg = Command::new("ffmpeg")@@ -154,13 +176,18 @@ pub fn record_and_transcribe(let mut stdin = ffmpeg.stdin.take().expect("Failed to open stdin");- while *is_running_clone.lock().unwrap() {+ debug!("FFmpeg process started");++ while is_running_clone.load(Ordering::Relaxed) {if let Ok(data) = audio_receiver.recv_timeout(Duration::from_millis(100)) {if let Err(e) = stdin.write_all(&data) {error!("Failed to write audio data to FFmpeg: {}", e);break;}}+ if start_time.elapsed() >= duration {+ break;+ }}// Close stdin to signal EOF to FFmpeg@@ -179,8 +206,10 @@ pub fn record_and_transcribe(cpal::SampleFormat::F32 => audio_device.build_input_stream(&config.into(),move |data: &[f32], _: &_| {- if let Err(e) = audio_sender.send(bytemuck::cast_slice(data).to_vec()) {- error!("Failed to send audio data: {}", e);+ if is_running_clone_4.load(Ordering::Relaxed) {+ if let Err(e) = audio_sender.try_send(bytemuck::cast_slice(data).to_vec()) {+ warn!("Failed to send audio data: {}", e);+ }}},err_fn,@@ -188,25 +217,45 @@ pub fn record_and_transcribe()?,sample_format => return Err(anyhow!("Unsupported sample format '{}'", sample_format)),};+ debug!("audio stream created");stream.play()?;info!("Recording for {} seconds", duration.as_secs());- thread::sleep(duration);+ while device_control.is_running.load(Ordering::Relaxed) {+ if start_time.elapsed() >= duration {+ break;+ }+ thread::sleep(Duration::from_millis(100));+ }++ info!(+ "Recording stopped, wrote to {}. Now triggering transcription",+ output_path_clone_2.to_str().unwrap()+ );// Stop the stream and signal the recording to stopstream.pause()?;- *is_running.lock().unwrap() = false;++ // Wait for a short time to ensure all data is processed+ // thread::sleep(Duration::from_millis(100));++ // Close the sender to signal the FFmpeg thread to finish+ // drop(audio_sender_clone);// Wait for the FFmpeg thread to finishffmpeg_handle.join().expect("Failed to join FFmpeg thread");+ debug!("FFmpeg thread finished");- whisper_sender.send(AudioInput {- path: output_path.to_str().unwrap().to_string(),- device: device_spec.to_string(),- })?;+ if let Err(e) = whisper_sender.send(AudioInput {+ path: output_path_clone_2.to_str().unwrap().to_string(),+ device: device_spec_clone.to_string(),+ }) {+ error!("Failed to send audio to whisper: {}", e);+ }+ debug!("Sent audio to whisper");- Ok(output_path)+ Ok(output_path_clone_2)}#[derive(Serialize)]diff --git a/screenpipe-audio/src/lib.rs b/screenpipe-audio/src/lib.rsindex 6904729ea..411c1f97b 100644--- a/screenpipe-audio/src/lib.rs+++ b/screenpipe-audio/src/lib.rs@@ -4,6 +4,6 @@ mod pcm_decode;mod stt;pub use core::{default_input_device, default_output_device, list_audio_devices, parse_device_spec,- record_and_transcribe, AudioCaptureResult, AudioDevice, DeviceSpec,+ record_and_transcribe, AudioCaptureResult, AudioDevice, DeviceSpec, DeviceControl};pub use stt::{create_whisper_channel, stt, AudioInput, TranscriptionResult, WhisperModel};diff --git a/screenpipe-audio/tests/core_tests.rs b/screenpipe-audio/tests/core_tests.rsindex f3c50a3d5..34536738a 100644--- a/screenpipe-audio/tests/core_tests.rs+++ b/screenpipe-audio/tests/core_tests.rs@@ -1,14 +1,33 @@#[cfg(test)]mod tests {use chrono::Utc;+ use cpal::traits::StreamTrait;use crossbeam::channel;+ use log::{debug, LevelFilter};use screenpipe_audio::record_and_transcribe;use screenpipe_audio::{default_output_device, list_audio_devices, parse_device_spec, stt, WhisperModel,};use std::path::PathBuf;+ use std::process::Command;+ use std::str::FromStr;+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::sync::Arc;+ use std::thread;use std::time::{Duration, Instant};+ fn setup() {+ // Initialize the logger with an info level filter+ match env_logger::builder()+ .filter_level(log::LevelFilter::Debug)+ .filter_module("tokenizers", LevelFilter::Error)+ .try_init()+ {+ Ok(_) => (),+ Err(_) => (),+ };+ }+// ! what happen in github action?#[test]#[ignore]@@ -26,6 +45,7 @@ mod tests {#[test]#[ignore]fn test_speech_to_text() {+ setup();println!("Starting speech to text test");println!("Loading audio file");@@ -44,16 +64,27 @@ mod tests {#[test]#[ignore] // Add this if you want to skip this test in regular test runsfn test_record_and_transcribe() {+ setup();+// Setuplet device_spec = default_output_device().unwrap();let duration = Duration::from_secs(30); // Record for 3 secondslet time = Utc::now().timestamp_millis();let output_path = PathBuf::from(format!("test_output_{}.mp3", time));let (sender, receiver) = channel::unbounded();+ let is_running = Arc::new(AtomicBool::new(true));// Actlet start_time = Instant::now();- let result = record_and_transcribe(&device_spec, duration, output_path.clone(), sender);+ println!("Starting record_and_transcribe");+ let result = record_and_transcribe(+ &device_spec,+ duration,+ output_path.clone(),+ sender,+ is_running,+ );+ println!("record_and_transcribe completed");let elapsed_time = start_time.elapsed();// Assert@@ -71,6 +102,7 @@ mod tests {// Check if we received the correct AudioInputlet audio_input = receiver.recv_timeout(Duration::from_secs(1)).unwrap();assert_eq!(audio_input.path, output_path.to_str().unwrap());+ println!("Audio input: {:?}", audio_input);// Verify file format (you might need to install the `infer` crate for this)let kind = infer::get_from_path(&output_path).unwrap().unwrap();@@ -83,4 +115,175 @@ mod tests {// Clean upstd::fs::remove_file(output_path).unwrap();}++ #[test]+ #[ignore]+ fn test_record_and_transcribe_interrupt_before_end() {+ setup();++ // Setup+ let device_spec = default_output_device().unwrap();+ let duration = Duration::from_secs(30);+ let time = Utc::now().timestamp_millis();+ let output_path = PathBuf::from(format!("test_output_interrupt_{}.mp3", time));+ let (sender, receiver) = channel::unbounded();+ let is_running = Arc::new(AtomicBool::new(true));+ let is_running_clone = Arc::clone(&is_running);++ // interrupt in 10 seconds+ thread::spawn(move || {+ thread::sleep(Duration::from_secs(10));+ is_running_clone.store(false, Ordering::Relaxed);+ });++ // Act+ let start_time = Instant::now();++ record_and_transcribe(+ &device_spec,+ duration,+ output_path.clone(),+ sender,+ is_running,+ )+ .unwrap();++ let elapsed_time = start_time.elapsed();++ println!("Elapsed time: {:?}", elapsed_time);+ // Assert+ assert!(+ elapsed_time < duration,+ "Recording should have been interrupted before the full duration"+ );+ assert!(+ elapsed_time >= Duration::from_secs(3),+ "Recording should have lasted at least 3 seconds"+ );++ // Check if the file was created+ assert!(output_path.exists(), "Output file should exist");++ // Check if we received the correct AudioInput+ let audio_input = receiver.recv_timeout(Duration::from_secs(1)).unwrap();+ assert_eq!(audio_input.path, output_path.to_str().unwrap());++ // Verify file format+ let kind = infer::get_from_path(&output_path).unwrap().unwrap();+ assert_eq!(+ kind.mime_type(),+ "audio/mpeg",+ "File should be in mp3 format"+ );++ // Verify file duration+ let file_duration = get_audio_duration(&output_path).unwrap();+ assert!(+ file_duration >= Duration::from_secs(3) && file_duration < duration,+ "File duration should be between 3 seconds and the full duration"+ );++ // Clean up+ std::fs::remove_file(output_path).unwrap();+ }++ // Helper function to get audio duration (you'll need to implement this)+ fn get_audio_duration(path: &PathBuf) -> Result<Duration, Box<dyn std::error::Error>> {+ let output = Command::new("ffprobe")+ .args(&[+ "-v",+ "error",+ "-show_entries",+ "format=duration",+ "-of",+ "default=noprint_wrappers=1:nokey=1",+ path.to_str().unwrap(),+ ])+ .output()?;++ let duration_str = String::from_utf8(output.stdout)?;+ let duration_secs = f64::from_str(duration_str.trim())?;++ Ok(Duration::from_secs_f64(duration_secs))+ }++ #[tokio::test]+ #[ignore]+ async fn test_audio_transcription() {+ setup();+ use screenpipe_audio::{create_whisper_channel, record_and_transcribe};+ use std::sync::Arc;+ use std::time::Duration;+ use tokio::time::timeout;++ // 1. start listening to https://music.youtube.com/watch?v=B6WAlAzuJb4&si=775sYWLG0b7XhQIH&t=50+ // 2. run the test+ // 3. the test should succeed (takes ~120s for some reason?) ! i think whisper is just slow as hell on cpu?++ // Setup+ let device_spec = Arc::new(default_output_device().unwrap());+ let output_path =+ PathBuf::from(format!("test_output_{}.mp3", Utc::now().timestamp_millis()));+ let output_path_2 = output_path.clone();+ let (whisper_sender, whisper_receiver) = create_whisper_channel().unwrap();+ let is_running = Arc::new(AtomicBool::new(true));+ // Start recording in a separate thread+ let recording_thread = std::thread::spawn(move || {+ let device_spec = Arc::clone(&device_spec);+ let whisper_sender = whisper_sender.clone();+ record_and_transcribe(+ device_spec.as_ref(),+ Duration::from_secs(15),+ output_path.clone(),+ whisper_sender,+ is_running,+ )+ .unwrap();+ });++ // Wait for the recording to complete (with a timeout)+ let timeout_duration = Duration::from_secs(10); // Adjust as needed+ let result = timeout(timeout_duration, async {+ // Wait for the transcription result+ let transcription_result = whisper_receiver.recv().unwrap();+ debug!("Received transcription: {:?}", transcription_result);+ // Check if we received a valid transcription+ assert!(+ transcription_result.error.is_none(),+ "Transcription error occurred"+ );+ assert!(+ transcription_result.transcription.is_some(),+ "No transcription received"+ );++ let transcription = transcription_result.transcription.unwrap();+ assert!(!transcription.is_empty(), "Transcription is empty");++ println!("Received transcription: {}", transcription);++ assert!(+ transcription.contains("même")+ || transcription.contains("tu m'aimes")+ || transcription.contains("champs")+ );++ transcription+ })+ .await;++ // Check the result+ match result {+ Ok(transcription) => {+ println!("Test passed. Transcription: {}", transcription);+ }+ Err(_) => {+ panic!("Test timed out waiting for transcription");+ }+ }++ // Clean up+ let _ = recording_thread.join();+ std::fs::remove_file(output_path_2).unwrap_or_default();+ }}diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 2131c1188..a2fbe5075 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -83,6 +83,8 @@ reqwest = { version = "0.11", features = ["json"] }criterion = { version = "0.5.1", features = ["async_tokio"] }rand = "0.8"+tower = "0.4"+[[bench]]name = "db_benchmarks"harness = falsediff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 78b22ede9..6d580c58a 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -1,7 +1,8 @@use std::{+ collections::HashMap,fs,net::SocketAddr,- sync::{mpsc::channel, Arc},+ sync::{atomic::AtomicBool, mpsc::channel, Arc, RwLock},time::Duration,};@@ -10,6 +11,7 @@ use colored::Colorize;use log::{info, warn, LevelFilter};use screenpipe_audio::{default_input_device, default_output_device, list_audio_devices, parse_device_spec,+ DeviceControl,};use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server}; // Import the list_audio_devices function@@ -135,8 +137,14 @@ async fn main() -> anyhow::Result<()> {let db_record = db.clone();let db_server = db.clone();- // Channel for controlling the recorder+ // Channel for controlling the recorder ! TODO RENAME SHITlet (_control_tx, control_rx) = channel();+ let vision_control = Arc::new(AtomicBool::new(false));+ let audio_devices_control: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>> =+ Arc::new(RwLock::new(HashMap::new()));++ let vision_control_server_clone = vision_control.clone();+ let audio_devices_control_server_clone = audio_devices_control.clone();// Start continuous recording in a separate tasklet _recording_task = tokio::spawn({@@ -151,13 +159,20 @@ async fn main() -> anyhow::Result<()> {control_rx,!cli.disable_audio,audio_devices,+ vision_control,+ audio_devices_control,).await}});tokio::spawn(async move {- let server = Server::new(db_server, SocketAddr::from(([0, 0, 0, 0], cli.port)));+ let server = Server::new(+ db_server,+ SocketAddr::from(([0, 0, 0, 0], cli.port)),+ vision_control_server_clone,+ audio_devices_control_server_clone,+ );server.start().await.unwrap();});diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex 523042553..25e8cdadf 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -4,10 +4,12 @@ use chrono::Utc;use crossbeam::channel::{Receiver, Sender};use log::{debug, error, info};use screenpipe_audio::{- create_whisper_channel, record_and_transcribe, AudioInput, DeviceSpec, TranscriptionResult,+ create_whisper_channel, record_and_transcribe, AudioInput, DeviceControl, DeviceSpec,+ TranscriptionResult,};+use std::collections::HashMap;use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::Arc;+use std::sync::{Arc, RwLock};use std::thread;use std::time::Duration;use tokio::runtime::Runtime;@@ -25,6 +27,8 @@ pub async fn start_continuous_recording(control_rx: std::sync::mpsc::Receiver<RecorderControl>,enable_audio: bool,audio_devices: Vec<Arc<DeviceSpec>>,+ vision_control: Arc<AtomicBool>,+ audio_devices_control: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,) -> Result<()> {info!("Starting continuous recording");if !enable_audio {@@ -36,9 +40,9 @@ pub async fn start_continuous_recording(let db_manager_video = Arc::clone(&db);let db_manager_audio = Arc::clone(&db);- let is_running = Arc::new(AtomicBool::new(true));- let is_running_video = Arc::clone(&is_running);- let is_running_audio = Arc::clone(&is_running);+ let is_running_video = Arc::clone(&vision_control);+ let is_running_audio = Arc::clone(&vision_control);+ let device_controls_clone = Arc::clone(&audio_devices_control);let output_path_video = Arc::clone(&output_path);let output_path_audio = Arc::clone(&output_path);@@ -57,6 +61,7 @@ pub async fn start_continuous_recording(audio_devices,whisper_sender,whisper_receiver,+ Arc::clone(&audio_devices_control),).await});@@ -70,10 +75,16 @@ pub async fn start_continuous_recording(while let Ok(ctrl) = control_rx.recv() {match ctrl {RecorderControl::Stop => {- is_running.store(false, Ordering::SeqCst);+ vision_control.store(false, Ordering::SeqCst);+ control_all_devices(&device_controls_clone, RecorderControl::Stop);break;}- _ => {} // Handle Pause and Resume if needed+ RecorderControl::Pause => {+ control_all_devices(&device_controls_clone, RecorderControl::Pause)+ }+ RecorderControl::Resume => {+ control_all_devices(&device_controls_clone, RecorderControl::Resume)+ }}}});@@ -131,6 +142,7 @@ async fn record_audio(devices: Vec<Arc<DeviceSpec>>,whisper_sender: Sender<AudioInput>,whisper_receiver: Receiver<TranscriptionResult>,+ device_controls: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,) -> Result<()> {let mut handles = vec![];@@ -142,17 +154,35 @@ async fn record_audio(let whisper_sender_clone = whisper_sender.clone();let whisper_receiver_clone = whisper_receiver.clone();+ let device_control = Arc::new(DeviceControl {+ is_running: Arc::new(AtomicBool::new(true)),+ is_paused: Arc::new(AtomicBool::new(false)),+ });++ device_controls+ .write()+ .unwrap()+ .insert(device_spec.to_string(), Arc::clone(&device_control));+let handle = tokio::spawn(async move {info!("Starting audio capture thread for device: {}",&device_spec_clone);+ let mut iteration = 0;while is_running_clone.load(Ordering::SeqCst) {+ iteration += 1;+ info!(+ "Starting iteration {} for device {}",+ iteration, &device_spec_clone+ );+let recording_thread = thread::spawn({let device_spec_clone = Arc::clone(&device_spec_clone);let output_path_clone = Arc::clone(&output_path_clone);let whisper_sender = whisper_sender_clone.clone();+ let device_control_clone = Arc::clone(&device_control);move || {let new_file_name = Utc::now().format("%Y-%m-%d_%H-%M-%S").to_string();@@ -160,12 +190,22 @@ async fn record_audio("{}/{}_{}.mp3",output_path_clone, device_spec_clone, new_file_name);- record_and_transcribe(+ info!(+ "Starting record_and_transcribe for device {} (iteration {})",+ device_spec_clone, iteration+ );+ let result = record_and_transcribe(device_spec_clone.as_ref(),chunk_duration,file_path.into(),whisper_sender,- )+ device_control_clone,+ );+ info!(+ "Finished record_and_transcribe for device {} (iteration {})",+ device_spec_clone, iteration+ );+ result}});@@ -173,20 +213,54 @@ async fn record_audio(match recording_thread.join() {Ok(Ok(file_path)) => {info!(- "Recording complete for device {}: {:?}",- device_spec_clone, file_path+ "Recording complete for device {} (iteration {}): {:?}",+ device_spec_clone, iteration, file_path);let whisper_receiver = whisper_receiver_clone.clone();// Process the recorded chunk- if let Ok(transcription) = whisper_receiver.recv() {- process_audio_result(&db_clone, transcription).await;+ match whisper_receiver.recv() {+ Ok(transcription) => {+ info!(+ "Received transcription for device {} (iteration {})",+ device_spec_clone, iteration+ );+ process_audio_result(&db_clone, transcription).await;+ }+ Err(e) => error!(+ "Failed to receive transcription for device {} (iteration {}): {}",+ device_spec_clone, iteration, e+ ),}}- Ok(Err(e)) => error!("Error in record_and_transcribe: {}", e),- Err(e) => error!("Thread panicked: {:?}", e),+ Ok(Err(e)) => error!(+ "Error in record_and_transcribe for device {} (iteration {}): {}",+ device_spec_clone, iteration, e+ ),+ Err(e) => error!(+ "Thread panicked for device {} (iteration {}): {:?}",+ device_spec_clone, iteration, e+ ),}++ if !device_control.is_running.load(Ordering::SeqCst) {+ info!(+ "Device control signaled stop for device {} after iteration {}",+ device_spec_clone, iteration+ );+ break;+ }++ info!(+ "Finished iteration {} for device {}",+ iteration, &device_spec_clone+ );}++ info!(+ "Exiting audio capture thread for device: {}",+ &device_spec_clone+ );});handles.push(handle);@@ -233,3 +307,17 @@ async fn process_audio_result(db: &DatabaseManager, result: TranscriptionResult)),}}++pub fn control_all_devices(+ device_controls: &Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,+ command: RecorderControl,+) {+ let controls = device_controls.read();+ for control in controls.unwrap().values() {+ match command {+ RecorderControl::Pause => control.is_paused.store(true, Ordering::SeqCst),+ RecorderControl::Resume => control.is_paused.store(false, Ordering::SeqCst),+ RecorderControl::Stop => control.is_running.store(false, Ordering::SeqCst),+ }+ }+}diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex 610098a6f..925f4dc8c 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -1,11 +1,11 @@mod core;mod db;+mod resource_monitor;mod server;mod video;-mod resource_monitor;pub use core::{start_continuous_recording, RecorderControl};pub use db::{ContentType, DatabaseManager, SearchResult};+pub use resource_monitor::ResourceMonitor;pub use server::Server;pub use video::{extract_frames_from_video, VideoCapture};-pub use resource_monitor::ResourceMonitor;\ No newline at end of filediff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex dc9de768f..a7ad5e6df 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -1,8 +1,8 @@use axum::{- extract::{Query, State},+ extract::{Path, Query, State},http::StatusCode,response::Json as JsonResponse,- routing::get,+ routing::{get, post},serve, Router,};@@ -10,18 +10,30 @@ use chrono::{DateTime, Utc};use log::{error, info};use serde::{Deserialize, Serialize};use serde_json::json;-use std::{net::SocketAddr, sync::Arc};+use std::{+ collections::HashMap,+ net::SocketAddr,+ sync::{+ atomic::{AtomicBool, Ordering},+ Arc, RwLock,+ },+};use tokio::net::TcpListener;use tower_http::cors::CorsLayer;use crate::{ContentType, DatabaseManager, SearchResult};+use screenpipe_audio::DeviceControl;+// App state-struct AppState {+pub(crate) struct AppState {db: Arc<DatabaseManager>,+ vision_control: Arc<AtomicBool>,+ audio_devices_control: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,}+// Request structs#[derive(Deserialize)]-struct SearchQuery {+pub(crate) struct SearchQuery {q: Option<String>,#[serde(flatten)]pagination: PaginationQuery,@@ -30,7 +42,7 @@ struct SearchQuery {}#[derive(Deserialize)]-struct PaginationQuery {+pub(crate) struct PaginationQuery {#[serde(default = "default_limit")]#[serde(deserialize_with = "deserialize_number_from_string")]limit: u32,@@ -39,7 +51,6 @@ struct PaginationQuery {offset: u32,}-// Add this function somewhere in your codefn deserialize_number_from_string<'de, D>(deserializer: D) -> Result<u32, D::Error>whereD: serde::Deserializer<'de>,@@ -95,12 +106,23 @@ struct AudioContent {offset_index: i64,}+#[derive(Serialize)]+struct DeviceStatus {+ id: String,+ is_running: bool,+}++#[derive(Serialize)]+struct RecordingStatus {+ is_running: bool,+}+// Helper functionsfn default_limit() -> u32 {20}-async fn search(+pub(crate) async fn search(Query(query): Query<SearchQuery>,State(state): State<Arc<AppState>>,) -> Result<@@ -155,57 +177,83 @@ async fn search(},}))}+pub(crate) async fn start_device(+ Path(device_id): Path<String>,+ State(state): State<Arc<AppState>>,+) -> Result<JsonResponse<DeviceStatus>, (StatusCode, JsonResponse<serde_json::Value>)> {+ let device_controls = state.audio_devices_control.read().unwrap();+ if let Some(device_control) = device_controls.get(&device_id) {+ device_control.is_paused.store(false, Ordering::SeqCst);+ device_control.is_running.store(true, Ordering::SeqCst);+ Ok(JsonResponse(DeviceStatus {+ id: device_id,+ is_running: true,+ }))+ } else {+ Err((+ StatusCode::NOT_FOUND,+ JsonResponse(json!({"error": "Device not found"})),+ ))+ }+}-async fn get_by_date_range(- Query(query): Query<DateRangeQuery>,+pub(crate) async fn stop_device(+ Path(device_id): Path<String>,State(state): State<Arc<AppState>>,-) -> Result<- JsonResponse<PaginatedResponse<ContentItem>>,- (StatusCode, JsonResponse<serde_json::Value>),-> {- info!(- "Received date range request: start_date={:?}, end_date={:?}, limit={}, offset={}",- query.start_date, query.end_date, query.pagination.limit, query.pagination.offset- );+) -> Result<JsonResponse<DeviceStatus>, (StatusCode, JsonResponse<serde_json::Value>)> {+ let device_controls = state.audio_devices_control.read().unwrap();+ if let Some(device_control) = device_controls.get(&device_id) {+ device_control.is_running.store(false, Ordering::SeqCst);+ device_control.is_paused.store(true, Ordering::SeqCst);+ Ok(JsonResponse(DeviceStatus {+ id: device_id,+ is_running: false,+ }))+ } else {+ Err((+ StatusCode::NOT_FOUND,+ JsonResponse(json!({"error": "Device not found"})),+ ))+ }+}- let results = state- .db- .get_recent_results(- query.pagination.limit,- query.pagination.offset,- query.start_date,- query.end_date,- )- .await- .map_err(|e| {- error!("Database error while fetching recent results: {}", e);- (- StatusCode::INTERNAL_SERVER_ERROR,- JsonResponse(json!({"error": format!("Database error: {}", e)})),- )- })?;+pub(crate) async fn start_recording(+ State(state): State<Arc<AppState>>,+) -> JsonResponse<RecordingStatus> {+ state.vision_control.store(true, Ordering::SeqCst);+ JsonResponse(RecordingStatus { is_running: true })+}- let total = state- .db- .count_recent_results(query.start_date, query.end_date)- .await- .map_err(|e| {- error!("Database error while counting recent results: {}", e);- (- StatusCode::INTERNAL_SERVER_ERROR,- JsonResponse(json!({"error": format!("Database error: {}", e)})),- )- })?;+pub(crate) async fn stop_recording(+ State(state): State<Arc<AppState>>,+) -> JsonResponse<RecordingStatus> {+ state.vision_control.store(false, Ordering::SeqCst);+ JsonResponse(RecordingStatus { is_running: false })+}- info!("Date range query completed: found {} results", total);- Ok(JsonResponse(PaginatedResponse {- data: results.into_iter().map(into_content_item).collect(),- pagination: PaginationInfo {- limit: query.pagination.limit,- offset: query.pagination.offset,- total: total as i64,- },- }))+pub(crate) async fn get_recording_status(+ State(state): State<Arc<AppState>>,+) -> JsonResponse<RecordingStatus> {+ let is_running = state.vision_control.load(Ordering::SeqCst);+ JsonResponse(RecordingStatus { is_running })+}++pub(crate) async fn get_device_status(+ Path(device_id): Path<String>,+ State(state): State<Arc<AppState>>,+) -> Result<JsonResponse<DeviceStatus>, (StatusCode, JsonResponse<serde_json::Value>)> {+ let device_controls = state.audio_devices_control.read().unwrap();+ if let Some(device_control) = device_controls.get(&device_id) {+ Ok(JsonResponse(DeviceStatus {+ id: device_id,+ is_running: device_control.is_running.load(Ordering::SeqCst),+ }))+ } else {+ Err((+ StatusCode::NOT_FOUND,+ JsonResponse(json!({"error": "Device not found"})),+ ))+ }}// Helper functions@@ -231,30 +279,46 @@ fn into_content_item(result: SearchResult) -> ContentItem {pub struct Server {db: Arc<DatabaseManager>,addr: SocketAddr,+ vision_control: Arc<AtomicBool>,+ audio_devices_control: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,}impl Server {- pub fn new(db: Arc<DatabaseManager>, addr: SocketAddr) -> Self {- Server { db, addr }+ pub fn new(+ db: Arc<DatabaseManager>,+ addr: SocketAddr,+ vision_control: Arc<AtomicBool>,+ audio_devices_control: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,+ ) -> Self {+ Server {+ db,+ addr,+ vision_control,+ audio_devices_control,+ }}pub async fn start(self) -> Result<(), std::io::Error> {- let app_state = Arc::new(AppState { db: self.db });+ let app_state = Arc::new(AppState {+ db: self.db,+ vision_control: self.vision_control,+ audio_devices_control: self.audio_devices_control,+ });let app = Router::new().route("/search", get(search))- .route("/recent", get(get_by_date_range))+ .route("/device/:id/start", post(start_device))+ .route("/device/:id/stop", post(stop_device))+ .route("/device/:id/status", get(get_device_status))+ .route("/recording/start", post(start_recording))+ .route("/recording/stop", post(stop_recording))+ .route("/recording/status", get(get_recording_status)).layer(CorsLayer::permissive()).with_state(app_state);info!("Starting server on {}", self.addr);- match serve(- TcpListener::bind(self.addr).await.unwrap(),- app.into_make_service(),- )- .await- {+ match serve(TcpListener::bind(self.addr).await?, app.into_make_service()).await {Ok(_) => {info!("Server stopped gracefully");Ok(())@@ -267,20 +331,39 @@ impl Server {}}+// Curl commands for reference:// # 1. Basic search query-// curl "http://localhost:3030/search?q=test&limit=5&offset=0"+// # curl "http://localhost:3030/search?q=test&limit=5&offset=0"// # 2. Search with content type filter (OCR)-// curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=ocr"+// # curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=ocr"// # 3. Search with content type filter (Audio)-// curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=audio"+// # curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=audio"// # 4. Search with pagination-// curl "http://localhost:3030/search?q=test&limit=10&offset=20"+// # curl "http://localhost:3030/search?q=test&limit=10&offset=20"++// # 5. Get recent results with date range+// # curl "http://localhost:3030/recent?limit=5&offset=0&start_date=2024-07-02T14:00:00&end_date=2024-07-02T23:59:59"++// # 6. Search with no query (should return all results)+// # curl "http://localhost:3030/search?limit=5&offset=0"++// # 7. Start a device+// # curl -X POST "http://localhost:3030/device/device1/start"++// # 8. Stop a device+// # curl -X POST "http://localhost:3030/device/device1/stop"++// # 9. Get device status+// # curl "http://localhost:3030/device/device1/status"++// # 10. Start recording+// # curl -X POST "http://localhost:3030/recording/start"-// # 6. Get recent results with date range-// curl "http://localhost:3030/recent?limit=5&offset=0&start_date=2024-07-02T14:00:00&end_date=2024-07-02T23:59:59"+// # 11. Stop recording+// # curl -X POST "http://localhost:3030/recording/stop"-// # 9. Search with no query (should return all results)-// curl "http://localhost:3030/search?limit=5&offset=0"+// # 12. Get recording status+// # curl "http://localhost:3030/recording/status"diff --git a/screenpipe-server/tests/start_stop.rs b/screenpipe-server/tests/start_stop.rsnew file mode 100644index 000000000..d5449a567--- /dev/null+++ b/screenpipe-server/tests/start_stop.rs@@ -0,0 +1,208 @@+use axum::{+ body::Body,+ http::{Request, StatusCode},+ routing::Router,+};+use screenpipe_server::RecorderControl;+use screenpipe_server::{+ get_device_status, get_recording_status, start_device, start_recording, stop_device,+ stop_recording, AppState,+};+use serde_json::json;+use std::collections::HashMap;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, RwLock};+use tower::util::ServiceExt;++// Mock DeviceControl for testing+struct MockDeviceControl {+ is_running: AtomicBool,+ sender: Option<std::sync::mpsc::Sender<RecorderControl>>,+}++impl DeviceControl {+ fn new() -> Self {+ let (sender, _receiver) = std::sync::mpsc::channel();+ Self {+ is_running: AtomicBool::new(false),+ sender: Some(sender),+ }+ }++ fn is_running(&self) -> bool {+ self.is_running.load(Ordering::SeqCst)+ }++ fn sender(&self) -> Option<&std::sync::mpsc::Sender<RecorderControl>> {+ self.sender.as_ref()+ }+}++fn create_test_app() -> Router {+ let db = Arc::new(DatabaseManager::new("test_db_url").unwrap());+ let is_running = Arc::new(AtomicBool::new(false));+ let device_controls = Arc::new(RwLock::new(HashMap::new()));+ device_controls+ .write()+ .unwrap()+ .insert("test_device".to_string(), Arc::new(DeviceControl::new()));++ let app_state = Arc::new(AppState {+ db,+ is_running,+ device_controls,+ });++ Router::new()+ .route("/device/:id/start", axum::routing::post(start_device))+ .route("/device/:id/stop", axum::routing::post(stop_device))+ .route("/device/:id/status", axum::routing::get(get_device_status))+ .route("/recording/start", axum::routing::post(start_recording))+ .route("/recording/stop", axum::routing::post(stop_recording))+ .route(+ "/recording/status",+ axum::routing::get(get_recording_status),+ )+ .with_state(app_state)+}++#[tokio::test]+async fn test_start_device() {+ let app = create_test_app();++ let response = app+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/device/test_device/start")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);++ let body = hyper::body::to_bytes(response.into_body()).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();++ assert_eq!(json["id"], "test_device");+ assert_eq!(json["is_running"], true);+}++#[tokio::test]+async fn test_stop_device() {+ let app = create_test_app();++ let response = app+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/device/test_device/stop")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);++ let body = hyper::body::to_bytes(response.into_body()).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();++ assert_eq!(json["id"], "test_device");+ assert_eq!(json["is_running"], false);+}++#[tokio::test]+async fn test_get_device_status() {+ let app = create_test_app();++ let response = app+ .oneshot(+ Request::builder()+ .method("GET")+ .uri("/device/test_device/status")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);++ let body = hyper::body::to_bytes(response.into_body()).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();++ assert_eq!(json["id"], "test_device");+ assert!(json["is_running"].is_boolean());+}++#[tokio::test]+async fn test_start_recording() {+ let app = create_test_app();++ let response = app+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/recording/start")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);++ let body = hyper::body::to_bytes(response.into_body()).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();++ assert_eq!(json["is_running"], true);+}++#[tokio::test]+async fn test_stop_recording() {+ let app = create_test_app();++ let response = app+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/recording/stop")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);++ let body = hyper::body::to_bytes(response.into_body()).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();++ assert_eq!(json["is_running"], false);+}++#[tokio::test]+async fn test_get_recording_status() {+ let app = create_test_app();++ let response = app+ .oneshot(+ Request::builder()+ .method("GET")+ .uri("/recording/status")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);++ let body = hyper::body::to_bytes(response.into_body()).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();++ assert!(json["is_running"].is_boolean());+}