File size: 47,169 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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
"""Report cards: descriptive results per arm (which models are promising, which failed), from VALIDATION score files only.

The status of every arm follows records/R5/RULE/r5_descriptive_labels.txt (sha256 0eaf7801...), applied exactly and stored with the
figures that produced it. The labels describe the arms on the pages; they do not change the decision rule (B1, B2 and the verdict
come from verdict.py). Score files of locked sets are never read here. The error gallery takes examples only from synth_hand_val,
synth_typed_val and print_real_val (never KOHTD, HKR, CHD, school notebooks or any other set of real persons' handwriting).
"""
import collections
import glob
import json
import os
import re

import numpy as np

from . import ioutil, metautil, selection, stats, verdictlib
from .align import align_ops
from .summary import total_samples
from .textnorm import norm

LABEL_RULE_SHA256 = "0eaf78014230ecd1d4d37136a522038e3e1e8f5d7a2b0ffa24027cfb2f3dd98b"
LINE_ARMS = ("A1", "A2", "A3", "A4", "A1s")
P_SHORT = 150000
GALLERY_SETS = ("synth_hand_val", "synth_typed_val", "print_real_val")
NO_IMAGE_SETS = ("print_real_val",)          # real printed documents: text only, no image path in the card
ALIASES = {"kohtd_screen_v1": "V1"}
BROKEN_RE = re.compile(r"\b(nan|inf|infinite|diverg\w*|crash\w*|abort\w*|killed|oom|error|failed)\b", re.I)
NOT_TRAINED_RE = re.compile(r"not trained", re.I)
LEVEL_SETS = ["V1", "kohtd_val", "synth_hand_val", "synth_typed_val", "print_real_val", "synth_clutter_val", "hkr_val", "chd_val", "school_val",
              "hkr_val_s2000", "chd_val_s2000", "school_val_s2000", "curve_v1", "V1lm"]
CLUSTER_ARRAY_SETS = ("V1", "kohtd_val", "synth_hand_val")     # sets whose per-cluster arrays the cards use (load_scores drops them for all other sets)
STATUS_ORDER = ["NOT TRAINED", "BROKEN RUN", "NO GAIN", "FAILS MEMORY GATE", "HALLUCINATES", "NOT COMPETITIVE", "COMPETITIVE", "PROMISING"]


# ---------------------------------------------------------------------------------------------------------------- loading
def canon(stem):
    return ALIASES.get(stem, stem)


def load_scores(scores_dir):
    """(arm, checkpoint) -> {canonical set name: score JSON}. Locked score files and non-scored files are skipped."""
    out = collections.defaultdict(dict)
    skipped_locked = 0
    for p in sorted(glob.glob(os.path.join(scores_dir, "*", "*", "*.json"))):
        parts = p.split(os.sep)
        if parts[-3].startswith("_") or parts[-3] == "pages":
            continue
        try:
            sc = json.load(open(p, encoding="utf-8"))
        except ValueError:
            continue
        if sc.get("locked"):
            skipped_locked += 1
            continue
        if sc.get("status") != "scored":
            continue
        names = ioutil.score_names(sc)
        known = [n for n in LEVEL_SETS + list(GALLERY_SETS) if n in names or canon(n) in names]
        key = known[0] if known else canon(re.sub(r"\s*\(.*\)\s*$", "", sc.get("registry_name") or sc["evalset"]))
        if key not in CLUSTER_ARRAY_SETS:
            # memory: the per-cluster arrays are used only for the paired V1 intervals (aligned_v1_arrays) and the gaps (gaps(): V1, kohtd_val, synth_hand_val); the score files are
            # 2.5 GB on disk (23 Nov: 1,265 files) and the cards of all arms are built in one process, which was killed at 16 GB without this
            for p_ in (sc.get("profiles") or {}).values():
                if isinstance(p_, dict):
                    p_.pop("cluster_sums", None)
                    p_.pop("cluster_ids", None)
        out[(sc["arm"], sc["checkpoint"])][key] = sc
    return out, skipped_locked


_SEED2_VARIANT_TAILS = ("_lm_gated", "_lm", "_retry")


def fold_seed2_arms(by):
    """Seed-2 arm folders as seed-2 checkpoints of their base arm. (arm, ck) keys: an arm folder X_s2 whose base arm X exists (maker-code VLM arms run by the leader
    runner, and the line arms A1_s2 and A2_s2 of LINEDET) is the second seed of X: its checkpoint c becomes (X, c_seed2), a variant tail kept after it (short_lm_gated
    becomes short_seed2_lm_gated), the form the VLMA arms already use. Returns (new mapping, sorted names of the folded folders). A set present in both places keeps
    the base arm's own."""
    arms = {a for a, _ in by}
    out, folded = collections.defaultdict(dict), set()
    for (arm, ck), sets in by.items():
        base = arm[:-3] if arm.endswith("_s2") and arm[:-3] in arms else None
        if base:
            folded.add(arm)
            tail = next((t for t in _SEED2_VARIANT_TAILS if ck.endswith(t)), "")
            key = (base, ck[: len(ck) - len(tail)] + "_seed2" + tail)
        else:
            key = (arm, ck)
        for name, sc in sets.items():
            if base is None or name not in out[key]:
                out[key][name] = sc
    return out, sorted(folded)


def load_meta(preds_dir, arm, ck):
    """meta.json of a checkpoint; a folded seed-2 checkpoint (c_seed2 of arm X) falls back to the arm folder X_s2 (checkpoint c)."""
    cands = [(arm, ck)]
    if "_seed2" in ck:
        tail = next((t for t in _SEED2_VARIANT_TAILS if ck.endswith(t)), "")
        stem = ck[: len(ck) - len(tail)]
        if stem.endswith("_seed2"):
            cands.append((arm + "_s2", stem[: -len("_seed2")] + tail))
    for a2, c2 in cands:
        p = os.path.join(preds_dir, a2, c2, "meta.json")
        if os.path.exists(p):
            try:
                return json.load(open(p, encoding="utf-8"))
            except ValueError:
                return {}
    return {}


def meta_value(meta, test):
    if isinstance(meta, dict):
        for k, v in meta.items():
            if isinstance(v, (int, float)) and not isinstance(v, bool) and test(str(k).lower()):
                return v
        for v in meta.values():
            if isinstance(v, dict):
                r = meta_value(v, test)
                if r is not None:
                    return r
    return None


def read_zero_shot(tsv_path):
    """J2 results.tsv: model -> pooled CER at 1x (the pre-registered main figure of that pass), complete rows only."""
    out = {}
    if tsv_path and os.path.exists(tsv_path):
        lines = open(tsv_path, encoding="utf-8").read().rstrip("\n").split("\n")
        hdr = lines[0].split("\t")
        for l in lines[1:]:
            r = dict(zip(hdr, l.split("\t")))
            if r.get("scale") == "1" and r.get("complete") == "yes":
                try:
                    out[r["model"]] = float(r["cer_pooled"])
                except ValueError:
                    pass
    return out


def read_models_tsv(path):
    out = {}
    if path and os.path.exists(path):
        lines = open(path, encoding="utf-8").read().rstrip("\n").split("\n")
        hdr = lines[0].split("\t")
        for l in lines[1:]:
            r = dict(zip(hdr, l.split("\t")))
            try:
                out[r["short"]] = float(r["params_unique_design"]) / 1e9
            except (KeyError, ValueError):
                pass
    return out


def fuzzy_get(d, arm):
    if arm in d:
        return d[arm]
    for k, v in d.items():
        if k.startswith(arm) or arm.startswith(k):
            return v
    return None


# ---------------------------------------------------------------------------------------------------------------- accessors
def rec(sc, group="all", metric="cer", profile="plain"):
    try:
        return sc["profiles"][profile]["groups"][group]["metrics"][metric]
    except (KeyError, TypeError):
        return None


def fig(r):
    if r is None:
        return None
    return {"value": r.get("value"), "lo": r.get("lo"), "hi": r.get("hi"), "num": r.get("num"), "den": r.get("den"), "rare": r.get("rare", False)}


def v(r):
    """Number of a metric record, from num/den when the record is flagged rare."""
    if r is None:
        return None
    if r.get("value") is not None:
        return r["value"]
    if r.get("den"):
        return r["num"] / r["den"]
    return None


def cluster_arrays(sc, group, profile="plain"):
    p = sc["profiles"][profile]
    cs = p["cluster_sums"].get(group)
    return p["cluster_ids"], cs


def gap(sc, group_a, group_b=None, minus_from=None, B=stats.B_DEFAULT):
    """CER(group_a) - CER(group_b) with a paired cluster-bootstrap interval. With minus_from, group_b is that group minus group_a
    (for example all crops minus the unseen-word slice = the seen words)."""
    try:
        ids, a = cluster_arrays(sc, group_a)
        if a is None:
            return None
        if minus_from:
            _, tot = cluster_arrays(sc, minus_from)
            if tot is None:
                return None
            bd, bl = np.asarray(tot["dist"]) - np.asarray(a["dist"]), np.asarray(tot["ref_len"]) - np.asarray(a["ref_len"])
        else:
            _, b = cluster_arrays(sc, group_b)
            if b is None:
                return None
            bd, bl = np.asarray(b["dist"]), np.asarray(b["ref_len"])
        ad, al = np.asarray(a["dist"]), np.asarray(a["ref_len"])
        if al.sum() < stats.MIN_EVENTS or bl.sum() < stats.MIN_EVENTS:
            return {"note": "fewer than %d reference characters in a group" % stats.MIN_EVENTS, "ref_len_a": float(al.sum()), "ref_len_b": float(bl.sum())}
        r = stats.paired_ratio_difference(ad, al, bd, bl, B=B)
        r.pop("_rel_reps", None)
        return {"cer_a": r["cer_x"], "cer_b": r["cer_y"], "gap_abs": r["d_abs"], "gap_abs_ci95": r.get("d_abs_ci95"), "gap_rel": r["d_rel"],
                "gap_rel_ci95": r.get("d_rel_ci95"), "B": r["B"], "K": r["K"]}
    except (KeyError, TypeError):
        return None


# ---------------------------------------------------------------------------------------------------------------- card sections
def headline(sets):
    out = {}
    for name in LEVEL_SETS:
        sc = sets.get(name)
        if not sc:
            continue
        pp = rec(sc, "all", "cer", "pp")
        out[name] = {"n_crops": sc["coverage"]["scored_rows"], "complete": sc["coverage"]["complete"], "cer": fig(rec(sc)),
                     "cer_postprocessed": fig(pp), "wer": fig(rec(sc, "all", "wer")), "exact_match": fig(rec(sc, "all", "exact_match")),
                     "n_clusters": sc["profiles"]["plain"]["groups"].get("all", {}).get("n_clusters")}
    return out


def per_language(sets):
    out = {}
    for name in ("synth_hand_val", "synth_typed_val", "print_real_val", "curve_v1", "hkr_val"):
        sc = sets.get(name)
        if not sc:
            continue
        macro = (sc["profiles"]["plain"].get("macro") or {}).get("macro_language_cer")
        langs = {}
        for g, r in sc["profiles"]["plain"]["groups"].items():
            if g.startswith("lang:"):
                langs[g[5:]] = {"cer": fig(r["metrics"].get("cer")), "n_crops": r["n_items"], "n_clusters": r["n_clusters"]}
        if macro or langs:
            out[name] = {"what_is_measured": WHAT.get(name), "macro_over_languages": macro, "languages": langs}
    return out


WHAT = {"synth_hand_val": "synthetic handwriting (rendered from handwriting fonts); not real handwriting",
        "synth_typed_val": "synthetic typed lines", "print_real_val": "real printed lines (born-digital PDFs)",
        "curve_v1": "fixed learning-curve set: Kazakh real handwriting words plus synthetic and printed lines (see learning_curve)",
        "hkr_val": "real handwriting words (Russian, a few Kazakh)"}


def sdi(sets):
    out = {}
    for name in ("V1", "kohtd_val", "synth_hand_val", "synth_typed_val", "print_real_val", "hkr_val"):
        sc = sets.get(name)
        if not sc:
            continue
        s, d, i = (rec(sc, "all", k) for k in ("sub_rate", "del_rate", "ins_rate"))
        if not (s and d and i):
            continue
        tot = s["num"] + d["num"] + i["num"]
        out[name] = {"substitutions_per_ref_char": fig(s), "deletions_per_ref_char": fig(d), "insertions_per_ref_char": fig(i),
                     "share_of_errors": {"substitution": s["num"] / tot if tot else None, "deletion": d["num"] / tot if tot else None,
                                         "insertion": i["num"] / tot if tot else None}, "character_errors": tot}
    return out


def confusions(sets, top=15):
    out = {}
    for name in ("V1", "kohtd_val", "synth_hand_val", "synth_typed_val", "print_real_val"):
        sc = sets.get(name)
        if not sc:
            continue
        conf = sc["profiles"]["plain"].get("confusion")
        if not conf:
            continue
        agg = collections.Counter()
        for lang, lst in conf["top20_off_diagonal_per_language"].items():
            for e in lst:
                agg[(e["ref"], e["out"])] += e["count"]
        out[name] = [{"reference": r, "output": o, "count": n, "meaning": ("deleted" if o == "" else ("inserted" if r == "" else "replaced"))}
                     for (r, o), n in agg.most_common(top)]
        out[name + ":note"] = "merged from the top 20 of each language; a pair outside a language's top 20 is not counted"
    return out


def special_letters(sets):
    out = {}
    for name in ("V1", "kohtd_val", "synth_hand_val", "synth_typed_val", "print_real_val", "hkr_val"):
        sc = sets.get(name)
        if not sc:
            continue
        g = sc["profiles"]["plain"]["groups"].get("all", {}).get("metrics", {})
        tab = collections.defaultdict(lambda: collections.defaultdict(dict))
        for k, r in g.items():
            if not k.startswith(("sl|", "slm|", "slg|")):
                continue
            kind, lang, u, what = k.split("|")
            key = {"sl": u, "slm": u + " (both cases)", "slg": "ALL special letters of " + lang}[kind]
            tab[lang][key][what] = {"value": r.get("value"), "lo": r.get("lo"), "hi": r.get("hi"), "num": r.get("num"), "den": r.get("den"),
                                    "rare": r.get("rare")}
        if tab:
            out[name] = {lang: dict(t) for lang, t in tab.items()}
    return out


def lookalikes(sets):
    out = {}
    for name in ("V1", "kohtd_val", "synth_hand_val", "synth_typed_val", "print_real_val"):
        sc = sets.get(name)
        if not sc:
            continue
        out[name] = {k: fig(rec(sc, "all", k)) for k in ("homoglyph_sub_rate", "mixed_script_token_rate_out", "mixed_script_token_rate_ref",
                                                         "other_script_rate_out", "other_script_rate_ref")}
    return out


def hallucination(sets):
    out = {}
    for name in ("V1", "kohtd_val", "synth_hand_val", "synth_typed_val", "print_real_val", "synth_clutter_val", "curve_v1"):
        sc = sets.get(name)
        if not sc:
            continue
        d = {"HR1_text_on_empty_images": fig(rec(sc, "all", "hr1")), "HR1_mean_output_characters": fig(rec(sc, "all", "hr1_mean_output_chars")),
             "HR2_inserted_chars_per_ref_char": fig(rec(sc, "all", "ins_rate")), "HR3_overlong_or_garbage": fig(rec(sc, "all", "hr3")),
             "HR4_loops": fig(rec(sc, "all", "hr4")), "fabricated_words_per_ref_word": fig(rec(sc, "all", "fabricated_word_rate")),
             "omissions_deleted_chars_per_ref_char": fig(rec(sc, "all", "del_rate")), "omitted_words_per_ref_word": fig(rec(sc, "all", "word_omission_rate")),
             "empty_outputs": fig(rec(sc, "all", "empty_output_rate")), "stopped_at_token_cap": fig(rec(sc, "all", "hit_cap_rate"))}
        out[name] = {k: x for k, x in d.items() if x is not None}
    return out


def by_group(sets):
    out = {"by_length_bucket": {}, "by_noise_effect_and_attribute": {}}
    for name in ("V1", "kohtd_val", "synth_hand_val", "synth_typed_val", "print_real_val", "curve_v1"):
        sc = sets.get(name)
        if not sc:
            continue
        groups = sc["profiles"]["plain"]["groups"]
        L = {g[4:]: {"cer": fig(r["metrics"].get("cer")), "n_crops": r["n_items"]} for g, r in groups.items() if g.startswith("len:") and "cer" in r["metrics"]}
        if L:
            out["by_length_bucket"][name] = L
        E = {}
        for g, r in groups.items():
            if g.startswith(("effect:", "attr:", "font:", "fontgroup:")) and "cer" in r["metrics"]:
                E[g] = {"cer": fig(r["metrics"]["cer"]), "n_crops": r["n_items"]}
        if E:
            none = (E.get("effect:none") or {}).get("cer")
            for g, d in E.items():
                if g.startswith("effect:") and g != "effect:none" and none and none.get("value") is not None and d["cer"].get("value") is not None:
                    d["delta_vs_no_effect"] = d["cer"]["value"] - none["value"]
            out["by_noise_effect_and_attribute"][name] = E
    out["note"] = ("noise effects co-occur, so deltas are descriptive and carry no interval; only the sidecar columns GEN wrote exist: "
                   "page_type, paper_kind, strength, geo_mode, ink, crop_mode, region_class, font, and the effects pattern/binder/staple/creases/stains/show_through")
    return out


def gaps(sets):
    out = {}
    hs = sets.get("synth_hand_val")
    if hs:
        out["unseen_font"] = {"all_scripts": gap(hs, "fontgroup:unseen", "fontgroup:seen"),
                              "Cyrl": gap(hs, "fontgroup:unseen|Cyrl", "fontgroup:seen|Cyrl"),
                              "Latn": gap(hs, "fontgroup:unseen|Latn", "fontgroup:seen|Latn"),
                              "note": "CER on lines in held-out handwriting fonts minus CER on lines in training fonts (synth_hand_val)",
                              "reading_H16": "reported as uninformative (clarification H16): held-out fonts score no worse than seen fonts in every arm, so this check does "
                                             "not show generalisation to real hands"}
        ga = (out["unseen_font"]["all_scripts"] or {}).get("gap_abs")
        out["unseen_font"]["held_out_no_worse_than_seen"] = (ga <= 0) if isinstance(ga, (int, float)) else None
    for name in ("V1", "kohtd_val"):
        sc = sets.get(name)
        if sc and "slice:P2" in sc["profiles"]["plain"]["groups"]:
            out["unseen_word_" + name] = gap(sc, "slice:P2", minus_from="all")
            out["unseen_word_" + name + ":note"] = "CER on words in no handwriting training label (slice P2 of K_train) minus CER on all other words"
    if not any(k.startswith("unseen_word") for k in out):
        out["unseen_word"] = {"note": "not available: needs K_train, which is built after the mix_v1 freeze"}
    return out


def calibration(sets):
    out = {}
    for name in ("V1", "kohtd_val", "synth_hand_val", "synth_typed_val", "print_real_val"):
        sc = sets.get(name)
        c = ((sc or {}).get("profiles", {}).get("plain", {}).get("calibration") or {}).get("all")
        if c and c.get("conf"):
            k = c["conf"]
            out[name] = {"conf_kind": sc["set_info"].get("conf_kind"), "ece_equal_mass_15": k["ece_equal_mass_15"], "ece_equal_width_15": k["ece_equal_width_15"],
                         "ed_ece_1": k["ed_ece_1"], "brier": k["brier"], "aurc": k["aurc"], "mean_confidence": k["mean_conf"], "accuracy": k["accuracy"],
                         "risk_coverage": k["risk_coverage"], "intervals": k.get("ci")}
    return out


def speed_memory(meta):
    mm, sp = metautil.memory(meta), metautil.speed(meta)
    return {"peak_mem_reserved_gib": mm["reserved_gib"], "peak_mem_allocated_gib": mm["allocated_gib"], "peak_mem_basis": mm["basis"],
            "images_per_second_batch16": sp["images_per_second"], "speed_basis": sp["basis"],
            "latency_batch1_s": meta_value(meta, lambda k: k.startswith("latency_batch1")), "gpu": meta.get("gpu"),
            "note": "H100 figures, not RTX 5090"}


def postproc(sets):
    out = {}
    for name in ("V1", "kohtd_val", "synth_hand_val", "synth_typed_val", "print_real_val"):
        sc = sets.get(name)
        if sc and sc.get("postproc"):
            out[name] = sc["postproc"]
    return out


# ---------------------------------------------------------------------------------------------------------------- gallery
def diff_segments(ref, hyp):
    d, ops = align_ops(ref, hyp)
    segs, cur_r, cur_o = [], "", ""
    eq = ""
    for op, i, j in ops:
        if op == "M":
            if cur_r or cur_o:
                segs.append({"op": "replace" if cur_r and cur_o else ("delete" if cur_r else "insert"), "ref": cur_r, "out": cur_o})
                cur_r = cur_o = ""
            eq += ref[i]
        else:
            if eq:
                segs.append({"op": "equal", "ref": eq, "out": eq})
                eq = ""
            if op in ("S", "D"):
                cur_r += ref[i]
            if op in ("S", "I"):
                cur_o += hyp[j]
    if eq:
        segs.append({"op": "equal", "ref": eq, "out": eq})
    if cur_r or cur_o:
        segs.append({"op": "replace" if cur_r and cur_o else ("delete" if cur_r else "insert"), "ref": cur_r, "out": cur_o})
    return d, segs


def gallery(arm, ck, sets, preds_dir, n=12):
    """12 error examples, only from the three allowed sets. Examples are spread over the error range of each set (quantile positions of
    the crops with errors, sorted by per-crop CER), so the gallery shows mild and severe cases."""
    from .ioutil import read_manifest, read_meta_tsv, read_preds
    present = [s for s in GALLERY_SETS if s in sets]
    if not present:
        return {"examples": [], "note": "no synth_hand_val, synth_typed_val or print_real_val score file yet"}
    base = n // len(present)
    quotas = {s: base for s in present}
    for s in present[: n - base * len(present)]:
        quotas[s] += 1
    ex = []
    for s in present:
        assert s in GALLERY_SETS, "gallery source not allowed"
        sc = sets[s]
        pred_path = (sc.get("inputs") or {}).get("pred_path") or os.path.join(preds_dir, arm, ck, s + ".tsv")
        man_path = (sc.get("inputs") or {}).get("manifest_path")
        if not os.path.exists(pred_path) or not man_path or not os.path.exists(man_path):
            continue
        preds, _, _, _ = read_preds(pred_path)
        mrows = {r["id"]: r for r in read_manifest(man_path)}
        side_path = os.path.splitext(man_path)[0] + ".meta.tsv"
        side = read_meta_tsv(side_path) if os.path.exists(side_path) else {}
        cand = []
        for i, p in preds.items():
            r = mrows.get(i)
            if r is None:
                continue
            ref, hyp = norm(r["text"]), norm(p["hyp"])
            if not ref or ref == hyp:
                continue
            d, _ = align_ops(ref, hyp)
            cand.append((d / len(ref), i, ref, hyp))
        cand.sort()
        if not cand:
            continue
        k = min(quotas[s], len(cand))
        pos = sorted({int(round(q * (len(cand) - 1))) for q in np.linspace(0.15, 0.95, k)}) if k > 1 else [len(cand) // 2]
        for pi in pos:
            cer, i, ref, hyp = cand[pi]
            d, segs = diff_segments(ref, hyp)
            r = mrows[i]
            e = {"set": s, "id": i, "lang": r["lang"], "kind": r["kind"], "reference": ref, "output": hyp, "cer": cer, "character_errors": d,
                 "diff": segs, "image": None if s in NO_IMAGE_SETS else r["image"]}
            sd = side.get(i)
            if sd:
                e["font_id"] = sd.get("font_id")
                e["font_group"] = sd.get("font_group")
                e["effects"] = sd.get("effects")
                e["page_type"] = sd.get("page_type")
            ex.append(e)
    return {"examples": ex[:n], "allowed_sets": list(GALLERY_SETS),
            "note": "examples are spread over the error range of each set; the image path of print_real_val is withheld; no real person's handwriting set is used"}


# ---------------------------------------------------------------------------------------------------------------- curve
def learning_curve(arm, ck_sets, preds_dir):
    pts = []
    for ck, sets in ck_sets.items():
        sc = sets.get("curve_v1")
        if not sc or variant_kind(ck):
            continue                       # a cap-retry decoding, an LM decoding, a second seed or a vote is not a point of this run's curve
        meta = load_meta(preds_dir, arm, ck)
        n = total_samples(meta)
        g = sc["profiles"]["plain"]["groups"]

        def c(group):
            r = g.get(group, {}).get("metrics", {}).get("cer")
            return fig(r) if r else None
        h = g.get("kind:clutter", {}).get("metrics", {}).get("hr1")
        pts.append({"checkpoint": ck, "samples_seen": n, "fraction_of_P_short": (n / P_SHORT) if isinstance(n, (int, float)) else None,
                    "cer_all_text_crops": c("all"), "cer_handwriting_kohtd_part": c("kind:hand_real"), "cer_synthetic_handwriting": c("kind:hand_synth"),
                    "cer_synthetic_typed": c("kind:typed_synth"), "cer_real_print": c("kind:typed_real"),
                    "hr1_clutter": fig(h) if h else None, "complete": sc["coverage"]["complete"]})
    pts.sort(key=lambda p: (p["samples_seen"] is None, p["samples_seen"] or 0, p["checkpoint"]))
    flag, why = None, "fewer than two curve points near 75% and 100% of P_short"
    with_n = [p for p in pts if isinstance(p["samples_seen"], (int, float)) and p["cer_handwriting_kohtd_part"] and p["cer_handwriting_kohtd_part"].get("value") is not None]
    if with_n:
        p75 = min(with_n, key=lambda p: abs(p["samples_seen"] - 0.75 * P_SHORT))
        p100 = min(with_n, key=lambda p: abs(p["samples_seen"] - P_SHORT))
        if p75 is not p100 and abs(p75["samples_seen"] - 0.75 * P_SHORT) <= 0.1 * P_SHORT and abs(p100["samples_seen"] - P_SHORT) <= 0.1 * P_SHORT:
            a, b = p75["cer_handwriting_kohtd_part"]["value"], p100["cer_handwriting_kohtd_part"]["value"]
            if a and a > 0:
                fell = (a - b) / a
                flag = "still improving" if fell > 0.10 else "plateaued"
                why = "KOHTD-part CER %.4f at %s samples and %.4f at %s samples: fell by %.1f%% (relative)" % (a, p75["samples_seen"], b, p100["samples_seen"], 100 * fell)
    return {"points": pts, "flag": flag, "flag_figures": why,
            "reading": "'V1-curve CER' is read as the CER on the KOHTD part (V1lm rows) of curve_v1 at the checkpoints; x = samples_seen of the checkpoint"}


# ---------------------------------------------------------------------------------------------------------------- status
MIN_ERRORS_FOR_LANGUAGE_FLAG = 20          # clarification H15: a per-language flag is printed only when it rests on at least 20 character errors


def language_flags(sets, with_suppressed=False):
    """'weak on <language>': CER of the language more than 2 x the set's macro CER over languages (label rule), printed only with at least
    20 character errors in that language and set (H15). Each printed flag carries the interval of the language's CER."""
    flags, suppressed = [], []
    for name in ("synth_hand_val", "synth_typed_val", "print_real_val"):
        sc = sets.get(name)
        if not sc:
            continue
        macro = (sc["profiles"]["plain"].get("macro") or {}).get("macro_language_cer")
        if not macro or macro.get("value") is None:
            continue
        groups = sc["profiles"]["plain"]["groups"]
        for lang, cer in (macro.get("per_language") or {}).items():
            if macro["value"] > 0 and cer > 2.0 * macro["value"]:
                m = (groups.get("lang:" + lang, {}).get("metrics", {}) or {}).get("cer") or {}
                errors = m.get("num") or 0
                f = {"flag": "weak on %s" % lang, "set": name, "cer": cer, "cer_ci95": [m.get("lo"), m.get("hi")], "macro_cer": macro["value"],
                     "ratio": cer / macro["value"], "character_errors": errors,
                     "note": "synthetic data" if name != "print_real_val" else "real printed lines"}
                (flags if errors >= MIN_ERRORS_FOR_LANGUAGE_FLAG else suppressed).append(f)
    return (flags, suppressed) if with_suppressed else flags


def v1_cer(sets):
    sc = sets.get("V1")
    if not sc or not sc["coverage"]["complete"]:
        return None
    return v(rec(sc))


def aligned_v1_arrays(sc_x, sc_y):
    """Cluster arrays (dist, ref_len) of two V1 score files on the union of their forms; None if the reference lengths differ."""
    try:
        ids_x, ax = cluster_arrays(sc_x, "all")
        ids_y, ay = cluster_arrays(sc_y, "all")
    except (KeyError, TypeError):
        return None
    if ax is None or ay is None:
        return None
    ids = sorted(set(ids_x) | set(ids_y))

    def put(cid, a):
        pos = {c: i for i, c in enumerate(cid)}
        n, d = np.zeros(len(ids)), np.zeros(len(ids))
        for i, c in enumerate(ids):
            j = pos.get(c)
            if j is not None:
                n[i], d[i] = a["dist"][j], a["ref_len"][j]
        return n, d
    nx, dx = put(ids_x, ax)
    ny, dy = put(ids_y, ay)
    if not np.array_equal(dx, dy):
        return None
    return nx, dx, ny, dy


def ratio_interval(sc_x, sc_ref, B=stats.B_DEFAULT):
    """CER(x) / CER(reference) with a paired form-bootstrap 95% interval: (ratio, [lo, hi]) or (None, None)."""
    arr = aligned_v1_arrays(sc_x, sc_ref)
    if arr is None:
        return None, None
    r = stats.paired_ratio_difference(*arr, B=B)
    if r.get("d_rel_ci95") is None or r.get("d_rel") is None:
        return (1.0 + r["d_rel"]) if r.get("d_rel") is not None else None, None
    return 1.0 + r["d_rel"], [1.0 + r["d_rel_ci95"][0], 1.0 + r["d_rel_ci95"][1]]


def assign_status(arm, info, sets_short, meta_short, ctx, curve_flag, ckpt_label="short (P_short)"):
    """Exactly one status, checked in the order of r5_descriptive_labels.txt. Returns (status, figures, note).
    Every figure that decides a label is printed with its 95% interval where one exists (clarification H15); interval_crosses lists the
    thresholds (1.10 and 1.5 times the lowest V1 CER) that lie inside the interval of the ratio, i.e. where the label could differ."""
    figs = {"checkpoint": ckpt_label}
    flagtxt = str(meta_short.get("train_flag") or "") + " " + " ".join(info.get("flags", []))
    # 1
    if info.get("not_trained_reason") or NOT_TRAINED_RE.search(flagtxt):
        figs["reason"] = info.get("not_trained_reason") or flagtxt.strip()
        return "NOT TRAINED", figs, None
    # 2
    br = info.get("broken_run_reason") or (BROKEN_RE.search(flagtxt) and flagtxt.strip())
    if br:
        figs["reason"] = br
        return "BROKEN RUN", figs, None
    if not sets_short:
        return None, figs, "no score file at P_short yet: the arm cannot be labelled"
    cer = v1_cer(sets_short)
    figs["v1_cer_at_P_short"] = cer
    if cer is None:
        return None, figs, "no complete V1 score at P_short yet: the arm cannot be labelled"
    r1 = rec(sets_short["V1"])
    figs["v1_cer_ci95"] = [r1.get("lo"), r1.get("hi")]
    figs["interval_method"] = "95% cluster bootstrap over forms (V1) or source pages (clutter), 10,000 resamples; a label is a threshold on a point estimate"
    figs["lowest_v1_cer_of_any_arm"] = ctx["lowest"]
    figs["lowest_arm"] = ctx.get("lowest_arm")
    # 3
    zs = info.get("zero_shot_v1_cer")
    figs["zero_shot_v1_cer"] = zs
    if zs is not None:
        figs["zero_shot_note"] = "zero-shot figure of the J2 screen (V1, 1x), a single run without an interval; the fine-tuned figure carries v1_cer_ci95"
    if zs is not None and not (cer < zs):
        figs["rule"] = "V1 CER at P_short is not lower than the arm's own zero-shot V1 CER"
        return "NO GAIN", figs, None
    # 4
    mm = metautil.memory(meta_short)
    mem = mm["reserved_gib"]
    figs["peak_mem_reserved_gib"] = mem
    figs["peak_mem_basis"] = mm["basis"]
    figs["peak_mem_note"] = "one measurement, no interval"
    figs["gate_24GB_as_gib"] = verdictlib.GATE_DECIMAL_GIB
    if mem is not None and mem > verdictlib.GATE_DECIMAL_GIB + verdictlib.EPS:
        figs["exceeds_24_GiB_reading_too"] = mem > verdictlib.GATE_BINARY_GIB + verdictlib.EPS
        return "FAILS MEMORY GATE", figs, None
    # 5
    cl = sets_short.get("synth_clutter_val")
    hr1 = v(rec(cl, "all", "hr1")) if cl else None
    a1_hr1 = ctx["hr1_a1"]
    figs.update({"hr1_clutter_val": hr1, "hr1_a1": a1_hr1})
    if cl and rec(cl, "all", "hr1"):
        figs["hr1_clutter_val_ci95"] = [rec(cl, "all", "hr1").get("lo"), rec(cl, "all", "hr1").get("hi")]
    v1sc = sets_short.get("V1")
    hr4 = v(rec(v1sc, "all", "hr4")) if v1sc else None
    figs["hr4_v1"] = hr4
    if v1sc and rec(v1sc, "all", "hr4"):
        figs["hr4_v1_ci95"] = [rec(v1sc, "all", "hr4").get("lo"), rec(v1sc, "all", "hr4").get("hi")]
    halluc = []
    if hr1 is not None:
        thr = max(2 * a1_hr1, a1_hr1 + 0.02) if a1_hr1 is not None else None
        if (thr is not None and hr1 > thr + verdictlib.EPS) or hr1 > 0.05 + verdictlib.EPS:
            ci = figs.get("hr1_clutter_val_ci95") or [None, None]
            halluc.append("HR1 %.4f (95%% interval %s) above max(2 x A1, A1 + 2 points) = %s or above 5%%" % (
                hr1, "[%.4f, %.4f]" % tuple(ci) if ci[0] is not None else "not available", "%.4f" % thr if thr is not None else "unknown (no A1 HR1)"))
    if hr4 is not None and hr4 > 0.001 + verdictlib.EPS:
        ci = figs.get("hr4_v1_ci95") or [None, None]
        halluc.append("HR4 %.5f (95%% interval %s) above 0.1%% on V1" % (hr4, "[%.5f, %.5f]" % tuple(ci) if ci[0] is not None else "not available"))
    if halluc:
        figs["reasons"] = halluc
        return "HALLUCINATES", figs, None
    # 6
    ratio = cer / ctx["lowest"] if ctx["lowest"] else None
    figs["ratio_to_lowest"] = ratio
    if ctx.get("lowest_sets") and ctx.get("lowest_arm") != arm:
        _, ci = ratio_interval(sets_short["V1"], ctx["lowest_sets"]["V1"])
        figs["ratio_to_lowest_ci95"] = ci
        if ci:
            figs["interval_crosses"] = [t for t in (1.10, 1.5) if ci[0] <= t <= ci[1]]
    elif ctx.get("lowest_arm") == arm:
        figs["ratio_to_lowest_ci95"] = [1.0, 1.0]
        figs["interval_crosses"] = []
    if ratio is not None and ratio > 1.5 + verdictlib.EPS:
        return "NOT COMPETITIVE", figs, None
    # 8 before 7
    cls = "line" if arm in LINE_ARMS else selection.size_class(info.get("unique_params_b"))
    figs["size_class"] = cls if cls is not None else "unknown (no unique parameter count): the size-class rule is not applied"
    lowest_in_class = ctx["lowest_by_class"].get(cls) if cls is not None else None
    figs["lowest_v1_cer_in_class"] = lowest_in_class
    if ratio is not None and ratio <= 1.10 + verdictlib.EPS:
        figs["why_promising"] = "V1 CER within 10%% of the lowest (ratio %.3f)" % ratio
        return "PROMISING", figs, None
    if lowest_in_class is not None and cer <= lowest_in_class + 1e-15:
        figs["why_promising"] = "lowest V1 CER in its size class (%s)" % cls
        return "PROMISING", figs, None
    return "COMPETITIVE", figs, None


# ---------------------------------------------------------------------------------------------------------------- matrix and failure modes
MATRIX = [
    ("v1_cer", "CER on V1 (plain)", "lower", lambda c: c["headline"].get("V1", {}).get("cer", {}) and c["headline"]["V1"]["cer"].get("value")),
    ("v1_cer_postprocessed", "CER on V1 after post-processing", "lower", lambda c: (c["headline"].get("V1", {}).get("cer_postprocessed") or {}).get("value")),
    ("kohtd_val_cer", "CER on all KOHTD validation crops", "lower", lambda c: (c["headline"].get("kohtd_val", {}).get("cer") or {}).get("value")),
    ("hand_synth_macro_cer", "macro CER over languages, synthetic handwriting", "lower", lambda c: ((c["per_language"].get("synth_hand_val") or {}).get("macro_over_languages") or {}).get("value")),
    ("typed_synth_macro_cer", "macro CER over languages, synthetic typed lines", "lower", lambda c: ((c["per_language"].get("synth_typed_val") or {}).get("macro_over_languages") or {}).get("value")),
    ("print_real_macro_cer", "macro CER over languages, real printed lines", "lower", lambda c: ((c["per_language"].get("print_real_val") or {}).get("macro_over_languages") or {}).get("value")),
    ("unseen_font_cer", "CER on held-out handwriting fonts", "lower", lambda c: (c["headline_extra"].get("unseen_font_cer"))),
    ("unseen_font_gap", "held-out font CER minus training font CER", "lower", lambda c: ((c["gaps"].get("unseen_font") or {}).get("all_scripts") or {}).get("gap_abs")),
    ("unseen_word_gap_v1", "unseen-word CER minus seen-word CER on V1", "lower", lambda c: (c["gaps"].get("unseen_word_V1") or {}).get("gap_abs")),
    ("hr1_clutter", "HR1: text on empty images", "lower", lambda c: (c["hallucination"].get("synth_clutter_val", {}).get("HR1_text_on_empty_images") or {}).get("value")),
    ("hr2_v1", "HR2: inserted characters per reference character, V1", "lower", lambda c: (c["hallucination"].get("V1", {}).get("HR2_inserted_chars_per_ref_char") or {}).get("value")),
    ("hr3_v1", "HR3: overlong or garbage outputs, V1", "lower", lambda c: (c["hallucination"].get("V1", {}).get("HR3_overlong_or_garbage") or {}).get("value")),
    ("hr4_v1", "HR4: loops, V1", "lower", lambda c: (c["hallucination"].get("V1", {}).get("HR4_loops") or {}).get("value")),
    ("fabricated_words_v1", "fabricated words per reference word, V1", "lower", lambda c: (c["hallucination"].get("V1", {}).get("fabricated_words_per_ref_word") or {}).get("value")),
    ("omissions_v1", "deleted characters per reference character, V1", "lower", lambda c: (c["hallucination"].get("V1", {}).get("omissions_deleted_chars_per_ref_char") or {}).get("value")),
    ("empty_outputs_v1", "empty outputs, V1", "lower", lambda c: (c["hallucination"].get("V1", {}).get("empty_outputs") or {}).get("value")),
    ("special_letter_miss_v1", "pooled miss rate on Kazakh special letters, V1", "lower", lambda c: c["headline_extra"].get("kk_special_letter_miss_v1")),
    ("homoglyph_rate_v1", "look-alike substitutions of the other script, V1", "lower", lambda c: (c["lookalikes"].get("V1", {}).get("homoglyph_sub_rate") or {}).get("value")),
    ("ece_v1", "expected calibration error, V1", "lower", lambda c: (c["calibration"].get("V1") or {}).get("ece_equal_mass_15")),
    ("aurc_v1", "area under the risk-coverage curve, V1", "lower", lambda c: (c["calibration"].get("V1") or {}).get("aurc")),
    ("images_per_second", "images per second, batch 16 (H100)", "higher", lambda c: c["speed_memory"].get("images_per_second_batch16")),
    ("peak_mem_reserved_gib", "peak GPU memory reserved, batch 1 (GiB)", "lower", lambda c: c["speed_memory"].get("peak_mem_reserved_gib")),
    ("unique_params_b", "unique parameters (billions)", "lower", lambda c: c.get("unique_params_b")),
]


def ranks(values, direction):
    items = [(a, x) for a, x in values.items() if x is not None]
    items.sort(key=lambda t: t[1], reverse=(direction == "higher"))
    out, prev, rk = {}, None, 0
    for pos, (a, x) in enumerate(items, start=1):
        if prev is None or x != prev:
            rk = pos
            prev = x
        out[a] = rk
    return out


def comparison_matrix(cards, reference_arms=()):
    """Arms by metrics with ranks (1 = best). Reference arms (amendment 3.3 D5) show their values but take no rank and give none away."""
    out = {"metrics": [], "arms": {}, "reference_arms_not_ranked": sorted(reference_arms)}
    for key, plain, direction, fn in MATRIX:
        vals = {}
        for arm, c in cards.items():
            try:
                x = fn(c)
            except (KeyError, TypeError, AttributeError):
                x = None
            vals[arm] = x if isinstance(x, (int, float)) and not isinstance(x, bool) else None
        rk = ranks({a: x for a, x in vals.items() if a not in reference_arms}, direction)
        out["metrics"].append({"key": key, "plain_name": plain, "better": direction, "n_arms_with_value": len(rk)})
        for arm in cards:
            out["arms"].setdefault(arm, {})[key] = {"value": vals[arm], "rank": rk.get(arm)}
    return out


def failure_modes(cards_sets):
    """Per arm and set: shares of each error type. substitution, deletion, insertion partition the character errors (shares add to 1);
    the other categories overlap with them and are shares of all character errors; the crop-level categories are shares of crops."""
    out = {}
    for arm, sets in cards_sets.items():
        per = {}
        for name in ("V1", "kohtd_val", "synth_hand_val", "synth_typed_val", "print_real_val", "hkr_val", "chd_val", "school_val"):
            sc = sets.get(name)
            if not sc:
                continue
            g = sc["profiles"]["plain"]["groups"].get("all", {}).get("metrics", {})
            def num(k):
                r = g.get(k)
                return r["num"] if r else 0.0
            tot = num("cer")
            if not tot:
                per[name] = {"character_errors": 0}
                continue
            coll = sum(r["num"] for k, r in g.items() if k.startswith("slg|") and k.endswith("|collapse_rate"))
            n_crops = sc["coverage"]["scored_rows"]
            d = {"character_errors": tot,
                 "partition_of_character_errors": {"substitution": num("sub_rate") / tot, "deletion": num("del_rate") / tot, "insertion": num("ins_rate") / tot},
                 "share_of_character_errors_overlapping": {"special_letter_collapse": coll / tot, "case_only": num("case_error_rate") / tot,
                                                            "look_alike_of_other_script": num("homoglyph_sub_rate") / tot,
                                                            "digit": (num("digit_miss_rate") + num("digit_insertion_rate")) / tot,
                                                            "punctuation": (num("punct_miss_rate") + num("punct_insertion_rate")) / tot,
                                                            "accent_or_dot": num("diacritic_error_rate") / tot},
                 "crop_level": {"empty_output": num("empty_output_rate") / n_crops if n_crops else None, "loop_HR4": num("hr4") / n_crops if n_crops else None,
                                "overlong_or_garbage_HR3": (g["hr3"]["num"] / g["hr3"]["den"]) if g.get("hr3") and g["hr3"]["den"] else None,
                                "third_script_letters": num("other_script_rate_out") / n_crops if n_crops else None},
                 "word_level": {"fabricated_words_per_ref_word": v(g.get("fabricated_word_rate")), "omitted_words_per_ref_word": v(g.get("word_omission_rate"))}}
            per[name] = d
        out[arm] = per
    return out


# ---------------------------------------------------------------------------------------------------------------- extra rows (H15, item 7)
RETRY_LABEL = ("cap-retry decoding at temperature 0.3 (outputs that hit the token cap without an end token are re-decoded once; "
               "r5_posttrain_experiment.txt)")          # NOT a retrained run: the same checkpoint, decoded again for the capped outputs only
VARIANT_SUFFIXES = (("_lm_gated", "gated character LM (H9)"), ("_lm", "character LM as decoded"), ("_retry", RETRY_LABEL),
                    ("_seed2", "second seed"), ("_s2", "second seed"))


def variant_kind(ck):
    """(kind, base checkpoint) of a checkpoint folder name such as short_retry, long_lm_gated, short_lm, long_seed2_lm_gated, vote; None for others."""
    for suf, label in VARIANT_SUFFIXES:
        if ck.endswith(suf):
            return label, ck[: -len(suf)]
    if ck == "vote":
        return "voted outputs of two seeds", None
    return None


def variant_rows(cks):
    """Extra rows for the checkpoint folders <ckpt>_retry, <ckpt>_lm, <ckpt>_lm_gated, <ckpt>_seed2 and vote: headline CERs with intervals and the
    hallucination figures, beside the main row. cks: checkpoint -> {set name: score JSON}."""
    out = []
    for ck, sets in sorted(cks.items()):
        k = variant_kind(ck)
        if not k or not sets:
            continue
        hallu = hallucination(sets)
        out.append({"checkpoint": ck, "kind": k[0], "base_checkpoint": k[1], "headline": headline(sets),
                    "hr1_clutter": (hallu.get("synth_clutter_val") or {}).get("HR1_text_on_empty_images"),
                    "hr4_v1": (hallu.get("V1") or {}).get("HR4_loops"), "hit_cap_v1": (hallu.get("V1") or {}).get("stopped_at_token_cap"),
                    "postprocessing_changes": postproc(sets)})
    return out


def variants_matrix(cards):
    """arm -> checkpoint -> the few figures that tell a variant apart from its base (V1 CER with interval, HR1 on clutter, HR4 on V1)."""
    out = {}
    for arm, c in cards.items():
        rows = {}
        for r in c.get("variant_rows", []):
            v1 = (r["headline"].get("V1") or {}).get("cer") or {}
            rows[r["checkpoint"]] = {"kind": r["kind"], "v1_cer": v1.get("value"), "v1_cer_ci95": [v1.get("lo"), v1.get("hi")],
                                     "hr1_clutter": (r.get("hr1_clutter") or {}).get("value"), "hr4_v1": (r.get("hr4_v1") or {}).get("value")}
        if rows:
            out[arm] = rows
    return out


# ---------------------------------------------------------------------------------------------------------------- clarification H16 notes
def reading_notes(sets):
    """What the synthetic figures can and cannot say (H16), with this arm's own numbers where they exist."""
    notes = [{"id": "H16.a", "text": "Handwriting CER for the eight non-Kazakh languages is reported only as synthetic handwriting. Real handwriting accuracy in those languages "
                                     "is not measured. The only real Latin-script handwriting figure is Azerbaijani on 442 real lines, which exists only in the locked test pass."}]
    syn = ((sets.get("synth_hand_val") or {}).get("profiles", {}).get("plain", {}).get("macro") or {}).get("macro_language_cer") or {}
    real = {}
    for name, label in (("V1", "KOHTD handwriting (Kazakh)"), ("hkr_val", "HKR handwriting (Russian)"), ("hkr_val_s2000", "HKR handwriting (Russian)"),
                        ("chd_val", "CHD handwriting (Russian)"), ("chd_val_s2000", "CHD handwriting (Russian)"),
                        ("school_val", "school notebooks (Russian)"), ("school_val_s2000", "school notebooks (Russian)")):
        sc = sets.get(name)
        if sc and v(rec(sc)) is not None:
            real[label] = v(rec(sc))
    fig_ = {"synthetic_handwriting_macro_cer": syn.get("value"), "real_handwriting_cer": real}
    if syn.get("value") and real:
        fig_["real_over_synthetic"] = {k: x / syn["value"] for k, x in real.items()}
        txt = "For this checkpoint, real handwriting CER is %s times the synthetic handwriting CER, so synthetic CER is not a proxy for real handwriting." % \
              ", ".join("%.1f (%s)" % (x / syn["value"], k) for k, x in real.items())
    else:
        txt = "Real handwriting CER is several times the synthetic CER for the same checkpoint (clarification H16); this card lacks one of the two figures."
    notes.append({"id": "H16.b", "text": txt, "figures": fig_})
    notes.append({"id": "H16.c", "text": "The held-out-font check is reported as uninformative: held-out fonts score no worse than seen fonts in every arm, so it does not show generalisation."})
    return notes