Sub topic 5
Transcribing a file with the openai-whisper package
This chapter shows how to run the openai-whisper package on an audio file and how to read what it returns. It assumes you can install packages with pip, run commands in a terminal, and read basic Python. You should also know that Whisper turns audio into a log-Mel spectrogram and decodes text from it, as covered in earlier chapters, and that the model sizes trade accuracy for speed and memory.
Installing and checking the setup
The package is published on PyPI as openai-whisper. You import it as whisper. Do not install the unrelated package named whisper, which is a different project and will fail with confusing errors.
Whisper decodes audio files by calling the ffmpeg command-line tool. If ffmpeg is missing, loading any file fails.
pip install -U openai-whisper
ffmpeg -versionIf the second command prints a version, ffmpeg is on your PATH. If not, install it with your system package manager (for example apt install ffmpeg on Debian or Ubuntu, brew install ffmpeg on macOS).
The package depends on PyTorch. On a machine without a GPU it runs on the CPU, which works but is slower. A later chapter covers speed and memory in detail.
The minimal transcription
The smallest useful program loads a model, transcribes a file, and prints the result.
import whisper
model = whisper.load_model("base")
result = model.transcribe("audio.mp3")
print(result["language"])
print(result["text"])Three things happen here.
whisper.load_model("base")downloads the checkpoint on first use and caches it, by default under~/.cache/whisper. Later calls load it from disk. The name selects a model size, such astiny,base,small,medium, orlarge. Names ending in.en(for examplebase.en) are English-only.model.transcribe("audio.mp3")loads the file through ffmpeg, resamples it to 16 kHz mono, builds the log-Mel spectrogram, and decodes text. It handles recordings longer than 30 seconds by moving a window across the audio.- The return value is a Python dictionary.
Because transcribe accepts a path, you do not need to convert files yourself. Any format ffmpeg can read works, including MP3, WAV, M4A, FLAC, and the audio track of a video file.
Reading the result dictionary
transcribe returns a dictionary with three top-level keys.
| Key | Type | Meaning |
|---|---|---|
| `text` | string | The full transcript, with all segments joined. |
| `segments` | list of dictionaries | One entry per decoded chunk of speech, with timing and decoding statistics. |
| `language` | string | The language code used, such as `en`. If you did not set one, this is the detected language. |
Each entry in segments contains these fields, among others.
| Field | Meaning |
|---|---|
| `id` | Position of the segment in the list. |
| `start`, `end` | Start and end time in seconds. |
| `text` | The text of this segment. |
| `tokens` | The token IDs the decoder produced. |
| `temperature` | The sampling temperature that produced this segment. |
| `avg_logprob` | Average log probability of the tokens. Lower values mean less confidence. |
| `compression_ratio` | Ratio of text size to its compressed size. Very high values often indicate repetition. |
| `no_speech_prob` | The model's estimate that the segment contains no speech. |
The last three fields are useful for debugging. They are the same signals Whisper uses internally to decide whether to retry a segment, so you can use them to flag suspect output yourself.
Working with segments
The full text is convenient, but segments let you see where each phrase falls in the audio. The next example fixes the language, asks for word timestamps, disables half precision for CPU use, and prints each segment with its time range.
import whisper
model = whisper.load_model("small")
result = model.transcribe(
"interview.mp3",
language="en",
task="transcribe",
word_timestamps=True,
fp16=False,
)
for segment in result["segments"]:
print(f"[{segment['start']:.2f} -> {segment['end']:.2f}] {segment['text']}")The options in this call do the following.
language="en"skips language detection and forces English. Passing a language removes one source of error and saves a small amount of time. Detection is covered in its own chapter.task="transcribe"is the default. It outputs text in the spoken language. The alternative,"translate", outputs English.word_timestamps=Trueadds awordslist to each segment, with a start and end time per word. It costs extra computation, because Whisper aligns words using cross-attention weights after decoding.fp16=Falsestops Whisper from using 16-bit floating point. On a CPU, fp16 is not supported by the default path, so Whisper warns and falls back to fp32 anyway. Setting it toFalseremoves the warning.
Segment text usually begins with a leading space, because tokens carry their own whitespace. Strip it if you format output yourself.
Translating instead of transcribing
The translate task asks the decoder to emit English regardless of the spoken language.
import whisper
model = whisper.load_model("medium")
result = model.transcribe("spanish_talk.mp3", task="translate")
print(result["text"])Use a multilingual model for this. English-only models (.en) cannot translate. Quality varies by source language and is generally better for languages that were well represented in training.
What happens inside `transcribe`
Knowing the loop explains most of the behavior you will see.
- The file is decoded to a float array at 16 kHz.
- The array is padded and converted to a log-Mel spectrogram.
- If no language was given and the model is multilingual, Whisper detects it from the first 30 seconds.
- A 30-second window is fed to the encoder, and the decoder generates tokens, including timestamp tokens.
- Whisper reads the last timestamp token to decide where the window ends, then moves the window forward from that point. It does not always advance by exactly 30 seconds.
- By default, the text from earlier windows is passed as a prompt to the next window. This keeps spelling and style consistent but can also carry errors forward.
The following diagram summarizes the flow.
The quality check in the diagram is the reason transcribe has several decoding parameters. If a window's compression ratio is too high, or its average log probability is too low, Whisper retries with a higher sampling temperature. The next chapter covers these settings. For now, note that result["segments"][i]["temperature"] tells you whether a retry happened.
Running on a GPU
If PyTorch can see a CUDA GPU, load_model uses it automatically. You can also choose the device explicitly.
import torch
import whisper
device = "cuda" if torch.cuda.is_available() else "cpu"
model = whisper.load_model("small", device=device)
result = model.transcribe("audio.mp3", fp16=(device == "cuda"))
print(result["text"])On a GPU, fp16 roughly halves memory use and speeds up decoding with little change in accuracy. On a CPU, keep it off.
Transcribing several files
Load the model once and reuse it. Loading is the slow part, and repeating it for every file wastes time and memory.
from pathlib import Path
import whisper
model = whisper.load_model("base")
for path in sorted(Path("recordings").glob("*.mp3")):
result = model.transcribe(str(path), fp16=False)
out = path.with_suffix(".txt")
out.write_text(result["text"].strip() + "\n", encoding="utf-8")
print(f"{path.name}: {result['language']}, {len(result['segments'])} segments")The script writes one text file next to each recording and prints the language and segment count. Pass str(path) because older releases expect a string path rather than a Path object.
Using the command line
The package installs a whisper command that wraps the same code. It is handy for quick checks and writes subtitle formats directly.
whisper audio.mp3 --model small --language en --output_format srt --output_dir outSupported output formats include txt, vtt, srt, tsv, and json. The default writes all of them. The json output contains the same structure as the Python result.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| `FileNotFoundError: ... 'ffmpeg'` | ffmpeg is not installed or not on `PATH`. | Install ffmpeg and reopen the terminal. |
| `FP16 is not supported on CPU; using FP32 instead` | Running on CPU with the default `fp16=True`. | Pass `fp16=False`. This is a warning, not a failure. |
| `CUDA out of memory` | The model is too large for the GPU. | Use a smaller model, or run on CPU. |
| Output in the wrong language | Language detection guessed wrong, often on short or noisy clips. | Set `language` explicitly. |
| Transcript of an English file is in another language or script | Same as above, or a `translate` task was set by mistake. | Check `language` and `task`. |
| Very slow on CPU | Large model on a CPU. | Use `base` or `small`, or move to a GPU. |
| Repeated phrases at the end of the text | Hallucination loop on silence or music. | Review `no_speech_prob` and `compression_ratio`; see the limitations chapter. |
Practical guidance
- Start with
baseorsmallto verify your pipeline, then move up in size only if accuracy is not enough. - Set
languagewhenever you know it. It is the cheapest accuracy improvement. - Inspect segments, not only
text. Lowavg_logprobor highno_speech_probpoints to the parts that need review. - Keep one model in memory for the lifetime of the process.
- Treat the transcript as machine output. Names, numbers, and rare terms deserve a human check when it matters.
Exercise
You run model.transcribe("talk.mp3") on a CPU and see the warning "FP16 is not supported on CPU; using FP32 instead". The transcript is correct. What does the warning mean, and how do you remove it? Then name the dictionary key you would read to get the time range of each phrase.
Show answer
The default fp16=True asks for half precision, which the CPU path does not support, so Whisper uses 32-bit floats instead. Results are unaffected. Pass fp16=False to transcribe to silence it. Time ranges are in result["segments"], where each entry has start and end in seconds.
Exercise
Write a short script that loads the small model once, transcribes every .wav file in a folder named clips with the language fixed to English, and prints each file name followed by the number of segments whose no_speech_prob is above 0.6.
Show answer
import whisper from pathlib import Path model = whisper.loadmodel("small") for path in sorted(Path("clips").glob("*.wav")): result = model.transcribe(str(path), language="en", fp16=False) suspect = [s for s in result["segments"] if s["nospeech_prob"] > 0.6] print(path.name, len(suspect))