Sub topic 7
Language detection and translating speech to English
This chapter covers how Whisper decides which language is being spoken and how it produces English text from non-English speech. It assumes you can already run model.transcribe() from the openai-whisper package and read the result dictionary. It also assumes you know that Whisper processes audio in 30-second windows and that it has multilingual and English-only model variants.
How the language is chosen
Whisper is a single decoder that handles many languages and two tasks. It is steered by special tokens placed at the start of the decoder's input. A typical prompt looks like this:
<|startoftranscript|>- A language token such as
<|es|>or<|ja|> - A task token, either
<|transcribe|>or<|translate|> - Optionally
<|notimestamps|>, which switches off timestamp tokens
The language token is predicted by the model itself. If you do not set language, the decoder runs one step after <|startoftranscript|>. The probabilities over the language tokens (about 99 of them in multilingual models) are the language detection result. The most probable token is then used for the rest of decoding. Detection therefore costs one extra decoder step. It is not a separate classifier.
In model.transcribe(), detection runs on the first 30-second window only. The detected language is then reused for every later window of that file.
import whisper
model = whisper.load_model("base")
result = model.transcribe("audio.mp3")
print(result["language"])
print(result["text"])result["language"] holds a short code such as "en", "es" or "de". Even when you pass language yourself, this key reports the language that was used.
Detecting the language directly
Use detection on its own when you want to route files, log the language, or reject uncertain files before spending time on a full transcription. The lower-level API takes a log-Mel spectrogram of exactly 30 seconds.
import whisper
model = whisper.load_model("small")
audio = whisper.load_audio("clip.mp3")
audio = whisper.pad_or_trim(audio)
mel = whisper.log_mel_spectrogram(audio, n_mels=model.dims.n_mels).to(model.device)
_, probs = model.detect_language(mel)
ranked = sorted(probs.items(), key=lambda item: item[1], reverse=True)
for code, probability in ranked[:5]:
print(f"{code}: {probability:.3f}")probs is a dictionary that maps language codes to probabilities and sums to about 1. Three details matter here:
pad_or_trimcuts the audio to 30 seconds or pads it with silence. A short clip padded with a lot of silence gives a weaker signal.n_mels=model.dims.n_melsmatters because large-v3 uses 128 mel bins while the earlier models use 80. A mismatch raises a shape error..enmodels always return English. Detection is meaningless for them.
Reading the probabilities
Treat the top probability as a confidence signal. A clean 30-second speech clip often gives a top probability above 0.9. A value around 0.5 usually means one of three things:
- the clip is short or noisy
- the audio contains mixed languages
- two languages are closely related
The second-ranked language is often informative. Spanish and Galician, or Norwegian and Danish, can compete for the top spot.
Forcing the language
If you know the language, set it. This removes the detection step and removes one source of error.
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']}")Setting language is not free of side effects. The language token is a strong instruction. If you force language="en" on Spanish audio with the transcribe task, the model tends to produce a rough English rendering, or a mix, instead of Spanish text. Force a language only when you are sure of it.
The language argument accepts either the code ("es") or the English name ("spanish"). Codes are less error-prone.
Translating speech to English
The translate task takes speech in any supported language and outputs English text. It is a single-step speech-to-text translation, not transcription followed by machine translation.
import whisper
model = whisper.load_model("medium")
result = model.transcribe("spanish_talk.mp3", task="translate")
print(result["text"])When task="translate" is set and language is not, detection still runs first, so the model knows the source language. The result["language"] value is the source language, not "en".
What translation cannot do
- The only target language is English. Whisper cannot translate Spanish into French. For that, transcribe first and pass the text to a text translation model.
- English-only models (
tiny.en,base.en,small.en,medium.en) do not translate. Use a multilingual checkpoint. - The
turbovariant of large-v3 was fine-tuned for transcription and is not recommended for translation. Usemediumorlargefor that task. - If the audio is already English,
translateandtranscribegive nearly the same output.
Quality expectations
Translation quality tracks model size and how much training data existed for the source language. The training set contained far more English speech than any other language. Whisper translates well from high-resource languages such as Spanish, German, French and Portuguese. It is much weaker for low-resource languages, where it may drop content, summarize, or invent fluent but wrong English. Larger models help, and the gap between tiny and medium on translation is large.
A practical habit is to run both tasks on a sample and compare:
import whisper
model = whisper.load_model("medium")
original = model.transcribe("spanish_talk.mp3", language="es", task="transcribe")
english = model.transcribe("spanish_talk.mp3", language="es", task="translate")
print("SOURCE :", original["text"][:200])
print("ENGLISH:", english["text"][:200])Reading the source text next to the English output lets you spot omissions. Passing language="es" in both calls keeps the comparison fair.
Common errors and how to handle them
| Symptom | Likely cause | Fix |
|---|---|---|
| Wrong language for the whole file | The first 30 seconds were music, silence, or another language | Set `language`, or trim the intro, or detect on a speech-heavy window |
| Output in English for non-English audio when you wanted the original | `task="translate"` was set, or `language="en"` was forced | Use `task="transcribe"` and the correct `language` |
| Later parts of the file are garbled | The file switches language partway through, but one language was applied to all windows | Split the file at the switch and transcribe each part with its own language |
| Translation returns the source language | An English-only model, or audio that is mostly English | Use a multilingual model and check `result["language"]` |
| Shape error in `detect_language` | Wrong number of mel bins | Pass `n_mels=model.dims.n_mels` |
| Unstable results on very short clips | Little speech to base the language on | Force `language`, or accept lower confidence |
Code-switching and mixed audio
Whisper picks one language per file in transcribe(). Speakers who switch languages mid-sentence are handled unevenly. The model may transcribe the second language phonetically in the first language's spelling, or translate it silently. There is no option that makes the openai-whisper transcribe() function re-detect per window. If you need that, split the audio yourself, detect on each piece, and call transcribe() per piece.
A confidence guard
A simple guard avoids silent mistakes in pipelines. Detect first, and fall back to a human or a default language when confidence is low.
import whisper
model = whisper.load_model("small")
def detect(path: str, threshold: float = 0.6):
audio = whisper.pad_or_trim(whisper.load_audio(path))
mel = whisper.log_mel_spectrogram(audio, n_mels=model.dims.n_mels).to(model.device)
_, probs = model.detect_language(mel)
code = max(probs, key=probs.get)
return code, probs[code], probs[code] >= threshold
code, confidence, ok = detect("clip.mp3")
print(code, round(confidence, 3), "accepted" if ok else "needs review")The threshold of 0.6 is a starting point. Tune it on a few labeled files from your own audio.
Detection in other runtimes
faster-whisper exposes the same information on the info object. It detects on the first 30 seconds by default. The language_probability value is the top probability.
from faster_whisper import WhisperModel
model = WhisperModel("small", device="cpu", compute_type="int8")
segments, info = model.transcribe("audio.mp3", task="translate", beam_size=5)
print(info.language, info.language_probability)
text = " ".join(segment.text.strip() for segment in segments)
print(text)The Hugging Face pipeline accepts the language and task through generate_kwargs, for example generate_kwargs={"language": "es", "task": "translate"}.
Summary of the decisions
- To keep the original language, use
task="transcribe"and setlanguageif you know it. - To get English text from foreign speech, use a multilingual
mediumorlargemodel withtask="translate". - To translate into any language other than English, transcribe first and use a separate translation tool.
- To handle files with several languages, split the audio and process each part separately.
Exercise
A 40-minute podcast starts with 45 seconds of English intro music and an English announcer, then continues in German. You call model.transcribe("show.mp3") with no options and the German part comes out as broken English-like text. Explain why this happens and give two ways to fix it.
Show answer
Language detection runs only on the first 30-second window, which here is English intro. The detected language, English, is then applied to every later window, so the German speech is decoded under an English language token. Fixes: (1) pass language="de" so the correct token is used for the whole file. (2) Cut off or skip the intro, for example by splitting the audio at about 45 seconds, then let detection run on the German section. Detecting on a speech-heavy 30-second slice with detect_language and passing the result as language also works.
Exercise
You need French speech turned into German text. Can you do it with task="translate" alone? What would you do instead?
Show answer
No. Whisper's translate task only outputs English. Transcribe the audio with task="transcribe" and language="fr" to get French text, then pass that text to a separate text translation model or service that supports French to German. Alternatively, translate to English with Whisper and then from English to German, but this adds a second error source.