Download code/2fca4cd-dirty-4e8c5dbd/src/pii_detector.py from Podtech/abeja-cc-ja-cleaned: direct link, hf CLI and curl.
- Browser
- Download file 20.1 kB
-
https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/2fca4cd-dirty-4e8c5dbd/src/pii_detector.py
- Command line
-
hf download hf://datasets/Podtech/abeja-cc-ja-cleaned/code/2fca4cd-dirty-4e8c5dbd/src/pii_detector.py
-
curl -L -o pii_detector.py https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/2fca4cd-dirty-4e8c5dbd/src/pii_detector.py
20.1 kB
| """日本語Web文書向けの限定的なPII検出・置換器。 | |
| ``PII_detect.md`` の検出方針を踏まえた、外部モデルに依存しない決定的な | |
| ベースラインである。公開用データでは、検出した値を削除するのではなく、 | |
| 種別ごとのプレースホルダーへ置換する。対象は次の7種類に限定する。 | |
| * 電話番号 | |
| * メールアドレス | |
| * 番地レベルの住所 | |
| * 個人名と所属の組合せ | |
| * マイナンバー | |
| * クレジットカード番号 | |
| * 銀行口座番号 | |
| 郵便番号だけ、IPアドレス、秘密情報、生年月日などは対象外とする。個人名 | |
| だけは「氏名:」等のラベル文脈に限って置換する。番号系(マイナンバー、 | |
| カード、口座)はURLでは検出せず、本文でもラベル文脈か区切り書式を必須にする | |
| (無作為な数字列の1割はチェックデジットを通るため)。将来 fuseji、GLiNER-ja、GiNZA 等を追加する場合は | |
| ``PIIDetector`` の結果へ検出結果を追加できる。 | |
| """ | |
| from __future__ import annotations | |
| import re | |
| import unicodedata | |
| from dataclasses import dataclass | |
| from typing import Any, Iterable | |
| PII_LABELS_JA = { | |
| "email": "メールアドレス", | |
| "phone": "電話番号", | |
| "address": "番地レベルの住所", | |
| "person_affiliation": "個人名+所属", | |
| "person_name": "個人名", | |
| "my_number": "マイナンバー", | |
| "credit_card": "クレジットカード番号", | |
| "bank_account": "銀行口座番号", | |
| } | |
| PLACEHOLDERS = { | |
| "email": "<EMAIL>", | |
| "phone": "<PHONE>", | |
| "address": "<ADDRESS>", | |
| "person_affiliation": "<PERSON_AFFILIATION>", | |
| "person_name": "<PERSON_NAME>", | |
| "my_number": "<MY_NUMBER>", | |
| "credit_card": "<CREDIT_CARD>", | |
| "bank_account": "<BANK_ACCOUNT>", | |
| } | |
| TARGET_PII_TYPES = tuple(PII_LABELS_JA) | |
| class PIIMatch: | |
| """検出されたPIIの位置と監査用メタデータ。位置はNFKC後の文字列基準。""" | |
| pii_type: str | |
| field: str | |
| start: int | |
| end: int | |
| value: str | |
| method: str | |
| confidence: str = "high" | |
| def label_ja(self) -> str: | |
| return PII_LABELS_JA.get(self.pii_type, self.pii_type) | |
| def masked_value(self) -> str: | |
| return mask_value(self.pii_type, self.value) | |
| def placeholder(self) -> str: | |
| return PLACEHOLDERS.get(self.pii_type, "<PII>") | |
| def to_dict(self) -> dict[str, Any]: | |
| return { | |
| "pii_type": self.pii_type, | |
| "pii_type_ja": self.label_ja, | |
| "field": self.field, | |
| "start": self.start, | |
| "end": self.end, | |
| "matched_value_masked": self.masked_value, | |
| "method": self.method, | |
| "confidence": self.confidence, | |
| "placeholder": self.placeholder, | |
| } | |
| def normalize_text(value: Any) -> str: | |
| """全角・半角差を吸収して照合する。""" | |
| if value is None: | |
| return "" | |
| return unicodedata.normalize("NFKC", str(value)) | |
| def mask_value(pii_type: str, value: str) -> str: | |
| """監査JSONにPIIそのものを再掲しないためのマスキング。""" | |
| if not value: | |
| return "" | |
| if pii_type == "email" and "@" in value: | |
| local, domain = value.split("@", 1) | |
| masked_local = local[0] + "*" * max(1, len(local) - 2) + local[-1:] | |
| return f"{masked_local}@{domain}" | |
| if pii_type in {"phone", "my_number", "credit_card", "bank_account"}: | |
| chars = list(value) | |
| positions = [i for i, char in enumerate(chars) if char.isalnum()] | |
| keep = 4 | |
| for index in positions[:-keep]: | |
| chars[index] = "*" | |
| return "".join(chars) | |
| if pii_type == "address": | |
| return value[:3] + "***" | |
| if pii_type == "person_affiliation": | |
| return "***" | |
| return "***" | |
| def is_valid_luhn(value: str) -> bool: | |
| digits = [int(char) for char in value if char.isdigit()] | |
| if len(digits) < 13 or len(digits) > 19: | |
| return False | |
| checksum = 0 | |
| parity = len(digits) % 2 | |
| for index, digit in enumerate(digits): | |
| if index % 2 == parity: | |
| digit *= 2 | |
| if digit > 9: | |
| digit -= 9 | |
| checksum += digit | |
| return checksum % 10 == 0 | |
| def is_valid_mynumber(value: str) -> bool: | |
| """12桁の個人番号のチェックデジットを検証する。""" | |
| digits = [int(char) for char in value if char.isdigit()] | |
| if len(digits) != 12: | |
| return False | |
| # 左から11桁に対して、右から 2,3,4,5,6,7 を繰り返す。 | |
| weights = [2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6] | |
| total = sum(digit * weight for digit, weight in zip(reversed(digits[:11]), weights)) | |
| check_digit = (11 - (total % 11)) % 10 | |
| return check_digit == digits[-1] | |
| EMAIL_RE = re.compile( | |
| r"(?<![A-Za-z0-9._%+\-])([A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+)(?![A-Za-z0-9._%+\-])" | |
| ) | |
| PHONE_SEPARATED_RE = re.compile( | |
| # 改行を区切りに含めない。住所末尾の番地と次行の電話番号を | |
| # ひとつの不正な候補として連結しないため、空白は半角スペース・タブのみ。 | |
| # 先行する郵便番号・日付などが不正候補になっても、後続の電話番号の | |
| # 開始位置を検査できるよう、候補全体を先読みして重複開始を許可する。 | |
| r"(?<!\d)(?=(?P<value>(?:\+81[ \t-]?)?0?\d{1,4}[ \t-]\d{1,4}[ \t-]\d{3,4})(?!\d))" | |
| ) | |
| PHONE_MOBILE_RE = re.compile(r"(?<!\d)0[789]0\d{8}(?!\d)") | |
| PHONE_PLAIN_RE = re.compile( | |
| r"(?<!\d)(?:0120\d{6}|0570\d{6}|050\d{8}|0[1-9]\d{8})(?!\d)" | |
| ) | |
| PHONE_CONTEXT_RE = re.compile( | |
| # ラベル候補も先読みして、TELの後に別のFAXが続く場合などの | |
| # 後続ラベルを取りこぼさない。 | |
| r"(?=(?:電話|携帯|連絡先|tel|telephone|phone|fax|ファクシミリ|ファックス)\s*[::]?[^0-9+]{0,10}(?P<value>\+?\d[\d\s().-]{8,18}\d))", | |
| re.IGNORECASE, | |
| ) | |
| # 12桁(4-4-4区切りも可)。チェックデジットに加えて、ラベル文脈を必須にする。 | |
| # 無作為な12桁の1割はチェックデジットを通るため、URL中のIDや注文番号を誤検出しないため。 | |
| MY_NUMBER_RE = re.compile(r"(?<![\d-])(?:\d{4}[ -]?\d{4}[ -]?\d{4})(?![\d-])") | |
| MY_NUMBER_CONTEXT_RE = re.compile(r"(?:個人番号|マイナンバー|my\s*number)", re.IGNORECASE) | |
| # 13〜19桁。区切り書式(4-4-4-4、4-6-5 等)かラベル文脈を必須にする(Luhn だけでは1割が通る)。 | |
| CARD_RE = re.compile(r"(?<![\d-])(?:\d{4}[ -]\d{4}[ -]\d{4}[ -]\d{1,7}|\d{4}[ -]\d{6}[ -]\d{5}|\d{13,19})(?![\d-])") | |
| CARD_CONTEXT_RE = re.compile( | |
| r"(?:カード番号|クレジットカード|クレカ|card\s*(?:no\.?|number)|credit\s*card|visa|master\s*card|jcb|amex|american\s*express|diners)", | |
| re.IGNORECASE, | |
| ) | |
| # 直前にこれらのラベルがある数字列は注文・伝票等の番号とみなして除外する。 | |
| NUMBER_NEGATIVE_CONTEXT_RE = re.compile( | |
| r"(?:注文番号|受注番号|伝票番号|追跡番号|お問い?合わせ番号|受付番号|管理番号|会員番号|予約番号|商品番号|型番|isbn|jan|tracking|order\s*(?:no\.?|number))", | |
| re.IGNORECASE, | |
| ) | |
| # 都道府県・市区町村に続く番地(1-2-3、1丁目2番3号等)を必須にする。番地の後ろの | |
| # 建物名・部屋番号も住所の一部として取り込む(「<ADDRESS>-802」のような取り残しを防ぐ)。 | |
| _ADDRESS_BLOCK = r"(?:\d+(?:[--]\d+){1,3}|\d+丁目\d+番(?:\d+号?)?)" | |
| _ADDRESS_TAIL = ( | |
| r"(?:\s*[^\s,、。\n()()]{0,20}?(?:ビル|マンション|ハイツ|コーポ|レジデンス|アパート|タワー|ハウス|荘|寮|号館)[^\s,、。\n()()]{0,10})?" | |
| r"(?:\s*\d{1,4}\s*(?:号室|号|[Ff]|階))?" | |
| ) | |
| ADDRESS_RE = re.compile( | |
| r"(?P<value>(?:北海道|東京都|大阪府|京都府|[一-龥々]{2,3}県)[^,、。\n]{1,60}?(?:市|区|町|村)[^,、。\n]{0,35}?" + _ADDRESS_BLOCK + _ADDRESS_TAIL + r")" | |
| ) | |
| # ラベル付きの住所は、都道府県が省かれた「宇都宮市江野町1-15」の形も許可する(残存確認で発見した取りこぼし)。 | |
| ADDRESS_CONTEXT_RE = re.compile( | |
| r"(?:住所|所在地|送付先|配送先)\s*[::]?\s*(?P<value>(?:北海道|東京都|大阪府|京都府|[一-龥々]{2,3}県|[一-龥々ぁ-ゖァ-ヶー]{1,6}(?:市|区|郡))[^\n。,、]{1,80}?" + _ADDRESS_BLOCK + _ADDRESS_TAIL + r")" | |
| ) | |
| # 氏名: 漢字2〜6字、または漢字1〜3字+かな2〜6字(佐藤ゆかり)。「皆さん」のような1字+さんは拾わない。 | |
| _NAME = r"(?:[一-龥々]{2,6}|[一-龥々]{1,3}\s?[ぁ-ゖァ-ヶー]{2,6})" | |
| # 所属: 法人格で始まる名称、または組織を示す語尾で終わる名称(20字以内)。任意で部署。 | |
| _ORG_PREFIX = r"(?:株式会社|有限会社|合同会社|合資会社|一般社団法人|一般財団法人|公益社団法人|公益財団法人|[Nn][Pp][Oo]法人|学校法人|医療法人|社会福祉法人|独立行政法人|国立研究開発法人)" | |
| _ORG_SUFFIX = r"(?:株式会社|有限会社|合同会社|会社|大学院|大学|高等学校|高校|中学校|小学校|専門学校|病院|クリニック|医院|省|庁|県庁|市役所|区役所|町役場|村役場|銀行|信用金庫|研究所|研究センター|協会|連盟|組合|法律事務所|事務所|事務局|財団|法人|商工会議所|観光局|放送局|新聞社|出版社)" | |
| _ORG = rf"(?:{_ORG_PREFIX}[^\s。、,,()()]{{1,20}}|[^\s。、,,()()のがはをにでと]{{1,20}}?{_ORG_SUFFIX})" | |
| _DEPT = r"(?:\s*[^\s。、,,()()]{0,15}?(?:部|課|室|科|係|チーム|支店|支社|営業所|研究室))?" | |
| # 所属の後ろに続く役職(「株式会社ABC 代表」「○○会 会員」)も置換範囲に含める。 | |
| _TITLE_OPT = r"(?:\s*[^\s。、,,()()の]{0,8}?(?:長|社長|部長|課長|主任|教授|准教授|講師|代表|取締役|[Cc][Ee][Oo]|[Cc][Tt][Oo]|マネージャー|リーダー|担当|研究員|弁護士|職員|会員|理事|社員|員))?" | |
| _TITLE = r"(?:[^\s。、,,()()の]{0,8}?(?:長|社長|部長|課長|主任|教授|准教授|講師|代表|取締役|[Cc][Ee][Oo]|[Cc][Tt][Oo]|マネージャー|リーダー|担当|研究員|弁護士))" | |
| # 「氏名:山田太郎(株式会社ABC)」「担当者:山田太郎、株式会社ABC 営業部」 | |
| NAME_AFFILIATION_LABEL_RE = re.compile( | |
| r"(?:氏名|お名前|担当者|代表者|名義人?)\s*[::]\s*" | |
| rf"(?P<value>(?P<name>{_NAME})\s*(?:[((、,]|所属\s*[::])\s*(?P<affiliation>{_ORG}{_DEPT}{_TITLE_OPT})[))]?)" | |
| ) | |
| # 「山田太郎さん、株式会社ABC」「山田太郎氏(株式会社ABC 営業部)」 | |
| NAME_AFFILIATION_SUFFIX_RE = re.compile( | |
| rf"(?P<value>(?P<name>{_NAME})(?:さん|氏|様|先生)[、,\s((]+(?P<affiliation>{_ORG}{_DEPT}{_TITLE_OPT})[))]?)" | |
| ) | |
| # 「株式会社ABC 営業部 部長 山田太郎さん」「○○大学教授・山田太郎氏」(所属→役職→氏名の順)。 | |
| # 役職か「・」区切りのどちらかと、敬称を必須にする。「会社の同僚さん」のような役割語を氏名にしないため。 | |
| AFFILIATION_NAME_RE = re.compile( | |
| rf"(?P<value>(?P<affiliation>{_ORG}{_DEPT})\s*(?:(?:の)?\s*{_TITLE}\s*(?:・|の|\s)?|・)\s*(?P<name>{_NAME})(?:さん|氏|様|先生))" | |
| ) | |
| # 個人名だけ(ラベル文脈)。かな名も許可し、フォームの定型語は除外する。 | |
| _NAME_TOKEN = r"[一-龥々ぁ-ゖァ-ヶー]{1,8}" | |
| NAME_CONTEXT_RE = re.compile( | |
| r"(?:氏名|お名前|名前|担当者|代表者|名義人?)\s*[::]\s*" | |
| rf"(?P<value>{_NAME_TOKEN}(?:\s*{_NAME_TOKEN})?)" | |
| ) | |
| NAME_STOPWORDS = {"必須", "任意", "未定", "なし", "不明", "非公開", "匿名", "ニックネーム", "ハンドルネーム", "例", "未入力", "空欄", "入力"} | |
| BANK_CONTEXT_RE = re.compile( | |
| r"(?:口座番号|口座|振込先|銀行口座)\D{0,20}(?P<value>\d{7})(?!\d)" | |
| ) | |
| # URL では数字列がIDであることが多く、番号系の検出は行わない(メール・電話のみ)。 | |
| URL_EXCLUDED_TYPES = frozenset({"my_number", "credit_card", "bank_account"}) | |
| def _has_context(text: str, position: int, pattern: re.Pattern[str], window: int) -> bool: | |
| """position の直前 window 文字以内に pattern があるか。""" | |
| return pattern.search(text, max(0, position - window), position) is not None | |
| def _digits(value: str) -> str: | |
| return "".join(char for char in value if char.isdigit()) | |
| def _valid_phone(value: str) -> bool: | |
| digits = _digits(value) | |
| if value.startswith("+81"): | |
| digits = "0" + digits[2:] | |
| if len(digits) not in {10, 11} or not digits.startswith("0"): | |
| return False | |
| if digits.startswith(("070", "080", "090")): | |
| return len(digits) == 11 | |
| return digits[1] in "123456789" and len(digits) in {10, 11} | |
| def _overlap(first: PIIMatch, second: PIIMatch) -> bool: | |
| return first.start < second.end and second.start < first.end | |
| def _select_non_overlapping(matches: Iterable[PIIMatch]) -> list[PIIMatch]: | |
| """重なった候補は、長く信頼度の高い候補を優先して1回だけ置換する。""" | |
| confidence_rank = {"high": 2, "medium": 1, "low": 0} | |
| ordered = sorted( | |
| matches, | |
| key=lambda item: ( | |
| item.start, | |
| -(item.end - item.start), | |
| -confidence_rank.get(item.confidence, 0), | |
| ), | |
| ) | |
| selected: list[PIIMatch] = [] | |
| for candidate in ordered: | |
| if any(_overlap(candidate, existing) for existing in selected): | |
| continue | |
| selected.append(candidate) | |
| return sorted(selected, key=lambda item: (item.start, item.end, item.pii_type)) | |
| class PIIDetector: | |
| """URLと本文から指定7種類だけを検出し、プレースホルダーへ置換する。""" | |
| def __init__(self, include_url: bool = True) -> None: | |
| self.include_url = include_url | |
| def detect(self, text: Any, field: str = "content") -> list[PIIMatch]: | |
| normalized = normalize_text(text) | |
| if not normalized: | |
| return [] | |
| matches: list[PIIMatch] = [] | |
| def add( | |
| pattern: re.Pattern[str], | |
| pii_type: str, | |
| method: str, | |
| confidence: str = "high", | |
| group: str | None = None, | |
| ) -> None: | |
| for found in pattern.finditer(normalized): | |
| value = found.group(group) if group else found.group(0) | |
| start = found.start(group) if group else found.start() | |
| end = found.end(group) if group else found.end() | |
| matches.append(PIIMatch(pii_type, field, start, end, value, method, confidence)) | |
| add(EMAIL_RE, "email", "regex_email") | |
| for found in PHONE_SEPARATED_RE.finditer(normalized): | |
| value = found.group("value") | |
| if _valid_phone(value): | |
| matches.append(PIIMatch("phone", field, found.start("value"), found.end("value"), value, "regex_phone")) | |
| for found in PHONE_MOBILE_RE.finditer(normalized): | |
| if _valid_phone(found.group(0)): | |
| matches.append(PIIMatch("phone", field, found.start(), found.end(), found.group(0), "regex_phone")) | |
| for found in PHONE_PLAIN_RE.finditer(normalized): | |
| if _valid_phone(found.group(0)): | |
| matches.append(PIIMatch("phone", field, found.start(), found.end(), found.group(0), "regex_phone")) | |
| for found in PHONE_CONTEXT_RE.finditer(normalized): | |
| value = found.group("value") | |
| if _valid_phone(value): | |
| matches.append(PIIMatch("phone", field, found.start("value"), found.end("value"), value, "context_phone", "medium")) | |
| if field != "url": | |
| for found in MY_NUMBER_RE.finditer(normalized): | |
| value = found.group(0) | |
| if not is_valid_mynumber(value): | |
| continue | |
| if _has_context(normalized, found.start(), NUMBER_NEGATIVE_CONTEXT_RE, 20): | |
| continue | |
| # 区切り書式だけでは数表・型番を誤検出するため、マイナンバーはラベル文脈を必須にする。 | |
| if _has_context(normalized, found.start(), MY_NUMBER_CONTEXT_RE, 40): | |
| matches.append(PIIMatch("my_number", field, found.start(), found.end(), value, "checksum_mynumber")) | |
| for found in CARD_RE.finditer(normalized): | |
| value = found.group(0) | |
| if not is_valid_luhn(value) or len(_digits(value)) == 12: | |
| continue | |
| if _has_context(normalized, found.start(), NUMBER_NEGATIVE_CONTEXT_RE, 20): | |
| continue | |
| labeled = _has_context(normalized, found.start(), CARD_CONTEXT_RE, 40) | |
| grouped = not value.isdigit() | |
| if labeled or grouped: | |
| matches.append(PIIMatch("credit_card", field, found.start(), found.end(), value, "checksum_luhn", "high" if labeled else "medium")) | |
| patterns = [ | |
| (ADDRESS_RE, "address", "regex_address"), | |
| (ADDRESS_CONTEXT_RE, "address", "context_address"), | |
| (NAME_AFFILIATION_LABEL_RE, "person_affiliation", "context_name_affiliation"), | |
| (NAME_AFFILIATION_SUFFIX_RE, "person_affiliation", "context_name_affiliation"), | |
| (AFFILIATION_NAME_RE, "person_affiliation", "context_affiliation_name"), | |
| ] | |
| if field != "url": | |
| patterns.append((BANK_CONTEXT_RE, "bank_account", "context_bank_account")) | |
| for pattern, pii_type, method in patterns: | |
| add(pattern, pii_type, method, "medium", "value") | |
| for found in NAME_CONTEXT_RE.finditer(normalized): | |
| value = found.group("value") | |
| if value in NAME_STOPWORDS or value.split()[0] in NAME_STOPWORDS: | |
| continue | |
| matches.append(PIIMatch("person_name", field, found.start("value"), found.end("value"), value, "context_name", "medium")) | |
| # 同一type・同一位置の重複を除き、出現順に返す。重複範囲は検出結果として | |
| # 残すが、置換時には _select_non_overlapping で一つにまとめる。 | |
| unique: dict[tuple[str, str, int, int], PIIMatch] = {} | |
| for match in matches: | |
| unique[(match.pii_type, match.field, match.start, match.end)] = match | |
| return sorted(unique.values(), key=lambda item: (item.start, item.end, item.pii_type)) | |
| def detect_record(self, url: Any, content: Any) -> list[PIIMatch]: | |
| matches: list[PIIMatch] = [] | |
| if self.include_url: | |
| matches.extend(self.detect(url, "url")) | |
| matches.extend(self.detect(content, "content")) | |
| return matches | |
| def replace_text(self, text: Any, field: str = "content") -> tuple[str, list[PIIMatch]]: | |
| """PIIをプレースホルダーに置換し、実際に置換した候補を返す。 | |
| NFKC正規化後の文字列を返すため、全角のメールアドレス等も一貫した | |
| 表記になる。検出位置は返却文字列(置換前のNFKC文字列)に対応する。 | |
| """ | |
| normalized = normalize_text(text) | |
| if not normalized: | |
| return normalized, [] | |
| selected = _select_non_overlapping(self.detect(normalized, field)) | |
| replaced = normalized | |
| for match in reversed(selected): | |
| replaced = replaced[: match.start] + match.placeholder + replaced[match.end :] | |
| return replaced, selected | |
| def replace_record(self, url: Any, content: Any) -> tuple[str, str, list[PIIMatch]]: | |
| replaced_url, url_matches = (self.replace_text(url, "url") if self.include_url else (normalize_text(url), [])) | |
| replaced_content, content_matches = self.replace_text(content, "content") | |
| return replaced_url, replaced_content, url_matches + content_matches | |
| def matches_to_dict(matches: Iterable[PIIMatch]) -> list[dict[str, Any]]: | |
| return [match.to_dict() for match in matches] | |