Whisper from a Python Script: Turn Audio into an SRT Subtitle File, and Pick a Model Size
Whisper is OpenAI's open speech recognition model: audio in, timed text out. Meet its sizes and languages, then run it from one script that reads an input folder, makes sure ffmpeg is there, loads the model once into a cache and writes an SRT per file. Base took 3.4 s on a 12.5 s clip; large-v3 took 24.3 s.
What you will learn
- Describe what Whisper does, its sizes and languages, and where it can run
- Run Whisper on a folder of media files and write one SRT per file
- Read the segments transcribe returns and how they become SRT blocks
- Compare base and large-v3 on time and quality, and see why the web app needs a worker
Before you start
- Basic Python
- Installing packages in a virtual environment
Whisper is the model that turns speech into text for the subtitle generator. You give it audio, or a video with sound in it. It works out what's being said and gives back text in small pieces, each with a start time and an end time. That's exactly what a subtitle file needs: the words, and when to show them. It also copes well with accents, background noise and music.
Before it goes inside the web app, it runs on its own as a plain script, so every step is visible with nothing else around it.
Whisper in one minute
Whisper is built by OpenAI and it's an open model, so you can download it and run it on your own machine. The first release was trained on about 680,000 hours of audio, roughly 78 years of non-stop listening.
- Sizes: tiny, base, small, medium and large (large-v2, large-v3), plus turbo. The smaller ones also come English-only, with
.enat the end, liketiny.en. A small model loads fast and needs less memory; a large one is slower but more accurate. You can build the whole app with tiny, then change one setting to medium or large-v3 for better subtitles. - Languages: 99. Its normal job is to transcribe, so French audio gives French text. It can also translate, but translation always goes into English. Languages with lots of training data, like English and Spanish, come out best.
- Where it runs: your own laptop or desktop (CPU works, a graphics card is much faster), a GPU server you rent in the cloud, or OpenAI's API. The model costs nothing to download; the machine that runs it is what costs money.
- Python packages:
openai-whisper(the original),faster-whisper(same models, faster, less memory) andwhisper.cpp(a C++ version that runs well without a big graphics card). This script usesopenai-whisper; the web app later uses faster-whisper.
The plan
The script came from an AI chat with a four-part prompt. Role: act like a senior Python developer. Context: an input folder and an output folder, using Whisper. Task: make an SRT for every audio and video file in input, keep the model in a cache folder, and list the model names in a comment so you can switch with one line. Format: one Python file plus a requirements file.
Set it up
openai-whisper>=20231117
torch>=2.0.0
imageio-ffmpeg>=0.5.0
Make a virtual environment with uv venv and install the requirements. One thing to watch on Windows: the requirements file alone installs the CPU build of torch. To use the GPU, install the CUDA build; here that was torch 2.11 with CUDA 12.8. Skip it and Whisper still works, only on the CPU and a lot slower.
Read the script
import whisper
from whisper.utils import get_writer
# Available models: tiny, base, small, medium, large, large-v2, large-v3, turbo
# Use base or small on CPU; large-v3 when you have a GPU.
MODEL_NAME = "base"
INPUT_DIR = Path("input")
OUTPUT_DIR = Path("output")
CACHE_DIR = Path("cache")
MODEL_NAME is the one line you change to switch models. A set of fifteen extensions follows (mp4, mkv, mov and others for video; mp3, wav, m4a and others for audio). A file with one of these endings gets transcribed, anything else is skipped.
ffmpeg first
def ensure_ffmpeg(base_dir: Path) -> None:
"""Make ffmpeg available for Whisper (system PATH or bundled copy)."""
if shutil.which("ffmpeg"):
return
try:
import imageio_ffmpeg
except ImportError:
print(
"ffmpeg not found. Install it from https://ffmpeg.org/ "
"or run: pip install imageio-ffmpeg",
file=sys.stderr,
)
sys.exit(1)
ffmpeg_src = Path(imageio_ffmpeg.get_ffmpeg_exe())
bin_dir = base_dir / CACHE_DIR / "bin"
bin_dir.mkdir(parents=True, exist_ok=True)
ffmpeg_exe = bin_dir / ("ffmpeg.exe" if os.name == "nt" else "ffmpeg")
if not ffmpeg_exe.exists():
shutil.copy2(ffmpeg_src, ffmpeg_exe)
os.environ["PATH"] = str(bin_dir) + os.pathsep + os.environ.get("PATH", "")
Whisper doesn't read audio files by itself; it calls a tool named ffmpeg to decode them. If ffmpeg isn't on your PATH, Windows stops with a file not found error, a common first problem. So this checks with shutil.which, and if ffmpeg is missing it copies the one that comes with imageio-ffmpeg into cache/bin and adds that folder to the PATH for this run only.
Load once, transcribe each file
print(f"Loading Whisper model '{MODEL_NAME}' (cache: {cache_dir})...")
model = whisper.load_model(MODEL_NAME, download_root=str(cache_dir))
srt_writer = get_writer("srt", str(output_dir))
for media_path in media_files:
print(f"Transcribing: {media_path.name}")
result = model.transcribe(str(media_path))
srt_writer(result, str(media_path))
srt_path = output_dir / f"{media_path.stem}.srt"
print(f" Saved: {srt_path}")
print(f"Done. {len(media_files)} subtitle file(s) in {output_dir}")
download_root set to the cache folder means the model downloads once and stays inside the project. get_writer("srt", ...) gives a function that writes SRT files into output.
Run it
Put take 05.mp3, about 12.5 seconds of speech, into input and run python transcribe.py. On the first run the model downloads: base.pt, about 139 MB, which took 43 seconds here. After that it loads from the cache in about 3 seconds. It ran on cuda:0, the GPU, and the transcribe step took 3.4 seconds. Then "Saved" with the path to take 05.srt, and "Done" with one subtitle file.
What transcribe returns
A dictionary with three keys. language came back as en, so Whisper worked out by itself that this is English. text is the whole transcript in one string. segments is a list; each segment has a start time, an end time and its text, with a few scores you don't need here. This clip gave two segments, 0 to 5.48 seconds and 5.48 to 10.64 seconds. The SRT writer turns each segment into a numbered block with the times in hours, minutes, seconds and milliseconds:
1
00:00:00,000 --> 00:00:05,480
Hey there, my name is Chand and in this video we will discuss about how exactly you can
2
00:00:05,480 --> 00:00:10,640
create your first school using Dubnext and the experience will be wonderful.
Most video players can load this file next to the video and show the words at the right moment.
base vs large-v3
Change one line: MODEL_NAME = "large-v3". This model file is about 3 GB, so the first download takes a while, and it needs more GPU memory.
| base | large-v3 | |
|---|---|---|
| Model file | about 139 MB | about 3 GB |
| Transcribe time, same 12.5 s clip, GPU | 3.4 s | 24.3 s |
| Segments | 2 | 3 |
| The name "Dubnext" | one word | "dub next", two words |
Rare names are where any model can slip, so read your subtitles once before you share them. Base is fine while you build. A bigger model is the choice when quality matters more than time.
Why the web app can't do this inside a request
A short file took seconds, but a long video with a big model can take minutes. In a web app that work can't sit inside one request: the request would time out, and the server would stay busy the whole time. So in the app the job goes to a background worker, set up in Celery and Redis for background tasks.
Common mistakes
- "File not found" on Windows: ffmpeg isn't on the PATH. That's what
ensure_ffmpeghandles. - Installing torch from the plain requirements file and wondering why it's slow. Install the CUDA build for the GPU.
- Expecting translate mode to give, say, French from English audio. It only translates into English.
Quick recap
- Whisper: audio in, timed segments out, in sizes from tiny to large.
- The script reads every media file in input, makes sure ffmpeg is there, loads the model once into cache, and writes an SRT per file.
MODEL_NAMEis the one line that trades speed for accuracy.
Try it yourself
Record half a minute of your own voice, put it in input, run the script with base, then with small, and compare the two files.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
