capri-voice: add wake module

This commit is contained in:
nocode committed 2026-11-11 20:20:48 +01:00
1 parent 1fa570bd54
commit 1cb37cc685
1 file changed
+441
+441
View File
@@ -0,0 +1,441 @@
//! Wake phrase "Capri" / "Hey, Capri" with tolerance, and the attention gate (Capri `wake-phrase.mjs`).
//! Offsets are byte offsets into the transcript; timers are driven by `tick(now)`.
use std::time::{Duration, Instant};
use unicode_normalization::UnicodeNormalization;
const GREETINGS: &[&str] = &["hey", "hay", "hi", "эй", "хей", "хэй", "эи", "хеи", "хэи"];
const WEAK_GREETINGS: &[&str] = &["a", "ay", "eh", "he", "okay", "ok"];
struct Token {
word: String,
start: usize,
end: usize,
}
fn tokens(text: &str) -> Vec<Token> {
let mut out = Vec::new();
let mut start = None;
for (i, c) in text.char_indices().chain([(text.len(), ' ')]) {
match (c.is_alphanumeric(), start) {
(true, None) => start = Some(i),
(false, Some(s)) => {
let word = text[s..i].nfkd().filter(|c| !unicode_normalization::char::is_combining_mark(*c)).collect::<String>().to_lowercase();
out.push(Token { word, start: s, end: i });
start = None;
if out.len() == 256 {
break;
}
}
_ => {}
}
}
out
}
fn phonetic(word: &str) -> String {
let mapped: String = word
.chars()
.map(|c| match c {
'к' => 'k',
'а' | 'э' => 'a',
'е' => 'e',
'п' => 'p',
'р' => 'r',
'и' | 'й' | 'ы' => 'i',
'ф' => 'f',
c => c,
})
.collect();
let mut s = mapped;
if s.ends_with("ce") {
s.truncate(s.len() - 2);
s.push('s');
}
let s = replace_pairs(&s);
let mut s = if s.ends_with('y') { format!("{}i", &s[..s.len() - 1]) } else { s };
s = s.chars().map(|c| match c {
'c' | 'q' => 'k',
'b' | 'f' => 'p',
c => c,
}).collect();
let mut out = String::new();
for c in s.chars() {
if !(c.is_ascii_lowercase() && out.ends_with(c)) {
out.push(c);
}
}
out
}
/// JS `replace(/ee|ie|ea/g, 'i')`: one left-to-right pass.
fn replace_pairs(s: &str) -> String {
let chars: Vec<char> = s.chars().collect();
let (mut out, mut i) = (String::new(), 0);
while i < chars.len() {
if i + 1 < chars.len() && matches!((chars[i], chars[i + 1]), ('e', 'e') | ('i', 'e') | ('e', 'a')) {
out.push('i');
i += 2;
} else {
out.push(chars[i]);
i += 1;
}
}
out
}
/// Bounded Damerau distance; a length difference above two counts as three.
fn distance(a: &[char], b: &[char]) -> usize {
if a.len().abs_diff(b.len()) > 2 {
return 3;
}
let mut rows = vec![vec![0usize; b.len() + 1]; a.len() + 1];
for (i, row) in rows.iter_mut().enumerate() {
row[0] = i;
}
for (j, cell) in rows[0].iter_mut().enumerate() {
*cell = j;
}
for i in 1..=a.len() {
for j in 1..=b.len() {
let cost = usize::from(a[i - 1] != b[j - 1]);
rows[i][j] = (rows[i - 1][j] + 1).min(rows[i][j - 1] + 1).min(rows[i - 1][j - 1] + cost);
if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
rows[i][j] = rows[i][j].min(rows[i - 2][j - 2] + 1);
}
}
}
rows[a.len()][b.len()]
}
/// `Some(exact)` when the word sounds like "Capri".
fn name_match(word: &str, relaxed: bool) -> Option<bool> {
let sound: Vec<char> = phonetic(word).chars().collect();
if sound.len() < 3 || sound.len() > 9 || sound[0] != 'k' || !sound.iter().take(4).any(|c| *c == 'p') {
return None;
}
let edits = distance(&sound, &['k', 'a', 'p', 'r', 'i']);
(edits <= if relaxed { 2 } else { 1 }).then_some(edits == 0)
}
#[derive(Clone, Debug, PartialEq)]
pub struct WakeMatch {
pub start: usize,
pub end: usize,
pub exact: bool,
pub body: String,
}
fn body_after(text: &str, end: usize) -> String {
text[end..].trim_start_matches(|c: char| c.is_whitespace() || ",.!?;:—–-".contains(c)).to_string()
}
fn joined(parts: &[Token]) -> String {
parts.iter().map(|p| p.word.as_str()).collect()
}
pub fn find_wake_phrase(text: &str, relaxed: bool) -> Option<WakeMatch> {
let parts = tokens(text);
// A bare name must start the address; stay strict so "copy" remains a command.
for count in [1, 2] {
if parts.len() >= count
&& let Some(exact) = name_match(&joined(&parts[..count]), false)
{
let end = parts[count - 1].end;
return Some(WakeMatch { start: parts[0].start, end, exact, body: body_after(text, end) });
}
}
for i in 0..parts.len() {
let greeting = parts[i].word.as_str();
let mut compound = None;
for prefix in ["hey", "hay", "эй", "эи"] {
if greeting.len() > prefix.len() && greeting.starts_with(prefix) {
compound = name_match(&greeting[prefix.len()..], relaxed);
}
}
if let Some(exact) = compound {
return Some(WakeMatch { start: parts[i].start, end: parts[i].end, exact, body: body_after(text, parts[i].end) });
}
let strong = GREETINGS.contains(&greeting);
if !strong && !WEAK_GREETINGS.contains(&greeting) {
continue;
}
for count in [1, 2] {
if i + count >= parts.len() {
continue;
}
let Some(exact) = name_match(&joined(&parts[i + 1..=i + count]), relaxed) else { continue };
if !strong && !exact && !relaxed {
continue;
}
let end = parts[i + count].end;
return Some(WakeMatch { start: parts[i].start, end, exact: exact && strong, body: body_after(text, end) });
}
}
None
}
/// Removes the address from the utterance that opened the gate.
pub fn strip_activated_prefix(text: &str) -> String {
if let Some(m) = find_wake_phrase(text, true) {
return m.body;
}
let parts = tokens(text);
for count in [1, 2] {
if parts.len() >= count && name_match(&joined(&parts[..count]), false).is_some() {
return body_after(text, parts[count - 1].end);
}
}
text.to_string()
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WordBoundary {
pub start: usize,
pub end: usize,
pub start_sample: u64,
pub end_sample: u64,
}
/// A wake probe or final transcript as seen by the gate.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WakeEvent {
pub utterance: i64,
pub text: String,
pub last: bool,
pub boundaries: Vec<WordBoundary>,
pub prefix_removed: bool,
/// The recognizer is still decoding: the command window is extended.
pub refining: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GateState {
Disabled,
Waiting,
Command,
}
#[derive(Clone, Debug, PartialEq)]
pub enum GateOutput {
Wake { utterance: i64, wake_end_sample: Option<u64> },
/// A held, ambiguous candidate was activated: feed it again to the transcript handler.
Ready(WakeEvent),
Sleep(&'static str),
}
#[derive(Debug, PartialEq)]
pub struct Observed {
pub accepted: bool,
pub pending: bool,
pub text: String,
}
pub struct WakeGate {
enabled: bool,
command_window: Duration,
hold: Duration,
pub state: GateState,
floor: i64,
last_utterance: i64,
wake_utterance: i64,
candidate: Option<(WakeEvent, Instant)>,
expiry: Option<Instant>,
out: Vec<GateOutput>,
}
impl WakeGate {
/// Capri bounds: window 3..30 s, hold 0..500 ms.
pub fn new(enabled: bool, command_window_ms: u32, ambiguity_hold_ms: u32) -> Self {
Self {
enabled,
command_window: Duration::from_millis(command_window_ms.clamp(3000, 30000).into()),
hold: Duration::from_millis(ambiguity_hold_ms.min(500).into()),
state: if enabled { GateState::Waiting } else { GateState::Disabled },
floor: 0,
last_utterance: -1,
wake_utterance: -1,
candidate: None,
expiry: None,
out: Vec::new(),
}
}
fn arm(&mut self, now: Instant, refining: bool, budget_ms: u64) {
let window = if refining {
self.command_window.max(Duration::from_millis(budget_ms.clamp(20_000, 90_000)))
} else {
self.command_window
};
self.expiry = Some(now + window);
}
fn activate(&mut self, event: WakeEvent, now: Instant, delayed: bool) {
self.candidate = None;
self.state = GateState::Command;
self.wake_utterance = event.utterance;
self.last_utterance = event.utterance;
self.arm(now, false, 0);
let matched = find_wake_phrase(&event.text, false);
let boundary = matched.and_then(|m| event.boundaries.iter().find(|w| w.start < m.end && w.end >= m.end).map(|w| w.end_sample));
self.out.push(GateOutput::Wake { utterance: event.utterance, wake_end_sample: boundary });
if delayed {
self.out.push(GateOutput::Ready(event));
}
}
/// `budget_ms`: 90 000 while a slow recognizer is processing, else 20 000.
pub fn observe(&mut self, event: &WakeEvent, now: Instant, budget_ms: u64) -> Observed {
if !self.enabled {
return Observed { accepted: true, pending: false, text: event.text.trim().to_string() };
}
let rejected = |pending| Observed { accepted: false, pending, text: String::new() };
if event.utterance < self.floor {
return rejected(false);
}
if self.state == GateState::Waiting {
let Some(m) = find_wake_phrase(&event.text, false) else {
self.candidate = None;
return rejected(false);
};
if m.exact || event.last || self.hold.is_zero() {
self.activate(event.clone(), now, false);
} else {
let deadline = match &self.candidate {
Some((c, at)) if c.utterance == event.utterance => *at,
_ => now + self.hold,
};
self.candidate = Some((event.clone(), deadline));
return rejected(true);
}
}
self.last_utterance = self.last_utterance.max(event.utterance);
// Only the utterance that opened the gate carries the address.
let text = if !event.prefix_removed && event.utterance == self.wake_utterance {
strip_activated_prefix(&event.text)
} else {
event.text.clone()
};
if !text.trim().is_empty() {
self.arm(now, event.refining, budget_ms);
}
Observed { accepted: true, pending: false, text: text.trim().to_string() }
}
pub fn cancel_candidate(&mut self) {
self.candidate = None;
}
pub fn has_candidate(&self) -> bool {
self.candidate.is_some()
}
pub fn rearm(&mut self, utterance: Option<i64>, reason: &'static str) {
if !self.enabled {
return;
}
self.candidate = None;
self.expiry = None;
self.floor = self.floor.max(utterance.unwrap_or(self.last_utterance) + 1);
self.state = GateState::Waiting;
self.out.push(GateOutput::Sleep(reason));
}
/// Opens the command window without a wake phrase (follow-up, listen now).
pub fn continue_listening(&mut self, now: Instant, ms: u64) -> bool {
if !self.enabled || self.state != GateState::Waiting {
return false;
}
self.candidate = None;
self.state = GateState::Command;
self.wake_utterance = -1;
self.expiry = Some(now + Duration::from_millis(ms.clamp(5000, 30000)));
true
}
/// Fires the hold and window timers, then returns every pending output.
pub fn tick(&mut self, now: Instant) -> Vec<GateOutput> {
if let Some((event, at)) = self.candidate.take() {
if now >= at {
self.activate(event, now, true);
} else {
self.candidate = Some((event, at));
}
}
if self.expiry.is_some_and(|at| now >= at) {
self.rearm(None, "timeout");
}
std::mem::take(&mut self.out)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn wake(text: &str) -> Option<(bool, String)> {
find_wake_phrase(text, false).map(|m| (m.exact, m.body))
}
#[test]
fn names_and_greetings() {
assert_eq!(wake("Capri, what time is it?"), Some((true, "what time is it?".into())));
assert_eq!(wake("Hey Capri open Spotify"), Some((true, "open Spotify".into())));
assert_eq!(wake("hey, Kapree stop"), Some((true, "stop".into())), "kapree sounds exactly like kapri");
assert_eq!(wake("hey, Kapro stop"), Some((false, "stop".into())));
assert_eq!(wake("heycapri hello"), Some((true, "hello".into())));
assert_eq!(wake("Ca pri play"), Some((true, "play".into())));
assert_eq!(wake("Эй, Капри, привет"), Some((true, "привет".into())));
assert_eq!(wake("copy that"), None, "commands are not names");
assert_eq!(wake("I told Capri yesterday"), None, "a name must start the address");
assert_eq!(wake("ok Capri go"), Some((false, "go".into())), "weak greetings are never exact");
assert_eq!(wake("ok Kapro go"), None, "weak greetings need an exact name");
assert_eq!(strip_activated_prefix("Capri. Open the door"), "Open the door");
assert_eq!(strip_activated_prefix("open the door"), "open the door");
}
fn event(utterance: i64, text: &str, last: bool) -> WakeEvent {
WakeEvent { utterance, text: text.into(), last, ..Default::default() }
}
#[test]
fn gate_activates_strips_and_times_out() {
let t0 = Instant::now();
let mut gate = WakeGate::new(true, 10_000, 120);
assert!(!gate.observe(&event(0, "what time is it", true), t0, 20_000).accepted);
let mut e = event(1, "Hey Capri what time is it", true);
e.boundaries = vec![
WordBoundary { start: 0, end: 3, start_sample: 100, end_sample: 4000 },
WordBoundary { start: 4, end: 9, start_sample: 4000, end_sample: 9000 },
];
let seen = gate.observe(&e, t0, 20_000);
assert_eq!(seen.text, "what time is it");
assert_eq!(gate.tick(t0), vec![GateOutput::Wake { utterance: 1, wake_end_sample: Some(9000) }]);
assert!(gate.observe(&event(2, "and the weather", true), t0, 20_000).accepted);
assert_eq!(gate.tick(t0 + Duration::from_secs(11)), vec![GateOutput::Sleep("timeout")]);
assert!(!gate.observe(&event(2, "Capri", true), t0, 20_000).accepted, "utterances before the floor are ignored");
}
#[test]
fn ambiguous_candidate_is_held_then_activated() {
let t0 = Instant::now();
let mut gate = WakeGate::new(true, 10_000, 120);
let seen = gate.observe(&event(0, "hey kapro", false), t0, 20_000);
assert!(seen.pending);
assert!(gate.tick(t0 + Duration::from_millis(50)).is_empty());
let out = gate.tick(t0 + Duration::from_millis(130));
assert!(matches!(out[0], GateOutput::Wake { utterance: 0, .. }));
assert!(matches!(out[1], GateOutput::Ready(_)));
assert_eq!(gate.state, GateState::Command);
}
#[test]
fn follow_up_and_disabled_gate() {
let t0 = Instant::now();
let mut gate = WakeGate::new(true, 10_000, 120);
assert!(gate.continue_listening(t0, 12_000));
assert_eq!(gate.observe(&event(0, "Capri is great", true), t0, 20_000).text, "Capri is great", "no stripping in follow-up");
let mut off = WakeGate::new(false, 10_000, 120);
assert_eq!(off.observe(&event(0, " hello ", true), t0, 20_000).text, "hello");
}
}