> built 2026-11-24 04:38 UTC from e9a34f1 (main) · nyms 0.0.4. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# nyms

Reversible pseudonymisation of text before it reaches an AI. A deterministic (non-AI) pass finds personal and sensitive identifiers in Danish and English text, replaces them with surrogates, remembers the mapping per project so the same person is `[PERSON_1]` in every document, and puts the originals back into whatever the AI answers.

```bash
pip install nyms            # add "nyms[crypto]" for an encrypted mapping store
```

```python
from nyms import Pseudonymiser

p = Pseudonymiser("case-2026", names=["Rasmus Østergaard Jensen"])
r = p.pseudonymise("Rasmus Jensen (CPR 010190-1234) skylder 12.500 kr. Rasmus Jensens advokat ringede.")
r.text
# '[PERSON_1] (CPR [CPR_1]) skylder [AMOUNT_1]. [PERSON_1]s advokat ringede.'
p.reidentify("Svar: [PERSON_1] skal betale [AMOUNT_1].").text
# 'Svar: Rasmus Jensen skal betale 12.500 kr.'
p.check("Rasmus Jensen bor her")      # what would leak if this were sent
# ['Rasmus Jensen']
```

The same four verbs from the shell:

```bash
nyms pseudonymise --path letter.md --project case-2026 --names "Rasmus Østergaard Jensen" --out letter.pseud.md
nyms reidentify --path answer.md --project case-2026 --out answer.clear.md
nyms check --path draft.md --project case-2026       # {"ok": false, "leaks": [...]} if an original is in it
nyms detect "Rasmus Jensen, tlf. 12 34 56 78"        # every span and the policy's decision; nothing stored
nyms readable 010190-1234 --project case-2026        # a keyed hash as two readable words
```

Content is positional text or `--path` (a file, or `-` for stdin), never guessed from one another.

```bash
```

`r.report` says what was replaced (by type and by detector), what was detected and kept (dates, postcodes and URLs, under the default policy) and which detectors ran, and ends with the caveat that this is pseudonymisation, not anonymisation.

## What it finds

Danish: CPR numbers (the date part must be valid; the pre-2007 modulus-11 check only raises confidence, because numbers issued since October 2007 need not pass it), CVR numbers (modulus-11 and context), DK VAT numbers, phone numbers, bank account numbers (registreringsnummer and kontonummer), IBAN (mod-97), street addresses with floor and postcode, postcode and town, amounts (`12.500 kr.`, `DKK 12.500`, `36.000,-`), dates, court and journal numbers. English: addresses, phone numbers, amounts (`£4,250.00`, `$5,000`), dates. Both: e-mail, URLs, IBAN, credentials (API keys, tokens, private keys), organisation names by legal form (`ApS`, `A/S`, `Ltd`, `GmbH`), names after a title (`Hr.`, `advokat`, `Mr`, `Dr`), names from a bundled Danish and English first-name list, names you pass in (`names=`), and a low-confidence heuristic for capitalised sequences.

Once a value has been replaced anywhere in a project, every later occurrence is replaced too, including a Danish genitive (`Rasmus Jensens` becomes `[PERSON_1]s`), ALL-CAPS headings, and a surname or first name alone when it identifies exactly one known person (`Jensen blev` becomes `[PERSON_1] blev`). An identifier inside something the policy keeps (a CPR number in a URL) is still replaced. Pseudonymising already pseudonymised text changes nothing.

It does not find: names it has never seen and the heuristic misses, roles and rare facts that identify without an identifier, inflected compounds, OCR-damaged identifiers. The report’s `kept` list and the `check` command exist so a reader sees what stayed.

## Choosing what is sensitive

A `Policy` decides after detection, so the report can say what it saw and kept. `Policy.default()` replaces credentials, persons, CPR, e-mail, phone, addresses, IBAN, bank accounts, case numbers, CVR, organisations and amounts; `Policy.identifiers()` leaves amounts and organisations; `Policy.strict()` replaces everything detected, dates and postcodes included. `include`, `exclude`, per-type `min_score`, `allow` (never replace) and `deny` (always replace) lists refine any of them. The taxonomy behind the types, with tiers and the equivalent Presidio, Google DLP and HIPAA names, is `nyms.taxonomy.ENTITY_TYPES`.

## Choosing the surrogates

| Strategy                       | Example                                 | When                                                                                 |
|--------------------------------|-----------------------------------------|--------------------------------------------------------------------------------------|
| `Counter()` (default)          | `[PERSON_1]`, `[CPR_2]`                 | the form LLMs alter least in the one published benchmark; numbered per project       |
| `KeyedWords(key)`              | `Alder Brook`, `[CPR:mustard-suitcase]` | the same surrogate on any machine that has the key, no shared store needed; readable |
| `RandomWords()`                | `Lunar Cobweb`                          | a classic tokenisation vault: random, readable, no key                               |
| `Aliases({...}, fallback=...)` | `the landlord`                          | you choose the pseudonym for some values yourself                                    |

`KeyedWords` is an HMAC-SHA-256 under the project key rendered as words from the EFF short wordlist (1,296 words, 10.3 bits each). The renderer stands alone as `nyms.readable(value, key=...)` and `nyms readable`. There is no unkeyed option: a plain hash of a CPR number is undone by enumerating the ten billion candidates.

Re-identification is tolerant of what models do to bracketed tokens (case, spacing, a dropped bracket, a genitive after it); name-shaped surrogates and aliases are matched exactly, so ordinary prose is left alone. It never guesses: tokens it did not issue come back in `unmatched`.

## Where the mapping and the key live

The mapping store (surrogate, original, type) is the key to the text. By default it is a set of JSON files under `~/.local/share/nyms/<project>/mapping/`, and the project key is 32 random bytes in `~/.config/nyms/keys/<project>.key` (mode 0600), created on first use; `NYMS_KEY` in the environment overrides it, and `Pseudonymiser(..., key=...)` accepts any bytes. With `pip install "nyms[crypto]"` and `encrypt=True` the records are Fernet-encrypted under the key before they hit disk; without it they are plaintext in your user directory, which is the trade-off of needing no dependency. Lose the store and `[PERSON_1]` cannot be reversed; lose the key and an encrypted store cannot be read. Back both up, apart from each other.

Any `MutableMapping` works as the store (`store=`), so [dol](https://github.com/i2mint/dol) backends (SQLite, S3) drop in, and `store={}` keeps a run in memory.

## For AI agents

<!-- epythet:agentic-readme:start -->

`nyms` ships a skill for coding agents, in [Agent Skills](https://agentskills.io) format:

```bash
gh skill install thorwhalen/nyms nyms --agent claude-code     # or copilot, cursor, codex, gemini
```

| Skill   | Use it to                                                                                              |
|---------|--------------------------------------------------------------------------------------------------------|
| `nyms`  | pseudonymise documents before they reach a model, re-identify the answer, and check that nothing leaks |

The skill folder also ships inside the wheel: `python -c "import nyms, os; print(os.path.join(nyms.__path__[0], 'data', 'skills'))"`.

<!-- epythet:agentic-readme:end -->

## Design

The research behind the design (terminology and regulation, detection libraries and methods, surrogates and key management, pipeline architecture) is in [`docs/research/`](), with a [synthesis](); the decisions are in [`docs/adr/`](). Six seams, each one keyword argument of `Pseudonymiser`: `detectors`, `post_detectors`, `policy`, `strategy`, `store`, `key`. The model-based second pass is the `post_detectors` seam: any callable `text -> spans`, run on the already-pseudonymised text with the surrogates protected; none ships in v1.

The EFF wordlist is CC BY 3.0 (see `nyms/data/wordlists/NOTICE.md`). Everything else is MIT.

<p class="epythet-aggregates">This documentation as a single file: <a href="nyms.md">nyms.md</a> (Markdown, for agents).</p>


# _autosummary/nyms.core.html.md

# nyms.core

The facade: detect, pseudonymise, re-identify, check. One object, six seams.

```default
from nyms import Pseudonymiser
p = Pseudonymiser('case-2026', names=['Rasmus Jensen'])
result = p.pseudonymise(text)      # result.text goes to the AI; result.report says what happened
answer = p.reidentify(ai_output)   # answer.text has the originals back; answer.unmatched lists invented tokens
p.check(outgoing_text)             # originals that would leak, before anything is sent
```

The seams, each one keyword argument of [`Pseudonymiser`](_autosummary/nyms.core.html.md#nyms.core.Pseudonymiser):

Not seams, written directly on purpose: the span data model, the report’s shape, the
tolerant re-identification matcher, the order of the stages.

How a run works. The text is NFC-normalised. Stage 1: every detector’s spans, overlap
resolution (strong spans before weak, longer before shorter), the policy’s split into
replaced and kept; an accepted span nested inside a kept one (a CPR number inside a URL the
policy keeps) is still replaced. New values enter the mapping, and a second pass adds
detectors for everything the project knows (its values, name components, its own surrogates)
so every occurrence is consistent. Stage 2, when `post_detectors` are given: they run on the
pseudonymised text, where the surrogates are protected from re-detection, and what they find
is replaced and added to the mapping too.

```pycon
>>> p = Pseudonymiser(store={})
>>> r = p.pseudonymise("Rasmus Jensen (CPR 010190-1234) skylder 12.500 kr. Rasmus Jensens advokat ringede.")
>>> r.text
'[PERSON_1] (CPR [CPR_1]) skylder [AMOUNT_1]. [PERSON_1]s advokat ringede.'
>>> p.reidentify("Svar: [PERSON_1] skal betale [AMOUNT_1]. [person 1]s sag.").text
'Svar: Rasmus Jensen skal betale 12.500 kr. Rasmus Jensens sag.'
>>> p.check("Rasmus Jensen bor her")
['Rasmus Jensen']
>>> p.pseudonymise(r.text).text == r.text   # idempotent: surrogates are never re-detected
True
```

### Module Attributes

| [`PROMOTABLE_TYPES`](_autosummary/nyms.core.html.md#nyms.core.PROMOTABLE_TYPES)   | structured identifiers, whose match is unambiguous.   |
|---------------------------------------------------------------------|-------------------------------------------------------|

### Classes

| [`Pseudonymiser`](_autosummary/nyms.core.html.md#nyms.core.Pseudonymiser)([project, detectors, ...])          | The facade.                                  |
|----------------------------------------------------------------------------------------------------|----------------------------------------------|
| [`Reidentified`](_autosummary/nyms.core.html.md#nyms.core.Reidentified)(text, restored, unmatched)           | What `Pseudonymiser.reidentify()` returns.   |
| [`Result`](_autosummary/nyms.core.html.md#nyms.core.Result)(text, replaced, kept, replacements[, ...]) | What `Pseudonymiser.pseudonymise()` returns. |

### nyms.core.PROMOTABLE_TYPES *= frozenset({'BANK_ACCOUNT', 'CASE_ID', 'CPR', 'CREDENTIAL', 'CVR', 'EMAIL', 'IBAN', 'PHONE'})*

structured identifiers, whose match is
unambiguous. Names are not (a first name inside a kept date: “1. Maj 2024”).

* **Type:**
  Entity types promoted out of a kept container span

### *class* nyms.core.Pseudonymiser(project='default', , detectors=None, post_detectors=(), policy=None, strategy=None, store=None, key=None, names=(), rootdir=None, encrypt=False, prefilter=False)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The facade. See the module docstring for the seams.

#### check(text)

Originals from the mapping that occur in *text*: what would leak if it were sent.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### *class* nyms.core.Reidentified(text, restored, unmatched)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What `Pseudonymiser.reidentify()` returns.

### *class* nyms.core.Result(text, replaced, kept, replacements, report=dict(), post_replacements=list())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What `Pseudonymiser.pseudonymise()` returns. Spans refer to the NFC-normalised input.

#### *property* mapping *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [str](https://docs.python.org/3/builtins/stdtypes.html#str)]*

`{surrogate: original}` for this run only. Sensitive.

#### post_replacements *: [list](https://docs.python.org/3/builtins/stdtypes.html#list)[[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[Span](_autosummary/nyms.spans.html.md#nyms.spans.Span), [str](https://docs.python.org/3/builtins/stdtypes.html#str)]]*

Stage-2 replacements (`post_detectors`), with offsets in the stage-1 output.


# _autosummary/nyms.data.html.md

# nyms.data

Bundled data files (data), shipped inside the wheel.

### Modules

| [`names`](_autosummary/nyms.data.names.html.md#module-nyms.data.names)         | Bundled data files (names), shipped inside the wheel.     |
|---------------------------------------------------------------------------------------|-----------------------------------------------------------|
| [`wordlists`](_autosummary/nyms.data.wordlists.html.md#module-nyms.data.wordlists) | Bundled data files (wordlists), shipped inside the wheel. |


# _autosummary/nyms.data.names.html.md

# nyms.data.names

Bundled data files (names), shipped inside the wheel.


# _autosummary/nyms.data.wordlists.html.md

# nyms.data.wordlists

Bundled data files (wordlists), shipped inside the wheel.


# _autosummary/nyms.html.md

# 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.

```pycon
>>> 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

| [`default_detectors`](_autosummary/nyms.html.md#nyms.default_detectors)(\*[, names, languages])      | The deterministic detector set.                                                                                       |
|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
| [`detect`](_autosummary/nyms.html.md#nyms.detect)(text[, detectors])                      | Run *detectors* (default: [`default_detectors()`](_autosummary/nyms.html.md#nyms.default_detectors)) and resolve overlaps. |
| [`gazetteer_detector`](_autosummary/nyms.html.md#nyms.gazetteer_detector)(names, \*[, name, ...])     | A detector for a list of known names (full names or first names), case-insensitive.                                   |
| [`known_values_detectors`](_autosummary/nyms.html.md#nyms.known_values_detectors)(records, \*[, ...])     | Detectors for what a project already knows: its values, their name components, its surrogates.                        |
| [`local_mapping_store`](_autosummary/nyms.html.md#nyms.local_mapping_store)([project, rootdir, codec]) | A `dol` file store of records under the project dir, optionally through *codec*.                                      |
| [`normalise`](_autosummary/nyms.html.md#nyms.normalise)(entity_type, text)                   | The identity of a value for the purpose of "same surrogate".                                                          |
| [`apply_replacements`](_autosummary/nyms.html.md#nyms.apply_replacements)(text, replacements)         | Rebuild *text* with each span replaced by its string.                                                                 |
| [`resolve_overlaps`](_autosummary/nyms.html.md#nyms.resolve_overlaps)(spans, \*[, priority])        | Keep a non-overlapping subset of *spans*, best first by *priority*, in text order.                                    |
| [`readable`](_autosummary/nyms.html.md#nyms.readable)(value, \*, key[, entity_type, ...])   | The stand-alone tool: a keyed hash of *value*, as readable words.                                                     |
| [`words_from_bytes`](_autosummary/nyms.html.md#nyms.words_from_bytes)(data, \*[, n, wordlist])      | Render *data* as *n* words from *wordlist* (default: the EFF short list).                                             |

### Classes

| [`Pseudonymiser`](_autosummary/nyms.html.md#nyms.Pseudonymiser)([project, detectors, ...])          | The facade.                                                                           |
|----------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| [`Reidentified`](_autosummary/nyms.html.md#nyms.Reidentified)(text, restored, unmatched)           | What `Pseudonymiser.reidentify()` returns.                                            |
| [`Result`](_autosummary/nyms.html.md#nyms.Result)(text, replaced, kept, replacements[, ...]) | What `Pseudonymiser.pseudonymise()` returns.                                          |
| [`Detector`](_autosummary/nyms.html.md#nyms.Detector)(name, entity_type, pattern[, ...])       | A regex detector with an optional validator and context words.                        |
| [`DetectorLike`](_autosummary/nyms.html.md#nyms.DetectorLike)(\*args, \*\*kwargs)                  | Anything that turns text into spans.                                                  |
| [`MappingStore`](_autosummary/nyms.html.md#nyms.MappingStore)([store, strategy])                   | Records keyed by surrogate, with an in-memory index by `(entity_type, normalised)`.   |
| [`Policy`](_autosummary/nyms.html.md#nyms.Policy)([name, include, exclude, min_score, ...])  | What to do with detected spans.                                                       |
| [`Span`](_autosummary/nyms.html.md#nyms.Span)(start, end, entity_type, text[, score, ...]) | One detected occurrence of an entity in a text.                                       |
| [`Aliases`](_autosummary/nyms.html.md#nyms.Aliases)(aliases[, fallback])                      | The user's own surrogates for some values; *fallback* for the rest.                   |
| [`Counter`](_autosummary/nyms.html.md#nyms.Counter)([template])                               | `[PERSON_1]`-style typed counters, numbered per entity type within the project.       |
| [`KeyedWords`](_autosummary/nyms.html.md#nyms.KeyedWords)(key[, n_words, wordlist, ...])         | Keyed hash (HMAC-SHA-256) rendered as readable words.                                 |
| [`RandomWords`](_autosummary/nyms.html.md#nyms.RandomWords)([n_words, wordlist, templates, ...])  | Random readable words (a tokenisation vault): no key, no information about the value. |
| [`EntityType`](_autosummary/nyms.html.md#nyms.EntityType)(name, identifier_class, tier[, ...])   | One entity type and its place in the taxonomy.                                        |

### *class* nyms.Aliases(aliases, fallback=Counter())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The user’s own surrogates for some values; *fallback* for the rest.

Keys are compared casefolded and whitespace-collapsed.

```pycon
>>> 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}]')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A regex detector with an optional validator and context words.

`validate(match)` may return `False` (drop), `True`/`None` (keep the base
score) or a float (use it as the score). `group` picks 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)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Anything that turns text into spans. `name` and `entity_type` are optional.

### *class* nyms.EntityType(name, identifier_class, tier, description='', aliases=tuple())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One entity type and its place in the taxonomy.

### *class* nyms.KeyedWords(key, n_words=2, wordlist=None, templates=<factory>, default_template='[{type}:{words}]')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Keyed hash (HMAC-SHA-256) rendered as readable words. Deterministic under one key.

### *class* nyms.MappingStore(store=None, , strategy=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Records keyed by surrogate, with an in-memory index by `(entity_type, normalised)`.

#### add(entity_type, text, , surrogate=None)

Create a record for a new value (with a given *surrogate*, or one from the strategy).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### add_alias_form(surrogate, entity_type, text)

Make *text* (a surname alone, say) resolve to an existing record’s surrogate.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### alias(entity_type, text, surrogate)

Choose the surrogate for a value yourself (before it is first seen).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### resolve(entity_type, text)

`(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 `...s` is a genitive; if the base form appears later the
record is relinked to it.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### to_dict()

`{surrogate: original}`. This is the sensitive artefact; handle it as such.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### *class* nyms.Policy(name='default', include=None, exclude=frozenset({}), min_score=0.5, min_score_by_type=dict(), allow=frozenset({}), deny=frozenset({}), keep=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What to do with detected spans. See the module docstring.

#### accepts(span)

Whether *span* gets replaced under this policy (post-detection decision).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### detector_filter(detectors)

The detectors whose entity type this policy wants; a pre-detection filter.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

#### split(spans)

`(replaced, kept)` under this policy.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Span`](_autosummary/nyms.spans.html.md#nyms.spans.Span)], [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Span`](_autosummary/nyms.spans.html.md#nyms.spans.Span)]]

#### wants(entity_type)

Whether this policy acts on a type at all (pre-detection filter).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### with_names(\*names)

A copy whose deny list also holds *names* (casefolded): the parties you know.

```pycon
>>> p = Policy.default().with_names('Acme ApS')
>>> 'acme aps' in p.deny
True
```

* **Return type:**
  [`Policy`](_autosummary/nyms.policy.html.md#nyms.policy.Policy)

### *class* nyms.Pseudonymiser(project='default', , detectors=None, post_detectors=(), policy=None, strategy=None, store=None, key=None, names=(), rootdir=None, encrypt=False, prefilter=False)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The facade. See the module docstring for the seams.

#### check(text)

Originals from the mapping that occur in *text*: what would leak if it were sent.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### *class* nyms.RandomWords(n_words=2, wordlist=None, templates=<factory>, default_template='[{type}:{words}]')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Random readable words (a tokenisation vault): no key, no information about the value.

### *class* nyms.Reidentified(text, restored, unmatched)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What `Pseudonymiser.reidentify()` returns.

### *class* nyms.Result(text, replaced, kept, replacements, report=dict(), post_replacements=list())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What `Pseudonymiser.pseudonymise()` returns. Spans refer to the NFC-normalised input.

#### *property* mapping *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [str](https://docs.python.org/3/builtins/stdtypes.html#str)]*

`{surrogate: original}` for this run only. Sensitive.

#### post_replacements *: [list](https://docs.python.org/3/builtins/stdtypes.html#list)[[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[Span](_autosummary/nyms.spans.html.md#nyms.spans.Span), [str](https://docs.python.org/3/builtins/stdtypes.html#str)]]*

Stage-2 replacements (`post_detectors`), with offsets in the stage-1 output.

### *class* nyms.Span(start, end, entity_type, text, score=1.0, detector='', value=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One detected occurrence of an entity in a text.

#### value *: [str](https://docs.python.org/3/builtins/stdtypes.html#str) | [None](https://docs.python.org/3/builtins/constants.html#None)* *= None*

a surname mention
(“Jensen”) that stands for a known full name (“Rasmus Jensen”).

* **Type:**
  The value this span stands for when it differs from the text

### nyms.apply_replacements(text, replacements)

Rebuild *text* with each span replaced by its string. Spans must not overlap.

```pycon
>>> apply_replacements('a b c', [(Span(2, 3, 'X', 'b'), 'B')])
'a B c'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### nyms.default_detectors(, names=(), languages=('da', 'en'))

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.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Detector`](_autosummary/nyms.html.md#nyms.Detector)]

### nyms.detect(text, detectors=None)

Run *detectors* (default: [`default_detectors()`](_autosummary/nyms.html.md#nyms.default_detectors)) and resolve overlaps.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Span`](_autosummary/nyms.spans.html.md#nyms.spans.Span)]

### nyms.gazetteer_detector(names, , name='gazetteer', entity_type='PERSON', score=1.0, surname_tail=True, value_of_name=None, single_word_score=0.85)

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 `s` on 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).

```pycon
>>> d = gazetteer_detector(['Rasmus'])
>>> [s.text for s in d('Rasmus Jensens bil, og Rasmus selv.')]
['Rasmus Jensens', 'Rasmus']
```

* **Return type:**
  [`Detector`](_autosummary/nyms.html.md#nyms.Detector)

### nyms.known_values_detectors(records, , extra_names=(), score=1.0)

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()`](_autosummary/nyms.html.md#nyms.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.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Detector`](_autosummary/nyms.html.md#nyms.Detector)]

### nyms.local_mapping_store(project='default', , rootdir=None, codec=None)

A `dol` file 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; see `encrypted()`. The project’s `meta.json` records which
codec the store was created with; a mismatch raises `StoreError`.

* **Return type:**
  [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### nyms.normalise(entity_type, text)

The identity of a value for the purpose of “same surrogate”.

```pycon
>>> normalise('CPR', '010190-1234'), normalise('PERSON', ' Hans   JENSEN '), normalise('EMAIL', 'A@B.dk')
('0101901234', 'hans jensen', 'a@b.dk')
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### nyms.readable(value, , key, entity_type='VALUE', n_words=2, wordlist=None)

The stand-alone tool: a keyed hash of *value*, as readable words.

```pycon
>>> 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:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### nyms.resolve_overlaps(spans, \*, priority=<function default_priority>)

Keep a non-overlapping subset of *spans*, best first by *priority*, in text order.

```pycon
>>> 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']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Span`](_autosummary/nyms.spans.html.md#nyms.spans.Span)]

### nyms.words_from_bytes(data, , n=2, wordlist=None)

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.

```pycon
>>> words_from_bytes(bytes([0, 0, 0, 1]), n=2)
['aardvark', 'abandoned']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### Modules

| [`core`](_autosummary/nyms.core.html.md#module-nyms.core)             | The facade: detect, pseudonymise, re-identify, check.                                   |
|------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|
| [`data`](_autosummary/nyms.data.html.md#module-nyms.data)             | Bundled data files (data), shipped inside the wheel.                                    |
| [`keys`](_autosummary/nyms.keys.html.md#module-nyms.keys)             | Key management for a single user or a small team: where the project's secret lives.     |
| [`mapping`](_autosummary/nyms.mapping.html.md#module-nyms.mapping)       | The reversible mapping store: surrogate <-> original, per project, on a `dol` store.    |
| [`policy`](_autosummary/nyms.policy.html.md#module-nyms.policy)         | The sensitivity policy: which detected spans get replaced, which are kept and reported. |
| [`spans`](_autosummary/nyms.spans.html.md#module-nyms.spans)           | Spans: where a detector found something, and how findings are merged and applied.       |
| [`surrogates`](_autosummary/nyms.surrogates.html.md#module-nyms.surrogates) | Surrogate (pseudonym) generation: what replaces a detected value.                       |
| [`taxonomy`](_autosummary/nyms.taxonomy.html.md#module-nyms.taxonomy)     | The entity taxonomy: what kinds of things nyms detects, and how sensitive each is.      |
| [`tools`](_autosummary/nyms.tools.html.md#module-nyms.tools)           | The SSOT of operations: plain functions, JSON-able in and out, surface-agnostic.        |


# _autosummary/nyms.keys.html.md

# nyms.keys

Key management for a single user or a small team: where the project’s secret lives.

The key is the “additional information” of GDPR Art. 4(5): whoever holds it and the mapping
store can re-identify. So it never sits next to the pseudonymised text, and never inside the
mapping store’s directory. Resolution order of [`resolve_key()`](_autosummary/nyms.keys.html.md#nyms.keys.resolve_key):

1. the environment variable (`NYMS_KEY`, hex or base64), for CI and scripted use;
2. a per-project key file under the user’s config dir (`~/.config/nyms/keys/<project>.key`,
   mode 0600), created with 32 random bytes on first use;
3. a passphrase, when one is given, derived with scrypt (stdlib) and a per-project salt
   stored next to the key file.

Replacements this seam allows: the `keyring` package (OS keychain), `config2py`’s layered
resolution, `age` recipients, an external KMS. Each is one `key=` argument to the
facade. Rotation is a new project (keyed-hash surrogates change with the key by construction;
counter surrogates survive it, since they live in the store).

```pycon
>>> import tempfile, os
>>> d = tempfile.mkdtemp()
>>> k1 = resolve_key('demo', key_dir=d, env_var=None)
>>> len(k1), k1 == resolve_key('demo', key_dir=d, env_var=None)
(32, True)
>>> derive_key('correct horse', salt=b'salt' * 4) == derive_key('correct horse', salt=b'salt' * 4)
True
```

### Functions

| [`config_dir`](_autosummary/nyms.keys.html.md#nyms.keys.config_dir)()                                  | `$XDG_CONFIG_HOME/nyms` or `~/.config/nyms`.                                          |
|------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| [`data_dir`](_autosummary/nyms.keys.html.md#nyms.keys.data_dir)()                                    | `$XDG_DATA_HOME/nyms` or `~/.local/share/nyms`: where mapping stores live by default. |
| [`decode_key`](_autosummary/nyms.keys.html.md#nyms.keys.decode_key)(text)                              | A key from its hex or base64 text form.                                               |
| [`derive_key`](_autosummary/nyms.keys.html.md#nyms.keys.derive_key)(passphrase, \*, salt[, length])    | scrypt key derivation (stdlib).                                                       |
| `key_path`(project, \*[, key_dir])                                                             |                                                                                       |
| [`resolve_key`](_autosummary/nyms.keys.html.md#nyms.keys.resolve_key)([project, env_var, key_dir, ...]) | The project's key, by the resolution order in the module docstring.                   |

### nyms.keys.config_dir()

`$XDG_CONFIG_HOME/nyms` or `~/.config/nyms`.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### nyms.keys.data_dir()

`$XDG_DATA_HOME/nyms` or `~/.local/share/nyms`: where mapping stores live by default.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### nyms.keys.decode_key(text)

A key from its hex or base64 text form.

```pycon
>>> decode_key('00' * 32) == bytes(32)
True
```

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### nyms.keys.derive_key(passphrase, , salt, length=32)

scrypt key derivation (stdlib). Argon2id is the replacement when `argon2-cffi` is wanted.

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### nyms.keys.resolve_key(project='default', , env_var='NYMS_KEY', key_dir=None, passphrase=None, create=True)

The project’s key, by the resolution order in the module docstring.

Raises `FileNotFoundError` when no key exists and *create* is false.

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)


# _autosummary/nyms.mapping.html.md

# nyms.mapping

The reversible mapping store: surrogate <-> original, per project, on a `dol` store.

A [`MappingStore`](_autosummary/nyms.mapping.html.md#nyms.mapping.MappingStore) holds one [`Record`](_autosummary/nyms.mapping.html.md#nyms.mapping.Record) per distinct value: entity type, original,
normalised form, surrogate, aliases (other normalised forms that stand for the same value,
such as a surname alone), strategy name and creation time. It is keyed by surrogate (so
re-identification is one lookup) and indexes every normalised form in memory so the same
value gets the same surrogate on every occurrence and in every document of the project.

The backing store is any `MutableMapping[str, dict]`. The default,
[`local_mapping_store()`](_autosummary/nyms.mapping.html.md#nyms.mapping.local_mapping_store), is `dol.JsonFiles` under `~/.local/share/nyms/<project>/mapping`,
one JSON file per record (file names are a URL-safe encoding of the surrogate, so any
surrogate string is a legal file name on any platform), which a human can inspect and
delete. Encryption at rest is the `codec` seam: pass [`encrypted()`](_autosummary/nyms.mapping.html.md#nyms.mapping.encrypted) (needs the optional
`cryptography` dependency) and every value is Fernet-encrypted under the project key before
it hits disk. The project directory carries a `meta.json` naming the codec, so opening an
encrypted store without the codec (or the reverse) fails with a clear message.

Normalisation decides what counts as “the same value”: digits only for numeric identifiers,
casefolded and whitespace-collapsed for names, lower case for e-mail. The Danish genitive is
handled in [`MappingStore.resolve()`](_autosummary/nyms.mapping.html.md#nyms.mapping.MappingStore.resolve): `Rasmus Jensens` resolves to `Rasmus Jensen`’s
surrogate plus the suffix `s` when that person is already known, and the facade writes
`[PERSON_1]s`. A first-seen `...s` is taken literally; if the base form turns up later,
the record is relinked to it.

```pycon
>>> from nyms.surrogates import Counter
>>> m = MappingStore({}, strategy=Counter())
>>> m.resolve('PERSON', 'Rasmus Jensen')
('[PERSON_1]', '')
>>> m.resolve('PERSON', 'Rasmus Jensens')
('[PERSON_1]', 's')
>>> m.resolve('CPR', '010190 1234') == m.resolve('CPR', '010190-1234')
True
>>> m.original('[PERSON_1]')
'Rasmus Jensen'
```

### Functions

| [`canon`](_autosummary/nyms.mapping.html.md#nyms.mapping.canon)(surrogate)                               | The loose form of a surrogate used for re-identification and collision checks.   |
|-------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`encrypted`](_autosummary/nyms.mapping.html.md#nyms.mapping.encrypted)(key)                                 | A `(encode, decode)` codec: Fernet under a key derived from *key*.               |
| [`local_mapping_store`](_autosummary/nyms.mapping.html.md#nyms.mapping.local_mapping_store)([project, rootdir, codec]) | A `dol` file store of records under the project dir, optionally through *codec*. |
| [`normalise`](_autosummary/nyms.mapping.html.md#nyms.mapping.normalise)(entity_type, text)                   | The identity of a value for the purpose of "same surrogate".                     |
| [`project_dir`](_autosummary/nyms.mapping.html.md#nyms.mapping.project_dir)(project, \*[, rootdir])            | Where a project's data lives: `<rootdir or ~/.local/share/nyms>/<project>`.      |

### Classes

| [`MappingStore`](_autosummary/nyms.mapping.html.md#nyms.mapping.MappingStore)([store, strategy])               | Records keyed by surrogate, with an in-memory index by `(entity_type, normalised)`.   |
|------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| [`Record`](_autosummary/nyms.mapping.html.md#nyms.mapping.Record)(surrogate, original, entity_type, ...) | One distinct value and its surrogate.                                                 |

### Exceptions

| [`StoreError`](_autosummary/nyms.mapping.html.md#nyms.mapping.StoreError)   | A mapping store could not be opened the way it was created (codec mismatch).   |
|---------------------------------------------------------------|--------------------------------------------------------------------------------|

### *class* nyms.mapping.MappingStore(store=None, , strategy=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Records keyed by surrogate, with an in-memory index by `(entity_type, normalised)`.

#### add(entity_type, text, , surrogate=None)

Create a record for a new value (with a given *surrogate*, or one from the strategy).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### add_alias_form(surrogate, entity_type, text)

Make *text* (a surname alone, say) resolve to an existing record’s surrogate.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### alias(entity_type, text, surrogate)

Choose the surrogate for a value yourself (before it is first seen).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### resolve(entity_type, text)

`(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 `...s` is a genitive; if the base form appears later the
record is relinked to it.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### to_dict()

`{surrogate: original}`. This is the sensitive artefact; handle it as such.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### *class* nyms.mapping.Record(surrogate, original, entity_type, normalised, strategy='', created=0.0, aliases=tuple())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One distinct value and its surrogate.

### *exception* nyms.mapping.StoreError

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

A mapping store could not be opened the way it was created (codec mismatch).

### nyms.mapping.canon(surrogate)

The loose form of a surrogate used for re-identification and collision checks.

```pycon
>>> canon('[ PERSON 1 ]'), canon('Alder  Brook')
('person_1', 'alder_brook')
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### nyms.mapping.encrypted(key)

A `(encode, decode)` codec: Fernet under a key derived from *key*. Needs `cryptography`.

Fernet (AES-128-CBC with HMAC-SHA-256) is the simplest authenticated encryption the
`cryptography` package offers; AES-GCM or `age` are the replacements.

### nyms.mapping.local_mapping_store(project='default', , rootdir=None, codec=None)

A `dol` file 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; see [`encrypted()`](_autosummary/nyms.mapping.html.md#nyms.mapping.encrypted). The project’s `meta.json` records which
codec the store was created with; a mismatch raises [`StoreError`](_autosummary/nyms.mapping.html.md#nyms.mapping.StoreError).

* **Return type:**
  [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### nyms.mapping.normalise(entity_type, text)

The identity of a value for the purpose of “same surrogate”.

```pycon
>>> normalise('CPR', '010190-1234'), normalise('PERSON', ' Hans   JENSEN '), normalise('EMAIL', 'A@B.dk')
('0101901234', 'hans jensen', 'a@b.dk')
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### nyms.mapping.project_dir(project, , rootdir=None)

Where a project’s data lives: `<rootdir or ~/.local/share/nyms>/<project>`.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)


# _autosummary/nyms.policy.html.md

# nyms.policy

The sensitivity policy: which detected spans get replaced, which are kept and reported.

A [`Policy`](_autosummary/nyms.policy.html.md#nyms.policy.Policy) is evaluated **after** detection (all detectors run, the policy decides),
which is what lets the run report say what it saw and chose to keep. A policy can also be
applied **before** detection through [`Policy.detector_filter()`](_autosummary/nyms.policy.html.md#nyms.policy.Policy.detector_filter), to skip detectors whose
type it will never act on; both orders are supported because the user asked for both.

Three presets:

- `Policy.default()`: tiers 0 and 1, plus organisation identifiers and amounts; dates,
  postcodes and URLs are kept and reported.
- `Policy.identifiers()`: tiers 0 and 1 only.
- `Policy.strict()`: everything detected.

Allow and deny lists are matched on the span text, case-insensitively: `allow` is never
replaced (a public institution’s name, say), `deny` is always replaced (the parties’
names, which no detector may know). A policy is a plain dataclass, so it serialises to and
from a dict (`to_dict()`, `from_dict()`) and can live in a project file.

```pycon
>>> from nyms.spans import Span
>>> p = Policy.default()
>>> p.accepts(Span(0, 10, 'CPR', '010190-1234', 0.9))
True
>>> p.accepts(Span(0, 10, 'DATE', '01.01.1990', 0.9))
False
>>> Policy.strict().accepts(Span(0, 10, 'DATE', '01.01.1990', 0.9))
True
```

### Classes

| [`Policy`](_autosummary/nyms.policy.html.md#nyms.policy.Policy)([name, include, exclude, min_score, ...])   | What to do with detected spans.   |
|-----------------------------------------------------------------------------------------------------|-----------------------------------|

### *class* nyms.policy.Policy(name='default', include=None, exclude=frozenset({}), min_score=0.5, min_score_by_type=dict(), allow=frozenset({}), deny=frozenset({}), keep=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What to do with detected spans. See the module docstring.

#### accepts(span)

Whether *span* gets replaced under this policy (post-detection decision).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### detector_filter(detectors)

The detectors whose entity type this policy wants; a pre-detection filter.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

#### split(spans)

`(replaced, kept)` under this policy.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Span`](_autosummary/nyms.spans.html.md#nyms.spans.Span)], [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Span`](_autosummary/nyms.spans.html.md#nyms.spans.Span)]]

#### wants(entity_type)

Whether this policy acts on a type at all (pre-detection filter).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### with_names(\*names)

A copy whose deny list also holds *names* (casefolded): the parties you know.

```pycon
>>> p = Policy.default().with_names('Acme ApS')
>>> 'acme aps' in p.deny
True
```

* **Return type:**
  [`Policy`](_autosummary/nyms.policy.html.md#nyms.policy.Policy)


# _autosummary/nyms.spans.html.md

# nyms.spans

Spans: where a detector found something, and how findings are merged and applied.

A [`Span`](_autosummary/nyms.spans.html.md#nyms.spans.Span) is a half-open character interval `[start, end)` over the text as given
(Python `str` indexing, so code points, never bytes or tokens), with the entity type the
detector assigned, the matched text, a confidence score in `[0, 1]` and the detector’s
name. Spans from several detectors overlap, and [`resolve_overlaps()`](_autosummary/nyms.spans.html.md#nyms.spans.resolve_overlaps) decides which
survive: the longer span first, then the higher score, then the earlier one. That order is
a function so it can be tested and replaced.

```pycon
>>> a = Span(0, 5, 'PERSON', 'Hans ', 0.5, 'heuristic')
>>> b = Span(0, 11, 'PERSON', 'Hans Jensen', 0.9, 'gazetteer')
>>> [s.detector for s in resolve_overlaps([a, b])]
['gazetteer']
>>> apply_replacements('Hans Jensen bor her', [(b, '[PERSON_1]')])
'[PERSON_1] bor her'
```

### Module Attributes

| [`WEAK_SCORE`](_autosummary/nyms.spans.html.md#nyms.spans.WEAK_SCORE)   | it never outranks an overlapping strong span, however long.   |
|---------------------------------------------------------------|---------------------------------------------------------------|

### Functions

| [`apply_replacements`](_autosummary/nyms.spans.html.md#nyms.spans.apply_replacements)(text, replacements)   | Rebuild *text* with each span replaced by its string.                                  |
|-------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|
| [`default_priority`](_autosummary/nyms.spans.html.md#nyms.spans.default_priority)(span)                   | Sort key: strong spans before weak ones, then longer, then higher score, then earlier. |
| [`resolve_overlaps`](_autosummary/nyms.spans.html.md#nyms.spans.resolve_overlaps)(spans, \*[, priority])  | Keep a non-overlapping subset of *spans*, best first by *priority*, in text order.     |

### Classes

| [`Span`](_autosummary/nyms.spans.html.md#nyms.spans.Span)(start, end, entity_type, text[, score, ...])   | One detected occurrence of an entity in a text.   |
|------------------------------------------------------------------------------------------------------|---------------------------------------------------|

### *class* nyms.spans.Span(start, end, entity_type, text, score=1.0, detector='', value=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One detected occurrence of an entity in a text.

#### value *: [str](https://docs.python.org/3/builtins/stdtypes.html#str) | [None](https://docs.python.org/3/builtins/constants.html#None)* *= None*

a surname mention
(“Jensen”) that stands for a known full name (“Rasmus Jensen”).

* **Type:**
  The value this span stands for when it differs from the text

### nyms.spans.WEAK_SCORE *= 0.6*

it never outranks an overlapping strong span, however long.

* **Type:**
  Below this score a span is “weak”

### nyms.spans.apply_replacements(text, replacements)

Rebuild *text* with each span replaced by its string. Spans must not overlap.

```pycon
>>> apply_replacements('a b c', [(Span(2, 3, 'X', 'b'), 'B')])
'a B c'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### nyms.spans.default_priority(span)

Sort key: strong spans before weak ones, then longer, then higher score, then earlier.

A long, low-confidence heuristic match must not swallow a short, certain one (a gazetteer
name inside a capitalised phrase); among spans of the same strength, the longer wins
(an address over the postcode inside it), then the score (a date over a phone number of
the same length).

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)

### nyms.spans.resolve_overlaps(spans, \*, priority=<function default_priority>)

Keep a non-overlapping subset of *spans*, best first by *priority*, in text order.

```pycon
>>> 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']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Span`](_autosummary/nyms.spans.html.md#nyms.spans.Span)]


# _autosummary/nyms.surrogates.html.md

# nyms.surrogates

Surrogate (pseudonym) generation: what replaces a detected value.

A **surrogate strategy** is a callable `(entity_type, value, *, vault) -> str` that returns
the replacement for a value seen for the first time; the mapping store calls it once per new
value and remembers the answer, so every later occurrence gets the same surrogate. `vault`
is the store itself, exposing `__contains__` (is this surrogate taken?) and
`count(entity_type)`, which is all a strategy needs to avoid collisions or number things.

Four strategies, matching the surrogate research (`docs/research/surrogates-crypto-and-keys.md`):

- [`Counter`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.Counter): `[PERSON_1]`, `[CPR_2]`. The default. Bracketed typed tokens were
  the form LLMs altered least in the one benchmark found, and the counter is per project
  (persisted with the store), so the same person is `[PERSON_1]` in every document.
- [`KeyedWords`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.KeyedWords): HMAC-SHA-256 of the value under a secret key, rendered as readable
  words from a word list (`[PERSON:alder-brook]`, or name-shaped `Alder Brook`). The
  same key gives the same surrogate on any machine without sharing a store, which is the
  property the vault lacks. Never unkeyed: a plain hash of a CPR number falls to enumeration.
- [`RandomWords`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.RandomWords): readable words from random bytes. A classic tokenisation vault.
- [`Aliases`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.Aliases): the user’s own choice for some values (“call the landlord Mr Green”),
  with any other strategy as the fallback.

The rendering of bytes to words ([`words_from_bytes()`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.words_from_bytes)) is separate from where the bytes
come from, and is the tool the user asked for (“a cryptographic hash mapped to a sequence of
letters that is actually readable”). It also stands alone:

```pycon
>>> words_from_bytes(b'\x00' * 8, n=2)
['aardvark', 'aardvark']
>>> Counter()('PERSON', 'Hans Jensen', vault=_EmptyVault())
'[PERSON_1]'
>>> KeyedWords(b'k' * 32)('CPR', '010190-1234', vault=_EmptyVault())
'[CPR:...]'
```

### Module Attributes

| [`DEFAULT_WORD_TEMPLATES`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.DEFAULT_WORD_TEMPLATES)   | Templates per entity type for word surrogates.   |
|---------------------------------------------------------------------------|--------------------------------------------------|

### Functions

| [`default_wordlist`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.default_wordlist)()                           | The bundled EFF short wordlist 2.0: 1,296 common words with unique 3-letter prefixes.   |
|-----------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|
| [`keyed_digest`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.keyed_digest)(key, entity_type, value)        | HMAC-SHA-256 of `entity_type || NUL || value` under *key*.                              |
| [`readable`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.readable)(value, \*, key[, entity_type, ...]) | The stand-alone tool: a keyed hash of *value*, as readable words.                       |
| [`syllables_from_bytes`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.syllables_from_bytes)(data, \*[, n])          | Render *data* as a pronounceable made-up word of *n* consonant-vowel syllables.         |
| [`words_from_bytes`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.words_from_bytes)(data, \*[, n, wordlist])    | Render *data* as *n* words from *wordlist* (default: the EFF short list).               |

### Classes

| [`Aliases`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.Aliases)(aliases[, fallback])                     | The user's own surrogates for some values; *fallback* for the rest.                   |
|---------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| [`Counter`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.Counter)([template])                              | `[PERSON_1]`-style typed counters, numbered per entity type within the project.       |
| [`KeyedWords`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.KeyedWords)(key[, n_words, wordlist, ...])        | Keyed hash (HMAC-SHA-256) rendered as readable words.                                 |
| [`RandomWords`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.RandomWords)([n_words, wordlist, templates, ...]) | Random readable words (a tokenisation vault): no key, no information about the value. |
| [`Vault`](_autosummary/nyms.surrogates.html.md#nyms.surrogates.Vault)(\*args, \*\*kwargs)                        | What a strategy may ask of the mapping store.                                         |

### *class* nyms.surrogates.Aliases(aliases, fallback=Counter())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The user’s own surrogates for some values; *fallback* for the rest.

Keys are compared casefolded and whitespace-collapsed.

```pycon
>>> 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.surrogates.Counter(template='[{type}_{n}]')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

`[PERSON_1]`-style typed counters, numbered per entity type within the project.

### nyms.surrogates.DEFAULT_WORD_TEMPLATES *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [str](https://docs.python.org/3/builtins/stdtypes.html#str)]* *= {'ORG': '{Words}', 'PERSON': '{Words}'}*

Templates per entity type for word surrogates. `{words}` is hyphen-joined lower case,
`{Words}` is capitalised and space-joined (name-shaped), `{type}` the entity type.

### *class* nyms.surrogates.KeyedWords(key, n_words=2, wordlist=None, templates=<factory>, default_template='[{type}:{words}]')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Keyed hash (HMAC-SHA-256) rendered as readable words. Deterministic under one key.

### *class* nyms.surrogates.RandomWords(n_words=2, wordlist=None, templates=<factory>, default_template='[{type}:{words}]')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Random readable words (a tokenisation vault): no key, no information about the value.

### *class* nyms.surrogates.Vault(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

What a strategy may ask of the mapping store.

### nyms.surrogates.default_wordlist()

The bundled EFF short wordlist 2.0: 1,296 common words with unique 3-letter prefixes.

```pycon
>>> len(default_wordlist())
1296
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]

### nyms.surrogates.keyed_digest(key, entity_type, value)

HMAC-SHA-256 of `entity_type || NUL || value` under *key*.

The type is part of the message so a person and a company with the same string get
different surrogates. The key must be secret: with a public key this is an unkeyed hash
and a low-entropy identifier (a CPR number, a phone number) is recovered by enumeration.

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### nyms.surrogates.readable(value, , key, entity_type='VALUE', n_words=2, wordlist=None)

The stand-alone tool: a keyed hash of *value*, as readable words.

```pycon
>>> 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:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### nyms.surrogates.syllables_from_bytes(data, , n=3)

Render *data* as a pronounceable made-up word of *n* consonant-vowel syllables.

Needs no word list and never collides with a dictionary word, at the cost of looking
invented. 70 syllables, about 6.1 bits each.

```pycon
>>> syllables_from_bytes(b'\x00\x00\x00', n=3)
'bababa'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### nyms.surrogates.words_from_bytes(data, , n=2, wordlist=None)

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.

```pycon
>>> words_from_bytes(bytes([0, 0, 0, 1]), n=2)
['aardvark', 'abandoned']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/nyms.taxonomy.html.md

# nyms.taxonomy

The entity taxonomy: what kinds of things nyms detects, and how sensitive each is.

Three axes, following the terminology research (`docs/research/terminology-and-regulation.md`):
the **identifier class** (credential, direct identifier, quasi-identifier, sensitive attribute,
organisation identifier), a **tier** that says what the default policy does with it, and
**aliases** that map the type onto the names Presidio, Google DLP and HIPAA use, so a reader
coming from those tools finds their footing.

Tiers:

- `0`: block. Credentials. Replaced always, whatever the policy says, unless a policy
  excludes the type explicitly.
- `1`: replace by default. Direct identifiers of a natural person.
- `2`: policy decides. Quasi-identifiers and sensitive attributes. The default policy
  replaces the ones that identify a party (organisation numbers and names, amounts) and keeps
  the ones the reader usually needs to reason (dates, postcodes, URLs), but reports them.

The registry is a plain dict so a caller can add a type (`ENTITY_TYPES['POLICY_NUMBER'] =
EntityType(...)`) before building detectors for it.

```pycon
>>> ENTITY_TYPES['CPR'].tier, ENTITY_TYPES['DATE'].tier
(1, 2)
```

### Module Attributes

| [`SURROGATE_TYPE`](_autosummary/nyms.taxonomy.html.md#nyms.taxonomy.SURROGATE_TYPE)   | The pseudo-type of a span that is one of the project's own surrogates.   |
|-------------------------------------------------------------------|--------------------------------------------------------------------------|

### Functions

| [`tier_of`](_autosummary/nyms.taxonomy.html.md#nyms.taxonomy.tier_of)(entity_type)   | The tier of a type, `2` for an unregistered one (policy decides).   |
|-------------------------------------------------------------------------|---------------------------------------------------------------------|

### Classes

| [`EntityType`](_autosummary/nyms.taxonomy.html.md#nyms.taxonomy.EntityType)(name, identifier_class, tier[, ...])   | One entity type and its place in the taxonomy.   |
|----------------------------------------------------------------------------------------------------|--------------------------------------------------|

### *class* nyms.taxonomy.EntityType(name, identifier_class, tier, description='', aliases=tuple())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One entity type and its place in the taxonomy.

### nyms.taxonomy.SURROGATE_TYPE *= 'SURROGATE'*

The pseudo-type of a span that is one of the project’s own surrogates. Such spans take
part in overlap resolution (so a surrogate is never re-detected as a name) and are then
dropped: a policy never acts on them.

### nyms.taxonomy.tier_of(entity_type)

The tier of a type, `2` for an unregistered one (policy decides).

```pycon
>>> tier_of('CREDENTIAL'), tier_of('UNKNOWN')
(0, 2)
```

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)


# _autosummary/nyms.tools.html.md

# nyms.tools

The SSOT of operations: plain functions, JSON-able in and out, surface-agnostic.

The CLI (`nyms.__main__`, via `cw`) dispatches this module’s `_dispatch_funcs`; an MCP
server (`py2mcp.mk_mcp_from_refs(['nyms.tools:pseudonymise', ...])`) or an HTTP adapter would
reference the same names. Nothing here prints or exits; nothing imports a surface.

Every verb takes the content as positional `text` or, exclusively, a `path` (a UTF-8 file,
or `-` for stdin). The two are never guessed from each other: a value that happens to be an
existing path is still text. The project key is touched only when a verb needs it.

### Functions

| [`check`](_autosummary/nyms.tools.html.md#nyms.tools.check)([text, path, project, encrypt])            | Originals of *project* that occur in the text: what would leak if this text were sent.                                  |
|---------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------|
| [`detect`](_autosummary/nyms.tools.html.md#nyms.tools.detect)([text, path, names, policy])              | The spans the deterministic pass finds, with the policy's decision for each.                                            |
| [`mapping`](_autosummary/nyms.tools.html.md#nyms.tools.mapping)([project, encrypt])                      | The project's records (surrogate, original, type).                                                                      |
| [`policies`](_autosummary/nyms.tools.html.md#nyms.tools.policies)()                                       | The policy presets and the entity types each replaces.                                                                  |
| [`pseudonymise`](_autosummary/nyms.tools.html.md#nyms.tools.pseudonymise)([text, path, project, out, ...])    | Replace detected identifiers in the text (or the file at *path*) with surrogates; the project's mapping remembers them. |
| [`readable`](_autosummary/nyms.tools.html.md#nyms.tools.readable)(value, \*[, project, entity_type, ...]) | A keyed hash of *value* under the project's key, rendered as readable words.                                            |
| [`reidentify`](_autosummary/nyms.tools.html.md#nyms.tools.reidentify)([text, path, project, out, encrypt])  | Put the originals back into the text (an AI's answer, say).                                                             |

### nyms.tools.check(text='', , path='', project='default', encrypt=False)

Originals of *project* that occur in the text: what would leak if this text were sent.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### nyms.tools.detect(text='', , path='', names='', policy='default')

The spans the deterministic pass finds, with the policy’s decision for each. Nothing is stored.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### nyms.tools.mapping(project='default', , encrypt=False)

The project’s records (surrogate, original, type). Sensitive: this is the key to the text.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### nyms.tools.policies()

The policy presets and the entity types each replaces.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### nyms.tools.pseudonymise(text='', , path='', project='default', out=None, policy='default', names='', strategy='counter', aliases='', encrypt=False)

Replace detected identifiers in the text (or the file at *path*) with surrogates; the project’s mapping remembers them.

*names*: comma-separated names you already know (the parties). *aliases*: `Name=Alias,...`
surrogates you choose yourself. *strategy*: `counter` (`[PERSON_1]`), `keyed-words`
or `random-words`. The result carries the text (or the `out` path) and the run report.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### nyms.tools.readable(value, , project='default', entity_type='VALUE', n_words=2)

A keyed hash of *value* under the project’s key, rendered as readable words.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### nyms.tools.reidentify(text='', , path='', project='default', out=None, encrypt=False)

Put the originals back into the text (an AI’s answer, say). Lists tokens it could not place.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-11-24 04:38 UTC** from commit <a href="https://github.com/addaix/nyms/commit/e9a34f12f7bdeaeb787e262b26b6941b49fb44b6"><code>e9a34f1</code></a> on branch <code>main</code>, for **nyms 0.0.4** (from <code>pyproject.toml</code>).

#### NOTE
Nothing suggests a mismatch: the tree was clean at the commit above, and the documented version is the one on PyPI.

## Source

|                     |                                                                                                                                                    |
|---------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/addaix/nyms/commit/e9a34f12f7bdeaeb787e262b26b6941b49fb44b6"><code>e9a34f12f7bdeaeb787e262b26b6941b49fb44b6</code></a> |
| Branch              | <code>main</code>                                                                                                                                  |
| Tags at this commit | none                                                                                                                                               |
| Working tree        | clean                                                                                                                                              |
| Remote              | <code>https://github.com/addaix/nyms</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>addaix/nyms</code>                                                                   |
| Run          | <a href="https://github.com/addaix/nyms/actions/runs/45327637344">45327637344</a>          |
| Ref          | <code>refs/heads/main</code>                                                               |
| Event commit | <code>e9a34f12f7bdeaeb787e262b26b6941b49fb44b6</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.25  |
| Sphinx   | 9.1.1   |
| docutils | 0.22.4  |
| Python   | 3.12.16 |

## Configuration as resolved

|               |                                                                   |
|---------------|-------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>pydata_sphinx_theme</code>) |
| accent        | <code>#7f4b00</code>                                              |
| api_generator | <code>autosummary</code>                                          |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code>  |
| agent_outputs | <code>true</code>                                                 |
| aggregates    | <code>md</code>                                                   |
| ai_artifacts  | <code>true</code>                                                 |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/nyms/0.0.4/">0.0.4</a>, the same as the documented version.

## Reproduce

```bash
git clone https://github.com/addaix/nyms && cd nyms
git checkout e9a34f12f7bdeaeb787e262b26b6941b49fb44b6
pip install "epythet==0.2.25"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# ai-agents.html.md

<!-- generated by epythet -->

# For AI agents

`nyms` ships artifacts for coding agents alongside its code. This page lists
them, says where each lives in the repository, and points at the
machine-readable copies of this documentation.

## Skills

Skills are folders holding a `SKILL.md` (the [Agent Skills](https://agentskills.io) format): a description that tells an agent when to use it and a body with the procedure. Install one into your agent with `gh skill` (any host: `--agent claude-code`, `copilot`, `cursor`, `codex`, `gemini`), or use the copy bundled in the wheel.

### `nyms`

Pseudonymise documents before any of their content reaches an AI model, re-identify the model’s answer, and check that nothing leaks, with the nyms package (Danish and English; CPR, CVR, names, addresses, phone, e-mail, IBAN, amounts, credentials). Use whenever a user wants to send personal, legal, medical or financial documents to an AI, asks to “anonymise”, “redact”, “remove names”, “mask the CPR numbers”, “de-identify”, “pseudonymise”, “protect privacy before sending to ChatGPT/Claude”, or when you are about to paste someone else’s personal data into a prompt. Also use to put the real names back into an answer (“re-identify”, “restore the names”).

```bash
gh skill install addaix/nyms nyms --agent claude-code
```

Source: [`nyms/data/skills/nyms`](https://github.com/addaix/nyms/tree/HEAD/nyms/data/skills/nyms) (bundled with the pip package).

### `nyms-dev-deidentification`

The expert index for working on de-identification and reversible pseudonymisation in the nyms package, for agents developing or extending it. Routes to the research reports (terminology and regulation, detection libraries and methods, surrogates and key management, pipeline architecture), the five ADRs, the seam table, the test rules (leakage, round trip, consistency) and the vocabulary to use. Use when adding a detector or entity type, a surrogate strategy, a store backend, the model-based second pass, Danish or English fixtures, or when a question about pseudonymisation, PII detection, CPR/CVR validation, keyed hashing, format-preserving encryption, re-identification risk or key management comes up while developing nyms.

```bash
gh skill install addaix/nyms nyms-dev-deidentification --agent claude-code
```

Source: [`skills/nyms-dev-deidentification`](https://github.com/addaix/nyms/tree/HEAD/skills/nyms-dev-deidentification).

The bundled skills are also on disk after `pip install nyms`, under the package’s `data/skills/` directory; link them into an agent without network access with `skill link-skills <that directory>`.

## Instruction files

Files agents read before working in this repository.

- [`.claude/CLAUDE.md`](https://github.com/addaix/nyms/tree/HEAD/.claude/CLAUDE.md): read by Claude Code

## Machine-readable documentation

This site publishes the same documentation in forms that fit an agent’s context window:

- [`llms.txt`](https://addaix.github.io/nyms/llms.txt): an index of every page with a one-line description ([llms.txt](https://llmstxt.org) format)
- [`nyms.md`](https://addaix.github.io/nyms/nyms.md): the whole documentation as one Markdown file
- `<page>.html.md`: a rendered Markdown twin of every page, advertised from each page’s `<head>` with `<link rel="alternate" type="text/markdown">`
- [`objects.inv`](https://addaix.github.io/nyms/objects.inv): the Sphinx inventory: a symbol-to-URL index (`sphobjinv convert plain objects.inv -`)


# api.html.md

# API reference

| [`nyms`](_autosummary/nyms.html.md#module-nyms)   | nyms: reversible pseudonymisation of text before it reaches an AI.   |
|---------------------------------------------------------------------|----------------------------------------------------------------------|


