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

fix #277

Louis Beaumontda51517dad10
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.toml
index d16a5a2a7..06e0ba9bc 100644
--- a/screenpipe-audio/Cargo.toml
+++ b/screenpipe-audio/Cargo.toml
@@ -46,6 +46,7 @@ rubato = "0.15.0"
# Log
log = { workspace = true }
+tracing = { workspace = true }
env_logger = "0.10"
# Bytes
diff --git a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
index 6c053db37..0c9a2b673 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
@@ -9,7 +9,7 @@ use screenpipe_audio::parse_audio_device;
use screenpipe_audio::record_and_transcribe;
use screenpipe_audio::AudioDevice;
use screenpipe_audio::AudioTranscriptionEngine;
-use screenpipe_audio::VadEngineEnum;
+use screenpipe_audio::VadEngineEnum;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
@@ -80,16 +80,13 @@ async fn main() -> Result<()> {
}
let chunk_duration = Duration::from_secs_f32(args.audio_chunk_duration);
- let (whisper_sender, mut whisper_receiver, _) =
- create_whisper_channel(
- Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),
- // non windows use silero
- #[cfg(not(target_os = "windows"))]
- VadEngineEnum::Silero, // Or VadEngineEnum::WebRtc, hardcoded for now
- #[cfg(target_os = "windows")]
- VadEngineEnum::WebRtc,
- args.deepgram_api_key,
- ).await?;
+ let (whisper_sender, mut whisper_receiver, _) = create_whisper_channel(
+ Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),
+ VadEngineEnum::Silero, // Or VadEngineEnum::WebRtc, hardcoded for now
+ args.deepgram_api_key,
+ &PathBuf::from("output.mp4"),
+ )
+ .await?;
// Spawn threads for each device
let _recording_threads: Vec<_> = devices
.into_iter()
@@ -97,10 +94,7 @@ async fn main() -> Result<()> {
.map(|(i, device)| {
let device = Arc::new(device);
let whisper_sender = whisper_sender.clone();
- let output_path = PathBuf::from(format!(
- "/tmp/output_{}.mp4",
- chrono::Utc::now().timestamp()
- ));
+
let device_control = Arc::new(AtomicBool::new(true));
@@ -109,7 +103,6 @@ async fn main() -> Result<()> {
let result = record_and_transcribe(
Arc::clone(&device),
chunk_duration,
- output_path.clone(),
whisper_sender.clone(),
Arc::clone(&device_control),
)
diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rs
index 6f78ceb95..f946fb06a 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs
@@ -9,7 +9,7 @@ use screenpipe_audio::parse_audio_device;
use screenpipe_audio::record_and_transcribe;
use screenpipe_audio::AudioDevice;
use screenpipe_audio::AudioTranscriptionEngine;
-use screenpipe_audio::VadEngineEnum;
+use screenpipe_audio::VadEngineEnum;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
@@ -84,20 +84,20 @@ async fn main() -> Result<()> {
let chunk_duration = Duration::from_secs(10);
let output_path = PathBuf::from("output.mp4");
- let (whisper_sender, mut whisper_receiver, _) =
- create_whisper_channel(
- Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),
- VadEngineEnum::WebRtc, // Or VadEngineEnum::WebRtc, hardcoded for now
- deepgram_api_key
- ).await?;
+ let (whisper_sender, mut whisper_receiver, _) = create_whisper_channel(
+ Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),
+ VadEngineEnum::WebRtc, // Or VadEngineEnum::WebRtc, hardcoded for now
+ deepgram_api_key,
+ &output_path,
+ )
+ .await?;
// Spawn threads for each device
let recording_threads: Vec<_> = devices
.into_iter()
.enumerate()
- .map(|(i, device)| {
+ .map(|(_, device)| {
let device = Arc::new(device);
let whisper_sender = whisper_sender.clone();
- let output_path = output_path.with_file_name(format!("output_{}.mp4", i));
let device_control = Arc::new(AtomicBool::new(true));
let device_clone = Arc::clone(&device);
@@ -108,7 +108,6 @@ async fn main() -> Result<()> {
record_and_transcribe(
device_clone_2,
chunk_duration,
- output_path,
whisper_sender,
device_control_clone,
)
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index f73a937cb..b7177a982 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -1,18 +1,15 @@
use anyhow::{anyhow, Result};
+use chrono::Utc;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::StreamError;
use log::{debug, error, info, warn};
-use screenpipe_core::find_ffmpeg_path;
use serde::Serialize;
-use std::path::PathBuf;
-use std::process::Stdio;
use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::{Arc, Weak};
+use std::sync::Arc;
use std::time::Duration;
use std::{fmt, thread};
-use tokio::io::AsyncWriteExt;
-use tokio::process::Command;
-use tokio::sync::mpsc::{self, UnboundedSender};
+use tokio::sync::mpsc::UnboundedSender;
+use tokio::sync::Mutex;
use crate::AudioInput;
@@ -159,104 +156,12 @@ async fn get_device_and_config(
Ok((cpal_audio_device, config))
}
-async fn run_ffmpeg(
- mut rx: mpsc::Receiver<Vec<u8>>,
- sample_rate: u32,
- channels: u16,
- output_path: &PathBuf,
- is_running: Weak<AtomicBool>,
- duration: Duration,
-) -> Result<()> {
- debug!("Starting FFmpeg process");
-
- let mut command = Command::new(find_ffmpeg_path().unwrap());
- command
- .args(&[
- "-f",
- "f32le",
- "-ar",
- &sample_rate.to_string(),
- "-ac",
- &channels.to_string(),
- "-i",
- "pipe:0",
- "-c:a",
- "aac",
- "-b:a",
- "64k", // Reduced bitrate for higher compression
- "-profile:a",
- "aac_low", // Use AAC-LC profile for better compatibility
- "-movflags",
- "+faststart", // Optimize for web streaming
- "-f",
- "mp4",
- output_path.to_str().unwrap(),
- ])
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
-
- debug!("FFmpeg command: {:?}", command);
-
- let mut ffmpeg: tokio::process::Child =
- command.spawn().expect("Failed to spawn FFmpeg process");
- debug!("FFmpeg process spawned");
- let mut stdin = ffmpeg.stdin.take().expect("Failed to open stdin");
- let start_time = std::time::Instant::now();
-
- while is_running
- .upgrade()
- .map_or(false, |arc| arc.load(Ordering::Relaxed))
- {
- tokio::select! {
- Some(data) = rx.recv() => {
- if start_time.elapsed() >= duration {
- debug!("Duration exceeded, breaking loop");
- break;
- }
- if let Err(e) = stdin.write_all(&data).await {
- error!("Failed to write audio data to FFmpeg: {}", e);
- break;
- }
- }
- _ = tokio::time::sleep(Duration::from_millis(100)) => {
- if start_time.elapsed() >= duration {
- debug!("Duration exceeded, breaking loop");
- break;
- }
- }
- }
- }
-
- debug!("Dropping stdin");
- drop(stdin);
- debug!("Waiting for FFmpeg process to exit");
- let output = ffmpeg.wait_with_output().await?;
- let status = output.status;
- let stdout = String::from_utf8_lossy(&output.stdout);
- let stderr = String::from_utf8_lossy(&output.stderr);
-
- debug!("FFmpeg process exited with status: {}", status);
- debug!("FFmpeg stdout: {}", stdout);
- debug!("FFmpeg stderr: {}", stderr);
-
- if !status.success() {
- error!("FFmpeg process failed with status: {}", status);
- error!("FFmpeg stderr: {}", stderr);
- // ? ffmpeg.kill().await?;
- return Err(anyhow!("FFmpeg process failed"));
- }
-
- Ok(())
-}
-
pub async fn record_and_transcribe(
audio_device: Arc<AudioDevice>,
duration: Duration,
- output_path: PathBuf,
whisper_sender: UnboundedSender<AudioInput>,
is_running: Arc<AtomicBool>,
-) -> Result<PathBuf> {
+) -> Result<()> {
let (cpal_audio_device, config) = get_device_and_config(&audio_device).await?;
let sample_rate = config.sample_rate().0;
let channels = config.channels() as u16;
@@ -264,16 +169,13 @@ pub async fn record_and_transcribe(
"Audio device config: sample_rate={}, channels={}",
sample_rate, channels
);
+ let start_time = Utc::now();
- // TODO: consider a lock-free ring buffer like crossbeam_queue::ArrayQueue (ask AI why)
- let (tx, rx) = mpsc::channel(100); // For audio data
+ let audio_data = Arc::new(Mutex::new(Vec::new()));
let is_running_weak = Arc::downgrade(&is_running);
let is_running_weak_2 = Arc::downgrade(&is_running);
let is_running_weak_3 = Arc::downgrade(&is_running);
- let is_running_weak_4 = Arc::downgrade(&is_running);
-
- let output_path_clone = Arc::new(output_path);
- let output_path_clone_2 = Arc::clone(&output_path_clone);
+ let audio_data_clone = Arc::clone(&audio_data);
// Define the error callback function
let error_callback = move |err: StreamError| {
@@ -285,6 +187,7 @@ pub async fn record_and_transcribe(
}
}
};
+
// Spawn a thread to handle the non-Send stream
let audio_handle = thread::spawn(move || {
let stream = match config.sample_format() {
@@ -295,7 +198,8 @@ pub async fn record_and_transcribe(
.upgrade()
.map_or(false, |arc| arc.load(Ordering::Relaxed))
{
- let _ = tx.blocking_send(bytemuck::cast_slice(data).to_vec());
+ let mut audio_data = audio_data_clone.blocking_lock();
+ audio_data.extend_from_slice(bytemuck::cast_slice::<i8, f32>(data));
}
},
error_callback,
@@ -308,7 +212,8 @@ pub async fn record_and_transcribe(
.upgrade()
.map_or(false, |arc| arc.load(Ordering::Relaxed))
{
- let _ = tx.blocking_send(bytemuck::cast_slice(data).to_vec());
+ let mut audio_data = audio_data_clone.blocking_lock();
+ audio_data.extend_from_slice(bytemuck::cast_slice(data));
}
},
error_callback,
@@ -321,7 +226,8 @@ pub async fn record_and_transcribe(
.upgrade()
.map_or(false, |arc| arc.load(Ordering::Relaxed))
{
- let _ = tx.blocking_send(bytemuck::cast_slice(data).to_vec());
+ let mut audio_data = audio_data_clone.blocking_lock();
+ audio_data.extend_from_slice(bytemuck::cast_slice(data));
}
},
error_callback,
@@ -334,7 +240,8 @@ pub async fn record_and_transcribe(
.upgrade()
.map_or(false, |arc| arc.load(Ordering::Relaxed))
{
- let _ = tx.blocking_send(bytemuck::cast_slice(data).to_vec());
+ let mut audio_data = audio_data_clone.blocking_lock();
+ audio_data.extend_from_slice(bytemuck::cast_slice(data));
}
},
error_callback,
@@ -346,8 +253,6 @@ pub async fn record_and_transcribe(
}
};
- // ? drop(tx);
-
match stream {
Ok(s) => {
if let Err(e) = s.play() {
@@ -373,47 +278,37 @@ pub async fn record_and_transcribe(
duration.as_secs()
);
- // Run FFmpeg in a separate task
- let ffmpeg_handle = run_ffmpeg(
- rx,
- sample_rate,
- channels,
- &output_path_clone,
- is_running_weak_4,
- duration,
- );
-
- ffmpeg_handle.await?;
-
- info!(
- "Recording stopped, wrote to {}. Now triggering transcription",
- output_path_clone_2.to_str().unwrap()
- );
+ // wait for the duration unless is_running is false
+ while is_running.load(Ordering::Relaxed) {
+ std::thread::sleep(Duration::from_millis(100));
+ if Utc::now().timestamp() - start_time.timestamp() > duration.as_secs() as i64 {
+ debug!("Recording duration reached");
+ break;
+ }
+ }
// Signal the recording thread to stop
- is_running.store(false, Ordering::Relaxed); // TODO: could also just kill the trhead..
+ is_running.store(false, Ordering::Relaxed);
// Wait for the native thread to finish
if let Err(e) = audio_handle.join() {
error!("Error joining audio thread: {:?}", e);
}
- // Commented to chekc if its the "Access is denied on windows" error
- // tokio::fs::File::open(&output_path_clone_2.to_path_buf())
- // .await?
- // .sync_all()
- // .await?;
-
debug!("Sending audio to audio model");
+ let data = audio_data.lock().await;
+ debug!("Sending audio of length {} to audio model", data.len());
if let Err(e) = whisper_sender.send(AudioInput {
- path: output_path_clone_2.to_str().unwrap().to_string(),
+ data: data.clone(),
device: audio_device.to_string(),
+ sample_rate,
+ channels,
}) {
error!("Failed to send audio to audio model: {}", e);
}
debug!("Sent audio to audio model");
- Ok(output_path_clone_2.to_path_buf())
+ Ok(())
}
pub async fn list_audio_devices() -> Result<Vec<AudioDevice>> {
diff --git a/screenpipe-audio/src/encode.rs b/screenpipe-audio/src/encode.rs
new file mode 100644
index 000000000..00d58d47d
--- /dev/null
+++ b/screenpipe-audio/src/encode.rs
@@ -0,0 +1,74 @@
+use screenpipe_core::find_ffmpeg_path;
+use std::io::Write;
+use std::{
+ path::PathBuf,
+ process::{Command, Stdio},
+};
+use tracing::{debug, error};
+
+pub fn encode_single_audio(
+ data: &[u8],
+ sample_rate: u32,
+ channels: u16,
+ output_path: &PathBuf,
+) -> anyhow::Result<()> {
+ debug!("Starting FFmpeg process");
+
+ let mut command = Command::new(find_ffmpeg_path().unwrap());
+ command
+ .args(&[
+ "-f",
+ "f32le",
+ "-ar",
+ &sample_rate.to_string(),
+ "-ac",
+ &channels.to_string(),
+ "-i",
+ "pipe:0",
+ "-c:a",
+ "aac",
+ "-b:a",
+ "64k", // Reduced bitrate for higher compression
+ "-profile:a",
+ "aac_low", // Use AAC-LC profile for better compatibility
+ "-movflags",
+ "+faststart", // Optimize for web streaming
+ "-f",
+ "mp4",
+ output_path.to_str().unwrap(),
+ ])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ debug!("FFmpeg command: {:?}", command);
+
+ 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");
+
+ stdin.write_all(data)?;
+
+ debug!("Dropping stdin");
+ drop(stdin);
+ debug!("Waiting for FFmpeg process to exit");
+ let output = ffmpeg.wait_with_output().unwrap();
+ let status = output.status;
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ debug!("FFmpeg process exited with status: {}", status);
+ debug!("FFmpeg stdout: {}", stdout);
+ debug!("FFmpeg stderr: {}", stderr);
+
+ if !status.success() {
+ error!("FFmpeg process failed with status: {}", status);
+ error!("FFmpeg stderr: {}", stderr);
+ return Err(anyhow::anyhow!(
+ "FFmpeg process failed with status: {}",
+ status
+ ));
+ }
+
+ Ok(())
+}
diff --git a/screenpipe-audio/src/lib.rs b/screenpipe-audio/src/lib.rs
index ba5f5d924..884bb926a 100644
--- a/screenpipe-audio/src/lib.rs
+++ b/screenpipe-audio/src/lib.rs
@@ -3,10 +3,12 @@ mod multilingual;
pub mod pcm_decode;
pub mod stt;
pub mod vad_engine;
+pub mod encode;
pub use core::{
default_input_device, default_output_device, list_audio_devices, parse_audio_device,
record_and_transcribe, AudioDevice, AudioTranscriptionEngine, DeviceControl, DeviceType
};
+pub use encode::encode_single_audio;
pub use pcm_decode::pcm_decode;
pub use stt::{create_whisper_channel, stt, AudioInput, TranscriptionResult, WhisperModel};
pub use vad_engine::VadEngineEnum;
\ No newline at end of file
diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rs
index f219e079f..87d5f0ee0 100644
--- a/screenpipe-audio/src/stt.rs
+++ b/screenpipe-audio/src/stt.rs
@@ -1,4 +1,5 @@
use std::{
+ path::PathBuf,
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
@@ -6,6 +7,7 @@ use std::{
use anyhow::{Error as E, Result};
use candle::{Device, IndexOp, Tensor};
use candle_nn::{ops::softmax, VarBuilder};
+use chrono::Utc;
use hf_hub::{api::sync::Api, Repo, RepoType};
use log::{debug, error, info};
#[cfg(target_os = "macos")]
@@ -20,8 +22,7 @@ use rubato::{
};
use crate::{
- multilingual,
- pcm_decode::pcm_decode,
+ encode_single_audio, multilingual,
vad_engine::{SileroVad, VadEngine, VadEngineEnum, WebRtcVad},
AudioTranscriptionEngine,
};
@@ -509,13 +510,13 @@ fn transcribe_with_deepgram(api_key: &str, audio_data: &[f32]) -> Result<String>
}
pub fn stt(
- file_path: &str,
+ audio_input: &AudioInput,
whisper_model: &WhisperModel,
audio_transcription_engine: Arc<AudioTranscriptionEngine>,
vad_engine: &mut dyn VadEngine,
deepgram_api_key: Option<String>,
-) -> Result<String> {
- debug!("Starting speech to text for file: {}", file_path);
+ output_path: &PathBuf,
+) -> Result<(String, String)> {
let model = &whisper_model.model;
let tokenizer = &whisper_model.tokenizer;
let device = &whisper_model.device;
@@ -529,22 +530,21 @@ pub fn stt(
let mut mel_filters = vec![0f32; mel_bytes.len() / 4];
<byteorder::LittleEndian as byteorder::ByteOrder>::read_f32_into(mel_bytes, &mut mel_filters);
- debug!("Decoding PCM data");
- let (mut pcm_data, sample_rate) = pcm_decode(file_path)?;
- if sample_rate != m::SAMPLE_RATE as u32 {
+ let mut audio_data = audio_input.data.clone();
+ if audio_input.sample_rate != m::SAMPLE_RATE as u32 {
info!(
"Resampling from {} Hz to {} Hz",
- sample_rate,
+ audio_input.sample_rate,
m::SAMPLE_RATE
);
- pcm_data = resample(pcm_data, sample_rate, m::SAMPLE_RATE as u32)?;
+ audio_data = resample(audio_data, audio_input.sample_rate, m::SAMPLE_RATE as u32)?;
}
// Filter out non-speech segments using Silero VAD
debug!("Filtering out non-speech segments with VAD");
let frame_size = 160; // 10ms frame size for 16kHz audio
let mut speech_frames = Vec::new();
- for (frame_index, chunk) in pcm_data.chunks(frame_size).enumerate() {
+ for (frame_index, chunk) in audio_data.chunks(frame_size).enumerate() {
match vad_engine.is_voice_segment(chunk) {
Ok(is_voice) => {
if is_voice {
@@ -553,136 +553,152 @@ pub fn stt(
}
Err(e) => {
debug!("VAD failed for frame {}: {:?}", frame_index, e);
- // Optionally, you can choose to include the frame if VAD fails
- // speech_frames.extend_from_slice(chunk);
}
}
}
info!(
"Total audio_frames processed: {}, frames that include speech: {}",
- pcm_data.len() / frame_size,
+ audio_data.len() / frame_size,
speech_frames.len() / frame_size
);
// If no speech frames detected, skip processing
if speech_frames.is_empty() {
debug!("No speech detected using VAD, skipping audio processing");
- return Ok("".to_string()); // Return an empty string or consider a more specific "no speech" indicator
+ return Ok(("".to_string(), "".to_string())); // Return an empty string or consider a more specific "no speech" indicator
}
debug!(
"Using {} speech frames out of {} total frames",
speech_frames.len() / frame_size,
- pcm_data.len() / frame_size
+ audio_data.len() / frame_size
);
- if audio_transcription_engine == AudioTranscriptionEngine::Deepgram.into() {
- // Deepgram implementation
- //check if key is set or empty or no chars in it
- let api_key = if deepgram_api_key.clone().is_some()
- && !deepgram_api_key.clone().unwrap().is_empty()
- && deepgram_api_key.clone().unwrap().chars().count() > 0
- {
- deepgram_api_key.clone().unwrap()
+ let transcription: Result<String> =
+ if audio_transcription_engine == AudioTranscriptionEngine::Deepgram.into() {
+ // Deepgram implementation
+ //check if key is set or empty or no chars in it
+ let api_key = if deepgram_api_key.clone().is_some()
+ && !deepgram_api_key.clone().unwrap().is_empty()
+ && deepgram_api_key.clone().unwrap().chars().count() > 0
+ {
+ deepgram_api_key.clone().unwrap()
+ } else {
+ get_deepgram_api_key()
+ };
+ info!("Using Deepgram API key: {}...", &api_key[..8]);
+ match transcribe_with_deepgram(&api_key, &speech_frames) {
+ Ok(transcription) => Ok(transcription),
+ Err(e) => {
+ error!(
+ "Deepgram transcription failed, falling back to Whisper: {:?}",
+ e
+ );
+ // Existing Whisper implementation
+ debug!("Converting PCM to mel spectrogram");
+ let mel = audio::pcm_to_mel(&model.config(), &speech_frames, &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(
+ &mut model.clone(),
+ &tokenizer,
+ &mel,
+ )?);
+ let mut model = model.clone();
+ debug!("Initializing decoder");
+ let mut dc = Decoder::new(
+ &mut model,
+ tokenizer,
+ 42,
+ &device,
+ language_token,
+ Some(Task::Transcribe),
+ true,
+ false,
+ )?;
+ debug!("Starting decoding process");
+ let segments = dc.run(&mel)?;
+ debug!("Decoding complete");
+ Ok(segments
+ .iter()
+ .map(|s| s.dr.text.clone())
+ .collect::<Vec<String>>()
+ .join("\n"))
+ }
+ }
} else {
- get_deepgram_api_key()
+ // Existing Whisper implementation
+ debug!("Starting Whisper transcription");
+ debug!("Converting PCM to mel spectrogram");
+ let mel = audio::pcm_to_mel(&model.config(), &speech_frames, &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(
+ &mut model.clone(),
+ &tokenizer,
+ &mel,
+ )?);
+ let mut model = model.clone();
+ debug!("Initializing decoder");
+ let mut dc = Decoder::new(
+ &mut model,
+ tokenizer,
+ 42,
+ &device,
+ language_token,
+ Some(Task::Transcribe),
+ true,
+ false,
+ )?;
+ debug!("Starting decoding process");
+ let segments = dc.run(&mel)?;
+ debug!("Decoding complete");
+ Ok(segments
+ .iter()
+ .map(|s| s.dr.text.clone())
+ .collect::<Vec<String>>()
+ .join("\n"))
};
- info!("Using Deepgram API key: {}...", &api_key[..8]);
- match transcribe_with_deepgram(&api_key, &speech_frames) {
- Ok(transcription) => Ok(transcription),
- Err(e) => {
- error!(
- "Deepgram transcription failed, falling back to Whisper: {:?}",
- e
- );
- // Existing Whisper implementation
- debug!("Converting PCM to mel spectrogram");
- let mel = audio::pcm_to_mel(&model.config(), &speech_frames, &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(
- &mut model.clone(),
- &tokenizer,
- &mel,
- )?);
- let mut model = model.clone();
- debug!("Initializing decoder");
- let mut dc = Decoder::new(
- &mut model,
- tokenizer,
- 42,
- &device,
- language_token,
- Some(Task::Transcribe),
- true,
- false,
- )?;
- debug!("Starting decoding process");
- let segments = dc.run(&mel)?;
- debug!("Decoding complete");
- Ok(segments
- .iter()
- .map(|s| s.dr.text.clone())
- .collect::<Vec<String>>()
- .join("\n"))
- }
- }
- } else {
- // Existing Whisper implementation
- debug!("Starting Whisper transcription");
- debug!("Converting PCM to mel spectrogram");
- let mel = audio::pcm_to_mel(&model.config(), &speech_frames, &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(
- &mut model.clone(),
- &tokenizer,
- &mel,
- )?);
- let mut model = model.clone();
- debug!("Initializing decoder");
- let mut dc = Decoder::new(
- &mut model,
- tokenizer,
- 42,
- &device,
- language_token,
- Some(Task::Transcribe),
- true,
- false,
- )?;
- debug!("Starting decoding process");
- let segments = dc.run(&mel)?;
- debug!("Decoding complete");
- Ok(segments
- .iter()
- .map(|s| s.dr.text.clone())
- .collect::<Vec<String>>()
- .join("\n"))
- }
+ let new_file_name = Utc::now().format("%Y-%m-%d_%H-%M-%S").to_string();
+ let sanitized_device_name = audio_input.device.to_string().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
+ encode_single_audio(
+ bytemuck::cast_slice(&audio_input.data),
+ audio_input.sample_rate,
+ audio_input.channels,
+ &file_path.into(),
+ )?;
+
+ Ok((transcription?, file_path_clone))
}
fn resample(input: Vec<f32>, from_sample_rate: u32, to_sample_rate: u32) -> Result<Vec<f32>> {
@@ -712,12 +728,16 @@ fn resample(input: Vec<f32>, from_sample_rate: u32, to_sample_rate: u32) -> Resu
#[derive(Debug, Clone)]
pub struct AudioInput {
- pub path: String,
+ pub data: Vec<f32>,
+
+ pub sample_rate: u32,
+ pub channels: u16,
pub device: String,
}
#[derive(Debug, Clone)]
pub struct TranscriptionResult {
+ pub path: String,
pub input: AudioInput,
pub transcription: Option<String>,
pub timestamp: u64,
@@ -729,6 +749,7 @@ pub async fn create_whisper_channel(
audio_transcription_engine: Arc<AudioTranscriptionEngine>,
vad_engine: VadEngineEnum,
deepgram_api_key: Option<String>,
+ output_path: &PathBuf,
) -> Result<(
UnboundedSender<AudioInput>,
UnboundedReceiver<TranscriptionResult>,
@@ -747,9 +768,10 @@ pub async fn create_whisper_channel(
VadEngineEnum::WebRtc => Box::new(WebRtcVad::new()),
VadEngineEnum::Silero => Box::new(SileroVad::new()?),
};
-
+
let shutdown_flag = Arc::new(AtomicBool::new(false));
let shutdown_flag_clone = shutdown_flag.clone();
+ let output_path = output_path.clone();
tokio::spawn(async move {
loop {
@@ -757,9 +779,11 @@ pub async fn create_whisper_channel(
info!("Whisper channel shutting down");
break;
}
+ debug!("Waiting for input from input_receiver");
tokio::select! {
Some(input) = input_receiver.recv() => {
+ debug!("Received input from input_receiver");
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards")
@@ -769,18 +793,20 @@ pub async fn create_whisper_channel(
#[cfg(target_os = "macos")]
{
autoreleasepool(|| {
- match stt(&input.path, &whisper_model, audio_transcription_engine.clone(), &mut *vad_engine, deepgram_api_key.clone()) {
- Ok(transcription) => TranscriptionResult {
+ match stt(&input, &whisper_model, audio_transcription_engine.clone(), &mut *vad_engine, deepgram_api_key.clone(), &output_path) {
+ Ok((transcription, path)) => TranscriptionResult {
input: input.clone(),
transcription: Some(transcription),
+ path,
timestamp,
error: None,
},
Err(e) => {
- error!("STT error for input {}: {:?}", input.path, e);
+ error!("STT error for input {}: {:?}", input.device, e);
TranscriptionResult {
input: input.clone(),
transcription: None,
+ path: "".to_string(),
timestamp,
error: Some(e.to_string()),
}
@@ -793,18 +819,20 @@ pub async fn create_whisper_channel(
unreachable!("This code should not be reached on non-macOS platforms")
}
} else {
- match stt(&input.path, &whisper_model, audio_transcription_engine.clone(), &mut *vad_engine, deepgram_api_key.clone()) {
- Ok(transcription) => TranscriptionResult {
+ match stt(&input, &whisper_model, audio_transcription_engine.clone(), &mut *vad_engine, deepgram_api_key.clone(), &output_path) {
+ Ok((transcription, path)) => TranscriptionResult {
input: input.clone(),
transcription: Some(transcription),
+ path,
timestamp,
error: None,
},
Err(e) => {
- error!("STT error for input {}: {:?}", input.path, e);
+ error!("STT error for input {}: {:?}", input.device, e);
TranscriptionResult {
input: input.clone(),
transcription: None,
+ path: "".to_string(),
timestamp,
error: Some(e.to_string()),
}
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index c706cc6c4..ce29e0736 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -1,14 +1,12 @@
use crate::cli::CliVadEngine;
use crate::{DatabaseManager, VideoCapture};
use anyhow::Result;
-use chrono::Utc;
use crossbeam::queue::SegQueue;
use futures::future::join_all;
use log::{debug, error, info, warn};
use screenpipe_audio::{
- create_whisper_channel, record_and_transcribe, AudioDevice, AudioInput,
- AudioTranscriptionEngine, DeviceControl, TranscriptionResult,
- vad_engine::VadEngineEnum,
+ create_whisper_channel, record_and_transcribe, vad_engine::VadEngineEnum, AudioDevice,
+ AudioInput, AudioTranscriptionEngine, DeviceControl, TranscriptionResult,
};
use screenpipe_core::pii_removal::remove_pii;
use screenpipe_integrations::friend_wearable::initialize_friend_wearable_loop;
@@ -59,11 +57,16 @@ pub async fn start_continuous_recording(
Arc::new(AtomicBool::new(false)),
)
} else {
- create_whisper_channel(audio_transcription_engine.clone(), VadEngineEnum::from(vad_engine), deepgram_api_key).await?
+ create_whisper_channel(
+ audio_transcription_engine.clone(),
+ VadEngineEnum::from(vad_engine),
+ deepgram_api_key,
+ &PathBuf::from(output_path.as_ref()),
+ )
+ .await?
};
let whisper_sender_clone = whisper_sender.clone();
let db_manager_audio = Arc::clone(&db);
- let output_path_audio = Arc::clone(&output_path);
// Initialize friend wearable loop
if let Some(uid) = &friend_wearable_uid {
tokio::spawn(initialize_friend_wearable_loop(
@@ -116,7 +119,6 @@ pub async fn start_continuous_recording(
audio_handle.spawn(async move {
record_audio(
db_manager_audio,
- output_path_audio,
audio_chunk_duration,
whisper_sender,
whisper_receiver,
@@ -246,7 +248,6 @@ async fn record_video(
async fn record_audio(
db: Arc<DatabaseManager>,
- output_path: Arc<String>,
chunk_duration: Duration,
whisper_sender: UnboundedSender<AudioInput>,
mut whisper_receiver: UnboundedReceiver<TranscriptionResult>,
@@ -270,7 +271,6 @@ async fn record_audio(
continue;
}
- let output_path_clone = Arc::clone(&output_path);
let whisper_sender_clone = whisper_sender.clone();
let audio_device = Arc::new(audio_device);
@@ -292,20 +292,11 @@ async fn record_audio(
iteration, audio_device_clone
);
- let output_path_clone = Arc::clone(&output_path_clone);
let whisper_sender = whisper_sender_clone.clone();
let audio_device_clone = audio_device_clone.clone();
let audio_device_clone_2 = audio_device_clone.clone();
let device_control_clone = device_control_clone.clone();
- let new_file_name = Utc::now().format("%Y-%m-%d_%H-%M-%S").to_string();
- let sanitized_device_name =
- audio_device_clone.to_string().replace(['/', '\\'], "_");
- let file_path = PathBuf::from(&*output_path_clone)
- .join(format!("{}_{}.mp4", sanitized_device_name, new_file_name))
- .to_str()
- .expect("Failed to create valid path")
- .to_string();
debug!(
"Starting record_and_transcribe for device {} (iteration {})",
audio_device_clone, iteration
@@ -313,7 +304,6 @@ async fn record_audio(
let result = record_and_transcribe(
audio_device_clone,
chunk_duration,
- file_path.into(),
whisper_sender,
Arc::new(AtomicBool::new(device_control_clone.is_running)),
)
@@ -396,8 +386,8 @@ async fn process_audio_result(
let transcription = result.transcription.unwrap();
let transcription_engine = audio_transcription_engine.to_string();
- info!("Inserting audio chunk: {:?}", result.input.path);
- match db.insert_audio_chunk(&result.input.path).await {
+ info!("Inserting audio chunk: {:?}", result.path);
+ match db.insert_audio_chunk(&result.path).await {
Ok(audio_chunk_id) => {
if transcription.is_empty() {
return Ok(());