File size: 5,410 Bytes
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""Tách từ tiếng Việt (pyvi) — BẢO TOÀN thẻ PII và số hiệu văn bản.

pyvi phá vỡ các token đặc biệt:
    '<MAHOSO_1>'      -> '< MAHOSO_1 >'
    '30/2020/NĐ-CP'   -> '30 / 2020 / NĐ - CP'
Nên phải mask -> tokenize -> restore. Hàm này được gọi ở CẢ BA khâu
(chuẩn bị dữ liệu / huấn luyện / suy luận) để không bao giờ lệch phân phối.
"""
from __future__ import annotations

import hashlib
import re
import sqlite3
import threading
from pathlib import Path
from typing import List, Optional, Tuple

from .text_norm import normalize

try:
    from pyvi import ViTokenizer
except ImportError:                                    # pragma: no cover
    ViTokenizer = None

# Các mẫu phải giữ nguyên khối
_PROTECT = [
    re.compile(r"<[A-Z]{2,10}_\d+>"),                                   # thẻ PII
    re.compile(r"\b\d{1,4}/\d{4}/[A-ZĐ][A-ZĐ\-]{1,12}\b"),              # 30/2020/NĐ-CP
    re.compile(r"\b\d{1,4}/[A-ZĐ]{2,6}-[A-ZĐ]{2,8}\b"),                 # 287/QĐ-BTP
    re.compile(r"\b\d{1,2}/\d{1,2}/\d{4}\b"),                           # 29/11/2024
    re.compile(r"\b\d{1,2}\.\d{6}\b"),                                  # mã TTHC 1.000005
    re.compile(r"\bhttps?://\S+"),
    re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.]+\b"),
]
_PH = "zpz{}zpz"
_PH_RE = re.compile(r"zpz(\d+)zpz")


def _mask(text: str) -> Tuple[str, List[str]]:
    kept: List[str] = []

    def repl(m: "re.Match[str]") -> str:
        kept.append(m.group(0))
        return _PH.format(len(kept) - 1)

    for pat in _PROTECT:
        text = pat.sub(repl, text)
    return text, kept


def _unmask(text: str, kept: List[str]) -> str:
    if not kept:
        return text

    def repl(m: "re.Match[str]") -> str:
        i = int(m.group(1))
        return kept[i] if 0 <= i < len(kept) else m.group(0)

    # pyvi có thể nối placeholder vào từ bên cạnh bằng '_' -> tách ra trước
    text = re.sub(r"_?(zpz\d+zpz)_?", r" \1 ", text)
    text = _PH_RE.sub(repl, text)
    return re.sub(r"\s{2,}", " ", text).strip()


class _SegCache:
    """Cache sqlite trên đĩa — word-segment phải chạy 3 lần trên cùng corpus."""

    def __init__(self, path: Optional[str]):
        self.enabled = bool(path)
        self._lock = threading.Lock()
        self._conn: Optional[sqlite3.Connection] = None
        if self.enabled:
            Path(path).parent.mkdir(parents=True, exist_ok=True)
            self._conn = sqlite3.connect(path, check_same_thread=False, timeout=10.0,
                                         isolation_level=None)
            self._conn.execute("CREATE TABLE IF NOT EXISTS seg (k TEXT PRIMARY KEY, v TEXT)")
            self._conn.execute("PRAGMA journal_mode=WAL")
            self._conn.commit()

    @staticmethod
    def _key(text: str) -> str:
        return hashlib.sha1(text.encode("utf-8")).hexdigest()

    def get(self, text: str) -> Optional[str]:
        if not self._conn:
            return None
        with self._lock:
            try:
                row = self._conn.execute(
                    "SELECT v FROM seg WHERE k=?", (self._key(text),)).fetchone()
            except sqlite3.OperationalError:
                return None
        return row[0] if row else None

    def put(self, text: str, value: str) -> None:
        if not self._conn:
            return
        with self._lock:
            try:
                self._conn.execute("INSERT OR REPLACE INTO seg VALUES (?,?)",
                                   (self._key(text), value))
            except sqlite3.OperationalError:
                # Cache contention must never break inference.
                return

    def commit(self) -> None:
        if self._conn:
            with self._lock:
                self._conn.commit()


_CACHE: Optional[_SegCache] = None


def init_cache(path: Optional[str]) -> None:
    global _CACHE
    _CACHE = _SegCache(path)


def commit_cache() -> None:
    if _CACHE:
        _CACHE.commit()


def segment(text: Optional[str], do_normalize: bool = True, use_cache: bool = True) -> str:
    """Trả văn bản đã word-segment, thẻ PII và số hiệu văn bản còn nguyên vẹn."""
    if not text:
        return ""
    raw = normalize(text) if do_normalize else str(text)
    if not raw:
        return ""
    if use_cache and _CACHE is not None:
        hit = _CACHE.get(raw)
        if hit is not None:
            return hit
    if ViTokenizer is None:                            # pragma: no cover
        out = raw
    else:
        masked, kept = _mask(raw)
        try:
            seg = ViTokenizer.tokenize(masked)
        except Exception:
            seg = masked
        out = _unmask(seg, kept)
    if use_cache and _CACHE is not None:
        _CACHE.put(raw, out)
    return out


def segment_tokens(text: Optional[str]) -> List[str]:
    return segment(text).split()


def desegment(text: str) -> str:
    """Bỏ gạch dưới ghép từ — chỉ để hiển thị cho người đọc. Giữ nguyên thẻ PII."""
    if not text:
        return ""
    holes: List[str] = []

    def keep(m: "re.Match[str]") -> str:
        holes.append(m.group(0))
        return _PH.format(len(holes) - 1)

    text = re.sub(r"<[A-Z]{2,10}_\d+>", keep, text)
    text = re.sub(r"(?<=\w)_(?=\w)", " ", text)
    return _PH_RE.sub(lambda m: holes[int(m.group(1))], text)