Sub topic 8
Transcribing long recordings with sliding 30-second windows
This chapter assumes you can already run model.transcribe() from the openai-whisper package and that you know Whisper takes a log-Mel spectrogram as input. It covers what happens when a recording is longer than the model's input size, which settings control that process, and the errors that appear on long files.
Why windows exist
Whisper's encoder always receives exactly 30 seconds of audio. At 16 kHz that is 480,000 samples, which become 3,000 spectrogram frames and 1,500 encoder positions of 20 ms each. Shorter clips are padded with silence to reach 30 seconds. Longer clips cannot be fed in at once.
The transcribe() function therefore does the following:
- It loads the whole file, resamples it to 16 kHz mono, and computes one long log-Mel spectrogram.
- It keeps a pointer called
seek, which marks how far into the audio it has already transcribed. - It cuts a 30-second window starting at
seek, decodes it, and movesseekforward. - It repeats until
seekreaches the end.
The windows are sequential and are not a fixed grid. The next window starts where the decoder says the last complete utterance ended.
How the seek pointer moves
The decoder predicts timestamp tokens as well as text. Each timestamp token marks a time in the window with 0.02 s resolution. The decoder output for one window looks like <|0.00|> text <|4.20|><|4.20|> more text <|9.60|>. A timestamp token at the end of a segment is also the start of the next one.
After decoding, transcribe() decides how far to advance:
- If the output ends with two consecutive timestamp tokens, the final segment is complete, so
seekadvances by the full window (30 s). - If the output ends with a single timestamp token, the final segment may have been cut off by the window edge.
seekmoves only to the last timestamp, so the next window starts at that point and re-decodes the partial speech with full context. - If the window contains no timestamp tokens,
seekadvances by the window length.
This is why a 95-minute file does not produce exactly 190 windows, and why segment boundaries rarely fall on multiples of 30 seconds.
Context carried between windows
By default condition_on_previous_text=True. The text decoded from earlier windows is passed to the next window as a prompt, up to a limit of about 224 tokens. This helps in several ways:
- Spelling of names and jargon stays consistent across windows.
- Punctuation and capitalization style persist.
- A sentence that straddles a window edge continues naturally.
It also creates the main failure mode of long-form transcription. If one window produces a repetition loop or a hallucinated phrase, that text becomes the prompt for the next window, which tends to repeat it. One bad window can then contaminate minutes of output.
Quality checks and temperature fallback
Each decoded window is checked, and transcribe() retries with a higher sampling temperature when a check fails. The defaults are:
| Parameter | Default | Meaning |
|---|---|---|
| `temperature` | `(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)` | Temperatures tried in order. The first value uses beam search or greedy decoding, and later values sample. |
| `compression_ratio_threshold` | `2.4` | If the gzip compression ratio of the text exceeds this, the output is too repetitive and the window is retried. |
| `logprob_threshold` | `-1.0` | If the average token log probability is below this, the window is retried. |
| `no_speech_threshold` | `0.6` | If the no-speech probability is above this and the log probability is also below the threshold, the window is treated as silence and skipped. |
Passing a single number such as temperature=0.0 turns fallback off. Doing so makes runs deterministic, but repetition loops then have no escape.
Inspecting windows in code
Each entry in result["segments"] carries the data these checks used. The example below disables previous-text conditioning and prints the numbers you need to find suspicious regions. It also counts how many 30-second windows the audio spans.
import whisper
from whisper.audio import N_SAMPLES
path = "lecture.mp3"
audio = whisper.load_audio(path) # 16 kHz mono float32; needs ffmpeg
print(f"duration: {len(audio) / 16000:.1f} s")
print(f"ceil(duration / 30 s): {-(-len(audio) // N_SAMPLES)} windows")
model = whisper.load_model("small")
result = model.transcribe(
path,
condition_on_previous_text=False,
temperature=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
compression_ratio_threshold=2.4,
logprob_threshold=-1.0,
no_speech_threshold=0.6,
fp16=False,
)
for seg in result["segments"]:
flag = ""
if seg["compression_ratio"] > 2.4 or seg["avg_logprob"] < -1.0:
flag = " <-- check"
print(
f"[{seg['start']:7.2f} -> {seg['end']:7.2f}] "
f"lp={seg['avg_logprob']:.2f} "
f"cr={seg['compression_ratio']:.2f} "
f"ns={seg['no_speech_prob']:.2f} "
f"T={seg['temperature']:.1f}{flag}"
)Each segment holds these fields:
avg_logprobis the average log probability of the segment's tokens.compression_ratiois the gzip ratio of the segment text.no_speech_probis the model's estimate that the window held no speech.temperatureis the temperature at which the accepted decode was produced. A value above 0.0 means the window needed at least one retry.
seek is also stored per segment and gives the window start in spectrogram frames.
Settings that matter on long files
condition_on_previous_text
Setting this to False prevents errors from spreading, at some cost to consistency. Terminology may vary between windows, and punctuation may drift. For noisy or music-heavy recordings, False is usually the safer choice. For clean speech with domain vocabulary, True usually gives better text.
initial_prompt
initial_prompt supplies text for the first window only, such as a list of names or a style sample. Later windows are prompted by previous output when conditioning is on. If conditioning is off, the initial prompt is still used for every window in current versions of the package, which keeps vocabulary hints alive. Check your installed version if this matters, because the behavior has changed between releases.
Language detection
Language is detected once, from the first 30 seconds, unless you pass language. A recording that opens with 30 seconds of music or a greeting in another language can be misdetected for its entire length. Pass language="en" (or the right code) whenever you know it.
hallucination_silence_threshold
With word_timestamps=True, you can set hallucination_silence_threshold to a number of seconds, such as 2.0. When Whisper finds a long silence next to a suspicious segment, it skips ahead instead of keeping the text. This is useful for recordings with long pauses, but it requires word timestamps, which add runtime.
clip_timestamps
Recent versions accept clip_timestamps, which restricts transcription to chosen ranges. Use it to skip a known intro or to rerun only a problem region, for example clip_timestamps="600,720".
Common errors
- Repeated sentences for minutes. This is a repetition loop propagated by
condition_on_previous_text=True. Turn conditioning off, keep fallback enabled, and rerun the affected range. - Invented text over silence or music. Phrases such as "Thanks for watching" can appear where nobody speaks. Raise
no_speech_thresholdcarefully, usehallucination_silence_threshold, or remove silent stretches beforehand with voice activity detection. - Wrong language for the whole file. See the language detection note above. Fix it with an explicit
language. - Timestamps drifting or overlapping. Segment times are usually correct because they come from the decoder's timestamp tokens, but they can be off by a second or more when a window is poor. Word timestamps are derived from cross-attention and are usually tighter.
- Memory spikes on very long files.
whisper.load_audioloads the whole file as float32, which is about 230 MB per hour at 16 kHz. Split multi-hour files into pieces of an hour or less at silent points, transcribe each, and add each piece's start offset to its timestamps. - Slow CPU runs. Decoding is sequential, and each window requires an encoder pass and many decoder steps. A fallback retry repeats that work, so a poor-quality file takes noticeably longer.
Other tools handle windows differently
The faster-whisper library from the topic's earlier examples follows the same seek-based algorithm, and it yields segments lazily. Nothing is decoded until you iterate. It also supports vad_filter=True, which drops non-speech audio before windowing.
from faster_whisper import WhisperModel
model = WhisperModel("small", device="cpu", compute_type="int8")
segments, info = model.transcribe(
"lecture.mp3",
beam_size=5,
vad_filter=True,
condition_on_previous_text=False,
)
for segment in segments:
print(f"[{segment.start:.2f}s -> {segment.end:.2f}s] {segment.text}")The Hugging Face pipeline works differently. With chunk_length_s=30 it cuts the audio into chunks and decodes them independently, then merges the results. Without overlap, words at the cut points are damaged. Adding stride_length_s, such as stride_length_s=5, makes neighboring chunks overlap so the merge can discard the unreliable edges. Chunked decoding runs faster in batches, but it gives up the seek pointer and previous-text context, so it can be slightly less accurate on the same model.
| Approach | Window placement | Context between windows | Typical strength |
|---|---|---|---|
| `openai-whisper` `transcribe()` | Sequential, driven by timestamp tokens | Previous text as prompt | Best accuracy and consistency |
| faster-whisper | Sequential, same algorithm | Previous text as prompt | Speed, lower memory, VAD option |
| transformers pipeline with chunks | Fixed chunks with optional overlap | None between chunks | Batching on GPU |
Summary of the working model
A long file is one spectrogram consumed by a moving pointer, with 30 seconds of input per step. The decoder's timestamp tokens decide how far the pointer advances. Previous text is the context. Compression ratio, log probability, and no-speech probability are the quality checks, and a rise in temperature is the recovery. Most long-file failures are either context contamination or a wrong first-window language detection.
Exercise
A two-hour podcast transcribes well for ten minutes, then the same sentence repeats for several minutes before normal text returns. Which setting most likely spread the problem, and what two changes would you try first?
Show answer
condition_on_previous_text=True (the default) passed the looping text to each following window as a prompt. First, set condition_on_previous_text=False. Second, make sure temperature fallback is enabled, for example with the default tuple, together with compression_ratio_threshold=2.4. Then rerun the bad range using clip_timestamps if needed.
Exercise
A file starts with 40 seconds of English intro music and then continues in Spanish. The output is garbled English-looking text. What happened, and how do you fix it?
Show answer
Language is detected once from the first 30 seconds. The music led to a wrong detection (English), and that language was applied to every window. Pass language="es" explicitly so detection is skipped.