File size: 23,681 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
"""Per-crop analysis and per-group aggregation: the metrics M01-M26 of eval_spec.json that need only (reference, output).

Flow: crop_features() turns one (reference, output) pair into sparse feature counts; Acc adds them to per-cluster sums of every
group the crop belongs to ('all', language, script, kind, length bucket, slices, side-file attributes ...); finalize() turns the
sums into metrics with 95% cluster-bootstrap intervals (S01). All rates are ratios of summed counts (micro).
Empty references (clutter) are excluded from every CER-type figure and feed HR1 only (convention C4).
"""
import collections
import difflib
import functools
import re
import unicodedata

import numpy as np

from . import stats
from .align import align_ops, lev_fast, op_counts
from .lookalike import PARTNER
from .textnorm import (APOSTROPHE_LIKE, base_letter, fold_lower, has_loop, is_mixed_script, other_script)

# ---- language-specific letters (eval_spec M06; source records/R4/G2_generator/letter_stats.tsv, capitals of oʻ gʻ added) -------
LETTERS = {
    "kk": list("ӘәҒғҚқҢңӨөҰұҮүҺһІі"),
    "ky": list("ҢңӨөҮү"),
    "uz_cyrl": list("ЎўҚқҒғҲҳ"),
    "uz_latn": ["Oʻ", "oʻ", "Gʻ", "gʻ"],
    "tt": list("ҖҗҢңҮүҺһӘәӨө"),
    "ba": list("ҒғҘҙҠҡҢңҪҫҮүҺһӘәӨө"),
    "sah": list("ҔҕҤҥҮүҺһӨө"),
    "tr": list("ÇçÖöÜüĞğİıŞş"),
    "az": list("ÇçÖöÜüĞğİıŞşƏə"),
    "tk": list("ÄäÇçÖöÜüÝýŇňŞşŽž"),
}
_PARTNER_LOWER = {
    "kk": {"ә": "а", "ғ": "г", "қ": "к", "ң": "н", "ө": "о", "ұ": "у", "ү": "у", "һ": "х", "і": "и"},
    "ky": {"ң": "н", "ө": "о", "ү": "у"},
    "uz_cyrl": {"ў": "у", "қ": "к", "ғ": "г", "ҳ": "х"},
    "tt": {"җ": "ж", "ң": "н", "ү": "у", "һ": "х", "ә": "а", "ө": "о"},
    "ba": {"ғ": "г", "ҙ": "з", "ҡ": "к", "ң": "н", "ҫ": "с", "ү": "у", "һ": "х", "ә": "а", "ө": "о"},
    "sah": {"ҕ": "г", "ҥ": "н", "ү": "у", "һ": "х", "ө": "о"},
    "uz_latn": {"oʻ": "o", "gʻ": "g"},
}


def _collapse_partners():
    out = {}
    for lang, tab in _PARTNER_LOWER.items():
        d = {}
        for c, p in tab.items():
            d[c] = p
            d[c.upper()] = p.upper()
        out[lang] = d
    for lang in ("tr", "az", "tk"):
        d = {}
        for c in LETTERS[lang]:
            b = base_letter(c)
            if c == "ı":
                b = "i"
            if c == "İ":
                b = "I"
            if c == "ə":
                b = "a"
            if c == "Ə":
                b = "A"
            if b != c:
                d[c] = b
        out[lang] = d
    return out


COLLAPSE = _collapse_partners()
DIAC_LANGS = ("tr", "az", "tk", "uz_latn", "uz_cyrl")
IFAM_LANGS = ("tr", "az")
IFAMILY = "iıİI"
_DIGRUN = re.compile(r"-?\d+(?:[.,]\d+)*%?")
LEN_EDGES = [(1, 3, "1-3"), (4, 7, "4-7"), (8, 15, "8-15"), (16, 31, "16-31"), (32, 63, "32-63"), (64, 10 ** 9, "64+")]


def length_bucket(n):
    for lo, hi, name in LEN_EDGES:
        if lo <= n <= hi:
            return name
    return None


@functools.lru_cache(maxsize=None)
def char_class(c):
    """(is_digit, is_punct, is_apostrophe, carries_diacritic) of one reference character."""
    cat = unicodedata.category(c)
    is_dig = cat == "Nd"
    is_apos = c in APOSTROPHE_LIKE
    is_p = cat.startswith("P") and not is_apos
    nfd = unicodedata.normalize("NFD", c)
    diac = len(nfd) > 1 and any(unicodedata.category(x).startswith("M") for x in nfd[1:])
    return is_dig, is_p, is_apos, diac


def _is_p(c):
    return unicodedata.category(c).startswith("P") and c not in APOSTROPHE_LIKE


def _fold_len_equal(ref, hyp, lang):
    fr, fh = fold_lower(ref, lang), fold_lower(hyp, lang)
    if fr == fh:
        return 0, len(fr), True
    return lev_fast(fr, fh), len(fr), False


def crop_features(ref, hyp, lang, full=True, sink=None):
    """Returns (base, letters, extra).
    base: dict feature -> value (sparse); letters: dict feature -> value for the special-letter tallies;
    extra: dict with per-crop values for calibration and quantiles (or None for an empty reference).
    sink (optional): {'conf': Counter, 'letter': dict} collecting the confusion counts (M07): conf[(lang, ref char, output char)]
    for every aligned error ('' for a deletion or an insertion) and letter[(lang, letter)][what it became]."""
    b = collections.defaultdict(float)
    L = collections.defaultdict(float)
    b["n_all"] = 1
    if ref == "":
        b["hr1_den"] = 1
        if hyp != "":
            b["hr1_num"] = 1
            b["hr1_outchars"] = len(hyp)
        if has_loop(ref, hyp):
            b["loop"] = 1
        if other_script(hyp):
            b["other_script_out"] = 1
        return dict(b), {}, None
    rl, hl = len(ref), len(hyp)
    dist, ops = align_ops(ref, hyp)
    s, d, ins = op_counts(ops)
    cer = dist / rl
    b["n_ref"] = 1
    b["ref_len"] = rl
    b["hyp_len"] = hl
    b["dist"] = dist
    b["sub"], b["del"], b["ins"] = s, d, ins
    b["cer_sum"] = cer
    b["cer_cap1_sum"] = min(cer, 1.0)
    exact = hyp == ref
    if exact:
        b["exact"] = 1
    if hyp == "":
        b["empty_out"] = 1
    if rl >= 5:
        b["hr3_den"] = 1
        if hl > rl + max(4, 0.5 * rl) or cer > 1.0:
            b["hr3_num"] = 1
    if has_loop(ref, hyp):
        b["loop"] = 1
    # words
    rt, ht = ref.split(" "), hyp.split(" ") if hyp else []
    b["ref_words"] = len(rt)
    b["hyp_words"] = len(ht)
    if exact:
        wd = 0
    else:
        wdist, wops = align_ops(rt, ht)
        wd = wdist
        ws, wdl, wi = op_counts(wops)
        b["wdel"] = wdl
        # fabricated words (M19): inserted or substituted output words of 3+ letters that no reference word of the crop is close to
        rfold = [fold_lower(w, lang) for w in rt]
        for op, i, j in wops:
            if op in ("S", "I"):
                w = ht[j]
                if len(w) >= 3:
                    fw = fold_lower(w, lang)
                    thr = len(w) // 3
                    if not any(lev_fast(fw, r) <= thr for r in rfold):
                        b["fab_words"] += 1
    b["wdist"] = wd
    # case-insensitive companions (N3)
    dcf, rlcf, eqcf = _fold_len_equal(ref, hyp, lang)
    b["dist_cf"] = dcf
    b["ref_len_cf"] = rlcf
    if eqcf:
        b["exact_cf"] = 1
    # scripts
    if other_script(hyp):
        b["other_script_out"] = 1
    if other_script(ref):
        b["ref_other_script"] = 1
    hts = hyp.split()
    b["hyp_tokens"] = len(hts)
    mh = sum(1 for t in hts if is_mixed_script(t))
    if mh:
        b["mixed_hyp_tokens"] = mh
    b["ref_tokens"] = len(rt)
    mr = sum(1 for t in rt if is_mixed_script(t))
    if mr:
        b["mixed_ref_tokens"] = mr
    extra = {"cer": cer, "dist": dist, "ref_len": rl, "exact": exact, "ed1": dist <= 1}
    if not full:
        return dict(b), {}, extra
    # ---- the published papers' own metrics, for comparison rows only (eval_spec N4 and N5) --------------------------------
    lr, lh = ref.lower(), hyp.lower()
    ml = max(len(lr), len(lh))
    b["n4_cer_sum"] = (lev_fast(lr, lh) / ml) if ml else 0.0                      # HTR-Flor: lower case, longer-string denominator, mean over crops
    lrw, lhw = lr.split(" "), (lh.split(" ") if lh else [])
    mw = max(len(lrw), len(lhw))
    b["n4_wer_sum"] = (lev_fast(lrw, lhw) / mw) if mw else 0.0
    if lr != lh:
        b["n4_ser"] = 1
    if ref != hyp:                                                                  # HKR makers: 100 - fuzz.ratio (difflib), mean over crops, in percent
        b["n5_cerlev_sum"] = 100.0 if (not hyp) else 100.0 - round(100 * difflib.SequenceMatcher(None, ref, hyp).ratio())
    # ---- per-character tallies from the alignment ----------------------------------------------------------------------
    n = rl
    rmap = ["D"] * n
    r2h = [-1] * n
    hmap = ["I"] * hl
    for op, i, j in ops:
        if i >= 0:
            rmap[i] = op
            r2h[i] = j
        if j >= 0:
            hmap[j] = op
    diac_lang = lang in DIAC_LANGS
    ifam_lang = lang in IFAM_LANGS
    for i, c in enumerate(ref):
        dg, pu, ap, dc = char_class(c)
        if dg:
            b["dig_ref"] += 1
        if pu:
            b["punct_ref"] += 1
        if ap:
            b["apos_ref"] += 1
        if diac_lang and dc:
            b["der_ref"] += 1
        if ifam_lang and c in IFAMILY:
            b["ifam_ref"] += 1
            if not dc:
                b["der_ref"] += 1 if diac_lang else 0
    for op, i, j in ops:
        if op == "M":
            continue
        if sink is not None:
            sink["conf"][(lang, ref[i] if i >= 0 else "", hyp[j] if j >= 0 else "")] += 1
        if op == "S":
            rc, hc = ref[i], hyp[j]
            if PARTNER.get(rc) == hc:
                b["homoglyph_sub"] += 1
            case_pair = fold_lower(rc, lang) == fold_lower(hc, lang)
            if case_pair:
                b["case_err"] += 1
            dg, pu, ap, dc = char_class(rc)
            if dg:
                b["dig_miss"] += 1
            if pu:
                b["punct_miss"] += 1
            if ap:
                b["apos_miss"] += 1
            if diac_lang and base_letter(rc) == base_letter(hc):
                b["der_num"] += 1
                if hc == base_letter(rc):
                    b["der_missing"] += 1
                else:
                    b["der_extra"] += 1
            if ifam_lang and rc in IFAMILY and hc in IFAMILY and not case_pair:
                b["ifam_sub"] += 1     # a changed dot; a pure case change (I and dotless i, dotted I and i) is a case error
        elif op == "D":
            dg, pu, ap, dc = char_class(ref[i])
            if dg:
                b["dig_miss"] += 1
            if pu:
                b["punct_miss"] += 1
            if ap:
                b["apos_miss"] += 1
        else:
            hc = hyp[j]
            if unicodedata.category(hc) == "Nd":
                b["dig_ins"] += 1
            if _is_p(hc):
                b["punct_ins"] += 1
            if hc in APOSTROPHE_LIKE:
                b["apos_ins"] += 1
    for m in _DIGRUN.finditer(ref):
        b["digrun_n"] += 1
        if all(rmap[k] == "M" for k in range(m.start(), m.end())):
            b["digrun_ok"] += 1
    # ---- special letters ---------------------------------------------------------------------------------------------
    letters = LETTERS.get(lang)
    if letters:
        part = COLLAPSE.get(lang, {})
        units2 = [u for u in letters if len(u) == 2]
        singles = set(u for u in letters if len(u) == 1)
        # reference side
        i = 0
        while i < n:
            u = None
            if units2 and i + 1 < n and ref[i:i + 2] in units2:
                u = ref[i:i + 2]
                miss = rmap[i] != "M" or rmap[i + 1] != "M"
                coll = rmap[i] == "M" and rmap[i + 1] == "D" and part.get(u) is not None
                step = 2
            elif ref[i] in singles:
                u = ref[i]
                miss = rmap[i] != "M"
                p = part.get(u)
                coll = rmap[i] == "S" and p is not None and hyp[r2h[i]] == p
                step = 1
            if u is not None:
                key = "sl|%s|%s|" % (lang, u)
                L[key + "ref"] += 1
                if miss:
                    L[key + "miss"] += 1
                else:
                    L[key + "tp"] += 1
                if coll:
                    L[key + "collapse"] += 1
                if sink is not None:
                    became = "".join(hyp[r2h[x]] for x in range(i, i + step) if rmap[x] != "D")
                    sink["letter"].setdefault((lang, u), collections.Counter())[became] += 1
                i += step
            else:
                i += 1
        # output side: false alarms
        j = 0
        while j < hl:
            u = None
            if units2 and j + 1 < hl and hyp[j:j + 2] in units2:
                u = hyp[j:j + 2]
                bad = hmap[j] != "M" or hmap[j + 1] != "M"
                step = 2
            elif hyp[j] in singles:
                u = hyp[j]
                bad = hmap[j] != "M"
                step = 1
            if u is not None:
                if bad:
                    L["sl|%s|%s|fp" % (lang, u)] += 1
                j += step
            else:
                j += 1
    return dict(b), dict(L), extra


class Acc:
    """Per-cluster sums of features for every group."""

    def __init__(self, K):
        self.K = K
        self.base = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(float)))
        self.letters = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(float)))
        self.members = collections.defaultdict(set)
        self.n_items = collections.Counter()

    def add(self, groups, k, base, letters):
        for g in groups:
            self.n_items[g] += 1
            self.members[g].add(k)
            gb = self.base[g]
            for f, v in base.items():
                gb[f][k] += v
            if letters and (g == "all" or g.startswith("slice:")):
                gl = self.letters[g]
                for f, v in letters.items():
                    gl[f][k] += v

    def dense(self, g):
        idx = np.array(sorted(self.members[g]), dtype=np.int64)
        pos = {k: i for i, k in enumerate(idx.tolist())}
        feats = {}
        for src in (self.base[g], self.letters.get(g, {})):
            for f, d in src.items():
                col = np.zeros(len(idx))
                for k, v in d.items():
                    col[pos[k]] = v
                feats[f] = col
        return idx, feats


RATIOS = [
    # name, numerator feature, denominator feature, plain name
    ("cer", "dist", "ref_len", "character error rate, pooled"),
    ("sub_rate", "sub", "ref_len", "substituted characters per reference character"),
    ("del_rate", "del", "ref_len", "deleted (omitted) characters per reference character"),
    ("ins_rate", "ins", "ref_len", "inserted characters per reference character (HR2)"),
    ("cer_casefold", "dist_cf", "ref_len_cf", "CER with the language-aware case fold (N3)"),
    ("cer_crop_mean", "cer_sum", "n_ref", "mean of per-crop CER"),
    ("cer_crop_mean_cap1", "cer_cap1_sum", "n_ref", "mean of per-crop CER, each cut at 1.0"),
    ("wer", "wdist", "ref_words", "word error rate, pooled"),
    ("word_omission_rate", "wdel", "ref_words", "reference words aligned to nothing"),
    ("fabricated_word_rate", "fab_words", "ref_words", "output words near no reference word, per reference word"),
    ("exact_match", "exact", "n_ref", "share of crops read perfectly"),
    ("exact_match_casefold", "exact_cf", "n_ref", "share read perfectly ignoring case (N3)"),
    ("empty_output_rate", "empty_out", "n_ref", "share of crops with no output"),
    ("hr3", "hr3_num", "hr3_den", "HR3: overlong or garbage outputs, references of 5+ characters"),
    ("hr4", "loop", "n_all", "HR4: share of outputs with a repetition loop"),
    ("case_error_rate", "case_err", "ref_len", "letters right but in the wrong case"),
    ("digit_miss_rate", "dig_miss", "dig_ref", "reference digits not read right"),
    ("digit_insertion_rate", "dig_ins", "dig_ref", "inserted digits per reference digit"),
    ("digit_run_exact", "digrun_ok", "digrun_n", "digit runs read exactly"),
    ("punct_miss_rate", "punct_miss", "punct_ref", "reference punctuation marks not read right"),
    ("punct_insertion_rate", "punct_ins", "punct_ref", "inserted punctuation marks per reference mark"),
    ("apostrophe_miss_rate", "apos_miss", "apos_ref", "apostrophe-like marks not read right"),
    ("apostrophe_insertion_rate", "apos_ins", "apos_ref", "inserted apostrophe-like marks"),
    ("diacritic_error_rate", "der_num", "der_ref", "accent or dot errors (Latin-script languages, Uzbek Cyrillic Y-breve)"),
    ("diacritic_missing_rate", "der_missing", "der_ref", "accent lost (the bare base letter written)"),
    ("diacritic_extra_rate", "der_extra", "der_ref", "extra or wrong accent"),
    ("ifamily_error_rate", "ifam_sub", "ifam_ref", "i, dotless i, dotted I, I confusions (tr, az)"),
    ("homoglyph_sub_rate", "homoglyph_sub", "ref_len", "substitutions by the look-alike letter of the other script"),
    ("mixed_script_token_rate_out", "mixed_hyp_tokens", "hyp_tokens", "output words that mix Latin and Cyrillic letters"),
    ("mixed_script_token_rate_ref", "mixed_ref_tokens", "ref_tokens", "reference words that mix Latin and Cyrillic letters"),
    ("other_script_rate_out", "other_script_out", "n_all", "outputs with a letter of a third script"),
    ("other_script_rate_ref", "ref_other_script", "n_all", "references with a letter of a third script"),
    ("hr1", "hr1_num", "hr1_den", "HR1: share of clutter-only crops with output"),
    ("hr1_mean_output_chars", "hr1_outchars", "hr1_den", "mean output length on clutter-only crops"),
    ("hit_cap_rate", "hit_cap", "cap_known", "share of outputs that stopped at the token cap"),
    ("n4_htrflor_cer", "n4_cer_sum", "n_ref", "HTR-Flor style CER (lower case, longer-string denominator, mean over crops): comparison with the KOHTD paper only"),
    ("n4_htrflor_wer", "n4_wer_sum", "n_ref", "HTR-Flor style WER on whitespace words: comparison only"),
    ("n4_htrflor_ser", "n4_ser", "n_ref", "share of crops not identical after lower-casing (SER of the KOHTD paper): comparison only"),
    ("n5_hkr_cer_lev_percent", "n5_cerlev_sum", "n_ref", "HKR makers' 'CER Lev' in percent (100 - fuzz.ratio, mean over crops): comparison with HKR papers only"),
]
COMPACT = ("cer", "sub_rate", "del_rate", "ins_rate", "wer", "exact_match", "hr3", "hr4", "empty_output_rate", "hr1", "cer_crop_mean")
ENDPOINT_FEATURES = ["dist", "ref_len", "sub", "del", "ins", "n_ref", "n_all", "exact", "hr3_num", "hr3_den", "loop",
                     "hr1_num", "hr1_den", "empty_out", "wdist", "ref_words", "dist_cf", "ref_len_cf"]


def _letter_virtual(feats):
    """Adds merged-case and per-language letter columns to the feature dict (columns are sums of columns)."""
    names = [f for f in feats if f.startswith("sl|")]
    out = {}
    for f in names:
        _, lang, u, what = f.split("|")
        merged = "slm|%s|%s|%s" % (lang, u.lower() if u != "İ" else "i", what)
        out[merged] = out.get(merged, 0) + feats[f]
        lg = "slg|%s|ALL|%s" % (lang, what)
        out[lg] = out.get(lg, 0) + feats[f]
    return out


def letter_ratios(feats):
    """Per-letter ratios (name, num, den) from the letter columns: miss rate, false-alarm rate, F1, collapse rate."""
    allf = dict(feats)
    allf.update(_letter_virtual(feats))
    keys = sorted(set(f.rsplit("|", 1)[0] for f in allf if f.split("|")[0] in ("sl", "slm", "slg")))
    out = []
    zeros = None
    for k in keys:
        ref = allf.get(k + "|ref")
        if ref is None:
            continue
        z = np.zeros_like(ref)
        miss, fp, tp, co = allf.get(k + "|miss", z), allf.get(k + "|fp", z), allf.get(k + "|tp", z), allf.get(k + "|collapse", z)
        out.append((k + "|miss_rate", miss, ref))
        out.append((k + "|false_alarm_rate", fp, ref))
        out.append((k + "|collapse_rate", co, ref))
        out.append((k + "|f1", 2 * tp, 2 * tp + fp + miss))
    return out


def group_metrics(idx, feats, K, B=stats.B_DEFAULT, seed=stats.SEED_BASE, compact=False, ci=True, letters=True, block=300):
    """Every ratio metric of one group with its 95% cluster-bootstrap interval (S01).
    idx: cluster indices that have members of the group; feats: feature -> per-cluster sums over idx.
    Returns dict name -> {value, lo, hi, num, den}. A ratio whose denominator is below stats.MIN_EVENTS (S05) has no value
    and no interval, only num and den ('k of n'); `rare` is true then."""
    cols = dict(feats)
    zero = np.zeros(len(idx))
    cols.setdefault("cap_known", zero)
    lst = []
    for name, nf, df, _ in RATIOS:
        if compact and name not in COMPACT:
            continue
        if df in cols and cols[df].sum() > 0:
            lst.append((name, cols.get(nf, zero), cols[df]))      # an absent numerator feature means no event: rate 0
    if letters and not compact:
        for name, nm, dn in letter_ratios(feats):
            if dn.sum() > 0:
                lst.append((name, nm, dn))
    out = {}
    todo = []
    for name, nm, dn in lst:
        n_, d_ = float(nm.sum()), float(dn.sum())
        if d_ < stats.MIN_EVENTS:
            out[name] = {"value": None, "lo": None, "hi": None, "num": n_, "den": d_, "rare": True}
        else:
            out[name] = {"value": n_ / d_, "lo": None, "hi": None, "num": n_, "den": d_, "rare": False}
            todo.append((name, nm, dn))
    if ci and len(idx) >= 2:
        for b0 in range(0, len(todo), block):
            part = todo[b0:b0 + block]
            M = np.hstack([np.column_stack([nm for _, nm, _ in part]), np.column_stack([dn for _, _, dn in part])])
            reps = stats.boot_matmul(idx, M, K, B, seed)
            r = len(part)
            for i, (name, _, _) in enumerate(part):
                lo, hi, nv = stats.ratio_ci(reps[:, i], reps[:, r + i])
                out[name]["lo"], out[name]["hi"] = lo, hi
    return out


def macro_metrics(per_lang, cluster_cols, K, B=stats.B_DEFAULT, seed=stats.SEED_BASE, ci=True):
    """Macro CER over languages (stratified cluster bootstrap: clusters are re-drawn within each language) and macro CER over
    clusters (forms, pages or documents). per_lang: lang -> (idx, dist per cluster, ref_len per cluster).
    cluster_cols: (dist per cluster, ref_len per cluster) over all K clusters. Returns dict."""
    out = {}
    langs = sorted(per_lang)
    if langs:
        pts = [per_lang[l][1].sum() / per_lang[l][2].sum() for l in langs if per_lang[l][2].sum() > 0]
        res = {"value": float(np.mean(pts)) if pts else None, "n_languages": len(pts), "lo": None, "hi": None,
               "per_language": {l: float(per_lang[l][1].sum() / per_lang[l][2].sum()) for l in langs if per_lang[l][2].sum() > 0}}
        if ci and pts:
            reps = []
            for li, l in enumerate(langs):
                idx, nm, dn = per_lang[l]
                if dn.sum() <= 0:
                    continue
                Kl = len(idx)
                parts = []
                for c0, Wc in stats.weight_chunks(Kl, B, seed + 1000 + li):
                    with np.errstate(divide="ignore", invalid="ignore"):
                        parts.append((Wc @ nm) / (Wc @ dn))
                reps.append(np.concatenate(parts))
            R = np.vstack(reps)
            m = np.nanmean(R, axis=0)
            m = m[np.isfinite(m)]
            if len(m) >= 20:
                res["lo"], res["hi"] = float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5))
        out["macro_language_cer"] = res
    nm, dn = cluster_cols
    ok = dn > 0
    if ok.any():
        rate = np.where(ok, nm / np.where(ok, dn, 1), 0.0)
        res = {"value": float(rate[ok].mean()), "n_clusters": int(ok.sum()), "lo": None, "hi": None}
        if ci and ok.sum() >= 2:
            # mean of cluster CERs over the drawn clusters: weights count draws of clusters with a non-empty reference
            sel = np.nonzero(ok)[0]
            Kc = len(sel)
            parts = []
            for c0, Wc in stats.weight_chunks(Kc, B, seed + 2000):
                parts.append((Wc @ rate[sel]) / Wc.sum(axis=1))
            m = np.concatenate(parts)
            res["lo"], res["hi"] = float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5))
        out["macro_cluster_cer"] = res
    return out