File size: 26,336 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
"""Probe P1 (design 'probe_P1_pixel_survival'): what share of a mark's pixels survives each augmentation op, at 32 and 64 px.

Part a, real letters: Sheriyeva val.zip crops (validation split only) of the classes with a detached mark that the project
loader exposes (lettersynth.letterbank.iter_zip: 33 Russian letters): й (breve) and ё (two dots). Cleaned with
letterbank.clean_letter; mark = kept connected components other than the largest (rule 3 of letterbank.py). The crop is
scaled so that its main body is k x H px high; k = median over 300 V1 crops of (height of the shortest row band holding 60%
of the Otsu ink) / (crop height) (estimate_k); sensitivity k +- 0.1. The letter is placed on a white line canvas of height H
and width max(4H, letter width + H) (a short word), body centred vertically.
Part b, fonts: every marked letter of the ten language-scripts (pagesynth/text.py PROFILES special) rendered in the
generator fonts (DATA/data/raw/fonts, one file per folder) next to its base letter at the same origin and size; only glyphs
in the font's cmap (fontTools). Size: the font's x-height is scaled to k x H px and the x-height band is centred in the H px
line, the same rule as the real letters (so rule 5 compares like with like); glyph ink outside the line is a rejection.
Mark = ink of the marked glyph outside the base glyph dilated by 1 px, at H. The base must be
contained in the marked glyph (>= 90% of its ink inside the marked ink dilated by 2 px at render size), else the pair is listed
and not measured (e.g. a schwa is not 'a' plus a mark). Probe bases: MANUAL_BASE of the scorer, except dotted i: (i, dotless
i) and (I-dot, I), and u-straight-bar against u-straight. Letters without a base (Cyrillic dotted i, shha) use the part a
component rule when the glyph has a detached part. Also й, ё (rule 5) and Uzbek o' g' (U+02BB).
Measure: S = (mask pixels still darker than 0.5 after the op; mask moved with the op's geometry, nearest) / (mask pixels
before), capped at 1; erased = S < 0.5; fused (detached marks) = a surviving mark pixel lies in the same 8-connected ink
component as the body. Orders: 'ours' (op at H) and 'native' (typical op at the native height, then resize to H; native height
56 px = KOHTD median crop height; the native downscale samples NEAREST from the native image straight to one third of the H px
line and BICUBIC back up to H, because TrOCR's downscale target is a fixed one third of its model input). Extra op: horizontal shear with factor 0.5 (26.57 deg; the other reading of 'shear +-0.5').
200 draws per (letter, policy, height, slot, order), spread round-robin over the letter's instances.
"""
import argparse
import datetime
import io
import json
import math
import os
import sys
import unicodedata
import zipfile
from multiprocessing import Pool

import numpy as np

CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
SHERIYEVA_VAL = DATA + "/data/raw/sheriyeva/val.zip"
V1 = DATA + "/data/processed/r5/manifests/kohtd_screen_v1.tsv"
FONT_ROOT = DATA + "/data/raw/fonts"
H_NATIVE = 56
REAL_LETTERS = {"й": "breve (detached)", "ё": "two dots (detached)"}
KK_SPECIFIC = "әғқңөұүһіӘҒҚҢӨҰҮҺІ"
SEED = 20261126

for p in (CODE + "/src/lettersynth", CODE + "/src/pagesynth"):
    if p not in sys.path:
        sys.path.insert(0, p)


# ------------------------------------------------------------------------------------------------ inputs
def _zip_name(info):
    name = info.filename
    if not (info.flag_bits & 0x800):
        try:
            name = name.encode("cp437").decode("utf-8")
        except (UnicodeEncodeError, UnicodeDecodeError):
            pass
    return unicodedata.normalize("NFC", name)


def list_sheriyeva_classes(path=SHERIYEVA_VAL):
    """All class folders of the archive (also those the loader skips), with PNG counts."""
    from lettersynth.common import LETTERS
    counts = {}
    with zipfile.ZipFile(path) as z:
        for info in z.infolist():
            name = _zip_name(info)
            if "__MACOSX" in name or not name.endswith(".png"):
                continue
            parts = name.split("/")
            if len(parts) < 3:
                continue
            counts[parts[-2]] = counts.get(parts[-2], 0) + 1
    return {"archive": path, "classes": len(counts), "pngs": sum(counts.values()),
            "per_class": dict(sorted(counts.items())),
            "classes_outside_loader_letters": sorted(c for c in counts if c not in LETTERS),
            "kazakh_specific_classes_found": sorted(c for c in counts if c in KK_SPECIFIC)}


def estimate_k(n=300, seed=SEED):
    import cv2
    from PIL import Image
    from linedet.common import read_manifest
    rows = [r for r in read_manifest(V1) if r.get("split") in ("val", "validation")]
    rng = np.random.default_rng([seed, 5151])
    pick = sorted(rng.choice(len(rows), min(n, len(rows)), replace=False))
    ratios = []
    for i in pick:
        g = np.asarray(Image.open(rows[i]["image"]).convert("L"))
        _, m = cv2.threshold(g, 0, 1, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
        prof = m.sum(1).astype(float)
        tot = prof.sum()
        if tot <= 0:
            continue
        need = 0.6 * tot
        best = len(prof)
        lo = 0
        acc = 0.0
        for hi in range(len(prof)):
            acc += prof[hi]
            while acc - prof[lo] >= need and lo < hi:
                acc -= prof[lo]
                lo += 1
            if acc >= need:
                best = min(best, hi - lo + 1)
        ratios.append(best / len(prof))
    return {"k": float(np.median(ratios)), "n": len(ratios), "p25": float(np.percentile(ratios, 25)), "p75": float(np.percentile(ratios, 75)),
            "rule": "median over V1 crops of (shortest row band holding 60% of the Otsu ink) / (crop height)", "seed": [seed, 5151]}


class Inst:
    """One measurable instance at a working height: grey uint8 (paper 255), mark mask and body mask (bool, ink only)."""

    def __init__(self, grey, mark, body, meta):
        self.grey, self.mark, self.body, self.meta = grey, mark, body, meta


def place_on_line(grey, mark, body, H, canvas_mult=4):
    """Pad an H-high letter image to a line canvas of width max(4H, w + H), centred."""
    h, w = grey.shape
    Wc = max(canvas_mult * H, w + H)
    g = np.full((H, Wc), 255, np.uint8)
    mk = np.zeros((H, Wc), bool)
    bd = np.zeros((H, Wc), bool)
    x0 = (Wc - w) // 2
    g[:, x0:x0 + w] = grey
    mk[:, x0:x0 + w] = mark
    bd[:, x0:x0 + w] = body
    return g, mk, bd


def iter_zip_classes(path, classes):
    """lettersynth.letterbank.iter_zip without its 33-Russian-letter filter (same name decoding, sheet pattern and 128 x 128
    check), restricted to `classes`. Used only for --extra_real (classes the project loader skips)."""
    import cv2
    from lettersynth.letterbank import SHEET_RE
    with zipfile.ZipFile(path) as z:
        for info in z.infolist():
            name = _zip_name(info)
            if "__MACOSX" in name or not name.endswith(".png"):
                continue
            parts = name.split("/")
            if len(parts) < 3 or parts[-2] not in classes:
                continue
            m = SHEET_RE.search(parts[-1])
            if not m:
                continue
            arr = cv2.imdecode(np.frombuffer(z.read(info), np.uint8), cv2.IMREAD_GRAYSCALE)
            if arr is None or arr.shape != (128, 128):
                continue
            yield parts[-2], int(m.group(1)), parts[-1], arr


def real_instances(H, k, limit=0, letters=None):
    """Part a instances at height H with body height k*H."""
    import cv2
    from PIL import Image
    from lettersynth.common import LETTERS
    from lettersynth.letterbank import clean_letter, iter_zip
    letters = dict(letters or REAL_LETTERS)
    out = {c: [] for c in letters}
    stats = {c: {"crops": 0, "cleaned": 0, "no_detached_mark": 0, "scaled_to_fit": 0} for c in letters}
    source = iter_zip(SHERIYEVA_VAL) if all(c in LETTERS for c in letters) else iter_zip_classes(SHERIYEVA_VAL, set(letters))
    for letter, sheet, name, arr in source:
        if letter not in letters:
            continue
        if limit and len(out[letter]) >= limit:
            continue
        stats[letter]["crops"] += 1
        res, why = clean_letter(arr, debug=True)
        if res is None:
            continue
        stats[letter]["cleaned"] += 1
        km = res["mask"].astype(np.uint8)
        n, lab, st, _ = cv2.connectedComponentsWithStats(km, connectivity=8)
        if n <= 2:
            stats[letter]["no_detached_mark"] += 1
            continue
        main = 1 + int(np.argmax(st[1:, cv2.CC_STAT_AREA]))
        f = np.asarray(res["crop"], dtype=np.float32)
        grey = np.clip(f * 255.0, 0, 255).astype(np.uint8)
        h, w = grey.shape
        by, bh = int(st[main, cv2.CC_STAT_TOP]), int(st[main, cv2.CC_STAT_HEIGHT])
        s = k * H / bh
        if h * s > H:
            s = H / h
            stats[letter]["scaled_to_fit"] += 1
        hs, ws = max(1, int(round(h * s))), max(1, int(round(w * s)))
        g = np.asarray(Image.fromarray(grey).resize((ws, hs), Image.LANCZOS))
        mk = np.asarray(Image.fromarray(((lab != main) & (lab > 0)).astype(np.uint8) * 255).resize((ws, hs), Image.NEAREST)) > 127
        bd = np.asarray(Image.fromarray((lab == main).astype(np.uint8) * 255).resize((ws, hs), Image.NEAREST)) > 127
        cy = (by + bh / 2.0) * s
        top = int(round(H / 2.0 - cy))
        top = min(max(top, 0), H - hs)
        G = np.full((H, ws), 255, np.uint8)
        MK = np.zeros((H, ws), bool)
        BD = np.zeros((H, ws), bool)
        G[top:top + hs] = g
        MK[top:top + hs] = mk
        BD[top:top + hs] = bd
        dark = G < 128
        gl, ml, bl = place_on_line(G, MK & dark, BD & dark, H)
        if ml.sum() == 0:
            stats[letter]["no_detached_mark"] += 1
            continue
        out[letter].append(Inst(gl, ml, bl, {"sheet": sheet, "name": name}))
    return out, stats


# fonts
def probe_base(c):
    from rq2.marks import MANUAL_BASE, base_of
    over = {"ı": None, "ұ": "ү", "Ұ": "Ү", "і": None, "І": None, "һ": None, "Һ": None}
    if c in over:
        return over[c]
    return base_of(c)


def font_pairs():
    from pagesynth import text as ptext
    pairs = {}
    for lang in ptext.LANG_ORDER:
        if lang == "uz_latn":
            continue
        for c in ptext.PROFILES[lang]["special"].replace(" ", ""):
            pairs.setdefault((c, probe_base(c)), set()).add(lang)
    for m, b in (("oʻ", "o"), ("gʻ", "g"), ("Oʻ", "O"), ("Gʻ", "G")):
        pairs.setdefault((m, b), set()).add("uz_latn")
    for m, b in (("й", "и"), ("ё", "е"), ("Й", "И"), ("Ё", "Е")):
        pairs.setdefault((m, b), set()).add("ru_rule5")
    for m, b in (("i", "ı"), ("İ", "I")):
        pairs.setdefault((m, b), set()).update({"tr", "az"})
    return sorted(((m, b, sorted(l)) for (m, b), l in pairs.items()), key=lambda x: x[0])


def font_files(limit=0):
    out = []
    for d in sorted(os.listdir(FONT_ROOT)):
        p = os.path.join(FONT_ROOT, d)
        if not os.path.isdir(p):
            continue
        fs = sorted(f for f in os.listdir(p) if f.lower().endswith((".ttf", ".otf")))
        if not fs:
            continue
        pref = [f for f in fs if "[" in f] or [f for f in fs if "regular" in f.lower()] or fs
        out.append(os.path.join(p, pref[0]))
    return out[:limit] if limit else out


def render_texts(font_path, texts, size=128):
    """Render each text at the same origin on a canvas 3 line-heights high (glyph in the middle). Returns (images, baseline y)."""
    from PIL import Image, ImageDraw, ImageFont
    font = ImageFont.truetype(font_path, size)
    asc, desc = font.getmetrics()
    Lh = asc + desc
    wmax = max(int(math.ceil(font.getbbox(t)[2])) for t in texts) + 8
    ims = []
    for t in texts:
        im = Image.new("L", (wmax, 3 * Lh), 255)
        ImageDraw.Draw(im).text((4, Lh), t, font=font, fill=0)
        ims.append(im)
    return ims, Lh + asc


def x_height(font_path, cmap):
    """Ink height of 'x' (Latin) or 'х' (Cyrillic) at size 128, the font's x-height."""
    for ch in ("x", "х"):
        if ord(ch) in cmap:
            ims, _ = render_texts(font_path, [ch])
            rows = np.nonzero((np.asarray(ims[0]) < 128).any(1))[0]
            if len(rows):
                return float(rows.max() - rows.min() + 1)
    return None


def font_instance(font_path, cmap, marked, base, H, k, xh):
    """Render marked and base letters at the same origin, scale so that the font's x-height xh (px at size 128) becomes k x H
    px (the rule of the real letters, whose main body is scaled to k x H), centre the x-height band in an H px line.
    -> (Inst or None, reason)."""
    import cv2
    from PIL import Image
    need = set(marked) | (set(base) if base else set())
    if not all(ord(ch) in cmap for ch in need):
        return None, "not_in_cmap"
    if not xh:
        return None, "no_x_height"
    big, baseline = render_texts(font_path, [marked] + ([base] if base else []))
    dm = np.asarray(big[0]) < 128
    if dm.sum() == 0:
        return None, "empty_glyph"
    s = k * H / xh
    Wb, Hb = big[0].size
    Ws, Hs = max(1, int(round(Wb * s))), max(1, int(round(Hb * s)))
    c = (baseline - xh / 2.0) * s
    top = int(round(c - H / 2.0))
    if top < 0 or top + H > Hs:
        return None, "canvas"
    scaled = [np.asarray(im.resize((Ws, Hs), Image.LANCZOS)) for im in big]
    if ((scaled[0][:top] < 128).any() or (scaled[0][top + H:] < 128).any()):
        return None, "clipped_outside_line"
    if base:
        db = np.asarray(big[1]) < 128            # containment at render size (128 px font size)
        if db.sum() == 0:
            return None, "empty_base"
        cover = cv2.dilate(dm.astype(np.uint8), np.ones((5, 5), np.uint8)) > 0
        if (db & cover).sum() < 0.9 * db.sum():
            return None, "base_not_contained"
        n_m = cv2.connectedComponents(dm.astype(np.uint8), connectivity=8)[0] - 1
        n_b = cv2.connectedComponents(db.astype(np.uint8), connectivity=8)[0] - 1
        mtype = "detached" if n_m > n_b else "attached"
    gm = scaled[0][top:top + H]
    darkm = gm < 128
    if base:
        gb = scaled[1][top:top + H]
        darkb = cv2.dilate((gb < 128).astype(np.uint8), np.ones((3, 3), np.uint8)) > 0
        mark = darkm & ~darkb
        body = darkm & ~mark
    else:
        n, lab, st, _ = cv2.connectedComponentsWithStats(darkm.astype(np.uint8), connectivity=8)
        if n <= 2:
            return None, "no_base_no_detached_part"
        main = 1 + int(np.argmax(st[1:, cv2.CC_STAT_AREA]))
        body = lab == main
        mark = (lab > 0) & ~body
        mtype = "detached"
    if mark.sum() == 0:
        return None, "mark_vanishes_at_H"
    ys = np.nonzero(mark.any(1))[0]
    cols = np.nonzero(darkm.any(0))[0]
    x0, x1 = max(0, cols.min() - 2), min(gm.shape[1], cols.max() + 3)   # trim the empty render margin
    gl, ml, bl = place_on_line(np.ascontiguousarray(gm[:, x0:x1]), mark[:, x0:x1], body[:, x0:x1], H)
    return Inst(gl, ml, bl, {"font": os.path.basename(os.path.dirname(font_path)), "mark_type": mtype,
                             "mark_height_px": int(ys.max() - ys.min() + 1), "mark_pixels": int(mark.sum()),
                             "x_height_px": round(k * H, 2)}), "ok"


# ------------------------------------------------------------------------------------------------ measurement
def one_draw(inst, pol_name, slot, z1, z2, H_out, shear_factor=False, H_policy=None, native=False):
    import cv2
    from PIL import Image
    from rq2.aug import Policy, geometry_on_mask, op_shear, resize_to_height
    im = Image.fromarray(inst.grey).convert("RGB")
    if shear_factor:
        deg = math.degrees(math.atan(0.5)) * (1 if z1 >= 0.5 else -1)
        out, op, params = op_shear(im, deg), "shear_factor", {"deg": deg}
    elif native and pol_name == "typical" and slot == 4:
        # TrOCR's downscale: a fixed one third of the model input; here NEAREST from the native-height image to
        # (W_H // 3, H // 3), then BICUBIC up to (W_H, H)
        W_H = max(int(im.size[0] * H_out / im.size[1]), 1)
        out = im.resize((max(1, W_H // 3), max(1, H_out // 3)), Image.NEAREST).resize((W_H, H_out), Image.BICUBIC)
        op, params = "down_up_third_native", {}
    else:
        out, op, params = Policy(pol_name, H_policy or inst.grey.shape[0]).apply(im, slot, z1, z2)
    mk = geometry_on_mask(Image.fromarray(inst.mark.astype(np.uint8) * 255), op, params)
    bd = geometry_on_mask(Image.fromarray(inst.body.astype(np.uint8) * 255), op, params)
    if out.size[1] != H_out:
        out = resize_to_height(out, H_out)
    if mk.size != out.size:
        mk = mk.resize(out.size, Image.NEAREST)
        bd = bd.resize(out.size, Image.NEAREST)
    dark = np.asarray(out.convert("L")) < 128
    mka = np.asarray(mk) > 127
    bda = np.asarray(bd) > 127
    surv = mka & dark
    fused = None
    if surv.any():
        _, lab = cv2.connectedComponents(dark.astype(np.uint8), connectivity=8)
        ml = set(np.unique(lab[surv])) - {0}
        bl = set(np.unique(lab[bda & dark])) - {0}
        fused = bool(ml & bl)
    return int(surv.sum()), fused, op


def n_before_at(inst, H_out):
    from PIL import Image
    if inst.grey.shape[0] == H_out:
        return int(inst.mark.sum())
    W = max(1, int(inst.grey.shape[1] * H_out / inst.grey.shape[0]))
    g = np.asarray(Image.fromarray(inst.grey).resize((W, H_out), Image.LANCZOS)) < 128
    m = np.asarray(Image.fromarray(inst.mark.astype(np.uint8) * 255).resize((W, H_out), Image.NEAREST)) > 127
    return int((g & m).sum())


def strata():
    """(policy, H, slot, order, shear_factor) to measure; slot 6 (keep) is the identity and is skipped."""
    out = []
    for pol in ("typical", "safe"):
        for H in (32, 64):
            for k in range(6):
                if pol == "safe" and H == 32 and k == 3:
                    continue
                out.append((pol, H, k, "ours", False))
    for H in (32, 64):
        for k in range(6):
            out.append(("typical", H, k, "native", False))
        out.append(("shear_factor_0.5", H, -1, "ours", True))
    return out


def measure_letter(job):
    """job: (part, letter_id, letter, langs, instances_by_H {H: [Inst]}, instances_native [Inst], draws, strata subset)."""
    part, li, letter, langs, insts_h, insts_nat, draws, strat = job
    recs = []
    for si, (pol, H, slot, order, sf) in enumerate(strat):
        pool = insts_nat if order == "native" else insts_h.get(H, [])
        if not pool:
            continue
        S, F, ops, types = [], [], {}, {}
        for d in range(draws):
            inst = pool[d % len(pool)]
            rng = np.random.default_rng([SEED, 4646, li, si, d])
            z1, z2 = float(rng.random()), float(rng.random())
            nb = n_before_at(inst, H)
            if nb == 0:
                continue
            na, fused, op = one_draw(inst, "typical" if sf else pol, slot, z1, z2, H, shear_factor=sf,
                                     H_policy=(inst.grey.shape[0] if order == "native" else H), native=(order == "native"))
            S.append(min(1.0, na / nb))
            if inst.meta.get("mark_type", "detached") == "detached":
                F.append(bool(fused) if fused is not None else False)
            ops[op] = ops.get(op, 0) + 1
            mt = inst.meta.get("mark_type", "detached")
            types[mt] = types.get(mt, 0) + 1
        if not S:
            continue
        S = np.asarray(S)
        recs.append({"part": part, "letter": letter, "languages": langs, "mark_type": max(types, key=types.get), "policy": pol, "H": H,
                     "slot": slot, "op": max(ops, key=ops.get), "ops": ops, "order": order, "draws": int(len(S)), "instances": len(pool),
                     "median_S": float(np.median(S)), "mean_S": float(S.mean()), "share_erased": float((S < 0.5).mean()),
                     "share_fused_detached": (float(np.mean(F)) if F else None)})
    return recs


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=DATA + "/outputs/rq2/probe_p1.json")
    ap.add_argument("--draws", type=int, default=200)
    ap.add_argument("--smoke", action="store_true", help="a few crops (5 per letter), 3 fonts, 4 draws")
    ap.add_argument("--procs", type=int, default=int(os.environ.get("SLURM_CPUS_PER_TASK", "8")))
    ap.add_argument("--extra_real", default="", help="optional, off by default: comma list of further val.zip classes with a detached "
                    "mark that the project loader skips (e.g. the Kazakh dotted i 'і'); measured as part 'real_extra', not used by rule 5")
    a = ap.parse_args()
    from fontTools.ttLib import TTFont
    t0 = datetime.datetime.now(datetime.timezone.utc)
    draws = 4 if a.smoke else a.draws
    doc = {"written_utc": t0.strftime("%Y-%m-%dT%H:%M:%SZ"), "design": "records/R5/RQ2/design.json probe_P1_pixel_survival", "smoke": a.smoke,
           "validation_only": "Sheriyeva val.zip and V1 (KOHTD validation) only", "draws_per_stratum": draws,
           "threshold": "dark = grey < 128 (0.5)", "native_height_px": H_NATIVE}
    doc["sheriyeva_classes"] = list_sheriyeva_classes()
    kinfo = estimate_k(30 if a.smoke else 300)
    doc["k"] = kinfo
    k = kinfo["k"]
    jobs = []
    li = 0
    real_stats = {}
    for kk_name, kv in (("k", k), ("k_minus_0.1", k - 0.1), ("k_plus_0.1", k + 0.1)):
        if a.smoke and kk_name != "k":
            continue
        ih = {}
        for H in (32, 64):
            inst, st = real_instances(H, kv, limit=5 if a.smoke else 0)
            ih[H] = inst
            real_stats["%s_H%d" % (kk_name, H)] = st
        nat, _ = real_instances(H_NATIVE, kv, limit=5 if a.smoke else 0) if kk_name == "k" else ({}, None)
        strat = strata() if kk_name == "k" else [s for s in strata() if s[3] == "ours"]
        for letter in REAL_LETTERS:
            jobs.append(("real_" + kk_name, li, letter, ["ru"], {H: ih[H][letter] for H in ih}, nat.get(letter, []), draws, strat))
            li += 1
    extra = [c for c in a.extra_real.split(",") if c]
    if extra:
        ex_letters = {c: "detached mark (class skipped by the project loader)" for c in extra}
        ih = {H: real_instances(H, k, limit=5 if a.smoke else 0, letters=ex_letters)[0] for H in (32, 64)}
        nat = real_instances(H_NATIVE, k, limit=5 if a.smoke else 0, letters=ex_letters)[0]
        for letter in extra:
            jobs.append(("real_extra", li, letter, ["kk"], {H: ih[H][letter] for H in ih}, nat.get(letter, []), draws, strata()))
            li += 1
    doc["real_letters"] = {"letters": REAL_LETTERS, "extra_real_classes": extra, "stats": real_stats}
    fonts = font_files(3 if a.smoke else 0)
    doc["fonts_used"] = [os.path.relpath(f, FONT_ROOT) for f in fonts]
    cmaps = {f: set(TTFont(f, lazy=True).getBestCmap().keys()) for f in fonts}
    xhs = {f: x_height(f, cmaps[f]) for f in fonts}
    doc["font_x_height_px_at_size_128"] = {os.path.basename(os.path.dirname(f)): v for f, v in xhs.items()}
    skipped = {}
    mark_heights = {}
    for marked, base, langs in font_pairs():
        ih, nat = {}, []
        for H in (32, 64, H_NATIVE):
            lst = []
            for f in fonts:
                inst, why = font_instance(f, cmaps[f], marked, base, H, k, xhs[f])
                if inst is None:
                    skipped.setdefault("%s|%s" % (marked, base or "-"), {}).setdefault(why, []).append(os.path.basename(os.path.dirname(f))) if H == 32 else None
                    continue
                lst.append(inst)
            if H == H_NATIVE:
                nat = lst
            else:
                ih[H] = lst
        if ih.get(32):
            mark_heights[marked] = {"H32_median_mark_height_px": float(np.median([i.meta["mark_height_px"] for i in ih[32]])), "fonts": len(ih[32])}
        if ih.get(32) or ih.get(64):
            jobs.append(("font", li, marked, langs, ih, nat, draws, strata()))
            li += 1
    doc["font_pairs_not_measured"] = skipped
    doc["font_mark_height_at_32px"] = mark_heights
    with Pool(a.procs) as pool:
        res = pool.map(measure_letter, jobs, chunksize=1)
    summary = [r for rr in res for r in rr]
    doc["summary"] = summary
    # aggregate over letters: part x mark type x policy x H x slot x order
    agg = {}
    for r in summary:
        key = (r["part"], r["mark_type"], r["policy"], r["H"], r["slot"], r["order"])
        agg.setdefault(key, []).append(r)
    doc["by_mark_type"] = [{"part": k[0], "mark_type": k[1], "policy": k[2], "H": k[3], "slot": k[4], "order": k[5], "letters": len(v),
                            "median_of_letter_medians_S": float(np.median([x["median_S"] for x in v])),
                            "mean_share_erased": float(np.mean([x["share_erased"] for x in v]))} for k, v in sorted(agg.items(), key=lambda kv: str(kv[0]))]
    # rule 5: real detached marks against the same letters in fonts
    r5 = []
    for r in summary:
        if r["part"] != "real_k":
            continue
        f = [x for x in summary if x["part"] == "font" and x["letter"] == r["letter"] and x["policy"] == r["policy"] and x["H"] == r["H"]
             and x["slot"] == r["slot"] and x["order"] == r["order"]]
        if f:
            d = r["median_S"] - f[0]["median_S"]
            r5.append({"letter": r["letter"], "policy": r["policy"], "H": r["H"], "slot": r["slot"], "op": r["op"], "order": r["order"],
                       "real_median_S": r["median_S"], "font_median_S": f[0]["median_S"], "diff": d, "carries_over": abs(d) <= 0.15})
    doc["rule5_real_vs_font"] = {"rule": "median S of the real detached marks within 0.15 of the font value for the same op and height = carries over",
                                 "pairs": r5, "share_carries_over": (float(np.mean([x["carries_over"] for x in r5])) if r5 else None)}
    doc["seconds"] = (datetime.datetime.now(datetime.timezone.utc) - t0).total_seconds()
    tmp = a.out + ".tmp"
    with open(tmp, "w") as f:
        json.dump(doc, f, indent=1, ensure_ascii=False)
    os.replace(tmp, a.out)
    print("wrote", a.out, len(summary), "records", doc["seconds"], "s")


if __name__ == "__main__":
    main()