09.4 Speech-to-Text
Speech-to-text (STT), also called automatic speech recognition (ASR) or simply transcription, turns recorded or live audio into text. It sits at the front of every voice product: meeting notes, call analytics, voice assistants, subtitles, searchable archives and dictation. This lesson is the complete engineering guide: what audio actually is on disk, how ASR systems work and how to measure them, every major provider's transcription API as of November 2026, long-audio chunking, speaker diarization, streaming transcription, the post-processing that turns raw transcripts into notes, and the privacy and consent rules that govern recorded speech.
What you'll learn
- Audio fundamentals for engineers: sample rate, channels, bit depth, codecs and containers, and why 16 kHz mono is the lingua franca of ASR
- How speech recognition works at a high level (acoustic model plus decoder; Whisper-style encoder-decoder; streaming vs offline)
- How to measure transcription quality: word error rate (WER), its normalisation rules and its blind spots — with a working implementation
- Every provider's transcription API: OpenAI (
gpt-transcribe,gpt-live-transcribeand the deprecated Whisper family), Gemini (gemini-3.5-transcribeand-live), Anthropic (no audio input — confirmed), OpenRouter's dedicated STT endpoint, and audio sent to general chat models - Specialised ASR vendors (Deepgram, AssemblyAI, ElevenLabs Scribe, Speechmatics, Google Cloud STT, Azure Speech, AWS Transcribe, Rev.ai) and self-hosted open models (Whisper runtimes, NVIDIA Parakeet and Canary, Qwen3-ASR, Moonshine)
- Long audio: per-provider limits, VAD-based and fixed-window chunking, stitching segments back onto the original timeline, parallel and batch processing, and cost-per-minute arithmetic
- Speaker diarization: provider features, known-speaker references, pyannote for self-hosting, and naming speakers with an LLM
- Streaming and realtime transcription: partial vs final results, endpointing, latency trade-offs
- Quality engineering: preprocessing, vocabulary biasing, language detection and code-switching, inverse text normalisation, hallucination on silence, PII redaction
- Post-processing transcripts with LLMs: cleanup, summaries, action items, chapters, QA, subtitles (SRT/VTT), and the meeting-notes pipeline end to end
- Privacy, consent and retention for recorded speech
What you don't need
- API keys. Every provider sample is labelled illustrative and written against official documentation; the audio, metrics, chunking, stitching and subtitle code all runs on synthetic signals with no network.
- A microphone or real recordings. The lesson generates its own test WAV (a tone-burst signal that exercises VAD and chunking logic) and describes how to substitute real audio.
- Signal-processing maths. Concepts are explained in plain English; the code does the arithmetic.
- Text-to-speech. Producing speech is lesson 09.5; realtime voice agents are 09.7.
Setup
The samples need Python 3.11+ and the standard library only — wave, struct, math, re, json, dataclasses — plus uv if you want the provider SDK samples runnable later:
uv init stt-lab --bare --python 3.13 && cd stt-lab # first time only; see 03.1 for the full setup
uv add openai google-genai httpx websockets python-dotenv pydantic
# pip install openai google-genai httpx websockets python-dotenv pydantic
# (httpx and websockets are needed by the OpenRouter and realtime samples)These samples were written and checked against openai 3.42.1, google-genai 2.34.0, httpx 0.28.1, websockets 17.4 and pydantic 2.14.3 as of November 2026. A plain install gives you the newest release of each. The realtime samples pass additional_headers to websockets, the parameter name on the modern asyncio client (websockets 15 and later); on an older release it was called extra_headers.
Optional local tools for real audio work (all free, no keys): ffmpeg/ffprobe for conversion and inspection, soundfile for NumPy-backed audio I/O, pydub as a friendlier ffmpeg wrapper, faster-whisper for self-hosted Whisper. Install only what a part uses; each says so.
The .env file holds keys for the provider samples (never commit it):
# .env
OPENAI_API_KEY=...
GEMINI_API_KEY=... # optional
OPENROUTER_API_KEY=... # optional gateway
HF_TOKEN=... # optional: huggingface.co token for the pyannote diarization
# sample (Part 9) — accept the model's gated conditions on HF firstWhat you must be able to do after this lesson#
- Prepare audio at the right sample rate and channels
- Transcribe audio through a provider API
- Measure transcription quality with word error rate
- Split long audio into chunks and stitch the results
- Improve quality with preprocessing and vocabulary hints
- Handle privacy and consent for recorded speech
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Just send us the audio file." | 1.2 PCM, codecs and containers — the format rules decide whether the upload works at all |
| "Resample it to 16 kHz mono first." | 1.5 Why 16 kHz mono |
| "Our WER is 8%." | 2.3 Word error rate — and why the number alone can mislead |
"Use gpt-transcribe, not whisper-1." |
3.2 The landscape as of November 2026 |
| "The file is 40 minutes — over the limit." | 8.2 Chunking strategies |
| "Who said what, and when?" | 9.1 What diarization is |
| "Show live captions." | 10.1 The three streaming shapes |
| "Whisper invented words during the silence." | 11.5 Hallucination on silence and noise |
| "We need the meeting notes by Friday." | 12.4 The meeting-notes pipeline |
| "Can we keep call recordings for training?" | 13.1 Consent and recording law |
Part 1: Audio for engineers#
1.1 What a digital recording actually is#
Sound is a continuously varying pressure wave. A microphone converts it to a voltage, and an analogue-to-digital converter (ADC) samples that voltage at regular intervals and stores each sample as a number. Three numbers describe any uncompressed recording:
| Parameter | Meaning | Typical values |
|---|---|---|
| Sample rate | How many times per second the wave is measured, in hertz (Hz) | 8,000 (telephony), 16,000 (ASR standard), 44,100 / 48,000 (music, video) |
| Bit depth | How precisely each sample is stored | 16-bit PCM is standard; 24-bit for production audio |
| Channels | How many simultaneous recordings | 1 (mono), 2 (stereo) |
Two consequences follow immediately:
- Duration × sample rate × channels × bytes-per-sample = file size. A 16 kHz mono 16-bit WAV uses
16000 × 2 = 32,000 bytes per second≈ 1.92 MB per minute. An hour is ~115 MB — which is why APIs cap upload sizes and why compressed formats exist. - The Nyquist limit: you can only represent frequencies up to half the sample rate. Speech's useful content sits mostly below ~8 kHz, which is exactly why 16 kHz captures it:
16000 / 2 = 8000 Hz. Telephony at 8 kHz keeps only up to 4 kHz — enough for intelligibility, less for quality. This is also why "CD quality" 44.1 kHz is overkill for speech recognition.
1.2 PCM, codecs and containers#
Raw PCM (pulse-code modulation) data is just the sample numbers. Everything else is a layer on top:
| Layer | What it is | Examples |
|---|---|---|
| Codec | Algorithm that compresses samples (lossy or lossless) | PCM (none), MP3, AAC, Opus, FLAC, μ-law/A-law (telephony) |
| Container | File wrapper holding compressed audio plus metadata | WAV, MP3 (also a codec), M4A/MP4, OGG, FLAC, WebM |
Practical rules:
- WAV is the safe interchange format: uncompressed PCM, trivially readable, huge. APIs accept it everywhere.
- MP3 / M4A (AAC) / OGG (Opus) are what phones, browsers and meeting tools actually produce. Opus in OGG/WebM gives the best quality per byte for voice.
- FLAC is lossless compression — smaller than WAV, bit-identical audio. Rarely needed for STT.
- μ-law / A-law are 8 kHz telephony codecs. If your audio comes from a call recording, it may already be μ-law; providers list
audio/mulawandaudio/alawas accepted MIME types (Gemini does). - A file extension is a hint, not a guarantee. APIs sniff the actual format; send the right
Content-Type/MIME and a filename with an extension (OpenAI's docs explicitly recommend "an extension-bearing filename and an appropriate content type").
1.3 Inspecting a WAV with the standard library#
Python's wave module reads uncompressed PCM WAVs with no dependencies. Here's a complete inspector that also computes loudness — the same computation a simple voice-activity detector uses later:
# wav_inspect.py — python3 wav_inspect.py meeting_sample.wav
import math
import sys
import wave
def rms(samples):
"""Root-mean-square loudness of a sequence of int16 samples."""
return math.sqrt(sum(s * s for s in samples) / len(samples))
def inspect(path: str, window_s: float = 0.5) -> None:
with wave.open(path, "rb") as w:
channels, width, rate = w.getnchannels(), w.getsampwidth(), w.getframerate()
n = w.getnframes()
print(f"{path}")
print(f" channels={channels} sampwidth={width} rate={rate} Hz")
print(f" duration={n / rate:.2f}s bytes/sec={rate * channels * width}")
if width != 2:
# `h` below unpacks signed 16-bit samples only; 8/24/32-bit PCM
# would silently decode as garbage. Convert first, e.g.:
# ffmpeg -i in.wav -sample_fmt s16 out_16bit.wav
print(" only 16-bit PCM supported; convert with ffmpeg first")
return
raw = w.readframes(n)
# int16 little-endian samples
import struct
samples = struct.unpack(f"<{n * channels}h", raw)
step = int(rate * window_s)
for start in range(0, len(samples), step):
chunk = samples[start:start + step]
if chunk:
print(f" t={start / rate / channels:6.2f}s rms={rms(chunk):9.0f}")
if __name__ == "__main__":
inspect(sys.argv[1] if len(sys.argv) > 1 else "meeting_sample.wav")To have something to inspect, generate a synthetic "speech-like" signal — tone bursts separated by silence, which is exactly what a voice-activity detector has to find:
# make_test_wav.py — python3 make_test_wav.py
"""Write an 8-second 16 kHz mono WAV: three tone bursts in silence."""
import math
import struct
import wave
SR = 16000
BURSTS = [(0.5, 1.2), (2.0, 3.5), (5.0, 6.0)] # (start_s, end_s)
DURATION = 8.0
frames = bytearray()
for i in range(int(SR * DURATION)):
t = i / SR
amp = 0
for s, e in BURSTS:
if s <= t < e:
amp = int(12000 * (0.6 + 0.4 * math.sin(2 * math.pi * 4 * t))
* math.sin(2 * math.pi * 220 * t))
frames += struct.pack("<h", amp)
with wave.open("meeting_sample.wav", "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(SR)
w.writeframes(bytes(frames))
print("wrote meeting_sample.wav")wrote meeting_sample.wav
meeting_sample.wav
channels=1 sampwidth=2 rate=16000 Hz
duration=8.00s bytes/sec=32000
t= 0.00s rms= 0
t= 0.50s rms= 5628
...
t= 5.00s rms= 5628
...1.4 Conversion and preprocessing with ffmpeg#
ffmpeg is the universal audio toolbox. The conversions you'll actually run:
# Inspect any audio file's real parameters (codec, rate, channels, duration)
ffprobe -v error -show_entries stream=codec_name,sample_rate,channels,duration \
-of default=noprint_wrappers=1 meeting.m4a
# The ASR-standard form: 16 kHz mono 16-bit WAV
ffmpeg -i meeting.m4a -ar 16000 -ac 1 -sample_fmt s16 meeting_16k.wav
# Compressed but high quality for upload: 64 kbps mono Opus in Ogg
ffmpeg -i meeting.wav -c:a libopus -b:a 64k meeting.ogg
# Loudness-normalise toward a speech-friendly level, then resample
ffmpeg -i noisy_call.mp3 -af "loudnorm=I=-16:TP=-1.5:LRA=11" -ar 16000 -ac 1 call_norm.wav
# Band-limit to the voice range: the high-pass removes rumble below 80 Hz:
ffmpeg -i call.mp3 -af "highpass=f=80,lowpass=f=8000" -ar 16000 -ac 1 call_voiceband.wavNever pass user-supplied filenames to a shell unsanitised — use ffmpeg's argument list form (subprocess.run(["ffmpeg", "-i", path, ...])), not string interpolation. Lesson 09.10 covers secure media pipelines in depth.
1.5 Why 16 kHz mono is the ASR standard#
- 16 kHz matches the Nyquist limit for speech (8 kHz bandwidth covers essentially all phonetic information; studies of telephone speech show most intelligibility lives below ~4 kHz).
- Mono because ASR models are trained on mono; stereo carries no extra linguistic information, only phase differences.
- 16-bit PCM is what the models' feature extractors expect internally; providers resample server-side anyway, but sending the standard form avoids surprises and keeps uploads small.
Exceptions: telephony audio is natively 8 kHz μ-law; high-quality music or forensic audio may stay at 44.1/48 kHz. For transcription APIs, 16 kHz mono WAV or a compressed equivalent (Opus ~32–64 kbps) is the sweet spot.
1.6 Bitrate and the size math#
| Format | Typical size for 1 hour of speech |
|---|---|
| WAV PCM 16 kHz mono 16-bit | ~115 MB |
| MP3 32 kbps mono | ~14 MB |
| Opus 24–32 kbps mono | ~11–14 MB |
| M4A/AAC 32 kbps mono | ~14 MB |
This is why OpenAI's 25 MB upload cap (see 4.1) means roughly a 13-minute 16 kHz WAV, or just under two hours of 32 kbps MP3 (about 14 MB per hour), per request — and why chunking strategy matters for long recordings.
Part 2: How ASR works, and how to measure it#
2.1 The pipeline inside a speech recognizer#
Every modern ASR system, whether a dedicated model or a general LLM with audio input, does the same three jobs:
flowchart LR
A["Audio waveform<br/>(samples)"] --> B["Feature extraction<br/>(log-mel spectrogram,<br/>~10 ms frames)"]
B --> C["Acoustic / audio encoder<br/>(neural network:<br/>sound → representations)"]
C --> D["Decoder / language model<br/>(representations → text,<br/>sometimes with timestamps<br/>and speaker labels)"]
D --> E["Transcript text<br/>+ metadata"]- Feature extraction turns the waveform into a time-frequency picture (a spectrogram-like representation) the network can consume. It's deterministic signal processing, not learning.
- The encoder (often a Conformer or similar) converts audio frames into a sequence of vectors — the audio analogue of token embeddings (lesson 02.3).
- The decoder is usually an autoregressive sequence model — for Whisper-style models, literally a Transformer decoder like the ones in lesson 02.4 — that predicts text tokens one at a time, conditioned on the audio and, in "encoder-decoder" models, on the text generated so far.
Two architecture families matter for engineering choices:
| Family | Examples | Consequences |
|---|---|---|
| Dedicated ASR encoder-decoder or transducer | Whisper, NVIDIA Parakeet (RNN-T), Deepgram Nova, AssemblyAI Universal | Fast, cheap per audio-minute, built for transcription only; may lack timestamps/diarization unless added |
| Audio-native LLM | gemini-3.5-transcribe, OpenAI gpt-transcribe, Voxtral, Qwen3-ASR, audio-capable chat models |
Understands context, vocabulary hints and formatting instructions; slower and pricier per minute; can hallucinate like any LLM |
Streaming vs offline is an architecture decision, not just an API one: streaming models emit partial hypotheses as audio arrives and must decide when a turn ended (endpointing); offline models see the whole file and can use future context, which is why file transcription is almost always more accurate than live.
2.2 The Whisper family: what "Whisper-style" means#
OpenAI's Whisper (the open-source model released in 2022, weights under MIT) established the encoder-decoder recipe above and popularised a crucial trick: train on 680,000 hours of weakly-supervised web audio with the transcript as the label. Practical consequences you still meet:
- 30-second window: Whisper processes audio in 30-second chunks internally; longer files are split and merged, with the previous window's text as prompt context.
- Multilingual by default: it detects language and can translate to English.
- Hallucination on non-speech: on silence, music or noise it can invent plausible-sounding text — the single most famous Whisper failure (11.5).
- Prompt conditioning: a short text prompt biases spelling of names and style — the ancestor of today's
prompt/keywords/custom_vocabularyparameters.
The API's whisper-1 was "powered by our open source Whisper V2 model" per OpenAI's docs — and is now deprecated, shutting down 26 February 2027 (3.2).
2.3 Word error rate (WER)#
The standard accuracy metric for transcription is word error rate: the minimum number of word-level edits (insertions, deletions, substitutions) needed to turn the hypothesis into the reference, divided by the number of reference words.
WER = (substitutions + deletions + insertions) / reference_wordsA WER of 0.10 means the transcript has errors touching ~10% of the reference words — but note it counts edits, not wrong words: one wrong word can cost 2 (delete + insert) or 1 (substitute), and one inserted word costs 1 even if everything else is perfect.
# wer.py — python3 wer.py
"""Word error rate via Levenshtein over word lists, with normalisation."""
import re
def normalize(text: str) -> list[str]:
"""Lowercase, strip punctuation, collapse whitespace, split into words."""
text = text.lower()
text = re.sub(r"[^\w\s]", "", text)
return re.sub(r"\s+", " ", text).strip().split()
def edit_distance(a: list[str], b: list[str]) -> int:
"""Levenshtein distance between two word lists (dynamic programming)."""
prev = list(range(len(b) + 1))
for i, x in enumerate(a, 1):
cur = [i] + [0] * len(b)
for j, y in enumerate(b, 1):
cur[j] = min(prev[j] + 1, # delete a[i]
cur[j - 1] + 1, # insert b[j]
prev[j - 1] + (x != y)) # substitute / match
prev = cur
return prev[-1]
def wer(reference: str, hypothesis: str) -> tuple[float, int, int]:
ref, hyp = normalize(reference), normalize(hypothesis)
d = edit_distance(ref, hyp)
return d / max(len(ref), 1), d, len(ref)
pairs = [
("the quick brown fox jumps over the lazy dog",
"the quick brown fox jumps over the lazy dog"),
("the quick brown fox jumps over the lazy dog",
"the quick brown fox jump over a lazy dog"),
("we will ship the invoice on friday",
"we will ship the invoice on friday thank you"),
]
for ref, hyp in pairs:
rate, edits, n = wer(ref, hyp)
print(f"edits={edits} ref_words={n} WER={rate:.3f} <- {hyp!r}")edits=0 ref_words=9 WER=0.000 <- 'the quick brown fox jumps over the lazy dog'
edits=2 ref_words=9 WER=0.222 <- 'the quick brown fox jump over a lazy dog'
edits=2 ref_words=7 WER=0.286 <- 'we will ship the invoice on friday thank you'Normalisation rules decide the score. Before computing WER, both sides are usually normalised: lowercase, strip punctuation, optionally standardise numbers ("twenty six" vs "26"), fillers, and disfluencies. Two transcripts that differ only in casing or commas can have WER 0 after normalisation and 0.2 before it. Always state your normaliser when reporting WER — and for domain work, the entities matter more than the average: a transcript with WER 5% that misses every invoice number is worse than WER 8% that gets them all right. Measure entity error rate separately for names, numbers, dates and IDs (12.2).
2.4 What this means for you#
- Offline file APIs will beat live APIs on the same audio — plan for that gap when you choose streaming.
- Your accuracy target should be set per use case: search indexing tolerates more errors than a medical-style form or a legal transcript.
- You will almost never compute WER in production; you compute it offline on a labelled eval set to choose providers and tune parameters (Module 10A).
Part 3: The provider landscape#
Reference
3.1 Four ways to get a transcript#
| Route | What it is | Examples (Nov 2026) |
|---|---|---|
| Dedicated STT API | A transcription endpoint built for the job: timestamps, diarization, vocabulary hints, per-minute pricing | OpenAI /v1/audio/transcriptions, Gemini gemini-3.5-transcribe, Deepgram, AssemblyAI, ElevenLabs Scribe, Google Cloud STT, Azure Speech, AWS Transcribe |
| Audio-capable chat model | Send the audio file as a content part and ask for a transcript in the prompt | Gemini generate_content/Interactions with general models, OpenAI audio models via Chat Completions, OpenRouter input_audio models, Voxtral |
| Realtime transcription session | WebSocket audio in, transcript deltas out | OpenAI gpt-live-transcribe, Gemini gemini-3.5-transcribe-live, Deepgram streaming, AssemblyAI streaming |
| Self-hosted open model | Download weights, run on your GPU/CPU | faster-whisper, whisper.cpp, NVIDIA Parakeet/Canary, Qwen3-ASR, Moonshine |
The first two overlap: OpenAI and Gemini now ship dedicated transcription models, while their general chat models also accept audio for understanding tasks (summarising a podcast, answering questions about a recording) — a different job covered in 6.2. For pure "give me the text", a dedicated STT endpoint is almost always cheaper and more controllable.
3.2 The landscape as of November 2026#
Provider facts in this lesson were verified against official documentation on 5 November 2026. This area moves fast — model names especially — so re-check the linked pages before relying on any ID or price.
| Provider | File STT | Realtime STT | Diarization | Word timestamps | Vocabulary hint | Price shape (pay-as-you-go) |
|---|---|---|---|---|---|---|
| OpenAI | gpt-transcribe ($0.0045/min) |
gpt-live-transcribe ($0.017/min) via Realtime transcription sessions |
gpt-4o-transcribe-diarize (returns diarized_json, deprecated, dies Feb 2027) |
whisper-1 verbose_json only (deprecated) |
prompt, keywords, languages |
Per audio minute |
| Anthropic | ❌ No audio input in Messages API | ❌ | ❌ | ❌ | ❌ | — |
| Gemini | gemini-3.5-transcribe (Interactions or generate_content) |
gemini-3.5-transcribe-live (Live API) |
✅ up to 8 speakers | ✅ (may reduce accuracy) | custom_vocabulary ≤1000 terms |
Per token (~$0.005/min blended file, ~$0.009/min live) |
| OpenRouter | /api/v1/audio/transcriptions (models vary) |
❌ dedicated endpoint is file-oriented | per model | per model (verbose_json) |
per model | Per minute (Whisper-class) or per token |
| Deepgram | Nova-3 pre-recorded | Nova-3 / Flux streaming WebSocket | ✅ (diarize_model) |
✅ | Keyterm prompting ≤100 terms | Per second, add-ons billed per minute |
| AssemblyAI | Universal-3.5 Pro / Universal-2 | Universal-3.6 Pro Realtime / Universal-Streaming | ✅ up to ~100 speakers (vendor claim) | ✅ | Prompting ≤1500 words + keyterms | Per audio hour; streaming per session hour |
| ElevenLabs | Scribe v3 (Scribe v2 still available) | Scribe v3 Live (Scribe v2 Realtime still available) | ✅ batch (up to 32 speakers); Scribe v3 Live adds realtime diarization (diarize=true) |
✅ | Keyterm prompting | Per hour (+add-ons) |
| Speechmatics | Melia 1 / Enhanced / Linden 1 | ✅ real-time | ✅ real-time diarization | ✅ | Custom dictionary + phonetics | Per hour; on-prem option |
| Google Cloud STT | Chirp 3 batch | Chirp streaming | batch (Chirp 3) | ✅ | Speech adaptation | Per 15s/60s audio blocks or per hour |
| Azure Speech | Fast transcription (≤5 h/file) | ✅ real-time | ✅ add-on | ✅ | Phrase lists | Per audio hour |
| AWS Transcribe | ✅ | ✅ HTTP/2 or WebSocket | ✅ | ✅ | Custom vocabulary | ~$0.006/min batch, $0.01/min streaming (US East) + variants |
| Rev.ai | ✅ (+ open Reverb model) | ✅ WebSocket/RTMP streaming | ✅ | ✅ | ✅ | Per hour |
Sources for every row are in Further resources and the report. Where a figure is a vendor's own claim (accuracy, speaker counts, latency), the table says so.
3.3 The decision table#
| Your situation | Start with | Why |
|---|---|---|
| Quick prototype, English meetings, want timestamps + speakers | gemini-3.5-transcribe or gpt-4o-transcribe-diarize (until Feb 2027) |
One call returns text + segments + speakers |
| Long archives, cost-sensitive batch | Deepgram Nova-3 pre-recorded or AssemblyAI Universal-2/3.5 Pro | Lowest per-minute prices among managed APIs; diarization included or cheap |
| Live captions / voice agent input | gpt-live-transcribe, gemini-3.5-transcribe-live, or Deepgram streaming |
Purpose-built streaming with partial results |
| Regulated audio (health, legal, EU data residency) | Speechmatics/AssemblyAI EU region, Google Cloud/AWS/Azure STT, or self-hosted | Data-residency and BAA options; on-prem possible |
| Sensitive audio that can't leave your infra | Self-hosted Parakeet/Canary/faster-whisper | No data leaves; you own the ops burden |
| Multilingual + code-switching | Gemini transcribe (85+ locales), Deepgram Nova-3 multilingual, AssemblyAI | Tested code-switching support |
| Domain vocabulary matters (product names, medical terms) | AssemblyAI prompting, Deepgram keyterms, Gemini custom_vocabulary, OpenAI keywords | Each biases recognition differently — A/B test |
| Already on OpenAI/Gemini for everything else | Their transcription models | One vendor, one bill, shared keys |
Part 4: OpenAI transcription#
4.1 The endpoint and its limits#
POST https://api.openai.com/v1/audio/transcriptions accepts multipart form data. As of November 2026:
- Models:
gpt-transcribe(recommended),gpt-4o-transcribe,gpt-4o-mini-transcribe,gpt-4o-mini-transcribe-2025-12-15,whisper-1,gpt-4o-transcribe-diarize— every model after the first (gpt-transcribe) is deprecated and shuts down on 26 February 2027. - File: up to 25 MB; the speech-to-text guide lists
mp3, mp4, mpeg, mpga, m4a, wav, webmas supported inputs (as of November 2026). The API reference forPOST /v1/audio/transcriptionsstill listsflacandoggas well (flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm), so the two OpenAI pages disagree; to be safe convert to one of the guide's formats unless you have tested the others. Larger files must be compressed or split (don't split mid-sentence). - Pricing:
gpt-transcribe$0.0045 per audio minute;gpt-live-transcribe$0.017/min for realtime sessions;whisper-1was $0.006/min. - Response formats:
json(default),text,srt,verbose_json,vtt,diarized_json— but support depends on the model:gpt-4o-transcribeandgpt-4o-mini-transcribeonly supportjson;gpt-4o-transcribe-diarizesupportsjson,textanddiarized_json(the last required for speaker annotations);whisper-1needsverbose_jsonfor timestamps. - Context params:
prompt(unstructured),keywords(literal terms,gpt-transcribeonly, one per line, no<>or newlines),languages(array of ISO-639-1/639-3/zh-* codes,gpt-transcribe; older models take a singlelanguage).gpt-transcribealso returns detectedlanguagesin the response. - Server-side chunking:
chunking_strategy: "auto"makes the server normalise loudness and pick chunk boundaries with VAD — worth enabling on long or noisy files; required for diarize inputs over 30 s."auto"can also be replaced by aserver_vadconfig object ({"type": "server_vad", "prefix_padding_ms": ..., "silence_duration_ms": ..., "threshold": ...}) that exposes the same knobs as your own VAD — see 8.2. - Streaming a file:
stream=truereturns SSE events (transcript.text.delta,transcript.text.done) — text arrives while the file is processed, without a realtime session.whisper-1doesn't support it.
4.2 File transcription, full sample#
# stt_openai_file.py — python3 stt_openai_file.py meeting_16k.wav
"""OpenAI file transcription with gpt-transcribe: context hints + verbose JSON."""
import json
from pathlib import Path
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
with open("meeting_16k.wav", "rb") as audio_file:
transcript = client.audio.transcriptions.create(
model="gpt-transcribe",
file=audio_file,
response_format="json",
prompt="A weekly product sync. Names: Priya, Sam, Elena. "
"Project codenames: Kestrel, Aurora.",
extra_body={
"keywords": ["Kestrel", "Aurora", "AC-42", "Q3 roadmap"],
"languages": ["en"],
},
)
print(transcript.text)
print("detected languages:", transcript.languages)
print("usage:", transcript.usage)Thanks for joining everyone. Let's start with the Kestrel timeline.
The Aurora migration is still blocked on AC-42, so I want to revisit scope.
detected languages: [TranscriptionLanguage(code='en')]
usage: usage(type='duration', seconds=1800.0)Notes a production reader should internalise:
response_format="json"returns{"text": ..., "languages": [...]}— forgpt-transcribe,languagesis the detected-language array (empty when detection fails). Theusageobject can be token-based or duration-based depending on the model.keywordsare hints, not required output — OpenAI warns they can cause unspoken terms to appear if overused.languagesreplaces the old singularlanguageforgpt-transcribe; never send both.srtandvttresponse formats give ready-made subtitles directly — handy for caption pipelines (see 12.4).
4.3 Speaker labels and word timestamps (deprecated path, still instructive)#
Until February 2027, gpt-4o-transcribe-diarize is the only OpenAI file model returning diarized_json: segments with speaker, start, end. It supports up to four known speakers via known_speaker_names/known_speaker_references (2–10 s reference clips as data URLs) — the only major API that lets you name speakers by voice sample:
# stt_openai_diarize.py — DANGER: model deprecated, shutdown 2027-02-26
import base64
from pathlib import Path
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
def to_data_url(path: str) -> str:
return "data:audio/wav;base64," + base64.b64encode(Path(path).read_bytes()).decode()
with open("meeting.wav", "rb") as f:
t = client.audio.transcriptions.create(
model="gpt-4o-transcribe-diarize",
file=f,
response_format="diarized_json",
chunking_strategy="auto",
extra_body={
"known_speaker_names": ["priya"],
"known_speaker_references": [to_data_url("priya_intro.wav")],
},
)
for seg in t.segments:
print(f"[{seg.start:7.2f}-{seg.end:7.2f}] {seg.speaker}: {seg.text}")[ 0.50- 4.20] A: Thanks for joining, let's start with the roadmap.
[ 4.40- 9.10] priya: The Aurora migration is still blocked on AC-42.4.4 Realtime transcription over WebSocket#
For live audio (call, mic, broadcast), OpenAI offers transcription sessions — a WebSocket at wss://api.openai.com/v1/realtime?intent=transcription (no model in the URL; the model goes in session.update). You stream base64 PCM16 audio and commit each turn:
# stt_openai_realtime.py — skeleton; needs `websockets` and a live mic source
"""OpenAI realtime transcription session with gpt-live-transcribe."""
import asyncio
import base64
import json
import os
import websockets
from dotenv import load_dotenv
load_dotenv()
URL = "wss://api.openai.com/v1/realtime?intent=transcription"
async def main() -> None:
async with websockets.connect(URL, additional_headers={
"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"],
# no "OpenAI-Beta: realtime=v1" header: the Realtime API is GA, and that old header
# would select the retired beta protocol (see 09.7)
}) as ws:
await ws.send(json.dumps({
"type": "session.update",
"session": {
"type": "transcription",
"audio": {
"input": {
"format": {"type": "audio/pcm", "rate": 24000},
"transcription": {
"model": "gpt-live-transcribe",
"prompt": "A customer support call about billing.",
"keywords": ["AC-42", "premium plan"],
"languages": ["en"],
"delay": "low", # minimal|low|medium|high|xhigh
},
"turn_detection": None, # required: no server_vad in transcription sessions
}
}
},
}))
# ... stream input_audio_buffer.append chunks, then input_audio_buffer.commit
# per turn; read conversation.item.input_audio_transcription.delta/.completed
asyncio.run(main())Key facts (verified against the realtime-transcription guide):
- Audio format:
audio/pcmat 24 kHz in the example (PCM16 mono); sendinput_audio_buffer.appendwith base64 chunks andinput_audio_buffer.commitat each turn boundary — you do endpointing (client-side VAD) becauseturn_detectionmust benull. - Events:
conversation.item.input_audio_transcription.delta(partial text),.completed(final per committed item),.failed. Order across turns isn't guaranteed — match byitem_id. delaytrades latency for accuracy:minimal→xhigh. OpenAI explicitly warns to benchmark on your audio, not synthetic samples.gpt-live-transcribereturns no timestamps, no speaker labels, no confidence scores, no detected languages. For those you need file transcription or a specialised vendor.gpt-transcribecan also run inside a realtime session for committed-turn transcription with detected languages — a niche path; the dedicated file endpoint is simpler.- Sibling session types share the realtime surface:
gpt-realtime-whisperprovides transcription inside voice-agent sessions, andgpt-realtime-translatepowers the separatev1/realtime/translationsspeech-to-speech endpoint — this lesson covers the dedicated transcription sessions; agent sessions are 09.7 and translation gets a mention in 12.6.
Part 5: Gemini transcription#
Deep-dive
5.1 Dedicated transcription models#
Google ships purpose-built transcription models, verified August–November 2026:
| Model | Job | Endpoint style |
|---|---|---|
gemini-3.5-transcribe |
File transcription up to 1 hour per request (30 min with diarization or word timestamps) | Interactions API (client.interactions.create) and generate_content |
gemini-3.5-transcribe-live |
Live WebSocket transcription via the Live API | interim_input_transcription (speculative partials) + input_transcription (final) fields |
Capabilities of gemini-3.5-transcribe: automatic detection across 85+ locales with intra-sentence code-switching, custom vocabulary up to 1,000 phrases, speaker diarization up to 8 speakers (≥3 experimental), word-level timestamps, and two modes — verbatim (default, exact) and smart (removes disfluencies, resolves self-corrections, applies structure/formatting/ITN).
Hard incompatibilities (the API rejects these combinations):
custom_vocabularycannot be combined with diarization or word timestamps.smartmode cannot be combined with timestamps or diarization.- Word timestamps "may degrade overall transcription accuracy" (Google's docs).
5.2 File transcription sample#
# stt_gemini_file.py — python3 stt_gemini_file.py meeting.mp3
"""Gemini file transcription: upload once, transcribe with vocabulary bias."""
from google import genai
from google.genai import types
client = genai.Client()
audio = client.files.upload(file="meeting.mp3") # Files API; poll until ACTIVE for long files
response = client.interactions.create(
model="gemini-3.5-transcribe",
input=[audio], # pass the uploaded File object directly — the documented Python form
generation_config={
"transcription_config": {
"language_codes": ["en-US"], # omit or [] for auto-detect
"custom_vocabulary": ["Kestrel", "Aurora", "AC-42", "Priya", "Q3 roadmap"],
# "mode": {"type": "verbatim", "diarization_mode": "speaker",
# "timestamp_granularities": ["word"]},
}
},
)
print(response.output_text)Thanks for joining everyone. Let's start with the Kestrel timeline.
The Aurora migration is still blocked on AC-42, so I want to revisit scope.With diarization + timestamps enabled (a different request — they can't combine with custom_vocabulary), annotations arrive as word_info objects on the response content:
# Walk response.steps[].content[].annotations[] for type == "word_info"
# each has: text, speaker ("spk_1"), start_offset "0.100s", end_offset "0.400s"
for step in response.steps or []:
for content in getattr(step, "content", []) or []:
for ann in getattr(content, "annotations", []) or []:
if getattr(ann, "type", None) == "word_info":
print(f"[{ann.start_offset} -> {ann.end_offset}] "
f"{ann.speaker or '-'}: {ann.text}")Notes:
- Passing the file:
input=[audio]is the documented Python form. The{"type": "audio", "uri": ..., "mime_type": ...}dict you see in the JavaScript and REST examples is the wire shape — the SDK accepts both, but prefer the object form. generate_contentalso works: passtypes.Part.from_bytes(...)(or a file URI part) andconfig=types.GenerateContentConfig(audio_transcription_config=types.AudioTranscriptionConfig(...))— handy when you already usegenerate_contentelsewhere. The Interactions API is Google's current recommended surface for new code.- Pricing is token-based: $2.00/1M audio-input tokens + $12.00/1M text-output tokens, which Google estimates at ~$0.005/min blended for file transcription and ~$0.009/min for the live model (25 audio tokens/sec input, 175 text tokens/min output). A free tier exists but Google may use free-tier data to improve products — paid tier does not (02.9, 9.2).
- Formats: WAV, MP3, AIFF, AAC, OGG, FLAC, MPEG, M4A, L16, Opus, ALAW, MULAW, WebM.
- Speaker labels come back as
spk_1,spk_2, ... — anonymous; naming them is your job (9.1).
5.3 Live transcription#
gemini-3.5-transcribe-live streams over the Live API WebSocket. Two transcript fields arrive in server_content: interim_input_transcription (fast, speculative partials — use for live subtitles) and input_transcription (authoritative final for the turn). It supports custom_vocabulary biasing, automatic language detection, manual and hybrid VAD, and smart transcription. Session mechanics (connect, audio frames, VAD, interruption) are 09.6 and 09.7 territory; the STT-specific point is that live transcription is a separate session type from a voice agent — you get text, not a spoken reply.
5.4 General audio understanding (when you don't want a transcript)#
Any audio-capable Gemini model (gemini-3.8-flash, etc.) accepts audio inline or via the Files API at ~25–32 tokens/second — up to 9.5 hours per prompt per 03.6, Part 8. Use this for "summarise this podcast" or "what's that sound?", not for transcription: dedicated STT is cheaper per minute and gives you timestamps, diarization and vocabulary controls. 09.6 covers audio-native models in depth.
Part 6: OpenRouter and audio-to-chat-models#
Reference
6.1 OpenRouter's dedicated STT endpoint#
OpenRouter exposes POST /api/v1/audio/transcriptions — a transcription endpoint that routes to whichever upstream provider serves the chosen model. Verified parameters:
| Parameter | Notes |
|---|---|
model |
STT model slug — discover via GET /api/v1/models?output_modalities=transcription; STT IDs don't appear in the default catalogue |
input_audio.data |
Base64 raw bytes, not a data: URI |
input_audio.format |
wav, mp3, flac, m4a, ogg, webm, aac (varies by provider) |
language |
ISO-639-1 hint; auto-detected if omitted |
response_format |
json or verbose_json (adds language, duration, segment timestamps where the provider returns them) |
timestamp_granularities |
["segment"] / ["word"] |
provider |
zdr: true / data_collection: "deny" data-policy routing plus options for provider-specific params (below); other routing prefs don't apply to transcription |
# stt_openrouter.py — OpenRouter STT via raw HTTP (httpx)
import base64
import os
import httpx
from dotenv import load_dotenv
load_dotenv()
with open("meeting_16k.wav", "rb") as f:
audio_b64 = base64.b64encode(f.read()).decode()
resp = httpx.post(
"https://openrouter.ai/api/v1/audio/transcriptions",
headers={"Authorization": "Bearer " + os.environ["OPENROUTER_API_KEY"]},
json={
"model": "openai/whisper-1", # example slug; check the live catalogue
"input_audio": {"data": audio_b64, "format": "wav"},
"language": "en",
"response_format": "verbose_json",
"timestamp_granularities": ["segment"],
"provider": {"zdr": True},
},
timeout=300,
)
resp.raise_for_status()
data = resp.json()
print(data["text"]){"text": "Thanks for joining everyone...", "language": "en", "duration": 1800.0,
"segments": [{"start": 0.5, "end": 4.2, "text": "Thanks for joining everyone."}]}With verbose_json the response can also carry a top-level confidence (0–1, only when the provider scores the whole transcript), a words array (with "word" in timestamp_granularities), and speaker indices on segments and words when the upstream diarizes.
Provider-specific options. Features a provider exposes only through its own API — speaker diarization, vocabulary or keyword hints, output style — are passed via provider.options, keyed by the provider slug from the endpoints API (GET /api/v1/models/{author}/{slug}/endpoints; each endpoint record's tag is your key). Only the options for the provider that actually serves the request are forwarded, under that provider's own field names — so check the upstream's transcription docs for exact names and shapes:
"provider": {
"zdr": true,
"options": {
"deepgram": {"diarize": true, "keyterm": "Kestrel Aurora AC-42"},
"azure": {"diarization": {"enabled": true}}
}
}Two more paths worth knowing. The endpoint also accepts OpenAI-style multipart/form-data (file, model, language, temperature, response_format, timestamp_granularities fields; prompt is accepted but ignored; text/srt/vtt are rejected with a 400), so the official OpenAI SDK works unchanged by pointing base_url at https://openrouter.ai/api/v1 — handy when migrating OpenAI code. Multipart uploads cap at 25 MB (about 13 min of 16 kHz WAV, ~26 min of 128 kbps MP3); base64 JSON past that is rejected except on OpenAI/Groq upstreams, which offload the body, and input_audio.url works for models that fetch a URL themselves. Finally, upstream providers time out after ~60 s of processing — recordings needing more than about a minute of transcription should be split into chunks first (8.2).
Pricing is mixed: Whisper-class models bill per audio duration; newer STT models bill per token — the catalogue response carries the current rate, so read it, don't hard-code it (02.9, 6.13 pattern).
6.2 Audio as a chat-model input#
Separate from the STT endpoint, OpenRouter (and the other providers) let you send audio to general chat models as an input_audio content part — useful when you want transcription plus understanding in one call, or when no dedicated STT model covers your language:
- Responses API:
{"type": "input_audio", "input_audio": {"data": "<base64>", "format": "wav"|"mp3"}}— base64 only, no URLs. - Chat Completions:
input_audioparts accept whatever format string the routed provider supports (aiff,aac,ogg,flac,m4a,pcm16,pcm24, ...). - Audio-capable model families include Gemini models, Mistral's Voxtral, xiaomi/mimo-v2-omni, OpenAI's audio models — filter the live catalogue by
architecture.input_modalitiescontaining"audio".
The catch: you pay text-model token prices for audio tokens (~25–32 tokens/sec on Gemini), get no timestamps/diarization guarantees, and the model may answer your "transcribe this" prompt with commentary instead of clean text. Use it for understanding tasks; use the STT endpoint for transcripts. Anthropic accepts no audio at all — its Messages API content blocks are text, image and document only (platform.claude.com vision docs; the SDK's own issue tracker confirms audio isn't on the roadmap as an API content type).
Part 7: Specialised ASR and open models#
Reference
7.1 The specialised vendors#
These companies do one thing — speech in, structured text out — and compete on accuracy, latency, diarization depth and compliance. Most figures are pay-as-you-go list prices; the Deepgram, AssemblyAI, ElevenLabs, Speechmatics and Rev.ai rows were re-read on each vendor's pricing page on 12 November 2026. Rows marked "reported" or "verify" rest on third-party trackers because the official page does not list the figure — re-check each pricing page before quoting.
| Vendor | Flagship (Nov 2026) | Batch price | Streaming | Standout features |
|---|---|---|---|---|
| Deepgram | Nova-3 (60+ languages), Flux STT (voice-agent model) | Nova-3 mono $0.0043/min, multi $0.0052/min | Nova-3 mono $0.0077/min, multi $0.0092/min; Flux English $0.0077/min (Flux multilingual $0.0078) | Keyterm prompting (≤100 terms), diarize_model v1/v2/latest, redaction, entity detection, per-second billing, $200 free credit |
| AssemblyAI | Universal-3.5 Pro, Universal-2 | $0.21/hr / $0.15/hr | Universal-3.6 Pro Realtime $0.45/hr, Universal-Streaming $0.15/hr | Diarization up to ~100 speakers (vendor claim), LLM prompting ≤1500 words, Sync API ≤2 min clips ~134 ms median, EU region same price, $50 free credits |
| ElevenLabs | Scribe v3 (current), Scribe v2, Scribe v2 Medical; realtime: Scribe v3 Live, Scribe v2 Realtime | $0.20/hr (Scribe v3, v2 and Medical, one list price on every plan; Medical adds BAA and Zero Retention Mode) | $0.22/hr (Scribe v3 Live and v2 Realtime; v2 Realtime "~150 ms" per ElevenLabs) | Keyterm prompting +$0.05/hr batch, +$0.08/hr realtime, 90+ languages, word-level timestamps, realtime diarization on Scribe v3 Live only |
| Speechmatics | Melia 1 (multilingual), Enhanced, Linden 1 (low-latency voice agents) | Melia 1 pre-recorded $0.24/hr list (headline "from $0.121/hr" needs the training opt-in plus the top annual discount), per Speechmatics pricing as of November 2026 | Real-time Melia 1 $0.40/hr, Linden 1 $0.30/hr | Real-time diarization, custom dictionary + phonetic prompts, on-prem containers, 56 languages (Melia 1, per the pricing page) |
| Google Cloud STT | Chirp 3 | $0.003/min (~$0.18/hr) dynamic batch | $0.016/min (~$0.96/hr) standard, first 500k min/month; per Google's pricing page as of November 2026, which lists chirp among the Standard models and shows no separate Chirp 3 row |
125+ languages (Google figure), medical model en-US, deep GCP integration |
| Azure AI Speech | Fast transcription API | per audio hour | ✅ real-time | Files under 5 h / 500 MB per request (fast-transcription docs), 140+ languages (vendor figure; the speech-to-text overview page does not state a count, see the language-support page), Custom Speech, container option |
| AWS Transcribe | Base / Medical / Call Analytics | $0.006/min (~$0.36/hr) standard batch, US East, per AWS's price list published 11 September 2026 (the pricing web page's tier table does not render in a text fetch, so the price list is the primary source: re-read on 12 November 2026, still the 11 September file; older write-ups quote $0.024/min); Medical $0.075/min, Call Analytics from $0.03/min; check your region | HTTP/2 or WebSocket, $0.01/min (US East) | Medical (HIPAA) + Call Analytics (sentiment, speaker labels), custom vocabulary, PII redaction, channel identification |
| Rev.ai | Hosted API + open Reverb model | Reverb $0.20/hr (English), $0.30/hr foreign-language, per Rev.ai pricing (opened 14 November 2026; its English "Whisper Large" line is $0.005/min). The page no longer lists a Reverb Turbo rate: an earlier reported $0.10/hr is unconfirmed, and a third-party price tracker says Rev.ai dropped Reverb Turbo and Whisper Fusion from the page in October 2026, so ask Rev.ai before planning around either | The pricing page shows no separate streaming rate; Rev.ai's streaming docs cover WebSocket and RTMP streams (10 concurrent streams by default, 3 hours per stream) and a transcriber option (the docs' example uses machine_v2), and an earlier reported Whisper Fusion streaming rate of $0.30/hr is not on any official page, so verify before quoting |
Long-form heritage (meetings, depositions); Reverb weights under a non-commercial licence (commercial use needs a Rev licence; English-only) |
7.2 When a specialist beats the generalists#
- Diarization depth: AssemblyAI (~100 speakers), Speechmatics real-time diarization and AWS channel identification beat the general APIs for messy multi-party audio.
- Compliance: Speechmatics on-prem, AssemblyAI EU region, Google/AWS/Azure BAA paths, ElevenLabs Medical — pick by where the data may legally live.
- Cost at scale: Deepgram and AssemblyAI batch rates (
$0.21–0.26/hr) undercut OpenAI/Gemini file transcription ($0.27–0.30/hr) before add-ons; but OpenAI/Gemini bundle vocabulary hints and language detection that specialists charge extra for. Total cost = base + every add-on you switch on — Deepgram's diarization alone adds $0.002/min streaming. - Latency: AssemblyAI's Sync API (~134 ms median for ≤2 min clips) and ElevenLabs Scribe v2 Realtime (~150 ms claimed) target interactive use; batch APIs trade minutes for accuracy.
7.3 Self-hosted open models#
When audio can't leave your infrastructure — or you transcribe at a scale where per-minute pricing hurts — open ASR models are production-viable. Verified landscape, November 2026:
| Model / runtime | Licence | Languages | Strengths | Watch out for |
|---|---|---|---|---|
| faster-whisper 1.2.1 (CTranslate2) | MIT | ~99 (Whisper) | Drop-in Whisper, up to ~4× faster, int8 CPU/GPU, built-in Silero VAD, large-v3-turbo |
Still Whisper's hallucination-on-silence tendency; NVIDIA GPU preferred |
| whisper.cpp v1.9.5 | MIT | ~99 | Single binary, CPU/Metal/CUDA/Vulkan, whisper-stream example, OpenAI-compatible server mode |
More assembly required; diarization is a separate component |
| mlx-whisper | MIT | ~99 | Fastest path on Apple Silicon | macOS only |
| WhisperX 3.8.6 | BSD-2 | ~99 | Adds word alignment + speaker diarization around Whisper | Heavier pipeline, more deps |
| NVIDIA Parakeet TDT (0.6B/1.1B) | NVIDIA Open Model License (check terms) | ~25 European | Fastest self-hostable throughput; RNN-T-style decoding can't hallucinate on silence (community bench) | Narrower language coverage; NeMo runtime |
| NVIDIA Canary / Canary-Qwen 2.5B | check per checkpoint | en/de/fr/es (+Qwen variant English-focused) | English accuracy leader among open models (vendor/community claims) | GPU-oriented; English-centric variants |
| Qwen3-ASR (0.6B/1.7B) | Apache-2.0 | 52 languages/dialects | Streaming via vLLM, broad coverage | Younger ecosystem |
| Moonshine | MIT (check non-English terms) | English-focused + growing | Edge/on-device, live dictation on Raspberry Pi-class hardware | Not for archive transcription |
| IBM Granite Speech 3.3 | Apache-2.0 | en/fr/de/es/pt | Licence clarity for enterprise | 8B-class — needs real GPU |
| Voxtral (Mistral) | Apache-2.0 | multilingual | Audio-native LLM — transcription and understanding | Bigger, pricier per hour than dedicated ASR |
# stt_faster_whisper.py — pip install faster-whisper; downloads model weights on first run
from faster_whisper import WhisperModel
model = WhisperModel("large-v3", device="cuda", compute_type="float16")
# or: device="cpu", compute_type="int8" on a laptop
segments, info = model.transcribe(
"meeting_16k.wav",
beam_size=5,
vad_filter=True, # Silero VAD: skip silence, fewer hallucinations
language="en",
initial_prompt="Kestrel, Aurora, AC-42, Priya, Q3 roadmap",
)
print(f"detected language={info.language} prob={info.language_probability:.2f}")
for seg in segments:
print(f"[{seg.start:7.2f}-{seg.end:7.2f}] {seg.text}")detected language=en prob=0.98
[ 0.50- 4.20] Thanks for joining everyone. Let's start with the Kestrel timeline.Part 8: Long audio#
Deep-dive
8.1 The limits that force chunking#
| Provider / route | File limit | Notes |
|---|---|---|
OpenAI /v1/audio/transcriptions |
25 MB per file | Just under 2 h of 32 kbps MP3, ~26 min of 128 kbps MP3, ~13 min of 16 kHz WAV; split larger files (don't cut mid-sentence) |
Gemini gemini-3.5-transcribe |
1 hour audio per request; 30 min with diarization or word timestamps | Upload via Files API |
| Azure fast transcription | 5 hours / 500 MB per request | Generous — often no chunking needed |
| AWS Transcribe / Google Cloud STT / Deepgram / AssemblyAI | Effectively unbounded for batch | Async job model: upload → poll/webhook |
| OpenRouter STT | Inherits the routed provider's limits | Base64-in-JSON: watch request size |
For a 3-hour meeting, OpenAI forces two chunks at 32 kbps (about 43 MB in total) and about seven at 128 kbps (about 170 MB); Azure takes it whole. Choose the route by duration before choosing by accuracy.
8.2 Chunking strategies#
Three patterns, in increasing sophistication:
| Strategy | How | Pros | Cons |
|---|---|---|---|
| Fixed windows + overlap | Cut every N seconds with M seconds of overlap | Trivial, predictable | Can split words at boundaries; overlap duplicates text you must dedupe |
| VAD-based splitting | Detect silence, cut only in quiet gaps | Never splits mid-word; fewer, cleaner chunks | Needs a VAD (below); very long monologues still need a hard cap |
| Provider-native chunking | chunking_strategy="auto" (OpenAI) or let the vendor's async API handle it |
Zero code, vendor-tuned | Less control; black box |
Energy VAD is the classic baseline: compute RMS loudness per short frame, mark frames above an adaptive threshold as speech, merge into segments with padding. It works because speech is bursty — pauses between words and sentences are genuinely quiet:
# vad_chunk.py — python3 vad_chunk.py
"""Energy VAD on a WAV: find speech segments, emit chunk boundaries in silence."""
import math
import struct
import sys
import wave
def read_pcm(path):
with wave.open(path, "rb") as w:
n = w.getnframes()
raw = w.readframes(n)
return w.getframerate(), w.getnchannels(), struct.unpack(f"<{n * w.getnchannels()}h", raw)
def vad_segments(samples, rate, frame_ms=100, min_speech_ms=300, pad_ms=200):
frame = rate * frame_ms // 1000
levels = [math.sqrt(sum(s * s for s in samples[i:i + frame]) / frame)
for i in range(0, len(samples) - frame + 1, frame)]
# adaptive threshold: speech is the loud minority; use a high percentile as reference
thresh = sorted(levels)[int(len(levels) * 0.7)] * 0.4
speech = [lvl > thresh for lvl in levels]
min_frames, pad = min_speech_ms // frame_ms, pad_ms // frame_ms
segs, cur = [], None
for i, s in enumerate(speech):
if s and cur is None:
cur = i
elif not s and cur is not None:
if i - cur >= min_frames:
segs.append((max(0, cur - pad) * frame_ms / 1000,
min(len(levels), i + pad) * frame_ms / 1000))
cur = None
if cur is not None:
segs.append((cur * frame_ms / 1000, len(levels) * frame_ms / 1000))
return segs
if __name__ == "__main__":
rate, ch, samples = read_pcm(sys.argv[1] if len(sys.argv) > 1 else "meeting_sample.wav")
for s, e in vad_segments(samples, rate):
print(f"speech {s:6.2f}s -> {e:6.2f}s ({e - s:.2f}s)")Running it on the synthetic meeting_sample.wav from 1.3:
speech 0.30s -> 1.40s (1.10s)
speech 1.80s -> 3.70s (1.90s)
speech 4.80s -> 6.20s (1.40s)8.3 Stitching transcripts back onto the timeline#
Each chunk returns segments timestamped relative to the chunk. Rebase them onto the original file by adding the chunk's offset — then sort and optionally re-merge adjacent segments from the same speaker:
# stitch.py — python3 stitch.py
"""Rebase per-chunk transcript segments onto the original timeline."""
CHUNKS = [ # what each provider call returned (timestamps relative to chunk start)
{"offset_s": 0.0, "segments": [
{"start": 0.4, "end": 1.1, "speaker": "A", "text": "Thanks for joining."},
{"start": 1.5, "end": 2.8, "speaker": "B", "text": "Let's start."}]},
{"offset_s": 30.0, "segments": [
{"start": 0.2, "end": 1.0, "speaker": "A", "text": "First item: roadmap."},
{"start": 12.0, "end": 14.0, "speaker": "B", "text": "Second item: evals."}]},
]
stitched = sorted(
({"start": s["start"] + c["offset_s"], "end": s["end"] + c["offset_s"],
"speaker": s["speaker"], "text": s["text"]}
for c in CHUNKS for s in c["segments"]),
key=lambda x: x["start"],
)
for s in stitched:
print(f"[{s['start']:6.1f}-{s['end']:6.1f}] {s['speaker']}: {s['text']}")[ 0.4- 1.1] A: Thanks for joining.
[ 1.5- 2.8] B: Let's start.
[ 30.2- 31.0] A: First item: roadmap.
[ 42.0- 44.0] B: Second item: evals.Overlap handling: with fixed-window overlap, a word can appear in two chunks. Dedupe by (approximate timestamp, text) or by transcribing only the non-overlapped core and using overlap purely as decoder context — OpenAI's own guidance is to carry the previous chunk's text as prompt context rather than double-count it.
8.4 Parallelism, batch APIs and cost#
- Parallel chunks: chunk transcription is embarrassingly parallel — 03.9's bounded-concurrency pattern applies directly (semaphore + per-provider rate limits). Watch provider concurrency quotas, not just RPM.
- Vendor batch APIs: AWS Transcribe, Google Cloud STT, Azure batch transcription and AssemblyAI all offer async job APIs (submit → poll/webhook → results), typically cheaper per hour than sync. OpenAI and Gemini currently have no batch transcription endpoint (verified on their model pages: Batch = "Not supported").
- Cost per hour (pay-as-you-go list, Nov 2026 — parameters, re-check pages):
| Route | $/audio-hour (approx) |
|---|---|
OpenAI gpt-transcribe |
$0.27 |
OpenAI gpt-live-transcribe |
$1.02 |
Gemini gemini-3.5-transcribe |
~$0.30 blended |
| Deepgram Nova-3 mono batch | ~$0.26 (+diarization included on prerecorded) |
| AssemblyAI Universal-3.5 Pro | $0.21 |
| ElevenLabs Scribe v3 / v2 | $0.20 |
A 1,000-hour/month archive costs ~$210–300 across the cheap batch routes — the per-hour differences are small; add-ons and retries dominate the bill. The arithmetic, with prices as parameters (03.7):
monthly_cost = audio_hours × (base_rate + Σ add-on rates) × (1 + retry_rate)Per-minute prices convert to per-hour by ×60; add-ons stack on the base before retries multiply everything. Concurrency changes wall-clock time, not spend — but watch per-session billing (AssemblyAI streams bill per session-hour whether or not anyone speaks) and per-channel billing (multichannel calls bill per channel). Track usage.seconds/usage.cost/duration fields every response returns.
# cost_model.py — python3 cost_model.py
"""Monthly STT spend = audio_hours x (base rate + add-ons) x retry factor.
Every price is a parameter — Nov 2026 pay-as-you-go list prices.
Re-check each vendor's pricing page before quoting a customer.
"""
BASE_PER_HOUR = { # $ per audio-hour (per-minute prices x 60)
"openai gpt-transcribe": 0.27, # $0.0045/min
"openai gpt-live-transcribe": 1.02, # $0.017/min, realtime sessions
"gemini-3.5-transcribe": 0.30, # ~$0.005/min blended estimate
"deepgram nova-3 mono (batch)": 0.26, # $0.0043/min; diarization included
"deepgram nova-3 mono (streaming)": 0.46, # $0.0077/min; diarization is +$0.002/min extra
"deepgram nova-3 stream + diarization": 0.58, # ($0.0077 + $0.0020)/min x 60
"assemblyai universal-3.5 pro": 0.21,
"assemblyai + std diarization": 0.23, # +$0.02/hr
"elevenlabs scribe v3": 0.20,
"elevenlabs scribe v3 + keyterms": 0.25, # +$0.05/hr
}
RETRY_FACTOR = 1.10 # fraction of audio re-run after failures, bad VAD cuts, re-uploads
def monthly_cost(audio_hours: float, route: str) -> float:
return audio_hours * BASE_PER_HOUR[route] * RETRY_FACTOR
HOURS = 1000.0 # a large archive: about 1,000 hours of audio a month
for route in BASE_PER_HOUR:
print(f"{route:36s} ${monthly_cost(HOURS, route):7.2f}/month")openai gpt-transcribe $ 297.00/month
openai gpt-live-transcribe $1122.00/month
gemini-3.5-transcribe $ 330.00/month
deepgram nova-3 mono (batch) $ 286.00/month
deepgram nova-3 mono (streaming) $ 506.00/month
deepgram nova-3 stream + diarization $ 638.00/month
assemblyai universal-3.5 pro $ 231.00/month
assemblyai + std diarization $ 253.00/month
elevenlabs scribe v3 $ 220.00/month
elevenlabs scribe v3 + keyterms $ 275.00/monthPart 9: Diarization — who spoke when#
Deep-dive
9.1 What diarization is and isn't#
Speaker diarization answers "who spoke when", not "who is this person". Output is anonymous labels (A, B, spk_1, speaker_0) on time segments. Three levels of product:
- Raw diarization — turn-level labels with timestamps (most APIs).
- Known-speaker matching — supply a voice sample and get that person's name on their turns. OpenAI's
known_speaker_names/known_speaker_references(≤4 speakers, 2–10 s clips) is the only major API doing this directly; elsewhere you match embeddings yourself. - Context naming — an LLM reads the transcript and infers names from content ("I'll send the deck, Marcus" → speaker is Marcus). Works surprisingly well on meetings with roll-call intros; fails silently when wrong — always show it as a suggestion.
9.2 Provider support (Nov 2026)#
| Provider | Diarization | Speaker cap | Notes |
|---|---|---|---|
| OpenAI | gpt-4o-transcribe-diarize only (deprecated, dies Feb 2027); none on recommended models or realtime |
4 known speakers | Plan a migration path |
Gemini gemini-3.5-transcribe |
✅ diarization_mode:"speaker" |
8 (≥3 experimental) | Requires verbatim mode; incompatible with custom_vocabulary |
| Deepgram | ✅ diarize_model=latest/v1/v2 |
— | v2 batch-only; included on prerecorded, +$0.002/min streaming |
| AssemblyAI | ✅ async + streaming | ~100 (vendor claim) | +$0.02/hr standard, +$0.065/hr experimental |
| ElevenLabs Scribe v3 | ✅ batch (32 speakers per ElevenLabs docs) and Scribe v3 Live (diarize=true, cap not stated) |
— | Scribe v2 Realtime lists no diarization |
| Speechmatics | ✅ including real-time | — | Real-time diarization is a differentiator |
| Google Cloud STT | ✅ batch (Chirp 3, ~15 locales) | — | Not on streaming per third-party comparisons |
| Azure Speech | ✅ add-on | — | Diarization is a paid add-on feature |
| AWS Transcribe | ✅ + Call Analytics speaker labels | — | Channel identification for multi-channel audio |
9.3 Self-hosted diarization: pyannote#
When you need diarization without a per-minute fee — or on audio that can't leave — pyannote.audio is the standard open toolkit:
pyannote/speaker-diarization-community-1is the open pipeline the project's README (checked 8 November 2026) shows in its quick start; its model card licence is CC-BY-4.0 (attribution required). You must accept the model's user conditions on Hugging Face and pass a Hugging Face access token (HF_TOKENin the.envabove) astoken=.pyannote/speaker-diarization-3.1is the earlier pipeline (MIT-licensed, also gated), now labelled "legacy" in the README's benchmark table. It belongs to the 3.x line ofpyannote.audio, where the token argument was nameduse_auth_token; the sample below uses the current 4.x call shape, so do not mix the two.- Input is 16 kHz mono: the pipeline downmixes and resamples for you. Output is an annotation you can write as RTTM, the standard text format for diarization.
- Speaker counting and overlapping speech remain hard problems; expect errors on crosstalk-heavy audio and always evaluate on your own recordings (Module 10A).
# diarize_pyannote.py — uv add pyannote.audio (PyPI's latest on 11 November 2026); needs HF_TOKEN
# + accepted conditions on Hugging Face (illustrative: pulls model weights and needs a GPU or patience)
import os
from dotenv import load_dotenv
from pyannote.audio import Pipeline
load_dotenv()
pipeline = Pipeline.from_pretrained(
"pyannote/speaker-diarization-community-1", token=os.environ["HF_TOKEN"])
output = pipeline("meeting_16k.wav") # 16 kHz mono; it resamples for you
for turn, speaker in output.speaker_diarization:
print(f"[{turn.start:7.2f}-{turn.end:7.2f}] {speaker}")[ 0.50- 4.20] SPEAKER_00
[ 4.40- 9.10] SPEAKER_019.4 The hard cases#
- Overlapping speech (crosstalk): most systems assign one speaker per segment; true overlap needs dedicated models. Expect errors; consider transcribing channels separately for call recordings.
- Multi-channel audio: phone calls often arrive as separate caller/callee channels — transcribe each channel independently and you get perfect diarization for free. AWS channel identification and AssemblyAI multichannel billing (per channel!) exist for this.
- Speaker changes mid-segment: fine-grained diarization helps; coarse turn-level labels blur rapid exchanges.
- Consistency across chunks: when you chunk long audio yourself, speaker labels (
A,B) are per-chunk and arbitrary — you must reconcile speaker identity across chunks (voice embeddings, or carry context) or your "Alice" becomes three different people in one transcript.
Part 10: Streaming and realtime transcription#
Deep-dive
10.1 The three streaming shapes#
| Shape | What it is | Examples |
|---|---|---|
| File streaming | Upload a complete file; text streams back while processed | OpenAI stream=true on /v1/audio/transcriptions (SSE transcript.text.delta events) |
| Committed-turn realtime | Stream live audio; you commit each turn; final transcript per turn | OpenAI gpt-live-transcribe / gpt-transcribe sessions |
| True streaming STT | Partial hypotheses emitted during speech, finals on endpointing | gpt-live-transcribe, gemini-3.5-transcribe-live, Deepgram/AssemblyAI/ElevenLabs realtime |
10.2 Partial vs final, and endpointing#
Streaming STT emits two kinds of text:
- Partials/interim — speculative, revised as more audio arrives. Render them in a "draft" style; never act on them.
- Finals — committed when the system decides the turn ended (endpointing). Wrong endpointing = clipped words (too eager) or laggy captions (too patient).
Endpointing options: fixed silence timeout, provider VAD (energy or neural), or semantic turn detection (the model judges whether the speaker finished a thought). OpenAI's transcription sessions require you to commit turns (input_audio_buffer.commit); gpt-live-transcribe has a delay knob (minimal→xhigh) trading latency for accuracy — benchmark on your audio, per OpenAI's own guidance. Gemini Live emits interim_input_transcription vs input_transcription automatically.
10.3 Latency budget#
For live captions the chain is: capture → encode → network → VAD/endpointing → decode → render. Each hop adds tens to hundreds of ms; the model's delay/accuracy setting is usually the biggest single lever. Measure time-to-first-partial and time-to-final separately — a system can feel instant on partials while finals lag seconds. 09.6 builds the full latency-budget model; 09.7 applies it to voice agents.
A useful decomposition for budgeting — typical orders of magnitude, measure your own:
| Stage | Typical contribution | Main lever |
|---|---|---|
| Capture → encode | ~10–50 ms | frame/chunk size; PCM16 is effectively free |
| Network (one way) | ~20–150 ms | region; persistent WebSocket vs per-request HTTPS |
| VAD / endpointing wait | ~200–1000 ms | silence timeout, delay level — the biggest controllable |
| Time to first partial | provider-dependent | delay setting, model size, language mix |
| Time to final | provider-dependent | endpointing patience + turn length |
Measure, don't guess — OpenAI's realtime production checklist says to benchmark on your audio, and the same timing loop works for any event stream:
# latency_probe.py — python3 latency_probe.py
"""Time-to-first-partial and time-to-final on an event stream.
`events()` below is a simulated provider stream; swap it for your real
WebSocket/SSE iterator — the timing logic is identical.
"""
import asyncio
import time
async def events():
for _ in range(5):
await asyncio.sleep(0.05)
yield {"type": "delta"}
await asyncio.sleep(0.05)
yield {"type": "completed"}
async def measure(stream) -> tuple[float, float]:
t0 = time.monotonic()
first_partial = final = None
async for ev in stream:
now = time.monotonic() - t0
if ev["type"] == "delta" and first_partial is None:
first_partial = now
elif ev["type"] == "completed":
final = now
return first_partial, final
async def main() -> None:
fp, fin = await measure(events())
print(f"time-to-first-partial={fp:.3f}s time-to-final={fin:.3f}s")
asyncio.run(main())time-to-first-partial=0.052s time-to-final=0.307s10.4 Pseudo-streaming for offline models#
Self-hosted Whisper isn't natively streaming. The standard trick: run a sliding window — transcribe the last ~30 s chunk every ~1 s with the previous text as prompt context, emit only new text. It works but costs ~30× realtime compute; fine for dictation, wasteful for many concurrent users. Prefer whisper.cpp whisper-stream, faster-whisper's VAD-chunked batch mode, or a provider streaming API for real products.
Part 11: Quality engineering#
Deep-dive
11.1 Preprocessing: when it helps and when it hurts#
| Treatment | Helps when | Hurts when |
|---|---|---|
| Resample to 16 kHz mono | Always for STT APIs | Never — it's the expected input |
Loudness normalisation (loudnorm, gain) |
Quiet recordings, inconsistent levels across chunks | Already-normalised audio; aggressive limiting can clip sibilance |
| Noise reduction (RNNoise, noisereduce, provider-side) | Steady background noise (fans, traffic) | It can remove quiet speech, breath sounds that aid recognition, and create musical-noise artifacts that increase WER — A/B test on your audio |
| High/low-pass filtering | Hum at 50/60 Hz, rumble | Cutting into the 300–3400 Hz speech band destroys intelligibility |
| Denoise/de-reverb | Conference-room echo | Over-processing flattens consonants |
Rule of thumb: fix level and format always; apply denoising only with measured benefit on a labelled eval set. Most modern ASR is robust to moderate noise — preprocessing is for the bad 10%.
11.2 Vocabulary biasing, done right#
Every provider offers a hint mechanism — OpenAI prompt+keywords, Gemini custom_vocabulary, Deepgram keyterms, AssemblyAI prompting, faster-whisper initial_prompt. They share failure modes:
- Hints are suggestions, not requirements. Over-biasing makes the model insert terms that weren't said (OpenAI warns explicitly). Include only terms likely to appear.
- Keep lists focused. Gemini: ≤1000 terms but "best results typically with up to 100". OpenAI keywords: one per line, no
<>/newlines (whole request rejected otherwise). Whisper prompt: 224-token cap. - Biasing can't fix what wasn't heard. A heavily accented or mumbled term stays wrong; hints help the decoder choose between plausible candidates, they don't create acoustic evidence.
- Post-correction is often better. For a fixed glossary (product names, people), a text-model cleanup pass (12.1) is more reliable than cramming 500 terms into a bias list.
11.3 Language detection, accents and code-switching#
- Auto-detect is the default and usually right for multilingual archives; provide
languages/language_codeshints when you know (faster, sometimes more accurate, and prevents misdetection on short clips). - Code-switching (a speaker mixing languages mid-sentence) is handled explicitly by Gemini transcribe (85+ locales, dynamic switching) and Deepgram Nova-3 multilingual; Whisper-family models handle it inconsistently. If your callers mix languages, test that specific pair.
- Accents: accuracy varies more by accent+noise+domain than by language. Evaluate on your callers' accents, not a public leaderboard.
11.4 Inverse text normalisation (ITN), punctuation and casing#
ASR outputs raw words; production transcripts want "AC-42", "$26M", "3pm", "Dr. Smith". Two routes:
- Model-side: Gemini
smartmode and most modern APIs do ITN + punctuation + casing natively;verbatimmode preserves disfluencies for legal/medical fidelity. - Post-process: an LLM cleanup pass normalises domain formats deterministically-ish — but verify numbers and IDs against the audio or a second pass; LLMs "correct" things that were right.
Choose verbatim when fidelity matters (legal, clinical, compliance); smart/cleaned when readability matters (notes, search, captions).
11.5 Hallucination on silence and noise#
Whisper-family models famously invent fluent text during silence, music or crosstalk — a known, documented failure. Newer models mitigate it (Parakeet's transducer can't emit text without acoustic evidence; Gemini/OpenAI document confidence/empty-segment handling) but none are immune. Defences:
- VAD before ASR — don't send silence to the model at all (energy VAD for clean audio, Silero/provider VAD otherwise).
- Watch confidence signals — Whisper's
no_speech_prob/avg_logprob/compression_ratiofields flag suspicious segments (OpenAI documents thresholds: compression_ratio > 2.4 or avg_logprob < -1 warrants suspicion). - Cross-check duration — transcript word count wildly disproportionate to speech duration is a hallucination smell.
- Never feed silence-only chunks in streaming pipelines; commit turns only after real speech.
11.6 Profanity, PII and confidence#
- Profanity: most APIs transcribe verbatim; some offer
profanityfilters (Deepgram) — decide per product whether to mask, keep, or tag. - PII in speech (names, account numbers, card digits, health details): transcripts inherit every privacy obligation of the audio — redact in post-processing or use vendor redaction features (Deepgram redaction, AWS redaction, AssemblyAI PII redaction). Card numbers should ideally never reach the model — see 13.
- Confidence: some APIs return segment/word confidence (verbose_json logprobs on older OpenAI models, AssemblyAI/Deepgram confidence fields, Gemini doesn't expose it on transcribe). Use it to route low-confidence spans to human review — but treat self-reported confidence as uncalibrated until measured on your data (03.4's confidence discussion applies equally).
Part 12: Post-processing with LLMs#
Raw transcripts are rarely the product. The LLM cleanup layer — any text model, structured output per 03.4 — turns them into notes, actions and searchable text.
12.1 Cleanup and normalisation#
# transcript_cleanup.py — skeleton; uses any chat model via the OpenAI SDK
"""Clean a raw transcript: fix disfluencies, normalise entities, keep it verbatim-ish."""
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
RAW = """um so for the meeting i think we should uh invite alice
and wait no bob and carol, the budget is twenty six million
dollars and we ship on friday."""
resp = client.responses.create(
model="gpt-6-luna",
instructions=(
"You clean meeting transcripts. Remove filler words and false starts, "
"fix punctuation and capitalization, and normalise numbers, dates and "
"money to standard written form. Do NOT change names, facts or meaning. "
"Keep speaker turns separated by blank lines. Output only the cleaned text."
),
input=RAW,
)
print(resp.output_text)For the meeting, I think we should invite Bob and Carol. The budget is
$26M and we ship on Friday.12.2 Summaries, action items and chapters#
Prompt patterns for transcript post-processing live in 04.8, Part 4 (summarization contracts) — meeting notes specifically in 4.5. The STT-specific additions:
- Chunk long transcripts before summarising — a 3-hour transcript is ~30–45k tokens; map-reduce over speaker-turn chunks beats one giant prompt for recall (04.8, 4.4).
- Preserve timestamps in the output — ask for
{"summary": ..., "action_items": [{"text","owner","due","timestamp"}]}via structured output so every claim links back to the audio moment. - Speaker attribution propagates errors — a diarization mistake upstream becomes a wrong owner downstream. Keep
speakerlabels as hints, and let the LLM quote the turn it inferred ownership from.
12.3 Subtitles: SRT and VTT#
Word-level timestamps (Gemini, Deepgram, AssemblyAI, ElevenLabs) enable proper subtitles; segment-level timestamps suffice for coarse captions. The writer is trivial once you have segments — and it's a good canonical-shape exercise:
# srt_writer.py — python3 srt_writer.py
"""Write SRT and WebVTT subtitles from transcript segments."""
def fmt_srt_time(seconds: float) -> str:
ms = int(round(seconds * 1000))
h, ms = divmod(ms, 3_600_000)
m, ms = divmod(ms, 60_000)
s, ms = divmod(ms, 1000)
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
def to_srt(segments: list[dict]) -> str:
blocks = []
for i, seg in enumerate(segments, 1):
blocks.append(
f"{i}\n{fmt_srt_time(seg['start'])} --> {fmt_srt_time(seg['end'])}\n{seg['text']}\n"
)
return "\n".join(blocks)
def to_vtt(segments: list[dict]) -> str:
body = to_srt(segments).split("\n\n")
# VTT: 'WEBVTT' header, '.' instead of ',' in timestamps, no numeric sequence required
out = ["WEBVTT\n"]
for block in body:
lines = block.split("\n")
out.append("\n".join([lines[1].replace(",", ".")] + lines[2:]) + "\n")
return "\n".join(out)
SEGMENTS = [
{"start": 0.5, "end": 1.2, "text": "Thanks for joining, let's start with the roadmap."},
{"start": 2.0, "end": 3.5, "text": "Sure. First item: the transcription pipeline."},
{"start": 5.0, "end": 6.0, "text": "Agreed. Second item is the eval harness."},
]
print(to_srt(SEGMENTS))1
00:00:00,500 --> 00:00:01,200
Thanks for joining, let's start with the roadmap.
2
00:00:02,000 --> 00:00:03,500
Sure. First item: the transcription pipeline.
3
00:00:05,000 --> 00:00:06,000
Agreed. Second item is the eval harness.Subtitle engineering notes: captions need reading-speed limits (~17 chars/sec CPS, ~42 chars/line), so segment text may need re-wrapping or splitting across cue boundaries — word timestamps let you split mid-sentence cleanly. VTT is YouTube/HTML5's format; SRT is the universal interchange. Both are ~20 lines of code; providers also emit them directly (OpenAI response_format="srt"|"vtt").
12.4 The meeting-notes pipeline (running example)#
The module's running example ties it together: record → transcribe → diarize → summarise → action items. A production-minded skeleton:
# meeting_pipeline.py — orchestrates the stages; provider calls are illustrative
"""Meeting notes pipeline: audio -> transcript -> notes -> action items.
Stages are deliberately separate functions so each can be swapped
(different STT vendor, different LLM) and tested independently.
"""
from dataclasses import dataclass, field
@dataclass
class Segment:
start: float
end: float
speaker: str | None
text: str
words: list[dict] | None = None # word-level entries, when the provider returns them
confidence: float | None = None # 0..1 where the vendor scores (AssemblyAI/Deepgram/OpenRouter)
@dataclass
class Transcript:
segments: list[Segment] = field(default_factory=list)
language: str | None = None
duration_s: float | None = None
confidence: float | None = None # transcript-level score, where returned
def to_plain_text(self) -> str:
return "\n".join(f"[{s.start:7.1f}] {s.speaker or '-'}: {s.text}"
for s in self.segments)
@property
def full_text(self) -> str:
return " ".join(s.text for s in self.segments)
def transcribe(path: str) -> Transcript:
"""Stage 1: file -> Transcript. Call the provider, then parse its
response into this shape with transcript_parsers.transcript_from_*."""
raise NotImplementedError("choose a provider — see Parts 4-7")
def diarize(path: str) -> list[dict]:
"""Stage 2 (optional): speaker turns. pyannote or a vendor feature."""
raise NotImplementedError
def summarise(transcript: Transcript) -> dict:
"""Stage 3: Transcript -> {summary, decisions, action_items}.
Use structured output (03.4) so action_items have owner/due/timestamp."""
raise NotImplementedError
def main(wav_path: str) -> None:
t = transcribe(wav_path)
notes = summarise(t)
for item in notes["action_items"]:
print(f"- {item['text']} (owner: {item.get('owner')}, "
f"@ {item.get('timestamp', 'n/a')})")
if __name__ == "__main__":
main("meeting_16k.wav")Stage 0 of that pipeline — the part that turns "whatever the vendor returned" into Segments — is where most integrations actually live. Three response shapes dominate: OpenAI/OpenRouter verbose_json/diarized_json (a segments array, optional top-level words, optional speaker), and Gemini's Interactions response (every word arrives as a word_info annotation you group yourself). faster-whisper, Deepgram and AssemblyAI map onto these — write a fourth parser when yours doesn't fit:
# transcript_parsers.py — python3 transcript_parsers.py
"""Vendor response -> canonical Transcript (from meeting_pipeline).
Run from the same directory as meeting_pipeline.py. `__main__` demos the
OpenAI-shape parser on a fixture; swap in a real API response dict.
"""
from meeting_pipeline import Segment, Transcript
def _seg_confidence(seg: dict) -> float | None:
"""0..1 score when the vendor gives one; else None.
OpenAI verbose_json exposes avg_logprob / no_speech_prob instead —
log-scale diagnostics, not a calibrated confidence. Use them as
hallucination signals (11.5), not as a Segment.confidence value.
"""
conf = seg.get("confidence")
return float(conf) if conf is not None else None
def _words_for_segment(words: list[dict], seg: dict) -> list[dict] | None:
"""Word entries whose midpoint falls inside the segment's [start, end)."""
out = [w for w in words
if seg["start"] <= (w.get("start", 0) + w.get("end", 0)) / 2 < seg["end"]]
return out or None
def transcript_from_verbose_json(data: dict) -> Transcript:
"""OpenAI `verbose_json`/`diarized_json`, OpenRouter `verbose_json`."""
words = data.get("words") or []
segments = [
Segment(start=s["start"], end=s["end"],
speaker=s.get("speaker"), # diarized_json / OpenRouter diarization
text=s.get("text", "").strip(),
words=_words_for_segment(words, s),
confidence=_seg_confidence(s))
for s in data.get("segments", [])
]
return Transcript(segments=segments,
language=data.get("language"),
duration_s=data.get("duration"),
confidence=data.get("confidence")) # OpenRouter: 0..1 transcript score
def _offset_s(value) -> float | None:
"""Gemini word_info offsets arrive as strings like '0.100s'."""
if value is None:
return None
return float(str(value).removesuffix("s"))
def transcript_from_gemini(response) -> Transcript:
"""Gemini Interactions response -> Transcript.
With word timestamps (and optional diarization) every recognised word
arrives as a `word_info` annotation carrying text, speaker and
start/end offsets; group them into segments on speaker change or pause.
"""
words = []
for step in response.steps or []:
for content in getattr(step, "content", []) or []:
for ann in getattr(content, "annotations", []) or []:
if getattr(ann, "type", None) == "word_info":
words.append({
"text": ann.text,
"speaker": getattr(ann, "speaker", None),
"start": _offset_s(getattr(ann, "start_offset", None)),
"end": _offset_s(getattr(ann, "end_offset", None)),
})
return Transcript(segments=_group_words(words))
_UNSET = object()
def _group_words(words: list[dict], gap_s: float = 1.0) -> list[Segment]:
"""Group consecutive words into segments: split on speaker change or a
pause longer than `gap_s`."""
segments: list[Segment] = []
cur: list[dict] = []
cur_speaker = _UNSET
def flush() -> None:
nonlocal cur, cur_speaker
if not cur:
return
start = next((w["start"] for w in cur if w["start"] is not None), 0.0)
end = next((w["end"] for w in reversed(cur) if w["end"] is not None), start)
segments.append(Segment(
start=start, end=end,
speaker=None if cur_speaker is _UNSET else cur_speaker,
text=" ".join(w["text"] for w in cur),
words=cur))
cur, cur_speaker = [], _UNSET
for w in words:
prev_end = cur[-1]["end"] if cur else None
gap = ((w["start"] - prev_end)
if prev_end is not None and w["start"] is not None else 0.0)
if cur and (w.get("speaker") != cur_speaker or gap > gap_s):
flush()
if cur_speaker is _UNSET:
cur_speaker = w.get("speaker")
cur.append(w)
flush()
return segments
if __name__ == "__main__":
# Fixture shaped like OpenAI's verbose_json — swap in a real response dict.
fixture = {
"task": "transcribe", "language": "english", "duration": 6.4,
"text": "Thanks for joining. Let's start with the roadmap.",
"segments": [
{"id": 0, "start": 0.0, "end": 1.2, "text": "Thanks for joining.",
"avg_logprob": -0.3, "compression_ratio": 1.1, "no_speech_prob": 0.01},
{"id": 1, "start": 1.5, "end": 3.1,
"text": "Let's start with the roadmap.",
"avg_logprob": -0.4, "compression_ratio": 1.2, "no_speech_prob": 0.02},
],
"words": [
{"word": "Thanks", "start": 0.0, "end": 0.4},
{"word": "for", "start": 0.4, "end": 0.6},
{"word": "joining.", "start": 0.6, "end": 1.2},
{"word": "Let's", "start": 1.5, "end": 1.7},
{"word": "start", "start": 1.7, "end": 2.0},
{"word": "roadmap.", "start": 2.0, "end": 3.1},
],
}
t = transcript_from_verbose_json(fixture)
print(t.to_plain_text())
print("seg0 words:", [w["word"] for w in t.segments[0].words or []])
print("confidence:", t.confidence, "| language:", t.language)[ 0.0] -: Thanks for joining.
[ 1.5] -: Let's start with the roadmap.
seg0 words: ['Thanks', 'for', 'joining.']
confidence: None | language: englishDesign points a production version adds: idempotent stage outputs stored per meeting ID (re-run summarisation without re-transcribing), the raw transcript retained for audit, speaker names as suggestions pending human confirmation, and per-stage cost/latency logging (03.7, 03.10).
12.5 Transcripts into RAG#
Meeting transcripts are a top RAG source: chunk by speaker turn or topic window (never mid-sentence), keep start_ms/end_ms/speaker in chunk metadata (05.7, §5.10; metadata fields in 05.8), embed the cleaned text, and cite back to timestamps. Full retrieval pipeline: Module 07.
12.6 Questions, chapters and translation#
Question answering over transcripts. "What did we decide about X?" is a RAG-shaped question (12.5) with one twist: the answer must cite the audio moment, not just a chunk. The pattern is structured output (03.4) that demands an answer plus evidence:
# transcript_qa.py — skeleton; any chat model + structured output
"""Ask the transcript a question; get an answer anchored to a timestamp."""
from dotenv import load_dotenv
from openai import OpenAI
from pydantic import BaseModel
load_dotenv()
client = OpenAI()
class Answer(BaseModel):
answer: str
timestamp_s: float | None # start of the supporting segment, if found
quote: str # exact transcript line the answer relies on
TRANSCRIPT = "[0.5] A: ...\n[4.4] B: ..." # Transcript.to_plain_text()
resp = client.responses.parse(
model="gpt-6-luna",
instructions=(
"Answer questions about this meeting transcript. If the transcript "
"doesn't contain the answer, say so plainly — do not use outside "
"knowledge. timestamp_s is the segment start time in seconds the "
"answer comes from, or null. quote is the exact transcript line "
"you relied on."
),
input=TRANSCRIPT,
text_format=Answer,
)
a = resp.output_parsed # None on a refusal — check before use (03.4)
if a is not None:
print(f"{a.answer}\n @ {a.timestamp_s}s — \"{a.quote}\"")The Aurora migration stays blocked until AC-42 lands; Priya owns the
scope revisit.
@ 4.4s — "The Aurora migration is still blocked on AC-42, so I want to revisit scope."Three production notes: (a) for transcripts longer than ~30k tokens, don't send it all — retrieve the relevant speaker-turn windows first (12.5) or map-reduce per 12.2; (b) the quote field is your hallucination check — verify it appears verbatim in the transcript before showing the answer; (c) timestamp_s lets the UI seek the audio player straight to the moment, which is what makes transcript QA feel different from document QA.
Chapters. The 12.2 heading promised them — here's the recipe. Chapters are navigation, not summary: each one needs a title, a start time and a one-line description, aligned to topic shifts rather than equal-length slices:
- Window the transcript into ~5–10 minute chunks on speaker-turn boundaries (reuse the 8.2/8.3 chunking and stitching machinery).
- Map: per window, ask for
{"title": ..., "summary": ..., "start_s": ...}— cheap model, structured output. - Reduce: order windows by
start_s, merge into{"chapters": [{"title", "start_s", "end_s", "summary"}]}; the merge pass fixes duplicate titles and adjusts boundaries. - For short meetings that fit one prompt, skip the map step and ask for chapters directly — but keep the same schema so downstream code doesn't care.
Chapters feed three products at once: a clickable outline in the notes UI, natural chunk boundaries for RAG (12.5), and the "sections" a skim-reader actually wants.
Translation. Three different jobs get conflated under this word — don't:
| Job | Route | Trade-off |
|---|---|---|
| Translate the transcript text (post-hoc) | LLM pass over the cleaned transcript, per segment to keep timestamps | Cheap, uses your stack, keeps citations; verbatim disfluencies translate badly — clean first (12.1) |
| Speech-to-speech translation (live) | gpt-realtime-translate on wss://api.openai.com/v1/realtime/translations (>70 input languages, 13 output languages, priced by audio duration); gemini-3.5-live-translate-preview on the Gemini Live API (70+ languages) |
Real-time interpreted audio; a different product from transcription — see 09.7 for session mechanics |
| File translation endpoint | /v1/audio/translations — deprecated, shuts down 26 Feb 2027; replacement is the realtime translation session above |
Don't build on it |
The common mistake: translating audio when the user wanted a translated transcript. For meeting notes in another language, translate the cleaned text per segment (timestamps survive), and keep the original-language transcript alongside — back-translation is the cheapest QA check on the result.
Part 13: Privacy, consent and operations#
Deep-dive
13.1 Consent and recording law (awareness, not legal advice)#
Recording consent laws vary sharply by jurisdiction: some places require all-party consent (California-style two-party rule), others allow one-party consent, and workplace recording adds employment-law layers. This lesson cannot give legal advice — get counsel for your markets — but the engineering consequences are concrete:
- Notice before capture: play a notice, show a recording banner, or get explicit consent; log the consent event.
- Minimise what you keep: transcribe → store text + timestamps; consider deleting audio after N days (02.9, 9.5).
- Speaker-level deletion: one participant's erasure request may require removing their turns from transcripts and retraining/re-indexing derived artifacts.
- Biometric sensitivity: a voiceprint is biometric data in many regimes (GDPR special-category-adjacent, BIPA in Illinois). Speaker embeddings and voice references (
known_speaker_references) deserve the same protection as face embeddings.
13.2 Data handling by route#
| Route | Data leaves your infra? | Retention knobs |
|---|---|---|
| OpenAI/Gemini APIs | Yes, to the provider | Paid tiers don't train; abuse logs ~30 days (OpenAI); check 02.9, 9.2 per provider; ZDR arrangements exist for eligible endpoints |
| Specialised ASR | Yes | Deepgram/AssemblyAI/ElevenLabs offer retention controls; ElevenLabs Medical has ZRM + BAA |
| Cloud STT (Google/AWS/Azure) | To your cloud account | Covered by your existing cloud DPA — often the easiest compliance path |
| Self-hosted | No | You own everything — including breach response |
PII heard in audio ends up in the transcript, the LLM summary, the vector index and the logs — apply the same redaction/retention discipline as text PII (Module 12). Never put card numbers or health details through a consumer-tier model; telephony systems should mask card digits via DTMF before transcription (see 09.7).
13.3 Operational checklist#
- Idempotency: transcription jobs are retryable — key them by audio hash + model + params version so a retry doesn't double-bill or duplicate notes.
- Timeouts/retries: file APIs are long-running (a 1-hour file can take minutes) — set timeouts in minutes, not seconds, and retry per 03.8.
- Observability: log audio duration, provider, model, WER-proxy signals (empty transcript, low confidence ratio), cost per hour and pipeline stage latencies.
- Fallbacks: primary STT fails → secondary vendor or self-hosted; voice features degrade to text upload rather than dying.
- Model/version pinning: transcription models update silently; pin snapshots where available (
gpt-4o-mini-transcribe-2025-12-15style) and re-run your eval set on upgrades (02.9, Part 8). - Free practice path: everything except provider calls runs keyless — WAV tooling, VAD, WER, stitching, SRT, the pipeline skeleton. Provider free tiers exist (Deepgram $200 credit, AssemblyAI $50, Gemini free tier with data-use caveat); 03.1, Part 12 covers the local stand-in for LLM post-processing steps.
Failure gallery#
The ways STT pipelines actually break in production — symptom first, then cause, the signal that catches it, and the fix:
| Symptom | Likely cause | Detection signal | Fix |
|---|---|---|---|
| Fluent text appears during silence or music | Whisper-family hallucination on non-speech | no_speech_prob / avg_logprob / compression_ratio out of range; word count wildly disproportionate to speech duration |
Run VAD before ASR; never feed silence-only chunks; switch to a transducer model (Parakeet) for noise-heavy audio (11.5) |
Empty transcript or languages: [] |
Language detection failed, or audio is silent/corrupt/oversized | languages array empty; duration ≈ 0; upload rejected |
Supply a languages/language_codes hint; check the file with ffprobe; re-encode if the codec isn't supported |
| Words clipped at turn ends in streaming | Endpointing too eager | Finals arrive mid-phrase; partials keep revising the last word | Raise delay (OpenAI) or the silence threshold; add prefix_padding_ms-style padding (10.2) |
| Speaker labels inconsistent across chunks | Per-chunk diarization assigns A/B arbitrarily |
Same voice is A in chunk 1, B in chunk 3 |
Reconcile via speaker embeddings or context across chunks; or diarize the whole file once (9.4) |
Request rejected: invalid keywords |
A keyword contains <, > or a newline |
400 with a keywords validation error | Sanitise the list — one term per line, no angle brackets or CR/LF (11.2) |
| Upload rejected: file too large | Over the provider's byte cap (OpenAI 25 MB) | HTTP 413 / size error | Compress to Opus/MP3, or VAD-chunk and stitch (8.1, 8.3) |
| WER regresses after enabling timestamps | Gemini documents word-timestamp mode can degrade accuracy | Eval-set WER before/after the flag | A/B test on your audio; keep timestamps off the critical path if the delta is real |
| Wrong names/numbers after LLM cleanup | The cleaner "corrected" a correct transcript | Entities differ between raw and cleaned text | Keep raw + cleaned side by side; validate entities against a glossary; quote-check before shipping (12.1) |
| Realtime session accepts audio but returns nothing | turn_detection isn't null |
session.update error or silent session |
Transcription sessions require turn_detection: null and client-side commits (4.4) |
OpenRouter returns 400 on verbose_json |
The routed provider doesn't emit structured output | 400 naming response_format/timestamp_granularities |
Drop to json, or pass provider.only/options to a provider that supports it (6.1) |
| Diarization "works" in dev, missing in prod | provider.options silently dropped upstream |
No speaker fields in prod responses |
Pin the provider slug and verify option forwarding per route — allowlists drop unknown fields without error (6.1) |
| Transcript QA invents an answer | Model used parametric knowledge, not the transcript | quote field doesn't appear verbatim in the transcript |
Require evidence fields and verify them; retrieve-then-answer for long transcripts (12.6) |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "STT is just another LLM API call." | It's a different shape: multipart file uploads, per-audio-minute pricing, timestamped segments, diarization flags — and deprecated-model churn (OpenAI's first-generation transcription models shut down on 26 February 2027). |
"whisper-1 is the safe default." |
Deprecated — shuts down 26 Feb 2027. gpt-transcribe is the recommended replacement; it lacks word timestamps and diarization that whisper-1/gpt-4o-transcribe-diarize had. |
| "Higher sample rate = better transcription." | Speech lives below ~8 kHz; 16 kHz mono is the standard. 44.1 kHz WAV just makes a 3× bigger upload. |
| "WER 5% means 95% of words are right." | WER counts edits: one substitution can cost 1–2, one insertion costs 1. And it ignores which words — missing every account number can hide inside a low average. |
| "Diarization tells you who people are." | It labels anonymous clusters (A, spk_1). Naming requires known-speaker references or LLM inference — and inference can be confidently wrong. |
| "Send the whole 3-hour file at once." | OpenAI caps at 25 MB; Gemini at 1 h (30 min with diarization/timestamps). Chunk on silence, never mid-word, and rebase timestamps. |
| "Streaming is always better." | Offline file transcription is more accurate (full context) and cheaper per minute. Stream only when the audio is live or latency demands it. |
| "Whisper hallucinates, so avoid it." | The failure mode is real on silence/noise, but VAD gating + confidence checks + newer models (Parakeet can't hallucinate on silence architecturally) mitigate it — evaluate on your audio. |
| "Vocabulary hints guarantee correct terms." | They're hints: they reduce plausible alternatives, can inject unspoken terms, and can't exceed their token/term limits. Post-correction with a glossary is often stronger. |
| "Any LLM can clean up the transcript for free." | Cleanup costs tokens and can "correct" facts wrongly — keep raw + cleaned versions, validate entities, and never let the cleaner invent numbers. |
| "Free tier = free to use." | Gemini's free tier may train on your audio; paid tiers don't. Check each provider's data-use terms before sending real recordings. |
Key takeaways#
- Audio is numbers: sample rate × channels × bit depth × duration = size; 16 kHz mono 16-bit is the ASR lingua franca (Nyquist: speech needs ~8 kHz bandwidth).
- ASR = feature extraction + encoder + decoder; dedicated STT APIs beat chat models for transcripts (timestamps, diarization, per-minute pricing).
- Measure with WER — but normalise first, watch which errors, and supplement with entity error rate for names/numbers/IDs.
- November 2026 landscape: OpenAI
gpt-transcribe($0.0045/min) +gpt-live-transcribe($0.017/min); Geminigemini-3.5-transcribe/-live(~$0.005–0.009/min); Anthropic has no audio; OpenRouter has a dedicated STT endpoint; specialists (Deepgram, AssemblyAI, ElevenLabs, Speechmatics, cloud STT) win on diarization depth, compliance and cost at scale; open models (faster-whisper, whisper.cpp, Parakeet, Canary, Qwen3-ASR) win on privacy and cost at volume. - OpenAI's first generation is on a shutdown clock:
whisper-1,gpt-4o-transcribe*shut down 26 Feb 2027 — and the replacements currently lack word timestamps and speaker labels. Design for migration. - Long audio = chunk on silence, rebase timestamps, dedupe overlaps, parallelise with bounded concurrency; vendor batch APIs exist everywhere except OpenAI/Gemini.
- Diarization labels clusters, not identities — name speakers via voice references or LLM inference, and reconcile labels across chunks.
- Streaming trades accuracy for latency: partials are speculative, finals need endpointing, and
delay/quality knobs must be benchmarked on real audio. - Hallucination on silence is the signature ASR failure — gate with VAD, check confidence signals, never transcribe pure noise.
- Post-processing is where transcripts become products: cleanup, summaries, action items with timestamps, SRT/VTT subtitles, RAG over speaker-turn chunks, timestamped QA — always keep the raw transcript for audit.
- Parse once, consume everywhere: vendor responses differ wildly; a canonical
Transcriptmodel (12.4) plus one parser per response shape keeps every downstream stage provider-agnostic. - Voice is biometric data: consent, notice, minimisation and retention apply doubly to audio and its derivatives.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Speech-to-text / ASR / STT | Converting speech audio into text |
| Sample rate | Measurements per second of the audio wave (Hz); 16 kHz is the ASR standard |
| Bit depth | Precision of each audio sample; 16-bit PCM is standard |
| Channel (mono/stereo) | Number of simultaneous audio recordings; ASR uses mono |
| PCM | Raw uncompressed audio samples |
| Codec / container | Compression algorithm (MP3, Opus, FLAC) vs file wrapper (WAV, M4A, OGG) |
| Nyquist limit | Highest representable frequency = half the sample rate |
| μ-law / A-law | 8 kHz telephony audio codecs |
| Feature extraction (log-mel) | Converting waveform windows into the representation the model consumes |
| Acoustic model / encoder | Neural net turning audio features into representations |
| Decoder | Sequence model turning representations into text tokens |
| Encoder-decoder ASR | Whisper-style architecture: audio encoder + text decoder |
| Audio-native model | A model that consumes audio directly (transcribe or understand) |
| Offline vs streaming transcription | Whole-file batch vs live audio with partial/final results |
| Word error rate (WER) | Edit distance between hypothesis and reference words ÷ reference length |
| CER | Character error rate — WER's finer-grained sibling |
| cpWER / DER | Diarization-aware WER / diarization error rate |
| Inverse text normalisation (ITN) | Converting spoken forms ("twenty six million") to written ("$26M") |
| Speaker diarization | Labeling who spoke when — anonymous clusters, not identities |
| Known-speaker reference | A short voice sample used to name a diarized speaker |
| Endpointing | Deciding when a speaker's turn has ended in streaming STT |
| Interim vs final transcript | Speculative partial text vs committed turn transcript |
| Voice activity detection (VAD) | Detecting speech vs silence — energy-based or learned (Silero) |
| Keyterm prompting / custom vocabulary | Biasing recognition toward domain terms |
| Code-switching | Mixing languages within one utterance |
| Verbatim vs smart mode | Exact disfluency-preserving transcript vs cleaned/formatted |
| Transcript normalisation | Lowercasing, punctuation stripping before WER |
| Pseudo-streaming | Chunked sliding-window transcription for non-streaming models |
| Canonical transcript model | Your own Transcript/Segment shape that every provider response is parsed into |
provider.options (OpenRouter) |
Per-upstream-provider parameters passed through OpenRouter's STT endpoint |
All terms are also collected in the glossary.
Exercises#
- Audio basics: generate the synthetic WAV (
make_test_wav.py), inspect it withwav_inspect.py, then convert a real phone recording to 16 kHz mono with ffmpeg and compare file sizes WAV vs Opus. - WER: extend
wer.pywith a normaliser that maps number words to digits ("twenty six" → "26"). Measure how WER changes on three transcript pairs before/after — and explain which choice a legal team would prefer. - VAD: run
vad_chunk.pyon a real meeting recording. Where does energy VAD fail (music intro, crosstalk)? Swap insilero-vadvia faster-whisper'svad_filterand compare segment boundaries. - Chunking: take a 90-minute recording, split it into provider-sized chunks on VAD boundaries for OpenAI's 25 MB cap, transcribe each, and stitch — verify no sentence is split and timestamps rebase correctly.
- Provider comparison: pick one 5-minute meeting clip you have rights to. Transcribe it with
gpt-transcribe,gemini-3.5-transcribe(with and withoutcustom_vocabulary) and faster-whisper locally. Score all three with yourwer.pyagainst a hand-corrected reference. Which won on entities (names, numbers)? - Diarization: run pyannote on the same clip (accept the HF conditions first). Compare its speaker turns to Gemini's
spk_1/spk_2output — where do they disagree, and what does that imply for naming speakers downstream? - Pipeline: complete
meeting_pipeline.py— implementtranscribeusing one of the parsers intranscript_parsers.py(writetranscript_from_openrouteryourself: it's theverbose_jsonshape plus a top-levelconfidenceand integerspeakerindices), implementsummarisewith structured output (action items with owner + timestamp), generate SRT subtitles from the segments, and produce a one-page "how to run this on Friday" checklist including consent/notice steps. - QA and chapters: using your completed pipeline, ask the transcript three questions with
transcript_qa.py— one answerable, one not in the transcript, one ambiguous — and check thatquoteverification catches the hallucinated case. Then generate chapters for a 30-minute recording and check that boundaries land on topic shifts, not mid-sentence.
Hints for the exercises
- A 16 kHz mono WAV is 32,000 bytes per second; 64 kbps Opus is 8,000 bytes per second, about a quarter of that (the table in 1.6 gives the hourly figures).
- A legal team prefers the unmapped comparison: it keeps what was actually said ("twenty six") and avoids a normaliser silently deciding that "twenty six" and "26" are the same. Report the score both ways and state the normaliser.
- Energy VAD marks a music intro or loud crosstalk as speech; a learned VAD (Silero, through
vad_filter=True) usually skips the music but may still keep crosstalk. Compare segment start and end times, not segment counts. - At 32 kbps a 90-minute file is about 22 MB, so one request may do; the exercise is the splitting logic, so lower your per-chunk cap (for example 8 MB) to force several chunks and test the stitching.
- Use the same normaliser for all three transcripts, and score names and numbers separately from the overall WER;
custom_vocabularyoften helps names and does nothing for numbers. - Expect disagreement at speaker changes shorter than about a second and in overlapping speech; both systems label anonymously, so naming still needs the LLM step or known-speaker references.
- For
transcript_from_openrouter, reusetranscript_from_verbose_jsonand map the integerspeakertof"spk_{n}". - For the hallucinated case,
quoteis not found verbatim in the transcript (quote in TRANSCRIPTis False), so show "not in the transcript" instead of the answer.
Check yourself#
- Why is 16 kHz mono the standard ASR input, and what does the Nyquist limit have to do with it?Speech's useful content sits below ~8 kHz; the Nyquist limit says a 16 kHz sample rate can represent up to 8 kHz — exactly covering speech. Mono because ASR models are trained on mono and stereo adds no linguistic information.
- What's the difference between a codec and a container? Name two of each.Codec = compression algorithm for the samples (MP3, AAC, Opus, FLAC, PCM); container = file wrapper holding compressed audio + metadata (WAV, M4A/MP4, OGG, WebM, FLAC).
- Why can
wavenot read an.m4afile, and what are two Python alternatives?waveonly reads uncompressed PCM WAV. Alternatives:soundfile(libsndfile),pydub(ffmpeg wrapper), orffmpeg/ffprobeon the CLI. - Draw the three stages inside an ASR system and say which stage a "prompt" or "keywords" parameter influences.Feature extraction (log-mel spectrogram) → acoustic encoder → decoder/language model. Vocabulary hints influence the decoder's candidate selection, not the acoustic analysis.
- Compute WER by hand: reference "the cat sat on the mat" (6 words), hypothesis "the cat sat mat" — what's the WER and why?Deleting "on" and "the" = 2 deletions (or substitute+delete variants); minimum edits = 2; WER = 2/6 ≈ 0.333.
- Why does normalisation change WER, and what should you normalise before comparing two ASR systems?Punctuation/casing/number-format differences create phantom edits. Normalise both sides identically (lowercase, strip punctuation, standardise numbers/fillers) — and document the normaliser, since it changes the score.
- As of November 2026, which OpenAI models are deprecated for transcription, when do they shut down, and what's the recommended replacement for file vs realtime?
whisper-1,gpt-4o-transcribe,gpt-4o-mini-transcribe,gpt-4o-transcribe-diarize(and/v1/audio/translations) shut down 26 February 2027. Replacements:gpt-transcribefor file transcription,gpt-live-transcribefor realtime. gpt-transcribereturnslanguages: []— what does that mean, and what do you do about it?The model couldn't reliably predict a language —languagesis empty when detection fails. Omit the hint or check the audio; don't treat it as an error.- Name three things
gpt-live-transcribedoes not return that a file-transcription product might need.Word-level timestamps, speaker labels/diarization, and confidence scores (per OpenAI's realtime-transcription docs). - Gemini's
custom_vocabularycan't be combined with which two features, and why might that matter for a meeting-notes product?Speaker diarization and word-level timestamps. A product wanting biased vocabulary AND speaker labels must choose: run two passes, use a different provider, or post-process. - Your 90-minute recording is far over OpenAI's 25 MB cap as a WAV (about 170 MB) but fits as a 32 kbps MP3 (about 22 MB) — what's the engineering trade-off of compressing vs splitting?Compression keeps one request but loses a little quality and still hits duration caps; splitting preserves quality but multiplies calls, needs boundary care (don't cut mid-word/sentence) and timestamp rebasing. Usually compress first, split only past the duration limit.
- Why is diarization label consistency across chunks a problem, and name two ways to solve it.Each chunk labels speakers independently (
Ain chunk 1 may beBin chunk 2). Solve via known-speaker references, speaker embeddings matched across chunks, or an LLM pass that reconciles names from context. - What's the difference between interim and final transcripts in streaming STT, and why must UI code treat them differently?Interims are speculative partial text revised as audio arrives (render as draft); finals are committed per turn (act on them). Acting on an interim that later changes produces flickering/wrong UI state.
- Whisper transcribes "Thank you for watching" during 30 seconds of silence. Name two mitigations.Run a VAD and don't send silence to the model; check
no_speech_prob/avg_logprob/compression_ratioon Whisper outputs; prefer models architecturally unable to emit text without acoustic evidence (e.g. Parakeet TDT) for noise-heavy audio. - A meeting participant asks to be removed from the notes. Which artifacts beyond the audio file might contain their data?The transcript text, cleaned/summary text, action items naming them, vector-index chunks containing their turns, subtitles, and any LLM prompts/logs that included the transcript — plus derived embeddings which can't be selectively edited.
Further resources#
- OpenAI: Speech-to-text guide, Realtime transcription, Transcription API reference, Deprecations, model pages for
gpt-transcribeandgpt-live-transcribe. - Google: Audio transcription (
gemini-3.5-transcribe), Live transcription, Gemini API pricing. - Anthropic: Vision/media docs (text+image+document only — no audio).
- OpenRouter: STT docs, Audio overview, Models API.
- Specialists: Deepgram docs + pricing; AssemblyAI docs + pricing; ElevenLabs Scribe + API pricing; Speechmatics; Google Cloud STT; Azure AI Speech; AWS Transcribe; Rev.ai.
- Open models: faster-whisper (PyPI), whisper.cpp, mlx-whisper, WhisperX, NeMo (Parakeet/Canary), Qwen3-ASR, Moonshine, pyannote.audio (its README shows the current
community-1quick start) + speaker-diarization-3.1 model card (the legacy pipeline), Open ASR Leaderboard. - Whisper: openai/whisper (MIT weights), Whisper paper.
- Tools: ffmpeg, soundfile, pydub, Silero VAD.
← 09.3 — Image Generation and Editing | Module 09 overview | 09.5 — Text-to-Speech →