diff options
Diffstat (limited to 'examples')
| -rwxr-xr-x | examples/tools/redact.py | 105 |
1 files changed, 87 insertions, 18 deletions
diff --git a/examples/tools/redact.py b/examples/tools/redact.py index fb1afff..ccf1fd3 100755 --- a/examples/tools/redact.py +++ b/examples/tools/redact.py @@ -26,6 +26,7 @@ import functools import html import os import re +import shutil import subprocess import sys import tempfile @@ -33,7 +34,7 @@ import zlib def iban_ok(s): - s = s.replace(" ", "") + s = s.replace(" ", "").upper() n = int("".join(str(int(c, 36)) for c in s[4:] + s[:4])) return n % 97 == 1 @@ -46,39 +47,61 @@ def luhn_ok(s): 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), + ("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), ("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), + r"[0-9LMNPQRSTUV]{2}[A-Z][0-9LMNPQRSTUV]{3}[A-Z]\b", re.I), None), ("card", re.compile(r"(?<!\d)(?:\d[ -]?){12,18}\d(?!\d)"), luhn_ok), - # Mobile (3xx), landline (0x), or international with + prefix. + # Mobile (3xx), landline (0x, optional parentheses), or +international. ("phone", re.compile(r"(?<![\w+])(?:\+\d{1,3}[ .-]?\d[\d .-]{5,13}\d" - r"|3\d{2}[ .-]?\d{3}[ .-]?\d{3,4}|0\d{1,3}[ .-]?\d{5,8})(?!\w)"), None), + r"|3\d{2}[ .-]?\d{3}[ .-]?\d{3,4}" + r"|\(?0\d{1,3}\)?[ ./-]?\d{2,4}(?:[ .-]?\d{2,4}){1,2})(?!\w)"), None), ] +def sub_span(m, rx, ok): + """The match absorbed a neighbour ("... 1332 EUR"): the longest run of + its whitespace/dash separated tokens that is valid on its own.""" + s, t = m.group(), [x.span() for x in re.finditer(r"[^ -]+", m.group())] + for n in range(len(t) - 1, 0, -1): + for i in range(len(t) - n + 1): + a, b = t[i][0], t[i + n - 1][1] + if rx.fullmatch(s[a:b]) and ok(s[a:b]): + return m.start() + a, m.start() + b + + def find(words, items): """words: [(text, box)] of one page. Returns (indices of words to black out, {kind: matches}, set of items seen).""" text, starts = "", [] - for w, _ in words: + for i, (w, _) in enumerate(words): + # No space between single characters: letter-spaced text and + # per-character form fields come out one word per glyph. + if i and not (len(w) == 1 and len(words[i - 1][0]) == 1): + text += " " starts.append(len(text)) - text += w + " " + text += w + text = text.replace("\u2019", "'") # same length, spans still map hits, counts, seen = set(), {}, set() - def mark(kind, a, b): - hits.update(i for i, s in enumerate(starts) if s < b and s + len(words[i][0]) > a) + def mark(kind, a, b, dedupe=True): + new = {i for i, s in enumerate(starts) if s < b and s + len(words[i][0]) > 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): - if ok is None or ok(m.group()): - mark(kind, *m.span()) + 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"(?<!\w)" + r"\s+".join(map(re.escape, it.split())) + r"(?!\w)", re.I) for m in rx.finditer(text): - mark("items", *m.span()) - seen.add(it) + mark("items", *m.span(), dedupe=False) + seen.add(orig) return hits, counts, seen @@ -100,7 +123,7 @@ def pdf_words(path): pages = [] for m in re.finditer(r'<page width="([\d.]+)" height="([\d.]+)">|<word xMin="([\d.]+)" ' r'yMin="([\d.]+)" xMax="([\d.]+)" yMax="([\d.]+)">([^<]*)</word>', - run(["pdftotext", "-bbox", path, "-"]).decode(errors="replace")): + run(["pdftotext", "-cropbox", "-bbox", path, "-"]).decode(errors="replace")): if m[1]: pages.append((float(m[1]), float(m[2]), [])) else: @@ -132,8 +155,11 @@ def render_pdf(path, tmp): 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", path, base]) + "-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 words = ([(t, tuple(v * k for v in b)) for t, b in words] if words else ocr_words(base + ".png")) pages.append((base + ".png", w, h, words)) @@ -197,6 +223,8 @@ def free_name(path): 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") with tempfile.TemporaryDirectory() as tmp: @@ -230,15 +258,15 @@ def main(path, items_arg): 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): +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 = 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] /Resources " + 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]) @@ -290,6 +318,47 @@ def test(): 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} + 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 print("ok") |
