<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Selina Mangaroo on Medium]]></title>
        <description><![CDATA[Stories by Selina Mangaroo on Medium]]></description>
        <link>https://medium.com/@selinamangaroo?source=rss-fa2ce83a0390------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wo4zYhaIm4VRfTCxZ77egw.jpeg</url>
            <title>Stories by Selina Mangaroo on Medium</title>
            <link>https://medium.com/@selinamangaroo?source=rss-fa2ce83a0390------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:13:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@selinamangaroo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Built and Shipped a Production App with Claude Code. The Lesson: Know What You’re Building.]]></title>
            <link>https://medium.com/@selinamangaroo/i-built-and-shipped-a-production-app-with-claude-code-the-lesson-know-what-youre-building-a1730ad5dbdf?source=rss-fa2ce83a0390------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1730ad5dbdf</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[developer-tools]]></category>
            <dc:creator><![CDATA[Selina Mangaroo]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 00:58:12 GMT</pubDate>
            <atom:updated>2026-08-19T00:58:12.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Stylized terminal window displaying a large ‘CLAUDE CODE’ graphic, with a welcome message and a login successful prompt." src="https://cdn-images-1.medium.com/max/1024/1*KZUh-L8pebU7iKsE-mloaQ.png" /></figure><p>I spent the last few weeks building a mobile app for museum staff using Claude Code as my main development tool. The app, CollectiveAccess Condition Check, lets gallery and museum staff create and manage artwork condition reports from their phones, with everything syncing directly into CollectiveAccess, an open-source collection management system used by hundreds of institutions worldwide.</p><h3>What Was Built</h3><p>The technical scope was Expo / React Native targeting both iOS and Android, a full CollectiveAccess GraphQL API integration, JWT auth with token refresh, dynamic form rendering from CA’s schema at runtime, media upload via a custom HTTP endpoint, lazy-loaded artwork thumbnails, per-installation branding from a remote config file, and full report editing. Then the usual App Store pipeline on top of that.</p><p>I’m a full-stack developer, comfortable with React and React Native. Claude Code for app development was new to me going into this.</p><h3>The Part That Actually Impressed Me</h3><p>Interface work. When I could describe clearly what a screen needed to do, what data it showed, what actions it supported, what the loading and error states looked like, Claude Code produced complete, working React Native screens fast. Not prototypes. Screens I could ship.</p><p>The dynamic form renderer was probably the best example. CollectiveAccess returns field definitions from its schema at runtime: bundle codes, data types, list items, container subelements. The app needed to turn that into a working form with different input types depending on what came back. I explained the data structure and what each field type should render as. It built it. It worked on the first pass.</p><p>That kind of thing, where the logic is clear and the output is predictable, is genuinely where Claude Code earns its place.</p><h3>The Part That Frustrated Me</h3><p>Claude Code fills gaps. That sounds helpful, but in practice it means if you don’t specify something, it will decide for you. Sometimes the decision is fine. Sometimes it isn’t. And because it touches multiple files in one pass, you don’t always notice the decisions it made until something breaks later.</p><p>Early in the project, before I had solid documentation in place, this happened more than I would have liked. I’d give it a feature prompt, it would implement it, and alongside the feature there would be a handful of small decisions I didn’t ask for. Such as an error handled differently than I wanted, a state variable added somewhere it shouldn’t be, a pattern that diverged from what the rest of the codebase was doing.</p><p>None of it was catastrophic. But it added up to review time and left me with more than a couple of questions.</p><p>The other frustration was specific to this project: CollectiveAccess has a lot of quirks that Claude Code had no way of knowing about. The search endpoint returns media: null for artwork records. The identifier field in mutations must be a quoted string or CA silently accepts the call and does nothing. Status values are stored as numeric codes internally so sending the idno string gets accepted without error but never applied. The schema query only supports one level of subelements.</p><p>These aren’t Claude Code’s fault. They’re real API behaviors that required Postman testing, server log analysis, and back-and-forth with CA developers to figure out. But they’re a good illustration of where AI assistance hits its limit, when the problem requires investigation, not implementation.</p><h3>The N+1 Issue</h3><p>One moment that stands out, the app was slow on the home screen. Looking at the server logs, the reason was obvious. For every condition report in the list, the app was making a separate API call to fetch its workflow status. Fifty reports meant fifty-one server requests every time the home screen loaded.</p><p>When I brought this to Claude Code with a clear description of the problem, it moved fast. It identified the issue, proposed a fix, and implemented it. Paginate at 25 records per page, fetch status only for the current page. That session felt like the collaboration working properly. I brought the diagnosis, it handled the implementation.</p><h3>What Made the Biggest Difference</h3><p>Documentation. Specifically, maintaining a CLAUDE.md file that Claude Code reads before every session which has project conventions, architecture decisions, known CA API behaviors, coding rules. Alongside that, a CA GraphQL query reference with confirmed syntax and known quirks, and a PRD with feature specs and open questions.</p><p>Once those were in place, the output quality improved noticeably. Claude Code stopped making decisions about things that were already decided. Queries matched the confirmed syntax. Patterns stayed consistent across files.</p><p>If I were starting this project over, I’d invest heavily in those documents before writing any code. What this process taught me is that specificity isn’t optional. It’s the work.</p><h3>What I’d Tell Someone Starting a Similar Project</h3><p>Be specific about what you don’t want, not just what you do. “Don’t touch the auth service” is a valid instruction. Negative constraints matter as much as positive ones.</p><p>Review everything it touches. Claude Code often modifies multiple files in one pass. The primary file is obvious. The supporting files are easy to miss, and that’s where subtle problems tend to hide.</p><p>Treat your prompts like proper tickets. Before writing one, ask: if a developer received this, would they know exactly what to build and exactly what to leave alone? If the answer is no, the prompt needs more work.</p><p>And accept that external API integration is still your job. Postman testing, reading documentation, talking to the people who maintain the API, none of that goes away. Claude Code implements solutions well once you understand the problem. Understanding the problem is still on you.</p><h3>Where It Lands</h3><p>Claude Code made this project faster. Not uniformly, some parts would have been faster without it, but on balance the development moved more quickly than it would have otherwise.</p><p>The gap between a good prompt and a vague prompt is large. With clear specifications and maintained documentation, the output is often exactly what you needed. Without them, you spend the time you saved on cleanup instead.</p><p>For production work on a real API with real quirks, it’s a tool worth having. It’s not a replacement for knowing what you’re building.</p><p><em>Building something similar? I’d genuinely love to hear how you approached it — drop a comment with your problem type and stack. And if this saved you a debugging session, a follow means I’ll keep writing things like it.</em></p><p>Check out more of my writing on <a href="https://medium.com/@selinamangaroo">Medium</a>!</p><p>Read more of my work and projects at <a href="https://selinamangaroo.com/">SelinaMangaroo.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1730ad5dbdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Before You Build a Custom Image Classifier: Lessons From a Real Production Project]]></title>
            <link>https://medium.com/@selinamangaroo/before-you-build-a-custom-image-classifier-lessons-from-a-real-production-project-dce87e285e92?source=rss-fa2ce83a0390------2</link>
            <guid isPermaLink="false">https://medium.com/p/dce87e285e92</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Selina Mangaroo]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 00:13:40 GMT</pubDate>
            <atom:updated>2026-04-14T00:13:40.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b38CNzeiZL_A1JM0y0-jyw.png" /></figure><p><em>What a Keith Haring motif detector taught me about data, model selection, and the gap between tutorial accuracy and real-world performance.</em></p><p>If you’ve ever thought about building a custom image classifier for an actual production use case with real stakeholders and messy data — this article is for you.</p><p>I spent several weeks building a computer vision pipeline to automatically identify motifs in Keith Haring artworks: things like his Radiant Baby, Barking Dog, Dancing Figures, and other recurring visual symbols. Seventeen classes in total, often appearing simultaneously in the same image. The kind of problem that looks tractable until you’re six weeks in and your model is confidently predicting nothing.</p><p>This is what I wish someone had told me before I started.</p><h3>What Kind of Problem Are You Actually Solving?</h3><p>Before you write a single line of code, make sure you’ve correctly identified your problem type.</p><p>My project is a <strong>multi-label classification</strong> problem — a single image can have multiple correct answers simultaneously. A Haring piece might contain Dancing Figures, a Barking Dog, and a Radiant Baby all at once. This is fundamentally different from single-label classification, and if you set it up wrong from the start, nothing downstream will work correctly.</p><p>Multi-label classification means your model is making 17 independent yes/no decisions rather than one choice between 17 options. That changes how you set up almost everything. You need BCEWithLogitsLoss rather than CrossEntropyLoss — because you&#39;re measuring 17 separate binary probabilities, not competing alternatives. Your output layer needs one sigmoid per class rather than a softmax across all classes, for the same reason. And your evaluation metrics need to be computed per-class, not just globally, or you&#39;ll miss the fact that your model has completely given up on your rarest classes. Get any of these wrong and your model will train silently, your logs will look fine, and your predictions will be garbage.</p><p>I used PyTorch with a ResNet50 backbone, transfer learning from ImageNet weights, and K-fold cross-validation across 990 images. The stack was reasonable. What came next was a lesson in how many ways a reasonable stack can still quietly fail you.</p><h3>Silent Failures Are the Most Dangerous Kind</h3><p>The first training run looked promising. Loss was going down. The model appeared to be learning. I felt good about it.</p><p>Then I ran predictions and got literally zero outputs across hundreds of images.</p><p>Days of debugging later, I found three configuration errors hiding in plain sight. The most damaging: I had omitted pos_weight from the loss function. In multi-label classification, most classes appear in a small fraction of your images. Without pos_weight, the model learns almost immediately that predicting &quot;not present&quot; for everything is almost always correct — and it stops trying. F1 near zero. Logs looking healthy. Total failure.</p><p>The second bug was a hardcoded confidence threshold set to 0.50 in one place and 0.35 in another. The model was generating predictions; the threshold was cutting them all before output.</p><p><strong>Before you scale up to real data, build a minimal test:</strong> create a tiny synthetic dataset where you know exactly what the output should be, run your full pipeline on it, and verify that predictions are actually reaching your output layer. ML pipelines don’t throw exceptions when they fail silently — you have to design the checks yourself.</p><h3>Your Architecture Is Probably Not the Problem</h3><p>When predictions were finally coming through but performance on new images was still poor, my instinct was to blame the model. Maybe ResNet50 wasn’t deep enough. So I tested ResNet101, then EfficientNet-B4.</p><p>Both performed worse.</p><p>That result forced a more honest diagnosis. With 990 images split across 17 motifs, several classes had fewer than 20 examples. After K-fold splits, some motifs had 15 training examples per fold. No architecture learns reliably from 15 examples. Bigger models actually compounded the problem — they need more data to generalize, and we didn’t have it.</p><p><strong>The practical rule of thumb:</strong> if your custom classifier isn’t working, reach for more data before you reach for a bigger model. Architecture decisions matter at the margin. Data volume determines whether learning is possible at all. Start with a well-understood baseline like ResNet50 and only consider alternatives once you’ve ruled out data as the constraint.</p><h3>Label Quality Is Load-Bearing</h3><p>Midway through the project we uncovered a more fundamental problem: the training labels themselves were inconsistent.</p><p>A reviewer had tagged thousands of images under time pressure and without strict guidelines. The result was systematic omission — images containing three motifs were tagged with one. The model learned contradictory things simultaneously: that Barking Dog appears without Dancing Figures (wrong), and that Dancing Figures doesn’t appear in images where it clearly does (also wrong).</p><p>This explained one of the most persistent failure modes throughout the project: the model over-predicted Barking Dog on new images. Because Barking Dog had been tagged in isolation on images that actually contained multiple motifs, the model associated it with a much broader range of visual contexts than was accurate. No amount of threshold tuning or architecture switching fixed it, because the problem was baked into the ground truth.</p><p><strong>If you’re setting up a labeling workflow:</strong> write annotation guidelines before your reviewers touch a single image. Define what counts as a positive label. Specify how to handle ambiguous cases. Have a domain expert review a sample before full labeling begins. The model can only learn what the labels teach it — inconsistent labels teach it inconsistent things.</p><h3>Three Things That Actually Moved the Needle</h3><p>Once the fundamentals were solid, three techniques produced real improvements.</p><p><strong>Human-in-the-loop fine-tuning.</strong> After each prediction run, a reviewer corrected mistakes and flagged errors. Those corrections fed back into fine-tuning with a higher loss weight — errors on reviewed images cost the model twice as much during training. Over two cycles, average F1 went from 0.344 to 0.986 on validation data. The review loop isn’t a patch. It’s the mechanism.</p><p><strong>Test time augmentation (TTA).</strong> Instead of passing each image through the model once at inference time, run it five times with slight variations — a brightness shift, contrast change, horizontal flip, and centre crop — then average the confidence scores. A genuine motif scores consistently across all five passes. A false positive doesn’t. This reduced our worst false positive problem (Barking Dog) by 62% without any retraining.</p><p><strong>Per-motif confidence thresholds.</strong> Rather than a single threshold for all classes, set a higher bar for specific problematic ones. Barking Dog required 75% confidence rather than the default 35%. Blunt, but effective when you have a well-understood failure mode and a class that consistently over-fires.</p><h3>The Gap Between Validation Accuracy and Production Reality</h3><p>Here’s the number that matters less than it looks: 0.986 average F1 after fine-tuning. Here’s the number that matters more: on genuinely unseen images from different artwork styles, time periods, and photographic conditions, performance drops considerably.</p><p>That gap is real, and every production ML project has a version of it. Validation metrics measure performance on data that looks like your training data. Production performance measures generalization to data that doesn’t. The only things that close this gap are more diverse labeled data, more fine-tuning cycles incorporating real-world feedback, and time.</p><p>If you’re planning a similar project: allocate 80% of your planning time to data strategy — sourcing, cleaning, labeling guidelines, and review workflow. Allocate the remaining 20% to model selection. I did it the other way around and it cost me months.</p><h3>What to Take Into Your Own Project</h3><p>To summarize what’s actually transferable:</p><ul><li>Identify your problem type precisely before writing any code — multi-label and single-label classification require different setups throughout</li><li>Validate your full pipeline on a toy example before using real data; silent failures are common and hard to catch otherwise</li><li>In multi-label classification, always set pos_weight on your loss function to handle class imbalance</li><li>Start with ResNet50 or an equivalent baseline and rule out data volume as a constraint before changing architecture</li><li>Write annotation guidelines before labeling begins; inconsistent labels actively teach the model wrong things</li><li>Treat human review as a first-class part of your pipeline, not a one-time fix</li></ul><p>The project is still running. The model is still improving. And the data is still finding new ways to surprise me.</p><p><em>Building something similar? I’d genuinely love to hear how you approached it — drop a comment with your problem type and stack. And if this saved you a debugging session, a follow means I’ll keep writing things like it.</em></p><p>Check out more of my writing on <a href="https://medium.com/@selinamangaroo">Medium</a>!</p><p>Read more of my work and projects at <a href="https://selinamangaroo.com/">SelinaMangaroo.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dce87e285e92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Fold Cross-Validation: A Guide to Reliable Model Evaluation]]></title>
            <link>https://medium.com/@selinamangaroo/k-fold-cross-validation-a-guide-to-reliable-model-evaluation-bbc1561e6f50?source=rss-fa2ce83a0390------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc1561e6f50</guid>
            <category><![CDATA[machine-learning-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Selina Mangaroo]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 22:28:51 GMT</pubDate>
            <atom:updated>2026-03-18T22:28:51.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hM-6-pQjcW_dyASJ0UqpA.png" /></figure><p>When you train a machine learning model, one of the most important questions you need to answer is, how well will this model actually perform on new data?</p><p>The most basic approach is to split your data into a training set and a test set to train on one and evaluate on the other. However, your results depend heavily on which data ended up in your test set. You can get unlucky with the split and you might overestimate or underestimate your model’s true performance.</p><p>K-fold cross-validation solves this by making your evaluation process more systematic and trustworthy.</p><h3>The Problem with a Single Split</h3><p>Imagine you have 1,000 images and you randomly set aside 200 for testing. That 200 might happen to be slightly easier or harder than the rest. Either way, your evaluation score reflects that particular split, not your model’s true ability to generalize.</p><p>Now imagine doing that split five different ways and averaging the results. You would feel a lot more confident in that number.</p><p>That’s the core idea behind K-fold cross-validation.</p><h3>How It Works</h3><ol><li>Your dataset is divided into <em>k</em> equally-sized groups, called <strong>folds</strong></li><li>Your model trains on <em>k-1</em> folds and is evaluated on the <strong>remaining fold</strong></li><li>This repeats <em>k</em> times, each fold gets a turn as the test set exactly once</li><li>Your final score is the <strong>average across all k runs</strong></li></ol><p>With k=5, you get five separate training and evaluation cycles. Every data point is used for both training and testing, just never at the same time.</p><h3>Implementing K-Fold in Python</h3><p>Here’s a simple, runnable example using scikit-learn:</p><pre>from sklearn.datasets import load_iris<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import KFold, cross_val_score<br>import numpy as np<br><br># Load a sample dataset<br>data = load_iris()<br>X, y = data.data, data.target<br><br># Define the model<br>model = RandomForestClassifier(random_state=42)<br><br># Set up 5-fold cross-validation<br>kf = KFold(n_splits=5, shuffle=True, random_state=42)<br><br># Run cross-validation<br>scores = cross_val_score(model, X, y, cv=kf, scoring=&#39;accuracy&#39;)<br><br>print(f&quot;Accuracy per fold: {scores}&quot;)<br>print(f&quot;Mean accuracy:     {scores.mean():.4f}&quot;)<br>print(f&quot;Standard deviation: {scores.std():.4f}&quot;)<br><br>```<br>**Output:**<br>Accuracy per fold: [0.9667 1.0000 0.9333 0.9667 0.9667]<br>Mean accuracy:     0.9667<br>Standard deviation: 0.0211<br>```</pre><p>Two numbers matter here: the mean accuracy and the standard deviation. A low standard deviation means your model performs consistently regardless of which data it sees and that’s a good sign. High variance across folds suggests the model is sensitive to the specific training data, which is worth investigating.</p><h3><strong>Choosing the Right K</strong></h3><p>For most projects, <strong>k=5 or k=10</strong> is a solid starting point. There’s no universal right answer, it depends on your dataset size and how much compute you have available.</p><h3>Other Variants</h3><p>Standard K-fold is a great default, but there are a few variants worth knowing about:</p><ul><li><strong>Stratified K-Fold</strong> — ensures each fold mirrors the class distribution of the full dataset, useful when your classes are imbalanced</li><li><strong>Repeated K-Fold</strong> — runs the full K-fold process multiple times with different random splits for a more stable estimate</li><li><strong>Leave-One-Out (LOOCV)</strong> — a special case where <em>k</em> equals the number of data points, the most thorough option but impractical on large datasets</li></ul><p>Each of these is available in scikit-learn and follows the same pattern as the example above.</p><h3>Nested Cross-Validation</h3><p>Once you’re comfortable with standard K-fold, there’s an important limitation to be aware of, one that becomes relevant as soon as you start tuning your model.</p><h4>The problem</h4><p>Most machine learning models have <strong>hyperparameters</strong> which are settings you choose before training that control how the model learns. For a neural network, this might be the learning rate or number of layers.</p><p>Finding the best hyperparameters typically involves trying many combinations and picking whichever performs best on your validation data. This is called <strong>hyperparameter tuning</strong>.</p><p>Here’s the problem: if you use the same data to both tune your hyperparameters and evaluate your model’s final performance, your results are overly optimistic. The model has effectively been exposed to the test data during the tuning process, even if indirectly. It hasn’t truly been tested on data it’s never influenced.</p><h4>The solution</h4><p>Nested cross-validation addresses this by separating the two concerns entirely using two loops:</p><ul><li><strong>Outer loop </strong>is responsible for evaluating generalization performance. It holds out a test set that is never touched during tuning.</li><li><strong>Inner loop </strong>runs inside each outer training set, trying different hyperparameter combinations and selecting the best one.</li></ul><p>The key distinction: the inner loop finds the best hyperparameters, and the outer loop then evaluates how well a model trained with those hyperparameters actually generalizes. Because the outer test set was never involved in tuning, the performance estimate is genuinely unbiased.</p><pre>from sklearn.model_selection import GridSearchCV, KFold, cross_val_score<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.datasets import load_iris<br><br>data = load_iris()<br>X, y = data.data, data.target<br><br># Inner loop: hyperparameter tuning<br>inner_cv = KFold(n_splits=3, shuffle=True, random_state=42)<br>param_grid = {&#39;n_estimators&#39;: [50, 100], &#39;max_depth&#39;: [None, 5]}<br><br>model = GridSearchCV(<br>    RandomForestClassifier(random_state=42),<br>    param_grid,<br>    cv=inner_cv<br>)<br><br># Outer loop: unbiased performance evaluation<br>outer_cv = KFold(n_splits=5, shuffle=True, random_state=42)<br>scores = cross_val_score(model, X, y, cv=outer_cv, scoring=&#39;accuracy&#39;)<br><br>print(f&quot;Nested CV accuracy per fold: {scores}&quot;)<br>print(f&quot;Mean accuracy: {scores.mean():.4f}&quot;)</pre><p>Notice that GridSearchCV handles the inner loop automatically. It tries every combination in param_grid across the inner folds and selects the best. The outer cross_val_score then evaluates that whole process as if it were a single model, giving you an honest performance estimate.</p><p>Nested cross-validation is more computationally expensive, but if you’re tuning and evaluating at the same time, it’s the right tool for the job.</p><h3>Wrapping Up</h3><p>K-fold cross-validation is one of those foundational techniques that makes your results genuinely more trustworthy. By training and evaluating across multiple splits rather than just one, you get a much clearer picture of how your model will perform on data it hasn’t seen before. Start with standard K-fold, reach for Stratified K-fold when your classes are imbalanced, and use nested cross-validation any time hyperparameter tuning is involved. It’s a small addition to your pipeline with a significant payoff.</p><h3>Further Reading</h3><ul><li><a href="https://scikit-learn.org/stable/modules/cross_validation.html">Scikit-learn Cross-validation</a></li></ul><p><em>Have questions about k-fold cross validation or want to share your experiences? Drop a comment below! And if you found this helpful, consider following for more tech related tutorials and content.</em></p><p>Check out more of my writing on <a href="https://medium.com/@selinamangaroo">Medium</a>!</p><p>Read more of my work and projects at <a href="https://selinamangaroo.com/">SelinaMangaroo.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc1561e6f50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Scikit-Learn Metrics: A Beginner’s Guide to Evaluating Your ML Models]]></title>
            <link>https://medium.com/@selinamangaroo/understanding-scikit-learn-metrics-a-beginners-guide-to-evaluating-your-ml-models-36e71f6a5fb8?source=rss-fa2ce83a0390------2</link>
            <guid isPermaLink="false">https://medium.com/p/36e71f6a5fb8</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Selina Mangaroo]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 02:57:45 GMT</pubDate>
            <atom:updated>2026-02-10T02:57:45.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*X7LMbfEKR7gaJ-iuRZpWzA.png" /></figure><p>When training machine learning models, writing code that runs without errors is just the beginning. The real question is: <strong>how good is your model?</strong> This is where evaluation metrics come in. In this article, I’ll walk you through the essential scikit-learn metrics using a real-world multi-label image classification project as our guide.</p><h3>Why Metrics Matter</h3><p>Imagine you’ve built a model to classify artwork images. Your code runs perfectly, training completes, and you get predictions. Success, right? Not so fast. Without proper metrics, you have no idea if your model is actually learning anything useful or just making random guesses.</p><p>Metrics give you concrete numbers that answer critical questions:</p><ul><li>Is my model improving during training?</li><li>How well does it perform on unseen data?</li><li>Which classes is it struggling with?</li><li>Should I continue training or try a different approach?</li></ul><h3>What We’re Measuring</h3><p>Before diving into code, let’s understand what we’re measuring. In classification tasks, we compare:</p><ul><li><strong>Predictions</strong>: What your model thinks the answer is</li><li><strong>Ground Truth</strong>: What the answer actually is</li></ul><p>From these comparisons, we calculate metrics that quantify performance.</p><h3>Setting Up A Simple Example</h3><p>Let’s start with a basic binary classification problem. Imagine classifying whether an image contains a dog or not:</p><pre>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score<br>import numpy as np<br><br># Ground truth: 1 = dog present, 0 = no dog<br>y_true = np.array([1, 0, 1, 1, 0, 1, 0, 0, 1, 1])<br><br># Model predictions<br>y_pred = np.array([1, 0, 1, 0, 0, 1, 0, 1, 1, 1])<br><br># Calculate metrics<br>accuracy = accuracy_score(y_true, y_pred)<br>precision = precision_score(y_true, y_pred)<br>recall = recall_score(y_true, y_pred)<br>f1 = f1_score(y_true, y_pred)<br><br>print(f&quot;Accuracy:  {accuracy:.2f}&quot;)<br>print(f&quot;Precision: {precision:.2f}&quot;)<br>print(f&quot;Recall:    {recall:.2f}&quot;)<br>print(f&quot;F1 Score:  {f1:.2f}&quot;)</pre><p><strong>Output:</strong></p><pre>Accuracy:  0.80<br>Precision: 0.83<br>Recall:    0.83<br>F1 Score:  0.83</pre><h3>Understanding Each Metric</h3><p><strong>Accuracy</strong> tells you what percentage of predictions were correct overall. Here, 80% of predictions matched reality.</p><p><strong>Precision</strong> answers: “Of all the times my model said ‘dog’, how often was it right?” Here, 83% of positive predictions were correct.</p><p><strong>Recall</strong> answers: “Of all the actual dogs, how many did my model find?” Our model found 83% of all dogs.</p><p><strong>F1 Score</strong> is the harmonic mean of precision and recall, giving you a single balanced metric. It’s especially useful when you care about both false positives and false negatives.</p><h3>Real-World Complexity: Multi-Label Classification</h3><p>In real projects, things get more complex. My artwork classification project deals with <strong>multi-label classification</strong>, where each image can have multiple labels simultaneously. An artwork might contain both a “heart” and a “cross”, for example.</p><p>Here’s how to handle this:</p><pre>from sklearn.metrics import classification_report, multilabel_confusion_matrix<br>import numpy as np<br><br># Example: 5 images, 3 possible labels (heart, cross, dog)<br># Each image can have multiple labels<br>y_true = np.array([<br>    [1, 0, 0],  # Image 1: has heart<br>    [1, 1, 0],  # Image 2: has heart and cross<br>    [0, 0, 1],  # Image 3: has dog<br>    [1, 1, 1],  # Image 4: has all three<br>    [0, 1, 0]   # Image 5: has cross<br>])<br><br>y_pred = np.array([<br>    [1, 0, 0],  # Correct<br>    [1, 0, 0],  # Missed the cross<br>    [0, 0, 1],  # Correct<br>    [1, 1, 0],  # Missed the dog<br>    [0, 1, 0]   # Correct<br>])<br><br># Calculate metrics for each label<br>label_names = [&#39;heart&#39;, &#39;cross&#39;, &#39;dog&#39;]<br><br>print(&quot;Per-Label Performance:&quot;)<br>print(&quot;-&quot; * 50)<br><br>for i, label in enumerate(label_names):<br>    precision = precision_score(y_true[:, i], y_pred[:, i], zero_division=0)<br>    recall = recall_score(y_true[:, i], y_pred[:, i], zero_division=0)<br>    f1 = f1_score(y_true[:, i], y_pred[:, i], zero_division=0)<br>    <br>    print(f&quot;{label:10} - Precision: {precision:.2f}, Recall: {recall:.2f}, F1: {f1:.2f}&quot;)</pre><p><strong>Output:</strong></p><pre>Per-Label Performance:<br>--------------------------------------------------<br>heart      - Precision: 1.00, Recall: 1.00, F1: 1.00<br>cross      - Precision: 1.00, Recall: 0.67, F1: 0.80<br>dog        - Precision: 1.00, Recall: 0.50, F1: 0.67</pre><p>This shows that our model is perfect at detecting hearts but struggles more with dogs (only finding 50% of them).</p><h3>Monitoring Training Progress</h3><p>During model training, you want to track metrics at each epoch. Here’s a complete, runnable example:</p><pre>from sklearn.metrics import f1_score<br>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>from torch.utils.data import DataLoader, TensorDataset<br>import numpy as np<br><br>def evaluate_model(model, dataloader, device):<br>    &quot;&quot;&quot;<br>    Evaluate model performance on a dataset.<br>    Returns average F1 score across all labels.<br>    &quot;&quot;&quot;<br>    model.eval()<br>    all_predictions = []<br>    all_targets = []<br>    <br>    with torch.no_grad():<br>        for inputs, targets in dataloader:<br>            inputs = inputs.to(device)<br>            outputs = model(inputs)<br>            predictions = (torch.sigmoid(outputs) &gt; 0.5).cpu().numpy()<br>            <br>            all_predictions.append(predictions)<br>            all_targets.append(targets.numpy())<br>    <br>    # Combine all batches<br>    y_pred = np.vstack(all_predictions)<br>    y_true = np.vstack(all_targets)<br>    <br>    # Calculate F1 for each label and average<br>    f1_scores = []<br>    for i in range(y_true.shape[1]):<br>        f1 = f1_score(y_true[:, i], y_pred[:, i], zero_division=0)<br>        f1_scores.append(f1)<br>    <br>    return np.mean(f1_scores), f1_scores<br><br># Define a simple neural network<br>class SimpleClassifier(nn.Module):<br>    def __init__(self, input_size, num_labels):<br>        super(SimpleClassifier, self).__init__()<br>        self.fc1 = nn.Linear(input_size, 128)<br>        self.fc2 = nn.Linear(128, 64)<br>        self.fc3 = nn.Linear(64, num_labels)<br>        self.relu = nn.ReLU()<br>    <br>    def forward(self, x):<br>        x = self.relu(self.fc1(x))<br>        x = self.relu(self.fc2(x))<br>        x = self.fc3(x)<br>        return x<br><br># Create sample data (replace with your actual data)<br>num_samples = 1000<br>input_size = 50<br>num_labels = 3<br><br>X_train = torch.randn(num_samples, input_size)<br>y_train = torch.randint(0, 2, (num_samples, num_labels)).float()<br><br>X_val = torch.randn(200, input_size)<br>y_val = torch.randint(0, 2, (200, num_labels)).float()<br><br># Create dataloaders<br>train_dataset = TensorDataset(X_train, y_train)<br>val_dataset = TensorDataset(X_val, y_val)<br><br>train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)<br>val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)<br><br># Setup model, optimizer, and loss<br>device = torch.device(&#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;)<br>model = SimpleClassifier(input_size, num_labels).to(device)<br>optimizer = optim.Adam(model.parameters(), lr=0.001)<br>criterion = nn.BCEWithLogitsLoss()  # For multi-label classification<br><br># Training loop with metric tracking<br>num_epochs = 10<br>train_losses = []<br>val_f1_scores = []<br><br>for epoch in range(num_epochs):<br>    # Training phase<br>    model.train()<br>    epoch_loss = 0<br>    <br>    for inputs, targets in train_loader:<br>        inputs, targets = inputs.to(device), targets.to(device)<br>        <br>        optimizer.zero_grad()<br>        outputs = model(inputs)<br>        loss = criterion(outputs, targets)<br>        loss.backward()<br>        optimizer.step()<br>        <br>        epoch_loss += loss.item()<br>    <br>    avg_train_loss = epoch_loss / len(train_loader)<br>    train_losses.append(avg_train_loss)<br>    <br>    # Evaluation phase<br>    avg_f1, per_label_f1 = evaluate_model(model, val_loader, device)<br>    val_f1_scores.append(avg_f1)<br>    <br>    print(f&quot;Epoch {epoch+1}/{num_epochs}&quot;)<br>    print(f&quot;  Train Loss: {avg_train_loss:.4f}&quot;)<br>    print(f&quot;  Val F1:     {avg_f1:.4f}&quot;)<br>    print(f&quot;  Per-label:  {[f&#39;{f:.2f}&#39; for f in per_label_f1]}&quot;)</pre><p><strong>Example Output:</strong></p><pre>Epoch 1/10<br>  Train Loss: 0.6234<br>  Val F1:     0.3521<br>  Per-label:  [&#39;0.45&#39;, &#39;0.32&#39;, &#39;0.28&#39;]<br><br>Epoch 2/10<br>  Train Loss: 0.5123<br>  Val F1:     0.4789<br>  Per-label:  [&#39;0.52&#39;, &#39;0.48&#39;, &#39;0.43&#39;]<br>...</pre><p>This complete example shows everything you need: model definition, data loading, and training with metrics.</p><h3>Advanced: Classification Report</h3><p>Scikit-learn’s classification_report gives you a comprehensive summary in one call:</p><pre>from sklearn.metrics import classification_report<br><br># Using our earlier multi-label example<br>y_true = np.array([<br>    [1, 0, 0],<br>    [1, 1, 0],<br>    [0, 0, 1],<br>    [1, 1, 1],<br>    [0, 1, 0]<br>])<br>y_pred = np.array([<br>    [1, 0, 0],<br>    [1, 0, 0],<br>    [0, 0, 1],<br>    [1, 1, 0],<br>    [0, 1, 0]<br>])<br><br>label_names = [&#39;heart&#39;, &#39;cross&#39;, &#39;dog&#39;]<br><br># Generate report for each label<br>for i, label in enumerate(label_names):<br>    print(f&quot;\n=== {label.upper()} ===&quot;)<br>    print(classification_report(<br>        y_true[:, i], <br>        y_pred[:, i],<br>        target_names=[&#39;absent&#39;, &#39;present&#39;]<br>    ))</pre><p><strong>Output:</strong></p><pre>=== HEART ===<br>              precision    recall  f1-score   support<br>      absent       1.00      1.00      1.00         2<br>     present       1.00      1.00      1.00         3<br>    accuracy                           1.00         5<br>   macro avg       1.00      1.00      1.00         5<br>weighted avg       1.00      1.00      1.00         5<br><br>=== CROSS ===<br>              precision    recall  f1-score   support<br>      absent       1.00      1.00      1.00         2<br>     present       1.00      0.67      0.80         3<br>    accuracy                           0.80         5<br>   macro avg       1.00      0.83      0.90         5<br>weighted avg       1.00      0.80      0.88         5</pre><p>This report shows precision, recall, F1, and support (number of examples) for each class, plus macro and weighted averages.</p><h3>Average Strategies for Multi-Label</h3><p>Scikit-learn offers different averaging strategies:</p><pre># Macro: unweighted mean (treats all labels equally)<br>f1_macro = f1_score(y_true, y_pred, average=&#39;macro&#39;)<br><br># Weighted: weighted by support (more common labels have more influence)<br>f1_weighted = f1_score(y_true, y_pred, average=&#39;weighted&#39;)<br><br># Samples: for multi-label (evaluates each sample)<br>f1_samples = f1_score(y_true, y_pred, average=&#39;samples&#39;)</pre><h3>Common Pitfalls to Avoid</h3><h3>1. Evaluating on Training Data</h3><p>Never measure metrics on the same data you trained on. Always use a separate validation set:</p><pre># WRONG<br>model.fit(X_train, y_train)<br>f1 = f1_score(y_train, model.predict(X_train))  # Overly optimistic<br><br># RIGHT<br>model.fit(X_train, y_train)<br>f1 = f1_score(y_val, model.predict(X_val))  # Realistic estimate</pre><h3>2. Ignoring Class Imbalance</h3><p>If 95% of your data is class 0, a model that always predicts 0 gets 95% accuracy but is useless. Use F1 score or weighted metrics instead.</p><h3>3. Not Checking Individual Classes</h3><p>Average metrics can hide problems. A 0.8 average F1 might include one class with 0.1 F1:</p><pre># Always inspect per-class metrics<br>for i in range(num_classes):<br>    f1 = f1_score(y_true[:, i], y_pred[:, i], zero_division=0)<br>    print(f&quot;Class {i}: F1 = {f1:.2f}&quot;)</pre><h3>Conclusion</h3><p>Metrics are your model’s report card. They tell you not just whether your code works, but whether your model actually learns. Start simple with accuracy and F1 score, then add more sophisticated metrics as your projects grow in complexity. Your future self will thank you when metrics help you catch problems early!</p><h3>Further Reading</h3><ul><li><a href="https://scikit-learn.org/stable/modules/model_evaluation.html">Scikit-learn Metrics Documentation</a></li><li><a href="https://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html">Understanding Precision-Recall</a></li><li><a href="https://scikit-learn.org/stable/modules/model_evaluation.html#multilabel-ranking-metrics">Multi-label Classification Metrics</a></li></ul><p><em>Have questions about metrics or want to share your experiences? Drop a comment below! And if you found this helpful, consider following for more tech related tutorials and content.</em></p><p>Read more of my work and projects at <a href="https://selinamangaroo.com/">SelinaMangaroo.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36e71f6a5fb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to the ChatGPT Batch API]]></title>
            <link>https://medium.com/@selinamangaroo/a-guide-to-the-chatgpt-batch-api-b80564daeca5?source=rss-fa2ce83a0390------2</link>
            <guid isPermaLink="false">https://medium.com/p/b80564daeca5</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-tools]]></category>
            <dc:creator><![CDATA[Selina Mangaroo]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 17:38:10 GMT</pubDate>
            <atom:updated>2025-12-23T03:18:56.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsC0P3t31ox8LXiDCTHM-w.png" /></figure><p>As engineers, most of us spend our time building systems that need to run efficiently, predictably, and within budget. As AI becomes a bigger part of our workflow, one of the first challenges we hit is scaling. How do you reliably process hundreds or thousands of LLM requests without hitting rate limits, blowing up costs, or writing endless retry loops?</p><p>If you’ve ever run a large loop of ChatGPT API calls, you’ve likely experienced:</p><ul><li>Rate limit throttling</li><li>Exponential backoff chaos</li><li>Increasing latency as jobs pile up</li><li>Inconsistent failures</li><li>Higher cost due to repeated overhead</li><li>The risk of partial or silent failure</li></ul><p>The ChatGPT Batch API was introduced to solve exactly these scaling problems and in practice it behaves much more like a data-processing engine than a chat API.</p><h3>What Is the ChatGPT Batch API?</h3><p>The Batch API lets you send a large list of requests to ChatGPT all at once, instead of calling the API repeatedly inside a loop.</p><p>Instead of:</p><pre>for item in dataset:<br>    client.responses.create(...)</pre><p>you generate a single input file containing all requests, submit a batch job, and later download a results file with one line per result.</p><p>It can assist in:</p><ul><li>data processing</li><li>large transformations</li><li>bulk text generation</li><li>batch labeling</li><li>content cleanup</li><li>any workload with many small or medium-sized AI tasks</li></ul><h3>Why Use the Batch API (and why I switched)</h3><h4>1. It dramatically lowers cost</h4><p>Batch requests are significantly cheaper than hitting the regular API endpoint repeatedly. Depending on the model you use, it can cut the cost by 50%. If your workflow involves hundreds or thousands of tasks, cost drops fast.</p><h4>2. No more rate limit issues</h4><p>Instead of fighting the API with retries, sleeps, or workarounds, the Batch API handles throughput internally. So no need to babysit when you can just check the job status.</p><h4>3. Perfect for overnight or automated pipelines</h4><p>You submit a job, and you are guaranteed results within a 24hr period or less. It’s ideal for scheduled jobs, ETL pipelines, or any asynchronous workflow.</p><h4>4. Cleaner, easier-to-maintain code</h4><p>Instead of dozens of lines dealing with exceptions and retry logic, your process becomes:</p><pre>create batch file → submit → wait → download results</pre><p>It’s simple and predictable.</p><h4>5. More consistent results</h4><p>Large loops tend to fail unpredictably. Batch jobs either succeed or fail as a whole and you get structured logs and result mappings.</p><h3>How the Batch API Workflow Actually Works</h3><p>Below is an example using Python and the OpenAI SDK. It shows:</p><ol><li>Building the .jsonl batch file</li><li>Uploading it</li><li>Submitting the batch</li><li>Polling for status</li><li>Hydrating the results</li></ol><h4>1. Creating the .jsonl Batch File</h4><p>Each line represents a single API call.</p><pre>import json<br><br>def create_batch_file(input_items, path=&quot;batch_input.jsonl&quot;):<br>    with open(path, &quot;w&quot;) as f:<br>        for i, text in enumerate(input_items):<br>            record = {<br>                &quot;custom_id&quot;: f&quot;job_{i}&quot;,<br>                &quot;method&quot;: &quot;POST&quot;,<br>                &quot;url&quot;: &quot;/v1/responses&quot;,<br>                &quot;body&quot;: {<br>                    &quot;model&quot;: &quot;gpt-4.1-mini&quot;,<br>                    &quot;input&quot;: f&quot;Rewrite this more clearly: {text}&quot;<br>                }<br>            }<br>            f.write(json.dumps(record) + &quot;\n&quot;)<br>    return path</pre><h4>2. Uploading the Batch File</h4><p>You send your .jsonl file to OpenAI using the Files API.</p><pre>from openai import OpenAI<br>client = OpenAI()<br><br>batch_file = client.files.create(<br>    file=open(&quot;batch_input.jsonl&quot;, &quot;rb&quot;),<br>    purpose=&quot;batch&quot;<br>)</pre><h4>3. Submitting the Batch Job</h4><pre>batch = client.batches.create(<br>    input_file_id=batch_file.id,<br>    endpoint=&quot;/v1/responses&quot;,<br>    completion_window=&quot;24h&quot;  # Must be 24h at this time<br>)<br><br>print(&quot;Batch submitted:&quot;, batch.id)</pre><h4>4. Polling for Batch Status</h4><p>You can poll the batch status or just come back later.</p><pre>def wait_for_batch(batch_id):<br>    while True:<br>        batch = client.batches.retrieve(batch_id)<br>        print(&quot;Status:&quot;, batch.status)<br><br>        if batch.status in (&quot;completed&quot;, &quot;failed&quot;, &quot;expired&quot;, &quot;cancelled&quot;):<br>            return batch</pre><h4>5. Downloading and Hydrating the Results</h4><p>You get a .jsonl file back where each line contains the output for the corresponding request.</p><p>Your script reads it, maps each result back to your custom_id, and continues with whatever comes next.</p><pre>batch = wait_for_batch(batch.id)<br><br># Once completed, download the output file<br>output_file_id = batch.output_file_id<br>output_file = client.files.content(output_file_id)<br># Save to disk<br>with open(&quot;batch_output.jsonl&quot;, &quot;wb&quot;) as f:<br>    f.write(output_file)</pre><p>Now parse the results:</p><pre>results = {}<br><br>with open(&quot;batch_output.jsonl&quot;, &quot;r&quot;) as f:<br>    for line in f:<br>        row = json.loads(line)<br>        custom_id = row[&quot;custom_id&quot;]<br>        output_text = row[&quot;response&quot;][&quot;output&quot;][0][&quot;content&quot;][0][&quot;text&quot;]<br>        results[custom_id] = output_text</pre><p>results is now a dictionary keyed by your original request IDs.</p><h3>When You Shouldn’t Use the Batch API</h3><p>Batch isn’t a replacement for the normal ChatGPT API.<br>It’s not meant for:</p><ul><li>chatbots</li><li>real-time apps</li><li>interactive features</li><li>in-browser experiences</li><li>workflows where users expect instant responses</li></ul><p>Think of it as a background worker, not a live API.</p><h3>Final Thoughts</h3><p>Instead of treating the model like a real-time service for everything, we have a way to use it like a true data-processing tool that is optimized for throughput, cost efficiency, and reliability.</p><p>If your workflow involves more than a handful of ChatGPT calls at a time, Batch is worth trying. It simplifies everything while giving you more control over structure, cost, and performance.</p><p>And once you start using it, you’ll wonder why you didn’t do it earlier.</p><p>Read more of my work and projects at <a href="https://selinamangaroo.com/">SelinaMangaroo.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b80564daeca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Whisper and Pyannote for Easy Speaker Diarization]]></title>
            <link>https://medium.com/@selinamangaroo/using-whisper-and-pyannote-for-easy-speaker-diarization-2feb2f67da30?source=rss-fa2ce83a0390------2</link>
            <guid isPermaLink="false">https://medium.com/p/2feb2f67da30</guid>
            <category><![CDATA[pyannote]]></category>
            <category><![CDATA[openai-whisper]]></category>
            <category><![CDATA[speech-to-text-conversion]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <dc:creator><![CDATA[Selina Mangaroo]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 22:16:53 GMT</pubDate>
            <atom:updated>2025-12-23T03:18:33.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_OzVGwLoM-Ukw1_WQIlyUw.png" /></figure><p>Have you ever listened to a long meeting recording and wondered who said what and when? This is where speaker diarization comes in. In this post, we’ll explore what speaker diarization is, why it’s useful, a short history of the field, and how modern tools like <strong>Whisper</strong> and <strong>pyannote.audio</strong> make it accessible for developers today.</p><p>I’ll also share a simple Python script that ties everything together.</p><h3>What is Speaker Diarization?</h3><p>Speaker diarization is the process of segmenting an audio stream into parts corresponding to who spoke when<strong>.</strong><br> In other words, it answers two key questions:</p><ol><li>Who is speaking?</li><li>When are they speaking?</li></ol><p>The output isn’t just a transcript, it’s a structured record of the conversation, often like:</p><pre>[00:00 - 00:12] Speaker 1: Hello everyone, thanks for joining.  <br>[00:12 - 00:20] Speaker 2: Hi, happy to be here.</pre><h3>Use Cases</h3><ul><li><strong>Meetings &amp; interviews</strong>: Tagging transcripts so you can follow speakers.</li><li><strong>Podcasts &amp; media</strong>: Identifying guests vs hosts automatically.</li><li><strong>Call centers</strong>: Separating agent vs customer speech.</li><li><strong>Accessibility</strong>: Cleaner captions with speaker labels.</li><li><strong>Research &amp; archives</strong>: Structuring oral histories or long conversations.</li></ul><h3>A Short History</h3><p>Speaker diarization started gaining traction in the 1990s, especially for automatically structuring broadcast news recordings. Early methods were pretty basic: they looked at patterns in the raw audio signal (like pitch and tone) and grouped together parts that sounded similar.</p><p>Later, researchers developed mathematical representations of voices called i-vectors and x-vectors. Think of these as fingerprints for each speaker’s voice. This made it much easier to tell people apart in recordings, and diarization accuracy improved a lot.</p><p>Today, deep learning has taken it even further. Libraries like <strong>pyannote.audio</strong> provide pre-trained neural networks that can recognize and separate voices far more reliably than older techniques.</p><h3>The pyannote Library</h3><p><a href="https://github.com/pyannote/pyannote-audio"><strong>pyannote.audio</strong></a> is a Python library designed for speaker diarization. It provides pre-trained models that:</p><ul><li>Detect speech segments.</li><li>Extract speaker embeddings.</li><li>Cluster embeddings to assign speaker labels.</li></ul><h3>Whisper + pyannote Together</h3><p><strong>OpenAI’s Whisper</strong> is excellent at generating transcripts from audio, but it doesn’t tell you who spoke. <strong>Pyannote</strong> doesn’t transcribe, but it does diarization really well.</p><p>By combining the two, we get the best of both worlds:</p><ul><li><strong>Whisper →</strong> transcript text.</li><li><strong>pyannote →</strong> speaker segmentation.</li><li><strong>Merge →</strong> speaker-attributed transcripts.</li></ul><h3>Minimal Example Script</h3><p>Here’s a script to get you started. I have a working GitHub repository for this located <a href="https://github.com/SelinaMangaroo/whisper-pyannote-diarization">here</a>. Please check it out.</p><pre>import os<br>import whisper<br>import warnings<br>from dotenv import load_dotenv<br>from pyannote.audio import Pipeline<br><br>warnings.filterwarnings(&quot;ignore&quot;)<br><br># === Load environment variables ===<br>load_dotenv()<br>HUGGINGFACE_TOKEN = os.getenv(&quot;HUGGINGFACE_TOKEN&quot;)<br>AUDIO_FILE = os.getenv(&quot;AUDIO_FILE&quot;, &quot;example.wav&quot;)<br><br>if not HUGGINGFACE_TOKEN:<br>    raise ValueError(&quot;HUGGINGFACE_TOKEN not set in your .env file&quot;)<br>if not os.path.exists(AUDIO_FILE):<br>    raise ValueError(f&quot;Audio file not found: {AUDIO_FILE}&quot;)<br><br># === Load models ===<br>print(&quot;Loading Whisper model...&quot;)<br>whisper_model = whisper.load_model(&quot;base&quot;)<br><br>print(&quot;Loading pyannote diarization pipeline...&quot;)<br>diarization_pipeline = Pipeline.from_pretrained(<br>    &quot;pyannote/speaker-diarization@2.1&quot;,<br>    use_auth_token=HUGGINGFACE_TOKEN<br>)<br><br>def main():<br>    print(f&quot;\nProcessing audio file: {AUDIO_FILE}\n&quot;)<br><br>    # Step 1: Transcribe with Whisper<br>    print(&quot;Step 1/3: Transcribing audio with Whisper...&quot;)<br>    transcript = whisper_model.transcribe(AUDIO_FILE)[&quot;segments&quot;]<br>    print(&quot;Transcription complete.\n&quot;)<br><br>    # Step 2: Run diarization with pyannote<br>    print(&quot;Step 2/3: Running speaker diarization with pyannote...&quot;)<br>    diarization = diarization_pipeline(AUDIO_FILE)<br>    print(&quot;Diarization complete.\n&quot;)<br><br>    # Step 3: Merge results<br>    print(&quot;Step 3/3: Merging transcription with speaker labels...\n&quot;)<br>    for segment in transcript:<br>        start = segment[&quot;start&quot;]<br>        end = segment[&quot;end&quot;]<br>        text = segment[&quot;text&quot;]<br><br>        # Find overlapping speaker segment<br>        speaker = &quot;Unknown&quot;<br>        for turn, _, label in diarization.itertracks(yield_label=True):<br>            if start &gt;= turn.start and end &lt;= turn.end:<br>                speaker = label<br>                break<br><br>        print(f&quot;[{speaker}] {start:.2f}–{end:.2f}: {text}&quot;)<br><br>    print(&quot;\nProcessing finished!&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>Conclusion</h3><p>Speaker diarization used to be something only labs with lots of compute could do. Today, with <strong>Whisper</strong> and <strong>pyannote</strong>, any developer can add this capability to their apps with just a few lines of Python.</p><p>Whether you’re building meeting tools or just experimenting, combining <strong>Whisper</strong> and <strong>pyannote</strong> is a powerful way to make audio more understandable and searchable.</p><p>Read more of my work and projects at <a href="https://selinamangaroo.com/">SelinaMangaroo.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2feb2f67da30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Guide to the Levenshtein Distance Algorithm (With Python Example)]]></title>
            <link>https://medium.com/@selinamangaroo/a-simple-guide-to-the-levenshtein-distance-algorithm-with-python-example-e4efeba1383e?source=rss-fa2ce83a0390------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4efeba1383e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[levenshtein-distance]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Selina Mangaroo]]></dc:creator>
            <pubDate>Mon, 19 May 2025 20:49:38 GMT</pubDate>
            <atom:updated>2025-12-23T03:17:56.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*lHVGQMKK0jdoNv2UdN5h-w.png" /><figcaption>Distance Matrix</figcaption></figure><h3>What is the Levenshtein <strong>Distance</strong>?</h3><p>The <strong>Levenshtein Distance </strong>algorithm<strong> </strong>measures how similar two strings are by counting the minimum number of edits needed to change one string into the other.</p><p>These edits can be:</p><ul><li><strong>Insertion</strong> (add a character)</li><li><strong>Deletion</strong> (remove a character)</li><li><strong>Substitution</strong> (replace one character with another)</li></ul><p>This is also known as <strong>edit distance</strong>.</p><h3>Simple Example:</h3><p>To turn &quot;kitten&quot; into &quot;sitting&quot;:</p><ol><li>Substitute ‘k’ → ‘s’ (kitten → sitten)</li><li>Substitute ‘e’ → ‘i’ (sitten → sittin)</li><li>Insert ‘g’ at the end (sittin → sitting)</li></ol><p>Total edits = <strong>3</strong><br>Levenshtein distance = <strong>3</strong></p><h3>Why is it Useful?</h3><p>It’s great for:</p><ul><li><strong>Spell checking</strong></li><li><strong>Comparing OCR text results</strong></li><li><strong>Fuzzy matching in databases</strong></li><li><strong>Comparing two text files for differences</strong></li></ul><h3>How Does It Work?</h3><p>It builds a grid (matrix) where:</p><ul><li>One string is on the X-axis, the other on the Y-axis.</li><li>It calculates the cost of edits step by step.</li><li>The value in the bottom-right cell is the final distance.</li></ul><h3>Conceptual Steps:</h3><ol><li>Start with empty strings → distance is 0.</li><li>Add cost of inserting/deleting letters.</li><li>For every character pair:</li></ol><ul><li>If same → cost = 0</li><li>If different → cost = 1</li></ul><p>4. Choose the minimal edit path (insert, delete, substitute).</p><p>5. Repeat until the end.</p><p>Here is the <strong>Levenshtein Distance Matrix</strong> for transforming &quot;kitten&quot; into &quot;sitting&quot;:</p><p>Each cell represents the minimum number of edits (insert, delete, substitute) needed to reach that character position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*lHVGQMKK0jdoNv2UdN5h-w.png" /></figure><h3>Using Levenshtein in Python</h3><p>You can use the <strong>python-Levenshtein</strong> library to do this easily.</p><h4>Install the Library:</h4><pre>pip install python-Levenshtein</pre><h4>Example Code (Comparing Two Text Files):</h4><pre>import Levenshtein<br><br># Read the two files<br>with open(&#39;file1.txt&#39;, &#39;r&#39;) as f1, open(&#39;file2.txt&#39;, &#39;r&#39;) as f2:<br>    text1 = f1.read()<br>    text2 = f2.read()<br><br># Calculate Levenshtein distance<br>distance = Levenshtein.distance(text1, text2)<br><br># Calculate similarity ratio (0 to 1)<br>similarity = Levenshtein.ratio(text1, text2)<br><br>print(f&quot;Levenshtein Distance: {distance}&quot;)<br>print(f&quot;Similarity Ratio: {similarity:.2%}&quot;)</pre><h4>Output Example:</h4><pre>Levenshtein Distance: 45<br>Similarity Ratio: 92.31%</pre><h3>Distance vs Ratio:</h3><ul><li><strong>Distance</strong> → Number of edits needed.</li><li><strong>Ratio</strong> → Percentage of similarity (0 = totally different, 1 = identical).</li></ul><h3>Key Takeaways:</h3><ul><li>Levenshtein shows how much two texts differ.</li><li>It’s simple but very powerful for real-world tasks.</li><li>python-Levenshtein library makes it easy to use.</li></ul><p>Read more of my work and projects at <a href="https://selinamangaroo.com/">SelinaMangaroo.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4efeba1383e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quickly Understand Your File Structure With the ‘tree’ Command]]></title>
            <link>https://medium.com/@selinamangaroo/quickly-understand-your-file-structure-with-the-tree-command-117dbc1e666a?source=rss-fa2ce83a0390------2</link>
            <guid isPermaLink="false">https://medium.com/p/117dbc1e666a</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[tree-command]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Selina Mangaroo]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 17:40:12 GMT</pubDate>
            <atom:updated>2025-12-23T03:17:26.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*hHqIUnFmQska2nQtZ8S5_A.png" /></figure><p>When I fork a new repository on GitHub, the first thing I want is a map, a quick look at all the files and folders so I know what I’m working with. That’s where the tree command saves the day. Instead of getting lost opening folders one by one, tree instantly lays out the entire structure right in my terminal. Here’s how you can use it to get a bird’s-eye view of any project.</p><h3>What is the tree Command?</h3><p>The tree command is a command-line utility that displays directories and files in a hierarchical, tree-like format. Unlike ls, which just lists files and folders, tree shows the relationships between them, helping you visualize your entire folder structure at a glance.</p><h3>Why Use the tree Command?</h3><ul><li><strong>Visualize complex projects:</strong> Instantly understand how folders and files are organized.</li><li><strong>Onboarding:</strong> Get up to speed with unfamiliar codebases or shared folders.</li><li><strong>Documentation:</strong> Include a snapshot of your directory structure in README files or project wikis.</li><li><strong>Spot issues:</strong> Quickly identify cluttered folders, misplaced files, or unexpected subdirectories.</li></ul><h3>How to Install tree</h3><p>tree isn’t always installed by default, but adding it to your system is quick and easy.</p><p><strong>macOS (using Homebrew):</strong></p><pre>brew install tree</pre><p><strong>Windows:</strong><br> You can use Git Bash or download tree from the GnuWin32 project.</p><h3>Basic Usage</h3><p>Just open your terminal, navigate to any directory, and type:</p><pre>tree</pre><p>This will display the current directory and all its subdirectories in a tree view.</p><p>Example output:</p><pre>.<br>├── README.md<br>├── src<br>│   ├── index.js<br>│   └── utils.js<br>├── package.json<br>└── node_modules</pre><h3>Handy Options and Examples</h3><ul><li><strong>Show hidden files (dotfiles):</strong></li></ul><pre>tree -a</pre><ul><li><strong>Limit the depth of the tree (e.g., only two levels deep):</strong></li></ul><pre>tree -L 2</pre><ul><li><strong>Display only directories, not files:</strong></li></ul><pre>tree -d</pre><ul><li><strong>Show file sizes:</strong></li></ul><pre>tree -h</pre><ul><li><strong>Ignore certain directories:</strong></li></ul><pre>tree -I &#39;node_modules|.next&#39;</pre><ul><li><strong>Export the output to a file (great for documentation!):</strong></li></ul><pre>tree -L 2 &gt; structure.txt</pre><h3>Real-World Use Cases</h3><ul><li><strong>Add project structure to your README:</strong></li></ul><pre>tree -L 2 &gt; PROJECT_STRUCTURE.txt</pre><p>Copy-paste this output into your documentation to help others understand your repo.</p><ul><li><strong>Find misplaced files:</strong><br> Visualize and clean up folders that have grown out of control.</li><li><strong>Quick overview before sharing or archiving:</strong><br> Ensure everything is in the right place before zipping or sharing directories.</li></ul><h3>Export to JSON, XML, or HTML</h3><p>tree can output in structured formats too:</p><ul><li><strong>JSON output:</strong></li></ul><pre>tree -J</pre><ul><li><strong>XML output:</strong></li></ul><pre>tree -X</pre><ul><li><strong>HTML output (clickable file tree):</strong></li></ul><pre>tree -H . -o tree.html</pre><p>These are great for scripting, building visual tools, or adding browsable file trees to your project documentation.</p><h3>Final Thoughts</h3><p>The tree command is a simple but powerful way to quickly visualize and understand your file structure. Next time you’re lost in a maze of directories, remember to try tree.</p><p>Read more of my work and projects at <a href="https://selinamangaroo.com/">SelinaMangaroo.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=117dbc1e666a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Whisper — Speech-to-Text Transcription]]></title>
            <link>https://medium.com/@selinamangaroo/an-introduction-to-whisper-speech-to-text-transcription-a3b86429c59a?source=rss-fa2ce83a0390------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3b86429c59a</guid>
            <category><![CDATA[whisper-ai]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Selina Mangaroo]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 03:09:34 GMT</pubDate>
            <atom:updated>2025-12-23T03:17:00.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*4l07m-rV0ZepWJ3n7ECC9w.png" /></figure><h3>An Introduction to Whisper —Speech-to-Text Transcription</h3><h3>A Deep Dive into OpenAI’s Whisper, How It Works, and a Step-by-Step Guide to Using It</h3><p><a href="https://openai.com/index/whisper/"><strong>Whisper</strong></a> is an open-source<strong> automatic speech recognition (ASR) </strong>model that is incredibly popular for transcription. It’s highly accurate, multilingual, and runs locally on your machine, meaning no internet connection required.</p><p>The model has been trained on a massive dataset of 680,000 hours of multilingual and multitask supervised data collected from the internet. Conventional ASR models often struggle with accents, background noise, and multiple speakers, while whisper excels in real-world scenarios.</p><p>OpenAI trained Whisper using a technique called <strong>Self-Supervised Learning (SSL)</strong>, which allows it to learn patterns in human speech across different languages and styles.</p><p>You can run Whisper in the command line, but today we will be using a <br>simple Python script thats run in a virtual environment.</p><p>You will need:</p><p><strong>Python 3.8 </strong>or higher versions.<br><strong>FFmpeg</strong> — Required for audio processing and conversion.</p><p>I prefer to create a virtual environment to isolate your Whisper installation and ensure that dependencies do not interfere with other projects.</p><h4>Create a Virtual Environment</h4><p>Navigate to the folder where you want to install Whisper and run:</p><pre>python -m venv whisper-env</pre><p>This will create a folder called whisper-env with an isolated Python setup.</p><h4>Activate the Virtual Environment</h4><ul><li><strong>Windows (Command Prompt or PowerShell)</strong>:</li></ul><pre>whisper-env\Scripts\activate</pre><ul><li><strong>Mac/Linux</strong>:</li></ul><pre>source whisper-env/bin/activate</pre><p>When activated, your terminal should now show (whisper-env) before commands.</p><h3>Install Whisper AI</h3><p>Once the virtual environment is active, install Whisper and its dependencies:</p><pre>pip install openai-whisper ffmpeg-python</pre><h3>Verify Installation</h3><p>To ensure everything is installed correctly, run:</p><pre>python -c &quot;import whisper; print(&#39;Whisper is ready!&#39;)&quot;</pre><p>If it prints Whisper is ready!, you&#39;re good to go.</p><h3>Transcribing Audio</h3><p>Now, let’s create a simple Python script to transcribe an audio file.</p><p>Save this script as transcribe.py</p><pre>import whisper<br>import os<br><br># Set the audio file<br>audio_file = &quot;&quot; # Change this to your actual file path<br><br># Load Whisper model<br>model = whisper.load_model(&quot;base&quot;)<br><br># Transcribe the audio<br>print(&quot;Transcribing...&quot;)<br>try:<br>    result = model.transcribe(audio_file)<br>    transcription = result[&quot;text&quot;]<br><br>    # Save transcription to a file<br>    text_file = os.path.splitext(audio_file)[0] + &quot;_transcription.txt&quot;<br>    with open(text_file, &quot;w&quot;, encoding=&quot;utf-8&quot;) as file:<br>        file.write(transcription)<br><br>    print(f&quot;Transcription saved to: {text_file}&quot;)<br>    print(&quot;\n Transcription:\n&quot;, transcription)<br><br>except Exception as e:<br>    print(f&quot;Error: {e}&quot;)</pre><h3>How to Run the Script</h3><p>Open your terminal in the folder where transcribe.py is saved.</p><p>Run:</p><pre>python transcribe.py</pre><p>Whisper will process the audio and save the transcript as a .txt file.</p><p>Whisper AI represents a significant advancement in speech recognition technology. It is an incredible tool for transcribing audio accurately and efficiently. Its multilingual support, and ability to run locally make it a powerful tool for developers, researchers, and professionals alike.</p><h3>A Note on Accuracy and Limitations</h3><p>While Whisper is highly accurate for many real-world transcription tasks, it’s important to recognize its limitations. Like other AI language models, Whisper can sometimes produce inaccurate or “hallucinated” transcriptions. Such as words or phrases that were not actually spoken in the audio. This risk is especially important to consider for sensitive domains such as medical, legal, or official records, where transcription errors could have significant consequences. For critical applications, always review and verify transcriptions carefully before relying on them.</p><p>Read more of my work and projects at <a href="https://selinamangaroo.com/">SelinaMangaroo.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3b86429c59a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Record and Visualize Audio in JavaScript]]></title>
            <link>https://medium.com/@selinamangaroo/building-a-simple-browser-based-audio-recorder-with-javascript-7d54a02db1be?source=rss-fa2ce83a0390------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d54a02db1be</guid>
            <category><![CDATA[web-audio-api]]></category>
            <category><![CDATA[media-recorder-api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[audio-visualization]]></category>
            <category><![CDATA[audio-recording]]></category>
            <dc:creator><![CDATA[Selina Mangaroo]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 04:44:17 GMT</pubDate>
            <atom:updated>2025-12-23T03:16:16.468Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZP3sWQi1BrckHwkMQSBpA.png" /></figure><p>In this guide, we’ll walk through how to create a simple browser-based audio recorder using JavaScript. This project will leverage the <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder"><strong>MediaRecorder API</strong></a> to capture audio and the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API"><strong>Web Audio API</strong></a> to visualize sound in real-time. By the end, you’ll have a fully functional web app that allows users to record, pause, stop, play back, and save their recordings as WebM files.</p><h3>Prerequisites</h3><p>Before we start, make sure you have:</p><ul><li>A basic understanding of HTML, CSS, and JavaScript.</li><li>A modern web browser.</li><li>A microphone-enabled device for testing.</li></ul><h3>Technologies Used</h3><ul><li><strong>HTML5</strong>: Structure of the app.</li><li><strong>CSS3</strong>: Styling and layout.</li><li><strong>JavaScript (ES6+)</strong>: Logic for recording and visualization.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder"><strong>MediaRecorder API</strong></a>: Captures and stores audio from the microphone.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API"><strong>Web Audio API</strong></a>: Analyzes and visualizes audio data.</li></ul><p>Here is some background on the API’s used:</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder"><strong>MediaRecorder API</strong></a></p><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder"><strong>MediaRecorder API</strong></a> lets you record audio and video directly in the browser. It works with <strong>getUserMedia()</strong> to access the microphone or camera and saves the recording in chunks. You can start, pause, resume, and stop recording, and the data can be saved as a <strong>WebM</strong> file. This API is useful for building voice recorders, podcast apps, and media capture tools.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API"><strong>Web Audio API</strong></a></p><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API"><strong>Web Audio API</strong></a> is used to process and manipulate audio in real-time. It allows you to analyze sound, apply effects, and create visualizations. By using an <strong>AudioContext</strong>, you can capture live audio, filter it, or display sound waves. This API is great for creating music visualizers, speech analyzers, and interactive audio applications.</p><h3>Setting Up the Project</h3><h4>Clone the Repository</h4><p>Instead of creating the project from scratch, you can clone the existing repository from <a href="https://github.com/SelinaMangaroo/JavaScript-Audio-Recorder">GitHub</a>:</p><pre>git clone https://github.com/SelinaMangaroo/JavaScript-Audio-Recorder.git<br>cd JavaScript-Audio-Recorder</pre><h4>Project Structure</h4><p>If you prefer to create the project manually, here’s the structure:</p><pre>js-audio-recorder/<br>│── index.html   # Main HTML file<br>│── styles.css   # CSS styles<br>│── script.js    # JavaScript functionality</pre><h3>Writing the Code</h3><h4>Setting Up the HTML</h4><p>Create an index.html file and add the following structure:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot;&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>        &lt;title&gt;Audio Recorder&lt;/title&gt;<br>        &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div class=&quot;audio-recorder&quot;&gt;<br>            &lt;h1&gt;Audio Recorder&lt;/h1&gt;<br>            &lt;canvas id=&quot;visualizer&quot; width=&quot;400&quot; height=&quot;80&quot;&gt;&lt;/canvas&gt;<br>            &lt;br&gt;<br>            &lt;div class=&quot;control-bar&quot;&gt;<br>                &lt;button id=&quot;startBtn&quot;&gt;▶ Record&lt;/button&gt;<br>                &lt;button id=&quot;pauseBtn&quot; disabled&gt;⏸ Pause&lt;/button&gt;<br>                &lt;button id=&quot;stopBtn&quot; disabled&gt;⏹ Finish&lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;br&gt;&lt;br&gt;<br>            &lt;label for=&quot;audioPlayback&quot;&gt;<br>              &lt;strong&gt;🎧 Audio Preview:&lt;/strong&gt;<br>            &lt;/label&gt;<br>            &lt;br&gt;<br>            &lt;audio id=&quot;audioPlayback&quot; controls&gt;&lt;/audio&gt;<br>            &lt;br&gt;&lt;br&gt;<br>            &lt;button id=&quot;cancelBtn&quot; disabled&gt;ⓧ Cancel&lt;/button&gt;  <br>            &lt;button id=&quot;saveBtn&quot; disabled&gt;✓ Save&lt;/button&gt; <br>        &lt;/div&gt;<br>        &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><h4>Styling the Recorder</h4><p>Now, create styles.css to style the app:</p><pre>body {font-family: Arial, sans-serif; text-align: center; margin-top: 20px;}<br>button {border: none; padding: 5px 10px; font-size: 14px; border-radius: 5px; cursor: pointer;}<br>canvas {display: block; margin: 10px auto; background: lightgrey; border-radius: 5px;}<br>.control-bar {display: flex; justify-content: center; align-items: center; gap: 10px; padding: 10px; background: darkgray; border-radius: 8px; width: fit-content; margin: 10px auto;}<br>.control-bar button:disabled {opacity: 0.5; cursor: not-allowed;}</pre><h3>Implementing the Audio Recorder in JavaScript</h3><h4><strong>Variable Setup</strong></h4><p>Create script.js and before defining any functions, we need to initialize several variables to handle the recording process, manage recorded data, and visualize the audio input.</p><pre>// Stores the MediaRecorder instance that manages the recording process.<br>let mediaRecorder; <br><br>// Array to temporarily store recorded audio chunks.<br>let audioChunks = [];<br><br>// Boolean to track whether the recording is paused.<br>let isPaused = false;<br><br>// Stores the final recorded audio as a Blob.<br>let audioBlob = null;<br><br>// Variables for the Web Audio API used for audio visualization.<br>let audioContext, analyser, dataArray, source;<br><br>//Stores animation reference for the visualizer.<br>let animationFrame;<br><br>// Get references to UI elements from the HTML document.<br>const startBtn = document.getElementById(&quot;startBtn&quot;);<br>const pauseBtn = document.getElementById(&quot;pauseBtn&quot;);<br>const stopBtn = document.getElementById(&quot;stopBtn&quot;);<br>const audioPlayback = document.getElementById(&quot;audioPlayback&quot;);<br>const cancelBtn = document.getElementById(&quot;cancelBtn&quot;);<br>const saveBtn = document.getElementById(&quot;saveBtn&quot;);<br>const canvas = document.getElementById(&quot;visualizer&quot;);<br>const canvasContext = canvas.getContext(&quot;2d&quot;);</pre><h4>Start Recording Function</h4><p>The startRecording function begins the recording process by accessing the microphone, setting up real-time audio visualization, and using the <strong>MediaRecorder API</strong> to capture audio. It saves the recorded data in chunks, converts it into a <strong>Blob</strong> when recording stops, and allows playback and saving.</p><pre>async function startRecording() {<br> // Requests microphone access. Returns a stream (audio data from the microphone).<br>    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });<br><br> // Initialize Web Audio API for visualization<br><br> // Creates an audio processing context.<br>    audioContext = new AudioContext();<br><br> // An analyser node for audio visualization.<br>    analyser = audioContext.createAnalyser(); <br><br> // Connects microphone input to the analyser.<br>    source = audioContext.createMediaStreamSource(stream); <br><br> // Links the audio input to the analyser.<br>    source.connect(analyser);<br><br> // Sets the resolution for frequency analysis.<br>    analyser.fftSize = 256;<br><br> // Array to store audio frequency data.<br>    dataArray = new Uint8Array(analyser.frequencyBinCount); <br>    <br>    drawVisualizer();  // Start visualization animation<br><br> // MediaRecorder API is initialized with the microphone stream.<br>    const options = { mimeType: &quot;audio/webm; codecs=opus&quot; };  <br>    mediaRecorder = new MediaRecorder(stream, options);<br><br> // Event that fires when a chunk of audio data is available.<br> // Push each chunk into audioChunks. All pieces of the recording are stored and can be assembled later.<br>    mediaRecorder.ondataavailable = event =&gt; {<br>        audioChunks.push(event.data);<br>    };<br><br> //Event triggers when recording is stopped.<br>    mediaRecorder.onstop = () =&gt; {<br>        cancelAnimationFrame(animationFrame); // Stop visualization<br><br>        // Combines all the stored audioChunks into a single WebM file using a Blob.<br>        audioBlob = new Blob(audioChunks, { type: &quot;audio/webm&quot; });<br><br>        // Creates a temporary URL to download the recorded file.<br>        const audioUrl = URL.createObjectURL(audioBlob);<br>        // Assigns Url to the audio player for playback.<br>        audioPlayback.src = audioUrl;<br><br>        saveBtn.disabled = false;<br>        audioChunks = [];<br>    };<br><br>    mediaRecorder.start();<br>    isPaused = false;<br><br>    // Update button states to reflect the active recording session.<br>    startBtn.disabled = true;<br>    pauseBtn.disabled = false;<br>    stopBtn.disabled = false;<br>    cancelBtn.disabled = false; <br>    saveBtn.disabled = true;<br>}</pre><h4>Pause Recording Function</h4><p>This function switches between pausing and resuming the recording. When paused, it resumes recording, restarts the visualization, and updates the button text. When active, it pauses recording, stops the visualization, and updates the button text.</p><pre>// Toggles between pausing and resuming the recording.<br>function pauseRecording() {<br>    if (!mediaRecorder) return;<br><br>    if (isPaused) {<br>        mediaRecorder.resume();<br>        pauseBtn.textContent = &quot;⏸ Pause&quot;;<br>        drawVisualizer(); // Restart visualization<br>    } else {<br>        mediaRecorder.pause();<br>        pauseBtn.textContent = &quot;▶ Resume&quot;;<br>        cancelAnimationFrame(animationFrame); // Stop visualization<br>    }<br>    isPaused = !isPaused;<br>}</pre><h4>Stop Recording Function</h4><p>This function stops the recording, finalizes the data, and updates the UI. It cancels the visualization, resets the pause button text, and adjusts the buttons to allow a new recording while disabling unnecessary options.</p><pre>// Stops the mediaRecorder. Enables Start button, disables the other buttons.<br>function stopRecording() {<br>    if (mediaRecorder) {<br>        mediaRecorder.stop();<br>        cancelAnimationFrame(animationFrame); // Stop visualization<br><br>        pauseBtn.textContent = &quot;⏸ Pause&quot;; // Reset button text<br><br>        // Update button states after stopping the recording.<br>        startBtn.disabled = false;<br>        pauseBtn.disabled = true;<br>        stopBtn.disabled = true;<br>    }<br>}</pre><h4>Cancel Recording Function</h4><p>This function cancels the recording by stopping the <strong>MediaRecorder</strong>, resetting variables, clearing playback data, stopping the visualization, and restoring the UI for a new recording session.</p><pre>function cancelRecording() {<br>    if (mediaRecorder &amp;&amp; mediaRecorder.state !== &quot;inactive&quot;) {<br>        mediaRecorder.stop();<br>    }<br><br>    // Reset recording-related variables.<br>    audioChunks = [];<br>    audioBlob = null;<br>    audioPlayback.src = &quot;&quot;;<br>    pauseBtn.textContent = &quot;⏸ Pause&quot;;<br><br>    // Reset button states.<br>    startBtn.disabled = false;<br>    pauseBtn.disabled = true;<br>    stopBtn.disabled = true;<br>    saveBtn.disabled = true;<br>    cancelBtn.disabled = true;<br><br>    cancelAnimationFrame(animationFrame); // Stop visualization <br>    canvasContext.clearRect(0, 0, canvas.width, canvas.height); // Clear visualizer<br>}</pre><h4>Save Recording Function</h4><p>This function lets users download the recorded audio in <strong>WebM</strong> format. It creates a temporary URL from the audio blob, triggers a download via an anchor (&lt;a&gt;) element, and then revokes the URL to free memory.</p><pre>function saveRecording() {<br>    if (audioBlob) {<br>        // Creates an anchor element.<br>        const a = Object.assign(document.createElement(&quot;a&quot;), {<br>            // Creates a downloadable URL from the recorded Blob.<br>            href: URL.createObjectURL(audioBlob),<br>            // Specifies the file name.<br>            download: &quot;recording.webm&quot;<br>        });<br>        a.click(); // Trigger the download.<br>        URL.revokeObjectURL(a.href); // Releases the memory used for the URL.<br>    }<br>}</pre><h4>Audio Visualization Function</h4><p>This function updates the audio visualization in real time by analyzing frequency data and drawing a bar graph. Each bar in the visualization represents the amplitude of a specific frequency range, creating a real-time visual representation of the recorded sound. It clears the canvas before each frame to prevent overlap and represents sound amplitude visually.</p><pre>function drawVisualizer() {<br>    // Repeatedly calls this function for animation.<br>    animationFrame = requestAnimationFrame(drawVisualizer);<br><br>    canvasContext.fillStyle = &quot;lightgrey&quot;; // Sets the background color.<br>    <br>    // Clears the previous frame.<br>    canvasContext.fillRect(0, 0, canvas.width, canvas.height);<br><br>    // Gets the current frequency data.<br>    analyser.getByteFrequencyData(dataArray);<br><br>    canvasContext.fillStyle = &quot;darkgrey&quot;; // Sets the bar color.<br>    <br>    // Draws a bar graph representation of the audio.<br>    for (let i = 0; i &lt; dataArray.length; i++) {<br>        let barHeight = dataArray[i] / 2; // Scales the height of each bar.<br>        // Draws each bar.<br>        canvasContext.fillRect(i * 3, canvas.height - barHeight, 2, barHeight);<br>    }<br>}</pre><h4>Event Listeners</h4><p>This section attaches event listeners to various buttons in the UI.</p><pre>// Adds event listeners to handle button clicks.<br>startBtn.addEventListener(&quot;click&quot;, startRecording);<br>pauseBtn.addEventListener(&quot;click&quot;, pauseRecording);<br>stopBtn.addEventListener(&quot;click&quot;, stopRecording);<br>cancelBtn.addEventListener(&quot;click&quot;, cancelRecording);<br>saveBtn.addEventListener(&quot;click&quot;, saveRecording);</pre><h3>Conclusion</h3><p>You’ve built a simple browser-based audio recorder using JavaScript, the <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder"><strong>MediaRecorder API</strong></a>, and the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API"><strong>Web Audio API</strong></a>. This guide covered recording, playback, and visualization. Try experimenting with the project to add new features!</p><p>Read more of my work and projects at <a href="https://selinamangaroo.com/">SelinaMangaroo.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d54a02db1be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>