Skip to content
MediumMedium
SOFTWARE AND DATA ENGINEERING

Remote Python Developer: 15 Skills You Need to Succeed

#### Learning Python is the easy part of becoming a remote developer. The harder part is everything around it: solving problems, talking to people you’ve never met, and getting work done with nobody watching. Photo by Mohammad Rahmani on Unsplash Picture a Monday morning. No commute. You make coffee, open your editor, and check Slack. One teammate is chasing a bug in a web app, another is reviewing a pull request, and someone else is arguing about a new API endpoint. They’re spread across different cities and time zones, and you might never meet any of them in person. That’s remote software development, and for a lot of Python developers it’s the goal. Python shows up in web development, automation, data science, AI and backend work, so the range of companies and clients you can work with is huge. But here’s the catch: knowing Python syntax won’t get you hired. Nobody offers a job because you can write a for loop. Companies want people who can read someone else's code, break down a messy problem, explain themselves clearly, and deliver without being chased. So what should you actually work on? Here are the 15 skills that matter most. ### 1. Strong Python Fundamentals Everything else sits on top of this. You don’t need to memorize the whole language, but you should know it well enough to write programs without hand-holding. That means being comfortable with: - Variables and data types - Strings, lists, tuples, sets, and dictionaries - Conditionals and loops - Functions and parameters - Object-oriented programming - Modules and packages - Exception handling and file handling - List comprehensions Say you’re handed a task to process a few hundred customer records. Checking them one by one is out of the question. You should be able to write a small function and let Python do it: def get_active_users(users): active_users = [] for user in users: if user["active"]: active_users.append(user) return active_users users = [ {"name": "Ali", "active": True}, {"name": "Sara", "active": False}, {"name": "Ahmed", "active": True} ] print(get_active_users(users)) It’s a small example, but it shows the core habit: take a problem, turn it into working code. How to improve: Stop watching tutorials and build things. A calculator, an expense tracker, a file organizer, a student management system. You’ll learn more from one small project you got stuck on than from ten videos. ### 2. Git and GitHub Suppose you’ve spent weeks on a project, adding features and fixing bugs. Then your latest change breaks something that used to work. How do you get back to the last good version? That’s the problem Git solves. It’s a version control system that tracks every change to your code. GitHub is where people host repositories, collaborate, and review each other’s work. A remote Python developer should know how to: - Create and clone repositories - Commit, push, and pull - Create and merge branches - Resolve merge conflicts - Open pull requests and review other people’s code The commands you’ll use most: git init git add . git commit -m "Add user authentication" git push origin main git pull origin main git status You don’t need to be a Git wizard on day one. Just start putting your personal projects on GitHub. A tidy profile also tells employers a lot about how you work. How to improve: Make a repository for every real project, write commit messages that actually say what changed, and add a README explaining what the project does and how to run it. ### 3. API Development and Integration Modern apps almost never work alone. A website talks to a payment service, a mobile app pulls data from a backend, an automation script grabs information from another platform. All of that happens through APIs. API stands for Application Programming Interface. It’s simply a structured way for software systems to talk to each other. As a Python developer you’ll mostly deal with REST APIs and JSON. Here’s how you might fetch data with the requests library: import requests url = "https://api.github.com/users/python" response = requests.get(url, timeout=10) if response.status_code == 200: data = response.json() print(data["login"]) print(data["public_repos"]) else: print("Request failed:", response.status_code) To get comfortable with APIs, learn about HTTP methods (GET, POST, PUT, DELETE), status codes, headers, JSON, authentication, API keys and tokens, error responses, and rate limits. If you’re aiming for backend work, this one is non-negotiable. How to improve: Build a small app that pulls data from a public API. Once that feels easy, build your own API with FastAPI or Django REST Framework. ### 4. Python Web Frameworks Three names come up again and again: Django, Flask, and FastAPI. Django is the full package. Authentication, database management, and an admin interface come built in. Flask is lightweight and gives you more freedom to structure things your own way. FastAPI is built for APIs and leans on modern Python features like type hints and async. You don’t need all three before your first job. Pick one that fits where you want to go: Django for full web applications, Flask for smaller services, FastAPI for API-focused backend work. A good first project is a task manager with registration, login, and CRUD (Create, Read, Update, Delete), the four operations nearly every real application relies on. How to improve: Finish one complete project with one framework. A single finished project beats five abandoned tutorial apps. ### 5. Database Management Almost every serious application has to store something. An online store keeps products and orders. A hospital system keeps patient records and appointments. A task app keeps users and their tasks. Start with a relational database like PostgreSQL, MySQL, or SQLite, and learn the SQL basics: creating tables, inserting, retrieving, updating and deleting records, filtering and sorting, joins, indexes, and relationships between tables. SELECT name, email FROM users WHERE active = TRUE; In Python you’ll often use SQLAlchemy or the Django ORM instead of writing raw SQL. That’s fine, but make sure you understand the SQL underneath. When something runs slowly or returns the wrong data, that’s the knowledge that saves you. How to improve: Build an app that stores user data in PostgreSQL or SQLite, and practice writing queries by hand instead of leaning on the ORM for everything. ### 6. Testing and Debugging Writing code is only half the job. The other half is making sure it works. Imagine you build a registration system. It works perfectly when you test it with your own details. Then a user types an invalid email address and the whole thing crashes. A reliable developer thinks about that user before it happens. It’s worth learning unit tests, integration tests, assertions, how to read a traceback, and how to debug properly. Python ships with unittest, but many people prefer pytest. A simple test looks like this: def add(a, b): return a + b def test_add(): assert add(2, 3) == 5 assert add(-1, 1) == 0 Save it as test_math.py and run: pytest Tests matter even more on a remote team. Your teammates depend on your code, and they can’t look over your shoulder to see whether it works. How to improve: Write tests for your own projects. Every time you write a function, ask what happens with normal input, weird input, and no input at all. ### 7. Linux and Command-Line Skills You don’t need to become a system administrator. But a lot of servers and deployment environments run Linux, and being comfortable in a terminal makes everything smoother. Learn the basics: pwd ls cd mkdir touch cp mv rm Then get used to navigating directories, setting up virtual environments, installing packages, running scripts, reading log files, setting environment variables, managing file permissions, and connecting to servers over SSH. Virtual environments are a good place to start, since they keep each project’s dependencies separate: python -m venv venv Activate it on Windows: venv\Scripts\activate Or on Linux and macOS: source venv/bin/activate Then install what you need: pip install requests How to improve: Use the terminal daily instead of reaching for graphical tools, and run your Python projects from the command line. ### 8. Docker and Deployment Basics Building something on your own laptop is very different from putting it in front of real users. A program can run perfectly on your machine and fail on someone else’s because of a different Python version, a missing package, or a different system setup. Docker fixes that by packaging your app and everything it needs into a container. Learn what containers and images are, how to write a basic Dockerfile, how to build and run a container, and how to use environment variables. A simple Dockerfile for a Python app: FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["python", "app.py"] It also helps to get a feel for hosting platforms and basic cloud ideas. AWS, Azure, and Google Cloud are the big names, but you don’t need advanced cloud skills yet. Knowing how to deploy one small app is a great first step. How to improve: Build a small API, put it in a Docker container, deploy it somewhere, and write up the steps in your repository. ### 9. Writing Clean, Readable Code On a remote team, your code is often the first impression you make. Teammates will review your pull requests, change your functions, and debug your work months later. If your code is confusing, everyone suffers. Compare these two: def c(p, q): return p * q def calculate_total_price(price, quantity): return price * quantity Same result, but only one of them tells you what it’s for. Clean code comes down to meaningful names, small focused functions, consistent formatting, not repeating yourself, comments that are actually useful, sensible error handling, and a clear project structure. Read up on PEP 8, Python’s style guide, and let tools like Black, Ruff, or Flake8 keep your formatting consistent. How to improve: Go back to an old project and refactor it. Could another developer understand it without you explaining every function? ### 10. Asynchronous Programming Some applications have to do many things at once: send lots of API requests, talk to external services, handle many connections. If each operation waits for the previous one, things get slow. Python handles this with async and await: import asyncio async def greet(): print("Hello") await asyncio.sleep(2) print("Welcome to Python") asyncio.run(greet()) Async shines with I/O-bound work like network requests and database calls. It isn’t a magic speed boost, though. CPU-heavy tasks usually need multiprocessing or specialized libraries instead. How to improve: Get comfortable with normal functions and execution flow first. Then learn asyncio and see how frameworks like FastAPI use it. ### 11. Basic Security Knowledge Getting an app to work isn’t the end of your responsibility. It also has to protect the people using it. Think about an app with customer accounts. If passwords are stored as plain text, anyone who gets into the database can read every one of them. That’s a serious failure. The basics worth knowing: password hashing, input validation, preventing SQL injection, authentication and authorization, secure sessions, HTTPS, environment variables, protecting API keys, and keeping dependencies updated. For example, never hard-code credentials in your source: # Avoid this API_KEY = "your-secret-api-key" Use environment variables or a proper secrets manager instead. And remember that hashing and encryption aren’t the same thing. Passwords should be stored with a dedicated password-hashing algorithm, not reversible encryption. How to improve: Learn the common web vulnerabilities, then build something with secure login and proper input validation. ### 12. Communication Skills This is the most underrated skill on the list. In an office you can lean over and ask a colleague a quick question. On a remote team, everything goes through messages, calls, tickets, and documents. If your manager gives you a vague task, you can lose an entire day building the wrong thing on assumptions. One clear question at the start would have saved it. Good remote communication means asking when something is unclear, explaining problems clearly, sharing progress, flagging blockers early, writing useful documentation, and giving context when you ask for help. Compare: “API is not working.” with: “I’m getting a 401 Unauthorized from the login endpoint. I’ve checked the request body and headers. Has the authentication token changed?” The second message gives your teammate something to work with. How to improve: Practice explaining technical problems in plain English. Write clear GitHub issues, READMEs, and project updates. ### 13. Time Management and Self-Discipline Remote work gives you flexibility, and with it comes responsibility. Nobody’s standing behind you. It’s easy to lose hours to social media, task-switching, or putting off the hard problem. A routine that works for many people: 1. Review your tasks at the start of the day. 2. Pick the most important one. 3. Break big tasks into smaller steps. 4. Work in focused sessions with short breaks. 5. Update your team on progress. 6. Look back at what you finished before you log off. Tools like Trello, Notion, or Jira help, but a plain to-do list works too. The aim isn’t to look busy all day. It’s to finish meaningful work, consistently. How to improve: Build a daily routine and track your progress. Learn to estimate how long tasks take, and speak up early when a deadline is at risk. ### 14. Problem-Solving and Independent Learning Programming is really just solving problems, over and over. You’ll hit errors you’ve never seen, unfamiliar libraries, old codebases, and requirements that aren’t fully clear. Remote developers can’t expect someone else to untangle all of that, so they learn to investigate. A process that works: 1. Understand the real problem. 2. Reproduce the error. 3. Read the error message carefully. 4. Check the documentation. 5. Look for reliable examples. 6. Test possible fixes. 7. Make sure the fix doesn’t break something else. 8. Write it down if it might come up again. Say you suddenly get a ModuleNotFoundError. Don't reinstall everything straight away. Check whether the right virtual environment is active, whether the package is installed, and whether the project is using the interpreter you think it is. Habits like this save hours. How to improve: Try solving small problems before copying a solution. Read the docs, experiment, and explain to yourself why the fix works. ### 15. Building a Strong Portfolio You might know Python, Git, APIs, databases, and testing. How would an employer know? A portfolio is your proof. You don’t need twenty tutorial clones. A few well-built projects say more than a pile of unfinished repositories. Here are five worth building: 1. Task Management API. Users register, log in, and create, update, and delete tasks. Shows Python, FastAPI or Django, databases, authentication, and API design. 2. Automated File Organizer. A script that sorts files into folders by extension. Shows fundamentals, file handling, automation, and error handling. 3. Expense Tracker. An app that stores expenses and produces monthly summaries. Shows databases, data processing, and reporting. 4. Web Scraping Project. A program that collects publicly available information while respecting the site’s terms and access rules. Shows Requests, Beautiful Soup, and data extraction. 5. Data Analysis Dashboard. Analyze a dataset and present useful visualizations. Shows Pandas, Matplotlib, data cleaning, and communicating results. For each project, include a clear description, the features and technologies used, installation and run instructions, a requirements file, screenshots where they help, and a short explanation of the problem it solves. Your GitHub profile should make it easy for a stranger to see what you can build. ### How to Prepare for Your First Remote Python Job Fifteen skills can feel overwhelming, especially as a beginner. The trick is to stop trying to master everything at once. Here’s a realistic six-month path. Month 1: Python foundation. Fundamentals, functions, data structures, OOP, and exception handling. Build small projects and practice problems. Month 2: Developer tools. Git, GitHub, the command line, virtual environments, and package management. Put your projects on GitHub with proper READMEs. Month 3: Backend development. Pick Django, Flask, or FastAPI. Learn to build APIs, work with databases, and add basic authentication. Month 4: Testing and deployment. pytest, debugging, basic Linux, and Docker. Deploy at least one project so other people can use it. Month 5: Portfolio. Build two or three meaningful projects, clean up your code, write documentation, and polish your GitHub profile. Month 6: Job hunting. Prepare your CV, practice technical interviews, and get good at explaining your projects. Start applying for internships, junior roles, and freelance work. Some places to look for remote work: LinkedIn, Wellfound, Remote OK, We Work Remotely, Upwork, and Freelancer. Read each listing carefully. Some require you to live in a specific country or time zone, while others hire internationally. Don’t assume every remote job is open worldwide. ### Final Thoughts: Become a Developer People Can Trust Python can open a lot of doors, but being a good remote developer takes more than technical knowledge. You need to understand problems, write reliable code, work with other people, manage your own time, and communicate well. Don’t treat this list like a checklist you have to finish before you start. Learn Git by using it. Learn databases by building something that needs one. Learn testing by testing your own code. Get better at communication by documenting your work. Every project teaches you several of these skills at once, and you don’t need to be an expert in all of them to apply for your first remote job. A solid foundation, real practical experience, and a willingness to keep learning are enough. Companies aren’t just looking for people who can write Python. They’re looking for people they can trust to understand a task, work through the problems, and deliver. Your journey to becoming a remote Python developer doesn’t start when someone hires you. It starts with the first project you build, the first problem you solve, and the first time you take responsibility for your own learning. --- Remote Python Developer: 15 Skills You Need to Succeed was originally published in Python in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.
GIT HUBPOSTGRE SQL
MediumMedium
ARTIFICIAL INTELLIGENCE

LLM, RAG, Tokens… Wait, What?

#### A developer’s friendly guide to the vocabulary of the AI era AI Image A few months ago I was on a call with a client, and he casually asked, “So are we going with RAG or fine-tuning for this?” I nodded like I knew exactly what he meant. I didn’t. I’ve been building web apps for years. I can debug a broken API at 2 AM, explain the event loop to a junior dev, and argue about state management until everyone leaves the room. But suddenly there was a whole new vocabulary floating around: tokens, embeddings, context windows, hallucinations, agents. Everyone seemed to be speaking it fluently, and I felt like the new kid again. So I sat down and learned it properly. This article is everything I wish someone had handed me on day one, explained the way I’d explain it to a friend over chai. No PhD required. Let’s go. ### AI (Artificial Intelligence) The big umbrella. Any system that does something we’d normally think needs human intelligence, like recognizing faces, translating languages, or writing text. Your spam filter is AI. So is ChatGPT. They’re just very different flavors of it. ### Machine Learning (ML) This is a branch of AI where, instead of writing rules by hand, you show the computer a ton of examples and let it figure out the patterns itself. As a developer, this was the mindset shift for me. Normally I write if (x) do y. In ML, you give the system thousands of x's and y's and it writes the "if" logic on its own. ### Deep Learning Machine learning, but using neural networks with many layers. “Deep” just means lots of layers. This is what powers most of the impressive stuff today: image generation, voice assistants, chatbots. ### Neural Network A system loosely inspired by the brain. It’s made of layers of “neurons,” which are really just numbers and math functions passing values to each other. Each connection has a weight, and training is the process of adjusting those weights until the output becomes useful. Don’t let the brain comparison fool you though. It’s a lot more matrix multiplication than magic. ### LLM (Large Language Model) The star of the show. An LLM is a neural network trained on a massive amount of text to predict what comes next in a sentence. That’s honestly it. GPT, Claude, Gemini, Llama, they’re all LLMs. When I first understood that these models are basically insanely good autocomplete, a lot of their behavior suddenly made sense to me, including their weird mistakes. “Large” refers to the size of the model (billions of parameters) and the amount of data it learned from. ### Parameters The internal numbers (weights) the model learned during training. When you hear “a 70B model,” that means 70 billion parameters. More parameters usually means more capability, but also more cost, memory, and slower responses. Bigger isn’t always better for your use case, the same way you don’t need Kubernetes for a landing page. ### Token This one confused me for a while. Models don’t read words the way we do. They break text into chunks called tokens. A token can be a full word, part of a word, or even punctuation. Roughly, one token is about 4 characters of English, or around three quarters of a word. “Unbelievable” might become “un”, “believ”, “able”. Why should you care? Because almost everything in AI is measured in tokens: pricing, limits, speed. When an API charges you per million tokens, this is what it’s counting. ### Tokenization The process of splitting text into tokens. Each model has its own tokenizer, which is why the same sentence can cost a different number of tokens on different models. Fun fact: non-English languages, including Hindi, often take more tokens for the same meaning, which makes them a bit more expensive to process. ### Context Window The amount of text (in tokens) a model can “see” at once. That includes your prompt, the conversation history, any documents you paste in, and the model’s reply. Think of it like RAM for the conversation. Once you go past it, older stuff falls out and the model simply forgets it. If you’ve ever had a chatbot “forget” something you told it an hour ago, this is usually why. ### Prompt Whatever you send to the model. A question, an instruction, a document, a piece of code. The prompt is your input, and the quality of the output depends heavily on it. Garbage in, garbage out, just like any API. ### Prompt Engineering The skill of writing prompts that get good results. It sounds fancy, but a lot of it is just clear communication: give context, be specific, show an example of what you want, and say what format you expect. Honestly, writing a good prompt feels a lot like writing a good ticket for another developer. The vaguer you are, the weirder the result. ### System Prompt A hidden set of instructions given to the model before the user says anything. It sets the rules, personality, and boundaries. If you build an AI feature in your app, the system prompt is where you say things like “You are a support assistant for an e-commerce store. Only answer questions about orders.” ### Inference When the model is actually being used to generate an answer. Training is the learning phase. Inference is the “doing the job” phase. Every time you hit an LLM API, you’re running inference, and that’s what you pay for. ### Training The expensive part where the model learns from data. Training a large model from scratch costs millions of dollars and huge amounts of compute. As a regular developer, you’ll almost never do this. You’ll use models someone else trained. ### Pre-training The first, massive stage of training where the model reads enormous amounts of text from the internet, books, code, and so on, and learns general language patterns. After this, the model knows a lot but isn’t great at following instructions yet. ### Fine-tuning Taking an already trained model and training it a bit more on your own specific data so it gets better at a particular task or style. Example: a model fine-tuned on legal documents will write more like a lawyer. It’s powerful, but it’s not always the first tool you should reach for. More on that in a second. ### RLHF (Reinforcement Learning from Human Feedback) A technique where humans rate model responses, and the model is trained to produce answers people prefer. This is a big part of why modern chatbots feel helpful and polite instead of just spitting out random internet text. ### Hallucination When a model confidently makes something up. Fake facts, fake citations, a library function that doesn’t exist. This one bit me personally. I once asked an AI for help with a package, and it gave me a beautiful code snippet using a method that had never existed. It looked so right. Remember: the model is predicting plausible text, not checking truth. Always verify, especially in code and anything factual. ### Temperature A setting that controls how random the output is. Low temperature (like 0 to 0.3) gives more predictable, focused answers. High temperature (0.8 and up) gives more creative, varied ones. My rule of thumb: low for code and data extraction, higher for brainstorming and creative writing. ### Embeddings This is one of my favorite concepts. An embedding turns a piece of text into a long list of numbers (a vector) that represents its meaning. The cool part is that texts with similar meaning end up with similar numbers. So “How do I reset my password?” and “I forgot my login” land close to each other, even though they share almost no words. That’s what makes semantic search possible. ### Vector Just a list of numbers. In AI, it’s usually the output of an embedding. If you’ve worked with arrays, you already get it. ### Vector Database A database built to store embeddings and quickly find the ones most similar to a given query. Pinecone, Weaviate, Qdrant, Chroma, and pgvector (a Postgres extension) are popular options. As a full stack dev, pgvector made this click for me. It’s just Postgres, with a new column type and a new way to search. ### RAG (Retrieval-Augmented Generation) Back to that client call. RAG is a pattern where, before asking the model a question, you first search your own data for relevant information and include it in the prompt. The flow looks like this: user asks a question, you turn it into an embedding, search your vector database for related documents, stuff those documents into the prompt, and then the LLM answers using that context. This is how you build “chat with your docs” or a support bot that actually knows your product. In most cases, RAG is cheaper, easier, and easier to update than fine-tuning. For that client, we went with RAG. Now I actually know why. ### Chunking Before storing documents for RAG, you split them into smaller pieces called chunks. Too big and you waste context and lose precision. Too small and you lose meaning. Getting chunking right is more art than science, and it makes a surprising difference in quality. ### Multimodal A model that can handle more than one type of input or output, like text plus images, audio, or video. You can upload a screenshot of a bug and ask what’s wrong. As someone who works with UI, this one genuinely changed how I debug layouts. ### AI Agent An LLM that doesn’t just answer but takes actions. It can decide which steps to take, call tools, look at the results, and keep going until the task is done. Instead of “write me a function,” it’s more like “fix this failing test,” and the agent reads files, runs the test, edits code, and runs it again. ### Tool Use / Function Calling The feature that makes agents possible. You describe functions to the model (like getWeather(city) or createOrder(items)), and the model can respond with a structured request to call one. Your code runs the function and sends the result back. For developers, this is the bridge between AI and your actual backend. Once I understood this, I started seeing LLMs less as chatbots and more as a new kind of API consumer. ### MCP (Model Context Protocol) An open standard for connecting AI models to external tools and data sources in a consistent way. Think of it like a USB-C port for AI: instead of building a custom integration for every tool, you build an MCP server once and any compatible AI client can use it. ### Open Source vs Closed Models Closed models (like GPT or Claude) are accessed through an API, and you don’t get the weights. Open-weight models (like Llama, Mistral, or DeepSeek) let you download and run them yourself. Open gives you control and privacy, closed usually gives you top performance with less setup. Pick based on your project, not on hype. ### Latency How long it takes to get a response. In AI apps, this matters a lot for user experience. A 10-second wait feels like forever in a chat UI. ### Streaming Sending the response piece by piece as it’s generated, instead of waiting for the whole thing. That typing effect you see in chat apps is streaming. As a frontend person, I’d say it’s the single biggest UX improvement for AI features. Users will happily wait if they can see progress. ### Rate Limits Caps on how many requests or tokens you can send to an API in a given time. You will hit them. Plan for retries and backoff from day one. Trust me. ### Guardrails Rules and checks around a model to keep its outputs safe and on-topic. This can be in the system prompt, in code that filters inputs and outputs, or both. If you’re putting AI in front of real users, you need them. ### AGI (Artificial General Intelligence) A hypothetical AI that can do pretty much any intellectual task a human can, across any domain. It’s the term you’ll see in big headlines and big debates. Whether and when we’ll get there is genuinely contested, so take bold predictions with a pinch of salt. ### What I Took Away From All This Learning these terms didn’t just help me survive client calls. It changed how I build. I stopped treating AI as a black box that either works or doesn’t. Now when something goes wrong, I can think it through like any other bug. Is the context window too full? Is the temperature too high? Is my retrieval pulling the wrong chunks? Is the model just hallucinating because I didn’t give it enough information? That’s the part nobody tells you. Under all the buzzwords, building with AI is still engineering. Inputs, outputs, trade-offs, edge cases. The same skills you already have as a developer carry over more than you think. If you’re where I was a few months ago, nodding along in meetings and secretly Googling terms afterward, that’s completely fine. Everyone starts there. Bookmark this, come back to it, and slowly the jargon turns into tools you actually understand. And next time someone asks “RAG or fine-tuning?”, you’ll have an answer. If this helped, drop a clap or leave a comment with a term I missed. I’m still learning too, and I’d love to add it to the list. --- LLM, RAG, Tokens… Wait, What? was originally published in Python in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.
PROMPT
CIOEffective Altruism ForumDon't Worry About the Vase
MediumMedium
ECONOMICS ACCOUNTING AND FINANCE

WhatsApp Orders Are 17% Bigger. Should She Move the Budget?

Part 2: One boutique owner, three new columns, eight steps from correlation to A/B test sizing, and a hidden group that changes the answer—with reproducible numbers An AI-generated image I n Part 1, Priya learned that her average order of ₹1,556 was not the norm. The average one was ₹1,092. She needed about 515 orders in a month to get to ₹8 lakh. Then her marketing lead came back with a new idea. “WhatsApp customers spend more per order. Let’s move the budget there.” The dashboard agreed. WhatsApp’s average order was ₹1,786. Instagram’s was ₹1,527. Priya had learned not to trust a single number. So she asked for three more columns: how many items were in each order, whether the customer was new or returning, and which channel the order came from. Now the question was no longer "What is a typical order?” It was "What makes an order bigger, and can we actually change it?” ### Where we left Priya > New here? Part 1 followed one column, Order_Amount, through eleven steps. The link to Part 1 is here: https://python.plainenglish.io/71-7-of-orders-fell-below-average-heres-why-that-s-normal-540b148ee37f The short version: the data is synthetic, 1,002 order records for a made-up boutique owner. It is heavily right-skewed, with a mean of ₹1,556, a median of ₹1,092, and a few large orders that bring in a big share of the revenue. Part 1 ended with an honest limit: one column can show the shape of the data, but not who is in it. Part 2 adds the columns that let her ask who. Here are the three new columns: - Items_Per_Order: numerical, a count (1 to 16 items). - Customer_Type: categorical, two levels (New or Returning). - Channel: categorical, four levels (WhatsApp, Website, Instagram, Marketplace). Order_Amount stays numerical and continuous. The mix of data types matters, because the type of data decides the tool: - Number vs. number: Do they move together? - Number vs. categories: Do groups differ? - Category vs. category: Are they linked? Here is the roadmap: - Basic: data check, correlation, regression (Steps 1 to 3) - Intermediate: two groups, two categories, four groups (Steps 4 to 6) - Advanced: confounding and experiment sizing (Steps 7 and 8) Her three questions map onto the steps. - What makes an order bigger? That is Steps 2 and 3. - Who spends more? That runs through Steps 4 to 6. - Should she move the budget? That is Steps 7 and 8. The data is built with a fixed random seed, so you can reproduce every number. I left Part 1’s Order_Amount column untouched, so the Part 1 results still hold. Let’s start where every analysis should start with ### Step 1: The data health check, again. Priya’s new file has 1,002 rows and five columns. The old problems are still there. The check finds: - 3 missing order amounts - 2 duplicate rows - 1 negative amount (-₹500, a refund logged as a sale) - 0 problems in the new columns: no blanks, and every value is a valid level She removes the duplicates and the negative amount, as before. But this time she drops the three orders with missing amounts instead of filling them with the median. [1] Why the change? In Part 1, one column could absorb three median values. With two variables, a filled-in amount would pretend those orders sit at the typical value, whatever their basket size, which weakens the very relationship she wants to measure. That leaves 996 orders. df = raw.drop_duplicates() df = df[df["Order_Amount"].isna() | (df["Order_Amount"] >= 0)] df = df.dropna(subset=["Order_Amount"]).reset_index(drop=True) Then she looks at the categories: - Customer_Type: 730 New, 266 Returning - Channel: Instagram 402, WhatsApp 227, Website 214, Marketplace 153 - Smallest cell in the Customer_Type by Channel table: 8 orders (Returning, Marketplace) That cell of 8 orders is a warning. Any result that rests on it is too thin to trust. > What this means for Priya: The file is clean enough to analyze, and she has 996 orders to work with. For categorical columns, the health check is about levels and counts, not just blanks. Tiny groups are where wrong conclusions start. Your turn: for each categorical column, list the levels and counts, and find your smallest cell before running any test. ### Step 2: Two numbers together, correlation Priya’s first question is simple. Do bigger baskets mean bigger orders? She plots items per order against order amount and measures the link two ways. [2] from scipy import stats pearson = stats.pearsonr(df["Items_Per_Order"], df["Order_Amount"]) spearman = stats.spearmanr(df["Items_Per_Order"], df["Order_Amount"]) - Pearson r: 0.805 (95% CI 0.782 to 0.826) - Spearman rho: 0.586 (95% CI 0.538 to 0.630) - Pearson on log values: 0.669 The two numbers disagree, and the gap is the lesson. Pearson measures how well the points fit a straight line, and a few large multi-item orders pull it up. Spearman uses only the ranking of the orders, so it ignores how far out those extremes sit (extremes explain much of the gap, not all of it; the many tied item counts play a part too). Grouping the orders by basket size shows where the money is: - 1 item: 374 orders, median ₹773 - 2 items: 295 orders, median ₹1,052 - 3 items: 161 orders, median ₹1,303 - 4 or more items: 166 orders, median ₹3,086 Orders with 4 or more items are 16.7% of orders but bring in 40.2% of revenue. Two scatter plots of items per order against order amount. On the raw scale the points fan out; on log scales they form a steadier band. In the left chart, the cloud fans out as items rise. On the right, with both axes on a log scale, it becomes a steadier band. > What this means for Priya: Bigger baskets go with bigger orders, strongly. But the link is not a clean straight line, and the money sits in the big baskets. A correlation says that two things move together. It does not say that one causes the other. Your turn: always compute both Pearson and Spearman. When they differ a lot, look for extreme values or a curved relationship. ### Step 3: Regression—How much more per item? Correlation says how strongly. Regression says how much. Priya fits a straight line from item to amount. [3] import statsmodels.formula.api as smf m1 = smf.ols("Order_Amount ~ Items_Per_Order", df).fit() - Slope: ₹663.95 per extra item (95% CI ₹633.50 to ₹694.41; a classical interval, which is unreliable given the unequal spread below) - R-squared: 0.648 - Intercept: -₹31.65. It is a meaningless value at 0 items, because every order has at least one item. Then she checks the assumptions, which she should do before trusting any of this. A regression wants the errors to have similar spread everywhere. They don’t: - Residual spread: ₹560 for orders with 1 or 2 items, but ₹2,027 for orders with 5 or more. - Breusch-Pagan test for unequal spread: p = 3.72e-28. - Shapiro-Wilk test on the residuals: p = 1.58e-26, far from normal. The slope of ₹664 is an average over a cloud that fans out, so a prediction for a big basket is much less certain than for a small one. She has seen this problem before: skew. So she takes logs, as in Part 1. [4] m2 = smf.ols("np.log(Order_Amount) ~ np.log(Items_Per_Order)", df).fit() - Elasticity: 0.751 (95% CI 0.699 to 0.803). A 10% increase in items goes with about a 7.4% higher order amount. - R-squared: 0.447, on the log scale. It is not comparable with the 0.648 above. - The spread is steadier, though not perfect: Breusch-Pagan p = 0.003. The log residuals show no sign of non-normality: Shapiro-Wilk p = 0.509. The model’s typical order amount is ₹715 for 1 item, ₹1,203 for 2, ₹1,632 for 3, and ₹2,025 for 4. Residual plots for two models. Linear residuals fan out as fitted amount grows; log-log residuals have steadier spread. In the left chart, the linear model’s errors fan out as the fitted amount grows. On the right, the log-log model’s errors have a steadier spread. > What this means for Priya: Each extra item goes with a higher order, but the fitted curve implies diminishing returns: the second item adds about ₹488, the fourth about ₹393. That shape comes from the log-log form. The raw medians rise more unevenly (₹773, ₹1,052 and ₹1,303 for 1 to 3 items, then a jump at 4 or more), and the curve sits above the 2- and 3-item medians (₹1,203 vs ₹1,052, ₹1,632 vs ₹1,303). Even so, the log-log model handles the fanning spread better than a straight line, and it passes its assumption checks far better. Still, it describes how orders differ. It does not prove that getting a customer to add an item will raise revenue. Your turn: after any regression, plot the residuals against the fitted values. A funnel shape means the spread is not constant, and a log transform is often the first fix. ### Step 4: Two groups—do returning customers spend more? Now the marketing lead asks something else: “Do our returning customers spend more?” Customer type is categorical with two groups, so Priya compares the groups. [5] - Returning: 266 orders, mean ₹1,960.11, median ₹1,163.16 - New: 730 orders, mean ₹1,409.98, median ₹1,062.46 First, an assumption check. Levene’s test says the spread is unequal between the groups (p = 2.2e-07). So she uses Welch’s t-test, which doesn’t assume equal spread, and a rank-based test as a cross-check. a = df.loc[df["Customer_Type"] == "Returning", "Order_Amount"] b = df.loc[df["Customer_Type"] == "New", "Order_Amount"] stats.ttest_ind(a, b, equal_var=False) stats.mannwhitneyu(a, b, alternative="two-sided") - Mean difference: ₹550.13 (95% CI ₹276.11 to ₹824.15). Welch t = 3.949, p = 9.57e-05. - Cohen’s d: 0.357, a small-to-medium effect by convention (a rough guide, since the spreads differ). - Median difference: ₹100.70, with a bootstrap 95% CI of -₹53.06 to ₹257.62. That interval includes zero. - Mann-Whitney U: p = 0.0063. A random returning order is larger than a random new order 55.7% of the time (50% would be a coin flip). - On the log scale, returning orders’ geometric mean is 21.7% higher (95% CI 9.3% to 35.5%). Several answers, mostly one story. The mean gap is large because returning customers place more of the very large orders: 16.5% of their orders are above Part 1’s outlier threshold (₹3,277.51), against 6.3% for new customers (two-proportion z-test, p = 6.13e-07). In the middle, the two groups are closer (though the rank test and log-scale interval still lean slightly toward returning customers). These tests are not independent verdicts—they answer slightly different questions about the same split. The z-test looks at the tail share, the median bootstrap looks at the middle, and the mean tests look at the average. The pattern across them is consistent: returning customers’ orders are shifted toward higher values, more in the tail than in the middle. Box plot of order amount for new and returning customers. Medians are close; returning customers have a higher mean and more large orders. > What this means for Priya: Returning customers do spend more on average, mostly because of a heavier upper tail, plus a smaller lift in the middle. “Spend more” depends on the question. The mean says ₹550 more. The median says ₹101 more, with a range that includes zero. She should say which one she means. Your turn: report the mean difference, the median difference, and the effect size together. If they tell different stories, the difference lives in the tails. > A bigger average is not the same as a bigger typical order. ### Step 5: Are two categories, channel and customer type, linked? Before judging channels by order amount, Priya checks who uses them. Both columns are categorical, so she uses a chi-square test of independence. [6] ct = pd.crosstab(df["Customer_Type"], df["Channel"]) chi2, p, dof, expected = stats.chi2_contingency(ct, correction=False) - New customers: Instagram 49.0%, Marketplace 19.9%, Website 20.1%, WhatsApp 11.0% - Returning customers: Instagram 16.5%, Marketplace 3.0%, Website 25.2%, WhatsApp 55.3% The assumption check: every expected count should be at least 5. The smallest is 40.9, so the test is valid. (The observed 8 returning Marketplace orders are far below the expected 40.9, which is itself a finding.) - Chi-square = 257.30, df = 3, p = 1.73e-55 - Cramér’s V = 0.508, a large association by common rules of thumb - The biggest gap: returning customers on WhatsApp (standardized residual +11.1). New customers on WhatsApp are far below expectation (-6.7). Stacked bars of channel share. Most returning customers buy on WhatsApp; most new customers buy on Instagram. > What this means for Priya: Channel and customer type are tightly linked. 55% of returning customers buy on WhatsApp, against 11% of new customers. Remember this. It matters in Step 7. Your turn: check the smallest expected count. If any is under 5, merge categories or use an exact test. ### Step 6: Four groups—does the channel change the order value? Now the main question. Channel has four groups, so Priya uses ANOVA (a test of means) and its rank-based twin, Kruskal-Wallis. [7] - WhatsApp: 227 orders, mean ₹1,785.93, median ₹1,137.48 - Website: 214 orders, mean ₹1,558.17, median ₹1,107.50 - Instagram: 402 orders, mean ₹1,526.95, median ₹1,115.40 - Marketplace: 153 orders, mean ₹1,294.04, median ₹973.16 Levene’s test shows only borderline unequal spread (p = 0.069), so ANOVA is reasonable, with Kruskal-Wallis as a cross-check. groups = [g["Order_Amount"] for _, g in df.groupby("Channel")] stats.f_oneway(*groups) stats.kruskal(*groups) - ANOVA: F = 3.145, p = 0.0245. Eta-squared = 0.0094. - Kruskal-Wallis: H = 8.939, p = 0.0301. Epsilon-squared = 0.0090. Both say the channels are not all the same. But look at the effect size: channel explains under 1% of the variation in order amount. Which channels differ? That is a second question, and asking it six times brings a trap. With six pairwise comparisons at the 0.05 level, there is about a 26.5% chance of at least one false alarm even if nothing is going on. [8] So she uses corrected tests. from statsmodels.stats.multicomp import pairwise_tukeyhsd from statsmodels.stats.multitest import multipletests pairwise_tukeyhsd(np.log(df["Order_Amount"]), df["Channel"]) multipletests(raw_p_values, method="holm") - Tukey HSD (on log amounts): only WhatsApp vs Marketplace is significant (adjusted p = 0.0045). WhatsApp’s typical order is about 27.5% higher (95% CI about 6% to 54%). - Pairwise Mann-Whitney with Holm correction agrees: WhatsApp vs Marketplace has an adjusted p of 0.0188. WhatsApp vs Instagram has an adjusted p of 0.61. Box plot of order amount by channel on a log scale. Medians are similar; WhatsApp has the highest mean, Marketplace the lowest. > What this means for Priya: The marketing lead’s claim, that WhatsApp beats Instagram, is not statistically distinguishable from chance. The only difference that survives correction is WhatsApp versus Marketplace, and it is modest in the middle of the distribution (medians of ₹1,137 and ₹973, about 17% apart) and imprecise (the interval runs from 6% to 54%). It has also not been adjusted for customer type, and Step 7 shows why that matters. A raw average gap that looks convincing on a dashboard can fall apart once she asks how many comparisons she made. Your turn: when you compare more than two groups, run the overall test first, then a corrected post-hoc test. Never run six uncorrected t-tests. ### Step 7: Confounding, is WhatsApp really better? The dashboard still shows WhatsApp ahead: a mean order of ₹1,785.93 against ₹1,526.95 for Instagram, which is 17.0% higher. The medians are ₹1,137.48 and ₹1,115.40, almost the same. Step 5 gives Priya a suspect. WhatsApp’s customers are 65% returning. Instagram’s are 11% returning. And Step 4 showed that returning customers have a heavier upper tail. Is it WhatsApp, or is it who shops on WhatsApp? Statisticians call this confounding. [9] First, she splits the data by customer type. These are median orders, with the number of orders in brackets: - Returning: WhatsApp ₹1,130 (147), Website ₹1,297 (67), Instagram ₹1,500 (44), Marketplace ₹797 (8, too few to read) - New: WhatsApp ₹1,159 (80), Website ₹1,049 (147), Instagram ₹1,097 (358), Marketplace ₹986 (145) Inside each customer type, WhatsApp no longer stands out. Then she fits two regressions on log amounts: channel alone, and channel plus customer type. smf.ols("np.log(Order_Amount) ~ C(Channel, Treatment('Instagram'))", df).fit() smf.ols("np.log(Order_Amount) ~ C(Channel, Treatment('Instagram')) + C(Customer_Type)", df).fit() WhatsApp compared with Instagram, typical order amount: - Channel only: +10.3% (95% CI -1.5% to +23.4%), p = 0.090 - Channel plus customer type: +0.4% (95% CI -11.6% to +14.1%), p = 0.949 The gap shrinks from +10.3% to +0.4% once customer type is in the model. Within each customer type, the WhatsApp versus Instagram comparison is also not significant (returning: p = 0.171, new: p = 0.191). Two cautions. The starting gap was itself not statistically clear (p = 0.090), and the adjusted interval (-11.6% to +14.1%) is too wide to rule out a real difference of roughly 12% in either direction. Also, the dashboard’s +17.0% is a gap in means, while these percentages are gaps in typical orders on the log scale, so the two are not directly comparable. One thing doesn’t go away. Marketplace’s typical order is about 13.5% below Instagram’s before adjustment, and about 12.7% below after adding customer type to the model (p = 0.039). The confound moved the gap by less than a percentage point; it did not erase it. That is one result among several, and these two p-values are not corrected for multiple comparisons. In Step 6 the corrected Instagram versus Marketplace comparison was not significant (Tukey 0.12, Holm 0.12), so she treats it as a lead, not a finding. Left: WhatsApp has the highest mean order, but medians are similar. Right: medians within each customer type show no WhatsApp advantage. > What this means for Priya: Most of the apparent WhatsApp advantage goes away once customer mix is accounted for, which points to who shops there rather than the channel itself. Moving budget to WhatsApp on the strength of that average would be a bet on a number that is largely customer mix. Even so, “no detectable difference” is not “no difference”, and adjusting can only remove the confounders she has measured. Your turn: when two variables are linked (Step 5), compare groups within each level of the third one, or add it to the model. ### Step 8: From association to an experiment Everything so far is observational. Priya watched what happened. She did not change anything. So she can’t say that a bundle offer would raise order value, or that a loyalty scheme would. To find out, she needs an experiment: show an offer to a random half of orders, and compare. The practical question is how long that takes. The answer depends on how big an uplift she wants to detect and how much orders vary. [10] The variation is large. The standard deviation of order amount is ₹1,560.90, the same size as the mean. On the log scale it is 0.695. The 600 is Part 1’s planning figure, set a little above the 515 break-even so the forecast has headroom. from statsmodels.stats.power import TTestIndPower power = TTestIndPower() n_per_arm = power.solve_power(effect_size=np.log(1.10) / sd_log, alpha=0.05, power=0.8) At a 5% significance level and 80% power, these are the orders needed per arm, testing either the typical order (log scale) or the mean order value: - 5% uplift: 3,184 orders per arm for the typical order (10.6 months at 600 orders a month), 6,313 for the mean (21.0 months) - 10% uplift: 835 per arm (2.8 months) for the typical order, 1,579 (5.3 months) for the mean - 15% uplift: 389 per arm (1.3 months) for the typical order, 703 (2.3 months) for the mean She checks the formula by simulation: 2,000 simulated experiments with a true 10% uplift added to her own order data. The log-scale test at 835 orders per arm detects it 80.0% of the time. The mean-based test at 1,579 per arm detects it only 74.9% of the time, about five points short of the 80% target, because skew makes the formula optimistic for means. (With 2,000 runs, each rate is good to about a point, so 74.9% is clearly short.) She would round up. The simulation applies a 10% lift to every order, so it models the most generous version of an offer. A real promotion that lifts only some orders would need its own simulation. Two curves of orders are needed per arm against uplift to detect. The mean-based test needs about twice as many as the log-scale test. > What this means for Priya: A test for a 10% uplift is feasible: about 2.8 months if she cares about the typical order, about 5.3 months if she needs the mean, which is what revenue follows. A 5% uplift would take 10 months or more. That is the honest answer: at her volume, she can only learn about moderate effects. She also knows what to decide in advance: the metric, the uplift worth detecting, and the number of orders. Your turn: replace sd_log with the standard deviation of your own log column, set your own orders per month, and read off how long your test must run. ### Behind the curtain: the hidden group is back As in Part 1, I wrote the data generator, so I can check what the analysis found. The same two groups from Part 1 are still there: typical customers and premium customers (12% of orders). I made premium customers more likely to be returning customers, and made returning customers more likely to use WhatsApp. The order amounts were never changed. - Premium share of returning customers’ orders: 24.4%. For new customers: 7.4%. - Premium share by channel: WhatsApp 20.3%, Website 14.5%, Instagram 8.7%, Marketplace 4.6%. Now look inside each group. Among typical customers, the median order is ₹948 for returning customers (201 orders) and ₹1,026 for new customers (676 orders), p = 0.295. Among premium customers, it is ₹3,822 (65 orders) against ₹4,021 (54 orders), p = 0.545. Once you know the group, there is no detectable difference for returning customers (the premium groups are small, 65 and 54 orders). So “returning customers spend more” was true on average, but not because they were returning. They were more often premium customers. The WhatsApp story had the same root, one step further back. And Marketplace’s lower orders? That fits its smallest premium share, 4.6% (not tested directly). Two more honest notes on the generator. I created Items_Per_Order from the order amount, so that the two would move together. In a real shop, the arrow runs the other way. And Priya never sees the premium label. That is the limit of this analysis, and it points to a natural next question: how to find hidden groups from the data itself. ### What Priya learned - The data type chooses the tool. Number vs number: correlation and regression. Number vs categories: t-test, Mann-Whitney, ANOVA, Kruskal-Wallis. Category vs category: chi-square. - Check two correlations. Pearson (0.805) and Spearman (0.586) told different stories about the same data. - Log scales tame fans. The log-log elasticity of 0.751 came with better-behaved residuals than the ₹664-per-item line. - Averages and medians answer different questions. Returning customers had a ₹550 higher mean but only a ₹101 higher median, with an interval that includes zero. - Test, then correct. Six comparisons carry a 26.5% false-alarm risk. After correction, only one channel pair stands out. - Confounding hides in plain sight. WhatsApp’s +10.3% fell to +0.4% once customer type was in the model. - Experiments need a plan. A 10% uplift needs 835 to 1,579 orders per arm. ### What this analysis can’t tell you - The data is synthetic. Real data has seasons, trends and customers who appear many times. - Everything here is observational. Associations are not causes. - The tests treat orders as independent. In real data, one customer’s orders are related. - Regression adjusts only for variables you measured. Unmeasured confounders, like the premium group here, remain. - Cells with few orders (8 returning Marketplace orders) are too thin to interpret. - Many tests are run in this article, but only the pairwise comparisons in Step 6 are corrected for multiple testing. Treat an isolated p-value, like the Marketplace result in Step 7, as a lead. - The sample-size numbers assume 600 orders a month (assumed, not measured) and an even split into two arms, with the same percentage lift on every order. ### which test for which data - Number vs number: scatter plot, Pearson and Spearman, then regression. - Number vs two groups: Welch t-test and Mann-Whitney, with an effect size and a bootstrap interval for the median difference. - Number vs three or more groups: ANOVA and Kruskal-Wallis, then Tukey or Holm-corrected post-hoc tests. - Category vs category: chi-square test and Cramér’s V, after checking expected counts. - Every comparison: check assumptions first, report an effect size, and ask what else is different about the groups. ### The takeaway The dashboard said WhatsApp customers spend more. The numbers said something more careful. Customers who shop on WhatsApp are mostly returning customers. Returning customers have a heavier upper tail. And behind them sits a small group of premium customers. Two variables gave Priya what one could not: a relationship she can measure, groups she can compare, and the habit of asking whether a difference belongs to the channel or to who is in it. Don’t ask “which group is bigger?” Ask “what else is different about them?” Have you ever moved budget based on an average that turned out to be hiding another variable? I’d like to hear how it went. ### Technical notes [1] Dropping vs imputing. Median imputation is a mild choice for a single variable. In a two-variable analysis, a filled-in value has no relationship to the other column, so it pulls correlations and slopes toward zero. With 3 of 999 orders it hardly matters here (996 rows instead of 999), but with more missing data, use multiple imputation or a method that handles missingness. [2] Pearson and Spearman. Pearson r = cov(x, y) / (sx · sy) measures linear association and is sensitive to extreme values. Spearman’s rho is Pearson’s r applied to the ranks, so it measures whether y tends to rise with x, in a straight line or not. The Pearson interval uses the Fisher z transform. The Spearman interval here is a bootstrap with 2,000 resamples. [3] Linear regression assumptions. Ordinary least squares assumes a linear relationship, independent errors, constant error variance and, for reliable intervals in small samples, roughly normal residuals. The Breusch-Pagan test checks constant variance (a small p means the spread changes). With unequal spread, the slope is still unbiased but its standard error is unreliable. Robust (HC) standard errors are another remedy, and the safer choice for the slope interval in Step 3, which is the classical one. R² is the share of variance explained, on the scale being modelled. [4] Log-log models. If log(y) = a + b · log(x), a 1% change in x goes with about a b% change in y, so b is an elasticity, and a k-fold change in x multiplies y by k^b. Exponentiating a prediction gives the typical (geometric-mean or median-style) amount, not the average. Recovering the mean needs a smearing correction. R² on the log scale cannot be compared with R² on the raw scale. [5] Two-group comparisons. Welch’s t-test does not assume equal variances and is a safe default. Levene’s test (centred on the median) checks equal spread. Cohen’s d = mean difference / pooled standard deviation (0.2 small, 0.5 medium, 0.8 large by convention). Mann-Whitney U tests whether a random value from one group tends to be larger than one from the other. It is not, in general, a test of medians. The common-language effect size is U / (n1 × n2), here 0.557. The interval for the median difference is a percentile bootstrap with 10,000 resamples. [6] Chi-square test of independence. Expected count = row total × column total / n. χ² = Σ (observed − expected)² / expected, with (r − 1)(c − 1) degrees of freedom. The test is reliable when expected counts are at least about 5. Cramér’s V = √(χ² / (n · min(r − 1, c − 1))) runs from 0 to 1. For a table with two rows, 0.1, 0.3 and 0.5 are the usual small, medium and large marks. Standardised (Pearson) residuals larger than about 2 in size flag cells that differ from independence. [7] ANOVA and Kruskal-Wallis. One-way ANOVA compares means across k groups with an F test. Eta-squared = between-group sum of squares / total sum of squares, the share of variance explained. Kruskal-Wallis is the rank-based counterpart, and epsilon-squared = H / (n − 1). Both are omnibus tests: they say whether any group differs, not which. [8] Multiple comparisons. With m independent tests at level α, the chance of at least one false positive is 1 − (1 − α)^m, here 1 − 0.9⁵⁶ = 26.5%. The pairwise tests are not fully independent, so this is an approximation. Tukey’s HSD controls the family-wise error rate for all pairwise mean comparisons. The Holm method adjusts a set of p-values step by step and is never less powerful than Bonferroni. [9] Confounding. A confounder is related both to the thing you compare (channel) and to the outcome (order amount). Stratifying (comparing inside each level) and regression adjustment are two ways to account for a measured confounder. In the log regression, exp(coefficient) − 1 is the percentage difference in the typical order. Adjustment cannot handle confounders you did not measure. Randomised experiments are the standard way around the problem. [10] Power and sample size. For a two-sample comparison, n per arm ≈ 2 × (z for α/2 + z for power)² / d², where d is the effect divided by the standard deviation. With α = 0.05 and 80% power, that is about 2 × (1.96 + 0.84)² / d². For the log-scale test, d = ln(1.10) / 0.695 = 0.137. For the mean test, d = 0.10 × ₹1,556.90 / ₹1,560.90 ≈ 0.10. The script uses the TTestIndPower class from statsmodels, then checks the result by simulation. A test on the mean costs more than a test on log amounts because skew inflates the standard deviation relative to the uplift. Randomise orders to arms, and fix the metric and the stopping rule before starting. ### Connect With Me If you found this analysis valuable: - Clap for this article. - Share your thoughts in the comments. - Follow for more such content To reproduce the analysis, run generate_data.py (Part 1), then generate_data_v2.py, then analyze_part2.1.py. It needs numpy, pandas, scipy, statsmodels, matplotlib and seaborn. For the Python code used in this article, follow: https://github.com/sawantpramod/WhatsApp-Orders-Are-17-Bigger.-Should-She-Move-the-Budget-Bivariate-analysis --- WhatsApp Orders Are 17% Bigger. Should She Move the Budget? was originally published in Python in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.
INSTAGRAMWHATS APP
MediumMedium
ARTIFICIAL INTELLIGENCE

Long Video Transcription Is a Checkpointing Problem

### Build a resumable Python pipeline with FFmpeg, Whisper, SQLite, overlap ownership, and timestamp QA A two-minute clip can be transcribed with one function call. A two-hour recording is a different engineering problem. The difficult part is not splitting a file. It is making the job restartable, deterministic, and timestamp-safe when a process crashes, a model call times out, or one chunk must be retried. If a pipeline cannot prove which chunks are complete, which configuration produced them, and which transcript owns the overlap between adjacent chunks, it is not ready for long video. This tutorial builds a local pipeline around five ideas: 1. probe the media before decoding it; 2. create overlapping audio chunks; 3. checkpoint every chunk in SQLite; 4. assign every word in an overlap to exactly one chunk; 5. reject a merged transcript when timestamp invariants fail. The examples use FFmpeg, ffprobe, OpenAI Whisper, and Python's standard sqlite3 module. The same control plane can wrap another speech-to-text engine. > This article is for developers building batch transcription, searchable video archives, lecture processing, or media-ingestion systems. It does not cover model training or live streaming. ### Why split -> transcribe -> concatenate fails The naive pipeline looks reasonable: video.mp4 -> 15-minute WAV files -> Whisper -> concatenate JSON It still leaves several unanswered questions. - If chunk 17 fails, must chunks 0 through 16 run again? - If the source file changes but keeps the same filename, can old results be reused? - If the last word of chunk 4 also appears at the start of chunk 5, which copy survives? - If Whisper returns a local timestamp of 00:12, what is its position in the original video? - How do we detect a timestamp regression before indexing the transcript? These are checkpointing and data-integrity questions. Treating them as such produces a much simpler system. ### The manifest is the source of truth Use SQLite rather than filenames as state. A manifest row should identify both the input and the transcription configuration. from __future__ import annotations import hashlib import json import sqlite3 from dataclasses import asdict, dataclass from pathlib import Path @dataclass(frozen=True) class Config: model: str = "small" language: str | None = None chunk_seconds: int = 900 overlap_seconds: int = 4 sample_rate: int = 16000 def sha256_file(path: Path, block_size: int = 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as file: while block := file.read(block_size): digest.update(block) return digest.hexdigest() def config_id(config: Config) -> str: payload = json.dumps(asdict(config), sort_keys=True).encode() return hashlib.sha256(payload).hexdigest()[:16] def open_db(path: Path) -> sqlite3.Connection: db = sqlite3.connect(path) db.execute(""" CREATE TABLE IF NOT EXISTS chunks ( source_hash TEXT NOT NULL, config_id TEXT NOT NULL, chunk_index INTEGER NOT NULL, start_sec REAL NOT NULL, end_sec REAL NOT NULL, audio_path TEXT NOT NULL, status TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, result_json TEXT, error TEXT, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (source_hash, config_id, chunk_index) ) """) db.commit() return db The compound key prevents two common forms of cache poisoning: reusing output from a different source and reusing output created with a different model or chunk policy. For very large files, hashing the entire source has a cost. You can instead store a fast fingerprint based on file size, modification time, and sampled byte ranges, then compute a full hash asynchronously. The trade-off is explicit: a fast fingerprint is cheaper but provides weaker identity guarantees. ### Probe before decoding ffprobe can return machine-readable stream metadata without converting the media. import json import subprocess def probe(path: Path) -> dict: command = [ "ffprobe", "-v", "error", "-show_entries", "format=duration:stream=index,codec_type,codec_name,channels,sample_rate", "-of", "json", str(path), ] result = subprocess.run(command, check=True, capture_output=True, text=True) data = json.loads(result.stdout) audio_streams = [s for s in data.get("streams", []) if s.get("codec_type") == "audio"] if not audio_streams: raise ValueError("The input contains no audio stream") duration = float(data["format"]["duration"]) if duration <= 0: raise ValueError(f"Invalid duration: {duration}") return {"duration": duration, "audio": audio_streams[0]} This gate stops silent videos, malformed duration values, and unexpected stream layouts from entering an expensive transcription stage. ### Build chunks with overlap A boundary can land in the middle of a word. A small overlap gives the model context on both sides, but that overlap must later have a single owner. import math def chunk_plan(duration: float, size: int, overlap: int): if overlap >= size: raise ValueError("overlap must be smaller than chunk size") plan = [] for index in range(math.ceil(duration / size)): logical_start = index * size logical_end = min((index + 1) * size, duration) decode_start = max(0.0, logical_start - overlap) decode_end = min(duration, logical_end + overlap) plan.append((index, decode_start, decode_end)) return plan def extract_audio(source: Path, output: Path, start: float, end: float, sample_rate: int): output.parent.mkdir(parents=True, exist_ok=True) command = [ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-ss", f"{start:.3f}", "-to", f"{end:.3f}", "-i", str(source), "-vn", "-ac", "1", "-ar", str(sample_rate), "-c:a", "pcm_s16le", str(output), ] subprocess.run(command, check=True) The logical chunk remains 15 minutes. The decoded file is wider by four seconds on either side, except at the beginning and end of the source. For stream-copy video segmentation, the FFmpeg segment muxer documentation warns that requested split times may not match exact output boundaries unless keyframes align. Extracting decoded mono audio avoids video-keyframe ownership, but you should still measure the actual output duration. ### Transcribe one chunk and checkpoint immediately OpenAI Whisper’s transcription implementation can emit word timestamps when word_timestamps=True. Save each successful result before moving to the next chunk. import whisper def transcribe_pending(db: sqlite3.Connection, model, language: str | None): rows = db.execute(""" SELECT source_hash, config_id, chunk_index, start_sec, audio_path FROM chunks WHERE status IN ('pending', 'failed') ORDER BY chunk_index """).fetchall() for source_hash, cfg_id, index, offset, audio_path in rows: db.execute(""" UPDATE chunks SET status='running', attempts=attempts+1, error=NULL, updated_at=CURRENT_TIMESTAMP WHERE source_hash=? AND config_id=? AND chunk_index=? """, (source_hash, cfg_id, index)) db.commit() try: result = model.transcribe( audio_path, language=language, word_timestamps=True, verbose=False, ) db.execute(""" UPDATE chunks SET status='done', result_json=?, updated_at=CURRENT_TIMESTAMP WHERE source_hash=? AND config_id=? AND chunk_index=? """, (json.dumps(result, ensure_ascii=False), source_hash, cfg_id, index)) except Exception as exc: db.execute(""" UPDATE chunks SET status='failed', error=?, updated_at=CURRENT_TIMESTAMP WHERE source_hash=? AND config_id=? AND chunk_index=? """, (repr(exc), source_hash, cfg_id, index)) finally: db.commit() A production worker should also reclaim rows left in running after a lease timeout. Do not blindly retry forever: distinguish transient errors from corrupt inputs, and cap attempts. ### Give the overlap one owner Text de-duplication after concatenation is fragile. Repeated phrases are legitimate speech, and punctuation can change between chunks. Timestamp ownership is more deterministic. For chunk i, keep words whose midpoint falls inside its logical interval: def owned_words(result: dict, decode_start: float, logical_start: float, logical_end: float): owned = [] for segment in result.get("segments", []): for word in segment.get("words", []): start = decode_start + float(word["start"]) end = decode_start + float(word["end"]) midpoint = (start + end) / 2 if logical_start <= midpoint < logical_end: owned.append({ "start": round(start, 3), "end": round(end, 3), "text": word["word"], }) return owned The midpoint rule does not claim that Whisper alignment is perfect. It only ensures that adjacent chunks cannot both own the same time region. Keep raw chunk output so a suspicious boundary can be reviewed later. ### Add a timestamp QA gate Before publishing or indexing, validate the merged stream. def validate_words(words: list[dict], source_duration: float) -> list[str]: issues = [] previous_start = -1.0 for index, word in enumerate(words): start, end = word["start"], word["end"] if not (0 <= start <= end <= source_duration + 0.5): issues.append(f"word {index}: invalid range {start}..{end}") if start + 0.05 < previous_start: issues.append(f"word {index}: timestamp regression") if end - start > 5.0: issues.append(f"word {index}: unusually long word span") previous_start = start return issues Useful additional checks include empty chunks surrounded by non-empty chunks, implausibly high words-per-second, repeated boundary n-grams, and a final timestamp far shorter than the probed media duration. These should create review tasks, not silently rewrite the transcript. ### Recovery semantics matter more than concurrency Parallel workers are tempting, but define recovery first. - Idempotency: rerunning a completed chunk with the same source and config must not create another logical result. - Leases: a running row needs a timestamp so an abandoned job can be reclaimed. - Atomicity: write the result and mark the row done in one transaction. - Backpressure: limit concurrent decoding and model inference independently. - Provenance: store model name, language, decoder settings, and code version with the job. Once these invariants hold, concurrency is an optimization rather than a source of mystery. ### When not to chunk Use a single pass when the input is short, memory fits comfortably, and the engine already offers reliable server-side checkpointing. Use a managed transcription service when operational simplicity matters more than local control. For privacy-sensitive media, a local pipeline may be preferable, but only if model files, logs, and temporary WAV files are handled under the same security policy as the source video. ### Conclusion Long video transcription is reliable when the pipeline can answer three questions after any interruption: what input and configuration produced this output, which chunks are complete, and who owns every timestamp? FFmpeg handles deterministic extraction, SQLite records durable progress, Whisper supplies word-level timing, and a small QA gate prevents broken timelines from reaching search or RAG systems. The model is only one component; the checkpoint protocol is the product-grade part. If you need the workflow without maintaining the chunking and recovery layer yourself, transcribe video to text with Video Transcriber AI and export the result for downstream indexing or analysis. Disclosure: I work with the team behind Video Transcriber AI. The engineering approach and code in this article are based on public documentation and can be used independently of the product. ### Resources - FFmpeg formats documentation: segment muxer - FFprobe documentation - OpenAI Whisper transcription implementation - Python sqlite3 documentation --- Long Video Transcription Is a Checkpointing Problem was originally published in Python in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.
TIMESTAMP QAWHISPER
MediumMedium
ARTIFICIAL INTELLIGENCE

Speaker Labels Are Not Ground Truth

### Build a turn-level transcript QA gate with Python before diarized speech enters search, summaries, or meeting notes A diarized transcript looks authoritative: [00:14:08] SPEAKER_01: We can ship on Friday. [00:14:11] SPEAKER_02: I still need legal approval. The labels, however, are model output — not verified identity. A diarization system can split one person into two labels, merge two similar voices, miss an overlap, or create rapid A-B-A speaker flips around a single utterance. Once those labels enter a summary, the error becomes a false attribution. The safest design is not “trust the best model.” It is validate the structure, rank suspicious regions, and preserve a path back to the audio. This tutorial builds a Python QA gate for turn-level transcripts. It checks timestamp integrity, overlaps, gaps, micro-turns, speaker fragmentation, and text density. It then merges nearby findings into review windows and extracts the corresponding audio with FFmpeg. > This article is for developers processing interviews, podcasts, support calls, and meetings. The gate detects anomalies; it does not prove a speaker’s real-world identity. ### A useful transcript contract Start with a small, explicit data model. A turn needs a label, a time range, and text. from __future__ import annotations from dataclasses import dataclass @dataclass(frozen=True) class Turn: speaker: str start: float end: float text: str @property def duration(self) -> float: return self.end - self.start @dataclass(frozen=True) class Finding: rule: str severity: str start: float end: float message: str An input JSON file can remain engine-agnostic: { "duration": 73.4, "turns": [ {"speaker": "SPEAKER_00", "start": 0.52, "end": 4.91, "text": "Let's review the launch plan."}, {"speaker": "SPEAKER_01", "start": 4.78, "end": 7.10, "text": "The landing page is ready."} ] } Keeping the transcript contract separate from the diarization library lets the same QA layer accept Whisper-derived output, pyannote.audio results, or a hosted API response. ### Rule 1: reject impossible time ranges Structural errors should fail the gate immediately. They are not “low confidence”; they are invalid data. def structural_findings(turns: list[Turn], media_duration: float) -> list[Finding]: findings: list[Finding] = [] for index, turn in enumerate(turns): if not turn.speaker.strip(): findings.append(Finding( "missing_speaker", "error", turn.start, turn.end, f"turn {index} has no speaker label", )) if turn.start < 0 or turn.end <= turn.start: findings.append(Finding( "invalid_range", "error", turn.start, turn.end, f"turn {index} has an invalid time range", )) if turn.end > media_duration + 0.25: findings.append(Finding( "past_media_end", "error", turn.start, turn.end, f"turn {index} ends after the media duration", )) if not turn.text.strip(): findings.append(Finding( "empty_text", "warning", turn.start, turn.end, f"turn {index} has no text", )) return findings The 250 ms tolerance absorbs small rounding differences between decoders. Choose and document a tolerance instead of silently clamping every timestamp. ### Rule 2: measure overlap instead of deleting it People interrupt each other. Overlap is not automatically an error. The suspicious condition is an overlap that conflicts with what your downstream format can represent. def overlap_findings(turns: list[Turn], warn_after: float = 1.5) -> list[Finding]: findings = [] ordered = sorted(turns, key=lambda item: (item.start, item.end)) for left, right in zip(ordered, ordered[1:]): overlap = left.end - right.start if overlap <= 0 or left.speaker == right.speaker: continue severity = "warning" if overlap < warn_after else "review" findings.append(Finding( "cross_speaker_overlap", severity, right.start, min(left.end, right.end), f"{left.speaker} and {right.speaker} overlap for {overlap:.2f}s", )) return findings Do not “fix” overlap by shortening one turn to the boundary. That destroys evidence. If a consumer requires non-overlapping turns, create a derived exclusive timeline while retaining the original diarization. pyannote.audio explicitly distinguishes regular diarization from exclusive diarization for this reason. ### Rule 3: find micro-turns and text-density outliers A 100 ms speaker turn containing eight words is probably a timestamp or attribution problem. A short “yes” may be legitimate. Combine duration and content rather than applying one threshold blindly. import re WORD_RE = re.compile(r"\b\w+(?:['-]\w+)?\b", re.UNICODE) def density_findings(turns: list[Turn]) -> list[Finding]: findings = [] for turn in turns: word_count = len(WORD_RE.findall(turn.text)) duration = max(turn.duration, 0.001) words_per_second = word_count / duration if duration < 0.35 and word_count >= 3: findings.append(Finding( "micro_turn", "review", turn.start, turn.end, f"{word_count} words assigned to a {duration:.2f}s turn", )) elif duration >= 1.0 and words_per_second > 6.0: findings.append(Finding( "text_density", "warning", turn.start, turn.end, f"unusually high text density: {words_per_second:.1f} words/s", )) return findings Six words per second is a triage threshold, not a universal law. Languages, tokenization, crosstalk, and transcription conventions change the distribution. Calibrate against your own accepted corpus and store the threshold with the QA report. ### Rule 4: detect A-B-A fragmentation One frequent diarization artifact is a very short label inserted between two turns from the same speaker. def fragmentation_findings( turns: list[Turn], bridge_max: float = 1.0, outer_gap_max: float = 0.6, ) -> list[Finding]: findings = [] ordered = sorted(turns, key=lambda item: item.start) for first, middle, third in zip(ordered, ordered[1:], ordered[2:]): same_outer = first.speaker == third.speaker different_middle = middle.speaker != first.speaker gaps_are_small = ( middle.start - first.end <= outer_gap_max and third.start - middle.end <= outer_gap_max ) if same_outer and different_middle and middle.duration <= bridge_max and gaps_are_small: findings.append(Finding( "aba_fragmentation", "review", first.end, third.start, f"short {middle.speaker} turn splits two {first.speaker} turns", )) return findings This is a review signal, not permission to relabel automatically. The middle turn could be a real backchannel such as “right” or “okay.” Audio review decides. ### Rule 5: surface long unexplained gaps Long gaps may be silence, music, an ASR miss, or a diarization miss. If the pipeline has a voice-activity detector, compare its speech regions with the transcript. Without one, flag only unusually long gaps. def gap_findings(turns: list[Turn], gap_after: float = 8.0) -> list[Finding]: findings = [] ordered = sorted(turns, key=lambda item: item.start) for left, right in zip(ordered, ordered[1:]): gap = right.start - left.end if gap >= gap_after: findings.append(Finding( "long_gap", "warning", left.end, right.start, f"no transcript turn for {gap:.2f}s", )) return findings If music or intentional silence is common, treat the gap as informational. A QA gate should reduce review work, not manufacture alarms. ### Merge findings into review windows Five rules may report the same 10-second region. Reviewers need one clip, not five. def merge_windows(findings: list[Finding], padding: float = 2.0, join_gap: float = 1.0): spans = sorted( (max(0.0, f.start - padding), f.end + padding, f) for f in findings ) windows = [] for start, end, finding in spans: if not windows or start > windows[-1]["end"] + join_gap: windows.append({"start": start, "end": end, "findings": [finding]}) else: windows[-1]["end"] = max(windows[-1]["end"], end) windows[-1]["findings"].append(finding) return windows Padding preserves the conversational lead-in and response. It is easier to judge a label when the reviewer hears context rather than an isolated syllable. ### Extract review audio with FFmpeg from pathlib import Path import subprocess def extract_review_clip(source: Path, output: Path, start: float, end: float): command = [ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-ss", f"{start:.3f}", "-to", f"{end:.3f}", "-i", str(source), "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", str(output), ] subprocess.run(command, check=True) Name clips with their source hash and millisecond boundaries, then include the associated rule IDs in a JSON report. That makes every correction auditable. ### Assemble the gate def run_qa(turns: list[Turn], media_duration: float): findings = [ *structural_findings(turns, media_duration), *overlap_findings(turns), *density_findings(turns), *fragmentation_findings(turns), *gap_findings(turns), ] return findings, merge_windows(findings) Use a two-level outcome: - block when timestamps are invalid, the media duration is inconsistent, or required fields are missing; - review when the structure is valid but patterns are suspicious. This separation prevents a heuristic threshold from stopping every job while still keeping corrupt data out of production. ### What the gate cannot tell you It cannot establish that SPEAKER_01 is Alice. It cannot determine consent to record, infer legal ownership, or guarantee that overlapping speech was transcribed correctly. It also should not automatically merge labels across a long recording solely because their embeddings are similar. Identity requires external evidence: enrollment audio, participant metadata, or human confirmation. Keep anonymous labels unless that evidence exists. ### Conclusion Speaker diarization becomes safer when labels are treated as claims with evidence, not facts. Validate impossible ranges first, rank statistical anomalies second, and send compact, contextual audio windows to a reviewer. Most importantly, preserve the raw model output alongside any corrected timeline. If you need a starting transcript with speaker labels and timestamps before running this QA layer, transcribe audio to text with Audio Converter AI, then export the result into your validation workflow. Disclosure: I work with the team behind Audio Converter AI. The QA rules and code in this article are product-independent and based on public technical documentation. ### Resources - pyannote.audio speaker diarization - pyannote.audio diarization pipeline source - FFmpeg documentation - JSON Schema object reference --- Speaker Labels Are Not Ground Truth was originally published in Python in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.
LEFTRIGHTRESPEAKER 01