//! Words as heard → text as written: spoken punctuation ("comma", "new //! paragraph", "కామా", "पूर्ण विराम", "句点"), casing and spacing. One //! implementation for dictation on the phone, meeting lines on the Mac and //! subtitle cues in the Worker. //! //! The rules are the UNION of the person's languages (one to three): a //! Telugu speaker who says "full stop" in English mid-sentence gets a full //! stop. Casing is by script, not by language: a sentence's first cased //! letter is raised whatever language it is in, and a script without case //! (Telugu, Devanagari, Japanese) is left as it is. use super::language::{self, Join, Language}; /// What the text before the new words says about how they start. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct Context { /// The new words begin a sentence (start of text, after a sentence's end /// mark or after a line break). pub sentence_start: bool, /// The last character before the new words; `None` at the start. pub prev: Option, } impl Context { /// The start of a text: a sentence starts and nothing needs a space. pub const START: Context = Context { sentence_start: true, prev: None }; } /// The person's languages and vocabulary, resolved once per session. #[derive(Debug, Clone, Default)] pub struct Rules { pub languages: Vec<&'static Language>, /// Names from the person's own rows, best first: they fix the casing of /// a caseless engine's words ("ravi" → "Ravi"). pub vocabulary: Vec, } /// How one pass is formatted. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct Options { /// The engine writes in capitals only (a streaming transducer's tokens). pub upper_case: bool, /// A command: no spoken punctuation, no sentence casing. pub command: bool, } impl Rules { /// The rules for these BCP 47 codes (`te-Latn` reads `te`'s file); a code /// with no file is skipped, and none known reads English. pub fn of(codes: &[&str], vocabulary: Vec) -> Rules { let mut languages: Vec<&'static Language> = Vec::new(); for code in codes { if let Some(found) = language::find(code) { if !languages.iter().any(|known| known.language == found.language) { languages.push(found); } } } if languages.is_empty() { languages.extend(language::find("en")); } Rules { languages, vocabulary } } fn ends_sentence(&self, mark: &str) -> bool { self.languages.iter().any(|language| language.sentence_end.iter().any(|end| end == mark)) } /// Whether `text`'s last word ends a sentence (closing quotes and /// brackets after the mark do not hide it). pub fn text_ends_sentence(&self, text: &str) -> bool { let trimmed = text.trim_end_matches(|c: char| c.is_whitespace() || CLOSERS.contains(c)); trimmed.chars().last().is_some_and(|last| { self.ends_sentence(&last.to_string()) || matches!(last, '.' | '?' | '!' | '।' | '。' | '?' | '!') }) } /// The context the text so far leaves for what follows it. pub fn context_after(&self, text: &str) -> Context { let prev = text.chars().last(); let sentence_start = match prev { None => true, Some('\n') => true, Some(_) => self.text_ends_sentence(text), }; Context { sentence_start, prev } } } pub(crate) const CLOSERS: &str = "”’\")]}»」』"; pub(crate) const OPENERS: &str = "“‘\"([{«「『¿¡"; pub(crate) const ATTACH_LEFT: &str = ".,;:!?…%)]}”’»、。,?!」』"; /// A script written without spaces between words (Japanese, Chinese, Thai). pub fn unspaced(c: char) -> bool { matches!(c as u32, 0x3000..=0x303F // CJK punctuation | 0x3040..=0x30FF // kana | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0xFF00..=0xFFEF // full-width forms | 0x0E00..=0x0E7F // Thai ) } /// Whether a space goes between `a` (the last character so far) and `b` /// (the first of what follows). pub fn needs_space(a: Option, b: char) -> bool { let Some(a) = a else { return false }; if a.is_whitespace() || b.is_whitespace() { return false; } if unspaced(a) || unspaced(b) { return false; } if ATTACH_LEFT.contains(b) || OPENERS.contains(a) { return false; } true } #[derive(Debug, Clone, PartialEq)] enum Item { Word(String), Mark { mark: String, join: Join }, } /// `raw` (one engine result) written after `context`: the result carries its /// own leading separator (a space, or nothing), so appending it to the text /// before is the whole job. pub fn format(raw: &str, rules: &Rules, context: Context, options: Options) -> String { let caseless = options.upper_case || all_capitals(raw) || !raw.chars().any(char::is_uppercase); let lowered; let raw = if options.upper_case || all_capitals(raw) { lowered = raw.to_lowercase(); lowered.as_str() } else { raw }; let tokens: Vec<&str> = raw.split_whitespace().collect(); let mut items = if options.command { tokens.iter().map(|t| Item::Word(t.to_string())).collect() } else { items(&tokens, rules) }; if caseless { recase(&mut items, rules); } assemble(&items, rules, context, options) } /// Every cased letter is a capital, and there are enough of them to be sure /// it is the engine's habit rather than an acronym ("OK", "NASA"). fn all_capitals(raw: &str) -> bool { let cased: Vec = raw.chars().filter(|c| c.is_uppercase() || c.is_lowercase()).collect(); cased.len() >= 4 && cased.iter().all(|c| c.is_uppercase()) && raw.split_whitespace().count() >= 2 } /// The spoken forms, longest first, as (words lowercased, the spoken entry). fn spoken_forms(rules: &Rules) -> Vec<(Vec, &'static language::Spoken, bool)> { let mut forms = Vec::new(); for language in &rules.languages { for spoken in &language.spoken { for say in &spoken.say { let words: Vec = say.split_whitespace().map(str::to_lowercase).collect(); if !words.is_empty() { forms.push((words, spoken, language.spaced)); } } } } forms.sort_by_key(|(words, _, _)| std::cmp::Reverse(words.len())); forms } fn strip_trailing(word: &str) -> (&str, &str) { let trimmed = word.trim_end_matches(|c: char| ATTACH_LEFT.contains(c) && c != '…'); (trimmed, &word[trimmed.len()..]) } fn items(tokens: &[&str], rules: &Rules) -> Vec { let forms = spoken_forms(rules); let mut out = Vec::new(); let mut i = 0; 'tokens: while i < tokens.len() { for (words, spoken, _) in &forms { let n = words.len(); if i + n > tokens.len() { continue; } let matches = (0..n).all(|k| { let token = if k + 1 == n { strip_trailing(tokens[i + k]).0 } else { tokens[i + k] }; token.to_lowercase() == words[k] }); if matches { out.push(Item::Mark { mark: spoken.mark.clone(), join: spoken.join }); i += n; continue 'tokens; } } // A token that is only punctuation the engine wrote by itself. let token = tokens[i]; if token.chars().all(|c| ATTACH_LEFT.contains(c)) { out.push(Item::Mark { mark: token.to_string(), join: Join::Left }); } else if token.chars().all(|c| OPENERS.contains(c)) { out.push(Item::Mark { mark: token.to_string(), join: Join::Right }); } else { split_unspaced(token, &forms, &mut out); } i += 1; } out } /// A token of an unspaced script may hold a spoken form inside it ("今日は改行明日"): /// a form that is not `whole_word` is found anywhere in it. fn split_unspaced(token: &str, forms: &[(Vec, &'static language::Spoken, bool)], out: &mut Vec) { let inside: Vec<(&str, &language::Spoken)> = forms .iter() .filter(|(words, spoken, spaced)| !spaced && !spoken.whole_word && words.len() == 1) .map(|(words, spoken, _)| (words[0].as_str(), *spoken)) .collect(); let mut rest = token; loop { let found = inside .iter() .filter_map(|(say, spoken)| rest.find(say).map(|at| (at, *say, *spoken))) .min_by_key(|(at, say, _)| (*at, std::cmp::Reverse(say.len()))); match found { Some((at, say, spoken)) if token.chars().any(unspaced) => { if at > 0 { out.push(Item::Word(rest[..at].to_string())); } out.push(Item::Mark { mark: spoken.mark.clone(), join: spoken.join }); rest = &rest[at + say.len()..]; } _ => { if !rest.is_empty() { out.push(Item::Word(rest.to_string())); } return; } } } } /// A caseless engine's words take the casing of the person's own names and /// of the words a language always writes so ("I"). fn recase(items: &mut [Item], rules: &Rules) { let mut terms: Vec<(Vec, Vec<&str>)> = rules .vocabulary .iter() .map(|term| (term.split_whitespace().map(str::to_lowercase).collect::>(), term.split_whitespace().collect::>())) .filter(|(lower, cased)| { !lower.is_empty() && cased.iter().any(|word| word.chars().any(char::is_uppercase)) && !(lower.len() == 1 && rules.languages.iter().any(|language| language.never_recase.iter().any(|common| common == &lower[0]))) }) .collect(); terms.sort_by_key(|(lower, _)| std::cmp::Reverse(lower.len())); let mut i = 0; while i < items.len() { let mut advanced = false; for (lower, cased) in &terms { let n = lower.len(); if i + n > items.len() { continue; } let fits = (0..n).all(|k| match &items[i + k] { Item::Word(word) => { let word = if k + 1 == n { strip_trailing(word).0 } else { word.as_str() }; word.to_lowercase() == lower[k] } Item::Mark { .. } => false, }); if fits { for k in 0..n { if let Item::Word(word) = &mut items[i + k] { let tail = if k + 1 == n { strip_trailing(word).1.to_string() } else { String::new() }; *word = format!("{}{tail}", cased[k]); } } i += n; advanced = true; break; } } if !advanced { if let Item::Word(word) = &mut items[i] { let (bare, tail) = strip_trailing(word); let lower = bare.to_lowercase(); if let Some(upper) = rules.languages.iter().flat_map(|language| &language.always_upper).find(|always| always.to_lowercase() == lower) { *word = format!("{upper}{tail}"); } } i += 1; } } } /// A command's words without the lead the person's languages start one /// with ("open ravi's page" → "ravi's page"). pub fn command_query(text: &str, rules: &Rules) -> String { let lower = text.trim().to_lowercase(); let mut leads: Vec<&String> = rules.languages.iter().flat_map(|language| &language.command_lead).collect(); leads.sort_by_key(|lead| std::cmp::Reverse(lead.len())); for lead in leads { let lead = lead.to_lowercase(); if let Some(rest) = lower.strip_prefix(&lead) { if rest.is_empty() || rest.starts_with(char::is_whitespace) || lead.chars().any(unspaced) { let cut = text.trim().len() - rest.len(); return text.trim()[cut..].trim().to_string(); } } } text.trim().to_string() } /// The first cased letter raised, past any opening quote or bracket. pub fn capitalise(word: &str) -> String { let mut out = String::with_capacity(word.len()); let mut done = false; for c in word.chars() { if !done && c.is_alphabetic() { done = true; if c.is_lowercase() { out.extend(c.to_uppercase()); continue; } } out.push(c); } out } fn assemble(items: &[Item], rules: &Rules, context: Context, options: Options) -> String { let mut out = String::new(); let mut start = context.sentence_start && !options.command; let mut prev = context.prev; // After an opening mark or a break the next word is glued on. let mut glued = false; for item in items { match item { Item::Word(word) => { let word = if start { capitalise(word) } else { word.clone() }; let first = word.chars().next().unwrap_or(' '); if !glued && needs_space(prev, first) { out.push(' '); } out.push_str(&word); glued = false; start = !options.command && rules.text_ends_sentence(&word); } Item::Mark { mark, join } => { match join { Join::Left | Join::None => { while out.ends_with(' ') { out.pop(); } out.push_str(mark); glued = *join == Join::None; start = false; } Join::Right => { let first = mark.chars().next().unwrap_or(' '); if !glued && prev.is_some_and(|p| !p.is_whitespace() && !OPENERS.contains(p)) && !(prev.is_some_and(unspaced) || unspaced(first)) { out.push(' '); } out.push_str(mark); glued = true; } Join::Space => { if prev.is_some_and(|p| !p.is_whitespace()) { out.push(' '); } out.push_str(mark); glued = false; start = false; } Join::Break => { while out.ends_with(' ') { out.pop(); } out.push_str(mark); glued = true; start = !options.command; } } if rules.ends_sentence(mark) { start = !options.command; } } } prev = out.chars().last().or(prev); } out } #[cfg(test)] #[path = "format_tests.rs"] mod tests;