diff --git a/frontend/src/app.rs b/frontend/src/app.rs index 2077521..b51bad8 100644 --- a/frontend/src/app.rs +++ b/frontend/src/app.rs @@ -18,7 +18,7 @@ use crate::config::AppConfig; use crate::markdown; use crate::model::{ChatMessage, Project, PublicUser, StoredMessage}; use crate::tamagotchi::{self, Mood}; -use crate::voice::audio::Recorder; +use crate::voice::audio::{self, Recorder}; use crate::voice::engine::{self, VoiceConfig, VoiceEvent, VoiceHandle}; use crate::voice::speech::SentenceChunker; @@ -89,8 +89,10 @@ enum UiEvent { caption_index: usize, context_messages: usize, }, - /// Speech recognition produced a transcript. + /// Speech recognition finished: this is the whole question. Transcribed(String), + /// A piece of the capture was transcribed while the user is still speaking. + TranscribedPart(String), /// A voice job (STT or TTS) failed. VoiceError(String), /// Text-to-speech playback finished. @@ -202,6 +204,13 @@ pub struct JarviseApp { recorder: Option, voice_status: Option, pending_transcript: Option, + /// Audio captured since the last piece was handed to Whisper. + listening: Vec, + /// What the pieces transcribed so far already said. + partial_transcript: String, + /// Total samples captured since the microphone was opened, so the "too + /// short" check still sees the whole recording once pieces have been sent. + captured_samples: usize, /// Reassembles the streamed answer into sentences to speak as it arrives, /// instead of waiting for the whole message. speech: SentenceChunker, @@ -259,6 +268,7 @@ impl JarviseApp { let voice = engine::spawn(voice_config, move |event| { voice_notifier.send(match event { VoiceEvent::Transcribed(text) => UiEvent::Transcribed(text), + VoiceEvent::TranscribedPart(text) => UiEvent::TranscribedPart(text), VoiceEvent::Spoken => UiEvent::Spoken, VoiceEvent::TranscriptionError(message) | VoiceEvent::SpeechError(message) => { UiEvent::VoiceError(message) @@ -308,6 +318,9 @@ impl JarviseApp { recorder: None, voice_status: None, pending_transcript: None, + listening: Vec::new(), + partial_transcript: String::new(), + captured_samples: 0, speech: SentenceChunker::new(), speech_pending: 0, draft_warmed: false, @@ -677,6 +690,9 @@ impl JarviseApp { match Recorder::start() { Ok(recorder) => { self.recorder = Some(recorder); + self.listening.clear(); + self.partial_transcript.clear(); + self.captured_samples = 0; self.voice_status = Some(format!( "🎙️ Enregistrement… appuie à nouveau ({MIC_HOTKEY_LABEL}) pour transcrire" )); @@ -707,22 +723,73 @@ impl JarviseApp { } } - /// Stops the capture and queues the transcription (second press of the toggle). + /// Stops the capture and queues the last piece of transcription (second + /// press of the toggle). Everything said so far was already transcribed + /// while the user was speaking, so only this tail is left to wait for. fn stop_recording(&mut self) { let Some(recorder) = self.recorder.take() else { return; }; - let (samples, sample_rate) = recorder.stop(); - let seconds = samples.len() as f32 / sample_rate.max(1) as f32; + let (tail, sample_rate) = recorder.stop(); + self.captured_samples += tail.len(); + let seconds = self.captured_samples as f32 / sample_rate.max(1) as f32; if seconds < 0.3 { self.voice_status = None; + self.listening.clear(); + self.partial_transcript.clear(); self.error = Some("Enregistrement trop court.".to_string()); return; } + self.listening.extend(tail); + let remaining = std::mem::take(&mut self.listening); + let remaining_seconds = remaining.len() as f32 / sample_rate.max(1) as f32; + + // A sliver left at the end carries no word: transcribing it would only + // give Whisper a chance to invent one, so the pieces already done are + // the whole question. + if remaining_seconds < MIN_TAIL_SECONDS { + self.finish_transcript(String::new()); + return; + } + self.voice_status = Some("Transcription en cours…".to_string()); - self.voice.transcribe(samples, sample_rate); + self.voice.transcribe(remaining, sample_rate); + } + + /// Hands Whisper the audio captured so far as soon as it forms a usable + /// piece, instead of waiting for the release: the model load and most of + /// the inference then happen while the user is still speaking. + fn feed_transcription(&mut self) { + let Some(recorder) = self.recorder.as_mut() else { + return; + }; + let sample_rate = recorder.sample_rate(); + let pending = recorder.drain_pending(); + self.captured_samples += pending.len(); + self.listening.extend(pending); + + let Some(cut) = audio::chunk_cut(&self.listening, sample_rate) else { + return; + }; + let piece: Vec = self.listening.drain(..cut).collect(); + self.voice.transcribe_part(piece, sample_rate); + } + + /// Ends the transcription: joins what the pieces already said with the last + /// one and hands the question to the conversation. + fn finish_transcript(&mut self, tail: String) { + let question = join_transcript(&self.partial_transcript, &tail); + self.partial_transcript.clear(); + self.listening.clear(); + self.voice_status = None; + + if question.is_empty() { + self.error = Some("Aucune parole détectée.".to_string()); + } else { + self.pending_transcript = Some(question); + } } /// Applies every event produced since the last frame. @@ -890,12 +957,12 @@ impl JarviseApp { self.streaming = false; self.cancel = None; } - UiEvent::Transcribed(text) => { - self.voice_status = None; - if text.trim().is_empty() { - self.error = Some("Aucune parole détectée.".to_string()); - } else { - self.pending_transcript = Some(text); + UiEvent::Transcribed(text) => self.finish_transcript(text), + // A piece of what is being said: shown right away, and kept for + // the moment the capture stops. + UiEvent::TranscribedPart(text) => { + if !text.trim().is_empty() { + self.partial_transcript = join_transcript(&self.partial_transcript, &text); } } UiEvent::VoiceError(message) => { @@ -1156,6 +1223,15 @@ impl JarviseApp { if let Some(status) = &self.voice_status { ui.colored_label(STATUS, status); } + // What is already transcribed appears while the user is + // still speaking, so the words are not a surprise at the end. + if self.recorder.is_some() && !self.partial_transcript.is_empty() { + ui.label( + egui::RichText::new(&self.partial_transcript) + .italics() + .color(ACCENT_SOFT), + ); + } if self.error.is_some() || self.voice_status.is_some() { ui.add_space(4.0); } @@ -1297,7 +1373,13 @@ impl JarviseApp { ui.add_space((available.y * 0.04).max(6.0)); - // Subtitles: what was just said, then Jarvis' live answer. + // Subtitles: what was just said, then Jarvis' live answer. While + // the microphone is open, the words being transcribed stand in + // for the previous question. + if self.recorder.is_some() && !self.partial_transcript.is_empty() { + subtitle(ui, "Vous", &self.partial_transcript, subtitle_width, false); + ui.add_space(6.0); + } if let Some(last_user) = self.messages.iter().rev().find(|m| m.is_user()) { subtitle(ui, "Vous", &last_user.content, subtitle_width, false); ui.add_space(6.0); @@ -1538,6 +1620,8 @@ impl eframe::App for JarviseApp { fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { self.drain_events(ui.ctx()); self.handle_mic_hotkey(ui); + // Transcribe while the user speaks, not once they stop. + self.feed_transcription(); // A finished transcription is placed in the input then sent as-is. if let Some(text) = self.pending_transcript.take() { @@ -1793,6 +1877,26 @@ pub fn chat_area(ui: &mut egui::Ui, messages: &[ChatMessage]) { ); } +/// Minimum audio left after the last piece was sent: below it there is no word +/// to recognise and Whisper can only guess. +const MIN_TAIL_SECONDS: f32 = 0.2; + +/// Joins the pieces transcribed during a capture with the last one, so the +/// question reads as a single sentence. +fn join_transcript(partial: &str, tail: &str) -> String { + let mut question = partial.trim().to_string(); + let tail = tail.trim(); + + if !tail.is_empty() { + if !question.is_empty() { + question.push(' '); + } + question.push_str(tail); + } + + question +} + /// Turns handed back to the model by `POST /api/chat`: everything that carries /// text, capped at the backend's contract and keeping the most recent exchange. /// @@ -2010,6 +2114,19 @@ mod tests { assert_eq!(history[0].content, "réponse 55"); } + /// A question transcribed in pieces must read as one sentence. + #[test] + fn the_pieces_and_the_tail_form_one_question() { + assert_eq!(join_transcript("", "Bonjour."), "Bonjour."); + assert_eq!(join_transcript("Bonjour.", ""), "Bonjour."); + assert_eq!( + join_transcript(" Bonjour Jarvis.", " Peux-tu ouvrir le fichier ?"), + "Bonjour Jarvis. Peux-tu ouvrir le fichier ?" + ); + assert_eq!(join_transcript("Bonjour.", " comment\n"), "Bonjour. comment"); + assert!(join_transcript(" ", "").is_empty()); + } + #[test] fn modes_have_distinct_tabs() { assert_ne!(Mode::Chat.label(), Mode::Companion.label()); diff --git a/frontend/src/voice/audio.rs b/frontend/src/voice/audio.rs index dbe2119..02432a5 100644 --- a/frontend/src/voice/audio.rs +++ b/frontend/src/voice/audio.rs @@ -34,12 +34,26 @@ impl std::fmt::Display for AudioError { impl std::error::Error for AudioError {} +/// Length of the quiet windows [`chunk_cut`] looks for, in milliseconds. +const SILENCE_WINDOW_MS: usize = 30; +/// RMS below which such a window counts as a pause between two words. +const SILENCE_RMS: f32 = 0.012; +/// Shortest piece worth transcribing: below that, Whisper has too little +/// context and starts inventing words. +pub const MIN_CHUNK_SECONDS: f32 = 1.2; +/// Longest piece sent without waiting for a pause, so the transcription never +/// trails far behind a speaker who does not breathe. +pub const MAX_CHUNK_SECONDS: f32 = 4.0; + /// An active microphone recording. Drop it (via [`Recorder::stop`]) to end the /// capture; the samples are mono `f32` at [`Recorder::sample_rate`]. pub struct Recorder { stream: cpal::Stream, sink: Arc>>, sample_rate: u32, + /// How many samples were already handed out, so a long recording can be + /// transcribed piece by piece while it is still being made. + read: usize, } impl Recorder { @@ -67,19 +81,102 @@ impl Recorder { stream, sink, sample_rate, + read: 0, }) } - /// Stops the capture and returns the recorded mono samples and their rate. - pub fn stop(self) -> (Vec, u32) { - drop(self.stream); - let samples = self - .sink - .lock() - .map(|guard| guard.clone()) - .unwrap_or_default(); - (samples, self.sample_rate) + /// Rate of the captured samples. + pub fn sample_rate(&self) -> u32 { + self.sample_rate } + + /// Takes everything recorded since the previous call, and forgets it here: + /// the caller owns those samples from now on. Lets the app transcribe the + /// beginning of a sentence while the end is still being spoken. + pub fn drain_pending(&mut self) -> Vec { + take_since(&self.sink, &mut self.read) + } + + /// Stops the capture and returns the mono samples recorded since the last + /// [`Self::drain_pending`], with their rate. + pub fn stop(mut self) -> (Vec, u32) { + // Closing the stream first guarantees no sample is appended after the + // final drain. + drop(self.stream); + let remaining = take_since(&self.sink, &mut self.read); + (remaining, self.sample_rate) + } +} + +/// Copies the samples written after `read`, then moves the cursor to the end. +fn take_since(sink: &Mutex>, read: &mut usize) -> Vec { + let Ok(guard) = sink.lock() else { + return Vec::new(); + }; + if *read >= guard.len() { + return Vec::new(); + } + let pending = guard[*read..].to_vec(); + *read = guard.len(); + pending +} + +/// Root-mean-square level of a window, the cheap way to tell a pause from +/// speech. +pub fn rms(samples: &[f32]) -> f32 { + if samples.is_empty() { + return 0.0; + } + let sum: f32 = samples.iter().map(|sample| sample * sample).sum(); + (sum / samples.len() as f32).sqrt() +} + +/// End of the last pause in `samples`, if the buffer holds one. +/// +/// Cutting in a pause is what keeps a word whole: a cut in the middle of \"bonjour\" +/// gives one chunk with \"bon\" and the next with \"jour\", and Whisper can only +/// guess at either. +fn last_silence(samples: &[f32], rate: usize) -> Option { + let window = (SILENCE_WINDOW_MS * rate / 1000).max(1); + if samples.len() < 2 * window { + return None; + } + let step = (window / 3).max(1); + let mut start = samples.len() - window; + + loop { + if rms(&samples[start..start + window]) < SILENCE_RMS { + // The pause stays in the chunk: it costs nothing and keeps the + // trailing word complete. + return Some(start + window); + } + if start < step { + return None; + } + start -= step; + } +} + +/// Where to cut the live capture so it can be transcribed, or `None` to keep +/// collecting. +/// +/// A pause is preferred, but a long uninterrupted stretch is cut anyway: the +/// words may suffer at the seam, waiting would cost more. +pub fn chunk_cut(samples: &[f32], rate: u32) -> Option { + let rate = rate.max(1) as usize; + let minimum = (MIN_CHUNK_SECONDS * rate as f32) as usize; + if samples.len() < minimum { + return None; + } + + if let Some(cut) = last_silence(samples, rate) { + if cut >= minimum { + return Some(cut); + } + } + + let maximum = (MAX_CHUNK_SECONDS * rate as f32) as usize; + (samples.len() >= maximum).then_some(samples.len()) } /// Plays `samples` (mono `f32`) at `sample_rate`, blocking until playback ends. @@ -282,7 +379,74 @@ fn fill_from_source( #[cfg(test)] mod tests { - use super::resample_linear; + use super::{chunk_cut, resample_linear, MAX_CHUNK_SECONDS, MIN_CHUNK_SECONDS}; + + const RATE: u32 = 16_000; + + /// A second of loud voice, then half a second of silence. + fn speech_then_pause() -> Vec { + let mut samples = vec![0.3_f32; RATE as usize]; + samples.extend(std::iter::repeat_n(0.0, RATE as usize / 2)); + samples + } + + #[test] + fn a_short_buffer_is_not_cut() { + let samples = vec![0.3_f32; (RATE as f32 * 0.5) as usize]; + assert_eq!(chunk_cut(&samples, RATE), None); + } + + #[test] + fn a_pause_is_the_preferred_cut() { + let samples = speech_then_pause(); + let cut = chunk_cut(&samples, RATE).expect("a pause after 1.2 s is cuttable"); + + assert_eq!(cut, samples.len(), "the whole pause is kept in the chunk"); + assert!(cut as f32 / RATE as f32 <= MAX_CHUNK_SECONDS); + } + + #[test] + fn a_word_is_never_split_when_a_pause_exists() { + // Two seconds of speech, a pause, then the start of the next sentence. + let mut samples = vec![0.4_f32; 2 * RATE as usize]; + samples.extend(std::iter::repeat_n(0.0, RATE as usize / 3)); + let after_pause = samples.len(); + samples.extend(vec![0.4_f32; RATE as usize / 4]); + + let cut = chunk_cut(&samples, RATE).expect("the pause must be found"); + // The cut lands inside the pause, never in the words around it. + assert!( + (2 * RATE as usize..=after_pause).contains(&cut), + "cut at {cut}, the pause ended at {after_pause}" + ); + } + + #[test] + fn continuous_speech_is_cut_at_the_hard_limit() { + let samples = vec![0.3_f32; (RATE as f32 * (MAX_CHUNK_SECONDS + 0.5)) as usize]; + let cut = chunk_cut(&samples, RATE).expect("a long stretch must be cut"); + + assert_eq!(cut, samples.len()); + assert!((cut as f32 / RATE as f32) >= MAX_CHUNK_SECONDS); + } + + #[test] + fn a_pause_that_is_too_early_is_ignored() { + // Silence almost immediately: cutting there would send a sliver with + // nothing in it, so the buffer keeps growing. + let mut samples = vec![0.0_f32; RATE as usize / 10]; + samples.extend(std::iter::repeat_n(0.4, (RATE as f32 * 0.6) as usize)); + + assert!(MIN_CHUNK_SECONDS > 0.6); + assert_eq!(chunk_cut(&samples, RATE), None); + } + + #[test] + fn silence_is_cut_at_the_shorter_threshold() { + // A gap right after the minimum: no need to wait for the hard limit. + let samples = vec![0.0_f32; (RATE as f32 * MIN_CHUNK_SECONDS) as usize]; + assert_eq!(chunk_cut(&samples, RATE), Some(samples.len())); + } #[test] fn resample_is_identity_at_the_same_rate() { diff --git a/frontend/src/voice/engine.rs b/frontend/src/voice/engine.rs index 2ce15ac..0f05bef 100644 --- a/frontend/src/voice/engine.rs +++ b/frontend/src/voice/engine.rs @@ -62,6 +62,10 @@ fn is_file(path: &Path) -> bool { /// Result of a voice job, delivered back to the GUI thread. #[derive(Debug, Clone)] pub enum VoiceEvent { + /// A piece of audio transcribed while the capture is still running. The UI + /// shows it as it arrives; it is not the question yet. + TranscribedPart(String), + /// The capture ended: this is the complete transcript of what was said. Transcribed(String), /// Playback of a synthesized answer finished. Spoken, @@ -70,7 +74,13 @@ pub enum VoiceEvent { } enum VoiceCommand { - Transcribe { samples: Vec, sample_rate: u32 }, + Transcribe { + samples: Vec, + sample_rate: u32, + /// Whether this closes the capture: the last piece decides which event + /// the app receives. + final_chunk: bool, + }, Speak { text: String }, } @@ -91,11 +101,23 @@ impl VoiceHandle { self.tts_ready } - /// Queues a transcription job (safe to call from the GUI thread). + /// Queues a transcription of the whole capture; the result is the question. pub fn transcribe(&self, samples: Vec, sample_rate: u32) { + self.send_transcription(samples, sample_rate, true); + } + + /// Queues a transcription of a piece of the capture. Pieces are inferred in + /// the order they are queued, so the app can start on the beginning of a + /// sentence while the end is still being spoken. + pub fn transcribe_part(&self, samples: Vec, sample_rate: u32) { + self.send_transcription(samples, sample_rate, false); + } + + fn send_transcription(&self, samples: Vec, sample_rate: u32, final_chunk: bool) { let _ = self.tx.send(VoiceCommand::Transcribe { samples, sample_rate, + final_chunk, }); } @@ -126,6 +148,7 @@ where VoiceCommand::Transcribe { samples, sample_rate, + final_chunk, } => { let Some(model) = worker_config.whisper_model.as_deref() else { on_event(VoiceEvent::TranscriptionError( @@ -147,7 +170,8 @@ where .expect("stt initialised above") .transcribe(&samples, sample_rate, &worker_config.language) { - Ok(text) => on_event(VoiceEvent::Transcribed(text)), + Ok(text) if final_chunk => on_event(VoiceEvent::Transcribed(text)), + Ok(text) => on_event(VoiceEvent::TranscribedPart(text)), Err(error) => { on_event(VoiceEvent::TranscriptionError(error.to_string())) }