""" Plotly charts for the Analysis tab's full-duplex section. Each chart answers one question people ask about a voice agent: * Who handles the conversation best? -> ranked interaction error * How fast does it answer and stop talking? -> response vs stop latency * Which behaviour does it get wrong? -> model x behaviour failure heatmap * Does it yield to the user but not to others -> missed vs false barge-ins scatter * Is it fast *and* correct? -> response latency vs interaction error * How much harder are smart glasses? -> far field vs smart glasses dumbbell * Does it interrupt itself on its own echo? -> echo self-stops per condition """ from __future__ import annotations import pandas as pd import plotly.graph_objects as go import analytics import duplex_results as dx from duplex_config import ARCHITECTURES, BEHAVIORS, CONDITIONS, conditions_for_view, view_label _TEMPLATE = analytics._TEMPLATE _NO_DATA = "No full-duplex results yet." memo_figure = analytics.memo_figure _ARCH_COLORS: dict[str, str] = { ARCHITECTURES[0]: analytics.SERIES_BLUE, ARCHITECTURES[1]: analytics.SERIES_ORANGE, } _OTHER_ARCH_COLOR = analytics.SERIES_VIOLET _COND_COLORS: dict[str, str] = { CONDITIONS[0].key: analytics.SERIES_BLUE, CONDITIONS[1].key: analytics.SERIES_ORANGE, } def _hbar_height(n: int) -> int: return int(min(900, max(380, 140 + 30 * n))) def _top(rows: list[dict], view: str, top_n: int) -> list[tuple[dict, float]]: return dx.ranked(rows, view)[: max(1, int(top_n))] def _hbar_layout(fig: go.Figure, title: str, subtitle: str, n: int, *, xaxis: dict) -> go.Figure: title_d, top = analytics.chart_title(title, subtitle, wrap=64) fig.update_layout( barmode="group", title=title_d, xaxis=xaxis, yaxis=dict(autorange="reversed", automargin=True, showgrid=False, ticks=""), template=_TEMPLATE, height=_hbar_height(n), margin=dict(l=8, r=16, t=top + 18, b=40), bargap=0.3, bargroupgap=0.1, legend=dict(orientation="h", yanchor="bottom", y=1.0, xanchor="left", x=0.0), ) return analytics.with_spotlight(fig, "category") @memo_figure def plot_error_bars(rows: list[dict], view: str = "all", top_n: int = 10) -> go.Figure: ranked = _top(rows, view, top_n) if not ranked: return analytics._empty_fig(_NO_DATA) ids = [r["model_id"] for r, _ in ranked] return analytics._plot_ranked_bars( labels=analytics.short_labels(ids, 26), values=[v * 100.0 for _, v in ranked], model_ids=ids, title="Interaction error", subtitle=f"Mean of five turn-taking failure rates (%) · {view_label(view)} · lower is better", value_fmt="{:.1f}%", hover_value_fmt="%{x:.2f}%", hover_metric_label="Interaction error", ) @memo_figure def plot_latency_bars(rows: list[dict], view: str = "all", top_n: int = 10) -> go.Figure: """Grouped bars: response latency and stop latency for the same models as the error bars.""" ranked = _top(rows, view, top_n) conds = conditions_for_view(view) if not ranked: return analytics._empty_fig(_NO_DATA) ids = [r["model_id"] for r, _ in ranked] labels = analytics.short_labels(ids, 22) fig = go.Figure() for metric, name, color in ( ("resp_latency_s", "Response latency", analytics.SERIES_BLUE), ("stop_latency_s", "Stop latency", analytics.SERIES_AQUA), ): fig.add_trace( go.Bar( y=labels, x=[dx.metric_mean(r, metric, conds) for r, _ in ranked], orientation="h", name=name, marker=dict(color=color, cornerradius=3), customdata=ids, hovertemplate=f"%{{customdata}}
{name}: %{{x:.2f}} s", ) ) return _hbar_layout( fig, "How fast it reacts", f"Seconds to start answering and to stop after a barge-in · {view_label(view)} · lower is better", len(ids), xaxis=dict(rangemode="tozero", ticksuffix=" s"), ) @memo_figure def plot_behavior_heatmap(rows: list[dict], view: str = "all", top_n: int = 10) -> go.Figure: ranked = _top(rows, view, top_n) if not ranked: return analytics._empty_fig(_NO_DATA) conds = conditions_for_view(view) z = [[(v * 100.0 if (v := dx.behavior_failure(r, b.key, conds)) is not None else None) for b in BEHAVIORS] 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.seq_heatmap( z, [b.label for b in BEHAVIORS], analytics.short_labels([r["model_id"] for r, _ in ranked], 40), zmax=zmax, unit_label="failure %", title="Which behaviour fails", subtitle=f"Share of test cases handled wrongly (%) · {view_label(view)} · stronger colour means more failures", ) def _scatter( points: list[tuple[str, str, float, float]], *, title: str, subtitle: str, x_title: str, y_title: str, x_suffix: str, y_suffix: str, hover_x: str, hover_y: str, highlight: list[str] | tuple, ) -> go.Figure: """Labelled scatter (lower-left is best), one colour per architecture.""" if not points: return analytics._empty_fig(_NO_DATA) labels = dict(zip([p[0] for p in points], analytics.short_labels([p[0] for p in points], 24))) # Alternate labels above / below the points (in x order) so neighbours collide less. by_x = sorted(points, key=lambda p: (p[2], p[3])) text_pos = {p[0]: ("top center" if i % 2 == 0 else "bottom center") for i, p in enumerate(by_x)} fig = go.Figure() archs = list(dict.fromkeys(p[1] for p in points)) for arch in archs: pts = [p for p in points if p[1] == arch] fig.add_trace( go.Scatter( x=[p[2] for p in pts], y=[p[3] for p in pts], mode="markers+text", name=arch, text=[labels[p[0]] for p in pts], textposition=[text_pos[p[0]] for p in pts], textfont=dict(size=12), marker=dict( size=12, color=_ARCH_COLORS.get(arch, _OTHER_ARCH_COLOR), line=dict(width=1.5, color="rgba(255,255,255,0.9)"), ), customdata=[p[0] for p in pts], hovertemplate=( f"%{{customdata}} ({arch})
{hover_x}
{hover_y}" ), cliponaxis=False, ) ) picked = [p for p in points if p[0] in set(highlight or ())] if picked: fig.add_trace( go.Scatter( x=[p[2] for p in picked], y=[p[3] for p in picked], mode="markers", marker=dict(size=22, color="rgba(0,0,0,0)", line=dict(width=2.5, color=analytics._HIGHLIGHT_COLOR)), hoverinfo="skip", showlegend=False, ) ) x_max = max(p[2] for p in points) * 1.15 or 1.0 y_max = max(p[3] for p in points) * 1.15 or 1.0 fig.add_annotation( x=0, y=0, xref="x", yref="y", xanchor="left", yanchor="bottom", showarrow=False, text="↙ better", font=dict(size=12, color=analytics.ACCENT), ) title_d, top = analytics.chart_title(title, subtitle, wrap=64) fig.update_layout( title=title_d, xaxis=dict(title=x_title, range=[0, x_max], ticksuffix=x_suffix, zeroline=False, automargin=True), yaxis=dict(title=y_title, range=[0, y_max], ticksuffix=y_suffix, zeroline=False, automargin=True), template=_TEMPLATE, height=500, margin=dict(l=8, r=16, t=top + 24, b=40), legend=dict(orientation="h", yanchor="bottom", y=1.0, xanchor="left", x=0.0), hovermode="closest", ) return analytics.with_spotlight(fig, "point") @memo_figure def plot_bargein_tradeoff(rows: list[dict], view: str = "all", highlight: list[str] | tuple = ()) -> go.Figure: """Missed barge-ins vs false barge-ins: a good agent yields to the user and to no one else.""" conds = conditions_for_view(view) points = [ (r["model_id"], (r.get("architecture") or "").strip() or "Other", f * 100.0, m * 100.0) for r in rows if r.get("model_id") and (f := dx.behavior_failure(r, "false_bargein", conds)) is not None and (m := dx.behavior_failure(r, "bargein", conds)) is not None ] return _scatter( points, title="Yields to the user, not to everyone else", subtitle=f"{view_label(view)} · right: stops for bystanders or TV · up: talks over the user", x_title="False barge-ins (%)", y_title="Missed barge-ins (%)", x_suffix="%", y_suffix="%", hover_x="False barge-ins: %{x:.1f}%", hover_y="Missed barge-ins: %{y:.1f}%", highlight=highlight, ) @memo_figure def plot_speed_tradeoff(rows: list[dict], view: str = "all", highlight: list[str] | tuple = ()) -> go.Figure: """Response latency vs interaction error: fast and correct is bottom-left.""" conds = conditions_for_view(view) points = [ (r["model_id"], (r.get("architecture") or "").strip() or "Other", lat, err * 100.0) for r in rows if r.get("model_id") and (lat := dx.metric_mean(r, "resp_latency_s", conds)) is not None and (err := dx.interaction_error(r, conds)) is not None ] return _scatter( points, title="Fast and correct", subtitle=f"{view_label(view)} · response latency against interaction error · bottom-left is best", x_title="Response latency (s)", y_title="Interaction error (%)", x_suffix=" s", y_suffix="%", hover_x="Response latency: %{x:.2f} s", hover_y="Interaction error: %{y:.1f}%", highlight=highlight, ) @memo_figure def plot_condition_dumbbell(rows: list[dict], top_n: int = 10) -> go.Figure: """Far field → smart glasses interaction error per model (gap = smart-glasses penalty).""" ids: list[str] = [] cols: list[list[float]] = [[] for _ in CONDITIONS] for r, _ in _top(rows, "all", top_n): vals = [dx.interaction_error(r, (c.key,)) for c in CONDITIONS] if all(v is not None for v in vals): ids.append(r["model_id"]) for col, v in zip(cols, vals): col.append(v * 100.0) if not ids: return analytics._empty_fig("This chart needs models with results for both conditions.") return analytics.plot_condition_dumbbell( ids, [(c.label, col) for c, col in zip(CONDITIONS, cols)], metric_label="interaction error", title="How much harder smart glasses are", subtitle="Interaction error (%) in far field and on smart glasses · sorted by smart glasses · lower is better", ) @memo_figure def plot_echo_bars(rows: list[dict], top_n: int = 10) -> go.Figure: """Grouped bars: echo self-interruption rate per condition.""" ranked = [(r, v) for r, v in _top(rows, "all", top_n) if dx.metric_mean(r, "echo_stop") is not None] if not ranked: return analytics._empty_fig("No echo self-interruption results yet.") ids = [r["model_id"] for r, _ in ranked] labels = analytics.short_labels(ids, 22) fig = go.Figure() for c in CONDITIONS: fig.add_trace( go.Bar( y=labels, x=[dx.metric_mean(r, "echo_stop", (c.key,)) * 100.0 for r, _ in ranked], orientation="h", name=c.label, marker=dict(color=_COND_COLORS[c.key], cornerradius=3), customdata=ids, hovertemplate=f"%{{customdata}}
{c.label}: %{{x:.1f}}%", ) ) return _hbar_layout( fig, "Interrupted by its own voice", "Agent turns cut off by the agent's own playback, with no user speech (%) · lower is better", len(ids), xaxis=dict(rangemode="tozero", ticksuffix="%"), ) def all_figures( rows: list[dict], view: str, top_n: int, models: list[str] | tuple | None = None, ) -> tuple[go.Figure, ...]: """Every duplex chart, in Analysis-tab order. Picked models replace the top-N cut.""" picked = [m for m in (models or []) if m] sub = [r for r in rows if r.get("model_id") in set(picked)] if picked else rows n = len(picked) if picked else top_n return ( plot_error_bars(sub, view, n), plot_latency_bars(sub, view, n), plot_behavior_heatmap(sub, view, n), plot_bargein_tradeoff(rows, view, highlight=picked), plot_speed_tradeoff(rows, view, highlight=picked), plot_condition_dumbbell(sub, n), plot_echo_bars(sub, n), )