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.
93 lines
2.9 KiB
Rust
93 lines
2.9 KiB
Rust
//! 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())
|
|
}
|
|
}
|