""" Vibe-check data layer: play the *stored* eval audio straight from the bucket. Every leaderboard number comes from generations that were already rendered and kept in a HF bucket, so the vibe check does not synthesise anything — it picks a sample and plays what the model actually produced during evaluation. The bucket is read directly through the `huggingface_hub` bucket API (``list_bucket_tree`` / ``download_bucket_files``) rather than a local mount — listings hit the Hub, and individual files (JSONL indexes, WAVs) are fetched lazily into a small on-disk cache the first time they are needed. Bucket layout (``hf-audio/tts_leaderboard_h200``) ---------------------------------------------- ``` / MODEL__DATASET_.jsonl # one line per sample MODEL__DATASET__voice_clone.jsonl # x-vector SIM scale MODEL__DATASET__voice_clone_wavlm_seed_tts.jsonl /output_.wav # default-voice runs _voice_clone/output_.wav # cloning runs _voice_clone/prompts/prompt_.wav # the reference clip ``` ```` is ``-`` (see ``_EVAL_NAMESPACE`` and ``_EVAL_PREFIXES`` below), optionally carrying a model-variant tag (``_rl``, ``_multilingual``) that marks which flavour of the checkpoint was run. A JSONL line holds ``audio_filepath``, ``text``, ``pred_text`` (the ASR transcript the WER is computed from), ``duration`` and ``time`` (wall-clock generation seconds), plus — for cloning runs — ``prompt_audio_filepath`` and ``sim``. Only the ``_wavlm_seed_tts`` variant carries SIM on the leaderboard's canonical seed-tts WavLM scale, so that file is preferred as the cloning index. """ import json import os import random import re import tempfile from concurrent.futures import ThreadPoolExecutor from functools import lru_cache from pathlib import Path from huggingface_hub import BucketFile, BucketFolder, download_bucket_files, list_bucket_tree from leaderboard_data import company_of, lang_display, load_version BUCKET = "hf-audio/tts_leaderboard_h200" BUCKET_URL = f"https://huggingface.co/buckets/{BUCKET}" TOKEN_HUB = os.environ.get("TOKEN_HUB") or os.environ.get("HF_TOKEN") # Files are fetched from the bucket on first use and kept here for the life of # the process, so re-playing a sample doesn't re-hit the Hub. CACHE_DIR = Path(os.environ.get("TTS_LEADERBOARD_CACHE_DIR") or Path(tempfile.gettempdir()) / "tts_leaderboard_bucket_cache") # Bases are named "-[_]". The # namespace is the Hub org holding the eval-dataset copies the samples were # generated from (see leaderboard_data.py's module docstring) — only the # current one is read; a base under any other namespace (a stale "bezzam-" # run from before the datasets moved here, or someone's private copy) is # left unparsed and dropped in ``listen_entries``. _EVAL_NAMESPACE = "hf-audio-" _EVAL_PREFIXES = { "seed_tts_eval_tts_": "Seed-TTS", "cv3_eval_zero_shot_": "CV3-Eval", "minimax_eval_tts_": "MiniMax", "neyshekar_eval_tts_": "Neyshekar", "ztts2_eval_mini_clean_": "ZTTS2-Mini-clean", } _CLONE_SUFFIX = "_voice_clone" _CANONICAL_SIM_SUFFIX = "_voice_clone_wavlm_seed_tts" # How many models may be compared at once — every clip is inlined into the page, # so this bounds how heavy one render gets. MAX_MODELS = 6 # ------------------------------------------------------------------ # Prompt-type filtering (Listen tab) # ------------------------------------------------------------------ # Each category names a class of text TTS models tend to stumble on (numbers, # acronyms, …). A prompt can belong to several at once; the Listen filter keeps # only samples whose text matches the chosen one. "all" is the no-op default. # The cues are casing/punctuation based, so for non-Latin scripts most filters # simply won't match — fine, since the filter is applied per language. PROMPT_CATEGORIES = ( ("all", "Everything (no filter)"), ("numbers", "Numbers, times & quantities"), ("acronyms", "Acronyms & initialisms"), ("proper_nouns", "Proper nouns (names / places)"), ("questions", "Questions & exclamations"), ) _CATEGORY_RE = { "numbers": re.compile(r"\d"), # NASA, FBI, U.S., Ph.D. — a run of caps or dotted single letters. "acronyms": re.compile(r"(?:\b[A-Z]\.){2,}|\b[A-Z]{2,}\b"), "questions": re.compile(r"[?!¿¡?!]"), } def _has_proper_noun(text: str) -> bool: """Rough cue: a capitalized word that isn't a sentence opener (a name/place). Only meaningful for cased scripts; non-Latin text simply won't match. """ first = True prev_ended_sentence = False for m in re.finditer(r"[^\W\d_]+", text, re.UNICODE): word = m.group() looks_name = word[0].isupper() and word[1:2].islower() if looks_name and not first and not prev_ended_sentence: return True first = False prev_ended_sentence = text[m.end():m.end() + 1] in ".!?…" return False def text_categories(text: str) -> set: """The set of breaking-point categories a prompt's text falls into.""" if not text: return set() cats = {k for k, rx in _CATEGORY_RE.items() if rx.search(text)} if _has_proper_noun(text): cats.add("proper_nouns") return cats def category_label(key: str) -> str: return dict(PROMPT_CATEGORIES).get(key, key) def _filter_ids_by_category(indexes: dict, common_ids: set, category: str | None) -> set: """Keep only sample ids whose prompt text matches ``category``. The text is shared across the compared models for a given id, so any one model's index is enough to read it. """ if not category or category == "all": return common_ids idx = next(iter(indexes.values())) return {sid for sid in common_ids if category in text_categories(idx.get(sid, {}).get("text", ""))} # ------------------------------------------------------------------ # Models present in the bucket # ------------------------------------------------------------------ def _repo_id(model: str) -> str: """Drop any variant tag a leaderboard id carries — a repo id has no spaces. The leaderboard writes variants both ways (``"… (RL)"``, ``"… multilingual"``), and neither is part of the Hub repo the bucket folder is named after. """ return model.split()[0] if model else model @lru_cache(maxsize=1) def bucket_models() -> dict: """``{"org/model": "org-model"}`` for the bucket folders that are on the leaderboard. The folder name is the model id with ``/`` flattened to ``-``, which is ambiguous on its own (``k2-fsa-OmniVoice``), so the split is resolved against the orgs that actually appear in the leaderboard results. The bucket also holds runs whose results were never computed, so anything without a leaderboard row is left out — there is nothing to compare it to. """ snap = load_version() orgs = {company_of(m) for m in snap.models_with_results} | { company_of(m) for m in snap.model_info } # Longest org first, so "OpenMOSS-Team" wins over a shorter false prefix. orgs = sorted(orgs, key=len, reverse=True) listed = {_repo_id(m) for m in snap.models_with_results} out, skipped = {}, [] try: folders = [item.path for item in list_bucket_tree(BUCKET, recursive=False, token=TOKEN_HUB) if isinstance(item, BucketFolder)] except Exception as e: # noqa: BLE001 — the tab must degrade, not break the app print(f"[vibe_check] could not list bucket {BUCKET}: {e}") return {} for slug in folders: org = next((o for o in orgs if slug.startswith(f"{o}-")), None) model_id = f"{org}/{slug[len(org) + 1:]}" if org else slug.replace("-", "/", 1) if model_id not in listed: skipped.append(model_id) continue out[model_id] = slug if skipped: print(f"[vibe_check] bucket folders with no leaderboard results (not offered): {skipped}") return dict(sorted(out.items(), key=lambda kv: kv[0].lower())) # ------------------------------------------------------------------ # Datasets a model was run on # ------------------------------------------------------------------ @lru_cache(maxsize=64) def model_bases(slug: str) -> tuple: """``((base, has_cloning), ...)`` for one model folder, from its JSONL index files.""" try: names = [item.path.rsplit("/", 1)[-1] for item in list_bucket_tree(BUCKET, prefix=f"{slug}/", recursive=False, token=TOKEN_HUB) if isinstance(item, BucketFile) and item.path.endswith(".jsonl")] except Exception as e: # noqa: BLE001 — the tab must degrade, not break the app print(f"[vibe_check] could not list {slug}: {e}") return () datasets = {n.split("_DATASET_", 1)[-1].removesuffix(".jsonl") for n in names if "_DATASET_" in n} bases = sorted(d for d in datasets if not d.endswith(_CLONE_SUFFIX) and not d.endswith(_CANONICAL_SIM_SUFFIX)) return tuple((b, f"{b}{_CLONE_SUFFIX}" in datasets) for b in bases) def split_base(base: str) -> tuple: """``"hf-audio-cv3_eval_zero_shot_de_rl"`` -> ``("hf-audio-cv3_eval_zero_shot_de", "rl")``. A variant tag names which flavour of the *checkpoint* was run, not a different eval set — every variant of one eval set and language holds the same samples — so it belongs on the model, and the tag-free base is the dataset key. A base outside ``_EVAL_NAMESPACE`` or with an unrecognized prefix comes back unparsed, with no tag — ``listen_entries`` is what actually drops it. """ if not base.startswith(_EVAL_NAMESPACE): return base, "" name = base[len(_EVAL_NAMESPACE):] for prefix in _EVAL_PREFIXES: if name.startswith(prefix): lang, _, tag = name[len(prefix):].partition("_") return f"{_EVAL_NAMESPACE}{prefix}{lang}", tag return base, "" def dataset_lang(key: str) -> tuple: """``"hf-audio-cv3_eval_zero_shot_de"`` -> ``("CV3-Eval", "de")``. The leaderboard dataset label and language code this bucket key names — the pair ``aggregate_rows`` needs to rank models for that key specifically. """ if not key.startswith(_EVAL_NAMESPACE): return "", "" name = key[len(_EVAL_NAMESPACE):] for prefix, label in _EVAL_PREFIXES.items(): if name.startswith(prefix): return label, name[len(prefix):] return "", "" def dataset_label(key: str) -> str: """``"hf-audio-cv3_eval_zero_shot_de"`` -> ``"CV3-Eval · 🇩🇪 German"``.""" label, lang = dataset_lang(key) return f"{label} · {lang_display(lang)}" if label else key def model_label(model_id: str, tag: str) -> str: """``("ResembleAI/chatterbox", "multilingual")`` -> ``"ResembleAI/chatterbox (multilingual)"``.""" return f"{model_id} ({tag.replace('_', ' ')})" if tag else model_id def _normalize_tag(s: str) -> str: """Compare variant tags with punctuation/case stripped — ``"heart-nano"``, ``"heartnano"`` and ``"HEART NANO"`` all collapse to ``"heartnano"``, so a bucket folder named ``_heartnano`` lines up with a published row named ``(heart-nano)``.""" return "".join(c for c in s.lower() if c.isalnum()) def _resolve_labels(model_id: str, bucket_tags: list, info_labels: list) -> dict: """Map bucket ``tag`` -> published ``model_info.csv`` row name for one model. Returns ``{tag: label}``. Uses three passes: 1. Exact: ``model_label(model_id, tag)`` matches an info label (ordinary case). 2. Normalized: bucket tag's alphanumerics match a parenthetical label tag (so ``heartnano`` resolves to ``(heart-nano)``). 3. Leftover: an empty bucket tag maps to the sole remaining info label (the "default voice" was renamed to carry an explicit parenthetical). """ import re paren = re.compile(r"\s*\((.+?)\)\s*$") def label_tag(lbl): m = paren.search(lbl[len(model_id):]) if lbl.startswith(model_id) else None return m.group(1) if m else "" tag_to_label = {label_tag(l): l for l in info_labels} out, used = {}, set() # Pass 1: exact match for bt in bucket_tags: d = model_label(model_id, bt) if d in info_labels and d not in used: out[bt] = d used.add(d) # Pass 2: normalized match for bt in bucket_tags: if bt in out: continue nbt = _normalize_tag(bt) for lt, lbl in tag_to_label.items(): if lbl in used or _normalize_tag(lt) != nbt: continue out[bt] = lbl used.add(lbl) break # Pass 3: last unclaimed label for an unresolved bucket tag (default-voice rename). unclaimed = [l for l in info_labels if l not in used] for bt in bucket_tags: if bt in out: continue if len(unclaimed) == 1: out[bt] = unclaimed[0] used.add(unclaimed[0]) unclaimed = [] else: out[bt] = model_label(model_id, bt) return out @lru_cache(maxsize=2) def listen_entries(clone: bool) -> dict: """``{lang code: {dataset key: {model label: (slug, base)}}}`` — what can be played, grouped by language and then by eval set (Seed-TTS, CV3-Eval, MiniMax), each level ordered by coverage (widest first). One entry per model *variant*, so a checkpoint run in two flavours shows up twice under the same eval set rather than splitting it in two. See ``pick_sample`` for why grouping by language never mixes samples across eval sets. Display labels are reconciled with ``model_info.csv`` so the dropdown shows the same row names as the Leaderboard tab (handles bucket folders whose "default voice" is published under an explicit parenthetical like ``ampixa/sanoTTS (heart)``). """ models = bucket_models() # One listing round trip per model folder; in parallel it is ~1s instead of ~5s. with ThreadPoolExecutor(max_workers=8) as pool: list(pool.map(model_bases, models.values())) snap = load_version() # Published labels grouped by bare repo id (the key the bucket indexes by). info_by_id = {} for m in snap.model_info: info_by_id.setdefault(_repo_id(m), []).append(m) out = {} for model_id, slug in models.items(): bucket_tags = [] kept = [] for base, has_clone in model_bases(slug): if clone and not has_clone: continue if not base.startswith(_EVAL_NAMESPACE): continue # stale/foreign eval-dataset copy — not offered here key, tag = split_base(base) _, lang = dataset_lang(key) if not lang: continue # an eval-set prefix _EVAL_PREFIXES doesn't recognize kept.append((base, key, tag, lang)) if tag not in bucket_tags: bucket_tags.append(tag) if not kept: continue labels = _resolve_labels(model_id, bucket_tags, info_by_id.get(model_id, [])) for base, key, tag, lang in kept: out.setdefault(lang, {}).setdefault(key, {})[labels[tag]] = (slug, base) variants_by_lang = { lang: { key: dict(sorted(entries.items(), key=lambda kv: kv[0].lower())) for key, entries in sorted(variants.items(), key=lambda kv: (-len(kv[1]), dataset_label(kv[0]))) } for lang, variants in out.items() } return dict(sorted( variants_by_lang.items(), key=lambda kv: (-max(len(e) for e in kv[1].values()), lang_display(kv[0])), )) # ------------------------------------------------------------------ # Per-sample index # ------------------------------------------------------------------ @lru_cache(maxsize=4096) def _fetch(rel_path: str) -> Path | None: """Download one bucket file into the local cache, once per process. ``None`` means the path doesn't exist in the bucket (or the fetch failed) — every caller treats that as "this sample/clip isn't available" rather than an error. """ dest = CACHE_DIR / rel_path if not dest.exists(): dest.parent.mkdir(parents=True, exist_ok=True) try: download_bucket_files(BUCKET, [(rel_path, dest)], token=TOKEN_HUB) except Exception as e: # noqa: BLE001 — a missing/broken clip must not break the tab print(f"[vibe_check] could not fetch {rel_path}: {e}") return None return dest if dest.exists() else None def _sample_id(audio_filepath: str) -> str: """``".../output_common_voice_en_1-common_voice_en_2.wav"`` -> the id part.""" stem = audio_filepath.split("/")[-1].removesuffix(".wav") return stem.removeprefix("output_") @lru_cache(maxsize=256) def sample_index(slug: str, base: str, clone: bool) -> dict: """``{sample_id: record}`` for one (model, dataset, mode), from its JSONL.""" if clone: # Only this variant scores SIM on the leaderboard's scale; the plain # cloning file is the same audio with an x-vector SIM, so it is the # fallback when the canonical run is missing. candidates = [f"{base}{_CANONICAL_SIM_SUFFIX}", f"{base}{_CLONE_SUFFIX}"] else: candidates = [base] for dataset in candidates: local = _fetch(f"{slug}/MODEL_{slug}_DATASET_{dataset}.jsonl") if local is None: continue records = {} with open(local) as f: for line in f: line = line.strip() if not line: continue try: rec = json.loads(line) except json.JSONDecodeError: continue if rec.get("audio_filepath"): records[_sample_id(rec["audio_filepath"])] = rec if records: return records return {} def _local_wav(slug: str, rel_path: str) -> Path | None: return _fetch(f"{slug}/{rel_path}") def bucket_url(slug: str, rel_path: str) -> str: """Exact Hub link to one stored clip, e.g. a model's take or the reference prompt.""" return f"{BUCKET_URL}/tree/{slug}/{rel_path}" def normalize_sample_id(raw: str) -> str: """``"output_uttid_1.wav"`` / ``"uttid_1"`` -> ``"uttid_1"`` — accept either the bare id or the filename it comes from, since a user copying it off the Hub link above would have the latter.""" return raw.strip().removesuffix(".wav").removeprefix("output_") def _resolve_variant(key: str, entries: dict, model_labels, clone: bool): """``(chosen, indexes, common_ids)`` for one eval-set key, or an error dict. ``None`` means none of ``model_labels`` have any entry here at all — not an error by itself, just "this eval set doesn't apply", for the sample-id search in ``pick_sample`` to move on to the next one. """ chosen = [(label, *entries[label]) for label in model_labels if label in entries] if not chosen: return None indexes = {label: sample_index(slug, base, clone) for label, slug, base in chosen} missing = [label for label, idx in indexes.items() if not idx] if missing: return {"error": f"No stored samples for {', '.join(missing)} on {dataset_label(key)}."} common_ids = set.intersection(*(set(idx) for idx in indexes.values())) if not common_ids: return {"error": f"These models have no sample in common on {dataset_label(key)}."} return chosen, indexes, common_ids def _finish_sample(key: str, chosen, indexes: dict, sample_id: str, clone: bool) -> dict: """Resolve the audio for an already-picked ``(key, sample_id)`` into ``pick_sample``'s return shape.""" out_models = [] for label, slug, _base in chosen: record = indexes[label][sample_id] local = _local_wav(slug, record["audio_filepath"]) out_models.append({ "model": label, "wav": local, "record": record, "slug": slug, "url": bucket_url(slug, record["audio_filepath"]), }) reference = reference_url = None if clone: # Every model clones from the same reference clip, so the first one that # names a prompt is representative. for entry in out_models: prompt = entry["record"].get("prompt_audio_filepath") if prompt: reference = _local_wav(entry["slug"], prompt) reference_url = bucket_url(entry["slug"], prompt) break have_reference = reference is not None return { "key": key, "label": dataset_label(key), "sample_id": sample_id, "text": out_models[0]["record"].get("text", ""), "reference": reference if have_reference else None, "reference_url": reference_url if have_reference else None, "models": [m for m in out_models if m["wav"] is not None], "error": "", } @lru_cache(maxsize=128) def category_counts(lang: str, clone: bool, datasets=None) -> dict: """``{category: n}`` — how many stored prompts for ``lang`` hit each breaking point, summed over the eval sets covering it (so the Listen dropdown can show the pool size per type). The text is shared across a sample's models, so one representative model index per eval set is enough to count from. ``datasets`` (a tuple of ``dataset_lang`` labels, for lru_cache hashability) restricts the count to those eval sets so it matches what ``pick_sample`` would actually draw from; ``None`` counts them all. """ counts = {key: 0 for key, _ in PROMPT_CATEGORIES} for key, entries in listen_entries(clone).get(lang, {}).items(): if datasets is not None and dataset_lang(key)[0] not in datasets: continue label = next(iter(entries)) slug, base = entries[label] for rec in sample_index(slug, base, clone).values(): counts["all"] += 1 for cat in text_categories(rec.get("text", "")): if cat in counts: counts[cat] += 1 return counts def pick_sample(model_labels, clone: bool, lang: str, seed=None, sample_id: str | None = None, category: str | None = None, datasets=None) -> dict: """Pick one sample every selected model rendered in ``lang``, and resolve its audio. ``lang`` is a language code, not one specific eval set: ``listen_entries`` groups every eval set covering it (Seed-TTS, CV3-Eval, MiniMax, Neyshekar) together, and eval sets don't share a sample-id namespace, so this resolves to one of them before picking a sample — every model in the result ends up on the same text from the same eval set. An explicit ``sample_id`` (bare id or filename, see ``normalize_sample_id``) is searched for across every eval set for ``lang`` — widest coverage first — since the caller may not know which one they copied it from. Without one, every matching shared sample across all the eval sets is pooled and one is drawn uniformly (``seed``) — so an eval set with a single match isn't picked as often as one with fifty; the draw picks the eval set and the sample at once. ``category`` (one of ``PROMPT_CATEGORIES``) restricts the pool to prompts whose text hits a given TTS breaking point (numbers, acronyms, …). It is ignored when an explicit ``sample_id`` is given. ``datasets`` restricts the pool to those eval sets (by their ``dataset_lang`` label, e.g. ``"MiniMax"``); ``None`` means all of them. An empty selection is an error. Only the random pool honours it — an explicit ``sample_id`` is still searched across every eval set. Returns ``{"key", "label", "sample_id", "text", "reference", "reference_url", "models", "error"}`` — ``models`` is ``[{"model", "wav", "url", "record"}, ...]`` in the given order; ``reference``/``reference_url`` are the cloning prompt clip (``None`` outside cloning mode); ``"key"``/``"label"`` name the eval set actually resolved to, not ``lang``. """ if not model_labels: return {"error": "Pick at least one model."} if datasets is not None and not datasets: return {"error": "Select at least one dataset."} variants = listen_entries(clone).get(lang, {}) if not variants: return {"error": f"No stored samples for {lang_display(lang)}."} if sample_id: wanted = normalize_sample_id(sample_id) last_error = None for key, entries in variants.items(): result = _resolve_variant(key, entries, model_labels, clone) if result is None: continue if isinstance(result, dict): last_error = result continue chosen, indexes, common_ids = result if wanted in common_ids: return _finish_sample(key, chosen, indexes, wanted, clone) return last_error or {"error": f"No sample '{sample_id}' shared by the selected " f"models for {lang_display(lang)}."} rng = random.Random(seed) # Pool every matching shared sample across all the eval sets, then draw one # uniformly: a split with a single match (e.g. the lone digit-bearing MiniMax # prompt) is then no likelier per-sample than one with fifty, instead of being # as likely as any other split under the old split-first shuffle. Each pool # entry is a (key, sample_id) pair, so one draw fixes both the eval set and # the sample. Pool order is deterministic (variants order, ids sorted), so a # fixed ``seed`` still reproduces. pool = [] resolved = {} last_error = None for key, entries in variants.items(): if datasets is not None and dataset_lang(key)[0] not in datasets: continue result = _resolve_variant(key, entries, model_labels, clone) if result is None: continue if isinstance(result, dict): last_error = result continue chosen, indexes, common_ids = result ids = _filter_ids_by_category(indexes, common_ids, category) if not ids: continue resolved[key] = (chosen, indexes) pool.extend((key, sid) for sid in sorted(ids)) if not pool: if category and category != "all": return {"error": f"No «{category_label(category)}» prompt is shared by the " f"selected models for {lang_display(lang)} — try another filter."} return last_error or {"error": "Pick at least one model."} key, sample_id = rng.choice(pool) chosen, indexes = resolved[key] return _finish_sample(key, chosen, indexes, sample_id, clone)