| """ZeroBench-TTS official scorer — pre-generated wavs in, metrics out. |
| |
| This never loads a TTS model. You synthesize the 137 clips however you like, |
| point this at the folder, and it reports WER / SSIM / UTMOS / silence. |
| |
| # 1. what to synthesize |
| python -m zerobench_eval manifest --out manifest.jsonl |
| |
| # 2. ... your own synthesis, writing one wav per row's `output_wav` ... |
| |
| # 3. score |
| python -m zerobench_eval score --wav_dir my_wavs/ --name MyModel |
| |
| Run ``python -m zerobench_eval <command> --help`` for the full flag list. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import sys |
| from pathlib import Path |
|
|
| from .benchmark import find_wavs, load_benchmark, resolve_ref_audio |
| from .report import format_report, group_report, write_outputs |
| from .scorers import DEFAULT_ASR, MetricSuite, load_wav_16k |
|
|
| _HERE = Path(__file__).resolve().parent |
| REPO_ID = "zeroweight-ai/ZeroBench-TTS" |
|
|
|
|
| def _log(msg: str) -> None: |
| print(f"[zerobench] {msg}", flush=True) |
|
|
|
|
| |
|
|
| def cmd_manifest(args: argparse.Namespace) -> None: |
| """Emit exactly what a submission must contain: one row per test item, with |
| the text to say, the reference clip to clone, and the wav path to write.""" |
| rows, root = load_benchmark(args.benchmark) |
| out = Path(args.out) |
| with out.open("w", encoding="utf-8") as f: |
| for r in rows: |
| f.write(json.dumps({ |
| "id": r["id"], |
| "subset": r["subset"], |
| "voice_id": r["voice_id"], |
| "text": r["text"], |
| "lang": r["lang"], |
| "ref_audio": str(resolve_ref_audio(r, root)), |
| "ref_text": r.get("ref_text", ""), |
| "output_wav": f"{r['subset']}/{r['voice_id']}.wav", |
| }, ensure_ascii=False) + "\n") |
| _log(f"wrote {len(rows)} rows -> {out}") |
| _log("Synthesize `text` with `ref_audio` as the voice prompt, save each to " |
| "<your_wav_dir>/<output_wav>, then run: " |
| f"python -m zerobench_eval score --wav_dir <your_wav_dir>") |
|
|
|
|
| |
|
|
| def cmd_score(args: argparse.Namespace) -> None: |
| rows, root = load_benchmark(args.benchmark) |
| if args.subsets: |
| rows = [r for r in rows if r["subset"] in set(args.subsets)] |
| if not rows: |
| raise SystemExit(f"no benchmark items matched (subsets={args.subsets})") |
|
|
| wav_dir = Path(args.wav_dir) |
| found, missing = find_wavs(rows, wav_dir) |
| if missing: |
| head = ", ".join(m["id"] for m in missing[:5]) |
| msg = (f"{len(missing)}/{len(rows)} wavs not found under {wav_dir} " |
| f"(e.g. {head}). Expected <wav_dir>/<subset>/<voice_id>.wav — see " |
| f"`python -m zerobench_eval manifest`.") |
| if not args.allow_missing: |
| raise SystemExit(msg + "\nPass --allow_missing to score the rest anyway.") |
| _log("WARNING " + msg) |
| if not found: |
| raise SystemExit("no wavs to score") |
| _log(f"scoring {len(found)}/{len(rows)} items from {wav_dir}") |
|
|
| metrics = MetricSuite(device=args.device, asr_models=args.asr or DEFAULT_ASR, |
| skip_utmos=args.skip_utmos) |
|
|
| ref_cache: dict[str, "object"] = {} |
| results, t0 = [], __import__("time").time() |
| for i, (row, wav_path) in enumerate(found, 1): |
| ref_path = str(resolve_ref_audio(row, root)) |
| if ref_path not in ref_cache: |
| ref_cache[ref_path] = load_wav_16k(ref_path) |
| scored = metrics.score( |
| pred_wav_16k=load_wav_16k(str(wav_path)), |
| ref_wav_16k=ref_cache[ref_path], |
| text=row["text"], text_normalized=row.get("text_normalized", ""), |
| lang=row["lang"], |
| ) |
| results.append({ |
| "id": row["id"], "subset": row["subset"], "voice_id": row["voice_id"], |
| "voice_source": row.get("voice_source", ""), "lang": row["lang"], |
| "length_bucket": row.get("length_bucket", ""), |
| "text": row["text"], "text_normalized": row.get("text_normalized", ""), |
| **scored, "wav_path": str(wav_path), |
| }) |
| if i % 10 == 0 or i == len(found): |
| _log(f" {i}/{len(found)} last wer={scored['wer_robust']:.3f} " |
| f"(strict {scored['wer_strict']:.3f}) " |
| f"[{__import__('time').time() - t0:.0f}s]") |
|
|
| name = args.name or wav_dir.name |
| out_dir = Path(args.out_dir) if args.out_dir else wav_dir.parent / f"{name}_zerobench" |
| summary = write_outputs(out_dir, name, results, rows, args) |
| print("\n" + group_report(name, results)) |
| _log(f"per-sample -> {out_dir / 'per_sample.csv'}") |
| _log(f"summary -> {out_dir / 'summary.json'}") |
| if summary["n_scored"] < len(rows): |
| _log(f"NOTE partial submission: {summary['n_scored']}/{len(rows)} items — " |
| "not comparable to full-benchmark numbers.") |
|
|
|
|
| |
|
|
| def cmd_rescore(args: argparse.Namespace) -> None: |
| """Recompute WER from saved transcripts — no ASR, no GPU, seconds not minutes. |
| |
| Transcription does not depend on the reference policy, so editing |
| references.py never requires re-running the ASRs. |
| """ |
| import pandas as pd |
| from .scorers import score_all_policies |
|
|
| for d in args.run_dirs: |
| d = Path(d) |
| csv_path = d / "per_sample.csv" |
| df = pd.read_csv(csv_path) |
| cols = [c for c in df.columns if c.startswith("transcript_")] |
| if not cols: |
| raise SystemExit(f"{csv_path}: no transcript_* columns") |
| before = df["wer"].mean() |
| new = pd.DataFrame([ |
| score_all_policies( |
| {c[len("transcript_"):]: ("" if pd.isna(r[c]) else str(r[c])) for c in cols}, |
| str(r.text), "" if pd.isna(r.text_normalized) else str(r.text_normalized)) |
| for _, r in df.iterrows()], index=df.index) |
| for c in new.columns: |
| df[c] = new[c] |
| df.to_csv(csv_path, index=False, encoding="utf-8") |
| print(f"[zerobench] {d.name}: WER {before * 100:.2f}% -> {df['wer'].mean() * 100:.2f}%") |
| print(group_report(d.name, df.to_dict("records"))) |
|
|
|
|
| |
|
|
| def main(argv: "list[str] | None" = None) -> None: |
| p = argparse.ArgumentParser( |
| prog="python -m zerobench_eval", description=__doc__, |
| formatter_class=argparse.RawDescriptionHelpFormatter) |
| sub = p.add_subparsers(dest="cmd", required=True) |
|
|
| def common(sp): |
| sp.add_argument("--benchmark", default=None, |
| help=f"Benchmark dir or metadata.jsonl. Default: this repo if " |
| f"run from a clone, else downloads {REPO_ID} from the Hub.") |
|
|
| m = sub.add_parser("manifest", help="write the list of clips to synthesize") |
| common(m) |
| m.add_argument("--out", default="manifest.jsonl") |
| m.set_defaults(func=cmd_manifest) |
|
|
| s = sub.add_parser("score", help="score a directory of generated wavs") |
| common(s) |
| s.add_argument("--wav_dir", required=True, |
| help="Directory of generated wavs. Layout <subset>/<voice_id>.wav " |
| "(a nested wav/ folder and flat <id>.wav names also work).") |
| s.add_argument("--name", default=None, help="Label for this system in the report.") |
| s.add_argument("--out_dir", default=None) |
| s.add_argument("--subsets", nargs="+", default=None) |
| s.add_argument("--device", default="cuda") |
| s.add_argument("--asr", action="append", default=None, metavar="MODEL_ID", |
| help="Override the ASR set (repeatable). Default is both " |
| "openai/whisper-large-v3 and vinai/PhoWhisper-large, min taken. " |
| "Changing this makes numbers non-comparable to the leaderboard.") |
| s.add_argument("--skip_utmos", action="store_true", |
| help="Skip UTMOSv2 (optional dep); UTMOS is reported as NaN.") |
| s.add_argument("--allow_missing", action="store_true", |
| help="Score a partial submission instead of erroring.") |
| s.set_defaults(func=cmd_score) |
|
|
| r = sub.add_parser("rescore", help="recompute WER from saved transcripts (no GPU)") |
| r.add_argument("run_dirs", nargs="+") |
| r.set_defaults(func=cmd_rescore) |
|
|
| args = p.parse_args(argv) |
| args.func(args) |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|