Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download diarization_analytics.py from treble-technologies/ffasr: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/spaces/treble-technologies/ffasr/resolve/main/diarization_analytics.py
- Command line
-
hf download hf://spaces/treble-technologies/ffasr/diarization_analytics.py
-
curl -L -o diarization_analytics.py https://huggingface.co/spaces/treble-technologies/ffasr/resolve/main/diarization_analytics.py
17.3 kB
| """ | |
| 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))) | |
| 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}", | |
| ) | |
| 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 | |
| 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 | |
| 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.", | |
| ) | |
| 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.", | |
| ) | |
| 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 | |
| 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, | |
| ) | |
| 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.", | |
| ) | |
| 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) | |