{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Audio Debug — Real-time Waveform & VAD Visualization\n",
    "\n",
    "Stream mic audio into a live Plotly chart, then inspect segments post-hoc.\n",
    "\n",
    "**Usage:**\n",
    "1. Run the cells in order\n",
    "2. The live chart streams RMS + peak amplitude per frame (20 updates/sec)\n",
    "3. Bump the mic, speak, clap — watch the difference\n",
    "4. Stop recording, then inspect the full waveform with zoom"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.path.insert(0, '../src')\n",
    "\n",
    "import numpy as np\n",
    "import sounddevice as sd\n",
    "import plotly.graph_objects as go\n",
    "from IPython.display import display, Audio\n",
    "import threading\n",
    "import time\n",
    "\n",
    "from cohere_transcribe.model import SAMPLE_RATE\n",
    "from cohere_transcribe.vad import (\n",
    "    FRAME_SIZE, SPEECH_ONSET_FRAMES, MIN_SPEECH_SECONDS,\n",
    "    calibrate_silence, VADStateMachine, DEFAULT_SILENCE_FRAMES,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ╔══════════════════════════════════════════════════════════════╗\n",
    "# ║                      CONFIGURATION                         ║\n",
    "# ╚══════════════════════════════════════════════════════════════╝\n",
    "\n",
    "# Recording\n",
    "RECORD_SECONDS = 10             # how long to record\n",
    "CALIBRATION_SECONDS = 0.5       # silence calibration duration\n",
    "THRESHOLD_MULTIPLIER = 3        # ambient RMS × this = VAD threshold\n",
    "THRESHOLD_FLOOR = 0.01          # minimum threshold regardless of ambient\n",
    "\n",
    "# Chart updates\n",
    "UPDATE_INTERVAL = 0.05          # seconds between chart refreshes (0.05 = 20fps)\n",
    "Y_AXIS_MAX = 0.5                # initial y-axis range for live chart\n",
    "\n",
    "# Chart appearance\n",
    "CHART_HEIGHT = 400              # pixels\n",
    "CHART_TEMPLATE = \"plotly_dark\"  # plotly theme: plotly_dark, plotly_white, plotly, etc.\n",
    "COLOR_RMS = \"dodgerblue\"\n",
    "COLOR_PEAK = \"orange\"\n",
    "COLOR_THRESHOLD = \"red\"\n",
    "COLOR_SPEECH = \"rgba(0,200,0,0.15)\"\n",
    "COLOR_WAVEFORM = \"dodgerblue\"\n",
    "SEGMENT_COMPARE_HEIGHT = 250    # pixels per segment in comparison view"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Calibrate & Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Calibrating silence threshold...\n",
      "Sample rate: 16000 Hz, Frame: 800 samples (50ms)\n",
      "Ambient RMS: 0.0021\n",
      "VAD threshold: 0.0100 (ambient × 3, floor 0.01)\n",
      "Min speech duration: 0.3s\n"
     ]
    }
   ],
   "source": [
    "print(\"Calibrating silence threshold...\")\n",
    "cal_audio = sd.rec(int(CALIBRATION_SECONDS * SAMPLE_RATE),\n",
    "                   samplerate=SAMPLE_RATE, channels=1, dtype=\"float32\")\n",
    "sd.wait()\n",
    "ambient_rms = np.sqrt(np.mean(cal_audio ** 2))\n",
    "threshold = max(ambient_rms * THRESHOLD_MULTIPLIER, THRESHOLD_FLOOR)\n",
    "\n",
    "print(f\"Sample rate: {SAMPLE_RATE} Hz, Frame: {FRAME_SIZE} samples ({FRAME_SIZE/SAMPLE_RATE*1000:.0f}ms)\")\n",
    "print(f\"Ambient RMS: {ambient_rms:.4f}\")\n",
    "print(f\"VAD threshold: {threshold:.4f} (ambient × {THRESHOLD_MULTIPLIER}, floor {THRESHOLD_FLOOR})\")\n",
    "print(f\"Min speech duration: {MIN_SPEECH_SECONDS}s\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Live Streaming Chart\n",
    "\n",
    "Streams RMS and peak amplitude per frame in real time. The VAD threshold is shown as a horizontal line.\n",
    "\n",
    "- **Blue** = RMS (energy)\n",
    "- **Orange** = Peak amplitude\n",
    "- **Red dashed** = VAD threshold\n",
    "- **Green shading** = VAD detected speech"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Shared state between audio callback and chart updater\n",
    "times = []\n",
    "rms_values = []\n",
    "peak_values = []\n",
    "vad_states = []  # True when VAD says speaking\n",
    "raw_audio = []   # store all raw samples for post-hoc analysis\n",
    "segments = []    # (start_time, end_time) of detected segments\n",
    "lock = threading.Lock()\n",
    "stop_event = threading.Event()\n",
    "\n",
    "vad = VADStateMachine(threshold)\n",
    "start_time = None\n",
    "\n",
    "def audio_callback(indata, frames, time_info, status):\n",
    "    global start_time\n",
    "    if stop_event.is_set():\n",
    "        return\n",
    "    if start_time is None:\n",
    "        start_time = time.monotonic()\n",
    "    \n",
    "    frame = indata[:, 0].copy()\n",
    "    elapsed = time.monotonic() - start_time\n",
    "    rms = np.sqrt(np.mean(frame ** 2))\n",
    "    peak = np.max(np.abs(frame))\n",
    "    \n",
    "    result = vad.process_frame(frame, elapsed)\n",
    "    \n",
    "    with lock:\n",
    "        times.append(elapsed)\n",
    "        rms_values.append(rms)\n",
    "        peak_values.append(peak)\n",
    "        vad_states.append(vad.speaking)\n",
    "        raw_audio.extend(frame.tolist())\n",
    "        if result is not None:\n",
    "            seg_start, seg_audio = result\n",
    "            seg_end = seg_start + len(seg_audio) / SAMPLE_RATE\n",
    "            segments.append((seg_start, seg_end, seg_audio))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "fbcdcf4a23cd439ba74931a0bad56a01",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "FigureWidget({\n",
       "    'data': [{'line': {'color': 'dodgerblue', 'width': 1.5},\n",
       "              'mode': 'lines',\n",
       "              'name': 'RMS',\n",
       "              'type': 'scatter',\n",
       "              'uid': '9914a448-ca9b-4b03-b991-5946814b60e1',\n",
       "              'x': [],\n",
       "              'y': []},\n",
       "             {'line': {'color': 'orange', 'dash': 'dot', 'width': 1},\n",
       "              'mode': 'lines',\n",
       "              'name': 'Peak',\n",
       "              'type': 'scatter',\n",
       "              'uid': 'cf15350a-0fcb-4106-b930-ce623014214b',\n",
       "              'x': [],\n",
       "              'y': []},\n",
       "             {'fill': 'tozeroy',\n",
       "              'fillcolor': 'rgba(0,200,0,0.15)',\n",
       "              'line': {'color': 'rgba(0,200,0,0.3)', 'width': 0},\n",
       "              'mode': 'lines',\n",
       "              'name': 'Speaking',\n",
       "              'type': 'scatter',\n",
       "              'uid': 'ebddef75-0910-4886-b663-fdd30f664ecc',\n",
       "              'x': [],\n",
       "              'y': []}],\n",
       "    'layout': {'annotations': [{'showarrow': False,\n",
       "                                'text': 'VAD threshold',\n",
       "                                'x': 1,\n",
       "                                'xanchor': 'right',\n",
       "                                'xref': 'x domain',\n",
       "                                'y': 0.01,\n",
       "                                'yanchor': 'bottom',\n",
       "                                'yref': 'y'}],\n",
       "               'height': 400,\n",
       "               'shapes': [{'line': {'color': 'red', 'dash': 'dash'},\n",
       "                           'type': 'line',\n",
       "                           'x0': 0,\n",
       "                           'x1': 1,\n",
       "                           'xref': 'x domain',\n",
       "                           'y0': 0.01,\n",
       "                           'y1': 0.01,\n",
       "                           'yref': 'y'}],\n",
       "               'showlegend': True,\n",
       "               'template': '...',\n",
       "               'title': {'text': 'Live Audio — RMS & Peak per Frame'},\n",
       "               'xaxis': {'title': {'text': 'Time (s)'}},\n",
       "               'yaxis': {'range': [0, 0.5], 'title': {'text': 'Amplitude'}}}\n",
       "})"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = go.FigureWidget()\n",
    "\n",
    "fig.add_trace(go.Scatter(x=[], y=[], mode='lines', name='RMS',\n",
    "                         line=dict(color=COLOR_RMS, width=1.5)))\n",
    "fig.add_trace(go.Scatter(x=[], y=[], mode='lines', name='Peak',\n",
    "                         line=dict(color=COLOR_PEAK, width=1, dash='dot')))\n",
    "fig.add_trace(go.Scatter(x=[], y=[], mode='lines', name='Speaking',\n",
    "                         fill='tozeroy', line=dict(color='rgba(0,200,0,0.3)', width=0),\n",
    "                         fillcolor=COLOR_SPEECH))\n",
    "fig.add_hline(y=threshold, line_dash='dash', line_color=COLOR_THRESHOLD,\n",
    "              annotation_text='VAD threshold')\n",
    "\n",
    "fig.update_layout(\n",
    "    title='Live Audio — RMS & Peak per Frame',\n",
    "    xaxis_title='Time (s)',\n",
    "    yaxis_title='Amplitude',\n",
    "    yaxis_range=[0, Y_AXIS_MAX],\n",
    "    height=CHART_HEIGHT,\n",
    "    template=CHART_TEMPLATE,\n",
    "    showlegend=True,\n",
    ")\n",
    "\n",
    "display(fig)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Recording for 10s — bump the mic, speak, clap...\n",
      "Done. Captured 624 frames, 7 speech segments.\n"
     ]
    }
   ],
   "source": [
    "stream = sd.InputStream(\n",
    "    samplerate=SAMPLE_RATE, channels=1, dtype='float32',\n",
    "    callback=audio_callback, blocksize=FRAME_SIZE,\n",
    ")\n",
    "\n",
    "print(f'Recording for {RECORD_SECONDS}s — bump the mic, speak, clap...')\n",
    "stream.start()\n",
    "\n",
    "end_time = time.monotonic() + RECORD_SECONDS\n",
    "last_len = 0\n",
    "\n",
    "while time.monotonic() < end_time:\n",
    "    time.sleep(UPDATE_INTERVAL)\n",
    "    with lock:\n",
    "        n = len(times)\n",
    "        if n <= last_len:\n",
    "            continue\n",
    "        t = list(times)\n",
    "        r = list(rms_values)\n",
    "        p = list(peak_values)\n",
    "        v = [peak_values[i] if vad_states[i] else 0 for i in range(n)]\n",
    "        last_len = n\n",
    "\n",
    "    with fig.batch_update():\n",
    "        fig.data[0].x = t\n",
    "        fig.data[0].y = r\n",
    "        fig.data[1].x = t\n",
    "        fig.data[1].y = p\n",
    "        fig.data[2].x = t\n",
    "        fig.data[2].y = v\n",
    "\n",
    "stop_event.set()\n",
    "stream.stop()\n",
    "stream.close()\n",
    "print(f'Done. Captured {len(times)} frames, {len(segments)} speech segments.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Post-hoc Waveform — Full Resolution\n",
    "\n",
    "Zoom into any region to see individual samples. Segment boundaries marked in green."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.plotly.v1+json": {
       "config": {
        "plotlyServerURL": "https://plot.ly"
       },
       "data": [
        {
         "line": {
          "color": "dodgerblue",
          "width": 0.5
         },
         "mode": "lines",
         "name": "Waveform",
         "type": "scattergl",
         "x": {
          "bdata": "[encoded data, 5324800 characters]",
          "dtype": "f8"
         },
         "y": {
          "bdata": "[encoded data, 5324800 characters]",
          "dtype": "f8"
         }
        }
       ],
       "layout": {
        "annotations": [
         {
          "showarrow": false,
          "text": "seg 1",
          "x": 1.3948768850415945,
          "xanchor": "left",
          "xref": "x",
          "y": 1,
          "yanchor": "top",
          "yref": "y domain"
         },
         {
          "showarrow": false,
          "text": "seg 2",
          "x": 2.5948107659816744,
          "xanchor": "left",
          "xref": "x",
          "y": 1,
          "yanchor": "top",
          "yref": "y domain"
         },
         {
          "showarrow": false,
          "text": "seg 3",
          "x": 3.106927268020809,
          "xanchor": "left",
          "xref": "x",
          "y": 1,
          "yanchor": "top",
          "yref": "y domain"
         },
         {
          "showarrow": false,
          "text": "seg 4",
          "x": 4.130804181029089,
          "xanchor": "left",
          "xref": "x",
          "y": 1,
          "yanchor": "top",
          "yref": "y domain"
         },
         {
          "showarrow": false,
          "text": "seg 5",
          "x": 5.125957830995321,
          "xanchor": "left",
          "xref": "x",
          "y": 1,
          "yanchor": "top",
          "yref": "y domain"
         },
         {
          "showarrow": false,
          "text": "seg 6",
          "x": 5.125957830995321,
          "xanchor": "left",
          "xref": "x",
          "y": 1,
          "yanchor": "top",
          "yref": "y domain"
         },
         {
          "showarrow": false,
          "text": "seg 7",
          "x": 5.879124196060002,
          "xanchor": "left",
          "xref": "x",
          "y": 1,
          "yanchor": "top",
          "yref": "y domain"
         },
         {
          "showarrow": false,
          "text": "threshold",
          "x": 1,
          "xanchor": "right",
          "xref": "x domain",
          "y": 0.01,
          "yanchor": "bottom",
          "yref": "y"
         }
        ],
        "height": 400,
        "shapes": [
         {
          "fillcolor": "rgba(0,200,0,0.15)",
          "line": {
           "width": 0
          },
          "type": "rect",
          "x0": 1.3948768850415945,
          "x1": 3.7448768850415943,
          "xref": "x",
          "y0": 0,
          "y1": 1,
          "yref": "y domain"
         },
         {
          "fillcolor": "rgba(0,200,0,0.15)",
          "line": {
           "width": 0
          },
          "type": "rect",
          "x0": 2.5948107659816744,
          "x1": 3.8448107659816744,
          "xref": "x",
          "y0": 0,
          "y1": 1,
          "yref": "y domain"
         },
         {
          "fillcolor": "rgba(0,200,0,0.15)",
          "line": {
           "width": 0
          },
          "type": "rect",
          "x0": 3.106927268020809,
          "x1": 6.206927268020809,
          "xref": "x",
          "y0": 0,
          "y1": 1,
          "yref": "y domain"
         },
         {
          "fillcolor": "rgba(0,200,0,0.15)",
          "line": {
           "width": 0
          },
          "type": "rect",
          "x0": 4.130804181029089,
          "x1": 6.880804181029089,
          "xref": "x",
          "y0": 0,
          "y1": 1,
          "yref": "y domain"
         },
         {
          "fillcolor": "rgba(0,200,0,0.15)",
          "line": {
           "width": 0
          },
          "type": "rect",
          "x0": 5.125957830995321,
          "x1": 7.575957830995321,
          "xref": "x",
          "y0": 0,
          "y1": 1,
          "yref": "y domain"
         },
         {
          "fillcolor": "rgba(0,200,0,0.15)",
          "line": {
           "width": 0
          },
          "type": "rect",
          "x0": 5.125957830995321,
          "x1": 7.525957830995321,
          "xref": "x",
          "y0": 0,
          "y1": 1,
          "yref": "y domain"
         },
         {
          "fillcolor": "rgba(0,200,0,0.15)",
          "line": {
           "width": 0
          },
          "type": "rect",
          "x0": 5.879124196060002,
          "x1": 15.379124196060001,
          "xref": "x",
          "y0": 0,
          "y1": 1,
          "yref": "y domain"
         },
         {
          "line": {
           "color": "red",
           "dash": "dash"
          },
          "type": "line",
          "x0": 0,
          "x1": 1,
          "xref": "x domain",
          "y0": 0.01,
          "y1": 0.01,
          "yref": "y"
         },
         {
          "line": {
           "color": "red",
           "dash": "dash"
          },
          "type": "line",
          "x0": 0,
          "x1": 1,
          "xref": "x domain",
          "y0": -0.01,
          "y1": -0.01,
          "yref": "y"
         }
        ],
        "template": {
         "data": {
          "bar": [
           {
            "error_x": {
             "color": "#f2f5fa"
            },
            "error_y": {
             "color": "#f2f5fa"
            },
            "marker": {
             "line": {
              "color": "rgb(17,17,17)",
              "width": 0.5
             },
             "pattern": {
              "fillmode": "overlay",
              "size": 10,
              "solidity": 0.2
             }
            },
            "type": "bar"
           }
          ],
          "barpolar": [
           {
            "marker": {
             "line": {
              "color": "rgb(17,17,17)",
              "width": 0.5
             },
             "pattern": {
              "fillmode": "overlay",
              "size": 10,
              "solidity": 0.2
             }
            },
            "type": "barpolar"
           }
          ],
          "carpet": [
           {
            "aaxis": {
             "endlinecolor": "#A2B1C6",
             "gridcolor": "#506784",
             "linecolor": "#506784",
             "minorgridcolor": "#506784",
             "startlinecolor": "#A2B1C6"
            },
            "baxis": {
             "endlinecolor": "#A2B1C6",
             "gridcolor": "#506784",
             "linecolor": "#506784",
             "minorgridcolor": "#506784",
             "startlinecolor": "#A2B1C6"
            },
            "type": "carpet"
           }
          ],
          "choropleth": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "type": "choropleth"
           }
          ],
          "contour": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "colorscale": [
             [
              0,
              "#0d0887"
             ],
             [
              0.1111111111111111,
              "#46039f"
             ],
             [
              0.2222222222222222,
              "#7201a8"
             ],
             [
              0.3333333333333333,
              "#9c179e"
             ],
             [
              0.4444444444444444,
              "#bd3786"
             ],
             [
              0.5555555555555556,
              "#d8576b"
             ],
             [
              0.6666666666666666,
              "#ed7953"
             ],
             [
              0.7777777777777778,
              "#fb9f3a"
             ],
             [
              0.8888888888888888,
              "#fdca26"
             ],
             [
              1,
              "#f0f921"
             ]
            ],
            "type": "contour"
           }
          ],
          "contourcarpet": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "type": "contourcarpet"
           }
          ],
          "heatmap": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "colorscale": [
             [
              0,
              "#0d0887"
             ],
             [
              0.1111111111111111,
              "#46039f"
             ],
             [
              0.2222222222222222,
              "#7201a8"
             ],
             [
              0.3333333333333333,
              "#9c179e"
             ],
             [
              0.4444444444444444,
              "#bd3786"
             ],
             [
              0.5555555555555556,
              "#d8576b"
             ],
             [
              0.6666666666666666,
              "#ed7953"
             ],
             [
              0.7777777777777778,
              "#fb9f3a"
             ],
             [
              0.8888888888888888,
              "#fdca26"
             ],
             [
              1,
              "#f0f921"
             ]
            ],
            "type": "heatmap"
           }
          ],
          "histogram": [
           {
            "marker": {
             "pattern": {
              "fillmode": "overlay",
              "size": 10,
              "solidity": 0.2
             }
            },
            "type": "histogram"
           }
          ],
          "histogram2d": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "colorscale": [
             [
              0,
              "#0d0887"
             ],
             [
              0.1111111111111111,
              "#46039f"
             ],
             [
              0.2222222222222222,
              "#7201a8"
             ],
             [
              0.3333333333333333,
              "#9c179e"
             ],
             [
              0.4444444444444444,
              "#bd3786"
             ],
             [
              0.5555555555555556,
              "#d8576b"
             ],
             [
              0.6666666666666666,
              "#ed7953"
             ],
             [
              0.7777777777777778,
              "#fb9f3a"
             ],
             [
              0.8888888888888888,
              "#fdca26"
             ],
             [
              1,
              "#f0f921"
             ]
            ],
            "type": "histogram2d"
           }
          ],
          "histogram2dcontour": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "colorscale": [
             [
              0,
              "#0d0887"
             ],
             [
              0.1111111111111111,
              "#46039f"
             ],
             [
              0.2222222222222222,
              "#7201a8"
             ],
             [
              0.3333333333333333,
              "#9c179e"
             ],
             [
              0.4444444444444444,
              "#bd3786"
             ],
             [
              0.5555555555555556,
              "#d8576b"
             ],
             [
              0.6666666666666666,
              "#ed7953"
             ],
             [
              0.7777777777777778,
              "#fb9f3a"
             ],
             [
              0.8888888888888888,
              "#fdca26"
             ],
             [
              1,
              "#f0f921"
             ]
            ],
            "type": "histogram2dcontour"
           }
          ],
          "mesh3d": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "type": "mesh3d"
           }
          ],
          "parcoords": [
           {
            "line": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "parcoords"
           }
          ],
          "pie": [
           {
            "automargin": true,
            "type": "pie"
           }
          ],
          "scatter": [
           {
            "marker": {
             "line": {
              "color": "#283442"
             }
            },
            "type": "scatter"
           }
          ],
          "scatter3d": [
           {
            "line": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scatter3d"
           }
          ],
          "scattercarpet": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scattercarpet"
           }
          ],
          "scattergeo": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scattergeo"
           }
          ],
          "scattergl": [
           {
            "marker": {
             "line": {
              "color": "#283442"
             }
            },
            "type": "scattergl"
           }
          ],
          "scattermap": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scattermap"
           }
          ],
          "scattermapbox": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scattermapbox"
           }
          ],
          "scatterpolar": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scatterpolar"
           }
          ],
          "scatterpolargl": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scatterpolargl"
           }
          ],
          "scatterternary": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scatterternary"
           }
          ],
          "surface": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "colorscale": [
             [
              0,
              "#0d0887"
             ],
             [
              0.1111111111111111,
              "#46039f"
             ],
             [
              0.2222222222222222,
              "#7201a8"
             ],
             [
              0.3333333333333333,
              "#9c179e"
             ],
             [
              0.4444444444444444,
              "#bd3786"
             ],
             [
              0.5555555555555556,
              "#d8576b"
             ],
             [
              0.6666666666666666,
              "#ed7953"
             ],
             [
              0.7777777777777778,
              "#fb9f3a"
             ],
             [
              0.8888888888888888,
              "#fdca26"
             ],
             [
              1,
              "#f0f921"
             ]
            ],
            "type": "surface"
           }
          ],
          "table": [
           {
            "cells": {
             "fill": {
              "color": "#506784"
             },
             "line": {
              "color": "rgb(17,17,17)"
             }
            },
            "header": {
             "fill": {
              "color": "#2a3f5f"
             },
             "line": {
              "color": "rgb(17,17,17)"
             }
            },
            "type": "table"
           }
          ]
         },
         "layout": {
          "annotationdefaults": {
           "arrowcolor": "#f2f5fa",
           "arrowhead": 0,
           "arrowwidth": 1
          },
          "autotypenumbers": "strict",
          "coloraxis": {
           "colorbar": {
            "outlinewidth": 0,
            "ticks": ""
           }
          },
          "colorscale": {
           "diverging": [
            [
             0,
             "#8e0152"
            ],
            [
             0.1,
             "#c51b7d"
            ],
            [
             0.2,
             "#de77ae"
            ],
            [
             0.3,
             "#f1b6da"
            ],
            [
             0.4,
             "#fde0ef"
            ],
            [
             0.5,
             "#f7f7f7"
            ],
            [
             0.6,
             "#e6f5d0"
            ],
            [
             0.7,
             "#b8e186"
            ],
            [
             0.8,
             "#7fbc41"
            ],
            [
             0.9,
             "#4d9221"
            ],
            [
             1,
             "#276419"
            ]
           ],
           "sequential": [
            [
             0,
             "#0d0887"
            ],
            [
             0.1111111111111111,
             "#46039f"
            ],
            [
             0.2222222222222222,
             "#7201a8"
            ],
            [
             0.3333333333333333,
             "#9c179e"
            ],
            [
             0.4444444444444444,
             "#bd3786"
            ],
            [
             0.5555555555555556,
             "#d8576b"
            ],
            [
             0.6666666666666666,
             "#ed7953"
            ],
            [
             0.7777777777777778,
             "#fb9f3a"
            ],
            [
             0.8888888888888888,
             "#fdca26"
            ],
            [
             1,
             "#f0f921"
            ]
           ],
           "sequentialminus": [
            [
             0,
             "#0d0887"
            ],
            [
             0.1111111111111111,
             "#46039f"
            ],
            [
             0.2222222222222222,
             "#7201a8"
            ],
            [
             0.3333333333333333,
             "#9c179e"
            ],
            [
             0.4444444444444444,
             "#bd3786"
            ],
            [
             0.5555555555555556,
             "#d8576b"
            ],
            [
             0.6666666666666666,
             "#ed7953"
            ],
            [
             0.7777777777777778,
             "#fb9f3a"
            ],
            [
             0.8888888888888888,
             "#fdca26"
            ],
            [
             1,
             "#f0f921"
            ]
           ]
          },
          "colorway": [
           "#636efa",
           "#EF553B",
           "#00cc96",
           "#ab63fa",
           "#FFA15A",
           "#19d3f3",
           "#FF6692",
           "#B6E880",
           "#FF97FF",
           "#FECB52"
          ],
          "font": {
           "color": "#f2f5fa"
          },
          "geo": {
           "bgcolor": "rgb(17,17,17)",
           "lakecolor": "rgb(17,17,17)",
           "landcolor": "rgb(17,17,17)",
           "showlakes": true,
           "showland": true,
           "subunitcolor": "#506784"
          },
          "hoverlabel": {
           "align": "left"
          },
          "hovermode": "closest",
          "mapbox": {
           "style": "dark"
          },
          "paper_bgcolor": "rgb(17,17,17)",
          "plot_bgcolor": "rgb(17,17,17)",
          "polar": {
           "angularaxis": {
            "gridcolor": "#506784",
            "linecolor": "#506784",
            "ticks": ""
           },
           "bgcolor": "rgb(17,17,17)",
           "radialaxis": {
            "gridcolor": "#506784",
            "linecolor": "#506784",
            "ticks": ""
           }
          },
          "scene": {
           "xaxis": {
            "backgroundcolor": "rgb(17,17,17)",
            "gridcolor": "#506784",
            "gridwidth": 2,
            "linecolor": "#506784",
            "showbackground": true,
            "ticks": "",
            "zerolinecolor": "#C8D4E3"
           },
           "yaxis": {
            "backgroundcolor": "rgb(17,17,17)",
            "gridcolor": "#506784",
            "gridwidth": 2,
            "linecolor": "#506784",
            "showbackground": true,
            "ticks": "",
            "zerolinecolor": "#C8D4E3"
           },
           "zaxis": {
            "backgroundcolor": "rgb(17,17,17)",
            "gridcolor": "#506784",
            "gridwidth": 2,
            "linecolor": "#506784",
            "showbackground": true,
            "ticks": "",
            "zerolinecolor": "#C8D4E3"
           }
          },
          "shapedefaults": {
           "line": {
            "color": "#f2f5fa"
           }
          },
          "sliderdefaults": {
           "bgcolor": "#C8D4E3",
           "bordercolor": "rgb(17,17,17)",
           "borderwidth": 1,
           "tickwidth": 0
          },
          "ternary": {
           "aaxis": {
            "gridcolor": "#506784",
            "linecolor": "#506784",
            "ticks": ""
           },
           "baxis": {
            "gridcolor": "#506784",
            "linecolor": "#506784",
            "ticks": ""
           },
           "bgcolor": "rgb(17,17,17)",
           "caxis": {
            "gridcolor": "#506784",
            "linecolor": "#506784",
            "ticks": ""
           }
          },
          "title": {
           "x": 0.05
          },
          "updatemenudefaults": {
           "bgcolor": "#506784",
           "borderwidth": 0
          },
          "xaxis": {
           "automargin": true,
           "gridcolor": "#283442",
           "linecolor": "#506784",
           "ticks": "",
           "title": {
            "standoff": 15
           },
           "zerolinecolor": "#283442",
           "zerolinewidth": 2
          },
          "yaxis": {
           "automargin": true,
           "gridcolor": "#283442",
           "linecolor": "#506784",
           "ticks": "",
           "title": {
            "standoff": 15
           },
           "zerolinecolor": "#283442",
           "zerolinewidth": 2
          }
         }
        },
        "title": {
         "text": "Full Waveform (zoom to inspect)"
        },
        "xaxis": {
         "title": {
          "text": "Time (s)"
         }
        },
        "yaxis": {
         "title": {
          "text": "Amplitude"
         }
        }
       }
      },
      "image/png": "[encoded data, 70968 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "audio_arr = np.array(raw_audio)\n",
    "time_axis = np.arange(len(audio_arr)) / SAMPLE_RATE\n",
    "\n",
    "fig2 = go.Figure()\n",
    "fig2.add_trace(go.Scattergl(x=time_axis, y=audio_arr, mode='lines',\n",
    "                             name='Waveform', line=dict(color=COLOR_WAVEFORM, width=0.5)))\n",
    "\n",
    "for i, (s_start, s_end, _) in enumerate(segments):\n",
    "    fig2.add_vrect(x0=s_start, x1=s_end,\n",
    "                   fillcolor=COLOR_SPEECH, line_width=0,\n",
    "                   annotation_text=f'seg {i+1}', annotation_position='top left')\n",
    "\n",
    "fig2.add_hline(y=threshold, line_dash='dash', line_color=COLOR_THRESHOLD, annotation_text='threshold')\n",
    "fig2.add_hline(y=-threshold, line_dash='dash', line_color=COLOR_THRESHOLD)\n",
    "\n",
    "fig2.update_layout(\n",
    "    title='Full Waveform (zoom to inspect)',\n",
    "    xaxis_title='Time (s)',\n",
    "    yaxis_title='Amplitude',\n",
    "    height=CHART_HEIGHT,\n",
    "    template=CHART_TEMPLATE,\n",
    ")\n",
    "fig2.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Play Back Detected Segments\n",
    "\n",
    "Listen to what the VAD captured — useful for comparing bumps vs speech."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Segment 1: 1.39s — 3.74s (2.35s)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio  controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 100328 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Segment 2: 2.59s — 3.84s (1.25s)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio  controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 53392 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Segment 3: 3.11s — 6.21s (3.10s)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio  controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 132328 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Segment 4: 4.13s — 6.88s (2.75s)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio  controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 117392 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Segment 5: 5.13s — 7.58s (2.45s)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio  controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 104592 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Segment 6: 5.13s — 7.53s (2.40s)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio  controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 102460 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Segment 7: 5.88s — 15.38s (9.50s)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio  controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 405392 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "if not segments:\n",
    "    print('No speech segments detected.')\n",
    "else:\n",
    "    for i, (s_start, s_end, audio) in enumerate(segments):\n",
    "        duration = s_end - s_start\n",
    "        print(f'Segment {i+1}: {s_start:.2f}s — {s_end:.2f}s ({duration:.2f}s)')\n",
    "        display(Audio(audio, rate=SAMPLE_RATE))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Compare Segment Shapes\n",
    "\n",
    "Side-by-side waveform of each detected segment — look for the sharp spike pattern of a mic bump vs the sustained envelope of speech."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.plotly.v1+json": {
       "config": {
        "plotlyServerURL": "https://plot.ly"
       },
       "data": [
        {
         "line": {
          "width": 0.5
         },
         "mode": "lines",
         "showlegend": false,
         "type": "scattergl",
         "x": {
          "bdata": "[encoded data, 401068 characters]",
          "dtype": "f8"
         },
         "xaxis": "x",
         "y": {
          "bdata": "[encoded data, 200536 characters]",
          "dtype": "f4"
         },
         "yaxis": "y"
        },
        {
         "line": {
          "width": 0.5
         },
         "mode": "lines",
         "showlegend": false,
         "type": "scattergl",
         "x": {
          "bdata": "[encoded data, 213336 characters]",
          "dtype": "f8"
         },
         "xaxis": "x2",
         "y": {
          "bdata": "[encoded data, 106668 characters]",
          "dtype": "f4"
         },
         "yaxis": "y2"
        },
        {
         "line": {
          "width": 0.5
         },
         "mode": "lines",
         "showlegend": false,
         "type": "scattergl",
         "x": {
          "bdata": "[encoded data, 529068 characters]",
          "dtype": "f8"
         },
         "xaxis": "x3",
         "y": {
          "bdata": "[encoded data, 264536 characters]",
          "dtype": "f4"
         },
         "yaxis": "y3"
        },
        {
         "line": {
          "width": 0.5
         },
         "mode": "lines",
         "showlegend": false,
         "type": "scattergl",
         "x": {
          "bdata": "[encoded data, 469336 characters]",
          "dtype": "f8"
         },
         "xaxis": "x4",
         "y": {
          "bdata": "[encoded data, 234668 characters]",
          "dtype": "f4"
         },
         "yaxis": "y4"
        },
        {
         "line": {
          "width": 0.5
         },
         "mode": "lines",
         "showlegend": false,
         "type": "scattergl",
         "x": {
          "bdata": "[encoded data, 418136 characters]",
          "dtype": "f8"
         },
         "xaxis": "x5",
         "y": {
          "bdata": "[encoded data, 209068 characters]",
          "dtype": "f4"
         },
         "yaxis": "y5"
        },
        {
         "line": {
          "width": 0.5
         },
         "mode": "lines",
         "showlegend": false,
         "type": "scattergl",
         "x": {
          "bdata": "[encoded data, 409600 characters]",
          "dtype": "f8"
         },
         "xaxis": "x6",
         "y": {
          "bdata": "[encoded data, 204800 characters]",
          "dtype": "f4"
         },
         "yaxis": "y6"
        },
        {
         "line": {
          "width": 0.5
         },
         "mode": "lines",
         "showlegend": false,
         "type": "scattergl",
         "x": {
          "bdata": "[encoded data, 1621336 characters]",
          "dtype": "f8"
         },
         "xaxis": "x7",
         "y": {
          "bdata": "[encoded data, 810668 characters]",
          "dtype": "f4"
         },
         "yaxis": "y7"
        }
       ],
       "layout": {
        "annotations": [
         {
          "font": {
           "size": 16
          },
          "showarrow": false,
          "text": "Segment 1 (2.35s)",
          "x": 0.5,
          "xanchor": "center",
          "xref": "paper",
          "y": 1,
          "yanchor": "bottom",
          "yref": "paper"
         },
         {
          "font": {
           "size": 16
          },
          "showarrow": false,
          "text": "Segment 2 (1.25s)",
          "x": 0.5,
          "xanchor": "center",
          "xref": "paper",
          "y": 0.8457142857142858,
          "yanchor": "bottom",
          "yref": "paper"
         },
         {
          "font": {
           "size": 16
          },
          "showarrow": false,
          "text": "Segment 3 (3.10s)",
          "x": 0.5,
          "xanchor": "center",
          "xref": "paper",
          "y": 0.6914285714285715,
          "yanchor": "bottom",
          "yref": "paper"
         },
         {
          "font": {
           "size": 16
          },
          "showarrow": false,
          "text": "Segment 4 (2.75s)",
          "x": 0.5,
          "xanchor": "center",
          "xref": "paper",
          "y": 0.5371428571428571,
          "yanchor": "bottom",
          "yref": "paper"
         },
         {
          "font": {
           "size": 16
          },
          "showarrow": false,
          "text": "Segment 5 (2.45s)",
          "x": 0.5,
          "xanchor": "center",
          "xref": "paper",
          "y": 0.3828571428571429,
          "yanchor": "bottom",
          "yref": "paper"
         },
         {
          "font": {
           "size": 16
          },
          "showarrow": false,
          "text": "Segment 6 (2.40s)",
          "x": 0.5,
          "xanchor": "center",
          "xref": "paper",
          "y": 0.2285714285714286,
          "yanchor": "bottom",
          "yref": "paper"
         },
         {
          "font": {
           "size": 16
          },
          "showarrow": false,
          "text": "Segment 7 (9.50s)",
          "x": 0.5,
          "xanchor": "center",
          "xref": "paper",
          "y": 0.07428571428571429,
          "yanchor": "bottom",
          "yref": "paper"
         }
        ],
        "height": 1750,
        "template": {
         "data": {
          "bar": [
           {
            "error_x": {
             "color": "#f2f5fa"
            },
            "error_y": {
             "color": "#f2f5fa"
            },
            "marker": {
             "line": {
              "color": "rgb(17,17,17)",
              "width": 0.5
             },
             "pattern": {
              "fillmode": "overlay",
              "size": 10,
              "solidity": 0.2
             }
            },
            "type": "bar"
           }
          ],
          "barpolar": [
           {
            "marker": {
             "line": {
              "color": "rgb(17,17,17)",
              "width": 0.5
             },
             "pattern": {
              "fillmode": "overlay",
              "size": 10,
              "solidity": 0.2
             }
            },
            "type": "barpolar"
           }
          ],
          "carpet": [
           {
            "aaxis": {
             "endlinecolor": "#A2B1C6",
             "gridcolor": "#506784",
             "linecolor": "#506784",
             "minorgridcolor": "#506784",
             "startlinecolor": "#A2B1C6"
            },
            "baxis": {
             "endlinecolor": "#A2B1C6",
             "gridcolor": "#506784",
             "linecolor": "#506784",
             "minorgridcolor": "#506784",
             "startlinecolor": "#A2B1C6"
            },
            "type": "carpet"
           }
          ],
          "choropleth": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "type": "choropleth"
           }
          ],
          "contour": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "colorscale": [
             [
              0,
              "#0d0887"
             ],
             [
              0.1111111111111111,
              "#46039f"
             ],
             [
              0.2222222222222222,
              "#7201a8"
             ],
             [
              0.3333333333333333,
              "#9c179e"
             ],
             [
              0.4444444444444444,
              "#bd3786"
             ],
             [
              0.5555555555555556,
              "#d8576b"
             ],
             [
              0.6666666666666666,
              "#ed7953"
             ],
             [
              0.7777777777777778,
              "#fb9f3a"
             ],
             [
              0.8888888888888888,
              "#fdca26"
             ],
             [
              1,
              "#f0f921"
             ]
            ],
            "type": "contour"
           }
          ],
          "contourcarpet": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "type": "contourcarpet"
           }
          ],
          "heatmap": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "colorscale": [
             [
              0,
              "#0d0887"
             ],
             [
              0.1111111111111111,
              "#46039f"
             ],
             [
              0.2222222222222222,
              "#7201a8"
             ],
             [
              0.3333333333333333,
              "#9c179e"
             ],
             [
              0.4444444444444444,
              "#bd3786"
             ],
             [
              0.5555555555555556,
              "#d8576b"
             ],
             [
              0.6666666666666666,
              "#ed7953"
             ],
             [
              0.7777777777777778,
              "#fb9f3a"
             ],
             [
              0.8888888888888888,
              "#fdca26"
             ],
             [
              1,
              "#f0f921"
             ]
            ],
            "type": "heatmap"
           }
          ],
          "histogram": [
           {
            "marker": {
             "pattern": {
              "fillmode": "overlay",
              "size": 10,
              "solidity": 0.2
             }
            },
            "type": "histogram"
           }
          ],
          "histogram2d": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "colorscale": [
             [
              0,
              "#0d0887"
             ],
             [
              0.1111111111111111,
              "#46039f"
             ],
             [
              0.2222222222222222,
              "#7201a8"
             ],
             [
              0.3333333333333333,
              "#9c179e"
             ],
             [
              0.4444444444444444,
              "#bd3786"
             ],
             [
              0.5555555555555556,
              "#d8576b"
             ],
             [
              0.6666666666666666,
              "#ed7953"
             ],
             [
              0.7777777777777778,
              "#fb9f3a"
             ],
             [
              0.8888888888888888,
              "#fdca26"
             ],
             [
              1,
              "#f0f921"
             ]
            ],
            "type": "histogram2d"
           }
          ],
          "histogram2dcontour": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "colorscale": [
             [
              0,
              "#0d0887"
             ],
             [
              0.1111111111111111,
              "#46039f"
             ],
             [
              0.2222222222222222,
              "#7201a8"
             ],
             [
              0.3333333333333333,
              "#9c179e"
             ],
             [
              0.4444444444444444,
              "#bd3786"
             ],
             [
              0.5555555555555556,
              "#d8576b"
             ],
             [
              0.6666666666666666,
              "#ed7953"
             ],
             [
              0.7777777777777778,
              "#fb9f3a"
             ],
             [
              0.8888888888888888,
              "#fdca26"
             ],
             [
              1,
              "#f0f921"
             ]
            ],
            "type": "histogram2dcontour"
           }
          ],
          "mesh3d": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "type": "mesh3d"
           }
          ],
          "parcoords": [
           {
            "line": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "parcoords"
           }
          ],
          "pie": [
           {
            "automargin": true,
            "type": "pie"
           }
          ],
          "scatter": [
           {
            "marker": {
             "line": {
              "color": "#283442"
             }
            },
            "type": "scatter"
           }
          ],
          "scatter3d": [
           {
            "line": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scatter3d"
           }
          ],
          "scattercarpet": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scattercarpet"
           }
          ],
          "scattergeo": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scattergeo"
           }
          ],
          "scattergl": [
           {
            "marker": {
             "line": {
              "color": "#283442"
             }
            },
            "type": "scattergl"
           }
          ],
          "scattermap": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scattermap"
           }
          ],
          "scattermapbox": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scattermapbox"
           }
          ],
          "scatterpolar": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scatterpolar"
           }
          ],
          "scatterpolargl": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scatterpolargl"
           }
          ],
          "scatterternary": [
           {
            "marker": {
             "colorbar": {
              "outlinewidth": 0,
              "ticks": ""
             }
            },
            "type": "scatterternary"
           }
          ],
          "surface": [
           {
            "colorbar": {
             "outlinewidth": 0,
             "ticks": ""
            },
            "colorscale": [
             [
              0,
              "#0d0887"
             ],
             [
              0.1111111111111111,
              "#46039f"
             ],
             [
              0.2222222222222222,
              "#7201a8"
             ],
             [
              0.3333333333333333,
              "#9c179e"
             ],
             [
              0.4444444444444444,
              "#bd3786"
             ],
             [
              0.5555555555555556,
              "#d8576b"
             ],
             [
              0.6666666666666666,
              "#ed7953"
             ],
             [
              0.7777777777777778,
              "#fb9f3a"
             ],
             [
              0.8888888888888888,
              "#fdca26"
             ],
             [
              1,
              "#f0f921"
             ]
            ],
            "type": "surface"
           }
          ],
          "table": [
           {
            "cells": {
             "fill": {
              "color": "#506784"
             },
             "line": {
              "color": "rgb(17,17,17)"
             }
            },
            "header": {
             "fill": {
              "color": "#2a3f5f"
             },
             "line": {
              "color": "rgb(17,17,17)"
             }
            },
            "type": "table"
           }
          ]
         },
         "layout": {
          "annotationdefaults": {
           "arrowcolor": "#f2f5fa",
           "arrowhead": 0,
           "arrowwidth": 1
          },
          "autotypenumbers": "strict",
          "coloraxis": {
           "colorbar": {
            "outlinewidth": 0,
            "ticks": ""
           }
          },
          "colorscale": {
           "diverging": [
            [
             0,
             "#8e0152"
            ],
            [
             0.1,
             "#c51b7d"
            ],
            [
             0.2,
             "#de77ae"
            ],
            [
             0.3,
             "#f1b6da"
            ],
            [
             0.4,
             "#fde0ef"
            ],
            [
             0.5,
             "#f7f7f7"
            ],
            [
             0.6,
             "#e6f5d0"
            ],
            [
             0.7,
             "#b8e186"
            ],
            [
             0.8,
             "#7fbc41"
            ],
            [
             0.9,
             "#4d9221"
            ],
            [
             1,
             "#276419"
            ]
           ],
           "sequential": [
            [
             0,
             "#0d0887"
            ],
            [
             0.1111111111111111,
             "#46039f"
            ],
            [
             0.2222222222222222,
             "#7201a8"
            ],
            [
             0.3333333333333333,
             "#9c179e"
            ],
            [
             0.4444444444444444,
             "#bd3786"
            ],
            [
             0.5555555555555556,
             "#d8576b"
            ],
            [
             0.6666666666666666,
             "#ed7953"
            ],
            [
             0.7777777777777778,
             "#fb9f3a"
            ],
            [
             0.8888888888888888,
             "#fdca26"
            ],
            [
             1,
             "#f0f921"
            ]
           ],
           "sequentialminus": [
            [
             0,
             "#0d0887"
            ],
            [
             0.1111111111111111,
             "#46039f"
            ],
            [
             0.2222222222222222,
             "#7201a8"
            ],
            [
             0.3333333333333333,
             "#9c179e"
            ],
            [
             0.4444444444444444,
             "#bd3786"
            ],
            [
             0.5555555555555556,
             "#d8576b"
            ],
            [
             0.6666666666666666,
             "#ed7953"
            ],
            [
             0.7777777777777778,
             "#fb9f3a"
            ],
            [
             0.8888888888888888,
             "#fdca26"
            ],
            [
             1,
             "#f0f921"
            ]
           ]
          },
          "colorway": [
           "#636efa",
           "#EF553B",
           "#00cc96",
           "#ab63fa",
           "#FFA15A",
           "#19d3f3",
           "#FF6692",
           "#B6E880",
           "#FF97FF",
           "#FECB52"
          ],
          "font": {
           "color": "#f2f5fa"
          },
          "geo": {
           "bgcolor": "rgb(17,17,17)",
           "lakecolor": "rgb(17,17,17)",
           "landcolor": "rgb(17,17,17)",
           "showlakes": true,
           "showland": true,
           "subunitcolor": "#506784"
          },
          "hoverlabel": {
           "align": "left"
          },
          "hovermode": "closest",
          "mapbox": {
           "style": "dark"
          },
          "paper_bgcolor": "rgb(17,17,17)",
          "plot_bgcolor": "rgb(17,17,17)",
          "polar": {
           "angularaxis": {
            "gridcolor": "#506784",
            "linecolor": "#506784",
            "ticks": ""
           },
           "bgcolor": "rgb(17,17,17)",
           "radialaxis": {
            "gridcolor": "#506784",
            "linecolor": "#506784",
            "ticks": ""
           }
          },
          "scene": {
           "xaxis": {
            "backgroundcolor": "rgb(17,17,17)",
            "gridcolor": "#506784",
            "gridwidth": 2,
            "linecolor": "#506784",
            "showbackground": true,
            "ticks": "",
            "zerolinecolor": "#C8D4E3"
           },
           "yaxis": {
            "backgroundcolor": "rgb(17,17,17)",
            "gridcolor": "#506784",
            "gridwidth": 2,
            "linecolor": "#506784",
            "showbackground": true,
            "ticks": "",
            "zerolinecolor": "#C8D4E3"
           },
           "zaxis": {
            "backgroundcolor": "rgb(17,17,17)",
            "gridcolor": "#506784",
            "gridwidth": 2,
            "linecolor": "#506784",
            "showbackground": true,
            "ticks": "",
            "zerolinecolor": "#C8D4E3"
           }
          },
          "shapedefaults": {
           "line": {
            "color": "#f2f5fa"
           }
          },
          "sliderdefaults": {
           "bgcolor": "#C8D4E3",
           "bordercolor": "rgb(17,17,17)",
           "borderwidth": 1,
           "tickwidth": 0
          },
          "ternary": {
           "aaxis": {
            "gridcolor": "#506784",
            "linecolor": "#506784",
            "ticks": ""
           },
           "baxis": {
            "gridcolor": "#506784",
            "linecolor": "#506784",
            "ticks": ""
           },
           "bgcolor": "rgb(17,17,17)",
           "caxis": {
            "gridcolor": "#506784",
            "linecolor": "#506784",
            "ticks": ""
           }
          },
          "title": {
           "x": 0.05
          },
          "updatemenudefaults": {
           "bgcolor": "#506784",
           "borderwidth": 0
          },
          "xaxis": {
           "automargin": true,
           "gridcolor": "#283442",
           "linecolor": "#506784",
           "ticks": "",
           "title": {
            "standoff": 15
           },
           "zerolinecolor": "#283442",
           "zerolinewidth": 2
          },
          "yaxis": {
           "automargin": true,
           "gridcolor": "#283442",
           "linecolor": "#506784",
           "ticks": "",
           "title": {
            "standoff": 15
           },
           "zerolinecolor": "#283442",
           "zerolinewidth": 2
          }
         }
        },
        "title": {
         "text": "Segment Comparison"
        },
        "xaxis": {
         "anchor": "y",
         "domain": [
          0,
          1
         ]
        },
        "xaxis2": {
         "anchor": "y2",
         "domain": [
          0,
          1
         ]
        },
        "xaxis3": {
         "anchor": "y3",
         "domain": [
          0,
          1
         ]
        },
        "xaxis4": {
         "anchor": "y4",
         "domain": [
          0,
          1
         ]
        },
        "xaxis5": {
         "anchor": "y5",
         "domain": [
          0,
          1
         ]
        },
        "xaxis6": {
         "anchor": "y6",
         "domain": [
          0,
          1
         ]
        },
        "xaxis7": {
         "anchor": "y7",
         "domain": [
          0,
          1
         ]
        },
        "yaxis": {
         "anchor": "x",
         "domain": [
          0.9257142857142857,
          1
         ]
        },
        "yaxis2": {
         "anchor": "x2",
         "domain": [
          0.7714285714285715,
          0.8457142857142858
         ]
        },
        "yaxis3": {
         "anchor": "x3",
         "domain": [
          0.6171428571428572,
          0.6914285714285715
         ]
        },
        "yaxis4": {
         "anchor": "x4",
         "domain": [
          0.46285714285714286,
          0.5371428571428571
         ]
        },
        "yaxis5": {
         "anchor": "x5",
         "domain": [
          0.3085714285714286,
          0.3828571428571429
         ]
        },
        "yaxis6": {
         "anchor": "x6",
         "domain": [
          0.1542857142857143,
          0.2285714285714286
         ]
        },
        "yaxis7": {
         "anchor": "x7",
         "domain": [
          0,
          0.07428571428571429
         ]
        }
       }
      },
      "image/png": "[encoded data, 413344 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from plotly.subplots import make_subplots\n",
    "\n",
    "if segments:\n",
    "    n_segs = len(segments)\n",
    "    fig3 = make_subplots(rows=n_segs, cols=1,\n",
    "                         subplot_titles=[f'Segment {i+1} ({s_end-s_start:.2f}s)'\n",
    "                                         for i, (s_start, s_end, _) in enumerate(segments)],\n",
    "                         vertical_spacing=0.08)\n",
    "\n",
    "    for i, (s_start, s_end, audio) in enumerate(segments):\n",
    "        seg_time = np.arange(len(audio)) / SAMPLE_RATE\n",
    "        fig3.add_trace(\n",
    "            go.Scattergl(x=seg_time, y=audio, mode='lines',\n",
    "                         line=dict(width=0.5), showlegend=False),\n",
    "            row=i+1, col=1\n",
    "        )\n",
    "\n",
    "    fig3.update_layout(height=SEGMENT_COMPARE_HEIGHT * n_segs,\n",
    "                       template=CHART_TEMPLATE,\n",
    "                       title='Segment Comparison')\n",
    "    fig3.show()\n",
    "else:\n",
    "    print('No segments to compare.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.14.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
