Choose live captions when you need words as someone speaks, or fast file
transcription when you need speaker labels and timestamps after a recording.
This local Gradio app lets you try both with MAI-Transcribe-2 models. It's for
Python developers adding transcription to meeting, media, or captioning apps.
Use recordings you have permission to process.

After completing this recipe, you can:

- Configure a file transcription request with speaker labels and timestamps.
- Compare transcripts with and without a phrase-list hint.
- Interpret provisional and committed captions in a streaming response.

## Watch the app transcribe a meeting

Watch the app transcribe a meeting as it plays. Then see how to save the
recording and transcribe it again as a file, with labels identifying each
speaker.

The video has audio and English captions.

<video controls preload="metadata" aria-label="Meeting app: live captions, download recording, and verbatim speaker-labeled file transcription" style="width:100%;height:auto">
  <source src="media/mai-transcribe-2/05-meeting-app-workflow.mp4" type="video/mp4">
  <track src="media/mai-transcribe-2/05-meeting-app-workflow.vtt" kind="captions" srclang="en" label="English">
</video>

[Download the walkthrough with audio](media/mai-transcribe-2/05-meeting-app-workflow.mp4).

## Scenarios to try

Explore the scenarios highlighted in the
[MAI-Transcribe-2 announcement](https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/mai-transcribe-2-highest-quality-transcription-at-the-fastest-speed-and-lowest-c/4550972):

- **Meetings, interviews, and recorded calls:** review speaker turns and
  domain-specific terms in a transcript.
- **Media and recorded presentations:** use word timestamps to locate speech
  in the recording.
- **Live speech:** watch provisional captions appear and change while a
  person speaks.

## Choose an interface

| Need | Interface | Result |
| --- | --- | --- |
| A completed recording with speaker labels or timestamps | [Fast transcription](https://learn.microsoft.com/azure/ai-services/speech-service/mai-transcribe) | A transcript with optional speaker and timing information |
| Captions while someone speaks | [Realtime API](https://learn.microsoft.com/azure/ai-services/speech-service/mai-transcribe-2-streaming-realtime) | Provisional and committed text as audio streams |

Streaming is in public preview without an SLA and isn't recommended for
production workloads. This app doesn't measure accuracy or latency; compare
its results with your own audio instead.

## Before you start

Estimated time, approximate:

- **Setup:** 15 to 25 minutes to create the resource and streaming deployment
  and install dependencies. A clean dependency install took about 3 minutes
  in testing.
- **App walkthrough:** about 10 minutes.
- **Optional API examples:** about 5 minutes, including about 31 seconds of
  streaming.

- Open this notebook from the Forgebook `notebooks/` directory with Python 3.11
  or later and Jupyter. Its `data/mai-transcribe-2/` folder contains the app, the
  sample recording, and the dependencies.
- [Create a Microsoft Foundry resource for Speech](https://learn.microsoft.com/azure/ai-services/multi-service-resource?pivots=azportal)
  or use one you already have. For file transcription, choose a region
  marked as supported in the **Transcribe with MAI-Transcribe** column
  of the [Speech service regions table](https://learn.microsoft.com/azure/ai-services/speech-service/regions?tabs=llmspeech).
  The currently listed resource regions are `centralindia`, `centralus`, `eastus`,
  `northeurope`, `southeastasia`, `swedencentral`, `westeurope`, `westus`, and
  `westus2`. For live transcription, deploy MAI-Transcribe-2-Streaming and
  follow its [availability guide](https://learn.microsoft.com/azure/ai-services/speech-service/mai-transcribe-2-streaming#availability-and-regions),
  which lists `centralus`, `eastus2`, `southeastasia`, and `swedencentral` as
  serving regions. This streaming serving-region list is distinct from the
  file model's resource-region list.
  Each path needs its endpoint and API key; both models can use the same
  resource when its region supports both.

> **Authentication:** MAI-Transcribe-2 supports both API keys and keyless
> Microsoft Entra ID authentication. This recipe uses API keys only for
> demonstration purposes; prefer Microsoft Entra ID for production workloads.
> To set it up, see [Configure Microsoft Entra authentication](https://learn.microsoft.com/azure/ai-services/speech-service/how-to-configure-azure-ad-auth).

### Find the endpoint, key, and deployment

In the Azure portal, open your resource and select **Keys and Endpoint**;
use its resource endpoint and a key for the app. For live audio, open your
project in the Foundry portal, select **Build** > **Models** > **Deploy a
base model**, find MAI-Transcribe-2-Streaming, and select **Deploy**. Note
the deployment name on the Models page. The fast transcription API selects
its model in the request and doesn't need a separate model deployment.

Alternatively, in Bash with the [Azure CLI](https://learn.microsoft.com/cli/azure/)
signed in to the correct subscription, replace the two values below. The
commands get the resource endpoint and key and list streaming deployments:

```bash
RESOURCE_GROUP="<resource-group>"
RESOURCE_NAME="<resource-name>"
MAI_ENDPOINT="$(az cognitiveservices account show --resource-group "$RESOURCE_GROUP" --name "$RESOURCE_NAME" --query properties.endpoint -o tsv)"
MAI_API_KEY="$(az cognitiveservices account keys list --resource-group "$RESOURCE_GROUP" --name "$RESOURCE_NAME" --query key1 -o tsv)"
export MAI_ENDPOINT MAI_API_KEY
az cognitiveservices account deployment list --resource-group "$RESOURCE_GROUP" --name "$RESOURCE_NAME" --query "[?properties.model.name=='MAI-Transcribe-2-Streaming'].name" -o tsv
```

The list command finds existing deployments; create one in Foundry first if
the list is empty. For the API examples, export `MAI_STREAMING_DEPLOYMENT`
with the deployment name if it differs from `MAI-Transcribe-2-Streaming`.
If streaming uses a different resource, repeat the endpoint and key lookup
for that resource and export them as `MAI_STREAMING_ENDPOINT` and
`MAI_STREAMING_API_KEY`. Start Jupyter from the same shell so the kernel
inherits these variables. For the app, enter the endpoint, key, and deployment
name in **Settings**; shell variables are for the API examples only.
See the CLI references for [accounts](https://learn.microsoft.com/cli/azure/cognitiveservices/account),
[keys](https://learn.microsoft.com/cli/azure/cognitiveservices/account/keys),
and [deployments](https://learn.microsoft.com/cli/azure/cognitiveservices/account/deployment).
Don't print or share keys, enable shell tracing, or save keys in the notebook.

- Use recordings you have permission to process and obtain any required
  consent. The app sends audio to Azure. Enter keys in the app, not in the
  notebook or source files.

> **Note:** App transcription requests are billed. Check
> [current pricing](https://azure.microsoft.com/pricing/details/ai-foundry-models/microsoft/)
> before submitting audio.

Install the app dependencies and PyAV, which prepares the sample recording for
the optional API examples.

```python
%pip install -r data/mai-transcribe-2/requirements.txt av
```

**Expected output:** pip reports installed or already-satisfied packages.

## Launch the local Gradio app

Run the next cell to launch the app inline in the notebook; Gradio also
provides a local URL if you prefer a separate browser tab. Open **Settings**
on the left. The next cell displays the app and a local URL. Under **Model
configuration**, enter the endpoint and API key for the model you want to
use. If your streaming deployment has a custom name, enter that name under
**MAI-Transcribe-2-Streaming**.

- Live speech: select the microphone, wait for the connection, and speak.
  Stop to finish the transcript. Select **Download recording** to save a WAV
  that you can also submit as a file.
- Recorded audio: attach a WAV, MP3, or FLAC file of up to 25 MiB. Open
  **Options** on the right to choose **Speaker labels**, **Word** timestamps,
  or **Key phrases** such as names and product terms. Select the up arrow to
  submit it. Separate key phrases with commas or newlines.

Compare the transcript, speaker turns, and times with the source audio. Try
the settings that matter for your scenario. Attaching a file alone doesn't
send a request.



```python
# Displays the app inline; it prints no output of its own.
import sys
from pathlib import Path

APP_DIR = Path("data/mai-transcribe-2").resolve()
if str(APP_DIR) not in sys.path:
    sys.path.insert(0, str(APP_DIR))
from app import MAX_UPLOAD_BYTES, build_app  # noqa: E402

demo = build_app()
demo.launch(
    server_name="127.0.0.1",
    share=False,
    inline=True,
    prevent_thread_lock=True,
    show_error=False,
    max_file_size=MAX_UPLOAD_BYTES,
)
```

## Explore the APIs with the sample

The walkthrough and saved results show the sample without requiring you to
run these cells. To explore the requests behind the app, run the optional
examples below. They use the fast transcription API for the file and the
Realtime API for streaming. Outputs can vary between runs.

### Before running the API examples

- The examples use API keys, like the app. Set `MAI_API_KEY` to a key from
  the Speech resource's **Keys and Endpoint** page in the Azure portal. If
  streaming uses another resource, also set `MAI_STREAMING_API_KEY`.
- Set `MAI_ENDPOINT` to the Speech resource's HTTPS base endpoint, for example
  `https://<resource>.services.ai.azure.com`.
- For the streaming example, deploy MAI-Transcribe-2-Streaming. If its
  deployment name differs, set `MAI_STREAMING_DEPLOYMENT`; if it's on another
  resource, set `MAI_STREAMING_ENDPOINT` to that resource's base endpoint.
  Use the portal or CLI steps above to find these values.

The examples use the [fast transcription REST API](https://learn.microsoft.com/rest/api/speechtotext/transcriptions/transcribe)
and the [Realtime API](https://learn.microsoft.com/azure/ai-services/speech-service/mai-transcribe-2-streaming-realtime).

Running all the examples sends three file requests and streams the 31-second
sample once. Those requests are billed separately from app requests.

The next cell decodes the bundled `meeting_b.m4a` to a temporary mono 16-kHz
PCM WAV. The cleanup step at the end removes it. `recipe_helpers.py` handles
the conversion and shortens printed transcript lines.

```python
import json
import os
import sys
import wave
from pathlib import Path
from urllib.parse import urlsplit

import requests

DATA_DIR = Path("data/mai-transcribe-2/")
sys.path.insert(0, str(DATA_DIR.resolve()))
from recipe_helpers import excerpt, prepare_recording  # noqa: E402

session_files, AUDIO = prepare_recording(DATA_DIR / "meeting_b.m4a")
with wave.open(str(AUDIO), "rb") as audio:
    print(
        f"Prepared: {audio.getnframes() / audio.getframerate():.3f}s, "
        f"{audio.getframerate()} Hz, {audio.getnchannels()} channel"
    )
```

**Expected output:** Prepared: 31.221s, 16000 Hz, 1 channel.
[Read the sample transcript](media/mai-transcribe-2/07-meeting-sample-transcript.txt).
Recording source: [Microsoft AI](https://microsoft.ai/models/mai-transcribe-2/).

## Who said what: speaker diarization

The [fast transcription API](https://learn.microsoft.com/rest/api/speechtotext/transcriptions/transcribe?view=rest-speechtotext-2025-10-15)
accepts the audio and a JSON `definition` as multipart form data.
`enhancedMode.enabled` and `enhancedMode.model` select MAI-Transcribe-2; both
are required, and no model deployment is needed. `with_options` adds the
model options used below. This cell reads the key and defines the helpers without
sending a request.

```python
def resource_root(variable):
    value = os.environ[variable].strip()
    parsed = urlsplit(value)
    host = parsed.hostname or ""
    if (
        parsed.scheme != "https"
        or parsed.netloc.lower() != host
        or parsed.path not in ("", "/")
        or parsed.query
        or parsed.fragment
        or not host.endswith((".services.ai.azure.com", ".cognitiveservices.azure.com"))
    ):
        raise ValueError(f"{variable} must be an HTTPS Speech resource base endpoint.")
    return f"https://{host}"


ENDPOINT = resource_root("MAI_ENDPOINT")
API_KEY = os.environ["MAI_API_KEY"].strip()
BASE = {"enhancedMode": {"enabled": True, "model": "MAI-Transcribe-2"}}


def transcribe(definition):
    with AUDIO.open("rb") as audio:
        response = requests.post(
            f"{ENDPOINT}/speechtotext/transcriptions:transcribe",
            params={"api-version": "2025-10-15"},
            headers={"Ocp-Apim-Subscription-Key": API_KEY},
            files={"audio": (AUDIO.name, audio, "audio/wav")},
            data={"definition": json.dumps(definition)},
            timeout=(10, 180),
            allow_redirects=False,
        )
    if response.status_code in range(300, 400):
        raise RuntimeError("Speech returned an unexpected redirect; check the resource endpoint.")
    response.raise_for_status()
    return response.json()



def with_options(**options):
    return {"enhancedMode": {**BASE["enhancedMode"], "modelOptions": options}}


print("Speech request helpers ready; no request sent.")
```

One request returns a transcript with clean text for reading, speaker
labels from diarization, segment timestamps for each turn, and a
phrase list with a term from this meeting, "sign-off". The next sections
reuse `meeting_definition` and change one option at a time.

```python
meeting_definition = {
    **with_options(transcribeStyle="clean", timestamps="segment"),
    "diarization": {"enabled": True},
    "phraseList": {"phrases": ["sign-off"]},
}
meeting = transcribe(meeting_definition)
meeting_text = meeting["combinedPhrases"][0]["text"]
if not meeting_text.strip():
    raise ValueError("Speech returned an empty transcript.")
print("Audio seconds:", round(meeting["durationMilliseconds"] / 1000))
print("Detected language:", meeting["phrases"][0]["locale"])
for phrase in meeting["phrases"]:
    seconds = phrase["offsetMilliseconds"] / 1000
    print(f"[{seconds:05.1f}s] Speaker {phrase['speaker']}: {excerpt(phrase['text'], 6)}")
```

**Expected output:** 31 audio seconds, detected language en, and turns
from speakers 0 and 1, each with its start time. Exact wording, segment
boundaries, and labels can vary between runs. Speaker IDs are labels within
this response, not names. Check words, speakers, and times against the
recording.

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| 401 or 403 | The key doesn't match the endpoint's resource, or key-based access is disabled | Copy the key and endpoint from the same resource; enable key-based access |
| Enhanced mode rejected | The resource region doesn't support MAI-Transcribe | Use a supported region from the regions table |
| Streaming connection fails | Wrong endpoint or deployment name | Check `MAI_STREAMING_ENDPOINT` and `MAI_STREAMING_DEPLOYMENT`; reconnect before sending more audio |
| Empty transcript or no word timestamps | The audio has no speech, or the request options changed | Check the recording and the `definition` options |

See [Speech authentication troubleshooting](https://learn.microsoft.com/azure/ai-services/speech-service/troubleshooting#authentication-failed).

## Time every word

Switch `timestamps` to word for word-level playback highlighting. Offsets
are milliseconds from the start of the audio.

```python
words = transcribe({**meeting_definition, **with_options(transcribeStyle="clean", timestamps="word")})
timed_words = [word for phrase in words["phrases"] for word in phrase.get("words", [])]
if not timed_words:
    raise ValueError("Speech returned no word timestamps.")
print("Words with timestamps:", len(timed_words))
for word in timed_words[:3]:
    print(f"{word['text']}: {word['offsetMilliseconds']} ms")
```

**Expected output:** 74 words have timestamps; the first three start
at 1520, 1920, and 2200 ms. Timing is an estimate and can vary between requests.

## Spell your terms: phrase-list biasing

Send the same request without its phrase list and compare the term.

```python
baseline = transcribe({key: value for key, value in meeting_definition.items() if key != "phraseList"})
for label, text in (("Without hint", baseline["combinedPhrases"][0]["text"]), ("With hint", meeting_text)):
    print(f"{label} contains 'sign-off':", "sign-off" in text.lower())
```

**Expected output:** false without the hint and true with it: the hint
changes the spelling to "sign-off" in this run. A hint raises a term's
likelihood; it doesn't force output. Test your own meetings' terms against the
audio.

## Watch live captions correct themselves

MAI-Transcribe-2-Streaming returns words while someone is still speaking. Its
Realtime API, in public preview without an SLA, uses an OpenAI Realtime
API–style WebSocket protocol; see the
[Realtime API guide](https://learn.microsoft.com/azure/ai-services/speech-service/mai-transcribe-2-streaming-realtime).
A session works like this:

1. A `session.update` message names the deployment and the audio format.
   Speaker labels, timestamps, and phrase lists are file options; streaming
   doesn't take them.
2. `input_audio_buffer.append` messages send base64 PCM16 mono audio, and
   `input_audio_buffer.commit` asks for the final transcript.
3. An `intermediate` event carries a provisional guess that can still change;
   replace the previous one. A `delta` event carries words that won't change;
   append it. A `completed` event carries the final text.

This cell defines the session message and a client that streams the meeting
at its real pace, recording each caption as committed and provisional text.
It doesn't connect.

```python
import asyncio
import base64

from websockets.asyncio.client import connect

STREAM_DEPLOYMENT = os.environ.get("MAI_STREAMING_DEPLOYMENT", "MAI-Transcribe-2-Streaming")
EVENT = "conversation.item.input_audio_transcription."


def streaming_session(deployment):
    return {
        "type": "session.update",
        "session": {
            "type": "transcription",
            "audio": {
                "input": {
                    "format": {"type": "audio/pcm", "rate": 16_000},
                    "transcription": {"model": deployment},
                    "turn_detection": None,
                }
            },
        },
    }


async def next_event(websocket):
    event = json.loads(await websocket.recv())
    if event["type"] in ("error", f"{EVENT}failed"):
        raise RuntimeError(f"Realtime API error: {event.get('error', {}).get('code', 'unknown')}")
    return event


async def send_audio(websocket, chunk_ms=100):
    with wave.open(str(AUDIO), "rb") as audio:
        frames = audio.getframerate() * chunk_ms // 1000
        while chunk := audio.readframes(frames):
            await websocket.send(
                json.dumps({"type": "input_audio_buffer.append", "audio": base64.b64encode(chunk).decode()})
            )
            await asyncio.sleep(chunk_ms / 1000)
    await websocket.send(json.dumps({"type": "input_audio_buffer.commit"}))


async def stream_meeting(deployment):
    root = resource_root("MAI_STREAMING_ENDPOINT") if "MAI_STREAMING_ENDPOINT" in os.environ else ENDPOINT
    resource = urlsplit(root).hostname.split(".")[0]
    url = f"wss://{resource}.services.ai.azure.com/mai/v1/realtime?intent=transcription"
    key = os.environ.get("MAI_STREAMING_API_KEY", "").strip() or API_KEY
    committed, captions = "", []
    async with asyncio.timeout(120), connect(url, additional_headers={"api-key": key}) as websocket:
        for expected in ("session.created", "session.updated"):
            if expected == "session.updated":
                await websocket.send(json.dumps(streaming_session(deployment)))
            if (event := await next_event(websocket))["type"] != expected:
                raise RuntimeError(f"Expected {expected}, received {event['type']}.")
        sender = asyncio.create_task(send_audio(websocket))
        try:
            while True:
                event = await next_event(websocket)
                kind = event["type"].removeprefix(EVENT)
                if kind == "delta":
                    committed += event["delta"]
                elif kind == "intermediate":
                    caption = (committed, event.get("intermediate") or "")
                    if caption[1] and caption != (captions[-1] if captions else None):
                        captions.append(caption)
                elif kind == "completed":
                    await sender
                    return captions, event["transcript"]
        finally:
            sender.cancel()


print(json.dumps(streaming_session(STREAM_DEPLOYMENT), indent=2))
```

**Expected output:** the `session.update` message with your deployment name
and a 16,000-Hz `audio/pcm` format, matching the converted recording.

Stream the meeting. Each line shows one caption update: text before the
vertical bar is committed, and text after it is still provisional. The loop
prints updates until the first sentence commits, then the final transcript.
Streaming takes about as long as the recording.

```python
captions, final = await stream_meeting(STREAM_DEPLOYMENT)
first_sentence = next((i for i, (done, _) in enumerate(captions) if "." in done), len(captions) - 1)
for done, pending in captions[: first_sentence + 1]:
    print(f"{done}|{pending}")
print("\nFinal:", excerpt(final, 12))
```

**Expected output:** provisional text grows and corrects itself before it
commits. In this run, "Q2." becomes "Q3 button.", then "Q3 budget.",
and only "Q3 budget review." moves to the committed side. Exact updates
vary between runs; the final transcript has no speaker labels or timestamps. In
`data/mai-transcribe-2/app.py`, `MaiRealtimeStreamHandler` applies the same
event rules to microphone audio.

## What the sample shows

The saved results connect the objectives to three reusable patterns:

- **Speaker labels and timestamps:** use them when you review a completed
  recording. A file request separated two speakers and timed their turns
  and words.
- **Phrase lists:** use them when names or product terms are misheard. The
  comparison showed "sign-off" with a hint and not without it; hints
  increase likelihood but don't guarantee a word.
- **Provisional and committed captions:** use them when people need words
  while someone speaks. Streaming revised "Q2" to "Q3 budget" before
  committing the text; provisional captions can change, while committed
  text is retained.

The examples use two Azure Speech
interfaces: `transcribe` posts a definition to
the fast transcription API, and `stream_meeting` speaks the Realtime API's
`session.update`, `append`, and `commit` protocol.

To reuse the sample, copy these pieces from `data/mai-transcribe-2/`:

- `app.py`: `file_definition` builds file requests from app options, and
  `MaiRealtimeStreamHandler` streams microphone audio.
- `recipe_helpers.py`: `prepare_recording` converts audio to mono 16-kHz
  PCM WAV.
- This notebook's `transcribe` and `stream_meeting` cells: minimal request
  and streaming clients.

## Tune it for your recordings

For a recorded file, open **Options** in the app and try these controls:

| Control | When to change it |
| --- | --- |
| **Key phrases** | Add names, products, and acronyms relevant to the recording. |
| **Style** | Choose **Verbatim** when fillers and false starts matter; the app defaults to **Clean**. |
| **Speaker labels** | Turn them on to distinguish speakers in a conversation. |
| **Timestamps** | Choose **Word** to see a time for each word, or **Segment** for each segment. |
| **Language** | Leave auto-detect on unless a known single-language recording is misdetected. |

Compare the result with your recording. Speaker labels and offsets show what
the service returned; they don't establish accuracy. For code experiments,
change `meeting_definition` or point `prepare_recording` at another file.
In `app.py`, `file_definition` maps the app controls to request options.
See the [MAI parameter reference](https://learn.microsoft.com/azure/ai-services/speech-service/mai-transcribe)
for supported options and limits.

When you're finished, run the final cell. `close_recipe()` closes the app
and removes the converted WAV, even if you skipped the app
step. A forced kernel stop can leave temporary files behind.

```python
def close_recipe():
    try:
        if "demo" in globals():
            demo.close()
    finally:
        if "session_files" in globals():
            session_files.cleanup()


close_recipe()
print("App and temporary recording closed.")
```