Sub topic 9
Reading segment and word timestamps
This chapter covers how Whisper reports time. You will read segment timestamps and word timestamps, learn where each comes from, and use them to build subtitles and to find low-confidence words. It assumes you can already run model.transcribe() and read its result dictionary, and that you know Whisper processes audio in 30-second windows.
Two kinds of timestamps
Whisper gives you timing at two levels, and they are produced by different mechanisms.
- Segment timestamps come from the decoder itself. The decoder is trained to emit special timestamp tokens between pieces of text. Each token represents a time in steps of 0.02 seconds (20 ms). Whisper emits them by default.
- Word timestamps are computed after decoding. Whisper looks at the decoder's cross-attention weights (how strongly each output token attends to each part of the encoded audio) and aligns tokens to audio frames using dynamic time warping. This step is optional and costs extra time.
The consequence is that segment boundaries are predicted text-and-time together, while word times are an estimate derived from attention. Word times are usually good, but they are not guaranteed to be exact.
Reading segment timestamps
transcribe() returns a dictionary. Its "segments" key holds a list of dictionaries, one per segment. A segment is a stretch of speech the decoder grouped between two timestamp tokens, usually a phrase or sentence. Its fields include:
| Field | Meaning |
|---|---|
| `id` | Index of the segment in the file |
| `seek` | Frame offset of the window the segment came from |
| `start`, `end` | Times in seconds from the start of the file |
| `text` | The transcribed text, often with a leading space |
| `tokens` | Token IDs for the text |
| `temperature` | The sampling temperature that produced this segment |
| `avg_logprob` | Mean log probability of the tokens; lower means less confident |
| `compression_ratio` | How compressible the text is; very high values suggest repetition |
| `no_speech_prob` | Probability that the segment contains no speech |
The times are already absolute. For long files, Whisper decodes each window with times relative to that window and adds the window offset before returning, so you do not need to add seek yourself.
import whisper
model = whisper.load_model("small")
result = model.transcribe("interview.mp3", language="en", fp16=False)
for segment in result["segments"]:
start, end = segment["start"], segment["end"]
print(f"[{start:7.2f} -> {end:7.2f}] {segment['text'].strip()}")Segment lengths vary. A segment can be a few words or most of a window, and boundaries often fall on pauses or punctuation. You cannot ask for a specific segment length through a normal option, so if you need fixed-length caption lines, regroup the word timestamps yourself (shown below).
Turning on word timestamps
Pass word_timestamps=True. Each segment then gains a "words" list.
import whisper
model = whisper.load_model("small")
result = model.transcribe(
"interview.mp3",
language="en",
word_timestamps=True,
fp16=False,
)
for segment in result["segments"]:
print(f"[{segment['start']:.2f} -> {segment['end']:.2f}] {segment['text'].strip()}")
for word in segment["words"]:
print(
f" {word['start']:7.2f} {word['end']:7.2f} "
f"p={word['probability']:.2f} {word['word']!r}"
)Each word dictionary has four keys: word, start, end, and probability. Note three details:
- The
wordstring usually keeps its leading space (' hello'), because that space is part of the token. Call.strip()before comparing or displaying. - Punctuation is merged into neighbouring words. By default, opening marks such as quotes are attached to the following word and closing marks such as commas and periods to the preceding word. The options
prepend_punctuationsandappend_punctuationscontrol this. probabilityis the model's probability for the word's token, not an alignment-quality score. It is useful as a confidence hint but does not measure timing accuracy.
Word-level timing adds processing time, since it needs the attention weights and an alignment pass. Turn it on only when you need it.
Building subtitles from timestamps
A common use is writing an SRT subtitle file. SRT numbers each cue and uses the format HH:MM:SS,mmm. The helper below works from segment times and needs no extra libraries.
import whisper
def srt_time(seconds: float) -> str:
total_ms = round(seconds * 1000)
hours, rest = divmod(total_ms, 3_600_000)
minutes, rest = divmod(rest, 60_000)
secs, millis = divmod(rest, 1000)
return f"{hours:02}:{minutes:02}:{secs:02},{millis:03}"
def write_srt(segments, path):
with open(path, "w", encoding="utf-8") as f:
for number, seg in enumerate(segments, start=1):
f.write(f"{number}\n")
f.write(f"{srt_time(seg['start'])} --> {srt_time(seg['end'])}\n")
f.write(seg["text"].strip() + "\n\n")
model = whisper.load_model("base")
result = model.transcribe("audio.mp3", fp16=False)
write_srt(result["segments"], "audio.srt")The whisper command-line tool does this for you with --output_format srt (or vtt, json, tsv, txt). Write your own helper when you need custom grouping or formatting.
Regrouping words into caption lines
Long segments make poor captions. With word timestamps you can start a new cue whenever a line gets too long.
def words_to_cues(segments, max_chars=42):
cues = []
current = []
for segment in segments:
for word in segment["words"]:
text = word["word"].strip()
if not text:
continue
candidate = " ".join(w["word"].strip() for w in current + [word])
if current and len(candidate) > max_chars:
cues.append(current)
current = []
current.append(word)
if current:
cues.append(current)
return [
{
"start": cue[0]["start"],
"end": cue[-1]["end"],
"text": " ".join(w["word"].strip() for w in cue),
}
for cue in cues
]Feed the result to write_srt from the previous example. The dictionaries have the same start, end, and text keys that write_srt reads.
Using probabilities to find weak spots
Word probabilities let you flag places to review. This script lists words below a threshold, with the time to jump to in an audio player.
import whisper
model = whisper.load_model("small")
result = model.transcribe("interview.mp3", word_timestamps=True, fp16=False)
threshold = 0.5
for segment in result["segments"]:
for word in segment["words"]:
if word["probability"] < threshold:
minutes, seconds = divmod(word["start"], 60)
print(f"{int(minutes):02}:{seconds:05.2f} p={word['probability']:.2f} {word['word'].strip()}")Low probability often marks names, jargon, or mumbled speech. It does not prove an error, and a high probability does not prove correctness.
Edge cases and gotchas
Timestamps look precise but have limits. Know these before you build on them.
- Resolution. Segment times are multiples of 0.02 s, and word times come from the same frame grid. Do not treat them as sample-accurate.
- Drift near silence and music. Alignment is weaker where there is no clear speech. Words next to long pauses may stretch across the pause, so a word's
endcan be later than the sound actually ends. - Very short or very long words. Whisper applies sanity rules to word durations after alignment, such as limiting unusually long words at segment boundaries. Odd durations still happen with numbers, acronyms, and disfluencies.
- Non-spaced languages. For languages such as Chinese, Japanese, and Thai, the model splits words differently, since there are no spaces. Word entries there are closer to characters or short units.
- Hallucinated segments. A made-up sentence over silence still gets timestamps. Check
no_speech_probandcompression_ratiobefore trusting a segment. The optionhallucination_silence_threshold(used with word timestamps) skips silent stretches above a given length when a hallucination is suspected. - Window boundaries. A word cut by a 30-second boundary may be split, repeated, or dropped. Times stay consistent, but check the text near multiples of 30 s.
- Restricting the range.
clip_timestamps(for example"60,120") transcribes only a time range. Returned times are still relative to the full file.
The same data in other runtimes
The openai-whisper structure above is the reference. Other libraries expose the same idea with different names.
faster-whisper returns segment objects with attributes. Pass word_timestamps=True to fill segment.words.
from faster_whisper import WhisperModel
model = WhisperModel("small", device="cpu", compute_type="int8")
segments, info = model.transcribe("audio.mp3", word_timestamps=True)
for segment in segments:
print(f"[{segment.start:.2f}s -> {segment.end:.2f}s] {segment.text.strip()}")
for word in segment.words:
print(f" {word.start:.2f} {word.end:.2f} {word.probability:.2f} {word.word.strip()}")Because faster-whisper yields segments lazily, the transcription work happens as you loop. Convert with list(segments) if you need to reuse them.
The Hugging Face pipeline uses return_timestamps. Use True for segment-level chunks and "word" for word-level ones. Each chunk has text and a timestamp tuple of start and end.
from transformers import pipeline
asr = pipeline(
"automatic-speech-recognition",
model="openai/whisper-small",
chunk_length_s=30,
)
result = asr("audio.mp3", return_timestamps="word")
for chunk in result["chunks"]:
start, end = chunk["timestamp"]
print(f"{start} -> {end} {chunk['text']}")The last chunk's end can be None if the audio is cut off mid-word, so guard against it when formatting.
Choosing between segment and word timestamps
| Need | Use |
|---|---|
| Rough navigation, searchable transcript | Segment timestamps |
| Standard subtitles with natural phrasing | Segment timestamps written to SRT or VTT |
| Fixed-width caption lines, karaoke-style highlighting | Word timestamps |
| Finding and reviewing uncertain words | Word probabilities |
| Fastest possible run | Segment timestamps only |
Exercise
You run model.transcribe("talk.mp3", word_timestamps=True). For the first segment, segment["words"][0]["word"] is ' Welcome'. Why does the string start with a space, and what should you do before comparing it to the text "Welcome"?
Show answer
The leading space is part of the token the model produced, because the tokenizer attaches the space that precedes a word to that word. Call .strip() on it before comparing. Word timestamps are also estimates from cross-attention alignment, so the same entry's start and end are only approximate.
Exercise
A segment from a recording with a long silent intro reads "Thanks for watching!" with a start of 0.00 and an end of 6.00, though nobody speaks. Name two fields you can check to decide whether to discard it, and one option that can help prevent this.
Show answer
Check no_speech_prob (high means likely no speech) and compression_ratio or avg_logprob (very high ratio or very low log probability suggests a hallucination). The option hallucination_silence_threshold, used with word_timestamps=True, helps skip long silences when a hallucination is suspected.
Exercise
Using only the words lists in a Whisper result, how do you compute the start and end of a caption cue made from several consecutive words?
Show answer
Take start from the first word in the cue and end from the last word in the cue. For example, cue[0]["start"] and cue[-1]["end"].