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

reapplying silero vad implementation changes

matthew-heartful71093af074e6
diff --git a/README.md b/README.md
index ed3abeab8..7c85ae2fe 100644
--- a/README.md
+++ b/README.md
@@ -120,9 +120,13 @@ if you want to run screenpipe in debug mode to show more logs in terminal:
```bash
screenpipe --debug
```
-by default screenpipe is using whisper-tiny that runs LOCALLY to get better quality or lower compute you can use cloud model (we use Deepgram) via cloud api:
+by default screenpipe is using Silero-VAD to identify speech and non-speech tokens to improve audio transcription, bu you can use WebRTC if needed by passing the following command:
```bash
-screenpipe -audio-transcription-engine deepgram
+screenpipe --vad-engine webrtc
+```
+by default screenpipe is using whisper-large that runs LOCALLY to get better quality or lower compute you can use cloud model (we use Deepgram) via cloud api:
+```bash
+screenpipe --audio-transcription-engine deepgram
```
by default screenpipe is using a local model for screen capture OCR processing to use the cloud (through unstructured.io) for better performance use this flag:
```bash
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.toml
index cfb974c53..0d2f92f0f 100644
--- a/screenpipe-audio/Cargo.toml
+++ b/screenpipe-audio/Cargo.toml
@@ -34,6 +34,8 @@ chrono = { version = "0.4.31", features = ["serde"] }
candle = { workspace = true }
candle-nn = { workspace = true }
candle-transformers = { workspace = true }
+ndarray = "0.15.6"
+vad-rs = "0.1.3"
tokenizers = { workspace = true }
anyhow = "1.0.86"
byteorder = "1.5.0"
diff --git a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
index a78f78af9..393e13cff 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
@@ -9,6 +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 std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
@@ -77,8 +78,10 @@ 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)).await?;
-
+ create_whisper_channel(
+ Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),
+ VadEngineEnum::Silero, // Or VadEngineEnum::WebRtc, hardcoded for now
+ ).await?;
// Spawn threads for each device
let _recording_threads: Vec<_> = devices
.into_iter()
diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rs
index c034bcd9c..bf219d7db 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs
@@ -9,6 +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 std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
@@ -79,7 +80,10 @@ 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)).await?;
+ create_whisper_channel(
+ Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),
+ VadEngineEnum::Silero, // Or VadEngineEnum::WebRtc, hardcoded for now
+ ).await?;
// Spawn threads for each device
let recording_threads: Vec<_> = devices
.into_iter()
diff --git a/screenpipe-audio/src/lib.rs b/screenpipe-audio/src/lib.rs
index e2f090871..ba5f5d924 100644
--- a/screenpipe-audio/src/lib.rs
+++ b/screenpipe-audio/src/lib.rs
@@ -2,9 +2,11 @@ mod core;
mod multilingual;
pub mod pcm_decode;
pub mod stt;
+pub mod vad_engine;
pub use core::{
default_input_device, default_output_device, list_audio_devices, parse_audio_device,
record_and_transcribe, AudioDevice, AudioTranscriptionEngine, DeviceControl, DeviceType
};
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 00eedf3b8..3a2ffabb7 100644
--- a/screenpipe-audio/src/stt.rs
+++ b/screenpipe-audio/src/stt.rs
@@ -19,9 +19,12 @@ use rubato::{
Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction,
};
-use crate::{multilingual, pcm_decode::pcm_decode, AudioTranscriptionEngine};
-
-use webrtc_vad::{Vad, VadMode};
+use crate::{
+ multilingual,
+ pcm_decode::pcm_decode,
+ vad_engine::{SileroVad, VadEngine, VadEngineEnum, WebRtcVad},
+ AudioTranscriptionEngine,
+};
use hound::{WavSpec, WavWriter};
use std::io::Cursor;
@@ -509,6 +512,7 @@ pub fn stt(
file_path: &str,
whisper_model: &WhisperModel,
audio_transcription_engine: Arc<AudioTranscriptionEngine>,
+ vad_engine: &mut dyn VadEngine,
) -> Result<String> {
debug!("Starting speech to text for file: {}", file_path);
let model = &whisper_model.model;
@@ -535,25 +539,15 @@ pub fn stt(
pcm_data = resample(pcm_data, sample_rate, m::SAMPLE_RATE as u32)?;
}
- // Initialize VAD
- debug!("VAD: Initializing VAD");
- let mut vad = Vad::new();
- vad.set_mode(VadMode::VeryAggressive); // Set mode to very aggressive
-
- // Filter out non-speech segments
- debug!("VAD: Filtering out non-speech segments");
+ // 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() {
- // Convert f32 to i16
- let i16_chunk: Vec<i16> = chunk.iter().map(|&x| (x * 32767.0) as i16).collect();
- match vad.is_voice_segment(&i16_chunk) {
+ match vad_engine.is_voice_segment(chunk) {
Ok(is_voice) => {
if is_voice {
- // debug!("VAD: Speech detected in frame {}", frame_index);
speech_frames.extend_from_slice(chunk);
- } else {
- // debug!("VAD: Non-speech frame {} filtered out", frame_index);
}
}
Err(e) => {
@@ -723,6 +717,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
pub async fn create_whisper_channel(
audio_transcription_engine: Arc<AudioTranscriptionEngine>,
+ vad_engine: VadEngineEnum,
) -> Result<(
UnboundedSender<AudioInput>,
UnboundedReceiver<TranscriptionResult>,
@@ -737,7 +732,11 @@ pub async fn create_whisper_channel(
UnboundedSender<TranscriptionResult>,
UnboundedReceiver<TranscriptionResult>,
) = unbounded_channel();
-
+ let mut vad_engine: Box<dyn VadEngine + Send> = match vad_engine {
+ 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();
@@ -759,7 +758,7 @@ pub async fn create_whisper_channel(
#[cfg(target_os = "macos")]
{
autoreleasepool(|| {
- match stt(&input.path, &whisper_model, audio_transcription_engine.clone()) {
+ match stt(&input.path, &whisper_model, audio_transcription_engine.clone(), &mut *vad_engine) {
Ok(transcription) => TranscriptionResult {
input: input.clone(),
transcription: Some(transcription),
@@ -780,11 +779,10 @@ pub async fn create_whisper_channel(
}
#[cfg(not(target_os = "macos"))]
{
- // This will be used for non-macOS platforms when compiling for macOS
unreachable!("This code should not be reached on non-macOS platforms")
}
} else {
- match stt(&input.path, &whisper_model, audio_transcription_engine.clone()) {
+ match stt(&input.path, &whisper_model, audio_transcription_engine.clone(), &mut *vad_engine) {
Ok(transcription) => TranscriptionResult {
input: input.clone(),
transcription: Some(transcription),
diff --git a/screenpipe-audio/src/vad_engine.rs b/screenpipe-audio/src/vad_engine.rs
new file mode 100644
index 000000000..5c1b99c87
--- /dev/null
+++ b/screenpipe-audio/src/vad_engine.rs
@@ -0,0 +1,108 @@
+use std::path::PathBuf;
+use vad_rs::{Vad};
+use anyhow;
+use std::io::Write;
+use log::debug;
+
+pub enum VadEngineEnum {
+ WebRtc,
+ Silero,
+}
+
+pub trait VadEngine {
+ fn is_voice_segment(&mut self, audio_chunk: &[f32]) -> anyhow::Result<bool>;
+}
+
+pub struct WebRtcVad(webrtc_vad::Vad);
+
+impl WebRtcVad {
+ pub fn new() -> Self {
+ let mut vad = webrtc_vad::Vad::new();
+ vad.set_mode(webrtc_vad::VadMode::VeryAggressive);
+ Self(vad)
+ }
+}
+
+impl VadEngine for WebRtcVad {
+ fn is_voice_segment(&mut self, audio_chunk: &[f32]) -> anyhow::Result<bool> {
+ // Convert f32 to i16
+ let i16_chunk: Vec<i16> = audio_chunk
+ .iter()
+ .map(|&x| (x * 32767.0) as i16)
+ .collect();
+
+ let result = self.0.is_voice_segment(&i16_chunk)
+ .map_err(|e| anyhow::anyhow!("WebRTC VAD error: {:?}", e))?;
+
+ // debug!("WebRTC VAD result: is_voice_segment = {}", result);
+
+ Ok(result)
+ }
+}
+
+pub struct SileroVad {
+ vad: Vad,
+}
+
+impl SileroVad {
+ pub fn new() -> anyhow::Result<Self> {
+ debug!("Initializing SileroVad...");
+ let model_path = Self::download_model()?;
+ debug!("SileroVad Model downloaded to: {:?}", model_path);
+ let vad = Vad::new(model_path, 16000).map_err(|e| {
+ debug!("SileroVad Error creating Vad: {}", e);
+ anyhow::anyhow!("Vad creation error: {}", e)
+ })?;
+ debug!("SileroVad initialized successfully");
+ Ok(Self { vad })
+ }
+
+ fn download_model() -> anyhow::Result<PathBuf> {
+ debug!("Downloading SileroVAD model...");
+ let url = "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/silero_vad.onnx";
+ let response = reqwest::blocking::get(url)?;
+ let model_data = response.bytes()?;
+
+ let path = std::env::temp_dir().join("silero_vad.onnx");
+ let mut file = std::fs::File::create(&path)?;
+ file.write_all(&model_data)?;
+ debug!("SileroVad Model downloaded and saved to: {:?}", path);
+
+ Ok(path)
+ }
+}
+
+impl VadEngine for SileroVad {
+ fn is_voice_segment(&mut self, audio_chunk: &[f32]) -> anyhow::Result<bool> {
+ const CHUNK_SIZE: usize = 1600; // 100 milliseconds
+
+ for chunk in audio_chunk.chunks(CHUNK_SIZE) {
+ let mut chunk_data: Vec<f32> = chunk.to_vec();
+ chunk_data.resize(CHUNK_SIZE, 0.0);
+
+ let result = self.vad.compute(&chunk_data).map_err(|e| {
+ debug!("SileroVad Error computing VAD: {}", e);
+ anyhow::anyhow!("Vad compute error: {}", e)
+ })?;
+
+ if result.prob < 0.3 {
+ return Ok(true);
+ }
+ }
+
+ Ok(false)
+ }
+}
+
+pub fn create_vad_engine(engine: VadEngineEnum) -> anyhow::Result<Box<dyn VadEngine>> {
+ match engine {
+ VadEngineEnum::WebRtc => Ok(Box::new(WebRtcVad::new())),
+ VadEngineEnum::Silero => {
+ let silero_vad = SileroVad::new()?;
+ Ok(Box::new(silero_vad))
+ },
+ }
+}
+
+unsafe impl Send for WebRtcVad {}
+unsafe impl Send for SileroVad {}
\ No newline at end of file
diff --git a/screenpipe-audio/tests/core_tests.rs b/screenpipe-audio/tests/core_tests.rs
index f4372b09d..d47e624e9 100644
--- a/screenpipe-audio/tests/core_tests.rs
+++ b/screenpipe-audio/tests/core_tests.rs
@@ -13,7 +13,8 @@ mod tests {
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::mpsc::unbounded_channel;
-
+ use screenpipe_audio::vad_engine::{VadEngineEnum, WebRtcVad};
+
fn setup() {
// Initialize the logger with an info level filter
match env_logger::builder()
@@ -50,10 +51,12 @@ mod tests {
let whisper_model =
WhisperModel::new(Arc::new(AudioTranscriptionEngine::WhisperTiny)).unwrap();
+ let mut vad_engine = WebRtcVad::new();
let text = stt(
"./test_data/selah.mp4",
&whisper_model,
Arc::new(AudioTranscriptionEngine::WhisperTiny),
+ &mut vad_engine
)
.unwrap();
let duration = start.elapsed();
@@ -231,9 +234,12 @@ mod tests {
PathBuf::from(format!("test_output_{}.mp4", Utc::now().timestamp_millis()));
let output_path_2 = output_path.clone();
let (whisper_sender, mut whisper_receiver, _) =
- create_whisper_channel(Arc::new(AudioTranscriptionEngine::WhisperTiny))
- .await
- .unwrap();
+ create_whisper_channel(
+ Arc::new(AudioTranscriptionEngine::WhisperTiny),
+ VadEngineEnum::WebRtc
+ )
+ .await
+ .unwrap();
let is_running = Arc::new(AtomicBool::new(true));
// Start recording in a separate thread
let recording_thread = tokio::spawn(async move {
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 0cb2b5e95..f2a0c837d 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -262,6 +262,7 @@ async fn main() -> anyhow::Result<()> {
});
let ocr_engine_clone = cli.ocr_engine.clone();
let restart_interval = cli.restart_interval;
+ let vad_engine = cli.vad_engine.clone();
// Function to start or restart the recording task
let _start_recording = tokio::spawn(async move {
@@ -283,6 +284,7 @@ async fn main() -> anyhow::Result<()> {
let vision_control = vision_control.clone();
let audio_devices_control = audio_devices_control.clone();
let friend_wearable_uid_clone = friend_wearable_uid.clone(); // Clone for each iteration
+ let vad_engine_clone = vad_engine.clone(); // Clone it here for each iteration
tokio::select! {
_ = &mut recording_task => {
@@ -319,10 +321,11 @@ async fn main() -> anyhow::Result<()> {
cli.save_text_files,
audio_transcription_engine,
ocr_engine,
- friend_wearable_uid_clone, // Use the cloned version
+ friend_wearable_uid_clone,
monitor_id,
cli.use_pii_removal,
cli.disable_vision,
+ vad_engine_clone,
)
.await;
diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rs
index 6b852fa70..55525436c 100644
--- a/screenpipe-server/src/cli.rs
+++ b/screenpipe-server/src/cli.rs
@@ -2,6 +2,7 @@ use clap::Parser;
use screenpipe_audio::AudioTranscriptionEngine as CoreAudioTranscriptionEngine;
use screenpipe_vision::utils::OcrEngine as CoreOcrEngine;
use clap::ValueEnum;
+use screenpipe_audio::vad_engine::VadEngineEnum;
#[derive(Clone, Debug, ValueEnum, PartialEq)]
pub enum CliAudioTranscriptionEngine {
@@ -49,6 +50,22 @@ impl From<CliOcrEngine> for CoreOcrEngine {
}
}
}
+#[derive(Clone, Debug, ValueEnum, PartialEq)]
+pub enum CliVadEngine {
+ #[clap(name = "webrtc")]
+ WebRtc,
+ #[clap(name = "silero")]
+ Silero,
+}
+
+impl From<CliVadEngine> for VadEngineEnum {
+ fn from(cli_engine: CliVadEngine) -> Self {
+ match cli_engine {
+ CliVadEngine::WebRtc => VadEngineEnum::WebRtc,
+ CliVadEngine::Silero => VadEngineEnum::Silero,
+ }
+ }
+}
#[derive(Parser)]
#[command(
@@ -155,4 +172,8 @@ pub struct Cli {
/// Disable vision recording
#[arg(long, default_value_t = false)]
pub disable_vision: bool,
+
+ /// VAD engine to use for speech detection
+ #[arg(long, value_enum, default_value_t = CliVadEngine::Silero)] // Silero or WebRtc
+ pub vad_engine: CliVadEngine,
}
\ No newline at end of file
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 23036cd94..1aeace105 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -1,3 +1,4 @@
+use crate::cli::CliVadEngine;
use crate::{DatabaseManager, VideoCapture};
use anyhow::Result;
use chrono::Utc;
@@ -6,6 +7,7 @@ use log::{debug, error, info, warn};
use screenpipe_audio::{
create_whisper_channel, record_and_transcribe, AudioDevice, AudioInput,
AudioTranscriptionEngine, DeviceControl, TranscriptionResult,
+ vad_engine::VadEngineEnum,
};
use screenpipe_core::pii_removal::remove_pii;
use screenpipe_integrations::friend_wearable::initialize_friend_wearable_loop;
@@ -33,6 +35,7 @@ pub async fn start_continuous_recording(
monitor_id: u32,
use_pii_removal: bool,
vision_disabled: bool,
+ vad_engine: CliVadEngine,
) -> Result<()> {
let (whisper_sender, whisper_receiver, whisper_shutdown_flag) = if audio_disabled {
// Create a dummy channel if no audio devices are available, e.g. audio disabled
@@ -48,7 +51,7 @@ pub async fn start_continuous_recording(
Arc::new(AtomicBool::new(false)),
)
} else {
- create_whisper_channel(audio_transcription_engine.clone()).await?
+ create_whisper_channel(audio_transcription_engine.clone(), VadEngineEnum::from(vad_engine)).await?
};
let whisper_sender_clone = whisper_sender.clone();
let db_manager_video = Arc::clone(&db);