//! 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.usesuper::language::{self, Join, Language};/// What the text before the new words says about how they start.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pubstructContext {/// 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<char>,}implContext {/// The start of a text: a sentence starts and nothing needs a space.pubconst START: Context = Context { sentence_start: true, prev: None };}/// The person's languages and vocabulary, resolved once per session.#[derive(Debug, Clone, Default)]pubstructRules {pub languages: Vec<&'staticLanguage>,/// Names from the person's own rows, best first: they fix the casing of/// a caseless engine's words ("ravi" → "Ravi").pub vocabulary: Vec<String>,}/// How one pass is formatted.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pubstructOptions {/// 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,}implRules {/// 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.pubfn of(codes: &[&str], vocabulary: Vec<String>) -> Rules {letmut languages: Vec<&'staticLanguage> = Vec::new();for code in codes {ifletSome(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).pubfn 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.pubfn 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).pubfn 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).pubfn needs_space(a: Option<char>, b: char) -> bool {letSome(a) = a else { returnfalse };if a.is_whitespace() || b.is_whitespace() {returnfalse; }if unspaced(a) || unspaced(b) {returnfalse; }if ATTACH_LEFT.contains(b) || OPENERS.contains(a) {returnfalse; }true}#[derive(Debug, Clone, PartialEq)]enumItem {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.pubfn 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();letmut 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<char> = 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<String>, &'static language::Spoken, bool)> {letmut forms = Vec::new();for language in &rules.languages {for spoken in &language.spoken {for say in &spoken.say {let words: Vec<String> = 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<Item> {let forms = spoken_forms(rules);letmut out = Vec::new();letmut 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 }); } elseif 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<String>, &'static language::Spoken, bool)], out: &mutVec<Item>) {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();letmut 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) {letmut terms: Vec<(Vec<String>, Vec<&str>)> = rules .vocabulary .iter() .map(|term| (term.split_whitespace().map(str::to_lowercase).collect::<Vec<_>>(), term.split_whitespace().collect::<Vec<_>>())) .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()));letmut i = 0;while i < items.len() {letmut 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 in0..n {ifletItem::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 {ifletItem::Word(word) = &mut items[i] {let (bare, tail) = strip_trailing(word);let lower = bare.to_lowercase();ifletSome(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").pubfn command_query(text: &str, rules: &Rules) -> String {let lower = text.trim().to_lowercase();letmut 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();ifletSome(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.pubfn capitalise(word: &str) -> String {letmut out = String::with_capacity(word.len());letmut 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 {letmut out = String::new();letmut start = context.sentence_start && !options.command;letmut prev = context.prev;// After an opening mark or a break the next word is glued on.letmut 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;