ectype-data 0.1.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.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""Conservative detection of columns that look like personal data (ADR-0010).
|
|
2
|
+
|
|
3
|
+
``detect_personal`` answers one question about a text (or integer-coded) column: does it look
|
|
4
|
+
like it identifies a person or an organisation - a name, a phone number, an e-mail address, a
|
|
5
|
+
postal address, a licence or passport number? The structural profiler uses the answer to give
|
|
6
|
+
such a column the ``pseudonym`` role by default (``profiling.structural``), so that its labels
|
|
7
|
+
are replaced by stand-in tokens before anything is fitted (``profiling.pseudonym``).
|
|
8
|
+
|
|
9
|
+
The detector is deliberately narrow. A miss leaves the column as it would have been without
|
|
10
|
+
the detector, and the user can opt it in with an override; a false positive replaces useful
|
|
11
|
+
labels by tokens, and the user has to notice and opt out. It never looks anything up and never
|
|
12
|
+
stores or returns a value of the column: the result is a kind and a sentence of evidence.
|
|
13
|
+
|
|
14
|
+
Evidence, strongest first
|
|
15
|
+
-------------------------
|
|
16
|
+
1. **Value patterns**, whatever the column is called: at least ``VALUE_MATCH_MIN`` of the
|
|
17
|
+
sampled non-blank values are e-mail addresses, formatted phone numbers (national
|
|
18
|
+
``(555) 123-4567`` / ``555-123-4567`` forms, or international ``+CC ...`` forms; a bare run
|
|
19
|
+
of digits is not enough) or have the ``999-99-9999`` shape.
|
|
20
|
+
2. **Column-name tokens, confirmed by the values.** The name is split into lowercase tokens
|
|
21
|
+
(``contactPhone`` and ``CONTACT_PHONE`` both give ``contact``, ``phone``); only whole tokens
|
|
22
|
+
count, so ``filename`` and ``telephony`` match nothing.
|
|
23
|
+
|
|
24
|
+
* ``email`` / ``e_mail`` / ``mail``: most values must contain ``@``.
|
|
25
|
+
* ``phone``, ``telephone``, ``tel``, ``mobile``, ``fax``, ``ssn``, ``passport``, ``license``
|
|
26
|
+
/ ``licence``: most values must contain at least ``CONTACT_MIN_DIGITS`` digits (so
|
|
27
|
+
``phone_type`` holding ``mobile`` / ``landline`` is not caught).
|
|
28
|
+
* ``dob``, ``birthdate``, ``birth_date``, ``birthday``.
|
|
29
|
+
* ``name`` together with a word for a person (``first``, ``last``, ``full``, ``owner``,
|
|
30
|
+
``applicant``, ``contact``, ``customer``, ``employee``, ``contractor``, ...).
|
|
31
|
+
3. **Column-name tokens alone**, only for columns with more than ``WEAK_MIN_LEVELS`` distinct
|
|
32
|
+
values (a handful of levels is a classification, not a list of people):
|
|
33
|
+
|
|
34
|
+
* a bare ``name`` (no other word), or ``name`` with a word for an organisation
|
|
35
|
+
(``business``, ``company``, ``firm``, ``vendor``, ...);
|
|
36
|
+
* ``address``, ``addr``, ``street`` (unless a part is named: ``street_number``,
|
|
37
|
+
``address_suffix``);
|
|
38
|
+
* a party named by its role: ``owner``, ``applicant``, ``contact``, ``contractor``, ...
|
|
39
|
+
|
|
40
|
+
The address or role word must be the head of the name: it comes last, or is followed only
|
|
41
|
+
by words for a person or an organisation (``property_owner``, ``contractor_company``,
|
|
42
|
+
``address_line_1``). ``patient_diagnosis`` and ``customer_feedback`` describe something
|
|
43
|
+
else and are not caught.
|
|
44
|
+
|
|
45
|
+
A name that also carries an *attribute* token describes a property of the thing, not the thing
|
|
46
|
+
itself, and is never caught by its name: ``address_zip``, ``address_state``, ``owner_type``,
|
|
47
|
+
``license_status``, ``contact_method``, ``name_length``, ``email_verified``, ``applicant_id``.
|
|
48
|
+
``name`` with any other word (``product_name``, ``city_name``, ``file_name``) is not caught
|
|
49
|
+
either.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
from __future__ import annotations
|
|
53
|
+
|
|
54
|
+
import re
|
|
55
|
+
from dataclasses import dataclass
|
|
56
|
+
|
|
57
|
+
import polars as pl
|
|
58
|
+
|
|
59
|
+
__all__ = ["PersonalHint", "detect_personal", "name_tokens", "VALUE_MATCH_MIN",
|
|
60
|
+
"NAME_VALUE_MIN", "CONTACT_MIN_DIGITS", "NUMERIC_MIN_DIGITS", "WEAK_MIN_LEVELS"]
|
|
61
|
+
|
|
62
|
+
#: share of sampled non-blank values that must match a value pattern (tier 1)
|
|
63
|
+
VALUE_MATCH_MIN = 0.9
|
|
64
|
+
#: share of sampled values that must be consistent with a name token (tier 2)
|
|
65
|
+
NAME_VALUE_MIN = 0.5
|
|
66
|
+
#: digits a value needs to be consistent with a phone / ssn / passport / licence token
|
|
67
|
+
CONTACT_MIN_DIGITS = 4
|
|
68
|
+
#: ... and for a numeric column (an integer holding phone or social-security numbers)
|
|
69
|
+
NUMERIC_MIN_DIGITS = 7
|
|
70
|
+
#: name-only evidence (tier 3) needs more distinct values than this
|
|
71
|
+
WEAK_MIN_LEVELS = 20
|
|
72
|
+
|
|
73
|
+
EMAIL_TOKENS = frozenset({"email", "mail"})
|
|
74
|
+
CONTACT_TOKENS: dict[str, str] = {
|
|
75
|
+
"phone": "phone number", "telephone": "phone number", "tel": "phone number",
|
|
76
|
+
"mobile": "phone number", "fax": "phone number",
|
|
77
|
+
"ssn": "social security number", "passport": "passport number",
|
|
78
|
+
"license": "licence number", "licence": "licence number",
|
|
79
|
+
}
|
|
80
|
+
ADDRESS_TOKENS = frozenset({"address", "addr", "street"})
|
|
81
|
+
#: a named part of an address is not an address
|
|
82
|
+
ADDRESS_PART_TOKENS = frozenset({"number", "no", "num", "nbr", "suffix", "prefix", "direction",
|
|
83
|
+
"dir", "unit", "apt", "suite", "floor"})
|
|
84
|
+
#: parties named by their role
|
|
85
|
+
ROLE_TOKENS = frozenset({
|
|
86
|
+
"owner", "applicant", "contact", "contractor", "permittee", "licensee", "customer",
|
|
87
|
+
"client", "patient", "employee", "tenant", "landlord", "borrower", "claimant", "payee",
|
|
88
|
+
"beneficiary", "taxpayer", "defendant", "plaintiff",
|
|
89
|
+
})
|
|
90
|
+
#: words that make ``name`` a person's name
|
|
91
|
+
PERSON_QUALIFIERS = ROLE_TOKENS | frozenset({
|
|
92
|
+
"first", "last", "middle", "full", "given", "family", "maiden", "sur", "legal", "nick",
|
|
93
|
+
"preferred", "person", "user", "member", "student", "parent", "guardian", "spouse",
|
|
94
|
+
"mother", "father", "child", "driver", "agent", "officer", "inspector", "doctor",
|
|
95
|
+
"physician", "nurse", "provider", "buyer", "seller", "payer", "insured", "holder",
|
|
96
|
+
"cardholder", "manager", "supervisor", "author", "recipient", "sender", "resident",
|
|
97
|
+
"victim", "witness", "respondent", "subscriber", "passenger", "guest", "host", "donor",
|
|
98
|
+
"principal", "architect", "engineer", "attorney", "lawyer", "representative", "rep",
|
|
99
|
+
"filer", "signatory", "debtor", "creditor", "staff", "worker", "operator", "teacher",
|
|
100
|
+
"instructor", "emergency", "kin",
|
|
101
|
+
})
|
|
102
|
+
#: words that make ``name`` an organisation's name (which may be a sole trader's own name)
|
|
103
|
+
ORG_QUALIFIERS = frozenset({
|
|
104
|
+
"business", "company", "firm", "vendor", "supplier", "employer", "organization",
|
|
105
|
+
"organisation", "org", "dba", "merchant", "account", "billing", "shipping",
|
|
106
|
+
})
|
|
107
|
+
#: words that may follow an address or role token without changing what the column holds
|
|
108
|
+
FILLER_TOKENS = frozenset({"line", "full", "text"})
|
|
109
|
+
#: a column whose name carries one of these describes a property, not the party itself
|
|
110
|
+
ATTRIBUTE_TOKENS = frozenset({
|
|
111
|
+
"type", "kind", "category", "cat", "class", "status", "state", "city", "town", "county",
|
|
112
|
+
"country", "region", "province", "zip", "postal", "code", "flag", "count", "cnt",
|
|
113
|
+
"length", "len", "method", "pref", "preference", "opt", "optin", "consent", "verified",
|
|
114
|
+
"valid", "confirmed", "is", "has", "year", "month", "date", "time", "at", "age", "gender",
|
|
115
|
+
"sex", "language", "lang", "domain", "source", "channel", "group", "segment", "tier",
|
|
116
|
+
"level", "role", "title", "id", "key", "uuid", "guid", "pk", "amount", "fee", "cost",
|
|
117
|
+
"price", "total", "pct", "percent", "rate", "share", "score", "rating", "rank",
|
|
118
|
+
})
|
|
119
|
+
#: run-together spellings, expanded before matching
|
|
120
|
+
_COMPOUNDS: dict[str, tuple[str, ...]] = {
|
|
121
|
+
"firstname": ("first", "name"), "lastname": ("last", "name"), "fullname": ("full", "name"),
|
|
122
|
+
"surname": ("sur", "name"), "forename": ("first", "name"),
|
|
123
|
+
"middlename": ("middle", "name"), "givenname": ("given", "name"),
|
|
124
|
+
"familyname": ("family", "name"), "maidenname": ("maiden", "name"),
|
|
125
|
+
"phonenumber": ("phone", "number"), "cellphone": ("phone",), "homephone": ("phone",),
|
|
126
|
+
"workphone": ("phone",), "mobilephone": ("phone",), "emailaddress": ("email",),
|
|
127
|
+
"streetaddress": ("street", "address"), "birthdate": ("birth", "date"),
|
|
128
|
+
"birthday": ("birth", "day"), "dob": ("birth", "date"), "zipcode": ("zip", "code"),
|
|
129
|
+
"postcode": ("postal", "code"),
|
|
130
|
+
}
|
|
131
|
+
_VOCABULARY = (EMAIL_TOKENS | frozenset(CONTACT_TOKENS) | ADDRESS_TOKENS | ROLE_TOKENS
|
|
132
|
+
| PERSON_QUALIFIERS | ORG_QUALIFIERS | ATTRIBUTE_TOKENS | frozenset(_COMPOUNDS)
|
|
133
|
+
| frozenset({"name", "birth", "day"}))
|
|
134
|
+
|
|
135
|
+
_EMAIL = r"^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$"
|
|
136
|
+
_EXT = r"(\s*(x|ext\.?)\s*[0-9]{1,5})?"
|
|
137
|
+
#: national forms: optional +1 / 1, a three-digit area code (optionally in parentheses), 3 + 4
|
|
138
|
+
_PHONE_NATIONAL = (r"^(\+?1[\s.\-]?)?\(?[0-9]{3}\)?[\s.\-]?[0-9]{3}[\s.\-]?[0-9]{4}"
|
|
139
|
+
+ _EXT + "$")
|
|
140
|
+
#: international forms: a leading +, a country code, then 2 to 5 groups of digits
|
|
141
|
+
_PHONE_INTERNATIONAL = r"^\+[0-9]{1,3}([\s.\-]?\(?[0-9]{1,4}\)?){2,5}" + _EXT + "$"
|
|
142
|
+
_SSN = r"^[0-9]{3}-[0-9]{2}-[0-9]{4}$"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass(frozen=True)
|
|
146
|
+
class PersonalHint:
|
|
147
|
+
"""Why a column looks personal: what it seems to hold and the evidence, as a phrase that
|
|
148
|
+
reads after "looks like personal data"."""
|
|
149
|
+
|
|
150
|
+
kind: str
|
|
151
|
+
evidence: str
|
|
152
|
+
|
|
153
|
+
def describe(self) -> str:
|
|
154
|
+
return f"{self.kind}: {self.evidence}"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def name_tokens(name: str) -> list[str]:
|
|
158
|
+
"""Lowercase word tokens of a column name: split on case changes, digits and punctuation;
|
|
159
|
+
possessive and plural endings and run-together spellings (``firstname``, ``dob``) are
|
|
160
|
+
normalised."""
|
|
161
|
+
snake = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", str(name))
|
|
162
|
+
snake = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", snake).lower()
|
|
163
|
+
raw = re.findall(r"[a-z]+|[0-9]+", snake)
|
|
164
|
+
out: list[str] = []
|
|
165
|
+
i = 0
|
|
166
|
+
while i < len(raw):
|
|
167
|
+
tok = raw[i]
|
|
168
|
+
if tok == "e" and i + 1 < len(raw) and raw[i + 1] == "mail": # e_mail, e-mail
|
|
169
|
+
out.append("email")
|
|
170
|
+
i += 2
|
|
171
|
+
continue
|
|
172
|
+
i += 1
|
|
173
|
+
if len(tok) == 1 and tok.isalpha(): # the "s" of "owner's", stray initials
|
|
174
|
+
continue
|
|
175
|
+
if tok not in _VOCABULARY:
|
|
176
|
+
for end in ("es", "s"):
|
|
177
|
+
if tok.endswith(end) and tok[: -len(end)] in _VOCABULARY:
|
|
178
|
+
tok = tok[: -len(end)]
|
|
179
|
+
break
|
|
180
|
+
out.extend(_COMPOUNDS.get(tok, (tok,)))
|
|
181
|
+
return out
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _share(mask: pl.Series) -> float:
|
|
185
|
+
return float(mask.mean() or 0.0) if mask.len() else 0.0 # type: ignore[arg-type]
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _by_values(values: pl.Series) -> PersonalHint | None:
|
|
189
|
+
if _share(values.str.contains(_EMAIL)) >= VALUE_MATCH_MIN:
|
|
190
|
+
return PersonalHint("e-mail address", "values look like e-mail addresses")
|
|
191
|
+
if _share(values.str.contains(_SSN)) >= VALUE_MATCH_MIN:
|
|
192
|
+
return PersonalHint("social security number", "values have the shape 999-99-9999")
|
|
193
|
+
formatted = values.str.contains(r"[^0-9]")
|
|
194
|
+
national = values.str.contains(_PHONE_NATIONAL)
|
|
195
|
+
digits = values.str.count_matches(r"[0-9]")
|
|
196
|
+
international = values.str.contains(_PHONE_INTERNATIONAL) & (digits >= 8) & (digits <= 15)
|
|
197
|
+
if _share(formatted & (national | international)) >= VALUE_MATCH_MIN:
|
|
198
|
+
return PersonalHint("phone number", "values look like formatted phone numbers")
|
|
199
|
+
return None
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _has_digits(values: pl.Series, n: int, share: float) -> bool:
|
|
203
|
+
return _share(values.str.count_matches(r"[0-9]") >= n) >= share
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def detect_personal(name: str, sample: pl.Series, n_levels: int, *,
|
|
207
|
+
numeric: bool = False) -> PersonalHint | None:
|
|
208
|
+
"""Whether the column called ``name`` looks like personal data (see the module docstring).
|
|
209
|
+
|
|
210
|
+
``sample`` holds sampled values of the column; ``n_levels`` is its number of distinct
|
|
211
|
+
values. With ``numeric`` (an integer-valued column) only the phone / ssn / passport /
|
|
212
|
+
licence name tokens count, and nearly every value needs at least ``NUMERIC_MIN_DIGITS``
|
|
213
|
+
digits: a number is a quantity unless both the name and the values say otherwise.
|
|
214
|
+
"""
|
|
215
|
+
values = sample.drop_nulls().cast(pl.String).str.strip_chars()
|
|
216
|
+
values = values.filter(values.str.len_chars() > 0)
|
|
217
|
+
if values.len() == 0:
|
|
218
|
+
return None
|
|
219
|
+
tokens = name_tokens(name)
|
|
220
|
+
words = {t for t in tokens if t.isalpha()}
|
|
221
|
+
described = sorted(words & ATTRIBUTE_TOKENS)
|
|
222
|
+
|
|
223
|
+
def token_note(tok: str) -> str:
|
|
224
|
+
return f"column name token '{tok}'"
|
|
225
|
+
|
|
226
|
+
contact = next((t for t in tokens if t in CONTACT_TOKENS), None)
|
|
227
|
+
if numeric:
|
|
228
|
+
if contact and not described and _has_digits(values, NUMERIC_MIN_DIGITS,
|
|
229
|
+
VALUE_MATCH_MIN):
|
|
230
|
+
return PersonalHint(CONTACT_TOKENS[contact], token_note(contact)
|
|
231
|
+
+ f" and values of at least {NUMERIC_MIN_DIGITS} digits")
|
|
232
|
+
return None
|
|
233
|
+
|
|
234
|
+
by_values = _by_values(values)
|
|
235
|
+
if by_values is not None:
|
|
236
|
+
return by_values
|
|
237
|
+
if "birth" in words and words & {"date", "day"}:
|
|
238
|
+
return PersonalHint("date of birth", "column name")
|
|
239
|
+
if described:
|
|
240
|
+
return None
|
|
241
|
+
email = next((t for t in tokens if t in EMAIL_TOKENS), None)
|
|
242
|
+
if email and _share(values.str.contains("@", literal=True)) >= NAME_VALUE_MIN:
|
|
243
|
+
return PersonalHint("e-mail address", token_note(email) + " and values containing '@'")
|
|
244
|
+
if contact and _has_digits(values, CONTACT_MIN_DIGITS, NAME_VALUE_MIN):
|
|
245
|
+
return PersonalHint(CONTACT_TOKENS[contact], token_note(contact)
|
|
246
|
+
+ " and values containing digits")
|
|
247
|
+
others = words - {"name"}
|
|
248
|
+
if "name" in words:
|
|
249
|
+
person = sorted(others & PERSON_QUALIFIERS)
|
|
250
|
+
if person:
|
|
251
|
+
return PersonalHint("person name", f"column name tokens '{person[0]}' and 'name'")
|
|
252
|
+
if n_levels <= WEAK_MIN_LEVELS:
|
|
253
|
+
return None
|
|
254
|
+
many = f" and more than {WEAK_MIN_LEVELS} distinct values"
|
|
255
|
+
if "name" in words:
|
|
256
|
+
org = sorted(others & ORG_QUALIFIERS)
|
|
257
|
+
if org:
|
|
258
|
+
return PersonalHint("organisation name",
|
|
259
|
+
f"column name tokens '{org[0]}' and 'name'" + many)
|
|
260
|
+
if not others:
|
|
261
|
+
return PersonalHint("name", token_note("name") + many)
|
|
262
|
+
alpha = [t for t in tokens if t.isalpha()]
|
|
263
|
+
|
|
264
|
+
def head(vocabulary: frozenset[str], may_follow: frozenset[str]) -> str | None:
|
|
265
|
+
"""The last token of ``vocabulary`` when only ``may_follow`` words come after it."""
|
|
266
|
+
at = [i for i, t in enumerate(alpha) if t in vocabulary]
|
|
267
|
+
if not at or any(t not in may_follow for t in alpha[at[-1] + 1:]):
|
|
268
|
+
return None
|
|
269
|
+
return alpha[at[-1]]
|
|
270
|
+
|
|
271
|
+
address = head(ADDRESS_TOKENS, ADDRESS_TOKENS | FILLER_TOKENS)
|
|
272
|
+
if address and not words & ADDRESS_PART_TOKENS and "name" not in words:
|
|
273
|
+
return PersonalHint("address", token_note(address) + many)
|
|
274
|
+
role = head(ROLE_TOKENS, PERSON_QUALIFIERS | ORG_QUALIFIERS | FILLER_TOKENS)
|
|
275
|
+
if role and "name" not in words:
|
|
276
|
+
return PersonalHint("person or organisation", token_note(role) + many)
|
|
277
|
+
return None
|
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
"""Pseudonymised categoricals (ADR-0010): the labels of ``pseudonym`` columns become tokens.
|
|
2
|
+
|
|
3
|
+
``pseudonymise`` runs once, right after the structural profile and before anything is fitted.
|
|
4
|
+
It returns the frame with every ``pseudonym`` column rewritten: each distinct value is replaced
|
|
5
|
+
by a stand-in token, the same value always by the same token. Marginals, encodings, the joint
|
|
6
|
+
model, targets, diagnostics and suggestions are then computed on that frame exactly as for an
|
|
7
|
+
ordinary categorical, so no code that stores something ever sees a source label of the column.
|
|
8
|
+
No real-to-token map is kept: it lives in this function's local variables only.
|
|
9
|
+
|
|
10
|
+
Tokens
|
|
11
|
+
------
|
|
12
|
+
* **Distinct per level and never a value of the column.** A candidate token that equals any
|
|
13
|
+
source value of the column (rare ones included) or an earlier token is discarded.
|
|
14
|
+
* **Unrelated to the value.** Tokens are handed out in an order drawn from a random stream, not
|
|
15
|
+
in the order of the values, their frequencies or their rows. The stream is seeded with the
|
|
16
|
+
fit seed, the column name and a SHA-256 digest of the column's *whole* set of values and
|
|
17
|
+
counts. The digest is not stored. The same table and seed therefore give the same tokens
|
|
18
|
+
(fitting stays reproducible), while a different table, sample, seed or column gives an
|
|
19
|
+
unrelated assignment; equal tokens in two fingerprints mean nothing. Only someone who
|
|
20
|
+
already holds every value of the column with its count can recompute the assignment, and
|
|
21
|
+
they learn nothing from it. No token is a hash, an encryption or any other function of the
|
|
22
|
+
single value it stands for.
|
|
23
|
+
* **Visibly different in every fingerprint.** Numbered tokens carry a four-character tag
|
|
24
|
+
drawn from the same stream (``company_k7q2_0042``). Two fingerprints, or one table fitted
|
|
25
|
+
with two seeds, therefore never share a token by accident: nobody joins synthetic tables on
|
|
26
|
+
tokens that only happen to be equal, and ``scenarios.merge`` keeps the levels of separately
|
|
27
|
+
fitted fingerprints apart.
|
|
28
|
+
* **Levels the policy keeps get the low numbers.** Levels below ``min_category_support`` are
|
|
29
|
+
pooled into ``__other__`` by the model like any rare level; they are numbered after the kept
|
|
30
|
+
ones, so the tokens that are stored and generated do not reveal how many rare levels exist.
|
|
31
|
+
* **Style** (``token_style``), chosen from the column's values:
|
|
32
|
+
|
|
33
|
+
``email`` most values are e-mail addresses: ``<column>_<tag>_<number>@example.com``.
|
|
34
|
+
``shape`` most values are code-like (digits and punctuation, at most a third letters:
|
|
35
|
+
phone numbers, licence numbers): each token takes one of the column's common
|
|
36
|
+
shapes (``(999) 999-9999``), drawn at random and independently of the value it
|
|
37
|
+
replaces, and fills it with random digits and letters. Integer columns always
|
|
38
|
+
use this style, without leading zeros, so the column keeps its dtype.
|
|
39
|
+
``indexed`` anything else (names, addresses): ``<column>_<tag>_<number>``.
|
|
40
|
+
|
|
41
|
+
Blank values (empty or whitespace only) and a literal ``__other__`` are not labels of anyone and
|
|
42
|
+
stay as they are; nulls stay null.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
|
|
47
|
+
import hashlib
|
|
48
|
+
import math
|
|
49
|
+
import re
|
|
50
|
+
from typing import Any
|
|
51
|
+
|
|
52
|
+
import numpy as np
|
|
53
|
+
import polars as pl
|
|
54
|
+
|
|
55
|
+
from ectype.errors import ProfilingError
|
|
56
|
+
from ectype.fingerprint.disclosure import OTHER
|
|
57
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
|
|
58
|
+
from ectype.io.values import category_labels
|
|
59
|
+
from ectype.rng import stream
|
|
60
|
+
from ectype.types import Role
|
|
61
|
+
|
|
62
|
+
__all__ = ["pseudonymise", "repeat_share", "supports_pseudonym", "token_style",
|
|
63
|
+
"EMAIL_DOMAIN", "TAG_LENGTH", "STYLE_MIN_SHARE", "CODE_MAX_LETTER_SHARE", "SHAPE_MIN_SHARE",
|
|
64
|
+
"SHAPE_MAX", "CAPACITY_FACTOR"]
|
|
65
|
+
|
|
66
|
+
#: reserved domain (RFC 2606) of e-mail style tokens
|
|
67
|
+
EMAIL_DOMAIN = "example.com"
|
|
68
|
+
#: length and alphabet of the per-fingerprint tag of numbered tokens (no vowels, so a tag
|
|
69
|
+
#: spells no word; no characters that are easily confused)
|
|
70
|
+
TAG_LENGTH = 4
|
|
71
|
+
_TAG_ALPHABET = "bcdfghjkmnpqrstvwxz23456789"
|
|
72
|
+
#: share of the levels that must be e-mail addresses / code-like for that token style
|
|
73
|
+
STYLE_MIN_SHARE = 0.9
|
|
74
|
+
#: a code-like value has at least one digit and at most this share of letters among its
|
|
75
|
+
#: letters and digits
|
|
76
|
+
CODE_MAX_LETTER_SHARE = 0.34
|
|
77
|
+
#: a shape is used for tokens when at least this share of the levels have it ...
|
|
78
|
+
SHAPE_MIN_SHARE = 0.05
|
|
79
|
+
#: ... and at most this many shapes are used
|
|
80
|
+
SHAPE_MAX = 8
|
|
81
|
+
#: a shape must offer this many times more strings than the column has values
|
|
82
|
+
CAPACITY_FACTOR = 20
|
|
83
|
+
#: the largest integer a float column represents exactly has 15 safe decimal digits
|
|
84
|
+
_FLOAT_DIGITS = 15
|
|
85
|
+
_MAX_DRAWS = 200
|
|
86
|
+
|
|
87
|
+
_EMAIL = r"^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$"
|
|
88
|
+
_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
89
|
+
_LOWER = _UPPER.lower()
|
|
90
|
+
_DIGITS = "0123456789"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def supports_pseudonym(dtype: pl.DataType, integral: bool = True) -> bool:
|
|
94
|
+
"""Whether a column of ``dtype`` can be pseudonymised: text, or integer codes (an integer
|
|
95
|
+
dtype, or a float column whose values are all whole numbers)."""
|
|
96
|
+
if dtype in (pl.String, pl.Categorical) or isinstance(dtype, pl.Enum):
|
|
97
|
+
return True
|
|
98
|
+
if dtype.is_integer():
|
|
99
|
+
return True
|
|
100
|
+
return bool(dtype.is_float() and integral)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _labels(s: pl.Series) -> pl.Series:
|
|
104
|
+
if s.dtype.is_float():
|
|
105
|
+
s = s.fill_nan(None)
|
|
106
|
+
return category_labels(s)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _is_blank(label: str) -> bool:
|
|
110
|
+
return label.strip() == "" or label == OTHER
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def repeat_share(s: pl.Series, policy: DisclosurePolicySpec) -> float:
|
|
114
|
+
"""Share of the non-null rows of ``s`` whose value occurs at least
|
|
115
|
+
``policy.min_category_support`` times: the part of the column a categorical model keeps as
|
|
116
|
+
levels of their own (the rest is pooled into ``__other__``)."""
|
|
117
|
+
counts = _labels(s).drop_nulls().value_counts(name="__n__").to_series(1).to_numpy()
|
|
118
|
+
total = float(counts.sum())
|
|
119
|
+
if total <= 0:
|
|
120
|
+
return 0.0
|
|
121
|
+
return float(counts[counts >= max(1, int(policy.min_category_support))].sum()) / total
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _slug(name: str) -> str:
|
|
125
|
+
return re.sub(r"[^0-9a-z]+", "_", str(name).lower()).strip("_") or "value"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _shapes(levels: pl.Series) -> pl.Series:
|
|
129
|
+
"""Every letter becomes ``A`` (upper case) or ``a`` (any other letter), every digit ``9``;
|
|
130
|
+
punctuation and spaces are kept."""
|
|
131
|
+
return (levels.str.replace_all(r"\p{Lu}", "A").str.replace_all(r"[^\P{L}A]", "a")
|
|
132
|
+
.str.replace_all(r"\p{Nd}", "9"))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def token_style(levels: pl.Series) -> str:
|
|
136
|
+
"""``"email"``, ``"shape"`` or ``"indexed"`` for a column with these distinct values (see
|
|
137
|
+
the module docstring)."""
|
|
138
|
+
if levels.len() == 0:
|
|
139
|
+
return "indexed"
|
|
140
|
+
if float(levels.str.contains(_EMAIL).mean() or 0.0) >= STYLE_MIN_SHARE: # type: ignore[arg-type]
|
|
141
|
+
return "email"
|
|
142
|
+
digits = levels.str.count_matches(r"\p{Nd}")
|
|
143
|
+
letters = levels.str.count_matches(r"\p{L}")
|
|
144
|
+
code = (digits >= 1) & (letters <= CODE_MAX_LETTER_SHARE * (digits + letters))
|
|
145
|
+
if float(code.mean() or 0.0) >= STYLE_MIN_SHARE: # type: ignore[arg-type]
|
|
146
|
+
return "shape"
|
|
147
|
+
return "indexed"
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _capacity(shape: str, numeric: bool) -> float:
|
|
151
|
+
d = shape.count("9")
|
|
152
|
+
letters = shape.count("A") + shape.count("a")
|
|
153
|
+
if numeric:
|
|
154
|
+
return 9.0 * 10.0 ** max(d - 1, 0) if d else 0.0
|
|
155
|
+
return 10.0 ** d * 26.0 ** letters
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _common_shapes(levels: pl.Series, min_levels: int, n_values: int, numeric: bool
|
|
159
|
+
) -> tuple[list[str], np.ndarray]:
|
|
160
|
+
"""The shapes tokens may take and their weights: shapes of at least ``SHAPE_MIN_SHARE`` of
|
|
161
|
+
the levels that are also held by ``min_levels`` levels (always the most common one), with
|
|
162
|
+
room for ``CAPACITY_FACTOR`` times the column's values."""
|
|
163
|
+
vc = _shapes(levels).alias("shape").value_counts(name="n").sort(
|
|
164
|
+
["n", "shape"], descending=[True, False])
|
|
165
|
+
shapes = [str(x) for x in vc[:, 0].to_list()]
|
|
166
|
+
counts = np.asarray(vc[:, 1].to_list(), dtype=np.float64)
|
|
167
|
+
total = float(counts.sum())
|
|
168
|
+
keep: list[int] = []
|
|
169
|
+
for i, (shape, c) in enumerate(zip(shapes, counts)):
|
|
170
|
+
if len(keep) >= SHAPE_MAX or c < SHAPE_MIN_SHARE * total:
|
|
171
|
+
break
|
|
172
|
+
if i > 0 and c < min_levels:
|
|
173
|
+
break
|
|
174
|
+
if _capacity(shape, numeric) >= CAPACITY_FACTOR * (n_values + 1):
|
|
175
|
+
keep.append(i)
|
|
176
|
+
w = counts[keep]
|
|
177
|
+
return [shapes[i] for i in keep], (w / w.sum() if w.size else w)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _fill(shape: str, rng: np.random.Generator, numeric: bool) -> str:
|
|
181
|
+
out = []
|
|
182
|
+
first_digit = numeric
|
|
183
|
+
for ch in shape:
|
|
184
|
+
if ch == "9":
|
|
185
|
+
lo = 1 if first_digit else 0
|
|
186
|
+
first_digit = False
|
|
187
|
+
out.append(_DIGITS[int(rng.integers(lo, 10))])
|
|
188
|
+
elif ch == "A":
|
|
189
|
+
out.append(_UPPER[int(rng.integers(0, 26))])
|
|
190
|
+
elif ch == "a":
|
|
191
|
+
out.append(_LOWER[int(rng.integers(0, 26))])
|
|
192
|
+
else:
|
|
193
|
+
out.append(ch)
|
|
194
|
+
return "".join(out)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _int_limit(dtype: pl.DataType) -> float:
|
|
198
|
+
if dtype.is_float():
|
|
199
|
+
return 10.0 ** _FLOAT_DIGITS - 1
|
|
200
|
+
try:
|
|
201
|
+
return float(np.iinfo(str(dtype).lower()).max)
|
|
202
|
+
except (TypeError, ValueError):
|
|
203
|
+
return 10.0 ** _FLOAT_DIGITS - 1
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _shape_tokens(name: str, levels: pl.Series, n: int, taken: set[str], min_levels: int,
|
|
207
|
+
rng: np.random.Generator, dtype: pl.DataType | None) -> list[str] | None:
|
|
208
|
+
"""``n`` distinct shape-preserving tokens, none of them in ``taken``; ``None`` when the
|
|
209
|
+
column's shapes have too little room (text columns then use indexed tokens)."""
|
|
210
|
+
numeric = dtype is not None
|
|
211
|
+
shapes, weights = _common_shapes(levels, min_levels, len(taken), numeric)
|
|
212
|
+
limit = _int_limit(dtype) if dtype is not None else math.inf
|
|
213
|
+
if numeric:
|
|
214
|
+
fits = [i for i, s in enumerate(shapes) if 10.0 ** max(s.count("9") - 1, 0) <= limit]
|
|
215
|
+
shapes, weights = [shapes[i] for i in fits], weights[fits]
|
|
216
|
+
if not shapes:
|
|
217
|
+
# no common digit count has room: use the shortest width that does
|
|
218
|
+
d = max(2, math.ceil(math.log10(CAPACITY_FACTOR * (len(taken) + n + 1) / 9.0)) + 1)
|
|
219
|
+
if 10.0 ** (d - 1) > limit:
|
|
220
|
+
raise ProfilingError(
|
|
221
|
+
f"cannot pseudonymise column {name!r}: its integer dtype {dtype} has no "
|
|
222
|
+
f"room for distinct stand-in codes; cast the column to strings first")
|
|
223
|
+
shapes, weights = ["9" * d], np.ones(1)
|
|
224
|
+
weights = weights / weights.sum()
|
|
225
|
+
if not shapes:
|
|
226
|
+
return None
|
|
227
|
+
used = set(taken)
|
|
228
|
+
out: list[str] = []
|
|
229
|
+
picks = rng.choice(len(shapes), size=n, p=weights)
|
|
230
|
+
for k in picks:
|
|
231
|
+
for attempt in range(_MAX_DRAWS):
|
|
232
|
+
# after repeated collisions fall back to the roomiest shape
|
|
233
|
+
shape = shapes[int(k)] if attempt < _MAX_DRAWS // 2 else max(
|
|
234
|
+
shapes, key=lambda s: _capacity(s, numeric))
|
|
235
|
+
tok = _fill(shape, rng, numeric)
|
|
236
|
+
if tok in used or (numeric and float(tok) > limit):
|
|
237
|
+
continue
|
|
238
|
+
used.add(tok)
|
|
239
|
+
out.append(tok)
|
|
240
|
+
break
|
|
241
|
+
else:
|
|
242
|
+
raise ProfilingError(f"cannot pseudonymise column {name!r}: no room for distinct "
|
|
243
|
+
f"tokens in its value shapes")
|
|
244
|
+
return out
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _indexed_tokens(name: str, n: int, taken: set[str], email: bool,
|
|
248
|
+
rng: np.random.Generator) -> list[str]:
|
|
249
|
+
tag = "".join(_TAG_ALPHABET[int(i)]
|
|
250
|
+
for i in rng.integers(0, len(_TAG_ALPHABET), TAG_LENGTH))
|
|
251
|
+
prefix = f"{_slug(name)}_{tag}"
|
|
252
|
+
width = max(2, len(str(n)))
|
|
253
|
+
suffix = f"@{EMAIL_DOMAIN}" if email else ""
|
|
254
|
+
out: list[str] = []
|
|
255
|
+
i = 0
|
|
256
|
+
while len(out) < n:
|
|
257
|
+
i += 1
|
|
258
|
+
tok = f"{prefix}_{i:0{width}d}{suffix}"
|
|
259
|
+
if tok not in taken:
|
|
260
|
+
out.append(tok)
|
|
261
|
+
return out
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _stream(seed: int, name: str, levels: list[str], counts: list[int]) -> np.random.Generator:
|
|
265
|
+
"""The column's token stream: seeded from the fit seed, the column name and a digest of
|
|
266
|
+
every value with its count (see the module docstring). Nothing of it is stored."""
|
|
267
|
+
h = hashlib.sha256()
|
|
268
|
+
h.update(f"ectype.pseudonym\x1f{int(seed)}\x1f{name}\x1f".encode("utf-8", "surrogatepass"))
|
|
269
|
+
for label, count in sorted(zip(levels, counts)):
|
|
270
|
+
h.update(label.encode("utf-8", "surrogatepass"))
|
|
271
|
+
h.update(f"\x1e{int(count)}\x1f".encode())
|
|
272
|
+
return stream(int.from_bytes(h.digest()[:16], "little"), "pseudonym", name)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _describe(style: str, tokens: list[str], levels: pl.Series) -> str:
|
|
276
|
+
if style == "shape":
|
|
277
|
+
shapes = sorted(set(_shapes(pl.Series(levels.name, tokens[:1000], dtype=pl.String))
|
|
278
|
+
.to_list()))
|
|
279
|
+
shown = ", ".join(repr(s) for s in shapes[:3]) + (", ..." if len(shapes) > 3 else "")
|
|
280
|
+
return (f"stand-in codes that keep the column's common shape(s) {shown} with random "
|
|
281
|
+
f"digits and letters")
|
|
282
|
+
example = tokens[0] if tokens else ""
|
|
283
|
+
return (f"numbered stand-in tokens such as {example!r} (numbered in random order; the "
|
|
284
|
+
f"tag before the number is specific to this fingerprint)")
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _pseudonymise_column(s: pl.Series, col: ColumnSchema, policy: DisclosurePolicySpec,
|
|
288
|
+
seed: int) -> tuple[pl.Series, ColumnSchema, dict[str, Any]]:
|
|
289
|
+
dtype = s.dtype
|
|
290
|
+
integral = True
|
|
291
|
+
if dtype.is_float():
|
|
292
|
+
nn = s.fill_nan(None).drop_nulls()
|
|
293
|
+
integral = bool((nn == nn.round(0)).all()) if nn.len() else True
|
|
294
|
+
if not supports_pseudonym(dtype, integral):
|
|
295
|
+
raise ProfilingError(
|
|
296
|
+
f"column {col.name!r} ({dtype}) cannot have the role 'pseudonym': it needs text "
|
|
297
|
+
f"or integer codes (cast the column to strings to pseudonymise it anyway)")
|
|
298
|
+
numeric = dtype.is_numeric()
|
|
299
|
+
labels = _labels(s)
|
|
300
|
+
vc = labels.drop_nulls().value_counts(name="__n__")
|
|
301
|
+
all_levels = [str(x) for x in vc[:, 0].to_list()]
|
|
302
|
+
all_counts = [int(x) for x in vc[:, 1].to_list()]
|
|
303
|
+
rng = _stream(seed, col.name, all_levels, all_counts)
|
|
304
|
+
|
|
305
|
+
support = max(1, int(policy.min_category_support))
|
|
306
|
+
real = sorted((lv, c) for lv, c in zip(all_levels, all_counts) if not _is_blank(lv))
|
|
307
|
+
kept = [lv for lv, c in real if c >= support]
|
|
308
|
+
rare = [lv for lv, c in real if c < support]
|
|
309
|
+
# kept levels first, each group in an order drawn from the stream
|
|
310
|
+
ordered = ([kept[i] for i in rng.permutation(len(kept))]
|
|
311
|
+
+ [rare[i] for i in rng.permutation(len(rare))])
|
|
312
|
+
level_series = pl.Series(col.name, [lv for lv, _ in real], dtype=pl.String)
|
|
313
|
+
taken = set(all_levels)
|
|
314
|
+
style = "shape" if numeric else token_style(level_series)
|
|
315
|
+
tokens: list[str] | None = None
|
|
316
|
+
if style == "shape":
|
|
317
|
+
tokens = _shape_tokens(col.name, level_series, len(ordered), taken, support, rng,
|
|
318
|
+
dtype if numeric else None)
|
|
319
|
+
if tokens is None:
|
|
320
|
+
style = "indexed"
|
|
321
|
+
if tokens is None:
|
|
322
|
+
tokens = _indexed_tokens(col.name, len(ordered), taken, style == "email", rng)
|
|
323
|
+
|
|
324
|
+
old = ordered + [lv for lv in all_levels if _is_blank(lv)]
|
|
325
|
+
new = tokens + [lv for lv in all_levels if _is_blank(lv)]
|
|
326
|
+
if old:
|
|
327
|
+
out = labels.replace_strict(pl.Series(old, dtype=pl.String),
|
|
328
|
+
pl.Series(new, dtype=pl.String), default=None,
|
|
329
|
+
return_dtype=pl.String)
|
|
330
|
+
else:
|
|
331
|
+
out = labels
|
|
332
|
+
physical = col.physical_dtype
|
|
333
|
+
if numeric:
|
|
334
|
+
out = out.cast(dtype)
|
|
335
|
+
elif dtype == pl.Categorical:
|
|
336
|
+
out = out.cast(pl.Categorical)
|
|
337
|
+
elif isinstance(dtype, pl.Enum):
|
|
338
|
+
physical = "String" # the Enum dtype lists the source labels
|
|
339
|
+
note = (f"pseudonymised: every value replaced by {_describe(style, tokens, level_series)}; "
|
|
340
|
+
f"no source value of this column is stored or generated")
|
|
341
|
+
schema = col.model_copy(update={"physical_dtype": physical, "pattern": None,
|
|
342
|
+
"min_value": None, "max_value": None, "decimals": None,
|
|
343
|
+
"integer_valued": False, "bool_labels": None,
|
|
344
|
+
"notes": [*col.notes, note]})
|
|
345
|
+
return out.alias(col.name), schema, {"token_style": style}
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def pseudonymise(df: pl.DataFrame, columns: list[ColumnSchema], policy: DisclosurePolicySpec,
|
|
349
|
+
seed: int) -> tuple[pl.DataFrame, list[ColumnSchema], dict[str, Any]]:
|
|
350
|
+
"""Replace the values of every ``pseudonym`` column of ``df`` by tokens.
|
|
351
|
+
|
|
352
|
+
Returns the rewritten frame, the column schemas (each pseudonym column with a note on its
|
|
353
|
+
tokens; an ``Enum`` dtype, which would list the source labels, recorded as ``String``) and
|
|
354
|
+
a diagnostics dict ``{column: {"token_style": ...}}``. ``df`` is returned unchanged when
|
|
355
|
+
no column has the role.
|
|
356
|
+
"""
|
|
357
|
+
diag: dict[str, Any] = {}
|
|
358
|
+
out_cols: list[ColumnSchema] = []
|
|
359
|
+
replaced: list[pl.Series] = []
|
|
360
|
+
for col in columns:
|
|
361
|
+
if col.role != Role.PSEUDONYM or col.name not in df.columns:
|
|
362
|
+
out_cols.append(col)
|
|
363
|
+
continue
|
|
364
|
+
series, schema, info = _pseudonymise_column(df.get_column(col.name), col, policy, seed)
|
|
365
|
+
replaced.append(series)
|
|
366
|
+
out_cols.append(schema)
|
|
367
|
+
diag[col.name] = info
|
|
368
|
+
if replaced:
|
|
369
|
+
df = df.with_columns(replaced)
|
|
370
|
+
return df, out_cols, diag
|