-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feat(analyzer): add country-specific predefined recognizer for Taiwan (TW) National ID #2072
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ArjunPakhan
wants to merge
5
commits into
data-privacy-stack:main
Choose a base branch
from
ArjunPakhan:feat/taiwan-recognizers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e68cd25
feat(analyzer): add clean country-specific predefined recognizer for …
ArjunPakhan 9211ef0
fix(lint): add ending period to docstring to satisfy D400 linter rule
ArjunPakhan 9189304
fix(lint): simplify docstring to single-line format to resolve D400 a…
ArjunPakhan e27dbf2
fix(lint): organize imports across core modules to pass linter check
ArjunPakhan f5e4e51
fix(analyzer): relocate TW national ID recognizer, fix inheritance, a…
ArjunPakhan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 changes: 5 additions & 0 deletions
5
presidio-analyzer/presidio_analyzer/predefined_recognizers/country_specific/tw/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| """Taiwan specific recognizers.""" | ||
|
|
||
| from .tw_national_id_recognizer import TwNationalIdRecognizer | ||
|
|
||
| __all__ = ["TwNationalIdRecognizer"] |
78 changes: 78 additions & 0 deletions
78
...presidio_analyzer/predefined_recognizers/country_specific/tw/tw_national_id_recognizer.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| """Taiwan National ID Recognizer.""" | ||
|
|
||
| from typing import List, Optional | ||
|
|
||
| from presidio_analyzer import Pattern, PatternRecognizer | ||
|
|
||
|
|
||
| class TwNationalIdRecognizer(PatternRecognizer): | ||
| """Recognize Taiwan National ID using patterns and checksums.""" | ||
|
|
||
| PATTERNS = [ | ||
| Pattern( | ||
| "TW National ID (Strict)", | ||
| r"(?<![A-Za-z0-9])[A-Z][1289][0-9]{8}(?![A-Za-z0-9])", | ||
| 0.3, | ||
| ) | ||
| ] | ||
|
|
||
| CONTEXT = [ | ||
| "身分證", | ||
| "統一證號", | ||
| "國民身分證", | ||
| "tw id", | ||
| "taiwan id", | ||
| ] | ||
|
|
||
| def __init__( | ||
| self, | ||
| patterns: Optional[List[Pattern]] = None, | ||
| context: Optional[List[str]] = None, | ||
| supported_language: str = "zh", | ||
| supported_entity: str = "TW_NATIONAL_ID", | ||
| ): | ||
| """Initialize Taiwan National ID Recognizer.""" | ||
| patterns = patterns if patterns is not None else self.PATTERNS | ||
| context = context if context is not None else self.CONTEXT | ||
| super().__init__( | ||
| supported_entity=supported_entity, | ||
| patterns=patterns, | ||
| context=context, | ||
| supported_language=supported_language, | ||
| ) | ||
|
|
||
| def invalidate_result(self, pattern_text: str) -> bool: | ||
| """Reject invalid Taiwan ID structures via Modulus-10 checksum validation.""" | ||
| if len(pattern_text) != 10: | ||
| return True | ||
|
|
||
| # Presidio uses IGNORECASE by default; explicitly reject lowercase initial letters | ||
| first_char = pattern_text[0] | ||
| if not first_char.isupper(): | ||
| return True | ||
|
|
||
| letter_codes = { | ||
| 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, 'G': 16, 'H': 17, | ||
| 'I': 34, 'J': 18, 'K': 19, 'L': 20, 'M': 21, 'N': 22, 'O': 35, 'P': 23, | ||
| 'Q': 24, 'R': 25, 'S': 26, 'T': 27, 'U': 28, 'V': 29, 'W': 32, 'X': 30, | ||
| 'Y': 31, 'Z': 33 | ||
| } | ||
|
|
||
| if first_char not in letter_codes: | ||
| return True | ||
|
|
||
| if pattern_text[1] not in ('1', '2', '8', '9'): | ||
| return True | ||
|
|
||
| try: | ||
| code = letter_codes[first_char] | ||
| n1 = code // 10 | ||
| n2 = code % 10 | ||
|
|
||
| digits = [n1, n2] + [int(char) for char in pattern_text[1:]] | ||
| weights = [1, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1] | ||
| total = sum(d * w for d, w in zip(digits, weights)) | ||
|
|
||
| return total % 10 != 0 | ||
| except ValueError: | ||
| return True | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import pytest | ||
| from presidio_analyzer.predefined_recognizers.country_specific.tw import TwNationalIdRecognizer | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def recognizer(): | ||
| return TwNationalIdRecognizer() | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "text, expected_len, expected_positions", | ||
| [ | ||
| # Valid Taiwan IDs (Verified with Modulus-10 checksum) | ||
| ("My ID is A123456789.", 1, ((9, 19),)), | ||
| ("B120000008", 1, ((0, 10),)), | ||
| ("F120000002", 1, ((0, 10),)), | ||
| ("H120000004", 1, ((0, 10),)), | ||
| # Adjacent to Chinese characters | ||
| ("身分證A123456789", 1, ((3, 13),)), | ||
| # Invalid Formats / Non-Matches / Checksum Failures | ||
| ("A323456789", 0, ()), # Invalid gender code (3) | ||
| ("A12345678", 0, ()), # Too short | ||
| ("A1234567890", 0, ()), # Too long | ||
| ("1123456789", 0, ()), # Missing letter | ||
| ("a123456789", 0, ()), # Lowercase prefix rejected | ||
| ("A123456780", 0, ()), # Checksum failure | ||
| ], | ||
| ) | ||
| def test_tw_national_id_recognizer(text, expected_len, expected_positions, recognizer): | ||
| results = recognizer.analyze(text, entities=["TW_NATIONAL_ID"]) | ||
| assert len(results) == expected_len | ||
| if expected_len > 0: | ||
| assert (results[0].start, results[0].end) == expected_positions[0] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,6 +3,7 @@ | |
|
|
||
| import pathspec | ||
| import yaml | ||
|
|
||
| from presidio_analyzer import AnalyzerEngine | ||
|
|
||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 2 additions & 2 deletions
4
presidio-image-redactor/presidio_image_redactor/image_redactor_engine.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ArjunPakhan
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The path you used for the recognizer is incorrect.
It should be presidio/presidio-analyzer/presidio_analyzer/predefined_recognizers
CC: @SharonHart