Spaces:
Running
Running
Download core/i18n/detect.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 8.94 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/i18n/detect.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/i18n/detect.py
-
curl -L -o detect.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/i18n/detect.py
8.94 kB
| """Language detection for customer text: ``en`` | ``ur`` | ``roman_ur`` (Phase 13). | |
| No network, no model download, no heavy dependencies: | |
| 1. **Script.** Arabic-script letters dominate -> Urdu, unless the text looks Arabic or | |
| Persian (letters Urdu does not use: ``ة ى ي ك ه``; or frequent Arabic/Persian function | |
| words) -> ``other``. Urdu-only letters (``ٹ ڈ ڑ ں ے ھ ہ``) and Urdu function words | |
| (``ہے کا کی میں نہیں``) push towards ``ur``. | |
| 2. **Latin script: English vs Roman Urdu.** Two signals, blended: | |
| * a lexicon vote: high-frequency Roman Urdu words (``hai nahi kya mera kahan``, after | |
| spelling-variant mapping) against English function words (``the is my where``); | |
| shared loanwords (``order refund delivery``) count for neither; | |
| * a character n-gram (1-4) multinomial Naive Bayes trained at import time on the small | |
| bundled labeled set ``core/i18n/data/train.tsv`` (plus the lexicon itself). | |
| The result carries a confidence in [0, 1]; short or mixed messages get low confidence, which | |
| callers use to send Roman Urdu they may misunderstand to a human (see ``review``). | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import re | |
| from collections import Counter | |
| from dataclasses import dataclass | |
| from functools import lru_cache | |
| from pathlib import Path | |
| from typing import Literal | |
| from core.i18n.lexicon import ENGLISH_MARKERS, SHARED_LOANWORDS, STRONG_MARKERS, variant_map | |
| Language = Literal["en", "ur", "roman_ur", "other", "und"] | |
| LANGUAGES: tuple[str, ...] = ("en", "ur", "roman_ur") | |
| DATA = Path(__file__).parent / "data" | |
| _ARABIC_SCRIPT = re.compile(r"[-ۿݐ-ݿﭐ-﷿ﹰ-]") | |
| _LATIN = re.compile(r"[A-Za-z]") | |
| _URDU_ONLY = set("ٹڈڑںےھہۂۓ") # retroflex, noon ghunna, bari ye, do-chashmi he, gol he | |
| _ARABIC_ONLY = set("ةىيكهأإؤئ") # Urdu writes ی ک ہ/ھ instead; hamza-seats are rare in Urdu | |
| _PERSIAN_HINT = set("ژ") | |
| _UR_WORDS = {"ہے", "ہیں", "کا", "کی", "کے", "میں", "نہیں", "کیا", "اور", "آپ", "میرا", "میری"} | |
| _UR_WORDS |= {"کہاں", "ہوں", "تھا", "تھی", "کو", "سے", "پر", "یہ", "وہ", "جی", "ہاں", "شکریہ"} | |
| _AR_WORDS = {"في", "من", "على", "إلى", "هذا", "هذه", "التي", "الذي", "أن", "كان", "لا", "ما"} | |
| _AR_WORDS |= {"هل", "أين", "طلبي", "شكرا", "مرحبا"} | |
| _FA_WORDS = {"است", "را", "این", "که", "برای", "می", "شد", "سفارش", "کجاست", "چه", "هست"} | |
| _FA_WORDS |= {"ممنون", "سلام", "خیلی", "باید", "نیست", "من", "شما"} | |
| _WORD = re.compile(r"[A-Za-z']+|[-ۿ]+") | |
| _STRIP_IDS = re.compile(r"\b[A-Z]{2,5}-?\d{2,12}\b|\d+", re.I) | |
| class Detection: | |
| language: Language | |
| confidence: float # 0..1 | |
| script: Literal["arabic", "latin", "mixed", "none"] | |
| detail: str | None = None # e.g. "ar" / "fa" when language == "other" | |
| def reply_language(self) -> str: | |
| """Language to answer in: ``en`` / ``ur`` / ``roman_ur`` (unknown -> ``en``).""" | |
| return self.language if self.language in LANGUAGES else "en" | |
| # ------------------------------------------------------------------ char n-gram NB | |
| def _grams(text: str, n_max: int = 4) -> Counter[str]: | |
| t = f" {' '.join(_WORD.findall(_STRIP_IDS.sub(' ', text.lower())))} " | |
| c: Counter[str] = Counter() | |
| for n in range(1, n_max + 1): | |
| for i in range(len(t) - n + 1): | |
| g = t[i : i + n] | |
| if g.strip(): | |
| c[g] += 1 | |
| return c | |
| def load_labeled(name: str) -> list[tuple[str, str]]: | |
| """``label<TAB>text`` lines; ``#`` comments and blank lines skipped.""" | |
| rows: list[tuple[str, str]] = [] | |
| for line in (DATA / name).read_text(encoding="utf-8").splitlines(): | |
| if not line.strip() or line.startswith("#"): | |
| continue | |
| label, _, text = line.partition("\t") | |
| rows.append((label.strip(), text.strip())) | |
| return rows | |
| class _NB: | |
| log_prior: dict[str, float] | |
| log_prob: dict[str, dict[str, float]] | |
| log_unk: dict[str, float] | |
| def logits(self, text: str) -> dict[str, float]: | |
| grams = _grams(text) | |
| return { | |
| c: self.log_prior[c] | |
| + sum(k * self.log_prob[c].get(g, self.log_unk[c]) for g, k in grams.items()) | |
| for c in self.log_prior | |
| } | |
| def _model() -> _NB: | |
| rows = [(lab, txt) for lab, txt in load_labeled("train.tsv") if lab in ("en", "roman_ur")] | |
| # The lexicon is training data too: canonical spellings and their variants. | |
| for canon, variant in variant_map().items(): | |
| rows.append(("roman_ur", f"{canon} {variant}")) | |
| rows.append(("roman_ur", " ".join(sorted(STRONG_MARKERS)))) | |
| rows.append(("en", " ".join(sorted(ENGLISH_MARKERS)))) | |
| counts: dict[str, Counter[str]] = {"en": Counter(), "roman_ur": Counter()} | |
| docs: Counter[str] = Counter() | |
| for lab, txt in rows: | |
| counts[lab].update(_grams(txt)) | |
| docs[lab] += 1 | |
| vocab = set(counts["en"]) | set(counts["roman_ur"]) | |
| alpha = 0.5 | |
| log_prob: dict[str, dict[str, float]] = {} | |
| log_unk: dict[str, float] = {} | |
| for lab, c in counts.items(): | |
| total = sum(c.values()) + alpha * (len(vocab) + 1) | |
| log_prob[lab] = {g: math.log((c[g] + alpha) / total) for g in vocab} | |
| log_unk[lab] = math.log(alpha / total) | |
| n = sum(docs.values()) | |
| return _NB({lab: math.log(docs[lab] / n) for lab in counts}, log_prob, log_unk) | |
| def nb_roman_urdu_probability(text: str) -> float: | |
| """P(roman_ur | text) from the character n-gram model alone (length-normalized).""" | |
| lg = _model().logits(text) | |
| n = max(1, sum(_grams(text).values()) // 4) | |
| z = (lg["roman_ur"] - lg["en"]) / n # per-gram evidence, comparable across lengths | |
| z = max(-30.0, min(30.0, z * 4)) | |
| return 1 / (1 + math.exp(-z)) | |
| # ------------------------------------------------------------------ detection | |
| def _detect_arabic_script(text: str, letters: int) -> Detection: | |
| chars = set(text) | |
| words = set(_WORD.findall(text)) | |
| ur = len(chars & _URDU_ONLY) * 2 + len(words & _UR_WORDS) * 2 | |
| ar = len(chars & _ARABIC_ONLY) * 2 + len(words & _AR_WORDS) * 2 | |
| fa = len(words & _FA_WORDS) * 2 + len(chars & _PERSIAN_HINT) | |
| # Persian shares ی ک گ with Urdu but writes ه (not ہ) and lacks Urdu-only letters. | |
| if "ه" in chars and not chars & _URDU_ONLY: | |
| fa += 1 | |
| total = ur + ar + fa | |
| if total == 0: # Arabic-script text with no telltale letters or words: most likely Urdu | |
| return Detection("ur", 0.55 if letters >= 4 else 0.4, "arabic") | |
| best = max(("ur", ur), ("ar", ar), ("fa", fa), key=lambda x: x[1]) | |
| conf = best[1] / total | |
| conf = round(min(0.99, conf * min(1.0, 0.55 + letters / 30)), 3) | |
| if best[0] == "ur": | |
| return Detection("ur", conf, "arabic") | |
| return Detection("other", conf, "arabic", detail=best[0]) | |
| def detect(text: str | None) -> Detection: | |
| t = text or "" | |
| arabic = len(_ARABIC_SCRIPT.findall(t)) | |
| latin = len(_LATIN.findall(_STRIP_IDS.sub(" ", t))) | |
| if arabic + latin == 0: | |
| return Detection("und", 0.0, "none") | |
| if arabic >= latin: | |
| d = _detect_arabic_script(t, arabic) | |
| if latin and d.language == "ur": | |
| return Detection("ur", round(d.confidence * arabic / (arabic + latin), 3), "mixed") | |
| return d | |
| words = [w.lower().strip("'") for w in _WORD.findall(_STRIP_IDS.sub(" ", t))] | |
| words = [w for w in words if w and _LATIN.match(w)] | |
| mapping = variant_map() | |
| ru = en = 0.0 | |
| for w in words: | |
| if w in SHARED_LOANWORDS: | |
| continue | |
| canon = mapping.get(w, w) | |
| is_ru = canon in STRONG_MARKERS | |
| is_en = w in ENGLISH_MARKERS | |
| if is_ru and is_en: # "me", "he", "is": weak evidence both ways | |
| ru += 0.3 | |
| en += 0.3 | |
| elif is_ru: | |
| ru += 1.0 | |
| elif is_en: | |
| en += 1.0 | |
| votes = ru + en | |
| if votes == 0 and len(words) <= 2: | |
| # "Confirm", "OK", "Refund": loanwords only, no evidence either way. | |
| return Detection("und", 0.0, "mixed" if arabic else "latin") | |
| p_nb = nb_roman_urdu_probability(t) | |
| if votes >= 1: | |
| p_tok = (ru + 0.25) / (votes + 0.5) | |
| weight = min(0.8, 0.4 + 0.1 * votes) | |
| p = weight * p_tok + (1 - weight) * p_nb | |
| else: | |
| p = p_nb | |
| lang: Language = "roman_ur" if p >= 0.5 else "en" | |
| margin = abs(p - 0.5) * 2 # 0 = coin flip, 1 = certain | |
| length = min(1.0, 0.35 + 0.13 * len(words)) | |
| conf = round(min(0.99, (0.5 + margin / 2) * length), 3) | |
| script: Literal["latin", "mixed"] = "mixed" if arabic else "latin" | |
| return Detection(lang, conf, script) | |