Add zerobench_eval: official standalone scorer (pre-generated wavs in, metrics out)

#2
zerobench_eval/README.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `zerobench_eval` — the official ZeroBench-TTS scorer
2
+
3
+ Scores **pre-generated wavs**. It never loads, downloads, or runs a TTS model —
4
+ you synthesize however you like, this reports the numbers.
5
+
6
+ ```bash
7
+ pip install -r zerobench_eval/requirements.txt
8
+
9
+ python -m zerobench_eval manifest --out manifest.jsonl # what to synthesize
10
+ # ... your synthesis, one wav per row's `output_wav` ...
11
+ python -m zerobench_eval score --wav_dir my_wavs/ --name MyModel
12
+ ```
13
+
14
+ ## Commands
15
+
16
+ | command | what it does |
17
+ |---|---|
18
+ | `manifest` | writes one JSONL row per test item: `text` to say, `ref_audio` to clone, `output_wav` to write |
19
+ | `score` | scores a wav directory → `per_sample.csv`, `summary.json`, `report.txt` |
20
+ | `rescore` | recomputes WER from saved transcripts — no ASR, no GPU, runs in seconds |
21
+
22
+ ## Layout
23
+
24
+ `score` looks for `<wav_dir>/<subset>/<voice_id>.wav`, and also accepts a
25
+ nested `wav/` folder or flat `<subset>_<voice_id>.wav` / `<id>.wav` names. If
26
+ files are missing it tells you which and refuses to report a number, unless you
27
+ pass `--allow_missing` (the summary is then flagged `complete: false`).
28
+
29
+ ## Files
30
+
31
+ | file | contents |
32
+ |---|---|
33
+ | `scorers.py` | WER / SSIM / UTMOS / silence, self-contained |
34
+ | `references.py` | the acceptable-reference expansion — the core of the WER policy |
35
+ | `benchmark.py` | locating benchmark data, matching wavs to items |
36
+ | `report.py` | aggregation and the printed table |
37
+ | `test_references.py` | pins both directions of the WER policy — run it after any edit |
38
+
39
+ ## Notes
40
+
41
+ * **UTMOSv2 is optional.** WER and SSIM work without it; pass `--skip_utmos`, or
42
+ install it with
43
+ `pip install git+https://github.com/sarulab-speech/UTMOSv2.git`.
44
+ * **UTMOS is seeded.** UTMOSv2 ensembles over random crops and is not
45
+ reproducible unseeded (3.05 / 3.03 / 2.96 for the same clip). The RNG is reset
46
+ before every clip so the score is a deterministic function of the audio.
47
+ * **Don't change `--asr`** if you want comparable numbers — the default pair is
48
+ part of the benchmark definition.
49
+
50
+ Full metric definitions and the rationale are in the
51
+ [dataset README](../README.md).
zerobench_eval/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ZeroBench-TTS official scorer.
2
+
3
+ Scores pre-generated wavs — it never loads a TTS model.
4
+
5
+ python -m zerobench_eval manifest --out manifest.jsonl
6
+ python -m zerobench_eval score --wav_dir my_wavs/ --name MyModel
7
+ """
8
+ from .scorers import DEFAULT_ASR, POLICIES, MetricSuite, score_all_policies # noqa: F401
9
+ from .references import best_wer, expand # noqa: F401
10
+
11
+ __version__ = "1.0.0"
zerobench_eval/__main__.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ZeroBench-TTS official scorer — pre-generated wavs in, metrics out.
2
+
3
+ This never loads a TTS model. You synthesize the 137 clips however you like,
4
+ point this at the folder, and it reports WER / SSIM / UTMOS / silence.
5
+
6
+ # 1. what to synthesize
7
+ python -m zerobench_eval manifest --out manifest.jsonl
8
+
9
+ # 2. ... your own synthesis, writing one wav per row's `output_wav` ...
10
+
11
+ # 3. score
12
+ python -m zerobench_eval score --wav_dir my_wavs/ --name MyModel
13
+
14
+ Run ``python -m zerobench_eval <command> --help`` for the full flag list.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ from .benchmark import find_wavs, load_benchmark, resolve_ref_audio
25
+ from .report import format_report, group_report, write_outputs
26
+ from .scorers import DEFAULT_ASR, MetricSuite, load_wav_16k
27
+
28
+ _HERE = Path(__file__).resolve().parent
29
+ REPO_ID = "zeroweight-ai/ZeroBench-TTS"
30
+
31
+
32
+ def _log(msg: str) -> None:
33
+ print(f"[zerobench] {msg}", flush=True)
34
+
35
+
36
+ # ── manifest ──────────────────────────────────────────────────────────────────
37
+
38
+ def cmd_manifest(args: argparse.Namespace) -> None:
39
+ """Emit exactly what a submission must contain: one row per test item, with
40
+ the text to say, the reference clip to clone, and the wav path to write."""
41
+ rows, root = load_benchmark(args.benchmark)
42
+ out = Path(args.out)
43
+ with out.open("w", encoding="utf-8") as f:
44
+ for r in rows:
45
+ f.write(json.dumps({
46
+ "id": r["id"],
47
+ "subset": r["subset"],
48
+ "voice_id": r["voice_id"],
49
+ "text": r["text"],
50
+ "lang": r["lang"],
51
+ "ref_audio": str(resolve_ref_audio(r, root)),
52
+ "ref_text": r.get("ref_text", ""),
53
+ "output_wav": f"{r['subset']}/{r['voice_id']}.wav",
54
+ }, ensure_ascii=False) + "\n")
55
+ _log(f"wrote {len(rows)} rows -> {out}")
56
+ _log("Synthesize `text` with `ref_audio` as the voice prompt, save each to "
57
+ "<your_wav_dir>/<output_wav>, then run: "
58
+ f"python -m zerobench_eval score --wav_dir <your_wav_dir>")
59
+
60
+
61
+ # ── score ─────────────────────────────────────────────────────────────────────
62
+
63
+ def cmd_score(args: argparse.Namespace) -> None:
64
+ rows, root = load_benchmark(args.benchmark)
65
+ if args.subsets:
66
+ rows = [r for r in rows if r["subset"] in set(args.subsets)]
67
+ if not rows:
68
+ raise SystemExit(f"no benchmark items matched (subsets={args.subsets})")
69
+
70
+ wav_dir = Path(args.wav_dir)
71
+ found, missing = find_wavs(rows, wav_dir)
72
+ if missing:
73
+ head = ", ".join(m["id"] for m in missing[:5])
74
+ msg = (f"{len(missing)}/{len(rows)} wavs not found under {wav_dir} "
75
+ f"(e.g. {head}). Expected <wav_dir>/<subset>/<voice_id>.wav — see "
76
+ f"`python -m zerobench_eval manifest`.")
77
+ if not args.allow_missing:
78
+ raise SystemExit(msg + "\nPass --allow_missing to score the rest anyway.")
79
+ _log("WARNING " + msg)
80
+ if not found:
81
+ raise SystemExit("no wavs to score")
82
+ _log(f"scoring {len(found)}/{len(rows)} items from {wav_dir}")
83
+
84
+ metrics = MetricSuite(device=args.device, asr_models=args.asr or DEFAULT_ASR,
85
+ skip_utmos=args.skip_utmos)
86
+
87
+ ref_cache: dict[str, "object"] = {}
88
+ results, t0 = [], __import__("time").time()
89
+ for i, (row, wav_path) in enumerate(found, 1):
90
+ ref_path = str(resolve_ref_audio(row, root))
91
+ if ref_path not in ref_cache:
92
+ ref_cache[ref_path] = load_wav_16k(ref_path)
93
+ scored = metrics.score(
94
+ pred_wav_16k=load_wav_16k(str(wav_path)),
95
+ ref_wav_16k=ref_cache[ref_path],
96
+ text=row["text"], text_normalized=row.get("text_normalized", ""),
97
+ lang=row["lang"],
98
+ )
99
+ results.append({
100
+ "id": row["id"], "subset": row["subset"], "voice_id": row["voice_id"],
101
+ "voice_source": row.get("voice_source", ""), "lang": row["lang"],
102
+ "length_bucket": row.get("length_bucket", ""),
103
+ "text": row["text"], "text_normalized": row.get("text_normalized", ""),
104
+ **scored, "wav_path": str(wav_path),
105
+ })
106
+ if i % 10 == 0 or i == len(found):
107
+ _log(f" {i}/{len(found)} last wer={scored['wer_robust']:.3f} "
108
+ f"(strict {scored['wer_strict']:.3f}) "
109
+ f"[{__import__('time').time() - t0:.0f}s]")
110
+
111
+ name = args.name or wav_dir.name
112
+ out_dir = Path(args.out_dir) if args.out_dir else wav_dir.parent / f"{name}_zerobench"
113
+ summary = write_outputs(out_dir, name, results, rows, args)
114
+ print("\n" + group_report(name, results))
115
+ _log(f"per-sample -> {out_dir / 'per_sample.csv'}")
116
+ _log(f"summary -> {out_dir / 'summary.json'}")
117
+ if summary["n_scored"] < len(rows):
118
+ _log(f"NOTE partial submission: {summary['n_scored']}/{len(rows)} items — "
119
+ "not comparable to full-benchmark numbers.")
120
+
121
+
122
+ # ── rescore ───────────────────────────────────────────────────────────────────
123
+
124
+ def cmd_rescore(args: argparse.Namespace) -> None:
125
+ """Recompute WER from saved transcripts — no ASR, no GPU, seconds not minutes.
126
+
127
+ Transcription does not depend on the reference policy, so editing
128
+ references.py never requires re-running the ASRs.
129
+ """
130
+ import pandas as pd
131
+ from .scorers import score_all_policies
132
+
133
+ for d in args.run_dirs:
134
+ d = Path(d)
135
+ csv_path = d / "per_sample.csv"
136
+ df = pd.read_csv(csv_path)
137
+ cols = [c for c in df.columns if c.startswith("transcript_")]
138
+ if not cols:
139
+ raise SystemExit(f"{csv_path}: no transcript_* columns")
140
+ before = df["wer"].mean()
141
+ new = pd.DataFrame([
142
+ score_all_policies(
143
+ {c[len("transcript_"):]: ("" if pd.isna(r[c]) else str(r[c])) for c in cols},
144
+ str(r.text), "" if pd.isna(r.text_normalized) else str(r.text_normalized))
145
+ for _, r in df.iterrows()], index=df.index)
146
+ for c in new.columns:
147
+ df[c] = new[c]
148
+ df.to_csv(csv_path, index=False, encoding="utf-8")
149
+ print(f"[zerobench] {d.name}: WER {before * 100:.2f}% -> {df['wer'].mean() * 100:.2f}%")
150
+ print(group_report(d.name, df.to_dict("records")))
151
+
152
+
153
+ # ── cli ───────────────────────────────────────────────────────────────────────
154
+
155
+ def main(argv: "list[str] | None" = None) -> None:
156
+ p = argparse.ArgumentParser(
157
+ prog="python -m zerobench_eval", description=__doc__,
158
+ formatter_class=argparse.RawDescriptionHelpFormatter)
159
+ sub = p.add_subparsers(dest="cmd", required=True)
160
+
161
+ def common(sp):
162
+ sp.add_argument("--benchmark", default=None,
163
+ help=f"Benchmark dir or metadata.jsonl. Default: this repo if "
164
+ f"run from a clone, else downloads {REPO_ID} from the Hub.")
165
+
166
+ m = sub.add_parser("manifest", help="write the list of clips to synthesize")
167
+ common(m)
168
+ m.add_argument("--out", default="manifest.jsonl")
169
+ m.set_defaults(func=cmd_manifest)
170
+
171
+ s = sub.add_parser("score", help="score a directory of generated wavs")
172
+ common(s)
173
+ s.add_argument("--wav_dir", required=True,
174
+ help="Directory of generated wavs. Layout <subset>/<voice_id>.wav "
175
+ "(a nested wav/ folder and flat <id>.wav names also work).")
176
+ s.add_argument("--name", default=None, help="Label for this system in the report.")
177
+ s.add_argument("--out_dir", default=None)
178
+ s.add_argument("--subsets", nargs="+", default=None)
179
+ s.add_argument("--device", default="cuda")
180
+ s.add_argument("--asr", action="append", default=None, metavar="MODEL_ID",
181
+ help="Override the ASR set (repeatable). Default is both "
182
+ "openai/whisper-large-v3 and vinai/PhoWhisper-large, min taken. "
183
+ "Changing this makes numbers non-comparable to the leaderboard.")
184
+ s.add_argument("--skip_utmos", action="store_true",
185
+ help="Skip UTMOSv2 (optional dep); UTMOS is reported as NaN.")
186
+ s.add_argument("--allow_missing", action="store_true",
187
+ help="Score a partial submission instead of erroring.")
188
+ s.set_defaults(func=cmd_score)
189
+
190
+ r = sub.add_parser("rescore", help="recompute WER from saved transcripts (no GPU)")
191
+ r.add_argument("run_dirs", nargs="+")
192
+ r.set_defaults(func=cmd_rescore)
193
+
194
+ args = p.parse_args(argv)
195
+ args.func(args)
196
+
197
+
198
+ if __name__ == "__main__":
199
+ sys.exit(main())
zerobench_eval/benchmark.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Locating the benchmark data and matching a submission's wavs to it.
2
+
3
+ Deliberately forgiving about wav layout — the point of the harness is that
4
+ anyone can score their system, not that they guess a folder convention.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+
12
+ REPO_ID = "zeroweight-ai/ZeroBench-TTS"
13
+ _HERE = Path(__file__).resolve().parent
14
+
15
+
16
+ def _local_root() -> "Path | None":
17
+ """metadata.jsonl next to this package (i.e. running from a repo clone)."""
18
+ for cand in (_HERE.parent, _HERE.parent.parent):
19
+ if (cand / "metadata.jsonl").exists():
20
+ return cand
21
+ return None
22
+
23
+
24
+ def load_benchmark(path: "str | None" = None) -> "tuple[list[dict], Path]":
25
+ """Returns (rows, root). ``root`` is what ``ref_audio`` resolves against.
26
+
27
+ Resolution order: explicit ``path`` -> a local clone -> download from the Hub.
28
+ """
29
+ if path:
30
+ p = Path(path)
31
+ if p.is_dir() and (p / "metadata.jsonl").exists():
32
+ meta, root = p / "metadata.jsonl", p
33
+ elif p.is_file():
34
+ meta, root = p, p.parent
35
+ else:
36
+ raise SystemExit(f"--benchmark {path!r}: no metadata.jsonl there")
37
+ else:
38
+ root = _local_root()
39
+ if root is None:
40
+ root = _download()
41
+ meta = root / "metadata.jsonl"
42
+
43
+ rows = [json.loads(l) for l in meta.read_text(encoding="utf-8").splitlines() if l.strip()]
44
+ rows.sort(key=lambda r: (r["subset"], r["voice_id"]))
45
+ return rows, root
46
+
47
+
48
+ def _download() -> Path:
49
+ """Pull metadata.jsonl + the reference audio from the Hub, once."""
50
+ from huggingface_hub import snapshot_download
51
+
52
+ print(f"[zerobench] downloading {REPO_ID} reference data from the Hub ...", flush=True)
53
+ return Path(snapshot_download(
54
+ REPO_ID, repo_type="dataset",
55
+ allow_patterns=["metadata.jsonl", "voices.jsonl", "audio/*"],
56
+ ))
57
+
58
+
59
+ def resolve_ref_audio(row: dict, root: Path) -> Path:
60
+ """Absolute path to a row's reference clip."""
61
+ p = Path(row["ref_audio"])
62
+ return p if p.is_absolute() else (root / p).resolve()
63
+
64
+
65
+ #: Layouts accepted for a submission, tried in order. Each maps a row to a
66
+ #: path fragment under --wav_dir.
67
+ _LAYOUTS = (
68
+ lambda r: f"{r['subset']}/{r['voice_id']}.wav", # the documented one
69
+ lambda r: f"wav/{r['subset']}/{r['voice_id']}.wav", # eval_tts.py's output dir
70
+ lambda r: f"{r['id'].replace('/', '_')}.wav", # flat, id-derived
71
+ lambda r: f"{r['subset']}_{r['voice_id']}.wav", # flat, joined
72
+ lambda r: f"{r['voice_id']}.wav", # flat (single-subset runs)
73
+ )
74
+
75
+
76
+ def find_wavs(rows: list[dict], wav_dir: Path) -> "tuple[list[tuple[dict, Path]], list[dict]]":
77
+ """Match every benchmark row to a wav under ``wav_dir``.
78
+
79
+ Returns (found, missing) where found is [(row, path)]. The flat
80
+ ``<voice_id>.wav`` layout is only consulted when it is unambiguous, since
81
+ the same voice appears in several subsets.
82
+ """
83
+ found: list[tuple[dict, Path]] = []
84
+ missing: list[dict] = []
85
+ multi_subset = len({r["subset"] for r in rows}) > 1
86
+ for row in rows:
87
+ hit = None
88
+ for i, layout in enumerate(_LAYOUTS):
89
+ if multi_subset and i == len(_LAYOUTS) - 1:
90
+ break # ambiguous across subsets
91
+ cand = wav_dir / layout(row)
92
+ if cand.exists():
93
+ hit = cand
94
+ break
95
+ (found.append((row, hit)) if hit else missing.append(row))
96
+ return found, missing
zerobench_eval/references.py ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Acceptable-reference expansion for WER scoring.
2
+
3
+ Why this exists
4
+ ───────────────
5
+ WER punishes the TTS model for every token the ASR writes differently from the
6
+ reference. But for Vietnamese benchmark text, *most* of those differences are
7
+ the ASR's formatting policy, not the model's pronunciation:
8
+
9
+ text "Hạn cuối là ngày 31/12/2025."
10
+ whisper-v3 "Hạn cuối là ngày 31 tháng 12, 2025." ← perfect audio, 0.72 WER
11
+ PhoWhisper "hạn cuối là ngày ba mốt tháng mười hai hai ngàn ..."
12
+
13
+ Both transcripts are *correct readings of correct audio*. A single written
14
+ reference plus a single hand-written spoken reference cannot cover them,
15
+ because the choices compose: an ASR may spell the acronym out while writing the
16
+ numbers as digits, giving a hybrid that matches neither. With k independent
17
+ format decisions there are 2^k acceptable transcripts, and the two-reference
18
+ scheme covers two of them.
19
+
20
+ So instead of enumerating whole sentences, this module declares, per **surface
21
+ span**, every realization a correct reading may produce, and expands the
22
+ cross-product at scoring time. ``zerobench_eval/scorers.py`` then takes the minimum
23
+ WER over that set (see :func:`best_wer`).
24
+
25
+ What is deliberately NOT admitted
26
+ ─────────────────────────────────
27
+ Only *legitimate* readings. Wrong Vietnamese stays wrong:
28
+
29
+ * ``18/04`` → "mười tám tháng **tư**" ✓ / "tháng **không** tư" ✗ (voiced leading zero)
30
+ * ``92.000.000`` → "chín mươi hai **triệu**" ✓ / "chín mươi hai **nghìn nghìn**" ✗
31
+ * ``AB-1234`` → "a bê một hai ba bốn" ✓ / "a bê một hai ba **bê** bốn" ✗
32
+
33
+ Those three are real ZeroTTS defects found in https://github.com/zeroweight-ai/ZeroTTS/blob/main/evaluation/HIGH_WER_ANALYSIS.md,
34
+ and the point of a faithful benchmark is that they keep costing WER.
35
+
36
+ Phonetic renderings of English loanwords ("Slack" → "sờ lếch") are also NOT
37
+ listed. They are an artifact of PhoWhisper specifically, and the eval now runs
38
+ two ASRs and takes the better — ``openai/whisper-large-v3`` writes the Latin
39
+ spelling, so the artifact is handled by ASR agreement rather than by loosening
40
+ the reference set. The one exception is intra-word spacing (``ChatGPT`` vs
41
+ "chat GPT"), which *both* ASRs get "wrong" and which is pure orthography.
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ import re
47
+ from itertools import product
48
+
49
+ # ── Vietnamese number reading ─────────────────────────────────────────────────
50
+ # Each helper returns EVERY standard reading, because the dialect/register
51
+ # switches below are all genuinely used by Vietnamese speakers and all emitted
52
+ # by ASR:
53
+ # 5 in the units slot after a tens word → "lăm" | "năm"
54
+ # 4 in the units slot after "mươi" → "tư" | "bốn"
55
+ # 1 in the units slot after "mươi" → "mốt" | "một"
56
+ # 10^3 → "nghìn" | "ngàn"
57
+ # a <100 group under a larger scale → with or without "không trăm"
58
+ # a <10 remainder after "trăm" → "lẻ" | "linh"
59
+
60
+ _DIGIT = ["không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín"]
61
+
62
+
63
+ def _under_100(n: int, *, after_tens_word: bool = True) -> list[str]:
64
+ """0-99. ``after_tens_word`` False renders 1-9 bare ("năm"), True allows the
65
+ post-"mươi" alternants."""
66
+ if n < 10:
67
+ return [_DIGIT[n]]
68
+ if n < 20:
69
+ unit = n % 10
70
+ if unit == 0:
71
+ return ["mười"]
72
+ if unit == 5:
73
+ return ["mười lăm"]
74
+ return [f"mười {_DIGIT[unit]}"]
75
+ tens, unit = divmod(n, 10)
76
+ head = f"{_DIGIT[tens]} mươi"
77
+ if unit == 0:
78
+ return [head]
79
+ if unit == 1:
80
+ tails = ["mốt", "một"] if after_tens_word else ["một"]
81
+ elif unit == 4:
82
+ tails = ["tư", "bốn"]
83
+ elif unit == 5:
84
+ tails = ["lăm"]
85
+ else:
86
+ tails = [_DIGIT[unit]]
87
+ # Speakers routinely contract away "mươi": "ba mươi mốt" -> "ba mốt",
88
+ # "hai mươi lăm" -> "hai lăm". Both ASRs emit the contracted form.
89
+ return ([f"{head} {t}" for t in tails]
90
+ + [f"{_DIGIT[tens]} {t}" for t in tails])
91
+
92
+
93
+ def _group3(n: int, *, pad_hundreds: bool) -> list[str]:
94
+ """0-999. ``pad_hundreds`` allows the "không trăm ..." form that Vietnamese
95
+ uses for a sub-100 group sitting under a larger scale ("hai nghìn KHÔNG TRĂM
96
+ hai mươi lăm")."""
97
+ if n == 0:
98
+ return [""]
99
+ if n < 100:
100
+ base = _under_100(n)
101
+ if pad_hundreds:
102
+ return base + [f"không trăm {b}" for b in base]
103
+ return base
104
+ hundreds, rest = divmod(n, 100)
105
+ head = f"{_DIGIT[hundreds]} trăm"
106
+ if rest == 0:
107
+ return [head]
108
+ if rest < 10:
109
+ return [f"{head} lẻ {_DIGIT[rest]}", f"{head} linh {_DIGIT[rest]}"]
110
+ return [f"{head} {r}" for r in _under_100(rest)]
111
+
112
+
113
+ _SCALES = ["", "nghìn", "triệu", "tỷ"]
114
+
115
+
116
+ def vi_int(n: int, *, cap: int = 12) -> list[str]:
117
+ """Every standard spoken reading of a non-negative integer."""
118
+ if n == 0:
119
+ return ["không"]
120
+ groups: list[int] = []
121
+ while n:
122
+ n, g = divmod(n, 1000)
123
+ groups.append(g)
124
+ groups.reverse() # most significant first
125
+ n_groups = len(groups)
126
+
127
+ per_group: list[list[str]] = []
128
+ for i, g in enumerate(groups):
129
+ scale = _SCALES[n_groups - 1 - i]
130
+ if g == 0:
131
+ per_group.append([""])
132
+ continue
133
+ # A group is "padded" only when something more significant precedes it.
134
+ readings = _group3(g, pad_hundreds=i > 0)
135
+ if scale == "nghìn":
136
+ per_group.append([f"{r} nghìn" for r in readings] + [f"{r} ngàn" for r in readings])
137
+ elif scale:
138
+ per_group.append([f"{r} {scale}" for r in readings])
139
+ else:
140
+ per_group.append(readings)
141
+
142
+ out: list[str] = []
143
+ for combo in product(*per_group):
144
+ s = " ".join(p for p in combo if p).strip()
145
+ if s and s not in out:
146
+ out.append(s)
147
+ if len(out) >= cap:
148
+ break
149
+ return out
150
+
151
+
152
+ def vi_decimal(written: str) -> list[str]:
153
+ """"3,2" -> ["ba phẩy hai", ...]. Two-digit fractions get both the
154
+ read-as-a-number form ("hai phẩy hai mươi bảy") and the digit-by-digit form
155
+ ("hai phẩy hai bảy"); Vietnamese speakers use both."""
156
+ whole, _, frac = written.replace(".", "").partition(",")
157
+ heads = vi_int(int(whole))
158
+ if not frac:
159
+ return heads
160
+ tails = []
161
+ if len(frac) == 1:
162
+ tails.append(_DIGIT[int(frac)])
163
+ else:
164
+ tails.extend(vi_int(int(frac)))
165
+ tails.append(" ".join(_DIGIT[int(d)] for d in frac))
166
+ return [f"{h} phẩy {t}" for h in heads for t in tails]
167
+
168
+
169
+ def _spoken(written: str) -> list[str]:
170
+ """Spoken readings of a bare numeric literal, decimal or integer."""
171
+ return vi_decimal(written) if "," in written else vi_int(int(written.replace(".", "")))
172
+
173
+
174
+ # ── span builders ─────────────────────────────────────────────────────────────
175
+ # Each returns the acceptable realizations of one surface span, written forms
176
+ # FIRST (index 0 is always the verbatim source text, so `text` itself is always
177
+ # among the references and coordinate descent starts from it).
178
+
179
+ def num(written: str, *, suffix: str = "", extra: list[str] | None = None) -> list[str]:
180
+ """A number, optionally with a trailing unit that is part of the span."""
181
+ tail = f" {suffix}" if suffix else ""
182
+ out = [f"{written}{tail}"] + [f"{s}{tail}" for s in _spoken(written)]
183
+ return _dedup(out + (extra or []))
184
+
185
+
186
+ def pct(written: str) -> list[str]:
187
+ """"3,2%" -> written form, digits + "phần trăm", and the fully spoken form."""
188
+ return _dedup([f"{written}%", f"{written} phần trăm"]
189
+ + [f"{s} phần trăm" for s in _spoken(written)])
190
+
191
+
192
+ def _day(d: int) -> list[str]:
193
+ """Day-of-month. 1 and 2 take the "mùng/mồng" prefix Vietnamese uses for the
194
+ first ten days; 31 contracts to "ba mốt"."""
195
+ base = _under_100(d)
196
+ out = list(base)
197
+ if d <= 10:
198
+ out += [f"mùng {b}" for b in base] + [f"mồng {b}" for b in base]
199
+ return _dedup(out)
200
+
201
+
202
+ def _month(m: int) -> list[str]:
203
+ """Month name. April is "tư" (never "bốn" as a month), January "một"/"giêng"."""
204
+ if m == 1:
205
+ return ["một", "giêng"]
206
+ if m == 4:
207
+ return ["tư"]
208
+ return _under_100(m)
209
+
210
+
211
+ def date(written: str, d: int, m: int, y: int | None = None) -> list[str]:
212
+ """A ``dd/mm[/yyyy]`` span. Covers the written form, the half-spoken forms
213
+ both ASRs actually emit ("31 tháng 12, 2025"), and the fully spoken form
214
+ with and without the "năm" filler before the year.
215
+
216
+ NOTE the leading zero in ``01/07`` / ``18/04`` is a *writing* convention
217
+ only — "tháng không bảy" is not admitted, so voicing it stays an error.
218
+ """
219
+ # The zero-padded numeral is deliberately NOT offered in the half-spoken
220
+ # forms. "18 tháng 04" is ambiguous — whisper-large-v3 writes it both for
221
+ # audio that says "tháng tư" and for audio that says "tháng KHÔNG tư" — and
222
+ # admitting it silently excuses the voiced-leading-zero defect that
223
+ # PhoWhisper transcribes explicitly. The verbatim ``written`` span stays a
224
+ # reference (it is the source text); only the expansion is unpadded.
225
+ parts = written.split("/")
226
+ d_num, m_num = [str(d)], [str(m)]
227
+ days = d_num + _day(d)
228
+ months = m_num + _month(m)
229
+
230
+ out = [written]
231
+ if y is None:
232
+ out += [f"{dd} tháng {mm}" for dd in days for mm in months]
233
+ out += [f"ngày {dd} tháng {mm}" for dd in d_num for mm in m_num]
234
+ return _dedup(out)
235
+ years = _dedup([parts[2]] + vi_int(y))
236
+ out += [f"{dd} tháng {mm} {yy}" for dd in days for mm in months for yy in years]
237
+ out += [f"{dd} tháng {mm} năm {yy}" for dd in days for mm in months for yy in years]
238
+ return _dedup(out)
239
+
240
+
241
+ def time_(written: str, h: int, mi: int = 0) -> list[str]:
242
+ """A ``8h30`` / ``6h`` span, including the "rưỡi" (half past) reading."""
243
+ out = [written, f"{h} giờ" if mi == 0 else f"{h} giờ {mi}", f"{h}:{mi:02d}"]
244
+ hours = _under_100(h)
245
+ if mi == 0:
246
+ out += [f"{hh} giờ" for hh in hours]
247
+ else:
248
+ mins = _under_100(mi)
249
+ out += [f"{hh} giờ {mm}" for hh in hours for mm in mins]
250
+ out += [f"{hh} giờ {mm} phút" for hh in hours for mm in mins]
251
+ if mi == 30:
252
+ out += [f"{hh} giờ rưỡi" for hh in hours] + [f"{hh} rưỡi" for hh in hours]
253
+ return _dedup(out)
254
+
255
+
256
+ def _dedup(items: list[str]) -> list[str]:
257
+ seen, out = set(), []
258
+ for s in items:
259
+ s = re.sub(r"\s+", " ", s).strip()
260
+ if s and s not in seen:
261
+ seen.add(s)
262
+ out.append(s)
263
+ return out
264
+
265
+
266
+ # ── the span table ────────────────────────────────────────────────────────────
267
+ # Keyed by the LITERAL substring as it appears in evaluation/text_pools.py.
268
+ # Matching is longest-key-first and non-overlapping, so "20h" wins over "0h"
269
+ # and "12,7%" over "12%".
270
+ #
271
+ # Curated by hand against the two ASRs' actual output (see
272
+ # https://github.com/zeroweight-ai/ZeroTTS/blob/main/evaluation/HIGH_WER_ANALYSIS.md); every entry is a reading a correct
273
+ # Vietnamese speaker could produce for that span.
274
+
275
+ SPANS: dict[str, list[str]] = {
276
+
277
+ # ── acronyms & brands ─────────────────────────────────────────────────────
278
+ # Vietnamese reads Latin acronyms three ways: keep the letters, spell them
279
+ # with Vietnamese letter names, or substitute the translated full name. All
280
+ # three are correct; which one comes out is the model's choice, not an error.
281
+ "ChatGPT": ["ChatGPT", "chat GPT", "Chát Ji Pi Ti", "chát gi pi ti",
282
+ "chat gi pi ti", "chát ji pi ti", "Chat GPT"],
283
+ "GDP": ["GDP", "gi đi pi", "giê đê pê", "tổng sản phẩm quốc nội"],
284
+ "WHO": ["WHO", "đắp liu hát ô", "vê hát ô", "đấp bờ liu ết chờ ô",
285
+ "Tổ chức Y tế Thế giới"],
286
+ "WTO": ["WTO", "đắp liu ti ô", "vê tê ô", "đấp bờ liu ti ô",
287
+ "Tổ chức Thương mại Thế giới"],
288
+ "UNICEF": ["UNICEF", "U-ni-xép", "u ni xép", "iu ni xép",
289
+ "Quỹ Nhi đồng Liên Hợp Quốc"],
290
+ "UNESCO": ["UNESCO", "U-nét-cô", "u nét cô", "iu nét cô"],
291
+ "ASEAN": ["ASEAN", "A-sê-an", "a sê an", "át xê an", "a si an"],
292
+ "HR": ["HR", "hát rờ", "ét chờ a rờ", "ây át rờ", "nhân sự"],
293
+ "IT": ["IT", "ai ti", "i ti"],
294
+ "QR": ["QR", "kiu a", "quy a", "cu rờ", "ku a"],
295
+ "Internet": ["Internet", "In-tơ-nét", "in tơ nét", "internet"],
296
+ "Gemini": ["Gemini", "Giê mi ni", "gờ mi ni", "gemini"],
297
+ "Copilot": ["Copilot", "Cô pi lốt", "co pi lot", "copilot"],
298
+ "Vientiane": ["Vientiane", "Viêng Chăn", "viêng chăn"],
299
+ "TP. HCM": ["TP. HCM", "TPHCM", "TP HCM", "Thành phố Hồ Chí Minh",
300
+ "thành phố Hồ Chí Minh", "tê pê hát xê em"],
301
+ "SE1": ["SE1", "SE 1", "ét ê một", "ét xê một", "es i một", "SE một"],
302
+
303
+ # Codes: the letters may stay Latin or be spelled with Vietnamese letter
304
+ # names, and the digits may stay digits or be read out — independently.
305
+ "VN-215": ["VN-215", "VN 215", "VN215",
306
+ "vê en 215", "vê en hai một năm", "vê en hai một lăm",
307
+ "vê en hai trăm mười lăm", "vê nờ hai một năm", "vi en hai một năm"],
308
+ "AB-1234": ["AB-1234", "AB 1234", "AB1234",
309
+ "a bê 1234", "a bê một hai ba bốn", "a bê một hai ba tư",
310
+ "ây bi một hai ba bốn", "a bê một nghìn hai trăm ba mươi bốn"],
311
+ "USD/VND": ["USD/VND", "USD VND", "USD trên VND",
312
+ "đô la Mỹ trên đồng Việt Nam", "đô la Mỹ đồng Việt Nam",
313
+ "u ét đê trên vê en đê", "đô la Mỹ VND", "u ét đê vê en đê"],
314
+
315
+ # ── quarters (roman numerals) ─────────────────────────────────────────────
316
+ "quý III": ["quý III", "quý 3", "quý ba"],
317
+ "quý II": ["quý II", "quý 2", "quý hai"],
318
+ "quý I": ["quý I", "quý 1", "quý một"],
319
+
320
+ # ── units & symbols ───────────────────────────────────────────────────────
321
+ "38°C": ["38°C", "38 độ C", "ba mươi tám độ C", "ba mươi tám độ xê",
322
+ "ba mươi tám độ"],
323
+ "5 km": ["5 km", "năm km", "năm ki lô mét", "5 ki lô mét", "năm cây số"],
324
+ "đồng/tháng": ["đồng/tháng", "đồng một tháng", "đồng mỗi tháng", "đồng trên tháng"],
325
+
326
+ # ── dates ─────────────────────────────────────────────────────────────────
327
+ "31/12/2025": date("31/12/2025", 31, 12, 2025),
328
+ "01/07/2024": date("01/07/2024", 1, 7, 2024),
329
+ "2/9/1945": date("2/9/1945", 2, 9, 1945),
330
+ "1/1/2026": date("1/1/2026", 1, 1, 2026),
331
+ "15/8": date("15/8", 15, 8),
332
+ "10/03": date("10/03", 10, 3),
333
+ "25/03": date("25/03", 25, 3),
334
+ "09/10": date("09/10", 9, 10),
335
+ "20/11": date("20/11", 20, 11),
336
+ "30/11": date("30/11", 30, 11),
337
+ "18/04": date("18/04", 18, 4),
338
+ "27/6": date("27/6", 27, 6),
339
+
340
+ # ── times ─────────────────────────────────────────────────────────────────
341
+ "23h59": time_("23h59", 23, 59),
342
+ "20h55": time_("20h55", 20, 55),
343
+ "12h30": time_("12h30", 12, 30),
344
+ "11h20": time_("11h20", 11, 20),
345
+ "8h30": time_("8h30", 8, 30),
346
+ "5h45": time_("5h45", 5, 45),
347
+ "4h50": time_("4h50", 4, 50),
348
+ "20h": time_("20h", 20),
349
+ "18h": time_("18h", 18),
350
+ "9h": time_("9h", 9),
351
+ "6h": time_("6h", 6),
352
+ "4h": time_("4h", 4),
353
+ "0h": time_("0h", 0) + ["không giờ", "12 giờ đêm"],
354
+
355
+ # ── percentages ───────────────────────────────────────────────────────────
356
+ "12,7%": pct("12,7"), "2,27%": pct("2,27"), "0,15%": pct("0,15"),
357
+ "99,4%": pct("99,4"), "0,3%": pct("0,3"), "1,7%": pct("1,7"),
358
+ "4,9%": pct("4,9"), "3,2%": pct("3,2"), "6,8%": pct("6,8"),
359
+ "100%": pct("100"), "90%": pct("90"), "75%": pct("75"), "60%": pct("60"),
360
+ "50%": pct("50"), "40%": pct("40"), "35%": pct("35"), "12%": pct("12"),
361
+ "10%": pct("10"), "6%": pct("6"),
362
+
363
+ # ── quantities (span includes the unit so bare digits stay unambiguous) ───
364
+ "92.000.000 đồng": num("92.000.000", suffix="đồng"),
365
+ "5.310.000 đồng": num("5.310.000", suffix="đồng"),
366
+ "1.100.000 thí sinh": num("1.100.000", suffix="thí sinh"),
367
+ "1.000.000 đồng": num("1.000.000", suffix="đồng"),
368
+ "350.000 giao dịch": num("350.000", suffix="giao dịch"),
369
+ "1.250 tỷ đồng": num("1.250", suffix="tỷ đồng"),
370
+ "9.000 ca": num("9.000", suffix="ca"),
371
+ "500 thí sinh": num("500", suffix="thí sinh"),
372
+ "5,2 triệu": num("5,2", suffix="triệu"),
373
+ "3,5 triệu": num("3,5", suffix="triệu"),
374
+ "7,5 triệu": num("7,5", suffix="triệu"),
375
+ "1,3 triệu": num("1,3", suffix="triệu"),
376
+ "lần thứ 44": ["lần thứ 44", "lần thứ bốn mươi bốn", "lần thứ bốn mươi tư"],
377
+ "10 nước": num("10", suffix="nước"),
378
+ "32 tiếng": num("32", suffix="tiếng"),
379
+ "gấp 3 lần": ["gấp 3 lần", "gấp ba lần"],
380
+ "26 và 27/6": ["26 và 27/6", "26 và 27 tháng 6",
381
+ "hai mươi sáu và hai mươi bảy tháng sáu",
382
+ "hai sáu và hai bảy tháng sáu"],
383
+ "2000 – 2019": ["2000 – 2019", "2000-2019", "2000 đến 2019",
384
+ "hai nghìn đến hai nghìn mười chín",
385
+ "hai nghìn đến hai nghìn không trăm mười chín",
386
+ "hai ngàn đến hai ngàn không trăm mười chín",
387
+ "hai nghìn hai nghìn mười chín"],
388
+
389
+ # ── spelled-out numbers in the SOURCE text ────────────────────────────────
390
+ # The mirror image of the cases above: where text_pools already writes the
391
+ # number as words, whisper-large-v3 transcribes it back as a digit ("thứ
392
+ # Sáu" -> "thứ 6", "chín giờ" -> "9 giờ"). Same audio either way, so
393
+ # admitting both spellings cannot excuse a mispronunciation — it only stops
394
+ # charging WER for the ASR's choice of numerals.
395
+ "thứ Hai": ["thứ Hai", "thứ 2"],
396
+ "thứ Tư": ["thứ Tư", "thứ 4"],
397
+ "thứ Sáu": ["thứ Sáu", "thứ 6"],
398
+ "thứ ba": ["thứ ba", "thứ 3"],
399
+ "chín giờ": ["chín giờ", "9 giờ", "9h"],
400
+ "sáu giờ": ["sáu giờ", "6 giờ", "6h"],
401
+ "mười lăm phút": ["mười lăm phút", "15 phút"],
402
+ "ba mươi phút": ["ba mươi phút", "30 phút"],
403
+ "mười tiếng": ["mười tiếng", "10 tiếng"],
404
+ "một tiếng": ["một tiếng", "1 tiếng"],
405
+ "ba năm": ["ba năm", "3 năm"],
406
+ "sáu tháng": ["sáu tháng", "6 tháng"],
407
+ "hai ngày": ["hai ngày", "2 ngày"],
408
+ "ba ngày": ["ba ngày", "3 ngày"],
409
+ "một tuần": ["một tuần", "1 tuần"],
410
+ "một ngày": ["một ngày", "1 ngày"],
411
+ "năm mươi nghìn": ["năm mươi nghìn", "50.000", "50000", "năm mươi ngàn"],
412
+
413
+ # ── English loanwords whose Vietnamese pronunciation both ASRs re-spell ───
414
+ # Kept deliberately short: two-ASR agreement already covers PhoWhisper's
415
+ # phonetic renderings. These are the ones BOTH ASRs write differently from
416
+ # the source, i.e. genuinely ambiguous orthography rather than ASR weakness.
417
+ "Series": ["Series", "Serie"],
418
+ "series": ["series", "serie"],
419
+ "Team": ["Team", "Tim"],
420
+ # NOTE deliberately absent: "khuyến mãi" / "khuyến mại". That pair differs
421
+ # by TONE (ngã vs nặng), so it is a mispronunciation, not a spelling
422
+ # variant — the model really did say the wrong tone and must be charged.
423
+ # Same rule for every other tone-only pair: never admit one.
424
+
425
+ # ── bare years (always preceded by "năm" in the source text) ──────────────
426
+ "năm 2020": ["năm 2020"] + [f"năm {s}" for s in vi_int(2020)],
427
+ "năm 2024": ["năm 2024"] + [f"năm {s}" for s in vi_int(2024)],
428
+ "năm 2025": ["năm 2025"] + [f"năm {s}" for s in vi_int(2025)],
429
+ "năm 2030": ["năm 2030"] + [f"năm {s}" for s in vi_int(2030)],
430
+ }
431
+
432
+ _SPAN_RE = re.compile("|".join(re.escape(k) for k in sorted(SPANS, key=len, reverse=True)))
433
+
434
+
435
+ # ── expansion & scoring ───────────────────────────────────────────────────────
436
+
437
+ def segment(text: str) -> list[list[str]]:
438
+ """Split ``text`` into alternating fixed and variable segments.
439
+
440
+ Returns a list where each element is the list of acceptable realizations of
441
+ that segment — length 1 for literal text between spans. Element 0 of every
442
+ variable segment is the verbatim source form, so taking index 0 everywhere
443
+ reconstructs ``text``.
444
+ """
445
+ segs: list[list[str]] = []
446
+ pos = 0
447
+ for m in _SPAN_RE.finditer(text):
448
+ if m.start() > pos:
449
+ segs.append([text[pos:m.start()]])
450
+ segs.append(SPANS[m.group(0)])
451
+ pos = m.end()
452
+ if pos < len(text):
453
+ segs.append([text[pos:]])
454
+ return segs or [[text]]
455
+
456
+
457
+ def n_variants(text: str) -> int:
458
+ n = 1
459
+ for s in segment(text):
460
+ n *= len(s)
461
+ return n
462
+
463
+
464
+ def expand(text: str, limit: int = 4096) -> list[str]:
465
+ """Full cross-product of acceptable references, capped. Mostly for
466
+ inspection and tests — :func:`best_wer` avoids materializing it."""
467
+ segs = segment(text)
468
+ out = []
469
+ for combo in product(*segs):
470
+ out.append(re.sub(r"\s+", " ", "".join(combo)).strip())
471
+ if len(out) >= limit:
472
+ break
473
+ return out
474
+
475
+
476
+ _EXHAUSTIVE_MAX = 512
477
+
478
+
479
+ def best_wer(hyp: str, text: str, extra_refs: list[str] | None = None) -> tuple[float, str]:
480
+ """Minimum WER of ``hyp`` over every acceptable reading of ``text``.
481
+
482
+ Returns ``(wer, winning_reference)``.
483
+
484
+ Exhaustive when the cross-product is small. Above that it uses coordinate
485
+ descent: start from the verbatim text, then repeatedly pick the best
486
+ realization of one span holding the others fixed. The spans are disjoint,
487
+ contiguous, and non-interacting under edit distance, so this reaches the
488
+ same optimum as brute force in practice while doing O(spans x variants)
489
+ scorings instead of their product.
490
+ """
491
+ from .scorers import normalize_for_cer, word_error_rate
492
+
493
+ h = normalize_for_cer(hyp)
494
+
495
+ def score(ref: str) -> float:
496
+ return word_error_rate(h, normalize_for_cer(ref))
497
+
498
+ segs = segment(text)
499
+ total = 1
500
+ for s in segs:
501
+ total *= len(s)
502
+
503
+ best_ref, best = None, 2.0
504
+ if total <= _EXHAUSTIVE_MAX:
505
+ for combo in product(*segs):
506
+ ref = "".join(combo)
507
+ w = score(ref)
508
+ if w < best:
509
+ best, best_ref = w, ref
510
+ else:
511
+ idx = [0] * len(segs)
512
+ best_ref = "".join(s[0] for s in segs)
513
+ best = score(best_ref)
514
+ for _ in range(3):
515
+ improved = False
516
+ for i, seg in enumerate(segs):
517
+ if len(seg) == 1:
518
+ continue
519
+ for j in range(len(seg)):
520
+ if j == idx[i]:
521
+ continue
522
+ trial = idx.copy()
523
+ trial[i] = j
524
+ ref = "".join(segs[k][trial[k]] for k in range(len(segs)))
525
+ w = score(ref)
526
+ if w < best - 1e-12:
527
+ best, best_ref, idx, improved = w, ref, trial, True
528
+ if not improved:
529
+ break
530
+
531
+ for ref in extra_refs or []:
532
+ if not ref:
533
+ continue
534
+ w = score(ref)
535
+ if w < best:
536
+ best, best_ref = w, ref
537
+ return min(best, 1.0), (best_ref or text)
zerobench_eval/report.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Aggregation, the printed table, and the files a scoring run leaves behind."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import json
7
+ import statistics
8
+ from collections import OrderedDict
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+
13
+ from .scorers import POLICIES
14
+
15
+ _AGG_KEYS = ("wer", "wer_strict", "wer_norm", "wer_robust", "ssim", "utmos",
16
+ "excess_silence")
17
+
18
+
19
+ def aggregate(rows: list[dict]) -> dict:
20
+ out: dict = {"n": len(rows)}
21
+ for key in _AGG_KEYS:
22
+ vals = [r[key] for r in rows
23
+ if r.get(key) is not None
24
+ and not (isinstance(r[key], float) and np.isnan(r[key]))]
25
+ out[f"{key}_mean"] = float(statistics.mean(vals)) if vals else float("nan")
26
+ out[f"{key}_median"] = float(statistics.median(vals)) if vals else float("nan")
27
+ return out
28
+
29
+
30
+ def _group_by(rows: list[dict], key: str) -> "OrderedDict[str, dict]":
31
+ buckets: "OrderedDict[str, list[dict]]" = OrderedDict()
32
+ for r in rows:
33
+ buckets.setdefault(str(r.get(key, "")), []).append(r)
34
+ return OrderedDict((k, aggregate(v)) for k, v in sorted(buckets.items()))
35
+
36
+
37
+ def format_report(title: str, groups: "dict[str, dict]") -> str:
38
+ """Fixed-width table; one row per group, all three WER policies side by side."""
39
+ w = 118
40
+ lines = ["=" * w, title, "=" * w,
41
+ f"{'group':<22}{'n':>5}{'WER strict':>15}{'WER norm':>15}"
42
+ f"{'WER robust':>15}{'SSIM':>15}{'UTMOS':>15}{'EXCESS-SIL s':>15}",
43
+ f"{'':<22}{'':>5}" + "".join(f"{'mean/median':>15}" for _ in range(6))]
44
+ for name, s in groups.items():
45
+ lines.append(
46
+ f"{name:<22}{s['n']:>5}"
47
+ + "".join(f"{s[f'wer_{p}_mean']:>7.4f}/{s[f'wer_{p}_median']:<7.4f}"
48
+ for p in POLICIES)
49
+ + f"{s['ssim_mean']:>7.4f}/{s['ssim_median']:<7.4f}"
50
+ f"{s['utmos_mean']:>7.4f}/{s['utmos_median']:<7.4f}"
51
+ f"{s['excess_silence_mean']:>7.4f}/{s['excess_silence_median']:<7.4f}")
52
+ lines.append("=" * w)
53
+ return "\n".join(lines)
54
+
55
+
56
+ def group_report(name: str, rows: list[dict]) -> str:
57
+ return "\n".join([
58
+ format_report(f"ZeroBench-TTS — {name}",
59
+ {**_group_by(rows, "subset"), "── overall ──": aggregate(rows)}),
60
+ format_report("by length bucket", _group_by(rows, "length_bucket")),
61
+ format_report("by voice source", _group_by(rows, "voice_source")),
62
+ ])
63
+
64
+
65
+ def write_outputs(out_dir: Path, name: str, results: list[dict],
66
+ all_rows: list[dict], args) -> dict:
67
+ """per_sample.csv + summary.json + report.txt. Returns the summary."""
68
+ out_dir.mkdir(parents=True, exist_ok=True)
69
+
70
+ with (out_dir / "per_sample.csv").open("w", newline="", encoding="utf-8") as f:
71
+ writer = csv.DictWriter(f, fieldnames=list(results[0].keys()))
72
+ writer.writeheader()
73
+ writer.writerows(results)
74
+
75
+ summary = {
76
+ "system": name,
77
+ "benchmark": "zeroweight-ai/ZeroBench-TTS",
78
+ "n_items": len(all_rows),
79
+ "n_scored": len(results),
80
+ "complete": len(results) == len(all_rows),
81
+ "asr_models": list(getattr(args, "asr", None) or
82
+ ("openai/whisper-large-v3", "vinai/PhoWhisper-large")),
83
+ "wer_policies": list(POLICIES),
84
+ "headline_wer_policy": "robust",
85
+ "utmos_scored": not getattr(args, "skip_utmos", False),
86
+ "overall": aggregate(results),
87
+ "by_subset": _group_by(results, "subset"),
88
+ "by_length_bucket": _group_by(results, "length_bucket"),
89
+ "by_voice_source": _group_by(results, "voice_source"),
90
+ }
91
+ (out_dir / "summary.json").write_text(
92
+ json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
93
+ (out_dir / "report.txt").write_text(group_report(name, results) + "\n",
94
+ encoding="utf-8")
95
+ return summary
zerobench_eval/requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ZeroBench-TTS scorer. Install with: pip install -r zerobench_eval/requirements.txt
2
+ torch>=2.0
3
+ torchaudio>=2.0
4
+ transformers>=4.40
5
+ huggingface_hub>=0.23
6
+ soundfile>=0.12
7
+ librosa>=0.10
8
+ numpy>=1.24
9
+ pandas>=2.0
10
+ jiwer>=3.0
11
+
12
+ # UTMOSv2 (naturalness MOS) is OPTIONAL — WER and SSIM work without it.
13
+ # Install it for the full metric set, or pass --skip_utmos:
14
+ # pip install git+https://github.com/sarulab-speech/UTMOSv2.git
zerobench_eval/scorers.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained metric implementations for ZeroBench-TTS.
2
+
3
+ No TTS model is ever loaded here — this module only reads finished wavs and
4
+ scores them:
5
+
6
+ WER two ASRs (openai/whisper-large-v3 + vinai/PhoWhisper-large), min taken,
7
+ against the expanded reference set from ``references.py``
8
+ SSIM cosine similarity of microsoft/wavlm-base-plus-sv x-vectors between
9
+ the generated clip and the benchmark's reference clip
10
+ UTMOS UTMOSv2 naturalness MOS (optional — see ``UTMOSScorer``)
11
+ SIL excess leading / trailing / mid-utterance silence, in seconds
12
+
13
+ Everything loads once per process and is reused across items.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ import unicodedata
20
+
21
+ import numpy as np
22
+
23
+ DEFAULT_ASR = ("openai/whisper-large-v3", "vinai/PhoWhisper-large")
24
+
25
+ #: Reference policies, in reporting order. See ``score_all_policies``.
26
+ POLICIES = ("strict", "norm", "robust")
27
+
28
+
29
+ # ── text normalization + WER ──────────────────────────────────────────────────
30
+
31
+ def normalize_for_cer(text: str) -> str:
32
+ """lowercase, NFC-normalize, strip punctuation, collapse whitespace."""
33
+ text = unicodedata.normalize("NFC", text.lower())
34
+ text = re.sub(r"[^\w\s]", "", text, flags=re.UNICODE)
35
+ text = re.sub(r"\s+", " ", text).strip()
36
+ return text
37
+
38
+
39
+ def _levenshtein_seq(a, b) -> int:
40
+ if a == b:
41
+ return 0
42
+ if not a:
43
+ return len(b)
44
+ if not b:
45
+ return len(a)
46
+ prev = list(range(len(b) + 1))
47
+ for i, ca in enumerate(a, 1):
48
+ cur = [i] + [0] * len(b)
49
+ for j, cb in enumerate(b, 1):
50
+ cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (0 if ca == cb else 1))
51
+ prev = cur
52
+ return prev[-1]
53
+
54
+
55
+ def word_error_rate(hyp: str, ref: str) -> float:
56
+ """WER = edit_distance(words) / len(ref_words), clamped to [0, 1]. Callers
57
+ normalize with :func:`normalize_for_cer` first."""
58
+ ref_words, hyp_words = ref.split(), hyp.split()
59
+ if not ref_words:
60
+ return 0.0 if not hyp_words else 1.0
61
+ try:
62
+ import jiwer
63
+ m = jiwer.process_words(ref, hyp)
64
+ dist = m.substitutions + m.deletions + m.insertions
65
+ except ImportError:
66
+ dist = _levenshtein_seq(hyp_words, ref_words)
67
+ return float(min(max(dist / len(ref_words), 0.0), 1.0))
68
+
69
+
70
+ def score_wer_flat(pred: str, references: list[str]) -> tuple[float, str]:
71
+ """min WER over an explicit list of whole-sentence references."""
72
+ hyp = normalize_for_cer(pred)
73
+ best, best_ref = 1.0, references[0] if references else ""
74
+ for ref in references:
75
+ if not ref:
76
+ continue
77
+ w = word_error_rate(hyp, normalize_for_cer(ref))
78
+ if w < best:
79
+ best, best_ref = w, ref
80
+ return best, best_ref
81
+
82
+
83
+ def score_all_policies(transcripts: dict[str, str], text: str,
84
+ text_normalized: str = "") -> dict:
85
+ """WER of every ASR transcript under all three reference policies.
86
+
87
+ ``transcripts`` maps an ASR label -> its transcript of the same clip.
88
+
89
+ Returns ``wer_<policy>`` (min across ASRs — the reported number),
90
+ ``wer_<policy>_<asr>`` per ASR, and which ASR / reference won ``robust``.
91
+ """
92
+ from .references import best_wer
93
+
94
+ normalized = text_normalized if text_normalized and text_normalized != text else ""
95
+ out: dict = {}
96
+ winners: dict[str, tuple[float, str, str]] = {}
97
+
98
+ for policy in POLICIES:
99
+ per_asr: dict[str, tuple[float, str]] = {}
100
+ for label, hyp in transcripts.items():
101
+ if policy == "strict":
102
+ wer, ref = score_wer_flat(hyp, [text])
103
+ elif policy == "norm":
104
+ wer, ref = score_wer_flat(hyp, [text] + ([normalized] if normalized else []))
105
+ else:
106
+ wer, ref = best_wer(hyp, text, [normalized] if normalized else [])
107
+ per_asr[label] = (wer, ref)
108
+ out[f"wer_{policy}_{label}"] = round(wer, 6)
109
+ label = min(per_asr, key=lambda k: per_asr[k][0])
110
+ wer, ref = per_asr[label]
111
+ out[f"wer_{policy}"] = round(wer, 6)
112
+ winners[policy] = (wer, ref, label)
113
+
114
+ out["wer"] = out["wer_robust"] # headline
115
+ out["wer_matched_reference"] = winners["robust"][1]
116
+ out["wer_matched_asr"] = winners["robust"][2]
117
+ return out
118
+
119
+
120
+ # ── ASR ───────────────────────────────────────────────────────────────────────
121
+
122
+ def asr_label(model_id: str) -> str:
123
+ """Short, column-safe name for an ASR checkpoint."""
124
+ tail = model_id.split("/")[-1].lower()
125
+ if "phowhisper" in tail:
126
+ return "pho"
127
+ if "whisper-large-v3" in tail:
128
+ return "wlv3"
129
+ return re.sub(r"[^0-9a-z]+", "_", tail).strip("_")
130
+
131
+
132
+ class WhisperTranscriber:
133
+ """Any Whisper-family checkpoint from `transformers`."""
134
+
135
+ def __init__(self, model_id: str = "openai/whisper-large-v3", device: str = "cuda"):
136
+ import torch
137
+ from transformers import WhisperForConditionalGeneration, WhisperProcessor
138
+
139
+ self.torch = torch
140
+ self.device = torch.device(device)
141
+ self.processor = WhisperProcessor.from_pretrained(model_id)
142
+ dtype = torch.float16 if self.device.type == "cuda" else torch.float32
143
+ self.model = (WhisperForConditionalGeneration
144
+ .from_pretrained(model_id, torch_dtype=dtype)
145
+ .to(self.device).eval())
146
+ for p in self.model.parameters():
147
+ p.requires_grad = False
148
+
149
+ def transcribe(self, wav_16k: np.ndarray, lang: str | None = "vi") -> str:
150
+ with self.torch.no_grad():
151
+ feats = self.processor(wav_16k, sampling_rate=16_000, return_tensors="pt")
152
+ feats = feats.input_features.to(self.device, dtype=self.model.dtype)
153
+ forced = (self.processor.get_decoder_prompt_ids(language=lang, task="transcribe")
154
+ if lang else None)
155
+ ids = self.model.generate(feats, forced_decoder_ids=forced, max_new_tokens=256)
156
+ return self.processor.batch_decode(ids, skip_special_tokens=True)[0].strip()
157
+
158
+
159
+ # ── speaker similarity ────────────────────────────────────────────────────────
160
+
161
+ class SSIMScorer:
162
+ """Cosine similarity between WavLM-SV x-vectors of generated and reference audio."""
163
+
164
+ def __init__(self, model_id: str = "microsoft/wavlm-base-plus-sv", device: str = "cuda"):
165
+ import torch
166
+ from transformers import WavLMForXVector, Wav2Vec2FeatureExtractor
167
+
168
+ self.torch = torch
169
+ self.device = torch.device(device)
170
+ self.extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_id)
171
+ self.model = WavLMForXVector.from_pretrained(model_id).to(self.device).eval()
172
+ for p in self.model.parameters():
173
+ p.requires_grad = False
174
+
175
+ def embed(self, wav_16k: np.ndarray) -> np.ndarray:
176
+ with self.torch.no_grad():
177
+ inputs = self.extractor(wav_16k, sampling_rate=16_000, return_tensors="pt")
178
+ inputs = {k: v.to(self.device) for k, v in inputs.items()}
179
+ return self.model(**inputs).embeddings.squeeze(0).float().cpu().numpy()
180
+
181
+ def score(self, pred_wav_16k: np.ndarray, ref_wav_16k: np.ndarray) -> float:
182
+ a, b = self.embed(pred_wav_16k), self.embed(ref_wav_16k)
183
+ return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-8))
184
+
185
+
186
+ # ── naturalness ───────────────────────────────────────────────────────────────
187
+
188
+ UTMOS_INSTALL_HINT = (
189
+ "UTMOSv2 is not installed. It is an optional dependency (WER and SSIM work "
190
+ "without it):\n"
191
+ " pip install git+https://github.com/sarulab-speech/UTMOSv2.git\n"
192
+ "Or pass --skip_utmos to report NaN for the UTMOS column."
193
+ )
194
+
195
+
196
+ class UTMOSScorer:
197
+ """UTMOSv2 naturalness MOS. Optional — see :data:`UTMOS_INSTALL_HINT`.
198
+
199
+ UTMOSv2 ensembles over randomly sampled spectrogram crops, so an unseeded
200
+ call is NOT reproducible: scoring one clip three times in a row returns
201
+ e.g. 3.05 / 3.03 / 2.96. A benchmark number that moves between runs is not
202
+ a benchmark number, so the RNG is reset to ``seed`` before every clip. That
203
+ makes UTMOS a deterministic function of the audio, which is what lets two
204
+ people scoring the same wavs get the same figure.
205
+ """
206
+
207
+ def __init__(self, device: str = "cuda", seed: int = 42):
208
+ try:
209
+ import utmosv2
210
+ except ImportError as e: # pragma: no cover
211
+ raise ImportError(UTMOS_INSTALL_HINT) from e
212
+ self.model = utmosv2.create_model(pretrained=True)
213
+ self.seed = seed
214
+
215
+ def _reseed(self) -> None:
216
+ import random
217
+
218
+ import torch
219
+ random.seed(self.seed)
220
+ np.random.seed(self.seed)
221
+ torch.manual_seed(self.seed)
222
+ if torch.cuda.is_available():
223
+ torch.cuda.manual_seed_all(self.seed)
224
+
225
+ def score(self, wav_16k: np.ndarray) -> float:
226
+ self._reseed()
227
+ mos = self.model.predict(data=wav_16k, sr=16_000)
228
+ if hasattr(mos, "item"):
229
+ return float(mos.item())
230
+ if isinstance(mos, (list, np.ndarray)):
231
+ return float(mos[0])
232
+ return float(mos)
233
+
234
+
235
+ # ── silence hygiene (no model) ────────────────────────────────────────────────
236
+
237
+ class SilenceScorer:
238
+ """How much *unwanted* silence a clip carries — long lead-in, long tail, long
239
+ internal pauses.
240
+
241
+ Nothing in WER/SSIM/UTMOS penalizes dead air: an ASR happily transcribes a
242
+ clip that opens with 1.5 s of nothing, the x-vector is unaffected, and UTMOS
243
+ rates the audio quality of silence as fine. ``librosa.effects.split`` gates
244
+ frame energy at ``top_db`` below the clip's own peak; whatever it drops is
245
+ silence. ``excess_silence`` ignores the silence a natural utterance is
246
+ allowed (``max_edge_sec`` per end, ``max_mid_sec`` per internal pause).
247
+ """
248
+
249
+ def __init__(self, top_db: float = 35.0, frame_length: int = 1024,
250
+ hop_length: int = 256, max_edge_sec: float = 0.1,
251
+ max_mid_sec: float = 0.3):
252
+ self.top_db = top_db
253
+ self.frame_length = frame_length
254
+ self.hop_length = hop_length
255
+ self.max_edge_sec = max_edge_sec
256
+ self.max_mid_sec = max_mid_sec
257
+
258
+ def score(self, wav_16k: np.ndarray, sr: int = 16_000) -> dict:
259
+ import librosa
260
+
261
+ wav = np.asarray(wav_16k, dtype=np.float32).reshape(-1)
262
+ dur = len(wav) / sr
263
+ dead = {"lead_silence": dur, "trail_silence": 0.0, "max_mid_silence": 0.0,
264
+ "total_mid_silence": 0.0, "excess_silence": dur,
265
+ "speech_duration": 0.0, "duration": dur}
266
+ if (len(wav) < self.frame_length or not np.any(np.isfinite(wav))
267
+ or float(np.abs(wav).max()) <= 0.0):
268
+ return dead
269
+
270
+ intervals = librosa.effects.split(wav, top_db=self.top_db,
271
+ frame_length=self.frame_length,
272
+ hop_length=self.hop_length)
273
+ if len(intervals) == 0:
274
+ return dead
275
+
276
+ lead = float(intervals[0][0]) / sr
277
+ trail = float(len(wav) - intervals[-1][1]) / sr
278
+ gaps = [float(intervals[k][0] - intervals[k - 1][1]) / sr
279
+ for k in range(1, len(intervals))]
280
+ excess = (max(0.0, lead - self.max_edge_sec) + max(0.0, trail - self.max_edge_sec)
281
+ + sum(max(0.0, g - self.max_mid_sec) for g in gaps))
282
+ return {
283
+ "lead_silence": lead, "trail_silence": trail,
284
+ "max_mid_silence": max(gaps) if gaps else 0.0,
285
+ "total_mid_silence": float(sum(gaps)),
286
+ "excess_silence": excess,
287
+ "speech_duration": float(sum(e - s for s, e in intervals)) / sr,
288
+ "duration": dur,
289
+ }
290
+
291
+
292
+ # ── audio io ──────────────────────────────────────────────────────────────────
293
+
294
+ def load_wav_16k(path: str) -> np.ndarray:
295
+ """Read any wav as mono float32 at 16 kHz."""
296
+ import soundfile as sf
297
+
298
+ wav, sr = sf.read(str(path), dtype="float32", always_2d=False)
299
+ wav = np.asarray(wav, dtype=np.float32)
300
+ if wav.ndim > 1:
301
+ wav = wav.mean(axis=1)
302
+ return resample_to_16k(wav.reshape(-1), sr)
303
+
304
+
305
+ def resample_to_16k(wav: np.ndarray, sr: int) -> np.ndarray:
306
+ if sr == 16_000:
307
+ return wav.astype(np.float32)
308
+ try:
309
+ import torch
310
+ import torchaudio
311
+ t = torch.from_numpy(wav.astype(np.float32)).unsqueeze(0)
312
+ return torchaudio.functional.resample(t, sr, 16_000).squeeze(0).numpy()
313
+ except ImportError:
314
+ import librosa
315
+ return librosa.resample(wav.astype(np.float32), orig_sr=sr, target_sr=16_000)
316
+
317
+
318
+ # ── the bundle ────────────────────────────────────────────────────────────────
319
+
320
+ class MetricSuite:
321
+ """Loads every scorer once. Instantiate a single time per process."""
322
+
323
+ def __init__(self, device: str = "cuda", asr_models=DEFAULT_ASR,
324
+ skip_utmos: bool = False, silence_top_db: float = 35.0,
325
+ silence_max_edge_sec: float = 0.1, silence_max_mid_sec: float = 0.3):
326
+ self.asr: dict[str, WhisperTranscriber] = {}
327
+ for model_id in asr_models:
328
+ print(f"[zerobench] loading ASR {model_id} ...", flush=True)
329
+ self.asr[asr_label(model_id)] = WhisperTranscriber(model_id, device=device)
330
+ print("[zerobench] loading SSIM (WavLM-SV) ...", flush=True)
331
+ self.ssim = SSIMScorer(device=device)
332
+ self.utmos = None
333
+ if not skip_utmos:
334
+ print("[zerobench] loading UTMOS (UTMOSv2) ...", flush=True)
335
+ self.utmos = UTMOSScorer(device=device)
336
+ self.silence = SilenceScorer(top_db=silence_top_db,
337
+ max_edge_sec=silence_max_edge_sec,
338
+ max_mid_sec=silence_max_mid_sec)
339
+
340
+ def score(self, pred_wav_16k: np.ndarray, ref_wav_16k: np.ndarray,
341
+ text: str, text_normalized: str = "", lang: str = "vi") -> dict:
342
+ transcripts = {label: a.transcribe(pred_wav_16k, lang=lang)
343
+ for label, a in self.asr.items()}
344
+ sil = self.silence.score(pred_wav_16k, 16_000)
345
+ return {
346
+ **{f"transcript_{k}": v for k, v in transcripts.items()},
347
+ **score_all_policies(transcripts, text, text_normalized),
348
+ "ssim": self.ssim.score(pred_wav_16k, ref_wav_16k),
349
+ "utmos": self.utmos.score(pred_wav_16k) if self.utmos else float("nan"),
350
+ "excess_silence": sil["excess_silence"],
351
+ "lead_silence": sil["lead_silence"],
352
+ "trail_silence": sil["trail_silence"],
353
+ "max_mid_silence": sil["max_mid_silence"],
354
+ "duration_sec": len(pred_wav_16k) / 16_000,
355
+ }
zerobench_eval/test_references.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression tests for the WER reference policy.
2
+
3
+ pytest zerobench_eval/test_references.py -q
4
+
5
+ Two invariants, and they pull in opposite directions:
6
+
7
+ ARTIFACTS a correct reading transcribed in an unexpected FORMAT must score
8
+ 0.00 — otherwise the benchmark measures the ASR's formatting
9
+ policy instead of the TTS model.
10
+ DEFECTS a genuinely wrong reading must still cost WER — otherwise the
11
+ reference set has been loosened into uselessness.
12
+
13
+ Every case below is a real transcript observed in https://github.com/zeroweight-ai/ZeroTTS/blob/main/evaluation/HIGH_WER_ANALYSIS.md.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import pytest
22
+
23
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
24
+
25
+ from zerobench_eval.references import best_wer, expand, n_variants, vi_int # noqa: E402
26
+
27
+ _TP_HCM = ("Hà Nội, TP. HCM và Đà Nẵng chiếm khoảng 35% GDP cả nước, nhưng chỉ có 12% "
28
+ "diện tích cây xanh trên đầu người đạt chuẩn, theo báo cáo được công bố "
29
+ "ngày 18/04 vừa qua.")
30
+
31
+ # (text, transcript) pairs that MUST score 0.00 — correct audio, unexpected format.
32
+ ARTIFACTS = [
33
+ # intra-word spacing: both ASRs write "chat GPT", the text says "ChatGPT"
34
+ ("Tôi dùng ChatGPT mỗi ngày.", "tôi dùng chat gpt mỗi ngày."),
35
+ # hybrid: acronym kept as letters WHILE numbers are spelled out
36
+ ("GDP quý III tăng 6,8%.", "gdp quý ba tăng sáu phẩy tám phần trăm."),
37
+ # whisper-large-v3 writes dates as digits, PhoWhisper spells them out
38
+ ("Hạn cuối là ngày 31/12/2025.", "Hạn cuối là ngày 31 tháng 12, 2025."),
39
+ ("Hạn cuối là ngày 31/12/2025.",
40
+ "hạn cuối là ngày ba mốt tháng mười hai hai ngàn không trăm hai mươi lăm."),
41
+ # "không trăm" year padding and bốn/tư are both standard
42
+ ("Từ năm 2020 đến năm 2024, số người dùng ví điện tử đã tăng gấp 3 lần.",
43
+ "từ năm hai nghìn không trăm hai mươi đến năm hai nghìn không trăm hai mươi tư "
44
+ "số người dùng ví điện tử đã tăng gấp ba lần."),
45
+ # năm/lăm for the digit 5
46
+ ("Chuyến bay VN-215 khởi hành lúc 6h.",
47
+ "chuyến bay vê en hai một lăm khởi hành lúc sáu giờ."),
48
+ # bare vs "mùng" day, nghìn/ngàn
49
+ ("Ngày 2/9/1945, Chủ tịch Hồ Chí Minh đọc Tuyên ngôn Độc lập tại Hà Nội.",
50
+ "ngày hai tháng chín một ngàn chín trăm bốn mươi lăm chủ tịch hồ chí minh "
51
+ "đọc tuyên ngôn độc lập tại hà nội."),
52
+ # acronym read with Vietnamese letter names instead of translated
53
+ ("Tỷ giá USD/VND đang ở mức cao.", "tỷ giá u ét đê trên vê en đê đang ở mức cao."),
54
+ # roman-numeral quarter spoken, adjacent number left as digits
55
+ ("Doanh thu quý I đạt 1.250 tỷ đồng, tăng 12,7% so với cùng kỳ năm trước.",
56
+ "doanh thu quý một đạt 1.250 tỷ đồng tăng mười hai phẩy bảy phần trăm "
57
+ "so với cùng kỳ năm trước."),
58
+ # every span left in written form == the source text
59
+ (_TP_HCM, _TP_HCM),
60
+ ]
61
+
62
+ # (text, transcript, why) that MUST still cost WER — real mispronunciations.
63
+ DEFECTS = [
64
+ (_TP_HCM,
65
+ "hà nội thành phố hồ chí minh và đà nẵng chiếm khoảng ba mươi lăm phần trăm gdp "
66
+ "cả nước nhưng chỉ có mười hai phần trăm diện tích cây xanh trên đầu người đạt "
67
+ "chuẩn theo báo cáo được công bố ngày mười tám tháng không bốn vừa qua.",
68
+ "voiced the leading zero of 18/04"),
69
+ ("Giá vàng hôm nay là 92.000.000 đồng một lượng.",
70
+ "giá vàng hôm nay là chín mươi hai nghìn nghìn đồng một lượng.",
71
+ "magnitude collapse: 'nghìn nghìn' instead of 'triệu'"),
72
+ ("Mã đơn hàng của bạn là AB-1234; vui lòng giữ lại để tra cứu khi cần.",
73
+ "mã đơn hàng của bạn là ab một hai ba bê bốn vui lòng giữ lại để trả cứu khi cần.",
74
+ "stray letter re-emitted before the final digit"),
75
+ ("WHO vừa đưa ra khuyến cáo mới.",
76
+ "bách thách hắc ô vừa đưa ra khuyến cáo mới.",
77
+ "acronym garbled"),
78
+ # The zero-padded numeral must NOT be an accepted half-spoken reading:
79
+ # "18 tháng 04" is what whisper-large-v3 writes for BOTH "tháng tư" and the
80
+ # defective "tháng không tư", so admitting it would excuse the defect above.
81
+ (_TP_HCM,
82
+ "hà nội thành phố hồ chí minh và đà nẵng chiếm khoảng 35% gdp cả nước nhưng chỉ "
83
+ "có 12% diện tích cây xanh trên đầu người đạt chuẩn theo báo cáo được công bố "
84
+ "ngày 18 tháng 04 vừa qua.",
85
+ "zero-padded month is ambiguous with the voiced-leading-zero defect"),
86
+ ("Tôi sống ở Hà Nội.", "tôi ở hà nội.", "dropped a word"),
87
+ ("Hôm nay trời đẹp quá.", "hôm nay trời xấu quá.", "wrong word"),
88
+ # Tone-only pairs are MISPRONUNCIATIONS, never spelling variants. Vietnamese
89
+ # tone is phonemic, so admitting one of these would blind the benchmark to
90
+ # the most common way a TTS model gets a Vietnamese word wrong.
91
+ ("Chương trình khuyến mãi áp dụng từ 0h ngày 20/11 đến 23h59 ngày 30/11, giảm tới "
92
+ "50% cho đơn hàng trên 1.000.000 đồng, và tặng thêm 10% cho khách thanh toán "
93
+ "bằng thẻ tín dụng.",
94
+ "chương trình khuyến mại áp dụng từ 0h ngày 20 tháng 11 đến 23h59 ngày 30 tháng 11 "
95
+ "giảm tới 50% cho đơn hàng trên 1.000.000 đồng và tặng thêm 10% cho khách thanh "
96
+ "toán bằng thẻ tín dụng.",
97
+ "tone error: khuyến mãi (ngã) -> khuyến mại (nặng)"),
98
+ ("Trưa nay mình order pizza về công ty ăn cho nhanh, khỏi phải xuống dưới sảnh "
99
+ "xếp hàng.",
100
+ "trưa nay mình order pizza về công ty ăn cho nhanh khỏi phải xuống dưới sành "
101
+ "xếp hàng.",
102
+ "tone error: sảnh (hỏi) -> sành (ngang)"),
103
+ ]
104
+
105
+
106
+ @pytest.mark.parametrize("text,hyp", ARTIFACTS)
107
+ def test_format_artifacts_score_zero(text, hyp):
108
+ wer, ref = best_wer(hyp, text)
109
+ assert wer == 0.0, f"format artifact charged {wer:.3f} WER; best reference was {ref!r}"
110
+
111
+
112
+ @pytest.mark.parametrize("text,hyp,why", DEFECTS)
113
+ def test_real_defects_still_cost(text, hyp, why):
114
+ wer, _ = best_wer(hyp, text)
115
+ assert wer > 0.0, f"real defect ({why}) scored 0.00 — reference set is too loose"
116
+
117
+
118
+ def test_source_text_is_always_a_reference():
119
+ """Index 0 of every span is the verbatim written form, so the unmodified
120
+ text must round-trip to 0.00 for every benchmark item."""
121
+ import json
122
+ meta = Path(__file__).resolve().parent.parent / "metadata.jsonl"
123
+ if not meta.exists():
124
+ pytest.skip("benchmark not built locally")
125
+ for line in meta.read_text(encoding="utf-8").splitlines():
126
+ text = json.loads(line)["text"]
127
+ assert best_wer(text, text)[0] == 0.0, text
128
+
129
+
130
+ def test_curated_normalization_is_admitted():
131
+ """text_normalized must be reachable from the span expansion, otherwise the
132
+ hand-curated spoken form and the generated variants disagree."""
133
+ import json
134
+ meta = Path(__file__).resolve().parent.parent / "metadata.jsonl"
135
+ if not meta.exists():
136
+ pytest.skip("benchmark not built locally")
137
+ bad = []
138
+ for line in meta.read_text(encoding="utf-8").splitlines():
139
+ row = json.loads(line)
140
+ if not row.get("has_normalization"):
141
+ continue
142
+ wer, _ = best_wer(row["text_normalized"], row["text"])
143
+ if wer > 0.0:
144
+ bad.append((round(wer, 3), row["text"][:60]))
145
+ assert not bad, f"curated normalization not covered by SPANS: {bad}"
146
+
147
+
148
+ @pytest.mark.parametrize("n,expected", [
149
+ (5, "năm"), (15, "mười lăm"), (21, "hai mươi mốt"), (24, "hai mươi tư"),
150
+ (1945, "một nghìn chín trăm bốn mươi lăm"), (2025, "hai nghìn không trăm hai mươi lăm"),
151
+ (92_000_000, "chín mươi hai triệu"), (1_100_000, "một triệu một trăm nghìn"),
152
+ (5_310_000, "năm triệu ba trăm mười nghìn"), (1_250, "một nghìn hai trăm năm mươi"),
153
+ (350_000, "ba trăm năm mươi nghìn"), (105, "một trăm lẻ năm"),
154
+ ])
155
+ def test_vi_int_produces_the_standard_reading(n, expected):
156
+ assert expected in vi_int(n), f"{n} -> {vi_int(n)}"
157
+
158
+
159
+ def test_variant_count_stays_bounded():
160
+ """Guards against a span edit blowing the cross-product up."""
161
+ assert n_variants(_TP_HCM) < 50_000
162
+ assert len(expand("Tôi dùng ChatGPT mỗi ngày.")) == 7