File size: 5,740 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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | """Showcase, job B step 2 (.venv_vlm): read every detected line with the fine-tuned PaddleOCR-VL 1.6 (R5 leader).
Same reading as records/R5/PAGECHK/detb1_page_check.py (and the end-to-end part of linedet.det_eval): reading order
(centre_y // 15, centre_x) in the 1280 px detector page; each box widened by 1 % of its width + 2 px and heightened by 10 % of
its height + 1 px, cut from the full-resolution page (School Notebooks: the original photograph, factor 1 / scale; generated
pages: the 1280 px detector page itself, factor 1); crops under 4 px dropped; vlm_common loader, prompt and greedy decoding
(instruction vlm_common.INSTR), bf16 on CPU, at most 192 new tokens per line, batches of 16 crops; text = NFC, white space
collapsed; empty readings left out of the page text.
Per crop it also records the processor's image-token count (image_token_id positions in input_ids of the same prompt) and the
patch grid (image_grid_thw), outside the timed part.
usage: showcase_read.py --pages pages.json --model DIR --out read.jsonl --crops_dir DIR --save_crops ID1,ID2 --threads 16
"""
import argparse
import json
import os
import sys
import time
import unicodedata
ap = argparse.ArgumentParser()
ap.add_argument("--pages", required=True)
ap.add_argument("--model", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--crops_dir", required=True)
ap.add_argument("--save_crops", default="")
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()
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)
SHORT = "paddleocr_vl_1_6"
P = json.load(open(a.pages, encoding="utf-8"))
save_ids = set(x for x in a.save_crops.split(",") if x)
t0 = time.time()
proc, tok = vc.load_processor(SHORT, a.model)
tok.padding_side = "left"
model = vc.load_model(SHORT, 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
img_tok = int(getattr(model.config, "image_token_id", -1))
dev = torch.device("cpu")
print("model loaded in %.1f s; instruction %r; image_token_id %d" % (load_s, vc.INSTR, img_tok), flush=True)
with open(a.out, "w", encoding="utf-8") as fo:
fo.write(json.dumps(dict(header=True, model=a.model, model_load_seconds=round(load_s, 1), instruction=vc.INSTR, max_new=vc.MAXNEW["line"], batch=16,
dtype="bfloat16", device="cpu", threads=a.threads, host=os.uname().nodename,
created_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())), ensure_ascii=False) + "\n")
for pg in P["pages"]:
boxes = pg["boxes"]
t1 = time.time()
if pg.get("reading_image"): # School Notebooks: the original photograph; kz benchmark page: the upright full-resolution copy
big = Image.open(pg["reading_image"]).convert("RGB")
sc = 1.0 / float(pg["scale"])
else:
big, sc = Image.open(pg["image"]).convert("RGB"), 1.0
W, H = big.size
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, meta = [], []
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:
meta.append(dict(box_index=i, box=boxes[i], dropped=True))
continue
crops.append(big.crop((X0, Y0, X1, Y1)))
meta.append(dict(box_index=i, box=boxes[i], crop_box=[X0, Y0, X1, Y1], crop_size=[X1 - X0, Y1 - Y0]))
t_crop = time.time() - t1
t2 = time.time()
recs = []
for s0 in range(0, len(crops), 16):
recs += vc.generate_batch(SHORT, model, proc, tok, crops[s0:s0 + 16], vc.MAXNEW["line"], tmpl_kw, gc, stop_set, dev)
t_read = time.time() - t2
kept = [m for m in meta if not m.get("dropped")]
for m, r, c in zip(kept, recs, crops):
m["raw"] = r["raw"]
m["text"] = " ".join(unicodedata.normalize("NFC", r["raw"]).split())
m["n_new"], m["hit_cap"], m["conf"] = r["n_new"], bool(r["hit_cap"]), r["conf"]
enc = vc.prompt_batch(SHORT, proc, [c], tmpl_kw)
m["n_image_tokens"] = int((enc["input_ids"][0] == img_tok).sum())
m["n_prompt_tokens"] = int(enc["input_ids"].shape[1])
if "image_grid_thw" in enc:
m["image_grid_thw"] = [int(x) for x in enc["image_grid_thw"][0].tolist()]
if pg["id"] in save_ids or "all" in save_ids:
d = os.path.join(a.crops_dir, pg["id"])
os.makedirs(d, exist_ok=True)
for k, c in enumerate(crops):
c.save(os.path.join(d, "%03d.png" % k))
hyp = [m["text"] for m in kept]
rec = dict(id=pg["id"], set=pg["set"], lang=pg["lang"], n_boxes=len(boxes), n_crops=len(crops), reading_image_size=[W, H], crop_scale=sc,
seconds_crop=round(t_crop, 3), seconds_read=round(t_read, 2), lines=meta, hyp_lines=[h for h in hyp if h], ref_lines=pg["ref_lines"])
fo.write(json.dumps(rec, ensure_ascii=False) + "\n")
fo.flush()
print(pg["id"], "boxes", len(boxes), "read %.1f s" % t_read, flush=True)
print("done", flush=True)
|