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

Whisper-live-transcript (#1099)

Ezra Ellette480a3f0a175f
diff --git a/screenpipe-actions/src/run.rs b/screenpipe-actions/src/run.rs
index fed4c44c8..9c68ddfbb 100644
--- a/screenpipe-actions/src/run.rs
+++ b/screenpipe-actions/src/run.rs
@@ -1,6 +1,5 @@
use crate::type_and_animate::{delete_characters, type_slowly, EnigoCommand};
use crate::{call_ai, run_keystroke_monitor, KeystrokeCommand};
-use reqwest;
use std::path::Path;
use std::string::ToString;
use std::sync::atomic::{AtomicBool, Ordering};
diff --git a/screenpipe-actions/src/type_and_animate.rs b/screenpipe-actions/src/type_and_animate.rs
index 3f8c918dd..328029a26 100644
--- a/screenpipe-actions/src/type_and_animate.rs
+++ b/screenpipe-actions/src/type_and_animate.rs
@@ -22,7 +22,7 @@ pub struct EnigoResponse {
}
thread_local! {
- static ENIGO: RefCell<Option<Enigo>> = RefCell::new(None);
+ static ENIGO: RefCell<Option<Enigo>> = const { RefCell::new(None) };
}
fn with_enigo<F, R>(f: F) -> R
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.toml
index ff602806b..b8ec19844 100644
--- a/screenpipe-audio/Cargo.toml
+++ b/screenpipe-audio/Cargo.toml
@@ -76,6 +76,9 @@ ndarray = "0.16"
ort = "=2.0.0-rc.6"
knf-rs = { git = "https://github.com/Neptune650/knf-rs.git" }
ort-sys = "=2.0.0-rc.8"
+futures = "0.3.31"
+deepgram = "0.6.4"
+bytes = { version = "1.9.0", features = ["serde"] }
[target.'cfg(target_os = "windows")'.dependencies]
ort = { version = "=2.0.0-rc.6", features = [
diff --git a/screenpipe-audio/examples/stt.rs b/screenpipe-audio/examples/stt.rs
index 3e128675c..be53a6199 100644
--- a/screenpipe-audio/examples/stt.rs
+++ b/screenpipe-audio/examples/stt.rs
@@ -95,7 +95,7 @@ async fn main() {
&segmentation_model_path,
embedding_manager,
embedding_extractor,
- "default",
+ &audio_input.device.to_string(),
)
.await
.unwrap();
diff --git a/screenpipe-audio/src/audio_processing.rs b/screenpipe-audio/src/audio_processing.rs
index 0e2f03615..4a55be50c 100644
--- a/screenpipe-audio/src/audio_processing.rs
+++ b/screenpipe-audio/src/audio_processing.rs
@@ -1,6 +1,14 @@
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();
@@ -101,3 +109,55 @@ pub fn audio_to_mono(audio: &[f32], channels: u16) -> Vec<f32> {
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,
+ &file_path.into(),
+ )?;
+ }
+ Ok(file_path_clone)
+}
diff --git a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
index 1441b3e32..179bd1af9 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
@@ -130,6 +130,7 @@ async fn main() -> Result<()> {
}
}
})
+ .await
}
})
.collect();
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index a06c5c301..46f6d5071 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -1,10 +1,12 @@
use crate::audio_processing::audio_to_mono;
+use crate::realtime::{realtime_stt, RealtimeTranscriptionEvent};
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;
@@ -200,6 +202,44 @@ pub async fn record_and_transcribe(
Ok(())
}
+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>>,
+ deepgram_api_key: Option<String>,
+) -> Result<()> {
+ 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(),
+ 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,
diff --git a/screenpipe-audio/src/deepgram/mod.rs b/screenpipe-audio/src/deepgram/mod.rs
new file mode 100644
index 000000000..6691d4597
--- /dev/null
+++ b/screenpipe-audio/src/deepgram/mod.rs
@@ -0,0 +1,16 @@
+mod process_chunk;
+mod realtime;
+use lazy_static::lazy_static;
+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 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/process_chunk.rs b/screenpipe-audio/src/deepgram/process_chunk.rs
new file mode 100644
index 000000000..a0350008f
--- /dev/null
+++ b/screenpipe-audio/src/deepgram/process_chunk.rs
@@ -0,0 +1,134 @@
+use anyhow::Result;
+use hound::{WavSpec, WavWriter};
+use log::{debug, error, info};
+use reqwest::Client;
+use screenpipe_core::Language;
+use serde_json::Value;
+use std::io::Cursor;
+
+use crate::deepgram::{CUSTOM_DEEPGRAM_API_TOKEN, DEEPGRAM_API_URL};
+
+pub async fn transcribe_with_deepgram(
+ api_key: &str,
+ audio_data: &[f32],
+ device: &str,
+ sample_rate: u32,
+ 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();
+
+ // Create a WAV file in memory
+ let mut cursor = Cursor::new(Vec::new());
+ {
+ let spec = WavSpec {
+ channels: 1,
+ sample_rate: match sample_rate {
+ 88200 => 16000, // Deepgram expects 16kHz for 88.2kHz
+ _ => sample_rate, // Fallback for other sample rates
+ },
+ bits_per_sample: 32,
+ sample_format: hound::SampleFormat::Float,
+ };
+ let mut writer = WavWriter::new(&mut cursor, spec)?;
+ for &sample in audio_data {
+ writer.write_sample(sample)?;
+ }
+ writer.finalize()?;
+ }
+
+ // Get the WAV data from the cursor
+ let wav_data = cursor.into_inner();
+
+ let mut query_params = String::from("model=nova-2&smart_format=true&sample_rate=16000");
+
+ if !languages.is_empty() {
+ query_params = [
+ query_params,
+ "&".into(),
+ languages
+ .iter()
+ .map(|lang| format!("detect_language={}", lang.as_lang_code()))
+ .collect::<Vec<String>>()
+ .join("&"),
+ ]
+ .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();
+
+ debug!("deepgram api key: {}", api_key_to_use);
+
+ let response = client
+ .post(format!("{}?{}", *DEEPGRAM_API_URL, query_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)
+ } else {
+ format!("Token {}", api_key_to_use)
+ },
+ )
+ .body(wav_data)
+ .send();
+
+ match response.await {
+ Ok(resp) => {
+ debug!("received response from deepgram api");
+ match resp.json::<Value>().await {
+ Ok(result) => {
+ debug!("successfully parsed json response");
+ if let Some(err_code) = result.get("err_code") {
+ error!(
+ "deepgram api error code: {:?}, result: {:?}",
+ err_code, result
+ );
+ return Err(anyhow::anyhow!("Deepgram API error: {:?}", result));
+ }
+ let transcription = result["results"]["channels"][0]["alternatives"][0]
+ ["transcript"]
+ .as_str()
+ .unwrap_or("");
+
+ if transcription.is_empty() {
+ info!(
+ "device: {}, transcription is empty. full response: {:?}",
+ device, result
+ );
+ } else {
+ info!(
+ "device: {}, transcription successful. length: {} characters",
+ device,
+ transcription.len()
+ );
+ }
+
+ Ok(transcription.to_string())
+ }
+ Err(e) => {
+ error!("Failed to parse JSON response: {:?}", e);
+ Err(anyhow::anyhow!("Failed to parse JSON response: {:?}", e))
+ }
+ }
+ }
+ Err(e) => {
+ error!("Failed to send request to Deepgram API: {:?}", e);
+ Err(anyhow::anyhow!(
+ "Failed to send request to Deepgram API: {:?}",
+ e
+ ))
+ }
+ }
+}
diff --git a/screenpipe-audio/src/deepgram/realtime.rs b/screenpipe-audio/src/deepgram/realtime.rs
new file mode 100644
index 000000000..7fad7e3a3
--- /dev/null
+++ b/screenpipe-audio/src/deepgram/realtime.rs
@@ -0,0 +1,130 @@
+use crate::DeviceType;
+use crate::{
+ deepgram::CUSTOM_DEEPGRAM_API_TOKEN, realtime::RealtimeTranscriptionEvent, AudioStream,
+};
+use anyhow::Result;
+use bytes::BufMut;
+use bytes::Bytes;
+use bytes::BytesMut;
+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 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(
+ stream: Arc<AudioStream>,
+ realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
+ languages: Vec<Language>,
+ is_running: Arc<AtomicBool>,
+ deepgram_api_key: Option<String>,
+) -> Result<()> {
+ start_deepgram_stream(
+ stream,
+ realtime_transcription_sender,
+ is_running,
+ languages,
+ deepgram_api_key,
+ )
+ .await?;
+
+ Ok(())
+}
+async fn start_deepgram_stream(
+ stream: Arc<AudioStream>,
+ 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 audio_stream = stream.subscribe().await;
+
+ let req = deepgram_transcription
+ .stream_request()
+ .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(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);
+ }
+ }
+ }
+ }
+ }
+ Err(e) => {
+ error!("Error getting transcription: {}", e);
+ }
+ }
+ }
+
+ join!(is_running_handle).0?;
+
+ Ok(())
+}
+
+fn get_stream(mut stream: Receiver<Vec<f32>>) -> FuturesReceiver<Result<Bytes, RecvError>> {
+ let (mut tx, rx) = mpsc::channel(1);
+
+ tokio::spawn(async move {
+ while let Ok(data) = stream.recv().await {
+ let mut bytes = BytesMut::with_capacity(data.len() * 2);
+ for sample in data {
+ bytes.put_i16_le((sample * i16::MAX as f32) as i16);
+ }
+ tx.send(Ok(bytes.freeze())).await.unwrap();
+ }
+ });
+
+ rx
+}
diff --git a/screenpipe-audio/src/encode.rs b/screenpipe-audio/src/encode.rs
index 00d58d47d..67e73cdf3 100644
--- a/screenpipe-audio/src/encode.rs
+++ b/screenpipe-audio/src/encode.rs
@@ -16,7 +16,7 @@ pub fn encode_single_audio(
let mut command = Command::new(find_ffmpeg_path().unwrap());
command
- .args(&[
+ .args([
"-f",
"f32le",
"-ar",
@@ -43,6 +43,7 @@ pub fn encode_single_audio(
debug!("FFmpeg command: {:?}", command);
+ #[allow(clippy::zombie_processes)]
let mut ffmpeg = command.spawn().expect("Failed to spawn FFmpeg process");
debug!("FFmpeg process spawned");
let mut stdin = ffmpeg.stdin.take().expect("Failed to open stdin");
diff --git a/screenpipe-audio/src/lib.rs b/screenpipe-audio/src/lib.rs
index e8314a6d6..6251b3100 100644
--- a/screenpipe-audio/src/lib.rs
+++ b/screenpipe-audio/src/lib.rs
@@ -1,20 +1,24 @@
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, trigger_audio_permission, AudioDevice, AudioStream,
- AudioTranscriptionEngine, DeviceControl, DeviceType, LAST_AUDIO_CAPTURE,
+ 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, resample, stt, AudioInput, TranscriptionResult};
+pub use stt::{create_whisper_channel, stt, AudioInput, TranscriptionResult};
pub use vad_engine::VadEngineEnum;
diff --git a/screenpipe-audio/src/multilingual.rs b/screenpipe-audio/src/multilingual.rs
index f9fb42b6c..1faf71ee5 100644
--- a/screenpipe-audio/src/multilingual.rs
+++ b/screenpipe-audio/src/multilingual.rs
@@ -2,7 +2,7 @@ use crate::whisper::{token_id, Model};
use candle::IndexOp;
use candle::{Result, Tensor, D};
use candle_transformers::models::whisper::SOT_TOKEN;
-use log::info;
+use log::debug;
use screenpipe_core::Language;
use tokenizers::Tokenizer;
@@ -158,6 +158,6 @@ pub fn detect_language(
probabilities.sort_by(|(_, p1), (_, p2)| p2.total_cmp(p1));
let language = token_id(tokenizer, &format!("<|{}|>", probabilities[0].0))?;
- info!("detected language: {:?}", probabilities[0].0);
+ debug!("detected language: {:?}", probabilities[0].0);
Ok(language)
}
diff --git a/screenpipe-audio/src/realtime.rs b/screenpipe-audio/src/realtime.rs
new file mode 100644
index 000000000..daf7b9e23
--- /dev/null
+++ b/screenpipe-audio/src/realtime.rs
@@ -0,0 +1,59 @@
+use crate::{
+ deepgram::stream_transcription_deepgram, whisper::stream_transcription_whisper, AudioStream,
+ AudioTranscriptionEngine,
+};
+use anyhow::Result;
+use chrono::{DateTime, Utc};
+use screenpipe_core::Language;
+use serde::Serialize;
+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?;
+ }
+ }
+ Ok(())
+}
+
+#[derive(Serialize, Clone)]
+pub struct RealtimeTranscriptionEvent {
+ pub timestamp: DateTime<Utc>,
+ pub device: String,
+ pub transcription: String,
+ pub is_final: bool,
+ pub is_input: bool,
+}
diff --git a/screenpipe-audio/src/segments.rs b/screenpipe-audio/src/segments.rs
new file mode 100644
index 000000000..c864eb7c0
--- /dev/null
+++ b/screenpipe-audio/src/segments.rs
@@ -0,0 +1,85 @@
+use crate::audio_processing::{average_noise_spectrum, spectral_subtraction};
+use crate::{
+ audio_processing::normalize_v2,
+ pyannote::{
+ embedding::EmbeddingExtractor,
+ identify::EmbeddingManager,
+ segment::{get_segments, SpeechSegment},
+ },
+ vad_engine::VadEngine,
+};
+use anyhow::Result;
+use log::{error, info};
+use std::{path::PathBuf, sync::Arc, sync::Mutex as StdMutex};
+use tokio::sync::Mutex;
+use vad_rs::VadStatus;
+
+pub async fn prepare_segments(
+ audio_data: &[f32],
+ vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>,
+ segmentation_model_path: &PathBuf,
+ embedding_manager: EmbeddingManager,
+ embedding_extractor: Arc<StdMutex<EmbeddingExtractor>>,
+ device: &str,
+) -> Result<tokio::sync::mpsc::Receiver<SpeechSegment>> {
+ let audio_data = normalize_v2(audio_data);
+
+ let frame_size = 1600;
+ let vad_engine = vad_engine.clone();
+
+ let mut noise = 0.;
+ let mut audio_frames = Vec::new();
+ let mut total_frames = 0;
+ let mut speech_frame_count = 0;
+
+ for chunk in audio_data.chunks(frame_size) {
+ total_frames += 1;
+
+ let mut new_chunk = chunk.to_vec();
+ let status = vad_engine.lock().await.audio_type(chunk);
+ match status {
+ Ok(VadStatus::Speech) => {
+ if let Ok(processed_audio) = spectral_subtraction(chunk, noise) {
+ new_chunk = processed_audio;
+ speech_frame_count += 1;
+ }
+ }
+ Ok(VadStatus::Unknown) => {
+ noise = average_noise_spectrum(chunk);
+ }
+ _ => {}
+ }
+ audio_frames.extend(new_chunk);
+ }
+
+ let speech_ratio = speech_frame_count as f32 / total_frames as f32;
+ let min_speech_ratio = vad_engine.lock().await.get_min_speech_ratio();
+
+ info!(
+ "device: {}, speech ratio: {}, min_speech_ratio: {}, audio_frames: {}, speech_frames: {}",
+ device,
+ speech_ratio,
+ min_speech_ratio,
+ audio_frames.len(),
+ speech_frame_count
+ );
+ let (tx, rx) = tokio::sync::mpsc::channel(100);
+ if !audio_frames.is_empty() && speech_ratio >= min_speech_ratio {
+ let segments = get_segments(
+ &audio_data,
+ 16000,
+ segmentation_model_path,
+ embedding_extractor,
+ embedding_manager,
+ )?;
+
+ for segment in segments.flatten() {
+ if let Err(e) = tx.send(segment).await {
+ error!("failed to send segment: {:?}", e);
+ break;
+ }
+ }
+ }
+
+ Ok(rx)
+}
diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rs
index 67a990382..715046b6f 100644
--- a/screenpipe-audio/src/stt.rs
+++ b/screenpipe-audio/src/stt.rs
@@ -1,26 +1,22 @@
+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;
+use crate::resample;
+pub use crate::segments::prepare_segments;
use crate::{
- audio_processing::normalize_v2,
- encode_single_audio, multilingual,
- pyannote::{
- embedding::EmbeddingExtractor,
- identify::EmbeddingManager,
- segment::{get_segments, SpeechSegment},
- },
+ pyannote::{embedding::EmbeddingExtractor, identify::EmbeddingManager},
vad_engine::{SileroVad, VadEngine, VadEngineEnum, VadSensitivity, WebRtcVad},
- whisper::{Decoder, WhisperModel},
+ whisper::{process_with_whisper, WhisperModel},
AudioDevice, AudioTranscriptionEngine,
};
use anyhow::{anyhow, Result};
-use candle::Tensor;
-use candle_transformers::models::whisper::{self as m, audio};
-use chrono::Utc;
+use candle_transformers::models::whisper as m;
use log::{debug, error, info};
#[cfg(target_os = "macos")]
use objc::rc::autoreleasepool;
-use rubato::{
- Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction,
-};
-use std::collections::HashSet;
+use screenpipe_core::Language;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::{
path::PathBuf,
sync::Arc,
@@ -29,149 +25,6 @@ use std::{
};
use tokio::sync::Mutex;
-use hound::{WavSpec, WavWriter};
-use regex::Regex;
-use reqwest::Client;
-use screenpipe_core::Language;
-use serde_json::Value;
-use std::io::Cursor;
-
-use crate::pyannote::models::{get_or_download_model, PyannoteModel};
-use lazy_static::lazy_static;
-use std::env;
-
-lazy_static! {
- static ref DEEPGRAM_API_URL: String = env::var("DEEPGRAM_API_URL")
- .unwrap_or_else(|_| "https://api.deepgram.com/v1/listen".to_string());
- static ref CUSTOM_DEEPGRAM_API_TOKEN: String =
- env::var("CUSTOM_DEEPGRAM_API_TOKEN").unwrap_or_else(|_| String::new());
-}
-
-async fn transcribe_with_deepgram(
- api_key: &str,
- audio_data: &[f32],
- device: &str,
- sample_rate: u32,
- 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();
-
- // Create a WAV file in memory
- let mut cursor = Cursor::new(Vec::new());
- {
- let spec = WavSpec {
- channels: 1,
- sample_rate: match sample_rate {
- 88200 => 16000, // Deepgram expects 16kHz for 88.2kHz
- _ => sample_rate, // Fallback for other sample rates
- },
- bits_per_sample: 32,
- sample_format: hound::SampleFormat::Float,
- };
- let mut writer = WavWriter::new(&mut cursor, spec)?;
- for &sample in audio_data {
- writer.write_sample(sample)?;
- }
- writer.finalize()?;
- }
-
- // Get the WAV data from the cursor
- let wav_data = cursor.into_inner();
-
- let mut query_params = String::from("model=nova-2&smart_format=true&sample_rate=16000");
-
- if !languages.is_empty() {
- query_params = [
- query_params,
- "&".into(),
- languages
- .iter()
- .map(|lang| format!("detect_language={}", lang.as_lang_code()))
- .collect::<Vec<String>>()
- .join("&"),
- ]
- .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();
-
- debug!("deepgram api key: {}", api_key_to_use);
-
- let response = client
- .post(format!("{}?{}", *DEEPGRAM_API_URL, query_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)
- } else {
- format!("Token {}", api_key_to_use)
- },
- )
- .body(wav_data)
- .send();
-
- match response.await {
- Ok(resp) => {
- debug!("received response from deepgram api");
- match resp.json::<Value>().await {
- Ok(result) => {
- debug!("successfully parsed json response");
- if let Some(err_code) = result.get("err_code") {
- error!(
- "deepgram api error code: {:?}, result: {:?}",
- err_code, result
- );
- return Err(anyhow::anyhow!("Deepgram API error: {:?}", result));
- }
- let transcription = result["results"]["channels"][0]["alternatives"][0]
- ["transcript"]
- .as_str()
- .unwrap_or("");
-
- if transcription.is_empty() {
- info!(
- "device: {}, transcription is empty. full response: {:?}",
- device, result
- );
- } else {
- info!(
- "device: {}, transcription successful. length: {} characters",
- device,
- transcription.len()
- );
- }
-
- Ok(transcription.to_string())
- }
- Err(e) => {
- error!("Failed to parse JSON response: {:?}", e);
- Err(anyhow::anyhow!("Failed to parse JSON response: {:?}", e))
- }
- }
- }
- Err(e) => {
- error!("Failed to send request to Deepgram API: {:?}", e);
- Err(anyhow::anyhow!(
- "Failed to send request to Deepgram API: {:?}",
- e
- ))
- }
- }
-}
-
pub fn stt_sync(
audio: &[f32],
sample_rate: u32,
@@ -202,180 +55,6 @@ pub fn stt_sync(
handle.join().unwrap()
}
-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");
-
- let mut ranges: HashSet<String> = HashSet::new();
- let token_regex = Regex::new(r"<\|\d{1,2}\.\d{1,2}\|>")?;
- 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)
-}
-
-pub async fn prepare_segments(
- audio_data: &[f32],
- vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>,
- segmentation_model_path: &PathBuf,
- embedding_manager: EmbeddingManager,
- embedding_extractor: Arc<StdMutex<EmbeddingExtractor>>,
- device: &str,
-) -> Result<tokio::sync::mpsc::Receiver<SpeechSegment>> {
- let audio_data = normalize_v2(audio_data);
-
- let frame_size = 1600;
- let vad_engine = vad_engine.clone();
-
- let mut noise = 0.;
- let mut audio_frames = Vec::new();
- let mut total_frames = 0;
- let mut speech_frame_count = 0;
-
- for chunk in audio_data.chunks(frame_size) {
- total_frames += 1;
-
- let mut new_chunk = chunk.to_vec();
- let status = vad_engine.lock().await.audio_type(chunk);
- match status {
- Ok(VadStatus::Speech) => {
- if let Ok(processed_audio) = spectral_subtraction(chunk, noise) {
- new_chunk = processed_audio;
- speech_frame_count += 1;
- }
- }
- Ok(VadStatus::Unknown) => {
- noise = average_noise_spectrum(chunk);
- }
- _ => {}
- }
- audio_frames.extend(new_chunk);
- }
-
- let speech_ratio = speech_frame_count as f32 / total_frames as f32;
- let min_speech_ratio = vad_engine.lock().await.get_min_speech_ratio();
-
- info!(
- "device: {}, speech ratio: {}, min_speech_ratio: {}, audio_frames: {}, speech_frames: {}",
- device,
- speech_ratio,
- min_speech_ratio,
- audio_frames.len(),
- speech_frame_count
- );
- let (tx, rx) = tokio::sync::mpsc::channel(100);
- if !audio_frames.is_empty() && speech_ratio >= min_speech_ratio {
- let segments = get_segments(
- &audio_data,
- 16000,
- segmentation_model_path,
- embedding_extractor,
- embedding_manager,
- )?;
-
- for segment in segments.flatten() {
- if let Err(e) = tx.send(segment).await {
- error!("failed to send segment: {:?}", e);
- break;
- }
- }
- }
-
- Ok(rx)
-}
-
#[allow(clippy::too_many_arguments)]
pub async fn stt(
audio: &[f32],
@@ -424,31 +103,6 @@ pub async fn stt(
transcription
}
-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())
-}
-
#[derive(Debug, Clone)]
pub struct AudioInput {
pub data: Arc<Vec<f32>>,
@@ -494,10 +148,6 @@ impl TranscriptionResult {
}
}
-use crate::audio_processing::{average_noise_spectrum, spectral_subtraction};
-use std::sync::atomic::{AtomicBool, Ordering};
-use vad_rs::VadStatus;
-
pub async fn create_whisper_channel(
audio_transcription_engine: Arc<AudioTranscriptionEngine>,
vad_engine: VadEngineEnum,
@@ -585,7 +235,6 @@ pub async fn create_whisper_channel(
}
};
-
let path = match write_audio_to_file(
&audio.data.to_vec(),
audio.sample_rate,
@@ -607,41 +256,7 @@ pub async fn create_whisper_channel(
#[cfg(target_os = "macos")]
{
autoreleasepool(|| {
- match stt_sync(&segment.samples, segment.sample_rate, &audio.device.to_string(), &mut whisper_model, audio_transcription_engine.clone(), deepgram_api_key.clone(), languages.clone()) {
- Ok(transcription) => TranscriptionResult {
- input: AudioInput {
- data: Arc::new(segment.samples),
- sample_rate: segment.sample_rate,
- channels: 1,
- device: audio.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 {}: {:?}", audio.device, e);
- TranscriptionResult {
- input: AudioInput {
- data: Arc::new(segment.samples),
- sample_rate: segment.sample_rate,
- channels: 1,
- device: audio.device.clone(),
- },
- transcription: None,
- path,
- timestamp,
- error: Some(e.to_string()),
- speaker_embedding: Vec::new(),
- start_time: segment.start,
- end_time: segment.end,
- }
- },
- }
+ 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"))]
@@ -649,41 +264,7 @@ pub async fn create_whisper_channel(
unreachable!("This code should not be reached on non-macOS platforms")
}
} else {
- match stt_sync(&segment.samples, segment.sample_rate, &audio.device.to_string(), &mut whisper_model, audio_transcription_engine.clone(), deepgram_api_key.clone(), languages.clone()) {
- Ok(transcription) => TranscriptionResult {
- input: AudioInput {
- data: Arc::new(segment.samples),
- sample_rate: segment.sample_rate,
- channels: 1,
- device: audio.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 {}: {:?}", audio.device, e);
- TranscriptionResult {
- input: AudioInput {
- data: Arc::new(segment.samples),
- sample_rate: segment.sample_rate,
- channels: 1,
- device: audio.device.clone(),
- },
- transcription: None,
- path,
- timestamp,
- error: Some(e.to_string()),
- speaker_embedding: Vec::new(),
- start_time: segment.start,
- end_time: segment.end,
- }
- },
- }
+ 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() {
@@ -707,6 +288,64 @@ pub async fn create_whisper_channel(
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();
@@ -745,30 +384,3 @@ pub fn longest_common_word_substring(s1: &str, s2: &str) -> Option<(usize, usize
_ => None,
}
}
-
-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,
- &file_path.into(),
- )?;
- }
- Ok(file_path_clone)
-}
diff --git a/screenpipe-audio/src/whisper.rs b/screenpipe-audio/src/whisper/decoder.rs
similarity index 65%
rename from screenpipe-audio/src/whisper.rs
rename to screenpipe-audio/src/whisper/decoder.rs
index bf4ab6bc2..baa041a65 100644
--- a/screenpipe-audio/src/whisper.rs
+++ b/screenpipe-audio/src/whisper/decoder.rs
@@ -1,118 +1,12 @@
+use crate::whisper::Model;
use anyhow::{Error as E, Result};
use candle::{Device, IndexOp, Tensor};
-use candle_nn::{ops::softmax, VarBuilder};
-use candle_transformers::models::whisper::{self as m, Config};
-use hf_hub::{api::sync::Api, Repo, RepoType};
+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(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),
- }
- }
-}
-
#[derive(Debug, Clone)]
pub struct DecodingResult {
tokens: Vec<u32>,
@@ -132,7 +26,7 @@ pub struct Segment {
}
pub struct Decoder<'a> {
- model: &'a mut Model,
+ pub model: &'a mut Model,
rng: rand::rngs::StdRng,
timestamps: bool,
verbose: bool,
@@ -157,7 +51,7 @@ impl<'a> Decoder<'a> {
timestamps: bool,
verbose: bool,
) -> Result<Self> {
- let no_timestamps_token = token_id(&tokenizer, m::NO_TIMESTAMPS_TOKEN)?;
+ 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)
@@ -170,12 +64,12 @@ impl<'a> Decoder<'a> {
})
.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 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());
+ .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,
@@ -323,6 +217,17 @@ impl<'a> Decoder<'a> {
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;
@@ -336,7 +241,7 @@ impl<'a> Decoder<'a> {
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 {
- info!("no speech detected, skipping {seek} {dr:?}");
+ debug!("no speech detected, skipping {seek} {dr:?}");
continue;
}
let segment = Segment {
@@ -345,11 +250,6 @@ impl<'a> Decoder<'a> {
dr,
};
if self.timestamps {
- // info!(
- // "{:.1}s -- {:.1}s",
- // segment.start,
- // segment.start + segment.duration,
- // );
let mut tokens_to_decode = vec![];
let mut prev_timestamp_s = 0f32;
for &token in segment.dr.tokens.iter() {
@@ -363,7 +263,7 @@ impl<'a> Decoder<'a> {
.tokenizer
.decode(&tokens_to_decode, true)
.map_err(E::msg)?;
- info!(" {:.1}s-{:.1}s: {}", prev_timestamp_s, timestamp_s, text);
+ debug!(" {:.1}s-{:.1}s: {}", prev_timestamp_s, timestamp_s, text);
tokens_to_decode.clear()
}
prev_timestamp_s = timestamp_s;
@@ -372,23 +272,10 @@ impl<'a> Decoder<'a> {
}
}
if !tokens_to_decode.is_empty() {
- let text = self
- .tokenizer
- .decode(&tokens_to_decode, true)
- .map_err(E::msg)?;
- if !text.is_empty() {
- // info!(" {:.1}s-...: {}", prev_timestamp_s, text);
- }
tokens_to_decode.clear()
}
- } else {
- // info!(
- // "{:.1}s -- {:.1}s: {}",
- // segment.start,
- // segment.start + segment.duration,
- // segment.dr.text,
- // )
}
+
if self.verbose {
info!("{seek}: {segment:?}, in {:?}", start.elapsed());
}
@@ -418,5 +305,3 @@ fn apply_repetition_penalty(logits: &mut [f32], token_history: &[u32], penalty:
}
}
}
-
-// ... (keep any other helper functions or structs that are specific to Whisper)
diff --git a/screenpipe-audio/src/whisper/mod.rs b/screenpipe-audio/src/whisper/mod.rs
new file mode 100644
index 000000000..a9577f07f
--- /dev/null
+++ b/screenpipe-audio/src/whisper/mod.rs
@@ -0,0 +1,9 @@
+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/model.rs b/screenpipe-audio/src/whisper/model.rs
new file mode 100644
index 000000000..ad6d22952
--- /dev/null
+++ b/screenpipe-audio/src/whisper/model.rs
@@ -0,0 +1,113 @@
+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
new file mode 100644
index 000000000..ecb251913
--- /dev/null
+++ b/screenpipe-audio/src/whisper/process_chunk.rs
@@ -0,0 +1,124 @@
+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/src/whisper/realtime.rs b/screenpipe-audio/src/whisper/realtime.rs
new file mode 100644
index 000000000..03a2e342c
--- /dev/null
+++ b/screenpipe-audio/src/whisper/realtime.rs
@@ -0,0 +1,126 @@
+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/core_tests.rs b/screenpipe-audio/tests/core_tests.rs
index 06fc7d0ce..56971b90e 100644
--- a/screenpipe-audio/tests/core_tests.rs
+++ b/screenpipe-audio/tests/core_tests.rs
@@ -24,14 +24,12 @@ mod tests {
fn setup() {
// Initialize the logger with an info level filter
- match env_logger::builder()
+ if env_logger::builder()
.filter_level(log::LevelFilter::Debug)
.filter_module("tokenizers", LevelFilter::Error)
.try_init()
- {
- Ok(_) => (),
- Err(_) => (),
- };
+ .is_ok()
+ {};
}
// ! what happen in github action?
@@ -176,7 +174,7 @@ mod tests {
// Helper function to get audio duration (you'll need to implement this)
fn get_audio_duration(path: &PathBuf) -> Result<Duration, Box<dyn std::error::Error>> {
let output = Command::new("ffprobe")
- .args(&[
+ .args([
"-v",
"error",
"-show_entries",
@@ -282,7 +280,7 @@ mod tests {
}
// Clean up
- let _ = recording_thread.abort();
+ recording_thread.abort();
std::fs::remove_file(output_path_2).unwrap_or_default();
}
@@ -337,7 +335,7 @@ mod tests {
&segmentation_model_path,
embedding_manager,
embedding_extractor,
- "default",
+ &audio_input.device.to_string(),
)
.await
.unwrap();
@@ -352,12 +350,13 @@ mod tests {
&mut whisper_model_guard,
Arc::new(AudioTranscriptionEngine::WhisperLargeV3Turbo),
None,
- vec![Language::English],
+ vec![Language::Arabic],
)
.await
.unwrap();
transcription_result.push_str(&transcript);
+ transcription_result.push('\n');
}
drop(whisper_model_guard);
@@ -368,13 +367,10 @@ mod tests {
println!("Received transcription: {}", transcription_result);
assert!(
- transcription_result.contains("موسیقی")
+ transcription_result.contains("موسيقى")
|| transcription_result.contains("تعال")
|| transcription_result.contains("الحيوانات")
);
-
- // Clean up
- std::fs::remove_file("test_output").unwrap_or_default();
}
#[tokio::test]
@@ -387,9 +383,6 @@ mod tests {
.join("test_data")
.join("selah.mp4");
let audio_data = pcm_decode(&audio_path).expect("Failed to decode audio file");
- // Create a temporary output path
- let output_path =
- PathBuf::from(format!("test_output_{}.mp4", Utc::now().timestamp_millis()));
// Create AudioInput from the audio data
let audio_input = AudioInput {
@@ -438,7 +431,7 @@ mod tests {
&segmentation_model_path,
embedding_manager,
embedding_extractor,
- "default",
+ &audio_input.device.to_string(),
)
.await
.unwrap();
@@ -463,8 +456,5 @@ mod tests {
let elapsed_time = start_time.elapsed();
debug!("Transcription completed in {:?}", elapsed_time);
-
- // Clean up
- std::fs::remove_file(output_path).unwrap_or_default();
}
}
diff --git a/screenpipe-core/examples/phi.rs b/screenpipe-core/examples/phi.rs
index e169fa8c2..1a4814b26 100644
--- a/screenpipe-core/examples/phi.rs
+++ b/screenpipe-core/examples/phi.rs
@@ -1,6 +1,7 @@
#[cfg(feature = "llm")]
+use anyhow::Result;
+#[cfg(feature = "llm")]
fn main() -> Result<()> {
- use anyhow::Result;
use candle::Device;
use screenpipe_core::{generate_text_streaming, load_llama_model};
use std::env;
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 46ba87627..2b7d1ad4b 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -1,14 +1,3 @@
-use std::{
- collections::HashMap,
- env, fs,
- io::Write,
- net::SocketAddr,
- ops::Deref,
- path::PathBuf,
- sync::{atomic::AtomicBool, Arc},
- time::Duration,
-};
-
use clap::Parser;
#[allow(unused_imports)]
use colored::Colorize;
@@ -31,6 +20,16 @@ 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,
+ ops::Deref,
+ path::PathBuf,
+ sync::{atomic::AtomicBool, Arc},
+ time::Duration,
+};
use tokio::{runtime::Runtime, signal, sync::broadcast};
use tracing::{debug, error, info, warn};
use tracing_appender::non_blocking::WorkerGuard;
@@ -308,6 +307,8 @@ async fn main() -> anyhow::Result<()> {
let audio_devices_control_server = 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 {
@@ -368,6 +369,29 @@ async fn main() -> anyhow::Result<()> {
});
}
}
+
+ if cli.enable_realtime_audio_transcription {
+ if cli.realtime_audio_device.is_empty() {
+ // Use default devices
+ if let Ok(input_device) = default_input_device() {
+ realtime_audio_devices.push(Arc::new(input_device.clone()));
+ }
+ // audio output only on macos <15.0 atm ?
+ // see https://github.com/mediar-ai/screenpipe/pull/106
+ if let Ok(output_device) = default_output_device() {
+ realtime_audio_devices.push(Arc::new(output_device.clone()));
+ }
+ } else {
+ for d in &cli.realtime_audio_device {
+ let device = parse_audio_device(d).expect("failed to parse audio device");
+ realtime_audio_devices.push(Arc::new(device.clone()));
+ }
+ }
+
+ if realtime_audio_devices.is_empty() {
+ eprintln!("no realtime audio devices available. realtime audio transcription will be disabled.");
+ }
+ }
}
let resource_monitor = ResourceMonitor::new();
@@ -391,6 +415,8 @@ 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 {
@@ -419,6 +445,7 @@ async fn main() -> anyhow::Result<()> {
let monitor_ids_clone = monitor_ids.clone();
let ignored_windows_clone = cli.ignored_windows.clone();
let included_windows_clone = cli.included_windows.clone();
+ let realtime_audio_devices_clone = realtime_audio_devices.clone();
let fps = if cli.fps.is_finite() && cli.fps > 0.0 {
cli.fps
@@ -428,13 +455,15 @@ async fn main() -> anyhow::Result<()> {
};
let audio_chunk_duration = Duration::from_secs(cli.audio_chunk_duration);
-
+ let (realtime_transcription_sender, _) = tokio::sync::broadcast::channel(1000);
+ let realtime_transcription_sender_clone = realtime_transcription_sender.clone();
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 realtime_transcription_sender_clone = realtime_transcription_sender.clone(); // Clone inside the loop
let recording_future = start_continuous_recording(
db_clone.clone(),
output_path_clone.clone(),
@@ -458,6 +487,10 @@ async fn main() -> anyhow::Result<()> {
cli.vad_sensitivity.clone(),
languages.clone(),
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 sender
);
let result = tokio::select! {
@@ -500,6 +533,7 @@ async fn main() -> anyhow::Result<()> {
// Track search requests
}
};
+ // TODO: Add SSE stream for realtime audio transcription
let server = Server::new(
db_server,
SocketAddr::from(([127, 0, 0, 1], cli.port)),
@@ -510,6 +544,8 @@ async fn main() -> anyhow::Result<()> {
cli.disable_vision,
cli.disable_audio,
cli.enable_ui_monitoring,
+ cli.enable_realtime_audio_transcription,
+ realtime_transcription_sender_clone,
);
// print screenpipe in gradient
@@ -525,56 +561,73 @@ async fn main() -> anyhow::Result<()> {
"open source | runs locally | developer friendly".bright_green()
);
- println!("┌─────────────────────┬────────────────────────────────────┐");
- println!("│ setting │ value │");
- println!("├─────────────────────┼────────────────────────────────────┤");
- println!("│ fps │ {:<34} │", cli.fps);
+ println!("┌────────────────────────┬────────────────────────────────────┐");
+ println!("│ setting │ value │");
+ println!("├────────────────────────┼────────────────────────────────────┤");
+ println!("│ fps │ {:<34} │", cli.fps);
println!(
- "│ audio chunk duration│ {:<34} │",
+ "│ audio chunk duration │ {:<34} │",
format!("{} seconds", cli.audio_chunk_duration)
);
println!(
- "│ video chunk duration│ {:<34} │",
+ "│ video chunk duration │ {:<34} │",
format!("{} seconds", cli.video_chunk_duration)
);
- println!("│ port │ {:<34} │", cli.port);
- println!("│ audio disabled │ {:<34} │", cli.disable_audio);
- println!("│ vision disabled │ {:<34} │", cli.disable_vision);
+ println!("│ port │ {:<34} │", cli.port);
+ println!(
+ "│ realtime audio enabled │ {:<34} │",
+ cli.enable_realtime_audio_transcription
+ );
+ println!("│ audio disabled │ {:<34} │", cli.disable_audio);
+ println!("│ vision disabled │ {:<34} │", cli.disable_vision);
println!(
- "│ audio engine │ {:<34} │",
+ "│ audio engine │ {:<34} │",
format!("{:?}", warning_audio_transcription_engine_clone)
);
println!(
- "│ ocr engine │ {:<34} │",
+ "│ realtime audio engine │ {:<34} │",
+ format!("{:?}", warning_realtime_audio_transcription_engine_clone)
+ );
+ println!(
+ "│ ocr engine │ {:<34} │",
format!("{:?}", ocr_engine_clone)
);
println!(
- "│ vad engine │ {:<34} │",
+ "│ vad engine │ {:<34} │",
format!("{:?}", vad_engine_clone)
);
println!(
- "│ vad sensitivity │ {:<34} │",
+ "│ vad sensitivity │ {:<34} │",
format!("{:?}", vad_sensitivity_clone)
);
println!(
- "│ data directory │ {:<34} │",
+ "│ data directory │ {:<34} │",
local_data_dir_clone.display()
);
- println!("│ debug mode │ {:<34} │", cli.debug);
- println!("│ telemetry │ {:<34} │", !cli.disable_telemetry);
- println!("│ local llm │ {:<34} │", cli.enable_llm);
+ println!("│ debug mode │ {:<34} │", cli.debug);
+ println!(
+ "│ telemetry │ {:<34} │",
+ !cli.disable_telemetry
+ );
+ println!("│ local llm │ {:<34} │", cli.enable_llm);
- println!("│ use pii removal │ {:<34} │", cli.use_pii_removal);
+ println!("│ use pii removal │ {:<34} │", cli.use_pii_removal);
println!(
- "│ ignored windows │ {:<34} │",
+ "│ ignored windows │ {:<34} │",
format_cell(&format!("{:?}", &ignored_windows_clone), VALUE_WIDTH)
);
println!(
- "│ included windows │ {:<34} │",
+ "│ included windows │ {:<34} │",
format_cell(&format!("{:?}", &included_windows_clone), VALUE_WIDTH)
);
- println!("│ ui monitoring │ {:<34} │", cli.enable_ui_monitoring);
- println!("│ frame cache │ {:<34} │", cli.enable_frame_cache);
+ println!(
+ "│ ui monitoring │ {:<34} │",
+ cli.enable_ui_monitoring
+ );
+ println!(
+ "│ frame cache │ {:<34} │",
+ cli.enable_frame_cache
+ );
const VALUE_WIDTH: usize = 34;
@@ -596,12 +649,12 @@ async fn main() -> anyhow::Result<()> {
}
// Add languages section
- println!("├─────────────────────┼────────────────────────────────────┤");
- println!("│ languages │ │");
+ println!("├────────────────────────┼────────────────────────────────────┤");
+ println!("│ languages │ │");
const MAX_ITEMS_TO_DISPLAY: usize = 5;
if cli.language.is_empty() {
- println!("│ {:<19} │ {:<34} │", "", "all languages");
+ println!("│ {:<22} │ {:<34} │", "", "all languages");
} else {
let total_languages = cli.language.len();
for (_, language) in languages_clone
@@ -611,11 +664,11 @@ async fn main() -> anyhow::Result<()> {
{
let language_str = format!("id: {}", language);
let formatted_language = format_cell(&language_str, VALUE_WIDTH);
- println!("│ {:<19} │ {:<34} │", "", formatted_language);
+ println!("│ {:<22} │ {:<34} │", "", formatted_language);
}
if total_languages > MAX_ITEMS_TO_DISPLAY {
println!(
- "│ {:<19} │ {:<34} │",
+ "│ {:<22} │ {:<34} │",
"",
format!("... and {} more", total_languages - MAX_ITEMS_TO_DISPLAY)
);
@@ -623,23 +676,23 @@ async fn main() -> anyhow::Result<()> {
}
// Add monitors section
- println!("├─────────────────────┼────────────────────────────────────┤");
- println!("│ monitors │ │");
+ println!("├────────────────────────┼────────────────────────────────────┤");
+ println!("│ monitors │ │");
if cli.disable_vision {
- println!("│ {:<19} │ {:<34} │", "", "vision disabled");
+ println!("│ {:<22} │ {:<34} │", "", "vision disabled");
} else if monitor_ids.is_empty() {
- println!("│ {:<19} │ {:<34} │", "", "no monitors available");
+ println!("│ {:<22} │ {:<34} │", "", "no monitors available");
} else {
let total_monitors = monitor_ids.len();
for (_, monitor) in monitor_ids.iter().enumerate().take(MAX_ITEMS_TO_DISPLAY) {
let monitor_str = format!("id: {}", monitor);
let formatted_monitor = format_cell(&monitor_str, VALUE_WIDTH);
- println!("│ {:<19} │ {:<34} │", "", formatted_monitor);
+ println!("│ {:<22} │ {:<34} │", "", formatted_monitor);
}
if total_monitors > MAX_ITEMS_TO_DISPLAY {
println!(
- "│ {:<19} │ {:<34} │",
+ "│ {:<22} │ {:<34} │",
"",
format!("... and {} more", total_monitors - MAX_ITEMS_TO_DISPLAY)
);
@@ -647,24 +700,52 @@ async fn main() -> anyhow::Result<()> {
}
// Audio devices section
- println!("├─────────────────────┼────────────────────────────────────┤");
- println!("│ audio devices │ │");
+ println!("├────────────────────────┼────────────────────────────────────┤");
+ println!("│ audio devices │ │");
if cli.disable_audio {
- println!("│ {:<19} │ {:<34} │", "", "disabled");
+ println!("│ {:<22} │ {:<34} │", "", "disabled");
} else if audio_devices.is_empty() {
- println!("│ {:<19} │ {:<34} │", "", "no devices available");
+ 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 device_str = device.deref().to_string();
let formatted_device = format_cell(&device_str, VALUE_WIDTH);
- println!("│ {:<19} │ {:<34} │", "", formatted_device);
+ println!("│ {:<22} │ {:<34} │", "", formatted_device);
+ }
+ if total_devices > MAX_ITEMS_TO_DISPLAY {
+ println!(
+ "│ {:<22} │ {:<34} │",
+ "",
+ format!("... and {} more", total_devices - MAX_ITEMS_TO_DISPLAY)
+ );
+ }
+ }
+ // Realtime Audio devices section
+ println!("├────────────────────────┼────────────────────────────────────┤");
+ println!("│ realtime audio devices │ │");
+
+ if cli.disable_audio || !cli.enable_realtime_audio_transcription {
+ println!("│ {:<22} │ {:<34} │", "", "disabled");
+ } else if realtime_audio_devices_clone.is_empty() {
+ println!("│ {:<22} │ {:<34} │", "", "no devices available");
+ } else {
+ let total_devices = realtime_audio_devices_clone.len();
+ for (_, device) in realtime_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);
+
+ println!("│ {:<22} │ {:<34} │", "", formatted_device);
}
if total_devices > MAX_ITEMS_TO_DISPLAY {
println!(
- "│ {:<19} │ {:<34} │",
+ "│ {:<22} │ {:<34} │",
"",
format!("... and {} more", total_devices - MAX_ITEMS_TO_DISPLAY)
);
@@ -672,11 +753,11 @@ async fn main() -> anyhow::Result<()> {
}
// Pipes section
- println!("├─────────────────────┼────────────────────────────────────┤");
- println!("│ pipes │ │");
+ println!("├────────────────────────┼────────────────────────────────────┤");
+ println!("│ pipes │ │");
let pipes = pipe_manager.list_pipes().await;
if pipes.is_empty() {
- println!("│ {:<19} │ {:<34} │", "", "no pipes available");
+ println!("│ {:<22} │ {:<34} │", "", "no pipes available");
} else {
let total_pipes = pipes.len();
for (_, pipe) in pipes.iter().enumerate().take(MAX_ITEMS_TO_DISPLAY) {
@@ -686,18 +767,18 @@ async fn main() -> anyhow::Result<()> {
pipe.id,
);
let formatted_pipe = format_cell(&pipe_str, VALUE_WIDTH);
- println!("│ {:<19} │ {:<34} │", "", formatted_pipe);
+ println!("│ {:<22} │ {:<34} │", "", formatted_pipe);
}
if total_pipes > MAX_ITEMS_TO_DISPLAY {
println!(
- "│ {:<19} │ {:<34} │",
+ "│ {:<22} │ {:<34} │",
"",
format!("... and {} more", total_pipes - MAX_ITEMS_TO_DISPLAY)
);
}
}
- println!("└─────────────────────┴────────────────────────────────────┘");
+ println!("└────────────────────────┴────────────────────────────────────┘");
// Add warning for cloud arguments and telemetry
if warning_audio_transcription_engine_clone == CliAudioTranscriptionEngine::Deepgram
diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rs
index 29ea877f5..228e56656 100644
--- a/screenpipe-server/src/cli.rs
+++ b/screenpipe-server/src/cli.rs
@@ -124,6 +124,10 @@ pub struct Cli {
#[arg(short = 'i', long)]
pub audio_device: Vec<String>,
+ // Audio devices to use for realtime audio transcription
+ #[arg(short = 'r', long)]
+ pub realtime_audio_device: Vec<String>,
+
/// List available audio devices
#[arg(long)]
pub list_audio_devices: bool,
@@ -144,6 +148,18 @@ 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,
+
/// OCR engine to use.
/// AppleNative is the default local OCR engine for macOS.
/// WindowsNative is a local OCR engine for Windows.
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 7710548e8..6e9b5c3d6 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -5,12 +5,13 @@ use anyhow::Result;
use crossbeam::queue::SegQueue;
use futures::future::join_all;
use log::{debug, error, info, warn};
+use screenpipe_audio::realtime::RealtimeTranscriptionEvent;
use screenpipe_audio::vad_engine::VadSensitivity;
-use screenpipe_audio::AudioStream;
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_vision::OcrEngine;
@@ -22,6 +23,7 @@ use std::time::Duration;
use tokio::runtime::Handle;
use tokio::task::JoinHandle;
+#[allow(clippy::too_many_arguments)]
pub async fn start_continuous_recording(
db: Arc<DatabaseManager>,
output_path: Arc<String>,
@@ -45,6 +47,10 @@ pub async fn start_continuous_recording(
vad_sensitivity: CliVadSensitivity,
languages: Vec<Language>,
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>>,
) -> Result<()> {
debug!("Starting video recording for monitor {:?}", monitor_ids);
let video_tasks = if !vision_disabled {
@@ -106,7 +112,7 @@ pub async fn start_continuous_recording(
create_whisper_channel(
audio_transcription_engine.clone(),
VadEngineEnum::from(vad_engine),
- deepgram_api_key,
+ deepgram_api_key.clone(),
&PathBuf::from(output_path.as_ref()),
VadSensitivity::from(vad_sensitivity),
languages.clone(),
@@ -125,6 +131,12 @@ pub async fn start_continuous_recording(
whisper_receiver,
audio_devices_control,
audio_transcription_engine,
+ realtime_audio_enabled,
+ realtime_audio_devices,
+ realtime_transcription_engine,
+ languages,
+ realtime_transcription_sender,
+ deepgram_api_key,
)
.await
})
@@ -160,6 +172,7 @@ pub async fn start_continuous_recording(
Ok(())
}
+#[allow(clippy::too_many_arguments)]
async fn record_video(
db: Arc<DatabaseManager>,
output_path: Arc<String>,
@@ -257,6 +270,7 @@ async fn record_video(
Ok(())
}
+#[allow(clippy::too_many_arguments)]
async fn record_audio(
db: Arc<DatabaseManager>,
chunk_duration: Duration,
@@ -264,10 +278,17 @@ async fn record_audio(
whisper_receiver: crossbeam::channel::Receiver<TranscriptionResult>,
audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,
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>,
) -> Result<()> {
let mut handles: HashMap<String, JoinHandle<()>> = HashMap::new();
let mut previous_transcript = "".to_string();
let mut previous_transcript_id: Option<i64> = None;
+ let realtime_transcription_sender_clone = realtime_transcription_sender.clone();
loop {
while let Some((audio_device, device_control)) = audio_devices_control.pop() {
debug!("Received audio device: {}", &audio_device);
@@ -287,9 +308,14 @@ async fn record_audio(
let audio_device = Arc::new(audio_device);
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();
let handle = tokio::spawn(async move {
let audio_device_clone = Arc::clone(&audio_device);
- // let error = Arc::new(AtomicBool::new(false));
+ let deepgram_api_key = deepgram_api_key_clone.clone();
debug!(
"Starting audio capture thread for device: {}",
&audio_device
@@ -299,6 +325,7 @@ async fn record_audio(
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(),
@@ -322,25 +349,55 @@ async fn record_audio(
}
};
+ 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(),
+ is_running_loop_clone.clone(),
)
.await;
}));
- // let live_transcription_handle = tokio::spawn(async move {
- // let _ = live_transcription(audio_stream, whisper_sender_clone.clone()).await;
- // });
-
if let Some(handle) = record_handle {
- handle.await.unwrap();
+ recording_handles.push(handle);
+ }
+
+ 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 =
+ realtime_transcription_sender_clone.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,
+ realtime_transcription_engine_clone.clone(),
+ languages_clone.clone(),
+ is_running_loop.clone(),
+ realtime_transcription_sender_clone.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);
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 23cf8003b..91ba53b4a 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -18,11 +18,7 @@ use crate::{
video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},
video_cache::{FrameCache, TimeSeriesFrame},
video_utils::{
- merge_videos,
- validate_media,
- MergeVideosRequest,
- MergeVideosResponse,
- ValidateMediaParams
+ merge_videos, validate_media, MergeVideosRequest, MergeVideosResponse, ValidateMediaParams,
},
DatabaseManager,
};
@@ -31,8 +27,8 @@ use base64::prelude::*;
use chrono::{DateTime, Utc};
use log::{debug, error, info};
use screenpipe_audio::{
- default_input_device, default_output_device, list_audio_devices, AudioDevice, DeviceControl,
- DeviceType,
+ default_input_device, default_output_device, list_audio_devices,
+ realtime::RealtimeTranscriptionEvent, AudioDevice, DeviceControl, DeviceType,
};
use screenpipe_vision::monitor::list_monitors;
use screenpipe_vision::OcrEngine;
@@ -74,6 +70,9 @@ pub struct AppState {
pub audio_disabled: bool,
pub ui_monitoring_enabled: bool,
pub frame_cache: Option<Arc<FrameCache>>,
+ pub realtime_transcription_enabled: bool,
+ pub realtime_transcription_sender:
+ Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
}
// Update the SearchQuery struct
@@ -806,6 +805,8 @@ pub struct Server {
vision_disabled: bool,
audio_disabled: bool,
ui_monitoring_enabled: bool,
+ realtime_transcription_enabled: bool,
+ realtime_transcription_sender: tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>,
}
impl Server {
@@ -820,6 +821,8 @@ impl Server {
vision_disabled: bool,
audio_disabled: bool,
ui_monitoring_enabled: bool,
+ realtime_transcription_enabled: bool,
+ realtime_transcription_sender: tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>,
) -> Self {
Server {
db,
@@ -831,6 +834,8 @@ impl Server {
vision_disabled,
audio_disabled,
ui_monitoring_enabled,
+ realtime_transcription_enabled,
+ realtime_transcription_sender,
}
}
@@ -863,6 +868,8 @@ impl Server {
} else {
None
},
+ realtime_transcription_enabled: self.realtime_transcription_enabled,
+ realtime_transcription_sender: Arc::new(self.realtime_transcription_sender),
});
let app = create_router()
@@ -920,15 +927,12 @@ async fn validate_media_handler(
State(_state): State<Arc<AppState>>,
Query(params): Query<ValidateMediaParams>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
-
match validate_media(&params.file_path).await {
Ok(_) => Ok(Json(json!({"status": "valid media file"}))),
- Err(e) => {
- Err((
- StatusCode::EXPECTATION_FAILED,
- Json(json!({"status": e.to_string()})),
- ))
- }
+ Err(e) => Err((
+ StatusCode::EXPECTATION_FAILED,
+ Json(json!({"status": e.to_string()})),
+ )),
}
}
@@ -1010,7 +1014,7 @@ async fn add_frame_to_db(
let db = &state.db;
let frame_id = db
- .insert_frame(&device_name, Some(frame.timestamp.unwrap_or_else(Utc::now)))
+ .insert_frame(device_name, Some(frame.timestamp.unwrap_or_else(Utc::now)))
.await?;
if let Some(ocr_results) = &frame.ocr_results {
@@ -1018,9 +1022,9 @@ async fn add_frame_to_db(
db.insert_ocr_text(
frame_id,
&ocr.text,
- &ocr.text_json.as_deref().unwrap_or(""),
- &frame.app_name.as_deref().unwrap_or(""),
- &frame.window_name.as_deref().unwrap_or(""),
+ ocr.text_json.as_deref().unwrap_or(""),
+ frame.app_name.as_deref().unwrap_or(""),
+ frame.window_name.as_deref().unwrap_or(""),
Arc::new(OcrEngine::default()), // Ideally could pass any str as ocr_engine since can be run outside of screenpipe
false,
)
@@ -1571,6 +1575,37 @@ async fn get_similar_speakers_handler(
Ok(JsonResponse(similar_speakers))
}
+async fn sse_transcription_handler(
+ State(state): State<Arc<AppState>>,
+) -> Result<
+ Sse<impl Stream<Item = Result<Event, Infallible>>>,
+ (StatusCode, JsonResponse<serde_json::Value>),
+> {
+ if !state.realtime_transcription_enabled {
+ return Err((
+ StatusCode::FORBIDDEN,
+ JsonResponse(json!({"error": "Real-time transcription is not enabled"})),
+ ));
+ }
+
+ // Get a new subscription - this won't affect the sender
+ let rx = state.realtime_transcription_sender.subscribe();
+
+ let stream = async_stream::stream! {
+ let mut rx = rx; // Create a new mutable reference to the receiver
+ while let Ok(event) = rx.recv().await {
+ yield Ok(Event::default().data(serde_json::to_string(&event).unwrap_or_default()));
+ }
+ // Even if this stream ends, the sender remains active
+ };
+
+ Ok(Sse::new(stream).keep_alive(
+ axum::response::sse::KeepAlive::new()
+ .interval(Duration::from_secs(1))
+ .text("keep-alive-text"),
+ ))
+}
+
pub fn create_router() -> Router<Arc<AppState>> {
let cors = CorsLayer::new()
.allow_origin(Any)
@@ -1612,6 +1647,7 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/speakers/similar", get(get_similar_speakers_handler))
.route("/experimental/frames/merge", post(merge_frames_handler))
.route("/experimental/validate/media", get(validate_media_handler))
+ .route("/sse/transcriptions", get(sse_transcription_handler))
.layer(cors);
#[cfg(feature = "experimental")]
@@ -1787,7 +1823,7 @@ curl "http://localhost:3030/search?limit=5&offset=0&content_type=all&include_fra
curl "http://localhost:3030/search?limit=1&offset=0&content_type=all&include_frames=true&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq -r '.data[0].content.frame' | base64 --decode > /tmp/frame.png && open /tmp/frame.png
# Search for content from the last 30 minutes
-curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&start_time=$(date -u -v-5M +%Y-%m-%dT%H:%M:%SZ)" | jq
+curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq
# Search for content up to 1 hour ago
curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
index 28fbde700..6b5c6f65a 100644
--- a/screenpipe-server/tests/endpoint_test.rs
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -45,6 +45,8 @@ mod tests {
FrameCache::new(PathBuf::from(""), db).await.unwrap(),
)),
ui_monitoring_enabled: false,
+ realtime_transcription_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
+ realtime_transcription_enabled: false,
});
let router = create_router();
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index 6a39ae3f5..3d737079f 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -40,6 +40,8 @@ async fn setup_test_app() -> (Router, Arc<AppState>) {
FrameCache::new(PathBuf::from(""), db).await.unwrap(),
)),
ui_monitoring_enabled: false,
+ realtime_transcription_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
+ realtime_transcription_enabled: false,
});
let app = create_router().with_state(app_state.clone());
diff --git a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin
index 1546bce73..27dc6d78e 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/apple.rs b/screenpipe-vision/src/apple.rs
index ee00470a0..726d15d17 100644
--- a/screenpipe-vision/src/apple.rs
+++ b/screenpipe-vision/src/apple.rs
@@ -80,7 +80,7 @@ pub fn perform_ocr_apple(
let handler = ImageRequestHandler::with_cv_pixel_buf(&pixel_buf, None).unwrap();
let mut request = RecognizeTextRequest::new();
// Recognize all languages
- request.set_recognition_langs(&languages);
+ request.set_recognition_langs(languages);
request.set_uses_lang_correction(false);
let requests = ns::Array::<vn::Request>::from_slice(&[&request]);
let result = handler.perform(&requests);
@@ -125,10 +125,11 @@ pub fn perform_ocr_apple(
ocr_text.push_str(text.to_string().as_str());
});
- let json_output_string = serde_json::to_string(&ocr_results_vec).unwrap_or_else(|e| {
- error!("Failed to serialize JSON output: {}", e);
- "[]".to_string()
- });
+ let json_output_string =
+ serde_json::to_string(&ocr_results_vec).unwrap_or_else(|e| {
+ error!("Failed to serialize JSON output: {}", e);
+ "[]".to_string()
+ });
return (ocr_text, json_output_string, Some(overall_confidence));
}