File size: 32,751 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
"""RELEASE2 job C: build the releasable package of OUR generated data under DATA/release/rc1_data/ (never uploaded).

Inputs (read-only)
  generated manifests with sidecar columns: frozen train (frozen_mix_v1/synth_{hand,typed,clutter}_train.meta.tsv),
  frozen val/test (frozen_eval_v1/synth_*_{val,test}.meta.tsv), pages (manifests/synth_pages_train.meta.tsv, frozen_eval_v1 val/test),
  pre-freeze train manifests (to list the rows dropped at the freeze),
  job B output (DATA/tmp/release2/regen/): pages.jsonl (font list, attempt and drawn documents of every regenerated page),
  row_mismatches.jsonl, regen_summary.json,
  real print train/val manifests and sidecars (pointer lists only: no image, no text),
  a decisions file (JSON): which text sources may be released.
Rules applied per item (all must pass, otherwise the item is excluded and counted with its reasons)
  1 the page of the item was regenerated and the item's row matched the stored row and bytes (provenance verified);
  2 no font of licence class personal_use_only was drawn anywhere on the item's page;
  3 every corpus document behind the item's text has a source kind allowed by the decisions file;
  4 the item is in the frozen split (rows dropped at the freeze are listed, not released).
Outputs
  hand|typed|clutter/<split>/<lang>/<bucket>/<id>.jpg, pages/<split>/<lang>/<id>.{jpg,json,xml} (PageXML 2019-07-15)
  labels/<kind>_<split>.jsonl and .tsv, excluded/excluded_items.tsv, excluded/exclusion_counts.json,
  attribution/*.tsv, LICENSE, real_print_pointers/*.tsv (owner decides whether to publish), build_report.json, SHA256SUMS
usage: CODE/.venv_gen/bin/python -I rel2_build_data.py --decisions decisions.json --out DATA/release/rc1_data --threads 8
"""
import argparse
import csv
import hashlib
import json
import os
import re
import shutil
import sys
import time
import unicodedata
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor

csv.field_size_limit(10 ** 9)
D = "/path/to/TURKIC_OCR_DATA"
R5 = D + "/data/processed/r5"
REGEN = D + "/tmp/release2/regen"
LANGS = ["kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"]
BCP47 = dict(kk="kk-Cyrl", ky="ky-Cyrl", uz_cyrl="uz-Cyrl", uz_latn="uz-Latn", tr="tr-Latn", az="az-Latn", tt="tt-Cyrl", ba="ba-Cyrl", tk="tk-Latn", sah="sah-Cyrl")
WIKI = dict(kk="kk", ky="ky", uz_cyrl="uz", uz_latn="uz", tt="tt", ba="ba", sah="sah", tr="tr", az="az", tk="tk")       # pagesynth/text.py PROFILES
FW2 = dict(kk="kaz_Cyrl", ky="kir_Cyrl", uz_cyrl="uzn_Cyrl", uz_latn="uzn_Latn", tt="tat_Cyrl", ba="bak_Cyrl", sah="sah_Cyrl", tr="tur_Latn", az="azj_Latn", tk="tuk_Latn")
RX_LINE = re.compile(r"^(hs|ts|cl)_(train|val|test)_(.+)_(\d{6})_(\d{2})$")
RX_PAGE = re.compile(r"^pg_(train|val|test)_[a-z]+_(.+)_[lmh]_(\d{6})$")
KINDDIR = dict(hand="hand", typed="typed", clutter="clutter", pages="pages")
SCRUB = ("/datahub", "/shared/home", "CLUSTER_USER", "CLUSTER_GROUP")
PAGE_NS = "http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15"
STYLE_COLS = ("slant_deg", "spacing", "word_gap", "drift_xh", "weight_px", "tex_depth", "elastic", "elastic_alpha", "size_scale")


def sha_int(*parts):        # produce_r5.sha_int and page.seed_for use the same hash
    return int.from_bytes(hashlib.sha256("|".join(str(p) for p in parts).encode("utf-8")).digest()[:8], "little")


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


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


def doc_kind(d):
    return d.split(":")[0] if d else ""


def jload(s, default):
    try:
        return json.loads(s) if s else default
    except Exception:
        return default


def to_num(v):
    if v in ("", None):
        return None
    try:
        f = float(v)
        return int(f) if f.is_integer() and "." not in v else f
    except ValueError:
        return v


def pts(poly, W, H):
    out = []
    for x, y in poly:
        xi = min(max(int(round(float(x))), 0), W - 1)
        yi = min(max(int(round(float(y))), 0), H - 1)
        out.append("%d,%d" % (xi, yi))
    if len(out) < 3:
        out = out + out[-1:] * (3 - len(out))
    return " ".join(out)


def page_xml(pj, image_name, created):
    ET.register_namespace("", PAGE_NS)
    W, H = int(pj["image"]["width"]), int(pj["image"]["height"])
    root = ET.Element("{%s}PcGts" % PAGE_NS)
    md = ET.SubElement(root, "{%s}Metadata" % PAGE_NS)
    ET.SubElement(md, "{%s}Creator" % PAGE_NS).text = "pagesynth %s (generated page)" % pj.get("generator_version", "")
    ET.SubElement(md, "{%s}Created" % PAGE_NS).text = created
    ET.SubElement(md, "{%s}LastChange" % PAGE_NS).text = created
    ET.SubElement(md, "{%s}Comments" % PAGE_NS).text = ("Synthetic page; every text line has a polygon, a baseline and its exact label. "
                                                        "Non-text regions: figure, stamp, picture, table, ignore (sticker etc.).")
    pg = ET.SubElement(root, "{%s}Page" % PAGE_NS, imageFilename=image_name, imageWidth=str(W), imageHeight=str(H))
    lines = sorted(pj.get("lines", []), key=lambda r: r.get("reading_order", 0))
    ro = ET.SubElement(pg, "{%s}ReadingOrder" % PAGE_NS)
    og = ET.SubElement(ro, "{%s}OrderedGroup" % PAGE_NS, id="ro_1", caption="reading order")
    for i, ln in enumerate(lines):
        ET.SubElement(og, "{%s}RegionRefIndexed" % PAGE_NS, index=str(i), regionRef="tr_" + ln["id"])
    n_nfc = 0
    for i, ln in enumerate(lines):
        t = unicodedata.normalize("NFC", ln.get("text", ""))
        if t != ln.get("text", ""):
            n_nfc += 1
        rc = ln.get("region_class", "")
        tr = ET.SubElement(pg, "{%s}TextRegion" % PAGE_NS, id="tr_" + ln["id"], custom="structure {type:%s;} readingOrder {index:%d;}" % (rc, i))
        ET.SubElement(tr, "{%s}Coords" % PAGE_NS, points=pts(ln["polygon"], W, H))
        tl = ET.SubElement(tr, "{%s}TextLine" % PAGE_NS, id=ln["id"], custom="readingOrder {index:0;} font {id:%s;}" % ln.get("font_id", ""))
        ET.SubElement(tl, "{%s}Coords" % PAGE_NS, points=pts(ln["polygon"], W, H))
        if ln.get("baseline"):
            ET.SubElement(tl, "{%s}Baseline" % PAGE_NS, points=pts(ln["baseline"], W, H) if len(ln["baseline"]) >= 2 else pts(ln["baseline"] * 2, W, H))
        te = ET.SubElement(tl, "{%s}TextEquiv" % PAGE_NS)
        ET.SubElement(te, "{%s}Unicode" % PAGE_NS).text = t
        te2 = ET.SubElement(tr, "{%s}TextEquiv" % PAGE_NS)
        ET.SubElement(te2, "{%s}Unicode" % PAGE_NS).text = t
    kinds = Counter()
    for rg in pj.get("regions", []):
        t = rg.get("type", "")
        rid = rg.get("id") or ("rg%d" % sum(kinds.values()))
        kinds[t] += 1
        poly = rg.get("polygon") or []
        if len(poly) < 2:
            continue
        if t == "stamp":
            el = ET.SubElement(pg, "{%s}GraphicRegion" % PAGE_NS, id=rid, type="stamp")
        elif t == "picture":
            el = ET.SubElement(pg, "{%s}ImageRegion" % PAGE_NS, id=rid)
        elif t == "table":
            el = ET.SubElement(pg, "{%s}TableRegion" % PAGE_NS, id=rid)
        elif t == "ignore":
            el = ET.SubElement(pg, "{%s}NoiseRegion" % PAGE_NS, id=rid, custom="structure {type:%s;}" % (rg.get("note") or "ignore"))
        else:
            el = ET.SubElement(pg, "{%s}GraphicRegion" % PAGE_NS, id=rid, type="other", custom="structure {type:%s;}" % (t or "other"))
        ET.SubElement(el, "{%s}Coords" % PAGE_NS, points=pts(poly, W, H))
    xml = ET.tostring(root, encoding="unicode")
    return '<?xml version="1.0" encoding="UTF-8"?>\n' + xml + "\n", n_nfc, dict(kinds)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--decisions", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--threads", type=int, default=8)
    ap.add_argument("--limit", type=int, default=0, help="smoke test: at most N items per (kind, split)")
    a = ap.parse_args()
    dec = json.load(open(a.decisions, encoding="utf-8"))
    allowed = dec["text_source_kinds_allowed"]          # e.g. {"wiki": true, "fw2": true, "ailab": false}
    lic_of = dec["text_licence_label"]                  # e.g. {"wiki": "CC-BY-SA-4.0", ...}
    OUT = a.out
    if os.path.exists(OUT) and os.listdir(OUT):
        sys.exit("output folder exists and is not empty: %s" % OUT)
    os.makedirs(OUT, exist_ok=True)
    t0 = time.time()
    created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())

    # ---- job B results
    regen = {}
    with open(REGEN + "/pages.jsonl", encoding="utf-8") as f:
        for line in f:
            r = json.loads(line)
            regen[(r["split"], r["lang"], r["pop"], r["idx"])] = r
    bad = {}
    with open(REGEN + "/row_mismatches.jsonl", encoding="utf-8") as f:
        for line in f:
            r = json.loads(line)
            bad[r["id"]] = r
    summ = json.load(open(REGEN + "/regen_summary.json", encoding="utf-8")) if os.path.exists(REGEN + "/regen_summary.json") else {}
    print("regen pages", len(regen), "mismatching rows", len(bad), flush=True)

    sets = []
    for kind in ("hand", "typed", "clutter"):
        sets.append((kind, "train", R5 + "/frozen_mix_v1/synth_%s_train.meta.tsv" % kind))
        for sp in ("val", "test"):
            sets.append((kind, sp, R5 + "/frozen_eval_v1/synth_%s_%s.meta.tsv" % (kind, sp)))
    sets.append(("pages", "train", R5 + "/manifests/synth_pages_train.meta.tsv"))
    for sp in ("val", "test"):
        sets.append(("pages", sp, R5 + "/frozen_eval_v1/synth_pages_%s.meta.tsv" % sp))

    counts = defaultdict(Counter)        # "kind|split|lang" -> Counter(in, kept, reason...)
    excluded_rows = []
    copy_jobs = []                       # (src, dst_rel)
    label_rows = defaultdict(list)       # "kind_split" -> records
    attrib = defaultdict(Counter)        # source kind -> Counter((lang, doc))
    font_use = Counter()
    seed_checks = Counter()
    nfc_changed = Counter()
    region_kinds = Counter()
    evidence_stats = Counter()
    page_side = {}                       # page id -> (xml text, json text)

    def page_key(rid, lang):
        m = RX_LINE.match(rid)
        if m:
            return (m.group(2), lang, "T" if m.group(1) == "ts" else "H", int(m.group(4)))
        m = RX_PAGE.match(rid)
        return (m.group(1), lang, "H", int(m.group(3)))

    # ---- stored evidence per page: fonts of every stored row of the page (frozen, pre-freeze, val/test) and the saved page JSON
    stored_fonts = defaultdict(dict)     # page key -> {font_id: licence class}
    stored_writer_or_print = defaultdict(set)
    saved_json = {}                    # page key -> path of the saved page JSON
    ev_paths = [p for _, _, p in sets] + [R5 + "/manifests/synth_%s_train.meta.tsv" % k for k in ("hand", "typed", "clutter")]
    for p in ev_paths:
        for r in load_tsv(p):
            k = page_key(r["id"], r["lang"])
            if r.get("unit") == "page":
                saved_json[k] = r["source"]
            elif r.get("font_id"):
                stored_fonts[k][r["font_id"]] = r.get("font_licence_class", "")
                if r.get("region_class") != "teacher_mark":     # teacher marks use a separate open face drawn later on the page
                    stored_writer_or_print[k].add(r["font_id"])
    saved_cache = {}
    # pages whose regenerated rows differ from the stored rows in content (text, font, line, class): their regenerated font list is
    # not trusted (a diverged retry chain would mean another seed); used only when no saved page JSON exists
    content_diff_pages = set()
    for rid, b in bad.items():
        if set(b.get("cols") or []) & {"text", "font_id", "line_id", "region_class"}:
            m = RX_LINE.match(rid)
            if m:
                content_diff_pages.add((m.group(2), m.group(3), "T" if m.group(1) == "ts" else "H", int(m.group(4))))
    print("pages with a content difference between stored and regenerated rows", len(content_diff_pages), flush=True)
    # items flagged by the Sakha attribution check (rel2_sakha_check.py): label text found, exactly or as a 3-word window, in a
    # newspaper (ailab) sentence drawn for its page although the line attribution named no ailab document
    extra_excl = {}
    if dec.get("extra_exclusions_json") and os.path.exists(dec["extra_exclusions_json"]):
        for h in json.load(open(dec["extra_exclusions_json"], encoding="utf-8")).get("hits", []):
            extra_excl[h["id"]] = "text_source_not_cleared:ailab_unattributed_match"
    print("extra exclusions", len(extra_excl), flush=True)
    # sha256 of every generated image recorded before training (DATA build log, 2026-11-21T01:52:29Z)
    pre_hash = {}
    with open(R5 + "/build_logs/hashes_synth.tsv", newline="", encoding="utf-8") as f:
        for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE):
            pre_hash[r["id"]] = r["sha256"]

    def saved_page(k):
        if k not in saved_json:
            return None
        if k not in saved_cache:
            try:
                saved_cache[k] = json.load(open(saved_json[k], encoding="utf-8"))
            except Exception:
                saved_cache[k] = None
        return saved_cache[k]

    for kind, sp, path in sets:
        rows = load_tsv(path)
        if a.limit:
            rows = rows[: a.limit]
        for r in rows:
            lang = r["lang"]
            ck = "%s|%s|%s" % (kind, sp, lang)
            counts[ck]["in_frozen_split"] += 1
            reasons = []
            key = page_key(r["id"], lang)
            _, _, pop, idx = key
            pr = regen.get(key)
            page = pr.get("page") if pr else None
            pj = saved_page(key)                      # exact record of the production page (saved pages: train idx < 400, val/test idx < 30)
            stored = stored_fonts.get(key, {})
            if pj is not None:
                fonts, font_source = pj.get("fonts", []), "saved page JSON (production record)"
                evidence_stats["fonts_from_saved_page_json"] += 1
                if page is not None:
                    evidence_stats["saved_vs_regenerated_fonts_equal" if sorted(x["id"] for x in fonts) == sorted(x["id"] for x in page.get("fonts") or []) else "saved_vs_regenerated_fonts_differ"] += 1
                    evidence_stats["saved_vs_regenerated_attempt_equal" if (pj.get("info") or {}).get("attempt") == page.get("attempt") else "saved_vs_regenerated_attempt_differ"] += 1
            elif page is not None:
                fonts, font_source = page.get("fonts") or [], "regenerated page (generator re-run, same seed)"
                evidence_stats["fonts_from_regenerated_page"] += 1
                if key in content_diff_pages:
                    reasons.append("regenerated_page_content_differs_from_stored_rows")
                if r["id"] not in set(pr.get("row_ids") or []):
                    reasons.append("row_not_reproduced_by_regeneration")
                missing = [f for f in stored_writer_or_print.get(key, ()) if f not in set(x["id"] for x in fonts)]
                evidence_stats["regenerated_pages_checked_against_stored_rows"] += 1
                if missing:
                    evidence_stats["regenerated_page_lacks_a_stored_writer_or_print_font"] += 1
                    reasons.append("regenerated_page_lacks_a_stored_row_font")
            else:
                fonts, font_source = [], "none"
                reasons.append("page_fonts_unknown")
            personal = sorted(set([x["id"] for x in fonts if x.get("licence_class") == "personal_use_only"] +
                                  [f for f, lc in stored.items() if lc == "personal_use_only"]))
            if personal:
                reasons.append("personal_use_font_on_page")
            if kind == "pages" and pj is None:
                reasons.append("page_json_unreadable")
            # text documents
            conf = r.get("source_doc_confidence", "")
            sd = r.get("source_doc", "")
            page_docs = list(dict.fromkeys(((pr or {}).get("drawn_docs") or []) + [x for x in sd.split("|") if x]))
            if kind == "pages":
                docs, scope = [x for x in sd.split("|") if x], "page (documents of every line of the page, as recorded at production)"
            elif kind == "clutter":
                docs, scope = [], "none (no text)"
            elif conf in ("unique", "split") or (conf == "ambiguous" and sd.count("|") < 2):
                docs, scope = [x for x in sd.split("|") if x], "line"
            elif conf == "ambiguous":
                docs, scope = list(page_docs), "page (line matched 3 or more documents; all documents drawn for the page are listed)"
            else:
                docs, scope = [], "none (generator-made text: vocabulary word, number, date, grade or label)"
            kinds_used = sorted(set(doc_kind(x) for x in docs))
            for k in kinds_used:
                if not allowed.get(k, False):
                    reasons.append("text_source_not_cleared:%s" % k)
            if r["id"] in extra_excl:
                reasons.append(extra_excl[r["id"]])
            # seed: page seed as in pagesynth/generate.py make_page -> page.seed_for(global_seed, page_type, lang, index, attempt)
            gseed = int(sha_int("r5v1", sp, pop) % (2 ** 31))
            pindex = idx if pop == "H" else 10_000_000 + idx
            ptype = r.get("page_type", "")
            if pj is not None:
                attempt, seed_source = (pj.get("info") or {}).get("attempt"), "saved page JSON"
            else:
                attempt, seed_source = (page or {}).get("attempt"), "attempt from the regenerated page"
            pseed = sha_int(gseed, ptype, lang, pindex, attempt) if attempt is not None else None
            if pj is not None and pseed is not None:
                seed_checks["equal" if pj.get("seed") == pseed else "differ"] += 1
            if reasons:
                for x in sorted(set(reasons)):
                    counts[ck]["excluded:" + x] += 1
                counts[ck]["excluded_items"] += 1
                excluded_rows.append((r["id"], kind, sp, lang, ";".join(sorted(set(reasons))), ",".join(personal)))
                continue
            counts[ck]["kept"] += 1
            for k in kinds_used:
                counts[ck]["kept_with_text_source:%s" % k] += 1
            # destination
            if kind == "pages":
                rel = "pages/%s/%s/%s.jpg" % (sp, lang, r["id"])
            else:
                rel = "%s/%s/%s/%04d/%s.jpg" % (KINDDIR[kind], sp, lang, idx // 500, r["id"])
            copy_jobs.append((r["image"], rel, r["id"]))
            text = r.get("text", "")
            if unicodedata.normalize("NFC", text) != text:
                nfc_changed[kind] += 1
            licences = sorted(set(lic_of[k] for k in kinds_used)) if kinds_used else []
            rec = dict(id=r["id"], image=rel, text=text, language=lang, language_bcp47=BCP47[lang], script=r["script"], kind=r["kind"], unit=r["unit"], split=sp,
                       font_id=r.get("font_id", ""), font_licence_class=r.get("font_licence_class", ""), heldout_font=to_num(r.get("heldout_font", "")),
                       generator_version="pagesynth-0.3.0",
                       seed=(str(pseed) if pseed is not None else None), seed_detail=dict(seed_tag="r5v1", population=pop, split_seed=gseed, page_type=ptype, page_index=pindex, attempt=attempt,
                                                    attempt_source=seed_source,
                                                    rule="page_seed = first 8 bytes (little-endian) of sha256('split_seed|page_type|lang|page_index|attempt'); "
                                                         "split_seed = that hash of 'r5v1|split|population' modulo 2^31"),
                       page_font_source=font_source,
                       page_id=r.get("page_id", ""), line_id=r.get("line_id", ""), group=r.get("group", ""), page_type=ptype, strength=r.get("strength", ""),
                       capture_mode=r.get("geo_mode", ""), paper_kind=r.get("paper_kind", ""), region_class=r.get("region_class", ""), ink=r.get("ink", ""),
                       crop_mode=r.get("crop_mode", ""), size_px=to_num(r.get("size_px", "")), font_axes=jload(r.get("font_axes", ""), {}),
                       writer_style={c: to_num(r.get(c, "")) for c in STYLE_COLS if r.get(c, "") != ""},
                       overlaps=[x for x in r.get("overlaps", "").split(",") if x], mixed=to_num(r.get("mixed", "")), orig_text=r.get("orig_text", ""),
                       n_chars=to_num(r.get("n_chars", "")), n_words=to_num(r.get("n_words", "")),
                       effects=[x for x in r.get("effects_all", "").split("|") if x], photo=jload(r.get("photo_json", ""), {}), geometry=jload(r.get("geometry_json", ""), {}),
                       text_sources=docs, text_source_scope=scope, text_source_confidence=conf if kind != "pages" else "page",
                       text_licences=licences, page_fonts=[x["id"] for x in fonts])
            if kind == "pages":
                rec["pagexml"] = "pages/%s/%s/%s.xml" % (sp, lang, r["id"])
                rec["page_json"] = "pages/%s/%s/%s.json" % (sp, lang, r["id"])
                xml, n_nfc, rk = page_xml(pj, r["id"] + ".jpg", created)
                region_kinds.update(rk)
                nfc_changed["pagexml_lines"] += n_nfc
                js = json.dumps(pj, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
                page_side[r["id"]] = (rec["pagexml"], xml, rec["page_json"], js)
            label_rows["%s_%s" % (kind, sp)].append(rec)
            for d in docs:
                attrib[doc_kind(d)][(lang, d)] += 1
            for fid in rec["page_fonts"]:
                font_use[fid] += 1
        print(kind, sp, "rows", len(rows), "kept so far", sum(c["kept"] for c in counts.values()), "%.0f s" % (time.time() - t0), flush=True)

    # ---- dropped at the freeze (listed, never released)
    for kind in ("hand", "typed", "clutter"):
        fz = set(r["id"] for r in load_tsv(R5 + "/frozen_mix_v1/synth_%s_train.tsv" % kind))
        for r in load_tsv(R5 + "/manifests/synth_%s_train.tsv" % kind):
            if r["id"] not in fz:
                ck = "%s|train|%s" % (kind, r["lang"])
                counts[ck]["dropped_at_freeze_not_in_frozen_split"] += 1
                excluded_rows.append((r["id"], kind, "train", r["lang"], "dropped_at_freeze (near-duplicate of, or label equal to, a validation or test row; never in the frozen training mix)", ""))

    # ---- copy images (verify bytes)
    sums = {}

    def do_copy(job):
        src, rel, iid = job
        dst = os.path.join(OUT, rel)
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        shutil.copyfile(src, dst)
        hs, hd = sha256_file(src), sha256_file(dst)
        return rel, hd, hs == hd, os.path.getsize(dst), iid, hs

    bytes_by_top = Counter()
    copy_bad = []
    pretrain = Counter()
    pretrain_diff = []
    with ThreadPoolExecutor(a.threads) as ex:
        for i, (rel, hd, ok, sz, iid, hs) in enumerate(ex.map(do_copy, copy_jobs, chunksize=64)):
            ph = pre_hash.get(iid)
            if ph is None:
                pretrain["not_in_pretraining_hash_log"] += 1
            elif ph == hs:
                pretrain["equal_to_pretraining_hash"] += 1
            else:
                pretrain["differs_from_pretraining_hash"] += 1
                pretrain_diff.append(iid)
            sums[rel] = hd
            bytes_by_top[rel.split("/")[0]] += sz
            if not ok:
                copy_bad.append(rel)
            if i % 20000 == 0:
                print("copied", i, "%.0f s" % (time.time() - t0), flush=True)

    def write_text(rel, text):
        p = os.path.join(OUT, rel)
        os.makedirs(os.path.dirname(p), exist_ok=True)
        with open(p, "w", encoding="utf-8", newline="") as f:
            f.write(text)
        sums[rel] = sha256_file(p)
        bytes_by_top[rel.split("/")[0]] += os.path.getsize(p)

    for pid, (xrel, xml, jrel, js) in page_side.items():
        write_text(xrel, xml)
        write_text(jrel, js + "\n")
        ET.fromstring(xml.split("\n", 1)[1])         # well-formed check (raises if not)

    # ---- labels
    tsv_cols = ["id", "image", "text", "language", "script", "kind", "split", "font_id", "generator_version", "seed", "page_id", "line_id", "crop_mode", "text_licences"]
    for key, recs in sorted(label_rows.items()):
        write_text("labels/%s.jsonl" % key, "".join(json.dumps(x, ensure_ascii=False, sort_keys=True) + "\n" for x in recs))
        lines = ["\t".join(tsv_cols)]
        for x in recs:
            vals = []
            for c in tsv_cols:
                v = x.get(c, "")
                v = "|".join(v) if isinstance(v, list) else ("" if v is None else str(v))
                vals.append(v.replace("\t", " ").replace("\n", " "))
            lines.append("\t".join(vals))
        write_text("labels/%s.tsv" % key, "\n".join(lines) + "\n")

    # ---- exclusions
    write_text("excluded/excluded_items.tsv", "id\tkind\tsplit\tlanguage\treasons\tpersonal_use_fonts_on_page\n" +
               "".join("\t".join(x) + "\n" for x in sorted(excluded_rows)))
    write_text("excluded/exclusion_counts.json", json.dumps({k: dict(v) for k, v in sorted(counts.items())}, indent=1, sort_keys=True) + "\n")

    # ---- attribution
    rows = ["language\twikipedia\tpage_id\turl\titems"]
    for (lang, d), n in sorted(attrib.get("wiki", {}).items()):
        pid = d.split(":", 1)[1]
        rows.append("%s\t%s.wikipedia.org\t%s\thttps://%s.wikipedia.org/wiki?curid=%s\t%d" % (lang, WIKI[lang], pid, WIKI[lang], pid, n))
    write_text("attribution/wikipedia_articles.tsv", "\n".join(rows) + "\n")
    rows = ["language\tfineweb2_config\tdocument_id\titems"]
    for (lang, d), n in sorted(attrib.get("fw2", {}).items()):
        rows.append("%s\t%s\t%s\t%d" % (lang, FW2[lang], d.split(":", 1)[1], n))
    write_text("attribution/fineweb2_documents.tsv", "\n".join(rows) + "\n")
    if attrib.get("ailab"):
        rows = ["language\tcorpus\tnewspaper_source\tdocument_ref\titems"]
        for (lang, d), n in sorted(attrib["ailab"].items()):
            parts = d.split(":")
            rows.append("%s\tailabykt/sakha-corpus-mono\t%s\t%s\t%d" % (lang, parts[1] if len(parts) > 1 else "", ":".join(parts[2:]), n))
        write_text("attribution/sakha_corpus_documents.tsv", "\n".join(rows) + "\n")
    other = {k: sum(v.values()) for k, v in attrib.items() if k not in ("wiki", "fw2", "ailab")}
    fl = ["font_id\titems_whose_page_uses_the_font"] + ["%s\t%d" % (k, v) for k, v in sorted(font_use.items())]
    write_text("attribution/fonts_used.tsv", "\n".join(fl) + "\n")
    write_text("LICENSE", dec["licence_file_text"])
    write_text("attribution/notices.json", json.dumps(dec["notices"], ensure_ascii=False, indent=1) + "\n")

    # ---- real print pointers (train and val only; no images, no text)
    pointer_counts = Counter()
    if dec.get("build_print_pointers"):
        ids = {}
        for sp in ("train", "val"):
            p = R5 + ("/frozen_mix_v1/print_real_train.tsv" if sp == "train" else "/manifests/print_real_val.tsv")
            for r in load_tsv(p):
                ids[r["id"]] = sp
        out = {"train": ["id\tlanguage\tscript\tsplit\tdocument\tsource\turl\tdocument_sha256\tpage\tdpi\tpad_px\tbbox_pt\tsize_pt\tcrop_png_sha256\tlabel_nfc_sha256"],
               "val": None}
        out["val"] = list(out["train"][:1])
        for sc in sorted(os.listdir(R5 + "/print_real/_sidecars")):
            if not sc.endswith(".jsonl") or sc.startswith("more"):
                continue
            with open(os.path.join(R5, "print_real/_sidecars", sc), encoding="utf-8") as f:
                for line in f:
                    if '"split": "train"' not in line and '"split": "val"' not in line:
                        continue          # test rows are skipped before parsing
                    r = json.loads(line)
                    sp = ids.get(r["id"])
                    if sp is None or r.get("split") != sp:
                        pointer_counts["sidecar_row_not_in_released_manifest"] += 1
                        continue
                    lab = hashlib.sha256(unicodedata.normalize("NFC", r.get("text", "")).encode("utf-8")).hexdigest()
                    out[sp].append("\t".join(str(x) for x in (r["id"], r["lang"], r["script"], sp, r["group"], r["source"], r.get("url", ""), r.get("doc_sha256", ""),
                                                             r.get("page", ""), r.get("dpi", ""), r.get("pad", ""), ",".join(str(v) for v in r.get("bbox_pt", [])),
                                                             r.get("size_pt", ""), r.get("sha256", ""), lab)))
                    pointer_counts[sp] += 1
        # separate package (owner decision D7): its own notice and checksums, outside the CC BY-SA data package
        PO = OUT.rstrip("/") + "_print_pointers" if not dec.get("pointer_dir") else dec["pointer_dir"]
        os.makedirs(PO, exist_ok=True)
        psums = {}
        for sp in ("train", "val"):
            fn = "print_real_%s_pointers.tsv" % sp
            with open(os.path.join(PO, fn), "w", encoding="utf-8", newline="") as f:
                f.write("\n".join(out[sp]) + "\n")
            psums[fn] = sha256_file(os.path.join(PO, fn))
        with open(os.path.join(PO, "NOTICE"), "w", encoding="utf-8") as f:
            f.write(dec["pointer_notice_text"])
        psums["NOTICE"] = sha256_file(os.path.join(PO, "NOTICE"))
        with open(os.path.join(PO, "SHA256SUMS"), "w", encoding="utf-8") as f:
            for k in sorted(psums):
                f.write("%s  %s\n" % (psums[k], k))
        pointer_counts["manifest_ids_train"] = sum(1 for v in ids.values() if v == "train")
        pointer_counts["manifest_ids_val"] = sum(1 for v in ids.values() if v == "val")
        pointer_counts["folder"] = PO.replace(D, "DATA")
        pointer_counts["bytes"] = sum(os.path.getsize(os.path.join(PO, k)) for k in psums)

    # ---- scrub check over every text file written
    scrub_hits = []
    for rel in sorted(sums):
        if rel.endswith((".jsonl", ".tsv", ".json", ".xml")) or rel == "LICENSE":
            with open(os.path.join(OUT, rel), encoding="utf-8") as f:
                s = f.read()
            for w in SCRUB:
                if w in s:
                    scrub_hits.append((rel, w))
    report = dict(written_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), seconds=round(time.time() - t0, 1), out=OUT.replace(D, "DATA"),
                  decisions=dec, limit=a.limit, regen_summary_totals=summ.get("totals"), regen_rows_not_regenerated=summ.get("manifest_rows_not_regenerated"),
                  counts={k: dict(v) for k, v in sorted(counts.items())}, files=len(sums) + 1, bytes_by_top_folder=dict(bytes_by_top),
                  total_bytes=sum(bytes_by_top.values()), copy_byte_mismatch=copy_bad[:20], n_copy_byte_mismatch=len(copy_bad),
                  page_seed_check=dict(seed_checks), nfc_changed=dict(nfc_changed), page_region_kinds=dict(region_kinds),
                  page_font_evidence=dict(evidence_stats), regenerated_rows_with_any_difference=len(bad),
                  regen_column_mismatch_counts=summ.get("column_mismatch_counts"),
                  attribution_documents={k: len(v) for k, v in attrib.items()}, other_text_source_kinds=other,
                  print_pointer_counts=dict(pointer_counts), scrub_hits=scrub_hits[:50], n_scrub_hits=len(scrub_hits),
                  images_vs_pretraining_hash_log=dict(pretrain, log="DATA/data/processed/r5/build_logs/hashes_synth.tsv (finished 2026-11-21T01:52:29Z, before the first training sequence was built)",
                                                      differing_examples=pretrain_diff[:20]),
                  pages_with_content_difference_stored_vs_regenerated=len(content_diff_pages))
    write_text("build_report.json", json.dumps(report, ensure_ascii=False, indent=1, sort_keys=True) + "\n")
    with open(os.path.join(OUT, "SHA256SUMS"), "w", encoding="utf-8") as f:
        for rel in sorted(sums):
            f.write("%s  %s\n" % (sums[rel], rel))
    print(json.dumps(dict(kept=sum(c["kept"] for c in counts.values()), excluded=len(excluded_rows), bytes=sum(bytes_by_top.values()),
                          scrub_hits=len(scrub_hits), copy_bad=len(copy_bad), seed_checks=dict(seed_checks))), flush=True)


if __name__ == "__main__":
    main()