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

      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.

      Chaand Sheikh

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

      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 .en at the end, like tiny.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) and whisper.cpp (a C++ version that runs well without a big graphics card). This script uses openai-whisper; the web app later uses faster-whisper.

      The plan

      input folder to output folder input/ take 05.mp3 transcribe.py ensure_ffmpeg load_model (cache/) transcribe, SRT writer output/ take 05.srt one SRT per input, same name
      Drop media into input, run the script, collect subtitles from output.

      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.

      baselarge-v3
      Model fileabout 139 MBabout 3 GB
      Transcribe time, same 12.5 s clip, GPU3.4 s24.3 s
      Segments23
      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_ffmpeg handles.
      • 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_NAME is 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.

      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 · 129 of 192

      Previous
      Private S3 Uploads from FastAPI: A Locked Bucket, a Key per User, and Presigned Links That Expire
      Next post
      Celery and Redis for Background Tasks: Answer 202, Hand the Job to a Worker, and Poll for the Result

      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

      • Whisper in one minute
      • The plan
      • Set it up
      • Read the script
      • ffmpeg first
      • Load once, transcribe each file
      • Run it
      • What transcribe returns
      • base vs large-v3
      • Why the web app can't do this inside a request
      • 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.