Download scripts/r5_erran/erran_sample.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 5.34 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_erran/erran_sample.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_erran/erran_sample.py
-
curl -L -o erran_sample.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_erran/erran_sample.py
5.34 kB
| """ERRAN (R5) task 2: draw the V1 error crops to view, and build contact sheets for viewing. | |
| Design (fixed before viewing, ERRAN plan task 2): | |
| - one random order of all V1 crop ids: numpy default_rng(20261122).permutation(sorted ids); | |
| - for each of the four arms (hunyuanocr, minicpm_ocr_1_0, paddleocr_vl_1_6, A1 long_lm_gated) the first 120 of ITS error crops | |
| in that order: a uniform random sample of that arm's error crops (the shared order only makes the samples overlap); | |
| - a separate stratum: the crops every arm of the task-1 list gets wrong (all of them if at most 80, else the first 80 in the order). | |
| Contact sheets show the crop images with a running number only (no text drawn); the references and outputs go to a separate index | |
| file. Everything is written under OUT/private/ on the cluster (real students' handwriting: never copied into page files). | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import numpy as np | |
| from PIL import Image, ImageDraw, ImageFont | |
| sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") | |
| from r5eval.ioutil import read_manifest # noqa: E402 | |
| SEED = 20261122 | |
| N_PER_ARM = 120 | |
| N_ALLWRONG = 80 | |
| ARMS = ["hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "A1 long_lm_gated"] | |
| V1_MANIFEST = "/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/kohtd_screen_v1.tsv" | |
| H = 120 | |
| MAXW = 1000 | |
| PER_SHEET = 8 | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--out", required=True) | |
| args = ap.parse_args() | |
| priv = os.path.join(args.out, "private") | |
| err = json.load(open(os.path.join(priv, "error_sets_V1.json"), encoding="utf-8")) | |
| allwrong = [l.strip() for l in open(os.path.join(priv, "wrong_for_every_arm_V1.txt"), encoding="utf-8") if l.strip()] | |
| man = read_manifest(V1_MANIFEST) | |
| mrow = {r["id"]: r for r in man} | |
| ids = sorted(mrow) | |
| order = np.random.default_rng(SEED).permutation(len(ids)) | |
| rank = {ids[k]: int(pos) for pos, k in enumerate(order)} | |
| samples = {} | |
| for a in ARMS: | |
| e = sorted(err[a], key=lambda i: rank[i]) | |
| samples[a] = e[:N_PER_ARM] | |
| aw = sorted(allwrong, key=lambda i: rank[i]) | |
| stratum = aw if len(aw) <= N_ALLWRONG else aw[:N_ALLWRONG] | |
| union = sorted(set(stratum).union(*[set(v) for v in samples.values()]), key=lambda i: rank[i]) | |
| # outputs of every arm for the index file | |
| hyp = {} | |
| ref = {} | |
| nwrong = {} | |
| with open(os.path.join(priv, "per_crop_errors.tsv"), encoding="utf-8") as f: | |
| hdr = f.readline().rstrip("\n").split("\t") | |
| for line in f: | |
| p = dict(zip(hdr, line.rstrip("\n").split("\t"))) | |
| if p["set"] != "V1": | |
| continue | |
| hyp[(p["arm"], p["id"])] = p["hyp"] | |
| ref[p["id"]] = p["ref"] | |
| if int(p["dist"]) > 0: | |
| nwrong[p["id"]] = nwrong.get(p["id"], 0) + 1 | |
| n_arms = len(err) | |
| sheets = os.path.join(priv, "sheets") | |
| os.makedirs(sheets, exist_ok=True) | |
| try: | |
| font = ImageFont.load_default(size=28) | |
| except TypeError: | |
| font = ImageFont.load_default() | |
| idx_rows = [] | |
| for s0 in range(0, len(union), PER_SHEET): | |
| chunk = union[s0:s0 + PER_SHEET] | |
| tiles = [] | |
| for k, cid in enumerate(chunk): | |
| n = s0 + k + 1 | |
| im = Image.open(mrow[cid]["image"]).convert("RGB") | |
| w0, h0 = im.size | |
| sc = H / float(h0) | |
| w = int(round(w0 * sc)) | |
| if w > MAXW: | |
| sc = MAXW / float(w0) | |
| w = MAXW | |
| im2 = im.resize((max(1, w), max(1, int(round(h0 * sc)))), Image.LANCZOS) | |
| tiles.append((n, im2, w0, h0)) | |
| idx_rows.append({"n": n, "id": cid, "orig_w": w0, "orig_h": h0, "sheet": s0 // PER_SHEET + 1, | |
| "in_sample_of": [a for a in ARMS if cid in samples[a]], "in_allwrong_stratum": cid in stratum, | |
| "arms_wrong_of_%d" % n_arms: nwrong.get(cid, 0), "ref": ref.get(cid), | |
| "out": {a: hyp.get((a, cid)) for a in ARMS}}) | |
| Wd = 90 + max(t[1].size[0] for t in tiles) + 10 | |
| Ht = sum(t[1].size[1] + 16 for t in tiles) + 8 | |
| sheet = Image.new("RGB", (Wd, Ht), (255, 255, 255)) | |
| dr = ImageDraw.Draw(sheet) | |
| y = 8 | |
| for n, im2, w0, h0 in tiles: | |
| dr.text((4, y + im2.size[1] // 2 - 14), "%d" % n, fill=(200, 0, 0), font=font) | |
| sheet.paste(im2, (90, y)) | |
| dr.rectangle([89, y - 1, 90 + im2.size[0], y + im2.size[1]], outline=(160, 160, 160)) | |
| y += im2.size[1] + 16 | |
| sheet.save(os.path.join(sheets, "sheet_%03d.png" % (s0 // PER_SHEET + 1))) | |
| with open(os.path.join(sheets, "index.jsonl"), "w", encoding="utf-8") as f: | |
| for r in idx_rows: | |
| f.write(json.dumps(r, ensure_ascii=False) + "\n") | |
| design = {"seed": SEED, "n_per_arm": N_PER_ARM, "arms": ARMS, "error_crops_per_arm": {a: len(err[a]) for a in ARMS}, | |
| "sample_sizes": {a: len(samples[a]) for a in ARMS}, "allwrong_total": len(aw), "allwrong_stratum": len(stratum), | |
| "union_crops_to_view": len(union), "sheets": (len(union) + PER_SHEET - 1) // PER_SHEET, "arms_in_every_arm_definition": sorted(err)} | |
| json.dump(design, open(os.path.join(priv, "sample_design.json"), "w"), indent=1) | |
| print(json.dumps(design)) | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |