Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Machine Learning
  • Supervised Learning: Features, Labels, Classification and Regression
  • NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
  • NumPy Arrays: Creation, Shape and Data Types From Scratch
  • NumPy Indexing, Slicing, Masks and np.where
  • NumPy Shapes: reshape, transpose, stack, concatenate and split
  • NumPy Universal Functions and Broadcasting, With the Shape Rule
  • NumPy Aggregation, Statistics and Sorting: sum, axis, percentile, argsort
  • Linear Algebra with NumPy: Dot Product, @, Determinant, Inverse and solve
  • Random Numbers in NumPy: default_rng, Seeds, Distributions and Sampling
  • Thinking in Arrays: A NumPy Student Performance Analysis
  • An Image Is a NumPy Array: Channels, Brightness, Grayscale, Invert and Crop
  • pandas Series and DataFrames: Your First Table, Inspected and Sorted
  • pandas Data IO: read_csv, to_csv, JSON, Excel and Parquet
  • pandas loc, iloc and Filtering: Label vs Position, Masks, query
  • Cleaning Messy Data in pandas: Missing Values, Duplicates, Types and Text
  • pandas groupby and merge: Split-Apply-Combine and Joining Tables
  • pandas Practice: Student Grades, Sales and an Employee Cleanup
  • First Look at a Dataset: 6 Checks Before You Plot or Model
  • Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  • Scatter Plots and Pair Plots: See How Two Columns Relate
  • Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  • Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  • Train-Test Split and Data Leakage: Split First, Learn After
  • Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
  • Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
  • Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
  • Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
  • Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
  • Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
    Regression
    • Linear Regression and the Cost Function: Draw a Line, Score It
    • Gradient Descent Explained: Feel the Slope, Step Downhill
    • Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
    • Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
    • Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
    • Regularisation with Ridge and Lasso: Put a Price on Big Weights
    Classification and Evaluation
    • Logistic Regression and the Sigmoid: Score, Squash, Decide
    • Logistic Regression in scikit-learn: predict, predict_proba and Softmax
    • Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
    • Precision, Recall and F1 Score: Two Questions and One Balance
    • ROC Curve, AUC and Choosing a Classification Threshold
    • Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
    • Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
    Classic Algorithms
    • K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
    • Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
    • Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
    • Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
    • Bagging and Random Forest: Many Shaky Trees, One Steady Answer
    • Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
    • Voting and Stacking: Does a Team of Models Beat the Best One?
    Model Selection and Tuning
    • Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
    • Which Features Matter? Feature Importances, Permutation Importance and SHAP
    • Project: The Classification Master Template, from Raw CSV to a Saved Model
    • K-Means Clustering: Find Groups in Data With No Labels
    • Choosing k for K-Means: the Elbow Method and the Silhouette Score
    • Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
    • Dimensionality Reduction with PCA: 13 Columns Down to 2
    • Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
    • Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
    • Bag of Words with CountVectorizer: Turn Text into Word Counts
    • TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
    • Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
    • Why Neural Networks: Pixels, One Neuron and Layers
    • The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
    • Loss and Backpropagation: How Wrong, and Who Is to Blame
    • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
    • Your First Neural Network with Keras: MNIST Digits at 97.7%
    • The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
    • Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
    • Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
    • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
    • Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
    • Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
    • Attention Explained Without the Maths: Query, Key, Value and the Word "it"
    • Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
    • Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
    • Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
    • Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
    • Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
    • When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
    • Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
    • LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
    • Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
    • Serving Open Models: Continuous Batching, vLLM and Cold Starts
      Engineering Basics
      • Python Virtual Environments: One Project, One Toolbox
      • Git and GitHub Fundamentals: Commits, Branches, Push and Pull
      • Testing a FastAPI App with pytest: Three Small Tests
      • Config and Logging Instead of Hard-Coded Values in ML Training
      • SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
      Data and Features in Production
      • Time Splits and Group Splits: Make the Split Match How the Model Is Used
      • Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
      • Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
      • Point-in-Time Correctness: Join Features as of Each Event with merge_asof
      • Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
      • Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
      • Feature Stores: Offline and Online Stores, and When You Actually Need One
      • Data Versioning with DVC: Tie Every Model to the Exact Data That Trained It
      Experiments and Model Quality
      • MLOps in One Picture: Code, Data, Model and the Lifecycle Loop
      • Experiment Tracking with MLflow: Log Params, Metrics and the Model, Then Compare Runs
      • MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      • The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
      • Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      • Slice Evaluation and Fairness Checks: Score the Model Group by Group
      Serving Models
      • Saving and Loading Models with joblib: One Pipeline, One File
      • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
      • Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
      • Docker Essentials for ML: Images, Containers and Volumes with a Model API
      • Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
      • Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
      • A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
      • Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
      • Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
      • Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
      • Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
      • Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
      • Docker Compose: Run a FastAPI App and Postgres From One File
      • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
      Pipelines, CI/CD and Cloud
      • The Training Pipeline as a DAG: Steps, Files, Retries and a Safe Rerun
      • Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
      • Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
      • CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
      • CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
      • Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
      • IaaS, PaaS, Containers or Serverless? Choosing Where a Model API Runs
      • Kubernetes at a High Level: Pods, a Deployment and a Service for a Model API
      • Managed ML Platforms: What SageMaker, Vertex AI and Azure ML Give You, and Tie You To
      • Deploying a Model API to AWS: ECR, Secrets Manager, CloudWatch and Fargate, Then Teardown
      • Cloud Cost Thinking for ML: Size x Count x Hours x Rate, and Three Decisions Worth Ten Times
      • Private S3 Uploads from FastAPI: A Locked Bucket, a Key per User, and Presigned Links That Expire
      • Whisper from a Python Script: Turn Audio into an SRT Subtitle File, and Pick a Model Size
      • Celery and Redis for Background Tasks: Answer 202, Hand the Job to a Worker, and Poll for the Result
      • Wiring Whisper, Celery and S3 into a FastAPI App: From One Upload to a Finished SRT, and Fixing the First Stuck Job
      • The S3 CORS Rule: Why the Browser Blocks a Presigned Link, and the Four Lines That Let Your Page Read the File
      • Running a Docker Compose App on One EC2 Instance: Launch the Server, Start the Stack, and the Three Settings That Decide If It Works
      • From One Hand-Built EC2 Box to Containers, Terraform and Autoscaling: What Each Fix Replaces
      • Safe to Run Twice: Why a Celery Job Comes Back, and a Status Check, a Leased Lock and a Failed-Jobs Table That Keep It Calm
      • Scheduled Jobs with Celery Beat: Interval or Crontab, a Stuck-Job Sweep, and Why You Run Exactly One Beat
      • Celery Pipelines with chain, group and chord: Transcribe, Translate in Parallel, Bundle, and Handle a Failed Branch
      • Job Progress: Polling vs Server-Sent Events, with Redis Pub/Sub and a Reconnect That Doesn't Lose the Bar
      • Watching Celery Workers: What Flower Sees, Queue Depth and the Oldest Job's Age from Redis, a Request ID and One Trace
      • Durable Workflows: What a Celery Chain Survives, How Temporal Replays From History, and What Prefect Promises Instead
      • Terraform Modules, Remote State and Environments: One Codebase for Staging and Production
      Monitoring and Release
      • Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change
      • Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
      • Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
      • A/B Tests for Models: Did the New Model Make Things Better for People?
      • When Labels Arrive Weeks Late: What to Watch Before You Can Grade the Model
      • Retraining Triggers: Schedule, Drift and Performance, Wired to One Retrain Pipeline
      • The User Feedback Loop: Why Thumbs Up Isn't the Truth, and What a Small Random Review Adds
      • Debugging a Model in Production: A Four-Step Runbook, Cheap Checks First
      • Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
      • Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
      • Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
      • Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
      • Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
      • Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
      • Recommendations, Part 1: Two Stages, Candidates Then Ranking
      • Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides
      • Recommendations, Part 2: Candidate Generation With Embeddings
      • Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
      • Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
      • Demand Forecasting, Part 4: Serving the Forecasts, the Outcome Join and a Retrain Rule
      • Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
      • Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
      • Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
      • Ticket Routing, Part 3: Quantise to int8, Host Behind FastAPI and Measure the Server
      • Ticket Routing, Part 4: Canary, Automatic Rollback and "Does Your Small Model Reason?"
      • The ML Engineer Interview Loop: Five Rounds, What Each One Looks For, and a Simple Rubric
      • The Answer Framework for Technical Interviews: Five Moves, Scored Out of 24
      • From Symptom to Pattern: How to Answer "Which Pattern Would You Use?" in an Interview
      • The ML System Design Framework: Eight Steps, in Order, on a Spam Filter
      • ML System Design Interview: Fraud Detection for Card Payments, in Eight Steps with Numbers
      • ML System Design Interview: A Recommendation Feed, From a Score to Beat to Online Guardrails
      • ML System Design Interview: Ad Click Prediction, Sparse Features, Calibration and Late Clicks
      • Interview Answer: How Do You Roll Out a New Model Safely When True Labels Come Weeks Later?
      • Mock ML Engineer Interview, Scored: A Rollout Question Where the Labels Arrive Weeks Late
      • The ML Coding Round: K-Means, Logistic Regression and a Top-k Metric From Scratch
      • The ML Depth Round: Five Questions That Always Come, in Thirty Seconds Each
      • Presenting Your Portfolio: A Six-Section README That Shows Evidence, Not Buzzwords
      • Reading a Job Ad and Shaping Your CV: A Gap List and CV Lines You Can Stand Behind
      • How AI Questions Show Up in an ML Engineer Interview: Your Angle, the Rounds and a Good Answer
      • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
      • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
      • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
      • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
      • Coding Round: Merge Top-k From Sorted Shards, Then Fuse Two Rankings by Place
      • Mock Interview, Scored: 429s at Peak Because One Customer's Batch Job Eats the Capacity
      • One Request Through Every Pattern: a Map of 25 AI System Design Patterns, Stop by Stop
      • AI Engineer, ML Engineer, FDE: What Each Interview Tests, and the Trap of Answering for the Wrong Room
      • Mock Interview: Layer the Guardrails on a Refund Agent, Scored From 6 to 20 of 24
      • Mock Interview for a Forward Deployed Engineer: a Private RAG Assistant in One Region, Scored From 4 to 30 of 36
      • The Coding Round in One Picture: Twenty Minutes, Small, Correct, Tested and Said Out Loud
      • Your AI Interview Preparation Roadmap by Track: AI Engineer, ML Engineer and FDE, Plus the Final Week
      1. Blog
      2. /
      3. Machine Learning
      4. /
      5. MLOps and Production ML

      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.

      Chaand Sheikh

      ·27 November 2026·Updated 29 November 2026Pipelines, CI/CD and Cloud

      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:

      ChoicePickedWhy
      Whisper packagefaster-whisperRuns on your own machine, CPU or GPU, no outside API
      Model sizesmallA balance of speed and accuracy
      Job recordsSQLiteOne local file is enough to start; Postgres or MongoDB later
      Progress in the UIHTTP polling every 2 sServer-sent events and WebSockets add complexity; one progress bar doesn't need them

      The flow

      Upload to subtitles Browser FastAPI S3 uploads/, subtitles/ SQLite row status, progress Redis Worker faster-whisper 1 file 2 QUEUED 3 task 4 download, then 5 upload SRT TRANSCRIBING, progress, COMPLETED poll every 2 s
      The request stays quick, and the heavy work happens somewhere else. The row is where the API and the worker meet.

      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/0 and /1).
      • include registers 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_all makes 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:

      LinesWhere the value comes from
      AWS_REGION, COGNITO_USER_POOL_ID, COGNITO_APP_CLIENT_ID, COGNITO_APP_CLIENT_SECRETThe Cognito user pool overview, then app clients and your client
      S3_BUCKETA bucket you create in S3, unique across AWS, in the same region
      AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEYIAM: 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_URLAlready 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 transcribe by 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.

      Tried the exercise? Share your answer or ask a question.

      The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

      Join free on Skool

      Keep going in Machine Learning · 131 of 192

      Previous
      Celery and Redis for Background Tasks: Answer 202, Hand the Job to a Worker, and Poll for the Result
      Next post
      The S3 CORS Rule: Why the Browser Blocks a Presigned Link, and the Four Lines That Let Your Page Read the File

      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.

      On this page

      • Four decisions before any code
      • The flow
      • The job record
      • The upload endpoint
      • The Celery app
      • The task
      • Where the worker runs
      • Filling the .env
      • The first real upload hangs
      • Log every step
      • It wasn't Redis
      • Fetch the model once, at build time
      • One file in, one SRT out
      • Common mistakes
      • Quick recap
      • Try it yourself
      Community · Free to join
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      Learn AI engineering, share what you build, and connect with other learners.

      • Free resources: lesson files, notebooks and code

      • Ask questions and join engineering discussions

      • Meet real people learning and building with AI

      Join free on Skool

      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)

      Single logo

      Empowering Education, One Course at a Time

      About
      About usContact us
      Legal
      Terms of UsePrivacy Policy

      © 2026 StudyEasy Organization. All rights reserved.