Download eval/score.py from idefinity/webfm-eval: direct link, hf CLI and curl.
- Browser
- Download file 9.79 kB
-
https://huggingface.co/datasets/idefinity/webfm-eval/resolve/main/eval/score.py
- Command line
-
hf download hf://datasets/idefinity/webfm-eval/eval/score.py
-
curl -L -o score.py https://huggingface.co/datasets/idefinity/webfm-eval/resolve/main/eval/score.py
9.79 kB
| #!/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()) | |