{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.13.0"
    },
    "blog_metadata": {
      "topic": "How Real-Time Multichannel Speech-to-Text Expands Azure’s Voice and Contact-Center Story",
      "slug": "how-real-time-multichannel-speech-to-text-expands-azure-s-vo",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-11-11T21:11:02.701Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# How Real-Time Multichannel Speech-to-Text Expands Azure’s Voice and Contact-Center Story\n",
        "\n",
        "This notebook turns the blog post into a hands-on validation workflow for multichannel speech-to-text architecture in contact centers. The focus is not just transcript quality, but preserving speaker attribution so downstream systems like QA, compliance, agent assist, and analytics can act on accountable conversation events in real time."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install -q pandas"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, field, asdict\n",
        "from typing import Literal, Optional, Dict, Any, List\n",
        "import json\n",
        "import os\n",
        "import time\n",
        "import pandas as pd"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Architecture overview\n",
        "\n",
        "This cell captures the reference architecture from the post as executable notebook data. Instead of rendering Mermaid, we represent the flow as structured edges so it can be inspected, validated, or exported."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "architecture_edges = [\n",
        "    (\"Customer + Agent Audio\", \"Azure Speech Real-Time Multichannel STT\"),\n",
        "    (\"Azure Speech Real-Time Multichannel STT\", \"Attributed Transcript Events\"),\n",
        "    (\"Attributed Transcript Events\", \"Agent Assist\"),\n",
        "    (\"Attributed Transcript Events\", \"Supervisor / QA Analytics\"),\n",
        "    (\"Attributed Transcript Events\", \"CRM / Case Timeline\"),\n",
        "    (\"Attributed Transcript Events\", \"Compliance / Archive\"),\n",
        "]\n",
        "\n",
        "for src, dst in architecture_edges:\n",
        "    print(f\"{src} -> {dst}\")\n",
        "\n",
        "pd.DataFrame(architecture_edges, columns=[\"from\", \"to\"])"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Attributed transcript event schema\n",
        "\n",
        "This example defines a normalized event contract for multichannel contact-center streaming. The key idea is that downstream systems should consume attributed events with channel, speaker role, timing, and confidence instead of a single merged transcript blob."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, field, asdict\n",
        "from typing import Literal, Optional, Dict, Any\n",
        "import json\n",
        "\n",
        "@dataclass\n",
        "class TranscriptEvent:\n",
        "    interaction_id: str\n",
        "    channel: Literal[\"left\", \"right\", \"mixed\"]\n",
        "    speaker_role: Literal[\"customer\", \"agent\", \"ivr\", \"unknown\"]\n",
        "    offset_ms: int\n",
        "    duration_ms: int\n",
        "    text: str\n",
        "    confidence: float\n",
        "    language: str = \"en-US\"\n",
        "    qa_route: Optional[str] = None\n",
        "    agent_assist_topic: Optional[str] = None\n",
        "    metadata: Dict[str, Any] = field(default_factory=dict)\n",
        "\n",
        "event = TranscriptEvent(\n",
        "    \"call-1007\",\n",
        "    \"left\",\n",
        "    \"customer\",\n",
        "    1250,\n",
        "    1840,\n",
        "    \"I need to change my flight.\",\n",
        "    0.97,\n",
        "    qa_route=\"intent-triage\",\n",
        "    agent_assist_topic=\"travel-change\"\n",
        ")\n",
        "print(json.dumps(asdict(event), indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Normalize raw recognizer output into a stable event payload\n",
        "\n",
        "This example converts raw recognizer timing fields into a cleaner event model. It demonstrates how to preserve attribution and timing in milliseconds so orchestration and analytics layers can use a consistent contract."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, asdict\n",
        "import json\n",
        "\n",
        "@dataclass\n",
        "class NormalizedEvent:\n",
        "    interaction_id: str\n",
        "    speaker_role: str\n",
        "    channel: str\n",
        "    start_ms: int\n",
        "    end_ms: int\n",
        "    text: str\n",
        "    confidence: float\n",
        "    route: str\n",
        "\n",
        "raw = {\"offset\": 5300000, \"duration\": 2100000, \"text\": \"Let me verify your account.\", \"confidence\": 0.94}\n",
        "event = NormalizedEvent(\n",
        "    interaction_id=\"call-1007\",\n",
        "    speaker_role=\"agent\",\n",
        "    channel=\"right\",\n",
        "    start_ms=raw[\"offset\"] // 10000,\n",
        "    end_ms=(raw[\"offset\"] + raw[\"duration\"]) // 10000,\n",
        "    text=raw[\"text\"],\n",
        "    confidence=raw[\"confidence\"],\n",
        "    route=\"agent-assist\"\n",
        ")\n",
        "print(json.dumps(asdict(event), separators=(\",\", \":\")))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Route events to workload-specific paths\n",
        "\n",
        "This example shows simple deterministic routing logic based on speaker role, confidence, and utterance content. It reflects the blog’s recommendation to separate live assist, compliance, and archive paths instead of forcing every workload through one generic transcript pipeline."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from typing import Dict\n",
        "\n",
        "def choose_route(event: Dict[str, object]) -> str:\n",
        "    if event[\"speaker_role\"] == \"customer\" and event[\"confidence\"] >= 0.85:\n",
        "        return \"intent-and-sentiment\"\n",
        "    if event[\"speaker_role\"] == \"agent\" and \"verify\" in str(event[\"text\"]).lower():\n",
        "        return \"compliance-check\"\n",
        "    return \"archive-only\"\n",
        "\n",
        "samples = [\n",
        "    {\"speaker_role\": \"customer\", \"confidence\": 0.96, \"text\": \"I want to cancel my order\"},\n",
        "    {\"speaker_role\": \"agent\", \"confidence\": 0.91, \"text\": \"Let me verify your address\"},\n",
        "]\n",
        "for item in samples:\n",
        "    print(choose_route(item))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Required environment variables\n",
        "\n",
        "If you connect this notebook to real Azure services or a pilot environment, validate these variables first:\n",
        "\n",
        "- `AZURE_SPEECH_KEY`\n",
        "- `AZURE_SPEECH_REGION`\n",
        "- `AZURE_STORAGE_CONNECTION_STRING`\n",
        "- `PILOT_INTERACTION_ID`\n",
        "- `PILOT_LOCALE` (optional, defaults to `en-US`)\n",
        "- `PILOT_CHANNEL_COUNT` (optional, defaults to `2`)\n",
        "\n",
        "The next two cells translate the original PowerShell validation and configuration examples into Python."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Validate required environment variables\n",
        "\n",
        "This cell checks whether the minimum configuration for a speech-to-text pilot is present. It is useful before wiring the notebook into live streaming, storage, or orchestration services."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import os\n",
        "\n",
        "required = [\n",
        "    \"AZURE_SPEECH_KEY\",\n",
        "    \"AZURE_SPEECH_REGION\",\n",
        "    \"AZURE_STORAGE_CONNECTION_STRING\",\n",
        "    \"PILOT_INTERACTION_ID\",\n",
        "]\n",
        "\n",
        "missing = [name for name in required if not os.environ.get(name, \"\").strip()]\n",
        "\n",
        "if missing:\n",
        "    print(\"Missing required environment variables: \" + \", \".join(missing))\n",
        "else:\n",
        "    print(\"Environment validation passed.\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Load non-secret pilot settings\n",
        "\n",
        "This cell loads non-secret runtime settings from environment variables while keeping credentials out of source code. It mirrors the configuration pattern from the post and provides sensible defaults for locale and channel count."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import os\n",
        "\n",
        "config = {\n",
        "    \"SpeechRegion\": os.environ.get(\"AZURE_SPEECH_REGION\"),\n",
        "    \"Locale\": os.environ.get(\"PILOT_LOCALE\") or \"en-US\",\n",
        "    \"Channels\": os.environ.get(\"PILOT_CHANNEL_COUNT\") or \"2\",\n",
        "    \"InteractionId\": os.environ.get(\"PILOT_INTERACTION_ID\"),\n",
        "}\n",
        "\n",
        "for key in sorted(config):\n",
        "    print(f\"{key}={config[key]}\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Sequence of real-time event flow\n",
        "\n",
        "This cell represents the sequence diagram from the post as ordered steps. It helps validate the intended handoff from audio capture to STT, event streaming, agent assist, and QA enrichment."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "sequence_steps = [\n",
        "    (\"Call Audio\", \"Azure Real-Time STT\", \"Multichannel audio frames\"),\n",
        "    (\"Azure Real-Time STT\", \"Event Stream\", \"Attributed transcript event\"),\n",
        "    (\"Event Stream\", \"Agent Assist\", \"Agent-side guidance trigger\"),\n",
        "    (\"Event Stream\", \"QA Analytics\", \"Quality/compliance enrichment\"),\n",
        "    (\"QA Analytics\", \"Event Stream\", \"Scores and flags\"),\n",
        "]\n",
        "\n",
        "for sender, receiver, message in sequence_steps:\n",
        "    print(f\"{sender} -> {receiver}: {message}\")\n",
        "\n",
        "pd.DataFrame(sequence_steps, columns=[\"sender\", \"receiver\", \"message\"])"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Aggregate per-speaker transcript text\n",
        "\n",
        "This example groups utterances by speaker role for CRM timelines, summaries, or replay views. It demonstrates why preserving attribution upstream makes downstream summarization and analytics more reliable."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "events = [\n",
        "    {\"speaker_role\": \"customer\", \"text\": \"I need to change my flight.\"},\n",
        "    {\"speaker_role\": \"agent\", \"text\": \"I can help with that.\"},\n",
        "    {\"speaker_role\": \"customer\", \"text\": \"I prefer the morning departure.\"},\n",
        "]\n",
        "\n",
        "timeline = {}\n",
        "for event in events:\n",
        "    role = event[\"speaker_role\"]\n",
        "    timeline.setdefault(role, []).append(event[\"text\"])\n",
        "\n",
        "for role, utterances in timeline.items():\n",
        "    print(f\"{role}: {' '.join(utterances)}\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## End-to-end validation with attributed events\n",
        "\n",
        "This additional hands-on example simulates a short multichannel interaction and validates several architecture goals from the post: speaker accountability, workload-specific routing, replayability, and curated facts for analytics."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "simulated_events = [\n",
        "    {\n",
        "        \"conversationId\": \"call-1007\",\n",
        "        \"speakerRole\": \"customer\",\n",
        "        \"channelId\": \"left\",\n",
        "        \"offsetMs\": 1250,\n",
        "        \"durationMs\": 1840,\n",
        "        \"text\": \"I need to change my flight.\",\n",
        "        \"confidence\": 0.97,\n",
        "    },\n",
        "    {\n",
        "        \"conversationId\": \"call-1007\",\n",
        "        \"speakerRole\": \"agent\",\n",
        "        \"channelId\": \"right\",\n",
        "        \"offsetMs\": 3400,\n",
        "        \"durationMs\": 1600,\n",
        "        \"text\": \"I can help with that. Let me verify your account.\",\n",
        "        \"confidence\": 0.94,\n",
        "    },\n",
        "    {\n",
        "        \"conversationId\": \"call-1007\",\n",
        "        \"speakerRole\": \"customer\",\n",
        "        \"channelId\": \"left\",\n",
        "        \"offsetMs\": 5600,\n",
        "        \"durationMs\": 1400,\n",
        "        \"text\": \"I prefer the morning departure.\",\n",
        "        \"confidence\": 0.96,\n",
        "    },\n",
        "]\n",
        "\n",
        "def route_event(e):\n",
        "    if e[\"speakerRole\"] == \"customer\" and e[\"confidence\"] >= 0.85:\n",
        "        return \"live-assist:intent-and-sentiment\"\n",
        "    if e[\"speakerRole\"] == \"agent\" and \"verify\" in e[\"text\"].lower():\n",
        "        return \"near-real-time:compliance-check\"\n",
        "    return \"batch:archive-only\"\n",
        "\n",
        "validated = []\n",
        "for e in simulated_events:\n",
        "    record = dict(e)\n",
        "    record[\"route\"] = route_event(e)\n",
        "    validated.append(record)\n",
        "\n",
        "print(json.dumps(validated, indent=2))\n",
        "\n",
        "print(\"\\nSpeaker attribution present on every event:\", all(\"speakerRole\" in e and e[\"speakerRole\"] for e in validated))\n",
        "print(\"Channel identity present on every event:\", all(\"channelId\" in e and e[\"channelId\"] for e in validated))\n",
        "print(\"Replay order preserved:\", [e[\"offsetMs\"] for e in validated] == sorted(e[\"offsetMs\"] for e in validated))\n",
        "\n",
        "curated_facts = {\n",
        "    \"conversationId\": \"call-1007\",\n",
        "    \"customer_intent\": \"travel-change\",\n",
        "    \"agent_verification_performed\": any(\"verify\" in e[\"text\"].lower() and e[\"speakerRole\"] == \"agent\" for e in validated),\n",
        "    \"customer_preferences\": [e[\"text\"] for e in validated if e[\"speakerRole\"] == \"customer\" and \"prefer\" in e[\"text\"].lower()],\n",
        "}\n",
        "\n",
        "print(\"\\nCurated facts:\")\n",
        "print(json.dumps(curated_facts, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Architecture scorecard\n",
        "\n",
        "This scorecard operationalizes the benchmark from the post. Use it to assess whether your current design preserves attribution, meets live latency expectations, supports QA replay, proves compliance statements, and separates curated analytics from sensitive raw data."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "scorecard = pd.DataFrame([\n",
        "    {\n",
        "        \"benchmark\": \"Identify the speaker correctly at every turn\",\n",
        "        \"why_it_matters\": \"QA, compliance, and summaries depend on accountable attribution\",\n",
        "        \"status_example\": \"Pass if every event has stable speakerRole and channelId\",\n",
        "    },\n",
        "    {\n",
        "        \"benchmark\": \"Trigger an action in under 2 seconds for live assist\",\n",
        "        \"why_it_matters\": \"Guidance must arrive while the interaction is still live\",\n",
        "        \"status_example\": \"Pass if streaming path is isolated from heavy summarization\",\n",
        "    },\n",
        "    {\n",
        "        \"benchmark\": \"QA can replay the exact sequence of attributed events\",\n",
        "        \"why_it_matters\": \"Audits and coaching require evidence, not inferred turns\",\n",
        "        \"status_example\": \"Pass if raw event log retains offsets, durations, and text\",\n",
        "    },\n",
        "    {\n",
        "        \"benchmark\": \"Compliance can prove who made a statement and when\",\n",
        "        \"why_it_matters\": \"Disclosures and promises must be attributable\",\n",
        "        \"status_example\": \"Pass if agent/customer channels remain distinct from capture onward\",\n",
        "    },\n",
        "    {\n",
        "        \"benchmark\": \"Analytics can consume curated facts without touching sensitive raw audio\",\n",
        "        \"why_it_matters\": \"Governance and privacy improve when workloads are separated\",\n",
        "        \"status_example\": \"Pass if BI reads curated facts rather than token-level raw streams\",\n",
        "    },\n",
        "])\n",
        "\n",
        "scorecard"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Summary\n",
        "\n",
        "This notebook validated the core argument of the post: in contact centers, the real value of speech-to-text comes from preserving attribution early enough to drive live and governed decisions. Multichannel STT becomes strategically useful when it emits stable attributed events, separates workload paths, and supports replay, compliance, and analytics without collapsing everything into one transcript.\n",
        "\n",
        "## Next Steps\n",
        "\n",
        "- Connect the event schema to a real Azure Speech streaming prototype.\n",
        "- Measure end-to-end latency for live assist versus post-call enrichment paths.\n",
        "- Add redaction, retention, and access-control rules for governed event storage.\n",
        "- Extend routing logic with policy markers, sentiment shifts, and objection detection.\n",
        "- Build a replay and audit view that reconstructs exact attributed event timelines."
      ]
    }
  ]
}