File size: 16,003 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
"""Scoring of one prediction file against its manifest: the result of score_set() is the content of one score JSON.

Four text profiles are scored (see textnorm.py):
  plain          N0 only, on the TSV output (VLMA PLAIN figure). Full metric suite. This is the decision figure (amendment 3.2 C10).
  pp             the frozen post-processing script of the VLM arms (strip wrappers, NFC, apostrophe folding), applied to ALL arms
                 (clarification G4), on the raw output when a <set>.raw.jsonl exists, else on the TSV output. Compact figures.
  j2strip        J2 strip_wrappers and N0, no folding (the figure of the J2 screen; rule 0.3 literal reading). Compact figures.
  repaired_refs  plain output against references whose mixed-script words were repaired with the frozen look-alike table
                 (rule 0.6(c)). Compact figures.
  n2fold         only for sets with typed rows: plain output and reference with apostrophe-like marks folded to U+02BB (endpoint N
                 of version 3 section 1; no wrapper stripping, no other folding). Compact figures.
Every profile counts crops by cluster (the manifest 'group') and carries 95% cluster-bootstrap intervals (S01, B resamples).
"""
import collections
import math
import re
import time

import numpy as np

from . import analyse, metautil, stats, textnorm
from .lookalike import repair_label

PROFILES = ("plain", "pp", "j2strip", "repaired_refs", "n2fold")
ATTR_COLS = ["page_type", "paper_kind", "paper", "strength", "geo_mode", "capture", "ink", "crop_mode", "region_class", "elastic",
             "licence_class"]
PAIRED_PREFIXES = ("all", "lang:", "slice:", "kind:", "script:", "fontgroup:")
QUANTILE_PREFIXES = ("all", "lang:", "slice:")
EDGES = np.array(list(np.round(np.arange(0.0, 1.0001, 0.05), 2)) + [np.inf])


def parse_float(s):
    if s is None or s == "":
        return None
    try:
        v = float(s)
    except ValueError:
        return None
    return v if math.isfinite(v) else None


def conf_probability(v, kind):
    """Confidence as a probability. kind 'logprob': v is a (mean) natural-log probability."""
    if v is None:
        return None
    if kind == "logprob":
        return math.exp(min(v, 0.0))
    return min(max(v, 0.0), 1.0)


def detect_conf_kind(meta):
    """'logprob' only when the writer's own text says natural-log or log-probability (LINEDET's 'frame maximum probability' stays a probability)."""
    return metautil.conf_kind(meta)


def sidecar_groups(m, script):
    """Group names from a side-file row (GEN's synth_*.meta.tsv). Only columns that exist are used; nothing is renamed."""
    g = []
    fg = m.get("font_group") or ""
    if not fg and m.get("heldout_font") in ("1", "True", "true"):
        fg = "unseen"
    if fg:
        g.append("fontgroup:" + fg)
        g.append("fontgroup:%s|%s" % (fg, script))
    fid = m.get("font_id") or ""
    if fid and "," not in fid:
        g.append("font:" + fid)
    for col in ATTR_COLS:
        v = m.get(col)
        if v not in (None, ""):
            g.append("attr:%s=%s" % (col, v))
    if "effects" in m:
        toks = [t for t in re.split(r"[|,]", m["effects"]) if t]
        if toks:
            for t in toks:
                g.append("effect:" + t)
        else:
            g.append("effect:none")
    return g


def build_items(manifest_rows, preds, raw, sidecar, ktrain, companion_slices, conf_kind):
    items = []
    for r in manifest_rows:
        p = preds.get(r["id"])
        if p is None:
            continue
        lang, script = r["lang"], r["script"]
        hyp_tsv = textnorm.norm(p["hyp"])
        rawtxt = hyp_tsv
        has_raw = False
        if raw is not None and r["id"] in raw and isinstance(raw[r["id"]].get("raw"), str):
            rawtxt = raw[r["id"]]["raw"]
            has_raw = True
        groups = ["all", "lang:" + lang, "script:" + script, "kind:" + r["kind"]]
        if ktrain is not None and r["unit"] == "word" and r["kind"] in ("hand_real", "hand_synth"):
            for nm, val in ktrain.flags(r["text"], lang).items():
                if val:
                    groups.append("slice:" + nm)
        for sname, ids in companion_slices.items():
            if r["id"] in ids:
                groups.append("slice:" + sname)
        if sidecar is not None and r["id"] in sidecar:
            groups.extend(sidecar_groups(sidecar[r["id"]], script))
        conf = parse_float(p.get("conf"))
        conf_min = parse_float(p.get("conf_min"))
        hc = p.get("hit_cap")
        hit_cap = None if hc in (None, "") else (1 if hc in ("1", "True", "true") else 0)
        items.append({"id": r["id"], "ref0": r["text"], "lang": lang, "script": script, "kind": r["kind"], "cluster": r["group"],
                      "hyp_tsv": hyp_tsv, "raw": rawtxt, "has_raw": has_raw, "groups": groups,
                      "conf": conf_probability(conf, conf_kind), "conf_min": conf_probability(conf_min, conf_kind),
                      "hit_cap": hit_cap})
    return items


def analyse_profile(items, refs, hyps, cluster_ids, full, B, seed):
    K = len(cluster_ids)
    cpos = {c: i for i, c in enumerate(cluster_ids)}
    acc = analyse.Acc(K)
    sink = {"conf": collections.Counter(), "letter": {}} if full else None
    q = collections.defaultdict(lambda: collections.defaultdict(list))
    for it, ref, hyp in zip(items, refs, hyps):
        k = cpos[it["cluster"]]
        b, L, extra = analyse.crop_features(ref, hyp, it["lang"], full=full, sink=sink)
        if it["hit_cap"] is not None:
            b["cap_known"] = 1
            if it["hit_cap"]:
                b["hit_cap"] = 1
        groups = list(it["groups"])
        if ref:
            bk = analyse.length_bucket(len(ref))
            if bk:
                groups.append("len:" + bk)
        acc.add(groups, k, b, L)
        if extra is not None:
            for g in groups:
                if g == "all" or g.startswith(QUANTILE_PREFIXES[1:]):
                    d = q[g]
                    d["cl"].append(k)
                    d["cer"].append(extra["cer"])
                    d["dist"].append(extra["dist"])
                    d["reflen"].append(extra["ref_len"])
                    d["exact"].append(1.0 if extra["exact"] else 0.0)
                    d["ed1"].append(1.0 if extra["ed1"] else 0.0)
                    d["conf"].append(it["conf"] if it["conf"] is not None else float("nan"))
                    d["conf_min"].append(it["conf_min"] if it["conf_min"] is not None else float("nan"))
    res = {"groups": {}, "cluster_sums": {}, "cluster_ids": list(cluster_ids)}
    names = sorted(acc.members)
    dense = {}
    for g in names:
        if not full and not (g == "all" or g.startswith(("slice:", "lang:"))):
            continue
        idx, feats = acc.dense(g)
        dense[g] = (idx, feats)
        metrics = analyse.group_metrics(idx, feats, K, B=B, seed=seed, compact=not full, ci=True)
        res["groups"][g] = {"n_items": int(acc.n_items[g]), "n_clusters": int(len(idx)), "metrics": metrics}
        if g == "all" or g.startswith(PAIRED_PREFIXES):
            cs = {}
            for f in analyse.ENDPOINT_FEATURES:
                if f in feats:
                    col = np.zeros(K)
                    col[idx] = feats[f]
                    cs[f] = col
            res["cluster_sums"][g] = cs
    # macro figures
    if "all" in dense:
        per_lang = {}
        for g, (idx, feats) in dense.items():
            if g.startswith("lang:") and "dist" in feats and feats["ref_len"].sum() > 0:
                per_lang[g[5:]] = (idx, feats["dist"], feats["ref_len"])
        allidx, allf = dense["all"]
        if "dist" in allf:
            nm = np.zeros(K)
            dn = np.zeros(K)
            nm[allidx] = allf["dist"]
            dn[allidx] = allf["ref_len"]
            res["macro"] = analyse.macro_metrics(per_lang, (nm, dn), K, B=B, seed=seed)
    if full:
        dist_out, cal_out, conf_out = {}, {}, {}
        for g, d in q.items():
            cer = np.asarray(d["cer"])
            n = len(cer)
            if n == 0:
                continue
            h = np.zeros(len(EDGES) - 1, dtype=np.int64)
            pos = np.minimum(np.searchsorted(EDGES, cer, side="right") - 1, len(EDGES) - 2)
            for p_ in pos:
                h[p_] += 1
            dd = {"n": n, "share_cer0": float(np.mean(cer == 0.0)), "share_cer_gt_0.5": float(np.mean(cer > 0.5)),
                  "share_cer_gt_1.0": float(np.mean(cer > 1.0)), "histogram_bin_width_0.05_last_bin_is_overflow": h.tolist()}
            if n >= stats.MIN_EVENTS:
                dd["quantiles"] = stats.quantiles_ci(cer, d["cl"], K, B=B, seed=seed)
            dist_out[g] = dd
            conf = np.asarray(d["conf"])
            ok = np.isfinite(conf)
            if ok.sum() >= 50 and ok.mean() >= 0.5:
                ex = np.asarray(d["exact"])[ok]
                ed1 = np.asarray(d["ed1"])[ok]
                co = {"conf": stats.calibration_point(conf[ok], ex, ed1, np.asarray(d["dist"])[ok], np.asarray(d["reflen"])[ok]),
                      "n_without_conf": int((~ok).sum())}
                if g == "all":
                    co["conf"]["ci"] = stats.calibration_ci(conf[ok], ex, np.asarray(d["dist"])[ok], np.asarray(d["reflen"])[ok],
                                                            np.asarray(d["cl"])[ok], K, seed=seed)
                cm = np.asarray(d["conf_min"])
                okm = np.isfinite(cm)
                if okm.sum() >= 50:
                    co["conf_min"] = stats.calibration_point(cm[okm], np.asarray(d["exact"])[okm], np.asarray(d["ed1"])[okm],
                                                             np.asarray(d["dist"])[okm], np.asarray(d["reflen"])[okm])
                cal_out[g] = co
        res["distribution"] = dist_out
        if cal_out:
            res["calibration"] = cal_out
        per = collections.defaultdict(list)
        for (lang, rc, hc), n in sink["conf"].items():
            per[lang].append((n, rc, hc))
        res["confusion"] = {
            "top20_off_diagonal_per_language": {lang: [{"ref": rc, "out": hc, "count": n} for n, rc, hc in sorted(v, reverse=True)[:20]]
                                                for lang, v in sorted(per.items())},
            "special_letter_rows": {"%s|%s" % k: dict(v.most_common(12)) for k, v in sorted(sink["letter"].items())},
            "note": "empty 'out' = reference character deleted; empty 'ref' = output character inserted; counts are pooled, no interval",
        }
    return res


def score_set(arm, ckpt, name, entry, manifest_rows, preds, header, ragged, dup, raw, sidecar, ktrain, companion_slices, meta,
              B=stats.B_DEFAULT, seed=stats.SEED_BASE, profiles=PROFILES):
    t0 = time.time()
    conf_kind, conf_def = detect_conf_kind(meta)
    mids = {r["id"] for r in manifest_rows}
    n_extra = sum(1 for i in preds if i not in mids)
    missing = [r["id"] for r in manifest_rows if r["id"] not in preds]
    by_id = {r["id"]: r for r in manifest_rows}
    mism = [i for i, p in preds.items() if i in by_id and textnorm.norm(p["ref"]) != textnorm.norm(by_id[i]["text"])]
    cov = {"manifest_rows": len(manifest_rows), "prediction_rows": len(preds), "scored_rows": len(manifest_rows) - len(missing),
           "missing_ids": len(missing), "extra_ids_ignored": n_extra, "ragged_rows_skipped": ragged, "duplicate_ids": dup,
           "ref_mismatch_rows": len(mism), "complete": len(missing) == 0 and ragged == 0, "tsv_columns": header}
    out = {"coverage": cov, "arm": arm, "checkpoint": ckpt, "evalset": name}
    if mism:
        out["status"] = "ref_mismatch"
        out["ref_mismatch_example_ids"] = mism[:10]
        return out
    # the replication split (random crop-level 70/15/15 of KOHTD, amendment 3.3 D5) has no unseen-word slices: its test crops overlap our training forms
    no_slices = "rand" in name or "rand" in str(entry.get("name", ""))
    items = build_items(manifest_rows, preds, raw, sidecar, None if no_slices else ktrain, {} if no_slices else companion_slices, conf_kind)
    if not items:
        out["status"] = "empty"
        return out
    cluster_ids = sorted({it["cluster"] for it in items})
    out["status"] = "scored"
    out["set_info"] = {"n_scored": len(items), "n_clusters": len(cluster_ids),
                       "cluster_unit": entry.get("group_unit"), "unit": sorted({r["unit"] for r in manifest_rows}),
                       "langs": dict(collections.Counter(it["lang"] for it in items)),
                       "kinds": dict(collections.Counter(it["kind"] for it in items)),
                       "has_sidecar": sidecar is not None, "has_ktrain": ktrain is not None,
                       "slices": sorted({g for it in items for g in it["groups"] if g.startswith("slice:")}),
                       "conf_kind": conf_kind if any(it["conf"] is not None for it in items) else None,
                       "conf_definition": conf_def[:400] if conf_def else None,
                       "cluster_ids_sorted_n": len(cluster_ids)}
    plain_refs = [textnorm.norm(it["ref0"]) for it in items]
    plain_hyps = [it["hyp_tsv"] for it in items]
    prof = {}
    if "plain" in profiles:
        prof["plain"] = analyse_profile(items, plain_refs, plain_hyps, cluster_ids, True, B, seed)
    if "pp" in profiles:
        prof["pp"] = analyse_profile(items, [textnorm.pp_ref(it["ref0"]) for it in items],
                                     [textnorm.pp_output(it["raw"]) for it in items], cluster_ids, False, B, seed)
    if "j2strip" in profiles:
        prof["j2strip"] = analyse_profile(items, plain_refs, [textnorm.j2strip_output(it["raw"]) for it in items], cluster_ids, False,
                                          B, seed)
    if "n2fold" in profiles and any(it["kind"].startswith("typed") for it in items):
        # endpoint N of version 3 section 1: apostrophe-like marks folded to U+02BB in reference and output, no other folding
        prof["n2fold"] = analyse_profile(items, [textnorm.fold_apostrophes(r) for r in plain_refs],
                                         [textnorm.fold_apostrophes(h) for h in plain_hyps], cluster_ids, False, B, seed)
    repairs = []
    if "repaired_refs" in profiles:
        rrefs = []
        for it, r0 in zip(items, plain_refs):
            new, ch = repair_label(r0, it["script"]) if r0 else (r0, [])
            rrefs.append(new)
            if ch:
                repairs.append((it["id"], r0, new))
        if repairs:
            prof["repaired_refs"] = analyse_profile(items, rrefs, plain_hyps, cluster_ids, False, B, seed)
            prof["repaired_refs"]["n_refs_changed"] = len(repairs)
        else:
            prof["repaired_refs"] = {"identical_to_plain": True, "n_refs_changed": 0}
    out["profiles"] = prof
    out["_repairs"] = repairs
    n_strip = n_pp = n_fold = n_rfold = n_raw = 0
    for it in items:
        n_raw += 1 if it["has_raw"] else 0
        plain = textnorm.norm(it["raw"])
        st = textnorm.norm(textnorm.strip_wrappers_pp(it["raw"]))
        if st != plain:
            n_strip += 1
        if textnorm.fold_apostrophes(st) != st:
            n_fold += 1
        if textnorm.pp_output(it["raw"]) != plain:
            n_pp += 1
        if textnorm.pp_ref(it["ref0"]) != textnorm.norm(it["ref0"]):
            n_rfold += 1
    out["postproc"] = {"outputs_changed_by_postproc_total": n_pp, "outputs_changed_by_wrapper_stripping": n_strip,
                       "outputs_with_apostrophes_folded": n_fold, "references_with_apostrophes_folded": n_rfold,
                       "rows_with_raw_output": n_raw, "pp_source": "raw" if n_raw == len(items) else ("tsv" if n_raw == 0 else "mixed"),
                       "rows": len(items)}
    out["timing_seconds"] = round(time.time() - t0, 1)
    out["bootstrap"] = {"B": B, "seed": seed, "interval": "95% percentile, cluster bootstrap, ratio of resampled sums",
                        "label": "single seed, form bootstrap only"}
    return out