Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 22c898e38f | |||
| 7be8fca42b | |||
| 8f43cb2c4c | |||
| 388e8e01c4 | |||
| 1d6693a195 | |||
| 7aa13d6c0a | |||
| 068dc6cfb7 | |||
| 31cf11cbbe | |||
| bb0a63a173 | |||
| 5f2cd1b7c1 | |||
| 92cb0b7d84 | |||
| 42404e8a1d | |||
| 40c2b5377b | |||
| 7dca9de95c | |||
| 4e68eec3c4 | |||
| 9a2ba174ce |
@@ -10,12 +10,22 @@ on this one **by git tag**, never by a path. The roadmap and the day pages are i
|
|||||||
crates/liber-format EPUB 2/3, FB2 (+ .fb2.zip), TXT, DRM-free MOBI/AZW3 -> one Document; the zip reader and
|
crates/liber-format EPUB 2/3, FB2 (+ .fb2.zip), TXT, DRM-free MOBI/AZW3 -> one Document; the zip reader and
|
||||||
writer; the sanitizer (whitelist, no scripts, no remote URLs); positions (CFI + text quote)
|
writer; the sanitizer (whitelist, no scripts, no remote URLs); positions (CFI + text quote)
|
||||||
crates/liber-library book identity (ISBN, text fingerprint), the library model, the event log and its merge
|
crates/liber-library book identity (ISBN, text fingerprint), the library model, the event log and its merge
|
||||||
(sync semantics), stats, Goodreads/StoryGraph CSV import, the liber-export format
|
(sync semantics), stats, Goodreads/StoryGraph CSV import, the liber-export format;
|
||||||
|
Day 5 `together`: what another person's Liber sends (strictly parsed), where a shared note
|
||||||
|
lands in one's own copy (exact / approximate / lost), the spoiler guard, recording approval
|
||||||
|
crates/liber-habit Day 2: the local day (the only day computation in Liber), days read, the forgiving streak,
|
||||||
|
the reminder schedule, the medal rules (a pure function of the log)
|
||||||
|
crates/liber-lang Day 3: words by UAX #29 with UTF-16 offsets, the Lemmatizer trait (a licensed table first,
|
||||||
|
hand-written rules per language after), a book's lemma counts, coverage, the warm-up, levels,
|
||||||
|
Ludus concept ids, edition alignment (Gale–Church with anchors). Ships no outside data.
|
||||||
|
crates/liber-audio Day 4: the audio engine, reusable (no Liber types): WSOLA time-stretch, silence trimming,
|
||||||
|
voice boost, chapters, queue, sleep timer, position saving, the read-aloud timeline and cache
|
||||||
|
key; MP4/ID3/cue containers with DRM detection (refused, never decrypted); symphonia decoding
|
||||||
fixtures-fetch/ sha256-pinned hostile corpora -> fixtures/fetched/ (never in git; the tests generate theirs)
|
fixtures-fetch/ sha256-pinned hostile corpora -> fixtures/fetched/ (never in git; the tests generate theirs)
|
||||||
docs/ FORMATS.md (formats, limits, positions, DRM), DEPENDENCIES.md (every crate, its licence)
|
docs/ FORMATS.md (formats, limits, positions, DRM), DEPENDENCIES.md (every crate, its licence)
|
||||||
scripts/deps.mjs regenerates the crate table in DEPENDENCIES.md; exits 1 on a licence outside the allowed set
|
scripts/deps.mjs regenerates the crate table in DEPENDENCIES.md; exits 1 on a licence outside the allowed set
|
||||||
```
|
```
|
||||||
Direction: `liber-library -> liber-format`. Neither crate opens files, sockets or reads the clock: bytes in, values
|
Direction: `liber-habit -> liber-library -> liber-format`; `liber-lang` and `liber-audio` stand alone. No crate opens files, sockets or reads the clock: bytes in, values
|
||||||
out; time and ids are parameters (`tests/purity.rs` checks the sources).
|
out; time and ids are parameters (`tests/purity.rs` checks the sources).
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|||||||
Generated
+182
-5
@@ -8,6 +8,12 @@ version = "2.0.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "arrayvec"
|
||||||
|
version = "0.7.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "autocfg"
|
name = "autocfg"
|
||||||
version = "1.5.1"
|
version = "1.5.1"
|
||||||
@@ -39,6 +45,12 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bitflags"
|
||||||
|
version = "1.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bitflags"
|
name = "bitflags"
|
||||||
version = "2.13.2"
|
version = "2.13.2"
|
||||||
@@ -78,6 +90,12 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bytemuck"
|
||||||
|
version = "1.25.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bytes"
|
name = "bytes"
|
||||||
version = "1.12.1"
|
version = "1.12.1"
|
||||||
@@ -222,6 +240,12 @@ dependencies = [
|
|||||||
"windows-sys",
|
"windows-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "extended"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fastrand"
|
name = "fastrand"
|
||||||
version = "2.5.0"
|
version = "2.5.0"
|
||||||
@@ -289,15 +313,31 @@ version = "1.0.19"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lazy_static"
|
||||||
|
version = "1.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libc"
|
name = "libc"
|
||||||
version = "0.2.191"
|
version = "0.2.191"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "liber-audio"
|
||||||
|
version = "0.6.0"
|
||||||
|
dependencies = [
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
|
"symphonia",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-format"
|
name = "liber-format"
|
||||||
version = "0.1.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64",
|
"base64",
|
||||||
"chardetng",
|
"chardetng",
|
||||||
@@ -315,9 +355,31 @@ dependencies = [
|
|||||||
"unicode-normalization",
|
"unicode-normalization",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "liber-habit"
|
||||||
|
version = "0.6.0"
|
||||||
|
dependencies = [
|
||||||
|
"liber-library",
|
||||||
|
"proptest",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "liber-lang"
|
||||||
|
version = "0.6.0"
|
||||||
|
dependencies = [
|
||||||
|
"proptest",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
|
"unicode-normalization",
|
||||||
|
"unicode-segmentation",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-library"
|
name = "liber-library"
|
||||||
version = "0.1.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"csv",
|
"csv",
|
||||||
"encoding_rs",
|
"encoding_rs",
|
||||||
@@ -509,7 +571,7 @@ checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"bit-set",
|
"bit-set",
|
||||||
"bit-vec",
|
"bit-vec",
|
||||||
"bitflags",
|
"bitflags 2.13.2",
|
||||||
"chacha20",
|
"chacha20",
|
||||||
"core_detect",
|
"core_detect",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
@@ -582,7 +644,7 @@ version = "0.5.18"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags",
|
"bitflags 2.13.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -597,7 +659,7 @@ version = "1.1.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags",
|
"bitflags 2.13.2",
|
||||||
"errno",
|
"errno",
|
||||||
"libc",
|
"libc",
|
||||||
"linux-raw-sys",
|
"linux-raw-sys",
|
||||||
@@ -731,6 +793,115 @@ dependencies = [
|
|||||||
"quote",
|
"quote",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
"symphonia-bundle-mp3",
|
||||||
|
"symphonia-codec-aac",
|
||||||
|
"symphonia-codec-pcm",
|
||||||
|
"symphonia-core",
|
||||||
|
"symphonia-format-isomp4",
|
||||||
|
"symphonia-format-riff",
|
||||||
|
"symphonia-metadata",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-bundle-mp3"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
"symphonia-metadata",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-codec-aac"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-codec-pcm"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4e89d716c01541ad3ebe7c91ce4c8d38a7cf266a3f7b2f090b108fb0cb031d95"
|
||||||
|
dependencies = [
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-core"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af"
|
||||||
|
dependencies = [
|
||||||
|
"arrayvec",
|
||||||
|
"bitflags 1.3.2",
|
||||||
|
"bytemuck",
|
||||||
|
"lazy_static",
|
||||||
|
"log",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-format-isomp4"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5"
|
||||||
|
dependencies = [
|
||||||
|
"encoding_rs",
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
"symphonia-metadata",
|
||||||
|
"symphonia-utils-xiph",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-format-riff"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c2d7c3df0e7d94efb68401d81906eae73c02b40d5ec1a141962c592d0f11a96f"
|
||||||
|
dependencies = [
|
||||||
|
"extended",
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
"symphonia-metadata",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-metadata"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16"
|
||||||
|
dependencies = [
|
||||||
|
"encoding_rs",
|
||||||
|
"lazy_static",
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-utils-xiph"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16"
|
||||||
|
dependencies = [
|
||||||
|
"symphonia-core",
|
||||||
|
"symphonia-metadata",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "3.0.10"
|
version = "3.0.10"
|
||||||
@@ -847,6 +1018,12 @@ dependencies = [
|
|||||||
"tinyvec",
|
"tinyvec",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-segmentation"
|
||||||
|
version = "1.13.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "version_check"
|
name = "version_check"
|
||||||
version = "0.9.5"
|
version = "0.9.5"
|
||||||
|
|||||||
+3
-2
@@ -1,9 +1,9 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
members = ["crates/liber-format", "crates/liber-library"]
|
members = ["crates/liber-format", "crates/liber-library", "crates/liber-habit", "crates/liber-lang", "crates/liber-audio"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.0"
|
version = "0.6.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
repository = "https://gitea.marek-novak.cz/mnovak/Liber-public"
|
repository = "https://gitea.marek-novak.cz/mnovak/Liber-public"
|
||||||
@@ -30,6 +30,7 @@ serde_json = "1"
|
|||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
csv = "1"
|
csv = "1"
|
||||||
proptest = "1"
|
proptest = "1"
|
||||||
|
unicode-segmentation = "1"
|
||||||
|
|
||||||
[profile.dev.package."*"]
|
[profile.dev.package."*"]
|
||||||
opt-level = 2
|
opt-level = 2
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
[package]
|
||||||
|
name = "liber-audio"
|
||||||
|
description = "Liber Domi: the audio engine (time-stretch, silence trimming, voice boost, chapters, queue, sleep timer) and audiobook containers"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde.workspace = true
|
||||||
|
sha2.workspace = true
|
||||||
|
symphonia = { version = "0.5", default-features = false, features = ["mp3", "aac", "isomp4", "wav", "pcm"] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
serde_json.workspace = true
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
//! Voice boost: a high-pass at 80 Hz (rumble), a presence bell at 2.5 kHz (+5 dB, where consonants live), a
|
||||||
|
//! compressor (−24 dBFS, 3:1, 5 ms attack, 80 ms release, +6 dB make-up) and a limiter that never lets a sample past
|
||||||
|
//! ±1. Biquads after Robert Bristow-Johnson's Audio EQ Cookbook.
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
|
struct Biquad {
|
||||||
|
b0: f32,
|
||||||
|
b1: f32,
|
||||||
|
b2: f32,
|
||||||
|
a1: f32,
|
||||||
|
a2: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Biquad {
|
||||||
|
fn highpass(rate: f32, f: f32, q: f32) -> Biquad {
|
||||||
|
let w = 2.0 * std::f32::consts::PI * f / rate;
|
||||||
|
let (s, c) = w.sin_cos();
|
||||||
|
let alpha = s / (2.0 * q);
|
||||||
|
let a0 = 1.0 + alpha;
|
||||||
|
Biquad {
|
||||||
|
b0: (1.0 + c) / 2.0 / a0,
|
||||||
|
b1: -(1.0 + c) / a0,
|
||||||
|
b2: (1.0 + c) / 2.0 / a0,
|
||||||
|
a1: -2.0 * c / a0,
|
||||||
|
a2: (1.0 - alpha) / a0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn peaking(rate: f32, f: f32, q: f32, gain_db: f32) -> Biquad {
|
||||||
|
let a = 10f32.powf(gain_db / 40.0);
|
||||||
|
let w = 2.0 * std::f32::consts::PI * f / rate;
|
||||||
|
let (s, c) = w.sin_cos();
|
||||||
|
let alpha = s / (2.0 * q);
|
||||||
|
let a0 = 1.0 + alpha / a;
|
||||||
|
Biquad {
|
||||||
|
b0: (1.0 + alpha * a) / a0,
|
||||||
|
b1: -2.0 * c / a0,
|
||||||
|
b2: (1.0 - alpha * a) / a0,
|
||||||
|
a1: -2.0 * c / a0,
|
||||||
|
a2: (1.0 - alpha / a) / a0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One biquad's state per channel (direct form I).
|
||||||
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
|
struct State {
|
||||||
|
x1: f32,
|
||||||
|
x2: f32,
|
||||||
|
y1: f32,
|
||||||
|
y2: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl State {
|
||||||
|
fn run(&mut self, f: &Biquad, x: f32) -> f32 {
|
||||||
|
let y = f.b0 * x + f.b1 * self.x1 + f.b2 * self.x2 - f.a1 * self.y1 - f.a2 * self.y2;
|
||||||
|
self.x2 = self.x1;
|
||||||
|
self.x1 = x;
|
||||||
|
self.y2 = self.y1;
|
||||||
|
self.y1 = y;
|
||||||
|
y
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Boost {
|
||||||
|
channels: usize,
|
||||||
|
hp: Biquad,
|
||||||
|
bell: Biquad,
|
||||||
|
states: Vec<(State, State)>,
|
||||||
|
env: f32,
|
||||||
|
attack: f32,
|
||||||
|
release: f32,
|
||||||
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
const THRESHOLD_DB: f32 = -24.0;
|
||||||
|
const RATIO: f32 = 3.0;
|
||||||
|
const MAKEUP_DB: f32 = 6.0;
|
||||||
|
|
||||||
|
impl Boost {
|
||||||
|
pub fn new(rate: u32, channels: u16) -> Boost {
|
||||||
|
let r = rate.max(8_000) as f32;
|
||||||
|
let channels = channels.max(1) as usize;
|
||||||
|
Boost {
|
||||||
|
channels,
|
||||||
|
hp: Biquad::highpass(r, 80.0, std::f32::consts::FRAC_1_SQRT_2),
|
||||||
|
bell: Biquad::peaking(r, 2_500.0, 1.0, 5.0),
|
||||||
|
states: vec![(State::default(), State::default()); channels],
|
||||||
|
env: 0.0,
|
||||||
|
attack: (-1.0 / (0.005 * r)).exp(),
|
||||||
|
release: (-1.0 / (0.080 * r)).exp(),
|
||||||
|
enabled: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// In place, interleaved.
|
||||||
|
pub fn process(&mut self, samples: &mut [f32]) {
|
||||||
|
if !self.enabled {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let ch = self.channels;
|
||||||
|
let makeup = 10f32.powf(MAKEUP_DB / 20.0);
|
||||||
|
for frame in samples.chunks_mut(ch) {
|
||||||
|
let mut peak = 0.0f32;
|
||||||
|
for (c, x) in frame.iter_mut().enumerate() {
|
||||||
|
let (hp, bell) = &mut self.states[c];
|
||||||
|
let y = hp.run(&self.hp, *x);
|
||||||
|
*x = bell.run(&self.bell, y);
|
||||||
|
peak = peak.max(x.abs());
|
||||||
|
}
|
||||||
|
// Envelope follower on the frame's peak, then the gain the compressor applies.
|
||||||
|
let coef = if peak > self.env { self.attack } else { self.release };
|
||||||
|
self.env = coef * self.env + (1.0 - coef) * peak;
|
||||||
|
let level_db = 20.0 * self.env.max(1e-9).log10();
|
||||||
|
let over = (level_db - THRESHOLD_DB).max(0.0);
|
||||||
|
let gain = 10f32.powf(-(over - over / RATIO) / 20.0) * makeup;
|
||||||
|
for x in frame.iter_mut() {
|
||||||
|
// The limiter: a soft knee from 0.9, never past 1.
|
||||||
|
let y = *x * gain;
|
||||||
|
*x = if y.abs() <= 0.9 { y } else { y.signum() * (0.9 + 0.1 * ((y.abs() - 0.9) / 0.1).tanh()) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,577 @@
|
|||||||
|
//! What is inside an audiobook file before any decoding: the container, its duration, its chapters, and whether it
|
||||||
|
//! is DRM-protected. MP4 (M4B/M4A: a walk over the boxes), MP3 (the ID3v2 tag's `CHAP` frames) and `.cue` sheets.
|
||||||
|
//! Every number read from a file is checked against the bytes actually there and against [`Caps`]; nothing is
|
||||||
|
//! allocated from a size a file claims. There is no decrypt path: DRM is only detected.
|
||||||
|
|
||||||
|
use crate::player::{Chapter, MAX_CHAPTERS, tidy};
|
||||||
|
|
||||||
|
pub const DRM_MESSAGE: &str = "This audiobook is DRM-protected, so Liber cannot play it.";
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct Caps {
|
||||||
|
pub max_boxes: usize,
|
||||||
|
pub max_depth: usize,
|
||||||
|
/// An ID3v2 tag larger than this is refused (cover art included).
|
||||||
|
pub max_tag: usize,
|
||||||
|
pub max_frames: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Caps {
|
||||||
|
fn default() -> Self {
|
||||||
|
Caps { max_boxes: 200_000, max_depth: 16, max_tag: 16 << 20, max_frames: 20_000 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum AudioError {
|
||||||
|
Drm,
|
||||||
|
/// Not an audio file Liber reads.
|
||||||
|
Unsupported,
|
||||||
|
/// Broken: truncated, inconsistent sizes, or over a cap.
|
||||||
|
Damaged(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AudioError {
|
||||||
|
pub fn message(&self) -> String {
|
||||||
|
match self {
|
||||||
|
AudioError::Drm => DRM_MESSAGE.into(),
|
||||||
|
AudioError::Unsupported => "Liber plays MP3, M4B, M4A and WAV audiobooks.".into(),
|
||||||
|
AudioError::Damaged(why) => format!("This audio file is damaged ({why})."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Kind {
|
||||||
|
Mp4,
|
||||||
|
Mp3,
|
||||||
|
Wav,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Info {
|
||||||
|
pub kind: Kind,
|
||||||
|
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.
|
||||||
|
pub fn sniff(head: &[u8]) -> Option<Kind> {
|
||||||
|
if head.len() >= 12 && &head[4..8] == b"ftyp" {
|
||||||
|
return Some(Kind::Mp4);
|
||||||
|
}
|
||||||
|
if head.starts_with(b"ID3") || (head.len() >= 2 && head[0] == 0xFF && head[1] & 0xE0 == 0xE0) {
|
||||||
|
return Some(Kind::Mp3);
|
||||||
|
}
|
||||||
|
if head.len() >= 12 && &head[..4] == b"RIFF" && &head[8..12] == b"WAVE" {
|
||||||
|
return Some(Kind::Wav);
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the container's facts. `bytes` is the start of the file (MP4 metadata lives in `moov`, which may be at the
|
||||||
|
/// end: pass the whole file, or at least the boxes up to `moov`).
|
||||||
|
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![],
|
||||||
|
chapter_samples: vec![],
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn be32(b: &[u8], at: usize) -> Option<u32> {
|
||||||
|
b.get(at..at + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn be64(b: &[u8], at: usize) -> Option<u64> {
|
||||||
|
b.get(at..at + 8).map(|s| u64::from_be_bytes(s.try_into().expect("8 bytes")))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- MP4 ----------
|
||||||
|
|
||||||
|
struct Walk<'a> {
|
||||||
|
caps: Caps,
|
||||||
|
boxes: usize,
|
||||||
|
drm: bool,
|
||||||
|
timescale: Option<u32>,
|
||||||
|
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 ()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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).
|
||||||
|
let ftyp_size = be32(b, 0).ok_or(AudioError::Damaged("no ftyp"))? as usize;
|
||||||
|
if ftyp_size < 16 || ftyp_size > b.len().min(4096) {
|
||||||
|
return Err(AudioError::Damaged("ftyp size"));
|
||||||
|
}
|
||||||
|
let drm_brand = |c: &[u8]| c == b"aax " || c == b"aaxc";
|
||||||
|
if drm_brand(&b[8..12]) || b[16..ftyp_size].as_chunks::<4>().0.iter().any(|c| drm_brand(c)) {
|
||||||
|
return Err(AudioError::Drm);
|
||||||
|
}
|
||||||
|
let mut w = Walk {
|
||||||
|
caps,
|
||||||
|
boxes: 0,
|
||||||
|
drm: false,
|
||||||
|
timescale: None,
|
||||||
|
duration: None,
|
||||||
|
chapters: vec![],
|
||||||
|
title: None,
|
||||||
|
tracks: vec![],
|
||||||
|
cur: None,
|
||||||
|
_b: Default::default(),
|
||||||
|
};
|
||||||
|
walk(&mut w, b, 0, b.len(), 0)?;
|
||||||
|
if w.drm {
|
||||||
|
return Err(AudioError::Drm);
|
||||||
|
}
|
||||||
|
let duration_ms = match (w.timescale, w.duration) {
|
||||||
|
(Some(ts), Some(d)) if ts > 0 => Some(d.saturating_mul(1000) / u64::from(ts)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
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> {
|
||||||
|
if depth > w.caps.max_depth {
|
||||||
|
return Err(AudioError::Damaged("boxes nested too deep"));
|
||||||
|
}
|
||||||
|
let mut at = from;
|
||||||
|
while at + 8 <= to {
|
||||||
|
w.boxes += 1;
|
||||||
|
if w.boxes > w.caps.max_boxes {
|
||||||
|
return Err(AudioError::Damaged("too many boxes"));
|
||||||
|
}
|
||||||
|
let size32 = be32(b, at).expect("8 bytes checked") as u64;
|
||||||
|
let kind: [u8; 4] = b[at + 4..at + 8].try_into().expect("4 bytes");
|
||||||
|
let (header, size) = match size32 {
|
||||||
|
1 => (16u64, be64(b, at + 8).ok_or(AudioError::Damaged("box size"))?),
|
||||||
|
0 => (8, (to - at) as u64),
|
||||||
|
s => (8, s),
|
||||||
|
};
|
||||||
|
if size < header {
|
||||||
|
return Err(AudioError::Damaged("box size"));
|
||||||
|
}
|
||||||
|
// A box may claim more than the bytes we have (mdat in a partial read): read only what is here.
|
||||||
|
let end = (at as u64).saturating_add(size).min(to as u64) as usize;
|
||||||
|
let body = at + header as usize;
|
||||||
|
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)?,
|
||||||
|
b"meta" => walk(w, b, (body + 4).min(end), end, depth + 1)?,
|
||||||
|
b"stsd" => {
|
||||||
|
// FullBox + entry count, then sample entries: an encrypted entry means DRM.
|
||||||
|
walk(w, b, (body + 8).min(end), end, depth + 1)?;
|
||||||
|
}
|
||||||
|
b"mp4a" | b"enca" => {
|
||||||
|
if &kind == b"enca" {
|
||||||
|
w.drm = true;
|
||||||
|
}
|
||||||
|
// An audio sample entry: 28 bytes of fields, then child boxes (esds, sinf …).
|
||||||
|
walk(w, b, (body + 28).min(end), end, depth + 1)?;
|
||||||
|
}
|
||||||
|
b"sinf" | b"schi" => walk(w, b, body, end, depth + 1)?,
|
||||||
|
b"mvhd" => {
|
||||||
|
let version = *b.get(body).ok_or(AudioError::Damaged("mvhd"))?;
|
||||||
|
let (ts, d) = if version == 1 {
|
||||||
|
(be32(b, body + 20), be64(b, body + 24))
|
||||||
|
} else {
|
||||||
|
(be32(b, body + 12), be32(b, body + 16).map(u64::from))
|
||||||
|
};
|
||||||
|
w.timescale = ts;
|
||||||
|
w.duration = d;
|
||||||
|
}
|
||||||
|
b"chpl" => chpl(w, &b[body..end])?,
|
||||||
|
b"\xa9nam" => {
|
||||||
|
// ilst item: a `data` box with 8 bytes of type and locale before the text.
|
||||||
|
if let Some(t) = b.get(body + 16..end).and_then(|t| std::str::from_utf8(t).ok()) {
|
||||||
|
w.title = Some(t.chars().take(300).collect());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
if end <= at {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
at = end;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nero chapters: FullBox, (version 1: 4 reserved bytes), a count, then per chapter a start in 100 ns units and a
|
||||||
|
/// length-prefixed UTF-8 title.
|
||||||
|
fn chpl(w: &mut Walk, b: &[u8]) -> Result<(), AudioError> {
|
||||||
|
let version = *b.first().ok_or(AudioError::Damaged("chpl"))?;
|
||||||
|
let mut at = if version == 1 { 8 } else { 4 };
|
||||||
|
let count = *b.get(at).ok_or(AudioError::Damaged("chpl"))? as usize;
|
||||||
|
at += 1;
|
||||||
|
for _ in 0..count {
|
||||||
|
let start = be64(b, at).ok_or(AudioError::Damaged("chpl truncated"))?;
|
||||||
|
let len = *b.get(at + 8).ok_or(AudioError::Damaged("chpl truncated"))? as usize;
|
||||||
|
let title = b.get(at + 9..at + 9 + len).ok_or(AudioError::Damaged("chpl truncated"))?;
|
||||||
|
at += 9 + len;
|
||||||
|
if w.chapters.len() >= MAX_CHAPTERS {
|
||||||
|
return Err(AudioError::Damaged("too many chapters"));
|
||||||
|
}
|
||||||
|
w.chapters.push(Chapter {
|
||||||
|
title: String::from_utf8_lossy(title).into_owned(),
|
||||||
|
start_ms: start / 10_000,
|
||||||
|
end_ms: 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- MP3 (ID3v2) ----------
|
||||||
|
|
||||||
|
fn synchsafe(b: &[u8]) -> usize {
|
||||||
|
b.iter().fold(0usize, |acc, &x| (acc << 7) | (x & 0x7F) as usize)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mp3(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
if b.len() < 10 {
|
||||||
|
return Err(AudioError::Damaged("ID3 header"));
|
||||||
|
}
|
||||||
|
let major = b[3];
|
||||||
|
let size = synchsafe(&b[6..10]);
|
||||||
|
if size > caps.max_tag {
|
||||||
|
return Err(AudioError::Damaged("metadata block too large"));
|
||||||
|
}
|
||||||
|
let end = (10 + size).min(b.len());
|
||||||
|
let mut at = 10;
|
||||||
|
let mut frames = 0;
|
||||||
|
let mut chapters = Vec::new();
|
||||||
|
while at + 10 <= end {
|
||||||
|
let id = &b[at..at + 4];
|
||||||
|
if id[0] == 0 {
|
||||||
|
break; // padding
|
||||||
|
}
|
||||||
|
frames += 1;
|
||||||
|
if frames > caps.max_frames {
|
||||||
|
return Err(AudioError::Damaged("too many metadata frames"));
|
||||||
|
}
|
||||||
|
let fsize = if major >= 4 { synchsafe(&b[at + 4..at + 8]) } else { be32(b, at + 4).unwrap_or(0) as usize };
|
||||||
|
let body = at + 10;
|
||||||
|
let fend = body.checked_add(fsize).filter(|&e| e <= end).ok_or(AudioError::Damaged("ID3 frame size"))?;
|
||||||
|
match id {
|
||||||
|
b"TIT2" => info.title = text_frame(&b[body..fend]),
|
||||||
|
b"CHAP" => {
|
||||||
|
let f = &b[body..fend];
|
||||||
|
let z = f.iter().position(|&c| c == 0).ok_or(AudioError::Damaged("CHAP"))?;
|
||||||
|
let start = be32(f, z + 1).ok_or(AudioError::Damaged("CHAP"))? as u64;
|
||||||
|
let stop = be32(f, z + 5).ok_or(AudioError::Damaged("CHAP"))? as u64;
|
||||||
|
// Embedded frames: the chapter's TIT2.
|
||||||
|
let mut title = None;
|
||||||
|
let mut s = z + 17;
|
||||||
|
while s + 10 <= f.len() {
|
||||||
|
let sid = &f[s..s + 4];
|
||||||
|
let ssize =
|
||||||
|
if major >= 4 { synchsafe(&f[s + 4..s + 8]) } else { be32(f, s + 4).unwrap_or(0) as usize };
|
||||||
|
let Some(se) = (s + 10).checked_add(ssize).filter(|&e| e <= f.len()) else { break };
|
||||||
|
if sid == b"TIT2" {
|
||||||
|
title = text_frame(&f[s + 10..se]);
|
||||||
|
}
|
||||||
|
s = se;
|
||||||
|
}
|
||||||
|
if chapters.len() >= MAX_CHAPTERS {
|
||||||
|
return Err(AudioError::Damaged("too many chapters"));
|
||||||
|
}
|
||||||
|
chapters.push(Chapter { title: title.unwrap_or_default(), start_ms: start, end_ms: stop });
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
at = fend;
|
||||||
|
}
|
||||||
|
if !chapters.is_empty() {
|
||||||
|
let last = chapters.iter().map(|c| c.end_ms).max().unwrap_or(0);
|
||||||
|
info.duration_ms = Some(last);
|
||||||
|
info.chapters = tidy(chapters, last.max(1)).unwrap_or_default();
|
||||||
|
}
|
||||||
|
Ok(info)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An ID3 text frame: an encoding byte, then ISO-8859-1, UTF-16 (with BOM), UTF-16BE or UTF-8.
|
||||||
|
fn text_frame(f: &[u8]) -> Option<String> {
|
||||||
|
let (&enc, rest) = f.split_first()?;
|
||||||
|
let s = match enc {
|
||||||
|
0 => rest.iter().map(|&c| c as char).collect::<String>(),
|
||||||
|
1 | 2 => {
|
||||||
|
let (le, body) = match rest {
|
||||||
|
[0xFF, 0xFE, r @ ..] => (true, r),
|
||||||
|
[0xFE, 0xFF, r @ ..] => (false, r),
|
||||||
|
r => (enc == 1, r),
|
||||||
|
};
|
||||||
|
let units: Vec<u16> = body
|
||||||
|
.as_chunks::<2>()
|
||||||
|
.0
|
||||||
|
.iter()
|
||||||
|
.map(|&c| if le { u16::from_le_bytes(c) } else { u16::from_be_bytes(c) })
|
||||||
|
.collect();
|
||||||
|
String::from_utf16_lossy(&units)
|
||||||
|
}
|
||||||
|
3 => String::from_utf8_lossy(rest).into_owned(),
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
let s = s.trim_matches(char::from(0)).trim().chars().take(300).collect::<String>();
|
||||||
|
(!s.is_empty()).then_some(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wav_duration(b: &[u8]) -> Option<u64> {
|
||||||
|
// fmt at 12 in the common layout; data size from the `data` chunk.
|
||||||
|
let mut at = 12;
|
||||||
|
let (mut rate, mut block) = (0u32, 0u16);
|
||||||
|
while at + 8 <= b.len() {
|
||||||
|
let id = &b[at..at + 4];
|
||||||
|
let size = u32::from_le_bytes(b[at + 4..at + 8].try_into().ok()?) as usize;
|
||||||
|
if id == b"fmt " && at + 24 <= b.len() {
|
||||||
|
rate = u32::from_le_bytes(b[at + 12..at + 16].try_into().ok()?);
|
||||||
|
block = u16::from_le_bytes(b[at + 20..at + 22].try_into().ok()?);
|
||||||
|
}
|
||||||
|
if id == b"data" {
|
||||||
|
if rate == 0 || block == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
return Some(size as u64 * 1000 / (u64::from(rate) * u64::from(block)));
|
||||||
|
}
|
||||||
|
at = at.checked_add(8 + size + (size & 1))?;
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- .cue ----------
|
||||||
|
|
||||||
|
/// A cue sheet's tracks as chapters (one audio file; `INDEX 01 mm:ss:ff`, 75 frames a second).
|
||||||
|
pub fn cue(text: &str, duration_ms: u64) -> Option<Vec<Chapter>> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut title = String::new();
|
||||||
|
for line in text.lines().take(100_000) {
|
||||||
|
let l = line.trim();
|
||||||
|
if let Some(t) = l.strip_prefix("TITLE ") {
|
||||||
|
title = t.trim().trim_matches('"').to_owned();
|
||||||
|
} else if let Some(i) = l.strip_prefix("INDEX 01 ") {
|
||||||
|
let p: Vec<u64> = i.trim().split(':').filter_map(|x| x.parse().ok()).collect();
|
||||||
|
if let [m, s, f] = p[..] {
|
||||||
|
if out.len() >= MAX_CHAPTERS {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
out.push(Chapter {
|
||||||
|
title: std::mem::take(&mut title),
|
||||||
|
start_ms: m * 60_000 + s * 1_000 + f * 1_000 / 75,
|
||||||
|
end_ms: 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tidy(out, duration_ms)
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
//! Decoding through `symphonia` (MPL-2.0): MP3, AAC in MP4/M4A/M4B, WAV. The source is any `Read + Seek` the app
|
||||||
|
//! hands over (a file there, a byte buffer in tests); this crate opens nothing itself. Caps keep a hostile file from
|
||||||
|
//! running away: channels, sample rate, total decoded time, and consecutive decode errors.
|
||||||
|
|
||||||
|
use crate::container::AudioError;
|
||||||
|
use std::io::{Read, Seek};
|
||||||
|
use symphonia::core::audio::SampleBuffer;
|
||||||
|
use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions};
|
||||||
|
use symphonia::core::errors::Error as SymError;
|
||||||
|
use symphonia::core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo};
|
||||||
|
use symphonia::core::io::MediaSourceStream;
|
||||||
|
use symphonia::core::meta::MetadataOptions;
|
||||||
|
use symphonia::core::probe::Hint;
|
||||||
|
use symphonia::core::units::Time;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct DecodeCaps {
|
||||||
|
pub max_channels: u16,
|
||||||
|
pub max_rate: u32,
|
||||||
|
pub max_hours: u32,
|
||||||
|
/// Decode errors in a row before the stream counts as broken.
|
||||||
|
pub max_errors: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for DecodeCaps {
|
||||||
|
fn default() -> Self {
|
||||||
|
DecodeCaps { max_channels: 8, max_rate: 192_000, max_hours: 200, max_errors: 50 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `Read + Seek` that symphonia can use (it wants `Send + Sync`).
|
||||||
|
pub trait Source: Read + Seek + Send + Sync {}
|
||||||
|
impl<T: Read + Seek + Send + Sync> Source for T {}
|
||||||
|
|
||||||
|
struct Seekable<S: Source>(S, Option<u64>);
|
||||||
|
impl<S: Source> Read for Seekable<S> {
|
||||||
|
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||||
|
self.0.read(buf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<S: Source> Seek for Seekable<S> {
|
||||||
|
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||||
|
self.0.seek(pos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<S: Source> symphonia::core::io::MediaSource for Seekable<S> {
|
||||||
|
fn is_seekable(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
fn byte_len(&self) -> Option<u64> {
|
||||||
|
self.1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Decoder {
|
||||||
|
format: Box<dyn FormatReader>,
|
||||||
|
decoder: Box<dyn symphonia::core::codecs::Decoder>,
|
||||||
|
track: u32,
|
||||||
|
pub rate: u32,
|
||||||
|
pub channels: u16,
|
||||||
|
caps: DecodeCaps,
|
||||||
|
decoded_frames: u64,
|
||||||
|
errors: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn err(e: SymError) -> AudioError {
|
||||||
|
match e {
|
||||||
|
SymError::Unsupported(_) => AudioError::Unsupported,
|
||||||
|
_ => AudioError::Damaged("the audio stream cannot be read"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Decoder {
|
||||||
|
/// Opens a stream. `len` is the byte length when known; `ext` only a hint (content decides).
|
||||||
|
pub fn open<S: Source + 'static>(
|
||||||
|
source: S,
|
||||||
|
len: Option<u64>,
|
||||||
|
ext: Option<&str>,
|
||||||
|
caps: DecodeCaps,
|
||||||
|
) -> Result<Decoder, AudioError> {
|
||||||
|
let mss = MediaSourceStream::new(Box::new(Seekable(source, len)), Default::default());
|
||||||
|
let mut hint = Hint::new();
|
||||||
|
if let Some(e) = ext {
|
||||||
|
hint.with_extension(e);
|
||||||
|
}
|
||||||
|
let probed = symphonia::default::get_probe()
|
||||||
|
.format(
|
||||||
|
&hint,
|
||||||
|
mss,
|
||||||
|
&FormatOptions { enable_gapless: true, ..Default::default() },
|
||||||
|
&MetadataOptions::default(),
|
||||||
|
)
|
||||||
|
.map_err(err)?;
|
||||||
|
let format = probed.format;
|
||||||
|
let track =
|
||||||
|
format.tracks().iter().find(|t| t.codec_params.codec != CODEC_TYPE_NULL).ok_or(AudioError::Unsupported)?;
|
||||||
|
let params = track.codec_params.clone();
|
||||||
|
let rate = params.sample_rate.ok_or(AudioError::Damaged("no sample rate"))?;
|
||||||
|
let channels = params.channels.map(|c| c.count() as u16).unwrap_or(1);
|
||||||
|
if rate < 4_000 || rate > caps.max_rate || channels == 0 || channels > caps.max_channels {
|
||||||
|
return Err(AudioError::Damaged("an impossible format"));
|
||||||
|
}
|
||||||
|
let decoder = symphonia::default::get_codecs().make(¶ms, &DecoderOptions::default()).map_err(err)?;
|
||||||
|
Ok(Decoder { track: track.id, format, decoder, rate, channels, caps, decoded_frames: 0, errors: 0 })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The next block of interleaved samples; `Ok(None)` at the end.
|
||||||
|
pub fn next_block(&mut self) -> Result<Option<Vec<f32>>, AudioError> {
|
||||||
|
loop {
|
||||||
|
if self.decoded_frames > u64::from(self.caps.max_hours) * 3600 * u64::from(self.rate) {
|
||||||
|
return Err(AudioError::Damaged("longer than any audiobook"));
|
||||||
|
}
|
||||||
|
let packet = match self.format.next_packet() {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(SymError::IoError(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
|
||||||
|
Err(SymError::ResetRequired) => return Ok(None),
|
||||||
|
Err(e) => {
|
||||||
|
self.errors += 1;
|
||||||
|
if self.errors > self.caps.max_errors {
|
||||||
|
return Err(err(e));
|
||||||
|
}
|
||||||
|
// A truncated or damaged file ends here rather than looping.
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if packet.track_id() != self.track {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match self.decoder.decode(&packet) {
|
||||||
|
Ok(buf) => {
|
||||||
|
self.errors = 0;
|
||||||
|
let spec = *buf.spec();
|
||||||
|
let frames = buf.frames();
|
||||||
|
if frames == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut sb = SampleBuffer::<f32>::new(frames as u64, spec);
|
||||||
|
sb.copy_interleaved_ref(buf);
|
||||||
|
self.decoded_frames += frames as u64;
|
||||||
|
return Ok(Some(sb.samples().to_vec()));
|
||||||
|
}
|
||||||
|
Err(SymError::DecodeError(_)) => {
|
||||||
|
self.errors += 1;
|
||||||
|
if self.errors > self.caps.max_errors {
|
||||||
|
return Err(AudioError::Damaged("too many decode errors"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => return Err(err(e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Jumps to a position (milliseconds); the next block starts there or just before.
|
||||||
|
pub fn seek(&mut self, ms: u64) -> Result<(), AudioError> {
|
||||||
|
let time = Time::new(ms / 1000, (ms % 1000) as f64 / 1000.0);
|
||||||
|
self.format.seek(SeekMode::Accurate, SeekTo::Time { time, track_id: Some(self.track) }).map_err(err)?;
|
||||||
|
self.decoder.reset();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For callers that have only bytes (tests, short clips): decodes everything.
|
||||||
|
pub fn decode_all(bytes: Vec<u8>, caps: DecodeCaps) -> Result<(u32, u16, Vec<f32>), AudioError> {
|
||||||
|
if crate::container::inspect(&bytes, Default::default()) == Err(AudioError::Drm) {
|
||||||
|
return Err(AudioError::Drm);
|
||||||
|
}
|
||||||
|
let len = bytes.len() as u64;
|
||||||
|
let mut d = Decoder::open(std::io::Cursor::new(bytes), Some(len), None, caps)?;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while let Some(b) = d.next_block()? {
|
||||||
|
out.extend_from_slice(&b);
|
||||||
|
}
|
||||||
|
Ok((d.rate, d.channels, out))
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
//! Liber Domi, Day 4: the audio engine. Everything above the decoder is ours: time-stretch, silence trimming, voice
|
||||||
|
//! boost, chapters, the queue, the sleep timer and when to save a position. It has no Liber types, so the listening
|
||||||
|
//! app and the AI radio can use it later. Pure: samples and bytes in, samples and values out; no files, devices or
|
||||||
|
//! clock (`liber-format`'s purity test scans this crate too). The day page is `docs/04_listening.md` in the app repo.
|
||||||
|
|
||||||
|
pub mod boost;
|
||||||
|
pub mod container;
|
||||||
|
pub mod decode;
|
||||||
|
pub mod player;
|
||||||
|
pub mod silence;
|
||||||
|
pub mod speech;
|
||||||
|
pub mod stretch;
|
||||||
|
|
||||||
|
pub use container::{AudioError, DRM_MESSAGE};
|
||||||
|
|
||||||
|
/// Stereo or more → one channel (TTS voices and level meters).
|
||||||
|
pub fn mono(samples: &[f32], channels: u16) -> Vec<f32> {
|
||||||
|
let ch = channels.max(1) as usize;
|
||||||
|
samples.chunks(ch).map(|f| f.iter().sum::<f32>() / ch as f32).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Linear resampling of interleaved samples (the output device's rate). Speech-quality, allocation-bounded by the
|
||||||
|
/// input.
|
||||||
|
pub fn resample(samples: &[f32], channels: u16, from: u32, to: u32) -> Vec<f32> {
|
||||||
|
if from == to || from == 0 || to == 0 {
|
||||||
|
return samples.to_vec();
|
||||||
|
}
|
||||||
|
let ch = channels.max(1) as usize;
|
||||||
|
let frames = samples.len() / ch;
|
||||||
|
let out_frames = (frames as u64 * u64::from(to) / u64::from(from)) as usize;
|
||||||
|
let mut out = Vec::with_capacity(out_frames * ch);
|
||||||
|
for i in 0..out_frames {
|
||||||
|
let pos = i as f64 * f64::from(from) / f64::from(to);
|
||||||
|
let j = pos as usize;
|
||||||
|
let t = (pos - j as f64) as f32;
|
||||||
|
for c in 0..ch {
|
||||||
|
let a = samples.get(j * ch + c).copied().unwrap_or(0.0);
|
||||||
|
let b = samples.get((j + 1) * ch + c).copied().unwrap_or(a);
|
||||||
|
out.push(a + (b - a) * t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
//! What a player knows, without a device or a clock: chapters, the queue, skips, the sleep timer and when to save
|
||||||
|
//! the position. The app drives it with the time it measures; every rule here is a pure function of that.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Most chapters an item may have (hostile metadata).
|
||||||
|
pub const MAX_CHAPTERS: usize = 10_000;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Chapter {
|
||||||
|
pub title: String,
|
||||||
|
pub start_ms: u64,
|
||||||
|
pub end_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Chapters as found, made sane: sorted, inside the duration, no zero-length or overlapping ones, at most
|
||||||
|
/// [`MAX_CHAPTERS`]; each ends where the next starts. `None` when there is nothing usable.
|
||||||
|
pub fn tidy(mut chapters: Vec<Chapter>, duration_ms: u64) -> Option<Vec<Chapter>> {
|
||||||
|
chapters.retain(|c| c.start_ms < duration_ms);
|
||||||
|
chapters.sort_by_key(|c| c.start_ms);
|
||||||
|
chapters.dedup_by_key(|c| c.start_ms);
|
||||||
|
chapters.truncate(MAX_CHAPTERS);
|
||||||
|
if chapters.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let n = chapters.len();
|
||||||
|
for i in 0..n {
|
||||||
|
let end = if i + 1 < n { chapters[i + 1].start_ms } else { duration_ms };
|
||||||
|
chapters[i].end_ms = end;
|
||||||
|
chapters[i].title = chapters[i].title.chars().take(200).collect::<String>().trim().to_owned();
|
||||||
|
if chapters[i].title.is_empty() {
|
||||||
|
chapters[i].title = format!("Chapter {}", i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(chapters)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The chapter that holds a position.
|
||||||
|
pub fn chapter_at(chapters: &[Chapter], ms: u64) -> Option<usize> {
|
||||||
|
chapters.iter().rposition(|c| c.start_ms <= ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The position after a skip, inside `0..=duration`.
|
||||||
|
pub fn skip(ms: u64, by_ms: i64, duration_ms: u64) -> u64 {
|
||||||
|
(ms as i64 + by_ms).clamp(0, duration_ms as i64) as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Previous chapter: back to this chapter's start, or to the one before when within the first 3 s of it.
|
||||||
|
pub fn previous_chapter(chapters: &[Chapter], ms: u64) -> u64 {
|
||||||
|
match chapter_at(chapters, ms) {
|
||||||
|
Some(i) if ms.saturating_sub(chapters[i].start_ms) < 3_000 && i > 0 => chapters[i - 1].start_ms,
|
||||||
|
Some(i) => chapters[i].start_ms,
|
||||||
|
None => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn next_chapter(chapters: &[Chapter], ms: u64) -> Option<u64> {
|
||||||
|
let i = chapter_at(chapters, ms).map_or(0, |i| i + 1);
|
||||||
|
chapters.get(i).map(|c| c.start_ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sleep timer.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||||
|
pub enum Sleep {
|
||||||
|
Off,
|
||||||
|
/// Stop when the device's monotonic clock reaches this.
|
||||||
|
At {
|
||||||
|
until_ms: u64,
|
||||||
|
},
|
||||||
|
/// Stop at the end of the chapter playing when it was set.
|
||||||
|
EndOfChapter {
|
||||||
|
chapter_end_ms: u64,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sleep {
|
||||||
|
pub fn minutes(now_ms: u64, minutes: u32) -> Sleep {
|
||||||
|
Sleep::At { until_ms: now_ms + u64::from(minutes.min(24 * 60)) * 60_000 }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn end_of_chapter(chapters: &[Chapter], position_ms: u64, duration_ms: u64) -> Sleep {
|
||||||
|
let end = chapter_at(chapters, position_ms).map_or(duration_ms, |i| chapters[i].end_ms);
|
||||||
|
Sleep::EndOfChapter { chapter_end_ms: end }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether playback should stop now.
|
||||||
|
pub fn due(&self, now_ms: u64, position_ms: u64) -> bool {
|
||||||
|
match *self {
|
||||||
|
Sleep::Off => false,
|
||||||
|
Sleep::At { until_ms } => now_ms >= until_ms,
|
||||||
|
Sleep::EndOfChapter { chapter_end_ms } => position_ms >= chapter_end_ms,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When to write the position: every 900 ms while playing (locally; the app syncs it on pause, chapter change and
|
||||||
|
/// every 30 s), and at once on pause, seek, chapter change or stop.
|
||||||
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
|
pub struct Saver {
|
||||||
|
last_ms: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// With playback blocks of at most 100 ms, a saved position is never more than a second behind.
|
||||||
|
pub const SAVE_EVERY_MS: u64 = 900;
|
||||||
|
pub const MAX_BLOCK_MS: u64 = 100;
|
||||||
|
|
||||||
|
impl Saver {
|
||||||
|
pub fn tick(&mut self, now_ms: u64) -> bool {
|
||||||
|
let due = self.last_ms.is_none_or(|l| now_ms.saturating_sub(l) >= SAVE_EVERY_MS);
|
||||||
|
if due {
|
||||||
|
self.last_ms = Some(now_ms);
|
||||||
|
}
|
||||||
|
due
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pause, seek, chapter change, stop: save now.
|
||||||
|
pub fn now(&mut self, now_ms: u64) -> bool {
|
||||||
|
self.last_ms = Some(now_ms);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A queue of things to play (an audiobook, a book read aloud, texts other apps sent).
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Queue<T> {
|
||||||
|
pub items: Vec<T>,
|
||||||
|
pub current: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Queue<T> {
|
||||||
|
pub fn push(&mut self, item: T) -> usize {
|
||||||
|
self.items.push(item);
|
||||||
|
if self.current.is_none() {
|
||||||
|
self.current = Some(self.items.len() - 1);
|
||||||
|
}
|
||||||
|
self.items.len() - 1
|
||||||
|
}
|
||||||
|
pub fn current(&self) -> Option<&T> {
|
||||||
|
self.current.and_then(|i| self.items.get(i))
|
||||||
|
}
|
||||||
|
pub fn advance(&mut self) -> Option<&T> {
|
||||||
|
let next = self.current.map_or(0, |i| i + 1);
|
||||||
|
self.current = (next < self.items.len()).then_some(next);
|
||||||
|
self.current()
|
||||||
|
}
|
||||||
|
pub fn remove(&mut self, i: usize) {
|
||||||
|
if i >= self.items.len() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.items.remove(i);
|
||||||
|
self.current = match self.current {
|
||||||
|
Some(c) if c == i => (c < self.items.len()).then_some(c),
|
||||||
|
Some(c) if c > i => Some(c - 1),
|
||||||
|
c => c,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
//! Silence trimming: pauses longer than `long` are shortened to `keep`; any frame louder than the threshold is never
|
||||||
|
//! removed. Streaming: the first `keep` of a pause goes out at once, the next part is held, and the held part is
|
||||||
|
//! dropped only once the pause has proved longer than `long`. A map turns output time back into input time, so a
|
||||||
|
//! position is always in the book's own seconds.
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct TrimConfig {
|
||||||
|
/// A 10 ms frame quieter than this (RMS, dBFS) is silence.
|
||||||
|
pub threshold_db: f32,
|
||||||
|
/// Pauses at least this long are shortened…
|
||||||
|
pub long_ms: u32,
|
||||||
|
/// …to this.
|
||||||
|
pub keep_ms: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for TrimConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
TrimConfig { threshold_db: -45.0, long_ms: 300, keep_ms: 150 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Trimmer {
|
||||||
|
cfg: TrimConfig,
|
||||||
|
channels: usize,
|
||||||
|
frame: usize,
|
||||||
|
threshold: f32,
|
||||||
|
/// Input not yet a whole frame.
|
||||||
|
pending: Vec<f32>,
|
||||||
|
/// Frames of the current pause held back (past `keep`, not yet `long`).
|
||||||
|
held: Vec<f32>,
|
||||||
|
/// Silent frames in the current pause so far.
|
||||||
|
run: usize,
|
||||||
|
keep_frames: usize,
|
||||||
|
long_frames: usize,
|
||||||
|
out: Vec<f32>,
|
||||||
|
/// Input and output frame counters, and (output, input) points where the two diverge.
|
||||||
|
in_frames: u64,
|
||||||
|
out_frames: u64,
|
||||||
|
map: Vec<(u64, u64)>,
|
||||||
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Trimmer {
|
||||||
|
pub fn new(rate: u32, channels: u16, cfg: TrimConfig) -> Trimmer {
|
||||||
|
let frame = (rate as usize / 100).max(1);
|
||||||
|
Trimmer {
|
||||||
|
cfg,
|
||||||
|
channels: channels.max(1) as usize,
|
||||||
|
frame,
|
||||||
|
threshold: 10f32.powf(cfg.threshold_db / 20.0),
|
||||||
|
pending: Vec::new(),
|
||||||
|
held: Vec::new(),
|
||||||
|
run: 0,
|
||||||
|
keep_frames: (cfg.keep_ms as usize).div_ceil(10),
|
||||||
|
long_frames: (cfg.long_ms as usize).div_ceil(10),
|
||||||
|
out: Vec::new(),
|
||||||
|
in_frames: 0,
|
||||||
|
out_frames: 0,
|
||||||
|
map: vec![(0, 0)],
|
||||||
|
enabled: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn config(&self) -> TrimConfig {
|
||||||
|
self.cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit(&mut self, block: &[f32]) {
|
||||||
|
self.out.extend_from_slice(block);
|
||||||
|
self.out_frames += (block.len() / self.channels) as u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn release_held(&mut self) {
|
||||||
|
let held = std::mem::take(&mut self.held);
|
||||||
|
self.emit(&held);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step(&mut self, frame: Vec<f32>) {
|
||||||
|
let n = frame.len() / self.channels;
|
||||||
|
if !self.enabled {
|
||||||
|
self.in_frames += n as u64;
|
||||||
|
self.emit(&frame);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let rms = (frame.iter().map(|x| x * x).sum::<f32>() / frame.len().max(1) as f32).sqrt();
|
||||||
|
let silent = rms < self.threshold;
|
||||||
|
if !silent {
|
||||||
|
// Speech: whatever was held belonged to a short pause; it goes out too.
|
||||||
|
self.release_held();
|
||||||
|
self.run = 0;
|
||||||
|
self.in_frames += n as u64;
|
||||||
|
self.emit(&frame);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.run += 1;
|
||||||
|
self.in_frames += n as u64;
|
||||||
|
if self.run <= self.keep_frames {
|
||||||
|
self.emit(&frame);
|
||||||
|
} else if self.run < self.long_frames {
|
||||||
|
self.held.extend_from_slice(&frame);
|
||||||
|
} else {
|
||||||
|
// A long pause: the held part and everything after it until speech is dropped.
|
||||||
|
self.held.clear();
|
||||||
|
// One map point per dropped pause: output stands still while input moves on.
|
||||||
|
match self.map.last_mut() {
|
||||||
|
Some(last) if last.0 == self.out_frames => last.1 = self.in_frames,
|
||||||
|
_ => self.map.push((self.out_frames, self.in_frames)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds interleaved samples.
|
||||||
|
pub fn push(&mut self, samples: &[f32]) {
|
||||||
|
self.pending.extend_from_slice(samples);
|
||||||
|
let size = self.frame * self.channels;
|
||||||
|
while self.pending.len() >= size {
|
||||||
|
let rest = self.pending.split_off(size);
|
||||||
|
let frame = std::mem::replace(&mut self.pending, rest);
|
||||||
|
self.step(frame);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// End of input: a held part of a short pause and the last partial frame go out.
|
||||||
|
pub fn finish(&mut self) {
|
||||||
|
self.release_held();
|
||||||
|
let rest = std::mem::take(&mut self.pending);
|
||||||
|
self.in_frames += (rest.len() / self.channels) as u64;
|
||||||
|
self.emit(&rest);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pull(&mut self) -> Vec<f32> {
|
||||||
|
std::mem::take(&mut self.out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The input frame an output frame came from (to report positions in the book's own time).
|
||||||
|
pub fn input_frame(&self, out_frame: u64) -> u64 {
|
||||||
|
let i = self.map.partition_point(|&(o, _)| o <= out_frame).saturating_sub(1);
|
||||||
|
let (o, inp) = self.map[i];
|
||||||
|
// Between map points output and input run together, except across a dropped pause where the last point
|
||||||
|
// already accounts for it.
|
||||||
|
let later = self.map.get(i + 1).map(|&(_, ni)| ni);
|
||||||
|
let guess = inp + (out_frame - o);
|
||||||
|
later.map_or(guess, |ni| guess.min(ni))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole of `samples`, trimmed (tests and short clips).
|
||||||
|
pub fn trim(samples: &[f32], rate: u32, channels: u16, cfg: TrimConfig) -> Vec<f32> {
|
||||||
|
let mut t = Trimmer::new(rate, channels, cfg);
|
||||||
|
t.push(samples);
|
||||||
|
t.finish();
|
||||||
|
t.pull()
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
//! Read-aloud bookkeeping, voice-agnostic: the cache key of a synthesized sentence, and the timeline that says which
|
||||||
|
//! sentence is being heard at a given moment (for the highlight), with pauses between sentences, after paragraphs
|
||||||
|
//! and after chapter titles. The voice itself runs in the app.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
/// Pauses inserted after a segment, by what ends there.
|
||||||
|
pub const PAUSE_SENTENCE_MS: u32 = 120;
|
||||||
|
pub const PAUSE_PARAGRAPH_MS: u32 = 600;
|
||||||
|
pub const PAUSE_TITLE_MS: u32 = 900;
|
||||||
|
|
||||||
|
/// The cache key of one synthesized sentence: everything that changes the audio is in it (the voice and its file
|
||||||
|
/// hash, the synthesis speed, the language, the exact text). Hex, so it is also a safe file name.
|
||||||
|
pub fn cache_key(voice: &str, voice_sha256: &str, speed: f32, lang: &str, text: &str) -> String {
|
||||||
|
let mut h = Sha256::new();
|
||||||
|
for part in [voice, voice_sha256, &format!("{speed:.3}"), lang, text] {
|
||||||
|
h.update((part.len() as u64).to_le_bytes());
|
||||||
|
h.update(part.as_bytes());
|
||||||
|
}
|
||||||
|
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum Ends {
|
||||||
|
Sentence,
|
||||||
|
Paragraph,
|
||||||
|
Title,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One spoken segment: its place in the book (chapter and UTF-16 range, opaque here), how long its audio is, what it
|
||||||
|
/// ends.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Segment {
|
||||||
|
pub chapter: usize,
|
||||||
|
pub start: usize,
|
||||||
|
pub end: usize,
|
||||||
|
pub audio_ms: u32,
|
||||||
|
pub ends: Ends,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Segments laid end to end with their pauses.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Timeline {
|
||||||
|
/// (start_ms, segment index), increasing.
|
||||||
|
starts: Vec<(u64, usize)>,
|
||||||
|
pub segments: Vec<Segment>,
|
||||||
|
pub total_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Timeline {
|
||||||
|
pub fn new(segments: Vec<Segment>) -> Timeline {
|
||||||
|
let mut at = 0u64;
|
||||||
|
let mut starts = Vec::with_capacity(segments.len());
|
||||||
|
for (i, s) in segments.iter().enumerate() {
|
||||||
|
starts.push((at, i));
|
||||||
|
at += u64::from(s.audio_ms)
|
||||||
|
+ u64::from(match s.ends {
|
||||||
|
Ends::Sentence => PAUSE_SENTENCE_MS,
|
||||||
|
Ends::Paragraph => PAUSE_PARAGRAPH_MS,
|
||||||
|
Ends::Title => PAUSE_TITLE_MS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Timeline { starts, segments, total_ms: at }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The segment being heard at `ms` (during its pause, still that segment); `None` past the end.
|
||||||
|
pub fn at(&self, ms: u64) -> Option<usize> {
|
||||||
|
if ms >= self.total_ms {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let i = self.starts.partition_point(|&(s, _)| s <= ms);
|
||||||
|
i.checked_sub(1).map(|k| self.starts[k].1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a segment's audio starts.
|
||||||
|
pub fn start_of(&self, segment: usize) -> Option<u64> {
|
||||||
|
self.starts.get(segment).map(|&(s, _)| s)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `ms` falls in a pause rather than in speech.
|
||||||
|
pub fn in_pause(&self, ms: u64) -> bool {
|
||||||
|
self.at(ms).is_some_and(|i| ms >= self.starts[i].0 + u64::from(self.segments[i].audio_ms))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
//! Speed without pitch: WSOLA (waveform-similarity overlap-add). Hann-windowed frames are overlap-added at a fixed
|
||||||
|
//! output hop; each next frame is taken from near its nominal input position (input advances `speed` times the
|
||||||
|
//! output hop), shifted by up to ±12 ms to where it best continues the frame before. Streaming: push input blocks,
|
||||||
|
//! pull output; the speed can change between blocks.
|
||||||
|
|
||||||
|
/// Frame length, overlap and search window, in seconds.
|
||||||
|
const FRAME: f64 = 0.040;
|
||||||
|
const SEARCH: f64 = 0.012;
|
||||||
|
pub const MIN_SPEED: f64 = 0.5;
|
||||||
|
pub const MAX_SPEED: f64 = 3.0;
|
||||||
|
|
||||||
|
pub struct Stretcher {
|
||||||
|
channels: usize,
|
||||||
|
n: usize,
|
||||||
|
hop: usize,
|
||||||
|
search: usize,
|
||||||
|
speed: f64,
|
||||||
|
window: Vec<f32>,
|
||||||
|
/// Interleaved input not yet consumed; `base` is the absolute frame index of its first frame.
|
||||||
|
input: Vec<f32>,
|
||||||
|
base: usize,
|
||||||
|
/// Nominal analysis position of the next frame (absolute, in frames), and the start chosen for the last one.
|
||||||
|
pos: f64,
|
||||||
|
last: Option<usize>,
|
||||||
|
/// Overlap-add accumulator: `n` frames, interleaved.
|
||||||
|
acc: Vec<f32>,
|
||||||
|
out: Vec<f32>,
|
||||||
|
flushed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stretcher {
|
||||||
|
pub fn new(rate: u32, channels: u16) -> Stretcher {
|
||||||
|
let channels = channels.max(1) as usize;
|
||||||
|
let n = ((rate as f64 * FRAME) as usize).max(64) & !1;
|
||||||
|
let window =
|
||||||
|
(0..n).map(|i| (0.5 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / n as f64).cos()) as f32).collect();
|
||||||
|
Stretcher {
|
||||||
|
channels,
|
||||||
|
n,
|
||||||
|
hop: n / 2,
|
||||||
|
search: (rate as f64 * SEARCH) as usize,
|
||||||
|
speed: 1.0,
|
||||||
|
window,
|
||||||
|
input: Vec::new(),
|
||||||
|
base: 0,
|
||||||
|
pos: 0.0,
|
||||||
|
last: None,
|
||||||
|
acc: vec![0.0; n * channels],
|
||||||
|
out: Vec::new(),
|
||||||
|
flushed: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn speed(&self) -> f64 {
|
||||||
|
self.speed
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 0.5–3×; outside values are clamped, NaN keeps the current speed.
|
||||||
|
pub fn set_speed(&mut self, speed: f64) {
|
||||||
|
if speed.is_finite() {
|
||||||
|
self.speed = speed.clamp(MIN_SPEED, MAX_SPEED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frames_in(&self) -> usize {
|
||||||
|
self.input.len() / self.channels
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mono sample at an absolute input frame (0 outside what is buffered).
|
||||||
|
fn mono(&self, abs: usize) -> f32 {
|
||||||
|
if abs < self.base {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
let i = abs - self.base;
|
||||||
|
if i >= self.frames_in() {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
let row = &self.input[i * self.channels..(i + 1) * self.channels];
|
||||||
|
row.iter().sum::<f32>() / self.channels as f32
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds interleaved samples.
|
||||||
|
pub fn push(&mut self, samples: &[f32]) {
|
||||||
|
self.input.extend_from_slice(samples);
|
||||||
|
self.run(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// No more input: everything buffered comes out.
|
||||||
|
pub fn finish(&mut self) {
|
||||||
|
if !self.flushed {
|
||||||
|
self.flushed = true;
|
||||||
|
self.run(true);
|
||||||
|
// The tail of the accumulator is the last frame's second half.
|
||||||
|
self.out.extend_from_slice(&self.acc[..self.hop * self.channels]);
|
||||||
|
self.acc.iter_mut().for_each(|x| *x = 0.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes what is ready.
|
||||||
|
pub fn pull(&mut self) -> Vec<f32> {
|
||||||
|
std::mem::take(&mut self.out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(&mut self, last: bool) {
|
||||||
|
let (n, hop, s, ch) = (self.n, self.hop, self.search, self.channels);
|
||||||
|
loop {
|
||||||
|
let nominal = self.pos.round() as usize;
|
||||||
|
let end_needed = nominal + s + n;
|
||||||
|
let have = self.base + self.frames_in();
|
||||||
|
if have < end_needed && !(last && nominal < have) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// Best start near the nominal one: the frame that best continues the last frame's natural sequel.
|
||||||
|
let start = match self.last {
|
||||||
|
None => nominal,
|
||||||
|
Some(prev) => {
|
||||||
|
let lo = nominal.saturating_sub(s).max(self.base);
|
||||||
|
let hi = (nominal + s).min(have.saturating_sub(n).max(lo));
|
||||||
|
let target = prev + hop;
|
||||||
|
let mut best = (f32::MIN, nominal.clamp(lo, hi));
|
||||||
|
let step = 2;
|
||||||
|
let overlap = hop;
|
||||||
|
let mut d = lo;
|
||||||
|
while d <= hi {
|
||||||
|
let mut c = 0.0f32;
|
||||||
|
let mut k = 0;
|
||||||
|
while k < overlap {
|
||||||
|
c += self.mono(target + k) * self.mono(d + k);
|
||||||
|
k += 4;
|
||||||
|
}
|
||||||
|
if c > best.0 {
|
||||||
|
best = (c, d);
|
||||||
|
}
|
||||||
|
d += step;
|
||||||
|
}
|
||||||
|
best.1
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for i in 0..n {
|
||||||
|
let w = self.window[i];
|
||||||
|
let abs = start + i;
|
||||||
|
for c in 0..ch {
|
||||||
|
let v = if abs >= self.base && abs - self.base < self.frames_in() {
|
||||||
|
self.input[(abs - self.base) * ch + c]
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
self.acc[i * ch + c] += v * w;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The first hop of the accumulator is complete: emit it and shift.
|
||||||
|
self.out.extend_from_slice(&self.acc[..hop * ch]);
|
||||||
|
self.acc.copy_within(hop * ch.., 0);
|
||||||
|
let len = self.acc.len();
|
||||||
|
self.acc[len - hop * ch..].iter_mut().for_each(|x| *x = 0.0);
|
||||||
|
self.last = Some(start);
|
||||||
|
self.pos += hop as f64 * self.speed;
|
||||||
|
// Drop input nothing will read again.
|
||||||
|
let keep_from = (self.pos as usize).saturating_sub(s).min(start + hop).min(self.base + self.frames_in());
|
||||||
|
if keep_from > self.base {
|
||||||
|
let drop = keep_from - self.base;
|
||||||
|
self.input.drain(..drop * ch);
|
||||||
|
self.base = keep_from;
|
||||||
|
}
|
||||||
|
if last && self.pos as usize >= have {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole of `samples` at `speed` (tests and short clips).
|
||||||
|
pub fn stretch(samples: &[f32], rate: u32, channels: u16, speed: f64) -> Vec<f32> {
|
||||||
|
let mut s = Stretcher::new(rate, channels);
|
||||||
|
s.set_speed(speed);
|
||||||
|
for block in samples.chunks(4096 * channels.max(1) as usize) {
|
||||||
|
s.push(block);
|
||||||
|
}
|
||||||
|
s.finish();
|
||||||
|
s.pull()
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
//! Mandatory test 1: time-stretch at 0.5×, 1.5× and 3× keeps the duration within tolerance and the pitch unchanged;
|
||||||
|
//! silence trimming never cuts speech (a fixture with marked speech regions); the position after a kill and restart
|
||||||
|
//! is within one second. Fixtures are generated here (no audio files in git).
|
||||||
|
|
||||||
|
use liber_audio::boost::Boost;
|
||||||
|
use liber_audio::player::{
|
||||||
|
Chapter, MAX_BLOCK_MS, Saver, Sleep, chapter_at, next_chapter, previous_chapter, skip, tidy,
|
||||||
|
};
|
||||||
|
use liber_audio::silence::{TrimConfig, Trimmer, trim};
|
||||||
|
use liber_audio::stretch::stretch;
|
||||||
|
|
||||||
|
const RATE: u32 = 16_000;
|
||||||
|
|
||||||
|
/// A voiced, speech-like tone: a fundamental and two harmonics, gently amplitude-modulated (syllables).
|
||||||
|
fn voice(f0: f32, secs: f32) -> Vec<f32> {
|
||||||
|
let n = (RATE as f32 * secs) as usize;
|
||||||
|
(0..n)
|
||||||
|
.map(|i| {
|
||||||
|
let t = i as f32 / RATE as f32;
|
||||||
|
let w = 2.0 * std::f32::consts::PI * f0 * t;
|
||||||
|
let env = 0.6 + 0.4 * (2.0 * std::f32::consts::PI * 4.0 * t).sin();
|
||||||
|
0.3 * env * (w.sin() + 0.5 * (2.0 * w).sin() + 0.25 * (3.0 * w).sin())
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fundamental by autocorrelation over a middle stretch (lags for 60–500 Hz).
|
||||||
|
fn pitch(x: &[f32]) -> f32 {
|
||||||
|
let mid = &x[x.len() / 4..x.len() * 3 / 4];
|
||||||
|
let seg = &mid[..mid.len().min(8_000)];
|
||||||
|
let (lo, hi) = ((RATE / 500) as usize, (RATE / 60) as usize);
|
||||||
|
let mut best = (0.0f32, lo);
|
||||||
|
for lag in lo..hi {
|
||||||
|
let c: f32 = seg.iter().zip(&seg[lag..]).map(|(a, b)| a * b).sum::<f32>() / (seg.len() - lag) as f32;
|
||||||
|
if c > best.0 {
|
||||||
|
best = (c, lag);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Parabolic interpolation around the peak for sub-sample precision.
|
||||||
|
let lag = best.1;
|
||||||
|
let ac = |l: usize| seg.iter().zip(&seg[l..]).map(|(a, b)| a * b).sum::<f32>() / (seg.len() - l) as f32;
|
||||||
|
let (y0, y1, y2) = (ac(lag - 1), ac(lag), ac(lag + 1));
|
||||||
|
let d = 0.5 * (y0 - y2) / (y0 - 2.0 * y1 + y2);
|
||||||
|
RATE as f32 / (lag as f32 + if d.is_finite() { d } else { 0.0 })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stretch_keeps_pitch_and_scales_duration() {
|
||||||
|
let input = voice(180.0, 4.0);
|
||||||
|
let p_in = pitch(&input);
|
||||||
|
for speed in [0.5, 1.5, 3.0] {
|
||||||
|
let out = stretch(&input, RATE, 1, speed);
|
||||||
|
let want = input.len() as f64 / speed;
|
||||||
|
let ratio = out.len() as f64 / want;
|
||||||
|
let p_out = pitch(&out);
|
||||||
|
println!("speed {speed}: length {:.3} of the ideal, pitch {p_in:.1} → {p_out:.1} Hz", ratio);
|
||||||
|
assert!((ratio - 1.0).abs() < 0.03, "speed {speed}: duration off by {:.1}%", (ratio - 1.0) * 100.0);
|
||||||
|
assert!(((p_out - p_in) / p_in).abs() < 0.02, "speed {speed}: pitch {p_in} → {p_out}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stretch_streams_with_speed_changes_and_stereo() {
|
||||||
|
let mono = voice(200.0, 2.0);
|
||||||
|
let stereo: Vec<f32> = mono.iter().flat_map(|&x| [x, -x]).collect();
|
||||||
|
let out = stretch(&stereo, RATE, 2, 1.5);
|
||||||
|
assert_eq!(out.len() % 2, 0);
|
||||||
|
// The channels stay opposite: the same alignment is applied to both.
|
||||||
|
let max_sum = out.chunks(2).map(|f| (f[0] + f[1]).abs()).fold(0.0f32, f32::max);
|
||||||
|
assert!(max_sum < 1e-4, "{max_sum}");
|
||||||
|
// NaN and out-of-range speeds are refused or clamped.
|
||||||
|
let mut s = liber_audio::stretch::Stretcher::new(RATE, 1);
|
||||||
|
s.set_speed(f64::NAN);
|
||||||
|
assert_eq!(s.speed(), 1.0);
|
||||||
|
s.set_speed(9.0);
|
||||||
|
assert_eq!(s.speed(), 3.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Speech regions (marked) and pauses of 100, 250, 600 and 2,000 ms.
|
||||||
|
fn speech_and_pauses() -> (Vec<f32>, Vec<(usize, usize)>, Vec<usize>) {
|
||||||
|
let mut x = Vec::new();
|
||||||
|
let mut speech = Vec::new();
|
||||||
|
let pauses_ms = [100, 250, 600, 2_000];
|
||||||
|
for (i, p) in pauses_ms.iter().enumerate() {
|
||||||
|
let s = x.len();
|
||||||
|
x.extend(voice(150.0 + 20.0 * i as f32, 0.7));
|
||||||
|
speech.push((s, x.len()));
|
||||||
|
x.extend(std::iter::repeat_n(0.0005f32, (RATE as usize * p) / 1000));
|
||||||
|
}
|
||||||
|
let s = x.len();
|
||||||
|
x.extend(voice(170.0, 0.5));
|
||||||
|
speech.push((s, x.len()));
|
||||||
|
(x, speech, pauses_ms.to_vec())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trimming_never_cuts_speech() {
|
||||||
|
let (x, speech, pauses) = speech_and_pauses();
|
||||||
|
let cfg = TrimConfig::default();
|
||||||
|
let out = trim(&x, RATE, 1, cfg);
|
||||||
|
let loud = |v: &[f32]| v.iter().filter(|s| s.abs() > 0.01).count();
|
||||||
|
let speech_loud: usize = speech.iter().map(|&(a, b)| loud(&x[a..b])).sum();
|
||||||
|
assert_eq!(loud(&out), speech_loud, "every loud sample of speech is still there");
|
||||||
|
// Short pauses (< 300 ms) stay; long ones become 150 ms (± one 10 ms frame each).
|
||||||
|
let ms = |n: usize| n as i64 * 1000 / RATE as i64;
|
||||||
|
let speech_ms: i64 = speech.iter().map(|&(a, b)| ms(b - a)).sum();
|
||||||
|
let want: i64 = speech_ms
|
||||||
|
+ pauses.iter().map(|&p| if p >= cfg.long_ms as usize { cfg.keep_ms as i64 } else { p as i64 }).sum::<i64>();
|
||||||
|
let got = ms(out.len());
|
||||||
|
assert!((got - want).abs() <= 40, "output {got} ms, want {want} ms");
|
||||||
|
// Turned off, nothing changes.
|
||||||
|
let mut t = Trimmer::new(RATE, 1, cfg);
|
||||||
|
t.enabled = false;
|
||||||
|
t.push(&x);
|
||||||
|
t.finish();
|
||||||
|
assert_eq!(t.pull().len(), x.len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trimmed_time_maps_back_to_the_books_time() {
|
||||||
|
let (x, speech, _) = speech_and_pauses();
|
||||||
|
let mut t = Trimmer::new(RATE, 1, TrimConfig::default());
|
||||||
|
t.push(&x);
|
||||||
|
t.finish();
|
||||||
|
let out = t.pull();
|
||||||
|
// The last speech region starts at the same place in the book whichever way it is counted.
|
||||||
|
let (last_start, _) = *speech.last().unwrap();
|
||||||
|
let out_start = out.len() - (x.len() - last_start);
|
||||||
|
let back = t.input_frame(out_start as u64) as usize;
|
||||||
|
assert!((back as i64 - last_start as i64).abs() <= (RATE / 100) as i64, "{back} vs {last_start}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn boost_never_clips_and_lifts_presence() {
|
||||||
|
let mut b = Boost::new(RATE, 1);
|
||||||
|
let mut loud: Vec<f32> = voice(200.0, 1.0).iter().map(|s| s * 4.0).collect();
|
||||||
|
b.process(&mut loud);
|
||||||
|
assert!(loud.iter().all(|s| s.abs() <= 1.0 && s.is_finite()));
|
||||||
|
// A 2.5 kHz tone comes out louder relative to a 100 Hz tone than it went in.
|
||||||
|
let tone = |f: f32| -> Vec<f32> {
|
||||||
|
(0..RATE as usize).map(|i| 0.05 * (2.0 * std::f32::consts::PI * f * i as f32 / RATE as f32).sin()).collect()
|
||||||
|
};
|
||||||
|
let rms = |v: &[f32]| (v[v.len() / 2..].iter().map(|x| x * x).sum::<f32>() / (v.len() / 2) as f32).sqrt();
|
||||||
|
let (mut lo, mut hi) = (tone(100.0), tone(2_500.0));
|
||||||
|
Boost::new(RATE, 1).process(&mut lo);
|
||||||
|
Boost::new(RATE, 1).process(&mut hi);
|
||||||
|
assert!(rms(&hi) > rms(&lo) * 1.3, "presence {} vs low {}", rms(&hi), rms(&lo));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A deterministic generator, so the test needs no `rand`.
|
||||||
|
struct Lcg(u64);
|
||||||
|
impl Lcg {
|
||||||
|
fn next(&mut self) -> u64 {
|
||||||
|
self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
|
||||||
|
self.0 >> 33
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_killed_player_resumes_within_a_second() {
|
||||||
|
// Playback in blocks of up to MAX_BLOCK_MS; the app is killed at a random moment; on restart the player reads the
|
||||||
|
// last saved position. Across 2,000 kills it is never more than a second behind.
|
||||||
|
let mut g = Lcg(11);
|
||||||
|
for _ in 0..2_000 {
|
||||||
|
let mut saver = Saver::default();
|
||||||
|
let (mut now, mut pos, mut saved) = (0u64, 0u64, 0u64);
|
||||||
|
let kill_at = 1_000 + g.next() % 600_000;
|
||||||
|
while now < kill_at {
|
||||||
|
let block = 1 + g.next() % MAX_BLOCK_MS;
|
||||||
|
now += block;
|
||||||
|
pos += block;
|
||||||
|
if saver.tick(now) {
|
||||||
|
saved = pos;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(pos - saved <= 1_000, "{} ms behind", pos - saved);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chapters_skips_and_the_sleep_timer() {
|
||||||
|
let raw = vec![
|
||||||
|
Chapter { title: "Two".into(), start_ms: 60_000, end_ms: 0 },
|
||||||
|
Chapter { title: "".into(), start_ms: 0, end_ms: 0 },
|
||||||
|
Chapter { title: "Beyond".into(), start_ms: 999_999, end_ms: 0 },
|
||||||
|
Chapter { title: "Dup".into(), start_ms: 60_000, end_ms: 0 },
|
||||||
|
];
|
||||||
|
let ch = tidy(raw, 120_000).expect("chapters");
|
||||||
|
assert_eq!(ch.len(), 2);
|
||||||
|
assert_eq!(ch[0].title, "Chapter 1");
|
||||||
|
assert_eq!((ch[0].end_ms, ch[1].end_ms), (60_000, 120_000));
|
||||||
|
assert_eq!(chapter_at(&ch, 61_000), Some(1));
|
||||||
|
assert_eq!(previous_chapter(&ch, 61_000), 0, "within 3 s of a start: the chapter before");
|
||||||
|
assert_eq!(previous_chapter(&ch, 90_000), 60_000);
|
||||||
|
assert_eq!(next_chapter(&ch, 1_000), Some(60_000));
|
||||||
|
assert_eq!(next_chapter(&ch, 61_000), None);
|
||||||
|
assert_eq!(skip(5_000, -15_000, 120_000), 0);
|
||||||
|
assert_eq!(skip(119_000, 30_000, 120_000), 120_000);
|
||||||
|
let s = Sleep::minutes(1_000, 10);
|
||||||
|
assert!(!s.due(600_999, 0) && s.due(601_000, 0));
|
||||||
|
let e = Sleep::end_of_chapter(&ch, 61_000, 120_000);
|
||||||
|
assert!(!e.due(0, 119_999) && e.due(0, 120_000));
|
||||||
|
}
|
||||||
@@ -0,0 +1,331 @@
|
|||||||
|
//! Mandatory tests 2 and 3. Hostile audio — truncated files, wrong extensions, absurd chapter counts, huge metadata
|
||||||
|
//! blocks, impossible nesting — is rejected cleanly within a time cap. DRM-protected files are refused with the one
|
||||||
|
//! sentence, and the crate has no decrypt path. Every fixture is built here.
|
||||||
|
|
||||||
|
use liber_audio::DRM_MESSAGE;
|
||||||
|
use liber_audio::container::{AudioError, Caps, Kind, cue, inspect};
|
||||||
|
use liber_audio::decode::{DecodeCaps, decode_all};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
const CAP: Duration = Duration::from_secs(2);
|
||||||
|
|
||||||
|
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||||
|
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
|
||||||
|
v.extend_from_slice(kind);
|
||||||
|
v.extend_from_slice(body);
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ftyp(brand: &[u8; 4]) -> Vec<u8> {
|
||||||
|
let mut b = brand.to_vec();
|
||||||
|
b.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
b.extend_from_slice(b"M4A isom");
|
||||||
|
bx(b"ftyp", &b)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mvhd(timescale: u32, duration: u32) -> Vec<u8> {
|
||||||
|
let mut b = vec![0u8; 4]; // version 0, flags
|
||||||
|
b.extend_from_slice(&[0; 8]); // creation, modification
|
||||||
|
b.extend_from_slice(×cale.to_be_bytes());
|
||||||
|
b.extend_from_slice(&duration.to_be_bytes());
|
||||||
|
b.extend_from_slice(&[0; 80]);
|
||||||
|
bx(b"mvhd", &b)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chpl(chapters: &[(u64, &str)], claim: Option<u8>) -> Vec<u8> {
|
||||||
|
let mut b = vec![1, 0, 0, 0, 0, 0, 0, 0]; // version 1, flags, reserved
|
||||||
|
b.push(claim.unwrap_or(chapters.len() as u8));
|
||||||
|
for (start_ms, t) in chapters {
|
||||||
|
b.extend_from_slice(&(start_ms * 10_000).to_be_bytes());
|
||||||
|
b.push(t.len() as u8);
|
||||||
|
b.extend_from_slice(t.as_bytes());
|
||||||
|
}
|
||||||
|
bx(b"chpl", &b)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn m4b(moov_children: &[Vec<u8>], brand: &[u8; 4]) -> Vec<u8> {
|
||||||
|
let mut f = ftyp(brand);
|
||||||
|
f.extend(bx(b"moov", &moov_children.concat()));
|
||||||
|
f.extend(bx(b"mdat", &[0u8; 64]));
|
||||||
|
f
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timed<T>(f: impl FnOnce() -> T) -> T {
|
||||||
|
let t = Instant::now();
|
||||||
|
let r = f();
|
||||||
|
assert!(t.elapsed() < CAP, "took {:?}", t.elapsed());
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wav(samples: &[i16], rate: u32) -> Vec<u8> {
|
||||||
|
let data: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
|
||||||
|
let mut v = b"RIFF".to_vec();
|
||||||
|
v.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
|
||||||
|
v.extend_from_slice(b"WAVEfmt ");
|
||||||
|
v.extend_from_slice(&16u32.to_le_bytes());
|
||||||
|
v.extend_from_slice(&1u16.to_le_bytes()); // PCM
|
||||||
|
v.extend_from_slice(&1u16.to_le_bytes()); // mono
|
||||||
|
v.extend_from_slice(&rate.to_le_bytes());
|
||||||
|
v.extend_from_slice(&(rate * 2).to_le_bytes());
|
||||||
|
v.extend_from_slice(&2u16.to_le_bytes());
|
||||||
|
v.extend_from_slice(&16u16.to_le_bytes());
|
||||||
|
v.extend_from_slice(b"data");
|
||||||
|
v.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||||
|
v.extend(data);
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_good_m4b_gives_duration_and_chapters() {
|
||||||
|
let udta = bx(b"udta", &chpl(&[(0, "Opening"), (90_000, "The mill"), (300_000, "Winter")], None));
|
||||||
|
let f = m4b(&[mvhd(1000, 600_000), udta], b"M4B ");
|
||||||
|
let info = timed(|| inspect(&f, Caps::default())).expect("reads");
|
||||||
|
assert_eq!(info.kind, Kind::Mp4);
|
||||||
|
assert_eq!(info.duration_ms, Some(600_000));
|
||||||
|
let titles: Vec<&str> = info.chapters.iter().map(|c| c.title.as_str()).collect();
|
||||||
|
assert_eq!(titles, ["Opening", "The mill", "Winter"]);
|
||||||
|
assert_eq!(info.chapters[2].end_ms, 600_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn drm_is_refused_with_the_sentence() {
|
||||||
|
// Audible AAX: the brand, an `adrm` box, an encrypted sample entry.
|
||||||
|
let by_brand = m4b(&[mvhd(1000, 1000)], b"aax ");
|
||||||
|
let by_aaxc = m4b(&[mvhd(1000, 1000)], b"aaxc");
|
||||||
|
let by_aabd = m4b(&[mvhd(1000, 1000), bx(b"aabd", &[0u8; 16])], b"M4B ");
|
||||||
|
let by_box = m4b(&[mvhd(1000, 1000), bx(b"adrm", &[0u8; 56])], b"M4B ");
|
||||||
|
let mut stsd = vec![0u8; 8];
|
||||||
|
stsd.extend(bx(b"enca", &[0u8; 28]));
|
||||||
|
let entry = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd)))));
|
||||||
|
let by_entry = m4b(&[mvhd(1000, 1000), entry], b"M4B ");
|
||||||
|
for f in [by_brand, by_aaxc, by_aabd, by_box, by_entry] {
|
||||||
|
let e = timed(|| inspect(&f, Caps::default())).expect_err("refused");
|
||||||
|
assert_eq!(e, AudioError::Drm);
|
||||||
|
assert_eq!(e.message(), DRM_MESSAGE);
|
||||||
|
assert_eq!(decode_all(f.clone(), DecodeCaps::default()).expect_err("refused"), AudioError::Drm);
|
||||||
|
}
|
||||||
|
assert_eq!(DRM_MESSAGE, "This audiobook is DRM-protected, so Liber cannot play it.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn there_is_no_decrypt_path() {
|
||||||
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||||
|
let manifest = std::fs::read_to_string(root.join("Cargo.toml")).unwrap();
|
||||||
|
for c in ["aes", "ctr", "cbc", "cipher", "openssl", "ring"] {
|
||||||
|
assert!(
|
||||||
|
!manifest
|
||||||
|
.lines()
|
||||||
|
.any(|l| l.trim_start().starts_with(&format!("{c} ")) || l.trim_start().starts_with(&format!("{c}="))),
|
||||||
|
"{c} in Cargo.toml"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for e in std::fs::read_dir(root.join("src")).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
let s = std::fs::read_to_string(&p).unwrap().to_lowercase();
|
||||||
|
for bad in ["decrypt(", "activation_bytes", "activation bytes", "aes::", "cipher::"] {
|
||||||
|
assert!(!s.contains(bad), "{}: {bad}", p.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_mp4_is_rejected_cleanly() {
|
||||||
|
// A chapter count that the bytes do not hold.
|
||||||
|
let lying = m4b(&[mvhd(1000, 1000), bx(b"udta", &chpl(&[(0, "a")], Some(255)))], b"M4B ");
|
||||||
|
assert!(matches!(timed(|| inspect(&lying, Caps::default())), Err(AudioError::Damaged(_))));
|
||||||
|
// A box claiming a terabyte inside a small file: read what is there, allocate nothing from the claim.
|
||||||
|
let mut huge = ftyp(b"M4B ");
|
||||||
|
huge.extend_from_slice(&1u32.to_be_bytes());
|
||||||
|
huge.extend_from_slice(b"mdat");
|
||||||
|
huge.extend_from_slice(&(1u64 << 40).to_be_bytes());
|
||||||
|
huge.extend_from_slice(&[0u8; 100]);
|
||||||
|
assert!(timed(|| inspect(&huge, Caps::default())).is_ok());
|
||||||
|
// A box smaller than its own header.
|
||||||
|
let mut tiny = ftyp(b"M4B ");
|
||||||
|
tiny.extend_from_slice(&4u32.to_be_bytes());
|
||||||
|
tiny.extend_from_slice(b"moov");
|
||||||
|
assert!(matches!(timed(|| inspect(&tiny, Caps::default())), Err(AudioError::Damaged(_))));
|
||||||
|
// Nesting deeper than any real file.
|
||||||
|
let mut nest = bx(b"udta", &[]);
|
||||||
|
for _ in 0..40 {
|
||||||
|
nest = bx(b"moov", &nest);
|
||||||
|
}
|
||||||
|
let mut deep = ftyp(b"M4B ");
|
||||||
|
deep.extend(nest);
|
||||||
|
assert!(matches!(timed(|| inspect(&deep, Caps::default())), Err(AudioError::Damaged(_))));
|
||||||
|
// Two hundred thousand empty boxes.
|
||||||
|
let mut many = ftyp(b"M4B ");
|
||||||
|
many.extend(bx(b"moov", &bx(b"free", &[]).repeat(250_000)));
|
||||||
|
assert!(matches!(timed(|| inspect(&many, Caps::default())), Err(AudioError::Damaged(_))));
|
||||||
|
// A ftyp that claims to be bigger than the file.
|
||||||
|
let mut bad_ftyp = ftyp(b"M4B ");
|
||||||
|
bad_ftyp[..4].copy_from_slice(&9_999u32.to_be_bytes());
|
||||||
|
assert!(matches!(timed(|| inspect(&bad_ftyp, Caps::default())), Err(AudioError::Damaged(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn id3(frames: &[u8], declared: Option<usize>) -> Vec<u8> {
|
||||||
|
let size = declared.unwrap_or(frames.len());
|
||||||
|
let ss = [(size >> 21) as u8 & 0x7F, (size >> 14) as u8 & 0x7F, (size >> 7) as u8 & 0x7F, size as u8 & 0x7F];
|
||||||
|
let mut v = b"ID3\x03\x00\x00".to_vec();
|
||||||
|
v.extend_from_slice(&ss);
|
||||||
|
v.extend_from_slice(frames);
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frame(id: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||||
|
let mut v = id.to_vec();
|
||||||
|
v.extend_from_slice(&(body.len() as u32).to_be_bytes());
|
||||||
|
v.extend_from_slice(&[0, 0]);
|
||||||
|
v.extend_from_slice(body);
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chap(id: &str, start: u32, end: u32, title: &str) -> Vec<u8> {
|
||||||
|
let mut b = id.as_bytes().to_vec();
|
||||||
|
b.push(0);
|
||||||
|
for x in [start, end, u32::MAX, u32::MAX] {
|
||||||
|
b.extend_from_slice(&x.to_be_bytes());
|
||||||
|
}
|
||||||
|
let mut t = vec![3u8];
|
||||||
|
t.extend_from_slice(title.as_bytes());
|
||||||
|
b.extend(frame(b"TIT2", &t));
|
||||||
|
frame(b"CHAP", &b)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mp3_chapters_and_hostile_tags() {
|
||||||
|
let good = id3(
|
||||||
|
&[chap("c1", 0, 60_000, "Eins"), chap("c2", 60_000, 125_000, "Zwei"), frame(b"TIT2", b"\x03Die M\xc3\xbchle")]
|
||||||
|
.concat(),
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
let info = timed(|| inspect(&good, Caps::default())).expect("reads");
|
||||||
|
assert_eq!(info.title.as_deref(), Some("Die Mühle"));
|
||||||
|
assert_eq!(info.chapters.iter().map(|c| c.title.as_str()).collect::<Vec<_>>(), ["Eins", "Zwei"]);
|
||||||
|
assert_eq!(info.duration_ms, Some(125_000));
|
||||||
|
// A tag that claims 200 MB.
|
||||||
|
let huge = id3(&[], Some(200 << 20));
|
||||||
|
assert!(matches!(timed(|| inspect(&huge, Caps::default())), Err(AudioError::Damaged(_))));
|
||||||
|
// An absurd number of chapter frames.
|
||||||
|
let many = id3(&chap("c", 0, 1, "x").repeat(30_000), None);
|
||||||
|
assert!(matches!(timed(|| inspect(&many, Caps::default())), Err(AudioError::Damaged(_))));
|
||||||
|
// A frame larger than its tag.
|
||||||
|
let mut lying = frame(b"TIT2", b"\x03abc");
|
||||||
|
lying[4..8].copy_from_slice(&1_000_000u32.to_be_bytes());
|
||||||
|
assert!(matches!(timed(|| inspect(&id3(&lying, None), Caps::default())), Err(AudioError::Damaged(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn decoding_real_samples_and_broken_streams() {
|
||||||
|
// A WAV the decoder reads end to end.
|
||||||
|
let samples: Vec<i16> = (0..16_000).map(|i| ((i as f32 * 0.07).sin() * 12_000.0) as i16).collect();
|
||||||
|
let good = wav(&samples, 16_000);
|
||||||
|
let (rate, ch, out) = timed(|| decode_all(good.clone(), DecodeCaps::default())).expect("decodes");
|
||||||
|
assert_eq!((rate, ch, out.len()), (16_000, 1, 16_000));
|
||||||
|
assert_eq!(inspect(&good, Caps::default()).unwrap().duration_ms, Some(1_000));
|
||||||
|
// Truncated: half the data is gone; it ends early or reports damage, never hangs or panics.
|
||||||
|
let cut = good[..good.len() / 2].to_vec();
|
||||||
|
match timed(|| decode_all(cut, DecodeCaps::default())) {
|
||||||
|
Ok((_, _, s)) => assert!(s.len() < 16_000),
|
||||||
|
Err(e) => assert!(matches!(e, AudioError::Damaged(_) | AudioError::Unsupported)),
|
||||||
|
}
|
||||||
|
// Wrong extension or plain junk: refused by content.
|
||||||
|
let junk = b"this is not audio, whatever its name says".repeat(100);
|
||||||
|
assert_eq!(timed(|| decode_all(junk.clone(), DecodeCaps::default())).expect_err("junk"), AudioError::Unsupported);
|
||||||
|
assert_eq!(timed(|| inspect(&junk, Caps::default())).expect_err("junk"), AudioError::Unsupported);
|
||||||
|
// An MP4 container with no audio track at all.
|
||||||
|
let empty = m4b(&[mvhd(1000, 1000)], b"M4B ");
|
||||||
|
assert!(timed(|| decode_all(empty, DecodeCaps::default())).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cue_sheets() {
|
||||||
|
let sheet = "FILE \"book.mp3\" MP3\n TRACK 01 AUDIO\n TITLE \"Kapitel 1\"\n INDEX 01 00:00:00\n TRACK 02 AUDIO\n TITLE \"Kapitel 2\"\n INDEX 01 12:30:37\n";
|
||||||
|
let ch = cue(sheet, 3_600_000).expect("chapters");
|
||||||
|
assert_eq!(ch.len(), 2);
|
||||||
|
assert_eq!(ch[1].title, "Kapitel 2");
|
||||||
|
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,68 @@
|
|||||||
|
//! Mandatory test 4 (the engine's half): the sentence highlight follows the audio within tolerance, across pauses
|
||||||
|
//! and speed changes; the cache key changes when the voice or the speed changes and not otherwise. (Synthesis itself
|
||||||
|
//! runs in the app with a local model; the app's test runs it network-blocked.)
|
||||||
|
|
||||||
|
use liber_audio::speech::{Ends, PAUSE_PARAGRAPH_MS, PAUSE_SENTENCE_MS, PAUSE_TITLE_MS, Segment, Timeline, cache_key};
|
||||||
|
use liber_audio::stretch::stretch;
|
||||||
|
|
||||||
|
fn seg(start: usize, audio_ms: u32, ends: Ends) -> Segment {
|
||||||
|
Segment { chapter: 0, start, end: start + 10, audio_ms, ends }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_highlight_follows_the_audio() {
|
||||||
|
let t = Timeline::new(vec![
|
||||||
|
seg(0, 900, Ends::Title),
|
||||||
|
seg(20, 2_000, Ends::Sentence),
|
||||||
|
seg(40, 1_500, Ends::Paragraph),
|
||||||
|
seg(60, 800, Ends::Sentence),
|
||||||
|
]);
|
||||||
|
let s1 = 900 + PAUSE_TITLE_MS as u64;
|
||||||
|
let s2 = s1 + 2_000 + PAUSE_SENTENCE_MS as u64;
|
||||||
|
let s3 = s2 + 1_500 + PAUSE_PARAGRAPH_MS as u64;
|
||||||
|
assert_eq!(t.at(0), Some(0));
|
||||||
|
assert_eq!(t.at(s1 - 1), Some(0), "the title's pause still shows the title");
|
||||||
|
assert!(t.in_pause(s1 - 1));
|
||||||
|
assert_eq!(t.at(s1), Some(1));
|
||||||
|
assert_eq!(t.at(s2 + 10), Some(2));
|
||||||
|
assert_eq!(t.at(s3), Some(3));
|
||||||
|
assert_eq!(t.start_of(2), Some(s2));
|
||||||
|
assert_eq!(t.at(t.total_ms), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_highlight_stays_with_stretched_audio() {
|
||||||
|
// A sentence's audio played at 1.5×: the player reports positions in the unstretched timeline (the stretcher
|
||||||
|
// consumes input at `speed` times the output), so the highlight changes when the real audio does, within a
|
||||||
|
// frame of the stretcher (40 ms) at any speed.
|
||||||
|
let rate = 16_000;
|
||||||
|
let sentence_ms = [1_200u32, 800, 1_500];
|
||||||
|
let audio: Vec<f32> = sentence_ms
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.flat_map(|(k, &ms)| (0..(rate * ms / 1000)).map(move |i| ((i as f32) * 0.05 * (k + 1) as f32).sin() * 0.3))
|
||||||
|
.collect();
|
||||||
|
for speed in [0.5, 1.5, 3.0] {
|
||||||
|
let out = stretch(&audio, rate, 1, speed);
|
||||||
|
// Output time t corresponds to input time t × speed.
|
||||||
|
let boundary_in = 1_200.0;
|
||||||
|
let boundary_out_ms = boundary_in / speed;
|
||||||
|
let reported = boundary_out_ms * speed;
|
||||||
|
assert!((reported - boundary_in).abs() <= 40.0, "speed {speed}");
|
||||||
|
let expected_len = audio.len() as f64 / speed;
|
||||||
|
assert!(((out.len() as f64 - expected_len) / expected_len).abs() < 0.03);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_cache_key_changes_with_voice_or_speed_only() {
|
||||||
|
let k = cache_key("kokoro-af_heart", "abc", 1.0, "en", "Hello there.");
|
||||||
|
assert_eq!(k.len(), 64);
|
||||||
|
assert_eq!(k, cache_key("kokoro-af_heart", "abc", 1.0, "en", "Hello there."));
|
||||||
|
assert_ne!(k, cache_key("kokoro-am_adam", "abc", 1.0, "en", "Hello there."), "another voice");
|
||||||
|
assert_ne!(k, cache_key("kokoro-af_heart", "abd", 1.0, "en", "Hello there."), "a new voice file");
|
||||||
|
assert_ne!(k, cache_key("kokoro-af_heart", "abc", 1.2, "en", "Hello there."), "another speed");
|
||||||
|
assert_ne!(k, cache_key("kokoro-af_heart", "abc", 1.0, "en", "Hello there!"), "other text");
|
||||||
|
// Field boundaries cannot be shifted to collide.
|
||||||
|
assert_ne!(cache_key("ab", "c", 1.0, "en", "x"), cache_key("a", "bc", 1.0, "en", "x"));
|
||||||
|
}
|
||||||
@@ -40,6 +40,9 @@ fn sources_have_no_io() {
|
|||||||
let mut hits = Vec::new();
|
let mut hits = Vec::new();
|
||||||
scan(&root.join("liber-format/src"), &mut hits);
|
scan(&root.join("liber-format/src"), &mut hits);
|
||||||
scan(&root.join("liber-library/src"), &mut hits);
|
scan(&root.join("liber-library/src"), &mut hits);
|
||||||
|
scan(&root.join("liber-habit/src"), &mut hits);
|
||||||
|
scan(&root.join("liber-lang/src"), &mut hits);
|
||||||
|
scan(&root.join("liber-audio/src"), &mut hits);
|
||||||
assert!(hits.is_empty(), "{hits:#?}");
|
assert!(hits.is_empty(), "{hits:#?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
[package]
|
||||||
|
name = "liber-habit"
|
||||||
|
description = "Liber Domi: the local day, days read, the forgiving streak, the reminder schedule and the medal rules"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
liber-library = { path = "../liber-library" }
|
||||||
|
serde.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
proptest.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
@@ -0,0 +1,314 @@
|
|||||||
|
//! Liber's reading habit (the app's `docs/02_habit.md`): the local day, days read, the forgiving streak, the reminder
|
||||||
|
//! schedule and the medal rules. Pure: the time, the UTC offset and the rollover hour are always parameters, and this
|
||||||
|
//! crate is the only place in Liber that turns a moment into a day.
|
||||||
|
|
||||||
|
use liber_library::Library;
|
||||||
|
use liber_library::library::{DailyKind, HabitGoal, Outcome};
|
||||||
|
use serde::Serialize;
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
const DAY_MS: i64 = 86_400_000;
|
||||||
|
|
||||||
|
/// A local day: days since 1970-01-01 in the reader's calendar.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
|
||||||
|
pub struct Day(pub i64);
|
||||||
|
|
||||||
|
impl Day {
|
||||||
|
/// Monday = 0 … Sunday = 6 (1970-01-01 was a Thursday).
|
||||||
|
pub fn weekday(self) -> u8 {
|
||||||
|
(self.0 + 3).rem_euclid(7) as u8
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Monday of this day's week.
|
||||||
|
pub fn week(self) -> Day {
|
||||||
|
Day(self.0 - self.weekday() as i64)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn plus(self, n: i64) -> Day {
|
||||||
|
Day(self.0 + n)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `YYYY-MM-DD`.
|
||||||
|
pub fn date(self) -> String {
|
||||||
|
let z = self.0 + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let doe = z - era * 146_097;
|
||||||
|
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||||
|
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||||
|
let y = yoe + era * 400 + i64::from(m <= 2);
|
||||||
|
format!("{y:04}-{m:02}-{d:02}")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(date: &str) -> Option<Day> {
|
||||||
|
let d = liber_library::parse_date(date)?;
|
||||||
|
let (y, m, dd) = (d[..4].parse().ok()?, d[5..7].parse().ok()?, d[8..].parse().ok()?);
|
||||||
|
Some(Day(liber_library::days_from_civil(y, m, dd)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The local day a moment belongs to: its local time (UTC + `offset_min`) minus `rollover_hour`, so reading at
|
||||||
|
/// 01:30 with a 03:00 rollover counts for the evening before. **The only day computation in Liber.**
|
||||||
|
pub fn local_day(utc_ms: i64, offset_min: i32, rollover_hour: u8) -> Day {
|
||||||
|
let local = utc_ms + offset_min as i64 * 60_000 - rollover_hour.min(23) as i64 * 3_600_000;
|
||||||
|
Day(local.div_euclid(DAY_MS))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The day a session counts for: the day it started (a session across the rollover counts once). Sessions from before
|
||||||
|
/// Day 2 carry no offset and keep their stored date.
|
||||||
|
pub fn session_day(s: &liber_library::library::Session, rollover_hour: u8) -> Option<Day> {
|
||||||
|
match s.offset_min {
|
||||||
|
Some(o) => Some(local_day(s.start as i64, o, rollover_hour)),
|
||||||
|
None => Day::parse(&s.date),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the reader did on each day: pages turned and active minutes.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct DayLog {
|
||||||
|
pub pages: u32,
|
||||||
|
pub active_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn goal(lib: &Library) -> HabitGoal {
|
||||||
|
lib.habit.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn met(g: &HabitGoal, d: &DayLog) -> bool {
|
||||||
|
match g.kind {
|
||||||
|
DailyKind::Pages => d.pages >= g.amount.max(1),
|
||||||
|
DailyKind::Minutes => d.active_ms >= g.amount.max(1) as u64 * 60_000,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every day with reading, summed over its sessions.
|
||||||
|
pub fn day_logs(lib: &Library) -> BTreeMap<Day, DayLog> {
|
||||||
|
let g = goal(lib);
|
||||||
|
let mut out: BTreeMap<Day, DayLog> = BTreeMap::new();
|
||||||
|
for s in lib.sessions.values() {
|
||||||
|
if let Some(d) = session_day(s, g.rollover_hour) {
|
||||||
|
let e = out.entry(d).or_default();
|
||||||
|
e.pages = e.pages.saturating_add(s.pages);
|
||||||
|
e.active_ms = e.active_ms.saturating_add(s.active_ms);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The days the goal was met.
|
||||||
|
pub fn days_read(lib: &Library) -> BTreeSet<Day> {
|
||||||
|
let g = goal(lib);
|
||||||
|
day_logs(lib).into_iter().filter(|(_, l)| met(&g, l)).map(|(d, _)| d).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum Mark {
|
||||||
|
Read,
|
||||||
|
/// A missed day the week forgives (the first in its week).
|
||||||
|
Forgiven,
|
||||||
|
/// A second missed day in a week: the streak ended here.
|
||||||
|
Missed,
|
||||||
|
/// Today, not read yet (not a miss until it is over).
|
||||||
|
Today,
|
||||||
|
/// Before the first day read, or after today.
|
||||||
|
None,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Habit {
|
||||||
|
pub today: String,
|
||||||
|
pub today_met: bool,
|
||||||
|
pub today_log: DayLog,
|
||||||
|
pub goal: HabitGoal,
|
||||||
|
/// Days read, ever. Never goes down.
|
||||||
|
pub total_days: u32,
|
||||||
|
/// Consecutive weeks (Monday–Sunday, this one included) with at most one missed day.
|
||||||
|
pub streak_weeks: u32,
|
||||||
|
/// The last weeks, oldest first, Monday first.
|
||||||
|
pub calendar: Vec<[Mark; 7]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mark(days: &BTreeSet<Day>, first: Option<Day>, today: Day, d: Day, misses_before: &mut u8) -> Mark {
|
||||||
|
let Some(first) = first else { return if d == today { Mark::Today } else { Mark::None } };
|
||||||
|
if d > today || d < first {
|
||||||
|
return Mark::None;
|
||||||
|
}
|
||||||
|
if days.contains(&d) {
|
||||||
|
return Mark::Read;
|
||||||
|
}
|
||||||
|
if d == today {
|
||||||
|
return Mark::Today;
|
||||||
|
}
|
||||||
|
*misses_before += 1;
|
||||||
|
if *misses_before == 1 { Mark::Forgiven } else { Mark::Missed }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The habit as of `today` (computed with [`local_day`]), with a calendar of the last `weeks` weeks.
|
||||||
|
pub fn habit(lib: &Library, today: Day, weeks: usize) -> Habit {
|
||||||
|
let g = goal(lib);
|
||||||
|
let logs = day_logs(lib);
|
||||||
|
let days: BTreeSet<Day> = logs.iter().filter(|(_, l)| met(&g, l)).map(|(d, _)| *d).collect();
|
||||||
|
let first = days.iter().next().copied();
|
||||||
|
// Streak: back from this week while a week has at most one missed day.
|
||||||
|
let mut streak = 0u32;
|
||||||
|
if let Some(f) = first {
|
||||||
|
let mut w = today.week();
|
||||||
|
while w.plus(6) >= f {
|
||||||
|
let mut misses = 0u8;
|
||||||
|
for i in 0..7 {
|
||||||
|
let d = w.plus(i);
|
||||||
|
if d >= f && d < today && !days.contains(&d) {
|
||||||
|
misses += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if misses >= 2 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
streak += 1;
|
||||||
|
w = w.plus(-7);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut calendar = Vec::with_capacity(weeks);
|
||||||
|
let start = today.week().plus(-7 * (weeks.max(1) as i64 - 1));
|
||||||
|
for k in 0..weeks.max(1) {
|
||||||
|
let w = start.plus(7 * k as i64);
|
||||||
|
let mut misses = 0u8;
|
||||||
|
let mut row = [Mark::None; 7];
|
||||||
|
for (i, slot) in row.iter_mut().enumerate() {
|
||||||
|
*slot = mark(&days, first, today, w.plus(i as i64), &mut misses);
|
||||||
|
}
|
||||||
|
calendar.push(row);
|
||||||
|
}
|
||||||
|
let today_log = logs.get(&today).copied().unwrap_or_default();
|
||||||
|
Habit {
|
||||||
|
today: today.date(),
|
||||||
|
today_met: met(&g, &today_log),
|
||||||
|
today_log,
|
||||||
|
goal: g,
|
||||||
|
total_days: days.len() as u32,
|
||||||
|
streak_weeks: streak,
|
||||||
|
calendar,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The reminder: one local notification at `minute` (0–1439) local time, off by default.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, serde::Deserialize)]
|
||||||
|
pub struct Reminder {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub minute: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When the next reminder should fire, as (day, minute of the local day): today if the goal is not met and the time is
|
||||||
|
/// still ahead, else tomorrow. `None` when the reminder is off. Never today when today's goal is met.
|
||||||
|
pub fn next_reminder(r: &Reminder, today: Day, now_minute: u16, today_met: bool) -> Option<(Day, u16)> {
|
||||||
|
if !r.enabled {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let m = r.minute.min(1439);
|
||||||
|
if !today_met && now_minute < m { Some((today, m)) } else { Some((today.plus(1), m)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The medals, in this order (docs/02_habit.md). `available: false`: earned from a later Liber version on.
|
||||||
|
pub const MEDALS: &[(&str, &str, bool)] = &[
|
||||||
|
("first-book", "First book finished", true),
|
||||||
|
("days-7", "Seven days read", true),
|
||||||
|
("days-30", "Thirty days read", true),
|
||||||
|
("days-100", "A hundred days read", true),
|
||||||
|
("days-365", "A year of days read", true),
|
||||||
|
("books-10", "Ten books", true),
|
||||||
|
("books-50", "Fifty books", true),
|
||||||
|
("books-100", "A hundred books", true),
|
||||||
|
("first-reread", "A book read again", true),
|
||||||
|
("let-go", "Let a book go", true),
|
||||||
|
("five-moods", "Five moods", true),
|
||||||
|
("other-language", "A book in another language", false),
|
||||||
|
("heard-aloud", "A chapter heard aloud", false),
|
||||||
|
("buddy-read", "Read with a friend", false),
|
||||||
|
];
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Medal {
|
||||||
|
pub id: &'static str,
|
||||||
|
pub name: &'static str,
|
||||||
|
pub available: bool,
|
||||||
|
/// The day it was earned (`YYYY-MM-DD`), `"earlier"` for an imported history without dates, `None` if not yet.
|
||||||
|
pub earned: Option<String>,
|
||||||
|
pub seen: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The medals: a pure function of the library. Recomputing gives the same value, so medals never drift between devices
|
||||||
|
/// or versions; only "seen" is stored.
|
||||||
|
pub fn medals(lib: &Library) -> Vec<Medal> {
|
||||||
|
let days: Vec<Day> = days_read(lib).into_iter().collect();
|
||||||
|
// Finished reads, dated ones in date order, then undated (imported) ones.
|
||||||
|
struct Fin {
|
||||||
|
date: Option<String>,
|
||||||
|
book: String,
|
||||||
|
outcome: Outcome,
|
||||||
|
}
|
||||||
|
let mut fins: Vec<Fin> = Vec::new();
|
||||||
|
for b in lib.books.values() {
|
||||||
|
for r in &b.reads {
|
||||||
|
if let Some(o) = r.outcome {
|
||||||
|
fins.push(Fin { date: r.finished.clone(), book: b.id.clone(), outcome: o });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fins.sort_by(|a, b| match (&a.date, &b.date) {
|
||||||
|
(Some(x), Some(y)) => x.cmp(y).then(a.book.cmp(&b.book)),
|
||||||
|
(Some(_), None) => std::cmp::Ordering::Less,
|
||||||
|
(None, Some(_)) => std::cmp::Ordering::Greater,
|
||||||
|
(None, None) => a.book.cmp(&b.book),
|
||||||
|
});
|
||||||
|
let when = |f: &Fin| Some(f.date.clone().unwrap_or_else(|| "earlier".into()));
|
||||||
|
let read: Vec<&Fin> = fins.iter().filter(|f| f.outcome == Outcome::Read).collect();
|
||||||
|
let nth_book = |n: usize| read.get(n - 1).and_then(|f| when(f));
|
||||||
|
let nth_day = |n: usize| days.get(n - 1).map(|d| d.date());
|
||||||
|
let reread = {
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
read.iter().find(|f| !seen.insert(f.book.clone())).and_then(|f| when(f))
|
||||||
|
};
|
||||||
|
let let_go = fins.iter().find(|f| f.outcome == Outcome::DidNotFinish).and_then(when);
|
||||||
|
let five_moods = {
|
||||||
|
let mut moods = BTreeSet::new();
|
||||||
|
let mut at = None;
|
||||||
|
for f in &read {
|
||||||
|
if let Some(b) = lib.books.get(&f.book) {
|
||||||
|
moods.extend(b.moods.iter().cloned());
|
||||||
|
}
|
||||||
|
if moods.len() >= 5 {
|
||||||
|
at = when(f);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
at
|
||||||
|
};
|
||||||
|
MEDALS
|
||||||
|
.iter()
|
||||||
|
.map(|&(id, name, available)| {
|
||||||
|
let earned = match id {
|
||||||
|
"first-book" => nth_book(1),
|
||||||
|
"days-7" => nth_day(7),
|
||||||
|
"days-30" => nth_day(30),
|
||||||
|
"days-100" => nth_day(100),
|
||||||
|
"days-365" => nth_day(365),
|
||||||
|
"books-10" => nth_book(10),
|
||||||
|
"books-50" => nth_book(50),
|
||||||
|
"books-100" => nth_book(100),
|
||||||
|
"first-reread" => reread.clone(),
|
||||||
|
"let-go" => let_go.clone(),
|
||||||
|
"five-moods" => five_moods.clone(),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
Medal { id, name, available, earned, seen: lib.medals_seen.contains(id) }
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Medals earned and not shown yet: what the end of a reading session reveals (at most one at a time).
|
||||||
|
pub fn unseen(lib: &Library) -> Vec<Medal> {
|
||||||
|
medals(lib).into_iter().filter(|m| m.earned.is_some() && !m.seen).collect()
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
#![allow(dead_code)]
|
||||||
|
use liber_library::library::BookInfo;
|
||||||
|
use liber_library::{Clock, Event, Library, Op};
|
||||||
|
|
||||||
|
/// Europe/Prague's UTC offset at a moment (minutes): CEST from the last Sunday of March 01:00 UTC to the last Sunday of
|
||||||
|
/// October 01:00 UTC, CET otherwise. Written out here because the core has no time-zone database by design.
|
||||||
|
pub fn prague(utc_ms: i64) -> i32 {
|
||||||
|
let day = utc_ms.div_euclid(86_400_000);
|
||||||
|
let (y, _, _) = civil(day);
|
||||||
|
let last_sunday = |m: u32| {
|
||||||
|
let last = liber_library::days_from_civil(y, m, 31);
|
||||||
|
last - ((last + 3).rem_euclid(7) - 6).rem_euclid(7)
|
||||||
|
};
|
||||||
|
let start = last_sunday(3) * 86_400_000 + 3_600_000;
|
||||||
|
let end = last_sunday(10) * 86_400_000 + 3_600_000;
|
||||||
|
if utc_ms >= start && utc_ms < end { 120 } else { 60 }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn civil(z: i64) -> (i64, u32, u32) {
|
||||||
|
let z = z + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let doe = z - era * 146_097;
|
||||||
|
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||||
|
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||||
|
(yoe + era * 400 + i64::from(m <= 2), m, d)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A library with one book and the given events after it.
|
||||||
|
pub struct Log {
|
||||||
|
pub events: Vec<Event>,
|
||||||
|
clock: Clock,
|
||||||
|
n: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Log {
|
||||||
|
pub fn new() -> Log {
|
||||||
|
let mut l = Log { events: vec![], clock: Clock::default(), n: 0 };
|
||||||
|
l.push(Op::BookAdd {
|
||||||
|
book: "b".into(),
|
||||||
|
info: BookInfo { title: "Kniha".into(), ..BookInfo::default() },
|
||||||
|
restore: false,
|
||||||
|
});
|
||||||
|
l
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push(&mut self, op: Op) {
|
||||||
|
self.n += 1;
|
||||||
|
let hlc = self.clock.tick(self.n as u64);
|
||||||
|
self.events.push(Event { id: format!("e{}", self.n), hlc, device: "d".into(), op });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A session starting at `utc_ms` in Prague, `pages` turned.
|
||||||
|
pub fn read_at(&mut self, utc_ms: i64, pages: u32) {
|
||||||
|
let n = self.n;
|
||||||
|
self.push(Op::Session {
|
||||||
|
id: format!("s{n}"),
|
||||||
|
book: "b".into(),
|
||||||
|
start: utc_ms as u64,
|
||||||
|
end: utc_ms as u64 + 600_000,
|
||||||
|
active_ms: 300_000,
|
||||||
|
pages,
|
||||||
|
date: String::new(),
|
||||||
|
offset_min: Some(prague(utc_ms)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One page read at 20:00 Prague time on `day`.
|
||||||
|
pub fn read_day(&mut self, day: liber_habit::Day) {
|
||||||
|
let utc = day.0 * 86_400_000 + 20 * 3_600_000;
|
||||||
|
self.read_at(utc - prague(utc) as i64 * 60_000, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn lib(&self) -> Library {
|
||||||
|
Library::from_events(&self.events)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 2026-03-02 (a Monday) as a local day.
|
||||||
|
pub fn monday() -> liber_habit::Day {
|
||||||
|
liber_habit::Day::parse("2026-03-02").unwrap()
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
//! Mandatory test 1: every session maps to exactly one local day; DST changes in both directions (Europe/Prague)
|
||||||
|
//! neither skip nor double a day; a session spanning the rollover counts once.
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
use common::*;
|
||||||
|
use liber_habit::{Day, local_day};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const H: i64 = 3_600_000;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_prague_model_switches_on_the_right_days() {
|
||||||
|
// 2026: summer time from 29 March 01:00 UTC to 25 October 01:00 UTC.
|
||||||
|
let at = |d: &str, h: i64| Day::parse(d).unwrap().0 * 86_400_000 + h * H;
|
||||||
|
assert_eq!(prague(at("2026-03-29", 0) + 59 * 60_000), 60);
|
||||||
|
assert_eq!(prague(at("2026-03-29", 1)), 120);
|
||||||
|
assert_eq!(prague(at("2026-10-25", 0) + 59 * 60_000), 120);
|
||||||
|
assert_eq!(prague(at("2026-10-25", 1)), 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rollover_puts_after_midnight_on_the_evening_before() {
|
||||||
|
// 01:30 on 15 Nov (Prague, CET) is 00:30 UTC.
|
||||||
|
let t = Day::parse("2026-11-15").unwrap().0 * 86_400_000 + 30 * 60_000;
|
||||||
|
assert_eq!(local_day(t, 60, 3).date(), "2026-11-14");
|
||||||
|
assert_eq!(local_day(t, 60, 0).date(), "2026-11-15");
|
||||||
|
// 03:30 local is the new day.
|
||||||
|
assert_eq!(local_day(t + 2 * H, 60, 3).date(), "2026-11-15");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk_hours(from_day: &str, days: i64, rollover: u8) {
|
||||||
|
let start = Day::parse(from_day).unwrap().0 * 86_400_000;
|
||||||
|
let mut prev: Option<Day> = None;
|
||||||
|
let mut hours_per_day = std::collections::BTreeMap::new();
|
||||||
|
for h in 0..days * 24 {
|
||||||
|
let t = start + h * H;
|
||||||
|
let d = local_day(t, prague(t), rollover);
|
||||||
|
if let Some(p) = prev {
|
||||||
|
assert!(
|
||||||
|
d.0 - p.0 == 0 || d.0 - p.0 == 1,
|
||||||
|
"{} → {} at hour {h}: a day was skipped or went back",
|
||||||
|
p.date(),
|
||||||
|
d.date()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
*hours_per_day.entry(d).or_insert(0) += 1;
|
||||||
|
prev = Some(d);
|
||||||
|
}
|
||||||
|
let inner: Vec<_> = hours_per_day.iter().skip(1).take(hours_per_day.len().saturating_sub(2)).collect();
|
||||||
|
for (d, n) in inner {
|
||||||
|
assert!((23..=25).contains(n), "{} has {n} hours", d.date());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dst_in_both_directions_skips_and_doubles_nothing() {
|
||||||
|
for rollover in [0, 3, 5] {
|
||||||
|
walk_hours("2026-03-26", 7, rollover); // spring forward
|
||||||
|
walk_hours("2026-10-22", 7, rollover); // fall back
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_session_across_the_rollover_counts_once_for_its_start() {
|
||||||
|
let mut log = Log::new();
|
||||||
|
// 02:30 to 03:40 Prague (CET): starts before the 03:00 rollover.
|
||||||
|
let start = Day::parse("2026-11-15").unwrap().0 * 86_400_000 + (2 * 60 + 30 - 60) * 60_000;
|
||||||
|
log.read_at(start, 1);
|
||||||
|
let days = liber_habit::days_read(&log.lib());
|
||||||
|
assert_eq!(days.iter().map(|d| d.date()).collect::<Vec<_>>(), vec!["2026-11-14"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 2000, ..ProptestConfig::default() })]
|
||||||
|
#[test]
|
||||||
|
fn every_moment_has_exactly_one_day_and_it_is_consistent(ms in 0i64..4_102_444_800_000, rollover in 0u8..=6) {
|
||||||
|
let off = prague(ms);
|
||||||
|
let d = local_day(ms, off, rollover);
|
||||||
|
// The same moment always gives the same day, and the day contains the moment's shifted local time.
|
||||||
|
prop_assert_eq!(local_day(ms, off, rollover), d);
|
||||||
|
let local = ms + off as i64 * 60_000 - rollover as i64 * H;
|
||||||
|
prop_assert!(local >= d.0 * 86_400_000 && local < (d.0 + 1) * 86_400_000);
|
||||||
|
// An hour later is the same day or the next, never another.
|
||||||
|
let d2 = local_day(ms + H, prague(ms + H), rollover);
|
||||||
|
prop_assert!(d2.0 == d.0 || d2.0 == d.0 + 1);
|
||||||
|
prop_assert_eq!(Day::parse(&d.date()), Some(d));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
//! Mandatory tests 3 and 4: medals recomputed give byte-identical results; an imported Goodreads history earns
|
||||||
|
//! book-count medals and no day medals; the reminder never fires when it is off or the goal is met.
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
use common::*;
|
||||||
|
use liber_habit::{Reminder, medals, next_reminder, unseen};
|
||||||
|
use liber_library::Op;
|
||||||
|
use liber_library::library::{Field, Outcome};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn earned(lib: &liber_library::Library) -> Vec<(String, String)> {
|
||||||
|
medals(lib).into_iter().filter_map(|m| m.earned.map(|e| (m.id.to_owned(), e))).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recomputing_gives_byte_identical_medals() {
|
||||||
|
let mut log = Log::new();
|
||||||
|
let m = monday();
|
||||||
|
for d in 0..40 {
|
||||||
|
log.read_day(m.plus(d));
|
||||||
|
}
|
||||||
|
log.push(Op::ReadStart { book: "b".into(), read: "r1".into(), date: Some("2026-03-02".into()) });
|
||||||
|
log.push(Op::ReadEnd { read: "r1".into(), date: Some("2026-03-20".into()), outcome: Outcome::Read });
|
||||||
|
let a = serde_json::to_vec(&medals(&log.lib())).unwrap();
|
||||||
|
let b = serde_json::to_vec(&medals(&log.lib())).unwrap();
|
||||||
|
assert_eq!(a, b);
|
||||||
|
// Rebuilt from the same events in another order: the same bytes.
|
||||||
|
let mut rev = log.events.clone();
|
||||||
|
rev.reverse();
|
||||||
|
assert_eq!(serde_json::to_vec(&medals(&liber_library::Library::from_events(&rev))).unwrap(), a);
|
||||||
|
let e = earned(&log.lib());
|
||||||
|
assert!(e.contains(&("days-7".into(), m.plus(6).date())));
|
||||||
|
assert!(e.contains(&("days-30".into(), m.plus(29).date())));
|
||||||
|
assert!(e.contains(&("first-book".into(), "2026-03-20".into())));
|
||||||
|
assert!(!e.iter().any(|(id, _)| id == "days-100"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_imported_history_earns_book_medals_and_no_day_medals() {
|
||||||
|
// Goodreads: twelve books read, one of them twice, one abandoned; no reading sessions at all.
|
||||||
|
let mut csv =
|
||||||
|
String::from("Book Id,Title,Author,ISBN,ISBN13,My Rating,Date Read,Date Added,Exclusive Shelf,Read Count\n");
|
||||||
|
for i in 0..12 {
|
||||||
|
csv.push_str(&format!(
|
||||||
|
"{i},Kniha {i},Autor {i},,,4,2024/0{}/1{i},2024/01/01,read,{}\n",
|
||||||
|
1 + i % 9,
|
||||||
|
if i == 3 { 2 } else { 1 }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
csv.push_str("99,Opuštěná,Autor,,,0,,2024/01/01,read,1\n");
|
||||||
|
let mut n = 0;
|
||||||
|
let (ops, report) = liber_library::import::import_csv(
|
||||||
|
csv.as_bytes(),
|
||||||
|
&Default::default(),
|
||||||
|
&mut || {
|
||||||
|
n += 1;
|
||||||
|
format!("id{n}")
|
||||||
|
},
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(report.imported, 13);
|
||||||
|
let mut log = Log::new();
|
||||||
|
for op in ops {
|
||||||
|
log.push(op);
|
||||||
|
}
|
||||||
|
// StoryGraph-style: one did-not-finish.
|
||||||
|
log.push(Op::ReadStart { book: "b".into(), read: "dnf".into(), date: None });
|
||||||
|
log.push(Op::ReadEnd { read: "dnf".into(), date: Some("2024-05-01".into()), outcome: Outcome::DidNotFinish });
|
||||||
|
let lib = log.lib();
|
||||||
|
let e = earned(&lib);
|
||||||
|
let ids: Vec<&str> = e.iter().map(|(i, _)| i.as_str()).collect();
|
||||||
|
assert!(ids.contains(&"first-book"), "{ids:?}");
|
||||||
|
assert!(ids.contains(&"books-10"));
|
||||||
|
assert!(ids.contains(&"first-reread"));
|
||||||
|
assert!(ids.contains(&"let-go"));
|
||||||
|
assert!(!ids.iter().any(|i| i.starts_with("days-")), "no fake days: {ids:?}");
|
||||||
|
assert_eq!(liber_habit::habit(&lib, monday(), 1).total_days, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn five_moods_and_seen_medals() {
|
||||||
|
let mut log = Log::new();
|
||||||
|
log.push(Op::BookSet {
|
||||||
|
book: "b".into(),
|
||||||
|
field: Field::Moods,
|
||||||
|
value: json!(["dark", "tense", "sad", "funny", "hopeful"]),
|
||||||
|
base: None,
|
||||||
|
});
|
||||||
|
log.push(Op::ReadStart { book: "b".into(), read: "r".into(), date: None });
|
||||||
|
log.push(Op::ReadEnd { read: "r".into(), date: Some("2026-01-05".into()), outcome: Outcome::Read });
|
||||||
|
let lib = log.lib();
|
||||||
|
assert!(earned(&lib).contains(&("five-moods".into(), "2026-01-05".into())));
|
||||||
|
assert_eq!(unseen(&lib).len(), 2, "first book and five moods");
|
||||||
|
log.push(Op::MedalSeen { medal: "first-book".into() });
|
||||||
|
let lib = log.lib();
|
||||||
|
assert_eq!(unseen(&lib).iter().map(|m| m.id).collect::<Vec<_>>(), vec!["five-moods"]);
|
||||||
|
assert!(
|
||||||
|
medals(&lib).iter().filter(|m| !m.available).all(|m| m.earned.is_none()),
|
||||||
|
"later medals cannot be earned yet"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_reminder_is_quiet_when_off_or_when_the_goal_is_met() {
|
||||||
|
let today = monday();
|
||||||
|
let off = Reminder { enabled: false, minute: 20 * 60 };
|
||||||
|
let on = Reminder { enabled: true, minute: 20 * 60 };
|
||||||
|
for met in [false, true] {
|
||||||
|
for now in [0u16, 600, 1199, 1200, 1439] {
|
||||||
|
assert_eq!(next_reminder(&off, today, now, met), None);
|
||||||
|
let next = next_reminder(&on, today, now, met).unwrap();
|
||||||
|
if met {
|
||||||
|
assert_ne!(next.0, today, "never today when today's goal is met");
|
||||||
|
}
|
||||||
|
assert_eq!(next.1, 1200);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(next_reminder(&on, today, 600, false), Some((today, 1200)));
|
||||||
|
assert_eq!(next_reminder(&on, today, 1300, false), Some((today.plus(1), 1200)));
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
//! Mandatory test 2: one miss per week keeps the streak; two misses in one week end it; the total never decreases.
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
use common::*;
|
||||||
|
use liber_habit::{Mark, habit};
|
||||||
|
use liber_library::Op;
|
||||||
|
use liber_library::library::{DailyKind, HabitGoal};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_miss_a_week_keeps_the_streak() {
|
||||||
|
let mut log = Log::new();
|
||||||
|
let m = monday();
|
||||||
|
// Four weeks, each missing one day (Wednesday).
|
||||||
|
for w in 0..4 {
|
||||||
|
for d in 0..7 {
|
||||||
|
if d != 2 {
|
||||||
|
log.read_day(m.plus(w * 7 + d));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let today = m.plus(4 * 7); // the next Monday, not read yet
|
||||||
|
let h = habit(&log.lib(), today, 5);
|
||||||
|
assert_eq!(h.streak_weeks, 5, "four weeks with one miss each, and this week so far");
|
||||||
|
assert_eq!(h.total_days, 24);
|
||||||
|
assert!(!h.today_met);
|
||||||
|
assert_eq!(h.calendar[0][2], Mark::Forgiven);
|
||||||
|
assert_eq!(h.calendar[4][0], Mark::Today, "today is not a miss");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_second_miss_in_a_week_ends_the_streak_but_not_the_total() {
|
||||||
|
let mut log = Log::new();
|
||||||
|
let m = monday();
|
||||||
|
for d in 0..14 {
|
||||||
|
if d != 9 && d != 10 {
|
||||||
|
log.read_day(m.plus(d));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let today = m.plus(14);
|
||||||
|
let h = habit(&log.lib(), today, 3);
|
||||||
|
assert_eq!(h.streak_weeks, 1, "only this week counts again");
|
||||||
|
assert_eq!(h.total_days, 12);
|
||||||
|
assert_eq!(h.calendar[1][2], Mark::Forgiven);
|
||||||
|
assert_eq!(h.calendar[1][3], Mark::Missed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn days_before_the_first_day_are_not_misses() {
|
||||||
|
let mut log = Log::new();
|
||||||
|
let m = monday();
|
||||||
|
for d in 4..7 {
|
||||||
|
log.read_day(m.plus(d));
|
||||||
|
}
|
||||||
|
let h = habit(&log.lib(), m.plus(6), 1);
|
||||||
|
assert_eq!(h.streak_weeks, 1);
|
||||||
|
assert_eq!(h.calendar[0][0], Mark::None);
|
||||||
|
assert!(h.today_met);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_goal_decides_what_a_day_is() {
|
||||||
|
let mut log = Log::new();
|
||||||
|
let m = monday();
|
||||||
|
log.read_day(m); // one page, 5 active minutes
|
||||||
|
log.push(Op::HabitGoal { goal: HabitGoal { kind: DailyKind::Minutes, amount: 10, rollover_hour: 3 } });
|
||||||
|
assert_eq!(habit(&log.lib(), m, 1).total_days, 0, "5 minutes are not 10");
|
||||||
|
log.push(Op::HabitGoal { goal: HabitGoal { kind: DailyKind::Pages, amount: 1, rollover_hour: 3 } });
|
||||||
|
assert_eq!(habit(&log.lib(), m, 1).total_days, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 300, ..ProptestConfig::default() })]
|
||||||
|
/// Adding reading, or letting time pass, never lowers the total.
|
||||||
|
#[test]
|
||||||
|
fn the_total_never_decreases(read in prop::collection::vec(any::<bool>(), 1..120), extra in 0usize..120, later in 0i64..60) {
|
||||||
|
let m = monday();
|
||||||
|
let mut log = Log::new();
|
||||||
|
for (i, r) in read.iter().enumerate() {
|
||||||
|
if *r { log.read_day(m.plus(i as i64)); }
|
||||||
|
}
|
||||||
|
let today = m.plus(read.len() as i64);
|
||||||
|
let before = habit(&log.lib(), today, 1).total_days;
|
||||||
|
prop_assert!(habit(&log.lib(), today.plus(later), 1).total_days >= before);
|
||||||
|
log.read_day(m.plus(extra as i64));
|
||||||
|
prop_assert!(habit(&log.lib(), today.plus(later), 1).total_days >= before);
|
||||||
|
// And the streak is never more than the weeks since the first day read.
|
||||||
|
let h = habit(&log.lib(), today, 1);
|
||||||
|
let weeks = (today.week().0 - m.week().0) / 7 + 1;
|
||||||
|
prop_assert!(h.streak_weeks as i64 <= weeks);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A random history with at most one miss in every week keeps the streak across all its weeks.
|
||||||
|
#[test]
|
||||||
|
fn one_miss_per_week_anywhere_keeps_it(misses in prop::collection::vec(0u8..8, 2..20)) {
|
||||||
|
let m = monday();
|
||||||
|
let mut log = Log::new();
|
||||||
|
for (w, miss) in misses.iter().enumerate() {
|
||||||
|
for d in 0..7u8 {
|
||||||
|
if *miss != d { log.read_day(m.plus(w as i64 * 7 + d as i64)); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let today = m.plus(misses.len() as i64 * 7);
|
||||||
|
prop_assert_eq!(habit(&log.lib(), today, 1).streak_weeks as usize, misses.len() + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
[package]
|
||||||
|
name = "liber-lang"
|
||||||
|
description = "Liber Domi: words, lemmas, coverage, levels, word counts and edition alignment for reading in another language"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
unicode-segmentation.workspace = true
|
||||||
|
unicode-normalization.workspace = true
|
||||||
|
sha2.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
serde_json.workspace = true
|
||||||
|
proptest.workspace = true
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
//! Two editions of one book, aligned: chapters, then paragraphs within aligned chapters, then sentences within
|
||||||
|
//! aligned paragraphs. Baseline: Gale–Church (1993) length-based dynamic programming over beads 1:1, 1:0, 0:1, 2:1,
|
||||||
|
//! 1:2, 2:2, plus **anchors** — numbers and capitalised names found on both sides — that pull the path through them,
|
||||||
|
//! so one removed or merged paragraph does not shift everything after it.
|
||||||
|
|
||||||
|
use crate::token::{Kind, sentences, tokens};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
/// One aligned group: segment indices on each side (either side may be empty: an omission).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Bead {
|
||||||
|
pub a: Vec<usize>,
|
||||||
|
pub b: Vec<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gale–Church variance of the length ratio.
|
||||||
|
const S2: f64 = 6.8;
|
||||||
|
/// Bead shapes and their prior probabilities (Gale & Church 1993, table 5), split evenly between mirror shapes.
|
||||||
|
const SHAPES: [((usize, usize), f64); 6] =
|
||||||
|
[((1, 1), 0.89), ((1, 0), 0.005), ((0, 1), 0.005), ((2, 1), 0.0445), ((1, 2), 0.0445), ((2, 2), 0.011)];
|
||||||
|
/// What one shared anchor is worth, in the cost's units (nats), up to three per bead.
|
||||||
|
const ANCHOR: f64 = 2.5;
|
||||||
|
/// Two sides that both carry numbers but share none are unlikely to be the same text.
|
||||||
|
const NUMBER_MISMATCH: f64 = 2.0;
|
||||||
|
|
||||||
|
struct Seg {
|
||||||
|
len: f64,
|
||||||
|
anchors: BTreeSet<String>,
|
||||||
|
numbers: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn seg(text: &str) -> Seg {
|
||||||
|
let mut anchors = BTreeSet::new();
|
||||||
|
let mut numbers = false;
|
||||||
|
for t in tokens(text) {
|
||||||
|
match t.kind {
|
||||||
|
Kind::Number if t.text.chars().any(|c| c.is_ascii_digit()) => {
|
||||||
|
numbers = true;
|
||||||
|
anchors.insert(t.text.clone());
|
||||||
|
}
|
||||||
|
Kind::Word if t.capitalised() && !t.sentence_start && t.text.chars().count() >= 3 => {
|
||||||
|
// Names keep their stem across languages more often than their endings (Caesar / Caesaris).
|
||||||
|
let stem: String = t.text.chars().take(5).flat_map(char::to_lowercase).collect();
|
||||||
|
anchors.insert(stem);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Seg { len: text.chars().filter(|c| !c.is_whitespace()).count() as f64, anchors, numbers }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The standard normal CDF (Abramowitz & Stegun 7.1.26 through erf).
|
||||||
|
fn phi(x: f64) -> f64 {
|
||||||
|
let z = x.abs() / std::f64::consts::SQRT_2;
|
||||||
|
let t = 1.0 / (1.0 + 0.327_591_1 * z);
|
||||||
|
let y = 1.0
|
||||||
|
- (((((1.061_405_429 * t - 1.453_152_027) * t) + 1.421_413_741) * t - 0.284_496_736) * t + 0.254_829_592)
|
||||||
|
* t
|
||||||
|
* (-z * z).exp();
|
||||||
|
if x >= 0.0 { 0.5 * (1.0 + y) } else { 0.5 * (1.0 - y) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length_cost(la: f64, lb: f64, ratio: f64) -> f64 {
|
||||||
|
if la == 0.0 && lb == 0.0 {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
let mean = (la + lb / ratio) / 2.0;
|
||||||
|
let delta = (lb - la * ratio) / (mean.max(1.0) * S2).sqrt();
|
||||||
|
let p = 2.0 * (1.0 - phi(delta.abs()));
|
||||||
|
-(p.max(1e-12)).ln()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Aligns two sequences of segments (chapters, paragraphs or sentences) by their lengths and anchors.
|
||||||
|
pub fn align<S: AsRef<str>>(a: &[S], b: &[S]) -> Vec<Bead> {
|
||||||
|
let sa: Vec<Seg> = a.iter().map(|s| seg(s.as_ref())).collect();
|
||||||
|
let sb: Vec<Seg> = b.iter().map(|s| seg(s.as_ref())).collect();
|
||||||
|
let (n, m) = (sa.len(), sb.len());
|
||||||
|
if n == 0 || m == 0 {
|
||||||
|
return if n == 0 && m == 0 { Vec::new() } else { vec![Bead { a: (0..n).collect(), b: (0..m).collect() }] };
|
||||||
|
}
|
||||||
|
let total_a: f64 = sa.iter().map(|s| s.len).sum();
|
||||||
|
let total_b: f64 = sb.iter().map(|s| s.len).sum();
|
||||||
|
let ratio = if total_a > 0.0 && total_b > 0.0 { total_b / total_a } else { 1.0 };
|
||||||
|
|
||||||
|
// A band around the diagonal keeps a book-length alignment small: wide enough for every omission seen in
|
||||||
|
// practice, the whole table when the sides are short.
|
||||||
|
let width = (n.abs_diff(m) + 64).max(64);
|
||||||
|
let centre = |i: usize| -> usize { i * m / n };
|
||||||
|
let lo = |i: usize| centre(i).saturating_sub(width);
|
||||||
|
let hi = |i: usize| (centre(i) + width).min(m);
|
||||||
|
let w = 2 * width + 1;
|
||||||
|
let idx = |i: usize, j: usize| -> Option<usize> { (j >= lo(i) && j <= hi(i)).then(|| i * w + (j - lo(i))) };
|
||||||
|
let mut cost = vec![f64::INFINITY; (n + 1) * w];
|
||||||
|
let mut back = vec![u8::MAX; (n + 1) * w];
|
||||||
|
cost[idx(0, 0).expect("origin in band")] = 0.0;
|
||||||
|
|
||||||
|
for i in 0..=n {
|
||||||
|
for j in lo(i)..=hi(i) {
|
||||||
|
if i == 0 && j == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let here = idx(i, j).expect("in band");
|
||||||
|
for (k, &((di, dj), prior)) in SHAPES.iter().enumerate() {
|
||||||
|
if di > i || dj > j {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(prev) = idx(i - di, j - dj) else { continue };
|
||||||
|
let before = cost[prev];
|
||||||
|
if !before.is_finite() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let la: f64 = sa[i - di..i].iter().map(|s| s.len).sum();
|
||||||
|
let lb: f64 = sb[j - dj..j].iter().map(|s| s.len).sum();
|
||||||
|
// An omission costs its prior only: comparing a paragraph's length with nothing says nothing, and it
|
||||||
|
// would make a badly fitting merge look cheaper than the omission it really is.
|
||||||
|
let mut c = if di == 0 || dj == 0 { -prior.ln() } else { length_cost(la, lb, ratio) - prior.ln() };
|
||||||
|
if di > 0 && dj > 0 {
|
||||||
|
let left: BTreeSet<&String> = sa[i - di..i].iter().flat_map(|s| &s.anchors).collect();
|
||||||
|
let right: BTreeSet<&String> = sb[j - dj..j].iter().flat_map(|s| &s.anchors).collect();
|
||||||
|
let shared = left.intersection(&right).count().min(3);
|
||||||
|
c -= ANCHOR * shared as f64;
|
||||||
|
let nums_a = sa[i - di..i].iter().any(|s| s.numbers);
|
||||||
|
let nums_b = sb[j - dj..j].iter().any(|s| s.numbers);
|
||||||
|
if nums_a && nums_b && shared == 0 {
|
||||||
|
c += NUMBER_MISMATCH;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if before + c < cost[here] {
|
||||||
|
cost[here] = before + c;
|
||||||
|
back[here] = k as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut beads = Vec::new();
|
||||||
|
let (mut i, mut j) = (n, m);
|
||||||
|
while i > 0 || j > 0 {
|
||||||
|
let Some(at) = idx(i, j) else { break };
|
||||||
|
let k = back[at];
|
||||||
|
if k == u8::MAX {
|
||||||
|
// Unreachable inside the band (cannot happen with the band above); keep the rest as one bead.
|
||||||
|
beads.push(Bead { a: (0..i).collect(), b: (0..j).collect() });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let ((di, dj), _) = SHAPES[k as usize];
|
||||||
|
beads.push(Bead { a: (i - di..i).collect(), b: (j - dj..j).collect() });
|
||||||
|
i -= di;
|
||||||
|
j -= dj;
|
||||||
|
}
|
||||||
|
beads.reverse();
|
||||||
|
beads
|
||||||
|
}
|
||||||
|
|
||||||
|
/// UTF-16 `(start, end)` ranges of sentences on each side of one aligned group.
|
||||||
|
pub type SentencePair = (Vec<(usize, usize)>, Vec<(usize, usize)>);
|
||||||
|
|
||||||
|
/// Sentences of two aligned paragraphs, aligned: each pair is the UTF-16 ranges of its sentences in `a` and in `b`.
|
||||||
|
pub fn sentence_pairs(a: &str, b: &str) -> Vec<SentencePair> {
|
||||||
|
let sa = sentences(a);
|
||||||
|
let sb = sentences(b);
|
||||||
|
let text = |s: &str, r: (usize, usize)| -> String {
|
||||||
|
let units: Vec<u16> = s.encode_utf16().collect();
|
||||||
|
String::from_utf16_lossy(&units[r.0.min(units.len())..r.1.min(units.len())])
|
||||||
|
};
|
||||||
|
let ta: Vec<String> = sa.iter().map(|&r| text(a, r)).collect();
|
||||||
|
let tb: Vec<String> = sb.iter().map(|&r| text(b, r)).collect();
|
||||||
|
align(&ta, &tb)
|
||||||
|
.into_iter()
|
||||||
|
.map(|bead| (bead.a.iter().map(|&k| sa[k]).collect(), bead.b.iter().map(|&k| sb[k]).collect()))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Precision, recall and F1 of an alignment against a gold one, over the links (every a-index × b-index pair of a
|
||||||
|
/// bead). Omissions (beads with an empty side) count as links to nothing on that side.
|
||||||
|
pub fn score(found: &[Bead], gold: &[Bead]) -> (f64, f64, f64) {
|
||||||
|
let links = |beads: &[Bead]| -> BTreeSet<(Option<usize>, Option<usize>)> {
|
||||||
|
let mut s = BTreeSet::new();
|
||||||
|
for bd in beads {
|
||||||
|
if bd.a.is_empty() {
|
||||||
|
s.extend(bd.b.iter().map(|&y| (None, Some(y))));
|
||||||
|
} else if bd.b.is_empty() {
|
||||||
|
s.extend(bd.a.iter().map(|&x| (Some(x), None)));
|
||||||
|
} else {
|
||||||
|
for &x in &bd.a {
|
||||||
|
for &y in &bd.b {
|
||||||
|
s.insert((Some(x), Some(y)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s
|
||||||
|
};
|
||||||
|
let f = links(found);
|
||||||
|
let g = links(gold);
|
||||||
|
let hit = f.intersection(&g).count() as f64;
|
||||||
|
let p = if f.is_empty() { 0.0 } else { hit / f.len() as f64 };
|
||||||
|
let r = if g.is_empty() { 0.0 } else { hit / g.len() as f64 };
|
||||||
|
let f1 = if p + r == 0.0 { 0.0 } else { 2.0 * p * r / (p + r) };
|
||||||
|
(p, r, f1)
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
//! Ludus concept ids for vocabulary: `w-<lang>-<16 base32 chars of sha256(lemma)>` (lowercase ASCII, Ludus rule).
|
||||||
|
|
||||||
|
use crate::{Lang, fold};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
|
||||||
|
|
||||||
|
/// The concept id of a lemma. The lemma is folded first (lowercase, NFC; Latin `j`/`v` → `i`/`u`), so every form of
|
||||||
|
/// one lemma shares one concept.
|
||||||
|
pub fn concept_id(lang: Lang, lemma: &str) -> String {
|
||||||
|
let digest = Sha256::digest(fold(lemma, lang).as_bytes());
|
||||||
|
// 16 base32 characters are exactly 80 bits: the first 10 bytes.
|
||||||
|
let mut bits: u128 = 0;
|
||||||
|
for &b in &digest[..10] {
|
||||||
|
bits = (bits << 8) | u128::from(b);
|
||||||
|
}
|
||||||
|
let mut out = String::with_capacity(21);
|
||||||
|
out.push_str("w-");
|
||||||
|
out.push_str(lang.code());
|
||||||
|
out.push('-');
|
||||||
|
for i in (0..16).rev() {
|
||||||
|
out.push(ALPHABET[((bits >> (i * 5)) & 31) as usize] as char);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
@@ -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(" ")
|
||||||
|
}
|
||||||
@@ -0,0 +1,919 @@
|
|||||||
|
//! Lemmas: the dictionary form a running word counts as (`went` → `go`, `Häuser` → `Haus`, `amavit` → `amo`).
|
||||||
|
//!
|
||||||
|
//! Two kinds, chained by [`Chain`]: a lookup [`Table`] (form → lemma) loaded from a data file whose licence Mark has
|
||||||
|
//! decided, then [`Rules`] written in this repository (suffix rules and short irregular lists, no outside data).
|
||||||
|
//! Rules propose candidates in order of likelihood; when a headword list ([`Headwords`]) is present, the first
|
||||||
|
//! candidate it knows wins, else the first candidate. Accuracy per language: `docs/03_languages.md` (app repo).
|
||||||
|
|
||||||
|
use crate::{Lang, fold};
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
|
/// A running word's dictionary form, folded (see [`crate::fold`]). `None`: not a word this lemmatizer will name.
|
||||||
|
pub trait Lemmatizer {
|
||||||
|
fn lang(&self) -> Lang;
|
||||||
|
fn lemma(&self, form: &str) -> Option<String>;
|
||||||
|
/// Whether a lexicon (a table or headwords) knows this form; rules alone know nothing. Used to tell German proper
|
||||||
|
/// nouns from common nouns, which are both capitalised.
|
||||||
|
fn knows(&self, _form: &str) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Caps for a table read from a file: hostile input.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct TableLimits {
|
||||||
|
pub max_bytes: usize,
|
||||||
|
pub max_entries: usize,
|
||||||
|
pub max_word: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for TableLimits {
|
||||||
|
fn default() -> Self {
|
||||||
|
TableLimits { max_bytes: 64 << 20, max_entries: 3_000_000, max_word: 64 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub enum TableError {
|
||||||
|
TooLarge,
|
||||||
|
TooManyEntries,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Form → lemma, both folded. Lines: `form<TAB>lemma`; `#` comments, blank lines and malformed lines are skipped.
|
||||||
|
pub struct Table {
|
||||||
|
lang: Lang,
|
||||||
|
map: HashMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Table {
|
||||||
|
pub fn from_tsv(lang: Lang, text: &str, limits: TableLimits) -> Result<Table, TableError> {
|
||||||
|
if text.len() > limits.max_bytes {
|
||||||
|
return Err(TableError::TooLarge);
|
||||||
|
}
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
for line in text.lines() {
|
||||||
|
let line = line.trim_end_matches('\r');
|
||||||
|
if line.is_empty() || line.starts_with('#') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut parts = line.split('\t');
|
||||||
|
let (Some(form), Some(lemma)) = (parts.next(), parts.next()) else { continue };
|
||||||
|
if form.is_empty()
|
||||||
|
|| lemma.is_empty()
|
||||||
|
|| form.chars().count() > limits.max_word
|
||||||
|
|| lemma.chars().count() > limits.max_word
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if map.len() >= limits.max_entries {
|
||||||
|
return Err(TableError::TooManyEntries);
|
||||||
|
}
|
||||||
|
map.entry(fold(form, lang)).or_insert_with(|| fold(lemma, lang));
|
||||||
|
}
|
||||||
|
Ok(Table { lang, map })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.map.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.map.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Lemmatizer for Table {
|
||||||
|
fn lang(&self) -> Lang {
|
||||||
|
self.lang
|
||||||
|
}
|
||||||
|
fn lemma(&self, form: &str) -> Option<String> {
|
||||||
|
self.map.get(&fold(form, self.lang)).cloned()
|
||||||
|
}
|
||||||
|
fn knows(&self, form: &str) -> bool {
|
||||||
|
self.map.contains_key(&fold(form, self.lang))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dictionary headwords (folded), used to choose among the rules' candidates.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Headwords(HashSet<String>);
|
||||||
|
|
||||||
|
impl Headwords {
|
||||||
|
pub fn new(lang: Lang, words: impl IntoIterator<Item = impl AsRef<str>>) -> Headwords {
|
||||||
|
Headwords(words.into_iter().map(|w| fold(w.as_ref(), lang)).filter(|w| !w.is_empty()).collect())
|
||||||
|
}
|
||||||
|
pub fn contains(&self, w: &str) -> bool {
|
||||||
|
self.0.contains(w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hand-written rules for one language.
|
||||||
|
pub struct Rules {
|
||||||
|
lang: Lang,
|
||||||
|
irregular: HashMap<&'static str, &'static str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Rules {
|
||||||
|
pub fn new(lang: Lang) -> Rules {
|
||||||
|
let list: &[(&str, &str)] = match lang {
|
||||||
|
Lang::En => EN_IRREGULAR,
|
||||||
|
Lang::De => DE_IRREGULAR,
|
||||||
|
Lang::La => LA_IRREGULAR,
|
||||||
|
Lang::Cs => &[],
|
||||||
|
};
|
||||||
|
Rules { lang, irregular: list.iter().copied().collect() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Candidate lemmas, most likely first; never empty for a word (the form itself is the last resort).
|
||||||
|
pub fn candidates(&self, form: &str) -> Vec<String> {
|
||||||
|
let capital = form.chars().next().is_some_and(char::is_uppercase);
|
||||||
|
let w = fold(form, self.lang);
|
||||||
|
if let Some(l) = self.irregular.get(w.as_str()) {
|
||||||
|
return vec![(*l).to_owned()];
|
||||||
|
}
|
||||||
|
let mut out = match self.lang {
|
||||||
|
Lang::En => en(&w),
|
||||||
|
Lang::De => de(&w, capital),
|
||||||
|
Lang::La => la(&w),
|
||||||
|
Lang::Cs => vec![],
|
||||||
|
};
|
||||||
|
out.push(w);
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
out.retain(|c| c.chars().count() >= 1 && seen.insert(c.clone()));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Lemmatizer for Rules {
|
||||||
|
fn lang(&self) -> Lang {
|
||||||
|
self.lang
|
||||||
|
}
|
||||||
|
fn lemma(&self, form: &str) -> Option<String> {
|
||||||
|
self.candidates(form).into_iter().next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A table, then rules (choosing by headwords when present).
|
||||||
|
pub struct Chain {
|
||||||
|
pub table: Option<Table>,
|
||||||
|
pub headwords: Option<Headwords>,
|
||||||
|
pub rules: Rules,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Chain {
|
||||||
|
pub fn rules_only(lang: Lang) -> Chain {
|
||||||
|
Chain { table: None, headwords: None, rules: Rules::new(lang) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Lemmatizer for Chain {
|
||||||
|
fn lang(&self) -> Lang {
|
||||||
|
self.rules.lang
|
||||||
|
}
|
||||||
|
fn lemma(&self, form: &str) -> Option<String> {
|
||||||
|
if let Some(l) = self.table.as_ref().and_then(|t| t.lemma(form)) {
|
||||||
|
return Some(l);
|
||||||
|
}
|
||||||
|
let cands = self.rules.candidates(form);
|
||||||
|
if let Some(h) = &self.headwords
|
||||||
|
&& let Some(c) = cands.iter().find(|c| h.contains(c))
|
||||||
|
{
|
||||||
|
return Some(c.clone());
|
||||||
|
}
|
||||||
|
cands.into_iter().next()
|
||||||
|
}
|
||||||
|
fn knows(&self, form: &str) -> bool {
|
||||||
|
let w = fold(form, self.rules.lang);
|
||||||
|
self.table.as_ref().is_some_and(|t| t.knows(form)) || self.headwords.as_ref().is_some_and(|h| h.contains(&w))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn strip<'a>(w: &'a str, suffix: &str) -> Option<&'a str> {
|
||||||
|
w.strip_suffix(suffix).filter(|s| s.chars().count() >= 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn vowel(c: char) -> bool {
|
||||||
|
"aeiouy".contains(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// English: -s/-es/-ies, -ed/-ied, -ing (undoubling, restoring a silent e), -est; possessive 's.
|
||||||
|
fn en(w: &str) -> Vec<String> {
|
||||||
|
let possessive = w.strip_suffix("'s");
|
||||||
|
let w = possessive.unwrap_or(w);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let undouble = |s: &str| -> Option<String> {
|
||||||
|
let c: Vec<char> = s.chars().collect();
|
||||||
|
let n = c.len();
|
||||||
|
(n >= 3 && c[n - 1] == c[n - 2] && !vowel(c[n - 1]) && !"lsz".contains(c[n - 1]))
|
||||||
|
.then(|| c[..n - 1].iter().collect())
|
||||||
|
};
|
||||||
|
// A short consonant-vowel-consonant stem usually lost a silent e (`making` → `mak` → `make`).
|
||||||
|
let silent_e = |s: &str| -> bool {
|
||||||
|
let c: Vec<char> = s.chars().collect();
|
||||||
|
let n = c.len();
|
||||||
|
(2..=4).contains(&n)
|
||||||
|
&& !vowel(c[n - 1])
|
||||||
|
&& !"wxy".contains(c[n - 1])
|
||||||
|
&& vowel(c[n - 2])
|
||||||
|
&& (n < 3 || !vowel(c[n - 3]))
|
||||||
|
|| s.ends_with('v')
|
||||||
|
|| s.ends_with("rg")
|
||||||
|
|| s.ends_with("dg")
|
||||||
|
|| (s.ends_with('c') && n > 2)
|
||||||
|
};
|
||||||
|
for (suf, rep) in [("ies", "y"), ("ied", "y")] {
|
||||||
|
if let Some(s) = strip(w, suf) {
|
||||||
|
out.push(format!("{s}{rep}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for suf in ["ing", "ed"] {
|
||||||
|
if let Some(s) = strip(w, suf) {
|
||||||
|
if let Some(u) = undouble(s) {
|
||||||
|
out.push(u);
|
||||||
|
}
|
||||||
|
if silent_e(s) {
|
||||||
|
out.push(format!("{s}e"));
|
||||||
|
}
|
||||||
|
out.push(s.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(s) = strip(w, "est") {
|
||||||
|
if let Some(u) = undouble(s) {
|
||||||
|
out.push(u);
|
||||||
|
}
|
||||||
|
out.push(s.to_owned());
|
||||||
|
}
|
||||||
|
if !w.ends_with("ss") && !w.ends_with("us") && !w.ends_with("is") {
|
||||||
|
for suf in ["sses", "xes", "ches", "shes", "zes", "oes"] {
|
||||||
|
if let Some(s) = strip(w, suf) {
|
||||||
|
out.push(format!("{s}{}", &suf[..suf.len() - 2]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(s) = strip(w, "s") {
|
||||||
|
out.push(s.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if possessive.is_some() {
|
||||||
|
out.push(w.to_owned());
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// German: participles (ge…t, ge…en), past -te(n), personal endings → the infinitive; noun plurals and cases.
|
||||||
|
fn de(w: &str, capital: bool) -> Vec<String> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if capital {
|
||||||
|
// Nouns: -ern, -en, -er, -es, -e, -n, -s (longest first); a plural umlaut is not undone.
|
||||||
|
for suf in ["ern", "en", "er", "es", "e", "n", "s"] {
|
||||||
|
if let Some(s) = strip(w, suf)
|
||||||
|
&& s.chars().count() >= 3
|
||||||
|
{
|
||||||
|
out.push(s.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// -eln / -ern verbs (sammeln, wandern) keep their e; a vowel before it (spiel-, frier-) is an ordinary stem.
|
||||||
|
let inf = |s: &str| -> String {
|
||||||
|
let c: Vec<char> = s.chars().collect();
|
||||||
|
let n = c.len();
|
||||||
|
let el_er = n >= 3 && (s.ends_with("el") || s.ends_with("er")) && !vowel(c[n - 3]);
|
||||||
|
if s.ends_with('e') || el_er { format!("{s}n") } else { format!("{s}en") }
|
||||||
|
};
|
||||||
|
if let Some(rest) = w.strip_prefix("ge") {
|
||||||
|
if let Some(s) = strip(rest, "t") {
|
||||||
|
out.push(inf(s));
|
||||||
|
}
|
||||||
|
if let Some(s) = strip(rest, "et") {
|
||||||
|
out.push(inf(s));
|
||||||
|
}
|
||||||
|
if rest.ends_with("en") && rest.chars().count() > 3 {
|
||||||
|
out.push(rest.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A stem ending in t or d takes -ete (arbeit-ete, red-ete).
|
||||||
|
for suf in ["eten", "ete", "etest"] {
|
||||||
|
if let Some(s) = strip(w, suf)
|
||||||
|
&& (s.ends_with('t') || s.ends_with('d'))
|
||||||
|
{
|
||||||
|
out.push(inf(s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for suf in ["teten", "tete", "test", "tet", "ten", "te", "est", "et", "st", "t", "e"] {
|
||||||
|
if let Some(s) = strip(w, suf)
|
||||||
|
&& s.chars().count() >= 2
|
||||||
|
{
|
||||||
|
out.push(inf(s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Adjective endings (schönen → schön) after the verb readings.
|
||||||
|
for suf in ["sten", "ster", "stes", "ste", "en", "em", "er", "es", "e"] {
|
||||||
|
if let Some(s) = strip(w, suf)
|
||||||
|
&& s.chars().count() >= 3
|
||||||
|
{
|
||||||
|
out.push(s.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Latin: verb endings → the first person present (-o), noun and adjective endings → the nominative.
|
||||||
|
fn la(w: &str) -> Vec<String> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
// First conjugation (the most common): ama-t, ama-bat, ama-vit, ama-re …
|
||||||
|
for suf in [
|
||||||
|
"auerunt", "auissent", "auisset", "aueram", "auerat", "auit", "aui", "abant", "abat", "abam", "abunt", "abit",
|
||||||
|
"ant", "amus", "atis", "are", "ari", "atur", "antur", "at",
|
||||||
|
] {
|
||||||
|
if let Some(s) = strip(w, suf) {
|
||||||
|
out.push(format!("{s}o"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Second conjugation (hab-et, hab-ebat → habeo).
|
||||||
|
for suf in ["ebant", "ebat", "ebam", "ent", "et", "emus", "etis", "ere"] {
|
||||||
|
if let Some(s) = strip(w, suf) {
|
||||||
|
out.push(format!("{s}eo"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Other conjugations: present stems (-it, -unt, -ere, -iebat) → -o; the perfect is irregular. The second person
|
||||||
|
// (-as, -is, -es) is rare in narrative and left to the noun readings.
|
||||||
|
for suf in ["iebant", "iebat", "iunt", "unt", "itur", "untur", "ire", "it", "imus", "itis"] {
|
||||||
|
if let Some(s) = strip(w, suf) {
|
||||||
|
out.push(format!("{s}o"));
|
||||||
|
if suf.starts_with('i') {
|
||||||
|
out.push(format!("{s}io"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Nouns and adjectives. Second declension -us/-um; first -a; third left as the stem's nominative guess.
|
||||||
|
for (suf, rep) in [
|
||||||
|
("orum", "us"),
|
||||||
|
("arum", "a"),
|
||||||
|
("ibus", ""),
|
||||||
|
("ae", "a"),
|
||||||
|
("am", "a"),
|
||||||
|
("as", "a"),
|
||||||
|
("is", "us"),
|
||||||
|
("os", "us"),
|
||||||
|
("um", "us"),
|
||||||
|
("o", "us"),
|
||||||
|
("i", "us"),
|
||||||
|
("e", "us"),
|
||||||
|
("em", ""),
|
||||||
|
("es", ""),
|
||||||
|
] {
|
||||||
|
if let Some(s) = strip(w, suf) {
|
||||||
|
out.push(format!("{s}{rep}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Irregular forms: grammar facts written for this repository, not copied from a data set.
|
||||||
|
|
||||||
|
const EN_IRREGULAR: &[(&str, &str)] = &[
|
||||||
|
("am", "be"),
|
||||||
|
("is", "be"),
|
||||||
|
("are", "be"),
|
||||||
|
("was", "be"),
|
||||||
|
("were", "be"),
|
||||||
|
("been", "be"),
|
||||||
|
("being", "be"),
|
||||||
|
("has", "have"),
|
||||||
|
("had", "have"),
|
||||||
|
("having", "have"),
|
||||||
|
("does", "do"),
|
||||||
|
("did", "do"),
|
||||||
|
("done", "do"),
|
||||||
|
("went", "go"),
|
||||||
|
("gone", "go"),
|
||||||
|
("goes", "go"),
|
||||||
|
("said", "say"),
|
||||||
|
("says", "say"),
|
||||||
|
("made", "make"),
|
||||||
|
("took", "take"),
|
||||||
|
("taken", "take"),
|
||||||
|
("saw", "see"),
|
||||||
|
("seen", "see"),
|
||||||
|
("came", "come"),
|
||||||
|
("knew", "know"),
|
||||||
|
("known", "know"),
|
||||||
|
("got", "get"),
|
||||||
|
("gotten", "get"),
|
||||||
|
("gave", "give"),
|
||||||
|
("given", "give"),
|
||||||
|
("found", "find"),
|
||||||
|
("thought", "think"),
|
||||||
|
("told", "tell"),
|
||||||
|
("became", "become"),
|
||||||
|
("left", "leave"),
|
||||||
|
("felt", "feel"),
|
||||||
|
("brought", "bring"),
|
||||||
|
("began", "begin"),
|
||||||
|
("begun", "begin"),
|
||||||
|
("kept", "keep"),
|
||||||
|
("held", "hold"),
|
||||||
|
("wrote", "write"),
|
||||||
|
("written", "write"),
|
||||||
|
("stood", "stand"),
|
||||||
|
("heard", "hear"),
|
||||||
|
("meant", "mean"),
|
||||||
|
("met", "meet"),
|
||||||
|
("ran", "run"),
|
||||||
|
("paid", "pay"),
|
||||||
|
("sat", "sit"),
|
||||||
|
("spoke", "speak"),
|
||||||
|
("spoken", "speak"),
|
||||||
|
("led", "lead"),
|
||||||
|
("grew", "grow"),
|
||||||
|
("grown", "grow"),
|
||||||
|
("lost", "lose"),
|
||||||
|
("fell", "fall"),
|
||||||
|
("fallen", "fall"),
|
||||||
|
("sent", "send"),
|
||||||
|
("built", "build"),
|
||||||
|
("understood", "understand"),
|
||||||
|
("drew", "draw"),
|
||||||
|
("drawn", "draw"),
|
||||||
|
("broke", "break"),
|
||||||
|
("broken", "break"),
|
||||||
|
("spent", "spend"),
|
||||||
|
("rose", "rise"),
|
||||||
|
("risen", "rise"),
|
||||||
|
("drove", "drive"),
|
||||||
|
("driven", "drive"),
|
||||||
|
("bought", "buy"),
|
||||||
|
("wore", "wear"),
|
||||||
|
("worn", "wear"),
|
||||||
|
("chose", "choose"),
|
||||||
|
("chosen", "choose"),
|
||||||
|
("sought", "seek"),
|
||||||
|
("threw", "throw"),
|
||||||
|
("thrown", "throw"),
|
||||||
|
("caught", "catch"),
|
||||||
|
("dealt", "deal"),
|
||||||
|
("won", "win"),
|
||||||
|
("fought", "fight"),
|
||||||
|
("taught", "teach"),
|
||||||
|
("ate", "eat"),
|
||||||
|
("eaten", "eat"),
|
||||||
|
("sang", "sing"),
|
||||||
|
("sung", "sing"),
|
||||||
|
("slept", "sleep"),
|
||||||
|
("flew", "fly"),
|
||||||
|
("flown", "fly"),
|
||||||
|
("forgot", "forget"),
|
||||||
|
("forgotten", "forget"),
|
||||||
|
("hid", "hide"),
|
||||||
|
("hidden", "hide"),
|
||||||
|
("lay", "lie"),
|
||||||
|
("lain", "lie"),
|
||||||
|
("woke", "wake"),
|
||||||
|
("woken", "wake"),
|
||||||
|
("bore", "bear"),
|
||||||
|
("borne", "bear"),
|
||||||
|
("swore", "swear"),
|
||||||
|
("sworn", "swear"),
|
||||||
|
("shook", "shake"),
|
||||||
|
("shaken", "shake"),
|
||||||
|
("struck", "strike"),
|
||||||
|
("bit", "bite"),
|
||||||
|
("bitten", "bite"),
|
||||||
|
("hung", "hang"),
|
||||||
|
("fed", "feed"),
|
||||||
|
("fled", "flee"),
|
||||||
|
("sold", "sell"),
|
||||||
|
("lit", "light"),
|
||||||
|
("men", "man"),
|
||||||
|
("women", "woman"),
|
||||||
|
("children", "child"),
|
||||||
|
("feet", "foot"),
|
||||||
|
("teeth", "tooth"),
|
||||||
|
("mice", "mouse"),
|
||||||
|
("geese", "goose"),
|
||||||
|
("better", "good"),
|
||||||
|
("best", "good"),
|
||||||
|
("worse", "bad"),
|
||||||
|
("worst", "bad"),
|
||||||
|
("him", "he"),
|
||||||
|
("his", "he"),
|
||||||
|
("her", "she"),
|
||||||
|
("hers", "she"),
|
||||||
|
("them", "they"),
|
||||||
|
("their", "they"),
|
||||||
|
("us", "we"),
|
||||||
|
("our", "we"),
|
||||||
|
("me", "i"),
|
||||||
|
("my", "i"),
|
||||||
|
("an", "a"),
|
||||||
|
("this", "this"),
|
||||||
|
("these", "this"),
|
||||||
|
("those", "that"),
|
||||||
|
("news", "news"),
|
||||||
|
("always", "always"),
|
||||||
|
("perhaps", "perhaps"),
|
||||||
|
("was't", "be"),
|
||||||
|
("isn't", "be"),
|
||||||
|
("don't", "do"),
|
||||||
|
("didn't", "do"),
|
||||||
|
("can't", "can"),
|
||||||
|
("could", "can"),
|
||||||
|
("would", "will"),
|
||||||
|
("won't", "will"),
|
||||||
|
("shall", "shall"),
|
||||||
|
("should", "shall"),
|
||||||
|
("wives", "wife"),
|
||||||
|
("lives", "life"),
|
||||||
|
("knives", "knife"),
|
||||||
|
("leaves", "leaf"),
|
||||||
|
("halves", "half"),
|
||||||
|
("selves", "self"),
|
||||||
|
("thus", "thus"),
|
||||||
|
("yes", "yes"),
|
||||||
|
("as", "as"),
|
||||||
|
("this's", "this"),
|
||||||
|
];
|
||||||
|
|
||||||
|
const DE_IRREGULAR: &[(&str, &str)] = &[
|
||||||
|
("bin", "sein"),
|
||||||
|
("bist", "sein"),
|
||||||
|
("ist", "sein"),
|
||||||
|
("sind", "sein"),
|
||||||
|
("seid", "sein"),
|
||||||
|
("war", "sein"),
|
||||||
|
("warst", "sein"),
|
||||||
|
("waren", "sein"),
|
||||||
|
("wart", "sein"),
|
||||||
|
("gewesen", "sein"),
|
||||||
|
("wäre", "sein"),
|
||||||
|
("wären", "sein"),
|
||||||
|
("sei", "sein"),
|
||||||
|
("habe", "haben"),
|
||||||
|
("hast", "haben"),
|
||||||
|
("hat", "haben"),
|
||||||
|
("habt", "haben"),
|
||||||
|
("hatte", "haben"),
|
||||||
|
("hatten", "haben"),
|
||||||
|
("hattest", "haben"),
|
||||||
|
("gehabt", "haben"),
|
||||||
|
("hätte", "haben"),
|
||||||
|
("hätten", "haben"),
|
||||||
|
("werde", "werden"),
|
||||||
|
("wirst", "werden"),
|
||||||
|
("wird", "werden"),
|
||||||
|
("werdet", "werden"),
|
||||||
|
("wurde", "werden"),
|
||||||
|
("wurden", "werden"),
|
||||||
|
("geworden", "werden"),
|
||||||
|
("würde", "werden"),
|
||||||
|
("würden", "werden"),
|
||||||
|
("kann", "können"),
|
||||||
|
("kannst", "können"),
|
||||||
|
("konnte", "können"),
|
||||||
|
("konnten", "können"),
|
||||||
|
("könnte", "können"),
|
||||||
|
("muss", "müssen"),
|
||||||
|
("musst", "müssen"),
|
||||||
|
("musste", "müssen"),
|
||||||
|
("mussten", "müssen"),
|
||||||
|
("müsste", "müssen"),
|
||||||
|
("will", "wollen"),
|
||||||
|
("willst", "wollen"),
|
||||||
|
("wollte", "wollen"),
|
||||||
|
("wollten", "wollen"),
|
||||||
|
("darf", "dürfen"),
|
||||||
|
("durfte", "dürfen"),
|
||||||
|
("soll", "sollen"),
|
||||||
|
("sollte", "sollen"),
|
||||||
|
("mag", "mögen"),
|
||||||
|
("mochte", "mögen"),
|
||||||
|
("möchte", "mögen"),
|
||||||
|
("weiß", "wissen"),
|
||||||
|
("weißt", "wissen"),
|
||||||
|
("wusste", "wissen"),
|
||||||
|
("gewusst", "wissen"),
|
||||||
|
("ging", "gehen"),
|
||||||
|
("gingen", "gehen"),
|
||||||
|
("gegangen", "gehen"),
|
||||||
|
("geht", "gehen"),
|
||||||
|
("kam", "kommen"),
|
||||||
|
("kamen", "kommen"),
|
||||||
|
("gekommen", "kommen"),
|
||||||
|
("sah", "sehen"),
|
||||||
|
("sahen", "sehen"),
|
||||||
|
("gesehen", "sehen"),
|
||||||
|
("sieht", "sehen"),
|
||||||
|
("siehst", "sehen"),
|
||||||
|
("gab", "geben"),
|
||||||
|
("gaben", "geben"),
|
||||||
|
("gegeben", "geben"),
|
||||||
|
("gibt", "geben"),
|
||||||
|
("nahm", "nehmen"),
|
||||||
|
("nahmen", "nehmen"),
|
||||||
|
("genommen", "nehmen"),
|
||||||
|
("nimmt", "nehmen"),
|
||||||
|
("sprach", "sprechen"),
|
||||||
|
("sprachen", "sprechen"),
|
||||||
|
("gesprochen", "sprechen"),
|
||||||
|
("spricht", "sprechen"),
|
||||||
|
("fand", "finden"),
|
||||||
|
("fanden", "finden"),
|
||||||
|
("gefunden", "finden"),
|
||||||
|
("stand", "stehen"),
|
||||||
|
("standen", "stehen"),
|
||||||
|
("gestanden", "stehen"),
|
||||||
|
("lag", "liegen"),
|
||||||
|
("lagen", "liegen"),
|
||||||
|
("gelegen", "liegen"),
|
||||||
|
("saß", "sitzen"),
|
||||||
|
("saßen", "sitzen"),
|
||||||
|
("gesessen", "sitzen"),
|
||||||
|
("ließ", "lassen"),
|
||||||
|
("ließen", "lassen"),
|
||||||
|
("lässt", "lassen"),
|
||||||
|
("hielt", "halten"),
|
||||||
|
("hielten", "halten"),
|
||||||
|
("gehalten", "halten"),
|
||||||
|
("hält", "halten"),
|
||||||
|
("trug", "tragen"),
|
||||||
|
("getragen", "tragen"),
|
||||||
|
("trägt", "tragen"),
|
||||||
|
("rief", "rufen"),
|
||||||
|
("gerufen", "rufen"),
|
||||||
|
("lief", "laufen"),
|
||||||
|
("läuft", "laufen"),
|
||||||
|
("gelaufen", "laufen"),
|
||||||
|
("fiel", "fallen"),
|
||||||
|
("fällt", "fallen"),
|
||||||
|
("gefallen", "fallen"),
|
||||||
|
("schlief", "schlafen"),
|
||||||
|
("schläft", "schlafen"),
|
||||||
|
("trat", "treten"),
|
||||||
|
("tritt", "treten"),
|
||||||
|
("brachte", "bringen"),
|
||||||
|
("gebracht", "bringen"),
|
||||||
|
("dachte", "denken"),
|
||||||
|
("gedacht", "denken"),
|
||||||
|
("kannte", "kennen"),
|
||||||
|
("gekannt", "kennen"),
|
||||||
|
("tat", "tun"),
|
||||||
|
("getan", "tun"),
|
||||||
|
("aß", "essen"),
|
||||||
|
("isst", "essen"),
|
||||||
|
("gegessen", "essen"),
|
||||||
|
("trank", "trinken"),
|
||||||
|
("getrunken", "trinken"),
|
||||||
|
("schrieb", "schreiben"),
|
||||||
|
("geschrieben", "schreiben"),
|
||||||
|
("blieb", "bleiben"),
|
||||||
|
("geblieben", "bleiben"),
|
||||||
|
("der", "der"),
|
||||||
|
("die", "der"),
|
||||||
|
("das", "der"),
|
||||||
|
("den", "der"),
|
||||||
|
("dem", "der"),
|
||||||
|
("des", "der"),
|
||||||
|
("ein", "ein"),
|
||||||
|
("eine", "ein"),
|
||||||
|
("einen", "ein"),
|
||||||
|
("einem", "ein"),
|
||||||
|
("einer", "ein"),
|
||||||
|
("eines", "ein"),
|
||||||
|
("kein", "kein"),
|
||||||
|
("keine", "kein"),
|
||||||
|
("keinen", "kein"),
|
||||||
|
("keinem", "kein"),
|
||||||
|
("keiner", "kein"),
|
||||||
|
("ich", "ich"),
|
||||||
|
("mich", "ich"),
|
||||||
|
("mir", "ich"),
|
||||||
|
("du", "du"),
|
||||||
|
("dich", "du"),
|
||||||
|
("dir", "du"),
|
||||||
|
("er", "er"),
|
||||||
|
("ihn", "er"),
|
||||||
|
("ihm", "er"),
|
||||||
|
("wir", "wir"),
|
||||||
|
("uns", "wir"),
|
||||||
|
("ihr", "ihr"),
|
||||||
|
("euch", "ihr"),
|
||||||
|
("sie", "sie"),
|
||||||
|
("ihnen", "sie"),
|
||||||
|
("mein", "mein"),
|
||||||
|
("meine", "mein"),
|
||||||
|
("meinen", "mein"),
|
||||||
|
("meinem", "mein"),
|
||||||
|
("meiner", "mein"),
|
||||||
|
("meines", "mein"),
|
||||||
|
("dein", "dein"),
|
||||||
|
("deine", "dein"),
|
||||||
|
("deinen", "dein"),
|
||||||
|
("deinem", "dein"),
|
||||||
|
("seine", "sein"),
|
||||||
|
("seinen", "sein"),
|
||||||
|
("seinem", "sein"),
|
||||||
|
("seiner", "sein"),
|
||||||
|
("ihre", "ihr"),
|
||||||
|
("ihren", "ihr"),
|
||||||
|
("ihrem", "ihr"),
|
||||||
|
("ihrer", "ihr"),
|
||||||
|
("dieser", "dieser"),
|
||||||
|
("diese", "dieser"),
|
||||||
|
("dieses", "dieser"),
|
||||||
|
("diesen", "dieser"),
|
||||||
|
("diesem", "dieser"),
|
||||||
|
("und", "und"),
|
||||||
|
("aber", "aber"),
|
||||||
|
("oder", "oder"),
|
||||||
|
("nicht", "nicht"),
|
||||||
|
("auch", "auch"),
|
||||||
|
("noch", "noch"),
|
||||||
|
("schon", "schon"),
|
||||||
|
("sehr", "sehr"),
|
||||||
|
("immer", "immer"),
|
||||||
|
("wieder", "wieder"),
|
||||||
|
("unter", "unter"),
|
||||||
|
("über", "über"),
|
||||||
|
("hinter", "hinter"),
|
||||||
|
("wenn", "wenn"),
|
||||||
|
("dann", "dann"),
|
||||||
|
("denn", "denn"),
|
||||||
|
("als", "als"),
|
||||||
|
("dass", "dass"),
|
||||||
|
("daß", "dass"),
|
||||||
|
("nachdem", "nachdem"),
|
||||||
|
("besser", "gut"),
|
||||||
|
("beste", "gut"),
|
||||||
|
("besten", "gut"),
|
||||||
|
("mehr", "viel"),
|
||||||
|
("meisten", "viel"),
|
||||||
|
];
|
||||||
|
|
||||||
|
const LA_IRREGULAR: &[(&str, &str)] = &[
|
||||||
|
("sum", "sum"),
|
||||||
|
("es", "sum"),
|
||||||
|
("est", "sum"),
|
||||||
|
("sumus", "sum"),
|
||||||
|
("estis", "sum"),
|
||||||
|
("sunt", "sum"),
|
||||||
|
("eram", "sum"),
|
||||||
|
("eras", "sum"),
|
||||||
|
("erat", "sum"),
|
||||||
|
("eramus", "sum"),
|
||||||
|
("erant", "sum"),
|
||||||
|
("ero", "sum"),
|
||||||
|
("erit", "sum"),
|
||||||
|
("erunt", "sum"),
|
||||||
|
("fui", "sum"),
|
||||||
|
("fuit", "sum"),
|
||||||
|
("fuerunt", "sum"),
|
||||||
|
("fuerat", "sum"),
|
||||||
|
("esse", "sum"),
|
||||||
|
("sit", "sum"),
|
||||||
|
("sint", "sum"),
|
||||||
|
("esset", "sum"),
|
||||||
|
("essent", "sum"),
|
||||||
|
("possum", "possum"),
|
||||||
|
("potest", "possum"),
|
||||||
|
("possunt", "possum"),
|
||||||
|
("posse", "possum"),
|
||||||
|
("poterat", "possum"),
|
||||||
|
("potuit", "possum"),
|
||||||
|
("possit", "possum"),
|
||||||
|
("posset", "possum"),
|
||||||
|
("it", "eo"),
|
||||||
|
("eunt", "eo"),
|
||||||
|
("ire", "eo"),
|
||||||
|
("iit", "eo"),
|
||||||
|
("ibat", "eo"),
|
||||||
|
("fert", "fero"),
|
||||||
|
("ferunt", "fero"),
|
||||||
|
("ferre", "fero"),
|
||||||
|
("tulit", "fero"),
|
||||||
|
("latum", "fero"),
|
||||||
|
("uult", "uolo"),
|
||||||
|
("uolunt", "uolo"),
|
||||||
|
("uelle", "uolo"),
|
||||||
|
("uoluit", "uolo"),
|
||||||
|
("dixit", "dico"),
|
||||||
|
("dicit", "dico"),
|
||||||
|
("dixerunt", "dico"),
|
||||||
|
("fecit", "facio"),
|
||||||
|
("facit", "facio"),
|
||||||
|
("fecerunt", "facio"),
|
||||||
|
("uenit", "uenio"),
|
||||||
|
("uenerunt", "uenio"),
|
||||||
|
("uidit", "uideo"),
|
||||||
|
("uiderunt", "uideo"),
|
||||||
|
("cepit", "capio"),
|
||||||
|
("ceperunt", "capio"),
|
||||||
|
("dedit", "do"),
|
||||||
|
("dederunt", "do"),
|
||||||
|
("misit", "mitto"),
|
||||||
|
("duxit", "duco"),
|
||||||
|
("ego", "ego"),
|
||||||
|
("me", "ego"),
|
||||||
|
("mihi", "ego"),
|
||||||
|
("mei", "ego"),
|
||||||
|
("tu", "tu"),
|
||||||
|
("te", "tu"),
|
||||||
|
("tibi", "tu"),
|
||||||
|
("tui", "tu"),
|
||||||
|
("nos", "nos"),
|
||||||
|
("nobis", "nos"),
|
||||||
|
("uos", "uos"),
|
||||||
|
("uobis", "uos"),
|
||||||
|
("se", "sui"),
|
||||||
|
("sibi", "sui"),
|
||||||
|
("sese", "sui"),
|
||||||
|
("qui", "qui"),
|
||||||
|
("quae", "qui"),
|
||||||
|
("quod", "qui"),
|
||||||
|
("quem", "qui"),
|
||||||
|
("quam", "qui"),
|
||||||
|
("cuius", "qui"),
|
||||||
|
("cui", "qui"),
|
||||||
|
("quo", "qui"),
|
||||||
|
("qua", "qui"),
|
||||||
|
("quibus", "qui"),
|
||||||
|
("quos", "qui"),
|
||||||
|
("quas", "qui"),
|
||||||
|
("quorum", "qui"),
|
||||||
|
("quarum", "qui"),
|
||||||
|
("hic", "hic"),
|
||||||
|
("haec", "hic"),
|
||||||
|
("hoc", "hic"),
|
||||||
|
("huius", "hic"),
|
||||||
|
("huic", "hic"),
|
||||||
|
("hunc", "hic"),
|
||||||
|
("hanc", "hic"),
|
||||||
|
("hos", "hic"),
|
||||||
|
("has", "hic"),
|
||||||
|
("his", "hic"),
|
||||||
|
("horum", "hic"),
|
||||||
|
("harum", "hic"),
|
||||||
|
("ille", "ille"),
|
||||||
|
("illa", "ille"),
|
||||||
|
("illud", "ille"),
|
||||||
|
("illum", "ille"),
|
||||||
|
("illam", "ille"),
|
||||||
|
("illi", "ille"),
|
||||||
|
("illis", "ille"),
|
||||||
|
("illos", "ille"),
|
||||||
|
("illas", "ille"),
|
||||||
|
("illius", "ille"),
|
||||||
|
("illo", "ille"),
|
||||||
|
("illorum", "ille"),
|
||||||
|
("is", "is"),
|
||||||
|
("ea", "is"),
|
||||||
|
("id", "is"),
|
||||||
|
("eum", "is"),
|
||||||
|
("eam", "is"),
|
||||||
|
("eius", "is"),
|
||||||
|
("ei", "is"),
|
||||||
|
("eo", "is"),
|
||||||
|
("eos", "is"),
|
||||||
|
("eas", "is"),
|
||||||
|
("eis", "is"),
|
||||||
|
("iis", "is"),
|
||||||
|
("eorum", "is"),
|
||||||
|
("earum", "is"),
|
||||||
|
("et", "et"),
|
||||||
|
("in", "in"),
|
||||||
|
("cum", "cum"),
|
||||||
|
("non", "non"),
|
||||||
|
("ad", "ad"),
|
||||||
|
("ab", "ab"),
|
||||||
|
("a", "ab"),
|
||||||
|
("ex", "ex"),
|
||||||
|
("e", "ex"),
|
||||||
|
("de", "de"),
|
||||||
|
("sed", "sed"),
|
||||||
|
("ut", "ut"),
|
||||||
|
("per", "per"),
|
||||||
|
("ac", "atque"),
|
||||||
|
("atque", "atque"),
|
||||||
|
("neque", "neque"),
|
||||||
|
("nec", "neque"),
|
||||||
|
("enim", "enim"),
|
||||||
|
("autem", "autem"),
|
||||||
|
("tamen", "tamen"),
|
||||||
|
("etiam", "etiam"),
|
||||||
|
("inter", "inter"),
|
||||||
|
("propter", "propter"),
|
||||||
|
("post", "post"),
|
||||||
|
("ante", "ante"),
|
||||||
|
("contra", "contra"),
|
||||||
|
("apud", "apud"),
|
||||||
|
("sine", "sine"),
|
||||||
|
("omnis", "omnis"),
|
||||||
|
("omnes", "omnis"),
|
||||||
|
("omnia", "omnis"),
|
||||||
|
("omnibus", "omnis"),
|
||||||
|
("omnium", "omnis"),
|
||||||
|
("omnem", "omnis"),
|
||||||
|
("tres", "tres"),
|
||||||
|
("tria", "tres"),
|
||||||
|
("trium", "tres"),
|
||||||
|
("tribus", "tres"),
|
||||||
|
];
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
//! The climb: levels by known lemmas, and which books a reader can take on.
|
||||||
|
|
||||||
|
/// Known lemmas needed for each level (level 1 at 500 … level 6 at 8,000). Tunable by the app.
|
||||||
|
pub const LEVELS: [u32; 6] = [500, 1_000, 2_000, 4_000, 6_000, 8_000];
|
||||||
|
|
||||||
|
/// Coverage a book needs to open at the reader's level.
|
||||||
|
pub const UNLOCK: f64 = 0.95;
|
||||||
|
/// … or, for a book the reader has read in their own language.
|
||||||
|
pub const UNLOCK_FAMILIAR: f64 = 0.90;
|
||||||
|
|
||||||
|
/// The level reached with `known` lemmas (0 below the first threshold), and the lemmas still needed for the next
|
||||||
|
/// (`None` at the top).
|
||||||
|
pub fn level(known: u32, levels: &[u32]) -> (usize, Option<u32>) {
|
||||||
|
let reached = levels.iter().take_while(|&&t| known >= t).count();
|
||||||
|
(reached, levels.get(reached).map(|&t| t - known))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a book with this estimated coverage is open to the reader now.
|
||||||
|
pub fn unlocked(coverage: f64, read_in_own_language: bool) -> bool {
|
||||||
|
coverage.is_finite() && coverage >= if read_in_own_language { UNLOCK_FAMILIAR } else { UNLOCK }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "About 94%": whole percent, rounded down so 0.949 never reads as the 95% that unlocks.
|
||||||
|
pub fn percent(coverage: f64) -> u32 {
|
||||||
|
if !coverage.is_finite() || coverage <= 0.0 { 0 } else { ((coverage.min(1.0) * 100.0) + 1e-9).floor() as u32 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
//! Liber Domi, Day 3: reading a loved book in another language.
|
||||||
|
//!
|
||||||
|
//! Pure: text and tables in, values out. No files, no network, no clock, no model. The app supplies chapter text
|
||||||
|
//! (the same text the reader shows, so offsets are the reader's UTF-16 offsets) and, once Mark has decided their
|
||||||
|
//! licences, lemma tables; this crate never ships outside data. The day page is `docs/03_languages.md` in the app repo.
|
||||||
|
//!
|
||||||
|
//! - [`token`]: words, numbers and punctuation by Unicode word boundaries, with UTF-16 offsets.
|
||||||
|
//! - [`lemma`]: the [`Lemmatizer`] trait, a lookup [`lemma::Table`] and hand-written [`lemma::Rules`] per language.
|
||||||
|
//! - [`profile`]: a book's lemma counts per chapter; coverage, "comes up N more times", the warm-up's words.
|
||||||
|
//! - [`level`]: the climb (levels by known lemmas) and the unlock rule.
|
||||||
|
//! - [`align`]: two editions of one book, aligned chapters → paragraphs → sentences (Gale–Church with anchors).
|
||||||
|
//! - [`concept`]: Ludus concept ids for vocabulary.
|
||||||
|
|
||||||
|
pub mod align;
|
||||||
|
pub mod concept;
|
||||||
|
pub mod g2p;
|
||||||
|
pub mod lemma;
|
||||||
|
pub mod level;
|
||||||
|
pub mod profile;
|
||||||
|
pub mod token;
|
||||||
|
|
||||||
|
pub use lemma::Lemmatizer;
|
||||||
|
pub use profile::Profile;
|
||||||
|
pub use token::{Kind, Token, tokens};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// A language Liber can read in (Day 3: English, German, Latin).
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Lang {
|
||||||
|
En,
|
||||||
|
De,
|
||||||
|
La,
|
||||||
|
/// Day 4: Czech, for reading aloud (the reader's own language; no lemma rules).
|
||||||
|
Cs,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Lang {
|
||||||
|
/// From a BCP 47 tag or a book's `dc:language` (`de`, `de-AT`, `ger`, `deu`, `lat`, `en-GB`, …).
|
||||||
|
pub fn from_tag(tag: &str) -> Option<Lang> {
|
||||||
|
let primary = tag.trim().split(['-', '_']).next()?.to_ascii_lowercase();
|
||||||
|
match primary.as_str() {
|
||||||
|
"en" | "eng" => Some(Lang::En),
|
||||||
|
"de" | "ger" | "deu" => Some(Lang::De),
|
||||||
|
"la" | "lat" => Some(Lang::La),
|
||||||
|
"cs" | "cze" | "ces" => Some(Lang::Cs),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn code(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Lang::En => "en",
|
||||||
|
Lang::De => "de",
|
||||||
|
Lang::La => "la",
|
||||||
|
Lang::Cs => "cs",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lowercase and NFC: the one form lemmas are compared and stored in. Latin also folds `j` → `i` and `v` → `u`
|
||||||
|
/// (editions differ in both).
|
||||||
|
pub fn fold(word: &str, lang: Lang) -> String {
|
||||||
|
use unicode_normalization::UnicodeNormalization;
|
||||||
|
let lower: String = word.nfc().flat_map(char::to_lowercase).collect();
|
||||||
|
let lower = lower.replace(['\u{2019}', '\u{2018}'], "'");
|
||||||
|
if lang == Lang::La { lower.replace('j', "i").replace('v', "u") } else { lower }
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
//! A book's words: lemma counts per chapter. Coverage, "comes up N more times" and the warm-up are folds over it.
|
||||||
|
|
||||||
|
use crate::lemma::Lemmatizer;
|
||||||
|
use crate::token::{Kind, Token, tokens};
|
||||||
|
use crate::{Lang, fold};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
/// What a running word counts as.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Counted {
|
||||||
|
/// A word to know, by its lemma.
|
||||||
|
Lemma(String),
|
||||||
|
/// A name (never unknown), a number or punctuation: not counted.
|
||||||
|
Skip,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a running word is a proper noun. English and Latin: capitalised and not the first word of a sentence
|
||||||
|
/// (English `I` is not a name). German, where every noun is capitalised: capitalised and unknown to the lexicon.
|
||||||
|
pub fn is_name(tok: &Token, lang: Lang, lem: &dyn Lemmatizer) -> bool {
|
||||||
|
if tok.kind != Kind::Word || !tok.capitalised() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
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 | Lang::Cs => !tok.sentence_start,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How one token counts. `lem.lemma` returning `None` also skips the word.
|
||||||
|
pub fn count_as(tok: &Token, lang: Lang, lem: &dyn Lemmatizer) -> Counted {
|
||||||
|
if tok.kind != Kind::Word || is_name(tok, lang, lem) {
|
||||||
|
return Counted::Skip;
|
||||||
|
}
|
||||||
|
lem.lemma(&tok.text).map(Counted::Lemma).unwrap_or(Counted::Skip)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lemma counts per chapter, sorted by lemma (deterministic, so the same book always gives the same bytes).
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Profile {
|
||||||
|
pub lang: Option<Lang>,
|
||||||
|
pub chapters: Vec<BTreeMap<String, u32>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Profile {
|
||||||
|
/// From each chapter's text (the reader's text of that chapter).
|
||||||
|
pub fn build<S: AsRef<str>>(chapters: &[S], lem: &dyn Lemmatizer) -> Profile {
|
||||||
|
let lang = lem.lang();
|
||||||
|
let chapters = chapters
|
||||||
|
.iter()
|
||||||
|
.map(|text| {
|
||||||
|
let mut counts = BTreeMap::new();
|
||||||
|
for tok in tokens(text.as_ref()) {
|
||||||
|
if let Counted::Lemma(l) = count_as(&tok, lang, lem) {
|
||||||
|
*counts.entry(l).or_insert(0u32) += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
counts
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Profile { lang: Some(lang), chapters }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Countable running words in the whole book.
|
||||||
|
pub fn words(&self) -> u64 {
|
||||||
|
self.chapters.iter().flat_map(|c| c.values()).map(|&n| u64::from(n)).sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Counts over the whole book.
|
||||||
|
pub fn total(&self) -> BTreeMap<&str, u64> {
|
||||||
|
let mut t: BTreeMap<&str, u64> = BTreeMap::new();
|
||||||
|
for c in &self.chapters {
|
||||||
|
for (l, &n) in c {
|
||||||
|
*t.entry(l.as_str()).or_insert(0) += u64::from(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The share of countable running words whose lemma is known (0–1); 1 for a book with no countable words.
|
||||||
|
pub fn coverage(&self, known: &dyn Fn(&str) -> bool) -> f64 {
|
||||||
|
let (mut all, mut ok) = (0u64, 0u64);
|
||||||
|
for c in &self.chapters {
|
||||||
|
for (l, &n) in c {
|
||||||
|
all += u64::from(n);
|
||||||
|
if known(l) {
|
||||||
|
ok += u64::from(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if all == 0 { 1.0 } else { ok as f64 / all as f64 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How often a lemma appears in the chapters after `chapter` (the reader adds the rest of the current chapter
|
||||||
|
/// from its own text, which it has).
|
||||||
|
pub fn later(&self, lemma: &str, chapter: usize) -> u64 {
|
||||||
|
self.chapters.iter().skip(chapter + 1).filter_map(|c| c.get(lemma)).map(|&n| u64::from(n)).sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `n` most frequent unknown lemmas of a chapter, most frequent first, ties by lemma: the warm-up.
|
||||||
|
pub fn warmup(&self, chapter: usize, known: &dyn Fn(&str) -> bool, n: usize) -> Vec<(String, u32)> {
|
||||||
|
let Some(c) = self.chapters.get(chapter) else { return Vec::new() };
|
||||||
|
let mut v: Vec<(String, u32)> = c.iter().filter(|(l, _)| !known(l)).map(|(l, &k)| (l.clone(), k)).collect();
|
||||||
|
v.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||||
|
v.truncate(n);
|
||||||
|
v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lemma a single tapped word counts as, or `None` for a name, a number or punctuation.
|
||||||
|
pub fn lemma_at(text: &str, utf16_offset: usize, lem: &dyn Lemmatizer) -> Option<(Token, String)> {
|
||||||
|
let toks = tokens(text);
|
||||||
|
let tok = toks.into_iter().find(|t| t.start <= utf16_offset && utf16_offset < t.end)?;
|
||||||
|
match count_as(&tok, lem.lang(), lem) {
|
||||||
|
Counted::Lemma(l) => Some((tok, l)),
|
||||||
|
Counted::Skip => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Folds a word the reader marked by hand ("Known" on a word the lemmatizer could not name).
|
||||||
|
pub fn folded(word: &str, lang: Lang) -> String {
|
||||||
|
fold(word, lang)
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
//! Words by Unicode word boundaries (UAX #29), with the reader's UTF-16 offsets.
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use unicode_segmentation::UnicodeSegmentation;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Kind {
|
||||||
|
Word,
|
||||||
|
/// Digits, or a Roman numeral of two or more letters (`XII`, `IV`): never a word to learn.
|
||||||
|
Number,
|
||||||
|
Punct,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Token {
|
||||||
|
pub text: String,
|
||||||
|
/// UTF-16 offsets into the text given to [`tokens`].
|
||||||
|
pub start: usize,
|
||||||
|
pub end: usize,
|
||||||
|
pub kind: Kind,
|
||||||
|
/// The first word of a sentence (after `.`, `!`, `?`, `…`, `:` before a capital, or the start).
|
||||||
|
pub sentence_start: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Token {
|
||||||
|
pub fn capitalised(&self) -> bool {
|
||||||
|
self.text.chars().next().is_some_and(char::is_uppercase)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn roman(s: &str) -> bool {
|
||||||
|
s.chars().count() >= 2 && s.chars().all(|c| "IVXLCDM".contains(c))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every word, number and punctuation mark; whitespace is skipped. A word's apostrophes stay inside it (`don't`).
|
||||||
|
pub fn tokens(text: &str) -> Vec<Token> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut utf16 = 0usize;
|
||||||
|
let mut sentence = true;
|
||||||
|
for (_, piece) in text.split_word_bound_indices() {
|
||||||
|
let len = piece.encode_utf16().count();
|
||||||
|
let start = utf16;
|
||||||
|
utf16 += len;
|
||||||
|
if piece.chars().all(char::is_whitespace) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let kind = if piece.chars().any(char::is_alphabetic) {
|
||||||
|
if roman(piece) { Kind::Number } else { Kind::Word }
|
||||||
|
} else if piece.chars().any(|c| c.is_ascii_digit() || c.is_numeric()) {
|
||||||
|
Kind::Number
|
||||||
|
} else {
|
||||||
|
Kind::Punct
|
||||||
|
};
|
||||||
|
let starts = sentence && kind != Kind::Punct;
|
||||||
|
out.push(Token { text: piece.to_owned(), start, end: utf16, kind, sentence_start: starts });
|
||||||
|
match kind {
|
||||||
|
Kind::Punct if piece.chars().any(|c| matches!(c, '.' | '!' | '?' | '…' | '¿' | '¡')) => sentence = true,
|
||||||
|
Kind::Punct => {}
|
||||||
|
_ => sentence = false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sentences of a paragraph as `(start, end)` UTF-16 ranges, split after `.`, `!`, `?`, `…` (and closing quotes
|
||||||
|
/// after them). Abbreviations are not handled; the aligner tolerates the odd extra split.
|
||||||
|
pub fn sentences(text: &str) -> Vec<(usize, usize)> {
|
||||||
|
let toks = tokens(text);
|
||||||
|
let closer = |t: &Token| t.kind == Kind::Punct && t.text.chars().all(|c| "\"'”’»«)]".contains(c));
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut begin: Option<usize> = None;
|
||||||
|
let mut end = 0;
|
||||||
|
let mut pending = false;
|
||||||
|
for (i, t) in toks.iter().enumerate() {
|
||||||
|
if begin.is_none() && t.kind != Kind::Punct {
|
||||||
|
begin = Some(t.start);
|
||||||
|
}
|
||||||
|
end = t.end;
|
||||||
|
let stop = t.kind == Kind::Punct && t.text.chars().any(|c| matches!(c, '.' | '!' | '?' | '…'));
|
||||||
|
if stop || (pending && closer(t)) {
|
||||||
|
if toks.get(i + 1).is_some_and(closer) {
|
||||||
|
pending = true;
|
||||||
|
} else if let Some(b) = begin.take() {
|
||||||
|
out.push((b, end));
|
||||||
|
pending = false;
|
||||||
|
}
|
||||||
|
} else if t.kind != Kind::Punct {
|
||||||
|
pending = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(b) = begin {
|
||||||
|
out.push((b, end));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
//! Mandatory test 3: on a fixture pair of editions with a hand-made gold alignment, the baseline aligner reaches a
|
||||||
|
//! stated F1; removed or merged paragraphs do not shift every later sentence.
|
||||||
|
//!
|
||||||
|
//! The fixture (`fixtures/align_de.txt`, `align_en.txt`) is a short story written for this repository in German and
|
||||||
|
//! English and dedicated to the public domain (CC0). The English edition merges paragraphs 4 and 5, leaves out
|
||||||
|
//! paragraph 8 and splits the last paragraph's second sentence in two — the three things real editions do.
|
||||||
|
|
||||||
|
use liber_lang::align::{Bead, align, score, sentence_pairs};
|
||||||
|
|
||||||
|
/// Paragraphs, whatever line endings the checkout gave the fixture.
|
||||||
|
fn paragraphs(text: &str) -> Vec<String> {
|
||||||
|
text.replace("\r\n", "\n").split("\n\n").map(str::trim).filter(|p| !p.is_empty()).map(str::to_owned).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bead(a: &[usize], b: &[usize]) -> Bead {
|
||||||
|
Bead { a: a.to_vec(), b: b.to_vec() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stated F1 for paragraphs (docs/03_languages.md).
|
||||||
|
const PARAGRAPH_F1: f64 = 0.9;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paragraphs_align_to_the_gold() {
|
||||||
|
let de = paragraphs(include_str!("fixtures/align_de.txt"));
|
||||||
|
let en = paragraphs(include_str!("fixtures/align_en.txt"));
|
||||||
|
assert_eq!((de.len(), en.len()), (11, 9));
|
||||||
|
let gold = vec![
|
||||||
|
bead(&[0], &[0]),
|
||||||
|
bead(&[1], &[1]),
|
||||||
|
bead(&[2], &[2]),
|
||||||
|
bead(&[3], &[3]),
|
||||||
|
bead(&[4, 5], &[4]),
|
||||||
|
bead(&[6], &[5]),
|
||||||
|
bead(&[7], &[6]),
|
||||||
|
bead(&[8], &[]),
|
||||||
|
bead(&[9], &[7]),
|
||||||
|
bead(&[10], &[8]),
|
||||||
|
];
|
||||||
|
let found = align(&de, &en);
|
||||||
|
let (p, r, f1) = score(&found, &gold);
|
||||||
|
println!("paragraphs: P {p:.2} R {r:.2} F1 {f1:.2}\n{found:?}");
|
||||||
|
assert!(f1 >= PARAGRAPH_F1, "F1 {f1:.2}");
|
||||||
|
// Nothing after the merge and the omission is shifted: the last two paragraphs pair exactly.
|
||||||
|
assert!(found.contains(&bead(&[9], &[7])), "{found:?}");
|
||||||
|
assert!(found.contains(&bead(&[10], &[8])), "{found:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sentences_of_an_aligned_paragraph() {
|
||||||
|
let de = paragraphs(include_str!("fixtures/align_de.txt"));
|
||||||
|
let en = paragraphs(include_str!("fixtures/align_en.txt"));
|
||||||
|
// The last paragraph: two German sentences, three English (the second split in two).
|
||||||
|
let pairs = sentence_pairs(&de[10], &en[8]);
|
||||||
|
let shape: Vec<(usize, usize)> = pairs.iter().map(|(a, b)| (a.len(), b.len())).collect();
|
||||||
|
assert_eq!(shape, vec![(1, 1), (1, 2)], "{pairs:?}");
|
||||||
|
// A one-to-one paragraph: three and three.
|
||||||
|
let pairs = sentence_pairs(&de[2], &en[2]);
|
||||||
|
assert_eq!(pairs.iter().map(|(a, b)| (a.len(), b.len())).collect::<Vec<_>>(), vec![(1, 1), (1, 1), (1, 1)]);
|
||||||
|
// Ranges are UTF-16 offsets into the paragraph: the first German sentence is the reader's text.
|
||||||
|
let (a, _) = &pairs[0];
|
||||||
|
let units: Vec<u16> = de[2].encode_utf16().collect();
|
||||||
|
let first = String::from_utf16_lossy(&units[a[0].0..a[0].1]);
|
||||||
|
assert!(first.starts_with("Im Jahr 1847"), "{first}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A deterministic generator, so the test needs no `rand`.
|
||||||
|
struct Lcg(u64);
|
||||||
|
impl Lcg {
|
||||||
|
fn next(&mut self) -> u64 {
|
||||||
|
self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
|
||||||
|
self.0 >> 33
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_book_length_alignment_with_omissions_stays_on_track() {
|
||||||
|
// 1,500 paragraphs; the other edition is ~15% longer with noise, drops every 97th paragraph and merges every
|
||||||
|
// 131st with the next. Every 10th paragraph carries a number on both sides (a date, a chapter): the anchors.
|
||||||
|
let mut g = Lcg(7);
|
||||||
|
let mut a = Vec::new();
|
||||||
|
let mut b = Vec::new();
|
||||||
|
let mut gold = Vec::new();
|
||||||
|
let mut i = 0;
|
||||||
|
while i < 1500 {
|
||||||
|
let words = 8 + (g.next() % 120) as usize;
|
||||||
|
let mk = |n: usize, tag: Option<usize>| {
|
||||||
|
let mut s = "lorem ".repeat(n);
|
||||||
|
if let Some(t) = tag {
|
||||||
|
s.push_str(&format!(" {t}"));
|
||||||
|
}
|
||||||
|
s
|
||||||
|
};
|
||||||
|
let tag = (i % 10 == 0).then_some(i);
|
||||||
|
if i % 97 == 50 {
|
||||||
|
a.push(mk(words, tag));
|
||||||
|
gold.push(bead(&[i], &[]));
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if i % 131 == 60 && i + 1 < 1500 {
|
||||||
|
let words2 = 8 + (g.next() % 120) as usize;
|
||||||
|
a.push(mk(words, tag));
|
||||||
|
a.push(mk(words2, None));
|
||||||
|
let noisy = ((words + words2) as f64 * (1.1 + (g.next() % 10) as f64 / 100.0)) as usize;
|
||||||
|
gold.push(bead(&[i, i + 1], &[b.len()]));
|
||||||
|
b.push(mk(noisy, tag));
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
a.push(mk(words, tag));
|
||||||
|
let noisy = (words as f64 * (1.1 + (g.next() % 10) as f64 / 100.0)) as usize;
|
||||||
|
gold.push(bead(&[i], &[b.len()]));
|
||||||
|
b.push(mk(noisy.max(1), tag));
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
let found = align(&a, &b);
|
||||||
|
let (_, _, f1) = score(&found, &gold);
|
||||||
|
println!("book: {} vs {} paragraphs, F1 {f1:.3}", a.len(), b.len());
|
||||||
|
assert!(f1 >= 0.9, "F1 {f1:.3}");
|
||||||
|
// The end is on track: the last bead is the gold's last bead.
|
||||||
|
assert_eq!(found.last(), gold.last());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn edge_cases() {
|
||||||
|
assert!(align::<&str>(&[], &[]).is_empty());
|
||||||
|
assert_eq!(align(&["a"], &[] as &[&str]), vec![bead(&[0], &[])]);
|
||||||
|
assert_eq!(align(&["Hello there."], &["Hallo dort."]), vec![bead(&[0], &[0])]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
//! Mandatory test 1: on fixture texts with known lemma sets, the coverage figure matches a hand-computed value;
|
||||||
|
//! proper nouns and numbers are excluded; a known word in any inflected form counts as known.
|
||||||
|
|
||||||
|
use liber_lang::lemma::{Chain, Headwords, Rules, Table, TableLimits};
|
||||||
|
use liber_lang::profile::{Profile, lemma_at};
|
||||||
|
use liber_lang::{Lang, level};
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
fn known(words: &[&str]) -> impl Fn(&str) -> bool {
|
||||||
|
let set: BTreeSet<String> = words.iter().map(|w| (*w).to_owned()).collect();
|
||||||
|
move |l: &str| set.contains(l)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn coverage_matches_the_hand_count() {
|
||||||
|
// Counted (lemma): The(the) cat sat(sit) on the mat | The(the) cats(cat) were(be) happy and saw(see) cats(cat) in in
|
||||||
|
// chapter. Not counted: Tom (a name: capitalised, not sentence-initial), 3 and 1999 (numbers), XII (a Roman
|
||||||
|
// numeral). 16 counted words; known = the, cat, sit, on, mat, be → 6 in the first sentence + 4 in the second.
|
||||||
|
let text = "The cat sat on the mat. The cats were happy, and Tom saw 3 cats in 1999, in chapter XII.";
|
||||||
|
let p = Profile::build(&[text], &Rules::new(Lang::En));
|
||||||
|
assert_eq!(p.words(), 16);
|
||||||
|
let cov = p.coverage(&known(&["the", "cat", "sit", "on", "mat", "be"]));
|
||||||
|
assert!((cov - 10.0 / 16.0).abs() < 1e-12, "{cov}");
|
||||||
|
assert!(!p.total().contains_key("tom"));
|
||||||
|
assert!(!p.total().keys().any(|k| k.chars().any(|c| c.is_ascii_digit()) || *k == "xii"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn any_inflected_form_of_a_known_lemma_is_known() {
|
||||||
|
let p = Profile::build(&["Cats. The cat and the cats; a cat's tail."], &Rules::new(Lang::En));
|
||||||
|
let cov = p.coverage(&known(&["cat", "the", "and", "a", "tail"]));
|
||||||
|
assert_eq!(cov, 1.0);
|
||||||
|
// Latin: amat, amabat, amauit all count as `amo`.
|
||||||
|
let p = Profile::build(&["Puella amat. Puella amabat. Puella amauit."], &Rules::new(Lang::La));
|
||||||
|
assert_eq!(p.total().get("amo"), Some(&3));
|
||||||
|
assert_eq!(p.coverage(&known(&["amo", "puella"])), 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn german_names_need_a_lexicon_to_be_told_from_nouns() {
|
||||||
|
// With headwords, a capitalised word they do not know (Hänsel) is a name; a known noun (Haus) counts.
|
||||||
|
let chain = Chain {
|
||||||
|
table: None,
|
||||||
|
headwords: Some(Headwords::new(Lang::De, ["Haus", "der", "sein", "und", "groß", "gehen"])),
|
||||||
|
rules: Rules::new(Lang::De),
|
||||||
|
};
|
||||||
|
let p = Profile::build(&["Das Haus ist groß, und Hänsel geht."], &chain);
|
||||||
|
let total = p.total();
|
||||||
|
assert!(total.contains_key("haus"));
|
||||||
|
assert!(!total.contains_key("hänsel"));
|
||||||
|
// Without a lexicon every capitalised German word is counted (a name cannot be told from a noun): stated in the docs.
|
||||||
|
let p = Profile::build(&["Das Haus ist groß, und Hänsel geht."], &Rules::new(Lang::De));
|
||||||
|
assert!(p.total().contains_key("hänsel"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn later_counts_and_the_warm_up() {
|
||||||
|
let chapters =
|
||||||
|
["Der Hund bellt. Der Hund schläft.", "Ein Hund und eine Katze. Die Katze schläft.", "Hunde und Katzen."];
|
||||||
|
// A table for the nouns, so the test is about counting, not about the German rules.
|
||||||
|
let table = Table::from_tsv(
|
||||||
|
Lang::De,
|
||||||
|
"Hund Hund
|
||||||
|
Hunde Hund
|
||||||
|
Katze Katze
|
||||||
|
Katzen Katze
|
||||||
|
",
|
||||||
|
TableLimits::default(),
|
||||||
|
)
|
||||||
|
.expect("table");
|
||||||
|
let chain = Chain { table: Some(table), headwords: None, rules: Rules::new(Lang::De) };
|
||||||
|
let p = Profile::build(&chapters, &chain);
|
||||||
|
// "comes up N more times" after chapter 0: Hund once in ch.1, Hunde (→ hund) once in ch.2.
|
||||||
|
assert_eq!(p.later("hund", 0), 2);
|
||||||
|
assert_eq!(p.later("hund", 2), 0);
|
||||||
|
// Warm-up for chapter 1: the most frequent unknown lemmas, ties by lemma.
|
||||||
|
let w = p.warmup(1, &known(&["und", "ein", "der"]), 5);
|
||||||
|
assert_eq!(w.first().map(|x| x.0.as_str()), Some("katze"));
|
||||||
|
assert_eq!(w.first().map(|x| x.1), Some(2));
|
||||||
|
assert!(w.len() <= 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_tapped_word_gives_its_lemma() {
|
||||||
|
let text = "Elizabeth was walking slowly.";
|
||||||
|
let rules = Rules::new(Lang::En);
|
||||||
|
// UTF-16 offset 15 is inside "walking".
|
||||||
|
let (tok, lemma) = lemma_at(text, 15, &rules).expect("a word");
|
||||||
|
assert_eq!(tok.text, "walking");
|
||||||
|
assert_eq!(lemma, "walk");
|
||||||
|
assert!(lemma_at(text, 2, &rules).is_some(), "sentence-initial capital is a word");
|
||||||
|
assert!(lemma_at("He met Darcy.", 8, &rules).is_none(), "a name is not glossed as unknown");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn levels_and_unlocking() {
|
||||||
|
assert_eq!(level::level(0, &level::LEVELS), (0, Some(500)));
|
||||||
|
assert_eq!(level::level(1_999, &level::LEVELS), (2, Some(1)));
|
||||||
|
assert_eq!(level::level(9_000, &level::LEVELS), (6, None));
|
||||||
|
assert!(level::unlocked(0.95, false));
|
||||||
|
assert!(!level::unlocked(0.949, false));
|
||||||
|
assert!(level::unlocked(0.91, true));
|
||||||
|
assert!(!level::unlocked(f64::NAN, true));
|
||||||
|
assert_eq!(level::percent(0.949), 94);
|
||||||
|
assert_eq!(level::percent(1.2), 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn concept_ids_follow_the_ludus_rule() {
|
||||||
|
use liber_lang::concept::concept_id;
|
||||||
|
let id = concept_id(Lang::De, "Haus");
|
||||||
|
assert!(id.starts_with("w-de-"));
|
||||||
|
assert_eq!(id.len(), 5 + 16);
|
||||||
|
assert!(id.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'));
|
||||||
|
// Folded first: every form of one lemma, one concept; Latin j/v folded.
|
||||||
|
assert_eq!(concept_id(Lang::De, "haus"), id);
|
||||||
|
assert_eq!(concept_id(Lang::La, "Iulius"), concept_id(Lang::La, "julius"));
|
||||||
|
assert_ne!(concept_id(Lang::En, "haus"), id);
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
Kapitel 1. Die alte Mühle
|
||||||
|
|
||||||
|
Am Rande des Dorfes stand eine alte Mühle. Niemand wusste genau, wann sie gebaut worden war. Die Leute sagten, sie sei älter als die Kirche.
|
||||||
|
|
||||||
|
Im Jahr 1847 kaufte ein junger Müller namens Anton die Mühle. Er kam aus Salzburg und hatte nur wenig Geld. Trotzdem war er voller Hoffnung.
|
||||||
|
|
||||||
|
Der erste Winter war hart. Der Bach fror zu, und das Rad stand still. Anton saß jeden Abend am Feuer und las in seinen Büchern.
|
||||||
|
|
||||||
|
Im Frühling kam das Wasser zurück.
|
||||||
|
|
||||||
|
Das Rad drehte sich wieder, und die Bauern brachten ihr Korn. Anton lachte zum ersten Mal seit Monaten.
|
||||||
|
|
||||||
|
Eines Tages kam ein Mädchen namens Clara ins Dorf. Sie suchte Arbeit und eine Unterkunft. Anton bot ihr ein Zimmer über der Stube an.
|
||||||
|
|
||||||
|
Clara arbeitete fleißig. Sie kannte sich mit Zahlen aus und führte bald die Bücher der Mühle. Nach zwei Jahren hatte Anton 300 Gulden gespart.
|
||||||
|
|
||||||
|
Der Pfarrer sah das nicht gern. Er fand, ein junger Mann und eine junge Frau sollten nicht unter einem Dach wohnen, solange sie nicht verheiratet waren.
|
||||||
|
|
||||||
|
Im Herbst 1850 heirateten Anton und Clara. Das ganze Dorf kam zum Fest, sogar der Pfarrer.
|
||||||
|
|
||||||
|
Viele Jahre später erzählten ihre Enkel noch von dieser Hochzeit. Die Mühle steht heute nicht mehr, aber ihr Name lebt im Dorf weiter.
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
Chapter 1. The Old Mill
|
||||||
|
|
||||||
|
At the edge of the village stood an old mill. Nobody knew exactly when it had been built. People said it was older than the church.
|
||||||
|
|
||||||
|
In the year 1847 a young miller named Anton bought the mill. He came from Salzburg and had only a little money. Even so, he was full of hope.
|
||||||
|
|
||||||
|
The first winter was hard. The brook froze over and the wheel stood still. Every evening Anton sat by the fire and read his books.
|
||||||
|
|
||||||
|
In spring the water came back. The wheel turned again, and the farmers brought their grain. Anton laughed for the first time in months.
|
||||||
|
|
||||||
|
One day a girl named Clara came to the village. She was looking for work and a place to stay. Anton offered her a room above the parlour.
|
||||||
|
|
||||||
|
Clara worked hard. She was good with numbers and soon kept the accounts of the mill. After two years Anton had saved 300 guilders.
|
||||||
|
|
||||||
|
In the autumn of 1850 Anton and Clara were married. The whole village came to the feast, even the priest.
|
||||||
|
|
||||||
|
Many years later their grandchildren still told stories about that wedding. The mill no longer stands today. But its name lives on in the village.
|
||||||
+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
|
||||||
|
+62
@@ -0,0 +1,62 @@
|
|||||||
|
# Inflected German forms and their lemmas, written for this repository (no outside data). form<TAB>lemma
|
||||||
|
# Nouns are capitalised as in running text; the rules use the capital to tell nouns from verbs and adjectives.
|
||||||
|
ging gehen
|
||||||
|
gegangen gehen
|
||||||
|
sagte sagen
|
||||||
|
gesagt sagen
|
||||||
|
machte machen
|
||||||
|
gemacht machen
|
||||||
|
spielten spielen
|
||||||
|
arbeitete arbeiten
|
||||||
|
wohnt wohnen
|
||||||
|
lernst lernen
|
||||||
|
kaufe kaufen
|
||||||
|
kauften kaufen
|
||||||
|
war sein
|
||||||
|
ist sein
|
||||||
|
hatte haben
|
||||||
|
wurde werden
|
||||||
|
konnte können
|
||||||
|
sah sehen
|
||||||
|
gegessen essen
|
||||||
|
geschrieben schreiben
|
||||||
|
fragte fragen
|
||||||
|
antwortete antworten
|
||||||
|
lachten lachen
|
||||||
|
Kinder Kind
|
||||||
|
Kindern Kind
|
||||||
|
Frauen Frau
|
||||||
|
Tage Tag
|
||||||
|
Tagen Tag
|
||||||
|
Hunde Hund
|
||||||
|
Hundes Hund
|
||||||
|
Bücher Buch
|
||||||
|
Häuser Haus
|
||||||
|
Mädchen Mädchen
|
||||||
|
Augen Auge
|
||||||
|
Straßen Straße
|
||||||
|
Wörter Wort
|
||||||
|
Freundes Freund
|
||||||
|
Freunde Freund
|
||||||
|
schönen schön
|
||||||
|
schöne schön
|
||||||
|
alten alt
|
||||||
|
kleines klein
|
||||||
|
großen groß
|
||||||
|
guten gut
|
||||||
|
besser gut
|
||||||
|
den der
|
||||||
|
dem der
|
||||||
|
einer ein
|
||||||
|
meinen mein
|
||||||
|
mich ich
|
||||||
|
uns wir
|
||||||
|
dachte denken
|
||||||
|
brachte bringen
|
||||||
|
fand finden
|
||||||
|
stand stehen
|
||||||
|
gefunden finden
|
||||||
|
Händen Hand
|
||||||
|
Mütter Mutter
|
||||||
|
Wasser Wasser
|
||||||
|
Nächte Nacht
|
||||||
|
+64
@@ -0,0 +1,64 @@
|
|||||||
|
# Inflected English forms and their lemmas, written for this repository (no outside data). form<TAB>lemma
|
||||||
|
went go
|
||||||
|
children child
|
||||||
|
running run
|
||||||
|
studies study
|
||||||
|
making make
|
||||||
|
walked walk
|
||||||
|
cats cat
|
||||||
|
boxes box
|
||||||
|
happiest happy
|
||||||
|
bigger big
|
||||||
|
was be
|
||||||
|
seen see
|
||||||
|
tried try
|
||||||
|
stopped stop
|
||||||
|
hoping hope
|
||||||
|
hopped hop
|
||||||
|
wolves wolf
|
||||||
|
taught teach
|
||||||
|
better good
|
||||||
|
dogs dog
|
||||||
|
flies fly
|
||||||
|
carried carry
|
||||||
|
watches watch
|
||||||
|
buses bus
|
||||||
|
women woman
|
||||||
|
thinking think
|
||||||
|
thought think
|
||||||
|
houses house
|
||||||
|
knives knife
|
||||||
|
played play
|
||||||
|
says say
|
||||||
|
has have
|
||||||
|
reading read
|
||||||
|
books book
|
||||||
|
loved love
|
||||||
|
used use
|
||||||
|
needed need
|
||||||
|
wanted want
|
||||||
|
asked ask
|
||||||
|
looked look
|
||||||
|
given give
|
||||||
|
sleeping sleep
|
||||||
|
swimming swim
|
||||||
|
writing write
|
||||||
|
coming come
|
||||||
|
having have
|
||||||
|
taking take
|
||||||
|
going go
|
||||||
|
doing do
|
||||||
|
eyes eye
|
||||||
|
ladies lady
|
||||||
|
cities city
|
||||||
|
churches church
|
||||||
|
dresses dress
|
||||||
|
heroes hero
|
||||||
|
quickest quick
|
||||||
|
largest large
|
||||||
|
smiled smile
|
||||||
|
arrived arrive
|
||||||
|
opened open
|
||||||
|
letters letter
|
||||||
|
answered answer
|
||||||
|
gentlemen gentleman
|
||||||
|
+59
@@ -0,0 +1,59 @@
|
|||||||
|
# Inflected Latin forms and their lemmas, written for this repository (no outside data). form<TAB>lemma
|
||||||
|
# Lemmas are folded as liber-lang folds them: lowercase, j → i, v → u.
|
||||||
|
amat amo
|
||||||
|
amabat amo
|
||||||
|
amauit amo
|
||||||
|
amare amo
|
||||||
|
laudant laudo
|
||||||
|
uocabant uoco
|
||||||
|
pugnauerunt pugno
|
||||||
|
portat porto
|
||||||
|
est sum
|
||||||
|
erat sum
|
||||||
|
fuit sum
|
||||||
|
sunt sum
|
||||||
|
potest possum
|
||||||
|
dixit dico
|
||||||
|
fecit facio
|
||||||
|
uenit uenio
|
||||||
|
uidit uideo
|
||||||
|
habet habeo
|
||||||
|
habebat habeo
|
||||||
|
regit rego
|
||||||
|
mittunt mitto
|
||||||
|
ducit duco
|
||||||
|
audit audio
|
||||||
|
puellae puella
|
||||||
|
puellam puella
|
||||||
|
puellarum puella
|
||||||
|
puellas puella
|
||||||
|
rosas rosa
|
||||||
|
aquam aqua
|
||||||
|
domini dominus
|
||||||
|
dominum dominus
|
||||||
|
dominorum dominus
|
||||||
|
dominos dominus
|
||||||
|
seruo seruus
|
||||||
|
amicis amicus
|
||||||
|
bellum bellum
|
||||||
|
belli bellum
|
||||||
|
bella bellum
|
||||||
|
regem rex
|
||||||
|
regis rex
|
||||||
|
militibus miles
|
||||||
|
urbem urbs
|
||||||
|
partes pars
|
||||||
|
gallia gallia
|
||||||
|
omnis omnis
|
||||||
|
omnia omnis
|
||||||
|
tres tres
|
||||||
|
quae qui
|
||||||
|
quorum qui
|
||||||
|
hanc hic
|
||||||
|
eius is
|
||||||
|
illum ille
|
||||||
|
mihi ego
|
||||||
|
nobis nos
|
||||||
|
magnum magnus
|
||||||
|
bonis bonus
|
||||||
|
longam longus
|
||||||
|
@@ -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());
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
//! Mandatory test 2: per language, a fixture of inflected forms maps to the expected lemmas at or above a stated
|
||||||
|
//! accuracy (recorded in the app repo's `docs/03_languages.md`). Rules only: the tables wait for Mark's data decision.
|
||||||
|
|
||||||
|
use liber_lang::lemma::{Chain, Headwords, Lemmatizer, Rules, Table, TableError, TableLimits};
|
||||||
|
use liber_lang::{Lang, fold};
|
||||||
|
|
||||||
|
fn fixture(lang: Lang) -> Vec<(String, String)> {
|
||||||
|
let text = match lang {
|
||||||
|
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'))
|
||||||
|
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||||
|
.map(|l| {
|
||||||
|
let (f, le) = l.split_once('\t').expect("form<TAB>lemma");
|
||||||
|
(f.to_owned(), le.to_owned())
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn accuracy(lang: Lang, lem: &dyn Lemmatizer) -> (usize, usize, Vec<String>) {
|
||||||
|
let cases = fixture(lang);
|
||||||
|
let mut wrong = Vec::new();
|
||||||
|
let ok = cases
|
||||||
|
.iter()
|
||||||
|
.filter(|(form, want)| {
|
||||||
|
let got = lem.lemma(form);
|
||||||
|
let hit = got.as_deref() == Some(fold(want, lang).as_str());
|
||||||
|
if !hit {
|
||||||
|
wrong.push(format!("{form} → {got:?} (want {want})"));
|
||||||
|
}
|
||||||
|
hit
|
||||||
|
})
|
||||||
|
.count();
|
||||||
|
(ok, cases.len(), wrong)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Floors: the measured rules-only accuracy, rounded down to the next 5%. A change that lowers one fails here.
|
||||||
|
const FLOOR: [(Lang, f64); 3] = [(Lang::En, 0.85), (Lang::De, 0.75), (Lang::La, 0.75)];
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rules_reach_the_stated_accuracy() {
|
||||||
|
for (lang, floor) in FLOOR {
|
||||||
|
let (ok, all, wrong) = accuracy(lang, &Rules::new(lang));
|
||||||
|
let acc = ok as f64 / all as f64;
|
||||||
|
println!("{lang:?}: {ok}/{all} = {:.1}% misses: {}", acc * 100.0, wrong.join("; "));
|
||||||
|
assert!(acc >= floor, "{lang:?} rules: {:.1}% < {:.0}%", acc * 100.0, floor * 100.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn headwords_choose_among_the_rules_candidates() {
|
||||||
|
// German: `schönen` is a verb reading first (schönen → schönen? no: schön+en) unless the headwords say otherwise.
|
||||||
|
let rules = Rules::new(Lang::De);
|
||||||
|
assert!(rules.candidates("schönen").contains(&"schön".to_owned()));
|
||||||
|
let chain = Chain { table: None, headwords: Some(Headwords::new(Lang::De, ["schön", "Haus"])), rules };
|
||||||
|
assert_eq!(chain.lemma("schönen").as_deref(), Some("schön"));
|
||||||
|
// Latin: `regem` is third declension; with `rex` absent the rules cannot know, with a table they do.
|
||||||
|
let table = Table::from_tsv(Lang::La, "regem\trex\nregis\trex\n", TableLimits::default()).expect("table");
|
||||||
|
let chain = Chain { table: Some(table), headwords: None, rules: Rules::new(Lang::La) };
|
||||||
|
assert_eq!(chain.lemma("Regem").as_deref(), Some("rex"));
|
||||||
|
assert!(chain.knows("regis"));
|
||||||
|
assert!(!chain.knows("amat"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_table_is_hostile_input() {
|
||||||
|
let limits = TableLimits { max_bytes: 100, max_entries: 2, max_word: 8 };
|
||||||
|
assert_eq!(Table::from_tsv(Lang::En, &"a\tb\n".repeat(40), limits).err(), Some(TableError::TooLarge));
|
||||||
|
assert_eq!(Table::from_tsv(Lang::En, "a\tb\nc\td\ne\tf\n", limits).err(), Some(TableError::TooManyEntries));
|
||||||
|
// Malformed lines, comments, over-long words and empty fields are skipped, not fatal.
|
||||||
|
let t = Table::from_tsv(
|
||||||
|
Lang::En,
|
||||||
|
"# c\nnope\n\tx\nverylongword\tx\nwent\tgo\r\n",
|
||||||
|
TableLimits { max_word: 8, ..limits },
|
||||||
|
)
|
||||||
|
.expect("ok");
|
||||||
|
assert_eq!(t.len(), 1);
|
||||||
|
assert_eq!(t.lemma("Went").as_deref(), Some("go"));
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
//! Events: what a device did, with a hybrid logical clock. The order of events is total and the same everywhere.
|
//! Events: what a device did, with a hybrid logical clock. The order of events is total and the same everywhere.
|
||||||
|
|
||||||
use crate::library::{BookFile, BookInfo, Colour, Field, GoalKind, Mark, Outcome, Person};
|
use crate::library::{BookFile, BookInfo, Colour, Field, GoalKind, HabitGoal, Mark, Outcome, Person, WordMark};
|
||||||
|
use crate::together::RecordingSource;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
@@ -151,10 +152,107 @@ pub enum Op {
|
|||||||
active_ms: u64,
|
active_ms: u64,
|
||||||
pages: u32,
|
pages: u32,
|
||||||
date: String,
|
date: String,
|
||||||
|
/// The device's UTC offset at `start`, in minutes (Day 2); `None` for older sessions.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
offset_min: Option<i32>,
|
||||||
},
|
},
|
||||||
Goal {
|
Goal {
|
||||||
year: i32,
|
year: i32,
|
||||||
kind: GoalKind,
|
kind: GoalKind,
|
||||||
target: u32,
|
target: u32,
|
||||||
},
|
},
|
||||||
|
/// The daily habit (Day 2): what counts as a day read, and when a day rolls over. Follows the person.
|
||||||
|
HabitGoal {
|
||||||
|
goal: HabitGoal,
|
||||||
|
},
|
||||||
|
/// A medal was shown (Day 2). Medals themselves are computed from the log, never stored.
|
||||||
|
MedalSeen {
|
||||||
|
medal: String,
|
||||||
|
},
|
||||||
|
/// Day 3: the reader marked a word (a folded lemma, see `liber_lang::fold`). Last writer wins.
|
||||||
|
Word {
|
||||||
|
lang: String,
|
||||||
|
lemma: String,
|
||||||
|
mark: WordMark,
|
||||||
|
},
|
||||||
|
/// Day 3: the band of a frequency list the reader knows.
|
||||||
|
KnownBand {
|
||||||
|
lang: String,
|
||||||
|
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,
|
||||||
|
sha256: String,
|
||||||
|
language: Option<String>,
|
||||||
|
},
|
||||||
|
/// Day 5: someone the reader reads with: `person` is their Tabellarius group (hex), `name` how Liber shows them.
|
||||||
|
/// Adding again renames.
|
||||||
|
PersonAdd {
|
||||||
|
person: String,
|
||||||
|
name: String,
|
||||||
|
},
|
||||||
|
PersonRemove {
|
||||||
|
person: String,
|
||||||
|
},
|
||||||
|
/// Day 5: hide (or show again) a person's notes, in one book or everywhere (`book: None`).
|
||||||
|
Hide {
|
||||||
|
person: String,
|
||||||
|
book: Option<String>,
|
||||||
|
hidden: bool,
|
||||||
|
},
|
||||||
|
/// Day 5: a highlight was shared with a person (the note itself travels in their group).
|
||||||
|
Share {
|
||||||
|
highlight: String,
|
||||||
|
person: String,
|
||||||
|
},
|
||||||
|
Unshare {
|
||||||
|
highlight: String,
|
||||||
|
person: String,
|
||||||
|
},
|
||||||
|
/// Day 5: a buddy read of a book with people.
|
||||||
|
BuddyRead {
|
||||||
|
id: String,
|
||||||
|
book: String,
|
||||||
|
people: Vec<String>,
|
||||||
|
},
|
||||||
|
/// Day 5: a link was made asking someone (`person`: the name the parent typed) to record a chapter. `key` opens
|
||||||
|
/// what is in the slot; it lives only here (the reader's own, end-to-end encrypted log) and in the link.
|
||||||
|
RecordAsk {
|
||||||
|
slot: String,
|
||||||
|
book: String,
|
||||||
|
chapter: u32,
|
||||||
|
person: String,
|
||||||
|
key: String,
|
||||||
|
created: u64,
|
||||||
|
},
|
||||||
|
/// Day 5: the link was cancelled (or the recording arrived and the parent closed it).
|
||||||
|
RecordAskClose {
|
||||||
|
slot: String,
|
||||||
|
},
|
||||||
|
/// Day 5: a recorded chapter, waiting for the parent's approval.
|
||||||
|
RecordingAdd {
|
||||||
|
id: String,
|
||||||
|
book: String,
|
||||||
|
chapter: u32,
|
||||||
|
by: String,
|
||||||
|
source: RecordingSource,
|
||||||
|
mime: String,
|
||||||
|
duration_ms: u64,
|
||||||
|
created: u64,
|
||||||
|
},
|
||||||
|
RecordingApprove {
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// Day 5: deleted by the parent, or found deleted by the person who recorded it. Final.
|
||||||
|
RecordingRemove {
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -129,6 +129,15 @@ pub fn ops_from(lib: &Library) -> Vec<Op> {
|
|||||||
if b.to_read {
|
if b.to_read {
|
||||||
ops.push(set(Field::ToRead, json!(true)));
|
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)));
|
||||||
|
}
|
||||||
|
for (sha, lang) in &b.editions {
|
||||||
|
ops.push(Op::Edition { book: id.clone(), sha256: sha.clone(), language: Some(lang.clone()) });
|
||||||
|
}
|
||||||
let pos = |p: &crate::library::Position| Op::Position {
|
let pos = |p: &crate::library::Position| Op::Position {
|
||||||
book: id.clone(),
|
book: id.clone(),
|
||||||
cfi: p.cfi.clone(),
|
cfi: p.cfi.clone(),
|
||||||
@@ -177,11 +186,66 @@ pub fn ops_from(lib: &Library) -> Vec<Op> {
|
|||||||
active_ms: s.active_ms,
|
active_ms: s.active_ms,
|
||||||
pages: s.pages,
|
pages: s.pages,
|
||||||
date: s.date.clone(),
|
date: s.date.clone(),
|
||||||
|
offset_min: s.offset_min,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
for g in lib.goals.values() {
|
for g in lib.goals.values() {
|
||||||
ops.push(Op::Goal { year: g.year, kind: g.kind, target: g.target });
|
ops.push(Op::Goal { year: g.year, kind: g.kind, target: g.target });
|
||||||
}
|
}
|
||||||
|
if let Some(h) = lib.habit {
|
||||||
|
ops.push(Op::HabitGoal { goal: h });
|
||||||
|
}
|
||||||
|
for m in &lib.medals_seen {
|
||||||
|
ops.push(Op::MedalSeen { medal: m.clone() });
|
||||||
|
}
|
||||||
|
for (lang, words) in &lib.words {
|
||||||
|
for (lemma, mark) in words {
|
||||||
|
ops.push(Op::Word { lang: lang.clone(), lemma: lemma.clone(), mark: *mark });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (lang, band) in &lib.bands {
|
||||||
|
ops.push(Op::KnownBand { lang: lang.clone(), list: band.list.clone(), upto: band.upto });
|
||||||
|
}
|
||||||
|
// Day 5: people, what was shared and hidden, buddy reads, links and recordings (deleted ones are simply absent).
|
||||||
|
for (person, p) in &lib.people {
|
||||||
|
ops.push(Op::PersonAdd { person: person.clone(), name: p.name.clone() });
|
||||||
|
}
|
||||||
|
for (person, book) in &lib.hides {
|
||||||
|
ops.push(Op::Hide { person: person.clone(), book: book.clone(), hidden: true });
|
||||||
|
}
|
||||||
|
for (highlight, people) in &lib.shares {
|
||||||
|
for person in people {
|
||||||
|
ops.push(Op::Share { highlight: highlight.clone(), person: person.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for r in lib.buddy_reads.values() {
|
||||||
|
ops.push(Op::BuddyRead { id: r.id.clone(), book: r.book.clone(), people: r.people.clone() });
|
||||||
|
}
|
||||||
|
for a in lib.asks.values() {
|
||||||
|
ops.push(Op::RecordAsk {
|
||||||
|
slot: a.slot.clone(),
|
||||||
|
book: a.book.clone(),
|
||||||
|
chapter: a.chapter,
|
||||||
|
person: a.person.clone(),
|
||||||
|
key: a.key.clone(),
|
||||||
|
created: a.created,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for r in lib.recordings.values() {
|
||||||
|
ops.push(Op::RecordingAdd {
|
||||||
|
id: r.id.clone(),
|
||||||
|
book: r.book.clone(),
|
||||||
|
chapter: r.chapter,
|
||||||
|
by: r.by.clone(),
|
||||||
|
source: r.source.clone(),
|
||||||
|
mime: r.mime.clone(),
|
||||||
|
duration_ms: r.duration_ms,
|
||||||
|
created: r.created,
|
||||||
|
});
|
||||||
|
if r.approved {
|
||||||
|
ops.push(Op::RecordingApprove { id: r.id.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
ops
|
ops
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ pub mod export;
|
|||||||
pub mod import;
|
pub mod import;
|
||||||
pub mod library;
|
pub mod library;
|
||||||
pub mod stats;
|
pub mod stats;
|
||||||
|
pub mod together;
|
||||||
|
|
||||||
pub use event::{Clock, Event, Hlc, Op};
|
pub use event::{Clock, Event, Hlc, Op};
|
||||||
pub use library::{Book, Highlight, Library, Loan, Possession, Read, ReadStatus, Text};
|
pub use library::{Book, Highlight, Library, Loan, Possession, Read, ReadStatus, Text};
|
||||||
|
|||||||
@@ -134,6 +134,8 @@ pub enum Field {
|
|||||||
Tags,
|
Tags,
|
||||||
ToRead,
|
ToRead,
|
||||||
Cover,
|
Cover,
|
||||||
|
/// Day 3: the reader has read this book in their own language (it opens at 90% coverage, not 95%).
|
||||||
|
Familiar,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Field {
|
impl Field {
|
||||||
@@ -158,6 +160,7 @@ impl Field {
|
|||||||
Field::Tags => "tags",
|
Field::Tags => "tags",
|
||||||
Field::ToRead => "to_read",
|
Field::ToRead => "to_read",
|
||||||
Field::Cover => "cover",
|
Field::Cover => "cover",
|
||||||
|
Field::Familiar => "familiar",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -209,6 +212,15 @@ pub struct Book {
|
|||||||
pub position: Option<Position>,
|
pub position: Option<Position>,
|
||||||
/// The most recent position, when it is behind the furthest: "Jump back to page X?".
|
/// The most recent position, when it is behind the furthest: "Jump back to page X?".
|
||||||
pub last_position: Option<Position>,
|
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,
|
||||||
|
/// Day 3: the language of each file (sha256 → BCP 47 tag) when it differs from the book's: a second edition.
|
||||||
|
#[serde(default)]
|
||||||
|
pub editions: BTreeMap<String, String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Book {
|
impl Book {
|
||||||
@@ -231,6 +243,9 @@ impl Book {
|
|||||||
cover: None,
|
cover: None,
|
||||||
position: None,
|
position: None,
|
||||||
last_position: None,
|
last_position: None,
|
||||||
|
familiar: false,
|
||||||
|
editions: BTreeMap::new(),
|
||||||
|
audio_position: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -278,8 +293,61 @@ pub struct Session {
|
|||||||
pub end: u64,
|
pub end: u64,
|
||||||
pub active_ms: u64,
|
pub active_ms: u64,
|
||||||
pub pages: u32,
|
pub pages: u32,
|
||||||
/// The local day it counts for (`YYYY-MM-DD`, from the device).
|
/// The local day it counts for (`YYYY-MM-DD`): from `liber_habit::local_day` since Day 2.
|
||||||
pub date: String,
|
pub date: String,
|
||||||
|
/// The device's UTC offset at `start`, minutes east of UTC (Day 2).
|
||||||
|
#[serde(default)]
|
||||||
|
pub offset_min: Option<i32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum DailyKind {
|
||||||
|
Pages,
|
||||||
|
Minutes,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What counts as a day read (Day 2). Default: one page, days rolling over at 03:00.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct HabitGoal {
|
||||||
|
pub kind: DailyKind,
|
||||||
|
pub amount: u32,
|
||||||
|
pub rollover_hour: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for HabitGoal {
|
||||||
|
fn default() -> Self {
|
||||||
|
HabitGoal { kind: DailyKind::Pages, amount: 1, rollover_hour: 3 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Day 3: how the reader knows a word (a lemma). Words not in the map are unknown.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum WordMark {
|
||||||
|
/// Looked up and being practised.
|
||||||
|
Learning,
|
||||||
|
Known,
|
||||||
|
/// Back to unknown (removes the word).
|
||||||
|
Unknown,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Day 3: the band of a frequency list the reader says they know ("the 2,000 most common words").
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Band {
|
||||||
|
/// The list's id (its file name, as decided in docs/03_languages.md).
|
||||||
|
pub list: String,
|
||||||
|
/// The first `upto` lemmas of the list count as known.
|
||||||
|
pub upto: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Caps for word events from sync (hostile input).
|
||||||
|
pub const MAX_LEMMA: usize = 64;
|
||||||
|
pub const MAX_WORDS: usize = 200_000;
|
||||||
|
|
||||||
|
fn lang_ok(l: &str) -> bool {
|
||||||
|
!l.is_empty() && l.len() <= 8 && l.bytes().all(|b| b.is_ascii_lowercase())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
@@ -289,6 +357,42 @@ pub struct Goal {
|
|||||||
pub target: u32,
|
pub target: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Day 5: someone the reader reads with.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct PersonEntry {
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct BuddyRead {
|
||||||
|
pub id: String,
|
||||||
|
pub book: String,
|
||||||
|
pub people: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct RecordAsk {
|
||||||
|
pub slot: String,
|
||||||
|
pub book: String,
|
||||||
|
pub chapter: u32,
|
||||||
|
pub person: String,
|
||||||
|
pub key: String,
|
||||||
|
pub created: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Recording {
|
||||||
|
pub id: String,
|
||||||
|
pub book: String,
|
||||||
|
pub chapter: u32,
|
||||||
|
pub by: String,
|
||||||
|
pub source: crate::together::RecordingSource,
|
||||||
|
pub mime: String,
|
||||||
|
pub duration_ms: u64,
|
||||||
|
pub created: u64,
|
||||||
|
pub approved: bool,
|
||||||
|
}
|
||||||
|
|
||||||
/// The whole library. Equal events in any arrival order give an equal library. Equality compares the content
|
/// The whole library. Equal events in any arrival order give an equal library. Equality compares the content
|
||||||
/// (books, highlights, sessions, goals), not the bookkeeping of how it was built.
|
/// (books, highlights, sessions, goals), not the bookkeeping of how it was built.
|
||||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||||
@@ -297,6 +401,39 @@ pub struct Library {
|
|||||||
pub highlights: BTreeMap<String, Highlight>,
|
pub highlights: BTreeMap<String, Highlight>,
|
||||||
pub sessions: BTreeMap<String, Session>,
|
pub sessions: BTreeMap<String, Session>,
|
||||||
pub goals: BTreeMap<i32, Goal>,
|
pub goals: BTreeMap<i32, Goal>,
|
||||||
|
/// The daily habit; `None` means the default (one page, 03:00).
|
||||||
|
#[serde(default)]
|
||||||
|
pub habit: Option<HabitGoal>,
|
||||||
|
/// Medals already shown (the medals are computed, see `liber_habit::medals`).
|
||||||
|
#[serde(default)]
|
||||||
|
pub medals_seen: BTreeSet<String>,
|
||||||
|
/// Day 3: language (`en`, `de`, `la`) → lemma → known or learning.
|
||||||
|
#[serde(default)]
|
||||||
|
pub words: BTreeMap<String, BTreeMap<String, WordMark>>,
|
||||||
|
/// Day 3: language → the frequency band marked as known.
|
||||||
|
#[serde(default)]
|
||||||
|
pub bands: BTreeMap<String, Band>,
|
||||||
|
/// Day 5: the people the reader reads with, by group.
|
||||||
|
#[serde(default)]
|
||||||
|
pub people: BTreeMap<String, PersonEntry>,
|
||||||
|
/// Day 5: (person, book) pairs whose notes are hidden; `None` for every book.
|
||||||
|
#[serde(default)]
|
||||||
|
pub hides: BTreeSet<(String, Option<String>)>,
|
||||||
|
/// Day 5: highlight -> the people it was shared with.
|
||||||
|
#[serde(default)]
|
||||||
|
pub shares: BTreeMap<String, BTreeSet<String>>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub buddy_reads: BTreeMap<String, BuddyRead>,
|
||||||
|
/// Day 5: open "Ask someone to record" links, by slot.
|
||||||
|
#[serde(default)]
|
||||||
|
pub asks: BTreeMap<String, RecordAsk>,
|
||||||
|
/// Day 5: recorded chapters, approved or waiting.
|
||||||
|
#[serde(default)]
|
||||||
|
pub recordings: BTreeMap<String, Recording>,
|
||||||
|
#[serde(skip)]
|
||||||
|
removed_recordings: BTreeSet<String>,
|
||||||
|
#[serde(skip)]
|
||||||
|
approved_early: BTreeSet<String>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
aliases: BTreeMap<String, String>,
|
aliases: BTreeMap<String, String>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
@@ -313,7 +450,20 @@ pub struct Library {
|
|||||||
|
|
||||||
impl PartialEq for Library {
|
impl PartialEq for Library {
|
||||||
fn eq(&self, o: &Library) -> bool {
|
fn eq(&self, o: &Library) -> bool {
|
||||||
self.books == o.books && self.highlights == o.highlights && self.sessions == o.sessions && self.goals == o.goals
|
self.books == o.books
|
||||||
|
&& self.highlights == o.highlights
|
||||||
|
&& self.sessions == o.sessions
|
||||||
|
&& self.goals == o.goals
|
||||||
|
&& self.habit == o.habit
|
||||||
|
&& self.medals_seen == o.medals_seen
|
||||||
|
&& self.words == o.words
|
||||||
|
&& self.bands == o.bands
|
||||||
|
&& self.people == o.people
|
||||||
|
&& self.hides == o.hides
|
||||||
|
&& self.shares == o.shares
|
||||||
|
&& self.buddy_reads == o.buddy_reads
|
||||||
|
&& self.asks == o.asks
|
||||||
|
&& self.recordings == o.recordings
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -365,6 +515,28 @@ impl Library {
|
|||||||
self.versions.get(&(format!("hl:{id}"), "note")).map(String::as_str)
|
self.versions.get(&(format!("hl:{id}"), "note")).map(String::as_str)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Day 5: whether a person's notes are hidden in this book (or everywhere).
|
||||||
|
pub fn hidden(&self, person: &str, book: &str) -> bool {
|
||||||
|
let book = self.canonical(book);
|
||||||
|
self.hides.contains(&(person.to_owned(), None)) || self.hides.contains(&(person.to_owned(), Some(book)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Day 5: the approved recordings of a chapter: the only ones that may be played.
|
||||||
|
pub fn playable(&self, book: &str, chapter: u32) -> Vec<&Recording> {
|
||||||
|
let book = self.canonical(book);
|
||||||
|
self.recordings.values().filter(|r| r.approved && r.book == book && r.chapter == chapter).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Day 5: recordings waiting for the parent's approval.
|
||||||
|
pub fn pending(&self) -> Vec<&Recording> {
|
||||||
|
self.recordings.values().filter(|r| !r.approved).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Day 5: recordings deleted (their audio must go from every device).
|
||||||
|
pub fn removed_recordings(&self) -> &BTreeSet<String> {
|
||||||
|
&self.removed_recordings
|
||||||
|
}
|
||||||
|
|
||||||
/// An existing book with the same identity: ISBN-13, else text fingerprint.
|
/// An existing book with the same identity: ISBN-13, else text fingerprint.
|
||||||
pub fn find_identity(&self, isbn13: Option<&str>, fingerprint: Option<&str>) -> Option<&Book> {
|
pub fn find_identity(&self, isbn13: Option<&str>, fingerprint: Option<&str>) -> Option<&Book> {
|
||||||
if let Some(i) = isbn13
|
if let Some(i) = isbn13
|
||||||
@@ -497,6 +669,7 @@ impl Library {
|
|||||||
Field::Tags => set_of(value).map(|v| b.tags = v).is_some(),
|
Field::Tags => set_of(value).map(|v| b.tags = v).is_some(),
|
||||||
Field::ToRead => value.as_bool().map(|v| b.to_read = v).is_some(),
|
Field::ToRead => value.as_bool().map(|v| b.to_read = v).is_some(),
|
||||||
Field::Cover => serde_json::from_value(value.clone()).map(|v| b.cover = v).is_ok(),
|
Field::Cover => serde_json::from_value(value.clone()).map(|v| b.cover = v).is_ok(),
|
||||||
|
Field::Familiar => value.as_bool().map(|v| b.familiar = v).is_some(),
|
||||||
};
|
};
|
||||||
if ok {
|
if ok {
|
||||||
self.versions.insert(key, e.id.clone());
|
self.versions.insert(key, e.id.clone());
|
||||||
@@ -638,7 +811,7 @@ impl Library {
|
|||||||
self.highlights.remove(id);
|
self.highlights.remove(id);
|
||||||
self.removed_highlights.insert(id.clone());
|
self.removed_highlights.insert(id.clone());
|
||||||
}
|
}
|
||||||
Op::Session { id, book, start, end, active_ms, pages, date } => {
|
Op::Session { id, book, start, end, active_ms, pages, date, offset_min } => {
|
||||||
let c = self.canonical(book);
|
let c = self.canonical(book);
|
||||||
if self.books.contains_key(&c) && end >= start {
|
if self.books.contains_key(&c) && end >= start {
|
||||||
self.sessions.entry(id.clone()).or_insert(Session {
|
self.sessions.entry(id.clone()).or_insert(Session {
|
||||||
@@ -649,12 +822,168 @@ impl Library {
|
|||||||
active_ms: (*active_ms).min(end - start),
|
active_ms: (*active_ms).min(end - start),
|
||||||
pages: *pages,
|
pages: *pages,
|
||||||
date: date.clone(),
|
date: date.clone(),
|
||||||
|
offset_min: offset_min.filter(|o| (-14 * 60..=14 * 60).contains(o)),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Op::Goal { year, kind, target } => {
|
Op::Goal { year, kind, target } => {
|
||||||
self.goals.insert(*year, Goal { year: *year, kind: *kind, target: *target });
|
self.goals.insert(*year, Goal { year: *year, kind: *kind, target: *target });
|
||||||
}
|
}
|
||||||
|
Op::HabitGoal { goal } => {
|
||||||
|
if goal.amount >= 1 && goal.amount <= 10_000 && goal.rollover_hour <= 12 {
|
||||||
|
self.habit = Some(*goal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::MedalSeen { medal } => {
|
||||||
|
if medal.len() <= 64 {
|
||||||
|
self.medals_seen.insert(medal.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::Word { lang, lemma, mark } => {
|
||||||
|
if !lang_ok(lang) || lemma.is_empty() || lemma.chars().count() > MAX_LEMMA {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let words = self.words.entry(lang.clone()).or_default();
|
||||||
|
match mark {
|
||||||
|
WordMark::Unknown => {
|
||||||
|
words.remove(lemma);
|
||||||
|
}
|
||||||
|
m if words.len() < MAX_WORDS || words.contains_key(lemma) => {
|
||||||
|
words.insert(lemma.clone(), *m);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
if words.is_empty() {
|
||||||
|
self.words.remove(lang);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::KnownBand { lang, list, upto } => {
|
||||||
|
if lang_ok(lang) && !list.is_empty() && list.len() <= 64 {
|
||||||
|
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::PersonAdd { person, name } => {
|
||||||
|
if crate::together::id_ok(person) && crate::together::name_ok(name) {
|
||||||
|
self.people.insert(person.clone(), PersonEntry { name: name.trim().to_owned() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::PersonRemove { person } => {
|
||||||
|
self.people.remove(person);
|
||||||
|
}
|
||||||
|
Op::Hide { person, book, hidden } => {
|
||||||
|
let key = (person.clone(), book.as_deref().map(|b| self.canonical(b)));
|
||||||
|
if *hidden {
|
||||||
|
self.hides.insert(key);
|
||||||
|
} else {
|
||||||
|
self.hides.remove(&key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::Share { highlight, person } => {
|
||||||
|
self.shares.entry(highlight.clone()).or_default().insert(person.clone());
|
||||||
|
}
|
||||||
|
Op::Unshare { highlight, person } => {
|
||||||
|
if let Some(s) = self.shares.get_mut(highlight) {
|
||||||
|
s.remove(person);
|
||||||
|
if s.is_empty() {
|
||||||
|
self.shares.remove(highlight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::BuddyRead { id, book, people } => {
|
||||||
|
let book = self.canonical(book);
|
||||||
|
if crate::together::id_ok(id) && self.books.contains_key(&book) && people.len() <= 16 {
|
||||||
|
self.buddy_reads.insert(id.clone(), BuddyRead { id: id.clone(), book, people: people.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::RecordAsk { slot, book, chapter, person, key, created } => {
|
||||||
|
let book = self.canonical(book);
|
||||||
|
if crate::together::slot_ok(slot)
|
||||||
|
&& crate::together::key_ok(key)
|
||||||
|
&& crate::together::name_ok(person)
|
||||||
|
&& self.books.contains_key(&book)
|
||||||
|
{
|
||||||
|
let a = RecordAsk {
|
||||||
|
slot: slot.clone(),
|
||||||
|
book,
|
||||||
|
chapter: *chapter,
|
||||||
|
person: person.trim().to_owned(),
|
||||||
|
key: key.clone(),
|
||||||
|
created: *created,
|
||||||
|
};
|
||||||
|
self.asks.insert(slot.clone(), a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::RecordAskClose { slot } => {
|
||||||
|
self.asks.remove(slot);
|
||||||
|
}
|
||||||
|
Op::RecordingAdd { id, book, chapter, by, source, mime, duration_ms, created } => {
|
||||||
|
let book = self.canonical(book);
|
||||||
|
if self.removed_recordings.contains(id)
|
||||||
|
|| self.recordings.contains_key(id)
|
||||||
|
|| !crate::together::id_ok(id)
|
||||||
|
|| !crate::together::name_ok(by)
|
||||||
|
|| !crate::together::mime_ok(mime)
|
||||||
|
|| !source.ok()
|
||||||
|
|| !self.books.contains_key(&book)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let approved = self.approved_early.remove(id);
|
||||||
|
self.recordings.insert(
|
||||||
|
id.clone(),
|
||||||
|
Recording {
|
||||||
|
id: id.clone(),
|
||||||
|
book,
|
||||||
|
chapter: *chapter,
|
||||||
|
by: by.trim().to_owned(),
|
||||||
|
source: source.clone(),
|
||||||
|
mime: mime.clone(),
|
||||||
|
duration_ms: *duration_ms,
|
||||||
|
created: *created,
|
||||||
|
approved,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Op::RecordingApprove { id } => {
|
||||||
|
if self.removed_recordings.contains(id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match self.recordings.get_mut(id) {
|
||||||
|
Some(r) => r.approved = true,
|
||||||
|
None => {
|
||||||
|
self.approved_early.insert(id.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::RecordingRemove { id } => {
|
||||||
|
self.recordings.remove(id);
|
||||||
|
self.approved_early.remove(id);
|
||||||
|
self.removed_recordings.insert(id.clone());
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
&& ok
|
||||||
|
{
|
||||||
|
match language {
|
||||||
|
Some(l) if !l.is_empty() && l.len() <= 35 => {
|
||||||
|
b.editions.insert(sha256.to_ascii_lowercase(), l.clone());
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
b.editions.remove(&sha256.to_ascii_lowercase());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,342 @@
|
|||||||
|
//! Day 5 (the app's `docs/05_together.md`): reading together. What one person's Liber sends another (strictly
|
||||||
|
//! parsed: the other side is as hostile as any outside file), where a shared note lands in the reader's copy, and the
|
||||||
|
//! spoiler guard. Recordings and the reader's own decisions are ops in the library (`Op::RecordingAdd` …).
|
||||||
|
|
||||||
|
use crate::library::{Book, BookInfo, Colour, Mark, ReadStatus};
|
||||||
|
use liber_format::Document;
|
||||||
|
use liber_format::position::{Anchor, Resolved, resolve};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// The most a body from another person may be, in bytes (Tabellarius allows 300 KiB a message).
|
||||||
|
pub const MAX_BODY: usize = 64 * 1024;
|
||||||
|
/// A shared note's text, in characters.
|
||||||
|
pub const MAX_NOTE: usize = 10_000;
|
||||||
|
/// The quoted text a note is anchored to, in characters.
|
||||||
|
pub const MAX_QUOTE: usize = 2_000;
|
||||||
|
/// A thread message, in characters.
|
||||||
|
pub const MAX_MESSAGE: usize = 4_000;
|
||||||
|
/// A name a person chose, in characters.
|
||||||
|
pub const MAX_NAME: usize = 80;
|
||||||
|
pub const MAX_TITLE: usize = 300;
|
||||||
|
|
||||||
|
/// Which book a shared item is about: enough to find the reader's own copy, nothing about the sender's files.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct BookRef {
|
||||||
|
pub isbn13: Option<String>,
|
||||||
|
pub fingerprint: Option<String>,
|
||||||
|
pub title: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BookRef {
|
||||||
|
pub fn of(info: &BookInfo) -> BookRef {
|
||||||
|
BookRef { isbn13: info.isbn13.clone(), fingerprint: info.fingerprint.clone(), title: info.title.clone() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same book (not just the same title): ISBN-13 or text fingerprint equal.
|
||||||
|
pub fn is(&self, info: &BookInfo) -> bool {
|
||||||
|
let eq =
|
||||||
|
|a: &Option<String>, b: &Option<String>| matches!((a, b), (Some(x), Some(y)) if !x.is_empty() && x == y);
|
||||||
|
eq(&self.isbn13, &info.isbn13) || eq(&self.fingerprint, &info.fingerprint)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ok(&self) -> bool {
|
||||||
|
self.isbn13.as_deref().is_none_or(|i| i.len() == 13 && i.bytes().all(|b| b.is_ascii_digit()))
|
||||||
|
&& self.fingerprint.as_deref().is_none_or(|f| !f.is_empty() && f.len() <= 128 && f.is_ascii())
|
||||||
|
&& chars_in(&self.title, 1, MAX_TITLE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where in the sender's copy an item belongs: the chapter and the progress through the book (0–1).
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Spot {
|
||||||
|
pub chapter: u32,
|
||||||
|
pub progress: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Spot {
|
||||||
|
fn ok(&self) -> bool {
|
||||||
|
self.chapter <= 100_000 && self.progress.is_finite() && (0.0..=1.0).contains(&self.progress)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A highlight or note shared with a person.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct SharedNote {
|
||||||
|
/// The sender's highlight id.
|
||||||
|
pub id: String,
|
||||||
|
pub book: BookRef,
|
||||||
|
pub anchor: Anchor,
|
||||||
|
pub spot: Spot,
|
||||||
|
pub kind: Mark,
|
||||||
|
pub colour: Colour,
|
||||||
|
pub note: String,
|
||||||
|
pub created: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SharedNote {
|
||||||
|
fn ok(&self) -> bool {
|
||||||
|
let a = &self.anchor;
|
||||||
|
id_ok(&self.id)
|
||||||
|
&& self.book.ok()
|
||||||
|
&& self.spot.ok()
|
||||||
|
&& a.chapter <= 100_000
|
||||||
|
&& a.start.len() <= 1024
|
||||||
|
&& a.end.len() <= 1024
|
||||||
|
&& a.chapter_hash.len() <= 128
|
||||||
|
&& chars_in(&a.quote.exact, 1, MAX_QUOTE)
|
||||||
|
&& a.quote.prefix.chars().count() <= 200
|
||||||
|
&& a.quote.suffix.chars().count() <= 200
|
||||||
|
&& self.note.chars().count() <= MAX_NOTE
|
||||||
|
&& self.kind != Mark::Bookmark
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything that travels in a person's group (Tabellarius app events). Each kind has its own body.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum Wire {
|
||||||
|
/// `liber.hello`: the name the person chose.
|
||||||
|
Hello { name: String },
|
||||||
|
/// `liber.note`
|
||||||
|
Note(Box<SharedNote>),
|
||||||
|
/// `liber.note.withdraw`: the sender took a note back.
|
||||||
|
Withdraw { id: String },
|
||||||
|
/// `liber.buddy`: an invitation to read a book together.
|
||||||
|
Buddy { read: String, book: BookRef },
|
||||||
|
/// `liber.progress`: how far the person is in a buddy read.
|
||||||
|
Progress { read: String, spot: Spot },
|
||||||
|
/// `liber.thread`: a message in a chapter's thread.
|
||||||
|
Thread { read: String, id: String, spot: Spot, text: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const HELLO: &str = "liber.hello";
|
||||||
|
pub const NOTE: &str = "liber.note";
|
||||||
|
pub const WITHDRAW: &str = "liber.note.withdraw";
|
||||||
|
pub const BUDDY: &str = "liber.buddy";
|
||||||
|
pub const PROGRESS: &str = "liber.progress";
|
||||||
|
pub const THREAD: &str = "liber.thread";
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct HelloB {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct WithdrawB {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct BuddyB {
|
||||||
|
read: String,
|
||||||
|
book: BookRef,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct ProgressB {
|
||||||
|
read: String,
|
||||||
|
spot: Spot,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct ThreadB {
|
||||||
|
read: String,
|
||||||
|
id: String,
|
||||||
|
spot: Spot,
|
||||||
|
text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Wire {
|
||||||
|
/// `None` for anything not exactly a Day 5 body: an unknown kind or field, a value out of its bounds.
|
||||||
|
pub fn parse(kind: &str, body: &[u8]) -> Option<Wire> {
|
||||||
|
if body.len() > MAX_BODY {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let w = match kind {
|
||||||
|
HELLO => {
|
||||||
|
let b: HelloB = serde_json::from_slice(body).ok()?;
|
||||||
|
Wire::Hello { name: b.name.trim().to_owned() }
|
||||||
|
}
|
||||||
|
NOTE => Wire::Note(Box::new(serde_json::from_slice(body).ok()?)),
|
||||||
|
WITHDRAW => Wire::Withdraw { id: serde_json::from_slice::<WithdrawB>(body).ok()?.id },
|
||||||
|
BUDDY => {
|
||||||
|
let b: BuddyB = serde_json::from_slice(body).ok()?;
|
||||||
|
Wire::Buddy { read: b.read, book: b.book }
|
||||||
|
}
|
||||||
|
PROGRESS => {
|
||||||
|
let b: ProgressB = serde_json::from_slice(body).ok()?;
|
||||||
|
Wire::Progress { read: b.read, spot: b.spot }
|
||||||
|
}
|
||||||
|
THREAD => {
|
||||||
|
let b: ThreadB = serde_json::from_slice(body).ok()?;
|
||||||
|
Wire::Thread { read: b.read, id: b.id, spot: b.spot, text: b.text }
|
||||||
|
}
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
w.ok().then_some(w)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ok(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Wire::Hello { name } => name_ok(name),
|
||||||
|
Wire::Note(n) => n.ok(),
|
||||||
|
Wire::Withdraw { id } => id_ok(id),
|
||||||
|
Wire::Buddy { read, book } => id_ok(read) && book.ok(),
|
||||||
|
Wire::Progress { read, spot } => id_ok(read) && spot.ok(),
|
||||||
|
Wire::Thread { read, id, spot, text } => {
|
||||||
|
id_ok(read) && id_ok(id) && spot.ok() && chars_in(text.trim(), 1, MAX_MESSAGE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `(kind, body)` to send.
|
||||||
|
pub fn encode(&self) -> (&'static str, Vec<u8>) {
|
||||||
|
let j = |v: serde_json::Result<Vec<u8>>| v.unwrap_or_default();
|
||||||
|
match self {
|
||||||
|
Wire::Hello { name } => (HELLO, j(serde_json::to_vec(&HelloB { name: name.clone() }))),
|
||||||
|
Wire::Note(n) => (NOTE, j(serde_json::to_vec(n.as_ref()))),
|
||||||
|
Wire::Withdraw { id } => (WITHDRAW, j(serde_json::to_vec(&WithdrawB { id: id.clone() }))),
|
||||||
|
Wire::Buddy { read, book } => {
|
||||||
|
(BUDDY, j(serde_json::to_vec(&BuddyB { read: read.clone(), book: book.clone() })))
|
||||||
|
}
|
||||||
|
Wire::Progress { read, spot } => {
|
||||||
|
(PROGRESS, j(serde_json::to_vec(&ProgressB { read: read.clone(), spot: *spot })))
|
||||||
|
}
|
||||||
|
Wire::Thread { read, id, spot, text } => (
|
||||||
|
THREAD,
|
||||||
|
j(serde_json::to_vec(&ThreadB { read: read.clone(), id: id.clone(), spot: *spot, text: text.clone() })),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chars_in(s: &str, min: usize, max: usize) -> bool {
|
||||||
|
let n = s.chars().count();
|
||||||
|
n >= min && n <= max
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An id another device made: 1–64 letters, digits, `-` or `_`.
|
||||||
|
pub fn id_ok(s: &str) -> bool {
|
||||||
|
!s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A name someone chose: 1–80 characters, no control characters.
|
||||||
|
pub fn name_ok(s: &str) -> bool {
|
||||||
|
chars_in(s.trim(), 1, MAX_NAME) && !s.chars().any(char::is_control)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a shared note lands in the reader's copy. Offsets are UTF-16 into the chapter's text.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||||
|
pub enum Placement {
|
||||||
|
Exact {
|
||||||
|
chapter: usize,
|
||||||
|
start: usize,
|
||||||
|
end: usize,
|
||||||
|
},
|
||||||
|
/// "Position approximate": found by its quoted text (another edition, or the text moved).
|
||||||
|
Approximate {
|
||||||
|
chapter: usize,
|
||||||
|
start: usize,
|
||||||
|
end: usize,
|
||||||
|
},
|
||||||
|
/// Not in this copy: shown in the side list with its quote, never at a guessed place.
|
||||||
|
Lost,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Placement {
|
||||||
|
pub fn chapter(&self) -> Option<usize> {
|
||||||
|
match self {
|
||||||
|
Placement::Exact { chapter, .. } | Placement::Approximate { chapter, .. } => Some(*chapter),
|
||||||
|
Placement::Lost => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The note's anchor in `doc`, the reader's copy of the book `mine`. Only the same book (ISBN-13 or fingerprint)
|
||||||
|
/// can be exact; any other edition is at best approximate.
|
||||||
|
pub fn place(doc: &Document, mine: &BookInfo, note: &SharedNote) -> Placement {
|
||||||
|
let same = note.book.is(mine);
|
||||||
|
match resolve(doc, ¬e.anchor) {
|
||||||
|
Resolved::Exact { chapter, start, end } if same => Placement::Exact { chapter, start, end },
|
||||||
|
Resolved::Exact { chapter, start, end } | Resolved::Approximate { chapter, start, end } => {
|
||||||
|
Placement::Approximate { chapter, start, end }
|
||||||
|
}
|
||||||
|
Resolved::Lost => Placement::Lost,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How far the reader has got in a book: the furthest position on any device, or the end once it is read.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct Reach {
|
||||||
|
pub chapter: u32,
|
||||||
|
pub progress: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Reach {
|
||||||
|
pub fn of(book: &Book) -> Reach {
|
||||||
|
if book.status() == ReadStatus::Read
|
||||||
|
|| book.reads.iter().any(|r| r.outcome == Some(crate::library::Outcome::Read))
|
||||||
|
{
|
||||||
|
return Reach { chapter: u32::MAX, progress: 1.0 };
|
||||||
|
}
|
||||||
|
match &book.position {
|
||||||
|
Some(p) => Reach { chapter: p.chapter, progress: p.progress },
|
||||||
|
None => Reach { chapter: 0, progress: 0.0 },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The spoiler guard: whether a note or message stays folded. `placed`: the chapter it landed in in the reader's copy
|
||||||
|
/// (`None` for the side list and for thread messages); `same`: the same book as the sender's. The chapter being read
|
||||||
|
/// is open; anything beyond the furthest chapter is folded.
|
||||||
|
pub fn folded(spot: &Spot, placed: Option<usize>, same: bool, reach: &Reach) -> bool {
|
||||||
|
if reach.chapter == u32::MAX {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match placed {
|
||||||
|
Some(ch) => ch as u64 > reach.chapter as u64,
|
||||||
|
None if same => spot.chapter > reach.chapter,
|
||||||
|
None => spot.progress > reach.progress,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a recording's audio is.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||||||
|
pub enum RecordingSource {
|
||||||
|
/// A slot on the home server: the sealed audio (`sha256` of the blob as it was found, so an approval holds for
|
||||||
|
/// exactly that take), opened with `key` (base64url, 32 bytes).
|
||||||
|
Slot { slot: String, key: String, sha256: String },
|
||||||
|
/// Only on the device that recorded it, sealed in its store.
|
||||||
|
Local { sha256: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RecordingSource {
|
||||||
|
pub(crate) fn ok(&self) -> bool {
|
||||||
|
let hex = |s: &str| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit());
|
||||||
|
match self {
|
||||||
|
RecordingSource::Slot { slot, key, sha256 } => slot_ok(slot) && key_ok(key) && hex(sha256),
|
||||||
|
RecordingSource::Local { sha256 } => hex(sha256),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A slot id: 22 base64url characters (128 bits).
|
||||||
|
pub fn slot_ok(s: &str) -> bool {
|
||||||
|
s.len() == 22 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A link key: 43 base64url characters (32 bytes).
|
||||||
|
pub fn key_ok(s: &str) -> bool {
|
||||||
|
s.len() == 43 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The audio types a recording may have (the browser's recorder: Opus in WebM or Ogg; Safari: AAC in MP4).
|
||||||
|
pub fn mime_ok(m: &str) -> bool {
|
||||||
|
let base = m.split(';').next().unwrap_or("").trim();
|
||||||
|
matches!(base, "audio/webm" | "audio/ogg" | "audio/mp4") && m.len() <= 64 && m.is_ascii()
|
||||||
|
}
|
||||||
@@ -83,6 +83,7 @@ pub fn op(r: &mut Rng, dev: &str, n: usize) -> Op {
|
|||||||
},
|
},
|
||||||
13 => Op::Return { loan: format!("l-{dev}-{}", n.saturating_sub(1 + r.below(4) as usize)), date },
|
13 => Op::Return { loan: format!("l-{dev}-{}", n.saturating_sub(1 + r.below(4) as usize)), date },
|
||||||
14 => Op::Session {
|
14 => Op::Session {
|
||||||
|
offset_min: None,
|
||||||
id: format!("s-{dev}-{n}"),
|
id: format!("s-{dev}-{n}"),
|
||||||
book,
|
book,
|
||||||
start: 1000,
|
start: 1000,
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ fn yearly_and_all_time() {
|
|||||||
e(Op::ReadStart { book: "a".into(), read: "r4".into(), date: Some("2026-01-01".into()) }),
|
e(Op::ReadStart { book: "a".into(), read: "r4".into(), date: Some("2026-01-01".into()) }),
|
||||||
e(Op::ReadEnd { read: "r4".into(), date: Some("2026-01-20".into()), outcome: Outcome::Read }),
|
e(Op::ReadEnd { read: "r4".into(), date: Some("2026-01-20".into()), outcome: Outcome::Read }),
|
||||||
e(Op::Session {
|
e(Op::Session {
|
||||||
|
offset_min: None,
|
||||||
id: "s1".into(),
|
id: "s1".into(),
|
||||||
book: "a".into(),
|
book: "a".into(),
|
||||||
start: 0,
|
start: 0,
|
||||||
@@ -41,6 +42,7 @@ fn yearly_and_all_time() {
|
|||||||
date: "2025-01-10".into(),
|
date: "2025-01-10".into(),
|
||||||
}),
|
}),
|
||||||
e(Op::Session {
|
e(Op::Session {
|
||||||
|
offset_min: None,
|
||||||
id: "s2".into(),
|
id: "s2".into(),
|
||||||
book: "b".into(),
|
book: "b".into(),
|
||||||
start: 0,
|
start: 0,
|
||||||
|
|||||||
@@ -0,0 +1,353 @@
|
|||||||
|
//! Day 5 (the app's `docs/05_together.md`): reading together. Mandatory tests 2 (matching), 3 (spoiler guard) and
|
||||||
|
//! 4 (approval, the core's half), and the strict parsing of what another person's Liber sends.
|
||||||
|
|
||||||
|
use liber_format::{Document, Limits};
|
||||||
|
use liber_library::library::{BookInfo, Colour, Mark};
|
||||||
|
use liber_library::together::{
|
||||||
|
self, BookRef, Placement, Reach, RecordingSource, SharedNote, Spot, Wire, folded, place,
|
||||||
|
};
|
||||||
|
use liber_library::{Clock, Event, Library, Op};
|
||||||
|
|
||||||
|
fn fb2(title: &str, chapters: &[(&str, &[&str])]) -> Document {
|
||||||
|
let mut body = String::new();
|
||||||
|
for (t, paras) in chapters {
|
||||||
|
body.push_str(&format!("<section><title><p>{t}</p></title>"));
|
||||||
|
for p in *paras {
|
||||||
|
body.push_str(&format!("<p>{p}</p>"));
|
||||||
|
}
|
||||||
|
body.push_str("</section>");
|
||||||
|
}
|
||||||
|
let x = format!(
|
||||||
|
r#"<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0"><description><title-info><book-title>{title}</book-title><lang>cs</lang></title-info></description><body>{body}</body></FictionBook>"#
|
||||||
|
);
|
||||||
|
liber_format::open(x.as_bytes(), Some("b.fb2"), &Limits::default()).expect("parses")
|
||||||
|
}
|
||||||
|
|
||||||
|
const C1: &[&str] =
|
||||||
|
&["Kapitán van Toch byl tlustý a dobrý člověk.", "Na ostrově Tana Masa žili mloci, kteří uměli házet kamením."];
|
||||||
|
const C2: &[&str] = &["Mloci se naučili mluvit a číst noviny.", "Pan Bondy založil Salamander Syndicate."];
|
||||||
|
const C3: &[&str] = &["Válka s mloky začala tiše.", "Nakonec zbyl jen spisovatel a jeho svědomí."];
|
||||||
|
|
||||||
|
/// The same book as the sender has.
|
||||||
|
fn edition_a() -> Document {
|
||||||
|
fb2("Válka s mloky", &[("I", C1), ("II", C2), ("III", C3)])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Another edition: a foreword before the story, and a sentence changed in chapter II.
|
||||||
|
fn edition_b() -> Document {
|
||||||
|
const FOREWORD: &[&str] = &["Předmluva vydavatele k tomuto vydání."];
|
||||||
|
const C2B: &[&str] = &["Mloci se naučili mluvit a číst noviny.", "Pan G. H. Bondy založil syndikát."];
|
||||||
|
fb2("Válka s mloky", &[("Předmluva", FOREWORD), ("I", C1), ("II", C2B), ("III", C3)])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chapter_of(d: &Document, needle: &str) -> usize {
|
||||||
|
d.chapters.iter().position(|c| c.root.text().contains(needle)).expect(needle)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn note_on(d: &Document, quote: &str, book: BookRef) -> SharedNote {
|
||||||
|
let ch = chapter_of(d, quote);
|
||||||
|
let text = d.chapters[ch].root.text();
|
||||||
|
let at = text.find(quote).unwrap();
|
||||||
|
let s = text[..at].encode_utf16().count();
|
||||||
|
let e = s + quote.encode_utf16().count();
|
||||||
|
let anchor = liber_format::position::anchor(d, ch, s, e).expect("anchor");
|
||||||
|
SharedNote {
|
||||||
|
id: "n-1".into(),
|
||||||
|
book,
|
||||||
|
anchor,
|
||||||
|
spot: Spot { chapter: ch as u32, progress: ch as f64 / d.chapters.len() as f64 },
|
||||||
|
kind: Mark::Note,
|
||||||
|
colour: Colour::Green,
|
||||||
|
note: "Tohle si pamatuj.".into(),
|
||||||
|
created: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn info(isbn: Option<&str>, fp: Option<&str>) -> BookInfo {
|
||||||
|
BookInfo {
|
||||||
|
title: "Válka s mloky".into(),
|
||||||
|
isbn13: isbn.map(str::to_owned),
|
||||||
|
fingerprint: fp.map(str::to_owned),
|
||||||
|
..BookInfo::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reff(isbn: Option<&str>, fp: Option<&str>) -> BookRef {
|
||||||
|
BookRef { isbn13: isbn.map(str::to_owned), fingerprint: fp.map(str::to_owned), title: "Válka s mloky".into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 2. matching ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_note_lands_exactly_in_the_same_edition() {
|
||||||
|
let a = edition_a();
|
||||||
|
let n = note_on(&a, "uměli házet kamením", reff(Some("9788020712479"), None));
|
||||||
|
let want = chapter_of(&a, "uměli házet");
|
||||||
|
match place(&a, &info(Some("9788020712479"), None), &n) {
|
||||||
|
Placement::Exact { chapter, start, end } => {
|
||||||
|
assert_eq!(chapter, want);
|
||||||
|
let t: Vec<u16> = a.chapters[chapter].root.text().encode_utf16().collect();
|
||||||
|
assert_eq!(String::from_utf16_lossy(&t[start..end]), "uměli házet kamením");
|
||||||
|
}
|
||||||
|
p => panic!("{p:?}"),
|
||||||
|
}
|
||||||
|
// The fingerprint identifies the book too.
|
||||||
|
assert!(matches!(
|
||||||
|
place(&a, &info(None, Some("fp")), ¬e_on(&a, "tlustý", reff(None, Some("fp")))),
|
||||||
|
Placement::Exact { .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn in_another_edition_the_note_is_approximate_and_at_the_right_words() {
|
||||||
|
let (a, b) = (edition_a(), edition_b());
|
||||||
|
let n = note_on(&a, "uměli házet kamením", reff(Some("9788020712479"), None));
|
||||||
|
match place(&b, &info(Some("9788000000000"), Some("other")), &n) {
|
||||||
|
Placement::Approximate { chapter, start, end } => {
|
||||||
|
assert_eq!(chapter, chapter_of(&b, "uměli házet"), "chapter I is the second chapter there");
|
||||||
|
let t: Vec<u16> = b.chapters[chapter].root.text().encode_utf16().collect();
|
||||||
|
assert_eq!(String::from_utf16_lossy(&t[start..end]), "uměli házet kamením");
|
||||||
|
}
|
||||||
|
p => panic!("{p:?}"),
|
||||||
|
}
|
||||||
|
// Even where the positions happen to point at the same words, another edition is never "exact".
|
||||||
|
let n = note_on(&a, "Kapitán van Toch", reff(None, Some("fp-a")));
|
||||||
|
assert!(matches!(place(&a, &info(None, Some("fp-b")), &n), Placement::Approximate { .. }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_note_on_text_that_is_not_there_goes_to_the_side_list() {
|
||||||
|
let (a, b) = (edition_a(), edition_b());
|
||||||
|
// "Salamander Syndicate" was rewritten in edition B.
|
||||||
|
let n = note_on(&a, "založil Salamander Syndicate", reff(None, Some("fp-a")));
|
||||||
|
assert_eq!(place(&b, &info(None, Some("fp-b")), &n), Placement::Lost);
|
||||||
|
// Two equally good places in the reader's copy (the same sentence twice, neither with the note's context): never
|
||||||
|
// a guess.
|
||||||
|
let twice = fb2("x", &[("I", &["A. Mloci mluví dál. B. Mloci mluví dál. C."])]);
|
||||||
|
let mut n = note_on(&twice, "Mloci mluví dál.", reff(None, Some("fp-t")));
|
||||||
|
n.anchor.start = "epubcfi(/6/99!/4/2/1:0)".into();
|
||||||
|
n.anchor.quote.prefix = "X. ".into();
|
||||||
|
n.anchor.quote.suffix = " Y.".into();
|
||||||
|
assert_eq!(place(&twice, &info(None, Some("fp-other")), &n), Placement::Lost);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 3. spoiler guard ----------
|
||||||
|
|
||||||
|
fn ev(id: &str, c: &mut Clock, t: u64, op: Op) -> Event {
|
||||||
|
Event { id: id.into(), hlc: c.tick(t), device: "phone".into(), op }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn position(chapter: u32, progress: f64) -> Op {
|
||||||
|
Op::Position {
|
||||||
|
book: "b1".into(),
|
||||||
|
cfi: format!("epubcfi(/6/{}!/4/2/1:0)", 2 * chapter + 2),
|
||||||
|
chapter,
|
||||||
|
progress,
|
||||||
|
label: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn notes_beyond_the_furthest_chapter_stay_folded_across_chapters_and_after_reopening() {
|
||||||
|
let mut c = Clock::default();
|
||||||
|
let mut evs =
|
||||||
|
vec![ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false })];
|
||||||
|
evs.push(ev("e1", &mut c, 2, position(1, 0.30)));
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
let reach = Reach::of(&lib.books["b1"]);
|
||||||
|
let at = |ch: u32, p: f64| Spot { chapter: ch, progress: p };
|
||||||
|
// Placed notes: by the chapter they landed in, in the reader's copy.
|
||||||
|
assert!(!folded(&at(0, 0.1), Some(0), true, &reach));
|
||||||
|
assert!(!folded(&at(1, 0.4), Some(1), true, &reach), "the chapter being read is open");
|
||||||
|
assert!(folded(&at(2, 0.6), Some(2), true, &reach));
|
||||||
|
// A note placed in a later chapter of the reader's edition stays folded even if the sender's chapter was earlier.
|
||||||
|
assert!(folded(&at(1, 0.2), Some(3), false, &reach));
|
||||||
|
// Not placed (side list) or a thread message: the same book → by chapter; another edition → by progress.
|
||||||
|
assert!(folded(&at(2, 0.1), None, true, &reach));
|
||||||
|
assert!(!folded(&at(5, 0.25), None, false, &reach));
|
||||||
|
assert!(folded(&at(0, 0.31), None, false, &reach));
|
||||||
|
|
||||||
|
// Reading on into chapter II opens its notes; going back does not fold them again (the furthest place counts).
|
||||||
|
evs.push(ev("e2", &mut c, 3, position(2, 0.55)));
|
||||||
|
evs.push(ev("e3", &mut c, 4, position(0, 0.05)));
|
||||||
|
// Re-opening: the library is rebuilt from its events, in another arrival order.
|
||||||
|
evs.reverse();
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
let reach = Reach::of(&lib.books["b1"]);
|
||||||
|
assert!(!folded(&at(2, 0.6), Some(2), true, &reach));
|
||||||
|
assert!(folded(&at(3, 0.8), Some(3), true, &reach));
|
||||||
|
|
||||||
|
// A finished book has no spoilers left.
|
||||||
|
evs.push(ev(
|
||||||
|
"e4",
|
||||||
|
&mut c,
|
||||||
|
5,
|
||||||
|
Op::ReadStart { read: "r1".into(), book: "b1".into(), date: Some("2026-11-01".into()) },
|
||||||
|
));
|
||||||
|
evs.push(ev(
|
||||||
|
"e5",
|
||||||
|
&mut c,
|
||||||
|
6,
|
||||||
|
Op::ReadEnd {
|
||||||
|
read: "r1".into(),
|
||||||
|
date: Some("2026-11-20".into()),
|
||||||
|
outcome: liber_library::library::Outcome::Read,
|
||||||
|
},
|
||||||
|
));
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
assert!(!folded(&at(3, 0.99), Some(3), true, &Reach::of(&lib.books["b1"])));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 4. approval (the core's half) ----------
|
||||||
|
|
||||||
|
fn rec(id: &str) -> Op {
|
||||||
|
Op::RecordingAdd {
|
||||||
|
id: id.into(),
|
||||||
|
book: "b1".into(),
|
||||||
|
chapter: 2,
|
||||||
|
by: "Babička".into(),
|
||||||
|
source: RecordingSource::Slot {
|
||||||
|
slot: "AAAAAAAAAAAAAAAAAAAAAA".into(),
|
||||||
|
key: "k".repeat(43),
|
||||||
|
sha256: "a".repeat(64),
|
||||||
|
},
|
||||||
|
mime: "audio/webm;codecs=opus".into(),
|
||||||
|
duration_ms: 600_000,
|
||||||
|
created: 10,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unapproved_recording_is_never_playable_and_a_removed_one_stays_gone() {
|
||||||
|
let mut c = Clock::default();
|
||||||
|
let mut evs = vec![
|
||||||
|
ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false }),
|
||||||
|
ev("e1", &mut c, 2, rec("r1")),
|
||||||
|
];
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
assert_eq!(lib.recordings.len(), 1, "the parent sees it, waiting");
|
||||||
|
assert!(!lib.recordings["r1"].approved);
|
||||||
|
assert!(lib.playable("b1", 2).is_empty());
|
||||||
|
assert!(lib.pending().iter().any(|r| r.id == "r1"));
|
||||||
|
|
||||||
|
evs.push(ev("e2", &mut c, 3, Op::RecordingApprove { id: "r1".into() }));
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
assert_eq!(lib.playable("b1", 2).iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), ["r1"]);
|
||||||
|
assert!(lib.playable("b1", 1).is_empty(), "only for its chapter");
|
||||||
|
assert!(lib.pending().is_empty());
|
||||||
|
|
||||||
|
// Deleted on one device: gone on every device that folds the log, and an old add arriving late does not bring it
|
||||||
|
// back, nor does a late approval.
|
||||||
|
evs.push(ev("e3", &mut c, 4, Op::RecordingRemove { id: "r1".into() }));
|
||||||
|
let mut late = Clock::default();
|
||||||
|
evs.push(ev("e4", &mut late, 2, rec("r1")));
|
||||||
|
evs.push(ev("e5", &mut c, 5, Op::RecordingApprove { id: "r1".into() }));
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
assert!(lib.recordings.is_empty());
|
||||||
|
assert!(lib.playable("b1", 2).is_empty());
|
||||||
|
assert!(lib.removed_recordings().contains("r1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_recording_and_ask_values_are_dropped() {
|
||||||
|
let mut c = Clock::default();
|
||||||
|
let mut bad = rec("r1");
|
||||||
|
if let Op::RecordingAdd { mime, .. } = &mut bad {
|
||||||
|
*mime = "text/html".into();
|
||||||
|
}
|
||||||
|
let mut no_book = rec("r2");
|
||||||
|
if let Op::RecordingAdd { book, .. } = &mut no_book {
|
||||||
|
*book = "missing".into();
|
||||||
|
}
|
||||||
|
let evs = vec![
|
||||||
|
ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false }),
|
||||||
|
ev("e1", &mut c, 2, bad),
|
||||||
|
ev("e2", &mut c, 3, no_book),
|
||||||
|
ev(
|
||||||
|
"e3",
|
||||||
|
&mut c,
|
||||||
|
4,
|
||||||
|
Op::RecordAsk {
|
||||||
|
slot: "short".into(),
|
||||||
|
book: "b1".into(),
|
||||||
|
chapter: 1,
|
||||||
|
person: "Babička".into(),
|
||||||
|
key: "k".repeat(43),
|
||||||
|
created: 1,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
assert!(lib.recordings.is_empty());
|
||||||
|
assert!(lib.asks.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- people, sharing, hiding ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn people_shares_and_hiding_fold_like_everything_else() {
|
||||||
|
let mut c = Clock::default();
|
||||||
|
let mut evs = vec![
|
||||||
|
ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false }),
|
||||||
|
ev("e1", &mut c, 2, Op::PersonAdd { person: "g1".into(), name: "Jana".into() }),
|
||||||
|
ev("e2", &mut c, 3, Op::Share { highlight: "h1".into(), person: "g1".into() }),
|
||||||
|
ev("e3", &mut c, 4, Op::Hide { person: "g1".into(), book: Some("b1".into()), hidden: true }),
|
||||||
|
ev("e4", &mut c, 5, Op::BuddyRead { id: "br1".into(), book: "b1".into(), people: vec!["g1".into()] }),
|
||||||
|
];
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
assert_eq!(lib.people["g1"].name, "Jana");
|
||||||
|
assert!(lib.shares["h1"].contains("g1"));
|
||||||
|
assert!(lib.hidden("g1", "b1"));
|
||||||
|
assert!(!lib.hidden("g1", "b2"));
|
||||||
|
assert_eq!(lib.buddy_reads["br1"].people, ["g1"]);
|
||||||
|
evs.push(ev("e5", &mut c, 6, Op::Hide { person: "g1".into(), book: None, hidden: true }));
|
||||||
|
evs.push(ev("e6", &mut c, 7, Op::Unshare { highlight: "h1".into(), person: "g1".into() }));
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
assert!(lib.hidden("g1", "b2"), "hidden everywhere");
|
||||||
|
assert!(lib.shares.get("h1").is_none_or(|s| s.is_empty()));
|
||||||
|
// An export restores all of it (with a recording, approved).
|
||||||
|
evs.push(ev("e8", &mut c, 9, rec("r1")));
|
||||||
|
evs.push(ev("e9", &mut c, 10, Op::RecordingApprove { id: "r1".into() }));
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
let mut rc = Clock::default();
|
||||||
|
let restored: Vec<Event> = liber_library::export::ops_from(&lib)
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, op)| ev(&format!("x{i}"), &mut rc, i as u64 + 1, op))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(Library::from_events(&restored), lib);
|
||||||
|
evs.push(ev("e7", &mut c, 8, Op::PersonRemove { person: "g1".into() }));
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
assert!(lib.people.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- what another person's Liber sends ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wire_bodies_are_parsed_strictly() {
|
||||||
|
let a = edition_a();
|
||||||
|
let n = note_on(&a, "tlustý a dobrý", reff(None, Some("fp")));
|
||||||
|
let body = serde_json::to_vec(&n).unwrap();
|
||||||
|
assert_eq!(Wire::parse("liber.note", &body), Some(Wire::Note(Box::new(n.clone()))));
|
||||||
|
assert_eq!(Wire::parse("liber.hello", br#"{"name":"Jana"}"#), Some(Wire::Hello { name: "Jana".into() }));
|
||||||
|
// Unknown kinds and fields, oversized values, bad numbers: refused.
|
||||||
|
assert_eq!(Wire::parse("liber.unknown", b"{}"), None);
|
||||||
|
assert_eq!(Wire::parse("liber.hello", br#"{"name":"Jana","admin":true}"#), None);
|
||||||
|
assert_eq!(Wire::parse("liber.hello", br#"{"name":""}"#), None);
|
||||||
|
let long = format!(r#"{{"name":"{}"}}"#, "x".repeat(81));
|
||||||
|
assert_eq!(Wire::parse("liber.hello", long.as_bytes()), None);
|
||||||
|
let mut big = n.clone();
|
||||||
|
big.note = "x".repeat(together::MAX_NOTE + 1);
|
||||||
|
assert_eq!(Wire::parse("liber.note", &serde_json::to_vec(&big).unwrap()), None);
|
||||||
|
let mut nan = n.clone();
|
||||||
|
nan.spot.progress = 2.0;
|
||||||
|
assert_eq!(Wire::parse("liber.note", &serde_json::to_vec(&nan).unwrap()), None);
|
||||||
|
let mut quote = n;
|
||||||
|
quote.anchor.quote.exact = String::new();
|
||||||
|
assert_eq!(Wire::parse("liber.note", &serde_json::to_vec("e).unwrap()), None);
|
||||||
|
let t = br#"{"read":"br1","id":"m1","spot":{"chapter":2,"progress":0.5},"text":"Ten konec!"}"#;
|
||||||
|
assert!(matches!(Wire::parse("liber.thread", t), Some(Wire::Thread { .. })));
|
||||||
|
assert_eq!(Wire::parse("liber.thread", &[0xff, 0xfe]), None);
|
||||||
|
assert_eq!(Wire::parse("liber.thread", &vec![b' '; together::MAX_BODY + 1]), None);
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
//! Day 3: known words, the known band, "read in my language" and second editions are events: they merge across
|
||||||
|
//! devices in any arrival order, survive an export, and hostile values from sync are dropped.
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::info;
|
||||||
|
use liber_library::export::{events_from, ops_from};
|
||||||
|
use liber_library::library::{Field, WordMark};
|
||||||
|
use liber_library::{Clock, Event, Library, Op};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn ev(id: &str, dev: &str, c: &mut Clock, t: u64, op: Op) -> Event {
|
||||||
|
Event { id: id.into(), hlc: c.tick(t), device: dev.into(), op }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn word(lang: &str, lemma: &str, mark: WordMark) -> Op {
|
||||||
|
Op::Word { lang: lang.into(), lemma: lemma.into(), mark }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn words_merge_last_writer_wins_in_any_order() {
|
||||||
|
let (mut pc, mut dc) = (Clock::default(), Clock::default());
|
||||||
|
let evs = vec![
|
||||||
|
ev("p1", "phone", &mut pc, 1_000, word("de", "haus", WordMark::Learning)),
|
||||||
|
ev("d1", "desk", &mut dc, 2_000, word("de", "haus", WordMark::Known)),
|
||||||
|
ev("p2", "phone", &mut pc, 3_000, word("de", "katze", WordMark::Learning)),
|
||||||
|
ev("d2", "desk", &mut dc, 4_000, word("de", "katze", WordMark::Unknown)),
|
||||||
|
ev("p3", "phone", &mut pc, 5_000, word("la", "amo", WordMark::Known)),
|
||||||
|
ev("d3", "desk", &mut dc, 6_000, Op::KnownBand { lang: "de".into(), list: "de-50k".into(), upto: 2_000 }),
|
||||||
|
];
|
||||||
|
let forward = Library::from_events(&evs);
|
||||||
|
let mut rev = evs.clone();
|
||||||
|
rev.reverse();
|
||||||
|
let backward = Library::from_events(&rev);
|
||||||
|
assert_eq!(forward, backward);
|
||||||
|
assert_eq!(forward.words["de"].get("haus"), Some(&WordMark::Known));
|
||||||
|
assert!(!forward.words["de"].contains_key("katze"), "Unknown removes the word");
|
||||||
|
assert_eq!(forward.words["la"].get("amo"), Some(&WordMark::Known));
|
||||||
|
assert_eq!(forward.bands["de"].upto, 2_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_word_events_are_dropped() {
|
||||||
|
let mut c = Clock::default();
|
||||||
|
let evs = vec![
|
||||||
|
ev("1", "x", &mut c, 1, word("DE", "haus", WordMark::Known)),
|
||||||
|
ev("2", "x", &mut c, 2, word("deutschland", "haus", WordMark::Known)),
|
||||||
|
ev("3", "x", &mut c, 3, word("de", "", WordMark::Known)),
|
||||||
|
ev("4", "x", &mut c, 4, word("de", &"a".repeat(65), WordMark::Known)),
|
||||||
|
ev("5", "x", &mut c, 5, Op::KnownBand { lang: "de".into(), list: "".into(), upto: 5 }),
|
||||||
|
ev("6", "x", &mut c, 6, Op::KnownBand { lang: "de".into(), list: "l".into(), upto: u32::MAX }),
|
||||||
|
];
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
assert!(lib.words.is_empty());
|
||||||
|
assert_eq!(lib.bands["de"].upto, 1_000_000, "capped");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn familiar_and_editions_on_a_book_and_through_an_export() {
|
||||||
|
let mut c = Clock::default();
|
||||||
|
let sha = "ab".repeat(32);
|
||||||
|
let evs = vec![
|
||||||
|
ev("1", "x", &mut c, 1, Op::BookAdd { book: "b".into(), info: info(1), restore: false }),
|
||||||
|
ev(
|
||||||
|
"2",
|
||||||
|
"x",
|
||||||
|
&mut c,
|
||||||
|
2,
|
||||||
|
Op::BookSet { book: "b".into(), field: Field::Familiar, value: json!(true), base: None },
|
||||||
|
),
|
||||||
|
ev("3", "x", &mut c, 3, Op::Edition { book: "b".into(), sha256: sha.clone(), language: Some("de".into()) }),
|
||||||
|
ev(
|
||||||
|
"4",
|
||||||
|
"x",
|
||||||
|
&mut c,
|
||||||
|
4,
|
||||||
|
Op::Edition { book: "b".into(), sha256: "not-a-sha".into(), language: Some("la".into()) },
|
||||||
|
),
|
||||||
|
ev("5", "x", &mut c, 5, word("de", "haus", WordMark::Learning)),
|
||||||
|
ev("6", "x", &mut c, 6, Op::KnownBand { lang: "en".into(), list: "en-50k".into(), upto: 4_000 }),
|
||||||
|
];
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
let b = &lib.books["b"];
|
||||||
|
assert!(b.familiar);
|
||||||
|
assert_eq!(b.editions.len(), 1);
|
||||||
|
assert_eq!(b.editions[&sha], "de");
|
||||||
|
// An export replays them all.
|
||||||
|
let back = Library::from_events(&events_from(&lib, "restore", 10));
|
||||||
|
assert_eq!(back, lib);
|
||||||
|
assert!(back.books.values().next().is_some_and(|b| b.familiar && b.editions.len() == 1));
|
||||||
|
assert!(ops_from(&lib).iter().any(|o| matches!(o, Op::Word { .. })));
|
||||||
|
// Removing an edition's language.
|
||||||
|
let mut evs2 = evs;
|
||||||
|
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)));
|
||||||
|
}
|
||||||
+16
-1
@@ -45,19 +45,22 @@ Versions are the ones `cargo` resolved on 2026-11-17; the table below is generat
|
|||||||
## Every crate in Cargo.lock
|
## Every crate in Cargo.lock
|
||||||
|
|
||||||
<!-- deps:begin -->
|
<!-- deps:begin -->
|
||||||
100 crates; 0 outside the allowed set.
|
115 crates; 0 outside the allowed set.
|
||||||
|
|
||||||
| Crate | Version | Licence | Allowed |
|
| Crate | Version | Licence | Allowed |
|
||||||
| :-- | :-- | :-- | :-- |
|
| :-- | :-- | :-- | :-- |
|
||||||
| adler2 | 2.0.1 | 0BSD OR MIT OR Apache-2.0 | yes |
|
| adler2 | 2.0.1 | 0BSD OR MIT OR Apache-2.0 | yes |
|
||||||
|
| arrayvec | 0.7.8 | MIT OR Apache-2.0 | yes |
|
||||||
| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes |
|
| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes |
|
||||||
| base64 | 0.22.1 | MIT OR Apache-2.0 | yes |
|
| base64 | 0.22.1 | MIT OR Apache-2.0 | yes |
|
||||||
| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes |
|
| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes |
|
||||||
| bit-vec | 0.10.2 | Apache-2.0 OR MIT | yes |
|
| bit-vec | 0.10.2 | Apache-2.0 OR MIT | yes |
|
||||||
|
| bitflags | 1.3.2 | MIT/Apache-2.0 | yes |
|
||||||
| bitflags | 2.13.2 | MIT OR Apache-2.0 | yes |
|
| bitflags | 2.13.2 | MIT OR Apache-2.0 | yes |
|
||||||
| block-buffer | 0.10.4 | MIT OR Apache-2.0 | yes |
|
| block-buffer | 0.10.4 | MIT OR Apache-2.0 | yes |
|
||||||
| borsh | 1.8.1 | MIT OR Apache-2.0 | yes |
|
| borsh | 1.8.1 | MIT OR Apache-2.0 | yes |
|
||||||
| borsh-derive | 1.8.1 | Apache-2.0 | yes |
|
| borsh-derive | 1.8.1 | Apache-2.0 | yes |
|
||||||
|
| bytemuck | 1.25.2 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||||
| bytes | 1.12.1 | MIT | yes |
|
| bytes | 1.12.1 | MIT | yes |
|
||||||
| cfg_aliases | 0.2.2 | MIT | yes |
|
| cfg_aliases | 0.2.2 | MIT | yes |
|
||||||
| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes |
|
| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -74,6 +77,7 @@ Versions are the ones `cargo` resolved on 2026-11-17; the table below is generat
|
|||||||
| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes |
|
| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes |
|
||||||
| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes |
|
| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes |
|
||||||
| errno | 0.3.15 | MIT OR Apache-2.0 | yes |
|
| errno | 0.3.15 | MIT OR Apache-2.0 | yes |
|
||||||
|
| extended | 0.1.0 | MIT | yes |
|
||||||
| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes |
|
| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes |
|
||||||
| fnv | 1.0.7 | Apache-2.0 / MIT | yes |
|
| fnv | 1.0.7 | Apache-2.0 / MIT | yes |
|
||||||
| generic-array | 0.14.7 | MIT | yes |
|
| generic-array | 0.14.7 | MIT | yes |
|
||||||
@@ -82,6 +86,7 @@ Versions are the ones `cargo` resolved on 2026-11-17; the table below is generat
|
|||||||
| html5ever | 0.40.1 | MIT OR Apache-2.0 | yes |
|
| html5ever | 0.40.1 | MIT OR Apache-2.0 | yes |
|
||||||
| indexmap | 2.14.2 | Apache-2.0 OR MIT | yes |
|
| indexmap | 2.14.2 | Apache-2.0 OR MIT | yes |
|
||||||
| itoa | 1.0.19 | MIT OR Apache-2.0 | yes |
|
| itoa | 1.0.19 | MIT OR Apache-2.0 | yes |
|
||||||
|
| lazy_static | 1.5.1 | MIT OR Apache-2.0 | yes |
|
||||||
| libc | 0.2.191 | MIT OR Apache-2.0 | yes |
|
| libc | 0.2.191 | MIT OR Apache-2.0 | yes |
|
||||||
| linux-raw-sys | 0.12.1 | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | yes |
|
| linux-raw-sys | 0.12.1 | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | yes |
|
||||||
| lock_api | 0.4.14 | MIT OR Apache-2.0 | yes |
|
| lock_api | 0.4.14 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -128,6 +133,15 @@ Versions are the ones `cargo` resolved on 2026-11-17; the table below is generat
|
|||||||
| smallvec | 1.16.5 | MIT OR Apache-2.0 | yes |
|
| smallvec | 1.16.5 | MIT OR Apache-2.0 | yes |
|
||||||
| string_cache | 0.11.0 | MIT OR Apache-2.0 | yes |
|
| string_cache | 0.11.0 | MIT OR Apache-2.0 | yes |
|
||||||
| string_cache_codegen | 0.11.2 | MIT OR Apache-2.0 | yes |
|
| string_cache_codegen | 0.11.2 | MIT OR Apache-2.0 | yes |
|
||||||
|
| symphonia | 0.5.5 | MPL-2.0 | yes |
|
||||||
|
| symphonia-bundle-mp3 | 0.5.5 | MPL-2.0 | yes |
|
||||||
|
| symphonia-codec-aac | 0.5.5 | MPL-2.0 | yes |
|
||||||
|
| symphonia-codec-pcm | 0.5.5 | MPL-2.0 | yes |
|
||||||
|
| symphonia-core | 0.5.5 | MPL-2.0 | yes |
|
||||||
|
| symphonia-format-isomp4 | 0.5.5 | MPL-2.0 | yes |
|
||||||
|
| symphonia-format-riff | 0.5.5 | MPL-2.0 | yes |
|
||||||
|
| symphonia-metadata | 0.5.5 | MPL-2.0 | yes |
|
||||||
|
| symphonia-utils-xiph | 0.5.5 | MPL-2.0 | yes |
|
||||||
| syn | 3.0.10 | MIT OR Apache-2.0 | yes |
|
| syn | 3.0.10 | MIT OR Apache-2.0 | yes |
|
||||||
| tempfile | 3.27.0 | MIT OR Apache-2.0 | yes |
|
| tempfile | 3.27.0 | MIT OR Apache-2.0 | yes |
|
||||||
| tendril | 0.5.1 | MIT OR Apache-2.0 | yes |
|
| tendril | 0.5.1 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -141,6 +155,7 @@ Versions are the ones `cargo` resolved on 2026-11-17; the table below is generat
|
|||||||
| unarray | 0.1.4 | MIT OR Apache-2.0 | yes |
|
| unarray | 0.1.4 | MIT OR Apache-2.0 | yes |
|
||||||
| unicode-ident | 1.0.27 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
| unicode-ident | 1.0.27 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||||
| unicode-normalization | 0.1.26 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
| unicode-normalization | 0.1.26 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||||
|
| unicode-segmentation | 1.13.3 | MIT OR Apache-2.0 | yes |
|
||||||
| version_check | 0.9.5 | MIT/Apache-2.0 | yes |
|
| version_check | 0.9.5 | MIT/Apache-2.0 | yes |
|
||||||
| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes |
|
| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes |
|
||||||
| web_atoms | 0.3.0 | MIT OR Apache-2.0 | yes |
|
| web_atoms | 0.3.0 | MIT OR Apache-2.0 | yes |
|
||||||
|
|||||||
Reference in New Issue
Block a user