"""Tests for the evaluation and baseline corpus builders.""" from __future__ import annotations import json import sys import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) import build_baseline_corpus as baseline # noqa: E402 import build_eval_corpus as evalc # noqa: E402 import shortlist_pivots as pivots # noqa: E402 class ConllParsing(unittest.TestCase): """xSID writes ``# text = x``; NaLiBaSID writes ``# text: x``. Both must parse.""" XSID = ( "# id = 1\n" "# text-en = show all reminders\n" "# text-de: Zeige alle Erinnerungen\n" "# text = Du mer au Erinnerige azeige\n" "# intent = reminder/show_reminders\n" "1\tDu\treminder/show_reminders\tO\n" "\n" "# id = 2\n" "# text-en = do I need a sweater\n" "# text = Bruuch i en Pulli\n" "1\tBruuch\tweather/find\tO\n" ) NALIBASID = ( "# id: 1\n" "# intent: reminder/show_reminders\n" "# text-en: show all reminders\n" "# text: Zoag ma olle Erinnerungen\n" "1\tZoag\treminder/show_reminders\tO\n" ) def test_equals_separator_is_parsed(self): records = evalc.parse_conll_sentences(self.XSID) self.assertEqual(len(records), 2) self.assertEqual(records[0]["text-en"], "show all reminders") self.assertEqual(records[0]["text"], "Du mer au Erinnerige azeige") def test_colon_separator_is_parsed(self): records = evalc.parse_conll_sentences(self.NALIBASID) self.assertEqual(len(records), 1) self.assertEqual(records[0]["text-en"], "show all reminders") def test_final_record_without_a_trailing_blank_line_is_kept(self): records = evalc.parse_conll_sentences(self.XSID) self.assertEqual(records[-1]["text"], "Bruuch i en Pulli") def test_both_pivots_become_separate_records(self): made = evalc._sid_records(self.XSID, "als", "xsid", "test", {"text-en": "en", "text-de": "de"}) pivots_seen = sorted({record["sl"] for record in made}) self.assertEqual(pivots_seen, ["de", "en"]) # Only the English side is an original; the German is itself a translation. english = next(r for r in made if r["sl"] == "en") german = next(r for r in made if r["sl"] == "de") self.assertTrue(english["is_src_orig"]) self.assertFalse(german["is_src_orig"]) def test_projected_training_files_are_never_eligible(self): self.assertIn("projectedTrain", evalc.XSID_EXCLUDED) class TatoebaParsing(unittest.TestCase): ROWS = ( "eng\tina_Latn\tA baby is God's opinion.\tUn infante es le opinion de Deo.\n" "eng\tina_Latn\tA barometer is useful.\tUn barometro es utile.\n" "\n" "short\tline\n" ) def test_four_column_rows_are_read_and_short_lines_ignored(self): rows = evalc.parse_tatoeba_test(self.ROWS) self.assertEqual(len(rows), 2) self.assertEqual(rows[0]["src_lang"], "eng") self.assertEqual(rows[0]["trg_lang"], "ina_Latn") self.assertEqual(rows[0]["trg"], "Un infante es le opinion de Deo.") class ParmeParsing(unittest.TestCase): TSV = ( "en_sentence\tfa_sentence\ttranslation\tvariety (Western Gilaki|Eastern Gilaki)\t" "county\torthography\ttranslator\n" "I have advised him.\tمن به او توصیه کردم.\tمۊ أن-أ سٚفارش بۊکۊدم\tWestern Gilaki\t" "Bandar Anzali\tVrg\tRRR\n" "Empty target.\tخالی\t\tWestern Gilaki\t\t\t\n" ) def test_english_and_persian_sides_are_both_available(self): rows = evalc.parse_parme(self.TSV) self.assertEqual(len(rows), 1) # the row with no translation is dropped self.assertEqual(rows[0]["en"], "I have advised him.") self.assertTrue(rows[0]["fa"]) self.assertEqual(rows[0]["variety"], "Western Gilaki") class Normalisation(unittest.TestCase): def test_zero_width_non_joiner_survives_cleaning(self): # Persian and Gilaki rely on ZWNJ inside words; stripping it changes the text. text = "مي‌خانه" self.assertIn("‌", evalc._clean(f" {text} ")) def test_whitespace_runs_collapse(self): self.assertEqual(evalc._clean("a b\n\tc "), "a b c") def test_comparison_key_ignores_case_and_punctuation(self): self.assertEqual(evalc.norm_key("Hello, world!"), evalc.norm_key("hello world")) def test_comparison_key_distinguishes_different_text(self): self.assertNotEqual(evalc.norm_key("hello"), evalc.norm_key("hallo")) class Deduplication(unittest.TestCase): def _record(self, source, src="show all reminders", trg="Zoag ma olle Erinnerungen"): return evalc.make_record( pivot_config="en", target_config="bar", src=src, trg=trg, source=source, split="test", ) def test_nalibasid_supersedes_xsid_for_the_same_pair(self): records, dropped = evalc.deduplicate( [self._record("xsid"), self._record("nalibasid")], {} ) self.assertEqual(len(records), 1) self.assertEqual(records[0]["source"], "nalibasid") self.assertEqual(dropped[0]["dropped"], "xsid") def test_order_of_arrival_does_not_change_the_winner(self): records, _ = evalc.deduplicate( [self._record("nalibasid"), self._record("xsid")], {} ) self.assertEqual(records[0]["source"], "nalibasid") def test_distinct_pairs_are_both_kept(self): records, _ = evalc.deduplicate( [self._record("xsid"), self._record("xsid", trg="Zoag ma d'Erinnerungen")], {} ) self.assertEqual(len(records), 2) def test_withheld_reference_rows_are_not_merged_away(self): reference = {"sl": "en", "tl": "wuu", "id": None, "src": None, "trg": None, "source": "flores_plus", "split": "dev"} records, _ = evalc.deduplicate([reference, self._record("xsid")], {}) self.assertEqual(len(records), 2) class SmolRouting(unittest.TestCase): def test_smol_records_are_flagged_as_released_for_training(self): record = evalc.make_record( pivot_config="en", target_config="glk", src="a", trg="b", source="smol", split="test", extra={"released_as": "training"}, ) self.assertEqual(record["split"], "test") self.assertEqual(record["released_as"], "training") self.assertEqual(record["licence"], "CC-BY-4.0") def test_smol_note_records_the_comparability_caveat(self): self.assertIn("not comparable", evalc.SOURCE_META["smol"]["note"]) class FloresWithholding(unittest.TestCase): def test_flores_reference_rows_carry_no_text(self): rows = {"wuu": {"in_flores_plus": True, "iso639_3": "wuu"}} made = evalc.collect_flores_reference(["wuu"], rows) self.assertEqual(len(made), 2) # dev and test for record in made: # Withheld rows carry empty text rather than null, uniformly across sources. self.assertEqual(record["src"], "") self.assertEqual(record["trg"], "") self.assertTrue(record["text_withheld"]) # The reason lives in licence_restriction; a separate withheld_reason column # repeated it verbatim on every withheld row and was removed. self.assertIn("crawlers", record["licence_restriction"]) def test_languages_without_flores_get_no_reference_rows(self): rows = {"glk": {"in_flores_plus": False, "iso639_3": "glk"}} self.assertEqual(evalc.collect_flores_reference(["glk"], rows), []) class CorpusClassification(unittest.TestCase): def test_automatically_produced_corpora_are_not_counted_as_human(self): for name in ("XLEnt", "WikiMatrix", "wikimedia", "translatewiki", "GNOME"): self.assertNotIn(baseline.corpus_type(name), baseline.HUMAN_TYPES, name) def test_entity_lists_are_distinguished_from_mined_sentences(self): self.assertEqual(baseline.corpus_type("XLEnt"), "entity_list") self.assertEqual(baseline.corpus_type("WikiMatrix"), "auto_mined") def test_human_sources_are_counted_as_human(self): for name in ("Tatoeba", "GlobalVoices", "QED", "bible-uedin"): self.assertIn(baseline.corpus_type(name), baseline.HUMAN_TYPES, name) def test_unknown_corpus_is_reported_rather_than_assumed_human(self): self.assertEqual(baseline.corpus_type("SomeNewCorpus2031"), "unclassified") self.assertNotIn("unclassified", baseline.HUMAN_TYPES) class Contamination(unittest.TestCase): def test_training_record_matching_an_eval_target_is_removed(self): keys = {"bar": {evalc.norm_key("hallo")}} records = [ {"tl": "bar", "sl": "en", "src": "Hello!", "trg": "Hallo!"}, {"tl": "bar", "sl": "en", "src": "Goodbye", "trg": "Pfiat di"}, ] kept, removed = baseline.drop_contamination(records, keys) self.assertEqual(len(removed), 1) self.assertEqual(kept[0]["src"], "Goodbye") def test_a_target_held_out_for_another_language_does_not_match(self): keys = {"als": {evalc.norm_key("hallo")}} records = [{"tl": "bar", "sl": "en", "src": "Hello", "trg": "Hallo"}] kept, removed = baseline.drop_contamination(records, keys) self.assertEqual((len(kept), len(removed)), (1, 0)) def test_the_same_target_under_a_different_source_is_still_removed(self): """The leak that a pair-keyed filter misses. One reference sentence reached the published baseline paired with a paraphrase or with a different pivot language, and a pair key let it through. A model that has memorised the reference scores just as highly either way. """ keys = {"ia": {evalc.norm_key("Tom evitava Maria.")}} records = [ {"tl": "ia", "sl": "pt", "src": "Tom evitou Maria.", "trg": "Tom evitava Maria."}, {"tl": "ia", "sl": "eo", "src": "Tom evitis Mary.", "trg": "Tom evitava Maria."}, ] kept, removed = baseline.drop_contamination(records, keys) self.assertEqual((len(kept), len(removed)), (0, 2)) def test_eval_keys_are_target_text_not_pairs(self): """The docstring promised target-side keys; the code built pair keys.""" import json import tempfile with tempfile.TemporaryDirectory() as tmp: release = Path(tmp) (release / "languages").mkdir() (release / "languages" / "bar.jsonl").write_text( json.dumps({"tl": "bar", "src": "Hello", "trg": "Hallo"}) + "\n", encoding="utf-8", ) keys = baseline.eval_keys(release) self.assertEqual(keys, {"bar": {evalc.norm_key("Hallo")}}) class MosesArchives(unittest.TestCase): def _zip(self, left_lines, right_lines, left="bar", right="en"): import io import zipfile buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as archive: archive.writestr(f"WikiMatrix.bar-en.{left}", "\n".join(left_lines)) archive.writestr(f"WikiMatrix.bar-en.{right}", "\n".join(right_lines)) return buffer.getvalue() def test_aligned_members_are_paired(self): payload = self._zip(["eins", "zwei"], ["one", "two"]) self.assertEqual( baseline.read_moses_zip(payload, "bar", "en"), [("eins", "one"), ("zwei", "two")] ) def test_mismatched_line_counts_are_refused(self): payload = self._zip(["eins", "zwei"], ["one"]) self.assertEqual(baseline.read_moses_zip(payload, "bar", "en"), []) def test_a_corrupt_archive_yields_nothing_rather_than_raising(self): self.assertEqual(baseline.read_moses_zip(b"not a zip", "bar", "en"), []) def test_one_member_cannot_serve_as_both_sides(self): import io import zipfile buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as archive: archive.writestr("WikiMatrix.bar-en.bar", "eins\nzwei") self.assertEqual(baseline.read_moses_zip(buffer.getvalue(), "bar", "bar"), []) class OpusRecordOrientation(unittest.TestCase): """``src`` must hold the pivot text and ``trg`` the target text. The published baseline had these swapped against their own ``sl``/``tl`` labels for all 1,036,226 records, which additionally defeated the contamination check because it compared the eval target text against the pivot column. """ def _run(self): import io import zipfile buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as archive: archive.writestr("WikiMatrix.bar-de.bar", "Hoibe\nServus") archive.writestr("WikiMatrix.bar-de.de", "Halbes\nHallo") payload = buffer.getvalue() rows = { "bar": {"iso639_3": "bar"}, "de": {"iso639_3": "deu"}, } original_fetch = baseline.fetch original_packages = baseline.opus_packages baseline.fetch = lambda *a, **k: payload baseline.opus_packages = lambda left, right: ( [{"corpus": "WikiMatrix", "url": "x", "version": "1", "license": "cc-by-sa-4.0"}] if (left, right) == ("bar", "de") else [] ) try: return baseline.collect_opus(["bar"], rows, {"bar": ["de"]}, workers=1)[0] finally: baseline.fetch = original_fetch baseline.opus_packages = original_packages def test_src_is_the_pivot_and_trg_is_the_target(self): records = self._run() self.assertEqual(len(records), 2) for record in records: self.assertEqual((record["sl"], record["tl"]), ("de", "bar")) self.assertEqual( [(r["src"], r["trg"]) for r in records], [("Halbes", "Hoibe"), ("Hallo", "Servus")], ) def test_the_target_text_is_never_in_the_source_column(self): target_text = {"Hoibe", "Servus"} for record in self._run(): self.assertNotIn(record["src"], target_text) class PivotSelection(unittest.TestCase): @classmethod def setUpClass(cls): try: cls.rows = pivots.load_rows() except FileNotFoundError: raise unittest.SkipTest("no audit release available") def test_gilaki_reaches_persian_and_mazandarani(self): # Persian is Gilaki's contact language and the one PARME publishes it against, yet # it contributes almost no article cover and is not Gilaki's closest relative. selected = pivots.structural_pivots("glk", self.rows) for code in ("en", "fa", "mzn"): self.assertIn(code, selected, code) def test_bot_stub_partners_are_not_proposed_as_relatives(self): # Cebuano and Swahili overlap Piedmontese only through generated stub articles. selected = pivots.structural_pivots("pms", self.rows) for code in ("ceb", "sw", "te"): self.assertNotIn(code, selected, code) def test_simple_english_is_never_a_separate_pivot(self): for config in ("sco", "frr"): self.assertNotIn("simple", pivots.structural_pivots(config, self.rows)) def test_unrelated_small_language_is_rejected_as_a_pivot(self): for pivot in ("ido", "lfn"): if pivot in self.rows: ok, _why = pivots.acceptable_pivot("als", pivot, self.rows) self.assertFalse(ok, pivot) def test_shortlist_pairs_are_accepted_as_a_direction(self): ok, why = pivots.acceptable_pivot("glk", "mzn", self.rows) self.assertTrue(ok) self.assertIn("under-served", why) def test_classification_overlap_is_a_prefix_not_a_set_intersection(self): # Sharing deep nodes only counts when the whole path down to them agrees. self.assertEqual(pivots.shared_classification_nodes("bar", "bar", self.rows), len(self.rows["bar"]["classification_path"])) class ReleaseIntegrity(unittest.TestCase): """Checks against the built releases, skipped when they are absent.""" @classmethod def setUpClass(cls): evals = sorted((ROOT / "dist" / "eval_corpus").glob("eval_*")) bases = sorted((ROOT / "dist" / "baseline_corpus").glob("baseline_*")) if not evals or not bases: raise unittest.SkipTest("corpora not built") cls.eval_release = evals[-1] cls.baseline_release = bases[-1] cls.eval_manifest = json.loads( (cls.eval_release / "manifest.json").read_text(encoding="utf-8") ) cls.baseline_manifest = json.loads( (cls.baseline_release / "manifest.json").read_text(encoding="utf-8") ) def test_every_eval_record_has_a_source_licence_and_revision(self): for path in (self.eval_release / "languages").glob("*.jsonl"): with path.open(encoding="utf-8") as handle: for line in handle: record = json.loads(line) self.assertTrue(record.get("source"), path.name) self.assertTrue(record.get("licence"), path.name) self.assertTrue(record.get("source_revision"), path.name) def test_no_eval_record_carries_an_empty_side_unless_withheld(self): for path in (self.eval_release / "languages").glob("*.jsonl"): with path.open(encoding="utf-8") as handle: for line in handle: record = json.loads(line) if record.get("text_withheld"): self.assertEqual(record.get("src", ""), "") continue self.assertTrue(record["src"].strip()) self.assertTrue(record["trg"].strip()) def test_no_withheld_source_leaks_its_text(self): """Generalised from the FLORES+ case: every tier-3 source must be textless. FLORES+ is no longer the only source we are not allowed to pass on, so checking it by name would let the next one through unnoticed. """ withheld_sources = { name for name, meta in evalc.SOURCE_META.items() if meta["tier"] == evalc.TIER_REFERENCE } self.assertIn("flores_plus", withheld_sources) seen = set() for path in (self.eval_release / "languages").glob("*.jsonl"): with path.open(encoding="utf-8") as handle: for line in handle: record = json.loads(line) if record.get("source") not in withheld_sources: continue seen.add(record["source"]) with self.subTest(source=record["source"], language=record["tl"]): self.assertEqual(record.get("src") or "", "") self.assertEqual(record.get("trg") or "", "") self.assertTrue(record["text_withheld"]) self.assertEqual(record["licence_tier"], evalc.TIER_REFERENCE) # The row still has to say what it stands for. self.assertTrue(record.get("upstream_rows")) self.assertTrue(seen, "no withheld rows found in the release at all") def test_ids_are_contiguous_within_each_language(self): for path in (self.eval_release / "languages").glob("*.jsonl"): ids = [json.loads(line)["id"] for line in path.read_text(encoding="utf-8").splitlines()] self.assertEqual(ids, list(range(len(ids))), path.name) def test_baseline_shares_the_eval_language_set(self): self.assertEqual(self.baseline_manifest["shortlist_count"], self.eval_manifest["shortlist_count"]) self.assertEqual(self.baseline_manifest["eval_release"], self.eval_release.name) def test_baseline_holds_no_evaluation_pair(self): keys = baseline.eval_keys(self.eval_release) for path in (self.baseline_release / "languages").glob("*.jsonl"): with path.open(encoding="utf-8") as handle: for line in handle: record = json.loads(line) pair = (evalc.norm_key(record["src"]), evalc.norm_key(record["trg"])) self.assertNotIn(pair, keys.get(record["tl"], set()), path.name) def test_subset_names_align_across_both_datasets(self): # A subset name must mean the same language pair in both, or composing a pair's # train and test splits from the two datasets would silently mismatch. eval_pairs = {n for n, e in self.eval_manifest["subsets"].items() if e.get("is_source_subset")} base_pairs = {n for n, e in self.baseline_manifest["subsets"].items() if e.get("is_source_subset")} self.assertTrue(eval_pairs) self.assertTrue(base_pairs) # Tatoeba is in both: the Challenge test split here, OPUS's Tatoeba corpus there. shared = eval_pairs & base_pairs self.assertTrue(shared, "no subset name is common to both datasets") for name in sorted(shared): source, _, language = name.partition("-") for manifest in (self.eval_manifest, self.baseline_manifest): entry = manifest["subsets"][name] self.assertEqual(entry["languages"], [language], name) # A shared name must carry train on one side and test on the other. for name in sorted(shared): self.assertIn("train", self.baseline_manifest["subsets"][name]["splits"], name) self.assertTrue( {"test", "dev"} & set(self.eval_manifest["subsets"][name]["splits"]), name ) def test_baseline_publishes_only_all_and_per_corpus_subsets(self): subsets = self.baseline_manifest["subsets"] aggregates = [n for n, e in subsets.items() if not e.get("is_source_subset")] self.assertEqual(aggregates, ["all"]) # corpus_type survives as a column, so the distinction is still available. self.assertTrue(all("corpus_types" in e for e in subsets.values())) def test_subset_names_say_source_then_language(self): for manifest in (self.eval_manifest, self.baseline_manifest): for name, entry in manifest["subsets"].items(): if not entry.get("is_source_subset"): continue source, sep, language = name.partition("-") self.assertTrue(sep, name) self.assertTrue(source, name) self.assertEqual(entry["languages"], [language], name) def test_both_datasets_expose_an_all_subset(self): for manifest in (self.eval_manifest, self.baseline_manifest): self.assertIn("all", manifest["subsets"]) self.assertEqual( manifest["subsets"]["all"]["records"], sum(e["records"] for n, e in manifest["subsets"].items() if e.get("is_source_subset")), ) def test_no_subset_is_published_empty(self): for manifest in (self.eval_manifest, self.baseline_manifest): for name, entry in manifest["subsets"].items(): self.assertGreater(entry["records"], 0, name) for split, info in entry["splits"].items(): self.assertGreater(info["records"], 0, f"{name}/{split}") def test_subset_parquet_files_exist_and_match_their_counts(self): import pyarrow.parquet as pq for release, manifest in ((self.eval_release, self.eval_manifest), (self.baseline_release, self.baseline_manifest)): for name, entry in sorted(manifest["subsets"].items())[:40]: for split, info in entry["splits"].items(): path = release / info["path"] self.assertTrue(path.exists(), info["path"]) self.assertEqual(pq.read_metadata(path).num_rows, info["records"], info["path"]) def test_withheld_flores_rows_are_in_no_subset(self): # They have no text, so they must not reach a trainable or scorable subset. self.assertEqual( self.eval_manifest["subsets"]["all"]["records"], self.eval_manifest["total_records"], ) def test_every_baseline_corpus_is_classified(self): for summary in self.baseline_manifest["languages"].values(): self.assertNotIn("unclassified", summary["by_corpus_type"]) if __name__ == "__main__": unittest.main() class LadinColumnKeys(unittest.TestCase): """The nested ``translation`` dict is keyed inconsistently across the Ladin repos.""" def test_two_letter_pivot_code_is_recognised(self): """The weather set keys German as ``de``, not ``deu``. Matching only the three-letter spelling dropped all 689 sentences with the reason "no recognisable column pair" -- a silent zero, not a failure. """ target, pivot = evalc.ladin_keys({"lld": "...", "de": "..."}) self.assertEqual((target, pivot), ("lld", "de")) def test_three_letter_pivot_code_is_recognised(self): target, pivot = evalc.ladin_keys({"lld_valbadia": "...", "ita": "..."}) self.assertEqual((target, pivot), ("lld_valbadia", "ita")) def test_an_intra_ladin_pair_yields_no_pivot(self): """Valbadia against Gherdeina is lexicon material, not a pivot pair.""" target, pivot = evalc.ladin_keys({"lld_valbadia": "...", "lld_gherd": "..."}) self.assertIsNotNone(target) self.assertIsNone(pivot) class Gil1000Sentences(unittest.TestCase): """The Top-1000 Gilaki example sentences, collected from the CSV release.""" CSV = ( "id,glk_word,glk_example,fa_word,fa_example,en_word,en_example\n" "1,آ,آ مأمۊد,آقا," "آقا محمود,Mr.,Mr. Mahmoud\n" "2,x,,y,,z,\n" # no Gilaki sentence: contributes nothing "3,w,gilaki only,fa,,en,\n" # pivot sides empty: contributes nothing ).encode("utf-8") def setUp(self): self.rows = pivots.load_rows() self._fetch = evalc.fetch evalc.fetch = lambda url, **kw: self.CSV def tearDown(self): evalc.fetch = self._fetch def records(self): got, _skipped = evalc.collect_gil1000_sentences({"glk"}, self.rows) return got def test_one_row_yields_both_pivot_pairs(self): got = self.records() self.assertEqual({r["sl"] for r in got}, {"fa", "en"}) self.assertEqual({r["tl"] for r in got}, {"glk"}) def test_rows_without_a_gilaki_sentence_are_dropped(self): """The CSV has a headword for every entry but not an example for every one.""" self.assertEqual(len(self.records()), 2) def test_the_gilaki_side_is_the_original(self): """Written in Gilaki first, then rendered into Persian and English. Every other source here translates *out* of the pivot, so leaving ``is_src_orig`` unset would let a reader assume the wrong direction of authorship. """ self.assertTrue(all(r["is_src_orig"] is False for r in self.records())) def test_it_is_marked_as_dictionary_examples_not_prose(self): self.assertTrue(all(r["domain"] == "dictionary_examples" for r in self.records())) def test_copyleft_puts_it_in_the_restricted_tier(self): got = self.records() self.assertTrue(all(r["licence_tier"] == evalc.TIER_RESTRICTED for r in got)) self.assertTrue(all(r["licence_tier"] != evalc.TIER_REFERENCE for r in got)) def test_the_headword_is_kept_so_an_example_can_be_traced_to_its_entry(self): self.assertTrue(all(r["headword"] for r in self.records())) def test_the_upstream_id_is_an_integer(self): """``upstream_id`` is an int64 column and the CSV reader hands back strings.""" self.assertTrue(all(isinstance(r["upstream_id"], int) for r in self.records())) def test_a_language_other_than_gilaki_collects_nothing(self): got, skipped = evalc.collect_gil1000_sentences({"bar"}, self.rows) self.assertEqual((got, skipped), ([], [])) class TargetScript(unittest.TestCase): """A language's records must be in that language's own script. Mixing scripts for one language makes the test set unscorable: chrF and BLEU compare characters, so a Georgian reference and a romanised transliteration of the same Megrelian sentence score as a total miss against each other. """ def test_romanised_megrelian_is_dropped(self): """Tatoeba's Megrelian is part Georgian, part contributor romanisation.""" self.assertLess(evalc.script_share("aucilebelo qobgholanq٦.", {"GEORGIAN"}), evalc.SCRIPT_SHARE) def test_georgian_megrelian_is_kept(self): self.assertEqual(evalc.script_share("ამერიკელეფ ირო იძიცანა.", {"GEORGIAN"}), 1.0) def test_wu_text_with_a_latin_username_is_kept(self): """30% Han and genuinely Wu: a majority test would wrongly drop this.""" share = evalc.script_share("sanchez_:好问题。", {"CJK", "BOPOMOFO"}) self.assertGreaterEqual(share, evalc.SCRIPT_SHARE) self.assertLess(share, 0.5) def test_a_stray_diacritic_does_not_rescue_a_transliteration(self): """A one-character test would keep romanised text containing any native letter.""" self.assertLess(evalc.script_share("a romanised sentence ა", {"GEORGIAN"}), evalc.SCRIPT_SHARE) def test_latin_is_the_default_so_most_languages_need_no_entry(self): for config in ("bar", "als", "nap", "ia", "nv", "sco"): self.assertNotIn(config, evalc.EXPECTED_SCRIPT) self.assertEqual(evalc.DEFAULT_SCRIPT, {"LATIN"}) def test_withheld_rows_survive_having_no_text(self): """Tier-3 rows carry no text at all and must not be filtered out as off-script.""" kept, dropped = evalc.drop_off_script( [{"tl": "xmf", "trg": "", "text_withheld": True}]) self.assertEqual((len(kept), len(dropped)), (1, 0)) def test_the_filter_separates_a_mixed_batch(self): kept, dropped = evalc.drop_off_script([ {"tl": "xmf", "trg": "ამერიკელეფ ირო იძიცანა."}, {"tl": "xmf", "trg": "Menndan shkurnafilo idziren."}, {"tl": "glk", "trg": "مَره اجازه دَهن"}, ]) self.assertEqual(len(kept), 2) self.assertEqual(dropped[0]["trg"], "Menndan shkurnafilo idziren.") class TrimmedColumns(unittest.TestCase): """The release carries translation, provenance and licence columns and nothing else.""" DROPPED = ("intent", "register", "text_domain", "source_url", "redistributable", "withheld_reason", "source_variant", "locality") @classmethod def setUpClass(cls): import pyarrow.parquet as pq cls.release = evalc.DIST / sorted(p.name for p in evalc.DIST.glob("eval_*"))[-1] cls.schema = pq.read_schema(cls.release / "eval.parquet") def test_task_annotations_and_derivable_columns_are_gone(self): for column in self.DROPPED: self.assertNotIn(column, self.schema.names, column) def test_the_columns_that_carry_unique_information_survived(self): for column in ("sl", "tl", "src", "trg", "split", "source", "source_revision", "licence", "licence_tier", "licence_restriction", "domain", "variety", "text_unit", "document_id", "released_as", "source_pair", "upstream_id", "upstream_file", "text_withheld", "upstream_rows"): self.assertIn(column, self.schema.names, column) def test_bouquet_text_domains_were_folded_into_domain(self): """BOUQuET rows used to carry domain="mixed" plus a real text_domain beside it.""" records = [json.loads(line) for line in (self.release / "languages" / "wuu.jsonl").read_text( encoding="utf-8").splitlines()] domains = {r["domain"] for r in records if r["source"] == "bouquet"} self.assertNotIn("mixed", domains) self.assertIn("conversation", domains) def test_bouquet_paragraph_rows_are_still_distinguishable(self): records = [json.loads(line) for line in (self.release / "languages" / "wuu.jsonl").read_text( encoding="utf-8").splitlines()] units = {r.get("text_unit") for r in records if r["source"] == "bouquet"} self.assertEqual(units, {"sentence", "paragraph"}) class MegrelianLanguageCorpus(unittest.TestCase): """Megrelian oral texts with aligned Georgian and English glosses.""" EAF = b""" \xe1\x83\x97\xe1\x83\x94 \xe1\x83\x93\xe1\x83\x9d \xe1\x83\x93\xe1\x83\x90 this t\xc9\x9b """ def setUp(self): self.rows = pivots.load_rows() self._fetch = evalc.fetch def fake(url, **kw): if url == evalc.MLC_INDEX: return b"Download" return self.EAF evalc.fetch = fake def tearDown(self): evalc.fetch = self._fetch def records(self): got, _skipped = evalc.collect_mlc({"xmf"}, self.rows) return got def test_georgian_is_collected_as_a_pivot(self): """The whole point: Megrelian against its closest high-resource relative.""" self.assertIn("ka", {r["sl"] for r in self.records()}) def test_glosses_are_matched_by_reference_not_by_position(self): """The Georgian gloss refers to the second phrase, the English one to the first.""" got = {(r["sl"], r["src"]) for r in self.records()} self.assertIn(("ka", "და"), got) self.assertIn(("en", "this"), got) def test_an_unglossed_phrase_contributes_nothing(self): """Phrase a1 has no Georgian gloss and a2 has no English one.""" self.assertEqual(len(self.records()), 2) def test_the_ipa_transcription_is_not_treated_as_a_translation(self): """A_phrase-gls-xmf-fonipa is the same Megrelian respelt, not another language.""" self.assertNotIn("tɛ", {r["src"] for r in self.records()}) def test_megrelian_is_the_original_side(self): self.assertTrue(all(r["is_src_orig"] is False for r in self.records())) def test_non_commercial_share_alike_is_the_restricted_tier(self): got = self.records() self.assertTrue(all(r["licence_tier"] == evalc.TIER_RESTRICTED for r in got)) self.assertTrue(all("commercial" in r["licence_restriction"] for r in got)) def test_every_record_survives_the_georgian_script_filter(self): kept, dropped = evalc.drop_off_script(self.records()) self.assertEqual(len(dropped), 0) self.assertEqual(len(kept), 2) def test_invalid_utf8_recovers_instead_of_losing_the_text(self): """One upstream file carries bytes that are not valid UTF-8.""" broken = self.EAF.replace(b"this", b"\xff\xfe") root = evalc._eaf_root(broken) self.assertIsNotNone(root.find(".//TIER"))