turkic-ocr-code / scripts /b1_page_check /detb1_page_check.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
4.38 kB
"""Line detector + B1 on the same sampled validation pages as b1_page_check.py.
The detector boxes are the stored YOLO11s stage-2 boxes from the route A run (det_eval e2e_yolo_s2_*_A1_long_pages.jsonl),
so detection is identical to route A and only the reader changes (A1 -> B1). Reading order, crop margins and the school
full-resolution lookup are copied from linedet.det_eval. B1 reads each crop with its training instruction, greedy, bf16 on
CPU, at most 192 new tokens per line (vlm_common.MAXNEW['line']).
usage: detb1_page_check.py --set gen|school --pages TSV --stride K --n 10 --chunk C --chunks 2 --routeA JSONL --out JSONL
"""
import argparse
import json
import os
import sys
import time
import unicodedata
ap = argparse.ArgumentParser()
ap.add_argument("--set", required=True)
ap.add_argument("--pages", required=True)
ap.add_argument("--stride", type=int, required=True)
ap.add_argument("--n", type=int, default=10)
ap.add_argument("--chunk", type=int, default=0)
ap.add_argument("--chunks", type=int, default=1)
ap.add_argument("--routeA", required=True)
ap.add_argument("--model", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--threads", type=int, default=16)
ap.add_argument("--vlma", default="/path/to/TURKIC_OCR_CODE/scripts/r5_vlma")
a = ap.parse_args()
assert "test" not in os.path.basename(a.pages).lower()
sys.path.insert(0, a.vlma)
import torch # noqa: E402
from PIL import Image # noqa: E402
import vlm_common as vc # noqa: E402
torch.set_num_threads(a.threads)
SCHOOL = "/path/to/TURKIC_OCR_DATA/data/raw/school_notebooks_ru"
def school_orig(pid):
sp, num = pid.split("_")[1], int(pid.split("_")[2])
d = json.load(open("%s/annotations_%s.json" % (SCHOOL, sp), encoding="utf-8"))
fn = {im["id"]: im["file_name"] for im in d["images"]}[num]
return "%s/val_test_images/%s/%s" % (SCHOOL, sp, fn)
with open(a.pages, encoding="utf-8") as f:
hdr = f.readline().rstrip("\n").split("\t")
pages = [dict(zip(hdr, ln.rstrip("\n").split("\t"))) for ln in f]
pages = pages[::a.stride][:a.n][a.chunk::a.chunks]
det = {}
for ln in open(a.routeA, encoding="utf-8"):
r = json.loads(ln)
det[r["id"]] = r["boxes"]
proc, tok = vc.load_processor("paddleocr_vl_1_6", a.model)
tok.padding_side = "left"
model = vc.load_model("paddleocr_vl_1_6", a.model, torch.bfloat16)
model.eval()
gc, stops, stop_set = vc.gen_setup(model, tok)
tmpl_kw = vc.template_kwargs(proc, tok)
dev = torch.device("cpu")
with open(a.out, "a", encoding="utf-8") as fo:
for pg in pages:
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
# M28 reading order, as det_eval: (centre_y // 15, centre_x) in the 1280 px page
order = sorted(range(len(boxes)), key=lambda i: (int(((boxes[i][1] + boxes[i][3]) / 2) // 15), (boxes[i][0] + boxes[i][2]) / 2))
crops = []
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)))
hyp = []
for s0 in range(0, len(crops), 16):
recs = vc.generate_batch("paddleocr_vl_1_6", model, proc, tok, crops[s0:s0 + 16], vc.MAXNEW["line"], tmpl_kw, gc, stop_set, dev)
hyp += [" ".join(unicodedata.normalize("NFC", r["raw"]).split()) for r in recs]
rec = {"id": pg["id"], "prompt": "detB1", "n_boxes": len(boxes), "n_new": 0, "stopped": True,
"seconds": round(time.time() - t1, 1), "hyp_lines": [h for h in hyp if h],
"ref_lines": json.loads(pg["ref_lines_json"]) if pg.get("ref_lines_json") else []}
fo.write(json.dumps(rec, ensure_ascii=False) + "\n")
fo.flush()
print(pg["id"], "boxes", len(boxes), "%.1f s" % rec["seconds"], flush=True)
print("done", flush=True)