File size: 14,002 Bytes
d231962
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""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"]