//! Text echo guard and spoken commands (Capri `microphone-service.mjs`). //! TODO: no acoustic echo cancellation; with speakers, enable PipeWire `module-echo-cancel` (see README). use std::sync::LazyLock; use std::time::{Duration, Instant}; use regex::Regex; fn words(text: &str) -> Vec { text.to_lowercase().split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).map(String::from).collect() } fn command_text(text: &str) -> &str { text.trim().trim_end_matches(['.', '!', '?', ',', ';', ':']).trim() } static MIC_OFF: LazyLock = LazyLock::new(|| { Regex::new(r"(?i)^(stop listening|microphone off|turn off (?:the )?microphone|не слушай|выключи микрофон|прекрати слушать)$").unwrap() }); static LOCAL_STOP: LazyLock = LazyLock::new(|| Regex::new(r"(?i)^(stop|stop capri|stop talking|be quiet|quiet capri|стоп|хватит|замолчи)$").unwrap()); static NEVER_ECHO: LazyLock = LazyLock::new(|| Regex::new(r"(?i)^(stop|stop capri|wait|no|be quiet|stop listening)$").unwrap()); static THREE: LazyLock = LazyLock::new(|| Regex::new(r"[\p{L}\p{N}]{3}").unwrap()); static SHORT: LazyLock = LazyLock::new(|| Regex::new(r"(?i)^(no|go|hi|ok)$").unwrap()); /// "Microphone off" works without the wake word. pub fn microphone_off(text: &str) -> bool { MIC_OFF.is_match(command_text(text)) } /// "Stop", "be quiet": handled locally, never sent to the model. pub fn local_stop(text: &str) -> bool { LOCAL_STOP.is_match(command_text(text)) } /// Speech substantial enough to interrupt Capri (barge-in). pub fn interruption(text: &str) -> bool { THREE.is_match(text) || SHORT.is_match(text.trim()) } /// Rejects transcripts of Capri's own speech. A new guard is created at every microphone stop. pub struct EchoGuard { tail: Duration, current: String, history: Vec<(String, Instant)>, } impl EchoGuard { pub fn new(trailing_silence_seconds: f32) -> Self { let tail = Duration::from_secs_f32((trailing_silence_seconds + 1.5).max(1.1)); Self { tail, current: String::new(), history: Vec::new() } } /// Called at each sentence start (`speaking`, text) and when playback stops. pub fn playback(&mut self, speaking: bool, text: &str, now: Instant) { if !self.current.is_empty() && (!speaking || self.current != text) { self.history.push((std::mem::take(&mut self.current), now + self.tail)); } self.current = if speaking { text.chars().take(1200).collect() } else { String::new() }; self.history.retain(|(_, until)| *until > now); let excess = self.history.len().saturating_sub(2); self.history.drain(..excess); } pub fn matches(&self, text: &str, now: Instant) -> bool { if NEVER_ECHO.is_match(command_text(text)) { return false; } let heard = words(text); let own: Vec<&str> = self.history.iter().filter(|(_, until)| *until > now).map(|(t, _)| t.as_str()).chain([self.current.as_str()]).collect(); let spoken = words(&own.join(" ")); if heard.is_empty() || spoken.is_empty() { return false; } if format!(" {} ", spoken.join(" ")).contains(&format!(" {} ", heard.join(" "))) { return true; } heard.len() >= 4 && heard.iter().filter(|w| spoken.contains(w)).count() as f32 / heard.len() as f32 >= 0.85 } } #[cfg(test)] mod tests { use super::*; #[test] fn commands() { assert!(microphone_off("Turn off the microphone.")); assert!(microphone_off("выключи микрофон")); assert!(local_stop("Stop!")); assert!(!local_stop("stop the music")); assert!(interruption("ok") && interruption("yes") && !interruption("uh")); } #[test] fn echo_of_own_sentence_within_tail() { let t0 = Instant::now(); let mut guard = EchoGuard::new(1.0); guard.playback(true, "The weather is sunny today in Paris.", t0); assert!(guard.matches("sunny today", t0)); assert!(!guard.matches("stop", t0), "explicit stop is never an echo"); guard.playback(false, "", t0); assert!(guard.matches("the weather is sunny", t0 + Duration::from_secs(2))); assert!(!guard.matches("the weather is sunny", t0 + Duration::from_secs(3)), "tail is 2.5 s at a 1 s pause"); assert!(!guard.matches("what about tomorrow", t0)); } }