//! The voice engine: a dedicated thread owning the (heavy) whisper and Piper //! models, so loading a model or running inference never freezes the GUI. //! //! The GUI sends commands through [`VoiceHandle`] and receives results as //! [`VoiceEvent`]s. use std::path::{Path, PathBuf}; use std::sync::mpsc::{channel, Sender}; use super::audio; use super::stt::WhisperStt; use super::tts::PiperTts; /// Paths to the local voice models, read from the environment: /// `WHISPER_MODEL`, `PIPER_MODEL`, `PIPER_CONFIG`, `JARVIS_STT_LANGUAGE`. #[derive(Clone, Default)] pub struct VoiceConfig { pub whisper_model: Option, pub piper_model: Option, pub piper_config: Option, pub language: String, } impl VoiceConfig { pub fn from_env() -> Self { let path = |key: &str| { std::env::var(key) .ok() .filter(|value| !value.trim().is_empty()) .map(PathBuf::from) }; let language = std::env::var("JARVIS_STT_LANGUAGE") .ok() .filter(|value| !value.trim().is_empty()) .unwrap_or_else(|| "fr".to_string()); Self { whisper_model: path("WHISPER_MODEL"), piper_model: path("PIPER_MODEL"), piper_config: path("PIPER_CONFIG"), language, } } /// Whether a usable speech-to-text model is configured. pub fn stt_ready(&self) -> bool { self.whisper_model.as_deref().is_some_and(is_file) } /// Whether a usable text-to-speech voice is configured. pub fn tts_ready(&self) -> bool { self.piper_model.as_deref().is_some_and(is_file) && self.piper_config.as_deref().is_some_and(is_file) } } fn is_file(path: &Path) -> bool { path.is_file() } /// 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, TranscriptionError(String), SpeechError(String), } enum VoiceCommand { 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 }, } /// GUI-side handle to the voice engine. Cheap to clone (it holds a channel). #[derive(Clone)] pub struct VoiceHandle { tx: Sender, stt_ready: bool, tts_ready: bool, } impl VoiceHandle { pub fn stt_ready(&self) -> bool { self.stt_ready } pub fn tts_ready(&self) -> bool { self.tts_ready } /// 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, }); } /// Queues a synthesis + playback job. pub fn speak(&self, text: String) { let _ = self.tx.send(VoiceCommand::Speak { text }); } } /// Starts the voice thread. `on_event` is invoked from that thread for every /// result; the app wraps it to push into its UI channel and repaint. pub fn spawn(config: VoiceConfig, on_event: F) -> VoiceHandle where F: Fn(VoiceEvent) + Send + 'static, { let (tx, rx) = channel::(); let worker_config = config.clone(); std::thread::Builder::new() .name("jarvise-voice".to_string()) .spawn(move || { // Models are loaded lazily on first use and kept for later jobs. let mut stt: Option = None; let mut tts: Option = None; while let Ok(command) = rx.recv() { match command { VoiceCommand::Transcribe { samples, sample_rate, final_chunk, } => { let Some(model) = worker_config.whisper_model.as_deref() else { on_event(VoiceEvent::TranscriptionError( "Whisper non configuré (variable WHISPER_MODEL).".to_string(), )); continue; }; if stt.is_none() { match WhisperStt::load(model) { Ok(engine) => stt = Some(engine), Err(error) => { on_event(VoiceEvent::TranscriptionError(error.to_string())); continue; } } } match stt .as_ref() .expect("stt initialised above") .transcribe(&samples, sample_rate, &worker_config.language) { 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())) } } } VoiceCommand::Speak { text } => { let (Some(model), Some(config_path)) = ( worker_config.piper_model.as_deref(), worker_config.piper_config.as_deref(), ) else { on_event(VoiceEvent::SpeechError( "Piper non configuré (variables PIPER_MODEL / PIPER_CONFIG)." .to_string(), )); continue; }; if tts.is_none() { match PiperTts::load(model, config_path) { Ok(engine) => tts = Some(engine), Err(error) => { on_event(VoiceEvent::SpeechError(error.to_string())); continue; } } } match tts.as_mut().expect("tts initialised above").synthesize(&text) { Ok((samples, sample_rate)) => { match audio::play_blocking(&samples, sample_rate) { Ok(()) => on_event(VoiceEvent::Spoken), Err(error) => { on_event(VoiceEvent::SpeechError(error.to_string())) } } } Err(error) => on_event(VoiceEvent::SpeechError(error.to_string())), } } } } }) .expect("failed to spawn the voice thread"); VoiceHandle { tx, stt_ready: config.stt_ready(), tts_ready: config.tts_ready(), } } #[cfg(test)] mod tests { use std::path::PathBuf; use super::VoiceConfig; #[test] fn default_config_is_not_ready() { let config = VoiceConfig::default(); assert!(!config.stt_ready()); assert!(!config.tts_ready()); } #[test] fn readiness_requires_existing_files() { let config = VoiceConfig { whisper_model: Some(PathBuf::from("/nope/absent.bin")), piper_model: Some(PathBuf::from("/nope/absent.onnx")), piper_config: Some(PathBuf::from("/nope/absent.json")), language: "fr".to_string(), }; assert!(!config.stt_ready()); assert!(!config.tts_ready()); } }