Download tests_r5eval/test_cli.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/tests_r5eval/test_cli.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/tests_r5eval/test_cli.py
-
curl -L -o test_cli.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/tests_r5eval/test_cli.py
15.1 kB
| """End-to-end test of score.py on a synthetic world. usage: python -I test_cli.py [workdir] | |
| Checks: scoring and score-file content, hand-computed CER, post-processing counts from raw output, incremental behaviour, refusal of | |
| locked sets (the manifest of the locked set does not exist, so any attempt to open it would be visible), the gate flag and file, | |
| registry names with parentheses, ragged and incomplete prediction files, reference mismatch stop, summary.tsv.""" | |
| import json | |
| import os | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import traceback | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| import synth_world as sw # noqa: E402 | |
| SCORE = os.path.join(HERE, "..", "scripts", "r5eval", "score.py") | |
| RESULTS = [] | |
| def test(fn): | |
| try: | |
| fn() | |
| RESULTS.append((fn.__name__, True)) | |
| print("PASS", fn.__name__) | |
| except Exception: # noqa: BLE001 | |
| RESULTS.append((fn.__name__, False)) | |
| print("FAIL", fn.__name__) | |
| print(traceback.format_exc()) | |
| return fn | |
| W = {} | |
| def run(args, expect_rc=None): | |
| cmd = [sys.executable, "-I", SCORE, "--registry", W["reg"], "--preds", W["preds"], "--out", W["out"], "--B", "200", | |
| "--settle", "0", "--ktrain", os.path.join(W["root"], "no_ktrain.json"), "--gate-file", W["gate"]] + args | |
| p = subprocess.run(cmd, capture_output=True, text=True) | |
| if expect_rc is not None: | |
| assert p.returncode == expect_rc, (p.returncode, p.stdout[-800:], p.stderr[-1500:]) | |
| return p | |
| def load(rel): | |
| return json.load(open(os.path.join(W["out"], rel), encoding="utf-8")) | |
| def t_build_world(): | |
| root = sys.argv[1] if len(sys.argv) > 1 else tempfile.mkdtemp(prefix="r5eval_cli_") | |
| shutil.rmtree(root, ignore_errors=True) | |
| os.makedirs(root) | |
| W["root"] = root | |
| W["preds"], W["out"] = os.path.join(root, "preds"), os.path.join(root, "scores") | |
| W["gate"] = os.path.join(root, "RULE", "test_pass_started.txt") | |
| W["reg"] = os.path.join(root, "evalsets.json") | |
| man = os.path.join(root, "manifests") | |
| v1 = sw.make_manifest(os.path.join(man, "kohtd_screen_v1.tsv"), "v1", 30, 10, seed=1) | |
| cl = sw.make_manifest(os.path.join(man, "synth_clutter_val.tsv"), "cl", 10, 10, clutter=True, kind="clutter", unit="line") | |
| sw.write_registry(W["reg"], [ | |
| {"name": "V1", "manifest": os.path.join(man, "kohtd_screen_v1.tsv"), "split": "val", "locked": False, "group_unit": "form"}, | |
| {"name": "synth_clutter_val", "manifest": os.path.join(man, "synth_clutter_val.tsv"), "split": "val", "locked": False}, | |
| {"name": "kohtd_test (P1)", "manifest": os.path.join(man, "kohtd_test.tsv"), "split": "test", "locked": True}, | |
| ]) | |
| sw.write_preds(os.path.join(W["preds"], "A1", "short", "V1.tsv"), v1, 0.10, seed=2) | |
| sw.write_meta(os.path.join(W["preds"], "A1", "short", "meta.json"), conf_logprob=False, peak_mem_reserved_batch1_GiB=2.0) | |
| sw.write_preds(os.path.join(W["preds"], "B1", "short", "V1.tsv"), v1, 0.05, seed=3, raw_wrap_rate=0.2) | |
| sw.write_meta(os.path.join(W["preds"], "B1", "short", "meta.json")) | |
| sw.write_preds(os.path.join(W["preds"], "A1", "short", "synth_clutter_val.tsv"), cl, 0.0, clutter_rate=0.0, with_conf=False) | |
| sw.write_preds(os.path.join(W["preds"], "B1", "short", "synth_clutter_val.tsv"), cl, 0.0, clutter_rate=0.3, seed=5, with_conf=False) | |
| # a locked test set whose manifest does not exist: scoring must refuse it without touching the manifest | |
| open(os.path.join(W["preds"], "A1", "short", "kohtd_test.tsv"), "w").write("id\tref\thyp\nx\ta\ta\n") | |
| # a smoke directory and an unregistered file | |
| os.makedirs(os.path.join(W["preds"], "smoke_arm", "short")) | |
| open(os.path.join(W["preds"], "smoke_arm", "short", "V1.tsv"), "w").write("id\tref\thyp\n") | |
| open(os.path.join(W["preds"], "A1", "short", "unknown_set.tsv"), "w").write("id\tref\thyp\n") | |
| W["v1_rows"] = v1 | |
| def t_first_run_scores_validation_and_refuses_locked(): | |
| p = run(["--workers", "2"], expect_rc=0) | |
| log = load("run_log.json") | |
| assert len(log["scored"]) == 4, log | |
| assert [r["set"] for r in log["refused_locked"]] == ["kohtd_test"], log["refused_locked"] | |
| assert len(log["unmatched"]) == 1 and log["unmatched"][0].endswith("unknown_set.tsv") | |
| assert any("smoke_arm" in d for d in log["skipped_dirs"]) | |
| assert not os.path.exists(os.path.join(W["out"], "A1", "short", "kohtd_test.json")) | |
| assert os.path.exists(os.path.join(W["out"], "summary.tsv")) | |
| def t_score_file_values_match_hand_computation(): | |
| sc = load("A1/short/V1.json") | |
| assert sc["status"] == "scored" and sc["locked"] is False and sc["registry_name"] == "V1" | |
| assert sc["coverage"]["complete"] and sc["coverage"]["scored_rows"] == 300 | |
| # recompute the pooled CER independently with the frozen J2 library | |
| sys.path.insert(0, os.path.join(HERE, "..", "src")) | |
| from r5eval import frozen | |
| d = n = 0 | |
| for line in open(os.path.join(W["preds"], "A1", "short", "V1.tsv"), encoding="utf-8").read().split("\n")[1:]: | |
| if not line: | |
| continue | |
| p = line.split("\t") | |
| d += frozen.j2.align(frozen.j2.norm(p[1]), frozen.j2.norm(p[2]))[0] | |
| n += len(frozen.j2.norm(p[1])) | |
| m = sc["profiles"]["plain"]["groups"]["all"]["metrics"]["cer"] | |
| assert abs(m["value"] - d / n) < 1e-12 and m["num"] == d and m["den"] == n | |
| assert m["lo"] <= m["value"] <= m["hi"] or abs(m["lo"] - m["value"]) < 0.05 | |
| assert sc["profiles"]["plain"]["groups"]["all"]["n_clusters"] == 30 | |
| assert "macro" in sc["profiles"]["plain"] and "distribution" in sc["profiles"]["plain"] | |
| assert "calibration" in sc["profiles"]["plain"] and sc["set_info"]["conf_kind"] == "probability" | |
| # special letters were counted for kk | |
| mm = sc["profiles"]["plain"]["groups"]["all"]["metrics"] | |
| assert any(k.startswith("sl|kk|қ|miss_rate") for k in mm) | |
| def t_raw_output_gives_postprocessing_counts_and_vlm_confidence_kind(): | |
| sc = load("B1/short/V1.json") | |
| pp = sc["postproc"] | |
| assert pp["pp_source"] == "raw" and pp["rows_with_raw_output"] == 300 | |
| assert pp["outputs_changed_by_wrapper_stripping"] > 0 # about 20% of 300 outputs were fenced in the raw file | |
| assert pp["outputs_changed_by_postproc_total"] >= pp["outputs_changed_by_wrapper_stripping"] - 1 | |
| plain = sc["profiles"]["plain"]["groups"]["all"]["metrics"]["cer"]["value"] | |
| j2s = sc["profiles"]["j2strip"]["groups"]["all"]["metrics"]["cer"]["value"] | |
| assert abs(plain - j2s) < 1e-12 # the TSV hyp is the stripped text; fences only exist in the raw file, so stripping raw gives the same CER | |
| assert sc["set_info"]["conf_kind"] == "logprob" | |
| a1 = load("A1/short/V1.json") | |
| assert a1["postproc"]["pp_source"] == "tsv" and a1["postproc"]["outputs_changed_by_wrapper_stripping"] == 0 | |
| def t_clutter_hr1(): | |
| a = load("A1/short/synth_clutter_val.json")["profiles"]["plain"]["groups"]["all"]["metrics"] | |
| b = load("B1/short/synth_clutter_val.json")["profiles"]["plain"]["groups"]["all"]["metrics"] | |
| assert a["hr1"]["value"] == 0.0 and a["hr1"]["den"] == 100 | |
| assert 0.1 < b["hr1"]["value"] < 0.5 and b["hr1"]["num"] > 0 | |
| assert "cer" not in a # clutter crops never enter CER (convention C4) | |
| def t_incremental_second_run_scores_nothing_and_modified_file_is_rescored(): | |
| p = run(["--workers", "1"], expect_rc=0) | |
| log = load("run_log.json") | |
| assert len(log["scored"]) == 0 and log["up_to_date"] == 4 | |
| path = os.path.join(W["preds"], "A1", "short", "V1.tsv") | |
| txt = open(path, encoding="utf-8").read().replace("қазақ", "казак", 1) if "қазақ" in open(path, encoding="utf-8").read() else open(path, encoding="utf-8").read() | |
| open(path, "w", encoding="utf-8").write(txt + "") | |
| sw.write_preds(path, W["v1_rows"], 0.12, seed=9) | |
| run(["--workers", "1"], expect_rc=0) | |
| log = load("run_log.json") | |
| assert len(log["scored"]) == 1 and log["up_to_date"] == 3 | |
| def t_test_pass_flag_alone_does_not_open_locked_sets(): | |
| run(["--test-pass"], expect_rc=0) | |
| log = load("run_log.json") | |
| assert log["gate_open"] is False and len(log["refused_locked"]) == 1 | |
| assert not os.path.exists(os.path.join(W["out"], "A1", "short", "kohtd_test.json")) | |
| def t_gate_file_alone_does_not_open_locked_sets(): | |
| os.makedirs(os.path.dirname(W["gate"]), exist_ok=True) | |
| open(W["gate"], "w").write("test pass started (test)\n") | |
| run([], expect_rc=0) # no --test-pass flag | |
| log = load("run_log.json") | |
| assert log["gate_open"] is False and len(log["refused_locked"]) == 1 | |
| os.remove(W["gate"]) | |
| def t_gate_open_scores_locked_set(): | |
| man = os.path.join(W["root"], "manifests", "kohtd_test.tsv") | |
| rows = sw.make_manifest(man, "t1", 20, 10, split="test", seed=4) | |
| sw.write_preds(os.path.join(W["preds"], "A1", "short", "kohtd_test.tsv"), rows, 0.1, seed=6) | |
| os.makedirs(os.path.dirname(W["gate"]), exist_ok=True) | |
| open(W["gate"], "w").write("test pass started (test)\n") | |
| run(["--test-pass"], expect_rc=0) | |
| sc = load("A1/short/kohtd_test.json") | |
| assert sc["locked"] is True and sc["status"] == "scored" and sc["registry_name"] == "kohtd_test (P1)" | |
| assert os.path.exists(os.path.join(W["out"], "A1", "short", "kohtd_test.json")) | |
| # validation summary never lists locked sets | |
| s = open(os.path.join(W["out"], "summary.tsv"), encoding="utf-8").read() | |
| assert "A1\tshort" in s and "B1\tshort" in s | |
| def t_summary_columns(): | |
| lines = open(os.path.join(W["out"], "summary.tsv"), encoding="utf-8").read().strip().split("\n") | |
| hdr = lines[0].split("\t") | |
| assert hdr[:2] == ["arm", "checkpoint"] and "V1_cer_greedy" in hdr and "HR1_clutter_val" in hdr | |
| rows = {l.split("\t")[0]: dict(zip(hdr, l.split("\t"))) for l in lines[1:]} | |
| assert rows["B1"]["V1_n"] == "300" and rows["B1"]["V1_complete"] == "1" | |
| assert float(rows["B1"]["V1_cer_greedy"]) < float(rows["A1"]["V1_cer_greedy"]) | |
| assert rows["B1"]["peak_mem_reserved_gib"] == "9.5" and rows["A1"]["peak_mem_reserved_gib"] == "2" | |
| assert rows["B1"]["images_per_second"] == "55" | |
| assert float(rows["B1"]["HR1_clutter_val"]) > 0 and float(rows["A1"]["HR1_clutter_val"]) == 0.0 | |
| def t_incomplete_ragged_and_mismatching_files(): | |
| # incomplete: only the first 100 rows predicted | |
| p = os.path.join(W["preds"], "A1", "partial", "V1.tsv") | |
| sw.write_preds(p, W["v1_rows"][:100], 0.1, seed=3) | |
| # ragged row appended | |
| open(p, "a", encoding="utf-8").write("badrow\tonly_two_fields\n") | |
| # reference mismatch: a changed reference stops scoring | |
| p2 = os.path.join(W["preds"], "A1", "mismatch", "V1.tsv") | |
| sw.write_preds(p2, W["v1_rows"], 0.1, seed=3, ref_override={W["v1_rows"][0]["id"]: "other text"}) | |
| run([], expect_rc=0) | |
| inc = load("A1/partial/V1.json") | |
| assert inc["status"] == "scored" and inc["coverage"]["scored_rows"] == 100 and inc["coverage"]["missing_ids"] == 200 | |
| assert inc["coverage"]["ragged_rows_skipped"] == 1 and inc["coverage"]["complete"] is False | |
| mm = load("A1/mismatch/V1.json") | |
| assert mm["status"] == "ref_mismatch" and mm["coverage"]["ref_mismatch_rows"] == 1 | |
| def t_file_named_by_registry_name_with_parentheses_reaches_the_summary(): | |
| reg = json.load(open(W["reg"])) | |
| reg["sets"].append({"name": "V1 (screen)", "manifest": os.path.join(W["root"], "manifests", "kohtd_screen_v1.tsv"), "split": "val", "locked": False}) | |
| json.dump(reg, open(W["reg"], "w")) | |
| sw.write_preds(os.path.join(W["preds"], "PN", "short", "V1 (screen).tsv"), W["v1_rows"], 0.08, seed=12) | |
| run([], expect_rc=0) | |
| assert os.path.exists(os.path.join(W["out"], "PN", "short", "V1 (screen).json")) | |
| lines = open(os.path.join(W["out"], "summary.tsv"), encoding="utf-8").read().strip().split("\n") | |
| hdr = lines[0].split("\t") | |
| row = [dict(zip(hdr, l.split("\t"))) for l in lines[1:] if l.startswith("PN\t")][0] | |
| assert row["V1_n"] == "300" and float(row["V1_cer_greedy"]) > 0 | |
| def t_parity_with_vlma_postproc_score_on_wrapped_and_apostrophe_outputs(): | |
| """Our plain and post-processed CER and WER equal VLMA's postproc.score() (the figures its eval_vlm.py writes) on the same rows, when the TSV | |
| hyp is N0 of the raw output as in the real VLMA files. The CER of clutter rows differs by design (convention C4) and is not in this set.""" | |
| import random | |
| sys.path.insert(0, os.path.join(HERE, "..", "src")) | |
| from r5eval import frozen | |
| pp = frozen.vlma_pp | |
| root = W["root"] | |
| man = os.path.join(root, "manifests") | |
| vocab = ["o'zbek", "oʻzbek", "ma’no", "gʻoya", "so‘z", "kitob", "maktab", "oq", "to`g`ri", "shahar"] | |
| rows = sw.make_manifest(os.path.join(man, "pp_check.tsv"), "pc", 25, 8, lang="uz_latn", script="Latn", vocab=vocab, seed=5) | |
| reg = json.load(open(W["reg"])) | |
| reg["sets"].append({"name": "pp_check", "manifest": os.path.join(man, "pp_check.tsv"), "split": "val", "locked": False}) | |
| json.dump(reg, open(W["reg"], "w")) | |
| rnd = random.Random(11) | |
| raws, refs = [], [] | |
| d = os.path.join(W["preds"], "VP", "short") | |
| os.makedirs(d, exist_ok=True) | |
| with open(os.path.join(d, "pp_check.tsv"), "w", encoding="utf-8", newline="") as f, open(os.path.join(d, "pp_check.raw.jsonl"), "w", encoding="utf-8") as g: | |
| f.write("id\tref\thyp\tconf\tconf_min\thit_cap\tn_tokens\n") | |
| for r in rows: | |
| t = r["text"] | |
| form = rnd.choice(["plain", "fence", "tags", "heading", "bold", "apos", "damaged", "empty", "latex", "entity"]) | |
| raw = {"plain": t, "fence": "```text\n" + t + "\n```", "tags": "<text>" + t + "</text>", "heading": "## " + t, "bold": "**" + t + "**", | |
| "apos": t.replace("o'", "oʻ").replace("’", "ʼ"), "damaged": t[1:] + "x", "empty": "", "latex": "$\\text{" + t + "}$", "entity": t + " & x"}[form] | |
| hyp = pp.plain_output(raw) | |
| refs.append(pp.plain_ref(t)) | |
| raws.append(raw) | |
| f.write("\t".join([r["id"], pp.plain_ref(t), hyp, "-0.1", "-0.2", "0", "3"]) + "\n") | |
| g.write(json.dumps({"id": r["id"], "raw": raw, "hit_cap": False}, ensure_ascii=False) + "\n") | |
| sw.write_meta(os.path.join(d, "meta.json")) | |
| run([]) | |
| sc = load("VP/short/pp_check.json") | |
| theirs = pp.score([r["text"] for r in rows], raws) | |
| for prof, key in (("plain", "plain"), ("pp", "pp")): | |
| m = sc["profiles"][prof]["groups"]["all"]["metrics"] | |
| assert abs(m["cer"]["value"] - theirs[key]["cer"]) < 1e-12, (prof, m["cer"]["value"], theirs[key]["cer"]) | |
| assert abs(m["wer"]["value"] - theirs[key]["wer"]) < 1e-12, (prof, m["wer"]["value"], theirs[key]["wer"]) | |
| assert abs(m["exact_match"]["value"] - theirs[key]["exact"]) < 1e-12 | |
| n_changed = sum(1 for x in raws if pp.pp_output(x) != pp.plain_output(x)) | |
| assert sc["postproc"]["outputs_changed_by_postproc_total"] == n_changed and n_changed > 0 and sc["postproc"]["pp_source"] == "raw" | |
| 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) | |