#!/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 functools import html import os import re import shutil import subprocess import sys import tempfile import zlib def iban_ok(s): s = s.replace(" ", "").upper() 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", re.I), iban_ok), # Any 16-character code mixing letters and digits, not the strict # codice fiscale layout: OCR read a scanned "80" as "E0" and the strict # pattern let it through. Other 16-character codes go too (safe side). ("codice fiscale", re.compile(r"\b[A-Z0-9]{16}\b", re.I), lambda s: sum(c.isdigit() for c in s) >= 3 and sum(c.isalpha() for c in s) >= 3), ("card", re.compile(r"(? a} if dedupe and new <= hits: # already covered by an earlier rule return hits.update(new) counts[kind] = counts.get(kind, 0) + 1 for kind, rx, ok in RULES: for m in rx.finditer(text): span = m.span() if ok is None or ok(m.group()) else sub_span(m, rx, ok) if span: mark(kind, *span) for it in items: orig, it = it, it.replace("\u2019", "'") # Whole words only, any spacing: a name split over two words or lines. rx = re.compile(r"(?|([^<]*)', run(["pdftotext", "-cropbox", "-bbox", path, "-"]).decode(errors="replace")): if m[1]: pages.append((float(m[1]), float(m[2]), [])) else: pages[-1][2].append((html.unescape(m[7]), tuple(map(float, m.group(3, 4, 5, 6))))) return pages @functools.cache def check_langs(): if not {"ita", "eng"} <= set(run(["tesseract", "--list-langs"]).decode().split()): sys.exit("tesseract has no ita and eng language data: images and scanned pages cannot be read") def ocr_words(png): check_langs() words = [] for line in run(["tesseract", png, "-", "-l", "ita+eng", "tsv"]).decode().splitlines()[1:]: f = line.split("\t") if len(f) == 12 and f[0] == "5" and f[11].strip(): x, y, w, h = map(int, f[6:10]) words.append((f[11], (x, y, x + w, y + h))) return words def render_pdf(path, tmp): """[(png, width pt, height pt, [(text, box px)])] per page.""" pages = [] for n, (w, h, words) in enumerate(pdf_words(path), 1): dpi = min(DPI, PAGE_PX * 72 / max(w, h)) base = os.path.join(tmp, f"p{n}") run(["pdftoppm", "-f", str(n), "-l", str(n), "-r", f"{dpi:.2f}", "-png", "-singlefile", "-cropbox", path, base]) k = dpi / 72 # Size from the render: /Rotate swaps it, pdftotext's w/h do not. pw, ph = map(int, run(["magick", "identify", "-format", "%w %h", base + ".png"]).split()) w, h = pw / k, ph / k if words: words = [(t, tuple(v * k for v in b)) for t, b in words] # A scan pasted into a text page has no text layer: OCR the render # too, keeping only words that sit on no text-layer word. if len(run(["pdfimages", "-list", "-f", str(n), "-l", str(n), path]).splitlines()) > 2: words += [(t, b) for t, b in ocr_words(base + ".png") if not any(x0 <= (b[0] + b[2]) / 2 <= x1 and y0 <= (b[1] + b[3]) / 2 <= y1 for _, (x0, y0, x1, y1) in words)] else: words = ocr_words(base + ".png") pages.append((base + ".png", w, h, words)) return pages def draw(src, boxes, dst): # -strip: an image's EXIF (GPS, owner) is personal data too. argv = ["magick", src, "-strip", "-fill", "black"] for x0, y0, x1, y1 in boxes: argv += ["-draw", f"rectangle {x0 - PAD:.0f},{y0 - PAD:.0f} {x1 + PAD:.0f},{y1 + PAD:.0f}"] run(argv + [dst]) def pdf_file(path, objs): # objs: object bodies, numbered from 1; object 1 is the catalog. out, offsets = b"%PDF-1.4\n", [] for k, o in enumerate(objs, 1): offsets.append(len(out)) out += f"{k} 0 obj\n".encode() + o + b"\nendobj\n" xref = len(out) out += (f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode() + b"".join(f"{o:010d} 00000 n \n".encode() for o in offsets) + f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\n" f"startxref\n{xref}\n%%EOF\n".encode()) with open(path, "wb") as f: f.write(out) def stream(head, data): return f"<< {head} /Length {len(data)} >>\nstream\n".encode() + data + b"\nendstream" def write_pdf(pages, dst): # ImageMagick's policy forbids writing PDF: one lossless RGB image per # page, at the original page size. No text, no metadata. objs, kids = [b"<< /Type /Catalog /Pages 2 0 R >>", b""], [] for png, w, h in pages: pw, ph = map(int, run(["magick", "identify", "-format", "%w %h", png]).split()) rgb = run(["magick", png, "-background", "white", "-alpha", "remove", "-depth", "8", "rgb:-"]) n = len(objs) + 1 kids.append(f"{n} 0 R") objs += [f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w:.2f} {h:.2f}] /Resources " f"<< /XObject << /I {n + 1} 0 R >> >> /Contents {n + 2} 0 R >>".encode(), stream(f"/Type /XObject /Subtype /Image /Width {pw} /Height {ph} /ColorSpace " "/DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode", zlib.compress(rgb)), stream("", f"q {w:.2f} 0 0 {h:.2f} 0 0 cm /I Do Q".encode())] objs[1] = f"<< /Type /Pages /Kids [{' '.join(kids)}] /Count {len(kids)} >>".encode() pdf_file(dst, objs) def free_name(path): stem, ext = os.path.splitext(path) dst, n = f"{stem}-redacted{ext}", 1 while os.path.exists(dst): n += 1 dst = f"{stem}-redacted-{n}{ext}" return dst def main(path, items_arg): if not (os.path.isabs(path) and os.path.isfile(path) and os.access(path, os.R_OK)): sys.exit(f"cannot read {path}") if not os.access(os.path.dirname(path), os.W_OK): sys.exit(f"cannot write beside {path}") items = [s.strip() for s in items_arg.splitlines() if s.strip()] is_pdf = path.lower().endswith(".pdf") if not is_pdf: # tesseract reads only the first frame: the others would leak. frames = run(["magick", "identify", "-format", "%n\\n", path]).split() if frames and int(frames[0]) > 1: sys.exit(f"{os.path.basename(path)}: multi-frame images are not supported, convert to PDF first") with tempfile.TemporaryDirectory() as tmp: if is_pdf: pages = render_pdf(path, tmp) else: # -strip drops EXIF Orientation, so bake it in first. src = os.path.join(tmp, "src.png") run(["magick", path, "-auto-orient", src]) pages = [(src, 0, 0, ocr_words(src))] counts, seen, marked = {}, set(), [] for png, w, h, words in pages: hits, c, s = find(words, items) for k, v in c.items(): counts[k] = counts.get(k, 0) + v seen |= s marked.append([words[i][1] for i in hits]) missing = [it for it in items if it not in seen] tail = (" Not found: " + ", ".join(f'"{m}"' for m in missing)) if missing else "" if not counts: print("nothing to redact found." + tail) return dst = free_name(path) if is_pdf: done = [] for i, ((png, w, h, _), boxes) in enumerate(zip(pages, marked)): out = os.path.join(tmp, f"r{i}.png") draw(png, boxes, out) done.append((out, w, h)) write_pdf(done, dst) else: draw(pages[0][0], marked[0], dst) subprocess.Popen([os.environ.get("REDACT_VIEWER", "xdg-open"), dst], start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) touched = sum(1 for b in marked if b) kinds = ", ".join(f"{n} {k}" for k, n in counts.items()) print(f"redacted {sum(counts.values())} on {touched} of {len(pages)} pages: {kinds}. " f"Written to {dst}, opened for review." + tail) def tiny_pdf(path, pages, extra="", content=None): # Test fixture: one Helvetica line per page, "" is a page with no text. objs = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [%s] /Count %d >>" % (" ".join(f"{4 + 2 * i} 0 R" for i in range(len(pages))), len(pages)), "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"] for i, t in enumerate(pages): stream = content or f"BT /F1 24 Tf 72 700 Td ({t}) Tj ET" if t else "" objs += [f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] {extra} /Resources " f"<< /Font << /F1 3 0 R >> >> /Contents {5 + 2 * i} 0 R >>", f"<< /Length {len(stream)} >>\nstream\n{stream}\nendstream"] pdf_file(path, [o.encode() for o in objs]) def test(): assert iban_ok("IT60X0542811101000000123456") and iban_ok("IT60 X054 2811 1010 0000 0123 456") assert not iban_ok("IT61X0542811101000000123456") assert luhn_ok("4111 1111 1111 1111") and not luhn_ok("4111 1111 1111 1112") words = [(w, (i, 0, i + 1, 1)) for i, w in enumerate( "Gentile Mario Rossi, scriva a mario@example.org o al 333 123 4567. " "IBAN IT60X0542811101000000123456 BIC X. CF RSSMRA85T10A562S. " "Carta 4111 1111 1111 1111, ordine 4111 1111 1111 1112. Rossini.".split())] hits, counts, seen = find(words, ["mario rossi", "Via Roma 3", "Rossi"]) got = {words[i][0] for i in hits} assert counts == {"email": 1, "iban": 1, "codice fiscale": 1, "card": 1, "phone": 1, "items": 2}, counts assert {"Mario", "Rossi,", "mario@example.org", "333", "123", "4567.", "IT60X0542811101000000123456", "RSSMRA85T10A562S."} <= got, got assert "Rossini." not in got and "BIC" not in got and "1112." not in got, got assert seen == {"mario rossi", "Rossi"} import hashlib with tempfile.TemporaryDirectory() as d: src = os.path.join(d, "x.pdf") tiny_pdf(src, ["Mario Rossi mario@example.org", "nothing here"]) before = hashlib.sha256(open(src, "rb").read()).hexdigest() env = {**os.environ, "REDACT_VIEWER": "true"} run1 = subprocess.run([__file__, src, "Mario Rossi"], capture_output=True, text=True, env=env) assert run1.returncode == 0 and "redacted 2 on 1 of 2 pages: 1 email, 1 items" in run1.stdout, run1 out = os.path.join(d, "x-redacted.pdf") assert subprocess.run(["pdftotext", out, "-"], capture_output=True, text=True).stdout.strip() == "" assert "Pages: 2" in subprocess.run(["pdfinfo", out], capture_output=True, text=True).stdout # At 72 dpi pixels are points: the email's box centre must be black. _, _, words = pdf_words(src)[0] x0, y0, x1, y1 = next(b for t, b in words if "@" in t) subprocess.run(["pdftoppm", "-f", "1", "-l", "1", "-r", "72", "-png", "-singlefile", out, os.path.join(d, "check")], check=True) px = subprocess.run(["magick", os.path.join(d, "check.png"), "-format", f"%[pixel:p{{{(x0 + x1) / 2:.0f},{(y0 + y1) / 2:.0f}}}]", "info:"], capture_output=True, text=True).stdout assert px in ("gray(0)", "srgb(0,0,0)", "black"), px subprocess.run([__file__, src, ""], capture_output=True, env=env) assert os.path.exists(os.path.join(d, "x-redacted-2.pdf")) assert hashlib.sha256(open(src, "rb").read()).hexdigest() == before empty = os.path.join(d, "e.pdf") tiny_pdf(empty, ["hello"]) r = subprocess.run([__file__, empty, "Nobody"], capture_output=True, text=True, env=env) assert r.stdout.strip() == 'nothing to redact found. Not found: "Nobody"', r assert not os.path.exists(os.path.join(d, "e-redacted.pdf")) bad = subprocess.run([__file__, "rel.pdf", ""], capture_output=True, text=True, env=env) assert bad.returncode == 1 and "cannot read rel.pdf" in bad.stderr W = lambda ws: [(c, (i, 0, i + 1, 1)) for i, c in enumerate(ws)] def marked(text, items=()): ws = W(text.split()) h, c, _ = find(ws, list(items)) return {ws[i][0] for i in h}, c # Letter-spaced text: one word per glyph. assert marked(" ".join("mario@example.org"))[1] == {"email": 1} # A validated match that absorbed a neighbour. for t, want in [("ES91 2100 0418 4502 0005 1332 EUR", {0, 1, 2, 3, 4, 5}), ("ES9121000418450200051332 BIC CAIXESBB", {0}), ("Rata 2 4111 1111 1111 1111", {2, 3, 4, 5}), ("4111 1111 1111 1111 123", {0, 1, 2, 3})]: h, c, _ = find(W(t.split()), []) assert h == want and sum(c.values()) == 1, (t, h, c) for t in ["06 1234 5678", "(06) 1234567", "06/1234567", "06-1234-5678", "333 123 4567"]: assert marked(t)[1] == {"phone": 1}, t assert not marked("ordine 4111 1111 1111 1112")[1] assert marked("Sig. D\u2019Angelo", ["D'Angelo"])[1] == {"items": 1} assert marked("Sig. D'Angelo", ["D\u2019Angelo"])[1] == {"items": 1} assert marked("it60x0542811101000000123456 rssmra85t10a562s")[1] == {"iban": 1, "codice fiscale": 1} # An OCR misread codice fiscale; a 16-letter word is not one. assert marked("CF NREMRCE0A01F205X")[1] == {"codice fiscale": 1} assert not marked("rappresentazione")[1] with tempfile.TemporaryDirectory() as d: env = {**os.environ, "REDACT_VIEWER": "true"} # Text outside the CropBox is not in the page, so not in the copy. src = os.path.join(d, "c.pdf") tiny_pdf(src, ["x"], "/CropBox [0 0 612 400]", "BT /F1 24 Tf 72 700 Td (secret) Tj ET BT /F1 24 Tf 72 100 Td (hello) Tj ET") assert [t for t, _ in pdf_words(src)[0][2]] == ["hello"], pdf_words(src) # /Rotate 90: the copy is landscape, not a stretched portrait. src = os.path.join(d, "r.pdf") tiny_pdf(src, ["a@example.org"], "/Rotate 90") subprocess.run([__file__, src, ""], capture_output=True, env=env, check=True) info = subprocess.run(["pdfinfo", os.path.join(d, "r-redacted.pdf")], capture_output=True, text=True).stdout assert re.search(r"Page size:\s+792 x 612", info), info # A read-only folder is a message, not a traceback. ro = os.path.join(d, "ro") os.mkdir(ro) shutil.copy(src, ro) os.chmod(ro, 0o500) r = subprocess.run([__file__, os.path.join(ro, "r.pdf"), ""], capture_output=True, text=True, env=env) os.chmod(ro, 0o700) assert r.returncode == 1 and "cannot write beside" in r.stderr and "Traceback" not in r.stderr, r with tempfile.TemporaryDirectory() as d: env = {**os.environ, "REDACT_VIEWER": "true"} black = ("gray(0)", "srgb(0,0,0)", "black") def pixel(png, x, y): return subprocess.run(["magick", png, "-format", f"%[pixel:p{{{x:.0f},{y:.0f}}}]", "info:"], capture_output=True, text=True).stdout def pic(name, *extra): out = os.path.join(d, name) subprocess.run(["magick", "-size", "900x200", "xc:white", "-pointsize", "40", "-annotate", "+20+100", "Scrivi a mario@example.org", *extra, out], check=True) return out # An image: the email is found by OCR and its region comes out black. img = pic("s.png") words = ocr_words(img) r = subprocess.run([__file__, img, ""], capture_output=True, text=True, env=env) assert "1 email" in r.stdout and os.path.exists(os.path.join(d, "s-redacted.png")), r x0, y0, x1, y1 = next(b for t, b in words if "@" in t) assert pixel(os.path.join(d, "s-redacted.png"), (x0 + x1) / 2, (y0 + y1) / 2) in black scan = os.path.join(d, "scan.pdf") tiny_pdf(scan, [""]) # a text-less page: OCR'd, nothing found r = subprocess.run([__file__, scan, ""], capture_output=True, text=True, env=env) assert r.stdout.startswith("nothing to redact found"), r # A text page with an embedded picture of an email: the picture is OCR'd too. rgb = run(["magick", img, "-depth", "8", "rgb:-"]) src = os.path.join(d, "mix.pdf") pdf_file(src, [b"<< /Type /Catalog /Pages 2 0 R >>", b"<< /Type /Pages /Kids [4 0 R] /Count 1 >>", b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font " b"<< /F1 3 0 R >> /XObject << /I 6 0 R >> >> /Contents 5 0 R >>", stream("", b"BT /F1 24 Tf 72 700 Td (Hello there) Tj ET q 450 0 0 100 72 500 cm /I Do Q"), stream("/Type /XObject /Subtype /Image /Width 900 /Height 200 /ColorSpace /DeviceRGB " "/BitsPerComponent 8 /Filter /FlateDecode", zlib.compress(rgb))]) r = subprocess.run([__file__, src, ""], capture_output=True, text=True, env=env) assert "redacted 1 on 1 of 1 pages: 1 email" in r.stdout, r out = os.path.join(d, "mix-redacted.pdf") subprocess.run(["pdftoppm", "-r", "72", "-png", "-singlefile", out, os.path.join(d, "m")], check=True) # The picture is 450x100 pt at (72, 592 from top); the email sits right of "Scrivi a ". w = [t for t, _ in ocr_words(os.path.join(d, "m.png"))] assert not any("@" in t for t in w), w ex0, ey0, ex1, ey1 = next(b for t, b in words if "@" in t) assert pixel(os.path.join(d, "m.png"), 72 + (ex0 + ex1) / 4, 192 + (ey0 + ey1) / 4) in black # Multi-frame images are refused, not half-redacted. gif = os.path.join(d, "m.gif") subprocess.run(["magick", img, img, gif], check=True) r = subprocess.run([__file__, gif, ""], capture_output=True, text=True, env=env) assert r.returncode == 1 and "m.gif: multi-frame images are not supported, convert to PDF first" \ in r.stderr and "Traceback" not in r.stderr and not os.path.exists(os.path.join(d, "m-redacted.gif")), r # EXIF orientation is applied before -strip drops it. jpg = pic("o.jpg") # magick will not write Orientation: splice in a minimal EXIF segment (6 = RightTop). exif = b"Exif\0\0MM\0*\0\0\0\x08\0\x01\x01\x12\0\x03\0\0\0\x01\0\x06\0\0\0\0\0\0" raw = open(jpg, "rb").read() open(jpg, "wb").write(raw[:2] + b"\xff\xe1" + (len(exif) + 2).to_bytes(2, "big") + exif + raw[2:]) tag = subprocess.run(["magick", "identify", "-format", "%[orientation]", jpg], capture_output=True, text=True).stdout assert tag == "RightTop", tag r = subprocess.run([__file__, jpg, ""], capture_output=True, text=True, env=env) assert "1 email" in r.stdout, r dims = lambda f, o: subprocess.run(["magick", f, *o, "-format", "%w %h", "info:"], capture_output=True, text=True).stdout assert dims(os.path.join(d, "o-redacted.jpg"), []) == dims(jpg, ["-auto-orient"]) == "200 900" print("ok") if __name__ == "__main__": if sys.argv[1:] == ["--test"]: test() else: main(sys.argv[1] if len(sys.argv) > 1 else "", sys.argv[2] if len(sys.argv) > 2 else "")