Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7be8fca42b | |||
| 8f43cb2c4c | |||
| 388e8e01c4 | |||
| 1d6693a195 | |||
| 7aa13d6c0a | |||
| 068dc6cfb7 | |||
| 31cf11cbbe | |||
| bb0a63a173 | |||
| 5f2cd1b7c1 |
Generated
+5
-5
@@ -327,7 +327,7 @@ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "liber-audio"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -337,7 +337,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "liber-format"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"chardetng",
|
||||
@@ -357,7 +357,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "liber-habit"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"liber-library",
|
||||
"proptest",
|
||||
@@ -367,7 +367,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "liber-lang"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -379,7 +379,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "liber-library"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"csv",
|
||||
"encoding_rs",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/liber-format", "crates/liber-library", "crates/liber-habit", "crates/liber-lang", "crates/liber-audio"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
edition = "2024"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/Liber-public"
|
||||
|
||||
@@ -54,6 +54,42 @@ pub struct Info {
|
||||
pub title: Option<String>,
|
||||
pub duration_ms: Option<u64>,
|
||||
pub chapters: Vec<Chapter>,
|
||||
/// A QuickTime chapter *track* whose titles live in the media data (outside the metadata given): each
|
||||
/// chapter's start and where its title sample is in the file. Read them with [`titles_from_samples`].
|
||||
pub chapter_samples: Vec<ChapterSample>,
|
||||
}
|
||||
|
||||
/// One sample of a QuickTime chapter track: a 16-bit big-endian length, then the UTF-8 title.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ChapterSample {
|
||||
pub start_ms: u64,
|
||||
pub offset: u64,
|
||||
pub size: u32,
|
||||
}
|
||||
|
||||
/// The longest chapter title sample read.
|
||||
pub const MAX_TITLE_SAMPLE: u32 = 1024;
|
||||
|
||||
/// Chapters from a chapter track's samples, reading each (small) sample through `read(offset, size)`.
|
||||
pub fn titles_from_samples(
|
||||
samples: &[ChapterSample],
|
||||
duration_ms: u64,
|
||||
mut read: impl FnMut(u64, u32) -> Option<Vec<u8>>,
|
||||
) -> Vec<Chapter> {
|
||||
let chapters = samples
|
||||
.iter()
|
||||
.take(MAX_CHAPTERS)
|
||||
.map(|c| {
|
||||
let title = read(c.offset, c.size.min(MAX_TITLE_SAMPLE))
|
||||
.and_then(|b| {
|
||||
let n = u16::from_be_bytes([*b.first()?, *b.get(1)?]) as usize;
|
||||
b.get(2..2 + n.min(b.len().saturating_sub(2))).map(|t| String::from_utf8_lossy(t).into_owned())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Chapter { title, start_ms: c.start_ms, end_ms: 0 }
|
||||
})
|
||||
.collect();
|
||||
tidy(chapters, duration_ms).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// By content, never by the file name.
|
||||
@@ -76,7 +112,13 @@ pub fn inspect(bytes: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
||||
match sniff(bytes).ok_or(AudioError::Unsupported)? {
|
||||
Kind::Mp4 => mp4(bytes, caps),
|
||||
Kind::Mp3 => mp3(bytes, caps),
|
||||
Kind::Wav => Ok(Info { kind: Kind::Wav, title: None, duration_ms: wav_duration(bytes), chapters: vec![] }),
|
||||
Kind::Wav => Ok(Info {
|
||||
kind: Kind::Wav,
|
||||
title: None,
|
||||
duration_ms: wav_duration(bytes),
|
||||
chapters: vec![],
|
||||
chapter_samples: vec![],
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,10 +140,29 @@ struct Walk<'a> {
|
||||
duration: Option<u64>,
|
||||
chapters: Vec<Chapter>,
|
||||
title: Option<String>,
|
||||
tracks: Vec<Track>,
|
||||
/// The `trak` being walked: track boxes elsewhere (the `hdlr` of `udta/meta`) belong to no track.
|
||||
cur: Option<usize>,
|
||||
_b: std::marker::PhantomData<&'a ()>,
|
||||
}
|
||||
|
||||
const CONTAINERS: [&[u8; 4]; 9] = [b"moov", b"udta", b"trak", b"mdia", b"minf", b"stbl", b"ilst", b"edts", b"dinf"];
|
||||
/// What a `trak` says, kept as byte ranges of its sample tables (decoded only for the chapter track).
|
||||
#[derive(Default)]
|
||||
struct Track {
|
||||
id: u32,
|
||||
handler: [u8; 4],
|
||||
timescale: u32,
|
||||
chap: Vec<u32>,
|
||||
stts: Option<(usize, usize)>,
|
||||
stsz: Option<(usize, usize)>,
|
||||
stsc: Option<(usize, usize)>,
|
||||
stco: Option<(usize, usize, bool)>,
|
||||
}
|
||||
|
||||
/// Most tracks a file may have.
|
||||
const MAX_TRACKS: usize = 64;
|
||||
|
||||
const CONTAINERS: [&[u8; 4]; 9] = [b"moov", b"udta", b"tref", b"mdia", b"minf", b"stbl", b"ilst", b"edts", b"dinf"];
|
||||
|
||||
fn mp4(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
||||
// The brand: Audible's AAX is `aax `, AAXC `aaxc` (major or compatible).
|
||||
@@ -121,6 +182,8 @@ fn mp4(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
||||
duration: None,
|
||||
chapters: vec![],
|
||||
title: None,
|
||||
tracks: vec![],
|
||||
cur: None,
|
||||
_b: Default::default(),
|
||||
};
|
||||
walk(&mut w, b, 0, b.len(), 0)?;
|
||||
@@ -131,8 +194,97 @@ fn mp4(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
||||
(Some(ts), Some(d)) if ts > 0 => Some(d.saturating_mul(1000) / u64::from(ts)),
|
||||
_ => None,
|
||||
};
|
||||
let chapters = duration_ms.and_then(|d| tidy(std::mem::take(&mut w.chapters), d)).unwrap_or_default();
|
||||
Ok(Info { kind: Kind::Mp4, title: w.title, duration_ms, chapters })
|
||||
let mut chapters = duration_ms.and_then(|d| tidy(std::mem::take(&mut w.chapters), d)).unwrap_or_default();
|
||||
// A QuickTime chapter track (what iTunes, LibriVox and most M4B tools write) when there is no Nero list.
|
||||
let mut chapter_samples = Vec::new();
|
||||
if chapters.is_empty() {
|
||||
let referenced: Vec<u32> = w.tracks.iter().flat_map(|t| t.chap.iter().copied()).collect();
|
||||
if let Some(t) =
|
||||
w.tracks.iter().find(|t| referenced.contains(&t.id) && (t.handler == *b"text" || t.handler == *b"sbtl"))
|
||||
{
|
||||
chapter_samples = chapter_track(b, t)?;
|
||||
// When the titles are inside the bytes we were given (a whole file), read them now.
|
||||
let d = duration_ms.unwrap_or(0);
|
||||
if d > 0 && chapter_samples.iter().all(|c| (c.offset as usize).saturating_add(c.size as usize) <= b.len()) {
|
||||
chapters = titles_from_samples(&chapter_samples, d, |o, n| {
|
||||
b.get(o as usize..o as usize + n as usize).map(<[u8]>::to_vec)
|
||||
});
|
||||
chapter_samples.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Info { kind: Kind::Mp4, title: w.title, duration_ms, chapters, chapter_samples })
|
||||
}
|
||||
|
||||
/// A chapter track's samples: start times from `stts`, file offsets from `stsc` + `stco`/`co64` + `stsz`.
|
||||
fn chapter_track(b: &[u8], t: &Track) -> Result<Vec<ChapterSample>, AudioError> {
|
||||
let bad = AudioError::Damaged("chapter track");
|
||||
let (Some(stts), Some(stsz), Some(stsc), Some(stco)) = (t.stts, t.stsz, t.stsc, t.stco) else { return Ok(vec![]) };
|
||||
if t.timescale == 0 {
|
||||
return Err(bad);
|
||||
}
|
||||
let table = |(from, to): (usize, usize), entry: usize| -> Result<(usize, usize), AudioError> {
|
||||
let n = be32(b, from + 4).ok_or(AudioError::Damaged("chapter track"))? as usize;
|
||||
if n > MAX_CHAPTERS || from + 8 + n * entry > to {
|
||||
return Err(AudioError::Damaged("chapter track"));
|
||||
}
|
||||
Ok((from + 8, n))
|
||||
};
|
||||
// Times.
|
||||
let (at, n) = table(stts, 8)?;
|
||||
let mut starts = Vec::new();
|
||||
let mut t_units = 0u64;
|
||||
for i in 0..n {
|
||||
let count = be32(b, at + i * 8).ok_or(AudioError::Damaged("stts"))?;
|
||||
let delta = be32(b, at + i * 8 + 4).ok_or(AudioError::Damaged("stts"))? as u64;
|
||||
for _ in 0..count {
|
||||
if starts.len() >= MAX_CHAPTERS {
|
||||
return Err(AudioError::Damaged("too many chapters"));
|
||||
}
|
||||
starts.push(t_units * 1000 / u64::from(t.timescale));
|
||||
t_units = t_units.saturating_add(delta);
|
||||
}
|
||||
}
|
||||
// Sizes.
|
||||
let fixed = be32(b, stsz.0 + 4).ok_or(AudioError::Damaged("stsz"))?;
|
||||
let count = be32(b, stsz.0 + 8).ok_or(AudioError::Damaged("stsz"))? as usize;
|
||||
if count > MAX_CHAPTERS || (fixed == 0 && stsz.0 + 12 + count * 4 > stsz.1) {
|
||||
return Err(AudioError::Damaged("stsz"));
|
||||
}
|
||||
let size = |i: usize| if fixed != 0 { Some(fixed) } else { be32(b, stsz.0 + 12 + i * 4) };
|
||||
// Chunk offsets.
|
||||
let (co_from, co_to, wide) = stco;
|
||||
let (co_at, chunks) = table((co_from, co_to), if wide { 8 } else { 4 })?;
|
||||
let chunk_offset = |k: usize| if wide { be64(b, co_at + k * 8) } else { be32(b, co_at + k * 4).map(u64::from) };
|
||||
// Samples per chunk: (first_chunk (1-based), samples_per_chunk) runs.
|
||||
let (sc_at, runs) = table(stsc, 12)?;
|
||||
let mut out = Vec::new();
|
||||
let mut sample = 0usize;
|
||||
for r in 0..runs {
|
||||
let first = be32(b, sc_at + r * 12).ok_or(AudioError::Damaged("stsc"))? as usize;
|
||||
let per = be32(b, sc_at + r * 12 + 4).ok_or(AudioError::Damaged("stsc"))? as usize;
|
||||
let next_first = if r + 1 < runs {
|
||||
be32(b, sc_at + (r + 1) * 12).ok_or(AudioError::Damaged("stsc"))? as usize
|
||||
} else {
|
||||
chunks + 1
|
||||
};
|
||||
if first == 0 || next_first < first || per > MAX_CHAPTERS {
|
||||
return Err(AudioError::Damaged("stsc"));
|
||||
}
|
||||
for chunk in first..next_first.min(chunks + 1) {
|
||||
let mut off = chunk_offset(chunk - 1).ok_or(AudioError::Damaged("stco"))?;
|
||||
for _ in 0..per {
|
||||
if sample >= count.min(starts.len()) {
|
||||
return Ok(out);
|
||||
}
|
||||
let sz = size(sample).ok_or(AudioError::Damaged("stsz"))?;
|
||||
out.push(ChapterSample { start_ms: starts[sample], offset: off, size: sz });
|
||||
off = off.saturating_add(u64::from(sz));
|
||||
sample += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn walk(w: &mut Walk, b: &[u8], from: usize, to: usize, depth: usize) -> Result<(), AudioError> {
|
||||
@@ -161,7 +313,55 @@ fn walk(w: &mut Walk, b: &[u8], from: usize, to: usize, depth: usize) -> Result<
|
||||
if body > end {
|
||||
return Err(AudioError::Damaged("box size"));
|
||||
}
|
||||
let cur = w.cur;
|
||||
match &kind {
|
||||
b"trak" => {
|
||||
if w.tracks.len() >= MAX_TRACKS {
|
||||
return Err(AudioError::Damaged("too many tracks"));
|
||||
}
|
||||
w.tracks.push(Track::default());
|
||||
let outer = w.cur.replace(w.tracks.len() - 1);
|
||||
walk(w, b, body, end, depth + 1)?;
|
||||
w.cur = outer;
|
||||
}
|
||||
b"tkhd" => {
|
||||
let v = *b.get(body).ok_or(AudioError::Damaged("tkhd"))?;
|
||||
if let (Some(i), Some(id)) = (cur, be32(b, body + if v == 1 { 20 } else { 12 })) {
|
||||
w.tracks[i].id = id;
|
||||
}
|
||||
}
|
||||
b"chap" => {
|
||||
if let Some(i) = cur {
|
||||
w.tracks[i].chap = b[body..end]
|
||||
.chunks(4)
|
||||
.take(16)
|
||||
.filter_map(|c| c.try_into().ok().map(u32::from_be_bytes))
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
b"hdlr" => {
|
||||
if let (Some(i), Some(h)) = (cur, b.get(body + 8..body + 12)) {
|
||||
w.tracks[i].handler = h.try_into().expect("4 bytes");
|
||||
}
|
||||
}
|
||||
b"mdhd" => {
|
||||
let v = *b.get(body).ok_or(AudioError::Damaged("mdhd"))?;
|
||||
if let (Some(i), Some(ts)) = (cur, be32(b, body + if v == 1 { 20 } else { 12 })) {
|
||||
w.tracks[i].timescale = ts;
|
||||
}
|
||||
}
|
||||
b"stts" | b"stsz" | b"stsc" | b"stco" | b"co64" => {
|
||||
if let Some(i) = cur {
|
||||
let t = &mut w.tracks[i];
|
||||
match &kind {
|
||||
b"stts" => t.stts = Some((body, end)),
|
||||
b"stsz" => t.stsz = Some((body, end)),
|
||||
b"stsc" => t.stsc = Some((body, end)),
|
||||
b"stco" => t.stco = Some((body, end, false)),
|
||||
_ => t.stco = Some((body, end, true)),
|
||||
}
|
||||
}
|
||||
}
|
||||
// Audible (`adrm`, `aabd`, the `aavd` sample entry), old iTunes FairPlay (`drms`, `drmi`).
|
||||
b"adrm" | b"aabd" | b"aavd" | b"drms" | b"drmi" => w.drm = true,
|
||||
k if CONTAINERS.contains(&k) => walk(w, b, body, end, depth + 1)?,
|
||||
@@ -236,7 +436,7 @@ fn synchsafe(b: &[u8]) -> usize {
|
||||
}
|
||||
|
||||
fn mp3(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
||||
let mut info = Info { kind: Kind::Mp3, title: None, duration_ms: None, chapters: vec![] };
|
||||
let mut info = Info { kind: Kind::Mp3, title: None, duration_ms: None, chapters: vec![], chapter_samples: vec![] };
|
||||
if !b.starts_with(b"ID3") {
|
||||
return Ok(info);
|
||||
}
|
||||
|
||||
@@ -247,3 +247,85 @@ fn cue_sheets() {
|
||||
assert_eq!(ch[1].start_ms, 12 * 60_000 + 30_000 + 37 * 1000 / 75);
|
||||
assert!(cue("garbage", 1000).is_none());
|
||||
}
|
||||
|
||||
/// An M4B whose chapters are a QuickTime chapter track: an audio track that refers (`tref`/`chap`) to a text track;
|
||||
/// the text track's samples (a 16-bit length, then the title) sit in `mdat`.
|
||||
fn m4b_with_chapter_track(titles: &[&str], starts_ms: &[u32]) -> Vec<u8> {
|
||||
let full = |v: u8| vec![v, 0, 0, 0];
|
||||
let tkhd = |id: u32| bx(b"tkhd", &[full(0), vec![0; 8], id.to_be_bytes().to_vec(), vec![0; 64]].concat());
|
||||
let mdhd = bx(
|
||||
b"mdhd",
|
||||
&[full(0), vec![0; 8], 1000u32.to_be_bytes().to_vec(), 0u32.to_be_bytes().to_vec(), vec![0; 4]].concat(),
|
||||
);
|
||||
let hdlr = |h: &[u8; 4]| bx(b"hdlr", &[full(0), vec![0; 4], h.to_vec(), vec![0; 13]].concat());
|
||||
// The text samples, laid out after ftyp + moov: we fix their offset after building moov once.
|
||||
let samples: Vec<Vec<u8>> =
|
||||
titles.iter().map(|t| [(t.len() as u16).to_be_bytes().to_vec(), t.as_bytes().to_vec()].concat()).collect();
|
||||
let build = |mdat_at: u32| {
|
||||
let mut stts = full(0);
|
||||
stts.extend((starts_ms.len() as u32).to_be_bytes());
|
||||
for (i, s) in starts_ms.iter().enumerate() {
|
||||
let next = starts_ms.get(i + 1).copied().unwrap_or(s + 1000);
|
||||
stts.extend(1u32.to_be_bytes());
|
||||
stts.extend((next - s).to_be_bytes());
|
||||
}
|
||||
let mut stsz = full(0);
|
||||
stsz.extend(0u32.to_be_bytes());
|
||||
stsz.extend((samples.len() as u32).to_be_bytes());
|
||||
for smp in &samples {
|
||||
stsz.extend((smp.len() as u32).to_be_bytes());
|
||||
}
|
||||
let mut stsc = full(0);
|
||||
stsc.extend(1u32.to_be_bytes());
|
||||
stsc.extend([1u32, samples.len() as u32, 1].iter().flat_map(|x| x.to_be_bytes()));
|
||||
let mut stco = full(0);
|
||||
stco.extend(1u32.to_be_bytes());
|
||||
stco.extend((mdat_at + 8).to_be_bytes());
|
||||
let stbl =
|
||||
bx(b"stbl", &[bx(b"stts", &stts), bx(b"stsz", &stsz), bx(b"stsc", &stsc), bx(b"stco", &stco)].concat());
|
||||
let text =
|
||||
bx(b"trak", &[tkhd(2), bx(b"mdia", &[mdhd.clone(), hdlr(b"text"), bx(b"minf", &stbl)].concat())].concat());
|
||||
let audio = bx(
|
||||
b"trak",
|
||||
&[
|
||||
tkhd(1),
|
||||
bx(b"tref", &bx(b"chap", &2u32.to_be_bytes())),
|
||||
bx(b"mdia", &[mdhd.clone(), hdlr(b"soun")].concat()),
|
||||
]
|
||||
.concat(),
|
||||
);
|
||||
let mut f = ftyp(b"M4B ");
|
||||
// iTunes metadata after the tracks, with its own `hdlr` (`mdir`): it belongs to no track.
|
||||
let udta = bx(b"udta", &bx(b"meta", &[full(0), hdlr(b"mdir")].concat()));
|
||||
f.extend(bx(b"moov", &[mvhd(1000, 600_000), audio, text, udta].concat()));
|
||||
f
|
||||
};
|
||||
let head_len = build(0).len() as u32;
|
||||
let mut f = build(head_len);
|
||||
f.extend(bx(b"mdat", &samples.concat()));
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quicktime_chapter_tracks_are_read() {
|
||||
let f = m4b_with_chapter_track(&["Part One", "Part Two", "Part Three"], &[0, 200_000, 400_000]);
|
||||
let info = timed(|| inspect(&f, Caps::default())).expect("reads");
|
||||
let titles: Vec<&str> = info.chapters.iter().map(|c| c.title.as_str()).collect();
|
||||
assert_eq!(titles, ["Part One", "Part Two", "Part Three"]);
|
||||
assert_eq!(info.chapters[1].start_ms, 200_000);
|
||||
assert!(info.chapter_samples.is_empty(), "titles read from the bytes given");
|
||||
// Given only the metadata (no mdat), the samples come back for the caller to read from the file.
|
||||
let moov_end = f.len() - (8 + "Part One".len() + "Part Two".len() + "Part Three".len() + 6);
|
||||
let meta = inspect(&f[..moov_end], Caps::default()).expect("reads");
|
||||
assert!(meta.chapters.is_empty());
|
||||
assert_eq!(meta.chapter_samples.len(), 3);
|
||||
let chapters = liber_audio::container::titles_from_samples(&meta.chapter_samples, 600_000, |o, n| {
|
||||
f.get(o as usize..(o + n as u64) as usize).map(<[u8]>::to_vec)
|
||||
});
|
||||
assert_eq!(chapters[2].title, "Part Three");
|
||||
// A chapter track that lies about its sample count is refused.
|
||||
let mut lying = f.clone();
|
||||
let at = lying.windows(4).position(|w| w == b"stsz").unwrap() + 12;
|
||||
lying[at..at + 4].copy_from_slice(&50_000u32.to_be_bytes());
|
||||
assert!(matches!(timed(|| inspect(&lying, Caps::default())), Err(AudioError::Damaged(_))));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Czech: spelling is nearly phonemic. Rules: digraphs (ch, dž, ou, au, eu, ej), palatals (ď ť ň, and d t n before
|
||||
//! i/í/ě), ě after labials (bě → bje, mě → mɲe), ř and its voiceless form, n before k/g, regressive voicing
|
||||
//! assimilation and final devoicing, syllabic r and l, stress on the first syllable. Symbols follow espeak-ng `cs`.
|
||||
|
||||
/// One phoneme and whether it is a vowel nucleus.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Ph {
|
||||
s: String,
|
||||
vowel: bool,
|
||||
}
|
||||
|
||||
fn v(s: &str) -> Ph {
|
||||
Ph { s: s.to_owned(), vowel: true }
|
||||
}
|
||||
fn c(s: &str) -> Ph {
|
||||
Ph { s: s.to_owned(), vowel: false }
|
||||
}
|
||||
|
||||
const R_HACEK: &str = "r\u{31D}";
|
||||
const R_HACEK_VOICELESS: &str = "r\u{31D}\u{30A}";
|
||||
|
||||
/// Short words read without stress (prepositions and the like lean on the next word).
|
||||
const CLITICS: [&str; 16] = ["a", "i", "v", "ve", "s", "se", "z", "ze", "k", "ke", "o", "u", "si", "jsem", "jsi", "že"];
|
||||
|
||||
fn letters(w: &str) -> Vec<Ph> {
|
||||
let ch: Vec<char> = w.chars().collect();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
let at = |k: usize| ch.get(k).copied();
|
||||
while i < ch.len() {
|
||||
let x = ch[i];
|
||||
let next = at(i + 1);
|
||||
let after = at(i + 2);
|
||||
// Two-letter units.
|
||||
match (x, next) {
|
||||
('c', Some('h')) => {
|
||||
out.push(c("x"));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
('d', Some('ž')) => {
|
||||
out.push(c("dʒ"));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
('o', Some('u')) => {
|
||||
out.push(v("oʊ"));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
('a', Some('u')) => {
|
||||
out.push(v("aʊ"));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
('e', Some('u')) => {
|
||||
out.push(v("eʊ"));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
('e', Some('j')) if after.is_none_or(|a| !"aáeéěiíoóuúůyý".contains(a)) => {
|
||||
out.push(v("eɪ"));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
// d t n before i í ě: ď ť ň.
|
||||
('d' | 't' | 'n', Some('i' | 'í' | 'ě')) => {
|
||||
out.push(c(match x {
|
||||
'd' => "ɟ",
|
||||
't' => "c",
|
||||
_ => "ɲ",
|
||||
}));
|
||||
out.push(match next {
|
||||
Some('í') => v("iː"),
|
||||
Some('ě') => v("e"),
|
||||
_ => v("i"),
|
||||
});
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
// bě pě vě fě: b je; mě: m ɲe.
|
||||
('b' | 'p' | 'v' | 'f', Some('ě')) => {
|
||||
out.push(c(&x.to_string()));
|
||||
out.push(c("j"));
|
||||
out.push(v("e"));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
('m', Some('ě')) => {
|
||||
out.push(c("m"));
|
||||
out.push(c("ɲ"));
|
||||
out.push(v("e"));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let p = match x {
|
||||
'a' => v("a"),
|
||||
'á' => v("aː"),
|
||||
'e' | 'ě' => v("e"),
|
||||
'é' => v("eː"),
|
||||
'i' | 'y' => v("i"),
|
||||
'í' | 'ý' => v("iː"),
|
||||
'o' => v("o"),
|
||||
'ó' => v("oː"),
|
||||
'u' => v("u"),
|
||||
'ú' | 'ů' => v("uː"),
|
||||
'c' => c("ts"),
|
||||
'č' => c("tʃ"),
|
||||
'ř' => c(R_HACEK),
|
||||
'š' => c("ʃ"),
|
||||
'ž' => c("ʒ"),
|
||||
'ť' => c("c"),
|
||||
'ď' => c("ɟ"),
|
||||
'ň' => c("ɲ"),
|
||||
'g' => c("ɡ"),
|
||||
'q' => {
|
||||
out.push(c("k"));
|
||||
c("v")
|
||||
}
|
||||
'w' => c("v"),
|
||||
'x' => {
|
||||
out.push(c("k"));
|
||||
c("s")
|
||||
}
|
||||
'n' if matches!(next, Some('k' | 'g')) => c("ŋ"),
|
||||
x if x.is_alphabetic() => c(&x.to_string()),
|
||||
_ => {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
out.push(p);
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Voiced ↔ voiceless obstruents.
|
||||
const PAIRS: [(&str, &str); 11] = [
|
||||
("b", "p"),
|
||||
("d", "t"),
|
||||
("ɟ", "c"),
|
||||
("ɡ", "k"),
|
||||
("v", "f"),
|
||||
("z", "s"),
|
||||
("ʒ", "ʃ"),
|
||||
("h", "x"),
|
||||
("dʒ", "tʃ"),
|
||||
("dz", "ts"),
|
||||
(R_HACEK, R_HACEK_VOICELESS),
|
||||
];
|
||||
|
||||
fn voiced(s: &str) -> Option<bool> {
|
||||
PAIRS.iter().find_map(|(a, b)| {
|
||||
if s == *a {
|
||||
Some(true)
|
||||
} else if s == *b {
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn with_voice(s: &str, on: bool) -> String {
|
||||
PAIRS
|
||||
.iter()
|
||||
.find_map(|(a, b)| if s == *a || s == *b { Some(if on { *a } else { *b }) } else { None })
|
||||
.unwrap_or(s)
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn assimilate(p: &mut [Ph]) {
|
||||
// Right to left: the end of the word is voiceless; an obstruent takes the voicing of the obstruent after it
|
||||
// (v and ř never pass their voicing on). ř is voiceless after a voiceless consonant.
|
||||
let n = p.len();
|
||||
for i in (0..n).rev() {
|
||||
if p[i].vowel || voiced(&p[i].s).is_none() {
|
||||
continue;
|
||||
}
|
||||
let next = p.get(i + 1).filter(|q| !q.vowel);
|
||||
let target = match next {
|
||||
// A one-consonant preposition (v, z, k, s) takes the next word's voicing, which one word cannot know.
|
||||
None if i + 1 == n && n == 1 => None,
|
||||
None if i + 1 == n => Some(false),
|
||||
Some(q) if q.s != "v" && q.s != R_HACEK && q.s != R_HACEK_VOICELESS => voiced(&q.s),
|
||||
_ => None,
|
||||
};
|
||||
if p[i].s == R_HACEK || p[i].s == R_HACEK_VOICELESS {
|
||||
let after_voiceless = i > 0 && voiced(&p[i - 1].s) == Some(false);
|
||||
if after_voiceless || target == Some(false) {
|
||||
p[i].s = R_HACEK_VOICELESS.to_owned();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(t) = target {
|
||||
p[i].s = with_voice(&p[i].s, t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn syllabic(p: &mut [Ph]) {
|
||||
// r or l with no vowel on either side is the nucleus of its syllable (vlk, krk, Brno).
|
||||
let n = p.len();
|
||||
for i in 0..n {
|
||||
if (p[i].s == "r" || p[i].s == "l") && !p[i].vowel {
|
||||
let left = i == 0 || !p[i - 1].vowel;
|
||||
let right = i + 1 == n || !p[i + 1].vowel;
|
||||
if left && right && i > 0 {
|
||||
p[i].s.push('\u{329}');
|
||||
p[i].vowel = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn word(w: &str) -> String {
|
||||
let mut p = letters(w);
|
||||
assimilate(&mut p);
|
||||
syllabic(&mut p);
|
||||
let stressed = !CLITICS.contains(&w);
|
||||
let mut out = String::new();
|
||||
let mut done = false;
|
||||
for ph in &p {
|
||||
if ph.vowel && !done && stressed {
|
||||
out.push(super::STRESS);
|
||||
done = true;
|
||||
}
|
||||
out.push_str(&ph.s);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! German: rules for the common cases. Stress on the first syllable, after an unstressed prefix (be-, ge-, ver- …)
|
||||
//! or on -ieren/-tion/-ei; vowels long when doubled, before h, in an open syllable, or before a single final
|
||||
//! consonant (except short function words); unstressed e → ə, final -er → ɐ, r after a vowel vocalised (ɐ);
|
||||
//! ch → x after a/o/u/au, ç elsewhere; sch, st-/sp-, z, final devoicing, -ig → ɪç. Symbols follow espeak-ng `de`.
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Ph {
|
||||
s: String,
|
||||
vowel: bool,
|
||||
}
|
||||
|
||||
const PREFIXES: [&str; 8] = ["be", "ge", "er", "ver", "zer", "ent", "emp", "miss"];
|
||||
/// Monosyllables whose vowel is short before one final consonant.
|
||||
const SHORT: [&str; 28] = [
|
||||
"das", "des", "es", "ist", "mit", "in", "im", "um", "an", "am", "ab", "ob", "von", "man", "bis", "was", "hat",
|
||||
"weg", "ich", "mich", "dich", "sich", "nicht", "doch", "noch", "auch", "und", "ins",
|
||||
];
|
||||
|
||||
fn is_vowel_letter(c: char) -> bool {
|
||||
"aeiouäöüy".contains(c)
|
||||
}
|
||||
|
||||
pub fn word(w: &str) -> String {
|
||||
let ch: Vec<char> = w.chars().collect();
|
||||
let n = ch.len();
|
||||
// Where the stressed vowel is: the index into `ch` of the first letter of the stressed nucleus.
|
||||
let mut stress_from = 0;
|
||||
for p in PREFIXES {
|
||||
if w.starts_with(p) && n > p.len() + 3 && ch[p.chars().count()..].iter().any(|&c| is_vowel_letter(c)) {
|
||||
stress_from = p.chars().count();
|
||||
break;
|
||||
}
|
||||
}
|
||||
let ends = |s: &str| w.ends_with(s);
|
||||
if ends("ieren") && n > 5 {
|
||||
stress_from = n - 5;
|
||||
} else if (ends("tion") || ends("erei")) && n > 4 {
|
||||
stress_from = n - 2;
|
||||
}
|
||||
let mut out: Vec<Ph> = Vec::new();
|
||||
let mut stressed_at: Option<usize> = None;
|
||||
let mut i = 0;
|
||||
let short_word = SHORT.contains(&w);
|
||||
while i < n {
|
||||
let x = ch[i];
|
||||
let at = |k: usize| ch.get(k).copied();
|
||||
let rest: String = ch[i..].iter().collect();
|
||||
let cons = |s: &str| Ph { s: s.to_owned(), vowel: false };
|
||||
let vow = |s: &str| Ph { s: s.to_owned(), vowel: true };
|
||||
let mark = |out: &Vec<Ph>, stressed_at: &mut Option<usize>| {
|
||||
if stressed_at.is_none() && i >= stress_from {
|
||||
*stressed_at = Some(out.len());
|
||||
}
|
||||
};
|
||||
// Consonant clusters first.
|
||||
let (ph, step): (Option<Vec<Ph>>, usize) = if rest.starts_with("tsch") {
|
||||
(Some(vec![cons("tʃ")]), 4)
|
||||
} else if rest.starts_with("sch") {
|
||||
(Some(vec![cons("ʃ")]), 3)
|
||||
} else if rest.starts_with("chs") {
|
||||
(Some(vec![cons("k"), cons("s")]), 3)
|
||||
} else if rest.starts_with("ch") {
|
||||
let back = out.last().is_some_and(|p| {
|
||||
p.vowel && matches!(p.s.as_str(), "a" | "aː" | "o" | "oː" | "ɔ" | "u" | "uː" | "ʊ" | "aʊ")
|
||||
});
|
||||
(Some(vec![cons(if back { "x" } else { "ç" })]), 2)
|
||||
} else if rest.starts_with("ck") {
|
||||
(Some(vec![cons("k")]), 2)
|
||||
} else if rest.starts_with("tz") || rest.starts_with("ts") {
|
||||
(Some(vec![cons("t"), cons("s")]), 2)
|
||||
} else if rest.starts_with("ph") {
|
||||
(Some(vec![cons("f")]), 2)
|
||||
} else if rest.starts_with("th") {
|
||||
(Some(vec![cons("t")]), 2)
|
||||
} else if rest.starts_with("qu") {
|
||||
(Some(vec![cons("k"), cons("v")]), 2)
|
||||
} else if rest.starts_with("ng") {
|
||||
(Some(vec![cons("ŋ")]), 2)
|
||||
} else if rest.starts_with("nk") {
|
||||
(Some(vec![cons("ŋ"), cons("k")]), 2)
|
||||
} else if rest.starts_with("pf") {
|
||||
(Some(vec![cons("p"), cons("f")]), 2)
|
||||
} else if rest.starts_with("dt") {
|
||||
(Some(vec![cons("t")]), 2)
|
||||
} else if (i == 0 || i == stress_from) && (rest.starts_with("st") || rest.starts_with("sp")) {
|
||||
(Some(vec![cons("ʃ"), cons(&ch[i + 1].to_string())]), 2)
|
||||
} else if rest == "ig" && i > 0 {
|
||||
mark(&out, &mut stressed_at);
|
||||
(Some(vec![vow("ɪ"), cons("ç")]), 2)
|
||||
} else {
|
||||
(None, 0)
|
||||
};
|
||||
if let Some(ps) = ph {
|
||||
out.extend(ps);
|
||||
i += step;
|
||||
continue;
|
||||
}
|
||||
// Diphthongs and long spellings.
|
||||
let di = match (x, at(i + 1)) {
|
||||
('e' | 'a', Some('i' | 'y')) => Some("aɪ"),
|
||||
('e' | 'ä', Some('u')) => Some("ɔʏ"),
|
||||
('a', Some('u')) => Some("aʊ"),
|
||||
('i', Some('e')) if at(i + 2) != Some('r') || i + 3 < n => Some("iː"),
|
||||
('a', Some('a')) => Some("aː"),
|
||||
('e', Some('e')) => Some("eː"),
|
||||
('o', Some('o')) => Some("oː"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(d) = di {
|
||||
mark(&out, &mut stressed_at);
|
||||
if d == "ɔʏ" {
|
||||
out.push(vow("ɔ"));
|
||||
out.push(Ph { s: "ʏ".into(), vowel: false });
|
||||
} else {
|
||||
out.push(vow(d));
|
||||
}
|
||||
i += 2;
|
||||
if at(i) == Some('h') && !at(i + 1).is_some_and(is_vowel_letter) {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if is_vowel_letter(x) {
|
||||
mark(&out, &mut stressed_at);
|
||||
let next = at(i + 1);
|
||||
let after = at(i + 2);
|
||||
let is_stressed = stressed_at == Some(out.len());
|
||||
// Unstressed e in endings.
|
||||
let tail: String = ch[i..].iter().collect();
|
||||
if x == 'e'
|
||||
&& !is_stressed
|
||||
&& (tail == "e" || tail == "en" || tail == "em" || tail == "es" || tail == "el" || tail == "et")
|
||||
{
|
||||
out.push(vow("ə"));
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if x == 'e' && !is_stressed && tail == "er" {
|
||||
out.push(vow("ɐ"));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
// h after a vowel is silent and makes it long (gehen, Jahr, ruhig).
|
||||
let silent_h = next == Some('h');
|
||||
let uch = x == 'u' && next == Some('c') && after == Some('h') && at(i + 3).is_none();
|
||||
let open = next.is_some_and(|c| !is_vowel_letter(c) && c != 'h')
|
||||
&& after.is_some_and(is_vowel_letter)
|
||||
&& !matches!((next, after), (Some('c'), Some('h')));
|
||||
let final_single = next.is_some_and(|c| !is_vowel_letter(c)) && after.is_none() && !short_word;
|
||||
let at_end = next.is_none();
|
||||
let long =
|
||||
silent_h || uch || (open && is_stressed) || (final_single && is_stressed) || (at_end && is_stressed);
|
||||
let s = match (x, long) {
|
||||
('a', true) => "aː",
|
||||
('a', false) => "a",
|
||||
('e', true) => "eː",
|
||||
('e', false) => "ɛ",
|
||||
('i' | 'y', true) => "iː",
|
||||
('i' | 'y', false) => "ɪ",
|
||||
('o', true) => "oː",
|
||||
('o', false) => "ɔ",
|
||||
('u', true) => "uː",
|
||||
('u', false) => "ʊ",
|
||||
('ä', true) => "ɛː",
|
||||
('ä', false) => "ɛ",
|
||||
('ö', true) => "øː",
|
||||
('ö', false) => "œ",
|
||||
('ü', true) => "yː",
|
||||
_ => "ʏ",
|
||||
};
|
||||
out.push(vow(s));
|
||||
i += if silent_h { 2 } else { 1 };
|
||||
continue;
|
||||
}
|
||||
// A doubled consonant is one sound (Mann, Wasser, können).
|
||||
if i > 0 && ch[i - 1] == x && !is_vowel_letter(x) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// Single consonants.
|
||||
let prev_vowel = out.last().is_some_and(|p| p.vowel);
|
||||
let next_vowel = at(i + 1).is_some_and(is_vowel_letter);
|
||||
let p: Option<&str> = match x {
|
||||
'r' if prev_vowel && !next_vowel => Some("ɐ"),
|
||||
'r' if i == 0 => Some("r"),
|
||||
'r' => Some("ɾ"),
|
||||
's' if next_vowel
|
||||
&& (i == 0
|
||||
|| prev_vowel
|
||||
|| out.last().is_some_and(|p| matches!(p.s.as_str(), "l" | "n" | "m" | "ɾ"))) =>
|
||||
{
|
||||
Some("z")
|
||||
}
|
||||
'ß' => Some("s"),
|
||||
'z' => {
|
||||
out.push(cons("t"));
|
||||
Some("s")
|
||||
}
|
||||
'v' => Some("f"),
|
||||
'w' => Some("v"),
|
||||
'j' => Some("j"),
|
||||
'g' => Some("ɡ"),
|
||||
'c' if at(i + 1).is_some_and(|c| "eiäy".contains(c)) => {
|
||||
out.push(cons("t"));
|
||||
Some("s")
|
||||
}
|
||||
'c' => Some("k"),
|
||||
'x' => {
|
||||
out.push(cons("k"));
|
||||
Some("s")
|
||||
}
|
||||
'h' if prev_vowel => None,
|
||||
x if x.is_alphabetic() => {
|
||||
out.push(cons(&x.to_string()));
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(p) = p {
|
||||
out.push(if p == "ɐ" { vow("ɐ") } else { cons(p) });
|
||||
if p == "ɐ" {
|
||||
// Vocalic r is not a syllable of its own.
|
||||
out.last_mut().expect("pushed").vowel = false;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
// Final devoicing: a voiced obstruent before a consonant or at the end.
|
||||
let n = out.len();
|
||||
for k in 0..n {
|
||||
let last = k + 1 == n
|
||||
|| !out[k + 1].vowel
|
||||
&& out[k + 1].s != "ɾ"
|
||||
&& out[k + 1].s != "l"
|
||||
&& out[k + 1].s != "r"
|
||||
&& out[k + 1].s != "j"
|
||||
&& out[k + 1].s != "ʏ";
|
||||
if last && !out[k].vowel {
|
||||
let d = match out[k].s.as_str() {
|
||||
"b" => Some("p"),
|
||||
"d" => Some("t"),
|
||||
"ɡ" => Some("k"),
|
||||
"v" => Some("f"),
|
||||
"z" => Some("s"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(d) = d {
|
||||
out[k].s = d.to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut s = String::new();
|
||||
for (k, p) in out.iter().enumerate() {
|
||||
if Some(k) == stressed_at && !short_word_unstressed(w) {
|
||||
s.push(super::STRESS);
|
||||
}
|
||||
s.push_str(&p.s);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Articles and similar short words carry no stress mark.
|
||||
fn short_word_unstressed(w: &str) -> bool {
|
||||
matches!(w, "der" | "die" | "dem" | "den" | "ein" | "eine" | "einen" | "zu" | "und" | "oder" | "es" | "sie" | "er")
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
//! English: CMUdict's ARPABET → espeak-ng `en-us` IPA (stress before the vowel, ɜː/ɚ for stressed/unstressed ER,
|
||||
//! t flapped to ɾ between a vowel and an unstressed vowel), and letter-to-sound rules for words not in the
|
||||
//! dictionary (good enough for names and rare words, never the main path).
|
||||
|
||||
const VOWELS: [(&str, &str, &str); 15] = [
|
||||
// ARPABET, stressed, unstressed
|
||||
("AA", "ɑː", "ɑː"),
|
||||
("AE", "æ", "æ"),
|
||||
("AH", "ʌ", "ə"),
|
||||
("AO", "ɔː", "ɔː"),
|
||||
("AW", "aʊ", "aʊ"),
|
||||
("AY", "aɪ", "aɪ"),
|
||||
("EH", "ɛ", "ɛ"),
|
||||
("ER", "ɜː", "ɚ"),
|
||||
("EY", "eɪ", "eɪ"),
|
||||
("IH", "ɪ", "ɪ"),
|
||||
("IY", "iː", "i"),
|
||||
("OW", "oʊ", "oʊ"),
|
||||
("OY", "ɔɪ", "ɔɪ"),
|
||||
("UH", "ʊ", "ʊ"),
|
||||
("UW", "uː", "uː"),
|
||||
];
|
||||
|
||||
const CONSONANTS: [(&str, &str); 24] = [
|
||||
("B", "b"),
|
||||
("CH", "tʃ"),
|
||||
("D", "d"),
|
||||
("DH", "ð"),
|
||||
("F", "f"),
|
||||
("G", "ɡ"),
|
||||
("HH", "h"),
|
||||
("JH", "dʒ"),
|
||||
("K", "k"),
|
||||
("L", "l"),
|
||||
("M", "m"),
|
||||
("N", "n"),
|
||||
("NG", "ŋ"),
|
||||
("P", "p"),
|
||||
("R", "ɹ"),
|
||||
("S", "s"),
|
||||
("SH", "ʃ"),
|
||||
("T", "t"),
|
||||
("TH", "θ"),
|
||||
("V", "v"),
|
||||
("W", "w"),
|
||||
("Y", "j"),
|
||||
("Z", "z"),
|
||||
("ZH", "ʒ"),
|
||||
];
|
||||
|
||||
/// One ARPABET pronunciation in IPA; `None` for an unknown symbol.
|
||||
pub fn from_arpabet(arpa: &[&str]) -> Option<String> {
|
||||
// (ipa, is vowel, stress 0/1/2)
|
||||
let mut ph: Vec<(String, bool, u8)> = Vec::with_capacity(arpa.len());
|
||||
for a in arpa {
|
||||
let (base, stress) = match a.chars().last() {
|
||||
Some(d @ '0'..='2') => (&a[..a.len() - 1], d as u8 - b'0'),
|
||||
_ => (*a, 0),
|
||||
};
|
||||
if let Some((_, s, u)) = VOWELS.iter().find(|(k, _, _)| *k == base) {
|
||||
ph.push(((if stress > 0 { *s } else { *u }).to_owned(), true, stress));
|
||||
} else if let Some((_, c)) = CONSONANTS.iter().find(|(k, _)| *k == base) {
|
||||
ph.push(((*c).to_owned(), false, 0));
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// Flapping: t (or d) after a vowel or r, before an unstressed vowel → ɾ (better, water, ladder).
|
||||
for i in 1..ph.len().saturating_sub(1) {
|
||||
if (ph[i].0 == "t" || ph[i].0 == "d") && (ph[i - 1].1 || ph[i - 1].0 == "ɹ") && ph[i + 1].1 && ph[i + 1].2 == 0
|
||||
{
|
||||
ph[i].0 = "ɾ".to_owned();
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
for (s, vowel, stress) in &ph {
|
||||
if *vowel {
|
||||
match stress {
|
||||
1 => out.push(super::STRESS),
|
||||
2 => out.push(super::STRESS2),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out.push_str(s);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Letter-to-sound for words the dictionary does not have: common English spellings, stress on the first vowel.
|
||||
pub fn rules(w: &str) -> String {
|
||||
const UNITS: [(&str, &str); 38] = [
|
||||
("tion", "ʃən"),
|
||||
("sion", "ʒən"),
|
||||
("ough", "ʌf"),
|
||||
("igh", "aɪ"),
|
||||
("tch", "tʃ"),
|
||||
("sch", "sk"),
|
||||
("ee", "iː"),
|
||||
("ea", "iː"),
|
||||
("oo", "uː"),
|
||||
("ou", "aʊ"),
|
||||
("ow", "oʊ"),
|
||||
("oa", "oʊ"),
|
||||
("ai", "eɪ"),
|
||||
("ay", "eɪ"),
|
||||
("oi", "ɔɪ"),
|
||||
("oy", "ɔɪ"),
|
||||
("au", "ɔː"),
|
||||
("aw", "ɔː"),
|
||||
("ar", "ɑːɹ"),
|
||||
("or", "ɔːɹ"),
|
||||
("er", "ɚ"),
|
||||
("ir", "ɜː"),
|
||||
("ur", "ɜː"),
|
||||
("ch", "tʃ"),
|
||||
("sh", "ʃ"),
|
||||
("th", "θ"),
|
||||
("ph", "f"),
|
||||
("wh", "w"),
|
||||
("ck", "k"),
|
||||
("ng", "ŋ"),
|
||||
("qu", "kw"),
|
||||
("kn", "n"),
|
||||
("wr", "ɹ"),
|
||||
("gh", ""),
|
||||
("ll", "l"),
|
||||
("ss", "s"),
|
||||
("tt", "t"),
|
||||
("nn", "n"),
|
||||
];
|
||||
let ch: Vec<char> = w.chars().filter(|c| c.is_alphabetic() || *c == '\'').collect();
|
||||
let s: String = ch.iter().collect();
|
||||
let mut out = String::new();
|
||||
let mut stressed = false;
|
||||
let mut i = 0;
|
||||
let vowel_ipa = |c: char, next: Option<char>, after: Option<char>| -> Option<&'static str> {
|
||||
// A vowel before one consonant and a final e is long (make, time, home, cute).
|
||||
let magic = next.is_some_and(|n| !"aeiou".contains(n)) && after == Some('e');
|
||||
Some(match (c, magic) {
|
||||
('a', true) => "eɪ",
|
||||
('a', false) => "æ",
|
||||
('e', _) => "ɛ",
|
||||
('i', true) => "aɪ",
|
||||
('i', false) => "ɪ",
|
||||
('o', true) => "oʊ",
|
||||
('o', false) => "ɑː",
|
||||
('u', true) => "juː",
|
||||
('u', false) => "ʌ",
|
||||
('y', _) => "i",
|
||||
_ => return None,
|
||||
})
|
||||
};
|
||||
while i < ch.len() {
|
||||
let rest = &s[s.char_indices().nth(i).map_or(s.len(), |(b, _)| b)..];
|
||||
if let Some((k, v)) = UNITS.iter().find(|(k, _)| rest.starts_with(k)) {
|
||||
let is_vowel = v.starts_with(|c: char| "iːuːaʊoʊeɪɔɪɑɚɜʌæɛɪəʊ".contains(c));
|
||||
if is_vowel && !stressed {
|
||||
out.push(super::STRESS);
|
||||
stressed = true;
|
||||
}
|
||||
out.push_str(v);
|
||||
i += k.chars().count();
|
||||
continue;
|
||||
}
|
||||
let c = ch[i];
|
||||
let next = ch.get(i + 1).copied();
|
||||
let after = ch.get(i + 2).copied();
|
||||
// A final e after a consonant is silent.
|
||||
if c == 'e' && next.is_none() && i > 0 {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if "aeiouy".contains(c) && !(c == 'y' && i == 0) {
|
||||
if let Some(v) = vowel_ipa(c, next, after) {
|
||||
if !stressed {
|
||||
out.push(super::STRESS);
|
||||
stressed = true;
|
||||
}
|
||||
out.push_str(v);
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let sound: String = match c {
|
||||
'c' if next.is_some_and(|n| "eiy".contains(n)) => "s".into(),
|
||||
'c' => "k".into(),
|
||||
'g' if next.is_some_and(|n| "eiy".contains(n)) => "dʒ".into(),
|
||||
'g' => "ɡ".into(),
|
||||
'j' => "dʒ".into(),
|
||||
'q' => "k".into(),
|
||||
'r' => "ɹ".into(),
|
||||
'x' => "ks".into(),
|
||||
'y' => "j".into(),
|
||||
c if c.is_ascii_alphabetic() => c.to_string(),
|
||||
_ => String::new(),
|
||||
};
|
||||
out.push_str(&sound);
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! 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
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Numbers as words, so a voice reads "1847" as a year and "3" as three. Cardinals below a billion; English and
|
||||
//! German read 1100–1999 as years when they stand alone (the common case in books).
|
||||
|
||||
use crate::Lang;
|
||||
|
||||
/// The words for `n`, or `None` when it is too large to read.
|
||||
pub fn words(n: u64, lang: Lang) -> Option<String> {
|
||||
if n >= 1_000_000_000 {
|
||||
return None;
|
||||
}
|
||||
Some(match lang {
|
||||
Lang::En => en(n),
|
||||
Lang::De => de(n),
|
||||
Lang::Cs | Lang::La => cs(n),
|
||||
})
|
||||
}
|
||||
|
||||
fn en(n: u64) -> String {
|
||||
const ONES: [&str; 20] = [
|
||||
"zero",
|
||||
"one",
|
||||
"two",
|
||||
"three",
|
||||
"four",
|
||||
"five",
|
||||
"six",
|
||||
"seven",
|
||||
"eight",
|
||||
"nine",
|
||||
"ten",
|
||||
"eleven",
|
||||
"twelve",
|
||||
"thirteen",
|
||||
"fourteen",
|
||||
"fifteen",
|
||||
"sixteen",
|
||||
"seventeen",
|
||||
"eighteen",
|
||||
"nineteen",
|
||||
];
|
||||
const TENS: [&str; 10] = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
|
||||
fn below_100(n: u64) -> String {
|
||||
if n < 20 {
|
||||
ONES[n as usize].to_owned()
|
||||
} else if n.is_multiple_of(10) {
|
||||
TENS[(n / 10) as usize].to_owned()
|
||||
} else {
|
||||
format!("{} {}", TENS[(n / 10) as usize], ONES[(n % 10) as usize])
|
||||
}
|
||||
}
|
||||
fn below_1000(n: u64) -> String {
|
||||
match (n / 100, n % 100) {
|
||||
(0, r) => below_100(r),
|
||||
(h, 0) => format!("{} hundred", ONES[h as usize]),
|
||||
(h, r) => format!("{} hundred {}", ONES[h as usize], below_100(r)),
|
||||
}
|
||||
}
|
||||
if (1100..2000).contains(&n) && !n.is_multiple_of(100) {
|
||||
let r = n % 100;
|
||||
return format!(
|
||||
"{} {}",
|
||||
below_100(n / 100),
|
||||
if r < 10 { format!("oh {}", ONES[r as usize]) } else { below_100(r) }
|
||||
);
|
||||
}
|
||||
let (m, k, r) = (n / 1_000_000, (n / 1000) % 1000, n % 1000);
|
||||
let mut parts = Vec::new();
|
||||
if m > 0 {
|
||||
parts.push(format!("{} million", below_1000(m)));
|
||||
}
|
||||
if k > 0 {
|
||||
parts.push(format!("{} thousand", below_1000(k)));
|
||||
}
|
||||
if r > 0 || parts.is_empty() {
|
||||
parts.push(below_1000(r));
|
||||
}
|
||||
parts.join(" ")
|
||||
}
|
||||
|
||||
fn de(n: u64) -> String {
|
||||
const ONES: [&str; 20] = [
|
||||
"null",
|
||||
"eins",
|
||||
"zwei",
|
||||
"drei",
|
||||
"vier",
|
||||
"fünf",
|
||||
"sechs",
|
||||
"sieben",
|
||||
"acht",
|
||||
"neun",
|
||||
"zehn",
|
||||
"elf",
|
||||
"zwölf",
|
||||
"dreizehn",
|
||||
"vierzehn",
|
||||
"fünfzehn",
|
||||
"sechzehn",
|
||||
"siebzehn",
|
||||
"achtzehn",
|
||||
"neunzehn",
|
||||
];
|
||||
const TENS: [&str; 10] =
|
||||
["", "", "zwanzig", "dreißig", "vierzig", "fünfzig", "sechzig", "siebzig", "achtzig", "neunzig"];
|
||||
fn unit(n: u64) -> &'static str {
|
||||
if n == 1 { "ein" } else { ONES[n as usize] }
|
||||
}
|
||||
fn below_100(n: u64) -> String {
|
||||
if n < 20 {
|
||||
ONES[n as usize].to_owned()
|
||||
} else if n.is_multiple_of(10) {
|
||||
TENS[(n / 10) as usize].to_owned()
|
||||
} else {
|
||||
format!("{}und{}", unit(n % 10), TENS[(n / 10) as usize])
|
||||
}
|
||||
}
|
||||
fn below_1000(n: u64) -> String {
|
||||
match (n / 100, n % 100) {
|
||||
(0, r) => below_100(r),
|
||||
(h, 0) => format!("{}hundert", unit(h)),
|
||||
(h, r) => format!("{}hundert{}", unit(h), below_100(r)),
|
||||
}
|
||||
}
|
||||
if (1100..2000).contains(&n) {
|
||||
let r = n % 100;
|
||||
return format!("{}hundert{}", below_100(n / 100), if r == 0 { String::new() } else { below_100(r) });
|
||||
}
|
||||
let (m, k, r) = (n / 1_000_000, (n / 1000) % 1000, n % 1000);
|
||||
let mut s = String::new();
|
||||
if m > 0 {
|
||||
s.push_str(&if m == 1 { "eine Million ".to_owned() } else { format!("{} Millionen ", below_1000(m)) });
|
||||
}
|
||||
if k > 0 {
|
||||
s.push_str(&format!("{}tausend", if k == 1 { "ein".to_owned() } else { below_1000(k) }));
|
||||
}
|
||||
if r > 0 || s.is_empty() {
|
||||
s.push_str(&below_1000(r));
|
||||
}
|
||||
s.trim().to_owned()
|
||||
}
|
||||
|
||||
fn cs(n: u64) -> String {
|
||||
const ONES: [&str; 20] = [
|
||||
"nula",
|
||||
"jedna",
|
||||
"dva",
|
||||
"tři",
|
||||
"čtyři",
|
||||
"pět",
|
||||
"šest",
|
||||
"sedm",
|
||||
"osm",
|
||||
"devět",
|
||||
"deset",
|
||||
"jedenáct",
|
||||
"dvanáct",
|
||||
"třináct",
|
||||
"čtrnáct",
|
||||
"patnáct",
|
||||
"šestnáct",
|
||||
"sedmnáct",
|
||||
"osmnáct",
|
||||
"devatenáct",
|
||||
];
|
||||
const TENS: [&str; 10] =
|
||||
["", "", "dvacet", "třicet", "čtyřicet", "padesát", "šedesát", "sedmdesát", "osmdesát", "devadesát"];
|
||||
const HUNDREDS: [&str; 10] =
|
||||
["", "sto", "dvě stě", "tři sta", "čtyři sta", "pět set", "šest set", "sedm set", "osm set", "devět set"];
|
||||
fn below_1000(n: u64) -> String {
|
||||
let (h, r) = (n / 100, n % 100);
|
||||
let mut parts = Vec::new();
|
||||
if h > 0 {
|
||||
parts.push(HUNDREDS[h as usize].to_owned());
|
||||
}
|
||||
if r > 0 {
|
||||
if r < 20 {
|
||||
parts.push(ONES[r as usize].to_owned());
|
||||
} else {
|
||||
parts.push(TENS[(r / 10) as usize].to_owned());
|
||||
if r % 10 > 0 {
|
||||
parts.push(ONES[(r % 10) as usize].to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
parts.join(" ")
|
||||
}
|
||||
let (m, k, r) = (n / 1_000_000, (n / 1000) % 1000, n % 1000);
|
||||
let mut parts = Vec::new();
|
||||
if m > 0 {
|
||||
parts.push(match m {
|
||||
1 => "milion".to_owned(),
|
||||
2..=4 => format!("{} miliony", below_1000(m)),
|
||||
_ => format!("{} milionů", below_1000(m)),
|
||||
});
|
||||
}
|
||||
if k > 0 {
|
||||
parts.push(match k {
|
||||
1 => "tisíc".to_owned(),
|
||||
2..=4 => format!("{} tisíce", below_1000(k)),
|
||||
_ => format!("{} tisíc", below_1000(k)),
|
||||
});
|
||||
}
|
||||
if r > 0 || parts.is_empty() {
|
||||
parts.push(if n == 0 { "nula".to_owned() } else { below_1000(r) });
|
||||
}
|
||||
parts.join(" ")
|
||||
}
|
||||
@@ -119,6 +119,7 @@ impl Rules {
|
||||
Lang::En => EN_IRREGULAR,
|
||||
Lang::De => DE_IRREGULAR,
|
||||
Lang::La => LA_IRREGULAR,
|
||||
Lang::Cs => &[],
|
||||
};
|
||||
Rules { lang, irregular: list.iter().copied().collect() }
|
||||
}
|
||||
@@ -134,6 +135,7 @@ impl Rules {
|
||||
Lang::En => en(&w),
|
||||
Lang::De => de(&w, capital),
|
||||
Lang::La => la(&w),
|
||||
Lang::Cs => vec![],
|
||||
};
|
||||
out.push(w);
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
pub mod align;
|
||||
pub mod concept;
|
||||
pub mod g2p;
|
||||
pub mod lemma;
|
||||
pub mod level;
|
||||
pub mod profile;
|
||||
@@ -31,6 +32,8 @@ pub enum Lang {
|
||||
En,
|
||||
De,
|
||||
La,
|
||||
/// Day 4: Czech, for reading aloud (the reader's own language; no lemma rules).
|
||||
Cs,
|
||||
}
|
||||
|
||||
impl Lang {
|
||||
@@ -41,6 +44,7 @@ impl Lang {
|
||||
"en" | "eng" => Some(Lang::En),
|
||||
"de" | "ger" | "deu" => Some(Lang::De),
|
||||
"la" | "lat" => Some(Lang::La),
|
||||
"cs" | "cze" | "ces" => Some(Lang::Cs),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -50,6 +54,7 @@ impl Lang {
|
||||
Lang::En => "en",
|
||||
Lang::De => "de",
|
||||
Lang::La => "la",
|
||||
Lang::Cs => "cs",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn is_name(tok: &Token, lang: Lang, lem: &dyn Lemmatizer) -> bool {
|
||||
match lang {
|
||||
Lang::De => !lem.knows(&tok.text) && !tok.sentence_start && lem.knows("Haus"),
|
||||
Lang::En => !tok.sentence_start && tok.text != "I" && !tok.text.starts_with("I'"),
|
||||
Lang::La => !tok.sentence_start,
|
||||
Lang::La | Lang::Cs => !tok.sentence_start,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
# Czech words and the IPA espeak-ng conventions give them (stress before the first vowel), written for this repository.
|
||||
dobrý dˈobriː
|
||||
den dˈen
|
||||
jak jˈak
|
||||
máte mˈaːte
|
||||
řeka r̝ˈeka
|
||||
tři tr̝̊ˈi
|
||||
moře mˈor̝e
|
||||
dítě ɟˈiːce
|
||||
něco ɲˈetso
|
||||
čtyři tʃtˈir̝i
|
||||
chleba xlˈeba
|
||||
hrad hrˈat
|
||||
kde ɡdˈe
|
||||
vlk vˈl̩k
|
||||
krk kˈr̩k
|
||||
pouze pˈoʊze
|
||||
auto ˈaʊto
|
||||
mě mɲˈe
|
||||
pět pjˈet
|
||||
banka bˈaŋka
|
||||
ještě jˈeʃce
|
||||
kůň kˈuːɲ
|
||||
džus dʒˈus
|
||||
nejlepší nˈeɪlepʃiː
|
||||
vůz vˈuːs
|
||||
léto lˈeːto
|
||||
odpověď ˈotpovjec
|
||||
kniha kɲˈiha
|
||||
otec ˈotets
|
||||
matka mˈatka
|
||||
dívka ɟˈiːfka
|
||||
sníh sɲˈiːx
|
||||
lidé lˈideː
|
||||
Praha prˈaha
|
||||
v v
|
||||
a a
|
||||
že ʒe
|
||||
|
+31
@@ -0,0 +1,31 @@
|
||||
# German words and the IPA espeak-ng conventions give them (stress before the stressed vowel), written for this repository.
|
||||
haus hˈaʊs
|
||||
mann mˈan
|
||||
vater fˈaːtɐ
|
||||
kinder kˈɪndɐ
|
||||
schule ʃˈuːlə
|
||||
ich ˈɪç
|
||||
nacht nˈaxt
|
||||
bäcker bˈɛkɐ
|
||||
tag tˈaːk
|
||||
liebe lˈiːbə
|
||||
zeit tsˈaɪt
|
||||
freund fɾˈɔʏnt
|
||||
stein ʃtˈaɪn
|
||||
gehen ɡˈeːən
|
||||
verstehen fɛɐʃtˈeːən
|
||||
sprechen ʃpɾˈɛçən
|
||||
über ˈyːbɐ
|
||||
schön ʃˈøːn
|
||||
können kˈœnən
|
||||
bruder bɾˈuːdɐ
|
||||
mit mˈɪt
|
||||
das dˈas
|
||||
wasser vˈasɐ
|
||||
zug tsˈuːk
|
||||
jahr jˈaːɐ
|
||||
milch mˈɪlç
|
||||
buch bˈuːx
|
||||
kind kˈɪnt
|
||||
fisch fˈɪʃ
|
||||
morgen mˈɔɐɡən
|
||||
|
@@ -0,0 +1,119 @@
|
||||
//! Day 4: text → phonemes for the reading voices. Gold pronunciations written for this repository in espeak-ng's
|
||||
//! conventions (the voices were trained on them); the accuracy per language is stated in the app's
|
||||
//! `docs/04_listening.md` and held here as a floor.
|
||||
|
||||
use liber_lang::Lang;
|
||||
use liber_lang::g2p::{Lexicon, en, ipa, num, tokens, word};
|
||||
|
||||
fn fixture(text: &str) -> Vec<(String, String)> {
|
||||
text.lines()
|
||||
.map(|l| l.trim_end_matches('\r'))
|
||||
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||
.map(|l| {
|
||||
let (w, p) = l.split_once('\t').expect("word<TAB>ipa");
|
||||
(w.to_owned(), p.to_owned())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn accuracy(lang: Lang, cases: &[(String, String)]) -> (usize, Vec<String>) {
|
||||
let mut wrong = Vec::new();
|
||||
let ok = cases
|
||||
.iter()
|
||||
.filter(|(w, want)| {
|
||||
let got = word(w, lang, None);
|
||||
let hit = got == *want;
|
||||
if !hit {
|
||||
wrong.push(format!("{w} → {got} (want {want})"));
|
||||
}
|
||||
hit
|
||||
})
|
||||
.count();
|
||||
(ok, wrong)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn czech_words() {
|
||||
let cases = fixture(include_str!("fixtures/g2p_cs.tsv"));
|
||||
let (ok, wrong) = accuracy(Lang::Cs, &cases);
|
||||
println!("cs: {ok}/{} — {}", cases.len(), wrong.join("; "));
|
||||
assert!(ok as f64 / cases.len() as f64 >= 0.95, "{wrong:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn german_words() {
|
||||
let cases = fixture(include_str!("fixtures/g2p_de.tsv"));
|
||||
let (ok, wrong) = accuracy(Lang::De, &cases);
|
||||
println!("de: {ok}/{} — {}", cases.len(), wrong.join("; "));
|
||||
assert!(ok as f64 / cases.len() as f64 >= 0.9, "{wrong:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn english_from_cmudict_and_rules() {
|
||||
// CMUdict lines (the format the app reads; the words' ARPABET is common knowledge, not the file).
|
||||
let lex = Lexicon::from_cmudict(
|
||||
";;; a comment\nHELLO HH AH0 L OW1\nHELLO(2) HH EH0 L OW1\nWORLD W ER1 L D\nBETTER B EH1 T ER0\nTHE DH AH0\nMOTHER M AH1 DH ER0\nFATHER F AA1 DH ER0\nCAT K AE1 T\nTHINKING TH IH1 NG K IH0 NG\nBOY B OY1\nTOMORROW T AH0 M AA1 R OW2\nBAD B AE1 D XX9\n",
|
||||
)
|
||||
.expect("parses");
|
||||
let cases = [
|
||||
("hello", "həlˈoʊ"),
|
||||
("world", "wˈɜːld"),
|
||||
("better", "bˈɛɾɚ"),
|
||||
("the", "ðə"),
|
||||
("mother", "mˈʌðɚ"),
|
||||
("father", "fˈɑːðɚ"),
|
||||
("cat", "kˈæt"),
|
||||
("thinking", "θˈɪŋkɪŋ"),
|
||||
("boy", "bˈɔɪ"),
|
||||
("tomorrow", "təmˈɑːɹˌoʊ"),
|
||||
];
|
||||
for (w, want) in cases {
|
||||
assert_eq!(word(w, Lang::En, Some(&lex)), want, "{w}");
|
||||
}
|
||||
assert!(lex.get("bad").is_none(), "an unknown ARPABET symbol drops the entry");
|
||||
assert_eq!(lex.len(), 10, "alternates and bad lines skipped");
|
||||
// Words not in the dictionary still get a reading: stressed, from the voice's symbols.
|
||||
let inventory = "ˈˌːabdefhijklmnoprstuvwzæðŋɐɑɔəɚɛɜɡɪɹʃʊʌʒθɾ";
|
||||
for w in ["make", "night", "station", "zork", "liber"] {
|
||||
let r = en::rules(w);
|
||||
assert!(r.starts_with(|c: char| c != ' ') && r.contains('ˈ'), "{w} → {r}");
|
||||
assert!(r.chars().all(|c| inventory.contains(c)), "{w} → {r}");
|
||||
}
|
||||
assert_eq!(en::rules("make"), "mˈeɪk");
|
||||
assert_eq!(en::rules("night"), "nˈaɪt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sentences_numbers_and_punctuation() {
|
||||
assert_eq!(ipa("Dobrý den, jak se máte?", Lang::Cs, None), "dˈobriː dˈen, jˈak se mˈaːte?");
|
||||
assert_eq!(ipa("Tři kočky.", Lang::Cs, None), "tr̝̊ˈi kˈotʃki.");
|
||||
// Numbers are read as words in the sentence's language.
|
||||
assert_eq!(num::words(1847, Lang::En).as_deref(), Some("eighteen forty seven"));
|
||||
assert_eq!(num::words(1847, Lang::De).as_deref(), Some("achtzehnhundertsiebenundvierzig"));
|
||||
assert_eq!(num::words(1847, Lang::Cs).as_deref(), Some("tisíc osm set čtyřicet sedm"));
|
||||
assert_eq!(num::words(21, Lang::De).as_deref(), Some("einundzwanzig"));
|
||||
assert_eq!(num::words(2_000_000_000, Lang::En), None);
|
||||
assert!(ipa("V roce 1847 koupil mlýn.", Lang::Cs, None).contains("cˈisiːts"), "tisíc: ti is ť");
|
||||
// Quotes and dashes never become sounds; a dash is a pause.
|
||||
assert_eq!(ipa("»Ano« – řekl.", Lang::Cs, None), "ˈano, r̝ˈekl̩.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_merge_the_voices_clusters() {
|
||||
let clusters: Vec<(String, String)> = [("a", "ɪ"), ("a", "ʊ"), ("e", "ɪ"), ("o", "ʊ"), ("ɔ", "ɪ")]
|
||||
.iter()
|
||||
.map(|(a, b)| ((*a).to_owned(), (*b).to_owned()))
|
||||
.collect();
|
||||
assert_eq!(tokens("hˈaʊs", &clusters), ["h", "ˈ", "aʊ", "s"]);
|
||||
// ř is r + a combining mark (and a second for the voiceless one): separate symbols, as the voice learned them.
|
||||
assert_eq!(tokens("tr̝̊ˈi", &clusters), ["t", "r", "\u{31D}", "\u{30A}", "ˈ", "i"]);
|
||||
// ç decomposes (NFD) to c + combining cedilla, the way the German voice was trained.
|
||||
assert_eq!(tokens("ˈɪç", &clusters), ["ˈ", "ɪ", "c", "\u{327}"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_dictionaries_are_refused() {
|
||||
assert!(Lexicon::from_cmudict(&"A AH0\n".repeat(3_000_000)).is_none(), "over the byte cap");
|
||||
let odd = Lexicon::from_cmudict("WORD\n\n \nX \u{0}\u{0}\n").expect("parses");
|
||||
assert!(odd.is_empty());
|
||||
}
|
||||
@@ -9,6 +9,7 @@ fn fixture(lang: Lang) -> Vec<(String, String)> {
|
||||
Lang::En => include_str!("fixtures/lemma_en.tsv"),
|
||||
Lang::De => include_str!("fixtures/lemma_de.tsv"),
|
||||
Lang::La => include_str!("fixtures/lemma_la.tsv"),
|
||||
Lang::Cs => "",
|
||||
};
|
||||
text.lines()
|
||||
.map(|l| l.trim_end_matches('\r'))
|
||||
|
||||
@@ -180,6 +180,12 @@ pub enum Op {
|
||||
list: String,
|
||||
upto: u32,
|
||||
},
|
||||
/// Day 4: where an audiobook file is, to the millisecond (the latest write wins, so any device resumes there).
|
||||
AudioPosition {
|
||||
book: String,
|
||||
sha256: String,
|
||||
ms: u64,
|
||||
},
|
||||
/// Day 3: a book file is an edition in another language (`None`: it is the book's own language again).
|
||||
Edition {
|
||||
book: String,
|
||||
|
||||
@@ -129,6 +129,9 @@ pub fn ops_from(lib: &Library) -> Vec<Op> {
|
||||
if b.to_read {
|
||||
ops.push(set(Field::ToRead, json!(true)));
|
||||
}
|
||||
if let Some((sha, ms)) = &b.audio_position {
|
||||
ops.push(Op::AudioPosition { book: id.clone(), sha256: sha.clone(), ms: *ms });
|
||||
}
|
||||
if b.familiar {
|
||||
ops.push(set(Field::Familiar, json!(true)));
|
||||
}
|
||||
|
||||
@@ -212,6 +212,9 @@ pub struct Book {
|
||||
pub position: Option<Position>,
|
||||
/// The most recent position, when it is behind the furthest: "Jump back to page X?".
|
||||
pub last_position: Option<Position>,
|
||||
/// Day 4: the audiobook's place: (file sha256, milliseconds).
|
||||
#[serde(default)]
|
||||
pub audio_position: Option<(String, u64)>,
|
||||
/// Day 3: read before in the reader's own language.
|
||||
#[serde(default)]
|
||||
pub familiar: bool,
|
||||
@@ -242,6 +245,7 @@ impl Book {
|
||||
last_position: None,
|
||||
familiar: false,
|
||||
editions: BTreeMap::new(),
|
||||
audio_position: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -773,6 +777,15 @@ impl Library {
|
||||
self.bands.insert(lang.clone(), Band { list: list.clone(), upto: (*upto).min(1_000_000) });
|
||||
}
|
||||
}
|
||||
Op::AudioPosition { book, sha256, ms } => {
|
||||
let ok =
|
||||
sha256.len() == 64 && sha256.bytes().all(|b| b.is_ascii_hexdigit()) && *ms < 1_000 * 3_600 * 1_000;
|
||||
if let Some(b) = self.book_mut(book)
|
||||
&& ok
|
||||
{
|
||||
b.audio_position = Some((sha256.to_ascii_lowercase(), *ms));
|
||||
}
|
||||
}
|
||||
Op::Edition { book, sha256, language } => {
|
||||
let ok = sha256.len() == 64 && sha256.bytes().all(|b| b.is_ascii_hexdigit());
|
||||
if let Some(b) = self.book_mut(book)
|
||||
|
||||
@@ -94,3 +94,23 @@ fn familiar_and_editions_on_a_book_and_through_an_export() {
|
||||
evs2.push(ev("7", "x", &mut c, 7, Op::Edition { book: "b".into(), sha256: sha, language: None }));
|
||||
assert!(Library::from_events(&evs2).books["b"].editions.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_audiobook_position_is_the_latest_write_and_survives_an_export() {
|
||||
let (mut pc, mut dc) = (Clock::default(), Clock::default());
|
||||
let sha = "cd".repeat(32);
|
||||
let pos = |ms: u64| Op::AudioPosition { book: "b".into(), sha256: sha.clone(), ms };
|
||||
let evs = vec![
|
||||
ev("0", "desk", &mut dc, 1, Op::BookAdd { book: "b".into(), info: info(1), restore: false }),
|
||||
ev("1", "desk", &mut dc, 1_000, pos(61_000)),
|
||||
ev("2", "phone", &mut pc, 2_000, pos(95_250)),
|
||||
ev("3", "phone", &mut pc, 3_000, Op::AudioPosition { book: "b".into(), sha256: "nope".into(), ms: 5 }),
|
||||
];
|
||||
let mut rev = evs.clone();
|
||||
rev.reverse();
|
||||
let lib = Library::from_events(&evs);
|
||||
assert_eq!(lib, Library::from_events(&rev));
|
||||
assert_eq!(lib.books["b"].audio_position, Some((sha.clone(), 95_250)), "to the millisecond, the latest write");
|
||||
let back = Library::from_events(&events_from(&lib, "restore", 10));
|
||||
assert_eq!(back.books.values().next().and_then(|b| b.audio_position.clone()), Some((sha, 95_250)));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user