File size: 10,426 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
"""Test pass 2: descriptive error analysis of EXISTING predictions (no new prediction) on az_localdoc_test and rukopys_test for M1
(PaddleOCR-VL 1.6 leader, test pass 2) and M2 label-free (greedy and gated LM, amendment 3).

Text: the scorer's N0 profile (r5eval.textnorm.norm) on reference and output; alignment r5eval.align.align_ops (the scorer's alignment).
1. substitutions, deletions, insertions per reference character; share of deletions that fall in the last 30% of the reference.
2. output/reference length ratio: quantiles, share < 0.5 and > 1.5.
3. M1 only, from the stored raw.jsonl: share of rows that hit the 192-token cap without an end token (hit_cap), share that ended on an end
   token with ratio < 0.5; n_new quantiles.
4. CER by reference length bin and by image width bin (PIL header size of the crop file).
5. script: substitutions Latin-only -> Cyrillic-only letter and back; share of output letters in the other script; share of rows whose
   output contains a letter of the other script; per Azerbaijani letter (ə ğ ı ö ü ş ç and capitals): reference count, correct,
   substituted (top outputs), deleted.
6. at most 3 example rows per set (fixed rule: among rows with 15-80 reference characters, the 3 with the largest count of M1's dominant
   error kind on that set; excerpt of 60 characters of reference, M1 and M2 greedy outputs).

usage: tp2_error_analysis.py --root DATA/outputs/r5/testpass2 --out JSON
"""
import argparse
import collections
import csv
import json
import os
import sys
import unicodedata

import numpy as np
from PIL import Image

sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
from r5eval import textnorm  # noqa: E402
from r5eval.align import align_ops  # noqa: E402

csv.field_size_limit(1 << 30)
REG = "/path/to/TURKIC_OCR_DATA/data/processed/r5/evalsets.json"
AZ = set("əğıöüşçƏĞIÖÜŞÇİ")
LEN_BINS = [(1, 15), (16, 31), (32, 47), (48, 63), (64, 10 ** 6)]
W_BINS = [(0, 499), (500, 999), (1000, 1499), (1500, 1999), (2000, 10 ** 6)]


def script(ch):
    if not unicodedata.category(ch).startswith("L"):
        return None
    s = textnorm.char_script_set(ch)
    if s is None:
        return None
    if "Latin" in s and "Cyrillic" not in s:
        return "Latin"
    if "Cyrillic" in s and "Latin" not in s:
        return "Cyrillic"
    return "other"


def read_tsv(p):
    with open(p, encoding="utf-8", newline="") as f:
        return {r["id"]: r for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)}


def analyse(rows, hyps, ref_script, raw=None):
    S = D = I = N = 0
    del_tail = 0
    ratios, per = [], []
    lat2cyr = cyr2lat = 0
    pairs_l2c, pairs_c2l = collections.Counter(), collections.Counter()
    out_letters = out_other = rows_other = 0
    az = collections.defaultdict(lambda: {"ref": 0, "correct": 0, "deleted": 0, "subs": collections.Counter()})
    other = "Cyrillic" if ref_script == "Latin" else "Latin"
    for r in rows:
        ref = textnorm.norm(r["text"])
        hyp = textnorm.norm(hyps.get(r["id"], ""))
        if not ref:
            continue
        dist, ops = align_ops(ref, hyp)
        s = d = i = 0
        for op, a, b in ops:
            if op == "S":
                s += 1
                sa, sb = script(ref[a]), script(hyp[b])
                if sa == "Latin" and sb == "Cyrillic":
                    lat2cyr += 1
                    pairs_l2c[ref[a] + "->" + hyp[b]] += 1
                elif sa == "Cyrillic" and sb == "Latin":
                    cyr2lat += 1
                    pairs_c2l[ref[a] + "->" + hyp[b]] += 1
            elif op == "D":
                d += 1
                if a >= 0.7 * len(ref):
                    del_tail += 1
            elif op == "I":
                i += 1
            if a >= 0 and ref[a] in AZ:
                e = az[ref[a]]
                e["ref"] += 1
                if op == "M":
                    e["correct"] += 1
                elif op == "D":
                    e["deleted"] += 1
                elif op == "S":
                    e["subs"][hyp[b]] += 1
        S, D, I, N = S + s, D + d, I + i, N + len(ref)
        nl = sum(1 for c in hyp if script(c) in ("Latin", "Cyrillic"))
        no = sum(1 for c in hyp if script(c) == other)
        out_letters += nl
        out_other += no
        rows_other += 1 if no else 0
        ratio = len(hyp) / len(ref)
        ratios.append(ratio)
        rec = {"id": r["id"], "ref_len": len(ref), "dist": dist, "s": s, "d": d, "i": i, "ratio": ratio, "width": r.get("_w"),
               "l2c": sum(1 for op, a, b in ops if op == "S" and script(ref[a]) == "Latin" and script(hyp[b]) == "Cyrillic"),
               "c2l": sum(1 for op, a, b in ops if op == "S" and script(ref[a]) == "Cyrillic" and script(hyp[b]) == "Latin")}
        if raw is not None and r["id"] in raw:
            rec["hit_cap"] = bool(raw[r["id"]].get("hit_cap"))
            rec["n_new"] = raw[r["id"]].get("n_new")
        per.append(rec)
    ra = np.asarray(ratios)
    res = {"rows": len(per), "ref_chars": N, "cer": (S + D + I) / N, "sub_per_ref_char": S / N, "del_per_ref_char": D / N,
           "ins_per_ref_char": I / N, "share_of_deletions_in_last_30pct_of_reference": del_tail / D if D else None,
           "ratio_quantiles_p10_p25_p50_p75_p90": [round(float(np.percentile(ra, q)), 3) for q in (10, 25, 50, 75, 90)],
           "share_ratio_below_0_5": float(np.mean(ra < 0.5)), "share_ratio_above_1_5": float(np.mean(ra > 1.5)),
           "subs_latin_to_cyrillic": lat2cyr, "subs_cyrillic_to_latin": cyr2lat,
           "subs_total": S, "share_of_substitutions_latin_to_cyrillic": lat2cyr / S if S else None,
           "swap_pairs_latin_to_cyrillic_top30": pairs_l2c.most_common(30),
           "swap_pairs_cyrillic_to_latin_top30": pairs_c2l.most_common(30),
           "swap_pairs_note": "reference character -> output character, substitutions of the scorer's alignment (N0 text), counts over all rows",
           "share_of_output_letters_in_other_script_than_reference": out_other / out_letters if out_letters else None,
           "share_of_rows_with_any_other_script_letter": rows_other / len(per) if per else None}
    res["cer_by_ref_length"] = {}
    for lo, hi in LEN_BINS:
        sel = [p for p in per if lo <= p["ref_len"] <= hi]
        if sel:
            res["cer_by_ref_length"]["%d-%s" % (lo, hi if hi < 10 ** 6 else "")] = {
                "rows": len(sel), "cer": sum(p["dist"] for p in sel) / sum(p["ref_len"] for p in sel)}
    res["cer_by_image_width_px"] = {}
    for lo, hi in W_BINS:
        sel = [p for p in per if p["width"] is not None and lo <= p["width"] <= hi]
        if sel:
            res["cer_by_image_width_px"]["%d-%s" % (lo, hi if hi < 10 ** 6 else "")] = {
                "rows": len(sel), "cer": sum(p["dist"] for p in sel) / sum(p["ref_len"] for p in sel)}
    if raw is not None:
        hc = [p for p in per if p.get("hit_cap")]
        early = [p for p in per if p.get("hit_cap") is False and p["ratio"] < 0.5]
        nn = [p["n_new"] for p in per if p.get("n_new") is not None]
        res["m1_share_hit_cap_192_without_end_token"] = len(hc) / len(per)
        res["m1_rows_hit_cap"] = len(hc)
        res["m1_share_ended_on_end_token_with_ratio_below_0_5"] = len(early) / len(per)
        res["m1_n_new_quantiles_p50_p90_p99_max"] = [float(np.percentile(nn, q)) for q in (50, 90, 99)] + [max(nn)] if nn else None
    if ref_script == "Latin":
        res["azerbaijani_letters"] = {c: {"ref": e["ref"], "correct": e["correct"], "deleted": e["deleted"],
                                          "substituted": sum(e["subs"].values()), "top_outputs": e["subs"].most_common(4)}
                                      for c, e in sorted(az.items())}
    return res, per


ap = argparse.ArgumentParser()
ap.add_argument("--root", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args()
reg = {e["name"]: e for e in json.load(open(REG, encoding="utf-8"))["sets"]}
out = {"note": "descriptive; existing predictions only; N0 text; scorer alignment", "sets": {}}
for s, rs in (("az_localdoc_test", "Latin"), ("rukopys_test", "Cyrillic")):
    with open(reg[s]["manifest"], encoding="utf-8", newline="") as f:
        rows = list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
    for r in rows:
        with Image.open(r["image"]) as im:
            r["_w"] = im.size[0]
    m1 = read_tsv("%s/preds/m1_%s/paddleocr_vl_1_6/leader/%s.tsv" % (a.root, s, s))
    raw = {}
    for ln in open("%s/preds/m1_%s/paddleocr_vl_1_6/leader/%s.raw.jsonl" % (a.root, s, s), encoding="utf-8"):
        x = json.loads(ln)
        raw[x["id"]] = x
    m2g = read_tsv("%s/preds/m2lf_%s/A1/long2x_labelfree/%s.tsv" % (a.root, s, s))
    m2l = read_tsv("%s/preds/m2lf_%s/A1/long2x_labelfree_lm_gated/%s.tsv" % (a.root, s, s))
    cell = {"image_width_quantiles_p10_p50_p90": [float(np.percentile([r["_w"] for r in rows], q)) for q in (10, 50, 90)]}
    per_m1 = None
    for nm, preds, rw in (("M1", m1, raw), ("M2_labelfree_greedy", m2g, None), ("M2_labelfree_gated_lm", m2l, None)):
        res, per = analyse(rows, {k: v["hyp"] for k, v in preds.items()}, rs, rw)
        cell[nm] = res
        if nm == "M1":
            per_m1 = per
    kinds = {"substitution": cell["M1"]["sub_per_ref_char"], "deletion": cell["M1"]["del_per_ref_char"], "insertion": cell["M1"]["ins_per_ref_char"]}
    dom = max(kinds, key=kinds.get)
    key = {"substitution": "s", "deletion": "d", "insertion": "i"}[dom]
    if s == "az_localdoc_test":
        key = "l2c" if cell["M1"]["subs_latin_to_cyrillic"] > 0.2 * cell["M1"]["sub_per_ref_char"] * cell["M1"]["ref_chars"] else key
    cand = sorted([p for p in per_m1 if 15 <= p["ref_len"] <= 80], key=lambda p: (-p[key], p["id"]))[:3]
    byid = {r["id"]: r for r in rows}
    cell["m1_dominant_error_kind"] = dom
    cell["example_rule"] = "rows with 15-80 reference characters, largest count of '%s' for M1" % key
    cell["examples"] = [{"id": p["id"], "ref": textnorm.norm(byid[p["id"]]["text"])[:60], "M1": textnorm.norm(m1[p["id"]]["hyp"])[:60],
                         "M2_labelfree_greedy": textnorm.norm(m2g[p["id"]]["hyp"])[:60], "width_px": byid[p["id"]]["_w"],
                         "m1_hit_cap": p.get("hit_cap"), "m1_n_new": p.get("n_new")} for p in cand]
    out["sets"][s] = cell
json.dump(out, open(a.out, "w", encoding="utf-8"), indent=1, ensure_ascii=False)
print("written", a.out)