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

refactor: screenpipe audio `AudioManager` (#1492)

Ezra Ellette9590e24fa487
diff --git a/.cargo/config.toml b/.cargo/config.toml
index dfae75492..602bea661 100644
--- a/.cargo/config.toml
+++ b/.cargo/config.toml
@@ -16,4 +16,5 @@ rustflags = [
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "link-arg=-Wl,--allow-multiple-definition"]
-
+[target.aarch64-apple-darwin]
+rustflags = "-lc++ -l framework=Accelerate"
diff --git a/Cargo.toml b/Cargo.toml
index 3d5007686..d33971941 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,6 +6,7 @@ members = [
"screenpipe-server",
"screenpipe-integrations",
"screenpipe-events",
+ "screenpipe-db",
]
exclude = ["screenpipe-app-tauri/src-tauri"]
resolver = "2"
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.toml
index 3b7ac7a71..b37c4ee13 100644
--- a/screenpipe-audio/Cargo.toml
+++ b/screenpipe-audio/Cargo.toml
@@ -31,12 +31,7 @@ clap = { version = "4.3", features = ["derive"] }
chrono = { version = "0.4.31", features = ["serde"] }
# Local Embeddings + STT
-# TODO: feature metal, cuda, etc. see https://github.com/huggingface/candle/blob/main/candle-core/Cargo.toml
-candle = { workspace = true }
-candle-nn = { workspace = true }
-candle-transformers = { workspace = true }
vad-rs = "0.1.4"
-tokenizers = { workspace = true }
anyhow = "1.0.86"
byteorder = "1.5.0"
hf-hub = "0.3.2"
@@ -44,6 +39,9 @@ hf-hub = "0.3.2"
symphonia = { version = "0.5.4", features = ["aac", "isomp4", "opt-simd"] }
rand = "0.8.5"
rubato = "0.15.0"
+whisper-rs = { git = "https://github.com/tazz4843/whisper-rs.git", rev = "e0597486400ec436669e6ee3d8cc94b3859355f5", features = [
+ "tracing_backend",
+] } # pin revision to avoid breaking changes
# Log
log = { workspace = true }
@@ -55,6 +53,7 @@ bytemuck = "1.16.1"
# Async
tokio = { workspace = true }
+tokio-stream = "0.1.17"
# Detect speech/silence
webrtc-vad = "0.4.0"
@@ -64,6 +63,7 @@ reqwest = { workspace = true }
screenpipe-core = { path = "../screenpipe-core" }
screenpipe-events = { path = "../screenpipe-events" }
+screenpipe-db = { path = "../screenpipe-db" }
# crossbeam
crossbeam = { workspace = true }
@@ -82,6 +82,7 @@ ort-sys = "=2.0.0-rc.8"
futures = "0.3.31"
deepgram = "0.6.4"
bytes = { version = "1.9.0", features = ["serde"] }
+num-traits = "0.2.19"
[target.'cfg(target_os = "windows")'.dependencies]
ort = { version = "=2.0.0-rc.6", features = [
@@ -108,13 +109,12 @@ tracing-subscriber = "0.3.16"
[features]
-metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]
-cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]
-mkl = ["candle/mkl", "candle-nn/mkl", "candle-transformers/mkl"]
+metal = ["whisper-rs/metal"]
+cuda = ["whisper-rs/cuda"]
-[[bin]]
+[[example]]
name = "screenpipe-audio"
-path = "src/bin/screenpipe-audio.rs"
+path = "examples/screenpipe-audio.rs"
[[bench]]
name = "pcm_decode_benchmark"
diff --git a/screenpipe-audio/benches/pcm_decode_benchmark.rs b/screenpipe-audio/benches/pcm_decode_benchmark.rs
index edd593ded..135299960 100644
--- a/screenpipe-audio/benches/pcm_decode_benchmark.rs
+++ b/screenpipe-audio/benches/pcm_decode_benchmark.rs
@@ -1,6 +1,6 @@
// cargo bench --bench pcm_decode_benchmark
use criterion::{black_box, criterion_group, criterion_main, Criterion};
-use screenpipe_audio::pcm_decode::pcm_decode;
+use screenpipe_audio::pcm_decode;
use std::path::PathBuf;
fn benchmark_pcm_decode(c: &mut Criterion) {
diff --git a/screenpipe-audio/benches/record_and_transcribe_benchmark.rs b/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
index ae81a7db3..29a4167d9 100644
--- a/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
+++ b/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
@@ -1,9 +1,8 @@
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
-use screenpipe_audio::vad_engine::VadSensitivity;
-use screenpipe_audio::{
- create_whisper_channel, default_input_device, record_and_transcribe, AudioDevice, AudioInput,
- AudioStream, AudioTranscriptionEngine,
-};
+use screenpipe_audio::core::device::{default_input_device, AudioDevice};
+use screenpipe_audio::core::record_and_transcribe;
+use screenpipe_audio::core::stream::AudioStream;
+use screenpipe_audio::AudioInput;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
@@ -17,18 +16,7 @@ async fn setup_test() -> (
) {
let audio_device = default_input_device().unwrap(); // TODO feed voice in automatically somehow
let output_path = PathBuf::from("/tmp/test_audio.mp4");
- // let (whisper_sender, _) = mpsc::unbounded_channel();
- let (whisper_sender, _, _) = create_whisper_channel(
- Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),
- screenpipe_audio::VadEngineEnum::Silero,
- None,
- &output_path,
- VadSensitivity::High,
- vec![],
- None,
- )
- .await
- .unwrap();
+ let (whisper_sender, _) = crossbeam::channel::bounded(1000);
let is_running = Arc::new(AtomicBool::new(true));
(
@@ -66,7 +54,7 @@ fn bench_record_and_transcribe(c: &mut Criterion) {
let result = record_and_transcribe(
black_box(Arc::new(audio_stream)),
black_box(duration),
- black_box(whisper_sender),
+ black_box(Arc::new(whisper_sender)),
black_box(is_running),
)
.await;
diff --git a/screenpipe-audio/examples/screenpipe-audio.rs b/screenpipe-audio/examples/screenpipe-audio.rs
new file mode 100644
index 000000000..4ce499428
--- /dev/null
+++ b/screenpipe-audio/examples/screenpipe-audio.rs
@@ -0,0 +1,92 @@
+use std::sync::Arc;
+
+use anyhow::Result;
+use clap::Parser;
+use futures::pin_mut;
+use screenpipe_audio::{audio_manager::AudioManagerBuilder, core::device::list_audio_devices};
+use screenpipe_core::Language;
+use screenpipe_db::DatabaseManager;
+use tokio::signal::{self};
+
+#[derive(Parser, Debug)]
+#[clap(author, version, about, long_about = None)]
+struct Args {
+ #[clap(
+ short,
+ long,
+ help = "Audio device name (can be specified multiple times)"
+ )]
+ audio_device: Vec<String>,
+
+ #[clap(long, help = "List available audio devices")]
+ list_audio_devices: bool,
+
+ #[clap(long, help = "Audio chunk duration in seconds")]
+ audio_chunk_duration: f32,
+
+ #[clap(long, help = "Deepgram API key")]
+ deepgram_api_key: Option<String>,
+
+ #[clap(short = 'l', long, value_enum)]
+ language: Vec<Language>,
+}
+
+fn print_devices(devices: &[String]) {
+ println!("Available audio devices:");
+ for device in devices.iter() {
+ println!(" {}", device);
+ }
+
+ #[cfg(target_os = "macos")]
+ println!("On macOS, it's not intuitive but output devices are your displays");
+}
+
+// ! usage - cargo run --bin screenpipe-audio -- --audio-device "Display 1 (output)"
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ use env_logger::Builder;
+ use log::LevelFilter;
+
+ Builder::new()
+ .filter(None, LevelFilter::Info)
+ .filter_module("tokenizers", LevelFilter::Error)
+ .init();
+
+ let args = Args::parse();
+
+ let languages = args.language;
+
+ let devices = list_audio_devices()
+ .await?
+ .iter()
+ .map(|d| d.to_string())
+ .collect::<Vec<String>>();
+
+ if args.list_audio_devices {
+ print_devices(&devices);
+ return Ok(());
+ }
+
+ let ctrl_c_future = signal::ctrl_c();
+ pin_mut!(ctrl_c_future);
+
+ let db = DatabaseManager::new("sqlite::memory:").await?;
+
+ let mut builder = AudioManagerBuilder::new()
+ .languages(languages)
+ .enabled_devices(args.audio_device)
+ .output_path("/tmp/screenpipe".into());
+
+ let manager = builder.build(Arc::new(db)).await?;
+
+ manager.start().await?;
+
+ tokio::select! {
+ _ = ctrl_c_future => {
+ manager.stop().await?;
+ }
+ }
+
+ Ok(())
+}
diff --git a/screenpipe-audio/examples/stt.rs b/screenpipe-audio/examples/stt.rs
deleted file mode 100644
index 9c73e6716..000000000
--- a/screenpipe-audio/examples/stt.rs
+++ /dev/null
@@ -1,153 +0,0 @@
-use futures::future::join_all;
-use screenpipe_audio::pyannote::embedding::EmbeddingExtractor;
-use screenpipe_audio::pyannote::identify::EmbeddingManager;
-use screenpipe_audio::stt::{prepare_segments, stt};
-use screenpipe_audio::vad_engine::{SileroVad, VadEngine};
-use screenpipe_audio::whisper::WhisperModel;
-use screenpipe_audio::{AudioInput, AudioTranscriptionEngine};
-use screenpipe_core::Language;
-use std::path::PathBuf;
-use std::sync::Arc;
-use strsim::levenshtein;
-use tokio::sync::Mutex;
-use tracing::debug;
-
-#[tokio::main]
-async fn main() {
- // Initialize tracing
- // tracing_subscriber::fmt()
- // .with_max_level(tracing::Level::DEBUG)
- // .init();
-
- debug!("starting transcription accuracy test");
-
- // Setup
- let test_cases = vec![
- (
- "test_data/accuracy1.wav",
- r#"yo louis, here's the tldr of that mind-blowing meeting. bob's cat walked across his keyboard 3 times. productivity increased by 200%. sarah's virtual background glitched, revealing she was actually on a beach. no one noticed. you successfully pretended to be engaged while scrolling twitter. achievement unlocked! 7 people said "you're on mute" in perfect synchronization. new world record. meeting could've been an email. shocking. key takeaway: we're all living in a simulation, and the devs are laughing. peace out, llama3.2:3b-instruct-q4_k_m"#,
- ),
- (
- "test_data/accuracy2.wav",
- r#"bro - got some good stuff from screenpipe here's the lowdown on your day, you productivity ninja: absolutely demolished that 2-hour coding sesh on the new feature. the keyboard is still smoking, bro! crushed 3 client calls like a boss. they're probably writing love letters to you as we speak, make sure to close john tomorrow 8.00 am according to our notes, let the cash flow in! spent 45 mins on slack. 90% memes, 10% actual work. perfectly balanced, as all things should bewatched a rust tutorial. way to flex those brain muscles, you nerd! overall, you're killing it! 80% of your time on high-value tasks. the other 20%? probably spent admiring your own reflection, you handsome devil. ps: seriously, quit tiktok. your fbi agent is getting bored watching you scroll endlessly. what's the plan for tomorrow? more coding? more memes? world domination? generated by your screenpipe ai assistant (who's definitely not planning to take over the world... yet)"#,
- ),
- (
- "test_data/accuracy3.wav",
- r#"again, screenpipe allows you to get meeting summaries, locally, without leaking data to openai, with any apps, like whatsapp, meet, zoom, etc. and it's open source at github.com/mediar-ai/screenpipe"#,
- ),
- (
- "test_data/accuracy4.wav",
- r#"eventually but, i mean, i feel like but, i mean, first, i mean, you think your your vision smart will be interesting because, yeah, you install once. you pay us, you install once. that that yours. so, basically, all the time microsoft explained, you know, ms office, long time ago, you just buy the the the software that you can using there forever unless you wanna you wanna update upgrade is the better version. right? so it's a little bit, you know"#,
- ),
- (
- "test_data/accuracy5.wav",
- r#"thank you. yeah. so i cannot they they took it, refresh because of my one set top top time. and, also, second thing is, your byte was stolen. by the time?"#,
- ),
- // Add more test cases as needed
- ];
-
- let whisper_model = Arc::new(Mutex::new(
- WhisperModel::new(&AudioTranscriptionEngine::WhisperLargeV3Turbo).unwrap(),
- ));
- let vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>> =
- Arc::new(Mutex::new(Box::new(SileroVad::new().await.unwrap())));
-
- let project_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
- let segmentation_model_path = project_dir
- .join("models")
- .join("pyannote")
- .join("segmentation-3.0.onnx");
-
- let embedding_model_path = project_dir
- .join("models")
- .join("pyannote")
- .join("wespeaker_en_voxceleb_CAM++.onnx");
-
- let embedding_extractor = Arc::new(std::sync::Mutex::new(
- EmbeddingExtractor::new(embedding_model_path.to_str().unwrap()).unwrap(),
- ));
- let embedding_manager = EmbeddingManager::new(usize::MAX);
-
- let mut tasks = Vec::new();
-
- for (audio_file, expected_transcription) in test_cases {
- let whisper_model = Arc::clone(&whisper_model);
- let vad_engine = Arc::clone(&vad_engine);
- let segmentation_model_path = segmentation_model_path.clone();
- let embedding_extractor = Arc::clone(&embedding_extractor);
- let embedding_manager = embedding_manager.clone();
-
- let task = tokio::spawn(async move {
- let audio_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(audio_file);
- let audio_data =
- screenpipe_audio::pcm_decode(&audio_path).expect("Failed to decode audio file");
-
- let audio_input = AudioInput {
- data: Arc::new(audio_data.0),
- sample_rate: 44100, // hardcoded based on test data sample rate
- channels: 1,
- device: Arc::new(screenpipe_audio::default_input_device().unwrap()),
- };
-
- let (mut segments, _) = prepare_segments(
- &audio_input.data,
- vad_engine.clone(),
- &segmentation_model_path,
- embedding_manager,
- embedding_extractor,
- &audio_input.device.to_string(),
- )
- .await
- .unwrap();
- let mut whisper_model_guard = whisper_model.lock().await;
-
- let mut transcription = String::new();
- while let Some(segment) = segments.recv().await {
- let transcript = stt(
- &segment.samples,
- audio_input.sample_rate,
- &audio_input.device.to_string(),
- &mut whisper_model_guard,
- Arc::new(AudioTranscriptionEngine::WhisperLargeV3Turbo),
- None,
- vec![Language::English],
- )
- .await
- .unwrap();
-
- transcription.push_str(&transcript);
- }
- drop(whisper_model_guard);
-
- let distance = levenshtein(expected_transcription, &transcription.to_lowercase());
- let accuracy = 1.0 - (distance as f64 / expected_transcription.len() as f64);
-
- (audio_file, expected_transcription, transcription, accuracy)
- });
-
- tasks.push(task);
- }
-
- let results = join_all(tasks).await;
-
- let mut total_accuracy = 0.0;
- let mut total_tests = 0;
-
- for result in results {
- let (audio_file, expected_transcription, transcription, accuracy) = result.unwrap();
-
- println!("file: {}", audio_file);
- println!("expected: {}", expected_transcription);
- println!("actual: {}", transcription);
- println!("accuracy: {:.2}%", accuracy * 100.0);
- // println!();
-
- total_accuracy += accuracy;
- total_tests += 1;
- }
-
- let average_accuracy = total_accuracy / total_tests as f64;
- println!("average accuracy: {:.2}%", average_accuracy * 100.0);
-
- assert!(average_accuracy > 0.55, "average accuracy is below 55%");
-}
diff --git a/screenpipe-audio/src/audio_manager/builder.rs b/screenpipe-audio/src/audio_manager/builder.rs
new file mode 100644
index 000000000..a99e852a0
--- /dev/null
+++ b/screenpipe-audio/src/audio_manager/builder.rs
@@ -0,0 +1,183 @@
+use anyhow::Result;
+use std::{collections::HashSet, env, path::PathBuf, sync::Arc, time::Duration};
+
+use screenpipe_core::Language;
+use screenpipe_db::DatabaseManager;
+
+use crate::{
+ core::{
+ device::{default_input_device, default_output_device},
+ engine::AudioTranscriptionEngine,
+ },
+ transcription::deepgram::CUSTOM_DEEPGRAM_API_TOKEN,
+ vad::{VadEngineEnum, VadSensitivity},
+};
+
+use crate::audio_manager::AudioManager;
+
+#[derive(Clone)]
+pub struct AudioManagerOptions {
+ pub transcription_engine: Arc<AudioTranscriptionEngine>,
+ pub vad_engine: VadEngineEnum,
+ pub languages: Vec<Language>,
+ pub deepgram_api_key: Option<String>,
+ pub enable_diarization: bool,
+ pub enable_realtime: bool,
+ pub audio_chunk_duration: Duration,
+ pub vad_sensitivity: VadSensitivity,
+ pub health_check_grace_period: u64,
+ pub enabled_devices: HashSet<String>,
+ pub use_all_devices: bool,
+ pub db_path: Option<String>,
+ pub deepgram_url: Option<String>,
+ pub deepgram_websocket_url: Option<String>,
+ pub output_path: Option<PathBuf>,
+}
+
+impl Default for AudioManagerOptions {
+ fn default() -> Self {
+ let deepgram_api_key = env::var("DEEPGRAM_API_KEY").ok();
+ let deepgram_websocket_url = env::var("DEEPGRAM_WEBSOCKET_URL").ok();
+ let deepgram_url = env::var("DEEPGRAM_API_URL").ok();
+ let enabled_devices = HashSet::new();
+ Self {
+ output_path: None,
+ transcription_engine: Arc::new(AudioTranscriptionEngine::default()),
+ vad_engine: VadEngineEnum::Silero,
+ languages: vec![],
+ deepgram_api_key,
+ enable_diarization: true,
+ enable_realtime: false,
+ audio_chunk_duration: Duration::from_secs(30),
+ vad_sensitivity: VadSensitivity::High,
+ health_check_grace_period: 15,
+ enabled_devices,
+ use_all_devices: false,
+ db_path: None,
+ deepgram_url,
+ deepgram_websocket_url,
+ }
+ }
+}
+
+#[derive(Default)]
+pub struct AudioManagerBuilder {
+ options: AudioManagerOptions,
+}
+
+impl AudioManagerBuilder {
+ pub fn new() -> Self {
+ Self {
+ options: AudioManagerOptions::default(),
+ }
+ }
+
+ pub fn transcription_engine(mut self, transcription_engine: AudioTranscriptionEngine) -> Self {
+ self.options.transcription_engine = Arc::new(transcription_engine);
+ self
+ }
+
+ pub fn vad_engine(mut self, vad_engine: VadEngineEnum) -> Self {
+ self.options.vad_engine = vad_engine;
+ self
+ }
+
+ pub fn languages(mut self, languages: Vec<Language>) -> Self {
+ self.options.languages = languages;
+ self
+ }
+
+ pub fn deepgram_api_key(mut self, deepgram_api_key: Option<String>) -> Self {
+ self.options.deepgram_api_key = deepgram_api_key;
+ self
+ }
+
+ pub fn diarization(mut self, enable_diarization: bool) -> Self {
+ self.options.enable_diarization = enable_diarization;
+ self
+ }
+
+ pub fn realtime(mut self, enable_realtime: bool) -> Self {
+ self.options.enable_realtime = enable_realtime;
+ self
+ }
+
+ pub fn audio_chunk_duration(mut self, audio_chunk_duration: Duration) -> Self {
+ self.options.audio_chunk_duration = audio_chunk_duration;
+ self
+ }
+
+ pub fn vad_sensitivity(mut self, vad_sensitivity: VadSensitivity) -> Self {
+ self.options.vad_sensitivity = vad_sensitivity;
+ self
+ }
+
+ pub fn health_check_grace_period(mut self, health_check_grace_period: u64) -> Self {
+ self.options.health_check_grace_period = health_check_grace_period;
+ self
+ }
+
+ pub fn enabled_devices(mut self, enabled_devices: Vec<String>) -> Self {
+ self.options.enabled_devices = HashSet::from_iter(enabled_devices);
+ self
+ }
+
+ pub fn use_all_devices(mut self, use_all_devices: bool) -> Self {
+ self.options.use_all_devices = use_all_devices;
+ self
+ }
+
+ pub fn deepgram_url(mut self, deepgram_url: Option<String>) -> Self {
+ self.options.deepgram_url = deepgram_url;
+ self
+ }
+
+ pub fn deepgram_websocket_url(mut self, deepgram_websocket_url: Option<String>) -> Self {
+ self.options.deepgram_websocket_url = deepgram_websocket_url;
+ self
+ }
+
+ pub async fn build(&mut self, db: Arc<DatabaseManager>) -> Result<AudioManager> {
+ self.validate_options()?;
+ let options = &mut self.options;
+
+ if options.enabled_devices.is_empty() {
+ options.enabled_devices = HashSet::from_iter(vec![
+ default_input_device()?.to_string(),
+ default_output_device()?.to_string(),
+ ]);
+ }
+
+ AudioManager::new(options.clone(), db).await
+ }
+
+ pub fn output_path(mut self, output_path: PathBuf) -> Self {
+ self.options.output_path = Some(output_path);
+ self
+ }
+
+ // TODO: Make sure the custom urls work
+ pub fn validate_options(&self) -> Result<()> {
+ if self.options.transcription_engine == Arc::new(AudioTranscriptionEngine::Deepgram)
+ && (self.options.deepgram_api_key.is_none() && CUSTOM_DEEPGRAM_API_TOKEN.is_empty())
+ {
+ return Err(anyhow::anyhow!(
+ "Deepgram API key is required for Deepgram transcription engine"
+ ));
+ }
+
+ if self.options.output_path.is_none() {
+ return Err(anyhow::anyhow!("Output path is required for audio manager"));
+ }
+
+ if self.options.enable_realtime
+ && (self.options.deepgram_api_key.is_none() && CUSTOM_DEEPGRAM_API_TOKEN.is_empty())
+ {
+ return Err(anyhow::anyhow!(
+ "Deepgram API key is required for realtime transcription"
+ ));
+ }
+
+ Ok(())
+ }
+}
diff --git a/screenpipe-audio/src/audio_manager/device_monitor.rs b/screenpipe-audio/src/audio_manager/device_monitor.rs
new file mode 100644
index 000000000..537f47547
--- /dev/null
+++ b/screenpipe-audio/src/audio_manager/device_monitor.rs
@@ -0,0 +1,93 @@
+use std::{collections::HashSet, sync::Arc, time::Duration};
+
+use anyhow::Result;
+use tokio::{sync::Mutex, task::JoinHandle, time::sleep};
+use tracing::{error, info};
+
+use crate::{core::device::parse_audio_device, device::device_manager::DeviceManager};
+
+use super::{AudioManager, AudioManagerStatus};
+
+lazy_static::lazy_static! {
+ pub static ref DEVICE_MONITOR: Mutex<Option<JoinHandle<()>>> = Mutex::new(None);
+}
+
+pub async fn start_device_monitor(
+ audio_manager: Arc<AudioManager>,
+ device_manager: Arc<DeviceManager>,
+) -> Result<()> {
+ stop_device_monitor().await?;
+
+ *DEVICE_MONITOR.lock().await = Some(tokio::spawn(async move {
+ let mut disconnected_devices: HashSet<String> = HashSet::new();
+ loop {
+ if audio_manager.status().await == AudioManagerStatus::Running {
+ let currently_available_devices = device_manager.devices().await;
+ let enabled_devices = audio_manager.enabled_devices().await;
+ for device_name in disconnected_devices.clone() {
+ let device = match parse_audio_device(&device_name) {
+ Ok(device) => device,
+ Err(e) => {
+ error!("Device name {} invalid: {}", device_name, e);
+ continue;
+ }
+ };
+
+ if audio_manager.start_device(&device).await.is_ok() {
+ disconnected_devices.remove(&device_name);
+ }
+ }
+
+ for device_name in enabled_devices.iter() {
+ let device = match parse_audio_device(device_name) {
+ Ok(device) => device,
+ Err(e) => {
+ error!("Device name {} invalid: {}", device_name, e);
+ continue;
+ }
+ };
+
+ if device_manager.is_running(&device)
+ && !currently_available_devices.contains(&device)
+ {
+ info!("Device {device_name} disconnected");
+ let _ = audio_manager.stop_device(device_name).await;
+ disconnected_devices.insert(device_name.clone());
+ } else {
+ if audio_manager.status().await != AudioManagerStatus::Running {
+ break;
+ }
+
+ if !audio_manager.enabled_devices().await.contains(device_name) {
+ continue;
+ }
+
+ match audio_manager.start_device(&device).await {
+ Ok(()) => {
+ //
+ }
+ Err(e) => {
+ let e_str = e.to_string();
+ if e_str.contains("already running") || e_str.contains("not found")
+ {
+ continue;
+ }
+ error!("device check error: {e}");
+ }
+ }
+ }
+ }
+ }
+ sleep(Duration::from_secs(2)).await;
+ }
+ }));
+ Ok(())
+}
+
+pub async fn stop_device_monitor() -> Result<()> {
+ if let Some(handle) = DEVICE_MONITOR.lock().await.take() {
+ handle.abort();
+ }
+
+ Ok(())
+}
diff --git a/screenpipe-audio/src/audio_manager/manager.rs b/screenpipe-audio/src/audio_manager/manager.rs
new file mode 100644
index 000000000..9a3007f67
--- /dev/null
+++ b/screenpipe-audio/src/audio_manager/manager.rs
@@ -0,0 +1,412 @@
+use anyhow::{anyhow, Result};
+use dashmap::DashMap;
+use std::{
+ collections::HashSet,
+ path::PathBuf,
+ sync::{atomic::Ordering, Arc},
+};
+use tokio::{
+ join,
+ sync::{Mutex, RwLock},
+ task::JoinHandle,
+};
+use tracing::{error, info, warn};
+use whisper_rs::WhisperContext;
+
+use screenpipe_db::DatabaseManager;
+
+use super::{start_device_monitor, stop_device_monitor, AudioManagerOptions};
+use crate::{
+ core::{
+ device::{parse_audio_device, AudioDevice},
+ record_and_transcribe,
+ },
+ device::device_manager::DeviceManager,
+ segmentation::segmentation_manager::SegmentationManager,
+ transcription::{
+ deepgram::streaming::stream_transcription_deepgram,
+ handle_new_transcript,
+ stt::process_audio_input,
+ whisper::model::{create_whisper_context_parameters, download_whisper_model},
+ },
+ vad::{silero::SileroVad, webrtc::WebRtcVad, VadEngine, VadEngineEnum},
+ AudioInput, TranscriptionResult,
+};
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub enum AudioManagerStatus {
+ Running,
+ Paused,
+ Stopped,
+}
+
+type RecordingHandlesMap = DashMap<AudioDevice, Arc<Mutex<JoinHandle<Result<()>>>>>;
+
+#[derive(Clone)]
+pub struct AudioManager {
+ options: Arc<RwLock<AudioManagerOptions>>,
+ device_manager: Arc<DeviceManager>,
+ segmentation_manager: Arc<SegmentationManager>,
+ status: Arc<RwLock<AudioManagerStatus>>,
+ db: Arc<DatabaseManager>,
+ vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>,
+ recording_handles: Arc<RecordingHandlesMap>,
+ recording_sender: Arc<crossbeam::channel::Sender<AudioInput>>,
+ recording_receiver: Arc<crossbeam::channel::Receiver<AudioInput>>,
+ transcription_receiver: Arc<crossbeam::channel::Receiver<TranscriptionResult>>,
+ transcription_sender: Arc<crossbeam::channel::Sender<TranscriptionResult>>,
+ transcription_receiver_handle: Arc<RwLock<Option<JoinHandle<()>>>>,
+ recording_receiver_handle: Arc<RwLock<Option<JoinHandle<()>>>>,
+ stt_model_path: PathBuf,
+}
+
+impl AudioManager {
+ pub async fn new(options: AudioManagerOptions, db: Arc<DatabaseManager>) -> Result<Self> {
+ let device_manager = DeviceManager::new().await?;
+ let segmentation_manager = Arc::new(SegmentationManager::new().await?);
+ let status = RwLock::new(AudioManagerStatus::Stopped);
+ let vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>> = match options.vad_engine {
+ VadEngineEnum::Silero => Arc::new(Mutex::new(Box::new(SileroVad::new().await?))),
+ VadEngineEnum::WebRtc => Arc::new(Mutex::new(Box::new(WebRtcVad::new()))),
+ };
+
+ let (recording_sender, recording_receiver) = crossbeam::channel::bounded(1000);
+ let (transcription_sender, transcription_receiver) = crossbeam::channel::bounded(1000);
+
+ let recording_handles = DashMap::new();
+ let stt_model_path = download_whisper_model(options.transcription_engine.clone())?;
+
+ whisper_rs::install_logging_hooks();
+
+ let manager = Self {
+ options: Arc::new(RwLock::new(options)),
+ device_manager: Arc::new(device_manager),
+ segmentation_manager,
+ status: Arc::new(status),
+ db,
+ vad_engine,
+ recording_sender: Arc::new(recording_sender),
+ recording_receiver: Arc::new(recording_receiver),
+ transcription_receiver: Arc::new(transcription_receiver),
+ transcription_sender: Arc::new(transcription_sender),
+ recording_handles: Arc::new(recording_handles),
+ recording_receiver_handle: Arc::new(RwLock::new(None)),
+ transcription_receiver_handle: Arc::new(RwLock::new(None)),
+ stt_model_path,
+ };
+
+ Ok(manager)
+ }
+
+ pub async fn start(&self) -> Result<()> {
+ if self.status().await == AudioManagerStatus::Running {
+ return Ok(());
+ }
+
+ *self.status.write().await = AudioManagerStatus::Running;
+ self.start_internal().await
+ }
+
+ async fn start_internal(&self) -> Result<()> {
+ *self.status.write().await = AudioManagerStatus::Running;
+ let mut transcription_receiver_handle = self.transcription_receiver_handle.write().await;
+ *transcription_receiver_handle = Some(self.start_transcription_receiver_handler().await?);
+
+ let mut recording_receiver_handle = self.recording_receiver_handle.write().await;
+ *recording_receiver_handle = Some(self.start_audio_receiver_handler().await?);
+ let self_arc = Arc::new(self.clone());
+
+ start_device_monitor(self_arc.clone(), self.device_manager.clone()).await?;
+
+ info!("audio manager started");
+
+ Ok(())
+ }
+
+ pub async fn restart(&self) -> Result<()> {
+ self.stop_internal().await?;
+ self.start_internal().await?;
+ info!("audio manager restarted");
+ Ok(())
+ }
+
+ async fn stop_internal(&self) -> Result<()> {
+ *self.status.write().await = AudioManagerStatus::Stopped;
+
+ stop_device_monitor().await?;
+
+ let mut recording_receiver_handle = self.recording_receiver_handle.write().await;
+ if let Some(handle) = recording_receiver_handle.take() {
+ handle.abort();
+ }
+
+ let mut transcription_receiver_handle = self.transcription_receiver_handle.write().await;
+ if let Some(handle) = transcription_receiver_handle.take() {
+ handle.abort();
+ }
+
+ for pair in self.recording_handles.iter() {
+ let handle = pair.value();
+ handle.lock().await.abort();
+ }
+
+ self.recording_handles.clear();
+ self.device_manager.stop_all_devices().await?;
+ info!("audio manager stopped");
+ Ok(())
+ }
+
+ pub async fn stop(&self) -> Result<()> {
+ if self.status().await == AudioManagerStatus::Stopped {
+ return Ok(());
+ }
+ *self.status.write().await = AudioManagerStatus::Stopped;
+ stop_device_monitor().await?;
+ self.stop_internal().await
+ }
+
+ pub async fn devices(&self) -> Result<Vec<AudioDevice>> {
+ let devices = self.device_manager.devices().await;
+ Ok(devices)
+ }
+
+ pub async fn stop_device(&self, device_name: &str) -> Result<()> {
+ let device = match parse_audio_device(device_name) {
+ Ok(device) => device,
+ Err(_) => return Err(anyhow!("Device {} not found", device_name)),
+ };
+
+ self.options
+ .write()
+ .await
+ .enabled_devices
+ .remove(device_name);
+
+ self.device_manager.stop_device(&device).await?;
+
+ if let Some(pair) = self.recording_handles.get(&device) {
+ let handle = pair.value();
+
+ handle.lock().await.abort();
+ }
+
+ self.recording_handles.remove(&device);
+
+ Ok(())
+ }
+
+ pub async fn status(&self) -> AudioManagerStatus {
+ self.status.read().await.clone()
+ }
+
+ pub async fn start_device(&self, device: &AudioDevice) -> Result<()> {
+ if let Err(e) = self.device_manager.start_device(device).await {
+ let err_str = e.to_string();
+
+ if err_str.contains("Failed to build input stream") {
+ return Err(anyhow!("Device {device} not found"));
+ } else if !err_str.contains("already running") {
+ return Err(e);
+ }
+ }
+
+ if !self.recording_handles.contains_key(device) {
+ if let Some(is_running) = self.device_manager.is_running_mut(device) {
+ is_running.store(true, Ordering::Relaxed);
+ }
+ let handle = self.record_device(device).await?;
+ self.recording_handles
+ .insert(device.clone(), Arc::new(Mutex::new(handle)));
+ }
+
+ if !self.enabled_devices().await.contains(&device.to_string()) {
+ self.options
+ .write()
+ .await
+ .enabled_devices
+ .insert(device.to_string());
+ }
+
+ Ok(())
+ }
+
+ pub async fn use_all_devices(&self) -> bool {
+ self.options.read().await.use_all_devices
+ }
+
+ async fn record_device(&self, device: &AudioDevice) -> Result<JoinHandle<Result<()>>> {
+ let options = self.options.read().await;
+ let stream = self.device_manager.stream(device).unwrap();
+ let audio_chunk_duration = options.audio_chunk_duration;
+ let recording_sender = self.recording_sender.clone();
+ let is_running = self.device_manager.is_running_mut(device).unwrap();
+ let languages = options.languages.clone();
+ let deepgram_api_key = options.deepgram_api_key.clone();
+ let realtime_enabled = options.enable_realtime;
+ let device_clone = device.clone();
+
+ let recording_handle = tokio::spawn(async move {
+ let record_and_transcribe_handle = tokio::spawn(record_and_transcribe(
+ stream.clone(),
+ audio_chunk_duration,
+ recording_sender.clone(),
+ is_running.clone(),
+ ));
+
+ let realtime_handle = if realtime_enabled {
+ Some(tokio::spawn(stream_transcription_deepgram(
+ stream,
+ languages,
+ is_running,
+ deepgram_api_key,
+ )))
+ } else {
+ None
+ };
+
+ let (record_result, realtime_result) = if let Some(handle) = realtime_handle {
+ join!(record_and_transcribe_handle, handle)
+ } else {
+ (record_and_transcribe_handle.await, Ok(Ok(())))
+ };
+
+ if record_result.is_err() || realtime_result.is_err() {
+ let mut e = anyhow!("record_device failed");
+
+ if record_result.is_err() {
+ let record_error = record_result.err().unwrap();
+ error!("Record and transcribe error: {}", record_error);
+ e = e.context(record_error)
+ }
+
+ if realtime_result.is_err() {
+ let realtime_error = realtime_result.err().unwrap();
+ error!("Realtime recording error: {}", realtime_error);
+ e = e.context(realtime_error);
+ }
+
+ return Err(e);
+ }
+
+ warn!(
+ "recording handle for device {} quit unexpectedly",
+ device_clone
+ );
+
+ Ok(())
+ });
+
+ Ok(recording_handle)
+ }
+
+ async fn start_audio_receiver_handler(&self) -> Result<JoinHandle<()>> {
+ let transcription_sender = self.transcription_sender.clone();
+ let segmentation_manager = self.segmentation_manager.clone();
+ let segmentation_model_path = segmentation_manager.segmentation_model_path.clone();
+ let embedding_manager = segmentation_manager.embedding_manager.clone();
+ let embedding_extractor = segmentation_manager.embedding_extractor.clone();
+ let options = self.options.read().await;
+ let output_path = options.output_path.clone();
+ let languages = options.languages.clone();
+ let deepgram_api_key = options.deepgram_api_key.clone();
+ let audio_transcription_engine = options.transcription_engine.clone();
+ let vad_engine = self.vad_engine.clone();
+ let whisper_receiver = self.recording_receiver.clone();
+ let context_param = create_whisper_context_parameters(audio_transcription_engine.clone())?;
+
+ let quantized_path = self.stt_model_path.clone();
+ let whisper_context = Arc::new(
+ WhisperContext::new_with_params(&quantized_path.to_string_lossy(), context_param)
+ .expect("failed to load model"),
+ );
+
+ Ok(tokio::spawn(async move {
+ while let Ok(audio) = whisper_receiver.recv() {
+ info!("Received audio from device: {:?}", audio.device.name);
+ if let Err(e) = process_audio_input(
+ audio.clone(),
+ vad_engine.clone(),
+ segmentation_model_path.clone(),
+ embedding_manager.clone(),
+ embedding_extractor.clone(),
+ &output_path.clone().unwrap(),
+ audio_transcription_engine.clone(),
+ deepgram_api_key.clone(),
+ languages.clone(),
+ &transcription_sender.clone(),
+ whisper_context.clone(),
+ )
+ .await
+ {
+ error!("Error processing audio: {:?}", e);
+ }
+ }
+ }))
+ }
+
+ async fn start_transcription_receiver_handler(&self) -> Result<JoinHandle<()>> {
+ let transcription_receiver = self.transcription_receiver.clone();
+ let db = self.db.clone();
+ let transcription_engine = self.options.read().await.transcription_engine.clone();
+ Ok(tokio::spawn(handle_new_transcript(
+ db,
+ transcription_receiver,
+ transcription_engine,
+ )))
+ }
+
+ pub async fn shutdown(&self) -> Result<()> {
+ self.stop().await?;
+ let rec = self.recording_handles.clone();
+ let recording = self.recording_receiver_handle.clone();
+ let transcript = self.transcription_receiver_handle.clone();
+
+ if let Some(handle) = recording.write().await.take() {
+ handle.abort();
+ }
+ if let Some(handle) = transcript.write().await.take() {
+ handle.abort();
+ }
+ for h in rec.iter() {
+ h.value().lock().await.abort();
+ }
+
+ let _ = stop_device_monitor().await;
+
+ Ok(())
+ }
+
+ pub fn current_devices(&self) -> Vec<AudioDevice> {
+ self.recording_handles
+ .iter()
+ .map(|p| p.key().clone())
+ .collect::<Vec<AudioDevice>>()
+ }
+
+ pub async fn enabled_devices(&self) -> HashSet<String> {
+ self.options.read().await.enabled_devices.clone()
+ }
+}
+
+impl Drop for AudioManager {
+ fn drop(&mut self) {
+ let rec = self.recording_handles.clone();
+ let recording = self.recording_receiver_handle.clone();
+ let transcript = self.transcription_receiver_handle.clone();
+ let device_manager = self.device_manager.clone();
+
+ tokio::spawn(async move {
+ let _ = stop_device_monitor().await;
+ let _ = device_manager.stop_all_devices().await;
+ if let Some(handle) = recording.write().await.take() {
+ handle.abort();
+ }
+ if let Some(handle) = transcript.write().await.take() {
+ handle.abort();
+ }
+ for h in rec.iter() {
+ h.value().lock().await.abort();
+ }
+ });
+ }
+}
diff --git a/screenpipe-audio/src/audio_manager/mod.rs b/screenpipe-audio/src/audio_manager/mod.rs
new file mode 100644
index 000000000..ef1c58a1d
--- /dev/null
+++ b/screenpipe-audio/src/audio_manager/mod.rs
@@ -0,0 +1,6 @@
+mod builder;
+mod device_monitor;
+mod manager;
+pub use builder::*;
+pub use device_monitor::*;
+pub use manager::*;
diff --git a/screenpipe-audio/src/audio_processing.rs b/screenpipe-audio/src/audio_processing.rs
deleted file mode 100644
index 5f243033e..000000000
--- a/screenpipe-audio/src/audio_processing.rs
+++ /dev/null
@@ -1,163 +0,0 @@
-use anyhow::Result;
-use chrono::Utc;
-use log::debug;
-use realfft::num_complex::{Complex32, ComplexFloat};
-use realfft::RealFftPlanner;
-use rubato::{
- Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction,
-};
-use std::path::PathBuf;
-
-use crate::encode_single_audio;
-
-pub fn normalize_v2(audio: &[f32]) -> Vec<f32> {
- let rms = (audio.iter().map(|&x| x * x).sum::<f32>() / audio.len() as f32).sqrt();
- let peak = audio
- .iter()
- .fold(0.0f32, |max, &sample| max.max(sample.abs()));
-
- // Return the original audio if it's completely silent
- if rms == 0.0 || peak == 0.0 {
- return audio.to_vec();
- }
-
- let target_rms = 0.2;
- let target_peak = 0.95;
-
- let rms_scaling = target_rms / rms;
- let peak_scaling = target_peak / peak;
-
- let scaling_factor = rms_scaling.min(peak_scaling);
-
- audio
- .iter()
- .map(|&sample| sample * scaling_factor)
- .collect()
-}
-
-pub fn spectral_subtraction(audio: &[f32], d: f32) -> Result<Vec<f32>> {
- let mut real_planner = RealFftPlanner::<f32>::new();
- let window_size = 1600; // 16k sample rate - 100ms
- let r2c = real_planner.plan_fft_forward(window_size);
-
- let mut y = r2c.make_output_vec();
-
- let mut padded_audio = audio.to_vec();
-
- padded_audio.append(&mut vec![0.0f32; window_size - audio.len()]);
-
- let mut indata = padded_audio;
- r2c.process(&mut indata, &mut y)?;
-
- let mut processed_audio = y
- .iter()
- .map(|&x| {
- let magnitude_y = x.abs().powf(2.0);
-
- let div = 1.0 - (d / magnitude_y);
-
- let gain = {
- if div > 0.0 {
- f32::sqrt(div)
- } else {
- 0.0f32
- }
- };
-
- x * gain
- })
- .collect::<Vec<Complex32>>();
-
- let c2r = real_planner.plan_fft_inverse(window_size);
-
- let mut outdata = c2r.make_output_vec();
-
- c2r.process(&mut processed_audio, &mut outdata)?;
-
- Ok(outdata)
-}
-
-// not an average of non-speech segments, but I don't know how much pause time we
-// get. for now, we will just assume the noise is constant (kinda defeats the purpose)
-// but oh well
-pub fn average_noise_spectrum(audio: &[f32]) -> f32 {
- let mut total_sum = 0.0f32;
-
- for sample in audio {
- let magnitude = sample.abs();
-
- total_sum += magnitude.powf(2.0);
- }
-
- total_sum / audio.len() as f32
-}
-
-pub fn audio_to_mono(audio: &[f32], channels: u16) -> Vec<f32> {
- let mut mono_samples = Vec::with_capacity(audio.len() / channels as usize);
-
- // Iterate over the audio slice in chunks, each containing `channels` samples
- for chunk in audio.chunks(channels as usize) {
- // Sum the samples from all channels in the current chunk
- let sum: f32 = chunk.iter().sum();
-
- // Calculate the averagechannelsono sample
- let mono_sample = sum / channels as f32;
-
- // Store the computed mono sample
- mono_samples.push(mono_sample);
- }
-
- mono_samples
-}
-
-pub fn resample(input: &[f32], from_sample_rate: u32, to_sample_rate: u32) -> Result<Vec<f32>> {
- debug!("Resampling audio");
- let params = SincInterpolationParameters {
- sinc_len: 256,
- f_cutoff: 0.95,
- interpolation: SincInterpolationType::Linear,
- oversampling_factor: 256,
- window: WindowFunction::BlackmanHarris2,
- };
-
- let mut resampler = SincFixedIn::<f32>::new(
- to_sample_rate as f64 / from_sample_rate as f64,
- 2.0,
- params,
- input.len(),
- 1,
- )?;
-
- let waves_in = vec![input.to_vec()];
- debug!("Performing resampling");
- let waves_out = resampler.process(&waves_in, None)?;
- debug!("Resampling complete");
- Ok(waves_out.into_iter().next().unwrap())
-}
-
-pub fn write_audio_to_file(
- audio: &[f32],
- sample_rate: u32,
- output_path: &PathBuf,
- device: &str,
- skip_encoding: bool,
-) -> Result<String> {
- let new_file_name = Utc::now().format("%Y-%m-%d_%H-%M-%S").to_string();
- let sanitized_device_name = device.replace(['/', '\\'], "_");
- let file_path = PathBuf::from(output_path)
- .join(format!("{}_{}.mp4", sanitized_device_name, new_file_name))
- .to_str()
- .expect("Failed to create valid path")
- .to_string();
- let file_path_clone = file_path.clone();
- // Run FFmpeg in a separate task
- if !skip_encoding {
- encode_single_audio(
- bytemuck::cast_slice(audio),
- sample_rate,
- 1,
- &PathBuf::from(file_path),
- )?;
- }
- Ok(file_path_clone)
-}
diff --git a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
deleted file mode 100644
index 073919061..000000000
--- a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
+++ /dev/null
@@ -1,150 +0,0 @@
-use anyhow::{anyhow, Result};
-use clap::Parser;
-use log::info;
-use screenpipe_audio::create_whisper_channel;
-use screenpipe_audio::default_input_device;
-use screenpipe_audio::default_output_device;
-use screenpipe_audio::list_audio_devices;
-use screenpipe_audio::parse_audio_device;
-use screenpipe_audio::record_and_transcribe;
-use screenpipe_audio::vad_engine::VadSensitivity;
-use screenpipe_audio::AudioDevice;
-use screenpipe_audio::AudioStream;
-use screenpipe_audio::AudioTranscriptionEngine;
-use screenpipe_audio::VadEngineEnum;
-use screenpipe_core::Language;
-use std::path::PathBuf;
-use std::sync::atomic::AtomicBool;
-use std::sync::Arc;
-use std::time::Duration;
-
-#[derive(Parser, Debug)]
-#[clap(author, version, about, long_about = None)]
-struct Args {
- #[clap(
- short,
- long,
- help = "Audio device name (can be specified multiple times)"
- )]
- audio_device: Vec<String>,
-
- #[clap(long, help = "List available audio devices")]
- list_audio_devices: bool,
-
- #[clap(long, help = "Audio chunk duration in seconds")]
- audio_chunk_duration: f32,
-
- #[clap(long, help = "Deepgram API key")]
- deepgram_api_key: Option<String>,
-
- #[clap(short = 'l', long, value_enum)]
- language: Vec<Language>,
-}
-
-fn print_devices(devices: &[AudioDevice]) {
- println!("Available audio devices:");
- for device in devices.iter() {
- println!(" {}", device);
- }
-
- #[cfg(target_os = "macos")]
- println!("On macOS, it's not intuitive but output devices are your displays");
-}
-
-// ! usage - cargo run --bin screenpipe-audio -- --audio-device "Display 1 (output)"
-
-#[tokio::main]
-async fn main() -> Result<()> {
- use env_logger::Builder;
- use log::LevelFilter;
-
- Builder::new()
- .filter(None, LevelFilter::Debug)
- .filter_module("tokenizers", LevelFilter::Error)
- .init();
-
- let args = Args::parse();
-
- let languages = args.language;
-
- let devices = list_audio_devices().await?;
-
- if args.list_audio_devices {
- print_devices(&devices);
- return Ok(());
- }
-
- let devices = if args.audio_device.is_empty() {
- vec![default_input_device()?, default_output_device()?]
- } else {
- args.audio_device
- .iter()
- .map(|d| parse_audio_device(d))
- .collect::<Result<Vec<_>>>()?
- };
-
- if devices.is_empty() {
- return Err(anyhow!("No audio input devices found"));
- }
-
- let chunk_duration = Duration::from_secs_f32(args.audio_chunk_duration);
- let (whisper_sender, whisper_receiver, _) = create_whisper_channel(
- Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),
- VadEngineEnum::Silero, // Or VadEngineEnum::WebRtc, hardcoded for now
- args.deepgram_api_key,
- &PathBuf::from("output.mp4"),
- VadSensitivity::Medium,
- languages,
- None,
- )
- .await?;
-
- let whisper_sender_clone = whisper_sender.clone();
- // Spawn threads for each device
- let _recording_threads: Vec<_> = devices
- .into_iter()
- .enumerate()
- .map(|(i, device)| {
- let whisper_sender = whisper_sender_clone.clone();
- async move {
- let device = Arc::new(device);
- let device_control = Arc::new(AtomicBool::new(true));
-
- let audio_stream = AudioStream::from_device(device.clone(), device_control.clone())
- .await
- .unwrap();
-
- tokio::spawn(async move {
- loop {
- let result = record_and_transcribe(
- Arc::new(audio_stream.clone()),
- chunk_duration,
- whisper_sender.clone(),
- Arc::clone(&device_control),
- )
- .await;
-
- if let Err(e) = result {
- eprintln!("Error in recording thread {}: {:?}", i, e);
- // Optionally add a short delay before retrying
- tokio::time::sleep(Duration::from_secs(1)).await;
- }
- }
- })
- .await
- }
- })
- .collect();
-
- // Main loop to receive and print transcriptions
- loop {
- match whisper_receiver.recv() {
- Ok(result) => {
- info!("Transcription: {:?}", result);
- }
- Err(e) => {
- eprintln!("Error receiving transcription: {:?}", e);
- }
- }
- }
-}
diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rs
deleted file mode 100644
index 22c3222b7..000000000
--- a/screenpipe-audio/src/bin/screenpipe-audio.rs
+++ /dev/null
@@ -1,160 +0,0 @@
-use anyhow::{anyhow, Result};
-use clap::Parser;
-use log::info;
-use screenpipe_audio::create_whisper_channel;
-use screenpipe_audio::default_input_device;
-use screenpipe_audio::default_output_device;
-use screenpipe_audio::list_audio_devices;
-use screenpipe_audio::parse_audio_device;
-use screenpipe_audio::record_and_transcribe;
-use screenpipe_audio::vad_engine::VadSensitivity;
-use screenpipe_audio::AudioDevice;
-use screenpipe_audio::AudioStream;
-use screenpipe_audio::AudioTranscriptionEngine;
-use screenpipe_audio::VadEngineEnum;
-use screenpipe_core::Language;
-use std::path::PathBuf;
-use std::sync::atomic::AtomicBool;
-use std::sync::Arc;
-use std::time::Duration;
-
-#[derive(Parser, Debug)]
-#[clap(author, version, about, long_about = None)]
-struct Args {
- #[clap(
- short,
- long,
- help = "Audio device name (can be specified multiple times)"
- )]
- audio_device: Vec<String>,
-
- #[clap(long, help = "List available audio devices")]
- list_audio_devices: bool,
-
- #[clap(short = 'l', long, value_enum)]
- language: Vec<Language>,
-
- #[clap(long, help = "Deepgram API key")]
- deepgram_api_key: Option<String>,
-}
-
-fn print_devices(devices: &[AudioDevice]) {
- println!("Available audio devices:");
- for device in devices.iter() {
- println!(" {}", device);
- }
-
- #[cfg(target_os = "macos")]
- println!("On macOS, it's not intuitive but output devices are your displays");
-}
-
-// ! usage - cargo run --bin screenpipe-audio -- --audio-device "Display 1 (output)"
-
-#[tokio::main]
-async fn main() -> Result<()> {
- use env_logger::Builder;
- use log::LevelFilter;
-
- Builder::new()
- .filter(None, LevelFilter::Debug)
- .filter_module("tokenizers", LevelFilter::Error)
- .init();
-
- let args = Args::parse();
-
- let devices = list_audio_devices().await?;
-
- if args.list_audio_devices {
- print_devices(&devices);
- return Ok(());
- }
-
- let languages = args.language;
-
- let deepgram_api_key = args.deepgram_api_key;
-
- let devices = if args.audio_device.is_empty() {
- vec![default_input_device()?, default_output_device()?]
- } else {
- args.audio_device
- .iter()
- .map(|d| parse_audio_device(d))
- .collect::<Result<Vec<_>>>()?
- };
-
- if devices.is_empty() {
- return Err(anyhow!("No audio input devices found"));
- }
-
- // delete .mp4 files (output*.mp4)
- std::fs::remove_file("output_0.mp4").unwrap_or_default();
- std::fs::remove_file("output_1.mp4").unwrap_or_default();
-
- let chunk_duration = Duration::from_secs(10);
- let output_path = PathBuf::from("output.mp4");
- let (whisper_sender, whisper_receiver, _) = create_whisper_channel(
- Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),
- VadEngineEnum::WebRtc, // Or VadEngineEnum::WebRtc, hardcoded for now
- deepgram_api_key,
- &output_path,
- VadSensitivity::Medium,
- languages,
- None
- )
- .await?;
- // Spawn threads for each device
- let recording_threads: Vec<_> = devices
- .into_iter()
- .map(|device| {
- let device = Arc::new(device);
- let whisper_sender = whisper_sender.clone();
- let device_control = Arc::new(AtomicBool::new(true));
- let device_clone = Arc::clone(&device);
-
- tokio::spawn(async move {
- let device_control_clone = Arc::clone(&device_control);
- let device_clone_2 = Arc::clone(&device_clone);
- let audio_stream =
- AudioStream::from_device(device_clone_2, device_control_clone.clone())
- .await
- .unwrap();
-
- record_and_transcribe(
- Arc::new(audio_stream),
- chunk_duration,
- whisper_sender,
- device_control_clone,
- )
- .await
- })
- })
- .collect();
- let mut consecutive_timeouts = 0;
- let max_consecutive_timeouts = 3; // Adjust this value as needed
-
- // Main loop to receive and print transcriptions
- loop {
- match whisper_receiver.try_recv() {
- Ok(result) => {
- info!("Transcription: {:?}", result);
- consecutive_timeouts = 0; // Reset the counter on successful receive
- }
- Err(_) => {
- consecutive_timeouts += 1;
- if consecutive_timeouts >= max_consecutive_timeouts {
- info!("No transcriptions received for a while, stopping...");
- break;
- }
- continue;
- }
- }
- }
-
- // Wait for all recording threads to finish
- for (i, thread) in recording_threads.into_iter().enumerate() {
- let file_path = thread.await.unwrap();
- println!("Recording {} complete: {:?}", i, file_path);
- }
-
- Ok(())
-}
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
deleted file mode 100644
index a035d4fd6..000000000
--- a/screenpipe-audio/src/core.rs
+++ /dev/null
@@ -1,596 +0,0 @@
-use crate::audio_processing::audio_to_mono;
-use crate::realtime::realtime_stt;
-use crate::AudioInput;
-use anyhow::{anyhow, Result};
-use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
-use cpal::StreamError;
-use lazy_static::lazy_static;
-use log::{debug, error, info, warn};
-use screenpipe_core::Language;
-use serde::{Deserialize, Serialize};
-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
-use std::sync::mpsc;
-use std::sync::Arc;
-use std::time::Duration;
-use std::{fmt, thread};
-use tokio::sync::{broadcast, oneshot};
-use oasgen::OaSchema;
-
-lazy_static! {
- pub static ref LAST_AUDIO_CAPTURE: AtomicU64 = AtomicU64::new(
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs()
- );
-}
-
-#[derive(Clone, Debug, PartialEq, Default)]
-pub enum AudioTranscriptionEngine {
- Deepgram,
- WhisperTiny,
- WhisperDistilLargeV3,
- #[default]
- WhisperLargeV3Turbo,
- WhisperLargeV3,
-}
-
-impl fmt::Display for AudioTranscriptionEngine {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- AudioTranscriptionEngine::Deepgram => write!(f, "Deepgram"),
- AudioTranscriptionEngine::WhisperTiny => write!(f, "WhisperTiny"),
- AudioTranscriptionEngine::WhisperDistilLargeV3 => write!(f, "WhisperLarge"),
- AudioTranscriptionEngine::WhisperLargeV3Turbo => write!(f, "WhisperLargeV3Turbo"),
- AudioTranscriptionEngine::WhisperLargeV3 => write!(f, "WhisperLargeV3"),
- }
- }
-}
-
-#[derive(Clone, Debug)]
-pub struct DeviceControl {
- pub is_running: bool,
- pub is_paused: bool,
-}
-
-#[derive(OaSchema, Clone, Eq, PartialEq, Hash, Serialize, Debug, Deserialize)]
-pub enum DeviceType {
- Input,
- Output,
-}
-
-#[derive(OaSchema, Clone, Eq, PartialEq, Hash, Serialize, Debug)]
-pub struct AudioDevice {
- pub name: String,
- pub device_type: DeviceType,
-}
-
-impl AudioDevice {
- pub fn new(name: String, device_type: DeviceType) -> Self {
- AudioDevice { name, device_type }
- }
-
- pub fn from_name(name: &str) -> Result<Self> {
- if name.trim().is_empty() {
- return Err(anyhow!("Device name cannot be empty"));
- }
-
- let (name, device_type) = if name.to_lowercase().ends_with("(input)") {
- (
- name.trim_end_matches("(input)").trim().to_string(),
- DeviceType::Input,
- )
- } else if name.to_lowercase().ends_with("(output)") {
- (
- name.trim_end_matches("(output)").trim().to_string(),
- DeviceType::Output,
- )
- } else {
- return Err(anyhow!(
- "Device type (input/output) not specified in the name"
- ));
- };
-
- Ok(AudioDevice::new(name, device_type))
- }
-}
-
-impl fmt::Display for AudioDevice {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(
- f,
- "{} ({})",
- self.name,
- match self.device_type {
- DeviceType::Input => "input",
- DeviceType::Output => "output",
- }
- )
- }
-}
-
-pub fn parse_audio_device(name: &str) -> Result<AudioDevice> {
- AudioDevice::from_name(name)
-}
-
-pub async fn get_device_and_config(
- audio_device: &AudioDevice,
-) -> Result<(cpal::Device, cpal::SupportedStreamConfig)> {
- let host = cpal::default_host();
-
- let is_output_device = audio_device.device_type == DeviceType::Output;
- let is_display = audio_device.to_string().contains("Display");
-
- let cpal_audio_device = if audio_device.to_string() == "default" {
- match audio_device.device_type {
- DeviceType::Input => host.default_input_device(),
- DeviceType::Output => host.default_output_device(),
- }
- } else {
- let mut devices = match audio_device.device_type {
- DeviceType::Input => host.input_devices()?,
- DeviceType::Output => host.output_devices()?,
- };
-
- #[cfg(target_os = "macos")]
- {
- if is_output_device {
- if let Ok(screen_capture_host) = cpal::host_from_id(cpal::HostId::ScreenCaptureKit)
- {
- devices = screen_capture_host.input_devices()?;
- }
- }
- }
-
- devices.find(|x| {
- x.name()
- .map(|y| {
- y == audio_device
- .to_string()
- .replace(" (input)", "")
- .replace(" (output)", "")
- .trim()
- })
- .unwrap_or(false)
- })
- }
- .ok_or_else(|| anyhow!("Audio device not found"))?;
-
- // if output device and windows, using output config
- let config = if is_output_device && !is_display {
- cpal_audio_device.default_output_config()?
- } else {
- cpal_audio_device.default_input_config()?
- };
- Ok((cpal_audio_device, config))
-}
-
-pub async fn record_and_transcribe(
- audio_stream: Arc<AudioStream>,
- duration: Duration,
- whisper_sender: crossbeam::channel::Sender<AudioInput>,
- is_running: Arc<AtomicBool>,
-) -> Result<()> {
- while is_running.load(Ordering::Relaxed) {
- match run_record_and_transcribe(
- audio_stream.clone(),
- duration,
- whisper_sender.clone(),
- is_running.clone(),
- )
- .await
- {
- Ok(_) => {
- // Normal shutdown
- break;
- }
- Err(e) => {
- if !is_running.load(Ordering::Relaxed) {
- // Normal shutdown
- break;
- }
-
- error!("record_and_transcribe error, restarting: {}", e);
- // Add a small delay before restarting to prevent rapid restart loops
- tokio::time::sleep(Duration::from_secs(1)).await;
- }
- }
- }
- Ok(())
-}
-
-pub async fn start_realtime_recording(
- audio_stream: Arc<AudioStream>,
- languages: Vec<Language>,
- is_running: Arc<AtomicBool>,
- deepgram_api_key: Option<String>,
-) -> Result<()> {
- while is_running.load(Ordering::Relaxed) {
- match realtime_stt(
- audio_stream.clone(),
- languages.clone(),
- is_running.clone(),
- deepgram_api_key.clone(),
- )
- .await
- {
- Ok(_) => {
- // Normal shutdown
- break;
- }
- Err(e) => {
- if !is_running.load(Ordering::Relaxed) {
- // Normal shutdown
- break;
- }
-
- error!("realtime_stt error, restarting: {}", e);
- // Add a small delay before restarting to prevent rapid restart loops
- tokio::time::sleep(Duration::from_secs(1)).await;
- }
- }
- }
- Ok(())
-}
-
-async fn run_record_and_transcribe(
- audio_stream: Arc<AudioStream>,
- duration: Duration,
- whisper_sender: crossbeam::channel::Sender<AudioInput>,
- is_running: Arc<AtomicBool>,
-) -> Result<()> {
- let mut receiver = audio_stream.subscribe().await;
-
- info!(
- "starting continuous recording for {} ({}s segments)",
- audio_stream.device.to_string(),
- duration.as_secs()
- );
-
- const OVERLAP_SECONDS: usize = 2;
- let mut collected_audio = Vec::new();
- let sample_rate = audio_stream.device_config.sample_rate().0 as usize;
- let overlap_samples = OVERLAP_SECONDS * sample_rate;
-
- while is_running.load(Ordering::Relaxed)
- && !audio_stream.is_disconnected.load(Ordering::Relaxed)
- {
- let start_time = tokio::time::Instant::now();
-
- while start_time.elapsed() < duration && is_running.load(Ordering::Relaxed) {
- match tokio::time::timeout(Duration::from_millis(100), receiver.recv()).await {
- Ok(Ok(chunk)) => {
- collected_audio.extend(chunk);
- LAST_AUDIO_CAPTURE.store(
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap()
- .as_secs(),
- Ordering::Relaxed,
- );
- }
- Ok(Err(e)) => {
- error!("error receiving audio data: {}", e);
- return Err(anyhow!("Audio stream error: {}", e));
- }
- Err(_) => {} // Timeout, continue loop
- }
- }
-
- if !collected_audio.is_empty() {
- debug!("sending audio segment to audio model");
- match whisper_sender.try_send(AudioInput {
- data: Arc::new(collected_audio.clone()),
- device: audio_stream.device.clone(),
- sample_rate: audio_stream.device_config.sample_rate().0,
- channels: audio_stream.device_config.channels(),
- }) {
- Ok(_) => {
- debug!("sent audio segment to audio model");
- if collected_audio.len() > overlap_samples {
- collected_audio =
- collected_audio.split_off(collected_audio.len() - overlap_samples);
- }
- }
- Err(e) => {
- if e.is_disconnected() {
- error!("whisper channel disconnected, restarting recording process");
- return Err(anyhow!("Whisper channel disconnected"));
- } else if e.is_full() {
- warn!("whisper channel full, dropping audio segment");
- tokio::time::sleep(Duration::from_millis(100)).await;
- }
- }
- }
- }
- }
-
- info!("stopped recording for {}", audio_stream.device.to_string());
- Ok(())
-}
-
-pub async fn list_audio_devices() -> Result<Vec<AudioDevice>> {
- let host = cpal::default_host();
- let mut devices = Vec::new();
-
- for device in host.input_devices()? {
- if let Ok(name) = device.name() {
- devices.push(AudioDevice::new(name, DeviceType::Input));
- }
- }
-
- // Filter function to exclude macOS speakers and AirPods for output devices
- fn should_include_output_device(name: &str) -> bool {
- #[cfg(target_os = "macos")]
- {
- !name.to_lowercase().contains("speakers") && !name.to_lowercase().contains("airpods")
- }
- #[cfg(not(target_os = "macos"))]
- {
- // Avoid "unused variable" warning in non-macOS systems
- let _ = name;
- true
- }
- }
-
- // macos hack using screen capture kit for output devices - does not work well
- #[cfg(target_os = "macos")]
- {
- // !HACK macos is supposed to use special macos feature "display capture"
- // ! see https://github.com/RustAudio/cpal/pull/894
- if let Ok(host) = cpal::host_from_id(cpal::HostId::ScreenCaptureKit) {
- for device in host.input_devices()? {
- if let Ok(name) = device.name() {
- if should_include_output_device(&name) {
- devices.push(AudioDevice::new(name, DeviceType::Output));
- }
- }
- }
- }
- }
-
- // add default output device - on macos think of custom virtual devices
- for device in host.output_devices()? {
- if let Ok(name) = device.name() {
- if should_include_output_device(&name) {
- devices.push(AudioDevice::new(name, DeviceType::Output));
- }
- }
- }
-
- // last, add devices that are listed in .devices() which are not already in the devices vector
- let other_devices = host.devices().unwrap();
- for device in other_devices {
- if !devices.iter().any(|d| d.name == device.name().unwrap())
- && should_include_output_device(&device.name().unwrap())
- {
- // TODO: not sure if it can be input, usually aggregate or multi output
- devices.push(AudioDevice::new(device.name().unwrap(), DeviceType::Output));
- }
- }
-
- Ok(devices)
-}
-
-pub fn default_input_device() -> Result<AudioDevice> {
- let host = cpal::default_host();
- let device = host
- .default_input_device()
- .ok_or(anyhow!("No default input device detected"))?;
- Ok(AudioDevice::new(device.name()?, DeviceType::Input))
-}
-// this should be optional ?
-pub fn default_output_device() -> Result<AudioDevice> {
- #[cfg(target_os = "macos")]
- {
- // ! see https://github.com/RustAudio/cpal/pull/894
- if let Ok(host) = cpal::host_from_id(cpal::HostId::ScreenCaptureKit) {
- if let Some(device) = host.default_input_device() {
- if let Ok(name) = device.name() {
- return Ok(AudioDevice::new(name, DeviceType::Output));
- }
- }
- }
- let host = cpal::default_host();
- let device = host
- .default_output_device()
- .ok_or_else(|| anyhow!("No default output device found"))?;
- Ok(AudioDevice::new(device.name()?, DeviceType::Output))
- }
-
- #[cfg(not(target_os = "macos"))]
- {
- let host = cpal::default_host();
- let device = host
- .default_output_device()
- .ok_or_else(|| anyhow!("No default output device found"))?;
- return Ok(AudioDevice::new(device.name()?, DeviceType::Output));
- }
-}
-
-pub fn trigger_audio_permission() -> Result<()> {
- let host = cpal::default_host();
- let device = host
- .default_input_device()
- .ok_or_else(|| anyhow!("No default input device found"))?;
-
- let config = device.default_input_config()?;
-
- // Attempt to build an input stream, which should trigger the permission request
- let _stream = device.build_input_stream(
- &config.into(),
- |_data: &[f32], _: &cpal::InputCallbackInfo| {
- // Do nothing, we just want to trigger the permission request
- },
- |err| eprintln!("Error in audio stream: {}", err),
- None,
- )?;
-
- // We don't actually need to start the stream
- // The mere attempt to build it should trigger the permission request
-
- Ok(())
-}
-
-#[derive(Clone)]
-pub struct AudioStream {
- pub device: Arc<AudioDevice>,
- pub device_config: cpal::SupportedStreamConfig,
- transmitter: Arc<tokio::sync::broadcast::Sender<Vec<f32>>>,
- stream_control: mpsc::Sender<StreamControl>,
- stream_thread: Option<Arc<tokio::sync::Mutex<Option<thread::JoinHandle<()>>>>>,
- is_disconnected: Arc<AtomicBool>,
-}
-
-enum StreamControl {
- Stop(oneshot::Sender<()>),
-}
-
-impl AudioStream {
- pub async fn from_device(
- device: Arc<AudioDevice>,
- is_running: Arc<AtomicBool>,
- ) -> Result<Self> {
- let (tx, _) = broadcast::channel::<Vec<f32>>(1000);
- let tx_clone = tx.clone();
- let (cpal_audio_device, config) = get_device_and_config(&device).await?;
- let channels = config.channels();
-
- let is_running_weak_2 = Arc::downgrade(&is_running);
- let is_disconnected = Arc::new(AtomicBool::new(false));
- let device_clone = device.clone();
- let config_clone = config.clone();
- let (stream_control_tx, stream_control_rx) = mpsc::channel();
-
- let is_disconnected_clone = is_disconnected.clone();
- let stream_control_tx_clone = stream_control_tx.clone();
- let stream_thread = Arc::new(tokio::sync::Mutex::new(Some(thread::spawn(move || {
- let device = device_clone;
- let device_name = device.to_string();
- let config = config_clone;
- let error_callback = move |err: StreamError| {
- if err
- .to_string()
- .contains("The requested device is no longer available")
- {
- warn!(
- "audio device {} disconnected. stopping recording.",
- device_name
- );
- stream_control_tx_clone
- .send(StreamControl::Stop(oneshot::channel().0))
- .unwrap();
-
- is_disconnected_clone.store(true, Ordering::Relaxed);
- } else {
- error!("an error occurred on the audio stream: {}", err);
- if err.to_string().contains("device is no longer valid") {
- warn!("audio device disconnected. stopping recording.");
- if let Some(arc) = is_running_weak_2.upgrade() {
- arc.store(false, Ordering::Relaxed);
- }
- }
- }
- };
-
- let stream = match config.sample_format() {
- cpal::SampleFormat::F32 => cpal_audio_device
- .build_input_stream(
- &config.into(),
- move |data: &[f32], _: &_| {
- let mono = audio_to_mono(data, channels);
- let _ = tx.send(mono);
- },
- error_callback,
- None,
- )
- .expect("Failed to build input stream"),
- cpal::SampleFormat::I16 => cpal_audio_device
- .build_input_stream(
- &config.into(),
- move |data: &[i16], _: &_| {
- let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
- let _ = tx.send(mono);
- },
- error_callback,
- None,
- )
- .expect("Failed to build input stream"),
- cpal::SampleFormat::I32 => cpal_audio_device
- .build_input_stream(
- &config.into(),
- move |data: &[i32], _: &_| {
- let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
- let _ = tx.send(mono);
- },
- error_callback,
- None,
- )
- .expect("Failed to build input stream"),
- cpal::SampleFormat::I8 => cpal_audio_device
- .build_input_stream(
- &config.into(),
- move |data: &[i8], _: &_| {
- let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
- let _ = tx.send(mono);
- },
- error_callback,
- None,
- )
- .expect("Failed to build input stream"),
- _ => {
- error!("unsupported sample format: {}", config.sample_format());
- return;
- }
- };
-
- if let Err(e) = stream.play() {
- error!("failed to play stream for {}: {}", device.to_string(), e);
- }
-
- if let Ok(StreamControl::Stop(response)) = stream_control_rx.recv() {
- info!("stopped recording audio stream");
- stream.pause().ok();
- drop(stream);
- response.send(()).ok();
- }
- }))));
-
- Ok(AudioStream {
- device,
- device_config: config,
- transmitter: Arc::new(tx_clone),
- stream_control: stream_control_tx,
- stream_thread: Some(stream_thread),
- is_disconnected,
- })
- }
-
- pub async fn subscribe(&self) -> broadcast::Receiver<Vec<f32>> {
- self.transmitter.subscribe()
- }
-
- pub async fn stop(mut self) -> Result<()> {
- self.is_disconnected.store(true, Ordering::Relaxed);
- let (tx, rx) = oneshot::channel();
- self.stream_control.send(StreamControl::Stop(tx))?;
- rx.await?;
-
- if let Some(thread_arc) = self.stream_thread.take() {
- let thread_handle = tokio::task::spawn_blocking(move || {
- let mut thread_guard = thread_arc.blocking_lock();
- if let Some(join_handle) = thread_guard.take() {
- join_handle
- .join()
- .map_err(|_| anyhow!("failed to join stream thread"))
- } else {
- Ok(())
- }
- });
-
- thread_handle.await??;
- }
-
- Ok(())
- }
-}
diff --git a/screenpipe-audio/src/core/device.rs b/screenpipe-audio/src/core/device.rs
new file mode 100644
index 000000000..1ab65664d
--- /dev/null
+++ b/screenpipe-audio/src/core/device.rs
@@ -0,0 +1,275 @@
+use std::{fmt, sync::Arc};
+
+use anyhow::{anyhow, Result};
+use cpal::traits::{DeviceTrait, HostTrait};
+use oasgen::OaSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(OaSchema, Clone, Debug)]
+pub struct DeviceControl {
+ pub is_running: bool,
+ pub is_paused: bool,
+}
+
+#[derive(OaSchema, Clone, Eq, PartialEq, Hash, Serialize, Debug, Deserialize)]
+pub enum DeviceType {
+ Input,
+ Output,
+}
+
+impl From<screenpipe_db::DeviceType> for DeviceType {
+ fn from(device_type: screenpipe_db::DeviceType) -> Self {
+ match device_type {
+ screenpipe_db::DeviceType::Input => DeviceType::Input,
+ screenpipe_db::DeviceType::Output => DeviceType::Output,
+ }
+ }
+}
+
+impl From<DeviceType> for screenpipe_db::DeviceType {
+ fn from(device_type: DeviceType) -> Self {
+ match device_type {
+ DeviceType::Input => screenpipe_db::DeviceType::Input,
+ DeviceType::Output => screenpipe_db::DeviceType::Output,
+ }
+ }
+}
+
+impl From<DeviceType> for Arc<screenpipe_db::DeviceType> {
+ fn from(device_type: DeviceType) -> Self {
+ Arc::new(match device_type {
+ DeviceType::Input => screenpipe_db::DeviceType::Input,
+ DeviceType::Output => screenpipe_db::DeviceType::Output,
+ })
+ }
+}
+
+#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug)]
+pub struct AudioDevice {
+ pub name: String,
+ pub device_type: DeviceType,
+}
+
+impl From<screenpipe_db::AudioDevice> for AudioDevice {
+ fn from(device: screenpipe_db::AudioDevice) -> Self {
+ AudioDevice {
+ name: device.name,
+ device_type: device.device_type.into(),
+ }
+ }
+}
+
+impl AudioDevice {
+ pub fn new(name: String, device_type: DeviceType) -> Self {
+ AudioDevice { name, device_type }
+ }
+
+ pub fn from_name(name: &str) -> Result<Self> {
+ if name.trim().is_empty() {
+ return Err(anyhow!("Device name cannot be empty"));
+ }
+
+ let (name, device_type) = match name.to_lowercase() {
+ n if n.ends_with("(input)") => (
+ name.trim_end_matches("(input)").trim().to_string(),
+ DeviceType::Input,
+ ),
+ n if n.ends_with("(output)") => (
+ name.trim_end_matches("(output)").trim().to_string(),
+ DeviceType::Output,
+ ),
+ _ => {
+ return Err(anyhow!(
+ "Device type (input/output) not specified in the name"
+ ))
+ }
+ };
+
+ Ok(AudioDevice::new(name, device_type))
+ }
+}
+
+impl fmt::Display for AudioDevice {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(
+ f,
+ "{} ({})",
+ self.name,
+ match self.device_type {
+ DeviceType::Input => "input",
+ DeviceType::Output => "output",
+ }
+ )
+ }
+}
+
+pub fn parse_audio_device(name: &str) -> Result<AudioDevice> {
+ AudioDevice::from_name(name)
+}
+
+pub async fn get_cpal_device_and_config(
+ audio_device: &AudioDevice,
+) -> Result<(cpal::Device, cpal::SupportedStreamConfig)> {
+ let host = cpal::default_host();
+ let is_output_device = audio_device.device_type == DeviceType::Output;
+ let is_display = audio_device.to_string().contains("Display");
+ let device_name = audio_device
+ .to_string()
+ .replace(" (input)", "")
+ .replace(" (output)", "")
+ .trim()
+ .to_string();
+
+ let cpal_audio_device = if audio_device.to_string() == "default" {
+ match audio_device.device_type {
+ DeviceType::Input => host.default_input_device(),
+ DeviceType::Output => host.default_output_device(),
+ }
+ } else {
+ let mut devices = match audio_device.device_type {
+ DeviceType::Input => host.input_devices()?,
+ DeviceType::Output => host.output_devices()?,
+ };
+
+ #[cfg(target_os = "macos")]
+ if is_output_device {
+ if let Ok(screen_capture_host) = cpal::host_from_id(cpal::HostId::ScreenCaptureKit) {
+ devices = screen_capture_host.input_devices()?;
+ }
+ }
+
+ devices.find(|x| x.name().map(|y| y == device_name).unwrap_or(false))
+ }
+ .ok_or_else(|| anyhow!("Audio device not found: {}", device_name))?;
+
+ let config = if is_output_device && !is_display {
+ cpal_audio_device.default_output_config()?
+ } else {
+ cpal_audio_device.default_input_config()?
+ };
+
+ Ok((cpal_audio_device, config))
+}
+
+pub async fn list_audio_devices() -> Result<Vec<AudioDevice>> {
+ let host = cpal::default_host();
+ let mut devices = Vec::new();
+
+ for device in host.input_devices()? {
+ if let Ok(name) = device.name() {
+ devices.push(AudioDevice::new(name, DeviceType::Input));
+ }
+ }
+
+ // Filter function to exclude macOS speakers and AirPods for output devices
+ fn should_include_output_device(name: &str) -> bool {
+ #[cfg(target_os = "macos")]
+ {
+ !name.to_lowercase().contains("speakers") && !name.to_lowercase().contains("airpods")
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ // Avoid "unused variable" warning in non-macOS systems
+ let _ = name;
+ true
+ }
+ }
+
+ // macos hack using screen capture kit for output devices - does not work well
+ #[cfg(target_os = "macos")]
+ {
+ // !HACK macos is supposed to use special macos feature "display capture"
+ // ! see https://github.com/RustAudio/cpal/pull/894
+ if let Ok(host) = cpal::host_from_id(cpal::HostId::ScreenCaptureKit) {
+ for device in host.input_devices()? {
+ if let Ok(name) = device.name() {
+ if should_include_output_device(&name) {
+ devices.push(AudioDevice::new(name, DeviceType::Output));
+ }
+ }
+ }
+ }
+ }
+
+ // add default output device - on macos think of custom virtual devices
+ for device in host.output_devices()? {
+ if let Ok(name) = device.name() {
+ if should_include_output_device(&name) {
+ devices.push(AudioDevice::new(name, DeviceType::Output));
+ }
+ }
+ }
+
+ // last, add devices that are listed in .devices() which are not already in the devices vector
+ let other_devices = host.devices().unwrap();
+ for device in other_devices {
+ if !devices.iter().any(|d| d.name == device.name().unwrap())
+ && should_include_output_device(&device.name().unwrap())
+ {
+ // TODO: not sure if it can be input, usually aggregate or multi output
+ devices.push(AudioDevice::new(device.name().unwrap(), DeviceType::Output));
+ }
+ }
+
+ Ok(devices)
+}
+
+pub fn default_input_device() -> Result<AudioDevice> {
+ let host = cpal::default_host();
+ let device = host
+ .default_input_device()
+ .ok_or(anyhow!("No default input device detected"))?;
+ Ok(AudioDevice::new(device.name()?, DeviceType::Input))
+}
+// this should be optional ?
+pub fn default_output_device() -> Result<AudioDevice> {
+ #[cfg(target_os = "macos")]
+ {
+ // ! see https://github.com/RustAudio/cpal/pull/894
+ if let Ok(host) = cpal::host_from_id(cpal::HostId::ScreenCaptureKit) {
+ if let Some(device) = host.default_input_device() {
+ if let Ok(name) = device.name() {
+ return Ok(AudioDevice::new(name, DeviceType::Output));
+ }
+ }
+ }
+ let host = cpal::default_host();
+ let device = host
+ .default_output_device()
+ .ok_or_else(|| anyhow!("No default output device found"))?;
+ Ok(AudioDevice::new(device.name()?, DeviceType::Output))
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ {
+ let host = cpal::default_host();
+ let device = host
+ .default_output_device()
+ .ok_or_else(|| anyhow!("No default output device found"))?;
+ return Ok(AudioDevice::new(device.name()?, DeviceType::Output));
+ }
+}
+
+pub fn trigger_audio_permission() -> Result<()> {
+ let host = cpal::default_host();
+ let device = host
+ .default_input_device()
+ .ok_or_else(|| anyhow!("No default input device found"))?;
+
+ let config = device.default_input_config()?;
+
+ // Attempt to build an input stream, which should trigger the permission request
+ let _stream = device.build_input_stream(
+ &config.into(),
+ |_data: &[f32], _: &cpal::InputCallbackInfo| {
+ // Do nothing, we just want to trigger the permission request
+ },
+ |err| eprintln!("Error in audio stream: {}", err),
+ None,
+ )?;
+
+ // We don't actually need to start the stream
+ // The mere attempt to build it should trigger the permission request
+
+ Ok(())
+}
diff --git a/screenpipe-audio/src/core/engine.rs b/screenpipe-audio/src/core/engine.rs
new file mode 100644
index 000000000..e35717dd7
--- /dev/null
+++ b/screenpipe-audio/src/core/engine.rs
@@ -0,0 +1,31 @@
+use std::fmt;
+
+#[derive(Clone, Debug, PartialEq, Default)]
+pub enum AudioTranscriptionEngine {
+ Deepgram,
+ WhisperTiny,
+ WhisperTinyQuantized,
+ #[default]
+ WhisperLargeV3Turbo,
+ WhisperLargeV3TurboQuantized,
+ WhisperLargeV3,
+ WhisperLargeV3Quantized,
+}
+
+impl fmt::Display for AudioTranscriptionEngine {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ AudioTranscriptionEngine::Deepgram => write!(f, "Deepgram"),
+ AudioTranscriptionEngine::WhisperTiny => write!(f, "WhisperTiny"),
+ AudioTranscriptionEngine::WhisperTinyQuantized => write!(f, "WhisperTinyQuantized"),
+ AudioTranscriptionEngine::WhisperLargeV3 => write!(f, "WhisperLargeV3"),
+ AudioTranscriptionEngine::WhisperLargeV3Quantized => {
+ write!(f, "WhisperLargeV3Quantized")
+ }
+ AudioTranscriptionEngine::WhisperLargeV3Turbo => write!(f, "WhisperLargeV3Turbo"),
+ AudioTranscriptionEngine::WhisperLargeV3TurboQuantized => {
+ write!(f, "WhisperLargeV3TurboQuantized")
+ }
+ }
+ }
+}
diff --git a/screenpipe-audio/src/core/mod.rs b/screenpipe-audio/src/core/mod.rs
new file mode 100644
index 000000000..af9892490
--- /dev/null
+++ b/screenpipe-audio/src/core/mod.rs
@@ -0,0 +1,83 @@
+pub mod device;
+pub mod engine;
+mod run_record_and_transcribe;
+pub mod stream;
+use crate::transcription::deepgram::streaming::stream_transcription_deepgram;
+use crate::AudioInput;
+use anyhow::Result;
+use lazy_static::lazy_static;
+use screenpipe_core::Language;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use stream::AudioStream;
+use tracing::error;
+
+lazy_static! {
+ pub static ref LAST_AUDIO_CAPTURE: AtomicU64 = AtomicU64::new(
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs()
+ );
+}
+
+fn is_normal_shutdown(is_running: &Arc<AtomicBool>) -> bool {
+ !is_running.load(Ordering::Relaxed)
+}
+
+pub async fn record_and_transcribe(
+ audio_stream: Arc<AudioStream>,
+ duration: Duration,
+ whisper_sender: Arc<crossbeam::channel::Sender<AudioInput>>,
+ is_running: Arc<AtomicBool>,
+) -> Result<()> {
+ while is_running.load(Ordering::Relaxed) {
+ match run_record_and_transcribe::run_record_and_transcribe(
+ audio_stream.clone(),
+ duration,
+ whisper_sender.clone(),
+ is_running.clone(),
+ )
+ .await
+ {
+ Ok(_) => break, // Normal shutdown
+ Err(e) => {
+ if is_normal_shutdown(&is_running) {
+ return Err(e);
+ }
+ error!("record_and_transcribe error, restarting: {}", e);
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ }
+ }
+ }
+ Ok(())
+}
+
+pub async fn start_realtime_recording(
+ audio_stream: Arc<AudioStream>,
+ languages: Vec<Language>,
+ is_running: Arc<AtomicBool>,
+ deepgram_api_key: Option<String>,
+) -> Result<()> {
+ while is_running.load(Ordering::Relaxed) {
+ match stream_transcription_deepgram(
+ audio_stream.clone(),
+ languages.clone(),
+ is_running.clone(),
+ deepgram_api_key.clone(),
+ )
+ .await
+ {
+ Ok(_) => break, // Normal shutdown
+ Err(e) => {
+ if is_normal_shutdown(&is_running) {
+ break;
+ }
+ error!("realtime_stt error, restarting: {}", e);
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ }
+ }
+ }
+ Ok(())
+}
diff --git a/screenpipe-audio/src/core/run_record_and_transcribe.rs b/screenpipe-audio/src/core/run_record_and_transcribe.rs
new file mode 100644
index 000000000..aba7f3546
--- /dev/null
+++ b/screenpipe-audio/src/core/run_record_and_transcribe.rs
@@ -0,0 +1,89 @@
+use std::{
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
+ time::Duration,
+};
+
+use anyhow::{anyhow, Result};
+use tracing::{debug, error, info, warn};
+
+use crate::{core::LAST_AUDIO_CAPTURE, AudioInput};
+
+use super::AudioStream;
+
+pub async fn run_record_and_transcribe(
+ audio_stream: Arc<AudioStream>,
+ duration: Duration,
+ whisper_sender: Arc<crossbeam::channel::Sender<AudioInput>>,
+ is_running: Arc<AtomicBool>,
+) -> Result<()> {
+ let mut receiver = audio_stream.subscribe().await;
+
+ info!(
+ "starting continuous recording for {} ({}s segments)",
+ audio_stream.device.to_string(),
+ duration.as_secs()
+ );
+
+ const OVERLAP_SECONDS: usize = 2;
+ let mut collected_audio = Vec::new();
+ let sample_rate = audio_stream.device_config.sample_rate().0 as usize;
+ let audio_samples_len = sample_rate * duration.as_secs() as usize;
+ let overlap_samples = OVERLAP_SECONDS * sample_rate;
+ let max_samples = audio_samples_len + overlap_samples;
+
+ while is_running.load(Ordering::Relaxed)
+ && !audio_stream.is_disconnected.load(Ordering::Relaxed)
+ {
+ while collected_audio.len() < max_samples && is_running.load(Ordering::Relaxed) {
+ match receiver.recv().await {
+ Ok(chunk) => {
+ collected_audio.extend(chunk);
+ LAST_AUDIO_CAPTURE.store(
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs(),
+ Ordering::Relaxed,
+ );
+ }
+ Err(e) => {
+ error!("error receiving audio data: {}", e);
+ return Err(anyhow!("Audio stream error: {}", e));
+ }
+ }
+ }
+
+ if !collected_audio.is_empty() {
+ debug!("sending audio segment to audio model");
+ match whisper_sender.try_send(AudioInput {
+ data: Arc::new(collected_audio.clone()),
+ device: audio_stream.device.clone(),
+ sample_rate: audio_stream.device_config.sample_rate().0,
+ channels: audio_stream.device_config.channels(),
+ }) {
+ Ok(_) => {
+ debug!("sent audio segment to audio model");
+ if collected_audio.len() > overlap_samples {
+ collected_audio =
+ collected_audio.split_off(collected_audio.len() - overlap_samples);
+ }
+ }
+ Err(e) => {
+ if e.is_disconnected() {
+ error!("whisper channel disconnected, restarting recording process");
+ return Err(anyhow!("Whisper channel disconnected"));
+ } else if e.is_full() {
+ warn!("whisper channel full, dropping audio segment");
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+ }
+ }
+ }
+
+ info!("stopped recording for {}", audio_stream.device.to_string());
+ Ok(())
+}
diff --git a/screenpipe-audio/src/core/stream.rs b/screenpipe-audio/src/core/stream.rs
new file mode 100644
index 000000000..e3c5ef0b9
--- /dev/null
+++ b/screenpipe-audio/src/core/stream.rs
@@ -0,0 +1,240 @@
+use anyhow::{anyhow, Result};
+use cpal::traits::{DeviceTrait, StreamTrait};
+use cpal::StreamError;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::mpsc;
+use std::sync::Arc;
+use tokio::sync::{broadcast, oneshot};
+use tokio::task::LocalSet;
+use tracing::{error, warn};
+
+use crate::utils::audio::audio_to_mono;
+
+use super::device::{get_cpal_device_and_config, AudioDevice};
+
+#[derive(Clone)]
+pub struct AudioStream {
+ pub device: Arc<AudioDevice>,
+ pub device_config: cpal::SupportedStreamConfig,
+ transmitter: Arc<tokio::sync::broadcast::Sender<Vec<f32>>>,
+ stream_control: mpsc::Sender<StreamControl>,
+ stream_thread: Option<Arc<tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>>>,
+ pub is_disconnected: Arc<AtomicBool>,
+}
+
+enum StreamControl {
+ Stop(oneshot::Sender<()>),
+}
+
+impl AudioStream {
+ pub async fn from_device(
+ device: Arc<AudioDevice>,
+ is_running: Arc<AtomicBool>,
+ ) -> Result<Self> {
+ let (tx, _) = broadcast::channel::<Vec<f32>>(1000);
+ let tx_clone = tx.clone();
+ let (cpal_audio_device, config) = get_cpal_device_and_config(&device).await?;
+ let channels = config.channels();
+
+ let is_running_weak = Arc::downgrade(&is_running);
+ let is_disconnected = Arc::new(AtomicBool::new(false));
+ let (stream_control_tx, stream_control_rx) = mpsc::channel();
+
+ let stream_thread = Self::spawn_audio_thread(
+ cpal_audio_device,
+ config.clone(),
+ tx,
+ stream_control_rx,
+ channels,
+ is_running_weak,
+ is_disconnected.clone(),
+ stream_control_tx.clone(),
+ )
+ .await?;
+
+ Ok(AudioStream {
+ device,
+ device_config: config,
+ transmitter: Arc::new(tx_clone),
+ stream_control: stream_control_tx,
+ stream_thread: Some(Arc::new(tokio::sync::Mutex::new(Some(stream_thread)))),
+ is_disconnected,
+ })
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ async fn spawn_audio_thread(
+ device: cpal::Device,
+ config: cpal::SupportedStreamConfig,
+ tx: broadcast::Sender<Vec<f32>>,
+ stream_control_rx: mpsc::Receiver<StreamControl>,
+ channels: u16,
+ is_running_weak: std::sync::Weak<AtomicBool>,
+ is_disconnected: Arc<AtomicBool>,
+ stream_control_tx: mpsc::Sender<StreamControl>,
+ ) -> Result<tokio::task::JoinHandle<()>> {
+ let device_name = device.name()?;
+
+ Ok(tokio::task::spawn_blocking(move || {
+ let error_callback = create_error_callback(
+ device_name.clone(),
+ is_running_weak,
+ is_disconnected,
+ stream_control_tx,
+ );
+
+ let stream = build_input_stream(&device, &config, channels, tx, error_callback);
+
+ match stream {
+ Ok(stream) => {
+ if let Err(e) = stream.play() {
+ error!("failed to play stream for {}: {}", device_name, e);
+ return;
+ }
+
+ if let Ok(StreamControl::Stop(response)) = stream_control_rx.recv() {
+ stream.pause().ok();
+ drop(stream);
+ response.send(()).ok();
+ }
+ }
+ Err(e) => {
+ error!("Failed to build input stream: {}", e);
+ }
+ }
+ }))
+ }
+
+ pub async fn subscribe(&self) -> broadcast::Receiver<Vec<f32>> {
+ self.transmitter.subscribe()
+ }
+
+ pub async fn stop(&self) -> Result<()> {
+ self.is_disconnected.store(true, Ordering::Relaxed);
+ let (tx, rx) = oneshot::channel();
+ self.stream_control.send(StreamControl::Stop(tx))?;
+ rx.await?;
+
+ if let Some(thread_arc) = self.stream_thread.as_ref() {
+ let thread_arc_clone = thread_arc.clone();
+ let thread_handle = tokio::task::spawn_blocking(move || {
+ let mut thread_guard = thread_arc_clone.blocking_lock();
+ if let Some(join_handle) = thread_guard.take() {
+ join_handle.abort();
+ }
+ });
+
+ thread_handle.await?;
+ }
+
+ Ok(())
+ }
+
+ pub fn is_disconnected(&self) -> bool {
+ self.is_disconnected.load(Ordering::Relaxed)
+ }
+}
+
+fn create_error_callback(
+ device_name: String,
+ is_running_weak: std::sync::Weak<AtomicBool>,
+ is_disconnected: Arc<AtomicBool>,
+ stream_control_tx: mpsc::Sender<StreamControl>,
+) -> impl FnMut(StreamError) + Send + 'static {
+ move |err: StreamError| {
+ if err
+ .to_string()
+ .contains("The requested device is no longer available")
+ {
+ warn!(
+ "audio device {} disconnected. stopping recording.",
+ device_name
+ );
+ stream_control_tx
+ .send(StreamControl::Stop(oneshot::channel().0))
+ .unwrap();
+ is_disconnected.store(true, Ordering::Relaxed);
+ } else {
+ error!("an error occurred on the audio stream: {}", err);
+ if err.to_string().contains("device is no longer valid") {
+ warn!("audio device disconnected. stopping recording.");
+ if let Some(arc) = is_running_weak.upgrade() {
+ arc.store(false, Ordering::Relaxed);
+ }
+ }
+ }
+ }
+}
+
+fn build_input_stream(
+ device: &cpal::Device,
+ config: &cpal::SupportedStreamConfig,
+ channels: u16,
+ tx: broadcast::Sender<Vec<f32>>,
+ error_callback: impl FnMut(StreamError) + Send + 'static,
+) -> Result<cpal::Stream> {
+ match config.sample_format() {
+ cpal::SampleFormat::F32 => device
+ .build_input_stream(
+ &config.config(),
+ move |data: &[f32], _: &_| {
+ let mono = audio_to_mono(data, channels);
+ let _ = tx.send(mono);
+ },
+ error_callback,
+ None,
+ )
+ .map_err(|e| anyhow!(e)),
+ cpal::SampleFormat::I16 => device
+ .build_input_stream(
+ &config.config(),
+ move |data: &[i16], _: &_| {
+ let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
+ let _ = tx.send(mono);
+ },
+ error_callback,
+ None,
+ )
+ .map_err(|e| anyhow!(e)),
+ cpal::SampleFormat::I32 => device
+ .build_input_stream(
+ &config.config(),
+ move |data: &[i32], _: &_| {
+ let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
+ let _ = tx.send(mono);
+ },
+ error_callback,
+ None,
+ )
+ .map_err(|e| anyhow!(e)),
+ cpal::SampleFormat::I8 => device
+ .build_input_stream(
+ &config.config(),
+ move |data: &[i8], _: &_| {
+ let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
+ let _ = tx.send(mono);
+ },
+ error_callback,
+ None,
+ )
+ .map_err(|e| anyhow!(e)),
+ _ => Err(anyhow!(
+ "unsupported sample format: {}",
+ config.sample_format()
+ )),
+ }
+}
+
+impl Drop for AudioStream {
+ fn drop(&mut self) {
+ let set = LocalSet::new();
+
+ let stream_control = self.stream_control.clone();
+ let is_disconnected = self.is_disconnected.clone();
+
+ set.spawn_local(async move {
+ let _ = stream_control.send(StreamControl::Stop(oneshot::channel().0));
+ is_disconnected.store(true, Ordering::Relaxed);
+ });
+ }
+}
diff --git a/screenpipe-audio/src/device/device_manager.rs b/screenpipe-audio/src/device/device_manager.rs
new file mode 100644
index 000000000..7c63249ba
--- /dev/null
+++ b/screenpipe-audio/src/device/device_manager.rs
@@ -0,0 +1,102 @@
+use crate::core::{
+ device::{list_audio_devices, AudioDevice},
+ stream::AudioStream,
+};
+use anyhow::{anyhow, Result};
+use dashmap::DashMap;
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+};
+use tracing::info;
+
+pub struct DeviceManager {
+ streams: Arc<DashMap<AudioDevice, Arc<AudioStream>>>,
+ states: Arc<DashMap<AudioDevice, Arc<AtomicBool>>>,
+}
+
+impl DeviceManager {
+ pub async fn new() -> Result<Self> {
+ let streams = Arc::new(DashMap::new());
+ let states = Arc::new(DashMap::new());
+
+ Ok(Self { streams, states })
+ }
+
+ pub async fn devices(&self) -> Vec<AudioDevice> {
+ list_audio_devices().await.unwrap_or_default()
+ }
+
+ pub async fn start_device(&self, device: &AudioDevice) -> Result<()> {
+ if !self.devices().await.contains(device) {
+ return Err(anyhow!("device {device} not found"));
+ }
+
+ if self.is_running(device) {
+ return Err(anyhow!("Device {} already running.", device));
+ }
+
+ let is_running = Arc::new(AtomicBool::new(false));
+ let stream =
+ match AudioStream::from_device(Arc::new(device.clone()), is_running.clone()).await {
+ Ok(stream) => stream,
+ Err(e) => {
+ return Err(e);
+ }
+ };
+
+ info!("starting recording for device: {}", device);
+
+ self.streams.insert(device.clone(), Arc::new(stream));
+ self.states.insert(device.clone(), is_running);
+
+ Ok(())
+ }
+
+ pub fn stream(&self, device: &AudioDevice) -> Option<Arc<AudioStream>> {
+ self.streams.get(device).map(|s| s.value().clone())
+ }
+
+ pub fn is_running(&self, device: &AudioDevice) -> bool {
+ self.states
+ .get(device)
+ .map(|s| s.load(Ordering::Relaxed))
+ .unwrap_or(false)
+ }
+
+ pub async fn stop_all_devices(&self) -> Result<()> {
+ for pair in self.states.iter() {
+ let device = pair.key();
+ let _ = self.stop_device(device).await;
+ }
+
+ self.states.clear();
+ self.streams.clear();
+
+ Ok(())
+ }
+
+ pub async fn stop_device(&self, device: &AudioDevice) -> Result<()> {
+ if !self.is_running(device) {
+ return Err(anyhow!("Device {} already stopped", device));
+ }
+
+ info!("Stopping device: {device}");
+
+ if let Some(is_running) = self.states.get(device) {
+ is_running.store(false, Ordering::Relaxed)
+ }
+
+ if let Some(p) = self.streams.get(device) {
+ let _ = p.value().stop().await;
+ }
+
+ self.streams.remove(device);
+
+ Ok(())
+ }
+
+ pub fn is_running_mut(&self, device: &AudioDevice) -> Option<Arc<AtomicBool>> {
+ self.states.get(device).map(|s| s.value().clone())
+ }
+}
diff --git a/screenpipe-audio/src/device/mod.rs b/screenpipe-audio/src/device/mod.rs
new file mode 100644
index 000000000..005c44fc9
--- /dev/null
+++ b/screenpipe-audio/src/device/mod.rs
@@ -0,0 +1 @@
+pub mod device_manager;
diff --git a/screenpipe-audio/src/lib.rs b/screenpipe-audio/src/lib.rs
index 6251b3100..1d1d7b283 100644
--- a/screenpipe-audio/src/lib.rs
+++ b/screenpipe-audio/src/lib.rs
@@ -1,24 +1,12 @@
-pub mod audio_processing;
-mod core;
-pub mod deepgram;
-pub mod encode;
-mod multilingual;
-pub mod pcm_decode;
-pub mod pyannote;
-mod segments;
-pub mod stt;
-mod tokenizer;
-pub mod vad_engine;
-pub mod whisper;
-pub use audio_processing::resample;
-pub use core::{
- default_input_device, default_output_device, get_device_and_config, list_audio_devices,
- parse_audio_device, record_and_transcribe, start_realtime_recording, trigger_audio_permission,
- AudioDevice, AudioStream, AudioTranscriptionEngine, DeviceControl, DeviceType,
- LAST_AUDIO_CAPTURE,
-};
-pub mod realtime;
-pub use encode::encode_single_audio;
-pub use pcm_decode::pcm_decode;
-pub use stt::{create_whisper_channel, stt, AudioInput, TranscriptionResult};
-pub use vad_engine::VadEngineEnum;
+pub mod core;
+mod utils;
+pub mod vad;
+pub use transcription::stt::stt;
+pub use transcription::{AudioInput, TranscriptionResult};
+pub mod speaker;
+pub mod transcription;
+pub use utils::audio::pcm_decode;
+pub use utils::audio::resample;
+pub mod audio_manager;
+mod device;
+mod segmentation;
diff --git a/screenpipe-audio/src/multilingual.rs b/screenpipe-audio/src/multilingual.rs
deleted file mode 100644
index 1faf71ee5..000000000
--- a/screenpipe-audio/src/multilingual.rs
+++ /dev/null
@@ -1,163 +0,0 @@
-use crate::whisper::{token_id, Model};
-use candle::IndexOp;
-use candle::{Result, Tensor, D};
-use candle_transformers::models::whisper::SOT_TOKEN;
-use log::debug;
-use screenpipe_core::Language;
-use tokenizers::Tokenizer;
-
-pub const LANGUAGES: [(&str, &str); 99] = [
- ("en", "english"),
- ("zh", "chinese"),
- ("de", "german"),
- ("es", "spanish"),
- ("ru", "russian"),
- ("ko", "korean"),
- ("fr", "french"),
- ("ja", "japanese"),
- ("pt", "portuguese"),
- ("tr", "turkish"),
- ("pl", "polish"),
- ("ca", "catalan"),
- ("nl", "dutch"),
- ("ar", "arabic"),
- ("sv", "swedish"),
- ("it", "italian"),
- ("id", "indonesian"),
- ("hi", "hindi"),
- ("fi", "finnish"),
- ("vi", "vietnamese"),
- ("he", "hebrew"),
- ("uk", "ukrainian"),
- ("el", "greek"),
- ("ms", "malay"),
- ("cs", "czech"),
- ("ro", "romanian"),
- ("da", "danish"),
- ("hu", "hungarian"),
- ("ta", "tamil"),
- ("no", "norwegian"),
- ("th", "thai"),
- ("ur", "urdu"),
- ("hr", "croatian"),
- ("bg", "bulgarian"),
- ("lt", "lithuanian"),
- ("la", "latin"),
- ("mi", "maori"),
- ("ml", "malayalam"),
- ("cy", "welsh"),
- ("sk", "slovak"),
- ("te", "telugu"),
- ("fa", "persian"),
- ("lv", "latvian"),
- ("bn", "bengali"),
- ("sr", "serbian"),
- ("az", "azerbaijani"),
- ("sl", "slovenian"),
- ("kn", "kannada"),
- ("et", "estonian"),
- ("mk", "macedonian"),
- ("br", "breton"),
- ("eu", "basque"),
- ("is", "icelandic"),
- ("hy", "armenian"),
- ("ne", "nepali"),
- ("mn", "mongolian"),
- ("bs", "bosnian"),
- ("kk", "kazakh"),
- ("sq", "albanian"),
- ("sw", "swahili"),
- ("gl", "galician"),
- ("mr", "marathi"),
- ("pa", "punjabi"),
- ("si", "sinhala"),
- ("km", "khmer"),
- ("sn", "shona"),
- ("yo", "yoruba"),
- ("so", "somali"),
- ("af", "afrikaans"),
- ("oc", "occitan"),
- ("ka", "georgian"),
- ("be", "belarusian"),
- ("tg", "tajik"),
- ("sd", "sindhi"),
- ("gu", "gujarati"),
- ("am", "amharic"),
- ("yi", "yiddish"),
- ("lo", "lao"),
- ("uz", "uzbek"),
- ("fo", "faroese"),
- ("ht", "haitian creole"),
- ("ps", "pashto"),
- ("tk", "turkmen"),
- ("nn", "nynorsk"),
- ("mt", "maltese"),
- ("sa", "sanskrit"),
- ("lb", "luxembourgish"),
- ("my", "myanmar"),
- ("bo", "tibetan"),
- ("tl", "tagalog"),
- ("mg", "malagasy"),
- ("as", "assamese"),
- ("tt", "tatar"),
- ("haw", "hawaiian"),
- ("ln", "lingala"),
- ("ha", "hausa"),
- ("ba", "bashkir"),
- ("jw", "javanese"),
- ("su", "sundanese"),
-];
-
-/// Returns the token id for the selected language.
-pub fn detect_language(
- model: &mut Model,
- tokenizer: &Tokenizer,
- mel: &Tensor,
- languages: Vec<Language>,
-) -> Result<u32> {
- let (_bsize, _, seq_len) = mel.dims3()?;
- let mel = mel.narrow(
- 2,
- 0,
- usize::min(seq_len, model.config().max_source_positions),
- )?;
- let device = mel.device();
- let mut language_token_ids = LANGUAGES
- .iter()
- .map(|(t, _)| token_id(tokenizer, &format!("<|{t}|>")))
- .collect::<Result<Vec<_>>>()?;
- if !languages.is_empty() {
- language_token_ids = languages
- .iter()
- .map(|l| token_id(tokenizer, &format!("<|{}|>", l.as_lang_code())))
- .collect::<Result<Vec<_>>>()?;
- }
- let sot_token = token_id(tokenizer, SOT_TOKEN)?;
- let audio_features = model.encoder_forward(&mel, true)?;
- let tokens = Tensor::new(&[[sot_token]], device)?;
- let language_token_ids = Tensor::new(language_token_ids.as_slice(), device)?;
- let ys = model.decoder_forward(&tokens, &audio_features, true)?;
- let logits = model.decoder_final_linear(&ys.i(..1)?)?.i(0)?.i(0)?;
- let logits = logits.index_select(&language_token_ids, 0)?;
- let probs = candle_nn::ops::softmax(&logits, D::Minus1)?;
- let probs = probs.to_vec1::<f32>()?;
- let mut probabilities: Vec<(&str, &f32)>;
- probabilities = match languages.is_empty() {
- true => LANGUAGES
- .iter()
- .zip(probs.iter())
- .map(|v| (v.0 .0, v.1))
- .collect::<Vec<_>>(),
- false => languages
- .iter()
- .map(|l| l.as_lang_code())
- .zip(probs.iter())
- .collect::<Vec<_>>(),
- };
-
- probabilities.sort_by(|(_, p1), (_, p2)| p2.total_cmp(p1));
-
- let language = token_id(tokenizer, &format!("<|{}|>", probabilities[0].0))?;
- debug!("detected language: {:?}", probabilities[0].0);
- Ok(language)
-}
diff --git a/screenpipe-audio/src/pyannote/mod.rs b/screenpipe-audio/src/pyannote/mod.rs
deleted file mode 100644
index 0092fb7ca..000000000
--- a/screenpipe-audio/src/pyannote/mod.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-pub mod embedding;
-pub mod identify;
-pub mod models;
-pub mod segment;
-pub mod session;
diff --git a/screenpipe-audio/src/realtime.rs b/screenpipe-audio/src/realtime.rs
deleted file mode 100644
index ca2c7f7e0..000000000
--- a/screenpipe-audio/src/realtime.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-use crate::{deepgram::stream_transcription_deepgram, AudioStream};
-use anyhow::Result;
-use chrono::{DateTime, Utc};
-use screenpipe_core::Language;
-use serde::{Deserialize, Serialize};
-use std::sync::{atomic::AtomicBool, Arc};
-
-pub async fn realtime_stt(
- stream: Arc<AudioStream>,
- languages: Vec<Language>,
- is_running: Arc<AtomicBool>,
- deepgram_api_key: Option<String>,
-) -> Result<()> {
- stream_transcription_deepgram(stream, languages, is_running, deepgram_api_key).await?;
-
- Ok(())
-}
-
-#[derive(Serialize, Deserialize, Clone)]
-#[serde(rename_all = "camelCase")]
-pub struct RealtimeTranscriptionEvent {
- pub timestamp: DateTime<Utc>,
- pub device: String,
- pub transcription: String,
- pub is_final: bool,
- pub is_input: bool,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub speaker: Option<String>,
-}
diff --git a/screenpipe-audio/src/segmentation/mod.rs b/screenpipe-audio/src/segmentation/mod.rs
new file mode 100644
index 000000000..d66cad465
--- /dev/null
+++ b/screenpipe-audio/src/segmentation/mod.rs
@@ -0,0 +1 @@
+pub mod segmentation_manager;
diff --git a/screenpipe-audio/src/segmentation/segmentation_manager.rs b/screenpipe-audio/src/segmentation/segmentation_manager.rs
new file mode 100644
index 000000000..f858845b3
--- /dev/null
+++ b/screenpipe-audio/src/segmentation/segmentation_manager.rs
@@ -0,0 +1,37 @@
+use anyhow::{anyhow, Result};
+use std::{
+ path::PathBuf,
+ sync::{Arc, Mutex as StdMutex},
+};
+
+use crate::speaker::{
+ embedding::EmbeddingExtractor,
+ embedding_manager::EmbeddingManager,
+ models::{get_or_download_model, PyannoteModel},
+};
+
+pub struct SegmentationManager {
+ pub embedding_manager: EmbeddingManager,
+ pub embedding_extractor: Arc<StdMutex<EmbeddingExtractor>>,
+ pub segmentation_model_path: PathBuf,
+}
+
+impl SegmentationManager {
+ pub async fn new() -> Result<Self> {
+ let embedding_model_path = get_or_download_model(PyannoteModel::Embedding).await?;
+ let segmentation_model_path = get_or_download_model(PyannoteModel::Segmentation).await?;
+
+ let embedding_extractor = Arc::new(StdMutex::new(EmbeddingExtractor::new(
+ embedding_model_path
+ .to_str()
+ .ok_or_else(|| anyhow!("Invalid embedding model path"))?,
+ )?));
+
+ let embedding_manager = EmbeddingManager::new(usize::MAX);
+ Ok(SegmentationManager {
+ embedding_manager,
+ embedding_extractor,
+ segmentation_model_path,
+ })
+ }
+}
diff --git a/screenpipe-audio/src/pyannote/embedding.rs b/screenpipe-audio/src/speaker/embedding.rs
similarity index 87%
rename from screenpipe-audio/src/pyannote/embedding.rs
rename to screenpipe-audio/src/speaker/embedding.rs
index 6f16ca245..65d94d158 100644
--- a/screenpipe-audio/src/pyannote/embedding.rs
+++ b/screenpipe-audio/src/speaker/embedding.rs
@@ -1,4 +1,3 @@
-use crate::pyannote::session;
use anyhow::{Context, Result};
use ndarray::Array2;
use ort::Session;
@@ -11,11 +10,13 @@ pub struct EmbeddingExtractor {
impl EmbeddingExtractor {
pub fn new<P: AsRef<Path>>(model_path: P) -> Result<Self> {
- let session = session::create_session(model_path.as_ref())?;
+ let session = super::create_session(&model_path)?;
Ok(Self { session })
}
pub fn compute(&mut self, samples: &[f32]) -> Result<impl Iterator<Item = f32>> {
- let features: Array2<f32> = knf_rs::compute_fbank(samples).map_err(anyhow::Error::msg)?;
+ let features: Array2<f32> = knf_rs::compute_fbank(samples)
+ .map_err(anyhow::Error::msg)
+ .context("compute_fbank failed")?;
let features = features.insert_axis(ndarray::Axis(0)); // Add batch dimension
let inputs = ort::inputs! ["feats" => features.view()]?;
diff --git a/screenpipe-audio/src/pyannote/identify.rs b/screenpipe-audio/src/speaker/embedding_manager.rs
similarity index 100%
rename from screenpipe-audio/src/pyannote/identify.rs
rename to screenpipe-audio/src/speaker/embedding_manager.rs
diff --git a/screenpipe-audio/src/pyannote/session.rs b/screenpipe-audio/src/speaker/mod.rs
similarity index 72%
rename from screenpipe-audio/src/pyannote/session.rs
rename to screenpipe-audio/src/speaker/mod.rs
index ae7fe7c33..3c310dbc5 100644
--- a/screenpipe-audio/src/pyannote/session.rs
+++ b/screenpipe-audio/src/speaker/mod.rs
@@ -1,3 +1,5 @@
+pub mod embedding;
+
use std::path::Path;
use anyhow::Result;
@@ -10,4 +12,9 @@ pub fn create_session<P: AsRef<Path>>(path: P) -> Result<Session> {
.with_inter_threads(1)?
.commit_from_file(path.as_ref())?;
Ok(session)
-}
\ No newline at end of file
+}
+pub mod embedding_manager;
+pub mod models;
+mod prepare_segments;
+pub use prepare_segments::prepare_segments;
+pub mod segment;
diff --git a/screenpipe-audio/src/pyannote/models.rs b/screenpipe-audio/src/speaker/models.rs
similarity index 99%
rename from screenpipe-audio/src/pyannote/models.rs
rename to screenpipe-audio/src/speaker/models.rs
index 42539845f..7a56dd8e4 100644
--- a/screenpipe-audio/src/pyannote/models.rs
+++ b/screenpipe-audio/src/speaker/models.rs
@@ -1,7 +1,6 @@
use anyhow::Result;
-use dirs;
use lazy_static::lazy_static;
-use log::{debug, info};
+use tracing::{debug, info};
use std::path::PathBuf;
use std::sync::Once;
use tokio::sync::Mutex;
diff --git a/screenpipe-audio/src/segments.rs b/screenpipe-audio/src/speaker/prepare_segments.rs
similarity index 70%
rename from screenpipe-audio/src/segments.rs
rename to screenpipe-audio/src/speaker/prepare_segments.rs
index 169638704..32b55dcf7 100644
--- a/screenpipe-audio/src/segments.rs
+++ b/screenpipe-audio/src/speaker/prepare_segments.rs
@@ -1,19 +1,18 @@
-use crate::audio_processing::{average_noise_spectrum, spectral_subtraction};
+use super::segment::get_segments;
use crate::{
- audio_processing::normalize_v2,
- pyannote::{
- embedding::EmbeddingExtractor,
- identify::EmbeddingManager,
- segment::{get_segments, SpeechSegment},
- },
- vad_engine::VadEngine,
+ utils::audio::{average_noise_spectrum, normalize_v2, spectral_subtraction},
+ vad::VadEngine,
};
use anyhow::Result;
-use log::{error, info};
use std::{path::PathBuf, sync::Arc, sync::Mutex as StdMutex};
use tokio::sync::Mutex;
+use tracing::{error, info};
use vad_rs::VadStatus;
+use super::{
+ embedding::EmbeddingExtractor, embedding_manager::EmbeddingManager, segment::SpeechSegment,
+};
+
pub async fn prepare_segments(
audio_data: &[f32],
vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>,
@@ -63,9 +62,11 @@ pub async fn prepare_segments(
audio_frames.len(),
speech_frame_count
);
+
+ let threshold_met = speech_ratio > min_speech_ratio;
+
let (tx, rx) = tokio::sync::mpsc::channel(100);
- let speech_ratio_ok = speech_ratio >= min_speech_ratio;
- if !audio_frames.is_empty() && speech_ratio_ok {
+ if !audio_frames.is_empty() && threshold_met {
let segments = get_segments(
&audio_data,
16000,
@@ -74,13 +75,21 @@ pub async fn prepare_segments(
embedding_manager,
)?;
- for segment in segments.flatten() {
- if let Err(e) = tx.send(segment).await {
- error!("failed to send segment: {:?}", e);
- break;
+ for segment in segments {
+ match segment {
+ Ok(segment) => {
+ if let Err(e) = tx.send(segment).await {
+ error!("failed to send segment: {:?}", e);
+ break;
+ }
+ }
+ Err(e) => {
+ error!("failed to get segment: {:?}", e);
+ return Err(e);
+ }
}
}
}
- Ok((rx, speech_ratio_ok))
+ Ok((rx, threshold_met))
}
diff --git a/screenpipe-audio/src/pyannote/segment.rs b/screenpipe-audio/src/speaker/segment.rs
similarity index 83%
rename from screenpipe-audio/src/pyannote/segment.rs
rename to screenpipe-audio/src/speaker/segment.rs
index 78c72b0f9..54eda21bf 100644
--- a/screenpipe-audio/src/pyannote/segment.rs
+++ b/screenpipe-audio/src/speaker/segment.rs
@@ -1,9 +1,9 @@
-use crate::pyannote::session;
use anyhow::{Context, Result};
use ndarray::{ArrayBase, Axis, IxDyn, ViewRepr};
use std::{cmp::Ordering, path::Path, sync::Arc, sync::Mutex};
+use tracing::error;
-use super::{embedding::EmbeddingExtractor, identify::EmbeddingManager};
+use super::{embedding::EmbeddingExtractor, embedding_manager::EmbeddingManager};
#[derive(Debug, Clone)]
#[repr(C)]
@@ -44,17 +44,36 @@ fn create_speech_segment(
let start_f64 = start * (sample_rate as f64);
let end_f64 = end * (sample_rate as f64);
- let start_idx = start_f64.min((samples.len() - 1) as f64) as usize;
- let end_idx = end_f64.min(samples.len() as f64) as usize;
+ let start_idx = start_f64.min((samples.len() - 1600) as f64) as usize;
+ let mut end_idx = end_f64.min(samples.len() as f64) as usize;
+
+ // TODO: Why is this empty sometimes?
+ let mut samples = padded_samples[start_idx..end_idx].to_vec();
+ // // Ensure the segment has at least 1600 samples
+ let min_length = 1600;
+ let segment_samples = if end_idx - start_idx < min_length {
+ if end_idx + (min_length - (end_idx - start_idx)) <= samples.len() {
+ // Increase the end index if possible
+ end_idx += min_length - (end_idx - start_idx);
+ &padded_samples[start_idx..end_idx]
+ } else if start_idx >= min_length - (end_idx - start_idx) {
+ // Otherwise, pad the samples.
+
+ samples.resize(1600, 0.0);
+
+ samples.as_slice()
+ } else {
+ &padded_samples[start_idx..end_idx]
+ }
+ } else {
+ &padded_samples[start_idx..end_idx]
+ };
- let segment_samples = &padded_samples[start_idx..end_idx];
let embedding = match get_speaker_embedding(embedding_extractor, segment_samples) {
Ok(embedding) => embedding,
Err(e) => {
- return Err(anyhow::anyhow!(
- "Failed to compute speaker embedding: {}",
- e
- ));
+ error!("Failed to compute speaker embedding: {}", e);
+ vec![0.0; 512]
}
};
let speaker = get_speaker_from_embedding(embedding_manager, embedding.clone());
@@ -114,7 +133,7 @@ impl SegmentIterator {
embedding_extractor: Arc<Mutex<EmbeddingExtractor>>,
embedding_manager: EmbeddingManager,
) -> Result<Self> {
- let session = session::create_session(model_path.as_ref())?;
+ let session = super::create_session(model_path.as_ref())?;
let window_size = (sample_rate * 10) as usize;
let padded_samples = {
@@ -181,8 +200,8 @@ impl SegmentIterator {
&mut self.embedding_manager,
) {
Ok(segment) => segment,
- Err(_) => {
- return Ok(None);
+ Err(e) => {
+ return Err(e);
}
};
@@ -212,7 +231,12 @@ impl Iterator for SegmentIterator {
while self.current_position < self.padded_samples.len() - 1 {
let end = (self.current_position + self.window_size).min(self.padded_samples.len());
- let window = self.padded_samples[self.current_position..end].to_vec();
+
+ let window = if end == self.padded_samples.len() {
+ self.padded_samples[self.current_position..].to_vec()
+ } else {
+ self.padded_samples[self.current_position..end].to_vec()
+ };
// Process the window
match self.process_window(&window) {
diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rs
deleted file mode 100644
index f7d87568f..000000000
--- a/screenpipe-audio/src/stt.rs
+++ /dev/null
@@ -1,403 +0,0 @@
-use crate::audio_processing::write_audio_to_file;
-use crate::deepgram::transcribe_with_deepgram;
-use crate::pyannote::models::{get_or_download_model, PyannoteModel};
-use crate::pyannote::segment::SpeechSegment;
-pub use crate::segments::prepare_segments;
-use crate::{
- pyannote::{embedding::EmbeddingExtractor, identify::EmbeddingManager},
- vad_engine::{SileroVad, VadEngine, VadEngineEnum, VadSensitivity, WebRtcVad},
- whisper::{process_with_whisper, WhisperModel},
- AudioDevice, AudioTranscriptionEngine,
-};
-use crate::{resample, DeviceControl};
-use anyhow::{anyhow, Result};
-use candle_transformers::models::whisper as m;
-use dashmap::DashMap;
-use log::{debug, error, info};
-#[cfg(target_os = "macos")]
-use objc::rc::autoreleasepool;
-use screenpipe_core::Language;
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::{
- path::Path,
- sync::Arc,
- sync::Mutex as StdMutex,
- time::{SystemTime, UNIX_EPOCH},
-};
-use tokio::sync::Mutex;
-
-pub fn stt_sync(
- audio: &[f32],
- sample_rate: u32,
- device: &str,
- whisper_model: &mut WhisperModel,
- audio_transcription_engine: Arc<AudioTranscriptionEngine>,
- deepgram_api_key: Option<String>,
- languages: Vec<Language>,
-) -> Result<String> {
- let mut whisper_model = whisper_model.clone();
- let audio = audio.to_vec();
-
- let device = device.to_string();
- let handle = std::thread::spawn(move || {
- let rt = tokio::runtime::Runtime::new().unwrap();
-
- rt.block_on(stt(
- &audio,
- sample_rate,
- &device,
- &mut whisper_model,
- audio_transcription_engine,
- deepgram_api_key,
- languages,
- ))
- });
-
- handle.join().unwrap()
-}
-
-#[allow(clippy::too_many_arguments)]
-pub async fn stt(
- audio: &[f32],
- sample_rate: u32,
- device: &str,
- whisper_model: &mut WhisperModel,
- audio_transcription_engine: Arc<AudioTranscriptionEngine>,
- deepgram_api_key: Option<String>,
- languages: Vec<Language>,
-) -> Result<String> {
- let model = &whisper_model.model;
-
- debug!("Loading mel filters");
- let mel_bytes = match model.config().num_mel_bins {
- 80 => include_bytes!("../models/whisper/melfilters.bytes").as_slice(),
- 128 => include_bytes!("../models/whisper/melfilters128.bytes").as_slice(),
- nmel => anyhow::bail!("unexpected num_mel_bins {nmel}"),
- };
- let mut mel_filters = vec![0f32; mel_bytes.len() / 4];
- <byteorder::LittleEndian as byteorder::ByteOrder>::read_f32_into(mel_bytes, &mut mel_filters);
-
- let transcription: Result<String> = if audio_transcription_engine
- == AudioTranscriptionEngine::Deepgram.into()
- {
- // Deepgram implementation
- let api_key = deepgram_api_key.unwrap_or_default();
-
- match transcribe_with_deepgram(&api_key, audio, device, sample_rate, languages.clone())
- .await
- {
- Ok(transcription) => Ok(transcription),
- Err(e) => {
- error!(
- "device: {}, deepgram transcription failed, falling back to Whisper: {:?}",
- device, e
- );
- // Fallback to Whisper
- process_with_whisper(&mut *whisper_model, audio, &mel_filters, languages.clone())
- }
- }
- } else {
- // Existing Whisper implementation
- process_with_whisper(&mut *whisper_model, audio, &mel_filters, languages)
- };
-
- transcription
-}
-
-#[derive(Debug, Clone)]
-pub struct AudioInput {
- pub data: Arc<Vec<f32>>,
- pub sample_rate: u32,
- pub channels: u16,
- pub device: Arc<AudioDevice>,
-}
-
-#[derive(Debug, Clone)]
-pub struct TranscriptionResult {
- pub path: String,
- pub input: AudioInput,
- pub speaker_embedding: Vec<f32>,
- pub transcription: Option<String>,
- pub timestamp: u64,
- pub error: Option<String>,
- pub start_time: f64,
- pub end_time: f64,
-}
-
-impl TranscriptionResult {
- // TODO --optimize
- pub fn cleanup_overlap(&mut self, previous_transcript: String) -> Option<(String, String)> {
- if let Some(transcription) = &self.transcription {
- let transcription = transcription.to_string();
- if let Some((prev_idx, cur_idx)) =
- longest_common_word_substring(previous_transcript.as_str(), transcription.as_str())
- {
- // strip old transcript from prev_idx word pos
- let new_prev = previous_transcript
- .split_whitespace()
- .collect::<Vec<&str>>()[..prev_idx]
- .join(" ");
- // strip new transcript before cur_idx word pos
- let new_cur =
- transcription.split_whitespace().collect::<Vec<&str>>()[cur_idx..].join(" ");
-
- return Some((new_prev, new_cur));
- }
- }
-
- None
- }
-}
-
-pub async fn create_whisper_channel(
- audio_transcription_engine: Arc<AudioTranscriptionEngine>,
- vad_engine: VadEngineEnum,
- deepgram_api_key: Option<String>,
- output_path: &Path,
- vad_sensitivity: VadSensitivity,
- languages: Vec<Language>,
- audio_devices_control: Option<Arc<DashMap<AudioDevice, DeviceControl>>>,
-) -> Result<(
- crossbeam::channel::Sender<AudioInput>,
- crossbeam::channel::Receiver<TranscriptionResult>,
- Arc<AtomicBool>, // Shutdown flag
-)> {
- let mut whisper_model = WhisperModel::new(&audio_transcription_engine)?;
- let (input_sender, input_receiver): (
- crossbeam::channel::Sender<AudioInput>,
- crossbeam::channel::Receiver<AudioInput>,
- ) = crossbeam::channel::bounded(1000);
- let (output_sender, output_receiver): (
- crossbeam::channel::Sender<TranscriptionResult>,
- crossbeam::channel::Receiver<TranscriptionResult>,
- ) = crossbeam::channel::bounded(1000);
- let mut vad_engine: Box<dyn VadEngine + Send> = match vad_engine {
- VadEngineEnum::WebRtc => Box::new(WebRtcVad::new()),
- VadEngineEnum::Silero => Box::new(SileroVad::new().await?),
- };
- vad_engine.set_sensitivity(vad_sensitivity);
- let vad_engine = Arc::new(Mutex::new(vad_engine));
- let shutdown_flag = Arc::new(AtomicBool::new(false));
- let shutdown_flag_clone = shutdown_flag.clone();
- let output_path = output_path.to_path_buf();
-
- let embedding_model_path = get_or_download_model(PyannoteModel::Embedding).await?;
- let segmentation_model_path = get_or_download_model(PyannoteModel::Segmentation).await?;
-
- let embedding_extractor = Arc::new(StdMutex::new(EmbeddingExtractor::new(
- embedding_model_path
- .to_str()
- .ok_or_else(|| anyhow!("Invalid embedding model path"))?,
- )?));
-
- let embedding_manager = EmbeddingManager::new(usize::MAX);
-
- tokio::spawn(async move {
- loop {
- if shutdown_flag_clone.load(Ordering::Relaxed) {
- info!("Whisper channel shutting down");
- break;
- }
- debug!("Waiting for input from input_receiver");
-
- crossbeam::select! {
- recv(input_receiver) -> input_result => {
- match input_result {
- Ok(mut audio) => {
- // Check if device should be recording
- if let Some(control) = audio_devices_control.as_ref().unwrap().get(&audio.device) {
- if !control.is_running {
- debug!("Skipping audio processing for stopped device: {}", audio.device);
- continue;
- }
- } else {
- debug!("Device not found in control list: {}", audio.device);
- continue;
- }
-
- debug!("Received input from input_receiver");
- let timestamp = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .expect("Time went backwards")
- .as_secs();
-
- let audio_data = if audio.sample_rate != m::SAMPLE_RATE as u32 {
- match resample(
- audio.data.as_ref(),
- audio.sample_rate,
- m::SAMPLE_RATE as u32,
- ) {
- Ok(data) => data,
- Err(e) => {
- error!("Error resampling audio: {:?}", e);
- continue;
- }
- }
- } else {
- audio.data.as_ref().to_vec()
- };
-
- audio.data = Arc::new(audio_data.clone());
- audio.sample_rate = m::SAMPLE_RATE as u32;
-
- let (mut segments, speech_ratio_ok) = match prepare_segments(&audio_data, vad_engine.clone(), &segmentation_model_path, embedding_manager.clone(), embedding_extractor.clone(), &audio.device.to_string()).await {
- Ok((segments, speech_ratio_ok)) => (segments, speech_ratio_ok),
- Err(e) => {
- error!("Error preparing segments: {:?}", e);
- continue;
- }
- };
-
- if !speech_ratio_ok {
- continue;
- }
-
- let path = match write_audio_to_file(
- &audio.data.to_vec(),
- audio.sample_rate,
- &output_path,
- &audio.device.to_string(),
- false,
- ) {
- Ok(file_path) => file_path,
- Err(e) => {
- error!("Error writing audio to file: {:?}", e);
- "".to_string()
- }
- };
-
- while let Some(segment) = segments.recv().await {
- let path = path.clone();
- let transcription_result = if cfg!(target_os = "macos") {
- #[cfg(target_os = "macos")]
- {
- let timestamp = timestamp + segment.start.round() as u64;
- autoreleasepool(|| {
- run_stt(segment, audio.device.clone(), &mut whisper_model, audio_transcription_engine.clone(), deepgram_api_key.clone(), languages.clone(), path, timestamp)
- })
- }
- #[cfg(not(target_os = "macos"))]
- {
- unreachable!("This code should not be reached on non-macOS platforms")
- }
- } else {
- run_stt(segment, audio.device.clone(), &mut whisper_model, audio_transcription_engine.clone(), deepgram_api_key.clone(), languages.clone(), path, timestamp)
- };
-
- if output_sender.send(transcription_result).is_err() {
- break;
- }
- }
- },
- Err(e) => {
- error!("Error receiving input: {:?}", e);
- // Depending on the error type, you might want to break the loop or continue
- // For now, we'll continue to the next iteration
- break;
- }
- }
- },
- }
- }
- // Cleanup code here (if needed)
- });
-
- Ok((input_sender, output_receiver, shutdown_flag))
-}
-
-#[allow(clippy::too_many_arguments)]
-pub fn run_stt(
- segment: SpeechSegment,
- device: Arc<AudioDevice>,
- whisper_model: &mut WhisperModel,
- audio_transcription_engine: Arc<AudioTranscriptionEngine>,
- deepgram_api_key: Option<String>,
- languages: Vec<Language>,
- path: String,
- timestamp: u64,
-) -> TranscriptionResult {
- let audio = segment.samples.clone();
- let sample_rate = segment.sample_rate;
- match stt_sync(
- &audio,
- sample_rate,
- &device.to_string(),
- whisper_model,
- audio_transcription_engine.clone(),
- deepgram_api_key.clone(),
- languages.clone(),
- ) {
- Ok(transcription) => TranscriptionResult {
- input: AudioInput {
- data: Arc::new(audio),
- sample_rate,
- channels: 1,
- device: device.clone(),
- },
- transcription: Some(transcription),
- path,
- timestamp,
- error: None,
- speaker_embedding: segment.embedding.clone(),
- start_time: segment.start,
- end_time: segment.end,
- },
- Err(e) => {
- error!("STT error for input {}: {:?}", device, e);
- TranscriptionResult {
- input: AudioInput {
- data: Arc::new(segment.samples),
- sample_rate: segment.sample_rate,
- channels: 1,
- device: device.clone(),
- },
- transcription: None,
- path,
- timestamp,
- error: Some(e.to_string()),
- speaker_embedding: Vec::new(),
- start_time: segment.start,
- end_time: segment.end,
- }
- }
- }
-}
-
-pub fn longest_common_word_substring(s1: &str, s2: &str) -> Option<(usize, usize)> {
- let s1 = s1.to_lowercase();
- let s2 = s2.to_lowercase();
-
- let s1 = s1.replace(|c| char::is_ascii_punctuation(&c), "");
- let s2 = s2.replace(|c| char::is_ascii_punctuation(&c), "");
-
- let s1_words: Vec<&str> = s1.split_whitespace().collect();
- let s2_words: Vec<&str> = s2.split_whitespace().collect();
-
- let s1_len = s1_words.len();
- let s2_len = s2_words.len();
-
- // Table to store lengths of longest common suffixes of word substrings
- let mut dp = vec![vec![0; s2_len + 1]; s1_len + 1];
-
- let mut max_len = 0;
- let mut max_index_s1 = None; // Store the starting word index of the longest substring in s1
- let mut max_index_s2 = None; // Store the starting word index of the longest substring in s2
-
- for i in 1..=s1_len {
- for j in 1..=s2_len {
- if s1_words[i - 1] == s2_words[j - 1] {
- dp[i][j] = dp[i - 1][j - 1] + 1;
- if dp[i][j] > max_len {
- max_len = dp[i][j];
- max_index_s1 = Some(i - max_len); // The start index of the match in s1
- max_index_s2 = Some(j - max_len); // The start index of the match in s2
- }
- }
- }
- }
-
- match (max_index_s1, max_index_s2) {
- (Some(idx1), Some(idx2)) => Some((idx1, idx2)),
- _ => None,
- }
-}
diff --git a/screenpipe-audio/src/tokenizer.rs b/screenpipe-audio/src/tokenizer.rs
deleted file mode 100644
index e69de29bb..000000000
diff --git a/screenpipe-audio/src/deepgram/process_chunk.rs b/screenpipe-audio/src/transcription/deepgram/batch.rs
similarity index 75%
rename from screenpipe-audio/src/deepgram/process_chunk.rs
rename to screenpipe-audio/src/transcription/deepgram/batch.rs
index a0350008f..e1c4a9c74 100644
--- a/screenpipe-audio/src/deepgram/process_chunk.rs
+++ b/screenpipe-audio/src/transcription/deepgram/batch.rs
@@ -1,12 +1,12 @@
use anyhow::Result;
use hound::{WavSpec, WavWriter};
-use log::{debug, error, info};
-use reqwest::Client;
+use reqwest::{Client, Response};
use screenpipe_core::Language;
use serde_json::Value;
use std::io::Cursor;
+use tracing::{debug, error, info};
-use crate::deepgram::{CUSTOM_DEEPGRAM_API_TOKEN, DEEPGRAM_API_URL};
+use crate::transcription::deepgram::{CUSTOM_DEEPGRAM_API_TOKEN, DEEPGRAM_API_URL};
pub async fn transcribe_with_deepgram(
api_key: &str,
@@ -16,11 +16,33 @@ pub async fn transcribe_with_deepgram(
languages: Vec<Language>,
) -> Result<String> {
debug!("starting deepgram transcription");
- let client = Client::new();
// Use token from env var
let custom_api_key = CUSTOM_DEEPGRAM_API_TOKEN.as_str();
+ let is_custom_endpoint = !custom_api_key.is_empty();
+
+ // Create a WAV file in memory
+ let wav_data = create_wav_file(audio_data, sample_rate)?;
+
+ let query_params = create_query_params(languages);
+
+ // rationale: custom api key = custom AI proxy to use deepgram
+ // no custom api key = use deepgram api key for real deepgram endpoint
+ let api_key_to_use = if custom_api_key.is_empty() {
+ api_key
+ } else {
+ custom_api_key
+ };
+
+ debug!("deepgram api key: {}", api_key_to_use);
+
+ let response =
+ get_deepgram_response(api_key_to_use, is_custom_endpoint, wav_data, query_params).await;
+
+ handle_deepgram_response(response, device).await
+}
+fn create_wav_file(audio_data: &[f32], sample_rate: u32) -> Result<Vec<u8>> {
// Create a WAV file in memory
let mut cursor = Cursor::new(Vec::new());
{
@@ -41,8 +63,10 @@ pub async fn transcribe_with_deepgram(
}
// Get the WAV data from the cursor
- let wav_data = cursor.into_inner();
+ Ok(cursor.into_inner())
+}
+fn create_query_params(languages: Vec<Language>) -> String {
let mut query_params = String::from("model=nova-2&smart_format=true&sample_rate=16000");
if !languages.is_empty() {
@@ -58,33 +82,39 @@ pub async fn transcribe_with_deepgram(
.concat();
}
- // rationale: custom api key = custom AI proxy to use deepgram
- // no custom api key = use deepgram api key for real deepgram endpoint
- let api_key_to_use = if custom_api_key.is_empty() {
- api_key
- } else {
- custom_api_key
- };
- let is_custom_endpoint = !custom_api_key.is_empty();
+ query_params
+}
- debug!("deepgram api key: {}", api_key_to_use);
+async fn get_deepgram_response(
+ api_key: &str,
+ is_custom_endpoint: bool,
+ wav_data: Vec<u8>,
+ params: String,
+) -> Result<Response, reqwest::Error> {
+ let client = Client::new();
- let response = client
- .post(format!("{}?{}", *DEEPGRAM_API_URL, query_params))
+ client
+ .post(format!("{}?{}", *DEEPGRAM_API_URL, params))
.header("Content-Type", "audio/wav")
// Use Bearer format when using custom endpoint/proxy
.header(
"Authorization",
if is_custom_endpoint {
- format!("Bearer {}", api_key_to_use)
+ format!("Bearer {}", api_key)
} else {
- format!("Token {}", api_key_to_use)
+ format!("Token {}", api_key)
},
)
.body(wav_data)
- .send();
+ .send()
+ .await
+}
- match response.await {
+async fn handle_deepgram_response(
+ response: Result<Response, reqwest::Error>,
+ device: &str,
+) -> Result<String> {
+ match response {
Ok(resp) => {
debug!("received response from deepgram api");
match resp.json::<Value>().await {
@@ -103,10 +133,7 @@ pub async fn transcribe_with_deepgram(
.unwrap_or("");
if transcription.is_empty() {
- info!(
- "device: {}, transcription is empty. full response: {:?}",
- device, result
- );
+ info!("device: {}, transcription is empty.", device);
} else {
info!(
"device: {}, transcription successful. length: {} characters",
diff --git a/screenpipe-audio/src/deepgram/mod.rs b/screenpipe-audio/src/transcription/deepgram/mod.rs
similarity index 50%
rename from screenpipe-audio/src/deepgram/mod.rs
rename to screenpipe-audio/src/transcription/deepgram/mod.rs
index c81843cd4..4042f5cf0 100644
--- a/screenpipe-audio/src/deepgram/mod.rs
+++ b/screenpipe-audio/src/transcription/deepgram/mod.rs
@@ -1,18 +1,14 @@
-mod process_chunk;
-mod realtime;
+pub mod batch;
+pub mod streaming;
+
use lazy_static::lazy_static;
-#[doc(hidden)]
-pub use realtime::start_deepgram_stream;
-pub use realtime::stream_transcription_deepgram;
use std::env;
lazy_static! {
pub(crate) static ref DEEPGRAM_API_URL: String = env::var("DEEPGRAM_API_URL")
.unwrap_or_else(|_| "https://api.deepgram.com/v1/listen".to_string());
- pub(crate) static ref DEEPGRAM_WEBSOCKET_URL: String = env::var("DEEPGRAM_WEBSOCKET_URL")
- .unwrap_or_else(|_| "wss://api.deepgram.com/v1/listen".to_string());
+ pub(crate) static ref DEEPGRAM_WEBSOCKET_URL: String =
+ env::var("DEEPGRAM_WEBSOCKET_URL").unwrap_or_else(|_| String::new());
pub(crate) static ref CUSTOM_DEEPGRAM_API_TOKEN: String =
env::var("CUSTOM_DEEPGRAM_API_TOKEN").unwrap_or_else(|_| String::new());
}
-
-pub use process_chunk::transcribe_with_deepgram;
diff --git a/screenpipe-audio/src/deepgram/realtime.rs b/screenpipe-audio/src/transcription/deepgram/streaming.rs
similarity index 67%
rename from screenpipe-audio/src/deepgram/realtime.rs
rename to screenpipe-audio/src/transcription/deepgram/streaming.rs
index 77074e58a..b5404c2a2 100644
--- a/screenpipe-audio/src/deepgram/realtime.rs
+++ b/screenpipe-audio/src/transcription/deepgram/streaming.rs
@@ -1,12 +1,9 @@
-use crate::{
- deepgram::CUSTOM_DEEPGRAM_API_TOKEN, deepgram::DEEPGRAM_WEBSOCKET_URL,
- realtime::RealtimeTranscriptionEvent, AudioStream,
-};
-use crate::{AudioDevice, DeviceType};
use anyhow::Result;
use bytes::BufMut;
use bytes::Bytes;
use bytes::BytesMut;
+use chrono::DateTime;
+use chrono::Utc;
use crossbeam::channel::RecvError;
use deepgram::common::options::Encoding;
use deepgram::common::stream_response::StreamResponse;
@@ -14,16 +11,43 @@ use futures::channel::mpsc::{self, Receiver as FuturesReceiver};
use futures::{SinkExt, TryStreamExt};
use screenpipe_core::Language;
use screenpipe_events::send_event;
+use serde::{Deserialize, Serialize};
+use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{atomic::AtomicBool, Arc};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::broadcast::Receiver;
use tokio::sync::oneshot;
+use tracing::debug;
use tracing::info;
-use std::sync::atomic::{AtomicI64, Ordering};
// Add this near other static/global variables
static LAST_DISPLAY_AUDIO_ACTIVITY: AtomicI64 = AtomicI64::new(0);
+use crate::core::device::AudioDevice;
+use crate::core::device::DeviceType;
+use crate::core::stream::AudioStream;
+use crate::transcription::deepgram::CUSTOM_DEEPGRAM_API_TOKEN;
+use crate::transcription::deepgram::DEEPGRAM_WEBSOCKET_URL;
+
+#[derive(Serialize, Deserialize, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct RealtimeTranscriptionEvent {
+ pub timestamp: DateTime<Utc>,
+ pub device: String,
+ pub transcription: String,
+ pub is_final: bool,
+ pub is_input: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub speaker: Option<String>,
+}
+
+/// Starts a Deepgram transcription stream for the given audio stream
+///
+/// # Arguments
+/// * `stream` - The audio stream to transcribe
+/// * `languages` - List of languages to transcribe (currently unused)
+/// * `is_running` - Atomic boolean to control the stream lifecycle
+/// * `deepgram_api_key` - Optional custom API key for Deepgram
pub async fn stream_transcription_deepgram(
stream: Arc<AudioStream>,
_languages: Vec<Language>, // TODO impl language
@@ -42,6 +66,7 @@ pub async fn stream_transcription_deepgram(
Ok(())
}
+/// Initializes and manages a Deepgram streaming session
pub async fn start_deepgram_stream(
stream: Receiver<Vec<f32>>,
device: Arc<AudioDevice>,
@@ -49,24 +74,20 @@ pub async fn start_deepgram_stream(
is_running: Arc<AtomicBool>,
deepgram_api_key: Option<String>,
) -> Result<()> {
- let api_key = deepgram_api_key.unwrap_or(CUSTOM_DEEPGRAM_API_TOKEN.to_string());
+ let api_key = deepgram_api_key.unwrap_or_else(|| CUSTOM_DEEPGRAM_API_TOKEN.to_string());
if api_key.is_empty() {
return Err(anyhow::anyhow!("Deepgram API key not found"));
}
- // create shutdown rx from is_running
let (shutdown_tx, mut shutdown_rx) = oneshot::channel();
+ // Spawn shutdown monitor
tokio::spawn(async move {
- loop {
- let running = is_running.load(std::sync::atomic::Ordering::SeqCst);
- if !running {
- shutdown_tx.send(()).unwrap();
- break;
- }
+ while is_running.load(std::sync::atomic::Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(100)).await;
}
+ let _ = shutdown_tx.send(()); // Ignore send errors if receiver is dropped
});
info!("Starting deepgram stream for device: {}", device);
@@ -94,26 +115,29 @@ pub async fn start_deepgram_stream(
.encoding(Encoding::Linear16);
let mut handle = req.clone().handle().await?;
- let mut results = req.stream(get_stream(stream, device.device_type.clone())).await?;
+ let mut results = req
+ .stream(get_stream(stream, device.device_type.clone()))
+ .await?;
let device_clone = device.clone();
loop {
tokio::select! {
- _ = &mut shutdown_rx => {
+ Ok(()) = &mut shutdown_rx => {
info!("Shutting down deepgram stream for device: {}", device);
break;
}
result = results.try_next() => {
- if let Ok(Some(result)) = result {
- handle_transcription(
- result,
- device_clone.clone(),
- ).await;
+ match result {
+ Ok(Some(result)) => {
+ handle_transcription(result, device_clone.clone()).await;
+ }
+ Ok(None) => break, // Stream ended
+ Err(e) => {
+ info!("Error in deepgram stream: {}", e);
+ break;
+ }
}
}
- _ = tokio::time::sleep(Duration::from_millis(100)) => {
- continue;
- }
}
}
@@ -121,7 +145,10 @@ pub async fn start_deepgram_stream(
Ok(())
}
-fn get_stream(mut stream: Receiver<Vec<f32>>, device_type: DeviceType) -> FuturesReceiver<Result<Bytes, RecvError>> {
+fn get_stream(
+ mut stream: Receiver<Vec<f32>>,
+ device_type: DeviceType,
+) -> FuturesReceiver<Result<Bytes, RecvError>> {
let (mut tx, rx) = mpsc::channel(1);
tokio::spawn(async move {
@@ -129,21 +156,22 @@ fn get_stream(mut stream: Receiver<Vec<f32>>, device_type: DeviceType) -> Future
if device_type == DeviceType::Output {
let sum_squares: f32 = data.iter().map(|&x| x * x).sum();
let rms = (sum_squares / data.len() as f32).sqrt();
-
+
if rms > 0.01 {
LAST_DISPLAY_AUDIO_ACTIVITY.store(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as i64,
- Ordering::SeqCst
+ Ordering::SeqCst,
);
}
} else if SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as i64
- - LAST_DISPLAY_AUDIO_ACTIVITY.load(Ordering::SeqCst) < 100
+ - LAST_DISPLAY_AUDIO_ACTIVITY.load(Ordering::SeqCst)
+ < 100
{
continue;
}
@@ -153,7 +181,7 @@ fn get_stream(mut stream: Receiver<Vec<f32>>, device_type: DeviceType) -> Future
bytes.put_i16_le((sample * i16::MAX as f32) as i16);
}
if tx.send(Ok(bytes.freeze())).await.is_err() {
- tx.close_channel();
+ break; // Stop if receiver is dropped
}
}
});
@@ -166,11 +194,17 @@ async fn handle_transcription(result: StreamResponse, device: Arc<AudioDevice>)
channel, is_final, ..
} = result
{
+ debug!(
+ "handling realtime transcription for device: {}",
+ device.name
+ );
let res = channel.alternatives.first().unwrap();
let text = res.transcript.clone();
let is_input = device.device_type == DeviceType::Input;
-
- let speaker = res.words.first()
+
+ let speaker = res
+ .words
+ .first()
.and_then(|w| w.speaker)
.map(|s| s.to_string());
diff --git a/screenpipe-audio/src/transcription/handle_new_transcript.rs b/screenpipe-audio/src/transcription/handle_new_transcript.rs
new file mode 100644
index 000000000..07d27dd69
--- /dev/null
+++ b/screenpipe-audio/src/transcription/handle_new_transcript.rs
@@ -0,0 +1,68 @@
+use std::sync::Arc;
+
+use crate::{core::engine::AudioTranscriptionEngine, transcription::process_transcription_result};
+use screenpipe_db::DatabaseManager;
+use tracing::{error, info};
+
+use super::TranscriptionResult;
+
+pub async fn handle_new_transcript(
+ db: Arc<DatabaseManager>,
+ transcription_receiver: Arc<crossbeam::channel::Receiver<TranscriptionResult>>,
+ transcription_engine: Arc<AudioTranscriptionEngine>,
+) {
+ let mut previous_transcript = "".to_string();
+ let mut previous_transcript_id: Option<i64> = None;
+ while let Ok(mut transcription) = transcription_receiver.recv() {
+ if transcription
+ .transcription
+ .clone()
+ .is_some_and(|t| t.is_empty())
+ {
+ continue;
+ }
+
+ info!(
+ "device {} received transcription {:?}",
+ transcription.input.device, transcription.transcription
+ );
+
+ // Insert the new transcript after fetching
+ let mut current_transcript: Option<String> = transcription.transcription.clone();
+ let mut processed_previous: Option<String> = None;
+ if let Some((previous, current)) =
+ transcription.cleanup_overlap(previous_transcript.clone())
+ {
+ if !previous.is_empty() && !current.is_empty() {
+ if previous != previous_transcript {
+ processed_previous = Some(previous);
+ }
+ if current_transcript.is_some()
+ && current != current_transcript.clone().unwrap_or_default()
+ {
+ current_transcript = Some(current);
+ }
+ }
+ }
+
+ transcription.transcription = current_transcript.clone();
+ if current_transcript.is_some() {
+ previous_transcript = current_transcript.unwrap();
+ } else {
+ continue;
+ }
+ // Process the transcription result
+ match process_transcription_result(
+ &db,
+ transcription,
+ transcription_engine.clone(),
+ processed_previous,
+ previous_transcript_id,
+ )
+ .await
+ {
+ Err(e) => error!("Error processing audio result: {}", e),
+ Ok(id) => previous_transcript_id = id,
+ }
+ }
+}
diff --git a/screenpipe-audio/src/transcription/mod.rs b/screenpipe-audio/src/transcription/mod.rs
new file mode 100644
index 000000000..c531612eb
--- /dev/null
+++ b/screenpipe-audio/src/transcription/mod.rs
@@ -0,0 +1,24 @@
+use std::sync::Arc;
+
+use crate::core::device::AudioDevice;
+
+pub mod deepgram;
+pub mod stt;
+pub mod whisper;
+
+#[derive(Debug, Clone)]
+pub struct AudioInput {
+ pub data: Arc<Vec<f32>>,
+ pub sample_rate: u32,
+ pub channels: u16,
+ pub device: Arc<AudioDevice>,
+}
+
+mod text_utils;
+
+mod transcription_result;
+
+pub use transcription_result::process_transcription_result;
+pub use transcription_result::TranscriptionResult;
+mod handle_new_transcript;
+pub use handle_new_transcript::handle_new_transcript;
diff --git a/screenpipe-audio/src/transcription/stt.rs b/screenpipe-audio/src/transcription/stt.rs
new file mode 100644
index 000000000..253566d1f
--- /dev/null
+++ b/screenpipe-audio/src/transcription/stt.rs
@@ -0,0 +1,252 @@
+use crate::core::device::AudioDevice;
+use crate::core::engine::AudioTranscriptionEngine;
+use crate::speaker::embedding::EmbeddingExtractor;
+use crate::speaker::embedding_manager::EmbeddingManager;
+use crate::speaker::prepare_segments;
+use crate::speaker::segment::SpeechSegment;
+use crate::transcription::deepgram::batch::transcribe_with_deepgram;
+use crate::transcription::whisper::batch::process_with_whisper;
+use crate::utils::audio::resample;
+use crate::utils::ffmpeg::{get_new_file_path, write_audio_to_file};
+use crate::vad::VadEngine;
+use anyhow::Result;
+#[cfg(target_os = "macos")]
+use objc::rc::autoreleasepool;
+use screenpipe_core::Language;
+use std::path::PathBuf;
+use std::{
+ sync::Arc,
+ sync::Mutex as StdMutex,
+ time::{SystemTime, UNIX_EPOCH},
+};
+use tokio::sync::Mutex;
+use tracing::error;
+use whisper_rs::WhisperContext;
+
+use crate::{AudioInput, TranscriptionResult};
+
+pub const SAMPLE_RATE: u32 = 16000;
+
+#[allow(clippy::too_many_arguments)]
+pub async fn stt_sync(
+ audio: &[f32],
+ sample_rate: u32,
+ device: &str,
+ audio_transcription_engine: Arc<AudioTranscriptionEngine>,
+ deepgram_api_key: Option<String>,
+ languages: Vec<Language>,
+ whisper_context: Arc<WhisperContext>,
+) -> Result<String> {
+ let audio = audio.to_vec();
+
+ let device = device.to_string();
+
+ stt(
+ &audio,
+ sample_rate,
+ &device,
+ audio_transcription_engine,
+ deepgram_api_key,
+ languages,
+ whisper_context,
+ )
+ .await
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn stt(
+ audio: &[f32],
+ sample_rate: u32,
+ device: &str,
+ audio_transcription_engine: Arc<AudioTranscriptionEngine>,
+ deepgram_api_key: Option<String>,
+ languages: Vec<Language>,
+ whisper_context: Arc<WhisperContext>,
+) -> Result<String> {
+ let transcription: Result<String> =
+ if audio_transcription_engine == AudioTranscriptionEngine::Deepgram.into() {
+ // Deepgram implementation
+ let api_key = deepgram_api_key.unwrap_or_default();
+
+ match transcribe_with_deepgram(&api_key, audio, device, sample_rate, languages.clone())
+ .await
+ {
+ Ok(transcription) => Ok(transcription),
+ Err(e) => {
+ error!(
+ "device: {}, deepgram transcription failed, falling back to Whisper: {:?}",
+ device, e
+ );
+ // Fallback to Whisper
+ process_with_whisper(audio, languages.clone(), whisper_context).await
+ }
+ }
+ } else {
+ // Existing Whisper implementation
+ process_with_whisper(audio, languages, whisper_context).await
+ };
+
+ transcription
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn process_audio_input(
+ audio: AudioInput,
+ vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>,
+ segmentation_model_path: PathBuf,
+ embedding_manager: EmbeddingManager,
+ embedding_extractor: Arc<StdMutex<EmbeddingExtractor>>,
+ output_path: &PathBuf,
+ audio_transcription_engine: Arc<AudioTranscriptionEngine>,
+ deepgram_api_key: Option<String>,
+ languages: Vec<Language>,
+ output_sender: &crossbeam::channel::Sender<TranscriptionResult>,
+ whisper_context: Arc<WhisperContext>,
+) -> Result<()> {
+ let timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .expect("Time went backwards")
+ .as_secs();
+
+ let audio_data = if audio.sample_rate != SAMPLE_RATE {
+ resample(audio.data.as_ref(), audio.sample_rate, SAMPLE_RATE)?
+ } else {
+ audio.data.as_ref().to_vec()
+ };
+
+ let audio = AudioInput {
+ data: Arc::new(audio_data.clone()),
+ sample_rate: SAMPLE_RATE,
+ ..audio
+ };
+
+ let (mut segments, speech_ratio_ok) = prepare_segments(
+ &audio_data,
+ vad_engine,
+ &segmentation_model_path,
+ embedding_manager,
+ embedding_extractor,
+ &audio.device.to_string(),
+ )
+ .await?;
+
+ if !speech_ratio_ok {
+ return Ok(());
+ }
+
+ let new_file_path = get_new_file_path(&audio.device.to_string(), output_path);
+
+ if let Err(e) = write_audio_to_file(
+ &audio.data.to_vec(),
+ audio.sample_rate,
+ &PathBuf::from(&new_file_path),
+ false,
+ ) {
+ error!("Error writing audio to file: {:?}", e);
+ }
+
+ while let Some(segment) = segments.recv().await {
+ let path = new_file_path.clone();
+ let transcription_result = if cfg!(target_os = "macos") {
+ #[cfg(target_os = "macos")]
+ {
+ let timestamp = timestamp + segment.start.round() as u64;
+ autoreleasepool(|| {
+ run_stt(
+ segment,
+ audio.device.clone(),
+ audio_transcription_engine.clone(),
+ deepgram_api_key.clone(),
+ languages.clone(),
+ path,
+ timestamp,
+ whisper_context.clone(),
+ )
+ })
+ .await?
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ unreachable!("This code should not be reached on non-macOS platforms")
+ }
+ } else {
+ run_stt(
+ segment,
+ audio.device.clone(),
+ audio_transcription_engine.clone(),
+ deepgram_api_key.clone(),
+ languages.clone(),
+ path,
+ timestamp,
+ whisper_context.clone(),
+ )
+ .await?
+ };
+
+ if output_sender.send(transcription_result).is_err() {
+ break;
+ }
+ }
+
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn run_stt(
+ segment: SpeechSegment,
+ device: Arc<AudioDevice>,
+ audio_transcription_engine: Arc<AudioTranscriptionEngine>,
+ deepgram_api_key: Option<String>,
+ languages: Vec<Language>,
+ path: String,
+ timestamp: u64,
+ whisper_context: Arc<WhisperContext>,
+) -> Result<TranscriptionResult> {
+ let audio = segment.samples.clone();
+ let sample_rate = segment.sample_rate;
+ match stt_sync(
+ &audio,
+ sample_rate,
+ &device.to_string(),
+ audio_transcription_engine.clone(),
+ deepgram_api_key.clone(),
+ languages.clone(),
+ whisper_context,
+ )
+ .await
+ {
+ Ok(transcription) => Ok(TranscriptionResult {
+ input: AudioInput {
+ data: Arc::new(audio),
+ sample_rate,
+ channels: 1,
+ device: device.clone(),
+ },
+ transcription: Some(transcription),
+ path,
+ timestamp,
+ error: None,
+ speaker_embedding: segment.embedding.clone(),
+ start_time: segment.start,
+ end_time: segment.end,
+ }),
+ Err(e) => {
+ error!("STT error for input {}: {:?}", device, e);
+ Ok(TranscriptionResult {
+ input: AudioInput {
+ data: Arc::new(segment.samples),
+ sample_rate: segment.sample_rate,
+ channels: 1,
+ device: device.clone(),
+ },
+ transcription: None,
+ path,
+ timestamp,
+ error: Some(e.to_string()),
+ speaker_embedding: Vec::new(),
+ start_time: segment.start,
+ end_time: segment.end,
+ })
+ }
+ }
+}
diff --git a/screenpipe-audio/src/transcription/text_utils.rs b/screenpipe-audio/src/transcription/text_utils.rs
new file mode 100644
index 000000000..e7cebf826
--- /dev/null
+++ b/screenpipe-audio/src/transcription/text_utils.rs
@@ -0,0 +1,38 @@
+pub fn longest_common_word_substring(s1: &str, s2: &str) -> Option<(usize, usize)> {
+ let s1 = s1.to_lowercase();
+ let s2 = s2.to_lowercase();
+
+ let s1 = s1.replace(|c| char::is_ascii_punctuation(&c), "");
+ let s2 = s2.replace(|c| char::is_ascii_punctuation(&c), "");
+
+ let s1_words: Vec<&str> = s1.split_whitespace().collect();
+ let s2_words: Vec<&str> = s2.split_whitespace().collect();
+
+ let s1_len = s1_words.len();
+ let s2_len = s2_words.len();
+
+ // Table to store lengths of longest common suffixes of word substrings
+ let mut dp = vec![vec![0; s2_len + 1]; s1_len + 1];
+
+ let mut max_len = 0;
+ let mut max_index_s1 = None; // Store the starting word index of the longest substring in s1
+ let mut max_index_s2 = None; // Store the starting word index of the longest substring in s2
+
+ for i in 1..=s1_len {
+ for j in 1..=s2_len {
+ if s1_words[i - 1] == s2_words[j - 1] {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ if dp[i][j] > max_len {
+ max_len = dp[i][j];
+ max_index_s1 = Some(i - max_len); // The start index of the match in s1
+ max_index_s2 = Some(j - max_len); // The start index of the match in s2
+ }
+ }
+ }
+ }
+
+ match (max_index_s1, max_index_s2) {
+ (Some(idx1), Some(idx2)) => Some((idx1, idx2)),
+ _ => None,
+ }
+}
diff --git a/screenpipe-audio/src/transcription/transcription_result.rs b/screenpipe-audio/src/transcription/transcription_result.rs
new file mode 100644
index 000000000..cb438ffab
--- /dev/null
+++ b/screenpipe-audio/src/transcription/transcription_result.rs
@@ -0,0 +1,149 @@
+use std::sync::Arc;
+
+use screenpipe_db::{DatabaseManager, Speaker};
+use tracing::{debug, error, info};
+
+use crate::core::engine::AudioTranscriptionEngine;
+
+use super::{text_utils::longest_common_word_substring, AudioInput};
+
+#[derive(Debug, Clone)]
+pub struct TranscriptionResult {
+ pub path: String,
+ pub input: AudioInput,
+ pub speaker_embedding: Vec<f32>,
+ pub transcription: Option<String>,
+ pub timestamp: u64,
+ pub error: Option<String>,
+ pub start_time: f64,
+ pub end_time: f64,
+}
+
+impl TranscriptionResult {
+ // TODO --optimize
+ pub fn cleanup_overlap(&mut self, previous_transcript: String) -> Option<(String, String)> {
+ if let Some(transcription) = &self.transcription {
+ let transcription = transcription.to_string();
+ if let Some((prev_idx, cur_idx)) =
+ longest_common_word_substring(previous_transcript.as_str(), transcription.as_str())
+ {
+ // strip old transcript from prev_idx word pos
+ let new_prev = previous_transcript
+ .split_whitespace()
+ .collect::<Vec<&str>>()[..prev_idx]
+ .join(" ");
+ // strip new transcript before cur_idx word pos
+ let new_cur =
+ transcription.split_whitespace().collect::<Vec<&str>>()[cur_idx..].join(" ");
+
+ return Some((new_prev, new_cur));
+ }
+ }
+
+ None
+ }
+}
+
+pub async fn process_transcription_result(
+ db: &DatabaseManager,
+ result: TranscriptionResult,
+ audio_transcription_engine: Arc<AudioTranscriptionEngine>,
+ previous_transcript: Option<String>,
+ previous_transcript_id: Option<i64>,
+) -> Result<Option<i64>, anyhow::Error> {
+ if result.error.is_some() || result.transcription.is_none() {
+ error!(
+ "Error in audio recording: {}. Not inserting audio result",
+ result.error.unwrap_or_default()
+ );
+ return Ok(None);
+ }
+
+ let speaker = get_or_create_speaker_from_embedding(db, &result.speaker_embedding).await?;
+
+ info!("Detected speaker: {:?}", speaker);
+
+ let transcription = result.transcription.unwrap();
+ let transcription_engine = audio_transcription_engine.to_string();
+ let mut chunk_id: Option<i64> = None;
+
+ info!(
+ "device {} inserting audio chunk: {:?}",
+ result.input.device, result.path
+ );
+ if let Some(id) = previous_transcript_id {
+ if let Some(prev_transcript) = previous_transcript {
+ match db
+ .update_audio_transcription(id, prev_transcript.as_str())
+ .await
+ {
+ Ok(_) => {}
+ Err(e) => error!(
+ "Failed to update transcription for {}: audio_chunk_id {}",
+ result.input.device, e
+ ),
+ }
+ }
+ }
+ match db.get_or_insert_audio_chunk(&result.path).await {
+ Ok(audio_chunk_id) => {
+ if transcription.is_empty() {
+ return Ok(Some(audio_chunk_id));
+ }
+
+ if let Err(e) = db
+ .insert_audio_transcription(
+ audio_chunk_id,
+ &transcription,
+ 0,
+ &transcription_engine,
+ &screenpipe_db::AudioDevice {
+ name: result.input.device.name.clone(),
+ device_type: match result.input.device.device_type {
+ crate::core::device::DeviceType::Input => {
+ screenpipe_db::DeviceType::Input
+ }
+ crate::core::device::DeviceType::Output => {
+ screenpipe_db::DeviceType::Output
+ }
+ },
+ },
+ Some(speaker.id),
+ Some(result.start_time),
+ Some(result.end_time),
+ )
+ .await
+ {
+ error!(
+ "Failed to insert audio transcription for device {}: {}",
+ result.input.device, e
+ );
+ return Ok(Some(audio_chunk_id));
+ } else {
+ debug!(
+ "Inserted audio transcription for chunk {} from device {} using {}",
+ audio_chunk_id, result.input.device, transcription_engine
+ );
+ chunk_id = Some(audio_chunk_id);
+ }
+ }
+ Err(e) => error!(
+ "Failed to insert audio chunk for device {}: {}",
+ result.input.device, e
+ ),
+ }
+ Ok(chunk_id)
+}
+
+async fn get_or_create_speaker_from_embedding(
+ db: &DatabaseManager,
+ embedding: &[f32],
+) -> Result<Speaker, anyhow::Error> {
+ let speaker = db.get_speaker_from_embedding(embedding).await?;
+ if let Some(speaker) = speaker {
+ Ok(speaker)
+ } else {
+ let speaker = db.insert_speaker(embedding).await?;
+ Ok(speaker)
+ }
+}
diff --git a/screenpipe-audio/src/transcription/whisper/batch.rs b/screenpipe-audio/src/transcription/whisper/batch.rs
new file mode 100644
index 000000000..48d8fcf36
--- /dev/null
+++ b/screenpipe-audio/src/transcription/whisper/batch.rs
@@ -0,0 +1,65 @@
+use super::detect_language;
+use anyhow::Result;
+use screenpipe_core::Language;
+use std::sync::Arc;
+use whisper_rs::{FullParams, SamplingStrategy, WhisperContext};
+/// Processes audio data using the Whisper model to generate transcriptions.
+///
+/// # Returns
+/// A string containing the processed transcript
+pub async fn process_with_whisper(
+ audio: &[f32],
+ languages: Vec<Language>,
+ whisper_context: Arc<WhisperContext>,
+) -> Result<String> {
+ let mut whisper_state = whisper_context
+ .create_state()
+ .expect("failed to create key");
+
+ let mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 0 });
+
+ let mut audio = audio.to_vec();
+
+ if audio.len() < 16000 {
+ audio.resize(16000, 0.0);
+ }
+
+ // Edit params as needed.
+ // Set the number of threads to use to 2.
+ params.set_n_threads(2);
+ // Disable anything that prints to stdout.
+ params.set_print_special(false);
+ params.set_print_progress(false);
+ params.set_print_realtime(false);
+ params.set_print_timestamps(false);
+ // Enable token level timestamps
+ params.set_token_timestamps(true);
+ whisper_state.pcm_to_mel(&audio, 2)?;
+ let (_, lang_tokens) = whisper_state.lang_detect(0, 2)?;
+ let lang = detect_language(lang_tokens, languages);
+ params.set_language(lang);
+ params.set_debug_mode(false);
+ params.set_logprob_thold(-2.0);
+ params.set_translate(false);
+
+ whisper_state
+ .full(params, &audio)
+ .expect("failed to run model");
+
+ let num_segments = whisper_state
+ .full_n_segments()
+ .expect("failed to get number of segments");
+
+ let mut transcript = String::new();
+
+ for i in 0..num_segments {
+ // Get the transcribed text and timestamps for the current segment.
+ let segment = whisper_state
+ .full_get_segment_text(i)
+ .expect("failed to get segment");
+
+ transcript.push_str(&segment);
+ }
+
+ Ok(transcript)
+}
diff --git a/screenpipe-audio/src/transcription/whisper/detect_language.rs b/screenpipe-audio/src/transcription/whisper/detect_language.rs
new file mode 100644
index 000000000..635e3ae58
--- /dev/null
+++ b/screenpipe-audio/src/transcription/whisper/detect_language.rs
@@ -0,0 +1,33 @@
+use anyhow::anyhow;
+use clap::ValueEnum;
+use log::debug;
+use screenpipe_core::Language;
+use whisper_rs::{get_lang_str, get_lang_str_full};
+
+pub fn detect_language<'a>(tokens: Vec<f32>, languages: Vec<Language>) -> Option<&'a str> {
+ if languages.len() == 1 {
+ return Some(languages.first().unwrap().as_lang_code());
+ }
+ for token in tokens {
+ let token = token as i32;
+ if let Some(lang) = get_lang_str_full(token) {
+ debug!("Detected language {lang}");
+ if languages.is_empty() {
+ return get_lang_str(token);
+ }
+
+ let l = match Language::from_str(lang, true)
+ .map_err(|_| anyhow!("language token not found"))
+ {
+ Ok(lang) => lang,
+ Err(_) => return None,
+ };
+
+ if languages.contains(&l) {
+ return get_lang_str(token);
+ }
+ }
+ }
+
+ None
+}
diff --git a/screenpipe-audio/src/transcription/whisper/mod.rs b/screenpipe-audio/src/transcription/whisper/mod.rs
new file mode 100644
index 000000000..981eaf51a
--- /dev/null
+++ b/screenpipe-audio/src/transcription/whisper/mod.rs
@@ -0,0 +1,4 @@
+pub mod batch;
+mod detect_language;
+pub use detect_language::detect_language;
+pub mod model;
diff --git a/screenpipe-audio/src/transcription/whisper/model.rs b/screenpipe-audio/src/transcription/whisper/model.rs
new file mode 100644
index 000000000..ff8add02b
--- /dev/null
+++ b/screenpipe-audio/src/transcription/whisper/model.rs
@@ -0,0 +1,45 @@
+use crate::core::engine::AudioTranscriptionEngine;
+use anyhow::Result;
+use hf_hub::{api::sync::Api, Repo, RepoType};
+use std::{path::PathBuf, sync::Arc};
+use whisper_rs::WhisperContextParameters;
+
+pub fn download_whisper_model(engine: Arc<AudioTranscriptionEngine>) -> Result<PathBuf> {
+ let api = Api::new()?;
+ let repo = Repo::with_revision(
+ "ggerganov/whisper.cpp".to_string(),
+ RepoType::Model,
+ "main".to_string(),
+ );
+ let api_repo = api.repo(repo);
+ let model_name = match *engine {
+ AudioTranscriptionEngine::WhisperLargeV3Turbo => "ggml-large-v3-turbo.bin",
+ AudioTranscriptionEngine::WhisperTiny => "ggml-tiny.bin",
+ AudioTranscriptionEngine::WhisperTinyQuantized => "ggml-tiny-q8_0.bin",
+ AudioTranscriptionEngine::WhisperLargeV3 => "ggml-large-v3.bin",
+ AudioTranscriptionEngine::WhisperLargeV3Quantized => "ggml-large-v3-q5_0.bin",
+ _ => "ggml-large-v3-turbo-q8_0.bin",
+ };
+
+ let model = api_repo.get(model_name)?;
+
+ Ok(model)
+}
+
+pub fn create_whisper_context_parameters<'a>(
+ engine: Arc<AudioTranscriptionEngine>,
+) -> Result<WhisperContextParameters<'a>> {
+ let model_preset = match *engine {
+ AudioTranscriptionEngine::WhisperLargeV3
+ | AudioTranscriptionEngine::WhisperLargeV3Quantized => whisper_rs::DtwModelPreset::LargeV3,
+ AudioTranscriptionEngine::WhisperTiny | AudioTranscriptionEngine::WhisperTinyQuantized => {
+ whisper_rs::DtwModelPreset::Tiny
+ }
+ _ => whisper_rs::DtwModelPreset::LargeV3Turbo,
+ };
+
+ let mut context_param = WhisperContextParameters::default();
+ context_param.dtw_parameters.mode = whisper_rs::DtwMode::ModelPreset { model_preset };
+
+ Ok(context_param)
+}
diff --git a/screenpipe-audio/src/utils/audio/convert.rs b/screenpipe-audio/src/utils/audio/convert.rs
new file mode 100644
index 000000000..5e7dcff81
--- /dev/null
+++ b/screenpipe-audio/src/utils/audio/convert.rs
@@ -0,0 +1,17 @@
+pub fn audio_to_mono(audio: &[f32], channels: u16) -> Vec<f32> {
+ let mut mono_samples = Vec::with_capacity(audio.len() / channels as usize);
+
+ // Iterate over the audio slice in chunks, each containing `channels` samples
+ for chunk in audio.chunks(channels as usize) {
+ // Sum the samples from all channels in the current chunk
+ let sum: f32 = chunk.iter().sum();
+
+ // Calculate the averagechannelsono sample
+ let mono_sample = sum / channels as f32;
+
+ // Store the computed mono sample
+ mono_samples.push(mono_sample);
+ }
+
+ mono_samples
+}
diff --git a/screenpipe-audio/src/utils/audio/mod.rs b/screenpipe-audio/src/utils/audio/mod.rs
new file mode 100644
index 000000000..21ce5000e
--- /dev/null
+++ b/screenpipe-audio/src/utils/audio/mod.rs
@@ -0,0 +1,11 @@
+mod convert;
+mod normalization;
+mod pcm_decode;
+mod resample;
+mod spectral_subtraction;
+
+pub use convert::audio_to_mono;
+pub use normalization::normalize_v2;
+pub use pcm_decode::pcm_decode;
+pub use resample::resample;
+pub use spectral_subtraction::{average_noise_spectrum, spectral_subtraction};
diff --git a/screenpipe-audio/src/utils/audio/normalization.rs b/screenpipe-audio/src/utils/audio/normalization.rs
new file mode 100644
index 000000000..53dfdd899
--- /dev/null
+++ b/screenpipe-audio/src/utils/audio/normalization.rs
@@ -0,0 +1,35 @@
+/// Normalizes audio samples to target RMS and peak levels while preserving dynamics.
+///
+/// # Arguments
+/// * `audio` - Slice of audio samples in the range [-1.0, 1.0]
+///
+/// # Returns
+/// * `Vec<f32>` - Normalized audio samples
+///
+/// The function normalizes audio by:
+/// 1. Computing RMS (Root Mean Square) and peak values
+/// 2. Calculating scaling factors to reach target levels
+/// 3. Applying the minimum of RMS and peak scaling to preserve dynamics
+pub fn normalize_v2(audio: &[f32]) -> Vec<f32> {
+ const TARGET_RMS: f32 = 0.2;
+ const TARGET_PEAK: f32 = 0.95;
+
+ let rms = (audio.iter().map(|&x| x * x).sum::<f32>() / audio.len() as f32).sqrt();
+ let peak = audio
+ .iter()
+ .fold(0.0f32, |max, &sample| max.max(sample.abs()));
+
+ // Return the original audio if it's completely silent
+ if rms.abs() < f32::EPSILON || peak.abs() < f32::EPSILON {
+ return audio.to_vec();
+ }
+
+ let rms_scaling = TARGET_RMS / rms;
+ let peak_scaling = TARGET_PEAK / peak;
+ let scaling_factor = rms_scaling.min(peak_scaling);
+
+ audio
+ .iter()
+ .map(|&sample| sample * scaling_factor)
+ .collect()
+}
diff --git a/screenpipe-audio/src/pcm_decode.rs b/screenpipe-audio/src/utils/audio/pcm_decode.rs
similarity index 62%
rename from screenpipe-audio/src/pcm_decode.rs
rename to screenpipe-audio/src/utils/audio/pcm_decode.rs
index 4b684b32c..032147932 100644
--- a/screenpipe-audio/src/pcm_decode.rs
+++ b/screenpipe-audio/src/utils/audio/pcm_decode.rs
@@ -1,8 +1,9 @@
-use log::debug;
use symphonia::core::audio::{AudioBufferRef, Signal};
-use symphonia::core::codecs::{DecoderOptions, CODEC_TYPE_NULL};
+use symphonia::core::codecs::CODEC_TYPE_NULL;
use symphonia::core::conv::FromSample;
+use tracing::debug;
+/// Converts audio samples from any supported format to f32
fn conv<T>(samples: &mut Vec<f32>, data: std::borrow::Cow<symphonia::core::audio::AudioBuffer<T>>)
where
T: symphonia::core::sample::Sample,
@@ -11,56 +12,67 @@ where
samples.extend(data.chan(0).iter().map(|v| f32::from_sample(*v)))
}
+/// Decodes an audio file to PCM format (f32 samples)
+///
+/// # Arguments
+/// * `path` - Path to the audio file
+///
+/// # Returns
+/// * `Ok((Vec<f32>, u32))` - Tuple containing the PCM samples and sample rate
+/// * `Err(anyhow::Error)` - If decoding fails
+///
+/// # Errors
+/// Returns an error if:
+/// * The file cannot be opened
+/// * No supported audio tracks are found
+/// * Decoding fails
pub fn pcm_decode<P: AsRef<std::path::Path>>(path: P) -> anyhow::Result<(Vec<f32>, u32)> {
debug!("Starting PCM decoding for {:?}", path.as_ref());
- // Open the media source.
- let src = std::fs::File::open(path)?;
- // Create the media source stream.
+ let src = std::fs::File::open(&path)?;
let mss = symphonia::core::io::MediaSourceStream::new(Box::new(src), Default::default());
- // Create a probe hint using the file's extension. [Optional]
+ // Create a probe hint and use default options
let hint = symphonia::core::probe::Hint::new();
- // hint.with_extension("mp4");
+ let probed = symphonia::default::get_probe().format(
+ &hint,
+ mss,
+ &Default::default(),
+ &Default::default(),
+ )?;
- // Use the default options for metadata and format readers.
- let meta_opts: symphonia::core::meta::MetadataOptions = Default::default();
- let fmt_opts: symphonia::core::formats::FormatOptions = Default::default();
-
- // Probe the media source.
- let probed = symphonia::default::get_probe().format(&hint, mss, &fmt_opts, &meta_opts)?;
- // Get the instantiated format reader.
let mut format = probed.format;
- // Find the first audio track with a known (decodeable) codec.
+ // Find the first decodeable audio track
let track = format
.tracks()
.iter()
.find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
- .ok_or_else(|| anyhow::anyhow!("no supported audio tracks"))?;
-
- // Use the default options for the decoder.
- let dec_opts: DecoderOptions = Default::default();
+ .ok_or_else(|| anyhow::anyhow!("no supported audio tracks found"))?;
- // Create a decoder for the track.
let mut decoder = symphonia::default::get_codecs()
- .make(&track.codec_params, &dec_opts)
- .expect("unsupported codec");
+ .make(&track.codec_params, &Default::default())
+ .map_err(|_| anyhow::anyhow!("unsupported codec"))?;
+
let track_id = track.id;
- let sample_rate = track.codec_params.sample_rate.unwrap_or(0);
+ let sample_rate = track
+ .codec_params
+ .sample_rate
+ .ok_or_else(|| anyhow::anyhow!("could not determine sample rate"))?;
+
let mut pcm_data = Vec::new();
debug!("Starting decode loop");
- // The decode loop.
+
while let Ok(packet) = format.next_packet() {
- // Consume any new metadata that has been read since the last packet.
+ // Skip metadata and packets from other tracks
while !format.metadata().is_latest() {
format.metadata().pop();
}
-
- // If the packet does not belong to the selected track, skip over it.
if packet.track_id() != track_id {
continue;
}
+
+ // Decode the packet
match decoder.decode(&packet)? {
AudioBufferRef::F32(buf) => pcm_data.extend(buf.chan(0)),
AudioBufferRef::U8(data) => conv(&mut pcm_data, data),
@@ -74,5 +86,6 @@ pub fn pcm_decode<P: AsRef<std::path::Path>>(path: P) -> anyhow::Result<(Vec<f32
AudioBufferRef::F64(data) => conv(&mut pcm_data, data),
}
}
+
Ok((pcm_data, sample_rate))
}
diff --git a/screenpipe-audio/src/utils/audio/resample.rs b/screenpipe-audio/src/utils/audio/resample.rs
new file mode 100644
index 000000000..5bbcb6542
--- /dev/null
+++ b/screenpipe-audio/src/utils/audio/resample.rs
@@ -0,0 +1,30 @@
+use anyhow::Result;
+use tracing::debug;
+use rubato::{
+ Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction,
+};
+
+pub fn resample(input: &[f32], from_sample_rate: u32, to_sample_rate: u32) -> Result<Vec<f32>> {
+ debug!("Resampling audio");
+ let params = SincInterpolationParameters {
+ sinc_len: 256,
+ f_cutoff: 0.95,
+ interpolation: SincInterpolationType::Linear,
+ oversampling_factor: 256,
+ window: WindowFunction::BlackmanHarris2,
+ };
+
+ let mut resampler = SincFixedIn::<f32>::new(
+ to_sample_rate as f64 / from_sample_rate as f64,
+ 2.0,
+ params,
+ input.len(),
+ 1,
+ )?;
+
+ let waves_in = vec![input.to_vec()];
+ debug!("Performing resampling");
+ let waves_out = resampler.process(&waves_in, None)?;
+ debug!("Resampling complete");
+ Ok(waves_out.into_iter().next().unwrap())
+}
diff --git a/screenpipe-audio/src/utils/audio/spectral_subtraction.rs b/screenpipe-audio/src/utils/audio/spectral_subtraction.rs
new file mode 100644
index 000000000..7fdf28365
--- /dev/null
+++ b/screenpipe-audio/src/utils/audio/spectral_subtraction.rs
@@ -0,0 +1,60 @@
+use anyhow::Result;
+use realfft::num_complex::{Complex32, ComplexFloat};
+use realfft::RealFftPlanner;
+
+pub fn spectral_subtraction(audio: &[f32], d: f32) -> Result<Vec<f32>> {
+ let mut real_planner = RealFftPlanner::<f32>::new();
+ let window_size = 1600; // 16k sample rate - 100ms
+ let r2c = real_planner.plan_fft_forward(window_size);
+
+ let mut y = r2c.make_output_vec();
+
+ let mut padded_audio = audio.to_vec();
+
+ padded_audio.append(&mut vec![0.0f32; window_size - audio.len()]);
+
+ let mut indata = padded_audio;
+ r2c.process(&mut indata, &mut y)?;
+
+ let mut processed_audio = y
+ .iter()
+ .map(|&x| {
+ let magnitude_y = x.abs().powf(2.0);
+
+ let div = 1.0 - (d / magnitude_y);
+
+ let gain = {
+ if div > 0.0 {
+ f32::sqrt(div)
+ } else {
+ 0.0f32
+ }
+ };
+
+ x * gain
+ })
+ .collect::<Vec<Complex32>>();
+
+ let c2r = real_planner.plan_fft_inverse(window_size);
+
+ let mut outdata = c2r.make_output_vec();
+
+ c2r.process(&mut processed_audio, &mut outdata)?;
+
+ Ok(outdata)
+}
+
+// not an average of non-speech segments, but I don't know how much pause time we
+// get. for now, we will just assume the noise is constant (kinda defeats the purpose)
+// but oh well
+pub fn average_noise_spectrum(audio: &[f32]) -> f32 {
+ let mut total_sum = 0.0f32;
+
+ for sample in audio {
+ let magnitude = sample.abs();
+
+ total_sum += magnitude.powf(2.0);
+ }
+
+ total_sum / audio.len() as f32
+}
diff --git a/screenpipe-audio/src/encode.rs b/screenpipe-audio/src/utils/ffmpeg.rs
similarity index 69%
rename from screenpipe-audio/src/encode.rs
rename to screenpipe-audio/src/utils/ffmpeg.rs
index 6e397f9b7..bf4ab8187 100644
--- a/screenpipe-audio/src/encode.rs
+++ b/screenpipe-audio/src/utils/ffmpeg.rs
@@ -1,12 +1,16 @@
+use anyhow::Result;
+use chrono::Utc;
+use tracing::debug;
use screenpipe_core::find_ffmpeg_path;
use std::io::Write;
+use std::path::PathBuf;
use std::{
path::Path,
process::{Command, Stdio},
};
-use tracing::{debug, error};
+use tracing::error;
-pub fn encode_single_audio(
+fn encode_single_audio(
data: &[u8],
sample_rate: u32,
channels: u16,
@@ -73,3 +77,31 @@ pub fn encode_single_audio(
Ok(())
}
+
+pub fn get_new_file_path(device: &str, output_path: &PathBuf) -> String {
+ let new_file_name = Utc::now().format("%Y-%m-%d_%H-%M-%S").to_string();
+ let sanitized_device_name = device.replace(['/', '\\'], "_");
+ PathBuf::from(output_path)
+ .join(format!("{}_{}.mp4", sanitized_device_name, new_file_name))
+ .to_str()
+ .expect("Failed to create valid path")
+ .to_string()
+}
+
+pub fn write_audio_to_file(
+ audio: &[f32],
+ sample_rate: u32,
+ path: &PathBuf,
+ skip_encoding: bool,
+) -> Result<()> {
+ // Run FFmpeg in a separate task
+ if !skip_encoding {
+ encode_single_audio(
+ bytemuck::cast_slice(audio),
+ sample_rate,
+ 1,
+ &PathBuf::from(path),
+ )?;
+ }
+ Ok(())
+}
diff --git a/screenpipe-audio/src/utils/mod.rs b/screenpipe-audio/src/utils/mod.rs
new file mode 100644
index 000000000..56574795e
--- /dev/null
+++ b/screenpipe-audio/src/utils/mod.rs
@@ -0,0 +1,2 @@
+pub mod audio;
+pub mod ffmpeg;
diff --git a/screenpipe-audio/src/vad/mod.rs b/screenpipe-audio/src/vad/mod.rs
new file mode 100644
index 000000000..07378c24a
--- /dev/null
+++ b/screenpipe-audio/src/vad/mod.rs
@@ -0,0 +1,66 @@
+pub mod silero;
+pub mod webrtc;
+
+use anyhow;
+use lazy_static::lazy_static;
+use silero::SileroVad;
+use std::path::PathBuf;
+use std::sync::Once;
+use tokio::sync::Mutex;
+use vad_rs::VadStatus;
+use webrtc::WebRtcVad;
+
+#[derive(Clone, Copy, Debug, Default)]
+pub enum VadSensitivity {
+ Low,
+ #[default]
+ Medium,
+ High,
+}
+
+impl VadSensitivity {
+ pub fn min_speech_ratio(&self) -> f32 {
+ match self {
+ VadSensitivity::Low => 0.01, // 1% of frames must be speech
+ VadSensitivity::Medium => 0.05, // 5% of frames must be speech
+ VadSensitivity::High => 0.2, // 20% of frames must be speech
+ }
+ }
+}
+
+#[derive(Clone)]
+pub enum VadEngineEnum {
+ WebRtc,
+ Silero,
+}
+
+pub trait VadEngine: Send {
+ fn is_voice_segment(&mut self, audio_chunk: &[f32]) -> anyhow::Result<bool>;
+ fn set_sensitivity(&mut self, sensitivity: VadSensitivity);
+ fn audio_type(&mut self, audio_chunk: &[f32]) -> anyhow::Result<VadStatus>;
+ fn get_min_speech_ratio(&self) -> f32;
+}
+
+const FRAME_HISTORY: usize = 10; // Number of frames to consider for decision
+const SPEECH_THRESHOLD: f32 = 0.5;
+const SILENCE_THRESHOLD: f32 = 0.35;
+const SPEECH_FRAME_THRESHOLD: usize = 3; // Minimum number of frames above SPEECH_THRESHOLD to consider as speech
+
+lazy_static! {
+ static ref MODEL_PATH: Mutex<Option<PathBuf>> = Mutex::new(None);
+}
+
+static DOWNLOAD_ONCE: Once = Once::new();
+
+pub async fn create_vad_engine(engine: VadEngineEnum) -> anyhow::Result<Box<dyn VadEngine>> {
+ match engine {
+ VadEngineEnum::WebRtc => Ok(Box::new(WebRtcVad::new())),
+ VadEngineEnum::Silero => {
+ let silero_vad = SileroVad::new().await?;
+ Ok(Box::new(silero_vad))
+ }
+ }
+}
+
+unsafe impl Send for WebRtcVad {}
+unsafe impl Send for SileroVad {}
diff --git a/screenpipe-audio/src/vad_engine.rs b/screenpipe-audio/src/vad/silero.rs
similarity index 57%
rename from screenpipe-audio/src/vad_engine.rs
rename to screenpipe-audio/src/vad/silero.rs
index 0b774dd9b..5be73002e 100644
--- a/screenpipe-audio/src/vad_engine.rs
+++ b/screenpipe-audio/src/vad/silero.rs
@@ -1,123 +1,16 @@
use anyhow;
use dirs;
-use lazy_static::lazy_static;
-use log::debug;
use std::collections::VecDeque;
use std::path::PathBuf;
-use std::sync::Once;
-use tokio::sync::Mutex;
-use tracing::info;
+use tracing::debug;
use vad_rs::{Vad, VadStatus};
-#[derive(Clone, Copy, Debug, Default)]
-pub enum VadSensitivity {
- Low,
- #[default]
- Medium,
- High,
-}
-
-impl VadSensitivity {
- pub fn min_speech_ratio(&self) -> f32 {
- match self {
- VadSensitivity::Low => 0.01, // 1% of frames must be speech
- VadSensitivity::Medium => 0.05, // 5% of frames must be speech
- VadSensitivity::High => 0.2, // 20% of frames must be speech
- }
- }
-}
-
-pub enum VadEngineEnum {
- WebRtc,
- Silero,
-}
-
-pub trait VadEngine: Send {
- fn is_voice_segment(&mut self, audio_chunk: &[f32]) -> anyhow::Result<bool>;
- fn set_sensitivity(&mut self, sensitivity: VadSensitivity);
- fn audio_type(&mut self, audio_chunk: &[f32]) -> anyhow::Result<VadStatus>;
- fn get_min_speech_ratio(&self) -> f32;
-}
-
-#[derive(Default)]
-pub struct WebRtcVad {
- vad: webrtc_vad::Vad,
- sensitivity: VadSensitivity,
-}
-
-impl WebRtcVad {
- pub fn new() -> Self {
- let vad = webrtc_vad::Vad::new();
- Self {
- vad,
- sensitivity: VadSensitivity::Medium,
- }
- }
-}
-
-impl VadEngine for WebRtcVad {
- fn is_voice_segment(&mut self, audio_chunk: &[f32]) -> anyhow::Result<bool> {
- // Convert f32 to i16
- let i16_chunk: Vec<i16> = audio_chunk.iter().map(|&x| (x * 32767.0) as i16).collect();
-
- // Set VAD mode based on sensitivity
- let mode = match self.sensitivity {
- VadSensitivity::Low => webrtc_vad::VadMode::Quality,
- VadSensitivity::Medium => webrtc_vad::VadMode::Aggressive,
- VadSensitivity::High => webrtc_vad::VadMode::VeryAggressive,
- };
- self.vad.set_mode(mode);
-
- let result = self
- .vad
- .is_voice_segment(&i16_chunk)
- .map_err(|e| anyhow::anyhow!("WebRTC VAD error: {:?}", e))?;
-
- Ok(result)
- }
- fn audio_type(&mut self, audio_chunk: &[f32]) -> anyhow::Result<VadStatus> {
- // Convert f32 to i16
- let i16_chunk: Vec<i16> = audio_chunk.iter().map(|&x| (x * 32767.0) as i16).collect();
-
- // Set VAD mode based on sensitivity
- let mode = match self.sensitivity {
- VadSensitivity::Low => webrtc_vad::VadMode::Quality,
- VadSensitivity::Medium => webrtc_vad::VadMode::Aggressive,
- VadSensitivity::High => webrtc_vad::VadMode::VeryAggressive,
- };
- self.vad.set_mode(mode);
-
- let result = self
- .vad
- .is_voice_segment(&i16_chunk)
- .map_err(|e| anyhow::anyhow!("WebRTC VAD error: {:?}", e))?;
-
- if !result {
- return Ok(VadStatus::Silence);
- }
+use crate::vad::FRAME_HISTORY;
- Ok(VadStatus::Speech)
- }
-
- fn set_sensitivity(&mut self, sensitivity: VadSensitivity) {
- self.sensitivity = sensitivity;
- }
-
- fn get_min_speech_ratio(&self) -> f32 {
- self.sensitivity.min_speech_ratio()
- }
-}
-
-const FRAME_HISTORY: usize = 10; // Number of frames to consider for decision
-const SPEECH_THRESHOLD: f32 = 0.5;
-const SILENCE_THRESHOLD: f32 = 0.35;
-const SPEECH_FRAME_THRESHOLD: usize = 3; // Minimum number of frames above SPEECH_THRESHOLD to consider as speech
-
-lazy_static! {
- static ref MODEL_PATH: Mutex<Option<PathBuf>> = Mutex::new(None);
-}
-
-static DOWNLOAD_ONCE: Once = Once::new();
+use super::{
+ VadEngine, VadSensitivity, DOWNLOAD_ONCE, MODEL_PATH, SILENCE_THRESHOLD,
+ SPEECH_FRAME_THRESHOLD, SPEECH_THRESHOLD,
+};
pub struct SileroVad {
vad: Vad,
@@ -127,9 +20,9 @@ pub struct SileroVad {
impl SileroVad {
pub async fn new() -> anyhow::Result<Self> {
- info!("Initializing SileroVad...");
+ debug!("Initializing SileroVad...");
let model_path = Self::get_or_download_model().await?;
- info!("SileroVad Model downloaded to: {:?}", model_path);
+ debug!("SileroVad Model downloaded to: {:?}", model_path);
let vad = Vad::new(model_path, 16000).map_err(|e| {
debug!("SileroVad Error creating Vad: {}", e);
anyhow::anyhow!("Vad creation error: {}", e)
@@ -285,16 +178,3 @@ impl VadEngine for SileroVad {
self.sensitivity.min_speech_ratio()
}
}
-
-pub async fn create_vad_engine(engine: VadEngineEnum) -> anyhow::Result<Box<dyn VadEngine>> {
- match engine {
- VadEngineEnum::WebRtc => Ok(Box::new(WebRtcVad::new())),
- VadEngineEnum::Silero => {
- let silero_vad = SileroVad::new().await?;
- Ok(Box::new(silero_vad))
- }
- }
-}
-
-unsafe impl Send for WebRtcVad {}
-unsafe impl Send for SileroVad {}
diff --git a/screenpipe-audio/src/vad/webrtc.rs b/screenpipe-audio/src/vad/webrtc.rs
new file mode 100644
index 000000000..51f4e2e22
--- /dev/null
+++ b/screenpipe-audio/src/vad/webrtc.rs
@@ -0,0 +1,72 @@
+use anyhow;
+use vad_rs::VadStatus;
+
+use super::{VadEngine, VadSensitivity};
+
+#[derive(Default)]
+pub struct WebRtcVad {
+ vad: webrtc_vad::Vad,
+ sensitivity: VadSensitivity,
+}
+
+impl WebRtcVad {
+ pub fn new() -> Self {
+ let vad = webrtc_vad::Vad::new();
+ Self {
+ vad,
+ sensitivity: VadSensitivity::Medium,
+ }
+ }
+}
+impl VadEngine for WebRtcVad {
+ fn is_voice_segment(&mut self, audio_chunk: &[f32]) -> anyhow::Result<bool> {
+ // Convert f32 to i16
+ let i16_chunk: Vec<i16> = audio_chunk.iter().map(|&x| (x * 32767.0) as i16).collect();
+
+ // Set VAD mode based on sensitivity
+ let mode = match self.sensitivity {
+ VadSensitivity::Low => webrtc_vad::VadMode::Quality,
+ VadSensitivity::Medium => webrtc_vad::VadMode::Aggressive,
+ VadSensitivity::High => webrtc_vad::VadMode::VeryAggressive,
+ };
+ self.vad.set_mode(mode);
+
+ let result = self
+ .vad
+ .is_voice_segment(&i16_chunk)
+ .map_err(|e| anyhow::anyhow!("WebRTC VAD error: {:?}", e))?;
+
+ Ok(result)
+ }
+ fn audio_type(&mut self, audio_chunk: &[f32]) -> anyhow::Result<VadStatus> {
+ // Convert f32 to i16
+ let i16_chunk: Vec<i16> = audio_chunk.iter().map(|&x| (x * 32767.0) as i16).collect();
+
+ // Set VAD mode based on sensitivity
+ let mode = match self.sensitivity {
+ VadSensitivity::Low => webrtc_vad::VadMode::Quality,
+ VadSensitivity::Medium => webrtc_vad::VadMode::Aggressive,
+ VadSensitivity::High => webrtc_vad::VadMode::VeryAggressive,
+ };
+ self.vad.set_mode(mode);
+
+ let result = self
+ .vad
+ .is_voice_segment(&i16_chunk)
+ .map_err(|e| anyhow::anyhow!("WebRTC VAD error: {:?}", e))?;
+
+ if !result {
+ return Ok(VadStatus::Silence);
+ }
+
+ Ok(VadStatus::Speech)
+ }
+
+ fn set_sensitivity(&mut self, sensitivity: VadSensitivity) {
+ self.sensitivity = sensitivity;
+ }
+
+ fn get_min_speech_ratio(&self) -> f32 {
+ self.sensitivity.min_speech_ratio()
+ }
+}
diff --git a/screenpipe-audio/src/whisper/decoder.rs b/screenpipe-audio/src/whisper/decoder.rs
deleted file mode 100644
index baa041a65..000000000
--- a/screenpipe-audio/src/whisper/decoder.rs
+++ /dev/null
@@ -1,307 +0,0 @@
-use crate::whisper::Model;
-use anyhow::{Error as E, Result};
-use candle::{Device, IndexOp, Tensor};
-use candle_nn::ops::softmax;
-use candle_transformers::models::whisper as m;
-use log::{debug, error, info};
-use rand::{distributions::Distribution, SeedableRng};
-use tokenizers::Tokenizer;
-
-#[derive(Debug, Clone)]
-pub struct DecodingResult {
- tokens: Vec<u32>,
- pub text: String,
- avg_logprob: f64,
- no_speech_prob: f64,
- #[allow(dead_code)]
- temperature: f64,
- compression_ratio: f64,
-}
-
-#[derive(Debug, Clone)]
-pub struct Segment {
- pub start: f64,
- pub duration: f64,
- pub dr: DecodingResult,
-}
-
-pub struct Decoder<'a> {
- pub model: &'a mut Model,
- rng: rand::rngs::StdRng,
- timestamps: bool,
- verbose: bool,
- tokenizer: &'a Tokenizer,
- suppress_tokens: Tensor,
- sot_token: u32,
- transcribe_token: u32,
- eot_token: u32,
- no_speech_token: u32,
- no_timestamps_token: u32,
- language_token: Option<u32>,
-}
-
-impl<'a> Decoder<'a> {
- #[allow(clippy::too_many_arguments)]
- pub fn new(
- model: &'a mut Model,
- tokenizer: &'a Tokenizer,
- seed: u64,
- device: &Device,
- language_token: Option<u32>,
- timestamps: bool,
- verbose: bool,
- ) -> Result<Self> {
- let no_timestamps_token = token_id(tokenizer, m::NO_TIMESTAMPS_TOKEN)?;
- let suppress_tokens: Vec<f32> = (0..model.config().vocab_size as u32)
- .map(|i| {
- if model.config().suppress_tokens.contains(&i)
- || timestamps && i == no_timestamps_token
- {
- f32::NEG_INFINITY
- } else {
- 0f32
- }
- })
- .collect();
- let suppress_tokens = Tensor::new(suppress_tokens.as_slice(), device)?;
- let sot_token = token_id(tokenizer, m::SOT_TOKEN)?;
- let transcribe_token = token_id(tokenizer, m::TRANSCRIBE_TOKEN)?;
- let eot_token = token_id(tokenizer, m::EOT_TOKEN)?;
- let no_speech_token = m::NO_SPEECH_TOKENS
- .iter()
- .find_map(|token| token_id(tokenizer, token).ok());
- let no_speech_token = match no_speech_token {
- None => anyhow::bail!("unable to find any non-speech token"),
- Some(n) => n,
- };
-
- Ok(Self {
- model,
- rng: rand::rngs::StdRng::seed_from_u64(seed),
- tokenizer,
- timestamps,
- verbose,
- suppress_tokens,
- sot_token,
- transcribe_token,
- eot_token,
- no_speech_token,
- language_token,
- no_timestamps_token,
- })
- }
-
- fn decode(&mut self, mel: &Tensor, t: f64) -> Result<DecodingResult> {
- let audio_features = self.model.encoder_forward(mel, true)?;
- if self.verbose {
- info!("audio features: {:?}", audio_features.dims());
- }
- let sample_len = self.model.config().max_target_positions / 2;
- let mut no_speech_prob = f64::NAN;
- let mut tokens = vec![self.sot_token];
- if let Some(language_token) = self.language_token {
- tokens.push(language_token);
- }
- tokens.push(self.transcribe_token);
-
- if !self.timestamps {
- tokens.push(self.no_timestamps_token);
- }
-
- let mut sum_logprob = 0f64;
- let mut last_token_was_timestamp = false;
-
- let mut token_history = Vec::new(); // Track recent tokens
-
- for i in 0..sample_len {
- let tokens_t = Tensor::new(tokens.as_slice(), mel.device())?;
- let tokens_t = tokens_t.unsqueeze(0)?;
- let ys = self
- .model
- .decoder_forward(&tokens_t, &audio_features, i == 0)?;
-
- if i == 0 {
- let logits = self.model.decoder_final_linear(&ys.i(..1)?)?.i(0)?.i(0)?;
- no_speech_prob = softmax(&logits, 0)?
- .i(self.no_speech_token as usize)?
- .to_scalar::<f32>()? as f64;
- }
-
- let (_, seq_len, _) = ys.dims3()?;
- let logits = self
- .model
- .decoder_final_linear(&ys.i((..1, seq_len - 1..))?)?
- .i(0)?
- .i(0)?;
-
- let logits = logits.broadcast_add(&self.suppress_tokens)?;
-
- let logits = if last_token_was_timestamp {
- let mask = Tensor::zeros_like(&logits)?;
- let eot_mask = mask.get(self.eot_token as usize)?;
- logits.broadcast_add(&eot_mask)?
- } else {
- logits
- };
-
- // Apply repetition penalty
- let mut logits_v: Vec<f32> = logits.to_vec1()?;
- apply_repetition_penalty(&mut logits_v, &token_history, 1.0); // Adjust penalty as needed
-
- let next_token = if t > 0f64 {
- let logits_tensor = Tensor::new(logits_v.as_slice(), logits.device())?;
- let scaled_logits = (&logits_tensor / t)?;
- let prs = softmax(&scaled_logits, 0)?;
- let prs_vec: Vec<f32> = prs.to_vec1()?;
- let distr = rand::distributions::WeightedIndex::new(&prs_vec)?;
- distr.sample(&mut self.rng) as u32
- } else {
- logits_v
- .iter()
- .enumerate()
- .max_by(|(_, u), (_, v)| u.total_cmp(v))
- .map(|(i, _)| i as u32)
- .unwrap()
- };
-
- tokens.push(next_token);
- token_history.push(next_token); // Add to history
-
- let prob = softmax(&logits, candle::D::Minus1)?
- .i(next_token as usize)?
- .to_scalar::<f32>()? as f64;
-
- sum_logprob += prob.ln();
-
- if next_token == self.eot_token
- || tokens.len() > self.model.config().max_target_positions
- {
- break;
- }
-
- last_token_was_timestamp = next_token > self.no_timestamps_token;
- }
-
- let text = self.tokenizer.decode(&tokens, true).map_err(E::msg)?;
- let avg_logprob = sum_logprob / tokens.len() as f64;
-
- Ok(DecodingResult {
- tokens,
- text,
- avg_logprob,
- no_speech_prob,
- temperature: t,
- compression_ratio: f64::NAN,
- })
- }
-
- fn decode_with_fallback(&mut self, segment: &Tensor) -> Result<DecodingResult> {
- for (i, &t) in m::TEMPERATURES.iter().enumerate() {
- let dr: Result<DecodingResult> = self.decode(segment, t);
- if i == m::TEMPERATURES.len() - 1 {
- return dr;
- }
- match dr {
- Ok(dr) => {
- let needs_fallback = dr.compression_ratio > m::COMPRESSION_RATIO_THRESHOLD
- || dr.avg_logprob < m::LOGPROB_THRESHOLD;
- if !needs_fallback || dr.no_speech_prob > m::NO_SPEECH_THRESHOLD {
- return Ok(dr);
- }
- }
- Err(err) => {
- error!("Error running at {t}: {err}")
- }
- }
- }
- unreachable!()
- }
-
- pub fn reset_kv_cache(&mut self) {
- match &mut self.model {
- Model::Normal(m) => m.reset_kv_cache(),
- Model::Quantized(m) => m.reset_kv_cache(),
- }
- }
-
- pub fn set_language_token(&mut self, language_token: Option<u32>) {
- self.language_token = language_token;
- }
-
- pub fn run(&mut self, mel: &Tensor) -> Result<Vec<Segment>> {
- let (_, _, content_frames) = mel.dims3()?;
- let mut seek = 0;
- let mut segments = vec![];
- while seek < content_frames {
- let start = std::time::Instant::now();
- let time_offset = (seek * m::HOP_LENGTH) as f64 / m::SAMPLE_RATE as f64;
- let segment_size = usize::min(content_frames - seek, m::N_FRAMES);
- let mel_segment = mel.narrow(2, seek, segment_size)?;
- let segment_duration = (segment_size * m::HOP_LENGTH) as f64 / m::SAMPLE_RATE as f64;
- let dr = self.decode_with_fallback(&mel_segment)?;
- seek += segment_size;
- if dr.no_speech_prob > m::NO_SPEECH_THRESHOLD && dr.avg_logprob < m::LOGPROB_THRESHOLD {
- debug!("no speech detected, skipping {seek} {dr:?}");
- continue;
- }
- let segment = Segment {
- start: time_offset,
- duration: segment_duration,
- dr,
- };
- if self.timestamps {
- let mut tokens_to_decode = vec![];
- let mut prev_timestamp_s = 0f32;
- for &token in segment.dr.tokens.iter() {
- if token == self.sot_token || token == self.eot_token {
- continue;
- }
- if token > self.no_timestamps_token {
- let timestamp_s = (token - self.no_timestamps_token + 1) as f32 / 50.;
- if !tokens_to_decode.is_empty() {
- let text = self
- .tokenizer
- .decode(&tokens_to_decode, true)
- .map_err(E::msg)?;
- debug!(" {:.1}s-{:.1}s: {}", prev_timestamp_s, timestamp_s, text);
- tokens_to_decode.clear()
- }
- prev_timestamp_s = timestamp_s;
- } else {
- tokens_to_decode.push(token)
- }
- }
- if !tokens_to_decode.is_empty() {
- tokens_to_decode.clear()
- }
- }
-
- if self.verbose {
- info!("{seek}: {segment:?}, in {:?}", start.elapsed());
- }
- segments.push(segment)
- }
- Ok(segments)
- }
-}
-pub fn token_id(tokenizer: &Tokenizer, token: &str) -> candle::Result<u32> {
- match tokenizer.token_to_id(token) {
- None => candle::bail!("no token-id for {token}"),
- Some(id) => Ok(id),
- }
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum Task {
- Transcribe,
- #[allow(dead_code)]
- Translate,
-}
-
-fn apply_repetition_penalty(logits: &mut [f32], token_history: &[u32], penalty: f32) {
- for &token in token_history {
- if let Some(logit) = logits.get_mut(token as usize) {
- *logit -= penalty;
- }
- }
-}
diff --git a/screenpipe-audio/src/whisper/mod.rs b/screenpipe-audio/src/whisper/mod.rs
deleted file mode 100644
index 6ebe8da45..000000000
--- a/screenpipe-audio/src/whisper/mod.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-mod decoder;
-mod model;
-mod process_chunk;
-
-pub use decoder::*;
-pub use model::*;
-pub use process_chunk::*;
diff --git a/screenpipe-audio/src/whisper/model.rs b/screenpipe-audio/src/whisper/model.rs
deleted file mode 100644
index ad6d22952..000000000
--- a/screenpipe-audio/src/whisper/model.rs
+++ /dev/null
@@ -1,113 +0,0 @@
-use anyhow::{Error as E, Result};
-use candle::{Device, Tensor};
-use candle_nn::VarBuilder;
-use candle_transformers::models::whisper::{self as m, Config};
-use hf_hub::{api::sync::Api, Repo, RepoType};
-use log::{debug, info};
-use tokenizers::Tokenizer;
-
-#[derive(Clone)]
-pub struct WhisperModel {
- pub model: Model,
- pub tokenizer: Tokenizer,
- pub device: Device,
-}
-
-impl WhisperModel {
- pub fn new(engine: &crate::AudioTranscriptionEngine) -> Result<Self> {
- debug!("Initializing WhisperModel");
- let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));
- info!("device = {:?}", device);
-
- debug!("Fetching model files");
- let (config_filename, tokenizer_filename, weights_filename) = {
- let api = Api::new()?;
- let repo = match engine {
- crate::AudioTranscriptionEngine::WhisperTiny => Repo::with_revision(
- "openai/whisper-tiny".to_string(),
- RepoType::Model,
- "main".to_string(),
- ),
- crate::AudioTranscriptionEngine::WhisperDistilLargeV3 => Repo::with_revision(
- "distil-whisper/distil-large-v3".to_string(),
- RepoType::Model,
- "main".to_string(),
- ),
- crate::AudioTranscriptionEngine::WhisperLargeV3Turbo => Repo::with_revision(
- "openai/whisper-large-v3-turbo".to_string(),
- RepoType::Model,
- "main".to_string(),
- ),
- _ => Repo::with_revision(
- "openai/whisper-large-v3-turbo".to_string(),
- RepoType::Model,
- "main".to_string(),
- ),
- };
- let api_repo = api.repo(repo);
- let config = api_repo.get("config.json")?;
- let tokenizer = api_repo.get("tokenizer.json")?;
- let model = api_repo.get("model.safetensors")?;
- (config, tokenizer, model)
- };
-
- debug!("Parsing config and tokenizer");
- let config: Config = serde_json::from_str(&std::fs::read_to_string(config_filename)?)?;
- let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?;
- // tokenizer.with_pre_tokenizer(PreT)
- debug!("Loading model weights");
- let vb =
- unsafe { VarBuilder::from_mmaped_safetensors(&[weights_filename], m::DTYPE, &device)? };
- let whisper = m::model::Whisper::load(&vb, config.clone())?;
-
- let model = Model::Normal(whisper);
-
- debug!("WhisperModel initialization complete");
- Ok(Self {
- model,
- tokenizer,
- device,
- })
- }
-}
-
-#[derive(Debug, Clone)]
-pub enum Model {
- Normal(m::model::Whisper),
- Quantized(m::quantized_model::Whisper),
-}
-
-impl Model {
- pub fn config(&self) -> &Config {
- match self {
- Self::Normal(m) => &m.config,
- Self::Quantized(m) => &m.config,
- }
- }
-
- pub fn encoder_forward(&mut self, x: &Tensor, flush: bool) -> candle::Result<Tensor> {
- match self {
- Self::Normal(m) => m.encoder.forward(x, flush),
- Self::Quantized(m) => m.encoder.forward(x, flush),
- }
- }
-
- pub fn decoder_forward(
- &mut self,
- x: &Tensor,
- xa: &Tensor,
- flush: bool,
- ) -> candle::Result<Tensor> {
- match self {
- Self::Normal(m) => m.decoder.forward(x, xa, flush),
- Self::Quantized(m) => m.decoder.forward(x, xa, flush),
- }
- }
-
- pub fn decoder_final_linear(&self, x: &Tensor) -> candle::Result<Tensor> {
- match self {
- Self::Normal(m) => m.decoder.final_linear(x),
- Self::Quantized(m) => m.decoder.final_linear(x),
- }
- }
-}
diff --git a/screenpipe-audio/src/whisper/process_chunk.rs b/screenpipe-audio/src/whisper/process_chunk.rs
deleted file mode 100644
index ecb251913..000000000
--- a/screenpipe-audio/src/whisper/process_chunk.rs
+++ /dev/null
@@ -1,124 +0,0 @@
-use super::Segment;
-use crate::{
- multilingual,
- whisper::{Decoder, WhisperModel},
-};
-use anyhow::Result;
-use candle::Tensor;
-use candle_transformers::models::whisper::audio;
-use lazy_static::lazy_static;
-use log::debug;
-use regex::Regex;
-use screenpipe_core::Language;
-use std::collections::HashSet;
-
-lazy_static! {
- static ref TOKEN_REGEX: Regex = Regex::new(r"<\|\d{1,2}\.\d{1,2}\|>").unwrap();
-}
-
-pub fn process_with_whisper(
- whisper_model: &mut WhisperModel,
- audio: &[f32],
- mel_filters: &[f32],
- languages: Vec<Language>,
-) -> Result<String> {
- let model = &mut whisper_model.model;
- let tokenizer = &whisper_model.tokenizer;
- let device = &whisper_model.device;
-
- debug!("converting pcm to mel spectrogram");
- let mel = audio::pcm_to_mel(model.config(), audio, mel_filters);
- let mel_len = mel.len();
-
- debug!("creating tensor from mel spectrogram");
- let mel = Tensor::from_vec(
- mel,
- (
- 1,
- model.config().num_mel_bins,
- mel_len / model.config().num_mel_bins,
- ),
- device,
- )?;
-
- debug!("detecting language");
- let language_token = Some(multilingual::detect_language(
- model,
- tokenizer,
- &mel,
- languages.clone(),
- )?);
-
- debug!("initializing decoder");
- let mut dc = Decoder::new(model, tokenizer, 42, device, language_token, true, false)?;
-
- debug!("starting decoding process");
- let segments = dc.run(&mel)?;
- debug!("decoding complete");
-
- process_segments(segments)
-}
-
-fn process_segments(segments: Vec<Segment>) -> Result<String> {
- let mut ranges: HashSet<String> = HashSet::new();
- let mut transcript = String::new();
-
- let mut min_time: f32 = f32::MAX;
- let mut max_time: f32 = f32::MIN;
- let segments_len = segments.len();
-
- for (i, segment) in segments.iter().enumerate() {
- let mut text = segment.dr.text.clone();
-
- // Extract start and end times
- let (start, end) = extract_time_tokens(&text, &TOKEN_REGEX);
- let (s_time, e_time) = parse_time_tokens(&start, &end, &mut min_time, &mut max_time);
-
- let range = format!("{}{}", start, end);
- if ranges.insert(range) {
- if segments_len > 1 && i == segments_len - 1 && s_time == min_time && e_time == max_time
- {
- continue;
- }
-
- text = TOKEN_REGEX.replace_all(&text, "").to_string();
- text.push('\n');
- transcript.push_str(&text);
- }
- }
-
- Ok(transcript)
-}
-
-fn extract_time_tokens(text: &str, token_regex: &Regex) -> (String, String) {
- let tokens = token_regex
- .find_iter(text)
- .map(|m| m.as_str())
- .collect::<Vec<&str>>();
-
- let start = tokens.first().unwrap().to_string();
- let end = tokens.last().unwrap().to_string();
-
- (start, end)
-}
-
-fn parse_time_tokens(start: &str, end: &str, min_time: &mut f32, max_time: &mut f32) -> (f32, f32) {
- let num_regex = Regex::new(r"([<>|])").unwrap();
- let s_time = num_regex
- .replace_all(start, "")
- .parse::<f32>()
- .unwrap_or(*min_time);
- let e_time = num_regex
- .replace_all(end, "")
- .parse::<f32>()
- .unwrap_or(*max_time);
-
- if *min_time > s_time {
- *min_time = s_time;
- }
- if *max_time < e_time {
- *max_time = e_time;
- }
-
- (s_time, e_time)
-}
diff --git a/screenpipe-audio/tests/accuracy_test.rs b/screenpipe-audio/tests/accuracy_test.rs
index dacf3335f..73bb46411 100644
--- a/screenpipe-audio/tests/accuracy_test.rs
+++ b/screenpipe-audio/tests/accuracy_test.rs
@@ -1,17 +1,22 @@
-use candle_transformers::models::whisper;
use futures::future::join_all;
-use screenpipe_audio::pyannote::embedding::EmbeddingExtractor;
-use screenpipe_audio::pyannote::identify::EmbeddingManager;
-use screenpipe_audio::stt::{prepare_segments, stt};
-use screenpipe_audio::vad_engine::{SileroVad, VadEngine};
-use screenpipe_audio::whisper::WhisperModel;
-use screenpipe_audio::{resample, AudioInput, AudioTranscriptionEngine};
+use screenpipe_audio::core::device::default_input_device;
+use screenpipe_audio::core::engine::AudioTranscriptionEngine;
+use screenpipe_audio::speaker::embedding::EmbeddingExtractor;
+use screenpipe_audio::speaker::embedding_manager::EmbeddingManager;
+use screenpipe_audio::speaker::prepare_segments;
+use screenpipe_audio::transcription::stt::SAMPLE_RATE;
+use screenpipe_audio::transcription::whisper::model::{
+ create_whisper_context_parameters, download_whisper_model,
+};
+use screenpipe_audio::vad::{silero::SileroVad, VadEngine};
+use screenpipe_audio::{resample, stt, AudioInput};
use screenpipe_core::Language;
use std::path::PathBuf;
use std::sync::Arc;
use strsim::levenshtein;
use tokio::sync::Mutex;
use tracing::debug;
+use whisper_rs::WhisperContext;
#[tokio::test]
#[ignore]
@@ -48,9 +53,17 @@ async fn test_transcription_accuracy() {
// Add more test cases as needed
];
- let whisper_model = Arc::new(Mutex::new(
- WhisperModel::new(&AudioTranscriptionEngine::WhisperLargeV3Turbo).unwrap(),
- ));
+ let context_params =
+ create_whisper_context_parameters(Arc::new(AudioTranscriptionEngine::WhisperTinyQuantized))
+ .unwrap();
+
+ let quantized_path =
+ download_whisper_model(Arc::new(AudioTranscriptionEngine::WhisperTinyQuantized)).unwrap();
+ let whisper_context = Arc::new(
+ WhisperContext::new_with_params(&quantized_path.to_string_lossy(), context_params)
+ .expect("failed to load model"),
+ );
+
let vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>> =
Arc::new(Mutex::new(Box::new(SileroVad::new().await.unwrap())));
@@ -72,7 +85,7 @@ async fn test_transcription_accuracy() {
));
for (audio_file, expected_transcription) in test_cases {
- let whisper_model = Arc::clone(&whisper_model);
+ let whisper_context = whisper_context.clone();
let vad_engine = Arc::clone(&vad_engine);
let embedding_extractor = Arc::clone(&embedding_extractor);
@@ -88,14 +101,14 @@ async fn test_transcription_accuracy() {
data: Arc::new(audio_data.0),
sample_rate: 44100, // hardcoded based on test data sample rate
channels: 1,
- device: Arc::new(screenpipe_audio::default_input_device().unwrap()),
+ device: Arc::new(default_input_device().unwrap()),
};
- let audio_data = if audio_input.sample_rate != whisper::SAMPLE_RATE as u32 {
+ let audio_data = if audio_input.sample_rate != SAMPLE_RATE {
match resample(
audio_input.data.as_ref(),
audio_input.sample_rate,
- whisper::SAMPLE_RATE as u32,
+ SAMPLE_RATE,
) {
Ok(data) => data,
Err(e) => {
@@ -116,7 +129,6 @@ async fn test_transcription_accuracy() {
)
.await
.unwrap();
- let mut whisper_model_guard = whisper_model.lock().await;
let mut transcription = String::new();
while let Some(segment) = segments.recv().await {
@@ -124,17 +136,16 @@ async fn test_transcription_accuracy() {
&segment.samples,
audio_input.sample_rate,
&audio_input.device.to_string(),
- &mut whisper_model_guard,
Arc::new(AudioTranscriptionEngine::WhisperLargeV3Turbo),
None,
vec![Language::English],
+ whisper_context.clone(),
)
.await
.unwrap();
transcription.push_str(&transcript);
}
- drop(whisper_model_guard);
let distance = levenshtein(expected_transcription, &transcription.to_lowercase());
let accuracy = 1.0 - (distance as f64 / expected_transcription.len() as f64);
diff --git a/screenpipe-audio/tests/core_tests.rs b/screenpipe-audio/tests/core_tests.rs
index f6fd445db..e53aad200 100644
--- a/screenpipe-audio/tests/core_tests.rs
+++ b/screenpipe-audio/tests/core_tests.rs
@@ -3,16 +3,20 @@ mod tests {
use anyhow::anyhow;
use chrono::Utc;
use log::{debug, LevelFilter};
- use screenpipe_audio::pyannote::embedding::EmbeddingExtractor;
- use screenpipe_audio::pyannote::identify::EmbeddingManager;
- use screenpipe_audio::stt::{prepare_segments, stt};
- use screenpipe_audio::vad_engine::{SileroVad, VadEngine, VadEngineEnum, VadSensitivity};
- use screenpipe_audio::whisper::WhisperModel;
- use screenpipe_audio::{
- default_output_device, list_audio_devices, pcm_decode, AudioInput, AudioStream,
- AudioTranscriptionEngine,
+ use screenpipe_audio::core::device::{
+ default_input_device, default_output_device, list_audio_devices, parse_audio_device,
};
- use screenpipe_audio::{parse_audio_device, record_and_transcribe};
+ use screenpipe_audio::core::engine::AudioTranscriptionEngine;
+ use screenpipe_audio::core::record_and_transcribe;
+ use screenpipe_audio::core::stream::AudioStream;
+ use screenpipe_audio::speaker::embedding::EmbeddingExtractor;
+ use screenpipe_audio::speaker::embedding_manager::EmbeddingManager;
+ use screenpipe_audio::speaker::prepare_segments;
+ use screenpipe_audio::transcription::whisper::model::{
+ create_whisper_context_parameters, download_whisper_model,
+ };
+ use screenpipe_audio::vad::{silero::SileroVad, VadEngine};
+ use screenpipe_audio::{pcm_decode, stt, AudioInput};
use screenpipe_core::Language;
use std::path::{Path, PathBuf};
use std::process::Command;
@@ -21,6 +25,7 @@ mod tests {
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
+ use whisper_rs::WhisperContext;
fn setup() {
// Initialize the logger with an info level filter
@@ -67,8 +72,13 @@ mod tests {
// Act
let start_time = Instant::now();
println!("Starting record_and_transcribe");
- let result =
- record_and_transcribe(Arc::new(audio_stream), duration, sender, is_running).await;
+ let result = record_and_transcribe(
+ Arc::new(audio_stream),
+ duration,
+ Arc::new(sender),
+ is_running,
+ )
+ .await;
println!("record_and_transcribe completed");
let elapsed_time = start_time.elapsed();
@@ -128,9 +138,14 @@ mod tests {
// Act
let start_time = Instant::now();
- record_and_transcribe(Arc::new(audio_stream), duration, sender, is_running)
- .await
- .unwrap();
+ record_and_transcribe(
+ Arc::new(audio_stream),
+ duration,
+ Arc::new(sender),
+ is_running,
+ )
+ .await
+ .unwrap();
let elapsed_time = start_time.elapsed();
@@ -193,108 +208,21 @@ mod tests {
#[tokio::test]
#[ignore]
- async fn test_audio_transcription() {
+ async fn test_audio_transcription_language() {
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?
+ let engine = Arc::new(AudioTranscriptionEngine::WhisperLargeV3TurboQuantized);
// Setup
- let device_spec = Arc::new(default_output_device().unwrap());
- let output_path =
- PathBuf::from(format!("test_output_{}.mp4", Utc::now().timestamp_millis()));
- let output_path_2 = output_path.clone();
- let (whisper_sender, whisper_receiver, _) = create_whisper_channel(
- Arc::new(AudioTranscriptionEngine::WhisperTiny),
- VadEngineEnum::WebRtc,
- None,
- &output_path_2.clone(),
- VadSensitivity::High,
- vec![],
- None,
- )
- .await
- .unwrap();
- let is_running = Arc::new(AtomicBool::new(true));
- // Start recording in a separate thread
- let recording_thread = tokio::spawn(async move {
- let device_spec = Arc::clone(&device_spec);
- let whisper_sender = whisper_sender.clone();
- let audio_stream = AudioStream::from_device(device_spec, is_running.clone())
- .await
- .unwrap();
-
- record_and_transcribe(
- Arc::new(audio_stream),
- Duration::from_secs(15),
- whisper_sender,
- is_running,
- )
- .await
- .unwrap();
- });
+ let context_params = create_whisper_context_parameters(engine.clone()).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.try_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
- recording_thread.abort();
- std::fs::remove_file(output_path_2).unwrap_or_default();
- }
-
- #[tokio::test]
- #[ignore]
- async fn test_audio_transcription_language() {
- setup();
- use std::sync::Arc;
+ let quantized_path = download_whisper_model(engine).unwrap();
+ let whisper_context = Arc::new(
+ WhisperContext::new_with_params(&quantized_path.to_string_lossy(), context_params)
+ .expect("failed to load model"),
+ );
- // Setup
- let whisper_model = Arc::new(tokio::sync::Mutex::new(
- WhisperModel::new(&AudioTranscriptionEngine::WhisperLargeV3Turbo).unwrap(),
- ));
let vad_engine: Arc<tokio::sync::Mutex<Box<dyn VadEngine + Send>>> = Arc::new(
tokio::sync::Mutex::new(Box::new(SileroVad::new().await.unwrap())),
);
@@ -305,7 +233,7 @@ mod tests {
data: Arc::new(audio_data.0),
sample_rate: 44100, // hardcoded based on test data sample rate
channels: 1,
- device: Arc::new(screenpipe_audio::default_input_device().unwrap()),
+ device: Arc::new(default_input_device().unwrap()),
};
// Create the missing parameters
@@ -340,7 +268,6 @@ mod tests {
)
.await
.unwrap();
- let mut whisper_model_guard = whisper_model.lock().await;
let mut transcription_result = String::new();
while let Some(segment) = segments.recv().await {
@@ -348,10 +275,10 @@ mod tests {
&segment.samples,
audio_input.sample_rate,
&audio_input.device.to_string(),
- &mut whisper_model_guard,
Arc::new(AudioTranscriptionEngine::WhisperLargeV3Turbo),
None,
vec![Language::Arabic],
+ whisper_context.clone(),
)
.await
.unwrap();
@@ -359,7 +286,6 @@ mod tests {
transcription_result.push_str(&transcript);
transcription_result.push('\n');
}
- drop(whisper_model_guard);
debug!("Received transcription: {:?}", transcription_result);
// Check if we received a valid transcription
@@ -415,9 +341,16 @@ mod tests {
let embedding_manager = EmbeddingManager::new(usize::MAX);
- // Initialize the WhisperModel
- let mut whisper_model = WhisperModel::new(&AudioTranscriptionEngine::WhisperLargeV3Turbo)
- .expect("Failed to initialize WhisperModel");
+ let engine = Arc::new(AudioTranscriptionEngine::WhisperLargeV3TurboQuantized);
+
+ // Setup
+ let context_params = create_whisper_context_parameters(engine.clone()).unwrap();
+
+ let quantized_path = download_whisper_model(engine).unwrap();
+ let whisper_context = Arc::new(
+ WhisperContext::new_with_params(&quantized_path.to_string_lossy(), context_params)
+ .expect("failed to load model"),
+ );
// Initialize VAD engine
let vad_engine: Box<dyn VadEngine + Send> = Box::new(SileroVad::new().await.unwrap());
@@ -443,10 +376,10 @@ mod tests {
&segment.samples,
audio_input.sample_rate,
&audio_input.device.to_string(),
- &mut whisper_model,
Arc::new(AudioTranscriptionEngine::WhisperLargeV3Turbo),
None,
vec![Language::English],
+ whisper_context.clone(),
)
.await
.unwrap();
diff --git a/screenpipe-audio/tests/realtime_test.rs b/screenpipe-audio/tests/realtime_test.rs
index 7706a1976..a5e4163b5 100644
--- a/screenpipe-audio/tests/realtime_test.rs
+++ b/screenpipe-audio/tests/realtime_test.rs
@@ -1,7 +1,9 @@
use futures::StreamExt;
-use screenpipe_audio::realtime::RealtimeTranscriptionEvent;
-use screenpipe_audio::{deepgram::start_deepgram_stream, AudioDevice};
-use screenpipe_audio::{pcm_decode, DeviceType};
+use screenpipe_audio::core::device::AudioDevice;
+use screenpipe_audio::core::device::DeviceType;
+use screenpipe_audio::pcm_decode;
+use screenpipe_audio::transcription::deepgram::streaming::start_deepgram_stream;
+use screenpipe_audio::transcription::deepgram::streaming::RealtimeTranscriptionEvent;
use screenpipe_events::subscribe_to_event;
use std::{
sync::{atomic::AtomicBool, Arc},
diff --git a/screenpipe-audio/tests/speaker_identification.rs b/screenpipe-audio/tests/speaker_identification.rs
index 219964371..0650ce984 100644
--- a/screenpipe-audio/tests/speaker_identification.rs
+++ b/screenpipe-audio/tests/speaker_identification.rs
@@ -1,6 +1,8 @@
mod tests {
use log::LevelFilter;
- use screenpipe_audio::pyannote::segment::get_segments;
+ use screenpipe_audio::speaker::embedding::EmbeddingExtractor;
+ use screenpipe_audio::speaker::embedding_manager::EmbeddingManager;
+ use screenpipe_audio::speaker::segment::get_segments;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
@@ -31,16 +33,15 @@ mod tests {
.join("segmentation-3.0.onnx");
let embedding_extractor = Arc::new(Mutex::new(
- screenpipe_audio::pyannote::embedding::EmbeddingExtractor::new(
+ EmbeddingExtractor::new(
embedding_model_path
.to_str()
.ok_or_else(|| anyhow::anyhow!("Invalid embedding model path"))
.unwrap(),
)
- .unwrap()
+ .unwrap(),
));
- let embedding_manager =
- screenpipe_audio::pyannote::identify::EmbeddingManager::new(usize::MAX);
+ let embedding_manager = EmbeddingManager::new(usize::MAX);
let multiple_speakers_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("test_data/speaker_identification/6_speakers.wav");
diff --git a/screenpipe-audio/tests/windows_output_device_tests.rs b/screenpipe-audio/tests/windows_output_device_tests.rs
index af4bdd71d..4675ae396 100644
--- a/screenpipe-audio/tests/windows_output_device_tests.rs
+++ b/screenpipe-audio/tests/windows_output_device_tests.rs
@@ -1,7 +1,7 @@
#[cfg(target_os = "windows")]
#[cfg(test)]
mod tests {
- use screenpipe_audio::{list_audio_devices, record_and_transcribe, AudioInput};
+ use screenpipe_audio::{core::device::list_audio_devices, record_and_transcribe, AudioInput};
use std::{
path::PathBuf,
@@ -15,7 +15,7 @@ mod tests {
let devices = list_audio_devices().await?;
let virtual_device = match devices.iter().find(|d| d.name.contains("CABLE Output")) {
Some(device) => device,
- None => return Ok(()), // Silently return if device not found
+ None => return Ok(()), // Silently return if device not found
};
println!("Found virtual device: {:?}", virtual_device.name);
@@ -26,7 +26,7 @@ mod tests {
let (tx, _rx): (
crossbeam::channel::Sender<AudioInput>,
crossbeam::channel::Receiver<AudioInput>,
- ) = crossbeam::channel::bounded(100);
+ ) = crossbeam::channel::bounded(100);
let is_running = Arc::new(AtomicBool::new(true));
// Record from the virtual device
diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.toml
index fc461ba6d..cd467cbdf 100644
--- a/screenpipe-core/Cargo.toml
+++ b/screenpipe-core/Cargo.toml
@@ -47,7 +47,6 @@ cron = "0.13.0"
chrono = "0.4.38"
sentry = { workspace = true }
zip = "0.6.2"
-tokio-stream = "0.1.17"
[dev-dependencies]
reqwest = { workspace = true }
diff --git a/screenpipe-core/src/devices.rs b/screenpipe-core/src/devices.rs
deleted file mode 100644
index febb06257..000000000
--- a/screenpipe-core/src/devices.rs
+++ /dev/null
@@ -1,278 +0,0 @@
-use std::{collections::HashMap, fmt, str::FromStr};
-
-use anyhow::anyhow;
-use serde::{Deserialize, Serialize};
-use tokio_stream::Stream;
-use tracing::debug;
-
-#[derive(Clone, Debug)]
-pub enum DeviceType {
- Audio(AudioDevice),
- Vision(u32), // monitor_id
-}
-
-impl DeviceType {
- pub fn is_vision(&self) -> bool {
- matches!(self, DeviceType::Vision(_))
- }
-
- pub fn is_audio(&self) -> bool {
- matches!(self, DeviceType::Audio(_))
- }
-}
-
-impl fmt::Display for DeviceType {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- DeviceType::Audio(audio_device) => write!(f, "{}", audio_device),
- DeviceType::Vision(monitor_id) => write!(f, "{}", monitor_id),
- }
- }
-}
-
-impl FromStr for DeviceType {
- type Err = anyhow::Error;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- // Check if it's a monitor ID (vision device)
- if let Ok(monitor_id) = s.parse::<u32>() {
- return Ok(DeviceType::Vision(monitor_id));
- }
-
- // Otherwise try to parse as audio device
- match AudioDevice::from_name(s) {
- Ok(audio_device) => Ok(DeviceType::Audio(audio_device)),
- Err(e) => Err(anyhow!("Failed to parse device string '{}': {}", s, e)),
- }
- }
-}
-
-#[derive(Clone, Debug)]
-pub struct DeviceControl {
- pub device: DeviceType,
- pub is_running: bool,
- pub is_paused: bool,
-}
-
-impl Default for DeviceControl {
- fn default() -> Self {
- Self {
- device: DeviceType::Audio(AudioDevice::new(
- "default".to_string(),
- AudioDeviceType::Input,
- )),
- is_running: false,
- is_paused: false,
- }
- }
-}
-
-#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug, Deserialize)]
-pub enum AudioDeviceType {
- Input,
- Output,
-}
-
-#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug)]
-pub struct AudioDevice {
- pub name: String,
- pub device_type: AudioDeviceType,
-}
-
-impl AudioDevice {
- pub fn new(name: String, device_type: AudioDeviceType) -> Self {
- AudioDevice { name, device_type }
- }
-
- pub fn from_name(name: &str) -> anyhow::Result<Self> {
- if name.trim().is_empty() {
- return Err(anyhow!("Device name cannot be empty"));
- }
-
- let (name, device_type) = if name.to_lowercase().ends_with("(input)") {
- (
- name.trim_end_matches("(input)").trim().to_string(),
- AudioDeviceType::Input,
- )
- } else if name.to_lowercase().ends_with("(output)") {
- (
- name.trim_end_matches("(output)").trim().to_string(),
- AudioDeviceType::Output,
- )
- } else {
- return Err(anyhow!(
- "Device type (input/output) not specified in the name"
- ));
- };
-
- Ok(AudioDevice::new(name, device_type))
- }
-}
-
-impl fmt::Display for AudioDevice {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(
- f,
- "{} ({})",
- self.name,
- match self.device_type {
- AudioDeviceType::Input => "input",
- AudioDeviceType::Output => "output",
- }
- )
- }
-}
-
-pub struct DeviceManager {
- sender: tokio::sync::broadcast::Sender<DeviceControl>,
- #[allow(dead_code)]
- _dummy: tokio::sync::broadcast::Receiver<DeviceControl>,
- state_sender: tokio::sync::mpsc::Sender<DeviceStateRequest>,
-}
-
-impl Clone for DeviceManager {
- fn clone(&self) -> Self {
- DeviceManager {
- sender: self.sender.clone(),
- _dummy: self.sender.subscribe(),
- state_sender: self.state_sender.clone(),
- }
- }
-}
-
-impl Drop for DeviceManager {
- fn drop(&mut self) {
- if self.state_sender.is_closed() {
- debug!("cleaning up device manager resources");
- }
- }
-}
-
-#[derive(Debug)]
-enum DeviceStateRequest {
- Get {
- respond_to: tokio::sync::oneshot::Sender<HashMap<String, DeviceControl>>,
- },
- Update(DeviceControl),
- Watch {
- respond_to: tokio::sync::mpsc::Sender<DeviceStateChange>,
- },
-}
-
-#[derive(Debug, Clone)]
-pub struct DeviceStateChange {
- pub device: String,
- pub control: DeviceControl,
-}
-
-impl Default for DeviceManager {
- fn default() -> Self {
- let (sender, dummy_receiver) = tokio::sync::broadcast::channel(32);
- let (state_sender, state_receiver) = tokio::sync::mpsc::channel(32);
-
- tokio::spawn(async move {
- Self::manage_state(state_receiver).await;
- });
-
- Self {
- sender,
- _dummy: dummy_receiver,
- state_sender,
- }
- }
-}
-
-impl DeviceManager {
- async fn manage_state(mut receiver: tokio::sync::mpsc::Receiver<DeviceStateRequest>) {
- let mut devices = HashMap::new();
- let mut watchers = Vec::new();
-
- while let Some(req) = receiver.recv().await {
- watchers.retain(|watcher: &tokio::sync::mpsc::Sender<DeviceStateChange>| {
- !watcher.is_closed()
- });
-
- debug!(
- "received device_state_request: {:?} watches length: {}",
- req,
- watchers.len()
- );
- match req {
- DeviceStateRequest::Get { respond_to } => {
- debug!("sending get request to {} devices", devices.len());
- let _ = respond_to.send(devices.clone());
- }
- DeviceStateRequest::Update(control) => {
- let device_id = control.device.to_string();
- let changed = devices
- .get(&device_id)
- .map_or(true, |current| current.is_running != control.is_running);
-
- if changed {
- debug!(
- "updating device '{}' with new control state: {:?}",
- device_id, control
- );
- debug!("notifying watchers of the change: {:?}", watchers);
- devices.insert(device_id.clone(), control.clone());
-
- // Notify watchers of the change
- watchers.retain(
- |watcher: &tokio::sync::mpsc::Sender<DeviceStateChange>| {
- watcher
- .try_send(DeviceStateChange {
- device: device_id.clone(),
- control: control.clone(),
- })
- .is_ok()
- },
- );
- }
- }
- DeviceStateRequest::Watch { respond_to } => {
- debug!("adding a new watcher");
- watchers.push(respond_to);
- }
- }
- }
- }
-
- pub async fn get_active_devices(&self) -> HashMap<String, DeviceControl> {
- let (tx, rx) = tokio::sync::oneshot::channel();
- self.state_sender
- .send(DeviceStateRequest::Get { respond_to: tx })
- .await
- .expect("state manager task has terminated");
- rx.await
- .unwrap_or_default()
- .into_iter()
- .filter(|(_, control)| control.is_running)
- .collect()
- }
-
- pub async fn watch_devices(&self) -> impl Stream<Item = DeviceStateChange> {
- let (tx, rx) = tokio::sync::mpsc::channel(32);
- self.state_sender
- .send(DeviceStateRequest::Watch { respond_to: tx })
- .await
- .expect("state manager task has terminated");
- tokio_stream::wrappers::ReceiverStream::new(rx)
- }
-
- pub async fn update_device(&self, control: DeviceControl) -> anyhow::Result<()> {
- self.state_sender
- .send(DeviceStateRequest::Update(control.clone()))
- .await?;
- self.sender.send(control)?;
- Ok(())
- }
-
- pub async fn shutdown(&self) {
- for device in self.get_active_devices().await.values_mut() {
- device.is_running = false;
- if !self.state_sender.is_closed() {
- self.update_device(device.clone()).await.unwrap();
- }
- }
- }
-}
diff --git a/screenpipe-core/src/lib.rs b/screenpipe-core/src/lib.rs
index ed3d699d3..505927844 100644
--- a/screenpipe-core/src/lib.rs
+++ b/screenpipe-core/src/lib.rs
@@ -36,9 +36,4 @@ pub mod network;
pub use network::*;
pub use language::{Language, TESSERACT_LANGUAGES};
-
-pub mod devices;
-pub use devices::*;
-
pub mod embedding;
-pub use embedding::*;
diff --git a/screenpipe-db/Cargo.toml b/screenpipe-db/Cargo.toml
new file mode 100644
index 000000000..ca1e1921c
--- /dev/null
+++ b/screenpipe-db/Cargo.toml
@@ -0,0 +1,43 @@
+[package]
+name = "screenpipe-db"
+version.workspace = true
+authors.workspace = true
+description.workspace = true
+repository.workspace = true
+license.workspace = true
+edition.workspace = true
+
+[dependencies]
+chrono = { version = "0.4.31", features = ["serde"] }
+image = { workspace = true }
+sqlx = { version = "0.7", features = [
+ "sqlite",
+ "runtime-tokio-native-tls",
+ "chrono",
+ "migrate",
+] }
+sqlite-vec = "0.1.3"
+libsqlite3-sys = { version = "0.26", features = ["bundled"] }
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+futures = { version = "0.3.31", features = ["std"] }
+
+zerocopy = { version = "0.7.32" }
+
+tokio-util = { version = "0.7", features = ["io"] }
+tokio = { version = "1.15", features = ["full", "tracing"] }
+
+tracing = { workspace = true }
+anyhow = "1.0.86"
+rand = "0.8.5"
+criterion = { workspace = true }
+oasgen = { workspace = true }
+tracing-subscriber = { workspace = true }
+
+[[bench]]
+name = "db_benchmarks"
+harness = false
+
+[[bench]]
+name = "new_db_benchmark"
+harness = false
diff --git a/screenpipe-server/benches/db_benchmarks.rs b/screenpipe-db/benches/db_benchmarks.rs
similarity index 86%
rename from screenpipe-server/benches/db_benchmarks.rs
rename to screenpipe-db/benches/db_benchmarks.rs
index 843337a6c..8264f58e1 100644
--- a/screenpipe-server/benches/db_benchmarks.rs
+++ b/screenpipe-db/benches/db_benchmarks.rs
@@ -2,9 +2,7 @@
use criterion::{criterion_group, criterion_main, Criterion};
use rand::Rng;
-use screenpipe_audio::AudioDevice;
-use screenpipe_server::{db_types::ContentType, DatabaseManager};
-use screenpipe_vision::OcrEngine;
+use screenpipe_db::{AudioDevice, ContentType, DatabaseManager, DeviceType, OcrEngine};
use std::sync::Arc;
use tokio::runtime::Runtime;
@@ -17,17 +15,17 @@ async fn setup_large_db(size: usize) -> DatabaseManager {
.insert_video_chunk("test_video.mp4", "test_device")
.await
.unwrap();
- let frame_id = db.insert_frame("test_device", None, None).await.unwrap();
+ let frame_id = db
+ .insert_frame("test_device", None, None, None, None, false)
+ .await
+ .unwrap();
let ocr_text = format!("OCR text {}", rng.gen::<u32>());
let text_json = format!(r#"{{"text": "{}"}}"#, ocr_text);
db.insert_ocr_text(
frame_id,
&ocr_text,
&text_json,
- "test_app",
- "test_window",
Arc::new(OcrEngine::default()), // Assuming a default implementation
- false,
)
.await
.unwrap();
@@ -39,10 +37,10 @@ async fn setup_large_db(size: usize) -> DatabaseManager {
&audio_text,
0,
"test_engine",
- &AudioDevice::new(
- "test_device".to_string(),
- screenpipe_audio::DeviceType::Input,
- ),
+ &AudioDevice {
+ name: "test_device".to_string(),
+ device_type: DeviceType::Input,
+ },
None,
None,
None,
@@ -86,6 +84,8 @@ fn bench_search(c: &mut Criterion) {
None,
None,
None,
+ None,
+ None,
)
.await
.unwrap()
diff --git a/screenpipe-server/benches/new_db_benchmark.rs b/screenpipe-db/benches/new_db_benchmark.rs
similarity index 81%
rename from screenpipe-server/benches/new_db_benchmark.rs
rename to screenpipe-db/benches/new_db_benchmark.rs
index a4f85d73c..efd7f71ff 100644
--- a/screenpipe-server/benches/new_db_benchmark.rs
+++ b/screenpipe-db/benches/new_db_benchmark.rs
@@ -1,6 +1,5 @@
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
-use screenpipe_server::DatabaseManager;
-use screenpipe_vision::OcrEngine;
+use screenpipe_db::{DatabaseManager, OcrEngine};
use std::time::Duration;
use tokio::runtime::Runtime;
@@ -36,22 +35,11 @@ fn bench_insert_ocr_text(c: &mut Criterion) {
let text = black_box(i);
let text_json =
black_box(format!("{{\"text\": \"{}\"}}", text.replace("\"", "\\\"")));
- let app_name = black_box("BenchmarkApp");
- let window_name = black_box("BenchmarkWindow");
let ocr_engine = black_box(OcrEngine::AppleNative);
- let focused = black_box(true);
-
- db.insert_ocr_text(
- frame_id,
- text,
- &text_json,
- app_name,
- window_name,
- std::sync::Arc::new(ocr_engine),
- focused,
- )
- .await
- .unwrap();
+
+ db.insert_ocr_text(frame_id, text, &text_json, std::sync::Arc::new(ocr_engine))
+ .await
+ .unwrap();
})
});
}
diff --git a/screenpipe-server/src/db.rs b/screenpipe-db/src/db.rs
similarity index 99%
rename from screenpipe-server/src/db.rs
rename to screenpipe-db/src/db.rs
index d64f0e4a3..978f07cd8 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-db/src/db.rs
@@ -1,8 +1,6 @@
use chrono::{DateTime, Utc};
use image::DynamicImage;
use libsqlite3_sys::sqlite3_auto_extension;
-use screenpipe_audio::{AudioDevice, DeviceType};
-use screenpipe_vision::OcrEngine;
use sqlite_vec::sqlite3_vec_init;
use sqlx::migrate::MigrateDatabase;
use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};
@@ -19,17 +17,15 @@ use std::collections::BTreeMap;
use zerocopy::AsBytes;
-use crate::db_types::{
- AudioChunksResponse, AudioEntry, AudioResult, AudioResultRaw, FrameData, FrameRow, OCREntry,
- OCRResult, OCRResultRaw, OcrTextBlock, Order, SearchMatch, Speaker, TagContentType, TextBounds,
- TextPosition,
-};
-use crate::db_types::{ContentType, UiContent};
-use crate::db_types::{SearchResult, TimeSeriesChunk};
-use crate::video_utils::VideoMetadata;
-
use futures::future::try_join_all;
+use crate::{
+ AudioChunksResponse, AudioDevice, AudioEntry, AudioResult, AudioResultRaw, ContentType,
+ DeviceType, FrameData, FrameRow, OCREntry, OCRResult, OCRResultRaw, OcrEngine, OcrTextBlock,
+ Order, SearchMatch, SearchResult, Speaker, TagContentType, TextBounds, TextPosition,
+ TimeSeriesChunk, UiContent, VideoMetadata,
+};
+
pub struct DatabaseManager {
pub pool: SqlitePool,
}
@@ -985,7 +981,6 @@ impl DatabaseManager {
browser_url: Option<&str>,
focused: Option<bool>,
) -> Result<usize, sqlx::Error> {
-
// if focused or browser_url is present, we run only on OCR
if focused.is_some() || browser_url.is_some() {
content_type = ContentType::OCR;
diff --git a/screenpipe-db/src/lib.rs b/screenpipe-db/src/lib.rs
new file mode 100644
index 000000000..79da9ff34
--- /dev/null
+++ b/screenpipe-db/src/lib.rs
@@ -0,0 +1,11 @@
+mod db;
+mod migration_worker;
+mod types;
+mod video_db;
+
+pub use db::DatabaseManager;
+pub use migration_worker::{
+ create_migration_worker, MigrationCommand, MigrationConfig, MigrationResponse, MigrationStatus,
+ MigrationWorker,
+};
+pub use types::*;
diff --git a/screenpipe-server/src/migration_worker.rs b/screenpipe-db/src/migration_worker.rs
similarity index 100%
rename from screenpipe-server/src/migration_worker.rs
rename to screenpipe-db/src/migration_worker.rs
diff --git a/screenpipe-server/src/migrations/20240703111257_screenpipe.sql b/screenpipe-db/src/migrations/20240703111257_screenpipe.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240703111257_screenpipe.sql
rename to screenpipe-db/src/migrations/20240703111257_screenpipe.sql
diff --git a/screenpipe-server/src/migrations/20240715121444_indexes.sql b/screenpipe-db/src/migrations/20240715121444_indexes.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240715121444_indexes.sql
rename to screenpipe-db/src/migrations/20240715121444_indexes.sql
diff --git a/screenpipe-server/src/migrations/20240716120000_add_fields_to_ocr_text.sql b/screenpipe-db/src/migrations/20240716120000_add_fields_to_ocr_text.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240716120000_add_fields_to_ocr_text.sql
rename to screenpipe-db/src/migrations/20240716120000_add_fields_to_ocr_text.sql
diff --git a/screenpipe-server/src/migrations/20240716120001_update_ocr_text_table.sql b/screenpipe-db/src/migrations/20240716120001_update_ocr_text_table.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240716120001_update_ocr_text_table.sql
rename to screenpipe-db/src/migrations/20240716120001_update_ocr_text_table.sql
diff --git a/screenpipe-server/src/migrations/20240716120002_snake_case.sql b/screenpipe-db/src/migrations/20240716120002_snake_case.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240716120002_snake_case.sql
rename to screenpipe-db/src/migrations/20240716120002_snake_case.sql
diff --git a/screenpipe-server/src/migrations/20240716120003_add_timestampt_to_audio_chunks.sql b/screenpipe-db/src/migrations/20240716120003_add_timestampt_to_audio_chunks.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240716120003_add_timestampt_to_audio_chunks.sql
rename to screenpipe-db/src/migrations/20240716120003_add_timestampt_to_audio_chunks.sql
diff --git a/screenpipe-server/src/migrations/20240716120004_app_name.sql b/screenpipe-db/src/migrations/20240716120004_app_name.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240716120004_app_name.sql
rename to screenpipe-db/src/migrations/20240716120004_app_name.sql
diff --git a/screenpipe-server/src/migrations/20240805120005_V2_create_inverted_index_table.sql b/screenpipe-db/src/migrations/20240805120005_V2_create_inverted_index_table.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240805120005_V2_create_inverted_index_table.sql
rename to screenpipe-db/src/migrations/20240805120005_V2_create_inverted_index_table.sql
diff --git a/screenpipe-server/src/migrations/20240808120006_V2_add_transcription_engine.sql b/screenpipe-db/src/migrations/20240808120006_V2_add_transcription_engine.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240808120006_V2_add_transcription_engine.sql
rename to screenpipe-db/src/migrations/20240808120006_V2_add_transcription_engine.sql
diff --git a/screenpipe-server/src/migrations/20240808120007_V2_add_friends_request_table.sql b/screenpipe-db/src/migrations/20240808120007_V2_add_friends_request_table.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240808120007_V2_add_friends_request_table.sql
rename to screenpipe-db/src/migrations/20240808120007_V2_add_friends_request_table.sql
diff --git a/screenpipe-server/src/migrations/20240808120008_V2_remove_fields.sql b/screenpipe-db/src/migrations/20240808120008_V2_remove_fields.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240808120008_V2_remove_fields.sql
rename to screenpipe-db/src/migrations/20240808120008_V2_remove_fields.sql
diff --git a/screenpipe-server/src/migrations/20240808120009_remove_columns_from_ocr_text.sql b/screenpipe-db/src/migrations/20240808120009_remove_columns_from_ocr_text.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240808120009_remove_columns_from_ocr_text.sql
rename to screenpipe-db/src/migrations/20240808120009_remove_columns_from_ocr_text.sql
diff --git a/screenpipe-server/src/migrations/20240808120010_create_unique_index_on_chunked_text_index.sql b/screenpipe-db/src/migrations/20240808120010_create_unique_index_on_chunked_text_index.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240808120010_create_unique_index_on_chunked_text_index.sql
rename to screenpipe-db/src/migrations/20240808120010_create_unique_index_on_chunked_text_index.sql
diff --git a/screenpipe-server/src/migrations/20240811010614_add_fields_to_friend_wearable_requests.sql b/screenpipe-db/src/migrations/20240811010614_add_fields_to_friend_wearable_requests.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240811010614_add_fields_to_friend_wearable_requests.sql
rename to screenpipe-db/src/migrations/20240811010614_add_fields_to_friend_wearable_requests.sql
diff --git a/screenpipe-server/src/migrations/20240812202755_add_is_successful_to_friend_wearable_requests.sql b/screenpipe-db/src/migrations/20240812202755_add_is_successful_to_friend_wearable_requests.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240812202755_add_is_successful_to_friend_wearable_requests.sql
rename to screenpipe-db/src/migrations/20240812202755_add_is_successful_to_friend_wearable_requests.sql
diff --git a/screenpipe-server/src/migrations/20240812205501_add_fts_index.sql b/screenpipe-db/src/migrations/20240812205501_add_fts_index.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240812205501_add_fts_index.sql
rename to screenpipe-db/src/migrations/20240812205501_add_fts_index.sql
diff --git a/screenpipe-server/src/migrations/20240815201445_add_window_name_to_ocr_text.sql b/screenpipe-db/src/migrations/20240815201445_add_window_name_to_ocr_text.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240815201445_add_window_name_to_ocr_text.sql
rename to screenpipe-db/src/migrations/20240815201445_add_window_name_to_ocr_text.sql
diff --git a/screenpipe-server/src/migrations/20240815214646_remove_app_name_from_frames.sql b/screenpipe-db/src/migrations/20240815214646_remove_app_name_from_frames.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240815214646_remove_app_name_from_frames.sql
rename to screenpipe-db/src/migrations/20240815214646_remove_app_name_from_frames.sql
diff --git a/screenpipe-server/src/migrations/20240815215557_add_focused_to_ocr_text.sql b/screenpipe-db/src/migrations/20240815215557_add_focused_to_ocr_text.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240815215557_add_focused_to_ocr_text.sql
rename to screenpipe-db/src/migrations/20240815215557_add_focused_to_ocr_text.sql
diff --git a/screenpipe-server/src/migrations/20240821074222_create_tags.sql b/screenpipe-db/src/migrations/20240821074222_create_tags.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240821074222_create_tags.sql
rename to screenpipe-db/src/migrations/20240821074222_create_tags.sql
diff --git a/screenpipe-server/src/migrations/20240917213422_add_device_info_to_audio_transcriptions.sql b/screenpipe-db/src/migrations/20240917213422_add_device_info_to_audio_transcriptions.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20240917213422_add_device_info_to_audio_transcriptions.sql
rename to screenpipe-db/src/migrations/20240917213422_add_device_info_to_audio_transcriptions.sql
diff --git a/screenpipe-server/src/migrations/20241024181218_add_device_name_to_chunks.sql b/screenpipe-db/src/migrations/20241024181218_add_device_name_to_chunks.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241024181218_add_device_name_to_chunks.sql
rename to screenpipe-db/src/migrations/20241024181218_add_device_name_to_chunks.sql
diff --git a/screenpipe-server/src/migrations/20241103222151_timeline_indexes.sql b/screenpipe-db/src/migrations/20241103222151_timeline_indexes.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241103222151_timeline_indexes.sql
rename to screenpipe-db/src/migrations/20241103222151_timeline_indexes.sql
diff --git a/screenpipe-server/src/migrations/20241106031800_create_ui_monitoring.sql b/screenpipe-db/src/migrations/20241106031800_create_ui_monitoring.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241106031800_create_ui_monitoring.sql
rename to screenpipe-db/src/migrations/20241106031800_create_ui_monitoring.sql
diff --git a/screenpipe-server/src/migrations/20241108202826_create_speaker_table.sql b/screenpipe-db/src/migrations/20241108202826_create_speaker_table.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241108202826_create_speaker_table.sql
rename to screenpipe-db/src/migrations/20241108202826_create_speaker_table.sql
diff --git a/screenpipe-server/src/migrations/20241127172038_create_speaker_id_col_final.sql b/screenpipe-db/src/migrations/20241127172038_create_speaker_id_col_final.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241127172038_create_speaker_id_col_final.sql
rename to screenpipe-db/src/migrations/20241127172038_create_speaker_id_col_final.sql
diff --git a/screenpipe-server/src/migrations/20241127220428_add_hallucination_column.sql b/screenpipe-db/src/migrations/20241127220428_add_hallucination_column.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241127220428_add_hallucination_column.sql
rename to screenpipe-db/src/migrations/20241127220428_add_hallucination_column.sql
diff --git a/screenpipe-server/src/migrations/20241204191424_fts.sql b/screenpipe-db/src/migrations/20241204191424_fts.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241204191424_fts.sql
rename to screenpipe-db/src/migrations/20241204191424_fts.sql
diff --git a/screenpipe-server/src/migrations/20241207202831_add_speaker_id_to_fts.sql b/screenpipe-db/src/migrations/20241207202831_add_speaker_id_to_fts.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241207202831_add_speaker_id_to_fts.sql
rename to screenpipe-db/src/migrations/20241207202831_add_speaker_id_to_fts.sql
diff --git a/screenpipe-server/src/migrations/20241210111055_add_fts_update_delete_triggers.sql b/screenpipe-db/src/migrations/20241210111055_add_fts_update_delete_triggers.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241210111055_add_fts_update_delete_triggers.sql
rename to screenpipe-db/src/migrations/20241210111055_add_fts_update_delete_triggers.sql
diff --git a/screenpipe-server/src/migrations/20241210205142_fix_audio_transcriptions.sql b/screenpipe-db/src/migrations/20241210205142_fix_audio_transcriptions.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241210205142_fix_audio_transcriptions.sql
rename to screenpipe-db/src/migrations/20241210205142_fix_audio_transcriptions.sql
diff --git a/screenpipe-server/src/migrations/20241213220649_create_segment_start_time_and_end_time_columns.sql b/screenpipe-db/src/migrations/20241213220649_create_segment_start_time_and_end_time_columns.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20241213220649_create_segment_start_time_and_end_time_columns.sql
rename to screenpipe-db/src/migrations/20241213220649_create_segment_start_time_and_end_time_columns.sql
diff --git a/screenpipe-server/src/migrations/20250117134500_create_ocr_text_embeddings.sql b/screenpipe-db/src/migrations/20250117134500_create_ocr_text_embeddings.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20250117134500_create_ocr_text_embeddings.sql
rename to screenpipe-db/src/migrations/20250117134500_create_ocr_text_embeddings.sql
diff --git a/screenpipe-server/src/migrations/20250117180530_add_frame_names.sql b/screenpipe-db/src/migrations/20250117180530_add_frame_names.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20250117180530_add_frame_names.sql
rename to screenpipe-db/src/migrations/20250117180530_add_frame_names.sql
diff --git a/screenpipe-server/src/migrations/20250130101751_add_text_length_columns.sql b/screenpipe-db/src/migrations/20250130101751_add_text_length_columns.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20250130101751_add_text_length_columns.sql
rename to screenpipe-db/src/migrations/20250130101751_add_text_length_columns.sql
diff --git a/screenpipe-server/src/migrations/20250219212616_add-browser_url-column.sql b/screenpipe-db/src/migrations/20250219212616_add-browser_url-column.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20250219212616_add-browser_url-column.sql
rename to screenpipe-db/src/migrations/20250219212616_add-browser_url-column.sql
diff --git a/screenpipe-server/src/migrations/20250223204844_browser_url_fts_and_move_window_app_to_frames.sql b/screenpipe-db/src/migrations/20250223204844_browser_url_fts_and_move_window_app_to_frames.sql
similarity index 100%
rename from screenpipe-server/src/migrations/20250223204844_browser_url_fts_and_move_window_app_to_frames.sql
rename to screenpipe-db/src/migrations/20250223204844_browser_url_fts_and_move_window_app_to_frames.sql
diff --git a/screenpipe-server/src/db_types.rs b/screenpipe-db/src/types.rs
similarity index 85%
rename from screenpipe-server/src/db_types.rs
rename to screenpipe-db/src/types.rs
index 6af279d3b..6aadba36c 100644
--- a/screenpipe-server/src/db_types.rs
+++ b/screenpipe-db/src/types.rs
@@ -1,6 +1,5 @@
use chrono::{DateTime, Utc};
use oasgen::OaSchema;
-use screenpipe_audio::DeviceType;
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use std::error::Error as StdError;
@@ -108,6 +107,12 @@ pub struct Speaker {
pub metadata: String,
}
+#[derive(OaSchema, Clone, Eq, PartialEq, Hash, Serialize, Debug, Deserialize)]
+pub enum DeviceType {
+ Input,
+ Output,
+}
+
#[derive(OaSchema, Debug, Serialize, Deserialize)]
pub struct AudioResult {
pub audio_chunk_id: i64,
@@ -276,3 +281,45 @@ pub enum Order {
#[default]
Descending,
}
+
+#[derive(OaSchema, Debug, Clone, Serialize, Deserialize)]
+pub struct VideoMetadata {
+ pub creation_time: DateTime<Utc>,
+ pub fps: f64,
+ pub duration: f64,
+ pub device_name: Option<String>,
+ pub name: Option<String>,
+}
+
+#[derive(OaSchema, Clone, Eq, PartialEq, Hash, Serialize, Debug, Deserialize)]
+pub struct AudioDevice {
+ pub name: String,
+ pub device_type: DeviceType,
+}
+
+#[derive(OaSchema, Clone, Debug, Default, Serialize, Deserialize)]
+pub enum OcrEngine {
+ Unstructured,
+ #[default]
+ Tesseract,
+ WindowsNative,
+ AppleNative,
+ Custom(CustomOcrConfig),
+}
+
+#[derive(OaSchema, 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,
+ }
+ }
+}
diff --git a/screenpipe-server/src/video_db.rs b/screenpipe-db/src/video_db.rs
similarity index 100%
rename from screenpipe-server/src/video_db.rs
rename to screenpipe-db/src/video_db.rs
diff --git a/screenpipe-server/tests/db.rs b/screenpipe-db/tests/db.rs
similarity index 94%
rename from screenpipe-server/tests/db.rs
rename to screenpipe-db/tests/db.rs
index ae934508e..9f4150867 100644
--- a/screenpipe-server/tests/db.rs
+++ b/screenpipe-db/tests/db.rs
@@ -3,12 +3,9 @@ mod tests {
use std::sync::Arc;
use chrono::Utc;
- use screenpipe_audio::{AudioDevice, DeviceType};
- use screenpipe_server::{
- db_types::{ContentType, Frame, SearchResult},
- DatabaseManager,
+ use screenpipe_db::{
+ AudioDevice, ContentType, DatabaseManager, DeviceType, Frame, OcrEngine, SearchResult,
};
- use screenpipe_vision::OcrEngine;
async fn setup_test_db() -> DatabaseManager {
// Initialize tracing for debug output
@@ -89,7 +86,10 @@ mod tests {
"Hello from audio",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
None,
None,
None,
@@ -155,7 +155,10 @@ mod tests {
"Hello from audio",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
None,
None,
None,
@@ -267,7 +270,10 @@ mod tests {
"Hello from audio",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
None,
None,
None,
@@ -361,7 +367,10 @@ mod tests {
"Hello from audio 1",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
None,
None,
None,
@@ -427,7 +436,10 @@ mod tests {
"Hello from audio 2",
1,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
None,
None,
None,
@@ -610,7 +622,10 @@ mod tests {
"Hello from audio 1",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
None,
None,
None,
@@ -645,7 +660,10 @@ mod tests {
"Hello from audio 2",
1,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
None,
None,
None,
@@ -789,7 +807,10 @@ mod tests {
"test transcription",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
Some(speaker.id),
None,
None,
@@ -853,7 +874,10 @@ mod tests {
"test transcription",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
Some(speaker.id),
None,
None,
@@ -909,7 +933,10 @@ mod tests {
"test transcription",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
Some(speaker.id),
None,
None,
@@ -952,7 +979,10 @@ mod tests {
"test transcription",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
Some(speaker.id),
None,
None,
@@ -996,7 +1026,10 @@ mod tests {
"test transcription",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
Some(speaker.id),
None,
None,
@@ -1013,7 +1046,10 @@ mod tests {
"test transcription",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
Some(speaker2.id),
None,
None,
@@ -1317,7 +1353,10 @@ mod tests {
"Hello from audio",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ },
None,
None,
None,
diff --git a/screenpipe-events/Cargo.toml b/screenpipe-events/Cargo.toml
index eec914a10..e7fe4d765 100644
--- a/screenpipe-events/Cargo.toml
+++ b/screenpipe-events/Cargo.toml
@@ -17,7 +17,7 @@ tokio-stream = { version = "0.1.17", features = ["sync"] }
once_cell = { version = "1.18" }
tracing.workspace = true
parking_lot = "0.12.3"
-chrono = "0.4.39"
+chrono = { version = "0.4.39", features = ["serde"] }
[dev-dependencies]
serde = { version = "1.0", features = ["derive"] }
diff --git a/screenpipe-events/tests/events_manager_test.rs b/screenpipe-events/tests/events_manager_test.rs
index d010f14f5..749a11cb6 100644
--- a/screenpipe-events/tests/events_manager_test.rs
+++ b/screenpipe-events/tests/events_manager_test.rs
@@ -13,17 +13,17 @@ struct TestData {
#[tokio::test]
async fn test_single_subscriber() {
- let mut stream = subscribe_to_event::<String>("test_event");
- let _ = send_event("test_event", "hello".to_string());
+ let mut stream = subscribe_to_event::<String>("single_subscriber_event");
+ let _ = send_event("single_subscriber_event", "hello".to_string());
assert_eq!(stream.next().await.unwrap().data, "hello");
}
#[tokio::test]
async fn test_multiple_subscribers() {
- let mut stream1 = subscribe_to_event::<String>("test_event");
- let mut stream2 = subscribe_to_event::<String>("test_event");
+ let mut stream1 = subscribe_to_event::<String>("multiple_subscriber_event");
+ let mut stream2 = subscribe_to_event::<String>("multiple_subscriber_event");
- let _ = send_event("test_event", "hello".to_string());
+ let _ = send_event("multiple_subscriber_event", "hello".to_string());
assert_eq!(stream1.next().await.unwrap().data, "hello");
assert_eq!(stream2.next().await.unwrap().data, "hello");
@@ -31,11 +31,11 @@ async fn test_multiple_subscribers() {
#[tokio::test]
async fn test_different_events() {
- let mut stream1 = subscribe_to_event::<i32>("event1");
- let mut stream2 = subscribe_to_event::<String>("event2");
+ let mut stream1 = subscribe_to_event::<i32>("different_event1");
+ let mut stream2 = subscribe_to_event::<String>("different_event2");
- let _ = send_event("event1", 42);
- let _ = send_event("event2", "hello".to_string());
+ let _ = send_event("different_event1", 42);
+ let _ = send_event("different_event2", "hello".to_string());
assert_eq!(stream1.next().await.unwrap().data, 42);
assert_eq!(stream2.next().await.unwrap().data, "hello");
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 2746868b0..5f5ba07d9 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -18,6 +18,7 @@ screenpipe-events = { path = "../screenpipe-events" }
screenpipe-vision = { path = "../screenpipe-vision" }
screenpipe-audio = { path = "../screenpipe-audio" }
screenpipe-core = { path = "../screenpipe-core", features = ["security"] }
+screenpipe-db = { path = "../screenpipe-db" }
killport = { version = "1.1.0" }
# Image processing
@@ -131,15 +132,6 @@ tokio-tungstenite = "0.19.0"
criterion = { workspace = true }
rand = "0.8"
-
-[[bench]]
-name = "db_benchmarks"
-harness = false
-
-[[bench]]
-name = "new_db_benchmark"
-harness = false
-
[features]
default = []
metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]
diff --git a/screenpipe-server/src/add.rs b/screenpipe-server/src/add.rs
index d0881baf9..75fd29564 100644
--- a/screenpipe-server/src/add.rs
+++ b/screenpipe-server/src/add.rs
@@ -1,6 +1,7 @@
use anyhow::Result;
use image::DynamicImage;
use regex::Regex;
+use screenpipe_db::DatabaseManager;
use screenpipe_vision::utils::{compare_with_previous_image, OcrEngine};
#[cfg(target_os = "macos")]
@@ -26,7 +27,6 @@ use crate::{
cli::CliOcrEngine,
text_embeds::generate_embedding,
video_utils::{extract_frames_from_video, get_video_metadata, VideoMetadataOverrides},
- DatabaseManager,
};
#[allow(clippy::too_many_arguments)]
@@ -136,7 +136,7 @@ pub async fn handle_index_command(
.create_video_with_frames(
video_path.to_str().unwrap(),
frames.clone(),
- metadata.clone(),
+ metadata.into(),
)
.await?;
@@ -178,8 +178,6 @@ pub async fn handle_index_command(
}
};
- let engine_arc = Arc::new(engine.clone());
-
// Do OCR processing directly
let (text, _, confidence): (String, String, Option<f64>) = match engine.clone() {
#[cfg(target_os = "macos")]
@@ -225,7 +223,7 @@ pub async fn handle_index_command(
frame_ids[idx],
&text,
"{}", // empty json
- engine_arc.clone(),
+ ocr_engine.clone().unwrap().into(),
)
.await
{
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index c95ff7b5b..8424e2bef 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -1,31 +1,36 @@
use clap::Parser;
#[allow(unused_imports)]
use colored::Colorize;
-use dashmap::DashMap;
use dirs::home_dir;
use futures::pin_mut;
use port_check::is_local_ipv4_port_free;
use screenpipe_audio::{
- default_input_device, default_output_device, list_audio_devices, parse_audio_device,
- AudioDevice, DeviceControl,
+ audio_manager::AudioManagerBuilder,
+ core::device::{
+ default_input_device, default_output_device, list_audio_devices, parse_audio_device,
+ trigger_audio_permission,
+ },
+ transcription::whisper::model::download_whisper_model,
+ vad::silero::SileroVad,
};
use screenpipe_core::find_ffmpeg_path;
+use screenpipe_db::{
+ create_migration_worker, DatabaseManager, MigrationCommand, MigrationConfig, MigrationStatus,
+};
use screenpipe_server::{
cli::{
AudioCommand, Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, MigrationSubCommand,
OutputFormat, PipeCommand, VisionCommand,
},
- create_migration_worker, handle_index_command,
+ handle_index_command,
pipe_manager::PipeInfo,
- start_continuous_recording, watch_pid, DatabaseManager, MigrationCommand, MigrationConfig,
- MigrationStatus, PipeManager, ResourceMonitor, SCServer,
+ start_continuous_recording, watch_pid, PipeManager, ResourceMonitor, SCServer,
};
use screenpipe_vision::monitor::list_monitors;
#[cfg(target_os = "macos")]
use screenpipe_vision::run_ui;
use serde_json::{json, Value};
use std::{
- collections::HashMap,
env, fs,
io::Write,
net::SocketAddr,
@@ -38,9 +43,9 @@ use tokio::{runtime::Runtime, signal, sync::broadcast};
use tracing::{debug, error, info, warn};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_appender::rolling::{RollingFileAppender, Rotation};
-use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter};
+use tracing_subscriber::{prelude::__tracing_subscriber_SubscriberExt, Layer};
const DISPLAY: &str = r"
_
@@ -77,61 +82,80 @@ fn setup_logging(local_data_dir: &PathBuf, cli: &Cli) -> anyhow::Result<WorkerGu
let (file_writer, guard) = tracing_appender::non_blocking(file_appender);
- let env_filter = EnvFilter::from_default_env()
- .add_directive("info".parse().unwrap())
- .add_directive("tokenizers=error".parse().unwrap())
- .add_directive("rusty_tesseract=error".parse().unwrap())
- .add_directive("symphonia=error".parse().unwrap())
- .add_directive("hf_hub=error".parse().unwrap());
-
- // noise - but prob should be more precise on which error to ignore
- #[cfg(target_os = "windows")]
- let env_filter = env_filter
- .add_directive("xcap::platform::impl_window=off".parse().unwrap())
- .add_directive("xcap::platform::impl_monitor=off".parse().unwrap())
- .add_directive("xcap::platform::utils=off".parse().unwrap());
-
- let env_filter = env::var("SCREENPIPE_LOG")
- .unwrap_or_default()
- .split(',')
- .filter(|s| !s.is_empty())
- .fold(
- env_filter,
- |filter, module_directive| match module_directive.parse() {
- Ok(directive) => filter.add_directive(directive),
- Err(e) => {
- eprintln!(
- "warning: invalid log directive '{}': {}",
- module_directive, e
- );
- filter
+ let make_env_filter = || {
+ let filter = EnvFilter::from_default_env()
+ .add_directive("tokio=debug".parse().unwrap())
+ .add_directive("runtime=debug".parse().unwrap())
+ .add_directive("info".parse().unwrap())
+ .add_directive("tokenizers=error".parse().unwrap())
+ .add_directive("rusty_tesseract=error".parse().unwrap())
+ .add_directive("symphonia=error".parse().unwrap())
+ .add_directive("hf_hub=error".parse().unwrap())
+ .add_directive("whisper_rs=error".parse().unwrap());
+
+ #[cfg(target_os = "windows")]
+ let filter = filter
+ .add_directive("xcap::platform::impl_window=off".parse().unwrap())
+ .add_directive("xcap::platform::impl_monitor=off".parse().unwrap())
+ .add_directive("xcap::platform::utils=off".parse().unwrap());
+
+ let filter = env::var("SCREENPIPE_LOG")
+ .unwrap_or_default()
+ .split(',')
+ .filter(|s| !s.is_empty())
+ .fold(filter, |filter, module_directive| {
+ match module_directive.parse() {
+ Ok(directive) => filter.add_directive(directive),
+ Err(e) => {
+ eprintln!(
+ "warning: invalid log directive '{}': {}",
+ module_directive, e
+ );
+ filter
+ }
}
- },
- );
+ });
- let env_filter = if cli.debug {
- env_filter.add_directive("screenpipe=debug".parse().unwrap())
- } else {
- env_filter
+ if cli.debug {
+ filter.add_directive("screenpipe=debug".parse().unwrap())
+ } else {
+ filter
+ }
};
let timer =
tracing_subscriber::fmt::time::ChronoLocal::new("%Y-%m-%dT%H:%M:%S%.6fZ".to_string());
- let registry = tracing_subscriber::registry()
- .with(env_filter)
+ let tracing_registry = tracing_subscriber::registry()
.with(
fmt::layer()
.with_writer(std::io::stdout)
- .with_timer(timer.clone()),
+ .with_timer(timer.clone())
+ .with_filter(make_env_filter()),
)
- .with(fmt::layer().with_writer(file_writer).with_timer(timer));
+ .with(
+ fmt::layer()
+ .with_writer(file_writer)
+ .with_timer(timer)
+ .with_filter(make_env_filter()),
+ );
+
+ #[cfg(feature = "debug-console")]
+ let tracing_registry = tracing_registry.with(
+ console_subscriber::spawn().with_filter(
+ EnvFilter::from_default_env()
+ .add_directive("tokio=trace".parse().unwrap())
+ .add_directive("runtime=trace".parse().unwrap()),
+ ),
+ );
// Build the final registry with conditional Sentry layer
if !cli.disable_telemetry {
- registry.with(sentry::integrations::tracing::layer()).init();
+ tracing_registry
+ .with(sentry::integrations::tracing::layer())
+ .init();
} else {
- registry.init();
+ tracing_registry.init();
};
Ok(guard)
@@ -258,7 +282,7 @@ async fn main() -> anyhow::Result<()> {
}
},
Command::Completions { shell } => {
- cli.handle_completions(shell.clone())?;
+ cli.handle_completions(*shell)?;
return Ok(());
}
Command::Pipe { subcommand } => {
@@ -266,9 +290,6 @@ async fn main() -> anyhow::Result<()> {
return Ok(());
}
Command::Setup {} => {
- use screenpipe_audio::{
- trigger_audio_permission, vad_engine::SileroVad, whisper::WhisperModel,
- };
use screenpipe_vision::core::trigger_screen_capture_permission;
// Trigger audio permission request
@@ -294,7 +315,7 @@ async fn main() -> anyhow::Result<()> {
// this command just download models and stuff (useful to have specific step to display in UI)
// ! should prob skip if deepgram?
- WhisperModel::new(&cli.audio_transcription_engine.into()).unwrap();
+ download_whisper_model(Arc::new(cli.audio_transcription_engine.into())).unwrap();
// ! assuming silero is used
SileroVad::new().await.unwrap();
@@ -328,7 +349,7 @@ async fn main() -> anyhow::Result<()> {
continue_on_error,
} => {
// Initialize the database
- let local_data_dir = get_base_dir(&data_dir)?;
+ let local_data_dir = get_base_dir(data_dir)?;
let db = Arc::new(
DatabaseManager::new(&format!(
"{}/db.sqlite",
@@ -513,7 +534,7 @@ async fn main() -> anyhow::Result<()> {
debug,
use_embedding,
} => {
- let local_data_dir = get_base_dir(&data_dir)?;
+ let local_data_dir = get_base_dir(data_dir)?;
// Update logging filter if debug is enabled
if *debug {
@@ -562,8 +583,6 @@ async fn main() -> anyhow::Result<()> {
std::process::exit(1);
}
- let mut devices_status = HashMap::new();
-
if !is_local_ipv4_port_free(cli.port) {
error!(
"you're likely already running screenpipe instance in a different environment, e.g. terminal/ide, close it and restart or use different port"
@@ -571,74 +590,31 @@ async fn main() -> anyhow::Result<()> {
return Err(anyhow::anyhow!("port already in use"));
}
- let all_audio_devices = list_audio_devices().await?;
-
let all_monitors = list_monitors().await;
let mut audio_devices = Vec::new();
- let audio_devices_control = Arc::new(DashMap::new());
- let audio_devices_control_recording = audio_devices_control.clone();
-
let mut realtime_audio_devices = Vec::new();
- // Add all available audio devices to the controls
- for device in &all_audio_devices {
- let device_control = DeviceControl {
- is_running: false,
- is_paused: false,
- };
- devices_status.insert(device.clone(), device_control);
- }
-
if !cli.disable_audio {
if cli.audio_device.is_empty() {
// Use default devices
if let Ok(input_device) = default_input_device() {
- audio_devices.push(Arc::new(input_device.clone()));
- let device_control = DeviceControl {
- is_running: true,
- is_paused: false,
- };
- devices_status.insert(input_device, device_control);
+ audio_devices.push(input_device.to_string());
}
if let Ok(output_device) = default_output_device() {
- audio_devices.push(Arc::new(output_device.clone()));
- let device_control = DeviceControl {
- is_running: true,
- is_paused: false,
- };
- devices_status.insert(output_device, device_control);
+ audio_devices.push(output_device.to_string());
}
} else {
// Use specified devices
for d in &cli.audio_device {
let device = parse_audio_device(d).expect("failed to parse audio device");
- audio_devices.push(Arc::new(device.clone()));
- let device_control = DeviceControl {
- is_running: true,
- is_paused: false,
- };
- devices_status.insert(device, device_control);
+ audio_devices.push(device.to_string());
}
}
if audio_devices.is_empty() {
- eprintln!("no audio devices available. audio recording will be disabled.");
- } else {
- for device in &audio_devices {
- let device_control = DeviceControl {
- is_running: true,
- is_paused: false,
- };
- let device_clone = device.deref().clone();
- let sender_clone = audio_devices_control.clone();
- // send signal after everything started
- tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(15)).await;
- sender_clone.insert(device_clone, device_control);
- });
- }
+ warn!("no audio devices available.");
}
if cli.enable_realtime_audio_transcription {
@@ -663,6 +639,7 @@ async fn main() -> anyhow::Result<()> {
}
}
+ let audio_devices_clone = audio_devices.clone();
let resource_monitor = ResourceMonitor::new(!cli.disable_telemetry);
resource_monitor.start_monitoring(Duration::from_secs(10), Some(Duration::from_secs(60)));
@@ -697,11 +674,9 @@ async fn main() -> anyhow::Result<()> {
let vad_sensitivity_clone = cli.vad_sensitivity.clone();
let (shutdown_tx, _) = broadcast::channel::<()>(1);
- let audio_runtime = Runtime::new().unwrap();
let vision_runtime = Runtime::new().unwrap();
let pipes_runtime = Runtime::new().unwrap();
- let audio_handle = audio_runtime.handle().clone();
let vision_handle = vision_runtime.handle().clone();
let pipes_handle = pipes_runtime.handle().clone();
@@ -722,39 +697,47 @@ async fn main() -> anyhow::Result<()> {
};
let audio_chunk_duration = Duration::from_secs(cli.audio_chunk_duration);
- let deepgram_api_key = cli.deepgram_api_key.clone();
+
+ let mut audio_manager_builder = AudioManagerBuilder::new()
+ .audio_chunk_duration(audio_chunk_duration)
+ .vad_engine(vad_engine.into())
+ .vad_sensitivity(cli.vad_sensitivity.into())
+ .languages(languages.clone())
+ .transcription_engine(cli.audio_transcription_engine.into())
+ .realtime(cli.enable_realtime_audio_transcription)
+ .enabled_devices(audio_devices)
+ .deepgram_api_key(cli.deepgram_api_key.clone())
+ .output_path(PathBuf::from(output_path_clone.clone().to_string()));
+
+ let audio_manager = match audio_manager_builder.build(db.clone()).await {
+ Ok(manager) => Arc::new(manager),
+ Err(e) => {
+ error!("{e}");
+ return Ok(());
+ }
+ };
+
let handle = {
let runtime = &tokio::runtime::Handle::current();
runtime.spawn(async move {
loop {
- let vad_engine_clone = vad_engine.clone(); // Clone it here for each iteration
let mut shutdown_rx = shutdown_tx_clone.subscribe();
let recording_future = start_continuous_recording(
db_clone.clone(),
output_path_clone.clone(),
fps,
- audio_chunk_duration,
Duration::from_secs(cli.video_chunk_duration),
vision_control_clone.clone(),
- audio_devices_control_recording.clone(),
- cli.disable_audio,
- Arc::new(cli.audio_transcription_engine.clone().into()),
Arc::new(cli.ocr_engine.clone().into()),
monitor_ids_clone.clone(),
cli.use_pii_removal,
cli.disable_vision,
- vad_engine_clone,
&vision_handle,
- &audio_handle,
&cli.ignored_windows,
&cli.included_windows,
- deepgram_api_key.clone(),
- cli.vad_sensitivity.clone(),
- languages.clone(),
+ languages_clone.clone(),
cli.capture_unfocused_windows,
- realtime_audio_devices.clone(),
cli.enable_realtime_audio_transcription,
- cli.enable_realtime_vision,
);
let result = tokio::select! {
@@ -789,8 +772,6 @@ async fn main() -> anyhow::Result<()> {
#[cfg(feature = "llm")]
debug!("LLM initialized");
- let (audio_devices_tx, _) = broadcast::channel(100);
-
let server = SCServer::new(
db_server,
SocketAddr::from(([127, 0, 0, 1], cli.port)),
@@ -799,48 +780,9 @@ async fn main() -> anyhow::Result<()> {
cli.disable_vision,
cli.disable_audio,
cli.enable_ui_monitoring,
+ audio_manager.clone(),
);
- let mut rx = audio_devices_tx.subscribe();
- let audio_devices_control_for_spawn = audio_devices_control.clone();
- tokio::spawn(async move {
- while let Ok((device, control)) = rx.recv().await {
- if let Err(e) =
- handle_device_update(&device, control, &audio_devices_control_for_spawn).await
- {
- error!("Device update failed: {}", e);
- continue;
- }
- }
- info!("Device monitoring task completed");
- });
-
- async fn handle_device_update(
- device: &AudioDevice,
- control: DeviceControl,
- devices_control: &DashMap<AudioDevice, DeviceControl>,
- ) -> anyhow::Result<()> {
- match list_audio_devices().await {
- Ok(available_devices) => {
- if !available_devices.contains(device) {
- return Err(anyhow::anyhow!(
- "attempted to control non-existent device: {}",
- device.name
- ));
- }
-
- // Update the device state
- devices_control.insert(device.clone(), control.clone());
- info!(
- "Device state changed: {} - running: {}",
- device.name, control.is_running
- );
- Ok(())
- }
- Err(e) => Err(anyhow::anyhow!("failed to list audio devices: {}", e)),
- }
- }
-
// print screenpipe in gradient
println!("\n\n{}", DISPLAY.truecolor(147, 112, 219).bold());
println!(
@@ -963,11 +905,7 @@ async fn main() -> anyhow::Result<()> {
println!("│ {:<22} │ {:<34} │", "", "all languages");
} else {
let total_languages = cli.language.len();
- for (_, language) in languages_clone
- .iter()
- .enumerate()
- .take(MAX_ITEMS_TO_DISPLAY)
- {
+ for (_, language) in languages.iter().enumerate().take(MAX_ITEMS_TO_DISPLAY) {
let language_str = format!("id: {}", language);
let formatted_language = format_cell(&language_str, VALUE_WIDTH);
println!("│ {:<22} │ {:<34} │", "", formatted_language);
@@ -1011,11 +949,15 @@ async fn main() -> anyhow::Result<()> {
if cli.disable_audio {
println!("│ {:<22} │ {:<34} │", "", "disabled");
- } else if audio_devices.is_empty() {
+ } else if audio_devices_clone.is_empty() {
println!("│ {:<22} │ {:<34} │", "", "no devices available");
} else {
- let total_devices = audio_devices.len();
- for (_, device) in audio_devices.iter().enumerate().take(MAX_ITEMS_TO_DISPLAY) {
+ let total_devices = audio_devices_clone.len();
+ for (_, device) in audio_devices_clone
+ .iter()
+ .enumerate()
+ .take(MAX_ITEMS_TO_DISPLAY)
+ {
let device_str = device.deref().to_string();
let formatted_device = format_cell(&device_str, VALUE_WIDTH);
@@ -1126,6 +1068,15 @@ async fn main() -> anyhow::Result<()> {
.italic()
);
+ // start recording after all this text
+ if !cli.disable_audio {
+ let audio_manager_clone = audio_manager.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_secs(10)).await;
+ audio_manager_clone.start().await.unwrap();
+ });
+ }
+
// Start pipes
info!("starting pipes");
let pipes = pipe_manager.list_pipes().await;
@@ -1228,6 +1179,7 @@ async fn main() -> anyhow::Result<()> {
}
_ = ctrl_c_future => {
info!("received ctrl+c, initiating shutdown");
+ audio_manager.shutdown().await?;
let _ = shutdown_tx.send(());
}
}
@@ -1235,7 +1187,7 @@ async fn main() -> anyhow::Result<()> {
tokio::task::block_in_place(|| {
drop(pipes_runtime);
drop(vision_runtime);
- drop(audio_runtime);
+ drop(audio_manager);
});
info!("shutdown complete");
@@ -1315,7 +1267,7 @@ async fn handle_pipe_command(
),
}
}
- _ => match pipe_manager.download_pipe(&url).await {
+ _ => match pipe_manager.download_pipe(url).await {
Ok(pipe_id) => match output {
OutputFormat::Json => println!(
"{}",
@@ -1358,7 +1310,7 @@ async fn handle_pipe_command(
_ => {
println!("note: server not running, showing pipe configuration");
pipe_manager
- .get_pipe_info(&id)
+ .get_pipe_info(id)
.await
.ok_or_else(|| anyhow::anyhow!("pipe not found"))?
}
@@ -1381,7 +1333,7 @@ async fn handle_pipe_command(
}
_ => {
pipe_manager
- .update_config(&id, json!({"enabled": true}))
+ .update_config(id, json!({"enabled": true}))
.await?;
println!("note: server not running, updated config only. pipe will start on next server launch");
}
@@ -1400,7 +1352,7 @@ async fn handle_pipe_command(
}
_ => {
pipe_manager
- .update_config(&id, json!({"enabled": false}))
+ .update_config(id, json!({"enabled": false}))
.await?;
println!("note: server not running, updated config only");
}
@@ -1408,8 +1360,8 @@ async fn handle_pipe_command(
}
PipeCommand::Update { id, config, port } => {
- let config: Value = serde_json::from_str(&config)
- .map_err(|e| anyhow::anyhow!("invalid json: {}", e))?;
+ let config: Value =
+ serde_json::from_str(config).map_err(|e| anyhow::anyhow!("invalid json: {}", e))?;
match client
.post(format!("{}:{}/pipes/update", server_url, port))
@@ -1424,7 +1376,7 @@ async fn handle_pipe_command(
println!("pipe {} config updated in running server", id);
}
_ => {
- pipe_manager.update_config(&id, config).await?;
+ pipe_manager.update_config(id, config).await?;
println!("note: server not running, updated config only");
}
}
@@ -1450,7 +1402,7 @@ async fn handle_pipe_command(
Ok(response) if response.status().is_success() => {
println!("pipe '{}' deleted from running server", id);
}
- _ => match pipe_manager.delete_pipe(&id).await {
+ _ => match pipe_manager.delete_pipe(id).await {
Ok(_) => println!("pipe '{}' deleted from local files", id),
Err(e) => println!("failed to delete pipe: {}", e),
},
diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rs
index f5b9cd9a6..fdab3b7d1 100644
--- a/screenpipe-server/src/cli.rs
+++ b/screenpipe-server/src/cli.rs
@@ -1,24 +1,30 @@
-use std::path::PathBuf;
+use std::{path::PathBuf, sync::Arc};
use clap::{Parser, Subcommand, ValueHint};
use clap_complete::{generate, Shell};
use clap::CommandFactory;
-use screenpipe_audio::{vad_engine::VadSensitivity, AudioTranscriptionEngine as CoreAudioTranscriptionEngine};
+use screenpipe_audio::{vad::{VadSensitivity, VadEngineEnum}, core::engine::AudioTranscriptionEngine as CoreAudioTranscriptionEngine};
use screenpipe_vision::{custom_ocr::CustomOcrConfig, utils::OcrEngine as CoreOcrEngine};
use clap::ValueEnum;
-use screenpipe_audio::vad_engine::VadEngineEnum;
use screenpipe_core::Language;
-
+use screenpipe_db::OcrEngine as DBOcrEngine;
+use screenpipe_db::CustomOcrConfig as DBCustomOcrConfig;
#[derive(Clone, Debug, ValueEnum, PartialEq)]
pub enum CliAudioTranscriptionEngine {
#[clap(name = "deepgram")]
Deepgram,
#[clap(name = "whisper-tiny")]
WhisperTiny,
+ #[clap(name = "whisper-tiny-quantized")]
+ WhisperTinyQuantized,
#[clap(name = "whisper-large")]
- WhisperDistilLargeV3,
+ WhisperLargeV3,
+ #[clap(name = "whisper-large-quantized")]
+ WhisperLargeV3Quantized,
#[clap(name = "whisper-large-v3-turbo")]
WhisperLargeV3Turbo,
+ #[clap(name = "whisper-large-v3-turbo-quantized")]
+ WhisperLargeV3TurboQuantized,
}
impl From<CliAudioTranscriptionEngine> for CoreAudioTranscriptionEngine {
@@ -26,12 +32,15 @@ impl From<CliAudioTranscriptionEngine> for CoreAudioTranscriptionEngine {
match cli_engine {
CliAudioTranscriptionEngine::Deepgram => CoreAudioTranscriptionEngine::Deepgram,
CliAudioTranscriptionEngine::WhisperTiny => CoreAudioTranscriptionEngine::WhisperTiny,
- CliAudioTranscriptionEngine::WhisperDistilLargeV3 => {
- CoreAudioTranscriptionEngine::WhisperDistilLargeV3
- }
+ CliAudioTranscriptionEngine::WhisperTinyQuantized => CoreAudioTranscriptionEngine::WhisperTinyQuantized,
+ CliAudioTranscriptionEngine::WhisperLargeV3 => CoreAudioTranscriptionEngine::WhisperLargeV3,
+ CliAudioTranscriptionEngine::WhisperLargeV3Quantized => CoreAudioTranscriptionEngine::WhisperLargeV3Quantized,
CliAudioTranscriptionEngine::WhisperLargeV3Turbo => {
CoreAudioTranscriptionEngine::WhisperLargeV3Turbo
}
+ CliAudioTranscriptionEngine::WhisperLargeV3TurboQuantized => {
+ CoreAudioTranscriptionEngine::WhisperLargeV3TurboQuantized
+ }
}
}
}
@@ -48,6 +57,21 @@ pub enum CliOcrEngine {
Custom,
}
+impl From<CliOcrEngine> for Arc<DBOcrEngine> {
+ fn from(cli_engine: CliOcrEngine) -> Self {
+ match cli_engine {
+ CliOcrEngine::Unstructured => Arc::new(DBOcrEngine::Unstructured),
+ #[cfg(target_os = "macos")]
+ CliOcrEngine::AppleNative => Arc::new(DBOcrEngine::AppleNative),
+ #[cfg(target_os = "linux")]
+ CliOcrEngine::Tesseract => Arc::new(DBOcrEngine::Tesseract),
+ #[cfg(target_os = "windows")]
+ CliOcrEngine::WindowsNative => Arc::new(DBOcrEngine::WindowsNative),
+ CliOcrEngine::Custom => Arc::new(DBOcrEngine::Custom(DBCustomOcrConfig::default())),
+ }
+ }
+}
+
impl From<CliOcrEngine> for CoreOcrEngine {
fn from(cli_engine: CliOcrEngine) -> Self {
match cli_engine {
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index bc227cdf8..febfec7cd 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -1,55 +1,34 @@
-use crate::cli::{CliVadEngine, CliVadSensitivity};
-use crate::db_types::Speaker;
-use crate::{DatabaseManager, VideoCapture};
+use crate::VideoCapture;
use anyhow::Result;
-use dashmap::DashMap;
use futures::future::join_all;
-use screenpipe_audio::vad_engine::VadSensitivity;
-use screenpipe_audio::{
- create_whisper_channel, record_and_transcribe, vad_engine::VadEngineEnum, AudioDevice,
- AudioInput, AudioTranscriptionEngine, DeviceControl, TranscriptionResult,
-};
-use screenpipe_audio::{start_realtime_recording, AudioStream};
use screenpipe_core::pii_removal::remove_pii;
use screenpipe_core::Language;
+use screenpipe_db::{DatabaseManager, Speaker};
use screenpipe_events::{poll_meetings_events, send_event};
use screenpipe_vision::core::WindowOcr;
use screenpipe_vision::OcrEngine;
-use std::collections::HashMap;
-use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::runtime::Handle;
-use tokio::task::JoinHandle;
-use tracing::{debug, error, info, warn};
+use tracing::{debug, error, warn};
#[allow(clippy::too_many_arguments)]
pub async fn start_continuous_recording(
db: Arc<DatabaseManager>,
output_path: Arc<String>,
fps: f64,
- audio_chunk_duration: Duration,
video_chunk_duration: Duration,
vision_control: Arc<AtomicBool>,
- audio_devices_control: Arc<DashMap<AudioDevice, DeviceControl>>,
- audio_disabled: bool,
- audio_transcription_engine: Arc<AudioTranscriptionEngine>,
ocr_engine: Arc<OcrEngine>,
monitor_ids: Vec<u32>,
use_pii_removal: bool,
vision_disabled: bool,
- vad_engine: CliVadEngine,
vision_handle: &Handle,
- audio_handle: &Handle,
ignored_windows: &[String],
include_windows: &[String],
- deepgram_api_key: Option<String>,
- vad_sensitivity: CliVadSensitivity,
languages: Vec<Language>,
capture_unfocused_windows: bool,
- realtime_audio_devices: Vec<Arc<AudioDevice>>,
- realtime_audio_enabled: bool,
realtime_vision: bool,
) -> Result<()> {
debug!("Starting video recording for monitor {:?}", monitor_ids);
@@ -94,69 +73,11 @@ pub async fn start_continuous_recording(
})]
};
- let (whisper_sender, whisper_receiver, whisper_shutdown_flag) = if audio_disabled {
- // Create a dummy channel if no audio devices are available, e.g. audio disabled
- let (input_sender, _): (
- crossbeam::channel::Sender<AudioInput>,
- crossbeam::channel::Receiver<AudioInput>,
- ) = crossbeam::channel::bounded(100);
- let (_, output_receiver): (
- crossbeam::channel::Sender<TranscriptionResult>,
- crossbeam::channel::Receiver<TranscriptionResult>,
- ) = crossbeam::channel::bounded(100);
- (
- input_sender,
- output_receiver,
- Arc::new(AtomicBool::new(false)),
- )
- } else {
- create_whisper_channel(
- audio_transcription_engine.clone(),
- VadEngineEnum::from(vad_engine),
- deepgram_api_key.clone(),
- &PathBuf::from(output_path.as_ref()),
- VadSensitivity::from(vad_sensitivity),
- languages.clone(),
- Some(audio_devices_control.clone()),
- )
- .await
- .map_err(|e| {
- if e.to_string().contains("ORT API") {
- anyhow::anyhow!("ONNX Runtime initialization failed. This is likely due to missing Visual C++ Redistributable packages. Please install the latest Visual C++ Redistributable from https://aka.ms/vs/17/release/vc_redist.x64.exe and restart your computer. For more information, see: https://github.com/mediar-ai/screenpipe/issues/1034")
- } else {
- e
- }
- })?
- };
- let whisper_sender_clone = whisper_sender.clone();
- let db_manager_audio = Arc::clone(&db);
-
- tokio::spawn(async move {
- let _ = poll_meetings_events().await;
- });
-
- let audio_task = if !audio_disabled {
- audio_handle.spawn(async move {
- record_audio(
- db_manager_audio,
- audio_chunk_duration,
- whisper_sender,
- whisper_receiver,
- audio_devices_control,
- audio_transcription_engine,
- realtime_audio_enabled,
- realtime_audio_devices,
- languages,
- deepgram_api_key,
- )
- .await
- })
- } else {
- audio_handle.spawn(async move {
- tokio::time::sleep(Duration::from_secs(60)).await;
- Ok(())
- })
- };
+ if !vision_disabled {
+ vision_handle.spawn(async move {
+ let _ = poll_meetings_events().await;
+ });
+ }
// Join all video tasks
let video_results = join_all(video_tasks);
@@ -164,22 +85,12 @@ pub async fn start_continuous_recording(
// Handle any errors from the tasks
for (i, result) in video_results.await.into_iter().enumerate() {
if let Err(e) = result {
- error!("Video recording error for monitor {}: {:?}", i, e);
+ if !e.is_cancelled() {
+ error!("Video recording error for monitor {}: {:?}", i, e);
+ }
}
}
- if let Err(e) = audio_task.await {
- error!("Audio recording error: {:?}", e);
- }
-
- // Shutdown the whisper channel
- whisper_shutdown_flag.store(true, Ordering::Relaxed);
- drop(whisper_sender_clone); // Close the sender channel
- // TODO: process any remaining audio chunks
- // TODO: wait a bit for whisper to finish processing
- // TODO: any additional cleanup like device controls to release
-
- info!("Stopped recording");
Ok(())
}
@@ -277,7 +188,12 @@ async fn record_video(
);
}
if let Err(e) = db
- .insert_ocr_text(frame_id, text, &text_json, Arc::clone(&ocr_engine))
+ .insert_ocr_text(
+ frame_id,
+ text,
+ &text_json,
+ Arc::new((*ocr_engine).clone().into()),
+ )
.await
{
error!(
@@ -301,299 +217,6 @@ async fn record_video(
Ok(())
}
-#[allow(clippy::too_many_arguments)]
-async fn record_audio(
- db: Arc<DatabaseManager>,
- chunk_duration: Duration,
- whisper_sender: crossbeam::channel::Sender<AudioInput>,
- whisper_receiver: crossbeam::channel::Receiver<TranscriptionResult>,
- audio_devices_control: Arc<DashMap<AudioDevice, DeviceControl>>,
- audio_transcription_engine: Arc<AudioTranscriptionEngine>,
- realtime_audio_enabled: bool,
- realtime_audio_devices: Vec<Arc<AudioDevice>>,
- languages: Vec<Language>,
- deepgram_api_key: Option<String>,
-) -> Result<()> {
- let mut handles: HashMap<String, JoinHandle<()>> = HashMap::new();
- let mut previous_transcript = "".to_string();
- let mut previous_transcript_id: Option<i64> = None;
- loop {
- // Iterate over DashMap entries and process each device
- for entry in audio_devices_control.iter() {
- let audio_device = entry.key().clone();
- let device_control = entry.value().clone();
- let device_id = audio_device.to_string();
-
- // Skip if we're already handling this device
- if handles.contains_key(&device_id) {
- continue;
- }
-
- info!("Received audio device: {}", &audio_device);
-
- if !device_control.is_running {
- info!("Device control signaled stop for device {}", &audio_device);
- if let Some(handle) = handles.remove(&device_id) {
- handle.abort();
- info!("Stopped thread for device {}", &audio_device);
- }
- // Remove from DashMap
- audio_devices_control.remove(&audio_device);
- continue;
- }
-
- let whisper_sender_clone = whisper_sender.clone();
-
- let audio_device = Arc::new(audio_device);
- let device_control = Arc::new(device_control);
-
- let realtime_audio_devices_clone = realtime_audio_devices.clone();
- let languages_clone = languages.clone();
- let deepgram_api_key_clone = deepgram_api_key.clone();
- let handle = tokio::spawn(async move {
- let audio_device_clone = Arc::clone(&audio_device);
- let deepgram_api_key = deepgram_api_key_clone.clone();
- debug!(
- "Starting audio capture thread for device: {}",
- &audio_device
- );
-
- let mut did_warn = false;
- let is_running = Arc::new(AtomicBool::new(device_control.is_running));
-
- while is_running.load(Ordering::Relaxed) {
- let deepgram_api_key = deepgram_api_key.clone();
- let is_running_loop = Arc::clone(&is_running); // Create separate reference for the loop
- let audio_stream = match AudioStream::from_device(
- audio_device_clone.clone(),
- Arc::clone(&is_running_loop), // Clone from original Arc
- )
- .await
- {
- Ok(stream) => stream,
- Err(e) => {
- if e.to_string().contains("Audio device not found") {
- if !did_warn {
- warn!("Audio device not found: {}", audio_device.name);
- did_warn = true;
- }
- tokio::time::sleep(Duration::from_secs(1)).await;
- continue;
- } else {
- error!("Failed to create audio stream: {}", e);
- return;
- }
- }
- };
-
- let mut recording_handles: Vec<JoinHandle<()>> = vec![];
-
- let audio_stream = Arc::new(audio_stream);
- let whisper_sender_clone = whisper_sender_clone.clone();
- let audio_stream_clone = audio_stream.clone();
- let is_running_loop_clone = is_running_loop.clone();
- let record_handle = Some(tokio::spawn(async move {
- let _ = record_and_transcribe(
- audio_stream,
- chunk_duration,
- whisper_sender_clone.clone(),
- is_running_loop_clone.clone(),
- )
- .await;
- }));
-
- if let Some(handle) = record_handle {
- recording_handles.push(handle);
- }
-
- let audio_device_clone = audio_device_clone.clone();
- let realtime_audio_devices_clone = realtime_audio_devices_clone.clone();
- let languages_clone = languages_clone.clone();
- let is_running_loop = is_running_loop.clone();
- let live_transcription_handle = Some(tokio::spawn(async move {
- if realtime_audio_enabled
- && realtime_audio_devices_clone.contains(&audio_device_clone)
- {
- let _ = start_realtime_recording(
- audio_stream_clone,
- languages_clone.clone(),
- is_running_loop.clone(),
- deepgram_api_key.clone(),
- )
- .await;
- }
- }));
-
- if let Some(handle) = live_transcription_handle {
- recording_handles.push(handle);
- }
-
- join_all(recording_handles).await;
- }
-
- info!("exiting audio capture thread for device: {}", &audio_device);
- });
-
- handles.insert(device_id, handle);
- }
-
- handles.retain(|device_id, handle| {
- if handle.is_finished() {
- info!("Handle for device {} has finished", device_id);
- false
- } else {
- true
- }
- });
-
- while let Ok(mut transcription) = whisper_receiver.try_recv() {
- info!(
- "device {} received transcription {:?}",
- transcription.input.device, transcription.transcription
- );
-
- // Insert the new transcript after fetching
- let mut current_transcript: Option<String> = transcription.transcription.clone();
- let mut processed_previous: Option<String> = None;
- if let Some((previous, current)) =
- transcription.cleanup_overlap(previous_transcript.clone())
- {
- if !previous.is_empty() && !current.is_empty() {
- if previous != previous_transcript {
- processed_previous = Some(previous);
- }
- if current_transcript.is_some()
- && current != current_transcript.clone().unwrap_or_default()
- {
- current_transcript = Some(current);
- }
- }
- }
-
- transcription.transcription = current_transcript.clone();
- if current_transcript.is_some() {
- previous_transcript = current_transcript.unwrap();
- } else {
- continue;
- }
- // Process the audio result
- match process_audio_result(
- &db,
- transcription,
- audio_transcription_engine.clone(),
- processed_previous,
- previous_transcript_id,
- )
- .await
- {
- Err(e) => error!("Error processing audio result: {}", e),
- Ok(id) => previous_transcript_id = id,
- }
- }
-
- tokio::time::sleep(Duration::from_millis(100)).await;
- }
-}
-
-async fn process_audio_result(
- db: &DatabaseManager,
- result: TranscriptionResult,
- audio_transcription_engine: Arc<AudioTranscriptionEngine>,
- previous_transcript: Option<String>,
- previous_transcript_id: Option<i64>,
-) -> Result<Option<i64>, anyhow::Error> {
- if result.error.is_some() || result.transcription.is_none() {
- error!(
- "Error in audio recording: {}. Not inserting audio result",
- result.error.unwrap_or_default()
- );
- return Ok(None);
- }
-
- let speaker = get_or_create_speaker_from_embedding(db, &result.speaker_embedding).await?;
-
- info!("Detected speaker: {:?}", speaker);
-
- let transcription = result.transcription.unwrap();
- let transcription_engine = audio_transcription_engine.to_string();
- let mut chunk_id: Option<i64> = None;
-
- info!(
- "device {} inserting audio chunk: {:?}",
- result.input.device, result.path
- );
- if let Some(id) = previous_transcript_id {
- if let Some(prev_transcript) = previous_transcript {
- match db
- .update_audio_transcription(id, prev_transcript.as_str())
- .await
- {
- Ok(_) => {}
- Err(e) => error!(
- "Failed to update transcription for {}: audio_chunk_id {}",
- result.input.device, e
- ),
- }
- }
- }
- match db.get_or_insert_audio_chunk(&result.path).await {
- Ok(audio_chunk_id) => {
- if transcription.is_empty() {
- return Ok(Some(audio_chunk_id));
- }
-
- let offset_index = db
- .count_audio_transcriptions(audio_chunk_id)
- .await
- .unwrap_or(0);
-
- if let Err(e) = db
- .insert_audio_transcription(
- audio_chunk_id,
- &transcription,
- offset_index,
- &transcription_engine,
- &result.input.device,
- Some(speaker.id),
- Some(result.start_time),
- Some(result.end_time),
- )
- .await
- {
- error!(
- "Failed to insert audio transcription for device {}: {}",
- result.input.device, e
- );
- return Ok(Some(audio_chunk_id));
- } else {
- debug!(
- "Inserted audio transcription for chunk {} from device {} using {}",
- audio_chunk_id, result.input.device, transcription_engine
- );
- chunk_id = Some(audio_chunk_id);
- }
- }
- Err(e) => error!(
- "Failed to insert audio chunk for device {}: {}",
- result.input.device, e
- ),
- }
- Ok(chunk_id)
-}
-
-async fn get_or_create_speaker_from_embedding(
- db: &DatabaseManager,
- embedding: &[f32],
-) -> Result<Speaker, anyhow::Error> {
- let speaker = db.get_speaker_from_embedding(embedding).await?;
- if let Some(speaker) = speaker {
- Ok(speaker)
- } else {
- let speaker = db.insert_speaker(embedding).await?;
- Ok(speaker)
- }
-}
-
pub async fn merge_speakers(
db: &DatabaseManager,
speaker_to_keep_id: i64,
diff --git a/screenpipe-server/src/embedding/embedding_endpoint.rs b/screenpipe-server/src/embedding/embedding_endpoint.rs
index e6e9c83c9..84f071720 100644
--- a/screenpipe-server/src/embedding/embedding_endpoint.rs
+++ b/screenpipe-server/src/embedding/embedding_endpoint.rs
@@ -1,7 +1,7 @@
use axum::Json;
use oasgen::{oasgen, OaSchema};
use once_cell::sync::OnceCell;
-use screenpipe_core::model::EmbeddingModel;
+use screenpipe_core::embedding::model::EmbeddingModel;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::Mutex;
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index 389032440..98060f250 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -3,29 +3,19 @@ mod auto_destruct;
pub mod chunking;
pub mod cli;
pub mod core;
-pub mod db;
-pub mod db_types;
-pub mod embedding;
pub mod filtering;
-pub mod migration_worker;
pub mod pipe_manager;
mod resource_monitor;
mod server;
pub mod text_embeds;
mod video;
pub mod video_cache;
-mod video_db;
pub mod video_utils;
pub use add::handle_index_command;
pub use auto_destruct::watch_pid;
pub use axum::Json as JsonResponse;
pub use cli::Cli;
pub use core::start_continuous_recording;
-pub use db::DatabaseManager;
-pub use migration_worker::{
- create_migration_worker, MigrationCommand, MigrationConfig, MigrationResponse, MigrationStatus,
- MigrationWorker,
-};
pub use pipe_manager::PipeManager;
pub use resource_monitor::{ResourceMonitor, RestartSignal};
pub use screenpipe_core::Language;
@@ -37,3 +27,4 @@ pub use server::PaginatedResponse;
pub use server::SCServer;
pub use server::{api_list_monitors, MonitorInfo};
pub use video::VideoCapture;
+pub mod embedding;
diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rs
index 721bbfa64..cd890436f 100644
--- a/screenpipe-server/src/pipe_manager.rs
+++ b/screenpipe-server/src/pipe_manager.rs
@@ -234,7 +234,7 @@ impl PipeManager {
pipe_name: &str,
pipe_id: &str,
) -> Result<String> {
- let pipe_dir = download_pipe_private(&pipe_name, &url, self.screenpipe_dir.clone()).await?;
+ let pipe_dir = download_pipe_private(pipe_name, url, self.screenpipe_dir.clone()).await?;
let package_json_path = pipe_dir.join("package.json");
let version = if package_json_path.exists() {
diff --git a/screenpipe-server/src/resource_monitor.rs b/screenpipe-server/src/resource_monitor.rs
index d3342e4cb..4112b7209 100644
--- a/screenpipe-server/src/resource_monitor.rs
+++ b/screenpipe-server/src/resource_monitor.rs
@@ -14,7 +14,6 @@ use std::time::{Duration, Instant};
use sysinfo::{PidExt, ProcessExt, System, SystemExt};
use tracing::debug;
use tracing::{error, info, warn};
-use uuid;
pub struct ResourceMonitor {
start_time: Instant,
@@ -302,7 +301,7 @@ impl ResourceMonitor {
}
}
- if let Some(_) = &self.posthog_client {
+ if self.posthog_client.is_some() {
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index b8832e617..020baa2f3 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -11,6 +11,10 @@ use axum::{
};
use oasgen::{oasgen, OaSchema, Server};
+use screenpipe_db::{
+ ContentType, DatabaseManager, FrameData, Order, SearchMatch, SearchResult, Speaker,
+ TagContentType,
+};
use tokio_util::io::ReaderStream;
use tokio::fs::File;
@@ -22,22 +26,22 @@ use futures::{
use image::ImageFormat::{self};
use screenpipe_events::{send_event, subscribe_to_all_events, Event as ScreenpipeEvent};
-use crate::video_utils::extract_frame;
use crate::{
- db_types::{ContentType, FrameData, Order, SearchMatch, SearchResult, Speaker, TagContentType},
embedding::embedding_endpoint::create_embeddings,
- pipe_manager::PipeManager,
video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},
video_cache::{AudioEntry, DeviceFrame, FrameCache, FrameMetadata, TimeSeriesFrame},
video_utils::{
- extract_frame_from_video, extract_high_quality_frame, merge_videos, validate_media,
- MergeVideosRequest, MergeVideosResponse, ValidateMediaParams,
+ extract_frame, extract_frame_from_video, extract_high_quality_frame, merge_videos,
+ validate_media, MergeVideosRequest, MergeVideosResponse, ValidateMediaParams,
},
- DatabaseManager,
+ PipeManager,
};
use chrono::{DateTime, Utc};
use screenpipe_audio::{
- default_input_device, default_output_device, list_audio_devices, AudioDevice, DeviceType,
+ audio_manager::AudioManager,
+ core::device::{
+ default_input_device, default_output_device, list_audio_devices, AudioDevice, DeviceType,
+ },
};
use tracing::{debug, error, info};
@@ -67,16 +71,15 @@ use tower_http::{cors::CorsLayer, trace::DefaultMakeSpan};
// At the top of the file, add:
#[cfg(feature = "experimental")]
use enigo::{Enigo, Key, Settings};
-
-use screenpipe_audio::LAST_AUDIO_CAPTURE;
-
use std::str::FromStr;
use crate::text_embeds::generate_embedding;
+pub type FrameImageCache = LruCache<i64, (String, Instant)>;
+
pub struct AppState {
pub db: Arc<DatabaseManager>,
- // pub device_manager: Arc<DeviceManager>,
+ pub audio_manager: Arc<AudioManager>,
pub app_start_time: DateTime<Utc>,
pub screenpipe_dir: PathBuf,
pub pipe_manager: Arc<PipeManager>,
@@ -84,7 +87,7 @@ pub struct AppState {
pub audio_disabled: bool,
pub ui_monitoring_enabled: bool,
pub frame_cache: Option<Arc<FrameCache>>,
- pub frame_image_cache: Option<Arc<Mutex<LruCache<i64, (String, Instant)>>>>,
+ pub frame_image_cache: Option<Arc<Mutex<FrameImageCache>>>,
}
// Update the SearchQuery struct
@@ -383,7 +386,7 @@ pub(crate) async fn search(
offset_index: audio.offset_index,
tags: audio.tags.clone(),
device_name: audio.device_name.clone(),
- device_type: audio.device_type.clone(),
+ device_type: audio.device_type.clone().into(),
speaker: audio.speaker.clone(),
start_time: audio.start_time,
end_time: audio.end_time,
@@ -588,7 +591,7 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
let app_uptime = (now as i64) - (state.app_start_time.timestamp());
let grace_period = 120; // 2 minutes in seconds
- let last_capture = LAST_AUDIO_CAPTURE.load(Ordering::Relaxed);
+ let last_capture = screenpipe_audio::core::LAST_AUDIO_CAPTURE.load(Ordering::Relaxed);
let audio_active = if app_uptime < grace_period {
true // Consider active during grace period
} else {
@@ -932,7 +935,7 @@ async fn list_pipes_handler(State(state): State<Arc<AppState>>) -> JsonResponse<
pub struct SCServer {
db: Arc<DatabaseManager>,
addr: SocketAddr,
- // device_manager: Arc<DeviceManager>,
+ audio_manager: Arc<AudioManager>,
screenpipe_dir: PathBuf,
pipe_manager: Arc<PipeManager>,
vision_disabled: bool,
@@ -950,6 +953,7 @@ impl SCServer {
vision_disabled: bool,
audio_disabled: bool,
ui_monitoring_enabled: bool,
+ audio_manager: Arc<AudioManager>,
) -> Self {
SCServer {
db,
@@ -959,16 +963,39 @@ impl SCServer {
vision_disabled,
audio_disabled,
ui_monitoring_enabled,
+ audio_manager,
}
}
pub async fn start(self, enable_frame_cache: bool) -> Result<(), std::io::Error> {
+ // Create the OpenAPI server
+ let app = self.create_router(enable_frame_cache).await;
+
+ #[cfg(feature = "experimental")]
+ let app = app.route("/experimental/input_control", post(input_control_handler));
+
+ // Create the listener
+ let listener = TcpListener::bind(&self.addr).await?;
+ info!("Server listening on {}", self.addr);
+
+ // Start serving
+ serve(
+ listener,
+ app.into_make_service_with_connect_info::<SocketAddr>(),
+ )
+ .await
+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
+
+ Ok(())
+ }
+
+ pub async fn create_router(&self, enable_frame_cache: bool) -> Router {
let app_state = Arc::new(AppState {
db: self.db.clone(),
- // device_manager: self.device_manager.clone(),
+ audio_manager: self.audio_manager.clone(),
app_start_time: Utc::now(),
screenpipe_dir: self.screenpipe_dir.clone(),
- pipe_manager: self.pipe_manager,
+ pipe_manager: self.pipe_manager.clone(),
vision_disabled: self.vision_disabled,
audio_disabled: self.audio_disabled,
ui_monitoring_enabled: self.ui_monitoring_enabled,
@@ -998,8 +1025,6 @@ impl SCServer {
axum::http::header::CONTENT_TYPE,
axum::http::header::CACHE_CONTROL,
]);
-
- // Create the OpenAPI server
let server = Server::axum()
.get("/search", search)
.get("/audio/list", api_list_audio_devices)
@@ -1029,12 +1054,14 @@ impl SCServer {
.get("/speakers/similar", get_similar_speakers_handler)
.post("/experimental/frames/merge", merge_frames_handler)
.get("/experimental/validate/media", validate_media_handler)
- // .post("/audio/start", start_audio_device)
- // .post("/audio/stop", stop_audio_device)
+ .post("/audio/start", start_audio)
+ .post("/audio/stop", stop_audio)
.get("/semantic-search", semantic_search_handler)
.get("/pipes/build-status/:pipe_id", get_pipe_build_status)
.get("/search/keyword", keyword_search_handler)
.post("/v1/embeddings", create_embeddings)
+ .post("/audio/device/start", start_audio_device)
+ .post("/audio/device/stop", stop_audio_device)
// .post("/vision/start", start_vision_device)
// .post("/vision/stop", stop_vision_device)
// .post("/audio/restart", restart_audio_devices)
@@ -1044,7 +1071,7 @@ impl SCServer {
.freeze();
// Build the main router with all routes
- let app = Router::new()
+ Router::new()
.merge(server.into_router())
// NOTE: websockerts and sse is not supported by openapi so we move it down here
.route("/stream/frames", get(stream_frames_handler))
@@ -1053,24 +1080,7 @@ impl SCServer {
.route("/frames/export", get(handle_video_export_ws))
.with_state(app_state)
.layer(cors)
- .layer(TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::default()));
-
- #[cfg(feature = "experimental")]
- let app = app.route("/experimental/input_control", post(input_control_handler));
-
- // Create the listener
- let listener = TcpListener::bind(&self.addr).await?;
- info!("Server listening on {}", self.addr);
-
- // Start serving
- serve(
- listener,
- app.into_make_service_with_connect_info::<SocketAddr>(),
- )
- .await
- .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
-
- Ok(())
+ .layer(TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::default()))
}
}
@@ -1202,7 +1212,7 @@ async fn add_frame_to_db(
frame_id,
&ocr.text,
ocr.text_json.as_deref().unwrap_or(""),
- Arc::new(OcrEngine::default()), // Ideally could pass any str as ocr_engine since can be run outside of screenpipe
+ Arc::new(OcrEngine::default().into()), // Ideally could pass any str as ocr_engine since can be run outside of screenpipe
)
.await?;
}
@@ -1253,11 +1263,6 @@ async fn add_transcription_to_db(
) -> Result<(), anyhow::Error> {
let db = &state.db;
- let device = AudioDevice {
- name: device_name.to_string(),
- device_type: DeviceType::Input,
- };
-
let dummy_audio_chunk_id = db.insert_audio_chunk("").await?;
db.insert_audio_transcription(
@@ -1265,7 +1270,10 @@ async fn add_transcription_to_db(
&transcription.transcription,
-1,
&transcription.transcription_engine,
- &device,
+ &screenpipe_db::AudioDevice {
+ name: device_name.to_string(),
+ device_type: DeviceType::Input.into(),
+ },
None,
None,
None,
@@ -1761,7 +1769,7 @@ async fn get_similar_speakers_handler(
// device_type: Option<DeviceType>,
// }
-#[derive(Serialize)]
+#[derive(Debug, OaSchema, Serialize)]
pub struct AudioDeviceControlResponse {
success: bool,
message: String,
@@ -1873,7 +1881,7 @@ struct SemanticSearchQuery {
async fn semantic_search_handler(
Query(query): Query<SemanticSearchQuery>,
State(state): State<Arc<AppState>>,
-) -> Result<JsonResponse<Vec<crate::db_types::OCRResult>>, (StatusCode, JsonResponse<Value>)> {
+) -> Result<JsonResponse<Vec<screenpipe_db::OCRResult>>, (StatusCode, JsonResponse<Value>)> {
let limit = query.limit.unwrap_or(10);
let threshold = query.threshold.unwrap_or(0.3);
@@ -2092,6 +2100,71 @@ pub struct VideoExportRequest {
fps: f64,
}
+#[derive(OaSchema, Debug, Deserialize)]
+#[serde(rename_all = "snake_case")]
+struct AudioDeviceControlRequest {
+ device_name: String,
+}
+
+#[oasgen]
+async fn start_audio_device(
+ State(state): State<Arc<AppState>>,
+ Json(payload): Json<AudioDeviceControlRequest>,
+) -> Result<Json<AudioDeviceControlResponse>, (StatusCode, JsonResponse<Value>)> {
+ let device_name = payload.device_name.clone();
+ let device: AudioDevice;
+ // todo Better handling error
+ match AudioDevice::from_name(&payload.device_name) {
+ Ok(audio_device) => device = audio_device,
+ Err(e) => {
+ return Err((
+ StatusCode::UNPROCESSABLE_ENTITY,
+ JsonResponse(
+ json!({"success": false, "message": format!("device {} not found: {}", device_name.clone(), e)}),
+ ),
+ ))
+ }
+ };
+
+ if let Err(e) = state.audio_manager.start_device(&device).await {
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({
+ "success": false,
+ "message": format!("Failed to start recording device {}: {}", device_name.clone(), e)
+ })),
+ ));
+ }
+
+ Ok(Json(AudioDeviceControlResponse {
+ success: true,
+ message: format!("started device: {}", device_name),
+ }))
+}
+
+#[oasgen]
+async fn stop_audio_device(
+ State(state): State<Arc<AppState>>,
+ Json(payload): Json<AudioDeviceControlRequest>,
+) -> Result<Json<AudioDeviceControlResponse>, (StatusCode, JsonResponse<Value>)> {
+ let device_name = payload.device_name.clone();
+
+ if let Err(e) = state.audio_manager.stop_device(&device_name).await {
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({
+ "success": false,
+ "message": format!("Failed to stop recording device {}: {}", device_name.clone(), e)
+ })),
+ ));
+ }
+
+ Ok(Json(AudioDeviceControlResponse {
+ success: true,
+ message: format!("stopped recording audio device: {}", device_name),
+ }))
+}
+
fn deserialize_frame_ids<'de, D>(deserializer: D) -> Result<Vec<i64>, D::Error>
where
D: serde::Deserializer<'de>,
@@ -2108,6 +2181,38 @@ struct ExportProgress {
error: Option<String>,
}
+#[oasgen]
+async fn start_audio(
+ State(state): State<Arc<AppState>>,
+) -> Result<Response, (StatusCode, JsonResponse<Value>)> {
+ match state.audio_manager.start().await {
+ Ok(_) => Ok(Response::builder().status(200).body(Body::empty()).unwrap()),
+ Err(e) => Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({
+ "success": false,
+ "message": format!("Failed to start audio processing: {}", e),
+ })),
+ )),
+ }
+}
+
+#[oasgen]
+async fn stop_audio(
+ State(state): State<Arc<AppState>>,
+) -> Result<Response, (StatusCode, JsonResponse<Value>)> {
+ match state.audio_manager.stop().await {
+ Ok(_) => Ok(Response::builder().status(200).body(Body::empty()).unwrap()),
+ Err(e) => Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({
+ "success": false,
+ "message": format!("Failed to start audio processing: {}", e),
+ })),
+ )),
+ }
+}
+
pub async fn handle_video_export_ws(
ws: WebSocketUpgrade,
State(state): State<Arc<AppState>>,
diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rs
index c3e9709ff..0de526a32 100644
--- a/screenpipe-server/src/video_cache.rs
+++ b/screenpipe-server/src/video_cache.rs
@@ -3,6 +3,7 @@ use bincode;
use chrono::{DateTime, Duration, Utc};
use dirs::cache_dir;
use screenpipe_core::find_ffmpeg_path;
+use screenpipe_db::{DatabaseManager, FrameData, OCREntry};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, HashMap};
@@ -15,9 +16,6 @@ use tokio::sync::mpsc::Sender;
use tokio::sync::{mpsc, oneshot};
use tracing::{debug, error};
-use crate::db_types::{FrameData, OCREntry};
-use crate::DatabaseManager;
-
type FrameChannel = mpsc::Sender<TimeSeriesFrame>;
#[derive(Debug, Clone)]
@@ -45,8 +43,8 @@ pub struct AudioEntry {
pub duration_secs: f64,
}
-impl From<crate::db_types::AudioEntry> for AudioEntry {
- fn from(db_entry: crate::db_types::AudioEntry) -> Self {
+impl From<screenpipe_db::AudioEntry> for AudioEntry {
+ fn from(db_entry: screenpipe_db::AudioEntry) -> Self {
Self {
transcription: db_entry.transcription,
device_name: db_entry.device_name,
diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rs
index 4f0b4c540..b668e8aca 100644
--- a/screenpipe-server/src/video_utils.rs
+++ b/screenpipe-server/src/video_utils.rs
@@ -5,6 +5,7 @@ use chrono::{DateTime, Utc};
use image::DynamicImage;
use oasgen::OaSchema;
use screenpipe_core::find_ffmpeg_path;
+use screenpipe_db::VideoMetadata as DBVideoMetadata;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::path::PathBuf;
@@ -501,6 +502,18 @@ pub struct VideoMetadata {
pub name: Option<String>,
}
+impl From<VideoMetadata> for DBVideoMetadata {
+ fn from(metadata: VideoMetadata) -> Self {
+ DBVideoMetadata {
+ creation_time: metadata.creation_time,
+ fps: metadata.fps,
+ duration: metadata.duration,
+ device_name: metadata.device_name,
+ name: metadata.name,
+ }
+ }
+}
+
#[derive(Debug, Deserialize)]
pub struct VideoMetadataOverrides {
pub overrides: Vec<VideoMetadataItem>,
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
index 328300d1d..9d55d40b6 100644
--- a/screenpipe-server/tests/endpoint_test.rs
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -6,21 +6,16 @@ mod tests {
use axum::Router;
use chrono::DateTime;
use chrono::{Duration, Utc};
- use lru::LruCache;
- use screenpipe_audio::{AudioDevice, DeviceType};
- use screenpipe_server::db_types::ContentType;
- use screenpipe_server::db_types::SearchResult;
- use screenpipe_server::video_cache::FrameCache;
+ use screenpipe_audio::audio_manager::AudioManagerBuilder;
+ use screenpipe_db::{ContentType, DatabaseManager, SearchResult};
use screenpipe_server::PipeManager;
- use screenpipe_server::{
- create_router, AppState, ContentItem, DatabaseManager, PaginatedResponse,
- };
+ use screenpipe_server::SCServer;
+ use screenpipe_server::{ContentItem, PaginatedResponse};
use screenpipe_vision::OcrEngine; // Adjust this import based on your actual module structure
use serde::Deserialize;
- use std::num::NonZeroUsize;
+ use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
- use tokio::sync::Mutex;
use tower::ServiceExt; // for `oneshot` and `ready`
// Before the test function, add:
@@ -28,35 +23,41 @@ mod tests {
struct TestErrorResponse {
error: String,
}
- async fn setup_test_app() -> (Router, Arc<AppState>) {
+ // Add this function to initialize the logger
+ fn init() {
+ let _ = env_logger::builder().is_test(true).try_init();
+ }
+
+ async fn setup_test_app() -> (Router, Arc<DatabaseManager>) {
let db = Arc::new(DatabaseManager::new("sqlite::memory:").await.unwrap());
- let app_state = Arc::new(AppState {
- db: db.clone(),
- app_start_time: Utc::now(),
- screenpipe_dir: PathBuf::from(""),
- pipe_manager: Arc::new(PipeManager::new(PathBuf::from(""))),
- vision_disabled: false,
- audio_disabled: false,
- frame_cache: Some(Arc::new(
- FrameCache::new(PathBuf::from(""), db).await.unwrap(),
- )),
- ui_monitoring_enabled: false,
- frame_image_cache: Some(Arc::new(Mutex::new(LruCache::new(
- NonZeroUsize::new(100).unwrap(),
- )))),
- });
-
- let router = create_router();
- let app = router.with_state(app_state.clone());
-
- (app, app_state)
+ let audio_manager = Arc::new(
+ AudioManagerBuilder::new()
+ .output_path("/tmp/screenpipe".into())
+ .build(db.clone())
+ .await
+ .unwrap(),
+ );
+
+ let app = SCServer::new(
+ db.clone(),
+ SocketAddr::from(([127, 0, 0, 1], 23948)),
+ PathBuf::from(""),
+ Arc::new(PipeManager::new(PathBuf::from(""))),
+ false,
+ false,
+ false,
+ audio_manager,
+ );
+
+ let router = app.create_router(true).await;
+ init();
+ (router, db)
}
#[tokio::test]
async fn test_search_audio_with_length_constraints() {
- let (app, state) = setup_test_app().await;
- let db = &state.db;
+ let (app, db) = setup_test_app().await;
// Insert some test data
let _ = db.insert_audio_chunk("test_audio1.wav").await.unwrap();
@@ -69,7 +70,10 @@ mod tests {
"Short",
0,
"",
- &AudioDevice::new("test1".to_string(), DeviceType::Input),
+ &screenpipe_db::AudioDevice {
+ name: "test1".to_string(),
+ device_type: screenpipe_db::DeviceType::Input,
+ },
None,
None,
None,
@@ -83,7 +87,10 @@ mod tests {
"This is a longer transcription with more words",
0,
"",
- &AudioDevice::new("test2".to_string(), DeviceType::Input),
+ &screenpipe_db::AudioDevice {
+ name: "test2".to_string(),
+ device_type: screenpipe_db::DeviceType::Input,
+ },
None,
None,
None,
@@ -164,8 +171,7 @@ mod tests {
#[tokio::test]
#[ignore]
async fn test_count_search_results() {
- let (_, state) = setup_test_app().await;
- let db = &state.db;
+ let (_, db) = setup_test_app().await;
// Insert test data with known lengths:
let _ = db
@@ -184,7 +190,7 @@ mod tests {
frame_id1,
"This is a test OCR text", // 21 chars
"",
- Arc::new(OcrEngine::Tesseract),
+ Arc::new(OcrEngine::Tesseract.into()),
)
.await
.unwrap();
@@ -192,7 +198,7 @@ mod tests {
frame_id2,
"Another OCR text for testing that should be longer than thirty characters", // >30 chars
"",
- Arc::new(OcrEngine::Tesseract),
+ Arc::new(OcrEngine::Tesseract.into()),
)
.await
.unwrap();
@@ -205,7 +211,10 @@ mod tests {
"This is a test audio transcription that should definitely be longer than thirty characters", // >30 chars
0,
"",
- &AudioDevice::new("test1".to_string(), DeviceType::Input),
+ &screenpipe_db::AudioDevice {
+ name: "test1".to_string(),
+ device_type: screenpipe_db::DeviceType::Input,
+ },
None,
None,
None,
@@ -218,7 +227,10 @@ mod tests {
"Short audio", // <30 chars
0,
"",
- &AudioDevice::new("test2".to_string(), DeviceType::Input),
+ &screenpipe_db::AudioDevice {
+ name: "test2".to_string(),
+ device_type: screenpipe_db::DeviceType::Input,
+ },
None,
None,
None,
@@ -369,8 +381,7 @@ mod tests {
#[tokio::test]
async fn test_search_with_time_constraints() {
- let (_, state) = setup_test_app().await;
- let db = &state.db;
+ let (_, db) = setup_test_app().await;
// insert test data with different timestamps
let _ = db
@@ -401,7 +412,7 @@ mod tests {
frame_id1,
"old ocr text",
"",
- Arc::new(OcrEngine::Tesseract),
+ Arc::new(OcrEngine::Tesseract.into()),
)
.await
.unwrap();
@@ -412,7 +423,10 @@ mod tests {
"old audio transcription",
0,
"",
- &AudioDevice::new("test".to_string(), DeviceType::Input),
+ &screenpipe_db::AudioDevice {
+ name: "test".to_string(),
+ device_type: screenpipe_db::DeviceType::Input,
+ },
None,
None,
None,
@@ -564,8 +578,7 @@ mod tests {
#[tokio::test]
async fn test_recent_tasks_no_bleeding() {
- let (_, state) = setup_test_app().await;
- let db = &state.db;
+ let (_, db) = setup_test_app().await;
// Setup test data with different timestamps
let now = Utc::now();
@@ -611,7 +624,7 @@ mod tests {
old_frame_id,
"old task: write documentation",
"",
- Arc::new(OcrEngine::Tesseract),
+ Arc::new(OcrEngine::Tesseract.into()),
)
.await
.unwrap();
@@ -620,7 +633,7 @@ mod tests {
recent_frame_id,
"current task: fix bug #123",
"",
- Arc::new(OcrEngine::Tesseract),
+ Arc::new(OcrEngine::Tesseract.into()),
)
.await
.unwrap();
diff --git a/screenpipe-server/tests/index_test.rs b/screenpipe-server/tests/index_test.rs
index a6a5522b7..a375338e1 100644
--- a/screenpipe-server/tests/index_test.rs
+++ b/screenpipe-server/tests/index_test.rs
@@ -5,7 +5,8 @@ use std::{
use anyhow::Result;
use dirs::home_dir;
-use screenpipe_server::{cli::OutputFormat, handle_index_command, DatabaseManager};
+use screenpipe_db::DatabaseManager;
+use screenpipe_server::{cli::OutputFormat, handle_index_command};
use tempfile::tempdir;
use tokio::fs;
use tracing::debug;
@@ -72,7 +73,7 @@ async fn test_index_command_with_sql() -> Result<()> {
None,
db.clone(),
OutputFormat::Text,
- None,
+ Some(screenpipe_server::cli::CliOcrEngine::Custom),
None,
false,
false,
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index 8010ecdac..309000bb4 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -3,55 +3,53 @@ use axum::{
http::{Request, StatusCode},
Router,
};
-use chrono::Utc;
-use lru::LruCache;
-use screenpipe_audio::{AudioDevice, DeviceType};
+use screenpipe_audio::audio_manager::AudioManagerBuilder;
use screenpipe_vision::OcrEngine;
use serde_json::json;
-use std::{num::NonZeroUsize, path::PathBuf, sync::Arc};
-use tokio::sync::Mutex;
+use std::{net::SocketAddr, path::PathBuf, sync::Arc};
use tower::ServiceExt;
-use screenpipe_server::{
- create_router, video_cache::FrameCache, AppState, ContentItem, DatabaseManager,
- PaginatedResponse, PipeManager,
-};
+use screenpipe_db::DatabaseManager;
+use screenpipe_server::{ContentItem, PaginatedResponse, PipeManager, SCServer};
// Add this function to initialize the logger
fn init() {
let _ = env_logger::builder().is_test(true).try_init();
}
-async fn setup_test_app() -> (Router, Arc<AppState>) {
+async fn setup_test_app() -> (Router, Arc<DatabaseManager>) {
let db = Arc::new(DatabaseManager::new("sqlite::memory:").await.unwrap());
- let app_state = Arc::new(AppState {
- db: db.clone(),
- vision_disabled: false,
- audio_disabled: false,
- app_start_time: Utc::now(),
- screenpipe_dir: PathBuf::from(""),
- pipe_manager: Arc::new(PipeManager::new(PathBuf::from(""))),
- frame_cache: Some(Arc::new(
- FrameCache::new(PathBuf::from(""), db).await.unwrap(),
- )),
- ui_monitoring_enabled: false,
- frame_image_cache: Some(Arc::new(Mutex::new(LruCache::new(
- NonZeroUsize::new(100).unwrap(),
- )))),
- });
-
- let app = create_router().with_state(app_state.clone());
+ let audio_manager = Arc::new(
+ AudioManagerBuilder::new()
+ .output_path("/tmp/screenpipe".into())
+ .build(db.clone())
+ .await
+ .unwrap(),
+ );
+
+ let app = SCServer::new(
+ db.clone(),
+ SocketAddr::from(([127, 0, 0, 1], 23948)),
+ PathBuf::from(""),
+ Arc::new(PipeManager::new(PathBuf::from(""))),
+ false,
+ false,
+ false,
+ audio_manager,
+ );
+
+ let router = app.create_router(true).await;
init();
- (app, app_state)
+ (router, db)
}
#[tokio::test]
async fn test_add_tags_and_search() {
- let (app, app_state) = setup_test_app().await;
+ let (app, db) = setup_test_app().await;
// Insert test data
- insert_test_data(&app_state.db).await;
+ insert_test_data(&db).await;
// Test adding tags to vision content
let vision_response = app
@@ -159,8 +157,8 @@ async fn test_add_tags_and_search() {
#[tokio::test]
async fn test_add_multiple_tags_to_single_item() {
- let (app, app_state) = setup_test_app().await;
- insert_test_data(&app_state.db).await;
+ let (app, db) = setup_test_app().await;
+ insert_test_data(&db).await;
let response = app
.clone()
@@ -211,8 +209,8 @@ async fn test_add_multiple_tags_to_single_item() {
#[tokio::test]
async fn test_remove_tags() {
- let (app, app_state) = setup_test_app().await;
- insert_test_data(&app_state.db).await;
+ let (app, db) = setup_test_app().await;
+ insert_test_data(&db).await;
// Add tags
app.clone()
@@ -281,8 +279,8 @@ async fn test_remove_tags() {
#[tokio::test]
async fn test_search_by_multiple_tags() {
- let (app, app_state) = setup_test_app().await;
- insert_test_data(&app_state.db).await;
+ let (app, db) = setup_test_app().await;
+ insert_test_data(&db).await;
// Add tags to multiple items
app.clone()
@@ -382,7 +380,7 @@ async fn insert_test_data(db: &Arc<DatabaseManager>) {
frame_id,
"Test OCR text",
"{'text': 'Test OCR text', 'confidence': 0.9}",
- Arc::new(OcrEngine::Tesseract),
+ Arc::new(OcrEngine::Tesseract.into()),
)
.await
.unwrap();
@@ -396,7 +394,10 @@ async fn insert_test_data(db: &Arc<DatabaseManager>) {
"Test audio transcription",
0,
"test_engine",
- &AudioDevice::new("test".to_string(), DeviceType::Output),
+ &screenpipe_db::AudioDevice {
+ name: "test".to_string(),
+ device_type: screenpipe_db::DeviceType::Output,
+ },
None,
None,
None,
diff --git a/screenpipe-server/tests/video_cache_test.rs b/screenpipe-server/tests/video_cache_test.rs
index 5e64061a6..f29a43f10 100644
--- a/screenpipe-server/tests/video_cache_test.rs
+++ b/screenpipe-server/tests/video_cache_test.rs
@@ -4,7 +4,8 @@ use dirs::home_dir;
use std::sync::Arc;
use tracing::{debug, error};
-use screenpipe_server::{video_cache::FrameCache, DatabaseManager};
+use screenpipe_db::DatabaseManager;
+use screenpipe_server::video_cache::FrameCache;
async fn setup_test_env() -> Result<(FrameCache, Arc<DatabaseManager>)> {
// enabled tracing logging
@@ -566,15 +567,15 @@ async fn test_cache_cleanup() -> Result<()> {
// First, populate cache with some frames
let target_time = Utc::now() - Duration::minutes(5);
let (tx1, mut rx1) = tokio::sync::mpsc::channel(100);
-
+
println!("populating cache with initial frames...");
cache.get_frames(target_time, 10, tx1, true).await?;
-
+
let mut initial_frames = Vec::new();
while let Some(frame) = rx1.recv().await {
initial_frames.push(frame);
}
-
+
println!("initial cache population: {} frames", initial_frames.len());
// Wait for cleanup interval (we'll use a shorter interval for testing)
@@ -584,7 +585,7 @@ async fn test_cache_cleanup() -> Result<()> {
// Request frames again to verify cache state
let (tx2, mut rx2) = tokio::sync::mpsc::channel(100);
cache.get_frames(target_time, 10, tx2, true).await?;
-
+
let mut post_cleanup_frames = Vec::new();
while let Some(frame) = rx2.recv().await {
post_cleanup_frames.push(frame);
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index 55e4fde3a..78b071e03 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -37,6 +37,7 @@ screenpipe-events = { path = "../screenpipe-events" }
# Lanuage specification
screenpipe-core = { path = "../screenpipe-core" }
+screenpipe-db = { path = "../screenpipe-db" }
tracing-subscriber = { workspace = true }
tracing = { workspace = true }
diff --git a/screenpipe-vision/bin/ui_monitor b/screenpipe-vision/bin/ui_monitor
index 3f8f3ac92..4cd463d0f 100755
Binary files a/screenpipe-vision/bin/ui_monitor and b/screenpipe-vision/bin/ui_monitor differ
diff --git a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin
index 3f8f3ac92..4cd463d0f 100755
Binary files a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin and b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin differ
diff --git a/screenpipe-vision/src/custom_ocr.rs b/screenpipe-vision/src/custom_ocr.rs
index bfd077ecd..76588a7c8 100644
--- a/screenpipe-vision/src/custom_ocr.rs
+++ b/screenpipe-vision/src/custom_ocr.rs
@@ -21,6 +21,26 @@ impl Default for CustomOcrConfig {
}
}
+impl From<screenpipe_db::CustomOcrConfig> for CustomOcrConfig {
+ fn from(config: screenpipe_db::CustomOcrConfig) -> Self {
+ CustomOcrConfig {
+ api_url: config.api_url,
+ api_key: config.api_key,
+ timeout_ms: config.timeout_ms,
+ }
+ }
+}
+
+impl From<CustomOcrConfig> for screenpipe_db::CustomOcrConfig {
+ fn from(config: CustomOcrConfig) -> Self {
+ screenpipe_db::CustomOcrConfig {
+ api_url: config.api_url,
+ api_key: config.api_key,
+ timeout_ms: config.timeout_ms,
+ }
+ }
+}
+
pub async fn perform_ocr_custom(
image: &DynamicImage,
languages: Vec<Language>,
diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rs
index a3cea7102..3ff507712 100644
--- a/screenpipe-vision/src/utils.rs
+++ b/screenpipe-vision/src/utils.rs
@@ -7,6 +7,7 @@ use crate::monitor::SafeMonitor;
use image::DynamicImage;
use image_compare::{Algorithm, Metric, Similarity};
use log::{debug, error, warn};
+use screenpipe_db::CustomOcrConfig as DBCustomOcrConfig;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::time::{Duration, Instant};
@@ -20,6 +21,32 @@ pub enum OcrEngine {
Custom(CustomOcrConfig),
}
+impl From<OcrEngine> for screenpipe_db::OcrEngine {
+ fn from(val: OcrEngine) -> Self {
+ match val {
+ OcrEngine::Unstructured => screenpipe_db::OcrEngine::Unstructured,
+ OcrEngine::Tesseract => screenpipe_db::OcrEngine::Tesseract,
+ OcrEngine::WindowsNative => screenpipe_db::OcrEngine::WindowsNative,
+ OcrEngine::AppleNative => screenpipe_db::OcrEngine::AppleNative,
+ OcrEngine::Custom(config) => {
+ screenpipe_db::OcrEngine::Custom(DBCustomOcrConfig::from(config))
+ }
+ }
+ }
+}
+
+impl From<screenpipe_db::OcrEngine> for OcrEngine {
+ fn from(engine: screenpipe_db::OcrEngine) -> Self {
+ match engine {
+ screenpipe_db::OcrEngine::Unstructured => OcrEngine::Unstructured,
+ screenpipe_db::OcrEngine::Tesseract => OcrEngine::Tesseract,
+ screenpipe_db::OcrEngine::WindowsNative => OcrEngine::WindowsNative,
+ screenpipe_db::OcrEngine::AppleNative => OcrEngine::AppleNative,
+ screenpipe_db::OcrEngine::Custom(config) => OcrEngine::Custom(config.into()),
+ }
+ }
+}
+
pub fn calculate_hash(image: &DynamicImage) -> u64 {
let mut hasher = DefaultHasher::new();
image.as_bytes().hash(&mut hasher);
diff --git a/screenpipe-vision/tests/windows_vision_test.rs b/screenpipe-vision/tests/windows_vision_test.rs
index 7bea59ec6..13de1cc59 100644
--- a/screenpipe-vision/tests/windows_vision_test.rs
+++ b/screenpipe-vision/tests/windows_vision_test.rs
@@ -1,9 +1,11 @@
#[cfg(target_os = "windows")]
#[cfg(test)]
mod tests {
+ use screenpipe_vision::capture_screenshot_by_window::{CapturedWindow, WindowFilters};
use screenpipe_vision::core::OcrTaskData;
use screenpipe_vision::monitor::get_default_monitor;
use screenpipe_vision::{process_ocr_task, OcrEngine};
+ use std::sync::Arc;
use std::{path::PathBuf, time::Instant};
use tokio::sync::mpsc;
@@ -27,12 +29,13 @@ mod tests {
let (tx, _rx) = mpsc::channel(1);
let ocr_engine = OcrEngine::WindowsNative;
- let window_images = vec![(
- image.clone(),
- "test_app".to_string(),
- "test_window".to_string(),
- true,
- )];
+ let window_images = vec![CapturedWindow {
+ app_name: "test_app".to_string(),
+ window_name: "test_window".to_string(),
+ image,
+ is_focused: true,
+ process_id: 1234,
+ }];
let result = process_ocr_task(
OcrTaskData {
@@ -42,8 +45,8 @@ mod tests {
timestamp,
result_tx: tx,
},
- false,
&ocr_engine,
+ vec![],
)
.await;
@@ -64,6 +67,7 @@ mod tests {
let interval = Duration::from_millis(1000);
let save_text_files_flag = false;
let ocr_engine = OcrEngine::WindowsNative;
+ let window_filters = Arc::new(WindowFilters::new(&[], &[]));
// Spawn the continuous_capture function with corrected parameter order
let capture_handle = tokio::spawn(continuous_capture(
@@ -71,8 +75,8 @@ mod tests {
interval,
ocr_engine,
monitor,
- vec![], // window filters as empty vec
- vec![], // languages as empty vec
+ window_filters, // window filters as empty vec
+ vec![], // languages as empty vec
save_text_files_flag,
));