turkic-ocr-code / scripts /j2 /raw_samples.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
2.14 kB
"""20 raw outputs per model and enlargement next to their references (for manual inspection only, never for a page).
Same 20 crops for every model and scale: ascending sha256 of "J2-raw-sample-v1:" + crop_file over the screen set.
Only crops that are already done are listed (a partial run shows fewer than 20 rows; the column crops_of_sample_done says so).
usage: raw_samples.py OUT_ROOT SCREEN_SET_TSV SCORELIB_PY OUT_TSV
"""
import hashlib
import importlib.util
import json
import os
import sys
out_root, screen_set, scorelib_py, out_tsv = sys.argv[1:5]
assert "screen_set_v1.tsv" in screen_set
spec = importlib.util.spec_from_file_location("scorelib", scorelib_py)
sl = importlib.util.module_from_spec(spec)
spec.loader.exec_module(sl)
labels = {}
with open(screen_set, encoding="utf-8", newline="") as f:
f.readline()
for line in f:
c, form, lab = line.rstrip("\n").split("\t")
labels[c] = lab
sample = sorted(labels, key=lambda c: hashlib.sha256(("J2-raw-sample-v1:" + c).encode("utf-8")).hexdigest())[:20]
rows = ["model\tscale\tcrop_file\treference\traw_output\tafter_wrapper_removal\tcer\tn_new_tokens\thit_cap\timage_tokens\tcrops_of_sample_done"]
for model in sorted(os.listdir(out_root)):
for scale in (1, 2, 3):
pp = os.path.join(out_root, model, f"s{scale}", "preds.jsonl")
if not os.path.exists(pp):
continue
preds = {}
for line in open(pp, encoding="utf-8"):
try:
r = json.loads(line)
except Exception: # noqa: BLE001
continue
preds[r["crop_file"]] = r
done = [c for c in sample if c in preds]
for c in done:
r = preds[c]
s = sl.score_crop(labels[c], r["raw"])
rows.append("\t".join([model, f"{scale}x", c, labels[c].replace("\t", " "), repr(r["raw"])[1:-1], s["hyp"].replace("\n", "\\n"),
f"{s['cer']:.3f}", str(r["n_new"]), str(int(r["hit_cap"])), str(r["n_img_tokens"]), f"{len(done)}/20"]))
open(out_tsv, "w", encoding="utf-8").write("\n".join(rows) + "\n")
print("rows", len(rows) - 1)