turkic-ocr-code / scripts /r5_onemodel /om_baseline.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
6.34 kB
"""ONEMODEL pilot (design ONEMODEL-pilot-1): the baseline detector + leader on ALL validation pages of one set.
Detection = the stored YOLO11s stage-2 boxes of det_eval (DATA/outputs/r5/linedet/det_eval/e2e_yolo_s2_<set>_A1_long_pages.jsonl),
so detection is identical to route A and only the reader changes (A1 -> leader), as records/R5/PAGECHK/detb1_page_check.py.
Crops as det_eval / detb1_page_check: margins 1% + 2 px left and right, 10% + 1 px top and bottom; generated pages are cut from
the det_prep 1280-px page image, School pages from the full-resolution photograph (scale 1/scale), PIL decoding without EXIF
transposition; crops smaller than 4 px are skipped. Crops are read in det_eval order ((centre_y // 15, centre_x)) in batches of
--batch with the leader's crop instruction, greedy, at most 192 new tokens (vlm_common.MAXNEW['line']), bf16; reading =
' '.join(NFC(raw).split()). The JSON line of a page stores the boxes and the reading of every box (null = skipped crop), so the
scorer can apply any ordering rule. Resumable per page; exit 99 at --max-seconds.
usage: om_baseline.py --set gen_val|school_val --out JSONL [--device cuda] [--chunk C --chunks K] [--max-seconds S]
"""
import argparse
import csv
import json
import os
import sys
import time
import unicodedata
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import om_common as C # noqa: E402
import om_text as T # noqa: E402
import torch # noqa: E402
from PIL import Image # noqa: E402
vc = C.vc
csv.field_size_limit(10 ** 9)
DET = C.DATA + "/data/processed/r5_linedet_det"
DET_EVAL = C.DATA + "/outputs/r5/linedet/det_eval"
SCHOOL = C.DATA + "/data/raw/school_notebooks_ru"
PAGES = {"gen_val": DET + "/gen/pages_gen_val.tsv", "school_val": DET + "/school2/pages_school_val.tsv"}
DETF = {"gen_val": DET_EVAL + "/e2e_yolo_s2_gen_val_A1_long_pages.jsonl", "school_val": DET_EVAL + "/e2e_yolo_s2_school_val_A1_long_pages.jsonl"}
ap = argparse.ArgumentParser()
ap.add_argument("--set", required=True, choices=sorted(PAGES))
ap.add_argument("--model-dir", default=C.LEADER)
ap.add_argument("--out", required=True)
ap.add_argument("--device", default="cuda")
ap.add_argument("--threads", type=int, default=0)
ap.add_argument("--batch", type=int, default=16)
ap.add_argument("--chunk", type=int, default=0)
ap.add_argument("--chunks", type=int, default=1)
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--ids", default="")
ap.add_argument("--max-seconds", type=float, default=0.0)
a = ap.parse_args()
T0 = time.time()
T.guard_not_test(a.out)
if a.threads:
torch.set_num_threads(a.threads)
dev = a.device
with open(PAGES[a.set], encoding="utf-8", newline="") as f:
pages = list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
det = {}
with open(DETF[a.set], encoding="utf-8") as f:
for line in f:
r = json.loads(line)
det[r["id"]] = r["boxes"]
if a.ids:
keep = set(a.ids.split(","))
pages = [p for p in pages if p["id"] in keep]
if a.limit:
pages = pages[:a.limit]
pages = pages[a.chunk::a.chunks]
_ann = {}
def school_orig(pid):
"""full-resolution photograph of a School val page (as linedet.det_eval.school_orig; annotations_val.json only)"""
sp, num = pid.split("_")[1], int(pid.split("_")[2])
assert sp == "val", pid
if sp not in _ann:
d = json.load(open("%s/annotations_%s.json" % (SCHOOL, sp), encoding="utf-8"))
_ann[sp] = {im["id"]: im["file_name"] for im in d["images"]}
return "%s/val_test_images/%s/%s" % (SCHOOL, sp, _ann[sp][num])
done = set()
if os.path.exists(a.out):
with open(a.out, encoding="utf-8") as f:
for line in f:
try:
done.add(json.loads(line)["id"])
except ValueError:
pass
os.makedirs(os.path.dirname(a.out), exist_ok=True)
proc, tok, model = C.load(a.model_dir)
tok.padding_side = "left"
model = model.to(dev).eval()
exp = json.load(open(os.path.join(a.model_dir, "r5_export.json"))) if os.path.exists(os.path.join(a.model_dir, "r5_export.json")) else {}
tmpl_kw = exp.get("chat_template_kwargs", vc.template_kwargs(proc, tok))
gc, stops, stop_set = vc.gen_setup(model, tok, exp.get("answer_suffix_ids"))
assert vc.INSTR == T.CROP_INSTRUCTION
status = 0
with open(a.out, "a", encoding="utf-8") as fo:
for pg in pages:
if pg["id"] in done:
continue
if a.max_seconds and time.time() - T0 > a.max_seconds:
status = 99
break
t1 = time.time()
boxes = det[pg["id"]]
if pg["id"].startswith("school_"):
big = Image.open(school_orig(pg["id"])).convert("RGB")
sc = 1.0 / float(pg["scale"])
else:
big, sc = Image.open(pg["image"]).convert("RGB"), 1.0
W, H = big.size
order = T.det_order(boxes)
crops, idx = [], []
for i in order:
x0, y0, x1, y1 = boxes[i]
hh = y1 - y0
x0, x1 = x0 - 0.01 * (x1 - x0) - 2, x1 + 0.01 * (x1 - x0) + 2
y0, y1 = y0 - 0.1 * hh - 1, y1 + 0.1 * hh + 1
X0, Y0, X1, Y1 = [int(round(v * sc)) for v in (max(x0, 0), max(y0, 0), x1, y1)]
X0, Y0, X1, Y1 = max(X0, 0), max(Y0, 0), min(X1, W), min(Y1, H)
if X1 - X0 < 4 or Y1 - Y0 < 4:
continue
crops.append(big.crop((X0, Y0, X1, Y1)))
idx.append(i)
readings = [None] * len(boxes)
caps = 0
for s0 in range(0, len(crops), a.batch):
recs = vc.generate_batch(C.SHORT, model, proc, tok, crops[s0:s0 + a.batch], vc.MAXNEW["line"], tmpl_kw, gc, stop_set, dev)
for i, r in zip(idx[s0:s0 + a.batch], recs):
readings[i] = " ".join(unicodedata.normalize("NFC", r["raw"]).split())
caps += int(bool(r["hit_cap"]))
rec = {"id": pg["id"], "set": a.set, "w1280": int(pg["width"]), "h1280": int(pg["height"]), "boxes": boxes,
"readings": readings, "n_boxes": len(boxes), "n_read": len(idx), "hit_cap_crops": caps,
"seconds": round(time.time() - t1, 2), "device": dev}
fo.write(json.dumps(rec, ensure_ascii=False) + "\n")
fo.flush()
print(pg["id"], "boxes", len(boxes), "%.1fs" % rec["seconds"], flush=True)
print("done status", status, flush=True)
sys.exit(status)