Wiring Whisper, Celery and S3 into a FastAPI App: From One Upload to a Finished SRT, and Fixing the First Stuck Job
The endpoint streams the file to S3, writes a QUEUED row and sends a transcribe task by name. The worker downloads the file, runs faster-whisper with a model it loads once, uploads the SRT and marks the row COMPLETED while the browser polls. Then the first real job hangs, and numbered logs, Flower and a model baked into the image fix it.
What you will learn
- Follow one upload from the endpoint to S3, a job row, Redis and the worker, and back as an SRT
- Configure the Celery app for long jobs: acks late, prefetch one, track started, time limits
- Fill the .env from Cognito, S3 and IAM without committing a secret
- Find where a stuck task stops with numbered logs and Flower, and bake the Whisper model into the image
Before you start
- Celery and Redis for background tasks
- Private S3 uploads from FastAPI
- Whisper from a Python script
So far the UI lets you drop a video or audio file, and nothing happens with it. There's no Whisper, so nothing turns speech into text. There's no background worker, so a long transcription would hold up the request. And there's no S3 wiring, so the file and its subtitles have nowhere to stay. Three pieces to add, and they have to work as one.
Four decisions before any code
This change touches many files, so it went to an AI agent with one prompt: you're a senior Python backend developer; the app has a UI, a FastAPI backend and Cognito, and nothing for transcription; add Whisper with the model name in .env, run the work as a Celery background task so the UI can follow its progress, and save the file and its subtitles in S3 so the user can sign in later and download them; give a plan first, with a question before each big choice. Four answers shaped everything:
| Choice | Picked | Why |
|---|---|---|
| Whisper package | faster-whisper | Runs on your own machine, CPU or GPU, no outside API |
| Model size | small | A balance of speed and accuracy |
| Job records | SQLite | One local file is enough to start; Postgres or MongoDB later |
| Progress in the UI | HTTP polling every 2 s | Server-sent events and WebSockets add complexity; one progress bar doesn't need them |
The flow
The plan also came with a flowchart.html page: the user uploads a video, it's saved to S3, a worker runs Whisper, the SRT is saved back to S3, the user downloads it. Keep it open beside the code whenever the code feels busy.
The job record
Each upload becomes one row in the projects table:
class ProjectStatus:
PENDING = "PENDING"
QUEUED = "QUEUED"
TRANSCRIBING = "TRANSCRIBING"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
class Project(Base):
__tablename__ = "projects"
id: Mapped[str] = mapped_column(String(36), primary_key=True)
user_sub: Mapped[str] = mapped_column(String(128), index=True, nullable=False)
original_filename: Mapped[str] = mapped_column(String(512), nullable=False)
language: Mapped[str | None] = mapped_column(String(16), nullable=True)
status: Mapped[str] = mapped_column(String(32), default=ProjectStatus.PENDING, nullable=False)
progress: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
error: Mapped[str | None] = mapped_column(Text, nullable=True)
source_key: Mapped[str] = mapped_column(String(1024), nullable=False)
srt_key: Mapped[str | None] = mapped_column(String(1024), nullable=True)
The id is a UUID, and user_sub ties the row to the Cognito user. source_key is where the upload sits in S3; srt_key stays empty until the work is done. The API creates the row, the worker updates it, and the browser reads it through the API.
The upload endpoint
project_id = project_service.new_project_id()
source_key = f"{settings.s3_upload_prefix}{project_id}/{filename}"
try:
s3.upload_fileobj(source_key, file.file, content_type=file.content_type)
except Exception as exc:
raise HTTPException(status_code=502, detail=f"S3 upload failed: {exc}") from exc
project = project_service.create_project(
db,
project_id=project_id,
user_sub=user_sub,
original_filename=filename,
language=lang,
source_key=source_key,
)
project_service.update_status(db, project=project, status=ProjectStatus.QUEUED)
celery_app.send_task("transcribe", args=[project_id], task_id=project_id)
return ProjectCreateResponse(id=project.id, status=project.status)
create_project cleans the file name, makes a project ID and builds the key uploads/<id>/<file>. The key line is send_task. The task is sent by name, so the API never imports the Whisper code. Only the ID goes in the message, so the message in Redis stays tiny, and the project ID doubles as the Celery task ID. The route returns 201 with the ID and QUEUED. The request takes as long as the upload, not the transcription.
The Celery app
celery_app = Celery(
"subly",
broker=settings.celery_broker_url,
backend=settings.celery_result_backend,
include=["app.tasks.transcribe"],
)
celery_app.conf.update(
task_acks_late=True,
worker_prefetch_multiplier=1,
task_track_started=True,
broker_connection_retry_on_startup=True,
task_soft_time_limit=60 * 60, # 1 hour - raises SoftTimeLimitExceeded
task_time_limit=60 * 60 + 60, # +1 minute grace, then SIGKILL
)
Base.metadata.create_all(bind=engine)
- Redis database 0 is the broker and database 1 keeps the results (the Compose defaults are
redis://redis:6379/0and/1). includeregisters the task when the worker starts.task_acks_late: the message is acknowledged only after the task finishes, so if a worker stops mid-job the task isn't lost.worker_prefetch_multiplier=1: a worker takes one job at a time, which suits long transcriptions.- The time limits (added in the debugging round) stop a hung task from holding the worker forever. Retries, backoff and time limits go deeper.
create_allmakes sure the projects table exists when the worker boots.
The task
Here's the heart of tasks/transcribe.py, abridged to the steps, so it won't run as shown (the full file logs each one):
@celery_app.task(name="transcribe", bind=True)
def transcribe(self, project_id: str) -> dict:
db = SessionLocal()
s3 = S3Service()
work_dir: Path | None = None
try:
project = project_service.get_by_id(db, project_id=project_id)
project_service.update_status(db, project=project, status=ProjectStatus.TRANSCRIBING)
project_service.update_progress(db, project=project, progress=0)
work_dir = Path(tempfile.mkdtemp(prefix=f"subly-{project_id}-"))
src_name = Path(project.original_filename).name or "source"
src_path = work_dir / src_name
# _on_chunk (defined here in the full file) logs download progress
s3.download_to_path(project.source_key, str(src_path), callback=_on_chunk)
model = _get_model()
segments, info = model.transcribe(
str(src_path),
language=project.language or None,
vad_filter=True,
)
srt_path = work_dir / (Path(src_name).stem + ".srt")
# write each segment as an SRT block; update progress every 5%
srt_key = f"{settings.s3_subtitle_prefix}{project_id}/{srt_path.name}"
with srt_path.open("rb") as fh:
s3.upload_fileobj(srt_key, fh, content_type="application/x-subrip")
project_service.set_srt_key(db, project=project, srt_key=srt_key)
project_service.update_progress(db, project=project, progress=100)
project_service.update_status(db, project=project, status=ProjectStatus.COMPLETED)
return {"ok": True, "srt_key": srt_key}
except Exception as exc:
# mark the row FAILED with the error text, then re-raise
...
finally:
db.close()
# remove the temp folder
The name transcribe matches what the endpoint sends. _get_model loads the Whisper model only once per worker, with the model, device and compute type from the settings; every task after that reuses it. vad_filter=True is the voice activity filter, which skips the silent parts. The segments are written as SRT blocks just like the script version, and progress is saved about every 5 percent. If anything breaks, the row gets FAILED and the error text.
Where the worker runs
worker:
build:
context: ./backend
container_name: subly-worker
command: celery -A app.celery_app worker -l info --concurrency=1
volumes:
- ./data:/data
- subly-whisper-cache:/root/.cache/huggingface
Same backend image, different command. It shares the data volume with the backend, so both see the same SQLite file. In a first test against a test Redis, with a local folder standing in for the bucket, one short audio file went from QUEUED to TRANSCRIBING after about a second and to COMPLETED after about 21 seconds on the CPU with the small model, or about 8 seconds on the GPU, both including loading the model.
In the full project, docker compose up --build starts the backend, worker and front end next to Redis. But with the AWS keys empty and no bucket created, the upload fails with 502, "S3 upload failed", and with no bucket set at all, earlier with "S3 bucket not configured". The wiring is in place; the values are next.
Filling the .env
Copy sample.env to .env at the project root. Every value has one source:
| Lines | Where the value comes from |
|---|---|
AWS_REGION, COGNITO_USER_POOL_ID, COGNITO_APP_CLIENT_ID, COGNITO_APP_CLIENT_SECRET | The Cognito user pool overview, then app clients and your client |
S3_BUCKET | A bucket you create in S3, unique across AWS, in the same region |
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY | IAM: users, the user the app runs as, create access key, "application running outside AWS". In a company your DevOps team often hands you this key instead |
REDIS_URL, DATABASE_URL | Already point inside Docker: the redis container on port 6379, and a SQLite file on a shared volume |
The comment in the file says the key must be able to put, get and delete objects. The user here had Cognito power user and S3 full access, which is fine for learning; in production, allow only put, get and delete on this one bucket. The secret access key shows only once, so copy it or keep the CSV safe. Never share these keys and never commit them to Git.
Run docker compose up --build from the folder that holds the compose file (from the parent folder it fails because no configuration file is found). Four containers come up: redis, worker, backend and frontend. Open localhost port 3000; upload asks you to sign in first.
The first real upload hangs
The compose file now has a fifth service, Flower, a small web page for Celery on port 5555, built from the same image. Its Workers page shows the worker online with counts of active, processed and failed tasks. Its Tasks page shows each task's name and state: started while it runs, then success or failure. When a job seems stuck, Flower is the first place to look, because it tells you whether the worker has the task at all.
The first upload: sign in, choose an audio file, keep English, upload. The file is in the bucket under uploads, so the API and S3 are fine. The task reaches the worker and Flower shows it as started. And it stays started, while the page keeps showing transcribing. The logs don't say why, because the task wrote only a few lines.
Log every step
So the next prompt asked for better logs: you're a Python backend engineer who knows Celery; the file is in S3, the task is stuck in started in Flower, the logs show no error; log every step of the transcribe task with its step number, plus the download progress; give the changed files only with a short note on what each new line tells us. The task now writes lines like these:
logger.info("[4/9] Flipping status → TRANSCRIBING, progress → 0")
...
logger.info(
"[6/9] S3 download starting: key=%s size=%.2f MB",
project.source_key, size_mb,
)
...
logger.info("[7/9] Loading Whisper model (no-op if pre-warmed)")
model = _get_model()
Step 6 also does a head_object first, so a missing object or a missing permission fails at once with a clear line instead of stalling. Now the log shows the last step that finished: if the last line is step 7, the job is waiting on the model. Follow it with docker compose logs -f worker after docker compose up -d.
It wasn't Redis
The next upload showed as received but didn't start, and the page said queued. A clean start (docker compose down, then deleting the Redis container to clear old task messages) is a fair thing to try, but the job still sat at received. The logs pointed at the model. The worker now loads Whisper when it boots, through a worker_process_init signal, so the first job doesn't wait for a download. But those runtime downloads from Hugging Face kept stalling, so the worker was still busy loading and the task stayed received. The same model file downloaded quickly from a browser, so the network wasn't slow; the way the files were fetched at run time was.
Fetch the model once, at build time
ARG WHISPER_MODEL=tiny
ARG WHISPER_DEVICE=cpu
ARG WHISPER_COMPUTE_TYPE=int8
ENV WHISPER_MODEL=${WHISPER_MODEL} \
WHISPER_DEVICE=${WHISPER_DEVICE} \
WHISPER_COMPUTE_TYPE=${WHISPER_COMPUTE_TYPE} \
WHISPER_MODEL_PATH=/opt/whisper-models/faster-whisper-${WHISPER_MODEL}
...
fetch "${REPO}/config.json" "${OUT}/config.json" yes; \
fetch "${REPO}/tokenizer.json" "${OUT}/tokenizer.json" yes; \
fetch "${REPO}/preprocessor_config.json" "${OUT}/preprocessor_config.json" no; \
fetch "${REPO}/vocabulary.txt" "${OUT}/vocabulary.txt" no; \
fetch "${REPO}/model.bin" "${OUT}/model.bin" yes; \
...
COPY app/whisper_loader.py /opt/whisper_loader.py
RUN echo "===== Verifying model files load cleanly =====" \
&& python /opt/whisper_loader.py --verify-only \
&& echo "===== Model verified ====="
The Dockerfile installs curl next to ffmpeg, and a small fetch function downloads each model file straight from the Hugging Face URL with retries. model.bin, config.json and tokenizer.json are required, so if one fails the build stops. The other two are optional; in this build the preprocessor config came back as not found, and the build went on. Right after, whisper_loader.py --verify-only loads the files with faster-whisper and drops them again, so a broken model.bin fails the build, not the first job. At run time the loader sees WHISPER_MODEL_PATH and loads from that folder; the worker log says LOCAL path, model.bin 72 MB, then model ready.
There's a cost. The build takes longer and the backend image was about 1.8 GB. Change the model size and you rebuild the image. The same idea, with more on image size, is in baking model weights in at build time.
One file in, one SRT out
With the tiny model on the CPU and a local stand-in for the bucket: upload a short clip, the project page shows queued, then transcribing at 0 percent, the bar moves (40 percent here), then completed with a green bar and two buttons, View SRT and Download SRT. The bucket now holds two keys with the project ID, the upload under uploads and the SRT under subtitles. The SRT starts with "In this video, we are starting object oriented programming". Showing the SRT inside the page needs one more S3 setting, in the S3 CORS rule.
Common mistakes
- Importing the task module into the API. Send the task by name.
- Putting the file itself in the message. Pass the ID; the worker reads the row and S3.
- Loading the model inside the task on every run.
- Letting the worker download the model at start in production. Bake it in and verify it at build.
- Giving the app key S3 full access outside a learning account.
Quick recap
- The endpoint stores the file in S3, writes a QUEUED row and sends
transcribeby name. - The worker downloads the file, runs Whisper with a model it loads once, puts the SRT in S3 and marks the row COMPLETED.
- Flower shows whether the worker has the task; numbered logs show where it stopped.
Try it yourself
Run docker compose logs -f worker, upload a file, and match each numbered line to its step in transcribe.py.
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.
