ZeroBench-TTS / zerobench_eval /benchmark.py
zeroweightai's picture
Add official standalone scorer + rewrite README (robustness, SEO, ZeroTTS links)
33d6997 verified
Raw
History Blame
3.55 kB
"""Locating the benchmark data and matching a submission's wavs to it.
Deliberately forgiving about wav layout — the point of the harness is that
anyone can score their system, not that they guess a folder convention.
"""
from __future__ import annotations
import json
from pathlib import Path
REPO_ID = "zeroweight-ai/ZeroBench-TTS"
_HERE = Path(__file__).resolve().parent
def _local_root() -> "Path | None":
"""metadata.jsonl next to this package (i.e. running from a repo clone)."""
for cand in (_HERE.parent, _HERE.parent.parent):
if (cand / "metadata.jsonl").exists():
return cand
return None
def load_benchmark(path: "str | None" = None) -> "tuple[list[dict], Path]":
"""Returns (rows, root). ``root`` is what ``ref_audio`` resolves against.
Resolution order: explicit ``path`` -> a local clone -> download from the Hub.
"""
if path:
p = Path(path)
if p.is_dir() and (p / "metadata.jsonl").exists():
meta, root = p / "metadata.jsonl", p
elif p.is_file():
meta, root = p, p.parent
else:
raise SystemExit(f"--benchmark {path!r}: no metadata.jsonl there")
else:
root = _local_root()
if root is None:
root = _download()
meta = root / "metadata.jsonl"
rows = [json.loads(l) for l in meta.read_text(encoding="utf-8").splitlines() if l.strip()]
rows.sort(key=lambda r: (r["subset"], r["voice_id"]))
return rows, root
def _download() -> Path:
"""Pull metadata.jsonl + the reference audio from the Hub, once."""
from huggingface_hub import snapshot_download
print(f"[zerobench] downloading {REPO_ID} reference data from the Hub ...", flush=True)
return Path(snapshot_download(
REPO_ID, repo_type="dataset",
allow_patterns=["metadata.jsonl", "voices.jsonl", "audio/*"],
))
def resolve_ref_audio(row: dict, root: Path) -> Path:
"""Absolute path to a row's reference clip."""
p = Path(row["ref_audio"])
return p if p.is_absolute() else (root / p).resolve()
#: Layouts accepted for a submission, tried in order. Each maps a row to a
#: path fragment under --wav_dir.
_LAYOUTS = (
lambda r: f"{r['subset']}/{r['voice_id']}.wav", # the documented one
lambda r: f"wav/{r['subset']}/{r['voice_id']}.wav", # eval_tts.py's output dir
lambda r: f"{r['id'].replace('/', '_')}.wav", # flat, id-derived
lambda r: f"{r['subset']}_{r['voice_id']}.wav", # flat, joined
lambda r: f"{r['voice_id']}.wav", # flat (single-subset runs)
)
def find_wavs(rows: list[dict], wav_dir: Path) -> "tuple[list[tuple[dict, Path]], list[dict]]":
"""Match every benchmark row to a wav under ``wav_dir``.
Returns (found, missing) where found is [(row, path)]. The flat
``<voice_id>.wav`` layout is only consulted when it is unambiguous, since
the same voice appears in several subsets.
"""
found: list[tuple[dict, Path]] = []
missing: list[dict] = []
multi_subset = len({r["subset"] for r in rows}) > 1
for row in rows:
hit = None
for i, layout in enumerate(_LAYOUTS):
if multi_subset and i == len(_LAYOUTS) - 1:
break # ambiguous across subsets
cand = wav_dir / layout(row)
if cand.exists():
hit = cand
break
(found.append((row, hit)) if hit else missing.append(row))
return found, missing