File size: 3,549 Bytes
b982e77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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