<?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 Bholay Nath Singh on Medium]]></title>
        <description><![CDATA[Stories by Bholay Nath Singh on Medium]]></description>
        <link>https://medium.com/@bholaynathsingh335619?source=rss-347a4af2cb20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4CJ90fuFSx7AzxAZ</url>
            <title>Stories by Bholay Nath Singh on Medium</title>
            <link>https://medium.com/@bholaynathsingh335619?source=rss-347a4af2cb20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:08:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bholaynathsingh335619/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[Stemming vs Lemmatization: A Simple NLP Technique I Used for Text Comparison]]></title>
            <link>https://medium.com/@bholaynathsingh335619/stemming-vs-lemmatization-a-simple-nlp-technique-i-used-for-text-comparison-d91033dbdd41?source=rss-347a4af2cb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/d91033dbdd41</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bholay Nath Singh]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 10:52:12 GMT</pubDate>
            <atom:updated>2026-10-12T10:52:12.969Z</atom:updated>
            <content:encoded><![CDATA[<p>During my experience as an AI-ML Developer, I have worked on different kinds of problems, from building machine learning models to working with text data and document processing. One thing I realised while working on professional projects is that not every problem requires a complex AI model or a deep learning approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Dd1DIYIcT5uxJsyQHsCHg.png" /></figure><p>Sometimes, the solution is much simpler than we think.</p><p>One such problem is <strong>text comparison</strong>.</p><p>At first, comparing two text values might look like a very simple task. We can use Python’s == operator to check whether two strings are equal, or use regular expressions (re) to handle specific text patterns. These approaches work well when we know exactly what we are looking for.</p><p>But what happens when two texts have the same meaning or use similar words, but are written differently?</p><p>For example:</p><ul><li>“The company is processing the documents.”</li><li>“The company processed the document.”</li></ul><p>If we compare these two sentences directly using ==, Python will return False. Even after applying some regular expressions, we might still struggle to handle all the variations of words.</p><p>This is where Natural Language Processing (NLP) becomes useful.</p><p>During my experimentation with text comparison, I explored two basic but useful NLP techniques: <strong>Stemming and Lemmatization</strong>. Both techniques help us reduce words to their base forms, making text comparison more meaningful in certain use cases.</p><p>In this blog, let’s understand what they are, how they work, and when we can use them.</p><h3>Why is direct text comparison not always enough?</h3><p>Consider a practical example from document processing.</p><p>Suppose we receive two documents containing information about a product, an invoice, or a purchase order. We want to compare specific text fields extracted from these documents.</p><p>One document contains the word “delivered”, while another contains “delivering” or “delivery”. Depending on the context, these words may be related, but a direct string comparison will treat them as different.</p><p>The same problem occurs with words such as:</p><ul><li>Connect, connected, connecting</li><li>Approve, approved, approving</li><li>Organise, organised, organising</li></ul><p>If our objective is to identify differences in the exact text, then this behaviour is correct. However, if we want to compare text while reducing variations caused by different word forms, we need a different approach.</p><p>One option is to use text normalisation techniques before comparison.</p><p>We could also use embeddings to calculate semantic similarity between two sentences. However, embeddings are not always the first solution I would choose for every text comparison problem. They introduce additional complexity and computational overhead, and their usefulness depends on what exactly we want to compare.</p><p>For a simple use case where the main issue is variations in word forms, traditional NLP techniques can be sufficient.</p><p>This is where Stemming and Lemmatization come into the picture.</p><h3>1. Stemming: Cutting words down to their roots</h3><p>Stemming is one of the simplest text normalisation techniques in NLP.</p><p>Think of Stemming as using a pair of scissors. It applies rules to remove prefixes or suffixes from words to produce a shortened form. It does not necessarily understand the actual meaning of a word or whether the resulting word is grammatically correct.</p><p>For example, depending on the stemming algorithm:</p><ul><li>Playing → Play</li><li>Played → Play</li><li>Connected → Connect</li><li>Studies → Studi</li></ul><p>Notice the last example. The stemmer produces “studi”, which is not a proper English word. This is not necessarily a bug. Stemming focuses on reducing related word forms, not on producing a valid dictionary word.</p><p>Similarly, words such as “universal”, “university”, and “universe” might look similar, but we should not assume that a stemmer will always reduce them to the same root. The output depends on the algorithm and its rules.</p><p>One popular stemming algorithm is the <strong>Porter Stemmer</strong>, which is available through the NLTK library in Python.</p><p>Here is a simple implementation:</p><pre>from nltk.stem import PorterStemmer</pre><pre>stemmer = PorterStemmer()</pre><pre>words = [<br>    &quot;playing&quot;,<br>    &quot;played&quot;,<br>    &quot;connected&quot;,<br>    &quot;studies&quot;,<br>    &quot;happily&quot;<br>]</pre><pre>for word in words:<br>    print(word, &quot;-&gt;&quot;, stemmer.stem(word))</pre><p>The main advantage of Stemming is that it is fast and computationally inexpensive. It can be useful when we want to reduce word variations across a large amount of text without needing a dictionary-based linguistic analysis.</p><p>However, there is a limitation. Since the output can be an incomplete or artificial word, Stemming is not always the best choice when the actual linguistic meaning of a word matters.</p><h3>2. Lemmatization: Finding the actual base form</h3><p>Lemmatization takes a slightly different approach.</p><p>Instead of simply cutting off word endings, it attempts to identify the correct base form of a word, known as its <em>lemma</em>. It uses linguistic information, such as vocabulary and grammatical rules, depending on the tool being used.</p><p>Think of it as looking up a word in a dictionary rather than cutting it down with scissors.</p><p>For example:</p><ul><li>Playing → Play</li><li>Played → Play</li><li>Better → Good</li><li>Cars → Car</li></ul><p>The exact result depends on the lemmatizer and the linguistic context it receives.</p><p>An important point to understand is that Lemmatization can depend on the part of speech of a word. For example, the word “saw” can refer to the past tense of “see” or to a cutting tool. A context-aware lemmatizer can use this information to produce the appropriate base form.</p><p>Using Python and NLTK, we can experiment with Lemmatization as follows:</p><pre>import nltk<br>from nltk.stem import WordNetLemmatizer</pre><pre>nltk.download(&quot;wordnet&quot;)<br>nltk.download(&quot;omw-1.4&quot;)</pre><pre>lemmatizer = WordNetLemmatizer()</pre><pre>words = [<br>    &quot;playing&quot;,<br>    &quot;played&quot;,<br>    &quot;cars&quot;,<br>    &quot;better&quot;<br>]</pre><pre>for word in words:<br>    print(word, &quot;-&gt;&quot;, lemmatizer.lemmatize(word))</pre><p>There is one important detail here. NLTK’s WordNetLemmatizer treats a word as a noun by default. Therefore, it may not produce the expected base form for every word unless we provide the appropriate part of speech.</p><p>For example, to lemmatize “playing” as a verb, we can write:</p><pre>print(lemmatizer.lemmatize(&quot;playing&quot;, pos=&quot;v&quot;))<br># play</pre><pre>print(lemmatizer.lemmatize(&quot;better&quot;, pos=&quot;a&quot;))<br># good</pre><p>This shows why Lemmatization can be more useful when linguistic correctness matters, although it also requires more care during implementation.</p><h3>Stemming vs Lemmatization: Which one should we use?</h3><p>Both techniques solve a similar problem, but their approaches are different.</p><p>Stemming is generally faster and simpler because it applies rules to reduce words. Lemmatization is more linguistically informed and can return meaningful base words, but it may require additional resources and processing.</p><p>For example, if we are processing thousands of product descriptions and want to reduce common word variations, Stemming might be sufficient.</p><p>On the other hand, if we are working on document analysis, search, or text comparison where the quality of normalised words matters, Lemmatization may be a better option.</p><p>But there is no universal answer. The correct choice depends on the data, the comparison requirements, and the errors we can tolerate.</p><p>Also, neither technique understands the complete meaning of a sentence. Reducing “approved” and “approving” to a common base form does not mean that the two sentences containing these words have the same meaning.</p><p>For more complex use cases, we may need techniques such as TF-IDF, fuzzy matching, or sentence embeddings. These methods solve different problems, and we should select them based on the actual requirement rather than using them simply because they are more advanced.</p><h3>My experimentation and implementation</h3><p>While exploring these techniques for text comparison, I wanted to keep the implementation simple enough for anyone to understand and experiment with.</p><p>Instead of limiting the explanation to theory, I created a GitHub repository containing my experimentation and implementation of Stemming and Lemmatization using Python.</p><p>The repository includes a Jupyter Notebook with a simple explanation and practical examples to understand how these techniques work and how their outputs differ.</p><p><strong>GitHub Repository:</strong><br><a href="https://github.com/BholaySingh23/Stemming-And-Lemmatization.git">https://github.com/BholaySingh23/Stemming-And-Lemmatization.git</a></p><p>You can clone the repository, run the notebook, change the input words, and observe how different word forms are processed. Experimenting with your own examples is one of the easiest ways to understand the difference between these techniques.</p><h3>Final thoughts</h3><p>One thing I have learned from working on AI-ML projects is that selecting the right technique is just as important as implementing it correctly.</p><p>We do not always need an LLM, a deep learning model, or sentence embeddings to solve a text-related problem. Sometimes, a traditional NLP technique can solve the problem with less complexity and lower computational cost.</p><p>Stemming and Lemmatization are good examples of this. They are simple concepts, but they can be useful building blocks when preparing text for comparison, search, or other NLP tasks.</p><p>The key is to understand what problem we are trying to solve first and then select the technique that fits the requirement.</p><p>If you are learning NLP or working on a text comparison use case, I would recommend experimenting with both techniques before moving towards more complex approaches.</p><p>Sometimes, the best solution is not the most advanced one. It is the one that solves the problem effectively without adding unnecessary complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d91033dbdd41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PNG Decompression Bomb: How a Tiny Image Can Bring Down a Document AI Pipeline]]></title>
            <link>https://medium.com/@bholaynathsingh335619/png-decompression-bomb-how-a-tiny-image-can-bring-down-a-document-ai-pipeline-7d35eb05fbc1?source=rss-347a4af2cb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d35eb05fbc1</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[denial-of-service]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aidoc]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Bholay Nath Singh]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 04:29:59 GMT</pubDate>
            <atom:updated>2026-09-04T04:29:59.580Z</atom:updated>
            <content:encoded><![CDATA[<p>When we talk about security testing an AI application, our first thoughts usually go towards things like prompt injection, data leakage, authentication, API security, or trying to manipulate the model’s output.</p><p>But while working with Document AI, I realised something important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXUSf4aWER570dmBZg9mQg.png" /></figure><p><strong>The AI model is not necessarily where an attacker has to attack.</strong></p><p>Before a document reaches an OCR model, VLM, LLM or any other AI component, it usually goes through a number of traditional software components.</p><p>The document has to be uploaded.</p><p>It has to be parsed.</p><p>PDF pages may have to be rendered.</p><p>Images have to be decoded.</p><p>Images may have to be resized, cropped or converted.</p><p>Only after all of this does the actual AI processing begin.</p><p>And this means that something as simple as an image decoder can become an attack surface.</p><p>I came across exactly this problem while doing security testing and penetration testing of an AI-enabled document extraction system.</p><p>The issue was called a <strong>PNG decompression bomb</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*0jreSVXr_0iYpzvh9EqWCg.png" /></figure><p>So I decided to understand it properly instead of just adding a check and moving on.</p><p>I created one in a controlled environment, tested how image dimensions affect memory requirements, and then looked at how I could protect a real Document AI pipeline from this type of input.</p><p>This article is about what I learned.</p><h3>First, What Exactly Is a PNG Decompression Bomb?</h3><p>To understand a decompression bomb, we first need to understand one simple difference:</p><p><strong>The size of an image file on disk is not the same as the amount of memory required to process that image.</strong></p><p>This is especially important for compressed image formats such as PNG.</p><p>PNG is a lossless image format. The image stored on disk is compressed, and when an application opens the image, the compressed representation has to be decoded back into pixels.</p><p>For a normal image, this is completely fine.</p><p>Suppose I have an image with:</p><pre>1000 × 1000 pixels</pre><p>That gives us:</p><pre>1000 × 1000 = 1,000,000 pixels</pre><p>or 1 million pixels.</p><p>If it is an 8-bit RGB image, a very rough estimate of the raw pixel memory is:</p><pre>1000 × 1000 × 3 = 3,000,000 bytes</pre><p>That is approximately 3 MB.</p><p>Nothing unusual here.</p><p>Now imagine that the PNG file is only a few kilobytes or megabytes, but its metadata says:</p><pre>Width  = 200,000<br>Height = 200,000</pre><p>The number of pixels is now:</p><pre>200,000 × 200,000 = 40,000,000,000 pixels</pre><p>That’s <strong>40 billion pixels</strong>.</p><p>If we were dealing with an RGB representation requiring roughly 3 bytes per pixel, the raw pixel data alone would theoretically require:</p><pre>40,000,000,000 × 3 = 120,000,000,000 bytes</pre><p>or around:</p><pre>120 GB</pre><p>And that’s before considering the additional memory used by image-processing operations, copies, NumPy arrays, OCR preprocessing, model tensors and other application components.</p><p>This is the basic idea behind a decompression bomb.</p><p>A relatively small compressed input can cause the application to deal with an extremely large expanded representation.</p><h3>The Important Part: Compression Is Not the Vulnerability</h3><p>It is tempting to think that PNG compression itself is the problem.</p><p>It isn’t.</p><p>Compression is doing exactly what it is supposed to do.</p><p>The problem appears when an application accepts an image whose <strong>declared dimensions are far beyond what the application can safely process</strong>.</p><p>Think about what happens internally.</p><p>The PNG contains metadata describing the dimensions of the image.</p><p>The decoder reads those dimensions.</p><p>The application then needs to create an in-memory representation of those pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*Zjdox9XCBoTX5IAZhAJJfw.png" /></figure><p>This is where the small input can become a very large resource requirement.</p><p>The important relationships are:</p><pre>Pixel Count = Width × Height</pre><p>and approximately:</p><pre>Raw Image Memory<br>≈ Width × Height × Bytes Per Pixel</pre><p>For an 8-bit RGB image:</p><pre>Memory ≈ Width × Height × 3</pre><p>For an RGBA image:</p><pre>Memory ≈ Width × Height × 4</pre><p>This is a simplified calculation, but it is enough to understand the problem.</p><p>The actual memory consumption of an application can be significantly higher.</p><h3>I Wanted to See This for Myself</h3><p>Rather than only reading about the problem, I decided to reproduce it in a controlled environment.</p><p>I created a small experimental repository containing a Jupyter Notebook where I generated PNG files with extremely large dimensions.</p><p>The repository is available here:</p><p><a href="https://github.com/BholaySingh23/PNG_Decompression_Bomb?utm_source=chatgpt.com">PNG Decompression Bomb — GitHub Repository</a></p><p>The first thing I tried was actually creating a very large image using Pillow itself.</p><p>The image dimensions were:</p><pre>150,000 × 150,000</pre><p>and I used an RGB image.</p><p>That means the theoretical raw pixel data is:</p><pre>150,000 × 150,000 × 3<br>= 67,500,000,000 bytes</pre><p>or approximately <strong>62.86 GiB</strong>.</p><p>The interesting part was that creating this image directly using Pillow already required the system to deal with the huge in-memory representation.</p><p>In my experiment, this approach caused the Colab environment to crash.</p><p>That taught me something important.</p><p>There is actually a difference between:</p><p><strong>creating a huge image</strong></p><p>and:</p><p><strong>creating a tiny compressed file that represents a huge image.</strong></p><p>The first approach needs the memory while generating the image.</p><p>The second is much more interesting from a security perspective.</p><h3>Creating the Actual Decompression Bomb</h3><p>For the second experiment, I changed the approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*aEy9SU2k-qL2qm8kJ-uYwQ.png" /></figure><p>Instead of asking Pillow to create the entire huge image in memory, I constructed the PNG structure directly.</p><p>I won’t reproduce the complete bomb-generation code here because the purpose of the experiment was security testing in an isolated environment, not providing a ready-made denial-of-service payload.</p><p>But conceptually, the experiment was based on how a PNG is structured.</p><p>A PNG contains chunks, and one of the important chunks is the IHDR chunk.</p><p>The IHDR contains information such as:</p><ul><li>width</li><li>height</li><li>bit depth</li><li>colour type</li><li>compression method</li><li>filter method</li><li>interlace method</li></ul><p>I created a PNG where the dimensions declared in the header were extremely large while keeping the actual file extremely small.</p><p>For one of my experiments, I used:</p><pre>Width  = 65,535<br>Height = 65,535</pre><p>That gives:</p><pre>65,535 × 65,535 = 4,294,836,225 pixels</pre><p>or approximately:</p><p><strong>4.29 billion pixels.</strong></p><p>I used 8-bit grayscale for this experiment, so the theoretical raw pixel representation is approximately:</p><pre>4,294,836,225 × 1 byte<br>= 4,294,836,225 bytes</pre><p>which is around:</p><p><strong>4 GB of pixel data.</strong></p><p>But the generated PNG file itself was only approximately:</p><p><strong>0.07 KB.</strong></p><p>That is the part that makes the experiment interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*lcepC2m0OdAQYtS2V27IDw.png" /></figure><p>A file measured in <strong>bytes or kilobytes</strong> was declaring an image containing <strong>billions of pixels</strong>.</p><h3>Why Does This Become Dangerous?</h3><p>At this point you might ask:</p><blockquote><em>“If the file is only 0.07 KB, why would the server care?”</em></blockquote><p>Because the server doesn’t ultimately work with the 0.07 KB compressed representation.</p><p>It needs to decode the image.</p><p>And decoding means reconstructing the image represented by those dimensions.</p><p>This is where the resource requirements change dramatically.</p><p>Imagine an API that does something like:</p><pre>from PIL import Image</pre><pre>image = Image.open(uploaded_file)<br>image.load()</pre><p>The developer may look at the uploaded file and see:</p><pre>File size: 1 MB</pre><p>and think:</p><blockquote><em>“This is a very small request.”</em></blockquote><p>But the image decoder may see:</p><pre>Width × Height<br>      ↓<br>Huge number of pixels<br>      ↓<br>Huge memory requirement</pre><p>So the important security metrics are not just:</p><pre>Uploaded file size</pre><p>but also:</p><pre>Declared dimensions<br>Pixel count<br>Expected decoded memory<br>Processing cost</pre><h3>A 1 MB File Can Still Be a Problem</h3><p>This is one of the biggest lessons from this experiment.</p><p>A common security check is:</p><pre>if file_size &gt; 10 * 1024 * 1024:<br>    reject()</pre><p>There is nothing wrong with this check.</p><p>You should have an upload-size limit.</p><p>But it isn’t enough.</p><p>Consider these two files:</p><pre>Image A<br>File size: 8 MB<br>Dimensions: 4000 × 4000</pre><p>and:</p><pre>Image B<br>File size: 1 MB<br>Dimensions: extremely large</pre><p>The second file can potentially be much more dangerous to an image-processing pipeline even though it is smaller on disk.</p><p>This is why <strong>file size and decoded resource size need to be treated as separate security concerns.</strong></p><h3>How Can This Crash a Server?</h3><p>Let’s say your Document AI API has four workers.</p><p>Each worker receives an image and starts processing it.</p><p>Now imagine one request causes several gigabytes of memory pressure.</p><p>That one request may consume a significant portion of the available RAM.</p><p>Now imagine multiple such requests arriving at the same time.</p><p>The situation becomes:</p><pre>Worker 1 → Large image → High memory<br>Worker 2 → Large image → High memory<br>Worker 3 → Large image → High memory<br>Worker 4 → Large image → High memory</pre><p>Eventually the system may start swapping, become extremely slow, terminate processes or run into an out-of-memory condition.</p><p>In a containerised environment, the container itself may be killed when it crosses its memory limit.</p><p>So the attacker doesn’t necessarily need to compromise your server.</p><p>They may only need to repeatedly make the server perform an extremely expensive operation.</p><p>That makes this essentially a <strong>Denial-of-Service problem</strong>.</p><p>Pillow itself describes decompression bombs as malicious images that can decompress into huge amounts of data and potentially consume enough memory to cause disruption.</p><h3>And This Is Where Document AI Becomes Interesting</h3><p>When I first encountered this, I started thinking about how often we actually process images in Document AI systems.</p><p>The answer is:</p><p><strong>Almost everywhere.</strong></p><p>Consider a typical document extraction use case.</p><p>A user uploads an invoice.</p><p>The invoice may be a digitally generated PDF.</p><p>Or it may be a scanned PDF.</p><p>Or it may contain embedded images.</p><p>The application might render each page into an image.</p><p>That image might then go through:</p><ul><li>Pillow</li><li>OpenCV</li><li>image resizing</li><li>image cropping</li><li>OCR</li><li>layout detection</li><li>object detection</li><li>VLM inference</li><li>LLM-based extraction</li></ul><p>So our pipeline isn’t just:</p><pre>Document → LLM → JSON</pre><p>There are many operations happening before the AI model sees anything.</p><p>And each image-processing operation potentially becomes part of the security boundary.</p><h3>The AI Model Doesn’t Even Have to Be Involved</h3><p>This is probably the most interesting part of this vulnerability.</p><p>Suppose I have a highly secure VLM.</p><p>It has:</p><ul><li>authentication</li><li>prompt-injection protection</li><li>output validation</li><li>token limits</li><li>access controls</li><li>logging</li></ul><p>All of that is good.</p><p>But what happens if the image crashes the application <strong>before the image reaches the VLM?</strong></p><p>The VLM security controls don’t matter.</p><p>The request has already caused the problem at the image-processing layer.</p><p>This changed the way I think about AI application security.</p><p>When we build AI applications, we shouldn’t only secure the AI model.</p><p>We need to secure the <strong>entire input-processing pipeline</strong>.</p><h3>How Pillow Protects Against This</h3><p>This is where Pillow provides a very useful built-in protection.</p><p>Pillow has:</p><pre>Image.MAX_IMAGE_PIXELS</pre><p>which defines a maximum number of pixels that an image can contain before Pillow considers it potentially dangerous.</p><p>In current Pillow documentation, the default value is:</p><pre>89,478,485 pixels</pre><p>or approximately <strong>89.5 megapixels</strong>.</p><p>If an image exceeds that limit, Pillow raises a DecompressionBombWarning.</p><p>If the image exceeds <strong>twice</strong> that value, Pillow raises a DecompressionBombError.</p><p>So approximately:</p><pre>89.5 MP</pre><p>is the warning boundary, while:</p><pre>178.96 MP</pre><p>is the hard-error boundary.</p><p>This distinction is important because I initially referred to the ~178 MP figure as the “cap”, but technically it is the <strong>2× threshold at which Pillow raises the exception</strong>.</p><p>The implementation in Pillow explicitly checks the pixel count and raises DecompressionBombError when the image exceeds twice MAX_IMAGE_PIXELS.</p><h3>What Happens When Pillow Opens the Image?</h3><p>One subtle point here is that:</p><pre>Image.open()</pre><p>is generally a lazy operation.</p><p>Pillow identifies the image and reads enough information to understand its structure, while the actual image data is generally loaded later when the image needs to be processed or when load() is called.</p><p>This distinction is important when testing.</p><p>You may have:</p><pre>image = Image.open(file)</pre><p>and think:</p><blockquote><em>“The image loaded successfully.”</em></blockquote><p>But that doesn’t necessarily mean that the entire pixel buffer has been decoded into memory yet.</p><p>When you perform operations that require the pixel data, such as:</p><pre>image.load()</pre><p>or image manipulation, the actual decoding work becomes relevant.</p><p>This is one reason why testing only Image.open() may not tell you the complete story about the resource consumption of your pipeline.</p><h3>The Fix I Used</h3><p>In my case, the practical solution was to use Pillow’s built-in pixel limit and make the warning an explicit failure condition rather than allowing the application to continue.</p><p>A simplified version looks like this:</p><pre>from PIL import Image<br>import warnings<br>Image.MAX_IMAGE_PIXELS = 89_478_485<br>warnings.simplefilter(<br>    &quot;error&quot;,<br>    Image.DecompressionBombWarning<br>)</pre><p>Then image processing can be wrapped with appropriate exception handling:</p><pre>try:<br>    image = Image.open(uploaded_file)<br>    image.load()<br>except Image.DecompressionBombError:<br>    # Reject oversized image<br>    ...<br>except Image.DecompressionBombWarning:<br>    # Reject image exceeding application policy<br>    ...<br>except Exception:<br>    # Handle other image-processing failures<br>    ...</pre><p>The exact error response depends on how your API is designed.</p><p>The important thing is that the malicious or unreasonable image should <strong>fail safely</strong>.</p><p>Pillow’s documentation explicitly supports converting DecompressionBombWarning into an exception using Python&#39;s warnings mechanism.</p><h3>But There Is a Very Important Mistake We Should Avoid</h3><p>You may come across code like this:</p><pre>Image.MAX_IMAGE_PIXELS = None</pre><p>This disables Pillow’s decompression-bomb protection.</p><p>It might appear to solve the problem because your large image suddenly gets processed.</p><p>But in a production application, this is usually the opposite of what you want.</p><p>You’re effectively saying:</p><blockquote><em>“I don’t want the image decoder to protect me from extremely large images.”</em></blockquote><p>Pillow’s security guidance specifically recommends <strong>not setting </strong><strong>MAX_IMAGE_PIXELS to </strong><strong>None in production</strong> and recommends treating the warning as an error.</p><p>If legitimate documents require more pixels, the better approach is to define an application-specific limit rather than completely disabling the protection.</p><h3>Why the Library Default Shouldn’t Be Your Only Security Policy</h3><p>The Pillow limit is a useful safety mechanism.</p><p>But your application should still define its own limits.</p><p>For example, a Document AI system may have:</p><pre>Maximum upload size<br>Maximum image width<br>Maximum image height<br>Maximum pixel count<br>Maximum PDF pages<br>Maximum PDF rendering DPI<br>Maximum processing time<br>Maximum concurrent jobs</pre><p>These limits should be based on what your system actually needs.</p><p>For example, if your OCR model eventually resizes every image to something like:</p><pre>2048 × 2048</pre><p>then accepting an enormous 200,000 × 200,000 source image may not make sense in the first place.</p><p>You could reject it before doing expensive processing.</p><p>This is an important security principle:</p><blockquote><strong><em>Don’t allow the input to become more expensive than the output requires.</em></strong></blockquote><h3>Pixel Count Is Not the Only Problem</h3><p>Another thing I learned while looking into this is that simply protecting against decompression bombs doesn’t make image processing completely safe.</p><p>Pillow’s current security documentation also discusses CPU exhaustion.</p><p>A large image that is technically within the pixel limit can still be expensive to process.</p><p>Operations such as:</p><ul><li>high-quality resizing</li><li>convolutions</li><li>filters</li><li>drawing operations</li></ul><p>can consume significant CPU.</p><p>Pillow therefore recommends practical dimension ceilings, CPU time limits and rate limiting in addition to pixel limits.</p><p>So a robust image-processing policy should not be:</p><pre>MAX_IMAGE_PIXELS = everything is solved</pre><p>It should be:</p><pre>Input constraints<br>+<br>Pixel constraints<br>+<br>CPU constraints<br>+<br>Memory constraints<br>+<br>Concurrency constraints<br>+<br>Timeouts</pre><h3>What About PDFs?</h3><p>This is another area that I think Document AI developers should pay attention to.</p><p>Suppose your API accepts PDFs.</p><p>You might have:</p><pre>10 MB PDF</pre><p>and consider it safe because it passes your upload-size check.</p><p>But what happens when you render every page at high resolution?</p><p>The PDF can turn into several large images.</p><p>So your actual resource consumption may be determined by:</p><pre>PDF<br>→ number of pages<br>→ rendering DPI<br>→ rendered width/height<br>→ pixel count<br>→ image memory</pre><p>This means that the same principle applies to PDF rendering.</p><p>Don’t only ask:</p><blockquote><em>“How large is the PDF?”</em></blockquote><p>Also ask:</p><blockquote><em>“How large can the representation become after I process it?”</em></blockquote><p>That is the more useful security question.</p><h3>What I Would Do in a Production Document AI Pipeline</h3><p>After encountering this issue, I started looking at image handling as a resource-management problem rather than simply an image-processing problem.</p><p>At the upload layer, I would enforce a reasonable maximum file size.</p><p>Then I would validate that the file is actually the type it claims to be rather than trusting only the extension or MIME type supplied by the client.</p><p>Once the image is opened, I would validate its dimensions and pixel count before allowing it to enter expensive preprocessing.</p><p>For PDFs, I would similarly control the number of pages and the rendering parameters.</p><p>I would also put timeouts around expensive processing operations.</p><p>And for systems processing untrusted documents at scale, I would isolate image processing from the main API process so that a problematic document doesn’t have the ability to take down the entire application.</p><p>This last part is particularly important.</p><p>Pillow’s current security recommendations include sandboxing image processing, enforcing MAX_IMAGE_PIXELS, keeping dependencies updated and setting OS/container memory limits per worker.</p><h3>Defence in Depth Is More Important Than a Single Check</h3><p>If I had to summarise the protection strategy, I wouldn’t say:</p><blockquote><em>“Use Pillow.”</em></blockquote><p>I’d say:</p><blockquote><strong><em>Build multiple independent resource boundaries.</em></strong></blockquote><p>For example, your application should have a limit on the uploaded file size.</p><p>Then the image decoder should have a pixel limit.</p><p>Then the application should have reasonable width and height limits.</p><p>Then your PDF renderer should have page and rendering limits.</p><p>Then your worker should have memory and CPU limits.</p><p>And finally, the API should have timeouts and rate limits.</p><p>Why so many layers?</p><p>Because every layer solves a slightly different problem.</p><p>A file-size limit protects your network and storage resources.</p><p>A pixel limit protects against excessive decoded image size.</p><p>A CPU limit protects against expensive image-processing operations.</p><p>A timeout protects against operations that don’t finish in a reasonable amount of time.</p><p>A container memory limit protects the rest of the infrastructure when something still goes wrong.</p><p>That is what defence in depth looks like in practice.</p><h3>What My Experiment Taught Me</h3><p>The most interesting part of this experiment wasn’t actually creating the PNG.</p><p>It was seeing the difference between what the file <strong>looked like</strong> and what it <strong>represented</strong>.</p><p>My test file could be tiny on disk.</p><p>But its declared image dimensions represented billions of pixels.</p><p>And that’s the fundamental problem.</p><p>When we look at:</p><pre>File size = 1 MB</pre><p>we are measuring the wrong thing if the expensive operation happens after decompression.</p><p>The more meaningful questions are:</p><pre>How many pixels are we going to create?</pre><pre>How much memory will those pixels require?</pre><pre>How much CPU will processing them consume?</pre><pre>How many such requests can run concurrently?</pre><pre>What happens if the processing fails?</pre><p>These are system-design questions, not just image-processing questions.</p><h3>The Bigger Lesson for AI Engineers</h3><p>This experiment also changed the way I think about security in AI applications.</p><p>When we build a Document AI pipeline, we often focus heavily on the model.</p><p>We test whether the OCR is accurate.</p><p>We test whether the VLM understands the document.</p><p>We test whether the LLM extracts the correct JSON.</p><p>We test prompt injection.</p><p>We test hallucinations.</p><p>All of that is important.</p><p>But before any of those things happen, there is an entire software stack processing the user’s input.</p><p>A malicious document can target that stack instead.</p><p>A malformed PDF can target the parser.</p><p>A decompression bomb can target the image decoder.</p><p>An enormous document can target memory and CPU.</p><p>A huge number of pages can target processing time.</p><p>And only after surviving all of these stages does the document reach our AI model.</p><p>So when we say:</p><blockquote><strong><em>“We have secured our AI application.”</em></strong></blockquote><p>we should really be asking:</p><blockquote><strong><em>“Have we secured everything that happens before, during and after the AI model processes the input?”</em></strong></blockquote><h3>Final Thoughts</h3><p>The PNG decompression bomb is a relatively simple concept.</p><p>But it demonstrates a very important security principle.</p><p><strong>The size of an input is not always the amount of work required to process that input.</strong></p><p>A compressed image can be tiny.</p><p>Its decoded representation can be enormous.</p><p>And if that image is coming from an untrusted user and entering a server-side Document AI pipeline, that difference can become a real security problem.</p><p>For me, the interesting part was not just learning that this vulnerability exists.</p><p>It was actually reproducing it in a controlled environment, understanding why the first approach crashed during image creation, manually constructing a tiny PNG with extremely large declared dimensions, and then testing how Pillow protects against it.</p><p>And the fix itself was not complicated.</p><p>The important part was knowing <strong>where the resource boundary needed to exist</strong>.</p><p>That is probably the biggest takeaway I got from this:</p><blockquote><strong><em>When building AI systems that process untrusted documents, don’t only ask whether the model can understand the input. Ask how expensive it is for your system to even reach the model.</em></strong></blockquote><p>Because sometimes the attack isn’t designed to fool your AI.</p><p><strong>Sometimes, it is designed to make sure your AI never gets the chance to run.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d35eb05fbc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BLEU, chrF and COMET: How Do We Actually Evaluate a Neural Machine Translation Model?]]></title>
            <link>https://medium.com/@bholaynathsingh335619/bleu-chrf-and-comet-how-do-we-actually-evaluate-a-neural-machine-translation-model-f3375039bd78?source=rss-347a4af2cb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3375039bd78</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-translation]]></category>
            <category><![CDATA[nmt]]></category>
            <dc:creator><![CDATA[Bholay Nath Singh]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 12:02:48 GMT</pubDate>
            <atom:updated>2026-07-20T12:02:48.600Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started working with Machine Learning models, I was mostly focused on one question:</p><blockquote><strong><em>Is my model giving the correct output or not?</em></strong></blockquote><p>For a classification problem, the answer is relatively straightforward. We can calculate accuracy, precision, recall, F1-score, and so on.</p><p>But things become slightly complicated when we move to <strong>Natural Language Processing</strong>, especially <strong>Neural Machine Translation (NMT)</strong>.</p><p>Suppose we have an English-to-Hindi translation model.</p><p>The input is:</p><pre>I am going to school.</pre><p>The model generates:</p><pre>मैं विद्यालय जा रहा हूँ।</pre><p>The human reference translation might be:</p><pre>मैं स्कूल जा रहा हूँ।</pre><p>Now the important question is:</p><blockquote><em>Is the model’s translation wrong?</em></blockquote><p>Not really.</p><p>Both विद्यालय and स्कूल mean &quot;school&quot;. The model has actually generated a perfectly understandable translation.</p><p>But if we compare the two sentences word by word, they are not exactly the same.</p><p>This is where evaluating an NMT model becomes challenging.</p><p>Unlike a traditional classification problem, there can be multiple correct ways of translating the same sentence.</p><p>For example:</p><pre>I am going to school.</pre><p>could be translated as:</p><pre>मैं स्कूल जा रहा हूँ।</pre><p>or:</p><pre>मैं विद्यालय जा रहा हूँ।</pre><p>or:</p><pre>मैं स्कूल के लिए जा रहा हूँ।</pre><p>All of these can potentially be acceptable depending on the context.</p><p>So, how do we evaluate a machine translation model?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYzjQ7tb9nFk65NpKGM_hw.png" /></figure><p>Three commonly used metrics are:</p><ol><li><strong>BLEU</strong></li><li><strong>chrF</strong></li><li><strong>COMET</strong></li></ol><p>In this blog, we will understand each of them with practical examples and the mathematics behind them.</p><h3>BLEU: Checking Word and Phrase Overlap</h3><p>BLEU stands for “<strong><em>Bilingual Evaluation Understudy”</em></strong></p><p>The basic idea behind BLEU is simple.</p><p>We compare:</p><pre>Machine Translation<br>        ↓<br>Human Reference Translation<br>        ↓<br>Compare words and phrases<br>        ↓<br>Calculate overlap</pre><p>Let’s take a simple example.</p><h4>Reference Translation</h4><pre>The cat is sitting on the mat.</pre><h4>Machine Translation</h4><pre>The cat is sitting on the rug.</pre><p>Let’s compare both sentences.</p><h4>Reference</h4><pre>The<br>cat<br>is<br>sitting<br>on<br>the<br>mat</pre><h4>Machine Translation</h4><pre>The<br>cat<br>is<br>sitting<br>on<br>the<br>rug</pre><p>Most of the words are common.</p><p>The only major difference is:</p><pre>mat ≠ rug</pre><p>Therefore, BLEU will give this translation a reasonably good score.</p><h4>BLEU Does Not Only Compare Individual Words</h4><p>BLEU also checks sequences of words called <strong>n-grams</strong>.</p><p>For example:</p><h4>1-gram (Unigram)</h4><pre>The<br>cat<br>is<br>sitting</pre><h4>2-gram (Bigram)</h4><pre>The cat<br>cat is<br>is sitting<br>sitting on</pre><h4>3-gram (Trigram)</h4><pre>The cat is<br>cat is sitting<br>is sitting on</pre><h4>4-gram</h4><pre>The cat is sitting<br>cat is sitting on</pre><p>The more word sequences match between the machine translation and the human reference, the better the BLEU score tends to be.</p><p>But how exactly is this calculated?</p><p>Let’s understand the mathematical formulation.</p><h4>BLEU Mathematical Formula</h4><p>The general BLEU formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*XqwVSldSH9fepnnyDcoxsQ.png" /></figure><p>Let’s break this down.</p><h4><strong>pn​: Modified n-gram Precision</strong></h4><p>The (p<em>n</em>) term represents the precision for a particular n-gram size.</p><p>For example:</p><pre>p₁ → Unigram precision<br>p₂ → Bigram precision<br>p₃ → Trigram precision<br>p₄ → 4-gram precision</pre><p>The general formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*eiEvrYSCIaAq-oJlI-GYaw.png" /></figure><p>For example:</p><h4>Reference</h4><pre>The cat is sitting on the mat</pre><h4>Candidate</h4><pre>The cat is sitting on the rug</pre><p>The candidate contains 7 unigrams:</p><pre>The<br>cat<br>is<br>sitting<br>on<br>the<br>rug</pre><p>The matching unigrams are:</p><pre>The<br>cat<br>is<br>sitting<br>on<br>the</pre><p>So, conceptually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*wlUKqfhKucDjCctC2P7fYQ.png" /></figure><p>This gives us the unigram precision.</p><h4>Why Is It Called “Modified” Precision?</h4><p>There is an important problem with simple precision.</p><p>Imagine the reference is:</p><pre>The cat is sitting.</pre><p>And the candidate is:</p><pre>The the the the the.</pre><p>If we simply counted matching words, the word the appears in the reference and also appears in the candidate.</p><p>A naive system might give too much credit for repeated words.</p><p>To prevent this, BLEU uses <strong>clipped n-gram counts</strong>.</p><p>The clipped count is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*0fJCG73oM8TIKnSaaGYWnw.png" /></figure><p>Suppose:</p><pre>Reference:<br>The cat is sitting</pre><p>The word:</p><pre>The</pre><p>appears only once in the reference.</p><p>Therefore, even if the candidate contains:</p><pre>The the the the</pre><p>only one occurrence can receive credit.</p><p>This prevents a model from artificially increasing its score by repeating words.</p><h4>Combining Different n-gram Precisions</h4><p>BLEU does not simply calculate:</p><pre>Unigram Precision + Bigram Precision + Trigram Precision + 4-gram Precision</pre><p>Instead, it uses a <strong>weighted geometric mean</strong>.</p><p>For example, if we use four n-gram levels with equal weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*n3UctbhfIc29pJiWkUjVkw.png" /></figure><p>Then the n-gram component becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*Wg7liid1U8vOswskrSdQtw.png" /></figure><p>This is mathematically equivalent to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*-iVZUVExUzxwc7kYsoRTCg.png" /></figure><p>The geometric mean is useful because a very low score for one n-gram level can significantly affect the final BLEU score.</p><p>For example, suppose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*97KjTFynC025zk36XCa0LQ.png" /></figure><p>Even though the unigram precision is high, the very low 4-gram precision reduces the overall score.</p><p>This makes sense because a model that gets individual words correct but fails to generate meaningful longer phrases should not receive an extremely high score.</p><h4>The Brevity Penalty</h4><p>Now let’s talk about the (BP) term.</p><p>The BLEU brevity penalty is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*UpR5l5dGq7jfwE0zWRwOZw.png" /></figure><p>Where:</p><ul><li>c = length of the candidate translation</li><li>r = effective length of the reference translation</li></ul><p>Let’s understand this with an example.</p><h4>Reference</h4><pre>The cat is sitting on the mat.</pre><p>Suppose the reference has: r = 7</p><h4>Candidate</h4><pre>The cat.</pre><p>The candidate has: c = 2</p><p>Since: c &lt; r</p><p>the brevity penalty becomes less than 1.</p><p>Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*xU2T7ESoj8KIUEK3qHi4wg.png" /></figure><p>The result is a lower score.</p><p>This is important because otherwise a model could generate only a small part of the sentence and still receive a reasonable precision score.</p><p>The brevity penalty ensures that:</p><blockquote><strong><em>A translation should not be rewarded for being accurate but incomplete.</em></strong></blockquote><h4>BLEU’s Biggest Limitation</h4><p>Let’s look at another example.</p><h4>Reference</h4><pre>The car is very fast.</pre><h4>Machine Translation</h4><pre>The automobile is extremely quick.</pre><p>From a human perspective, these sentences have almost the same meaning.</p><p>But word overlap is low:</p><pre>car          ≠ automobile<br>very         ≠ extremely<br>fast         ≠ quick</pre><p>Therefore, BLEU may give a relatively low score.</p><p>This is one of the biggest limitations of BLEU.</p><p>BLEU mainly asks:</p><blockquote><strong><em>How many words and phrases are similar?</em></strong></blockquote><p>It does not deeply understand:</p><blockquote><strong><em>Does the translation have the same meaning?</em></strong></blockquote><p>This becomes particularly important in real-world translation systems.</p><h4>BLEU in Python</h4><p>For NMT evaluation, I prefer using SacreBLEU because it standardises the evaluation process.</p><pre>pip install sacrebleu</pre><p>A simple example:</p><pre>import sacrebleu</pre><pre>references = [<br>    &quot;The cat is sitting on the mat.&quot;<br>]</pre><pre>hypotheses = [<br>    &quot;The cat is sitting on the rug.&quot;<br>]</pre><pre>score = sacrebleu.corpus_bleu(<br>    hypotheses,<br>    [references]<br>)</pre><pre>print(score.score)</pre><p>Output might look something like:</p><pre>78.5</pre><p>The exact score depends on the data and evaluation configuration.</p><p>The important point is:</p><blockquote><em>We should not blindly compare BLEU scores obtained using different datasets or different evaluation settings.</em></blockquote><h3>chrF: Looking at Characters Instead of Only Words</h3><p>Now let’s talk about <strong>chrF</strong>.</p><p>chrF stands for: “<strong><em>Character n-gram F-score”</em></strong></p><p>The key difference is:</p><pre>BLEU → Mostly word-level comparison<br>chrF → Character-level comparison</pre><p>Let’s take:</p><pre>playing</pre><p>The word can be broken into character sequences such as:</p><pre>pla<br>lay<br>ayi<br>yin<br>ing</pre><p>Now imagine the reference contains:</p><pre>playing</pre><p>and the model generates:</p><pre>played</pre><p>At the complete word level:</p><pre>playing ≠ played</pre><p>But at the character level, both words share:</p><pre>play</pre><p>So chrF can give partial credit for the similarity.</p><h4>How Does chrF Work Mathematically?</h4><p>The core idea of chrF is to calculate <strong>precision and recall over character n-grams</strong>.</p><p>For a particular character n-gram order (n):</p><h4>Character Precision</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*VBZoIfTUJZ0snjsfD2k4PA.png" /></figure><p>This answers:</p><blockquote><em>Out of the character n-grams generated by the model, how many appear in the reference?</em></blockquote><h4>Character Recall</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*_ajMQIMCnsKR4e6c4aXs7w.png" /></figure><p>This answers:</p><blockquote><em>Out of the character n-grams present in the reference, how many did the model generate?</em></blockquote><p>Once we have precision and recall, we calculate the F-score.</p><p>The general <strong>F</strong><em>β</em>​ formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*QtK47JFwZHRRIopsY8-y6A.png" /></figure><p>Where:</p><ul><li>P = precision</li><li>R = recall</li><li><em>β</em> controls the relative importance of recall</li></ul><p>For the commonly used chrF configuration:<br><em>β</em> = 2</p><p>Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*2q9c8Xc3RvA3Xg_zcpE3uA.png" /></figure><p>The reason for giving more importance to recall is that in machine translation, it is useful to check whether the generated translation covers the information present in the reference.</p><h4>A Simple chrF Calculation</h4><p>Let’s use a simplified example.</p><h4>Reference</h4><pre>playing</pre><h4>Candidate</h4><pre>played</pre><p>Suppose, for simplicity, we compare character trigrams.</p><p>The candidate contains:</p><pre>pla<br>lay<br>aye<br>yed</pre><p>The reference contains:</p><pre>pla<br>lay<br>ayi<br>yin<br>ing</pre><p>The matching trigrams are:</p><pre>pla<br>lay</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*W-sgTO2E4iwa3IPBOMHBaA.png" /></figure><p>This is a simplified example, but it demonstrates the basic calculation behind chrF.</p><p>In real implementations, the metric considers multiple character n-gram orders and combines their scores.</p><h4>Why chrF Is Useful for Morphologically Rich Languages</h4><p>This becomes particularly useful when working with languages that have many word variations.</p><p>For example:</p><pre>लड़का<br>लड़के<br>लड़कों</pre><p>These are different forms of a word.</p><p>A strict word-level metric may treat them as completely different tokens.</p><p>But character-level comparison can identify the shared patterns.</p><p>Similarly, in Kannada:</p><pre>ಮನೆ<br>ಮನೆಯಲ್ಲಿ<br>ಮನೆಗಳು</pre><p>The words are not exactly the same, but they share common character patterns.</p><p>This is one reason why chrF is often useful for:</p><ul><li>Hindi</li><li>Kannada</li><li>Tamil</li><li>Telugu</li><li>Malayalam</li><li>Marathi</li><li>Bengali</li><li>Other morphologically rich languages</li></ul><p>For Indian language translation projects, I personally would not depend only on BLEU.</p><p>I would also consider chrF.</p><h4>chrF in Python</h4><p>We can calculate chrF using SacreBLEU.</p><pre>from sacrebleu.metrics import CHRF</pre><pre>references = [<br>    [&quot;The cat is sitting on the mat.&quot;]<br>]</pre><pre>hypotheses = [<br>    &quot;The cat is sitting on the rug.&quot;<br>]</pre><pre>chrf = CHRF()</pre><pre>score = chrf.corpus_score(<br>    hypotheses,<br>    references<br>)</pre><pre>print(score.score)</pre><p>Example output:</p><pre>82.4</pre><p>Again, the actual score depends on the dataset.</p><p>The important thing is that chrF can provide a different perspective from BLEU.</p><h4>BLEU and chrF Can Give Different Results</h4><p>Let’s consider:</p><h4>Reference</h4><pre>The car is very fast.</pre><h4>Candidate</h4><pre>The automobile is extremely quick.</pre><p>BLEU may give a lower score because the words are different.</p><p>However, character-level overlap may still exist between some words.</p><p>Therefore:</p><pre>BLEU → Low or Moderate<br>chrF → May give more partial credit</pre><p>This tells us something important:</p><blockquote><em>Evaluation metrics are measuring different aspects of translation quality.</em></blockquote><p>This is why relying on only one metric can sometimes be misleading.</p><h4>chrF++</h4><p>There is also a variant called:</p><blockquote><strong><em>chrF++</em></strong></blockquote><p>The difference is that chrF++ considers:</p><pre>Character n-grams + Word n-grams</pre><p>So conceptually:</p><pre>chrF<br>    ↓<br>Character-level similarity</pre><pre>chrF++<br>    ↓<br>Character-level similarity<br>+<br>Word-level similarity</pre><p>This can provide a more complete surface-level comparison between the generated translation and the reference translation.</p><h4>But Both BLEU and chrF Have One Major Limitation</h4><p>Let’s take this example.</p><h4>Reference</h4><pre>The boy is riding a bicycle.</pre><h4>Candidate</h4><pre>A child is cycling.</pre><p>A human can understand that the meaning is very similar.</p><p>But the words are different:</p><pre>boy       ≠ child<br>riding    ≠ cycling<br>bicycle   ≠ not explicitly mentioned</pre><p>Therefore:</p><pre>BLEU → Possibly Low<br>chrF → Possibly Low or Moderate</pre><p>But the translation may still be perfectly acceptable.</p><p>This leads us to a more advanced metric.</p><h3>COMET: Evaluating Meaning</h3><p>COMET is designed to evaluate machine translation quality using <strong>neural models</strong>.</p><p>Instead of relying only on surface-level word or character overlap, COMET attempts to understand the relationship between:</p><ol><li>The original source sentence</li><li>The machine-generated translation</li><li>The human reference translation</li></ol><p>The evaluation looks conceptually like this:</p><pre>Source Sentence<br>       +<br>Machine Translation<br>       +<br>Reference Translation<br>       ↓<br>   COMET Model<br>       ↓<br>  Quality Score</pre><p>For example:</p><h4>Source</h4><pre>The boy is riding a bicycle.</pre><h4>Reference</h4><pre>A child is cycling.</pre><h4>Machine Translation</h4><pre>A young boy is riding a bike.</pre><p>A traditional word-overlap metric may not always fully capture the quality.</p><p>But a semantic model can understand that:</p><pre>boy ≈ child<br>riding a bicycle ≈ cycling<br>bike ≈ bicycle</pre><p>Therefore, COMET may give the translation a high score.</p><h4>How Does COMET Work Conceptually?</h4><p>A COMET model uses a neural encoder to generate representations of the sentences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*dD2HQ85_Z9HUZcyTRh31AA.png" /></figure><p>In simple words:</p><pre>Source Sentence<br>       ↓<br>    Encoder<br>       ↓<br> Source Representation</pre><pre>Machine Translation<br>       ↓<br>    Encoder<br>       ↓<br> Translation Representation</pre><pre>Reference Translation<br>       ↓<br>    Encoder<br>       ↓<br> Reference Representation<br>       ↓<br> Combine Representations<br>       ↓<br> Neural Regression Model<br>       ↓<br> COMET Score</pre><p>This allows COMET to evaluate more than exact word matching.</p><p>It can capture relationships such as:</p><pre>car ≈ automobile<br>fast ≈ quick<br>child ≈ boy</pre><p>This is why COMET is generally considered a more semantic evaluation metric.</p><h4>COMET in Python</h4><p>First, install the package:</p><pre>pip install unbabel-comet</pre><p>Then:</p><pre>from comet import download_model, load_from_checkpoint</pre><pre>model_path = download_model(<br>    &quot;Unbabel/wmt22-comet-da&quot;<br>)</pre><pre>model = load_from_checkpoint(model_path)</pre><p>Now create the data:</p><pre>data = [<br>    {<br>        &quot;src&quot;: &quot;The cat is sitting on the mat.&quot;,<br>        &quot;mt&quot;: &quot;The cat is sitting on the rug.&quot;,<br>        &quot;ref&quot;: &quot;The cat is sitting on the mat.&quot;<br>    }<br>]</pre><p>Then calculate the score:</p><pre>model_output = model.predict(<br>    data,<br>    batch_size=8,<br>    gpus=1<br>)<br>print(model_output.scores)</pre><p>A typical output might look like:</p><pre>[0.91]</pre><p>The exact model and score range can vary depending on the COMET model being used.</p><p>The important point is that COMET uses a trained neural model to evaluate translation quality.</p><h4>Reference-Based and Reference-Free Evaluation</h4><p>Many traditional metrics require a reference translation.</p><p>For example:</p><pre>Source<br>  ↓<br>Machine Translation<br>  ↓<br>Compare with Human Reference</pre><p>BLEU and traditional chrF evaluation require a reference translation.</p><p>Some COMET models can also perform <strong>quality estimation</strong> without a reference translation.</p><p>The flow becomes:</p><pre>Source Sentence<br>       +<br>Machine Translation<br>       ↓<br>Quality Estimation Model<br>       ↓<br>Translation Quality Score</pre><p>This is useful in real-world production systems where we may not have a human translation for every new sentence.</p><h4>A Practical NMT Evaluation Pipeline</h4><p>Suppose I train an English-to-Kannada translation model.</p><p>My test data could look like this:</p><pre>Source:<br>I am going to the market.</pre><pre>Reference:<br>ನಾನು ಮಾರುಕಟ್ಟೆಗೆ ಹೋಗುತ್ತಿದ್ದೇನೆ.</pre><pre>Model Output:<br>ನಾನು ಮಾರುಕಟ್ಟೆಗೆ ಹೋಗುತ್ತಿದ್ದೇನೆ.</pre><p>Now I can evaluate it using:</p><pre>                 NMT Model<br>                     ↓<br>              Generated Translation<br>                     ↓<br>        ┌────────────┼────────────┐<br>        ↓            ↓            ↓<br>      BLEU          chrF        COMET<br>        ↓            ↓            ↓<br> Word overlap  Character     Semantic<br>               similarity     quality</pre><p>A simple evaluation table might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8f3A0bDjYeTqeVfzXXcfg.png" /></figure><p>The improved model performs better according to all three metrics.</p><p>This gives us stronger evidence that the model has actually improved.</p><h4>What Should We Use in a Real NMT Project?</h4><p>My recommendation would be:</p><pre>BLEU + chrF + COMET</pre><p>Each metric provides a different perspective.</p><h4>BLEU</h4><p>Useful for:</p><ul><li>Comparing word-level overlap</li><li>Comparing against previous research</li><li>Benchmarking NMT models</li></ul><h4>chrF</h4><p>Useful for:</p><ul><li>Morphologically rich languages</li><li>Indian languages</li><li>Character-level similarity</li><li>Handling word-form variations</li></ul><h4>COMET</h4><p>Useful for:</p><ul><li>Semantic quality</li><li>Meaning preservation</li><li>More human-like evaluation</li><li>Better understanding of paraphrased translations</li></ul><h4>One Important Point: Metric Scores Should Be Compared Carefully</h4><p>Suppose:</p><pre>Model A:<br>BLEU  = 32<br>chrF  = 58<br>COMET = 0.78</pre><p>And:</p><pre>Model B:<br>BLEU  = 29<br>chrF  = 60<br>COMET = 0.84</pre><p>Which model is better?</p><p>There is no automatic answer.</p><p>Model A may have better word-level overlap.</p><p>Model B may produce more natural and semantically correct translations.</p><p>Also, BLEU, chrF and COMET scores are not directly comparable to each other.</p><p>For example:</p><pre>BLEU = 32<br>chrF = 58<br>COMET = 0.84</pre><p>does not mean that one metric is better simply because its number is higher or lower.</p><p>These metrics use completely different scales and mathematical formulations.</p><p>We should compare:</p><pre>BLEU(Model A) vs BLEU(Model B)</pre><p>and:</p><pre>chrF(Model A) vs chrF(Model B)</pre><p>and:</p><pre>COMET(Model A) vs COMET(Model B)</pre><p>using the same test set and evaluation setup.</p><h4>The Important Lesson</h4><p>One thing I have learned while working with Machine Learning models is that:</p><blockquote><strong><em>A metric is only a measurement. It is not the complete truth.</em></strong></blockquote><p>The same principle applies to NMT evaluation.</p><p>A model may achieve a higher BLEU score simply because its output is closer to the exact wording used in the reference translation.</p><p>Another model may achieve a better COMET score because it generates a different but more natural translation.</p><p>Therefore, a good NMT evaluation process should combine:</p><pre>Automatic Metrics<br>        +<br>Human Evaluation<br>        +<br>Real-World Testing</pre><h3>Conclusion</h3><p>When evaluating Neural Machine Translation systems, we need to understand what each metric is actually measuring.</p><p><strong>BLEU</strong> mainly evaluates word and phrase overlap between the generated translation and the human reference.</p><p>Mathematically, it combines modified n-gram precision using a weighted geometric mean and applies a brevity penalty to prevent short, incomplete translations from receiving artificially high scores.</p><p><strong>chrF</strong> evaluates character-level similarity using precision, recall and the F-score. It is especially useful when dealing with morphological variations and languages where word forms change frequently.</p><p><strong>COMET</strong> goes one step further by using neural models to evaluate the semantic quality of the translation. Instead of only checking whether the exact words match, it tries to understand whether the meaning of the source sentence has been preserved.</p><p>The simplest way to remember the difference is:</p><pre>BLEU  → Are the words and phrases similar?</pre><pre>chrF  → Are the character patterns and word forms similar?</pre><pre>COMET → Is the meaning and translation quality similar?</pre><p>In a practical NMT project, I would not depend on only one of these metrics.</p><p>I would use:</p><pre>BLEU + chrF + COMET</pre><p>and, whenever possible, validate the results using human evaluation as well.</p><p>Because ultimately, the goal of a translation model is not to produce a sentence that merely looks similar to the reference.</p><p>The real goal is:</p><blockquote><strong><em>To preserve the meaning of the original sentence in a natural and understandable way.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3375039bd78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Pixels to Production: I Tried FastAPI vs NVIDIA Triton for CV Inference… and the Results…]]></title>
            <link>https://medium.com/@bholaynathsingh335619/from-pixels-to-production-i-tried-fastapi-vs-nvidia-triton-for-cv-inference-and-the-results-7eb4e73c08a3?source=rss-347a4af2cb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eb4e73c08a3</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deployment-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Bholay Nath Singh]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 05:53:12 GMT</pubDate>
            <atom:updated>2026-04-27T05:53:12.850Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Pixels to Production: I Tried FastAPI vs NVIDIA Triton for CV Inference… and the Results Surprised Me</h3><h3>Why your simple model.predict() is not enough when real users start hitting your system</h3><p>I still remember the moment when my model was finally giving good accuracy. It was a simple cats vs dogs classifier. Training went smooth, validation looked decent, and everything felt “done”.</p><p>But then one question hit me.</p><p><strong>“Okay… but how will this model actually run in real life?”</strong></p><p>Not in a notebook. Not on one image.<br> But when users start sending requests. Multiple images. At the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sl4iwj82GlR90rtTEV-oA.png" /></figure><p>That’s where inference architecture comes into the picture. And trust me, this is where things get interesting.</p><p>So I decided to experiment with two very different approaches:</p><ul><li>One using <strong>FastAPI</strong> (simple, Python-based serving)</li><li>One using <strong>NVIDIA Triton</strong> (a proper inference engine)</li></ul><p>Same model. Same task.<br> But completely different behaviour.</p><h3>The Experiment Setup</h3><p>I kept things very real-world.</p><p>I used a basic image classification model (cats vs dogs), and tested it in two scenarios:</p><ol><li>Single image inference</li><li>Batch inference (multiple images)</li></ol><p>For testing, I used actual images from the internet instead of dummy data, because that’s how real systems behave.</p><p>Here is the exact code I used for single image benchmarking:</p><pre>import requests<br>import time<br>import io<br>import numpy as np<br>import tensorflow as tf<br>from PIL import Image<br><br><br>cat_url = &quot;https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg&quot;<br>headers = {&#39;User-Agent&#39;: &#39;Mozilla/5.0&#39;}<br>img_response = requests.get(cat_url, headers=headers)<br>img_raw = Image.open(io.BytesIO(img_response.content))<br>img_raw.save(&#39;benchmark_cat.jpg&#39;)<br># FastAPI<br>start_api = time.time()<br>with open(&#39;benchmark_cat.jpg&#39;, &#39;rb&#39;) as f:<br>    api_resp = requests.post(&quot;http://localhost:8000/predict&quot;, files={&quot;file&quot;: f})<br>api_time = time.time() - start_api<br># Triton-style<br>start_triton = time.time()<br>imported = tf.saved_model.load(&#39;model_repository/cats_dogs/1/model.savedmodel&#39;)<br>infer_fn = imported.signatures[&#39;serve&#39;]<br>img = Image.open(&#39;benchmark_cat.jpg&#39;).convert(&quot;RGB&quot;).resize((224, 224))<br>img_array = np.array(img).astype(np.float32) / 255.0<br>input_tensor = np.expand_dims(img_array, axis=0)<br>triton_results = infer_fn(input_layer_1=tf.constant(input_tensor))<br>triton_time = time.time() - start_triton</pre><p>And the result?</p><p>FastAPI was faster for a single request.</p><p>That was unexpected.</p><h3>What Actually Happens When You Send an Image to a Model</h3><p>Before comparing anything, we need to understand one important thing.</p><p>A model cannot understand an image file directly.</p><p>It does not “see” a .jpg.</p><p>It only understands numbers.</p><p>So every image goes through a transformation pipeline.</p><p>First, the image is decoded. That means converting compressed bytes into actual pixel values.</p><p>Then it is resized. Because the model expects a fixed input size, like 224x224.</p><p>Then normalization happens. Pixel values from 0–255 are scaled to 0–1.</p><p>Finally, a batch dimension is added. Even a single image becomes something like (1, 224, 224, 3).</p><p>Only after this, the model can run prediction.</p><p>Now here’s the interesting part.</p><p>Where this pipeline happens changes everything.</p><h3>FastAPI: The Simple but Heavy Approach</h3><p>When I used FastAPI, everything was happening inside Python.</p><p>The image was sent as a file using HTTP. FastAPI received it as raw bytes.</p><p>Then inside the API, I had code that converted it using PIL, resized it, normalized it, and then passed it to the model.</p><p>Something like this:</p><pre>from fastapi import FastAPI, File, UploadFile<br>from PIL import Image<br>import numpy as np<br>import tensorflow as tf<br>import io<br><br><br>app = FastAPI()<br>model = tf.keras.models.load_model(&quot;model.h5&quot;)<br>@app.post(&quot;/predict&quot;)<br>async def predict(file: UploadFile = File(...)):<br>    contents = await file.read()<br>    img = Image.open(io.BytesIO(contents)).convert(&quot;RGB&quot;).resize((224, 224))<br>    arr = np.array(img) / 255.0<br>    arr = np.expand_dims(arr, axis=0)<br>    pred = model.predict(arr)<br>    return {&quot;prediction&quot;: float(pred[0][0])}</pre><p>Looks simple, right?</p><p>But internally, a lot is happening.</p><p>Every request goes through Python runtime. Every request does preprocessing again. And most importantly, Python has something called the GIL (Global Interpreter Lock).</p><p>Because of this, handling multiple requests efficiently becomes difficult.</p><p>Also, every image travels fully through HTTP as bytes, which adds overhead.</p><p>Still, for a single request, this works really well. That’s why in my test, FastAPI was faster.</p><h3>Triton: The Specialist Approach</h3><p>Now comes the interesting part.</p><p>Triton does not behave like a normal API.</p><p>It behaves like an inference engine.</p><p>Instead of sending images, the idea is to send tensors.</p><p>That means preprocessing is done on the client side.</p><p>The server only focuses on running the model.</p><p>In my simulation, I loaded the model using TensorFlow SavedModel format:</p><pre>imported = tf.saved_model.load(&#39;model_repository/cats_dogs/1/model.savedmodel&#39;)<br>infer_fn = imported.signatures[&#39;serve&#39;]</pre><p>Then I passed the processed tensor directly.</p><p>No decoding inside server. No resizing inside server.</p><p>Just pure numerical data.</p><p>And this changes everything.</p><h3>Why Triton Felt Slower for One Image</h3><p>In my test, Triton took around 0.41 seconds, while FastAPI took 0.17 seconds.</p><p>At first, it looks like Triton is worse.</p><p>But that’s actually a wrong conclusion.</p><p>Because Triton is not built for single requests.</p><p>It is built for scale.</p><p>Loading the model, preparing execution graph, handling signatures — all this adds initial overhead.</p><p>But Triton shines when multiple requests come together.</p><h3>The Real Test: Batch Inference</h3><p>This is where things flipped completely.</p><p>I ran a second experiment where I sent multiple images.</p><p>FastAPI handled them one by one.</p><p>Triton handled them as a batch.</p><p>Here is the key part:</p><pre>batch_array = []<br>for img_path in images_data:<br>    img = Image.open(img_path)<br>    arr = np.array(img).astype(np.float32) / 255.0<br>    batch_array.append(arr)<br><br>input_batch = np.stack(batch_array, axis=0)<br>triton_results = infer_fn(input_layer_1=tf.constant(input_batch))</pre><p>And now the result changed completely.</p><p>FastAPI total time was around 0.41 seconds.</p><p>Triton total time was around 0.17 seconds.</p><p>Almost <strong>2.3x faster</strong>.</p><p>Same model. Same images.</p><p>But completely different performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ivXBTVeKTuD2ldxwzMu0A.png" /></figure><h3>What’s Happening Internally</h3><p>Now comes the most important part.</p><p>Why did this happen?</p><p>FastAPI is acting like a general-purpose system. It handles requests one by one, runs preprocessing, then prediction.</p><p>Triton is acting like a high-performance engine.</p><p>When multiple requests come, Triton does something very powerful called <strong>dynamic batching</strong>.</p><p>Instead of running 10 predictions separately, it waits for a few milliseconds, combines them, and runs one large batch.</p><p>And GPUs love batches.</p><p>Because matrix operations become more efficient.</p><p>Also, Triton is written in C++. No Python overhead. No GIL.</p><p>It talks directly to GPU using CUDA.</p><p>So instead of:</p><p>“run prediction 10 times”</p><p>It does:</p><p>“run one big prediction once”</p><p>That is the real difference.</p><h3>FastAPI vs Triton: The Real Difference</h3><p>After doing this experiment, one thing became very clear.</p><p>FastAPI is like a good engineer who can do everything.</p><p>Triton is like a specialist who only does one thing but does it extremely well.</p><p>FastAPI handles everything. Request parsing, preprocessing, model execution.</p><p>Triton only cares about inference.</p><p>FastAPI is easy to build and debug.</p><p>Triton is harder to set up, but much more powerful in production.</p><p>FastAPI scales by adding more workers.</p><p>Triton scales by optimizing execution itself.</p><h3>So What Should You Use?</h3><p>If you are building a project, testing models, or creating APIs for small traffic, FastAPI is more than enough.</p><p>It is simple, flexible, and works really well.</p><p>But if you are thinking about real production systems, where thousands of requests can come at the same time, Triton becomes very powerful.</p><p>Especially when GPUs are involved.</p><p>Because then batching, memory management, and parallel execution actually matter.</p><h3>Final Thought</h3><p>This experiment changed how I think about ML systems.</p><p>Training a model is just the beginning.</p><p>Real challenge starts when you try to serve it.</p><p>Because in real world, users don’t wait. Systems need to be fast, scalable, and efficient.</p><p>And the choice of inference architecture decides that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eb4e73c08a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salt and Pepper Noise — Tiny Dots, Big OCR Problems : Why your OCR fails even when the document…]]></title>
            <link>https://medium.com/@bholaynathsingh335619/salt-and-pepper-noise-tiny-dots-big-ocr-problems-why-your-ocr-fails-even-when-the-document-f86993a5b0bc?source=rss-347a4af2cb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/f86993a5b0bc</guid>
            <category><![CDATA[ml-pipeline]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bholay Nath Singh]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 05:00:40 GMT</pubDate>
            <atom:updated>2026-03-27T05:00:40.451Z</atom:updated>
            <content:encoded><![CDATA[<h3>Salt and Pepper Noise — Tiny Dots, Big OCR Problems : Why your OCR fails even when the document looks perfectly clean</h3><p>I still remember the first time I tried extracting text from a scanned document. Everything looked perfect to the naked eye, clean white background, black text, nothing fancy. But the moment I ran my OCR pipeline… chaos. Random dots, broken characters, weird misreads like “H3llo” instead of “Hello”.</p><p>At that moment, I felt like*, where did all this noise come from?*</p><p>That’s when I got introduced to something called <strong>salt and pepper noise</strong>. And trust me, once you understand this, half of your OCR problems will start making sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbAPyGt8RpOrban3v08ItQ.png" /></figure><h3>What Exactly is Salt and Pepper Noise?</h3><p>In simple words, salt and pepper noise is just random black and white pixels scattered across an image.</p><ul><li>“Salt” → white pixels</li><li>“Pepper” → black pixels</li></ul><p>Imagine you are looking at a clean document, and suddenly someone throws tiny grains of salt and pepper all over it. That’s exactly what happens at the pixel level.</p><p>These pixels are not part of the original text or background, they are just unwanted disturbances.</p><h3>Why Does This Noise Even Appear?</h3><p>This is not because your code is bad. It usually comes from the source itself.</p><p>When you scan or capture documents, a lot of real-world issues come into play:</p><p>The scanner sensor might have small errors. Sometimes dust particles sit on the scanner glass. If you click a photo using your phone, lighting conditions may not be perfect. Compression (like saving as low-quality JPEG) also introduces these random pixels.</p><p>So basically, even before your model sees the image, the damage is already done.</p><h3>How It Affects OCR (This is Where the Real Pain Starts)</h3><p>Now let’s talk about why this noise is such a headache.</p><p>OCR models don’t “see” like humans. We can ignore small dots and still read the text easily. But models treat every pixel as information.</p><p>So what happens?</p><p>A small black dot near a character might make:</p><ul><li>“i” look like “l”</li><li>“o” look like “a”</li><li>“.” appear randomly inside words</li><li>Characters break into pieces</li></ul><p>For example:</p><p>Original text:</p><pre>Invoice Number: 12345</pre><p>With salt and pepper noise:</p><pre>Invo.ce Num.ber: 12.45</pre><p>See the problem? The structure itself starts breaking.</p><p>Even worse, if you’re doing downstream tasks like NLP or data extraction, these small errors propagate and create bigger issues.</p><h3>Real-Life Example (Relatable One)</h3><p>Let’s say you are building a system to extract data from bank statements or Aadhaar cards.</p><p>Now imagine:</p><ul><li>A dot appears inside a number → ₹10,000 becomes ₹1.0,000</li><li>A letter breaks → “Name” becomes “Narne”</li></ul><p>Now your pipeline might:</p><ul><li>Misclassify fields</li><li>Fail validation checks</li><li>Or worse, store wrong data</li></ul><p>That’s when you realize, this is not just a small image problem, it’s a full pipeline issue.</p><h3>How Do We Handle This?</h3><p>Now comes the interesting part — how do we fix it?</p><p>The goal is simple: <strong>remove noise without damaging the actual text</strong>.</p><p>One of the most common and effective techniques is using a <strong>median filter</strong>.</p><p>Instead of averaging pixels (which can blur text), median filtering replaces each pixel with the median of its neighborhood. This way, those random black and white spikes get removed, but edges (like text) stay sharp.</p><p>In simple terms:</p><ul><li>Noise goes away</li><li>Text stays readable</li></ul><p>Now comes the interesting part, how do we actually fix this problem in real-world pipelines?</p><h3>Other Practical Tricks I’ve Used</h3><p>From my experience, there is no single magic function that removes salt and pepper noise completely. Instead, what works better is a <strong>combination of multiple techniques applied step by step</strong>, almost like a pipeline.</p><p>Below is one such pipeline that I’ve used while working with document images:</p><pre>import cv2<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br>def process_and_compare(file_path):<br>    # 0. Load Image<br>    img = cv2.imread(file_path)<br>    if img is None:<br>        print(f&quot;Error: Could not load image from {file_path}&quot;)<br>        return<br><br>    # 1. Grayscale<br>    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)<br><br>    # 2. Shadow removal — Using a Large Gaussian Blur for background estimation<br>    bg = cv2.GaussianBlur(gray, (101, 101), 0)<br>    shadow_removed = cv2.divide(gray, bg, scale=255)<br><br>    # 3. CLAHE (Local Contrast)<br>    clahe = cv2.createCLAHE(clipLimit=5.0, tileGridSize=(8, 8))<br>    enhanced = clahe.apply(shadow_removed)<br><br>    # 4. Gamma correction<br>    gamma = 0.55<br>    inv_gamma = 1.0 / gamma<br>    table = np.array([((i / 255.0) ** inv_gamma) * 255 for i in range(256)]).astype(&quot;uint8&quot;)<br>    corrected = cv2.LUT(enhanced, table)<br><br>    # 5. Final Sharpening<br>    def unsharp_mask(image, amount=1.5):<br>        blurred = cv2.GaussianBlur(image, (5, 5), 1.0)<br>        sharpened = cv2.addWeighted(image, 1.0 + amount, blurred, -amount, 0)<br>        return sharpened<br>    <br>    final_output = unsharp_mask(corrected, amount=1.0)<br><br>    # Display<br>    plt.figure(figsize=(20, 10))<br>    <br>    plt.subplot(1, 2, 1)<br>    plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))<br>    plt.title(&quot;Original Document&quot;)<br>    plt.axis(&#39;off&#39;)<br><br>    plt.subplot(1, 2, 2)<br>    plt.imshow(final_output, cmap=&#39;gray&#39;)<br>    plt.title(&quot;Processed (Optimized for VLM)&quot;)<br>    plt.axis(&#39;off&#39;)<br><br>    plt.tight_layout()<br>    plt.show()</pre><p>This is basically a combination of multiple techniques in a pipeline. Each step is doing a small job, but together they improve the overall quality a lot. I’ll explain each component in detail in some other blog, but for now just focus on the idea that <strong>we need to experiment with different parameters and combinations</strong> depending on the type of document.</p><p>Let me quickly give you a small intuition of what each step is doing:</p><p>Grayscale conversion reduces the image complexity and removes unnecessary color information, which is not useful for text.</p><p>Shadow removal helps in normalizing uneven lighting, especially when documents are captured using mobile cameras.</p><p>CLAHE (Contrast Limited Adaptive Histogram Equalization) improves local contrast, so faded or low-visibility text becomes clearer.</p><p>Gamma correction adjusts brightness levels — sometimes text is too dark or too light, and this step helps balance that.</p><p>Sharpening enhances edges, making characters more defined and easier for OCR models to detect.</p><p>Sometimes even resizing the image improves OCR performance because models prefer certain resolutions.</p><p>The main takeaway here is simple:</p><blockquote><em>Don’t rely on a single trick. Build a pre-processing pipeline and keep tweaking it.</em></blockquote><p>Some documents will respond well to this setup, some won’t. That’s where your experimentation mindset comes in, and honestly, that’s where the real learning happens.</p><h3>Small Insight (This Changed My Approach)</h3><p>Earlier I used to directly throw images into OCR and expect perfect results.</p><p>But now I think like this:</p><blockquote><em>“OCR is not the hero. Preprocessing is the hero.”</em></blockquote><p>If your input image is clean, even a basic OCR model will perform well. But if your image is noisy, even the best model will struggle.</p><h3>Final Thoughts</h3><p>Salt and pepper noise may look like a small issue, but in document text extraction, it plays a huge role.</p><p>It silently degrades your results, creates confusion in models, and impacts downstream tasks.</p><p>So next time your OCR gives weird outputs, don’t just blame the model. Take a step back and check the image quality. Chances are, some invisible “salt and pepper” is already sitting there.</p><p>And once you start handling it properly, you’ll see a noticeable jump in your extraction accuracy.</p><p>If you’ve faced similar issues while working with OCR or document pipelines, you’ll know exactly what I’m talking about. And if you’re just starting out, trust me… keep preprocessing in focus, it will save you a lot of debugging time later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f86993a5b0bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Manual Model Chaining to Pipeline(): A Lesson I Learnt the Hard Way]]></title>
            <link>https://medium.com/@bholaynathsingh335619/from-manual-model-chaining-to-pipeline-a-lesson-i-learnt-the-hard-way-b65e4e5cf754?source=rss-347a4af2cb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/b65e4e5cf754</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn-pipelines]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Bholay Nath Singh]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 18:01:26 GMT</pubDate>
            <atom:updated>2026-02-01T18:01:26.952Z</atom:updated>
            <content:encoded><![CDATA[<p>When we start learning machine learning, everything looks very straight.<br> One dataset, one model, one output.</p><p>But the moment we start working on <strong>real projects</strong>, we realize something important — <br> <strong>one model is almost never enough</strong>.</p><p>I understood this properly while working on projects where <strong>the output of one model had to become the input of another model</strong>. Initially, I handled everything manually, and honestly, it worked. But as the project grew, the code became messy, difficult to maintain, and easy to break.</p><p>That is when I came across the Pipeline() keyword, and it completely changed how I structure my ML systems.</p><h3>How I Used to Build Multi-Step Models (The Hard Way)</h3><p>Earlier, whenever a project had multiple steps, I used to write each step separately.</p><p>I would take the input, process it, pass it to a model, take its output, store it somewhere, load it again, process it further, and then pass it to the next model. At that time, I thought this was normal, because that’s how most beginners build things.</p><p>The problem was not visible in small experiments.<br> But as soon as the logic became a little complex, the cracks started showing.</p><p>I had to remember which preprocessing step was applied where, which model expected what type of input, and how to make sure the same logic was followed during prediction as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-HCoYhW6Q3KO4EH2tUcAwQ.png" /></figure><h3>A Real Incident: Number Plate Detection to Text Extraction</h3><p>One project that really exposed this issue was <strong>vehicle number plate recognition</strong>.</p><p>The idea was simple:<br> First detect the number plate from a vehicle image, then crop that part, and finally extract text from it using OCR.</p><p>But in reality, my code was doing too much manual work.</p><p>I had one model for number plate detection.<br> Then I manually handled the bounding boxes, cropped the image, saved it, reloaded it, and passed it to another model for text extraction.</p><p>Everything was tightly coupled and fragile.<br> If one small thing went wrong, the whole flow broke.</p><p>At that moment, I realised that what I was building was actually a <strong>pipeline</strong>, just without calling it one.</p><p>Conceptually, it looked like this:</p><pre>vehicle_image <br>   → number_plate_detection <br>   → plate_cropping <br>   → text_extraction</pre><p>Using a pipeline mindset, I stopped thinking in terms of “models” and started thinking in terms of <strong>steps in a flow</strong>.</p><h3>What Pipeline() Actually Means</h3><p>In very simple words, a <strong>pipeline is a fixed flow of steps</strong>.</p><p>Each step does its own work, and once it finishes, its output automatically becomes the input of the next step. You don’t need to manually pass values again and again.</p><p>You define the steps once, and then you just give input at the start and get output at the end.</p><p>This sounds small, but in real projects, it makes a huge difference.</p><h3>Another Example: Text Vectorization and Classification</h3><p>I faced a similar problem while working on <strong>text classification</strong>.</p><p>Raw text cannot be directly given to a machine learning model. First, it needs to be converted into numbers using vectorization techniques like TF-IDF or Count Vectorizer.</p><p>Earlier, I used to:</p><ul><li>Vectorize text manually</li><li>Store the vectorizer</li><li>Load it again during inference</li><li>Make sure the same logic was applied everywhere</li></ul><p>This approach was error-prone and confusing.</p><p>With Pipeline(), I could clearly define the flow:<br> First vectorization happens, then classification happens. I just pass raw text to the pipeline, and it handles everything internally.</p><p>A light example looks like this:</p><pre>from sklearn.pipeline import Pipeline<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.naive_bayes import MultinomialNB</pre><pre>text_pipeline = Pipeline([<br>    (&quot;vectorizer&quot;, TfidfVectorizer()),<br>    (&quot;classifier&quot;, MultinomialNB())<br>])</pre><p>Now the best part — I don’t need to worry about vectorization separately.</p><p>I can directly do:</p><pre>text_pipeline.fit(train_texts, train_labels)<br>predictions = text_pipeline.predict(test_texts)</pre><p>I just pass <strong>raw text</strong>, and the pipeline handles everything internally.</p><p>This not only reduced bugs but also made the code much cleaner and easier to understand.</p><h3>Why Pipeline() Feels Like a Real-World Solution</h3><p>What I like about pipelines is that they force you to <strong>think in systems, not just models</strong>.</p><p>You stop thinking, “Which model should I train?”<br> And start thinking, “What is the full flow of my data?”</p><p>Some advantages become very clear once you start using pipelines:</p><ul><li>Code becomes more readable</li><li>Training and prediction follow the exact same steps</li><li>You can replace or experiment with models easily</li><li>Less chance of missing preprocessing steps</li></ul><h3>A Simple Way to Think About Pipelines</h3><p>Think of making chai at home.</p><p>You don’t randomly add ingredients. There is a fixed order — water, tea leaves, milk, sugar. Each step depends on the previous one.</p><p>Machine learning pipelines work in the same way.<br> Each step prepares the data for the next step.</p><h3>Final Thoughts</h3><p>Initially, I thought Pipeline() was just a helper feature in scikit-learn.</p><p>But after working on multi-step projects like number plate detection with OCR and text classification with vectorization, I realized it is actually a <strong>core design concept</strong>.</p><p>If your project has:</p><ul><li>Multiple preprocessing steps</li><li>One model feeding into another</li><li>A need for clean and reliable inference</li></ul><p>Then Pipeline() is not optional — it’s essential.</p><p>Once you start thinking in pipelines, your ML projects automatically start looking more professional and production-ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b65e4e5cf754" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Messy Complaints to Meaningful Categories: Building a Smart NLP Classifier]]></title>
            <link>https://medium.com/@bholaynathsingh335619/from-messy-complaints-to-meaningful-categories-building-a-smart-nlp-classifier-c6a15bfd4f90?source=rss-347a4af2cb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6a15bfd4f90</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bholay Nath Singh]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 14:19:28 GMT</pubDate>
            <atom:updated>2026-01-25T14:19:28.439Z</atom:updated>
            <content:encoded><![CDATA[<p>While working on different ML projects, I realised one thing — in real companies, data is not always clean tables and numbers. Most of the time, it is messy human text. Every day, customers write long emails, raise tickets, and chat with support teams. Someone has to read each message and decide: is this a billing problem, a service issue, or a delivery delay? This manual work is slow, tiring, and sometimes inconsistent. So I decided to build a small NLP system that can read a complaint and automatically tag it into the right category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3b-dk-gDS7WHXJlcfjzWQ.png" /></figure><p>The problem looks simple from outside, but in reality it is quite interesting. A single sentence like “My card was charged twice but the refund is still not processed” already contains enough information to tell that it is a billing issue. Similarly, “I have not received my card even after 10 days” clearly points to delivery, while “My app is crashing when I try to reset my PIN” is a service problem. The challenge is to teach a machine to understand this difference from text.</p><p>For data, I did not want to use some random small CSV. I wanted something that looks close to real customer support data. So I used the open-source Banking77 dataset from HuggingFace. It contains thousands of real banking-related user queries, each tagged with a fine-grained intent like card_arrival, wrong_exchange_rate, charged_twice, pin_failed, and many more. In total, there are 77 such intent classes. But in real business dashboards, no one wants to see 77 tiny categories. Usually, they want high-level buckets like Billing, Service, and Delivery. So the first important step in my project was to map these 77 intents into these three business-friendly categories. All charge, refund, and fee-related intents went into Billing. All card arrival and courier related intents went into Delivery. The remaining technical and account related issues were grouped under Service. This step itself felt very close to how actual product teams design their taxonomies.</p><p>Once the labels were ready, the next step was to work on the text. Machines cannot directly understand words; they only understand numbers. So I used TF-IDF to convert each complaint sentence into a numerical vector. TF-IDF basically tells how important a word is in a sentence compared to the whole dataset. I also used bigrams, which means not only single words like “charge” or “refund”, but also two-word phrases like “wrong charge”, “card blocked”, and “delivery delay”. In complaint texts, such phrases carry much more meaning than single words. I also removed common stopwords like “is”, “the”, and “and”, because they do not help in deciding the category.</p><p>For the model, I first tried Naive Bayes, which is a classic algorithm for text classification. It works on probability and is surprisingly strong for NLP tasks. But then I also trained a Logistic Regression model with class balancing. In real complaint data, some categories are more frequent than others. For example, service-related issues are usually much more than delivery ones. If we train a model without handling this imbalance, it may become biased and start predicting the majority class most of the time. By using class_weight=”balanced” in Logistic Regression, the model is forced to give equal importance to Billing, Service, and Delivery, even if their sample counts are different.</p><p>I trained the model using a proper pipeline. The pipeline first applies TF-IDF vectorization and then passes the vectors to the classifier. This is very useful because, in production, you can directly give raw text to the pipeline and it will handle everything internally. For evaluation, I did not rely only on accuracy. Instead, I used Macro F1 score. Macro F1 calculates the F1 score for each class separately and then averages them. This is important in imbalanced datasets, because it tells you whether the model is performing well on all categories, not just the dominant one. I also looked at the full classification report to check precision and recall for Billing, Service, and Delivery individually.</p><p>After training and evaluation, the system was able to take a new complaint like “My card was delivered but it is not working and shows wrong balance” and automatically predict whether it belongs to Service or Billing. From a business point of view, this means the complaint can be directly routed to the correct team without any human reading it first. In a real call center or ticketing system, such a model can save a lot of time and reduce response delays.</p><p>To make this project closer to real-world deployment, I also thought about model packaging. Instead of just keeping everything inside a notebook, the trained pipeline can be saved using joblib and then loaded inside a FastAPI application. This way, the whole system becomes a microservice: you send a complaint as a request, and it returns the predicted category as a response in milliseconds. This is exactly how many modern customer support automation systems work behind the scenes.</p><p>What I liked most about this mini project is that it connects pure machine learning concepts with actual business problems. It starts from raw human text, passes through NLP feature engineering, uses a statistically sound classifier, and finally ends as a practical decision-making tool. It shows how something as simple as a few lines of text can be transformed into structured information that helps companies route issues faster, improve customer satisfaction, and reduce manual workload. In the end, this is the real power of applied NLP — quietly working in the background, turning unstructured language into actionable insight.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6a15bfd4f90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why OSD Matters: The Day a Rotated PDF Page Confused My OCR and VLM Models]]></title>
            <link>https://medium.com/@bholaynathsingh335619/why-osd-matters-the-day-a-rotated-pdf-page-confused-my-ocr-and-vlm-models-0af16ba53d18?source=rss-347a4af2cb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/0af16ba53d18</guid>
            <category><![CDATA[ai-pipelines]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[tesseract]]></category>
            <dc:creator><![CDATA[Bholay Nath Singh]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 09:57:20 GMT</pubDate>
            <atom:updated>2026-01-18T09:57:20.181Z</atom:updated>
            <content:encoded><![CDATA[<p>While working on a real-time AI document processing project, I faced a problem that looked very small but taught me a very deep lesson about how OCR systems actually “see” documents.</p><p>Everything was working fine. PDFs were coming, pages were being converted to images, OCR was running, and key-value pairs like <em>Invoice Number</em>, <em>Date</em>, <em>Total Amount</em> were being extracted correctly. Then one day, one particular PDF started giving completely wrong results.</p><p>The text was there. The quality was good. But the extracted fields were garbage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Yp0tXv2JcBbhKJx81R8AA.png" /></figure><p>Later I found the root cause:<br>One single page in that PDF was rotated by 90 degrees.</p><p>Visually, when I opened the PDF, it looked okay because my PDF viewer auto-rotated it. But for the OCR engine and the Vision-Language Model, the page was actually sideways. So when the model tried to read “Invoice Number”, it was literally trying to read vertical text as horizontal. No wonder the key-value extraction failed.</p><p>That day I understood one important thing:<br>OCR does not see what humans see. It sees raw pixels and orientation.</p><h3>Portrait Page vs Landscape Content — Where Confusion Starts</h3><p>There are multiple combinations possible in real-world documents:</p><ol><li><strong>Portrait page + Portrait content</strong><br>This is the ideal case. Page is upright, text flows top to bottom, left to right. Every OCR engine is happy here.</li><li><strong>Landscape page + Landscape content</strong><br>Still fine. The page is rotated, but content is also aligned with it. OCR can handle this if it knows the page orientation.</li><li><strong>Portrait page + Landscape content</strong><br>This is dangerous. The page metadata says portrait, but the actual scanned content is sideways. Humans rotate it mentally. OCR won’t, unless we tell it.</li><li><strong>Landscape page + Portrait content</strong><br>Same problem in reverse. The container and the content disagree.</li></ol><p>In my case, the PDF page was technically portrait, but the scanned image inside it was landscape. So the OCR thought, “Everything is upright”, while the text was actually lying on its side.</p><h3>How OCR Engines Detect Rotation</h3><p>From an AI/ML engineer’s perspective, orientation detection is a small computer vision model running before the actual OCR.</p><p>Most modern OCR engines like Tesseract, Google Vision, Azure OCR, PaddleOCR, EasyOCR, and even VLMs internally do these steps:</p><ol><li><strong>Text Line Direction Analysis</strong><br>They detect dominant text lines using Hough Transform or CNNs and check the angle.<br>If most lines are at 90°, 180°, or 270°, they rotate the image.</li><li><strong>Character Shape Distribution</strong><br>Letters like ‘A’, ‘E’, ‘T’ have vertical strokes. Their orientation helps estimate rotation.</li><li><strong>Confidence Scoring After Rotation</strong><br>They try OCR at 0°, 90°, 180°, 270° and choose the angle with maximum language confidence.</li></ol><p>This is called <strong>OSD (Orientation and Script Detection)</strong>.</p><p>In simple words:<br>OCR engines rotate the page in all four directions, read it, and keep the one that “makes most sense as a language”.</p><h3>Why Key-Value Extraction Fails Without Correct Orientation</h3><p>When the page is rotated:</p><ul><li>Bounding boxes become wrong</li><li>Reading order becomes wrong</li><li>“Key : Value” becomes “Value : Key” or completely broken</li><li>Table detection fails</li><li>Layout models like LayoutLM, Donut, or VLMs mis-understand spatial relations</li></ul><p>For example, the model may read:</p><pre>12345<br>Invoice Number</pre><p>instead of</p><pre>Invoice Number : 12345</pre><p>So your downstream NER, regex, or LLM prompt breaks.</p><h3>Special Case: VLMs and Multimodal Models</h3><p>Vision-Language Models do not magically fix rotation. They are still dependent on correct visual orientation.</p><p>If the page is sideways:</p><ul><li>The attention maps focus on wrong regions</li><li>Token-to-pixel alignment breaks</li><li>The model hallucinates structure</li></ul><p>That is why, before sending images to VLMs, rotation normalization is critical.</p><h3>How We Should Handle It in a Production Pipeline</h3><p>As an AI/ML engineer, the correct flow should be:</p><ol><li>Convert PDF page to image</li><li>Run orientation detection</li><li>Rotate to upright (0°)</li><li>Only then run OCR / VLM</li><li>Then perform key-value extraction</li></ol><p>Never trust PDF viewers. Always trust pixel orientation.</p><h3>Possible Issues Even After Rotation</h3><p>Even with auto-rotation, problems can occur:</p><ul><li>Mixed orientation pages in one document</li><li>Stamps or logos confusing orientation models</li><li>Tables printed diagonally</li><li>Mobile-scanned documents with skew + rotation</li><li>Low resolution causing wrong angle detection</li></ul><p>So sometimes we need both:</p><ul><li>Auto rotation</li><li>Manual fallback</li><li>Confidence-based re-OCR</li></ul><h3>Final Learning</h3><p>That one rotated page taught me that document AI is not only about LLMs and deep models. It is also about very basic things like geometry and orientation.</p><p>Before teaching a model to “understand” a document, we must first make sure the document is standing straight.</p><p>In the world of OCR and VLMs,<br><strong>If the page is confused, the AI will be more confused.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0af16ba53d18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Smaller Images Became Bigger Than Bigger Ones]]></title>
            <link>https://medium.com/@bholaynathsingh335619/when-smaller-images-became-bigger-than-bigger-ones-6924c726c4b0?source=rss-347a4af2cb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/6924c726c4b0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Bholay Nath Singh]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 15:41:30 GMT</pubDate>
            <atom:updated>2026-01-11T15:41:30.652Z</atom:updated>
            <content:encoded><![CDATA[<p>While working on a real-time AI project, I came across a problem that looked very small on the surface, but later taught me a deep lesson about how data actually behaves in ML and AI systems.</p><p>The project was not limited to just images. I was dealing with different kinds of documents :Excel files, PDFs, Word documents, and images — all flowing through an AI pipeline. Some of these were used for OCR, some for document understanding, and some directly for computer vision tasks using foundation models via AWS Bedrock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEkOkSAVYt1oizyqHl6Z2Q.png" /></figure><p>Everything was working fine until image encoding entered the picture.</p><p>I had two images.<br> One image was around <strong>3 MB</strong>.<br> The second image was around <strong>3.5 MB</strong>.</p><p>Nothing unusual so far. Anyone would expect the second image to be heavier in every form.</p><p>But the moment I encoded them using <strong>Base64</strong>, the behaviour completely changed.</p><p>The first image suddenly became <strong>more than 5 MB</strong>, while the second image ended up around <strong>4.7 MB</strong>. This immediately caused a serious issue because AWS Bedrock enforces strict payload limits. Depending on the model, the maximum allowed size is around <strong>3.75 MB or 5 MB</strong>. So even though my original images were well within limits, the API started rejecting the requests after encoding.</p><p>This is where confusion starts for many ML engineers — including me at that time.</p><h3>Why Base64 Became a Problem Only in AI Systems</h3><p>Base64 encoding itself is not new. We have been using it for years. But in ML and AI pipelines, especially when working with <strong>vision models and LLMs</strong>, Base64 becomes unavoidable because images are usually sent inside JSON payloads.</p><p>Binary data cannot safely travel through text-based APIs, so Base64 converts raw bytes into plain text. This makes it compatible with REST APIs, logging systems, and cloud services like AWS Bedrock.</p><p>The problem is not Base64.<br> The problem is what Base64 <em>does</em> to size.</p><p>Base64 increases data size by roughly <strong>33 percent</strong>. This is not accidental — it is part of how the encoding works. Every chunk of binary data expands when converted into readable characters. So a 3 MB image easily crosses 4 MB, and anything slightly complex can push it even further.</p><p>In normal systems, this extra size often goes unnoticed. But in AI systems with strict input limits, it becomes a breaking point.</p><h3>The Most Confusing Part: Why the Smaller Image Became Larger</h3><p>The real surprise for me was not that size increased. That part is expected.</p><p>What shocked me was this:<br> <strong>the smaller image ended up larger than the bigger one after Base64 encoding.</strong></p><p>This is where file size intuition completely fails.</p><p>In ML and computer vision, an image’s disk size does not represent how “heavy” it actually is internally. Two images with similar sizes can behave very differently after encoding because what matters is not just size, but <strong>structure</strong>.</p><p>One image may be:</p><ul><li>A PNG with sharp edges, text, and transparency</li><li>Rich in metadata</li><li>Less friendly to compression</li></ul><p>Another image may be:</p><ul><li>A JPEG</li><li>A natural photograph</li><li>Smooth colour gradients</li><li>Already well compressed</li></ul><p>When Base64 encodes these images, it does not care about which one <em>looks</em> bigger. It only sees raw binary complexity. Images that are harder to compress tend to expand more, even if their original size was smaller.</p><p>This is why, in my case, the 3 MB image crossed 5 MB while the 3.5 MB image stayed below it.</p><p>In AI pipelines, this behaviour is very common — but rarely discussed.</p><h3>Why This Became Critical While Using AWS Bedrock</h3><p>AWS Bedrock is designed for scale and safety, so it enforces strict payload limits. This makes sense, especially when models are expected to handle thousands of requests.</p><p>But when you are working on real-world AI use cases like document intelligence or multimodal LLMs, you don’t just send text. You send images, sometimes multiple ones, and almost always encoded.</p><p>So the flow becomes:<br> image → Base64 → JSON → API request</p><p>By the time the request reaches the model, the payload has already grown much larger than expected. A perfectly valid image suddenly becomes invalid — not because of quality, but because of transport size.</p><p>This is one of those issues that only shows up when theory meets production.</p><h3>What I Learned While Handling Multiple Document Types</h3><p>This problem became even clearer when I started processing different formats together. PDFs often contain embedded images, scanned documents are noisy and heavy, mobile photos come in very high resolution, and Word files may contain unnecessary metadata.</p><p>All of these behave differently once encoded and passed to AI models.</p><p>That’s when I realised that in ML systems, <strong>data movement is as important as data modelling</strong>.</p><h3>How This Is Actually Solved in Real AI Systems</h3><p>In production-grade ML and CV systems, engineers rarely rely on raw Base64 images without optimisation.</p><p>Images are resized before encoding because vision models do not need extreme resolution. Formats are converted where possible, metadata is stripped, and payload sizes are validated before inference. In many architectures, images are uploaded to object storage like S3 and only references are sent to the model, avoiding Base64 altogether.</p><p>These are not optimisations — they are necessities.</p><h3>A Data Science Lesson Hidden Inside an Image</h3><p>This experience taught me something important as a data scientist working with AI systems.</p><p>We often focus heavily on:</p><ul><li>Model accuracy</li><li>Architecture</li><li>Prompt engineering</li></ul><p>But real-world AI fails more often because of:</p><ul><li>Data encoding</li><li>Transport limits</li><li>Payload size</li><li>Infrastructure constraints</li></ul><p>A model that never receives the input is as useless as a model that makes wrong predictions.</p><p>That day, when a smaller image became bigger than a larger one, I stopped trusting assumptions and started trusting measurements.</p><h3>Closing Thoughts</h3><p>In ML, AI, and computer vision systems, data does not behave the way we expect it to behave. Base64 is not the enemy ,ignorance is.</p><p>For better understanding look into the practical code for it — “<a href="https://github.com/BholaySingh23/Image-size-difference-logic-check.git">https://github.com/BholaySingh23/Image-size-difference-logic-check.git</a>”</p><p>If you are building AI systems on AWS Bedrock or any multimodal platform, always remember:<br> <strong>image size on disk means nothing once encoding enters the pipeline.</strong></p><p>Sometimes, the smallest image can break the biggest system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6924c726c4b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks Explained in the Easiest Way: How They Actually Work Inside (Especially in Computer…]]></title>
            <link>https://medium.com/@bholaynathsingh335619/neural-networks-explained-in-the-easiest-way-how-they-actually-work-inside-especially-in-computer-dcdcedbf850a?source=rss-347a4af2cb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcdcedbf850a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Bholay Nath Singh]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 08:18:21 GMT</pubDate>
            <atom:updated>2025-11-16T08:18:21.810Z</atom:updated>
            <content:encoded><![CDATA[<h3>Neural Networks Explained in the Easiest Way: How They Actually Work Inside (Especially in Computer Vision)</h3><p><em>My journey from simple ML models to understanding how machines detect traffic lights and number plates</em></p><p>When I first started learning machine learning, I was mostly comfortable with the classic models. Linear Regression, Decision Trees, Random Forests — these models felt very logical and grounded. You could see the formula, see the splits, and understand why a particular result came out. But the moment I stepped into the world of Computer Vision, everything suddenly felt different and honestly, a bit magical. I kept wondering how a machine, which only understands numbers, could look at a picture and tell whether the traffic light is red or green, or even go one step further and read the number plate of a fast-moving vehicle. It sounded almost impossible in the beginning.</p><p>With time, after studying neural networks in detail (including the kind of PPT material we get in BITS), I understood that this magic is actually pure mathematics wrapped in clever engineering. The beauty of neural networks is that even though their internal working looks complicated from the outside, the underlying ideas are extremely simple. And once those simple ideas come together, they form a powerful system that can recognise objects, read text, detect signals, classify images, and do hundreds of other things that we see around us today.</p><p>So in this blog, I will explain how neural networks work internally, why they are so powerful, how they learn from data, and how they are able to perform real-world tasks like <strong>traffic signal detection and number plate recognition (ANPR)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcHW3xscBuoXBeitf5zlFA.png" /></figure><h4>What Exactly Is a Neural Network?</h4><p>A neural network is nothing but a large collection of tiny decision-makers called <strong>neurons</strong>. These neurons are not biological, but mathematical. Each of them takes some numbers as input, multiplies those numbers with weights, adds a small adjustment called bias, and then decides whether to activate or not using something called an activation function. If it activates, it passes a number to the next neuron. If it does not activate, it passes something close to zero.</p><p>This process continues from the first layer of the network to the last layer. And even though each neuron performs a very simple calculation, when thousands or millions of neurons work together in layers, they start learning patterns. These patterns allow the network to identify traffic lights, detect cars, recognise number plates, classify images, and so on. So you can imagine a neural network as a huge team of tiny mathematical “workers,” each doing very small jobs but all contributing to a big intelligent outcome.</p><h4>Layers: The Building Blocks of Neural Networks</h4><p>A neural network has three main types of layers: the input layer, the hidden layers, and the output layer. The input layer receives the raw data, such as pixel values from an image. This data is then passed to the hidden layers, which handle the actual thinking. Every hidden layer transforms the input into more useful information. Finally, the output layer gives the final result such as whether the traffic signal is red or green, whether the object is a car or bike, or what characters are present on a number plate.</p><p>In shallow networks, you have fewer hidden layers, so the network can learn only simple patterns. But in deep neural networks, you stack many layers, and each layer learns more complex patterns than the previous one. This is why deep learning has become extremely popular — more layers mean the network can learn richer features from the data.</p><h4>Why Are Neural Networks So Powerful?</h4><p>The reason neural networks are so powerful is because they are what mathematicians call <strong>Universal Approximators</strong>. This simply means that with enough layers and enough neurons, a neural network can learn almost any pattern in the world — whether it is mathematical, logical, or visual. It can learn curved boundaries, shapes, textures, colours, differences between objects, and even complex logical functions like XOR, which a single perceptron cannot solve.</p><p>This ability to learn <strong>any kind of pattern</strong> is why neural networks are used in almost every advanced AI system today — from self-driving cars to face recognition, from medical imaging to language translation, and from CCTV monitoring to number plate recognition.</p><h4>The Foundation: Perceptron and Why We Need Layers</h4><p>The basic unit of a neural network is the <strong>perceptron</strong>, which takes inputs, multiplies them with weights, adds bias, and then produces an output. A perceptron can act like simple logical gates such as AND, OR, or NOT. However, it cannot handle more complex patterns like XOR, because XOR requires a curved decision boundary. This limitation is exactly why we need multiple layers. Once you add hidden layers, the network becomes capable of drawing curved, folded, and highly complex decision boundaries. Suddenly, even a problem like XOR becomes solvable.</p><p>This is the same idea that applies to images. Images contain extremely complex patterns — edges, corners, curves, textures, combinations of shapes — all arranged in complicated ways. A single layer cannot understand all this. But with many layers stacked on top of each other, the network can gradually build up an understanding from simple edges to complex objects.</p><h4>How Neural Networks “See” an Image</h4><p>When a neural network looks at an image, it does not understand cars, traffic lights, or number plates. It only sees a huge grid of numbers. Every pixel is converted into a numerical value between 0 and 255. A typical image might have lakhs of such pixels. So the input to a neural network is basically a long list like:</p><p>[125, 200, 55, 89, 255, 10, ...]</p><p>Yet, the network eventually learns to recognise objects. How does this happen?</p><p>The process is actually very systematic. The <strong>first layer</strong> of the network learns extremely basic things like edges and colour transitions. These are the simplest patterns in an image. The <strong>middle layers</strong> start detecting small shapes like circles, rectangles, corners, textures, or the outlines of characters. Once you move further into the deeper layers, the network begins to understand more meaningful concepts like wheels, headlights, traffic signals, or the rectangular region of a number plate. Finally, the last layers combine all these features to identify the object or read the number plate.</p><p>This layered understanding is what makes neural networks so good at computer vision.</p><h4>Real-World Example: Traffic Signal and Number Plate Detection</h4><p>One of the best examples that connects theoretical neural network concepts with real-world usage is the system used for <strong>traffic signal detection and automatic number plate recognition (ANPR)</strong>. This system is used in many countries to enforce traffic rules and monitor road safety.</p><p>In traffic signal detection, the first few layers of the neural network learn to identify simple things like circles and colour gradients. The network starts noticing that certain circular patterns appear as red, yellow, or green. As the network goes deeper, it starts understanding the relative brightness of the signal light, its position, and whether the light is on or off. Eventually, the network becomes capable of accurately identifying whether the traffic light is red, yellow, or green, even in low-light conditions or when the image is slightly blurry.</p><p>Once the traffic signal is identified, the system proceeds to detect vehicles using an object detection model like YOLO. These models learn the shapes and features of cars, bikes, trucks, and other vehicles. The deeper layers of these models understand complex patterns such as the shape of a vehicle body, wheel positions, headlights, and overall silhouette.</p><p>After detecting the vehicle, the next task is to locate its number plate. This is done through another neural network that learns to recognise the rectangular boundary of a number plate. It looks for high contrast between characters and background, the thickness of the border, and the general size and placement of plates on vehicles. Once the plate is detected, it is cropped and passed through a character recognition model. This model reads the digits and letters even if the plate is tilted, partially dirty, or affected by lighting.</p><p>By the end of this process, the system can tell you:<br> <strong>“The signal is red, a vehicle crossed the line, and the number plate is MH14BX2458.”</strong></p><p>All of this is done through different neural networks working together, each layer learning a deeper level of pattern than the previous one.</p><h4>What Happens Inside During Training?</h4><p>Inside the neural network, everything is controlled by weights. These weights are initially random, but during training, the model keeps adjusting them. The network makes a prediction, compares it with the actual output, calculates how wrong it is, and then updates the weights to reduce future errors. This process repeats thousands or millions of times until the network becomes extremely accurate.</p><p>The amazing part is that the network discovers features automatically. No one tells it what a “traffic signal” looks like or how a number plate should appear. It learns all of that on its own simply by looking at many examples.</p><h4>Why Deep Networks Are So Good at Vision</h4><p>Deep neural networks work well for computer vision because they learn in stages. The initial layers learn simple visual patterns like edges. The middle layers learn shapes. The deeper layers learn complete objects. This hierarchical learning process is very similar to how our own visual system works. That is why these networks can recognize traffic signals, vehicles, number plates, and even the characters written on those plates with high accuracy.</p><h4>Final Thoughts</h4><p>When I first encountered neural networks, they felt like black boxes doing something mysterious. But with time, I realised that the magic is actually just mathematics working in layers. Each layer adds a new level of understanding, and together they form a very powerful pattern-recognition system. Today, neural networks are everywhere from Google Photos to traffic monitoring systems and understanding them opens up many opportunities.</p><p>I am still on my journey of exploring more advanced topics in CV and neural networks. In future blogs, I plan to build and share more mini-projects around these concepts, breaking them down just like I did here. So stay tuned for that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcdcedbf850a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>