Sub topic 14
Using Whisper through the transformers pipeline
This chapter shows how to run Whisper through the Hugging Face transformers library instead of the openai-whisper package. You need to know the basics from earlier chapters: how Whisper handles 30-second windows, what the model sizes are, and what the language and task options do. You also need working Python, pip, and some comfort reading PyTorch-style code.
Why use the pipeline
The openai-whisper package is the reference implementation. The transformers library hosts the same weights, converted to its own format, under names like openai/whisper-small. Using them through transformers has three practical benefits:
- You use the same
pipeline(...)interface as other Hugging Face models, so Whisper fits into code that already uses that library. - Checkpoints download from the Hugging Face Hub and are cached locally. Fine-tuned Whisper variants on the Hub load the same way.
- Batching, half precision, and device placement are controlled through familiar arguments.
Install the dependencies first. The file-path examples decode audio with ffmpeg, so it must be installed on your system.
pip install transformers torch accelerateWhat the pipeline does for you
The automatic-speech-recognition pipeline bundles three steps: it loads and resamples audio, converts it to a log-Mel spectrogram with a feature extractor, and runs the encoder-decoder model with a tokenizer to produce text. This is the same processing described earlier, wrapped in one call.
A first transcription
This example picks the device and numeric precision from what is available. Half precision (float16) is a good default on a GPU but is slow or unsupported for some operations on CPU, so the code uses float32 there.
import torch
from transformers import pipeline
device = "cuda:0" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if torch.cuda.is_available() else torch.float32
asr = pipeline(
"automatic-speech-recognition",
model="openai/whisper-small",
torch_dtype=dtype,
device=device,
chunk_length_s=30,
)
result = asr("audio.mp3")
print(result["text"])The result is a dictionary. Without timestamps it has a single key, text. Unlike openai-whisper, it does not report the detected language in the result.
Long audio: chunking
Whisper's encoder sees 30 seconds at a time. For longer files the pipeline needs a strategy, and by default it has none. Pass chunk_length_s=30 to turn on chunked decoding:
- The audio is cut into 30-second chunks.
- Neighboring chunks overlap. The overlap is set by
stride_length_s, which defaults to one sixth of the chunk length on each side, so 5 seconds. - Each chunk is transcribed independently, which allows batching.
- The pipeline merges the chunk outputs and uses the overlapping regions to line up the text and remove duplicates.
Because chunks are decoded independently, the model has no text context from the previous chunk. Words that fall on a chunk boundary are the usual place for errors, and the overlap exists to reduce them. The sequential method in openai-whisper feeds earlier text forward and moves the window using timestamps, so it can be more accurate on long speech, though it cannot be batched in the same way. The chunked method is faster on a GPU.
You can raise throughput on a GPU with batch_size, which sets how many chunks are decoded together:
result = asr("long_lecture.mp3", batch_size=8)
print(result["text"])A larger batch uses more GPU memory. If you get an out-of-memory error, lower it.
Timestamps
Set return_timestamps=True to get segment-level timestamps. The result gains a chunks list. Each item has text and a timestamp tuple of (start, end) in seconds.
result = asr("interview.mp3", return_timestamps=True)
for chunk in result["chunks"]:
start, end = chunk["timestamp"]
print(f"[{start} -> {end}] {chunk['text']}")For word-level timing, pass the string "word":
result = asr("interview.mp3", return_timestamps="word")
for word in result["chunks"]:
start, end = word["timestamp"]
print(f"{start:>6} {end:>6} {word['text']}")Two details to watch:
- The
endvalue of the final segment can beNonewhen the audio ends mid-segment. Handle that before formatting it as a number, orf"{end:.2f}"will fail. - Word timestamps come from cross-attention patterns in the model, so they are estimates. They are usually close but can drift on fast or overlapping speech.
Language and task options
The pipeline does not take language and task directly. Pass them through generate_kwargs, which is forwarded to the model's generate method. The same dictionary can carry decoding settings such as num_beams.
from transformers import pipeline
asr = pipeline(
"automatic-speech-recognition",
model="openai/whisper-small",
chunk_length_s=30,
)
# Fixed language, plain transcription.
result = asr(
"interview.mp3",
generate_kwargs={"language": "english", "task": "transcribe", "num_beams": 5},
)
print(result["text"])
# Translate non-English speech to English.
result = asr(
"spanish_talk.mp3",
generate_kwargs={"language": "spanish", "task": "translate"},
)
print(result["text"])If you leave language out, the model detects it. Fixing the language is worth doing when you know it, because a wrong detection on a short or noisy opening can make the model transcribe in the wrong language or translate by accident.
Passing audio that is already in memory
You do not have to use a file path. If you already have a NumPy array, for example from a microphone buffer or another library, pass a dictionary that states the sampling rate. The pipeline resamples it to 16 kHz if needed.
import numpy as np
from transformers import pipeline
asr = pipeline("automatic-speech-recognition", model="openai/whisper-tiny")
# One second of silence at 16 kHz, as a stand-in for real samples.
samples = np.zeros(16000, dtype=np.float32)
result = asr({"raw": samples, "sampling_rate": 16000})
print(repr(result["text"]))If you pass a bare array with no sampling rate, the pipeline assumes it is already at the model's rate of 16 kHz. Audio at another rate then plays back too fast or too slow from the model's point of view, and accuracy drops. Always include sampling_rate.
Comparing with openai-whisper and faster-whisper
| Aspect | `openai-whisper` | `transformers` pipeline | `faster-whisper` |
|---|---|---|---|
| Weights source | OpenAI download | Hugging Face Hub | Converted CTranslate2 models |
| Long audio | Sequential windows with context | Overlapping chunks, batchable | Sequential, with optional voice activity filter |
| Language in result | Yes | No | Yes, with probability |
| Options | Arguments to `transcribe` | `generate_kwargs` | Arguments to `transcribe` |
| Fine-tuned models | Manual conversion | Load directly from the Hub | Needs conversion |
Choose the pipeline when you already work in the Hugging Face ecosystem, need a fine-tuned Hub checkpoint, or want batched GPU throughput. Choose faster-whisper for the fastest CPU or low-memory inference. Choose openai-whisper when you want the reference long-form behavior.
Common errors
- No
ffmpeg. Loading a file path fails with a message aboutffmpeg. Install it, or load the audio yourself and pass an array. - Long audio returns only the start. Without
chunk_length_s, the model only handles the first 30 seconds of input. Add the argument. - Out of memory. Use a smaller model, lower
batch_size, or usefloat16on a GPU. - Repeated or invented text on silence. This is the same hallucination behavior described in the limitations chapter. Trim long silences before transcribing.
Noneend timestamp. Check for it before formatting.
Exercise
You transcribe a 45-minute meeting with asr("meeting.mp3") using openai/whisper-small and get only about 30 seconds of text. You then need segment timestamps and English output, and the meeting is in German. Which arguments do you change or add to the pipeline call, and why?
Show answer
Add chunk_length_s=30 to the pipeline (or the call), because without it only the first 30-second window is transcribed. Add return_timestamps=True to get a chunks list with (start, end) tuples. Pass generate_kwargs={"language": "german", "task": "translate"} to produce English from German speech. You can also add batch_size on a GPU to speed up the many chunks. The model must be multilingual, so openai/whisper-small works but openai/whisper-small.en would not.