"""Tests of the K_train builder and the P2 / P2b / P2_literal slice flags (clarification G3). usage: python -I test_ktrain.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, os.path.join(HERE, "..", "src")) from r5eval import ktrain # noqa: E402 BUILD = os.path.join(HERE, "..", "scripts", "r5eval", "build_ktrain.py") HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] 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 def write_manifest(path, rows): with open(path, "w", encoding="utf-8", newline="") as f: f.write("\t".join(HDR) + "\n") for i, (text, lang, kind, split) in enumerate(rows): f.write("\t".join(["x:%d" % i, "/nonexistent.jpg", text, lang, "Cyrl", kind, "src", split, "g%d" % i, "line"]) + "\n") W = {} @test def t_build_and_flags(): root = tempfile.mkdtemp(prefix="r5eval_kt_") W["root"] = root man = os.path.join(root, "m") os.makedirs(man) write_manifest(os.path.join(man, "real.tsv"), [ ("Қазақ тілі", "kk", "hand_real", "train"), # tokens қазақ, тілі and whole key қазақтілі ("кітап", "kk", "hand_real", "train"), ("секретнегізгі", "kk", "hand_real", "val"), # validation row: must be ignored ]) write_manifest(os.path.join(man, "synth.tsv"), [ ("үй жануарлары", "kk", "hand_synth", "train"), ("ILIK hava", "tr", "hand_synth", "train"), ("oʻzbek tili", "uz_latn", "hand_synth", "train"), ("", "kk", "clutter", "train"), ]) write_manifest(os.path.join(man, "typed.tsv"), [ ("баспа мәтін", "kk", "typed_synth", "train"), ("Typed line", "tr", "typed_synth", "train"), ("Басылым мәтіні", "kk", "typed_real", "train"), # PRINT's real printed lines: training text, so inside the P2b set ("сканерленген жол", "kk", "typed_real_ocr", "train"), ]) gen = os.path.join(root, "gen", "train", "kk") os.makedirs(gen) with open(os.path.join(gen, "sentences.tsv"), "w", encoding="utf-8") as f: f.write("wiki:1\tГенератор сөйлемі мұнда жазылған.\n") mix = os.path.join(root, "mix_v1.yaml") with open(mix, "w", encoding="utf-8") as f: f.write("mix:\n groups:\n - name: hand\n share: 0.8\n members:\n" " - {name: real, manifest: %s/real.tsv, share: 0.5}\n" " - {name: synth_tr_only, manifest: %s/synth.tsv, share: 0.5, filter: {lang: tr}}\n" " - {name: synth_other, manifest: %s/synth.tsv, share: 0.5, filter: {lang: kk}}\n" " - {name: synth_uz, manifest: %s/synth.tsv, share: 0.5, filter: {lang: uz_latn}}\n" " - name: typed\n share: 0.2\n manifest: %s/typed.tsv\n" % ((man,) * 5)) out = os.path.join(root, "p2") p = subprocess.run([sys.executable, "-I", BUILD, "--mix", mix, "--out", out, "--extra-text", os.path.join(gen, "sentences.tsv")], capture_output=True, text=True) assert p.returncode == 0, p.stderr[-1500:] kt = ktrain.load(os.path.join(out, "ktrain_manifest.json")) W["kt"], W["out"], W["mix"], W["gen"] = kt, out, mix, gen f = kt.flags # seen as a whole label or as a token of a hand training label assert f("Қазақ тілі", "kk") == {"P2": False, "P2b": False, "P2_literal": False} assert f("тілі", "kk")["P2"] is False # token of a hand label assert f("тілі", "kk")["P2_literal"] is True # not a whole hand label: literal variant calls it unseen assert f("кітап", "kk") == {"P2": False, "P2b": False, "P2_literal": False} # only in a typed label or in the generator text: unseen in handwriting, seen in some text assert f("баспа", "kk") == {"P2": True, "P2b": False, "P2_literal": True} assert f("жазылған", "kk")["P2"] is True and f("жазылған", "kk")["P2b"] is False assert f("басылым", "kk") == {"P2": True, "P2b": False, "P2_literal": True} # token of a typed_real label assert f("жол", "kk")["P2b"] is False # token of a typed_real_ocr label # nowhere assert f("қалам", "kk") == {"P2": True, "P2b": True, "P2_literal": True} # validation row was ignored assert f("секретнегізгі", "kk")["P2"] is True # Turkic fold: train "ILIK" (tr) is the key of dotless ılık assert f("ılık", "tr")["P2"] is False and f("ILIK", "tr")["P2"] is False assert f("ilik", "tr")["P2"] is True # dotted i is a different word in Turkish # the filter {lang: tr} kept the tr row; "hava" is a token of it assert f("hava", "tr")["P2"] is False # Uzbek Latin with U+02BB kept as a letter assert f("oʻzbek", "uz_latn")["P2"] is False # empty key (punctuation only) belongs to no slice assert f("-", "kk") == {"P2": False, "P2b": False, "P2_literal": False} # clutter rows add nothing assert "" not in kt.hand_keys @test def t_rebuild_gives_identical_hashes_and_check_detects_edit(): out2 = os.path.join(W["root"], "p2b") man2 = ktrain.build(W["mix"], out2, [os.path.join(W["gen"], "sentences.tsv")]) man1 = json.load(open(os.path.join(W["out"], "ktrain_manifest.json"))) assert man2["ktrain_sha256"] == man1["ktrain_sha256"] and man2["set_sha256"] == man1["set_sha256"] # a hand-edited key file is caught by load(verify=True) import gzip p = os.path.join(out2, "ktrain_hand_keys.txt.gz") keys = gzip.open(p, "rt", encoding="utf-8").read().split("\n") with gzip.open(p, "wt", encoding="utf-8") as f: f.write("\n".join(keys + ["extra"])) try: ktrain.load(os.path.join(out2, "ktrain_manifest.json")) raise AssertionError("edit not detected") except SystemExit: pass @test def t_sha_mismatch_in_mix_yaml_stops_build(): mix = os.path.join(W["root"], "mix_bad.yaml") man = os.path.join(W["root"], "m") with open(mix, "w", encoding="utf-8") as f: f.write("mix:\n members:\n - {name: real, manifest: %s/real.tsv, share: 1.0, sha256: 0000}\n" % man) try: ktrain.build(mix, os.path.join(W["root"], "p2c"), []) raise AssertionError("sha mismatch not detected") except SystemExit: pass @test def t_builder_refuses_validation_or_test_text(): p = subprocess.run([sys.executable, "-I", BUILD, "--mix", W["mix"], "--out", os.path.join(W["root"], "p2d"), "--extra-text", "/x/pagesynth_text_split/test/kk/sentences.tsv"], capture_output=True, text=True) assert p.returncode != 0 and "refusing" in (p.stderr + p.stdout) 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)