nyms#
nyms: reversible pseudonymisation of text before it reaches an AI.
A deterministic (non-AI) pass detects personal and sensitive identifiers in Danish and English text, replaces them with surrogates from a configurable strategy, remembers the mapping per project so the same person is the same pseudonym in every document, and puts the originals back into whatever the AI answers.
>>> from nyms import Pseudonymiser
>>> p = Pseudonymiser(store={})
>>> p.pseudonymise("Mail hans.jensen@example.dk, tlf. 12 34 56 78").text
'Mail [EMAIL_1], tlf. [PHONE_1]'
Functions
|
The deterministic detector set. |
|
Run detectors (default: |
|
A detector for a list of known names (full names or first names), case-insensitive. |
|
Detectors for what a project already knows: its values, their name components, its surrogates. |
|
A |
|
The identity of a value for the purpose of "same surrogate". |
|
Rebuild text with each span replaced by its string. |
|
Keep a non-overlapping subset of spans, best first by priority, in text order. |
|
The stand-alone tool: a keyed hash of value, as readable words. |
|
Render data as n words from wordlist (default: the EFF short list). |
Classes
|
The facade. |
|
What |
|
What |
|
A regex detector with an optional validator and context words. |
|
Anything that turns text into spans. |
|
Records keyed by surrogate, with an in-memory index by |
|
What to do with detected spans. |
|
One detected occurrence of an entity in a text. |
|
The user's own surrogates for some values; fallback for the rest. |
|
|
|
Keyed hash (HMAC-SHA-256) rendered as readable words. |
|
Random readable words (a tokenisation vault): no key, no information about the value. |
|
One entity type and its place in the taxonomy. |
- class nyms.Aliases(aliases, fallback=Counter())[source]#
Bases:
objectThe user’s own surrogates for some values; fallback for the rest.
Keys are compared casefolded and whitespace-collapsed.
>>> a = Aliases({'Hans Jensen': 'Mr Green'}, fallback=Counter()) >>> a('PERSON', 'hans jensen', vault=_EmptyVault()), a('PERSON', 'Else Berg', vault=_EmptyVault()) ('Mr Green', '[PERSON_1]')
- class nyms.Counter(template='[{type}_{n}]')[source]#
Bases:
object[PERSON_1]-style typed counters, numbered per entity type within the project.
- class nyms.Detector(name, entity_type, pattern, score=1.0, validate=None, group=0, context=tuple(), value_of=None)[source]#
Bases:
objectA regex detector with an optional validator and context words.
validate(match)may returnFalse(drop),True/None(keep the base score) or a float (use it as the score).grouppicks the capture group that is the span (the whole match by default).value_of(match)may name the canonical value the span stands for when it differs from the matched text.
- class nyms.DetectorLike(*args, **kwargs)[source]#
Bases:
ProtocolAnything that turns text into spans.
nameandentity_typeare optional.
- class nyms.EntityType(name, identifier_class, tier, description='', aliases=tuple())[source]#
Bases:
objectOne entity type and its place in the taxonomy.
- class nyms.KeyedWords(key, n_words=2, wordlist=None, templates=<factory>, default_template='[{type}:{words}]')[source]#
Bases:
objectKeyed hash (HMAC-SHA-256) rendered as readable words. Deterministic under one key.
- class nyms.MappingStore(store=None, *, strategy=None)[source]#
Bases:
objectRecords keyed by surrogate, with an in-memory index by
(entity_type, normalised).- add(entity_type, text, *, surrogate=None)[source]#
Create a record for a new value (with a given surrogate, or one from the strategy).
- Return type:
- add_alias_form(surrogate, entity_type, text)[source]#
Make text (a surname alone, say) resolve to an existing record’s surrogate.
- Return type:
- alias(entity_type, text, surrogate)[source]#
Choose the surrogate for a value yourself (before it is first seen).
- Return type:
- resolve(entity_type, text)[source]#
(surrogate, suffix)for text, creating the surrogate if the value is new.suffix is a genitive ending found on an already known value, to be re-attached after the surrogate (
[PERSON_1]+s). It is empty for a new value: nyms does not guess that an unknown...sis a genitive; if the base form appears later the record is relinked to it.
- class nyms.Policy(name='default', include=None, exclude=frozenset({}), min_score=0.5, min_score_by_type=dict(), allow=frozenset({}), deny=frozenset({}), keep=None)[source]#
Bases:
objectWhat to do with detected spans. See the module docstring.
- accepts(span)[source]#
Whether span gets replaced under this policy (post-detection decision).
- Return type:
- detector_filter(detectors)[source]#
The detectors whose entity type this policy wants; a pre-detection filter.
- Return type:
- class nyms.Pseudonymiser(project='default', *, detectors=None, post_detectors=(), policy=None, strategy=None, store=None, key=None, names=(), rootdir=None, encrypt=False, prefilter=False)[source]#
Bases:
objectThe facade. See the module docstring for the seams.
- class nyms.RandomWords(n_words=2, wordlist=None, templates=<factory>, default_template='[{type}:{words}]')[source]#
Bases:
objectRandom readable words (a tokenisation vault): no key, no information about the value.
- class nyms.Reidentified(text, restored, unmatched)[source]#
Bases:
objectWhat
Pseudonymiser.reidentify()returns.
- class nyms.Result(text, replaced, kept, replacements, report=dict(), post_replacements=list())[source]#
Bases:
objectWhat
Pseudonymiser.pseudonymise()returns. Spans refer to the NFC-normalised input.
- class nyms.Span(start, end, entity_type, text, score=1.0, detector='', value=None)[source]#
Bases:
objectOne detected occurrence of an entity in a text.
- nyms.apply_replacements(text, replacements)[source]#
Rebuild text with each span replaced by its string. Spans must not overlap.
>>> apply_replacements('a b c', [(Span(2, 3, 'X', 'b'), 'B')]) 'a B c'
- Return type:
- nyms.default_detectors(*, names=(), languages=('da', 'en'))[source]#
The deterministic detector set. names are the parties you already know.
Order does not matter for the result (overlaps are resolved afterwards), only for the report’s grouping.
- nyms.detect(text, detectors=None)[source]#
Run detectors (default:
default_detectors()) and resolve overlaps.
- nyms.gazetteer_detector(names, *, name='gazetteer', entity_type='PERSON', score=1.0, surname_tail=True, value_of_name=None, single_word_score=0.85)[source]#
A detector for a list of known names (full names or first names), case-insensitive.
A first name followed by capitalised words extends to the full name when surname_tail is true. A genitive
son the last word stays in the span; the mapping store decides whether it is a genitive of a known value. value_of_name may map the matched text to the canonical value it stands for (a surname to the full name).>>> d = gazetteer_detector(['Rasmus']) >>> [s.text for s in d('Rasmus Jensens bil, og Rasmus selv.')] ['Rasmus Jensens', 'Rasmus']
- Return type:
- nyms.known_values_detectors(records, *, extra_names=(), score=1.0)[source]#
Detectors for what a project already knows: its values, their name components, its surrogates.
every original in the mapping, by type: names through
gazetteer_detector()(word boundaries, genitive), everything else literally;for persons, each component (first name or surname) that identifies exactly one known person, standing for the full name (
Span.value), scored above a lone first name from the bundled list so the known person wins;every surrogate already issued, as
SURROGATE_TYPE, so the project’s own surrogates are never re-detected as names when pseudonymised text is processed again.
- nyms.local_mapping_store(project='default', *, rootdir=None, codec=None)[source]#
A
dolfile store of records under the project dir, optionally through codec.codec is a pair
(encode: bytes -> bytes, decode: bytes -> bytes)applied to the JSON bytes of each record; seeencrypted(). The project’smeta.jsonrecords which codec the store was created with; a mismatch raisesStoreError.- Return type:
- nyms.normalise(entity_type, text)[source]#
The identity of a value for the purpose of “same surrogate”.
>>> normalise('CPR', '010190-1234'), normalise('PERSON', ' Hans JENSEN '), normalise('EMAIL', 'A@B.dk') ('0101901234', 'hans jensen', 'a@b.dk')
- Return type:
- nyms.readable(value, *, key, entity_type='VALUE', n_words=2, wordlist=None)[source]#
The stand-alone tool: a keyed hash of value, as readable words.
>>> readable('010190-1234', key=b'0' * 32) == readable('010190-1234', key=b'0' * 32) True >>> readable('010190-1234', key=b'0' * 32) != readable('010190-1234', key=b'1' * 32) True
- Return type:
- nyms.resolve_overlaps(spans, *, priority=<function default_priority>)[source]#
Keep a non-overlapping subset of spans, best first by priority, in text order.
>>> s = [Span(0, 4, 'A', 'aaaa', 0.5), Span(2, 6, 'B', 'bbbb', 0.9), Span(8, 9, 'C', 'c')] >>> [x.entity_type for x in resolve_overlaps(s)] ['B', 'C']
- nyms.words_from_bytes(data, *, n=2, wordlist=None)[source]#
Render data as n words from wordlist (default: the EFF short list).
The integer value of the bytes is written in base
len(wordlist); the lowest n digits become words. Each word of the default list carries log2(1296) = 10.3 bits, so two words identify about 1.7 million values and three about 2.2 billion.>>> words_from_bytes(bytes([0, 0, 0, 1]), n=2) ['aardvark', 'abandoned']
Modules
The facade: detect, pseudonymise, re-identify, check. |
|
Bundled data files (data), shipped inside the wheel. |
|
Key management for a single user or a small team: where the project's secret lives. |
|
The reversible mapping store: surrogate <-> original, per project, on a |
|
The sensitivity policy: which detected spans get replaced, which are kept and reported. |
|
Spans: where a detector found something, and how findings are merged and applied. |
|
Surrogate (pseudonym) generation: what replaces a detected value. |
|
The entity taxonomy: what kinds of things nyms detects, and how sensitive each is. |
|
The SSOT of operations: plain functions, JSON-able in and out, surface-agnostic. |