From d4dcbd54bf4d91f4512add36589ae72cfa01be8d Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Mon, 9 Nov 2026 00:23:34 +0100 Subject: tools: redact, PII detection over words Co-Authored-By: Claude Opus 5.5 --- examples/tools/redact.py | 101 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100755 examples/tools/redact.py (limited to 'examples') diff --git a/examples/tools/redact.py b/examples/tools/redact.py new file mode 100755 index 0000000..3e14bd8 --- /dev/null +++ b/examples/tools/redact.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +# desktop-assistant tool: black out personal data in a PDF or image. +# Copyright (C) 2026 Danilo M. +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +"""redact.py PATH [ITEMS]: writes PATH's copy with personal data blacked +out as -redacted. beside it, and opens it in REDACT_VIEWER +(default xdg-open). ITEMS is extra strings, one per line. Emails, phones, +IBANs, codici fiscali and card numbers are always found. A PDF comes out +as page images only: no text layer, nothing under the boxes. --test runs +the self-check. +""" + +import os +import re +import sys + + +def iban_ok(s): + s = s.replace(" ", "") + n = int("".join(str(int(c, 36)) for c in s[4:] + s[:4])) + return n % 97 == 1 + + +def luhn_ok(s): + d = [int(c) for c in s if c.isdigit()][::-1] + return sum(x if i % 2 == 0 else (x * 2 - 9 if x > 4 else x * 2) + for i, x in enumerate(d)) % 10 == 0 + + +RULES = [ + ("email", re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+"), None), + ("iban", re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,3})?\b"), iban_ok), + ("codice fiscale", re.compile(r"\b[A-Z]{6}[0-9LMNPQRSTUV]{2}[ABCDEHLMPRST]" + r"[0-9LMNPQRSTUV]{2}[A-Z][0-9LMNPQRSTUV]{3}[A-Z]\b"), None), + ("card", re.compile(r"(? a) + counts[kind] = counts.get(kind, 0) + 1 + + for kind, rx, ok in RULES: + for m in rx.finditer(text): + if ok is None or ok(m.group()): + mark(kind, *m.span()) + for it in items: + # Whole words only, any spacing: a name split over two words or lines. + rx = re.compile(r"(?