aboutsummaryrefslogtreecommitdiffstats
path: root/examples/tools/redact.py
blob: 3e14bd8a3db5dd66cd0469c3735dc3b29145ebfd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/usr/bin/env python3
# desktop-assistant tool: black out personal data in a PDF or image.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# 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 <name>-redacted.<ext> 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"(?<!\d)(?:\d[ -]?){12,18}\d(?!\d)"), luhn_ok),
    # Mobile (3xx), landline (0x), or international with + prefix.
    ("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),
]


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:
        starts.append(len(text))
        text += w + " "
    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)
        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"(?<!\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)
    return hits, counts, seen


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"}
    print("ok")


if __name__ == "__main__":
    if sys.argv[1:] == ["--test"]:
        test()