Download tests_r5eval/test_core.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/tests_r5eval/test_core.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/tests_r5eval/test_core.py
-
curl -L -o test_core.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/tests_r5eval/test_core.py
18 kB
| """Unit tests of r5eval core (hand-made cases with known answers). usage: python -I test_core.py | |
| Exit code 0 only if every test passes; each test prints PASS or FAIL.""" | |
| import hashlib | |
| import os | |
| import random | |
| import sys | |
| import traceback | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, os.path.join(HERE, "..", "src")) | |
| import numpy as np # noqa: E402 | |
| from r5eval import analyse, frozen, lookalike, stats, textnorm # noqa: E402 | |
| from r5eval.align import align_ops, lev_fast, min_cost_line_assignment, op_counts # noqa: E402 | |
| RESULTS = [] | |
| def test(fn): | |
| try: | |
| fn() | |
| RESULTS.append((fn.__name__, True, "")) | |
| print("PASS", fn.__name__) | |
| except Exception: # noqa: BLE001 | |
| RESULTS.append((fn.__name__, False, traceback.format_exc())) | |
| print("FAIL", fn.__name__) | |
| print(traceback.format_exc()) | |
| return fn | |
| def close(a, b, tol=1e-9): | |
| return abs(a - b) <= tol | |
| def t_frozen_files_hash_checked(): | |
| assert frozen.j2.norm(" a \n b ") == "a b" | |
| assert frozen.vlma_pp.fold("a'b") == "aʻb" | |
| p = os.path.join(HERE, "..", "src", "r5eval", "frozen", "scorelib_j2.py") | |
| assert hashlib.sha256(open(p, "rb").read()).hexdigest() == frozen.FROZEN_SHA256["scorelib_j2.py"] | |
| def t_align_tie_break_cases(): | |
| assert align_ops("ab", "ba")[0] == 2 and op_counts(align_ops("ab", "ba")[1]) == (2, 0, 0) | |
| assert op_counts(align_ops("abc", "bcd")[1]) == (0, 1, 1) | |
| assert op_counts(align_ops("", "xy")[1]) == (0, 0, 2) | |
| assert op_counts(align_ops("ab", "b")[1]) == (0, 1, 0) # deletion | |
| assert op_counts(align_ops("b", "ab")[1]) == (0, 0, 1) # insertion | |
| d, ops = align_ops("қазақ", "казак") | |
| assert d == 2 and op_counts(ops) == (2, 0, 0) | |
| d, ops = align_ops("kitten", "sitting") | |
| assert d == 3 and op_counts(ops) == (2, 0, 1) | |
| def t_align_matches_j2_counts_on_random_pairs(): | |
| random.seed(7) | |
| alphabet = "аәбвгғдеёжзийкқлмнңоөпрстуұүфхһцчшщъыіьэюяabc 1,." | |
| for _ in range(4000): | |
| a = "".join(random.choice(alphabet) for _ in range(random.randint(0, 14))) | |
| b = "".join(random.choice(alphabet) for _ in range(random.randint(0, 18))) | |
| d, ops = align_ops(a, b) | |
| dj, sj, dlj, ij = frozen.j2.align(a, b) | |
| assert d == dj and op_counts(ops) == (sj, dlj, ij), (a, b) | |
| # the operation list reproduces both strings | |
| ra = "".join(a[i] for o, i, j in ops if o in "MSD") | |
| rb = "".join(b[j] for o, i, j in ops if o in "MSI") | |
| assert ra == a and rb == b | |
| assert lev_fast(a, b) == d | |
| def t_lev_fast_long_strings_and_token_lists(): | |
| random.seed(3) | |
| for _ in range(60): | |
| a = "".join(random.choice("abcdefg ") for _ in range(random.randint(100, 400))) | |
| b = "".join(random.choice("abcdefg ") for _ in range(random.randint(100, 400))) | |
| assert lev_fast(a, b) == align_ops(a, b)[0] | |
| assert lev_fast(["a", "b", "c"], ["a", "c"]) == 1 | |
| assert lev_fast("", "") == 0 and lev_fast("abc", "") == 3 and lev_fast("", "abc") == 3 | |
| def t_n0_n1_n2_n3(): | |
| assert textnorm.norm(" й\n и ") == "й и" | |
| assert textnorm.n1_key("Қазақ-123!", "kk") == "қазақ123" | |
| assert textnorm.n1_key("İSTANBUL", "tr") == "istanbul" | |
| assert textnorm.n1_key("ILIK", "tr") == "ılık" # Turkic fold: I -> dotless i | |
| assert textnorm.n1_key("ILIK", "kk") == "ilik" | |
| assert textnorm.n1_key("Oʻzbek", "uz_latn") == "oʻzbek" # U+02BB is a letter (Lm), kept | |
| assert textnorm.fold_lower("İSTANBUL ILIK", "tr") == "istanbul ılık" | |
| assert textnorm.fold_lower("İ", "kk") != "i" # default Python lower(): two code points | |
| for ch in ["'", "‘", "’", "ʼ", "ʻ"]: | |
| assert textnorm.fold_apostrophes("o" + ch + "g") == "oʻg" | |
| assert textnorm.fold_apostrophes("abc") == "abc" | |
| def t_scripts(): | |
| assert textnorm.other_script("oʻzbek") is False # J2 other_script() flags this one (RESEVAL finding) | |
| assert textnorm.other_script("слово") is False and textnorm.other_script("word1") is False | |
| assert textnorm.other_script("слово字") is True and textnorm.other_script("كلمة") is True | |
| assert textnorm.is_mixed_script("кaзак") is True # Latin a inside a Cyrillic word | |
| assert textnorm.is_mixed_script("казак") is False and textnorm.is_mixed_script("kazak") is False | |
| assert textnorm.is_mixed_script("123") is False and textnorm.is_mixed_script("а-б.") is False | |
| assert textnorm.is_mixed_script("Қазақстан") is False | |
| assert textnorm.latin_cyrillic_counts("кaзак") == (1, 4) | |
| def t_lookalike_table_and_repair(): | |
| p = lookalike.table_path() | |
| assert open(p, encoding="utf-8").read() == lookalike.table_tsv() | |
| sha_line = open(p.replace(".tsv", ".sha256")).read().split()[0] | |
| assert hashlib.sha256(lookalike.table_tsv().encode("utf-8")).hexdigest() == sha_line | |
| assert lookalike.PARTNER["a"] == "а" and lookalike.PARTNER["а"] == "a" | |
| new, ch = lookalike.repair_label("кiтап", "Cyrl") # Latin i inside a Cyrillic word | |
| assert new == "кітап" and ch == [("кiтап", "кітап")] | |
| new, ch = lookalike.repair_label("ISBN 5 кiтап", "Cyrl") # Latin-only token untouched | |
| assert new == "ISBN 5 кітап" | |
| new, ch = lookalike.repair_label("мəтін", "Cyrl") # Latin schwa inside a Cyrillic word | |
| assert new == "мәтін" | |
| new, ch = lookalike.repair_label("kaзak", "Latn") # Cyrillic з in a Latin word (z is not a table pair): untouched | |
| assert new == "kaзak" and ch == [] | |
| new, ch = lookalike.repair_label("kаzak", "Latn") # Cyrillic а in a Latin word: repaired to Latin a | |
| assert new == "kazak" | |
| assert lookalike.repair_label("слово слово", "Cyrl")[0] == "слово слово" | |
| def feats(ref, hyp, lang="kk", full=True): | |
| b, L, extra = analyse.crop_features(ref, hyp, lang, full=full) | |
| return b, L, extra | |
| def t_crop_features_basic_counts_and_hr(): | |
| b, L, e = feats("слово", "слово слово слово слово слово") | |
| assert b["hr3_den"] == 1 and b["hr3_num"] == 1 and b["loop"] == 1 and b["n_ref"] == 1 | |
| b, L, e = feats("1", "11") | |
| assert b.get("hr3_den", 0) == 0 and b["cer_sum"] == 1.0 and b["ins"] == 1 | |
| b, L, e = feats("слово", "") | |
| assert b["empty_out"] == 1 and b["dist"] == 5 and b["del"] == 5 and b["cer_sum"] == 1.0 | |
| b, L, e = feats("", "abc") # clutter crop: HR1 only | |
| assert b["hr1_den"] == 1 and b["hr1_num"] == 1 and "dist" not in b and "n_ref" not in b | |
| b, L, e = feats("", "") | |
| assert b["hr1_den"] == 1 and "hr1_num" not in b | |
| assert e is None | |
| def t_special_letters_and_collapse(): | |
| b, L, e = feats("қазақ", "казак") | |
| assert L["sl|kk|қ|ref"] == 2 and L["sl|kk|қ|miss"] == 2 and L["sl|kk|қ|collapse"] == 2 | |
| assert "sl|kk|қ|tp" not in L | |
| b, L, e = feats("қазақ", "қазақ") | |
| assert L["sl|kk|қ|tp"] == 2 and "sl|kk|қ|miss" not in L | |
| b, L, e = feats("кітап", "китап") # і -> и | |
| assert L["sl|kk|і|collapse"] == 1 | |
| b, L, e = feats("жаз", "жаз", "kk") | |
| assert not L | |
| b, L, e = feats("мектеп", "мектеп", "kk") | |
| assert not any(k.endswith("|ref") for k in L) | |
| # false alarm: output writes a special letter where the reference has none | |
| b, L, e = feats("кат", "қат") | |
| assert L["sl|kk|қ|fp"] == 1 | |
| def t_uzbek_latin_units_and_other_script(): | |
| b, L, e = feats("oʻzbek", "ozbek", "uz_latn") | |
| assert L["sl|uz_latn|oʻ|ref"] == 1 and L["sl|uz_latn|oʻ|miss"] == 1 and L["sl|uz_latn|oʻ|collapse"] == 1 | |
| assert "other_script_out" not in b | |
| b, L, e = feats("oʻzbek", "oʻzbek", "uz_latn") | |
| assert L["sl|uz_latn|oʻ|tp"] == 1 | |
| b, L, e = feats("gʻoya", "goʻya", "uz_latn") # oʻ written where the reference has o, gʻ lost | |
| assert L["sl|uz_latn|gʻ|miss"] == 1 | |
| def t_case_diacritic_ifamily_turkish(): | |
| b, L, e = feats("Işık", "ışık", "tr") # I -> dotless i is a case error, not an i-family error | |
| assert b["case_err"] == 1 and b.get("ifam_sub", 0) == 0 and b["dist"] == 1 | |
| b, L, e = feats("Işık", "işık", "tr") # I -> i: i-family error, not case | |
| assert b.get("case_err", 0) == 0 and b["ifam_sub"] == 1 | |
| b, L, e = feats("İstanbul", "Istanbul", "tr") # dot lost: diacritic error (missing) and i-family error | |
| assert b["der_num"] == 1 and b["der_missing"] == 1 and b["ifam_sub"] == 1 | |
| b, L, e = feats("çay", "cay", "tr") # cedilla lost | |
| assert b["der_num"] == 1 and b["der_missing"] == 1 and L["sl|tr|ç|collapse"] == 1 | |
| b, L, e = feats("cay", "çay", "tr") # extra cedilla | |
| assert b["der_num"] == 1 and b["der_extra"] == 1 and b.get("der_missing", 0) == 0 | |
| b, L, e = feats("Қазақ", "қазақ", "kk") # case error on a special letter | |
| assert b["case_err"] == 1 and b["dist"] == 1 | |
| # case-insensitive companions use the Turkic fold | |
| b, L, e = feats("IŞIK", "ışık", "tr") | |
| assert b["exact_cf"] == 1 and b["dist_cf"] == 0 | |
| b, L, e = feats("IŞIK", "işik", "tr") | |
| assert b.get("exact_cf", 0) == 0 | |
| def t_digits_punct_apostrophe_homoglyph(): | |
| b, L, e = feats("4,5", "4.5") | |
| assert b["dig_ref"] == 2 and b.get("dig_miss", 0) == 0 and b["punct_ref"] == 1 and b["punct_miss"] == 1 | |
| assert b["digrun_n"] == 1 and b.get("digrun_ok", 0) == 0 | |
| b, L, e = feats("45", "45") | |
| assert b["digrun_n"] == 1 and b["digrun_ok"] == 1 | |
| b, L, e = feats("12", "132") | |
| assert b["dig_ins"] == 1 and b["dig_ref"] == 2 | |
| b, L, e = feats("дата 5", "дата") | |
| assert b["dig_miss"] == 1 | |
| b, L, e = feats("o'g'li", "oʻgʻli", "uz_latn") | |
| assert b["apos_ref"] == 2 and b["apos_miss"] == 2 | |
| b, L, e = feats("кітап", "кiтап") # Cyrillic і written as Latin i: homoglyph substitution and mixed token | |
| assert b["homoglyph_sub"] == 1 and b["mixed_hyp_tokens"] == 1 and b["hyp_tokens"] == 1 | |
| b, L, e = feats("слово", "字词слово") | |
| assert b["other_script_out"] == 1 | |
| def t_word_level_and_fabricated(): | |
| b, L, e = feats("мен үйге бардым", "мен үйге бардым") | |
| assert b["wdist"] == 0 and b["ref_words"] == 3 | |
| b, L, e = feats("мен үйге бардым", "мен бардым") | |
| assert b["wdist"] == 1 and b["wdel"] == 1 | |
| b, L, e = feats("мен үйге бардым", "мен үйге бардым қаламсапқа") # invented long word | |
| assert b["fab_words"] == 1 and b["wdist"] == 1 | |
| b, L, e = feats("мен үйге бардым", "мен үйгэ бардым") # near-miss word is not fabricated | |
| assert b.get("fab_words", 0) == 0 and b["wdist"] == 1 | |
| def t_group_metrics_and_bootstrap_point_values(): | |
| K = 3 | |
| acc = analyse.Acc(K) | |
| rows = [("а", "а", 0), ("бв", "бг", 1), ("где", "гд", 1), ("жзик", "жзик", 2)] | |
| for rep in range(10): # 40 crops, so that no denominator is below the rare-event limit of 30 | |
| for ref, hyp, k in rows: | |
| b, L, e = feats(ref, hyp) | |
| acc.add(["all"], k, b, L) | |
| idx, f = acc.dense("all") | |
| m = analyse.group_metrics(idx, f, K, B=500, compact=False) | |
| assert close(m["cer"]["value"], 2 / 10) # distance 0+1+1+0 over reference length 1+2+3+4 (x10 each) | |
| assert close(m["exact_match"]["value"], 0.5) | |
| assert m["cer"]["lo"] is not None and m["cer"]["lo"] <= m["cer"]["value"] + 1e-12 <= m["cer"]["hi"] + 2e-12 | |
| assert close(m["sub_rate"]["value"], 1 / 10) and close(m["del_rate"]["value"], 1 / 10) | |
| assert m["cer"]["num"] == 20 and m["cer"]["den"] == 100 | |
| def t_bootstrap_is_deterministic_and_paired_arms_share_resamples(): | |
| a = stats.boot_matmul(np.arange(5), np.arange(10, dtype=float).reshape(5, 2), 5, B=200) | |
| b = stats.boot_matmul(np.arange(5), np.arange(10, dtype=float).reshape(5, 2), 5, B=200) | |
| assert np.array_equal(a, b) | |
| # identical arms: the paired difference is exactly zero everywhere | |
| num = np.array([3.0, 5.0, 2.0, 8.0]) | |
| den = np.array([40.0, 50.0, 30.0, 60.0]) | |
| r = stats.paired_ratio_difference(num, den, num, den, B=500) | |
| assert r["d_rel"] == 0.0 and r["d_rel_ci95"] == [0.0, 0.0] and r["prob_improvement"] == 0.0 | |
| # a clearly better system | |
| r = stats.paired_ratio_difference(num * 0.5, den, num, den, B=2000) | |
| assert close(r["d_rel"], -0.5) and r["d_rel_ci95"][1] < 0 and r["p_better"] < 0.01 and r["prob_improvement"] == 1.0 | |
| def t_holm_known_example(): | |
| h = stats.holm_adjust({"a": 0.01, "b": 0.04, "c": 0.03, "d": 0.02}, 0.05) | |
| assert h["a"]["reject"] is True and h["a"]["threshold"] == 0.05 / 4 | |
| assert h["d"]["reject"] is False # 0.02 > 0.05/3: Holm stops here | |
| assert h["c"]["reject"] is False and h["b"]["reject"] is False | |
| h = stats.holm_adjust({"a": 0.001, "b": 0.012, "c": 0.02}, 0.05) | |
| assert all(h[k]["reject"] for k in "abc") # 0.001<=.05/3, 0.012<=.05/2, 0.02<=.05/1 | |
| assert stats.holm_adjust({"a": 0.2}, 0.05)["a"]["reject"] is False | |
| def t_ece_and_risk_coverage(): | |
| conf = [0.9] * 1500 | |
| correct = [1, 0] * 750 # every one of the 15 equal-mass bins holds an alternating run: accuracy 0.5, confidence 0.9 | |
| assert close(stats.ece_equal_mass(conf, correct), 0.4) | |
| assert close(stats.ece_equal_width(conf, correct), 0.4) | |
| assert close(stats.ece_equal_mass([1.0] * 4, [1, 1, 1, 1]), 0.0) | |
| # perfectly ordered confidence: risk rises with coverage | |
| conf = np.linspace(0.99, 0.01, 100) | |
| dist = np.zeros(100) | |
| dist[80:] = 3.0 | |
| reflen = np.full(100, 5.0) | |
| risk, aurc = stats.risk_coverage(conf, dist, reflen) | |
| assert risk[0] == 0.0 and risk[15] == 0.0 and risk[-1] > risk[15] and close(risk[-1], dist.sum() / reflen.sum()) | |
| assert np.all(np.diff(risk) >= -1e-12) | |
| # an uninformative ordering gives a flat curve at the overall CER | |
| rng = np.random.default_rng(1) | |
| conf = rng.random(2000) | |
| dist = rng.integers(0, 2, 2000).astype(float) | |
| risk, aurc = stats.risk_coverage(conf, dist, np.ones(2000)) | |
| assert abs(risk[-1] - dist.mean()) < 1e-9 and abs(risk[5] - dist.mean()) < 0.06 | |
| def t_quantile_ci_and_rare_event_rule(): | |
| v = np.arange(100, dtype=float) / 100.0 | |
| cl = np.arange(100) % 10 | |
| q = stats.quantiles_ci(v, cl, 10, qs=(0.5, 0.9), B=300, chunk=100) | |
| assert close(q["q0.5"]["value"], np.quantile(v, 0.5)) and q["q0.5"]["lo"] <= q["q0.5"]["hi"] | |
| assert stats.rare_event(3, 29) is True and stats.rare_event(3, 30) is False | |
| K = 2 | |
| acc = analyse.Acc(K) | |
| for k in (0, 1): | |
| b, L, e = feats("a", "b") | |
| acc.add(["all"], k, b, L) | |
| idx, f = acc.dense("all") | |
| m = analyse.group_metrics(idx, f, K, B=100) | |
| assert m["cer"]["rare"] is True and m["cer"]["value"] is None and m["cer"]["num"] == 2.0 and m["cer"]["den"] == 2.0 | |
| def t_paper_metrics_n4_and_n5_match_the_reference_checks(): | |
| # RESEVAL work/eval_reference_checks_out.txt: on these four pairs the HTR-Flor style CER is 0.2394 and the HKR 'CER Lev' 24.75 percent | |
| toy = [("Қазақ", "қазак"), ("ab", "abcdef"), ("тіл", "тіл"), ("Шёл человек", "Шел человек")] | |
| n4 = n5 = ser = 0.0 | |
| for r, h in toy: | |
| b, L, e = feats(r, h) | |
| n4 += b.get("n4_cer_sum", 0.0) | |
| n5 += b.get("n5_cerlev_sum", 0.0) | |
| ser += b.get("n4_ser", 0) | |
| assert abs(n4 / 4 - 0.2394) < 5e-5, n4 / 4 | |
| assert abs(n5 / 4 - 24.75) < 1e-9, n5 / 4 | |
| assert ser == 3 # three of the four pairs still differ after lower-casing (қ/к, ab/abcdef, ё/е) | |
| def t_scoring_hash_ignores_reporting_modules(): | |
| """A change of the report cards, the verdict, the selection or the summary must not force a re-score; a change of a scoring module must.""" | |
| import importlib | |
| import shutil | |
| import tempfile | |
| d = tempfile.mkdtemp(prefix="r5eval_hash_") | |
| shutil.copytree(os.path.join(HERE, "..", "src", "r5eval"), os.path.join(d, "r5eval"), ignore=shutil.ignore_patterns("__pycache__")) | |
| sys.path.insert(0, d) | |
| saved = {k: v for k, v in sys.modules.items() if k == "r5eval" or k.startswith("r5eval.")} | |
| for k in saved: | |
| del sys.modules[k] | |
| try: | |
| pkg = importlib.import_module("r5eval") | |
| a, b = pkg.code_sha256(), pkg.report_code_sha256() | |
| with open(os.path.join(d, "r5eval", "cards.py"), "a") as f: | |
| f.write("\n# a change in a reporting module\n") | |
| with open(os.path.join(d, "r5eval", "verdictlib.py"), "a") as f: | |
| f.write("\n# another one\n") | |
| assert pkg.code_sha256() == a and pkg.report_code_sha256() != b | |
| with open(os.path.join(d, "r5eval", "align.py"), "a") as f: | |
| f.write("\n# a change in a scoring module\n") | |
| assert pkg.code_sha256() != a | |
| finally: | |
| sys.path.remove(d) | |
| for k in [k for k in sys.modules if k == "r5eval" or k.startswith("r5eval.")]: | |
| del sys.modules[k] | |
| sys.modules.update(saved) | |
| shutil.rmtree(d, ignore_errors=True) | |
| def t_min_cost_line_assignment_m29(): | |
| cost, pairs = min_cost_line_assignment(["аб", "вг"], ["вг", "аб"]) | |
| assert cost == 0 and sorted(pairs) == [(0, 1), (1, 0)] | |
| cost, pairs = min_cost_line_assignment(["аб", "вг"], ["вг", "аб", "xyz"]) # an invented line is charged in full | |
| assert cost == 3 | |
| cost, pairs = min_cost_line_assignment(["аб", "вг"], ["абвг"]) # merged lines are charged | |
| assert cost == 4 | |
| cost, pairs = min_cost_line_assignment(["аб", "вг"], []) | |
| assert cost == 4 | |
| cost, pairs = min_cost_line_assignment([], ["abc"]) | |
| assert cost == 3 | |
| if __name__ == "__main__": | |
| bad = [r for r in RESULTS if not r[1]] | |
| print("tests: %d passed, %d failed" % (len(RESULTS) - len(bad), len(bad))) | |
| sys.exit(1 if bad else 0) | |