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: 10x audio transcription quality

Louis Beaumontd8ea63635d0c
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index d02ad0262..b37bab670 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.2.45"
+version = "0.2.46"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index 6d33cdb8f..a2346be30 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -41,13 +41,13 @@ pub struct DeviceControl {
pub is_paused: bool,
}
-#[derive(Clone, Eq, PartialEq, Hash, Serialize)]
+#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug)]
pub enum DeviceType {
Input,
Output,
}
-#[derive(Clone, Eq, PartialEq, Hash, Serialize)]
+#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug)]
pub struct AudioDevice {
pub name: String,
pub device_type: DeviceType,
@@ -299,7 +299,7 @@ pub async fn record_and_transcribe(
debug!("Sending audio of length {} to audio model", data.len());
if let Err(e) = whisper_sender.send(AudioInput {
data: data.clone(),
- device: audio_device.to_string(),
+ device: audio_device.clone(),
sample_rate,
channels,
}) {
diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rs
index f09d909ed..f9bcf92d8 100644
--- a/screenpipe-audio/src/stt.rs
+++ b/screenpipe-audio/src/stt.rs
@@ -24,7 +24,7 @@ use rubato::{
use crate::{
encode_single_audio, multilingual,
vad_engine::{SileroVad, VadEngine, VadEngineEnum, WebRtcVad},
- AudioTranscriptionEngine,
+ AudioDevice, AudioTranscriptionEngine,
};
use hound::{WavSpec, WavWriter};
@@ -555,13 +555,46 @@ pub fn stt(
"device: {}, filtering out non-speech segments with VAD",
audio_input.device
);
- let frame_size = 160; // 10ms frame size for 16kHz audio
+ let frame_size = 1600; // 10ms frame size for 16kHz audio
let mut speech_frames = Vec::new();
+ let mut is_speech = false;
+ let mut speech_duration = 0.0;
+ let mut silence_duration = 0.0;
+ let min_speech_dur = 0.3; // Minimum speech duration in seconds
+ let min_silence_dur = 0.5; // Minimum silence duration in seconds
+ let sample_rate = m::SAMPLE_RATE as f32;
+
for (frame_index, chunk) in audio_data.chunks(frame_size).enumerate() {
match vad_engine.is_voice_segment(chunk) {
Ok(is_voice) => {
if is_voice {
+ if is_speech {
+ speech_duration += frame_size as f32 / sample_rate;
+ } else {
+ if silence_duration >= min_silence_dur {
+ silence_duration = 0.0;
+ }
+ speech_duration = frame_size as f32 / sample_rate;
+ is_speech = true;
+ }
speech_frames.extend_from_slice(chunk);
+ } else {
+ if is_speech {
+ if speech_duration >= min_speech_dur {
+ // Keep the speech segment
+ silence_duration = frame_size as f32 / sample_rate;
+ } else {
+ // Discard short speech segment
+ speech_frames.truncate(
+ speech_frames.len() - speech_duration as usize * frame_size,
+ );
+ silence_duration += speech_duration + frame_size as f32 / sample_rate;
+ }
+ speech_duration = 0.0;
+ is_speech = false;
+ } else {
+ silence_duration += frame_size as f32 / sample_rate;
+ }
}
}
Err(e) => {
@@ -613,7 +646,7 @@ pub fn stt(
match transcribe_with_deepgram(
&api_key,
&speech_frames,
- &audio_input.device,
+ &audio_input.device.name,
audio_input.sample_rate,
) {
Ok(transcription) => Ok(transcription),
@@ -773,7 +806,7 @@ pub struct AudioInput {
pub data: Vec<f32>,
pub sample_rate: u32,
pub channels: u16,
- pub device: String,
+ pub device: Arc<AudioDevice>,
}
#[derive(Debug, Clone)]
diff --git a/screenpipe-audio/src/vad_engine.rs b/screenpipe-audio/src/vad_engine.rs
index 630fb5d45..27740f9e9 100644
--- a/screenpipe-audio/src/vad_engine.rs
+++ b/screenpipe-audio/src/vad_engine.rs
@@ -2,7 +2,7 @@ use anyhow;
use log::debug;
use std::io::Write;
use std::path::PathBuf;
-use vad_rs::Vad;
+use vad_rs::{Vad, VadStatus};
pub enum VadEngineEnum {
WebRtc,
@@ -80,12 +80,12 @@ impl VadEngine for SileroVad {
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| {
+ let mut 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 {
+ if result.status() == VadStatus::Speech {
return Ok(true);
}
}
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 8d4526977..c7f1f6b5a 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -106,17 +106,18 @@ async fn main() -> anyhow::Result<()> {
// Add custom log levels for specific modules based on environment variables
let env_filter = env::var("SCREENPIPE_LOG")
- .unwrap_or_default()
- .split(',')
- .fold(env_filter, |filter, module_directive| {
- match module_directive.parse() {
- Ok(directive) => filter.add_directive(directive),
- Err(e) => {
- eprintln!("warning: invalid log directive '{}': {}", module_directive, e);
- filter
+ .unwrap_or_default()
+ .split(',')
+ .filter(|s| !s.is_empty()) // Filter out empty strings
+ .fold(env_filter, |filter, module_directive| {
+ match module_directive.parse() {
+ Ok(directive) => filter.add_directive(directive),
+ Err(e) => {
+ eprintln!("warning: invalid log directive '{}': {}", module_directive, e);
+ filter
+ }
}
- }
- });
+ });
// Usage:
// SCREENPIPE_LOG=screenpipe_audio=debug ./screenpipe
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 02cb35fea..305810720 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -405,6 +405,7 @@ async fn process_audio_result(
&transcription,
0,
&transcription_engine,
+ &result.input.device,
)
.await
{
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index be6249a13..c18ad7201 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -2,6 +2,7 @@ use crate::filtering::filter_texts;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use log::{debug, error, info, warn};
+use screenpipe_audio::{AudioDevice, DeviceType};
use screenpipe_integrations::friend_wearable::FriendWearableDatabase;
use screenpipe_vision::OcrEngine;
use serde::{Deserialize, Serialize};
@@ -204,80 +205,27 @@ impl DatabaseManager {
transcription: &str,
offset_index: i64,
transcription_engine: &str,
+ device: &AudioDevice,
) -> Result<(), sqlx::Error> {
let mut tx = self.pool.begin().await?;
// Insert the full transcription
sqlx::query(
- "INSERT INTO audio_transcriptions (audio_chunk_id, transcription, offset_index, timestamp, transcription_engine) VALUES (?1, ?2, ?3, ?4, ?5)",
+ "INSERT INTO audio_transcriptions (audio_chunk_id, transcription, offset_index, timestamp, transcription_engine, device, is_input_device) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
)
.bind(audio_chunk_id)
.bind(transcription)
.bind(offset_index)
.bind(Utc::now())
.bind(transcription_engine)
+ .bind(&device.name)
+ .bind(device.device_type == DeviceType::Input)
.execute(&mut *tx)
.await?;
// Commit the transaction for the full transcription
tx.commit().await?;
- // // Now, let's chunk the transcription and insert into chunk tables
- // const CHUNKING_ENGINE: &str = "local_simple";
-
- // let chunks = match CHUNKING_ENGINE {
- // "local_simple" => text_chunking_simple(transcription),
- // "candle_jina_bert" => text_chunking_by_similarity(transcription).await,
- // "unstructured" => unstructured_chunking(transcription)
- // .map_err(|e| anyhow::anyhow!(e))
- // .and_then(|chunks| Ok(chunks)),
- // _ => text_chunking_simple(transcription), // Default to simple chunking for unknown engines
- // };
-
- // match chunks {
- // Ok(chunks) => {
- // info!(
- // "Successfully chunked audio transcription into {} chunks",
- // chunks.len()
- // );
- // for chunk in chunks.iter() {
- // if let Err(e) = self
- // .insert_chunked_text(
- // audio_chunk_id,
- // chunk,
- // Utc::now(),
- // transcription_engine,
- // CHUNKING_ENGINE,
- // ContentSource::Audio,
- // )
- // .await
- // {
- // error!("Failed to insert chunk into chunked text index: {}", e);
- // }
- // }
- // }
- // Err(e) => {
- // error!("Failed to chunk audio transcription: {}", e);
- // // Fallback to inserting the whole transcription as a single chunk
- // if let Err(e) = self
- // .insert_chunked_text(
- // audio_chunk_id,
- // transcription,
- // Utc::now(),
- // transcription_engine,
- // "No_Chunking",
- // ContentSource::Audio,
- // )
- // .await
- // {
- // error!(
- // "Failed to insert whole audio transcription into chunked text index: {}",
- // e
- // );
- // }
- // }
- // }
-
Ok(())
}
@@ -538,8 +486,10 @@ impl DatabaseManager {
results.extend(ocr_results.into_iter().map(SearchResult::OCR));
}
- if (content_type == ContentType::All || content_type == ContentType::Audio)
- && app_name.is_none() && window_name.is_none() {
+ if (content_type == ContentType::All || content_type == ContentType::Audio)
+ && app_name.is_none()
+ && window_name.is_none()
+ {
let audio_results = self
.search_audio(
query, limit, offset, start_time, end_time, min_length, max_length,
diff --git a/screenpipe-server/src/migrations/20240917213422_add_device_info_to_audio_transcriptions.sql b/screenpipe-server/src/migrations/20240917213422_add_device_info_to_audio_transcriptions.sql
new file mode 100644
index 000000000..5cc751431
--- /dev/null
+++ b/screenpipe-server/src/migrations/20240917213422_add_device_info_to_audio_transcriptions.sql
@@ -0,0 +1,6 @@
+-- Add device and is_input_device columns to audio_transcriptions table
+ALTER TABLE audio_transcriptions ADD COLUMN device TEXT NOT NULL DEFAULT '';
+ALTER TABLE audio_transcriptions ADD COLUMN is_input_device BOOLEAN NOT NULL DEFAULT TRUE;
+
+-- Create an index on the new device column
+CREATE INDEX idx_audio_transcriptions_device ON audio_transcriptions(device);
\ No newline at end of file