File size: 5,642 Bytes
cf29045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5653064
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf29045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5653064
 
 
 
cf29045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""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",
}