Sub topic 2
Transcribing a file with the openai-whisper package
This chapter assumes you know basic Python, can install packages with pip, and have ffmpeg installed so Whisper can decode MP3 and WAV files.
Transcribing a file
Load a model once, then pass it a file path. The result is a dictionary with the detected language, the full text, and a list of segments.
import whisper
model = whisper.load_model("base")
result = model.transcribe("audio.mp3")
print(result["language"])
print(result["text"])On a CPU, Whisper prints a warning that fp16 is not supported and falls back to fp32. This warning is harmless.
Tuning decoding
Extra keyword arguments to transcribe() go to the decoder. The options you will use most are:
language: a code such as"en"or"fr". Setting it skips detection.beam_size: the number of candidate paths kept during search. Larger values often improve accuracy and cost more time.temperature: a value or a tuple. Whisper retries a window at the next temperature when output looks repetitive or low-confidence.initial_prompt: text that biases spelling and vocabulary, such as names or technical terms.
import whisper
model = whisper.load_model("small")
result = model.transcribe(
"interview.mp3",
language="en",
beam_size=5,
temperature=(0.0, 0.2, 0.4),
initial_prompt="Interview about solar panels. Terms: photovoltaic, inverter.",
)
for seg in result["segments"]:
print(f"[{seg['start']:.2f} -> {seg['end']:.2f}] {seg['text']}")Language detection and translation
Whisper detects the language from the first 30 seconds. Detection can fail on short clips, noisy audio, or mixed-language speech, so set language when you know it.
With task="translate", Whisper outputs English text from speech in another language:
result = model.transcribe("spanish_talk.mp3", task="translate")
print(result["text"])Transcribing long recordings
Whisper processes audio in 30-second windows. For a long file, transcribe() slides the window forward and joins the results, so you do not split the file yourself. Each segment keeps its own start and end times.
Exercise
You set temperature=0.0 alone and the output loops on the same phrase. Which argument change gives Whisper a fallback path, and why does it help?
Show answer
Pass a tuple such as temperature=(0.0, 0.2, 0.4). When a window fails the repetition or confidence checks, Whisper retries it at the next, higher temperature.