Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 17,279 Bytes
5f0f535 | 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | """
Plotly charts for the Analysis tab's Diarization section.
Chosen to answer the questions diarization users actually ask:
* Who is best overall? -> ranked Avg DER / JER bars
* Where do a model's errors come from? -> missed / false-alarm / confusion breakdown
* How much does overlapping speech hurt? -> without-vs-with overlap dumbbell
* How much does noise hurt? -> High / Mid / Low SNR dumbbell
* How does it degrade with noise? -> model x (SNR x overlap) heatmap
* Does it find the right number of talkers? -> speaker-count accuracy bars
* Accuracy vs speed trade-off -> Pareto front (Avg DER vs RTFx)
"""
from __future__ import annotations
import pandas as pd
import plotly.graph_objects as go
import analytics
import diarization_results as dr
from diarization_config import (
CONDITIONS,
METRICS_BY_KEY,
OVERLAP_LABELS,
RANK_METRICS,
SNR_LEVELS,
metric_column,
overlaps_for_view,
view_label,
)
_FIG_HEIGHT = 460
# Shared transparent / theme-neutral template (works in light and dark mode).
_TEMPLATE = analytics._TEMPLATE
_NO_DATA = "No diarization results yet. Submit a model with the task 'Speaker diarization'."
# Figure memo (P3-3): every ``plot_*`` below is wrapped with ``analytics.memo_figure``;
# keys are a digest of ``rows`` plus the plot args, hits return deep copies.
memo_figure = analytics.memo_figure
_COMPONENT_STYLE: tuple[tuple[str, str, str], ...] = (
("miss", "Missed speech", analytics.SERIES_BLUE),
("fa", "False alarm", analytics.SERIES_ORANGE),
("conf", "Speaker confusion", analytics.SERIES_AQUA),
)
_NOOVL_COLOR = analytics.SERIES_BLUE
_OVL_COLOR = analytics.SERIES_ORANGE
def _metric(metric: str) -> str:
return metric if metric in RANK_METRICS else "der"
def _pct(v: float | None) -> float | None:
return None if v is None else v * 100.0
def _ranked(rows: list[dict], metric: str, view: str, top_n: int) -> list[tuple[dict, float]]:
"""Rows with a value for ``metric`` in ``view``, best first, capped at ``top_n``."""
overlaps = overlaps_for_view(view)
scored = [(r, v) for r in rows if (v := dr.metric_mean(r, metric, overlaps=overlaps)) is not None]
scored.sort(key=lambda t: t[1])
return scored[: max(1, int(top_n))]
def _short(model_id: str, n: int = 32) -> str:
"""Single-id truncation; use ``_shorts`` for a set so labels stay unique."""
return analytics._short_model_label(model_id, n)
def _shorts(model_ids: list[str], n: int = 32) -> list[str]:
"""Unique short labels (see ``analytics.unique_short_labels``), parallel to ``model_ids``."""
return analytics.short_labels(model_ids, n)
def m_short_view(metric: str, view: str) -> str:
"""'DER, all conditions' style prefix for chart subtitles."""
return f"{METRICS_BY_KEY[_metric(metric)].short}, {view_label(view).lower()}"
def _hbar_height(n: int) -> int:
return int(min(900, max(_FIG_HEIGHT, 120 + 28 * n)))
@memo_figure
def plot_avg_bars(rows: list[dict], metric: str = "der", view: str = "all", top_n: int = 10) -> go.Figure:
metric = _metric(metric)
ranked = _ranked(rows, metric, view, top_n)
if not ranked:
return analytics._empty_fig(_NO_DATA)
m = METRICS_BY_KEY[metric]
ids = [r["model_id"] for r, _ in ranked]
return analytics._plot_ranked_bars(
labels=_shorts(ids, 26),
values=[v * 100.0 for _, v in ranked],
model_ids=ids,
title=f"Average {m.short}",
subtitle=f"Mean {m.short} ({view_label(view).lower()}). Lower is better.",
value_fmt="{:.1f}%",
hover_value_fmt="%{x:.2f}%",
hover_metric_label=f"Average {m.short}",
)
@memo_figure
def plot_error_breakdown(rows: list[dict], view: str = "all", top_n: int = 10) -> go.Figure:
"""Stacked horizontal bars: DER split into missed / false alarm / confusion."""
ranked = _ranked(rows, "der", view, top_n)
if not ranked:
return analytics._empty_fig(_NO_DATA)
overlaps = overlaps_for_view(view)
ids = [r["model_id"] for r, _ in ranked]
labels = _shorts(ids)
fig = go.Figure()
for comp, name, color in _COMPONENT_STYLE:
vals = [_pct(dr.metric_mean(r, comp, overlaps=overlaps)) for r, _ in ranked]
fig.add_trace(
go.Bar(
y=labels,
x=vals,
name=name,
orientation="h",
marker=dict(color=color, line=dict(width=2, color="rgba(255,255,255,0.9)")),
customdata=ids,
hovertemplate=f"<b>%{{customdata}}</b><br>{name}: %{{x:.2f}}%<extra></extra>",
)
)
title_d, top = analytics.chart_title(
"Where the DER comes from",
f"Missed speech, false alarms and speaker confusion add up to DER ({view_label(view).lower()}).",
)
fig.update_layout(
barmode="stack",
title=title_d,
xaxis=dict(rangemode="tozero", ticksuffix="%"),
yaxis=dict(autorange="reversed", automargin=True, showgrid=False),
template=_TEMPLATE,
height=_hbar_height(len(ranked)),
margin=dict(l=8, r=16, t=top + analytics.LEGEND_ROW, b=40),
bargap=0.45,
legend=dict(analytics.LEGEND_TOP, traceorder="normal"),
)
return fig
@memo_figure
def plot_overlap_dumbbell(rows: list[dict], metric: str = "der", top_n: int = 10) -> go.Figure:
"""Per model: without-overlap vs with-overlap metric joined by a line (gap = overlap cost)."""
metric = _metric(metric)
pairs = []
for r in rows:
a = dr.metric_mean(r, metric, overlaps=("noovl",))
b = dr.metric_mean(r, metric, overlaps=("ovl",))
if a is not None and b is not None:
pairs.append((r["model_id"], a * 100.0, b * 100.0))
if not pairs:
return analytics._empty_fig(
"This chart needs models with results for the without-overlap and with-overlap splits."
)
pairs.sort(key=lambda t: (t[1] + t[2]) / 2.0)
pairs = pairs[: max(1, int(top_n))]
labels = _shorts([p[0] for p in pairs])
m = METRICS_BY_KEY[metric]
fig = go.Figure()
xs: list[float | None] = []
ys: list[str | None] = []
for label, (_, a, b) in zip(labels, pairs):
xs += [a, b, None]
ys += [label, label, None]
fig.add_trace(
go.Scatter(
x=xs, y=ys, mode="lines", line=dict(color=analytics.NEUTRAL_LINE, width=2),
hoverinfo="skip", showlegend=False,
)
)
for idx, (name, color, symbol) in enumerate(
((OVERLAP_LABELS["noovl"], _NOOVL_COLOR, "circle"), (OVERLAP_LABELS["ovl"], _OVL_COLOR, "diamond"))
):
fig.add_trace(
go.Scatter(
x=[p[1 + idx] for p in pairs],
y=labels,
mode="markers",
name=name,
marker=dict(size=11, color=color, symbol=symbol, line=dict(width=1.5, color="rgba(255,255,255,0.85)")),
customdata=[[p[0], p[2] - p[1]] for p in pairs],
hovertemplate=(
f"<b>%{{customdata[0]}}</b><br>{name}: %{{x:.2f}}%"
"<br>Overlap Δ: %{customdata[1]:+.2f} pp<extra></extra>"
),
)
)
title_d, top = analytics.chart_title(
"How much overlapping talkers hurt",
f"{m.short} without and with overlapping speech. A longer line means a bigger drop.",
)
fig.update_layout(
title=title_d,
xaxis=dict(rangemode="tozero", ticksuffix="%"),
yaxis=dict(autorange="reversed", automargin=True, showgrid=False),
template=_TEMPLATE,
height=_hbar_height(len(pairs)),
margin=dict(l=8, r=16, t=top + analytics.LEGEND_ROW, b=40),
legend=analytics.LEGEND_TOP,
)
return fig
@memo_figure
def plot_snr_dumbbell(rows: list[dict], metric: str = "der", view: str = "all", top_n: int = 10) -> go.Figure:
"""Per top-N model: High → Mid → Low SNR metric for the selected overlap view."""
metric = _metric(metric)
overlaps = overlaps_for_view(view)
ids: list[str] = []
per_snr: list[list[float]] = [[] for _ in SNR_LEVELS]
for r, _ in _ranked(rows, metric, view, top_n):
vals = [dr.metric_mean(r, metric, snrs=(snr,), overlaps=overlaps) for snr, _ in SNR_LEVELS]
if all(v is not None for v in vals):
ids.append(r["model_id"])
for col, v in zip(per_snr, vals):
col.append(v * 100.0)
if not ids:
return analytics._empty_fig(_NO_DATA)
m = METRICS_BY_KEY[metric]
return analytics.plot_condition_dumbbell(
ids,
[(label, col) for (_, label), col in zip(SNR_LEVELS, per_snr)],
metric_label=m.short,
title="How much each model degrades in noise",
subtitle=f"{m.short} from high to low SNR ({view_label(view).lower()}), sorted by Low SNR.",
)
@memo_figure
def plot_condition_heatmap(rows: list[dict], metric: str = "der", top_n: int = 10) -> str:
"""Models x 6 conditions (SNR level x overlap) HTML heatmap, sorted by the all-conditions average."""
metric = _metric(metric)
ranked = _ranked(rows, metric, "all", top_n)
if not ranked:
return analytics.empty_html(_NO_DATA)
m = METRICS_BY_KEY[metric]
x_labels = [c.short for c in CONDITIONS]
ids = [r["model_id"] for r, _ in ranked]
z = [[_pct(dr.num_or_none(r.get(metric_column(metric, c.key)))) for c in CONDITIONS] for r, _ in ranked]
finite = [v for row in z for v in row if v is not None]
zmax = max(25.0, float(pd.Series(finite).quantile(0.95)) if finite else 100.0)
return analytics.heatmap_html(
z,
x_labels,
ids,
_shorts(ids, 40),
zmax=zmax,
unit="%",
title=f"{m.short} by SNR and overlap",
subtitle=f"Top {len(ranked)} models in all six conditions. Bold marks the best model in each condition.",
)
@memo_figure
def plot_speaker_count(rows: list[dict], top_n: int = 10) -> go.Figure:
"""Grouped bars: share of recordings with the correct speaker count, per overlap split."""
ranked = _ranked(rows, "der", "all", top_n)
ranked = [(r, v) for r, v in ranked if dr.metric_mean(r, "spkacc") is not None]
if not ranked:
return analytics._empty_fig("No speaker-count results yet.")
labels = _shorts([r["model_id"] for r, _ in ranked], 22)
fig = go.Figure()
for ovl, color in (("noovl", _NOOVL_COLOR), ("ovl", _OVL_COLOR)):
name = OVERLAP_LABELS[ovl]
fig.add_trace(
go.Bar(
y=labels,
x=[_pct(dr.metric_mean(r, "spkacc", overlaps=(ovl,))) for r, _ in ranked],
orientation="h",
name=name,
marker=dict(color=color, cornerradius=3),
customdata=[r["model_id"] for r, _ in ranked],
hovertemplate=f"<b>%{{customdata}}</b><br>{name}: %{{x:.1f}}%<extra></extra>",
)
)
title_d, top = analytics.chart_title(
"Speaker counting",
"How often the model finds the right number of talkers. Higher is better.",
wrap=60,
)
fig.update_layout(
barmode="group",
title=title_d,
xaxis=dict(range=[0, 105], ticksuffix="%"),
yaxis=dict(autorange="reversed", automargin=True, showgrid=False),
template=_TEMPLATE,
height=_hbar_height(len(ranked)),
margin=dict(l=8, r=16, t=top + analytics.LEGEND_ROW, b=40),
bargap=0.35,
bargroupgap=0.12,
legend=analytics.LEGEND_TOP,
)
return fig
@memo_figure
def plot_pareto(
rows: list[dict], metric: str = "der", view: str = "all", highlight: list[str] | tuple = ()
) -> go.Figure:
metric = _metric(metric)
overlaps = overlaps_for_view(view)
recs = [
{
"model_id": r["model_id"],
"avg_wer": dr.metric_mean(r, metric, overlaps=overlaps),
"eval_rtf": dr.num_or_none(r.get("eval_rtf")),
}
for r in rows
]
df = pd.DataFrame(recs, columns=["model_id", "avg_wer", "eval_rtf"])
m = METRICS_BY_KEY[metric]
return analytics.plot_pareto_frontier(
df,
title="Accuracy vs speed",
metric_label=f"Average {m.short}",
highlight=highlight,
)
@memo_figure
def plot_snr_race(rows: list[dict], metric: str = "der", view: str = "all", top_n: int = 10) -> go.Figure:
"""Ranking race High → Mid → Low SNR for the selected overlap view."""
metric = _metric(metric)
overlaps = overlaps_for_view(view)
complete = []
for r, _ in _ranked(rows, metric, view, top_n):
vals = [dr.metric_mean(r, metric, snrs=[s], overlaps=overlaps) for s, _ in SNR_LEVELS]
if all(v is not None for v in vals):
complete.append((r["model_id"], [v * 100.0 for v in vals]))
if not complete:
return analytics._empty_fig(_NO_DATA)
return analytics.plot_ranking_race(
[mid for mid, _ in complete],
[(label, [vals[i] for _, vals in complete]) for i, (_, label) in enumerate(SNR_LEVELS)],
metric_label=METRICS_BY_KEY[metric].short,
title="How the ranking changes with noise",
subtitle=f"{m_short_view(metric, view)}. ▲ ▼ show places gained or lost since the previous SNR level.",
)
@memo_figure
def plot_addition_timeline(
rows: list[dict],
metric: str = "der",
view: str = "all",
top_n: int = 10,
models: list[str] | tuple | None = None,
) -> go.Figure:
"""Top-N ranks after each of the last five additions, for Overall and each SNR."""
metric = _metric(metric)
overlaps = overlaps_for_view(view)
m = METRICS_BY_KEY[metric]
by_id = {str(r.get("model_id") or "").strip(): r for r in rows if r.get("model_id")}
if len(by_id) < 2:
return analytics._empty_fig(_NO_DATA)
ordered = analytics.addition_order(
list(by_id),
[by_id[mid].get("submitted_at") for mid in by_id],
)
snaps = analytics.addition_snapshots(ordered, last_n=analytics.ADDITION_LAST_N)
if len(snaps) < 2:
return analytics._empty_fig("Need at least two model additions to draw the timeline.")
def score(mid: str, snrs: tuple[str, ...] | None) -> float | None:
row = by_id.get(mid)
if row is None:
return None
v = dr.metric_mean(row, metric, snrs=snrs, overlaps=overlaps)
return None if v is None else v * 100.0
conditions: list[tuple[str, tuple[str, ...] | None]] = [("Overall", None)]
conditions.extend((label, (snr,)) for snr, label in SNR_LEVELS)
picked = [m for m in (models or []) if m in by_id]
shown: list[str] = list(picked)
if not shown:
for _, present in snaps:
for mid in analytics._top_n_ids(present, lambda m_id: score(m_id, None), top_n):
if mid not in shown:
shown.append(mid)
if not shown:
return analytics._empty_fig(_NO_DATA)
groups = {
label: [
(snap_label, [score(mid, snrs) if mid in present else None for mid in shown])
for snap_label, present in snaps
]
for label, snrs in conditions
}
return analytics.plot_ranking_race(
shown,
groups["Overall"],
metric_label=m.short,
title="How the top 10 changed with recent submissions",
subtitle=f"{m_short_view(metric, view)}. Each step adds one newly submitted model.",
groups=groups,
)
def _picked_rows(rows: list[dict], models: list[str] | tuple | None) -> tuple[list[dict], int | None]:
"""Rows for the picked models plus a top-N override, or all rows when nothing is picked."""
picked = set(models or [])
if not picked:
return rows, None
return [r for r in rows if r.get("model_id") in picked], len(picked)
def all_figures(
rows: list[dict],
metric: str,
view: str,
top_n: int,
models: list[str] | tuple | None = None,
) -> tuple[go.Figure, ...]:
"""Every diarization chart, in Analysis-tab order.
Each chart is memoized individually (``memo_figure``), so repeated calls with the
same rows / settings return cached deep copies in a few milliseconds.
"""
sub, n_override = _picked_rows(rows, models)
n = n_override or top_n
return (
plot_snr_race(sub, metric, view, n),
plot_addition_timeline(rows, metric, view, n, models),
plot_pareto(rows, metric, view, highlight=list(models or [])),
plot_avg_bars(sub, metric, view, n),
analytics.with_spotlight(plot_speaker_count(sub, n), "category"),
analytics.with_spotlight(plot_error_breakdown(sub, view, n), "category"),
analytics.with_spotlight(plot_overlap_dumbbell(sub, metric, n), "category"),
analytics.with_spotlight(plot_snr_dumbbell(sub, metric, view, n), "category"),
plot_condition_heatmap(sub, metric, n),
)
def precompute_default_figures(
rows: list[dict], metric: str = "der", view: str = "all", top_n: int = 10
) -> tuple[go.Figure, ...]:
"""Warm the figure cache with the Diarization Analysis defaults (call after results load)."""
return all_figures(rows, metric, view, top_n, None)
|