"""Quick whole-page check of B1 (PaddleOCR-VL 1.6 R5 leader) on CPU: one prompt, a few validation pages. Not a benchmark: a smoke sample before a deadline. Validation pages only. Reuses the R5 loader and prompt builder (CODE/scripts/r5_vlma/vlm_common.py) with the instruction swapped, greedy decoding, bf16 as in the R5 evaluation. Writes one JSON line per page as soon as it is read, and stops before --stop_utc. usage: b1_page_check.py --model DIR --pages TSV --start K --n N --prompt spot|instr|ocr --out JSONL --stop_utc HH:MM """ import argparse import json import os import re import sys import time import unicodedata from datetime import datetime, timezone ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--pages", required=True) ap.add_argument("--stride", type=int, default=1) 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("--prompt", choices=["spot", "instr", "ocr"], required=True) ap.add_argument("--out", required=True) ap.add_argument("--stop_utc", required=True) ap.add_argument("--max_new", type=int, default=2048) 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(), "refusing a test page list" 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) PROMPTS = {"spot": "Spotting:", "ocr": "OCR:", "instr": vc.INSTR} vc.INSTR = PROMPTS[a.prompt] # prompt_batch reads the module global at call time SCHOOL = "/path/to/TURKIC_OCR_DATA/data/raw/school_notebooks_ru" LOC = re.compile(r"<\|LOC_\d+\|>") SPECIAL = re.compile(r"<\|[A-Za-z_]+\|>||") stop_h, stop_m = (int(x) for x in a.stop_utc.split(":")) def now(): return datetime.now(timezone.utc) def past_stop(): t = now() return (t.hour, t.minute) >= (stop_h, stop_m) def school_orig(pid): # same lookup as linedet.det_eval.school_orig: the full-resolution photograph of a school val page 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) def lines_from(raw_special): """Page text lines from the raw output: location tokens and other special tokens removed, one line per newline.""" out = [] for ln in raw_special.split("\n"): t = SPECIAL.sub("", LOC.sub("", ln)) t = " ".join(unicodedata.normalize("NFC", t).split()) if t: out.append(t) return out 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] # every stride-th page spreads the sample over page kinds and languages (the lists are sorted by kind, then language) sel = pages[::a.stride][:a.n] pages = sel[a.chunk::a.chunks] t0 = time.time() 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) load_s = time.time() - t0 print("loaded in %.1f s; prompt %r; %d pages" % (load_s, vc.INSTR, len(pages)), flush=True) dev = torch.device("cpu") with open(a.out, "a", encoding="utf-8") as fo: for pg in pages: if past_stop(): print("stop time reached before page", pg["id"], flush=True) break path = school_orig(pg["id"]) if pg["id"].startswith("school_") else pg["image"] im = Image.open(path).convert("RGB") t1 = time.time() inputs = vc.prompt_batch("paddleocr_vl_1_6", proc, [im], tmpl_kw).to(dev, dtype=torch.bfloat16) g = __import__("copy").deepcopy(gc) g.max_new_tokens = a.max_new with torch.inference_mode(): out = model.generate(**inputs, generation_config=g) new = out[0, inputs["input_ids"].shape[1]:].tolist() hit = any(t in stop_set for t in new) raw_sp = tok.decode(new, skip_special_tokens=False, clean_up_tokenization_spaces=False) rec = {"id": pg["id"], "prompt": a.prompt, "image": path, "image_size": list(im.size), "n_visual_tokens": int((inputs["input_ids"][0] == getattr(model.config, "image_token_id", -1)).sum()), "n_new": len(new), "stopped": hit, "seconds": round(time.time() - t1, 1), "hyp_lines": lines_from(raw_sp), "ref_lines": json.loads(pg["ref_lines_json"]) if pg.get("ref_lines_json") else [], "raw": raw_sp} fo.write(json.dumps(rec, ensure_ascii=False) + "\n") fo.flush() print(pg["id"], "%.1f s" % rec["seconds"], "new", len(new), "stopped", hit, "lines", len(rec["hyp_lines"]), flush=True) print("done", now().isoformat(), flush=True)