YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
refactor: reduce redundant code
Louis Beaumontc7174aa256e0
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex bf46126cf..c3cf74013 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.3.9"+version = "0.4.0"description = ""authors = ["you"]license = ""diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rsindex 2e96a421b..af747b946 100644--- a/screenpipe-audio/src/stt.rs+++ b/screenpipe-audio/src/stt.rs@@ -1,3 +1,10 @@+use crate::{+ audio_processing::normalize_v2,+ encode_single_audio, multilingual,+ vad_engine::{SileroVad, VadEngine, VadEngineEnum, VadSensitivity, WebRtcVad},+ whisper::{Decoder, WhisperModel},+ AudioDevice, AudioTranscriptionEngine, DeviceType,+};use anyhow::Result;use candle::Tensor;use candle_transformers::models::whisper::{self as m, audio};@@ -8,24 +15,15 @@ use objc::rc::autoreleasepool;use rubato::{Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction,};-use std::cmp::min;use std::collections::HashSet;use std::{path::PathBuf,- string,sync::{Arc, Mutex},time::{SystemTime, UNIX_EPOCH},};-use crate::{- audio_processing::normalize_v2,- encode_single_audio, multilingual,- vad_engine::{SileroVad, VadEngine, VadEngineEnum, VadSensitivity, WebRtcVad},- whisper::{Decoder, WhisperModel},- AudioDevice, AudioTranscriptionEngine, DeviceType,-};-use hound::{WavSpec, WavWriter};+use regex::Regex;use reqwest::Client;use serde_json::Value;use std::io::Cursor;@@ -124,14 +122,14 @@ async fn transcribe_with_deepgram(pub fn stt_sync(audio_input: &AudioInput,- whisper_model: &WhisperModel,+ whisper_model: &mut WhisperModel,audio_transcription_engine: Arc<AudioTranscriptionEngine>,vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>, // Changed type heredeepgram_api_key: Option<String>,output_path: &PathBuf,) -> Result<(String, String)> {let audio_input = audio_input.clone();- let whisper_model = whisper_model.clone();+ let mut whisper_model = whisper_model.clone();let output_path = output_path.clone();let vad_engine = vad_engine.clone(); // Clone the Arc to move into the closure@@ -141,7 +139,7 @@ pub fn stt_sync(rt.block_on(stt(&audio_input,- &whisper_model,+ &mut whisper_model,audio_transcription_engine,&mut **vad_engine_guard, // Obtain &mut dyn VadEnginedeepgram_api_key,@@ -153,9 +151,111 @@ pub fn stt_sync(handle.join().unwrap()}+fn process_with_whisper(+ whisper_model: &mut WhisperModel,+ speech_frames: &[f32],+ mel_filters: &[f32],+) -> 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(), 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(model, tokenizer, &mel)?);++ 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);+ 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) -> (String, String) {+ let start = if text[..8].ends_with('>') {+ text[..8].to_string()+ } else {+ text[..9].to_string()+ };++ let end = if text[text.len() - 9..].starts_with('<') {+ text[text.len() - 9..].to_string()+ } else {+ text[text.len() - 8..].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 stt(audio_input: &AudioInput,- whisper_model: &WhisperModel,+ whisper_model: &mut WhisperModel,audio_transcription_engine: Arc<AudioTranscriptionEngine>,vad_engine: &mut dyn VadEngine,deepgram_api_key: Option<String>,@@ -163,8 +263,6 @@ pub async fn stt(skip_encoding: bool,) -> Result<(String, String)> {let model = &whisper_model.model;- let tokenizer = &whisper_model.tokenizer;- let device = &whisper_model.device;debug!("Loading mel filters");let mel_bytes = match model.config().num_mel_bins {@@ -253,15 +351,9 @@ pub async fn stt(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()- };+ let api_key = deepgram_api_key+ .clone()+ .unwrap_or_else(|| get_deepgram_api_key());info!("device: {}, using deepgram api key: {}...",audio_input.device,@@ -281,159 +373,15 @@ pub async fn stt("device: {}, deepgram transcription failed, falling back to Whisper: {:?}",audio_input.device, e);- // Existing Whisper implementation- debug!(- "device: {}, converting pcm to mel spectrogram",- audio_input.device- );- let mel = audio::pcm_to_mel(&model.config(), &speech_frames, &mel_filters);- let mel_len = mel.len();- debug!(- "device: {}, creating tensor from mel spectrogram",- audio_input.device- );- let mel = Tensor::from_vec(- mel,- (- 1,- model.config().num_mel_bins,- mel_len / model.config().num_mel_bins,- ),- &device,- )?;-- debug!("device: {}, detecting language", audio_input.device);- let language_token = Some(multilingual::detect_language(- &mut model.clone(),- &tokenizer,- &mel,- )?);- let mut model = model.clone();- debug!("device: {}, initializing decoder", audio_input.device);- let mut dc = Decoder::new(- &mut model,- tokenizer,- 42,- &device,- language_token,- true,- false,- )?;- debug!("device: {}, starting decoding process", audio_input.device);- let segments = dc.run(&mel)?;- debug!("device: {}, decoding complete", audio_input.device);- Ok(segments- .iter()- .map(|s| s.dr.text.clone())- .collect::<Vec<String>>()- .join("\n"))+ // Fallback to Whisper+ process_with_whisper(&mut *whisper_model, &speech_frames, &mel_filters)}}} else {// Existing Whisper implementation- debug!(- "device: {}, starting whisper transcription",- audio_input.device- );- debug!(- "device: {}, converting pcm to mel spectrogram",- audio_input.device- );- let mel = audio::pcm_to_mel(&model.config(), &speech_frames, &mel_filters);- let mel_len = mel.len();- debug!(- "device: {}, creating tensor from mel spectrogram",- audio_input.device- );- let mel = Tensor::from_vec(- mel,- (- 1,- model.config().num_mel_bins,- mel_len / model.config().num_mel_bins,- ),- &device,- )?;-- debug!("device: {}, detecting language", audio_input.device);- let language_token = Some(multilingual::detect_language(- &mut model.clone(),- &tokenizer,- &mel,- )?);- let mut model = model.clone();- debug!("device: {}, initializing decoder", audio_input.device);- let mut dc = Decoder::new(- &mut model,- tokenizer,- 42,- &device,- language_token,- true,- false,- )?;- debug!("device: {}, starting decoding process", audio_input.device);- let segments = dc.run(&mel)?;- debug!("device: {}, decoding complete", audio_input.device);-- let mut ranges: HashSet<String> = HashSet::new();- let token_regex = Regex::new(r"<\|\d{1,2}\.\d{1,2}\|>")?;- let mut transcript = String::from("");-- let mut min_time: f32 = f32::MAX;- let mut max_time: f32 = f32::MIN;- let mut i = 0;- let segments_len = segments.len();- for segment in segments {- let mut text = segment.dr.text.clone();-- // maybe not <|0.00|> but <|12.34|>- let mut start = text[..8].to_string();- if !start.ends_with('>') {- start = text[..9].to_string();- }- let mut end = text[text.len() - 9..].to_string();- // same but for <- if !end.starts_with('<') {- end = text[text.len() - 8..].to_string();- }- // convert start to float- let num_regex = Regex::new(r"([<>|])")?;- let start_clone = start.clone();- let s_time = num_regex- .replace_all(start_clone.as_str(), "")- .parse::<f32>()- .unwrap_or(min_time);- let e_time = num_regex- .replace_all(end.as_str(), "")- .parse::<f32>()- .unwrap_or(max_time);-- if min_time > s_time {- min_time = s_time;- } else if max_time < e_time {- max_time = e_time;- }-- start.push_str(&end);- // hallucination still present if last range is largest? or if duplicate range?- // still unclear https://github.com/openai/whisper/discussions/679 (try)- if ranges.insert(start) {- if segments_len > 1 && i == segments_len - 1 {- if s_time == min_time && e_time == max_time {- continue;- }- }-- text = token_regex.replace_all(text.as_str(), "").to_string();- text.push('\n');- transcript.push_str(text.as_str());- }- i += 1;- }-- Ok(transcript)+ process_with_whisper(&mut *whisper_model, &speech_frames, &mel_filters)};+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)@@ -523,8 +471,6 @@ impl TranscriptionResult {}use crate::audio_processing::{average_noise_spectrum, spectral_subtraction};-use crate::whisper::Segment;-use regex::Regex;use std::sync::atomic::{AtomicBool, Ordering};use vad_rs::VadStatus;@@ -539,7 +485,7 @@ pub async fn create_whisper_channel(crossbeam::channel::Receiver<TranscriptionResult>,Arc<AtomicBool>, // Shutdown flag)> {- let whisper_model = WhisperModel::new(&audio_transcription_engine)?;+ let mut whisper_model = WhisperModel::new(&audio_transcription_engine)?;let (input_sender, input_receiver): (crossbeam::channel::Sender<AudioInput>,crossbeam::channel::Receiver<AudioInput>,@@ -580,7 +526,7 @@ pub async fn create_whisper_channel(#[cfg(target_os = "macos")]{autoreleasepool(|| {- match stt_sync(&input, &whisper_model, audio_transcription_engine.clone(), vad_engine.clone(), deepgram_api_key.clone(), &output_path) {+ match stt_sync(&input, &mut whisper_model, audio_transcription_engine.clone(), vad_engine.clone(), deepgram_api_key.clone(), &output_path) {Ok((transcription, path)) => TranscriptionResult {input: input.clone(),transcription: Some(transcription),@@ -606,7 +552,7 @@ pub async fn create_whisper_channel(unreachable!("This code should not be reached on non-macOS platforms")}} else {- match stt_sync(&input, &whisper_model, audio_transcription_engine.clone(), vad_engine.clone(), deepgram_api_key.clone(), &output_path) {+ match stt_sync(&input, &mut whisper_model, audio_transcription_engine.clone(), vad_engine.clone(), deepgram_api_key.clone(), &output_path) {Ok((transcription, path)) => TranscriptionResult {input: input.clone(),transcription: Some(transcription),