<?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 Pranav Kulkarni on Medium]]></title>
        <description><![CDATA[Stories by Pranav Kulkarni on Medium]]></description>
        <link>https://medium.com/@pranavesque?source=rss-b454dbfc7cb7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*12VekACLf3Z_5Qd8</url>
            <title>Stories by Pranav Kulkarni on Medium</title>
            <link>https://medium.com/@pranavesque?source=rss-b454dbfc7cb7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:47:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pranavesque/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[Google Summer of Code: Enhancing Spanish OCR for historical documents]]></title>
            <link>https://medium.com/@pranavesque/google-summer-of-code-enhancing-spanish-ocr-for-historical-documents-ef7c9f73381d?source=rss-b454dbfc7cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef7c9f73381d</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Pranav Kulkarni]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 13:48:23 GMT</pubDate>
            <atom:updated>2026-08-19T13:48:23.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*CUQn_x77HQkNCUMW.png" /></figure><blockquote>“History, despite its wrenching pain, cannot be unlived, and if faced with courage, need not be lived again.” <br>~ Maya Angelou</blockquote><p>The challenge of the RenAIssance project is to make sure it survives in digital form, accurately and at scale.</p><h3>Abstract</h3><p>Hello! I am Pranav. For the past two summers, I have been working on a deceptively simple problem: how do you get a computer to read a 17th-century Spanish book? The answer, as I learned, is not one model and definitely not one pipeline() call.</p><p>During GSoC 2025, I worked on the core pieces of the RenAIssance OCR pipeline, text-line detection, Spanish OCR, spelling correction, annotation tooling, and synthetic data generation. By the end of that work, the individual components were working, but they still lived mostly as experiments, scripts, and notebooks.</p><p>GSoC 2026 was about turning those pieces into something that could actually be used.</p><p>Over the course of this project, I built and integrated a complete OCR preprocessing and correction application around the existing models. The final system combines image preprocessing, text-line detection, OCR, marginalia handling, spelling correction, and LLM-based post-processing behind a web interface. The application is built with FastAPI and vanilla JavaScript, packaged with Docker, and designed to run locally without requiring users to understand the underlying machine-learning stack.</p><p>This post is a technical walkthrough of how that system came together, including the parts that worked, the parts that didn’t, and the benchmarks that changed design decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHCC2aRGHHpLkCDbp2skgQ.png" /></figure><h3>Introduction</h3><p>This is my end-term report for <strong>Google Summer of Code 2026</strong>, my second year working with <strong>HumanAI</strong> on the <strong>RenAIssance</strong> project.</p><p>The end result of this year’s work is the <strong>OCR Process Studio,</strong> a self-contained web application that takes scanned historical documents and runs them through the RenAIssance OCR pipeline, from image preprocessing all the way to corrected transcription.</p><p>A historian shouldn’t need to know what CUDA version is installed, which Hugging Face model is being loaded, or which Python function starts the OCR pipeline.</p><p>Ideally, they should be able to open the application, upload a document, configure what they need, and get a transcription.</p><p>That was the goal for GSoC 2026.</p><h3>Where We Left Off</h3><p>Before getting into 2026, it’s worth looking at what already existed.</p><p>At the end of my GSoC 2025 work, the project had most of the important research components in place:</p><ul><li>A fine-tuned <a href="https://github.com/matterport/mask_RCNN"><strong>Mask R-CNN</strong></a><strong> (ResNet-101 + FPN)</strong> model for text-line detection on historical Spanish pages.</li><li>A Spanish-optimized <a href="https://huggingface.co/docs/transformers/en/model_doc/trocr"><strong>TrOCR</strong> </a>model for recognizing the detected text lines.</li><li>Several experiments around spelling correction, including Hunspell, fastText, Gemma, and <a href="https://github.com/google-research/text-to-text-transfer-transformer">T5 </a>with LoRA.</li><li>An annotation tool for correcting and creating training data.</li><li>A synthetic noise generation pipeline for producing spelling-error data.</li></ul><p>None of it was usable as an app yet. Most of the pipeline existed as Python scripts, notebooks, experiments, and model checkpoints. Running it meant setting up the right environment, installing the dependencies, loading the models, passing the correct arguments, and knowing which script to run next. That’s fine for research, but not for someone who just wants to study the manuscript.</p><h3>What Changed in 2026</h3><p>The focus of GSoC 2026 therefore shifted from building individual components to packaging the entire pipeline.</p><p>The progression looks roughly like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*dt1FcoovlfUGEvX-TshAJQ.png" /></figure><p>The final application isn’t a completely new OCR system built from scratch this year. It is the result of taking the research work from the previous cycle, improving the weak points, and then building the layer necessary to make all of it work together.</p><h3>What the Final System Actually Does</h3><p>A user starts with a scanned PDF. The Studio loads the pages, lets the user inspect and adjust the preprocessing, detects text lines, runs OCR, and then presents the transcription in a separate viewer where individual results can be reviewed and corrected.</p><p>In the code, the application is split into a lightweight browser frontend and a Python backend. The frontend is vanilla JavaScript rather than a large framework, while <a href="https://github.com/fastapi/fastapi">FastAPI </a>handles the API layer. The heavier OpenCV and PyTorch operations are pushed into a ThreadPoolExecutor, so the asyncio event loop can continue handling HTTP requests instead of getting stuck while an image is being processed.</p><p>The backend ties the existing models together and exposes them through the application:</p><p><strong>PDF → preprocessing → text-line detection → line crops → TrOCR → OCR results → optional LLM/manual correction → export</strong></p><h3>1. PDF Loading and Preprocessing</h3><p>Historical scans are rarely clean inputs for an OCR model. Pages can be slightly rotated, have uneven lighting from the scanner, contain paper texture and noise, and have ink that is faint in some places and very dark in others. Feeding the raw scan directly into OCR usually leaves a lot of unnecessary work for the recognition model. So preprocessing ended up being one of the biggest parts of the project.</p><p>The Studio first rasterizes the uploaded PDF at 300 DPI using <a href="https://github.com/pymupdf/pymupdf">PyMuPDF</a>. I chose this instead of relying on Poppler, which keeps the application self-contained and avoids another system dependency. The rasterized pages are then kept in the current session so that every time the user changes a preprocessing setting, the server does not have to go back to the PDF and rasterize the page again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFluLB4sfLta_wh564-OSg.png" /></figure><h3>The Five Preprocessing Stages</h3><p>The actual preprocessing pipeline has five main stages:</p><ol><li><strong>Deskewing</strong></li><li><strong>Background illumination normalization</strong></li><li><strong>Denoising</strong></li><li><strong>Sauvola binarization</strong></li><li><strong>Morphological cleanup</strong></li></ol><p>Deskewing finds the text angle using Canny edges and a Hough transform. I used the median angle instead of the mean, since page borders and diagonal marks can skew a mean badly. The original preprocessing took about <strong>23.8 seconds per 300 DPI page</strong> on the Guardiola manuscript used for development. Background normalization alone took 8.2 seconds, Non-Local Means denoising took 12.4 seconds, and Sauvola binarization took another 2.1 seconds. At that rate, preprocessing a 100-page document would take roughly 40 minutes.</p><p>That was too slow for a live preview.</p><h4>Background Normalization</h4><p>The original implementation performed a large Gaussian blur on the full-resolution image. The idea was correct but doing the blur at full resolution was unnecessarily expensive. So I shrank the image first, blurred that, then scaled it back up.</p><p>The assumption is that illumination changes across a scanned page are low-frequency. The text strokes and scanner noise are high-frequency details that we don’t need in the background estimate anyway.</p><p>This brought background normalization from around <strong>8.2 seconds to 0.13 seconds</strong> on the benchmark image set.</p><h4>Denoising</h4><p>The original pipeline used Non-Local Means denoising. It worked, but it was far too expensive for something that had to run over every page.</p><p>At the point where denoising happens, color is no longer particularly useful because the next stage is converting the page to a binary representation. So the optimized version first converts the image to grayscale and then uses bilateral filtering, which smooths relatively flat regions while retaining strong edges around the characters.</p><p>That reduced denoising from roughly <strong>12 seconds to 0.15 seconds</strong> in the benchmark.</p><h4>Sauvola Binarization</h4><p>The same philosophy was applied to Sauvola thresholding.</p><p>The original implementation effectively evaluates a local window around each pixel. The optimized version uses OpenCV’s boxFilter to compute local means and squared means efficiently, turning what would otherwise be an expensive sliding-window operation into an integral-image based calculation.</p><p>The result was about <strong>2.1 seconds → 0.06 seconds</strong> for binarization.</p><p>The final benchmark looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*1qyQhP-bHhFCEQT1H0qC7g.png" /></figure><p>None of this needed a better GPU. Most of the improvement came from changing the algorithms and the way they were implemented.</p><blockquote>NOTE: To make the preview responsive, large pages are temporarily downscaled to a maximum dimension and the pixel-based parameters are scaled along with them. Otherwise a Sauvola window or morphological kernel that is meaningful at 3000 × 4200 pixels would mean something completely different on a 1200-pixel preview.</blockquote><h3>2. Text-Line Detection</h3><p>I covered this in an earlier blog as well. The project already had a fine-tuned <a href="https://github.com/facebookresearch/detectron2"><strong>Detectron2 </strong></a><strong>Mask R-CNN with a ResNet-101 + FPN backbone</strong>, trained on historical Spanish pages. That model became the text-line detection stage of the final application.</p><p>The process is roughly:</p><blockquote>Processed page → Mask R-CNN → Filter small/noisy detections → Sort detected lines → Calculate padding → Crop individual lines → Batch the crops → OCR</blockquote><p>Detectron2 gives us tight bounding boxes around the detected text. That is useful for detection, but not necessarily ideal for recognition. TrOCR works better when the line has a little surrounding context.</p><p>More importantly, historical lettering has descenders. Characters such as g, p, q, and y can extend noticeably below the baseline. A crop that cuts those parts off can turn an otherwise correct OCR result into something wrong. So padding isn’t fixed and it’s calculated from the gap between neighboring lines. The bottom padding is deliberately a little larger to account for descenders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*gjpHoRoYq3agfrQ2.png" /><figcaption>The results of finetuned model to textline detection (The left side shows results without any padding added and the right side shows results after padding is added)</figcaption></figure><h3>3. Running TrOCR</h3><p>After detection, the line crops are passed to the TrOCR model. The obvious implementation would be to run the model once for every crop. That works, but it also wastes GPU capacity.</p><p>Instead, the Studio collects the valid line crops from a page and runs them in batches. A batch size of 8 gave good utilization on the T4 used during development without running into memory issues. The processor handles padding the line crops to a common size before they are passed into the model.</p><p>On CUDA, the model uses <strong>FP16</strong> instead of FP32. The attention implementation uses <strong>SDPA</strong>, and decoding uses the <strong>KV cache</strong> so the decoder doesn’t repeatedly recompute attention information for tokens it has already generated.</p><p>The KV-cache change is especially useful because TrOCR generates text autoregressively. Without caching, previous key/value projections are recalculated at every decoding step. With caching, they are stored and reused.</p><p>Taken together, batching, FP16, SDPA, and KV caching brought GPU TrOCR inference from roughly <strong>4 seconds per page to under one second per page</strong> on the development setup, around a <strong>4× speedup</strong>. We also <strong>fine-tuned the model on the private datasets available to us</strong>, giving it some additional exposure to the specific material the Studio is meant to handle.</p><p>The overall line-level pipeline now looks like:</p><blockquote>Page → Detect text lines → Filter + sort detections → Dynamic padding → Crop lines → Batch crops → TrOCR → Join recognized lines → Full-page transcriptions</blockquote><h3>4. Manual Regions and the ROI Selector</h3><p>Automatic detection is useful, but historical pages are messy enough that I didn’t want the application to assume that the model would always get everything right. The Studio therefore also has a <strong>manual ROI selector</strong>. A user can draw a rectangular region on the page and tell the pipeline, essentially, “process this part.” Regions are kept separate from whole-page OCR results in the results viewer, so a manually selected area is clearly identified as a region rather than looking like another page transcription.</p><p>This turned out to be particularly important because I had also investigated automatic marginalia detection (next section) during the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*ik5yCxWfKgSbuBz_.png" /></figure><h3>5. Automatic marginalia detection</h3><p>Marginalia are handwritten notes, annotations, drawings, and other additions in the margins of historical documents.</p><p>I benchmarked ten different detection models to see whether we could automatically identify them and remove them from the OCR input. The best result came from <a href="https://docs.ultralytics.com/models/yolo11">YOLO11m </a>at around <strong>0.86 mAP@0.5</strong>. For this particular application, that failure is worse than leaving some marginalia in the OCR input.</p><p>So the final Studio keeps manual region selection as the safer mechanism. The best benchmark score wasn’t the right choice for the app, so I didn’t use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*LUb7mOX_tCEoYAm4.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/0*PXN-8-q2YkBKG7La.png" /></figure><h3>6. OCR Results and Progressive Processing</h3><p>The OCR output is displayed in a separate results viewer, with results organized by page and region. This makes it easier to identify the source of each result and review individual OCR outputs. If a line is detected incorrectly, users can recrop the region and run OCR again without reprocessing the entire document.</p><p>The application also supports progressive result updates. Each page’s OCR result is stored as soon as processing for that page is completed. The frontend polls the backend every two seconds and updates the viewer when new results are available. This allows users to start reviewing earlier pages while the remaining pages are still being processed.</p><p>The current implementation uses polling to keep the system simple. A WebSocket-based approach could provide more immediate updates, but was not included in the final implementation.</p><h3>7. LLM-Based Correction</h3><p>OCR gets us much closer to the text, but historical Spanish introduces another problem: the text itself can be difficult to normalize and interpret. So the final pipeline includes an optional LLM correction layer.</p><p>The correction layer isn’t tied to one API; it supports multiple providers:</p><ul><li>Gemini</li><li>OpenAI</li><li>Hugging Face inference</li><li>A local <a href="https://huggingface.co/collections/Qwen/qwen25">Qwen2.5–7B model</a></li></ul><p>This also keeps the correction layer flexible: a user can choose a cloud provider, use Hugging Face, or run the correction fully locally with the bundled quantized model.</p><p>Historical Spanish can contain spellings that look incorrect by modern standards but are perfectly valid for the source being transcribed. The correction prompt therefore explicitly tells the model not to modernize the language. A low temperature of 0.2 is also used to keep the output conservative rather than encouraging the model to rewrite the text more freely.</p><blockquote>The goal isn’t to fix the Spanish. It’s to fix OCR mistakes without changing what the document actually says.</blockquote><p>There is also a fully offline path using a local Qwen2.5–7B GGUF model through <a href="https://github.com/ggml-org/llama.cpp">llama.cpp</a>, which means the correction stage does not inherently require an external API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*hjYTC4_w88OO94zdEu91aA.png" /><figcaption>LLM instructions in the final studio app</figcaption></figure><h3>8. Docker Deployment</h3><p>The application was packaged using <a href="https://docs.docker.com/">Docker </a>to make it easier to run across different environments. Separate configurations were prepared for <strong>NVIDIA GPU</strong> and <strong>CPU-based environments</strong>, including Macs where NVIDIA GPUs are not available. The CPU setup allows the application to run without requiring CUDA or an NVIDIA GPU, although TrOCR inference is slower on CPU.</p><p>The Docker Compose setup also uses a persistent Hugging Face cache volume so that the TrOCR and Detectron2 models do not need to be downloaded again after every container rebuild or restart. Output files are mounted back to the host system so that they remain accessible outside the container.</p><p>So, the final pipeline looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcvsfxh9OJccTCHFl8uyOQ.png" /><figcaption>Credits: ChatGPT</figcaption></figure><h3>What Didn’t Make It</h3><p>There are still some things I would like to improve.</p><p>The application currently uses polling rather than WebSockets for live OCR updates. A proper push-based implementation would reduce the latency and simplify some of the result synchronization logic.</p><p>LLM correction is also currently page-based. A better future implementation would allow context to flow between pages, which would help with words split across page breaks, recurring names, abbreviations, and other document-level patterns.</p><p>And the manual ROI path currently treats a selected region as a whole-image OCR crop rather than running full line detection inside that region. That’s useful already, but there is room to make it more precise.</p><p>And there are definitely still bugs we haven’t found yet.</p><h3>Conclusion</h3><p>Over the past two summers, RenAIssance developed from a research project into a complete OCR application. The first stage focused on building the individual components: text-line detection, TrOCR recognition, spelling correction, annotation tools, and training data. This year, the focus was on integrating these components into a usable system.</p><p>One of the main lessons from this work was that building an OCR model is only one part of building an OCR application. The surrounding system also requires careful implementation. This includes preprocessing, text-line detection and cropping, application state, progressive result handling, containerization, and post-processing. Each of these components affects how reliably the overall system works.</p><p>The final RenAIssance OCR Studio is not intended to be a perfect OCR system. It is a practical application that brings together the work developed over the past two summers and provides a way for users to run OCR, review the results, correct individual lines, and export the output.</p><p>This was the main goal of GSoC 2026, and I am satisfied with where the project has reached.</p><p>I would like to thank my mentors for their guidance, reviews and support, I look forward to mentor next batch of contributors as my tenure ends!</p><p><em>This work is part of Google Summer of Code 2026 with HumanAI, contributing to the RenAIssance Project for historical document digitization.</em></p><p><em>LinkedIn: </em><a href="https://www.linkedin.com/in/pranav-kulkarni-2b6b6a262/"><em>https://www.linkedin.com/in/pranav-kulkarni-2b6b6a262/</em></a><em><br>GitHub: </em><a href="https://github.com/KalkulatorHere"><em>https://github.com/KalkulatorHere</em></a><em><br>RenAIssance: </em><a href="https://github.com/humanai-foundation/RenAIssance"><em>https://github.com/humanai-foundation/RenAIssance</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef7c9f73381d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Summer of Code 2026: Enhancing Spanish OCR for historical documents]]></title>
            <link>https://medium.com/@pranavesque/google-summer-of-code-2026-enhancing-spanish-ocr-for-historical-documents-b83d569bca4c?source=rss-b454dbfc7cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b83d569bca4c</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[google-summer-of-code]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Pranav Kulkarni]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 07:30:27 GMT</pubDate>
            <atom:updated>2026-07-09T07:30:27.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*RYAXsUlZFxkYXfBk.png" /></figure><p>Hello everyone!</p><p>I’m Pranav Kulkarni, and I’m excited to continue my journey with HumanAI as part of Google Summer of Code 2026. Last year, during <a href="https://medium.com/@pranavesque/google-summer-of-code-enhancing-spanish-ocr-for-historical-documents-4cb408920d12">GSoC 2025</a>, I worked on building the foundation of the RenAIssance OCR pipeline which is a deep-learning based system designed for recognizing and preserving 17th-century Spanish historical documents.</p><p>The initial goal was to move beyond traditional OCR approaches and create a complete workflow capable of handling the challenges of historical texts. During GSoC 2025, I developed an end-to-end pipeline combining text-line detection using <a href="https://github.com/matterport/Mask_RCNN">Mask R-CNN</a>, <a href="https://github.com/microsoft/unilm/tree/master/trocr">TrOCR</a>-based recognition, OCR correction experiments with <a href="https://github.com/hunspell/hunspell">Hunspell</a>, <a href="https://github.com/google-research/text-to-text-transfer-transformer">T5</a>, and LLMs, along with a human-in-the-loop annotation platform for expert correction and dataset improvement.</p><p>The pipeline followed the structure:</p><p><em>Scanned Document → Text Line Detection → OCR Recognition → Correction → Human Review → Final Transcription</em></p><p>This work resulted in a functional prototype that demonstrated how modern transformer-based models could be adapted for historical document digitization. However, while the system performed well, several real-world challenges remained: noisy scans, marginalia interference, unnecessary computational overhead, deployment limitations, and the need for a more optimized user-facing workflow.</p><h3>Moving Forward: GSoC 2026 Goals</h3><p>For GSoC 2026, the focus shifts from building the OCR pipeline to making it efficient and deployment-ready.</p><p>The objective is to transform the existing prototype into a complete optimized system by improving every stage of the pipeline. The major goals include:</p><ul><li>Developing a stronger <strong>preprocessing pipeline</strong> for degraded historical scans</li><li>Adding<strong> layout-aware filtering</strong> and <strong>marginalia removal</strong></li><li>Optimizing the existing TrOCR model for <strong>lower inference time </strong>and <strong>memory usage</strong></li><li>Delivering a complete application where researchers can process documents through a clean interface</li></ul><p>The final system aims to operate as:</p><blockquote><em>Preprocessing → Layout Filtering (Marginalia Removal) → Text Line Extraction → OCR → Correction → User Application</em></blockquote><p>Rather than simply improving recognition accuracy, the goal is to make the entire pipeline practical for historians, researchers, and digital archive projects.</p><h3>Executive Summary: Midterm Progress</h3><p>By the GSoC 2026 midterm milestone, the focus has been on evolving last year’s OCR prototype into a faster, cleaner, and more scalable end-to-end system.</p><p>The pipeline has been redesigned around structured document processing:</p><blockquote>Raw Historical Page<br>→ Preprocessing<br>→ Marginalia Detection &amp; Removal<br>→ Clean Text Region Extraction<br>→ Text Line Detection<br>→ TrOCR Recognition</blockquote><p>Major progress includes building a robust preprocessing workflow, introducing layout-aware marginalia filtering, and optimizing the existing TrOCR model for improved inference speed and memory efficiency while preserving accuracy.</p><p>These improvements establish a stronger foundation for the second half of GSoC 2026, focused on correction systems, application integration, benchmarking, and delivering a complete deployable OCR platform for historical document transcription.</p><h3>Marginalia Detection: Separating Notes from Main Text</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BGCJi9_PRyu9Nkc-z7paig.png" /></figure><p>One of the major limitations observed in last year’s OCR pipeline was handling marginalia handwritten notes and annotations appearing around the main printed content. These regions can be important, but when processed together with the main text, they can disrupt text-line extraction, reading order reconstruction, and OCR quality.</p><p>To explore an automated solution, I framed marginalia detection as a single-class object detection problem. The models were trained using the <a href="https://www.kaggle.com/datasets/chantalb/marginalia-training-data/data"><strong>Marginalia Training Data dataset</strong></a><strong>,</strong> containing annotated early modern book pages from sources including the Archaeology of Reading (AoR), UCLA Clark Library, and National Library of Scotland collections.</p><p>Our aim here is detect handwritten marginal notes and generate bounding boxes around them before OCR processing.</p><blockquote>Pipeline tested:</blockquote><blockquote>Raw Page<br>→ Image Preprocessing<br>→ Marginalia Detection Model<br>→ Bounding Box Filtering<br>→ Clean Text Region Extraction</blockquote><p>I benchmarked 10 different models across two approaches:</p><ul><li><a href="https://docs.ultralytics.com/"><strong>YOLO (Ultralytics)</strong>:</a> single-stage detectors optimized for fast inference</li><li><a href="https://layout-parser.github.io/"><strong>LayoutParser / Detectron2</strong></a>: two-stage Faster R-CNN and Mask R-CNN models optimized for document layout understanding</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*7Bq3tyvj0uhn3AmHENbOmA.png" /></figure><p>Observations: YOLOv8m achieved the best overall balance between accuracy and efficiency, while YOLO11m provided the fastest inference with the highest mAP@50. LayoutParser-based models, especially FasterRCNN-R101, produced more precise bounding boxes due to their region proposal architecture, which is useful when exact document boundaries matter.</p><p>I also experimented with post-processing strategies such as <a href="https://medium.com/@juneta.tao/nms-vs-soft-nms-vs-weighted-box-fusion-for-object-detection-28d46828ac79">Soft-NMS</a> to reduce duplicate overlapping detections, improving precision when marginal notes appeared close together.</p><p><em>While these results were promising, fully automated marginalia removal was still not reliable enough for integration into the final OCR pipeline. Historical documents vary heavily annotations differ in handwriting style, ink quality, placement, and density. In archival workflows, a false removal is worse than extra noise because it risks losing original historical information.</em></p><p>Therefore, instead of forcing an uncertain detection model into production, I moved toward a different approach: adding a <strong>manual main-text definition feature</strong> directly inside the preprocessing pipeline. This allows to select the primary text region when needed while maintaining predictable OCR behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*LCdykIr2HRWwqr5tQGwARg.png" /></figure><p>The complete preprocessing workflow and this user-guided filtering approach are discussed in the next section.</p><h3>Building a Preprocessing Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AD6VQ2C1iS4MIgWIR7JrDw.png" /></figure><p>After experimenting with automated marginalia detection, the next focus was improving the input stage of the OCR pipeline itself. Historical documents are rarely clean and pages often contain uneven illumination, faded ink, scanning noise, page curvature, and alignment issues.</p><p>Instead of sending raw scanned pages directly into text-line detection and OCR, I built a dedicated preprocessing pipeline to generate cleaner and more consistent inputs.</p><p>The final preprocessing workflow:</p><blockquote>Raw Scan<br>→ Skew Correction<br>→ Background Normalization<br>→ Denoising<br>→ Adaptive Binarization<br>→ Morphological Cleanup<br>→ OCR-ready Document</blockquote><h3>Core Preprocessing Steps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*iOm_yY2AN-esFOTx0baH1w.png" /><figcaption>Main stages of the OCR preprocessing workflow.</figcaption></figure><p>Along with improving image quality, a major challenge was making preprocessing fast enough for an interactive application. The initial implementation produced good outputs but was computationally expensive, taking around <strong>14.2 seconds per page</strong>, mainly due to full-resolution denoising and background normalization.</p><p>To solve this, I optimized multiple components of the pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*hud67HlpNg9Y0Al5vi44Fg.png" /><figcaption>Major algorithmic improvements reducing preprocessing latency</figcaption></figure><p>These changes reduced preprocessing latency significantly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*a2qQp1WVvNfDroSADBJX_w.png" /><figcaption>End-to-end preprocessing performance after optimization</figcaption></figure><p>The optimized system can now preprocess a high-resolution 300 DPI document scan in under a second, making real-time interaction practical.</p><h3>Manual Main Text Region Selection</h3><p>The preprocessing pipeline also introduced an important feature motivated by the marginalia detection experiments: manual region selection.</p><p>Although object detection models achieved strong benchmark results, fully automated marginalia removal was not reliable enough for archival workflows. Removing the wrong region could permanently discard historically important content.</p><p>To solve this, I added an interactive <strong>Region of Interest (ROI) selector.</strong></p><p>Users can:</p><ul><li>manually draw the main text regions</li><li>define reading order through numbered selections</li><li>apply the same layout template across multiple pages</li><li>process only the selected regions through OCR</li></ul><p>With these improvements, we can minimize the OCR workflow errors.</p><h3>Optimizing TrOCR: Faster Inference Without Sacrificing Accuracy</h3><p>The OCR backbone continues to use <strong>qantev/trocr-large-spanish</strong>, the transformer-based recognition model adapted for historical Spanish documents.</p><p>During GSoC 2025, the focus was maximizing OCR accuracy. However, for real-world deployment, processing speed and GPU efficiency became equally important. Instead of replacing the model with a smaller alternative and losing accuracy, I focused on optimizing the inference pipeline around the existing TrOCR-Large model.</p><p>The optimization process targeted multiple bottlenecks:</p><ul><li><strong>Batched Inference:</strong> Processes multiple text-line crops together to improve GPU utilization.</li><li><strong>FP16 Mixed Precision:</strong> Reduces computation and memory requirements using half-precision operations.</li><li><strong>KV-Cache Decoding:</strong> Stores previous attention states during autoregressive decoding to avoid repeated computation.</li><li><strong>SDPA Attention Backend:</strong> Uses PyTorch’s optimized scaled dot-product attention kernels for faster transformer execution.</li><li><strong>FP8 Simulation Experiments:</strong> Evaluates lower precision execution strategies for future hardware acceleration.</li></ul><p>Benchmarking was performed using <strong>qantev/trocr-large-spanish</strong> on historical Spanish text-line crops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*mbRzXSxKbwWG8buUai21cQ.png" /><figcaption>Incremental inference optimizations on qantev/trocr-large-spanish (T4<br>GPU, 4 pages, 92 text-line crops)</figcaption></figure><p>Through these optimizations, the same TrOCR-Large model achieved around a <strong>4× inference speedup</strong> with significantly lower memory usage while preserving transcription accuracy.</p><p>This allowed the OCR engine to move closer toward a feasible system capable of processing efficiently.</p><h3>Integrating the Pipeline: Connecting Preprocessing with OCR</h3><p>After optimizing the individual components, the next step was combining this year’s preprocessing improvements with the OCR system developed during GSoC 2025.</p><p>The previous pipeline already contained the core recognition workflow:</p><blockquote>Text Line Detection<br>→ TrOCR Recognition<br>→ Correction Pipeline<br>→ Final Output</blockquote><p>However, raw scanned pages were directly passed into the system, which made OCR performance highly dependent on input quality. In GSoC 2026, the pipeline was redesigned so that every document first passes through the preprocessing and layout filtering stages before recognition.</p><p>The updated workflow:</p><blockquote>Raw Historical Document<br>→ Preprocessing Pipeline<br>→ Manual Region Selection / Text Line Detection<br>→ Optimized TrOCR Inference<br>→ OCR Output</blockquote><p>The existing components were also modularized during integration. The TrOCR engine was separated into its own inference module with batching, FP16, KV-cache, and attention optimizations. The Detectron2-based text-line detector from last year was preserved and connected directly with the new preprocessing outputs.</p><p>The manual region selector was also integrated into this flow — user-defined regions are cropped from the cleaned document, processed in reading order, and passed through batched TrOCR inference automatically.</p><h3>Conclusion</h3><p>At the GSoC 2026 midterm stage, the RenAIssance OCR pipeline has progressed from last year’s working prototype into a more optimized and scalable document processing system.</p><p>The focus so far has been on building a faster preprocessing workflow, exploring layout-aware marginalia handling, optimizing TrOCR inference, and integrating these improvements with the existing OCR pipeline developed during GSoC 2025.</p><p><strong>The current system now follows a complete flow.</strong></p><p>With the core pipeline now in place, the second half of GSoC 2026 will focus on turning this system into a complete user-facing application. Upcoming work includes improving the interface, adding advanced correction layers, benchmarking the full pipeline, and preparing a deployable tool that researchers can use for historical document transcription.</p><p>For those interested in the code can visit my GitHub. Thanks to HumanAI and my mentors for their support!</p><p><em>This work is part of Google Summer of Code 2026 with HumanAI, contributing to the RenAIssance Project for historical document digitization.</em></p><p><em>LinkedIn: </em><a href="https://www.linkedin.com/in/pranav-kulkarni-2b6b6a262/"><em>https://www.linkedin.com/in/pranav-kulkarni-2b6b6a262/</em></a><em><br>GitHub: </em><a href="https://github.com/KalkulatorHere"><em>https://github.com/KalkulatorHere</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b83d569bca4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Summer of Code: Enhancing Spanish OCR for historical documents]]></title>
            <link>https://medium.com/@pranavesque/google-summer-of-code-enhancing-spanish-ocr-for-historical-documents-4cb408920d12?source=rss-b454dbfc7cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cb408920d12</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[google-summer-of-code]]></category>
            <dc:creator><![CDATA[Pranav Kulkarni]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 06:49:48 GMT</pubDate>
            <atom:updated>2025-10-02T13:44:27.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*jf1pVamsAR3Oq94v.png" /></figure><p>Hello, everyone!</p><p>I’m Pranav Kulkarni, and over the past few months I’ve been working with <strong>HumanAI</strong> as part of <strong>Google Summer of Code 2025</strong>. My project has focused on improving <strong>Spanish OCR for historical documents</strong> through deep learning approaches. With the program now moving into its final phase, I’d like to share an overview of the work completed, the challenges tackled, and the outcomes achieved during this journey.</p><h4>My Project</h4><p>I’m building a robust OCR pipeline for 17th-century Spanish texts under the RenAIssance Project. The workflow combines <a href="https://github.com/matterport/Mask_RCNN">Mask R-CNN</a> for precise line segmentation, a fine-tuned <a href="https://github.com/microsoft/unilm/tree/master/trocr">TrOCR</a> model for recognition, and a <a href="https://github.com/google-research/text-to-text-transfer-transformer">T5-based correction</a> stage later enhanced with LLMs to preserve historical accuracy. An annotation tool also supports expert feedback and iterative dataset growth.</p><blockquote>The proposed pipeline: <br>Scanned PDF → Bounding box generation + OCR → T5 correction → LLM correction → Final output</blockquote><h4>Executive summary</h4><p>Delivered a production-ready MVP OCR pipeline for 17th-century Spanish documents that combines high-precision line segmentation (Mask R-CNN), a fine-tuned TrOCR recognizer, and a correction stage augmented by LLM fallbacks — all supported by a lightweight annotation tool and a bonus synthetic-noise data generator. Outcome: a reproducible, low-resource workflow that improves transcription accuracy, enables secure local deployment to protect archives, and produces training data for continuous improvement. Key deliverables shipped: segmentation model, OCR finetune, correction pipeline scaffold (Hunspell baseline → T5/LoRA), annotation UI with Human In the Loop workflow, and a Kaggle-accessible error corpus.</p><h4>Pre-Coding Phase Period</h4><p>Before the proposals were accepted, we were given a <a href="https://humanai.foundation/gsoc/2025/proposal_OCR2.html">preliminary task</a> — a hands-on challenge that allowed us to explore the problem space and experiment with potential solutions even before the official GSoC timeline began. This early exposure helped me and my teammates brainstorm ideas and lay the groundwork for our contributions well in advance.</p><p>My journey with HumanAI officially began during the community bonding period of Google Summer of Code. This phase was instrumental in building a strong rapport with mentors, understanding the project’s goals, and aligning expectations for the coding phase.</p><p>During this time, I also gained access to the full dataset comprising both printed and handwritten early modern Spanish texts along with their ground truth annotations. The dataset spans a wide range of fonts, page qualities, and stylistic variations, offering both a challenge and a rich ground for training robust OCR models.</p><h4>Fine-tuned Text-Line Detection &amp; TrOCR Extraction</h4><p>I fine-tuned a Mask R-CNN (<a href="https://www.kaggle.com/code/alimustoofaa/mask-rcnn-detectron-2">ResNet-101 FPN</a>) on PAGE-XML→COCO annotations of historical Spanish pages to get high-precision text-line boxes. Once the <a href="https://github.com/facebookresearch/detectron2">Detectron2</a> predictor outputs [x1,y1,x2,y2] boxes, I apply dynamic padding (based on median vertical/horizontal gaps) and margin-area filtering to crop each line cleanly. Those crops are then passed, in sorted reading order, into a <a href="https://huggingface.co/qantev/trocr-large-spanish">qantev/trocr-large-spanish VisionEncoderDecoderModel </a>— yielding line-level OCR text that’s robust to 17th-century fonts and degradations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GopgBh-yziFvjBhQqKUHog.png" /><figcaption>The results of finetuned model to textline detection (The left side shows results without any padding added and the right side shows results after padding is added)</figcaption></figure><h4>Clustering for Reading Sequence</h4><p>Because pages can have multiple columns or irregular spacing, I built a small clustering module that takes the raw text-line boxes, computes a custom distance (vertical gap + α × horizontal penalty), then groups them into blocks via <a href="https://www.geeksforgeeks.org/machine-learning/dbscan-clustering-in-ml-density-based-clustering/">DBSCAN</a>. Within each block, lines are sorted by their y-coordinate to reconstruct the intended reading sequence — even on two-column layouts. This post-processing step fixes the out-of-order lines that confused TrOCR and now delivers perfect single-block and two-block results alike.</p><pre>#pseudo code<br>boxes = load_json(&quot;textlines.json&quot;)         # [[x1,y1,x2,y2],…]<br>lines = [centroid_and_size(b) for b in boxes]<br>D = pairwise_distance(lines, custom_metric) # vertical_gap + α*horizontal_penalty<br>clusters = DBSCAN(eps, min_samples, metric=&quot;precomputed&quot;).fit(D)<br>if too_many_singletons(clusters):<br>    clusters = hierarchical_clustering(D, threshold)<br>reading_sequence = []<br>for block in unique(clusters.labels_):<br>    block_lines = select(lines, clusters.labels_==block)<br>    ordered = sort(block_lines, key=lambda L: L.y_center)<br>    reading_sequence.extend(ordered)<br>save_sequence(&quot;reading_order.txt&quot;, reading_sequence)</pre><p><em>Although the clustering algorithm produced strong results for a fully automated pipeline, I chose not to include it. The issue was that it sometimes misclassified marginalia as part of the main OCR blocks, which led to poor outputs and, in turn, unreliable LLM corrections.</em></p><p><em>Instead, I added a toggle option within the annotation tool that allows users to manually split text into two blocks. This approach provides users with greater control over data processing and ensures more reliable results.</em></p><h4>Finetuning TrOCR on Rodrigo Dataset</h4><p>The code performs finetuning of the model on the <a href="https://www.kaggle.com/datasets/kalkulatork/rodrigo-dataset-spanish">Rodrigo dataset</a>, which consists of handwritten Spanish text line images paired with ground truth transcriptions. The dataset was parsed, cleaned, and split into training, validation, and test sets, with subsampling applied for efficient training under memory constraints. A streamlined pipeline was set up using Hugging Face’s Seq2SeqTrainer, where multiple experiments were run — ranging from basic setups to optimized runs with augmentations and evaluation metrics like CER and WER. The trained model was saved and later evaluated on unseen test samples, verifying its performance visually. Overall, this code establishes a complete, low-resource-friendly finetuning framework for historical OCR adaptation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sg4X0mv3NwwpnIDp" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vrn99Xtyg-iQbLxh" /><figcaption>Sample results for handwritten text</figcaption></figure><p>Using the segementation pipeline developed, we were able to finetune this model on the historical spanish handwritten data that was provided to us. Dividing the the handwritten pages into the textlines necessary for OCR by our model.</p><h4>Experiments in Spanish Spell Correction: From Hunspell to T5 + LoRA</h4><p><em>Various experiments with T5 and other spelling correction models were performed to get results</em></p><h4>1. Hunspell Dictionary Baseline</h4><p>The first stop was the classic: <strong>Hunspell</strong>.</p><ul><li>I integrated the Spanish .dic and .aff files from<a href="https://github.com/wooorm/dictionaries"> wooorm/dictionaries</a>.</li><li>For each token, Hunspell either verified the spelling or provided suggestions, from which I picked the top candidate.</li><li>I wrote a wrapper to preserve punctuation and compute metrics like word-, character-, and exact-match accuracy.</li></ul><p>On a <strong>10,000-sample dataset</strong>, Hunspell performed surprisingly well:</p><ul><li><strong>Exact match accuracy:</strong> 72.6%</li><li><strong>Character-level accuracy:</strong> 85.9%</li><li>Perfect corrections: 7,260 / 10,000</li></ul><p>The takeaway? Hunspell’s dictionary coverage is excellent, but performance depends heavily on suggestion ranking.</p><h4>2. fastText Embeddings + Edit Distance Hybrid</h4><p>Next, I tried a more learned approach by combining <strong>fastText embeddings</strong> with <strong>edit distance</strong>.</p><p>The pipeline looked like this:</p><ul><li>Generate candidates via edits (distance 1–2) and approximate matches.</li><li>Filter them using a Spanish vocabulary.</li><li>Score candidates with a weighted combination of:</li><li>Embedding similarity (fastText vectors)</li><li>Word frequency priors</li><li>Edit distance penalties</li></ul><p>With a small test set (n=1,000), results lagged behind Hunspell:</p><ul><li><strong>Overall accuracy:</strong> 31.9%</li><li>Stronger performance in higher-frequency buckets (up to ~67%), but very weak on rare words.</li></ul><p>This method was flexible but biased toward common words — and suffered without a very large, curated Spanish lexicon.</p><h4>3. LLM Prompting with Gemma-2–9B-IT</h4><p>To test how far raw language models could go without fine-tuning, I prompted <strong>Gemma-2–9B-IT</strong> in a zero-shot setting.</p><p>The prompt was strict: <em>“Output exactly one Spanish word. Preserve meaning, fix only orthography, lowercase unless proper noun, keep diacritics.”</em></p><ul><li>Inference was capped at <strong>5 new tokens</strong> and post-processed to keep only the first valid output.</li><li>Evaluated on 100 samples, the model achieved:</li><li><strong>Exact match accuracy:</strong> 45%</li><li><strong>Average CER:</strong> 0.207</li></ul><p>While not beating Hunspell, the LLM showed promise, especially given it wasn’t fine-tuned for this task. Strict output cleaning was essential to make results usable.</p><h4>4. Developing a T5 + LoRA Pipeline</h4><p>Finally, I set out to build my own <strong>sequence-to-sequence pipeline</strong> using T5. The goal was to train a model that could learn correction rules directly from noisy–clean pairs. This pipeline can easily be extented for a bigger dataset. Due to time constraint, it was not possible to train this for a very large corpus that I developed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hu6T3N06vEKFcKYx.png" /><figcaption>Low-Rank Adaptation (Source: DailyDoseofDS.com)</figcaption></figure><h4>Data Preparation</h4><p>The dataset contained paired misspelled and correct words. My preprocessing pipeline:</p><ul><li>Normalize text to <strong>Unicode NFC</strong>.</li><li>Remove non-Spanish characters and cap length at <strong>≤50</strong>.</li><li>Down-sample “identity” pairs (input = target) to avoid the model degenerating into simply copying. I kept ~100 identity samples for balance.</li><li>Final split: <strong>5,000 training pairs</strong> and <strong>1,000 test pairs</strong>.</li></ul><h4>Model Setup</h4><p>I chose <strong>google/byt5-small</strong>, a character-level variant of T5. ByT5 is well-suited for noisy text because it doesn’t rely on subword vocabularies.</p><p>For fine-tuning, I applied <strong>LoRA adapters</strong>:</p><ul><li>Rank = 4, Alpha = 4</li><li>Inserted only into the <strong>q/v attention matrices</strong></li><li>This kept training lightweight but limited adaptability.</li></ul><p>The model used a <strong>prefix-style input</strong>:</p><p>fix: {noisy_word}</p><p>And generated the corrected token, capped at <strong>MAX_LENGTH=64</strong>.</p><h4>Inference</h4><p>During inference, I tried greedy and low-beam decoding. Post-processing enforced:</p><ul><li>Lowercasing (unless proper noun)</li><li>Preservation of diacritics</li><li>Single-token outputs only</li></ul><h4>Summary</h4><p>The first attempt was clearly <strong>under-trained</strong>. With minimal steps and conservative LoRA, results were weak. But the pipeline design was solid:</p><ul><li><strong>Character-level modeling</strong> handled noisy inputs.</li><li><strong>LoRA adapters</strong> made training efficient.</li><li><strong>Identity down-sampling</strong> prevented degenerate copying.</li><li><strong>Prefix prompting</strong> kept inference structured.</li></ul><p>For future runs, we can expand LoRA coverage (q, k, v, o), train for more steps, and try stronger checkpoints like byt5-base or Spanish T5 models.</p><p>Across experiments, Hunspell surprisingly came out strongest, showing how far good dictionaries still go. The fastText hybrid and Gemma offered glimpses of learned flexibility but struggled without richer data or fine-tuning. The real opportunity lies in the <strong>T5 + LoRA pipeline</strong>: even though my initial attempt under-trained, the framework is extensible. With more steps, broader adapter coverage, and lexicon-constrained decoding, it could surpass dictionary-based methods and learn corrections that rule-based systems miss.</p><h3>The annotation tool</h3><p>I built a simple, fast annotation tool to sit between the models and the historians — a place where messy OCR meets clear human judgement. It’s not flashy. It shows one line image at a time, the model’s best guess, and an editable field. That tiny bit of friction turns a brittle automated output into publishable text and, importantly, into better training data.</p><h4>How it fits in the workflow</h4><p>Scanned page → automatic line detection → line crops shown in the tool → model suggestion → human edit/approve → export + retraining. Every accepted edit is versioned and stored, so the dataset improves each time someone corrects a line.</p><h4>What annotators actually see and do</h4><ul><li><strong>Side-by-side view:</strong> the line image next to the suggested transcription. No menus, no clutter.</li><li><strong>Automatic Line Detection</strong>: the tool will automate the entire workflow without any manual help and you can see results straightaway.</li><li><strong>Block controls:</strong> easy split/merge for two-column pages or marginalia — one click, no hunting for coordinates.</li><li><strong>Batch actions:</strong> reviewers can mark many lines as done, then export a clean, audited corpus for retraining.</li><li><strong>Audit trail:</strong> every correction logs who edited it and when, so you can trace changes and measure inter-annotator agreement.</li></ul><h4>Fallbacks</h4><p>Language and correction services are layered: a primary cloud model when the network and budget allow, a secondary hosted endpoint if the first is unavailable, and a local open model as a final fallback. That design keeps the tool usable in a lab with flaky bandwidth, at a small archive that can’t afford per-page API bills, or where data can’t leave the premises.</p><h4>Importance</h4><p>Local deployment keeps data private, avoids per-call API costs, and makes results reproducible across teams. LLaMA-style models are available as open-source checkpoints, which makes running a local model practical for research groups and archives.</p><h4>One-sentence summary</h4><p>A lightweight, human-first annotation tool that turns model guesses into reliable transcriptions while offering resilient fallbacks and an open-local option so archives and researchers can work securely and collaboratively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zezkmX-iesY2oQlfH3SzeA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SwmQbkggLSnQz5X387bsSA.jpeg" /><figcaption>Sample Images from annotation tool (Grey bar in between has appeared to due web capture glitch and does not appear in the actual annotation tool)</figcaption></figure><h4>Synthetic-noise pipeline</h4><p>I built a compact synthetic-noise generator to produce realistic noisy–clean Spanish pairs for OCR correction and historical-normalization training. The error-target dataset I created can be accessed on kaggle through this link. Noisy pairs were generated from the Hugging Face Spanish Billion Words collection (crscardellino/spanish_billion_words) by applying controlled, linguistically-informed edits so models learn real OCR and historical spelling errors.</p><p><strong>Functionality<br></strong> The pipeline corrupts clean text with realistic error types — dropped or misplaced diacritics, historical orthography swaps (x↔j, v↔u, long-s), common OCR confusions (i/l/1, o/0, rn→m), keyboard typos, phonetic swaps (b↔v, ll↔y), and occasional merge/split or punctuation artifacts. A small fraction of examples are left unchanged so the model learns when to preserve text. Generation is seeded and frequency-aware for reproducibility and realistic vocabulary weighting.</p><p><strong>Importance</strong><br> Synthetic pairs fill gaps where annotated historical OCR data is scarce: they expose the model to realistic error patterns, help T5/ByT5-style models learn robust correction strategies, and bootstrap performance on rare or archaic forms. The noise generator is deliberately simple to tune — tweak probabilities, preserve identity examples, and re-run to produce more targeted training sets without heavy annotation overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*PcYtvRY9bSpuU-Gj8Xko4Q.png" /><figcaption>Example of Inference of the full pipeline</figcaption></figure><pre>A estos dos nombres dan misterio-<br>sas interpretaciones los Sagrados In-<br>terpretes. A Caleb le llaman Quasi cor,<br>y a Iosuè Dominus Salvador; Corazon, Señor,<br>y Salvador. Y todos tres significados se<br>hallan en V.I. siendo en el ministerio<br>de Patriarca el Aaron de Palacio, el Sa-<br>cerdote grande de la Casa Real, en cu-<br>yo pecho mejor, que en el racional, se<br>lee Verdad, y Doctrina, para que como en<br>animado Pectoral de discreciones, des-<br>canse el corazon de su Magestad.<br>Es también V.I. Corazón, Señor, y Sal-<br>vador de toda la Christiandad en los Rey-<br>nos de España, pues por su ministerio,<br>a imitación del corazon, da vida espiri-<br>tual a las almas para que se salven, re-<br>partiendo la Bula de la Santa Cruzada<br>a los fieles.<br>Los primeros Comissarios de Cru-<br>zada, que huvo, fueron Iosuè, y Caleb<br>(no es arrojo de Predicador, sino inte-<br>ligencia de Escripturario) pues en un</pre><h3>Conclusion</h3><p>At the GSoC 2025 end, the Spanish OCR pipeline is delivering strong results with accurate text extraction, correction, and a functional inference tool. I have completed tasks I had proposed initially. I will continue to work with HumanAI organization next year too as we can scale this work even more and deliver something that is truly a product for open source community!</p><p>For those interested in the code can visit my GitHub. Thanks to HumanAI and my mentors Xabier Granja, Harrison Meadows and Sergei Gleyzer for their support!</p><p><em>This work is part of Google Summer of Code 2025 with HumanAI, contributing to the RenAIssance Project for historical document digitization.</em></p><p><em>LinkedIn: </em><a href="https://www.linkedin.com/in/pranav-kulkarni-2b6b6a262/"><em>https://www.linkedin.com/in/pranav-kulkarni-2b6b6a262/</em></a><em><br>GitHub: </em><a href="https://github.com/KalkulatorHere"><em>https://github.com/KalkulatorHere</em></a><em><br>RenAIssance GitHub: </em><a href="https://github.com/humanai-foundation/RenAIssance"><em>https://github.com/humanai-foundation/RenAIssance</em></a><em><br>Demo Link: </em><a href="https://drive.google.com/drive/folders/1-8MabxTyBsEvW5irWQjqSU-8SmtfVph8?usp=sharing"><em>https://drive.google.com/drive/folders/1-8MabxTyBsEvW5irWQjqSU-8SmtfVph8?usp=sharing</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cb408920d12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Summer of Code 2025: Enhancing Spanish OCR for Historical Documents]]></title>
            <link>https://medium.com/@pranavesque/gsoc-2025-midterm-report-enhancing-spanish-ocr-for-historical-documents-a754cd3d798f?source=rss-b454dbfc7cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a754cd3d798f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[document-digitalization]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Pranav Kulkarni]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 09:57:55 GMT</pubDate>
            <atom:updated>2025-07-24T13:28:36.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xzANAnVmctlT2D0z.png" /></figure><p>Hello, community!</p><p>I’m Pranav Kulkarni, currently contributing to HumanAI as part of Google Summer of Code 2025. My project focuses on enhancing Spanish OCR for historical documents using deep learning techniques. Now that we’ve reached the midterm of GSoC, I’m excited to share the journey so far. In this article, I’ll walk you through the work I’ve done up to this point.</p><h4>My Project</h4><p>I’m building a robust OCR pipeline for 17th-century Spanish texts under the RenAIssance Project. The workflow combines <a href="https://github.com/matterport/Mask_RCNN">Mask R-CNN</a> for precise line segmentation, a fine-tuned <a href="https://github.com/microsoft/unilm/tree/master/trocr">TrOCR</a> model for recognition, and a <a href="https://github.com/google-research/text-to-text-transfer-transformer">T5-based correction</a> stage later enhanced with LLMs to preserve historical accuracy. An annotation tool also supports expert feedback and iterative dataset growth.</p><blockquote>The proposed pipeline: <br>Scanned PDF → Bounding box generation + OCR → T5 correction → LLM correction → Final output</blockquote><h4>Pre-Coding Phase Period</h4><p>Before the proposals were accepted, we were given a <a href="https://humanai.foundation/gsoc/2025/proposal_OCR2.html">preliminary task</a> — a hands-on challenge that allowed us to explore the problem space and experiment with potential solutions even before the official GSoC timeline began. This early exposure helped me and my teammates brainstorm ideas and lay the groundwork for our contributions well in advance.</p><p>My journey with HumanAI officially began during the community bonding period of Google Summer of Code. This phase was instrumental in building a strong rapport with mentors, understanding the project’s goals, and aligning expectations for the coding phase.</p><p>During this time, I also gained access to the full dataset comprising both printed and handwritten early modern Spanish texts along with their ground truth annotations. The dataset spans a wide range of fonts, page qualities, and stylistic variations, offering both a challenge and a rich ground for training robust OCR models.</p><h4>Fine-tuned Text-Line Detection &amp; TrOCR Extraction</h4><p>I fine-tuned a Mask R-CNN (<a href="https://www.kaggle.com/code/alimustoofaa/mask-rcnn-detectron-2">ResNet-101 FPN</a>) on PAGE-XML→COCO annotations of historical Spanish pages to get high-precision text-line boxes. Once the <a href="https://github.com/facebookresearch/detectron2">Detectron2</a> predictor outputs [x1,y1,x2,y2] boxes, I apply dynamic padding (based on median vertical/horizontal gaps) and margin-area filtering to crop each line cleanly. Those crops are then passed, in sorted reading order, into a <a href="https://huggingface.co/qantev/trocr-large-spanish">qantev/trocr-large-spanish VisionEncoderDecoderModel </a>— yielding line-level OCR text that’s robust to 17th-century fonts and degradations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GopgBh-yziFvjBhQqKUHog.png" /><figcaption>The results of finetuned model to textline detection (The left side shows results without any padding added and the right side shows results after padding is added)</figcaption></figure><h4>Clustering for Reading Sequence</h4><p>Because pages can have multiple columns or irregular spacing, I built a small clustering module that takes the raw text-line boxes, computes a custom distance (vertical gap + α × horizontal penalty), then groups them into blocks via <a href="https://www.geeksforgeeks.org/machine-learning/dbscan-clustering-in-ml-density-based-clustering/">DBSCAN</a>. Within each block, lines are sorted by their y-coordinate to reconstruct the intended reading sequence — even on two-column layouts. This post-processing step fixes the out-of-order lines that confused TrOCR and now delivers perfect single-block and two-block results alike.</p><pre>#pseudo code<br>boxes = load_json(&quot;textlines.json&quot;)         # [[x1,y1,x2,y2],…]<br>lines = [centroid_and_size(b) for b in boxes]<br>D = pairwise_distance(lines, custom_metric) # vertical_gap + α*horizontal_penalty<br>clusters = DBSCAN(eps, min_samples, metric=&quot;precomputed&quot;).fit(D)<br>if too_many_singletons(clusters):<br>    clusters = hierarchical_clustering(D, threshold)<br>reading_sequence = []<br>for block in unique(clusters.labels_):<br>    block_lines = select(lines, clusters.labels_==block)<br>    ordered = sort(block_lines, key=lambda L: L.y_center)<br>    reading_sequence.extend(ordered)<br>save_sequence(&quot;reading_order.txt&quot;, reading_sequence)</pre><h4>Finetuning TrOCR for Better Results and T5 for Spell Correction</h4><h4>Finetuning TrOCR on Rodrigo Dataset</h4><p>The code performs finetuning of the model on the <a href="https://www.kaggle.com/datasets/kalkulatork/rodrigo-dataset-spanish">Rodrigo dataset</a>, which consists of handwritten Spanish text line images paired with ground truth transcriptions. The dataset was parsed, cleaned, and split into training, validation, and test sets, with subsampling applied for efficient training under memory constraints. A streamlined pipeline was set up using Hugging Face’s Seq2SeqTrainer, where multiple experiments were run — ranging from basic setups to optimized runs with augmentations and evaluation metrics like CER and WER. The trained model was saved and later evaluated on unseen test samples, verifying its performance visually. Overall, this code establishes a complete, low-resource-friendly finetuning framework for historical OCR adaptation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sg4X0mv3NwwpnIDp" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vrn99Xtyg-iQbLxh" /><figcaption>Sample results for handwritten text</figcaption></figure><h4>Finetuning Spanish T5 Model for Text Error Correction</h4><p>A pretrained Spanish T5 model was further fine-tuned on a synthetic dataset of erroneous-correct sentence pairs, generated using rule-based strategies to mimic real grammar and spelling mistakes. Data from medical and Wikipedia domains was combined, cleaned, and tokenized before training. The model was trained using Hugging Face’s Trainer with optimized settings, producing a robust error correction model for noisy Spanish text.</p><h4>Current Pipeline Performance</h4><p>At this midterm milestone, I’ve put together a solid, end-to-end OCR pipeline — Detectron2 finetuned model for line extraction (complete with smart dynamic padding and a fail-safe single-column reading order), TrOCR for high-fidelity transcription, and an LLM-powered cleanup stage that preserves the original 17th-century Spanish flair. So far I’ve processed multiple pages and am hitting industry-leading averages: a CER below 8.5%, WER around 11%, a BLEU creeping up on 80%, and an outstanding 94% cosine-similarity — essentially near-human accuracy on these challenging historical documents.</p><h4>Sample Output from Current Pipeline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*_KEC6ADzhH3qTSK6hqMFHQ.png" /><figcaption>Sample image</figcaption></figure><p>The corresponding output:</p><pre>A estos dos nombres dan misterio-<br>sas interpretaciones los Sagrados In-<br>terpretes. A Caleb le llaman Quasi cor,<br>y a Iosuè Dominus Salvador; Corazon, Señor,<br>y Salvador. Y todos tres significados se<br>hallan en V.I. siendo en el ministerio<br>de Patriarca el Aaron de Palacio, el Sa-<br>cerdote grande de la Casa Real, en cu-<br>yo pecho mejor, que en el racional, se<br>lee Verdad, y Doctrina, para que como en<br>animado Pectoral de discreciones, des-<br>canse el corazon de su Magestad.<br>Es también V.I. Corazón, Señor, y Sal-<br>vador de toda la Christiandad en los Rey-<br>nos de España, pues por su ministerio,<br>a imitación del corazon, da vida espiri-<br>tual a las almas para que se salven, re-<br>partiendo la Bula de la Santa Cruzada<br>a los fieles.<br>Los primeros Comissarios de Cru-<br>zada, que huvo, fueron Iosuè, y Caleb<br>(no es arrojo de Predicador, sino inte-<br>ligencia de Escripturario) pues en un</pre><h4>Progress on Inference and Correction Tool</h4><p>I’ve also built a lightweight Flask inference interface that lets me upload in any image or PDF, runs the full OCR pipeline on the server, and returns both the raw TrOCR transcription and the cleaned-up, LLM-corrected text in your browser. Behind the scenes, the Flask app’s /upload endpoint saves the file, kicks off Detectron2 line extraction and TrOCR transcription, then bundles the results into a JSON response; the frontend renders the image, overlays the detected boxes, and displays both the original and corrected text side-by-side for quick review or further annotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nVLBMXF_jXsAcSCTE9mubQ.png" /></figure><h4>Looking Forward</h4><p>The pipeline is performing well at this midterm stage, with strong metrics and a working inference tool. The next phase will focus on further optimization, expanding the dataset for future contributors, and refining the correction mechanisms (be it OCR or spelling corrections) to handle even more complex historical document variations.</p><h3>Conclusion</h3><p>At the GSoC 2025 midterm, the Spanish OCR pipeline is delivering strong results with accurate text extraction, correction, and a functional inference tool. The next phase will focus on model optimization, dataset expansion, and refining correction quality.</p><p>For those interested in the code can visit my GitHub. Thanks to HumanAI and my mentors for their support!</p><p><em>This work is part of Google Summer of Code 2025 with HumanAI, contributing to the RenAIssance Project for historical document digitization.</em></p><p><em>LinkedIn: </em><a href="https://www.linkedin.com/in/pranav-kulkarni-2b6b6a262/"><em>https://www.linkedin.com/in/pranav-kulkarni-2b6b6a262/</em></a><em><br>GitHub: </em><a href="https://github.com/KalkulatorHere"><em>https://github.com/KalkulatorHere</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a754cd3d798f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>