"""Non-destructive normalization of customer text (Phase 13). * Urdu / Arabic-Indic digits -> ASCII (``ORD-۱۰۰۳`` -> ``ORD-1003``), always; * Roman Urdu spelling variants -> one canonical spelling (``mera odr kahaan he`` -> ``mera order kahan hai``), when the text is Roman Urdu; * cheap number words in Roman Urdu amounts (``do hazar rupay`` -> ``2000 rupay``). The original text is never replaced: callers keep it for display, audit and the extractor (which sees both). Normalized text is exactly as untrusted as the original. """ from __future__ import annotations import re from dataclasses import dataclass, field from functools import lru_cache from core.i18n.lexicon import AMBIGUOUS_WITH_ENGLISH, known_words, variant_map # Arabic-Indic (U+0660..0669) and Extended Arabic-Indic / Urdu (U+06F0..06F9) digits. _DIGITS = {**{0x0660 + i: str(i) for i in range(10)}, **{0x06F0 + i: str(i) for i in range(10)}} _DIGITS[0x066B] = "." # Arabic decimal separator _DIGITS[0x066C] = "," # Arabic thousands separator _WORD = re.compile(r"[A-Za-z][A-Za-z']*") _ID = re.compile(r"\b[A-Z]{2,5}-?\d{2,12}\b|\b\d+\b", re.I) UNITS = { "ek": 1, "aik": 1, "do": 2, "teen": 3, "char": 4, "chaar": 4, "paanch": 5, "panch": 5, "chhe": 6, "chay": 6, "che": 6, "saat": 7, "sat": 7, "aath": 8, "ath": 8, "nau": 9, "das": 10, "bees": 20, "tees": 30, "chalees": 40, "pachas": 50, "pachaas": 50, "sath": 60, "saath": 60, "sattar": 70, "assi": 80, "nabbe": 90, "dedh": 1.5, "dhai": 2.5, } SCALES = {"sau": 100, "hazar": 1000, "hazaar": 1000, "hajar": 1000, "lakh": 100_000} _NUMBER_RUN = re.compile( r"\b((?:(?:" + "|".join(UNITS) + r")\s+)?(?:" + "|".join(SCALES) + r")" r"(?:\s+(?:(?:" + "|".join(UNITS) + r")\s+)?(?:" + "|".join(SCALES) + r"))*" r"(?:\s+(?:" + "|".join(UNITS) + r"))?)\b", re.I, ) def _enabled() -> bool: from core.config import get_settings return get_settings().i18n_normalization_enabled def ascii_digits(text: str) -> str: return text.translate(_DIGITS) def _number_words(text: str) -> str: """``do hazar`` -> ``2000``; ``paanch sau`` -> ``500``; ``dedh lakh`` -> ``150000``. Only runs that contain a scale word (sau/hazar/lakh) are converted: a bare ``do`` is a verb ("bhej do"), never a number.""" def conv(m: re.Match[str]) -> str: total = 0.0 current = 0.0 for w in m.group(1).lower().split(): if w in UNITS: current += UNITS[w] elif w in SCALES: scale = SCALES[w] current = (current or 1) * scale if scale >= 1000: total += current current = 0 total += current return str(int(total)) if total == int(total) else m.group(1) return _NUMBER_RUN.sub(conv, text) @lru_cache(maxsize=1) def _variants() -> tuple[dict[str, str], re.Pattern[str] | None]: m = variant_map() phrases = sorted((v for v in m if " " in v), key=len, reverse=True) pat = ( re.compile(r"\b(" + "|".join(re.escape(p) for p in phrases) + r")\b", re.I) if phrases else None ) return m, pat @dataclass(frozen=True) class Normalized: original: str text: str # normalized (same as ``original`` when nothing changed) language: str # what the normalizer assumed: en | ur | roman_ur | other | und changes: list[tuple[str, str]] = field(default_factory=list) # (variant, canonical) coverage: float = 1.0 # share of words the lexicon knows (0..1); 1.0 for empty text @property def changed(self) -> bool: return self.text != self.original def normalize_roman_urdu(text: str, *, strict: bool = False) -> tuple[str, list[tuple[str, str]]]: """Map spelling variants to canonical spellings. With ``strict`` (text not known to be Roman Urdu) variants that are also English words ("he", "me", "or") are left alone.""" mapping, phrase_pat = _variants() changes: list[tuple[str, str]] = [] def phrase(m: re.Match[str]) -> str: canon = mapping[m.group(1).lower()] changes.append((m.group(1), canon)) return canon out = phrase_pat.sub(phrase, text) if phrase_pat else text def word(m: re.Match[str]) -> str: w = m.group(0) low = w.lower() canon = mapping.get(low) if canon is None or (strict and low in AMBIGUOUS_WITH_ENGLISH): return w changes.append((w, canon)) return canon return _WORD.sub(word, out), changes def coverage(text: str) -> float: """Share of word tokens (ids and numbers excluded) that the lexicon knows.""" words = [w.lower() for w in _WORD.findall(_ID.sub(" ", text))] if not words: return 1.0 known = known_words() return sum(w in known for w in words) / len(words) def normalize(text: str | None, language: str | None = None) -> Normalized: """Normalize ``text``; ``language`` defaults to :func:`core.i18n.detect.detect`.""" original = text or "" if language is None: from core.i18n.detect import detect language = detect(original).language out = ascii_digits(original) changes: list[tuple[str, str]] = [] if language == "roman_ur" and _enabled(): out, changes = normalize_roman_urdu(out) out = _number_words(out) cov = coverage(out) if language == "roman_ur" else 1.0 return Normalized(original, out, language, changes, cov) def normalize_for_rules(text: str | None) -> str: """Lower-cased text for deterministic keyword rules (COD replies, safety keywords): digits folded, Roman Urdu variants mapped (English-ambiguous ones only when the text is detected as Roman Urdu), number words converted.""" from core.i18n.detect import detect raw = ascii_digits(text or "") if not _enabled(): return raw.lower() lang = detect(raw).language out, _ = normalize_roman_urdu(raw, strict=lang != "roman_ur") return _number_words(out).lower()