File size: 7,619 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""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]

LOOPGUARD-1 copy (scripts/r5_loopguard): adds the held-out sets gen_test and school_test (page files of the LOOPGUARD prep
job, DATA/data/processed/r6_loopguard/det/{gen,school2}/pages_*_test.tsv, and its CPU detector boxes,
DATA/outputs/r6_loopguard/det/<set>.jsonl, made on CPU with lg_detect.py, the copy of tp2_tob_detect.py, at the det_eval
settings). Held-out page files, box
files and annotations_test.json are opened only under the unseal token (role 'pipeline'); the guard_not_test check of --out
applies to the validation sets as before. Crops, order, reader and record format are unchanged.
"""
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"}
LG_DET = C.DATA + "/data/processed/r6_loopguard/det"
LG_BOX = C.DATA + "/outputs/r6_loopguard/det"
PAGES.update({"gen_test": LG_DET + "/gen/pages_gen_test.tsv", "school_test": LG_DET + "/school2/pages_school_test.tsv"})
DETF.update({"gen_test": LG_BOX + "/gen_test.jsonl", "school_test": LG_BOX + "/school_test.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)
ap.add_argument("--sealed-token", default=T.OFFICIAL_UNSEAL)
a = ap.parse_args()
T0 = time.time()
HELD = a.set in T.HELDOUT_SETS
if HELD:
    T.check_unsealed(a.sealed_token, "pipeline")
else:
    T.guard_not_test(a.out)
if a.threads:
    torch.set_num_threads(a.threads)
dev = a.device


def _open(p):
    return T.open_sealed(p, a.sealed_token, "pipeline") if HELD else open(p, encoding="utf-8", newline="")


with _open(PAGES[a.set]) as f:
    pages = list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
det = {}
with _open(DETF[a.set]) 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);
    LOOPGUARD-1: a School test page under the unseal token (annotations_test.json opened through open_sealed)"""
    sp, num = pid.split("_")[1], int(pid.split("_")[2])
    assert sp == ("test" if HELD else "val"), pid
    if sp not in _ann:
        d = json.load(_open("%s/annotations_%s.json" % (SCHOOL, sp)))
        _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)