Medium
New Python content every day. Follow to join our 3.5M+ monthly readers.
python.plainenglish.ioNew Python content every day. Follow to join our 3.5M+ monthly readers.
python.plainenglish.iodef 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.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.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.[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.