File size: 26,118 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
"""Showcase, job A (generator environment .venv_gen): typed "_T" validation pages and the generator-stage dumps.

Part T. One population-T validation page per language, rebuilt with the production code exactly as produce_r5.work() builds it
(seed sha_int("r5v1", "val", "T") % 2**31, page index 10,000,000 + idx, page type pick_type(page_mix_typed, lang, idx, seed),
strength "mixed", font policy set_font_policy("val"), validation sentence banks). Production never saved these pages (only their
print-line crops), so each rebuilt page is checked against the production crops: for every production crop of the page the line
is cut again with crops.crop_line (same polygon, same crop mode), JPEG-encoded at quality 92 like production, and its bytes are
compared with the production crop file (sha256). The page is then saved like a production page (page JSON with line boxes) and
turned into a detector page with linedet.det_prep._gen_work (long side 1280 px, reference lines in reading order).

Part S. Generator stages of chosen handwritten validation pages (population H): produce_r5.work() is run once for the page with
pass-through wrappers around the generator's own functions (each wrapper calls the original with the same arguments, keeps a
copy of its inputs or outputs, and returns the original result unchanged, so the random streams are untouched). The rebuilt page
and its crops are compared byte for byte with the production page and crops. Then each stage is written as a PNG.

usage: showcase_gen.py --selection JSON --out DIR [--stage_pages kk:1,uz_latn:11]
Validation data only.
"""
import argparse
import copy
import hashlib
import json
import os
import sys
import time
import types
import unicodedata

CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
PS = CODE + "/src/pagesynth"
sys.path.insert(0, PS)
sys.path.insert(0, CODE + "/src")

import cv2  # noqa: E402
import numpy as np  # noqa: E402

import produce_r5 as PR  # noqa: E402
from pagesynth import crops as CR  # noqa: E402
from pagesynth import fonts as F  # noqa: E402
from pagesynth import generate as GEN  # noqa: E402
from pagesynth import geometry as GM  # noqa: E402
from pagesynth import ink as I  # noqa: E402
from pagesynth import layouts as L  # noqa: E402
from pagesynth import page as PG  # noqa: E402
from pagesynth import paper as P  # noqa: E402
from linedet import det_prep as DP  # noqa: E402

TEXT_DIR = DATA + "/data/processed/r5/pagesynth_text_split/val"
SYNTH = DATA + "/data/processed/r5/synth"


def sha(b):
    return hashlib.sha256(b).hexdigest()


def sha_file(p):
    with open(p, "rb") as f:
        return sha(f.read())


def jpg_bytes(img, q):
    ok, enc = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, q])
    assert ok
    return enc.tobytes()


def jsonable(v):
    if isinstance(v, dict):
        return {str(k): jsonable(x) for k, x in v.items()}
    if isinstance(v, (list, tuple)):
        return [jsonable(x) for x in v]
    if isinstance(v, np.ndarray):
        return v.tolist() if v.size <= 64 else "array%s" % (list(v.shape),)
    if isinstance(v, (np.floating,)):
        return float(v)
    if isinstance(v, (np.integer,)):
        return int(v)
    if isinstance(v, (str, int, float, bool)) or v is None:
        return v
    return repr(v)


# ------------------------------------------------------------------------------------------------ part T
def typed_pages(sel, out, banks_cache, report):
    seed = int(PR.sha_int(PR.CFG["seed_tag"], "val", "T") % (2 ** 31))
    report["typed_seed"] = seed
    PR.set_font_policy("val")
    tdir = os.path.join(out, "typed")
    os.makedirs(tdir, exist_ok=True)
    det_root = os.path.join(out, "typed_det")
    det_rows = []
    res = []
    for t in sel["typed"]:
        lang, idx = t["lang"], int(t["idx"])
        banks = banks_cache(lang)
        ptype = PR.pick_type(PR.CFG["page_mix_typed"], lang, idx, seed)
        t0 = time.time()
        banks[lang].drawn = []
        img, pj, qa, failures = GEN.attempt_page(ptype, lang, 10_000_000 + idx, seed, "mixed", banks, include_personal=True)
        gen_s = time.time() - t0
        r = dict(lang=lang, idx=idx, page_type=ptype, selected_kind=t["kind"], seconds_generate=round(gen_s, 2),
                 failures=[list(map(str, f)) for f in failures])
        if img is None:
            r["error"] = "generation failed"
            res.append(r)
            continue
        page_id = pj["page_id"] + "_T"
        r["page_id"] = page_id
        r["matches_selection_page_id"] = page_id == t["page_id"]
        lines = {ln["id"]: ln for ln in pj["lines"]}
        checks = []
        for c in t["production_crops"]:
            ln = lines.get(c["line_id"])
            prod = os.path.join(SYNTH, "typed", "val", lang, "%04d" % (idx // 500), c["id"] + ".jpg")
            row = dict(crop_id=c["id"], line_id=c["line_id"], mode=c["crop_mode"], text_equal=bool(ln is not None and unicodedata.normalize("NFC", ln["text"]) == c["text"]))
            if ln is not None and os.path.exists(prod):
                mine = jpg_bytes(CR.crop_line(img, ln["polygon"], c["crop_mode"]), PR.CFG["jpeg_quality"])
                row["sha_equal"] = sha(mine) == sha_file(prod)
            else:
                row["sha_equal"] = None
                row["note"] = "line or production file missing"
            checks.append(row)
        r["production_crop_checks"] = checks
        r["all_production_crops_identical"] = all(x.get("sha_equal") and x["text_equal"] for x in checks)
        # save like a production page (produce_r5.work, pop H branch), then the detector page (det_prep._gen_work)
        pid = "pg_val_" + page_id
        ip, jp = os.path.join(tdir, pid + ".jpg"), os.path.join(tdir, pid + ".json")
        cv2.imwrite(ip, img, [cv2.IMWRITE_JPEG_QUALITY, PR.CFG["page_jpeg_quality"]])
        for ln in pj["lines"]:
            ln["box"] = CR.box_of(ln["polygon"])
        pj["split"] = "val"
        pj["generator_version"] = GEN.VERSION
        with open(jp, "w", encoding="utf-8") as f:
            json.dump(pj, f, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
        d = DP._gen_work((jp, "val", det_root))
        if "error" in d:
            r["det_error"] = d["error"]
        else:
            det_rows.append((d["id"], d["image"], d["width"], d["height"], "%.6f" % d["scale"], len(d["boxes"]), json.dumps(d["boxes"]),
                             json.dumps(d["polys"]), json.dumps(d["baselines"]), json.dumps(d["ref_lines"], ensure_ascii=False), d["note"]))
            cls = [ln["region_class"] for ln in sorted(pj["lines"], key=lambda L_: L_.get("reading_order", 0))]
            texts = [ln["text"] for ln in sorted(pj["lines"], key=lambda L_: L_.get("reading_order", 0))]
            r["n_lines"] = len(pj["lines"])
            r["line_classes"] = {k: cls.count(k) for k in sorted(set(cls))}
            r["ref_chars"] = sum(len(x) for x in texts)
            r["print_chars"] = sum(len(x) for x, c in zip(texts, cls) if c == "print")
            r["ref_line_classes"] = cls
            r["page_size"] = [int(pj["image"]["width"]), int(pj["image"]["height"])]
            r["det_size"] = [d["width"], d["height"]]
            r["strength"] = pj["strength"]
            r["geometry"] = {k: v for k, v in pj["geometry"].items() if k not in ("M", "phases")}
            r["photo"] = pj["photo"]
            r["fonts"] = pj["fonts"]
        r["page_image"], r["page_json"] = ip, jp
        res.append(r)
        print("typed", lang, idx, page_id, "identical", r["all_production_crops_identical"], "%.1f s" % gen_s, flush=True)
    DP.write_tsv(os.path.join(out, "pages_typed_val.tsv"),
                 ["id", "image", "width", "height", "scale", "n_lines", "boxes_json", "polys_json", "baselines_json", "ref_lines_json", "note"], det_rows)
    report["typed"] = res


# ------------------------------------------------------------------------------------------------ part S
CAP = {}
ORIG = {}


def install_wrappers():
    ORIG.update(make_page=GEN.make_page, make_ghost=GEN.make_ghost, make_paper=P.make_paper, add_texture=P.add_texture, add_pattern=P.add_pattern,
                add_holes=P.add_holes, add_staple=P.add_staple, add_creases=P.add_creases, add_stains=P.add_stains, choose_writer=L.choose_writer,
                draw_text_units=L.draw_text_units, render_line=I.render_line, finalize=PG.Page.finalize, photo_effects=GM.photo_effects)

    def make_page_w(*a, **k):
        CAP.clear()
        CAP.update(attempt=k.get("attempt", 0), renders=[], units=[], writers=[], paper_steps=[])
        return ORIG["make_page"](*a, **k)

    def make_ghost_w(page, rng, strength):
        g = ORIG["make_ghost"](page, rng, strength)
        CAP["ghost"] = None if g is None else g.copy()
        return g

    def make_paper_w(kind, Wf, Hf, rng, options=None):
        paper, layout = ORIG["make_paper"](kind, Wf, Hf, rng, options)
        CAP["paper_base"] = paper.copy()
        CAP["layout"] = jsonable({k: v for k, v in layout.items() if k not in ("grid_x", "grid_y")})
        CAP["layout"]["n_grid_y"] = int(len(layout.get("grid_y", []))) if layout.get("grid_y") is not None else 0
        CAP["paper_call"] = dict(kind=kind, Wf=Wf, Hf=Hf, options=jsonable(options))
        return paper, layout

    def step(name, fn):
        def w(*a, **k):
            r = fn(*a, **k)
            arr = r[0] if isinstance(r, tuple) else r
            extra = jsonable(r[1]) if isinstance(r, tuple) else None
            kw = {kk: jsonable(vv) for kk, vv in k.items() if kk != "log"}
            if "log" in k and k["log"] is not None:
                kw["log"] = jsonable(k["log"])
            CAP.setdefault("paper_steps", []).append(dict(step=name, kwargs=kw, returned=extra, image=arr.copy()))
            return r
        return w

    def choose_writer_w(*a, **k):
        wr = ORIG["choose_writer"](*a, **k)
        if wr is not None:
            CAP.setdefault("writers", []).append(dict(font=wr.face.id, licence=wr.face.licence_class, connected=bool(wr.face.connected), axes=dict(wr.axes),
                                                      style=jsonable(wr.style), size_px=float(wr.size_px), ink=wr.ink_name))
        return wr

    def draw_text_units_w(*a, **k):
        u = ORIG["draw_text_units"](*a, **k)
        if u:
            sents, cur = [], []
            for x in u:
                if x is None:
                    sents.append(" ".join(cur))
                    cur = []
                else:
                    cur.append(x[1])
            CAP.setdefault("units", []).append(dict(n_words_requested=a[4] if len(a) > 4 else k.get("n_words"), sentences=sents))
        return u

    def render_line_w(face, axes, text, x0, ybase, size_px, rng, style, hand=True):
        li = ORIG["render_line"](face, axes, text, x0, ybase, size_px, rng, style, hand)
        CAP.setdefault("renders", []).append(dict(font=face.id, axes=dict(axes or {}), text=text, x0=float(x0), ybase=float(ybase), size_px=float(size_px),
                                                  style_in=jsonable(style), hand=bool(hand), alpha=li.alpha.copy(), x_off=int(li.x_off), y_off=int(li.y_off),
                                                  style_out=jsonable(li.style)))
        return li

    def finalize_w(self, paper_flat, layout, rng_fx, desk_rng, ghost=None, strict=True):
        CAP["paper_flat"] = np.asarray(paper_flat).copy()
        CAP["items"] = [dict(kind=it.kind, x_off=int(it.x_off), y_off=int(it.y_off), h=int(it.alpha.shape[0]), w=int(it.alpha.shape[1]), z=it.z,
                             text=(it.label or {}).get("text"), region_class=(it.label or {}).get("region_class"), font=(it.label or {}).get("font_id"),
                             ink=(it.label or {}).get("ink"), generator=(it.meta or {}).get("generator"),
                             alpha=(it.alpha.copy() if it.label is not None else None), color=(None if it.color is None else it.color.tolist()))
                        for it in self.items]
        CAP["regions_flat"] = jsonable([dict(r) for r in self.regions])
        CAP["geo_params"] = jsonable({k: v for k, v in self.geo.params.items()})
        CAP["strength"] = self.strength
        CAP["strength_cfg"] = jsonable(GM.STRENGTHS[self.strength])
        CAP["flat_size"] = [self.Wf, self.Hf]
        CAP["info_before"] = jsonable(dict(self.info))
        return ORIG["finalize"](self, paper_flat, layout, rng_fx, desk_rng, ghost=ghost, strict=strict)

    def photo_effects_w(img, cfg, rng, strength, mode):
        CAP["pre_photo"] = np.asarray(img).copy()
        out, fx = ORIG["photo_effects"](img, cfg, rng, strength, mode)
        CAP["post_photo"] = out.copy()
        CAP["fx"] = jsonable(fx)
        CAP["mode"] = mode
        return out, fx

    GEN.make_page = make_page_w
    GEN.make_ghost = make_ghost_w
    P.make_paper = make_paper_w
    for nm in ("add_texture", "add_pattern", "add_holes", "add_staple", "add_creases", "add_stains"):
        setattr(P, nm, step(nm, ORIG[nm]))
    L.choose_writer = choose_writer_w
    L.draw_text_units = draw_text_units_w
    I.render_line = render_line_w
    PG.Page.finalize = finalize_w
    GM.photo_effects = photo_effects_w


def remove_wrappers():
    GEN.make_page, GEN.make_ghost, P.make_paper = ORIG["make_page"], ORIG["make_ghost"], ORIG["make_paper"]
    for nm in ("add_texture", "add_pattern", "add_holes", "add_staple", "add_creases", "add_stains"):
        setattr(P, nm, ORIG[nm])
    L.choose_writer, L.draw_text_units, I.render_line = ORIG["choose_writer"], ORIG["draw_text_units"], ORIG["render_line"]
    PG.Page.finalize, GM.photo_effects = ORIG["finalize"], ORIG["photo_effects"]


def u8(a):
    return np.clip(np.asarray(a, np.float32), 0, 255).round().astype(np.uint8)


def ink_on_white(alpha, bgr):
    """The compositing rule of page.Page.finalize (page.py: reg *= 1 - a * (1 - colour / 255)) on white paper (255)."""
    a = np.asarray(alpha, np.float32)[..., None]
    col = np.asarray(bgr, np.float32)[None, None, :] / 255.0
    return u8(255.0 * (1.0 - a * (1.0 - col)))


KIND_COLOURS = {"handwriting": (200, 90, 30), "annotation": (40, 150, 40), "teacher_mark": (40, 40, 220), "print": (60, 60, 60), "table_cell": (150, 60, 150),
                "figure_ink": (0, 160, 230), "picture": (0, 200, 200), "stamp": (180, 0, 180)}


def stage_page(lang, idx, out, banks_cache, report):
    sd = os.path.join(out, "stages", "%s_%d" % (lang, idx))
    os.makedirs(sd, exist_ok=True)
    scratch = os.path.join(out, "stages_scratch", "%s_%d" % (lang, idx))
    os.makedirs(scratch, exist_ok=True)
    PR.set_font_policy("val")
    banks = banks_cache(lang)
    seed = int(PR.sha_int(PR.CFG["seed_tag"], "val", "H") % (2 ** 31))
    PR.G.clear()
    PR.G.update(args=types.SimpleNamespace(lang=lang, split="val", pop="H", pages_save=idx + 1), seed=seed, banks=banks, out_root=scratch)
    install_wrappers()
    try:
        t0 = time.time()
        _idx, rows, secs, fail = PR.work((idx,))
        cap = dict(CAP)
    finally:
        remove_wrappers()
    rec = dict(lang=lang, idx=idx, seed_H=seed, seconds_work=round(time.time() - t0, 2), attempt=cap.get("attempt"), fail=fail)
    page_row = [r for r in rows if r.get("unit") == "page"][0]
    pid = page_row["id"]
    rec["page_id"] = pid
    # ---- identity with production
    prod_img = os.path.join(SYNTH, "pages", "val", lang, pid + ".jpg")
    prod_json = os.path.join(SYNTH, "pages", "val", lang, pid + ".json")
    rec["identical_page_jpeg"] = sha_file(page_row["image"]) == sha_file(prod_img)
    pj = json.load(open(page_row["source"], encoding="utf-8"))
    pj_prod = json.load(open(prod_json, encoding="utf-8"))
    rec["identical_page_json_file"] = sha_file(page_row["source"]) == sha_file(prod_json)
    rec["identical_page_json_lines"] = [(l["text"], l["polygon"]) for l in pj["lines"]] == [(l["text"], l["polygon"]) for l in pj_prod["lines"]]
    crop_checks = []
    for r in rows:
        if r.get("unit") != "line":
            continue
        kd = {"hand_synth": "hand", "clutter": "clutter"}[r["kind"]]
        prod = os.path.join(SYNTH, kd, "val", lang, "%04d" % (idx // 500), r["id"] + ".jpg")
        crop_checks.append(dict(id=r["id"], kind=r["kind"], text=r["text"], crop_mode=r.get("crop_mode"), line_id=r.get("line_id"),
                                identical=(os.path.exists(prod) and sha_file(r["image"]) == sha_file(prod))))
    rec["crops"] = crop_checks
    final = cv2.imread(page_row["image"], cv2.IMREAD_COLOR)
    post = cap["post_photo"]
    rec["post_photo_equals_saved_page_after_jpeg"] = sha(jpg_bytes(post, PR.CFG["page_jpeg_quality"])) == sha_file(page_row["image"])
    files = {}

    def save(name, img):
        p = os.path.join(sd, name)
        cv2.imwrite(p, img)
        files[name] = p
        return p

    # ---- stage 1: sentences drawn from the bank
    rec["stage1_text"] = dict(text_file=TEXT_DIR + "/%s/sentences.tsv" % lang, sentence_bank_size=len(banks[lang]),
                              units_calls=cap.get("units", []), n_bank_draws_including_rejected_and_font_probes=len(banks[lang].drawn),
                              first_draws=[dict(source=s, text=t) for s, t in banks[lang].drawn[:40]])
    # ---- stage 2: writer and one line before and after the writer effects
    writers = cap.get("writers", [])
    rec["stage2_writers"] = writers
    body = None
    item_by_pos = {(it["x_off"], it["y_off"], it["text"]): it for it in cap["items"] if it["text"] is not None}
    used = [r for r in cap["renders"] if r["hand"] and (r["x_off"], r["y_off"], r["text"]) in item_by_pos and
            item_by_pos[(r["x_off"], r["y_off"], r["text"])]["region_class"] == "handwriting" and len(r["text"].split(" ")) >= 3]
    el = [r for r in used if (r["style_out"] or {}).get("elastic")]
    body = (el or used)[0]
    it = item_by_pos[(body["x_off"], body["y_off"], body["text"])]
    face = F.get_face(body["font"])
    rng_plain = np.random.default_rng(12345)
    plain_style = I.default_style(rng_plain, face, hand=False)
    li0 = ORIG["render_line"](face, body["axes"], body["text"], 0.0, 200.0, body["size_px"], rng_plain, plain_style, hand=False)
    col, amul = PG.INKS[it["ink"]]
    save("stage2_line_a_font_only.png", ink_on_white(li0.alpha * amul, col))
    save("stage2_line_b_writer_effects.png", ink_on_white(body["alpha"] * amul, col))
    save("stage2_line_c_ink_on_page_item.png", ink_on_white(it["alpha"], col))
    rec["stage2_line"] = dict(text=body["text"], font=body["font"], axes=body["axes"], size_px=body["size_px"], writer_style_in=body["style_in"],
                              line_style_out=body["style_out"], ink=it["ink"], ink_bgr=list(col), ink_alpha_multiplier=amul,
                              plain_render=dict(function="ink.render_line(..., hand=False)", style="ink.default_style(rng, face, hand=False)", rng_seed=12345),
                              chosen_as="first handwriting body line of 3+ words with elastic distortion drawn" if el else "first handwriting body line of 3+ words (no line of the page drew elastic distortion)",
                              composite_rule="page.py Page.finalize: reg *= 1 - alpha * (1 - ink_bgr / 255), on white 255; panel c uses the page item alpha (Page.add_line: _bleed sigma 0.9, times the ink multiplier)")
    # ---- stage 3: paper and layout
    save("stage3_a_paper_make_paper.png", u8(cap["paper_base"]))
    steps = []
    for k, s in enumerate(cap.get("paper_steps", [])):
        nm = "stage3_b%d_%s.png" % (k, s["step"])
        save(nm, u8(s["image"]))
        steps.append(dict(step=s["step"], kwargs=s["kwargs"], returned=s["returned"], png=nm))
    save("stage3_c_paper_into_finalize.png", u8(cap["paper_flat"]))
    if cap.get("ghost") is not None:
        g = cap["ghost"]
        save("stage3_d_ghost_alpha.png", u8(255.0 * (1.0 - g / max(float(g.max()), 1e-6))))
    lay = u8(cap["paper_flat"]).copy()
    for itm in sorted(cap["items"], key=lambda q: q["z"]):
        key = itm["region_class"] or itm["kind"]
        c = KIND_COLOURS.get(key, (120, 120, 120))
        x0, y0 = itm["x_off"], itm["y_off"]
        cv2.rectangle(lay, (x0, y0), (x0 + itm["w"], y0 + itm["h"]), c, 2)
    for rg in cap["regions_flat"]:
        if isinstance(rg.get("polygon"), list) and rg["polygon"]:
            pts = np.round(np.asarray(rg["polygon"], np.float64)).astype(np.int32).reshape(-1, 1, 2)
            cv2.polylines(lay, [pts], True, (0, 120, 255), 2)
    save("stage3_e_layout_boxes.png", lay)
    kinds = {}
    for itm in cap["items"]:
        key = itm["region_class"] or itm["kind"]
        kinds[key] = kinds.get(key, 0) + 1
    rec["stage3_layout"] = dict(page_type=pj["info"].get("page_type"), size=pj["info"].get("size"), flat_size=cap["flat_size"], paper_call=cap["paper_call"], layout=cap["layout"],
                                scene_flags=pj["info"].get("scene"), blocks=pj["info"].get("blocks"), fill=pj["info"].get("fill"), rows=pj["info"].get("rows"),
                                figure_generator=pj["info"].get("figure_generator"), items_by_class=kinds,
                                regions=[dict(id=r.get("id"), type=r.get("type"), generator=r.get("generator"), note=r.get("note")) for r in cap["regions_flat"]],
                                paper_steps=steps, ghost_max=(None if cap.get("ghost") is None else round(float(cap["ghost"].max()), 4)),
                                box_colours_bgr=KIND_COLOURS, region_outline_bgr=[0, 120, 255])
    # ---- stage 4 and 5
    save("stage4_composite_after_geometry.png", cap["pre_photo"])
    save("stage5_after_photo_effects.png", post)
    rec["stage4_5_capture"] = dict(strength=cap["strength"], strength_ranges=cap["strength_cfg"], geometry=cap["geo_params"], photo=cap["fx"], mode=cap["mode"],
                                   output_size=[int(post.shape[1]), int(post.shape[0])],
                                   effects=[e for e in pj["info"].get("effects", []) if not e.startswith(("font:", "ink:", "class:", "pen:"))])
    # ---- stage 6: line crops (production rows) and one line cut both ways
    lines = {ln["id"]: ln for ln in pj["lines"]}
    crops6 = []
    for r in rows:
        if r.get("kind") == "hand_synth" and r.get("unit") == "line":
            im = cv2.imread(r["image"], cv2.IMREAD_COLOR)
            nm = "stage6_crop_%s_%s.png" % (r["id"], r["crop_mode"])
            save(nm, im)
            crops6.append(dict(id=r["id"], line_id=r["line_id"], crop_mode=r["crop_mode"], text=r["text"], size=[int(im.shape[1]), int(im.shape[0])], png=nm))
    ln = lines[crops6[0]["line_id"]]
    for mode in ("poly", "rect"):
        save("stage6_both_%s_%s.png" % (crops6[0]["line_id"], mode), CR.crop_line(final, ln["polygon"], mode))
    rec["stage6_crops"] = dict(production_crops=crops6, both_modes_line=crops6[0]["line_id"], both_modes_text=ln["text"],
                               rule="produce_r5.work: K=%d lines per validation page drawn without replacement (weights 1 / 0.5 / 0.15 by word count), crop mode poly with p=%.2f else rect; crops.crop_line(img, polygon, mode, pad=4)" % (PR.CFG["lines_per_page"]["val"], PR.CFG["p_crop_poly"]))
    # ---- stage 7: clutter
    cl = [r for r in rows if r.get("kind") == "clutter"]
    if cl:
        im = cv2.imread(cl[0]["image"], cv2.IMREAD_COLOR)
        save("stage7_clutter.png", im)
        rec["stage7_clutter"] = dict(source="production work() row", id=cl[0]["id"], window_kind=cl[0]["crop_mode"], size=[int(im.shape[1]), int(im.shape[0])])
    else:
        rng_c = np.random.default_rng(777)
        win = CR.clutter_windows(pj, final.shape, rng_c, 2)
        if win:
            x0, y0, x1, y1, wk = win[0]
            save("stage7_clutter.png", final[y0:y1, x0:x1])
            rec["stage7_clutter"] = dict(source="production drew no clutter crop for this page (clutter_page_p=%.2f); crops.clutter_windows(page_json, shape, np.random.default_rng(777), 2) called on the same page" % PR.CFG["clutter_page_p"],
                                         window=[int(x0), int(y0), int(x1), int(y1)], window_kind=wk, label="")
        else:
            rec["stage7_clutter"] = dict(source="no clutter window found")
    rec["png_files"] = files
    rec["lines_on_page"] = [dict(id=l["id"], text=l["text"], region_class=l["region_class"], font=l["font_id"]) for l in pj["lines"]]
    report.setdefault("stages", []).append(rec)
    print("stages", lang, idx, pid, "jpeg identical", rec["identical_page_jpeg"], "crops identical", all(c["identical"] for c in crop_checks), flush=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--selection", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--stage_pages", default="kk:1,uz_latn:11")
    ap.add_argument("--skip_typed", action="store_true")
    a = ap.parse_args()
    assert "test" not in a.selection
    os.makedirs(a.out, exist_ok=True)
    sel = json.load(open(a.selection, encoding="utf-8"))
    report = dict(created_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), generator_version=GEN.VERSION, fonts_in_registry=len(F.REGISTRY),
                  font_dir=F.FONT_DIR, text_dir=TEXT_DIR, cfg=jsonable(PR.CFG))
    assert len(F.REGISTRY) == 73, len(F.REGISTRY)
    cache = {}

    def banks_cache(lang):
        if lang not in cache:
            cache[lang] = GEN.load_banks(TEXT_DIR, [lang], filename="sentences.tsv")
            assert cache[lang][lang].vocab.source != "bank-fallback"
        return cache[lang]
    for spec in a.stage_pages.split(","):
        lang, idx = spec.split(":")
        stage_page(lang, int(idx), a.out, banks_cache, report)
        json.dump(report, open(os.path.join(a.out, "gen_report.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    if not a.skip_typed:
        typed_pages(sel, a.out, banks_cache, report)
    report["finished_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    json.dump(report, open(os.path.join(a.out, "gen_report.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    print("done", flush=True)


if __name__ == "__main__":
    main()