import base64 import json import random import re import shutil import threading import time import wave from contextlib import nullcontext from functools import partial from html import escape from pathlib import Path import gradio as gr import numpy as np from huggingface_hub import CommitScheduler, hf_hub_download from constants import ( BANNER, INTRODUCTION_TEXT, CITATION_TEXT, VERSIONING_TEXT, ABOUT_TAB_TEXT, VIBE_CHECK_TAB_TEXT, LEADERBOARD_TAB_TEXT, STREAMING_TAB_TEXT, LEADERBOARD_CSS, ) from leaderboard_data import ( ACTIVE_VERSION, CHANGELOG_TEXT, DATASET_LABELS, DATASETS, DEFAULT_LANG, LANG_ORDER, RESULTS_REPO, TOKEN_HUB, VERSIONS, all_models, all_result_models, dataset_language_coverage, get_version_choices, keys_from_labels, lang_display, lang_flag, languages_for, languages_for_model, size_bounds, streaming_rows, version_id_for_semver, ) from leaderboard_views import clickable_model, leaderboard_view, streaming_table, streaming_view from vibe_check import ( MAX_MODELS, PROMPT_CATEGORIES, category_counts, dataset_lang, listen_entries, pick_sample, ) # ------------------------------------------------------------------ # Extract "last updated" date from changelog # ------------------------------------------------------------------ _changelog_date_match = re.search(r"\*\*(.+?)\*\* \((v[\d.]+)\)", CHANGELOG_TEXT) LAST_UPDATED = _changelog_date_match.group(1) if _changelog_date_match else "22 May 2026" LAST_VERSION = _changelog_date_match.group(2) if _changelog_date_match else "" # ------------------------------------------------------------------ # Leaderboard state # ------------------------------------------------------------------ ALL_LANG_DISPLAYS = [lang_display(c) for c in LANG_ORDER] DEFAULT_LANG_DISPLAYS = [lang_display(DEFAULT_LANG)] # Each dataset's own language coverage, shown as flags next to its toggle so # it's clear e.g. Seed-TTS only has English/Chinese before you even check it. # Plain (non-cloning) coverage on the default version — a stable reference # label, not something that shifts with the clone toggle or version picker. _dataset_coverage = dataset_language_coverage([d["key"] for d in DATASETS], clone=False) DATASET_CHOICES = [ (f"{d['label']} ({''.join(lang_flag(c) for c in _dataset_coverage[d['key']])})", d["label"]) for d in DATASETS ] # (min, max) for the model-size filter slider, on the default version — a # stable range, not something that shifts with the version picker (same # simplification as DATASET_CHOICES above). SIZE_MIN, SIZE_MAX = size_bounds() # Every model, for the "match a model's languages" preset dropdown — same # simplification as DATASET_CHOICES/SIZE_MIN/MAX: the roster on the default # version, not re-fetched per version/dataset/clone toggle. ALL_MODELS = all_models() # Full model universe (any result, any language) for the Pareto "Highlight # models" pickers — unlike ALL_MODELS (English-complete only), this reaches a # single-language port too. (value == label == the exact model id.) HIGHLIGHT_MODELS = [(m, m) for m in all_result_models()] STREAM_HIGHLIGHT_MODELS = [ (r["model"], r["model"]) for r in sorted(streaming_rows(), key=lambda r: r["model"].lower()) ] # (default, max) for the "Models to show" sliders next to the bar charts — # some bars are much shorter than others once every model is plotted, so the # slider trades "see everyone" for "keep the short bars legible". Same # simplification as above: a stable count on the default version. The # Leaderboard's max is every model ranked in the default view (English, # every dataset, no cloning) — selecting more languages only narrows that # set further, never grows it, so it's a safe ceiling for any selection. LB_TOP_N_MAX = max(len(ALL_MODELS), 1) LB_TOP_N_DEFAULT = min(LB_TOP_N_MAX, 10) _stream_default_measured = streaming_table(streaming_rows(), "a100")[3] STREAM_TOP_N_MAX = max(len(_stream_default_measured), 1) STREAM_TOP_N_DEFAULT = min(STREAM_TOP_N_MAX, 10) # ------------------------------------------------------------------ # Vibe-check state # ------------------------------------------------------------------ def _vibe_models_for_lang(lang, clone): """Models with stored audio on *every* eval set covering ``lang`` — the ones actually published on the leaderboard for it, so a random pick (which may land on any of those eval sets) always has audio to play. A model that only ran on some of the splits is left out rather than risking an empty pick.""" per_split = [set(entries) for entries in listen_entries(clone).get(lang, {}).values()] return set.intersection(*per_split) if per_split else set() def _vibe_dataset_choices(clone): """Language options, widest coverage first, with the model count. One option per language — Seed-TTS, CV3-Eval and MiniMax all group under whichever languages they cover, rather than each being its own near- identical entry; a checkpoint run in several variants (``rl``, ``multilingual``) holds the same samples, so the variant is a model label, not a separate option either. """ return [ (f"{lang_display(lang)} — {len(_vibe_models_for_lang(lang, clone))} models", lang) for lang in listen_entries(clone) ] def _vibe_default_dataset(clone): choices = _vibe_dataset_choices(clone) return choices[0][1] if choices else "" def _vibe_model_choices(lang, clone): """Only models with stored audio for this language — so any pick is comparable.""" return sorted(_vibe_models_for_lang(lang, clone), key=str.lower) def _vibe_category_choices(lang, clone, datasets=None): """Prompt-type options for a language, each tagged with how many stored prompts match it — so the pool size is visible before picking. ``datasets`` (a list of dataset labels) narrows the count to the selected eval sets, to match what a pick would actually draw from.""" counts = category_counts(lang, clone, tuple(datasets) if datasets is not None else None) return [(f"{label} — {counts.get(key, 0):,} prompts", key) for key, label in PROMPT_CATEGORIES] def _vibe_keep_models(key, clone, current=None): """Models to keep selected after the dataset or cloning mode changes. Whatever was already picked stays selected as long as it still has audio here; otherwise the picker goes back to empty — "Listen" then fills in ``MAX_MODELS`` random ones for you. """ applicable = _vibe_model_choices(key, clone) return [m for m in (current or []) if m in applicable] LOADER_CSS = """ """ _FEEDBACK_JS = """ function tts_leaderboard_feedback_init() { // localStorage remembers a vote per (model, sample, clone mode) in this // browser, so a clip already rated — even one replayed later, or after a // reload — comes back locked instead of accepting a second vote. Clone // mode is part of the key because the plain and voice-cloning runs can // share a sample_id while rating different audio. function voteKey(model, sampleId, clone) { return 'tts_leaderboard_vote::' + model + '::' + sampleId + '::' + clone; } function lockRow(row, vote) { row.querySelectorAll('.vibe-feedback-btn').forEach(function (b) { const isThisVote = b.getAttribute('data-vote') === vote; b.classList.toggle('selected-up', isThisVote && vote === 'up'); b.classList.toggle('selected-down', isThisVote && vote === 'down'); b.disabled = true; }); const thanks = row.querySelector('.vibe-feedback-thanks'); const label = row.querySelector('.vibe-feedback-label'); if (thanks) thanks.classList.add('show'); if (label) label.style.display = 'none'; } // Restore a previously-cast vote for whatever (model, sample, clone) a // row currently names. Keyed off that identity, not off "have we seen // this DOM node before": on a second (or later) "Listen" click, Gradio's // HTML component doesn't always replace the row/audio nodes — it can // patch the existing ones in place (new data-* attributes, same node), // so a one-time per-node hydration flag goes stale silently and never // re-fires. Re-checking by identity instead means a patched row is // handled exactly like a freshly inserted one. const lastKey = new WeakMap(); function syncRow(row) { const model = row.getAttribute('data-model'); const sampleId = row.getAttribute('data-sample'); const clone = row.getAttribute('data-clone') === 'true'; if (!model || !sampleId) return; const key = voteKey(model, sampleId, clone); if (lastKey.get(row) === key) return; lastKey.set(row, key); let stored = null; try { stored = localStorage.getItem(key); } catch (err) { /* ignore */ } if (stored === 'up' || stored === 'down') lockRow(row, stored); } // Catch rows already on the page, then any inserted or patched later // (every replay swaps in a fresh vibe_out HTML block — see the comment // on syncRow for why that isn't always a fresh set of nodes). document.querySelectorAll('.vibe-feedback').forEach(syncRow); new MutationObserver(function (mutations) { mutations.forEach(function (m) { if (m.type === 'attributes') { const row = m.target.closest && m.target.closest('.vibe-feedback'); if (row) syncRow(row); return; } m.addedNodes.forEach(function (node) { if (node.nodeType !== 1) return; if (node.classList && node.classList.contains('vibe-feedback')) syncRow(node); if (node.querySelectorAll) node.querySelectorAll('.vibe-feedback').forEach(syncRow); }); }); }).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-model', 'data-sample', 'data-clone'], }); // Whether the row's *own* clip has played all the way through. Read // straight off the native