civic-backup / src /preprocessing /text_norm.py
khiemdztv's picture
Backup source code and docs
cf29045 verified
Raw History Blame Contribute Delete
2.55 kB
"""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() + " …"