the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Pinyin: claim only words written as pinyin is, so accented English stays English (résumé, touché, née, Pokémon)
Joshua Pham58099b8d3019
diff --git a/crates/chimera/src/phonetics/mandarin.rs b/crates/chimera/src/phonetics/mandarin.rsindex 696dc3c..92aa494 100644--- a/crates/chimera/src/phonetics/mandarin.rs+++ b/crates/chimera/src/phonetics/mandarin.rs@@ -499,6 +499,8 @@ fn parse_pinyin(word: &str) -> Option<Vec<(String, String)>> {return None;}let mut out = Vec::new();+ // whether each syllable's tone was written (a mark or a number), and its letters+ let mut written: Vec<(bool, String)> = Vec::new();for (letters, digit) in pieces.into_iter().filter(|p| !p.0.is_empty()) {let base: String = letters.iter().map(|l| l.1).collect();let cuts = split_syllables(&base)?;@@ -509,7 +511,9 @@ fn parse_pinyin(word: &str) -> Option<Vec<(String, String)>> {if marks.len() > 1 {return None;}- let tone = marks.first().copied().or(if n + 1 == cuts.len() { digit } else { None }).unwrap_or(5);+ let number = if n + 1 == cuts.len() { digit } else { None };+ written.push((!marks.is_empty() || number.is_some(), base[start..end].to_string()));+ let tone = marks.first().copied().or(number).unwrap_or(5);let mut text: String = span.iter().map(|l| l.0).collect();if n + 1 == cuts.len() && digit.is_some() && marks.is_empty() {text.push(char::from(b'0' + tone));@@ -518,6 +522,14 @@ fn parse_pinyin(word: &str) -> Option<Vec<(String, String)>> {start = end;}}+ // a toned word starts with a written tone; after that an unwritten one is neutral, at the end+ // (xièxie, dōngxi) or as bu, de, yi inside (duìbuqǐ, kànbujiàn). English words with accents+ // break this: résumé (su unwritten inside), touché (tou unwritten first)+ let last = written.len() - 1;+ let neutral_inside = |b: &str| matches!(b, "bu" | "de" | "yi");+ if !written[0].0 || written.iter().enumerate().any(|(i, (w, b))| !w && i > 0 && i < last && !neutral_inside(b)) {+ return None;+ }Some(out)}@@ -528,7 +540,17 @@ fn split_syllables(base: &str) -> Option<Vec<usize>> {return true;}for end in (at + 1..=base.len().min(at + 6)).rev() {- if valid_syllable(&base[at..end]) {+ let s = &base[at..end];+ // pinyin's spelling: a syllable starting with a, o or e after another needs an apostrophe+ // (Xī'ān), so née isn't né + e; the syllabic nasals are whole words (嗯 n), so Pokémon+ // isn't po ké mo + n+ if at > 0 && matches!(s.as_bytes()[0], b'a' | b'o' | b'e') {+ continue;+ }+ if matches!(s, "n" | "ng" | "m" | "hm" | "hng") && !(at == 0 && end == base.len()) {+ continue;+ }+ if valid_syllable(s) {out.push(end);if go(base, end, out) {return true;@@ -550,9 +572,8 @@ impl FrontEnd for Pinyin {self.starts(c) || c.is_ascii_digit() || c == '\''}fn claims(&self, word: &str) -> bool {- // a one-letter word with a tone number is English ("room a1"); 啊 and 饿 take marks (ā, è)- let numbered = word.chars().any(|c| c.is_ascii_digit());- if numbered && word.chars().filter(|c| c.is_alphabetic()).count() < 2 {+ // a one-letter word is English ("room a1", French "à"); write 啊 and 饿 in characters+ if word.chars().filter(|c| c.is_alphabetic()).count() < 2 {return false;}parse_pinyin(word).is_some()diff --git a/crates/chimera/tests/mandarin.rs b/crates/chimera/tests/mandarin.rsindex 4b8672e..899f61b 100644--- a/crates/chimera/tests/mandarin.rs+++ b/crates/chimera/tests/mandarin.rs@@ -3,7 +3,7 @@use chimera::phonetics::english::EnglishG2P;use chimera::phonetics::korean::Korean;use chimera::phonetics::mandarin::{Mandarin, MandarinLexicon, Pinyin, tone_bends};-use chimera::phonetics::syllables::{English, read_lyrics};+use chimera::phonetics::syllables::{English, FrontEnd, read_lyrics};use chimera::phonetics::{Edge, Syllable};const LEX: &str = "举\tju3\n风\tfeng1\n多\tduo1\n头\ttou2\n鸟\tniao3\n光\tguang1\n四\tsi4\n是\tshi4\n点\tdian3\n哪\tna3\n儿\ter2\n女\tnv3\n子\tzi5\n块\tkuai4\n一会儿\tyi1 hui4 er5\n天\ttian1\n你\tni3\n好\thao3\n我\two3\n不\tbu4\n会\thui4\n银\tyin2\n行\txing2\n银行\tyin2 hang2\n走\tzou3\n的\tde5\n跑\tpao3\n一\tyi1\n个\tge4\n绿\tlv4\n学\txue2\n吃\tchi1\n爱\tai4\n去\tqu4\n";@@ -92,9 +92,26 @@ fn pinyin_with_tones_is_mandarin_and_without_is_english() {// sings "Z rich ber" as on main (review of #78: it sang "Z ber")let e: Vec<String> = typed("hello café it's Zürich über").into_iter().map(|x| x.0).collect();assert_eq!(e, ["hel", "lo", "caf", "it's", "Z", "rich", "ber"]);- // a one-letter word with a tone number stays English; with marks it is pinyin- let a: Vec<(String, String)> = typed("a1 ā").into_iter().map(|x| (x.0, x.1)).collect();- assert_eq!(a.iter().map(|x| x.0.as_str()).collect::<Vec<_>>(), ["a", "ā"]);+ // a one-letter word stays English ("room a1", French "à")+ let a: Vec<String> = typed("a1 à").into_iter().map(|x| x.0).collect();+ assert_eq!(a, ["a"]); // "à" isn't English's (accented letters are skipped, as on main)+}++#[test]+fn accented_english_words_stay_english() {+ // pinyin's spelling rules keep these out (review of #85: 12 of 42 were read as pinyin): a toned+ // word starts with a written tone, an unwritten one inside is only bu, de or yi (résumé,+ // touché, lamé), a vowel-initial syllable inside needs an apostrophe (née, matinée, mélange,+ // brûlée), and n, ng, m are syllables only as whole words (Pokémon, détente)+ for w in ["café", "résumé", "cliché", "naïve", "brûlée", "Pokémon", "touché", "détente", "matinée", "née", "lamé", "saké", "mélange", "à"] {+ assert!(!Pinyin.claims(w), "{w} read as pinyin");+ }+ // the one left: é + lan is real pinyin with a neutral last syllable+ assert!(Pinyin.claims("élan"));+ // and real pinyin still reads, including a neutral bu or de inside and apostrophes+ for w in ["nǐhǎo", "xièxie", "dōngxi", "duìbuqǐ", "kànbujiàn", "Xī'ān", "Tiān'ānmén", "nǚ'ér", "ni3hao3", "zhong1guo2", "xǐhuan", "bú"] {+ assert!(Pinyin.claims(w), "{w} not read as pinyin");+ }}#[test]diff --git a/docs/language-front-ends.md b/docs/language-front-ends.mdindex baf5791..e08bbb4 100644--- a/docs/language-front-ends.md+++ b/docs/language-front-ends.md@@ -87,12 +87,17 @@ data, `tools/build-mandarin.ts`), longest phrase first: 银行 is yín háng,- **A vowel-initial syllable** (爱, 安) starts with a soft glottal catch, so it doesn't run into thevowel before.-**Pinyin** with tones is Mandarin too: tone marks (`nǐhǎo`, `xièxie`, an unmarked syllable inside a-marked word being neutral) or numbers (`ni3 hao3`, `de5`); apostrophes split syllables (`Xī'ān`),-and `ü` or `v` both work. Third-tone sandhi applies inside a word. Pinyin claims only a word that-parses fully into real syllables and carries tones, so plain Latin words stay English. Two-ambiguities: an accented English word that is also toned pinyin (`résumé`) reads as pinyin, so type-it unaccented; and a one-letter word with a tone number (`a1`) stays English, so write 啊 as `ā`.+**Pinyin** with tones is Mandarin too: tone marks (`nǐhǎo`, and `xièxie` with a neutral last+syllable) or numbers (`ni3 hao3`, `de5`); apostrophes split syllables (`Xī'ān`), and `ü` or `v` both+work. Third-tone sandhi applies inside a word. Pinyin claims only a word written as pinyin is:+- every syllable real, and a vowel-initial one inside the word after an apostrophe (`Xī'ān`);+- the first syllable's tone written; an unwritten one later is neutral, at the end (`dōngxi`) or as+ bu, de, yi inside (`duìbuqǐ`);+- two letters or more (a one-letter word, `a1` or `à`, is English; write 啊 in characters).++So plain Latin words stay English, and so do accented English words (`café`, `résumé`, `touché`,+`née`, `Pokémon`). The one left: `élan` is also real pinyin (é + a neutral lan), so type it+unaccented.What each choice measured, on the scramble test (#80) where it was tuned: