the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Speak, IPA mode: say which symbols the voice skipped, and why (#52) (#75)
Sayoedd2676607d1
diff --git a/README.md b/README.mdindex ace7da7..8a67154 100644--- a/README.md+++ b/README.md@@ -25,7 +25,9 @@ for tests and the `chimera` CLI.- **Play**: drag the tongue, lips and jaw in a live cutaway of the head; vowel pad, encoders,computer keyboard and Web MIDI.- **Speak**: English text (CMUdict with a letter-to-sound fallback) or IPA, turned into- gestures and prosody, with the gestural score and a consonant chart on screen.+ gestures and prosody, with the gestural score and a consonant chart on screen. In IPA mode a+ notice under the box lists the symbols and marks the voice doesn't say (`chimera render speech`+ prints the same as warnings).- **Sing**: a pitch roll with lyrics per note; consonants land before the beat. Lyrics can beEnglish or Korean (Hangul: one block per note, with Korean sound rules); each language is afront end ([docs/language-front-ends.md](docs/language-front-ends.md)).diff --git a/crates/chimera-cli/src/render.rs b/crates/chimera-cli/src/render.rsindex 5e8a7d3..6555893 100644--- a/crates/chimera-cli/src/render.rs+++ b/crates/chimera-cli/src/render.rs@@ -13,7 +13,7 @@ use chimera::creatures::{CREATURES, creature_by_id};use chimera::math::{js_max, js_min, js_round, log10};use chimera::phonetics::beatbox::{BEAT_PRESETS, BEAT_SOUNDS, BeatStep, beat_ready, parse_beat};use chimera::phonetics::english::EnglishG2P;-use chimera::phonetics::ipa::tokenize_ipa;+use chimera::phonetics::ipa::{skipped_ipa, tokenize_ipa};use chimera::phonetics::planner::{PhraseInput, PlanOptions, plan_phrases, plan_utterance, vowel_table,};@@ -92,6 +92,11 @@ pub fn speech(ctx: &Ctx, a: &[String]) -> Result<(), String> {voice.set_source(&SourcePatch::f0(f0));let mut marks: Vec<(f64, String)> = Vec::new();let mut t0 = 0.05;+ // what the engine will not say as typed, one warning line per kind on stderr (the render is unchanged)+ // (the "/" between utterances is a transcription delimiter, which skipped_ipa does not report)+ for line in skipped_ipa(&text).warnings() {+ eprintln!("warning: {line}");+ }for u in text.split('/').map(str::trim).filter(|u| !u.is_empty()) {let segs = tokenize_ipa(u);let plan = plan_utterance(diff --git a/crates/chimera-wasm/src/api.rs b/crates/chimera-wasm/src/api.rsindex 46975da..fbb9219 100644--- a/crates/chimera-wasm/src/api.rs+++ b/crates/chimera-wasm/src/api.rs@@ -118,6 +118,8 @@ fn dispatch(st: &mut State, req: &Value) -> Res {}// ---------------------------------------------------------------- text → phonemes"tokenizeIpa" => to_json(&ipa::tokenize_ipa(&arg::<String>(req, "text")?)),+ // what tokenizeIpa leaves out of the text without a word: { unknown, noSound, ignoredMarks }+ "skippedIpa" => to_json(&ipa::skipped_ipa(&arg::<String>(req, "text")?)),"g2pLoad" => {st.g2p.load_dict(&arg::<String>(req, "text")?);Ok(json!(true))diff --git a/crates/chimera/src/phonetics/ipa.rs b/crates/chimera/src/phonetics/ipa.rsindex 6b3010a..850dce8 100644--- a/crates/chimera/src/phonetics/ipa.rs+++ b/crates/chimera/src/phonetics/ipa.rs@@ -13,6 +13,10 @@ const ALIASES: [(&str, &str); 9] = [("t͡ʃ", "tʃ"), ("d͡ʒ", "dʒ"), ("t͡s",/// combining tilde and combining diaeresis below: the vowel before them is nasalized, breathyconst NASALIZED: char = '\u{303}';const BREATHY: char = '\u{324}';+/// combining inverted breve below (non-syllabic, `aɪ̯`) and combining vertical line below (syllabic,+/// `bʌtn̩`): in most dictionary IPA, and the voice says the sound they mark, so they are never reported+const NONSYLLABIC: char = '\u{32F}';+const SYLLABIC: char = '\u{329}';/// NFC composes these vowels with their mark into one code point; the tokenizer reads them as the/// vowel and the mark (those that don't compose, like ɛ̃, arrive as two)const PRECOMPOSED: [(&str, &str); 7] = [("ã", "a\u{303}"), ("õ", "o\u{303}"), ("ẽ", "e\u{303}"), ("ĩ", "i\u{303}"), ("ũ", "u\u{303}"), ("ỹ", "y\u{303}"), ("ṳ", "u\u{324}")];@@ -36,6 +40,120 @@ pub fn init() {}pub fn tokenize_ipa(input: &str) -> Vec<Segment> {+ tokenize(input, &mut Gaps::default())+}++/// What `tokenize` leaves out of its input without a word.+#[derive(Default)]+struct Gaps {+ /// symbols it does not know+ unknown: Vec<String>,+ /// letters that carried a combining mark it does not model, and marks it reads written after a+ /// sound they do not apply to (shown with that sound)+ marked: Vec<String>,+}++fn add(list: &mut Vec<String>, item: String) {+ if !list.contains(&item) {+ list.push(item);+ }+}++/// A lone combining mark is shown on a dotted circle, so it is visible.+fn shown(s: &str) -> String {+ if s.chars().next().is_some_and(|c| ('\u{300}'..='\u{36F}').contains(&c)) { format!("\u{25CC}{s}") } else { s.to_string() }+}++impl Gaps {+ /// A mark the tokenizer reads, written after a sound it does not apply to (ʲ after a vowel, ʱ+ /// after a voiceless stop): reported with that sound, or alone when no sound precedes it.+ fn ignore(&mut self, after: Option<&Segment>, mark: char) {+ add(+ &mut self.marked,+ match after {+ Some(s) if s.ipa != "_" => format!("{}{mark}", s.ipa),+ _ => shown(&mark.to_string()),+ },+ );+ }+}++/// What the engine will not say as written in a piece of IPA text (see [`skipped_ipa`]).+#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SkippedIpa {+ /// symbols the tokenizer does not know (a tone letter, a click, a capital, a typo): dropped+ pub unknown: Vec<String>,+ /// symbols the tokenizer knows and the planner has no sound for (a vowel letter without a+ /// calibrated vowel): dropped+ pub no_sound: Vec<String>,+ /// letters written with a mark the engine does not model (a devoicing ring; not the syllabic and+ /// non-syllabic marks `n̩` `ɪ̯`, which are in most dictionary IPA and the voice says the sound),+ /// or a mark it reads written where it cannot apply (`ʲ` after a vowel, `ʱ` after a voiceless+ /// stop), shown with the letter: the letter is said, the mark is not+ pub ignored_marks: Vec<String>,+}++impl SkippedIpa {+ pub fn is_empty(&self) -> bool {+ self.unknown.is_empty() && self.no_sound.is_empty() && self.ignored_marks.is_empty()+ }++ /// One line per kind that is not empty, ready to print after `warning: `. The labels are the+ /// ones the Speak notice shows (`Not said`, `No sound yet`, `Mark ignored`).+ pub fn warnings(&self) -> Vec<String> {+ let mut out = Vec::new();+ let mut line = |what: &str, items: &[String]| {+ if !items.is_empty() {+ out.push(format!("{what}: {}", items.join(" ")));+ }+ };+ line("not said", &self.unknown);+ line("no sound yet", &self.no_sound);+ line("mark ignored", &self.ignored_marks);+ out+ }+}++/// Whether the planner has a sound for a symbol `tokenize_ipa` can emit: a calibrated vowel for+/// some body, a diphthong made of them, or a consonant in the inventory.+fn has_sound(sym: &str) -> bool {+ use crate::anatomy::human::BodyMix;+ [BodyMix::MALE, BodyMix::FEMALE, BodyMix::CHILD].into_iter().any(|b| super::planner::is_vowel(sym, b)) || consonant(sym).is_some()+}++/// What the engine will not say as written in `input`, in input order, each item once: symbols it+/// does not know at all, symbols it knows but has no sound for (derived: `tokenize_ipa` emits+/// them and the planner has no vowel or consonant for them, so the list shrinks as sounds are+/// added), and marks it does not model or cannot apply (the letter is said, the mark is not).+/// The syllabic and non-syllabic marks (U+0329 `n̩`, U+032F `ɪ̯`) are the exception: they are in most+/// dictionary IPA and the voice says the sound they mark, so they are never reported, on any letter+/// or where no letter precedes them.+///+/// The marks `tokenize_ipa` reads (`ʰ ˭`, a tilde or diaeresis below on a vowel, `ʲ`, `ʱ` where+/// they apply), stress, length, tie bars, spaces and `. , |` are not reported, and neither are+/// whitespace of other kinds and the transcription delimiters `/ [ ]` (`/ɕiɛ/`, `[ɕiɛ]`). `tokenize_ipa` itself is unchanged and still drops these silently,+/// so a caller that takes IPA from a person should show this.+pub fn skipped_ipa(input: &str) -> SkippedIpa {+ let mut g = Gaps::default();+ let mut no_sound = Vec::new();+ for seg in tokenize(input, &mut g) {+ if seg.ipa != "_" && !has_sound(&seg.ipa) {+ add(&mut no_sound, seg.ipa);+ }+ }+ SkippedIpa { unknown: g.unknown, no_sound, ignored_marks: g.marked }+}++/// Every symbol `tokenize_ipa` can emit: the inventory's consonants, the vowel letters and the+/// multi-letter affricates and diphthongs. Not every one has a sound (see [`skipped_ipa`]).+pub fn known_ipa_symbols() -> Vec<&'static str> {+ let mut v: Vec<&'static str> = known().iter().copied().collect();+ v.sort_unstable();+ v+}++fn tokenize(input: &str, gaps: &mut Gaps) -> Vec<Segment> {let mut s = nfc(input);for (a, b) in ALIASES {s = s.replace(a, b);@@ -81,28 +199,28 @@ pub fn tokenize_ipa(input: &str) -> Vec<Segment> {}// palatalization, on a consonant made with a mouth gesture (not a glottal one)if ch == 'ʲ' {- if let Some(last) = out.last_mut().filter(|l| consonant(&l.ipa).is_some_and(|c| c.manner != Manner::Glottal)) {- last.palatalized = Some(true);+ match out.last_mut().filter(|l| consonant(&l.ipa).is_some_and(|c| c.manner != Manner::Glottal)) {+ Some(last) => last.palatalized = Some(true),+ None => gaps.ignore(out.last(), ch),}i += 1;continue;}// a breathy-voiced release, on a voiced stop or affricate (Hindi bʱ dʱ gʱ)if ch == 'ʱ' {- if let Some(last) = out.last_mut().filter(|l| consonant(&l.ipa).is_some_and(|c| c.voicing == Voicing::Voiced && matches!(c.manner, Manner::Stop | Manner::Affricate))) {- last.breathy = Some(true);+ match out.last_mut().filter(|l| consonant(&l.ipa).is_some_and(|c| c.voicing == Voicing::Voiced && matches!(c.manner, Manner::Stop | Manner::Affricate))) {+ Some(last) => last.breathy = Some(true),+ None => gaps.ignore(out.last(), ch),}i += 1;continue;}// a vowel mark after the length mark instead of the vowel (ɛː̃)if (ch == NASALIZED || ch == BREATHY) && i > 0 && (s[i - 1] == 'ː' || s[i - 1] == ':') {- if let Some(last) = out.last_mut().filter(|l| is_vowel_token(&l.ipa)) {- if ch == NASALIZED {- last.nasalized = Some(true);- } else {- last.breathy = Some(true);- }+ match out.last_mut().filter(|l| is_vowel_token(&l.ipa)) {+ Some(last) if ch == NASALIZED => last.nasalized = Some(true),+ Some(last) => last.breathy = Some(true),+ None => gaps.ignore(out.last(), ch),}i += 1;continue;@@ -115,6 +233,12 @@ pub fn tokenize_ipa(input: &str) -> Vec<Segment> {i += 1;continue;}+ // a syllabic or non-syllabic mark with no sound before it to sit on (the start, after a space+ // or a length mark): dropped, as it always was, but not reported either+ if ch == NONSYLLABIC || ch == SYLLABIC {+ i += 1;+ continue;+ }let mut tok = String::new();for m in MULTI {if starts_with_at(&s, i, m) {@@ -125,7 +249,9 @@ pub fn tokenize_ipa(input: &str) -> Vec<Segment> {tok = ch.to_string();}i += tok.chars().count();- // combining diacritics: the tilde and the diaeresis below are read, the rest we do not model+ // combining diacritics: the tilde and the diaeresis below on a vowel are read, the rest we+ // do not model+ let marks_from = i;let (mut nasalized, mut breathy) = (false, false);while i < s.len() && ('\u{300}'..='\u{36F}').contains(&s[i]) {nasalized |= s[i] == NASALIZED;@@ -133,9 +259,19 @@ pub fn tokenize_ipa(input: &str) -> Vec<Segment> {i += 1;}if !known.contains(tok.as_str()) {+ // whitespace and the delimiters IPA is written between (/phonemic/, [phonetic]) are structure+ if !tok.chars().all(|c| c.is_whitespace() || matches!(c, '/' | '[' | ']')) {+ add(&mut gaps.unknown, shown(&tok));+ }continue;}let is_v = is_vowel_token(&tok);+ // what is left unread: any mark but a tilde or diaeresis below on a vowel, and the+ // syllabic and non-syllabic marks on any letter (never reported)+ let unread: String = s[marks_from..i].iter().copied().filter(|c| !(is_v && (*c == NASALIZED || *c == BREATHY)) && *c != NONSYLLABIC && *c != SYLLABIC).collect();+ if !unread.is_empty() {+ add(&mut gaps.marked, format!("{tok}{unread}"));+ }out.push(Segment { ipa: tok, stress: Some(if is_v { stress } else { 0 }), nasalized: (is_v && nasalized).then_some(true), breathy: (is_v && breathy).then_some(true), ..Default::default() });if is_v {stress = 0;diff --git a/crates/chimera/tests/skipped_ipa.rs b/crates/chimera/tests/skipped_ipa.rsnew file mode 100644index 0000000..9fe6bb4--- /dev/null+++ b/crates/chimera/tests/skipped_ipa.rs@@ -0,0 +1,155 @@+//! `skipped_ipa`: what the Speak box and the CLI tell a person the engine did not say. The owner's+//! report (issue 52): pasted Wiktionary IPA `ɕiɛ˥˩ɕiɛ` came out as a different word and nothing said so.++use chimera::anatomy::human::BodyMix;+use chimera::phonetics::ipa::{SkippedIpa, known_ipa_symbols, skipped_ipa, tokenize_ipa};+use chimera::phonetics::planner::is_vowel;++fn strs(v: &[&str]) -> Vec<String> {+ v.iter().map(|s| s.to_string()).collect()+}++#[test]+fn empty_and_all_known_input_report_nothing() {+ assert!(skipped_ipa("").is_empty());+ assert!(skipped_ipa(" ").is_empty());+ let r = skipped_ipa("ˈpʰaː.tɑ, bɑ|dɑ t͡ʃa");+ assert!(r.is_empty(), "{r:?}");+ assert!(skipped_ipa("ˈɑpɑ / ˈɑbɑ").is_empty());+}++#[test]+fn unknown_symbols_are_reported_the_owners_example() {+ // tone letters are not read, and ɕ is not in the inventory yet (when it is, it drops out of+ // this list by itself, so the expectation asks the function about ɕ alone)+ let r = skipped_ipa("ɕiɛ˥˩ɕiɛ");+ let mut want = skipped_ipa("ɕ").unknown;+ want.extend(strs(&["˥", "˩"]));+ assert_eq!(r.unknown, want);+ assert!(r.no_sound.is_empty() && r.ignored_marks.is_empty(), "{r:?}");+ // a capital, a digit, a click, a typo+ assert_eq!(skipped_ipa("Ab2ǃ").unknown, strs(&["A", "2", "ǃ"]));+}++#[test]+fn transcription_delimiters_are_structure() {+ // what people paste from Wiktionary: /phonemic/ and [phonetic]; only the real gaps are named+ let bare = skipped_ipa("ɕiɛ˥˩");+ assert!(bare.unknown.iter().any(|s| s == "˥") && bare.unknown.iter().any(|s| s == "˩"));+ assert_eq!(skipped_ipa("/ɕiɛ/"), skipped_ipa("ɕiɛ"));+ assert_eq!(skipped_ipa("[ɕiɛ˥˩]"), bare);+ assert_eq!(skipped_ipa("/ɕiɛ˥˩/ [ɕiɛ˥˩]"), bare);+ // anything else stays as it was: parentheses and the like are reported+ assert_eq!(skipped_ipa("/a(b)/").unknown, strs(&["(", ")"]));+ assert!(skipped_ipa("/ˈhɛlo/ [ˈhɛlo]").is_empty());+}++#[test]+fn order_is_input_order_and_each_item_once() {+ assert_eq!(skipped_ipa("˩a˥˩˥a˩").unknown, strs(&["˩", "˥"]));+ let r = skipped_ipa("n̥ n̥ a n̥ aʲ aʲ");+ assert_eq!(r.ignored_marks, strs(&["n̥", "aʲ"]));+}++#[test]+fn a_mark_the_tokenizer_reads_is_not_reported() {+ for ipa in ["pʰa p˭a", "a\u{303} ã ɛ\u{303} ɛː\u{303}", "tʃʲa pʲa", "bʱa dʱa", "a\u{324} ṳ ɛː\u{324}", "ˈaː a\u{361}b t͡s"] {+ assert!(skipped_ipa(ipa).is_empty(), "{ipa}: {:?}", skipped_ipa(ipa));+ }+}++/// Review of the PR: the syllabic (U+0329) and non-syllabic (U+032F) marks are in most dictionary+/// IPA and the voice says the sound, so a notice for them fires on many pastes for nothing.+#[test]+fn the_syllabic_and_non_syllabic_marks_are_not_reported() {+ // the reviewer's examples, and the same marks on other letters, after a length mark, at the+ // start, after a space or stress mark, and doubled+ for ipa in ["a\u{26A}\u{32F}", "b\u{28C}tn\u{329}", "l\u{329}", "\u{250}\u{32F}", "n\u{2D0}\u{329}", "\u{329}a", "a \u{32F}b", "\u{2C8}\u{329}a", "m\u{329}\u{32F}", "a\u{2D0}\u{32F}", "p\u{329}"] {+ assert!(skipped_ipa(ipa).is_empty(), "{ipa:?}: {:?}", skipped_ipa(ipa));+ }+}++#[test]+fn a_syllabic_mark_is_not_shown_beside_a_mark_that_is_reported() {+ // n + devoicing ring + syllabic mark reports the ring only+ assert_eq!(skipped_ipa("n\u{325}\u{329}").ignored_marks, strs(&["n\u{325}"]));+ assert_eq!(skipped_ipa("n\u{329}\u{325}").ignored_marks, strs(&["n\u{325}"]));+ // an unknown letter is still reported, without the mark+ assert_eq!(skipped_ipa("\u{298}\u{329}").unknown, strs(&["\u{298}"]));+}++#[test]+fn marks_that_are_not_modelled_or_cannot_apply_are_reported_with_their_letter() {+ // a devoicing ring and a nasal tilde on a consonant are not modelled+ assert_eq!(skipped_ipa("n\u{325}").ignored_marks, strs(&["n\u{325}"]));+ assert_eq!(skipped_ipa("m\u{303}").ignored_marks, strs(&["m\u{303}"]));+ // ʲ after a vowel, ʱ after a voiceless stop, and a vowel mark on a consonant after a length mark+ assert_eq!(skipped_ipa("aʲ").ignored_marks, strs(&["aʲ"]));+ assert_eq!(skipped_ipa("pʱ").ignored_marks, strs(&["pʱ"]));+ assert_eq!(skipped_ipa("mː\u{303}").ignored_marks, strs(&["m\u{303}"]));+ // the letter is still said: nothing else is reported+ let r = skipped_ipa("n\u{325}a");+ assert!(r.unknown.is_empty() && r.no_sound.is_empty(), "{r:?}");+ // a mark with nothing before it to carry it+ assert_eq!(skipped_ipa("ʲa").ignored_marks, strs(&["ʲ"]));+ assert_eq!(skipped_ipa("\u{325}a").unknown, strs(&["\u{25CC}\u{325}"]));+}++#[test]+fn structure_is_not_a_skipped_symbol() {+ assert!(skipped_ipa("ˈa ˌa aː a:. a, a| 'a\ta\n").is_empty());+}++#[test]+fn the_three_kinds_together() {+ // ɔ̃ and ʰ are read; n̥ keeps its letter and loses its ring; ʏ is a letter the tokenizer accepts+ // and, today, no body has a calibrated vowel for (what it is now is whatever `skipped_ipa("ʏ")`+ // says, so this holds when it gets one)+ let lone = skipped_ipa("ʏ");+ let r = skipped_ipa("bɔ̃ʒuʁ n̥ pʰa ʏ");+ assert_eq!(r, SkippedIpa { unknown: vec![], no_sound: lone.no_sound, ignored_marks: strs(&["n\u{325}"]) });+ let r = skipped_ipa("A n̥ ˥ ʏ");+ assert_eq!((r.unknown, r.ignored_marks), (strs(&["A", "˥"]), strs(&["n\u{325}"])));+}++/// The "no sound" kind is derived from the tokenizer's symbols and the planner's vowel table and+/// inventory, never a list of its own: feed every symbol the tokenizer knows, and the kind is+/// exactly the ones the planner cannot voice.+#[test]+fn no_sound_is_derived_not_listed() {+ let known = known_ipa_symbols();+ assert!(known.len() > 40);+ let all: String = known.iter().map(|s| format!("{s} ")).collect();+ let r = skipped_ipa(&all);+ assert!(r.unknown.is_empty(), "every known symbol is known: {r:?}");+ let silent: Vec<&str> = known+ .iter()+ .copied()+ .filter(|s| {+ let voiced = [BodyMix::MALE, BodyMix::FEMALE, BodyMix::CHILD].into_iter().any(|b| is_vowel(s, b)) || chimera::phonetics::inventory::consonant_symbols().contains(s);+ !voiced+ })+ .collect();+ // every reported symbol is one the tokenizer emits; every silent one is reported+ for s in &r.no_sound {+ assert!(known.contains(&s.as_str()), "{s}");+ assert!(tokenize_ipa(s).iter().any(|g| &g.ipa == s), "{s}");+ }+ let mut got: Vec<&str> = r.no_sound.iter().map(String::as_str).collect();+ got.sort_unstable();+ assert_eq!(got, silent);+ // vowel letters the tokenizer accepts but no body has a calibrated vowel for are in the kind+ assert!(!silent.is_empty(), "if every letter has a sound now, this kind is empty and the assertions above still hold");+ // and a symbol with a sound is not+ for ok in ["a", "ɛ", "p", "tʃ", "aɪ", "ɚ"] {+ assert!(!r.no_sound.contains(&ok.to_string()), "{ok}");+ }+}++#[test]+fn warnings_make_one_line_per_kind() {+ let r = skipped_ipa("ɕa˥ n̥");+ assert_eq!(r.warnings(), ["not said: ˥", "mark ignored: n̥"]);+ assert_eq!(skipped_ipa("ʏ").warnings(), ["no sound yet: ʏ"]);+ assert!(SkippedIpa::default().warnings().is_empty());+}diff --git a/src/ui/components/SpeakPanel.tsx b/src/ui/components/SpeakPanel.tsxindex 0d718af..d348478 100644--- a/src/ui/components/SpeakPanel.tsx+++ b/src/ui/components/SpeakPanel.tsx@@ -1,4 +1,5 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";+import { skippedLines } from "../skipped.ts";import { useStore } from "../store.ts";import { speakText, speakPhrases, stopSpeaking, onPlan, currentPlan, spokenWordNow, speakingNow } from "../speech.ts";import { mouthWords } from "../mouthWords.ts";@@ -141,6 +142,8 @@ export function SpeakRight() {const [vowel, setVowel] = useState("ɑ");const speaking = useSpeaking();useEffect(() => onPlan((p) => setTrans(p?.transcription ?? "")), []);+ // in IPA mode: the symbols in the box that the voice will not say, updated as the text changes+ const skipped = useMemo(() => (ipa ? skippedLines(text) : []), [ipa, text]);const speak = async () => {setBusy(true);@@ -199,9 +202,18 @@ export function SpeakRight() {/></div><div className="say-row">- <p className="transcription" aria-live="polite">- {trans ? `/${trans}/` : ""}- </p>+ <div className="say-read">+ <p className="transcription" aria-live="polite">+ {trans ? `/${trans}/` : ""}+ </p>+ <div className="say-skipped" aria-live="polite">+ {skipped.map((l) => (+ <p key={l.what}>+ {l.what}: <span className="say-skipped-sym">{l.symbols.join(" ")}</span>+ </p>+ ))}+ </div>+ </div></div></div></Screen>diff --git a/src/ui/skipped.ts b/src/ui/skipped.tsnew file mode 100644index 0000000..a6c41d2--- /dev/null+++ b/src/ui/skipped.ts@@ -0,0 +1,35 @@+/** What the Speak box tells a person about IPA the engine will not say as written. */+import { skippedIpa, type SkippedIpa } from "../wasm/engine.ts";++/** the pieces of IPA text that become phrases (`.`, `|`, `?` and `!` end one) */+export function ipaPhraseTexts(text: string): string[] {+ return text+ .split(/[|.?!]+/)+ .map((p) => p.trim())+ .filter(Boolean);+}++/** One line of the notice: what the engine did with `symbols`. */+export interface SkippedLine {+ what: string;+ symbols: string[];+}++/** The notice's lines for IPA typed into Speak, one per kind that is not empty (none: nothing is skipped). */+export function skippedLines(text: string): SkippedLine[] {+ // the phrase separators are structure, as the Speak box reads them: check what it says, not them+ return skippedLinesOf(skippedIpa(ipaPhraseTexts(text).join(" | ")));+}++export function skippedLinesOf(r: SkippedIpa): SkippedLine[] {+ const out: SkippedLine[] = [];+ if (r.unknown.length) out.push({ what: "Not said", symbols: r.unknown });+ if (r.noSound.length) out.push({ what: "No sound yet", symbols: r.noSound });+ if (r.ignoredMarks.length) out.push({ what: "Mark ignored", symbols: r.ignoredMarks });+ return out;+}++/** a line as plain text (`Not said: ɕ ˥`) */+export function skippedText(l: SkippedLine): string {+ return `${l.what}: ${l.symbols.join(" ")}`;+}diff --git a/src/ui/speech.ts b/src/ui/speech.tsindex a94d8d5..974ae65 100644--- a/src/ui/speech.ts+++ b/src/ui/speech.ts@@ -5,6 +5,7 @@ import { tokenizeIpa } from "../wasm/engine.ts";import { planPhrases, type Plan, type Segment } from "../wasm/engine.ts";import { engine } from "../audio/AudioEngine.ts";import type { Gesture } from "../wasm/types.ts";+import { ipaPhraseTexts } from "./skipped.ts";import { wordSpans, type WordSpan } from "./words.ts";export const g2p = new EnglishG2P();@@ -40,11 +41,7 @@ export function currentPlan(): SpokenPlan | null {}export function ipaToPhrases(text: string): Phrase[] {- return text- .split(/[|.?!]+/)- .map((p) => p.trim())- .filter(Boolean)- .map((p) => ({ segments: tokenizeIpa(p), intonation: "statement" as const, pause: 0.3, words: [] }));+ return ipaPhraseTexts(text).map((p) => ({ segments: tokenizeIpa(p), intonation: "statement" as const, pause: 0.3, words: [] }));}export function transcribe(phrases: { segments: Segment[]; intonation?: string }[]): string {diff --git a/src/ui/styles.css b/src/ui/styles.cssindex c5c73f7..65c14d4 100644--- a/src/ui/styles.css+++ b/src/ui/styles.css@@ -1914,6 +1914,24 @@ input[type="range"]::-moz-range-thumb {white-space: nowrap;}+/* the transcription, and under it what IPA mode did not say */+.say-read {+ flex: 1;+ min-width: 0;+}++.say-skipped p {+ margin: 2px 0 0;+ font-size: 13px;+ color: var(--text-dim);+ word-break: break-word;+}++.say-skipped-sym {+ color: var(--text);+ letter-spacing: 0.04em;+}+.vowel-pick {display: flex;gap: 4px;diff --git a/src/wasm/engine.ts b/src/wasm/engine.tsindex e18c180..68f4f14 100644--- a/src/wasm/engine.ts+++ b/src/wasm/engine.ts@@ -8,7 +8,7 @@ import { call } from "./chimera.ts";import { CREATURE_VISUALS } from "../ui/creatureVisuals.ts";import type {ArticKey, ArticSpec, BeatPreset, BodyMix, BeatSound, BeatStep, CreatureDef, CreatureTelemetry, DemoSong, Gesture, HumanArtic, HumanBody,- HumanFrame, Phrase, Plan, Segment, SungNote, Syllable, VoiceSource, VowelRef,+ HumanFrame, Phrase, Plan, Segment, SkippedIpa, SungNote, Syllable, VoiceSource, VowelRef,} from "./types.ts";export type * from "./types.ts";@@ -60,6 +60,15 @@ export function tokenizeIpa(text: string): Segment[] {return call("tokenizeIpa", { text });}+/**+ * What `tokenizeIpa` leaves out of IPA text without a word, in input order, each item once: symbols+ * the engine does not know, symbols it knows but has no sound for, and letters whose mark it+ * cannot say (shown with the letter). Stress, length, spaces and the marks it reads are not listed.+ */+export function skippedIpa(text: string): SkippedIpa {+ return call("skippedIpa", { text });+}+/*** English text → phonemes: CMUdict once loaded (fetched and gunzipped here, parsed by the* engine), letter-to-sound rules until then. One dictionary per page (the engine keeps it).diff --git a/src/wasm/types.ts b/src/wasm/types.tsindex f5e5715..c7e767c 100644--- a/src/wasm/types.ts+++ b/src/wasm/types.ts@@ -167,6 +167,16 @@ export interface Segment {breathy?: boolean;}+/** What the engine will not say as written in a piece of IPA text (see `skippedIpa`). */+export interface SkippedIpa {+ /** symbols it does not know (a tone letter, a click, a capital, a typo) */+ unknown: string[];+ /** symbols it knows but has no sound for (a vowel letter without a calibrated vowel) */+ noSound: string[];+ /** letters written with a mark it does not model or cannot apply there: the letter is said, the mark is not */+ ignoredMarks: string[];+}+export interface PlannedSegment {ipa: string;t0: number;diff --git a/tests/skipped-ipa.test.ts b/tests/skipped-ipa.test.tsnew file mode 100644index 0000000..1b97f09--- /dev/null+++ b/tests/skipped-ipa.test.ts@@ -0,0 +1,60 @@+/**+ * `skippedIpa` through the wasm facade, and the notice's lines: what Speak's IPA mode tells a+ * person the voice will not say (upstream issue 52: pasted `ɕiɛ˥˩ɕiɛ` came out as another word).+ */+import { describe, expect, test } from "bun:test";+import { initEngine } from "./harness.ts";++await initEngine();+const { skippedIpa } = await import("../src/wasm/engine.ts");+const { skippedLines, skippedText } = await import("../src/ui/skipped.ts");++describe("skippedIpa", () => {+ test("tone letters are unknown, in input order, each once", () => {+ const r = skippedIpa("ɕiɛ˥˩ɕiɛ˥");+ expect(r.unknown.slice(-2)).toEqual(["˥", "˩"]);+ expect(r.unknown.filter((s) => s === "˥")).toHaveLength(1);+ expect(r.noSound).toEqual([]);+ expect(r.ignoredMarks).toEqual([]);+ });++ test("a mark it cannot say is shown with its letter; the marks it reads are not listed", () => {+ expect(skippedIpa("n̥a").ignoredMarks).toEqual(["n̥"]);+ expect(skippedIpa("pʰa bɔ̃ ˈtʃʲaː, bʱa")).toEqual({ unknown: [], noSound: [], ignoredMarks: [] });+ });++ test("a symbol with no sound is reported by its own kind, and the same call says nothing for plain IPA", () => {+ const r = skippedIpa("ʏ");+ expect(r.unknown).toEqual([]);+ expect(skippedIpa("ˈhɛloʊ wɝld")).toEqual({ unknown: [], noSound: [], ignoredMarks: [] });+ expect(r.noSound.length + r.unknown.length + r.ignoredMarks.length).toBeLessThanOrEqual(1);+ });+});++describe("the Speak notice", () => {+ test("no lines when nothing is skipped, and for empty text", () => {+ expect(skippedLines("ˈhɛloʊ")).toEqual([]);+ expect(skippedLines("")).toEqual([]);+ });++ test("the phrase separators . | ? ! are structure, not unknown symbols", () => {+ expect(skippedLines("haɪ. ðɛə? goʊ! bɑ | dɑ")).toEqual([]);+ });++ test("the delimiters of /phonemic/ and [phonetic] IPA are not listed", () => {+ for (const t of ["/a˥/", "[a˥]"]) expect(skippedLines(t).map(skippedText)).toEqual(["Not said: ˥"]);+ });++ test("a symbol with no sound gets its own short line", () => {+ expect(skippedLines("ʏ").map(skippedText)).toEqual(["No sound yet: ʏ"]);+ });++ test("the syllabic and non-syllabic marks are not reported", () => {+ expect(skippedLines("aɪ̯ bʌtn̩")).toEqual([]);+ });++ test("one line per kind, in plain words", () => {+ const lines = skippedLines("a˥ n̥");+ expect(lines.map(skippedText)).toEqual(["Not said: ˥", "Mark ignored: n̥"]);+ });+});diff --git a/tools/e2e.ts b/tools/e2e.tsindex 409abb7..a6619b5 100644--- a/tools/e2e.ts+++ b/tools/e2e.ts@@ -120,6 +120,27 @@ async function run(viewport: { width: number; height: number }, tag: string) {await page.locator("button.ipa", { hasText: "ʃ" }).first().click();await page.waitForTimeout(700);await page.screenshot({ path: `${outDir}/${tag}-4-pad.png` });+ // IPA mode tells the person which symbols the voice will not say (it used to drop them without a+ // word: upstream issue 52), as they type; plain text and clean IPA get no notice+ const notice = page.locator(".say-skipped");+ const box_ = page.getByRole("textbox", { name: /to speak/ });+ const noticeText = async () => ((await notice.textContent()) ?? "").trim();+ if ((await notice.getAttribute("aria-live")) !== "polite") errors.push(`[${tag}] the skipped-symbols notice is not a polite live region`);+ if (await noticeText()) errors.push(`[${tag}] the skipped-symbols notice shows with IPA mode off: ${await noticeText()}`);+ await ipaChip.click(); // IPA mode on (a toggle button)+ await box_.fill("ɕiɛ˥˩");+ const shown = await noticeText();+ logs.push(`[${tag}] skipped-symbols notice: ${shown}`);+ if (!/Not said/.test(shown) || !shown.includes("˥") || !shown.includes("˩")) errors.push(`[${tag}] typing IPA with tone letters showed no notice naming them: "${shown}"`);+ await page.screenshot({ path: `${outDir}/${tag}-4-speak-skipped.png`, fullPage: true });+ await box_.fill("ˈhɛloʊ");+ if (await noticeText()) errors.push(`[${tag}] the notice stayed for IPA the voice says: ${await noticeText()}`);+ await box_.fill("ɕiɛ˥˩");+ await box_.fill("");+ if (await noticeText()) errors.push(`[${tag}] clearing the box left the notice: ${await noticeText()}`);+ await box_.fill("ɕiɛ˥˩");+ await ipaChip.click(); // and off+ if (await noticeText()) errors.push(`[${tag}] turning IPA mode off left the notice: ${await noticeText()}`);// sing mode: a key sings the marked syllable and moves the cursor; legato; a demo songawait page.getByRole("radio", { name: "Sing" }).click();await page.waitForTimeout(600);