From a9562c73f1f2f1c32dbf81c3e6fa02f6c192eb09 Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:48 +0100 Subject: [PATCH] capri-voice: add text module --- crates/capri-voice/src/text.rs | 177 +++++++++++++++++++++++++++++++++ 1 file changed, 177 insertions(+) create mode 100644 crates/capri-voice/src/text.rs diff --git a/crates/capri-voice/src/text.rs b/crates/capri-voice/src/text.rs new file mode 100644 index 0000000..c2f062a --- /dev/null +++ b/crates/capri-voice/src/text.rs @@ -0,0 +1,177 @@ +//! Spoken-text rules (Capri `renderer/speech-text.mjs`, `voice-follow-up.mjs`): what is read aloud and where sentences end. +use std::sync::LazyLock; + +use regex::Regex; + +/// Longest sentence sent to synthesis (also the sidecar limit). +pub const MAX_SPEECH_SENTENCE: usize = 1200; + +static FENCE: LazyLock = LazyLock::new(|| Regex::new(r"```[\s\S]*?(?:```|$)").unwrap()); +static TAGS: LazyLock = LazyLock::new(|| Regex::new(r"(?i)\[(?:voice|avatar|pose):[^\]]*\]").unwrap()); +static LINK: LazyLock = LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\(https?://[^)]+\)").unwrap()); +static URL: LazyLock = LazyLock::new(|| Regex::new(r"https?://\S+").unwrap()); +static MARKS: LazyLock = LazyLock::new(|| Regex::new(r"[*#_~]").unwrap()); +static SPACES: LazyLock = LazyLock::new(|| Regex::new(r"\s+").unwrap()); +static ABBREVIATION: LazyLock = + LazyLock::new(|| Regex::new(r"(?i)(?:\b(?:mr|mrs|ms|dr|prof|st|vs|etc|no)|\b[a-z])\.$").unwrap()); +static NUMBER: LazyLock = LazyLock::new(|| Regex::new(r"^\d+\.$").unwrap()); +static FOLLOW_UP: LazyLock = LazyLock::new(|| Regex::new(r#"[??؟][\s\p{Pe}\p{Pf}"'»]*$"#).unwrap()); + +/// Code is hidden with NUL bytes of the same byte length, so streamed offsets stay stable. +fn masked(text: &str) -> String { + let fenced = FENCE.replace_all(text, |c: ®ex::Captures| "\0".repeat(c[0].len())); + fenced.replace('`', "\0") +} + +/// Text as it is spoken: no code, tags, links, URLs or Markdown marks. +pub fn spoken_text(text: &str) -> String { + let text = masked(text).replace('\0', " "); + let text = TAGS.replace_all(&text, ""); + let text = LINK.replace_all(&text, "$1"); + let text = URL.replace_all(&text, ""); + let text = MARKS.replace_all(&text, ""); + SPACES.replace_all(&text, " ").trim().to_string() +} + +/// The English voice must not read mostly non-Latin text. +pub fn speech_language_mismatch(text: &str, language: &str) -> bool { + if language != "en" { + return false; + } + let (mut letters, mut foreign) = (0usize, 0usize); + static LATIN: LazyLock = LazyLock::new(|| Regex::new(r"\p{Latin}").unwrap()); + for c in text.chars().filter(|c| c.is_alphabetic()) { + letters += 1; + if !LATIN.is_match(c.encode_utf8(&mut [0; 4])) { + foreign += 1; + } + } + foreign >= 3 && foreign * 4 >= letters +} + +const LATIN_END: &str = ".!?;…"; +const LATIN_CLOSE: &str = "\"”'’)]}"; +const WIDE_END: &str = "!?;。؟؛।॥"; +const WIDE_CLOSE: &str = "\"”'’)]}」』"; + +/// Byte offset just after the first sentence terminator, if any (commas and colons never split). +pub fn find_sentence_end(text: &str, last: bool) -> Option { + let chars: Vec<(usize, char)> = text.char_indices().collect(); + let run = |mut i: usize, set: &str| { + while i < chars.len() && set.contains(chars[i].1) { + i += 1; + } + i + }; + let at = |i: usize| chars.get(i).map_or(text.len(), |c| c.0); + let mut i = 0; + while i < chars.len() { + let c = chars[i].1; + let (wide, stop) = if LATIN_END.contains(c) { + (false, run(run(i, LATIN_END), LATIN_CLOSE)) + } else if WIDE_END.contains(c) { + (true, run(run(i, WIDE_END), WIDE_CLOSE)) + } else { + i += 1; + continue; + }; + let end = at(stop); + let next_space = chars.get(stop).is_some_and(|c| c.1.is_whitespace()); + let matched = wide || next_space || (last && stop == chars.len()); + if matched { + // A wide terminator at the end of a streamed buffer may still get a closing quote. + let waiting = wide && !last && end == text.len(); + let dot = c == '.' && !text[chars[i].0..].starts_with(".."); + let abbreviation = dot && { + let prefix = &text[..chars[i].0 + 1]; + ABBREVIATION.is_match(prefix) || NUMBER.is_match(prefix.trim()) + }; + if !waiting && !abbreviation { + return Some(end); + } + } + i = stop.max(i + 1); + } + None +} + +/// Splits streamed reply text into spoken sentences. +#[derive(Default)] +pub struct SentenceBuffer { + buffer: String, +} + +impl SentenceBuffer { + pub fn push(&mut self, text: &str, last: bool) -> Vec { + self.buffer.push_str(text); + let mut parts = Vec::new(); + while !self.buffer.is_empty() { + let visible = masked(&self.buffer); + let Some(first) = visible.find(|c: char| c != '\0' && !c.is_whitespace()) else { + if last { + self.buffer.clear(); + } + break; + }; + if first > 0 { + self.buffer.drain(..first); + continue; + } + let Some(end) = find_sentence_end(&visible, last).or(last.then_some(self.buffer.len())) else { break }; + let sentence = spoken_text(&self.buffer[..end]); + self.buffer.drain(..end); + if !sentence.is_empty() { + parts.push(sentence); + } + } + parts + } +} + +/// A spoken reply ending with a question reopens the microphone. +pub fn wants_follow_up(reply: &str) -> bool { + FOLLOW_UP.is_match(reply.trim()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn spoken_text_drops_code_tags_links() { + assert_eq!(spoken_text("Hi *there* [avatar:happy] see [docs](https://x.y/z) at https://a.b ```rm -rf``` `ls` ok"), "Hi there see docs at ls ok", "inline code delimiters never swallow words"); + } + + #[test] + fn sentence_boundaries() { + assert_eq!(find_sentence_end("Hello there. Next", false), Some(12)); + assert_eq!(find_sentence_end("Hello there.", false), None); + assert_eq!(find_sentence_end("Hello there.", true), Some(12)); + assert_eq!(find_sentence_end("Ask Dr. Who now", false), None); + assert_eq!(find_sentence_end("3. go", false), None); + assert_eq!(find_sentence_end("Step 3. go", false), Some(7)); + assert_eq!(find_sentence_end("Wait... go", false), Some(7)); + assert_eq!(find_sentence_end("He said \"no!\" then", false), Some(13)); + assert_eq!(find_sentence_end("你好。", false), None, "a closing quote may still follow"); + assert_eq!(find_sentence_end("你好。再", false), Some(9)); + assert_eq!(find_sentence_end("a, b: c", true), None); + } + + #[test] + fn buffer_streams_sentences_and_skips_code() { + let mut b = SentenceBuffer::default(); + assert!(b.push("Hello wor", false).is_empty()); + assert_eq!(b.push("ld. How are", false), vec!["Hello world."]); + assert_eq!(b.push(" you? ```a. b. c.``` Done", false), vec!["How are you?"]); + assert_eq!(b.push("", true), vec!["Done"]); + } + + #[test] + fn language_guard_and_follow_up() { + assert!(speech_language_mismatch("Привет, как дела?", "en")); + assert!(!speech_language_mismatch("Hello there my good friend, Привет", "en")); + assert!(!speech_language_mismatch("Привет", "ru")); + assert!(wants_follow_up("Want more? »")); + assert!(!wants_follow_up("Done.")); + } +}