Skip to main content

ru-pii-guard

CI PyPI Python License: MIT

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.

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:

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

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

CLI

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 и команды выше можно выполнить без изменений.

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.

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

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

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 · Independent corpus · Benchmark specification · Engineering decisions.

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:

    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.

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 for the details, including the relevant Russian norms (152-ФЗ, ст. 272.1 УК РФ, ст. 13.11 КоАП РФ).

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

License / Лицензия

MIT © dx0t1011. License text.

Metadata

Release files for ru-pii-guard 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ru-pii-guard 0.1.0
File Size Uploaded Provenance Actions
ru_pii_guard-0.1.0.tar.gz 38.9 kB With provenance Details for ru_pii_guard-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ru-pii-guard 0.1.0
File Interpreter ABI Platform Actions
ru_pii_guard-0.1.0-py3-none-any.whl Python 3 none any Details for ru_pii_guard-0.1.0-py3-none-any.whl

Total release size: 59.7 kB

Release files / ru_pii_guard-0.1.0.tar.gz

Download URL ru_pii_guard-0.1.0.tar.gz
Size 38.9 kB
Tags Source
SHA-256 checksum
How to use checksums
f27aa9548f987b47882ac068a8a25bf93cadf7e1c8f95e864bf3da7a71a6dd5d
BLAKE2b-256 checksum
How to use checksums
799d8c567199466ba74e46e9f93f8d6370184907c4c8037a346e1c91792d8a2d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / ru_pii_guard-0.1.0-py3-none-any.whl

Download URL ru_pii_guard-0.1.0-py3-none-any.whl
Size 20.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
deb57cf1d4e393d4a5f287bbe6649007f5f59475db056700a5f01bf95ec1b442
BLAKE2b-256 checksum
How to use checksums
b5a52ceb8656ba8f8ef5ff39ea7fcad938b70b4fded9b675fb6a1bf9c4d23dc2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for ru-pii-guard 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for ru_pii_guard-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page