From 81fb9c3f6fae47072381f3973296d9de87b5af5e Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Mon, 9 Nov 2026 00:52:27 +0100 Subject: tools: redact, OCR for images, scans and pictures in text pages Co-Authored-By: Claude Opus 5.5 --- examples/tools/redact.py | 88 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 84 insertions(+), 4 deletions(-) (limited to 'examples/tools/redact.py') diff --git a/examples/tools/redact.py b/examples/tools/redact.py index ccf1fd3..7884d3b 100755 --- a/examples/tools/redact.py +++ b/examples/tools/redact.py @@ -160,8 +160,16 @@ def render_pdf(path, tmp): # 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 - words = ([(t, tuple(v * k for v in b)) for t, b in words] if words - else ocr_words(base + ".png")) + 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 @@ -227,8 +235,19 @@ def main(path, items_arg): 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: - pages = render_pdf(path, tmp) if is_pdf else [(path, 0, 0, ocr_words(path))] + 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) @@ -250,7 +269,7 @@ def main(path, items_arg): done.append((out, w, h)) write_pdf(done, dst) else: - draw(path, marked[0], dst) + 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) @@ -359,6 +378,67 @@ def test(): 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") -- cgit v1.2.3