turkic-ocr-code / tests_r5eval /test_curve.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
6.76 kB
"""Tests of build_curve_set.py on synthetic manifests. usage: python -I test_curve.py"""
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
BUILD = os.path.join(HERE, "..", "scripts", "r5eval", "build_curve_set.py")
LANGS = ["kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"]
LATIN = {"uz_latn", "tr", "az", "tk"}
RESULTS = []
W = {}
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
def multi_lang(path, name, per_lang, kind, clutter=False, split="val", skip=()):
rows = []
for lang in LANGS:
if lang in skip:
continue
rows += sw.make_manifest(path + "." + lang, "%s_%s" % (name, lang), 10, per_lang // 10, split=split, lang=lang,
script="Latn" if lang in LATIN else "Cyrl", kind=kind, unit="line", clutter=clutter, seed=hash(lang) % 100)
os.remove(path + "." + lang)
with open(path, "w", encoding="utf-8", newline="") as f:
extra_col = "typed" in name or name == "tv" # a producer with one extra column: the builder keeps the ten shared columns
f.write("\t".join(sw.HDR + (["font_id"] if extra_col else [])) + "\n")
for r in rows:
f.write("\t".join([r[c] for c in sw.HDR] + (["fontX"] if extra_col else [])) + "\n")
def run(*extra):
p = subprocess.run([sys.executable, "-I", BUILD, "--manifests", W["man"], "--registry", W["reg"]] + list(extra), capture_output=True, text=True)
return p
def rows(path):
t = open(path, encoding="utf-8").read().rstrip("\n").split("\n")
return [dict(zip(t[0].split("\t"), l.split("\t"))) for l in t[1:]]
@test
def t_partial_build_then_complete_build():
root = tempfile.mkdtemp(prefix="r5eval_curve_")
W["root"], W["man"], W["reg"] = root, os.path.join(root, "manifests"), os.path.join(root, "evalsets.json")
os.makedirs(W["man"])
sw.make_manifest(os.path.join(W["man"], "kohtd_lmtune.tsv"), "lm", 50, 10, seed=3) # 500 rows
sw.write_registry(W["reg"], [{"name": "V1", "manifest": "x", "split": "val", "locked": False}])
p = run()
assert p.returncode == 0, p.stderr[-1500:]
r1 = rows(os.path.join(W["man"], "curve_v1.tsv"))
assert len(r1) == 500
info = json.load(open(os.path.join(root, "curve_v1_info.json")))
assert info["complete"] is False and set(info["missing_parts"]) == {"synth_hand_val", "synth_typed_val", "print_real_val", "synth_clutter_val"}
reg = json.load(open(W["reg"]))
cv = [s for s in reg["sets"] if s["name"] == "curve_v1"]
assert len(cv) == 1 and cv[0]["locked"] is False and cv[0]["split"] == "val" and cv[0]["n_rows"] == 500 and len(reg["sets"]) == 2
# the other parts appear (print_real_val still missing for one language)
multi_lang(os.path.join(W["man"], "synth_hand_val.tsv"), "hv", 200, "hand_synth")
multi_lang(os.path.join(W["man"], "synth_typed_val.tsv"), "tv", 100, "typed_synth")
multi_lang(os.path.join(W["man"], "synth_clutter_val.tsv"), "cv", 200, "clutter", clutter=True)
multi_lang(os.path.join(W["man"], "print_real_val.tsv"), "pv", 60, "typed_real", skip=("sah",))
p = run()
assert p.returncode == 0, p.stderr[-1500:]
r2 = rows(os.path.join(W["man"], "curve_v1.tsv"))
assert [r["id"] for r in r2[:500]] == [r["id"] for r in r1] # earlier part unchanged
by = {}
for r in r2[500:]:
by.setdefault(r["source"], {}).setdefault(r["lang"], 0)
by[r["source"]][r["lang"]] += 1
hand = [r for r in r2 if r["kind"] == "hand_synth"]
typed = [r for r in r2 if r["kind"] == "typed_synth"]
prn = [r for r in r2 if r["kind"] == "typed_real"]
cl = [r for r in r2 if r["kind"] == "clutter"]
assert len(hand) == 500 and all(sum(1 for r in hand if r["lang"] == l) == 50 for l in LANGS)
assert len(typed) == 200 and all(sum(1 for r in typed if r["lang"] == l) == 20 for l in LANGS)
assert len(prn) == 180 and not any(r["lang"] == "sah" for r in prn) # sah missing in print_real_val: skipped
assert len(cl) == 100 and all(r["text"] == "" for r in cl)
assert all(r["split"] == "val" for r in r2) and len({r["id"] for r in r2}) == len(r2)
info = json.load(open(os.path.join(root, "curve_v1_info.json")))
assert info["complete"] is True and info["rows"] == len(r2)
assert [x for x in info["parts"] if x["part"] == "print_real_val"][0]["short_languages"] == {"sah": 0}
# deterministic: a second run gives the identical file
import hashlib
sha1 = hashlib.sha256(open(os.path.join(W["man"], "curve_v1.tsv"), "rb").read()).hexdigest()
run()
sha2 = hashlib.sha256(open(os.path.join(W["man"], "curve_v1.tsv"), "rb").read()).hexdigest()
assert sha1 == sha2
@test
def t_register_only_restores_entry_after_registry_rewrite():
sw.write_registry(W["reg"], [{"name": "V1", "manifest": "x", "split": "val", "locked": False}]) # DATA's script rewrote the registry
p = run("--register-only")
assert p.returncode == 0, p.stderr[-1500:]
reg = json.load(open(W["reg"]))
assert [s["name"] for s in reg["sets"]] == ["V1", "curve_v1"]
@test
def t_refuses_non_validation_rows():
multi_lang(os.path.join(W["man"], "synth_typed_val.tsv"), "tv", 100, "typed_synth", split="test")
p = run()
assert p.returncode != 0 and "not split val" in (p.stderr + p.stdout)
multi_lang(os.path.join(W["man"], "synth_typed_val.tsv"), "tv", 100, "typed_synth") # restore a valid source
@test
def t_final_build_freezes_the_set():
p = run("--final")
assert p.returncode == 0, p.stderr[-1500:]
fz = json.load(open(os.path.join(W["root"], "curve_v1_frozen.json")))
assert fz["rows"] == 500 + 500 + 200 + 180 + 100 and fz["rows_by_part"]["V1lm"] == 500 and fz["missing_parts_left_out_for_good"] == []
import hashlib
assert fz["manifest_sha256"] == hashlib.sha256(open(os.path.join(W["man"], "curve_v1.tsv"), "rb").read()).hexdigest()
p = run()
assert p.returncode != 0 and "frozen" in (p.stderr + p.stdout)
assert run("--register-only").returncode == 0 # the registry entry can still be restored after DATA rewrites it
if __name__ == "__main__":
shutil.rmtree(W.get("root", "/nonexistent"), ignore_errors=True)
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)