File size: 5,284 Bytes
24aaa76 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | """Test pass 2, amendment 3: M2 (A1, PP-OCRv6 medium long2x) read with LABEL-FREE batching, through the release package
DATA/release/rc1/turkic-ocr-ppocrv6-medium/infer.py (imported, unchanged): crops sorted by image width, batches of 32, 256 extra zero
columns per batch (--sort width --batch-pad 256), CPU float32; one forward pass gives both the greedy CTC output and the gated character
LM output (--decode lm_gated: beam 16, top-6 labels per frame, alpha 0.40, beta 1.00, prune -10, empty greedy output -> empty text).
No reference text is used to order or batch anything; the reference is only copied into the 'ref' column the scorer checks.
Writes <out-root>/A1/long2x_labelfree/<set>.tsv and <out-root>/A1/long2x_labelfree_lm_gated/<set>.tsv (columns id, ref, hyp, conf,
conf_min, hit_cap, n_tokens; conf empty) and a meta.json in each folder.
--smoke: validation only; also prints the micro CER (scorer N0 text, r5eval edit distance) of both outputs and exits 6 unless they are
within 0.001 of the release report's V1 figures (greedy 0.0648, LM and gate 0.0482, records/R5/RELEASE/rc1_report.json).
usage: tp2_a1_labelfree.py --manifest TSV --set NAME --out-root DIR [--gate-file F | --smoke] [--threads 16] [--workers 16]
"""
import os
import sys
REL = "/path/to/TURKIC_OCR_DATA/release/rc1/turkic-ocr-ppocrv6-medium"
sys.path.insert(0, REL)
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
def main():
import argparse
import csv
import hashlib
import json
import time
import unicodedata
from PIL import Image
import infer as rel
from r5eval import textnorm
from r5eval.align import lev_fast
csv.field_size_limit(1 << 30)
ap = argparse.ArgumentParser()
ap.add_argument("--manifest", required=True)
ap.add_argument("--set", required=True)
ap.add_argument("--out-root", required=True)
ap.add_argument("--gate-file", default="")
ap.add_argument("--smoke", action="store_true")
ap.add_argument("--threads", type=int, default=16)
ap.add_argument("--workers", type=int, default=16)
a = ap.parse_args()
if not a.smoke and not (a.gate_file and os.path.exists(a.gate_file)):
print("REFUSED: test sets need the gate file", flush=True)
sys.exit(3)
t0 = time.time()
with open(a.manifest, encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
if a.smoke:
assert all(r.get("split") == "val" for r in rows), "smoke runs on validation rows only"
imgs = [Image.open(r["image"]).convert("RGB") for r in rows]
rec = rel.Recognizer(None, "cpu", a.threads)
lm = rel.CharLM(os.path.join(REL, "lm", "char6.klm"), rec.c2l)
outs = rec.read(imgs, 32, "lm_gated", lm, a.workers, "width", 256)
secs = time.time() - t0
sha = lambda p: hashlib.sha256(open(p, "rb").read()).hexdigest() # noqa: E731
meta = {"arm": "A1", "model": "release rc1 turkic-ocr-ppocrv6-medium (A1 long2x exported to safetensors)",
"infer_py_sha256": sha(os.path.join(REL, "infer.py")), "model_safetensors_sha256": sha(os.path.join(REL, "model", "model.safetensors")),
"codec_sha256": sha(os.path.join(REL, "model", "codec.json")), "lm_sha256": sha(os.path.join(REL, "lm", "char6.klm")),
"batching": "label-free: sorted by image width, batch 32, 256 extra zero columns per batch (infer.py --sort width --batch-pad 256)",
"device": "cpu float32", "threads": a.threads,
"confidence": "conf not written (empty); hit_cap = 0 (CTC has no length cap)", "seconds_total": round(secs, 1),
"created_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "rows": len(rows)}
res = {}
for ck, key, dec in (("long2x_labelfree", "greedy", "greedy CTC"), ("long2x_labelfree_lm_gated", "text", "lm_gated (alpha 0.40, beta 1.00)")):
d = os.path.join(a.out_root, "A1", ck)
os.makedirs(d, exist_ok=True)
tmp = os.path.join(d, a.set + ".tsv.tmp")
num = den = 0
with open(tmp, "w", encoding="utf-8") as f:
f.write("id\tref\thyp\tconf\tconf_min\thit_cap\tn_tokens\n")
for r, o in zip(rows, outs):
ref = unicodedata.normalize("NFC", r["text"]).replace("\t", " ").replace("\n", " ")
hyp = (o[key] or "").replace("\t", " ").replace("\n", " ")
f.write("%s\t%s\t%s\t\t\t0\t\n" % (r["id"], ref, hyp))
if a.smoke:
rn = textnorm.norm(ref)
if rn:
num += lev_fast(rn, textnorm.norm(hyp))
den += len(rn)
os.replace(tmp, os.path.join(d, a.set + ".tsv"))
m = dict(meta, decoding=dec)
json.dump(m, open(os.path.join(d, "meta.json"), "w", encoding="utf-8"), indent=1)
if a.smoke:
res[ck] = num / den
print("done", a.set, len(rows), "rows", round(secs, 1), "s", flush=True)
if a.smoke:
print("smoke V1 CER", json.dumps(res), flush=True)
ok = abs(res["long2x_labelfree"] - 0.0648) <= 0.001 and abs(res["long2x_labelfree_lm_gated"] - 0.0482) <= 0.001
print("smoke", "PASS" if ok else "FAIL", flush=True)
sys.exit(0 if ok else 6)
if __name__ == "__main__":
main()
|