Metadata-Version: 2.4
Name: ru-pii-guard
Version: 0.1.0
Summary: Find, validate, normalize and reversibly mask Russian PII (INN, SNILS, OGRN, cards, phones) before sending text to an LLM.
Author: dx0t1011
License-Expression: MIT
Project-URL: Homepage, https://github.com/dx0t1011/ru-pii-guard
Project-URL: Repository, https://github.com/dx0t1011/ru-pii-guard
Project-URL: Issues, https://github.com/dx0t1011/ru-pii-guard/issues
Project-URL: Changelog, https://github.com/dx0t1011/ru-pii-guard/blob/main/CHANGELOG.md
Keywords: pii,russia,inn,snils,anonymization,privacy,llm,redaction
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Operating System :: OS Independent
Classifier: Topic :: Security
Classifier: Topic :: Text Processing
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pytest-cov>=7; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Requires-Dist: mypy<1.20,>=1.8; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Dynamic: license-file

# ru-pii-guard

[![CI](https://github.com/dx0t1011/ru-pii-guard/actions/workflows/ci.yml/badge.svg)](https://github.com/dx0t1011/ru-pii-guard/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/ru-pii-guard)](https://pypi.org/project/ru-pii-guard/)
[![Python](https://img.shields.io/pypi/pyversions/ru-pii-guard)](https://pypi.org/project/ru-pii-guard/)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

Find and mask Russian identifiers locally before sharing a contract, résumé or receipt with an LLM. Keep the mapping on your machine to restore the original spellings in the reply. Python 3.9+, standard library only at runtime. [Русское руководство](#русское-руководство).

## Install and try it

From a checkout of this repository, run `python -m pip install -e .`. After the owner publishes the release, use `python -m pip install ru-pii-guard`.

```python
import ru_pii_guard as r

text = "ИНН 7707083893, тел. 8 (912) 345-67-89"
masked, mapping = r.mask(text)
assert masked == "ИНН [INN_1], тел. [PHONE_1]"
assert r.unmask(masked, mapping) == text
assert r.unmask("Call [PHONE_1]", mapping) == "Call 8 (912) 345-67-89"
assert r.redact(text) == "ИНН [REDACTED], тел. [REDACTED]"

first = r.find(text)[0]
assert (first.kind, first.start, first.end, first.confidence) == ("inn", 4, 14, 1.0)
assert r.validate(first.kind, first.value)
assert r.normalize("phone", "8 (912) 345-67-89") == "+79123456789"
```

`find` returns non-overlapping spans in source order. Offsets index Python characters and exclude the end. `normalize` checks the shape, and `validate` also verifies the check digits where applicable. Unknown kinds and malformed inputs to `normalize` raise `ValueError`. For customer bank accounts use `validate("account", number, bik=bank_code)`. Without a BIK the result is `False`.

## Real-world use cases / Реальные сценарии

The pattern is the same everywhere: the document never leaves your machine in readable form. You mask first, the model or the other party sees placeholders, you restore locally afterwards.

**1. Sending a contract to a chat LLM.** A lawyer or accountant exports a contract with a client's passport and bank details, runs `mask`, asks the model to flag risky clauses, then `unmask` restores the real values in the answer. The model never receives the passport number.

**2. A service that proxies documents to an LLM.** Your backend receives a document, masks it, calls the model, restores the answer. This is the most common production pattern:

```python
# docs-only: needs your own LLM client
import ru_pii_guard as r

def ask_llm(document: str) -> str:
    masked, mapping = r.mask(document)
    answer = client.chat.completions.create(
        model="...", messages=[{"role": "user", "content": masked}]
    ).choices[0].message.content
    return r.unmask(answer, mapping)
```

**3. Cleaning a dataset before handing it to a contractor.** A data engineer runs `redact` over a dump, so exports and support tickets contain no INNs or phone numbers.

**4. Publishing a document.** `redact` before posting a scanned receipt, a court filing or a sample contract in a public repository.

**5. Building test fixtures.** Replace real customer rows with `[INN_1]`-style tokens, or use the benchmark generators for synthetic data.

### Environment / Среда использования

- A local machine or CI runner with Python 3.9+. No server, no account, no network call.
- The library in application code, or the CLI in a shell pipeline: `cat doc.txt | ru-pii-guard mask - --map keys.json > masked.txt`.
- You process data you are allowed to process: your own, your company's, or a client's under a contract or consent. The library is a technical protection measure; it does not create a legal basis and is not statutory anonymisation under 152-ФЗ.
- Do not use it on data you obtained without lawful access. See [LEGAL.md](LEGAL.md).

**Не используйте пакет на данных, к которым у вас нет законного доступа.** Маскировка — техническая мера защиты, а не основание для обработки.

## CLI

```bash
ru-pii-guard find document.txt
ru-pii-guard mask - --map keys.json < document.txt > masked.txt
ru-pii-guard unmask masked.txt --map keys.json -o restored.txt
ru-pii-guard validate --kind inn 7707083893
ru-pii-guard benchmark --report report.json
```

Files and streams use UTF-8. Use `-` for stdin and omit `-o` for stdout. `find` emits a JSON array, `mask` saves a local JSON object, and `validate` signals the result by exit code. Codes are 0 for success, 1 for an input or I/O error, and 2 for a failed validation.

## Detection rules and limits

- Supported kinds are `inn`, `snils`, `ogrn`, `ogrnip`, `kpp`, `bik`, `account`, `card`, `oms`, `passport`, `phone`, `email` and `iban`. Checksums establish arithmetic consistency. Issuance and ownership require independent verification.
- Checksum confidence is 1.0 on success and 0.5 for a recognized candidate that fails verification or an account lacking an unambiguous nearby BIK. Labels help distinguish card and policy numbers, or KPP and BIK. Ties favor a field label and a distinctive format. Longer spans win first.
- Passport detection uses a field label or a four-digit series and six-digit number (confidence 0.75). Russian telephone candidates start with +7, 7 or 8 and have ten more digits. Email uses an ASCII dot-atom local part and a dotted domain. Phone and email confidence is 0.98. IBAN checks the generic structure and MOD-97. Country-specific account registries and quoted or internationalized email addresses are outside this release.
- Identical original spellings share a token within a document. Different formatting receives separate tokens so the map restores whitespace, line breaks and punctuation exactly. Unknown tokens survive restoration.

## Security

Processing runs locally without network access, telemetry or logging of identifier values. `find` results, restored documents and JSON mappings contain plaintext identifiers. Keep the mapping private and send only the masked document. Review the result for unsupported identifiers and missed spans. Use `redact` when restoration is unnecessary.

## Русское руководство

Пакет находит и маскирует российские реквизиты перед отправкой документа во внешний сервис. Для установки из репозитория выполните `python -m pip install -e .`. Требуется Python 3.9 или новее. Пример Python и команды выше можно выполнить без изменений.

```python
from ru_pii_guard import mask, unmask

исходник = "Паспорт 45 12 345678"
текст, словарь = mask(исходник)
assert текст == "Паспорт [PASSPORT_1]"
assert unmask(текст, словарь) == исходник
```

`find` возвращает тип, нормализованное значение, границы в символах исходной строки и уверенность. `validate` проверяет структуру и доступную контрольную сумму. Для расчётного счёта передайте БИК через `bik=` в Python или `--bik` в CLI. `redact` заменяет найденные фрагменты без словаря восстановления. CLI читает UTF-8 из файла или stdin (`-`) и по умолчанию пишет в stdout. Коды выхода 0, 1 и 2 означают успех, ошибку ввода и отрицательную проверку соответственно.

### Безопасность

Текст обрабатывается локально. Пакет не обращается к сети, не собирает телеметрию и не записывает реквизиты в логи или сообщения об ошибках. JSON-словарь содержит исходные значения в открытом виде. Храните его отдельно от текста, который отправляете наружу.

### Ограничения

Паспорт распознаётся по подписи или сочетанию серии и номера. Телефон должен иметь префикс +7, 7 или 8. Для email поддерживается распространённая запись ASCII. В спорных цифровых форматах помогает подпись поля. Проверка суммы ничего не говорит о выдаче документа. Одинаковые написания получают один токен, разные сохраняются раздельно для точного восстановления.

## Benchmark / Бенчмарк

Two corpora, two different claims. Both are small; neither replaces a run on your own documents.

### Synthetic corpus — regression guard

250 generated documents (50 with distractors), seed `20260101`. The generator and the detector are siblings: a high score means known formats still work, not that real documents are handled. Do not read it as real-world accuracy.

| Kind | TP | FP | FN | Precision | Recall | F1 |
|---|---:|---:|---:|---:|---:|---:|
| account | 88 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| bik | 96 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| card | 92 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| email | 101 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| iban | 111 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| inn | 98 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| kpp | 90 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| ogrn | 93 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| ogrnip | 99 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| oms | 102 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| passport | 93 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| phone | 96 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| snils | 90 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |
| overall | 1249 | 0 | 0 | 1.0000 | 1.0000 | 1.0000 |

### Independent corpus — real forms

13 hand-written documents from `benchmark/independent/sources.py`: contracts, résumés, receipts, invoices, IBAN, ОГРНИП, passports as «серия … номер …», product codes as distractors. Built by `build.py` with exact offsets and scored like the synthetic set. Table and reproduction: [benchmark/independent/README.md](benchmark/independent/README.md).

**Что это значит.** Синтетика ловит регрессии, ручной набор проверяет реальные форматы. Ни один набор не заменяет прогон на ваших документах: перед отправкой во внешний сервис просмотрите результат.

Reproduce from the checkout / Воспроизведение:

```bash
python benchmark/generate.py --seed 20260101
python benchmark/evaluate.py --report benchmark/report.json
python benchmark/independent/build.py
python benchmark/evaluate.py --dataset benchmark/independent/dataset --report benchmark/independent/report.json
```

[Raw metrics](benchmark/report.json) · [Independent corpus](benchmark/independent/README.md) · [Benchmark specification](benchmark/spec.md) · [Engineering decisions](DECISIONS.md).

## Release / Выпуск версии

Publishing uses PyPI trusted publishing: no API token is stored anywhere. The GitHub Actions workflow exchanges a short-lived OIDC token with PyPI.

**One-time setup by the owner / Однократная настройка владельцем:**

1. Sign in to PyPI and open <https://pypi.org/manage/account/publishing/>.
2. Add a **pending publisher** with exactly these values:
   - PyPI Project Name: `ru-pii-guard`
   - Owner: `dx0t1011`
   - Repository name: `ru-pii-guard`
   - Workflow name: `publish.yml`
   - Environment name: `pypi`
3. Push a tag. `release.yml` builds artifacts and creates the GitHub Release; `publish.yml` then publishes to PyPI automatically.

**Release checklist / Чек-лист выпуска:**

1. Update the version in `pyproject.toml`, `src/ru_pii_guard/__init__.py` and `tests/test_import.py`. Record changes in `CHANGELOG.md`.
2. Run `ruff check .`, `mypy --strict src`, `pytest`, `python -m build` and `twine check dist/*`. Commit and push; wait for CI.
3. Tag and push:

   ```bash
   git tag v0.1.0
   git push origin v0.1.0
   ```

4. Watch the **Release** and **Publish to PyPI** workflows. The package appears at <https://pypi.org/project/ru-pii-guard/>.

For a manual re-run without a tag, use **Actions → Publish to PyPI → Run workflow**.

## Legal / Правовая информация

This package is a technical protection measure, not legal advice and not statutory anonymisation under 152-ФЗ. The operator who processes personal data remains responsible for having a lawful basis and for cross-border transfer decisions. The library has no network access, does not collect or store personal data, and does not connect to government systems. See [LEGAL.md](LEGAL.md) for the details, including the relevant Russian norms (152-ФЗ, ст. 272.1 УК РФ, ст. 13.11 КоАП РФ).

Пакет — техническая мера защиты, а не юридическое обезличивание по 152-ФЗ. Ответственность за обработку персональных данных несёт оператор. Библиотека не имеет доступа к сети, не собирает и не хранит персональные данные и не подключается к государственным системам. Подробности — в [LEGAL.md](LEGAL.md).

## License / Лицензия

MIT © dx0t1011. [License text](LICENSE).
