feat(frontend): add native Rust client with SSE chat and local voice
Keep speech-to-text and text-to-speech on the machine so only text travels to the backend while the backend still speaks JSON to Ollama.
This commit is contained in:
17 files changed
+8014
No files matched your search
@@ -0,0 +1,311 @@
|
||||
//! Audio input (microphone) and output (speaker) through `cpal`.
|
||||
//!
|
||||
//! Callbacks run on the audio thread and only push/pull samples to/from a shared
|
||||
//! buffer, so nothing here blocks for long.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
use cpal::{FromSample, Sample, SampleFormat, SizedSample, StreamConfig};
|
||||
|
||||
/// Anything that can go wrong when opening or using an audio device.
|
||||
#[derive(Debug)]
|
||||
pub enum AudioError {
|
||||
NoInputDevice,
|
||||
NoOutputDevice,
|
||||
Config(String),
|
||||
Build(String),
|
||||
Play(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for AudioError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
AudioError::NoInputDevice => write!(f, "aucun micro détecté"),
|
||||
AudioError::NoOutputDevice => write!(f, "aucun haut-parleur détecté"),
|
||||
AudioError::Config(message) => write!(f, "configuration audio : {message}"),
|
||||
AudioError::Build(message) => write!(f, "ouverture du flux audio : {message}"),
|
||||
AudioError::Play(message) => write!(f, "lecture audio : {message}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AudioError {}
|
||||
|
||||
/// 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<Mutex<Vec<f32>>>,
|
||||
sample_rate: u32,
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
/// Opens the default microphone and starts capturing.
|
||||
pub fn start() -> Result<Self, AudioError> {
|
||||
let host = cpal::default_host();
|
||||
let device = host
|
||||
.default_input_device()
|
||||
.ok_or(AudioError::NoInputDevice)?;
|
||||
let supported = device
|
||||
.default_input_config()
|
||||
.map_err(|error| AudioError::Config(error.to_string()))?;
|
||||
|
||||
let sample_rate = supported.sample_rate();
|
||||
let format = supported.sample_format();
|
||||
let config = supported.config();
|
||||
|
||||
let sink = Arc::new(Mutex::new(Vec::new()));
|
||||
let stream = build_input(&device, config, format, sink.clone())?;
|
||||
stream
|
||||
.play()
|
||||
.map_err(|error| AudioError::Play(error.to_string()))?;
|
||||
|
||||
Ok(Self {
|
||||
stream,
|
||||
sink,
|
||||
sample_rate,
|
||||
})
|
||||
}
|
||||
|
||||
/// Stops the capture and returns the recorded mono samples and their rate.
|
||||
pub fn stop(self) -> (Vec<f32>, u32) {
|
||||
drop(self.stream);
|
||||
let samples = self
|
||||
.sink
|
||||
.lock()
|
||||
.map(|guard| guard.clone())
|
||||
.unwrap_or_default();
|
||||
(samples, self.sample_rate)
|
||||
}
|
||||
}
|
||||
|
||||
/// Plays `samples` (mono `f32`) at `sample_rate`, blocking until playback ends.
|
||||
///
|
||||
/// Callers run this on a background thread (the voice engine), never on the GUI
|
||||
/// thread.
|
||||
pub fn play_blocking(samples: &[f32], sample_rate: u32) -> Result<(), AudioError> {
|
||||
if samples.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let host = cpal::default_host();
|
||||
let device = host
|
||||
.default_output_device()
|
||||
.ok_or(AudioError::NoOutputDevice)?;
|
||||
let supported = device
|
||||
.default_output_config()
|
||||
.map_err(|error| AudioError::Config(error.to_string()))?;
|
||||
|
||||
let output_rate = supported.sample_rate();
|
||||
let format = supported.sample_format();
|
||||
let config = supported.config();
|
||||
|
||||
// Resample once so the callback is a simple copy.
|
||||
let source = Arc::new(resample_linear(samples, sample_rate, output_rate));
|
||||
let position = Arc::new(AtomicUsize::new(0));
|
||||
let finished = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let stream = build_output(
|
||||
&device,
|
||||
config,
|
||||
format,
|
||||
source,
|
||||
position.clone(),
|
||||
finished.clone(),
|
||||
)?;
|
||||
stream
|
||||
.play()
|
||||
.map_err(|error| AudioError::Play(error.to_string()))?;
|
||||
|
||||
while !finished.load(Ordering::SeqCst) {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
// Give the device a moment to flush the last buffer.
|
||||
std::thread::sleep(Duration::from_millis(80));
|
||||
drop(stream);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Linear resampling between two sample rates (good enough for speech).
|
||||
pub fn resample_linear(input: &[f32], source_rate: u32, target_rate: u32) -> Vec<f32> {
|
||||
if input.is_empty() || source_rate == target_rate || source_rate == 0 {
|
||||
return input.to_vec();
|
||||
}
|
||||
|
||||
let ratio = source_rate as f64 / target_rate as f64;
|
||||
let out_len = ((input.len() as f64) / ratio).max(1.0) as usize;
|
||||
let last = input.len() - 1;
|
||||
|
||||
(0..out_len)
|
||||
.map(|i| {
|
||||
let src = i as f64 * ratio;
|
||||
let index = src.floor() as usize;
|
||||
let frac = (src - index as f64) as f32;
|
||||
let a = input[index.min(last)];
|
||||
let b = input[(index + 1).min(last)];
|
||||
a + (b - a) * frac
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn build_input(
|
||||
device: &cpal::Device,
|
||||
config: StreamConfig,
|
||||
format: SampleFormat,
|
||||
sink: Arc<Mutex<Vec<f32>>>,
|
||||
) -> Result<cpal::Stream, AudioError> {
|
||||
match format {
|
||||
SampleFormat::F32 => input_stream::<f32>(device, config, sink),
|
||||
SampleFormat::I16 => input_stream::<i16>(device, config, sink),
|
||||
SampleFormat::U16 => input_stream::<u16>(device, config, sink),
|
||||
SampleFormat::I32 => input_stream::<i32>(device, config, sink),
|
||||
other => Err(AudioError::Config(format!(
|
||||
"format d'entrée non pris en charge : {other:?}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn input_stream<T>(
|
||||
device: &cpal::Device,
|
||||
config: StreamConfig,
|
||||
sink: Arc<Mutex<Vec<f32>>>,
|
||||
) -> Result<cpal::Stream, AudioError>
|
||||
where
|
||||
T: SizedSample + 'static,
|
||||
f32: FromSample<T>,
|
||||
{
|
||||
let channels = config.channels as usize;
|
||||
device
|
||||
.build_input_stream::<T, _, _>(
|
||||
config,
|
||||
move |data, _| push_mono::<T>(data, channels, &sink),
|
||||
|_error| {},
|
||||
None,
|
||||
)
|
||||
.map_err(|error| AudioError::Build(error.to_string()))
|
||||
}
|
||||
|
||||
fn push_mono<T>(data: &[T], channels: usize, sink: &Arc<Mutex<Vec<f32>>>)
|
||||
where
|
||||
T: Sample,
|
||||
f32: FromSample<T>,
|
||||
{
|
||||
if channels == 0 {
|
||||
return;
|
||||
}
|
||||
let mut out = match sink.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
for frame in data.chunks(channels) {
|
||||
let sum: f32 = frame.iter().map(|sample| sample.to_sample::<f32>()).sum();
|
||||
out.push(sum / channels as f32);
|
||||
}
|
||||
}
|
||||
|
||||
fn build_output(
|
||||
device: &cpal::Device,
|
||||
config: StreamConfig,
|
||||
format: SampleFormat,
|
||||
source: Arc<Vec<f32>>,
|
||||
position: Arc<AtomicUsize>,
|
||||
finished: Arc<AtomicBool>,
|
||||
) -> Result<cpal::Stream, AudioError> {
|
||||
match format {
|
||||
SampleFormat::F32 => output_stream::<f32>(device, config, source, position, finished),
|
||||
SampleFormat::I16 => output_stream::<i16>(device, config, source, position, finished),
|
||||
SampleFormat::U16 => output_stream::<u16>(device, config, source, position, finished),
|
||||
SampleFormat::I32 => output_stream::<i32>(device, config, source, position, finished),
|
||||
other => Err(AudioError::Config(format!(
|
||||
"format de sortie non pris en charge : {other:?}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn output_stream<T>(
|
||||
device: &cpal::Device,
|
||||
config: StreamConfig,
|
||||
source: Arc<Vec<f32>>,
|
||||
position: Arc<AtomicUsize>,
|
||||
finished: Arc<AtomicBool>,
|
||||
) -> Result<cpal::Stream, AudioError>
|
||||
where
|
||||
T: SizedSample + 'static,
|
||||
T: FromSample<f32>,
|
||||
{
|
||||
let channels = config.channels as usize;
|
||||
device
|
||||
.build_output_stream::<T, _, _>(
|
||||
config,
|
||||
move |data, _| fill_from_source::<T>(data, channels, &source, &position, &finished),
|
||||
|_error| {},
|
||||
None,
|
||||
)
|
||||
.map_err(|error| AudioError::Build(error.to_string()))
|
||||
}
|
||||
|
||||
fn fill_from_source<T>(
|
||||
output: &mut [T],
|
||||
channels: usize,
|
||||
source: &Arc<Vec<f32>>,
|
||||
position: &Arc<AtomicUsize>,
|
||||
finished: &Arc<AtomicBool>,
|
||||
) where
|
||||
T: Sample,
|
||||
T: FromSample<f32>,
|
||||
{
|
||||
if channels == 0 {
|
||||
return;
|
||||
}
|
||||
let len = source.len();
|
||||
let mut index = position.load(Ordering::Relaxed);
|
||||
|
||||
for frame in output.chunks_mut(channels) {
|
||||
let value = if index < len { source[index] } else { 0.0 };
|
||||
let sample = T::from_sample(value);
|
||||
for out in frame.iter_mut() {
|
||||
*out = sample;
|
||||
}
|
||||
if index < len {
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
position.store(index, Ordering::Relaxed);
|
||||
if index >= len {
|
||||
finished.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::resample_linear;
|
||||
|
||||
#[test]
|
||||
fn resample_is_identity_at_the_same_rate() {
|
||||
let input = vec![0.1, -0.2, 0.3];
|
||||
assert_eq!(resample_linear(&input, 16_000, 16_000), input);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resample_downsamples_to_the_expected_length() {
|
||||
let input: Vec<f32> = (0..48_000).map(|i| (i as f32 / 48_000.0).sin()).collect();
|
||||
let output = resample_linear(&input, 48_000, 16_000);
|
||||
assert_eq!(output.len(), 16_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resample_preserves_constant_signal() {
|
||||
let input = vec![0.5_f32; 44_100];
|
||||
let output = resample_linear(&input, 44_100, 16_000);
|
||||
assert!(output.iter().all(|sample| (sample - 0.5).abs() < 1e-3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resample_handles_empty_input() {
|
||||
assert!(resample_linear(&[], 44_100, 16_000).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
//! 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),
|
||||
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)) => {
|
||||
if let Err(error) = audio::play_blocking(&samples, sample_rate) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//! Local voice capabilities of the "thick client".
|
||||
//!
|
||||
//! The backend only ever exchanges **text** (client↔backend) and **JSON**
|
||||
//! (backend↔Ollama): speech-to-text and text-to-speech are performed entirely on
|
||||
//! this machine, by [`audio`] (microphone/speaker), [`stt`] (whisper.cpp) and
|
||||
//! [`tts`] (Piper). [`engine`] wires them together on a dedicated thread so the
|
||||
//! GUI never blocks.
|
||||
|
||||
pub mod audio;
|
||||
pub mod engine;
|
||||
pub mod stt;
|
||||
pub mod tts;
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Speech-to-text using the embedded whisper.cpp (via `whisper-rs`).
|
||||
//!
|
||||
//! Whisper expects 16 kHz mono `f32` audio, so the incoming samples are
|
||||
//! resampled here when needed.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use whisper_rs::{FullParams, SamplingStrategy, WhisperContext, WhisperContextParameters};
|
||||
|
||||
use super::audio::resample_linear;
|
||||
|
||||
/// Sample rate whisper.cpp works with.
|
||||
pub const WHISPER_SAMPLE_RATE: u32 = 16_000;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SttError(pub String);
|
||||
|
||||
impl std::fmt::Display for SttError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for SttError {}
|
||||
|
||||
/// Loaded whisper model, reused across transcriptions.
|
||||
pub struct WhisperStt {
|
||||
context: WhisperContext,
|
||||
threads: i32,
|
||||
}
|
||||
|
||||
impl WhisperStt {
|
||||
/// Loads a GGML model (`.bin`) from disk. This can take a moment, hence it
|
||||
/// runs on the voice thread and is cached afterwards.
|
||||
pub fn load(model_path: &Path) -> Result<Self, SttError> {
|
||||
let path = model_path
|
||||
.to_str()
|
||||
.ok_or_else(|| SttError("chemin de modèle Whisper invalide".to_string()))?;
|
||||
|
||||
let context = WhisperContext::new_with_params(path, WhisperContextParameters::default())
|
||||
.map_err(|error| SttError(format!("chargement du modèle Whisper : {error}")))?;
|
||||
|
||||
let threads = std::thread::available_parallelism()
|
||||
.map(|count| count.get() as i32)
|
||||
.unwrap_or(4)
|
||||
.max(1);
|
||||
|
||||
Ok(Self { context, threads })
|
||||
}
|
||||
|
||||
/// Transcribes mono `f32` samples. `language` follows whisper's codes
|
||||
/// (`"fr"`, `"en"`, …).
|
||||
pub fn transcribe(
|
||||
&self,
|
||||
samples: &[f32],
|
||||
sample_rate: u32,
|
||||
language: &str,
|
||||
) -> Result<String, SttError> {
|
||||
let pcm = if sample_rate == WHISPER_SAMPLE_RATE {
|
||||
samples.to_vec()
|
||||
} else {
|
||||
resample_linear(samples, sample_rate, WHISPER_SAMPLE_RATE)
|
||||
};
|
||||
|
||||
let mut state = self
|
||||
.context
|
||||
.create_state()
|
||||
.map_err(|error| SttError(format!("état Whisper : {error}")))?;
|
||||
|
||||
let mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 });
|
||||
params.set_n_threads(self.threads);
|
||||
params.set_translate(false);
|
||||
params.set_language(Some(language));
|
||||
params.set_print_special(false);
|
||||
params.set_print_progress(false);
|
||||
params.set_print_realtime(false);
|
||||
params.set_print_timestamps(false);
|
||||
|
||||
state
|
||||
.full(params, &pcm)
|
||||
.map_err(|error| SttError(format!("transcription : {error}")))?;
|
||||
|
||||
let mut text = String::new();
|
||||
for index in 0..state.full_n_segments() {
|
||||
if let Some(segment) = state.get_segment(index) {
|
||||
text.push_str(segment.to_str().unwrap_or(""));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(text.trim().to_string())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! Text-to-speech using the embedded Piper engine (via `piper-rs`).
|
||||
//!
|
||||
//! Piper produces raw `f32` PCM plus its sample rate; playback is handled by the
|
||||
//! [`super::audio`] module.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use piper_rs::Piper;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TtsError(pub String);
|
||||
|
||||
impl std::fmt::Display for TtsError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TtsError {}
|
||||
|
||||
/// Loaded Piper voice, reused across syntheses.
|
||||
pub struct PiperTts {
|
||||
piper: Piper,
|
||||
}
|
||||
|
||||
impl PiperTts {
|
||||
/// Loads a Piper voice from its `.onnx` model and `.json` config.
|
||||
pub fn load(model_path: &Path, config_path: &Path) -> Result<Self, TtsError> {
|
||||
let piper = Piper::new(model_path, config_path)
|
||||
.map_err(|error| TtsError(format!("chargement de la voix Piper : {error}")))?;
|
||||
Ok(Self { piper })
|
||||
}
|
||||
|
||||
/// Synthesizes `text` into mono `f32` samples and their sample rate.
|
||||
pub fn synthesize(&mut self, text: &str) -> Result<(Vec<f32>, u32), TtsError> {
|
||||
self.piper
|
||||
.create(text, false, None, None, None, None)
|
||||
.map_err(|error| TtsError(format!("synthèse Piper : {error}")))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user