Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

Pinyin and the lexicon, from review: splitting in linear time, 哟 reads, neutral syllables inside a word, capitals kept

Joshua Pham6b79da816490
diff --git a/crates/chimera-cli/src/compare.rs b/crates/chimera-cli/src/compare.rs
index 3b470e7..ab5615b 100644
--- a/crates/chimera-cli/src/compare.rs
+++ b/crates/chimera-cli/src/compare.rs
@@ -291,7 +291,6 @@ fn render_notes(notes: &[Note], body_name: &str, seconds: f64) -> Result<Render,
bpm: 60.0,
t0: notes[i].start,
vibrato: VIBRATO_CENTS,
- ..Default::default()
},
);
v.schedule(&plan.gestures);
diff --git a/crates/chimera/src/phonetics/mandarin.rs b/crates/chimera/src/phonetics/mandarin.rs
index 92aa494..e6ecf49 100644
--- a/crates/chimera/src/phonetics/mandarin.rs
+++ b/crates/chimera/src/phonetics/mandarin.rs
@@ -228,6 +228,8 @@ fn final_parts(f: &str) -> Option<(&'static [&'static str], &'static str, &'stat
"eng" => (N, "ɤ", &["ŋ"]),
"ong" => (N, "ʊ", &["ŋ"]),
"ia" => (&["j"], "a", N),
+ // yo (哟 唷): an interjection's [jɔ]
+ "io" => (&["j"], "ɔ", N),
"ie" => (&["j"], "ɛ", N),
"iao" => (&["j"], "aʊ", N),
"iu" | "iou" => (&["j"], "əʊ", N),
@@ -470,12 +472,23 @@ fn valid_syllable(base: &str) -> bool {
(real(base) || erhua) && pinyin_syllable(&format!("{base}1"), "").is_some()
}
+/// Syllables often unstressed and toneless inside a word: particles and suffixes (de le me men zi
+/// tou ge ba ma ne), the negation and 一 in a verb pattern (bu yi), directional complements (lai qu
+/// shang xia guo), and words' second halves that are neutral (you huan xi shi hou fu mian bian li
+/// zhe). Written without a tone inside a toned word, they are neutral.
+const NEUTRAL_INSIDE: &[&str] = &[
+ "ba", "bian", "bu", "de", "fu", "ge", "guo", "hou", "huan", "lai", "le", "li", "ma", "me", "men", "mian", "ne", "qu",
+ "shang", "shi", "tou", "xi", "xia", "yi", "you", "zhe", "zi",
+];
+
/// A word → (spelling, numbered pinyin) per syllable; None if it carries no tone or isn't pinyin.
fn parse_pinyin(word: &str) -> Option<Vec<(String, String)>> {
// pieces end at a tone number or an apostrophe; each letter keeps its spelling and its mark
let mut pieces: Vec<(Vec<(char, char, u8)>, Option<u8>)> = vec![(Vec::new(), None)];
let mut toned = false;
- for c in word.chars().flat_map(char::to_lowercase) {
+ // each letter is read lowercased but keeps its spelling for the note's text (Xī'ān, not xī'ān)
+ for shown in word.chars() {
+ let c = shown.to_lowercase().next().unwrap_or(shown);
let last = pieces.last_mut().unwrap();
if let Some(d) = c.to_digit(10) {
if d > 5 || last.0.is_empty() {
@@ -487,10 +500,10 @@ fn parse_pinyin(word: &str) -> Option<Vec<(String, String)>> {
} else if c == '\'' {
pieces.push((Vec::new(), None));
} else if let Some((b, t)) = tone_mark(c) {
- last.0.push((c, b, t));
+ last.0.push((shown, b, t));
toned = true;
} else if c == 'ü' || c.is_ascii_lowercase() {
- last.0.push((c, if c == 'ü' { 'v' } else { c }, 0));
+ last.0.push((shown, if c == 'ü' { 'v' } else { c }, 0));
} else {
return None;
}
@@ -522,46 +535,58 @@ 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)
+ // a toned word starts with a written tone, and an unwritten one later is neutral: at the end
+ // (xièxie, dōngxi), or inside as one of the syllables that are often neutral (zěnmeyàng,
+ // háizimen, duìbuqǐ). 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");
+ let neutral_inside = |b: &str| NEUTRAL_INSIDE.contains(&b);
if !written[0].0 || written.iter().enumerate().any(|(i, (w, b))| !w && i > 0 && i < last && !neutral_inside(b)) {
return None;
}
Some(out)
}
-/// The longest valid syllable first, backing off when the rest can't be split.
+/// The longest valid syllable first, backing off when the rest can't be split. Positions the rest
+/// already failed from are remembered, so a long word that can't be split fails in linear time (it
+/// was exponential: a 30-letter typo took seconds, and Sing re-reads the lyrics on every keystroke).
fn split_syllables(base: &str) -> Option<Vec<usize>> {
- fn go(base: &str, at: usize, out: &mut Vec<usize>) -> bool {
+ fn go(base: &str, at: usize, out: &mut Vec<usize>, failed: &mut [bool]) -> bool {
if at == base.len() {
return true;
}
+ if failed[at] {
+ return false;
+ }
for end in (at + 1..=base.len().min(at + 6)).rev() {
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
+ // isn't po ké mo + n; and an erhua r ends a word (xīnr isn't xi + nr)
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()) {
+ let nasal = matches!(s.trim_end_matches('r'), "n" | "ng" | "m" | "hm" | "hng");
+ if nasal && !(at == 0 && end == base.len()) {
+ continue;
+ }
+ if s.len() > 1 && s != "er" && s.ends_with('r') && end != base.len() {
continue;
}
if valid_syllable(s) {
out.push(end);
- if go(base, end, out) {
+ if go(base, end, out, failed) {
return true;
}
out.pop();
}
}
+ failed[at] = true;
false
}
let mut out = Vec::new();
- go(base, 0, &mut out).then_some(out)
+ let mut failed = vec![false; base.len()];
+ go(base, 0, &mut out, &mut failed).then_some(out)
}
impl FrontEnd for Pinyin {
diff --git a/crates/chimera/tests/aspiration.rs b/crates/chimera/tests/aspiration.rs
index 912607b..9b16257 100644
--- a/crates/chimera/tests/aspiration.rs
+++ b/crates/chimera/tests/aspiration.rs
@@ -36,7 +36,7 @@ fn the_front_end_overrides_the_english_rule() {
#[test]
fn sung_onsets_keep_the_flag() {
let syl = |aspirated| Syllable { text: "pa".into(), onset: vec![Segment { aspirated, ..Segment::new("p") }], nucleus: Segment::new("a"), coda: vec![], melisma: None, word_end: true, phrase_end: false, ..Default::default() };
- let sing = |aspirated| aspiration(&plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: syl(aspirated) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0, ..Default::default() }).gestures);
+ let sing = |aspirated| aspiration(&plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: syl(aspirated) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0 }).gestures);
assert_eq!(sing(None), 0.36);
assert_eq!(sing(Some(false)), 0.22);
}
diff --git a/crates/chimera/tests/mandarin.rs b/crates/chimera/tests/mandarin.rs
index 899f61b..f29002a 100644
--- a/crates/chimera/tests/mandarin.rs
+++ b/crates/chimera/tests/mandarin.rs
@@ -79,7 +79,7 @@ fn typed(text: &str) -> Vec<(String, String, usize)> {
fn pinyin_with_tones_is_mandarin_and_without_is_english() {
let t = typed("nǐhǎo xièxie ni3 hao3 de5 Xī'ān nǚ");
let text: Vec<&str> = t.iter().map(|x| x.0.as_str()).collect();
- assert_eq!(text, ["nǐ", "hǎo", "xiè", "xie", "ni3", "hao3", "de5", "xī", "ān", "nǚ"]);
+ assert_eq!(text, ["nǐ", "hǎo", "xiè", "xie", "ni3", "hao3", "de5", "Xī", "ān", "nǚ"]); // capitals kept
let ipa: Vec<&str> = t.iter().map(|x| x.1.as_str()).collect();
assert_eq!(ipa, ["ni", "xaʊ", "ɕiɛ", "ɕiɛ", "ni", "xaʊ", "t˭ə", "ɕi", "ʔan", "ny"]);
// nǐhǎo is one word: third-tone sandhi sings nǐ rising (one bend); "ni3 hao3" are two words
@@ -103,13 +103,14 @@ fn accented_english_words_stay_english() {
// 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", "à"] {
+ 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", "à", "olé", "Renée"] {
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ú"] {
+ // review of #85: a neutral me, zi, you inside a word (zěnmeyàng, háizimen, péngyoumen)
+ 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ú", "zěnmeyàng", "shénmeshíhou", "háizimen", "péngyoumen", "zen3meyang4"] {
assert!(Pinyin.claims(w), "{w} not read as pinyin");
}
}
@@ -160,3 +161,41 @@ fn mandarin_timing_and_vowels() {
let n: Vec<String> = syls("风多头鸟").iter().map(|s| s.nucleus.ipa.clone()).collect();
assert_eq!(n, ["ɤ", "uɔ", "əʊ", "iaʊ"]);
}
+
+#[test]
+fn every_reading_in_the_lexicon_is_a_syllable_the_front_end_sings() {
+ // review of #85: 哟 唷 喲 (yo) didn't parse, so their note went missing
+ use chimera::phonetics::mandarin::pinyin_syllable;
+ use std::io::Read;
+ let path = format!("{}/../../public/data/mandarin.txt.gz", env!("CARGO_MANIFEST_DIR"));
+ let gz = std::fs::read(&path).unwrap();
+ let mut text = String::new();
+ flate2::read::GzDecoder::new(&gz[..]).read_to_string(&mut text).unwrap();
+ let mut bad = Vec::new();
+ let mut n = 0;
+ for line in text.lines() {
+ let (word, readings) = line.split_once('\t').unwrap();
+ for py in readings.split(' ') {
+ n += 1;
+ if pinyin_syllable(py, word).is_none() {
+ bad.push(format!("{word} {py}"));
+ }
+ }
+ }
+ assert!(n > 40_000, "{n} readings");
+ assert!(bad.is_empty(), "{} of {n} readings don't parse: {:?}", bad.len(), &bad[..bad.len().min(20)]);
+ assert!(pinyin_syllable("yo1", "哟").is_some());
+}
+
+#[test]
+fn a_long_word_that_cant_be_split_fails_fast() {
+ // review of #85: splitting backtracked exponentially ("xīnr" × 20 + "q", 81 letters, took 2 s)
+ let long = "xīnr".repeat(200) + "q";
+ let t = std::time::Instant::now();
+ assert!(!Pinyin.claims(&long));
+ assert!(!Pinyin.claims(&("anan".repeat(100) + "q")));
+ assert!(t.elapsed().as_millis() < 500, "{:?}", t.elapsed());
+ // and an erhua r only ends a word: xīnr is one syllable, not xi + nr
+ let texts: Vec<String> = typed("xīnr").into_iter().map(|x| x.0).collect();
+ assert_eq!(texts, ["xīnr"]);
+}
diff --git a/crates/chimera/tests/sing_fast.rs b/crates/chimera/tests/sing_fast.rs
index 4d56d54..8ead686 100644
--- a/crates/chimera/tests/sing_fast.rs
+++ b/crates/chimera/tests/sing_fast.rs
@@ -17,7 +17,7 @@ fn sing(lyrics: &str, beats: f64, bpm: f64) -> (Vec<SungNote>, Vec<f64>, Plan) {
let syl = lyrics_to_syllables(lyrics, &g2p());
let notes: Vec<SungNote> = syl.iter().enumerate().map(|(i, s)| SungNote { midi: if i % 2 == 0 { 60.0 } else { 64.0 }, beats, syl: s.clone() }).collect();
let times = (0..notes.len()).map(|i| 0.5 + i as f64 * beats * 60.0 / bpm).collect();
- let plan = plan_song(&notes, &SongOptions { body: "male".into(), bpm, t0: 0.5, vibrato: 0.0, ..Default::default() });
+ let plan = plan_song(&notes, &SongOptions { body: "male".into(), bpm, t0: 0.5, vibrato: 0.0 });
(notes, times, plan)
}
@@ -84,7 +84,7 @@ fn a_delayed_cluster_closure_stays_inside_a_short_sung_stop() {
g.load_dict("harped\tHH AA1 R P T\nah\tAA1\n");
let syl = lyrics_to_syllables("harped ah harped ah", &g);
let notes: Vec<SungNote> = syl.iter().map(|s| SungNote { midi: 60.0, beats: 0.25, syl: s.clone() }).collect();
- let plan = plan_song(&notes, &SongOptions { body: "male".into(), bpm: 180.0, t0: 0.5, vibrato: 0.0, ..Default::default() });
+ let plan = plan_song(&notes, &SongOptions { body: "male".into(), bpm: 180.0, t0: 0.5, vibrato: 0.0 });
let ts: Vec<_> = plan.segments.iter().enumerate().filter(|(i, s)| s.ipa == "t" && *i > 0 && plan.segments[i - 1].ipa == "p").map(|(_, s)| s.clone()).collect();
assert!(!ts.is_empty());
for t in ts {
diff --git a/crates/chimera/tests/sound_marks.rs b/crates/chimera/tests/sound_marks.rs
index ada9ac5..e7938ac 100644
--- a/crates/chimera/tests/sound_marks.rs
+++ b/crates/chimera/tests/sound_marks.rs
@@ -97,7 +97,7 @@ fn syl(onset: Vec<Segment>, nucleus: Segment) -> Syllable {
#[test]
fn a_sung_vowel_keeps_its_nasalization() {
let nucleus = |n: Option<bool>| Segment { nasalized: n, ..Segment::new("ɛ") };
- let sung = |n| plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: syl(vec![Segment::new("p")], nucleus(n)) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0, ..Default::default() });
+ let sung = |n| plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: syl(vec![Segment::new("p")], nucleus(n)) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0 });
assert_eq!(labelled(&sung(Some(true)).gestures, "velum").len(), 1);
assert!(labelled(&sung(None).gestures, "velum").is_empty());
// a live note
@@ -106,7 +106,7 @@ fn a_sung_vowel_keeps_its_nasalization() {
assert!(labelled(&live(None), "velum").is_empty());
// a nasalized diphthong, sung: each half is a vowel of its own
let diph = Segment { nasalized: Some(true), ..Segment::new("aɪ") };
- let p = plan_song(&[SungNote { midi: 57.0, beats: 2.0, syl: syl(vec![], diph) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0, ..Default::default() });
+ let p = plan_song(&[SungNote { midi: 57.0, beats: 2.0, syl: syl(vec![], diph) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0 });
assert_eq!(labelled(&p.gestures, "velum").len(), 2);
}
@@ -269,7 +269,7 @@ fn a_breathy_vowel_parts_the_folds_for_the_whole_vowel() {
#[test]
fn sung_syllables_keep_their_breathiness() {
- let song = |onset: Vec<Segment>, nucleus: Segment| plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: syl(onset, nucleus) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0, ..Default::default() });
+ let song = |onset: Vec<Segment>, nucleus: Segment| plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: syl(onset, nucleus) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0 });
let live = |onset: Vec<Segment>, nucleus: Segment| plan_note_on(&syl(onset, nucleus), 57.0, &NoteOnOptions { body: "male".into(), vibrato: 0.0, tag: 1.0, legato_from: None });
let (b, b_soft) = (Segment::new("b"), Segment { breathy: Some(true), ..Segment::new("b") });
let (a, a_soft) = (Segment::new("a"), Segment { breathy: Some(true), ..Segment::new("a") });
@@ -284,7 +284,7 @@ fn sung_syllables_keep_their_breathiness() {
#[test]
fn a_sung_consonant_keeps_its_palatalization() {
let onset = |soft| vec![Segment { palatalized: soft, ..Segment::new("t") }];
- let sung = |s| plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: syl(onset(s), Segment::new("a")) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0, ..Default::default() });
+ let sung = |s| plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: syl(onset(s), Segment::new("a")) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0 });
assert_eq!(labelled(&sung(Some(true)).gestures, "palatalized").len(), 1);
assert!(labelled(&sung(None).gestures, "palatalized").is_empty());
let live = |s| plan_note_on(&syl(onset(s), Segment::new("a")), 57.0, &NoteOnOptions { body: "male".into(), vibrato: 0.0, tag: 1.0, legato_from: None });
@@ -292,6 +292,6 @@ fn a_sung_consonant_keeps_its_palatalization() {
assert!(labelled(&live(None), "palatalized").is_empty());
// a coda too
let coda = |s| Syllable { coda: onset(s), ..syl(vec![], Segment::new("a")) };
- let p = plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: coda(Some(true)) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0, ..Default::default() });
+ let p = plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: coda(Some(true)) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0 });
assert_eq!(labelled(&p.gestures, "palatalized").len(), 1);
}
diff --git a/public/data/mandarin.txt.gz b/public/data/mandarin.txt.gz
index 40bbd1c..f32bcaf 100644
Binary files a/public/data/mandarin.txt.gz and b/public/data/mandarin.txt.gz differ
diff --git a/tools/build-mandarin.ts b/tools/build-mandarin.ts
index 49a15a4..ec55e40 100644
--- a/tools/build-mandarin.ts
+++ b/tools/build-mandarin.ts
@@ -1,8 +1,8 @@
/**
* Build the Mandarin front end's lexicon shipped to the browser (and read by the CLI).
* Usage: bun tools/build-mandarin.ts (downloads the pinned sources below)
- * Output: public/data/mandarin.txt.gz, lines "字<TAB>zhong1" (each Han character's most common
- * reading) and "银行<TAB>yin2 hang2" (phrases whose reading differs from their characters' own,
+ * Output: public/data/mandarin.txt.gz, lines "字<TAB>zhong1" (each Han character's first listed
+ * reading, Unihan's order: usually the most common, not always, e.g. 得 de2, 长 zhang3) and "银行<TAB>yin2 hang2" (phrases whose reading differs from their characters' own,
* which is what decides a polyphone, and every phrase with 儿, which says whether 儿 is a syllable
* or an erhua ending), tone numbers 1-4 and 5 for neutral, ü as v.
*
@@ -49,13 +49,16 @@ function numbered(syl: string): string | null {
const isHan = (c: string) => /^[㐀-䶿一-鿿豈-﫿]$/u.test(c);
-// characters: "U+4E2D: zhōng,zhòng # 中" → the first (most common) reading
+/** One syllable: one run of vowels (a character read as two, 瓲 tunwa "ton-watt", can't be one note). */
+const oneSyllable = (numberedSyl: string) => (numberedSyl.match(/[aeiouv]+/g) ?? []).length <= 1;
+
+// characters: "U+4E2D: zhōng,zhòng # 中" → the first listed reading that is one syllable
const chars = new Map<string, string>();
for (const line of (await get(`${CHARS}/pinyin.txt`)).split("\n")) {
const m = line.match(/^U\+([0-9A-F]+):\s*([^#]+)/);
if (!m) continue;
const c = String.fromCodePoint(parseInt(m[1], 16));
- const first = numbered(m[2].split(",")[0].trim());
+ const first = m[2].split(",").map((r) => numbered(r.trim())).find((r) => r && oneSyllable(r));
if (isHan(c) && first) chars.set(c, first);
}