PopTurk / code /berx /textnorm.py
Jyo-K's picture
Upload folder using huggingface_hub
d231962 verified
Raw History Blame Contribute Delete
14 kB
"""Text normalisation and the derived columns the rest of the pipeline consumes.
The raw TSVs carry only `entity_id, business_name, business_address, country`. The server
pipeline consumed pre-computed derived columns; that preprocessing code did not survive, so it
is rewritten here to the same contract:
country_norm casefolded country, whitespace collapsed ("US" -> "us")
name_norm accent/case/punctuation-normalised full name
name_core name_norm with the trailing legal form removed
legal_suffix the legal form that was removed ("" if none)
address_abbrev_norm normalised address with learned abbreviations applied
address_numbers set of numeric tokens in the address
TWO TEXT VIEWS, deliberately (Model-5 s5, Model-2 s1):
* rule-free (name_norm, name_core, address_norm) -> used by FEATURES, so every country
including unseen France looks the same to the model
* rule-applied (name_core_abbr, address_abbrev_norm) -> used ONLY by lexical blocking,
where learned expansions widen recall
The cross-encoder always receives RAW `business_name` / `business_address` (see
ber.cross_encoder.pair_text). This is not an oversight - it was measured. On validation,
entities whose true pairs carry an ASYMMETRIC legal form scored 0.98334 against 0.98042 for
symmetric ones, i.e. the fine-tuned cross-encoder already discounts "private limited"/"inc"
by itself. Normalising the neural input away would discard signal for no gain.
"""
from __future__ import annotations
import re
import unicodedata
from collections import Counter, defaultdict
# --------------------------------------------------------------------------- constants
# Legal forms observed in the data. FRENCH FORMS ARE INCLUDED ON PURPOSE: the test set is
# 14.975% France and no French label exists, so nothing downstream can learn them. Measured
# prevalence in the test data - French records carrying an unstripped French form: 17.35%
# (sasu 4.34%, sci 3.76%, sarl 3.34%, sas 2.34%). The S1/S2-S3 asymmetry is large and
# systematic (france 8.98% vs 19.15%/18.57%; india 0.11% vs 21.55%/23.49%).
LEGAL_FORMS = {
# US / international
"inc", "incorporated", "llc", "l l c", "lc", "ltd", "limited", "corp", "corporation",
"co", "company", "lp", "llp", "pllc", "pc", "pa", "plc", "trust", "holdings",
# India
"pvt", "private", "pte",
# France (label-free: no French training data exists)
"sa", "sarl", "sas", "sasu", "sci", "eurl", "snc", "scop", "scm", "selarl", "sel",
"scs", "sca", "scic", "gie", "ei", "eirl", "scp", "sem",
# Devanagari. 6.3% of the S2 test rows are written in Devanagari and they carry the same
# legal forms transliterated, which the Latin list cannot match. Without these,
# "आनंद फाउंडेशन प्राइवेट लिमिटेड" keeps its legal form while the Latin-script record for
# the same business has it stripped - manufacturing exactly the asymmetry the S1/S2-S3
# measurements showed is already the largest in the data.
"लिमिटेड", "लि", "प्राइवेट", "प्रा", "प्रायवेट", "पीवीटी", "कंपनी", "कम्पनी",
"इंक", "कॉर्प", "कॉर्पोरेशन", "एलएलपी", "एलएलसी",
}
# Multi-token legal forms, longest first so "private limited" wins over "limited".
LEGAL_PHRASES = [
"private limited", "pvt ltd", "pvt limited", "private ltd",
"limited liability company", "limited liability partnership",
"societe a responsabilite limitee", "societe par actions simplifiee",
# Devanagari equivalents, longest first
"प्राइवेट लिमिटेड", "प्रायवेट लिमिटेड", "प्रा लि", "पीवीटी लिमिटेड", "प्राइवेट लि",
]
_NUM = re.compile(r"\d+")
_WS = re.compile(r"\s+")
def _build_class(keep_categories) -> str:
"""Compact regex character class of every codepoint NOT in `keep_categories`.
Built by scanning the BMP once at import (~65k iterations, milliseconds) and collapsing the
result into ranges.
This exists because `\\w` IS NOT USABLE HERE. Python's `\\w` excludes Unicode marks
(categories Mn/Mc/Me), and Devanagari vowel signs are marks - so `[^\\w\\s]` deletes the
vowels out of Indian business names, and `\\w+` refuses to tokenise them. That silently
destroyed a large share of the India rows until the smoke test caught it.
"""
bad = []
for cp in range(0x10000):
ch = chr(cp)
if ch.isspace():
continue
if unicodedata.category(ch)[0] not in keep_categories:
bad.append(cp)
ranges, start, prev = [], None, None
for cp in bad:
if start is None:
start = prev = cp
elif cp == prev + 1:
prev = cp
else:
ranges.append((start, prev))
start = prev = cp
if start is not None:
ranges.append((start, prev))
parts = []
for a, b in ranges:
if a == b:
parts.append(re.escape(chr(a)))
else:
parts.append(f"{re.escape(chr(a))}-{re.escape(chr(b))}")
return "".join(parts)
# Keep Letters, Numbers and Marks; everything else becomes a space.
_DROP_CLASS = _build_class({"L", "N", "M"})
_PUNCT = re.compile(f"[{_DROP_CLASS}]", re.UNICODE)
# A token is a maximal run of anything we keep - i.e. of anything not in the drop class and not
# whitespace. Derived from the same category scan so the two can never disagree.
_WORD = re.compile(f"[^{_DROP_CLASS}\\s]+", re.UNICODE)
# --------------------------------------------------------------------------- primitives
def strip_accents(s: str) -> str:
"""Fold Latin accents (cafe/café) WITHOUT damaging non-Latin scripts.
A naive "NFKD then drop every combining mark" is WRONG on this dataset and the smoke test
catches it. Devanagari vowel signs are combining marks, so that approach turns
"राम मार्केटिंग" into "रम मरकटग" - it deletes the vowels from a large share of the Indian
records and quietly wrecks every string feature computed on them.
A combining mark is therefore dropped only when the base character it attaches to is Latin.
"""
out = []
base_is_latin = False
for ch in unicodedata.normalize("NFKD", s):
if unicodedata.combining(ch):
if not base_is_latin:
out.append(ch) # keep matras, CJK marks, Arabic harakat, ...
continue
cp = ord(ch)
base_is_latin = cp < 0x0250 or 0x1E00 <= cp <= 0x1EFF
out.append(ch)
return "".join(out)
def norm_text(s) -> str:
"""Casefold, accent-fold, drop punctuation, collapse whitespace."""
if s is None:
return ""
s = strip_accents(str(s)).casefold()
s = _PUNCT.sub(" ", s)
return _WS.sub(" ", s).strip()
def norm_country(s) -> str:
"""Country is an OPEN STRING SET. It is only ever compared for equality and never
whitelisted, one-hot encoded, or filtered against a fixed list (Model-5 s22)."""
return _WS.sub(" ", str(s or "").casefold()).strip()
def tokens(s) -> list[str]:
return _WORD.findall(str(s).casefold()) if s else []
def numbers(s) -> set[str]:
return set(_NUM.findall(str(s))) if s else set()
def alnum_tokens(s) -> set[str]:
"""Tokens containing at least one digit - house numbers, unit numbers, postcodes.
These carry most of the address's identifying power."""
return {t for t in tokens(s) if any(ch.isdigit() for ch in t)}
# --------------------------------------------------------------------------- legal forms
def split_legal_suffix(name_normalised: str) -> tuple[str, str]:
"""Return (core, legal_suffix). Only TRAILING legal forms are removed - "Trust Bank of
India" keeps "trust", while "Acme Trust" does not. Returns the original string as the core
if stripping would empty it."""
s = name_normalised
if not s:
return "", ""
for phrase in LEGAL_PHRASES:
if s.endswith(" " + phrase) or s == phrase:
core = s[: -len(phrase)].strip()
return (core or s), phrase
parts = s.split()
removed = []
while len(parts) > 1 and parts[-1] in LEGAL_FORMS:
removed.insert(0, parts.pop())
if not removed:
return s, ""
return " ".join(parts), " ".join(removed)
def has_legal_form(raw_name) -> bool:
"""Whether a raw name carries any known legal form anywhere (used for diagnostics)."""
return bool(LEGAL_FORMS & set(tokens(norm_text(raw_name))))
# --------------------------------------------------------------------------- abbreviations
def is_abbrev(short: str, long: str) -> bool:
"""Language-independent abbreviation test: prefix, or ordered subsequence sharing the
first letter. corp->corporation, pvt->private, rd->road. Deliberately dictionary-free so
it behaves identically on unseen countries."""
if not short or not long or len(short) >= len(long) or short[0] != long[0]:
return False
if long.startswith(short):
return len(short) >= 2
it = iter(long)
return len(short) >= 2 and all(ch in it for ch in short)
def _leftovers(a: list[str], b: list[str]):
sa, sb = set(a), set(b)
return [t for t in a if t not in sb], [t for t in b if t not in sa]
def mine_abbreviations(pos_pairs, neg_pairs=(), min_support=5, min_precision=0.8):
"""Mine short->long token rules from TRAIN-FOLD POSITIVE PAIRS ONLY.
pos_pairs / neg_pairs: iterables of (text_a, text_b).
LEAKAGE: this must only ever see the fitting fold's positives. Mining on all labels and
then validating leaks the answer into the blocking view.
A caution from the original run: the mined map was visibly noisy - it contained
`of -> officefinance`, `be -> blue`, `ca -> care`. Chinmay's ablation found the map gave
NO measurable gain (K1 recall@30: 0.5844 with, 0.5852 without). It is kept because it is
cheap and only affects the blocking view, but do not expect anything from it, and keep
`min_precision` high.
"""
pos_cnt: Counter = Counter()
short_cnt: Counter = Counter()
for a, b in pos_pairs:
ta, tb = tokens(a), tokens(b)
la, lb = _leftovers(ta, tb)
for x, ys, yfull in ((la, lb, tb), (lb, la, ta)):
for s in x:
short_cnt[s] += 1
for l in ys:
if is_abbrev(s, l):
pos_cnt[(s, l)] += 1
if 2 <= len(s) <= 6: # initialism
for i in range(len(yfull) - len(s) + 1):
seg = yfull[i:i + len(s)]
if "".join(t[0] for t in seg) == s:
pos_cnt[(s, " ".join(seg))] += 1
break
neg_cnt: Counter = Counter()
for a, b in neg_pairs:
ta, tb = tokens(a), tokens(b)
la, lb = _leftovers(ta, tb)
for x, ys in ((la, lb), (lb, la)):
for s in x:
for l in ys:
if is_abbrev(s, l):
neg_cnt[(s, l)] += 1
best: dict[str, tuple[int, str]] = {}
for (s, l), n in pos_cnt.items():
if n < min_support:
continue
prec = n / (n + neg_cnt.get((s, l), 0))
if prec < min_precision:
continue
if s not in best or n > best[s][0]:
best[s] = (n, l)
return {s: l for s, (_, l) in best.items()}
def apply_abbrev(text: str, amap: dict[str, str]) -> str:
"""Rule-APPLIED view. Only used for lexical blocking, never for features."""
if not amap:
return text
return " ".join(amap.get(t, t) for t in text.split())
def learn_address_rules(pairs, min_support=20, min_precision=0.85):
"""Learn address token expansions (rd->road, st->street) per country, from positives."""
cnt: Counter = Counter()
for a, b in pairs:
ta, tb = tokens(a), tokens(b)
la, lb = _leftovers(ta, tb)
for x, ys in ((la, lb), (lb, la)):
for s in x:
for l in ys:
if is_abbrev(s, l):
cnt[(s, l)] += 1
out: dict[str, tuple[int, str]] = {}
for (s, l), n in cnt.items():
if n >= min_support and (s not in out or n > out[s][0]):
out[s] = (n, l)
return {s: l for s, (_, l) in out.items()}
# --------------------------------------------------------------------------- driver
def derive_columns(df, name_col="business_name", addr_col="business_address",
country_col="country", abbrev_map=None, addr_map=None):
"""Add every derived column in place and return the frame.
Safe to call on S1, S2 and S3 identically. `abbrev_map` / `addr_map` are the learned
rule-applied views; pass None during the first pass (before rules exist).
"""
df["country_norm"] = df[country_col].map(norm_country)
df["name_norm"] = df[name_col].map(norm_text)
split = df["name_norm"].map(split_legal_suffix)
df["name_core"] = [x[0] for x in split]
df["legal_suffix"] = [x[1] for x in split]
df["address_norm"] = df[addr_col].map(norm_text)
df["address_numbers"] = df["address_norm"].map(lambda s: ",".join(sorted(numbers(s))))
if abbrev_map:
df["name_core_abbr"] = df["name_core"].map(lambda s: apply_abbrev(s, abbrev_map))
else:
df["name_core_abbr"] = df["name_core"]
if addr_map:
df["address_abbrev_norm"] = df["address_norm"].map(lambda s: apply_abbrev(s, addr_map))
else:
df["address_abbrev_norm"] = df["address_norm"]
return df
DERIVED_COLS = ["country_norm", "name_norm", "name_core", "legal_suffix", "address_norm",
"address_numbers", "name_core_abbr", "address_abbrev_norm"]