File size: 4,060 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 | """Test pass 2: RUKOPYS crop-to-label alignment check, sample preparation (no prediction, no tuning).
Sample: 20 rows drawn with numpy default_rng(20261125).choice(n, 20, replace=False) over the manifest order, plus the 10 rows with the
highest M1 CER (existing test pass 2 predictions; scorer N0 text and edit distance; ties by id) among the remaining rows.
For each row: the crop as stored (copied, scaled to at most 1400 px wide) and a page view (the raw RUKOPYS page as stored, no EXIF
rotation, as the crops were cut; long side 1600 px) with this region's box in red and the other regions of the page in blue, plus
review.tsv (k, sample kind, id, crop size, M1 CER, bbox, region index). Reference and M1 output go to review_text.json for the
reviewer only (not printed).
usage: tp2_rk_align_prep.py --root DATA/outputs/r5/testpass2 --out DIR
"""
import argparse
import csv
import json
import os
import sys
import cv2
import numpy as np
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
from r5eval import textnorm # noqa: E402
from r5eval.align import lev_fast # noqa: E402
csv.field_size_limit(1 << 30)
RAW = "/path/to/TURKIC_OCR_DATA/data/raw/rukopys_test/test"
MAN = "/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/rukopys_test.tsv"
ap = argparse.ArgumentParser()
ap.add_argument("--root", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
with open(MAN, encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
with open("%s/preds/m1_rukopys_test/paddleocr_vl_1_6/leader/rukopys_test.tsv" % a.root, encoding="utf-8", newline="") as f:
hyp = {r["id"]: r["hyp"] for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)}
cer = {}
for r in rows:
ref = textnorm.norm(r["text"])
cer[r["id"]] = lev_fast(ref, textnorm.norm(hyp.get(r["id"], ""))) / max(len(ref), 1)
rng = np.random.default_rng(20261125)
rand_idx = sorted(rng.choice(len(rows), 20, replace=False).tolist())
picked = [("random", rows[i]) for i in rand_idx]
taken = {rows[i]["id"] for i in rand_idx}
worst = sorted([r for r in rows if r["id"] not in taken], key=lambda r: (-cer[r["id"]], r["id"]))[:10]
picked += [("worst_m1_cer", r) for r in worst]
meta = {}
for line in open(RAW + "/metadata.jsonl", encoding="utf-8"):
d = json.loads(line)
meta[d["file_name"].split("/")[-1].rsplit(".", 1)[0]] = d
out_rows, texts = [], {}
for k, (kind, r) in enumerate(picked):
stem, ri = r["id"].split(":", 1)[1].rsplit("_", 1)
ri = int(ri)
rec = meta[stem]
crop = cv2.imread(r["image"], cv2.IMREAD_COLOR)
h, w = crop.shape[:2]
s = min(1.0, 1400.0 / w)
cv2.imwrite(os.path.join(a.out, "%02d_crop.jpg" % k), cv2.resize(crop, (int(w * s), int(h * s)), interpolation=cv2.INTER_AREA) if s < 1 else crop,
[cv2.IMWRITE_JPEG_QUALITY, 92])
page = cv2.imread(os.path.join(RAW, rec["file_name"]), cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
H, W = page.shape[:2]
for j, reg in enumerate(rec["regions"]):
x1, y1, x2, y2 = [int(v) for v in reg["bbox"]]
cv2.rectangle(page, (x1, y1), (x2, y2), (255, 0, 0) if j != ri else (0, 0, 255), max(2, int(max(W, H) / 400)))
sp = 1600.0 / max(W, H)
cv2.imwrite(os.path.join(a.out, "%02d_page.jpg" % k), cv2.resize(page, (int(W * sp), int(H * sp)), interpolation=cv2.INTER_AREA),
[cv2.IMWRITE_JPEG_QUALITY, 85])
bb = rec["regions"][ri]["bbox"]
out_rows.append({"k": k, "kind": kind, "id": r["id"], "crop_w": w, "crop_h": h, "m1_cer": round(cer[r["id"]], 3), "bbox": bb,
"region_index": ri, "page_w": W, "page_h": H, "regions_on_page": len(rec["regions"])})
texts[k] = {"ref": textnorm.norm(r["text"]), "m1": textnorm.norm(hyp.get(r["id"], ""))}
json.dump(out_rows, open(os.path.join(a.out, "review.json"), "w", encoding="utf-8"), indent=1)
json.dump(texts, open(os.path.join(a.out, "review_text.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False)
print("prepared", len(out_rows))
|