"""
View builders for the Open TTS Leaderboard: result tables and Pareto plots.
Everything here is a pure function of the current selector state
(search / languages / datasets / voice-cloning), so the Gradio callbacks in
`app.py` stay thin.
"""
import re
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from leaderboard_data import (
DATASET_BY_KEY,
aggregate_rows,
company_of,
codes_from_display,
dataset_language_coverage,
keys_from_labels,
lang_display,
lang_flag,
matches_search,
matches_size,
streaming_rows,
)
WER_COL = "Average ER ⬇️"
RTFX_COL = "Average RTFx ⬆️"
SIM_COL = "Average SIM ⬆️"
UTMOS_COL = "UTMOS (en) ⬆️"
KOMOS_COL = "KOMOS (ko) ⬆️"
MODEL_COL = "Model"
COVERAGE_COL = "Coverage"
TTFA_P50_COL = "TTFA p50 (ms)"
TTFA_P95_COL = "TTFA p95 (ms)"
STREAM_RTFX_COL = "RTFx ⬆️"
# Column -> Dataframe datatype for every non per-language column we can emit.
_INFO_TYPES = {
MODEL_COL: "markdown",
"License": "markdown",
COVERAGE_COL: "str",
WER_COL: "number",
RTFX_COL: "number",
SIM_COL: "number",
UTMOS_COL: "number",
KOMOS_COL: "number",
TTFA_P50_COL: "number",
TTFA_P95_COL: "number",
STREAM_RTFX_COL: "number",
"Size (B)": "number",
"# languages": "str",
"Voice cloning": "str",
"Batch inference": "str",
"Transformers": "str",
"Streaming API": "str",
}
_PLOT_LAYOUT = dict(
template="plotly_white",
hovermode="closest",
margin=dict(l=60, r=60, t=60, b=50),
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
)
# ------------------------------------------------------------------
# Small formatting helpers
# ------------------------------------------------------------------
def _round(value, digits=2):
return None if value is None else round(value, digits)
def _link(href: str, label: str) -> str:
return (
f'{label}'
)
def _strip_variant_suffix(model: str) -> str:
"""``"kyutai/pocket-tts (audio.cpp)"`` -> ``"kyutai/pocket-tts"``.
Some streaming/engine entries and checkpoint variants carry a
disambiguating ``"(...)"`` suffix that isn't part of the repo id or of
what the model was scored on for quality — e.g. a streaming engine like
``audio.cpp``/``photon`` only changes how a checkpoint is served, not its
WER.
"""
return re.sub(r"\s*\(.*\)\s*$", "", model).strip()
_NEW_BADGE = (
'NEW'
)
def clickable_model(model: str, is_new: bool = False) -> str:
"""Link a model name to its Hub page.
Some entries carry a disambiguating suffix (e.g.
``"ResembleAI/chatterbox (ChatterboxTTS)"``) that is not part of the repo id,
so the suffix is stripped for the URL but kept in the visible label.
Appends a "NEW" pill when ``is_new`` is set (models added in the current
release vs. the previous one).
"""
repo_id = _strip_variant_suffix(model)
badge = _NEW_BADGE if is_new else ""
if repo_id.count("/") != 1:
return model + badge
return _link(f"https://huggingface.co/{repo_id}", model) + badge
def license_cell(value) -> str:
"""Render a license.
``model_info.csv`` carries a URL instead of an SPDX id for custom licenses,
so those show up as a "custom" link to the license text.
"""
text = str(value or "").strip()
if text.startswith(("http://", "https://")):
return _link(text, "custom")
return text or "—"
def _info_cells(info: dict) -> dict:
return {
"Size (B)": _round(info.get("size"), 4),
"License": license_cell(info.get("license")),
"# languages": info.get("n_languages", "—"),
"Voice cloning": "✅" if info.get("voice_cloning") else "—",
"Batch inference": "✅" if info.get("batch_inference") else "—",
"Transformers": "✅" if info.get("transformers") else "—",
}
def _empty(columns):
return pd.DataFrame(columns=columns), [_INFO_TYPES.get(c, "number") for c in columns]
# ------------------------------------------------------------------
# Medal badges on the headline metric columns
# ------------------------------------------------------------------
# Which direction is "better" for a metric column, keyed by its header text
# prefix — reused to rank the top three rows in each metric column.
_METRIC_BETTER = {WER_COL: "min", RTFX_COL: "max", SIM_COL: "max", UTMOS_COL: "max", KOMOS_COL: "max"}
_MEDALS = ["🥇", "🥈", "🥉"]
def _medal_ranks(values, better, mask=None):
"""Row indices of the best three non-null values in a column, best first.
A missing score comes back from ``pandas`` as ``NaN``, not ``None``, since
the column holds a numeric dtype — ``pd.isna`` catches both. ``mask``
(e.g. "complete" rows only, for a headline column) further restricts
which rows are *eligible* to medal, without hiding any row's own value —
a model excluded by the mask still shows its number, just never a medal.
"""
idx = [i for i, v in enumerate(values)
if not pd.isna(v) and (mask is None or mask[i])]
idx.sort(key=lambda i: values[i], reverse=(better == "max"))
return idx[:3]
def _metric_display(values, better, digits=2, mask=None):
"""Display strings for a metric column: fixed decimals, medal on the top 3.
The underlying numeric cell is left untouched (see ``overview_table``), so
the table still sorts on the real value — this only changes what is shown.
"""
ranked = {i: _MEDALS[r] for r, i in enumerate(_medal_ranks(values, better, mask))}
out = []
for i, v in enumerate(values):
text = "—" if pd.isna(v) else f"{v:.{digits}f}"
out.append(f"{ranked[i]} {text}" if i in ranked else text)
return out
# ------------------------------------------------------------------
# Leaderboard tab: one average column per selected language
# ------------------------------------------------------------------
RANK_COL = "Rank"
# Languages scored by Character Error Rate rather than Word Error Rate (matches
# ``normalizer.eval_utils.CJK_LANGUAGES | CHAR_LANGUAGES`` — single source of truth).
# CJK has no word delimiters; Thai too; Persian's are optional (میروم / می روم / میروم)
# so WER would mostly count spelling conventions of the TTS/ASR output.
_CER_LANGS = {
"zh", "cmn", "yue",
"ja", "jpn",
"ko", "kor",
"th",
"fa",
}
def _lang_error_label(code: str) -> str:
return "CER" if code in _CER_LANGS else "WER"
def overview_table(rows, langs, clone):
"""Cross-dataset table: headline averages plus one WER/CER column per language.
UTMOS is English-only (see ``aggregate_rows``), so unlike WER/RTFx/SIM it's
shown and medal-ranked regardless of a row's language coverage. KOMOS is
the same idea for Korean, but — since it's a much newer addition most
users haven't selected Korean for — it only appears once ``"ko"`` is one
of the selected languages, rather than unconditionally like UTMOS.
With more than one language selected, a ``"Coverage"`` column (e.g.
"3/5") shows how many of them a model actually has results for — with
only one language selected every listed model trivially covers it, so
the column would say "1/1" everywhere and isn't shown.
Returns ``(value, types, footnotes)`` — ``footnotes`` is
``[(mark, model, note), ...]`` for every row with a ``"note"``, same shape
and superscript-marking convention as ``streaming_table``.
"""
lang_cols = [f"{lang_flag(c)} {_lang_error_label(c)}" for c in langs] if len(langs) > 1 else []
show_coverage = len(langs) > 1
show_komos = "ko" in langs
columns = (
[RANK_COL, MODEL_COL]
+ ([COVERAGE_COL] if show_coverage else [])
+ [WER_COL, RTFX_COL]
+ ([KOMOS_COL] if show_komos else [])
+ [UTMOS_COL]
+ ([SIM_COL] if clone else [])
+ lang_cols
+ ["Size (B)", "License", "# languages", "Voice cloning", "Batch inference", "Transformers"]
)
if not rows:
df, types = _empty(columns)
return df, types, []
footnotes = []
marks = {}
for row in rows:
if row.get("note") and row["model"] not in marks:
marks[row["model"]] = _FOOTNOTE_MARKS[len(footnotes) % len(_FOOTNOTE_MARKS)]
footnotes.append((marks[row["model"]], row["model"], row["note"]))
records = []
complete_flags = []
# ``rows`` is already sorted (complete-coverage models first, best WER
# first; incomplete-coverage models below, by coverage then by their own
# WER — see ``aggregate_rows``), so position among the *complete* rows is
# the leaderboard rank. A model missing one or more of the selected
# languages still gets a row and a WER (over just the languages it does
# cover), e.g. it may still be the best at one particular language — but
# no rank: that would misleadingly look comparable to a model actually
# scored on the full selection. ``Coverage`` is what makes a partial
# average legible instead of looking like a complete one.
rank = 0
for row in rows:
if row["complete"]:
rank += 1
model_html = clickable_model(row["model"], is_new=row.get("is_new", False))
if row["model"] in marks:
model_html += f"{marks[row['model']]}"
record = {
RANK_COL: rank if row["complete"] else None,
MODEL_COL: model_html,
}
if show_coverage:
covered, total = row["coverage"]
record[COVERAGE_COL] = f"{covered}/{total}"
record[WER_COL] = _round(row["wer"])
record[RTFX_COL] = _round(row["rtfx"])
record[UTMOS_COL] = _round(row["utmos"])
if show_komos:
record[KOMOS_COL] = _round(row["komos"])
if clone:
record[SIM_COL] = _round(row["sim"])
for code, col in zip(langs, lang_cols):
record[col] = _round(row["per_lang"].get(code, {}).get("wer"))
record.update(_info_cells(row["info"]))
records.append(record)
complete_flags.append(row["complete"])
df = pd.DataFrame(records)[columns]
types = [_INFO_TYPES.get(c, "number") for c in columns]
# Medal display strings for rank/model plus every metric column. The
# headline columns only medal among *complete* rows — an incomplete row's
# WER/RTFx/SIM is averaged over just the languages it covers (see
# aggregate_rows), so e.g. a single easy language can give it a better
# number than the real best-of-selection model, which must not steal that
# model's medal. Lang WER columns are the exception: they rank *across
# every row*, complete or not — a model missing other languages can still
# medal on the one it's actually the best at. Only these leading columns
# need a display entry: the frontend falls back to the raw value for any
# column past the end of a row's display-value list. Coverage isn't a
# ranked metric, so its cell is appended plain, ahead of the medalled
# ones, to keep this list's order matching ``columns``.
headline_medal_cols = (
[WER_COL, RTFX_COL] + ([KOMOS_COL] if show_komos else []) + [UTMOS_COL] + ([SIM_COL] if clone else [])
)
rank_display = ["—" if pd.isna(r) else str(int(r)) for r in df[RANK_COL].tolist()]
display = [[r, m] for r, m in zip(rank_display, df[MODEL_COL].tolist())]
if show_coverage:
for row_disp, coverage in zip(display, df[COVERAGE_COL].tolist()):
row_disp.append(coverage)
for col in headline_medal_cols:
better = _METRIC_BETTER.get(col, "min")
texts = _metric_display(df[col].tolist(), better, mask=complete_flags)
for row_disp, text in zip(display, texts):
row_disp.append(text)
for col in lang_cols:
better = _METRIC_BETTER.get(col, "min") # lang WER columns aren't in the map
for row_disp, text in zip(display, _metric_display(df[col].tolist(), better)):
row_disp.append(text)
value = {
"headers": columns,
"data": df.values.tolist(),
"metadata": {"display_value": display},
}
return value, types, footnotes
# ------------------------------------------------------------------
# Streaming tab: CPU / H200 / A100 time-to-first-audio / RTFx
# ------------------------------------------------------------------
# Superscript digits for footnote markers — plenty for how many models could
# realistically carry a Note in one table.
_FOOTNOTE_MARKS = "¹²³⁴⁵⁶⁷⁸⁹"
def streaming_table(rows, mode):
"""Streaming-benchmark table for ``mode`` ("cpu", "h200", or "a100").
A row without a p95 TTFA for this hardware is left out entirely, rather
than shown ranked by p50 alongside rows that do have one — the ranking
(and the bar charts, which reuse this same row set) needs one consistent
measure across every row.
"""
p50_key, p95_key, rtfx_key = f"{mode}_ttfa", f"{mode}_ttfa_p95", f"{mode}_rtfx"
columns = [RANK_COL, MODEL_COL, TTFA_P95_COL, TTFA_P50_COL, STREAM_RTFX_COL,
"Streaming API", "Size (B)"]
measured = sorted(
(r for r in rows if r.get(p95_key) is not None),
key=lambda r: r[p95_key],
)
if not measured:
df, types = _empty(columns)
return df, types, [], []
footnotes = []
marks = {}
for row in measured:
if row.get("note") and row["model"] not in marks:
marks[row["model"]] = _FOOTNOTE_MARKS[len(footnotes) % len(_FOOTNOTE_MARKS)]
footnotes.append((marks[row["model"]], row["model"], row["note"]))
records = []
for i, row in enumerate(measured):
model_html = clickable_model(row["model"], is_new=row.get("is_new", False))
if row["model"] in marks:
model_html += f"{marks[row['model']]}"
record = {
RANK_COL: i + 1,
MODEL_COL: model_html,
}
record[TTFA_P95_COL] = _round(row.get(p95_key), 1)
record[TTFA_P50_COL] = _round(row.get(p50_key), 1)
record[STREAM_RTFX_COL] = _round(row.get(rtfx_key))
record["Streaming API"] = "✅" if row.get("streaming_api") else "—"
record["Size (B)"] = _round(row.get("size"), 4)
records.append(record)
df = pd.DataFrame(records)[columns]
types = [_INFO_TYPES.get(c, "number") for c in columns]
display = [[r, m] for r, m in zip(df[RANK_COL].tolist(), df[MODEL_COL].tolist())]
medal_cols = [(TTFA_P95_COL, "min", 1), (TTFA_P50_COL, "min", 1), (STREAM_RTFX_COL, "max", 2)]
for col, better, digits in medal_cols:
for row_disp, text in zip(display, _metric_display(df[col].tolist(), better, digits)):
row_disp.append(text)
value = {
"headers": columns,
"data": df.values.tolist(),
"metadata": {"display_value": display},
}
return value, types, footnotes, measured
def _streaming_bar_rows(rows, mode):
"""``rows`` reshaped to plain "ttfa"/"rtfx" keys for ``top_bar_plot``.
"ttfa" is p95 — ``rows`` comes from ``streaming_table``, which already
excludes any row without one for this hardware.
"""
p95_key, rtfx_key = f"{mode}_ttfa_p95", f"{mode}_rtfx"
return [
{"model": r["model"], "is_new": r.get("is_new", False),
"ttfa": r.get(p95_key), "rtfx": r.get(rtfx_key)}
for r in rows
]
def _streaming_pareto_rows(rows, mode, version=None):
"""``rows`` (already filtered to this hardware and search term — see
``streaming_table``) paired with CV3-Eval English WER, the main tab's
result with no voice cloning.
Streaming is benchmarked once per model, not per language/dataset (see
``streaming_rows``), so there's no selection to average over the way the
main tab does — CV3-Eval's English split is the fixed quality number
every streaming Pareto plot reads against (it's what STREAMING_TAB_TEXT
says the hardware is timed on).
Looked up by the row's model name with any ``"(...)"`` suffix stripped —
a streaming engine like ``audio.cpp``/``photon`` is its own row here
(different RTFx/TTFA), but was never scored for WER under that engine
tag, only under its plain checkpoint name.
"""
wer_by_model = {
r["model"]: r["wer"]
for r in aggregate_rows(["en"], ["cv3"], clone=False, version=version)
if r["wer"] is not None
}
p95_key, rtfx_key = f"{mode}_ttfa_p95", f"{mode}_rtfx"
out = []
for r in rows:
# First try the model name as-is: a published row that already carries a parenthetical
# (e.g. ``"ampixa/sanoTTS (heart)"``) has its own WER row under that exact name, so
# stripping would miss it. Fall back to the suffix-stripped form only for rows whose
# engine/variant tag isn't scored for WER on its own (e.g. ``"foo (audio.cpp)"``).
wer = wer_by_model.get(r["model"])
if wer is None:
wer = wer_by_model.get(_strip_variant_suffix(r["model"]))
if wer is None:
continue
out.append({"model": r["model"], "wer": wer, "rtfx": r.get(rtfx_key), "ttfa": r.get(p95_key)})
return out
def _streaming_pareto_plots(rows, mode, version=None, highlight=None):
"""WER (CV3-Eval, English) vs this hardware's RTFx and TTFA p95."""
pareto_rows = _streaming_pareto_rows(rows, mode, version)
wer_title = "CV3-Eval WER %, English (lower is better)"
return [
pareto_plot(pareto_rows, "wer", "rtfx", "RTFx", x_title=wer_title, highlight=highlight),
pareto_plot(pareto_rows, "wer", "ttfa", "TTFA p95 (ms)", x_title=wer_title, highlight=highlight),
]
# ------------------------------------------------------------------
# Pareto plots
# ------------------------------------------------------------------
def _pareto_mask(x, y, x_better, y_better):
"""Boolean mask of non-dominated points.
``x_better`` / ``y_better`` are "min" or "max"; a point is dominated when
another point is at least as good on both axes and strictly better on one.
"""
xs = np.array(x, dtype=float) * (1 if x_better == "min" else -1)
ys = np.array(y, dtype=float) * (1 if y_better == "min" else -1)
keep = np.ones(len(xs), dtype=bool)
for i in range(len(xs)):
for j in range(len(xs)):
if i == j:
continue
if xs[j] <= xs[i] and ys[j] <= ys[i] and (xs[j] < xs[i] or ys[j] < ys[i]):
keep[i] = False
break
return keep
def _add_metric_traces(fig, names, x, y, *, x_better, y_better, label, color,
symbol, hover_fmt, highlight=None):
"""Scatter one metric plus its Pareto frontier (labelled, dashed line).
``highlight``, if given, is a set/list of exact model names: those models
get a bigger crimson marker and an always-on name label whether or not they
sit on the frontier — everything else keeps its usual look and still shows
its name on hover. Modelled on the Open ASR Leaderboard's Pareto highlight.
"""
if not names:
return
highlight = set(highlight or [])
x = np.asarray(x, dtype=float)
y = np.asarray(y, dtype=float)
keep = _pareto_mask(x, y, x_better, y_better)
front = np.where(keep)[0]
rest = np.where(~keep)[0]
front = front[np.argsort(x[front])]
# Non-frontier points split into plain (faint, no label) and highlighted
# (crimson, labelled). Frontier points are already labelled; highlighted
# ones there just switch to the crimson marker + label colour.
rest_plain = [i for i in rest if names[i] not in highlight]
rest_hl = [i for i in rest if names[i] in highlight]
if rest_plain:
fig.add_trace(go.Scatter(
x=x[rest_plain], y=y[rest_plain], mode="markers",
marker=dict(size=9, color=color, opacity=0.35, symbol=symbol),
text=[names[i] for i in rest_plain],
hovertemplate=hover_fmt,
name=f"{label} — other models",
))
if rest_hl:
fig.add_trace(go.Scatter(
x=x[rest_hl], y=y[rest_hl], mode="markers+text",
marker=dict(size=13, color=HIGHLIGHT_COLOR, symbol=symbol,
line=dict(width=1.5, color="white")),
text=[names[i] for i in rest_hl],
textposition="top center",
textfont=dict(size=9, color=HIGHLIGHT_COLOR),
hovertemplate=hover_fmt,
name=f"{label} — highlighted",
))
front_names = [names[i] for i in front]
front_colors = [HIGHLIGHT_COLOR if n in highlight else color for n in front_names]
fig.add_trace(go.Scatter(
x=x[front], y=y[front], mode="markers+text+lines",
marker=dict(size=[14 if n in highlight else 12 for n in front_names],
color=front_colors, symbol=symbol,
line=dict(width=1, color="white")),
line=dict(dash="dash", color=color, width=1),
text=front_names,
textposition="top center",
textfont=dict(size=9, color=front_colors),
hovertemplate=hover_fmt,
name=f"{label} — Pareto frontier",
))
WER_COLOR = "#2563eb"
SIM_COLOR = "#d97706"
# Marker/label colour for a model picked in the Pareto "Highlight models" box.
HIGHLIGHT_COLOR = "#dc2626"
# The quality metric on the x-axis: which direction is better, how to label and
# format it, and whether the axis is log-scaled.
_METRICS = {
"wer": dict(label="WER", better="min", color=WER_COLOR, symbol="circle",
axis_title="Average ER % (lower is better)",
hover="WER: %{x:.2f} %", log=True),
"sim": dict(label="SIM", better="max", color=SIM_COLOR, symbol="diamond",
axis_title="Average SIM (higher is better)",
hover="SIM: %{x:.2f}", log=False),
}
def pareto_plot(rows, metric, y_key, y_title, log_y=True, x_title=None, highlight=None):
"""Quality metric (x) vs ``y_key`` (y), with the Pareto frontier highlighted.
``metric`` is ``"wer"`` or ``"sim"``. ``y_key`` is ``"rtfx"`` or ``"size"``
(read from ``row["info"]``) — both higher/smaller-is-better respectively —
or anything else, read straight off the row (e.g. ``"ttfa"``, lower is
better), for callers whose rows aren't shaped like ``aggregate_rows``'s.
``x_title`` overrides the metric's default axis label, for a caller whose
rows aren't an average over the full selection (see ``_streaming_pareto_rows``).
"""
spec = _METRICS[metric]
y_better = "max" if y_key == "rtfx" else "min"
names, xs, ys = [], [], []
for row in rows:
if y_key == "rtfx":
yv = row["rtfx"]
elif y_key == "size":
yv = row["info"].get("size")
else:
yv = row.get(y_key)
xv = row[metric]
if xv is None or yv is None or yv <= 0:
continue
names.append(row["model"])
xs.append(xv)
ys.append(yv)
fig = go.Figure()
_add_metric_traces(
fig, names, xs, ys, x_better=spec["better"], y_better=y_better,
label=spec["label"], color=spec["color"], symbol=spec["symbol"],
hover_fmt="%{text}
" + spec["hover"] + "
" + y_title
+ ": %{y:.2f}",
highlight=highlight,
)
fig.update_layout(
title=f"{y_title} vs {spec['label']}",
xaxis=dict(title=x_title or spec["axis_title"], type="log" if spec["log"] else "linear"),
yaxis=dict(title=f"{y_title} ({'higher' if y_better == 'max' else 'lower'} is better)",
type="log" if log_y else "linear"),
**_PLOT_LAYOUT,
)
if not names:
fig.add_annotation(text="No models match the current selection",
showarrow=False, font=dict(size=14, color="#6b7280"))
return fig
# ------------------------------------------------------------------
# Ranking bar charts
# ------------------------------------------------------------------
# Every model with a value for the metric, ranked column, best on the left,
# one metric per figure (same idea — and palette — the Open ASR Leaderboard's
# own ranking bar chart borrowed from here:
# https://huggingface.co/spaces/hf-audio/open_asr_leaderboard). Bars are
# coloured by the model's company; the value sits on each cap, which lets the
# value axis go away entirely. Identity never rests on colour alone — the
# tick label names the model and the legend names the company.
_BAR_METRICS = {
"wer": dict(label="WER", better="min", fmt="{:.2f}",
subtitle="Average ER % · lower is better"),
"rtfx": dict(label="RTFx", better="max", fmt="{:.1f}",
subtitle="Average RTFx · higher is better"),
"sim": dict(label="SIM", better="max", fmt="{:.2f}",
subtitle="Average speaker similarity · higher is better"),
"utmos": dict(label="UTMOS (en)", better="max", fmt="{:.2f}",
subtitle="Average UTMOS (en) · higher is better (1-5)"),
"komos": dict(label="KOMOS (ko)", better="max", fmt="{:.2f}",
subtitle="Average KOMOS (ko) · higher is better (1-5)"),
"ttfa": dict(label="TTFA", better="min", fmt="{:.0f}",
subtitle="Median time-to-first-audio (ms) · lower is better"),
}
# Headline fields shown in a bar's hover breakdown, in order, whenever the
# row actually carries them — (row key, label, format). Every bar chart shows
# the same full breakdown regardless of which metric it's plotting, so
# hovering any one bar answers "how does this model do overall", not just on
# this chart's own axis.
_HOVER_HEADER_FIELDS = [
("wer", "Average ER", "{:.2f} %"),
("rtfx", "RTFx", "{:.2f}"),
("komos", "KOMOS (ko)", "{:.2f}"),
("utmos", "UTMOS (en)", "{:.2f}"),
("sim", "Average SIM", "{:.2f}"),
("ttfa", "TTFA (p95)", "{:.0f} ms"),
]
# ------------------------------------------------------------------
# Bar colour per company
# ------------------------------------------------------------------
# Named colours, so COMPANY_COLORS below reads as intent rather than hex. Tune a
# shade here and every company using it follows.
BAR_COLORS = {
"green": "#16a34a",
"blue": "#1d4ed8",
"royal blue": "#4169e1",
"light blue": "#38bdf8",
"purple": "#7c3aed",
"yellow": "#eab308",
"orange": "#f97316",
"red": "#dc2626",
"turquoise": "#14b8a6",
"black": "#111827",
"beige": "#c8a97e",
}
# HF org -> colour name. A company not listed here falls back to OTHER_HUE, so
# adding one is a single line. Two companies may deliberately share a colour.
COMPANY_COLORS = {
"nvidia": "green",
"facebook": "blue",
"Qwen": "purple",
"FunAudioLLM": "purple",
"bosonai": "green",
"microsoft": "yellow",
"Supertone": "royal blue",
"hexgrad": "black",
"fishaudio": "red",
"k2-fsa": "blue",
"kyutai": "turquoise",
"ResembleAI": "turquoise",
"OpenMOSS-Team": "light blue",
"openbmb": "blue",
"neuphonic": "red",
"sesame": "black",
"owensong": "beige",
"mistralai": "orange",
"BreezeBlue": "blue",
}
# Every company without an entry above.
OTHER_HUE = "#9ca3af"
# Values and axis labels are ink, never a bar colour.
_INK = "#374151"
_MUTED = "#6b7280"
# Org names are matched case-insensitively, so "NVIDIA" in the results still
# finds the "nvidia" entry.
_COMPANY_HUE = {c.lower(): BAR_COLORS[name] for c, name in COMPANY_COLORS.items()}
def company_hue(model: str) -> str:
"""Bar colour for a model, from its company."""
return _COMPANY_HUE.get(company_of(model).lower(), OTHER_HUE)
def _short_label(model: str, limit: int = 16) -> str:
"""Column tick label: drop the org prefix, ellipsize — hover has the full id."""
name = model.split("/", 1)[-1]
return name if len(name) <= limit else name[: limit - 1] + "…"
def _bar_title(text: str, subtitle: str) -> dict:
return dict(
text=f"{text}
{subtitle}",
x=0.0, xanchor="left", font=dict(size=15, color="#111827"),
)
# Fixed width for the right-aligned value block in a bar's hover breakdown
# (see _hover_line) — wide enough for a value plus its unit. Relies on a
# monospace hoverlabel font (set in top_bar_plot) to actually line up.
_HOVER_VALUE_WIDTH = 10
def _hover_line(label: str, value_text: str, label_width: int, medal: str = "", bold=False) -> str:
"""One column-aligned hover line: the label left-aligned, a 'medal value'
block right-aligned — the medal (🥇🥈🥉, when this row is top-3 on this
metric — see ``_bar_medal_maps``) sits to the *left* of the value, so the
value's own digits land in the same column across rows whether or not
there's a medal. Same convention as the Open ASR Leaderboard's bar-hover
breakdown (https://huggingface.co/spaces/hf-audio/open_asr_leaderboard).
"""
value_block = f"{medal} {value_text}" if medal else value_text
# A medal emoji renders about one column wider than its string length
# accounts for, which would otherwise push medal rows' numbers past the
# non-medal rows' right edge — compensate.
pad_width = _HOVER_VALUE_WIDTH - (1 if medal else 0)
line = f"{label.ljust(label_width)}{value_block.rjust(pad_width)}"
return f"{line}" if bold else line
def _bar_medal_maps(rows: list[dict], show_komos: bool) -> dict:
"""``{key: {id(row): medal}}`` — the top-3 🥇🥈🥉 ranking for every
headline metric these rows carry, plus one more for each language any
row has a result for (keyed ``"lang:"``). Computed over exactly
``rows`` — the ranked/complete models a bar chart actually plots — so a
medal here means "top 3 among the models shown on this chart", the same
idea as the table's own medal columns (see ``overview_table``).
"""
maps = {}
for key, spec in _BAR_METRICS.items():
if key == "komos" and not show_komos:
continue
values = [r.get(key) for r in rows]
ranks = _medal_ranks(values, spec["better"])
if ranks:
maps[key] = {id(rows[i]): _MEDALS[rank] for rank, i in enumerate(ranks)}
langs = {code for r in rows for code in (r.get("per_lang") or {})}
for code in langs:
values = [(r.get("per_lang") or {}).get(code, {}).get("wer") for r in rows]
ranks = _medal_ranks(values, "min")
if ranks:
maps[f"lang:{code}"] = {id(rows[i]): _MEDALS[rank] for rank, i in enumerate(ranks)}
return maps
def _model_hover_text(row: dict, show_komos: bool = True, medal_maps: dict | None = None) -> str:
"""Full per-model breakdown for a bar's hover: the model name, then every
headline metric the row actually carries (WER, RTFx, KOMOS, UTMOS, SIM,
TTFA — whichever apply), then one WER/CER line per language the row has
a result for — each medalled if it's top-3 (see ``_bar_medal_maps``) —
mirroring the Open ASR Leaderboard's bar-hover breakdown
(https://huggingface.co/spaces/hf-audio/open_asr_leaderboard).
``show_komos`` mirrors the table's own KOMOS column (see
``overview_table``): KOMOS is left out of the breakdown entirely unless
Korean is one of the selected languages, same as everywhere else it
appears.
"""
medal_maps = medal_maps or {}
header = [
(label, fmt.format(row[key]), medal_maps.get(key, {}).get(id(row), ""))
for key, label, fmt in _HOVER_HEADER_FIELDS
if row.get(key) is not None and (key != "komos" or show_komos)
]
per_lang = row.get("per_lang") or {}
lang_lines = [
(f"{lang_flag(code)} {_lang_error_label(code)}", f"{vals['wer']:.2f}",
medal_maps.get(f"lang:{code}", {}).get(id(row), ""))
for code, vals in per_lang.items()
if vals.get("wer") is not None
]
label_width = max((len(l) for l, _, _ in header + lang_lines), default=0) + 2
lines = [f"{row['model']}", ""]
lines += [_hover_line(label, value, label_width, medal, bold=True) for label, value, medal in header]
if lang_lines:
lines.append("")
lines += [_hover_line(label, value, label_width, medal) for label, value, medal in lang_lines]
return "
".join(lines)
def top_bar_plot(rows, metric, subtitle=None, show_komos=True, top_n=None):
"""Ranked column per model with a value for ``metric``, best on the left,
limited to the best ``top_n`` (every one of them if ``top_n`` is falsy) —
some bars are much shorter than others once every model is plotted, so a
slider lets the user trade "see everyone" for "keep the short bars
legible" (see the size slider next to this one in app.py).
Hovering a bar shows that model's full breakdown — every headline metric
the row carries plus a per-language line — not just this chart's own
value (see ``_model_hover_text``). ``show_komos`` is forwarded to that
breakdown so KOMOS stays out of every chart's hover, not just its own,
whenever Korean isn't one of the selected languages.
``subtitle`` overrides ``_BAR_METRICS[metric]``'s default, for a metric
whose meaning shifts with context (e.g. streaming TTFA is p95, not the
median the default subtitle describes — see ``_streaming_bar_rows``).
"""
spec = _BAR_METRICS[metric]
subtitle = subtitle or spec["subtitle"]
scored = [r for r in rows if r.get(metric) is not None]
scored.sort(key=lambda r: r[metric], reverse=spec["better"] == "max")
if top_n:
scored = scored[:top_n]
fig = go.Figure()
if not scored:
fig.update_layout(
title=_bar_title(f"Models by {spec['label']}", subtitle),
xaxis=dict(visible=False), yaxis=dict(visible=False),
template="plotly_white", height=280, margin=dict(l=10, r=20, t=70, b=20),
)
fig.add_annotation(text="No models match the current selection",
showarrow=False, font=dict(size=14, color=_MUTED))
return fig
names = [r["model"] for r in scored]
values = [r[metric] for r in scored]
is_new = [bool(r.get("is_new")) for r in scored]
any_new = any(is_new)
medal_maps = _bar_medal_maps(scored, show_komos)
hover_texts = [_model_hover_text(r, show_komos, medal_maps) for r in scored]
# Integer positions (not the labels) keep two models that shorten to the same
# name from collapsing onto one column.
positions = list(range(len(names)))
# Models added in the last two weeks get a small green "NEW" above the value.
cap_texts = [
('NEW
' if new else "") + spec["fmt"].format(v)
for v, new in zip(values, is_new)
]
# One trace with a colour per bar: the company is read off the column's own
# label, so no legend is needed to tell them apart.
fig.add_trace(go.Bar(
x=positions, y=values,
marker=dict(color=[company_hue(m) for m in names], cornerradius=4),
text=cap_texts,
textposition="outside",
textfont=dict(size=11, color=_INK),
cliponaxis=False,
hovertext=hover_texts,
hovertemplate="%{hovertext}",
# Monospace so the hand-padded label/value columns in each hover line
# (see _hover_line) actually line up.
hoverlabel=dict(font=dict(family="Menlo, Consolas, monospace", size=11), align="left"),
))
# When a NEW cap sits above the value it needs an extra line of headroom;
# bump the y-range cap so the tallest column + its cap stay inside the plot.
y_pad = 1.30 if any_new else 1.18
new_subtitle = subtitle + (" · NEW = added in the last 2 weeks" if any_new else "")
fig.update_layout(
title=_bar_title(f"Top {len(names)} by {spec['label']}", new_subtitle),
# The explicit range pads both ends: without it the first and last
# columns (and their rotated labels) sit on the plot edge and clip.
xaxis=dict(tickmode="array", tickvals=positions,
ticktext=[_short_label(n) for n in names],
range=[-0.7, len(names) - 0.3],
tickangle=-60, automargin=True, showgrid=False,
tickfont=dict(size=10, color=_INK)),
# Every column is labelled, so the value axis carries nothing — drop it and
# leave headroom for the caps.
yaxis=dict(visible=False, range=[0, max(values) * y_pad]),
# Each position holds exactly one column: overlay keeps it full width
# instead of reserving a slot per company.
bargap=0.3,
template="plotly_white",
hovermode="closest",
showlegend=False,
height=440,
margin=dict(l=40, r=30, t=80, b=20),
)
return fig
def _top_bar_plots(rows, clone, show_komos, top_n=None):
"""WER, RTFx, optionally KOMOS, then UTMOS, plus SIM when scoring
voice-cloning runs. KOMOS sits ahead of UTMOS — same ordering as its
table column — and only appears once Korean is one of the selected
languages (see ``overview_table``)."""
return [
top_bar_plot(rows, "wer", show_komos=show_komos, top_n=top_n),
top_bar_plot(rows, "rtfx", show_komos=show_komos, top_n=top_n),
top_bar_plot(rows, "komos", show_komos=show_komos, top_n=top_n) if show_komos else None,
top_bar_plot(rows, "utmos", show_komos=show_komos, top_n=top_n),
top_bar_plot(rows, "sim", show_komos=show_komos, top_n=top_n) if clone else None,
]
def _pareto_plots(rows, clone, highlight=None):
"""WER plots, plus the SIM pair when scoring voice-cloning runs."""
figs = [
pareto_plot(rows, "wer", "rtfx", "RTFx", highlight=highlight),
pareto_plot(rows, "wer", "size", "Model size (B params)", highlight=highlight),
]
figs += [
pareto_plot(rows, "sim", "rtfx", "RTFx", highlight=highlight) if clone else None,
pareto_plot(rows, "sim", "size", "Model size (B params)", highlight=highlight) if clone else None,
]
return figs
# ------------------------------------------------------------------
# Callback entry points
# ------------------------------------------------------------------
def _filter_table_rows(value, keep_mask):
"""Keep only the rows flagged in ``keep_mask`` (aligned with the rows
``overview_table`` built ``value`` from).
Applied *after* ``overview_table``, so a search that narrows which rows
are shown never disturbs the Rank number or medals it already assigned —
those reflect the full, unfiltered standings.
"""
if isinstance(value, pd.DataFrame):
return value # already empty — nothing to filter
return {
"headers": value["headers"],
"data": [row for row, keep in zip(value["data"], keep_mask) if keep],
"metadata": {
"display_value": [
row for row, keep in zip(value["metadata"]["display_value"], keep_mask) if keep
],
},
}
def leaderboard_view(version, search, lang_displays, dataset_labels, clone, max_size=None, top_n=None, highlight=None):
"""Main tab: table + Pareto plots for the current selection of ``version``.
``max_size`` narrows by the model-size slider the same way ``search``
narrows by name — after ``overview_table`` so Rank still reflects the
full selection, not just what's left once oversized models are hidden.
``top_n`` only limits the bar charts (see ``top_bar_plot``) — the table
and Pareto plots are unaffected.
"""
langs = codes_from_display(lang_displays)
keys = keys_from_labels(dataset_labels)
all_rows = aggregate_rows(langs, keys, clone, version) if langs and keys else []
value, types, footnotes = overview_table(all_rows, langs, clone)
keep_mask = [
matches_search(r["model"], search) and matches_size(r["info"].get("size"), max_size)
for r in all_rows
]
value = _filter_table_rows(value, keep_mask)
rows = [r for r, keep in zip(all_rows, keep_mask) if keep]
matched_models = {r["model"] for r in rows}
footnotes = [f for f in footnotes if f[1] in matched_models]
footnote_text = ""
if footnotes:
footnote_text = "**Notes:**\n\n" + "\n\n".join(
f"{mark} {model} — {note}" for mark, model, note in footnotes
)
# Pareto/bar plots are a ranked comparison, same as the table's Rank
# column, so they're built from *complete* rows only — an incomplete
# row's WER/RTFx/SIM is averaged over just the languages it covers (see
# aggregate_rows), not comparable to a full-selection average, and
# including it would crowd out the actual best-of-selection models.
ranked_rows = [r for r in rows if r["complete"]]
return (
value, types,
*_pareto_plots(ranked_rows, clone, highlight),
*_top_bar_plots(ranked_rows, clone, "ko" in langs, top_n),
_caption(rows, langs, keys, clone, version),
footnote_text,
)
def streaming_view(mode, version=None, search=None, top_n=None, highlight=None):
"""Streaming tab: table, WER-vs-streaming Pareto plots, and top-N TTFA/RTFx
bar charts, for ``mode`` ("cpu", "h200", or "a100")."""
rows = streaming_rows(version)
value, types, footnotes, measured = streaming_table(rows, mode)
keep_mask = [matches_search(r["model"], search) for r in measured]
value = _filter_table_rows(value, keep_mask)
matched = [r for r, keep in zip(measured, keep_mask) if keep]
matched_models = {r["model"] for r in matched}
footnotes = [f for f in footnotes if f[1] in matched_models]
bar_rows = _streaming_bar_rows(matched, mode)
ttfa_subtitle = "95th-percentile time-to-first-audio (ms) · lower is better"
footnote_text = ""
if footnotes:
footnote_text = "**Notes:**\n\n" + "\n\n".join(
f"{mark} {model} — {note}" for mark, model, note in footnotes
)
return (
value, types,
*_streaming_pareto_plots(matched, mode, version, highlight),
top_bar_plot(bar_rows, "ttfa", subtitle=ttfa_subtitle, top_n=top_n),
top_bar_plot(bar_rows, "rtfx", top_n=top_n),
footnote_text,
)
def _caption(rows, langs, keys, clone, version=None):
"""``keys`` is every selected dataset, but only the ones that actually
cover one of ``langs`` are named in the "averaged over" list — a dataset
selected alongside others but covering none of the chosen languages
contributes nothing to the average, so naming it would be misleading
(e.g. Seed-TTS/CV3-Eval checked but Portuguese selected: only MiniMax
covers it).
"""
if not langs:
return "⚠️ Select at least one language."
if not keys:
return "⚠️ Select at least one dataset."
names = ", ".join(lang_display(c) for c in langs)
coverage = dataset_language_coverage(keys, clone, version)
relevant = [k for k in keys if set(coverage[k]) & set(langs)]
if not relevant:
return f"⚠️ No selected dataset covers {names}."
datasets = ", ".join(DATASET_BY_KEY[k]["label"] for k in relevant)
mode = "with voice cloning" if clone else "without voice cloning"
complete = sum(1 for r in rows if r["complete"])
return (
f"**{complete} model(s)** evaluated on **all** of {names} across "
f"**every** selected dataset — averaged over {datasets}, {mode}."
)