[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:
@@ -0,0 +1,128 @@
|
||||
//! 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};
|
||||
|
||||
fn paragraphs(text: &str) -> Vec<&str> {
|
||||
text.split("\n\n").map(str::trim).filter(|p| !p.is_empty()).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.
|
||||
+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,81 @@
|
||||
//! 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"),
|
||||
};
|
||||
text.lines()
|
||||
.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"));
|
||||
}
|
||||
Reference in New Issue
Block a user