[lang][library] Languages: liber-lang (words with UTF-16 offsets, lemmatizer trait with tables and hand-written rules, coverage, warm-up, levels, Ludus concept ids, Gale-Church alignment with anchors); known words, the known band, familiar books and editions as events

This commit is contained in:
2026-11-17 19:33:45 +01:00
parent 4e68eec3c4
commit 7dca9de95c
25 changed files with 2272 additions and 8 deletions
+202
View File
@@ -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)
}
+25
View File
@@ -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
}
+917
View File
@@ -0,0 +1,917 @@
//! 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,
};
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),
};
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"),
];
+26
View File
@@ -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 }
}
+64
View File
@@ -0,0 +1,64 @@
//! 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 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,
}
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),
_ => None,
}
}
pub fn code(self) -> &'static str {
match self {
Lang::En => "en",
Lang::De => "de",
Lang::La => "la",
}
}
}
/// 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 }
}
+124
View File
@@ -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 => !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)
}
+96
View File
@@ -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
}