File size: 2,546 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
"""Chuẩn hoá văn bản: Unicode NFC, sửa mojibake, gọn khoảng trắng, chuẩn số hiệu văn bản.

Đã đo thật: VBPL có mojibake ('Thông tư' xuất hiện 3.185 chunk) -> phải sửa trước khi index.
"""
from __future__ import annotations

import re
import unicodedata
from typing import Optional

try:
    from ftfy import fix_text as _ftfy_fix
except ImportError:                                    # pragma: no cover
    _ftfy_fix = None

_WS = re.compile(r"[ \t  -​]+")
_NL = re.compile(r"\n{3,}")
_CTRL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
# Số hiệu văn bản: "30 / 2020 / NĐ - CP" -> "30/2020/NĐ-CP"
_DOCNO_SPACED = re.compile(r"(\d{1,4})\s*/\s*(\d{4})\s*/\s*([A-ZĐ]{2,4})\s*-\s*([A-ZĐ]{2,6})")
_DOCNO_SPACED2 = re.compile(r"(\d{1,4})\s*/\s*(\d{4})\s*/\s*([A-ZĐ]{2,12})")
# Dấu hiệu mojibake latin-1/utf-8
_MOJI_HINT = re.compile(r"[ÃÂ][\x80-\xbf -ÿ]|ư|ô|áº|áu|Ä‘")


def looks_mojibake(text: str) -> bool:
    return bool(_MOJI_HINT.search(text or ""))


def fix_mojibake(text: str) -> str:
    """Sửa văn bản bị giải mã sai (utf-8 đọc thành latin-1)."""
    if not text or not looks_mojibake(text):
        return text
    if _ftfy_fix is not None:
        try:
            return _ftfy_fix(text)
        except Exception:
            pass
    try:
        return text.encode("latin-1", errors="strict").decode("utf-8", errors="strict")
    except (UnicodeEncodeError, UnicodeDecodeError):
        return text


def normalize_doc_numbers(text: str) -> str:
    text = _DOCNO_SPACED.sub(r"\1/\2/\3-\4", text)
    return _DOCNO_SPACED2.sub(r"\1/\2/\3", text)


def normalize(text: Optional[str], keep_newlines: bool = False) -> str:
    """Chuẩn hoá một đoạn văn bản. Giữ nguyên các thẻ PII dạng <HOTEN_1>."""
    if not text:
        return ""
    text = fix_mojibake(str(text))
    text = unicodedata.normalize("NFC", text)
    text = _CTRL.sub(" ", text)
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    text = normalize_doc_numbers(text)
    if keep_newlines:
        text = _WS.sub(" ", text)
        text = _NL.sub("\n\n", text)
        return "\n".join(line.strip() for line in text.split("\n")).strip()
    text = _WS.sub(" ", text.replace("\n", " "))
    return text.strip()


def truncate_chars(text: str, max_chars: int) -> str:
    if len(text) <= max_chars:
        return text
    cut = text[:max_chars]
    sp = cut.rfind(" ")
    return (cut[:sp] if sp > max_chars * 0.6 else cut).rstrip() + " …"