A conversation that only lives in memory is lost when the window closes, and long answers used to be cut off at the window edge because a scroll area inherits the layout of the parent it is added to. Projects give each exchange a durable context, the reload and verification actions make that context observable instead of a black box, and laying the text out before drawing the bubble keeps every answer inside the column.
225 lines
7.6 KiB
Rust
225 lines
7.6 KiB
Rust
//! 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<PathBuf>,
|
|
pub piper_model: Option<PathBuf>,
|
|
pub piper_config: Option<PathBuf>,
|
|
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 {
|
|
Transcribed(String),
|
|
/// Playback of a synthesized answer finished.
|
|
Spoken,
|
|
TranscriptionError(String),
|
|
SpeechError(String),
|
|
}
|
|
|
|
enum VoiceCommand {
|
|
Transcribe { samples: Vec<f32>, sample_rate: u32 },
|
|
Speak { text: String },
|
|
}
|
|
|
|
/// GUI-side handle to the voice engine. Cheap to clone (it holds a channel).
|
|
#[derive(Clone)]
|
|
pub struct VoiceHandle {
|
|
tx: Sender<VoiceCommand>,
|
|
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 job (safe to call from the GUI thread).
|
|
pub fn transcribe(&self, samples: Vec<f32>, sample_rate: u32) {
|
|
let _ = self.tx.send(VoiceCommand::Transcribe {
|
|
samples,
|
|
sample_rate,
|
|
});
|
|
}
|
|
|
|
/// 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<F>(config: VoiceConfig, on_event: F) -> VoiceHandle
|
|
where
|
|
F: Fn(VoiceEvent) + Send + 'static,
|
|
{
|
|
let (tx, rx) = channel::<VoiceCommand>();
|
|
|
|
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<WhisperStt> = None;
|
|
let mut tts: Option<PiperTts> = None;
|
|
|
|
while let Ok(command) = rx.recv() {
|
|
match command {
|
|
VoiceCommand::Transcribe {
|
|
samples,
|
|
sample_rate,
|
|
} => {
|
|
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) => on_event(VoiceEvent::Transcribed(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());
|
|
}
|
|
}
|