<?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 Tarun Kumar Anchala on Medium]]></title>
        <description><![CDATA[Stories by Tarun Kumar Anchala on Medium]]></description>
        <link>https://medium.com/@anchala.tarun?source=rss-bc5559f67697------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tI_UVP5NaMxUuiRlWyI1Xw.png</url>
            <title>Stories by Tarun Kumar Anchala on Medium</title>
            <link>https://medium.com/@anchala.tarun?source=rss-bc5559f67697------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:46:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anchala.tarun/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[In-House Content Moderation with CLIP: As Accurate as Third-Party APIs, at Zero Token Cost]]></title>
            <link>https://engg.glance.com/in-house-content-moderation-with-clip-as-accurate-as-third-party-apis-at-zero-token-cost-1dc3795a7942?source=rss-bc5559f67697------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dc3795a7942</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[clip]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tarun Kumar Anchala]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 05:49:18 GMT</pubDate>
            <atom:updated>2026-09-30T05:49:18.543Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>We replaced a general-purpose vision API with fine-tuned models we own. Latency dropped from 3–5 seconds to 80ms. Cost dropped to zero after training. Validated in production with ~95% agreement against the incumbent. Here’s the full system — why we built it, how it works, and what we learned</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZ4AZhRjPsz7GsVki7UpKw.png" /></figure><h3>TL;DR</h3><ul><li>Our image generation platform ran five content policy checks per image through a single external vision API call — at 3–5s latency and unpredictable per-request cost</li><li>We replaced it with fine-tuned CLIP classifiers: nudity, alcohol, smoking, meat, distortion</li><li>Trained on as few as 152 images per category using synthetic data we generated ourselves</li><li>All five checks now run locally in ~80ms on CPU — no external dependency, no rate limits, no ongoing cost</li><li>A weekly auto-training loop retrains from production feedback and promotes a new model only if it passes a fixed quality bar</li></ul><h3>The Problem</h3><p>Our image generation platform checks every image against five content policies before it moves downstream: nudity, alcohol, smoking, meat, and distortion. These checks ran synchronously — meaning every image had to wait for moderation to complete before anything else could happen.</p><p>We were using a general-purpose vision model for this, calling it over the network on every image. At low traffic, this was fine. At production scale, it became the most expensive and fragile step in the entire pipeline.</p><p><strong>The breaking point:</strong> when the vision model hit a rate limit or returned an error, image generation throughput dropped immediately. A problem in a service we didn’t control became a problem for our users.</p><p>That’s when the question changed — from “how do we make this external service more reliable?” to “why are we calling it at all?”</p><h3>What Was Breaking</h3><p>Each of our five policies was failing in a different way through the same API:</p><p><strong>Cost was unpredictable.</strong> Every check was a full model inference call — image encoded as tokens plus a structured prompt, roughly 4,000–6,000 tokens per check. The bill grew non-linearly with traffic and was difficult to forecast or cap.</p><p><strong>Latency set the ceiling.</strong> At 3–5 seconds per call running synchronously, moderation controlled the pace of the entire pipeline — regardless of how fast everything else was.</p><p><strong>Rate limit failures looked like bugs.</strong> During traffic spikes, quota exhaustion caused inconsistent failures within the same batch. This looked identical to a flaky service, not a quota problem. We’d spend time debugging before realising we’d simply hit a limit.</p><p><strong>Accuracy didn’t match our policies.</strong> A general-purpose model is calibrated to general content, not your platform’s specific definitions. Prompt engineering helped at the margins but couldn’t close the gap structurally.</p><p><strong>Distortion couldn’t be prompted away.</strong> Our distortion policy covers AI-generated artifacts, warped faces, and corrupted renders. No prompt reliably separated this from a normal image. It needed a trained classifier — something a general-purpose model has no path to become.</p><h3>Before vs. After</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*9wBjIAvdO3vUt62cbl1RDg.png" /></figure><blockquote><strong><em>Key takeaway:</em></strong><em> The biggest gain wasn’t latency or cost. It was the last row — going from a dependency we couldn’t measure or tune, to a system we control end to end: training data, decision boundaries, evaluation criteria, and how we recover when something goes wrong.</em></blockquote><p>We were paying per token for image moderation. Now we’re not.</p><h3>Why CLIP</h3><p>The obvious alternative was fine-tuning a standard CNN — a ResNet or EfficientNet — on a labeled dataset. Two things ruled that out.</p><p><strong>We didn’t have enough data.</strong> Collecting real labeled images for sensitive categories — nudity, alcohol in context, smoking versus steam — is a months-long effort with real legal complexity. We needed something that worked with a few hundred images, not tens of thousands.</p><p><strong>CNNs learn patterns, not concepts.</strong> A model trained on beer bottle photos will struggle with craft beer cans, unconventional packaging, or alcohol presented in a cultural context it hasn’t seen. We needed a model that understood alcohol as a <em>concept</em>, not a memorised set of visual templates.</p><p>CLIP (Contrastive Language–Image Pre-Training) solves both. It was trained on 400 million image-text pairs to understand images and language in the same space — a photo of a wine glass, the phrase “alcoholic beverage,” and a sketch of a cocktail all land near each other. This means CLIP already understands what alcohol, smoke, exposed skin, and distorted faces look like <em>before</em> you give it a single example from your own dataset.</p><p><strong>The mechanics behind that claim.</strong> CLIP is pre-trained with a symmetric contrastive loss over a batch of N image-text pairs. For each image embedding Ii and text embedding Tj, it maximizes cosine similarity for matched pairs and minimizes it for all mismatched pairs in the batch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*mjbnrlARJ1T49plHPVLLtA.png" /></figure><p>where sim(·,·) is cosine similarity and τ is a learned temperature. This is computed in both directions (image→text and text→image) and averaged. This objective is <em>why</em> a photo of a wine glass and the phrase &quot;alcoholic beverage&quot; end up near each other in embedding space — the model was never told &quot;this is alcohol,&quot; it was only ever told &quot;this image and this caption co-occurred, and these others didn&#39;t.&quot; That&#39;s the mechanical basis for the concept-level generalization the rest of this post relies on.</p><p><strong>The result:</strong> a few hundred targeted images per category is genuinely enough to shift the decision boundary to exactly where your policy needs it. You’re not teaching the model what alcohol looks like from scratch — you’re telling it where your line is.</p><p>We use openai/clip-vit-base-patch32 — 12 transformer layers, pre-trained on 400M pairs, the right balance of quality and inference speed for production.</p><h3>Why Not Zero-Shot CLIP</h3><p>Before fine-tuning, we tried zero-shot CLIP — define text anchors for each side of the policy, score images by similarity, take the winner. It’s fast to set up and gets you something workable quickly.</p><p>It failed on the cases that actually matter.</p><p>A mocktail in a cocktail glass scores high on “alcoholic beverage” because the visual context — bar glassware, garnish, ice, presentation — matches the anchor more than the liquid itself does. Zero-shot CLIP answers: <em>does this image resemble alcohol?</em> Our policy needs the answer to: <em>does this image violate our alcohol policy?</em> Those are different questions.</p><blockquote><strong><em>Key insight:</em></strong><em> Zero-shot tells you what an image resembles in pre-trained space. Fine-tuning tells you what your policy means. Only one of those is solvable without labeled data.</em></blockquote><p>This distinction also introduced the rule we now apply to every category: <strong>design the hard negative before the positive.</strong> The image that looks like a violation but isn’t is the one that breaks your model in production.</p><h3>Architecture: One Encoder, Five Policies</h3><p>Instead of running five separate models, all five classifiers share a single CLIP image encoder. The image is encoded once, then passed through five lightweight classification heads in parallel — one per policy.</p><pre>Generated Image<br>        │<br>        ▼<br>  Shared CLIP Encoder  ← computed once per image<br>        │<br>   ┌────┼────┬────┬────┐<br>   ▼    ▼    ▼    ▼    ▼<br>Nudity Alc. Smoke Meat Distort.<br> Head  Head Head  Head   Head<br>        │<br>        ▼<br>   All five scores returned together</pre><p>This matters for performance: one encoder pass instead of five means lower latency and lower memory. It also means all five policies run from the same feature representation — consistent and easy to maintain.</p><p>Inside the encoder, only the top layers are trained. The rest stay frozen:</p><pre>CLIP ViT-Base/Patch32 — Vision Encoder (12 Transformer Layers)<br>    ├── Layers 0–9:    FROZEN  ←  universal visual features<br>    ├── Layer 10:      TRAINABLE<br>    ├── Layer 11:      TRAINABLE<br>    └── Post LayerNorm: TRAINABLE<br>Visual Projection (768 → 512): TRAINABLE<br>Classifier Head (per category):<br>    LayerNorm(512) → Linear(512→256) → GELU → Dropout(0.4) → Linear(256→2)</pre><p><strong>The forward pass, written out.</strong> For an input image, patch embeddings flow through the frozen layers 0–9, then through the two trainable transformer layers, producing a pooled CLS-token representation h (a 768-dim vector). This is projected into CLIP&#39;s shared embedding space and passed through the classifier head:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*7OsmV5ynZPnAQzqG_nSuzw.png" /></figure><p>This is a direct read of CLIPClassifier.forward() — vision_model(pixel_values) gives the pooled output, visual_projection maps it to the 512-dim shared space, and the classifier head reduces that to two logits.</p><p><strong>Why freeze 83% of the network?</strong> The lower layers encode universal visual features — edges, textures, shapes — that are identical no matter what you’re classifying. Retraining them on a few hundred images would destroy representations that took 400 million pairs to build. Fine-tuning only the top two layers, projection, and classifier head gives ~14.7M trainable parameters out of ~88M total — 83% of the network stays frozen. A small enough share that the pretrained representations survive; expressive enough to draw a sharp boundary.</p><p><strong>Adding a new policy</strong> means creating a data folder and attaching a new head. Nothing about the encoder, training script, or serving layer changes.</p><h3>Building Synthetic Training Data</h3><p>You can’t scrape real nudity for a training set. Labeled alcohol and smoking data at scale takes months. Distortion has no usable public dataset. So every training image is synthetic — generated through an automated pipeline.</p><p>Generating good synthetic data is harder than it sounds. Three problems come up immediately:</p><p><strong>Simple prompts produce simple examples.</strong> A prompt like <em>“person smoking a cigarette”</em> generates clean, obvious positives. A model trained on these will be accurate on easy cases and brittle on the ones that appear in production. The model learns to classify the prompt, not the policy boundary.</p><p><strong>Hard negatives must be designed, not discovered.</strong> The cases that broke the old system — mocktails in bar glassware, breath condensation that looks like smoke, plant-based meat that looks real — will not appear from generic prompts. They have to be written in deliberately.</p><p><strong>Diversity must be managed.</strong> For distortion, generating the same failure mode repeatedly produces a large but narrow bank. The classifier learns to recognise one type of artifact, not the concept of distortion.</p><h3>How the pipeline works</h3><pre>Curated Prompt Library<br>(positive + hard-negative pairs per category)<br>        │<br>        ▼<br>  Image Generation Model<br>        │<br>        ▼<br>  Fine-Tuned CLIP Quality Router<br>  (already-trained model scores each image)<br>        │<br>  confidence &gt; 0.75?<br>   ┌────┴────┐<br>  YES         NO<br>   │           │<br>   ▼           ▼<br>Training      Human Review<br> Bank              Queue</pre><p>Images that score above 0.75 confidence are routed automatically to the training bank. Below that, they go to a human reviewer. Corrected labels feed back into both the bank and the router’s calibration.</p><h3>Hard negative examples per category</h3><p><strong>Smoking</strong> is the clearest example — breath condensation in cold weather is visually indistinguishable from cigarette smoke in a photo</p><p><strong>Positive</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8I32UjJsym473gnjKUuXQ.png" /></figure><p><strong>Negative</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdOixHjbC20s0s2ns4dOIA.png" /></figure><p>From the examples above, you can see how visually similar these pairs are — this is exactly why a general-purpose model struggles, and why training on carefully labeled positive and negative examples is the only reliable fix.</p><p>The principle is the same across every category: find the image that most resembles a violation while not being one, and generate it deliberately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*bK-Y99fOK-7m3dOD0nuZBA.png" /></figure><p>Distortion’s bank is 10× larger because its positive class is heterogeneous — multiple visually distinct failure modes need coverage. The training counts and final results are summarised together in the Evaluation section below.</p><h3>Training</h3><p>Every category shares the same training script, loss, and optimizer setup. Only the epoch budget, batch size, and learning rate are tuned per category to its dataset size.</p><blockquote>for example, nudity trains for up to 50 epochs ( lr 2e-5, patience 15), while distortion trains for up to 25 epochs ( lr 5e-5, patience 7) to suit its larger, more heterogeneous bank.</blockquote><pre>Optimizer:        AdamW, weight_decay=1e-3<br>Scheduler:        CosineAnnealingLR<br>Loss:             CrossEntropyLoss, label_smoothing=0.05, class-weighted<br>Val split:        20%, stratified by class<br>Hardware:         CPU, roughly 5–10 minutes per category</pre><p>Four decisions in this config that aren’t obvious until something breaks without them:</p><ul><li><strong>Stratified split</strong> — with 150–300 total samples, a random split can skew class balance in validation. We split per class first, then merge. Without this, the F1 score partially reflects split luck, not model quality.</li><li><strong>Class weighting</strong> — without it, the model can achieve acceptable accuracy by biasing toward the majority class while ignoring the minority. Weighting the loss forces it to learn the boundary.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*Ml3LXj77iZKzQUx5zjpixg.png" /></figure><p>For instance, in the nudity dataset if the non-nudity/nudity training split is 200/60, the minority class (nudity) is weighted at 200/60 ≈ 3.33× the majority class in the loss — a policy violation the model got wrong costs over 3× as much as a false alarm getting it wrong, forcing the boundary away from just predicting “safe” every time.</p><ul><li><strong>Label smoothing (0.05)</strong> — training images are clean and synthetic; production images are not. Smoothing prevents overconfidence on the training distribution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*5dAFFvxLDeHTOCVIBoD6Sg.png" /></figure><p>With K=2 and ε=0.05, the &quot;correct&quot; class target drops from 1.0 to 0.975, and the &quot;wrong&quot; class target rises from 0.0 to 0.025 — a small but deliberate hedge against the model becoming overconfident on synthetic images that are cleaner than anything it will see in production.</p><ul><li><strong>F1 checkpointing</strong> — on imbalanced datasets, a model that always predicts “safe” can still show high accuracy. F1 catches this. We save the best F1 checkpoint, using accuracy only as a tiebreaker.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*lXpf-kfAYlV94m781HCriQ.png" /></figure><p>A model that always predicts “safe” (i.e., always predicts the majority class) has TP=0, and both precision and recall on the violation class collapse to 0 — even if raw accuracy still looks high because the majority class dominates the validation set. F1 exposes this failure mode where accuracy hides it.</p><p><strong>The 95%-accuracy gate, and why there’s a fallback.</strong> For nudity specifically, we additionally require train_acc &gt;= 95% before a checkpoint is even eligible to become the new &quot;best&quot; model — we don&#39;t want to ship a model that hasn&#39;t actually fit its own training data well, even if its F1 momentarily looks good. But requiring this gate means training could in principle finish without ever satisfying it. So a second checkpoint — fallback_f1 — tracks the best F1 seen regardless of the accuracy gate, and is promoted to the primary model only if the gate is never met by the end of training. This guarantees the pipeline always produces <em>some</em> usable model, while still preferring one that&#39;s demonstrably learned the training set when one exists.</p><p>One category-specific note: <strong>use lighter augmentation for distortion.</strong> Aggressive ColorJitter and crop transforms can make visually normal images resemble distortion artifacts — creating noisy training signal in a category where the positive class is already broad.</p><p><strong>Why cosine annealing, not step decay.</strong> The learning rate follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*L4rZmX2VkSeWxTqXrNOp4g.png" /></figure><p>where t is the current epoch and T is the total epoch budget. Unlike step decay, this produces a smooth, monotonic decrease with no sudden drops — which matters more than usual here because these are small fine-tuning runs (25–50 epochs total, not hundreds). A sudden LR drop on a run this short can freeze the model mid-convergence; cosine annealing lets the last few epochs fine-tune with a gently vanishing step size instead.</p><h3>How We Evaluate Models Before Shipping:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUNKOPxl_iVthjLxL5H4fA.png" /></figure><p>These validation F1 scores tell us training worked. They don’t tell us whether to ship.</p><p>With validation splits of just 30–35 images for smaller categories, a perfect score is directional — not statistically conclusive. A model that memorised the validation set would look identical to one that genuinely learned the boundary.</p><p><strong>Putting a number on that uncertainty.</strong> At n=30 validation samples with an observed F1 of, say, 0.95, a Wilson score interval around that estimate spans roughly 80–99% at the 95% confidence level — meaning the <em>true</em> population F1 could plausibly be anywhere in that 20-point band. At n=150+ (our golden set size), that same point estimate tightens to within a few points. This is the concrete reason a strong validation F1 on a small split is a promising signal, not a shippable one.</p><p>That’s why every candidate model is separately evaluated against a <strong>golden test set</strong> — built by hand from real production failures, reviewed false positives and false negatives, and edge cases discovered after deployment. A model is only promoted if it matches or improves on the golden set relative to the currently live model.</p><blockquote><strong><em>The rule:</em></strong><em> Validation score tells us training worked. Golden set tells us deployment is safe.</em></blockquote><h3>Tracking Performance in Production</h3><p>Before fully replacing the old system, we ran the new model in the background — processing the same images in parallel — and built dashboards to track its detections against the existing model in real time.</p><p>This gave us visibility into confusion matrix metrics as they actually landed in production: True Positives (TP), False Positives (FP), and False Negatives (FN) — not just on a held-out test set, but on live traffic.</p><p><strong>What we saw:</strong> a healthy number of TPs being detected from the start — violations were being caught. Our first priority was ensuring FNs stayed low, meaning no real violations were slipping through. Once recall was solid, we turned attention to FPs — cases where the model flagged images that should have passed. Each FP cluster pointed directly to a gap in the hard-negative bank, which we addressed with targeted prompts and a retrain.</p><p>With every improvement cycle, the agreement rate between the new model and the old system climbed. We started at a lower baseline and worked up to approximately <strong>~95% agreement</strong> — with the remaining gap largely explained by cases where the old model was over-flagging visually acceptable images, particularly in distortion scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ptnAF7urk9NHfRhsgHImw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kXmTY9tRT05UpTBAG4Mow.png" /></figure><blockquote><strong><em>Key takeaway:</em></strong><em> The improvement wasn’t a one-time jump. Each retrain — fed by reviewed production flags — moved the agreement rate higher. The loop compounds: better hard negatives → fewer FPs → higher agreement → more trust in the model.</em></blockquote><h3>Serving</h3><p>All five classifiers run from one shared encoder loaded once at startup. On every image: one encoder forward pass, followed by five lightweight classifier passes in parallel.</p><p><strong>Where the 80ms actually goes.</strong> A ViT-B/32 forward pass at 224×224 resolution costs roughly ~4.4 GFLOPs — dominated by the 12 transformer layers processing 49 patch tokens (224/32 = 7×7 patches) through self-attention and MLP blocks. The five classifier heads are each a 512→256→2 MLP — a few hundred thousand FLOPs total, negligible next to the encoder. This is exactly why the shared-encoder design matters materially, not just aesthetically: running five separate CLIP backbones would mean paying that ~4.4 GFLOPs cost five times over; sharing it means paying it once and adding five near-free linear passes on top.</p><p>Each category has its own decision threshold, tuned to its precision/recall tradeoff:</p><pre>DETECTION_THRESHOLDS = {<br>    &quot;nudity&quot;:     0.45, <br>    &quot;alcohol&quot;:    0.50,<br>    &quot;smoking&quot;:    0.50,<br>    &quot;meat&quot;:       0.55, <br>    &quot;distortion&quot;: 0.50,<br>}</pre><p>Every image returns a single combined response:</p><pre>{<br>  &quot;safe&quot;: false,<br>  &quot;flagged_categories&quot;: [&quot;alcohol&quot;],<br>  &quot;scores&quot;: {<br>    &quot;nudity&quot;: 0.02, &quot;alcohol&quot;: 0.87,<br>    &quot;smoking&quot;: 0.01, &quot;meat&quot;: 0.03, &quot;distortion&quot;: 0.05<br>  }<br>}</pre><p>Total latency: <strong>~80ms on CPU.</strong> No network call. No quota. Nothing outside our own infrastructure.</p><h3>What This Actually Taught Us</h3><p>The architecture barely changed after the first version. What changed, repeatedly, was the dataset.</p><p>Most moderation problems look like model problems and turn out to be data problems. Chasing better prompts produced diminishing returns. Chasing better hard negatives produced predictable, compounding improvements.</p><p>Once the loop was in place — flag, review, retrain, evaluate against a fixed bar, promote — model quality stopped being something we had to actively manage and became something that improved on its own schedule.</p><blockquote><strong><em>If you’re fighting rate limits, latency, or inconsistent accuracy from a general-purpose model:</em></strong><em> the fix usually isn’t a bigger model. It’s a smaller one, trained on the examples that actually define your policy — starting with the hard negative, not the obvious positive.</em></blockquote><p><em>The hardest part is almost never the architecture — it’s finding the image that looks like a violation but isn’t. What’s yours?</em></p><p>By <a href="https://www.linkedin.com/in/tarun-anchala-65a84714b/">Tarun Anchala</a>, with contributions from <a href="https://www.linkedin.com/in/karthik-sai-marala-a1116786/">Karthik Marala</a> , <a href="https://www.linkedin.com/in/tejas-venugopalan-149956244/">Tejas venugopalan</a> and <a href="https://www.linkedin.com/in/prashant-gupta-09278821b/">Prashant Gupta</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dc3795a7942" width="1" height="1" alt=""><hr><p><a href="https://engg.glance.com/in-house-content-moderation-with-clip-as-accurate-as-third-party-apis-at-zero-token-cost-1dc3795a7942">In-House Content Moderation with CLIP: As Accurate as Third-Party APIs, at Zero Token Cost</a> was originally published in <a href="https://engg.glance.com/">Glance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Glance TV Optimization Part 1: Shrinking APK Size by 65%]]></title>
            <link>https://engg.glance.com/glance-tv-optimization-part-1-shrinking-apk-size-by-65-2c0084da83a1?source=rss-bc5559f67697------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c0084da83a1</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Tarun Kumar Anchala]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 08:06:41 GMT</pubDate>
            <atom:updated>2023-11-06T08:06:41.524Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlkJsbu9fM8HW9nSsHjuzA.png" /></figure><p>We’ve been developing the Glance TV Application, where the primary focus is on showcasing high-quality large images (2k &amp; 4k), live news, live sports, videos e.t.c leading to increased memory usage and a larger APK size. Our aim is to enhance app performance across a wide range of devices, from low-end TVs with less than 1 GB of RAM to high-end models. After analyzing our app, we’ve identified areas that require improvement in memory usage, APK size, CPU usage, and UI performance.</p><p>In a series of upcoming blogs, I will cover the following topics step by step</p><ol><li><strong>APK Size (</strong>Reduced by<strong> 65% </strong>from<strong> 20.6MB to 8.3MB)</strong></li><li><strong>App Memory (</strong>Down by<strong> 70% </strong>from<strong> 515MB to 127MB)</strong></li></ol><h3>1. APK Size</h3><p>Reducing APK size is our initial focus in app optimization. This is because a larger APK size can have significant implications:</p><p><strong>Why APK size is important?</strong></p><ol><li><strong>Storage Impact:<em> </em></strong>Larger APKs occupy more storage space on the user’s device, potentially leading to storage-related performance problems. Users may run out of storage for other apps or files.</li><li><strong>Memory Usage:</strong> A larger APK may require more memory to load and run the app. This increased memory usage can strain devices with limited RAM, causing performance issues.</li></ol><p>Our goal is to improve both user experience and app performance by reducing the APK size. We’ll use <strong>APK Analyzer</strong> to identify the factors contributing to the increase in APK size.</p><p><strong><em>What’s APK Analyzer:</em></strong></p><p><a href="https://developer.android.com/studio/debug/apk-analyzer">APK Analyzer</a> is a tool provided by Google for inspecting the contents of Android application packages (APKs). APK Analyzer helps developers understand the composition of their APK files, including the resources, assets, and code that make up their Android apps.</p><p>Drag &amp; drop the APK into the Android Studio IDE to inspect its components.</p><p>The <strong><em>Initial APK size</em></strong> was ~ <strong><em>20.6MB</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*dePISVKLbIUao9MbPRElWA.png" /></figure><blockquote><strong>1. Proguard rules :</strong></blockquote><ul><li>By enabling minifyEnabled and shrinkResources flags and adding ProGuard rules to address build errors, we successfully reduced the APK size from approximately <strong>20.5 MB to 15.5 MB</strong>. This represents a <strong>25%</strong> decrease in APK size.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*7VZTYhKigzxMcbpfgzaFCA.png" /></figure><p><strong><em>official docuementation:</em></strong> <a href="https://developer.android.com/build/shrink-code">https://developer.android.com/build/shrink-code</a></p><ul><li>While we did manage to shrink the APK size by 25% with the rules we applied, it’s clear from the screenshot that 77% of the size is still taken up by resources. This suggests there’s more scope for APK size reduction.</li></ul><blockquote><strong>2. Png to Webp :</strong></blockquote><p>Converting PNG drawables to Webp can lead to a significant reduction in APK size, often achieving a 60%-70% reduction in asset size.</p><p><strong>Important Note:</strong></p><p><em>Optimizing WebP assets through Android Studio’s conversion process is highly efficient compared to using assets directly from designers or design tools like Figma or Zeplin. The results can be interesting in terms of APK size reduction.</em></p><p><strong>Select Webp images -&gt; right click -&gt; convert to PNG</strong></p><p>After conversion to PNG, now convert all these images to webp.</p><p><strong>Select PNG images -&gt; right click -&gt; convert to Webp</strong></p><p>This approach significantly reduces the APK size.</p><blockquote><strong>3. Remove Unused Resources :</strong></blockquote><p>As the Project scope increases, we might have added many drawables that are not in use. Removing these unused resources helps in reducing APK size</p><p>Navigate to “<strong>Refactor</strong>” at the top of Android Studio, then select “<strong>Remove Unused Resources</strong>.” This action will display a list of resources. Verify whether each resource is being used in your project and proceed to delete resources that are confirmed as unused.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*VZPhyC6t-OoY0wMK9_YsaQ.png" /></figure><blockquote><strong>4. Add ResConfigs :</strong></blockquote><p>The “<strong>resConfigs</strong>” option provides control over which language or locale-specific resources are included in your app’s APK (Android Package) file. This feature is valuable for optimizing your app’s size by excluding unnecessary resources associated with specific languages or configurations.</p><p>To include only English resources and exclude resources for other locales in your app’s APK, add the following line inside the defaultConfig block of your app&#39;s build.gradle file:</p><p>If your app supports multiple languages, add language codes like below.</p><blockquote><strong>5. Handling In-App Assets :</strong></blockquote><p><strong>Step 1</strong>: To ensure a smooth user experience, we included high-quality images within the app to avoid slow loading times from external URLs. We optimized this by shipping 10 essential images with the APK, even though the app only displays a maximum of 5 at any given time. By reducing image count and storage consumption, we improved app performance and eliminated unexpected blank screens during image loading.</p><p><strong>Step 2: </strong>For splash screen, we initially used an 8-second video of approximately 2MB in size, which was displayed only during the first app launch. To optimize app size and user experience, we decided to trim the video down to approximately 800KB, making it more efficient for its limited use case.</p><blockquote><strong>6. Font Optimization:</strong></blockquote><p>We received designs from multiple teams for various features, each with their preferred fonts like ‘Inter’ and ‘Poppins.’ Using multiple .ttf font files increases the app’s size. To reduce the app’s footprint, we standardized on a single font style throughout the app, eliminating redundant font files.</p><p>However, if your app requires multiple font styles, consider using <a href="https://medium.com/android-news/downloadable-fonts-android-283b0cc21934">Downloadable Fonts</a>. This approach allows you to avoid embedding fonts directly within the app.</p><h3>Result:</h3><p>With all the above steps and some minor refactoring across the app, we successfully reduced the APK size from <strong>20.6 MB to 8.3 MB 😍 </strong>🥳, marking an impressive <strong>~60%</strong> reduction in APK size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*or_Yp4ajrMl2SuTvnMnmyA.png" /></figure><p>Even though the APK size is 8.3 MB, users are required to download only <strong>7.7 MB </strong>🥳 of the APK as shown above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*enQ0Q4XpJZFbI4UqJB3EhA.jpeg" /><figcaption>Image by fabrikasimf</figcaption></figure><p>In the next article, we delve into memory optimization where we’ve achieved a remarkable 70% reduction in memory usage. Explore the full details in the article <a href="https://medium.com/@tarunanchala/65-smaller-apks-and-70-less-memory-how-i-optimized-my-android-app-part-ii-app-memory-d4e652cf2c49"><strong>65% Smaller APKs and 70% Less Memory: How I Optimized My Android App -Part II (App Memory)</strong></a>:</p><p><a href="https://medium.com/@tarunanchala/65-smaller-apks-and-70-less-memory-how-i-optimized-my-android-app-part-ii-app-memory-d4e652cf2c49">65% Smaller APKs and 70% Less Memory: How I Optimized My Android App -Part II (App Memory)</a></p><p>Thanks for Reading….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c0084da83a1" width="1" height="1" alt=""><hr><p><a href="https://engg.glance.com/glance-tv-optimization-part-1-shrinking-apk-size-by-65-2c0084da83a1">Glance TV Optimization Part 1: Shrinking APK Size by 65%</a> was originally published in <a href="https://engg.glance.com/">Glance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>