Skip to content

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

Rust

Mandarin front end: sing Chinese lyrics (Han characters) and pinyin with tones, with tones as pitch bends

Joshua Phamb3a82b97935c
diff --git a/crates/chimera-cli/src/main.rs b/crates/chimera-cli/src/main.rs
index ed5cf80..9f7b958 100644
--- a/crates/chimera-cli/src/main.rs
+++ b/crates/chimera-cli/src/main.rs
@@ -113,10 +113,7 @@ fn run(args: Vec<String>) -> Result<(), String> {
["compare", "csd", ..] => compare::csd(&ctx, &args[2..]),
["compare", "tsp", ..] => compare::tsp::run(&ctx, &args[2..]),
["diagnose", ..] => diagnose::run(&ctx, &args[1..]),
- ["syllables", text] => render::g2p()
- .map(|g| chimera::phonetics::syllables::lyrics_to_syllables(text, &g))
- .and_then(|s| serde_json::to_string(&s).map_err(|e| e.to_string()))
- .map(|j| println!("{j}")),
+ ["syllables", text] => render::sung_lyrics(text).and_then(|s| serde_json::to_string(&s).map_err(|e| e.to_string())).map(|j| println!("{j}")),
["calibrate", "vowels", ..] => calibrate::vowels(&args[2..]),
["calibrate", "consonants", ..] => calibrate::consonants(&args[2..]),
["help" | "--help" | "-h", ..] => {
diff --git a/crates/chimera-cli/src/render.rs b/crates/chimera-cli/src/render.rs
index d9dc4c1..5816756 100644
--- a/crates/chimera-cli/src/render.rs
+++ b/crates/chimera-cli/src/render.rs
@@ -22,7 +22,8 @@ use chimera::phonetics::sing::{
plan_song,
};
use chimera::phonetics::songs::DEMO_SONGS;
-use chimera::phonetics::syllables::lyrics_to_syllables;
+use chimera::phonetics::mandarin::{MandarinLexicon, is_han};
+use chimera::phonetics::syllables::{lyrics_to_syllables, lyrics_to_syllables_with};
use chimera::phonetics::{Intonation, Plan, Syllable};
use chimera::voice::human_voice::{HumanVoice, SCOPE_POINTS, SourcePatch, VoiceTelemetry};
use std::io::Read;
@@ -48,6 +49,24 @@ pub fn g2p() -> Result<EnglishG2P, String> {
Ok(g)
}
+/// The Mandarin front end's lexicon (public/data/mandarin.txt.gz, from tools/build-mandarin.ts).
+pub fn zh() -> Result<MandarinLexicon, String> {
+ let path = repo_path("public/data/mandarin.txt.gz");
+ let gz = std::fs::read(&path).map_err(|e| format!("{path}: {e}"))?;
+ let mut text = String::new();
+ flate2::read::GzDecoder::new(&gz[..]).read_to_string(&mut text).map_err(|e| format!("{path}: {e}"))?;
+ let mut l = MandarinLexicon::new();
+ l.load(&text);
+ Ok(l)
+}
+
+/// Lyrics → syllables through every built-in front end (the Mandarin lexicon only when needed).
+pub fn sung_lyrics(text: &str) -> Result<Vec<Syllable>, String> {
+ let g = g2p()?;
+ let lex = if text.chars().any(is_han) { zh()? } else { MandarinLexicon::new() };
+ Ok(lyrics_to_syllables_with(text, &g, &lex))
+}
+
/// A file name from a song's name: letters of any script, everything else as one "-".
/// (Only a-z counted, so "Ночной ветер" was written to "--male.wav".)
fn slug(name: &str) -> String {
@@ -501,8 +520,9 @@ fn render_tracked(v: &mut HumanVoice, out: &mut [f32], artic: bool, tele: bool)
/// writes the articulators over time (`{"rate", "body", "keys", "frames"}`), to animate a face in
/// sync; `--tele` writes the voice's whole telemetry over time (see `TeleRecorder`), which the
/// app's duet page replays on a 3D head. The melody file may give `"syllables"` (IPA
-/// onset/nucleus/coda per sounding note) instead of English `"lyrics"`: a language front end's
-/// output (docs/language-front-ends.md).
+/// onset/nucleus/coda per sounding note, optional `"pitch"` bends) instead of `"lyrics"`: a
+/// language front end's output (docs/language-front-ends.md). Optional sing-planner settings:
+/// `"nasalLead"`, `"consonantScale"`.
pub fn notes(ctx: &Ctx, a: &[String]) -> Result<(), String> {
let mut artic_out: Option<String> = None;
let mut tele_out: Option<String> = None;
@@ -532,8 +552,7 @@ pub fn notes(ctx: &Ctx, a: &[String]) -> Result<(), String> {
let syl: Vec<Syllable> = if j.get("syllables").is_some() {
serde_json::from_value(j["syllables"].clone()).map_err(|e| format!("syllables: {e}"))?
} else {
- let g = g2p()?;
- lyrics_to_syllables(j["lyrics"].as_str().ok_or("lyrics missing")?, &g)
+ sung_lyrics(j["lyrics"].as_str().ok_or("lyrics missing")?)?
};
let sounding = raw.iter().filter(|n| n[0] > 0.0).count();
if syl.len() != sounding {
diff --git a/crates/chimera-cli/tests/cli.rs b/crates/chimera-cli/tests/cli.rs
index 141732a..77a1157 100644
--- a/crates/chimera-cli/tests/cli.rs
+++ b/crates/chimera-cli/tests/cli.rs
@@ -418,6 +418,15 @@ fn the_cli_reads_russian_lyrics() {
assert!(stdout.contains("3 notes"), "{stdout}");
}
+#[test]
+fn render_notes_reads_chinese_lyrics_through_the_mandarin_front_end() {
+ // the bundled lexicon (public/data/mandarin.txt.gz): one note per character, 银行 as yin2 hang2
+ let melody = tmp("melody-zh.json");
+ std::fs::write(&melody, r#"{"bpm": 120, "t0": 0, "lyrics": "我爱银行,你好", "notes": [[60,1],[62,1],[64,1],[65,1],[64,1],[62,2]]}"#).unwrap();
+ let stdout = chimera(&["render", "notes", &melody, &tmp("notes-zh"), "male"]);
+ assert!(stdout.contains("6 notes"), "{stdout}");
+}
+
#[test]
fn render_notes_tele_records_the_live_telemetry_without_changing_the_sound() {
let melody = tmp("tele-melody.json");
diff --git a/crates/chimera-wasm/src/api.rs b/crates/chimera-wasm/src/api.rs
index fbb9219..c109176 100644
--- a/crates/chimera-wasm/src/api.rs
+++ b/crates/chimera-wasm/src/api.rs
@@ -12,7 +12,9 @@ use chimera::phonetics::beatbox::{self, BeatStep};
use chimera::phonetics::planner::{self, PhraseInput, PlanOptions};
use chimera::phonetics::sing::{self, MelismaOptions, NoteOnOptions, SongOptions, SungNote};
use chimera::phonetics::english::EnglishG2P;
-use chimera::phonetics::{Segment, Syllable, ipa, songs, syllables, vowel_data};
+use chimera::phonetics::mandarin::MandarinLexicon;
+use chimera::phonetics::syllables::lyrics_to_syllables_with;
+use chimera::phonetics::{Segment, Syllable, ipa, songs, vowel_data};
use chimera::voice::human_airway::HumanAirway;
use serde_json::{Value, json};
use std::cell::RefCell;
@@ -33,6 +35,8 @@ struct State {
next_model: usize,
/// the page's English G2P (one dictionary, loaded once)
g2p: EnglishG2P,
+ /// the Mandarin front end's lexicon (loaded once, when lyrics first need it)
+ mandarin: MandarinLexicon,
}
thread_local! {
@@ -126,7 +130,12 @@ fn dispatch(st: &mut State, req: &Value) -> Res {
}
"g2pPhrases" => to_json(&st.g2p.to_phrases(&arg::<String>(req, "text")?)),
"g2pWord" => to_json(&st.g2p.word(&arg::<String>(req, "word")?, arg::<Option<bool>>(req, "reduce")?.unwrap_or(true))),
- "lyricsToSyllables" => to_json(&syllables::lyrics_to_syllables(&arg::<String>(req, "text")?, &st.g2p)),
+ "zhLoad" => {
+ st.mandarin.load(&arg::<String>(req, "text")?);
+ Ok(json!(true))
+ }
+ // every built-in front end: pinyin, English, Korean, and Mandarin once its lexicon is loaded
+ "lyricsToSyllables" => to_json(&lyrics_to_syllables_with(&arg::<String>(req, "text")?, &st.g2p, &st.mandarin)),
// ---------------------------------------------------------------- creatures
"creaturePreview" => {
let id: String = arg(req, "id")?;
diff --git a/crates/chimera/src/phonetics/mandarin.rs b/crates/chimera/src/phonetics/mandarin.rs
new file mode 100644
index 0000000..696dc3c
--- /dev/null
+++ b/crates/chimera/src/phonetics/mandarin.rs
@@ -0,0 +1,566 @@
+//! The Mandarin front end: Han characters → sung syllables, one per character, so a character maps
+//! to one note and keeps its spelling as the note's text.
+//!
+//! - Readings come from a lexicon (`public/data/mandarin.txt.gz`, built by tools/build-mandarin.ts
+//! from MIT pinyin data): each character's most common reading, and the phrases whose reading
+//! differs from their characters' own. A run of characters is read by longest phrase match,
+//! which decides most polyphones (银行 yin2 hang2, 行走 xing2 zou3).
+//! - Tone sandhi inside the run: 不 before a fourth tone is second (不会 bu2 hui4); 一 before a
+//! fourth tone is second and before the others fourth; a run of third tones keeps the last and
+//! turns the others second (你好 ni2 hao3).
+//! - Pinyin → IPA on the inventory. Stops and affricates say their aspiration, which is what
+//! Mandarin contrasts: b d g z zh j are unaspirated (p˭ t˭ k˭ ts˭ tʂ˭ tɕ˭), p t k c ch q aspirated.
+//! - Tones → pitch bends ([`tone_bends`]): the melody stays as written, the tone colours the
+//! note's start or end.
+//!
+//! [`Pinyin`] reads Mandarin typed as pinyin instead, with no lexicon: a Latin word that carries
+//! tones (marks, "nǐhǎo", or numbers, "ni3 hao3") and parses as pinyin. Toneless words stay
+//! English.
+
+use super::syllables::FrontEnd;
+use super::{Bend, Edge, Segment, Syllable};
+use std::collections::HashMap;
+
+pub fn is_han(c: char) -> bool {
+ matches!(c, '\u{3400}'..='\u{4DBF}' | '\u{4E00}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}')
+}
+
+/// Readings: each character's most common, and the phrases that read otherwise.
+#[derive(Default)]
+pub struct MandarinLexicon {
+ chars: HashMap<char, String>,
+ phrases: HashMap<String, Vec<String>>,
+ longest: usize,
+}
+
+impl MandarinLexicon {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Load "字<TAB>zhong1" and "银行<TAB>yin2 hang2" lines (later lines win).
+ pub fn load(&mut self, text: &str) {
+ for line in text.lines() {
+ let Some((w, py)) = line.split_once('\t') else { continue };
+ let syls: Vec<String> = py.split(' ').filter(|s| !s.is_empty()).map(str::to_string).collect();
+ let chars: Vec<char> = w.chars().collect();
+ if chars.len() == 1 && syls.len() == 1 {
+ self.chars.insert(chars[0], syls[0].clone());
+ } else if chars.len() == syls.len() && chars.len() > 1 {
+ self.longest = self.longest.max(chars.len());
+ self.phrases.insert(w.to_string(), syls);
+ }
+ }
+ }
+
+ pub fn is_loaded(&self) -> bool {
+ !self.chars.is_empty()
+ }
+
+ /// A run of Han characters → one numbered pinyin syllable per character ("" where unknown),
+ /// by longest phrase match, then tone sandhi.
+ pub fn read(&self, run: &str) -> Vec<String> {
+ self.read_with_source(run).into_iter().map(|(p, _)| p).collect()
+ }
+
+ /// [`read`](Self::read), with whether each reading came from a phrase (rather than the
+ /// character's own most common reading).
+ fn read_with_source(&self, run: &str) -> Vec<(String, bool)> {
+ let cs: Vec<char> = run.chars().collect();
+ let mut out: Vec<String> = Vec::with_capacity(cs.len());
+ let mut from_phrase: Vec<bool> = Vec::with_capacity(cs.len());
+ let mut i = 0;
+ while i < cs.len() {
+ let mut took = false;
+ for n in (2..=self.longest.min(cs.len() - i)).rev() {
+ let w: String = cs[i..i + n].iter().collect();
+ if let Some(syls) = self.phrases.get(&w) {
+ out.extend(syls.iter().cloned());
+ from_phrase.extend(std::iter::repeat_n(true, n));
+ i += n;
+ took = true;
+ break;
+ }
+ }
+ if !took {
+ out.push(self.chars.get(&cs[i]).cloned().unwrap_or_default());
+ from_phrase.push(false);
+ i += 1;
+ }
+ }
+ sandhi(&cs, &mut out);
+ out.into_iter().zip(from_phrase).collect()
+ }
+}
+
+fn tone(py: &str) -> u8 {
+ py.chars().last().and_then(|c| c.to_digit(10)).map_or(5, |d| d as u8)
+}
+fn set_tone(py: &mut String, t: u8) {
+ if py.ends_with(|c: char| c.is_ascii_digit()) {
+ py.pop();
+ py.push(char::from(b'0' + t));
+ }
+}
+
+fn sandhi(cs: &[char], py: &mut [String]) {
+ let n = py.len();
+ // 不 and 一 by the character: pinyin alone can't tell 不 bu4 from 部 bu4
+ for i in 0..n {
+ let next = if i + 1 < n { Some(tone(&py[i + 1])) } else { None };
+ match (cs[i], next) {
+ ('不', Some(4)) => set_tone(&mut py[i], 2),
+ ('一', Some(4)) => set_tone(&mut py[i], 2),
+ ('一', Some(1..=3)) => set_tone(&mut py[i], 4),
+ _ => {}
+ }
+ }
+ third_tones(py);
+}
+
+/// A run of third tones: all but the last become second (你好 ni2 hao3).
+fn third_tones(py: &mut [String]) {
+ let n = py.len();
+ let mut i = 0;
+ while i < n {
+ let mut j = i;
+ while j < n && tone(&py[j]) == 3 && !py[j].is_empty() {
+ j += 1;
+ }
+ for k in i..j.saturating_sub(1) {
+ set_tone(&mut py[k], 2);
+ }
+ i = j.max(i + 1);
+ }
+}
+
+/// How a Mandarin tone bends its sung note (semitones from the note; see [`Bend`]): 2 scoops up
+/// from below, 3 dips, 4 starts a little high and falls off the end, 1 and 5 stay on the note.
+pub fn tone_bends(tone: u8) -> Vec<Bend> {
+ let b = |at, len, max, st| Bend { at, len, max, st };
+ match tone {
+ 2 => vec![b(Edge::Start, 0.45, 0.25, -3.5)],
+ // sung low from the start: a dip in the middle (Edge::Middle), or a dip then a rise (214),
+ // measured no better on the poems (tone 3 ~50% wrong either way, mostly heard as 4)
+ 3 => vec![b(Edge::Start, 0.55, 0.3, -4.0)],
+ 4 => vec![b(Edge::Start, 0.25, 0.12, 1.5), b(Edge::End, 0.4, 0.2, -4.0)],
+ _ => vec![],
+ }
+}
+
+
+/// Fraction of a vowel nasalised before -n/-ng.
+const NASAL_LEAD: f64 = 0.4;
+
+/// Mandarin's sung timing: nasal codas held long enough to tell -n from -ng (the place cue is in
+/// the vowel's last formant movement and the murmur; at the default ~60 ms they read as one).
+fn coda_dur(ipa: &str) -> Option<f64> {
+ match ipa {
+ "ŋ" => Some(0.13),
+ "n" => Some(0.10),
+ _ => None,
+ }
+}
+
+/// Mandarin's sung onset timing, where the defaults blurred contrasts: an unaspirated affricate's
+/// frication short (j heard as q), nasal onsets long enough to hear (n heard as y), f long enough
+/// to tell from sh.
+fn onset_dur(ipa: &str, aspirated: Option<bool>) -> Option<f64> {
+ match (ipa, aspirated) {
+ ("tɕ" | "tʂ" | "ts", Some(false)) => Some(0.08),
+ ("n" | "m", _) => Some(0.09),
+ ("f", _) => Some(0.13),
+ _ => None,
+ }
+}
+
+/// Aspiration length of Mandarin's aspirated stops and affricates (s).
+const MANDARIN_VOT: f64 = 0.09;
+/// The share of a falling diphthong's note its off-glide takes.
+const OFFGLIDE: f64 = 0.35;
+
+/// An initial → its sound and, for stops and affricates, its aspiration.
+fn initial(i: &str) -> Option<(&'static str, Option<bool>)> {
+ Some(match i {
+ "b" => ("p", Some(false)),
+ "p" => ("p", Some(true)),
+ "m" => ("m", None),
+ "f" => ("f", None),
+ "d" => ("t", Some(false)),
+ "t" => ("t", Some(true)),
+ "n" => ("n", None),
+ "l" => ("l", None),
+ "g" => ("k", Some(false)),
+ "k" => ("k", Some(true)),
+ "h" => ("x", None),
+ "j" => ("tɕ", Some(false)),
+ "q" => ("tɕ", Some(true)),
+ "x" => ("ɕ", None),
+ "zh" => ("tʂ", Some(false)),
+ "ch" => ("tʂ", Some(true)),
+ "sh" => ("ʂ", None),
+ "r" => ("ɻ", None),
+ "z" => ("ts", Some(false)),
+ "c" => ("ts", Some(true)),
+ "s" => ("s", None),
+ _ => return None,
+ })
+}
+
+/// A final (after its initial, with y/w spellings undone) → glide, nucleus, coda.
+fn final_parts(f: &str) -> Option<(&'static [&'static str], &'static str, &'static [&'static str])> {
+ const N: &[&str] = &[];
+ Some(match f {
+ "a" => (N, "a", N),
+ "o" => (&["w"], "ɔ", N),
+ "e" => (N, "ɤ", N),
+ "i" => (N, "i", N),
+ "u" => (N, "u", N),
+ "v" => (N, "y", N),
+ "er" => (N, "ɝ", N),
+ "ai" => (N, "aɪ", N),
+ "ei" => (N, "eɪ", N),
+ "ao" => (N, "aʊ", N),
+ "ou" => (N, "əʊ", N),
+ "an" => (N, "a", &["n"]),
+ "en" => (N, "ə", &["n"]),
+ "ang" => (N, "ɑ", &["ŋ"]),
+ "eng" => (N, "ɤ", &["ŋ"]),
+ "ong" => (N, "ʊ", &["ŋ"]),
+ "ia" => (&["j"], "a", N),
+ "ie" => (&["j"], "ɛ", N),
+ "iao" => (&["j"], "aʊ", N),
+ "iu" | "iou" => (&["j"], "əʊ", N),
+ "ian" => (&["j"], "ɛ", &["n"]),
+ "in" => (N, "i", &["n"]),
+ "iang" => (&["j"], "ɑ", &["ŋ"]),
+ "ing" => (N, "i", &["ŋ"]),
+ "iong" => (&["j"], "ʊ", &["ŋ"]),
+ "ua" => (&["w"], "a", N),
+ "uo" => (&["w"], "ɔ", N),
+ "uai" => (&["w"], "aɪ", N),
+ "ui" | "uei" => (&["w"], "eɪ", N),
+ "uan" => (&["w"], "a", &["n"]),
+ "un" | "uen" => (&["w"], "ə", &["n"]),
+ "uang" => (&["w"], "ɑ", &["ŋ"]),
+ "ueng" => (&["w"], "ə", &["ŋ"]),
+ "ve" | "ue" => (&["ɥ"], "ɛ", N),
+ "van" => (&["ɥ"], "ɛ", &["n"]),
+ "vn" => (N, "y", &["n"]),
+ // syllabic nasals (嗯 n, ng, m)
+ "n" | "ng" | "m" | "hm" | "hng" => (N, "ə", &["n"]),
+ _ => return None,
+ })
+}
+
+/// One numbered pinyin syllable ("zhong1") → a sung syllable with its spelling `text`; None when
+/// it isn't pinyin.
+pub fn pinyin_syllable(py: &str, text: &str) -> Option<Syllable> {
+ let t = tone(py);
+ let body = py.trim_end_matches(|c: char| c.is_ascii_digit());
+ // erhua spelled in pinyin: a trailing r on any syllable but er itself (nǎr, diǎnr)
+ if body.len() > 1 && body.ends_with('r') && body != "er" {
+ let mut s = pinyin_syllable(&format!("{}{t}", &body[..body.len() - 1]), text)?;
+ rhotacize(&mut s);
+ return Some(s);
+ }
+ let ini = ["zh", "ch", "sh"].into_iter().find(|i| body.starts_with(i)).or_else(|| {
+ let c = &body[..body.chars().next()?.len_utf8()];
+ (initial(c).is_some() || c == "y" || c == "w").then_some(c)
+ });
+ let (ini, mut fin) = match ini {
+ Some(i) if body.len() > i.len() => (i, body[i.len()..].to_string()),
+ _ => ("", body.to_string()),
+ };
+ // spellings: y/w stand for glides; u after j q x (and y) is ü
+ match ini {
+ "y" => {
+ fin = match fin.as_str() {
+ "i" | "in" | "ing" => fin,
+ f if f.starts_with('u') => format!("v{}", &f[1..]),
+ f if f.starts_with('i') => f.to_string(),
+ f => format!("i{f}"),
+ }
+ }
+ "w" => {
+ fin = match fin.as_str() {
+ "u" => fin,
+ "o" => "uo".into(),
+ f => format!("u{f}"),
+ }
+ }
+ "j" | "q" | "x" if fin.starts_with('u') => fin = format!("v{}", &fin[1..]),
+ _ => {}
+ }
+ let apical = matches!(ini, "z" | "c" | "s" | "zh" | "ch" | "sh" | "r") && fin == "i";
+ // the apical vowels: the consonant's tongue held open (ɿ after z c s, ʅ after zh ch sh r)
+ let apical_vowel = if matches!(ini, "z" | "c" | "s") { "ɿ" } else { "ʅ" };
+ let (glide, mut nucleus, coda) = if apical { (&[][..], apical_vowel, &[][..]) } else { final_parts(&fin)? };
+ // a neutral-tone syllable's e reduces (的 de, 了 le)
+ if t == 5 && nucleus == "ɤ" {
+ nucleus = "ə";
+ }
+ // a medial glide belongs to the rhyme: glide + vowel as one rising diphthong, sung on the beat
+ let mut glide = glide;
+ let rising = match (glide, nucleus) {
+ (["j"], "a") => Some("ia"),
+ (["j"], "ɛ") => Some("iɛ"),
+ (["j"], "ɑ") => Some("iɑ"),
+ (["j"], "ʊ") => Some("iʊ"),
+ (["w"], "a") => Some("ua"),
+ (["w"], "ɔ") => Some("uɔ"),
+ (["w"], "ɑ") => Some("uɑ"),
+ (["w"], "ə") => Some("uə"),
+ (["ɥ"], "ɛ") => Some("yɛ"),
+ // the three-vowel finals: the glide into a falling diphthong (iao, iou, uai, uei)
+ (["j"], "aʊ") => Some("iaʊ"),
+ (["j"], "əʊ") => Some("iəʊ"),
+ (["w"], "aɪ") => Some("uaɪ"),
+ (["w"], "eɪ") => Some("ueɪ"),
+ _ => None,
+ };
+ if let Some(r) = rising {
+ nucleus = r;
+ glide = &[];
+ }
+ let mut onset: Vec<Segment> = Vec::new();
+ // a syllable spelled with no initial (爱 ài, 安 ān, 饿 è; not y-/w-) starts with a soft glottal
+ // catch, which keeps it from running into the vowel before
+ if ini.is_empty() && !matches!(fin.as_str(), "n" | "ng" | "m" | "hm" | "hng") {
+ onset.push(Segment::new("ʔ"));
+ }
+ if let Some((ipa, aspirated)) = initial(ini) {
+ // Mandarin's aspirated stops and affricates aspirate for ~80-100 ms, longer than English's
+ let vot = (aspirated == Some(true)).then_some(MANDARIN_VOT);
+ onset.push(Segment { aspirated, vot, dur: onset_dur(ipa, aspirated), ..Segment::new(ipa) });
+ }
+ onset.extend(glide.iter().map(|g| Segment::new(g)));
+ Some(Syllable {
+ text: text.to_string(),
+ onset,
+ nucleus: Segment::new(nucleus),
+ coda: coda.iter().map(|c| Segment { dur: coda_dur(c), ..Segment::new(c) }).collect(),
+ pitch: tone_bends(t),
+ // vowels before -n/-ng are nasalised. (Lighter neutral tones, breath 0.7 on 的 了, sounded
+ // more natural but made them harder to recognise in the scramble test, so they stay full.)
+ nasal_lead: (!coda.is_empty()).then_some(NASAL_LEAD),
+ // ai ao ei ou (and iao iou uai uei) glide off over the note's last 35%: at the planner's
+ // 20% the glide was too short to hear on a long note
+ offglide: super::planner::offglide(nucleus).is_some().then_some(OFFGLIDE),
+ ..Default::default()
+ })
+}
+
+/// 儿 after these is always erhua (哪儿 nǎr, 这儿, 那儿), whatever the lexicon says.
+const ERHUA_AFTER: &str = "哪这那";
+/// 儿 after these is its own syllable (女儿 nǚ'ér, 婴儿, 孤儿, 托儿所): words for people.
+const ER_SYLLABLE_AFTER: &str = "女婴孤幼男健宠胎孙侄托";
+
+/// Erhua: the syllable ends rhotic instead (一点儿 diǎnr, 哪儿 nǎr). A nasal coda gives way to
+/// the r, and a falling diphthong keeps its first vowel (块儿 kuàir → [kʰwaɻ]).
+fn rhotacize(s: &mut Syllable) {
+ // the off-glide gives way to the r: aɪ → a, uaɪ → ua (a rising nucleus keeps its on-glide)
+ let nuc = s.nucleus.ipa.clone();
+ if super::planner::offglide(&nuc).is_some() {
+ let held = super::planner::held_vowel(&nuc);
+ let rising = super::planner::onglide(&nuc).map(|g| format!("{g}{held}"));
+ match rising {
+ // glide + vowel as a rising diphthong the planner knows (uai → ua)
+ Some(r) if super::planner::is_rising(&r) => s.nucleus = Segment::new(&r),
+ // otherwise the glide goes back to the onset (uei → w + e)
+ Some(_) => {
+ let g = super::planner::onglide(&nuc).unwrap();
+ s.onset.push(Segment::new(match g { "i" => "j", "y" => "ɥ", _ => "w" }));
+ s.nucleus = Segment::new(held);
+ }
+ None => s.nucleus = Segment::new(held),
+ }
+ }
+ s.coda = vec![Segment::new("ɻ")];
+ s.nasal_lead = None;
+ s.offglide = None;
+}
+
+/// The Mandarin front end, over a loaded lexicon (without one it reads nothing).
+pub struct Mandarin<'a>(pub &'a MandarinLexicon);
+
+impl FrontEnd for Mandarin<'_> {
+ fn starts(&self, c: char) -> bool {
+ is_han(c)
+ }
+ fn word(&self, run: &str) -> Vec<Syllable> {
+ let cs: Vec<char> = run.chars().collect();
+ let mut out: Vec<Syllable> = Vec::new();
+ for (i, ((py, phrase), c)) in self.0.read_with_source(run).iter().zip(&cs).enumerate() {
+ // erhua: 儿 after another syllable is its rhotic ending (一会儿 er5, 块儿, 哪儿), unless it's
+ // a word's own syllable (女儿, 婴儿, or a phrase reading it with a tone): lyrics' 儿 is
+ // mostly erhua. The data marks 哪儿/这儿/那儿 toned and lacks 婴儿-type words, hence the lists.
+ let prev = if i > 0 { Some(cs[i - 1]) } else { None };
+ let erhua = *c == '儿'
+ && prev.is_some_and(|p| ERHUA_AFTER.contains(p) || (!ER_SYLLABLE_AFTER.contains(p) && (py == "er5" || !phrase)));
+ if erhua {
+ if let Some(prev) = out.last_mut() {
+ rhotacize(prev);
+ prev.text.push('儿');
+ continue;
+ }
+ }
+ out.extend(pinyin_syllable(py, &c.to_string()));
+ }
+ out
+ }
+}
+
+/// Mandarin typed as pinyin: a Latin word that carries tones, as marks ("nǐhǎo", "xièxie") or numbers
+/// ("ni3", "hao3", "de5"), and parses fully as pinyin. Syllables split at numbers and apostrophes
+/// ("xi'an"), otherwise by the longest valid syllable; an unmarked syllable in a marked word is
+/// neutral ("xièxie" xie4 xie5). Third-tone sandhi applies inside a word; 不 and 一 are written with
+/// the tone they're sung with (bú, yí), since pinyin alone can't tell 不 from 部. A word without tones
+/// isn't claimed, so English reads it.
+pub struct Pinyin;
+
+/// A tone-marked vowel → (its letter, the tone).
+fn tone_mark(c: char) -> Option<(char, u8)> {
+ const MARKS: [(&str, char); 6] = [("āáǎà", 'a'), ("ēéěè", 'e'), ("īíǐì", 'i'), ("ōóǒò", 'o'), ("ūúǔù", 'u'), ("ǖǘǚǜ", 'v')];
+ MARKS.iter().find_map(|(m, b)| m.chars().position(|x| x == c).map(|k| (*b, k as u8 + 1)))
+}
+
+/// Every Mandarin syllable (toneless pinyin, ü as v), sorted: the readings in the lexicon
+/// (public/data/mandarin.txt.gz), so typed pinyin is checked against real syllables (no "fe" in café).
+#[rustfmt::skip]
+const SYLLABLES: &[&str] = &[
+ "a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi",
+ "bian", "biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce",
+ "cen", "ceng", "cha", "chai", "chan", "chang", "chao", "che", "chen", "cheng", "chi", "chong",
+ "chou", "chu", "chua", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou",
+ "cu", "cuan", "cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "dei", "den",
+ "deng", "di", "dia", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du", "duan", "dui",
+ "dun", "duo", "e", "ei", "en", "eng", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fiao",
+ "fo", "fou", "fu", "ga", "gai", "gan", "gang", "gao", "ge", "gei", "gen", "geng", "gong", "gou",
+ "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang", "hao",
+ "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun",
+ "huo", "ji", "jia", "jian", "jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan",
+ "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken", "keng", "kong", "kou", "ku",
+ "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le",
+ "lei", "leng", "li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou",
+ "lu", "luan", "lun", "luo", "lv", "lve", "m", "ma", "mai", "man", "mang", "mao", "me", "mei",
+ "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "n", "na",
+ "nai", "nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie",
+ "nin", "ning", "niu", "nong", "nou", "nu", "nuan", "nun", "nuo", "nv", "nve", "o", "ou", "pa",
+ "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping",
+ "po", "pou", "pu", "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu",
+ "qu", "quan", "que", "qun", "ran", "rang", "rao", "re", "ren", "reng", "ri", "rong", "rou",
+ "ru", "rua", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen",
+ "seng", "sha", "shai", "shan", "shang", "shao", "she", "shei", "shen", "sheng", "shi", "shou",
+ "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun", "shuo", "si", "song", "sou", "su",
+ "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian",
+ "tiao", "tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai",
+ "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi", "xia", "xian", "xiang", "xiao", "xie",
+ "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye",
+ "yi", "yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan",
+ "zang", "zao", "ze", "zei", "zen", "zeng", "zha", "zhai", "zhan", "zhang", "zhao", "zhe",
+ "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui",
+ "zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo",
+];
+
+fn valid_syllable(base: &str) -> bool {
+ // a real syllable, or one with an erhua r (nar, dianr)
+ let real = |b: &str| SYLLABLES.binary_search(&b).is_ok();
+ let erhua = base.len() > 1 && base != "er" && base.strip_suffix('r').is_some_and(real);
+ (real(base) || erhua) && pinyin_syllable(&format!("{base}1"), "").is_some()
+}
+
+/// 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) {
+ let last = pieces.last_mut().unwrap();
+ if let Some(d) = c.to_digit(10) {
+ if d > 5 || last.0.is_empty() {
+ return None;
+ }
+ last.1 = Some(if d == 0 { 5 } else { d as u8 });
+ toned = true;
+ pieces.push((Vec::new(), None));
+ } else if c == '\'' {
+ pieces.push((Vec::new(), None));
+ } else if let Some((b, t)) = tone_mark(c) {
+ last.0.push((c, b, t));
+ toned = true;
+ } else if c == 'ü' || c.is_ascii_lowercase() {
+ last.0.push((c, if c == 'ü' { 'v' } else { c }, 0));
+ } else {
+ return None;
+ }
+ }
+ if !toned {
+ return None;
+ }
+ let mut out = 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)?;
+ let mut start = 0;
+ for (n, &end) in cuts.iter().enumerate() {
+ let span = &letters[start..end];
+ let marks: Vec<u8> = span.iter().map(|l| l.2).filter(|&t| t > 0).collect();
+ if marks.len() > 1 {
+ return None;
+ }
+ let tone = marks.first().copied().or(if n + 1 == cuts.len() { digit } else { None }).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));
+ }
+ out.push((text, format!("{}{tone}", &base[start..end])));
+ start = end;
+ }
+ }
+ Some(out)
+}
+
+/// The longest valid syllable first, backing off when the rest can't be split.
+fn split_syllables(base: &str) -> Option<Vec<usize>> {
+ fn go(base: &str, at: usize, out: &mut Vec<usize>) -> bool {
+ if at == base.len() {
+ return true;
+ }
+ for end in (at + 1..=base.len().min(at + 6)).rev() {
+ if valid_syllable(&base[at..end]) {
+ out.push(end);
+ if go(base, end, out) {
+ return true;
+ }
+ out.pop();
+ }
+ }
+ false
+ }
+ let mut out = Vec::new();
+ go(base, 0, &mut out).then_some(out)
+}
+
+impl FrontEnd for Pinyin {
+ fn starts(&self, c: char) -> bool {
+ c.is_ascii_alphabetic() || c.to_lowercase().any(|l| tone_mark(l).is_some() || l == 'ü')
+ }
+ fn continues(&self, c: char) -> bool {
+ 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 {
+ return false;
+ }
+ parse_pinyin(word).is_some()
+ }
+ fn word(&self, word: &str) -> Vec<Syllable> {
+ let Some(sy) = parse_pinyin(word) else { return Vec::new() };
+ let mut py: Vec<String> = sy.iter().map(|s| s.1.clone()).collect();
+ third_tones(&mut py);
+ sy.iter().zip(&py).filter_map(|((text, _), p)| pinyin_syllable(p, text)).collect()
+ }
+}
diff --git a/crates/chimera/src/phonetics/mod.rs b/crates/chimera/src/phonetics/mod.rs
index efad454..a4989d5 100644
--- a/crates/chimera/src/phonetics/mod.rs
+++ b/crates/chimera/src/phonetics/mod.rs
@@ -11,6 +11,7 @@ pub mod english;
pub mod inventory;
pub mod ipa;
pub mod korean;
+pub mod mandarin;
pub mod planner;
pub mod russian;
pub mod sing;
diff --git a/crates/chimera/src/phonetics/syllables.rs b/crates/chimera/src/phonetics/syllables.rs
index ca99a47..4c90db0 100644
--- a/crates/chimera/src/phonetics/syllables.rs
+++ b/crates/chimera/src/phonetics/syllables.rs
@@ -12,6 +12,7 @@
use crate::anatomy::human::BodyMix;
use super::english::js_is_space;
use super::korean::Korean;
+use super::mandarin::{Mandarin, MandarinLexicon, Pinyin};
use super::russian::Russian;
use super::planner::is_vowel;
use super::{Segment, Syllable};
@@ -308,7 +309,16 @@ pub fn read_lyrics(text: &str, front_ends: &[&dyn FrontEnd]) -> Vec<Syllable> {
}
/// Lyrics text → syllables through the built-in front ends that need no data beyond the English
-/// dictionary: English (`g2p`), Korean and Russian.
+/// dictionary: every built-in front end but Mandarin's characters (they need its lexicon; see
+/// [`lyrics_to_syllables_with`]).
pub fn lyrics_to_syllables(text: &str, g2p: &impl WordSource) -> Vec<Syllable> {
- read_lyrics(text, &[&English(g2p), &Korean, &Russian])
+ lyrics_to_syllables_with(text, g2p, &MandarinLexicon::new())
+}
+
+/// Lyrics → sung syllables through every built-in front end: pinyin (only words with tones; before
+/// English, which shares its alphabet), English (`g2p`), Korean, Russian, and Mandarin with its
+/// lexicon (empty: Han characters are skipped). The one list the app, the wasm engine and the CLI
+/// all read lyrics through, so a new front end can't be missing from one of them.
+pub fn lyrics_to_syllables_with(text: &str, g2p: &impl WordSource, zh: &MandarinLexicon) -> Vec<Syllable> {
+ read_lyrics(text, &[&Pinyin, &English(g2p), &Korean, &Russian, &Mandarin(zh)])
}
diff --git a/crates/chimera/tests/mandarin.rs b/crates/chimera/tests/mandarin.rs
new file mode 100644
index 0000000..4b8672e
--- /dev/null
+++ b/crates/chimera/tests/mandarin.rs
@@ -0,0 +1,145 @@
+//! Mandarin: the front end reads Han characters: longest phrase match, tone sandhi, pinyin → IPA
+//! with aspiration said, tones → pitch bends; and pinyin typed with tones.
+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::{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";
+
+fn lex() -> MandarinLexicon {
+ let mut l = MandarinLexicon::new();
+ l.load(LEX);
+ l
+}
+
+fn syls(text: &str) -> Vec<Syllable> {
+ let l = lex();
+ read_lyrics(text, &[&Mandarin(&l)])
+}
+
+/// onset+nucleus+coda, with ʰ/˭ where the front end says a stop's aspiration
+fn ipa(s: &Syllable) -> String {
+ let m = |segs: &[chimera::phonetics::Segment]| segs.iter().map(|x| format!("{}{}", x.ipa, match x.aspirated { Some(true) => "ʰ", Some(false) => "˭", None => "" })).collect::<String>();
+ format!("{}{}{}", m(&s.onset), s.nucleus.ipa, m(&s.coda))
+}
+
+#[test]
+fn readings_by_longest_phrase_then_tone_sandhi() {
+ let l = lex();
+ assert_eq!(l.read("银行"), ["yin2", "hang2"]); // the phrase decides 行
+ assert_eq!(l.read("行走"), ["xing2", "zou3"]); // no phrase: the character's own reading
+ assert_eq!(l.read("你好"), ["ni2", "hao3"]); // 3-3 → 2-3
+ assert_eq!(l.read("我你好"), ["wo2", "ni2", "hao3"]); // a run of third tones
+ assert_eq!(l.read("不会"), ["bu2", "hui4"]); // 不 before a fourth tone
+ assert_eq!(l.read("一个"), ["yi2", "ge4"]); // 一 before a fourth tone
+ assert_eq!(l.read("不去"), ["bu2", "qu4"]);
+}
+
+#[test]
+fn pinyin_becomes_ipa_with_aspiration_said() {
+ let all: Vec<String> = syls("跑不吃学绿的爱").iter().map(ipa).collect();
+ // p aspirated, b unaspirated; ch aspirated before an apical vowel; xue = ɕ ɥ ɛ; lü; neutral de; ai
+ // apical ʅ after ch; xue's glide sings inside the vowel (yɛ); 爱 starts with a glottal catch
+ assert_eq!(all, ["pʰaʊ", "p˭u", "tʂʰʅ", "ɕyɛ", "ly", "t˭ə", "ʔaɪ"]);
+}
+
+#[test]
+fn tones_become_bends_and_text_keeps_the_character() {
+ let s = syls("你好");
+ assert_eq!((s[0].text.as_str(), s[1].text.as_str()), ("你", "好"));
+ assert_eq!(s[0].pitch, tone_bends(2)); // sandhi: sung as a rising tone
+ assert_eq!(s[1].pitch, tone_bends(3));
+ assert!(s[1].word_end && !s[0].word_end);
+ assert!(tone_bends(1).is_empty() && tone_bends(5).is_empty());
+ assert_eq!(tone_bends(4).iter().map(|b| b.at).collect::<Vec<_>>(), [Edge::Start, Edge::End]);
+}
+
+#[test]
+fn a_mixed_line_routes_each_word_to_its_front_end() {
+ let l = lex();
+ let mut g = EnglishG2P::new();
+ g.load_dict("you\tY UW1\n");
+ let out = read_lyrics("我爱 you, 你。", &[&English(&g), &Korean, &Mandarin(&l)]);
+ let shown: Vec<(&str, bool, bool)> = out.iter().map(|s| (s.text.as_str(), s.word_end, s.phrase_end)).collect();
+ assert_eq!(shown, [("我", false, false), ("爱", true, false), ("you", true, true), ("你", true, true)]);
+ // no lexicon loaded: Han reads as nothing, the rest is unaffected
+ let empty = MandarinLexicon::new();
+ assert_eq!(read_lyrics("我 you", &[&English(&g), &Mandarin(&empty)]).len(), 1);
+}
+
+fn typed(text: &str) -> Vec<(String, String, usize)> {
+ let mut g = EnglishG2P::new();
+ g.load_dict("hello\tHH AH0 L OW1\ncaf\tK AE1 F\nit's\tIH1 T S\nz\tZ IY1\nrich\tR IH1 CH\nber\tB ER1\n");
+ read_lyrics(text, &[&Pinyin, &English(&g), &Korean]).iter().map(|s| (s.text.clone(), ipa(s), s.pitch.len())).collect()
+}
+
+#[test]
+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ǚ"]);
+ 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
+ assert_eq!(t[0].2, tone_bends(2).len());
+ assert_eq!(t[4].2, tone_bends(3).len());
+ // the unmarked syllable of a marked word is neutral: no bend
+ assert_eq!(t[3].2, 0);
+ // English: no tones, not pinyin. A word pinyin declines reads as it would without pinyin
+ // ("café" English's "caf", not "caf" and a pinyin "é"), and nothing in it is lost: "Zürich über"
+ // 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", "ā"]);
+}
+
+#[test]
+fn the_front_end_says_aspiration_length_and_nasalisation() {
+ let s = syls("跑的天");
+ assert_eq!(s[0].onset[0].vot, Some(0.09)); // aspirated: Mandarin's long aspiration
+ assert_eq!(s[1].onset[0].vot, None); // unaspirated
+ assert!(s[2].nasal_lead.is_some()); // tiān: nasalised before -n
+ assert_eq!(s[0].nasal_lead, None);
+}
+
+#[test]
+fn apical_vowels_follow_their_consonant() {
+ let n: Vec<String> = syls("四是").iter().map(|s| s.nucleus.ipa.clone()).collect();
+ assert_eq!(n, ["ɿ", "ʅ"]);
+}
+
+#[test]
+fn erhua_merges_into_the_syllable_before() {
+ let shown = |t: &str| syls(t).iter().map(|s| format!("{}={}", s.text, ipa(s))).collect::<Vec<_>>().join(" ");
+ // erhua: the syllable ends in ɻ, its -n gives way, a falling diphthong keeps its first vowel
+ assert_eq!(shown("一点儿"), "一=i 点儿=t˭iɛɻ");
+ assert_eq!(shown("块儿"), "块儿=kʰuaɻ"); // uai → ua + ɻ (the off-glide gives way, the on-glide stays)
+ assert_eq!(shown("哪儿"), "哪儿=naɻ");
+ assert_eq!(shown("一会儿"), "一=i 会儿=xweɻ");
+ // 儿 as a word's own syllable
+ assert_eq!(shown("女儿"), "女=ny 儿=ʔɝ");
+ assert_eq!(shown("儿子"), "儿=ʔɝ 子=ts˭ɿ");
+ // pinyin's r
+ let p: Vec<String> = typed("nǎr yìdiǎnr").into_iter().map(|x| x.1).collect();
+ assert_eq!(p, ["naɻ", "i", "t˭iɛɻ"]);
+}
+
+#[test]
+fn mandarin_timing_and_vowels() {
+ let s = syls("光天你风举");
+ let dur = |segs: &[chimera::phonetics::Segment]| segs.iter().map(|x| x.dur).collect::<Vec<_>>();
+ // nasal codas held long enough to tell -n from -ng
+ assert_eq!(dur(&s[0].coda), [Some(0.13)]);
+ assert_eq!(dur(&s[1].coda), [Some(0.10)]);
+ // nasal onsets and f longer; an unaspirated affricate's frication shorter
+ assert_eq!(s[2].onset[0].dur, Some(0.09));
+ assert_eq!(s[3].onset[0].dur, Some(0.13));
+ assert_eq!(s[4].onset[0].dur, Some(0.08));
+ // Mandarin's own vowels: eng back [ɤŋ], uo open [uɔ], ou central [əʊ], iao one three-part nucleus
+ let n: Vec<String> = syls("风多头鸟").iter().map(|s| s.nucleus.ipa.clone()).collect();
+ assert_eq!(n, ["ɤ", "uɔ", "əʊ", "iaʊ"]);
+}
diff --git a/public/data/MANDARIN-PINYIN-LICENSE.txt b/public/data/MANDARIN-PINYIN-LICENSE.txt
new file mode 100644
index 0000000..8d83b39
--- /dev/null
+++ b/public/data/MANDARIN-PINYIN-LICENSE.txt
@@ -0,0 +1,50 @@
+public/data/mandarin.txt.gz is built by tools/build-mandarin.ts from
+- https://raw.githubusercontent.com/mozillazg/pinyin-data/fe29ad32bdf352b31a02b9936e537f575432e9a6/pinyin.txt (pinyin-data)
+- https://raw.githubusercontent.com/mozillazg/phrase-pinyin-data/4afa3226ce53c9138b939e83c3bb294dbe0da511/pinyin.txt (phrase-pinyin-data)
+under their MIT licenses:
+
+The MIT License (MIT)
+
+Copyright (c) 2016 mozillazg
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+---
+
+MIT License
+
+Copyright (c) 2017 mozillazg
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/public/data/mandarin.txt.gz b/public/data/mandarin.txt.gz
new file mode 100644
index 0000000..40bbd1c
Binary files /dev/null and b/public/data/mandarin.txt.gz differ
diff --git a/src/ui/components/DuetPage.tsx b/src/ui/components/DuetPage.tsx
index 9f9e4a3..fdf53cf 100644
--- a/src/ui/components/DuetPage.tsx
+++ b/src/ui/components/DuetPage.tsx
@@ -25,8 +25,8 @@ import { bodyLabel } from "../body.ts";
import type { ViewFlags } from "../render/anatomy.ts";
import { mouthWords } from "../mouthWords.ts";
import { V } from "../colors.ts";
-import { g2p } from "../speech.ts";
-import { lyricsToSyllables } from "../../wasm/engine.ts";
+import { g2p, zh } from "../speech.ts";
+import { hasHan, lyricsToSyllables } from "../../wasm/engine.ts";
import { sungWords, wordAt, type Melody, type SungWords } from "../../show/words.ts";
import type { OverlayFn } from "./AnatomyView.tsx";
@@ -80,6 +80,7 @@ export function DuetPage(props: { id: string }) {
// the words: syllables as the CLI splits them (the pronouncing dictionary first, as it does)
const melodies = await Promise.all(show.voices.map((v) => (v.melody ? fetchOk(base + v.melody).then((r) => r.json() as Promise<Melody>) : null)));
if (melodies.some(Boolean)) await g2p.load().catch(() => {});
+ if (melodies.some((m) => m && !m.syllables && hasHan(m.lyrics))) await zh.load().catch(() => {});
const words = melodies.map((m) => {
if (!m) return null;
try {
diff --git a/src/ui/singing.ts b/src/ui/singing.ts
index 472aa3a..360980e 100644
--- a/src/ui/singing.ts
+++ b/src/ui/singing.ts
@@ -9,8 +9,8 @@
*/
import { create } from "zustand";
import { engine } from "../audio/AudioEngine.ts";
-import { g2p } from "./speech.ts";
-import { lyricsToSyllables, type Syllable } from "../wasm/engine.ts";
+import { g2p, zh } from "./speech.ts";
+import { hasHan, lyricsToSyllables, type Syllable } from "../wasm/engine.ts";
import { planSong, planNoteOn, planNoteOff, planMelisma } from "../wasm/engine.ts";
import { EXHALE_LABEL } from "../wasm/engine.ts";
import type { Gesture } from "../wasm/types.ts";
@@ -94,6 +94,7 @@ export const useSing = create<SingState>((set, get) => ({
setLyrics: (text) => {
stopDemo();
set({ lyrics: text, syllables: lyricsToSyllables(text), cursor: 0 });
+ if (hasHan(text) && !zh.loaded) ensureDictionary();
},
setCursor: (i) => set({ cursor: Math.max(0, Math.min(i, Math.max(0, get().syllables.length - 1))) }),
setVibrato: (cents) => set({ vibrato: cents }),
@@ -111,19 +112,21 @@ useSing.subscribe((s, p) => {
}
});
-/** Load the pronouncing dictionary, then re-read the lyrics with it (the cursor stays). */
+/**
+ * Load what the lyrics' front ends need (the pronouncing dictionary; the Mandarin lexicon when there
+ * are Han characters), then re-read the lyrics with it (the cursor stays).
+ */
export function ensureDictionary(): void {
- if (g2p.loaded) return;
- g2p
- .load()
- .then(() => {
- const s = useSing.getState();
- const syllables = lyricsToSyllables(s.lyrics);
- useSing.setState({ syllables, cursor: Math.min(s.cursor, Math.max(0, syllables.length - 1)) });
- })
- .catch(() => {
- // no dictionary: the letter-to-sound rules keep working
- });
+ const needs: Promise<void>[] = [];
+ if (!g2p.loaded) needs.push(g2p.load());
+ if (!zh.loaded && hasHan(useSing.getState().lyrics)) needs.push(zh.load());
+ if (!needs.length) return;
+ // a failed load leaves the rest working (letter-to-sound rules for English)
+ void Promise.allSettled(needs).then(() => {
+ const s = useSing.getState();
+ const syllables = lyricsToSyllables(s.lyrics);
+ useSing.setState({ syllables, cursor: Math.min(s.cursor, Math.max(0, syllables.length - 1)) });
+ });
}
// ---- live notes
@@ -320,6 +323,7 @@ export async function playTune(id: string, body: BodyMix, ready?: () => Promise<
} catch {
// letter-to-sound rules
}
+ if (hasHan(useSing.getState().lyrics)) await zh.load().catch(() => {});
if (token !== demoToken) return false;
const st = useSing.getState();
// read again: the dictionary may have arrived since the words were typed
diff --git a/src/ui/speech.ts b/src/ui/speech.ts
index 974ae65..11db569 100644
--- a/src/ui/speech.ts
+++ b/src/ui/speech.ts
@@ -1,6 +1,6 @@
/** Main-thread speech planning: text/IPA → phrases → gestural plan → worklet. */
import type { BodyMix } from "../wasm/types.ts";
-import { EnglishG2P, type Phrase } from "../wasm/engine.ts";
+import { EnglishG2P, MandarinLexicon, type Phrase } from "../wasm/engine.ts";
import { tokenizeIpa } from "../wasm/engine.ts";
import { planPhrases, type Plan, type Segment } from "../wasm/engine.ts";
import { engine } from "../audio/AudioEngine.ts";
@@ -9,6 +9,8 @@ import { ipaPhraseTexts } from "./skipped.ts";
import { wordSpans, type WordSpan } from "./words.ts";
export const g2p = new EnglishG2P();
+/** the Mandarin front end's lexicon, loaded when lyrics first have Han characters */
+export const zh = new MandarinLexicon();
export interface SpokenPlan {
plan: Plan;
diff --git a/src/wasm/engine.ts b/src/wasm/engine.ts
index 68f4f14..bafc3fd 100644
--- a/src/wasm/engine.ts
+++ b/src/wasm/engine.ts
@@ -85,23 +85,13 @@ export class EnglishG2P {
load(url = "/data/cmudict.txt.gz"): Promise<void> {
if (this.isLoaded) return Promise.resolve();
if (this.loading) return this.loading;
- this.loading = (async () => {
- try {
- const res = await fetch(url);
- if (!res.ok) throw new Error(`dictionary ${res.status}`);
- const bytes = new Uint8Array(await res.arrayBuffer());
- // servers differ: some send Content-Encoding: gzip (already inflated by the browser)
- let text: string;
- if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
- const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
- text = await new Response(stream).text();
- } else text = new TextDecoder().decode(bytes);
- this.setDictionaryText(text);
- } catch (e) {
+ this.loading = fetchGzText(url).then(
+ (text) => this.setDictionaryText(text),
+ (e) => {
this.loading = null; // allow a retry
throw e;
- }
- })();
+ },
+ );
return this.loading;
}
@@ -121,7 +111,48 @@ export class EnglishG2P {
}
}
-/** Lyrics → sung syllables, through the page's dictionary (see EnglishG2P). */
+/** Fetch a gzipped text file (servers differ: some send Content-Encoding: gzip, already inflated). */
+async function fetchGzText(url: string): Promise<string> {
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`${url}: ${res.status}`);
+ const bytes = new Uint8Array(await res.arrayBuffer());
+ if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
+ return new Response(stream).text();
+ }
+ return new TextDecoder().decode(bytes);
+}
+
+/** Han characters, which the Mandarin front end reads once its lexicon is loaded. */
+export const hasHan = (text: string): boolean => /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/u.test(text);
+
+/** The Mandarin front end's lexicon (character and phrase readings), fetched once when needed. */
+export class MandarinLexicon {
+ private loading: Promise<void> | null = null;
+ private isLoaded = false;
+
+ get loaded(): boolean {
+ return this.isLoaded;
+ }
+
+ load(url = "/data/mandarin.txt.gz"): Promise<void> {
+ if (this.isLoaded) return Promise.resolve();
+ if (this.loading) return this.loading;
+ this.loading = fetchGzText(url).then(
+ (text) => {
+ call("zhLoad", { text });
+ this.isLoaded = true;
+ },
+ (e) => {
+ this.loading = null;
+ throw e;
+ },
+ );
+ return this.loading;
+ }
+}
+
+/** Lyrics → sung syllables through the built-in front ends: English (the page's dictionary, see EnglishG2P), Korean, and Mandarin once its lexicon is loaded. */
export function lyricsToSyllables(text: string): Syllable[] {
return call("lyricsToSyllables", { text });
}
diff --git a/tools/build-mandarin.ts b/tools/build-mandarin.ts
new file mode 100644
index 0000000..49a15a4
--- /dev/null
+++ b/tools/build-mandarin.ts
@@ -0,0 +1,85 @@
+/**
+ * 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,
+ * 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.
+ *
+ * Sources, both MIT (mozillazg): pinyin-data's pinyin.txt (merged from Unicode's Unihan readings,
+ * no CC-CEDICT) and phrase-pinyin-data's pinyin.txt (its base phrase list plus overrides; not the
+ * large_pinyin.txt that merges CC-CEDICT, which is CC BY-SA).
+ */
+import { mkdirSync, writeFileSync } from "node:fs";
+import { gzipSync } from "node:zlib";
+
+const CHARS = "https://raw.githubusercontent.com/mozillazg/pinyin-data/fe29ad32bdf352b31a02b9936e537f575432e9a6";
+const PHRASES = "https://raw.githubusercontent.com/mozillazg/phrase-pinyin-data/4afa3226ce53c9138b939e83c3bb294dbe0da511";
+
+const get = async (url: string) => {
+ const r = await fetch(url);
+ if (!r.ok) throw new Error(`${url}: ${r.status}`);
+ return r.text();
+};
+
+const TONED: Record<string, [string, number]> = {};
+for (const [base, marks] of Object.entries({ a: "āáǎà", e: "ēéěè", i: "īíǐì", o: "ōóǒò", u: "ūúǔù", v: "ǖǘǚǜ", m: "ḿḿ", n: "ńńňǹ" })) {
+ [...marks].forEach((m, k) => (TONED[m] = [base, base === "m" ? 2 : base === "n" && k === 0 ? 2 : k + 1]));
+}
+TONED["ḿ"] = ["m", 2];
+TONED["ń"] = ["n", 2];
+TONED["ň"] = ["n", 3];
+TONED["ǹ"] = ["n", 4];
+
+/** "zhōng" → "zhong1", "lǜ" → "lv4", "de" → "de5"; null for what isn't a pinyin syllable. */
+function numbered(syl: string): string | null {
+ let tone = 5;
+ let out = "";
+ for (const ch of syl.normalize("NFC").toLowerCase()) {
+ if (TONED[ch]) {
+ const [b, t] = TONED[ch];
+ out += b;
+ tone = t;
+ } else if (ch === "ü") out += "v";
+ else if (/[a-z]/.test(ch)) out += ch;
+ else return null;
+ }
+ return out ? out + tone : null;
+}
+
+const isHan = (c: string) => /^[㐀-䶿一-鿿豈-﫿]$/u.test(c);
+
+// characters: "U+4E2D: zhōng,zhòng # 中" → the first (most common) reading
+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());
+ if (isHan(c) && first) chars.set(c, first);
+}
+
+// phrases: "银行: yín háng" → kept only when some character reads otherwise than on its own
+const phrases: string[] = [];
+let all = 0;
+for (const line of (await get(`${PHRASES}/pinyin.txt`)).split("\n")) {
+ const m = line.match(/^([^#:\s]+):\s*([^#]+)/);
+ if (!m) continue;
+ const word = [...m[1]];
+ const syls = m[2].trim().split(/\s+/).map(numbered);
+ if (word.length < 2 || word.length !== syls.length || syls.some((s) => !s) || !word.every(isHan)) continue;
+ all++;
+ // kept: phrases that read a character otherwise, and every phrase with 儿 (it says whether 儿 is
+ // a syllable, 女儿 er2, or an erhua ending, 一会儿 er5; the front end needs to know which)
+ if (word.some((c, i) => chars.get(c) !== syls[i]) || word.includes("儿")) phrases.push(`${m[1]}\t${syls.join(" ")}`);
+}
+
+const lines = [...[...chars].map(([c, p]) => `${c}\t${p}`), ...phrases];
+mkdirSync("public/data", { recursive: true });
+writeFileSync("public/data/mandarin.txt.gz", gzipSync(Buffer.from(lines.join("\n"), "utf8"), { level: 9 }));
+const license = (await get(`${CHARS}/LICENSE`)) + "\n---\n\n" + (await get(`${PHRASES}/LICENSE`));
+writeFileSync(
+ "public/data/MANDARIN-PINYIN-LICENSE.txt",
+ `public/data/mandarin.txt.gz is built by tools/build-mandarin.ts from\n- ${CHARS}/pinyin.txt (pinyin-data)\n- ${PHRASES}/pinyin.txt (phrase-pinyin-data)\nunder their MIT licenses:\n\n${license}`,
+);
+console.log(`${chars.size} characters, ${phrases.length} of ${all} phrases (the ones that decide a reading)`);