use crate::util::UnwrapPoison;
use crate::util::model_state::ModelState;
use anyhow::{Context as _, Result};
use mahbot_inference::ced::{CED_MODEL, Tagger};
use mahbot_inference::listen::{Listener, PAIR};
use mahbot_inference::loader::{Pair, Role};
use mahbot_inference::transcribe::{Region, SPEECH_LABELS, Transcriber};
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex, Weak};
use std::time::{Duration, Instant};
use crate::speech::decode;
use crate::speech::load::Lazy;
use crate::speech::models::{self, Purpose};
pub(crate) const INFERENCE_TIMEOUT: Duration = Duration::from_mins(10);
pub(crate) const UNTRANSCRIBED: &str = "[untranscribed speech]";
#[derive(Debug)]
pub(crate) struct InferenceTimedOut;
impl std::fmt::Display for InferenceTimedOut {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("speech recognition timed out")
}
}
impl std::error::Error for InferenceTimedOut {}
#[derive(Debug)]
pub(crate) struct Interrupted;
impl std::fmt::Display for Interrupted {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("the product is stopping")
}
}
impl std::error::Error for Interrupted {}
#[derive(Debug)]
pub(crate) struct Unreadable;
impl std::fmt::Display for Unreadable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("the sound could not be decoded")
}
}
impl std::error::Error for Unreadable {}
const CEILING_MIB: u64 = mahbot_inference::guard::DEFAULT_MAX_RSS_MIB;
pub(crate) static ENCODER: Lazy<Listener> = Lazy::new(Purpose::Listening, open_listener);
pub(crate) static TRANSCRIBER: Lazy<Transcriber> =
Lazy::new(Purpose::Recognition, open_transcriber);
fn shared_pair() -> Result<Arc<Pair>> {
static SLOT: Mutex<Option<Weak<Pair>>> = Mutex::new(None);
let mut slot = SLOT.lock().unwrap_poison();
if let Some(pair) = slot.as_ref().and_then(Weak::upgrade) {
return Ok(pair);
}
let pair = Arc::new(Pair::of_role(Role::Recognition)?);
*slot = Some(Arc::downgrade(&pair));
Ok(pair)
}
fn open_listener() -> Result<Listener> {
let mut listener = Listener::new(shared_pair()?);
for warm in [
listener.embed_pair(&[], &[]).map(drop),
listener.embed(&[]).map(drop),
] {
if let Err(e) = warm {
tracing::warn!("the listening front end did not warm up: {e:#}");
}
}
Ok(listener)
}
fn open_transcriber() -> Result<Transcriber> {
let pair = shared_pair()?;
let tagger = Tagger::open(&models::root()?.join(CED_MODEL))?;
Transcriber::open(pair, tagger, CEILING_MIB)
}
pub(crate) fn listening_state() -> ModelState {
ENCODER.state()
}
pub(crate) fn is_listening_loaded() -> bool {
ENCODER.is_loaded()
}
pub(crate) fn is_listening_loading() -> bool {
ENCODER.is_loading()
}
pub(crate) fn is_listening_failed() -> bool {
ENCODER.is_failed()
}
pub(crate) fn retry_listening() {
ENCODER.retry();
}
pub(crate) fn spawn_listening_init() {
ENCODER.spawn_background_init();
}
pub(crate) fn transcriber_state() -> ModelState {
TRANSCRIBER.state()
}
pub(crate) fn is_transcriber_failed() -> bool {
TRANSCRIBER.is_failed()
}
pub(crate) fn retry_transcription() {
TRANSCRIBER.retry();
}
pub(crate) fn spawn_transcriber_init() {
TRANSCRIBER.spawn_background_init();
}
pub(crate) async fn ensure_ready_once(announce: impl FnOnce(&Path)) -> Result<()> {
TRANSCRIBER.ensure_ready_once(announce).await
}
pub(crate) async fn transcribe_file_async(path: &Path, timeout: Duration) -> Result<String> {
let owned: PathBuf = path.to_owned();
let (samples, rate) =
tokio::task::spawn_blocking(move || decode::decode_audio_to_mono_f32(&owned))
.await
.context("Audio decode task panicked")??;
transcribe_samples(samples, rate, timeout).await
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub(crate) struct Segment {
pub(crate) start: f64,
pub(crate) end: f64,
pub(crate) text: Option<String>,
pub(crate) label: Option<String>,
}
pub(crate) struct Read {
pub(crate) regions: Vec<Segment>,
pub(crate) pieces: usize,
pub(crate) failure: Option<anyhow::Error>,
}
pub(crate) async fn transcribe_pieces(
pieces: &[(PathBuf, f64)],
deadline: Instant,
) -> Result<Read> {
if pieces.is_empty() {
return Ok(Read {
regions: Vec::new(),
pieces: 0,
failure: None,
});
}
let pieces = pieces
.iter()
.map(|(path, offset)| Piece::File {
path: path.clone(),
offset: *offset,
})
.collect();
read_pieces(pieces, deadline, INFERENCE_TIMEOUT).await
}
pub(crate) async fn transcribe_samples(
samples: Vec<f32>,
rate: u32,
timeout: Duration,
) -> Result<String> {
anyhow::ensure!(!samples.is_empty(), "the recording holds no samples");
let pieces = vec![Piece::Memory { samples, rate }];
let read = read_pieces(pieces, Instant::now() + timeout, Duration::ZERO).await?;
Ok(compose(&read.regions))
}
enum Piece {
File { path: PathBuf, offset: f64 },
Memory { samples: Vec<f32>, rate: u32 },
}
static PASS: LazyLock<Arc<tokio::sync::Mutex<()>>> =
LazyLock::new(|| Arc::new(tokio::sync::Mutex::new(())));
async fn read_pieces(pieces: Vec<Piece>, deadline: Instant, grace: Duration) -> Result<Read> {
let dir = models::root()?;
let Some(transcriber) = TRANSCRIBER.acquire(&dir).await else {
anyhow::bail!(
"{}",
models::unloaded_message(&dir, Purpose::Recognition, is_transcriber_failed())
);
};
let shutdown = crate::shutdown::shutdown_token();
let pass_guard = tokio::select! {
pass = PASS.clone().lock_owned() => pass,
() = shutdown.cancelled() => {
return Err(anyhow::Error::new(Interrupted));
}
() = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)) => {
return Err(anyhow::Error::new(InferenceTimedOut));
}
};
if Instant::now() >= deadline {
return Err(anyhow::Error::new(InferenceTimedOut));
}
let pass = tokio::task::spawn_blocking(move || {
let _pass = pass_guard;
let mut engine = transcriber.lock().unwrap_poison();
read_all(&mut engine, pieces, deadline)
});
let abandon = tokio::time::Instant::from_std(deadline + grace);
let outcome = tokio::select! {
joined = tokio::time::timeout_at(abandon, pass) => joined,
() = shutdown.cancelled() => {
return Err(anyhow::Error::new(Interrupted));
}
};
match outcome {
Ok(Ok(read)) if read.pieces == 0 && read.failure.is_some() => {
let failure = read
.failure
.unwrap_or_else(|| anyhow::anyhow!("no piece was read"));
Err(failure.context("the recording could not be transcribed"))
}
Ok(Ok(read)) => Ok(read),
Ok(Err(join)) => Err(anyhow::anyhow!("Inference task panicked: {join}")),
Err(_elapsed) => Err(anyhow::Error::new(InferenceTimedOut)),
}
}
fn read_all(engine: &mut Transcriber, pieces: Vec<Piece>, deadline: Instant) -> Read {
let mut read = Read {
regions: Vec::new(),
pieces: 0,
failure: None,
};
for piece in pieces {
if Instant::now() >= deadline {
break;
}
match read_piece(engine, piece) {
Ok(regions) => {
read.pieces += 1;
read.regions.extend(regions);
}
Err(error) => {
read.failure = Some(error);
break;
}
}
}
read
}
fn read_piece(engine: &mut Transcriber, piece: Piece) -> Result<Vec<Segment>> {
let (samples, rate, offset) = match piece {
Piece::File { path, offset } => {
let (samples, rate) = decode::decode_audio_to_mono_f32(&path).map_err(|error| {
tracing::warn!(path = %path.display(), %error, "A transcribed piece could not be decoded");
anyhow::Error::new(Unreadable)
})?;
(samples, rate, offset)
}
Piece::Memory { samples, rate } => (samples, rate, 0.0),
};
if samples.is_empty() {
return Ok(Vec::new());
}
let heard = engine.transcribe(&samples, rate)?;
Ok(heard
.regions
.into_iter()
.map(|region| segment(offset, heard.sample_rate, region))
.collect())
}
#[expect(
clippy::cast_precision_loss,
reason = "a sample index is exact in f64 far past any recording a machine can hold"
)]
fn segment(offset: f64, rate: u32, region: Region) -> Segment {
let at = |samples: usize| offset + samples as f64 / f64::from(rate);
Segment {
start: at(region.start),
end: at(region.end),
text: region.text,
label: region.label,
}
}
fn listener() -> Result<Arc<Mutex<Listener>>> {
ENCODER
.engine()
.context("the listening engine is not loaded")
}
pub(crate) fn embed_clip(samples: &[f32]) -> Result<Vec<f32>> {
let listener = listener()?;
let mut listener = listener.lock().unwrap_poison();
listener.embed(samples)
}
pub(crate) fn embed_pair(first: &[f32], second: &[f32]) -> Result<[Vec<f32>; PAIR]> {
let listener = listener()?;
let mut listener = listener.lock().unwrap_poison();
listener.embed_pair(first, second)
}
pub(crate) fn embed_clips(clips: &[Vec<f32>]) -> Vec<Vec<f32>> {
let Ok(listener) = listener() else {
tracing::warn!("embed_clips: the listening engine is not loaded");
return Vec::new();
};
let mut listener = listener.lock().unwrap_poison();
clips
.iter()
.filter_map(|clip| match listener.embed(clip) {
Ok(embedding) => Some(embedding),
Err(e) => {
tracing::warn!(
"Failed to embed a {}-sample clip: {e} — skipping",
clip.len()
);
None
}
})
.collect()
}
fn compose(segments: &[Segment]) -> String {
let mut text = String::new();
let mut marked = false;
for segment in segments {
if let Some(read) = &segment.text {
push_words(&mut text, read);
marked = false;
} else if segment.label.as_deref().is_some_and(is_speech_label) {
if !marked {
push_words(&mut text, UNTRANSCRIBED);
}
marked = true;
} else {
marked = false;
}
}
text
}
fn push_words(into: &mut String, words: &str) {
let words = words.trim();
if words.is_empty() {
return;
}
if !into.is_empty() {
into.push(' ');
}
into.push_str(words);
}
pub(crate) fn is_speech_label(label: &str) -> bool {
let label = label.trim();
SPEECH_LABELS
.iter()
.any(|class| label.eq_ignore_ascii_case(class))
}
const SILENCE_LABEL: &str = "Silence";
pub(crate) fn is_silence_label(label: &str) -> bool {
label.trim().eq_ignore_ascii_case(SILENCE_LABEL)
}
#[cfg(test)]
mod tests {
use super::*;
fn heard(start: f64, end: f64, text: Option<&str>, label: Option<&str>) -> Segment {
Segment {
start,
end,
text: text.map(str::to_string),
label: label.map(str::to_string),
}
}
#[test]
fn a_recording_of_silence_yields_nothing() {
let text = compose(&[heard(0.0, 1.0, None, Some("Silence"))]);
assert_eq!(text, "");
let text = compose(&[heard(0.0, 1.0, None, Some("Music"))]);
assert_eq!(text, "");
}
#[test]
fn unread_speech_is_marked_once_per_stretch() {
let text = compose(&[
heard(0.0, 1.0, Some("hello there"), None),
heard(1.0, 2.0, None, Some("Speech")),
heard(2.0, 3.0, None, Some("Male speech, man speaking")),
heard(3.0, 4.0, Some("how are you"), None),
heard(4.0, 5.0, None, Some("Speech")),
]);
assert_eq!(
text,
format!("hello there {UNTRANSCRIBED} how are you {UNTRANSCRIBED}")
);
}
#[test]
fn two_unread_stretches_apart_are_two_markers() {
let text = compose(&[
heard(0.0, 1.0, None, Some("Speech")),
heard(1.0, 2.0, None, Some("Music")),
heard(2.0, 3.0, None, Some("Speech")),
]);
assert_eq!(text, format!("{UNTRANSCRIBED} {UNTRANSCRIBED}"));
}
#[test]
fn a_recording_the_engine_could_not_read_still_says_so() {
let text = compose(&[heard(0.0, 1.0, None, Some("Speech"))]);
assert_eq!(text, UNTRANSCRIBED);
}
}