Download src/preprocessing/pii.py from khiemdztv/civic-backup: direct link, hf CLI and curl.
- Browser
- Download file 5.64 kB
-
https://huggingface.co/khiemdztv/civic-backup/resolve/main/src/preprocessing/pii.py
- Command line
-
hf download hf://khiemdztv/civic-backup/src/preprocessing/pii.py
-
curl -L -o pii.py https://huggingface.co/khiemdztv/civic-backup/resolve/main/src/preprocessing/pii.py
5.64 kB
| """Khử PII ở thời điểm SUY LUẬN (dữ liệu mới của dân chưa qua làm sạch). | |
| Dữ liệu trong data_clean/ đã được khử sẵn (thẻ <HOTEN_1>, <MAHOSO_2>...). | |
| Module này bảo đảm dữ liệu đến từ cổng tiếp nhận cũng có cùng phân phối thẻ. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from collections import Counter | |
| from typing import Dict, List, Tuple | |
| # Thứ tự QUAN TRỌNG: mẫu cụ thể chạy trước mẫu tổng quát. | |
| PII_PATTERNS: List[Tuple[str, "re.Pattern[str]"]] = [ | |
| ("EMAIL", re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.]{2,}\b")), | |
| ("CCCD", re.compile(r"(?<!\d)(?:0\d{11})(?!\d)")), | |
| ("CMND", re.compile(r"(?<!\d)\d{9}(?!\d)")), | |
| ("BHXH", re.compile(r"\b(?:m[ãa]\s*(?:s[ốo]\s*)?bhxh|s[ổo]\s*bhxh)[:\s]*([A-Z]{0,2}\d{8,12})\b", re.I)), | |
| ("MST", re.compile(r"\b(?:m[ãa]\s*s[ốo]\s*thu[ếe])[:\s]*(\d{10}(?:-\d{3})?)\b", re.I)), | |
| ("SDT", re.compile(r"(?<!\d)(?:\+?84|0)(?:3|5|7|8|9)\d{8}(?!\d)")), | |
| ("BIENSO", re.compile(r"\b\d{2}[A-Z]{1,2}[- ]?\d{3}\.?\d{2}\b")), | |
| # Mã DVC thực tế không hoàn toàn đồng nhất giữa địa phương, ví dụ: | |
| # G01.801.909-260909-890232 hoặc H29.280-260304-10571. | |
| ("MAHOSO", re.compile(r"\b[A-Z]\d{2}(?:\.\d{3}){1,2}-\d{6}-\d{4,8}\b", re.I)), | |
| ("MAHOSO", re.compile(r"\b(?:m[ãa]\s*(?:h[ồo]\s*s[ơo]|bi[êe]n\s*nh[ậa]n))[:\s]*([A-Z0-9][A-Z0-9./-]{5,})\b", re.I)), | |
| ("STK", re.compile(r"\b(?:s[ốo]\s*t[àa]i\s*kho[ảa]n|stk)[:\s]*(\d{8,20})\b", re.I)), | |
| ] | |
| _TAG_RE = re.compile(r"<([A-Z]{2,10})_(\d+)>") | |
| # Họ tên: chỉ khử khi có dấu hiệu rõ ràng để tránh nhầm địa danh (phường Trần Hưng Đạo...). | |
| # - sau cụm giới thiệu tên: "tôi tên là Nam", "họ và tên: Nguyễn Văn A" (>= 1 từ viết hoa) | |
| # - sau danh xưng: "bà Nguyễn Thị Hoa", "anh Lê Minh" (>= 2 từ viết hoa) | |
| _NAME_INTRO_RE = re.compile( | |
| r"\b(?:t[êe]n\s+t[ôo]i\s+l[àa]|t[ôo]i\s+t[êe]n\s+l[àa]|t[ôo]i\s+t[êe]n|h[ọo]\s+v[àa]\s+t[êe]n|h[ọo]\s+t[êe]n)" | |
| r"[:\s]+", re.I) | |
| # Danh xưng chỉ nhận chữ thường để không nhầm địa danh viết hoa (Bà Rịa, Cô Tô...). | |
| _NAME_TITLE_RE = re.compile(r"\b(?:ông|bà|anh|chị|cô|chú|em|cháu)\s+") | |
| _WORD_RE = re.compile(r"[^\W\d_]+") | |
| def _name_span(text: str, pos: int, min_words: int) -> int: | |
| """Độ dài chuỗi 1-4 từ viết hoa liên tiếp bắt đầu tại pos (0 nếu không đủ min_words).""" | |
| end, n = pos, 0 | |
| while n < 4: | |
| m = _WORD_RE.match(text, end) | |
| if not m or not m.group(0)[0].isupper(): | |
| break | |
| end, n = m.end(), n + 1 | |
| sp = re.match(r"[ \t]+", text[end:]) | |
| if not sp or not _WORD_RE.match(text, end + sp.end()) or \ | |
| not text[end + sp.end()].isupper(): | |
| break | |
| end += sp.end() | |
| return end - pos if n >= min_words else 0 | |
| def _redact_names(work: str, counter: int) -> Tuple[str, int]: | |
| out, i, found = [], 0, 0 | |
| marks = sorted([(m.end(), 1) for m in _NAME_INTRO_RE.finditer(work)] + | |
| [(m.end(), 2) for m in _NAME_TITLE_RE.finditer(work)]) | |
| for pos, min_words in marks: | |
| if pos < i: | |
| continue | |
| span = _name_span(work, pos, min_words) | |
| if span: | |
| found += 1 | |
| out.append(work[i:pos] + f"<HOTEN_{counter + found}>") | |
| i = pos + span | |
| out.append(work[i:]) | |
| return "".join(out), found | |
| def find_existing_tags(text: str) -> Counter: | |
| """Đếm thẻ PII đã có sẵn trong văn bản (dữ liệu data_clean).""" | |
| return Counter(m.group(1) for m in _TAG_RE.finditer(text or "")) | |
| def redact(text: str, start_index: int = 1) -> Tuple[str, Dict[str, int]]: | |
| """Thay PII bằng thẻ chuẩn. Trả (văn bản đã khử, {loại: số lần}). | |
| Giữ nguyên các thẻ đã có sẵn, chỉ đánh số tiếp cho phần mới. | |
| """ | |
| if not text: | |
| return "", {} | |
| counts: Counter = Counter() | |
| existing = find_existing_tags(text) | |
| counters = {k: max(existing.get(k, 0), start_index - 1) for k, _ in PII_PATTERNS} | |
| # Bảo vệ thẻ đã có để không khử chồng | |
| holes: List[str] = [] | |
| def keep(m: "re.Match[str]") -> str: | |
| holes.append(m.group(0)) | |
| return f"\x00{len(holes)-1}\x00" | |
| work = _TAG_RE.sub(keep, text) | |
| for kind, pat in PII_PATTERNS: | |
| def repl(m: "re.Match[str]", _k=kind) -> str: | |
| counters[_k] += 1 | |
| counts[_k] += 1 | |
| tag = f"<{_k}_{counters[_k]}>" | |
| # Nhóm 1 tồn tại nghĩa là mẫu có tiền tố (ví dụ "mã hồ sơ: XXX") | |
| if m.lastindex: | |
| return m.group(0).replace(m.group(1), tag) | |
| return tag | |
| work = pat.sub(repl, work) | |
| work, n_names = _redact_names(work, max(existing.get("HOTEN", 0), start_index - 1)) | |
| if n_names: | |
| counts["HOTEN"] += n_names | |
| work = re.sub(r"\x00(\d+)\x00", lambda m: holes[int(m.group(1))], work) | |
| return work, dict(counts) | |
| def has_slot_tag(text: str, kind: str) -> bool: | |
| """Ví dụ has_slot_tag(t, 'MAHOSO') -> công dân ĐÃ cung cấp mã hồ sơ.""" | |
| return bool(re.search(rf"<{kind}_\d+>", text or "")) | |
| # Ánh xạ thẻ PII -> slot nghiệp vụ (dùng trong state_builder & weak_label) | |
| TAG_TO_SLOT = { | |
| "MAHOSO": "application_id", | |
| "MST": "tax_code", | |
| "BHXH": "insurance_id", | |
| "BIENSO": "vehicle_plate", | |
| "SDT": "contact_channel", | |
| "EMAIL": "contact_channel", | |
| "CCCD": "citizen_doc_type", | |
| "CMND": "citizen_doc_type", | |
| "GIAYTO": "citizen_doc_type", | |
| } | |