File size: 5,457 Bytes
e1adf24
 
 
 
 
 
23a3fdf
 
 
e1adf24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23a3fdf
 
e1adf24
 
 
 
 
 
 
23a3fdf
 
 
 
 
 
e1adf24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
evaluate.py — GD-RareName 评测脚本(随数据集发布,只用标准库)。

输入:
  --bench   benchmark/rare_lines.jsonl(或 random_test.jsonl),每行 {"file", "text", "label_source", ...}
  --split   只评哪些划分的行,默认 val,test。rare_lines.jsonl 里有 3,021 行来自训练卷,
            用 real/train 训练过的模型一定不能把它们算进成绩;调参看 val,最终成绩只报 test。
            random_val / random_test 没有 split 字段,不受这个参数影响。
  --pred    预测文件,两种格式都行:
              TSV:file<TAB>prediction(有表头 file 或没有都可以)
              JSONL:{"file": ..., "text": ...}
  --charlist charlist.csv(按字统计用,分类 A=字典外,B=字典内但难认)
输出到屏幕:整行全对率(全部 / 人工核对行 / 含字典外字 / 含字典内难认字)、字符错误率;
--out 给出时另存 per_char.csv(每个目标字的读对率和最常见错读)。

比较前对预测做的清洗:去掉空白和 markdown 符号(# * ` > |),半角括号转全角,去首尾标点。
"""
import argparse
import csv
import difflib
import json
import os
import re
from collections import Counter, defaultdict

PUNCT = ",。、;:!?,.;:!?"


def clean(t):
    t = re.sub(r"<[^>]{1,20}>", "", t or "")
    t = re.sub(r"[#*`>|]", "", t)
    t = re.sub(r"\s+", "", t)
    return t.replace("(", "(").replace(")", ")").strip(PUNCT)


def edit(a, b):
    d = list(range(len(b) + 1))
    for i in range(1, len(a) + 1):
        prev, d[0] = d[0], i
        for j in range(1, len(b) + 1):
            cur = d[j]
            d[j] = min(d[j] + 1, d[j - 1] + 1, prev + (a[i - 1] != b[j - 1]))
            prev = cur
    return d[len(b)]


def load_pred(p):
    out = {}
    with open(p, encoding="utf-8") as f:
        if p.endswith(".jsonl"):
            for l in f:
                r = json.loads(l)
                out[r["file"]] = r.get("text") or r.get("prediction") or ""
        else:
            for l in f:
                parts = l.rstrip("\n").split("\t", 1)
                if len(parts) == 2 and parts[0] != "file":
                    out[parts[0]] = parts[1]
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--bench", required=True)
    ap.add_argument("--pred", required=True)
    ap.add_argument("--charlist", default="charlist.csv")
    ap.add_argument("--out")
    ap.add_argument("--split", default="val,test",
                    help="逗号分隔:train / val / test,或 all;默认 val,test(不含训练卷)")
    args = ap.parse_args()
    cat = {}
    if os.path.exists(args.charlist):
        with open(args.charlist, encoding="utf-8-sig") as f:
            cat = {r["字"]: r["分类"][0] for r in csv.DictReader(f) if r["分类"][0] in "AB"}
    with open(args.bench, encoding="utf-8") as f:
        bench = [json.loads(l) for l in f]
    if args.split != "all":
        keep = set(args.split.split(","))
        bench = [r for r in bench if r.get("split", "") in keep or "split" not in r]
    if any(r.get("split") == "train" for r in bench):
        print("注意:评测里包含训练卷的行;如果模型用 real/train 训练过,这个分数会偏高。")
    print("评测行数:{}(--split {})".format(len(bench), args.split))
    pred = load_pred(args.pred)

    grp = defaultdict(lambda: [0, 0])
    e = n = missing = 0
    ok, wrong = Counter(), defaultdict(Counter)
    for r in bench:
        lab = r["text"]
        if r["file"] not in pred:
            missing += 1
        p = clean(pred.get(r["file"], ""))
        hit = p == lab
        keys = ["全部"]
        if r.get("label_source") == "human":
            keys.append("人工核对行")
        if any(cat.get(c) == "A" for c in lab):
            keys.append("含字典外字")
        elif any(cat.get(c) == "B" for c in lab):
            keys.append("含字典内难认字")
        for k in keys:
            grp[k][0] += hit
            grp[k][1] += 1
        e += edit(lab, p)
        n += max(1, len(lab))
        for op, i1, i2, j1, j2 in difflib.SequenceMatcher(None, lab, p, autojunk=False).get_opcodes():
            for i in range(i1, i2):
                c = lab[i]
                if c not in cat:
                    continue
                if op == "equal":
                    ok[c] += 1
                elif op == "replace" and i2 - i1 == j2 - j1:
                    wrong[c][p[j1 + i - i1]] += 1
                else:
                    wrong[c][p[j1:j2] or "∅"] += 1
    for k in ("全部", "人工核对行", "含字典外字", "含字典内难认字"):
        if grp[k][1]:
            print(f"{k}: {grp[k][0]}/{grp[k][1]} = {grp[k][0] / grp[k][1]:.4f}")
    print(f"CER: {e / n:.4f}   缺失预测: {missing}")
    if args.out:
        with open(args.out, "w", encoding="utf-8-sig", newline="") as f:
            w = csv.writer(f)
            w.writerow(["字", "码位", "分类", "出现次数", "读对率", "最常见错读"])
            for c in sorted(set(ok) | set(wrong), key=lambda c: -(ok[c] + sum(wrong[c].values()))):
                t = ok[c] + sum(wrong[c].values())
                w.writerow([c, f"U+{ord(c):04X}", cat[c], t, f"{ok[c] / t:.3f}",
                            " ".join(f"{g}×{k}" for g, k in wrong[c].most_common(3))])


if __name__ == "__main__":
    main()