tr-pii-guard 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 suleymanssardogan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: tr-pii-guard
3
+ Version: 0.1.0
4
+ Summary: Turkish PII detection and redaction for LLM pipelines
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Provides-Extra: ner
10
+ Requires-Dist: transformers>=4.30; extra == "ner"
11
+ Requires-Dist: torch>=2.0; extra == "ner"
12
+ Dynamic: license-file
13
+
14
+ # tr-pii-guard
15
+
16
+ Türkçe metinlerdeki kişisel verileri (TC kimlik no, IBAN, telefon, e-posta, isim, adres) LLM API çağrısından önce tespit edip maskeleyen açık kaynak Python kütüphanesi.
17
+
18
+ KVKK/GDPR uyumu için, kullanıcı verisini OpenAI/Claude/Gemini gibi servislere göndermeden önce bir güvenlik katmanı sağlar.
19
+
20
+ ## Durum
21
+
22
+ Erken geliştirme aşamasında.
23
+
24
+ ## Kurulum
25
+
26
+ ```bash
27
+ pip install -e .
28
+ ```
29
+
30
+ ## Kullanım
31
+
32
+ ```python
33
+ from tr_pii_guard import redact, restore
34
+
35
+ masked_text, mapping = redact("TC no 10000000146, telefon 0532 123 45 67.")
36
+ # masked_text -> "TC no [TC_NO_1], telefon [TELEFON_1]."
37
+
38
+ original = restore(masked_text, mapping)
39
+ ```
40
+
41
+ Şu an tespit edilen türler: TC kimlik no, IBAN, telefon, e-posta (hepsi checksum/format
42
+ doğrulamalı).
43
+
44
+ ### İsim/adres tespiti (opsiyonel, NER)
45
+
46
+ ```bash
47
+ pip install tr-pii-guard[ner]
48
+ ```
49
+
50
+ ```python
51
+ masked_text, mapping = redact("Ahmet Yılmaz İstanbul'a gitti.", use_ner=True)
52
+ ```
53
+
54
+ `use_ner` varsayılan olarak kapalı — temel paket `transformers`/`torch` indirmeden çalışır.
55
+ Ekstra kurulu değilken `use_ner=True` çağrılırsa açık bir hata mesajıyla uyarır.
56
+
57
+ ### Komut satırı
58
+
59
+ ```bash
60
+ tr-pii-guard scan dosya.txt
61
+ ```
62
+
63
+ ### Özel detector ekleme
64
+
65
+ ```python
66
+ import re
67
+ from tr_pii_guard import register_detector
68
+
69
+ register_detector("CALISAN_ID", lambda text: list(re.finditer(r"EMP-\d{5}", text)))
70
+ ```
71
+
72
+ ## Lisans
73
+
74
+ MIT
@@ -0,0 +1,61 @@
1
+ # tr-pii-guard
2
+
3
+ Türkçe metinlerdeki kişisel verileri (TC kimlik no, IBAN, telefon, e-posta, isim, adres) LLM API çağrısından önce tespit edip maskeleyen açık kaynak Python kütüphanesi.
4
+
5
+ KVKK/GDPR uyumu için, kullanıcı verisini OpenAI/Claude/Gemini gibi servislere göndermeden önce bir güvenlik katmanı sağlar.
6
+
7
+ ## Durum
8
+
9
+ Erken geliştirme aşamasında.
10
+
11
+ ## Kurulum
12
+
13
+ ```bash
14
+ pip install -e .
15
+ ```
16
+
17
+ ## Kullanım
18
+
19
+ ```python
20
+ from tr_pii_guard import redact, restore
21
+
22
+ masked_text, mapping = redact("TC no 10000000146, telefon 0532 123 45 67.")
23
+ # masked_text -> "TC no [TC_NO_1], telefon [TELEFON_1]."
24
+
25
+ original = restore(masked_text, mapping)
26
+ ```
27
+
28
+ Şu an tespit edilen türler: TC kimlik no, IBAN, telefon, e-posta (hepsi checksum/format
29
+ doğrulamalı).
30
+
31
+ ### İsim/adres tespiti (opsiyonel, NER)
32
+
33
+ ```bash
34
+ pip install tr-pii-guard[ner]
35
+ ```
36
+
37
+ ```python
38
+ masked_text, mapping = redact("Ahmet Yılmaz İstanbul'a gitti.", use_ner=True)
39
+ ```
40
+
41
+ `use_ner` varsayılan olarak kapalı — temel paket `transformers`/`torch` indirmeden çalışır.
42
+ Ekstra kurulu değilken `use_ner=True` çağrılırsa açık bir hata mesajıyla uyarır.
43
+
44
+ ### Komut satırı
45
+
46
+ ```bash
47
+ tr-pii-guard scan dosya.txt
48
+ ```
49
+
50
+ ### Özel detector ekleme
51
+
52
+ ```python
53
+ import re
54
+ from tr_pii_guard import register_detector
55
+
56
+ register_detector("CALISAN_ID", lambda text: list(re.finditer(r"EMP-\d{5}", text)))
57
+ ```
58
+
59
+ ## Lisans
60
+
61
+ MIT
@@ -0,0 +1,20 @@
1
+ [project]
2
+ name = "tr-pii-guard"
3
+ version = "0.1.0"
4
+ description = "Turkish PII detection and redaction for LLM pipelines"
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ license = "MIT"
8
+
9
+ [project.optional-dependencies]
10
+ ner = ["transformers>=4.30", "torch>=2.0"]
11
+
12
+ [project.scripts]
13
+ tr-pii-guard = "tr_pii_guard.cli:main"
14
+
15
+ [build-system]
16
+ requires = ["setuptools>=61.0"]
17
+ build-backend = "setuptools.build_meta"
18
+
19
+ [tool.setuptools.packages.find]
20
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """Turkish PII detection and redaction for LLM pipelines."""
2
+
3
+ from .redactor import redact, register_detector, restore
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["redact", "restore", "register_detector"]
@@ -0,0 +1,32 @@
1
+ """Command-line interface: tr-pii-guard scan <file>"""
2
+
3
+ import argparse
4
+ import sys
5
+
6
+ from .redactor import redact
7
+
8
+
9
+ def main(argv=None) -> int:
10
+ parser = argparse.ArgumentParser(prog="tr-pii-guard")
11
+ subparsers = parser.add_subparsers(dest="command", required=True)
12
+
13
+ scan = subparsers.add_parser("scan", help="Print a file's content with PII masked")
14
+ scan.add_argument("path", help="Path to a text file")
15
+ scan.add_argument(
16
+ "--use-ner",
17
+ action="store_true",
18
+ help="Also mask names/locations (requires: pip install tr-pii-guard[ner])",
19
+ )
20
+
21
+ args = parser.parse_args(argv)
22
+
23
+ with open(args.path, encoding="utf-8") as f:
24
+ text = f.read()
25
+
26
+ masked, _ = redact(text, use_ner=args.use_ner)
27
+ print(masked)
28
+ return 0
29
+
30
+
31
+ if __name__ == "__main__":
32
+ sys.exit(main())
@@ -0,0 +1,56 @@
1
+ """Regex-based detectors for Turkish PII: TC kimlik no, phone numbers, IBAN."""
2
+
3
+ import re
4
+
5
+ TC_NO_PATTERN = re.compile(r"(?<!\d)\d{11}(?!\d)")
6
+
7
+ # shortcut: fixed area-code range [2-5]xx, no real operator/area-code table;
8
+ # widen if a valid number gets missed in practice.
9
+ PHONE_PATTERN = re.compile(
10
+ r"(?<!\d)(?:\+90[ .-]?|0090[ .-]?)?0?[ .-]?\(?[2-5]\d{2}\)?"
11
+ r"[ .-]?\d{3}[ .-]?\d{2}[ .-]?\d{2}(?!\d)"
12
+ )
13
+
14
+ IBAN_PATTERN = re.compile(r"TR\d{2}(?:[ ]?\d{4}){5}[ ]?\d{2}\b", re.IGNORECASE)
15
+
16
+ EMAIL_PATTERN = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
17
+
18
+
19
+ def _is_valid_tc_no(digits: str) -> bool:
20
+ if len(digits) != 11 or not digits.isdigit() or digits[0] == "0":
21
+ return False
22
+ d = [int(c) for c in digits]
23
+ odd_sum = d[0] + d[2] + d[4] + d[6] + d[8]
24
+ even_sum = d[1] + d[3] + d[5] + d[7]
25
+ d10 = (odd_sum * 7 - even_sum) % 10
26
+ d11 = (odd_sum + even_sum + d10) % 10
27
+ return d10 == d[9] and d11 == d[10]
28
+
29
+
30
+ def _is_valid_iban(iban: str) -> bool:
31
+ iban = iban.replace(" ", "").upper()
32
+ if not re.fullmatch(r"TR\d{24}", iban):
33
+ return False
34
+ rearranged = iban[4:] + iban[:4]
35
+ numeric = "".join(str(int(ch, 36)) for ch in rearranged)
36
+ return int(numeric) % 97 == 1
37
+
38
+
39
+ def find_tc_no(text: str) -> list[re.Match]:
40
+ """Find valid (checksum-passing) TC kimlik no occurrences in text."""
41
+ return [m for m in TC_NO_PATTERN.finditer(text) if _is_valid_tc_no(m.group())]
42
+
43
+
44
+ def find_phone(text: str) -> list[re.Match]:
45
+ """Find Turkish phone number occurrences in text."""
46
+ return list(PHONE_PATTERN.finditer(text))
47
+
48
+
49
+ def find_iban(text: str) -> list[re.Match]:
50
+ """Find valid (checksum-passing) Turkish IBAN occurrences in text."""
51
+ return [m for m in IBAN_PATTERN.finditer(text) if _is_valid_iban(m.group())]
52
+
53
+
54
+ def find_email(text: str) -> list[re.Match]:
55
+ """Find email address occurrences in text."""
56
+ return list(EMAIL_PATTERN.finditer(text))
@@ -0,0 +1,54 @@
1
+ """Optional Turkish NER-based name/location detection (PERSON/LOC).
2
+
3
+ Needs the `ner` extra: pip install tr-pii-guard[ner]
4
+ The model is loaded lazily on first use so importing this package never
5
+ forces the transformers/torch download.
6
+ """
7
+
8
+ _MODEL_NAME = "savasy/bert-base-turkish-ner-cased"
9
+ _WANTED_LABELS = {"PER", "LOC"}
10
+
11
+ _pipeline = None
12
+
13
+
14
+ class _Span:
15
+ """Minimal re.Match-like wrapper so NER results fit the same
16
+ (start(), end(), group()) interface the regex detectors use."""
17
+
18
+ def __init__(self, start: int, end: int, value: str):
19
+ self._start = start
20
+ self._end = end
21
+ self._value = value
22
+
23
+ def start(self) -> int:
24
+ return self._start
25
+
26
+ def end(self) -> int:
27
+ return self._end
28
+
29
+ def group(self) -> str:
30
+ return self._value
31
+
32
+
33
+ def _get_pipeline():
34
+ global _pipeline
35
+ if _pipeline is None:
36
+ try:
37
+ from transformers import pipeline
38
+ except ImportError as exc:
39
+ raise ImportError(
40
+ "İsim/adres tespiti için ek bağımlılıklar gerekli: "
41
+ "pip install tr-pii-guard[ner]"
42
+ ) from exc
43
+ _pipeline = pipeline("ner", model=_MODEL_NAME, aggregation_strategy="simple")
44
+ return _pipeline
45
+
46
+
47
+ def find_names(text: str) -> list[_Span]:
48
+ """Find person/location entities in `text` using a Turkish NER model."""
49
+ ner = _get_pipeline()
50
+ return [
51
+ _Span(r["start"], r["end"], text[r["start"] : r["end"]])
52
+ for r in ner(text)
53
+ if r["entity_group"] in _WANTED_LABELS
54
+ ]
@@ -0,0 +1,82 @@
1
+ """Combine all PII detectors into a single mask/unmask API."""
2
+
3
+ from collections import defaultdict
4
+ from typing import Callable
5
+
6
+ from .detectors import find_email, find_iban, find_phone, find_tc_no
7
+
8
+ _BASE_DETECTORS = (
9
+ ("TC_NO", find_tc_no),
10
+ ("IBAN", find_iban),
11
+ ("TELEFON", find_phone),
12
+ ("EPOSTA", find_email),
13
+ )
14
+
15
+ _extra_detectors: list[tuple[str, Callable]] = []
16
+
17
+
18
+ def register_detector(label: str, finder) -> None:
19
+ """Register a custom detector used by every later `redact()` call.
20
+
21
+ `finder(text)` must return matches exposing `.start()`, `.end()`, `.group()`
22
+ (anything `re.finditer` returns satisfies this).
23
+ """
24
+ _extra_detectors.append((label, finder))
25
+
26
+
27
+ def _collect_matches(text: str, detectors) -> list[tuple[int, int, str, str]]:
28
+ candidates = [
29
+ (m.start(), m.end(), label, m.group())
30
+ for label, finder in detectors
31
+ for m in finder(text)
32
+ ]
33
+ # Longer matches win when two detectors claim overlapping spans.
34
+ candidates.sort(key=lambda c: (-(c[1] - c[0]), c[0]))
35
+
36
+ selected: list[tuple[int, int, str, str]] = []
37
+ occupied: list[tuple[int, int]] = []
38
+ for start, end, label, value in candidates:
39
+ if any(start < o_end and end > o_start for o_start, o_end in occupied):
40
+ continue
41
+ selected.append((start, end, label, value))
42
+ occupied.append((start, end))
43
+
44
+ selected.sort(key=lambda c: c[0])
45
+ return selected
46
+
47
+
48
+ def redact(text: str, use_ner: bool = False) -> tuple[str, dict[str, str]]:
49
+ """Mask Turkish PII in `text`. Returns (masked_text, mapping) where
50
+ mapping maps each placeholder back to the original value.
51
+
52
+ use_ner=True also masks person/location names via an optional Turkish
53
+ NER model (pip install tr-pii-guard[ner]); off by default so the base
54
+ package stays dependency-light.
55
+ """
56
+ detectors = _BASE_DETECTORS + tuple(_extra_detectors)
57
+ if use_ner:
58
+ from .ner import find_names
59
+
60
+ detectors = detectors + (("ISIM", find_names),)
61
+
62
+ mapping: dict[str, str] = {}
63
+ counters: dict[str, int] = defaultdict(int)
64
+ pieces = []
65
+ cursor = 0
66
+ for start, end, label, value in _collect_matches(text, detectors):
67
+ counters[label] += 1
68
+ placeholder = f"[{label}_{counters[label]}]"
69
+ mapping[placeholder] = value
70
+ pieces.append(text[cursor:start])
71
+ pieces.append(placeholder)
72
+ cursor = end
73
+ pieces.append(text[cursor:])
74
+ return "".join(pieces), mapping
75
+
76
+
77
+ def restore(masked_text: str, mapping: dict[str, str]) -> str:
78
+ """Reverse `redact`: replace placeholders with their original values."""
79
+ result = masked_text
80
+ for placeholder, original in mapping.items():
81
+ result = result.replace(placeholder, original)
82
+ return result
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: tr-pii-guard
3
+ Version: 0.1.0
4
+ Summary: Turkish PII detection and redaction for LLM pipelines
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Provides-Extra: ner
10
+ Requires-Dist: transformers>=4.30; extra == "ner"
11
+ Requires-Dist: torch>=2.0; extra == "ner"
12
+ Dynamic: license-file
13
+
14
+ # tr-pii-guard
15
+
16
+ Türkçe metinlerdeki kişisel verileri (TC kimlik no, IBAN, telefon, e-posta, isim, adres) LLM API çağrısından önce tespit edip maskeleyen açık kaynak Python kütüphanesi.
17
+
18
+ KVKK/GDPR uyumu için, kullanıcı verisini OpenAI/Claude/Gemini gibi servislere göndermeden önce bir güvenlik katmanı sağlar.
19
+
20
+ ## Durum
21
+
22
+ Erken geliştirme aşamasında.
23
+
24
+ ## Kurulum
25
+
26
+ ```bash
27
+ pip install -e .
28
+ ```
29
+
30
+ ## Kullanım
31
+
32
+ ```python
33
+ from tr_pii_guard import redact, restore
34
+
35
+ masked_text, mapping = redact("TC no 10000000146, telefon 0532 123 45 67.")
36
+ # masked_text -> "TC no [TC_NO_1], telefon [TELEFON_1]."
37
+
38
+ original = restore(masked_text, mapping)
39
+ ```
40
+
41
+ Şu an tespit edilen türler: TC kimlik no, IBAN, telefon, e-posta (hepsi checksum/format
42
+ doğrulamalı).
43
+
44
+ ### İsim/adres tespiti (opsiyonel, NER)
45
+
46
+ ```bash
47
+ pip install tr-pii-guard[ner]
48
+ ```
49
+
50
+ ```python
51
+ masked_text, mapping = redact("Ahmet Yılmaz İstanbul'a gitti.", use_ner=True)
52
+ ```
53
+
54
+ `use_ner` varsayılan olarak kapalı — temel paket `transformers`/`torch` indirmeden çalışır.
55
+ Ekstra kurulu değilken `use_ner=True` çağrılırsa açık bir hata mesajıyla uyarır.
56
+
57
+ ### Komut satırı
58
+
59
+ ```bash
60
+ tr-pii-guard scan dosya.txt
61
+ ```
62
+
63
+ ### Özel detector ekleme
64
+
65
+ ```python
66
+ import re
67
+ from tr_pii_guard import register_detector
68
+
69
+ register_detector("CALISAN_ID", lambda text: list(re.finditer(r"EMP-\d{5}", text)))
70
+ ```
71
+
72
+ ## Lisans
73
+
74
+ MIT
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/tr_pii_guard/__init__.py
5
+ src/tr_pii_guard/cli.py
6
+ src/tr_pii_guard/detectors.py
7
+ src/tr_pii_guard/ner.py
8
+ src/tr_pii_guard/redactor.py
9
+ src/tr_pii_guard.egg-info/PKG-INFO
10
+ src/tr_pii_guard.egg-info/SOURCES.txt
11
+ src/tr_pii_guard.egg-info/dependency_links.txt
12
+ src/tr_pii_guard.egg-info/entry_points.txt
13
+ src/tr_pii_guard.egg-info/requires.txt
14
+ src/tr_pii_guard.egg-info/top_level.txt
15
+ tests/test_basic.py
16
+ tests/test_cli.py
17
+ tests/test_detectors.py
18
+ tests/test_ner.py
19
+ tests/test_plugin.py
20
+ tests/test_redactor.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tr-pii-guard = tr_pii_guard.cli:main
@@ -0,0 +1,4 @@
1
+
2
+ [ner]
3
+ transformers>=4.30
4
+ torch>=2.0
@@ -0,0 +1 @@
1
+ tr_pii_guard
@@ -0,0 +1,5 @@
1
+ import tr_pii_guard
2
+
3
+
4
+ def test_package_importable():
5
+ assert tr_pii_guard.__version__
@@ -0,0 +1,15 @@
1
+ from tr_pii_guard.cli import main
2
+
3
+ VALID_TC_NO = "10000000146"
4
+
5
+
6
+ def test_cli_scan_masks_file(tmp_path, capsys):
7
+ f = tmp_path / "input.txt"
8
+ f.write_text(f"TC no {VALID_TC_NO}.", encoding="utf-8")
9
+
10
+ exit_code = main(["scan", str(f)])
11
+ out = capsys.readouterr().out
12
+
13
+ assert exit_code == 0
14
+ assert VALID_TC_NO not in out
15
+ assert "[TC_NO_1]" in out
@@ -0,0 +1,37 @@
1
+ from tr_pii_guard.detectors import find_iban, find_phone, find_tc_no
2
+
3
+ VALID_TC_NO = "10000000146" # well-known checksum-valid test number, not a real person
4
+ VALID_IBAN = "TR33 0006 1005 1978 6457 8413 26"
5
+
6
+
7
+ def test_find_tc_no_valid():
8
+ text = f"Müşteri TC no: {VALID_TC_NO}."
9
+ matches = find_tc_no(text)
10
+ assert [m.group() for m in matches] == [VALID_TC_NO]
11
+
12
+
13
+ def test_find_tc_no_rejects_bad_checksum():
14
+ text = "Rastgele sayı 12345678901 burada."
15
+ assert find_tc_no(text) == []
16
+
17
+
18
+ def test_find_phone_variants():
19
+ samples = [
20
+ "0532 123 45 67",
21
+ "+90 532 123 45 67",
22
+ "05321234567",
23
+ "0212 123 45 67",
24
+ ]
25
+ for s in samples:
26
+ assert find_phone(s), f"should match: {s}"
27
+
28
+
29
+ def test_find_iban_valid():
30
+ text = f"IBAN: {VALID_IBAN}"
31
+ matches = find_iban(text)
32
+ assert len(matches) == 1
33
+
34
+
35
+ def test_find_iban_rejects_bad_checksum():
36
+ text = "IBAN: TR33 0006 1005 1978 6457 8413 27" # last digit tampered
37
+ assert find_iban(text) == []
@@ -0,0 +1,24 @@
1
+ import pytest
2
+
3
+
4
+ def test_redact_use_ner_without_extra_raises_helpful_error():
5
+ try:
6
+ import transformers # noqa: F401
7
+ except ImportError:
8
+ pass
9
+ else:
10
+ pytest.skip("transformers is installed; nothing to assert here")
11
+
12
+ from tr_pii_guard import redact
13
+
14
+ with pytest.raises(ImportError, match="tr-pii-guard\\[ner\\]"):
15
+ redact("Ahmet Yılmaz İstanbul'a gitti.", use_ner=True)
16
+
17
+
18
+ def test_find_names_detects_person():
19
+ pytest.importorskip("transformers")
20
+
21
+ from tr_pii_guard.ner import find_names
22
+
23
+ results = find_names("Ahmet Yılmaz İstanbul'a gitti.")
24
+ assert any(r.group() for r in results)
@@ -0,0 +1,18 @@
1
+ import re
2
+
3
+ from tr_pii_guard import redact
4
+ from tr_pii_guard.redactor import _extra_detectors, register_detector
5
+
6
+
7
+ def test_register_custom_detector():
8
+ def find_secret(text):
9
+ return list(re.finditer(r"GIZLI-\d+", text))
10
+
11
+ register_detector("OZEL", find_secret)
12
+ try:
13
+ masked, mapping = redact("Kod: GIZLI-42 burada.")
14
+ assert "GIZLI-42" not in masked
15
+ assert "[OZEL_1]" in masked
16
+ assert mapping["[OZEL_1]"] == "GIZLI-42"
17
+ finally:
18
+ _extra_detectors.clear()
@@ -0,0 +1,37 @@
1
+ from tr_pii_guard import redact, restore
2
+
3
+ VALID_TC_NO = "10000000146" # checksum-valid test number, not a real person
4
+ VALID_IBAN = "TR33 0006 1005 1978 6457 8413 26"
5
+
6
+
7
+ def test_redact_masks_every_type():
8
+ text = (
9
+ f"TC no {VALID_TC_NO}, telefon 0532 123 45 67, "
10
+ f"IBAN {VALID_IBAN}, e-posta test@example.com."
11
+ )
12
+ masked, _ = redact(text)
13
+
14
+ assert VALID_TC_NO not in masked
15
+ assert "0532 123 45 67" not in masked
16
+ assert VALID_IBAN not in masked
17
+ assert "test@example.com" not in masked
18
+
19
+
20
+ def test_redact_restore_roundtrip():
21
+ text = f"Kart sahibi, IBAN {VALID_IBAN}, TC no {VALID_TC_NO}."
22
+ masked, mapping = redact(text)
23
+ assert restore(masked, mapping) == text
24
+
25
+
26
+ def test_redact_numbers_repeated_type():
27
+ text = "Birinci telefon 0532 123 45 67, ikinci telefon 0212 123 45 67."
28
+ masked, mapping = redact(text)
29
+ assert "[TELEFON_1]" in masked and "[TELEFON_2]" in masked
30
+ assert restore(masked, mapping) == text
31
+
32
+
33
+ def test_redact_leaves_clean_text_untouched():
34
+ text = "Bugün hava çok güzel."
35
+ masked, mapping = redact(text)
36
+ assert masked == text
37
+ assert mapping == {}