YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
Remove whisper Support for streaming (#1161)
Ezra Elletted7d9ab3fc66c
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rsindex ba0e8e266..02059d3ef 100644--- a/screenpipe-audio/src/core.rs+++ b/screenpipe-audio/src/core.rs@@ -204,7 +204,6 @@ pub async fn record_and_transcribe(pub async fn start_realtime_recording(audio_stream: Arc<AudioStream>,- realtime_transcription_engine: Arc<AudioTranscriptionEngine>,languages: Vec<Language>,is_running: Arc<AtomicBool>,realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,@@ -213,7 +212,6 @@ pub async fn start_realtime_recording(while is_running.load(Ordering::Relaxed) {match realtime_stt(audio_stream.clone(),- realtime_transcription_engine.clone(),languages.clone(),realtime_transcription_sender.clone(),is_running.clone(),diff --git a/screenpipe-audio/src/deepgram/mod.rs b/screenpipe-audio/src/deepgram/mod.rsindex 6691d4597..c81843cd4 100644--- a/screenpipe-audio/src/deepgram/mod.rs+++ b/screenpipe-audio/src/deepgram/mod.rs@@ -1,6 +1,8 @@mod process_chunk;mod realtime;use lazy_static::lazy_static;+#[doc(hidden)]+pub use realtime::start_deepgram_stream;pub use realtime::stream_transcription_deepgram;use std::env;diff --git a/screenpipe-audio/src/deepgram/realtime.rs b/screenpipe-audio/src/deepgram/realtime.rsindex 7fad7e3a3..a5949fd5a 100644--- a/screenpipe-audio/src/deepgram/realtime.rs+++ b/screenpipe-audio/src/deepgram/realtime.rs@@ -1,7 +1,7 @@-use crate::DeviceType;use crate::{deepgram::CUSTOM_DEEPGRAM_API_TOKEN, realtime::RealtimeTranscriptionEvent, AudioStream,};+use crate::{AudioDevice, DeviceType};use anyhow::Result;use bytes::BufMut;use bytes::Bytes;@@ -10,15 +10,11 @@ use crossbeam::channel::RecvError;use deepgram::common::options::Encoding;use deepgram::common::stream_response::StreamResponse;use futures::channel::mpsc::{self, Receiver as FuturesReceiver};-use futures::stream::StreamExt;-use futures::SinkExt;+use futures::{SinkExt, TryStreamExt};use screenpipe_core::Language;-use serde_json::json;use std::sync::{atomic::AtomicBool, Arc};use std::time::Duration;-use tokio::join;use tokio::sync::broadcast::Receiver;-use tokio::time::sleep;use tracing::error;pub async fn stream_transcription_deepgram(@@ -29,7 +25,9 @@ pub async fn stream_transcription_deepgram(deepgram_api_key: Option<String>,) -> Result<()> {start_deepgram_stream(- stream,+ stream.subscribe().await,+ stream.device.clone(),+ stream.device_config.sample_rate().0,realtime_transcription_sender,is_running,languages,@@ -39,77 +37,65 @@ pub async fn stream_transcription_deepgram(Ok(())}-async fn start_deepgram_stream(- stream: Arc<AudioStream>,++pub async fn start_deepgram_stream(+ stream: Receiver<Vec<f32>>,+ device: Arc<AudioDevice>,+ sample_rate: u32,realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,is_running: Arc<AtomicBool>,_languages: Vec<Language>,deepgram_api_key: Option<String>,) -> Result<()> {- let sample_rate = stream.device_config.sample_rate().0;- let deepgram =- deepgram::Deepgram::new(deepgram_api_key.unwrap_or(CUSTOM_DEEPGRAM_API_TOKEN.to_string()))?;- let deepgram_transcription = deepgram.transcription();+ let api_key = deepgram_api_key.unwrap_or(CUSTOM_DEEPGRAM_API_TOKEN.to_string());- let audio_stream = stream.subscribe().await;+ if api_key.is_empty() {+ return Err(anyhow::anyhow!("Deepgram API key not found"));+ }++ let deepgram = deepgram::Deepgram::new(api_key)?;++ let deepgram_transcription = deepgram.transcription();let req = deepgram_transcription- .stream_request()+ .stream_request_with_options(+ deepgram::common::options::OptionsBuilder::new()+ .model(deepgram::common::options::Model::Nova2)+ .smart_format(true)+ .build(),+ ).keep_alive().channels(1).sample_rate(sample_rate).encoding(Encoding::Linear16);let mut handle = req.clone().handle().await?;- let is_running_handle = tokio::spawn({- async move {- while is_running.load(std::sync::atomic::Ordering::Relaxed) {- sleep(Duration::from_secs(1)).await;- }- handle.close_stream().await.unwrap();+ let mut results = req.stream(get_stream(stream)).await?;+ let realtime_transcription_sender_clone = realtime_transcription_sender.clone();+ let device_clone = device.clone();++ loop {+ if !is_running.load(std::sync::atomic::Ordering::SeqCst) {+ break;}- });- let mut results = req.stream(get_stream(audio_stream)).await?;-- while let Some(result) = results.next().await {- match result {- Ok(result) => {- if let StreamResponse::TranscriptResponse {- channel, is_final, ..- } = result- {- let res = channel.alternatives.first().unwrap();- let text = res.transcript.clone();- let is_input = stream.device.device_type == DeviceType::Input;-- match realtime_transcription_sender.send(RealtimeTranscriptionEvent {- timestamp: chrono::Utc::now(),- device: stream.device.to_string(),- transcription: json!({- "transcript": text- })- .to_string(),- is_final,- is_input,- }) {- Ok(_) => {}- Err(e) => {- if !e.to_string().contains("channel closed") {- error!("Error sending transcription event: {}", e);- }- }- }+ tokio::select! {+ result = results.try_next() => {+ if let Ok(Some(result)) = result {+ handle_transcription(+ result,+ realtime_transcription_sender_clone.clone(),+ device_clone.clone(),+ ).await;}}- Err(e) => {- error!("Error getting transcription: {}", e);+ _ = tokio::time::sleep(Duration::from_millis(100)) => {+ continue;}}}- join!(is_running_handle).0?;-+ handle.close_stream().await?;Ok(())}@@ -128,3 +114,35 @@ fn get_stream(mut stream: Receiver<Vec<f32>>) -> FuturesReceiver<Result<Bytes, Rrx}++async fn handle_transcription(+ result: StreamResponse,+ realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,+ device: Arc<AudioDevice>,+) {+ if let StreamResponse::TranscriptResponse {+ channel, is_final, ..+ } = result+ {+ let res = channel.alternatives.first().unwrap();+ let text = res.transcript.clone();+ let is_input = device.device_type == DeviceType::Input;++ if !text.is_empty() {+ match realtime_transcription_sender.send(RealtimeTranscriptionEvent {+ timestamp: chrono::Utc::now(),+ device: device.to_string(),+ transcription: text.to_string(),+ is_final,+ is_input,+ }) {+ Ok(_) => {}+ Err(e) => {+ if !e.to_string().contains("channel closed") {+ error!("Error sending transcription event: {}", e);+ }+ }+ }+ }+ }+}diff --git a/screenpipe-audio/src/realtime.rs b/screenpipe-audio/src/realtime.rsindex daf7b9e23..5baf1a6e8 100644--- a/screenpipe-audio/src/realtime.rs+++ b/screenpipe-audio/src/realtime.rs@@ -1,7 +1,4 @@-use crate::{- deepgram::stream_transcription_deepgram, whisper::stream_transcription_whisper, AudioStream,- AudioTranscriptionEngine,-};+use crate::{deepgram::stream_transcription_deepgram, AudioStream};use anyhow::Result;use chrono::{DateTime, Utc};use screenpipe_core::Language;@@ -10,46 +7,25 @@ use std::sync::{atomic::AtomicBool, Arc};pub async fn realtime_stt(stream: Arc<AudioStream>,- audio_transcription_engine: Arc<AudioTranscriptionEngine>,languages: Vec<Language>,realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,is_running: Arc<AtomicBool>,deepgram_api_key: Option<String>,) -> Result<()> {- // while is_running.load(Ordering::Relaxed) {- // realtime_transcription_sender.send(RealtimeTranscriptionEvent {- // timestamp: Utc::now(),- // device: stream.device.to_string(),- // transcription: "test".to_string(),- // });- // tokio::time::sleep(Duration::from_secs(1)).await;- // }- match *audio_transcription_engine {- AudioTranscriptionEngine::Deepgram => {- stream_transcription_deepgram(- stream,- realtime_transcription_sender,- languages,- is_running,- deepgram_api_key,- )- .await?;- }- _ => {- stream_transcription_whisper(- stream,- realtime_transcription_sender,- languages,- is_running,- audio_transcription_engine,- )- .await?;- }- }+ stream_transcription_deepgram(+ stream,+ realtime_transcription_sender,+ languages,+ is_running,+ deepgram_api_key,+ )+ .await?;+Ok(())}#[derive(Serialize, Clone)]+#[serde(rename_all = "camelCase")]pub struct RealtimeTranscriptionEvent {pub timestamp: DateTime<Utc>,pub device: String,diff --git a/screenpipe-audio/src/whisper/mod.rs b/screenpipe-audio/src/whisper/mod.rsindex a9577f07f..6ebe8da45 100644--- a/screenpipe-audio/src/whisper/mod.rs+++ b/screenpipe-audio/src/whisper/mod.rs@@ -1,9 +1,7 @@mod decoder;mod model;mod process_chunk;-mod realtime;pub use decoder::*;pub use model::*;pub use process_chunk::*;-pub use realtime::*;diff --git a/screenpipe-audio/src/whisper/realtime.rs b/screenpipe-audio/src/whisper/realtime.rsdeleted file mode 100644index 03a2e342c..000000000--- a/screenpipe-audio/src/whisper/realtime.rs+++ /dev/null@@ -1,126 +0,0 @@-use crate::{- multilingual, realtime::RealtimeTranscriptionEvent, resample, AudioStream,- AudioTranscriptionEngine, DeviceType,-};-use anyhow::Result;-use candle::{Device, Tensor};-use candle_transformers::models::whisper::audio;-use chrono::Utc;-use screenpipe_core::Language;-use std::sync::{atomic::AtomicBool, Arc};-use tokenizers::Tokenizer;-use tokio::sync::broadcast::Sender;--use super::{Decoder, WhisperModel};--pub async fn stream_transcription_whisper(- stream: Arc<AudioStream>,- realtime_transcription_sender: Arc<Sender<RealtimeTranscriptionEvent>>,- languages: Vec<Language>,- is_running: Arc<AtomicBool>,- transcription_engine: Arc<AudioTranscriptionEngine>,-) -> Result<()> {- let mut whisper_model = WhisperModel::new(&transcription_engine)?;- let mel_bytes = match whisper_model.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 model = &mut whisper_model.model;- let tokenizer = &whisper_model.tokenizer;- let device = &whisper_model.device;-- let mut dc = Decoder::new(model, tokenizer, 42, device, None, false, false)?;-- let mut audio_stream = stream.subscribe().await;- let sample_rate = stream.device_config.sample_rate().0;-- let mut audio_buffer: Vec<f32> = Vec::with_capacity(sample_rate as usize * 5);-- while let Ok(audio_data) = audio_stream.recv().await {- audio_buffer.extend_from_slice(&audio_data);-- if audio_buffer.len() >= sample_rate as usize * 5 {- let audio_chunk = audio_buffer- .drain(..sample_rate as usize * 5)- .collect::<Vec<f32>>();- let result = process_realtime_whisper(- &audio_chunk,- languages.clone(),- &mel_filters,- &mut dc,- tokenizer,- device,- sample_rate,- )- .await?;-- if !result.is_empty() {- let _ = realtime_transcription_sender.send(RealtimeTranscriptionEvent {- timestamp: Utc::now(),- device: stream.device.to_string(),- transcription: result,- is_final: true,- is_input: stream.device.device_type == DeviceType::Input,- });- }- }-- if !is_running.load(std::sync::atomic::Ordering::Relaxed) {- break;- }- }- Ok(())-}--pub async fn process_realtime_whisper(- audio: &[f32],- languages: Vec<Language>,- mel_filters: &[f32],- dc: &mut Decoder<'_>,- tokenizer: &Tokenizer,- device: &Device,- sample_rate: u32,-) -> Result<String> {- let audio = if sample_rate != candle_transformers::models::whisper::SAMPLE_RATE as u32 {- &resample(- audio,- sample_rate,- candle_transformers::models::whisper::SAMPLE_RATE as u32,- )?- } else {- audio- };-- let model = &mut dc.model;- let mel = audio::pcm_to_mel(model.config(), audio, mel_filters);- let mel_len = mel.len();-- let mel = Tensor::from_vec(- mel,- (- 1,- model.config().num_mel_bins,- mel_len / model.config().num_mel_bins,- ),- device,- )?;-- let language_token = multilingual::detect_language(model, tokenizer, &mel, languages.clone())?;-- dc.set_language_token(Some(language_token));-- let segments = dc.run(&mel)?;- dc.reset_kv_cache();-- let mut transcription = String::new();-- for segment in segments {- transcription.push_str(&segment.dr.text);- }-- Ok(transcription)-}diff --git a/screenpipe-audio/tests/realtime_test.rs b/screenpipe-audio/tests/realtime_test.rsnew file mode 100644index 000000000..f9a673603--- /dev/null+++ b/screenpipe-audio/tests/realtime_test.rs@@ -0,0 +1,74 @@+use screenpipe_audio::deepgram::start_deepgram_stream;+use screenpipe_audio::{pcm_decode, AudioDevice, DeviceType};+use std::{+ sync::{atomic::AtomicBool, Arc},+ time::Duration,+};+use tokio::sync::broadcast;++/// 1. Get sample audio from test_data/accuracy1.wav+/// 2. Stream audio from file+/// 3. Transcribe audio+/// 4. Assert that the transcription is correct+#[tokio::test]+#[ignore]+async fn test_realtime_transcription() {+ let (samples, sample_rate) = pcm_decode("test_data/accuracy1.wav").unwrap();++ let (stream_tx, stream_rx) = broadcast::channel(sample_rate as usize * 3);+ let device = AudioDevice::new("test".to_string(), DeviceType::Output);+ let is_running = Arc::new(AtomicBool::new(true));++ let deepgram_api_key = std::env::var("CUSTOM_DEEPGRAM_API_KEY").unwrap();++ let (realtime_transcription_sender, realtime_transcription_receiver) =+ broadcast::channel(10000);++ let is_running_clone = is_running.clone();++ tokio::spawn(async move {+ let _ = start_deepgram_stream(+ stream_rx,+ Arc::new(device),+ sample_rate,+ Arc::new(realtime_transcription_sender),+ is_running_clone,+ vec![],+ Some(deepgram_api_key),+ )+ .await;++ println!("Deepgram stream closed");+ });++ let transcription_receiver_handle = tokio::spawn(async move {+ let mut receiver = realtime_transcription_receiver;+ loop {+ tokio::select! {+ event = receiver.recv() => {+ if let Ok(event) = event {+ println!("Received event: {:?}", event.transcription);+ } else {+ println!("Receiver closed");+ }+ },+ _ = tokio::time::sleep(Duration::from_secs(10)) => {+ println!("Timeout");+ return;+ }+ }+ }+ });++ tokio::time::sleep(Duration::from_secs(5)).await;++ let tx = stream_tx.clone();+ let samples = samples.clone();++ for sample in samples.chunks(sample_rate as usize * 5) {+ tx.send(sample.to_vec()).unwrap();+ tokio::time::sleep(Duration::from_millis(10)).await;+ }++ transcription_receiver_handle.await.unwrap();+}diff --git a/screenpipe-server/src/add.rs b/screenpipe-server/src/add.rsindex 24e2a26c8..7574b2ffd 100644--- a/screenpipe-server/src/add.rs+++ b/screenpipe-server/src/add.rs@@ -183,8 +183,13 @@ pub async fn handle_index_command(#[cfg(target_os = "macos")]OcrEngine::AppleNative => perform_ocr_apple(&frame, &[]),#[cfg(target_os = "windows")]- OcrEngine::WindowsNative => perform_ocr_windows(&frame).await.unwrap(),- _ => perform_ocr_tesseract(&frame, vec![]),+ OcrEngine::WindowsNative => perform_ocr_windows(&frame).await?,+ _ => {+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]+ return perform_ocr_tesseract(&frame, vec![]);++ panic!("unsupported ocr engine");+ }};if let Ok(()) = tx.send((frame_num, text, confidence.unwrap_or(0.0))).await {diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex ce2dceccc..831bae387 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -467,8 +467,6 @@ async fn main() -> anyhow::Result<()> {let warning_ocr_engine_clone = cli.ocr_engine.clone();let warning_audio_transcription_engine_clone = cli.audio_transcription_engine.clone();- let warning_realtime_audio_transcription_engine_clone =- cli.realtime_audio_transcription_engine.clone();let monitor_ids = if cli.monitor_id.is_empty() {all_monitors.iter().map(|m| m.id()).collect::<Vec<_>>()} else {@@ -545,7 +543,6 @@ async fn main() -> anyhow::Result<()> {cli.capture_unfocused_windows,realtime_audio_devices.clone(),cli.enable_realtime_audio_transcription,- Arc::new(cli.realtime_audio_transcription_engine.clone().into()),Arc::new(realtime_transcription_sender_clone), // Use the cloned senderrealtime_vision_sender_clone,);@@ -684,10 +681,6 @@ async fn main() -> anyhow::Result<()> {"│ audio engine │ {:<34} │",format!("{:?}", warning_audio_transcription_engine_clone));- println!(- "│ realtime audio engine │ {:<34} │",- format!("{:?}", warning_realtime_audio_transcription_engine_clone)- );println!("│ ocr engine │ {:<34} │",format!("{:?}", ocr_engine_clone)diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rsindex 1645f809d..8761a899a 100644--- a/screenpipe-server/src/cli.rs+++ b/screenpipe-server/src/cli.rs@@ -165,14 +165,6 @@ pub struct Cli {#[arg(short = 'a', long, value_enum, default_value_t = CliAudioTranscriptionEngine::WhisperLargeV3Turbo)]pub audio_transcription_engine: CliAudioTranscriptionEngine,- /// Realtime Audio transcription engine to use.- /// Deepgram is a very high quality cloud-based transcription service (free of charge on us for now), recommended for high quality audio.- /// WhisperTiny is a local, lightweight transcription model, recommended for high data privacy.- /// WhisperDistilLargeV3 is a local, lightweight transcription model (-a whisper-large), recommended for higher quality audio than tiny.- /// WhisperLargeV3Turbo is a local, lightweight transcription model (-a whisper-large-v3-turbo), recommended for higher quality audio than tiny.- #[arg(long, value_enum, default_value_t = CliAudioTranscriptionEngine::WhisperTiny)]- pub realtime_audio_transcription_engine: CliAudioTranscriptionEngine,-/// Enable realtime audio transcription#[arg(long, default_value_t = false)]pub enable_realtime_audio_transcription: bool,diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex 369a39339..d4c4e90aa 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -50,7 +50,6 @@ pub async fn start_continuous_recording(capture_unfocused_windows: bool,realtime_audio_devices: Vec<Arc<AudioDevice>>,realtime_audio_enabled: bool,- realtime_transcription_engine: Arc<AudioTranscriptionEngine>,realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,) -> Result<()> {@@ -138,7 +137,6 @@ pub async fn start_continuous_recording(audio_transcription_engine,realtime_audio_enabled,realtime_audio_devices,- realtime_transcription_engine,languages,realtime_transcription_sender,deepgram_api_key,@@ -297,7 +295,6 @@ async fn record_audio(audio_transcription_engine: Arc<AudioTranscriptionEngine>,realtime_audio_enabled: bool,realtime_audio_devices: Vec<Arc<AudioDevice>>,- realtime_transcription_engine: Arc<AudioTranscriptionEngine>,languages: Vec<Language>,realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,deepgram_api_key: Option<String>,@@ -337,7 +334,6 @@ async fn record_audio(let device_control = Arc::new(device_control);let realtime_audio_devices_clone = realtime_audio_devices.clone();- let realtime_transcription_engine_clone = realtime_transcription_engine.clone();let languages_clone = languages.clone();let realtime_transcription_sender_clone = realtime_transcription_sender_clone.clone();let deepgram_api_key_clone = deepgram_api_key.clone();@@ -399,8 +395,6 @@ async fn record_audio(let audio_device_clone = audio_device_clone.clone();let realtime_audio_devices_clone = realtime_audio_devices_clone.clone();- let realtime_transcription_engine_clone =- realtime_transcription_engine_clone.clone();let languages_clone = languages_clone.clone();let is_running_loop = is_running_loop.clone();let realtime_transcription_sender_clone =@@ -411,7 +405,6 @@ async fn record_audio({let _ = start_realtime_recording(audio_stream_clone,- realtime_transcription_engine_clone.clone(),languages_clone.clone(),is_running_loop.clone(),realtime_transcription_sender_clone.clone(),diff --git a/screenpipe-vision/bin/ui_monitor b/screenpipe-vision/bin/ui_monitorindex 602bde837..c18230ba8 100755Binary files a/screenpipe-vision/bin/ui_monitor and b/screenpipe-vision/bin/ui_monitor differdiff --git a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwinindex 602bde837..c18230ba8 100755Binary files a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin and b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin differ