File size: 9,785 Bytes
bc7b7ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Score Ming TTS candidates on the fixed eval set in eval/sentences.json.

Two numbers are always reported:

- `cer_raw`  — character error rate on the ASR transcript exactly as produced.
- `cer_norm` — same, after traditional->simplified, full-width folding and
  punctuation stripping.

The gap between them is a measurement artefact, not model quality. Whisper
usually emits Chinese in traditional characters; comparing that to simplified
references can add 30-50 points of fake error. Always report both, and always
compare a candidate against a baseline measured in the same run.

Input is JSONL, one row per generated utterance:

  {"id": "s01", "model": "3step", "voice": "v01", "text": "...",
   "hyp_text": "...", "spk_cos": 0.91, "mel_l1": 3.2, "dur_ratio": 1.00}

`text` and `hyp_text` are required; audio metrics are optional and only
aggregated when present.

Usage:
  python3 eval/score.py aggregate --results runs/eval.jsonl --baseline teacher
  python3 eval/score.py selftest
"""
from __future__ import annotations

import argparse
import json
import sys
import unicodedata
from pathlib import Path

HERE = Path(__file__).resolve().parent
PUNCT = set(",。、;:?!“”‘’()《》〈〉【】…—·「」『』,.;:?!!()[]<>\"'`~-_/\\|@#$%^&*+= \t\n\r")


def load_t2s() -> dict[str, str]:
    try:
        import opencc  # type: ignore

        conv = opencc.OpenCC("t2s")

        return {"__opencc__": conv}  # type: ignore[dict-item]
    except Exception:
        pass
    path = HERE / "t2s.json"
    if not path.exists():
        return {}
    return json.loads(path.read_text())["map"]


def to_simplified(text: str, table: dict) -> str:
    conv = table.get("__opencc__")
    if conv is not None:
        return conv.convert(text)
    return "".join(table.get(ch, ch) for ch in text)


def strip_text(text: str) -> str:
    text = unicodedata.normalize("NFKC", text or "")
    out = []
    for ch in text:
        if ch in PUNCT or ch.isspace():
            continue
        if "\u4e00" <= ch <= "\u9fff" or ch.isalnum():
            out.append(ch.lower())
    return "".join(out)


def normalize(text: str, table: dict, simplify: bool) -> str:
    if simplify:
        text = to_simplified(text, table)
    return strip_text(text)


def edit_distance(a: str, b: str) -> int:
    if a == b:
        return 0
    if not a:
        return len(b)
    if not b:
        return len(a)
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(cur[-1] + 1, prev[j] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]


def cer(ref: str, hyp: str) -> float:
    if not ref:
        return 0.0 if not hyp else 1.0
    return edit_distance(ref, hyp) / len(ref)


def score_row(row: dict, table: dict) -> dict:
    ref_raw = strip_text(row["text"])
    hyp_raw = strip_text(row["hyp_text"])
    ref_norm = normalize(row["text"], table, True)
    hyp_norm = normalize(row["hyp_text"], table, True)
    head = min(4, len(ref_norm))
    return {
        "cer_raw": cer(ref_raw, hyp_raw),
        "cer_norm": cer(ref_norm, hyp_norm),
        "cer_prefix": cer(ref_norm[:head], hyp_norm[:head]) if head else 0.0,
        "ref_norm": ref_norm,
        "hyp_norm": hyp_norm,
    }


def mean(values: list[float]) -> float | None:
    values = [v for v in values if v is not None]
    return sum(values) / len(values) if values else None


def aggregate(rows: list[dict], table: dict, baseline: str | None) -> dict:
    sentences = {i["id"]: i for i in json.loads((HERE / "sentences.json").read_text())["items"]}
    scored: list[dict] = []
    for row in rows:
        entry = dict(row)
        entry.update(score_row(row, table))
        bucket = sentences.get(row.get("id", ""), {}).get("bucket", "unknown")
        entry["bucket"] = bucket
        scored.append(entry)

    models: dict[str, dict] = {}
    for entry in scored:
        m = models.setdefault(entry["model"], {"rows": [], "by_bucket": {}, "voices": {}})
        m["rows"].append(entry)
        m["by_bucket"].setdefault(entry["bucket"], []).append(entry)
        m["voices"].setdefault(entry.get("voice", "-"), []).append(entry)

    summary: dict[str, dict] = {}
    for name, m in models.items():
        rows_m = m["rows"]
        summary[name] = {
            "n": len(rows_m),
            "cer_raw": mean([r["cer_raw"] for r in rows_m]),
            "cer_norm": mean([r["cer_norm"] for r in rows_m]),
            "cer_prefix": mean([r["cer_prefix"] for r in rows_m]),
            "spk_cos": mean([r.get("spk_cos") for r in rows_m]),
            "mel_l1": mean([r.get("mel_l1") for r in rows_m]),
            "dur_ratio": mean([r.get("dur_ratio") for r in rows_m]),
            "by_bucket": {
                b: {
                    "n": len(rs),
                    "cer_norm": mean([r["cer_norm"] for r in rs]),
                }
                for b, rs in m["by_bucket"].items()
            },
            "by_voice": {
                v: {
                    "n": len(rs),
                    "cer_norm": mean([r["cer_norm"] for r in rs]),
                    "spk_cos": mean([r.get("spk_cos") for r in rs]),
                }
                for v, rs in m["voices"].items()
            },
            "worst": sorted(rows_m, key=lambda r: -r["cer_norm"])[:5],
        }

    if baseline and baseline in summary:
        base = summary[baseline]
        for name, s in summary.items():
            if name == baseline:
                continue
            s["delta_vs_baseline"] = {
                "cer_norm_pp": None
                if s["cer_norm"] is None or base["cer_norm"] is None
                else (s["cer_norm"] - base["cer_norm"]) * 100,
                "spk_cos": None
                if s["spk_cos"] is None or base["spk_cos"] is None
                else s["spk_cos"] - base["spk_cos"],
            }
    return {"models": summary, "scored": scored}


def print_table(summary: dict) -> None:
    print(f"{'model':<14}{'n':>5}{'cer_raw':>10}{'cer_norm':>10}{'cer_head':>10}{'spk_cos':>10}{'dur':>8}")
    for name, s in sorted(summary.items(), key=lambda kv: (kv[1]["cer_norm"] or 0)):
        def fmt(v, p=4):
            return "-" if v is None else f"{v:.{p}f}"

        print(f"{name:<14}{s['n']:>5}{fmt(s['cer_raw']):>10}{fmt(s['cer_norm']):>10}"
              f"{fmt(s['cer_prefix'], 3):>10}{fmt(s['spk_cos'], 3):>10}{fmt(s['dur_ratio'], 3):>8}")


def cmd_aggregate(args) -> int:
    table = load_t2s()
    rows = []
    with open(args.results) as f:
        for line in f:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    if not rows:
        print("no rows", file=sys.stderr)
        return 1
    result = aggregate(rows, table, args.baseline)
    print_table(result["models"])
    if args.baseline and any("delta_vs_baseline" in s for s in result["models"].values()):
        print(f"\ndelta vs {args.baseline} (negative CER delta is better):")
        for name, s in result["models"].items():
            d = s.get("delta_vs_baseline")
            if d:
                print(f"  {name:<12} cer {'%+.2f' % d['cer_norm_pp']} pp   "
                      f"spk {'%+.3f' % d['spk_cos'] if d['spk_cos'] is not None else '-'}")
    if args.by_bucket:
        print("\ncer_norm by bucket:")
        buckets = sorted({b for s in result["models"].values() for b in s["by_bucket"]})
        print(f"{'model':<14}" + "".join(f"{b:>12}" for b in buckets))
        for name, s in result["models"].items():
            cells = []
            for b in buckets:
                v = s["by_bucket"].get(b, {}).get("cer_norm")
                cells.append(f"{v:.3f}" if v is not None else "-")
            print(f"{name:<14}" + "".join(f"{c:>12}" for c in cells))
    if args.out:
        Path(args.out).parent.mkdir(parents=True, exist_ok=True)
        Path(args.out).write_text(json.dumps(result, ensure_ascii=False, indent=2))
        print(f"\nwrote {args.out}")
    return 0


SELFTEST = [
    ("雨落在窗台上,远处的灯一盏一盏亮起来。", "雨落在窗台上遠處的燈一盞一盞亮起來", 0.0),
    ("风从门缝里进来,带着一点潮湿的木头气味。", "風從門縫裡進來帶著一點潮濕的木頭氣味", 0.0),
    ("她把杯子放在桌边,屋里的光慢慢暗下去。", "他把杯子放在桌邊屋裡的光慢慢按下去", 2 / 17),
]


def cmd_selftest(_args) -> int:
    table = load_t2s()
    backend = "opencc" if "__opencc__" in table else "bundled table"
    print(f"t2s backend: {backend}\n")
    ok = True
    for ref, hyp, expect in SELFTEST:
        s = score_row({"text": ref, "hyp_text": hyp}, table)
        flag = "ok" if abs(s["cer_norm"] - expect) < 0.02 else "MISMATCH"
        if flag != "ok":
            ok = False
        print(f"raw {s['cer_raw']:.3f} -> norm {s['cer_norm']:.3f}  "
              f"(expect {expect:.3f})  {flag}\n  {s['hyp_norm']}")
    if not ok:
        print("\nselftest failed", file=sys.stderr)
        return 1
    print("\nselftest ok")
    return 0


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    a = sub.add_parser("aggregate")
    a.add_argument("--results", required=True)
    a.add_argument("--baseline", default=None)
    a.add_argument("--out", default=None)
    a.add_argument("--by-bucket", action="store_true")
    a.set_defaults(func=cmd_aggregate)
    s = sub.add_parser("selftest")
    s.set_defaults(func=cmd_selftest)
    args = ap.parse_args()
    return args.func(args)


if __name__ == "__main__":
    raise SystemExit(main())