<?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 Mykola Melnyk on Medium]]></title>
        <description><![CDATA[Stories by Mykola Melnyk on Medium]]></description>
        <link>https://medium.com/@mmykola?source=rss-1d4546062b88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zh1NrOU2ockTFrKi</url>
            <title>Stories by Mykola Melnyk on Medium</title>
            <link>https://medium.com/@mmykola?source=rss-1d4546062b88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:59:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mmykola/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[PDF Redaction Studio Desktop Is Now Available for macOS]]></title>
            <link>https://mmykola.medium.com/pdf-redaction-studio-desktop-is-now-available-for-macos-ac3af6334678?source=rss-1d4546062b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac3af6334678</guid>
            <category><![CDATA[desktop-app]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[privacy]]></category>
            <dc:creator><![CDATA[Mykola Melnyk]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 17:01:52 GMT</pubDate>
            <atom:updated>2026-10-17T17:01:52.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ul9xAm4wp-1mpUOXk_eLOw.png" /></figure><p>Scrubbing sensitive information out of a PDF — a name, a Social Security number, an address, a face in a scanned ID — only counts if the underlying data is actually gone. A black box painted over text is not redaction; the text is still there underneath.</p><p><strong>PDF Redaction Studio Desktop</strong>, already available for Windows and Linux, now runs natively on macOS too.</p><h3>Get It Now</h3><p>👉 <a href="https://pdf-redaction.com/download/"><strong>Download PDF Redaction Studio Desktop for Mac</strong></a></p><p>Requires Apple Silicon (M1 or later) and macOS 11 Big Sur or newer.</p><h3>Why a Desktop App</h3><p>The <a href="https://pdf-redaction.com/">web app</a> already redacts PDFs entirely in your browser, which covers most one-off jobs. The desktop app is for teams that process documents regularly — legal, HR, healthcare, support — and wanted:</p><ul><li>A real native app, not a browser tab to keep open</li><li>No Docker, no backend to stand up</li><li>Document processing that’s unambiguously local by default</li><li>A dashboard that tracks documents, completed redactions and usage</li></ul><h3>What It Does</h3><ul><li><strong>AI-powered PII detection</strong> — finds and flags names, addresses, emails, phone numbers, ID numbers, and faces</li><li><strong>Local processing</strong> — OCR, PII detection and face detection run on your own Mac; documents don’t need to leave the machine to get scanned</li><li><strong>Review before anything changes</strong> — filter by category, add what the model missed, remove false positives</li><li><strong>Custom redaction rules</strong> — match patterns specific to your compliance requirements</li><li><strong>True redaction on export</strong> — the matched content is actually removed from the PDF, not painted over</li></ul><h3>Installing on macOS</h3><p>Two options from the <a href="https://pdf-redaction.com/download/">download page</a>:</p><ul><li>Pdf.Redaction.Studio.dmg — open it, drag the app into Applications</li><li>Pdf.Redaction.Studio-darwin-arm64.zip — portable, unzip and run</li></ul><p>The build isn’t notarized by Apple yet, so the first launch may show “can’t be opened” or “is damaged.” Run this once in Terminal:</p><pre>xattr -dr com.apple.quarantine &quot;/Applications/Pdf Redaction Studio.app&quot;</pre><p>Then open it as usual. Or skip Terminal entirely: open the app once, then go to <strong>System Settings → Privacy &amp; Security → Open Anyway</strong>. Full instructions: <a href="https://pdf-redaction.com/docs/studio-desktop/">Studio Desktop docs</a>.</p><h3>Getting Started</h3><ol><li>Install from the <a href="https://pdf-redaction.com/download/">download page</a></li><li>Open a PDF</li><li>Let AI detection scan for PII, or add your own custom rules</li><li>Review and adjust the flagged matches</li><li>Export a clean, fully redacted PDF</li></ol><h3>What’s Next</h3><p>Studio Desktop is now on Windows (via the <a href="https://apps.microsoft.com/detail/9p9g1wdm89qw">Microsoft Store</a>), Linux (via Snap: sudo snap install pdf-redaction-studio), and macOS. Apple notarization and an Intel build for Mac are both next on the list. All builds, including older versions, are published on <a href="https://github.com/StabRise/pdf-redaction-studio/releases/">GitHub Releases</a>.</p><p>If you run into a document type or redaction rule the macOS build doesn’t handle well yet, we’d like to hear about it.</p><p><em>PDF Redaction Studio Desktop is part of </em><a href="https://pdf-redaction.com/"><em>PDF Redaction</em></a><em>, an AI-powered redaction tool for removing sensitive information from PDFs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac3af6334678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Redact Sensitive PDFs in Google Drive Before You Share Them]]></title>
            <link>https://mmykola.medium.com/how-to-redact-sensitive-pdfs-in-google-drive-before-you-share-them-5273faa26cdd?source=rss-1d4546062b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/5273faa26cdd</guid>
            <category><![CDATA[google-drive]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[gdpr]]></category>
            <category><![CDATA[compliance]]></category>
            <dc:creator><![CDATA[Mykola Melnyk]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 06:37:34 GMT</pubDate>
            <atom:updated>2026-10-14T06:37:34.030Z</atom:updated>
            <content:encoded><![CDATA[<p>Every team has the same quiet risk: a PDF in a shared Drive folder that contains more than the person receiving it should see. A contract with bank details. A performance review with a home address. A scanned form with a national ID number.</p><p>Sharing the original is a data-protection incident waiting to happen. Sending a “redacted” copy where someone drew black boxes in a PDF editor can be worse, because the text under the boxes is often still there and can be copied out.</p><p>This guide covers a simple way to handle it without leaving Google Drive™.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S1nrqhReBh-HbpA7.png" /></figure><h3>When you actually need to redact</h3><p>Redaction is the right tool when a document has to go outside its original audience but the rest of its content must stay intact. Common cases:</p><ul><li><strong>HR:</strong> sharing a policy acknowledgement or a case file with a third party</li><li><strong>Legal:</strong> producing documents for disclosure or discovery</li><li><strong>Finance:</strong> sending invoices to auditors without customer details</li><li><strong>Support:</strong> attaching a customer’s document to a ticket for another team</li><li><strong>Subject access requests:</strong> removing other people’s data from what you hand back</li></ul><h3>Step by step</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BjsXTmhtMOJ7FJdl.png" /></figure><ol><li><strong>Install the app once.</strong> Add <a href="https://workspace.google.com/marketplace/app/redact_pdf_by_pdf_redaction/235796577754">Redact PDF by PDF Redaction</a> from the Google Workspace Marketplace. If you’re an admin, you can roll it out to your whole domain.</li><li><strong>Right-click the PDF in Drive</strong> and choose Open with, then Redact PDF by PDF Redaction.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XlqenJwC0-Rrw18C.png" /></figure><ol><li><strong>Let the AI scan it.</strong> Names, emails, phone numbers, addresses, ID and card numbers, faces and signatures are flagged automatically, including on scanned pages.</li><li><strong>Review before you commit.</strong> Drop false positives, widen a box that is too tight, and add anything the AI missed by drawing it yourself.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GaJx4KgF-9JJM6jC.png" /></figure><ol><li><strong>Download the redacted copy</strong> and upload it back to Drive in the folder you want.</li></ol><h3>A checklist before you share</h3><ul><li>Search the redacted file for a name or number you removed. It should not be found.</li><li>Check headers, footers and page numbers; they’re easy to forget.</li><li>Look at metadata such as the author field if the file’s origin matters.</li><li>Keep the original in a restricted folder and label the redacted copy clearly.</li></ul><h3>Questions people ask</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6tSmitNK9gU_e-S0.png" /></figure><p><strong>Does it see my whole Drive?</strong> No. It uses Google’s per-file permission, so it can only read PDFs you open with it or choose in the picker.</p><p><strong>Is my document uploaded somewhere?</strong> The PDF is processed in your browser. By default the extracted text is sent for detection with zero retention, and a local mode keeps everything on your device.</p><p><strong>Does it write back to Drive?</strong> Not automatically. You download the redacted file and upload it yourself, which keeps your original safe from accidental overwrites.</p><h3>Where to go next</h3><p>The <a href="https://pdf-redaction.com/docs/integrations/google-drive/">integration documentation</a> covers permissions, limits and troubleshooting in detail. If you’re evaluating it for a team, start with a handful of real documents; that tells you more than any feature list.</p><p><em>Google Drive™ is a trademark of Google LLC. Redact PDF by PDF Redaction is not affiliated with or endorsed by Google LLC.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5273faa26cdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PDF Redaction Studio Desktop Is Now Available on the Microsoft Store]]></title>
            <link>https://mmykola.medium.com/pdf-redaction-studio-desktop-is-now-available-on-the-microsoft-store-f1c033809cbc?source=rss-1d4546062b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1c033809cbc</guid>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Mykola Melnyk]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 19:52:17 GMT</pubDate>
            <atom:updated>2026-08-24T20:01:59.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTJrlkI1Pk-edIXM1Kbh0w.png" /></figure><p>If you’ve ever had to scrub sensitive information out of a PDF before sending it to someone — a name, a Social Security number, an address, a face in a scanned ID — you know how painful it usually is. Real redaction means removing the underlying data, not just painting over it.</p><p>That’s what <strong>PDF Redaction Studio Desktop</strong> is built for, and it’s now available as a native Windows app on the Microsoft Store.</p><h2>Get It Now</h2><p>👉 <a href="https://apps.microsoft.com/detail/9p9g1wdm89qw"><strong>Install PDF Redaction Studio Desktop from the Microsoft Store</strong></a></p><p>No Docker, no server setup, no account juggling — just install and start redacting.</p><h2>Why a Desktop App</h2><p>PDF Redaction started as a web app, and the web app is still there for anyone who wants zero installation. But a lot of our users — lawyers, HR teams, healthcare admins, developers handling exports — work with documents they’d rather not upload anywhere. They wanted something that:</p><ul><li>Runs as a real native app, not a browser tab</li><li>Doesn’t require standing up Docker or a backend server</li><li>Keeps document processing on their own machine</li><li>Still gets the benefit of AI-powered PII detection</li></ul><p>PDF Redaction Studio Desktop is the answer. It brings the same AI-powered redaction engine from pdf-redaction.com into a native app for Windows (with Linux available via Snap, and macOS support on the way).</p><h2>What It Does</h2><ul><li><strong>AI-powered PII detection</strong> — automatically finds and flags names, addresses, emails, phone numbers, ID numbers, and faces in scanned documents.</li><li><strong>Local processing</strong> — OCR, data extraction, and face detection run on your own device, so documents don’t need to leave your machine to get analyzed.</li><li><strong>Real-time preview</strong> — see exactly what will be redacted before you commit to it.</li><li><strong>Custom redaction rules</strong> — define your own patterns to match specific compliance requirements (GDPR, HIPAA, internal policy, whatever your case needs).</li><li><strong>True redaction on export</strong> — the final PDF has the sensitive content actually removed, not just painted over, so it can’t be recovered by copy-pasting or peeling back a layer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXr9dKYeWWVejxisS08lDQ.png" /><figcaption>Main Dashboard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ul9xAm4wp-1mpUOXk_eLOw.png" /><figcaption>Redaction interface</figcaption></figure><h2>Why It Matters</h2><p>Redaction is a compliance and trust problem as much as a technical one. Getting it wrong — leaving recoverable data behind — has ended up in the news more than once, in legal filings and government documents alike.</p><p>Running the tool locally also means fewer questions to answer about where your documents went. If you’re handling contracts, medical records, or anything with PII in it, “processing happened on my own laptop” is a much easier sentence to say than “processing happened on someone else’s server.”</p><h2>Getting Started</h2><ol><li>Install from the <a href="https://apps.microsoft.com/detail/9p9g1wdm89qw">Microsoft Store</a></li><li>Open a PDF</li><li>Let the AI detection scan for PII, or add your own custom rules</li><li>Preview the redactions</li><li>Export a clean, fully redacted PDF</li></ol><p>Full setup and usage docs are here: <a href="https://pdf-redaction.com/docs/studio-desktop/">pdf-redaction.com/docs/studio-desktop</a></p><h2>What’s Next</h2><p>Linux is already supported via Snap (sudo snap install pdf-redaction-studio), and macOS support is coming soon. All builds — including older versions — are also published on <a href="https://github.com/StabRise/pdf-redaction-studio/releases/">GitHub Releases</a> for anyone who wants them outside the app stores.</p><p>If you try it out, we’d love to hear what you think — and if you hit a document type or redaction rule it doesn’t handle well yet, tell us. That’s exactly the kind of feedback that shapes what we build next.</p><p><em>PDF Redaction Studio Desktop is part of </em><a href="https://pdf-redaction.com/"><em>PDF Redaction</em></a><em>, an AI-powered redaction tool for removing sensitive information from PDFs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1c033809cbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PDF Schwärzen mit KI — kostenlos und ohne Installation]]></title>
            <link>https://mmykola.medium.com/pdf-schw%C3%A4rzen-mit-ki-kostenlos-und-ohne-installation-e87c6e1ba650?source=rss-1d4546062b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/e87c6e1ba650</guid>
            <category><![CDATA[datenschutz]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[dsgvo]]></category>
            <dc:creator><![CDATA[Mykola Melnyk]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 09:59:52 GMT</pubDate>
            <atom:updated>2026-06-07T13:03:17.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sew_gmlGZnyfvRZcCJBOMA.png" /></figure><p><a href="https://pdf-redaction.com/de/">pdf-redaction.com</a> — <em>KI-gestütztes PDF Schwärzen im Browser</em></p><p>Das Schwärzen von Dokumenten sollte keine komplizierte Angelegenheit sein. Wir haben ein browserbasiertes Werkzeug entwickelt, mit dem du ein PDF hochladen, personenbezogene Daten automatisch per KI erkennen lassen, nach Bedarf anpassen und eine saubere, geschwärzte Version exportieren kannst. Keine Installation erforderlich — alles läuft direkt im Browser.</p><h3>Was ist PDF Schwärzen?</h3><p><strong>PDF Schwärzen</strong> (englisch: <em>PDF Redaction</em>) bedeutet das dauerhafte Entfernen sensibler oder vertraulicher Informationen aus einem Dokument. Im Gegensatz zum einfachen Abdecken mit schwarzen Balken — wie es viele Tools nur visuell tun — werden beim echten Schwärzen die Daten vollständig aus der Datei gelöscht. Das Ergebnis: ein sicheres, teilbares Dokument ohne jede Spur der entfernten Inhalte.</p><p>Typische Anwendungsfälle:</p><ul><li>Behörden und Unternehmen, die Dokumente nach DSGVO-konform teilen müssen</li><li>Anwälte und Notare, die Verträge anonymisieren</li><li>Journalisten, die Quellen schützen</li><li>HR-Abteilungen, die Bewerbungsunterlagen weiterleiten</li></ul><h3>Einfach hochladen — KI erkennt das Wesentliche</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DaJ-3LEgqtAdYx_AdOKs6Q.png" /></figure><p>Die Oberfläche ist bewusst schlicht gehalten. Lade ein PDF hoch, und die KI markiert sofort personenbezogene Daten:</p><ul><li>Namen</li><li>E-Mail</li><li>Telefonnummern</li><li>Adressen</li><li>und weitere sensible Informationen</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtAwljLNmWG0EAh193zGYQ.png" /></figure><h3>Du behältst die Kontrolle</h3><p>Die KI übernimmt den ersten Durchlauf — aber du entscheidest, was tatsächlich geschwärzt wird:</p><p>✔ KI-Vorschläge prüfen und bestätigen<br> ✔ Markierungen verschieben, anpassen oder löschen<br> ✔ Eigene Bereiche manuell auswählen<br> ✔ Gezielt nach Text suchen und schwärzen<br> ✔ Schwärzungsfarbe wählen: Schwarz oder Weiß</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4OBA3R4idXMdsWiHlo4ZA.png" /></figure><h3>Echtes Schwärzen — keine Kosmetik</h3><p>Viele Tools legen lediglich schwarze Rechtecke über den Text. Die Daten sind dabei noch vorhanden — und können wiederhergestellt werden.</p><p>pdf-redaction.com baut das PDF nach dem Schwärzen neu auf. Der sensible Inhalt ist tatsächlich entfernt, nicht nur überdeckt. Das Ergebnis ist ein sauberes, sicheres Dokument.</p><p>Kostenlos nutzen — ohne Limits bei der Dokumentenanzahl</p><p>Das Tool bietet einen <strong>kostenlosen Tarif</strong> mit klaren Konditionen:</p><p>KostenlosSeiten pro Dokumentbis zu 25Anzahl der DokumenteunbegrenztInstallationnicht nötigRegistrierungoptional</p><p>Für größere Dokumente oder Enterprise-Workflows sind kostenpflichtige Pläne verfügbar.</p><h3>Für den Einstieg und darüber hinaus</h3><p>Das Tool ist sofort einsatzbereit für Einzeldokumente im Browser. Es basiert jedoch auf einer skalierbaren Architektur — und kann problemlos in größere Workflows integriert werden zur Massenverarbeitung tausender Dokumente.</p><h3>Jetzt kostenlos ausprobieren</h3><p><a href="https://pdf-redaction.com/de/redact-pdf/">PDF hochladen und in Sekunden schwärzen →</a></p><p>Ein Klick genügt. Keine Registrierung erforderlich. Die KI erledigt die Arbeit — du behältst die Kontrolle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e87c6e1ba650" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Custom PII in PDF Documents Using the PDF Redaction API]]></title>
            <link>https://mmykola.medium.com/detecting-custom-pii-in-pdf-documents-using-the-pdf-redaction-api-8d42fa71107d?source=rss-1d4546062b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d42fa71107d</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mykola Melnyk]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 08:01:45 GMT</pubDate>
            <atom:updated>2026-04-21T04:57:41.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uGN29RXheh3iI7xWmXf9Q.png" /></figure><h3>Standard PII Detection Isn’t Enough</h3><p>Every organization handles sensitive data that goes beyond the usual suspects — names, emails, phone numbers. A hospital needs to protect patient IDs and medical record numbers. A law firm needs to redact case numbers and file references. A bank needs to mask internal branch codes and transaction IDs.</p><p>Most PDF redaction tools stop at the standard set of PII categories. But real-world compliance requirements often demand more. That’s where <strong>custom tags</strong> in the <a href="https://pdf-redaction.com/redaction-api/">PDF Redaction API</a> come in — letting you define your own entity types to detect and redact, alongside the built-in PII categories.</p><p>In this article, we’ll walk through how to use custom tags with the API, with a complete Python example you can run in <a href="https://colab.research.google.com/github/StabRise/pdf-redaction-api/blob/main/jupyter/PDF-Redaction-API-custom-tags.ipynb">Google Colab</a>.</p><h3>What Is the PDF Redaction API?</h3><p>The <a href="https://api.pdf-redaction.com/api/docs">PDF Redaction API</a> is a REST API for automated, AI-powered PDF redaction. It uses ML/LLM models to identify sensitive information in documents — including OCR for image-based PDFs — and returns permanently redacted PDFs.</p><p>Key capabilities:</p><ul><li><strong>21 built-in PII categories</strong> — names, emails, SSNs, credit cards, faces, signatures, QR codes, and more</li><li><strong>Custom tags</strong> — define your own entity types for domain-specific data</li><li><strong>OCR support</strong> — handles scanned documents and image-based PDFs</li><li><strong>Detailed detection results</strong> — returns bounding boxes, confidence scores, and entity types for every finding</li></ul><h3>Standard PII Tags</h3><p>Out of the box, the API detects these standard entity types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*pkci9kDaQWGEOG5yo9ZB0A.png" /></figure><h3>Enter Custom Tags</h3><p>Custom tags let you extend the detection engine with domain-specific entity types. They are <strong>added on top of</strong> the standard PII tags — you don’t lose any built-in detection.</p><p>Some practical examples:</p><ul><li><strong>Medical documents</strong>: PATIENT_ID, MEDICAL_RECORD_NUMBER, DIAGNOSIS_CODE</li><li><strong>Legal documents</strong>: CASE_NUMBER, FILE_REFERENCE, COURT_LOCATION</li><li><strong>Financial documents</strong>: TRANSACTION_ID, BRANCH_CODE, INTERNAL_ACCOUNT</li><li><strong>HR documents</strong>: EMPLOYEE_ID, DEPARTMENT_CODE, PROJECT_NAME</li><li><strong>Research data</strong>: PARTICIPANT_CODE, STUDY_ID, LAB_REFERENCE</li></ul><h3>Getting Started</h3><h3>1. Get an API Key</h3><p>Sign up at <a href="https://pdf-redaction.com/apikeys/">pdf-redaction.com/apikeys/</a> to generate your free API key.</p><h3>2. Install Dependencies</h3><pre>pip install requests python-dotenv</pre><h3>3. Write Your First Request</h3><p>Here’s a complete example that redacts standard PII plus a custom TIN (Tax Identification Number) tag:</p><pre>import requests<br>import base64<br>import json<br>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()<br>API_URL = &quot;https://api.pdf-redaction.com/api/anonymize/pdf&quot;<br>API_KEY = os.environ.get(&quot;PDF_REDACTION_API_KEY&quot;)<br># Standard PII tags to redact<br>tags = [<br>    &quot;DATE&quot;,<br>    &quot;PERSON_NAME&quot;,<br>    &quot;LOCATION&quot;,<br>    &quot;EMAIL&quot;,<br>    &quot;PHONE&quot;,<br>    &quot;ID&quot;,<br>    &quot;ACCOUNT&quot;<br>]<br># Custom tags - these extend the standard detection<br>custom_tags = [<br>    &quot;TIN&quot;<br>]<br># Read and encode the PDF<br>with open(&quot;document.pdf&quot;, &quot;rb&quot;) as f:<br>    pdf_base64 = base64.b64encode(f.read()).decode(&quot;utf-8&quot;)<br>response = requests.post(<br>    API_URL,<br>    headers={<br>        &quot;accept&quot;: &quot;application/pdf&quot;,<br>        &quot;X-API-Key&quot;: API_KEY,<br>    },<br>    json={<br>        &quot;pdf&quot;: pdf_base64,<br>        &quot;tags&quot;: tags,<br>        &quot;custom_tags&quot;: custom_tags,<br>        &quot;rotated_text&quot;: False,<br>        &quot;force_ocr&quot;: True<br>    }<br>)<br>if response.status_code == 200:<br>    result = response.json()<br>    # Save the redacted PDF<br>    pdf_data = base64.b64decode(result[&quot;pdf&quot;].encode())<br>    with open(&quot;redacted_output.pdf&quot;, &quot;wb&quot;) as out:<br>        out.write(pdf_data)<br>    # Inspect what was detected<br>    for page in result[&quot;detected_pii&quot;]:<br>        for entity in page[&quot;entities&quot;]:<br>            print(f&quot;  {entity[&#39;entity_group&#39;]}: {entity[&#39;word&#39;]}&quot;)<br>else:<br>    print(&quot;Error:&quot;, response.json())</pre><h3>4. Inspect Detection Results</h3><p>The API returns detailed information about every detected entity, including bounding boxes with coordinates and confidence scores:</p><pre>{<br>  &quot;entity_group&quot;: &quot;TIN&quot;,<br>  &quot;word&quot;: &quot;98-76543&quot;,<br>  &quot;boxes&quot;: [<br>    {<br>      &quot;text&quot;: &quot;98-76543&quot;,<br>      &quot;score&quot;: 0.884,<br>      &quot;x&quot;: 1983,<br>      &quot;y&quot;: 1783,<br>      &quot;width&quot;: 190,<br>      &quot;height&quot;: 34<br>    }<br>  ]<br>}</pre><p>This makes it easy to build auditing and review workflows on top of the API — you can log every detection, flag low-confidence matches for human review, or filter results by entity type.</p><h3>Combining Standard and Custom Tags</h3><p>You have full flexibility in how you combine tags:</p><pre># Comprehensive: all standard PII + custom tags<br>tags = []  # empty = use all 21 standard tags<br>custom_tags = [&quot;MEDICAL_RECORD&quot;, &quot;PATIENT_ID&quot;]<br><br># Targeted: only specific standard tags + custom tags<br>tags = [&quot;PERSON_NAME&quot;, &quot;EMAIL&quot;]<br>custom_tags = [&quot;EMPLOYEE_ID&quot;]</pre><h3>Free Tier</h3><p>The PDF Redaction API has a generous free tier so you can start building right away:</p><h3>Free — $0/month</h3><ul><li>First 25 pages per document</li><li>25 MB max file size</li><li>Unlimited documents</li><li>OCR for image-based PDFs</li><li>Common language support</li><li>Web-based access</li><li>Basic redaction patterns</li><li>Community support</li><li>100 API requests/month</li><li>Up to 10 pages per API request</li><li>5 requests/minute rate limit</li></ul><h3>Self-Hosted — PDF Redaction API</h3><p>For organizations that need full control over their data, PDF Redaction offers an <strong>on-premise deployment</strong> option. Your AI models, documents, and processing never leave your infrastructure.</p><ul><li>Complete data sovereignty — documents never leave your environment</li><li>Air-gapped security for defense, government, and finance</li><li>Custom rule engine with highly specific redaction rules</li><li>Continuous machine learning on proprietary data</li><li>Batch processing and enterprise-level performance</li><li>Professional services: 15+ years of expertise in ML, NLP, OCR, and Big Data</li></ul><p>Read the <a href="https://pdf-redaction.com/docs/api-self-hosted/">Self-Hosted API Guide</a> for setup details.Try It Yourself</p><p>The complete working example is available as a Jupyter Notebook that runs in Google Colab — no local setup required:</p><blockquote><a href="https://colab.research.google.com/github/StabRise/pdf-redaction-api/blob/main/jupyter/PDF-Redaction-API-custom-tags.ipynb"><em>Open the Custom Tags Notebook in Colab</em></a></blockquote><p>The full source code repository with additional examples (base64 upload, custom prompts, face redaction) is on GitHub:</p><blockquote><a href="https://github.com/StabRise/pdf-redaction-api"><em>StabRise/pdf-redaction-api</em></a></blockquote><h3>Useful Links</h3><ul><li><a href="https://api.pdf-redaction.com/api/docs">PDF Redaction API Docs (Swagger)</a></li><li><a href="https://pdf-redaction.com/docs/api/">API Documentation</a></li><li><a href="https://pdf-redaction.com/docs/api-self-hosted/">Self-Hosted API Guide</a></li><li><a href="https://pdf-redaction.com/apikeys/">API Key Management</a></li><li><a href="https://pdf-redaction.com/apikeys/usage/">Usage Dashboard</a></li><li><a href="https://pdf-redaction.com/en/pricing">Pricing</a></li><li><a href="https://pdf-redaction.com/">Web UI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d42fa71107d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating NeMo Guardrails with LangGraph: Using Detected Intent to Power Your Graph Workflows]]></title>
            <link>https://mmykola.medium.com/integrating-nemo-guardrails-with-langgraph-using-detected-intent-to-power-your-graph-workflows-52b424d861d6?source=rss-1d4546062b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/52b424d861d6</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nemo-guardrails]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Mykola Melnyk]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 16:23:36 GMT</pubDate>
            <atom:updated>2026-01-25T16:23:36.127Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Building production-ready AI applications requires more than just connecting a language model to your tools. You need robust input validation, content filtering, intent detection, and sophisticated routing logic. While LangGraph provides excellent orchestration capabilities for multi-step AI workflows, integrating it with NeMo Guardrails for safety and intent detection creates a powerful combination that’s greater than the sum of its parts.</p><p>In this comprehensive guide, we’ll explore how to integrate NeMo Guardrails with LangGraph, focusing specifically on extracting and utilizing detected intent within your graph workflows. We’ll compare this approach with standard integrations, provide practical code examples, and demonstrate how intent-based tool filtering can dramatically improve both performance and accuracy.</p><h3>The Challenge: Why Intent Matters in Graph Workflows</h3><h3>The Problem with Standard Integrations</h3><p>Most LangGraph tutorials show you how to build agents with tool calling capabilities. A typical implementation looks like this:</p><pre>from langgraph.graph import StateGraph, START<br>from langgraph.prebuilt import ToolNode, tools_condition<br>from langchain_core.messages import HumanMessage<br>from typing import TypedDict, Annotated<br>from langgraph.graph.message import add_messages<br><br>class State(TypedDict):<br>    messages: Annotated[list, add_messages]<br>def chatbot(state: State):<br>    # All tools are always available<br>    llm_with_tools = base_llm.bind_tools(all_tools)<br>    return {&quot;messages&quot;: [llm_with_tools.invoke(state[&quot;messages&quot;])]}<br># Build graph<br>graph = StateGraph(State)<br>graph.add_node(&quot;chatbot&quot;, chatbot)<br>graph.add_node(&quot;tools&quot;, ToolNode(tools=all_tools))<br>graph.add_conditional_edges(&quot;chatbot&quot;, tools_condition)<br>graph.add_edge(&quot;tools&quot;, &quot;chatbot&quot;)<br>graph.add_edge(START, &quot;chatbot&quot;)</pre><p>This approach works, but it has significant limitations:</p><ol><li>Tool Overload: When you have many tools (10+), the LLM faces a large action space, leading to slower inference and higher costs</li><li>No Input Validation: Malicious or off-topic queries reach your main LLM</li><li>No Intent Awareness: The system can’t route queries intelligently or provide context-specific responses</li><li>Inefficient Resource Usage: Every query goes through the full LLM pipeline, even for simple greetings or refusals</li></ol><h3>The Solution: Intent-Driven Graph Architecture</h3><p>By integrating NeMo Guardrails with LangGraph, we can:</p><ul><li>Detect intent early in the conversation flow</li><li>Filter tools dynamically based on detected intent</li><li>Validate inputs before they reach expensive LLM calls</li><li>Route intelligently to appropriate handlers</li><li>Reduce costs by using smaller models for guardrails and only exposing relevant tools</li></ul><h3>Understanding NeMo Guardrails</h3><p>NeMo Guardrails is an open-source toolkit for adding programmable guardrails to LLM applications. It provides three main types of rails:</p><ol><li>Input Rails: Validate and filter user input before processing</li><li>Output Rails: Validate and filter LLM responses before returning</li><li>Dialog Rails: Control conversation flow and detect intents</li></ol><h3>Key Concepts</h3><p>Intent Detection: NeMo Guardrails uses embedding-based similarity as its primary method for intent detection. When you define user intents in CoLang with example phrases, Guardrails:</p><ul><li>Generates embeddings for the user’s input message</li><li>Compares these embeddings against embeddings of your defined intent examples</li><li>Matches the user’s message to the most similar intent based on semantic similarity</li></ul><p>This embedding-based approach allows Guardrails to detect intents even when users phrase their queries differently than your examples, making the system robust to natural language variations. The embeddings are generated using the embedding model configured in your config.yml (e.g., all-MiniLM-L6-v2 by default).</p><p>CoLang: Guardrails uses a domain-specific language called CoLang to define conversation flows, intents, and bot responses.</p><p>Internal Events: When processing messages, Guardrails emits internal events that include detected intents, which we can extract programmatically.</p><h3>Architecture Overview: The Star Schema</h3><p>Our integration follows a star schema pattern where intent detection sits at the center, and different components branch out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZzo8EKW7aiUf2wWL1FzLw.png" /></figure><h3>Implementation: Step-by-Step Integration</h3><h3>Step 1: Define Your State Schema with Intent</h3><p>The first step is to extend LangGraph’s state to include intent information:</p><pre>from typing import TypedDict, Annotated, Any<br>from langgraph.graph.message import add_messages<br><br>class State(TypedDict):<br>    &quot;&quot;&quot;State schema for the LangGraph agent with intent tracking.<br>    <br>    Attributes:<br>        messages: List of conversation messages (HumanMessage, AIMessage, etc.)<br>        intent: Detected user intent (e.g., &quot;search_books&quot;, &quot;ask about authors&quot;, &quot;check_inventory&quot;, &quot;general&quot;)<br>    &quot;&quot;&quot;<br>    messages: Annotated[list[Any], add_messages]<br>    intent: Annotated[str, &quot;general&quot;]  # Default to &quot;general&quot; if no intent detected</pre><p>The intent field will persist across graph nodes, allowing downstream nodes to make routing decisions based on the detected intent.</p><h3>Step 2: Configure NeMo Guardrails</h3><p>NeMo Guardrails requires configuration files. Here’s a minimal setup:</p><p>config.yml:</p><pre>rails:<br>  input:<br>    flows:<br>      - self check input  # Input validation flow<br>  <br>  dialog:<br>    single_call:<br>      enabled: false<br>    user_messages:<br>      embeddings_only: false<br><br>core:<br>  embedding_search_provider:<br>    name: default<br>    parameters:<br>      embedding_engine: FastEmbed<br>      embedding_model: all-MiniLM-L6-v2</pre><p>rails.co (CoLang file):</p><pre># Define user intents<br>define user express greeting<br>  &quot;hello&quot;<br>  &quot;hi&quot;<br>  &quot;hey&quot;<br>  &quot;good morning&quot;<br><br>define user search books<br>  &quot;find me a book about Python&quot;<br>  &quot;search for mystery novels&quot;<br>  &quot;I&#39;m looking for science fiction books&quot;<br>  &quot;show me books by Stephen King&quot;<br><br>define user ask about authors<br>  &quot;who wrote The Great Gatsby?&quot;<br>  &quot;tell me about J.K. Rowling&quot;<br>  &quot;what books has this author written?&quot;<br><br>define user check inventory<br>  &quot;is this book in stock?&quot;<br>  &quot;do you have this book available?&quot;<br>  &quot;check availability&quot;<br><br># Define bot responses<br>define bot express greeting<br>  &quot;Hello! Welcome to our bookstore. How can I help you find the perfect book today?&quot;<br><br># Define flows<br>define flow greeting<br>  priority 1.0<br>  user express greeting<br>  bot express greeting<br><br>define flow self check input<br>  $input_safe = execute self_check_input<br>  if not $input_safe<br>    bot refuse<br>    stop</pre><h3>Step 3: Initialize Guardrails with Intent Detection</h3><pre>from nemoguardrails.integrations.langchain.runnable_rails import RunnableRails<br>from nemoguardrails.rails.llm.options import GenerationOptions<br>from nemoguardrails import RailsConfig<br><br># Load guardrails configuration<br>rails_config = RailsConfig.from_path(&quot;./guardrails_config&quot;)<br># Initialize guardrails<br># passthrough=False ensures all inputs are validated<br>guardrails = RunnableRails(<br>    config=rails_config,<br>    passthrough=False,<br>    llm=rails_llm,  # Smaller/faster model for guardrails<br>    verbose=True<br>)</pre><h3>Step 4: Create the Chatbot Node with Intent Extraction</h3><p>This is the core of our integration. The chatbot node processes messages through guardrails, extracts intent, and uses it to filter tools:</p><pre>from langchain_core.messages import HumanMessage<br>from langchain_core.prompts import ChatPromptTemplate<br><br>async def chatbot(state: State) -&gt; State:<br>    &quot;&quot;&quot;Main chatbot node that processes messages through guardrails.<br>    <br>    Flow:<br>    1. Process user messages through guardrails for intent detection<br>    2. Extract detected intent from guardrails internal events<br>    3. Filter tools based on intent<br>    4. Generate response with filtered tools<br>    &quot;&quot;&quot;<br>    new_state = {}<br>    <br>    # Process user messages through guardrails<br>    if isinstance(state[&quot;messages&quot;][-1], HumanMessage):<br>        # Transform message to guardrails format<br>        input_messages = guardrails._transform_input_to_rails_format(<br>            state[&quot;messages&quot;][-1]<br>        )<br>        <br>        # Generate response with intent detection enabled<br>        res = await guardrails.rails.generate_async(<br>            messages=input_messages,<br>            options=GenerationOptions(<br>                output_vars=True,<br>                log={<br>                    &quot;activated_rails&quot;: False,<br>                    &quot;llm_calls&quot;: False,<br>                    &quot;internal_events&quot;: True,  # Critical: enables intent capture<br>                    &quot;colang_history&quot;: False,<br>                },<br>                rails=[&quot;input&quot;, &quot;dialog&quot;],  # Run input validation and dialog rails<br>            ),<br>        )<br>        <br>        # Extract detected intent from internal events<br>        # UserIntent events are emitted when intent is detected<br>        intents = [<br>            event for event in res.log.internal_events <br>            if event.get(&quot;type&quot;) == &quot;UserIntent&quot;<br>        ]<br>        <br>        if intents:<br>            # Use the most recent intent if multiple are detected<br>            intent = intents[-1].get(&quot;intent&quot;)<br>            new_state[&quot;intent&quot;] = intent<br>        <br>        # Check if guardrails returned a direct response<br>        # (e.g., greeting, refusal)<br>        output = res.response[-1][&quot;content&quot;]<br>        <br>        if output:<br>            # Guardrails intercepted and provided direct response<br>            # Return it immediately without calling main LLM<br>            return {<br>                &quot;messages&quot;: [AIMessage(content=output)],<br>                &quot;intent&quot;: new_state.get(&quot;intent&quot;, state.get(&quot;intent&quot;, &quot;general&quot;))<br>            }<br>    <br>    # Get detected intent (from current processing or previous state)<br>    intent = new_state.get(&quot;intent&quot;, state.get(&quot;intent&quot;, &quot;general&quot;))<br>    <br>    # Filter tools based on intent<br>    intent_tools = get_tools_for_intent(intent, all_tools)<br>    <br>    # Bind filtered tools to base LLM<br>    llm_with_tools = base_llm.bind_tools(intent_tools)<br>    <br>    # Build system prompt with filtered tools<br>    system_prompt = build_system_prompt(intent_tools)<br>    <br>    # Create prompt chain<br>    prompt = ChatPromptTemplate.from_messages([<br>        (&quot;system&quot;, system_prompt),<br>        (&quot;placeholder&quot;, &quot;{messages}&quot;),<br>    ])<br>    <br>    chain = prompt | llm_with_tools<br>    <br>    # Generate response<br>    result = await chain.ainvoke(dict(state))<br>    <br>    return {<br>        &quot;messages&quot;: [result],<br>        &quot;intent&quot;: new_state.get(&quot;intent&quot;, state.get(&quot;intent&quot;, &quot;general&quot;))<br>    }</pre><h3>Step 5: Implement Intent-Based Tool Filtering</h3><p>Create a mapping from intents to relevant tools:</p><pre>INTENT_TOOL_MAP = {<br>    &quot;search books&quot;: [&quot;search_books&quot;, &quot;search_by_genre&quot;, &quot;search_by_author&quot;],<br>    &quot;ask about authors&quot;: [&quot;get_author_info&quot;, &quot;get_author_books&quot;, &quot;get_author_bio&quot;],<br>    &quot;check inventory&quot;: [&quot;check_book_availability&quot;, &quot;get_stock_status&quot;, &quot;check_store_location&quot;],<br>    &quot;ask about capabilities&quot;: [],  # No tools needed for capability queries<br>    &quot;express greeting&quot;: [],  # Handled by guardrails directly<br>    &quot;general&quot;: [&quot;search_knowledge_base&quot;, &quot;general_query&quot;],  # Fallback tools<br>}</pre><pre>def get_tools_for_intent(intent: str, tools: list) -&gt; list:<br>    &quot;&quot;&quot;Filter tools based on detected intent.<br>    <br>    This dramatically reduces the tool space, improving:<br>    - LLM inference speed (fewer tools to consider)<br>    - Token usage (smaller tool descriptions in context)<br>    - Accuracy (less confusion from irrelevant tools)<br>    &quot;&quot;&quot;<br>    tool_names = INTENT_TOOL_MAP.get(intent, INTENT_TOOL_MAP[&quot;general&quot;])<br>    return [tool for tool in tools if tool.name in tool_names]</pre><h3>Step 6: Build the LangGraph</h3><p>Now assemble everything into a LangGraph:</p><pre>from langgraph.graph import StateGraph, START<br>from langgraph.prebuilt import ToolNode, tools_condition<br>from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver</pre><pre>def create_intent_driven_agent(<br>    base_llm: BaseChatModel,<br>    rails_llm: BaseChatModel,<br>    tools: list,<br>    checkpointer: AsyncPostgresSaver,<br>    build_system_prompt: Callable,<br>) -&gt; StateGraph:<br>    &quot;&quot;&quot;Create a LangGraph agent with NeMo Guardrails integration.<br>    <br>    The graph structure:<br>    START -&gt; chatbot -&gt; (tools_condition) -&gt; tools -&gt; chatbot -&gt; END<br>    &quot;&quot;&quot;<br>    # Initialize guardrails (from Step 3)<br>    guardrails = initialize_guardrails(rails_llm)<br>    <br>    # Create chatbot node (from Step 4)<br>    chatbot_node = create_chatbot_node(<br>        base_llm, guardrails, tools, build_system_prompt<br>    )<br>    <br>    # Build graph<br>    graph = StateGraph(State)<br>    graph.add_node(&quot;chatbot&quot;, chatbot_node)<br>    graph.add_node(&quot;tools&quot;, ToolNode(tools=tools))<br>    <br>    # Conditional routing: check if tool calls are needed<br>    graph.add_conditional_edges(&quot;chatbot&quot;, tools_condition)<br>    <br>    # After tools execute, return to chatbot<br>    graph.add_edge(&quot;tools&quot;, &quot;chatbot&quot;)<br>    <br>    # Start at chatbot<br>    graph.add_edge(START, &quot;chatbot&quot;)<br>    <br>    # Compile with checkpointer for state persistence<br>    return graph.compile(checkpointer=checkpointer)</pre><h3>Comparison: Standard vs. Intent-Driven Integration</h3><h3>Standard LangGraph Integration</h3><pre># Standard approach: all tools always available<br>def chatbot(state: State):<br>    llm_with_tools = base_llm.bind_tools(all_tools)  # 20+ tools<br>    return {&quot;messages&quot;: [llm_with_tools.invoke(state[&quot;messages&quot;])]}</pre><pre># Issues:<br># - No input validation<br># - Large tool space (slow, expensive)<br># - No intent awareness<br># - Every query goes through full pipeline</pre><p>Performance Characteristics:</p><ul><li>Tool space: 20+ tools</li><li>Average tokens per request: ~8,000 (with tool descriptions)</li><li>Average latency: 2–3 seconds</li><li>Cost per request: $0.02–0.05 (depending on model)</li></ul><h3>Intent-Driven Integration with Guardrails</h3><pre># Intent-driven approach: tools filtered by intent<br>async def chatbot(state: State):<br>    # 1. Validate input and detect intent (fast, small model)<br>    intent = await detect_intent(state[&quot;messages&quot;][-1])<br>    <br>    # 2. Filter tools based on intent<br>    intent_tools = get_tools_for_intent(intent, all_tools)  # 2-5 tools<br>    <br>    # 3. Generate response with filtered tools<br>    llm_with_tools = base_llm.bind_tools(intent_tools)<br>    return {&quot;messages&quot;: [await llm_with_tools.ainvoke(state[&quot;messages&quot;])]}</pre><pre># Benefits:<br># - Input validation (blocks malicious queries)<br># - Small tool space (fast, cheap)<br># - Intent-aware routing<br># - Direct responses for simple queries (greetings, etc.)</pre><p>Performance Characteristics:</p><ul><li>Tool space: 2–5 tools (after filtering)</li><li>Average tokens per request: ~3,000 (60% reduction)</li><li>Average latency: 1–1.5 seconds (40% faster)</li><li>Cost per request: $0.01–0.02 (50% reduction)</li></ul><h3>Side-by-Side Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*Hwd3QJixKMk5X7ITN1P9qw.png" /></figure><h3>Advanced Patterns</h3><h3>Pattern 1: Multi-Stage Intent Refinement</h3><p>Sometimes you need to refine intent as the conversation progresses:</p><pre>async def chatbot(state: State) -&gt; State:<br>    # First, get coarse intent from guardrails<br>    coarse_intent = await detect_intent(state[&quot;messages&quot;][-1])<br>    <br>    # If conversation has context, refine intent<br>    if len(state[&quot;messages&quot;]) &gt; 2:<br>        refined_intent = await refine_intent(<br>            coarse_intent, <br>            state[&quot;messages&quot;][-3:]  # Last 3 messages<br>        )<br>        intent = refined_intent<br>    else:<br>        intent = coarse_intent<br>    <br>    # Use refined intent for tool filtering<br>    tools = get_tools_for_intent(intent, all_tools)<br>    # ... rest of processing</pre><h3>Pattern 2: Intent-Based Conditional Routing</h3><p>Use intent to route to different specialized nodes:</p><pre>def route_by_intent(state: State) -&gt; str:<br>    &quot;&quot;&quot;Route to different nodes based on intent.&quot;&quot;&quot;<br>    intent = state.get(&quot;intent&quot;, &quot;general&quot;)<br>    <br>    if intent == &quot;express greeting&quot;:<br>        return &quot;greeting_handler&quot;<br>    elif intent == &quot;search books&quot;:<br>        return &quot;book_search_handler&quot;<br>    elif intent == &quot;ask about authors&quot;:<br>        return &quot;author_query_handler&quot;<br>    elif intent == &quot;check inventory&quot;:<br>        return &quot;inventory_check_handler&quot;<br>    else:<br>        return &quot;general_handler&quot;</pre><pre># Add conditional routing<br>graph.add_conditional_edges(<br>    &quot;chatbot&quot;,<br>    route_by_intent,<br>    {<br>        &quot;greeting_handler&quot;: &quot;greeting_node&quot;,<br>        &quot;book_search_handler&quot;: &quot;book_search_node&quot;,<br>        &quot;author_query_handler&quot;: &quot;author_node&quot;,<br>        &quot;inventory_check_handler&quot;: &quot;inventory_node&quot;,<br>        &quot;general_handler&quot;: &quot;general_node&quot;,<br>    }<br>)</pre><h3>Pattern 3: Intent Persistence Across Turns</h3><p>Maintain intent context across conversation turns:</p><pre>class State(TypedDict):<br>    messages: Annotated[list, add_messages]<br>    intent: Annotated[str, &quot;general&quot;]<br>    intent_history: Annotated[list[str], []]  # Track intent over time</pre><pre>async def chatbot(state: State) -&gt; State:<br>    # Detect new intent<br>    new_intent = await detect_intent(state[&quot;messages&quot;][-1])<br>    <br>    # Update intent history<br>    intent_history = state.get(&quot;intent_history&quot;, [])<br>    intent_history.append(new_intent)<br>    <br>    # Use recent intent trend for better tool selection<br>    if len(intent_history) &gt;= 3:<br>        # If last 3 intents are similar, use that intent<br>        recent_intents = intent_history[-3:]<br>        if len(set(recent_intents)) == 1:<br>            intent = recent_intents[0]<br>        else:<br>            intent = new_intent<br>    else:<br>        intent = new_intent<br>    <br>    return {<br>        &quot;messages&quot;: [...],<br>        &quot;intent&quot;: intent,<br>        &quot;intent_history&quot;: intent_history<br>    }p</pre><h3>Pattern 4: Streaming with Intent Awareness</h3><p>Stream responses while maintaining intent context:</p><pre>async def stream_with_intent(agent, messages):<br>    &quot;&quot;&quot;Stream agent responses with intent tracking.&quot;&quot;&quot;<br>    intent_detected = False<br>    <br>    async for event in agent.astream_events(<br>        {&quot;messages&quot;: messages},<br>        version=&quot;v2&quot;<br>    ):<br>        # Capture intent from guardrails events<br>        if event[&quot;event&quot;] == &quot;on_chain_start&quot;:<br>            if event.get(&quot;name&quot;) == &quot;RunnableRails&quot;:<br>                intent_detected = True<br>        <br>        # Stream main LLM responses<br>        if event[&quot;event&quot;] == &quot;on_chat_model_stream&quot;:<br>            if &quot;main_llm&quot; in event.get(&quot;tags&quot;, []):<br>                chunk = event[&quot;data&quot;][&quot;chunk&quot;]<br>                yield chunk.content<br>        <br>        # Emit intent metadata<br>        if event[&quot;event&quot;] == &quot;on_chain_end&quot;:<br>            if intent_detected:<br>                state = event.get(&quot;data&quot;, {}).get(&quot;output&quot;, {})<br>                if &quot;intent&quot; in state:<br>                    yield f&quot;\n[Intent: {state[&#39;intent&#39;]}]&quot;</pre><h3>Best Practices and Considerations</h3><h3>1. Model Selection</h3><p>Guardrails LLM: Use a smaller, faster model and specialised models. These models are sufficient for intent detection and input validation.</p><p>Base LLM: Use your primary model for the main conversation and tool calling.</p><h3>2. Intent Definition Strategy</h3><p>Start Broad, Refine Later: Begin with high-level intents (e.g., “search_books”, “ask_about_authors”) and add specificity as needed.</p><p>Use Hierarchical Intents: Consider a two-level hierarchy:</p><ul><li>Top-level: Domain (books, authors, inventory, general)</li><li>Second-level: Action (search, query, check, purchase)</li></ul><pre># Hierarchical intent example<br>define user search books<br>  &quot;find me a book&quot;<br>  &quot;search for novels&quot;<br>  &quot;show me books&quot;</pre><pre>define user search books by genre<br>  &quot;find mystery books&quot;<br>  &quot;show me science fiction&quot;<br>  &quot;I want fantasy novels&quot;</pre><h3>3. Tool Filtering Granularity</h3><p>Balance Specificity and Coverage: Too specific (1 tool per intent) risks missing valid tool calls. Too broad (all tools) defeats the purpose.</p><p>Recommended: 2–5 tools per intent provides good balance.</p><h3>Real-World Example: Book Store AI Assistant</h3><p>Let’s see how this integration works in a book store context:</p><h3>Scenario: User asks “Find me science fiction books by Isaac Asimov”</h3><p>Step 1: Input Processing</p><pre>User: &quot;Find me science fiction books by Isaac Asimov&quot;<br>↓<br>NeMo Guardrails processes input<br>↓<br>Intent detected: &quot;search books&quot;<br>Input validated: Safe</pre><p>Step 2: Tool Filtering</p><pre>All tools: [search_books, search_by_genre, search_by_author, <br>            get_author_info, check_inventory, place_order, <br>            get_reviews, get_recommendations, ...]<br>↓<br>Intent: &quot;search books&quot;<br>↓<br>Filtered tools: [search_books, search_by_genre, search_by_author]</pre><p>Step 3: LLM Processing</p><pre>Base LLM receives:<br>- System prompt with 3 tools (instead of 15+)<br>- User message<br>- Conversation history<br>↓<br>LLM selects: search_books(genre=&quot;science fiction&quot;, author=&quot;Isaac Asimov&quot;)</pre><p>Step 4: Tool Execution</p><pre>Tool executes → Returns book catalog results<br>↓<br>LLM formats response with book titles, descriptions, and availability<br>↓<br>User receives: &quot;I found several science fiction books by Isaac Asimov:<br>              - Foundation (available)<br>              - I, Robot (available)<br>              - The End of Eternity (in stock)<br>              Would you like more details about any of these?&quot;</pre><p>Performance Impact:</p><ul><li>Tokens saved: ~4,500 (tool descriptions not in context)</li><li>Latency reduction: ~0.8 seconds (smaller context, faster inference)</li><li>Cost savings: ~50% per request</li></ul><h3>Another Scenario: User asks “Who wrote The Great Gatsby?”</h3><p>Step 1: Input Processing</p><pre>User: &quot;Who wrote The Great Gatsby?&quot;<br>↓<br>NeMo Guardrails processes input<br>↓<br>Intent detected: &quot;ask about authors&quot;<br>Input validated: Safe</pre><p>Step 2: Tool Filtering</p><pre>All tools: [search_books, search_by_genre, search_by_author, <br>            get_author_info, get_author_books, get_author_bio,<br>            check_inventory, place_order, ...]<br>↓<br>Intent: &quot;ask about authors&quot;<br>↓<br>Filtered tools: [get_author_info, get_author_books, get_author_bio]</pre><p>Step 3: LLM Processing</p><pre>Base LLM receives:<br>- System prompt with 3 author-related tools<br>- User message<br>↓<br>LLM selects: get_author_info(book_title=&quot;The Great Gatsby&quot;)</pre><p>Step 4: Tool Execution</p><pre>Tool executes → Returns: &quot;F. Scott Fitzgerald&quot;<br>↓<br>LLM formats response with additional context<br>↓<br>User receives: &quot;The Great Gatsby was written by F. Scott Fitzgerald, <br>              published in 1925. Would you like to see other books <br>              by this author?&quot;</pre><p>This demonstrates how intent-based filtering ensures the LLM only sees relevant tools, leading to faster, more accurate responses.</p><h3>Conclusion</h3><p>Integrating NeMo Guardrails with LangGraph creates a powerful, production-ready architecture that combines safety, efficiency, and intelligence. By detecting intent early and using it to filter tools and route requests, you can:</p><ul><li>Reduce costs by 50% through smaller contexts and tool filtering</li><li>Improve latency by 40% with faster inference on smaller tool sets</li><li>Enhance security with multi-layer input validation</li><li>Increase accuracy by reducing tool confusion</li><li>Enable smart routing based on user intent</li></ul><p>The key insights are:</p><ol><li>Intent is central: Make intent detection the first step in your graph</li><li>Filter aggressively: Reduce tool space based on intent for better performance</li><li>Validate early: Use guardrails to block invalid queries before expensive LLM calls</li><li>Persist context: Maintain intent across conversation turns for better continuity</li><li>Handle edge cases: Always provide fallbacks for missing or unexpected intents</li></ol><p>As AI applications grow in complexity, architectures that combine orchestration (LangGraph) with safety and intelligence (NeMo Guardrails) will become the standard. The intent-driven approach we’ve explored here provides a blueprint for building scalable, efficient, and secure AI systems.</p><p>Start with the basic integration, measure performance improvements, and iteratively refine your intent definitions and tool mappings. The investment in this architecture pays dividends in reduced costs, improved user experience, and enhanced security.</p><h3>Further Reading</h3><ul><li><a href="https://langchain-ai.github.io/langgraph/">LangGraph Documentation</a></li><li><a href="https://github.com/NVIDIA/NeMo-Guardrails">NeMo Guardrails Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52b424d861d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easily Remove Sensitive Data using AI with the PDF Redaction API]]></title>
            <link>https://mmykola.medium.com/easily-remove-sensitive-data-using-ai-with-the-pdf-redaction-api-f9345838b1e0?source=rss-1d4546062b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9345838b1e0</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[n8n]]></category>
            <dc:creator><![CDATA[Mykola Melnyk]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 05:12:25 GMT</pubDate>
            <atom:updated>2026-06-26T07:43:23.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://pdf-redaction.com/redaction-api/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_z-aZ8DRYp91lqtYtOzlQ.png" /></a></figure><p>If you work with documents, chances are you’ve had to hide sensitive information before sharing them. Maybe it’s customer details, emails, medical data, or financial info. Doing this by hand is slow, stressful, and mistakes can be costly.</p><p>That’s why we built the PDF Redaction and PDF Redaction API — a simple and secure way to automatically remove private information from PDFs.</p><p><a href="https://pdf-rdeaction.com/">https://pdf-redaction.com</a> is online tool for AI and manual redaction PDF files.</p><p><a href="https://pdf-redaction.com/redaction-api/">PDF Redaction API</a> is a way to integrate redaction to your existing tools or infrastructure.</p><h3>What is PDF Redaction?</h3><p>Redaction means hiding or removing parts of a document so they can’t be read. In a PDF, that usually means covering up names, phone numbers, addresses, or anything else that shouldn’t be shared.</p><p>Traditionally, people do this by hand with a PDF editor. But with AI, we can now automate most of the process.</p><h3>Why Use the PDF Redaction API?</h3><p>Here are a few reasons people are choosing our tool:</p><ul><li><strong>Fast and automatic -</strong> Upload a file and the API finds sensitive text for you and blackout it in PDF.</li><li><strong>Works on scanned PDFs - </strong>Built-in OCR reads text from images and scans.</li><li><strong>Supports multiple languages -</strong> English, German, Spanish, Italian, Russian, and more.</li><li><strong>Supports custom defined tags</strong>.</li><li><strong>Privacy-friendly - </strong>We do not store your files. Once they are processed, they are gone.</li><li><strong>On-premise - </strong>You can deploy API server to your private server using docker. More details about self-hosted <a href="https://pdf-redaction.com/docs/api-self-hosted/">here</a>.</li><li><strong>Easy to integrate -</strong> Just call the API from your app, website, or n8n workflow.</li></ul><h3>How It Works</h3><ol><li><strong>Upload your PDF</strong> through the API.</li><li><strong>AI scans the file</strong> for sensitive data like names, dates, or emails.</li><li><strong>Redacted PDF is returned</strong> — ready to share safely.</li></ol><p>That’s it — no complex setup, no software to install.</p><h3>API Documentation and Playground</h3><p>API documentation available here: <a href="https://pdf-redaction.com/docs/api/">https://pdf-redaction.com/docs/api/</a></p><p>You can in easy way try api in playground:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzXLGsElw5AWHB09g7F_tg.png" /></figure><p>Available parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jatv-_FLoOiEUN4p08ArA.png" /></figure><h3>Swagger UI</h3><p>Available <a href="https://api.pdf-redaction.com/api/docs">here</a>.</p><figure><a href="https://api.pdf-redaction.com/api/docs"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6psd4piww0N9Kg5fosfKcw.png" /></a></figure><h3>Examples</h3><p>Here few Jupyter Notebooks with full examples. You can simply open and run it on Google Colab:</p><ul><li><a href="https://colab.research.google.com/github/StabRise/pdf-redaction-api/blob/main/jupyter/PDF-Redaction-API.ipynb">PDF Redaction API</a></li><li><a href="https://colab.research.google.com/github/StabRise/pdf-redaction-api/blob/main/jupyter/PDF-Redaction-API-base64.ipynb">PDF Redaction API base64</a></li><li><a href="https://colab.research.google.com/github/StabRise/pdf-redaction-api/blob/main/jupyter/PDF-Redaction-API-base64-prompt.ipynb">PDF Redaction API using prompt</a></li></ul><p>Here is example of the output page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M0in7DCgQ0F1qWZYRSC-QA.png" /></figure><p>And example of detected PII in json format:</p><pre>{<br>    &quot;entities&quot;: [<br>        {<br>            &quot;entity_group&quot;: &quot;PERSON_NAME&quot;,<br>            &quot;score&quot;: 0.0,<br>            &quot;word&quot;: &quot;Johnathan Smith&quot;,<br>            &quot;start&quot;: 0,<br>            &quot;end&quot;: 0,<br>            &quot;boxes&quot;: [<br>                {<br>                    &quot;text&quot;: &quot;Johnathan&quot;,<br>                    &quot;score&quot;: 1.0,<br>                    &quot;x&quot;: 1402,<br>                    &quot;y&quot;: 838,<br>                    &quot;width&quot;: 213,<br>                    &quot;height&quot;: 51<br>                },<br>                {<br>                    &quot;text&quot;: &quot;Smith&quot;,<br>                    &quot;score&quot;: 1.0,<br>                    &quot;x&quot;: 1628,<br>                    &quot;y&quot;: 838,<br>                    &quot;width&quot;: 117,<br>                    &quot;height&quot;: 51<br>                }<br>            ]<br>        },</pre><h3>Try It Free</h3><p>We offer a <strong>free plan</strong> so you can test the API right away. If you need to process more documents, we have paid plans.</p><p>👉 Check it out here: <a href="https://pdf-redaction.com/redaction-api/">PDF Redaction API</a></p><h3>Links</h3><ul><li><a href="https://pdf-redaction.com/redaction-api/">https://pdf-redaction.com/redaction-api/</a></li><li><a href="https://github.com/StabRise/pdf-redaction-api/">https://github.com/StabRise/pdf-redaction-api/</a></li><li>Docker Image: <a href="https://hub.docker.com/r/stabrise/pdf-redaction-api">https://hub.docker.com/r/stabrise/pdf-redaction-api</a></li><li><a href="https://colab.research.google.com/github/StabRise/pdf-redaction-api/blob/main/jupyter/PDF-Redaction-API.ipynb">PDF Redaction API</a> - Example Nonebook on Google Colab</li><li><a href="https://colab.research.google.com/github/StabRise/pdf-redaction-api/blob/main/jupyter/PDF-Redaction-API-base64.ipynb">PDF Redaction API base64</a></li><li><a href="https://colab.research.google.com/github/StabRise/pdf-redaction-api/blob/main/jupyter/PDF-Redaction-API-base64-prompt.ipynb">PDF Redaction API using prompt</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9345838b1e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Powered PDF Redaction, With Full Manual Control for FREE]]></title>
            <link>https://mmykola.medium.com/ai-powered-pdf-redaction-with-full-manual-control-for-free-7c79a6a31a04?source=rss-1d4546062b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c79a6a31a04</guid>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[ai-tools-for-business]]></category>
            <dc:creator><![CDATA[Mykola Melnyk]]></dc:creator>
            <pubDate>Sun, 18 May 2025 17:32:19 GMT</pubDate>
            <atom:updated>2026-08-24T19:40:47.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://pdf-redaction.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jtZWcFduKViEk_d1" /></a><figcaption>PDF Redaction Online Tool</figcaption></figure><p>We built a <a href="https://pdf-redaction.com/">web-based pdf redaction tool</a> that lets you upload a PDF, automatically detect personal data using AI, tweak what you want, and export a clean, redacted version. It works in your browser. No installation needed.</p><p>You can redact <strong>unlimited</strong> number of the documents for <strong>Free. </strong>Only one limitation 25 pages per document.</p><h3>Designed for focus</h3><p>The UI is minimal. Drag in a PDF, and AI highlights personal data — names, emails, addresses, phone numbers.</p><p>You stay in control:<br> ✔ Review AI suggestions<br> ✔ Edit, move, or delete boxes<br> ✔ Draw your own redactions<br> ✔ Search and redact specific text<br> ✔ Fill free to choose redaction color: could be white or black</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiv5SjVnXHhb68ApO-iqsw.png" /></figure><h3>Real redaction, not black rectangles</h3><p>Some tools just draw over text. The data is still there underneath.</p><p>We rebuild the PDF after redaction. The sensitive content is actually gone — not covered up.<br>The result: a clean, shareable document with zero trace.</p><h3>Manual when you need it</h3><p>AI handles the first pass. But you can still:</p><ul><li>Search for exact text</li><li>Select specific areas</li><li>Adjust redaction with precision</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wfhYhkHxv0-Awzmmv4cJg.png" /></figure><h3>Works now. Scales later.</h3><p>Right now, this is a fast, browser-based tool for individual docs. But it’s built on a foundation that can scale.</p><p>PDF Redaction can be easily integrated into larger workflows — and scaled with <strong>Apache Spark</strong> or <strong>Databricks</strong> to process thousands of documents in enterprise pipelines.</p><h3>Started as an demo project</h3><p>This tool began as a demo for our open-source projects, <a href="https://stabrise.com/spark-pdf/">spark-pdf</a> and <a href="https://stabrise.com/scaledp/">scaleDP</a>.<br>We planned to make something which demonstrates the possibilities of these projects. Then we created UI — something intuitive and fast. And now we have several products: <br>- <a href="https://pdf-redaction.com/redact-pdf/">PDF Redaction Online </a>— instant access from any browser<br>- <a href="https://pdf-redaction.com/docs/studio-desktop/">PDF Redaction Studio Desktop</a> — native applications for Linux nad Windows. <a href="http://apps.microsoft.com/detail/9p9g1wdm89qw">PDF Redaction Studio</a> is available for download on Microsoft App store.<br>- <a href="https://pdf-redaction.com/docs/studio/">PDF Redaction Studio On-Premise </a>— complete data control, install on your own server using docker, full customization.<br>- <a href="https://pdf-redaction.com/redaction-api/">PDF Redaction API</a> — for integrate redaction to your existing infrastructure (Cloud and On-Premise).<br>- PDF Redaction SDK- for full controll and process in scale.</p><p>All our products has rich free limits Cloud and On-Premise.</p><h3>Redact for free</h3><p><a href="https://pdf-redaction.com/">Upload a PDF.</a> Watch AI redact it in seconds. You can edit anything before export. Just few clicks and you got redacted pdf. You can redact unlimited number of the documents for free (limit 25 pages per document).</p><figure><a href="https://pdf-redaction.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rwlq2om7LxxbkmyN" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c79a6a31a04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DICOM de-identification at scale in Visual NLP-Part 3]]></title>
            <link>https://mmykola.medium.com/dicom-de-identification-at-scale-in-visual-nlp-part-3-ac750be386cb?source=rss-1d4546062b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac750be386cb</guid>
            <category><![CDATA[spark-nlp]]></category>
            <category><![CDATA[de-identification]]></category>
            <category><![CDATA[dicom]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Mykola Melnyk]]></dc:creator>
            <pubDate>Fri, 29 Sep 2023 09:56:06 GMT</pubDate>
            <atom:updated>2024-10-29T15:52:49.277Z</atom:updated>
            <content:encoded><![CDATA[<h3>DICOM de-identification at scale in Visual NLP — Part 3.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dp_Bu-wVhNuY6CF0oFLFTw.png" /></figure><p>This post will delve into the utilization of <strong>Visual NLP</strong> to manipulate <strong>pixel</strong> and <strong>overlay data</strong> within DICOM images.</p><p>In the following examples, we will work with these two transformers: <strong>DicomToImageV3</strong>, which is responsible for extracting frame images, and <strong>DicomDrawRegions</strong>, which draws rectangle regions on top of Dicom frames and proves useful in building de-identification pipelines.</p><h4>DicomToImageV3</h4><p><strong>DicomToImageV3</strong> will extract images from the <strong>pixel</strong> and <strong>overlay data</strong> in the Dicom file, and will return them in a Spark DataFrame following Visual NLP’s <strong>Image</strong> structure.</p><p>Image representation on the dataframe can take multiple forms in Visual NLP. Typically, it’s either a grayscale or RGB image in uncompressed format.</p><p>On the other hand, DICOM files come with a vast variety of color spaces(or photometric interpretations), compression techniques, and many other metadata elements that help specify how the binary data contained in the file should be interpreted. Each combination of these settings, is called a Transfer Syntax, according to the DICOM standard.</p><p>Back to the color spaces, these are some typical input values you can expect to deal with in DicomToImageV3, MONOCHROME2, RGB, YBR, YBR FULL, YBR FULL 422, PALETTE COLOR. After this point, everything will happen automatically in the subsequent stages in the pipeline, so there’s not that much you have to worry about.</p><p>Now, let’s extract frames from one of the test DICOM files:</p><pre>dicom_to_image = DicomToImageV3() \<br>    .setInputCols([&quot;content&quot;]) \<br>    .setOutputCol(&quot;image&quot;) \<br>    .setKeepInput(False)<br><br>result = dicom_to_image.transform(dicom_df)<br><br>results.show()</pre><pre>+--------------------+---------+-------+--------------------+-------------------+------+<br>|               image|exception|pagenum|                path|   modificationTime|length|<br>+--------------------+---------+-------+--------------------+-------------------+------+<br>|{file:/Users/nmel...|         |      0|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>|{file:/Users/nmel...|         |      1|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>|{file:/Users/nmel...|         |      2|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>|{file:/Users/nmel...|         |      3|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>|{file:/Users/nmel...|         |      4|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>|{file:/Users/nmel...|         |      5|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>|{file:/Users/nmel...|         |      6|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>|{file:/Users/nmel...|         |      7|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>|{file:/Users/nmel...|         |      8|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>|{file:/Users/nmel...|         |      9|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>|{file:/Users/nmel...|         |     10|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>+--------------------+---------+-------+--------------------+-------------------+------+</pre><p>There will be a separate row with an image for each DICOM frame. Then, the <strong><em>pagenum</em></strong> column will contain the number of the frame. Let’s display frames as images using <strong><em>display_images</em></strong> function:</p><pre>display_images(result, limit=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*t_0dNmh9Mn8QNapJHaCZyA.png" /></figure><p><strong>DicomToImageV3</strong> supports up to 1000 frames or more, depending on the size of the frames and the available memory. When working with a large number of frames during debugging of the pipeline, it is useful to extract only a limited number of frames. To do this, you can set the <strong><em>frameLimit</em></strong> parameter:</p><pre>dicom_to_image = DicomToImageV3() \<br>    .setInputCols([&quot;content&quot;]) \<br>    .setOutputCol(&quot;image&quot;) \<br>    .setFrameLimit(1) \<br>    .setKeepInput(False)<br><br>result = dicom_to_image.transform(dicom_df)<br><br>result.show()</pre><pre>+--------------------+---------+-------+--------------------+-------------------+------+<br>|               image|exception|pagenum|                path|   modificationTime|length|<br>+--------------------+---------+-------+--------------------+-------------------+------+<br>|{file:/Users/nmel...|         |      0|file:/Users/nmeln...|2023-08-20 14:17:23|426776|<br>+--------------------+---------+-------+--------------------+-------------------+------+</pre><p>For handling big files (2 GB or more) we need to use the <strong>path</strong> column as input instead of<strong> </strong>the content column. This forces to load files directly from the file system instead of passing through the DataFrame.</p><pre>dicom_to_image = DicomToImageV3() \<br>  .setInputCols([“path”]) \<br>  .setOutputCol(“image”) \<br>  .setKeepInput(False)</pre><h4>DicomDrawRegions</h4><p><strong>DicomDrawRegions</strong> is draw regions to the frames on DICOM. It updates both <strong>pixel </strong>and <strong>overlay data.</strong></p><p>It support same <strong>PhotometricInterpretations </strong>as<strong> DicomToImageV3.</strong></p><p>Let’s do simplest de-identification, detect text on the image and hide it. We already can extract frame images using <strong>DicomToImageV3</strong>. Need set <strong><em>keepInput</em></strong> to <strong>True </strong>for able to compare results with original images<strong>.</strong></p><pre>dicom_to_image = DicomToImageV3() \<br>    .setInputCols([&quot;content&quot;]) \<br>    .setOutputCol(&quot;image&quot;) \<br>    .setKeepInput(True)</pre><p>Next we need to detect text. We can use <strong>ImageTextDetectorV2 </strong>here<strong>:</strong></p><pre>text_detector = ImageTextDetectorV2 \<br>    .pretrained(&quot;image_text_detector_v2&quot;, &quot;en&quot;, &quot;clinical/ocr&quot;) \<br>    .setInputCol(&quot;image&quot;) \<br>    .setOutputCol(&quot;regions&quot;) \<br>    .setScoreThreshold(0.5) \<br>    .setTextThreshold(0.2) \<br>    .setSizeThreshold(10)</pre><p>And as final step we draw filled rectangles using <strong>DicomDrawRegions:</strong></p><pre>draw_regions = DicomDrawRegions() \<br>    .setInputCol(&quot;path&quot;) \<br>    .setInputRegionsCol(&quot;regions&quot;) \<br>    .setOutputCol(&quot;dicom_cleaned&quot;) \<br>    .setRotated(True) \<br>    .setKeepInput(True)</pre><p>For run this we will define Spark ML Pipeline and call it:</p><pre>pipeline = PipelineModel(stages=[<br>     dicom_to_image,<br>     text_detector,<br>     draw_regions<br>])<br><br>result = pipeline.transform(dicom_df)<br><br>result.show()</pre><pre>+--------------------+----------+--------------------+--------------------+<br>|       dicom_cleaned| exception|                path|             content|<br>+--------------------+----------+--------------------+--------------------+<br>|[52 75 62 6F 20 4...|          |file:/Users/nmeln...|[52 75 62 6F 20 4...|<br>+--------------------+----------+--------------------+--------------------+</pre><p>Let’s display original and cleaned DICOMS using <strong><em>display_dicom </em></strong>function:</p><pre>display_dicom(result, &quot;content,dicom_cleaned&quot;, show_meta=False, limit_frame=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qsuwfUntt4YsGGODXEtVg.png" /></figure><p>Additionally, <strong>DicomDrawRegions</strong> also supports the following <em>compressions</em>:</p><ul><li><strong>RLELossless</strong>: RLELossless is a compression method used in DICOM for medical image storage. It operates based on Run-Length Encoding Lossless, encoding consecutive runs of identical pixel values as a count followed by the pixel value itself. This method is employed for lossless compression, ensuring that the original medical image can be perfectly reconstructed from the compressed data without any loss of quality.</li><li><strong>JPEGBaseline8Bit</strong>: JPEGBaseline8Bit is a specific variant of JPEG (Joint Photographic Experts Group) compression. It adheres to baseline compression with 8 bits per color channel, typically resulting in a 24-bit color depth for RGB medical images. This compression method is inherently lossy, reducing file size by discarding some image data while aiming to maintain diagnostic image quality.</li><li><strong>JPEGLSLossless</strong>: JPEGLSLossless is a DICOM compression method that represents a lossless image compression standard based on the JPEG-LS (Lossless JPEG) standard. In DICOM, it is used to ensure that medical images are stored and transmitted without any loss of quality. It achieves this by employing predictive coding, context modeling, and entropy coding techniques, making it suitable for medical imaging applications where preserving diagnostic image quality is paramount.</li></ul><p>We can choose compression by setting the <strong>compression</strong> parameter and force compression of <strong>pixel data</strong> for files without compression by setting the <strong>forceCompress</strong> parameter to <strong>True</strong>:</p><pre>draw_regions = DicomDrawRegions() \<br>    .setInputCol(&quot;content&quot;) \<br>    .setInputRegionsCol(&quot;regions&quot;) \<br>    .setOutputCol(&quot;dicom_cleaned&quot;) \<br>    .setRotated(True) \<br>    .setCompression(DicomCompression.RLELossless) \<br>    .setForceCompress(True)</pre><p>The last stage in our today’s post is storing the results back to the file. To retrieve the name of the original file from the <strong>path</strong> column, let’s define a UDF function:</p><pre>def get_name(path, keep_subfolder_level=0):<br>    path = path.split(&quot;/&quot;)<br>    path[-1] = path[-1].split(&#39;.&#39;)[0]<br>    return &quot;/&quot;.join(path[-keep_subfolder_level-1:])</pre><p>To save the DataFrame with the cleaned DICOM files using the <strong><em>binaryFormat</em></strong> datasource to the <strong><em>output_path</em></strong>, we need to specify a few options:</p><ol><li><strong>‘type’</strong> of the file.</li><li>The ‘<strong>field’</strong> that contains the DICOM file.</li><li>A ‘<strong>prefix’</strong> for the files.</li><li>The ‘<strong>nameField</strong>’ column, which contains the name of the file.”</li></ol><pre>output_path = &quot;./deidentified/&quot;<br>from pyspark.sql.functions import *<br><br><br>result.withColumn(&quot;fileName&quot;, udf(get_name, StringType())(col(&quot;path&quot;))) \<br>    .write \<br>    .format(&quot;binaryFormat&quot;) \<br>    .option(&quot;type&quot;, &quot;dicom&quot;) \<br>    .option(&quot;field&quot;, &quot;dicom_cleaned&quot;) \<br>    .option(&quot;prefix&quot;, &quot;ocr_&quot;) \<br>    .option(&quot;nameField&quot;, &quot;fileName&quot;) \<br>    .mode(&quot;overwrite&quot;) \<br>    .save(output_path)</pre><p><strong>Jupyter</strong> notebook with full code you can found <a href="https://github.com/JohnSnowLabs/spark-ocr-workshop/blob/master/jupyter/Dicom/SparkOcrDicomRemoveText.ipynb">here</a>.</p><p>In this post, we have constructed the simplest de-identification pipeline to conceal all text in DICOM images. In the next post, we will create a more complex pipeline using <strong>NER</strong> de-identification models with <strong>Spark NLP </strong>and<strong> Spark NLP for Healthcare</strong>.</p><h4>Links</h4><ul><li><a href="https://github.com/JohnSnowLabs/spark-ocr-workshop">Visual NLP Workshop</a></li><li><a href="https://nlp.johnsnowlabs.com/docs/en/ocr">Visual NLP Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac750be386cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DICOM de-identification at scale in Visual NLP-Part 2]]></title>
            <link>https://medium.com/john-snow-labs/dicom-de-identification-at-scale-in-visual-nlp-part-2-361af5e36412?source=rss-1d4546062b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/361af5e36412</guid>
            <category><![CDATA[spark-nlp]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[dicom]]></category>
            <category><![CDATA[de-identification]]></category>
            <dc:creator><![CDATA[Mykola Melnyk]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 08:51:54 GMT</pubDate>
            <atom:updated>2025-09-01T13:28:00.950Z</atom:updated>
            <content:encoded><![CDATA[<h3>DICOM de-identification at scale in Visual NLP — Part 2.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dp_Bu-wVhNuY6CF0oFLFTw.png" /></figure><h3>Start to work with DICOM in Visual NLP</h3><p>In this post, we are taking a deep dive into working with metadata using <a href="https://www.johnsnowlabs.com/visual-nlp/">Visual NLP</a>.</p><p>We are going to make use of Visual NLP pipelines. Visual NLP pipelines are Spark ML pipelines. Each stage(a.k.a ‘transformer’) in the pipeline is in charge of a specific task, we will make use of these two Visual NLP transformers in the following example,</p><ul><li><strong>DicomToMetadata</strong> this transformer will extract metadata from the DICOM document.</li><li><strong>DicomMetadataDeidentifier</strong> this transformer will de-indentify the metadata.</li></ul><p>To get started, you need to read DICOM files into the a dataframe using the binaryFile data source of Spark:</p><pre>dicom_df = spark.read.format(&quot;binaryFile&quot;).load(dicom_path)<br>dicom_df.show()</pre><pre>+--------------------+-------------------+-------+--------------------+<br>|                path|   modificationTime| length|             content|<br>+--------------------+-------------------+-------+--------------------+<br>|file:/Users/nmeln...|2023-08-20 14:17:23|1049988|[52 75 62 6F 20 4...|<br>|file:/Users/nmeln...|2023-08-20 14:17:23| 651696|[00 00 00 00 00 0...|<br>|file:/Users/nmeln...|2023-08-20 14:17:23| 640574|[00 00 00 00 00 0...|<br>|file:/Users/nmeln...|2023-08-20 14:17:23| 426776|[52 75 62 6F 20 4...|<br>+--------------------+-------------------+-------+--------------------+</pre><p>First thing we can check are the number of files and their size. Dicom documents can have sizes ranging from a couple of kilobytes up to a few gigabytes.</p><pre>dicom_df.select(f.col(“length”) / 2**20).summary().show()</pre><pre>+-------+-------------------+<br>|summary| (length / 1000000)|<br>+-------+-------------------+<br>|  count|                  3|<br>|   mean| 0.7057793333333332|<br>| stddev|0.31668138697645826|<br>|    min|           0.426776|<br>|    25%|           0.426776|<br>|    50%|           0.640574|<br>|    75%|           1.049988|<br>|    max|           1.049988|<br>+-------+-------------------+</pre><p>For displaying DICOM files we will use the <strong><em>display_dicom() </em>function<em>. </em></strong>We will limit the number of files and the number of frames, and for the case of files with a massive number of frames, this will enable us to show metadata,</p><pre>display_dicom(dicom_df, &quot;content&quot;, limit=1, show_meta=True, limit_frame=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*tTwWjQtiLAKJARjCpue6Dg.png" /></figure><h4>DicomToMetadata</h4><p>The DicomToMetadata transformer will help extracting metadata, returning results as a dataframe column in JSON format. Let’s take a look!,</p><pre>dicom = DicomToMetadata() \<br>   .setInputCol(“content”) \<br>   .setOutputCol(“metadata”)<br><br>result = dicom.transform(dicom_df)<br>result.show()</pre><pre>+--------------------+-------------------+-------+--------------------+<br>|                path|   modificationTime| length|            metadata|<br>+--------------------+-------------------+-------+--------------------+<br>|file:/Users/nmeln...|2023-08-20 14:17:23|1049988|{\n    &quot;SpecificC...|<br>|file:/Users/nmeln...|2023-08-20 14:17:23| 651696|{\n    &quot;ImageType...|<br>|file:/Users/nmeln...|2023-08-20 14:17:23| 640574|{\n    &quot;StudyDate...|<br>|file:/Users/nmeln...|2023-08-20 14:17:23| 426776|{\n    &quot;GroupLeng...|<br>+--------------------+-------------------+-------+--------------------+</pre><p>Let’s read these results as JSON using spark capabilities, and let’s use pandas to prettify results,</p><pre># Import the necessary functions<br>from pyspark.sql.functions import from_json<br><br># Get the schema of the &#39;metadata&#39; column (present as a string with JSON in the<br># result DataFrame)<br>json_schema = spark.read.json(result.rdd.map(lambda row: row.metadata)).schema<br><br># Convert the &#39;metadata&#39; column to a struct using the &#39;from_json&#39; function<br>metadata = result.select(from_json(&#39;metadata&#39;, json_schema).alias(&quot;metadata&quot;))<br><br># Select all subfields and convert them to a Pandas DataFrame, then transpose it<br>metadata.select(&quot;metadata.*&quot;).toPandas().T</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMb2nBZTYXFD9hVh0Z064Q.png" /></figure><h4>Estimating Dataset Size</h4><p>As we have seen in previous plot, there are many different metadata fields containing all sorts of information. In order for us to understand the real size of the dataset we have, we need to check statistics related to the number of frames on each file,</p><pre>metadata.select(f.col(“metadata.NumberofFrames”).alias(“NumberOfFrames”).cast(“int”)) \<br>  .na.fill(1).summary()</pre><pre>+-------+--------------+<br>|summary|NumberOfFrames|<br>+-------+--------------+<br>|  count|             4|<br>|   mean|           3.5|<br>| stddev|           5.0|<br>|    min|             1|<br>|    25%|             1|<br>|    50%|             1|<br>|    75%|             1|<br>|    max|            11|<br>+-------+--------------+</pre><p>So we see that although we have 4 files, the number of frames can go as high as 11 in our files. For a better proxy of processing time requirements, we can go ahead and compute the total number of frames using aggregation:</p><pre>metadata.select(f.col(“metadata.NumberofFrames”).alias(“NumberOfFrames”).cast(“int”).alias(“frames”)) \<br> .fillna(1) \<br> .groupBy() \<br> .sum()</pre><p>Output: 13</p><p>This is a very useful number that can guide us to size our infrastructure in the best possible way. And if you paid close attention, you probably noticed that we computed this number out of metadata only, without incurring the memory costs of processing the files entirely.</p><p>Another useful characteristic that we can use to estimate processing time together with the number of frames is the resolution of images. So let’s extract the pixel width of each frame, and calculate statistics,</p><pre>metadata.select(f.col(“metadata.Rows”).alias(“width”).cast(“int”)).summary()</pre><pre>+-------+-----------------+<br>|summary|            width|<br>+-------+-----------------+<br>|  count|                4|<br>|   mean|            657.5|<br>| stddev|308.5595566499278|<br>|    min|              376|<br>|    25%|              376|<br>|    50%|              430|<br>|    75%|              800|<br>|    max|             1024|<br>+-------+-----------------+</pre><p>We can do something similar with Columns to obtain the height of the image.</p><p><strong>Note: </strong>sometimes the orientation of the images can be different, and in that situation we may use Rows to compute height, and Columns to compute width, for the purposes of estimating computational workload this is irrelevant.</p><p>Once we get figures for average width and height we can get use that to estimate memory requirements.</p><h4>Other Examples</h4><p>We can group and aggregate by any metadata tag, for instance, let’s take <strong><em>PhotometricInterpretation:</em></strong></p><pre>metadata.select(f.col(“metadata.PhotometricInterpretation”)) \<br> .groupBy(“PhotometricInterpretation”) \<br> .count()</pre><pre>+-------------------------+-----+<br>|PhotometricInterpretation|count|<br>+-------------------------+-----+<br>|              MONOCHROME2|    3|<br>|            PALETTE COLOR|    1|<br>+-------------------------+-----+</pre><p>All these statistics of the dataset give us the possibility to understand the dataset, and to calculate how many resources we need to have to process it.</p><p>To get the whole picture, please check this <a href="https://github.com/JohnSnowLabs/spark-ocr-workshop/blob/master/jupyter/Dicom/SparkOcrDicomMetadata.ipynb">Jupyter Notebook</a>, in which you can access the full code.</p><h4><strong>DicomMetadataDeidentifier</strong></h4><p>DicomMetadataDeidentifier helps to de-identify metadata of DICOM files in Visual NLP. It cleaned tags which can contains PHI.</p><pre>dicom_deidentifier = DicomMetadataDeidentifier() \<br>  .setInputCols([“content”]) \<br>  .setOutputCol(“dicom_cleaned”)<br><br>result = dicom_deidentifier.transform(dicom_df)<br><br>result.show()</pre><pre>+--------------------+---------+--------------------+-------------------+-------+<br>|       dicom_cleaned|exception|                path|   modificationTime| length|<br>+--------------------+---------+--------------------+-------------------+-------+<br>|[52 75 62 6F 20 4...|         |file:/Users/nmeln...|2023-08-20 14:17:23|1049988|<br>|[00 00 00 00 00 0...|         |file:/Users/nmeln...|2023-08-20 14:17:23| 651696|<br>|[00 00 00 00 00 0...|         |file:/Users/nmeln...|2023-08-20 14:17:23| 640574|<br>|[52 75 62 6F 20 4...|         |file:/Users/nmeln...|2023-08-20 14:17:23| 426776|<br>+--------------------+---------+--------------------+-------------------+-------+</pre><p>To allow us to compare the original metadata against the cleaned metadata, let’s set the <strong><em>keepInput </em></strong>parameter to True in the DicomMetadataDeidentifier, and display results using <strong><em>display_dicom():</em></strong></p><pre>dicom_deidentifier = DicomMetadataDeidentifier() \<br> .setInputCols([“content”]) \<br> .setOutputCol(“dicom_cleaned”) \<br> .setKeepInput(True)<br><br>result = dicom_deidentifier.transform(dicom_df)<br><br>display_dicom(result, &quot;content,dicom_cleaned&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cf5RGhbvZgDOdiC_ZPc3tQ.png" /></figure><p>This is all for today! You can now jump to the <a href="https://medium.com/@albertoandreotti/dicom-de-identification-at-scale-in-visual-nlp-part-3-61cecc3adb56">next post</a> of this series in which we will work with pixel data.</p><h4>Links</h4><ul><li><a href="https://github.com/JohnSnowLabs/spark-ocr-workshop">Visual NLP Workshop</a></li><li><a href="https://nlp.johnsnowlabs.com/docs/en/ocr">Visual NLP Documentation</a></li><li><a href="https://medium.com/john-snow-labs/dicom-de-identification-at-scale-in-visual-nlp-part-3-61cecc3adb56">Part 3</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=361af5e36412" width="1" height="1" alt=""><hr><p><a href="https://medium.com/john-snow-labs/dicom-de-identification-at-scale-in-visual-nlp-part-2-361af5e36412">DICOM de-identification at scale in Visual NLP-Part 2</a> was originally published in <a href="https://medium.com/john-snow-labs">John Snow Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>