Sub topic 14
Using Whisper through the Transformers Pipeline
This chapter assumes you know basic Python, can install packages with pip, and understand that automatic speech recognition (ASR) converts spoken audio into text. You should also know how to work with files such as WAV and MP3.
The Hugging Face transformers library provides a pipeline interface for common machine-learning tasks. Its automatic speech recognition pipeline loads a Whisper checkpoint, prepares the audio, runs the model, and returns text in a Python dictionary. This is convenient when you want a standard interface instead of calling the openai-whisper package directly.
Install the required packages
Install Transformers and an audio backend:
pip install transformers torch librosaYour system also needs FFmpeg when you pass an MP3 or another compressed format. FFmpeg decodes the file so that Python can read its audio samples.
For example, on Debian or Ubuntu:
sudo apt update
sudo apt install ffmpegThe first use of a checkpoint downloads its model files. Later runs reuse the local cache.
Create an ASR pipeline
The pipeline task name is "automatic-speech-recognition". The model name selects a Whisper checkpoint from the Hugging Face Hub.
from transformers import pipeline
asr = pipeline(
"automatic-speech-recognition",
model="openai/whisper-small",
chunk_length_s=30,
)
result = asr("audio.mp3")
print(result["text"])chunk_length_s=30 tells the pipeline to process long input in approximately 30-second chunks. Whisper was trained around 30-second audio windows, so chunking helps the pipeline handle recordings longer than one window.
The returned dictionary normally contains a text key. When timestamps are requested, it also contains timestamp information.
from transformers import pipeline
asr = pipeline(
"automatic-speech-recognition",
model="openai/whisper-small",
chunk_length_s=30,
)
result = asr("audio.mp3", return_timestamps=True)
print(result["text"])
for chunk in result["chunks"]:
start, end = chunk["timestamp"]
print(f"[{start:.2f} -> {end:.2f}] {chunk['text'].strip()}")The exact timestamp boundaries are estimates. A chunk may contain several words, and boundaries can be less precise around pauses, overlapping speech, or background noise.
Choose a model and device
Whisper checkpoints trade speed and accuracy for memory use. A smaller checkpoint is easier to run on a CPU. A larger checkpoint can recognize difficult speech more accurately, but it needs more memory and takes longer.
| Checkpoint | Typical choice |
|---|---|
| `openai/whisper-tiny` | Fast experiments and low-resource systems |
| `openai/whisper-base` | Small general-purpose workload |
| `openai/whisper-small` | Better accuracy with moderate resource use |
| `openai/whisper-medium` | Higher accuracy with more memory and time |
You can place the pipeline on a CUDA GPU by setting device=0. CPU execution uses device=-1.
from transformers import pipeline
asr = pipeline(
"automatic-speech-recognition",
model="openai/whisper-small",
device=-1,
chunk_length_s=30,
)Use device=0 only when PyTorch can access a CUDA-compatible GPU. Otherwise, pipeline construction or inference may fail.
Pass language and task information
Whisper can detect a language, but detection can be wrong for short clips or noisy recordings. Supplying the language makes decoding more predictable. The language value is usually a language code such as "en" or "es".
The generate_kwargs argument passes Whisper generation settings to the model:
from transformers import pipeline
asr = pipeline(
"automatic-speech-recognition",
model="openai/whisper-small",
chunk_length_s=30,
)
result = asr(
"interview.mp3",
return_timestamps=True,
generate_kwargs={
"language": "english",
"task": "transcribe",
},
)
print(result["text"])Use "transcribe" to keep the spoken language. Use "translate" to produce English text from supported non-English speech.
Exercise
Which pipeline option helps the Transformers interface process a recording longer than Whisper's usual 30-second window?
Show answer
Set chunklengths=30, then request the pipeline to process the complete file.