"""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ẻ , ...). 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"(?") # 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"") 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", }