File size: 25,273 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
"""ONEMODEL pilot (design ONEMODEL-pilot-1), CPU job: page records, resized page images, spotting targets, the page and crop
sequence files and the frozen max_new_tokens.

Inputs (validation and training splits only; no test file is opened):
  det_eval page files DATA/data/processed/r5_linedet_det/{gen/pages_gen,school2/pages_school}_{train,val}.tsv
    (reference lines, 1280-px boxes, scale: exactly what det_eval scores against)
  generated page originals: image column of DATA/data/processed/r5/manifests/synth_pages_{train,val}.tsv
  School originals: train from data/raw/school_notebooks_ru/images.zip (as linedet.det_prep), val from val_test_images/val
    (file names from annotations_{train,val}.json only)
  crop rows: DATA/data/processed/r5/seq/mix_v1_seq.tsv rows 1,310,592 .. +N (the leader stopped at 1,310,592)
Outputs under DATA/data/processed/r6_onemodel/: pages/<set>/<id>.jpg, records/<set>.jsonl, seq/page_seq.tsv,
  seq/crop_seq.tsv, build_report.json (passed true only if every target round-trips and every count is as expected).

usage: om_build_pages.py --workers 16 [--limit N (smoke: N pages per set, written under --out)] [--out DIR]

LOOPGUARD-1 copy (scripts/r5_loopguard): adds ONLY the mode --heldout, which builds the two held-out page sets gen_test
('gen', 'test', 300) and school_test ('school', 'test', 150) with the same work() function into
DATA/data/processed/r6_loopguard/{pages,records}/ and writes build_report_heldout.json. Inputs: the LOOPGUARD prep job's
det page files DATA/data/processed/r6_loopguard/det/{gen/pages_gen_test,school2/pages_school_test}.tsv, generated originals
from the image column of DATA/data/processed/r5/manifests/synth_pages_test.tsv, School originals from
val_test_images/test (file names from annotations_test.json). It prints counts only, never text. The sequence files and
max_new_tokens of the existing build are not rebuilt. Leak check: ids and original sha256 against the four r6_onemodel
record files; known perceptual near-duplicates from outputs/r5/freeze/dedupe_all_dropped_used.tsv are listed.
Without --heldout the script is the original.
"""
import argparse
import collections
import csv
import hashlib
import io
import json
import math
import os
import sys
import time
import zipfile

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import om_text as T  # noqa: E402

csv.field_size_limit(10 ** 9)
DATA = "/path/to/TURKIC_OCR_DATA"
LEADER = DATA + "/checkpoints/r5/paddleocr_vl_1_6/leader"
DET = DATA + "/data/processed/r5_linedet_det"
SCHOOL = DATA + "/data/raw/school_notebooks_ru"
MIX_SEQ = DATA + "/data/processed/r5/seq/mix_v1_seq.tsv"
MIX_SEQ_SHA = "87d605c41cce7aeffcca827a1ea98f3acb30d350cc43c14228f080468e079440"
CROP_START = 1310592
SETS = {"gen_train": ("gen", "train", 3999), "gen_val": ("gen", "val", 300), "school_train": ("school", "train", 1557),
        "school_val": ("school", "val", 150)}
SEED = 20261125
N_PAGE = 30000
N_CROP = 30000
SCHOOL_SHARE_MOD = (3, 10)        # global page index s is a School page when s % 10 < 3

_W = {}


def sha256_file(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for blk in iter(lambda: f.read(1 << 20), b""):
            h.update(blk)
    return h.hexdigest()


def read_tsv(p):
    T.guard_not_test(p)
    with open(p, encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))


def _init(leader):
    sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/scripts/r5_vlma")
    import vlm_common as vc
    proc, tok = vc.load_processor("paddleocr_vl_1_6", leader)
    _W["tok"] = tok
    _W["zip"] = zipfile.ZipFile(SCHOOL + "/images.zip")
    _W["names"] = {n.lower(): n for n in _W["zip"].namelist() if not n.startswith("__MACOSX")}


def _open_original(job):
    from PIL import Image
    if job["src"].startswith("zip:"):
        name = _W["names"].get(("images/" + job["src"][4:]).lower())
        if name is None:
            raise FileNotFoundError("not in images.zip: " + job["src"])
        raw = _W["zip"].read(name)
        im = Image.open(io.BytesIO(raw))
        src_sha = hashlib.sha256(raw).hexdigest()
    else:
        im = Image.open(job["src"])
        src_sha = sha256_file(job["src"])
    orient = None
    try:
        orient = im.getexif().get(0x0112)
    except Exception:  # noqa: BLE001
        orient = "unreadable"
    im.load()
    return im, src_sha, orient


def work(job):
    """one page: resize the original, build the target, tokenize, round-trip. Returns the record or an error."""
    from PIL import Image
    try:
        tok = _W["tok"]
        im, src_sha, orient = _open_original(job)
        W0, H0 = im.size
        w1280, h1280, scale = job["width"], job["height"], job["scale"]
        size_ok = abs(W0 * scale - w1280) <= 1.0 and abs(H0 * scale - h1280) <= 1.0
        W, H = T.spot_size(W0, H0)
        rgb = im.convert("RGB")
        out = rgb.resize((W, H), Image.LANCZOS)
        out.info = {}
        os.makedirs(os.path.dirname(job["dst"]), exist_ok=True)
        out.save(job["dst"], format="JPEG", quality=95)
        chk = Image.open(job["dst"])
        saved_exif = len(chk.getexif())
        saved_size = chk.size
        boxes, texts = job["boxes"], job["ref_lines"]
        if job["kind"] == "school":
            order, ginfo = T.school_order(boxes, w1280)
        else:
            order, ginfo = list(range(len(boxes))), None
        target, kept, quads, cnt = T.build_target(texts, boxes, w1280, h1280, order)
        ids = tok(target, add_special_tokens=False).input_ids
        dec = tok.decode(ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)
        par = T.parse_output(target)
        par_dec = T.parse_output(dec)
        exp_texts = [T.norm_line(texts[i]) for i in kept]
        rt = {"decode_equals_target": dec == target,
              "parse_texts_equal": [p["text"] for p in par] == exp_texts,
              "parse_quads_equal": [p["locs"] for p in par] == quads,
              "parse_of_decoded_equal": [(p["text"], p["locs"]) for p in par_dec] == [(p["text"], p["locs"]) for p in par],
              "loc_ids_count_ok": sum(1 for t in ids if 100297 <= t <= 101297) == 8 * len(kept),
              "no_malformed": not any(p["malformed"] for p in par)}
        tgt_ids = list(ids) + [2]
        rec = {"id": job["id"], "set": job["set"], "split": job["split"], "kind": job["kind"], "lang": job["lang"],
               "page_type": job["page_type"], "image": job["dst"], "orig_image": job["src"], "orig_sha256": src_sha,
               "orig_size": [W0, H0], "exif_orientation": orient, "img_w": W, "img_h": H, "saved_size": list(saved_size),
               "saved_exif_tags": saved_exif, "w1280": w1280, "h1280": h1280, "scale": scale, "size_consistent": size_ok,
               "n_ref_lines": len(texts), "ref_lines": texts, "boxes1280": boxes, "order": order, "gutter": ginfo,
               "kept": kept, "target": target, "target_ids": tgt_ids, "n_target_tokens": len(tgt_ids),
               "n_target_lines": len(kept), "target_chars": len(target), "over_cap": len(tgt_ids) > T.TARGET_CAP,
               "counts": cnt, "roundtrip": rt, "roundtrip_ok": all(rt.values())}
        return rec
    except Exception as e:  # noqa: BLE001
        import traceback
        return {"id": job["id"], "set": job["set"], "error": repr(e)[:300], "trace": traceback.format_exc()[-1200:]}


def jobs_for(set_name, out_root, limit):
    kind, split, _ = SETS[set_name]
    if kind == "gen":
        rows = read_tsv("%s/gen/pages_gen_%s.tsv" % (DET, split))
        man = {r["id"]: r for r in read_tsv("%s/data/processed/r5/manifests/synth_pages_%s.tsv" % (DATA, split))}
    else:
        rows = read_tsv("%s/school2/pages_school_%s.tsv" % (DET, split))
        ann = json.load(open("%s/annotations_%s.json" % (SCHOOL, split), encoding="utf-8"))
        fn = {im["id"]: im["file_name"] for im in ann["images"]}
    if limit:
        rows = rows[:limit]
    jobs = []
    for r in rows:
        pid = r["id"]
        assert pid.startswith(("pg_%s_" % split, "school_%s_" % split)), pid
        if kind == "gen":
            m = man[pid]
            src = m["image"]
            lang = m["lang"]
            page_type = pid.split("_")[2]
        else:
            num = int(pid.split("_")[2])
            src = ("zip:" + fn[num]) if split == "train" else "%s/val_test_images/val/%s" % (SCHOOL, fn[num])
            lang, page_type = "ru", "notebook_photo"
        jobs.append({"id": pid, "set": set_name, "split": split, "kind": kind, "lang": lang, "page_type": page_type, "src": src,
                     "dst": "%s/pages/%s/%s.jpg" % (out_root, set_name, pid), "width": int(r["width"]), "height": int(r["height"]),
                     "scale": float(r["scale"]), "boxes": json.loads(r["boxes_json"]), "ref_lines": json.loads(r["ref_lines_json"])})
    return jobs


def pct(v, q):
    if not v:
        return None
    s = sorted(v)
    k = (len(s) - 1) * q
    lo, hi = int(math.floor(k)), int(math.ceil(k))
    return s[lo] + (s[hi] - s[lo]) * (k - lo)


def dist(v):
    return {"n": len(v), "min": min(v) if v else None, "p50": pct(v, 0.5), "p90": pct(v, 0.9), "p99": pct(v, 0.99),
            "p99.9": pct(v, 0.999), "max": max(v) if v else None, "mean": (sum(v) / len(v)) if v else None}


def page_sequence(recs_train):
    import numpy as np
    pools = {"gen": sorted(r["id"] for r in recs_train if r["kind"] == "gen" and not r["over_cap"]),
             "school": sorted(r["id"] for r in recs_train if r["kind"] == "school" and not r["over_cap"])}
    streams = {}
    for k, code in (("gen", 1), ("school", 2)):
        ids, out, p = pools[k], [], 0
        while len(out) < N_PAGE:
            perm = np.random.default_rng([SEED, code, p]).permutation(len(ids)).tolist()
            out += [(ids[i], p) for i in perm]
            p += 1
        streams[k] = out
    rng_u = np.random.default_rng([SEED, 99])
    us = rng_u.uniform(0.75, 1.0, size=N_PAGE)
    rows, pos = [], {"gen": 0, "school": 0}
    for s in range(N_PAGE):
        k = "school" if (s % SCHOOL_SHARE_MOD[1]) < SCHOOL_SHARE_MOD[0] else "gen"
        pid, p = streams[k][pos[k]]
        pos[k] += 1
        rows.append((s, pid, k, p, "%.6f" % us[s]))
    return rows, {k: len(v) for k, v in pools.items()}, pos


HO_SETS = {"gen_test": ("gen", "test", 300), "school_test": ("school", "test", 150)}
HO_DET = DATA + "/data/processed/r6_loopguard/det"
HO_OUT = DATA + "/data/processed/r6_loopguard"
OM_RECORDS = DATA + "/data/processed/r6_onemodel/records"
DEDUPE_USED = DATA + "/outputs/r5/freeze/dedupe_all_dropped_used.tsv"


def jobs_for_heldout(set_name, out_root):
    """as jobs_for, for the held-out sets (explicit paths; the 'test' name guard of read_tsv does not apply here)"""
    kind, split, _ = HO_SETS[set_name]
    assert split == "test"

    def tsv(p):
        with open(p, encoding="utf-8", newline="") as f:
            return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
    if kind == "gen":
        rows = tsv("%s/gen/pages_gen_test.tsv" % HO_DET)
        man = {r["id"]: r for r in tsv("%s/data/processed/r5/manifests/synth_pages_test.tsv" % DATA)}
    else:
        rows = tsv("%s/school2/pages_school_test.tsv" % HO_DET)
        ann = json.load(open("%s/annotations_test.json" % SCHOOL, encoding="utf-8"))
        fn = {im["id"]: im["file_name"] for im in ann["images"]}
    jobs = []
    for r in rows:
        pid = r["id"]
        assert pid.startswith(("pg_test_", "school_test_")), pid
        if kind == "gen":
            m = man[pid]
            src, lang, page_type = m["image"], m["lang"], pid.split("_")[2]
        else:
            num = int(pid.split("_")[2])
            src = "%s/val_test_images/test/%s" % (SCHOOL, fn[num])
            lang, page_type = "ru", "notebook_photo"
        jobs.append({"id": pid, "set": set_name, "split": split, "kind": kind, "lang": lang, "page_type": page_type, "src": src,
                     "dst": "%s/pages/%s/%s.jpg" % (out_root, set_name, pid), "width": int(r["width"]), "height": int(r["height"]),
                     "scale": float(r["scale"]), "boxes": json.loads(r["boxes_json"]), "ref_lines": json.loads(r["ref_lines_json"])})
    return jobs


def main_heldout(a):
    t0 = time.time()
    import multiprocessing as mp
    out = a.out if a.out != DATA + "/data/processed/r6_onemodel" else HO_OUT
    assert os.path.realpath(out) != os.path.realpath(DATA + "/data/processed/r6_onemodel"), "held-out records never go to r6_onemodel"
    rep = {"design": "LOOPGUARD-1", "base_design": T.DESIGN_ID, "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
           "out": out, "sets": {}, "errors": []}
    by_set = {}
    with mp.Pool(a.workers, initializer=_init, initargs=(LEADER,)) as pool:
        for s in HO_SETS:
            jobs = jobs_for_heldout(s, out)
            res = pool.map(work, jobs, chunksize=4)
            ok = [r for r in res if "error" not in r]
            rep["errors"] += [{"id": r["id"], "set": r["set"], "error": r["error"][:120]} for r in res if "error" in r][:20]
            by_set[s] = ok
            os.makedirs(out + "/records", exist_ok=True)
            p = "%s/records/%s.jsonl" % (out, s)
            with open(p, "w", encoding="utf-8") as f:
                for r in ok:
                    f.write(json.dumps(r, ensure_ascii=False) + "\n")
            st = {"pages": len(ok), "errors": len(res) - len(ok), "expected": HO_SETS[s][2], "records": p, "records_sha256": sha256_file(p),
                  "roundtrip_ok_pages": sum(1 for r in ok if r["roundtrip_ok"]), "over_cap_pages": sum(1 for r in ok if r["over_cap"]),
                  "size_inconsistent_pages": sum(1 for r in ok if not r["size_consistent"]),
                  "saved_with_exif": sum(1 for r in ok if r["saved_exif_tags"]),
                  "languages": dict(collections.Counter(r["lang"] for r in ok)), "page_types": dict(collections.Counter(r["page_type"] for r in ok)),
                  "reference_lines": sum(r["n_ref_lines"] for r in ok), "target_lines_total": sum(r["n_target_lines"] for r in ok)}
            if HO_SETS[s][0] == "school":
                st["two_column_pages"] = sum(1 for r in ok if r["gutter"] and r["gutter"].get("two_columns"))
            rep["sets"][s] = st
            print(s, json.dumps({k: st[k] for k in ("pages", "errors", "expected", "roundtrip_ok_pages", "over_cap_pages")}), flush=True)
    # leak check: ids and original image bytes of the held-out pages against every page of the page model's build
    seen_ids, seen_sha = {}, {}
    for s in ("gen_train", "gen_val", "school_train", "school_val"):
        with open("%s/%s.jsonl" % (OM_RECORDS, s), encoding="utf-8") as f:
            for line in f:
                r = json.loads(line)
                seen_ids[r["id"]] = s
                seen_sha[r["orig_sha256"]] = s
    leak = {}
    for s, recs in by_set.items():
        leak[s] = {"id_overlap": sorted(r["id"] for r in recs if r["id"] in seen_ids),
                   "orig_sha256_overlap": sorted("%s=%s" % (r["id"], seen_sha[r["orig_sha256"]]) for r in recs if r["orig_sha256"] in seen_sha)}
    rep["leak_check_sha256_and_ids"] = leak
    # known perceptual near-duplicates (R5 freeze dedupe: training items dropped from the crop mix as near-duplicates of a
    # held-out page); listed if the training page is in the page model's training records
    near = []
    if os.path.exists(DEDUPE_USED):
        with open(DEDUPE_USED, encoding="utf-8", newline="") as f:
            for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE):
                if r.get("partner_manifest") == "synth_pages_test" or str(r.get("partner_id", "")).startswith("school:test_"):
                    near.append({"train_id": r["train_id"], "reason": r["reason"], "partner_id": r["partner_id"],
                                 "same_label": r["same_label"], "train_page_in_page_model_training": seen_ids.get(r["train_id"]) in ("gen_train", "school_train")})
    rep["known_near_duplicates_of_heldout_pages"] = near
    exp_ok = all(rep["sets"][s]["pages"] == HO_SETS[s][2] for s in HO_SETS)
    rt_ok = all(rep["sets"][s]["roundtrip_ok_pages"] == rep["sets"][s]["pages"] for s in HO_SETS)
    leak_ok = all(not v["id_overlap"] and not v["orig_sha256_overlap"] for v in leak.values())
    exif_ok = all(rep["sets"][s]["saved_with_exif"] == 0 for s in HO_SETS)
    rep["checks"] = {"counts_as_expected": exp_ok, "all_roundtrips_ok": rt_ok, "no_sha256_or_id_leak": leak_ok, "saved_without_exif": exif_ok,
                     "no_errors": not rep["errors"]}
    rep["passed"] = bool(exp_ok and rt_ok and leak_ok and exif_ok and not rep["errors"])
    rep["seconds"] = round(time.time() - t0, 1)
    rep["finished_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    json.dump(rep, open(out + "/build_report_heldout.json", "w"), indent=1, ensure_ascii=False)
    print(json.dumps({"passed": rep["passed"], "checks": rep["checks"], "near_duplicates": len(near)}), flush=True)
    return 0 if rep["passed"] else 2


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=DATA + "/data/processed/r6_onemodel")
    ap.add_argument("--workers", type=int, default=16)
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--heldout", action="store_true")
    a = ap.parse_args()
    if a.heldout:
        return main_heldout(a)
    t0 = time.time()
    import multiprocessing as mp
    rep = {"design": T.DESIGN_ID, "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "out": a.out, "limit": a.limit,
           "sets": {}, "errors": []}
    # tokenizer facts (P9) checked in the parent before any page
    _init(LEADER)
    tok = _W["tok"]
    loc_ids = tok.convert_tokens_to_ids(["<|LOC_%d|>" % n for n in range(1001)])
    rep["tokenizer"] = {"loc_0_id": loc_ids[0], "loc_1000_id": loc_ids[-1],
                        "loc_ids_contiguous_100297_101297": loc_ids == list(range(100297, 101298)),
                        "eos": [tok.eos_token, tok.eos_token_id], "pad": [tok.pad_token, tok.pad_token_id],
                        "newline_ids": tok("\n", add_special_tokens=False).input_ids,
                        "loc_token_special_flag": bool(getattr(tok.added_tokens_decoder.get(100297), "special", None)),
                        "loc_in_all_special_ids": 100297 in set(tok.all_special_ids)}
    by_set = {}
    with mp.Pool(a.workers, initializer=_init, initargs=(LEADER,)) as pool:
        for s in SETS:
            jobs = jobs_for(s, a.out, a.limit)
            res = pool.map(work, jobs, chunksize=4)
            ok = [r for r in res if "error" not in r]
            rep["errors"] += [r for r in res if "error" in r][:20]
            by_set[s] = ok
            os.makedirs(a.out + "/records", exist_ok=True)
            p = "%s/records/%s.jsonl" % (a.out, s)
            with open(p, "w", encoding="utf-8") as f:
                for r in ok:
                    f.write(json.dumps(r, ensure_ascii=False) + "\n")
            n_tok = [r["n_target_tokens"] for r in ok]
            st = {"pages": len(ok), "errors": len(res) - len(ok), "expected": SETS[s][2] if not a.limit else a.limit,
                  "records": p, "records_sha256": sha256_file(p),
                  "target_tokens_incl_end": dist(n_tok), "target_lines": dist([r["n_target_lines"] for r in ok]),
                  "target_chars": dist([r["target_chars"] for r in ok]),
                  "over_cap_pages": sum(1 for r in ok if r["over_cap"]), "over_cap_ids": [r["id"] for r in ok if r["over_cap"]][:50],
                  "roundtrip_failed": [r["id"] for r in ok if not r["roundtrip_ok"]][:50],
                  "roundtrip_ok_pages": sum(1 for r in ok if r["roundtrip_ok"]),
                  "roundtrip_checks_failed_counts": dict(collections.Counter(k for r in ok for k, v in r["roundtrip"].items() if not v)),
                  "empty_text_lines_left_out": sum(r["counts"]["empty_text_lines_left_out"] for r in ok),
                  "lines_with_special_like_text": sum(r["counts"]["lines_with_special_like_text"] for r in ok),
                  "reference_lines": sum(r["n_ref_lines"] for r in ok), "target_lines_total": sum(r["n_target_lines"] for r in ok),
                  "reference_chars": sum(sum(len(x) for x in r["ref_lines"]) for r in ok),
                  "size_inconsistent": [r["id"] for r in ok if not r["size_consistent"]][:20],
                  "resized_sizes": dict(collections.Counter("%dx%d" % (r["img_w"], r["img_h"]) for r in ok).most_common(8)),
                  "visual_tokens": dist([r["img_w"] * r["img_h"] // 784 for r in ok]),
                  "saved_with_exif": sum(1 for r in ok if r["saved_exif_tags"]),
                  "exif_orientation_of_originals": dict(collections.Counter(str(r["exif_orientation"]) for r in ok)),
                  "languages": dict(collections.Counter(r["lang"] for r in ok)),
                  "page_types": dict(collections.Counter(r["page_type"] for r in ok))}
            if SETS[s][0] == "school":
                st["two_column_pages"] = sum(1 for r in ok if r["gutter"] and r["gutter"].get("two_columns"))
            rep["sets"][s] = st
            print(s, json.dumps({k: st[k] for k in ("pages", "errors", "over_cap_pages", "roundtrip_ok_pages")}), flush=True)
    # leak check: ids and original image bytes of train vs val
    for kind in ("gen", "school"):
        tr, va = by_set[kind + "_train"], by_set[kind + "_val"]
        rep.setdefault("leak_check", {})[kind] = {
            "id_overlap": len({r["id"] for r in tr} & {r["id"] for r in va}),
            "image_sha256_overlap": len({r["orig_sha256"] for r in tr} & {r["orig_sha256"] for r in va})}
    # frozen max_new_tokens for page evaluation (design page_decoding)
    train_tok = [r["n_target_tokens"] for s in ("gen_train", "school_train") for r in by_set[s]]
    p999 = pct(train_tok, 0.999)
    rep["max_new_tokens"] = {"p99.9_train_target_tokens": p999, "rule": "min(6144, ceil64(1.2 x p99.9))",
                             "value": int(min(T.MAX_NEW_CEILING, 64 * math.ceil(1.2 * p999 / 64.0))) if p999 else None}
    # sequences
    os.makedirs(a.out + "/seq", exist_ok=True)
    train_recs = by_set["gen_train"] + by_set["school_train"]
    rows, pools, used = page_sequence(train_recs)
    ps = a.out + "/seq/page_seq.tsv"
    with open(ps, "w", encoding="utf-8") as f:
        f.write("s\tpage_id\tsource\tpass\tu\n")
        for r in rows:
            f.write("\t".join(str(x) for x in r) + "\n")
    src_count = collections.Counter(r[2] for r in rows)
    passes = {k: used[k] / float(pools[k]) for k in pools if pools[k]}
    rep["page_seq"] = {"path": ps, "sha256": sha256_file(ps), "rows": len(rows), "by_source": dict(src_count),
                       "pool_pages": pools, "passes": passes, "seed": SEED,
                       "all_train_ids": all(r[1].startswith(("pg_train_", "school_train_")) for r in rows)}
    cs = a.out + "/seq/crop_seq.tsv"
    if not a.limit:
        sha = sha256_file(MIX_SEQ)
        rep["mix_seq_sha256_ok"] = sha == MIX_SEQ_SHA
    n_c, strata = 0, collections.Counter()
    with open(MIX_SEQ, encoding="utf-8") as f, open(cs, "w", encoding="utf-8") as fo:
        hdr = f.readline()
        fo.write(hdr)
        ix = {h: i for i, h in enumerate(hdr.rstrip("\n").split("\t"))}
        for k, line in enumerate(f):
            if k < CROP_START:
                continue
            if k >= CROP_START + N_CROP:
                break
            p = line.rstrip("\n").split("\t")
            strata[p[ix["stratum"]]] += 1
            fo.write(line)
            n_c += 1
    rep["crop_seq"] = {"path": cs, "sha256": sha256_file(cs), "rows": n_c, "first_row_of_mix_v1_seq": CROP_START,
                       "strata": dict(strata), "header": hdr.rstrip("\n").split("\t")}
    exp_ok = all(rep["sets"][s]["pages"] == rep["sets"][s]["expected"] for s in SETS)
    rt_ok = all(not rep["sets"][s]["roundtrip_failed"] for s in SETS)
    leak_ok = all(v["id_overlap"] == 0 and v["image_sha256_overlap"] == 0 for v in rep["leak_check"].values())
    exif_ok = all(rep["sets"][s]["saved_with_exif"] == 0 for s in SETS)
    tok_ok = rep["tokenizer"]["loc_ids_contiguous_100297_101297"]
    rep["checks"] = {"counts_as_expected": exp_ok, "all_roundtrips_ok": rt_ok, "no_leak": leak_ok, "saved_without_exif": exif_ok,
                     "loc_ids_ok": tok_ok, "no_errors": not rep["errors"], "crop_rows": n_c == N_CROP,
                     "mix_seq_sha256_ok": rep.get("mix_seq_sha256_ok", "not checked (limit)")}
    rep["passed"] = bool(exp_ok and rt_ok and leak_ok and exif_ok and tok_ok and not rep["errors"] and n_c == N_CROP
                         and rep.get("mix_seq_sha256_ok", True) is True and not a.limit)
    rep["seconds"] = round(time.time() - t0, 1)
    rep["finished_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    json.dump(rep, open(a.out + "/build_report.json", "w"), indent=1, ensure_ascii=False)
    print(json.dumps({"passed": rep["passed"], "checks": rep["checks"], "max_new_tokens": rep["max_new_tokens"]}, ensure_ascii=False), flush=True)
    return 0 if (rep["passed"] or a.limit) else 2


if __name__ == "__main__":
    sys.exit(main())