grootveil 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- grootveil/__init__.py +42 -0
- grootveil/actions/__init__.py +0 -0
- grootveil/actions/base.py +33 -0
- grootveil/actions/encrypt.py +32 -0
- grootveil/actions/hash.py +12 -0
- grootveil/actions/keep.py +6 -0
- grootveil/actions/mask.py +24 -0
- grootveil/actions/pseudonymize.py +23 -0
- grootveil/actions/redact.py +6 -0
- grootveil/actions/registry.py +27 -0
- grootveil/actions/replace.py +8 -0
- grootveil/core/__init__.py +0 -0
- grootveil/core/errors.py +2 -0
- grootveil/core/labels.py +40 -0
- grootveil/detectors/__init__.py +0 -0
- grootveil/detectors/base.py +11 -0
- grootveil/detectors/deny_list.py +27 -0
- grootveil/detectors/model.py +129 -0
- grootveil/detectors/rules/__init__.py +14 -0
- grootveil/detectors/rules/address.py +50 -0
- grootveil/detectors/rules/checks.py +18 -0
- grootveil/detectors/rules/contact.py +114 -0
- grootveil/detectors/rules/dates.py +127 -0
- grootveil/detectors/rules/detector.py +77 -0
- grootveil/detectors/rules/financial.py +96 -0
- grootveil/detectors/rules/ids/__init__.py +20 -0
- grootveil/detectors/rules/ids/americas.py +50 -0
- grootveil/detectors/rules/ids/asia_pacific.py +148 -0
- grootveil/detectors/rules/ids/documents.py +48 -0
- grootveil/detectors/rules/ids/europe.py +219 -0
- grootveil/detectors/rules/ids/germany.py +84 -0
- grootveil/detectors/rules/ids/middle_east_africa.py +85 -0
- grootveil/detectors/rules/rule.py +37 -0
- grootveil/detectors/rules/secrets.py +74 -0
- grootveil/models/__init__.py +0 -0
- grootveil/models/action_config.py +24 -0
- grootveil/models/finding.py +14 -0
- grootveil/models/item.py +14 -0
- grootveil/models/protected.py +21 -0
- grootveil/py.typed +0 -0
- grootveil/resolvers/__init__.py +0 -0
- grootveil/resolvers/address_prefix.py +64 -0
- grootveil/resolvers/join.py +30 -0
- grootveil/resolvers/overlaps.py +42 -0
- grootveil/resolvers/register.py +33 -0
- grootveil/resolvers/words.py +14 -0
- grootveil/services/__init__.py +0 -0
- grootveil/services/applier.py +26 -0
- grootveil/services/resolver.py +35 -0
- grootveil/services/vault.py +40 -0
- grootveil/shield.py +257 -0
- grootveil-2.0.0.dist-info/METADATA +198 -0
- grootveil-2.0.0.dist-info/RECORD +54 -0
- grootveil-2.0.0.dist-info/WHEEL +4 -0
grootveil/__init__.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""grootveil: find PII (scan), change it (protect) and put it back (restore), with our fine-tuned model and rules.
|
|
2
|
+
|
|
3
|
+
from grootveil import Shield
|
|
4
|
+
shield = Shield(secret="...")
|
|
5
|
+
|
|
6
|
+
Everything a caller needs is exported here; the folders under grootveil/ are internal.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
10
|
+
|
|
11
|
+
from grootveil.actions.encrypt import decrypt
|
|
12
|
+
from grootveil.actions.registry import ACTIONS, REVERSIBLE
|
|
13
|
+
from grootveil.core.errors import RefError
|
|
14
|
+
from grootveil.core.labels import DIRECT, LABELS
|
|
15
|
+
from grootveil.detectors.rules import DEFAULT_RULES, Rule
|
|
16
|
+
from grootveil.models.action_config import ActionConfig
|
|
17
|
+
from grootveil.models.finding import Finding
|
|
18
|
+
from grootveil.models.item import Item
|
|
19
|
+
from grootveil.models.protected import Protected
|
|
20
|
+
from grootveil.shield import MODEL, Shield
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
__version__ = version("grootveil")
|
|
24
|
+
except PackageNotFoundError: # pragma: no cover (the source folder on PYTHONPATH, not installed)
|
|
25
|
+
__version__ = "0+unknown"
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"ACTIONS",
|
|
29
|
+
"DEFAULT_RULES",
|
|
30
|
+
"DIRECT",
|
|
31
|
+
"LABELS",
|
|
32
|
+
"MODEL",
|
|
33
|
+
"REVERSIBLE",
|
|
34
|
+
"ActionConfig",
|
|
35
|
+
"Finding",
|
|
36
|
+
"Item",
|
|
37
|
+
"Protected",
|
|
38
|
+
"RefError",
|
|
39
|
+
"Rule",
|
|
40
|
+
"Shield",
|
|
41
|
+
"decrypt",
|
|
42
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""An action changes one found value. Every action is fn(value, label, ctx, **params) -> new value.
|
|
2
|
+
|
|
3
|
+
ctx carries the secret (hash, encrypt), the call's tokens: {token in the new text: original value} for the actions
|
|
4
|
+
that restore() can undo (pseudonymize, encrypt), and the call's texts (a new placeholder must not be in them already).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class Context:
|
|
13
|
+
secret: bytes | None = None
|
|
14
|
+
tokens: dict[str, str] = field(default_factory=dict)
|
|
15
|
+
texts: list[str] = field(default_factory=list)
|
|
16
|
+
|
|
17
|
+
def key(self, given: str | bytes | None = None) -> bytes:
|
|
18
|
+
key = given or self.secret
|
|
19
|
+
if not key:
|
|
20
|
+
raise ValueError("hash and encrypt need a secret (Shield(secret=...) or the action's key param)")
|
|
21
|
+
if not isinstance(key, str | bytes):
|
|
22
|
+
raise ValueError("a secret or key must be a text or bytes")
|
|
23
|
+
return key.encode() if isinstance(key, str) else key
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def whole_number(action: str, name: str, value: object, low: int, high: int | None = None) -> None:
|
|
27
|
+
"""A setting that must be a whole number from low (to high): a clear error instead of a wrong result."""
|
|
28
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < low or (high is not None and value > high):
|
|
29
|
+
limit = f"from {low} to {high}" if high is not None else f"{low} or more"
|
|
30
|
+
raise ValueError(f"action {action}: bad settings: {name} must be a whole number, {limit}")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
Action = Callable[..., str]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
from cryptography.exceptions import InvalidTag
|
|
6
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
7
|
+
|
|
8
|
+
from grootveil.actions.base import Context
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _aes(key: bytes) -> AESGCM:
|
|
12
|
+
return AESGCM(hashlib.sha256(b"grootveil encrypt v1:" + key).digest())
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def encrypt(value: str, label: str, ctx: Context, key: str | None = None) -> str:
|
|
16
|
+
"""AES-256-GCM, random nonce, url-safe base64. Undone by restore() (with the ref) or decrypt() (with the secret),
|
|
17
|
+
so it also works for data kept at rest."""
|
|
18
|
+
nonce = os.urandom(12)
|
|
19
|
+
token = base64.urlsafe_b64encode(nonce + _aes(ctx.key(key)).encrypt(nonce, value.encode(), None)).decode()
|
|
20
|
+
ctx.tokens[token] = value
|
|
21
|
+
return token
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def decrypt(token: str, secret: str | bytes) -> str:
|
|
25
|
+
"""The value of one encrypted token. ValueError when the token is not ours, was changed, or the secret is
|
|
26
|
+
another one."""
|
|
27
|
+
aes = _aes(Context(secret=None).key(secret))
|
|
28
|
+
try:
|
|
29
|
+
raw = base64.urlsafe_b64decode(token)
|
|
30
|
+
return aes.decrypt(raw[:12], raw[12:], None).decode()
|
|
31
|
+
except (InvalidTag, ValueError, TypeError) as e:
|
|
32
|
+
raise ValueError("cannot decrypt: not an encrypted value of ours, changed, or another secret") from e
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
|
|
4
|
+
from grootveil.actions.base import Context, whole_number
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def hash_value(value: str, label: str, ctx: Context, length: int = 16, key: str | None = None) -> str:
|
|
8
|
+
"""HMAC-SHA256 with the secret: the same value always gives the same hash (records stay linkable), and without the
|
|
9
|
+
secret nobody can test guesses. Cannot be undone. length: 8 to 64 characters (shorter: different values would
|
|
10
|
+
share a hash)."""
|
|
11
|
+
whole_number("hash", "length", length, 8, 64)
|
|
12
|
+
return hmac.new(ctx.key(key), value.encode(), hashlib.sha256).hexdigest()[:length]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from grootveil.actions.base import Context, whole_number
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def mask(
|
|
5
|
+
value: str,
|
|
6
|
+
label: str,
|
|
7
|
+
ctx: Context,
|
|
8
|
+
char: str = "*",
|
|
9
|
+
chars: int | None = None,
|
|
10
|
+
from_end: bool = False,
|
|
11
|
+
keep_last: int = 0,
|
|
12
|
+
) -> str:
|
|
13
|
+
"""Every character becomes `char`, except the last `keep_last` (card ************1111). Or `chars` characters from
|
|
14
|
+
the start (from the end when from_end)."""
|
|
15
|
+
if not isinstance(char, str) or len(char) != 1:
|
|
16
|
+
raise ValueError("action mask: bad settings: char must be one character")
|
|
17
|
+
whole_number("mask", "keep_last", keep_last, 0)
|
|
18
|
+
if chars is not None:
|
|
19
|
+
whole_number("mask", "chars", chars, 0)
|
|
20
|
+
if keep_last:
|
|
21
|
+
n = max(len(value) - keep_last, 0)
|
|
22
|
+
return char * n + value[n:]
|
|
23
|
+
n = len(value) if chars is None else min(chars, len(value))
|
|
24
|
+
return value[: len(value) - n] + char * n if from_end else char * n + value[n:]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from grootveil.actions.base import Context
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def pseudonymize(value: str, label: str, ctx: Context, format: str = "<{label}_{n}>") -> str: # noqa: A002
|
|
5
|
+
"""The same value gets the same placeholder, numbered per label from 1, left to right; across a batch too (the
|
|
6
|
+
call's tokens are shared). restore() puts the value back. A number whose placeholder is already written in the
|
|
7
|
+
text ("<EMAIL_1>" in a template) is skipped: restore() would change that text too."""
|
|
8
|
+
try:
|
|
9
|
+
differs = format.format(label=label, n=1) != format.format(label=label, n=2)
|
|
10
|
+
except (AttributeError, LookupError, ValueError):
|
|
11
|
+
differs = False
|
|
12
|
+
if not differs: # without the number two values would share one placeholder
|
|
13
|
+
raise ValueError("action pseudonymize: bad settings: format is a text with {n} in it, and {label} if wanted")
|
|
14
|
+
n = 1
|
|
15
|
+
while True:
|
|
16
|
+
token = format.format(label=label, n=n)
|
|
17
|
+
if ctx.tokens.get(token) == value:
|
|
18
|
+
return token
|
|
19
|
+
# ponytail: one search of the texts per new value; index the texts if a call with many thousand values is slow
|
|
20
|
+
if token not in ctx.tokens and not any(token in t for t in ctx.texts):
|
|
21
|
+
ctx.tokens[token] = value
|
|
22
|
+
return token
|
|
23
|
+
n += 1
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Every built-in action by name. A new action: its own file in this folder, then one line here."""
|
|
2
|
+
|
|
3
|
+
from grootveil.actions.base import Action
|
|
4
|
+
from grootveil.actions.encrypt import encrypt
|
|
5
|
+
from grootveil.actions.hash import hash_value
|
|
6
|
+
from grootveil.actions.keep import keep
|
|
7
|
+
from grootveil.actions.mask import mask
|
|
8
|
+
from grootveil.actions.pseudonymize import pseudonymize
|
|
9
|
+
from grootveil.actions.redact import redact
|
|
10
|
+
from grootveil.actions.replace import replace
|
|
11
|
+
|
|
12
|
+
ACTIONS: dict[str, Action] = {
|
|
13
|
+
"replace": replace,
|
|
14
|
+
"redact": redact,
|
|
15
|
+
"mask": mask,
|
|
16
|
+
"keep": keep,
|
|
17
|
+
"pseudonymize": pseudonymize,
|
|
18
|
+
"hash": hash_value,
|
|
19
|
+
"encrypt": encrypt,
|
|
20
|
+
}
|
|
21
|
+
REVERSIBLE = frozenset({"pseudonymize", "encrypt"}) # restore() can undo them
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get(name: str) -> Action:
|
|
25
|
+
if name not in ACTIONS:
|
|
26
|
+
raise ValueError(f"unknown action {name!r}; known: {sorted(ACTIONS)}")
|
|
27
|
+
return ACTIONS[name]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
from grootveil.actions.base import Context
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def replace(value: str, label: str, ctx: Context, new_value: str | None = None) -> str:
|
|
5
|
+
"""[LABEL], or new_value."""
|
|
6
|
+
if new_value is not None and not isinstance(new_value, str):
|
|
7
|
+
raise ValueError("action replace: bad settings: new_value must be a text")
|
|
8
|
+
return f"[{label}]" if new_value is None else new_value
|
|
File without changes
|
grootveil/core/errors.py
ADDED
grootveil/core/labels.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Our 18 labels, and the ones that identify a person on their own."""
|
|
2
|
+
|
|
3
|
+
LABELS = [
|
|
4
|
+
"PERSON_NAME",
|
|
5
|
+
"DATE",
|
|
6
|
+
"AGE",
|
|
7
|
+
"EMAIL",
|
|
8
|
+
"PHONE",
|
|
9
|
+
"ADDRESS",
|
|
10
|
+
"BANK_ACCOUNT",
|
|
11
|
+
"CARD_NUMBER",
|
|
12
|
+
"NATIONAL_ID",
|
|
13
|
+
"TAX_ID",
|
|
14
|
+
"PASSPORT",
|
|
15
|
+
"DRIVING_LICENCE",
|
|
16
|
+
"USERNAME",
|
|
17
|
+
"URL",
|
|
18
|
+
"IP_ADDRESS",
|
|
19
|
+
"CUSTOMER_ID",
|
|
20
|
+
"PASSWORD",
|
|
21
|
+
"API_KEY",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
# Labels that identify a person on their own: a miss is a leak, and the entity register masks every mention of them.
|
|
25
|
+
DIRECT = frozenset(
|
|
26
|
+
{
|
|
27
|
+
"PERSON_NAME",
|
|
28
|
+
"EMAIL",
|
|
29
|
+
"PHONE",
|
|
30
|
+
"ADDRESS",
|
|
31
|
+
"BANK_ACCOUNT",
|
|
32
|
+
"CARD_NUMBER",
|
|
33
|
+
"NATIONAL_ID",
|
|
34
|
+
"TAX_ID",
|
|
35
|
+
"PASSPORT",
|
|
36
|
+
"DRIVING_LICENCE",
|
|
37
|
+
"USERNAME",
|
|
38
|
+
"CUSTOMER_ID",
|
|
39
|
+
}
|
|
40
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""A detector finds raw PII candidates in many texts at once. services/resolver.py decides which ones stay."""
|
|
2
|
+
|
|
3
|
+
from typing import Protocol
|
|
4
|
+
|
|
5
|
+
from grootveil.models.finding import Finding
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Detector(Protocol):
|
|
9
|
+
def detect(self, texts: list[str]) -> list[list[Finding]]:
|
|
10
|
+
"""One list of findings per text, in the same order."""
|
|
11
|
+
...
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Deny list: values that are always PII, with the label the caller gives, for one call.
|
|
2
|
+
|
|
3
|
+
{"Project Falcon": "CUSTOMER_ID"} finds every mention of "Project Falcon" as a whole word, in any case, with score 1.0.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from grootveil.models.finding import Finding
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DenyListDetector:
|
|
12
|
+
def __init__(self, values: dict[str, str]):
|
|
13
|
+
self.patterns = [
|
|
14
|
+
(re.compile(rf"(?<!\w){re.escape(value.strip())}(?!\w)", re.IGNORECASE), label)
|
|
15
|
+
for value, label in values.items()
|
|
16
|
+
if value.strip()
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
def detect(self, texts: list[str]) -> list[list[Finding]]:
|
|
20
|
+
return [self.detect_one(t) for t in texts]
|
|
21
|
+
|
|
22
|
+
def detect_one(self, text: str) -> list[Finding]:
|
|
23
|
+
return [
|
|
24
|
+
Finding(label, m.start(), m.end(), 1.0, "deny_list", "in the deny list")
|
|
25
|
+
for pattern, label in self.patterns
|
|
26
|
+
for m in pattern.finditer(text)
|
|
27
|
+
]
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Our fine-tuned token-classification model (BIO tags, our 18 labels) as a detector. Needs the `model` extra
|
|
2
|
+
(torch, transformers): pip install grootveil[transformers].
|
|
3
|
+
|
|
4
|
+
Long texts are split into overlapping windows; each token keeps the prediction from the window where it sits farthest
|
|
5
|
+
from the edge. A span's score is the mean probability of its tokens' tags.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
from transformers import AutoModelForTokenClassification, AutoTokenizer, pipeline
|
|
12
|
+
|
|
13
|
+
from grootveil.models.finding import Finding
|
|
14
|
+
|
|
15
|
+
# English, German and Arabic, our 18 labels (private repo: HF_TOKEN). The same pin as grootveil-beta in the server's
|
|
16
|
+
# models.yaml (the repo was groot-privacy-v2-beta, renamed on Hugging Face; same weights at this pin)
|
|
17
|
+
DEFAULT_MODEL = "IDP0grootan/GrootVeil-beta"
|
|
18
|
+
DEFAULT_REVISION = "df31384978e5dd602cbedacaa2cd37679c6a4452" # pinned: change only with a new test run
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def decode(text: str, tokens: list[tuple[int, int, str, float]]) -> list[Finding]:
|
|
22
|
+
"""tokens: (start, end, tag, probability) sorted by start. B- starts a span, I- of the same label continues it;
|
|
23
|
+
a B- inside the same word (no gap) continues it too. Spaces at the span edges are trimmed."""
|
|
24
|
+
spans: list[dict[str, Any]] = []
|
|
25
|
+
cur: dict[str, Any] | None = None
|
|
26
|
+
for a, b, tag, p in tokens:
|
|
27
|
+
prefix, _, label = tag.partition("-")
|
|
28
|
+
if not label:
|
|
29
|
+
cur = None
|
|
30
|
+
continue
|
|
31
|
+
same_word = cur and cur["label"] == label and a == cur["end"]
|
|
32
|
+
if cur is None or cur["label"] != label or (prefix == "B" and not same_word):
|
|
33
|
+
cur = {"label": label, "start": a, "end": b, "probs": [p]}
|
|
34
|
+
spans.append(cur)
|
|
35
|
+
else:
|
|
36
|
+
cur["end"] = b
|
|
37
|
+
cur["probs"].append(p)
|
|
38
|
+
out = []
|
|
39
|
+
for s in spans:
|
|
40
|
+
piece = text[s["start"] : s["end"]]
|
|
41
|
+
start = s["start"] + len(piece) - len(piece.lstrip())
|
|
42
|
+
end = s["end"] - (len(piece) - len(piece.rstrip()))
|
|
43
|
+
if start < end:
|
|
44
|
+
score = round(sum(s["probs"]) / len(s["probs"]), 4)
|
|
45
|
+
out.append(Finding(s["label"], start, end, score, "model", f"model score {score}"))
|
|
46
|
+
return out
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ModelDetector:
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
model: str = DEFAULT_MODEL,
|
|
53
|
+
revision: str | None = DEFAULT_REVISION,
|
|
54
|
+
max_len: int = 1024,
|
|
55
|
+
stride: int = 256,
|
|
56
|
+
device: str = "auto",
|
|
57
|
+
fp16: bool = True,
|
|
58
|
+
batch_size: int = 16,
|
|
59
|
+
):
|
|
60
|
+
if not (isinstance(max_len, int) and isinstance(stride, int) and 0 <= stride < max_len - 2):
|
|
61
|
+
raise ValueError("max_len and stride are whole numbers of tokens, with stride at least 3 below max_len")
|
|
62
|
+
if not isinstance(batch_size, int) or batch_size < 1:
|
|
63
|
+
raise ValueError("batch_size must be a whole number, 1 or more")
|
|
64
|
+
if device == "auto":
|
|
65
|
+
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
|
66
|
+
dtype = torch.float16 if fp16 and device == "cuda" else torch.float32
|
|
67
|
+
self.tok = AutoTokenizer.from_pretrained(model, revision=revision)
|
|
68
|
+
self.model = AutoModelForTokenClassification.from_pretrained(model, revision=revision, dtype=dtype)
|
|
69
|
+
self.model.to(device).eval()
|
|
70
|
+
self.device, self.max_len, self.stride, self.batch_size = device, max_len, stride, batch_size
|
|
71
|
+
self.id2label = self.model.config.id2label
|
|
72
|
+
|
|
73
|
+
@torch.no_grad()
|
|
74
|
+
def detect(self, texts: list[str]) -> list[list[Finding]]:
|
|
75
|
+
"""All windows of all texts go through the model in batches of batch_size."""
|
|
76
|
+
enc = self.tok(
|
|
77
|
+
texts,
|
|
78
|
+
truncation=True,
|
|
79
|
+
max_length=self.max_len,
|
|
80
|
+
stride=self.stride,
|
|
81
|
+
return_overflowing_tokens=True,
|
|
82
|
+
return_offsets_mapping=True,
|
|
83
|
+
padding=True,
|
|
84
|
+
return_tensors="pt",
|
|
85
|
+
)
|
|
86
|
+
offsets = enc.pop("offset_mapping").tolist()
|
|
87
|
+
owner = enc.pop("overflow_to_sample_mapping").tolist()
|
|
88
|
+
lengths = enc["attention_mask"].sum(1).tolist()
|
|
89
|
+
# per text: (start, end) -> (distance from window edge, tag, probability)
|
|
90
|
+
best: list[dict[tuple[int, int], tuple[int, str, float]]] = [{} for _ in texts]
|
|
91
|
+
for i in range(0, len(offsets), self.batch_size):
|
|
92
|
+
inputs = {k: v[i : i + self.batch_size].to(self.device) for k, v in enc.items()}
|
|
93
|
+
probs, ids = self.model(**inputs).logits.float().softmax(-1).max(-1)
|
|
94
|
+
for w, (p_row, id_row) in enumerate(zip(probs.tolist(), ids.tolist(), strict=True), start=i):
|
|
95
|
+
for j, ((a, b), p, t) in enumerate(zip(offsets[w], p_row, id_row, strict=True)):
|
|
96
|
+
if a == b: # special or padding token
|
|
97
|
+
continue
|
|
98
|
+
d = min(j, lengths[w] - j)
|
|
99
|
+
if (a, b) not in best[owner[w]] or d > best[owner[w]][(a, b)][0]:
|
|
100
|
+
best[owner[w]][(a, b)] = (d, self.id2label[t], p)
|
|
101
|
+
return [
|
|
102
|
+
decode(text, sorted((a, b, tag, p) for (a, b), (_, tag, p) in tokens.items()))
|
|
103
|
+
for text, tokens in zip(texts, best, strict=True)
|
|
104
|
+
]
|
|
105
|
+
|
|
106
|
+
def pipeline_output(self, text: str) -> dict:
|
|
107
|
+
"""The model's answer exactly as transformers' token-classification pipeline gives it (same loaded model),
|
|
108
|
+
per token and joined (aggregation_strategy="simple"). For looking at the raw model, not used by analyze()."""
|
|
109
|
+
|
|
110
|
+
def clean(rows):
|
|
111
|
+
return [
|
|
112
|
+
{
|
|
113
|
+
k: round(float(v), 4) if k == "score" else int(v) if k in ("index", "start", "end") else v
|
|
114
|
+
for k, v in r.items()
|
|
115
|
+
}
|
|
116
|
+
for r in rows
|
|
117
|
+
]
|
|
118
|
+
|
|
119
|
+
if not hasattr(self, "_pipes"): # built once, on the already loaded model
|
|
120
|
+
|
|
121
|
+
def make(**kw):
|
|
122
|
+
return pipeline("token-classification", model=self.model, tokenizer=self.tok, device=self.device, **kw)
|
|
123
|
+
|
|
124
|
+
# per token: transformers allows no stride here, so only the first window (max_len tokens) is shown
|
|
125
|
+
self._pipes = {
|
|
126
|
+
"none": make(aggregation_strategy="none"),
|
|
127
|
+
"simple": make(aggregation_strategy="simple", stride=self.stride),
|
|
128
|
+
}
|
|
129
|
+
return {"tokens": clean(self._pipes["none"](text)), "entities": clean(self._pipes["simple"](text))}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Rules: regex + validator (check digits) + context words, for PII with a fixed format (email, card, IBAN, IP
|
|
2
|
+
address, URL, a date, a postcode) and for labels the model has little training data for (passport, driving licence,
|
|
3
|
+
the ID and tax numbers of many countries, a phone number without a country code: most of these need a context word).
|
|
4
|
+
|
|
5
|
+
One file per kind of PII (`contact.py`, `financial.py`, `secrets.py`, `dates.py`, `address.py`, and the folder `ids/`
|
|
6
|
+
with one file per region), each with its rules in `RULES` and their validators. `rule.py` is the `Rule` itself,
|
|
7
|
+
`detector.py` joins the groups into `DEFAULT_RULES` and runs them, `checks.py` holds a check used by more than one
|
|
8
|
+
group.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from grootveil.detectors.rules.detector import DEFAULT_RULES, RuleDetector
|
|
12
|
+
from grootveil.detectors.rules.rule import Rule
|
|
13
|
+
|
|
14
|
+
__all__ = ["DEFAULT_RULES", "Rule", "RuleDetector"]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Where someone lives: postcodes with a fixed format (United Kingdom, Canada, Germany). Streets and towns have no
|
|
2
|
+
fixed format: the model finds those."""
|
|
3
|
+
|
|
4
|
+
from grootveil.detectors.rules.rule import Rule
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def german_postcode(value: str) -> bool:
|
|
8
|
+
"""A German Postleitzahl: 01001 to 99998 (none starts with 00)."""
|
|
9
|
+
return 1001 <= int(value) <= 99998
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
POSTCODE_WORDS = (
|
|
13
|
+
"postcode", "post code", "postal code", "zip", "zip code", "address", "code postal", "resident at", "lives at",
|
|
14
|
+
"living at", "at home",
|
|
15
|
+
) # fmt: skip
|
|
16
|
+
GERMAN_POSTCODE_WORDS = (
|
|
17
|
+
"plz", "postleitzahl", "anschrift", "adresse", "wohnhaft", "wohnort", "wohnt in", "wohnung", "zu hause",
|
|
18
|
+
"wohnanschrift", "postanschrift", "lieferadresse", "rechnungsadresse", "meldeadresse", "wohnadresse",
|
|
19
|
+
) # fmt: skip
|
|
20
|
+
|
|
21
|
+
RULES = [
|
|
22
|
+
Rule(
|
|
23
|
+
"uk_postcode",
|
|
24
|
+
"ADDRESS",
|
|
25
|
+
# SW1A 1AA, M1 1AE, B33 8TH: area letters, a district, then a digit and two letters. Capitals only
|
|
26
|
+
# A9A takes A-H J K P S T U W as its last letter, AA9A A B E H M N P R V W X Y
|
|
27
|
+
r"\b(?:GIR ?0AA|(?:[A-PR-UWYZ]\d[A-HJKPSTUW]|[A-PR-UWYZ][A-HK-Y]\d[ABEHMNPRV-Y]|[A-PR-UWYZ][A-HK-Y]?\d\d?)"
|
|
28
|
+
r" ?\d[ABD-HJLNP-UW-Z]{2})\b",
|
|
29
|
+
0.4,
|
|
30
|
+
POSTCODE_WORDS,
|
|
31
|
+
0.75,
|
|
32
|
+
),
|
|
33
|
+
Rule(
|
|
34
|
+
"canada_postcode",
|
|
35
|
+
"ADDRESS",
|
|
36
|
+
r"\b[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] ?\d[ABCEGHJ-NPRSTV-Z]\d\b", # K1A 0B1; no D, F, I, O, Q, U
|
|
37
|
+
0.4,
|
|
38
|
+
POSTCODE_WORDS,
|
|
39
|
+
0.75,
|
|
40
|
+
),
|
|
41
|
+
Rule(
|
|
42
|
+
"german_postcode",
|
|
43
|
+
"ADDRESS",
|
|
44
|
+
r"(?<![\w.,/+-])\d{5}(?![\w/+-]|[.,]\d)", # any five digits: only with a context word
|
|
45
|
+
0.1,
|
|
46
|
+
GERMAN_POSTCODE_WORDS,
|
|
47
|
+
0.6,
|
|
48
|
+
validator=german_postcode,
|
|
49
|
+
),
|
|
50
|
+
]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Checks used by more than one rule group. A check used by one group sits in that group's file."""
|
|
2
|
+
|
|
3
|
+
from datetime import date
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def luhn_ok(digits: list[int]) -> bool:
|
|
7
|
+
"""The Luhn check digit: payment cards (financial.py) and ID numbers of several countries (ids/)."""
|
|
8
|
+
total = sum(d if i % 2 == 0 else (d * 2 - 9 if d > 4 else d * 2) for i, d in enumerate(reversed(digits)))
|
|
9
|
+
return total % 10 == 0
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def date_ok(year: int, month: int, day: int) -> bool:
|
|
13
|
+
"""A day that exists in the calendar: a written date (dates.py) and the birth date inside an ID number (ids/)."""
|
|
14
|
+
try:
|
|
15
|
+
date(year, month, day)
|
|
16
|
+
except ValueError:
|
|
17
|
+
return False
|
|
18
|
+
return True
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""How to reach someone, or their machine: email, URL, IP address, phone number."""
|
|
2
|
+
|
|
3
|
+
import ipaddress
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from grootveil.detectors.rules.rule import Rule
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def ip(value: str) -> bool:
|
|
10
|
+
"""A valid IPv4/IPv6, but not a network mask (255.255.255.0) or "any address" (0.0.0.0)."""
|
|
11
|
+
value = "".join(str(int(c)) if c.isdecimal() else c for c in value) # Arabic-Indic digits: ١٩٢.١٦٨.١.١
|
|
12
|
+
try:
|
|
13
|
+
ipaddress.ip_address(value)
|
|
14
|
+
except ValueError:
|
|
15
|
+
return False
|
|
16
|
+
return not value.startswith("255.") and value != "0.0.0.0" # noqa: S104 (a value check, not a bind)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def phone_digits(value: str) -> bool:
|
|
20
|
+
return 8 <= sum(c.isdigit() for c in value) <= 15
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
SERVICE = re.compile(r"0(?:800|180)") # German 0800 (free) and 0180 (shared cost) service numbers
|
|
24
|
+
DATE_START = re.compile(r"(\d{1,2})[./-](\d{1,2})[./-](?:\d{4}|\d{2})(?!\d)")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def phone_national(value: str) -> bool:
|
|
28
|
+
"""8 to 14 digits, not a date (01.02.2024, 03-04-1999 and "01.02.2024 10" start like a phone number with a 0 in
|
|
29
|
+
front; 05.56.77.88.32 is a phone number: no month 56 or 77), and not a German 0800 or 0180 service line."""
|
|
30
|
+
if (m := DATE_START.match(value)) and (a := int(m[1])) <= 31 and (b := int(m[2])) <= 31 and min(a, b) <= 12:
|
|
31
|
+
return False
|
|
32
|
+
if SERVICE.match(value): # a free or shared-cost service line, not a person's number
|
|
33
|
+
return False
|
|
34
|
+
return 8 <= sum(c.isdigit() for c in value) <= 14
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
PHONE_WORDS = (
|
|
38
|
+
"phone", "telephone", "tel", "mobile", "cell", "call", "fax", "whatsapp", "sms", "text message", "reach me",
|
|
39
|
+
"contact me", "landline",
|
|
40
|
+
"telefon", "telefonnummer", "telefonisch", "rufnummer", "mobil", "mobilnummer", "handy", "handynummer",
|
|
41
|
+
"festnetz", "anrufen", "rufen", "erreichbar", "kontakt", "notfallkontakt", "rückruf", "rückfragen",
|
|
42
|
+
"هاتف", "الهاتف", "هاتفي", "جوال", "الجوال", "جوالي", "جواله", "وجوالي", "موبايل", "الموبايل", "واتساب",
|
|
43
|
+
"تلفون", "تليفون", "اتصل", "جوالك", "هاتفك", "اتصلوا", "الاتصال",
|
|
44
|
+
) # fmt: skip
|
|
45
|
+
|
|
46
|
+
# The field of another number, just before the value: in a form, a "Phone" field is often the next line, so the phone
|
|
47
|
+
# word is near ("Medical Record Number: 0008264713 - Phone Number: ...", "عقد مؤقت رقم: ٠٩٧٠٠٥٥٥١٧١٤")
|
|
48
|
+
OTHER_NUMBER = (
|
|
49
|
+
r"(?:\b(?:(?:record|routing|beneficiary|account|policy|order|invoice|ticket|contract|case|reference|tracking|"
|
|
50
|
+
r"customer|member|employee)\s+(?:number|no\.?|id)|mrn|kundennummer|bestellnummer|rechnungsnummer|vertragsnummer|"
|
|
51
|
+
r"kontonummer|auftragsnummer)|عقد(?:\s+\S+)?\s+رقم)[*_]*\s*(?:is|ist|lautet)?\s*[:=#,-]?[*_]*\s*(?:[a-z]{2}-)?"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
RULES = [
|
|
55
|
+
Rule(
|
|
56
|
+
"email",
|
|
57
|
+
"EMAIL",
|
|
58
|
+
# \w: any letter, so jürgen@münchen.de too. At most 64 characters before the @ (RFC 5321): without the limit
|
|
59
|
+
# a long text with no @ is read again from every position (100 KB took 10 s)
|
|
60
|
+
r"\b[\w.%+-]{1,64}@[\w-]+(?:\.[\w-]+)*\.[^\W\d_]{2,}\b",
|
|
61
|
+
0.95,
|
|
62
|
+
),
|
|
63
|
+
Rule(
|
|
64
|
+
"ipv4",
|
|
65
|
+
"IP_ADDRESS",
|
|
66
|
+
r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
|
|
67
|
+
0.6,
|
|
68
|
+
("ip", "address", "host", "server"),
|
|
69
|
+
validator=ip,
|
|
70
|
+
# a version or section number looks like an IP: "Version 3.2.1.4", "Firmware: 8.8.8.8", "Abschnitt 1.2.3.4",
|
|
71
|
+
# "Artikel-Nr. 12.40.33.1" (not plain "Nummer": "IP-Nummer 10.0.0.1" is an IP)
|
|
72
|
+
not_after=r"(?:\b(?:version|versionsnummer|paketversion|ver\.?|v|build|release|rc|firmware|fw|treiber|driver|"
|
|
73
|
+
r"patch|softwarestand|stand|ausgabe|changelog|abschnitt|kapitel|paragraf|paragraph|section|chapter|"
|
|
74
|
+
r"gliederungspunkt|ziffer|artikel-nr\.?|art\.-nr\.?|bestellnummer|bestellung|paketnummer|seriennummer|"
|
|
75
|
+
r"bauteilnummer|prüfnummer)|§)\s*[:=]?\s*",
|
|
76
|
+
),
|
|
77
|
+
Rule(
|
|
78
|
+
"ipv6",
|
|
79
|
+
"IP_ADDRESS",
|
|
80
|
+
# also with an IPv4 at the end (::ffff:192.0.2.44)
|
|
81
|
+
r"(?<![\w:])(?:(?:[0-9A-Fa-f]{0,4}:){2,6}(?:\d{1,3}\.){3}\d{1,3}|(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4})"
|
|
82
|
+
r"(?![\w:.])",
|
|
83
|
+
0.6,
|
|
84
|
+
("ip", "ipv6", "address", "host"),
|
|
85
|
+
validator=ip,
|
|
86
|
+
),
|
|
87
|
+
Rule("url", "URL", r"\b(?:https?://|www\.)[^\s<>\"']*[^\s<>\"'.,;:!?)\]]", 0.6),
|
|
88
|
+
Rule(
|
|
89
|
+
"phone_international",
|
|
90
|
+
"PHONE",
|
|
91
|
+
r"(?<![\w+])\+\d{1,3}[\s.-]?(?:\(?\d{1,5}\)?[\s.-]?){1,5}\d{2,5}(?!\w)",
|
|
92
|
+
0.6,
|
|
93
|
+
(*PHONE_WORDS, "contact"), # never weaker than phone_national on the same number
|
|
94
|
+
validator=phone_digits,
|
|
95
|
+
),
|
|
96
|
+
Rule(
|
|
97
|
+
"phone_national",
|
|
98
|
+
"PHONE",
|
|
99
|
+
# no country code, so only with a context word. Not after a letter, a +, a digit group (the middle of a
|
|
100
|
+
# longer number: an IBAN, a card) or a code's prefix (CA-0005384769). The 0 in front may be Arabic-Indic (٠) or
|
|
101
|
+
# Persian (۰); \d takes both
|
|
102
|
+
r"(?<![\w+])(?<!\d[\s./-])(?<![A-Za-z]-)(?:"
|
|
103
|
+
r"\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}" # 657-224-5793, (832) 567-2914, 071 373 8929
|
|
104
|
+
r"|[0٠۰]\d{8,13}" # 0598341943, 09033514429, 00966502352701
|
|
105
|
+
r"|[0٠۰]\d{1,4}[\s./-]\d{2,8}(?:[\s.-]\d{2,4}){0,3}" # 030-12345678, 0171/1234567, 079 123 45 67
|
|
106
|
+
r"|\([0٠۰]\d{1,4}\)\s?\d{2,8}(?:[\s.-]\d{2,4}){0,3}" # (030) 12345678
|
|
107
|
+
r")(?!\w)",
|
|
108
|
+
0.3,
|
|
109
|
+
PHONE_WORDS,
|
|
110
|
+
0.75,
|
|
111
|
+
validator=phone_national,
|
|
112
|
+
not_after=OTHER_NUMBER,
|
|
113
|
+
),
|
|
114
|
+
]
|