163 lines
5.8 KiB
Rust
163 lines
5.8 KiB
Rust
//! Text → phonemes for the reading voices (Day 4, `docs/04_listening.md` in the app repo).
|
||
//!
|
||
//! The voices (Piper VITS models) were trained on espeak-ng's IPA. espeak-ng is GPL, so it is not used: this module
|
||
//! writes the same conventions itself — stress marks (`ˈ`, `ˌ`) right before the stressed vowel, `ː` for length,
|
||
//! words separated by spaces, `. , ? ! ; :` kept as they are. Czech and German are rules; English is a pronouncing
|
||
//! dictionary (CMUdict, BSD-style, supplied by the app) with rules for words it does not have. Numbers are spelled
|
||
//! out first. [`tokens`] splits the result into the voice's symbols.
|
||
|
||
pub mod cs;
|
||
pub mod de;
|
||
pub mod en;
|
||
pub mod num;
|
||
|
||
use crate::Lang;
|
||
use crate::token::{Kind, tokens as words};
|
||
use std::collections::HashMap;
|
||
use unicode_normalization::UnicodeNormalization;
|
||
|
||
/// Primary and secondary stress, length.
|
||
pub const STRESS: char = 'ˈ';
|
||
pub const STRESS2: char = 'ˌ';
|
||
pub const LONG: char = 'ː';
|
||
|
||
/// English pronunciations (word → IPA with stress), from CMUdict.
|
||
#[derive(Default)]
|
||
pub struct Lexicon(HashMap<String, String>);
|
||
|
||
/// Caps for a pronouncing dictionary read from a file (hostile input).
|
||
pub const LEXICON_MAX_BYTES: usize = 16 << 20;
|
||
pub const LEXICON_MAX_ENTRIES: usize = 400_000;
|
||
|
||
impl Lexicon {
|
||
/// CMUdict's format: `WORD PH1 PH2 …` (ARPABET with stress digits); `;;;` comments; `WORD(2)` alternates are
|
||
/// skipped (the first pronunciation is the common one).
|
||
pub fn from_cmudict(text: &str) -> Option<Lexicon> {
|
||
if text.len() > LEXICON_MAX_BYTES {
|
||
return None;
|
||
}
|
||
let mut map = HashMap::new();
|
||
for line in text.lines() {
|
||
if line.starts_with(";;;") || line.trim().is_empty() {
|
||
continue;
|
||
}
|
||
let mut parts = line.split_whitespace();
|
||
let Some(word) = parts.next() else { continue };
|
||
if word.contains('(') || word.len() > 48 {
|
||
continue;
|
||
}
|
||
let arpa: Vec<&str> = parts.collect();
|
||
if arpa.is_empty() || arpa.len() > 48 {
|
||
continue;
|
||
}
|
||
if map.len() >= LEXICON_MAX_ENTRIES {
|
||
return None;
|
||
}
|
||
if let Some(ipa) = en::from_arpabet(&arpa) {
|
||
map.entry(word.to_lowercase()).or_insert(ipa);
|
||
}
|
||
}
|
||
Some(Lexicon(map))
|
||
}
|
||
|
||
pub fn get(&self, word: &str) -> Option<&str> {
|
||
self.0.get(word).map(String::as_str)
|
||
}
|
||
|
||
pub fn len(&self) -> usize {
|
||
self.0.len()
|
||
}
|
||
|
||
pub fn is_empty(&self) -> bool {
|
||
self.0.is_empty()
|
||
}
|
||
|
||
/// Adds an entry (tests, a reader's own corrections).
|
||
pub fn insert(&mut self, word: &str, ipa: &str) {
|
||
self.0.insert(word.to_lowercase(), ipa.to_owned());
|
||
}
|
||
}
|
||
|
||
/// One word's IPA in a language.
|
||
pub fn word(w: &str, lang: Lang, lex: Option<&Lexicon>) -> String {
|
||
let lower: String = w.nfc().flat_map(char::to_lowercase).collect();
|
||
let lower = lower.replace(['\u{2019}', '\u{2018}'], "'");
|
||
match lang {
|
||
Lang::Cs => cs::word(&lower),
|
||
Lang::De => de::word(&lower),
|
||
// Latin has no voice of its own; read with the Czech rules (close to the school pronunciation in Czechia).
|
||
Lang::La => cs::word(&lower),
|
||
Lang::En => lex.and_then(|l| l.get(&lower)).map(str::to_owned).unwrap_or_else(|| en::rules(&lower)),
|
||
}
|
||
}
|
||
|
||
/// A sentence (or any text) in IPA, the way espeak-ng writes it: words separated by spaces, punctuation attached.
|
||
pub fn ipa(text: &str, lang: Lang, lex: Option<&Lexicon>) -> String {
|
||
let mut out = String::new();
|
||
let push_word = |out: &mut String, w: &str| {
|
||
if w.is_empty() {
|
||
return;
|
||
}
|
||
if !out.is_empty() && !out.ends_with(' ') {
|
||
out.push(' ');
|
||
}
|
||
out.push_str(w);
|
||
};
|
||
for t in words(text) {
|
||
match t.kind {
|
||
Kind::Word => push_word(&mut out, &word(&t.text, lang, lex)),
|
||
Kind::Number => {
|
||
let digits: String = t.text.chars().filter(|c| c.is_ascii_digit()).collect();
|
||
match digits.parse::<u64>().ok().and_then(|n| num::words(n, lang)) {
|
||
Some(spelled) => {
|
||
for w in spelled.split_whitespace() {
|
||
push_word(&mut out, &word(w, lang, lex));
|
||
}
|
||
}
|
||
None => push_word(&mut out, &word(&t.text, lang, lex)),
|
||
}
|
||
}
|
||
Kind::Punct => {
|
||
let p = match t.text.as_str() {
|
||
"." | "…" => Some('.'),
|
||
"," | "–" | "—" | "-" => Some(','),
|
||
"?" => Some('?'),
|
||
"!" => Some('!'),
|
||
";" => Some(';'),
|
||
":" => Some(':'),
|
||
_ => None,
|
||
};
|
||
if let Some(p) = p
|
||
&& !out.is_empty()
|
||
&& !out.ends_with(['.', ',', '?', '!', ';', ':'])
|
||
{
|
||
let trimmed = out.trim_end().len();
|
||
out.truncate(trimmed);
|
||
out.push(p);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
out.trim().to_owned()
|
||
}
|
||
|
||
/// The voice's symbols: NFD code points, with the voice's vowel clusters (`aɪ`, `oʊ` …) merged into one symbol.
|
||
pub fn tokens(ipa: &str, clusters: &[(String, String)]) -> Vec<String> {
|
||
let chars: Vec<char> = ipa.nfd().collect();
|
||
let mut out = Vec::with_capacity(chars.len());
|
||
let mut i = 0;
|
||
while i < chars.len() {
|
||
let c = chars[i];
|
||
if let Some(&n) = chars.get(i + 1)
|
||
&& clusters.iter().any(|(a, b)| a.chars().eq(std::iter::once(c)) && b.chars().eq(std::iter::once(n)))
|
||
{
|
||
out.push(format!("{c}{n}"));
|
||
i += 2;
|
||
continue;
|
||
}
|
||
out.push(c.to_string());
|
||
i += 1;
|
||
}
|
||
out
|
||
}
|