File size: 6,616 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
"""ERRAN (R5) task 2: shares of the visual causes per arm, with Wilson 95% intervals, from the viewer's judgements.

Input (cluster only, OUT/private/): sheets/index.jsonl (crop number -> id, which arm samples hold it, stratum flag) and
visual_judgements.tsv with columns n, cause, overrides (arm=cause;...), written by the viewer after looking at each crop next to
its reference and the outputs. One primary cause per (crop, arm): the crop's cause unless an override names the arm.
Output: OUT/visual_causes_counts.json with counts and shares only (no ids, no text).
"""
import argparse
import collections
import json
import math
import os
import sys
import time

CAUSES = {
    "a": "the reference label looks wrong or incomplete",
    "b": "the crop cuts off letters, or holds parts of other words",
    "c": "handwriting genuinely ambiguous or illegible to a careful reader",
    "d": "a correction or strike-through in the ink",
    "e": "ruled lines, stains or noise over the ink",
    "f": "an unusual letter form for a known letter",
    "g": "a clear, legible image that the model misread (model fault)",
    "h": "other",
}
ARMS = ["hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "A1 long_lm_gated"]


def wilson(k, n, z=1.959964):
    if n == 0:
        return None, None
    p = k / n
    den = 1 + z * z / n
    c = (p + z * z / (2 * n)) / den
    h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / den
    return max(0.0, c - h), min(1.0, c + h)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", required=True)
    args = ap.parse_args()
    priv = os.path.join(args.out, "private")
    idx = {}
    with open(os.path.join(priv, "sheets", "index.jsonl"), encoding="utf-8") as f:
        for line in f:
            r = json.loads(line)
            idx[r["n"]] = r
    jud = {}
    notes = {}
    with open(os.path.join(priv, "visual_judgements.tsv"), encoding="utf-8") as f:
        hdr = f.readline().rstrip("\n").split("\t")
        for line in f:
            p = dict(zip(hdr, line.rstrip("\n").split("\t")))
            if not p.get("n"):
                continue
            ov = {}
            for t in (p.get("overrides") or "").split(";"):
                if "=" in t:
                    a, c = t.split("=", 1)
                    ov[a.strip()] = c.strip()
            jud[int(p["n"])] = (p["cause"].strip(), ov)
            alias = {"punct": "punct-missing-in-ref", "space": "space-missing-in-ref"}
            notes[int(p["n"])] = [alias.get(t.strip(), t.strip()) for t in (p.get("note") or "").replace("+", ";").split(";") if t.strip()]
    missing = sorted(n for n in idx if n not in jud)
    bad = sorted(n for n, (c, ov) in jud.items() if c not in CAUSES or any(v not in CAUSES for v in ov.values()))
    per_arm = {}
    for a in ARMS:
        cnt = collections.Counter()
        n = 0
        for k, r in idx.items():
            if a in r["in_sample_of"] and k in jud:
                c, ov = jud[k]
                cnt[ov.get(a, c)] += 1
                n += 1
        per_arm[a] = {"n_viewed": n, "causes": {}}
        for c in CAUSES:
            lo, hi = wilson(cnt[c], n)
            per_arm[a]["causes"][c] = {"cause": CAUSES[c], "count": cnt[c], "share": cnt[c] / n if n else None, "wilson95": [lo, hi]}
        sub = collections.Counter()
        for k, r in idx.items():
            if a in r["in_sample_of"] and k in jud:
                c, ov = jud[k]
                if a in ov:
                    sub["%s|arm-specific-override" % ov[a]] += 1
                    continue
                for t in notes.get(k, []):
                    sub["%s|%s" % (c, t)] += 1
        per_arm[a]["viewer_tags_within_causes"] = dict(sorted(sub.items()))
    # every-arm-wrong stratum: crop-level cause (overrides ignored), and per-arm for those in it
    cnt = collections.Counter()
    n = 0
    for k, r in idx.items():
        if r["in_allwrong_stratum"] and k in jud:
            cnt[jud[k][0]] += 1
            n += 1
    strat = {"n_viewed": n, "causes": {c: {"cause": CAUSES[c], "count": cnt[c], "share": cnt[c] / n if n else None,
                                           "wilson95": list(wilson(cnt[c], n))} for c in CAUSES}}
    sub = collections.Counter()
    for k, r in idx.items():
        if r["in_allwrong_stratum"] and k in jud:
            for t in notes.get(k, []):
                sub["%s|%s" % (jud[k][0], t)] += 1
    strat["viewer_tags_within_causes"] = dict(sorted(sub.items()))
    strat["note"] = "crop-level cause (per-arm overrides ignored); these crops are wrong for all 15 arms of the task-1 list"
    n_override = sum(1 for c, ov in jud.values() if ov)
    design = json.load(open(os.path.join(priv, "sample_design.json"), encoding="utf-8"))
    out = {"generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "validation_only": True, "set": "V1 (KOHTD validation screen set)",
           "design": design, "causes": CAUSES, "per_arm_uniform_sample": per_arm, "every_arm_wrong_stratum": strat,
           "crops_viewed": len(jud), "crops_in_index": len(idx), "crops_not_judged": len(missing), "invalid_codes": len(bad),
           "crops_with_arm_specific_override": n_override,
           "viewer_tags": {"case": "case-only mismatch between reference and what the image shows",
                           "punct-missing-in-ref": "a punctuation mark visible in the image is missing from the reference",
                           "space-conv": "spacing next to punctuation differs between reference and image (KOHTD labels often put a space before , . : ) -)",
                           "language-prior": "the output replaced what is written with a more frequent real word or spelling",
                           "spelling-normalised-in-ref": "the writer misspelled, the reference gives the correct spelling",
                           "wrong-script-output": "the output uses letters of the other script",
                           "other tags": "short free-text notes of the viewer (faint, lowres, cut-right, neighbour-comma, strike, ...)"},
           "viewer": "stage ERRAN, one viewer, no second rater: agreement unknown",
           "judgement_file_on_cluster": os.path.join(priv, "visual_judgements.tsv"),
           "privacy": "counts and categories only; crop ids, images and label text stay on the cluster under OUT/private/"}
    json.dump(out, open(os.path.join(args.out, "visual_causes_counts.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    print(json.dumps({"missing": len(missing), "bad": len(bad), "n": len(jud)}))


if __name__ == "__main__":
    sys.exit(main())