"""A. Administrative-level equivalence, learned from the pool with no labels. THE PROBLEM. The generator rewrites the administrative tail of an address: it swaps a region for a department, or a department for a district. In a 25-pair sample of France's uncertain band this was about half the cases - the single largest identified cause of France's weakness (France model-expected F0.5 0.975 against US 0.986 / India 0.989). Nothing downstream can learn it, because there are no French labels at all. WHY IT IS LEARNABLE ANYWAY. Three signals exist inside the data itself, so this uses no external gazetteer and stays inside the competition's no-external-data rule: 1. STREET PIVOT (strongest). Two records that share a house number and street name are almost certainly the same place. Whatever administrative names they disagree on are therefore names for the same place. This is what actually discovers "Hauts-de-France" ~ "Pas-de-Calais": nothing else in the data states it. 2. NESTING. A single record that writes both a region and its department co-occurs them. This is weaker - it proves containment, not substitutability - so it is weighted down. 3. POSTCODE. A postcode prefix is a deterministic in-data key. Two administrative names whose postcode-prefix distributions agree are compatible even when they never co-occur. All three are counted, combined, and filtered on support and on a precision-like ratio. The output is a symmetric equivalence map plus a name -> postcode-prefix distribution. GENERIC BY DESIGN. Nothing here is French. The same swap exists in India (district vs state) and the US (county vs state), so the miner runs per country and the feature is country-blind. That also means it can be validated on a country that HAS labels before it is trusted on one that does not - which is the only honest way to check a France-only change. """ from __future__ import annotations import json import math import re from collections import Counter, defaultdict from . import textnorm as T _SPLIT = re.compile(r"[,;/|\n]+") _POSTCODE = re.compile(r"\b(\d{4,6})\b") _HOUSENO = re.compile(r"\b\d{1,5}[a-zA-Z]?\b") # Components that are never administrative names: unit/floor markers and bare ordinals. # Floor, unit and building markers. A component made only of these is a position inside a # building, never an administrative name. The French entries are here because the miner found # them empirically: without them "rdc" and "rez de chaussee" (ground floor) and "batiment b" # came out as equivalents of Lille and Bordeaux, since a ground floor genuinely does co-occur # with every street in the city. This is normalisation vocabulary in the same sense as the # existing legal-form list, not an external gazetteer. _NOISE = {"unit", "suite", "ste", "apt", "apartment", "floor", "fl", "no", "number", "building", "bldg", "block", "plot", "khno", "kh", "door", "room", "shop", # France "rdc", "rez de chaussee", "rez", "chaussee", "batiment", "bat", "etage", "esc", "escalier", "porte", "appartement", "appt", "bp", "boite postale", "cedex", "bis", "ter", "lieu dit", "zi", "za", "zac", # India "gali", "marg", "opp", "near", "behind", "above"} # Connectives carry no place identity on their own, but they DO appear inside real names # ("hauts de france", "loire atlantique"), so they are only ever dropped when a component # consists of nothing else. _CONNECTIVE = {"de", "du", "des", "la", "le", "les", "d", "l", "sur", "sous", "en", "et"} # --------------------------------------------------------------------------- parsing def parse_address(addr: str) -> dict: """Split one raw address into a street key, administrative names and a postcode prefix. The split is purely structural - comma components, digits, token shape - so it behaves the same on `1795 Westchester Drive, High Point, NC` and on `12 Rue de la Paix, Lille, Nord, Hauts-de-France, 59000`. """ parts = [p.strip() for p in _SPLIT.split(str(addr or "")) if p.strip()] street, admin, pc = None, [], "" for p in parts: n = T.norm_text(p) if not n: continue toks = n.split() # A component counts as noise if every token is a marker, a connective, or a single # character. "batiment b" and "rez de chaussee" must both fall out here, so the test # cannot be a plain membership check on whole tokens. if not toks or all(t in _NOISE or t in _CONNECTIVE or len(t) == 1 for t in toks): continue m = _POSTCODE.search(p) if m and len(toks) <= 2 and any(t.isdigit() for t in toks): pc = pc or m.group(1) # a component that is just a postcode continue if street is None and _HOUSENO.search(p) and any(not t.isdigit() for t in toks): street = n # first component with a house number continue if not any(c.isdigit() for c in n): admin.append(n) if not pc: m = _POSTCODE.search(str(addr or "")) pc = m.group(1) if m else "" return {"street": street or "", "admin": admin, "admin_set": set(admin), "pc2": pc[:2] if pc else ""} def street_key(parsed: dict) -> str: """House number plus street words, order-insensitive, so field reordering cannot break it.""" s = parsed["street"] if not s: return "" toks = s.split() nums = sorted(t for t in toks if t.isdigit()) words = sorted(t for t in toks if not t.isdigit() and len(t) > 2) if not nums or not words: return "" # need both, or the key is not specific return " ".join(nums) + "|" + " ".join(words) # --------------------------------------------------------------------------- mining def mine(records, min_support: int = 6, min_ratio: float = 0.25, max_admin_card: int = 60_000, min_streets: int = 25): """Learn the equivalence map for ONE country. `records` yields raw address strings. Returns a dict ready for `json.dump`. min_support a pair must share this many distinct street keys. Stops a single noisy key (several unrelated businesses at "1 Main St") creating an equivalence. min_ratio shared street keys as a fraction of the RARER name's own street-key count. Both sides are counted in street keys. An earlier version divided street keys by record count, which is a unit mismatch, and it had exactly the wrong effect: a genuine region/department pair sharing 5,000 street keys out of 100,000 records scored 0.05 and was rejected, while a venue name appearing twice scored 1.0 and was kept. Every equivalence it produced for Lille was a building ("espace tween", "maison des sports"). min_streets a name must appear at this many distinct street keys to be eligible at all. This is what actually removes venue names: a real administrative unit covers hundreds of streets, a building covers one. max_admin_card a name at more than this many street keys is a country or a top-level region, compatible with everything and carrying no information. """ by_street: dict[str, set] = defaultdict(set) admin_freq: Counter = Counter() admin_streets: Counter = Counter() pc_dist: dict[str, Counter] = defaultdict(Counter) nest: Counter = Counter() n = 0 for addr in records: p = parse_address(addr) a = [x for x in p["admin"] if x] if not a: continue n += 1 admin_freq.update(set(a)) if p["pc2"]: for x in set(a): pc_dist[x][p["pc2"]] += 1 for i in range(len(a)): # signal 2: nesting, within a record for j in range(i + 1, len(a)): if a[i] != a[j]: nest[tuple(sorted((a[i], a[j])))] += 1 k = street_key(p) if k: by_street[k].update(a) for k, names in by_street.items(): for x in names: admin_streets[x] += 1 pivot: Counter = Counter() # signal 1: same street, different name for k, names in by_street.items(): ns = [x for x in names if min_streets <= admin_streets[x] <= max_admin_card] if len(ns) < 2 or len(ns) > 6: # >6 means the street key is degenerate continue ns = sorted(ns) for i in range(len(ns)): for j in range(i + 1, len(ns)): pivot[(ns[i], ns[j])] += 1 # signal 3: postcode-prefix agreement, as cosine over the prefix distributions def pc_agree(x: str, y: str) -> float: dx, dy = pc_dist.get(x), pc_dist.get(y) if not dx or not dy: return 0.0 keys = set(dx) & set(dy) if not keys: return 0.0 num = sum(dx[k] * dy[k] for k in keys) den = math.sqrt(sum(v * v for v in dx.values())) * math.sqrt(sum(v * v for v in dy.values())) return num / den if den else 0.0 equiv: dict[str, dict] = defaultdict(dict) considered = set(pivot) | {p for p, c in nest.items() if c >= min_support * 4} for (x, y) in considered: pv, nv = pivot.get((x, y), 0), nest.get((x, y), 0) # nesting is halved: it proves containment, not substitutability support = pv + 0.5 * nv if support < min_support: continue # Both numerator and denominator are counted in DISTINCT STREET KEYS. rarer = min(admin_streets[x], admin_streets[y]) if rarer < min_streets: continue ratio = support / rarer agree = pc_agree(x, y) if ratio < min_ratio and agree < 0.6: continue score = min(1.0, 0.6 * min(1.0, ratio / min_ratio) + 0.4 * agree) equiv[x][y] = round(score, 4) equiv[y][x] = round(score, 4) return { "n_records": n, "n_admin_names": len(admin_freq), "equiv": {k: v for k, v in equiv.items()}, "pc2": {k: c.most_common(1)[0][0] for k, c in pc_dist.items() if c}, "admin_freq": dict(admin_freq.most_common(50000)), } # --------------------------------------------------------------------------- scoring class GeoMatcher: """Turns a mined table into the five features the stacker consumes.""" def __init__(self, table: dict): self.equiv = table.get("equiv", {}) self.pc2 = table.get("pc2", {}) @classmethod def load(cls, path: str) -> "GeoMatcher": with open(path, encoding="utf-8") as fh: return cls(json.load(fh)) def features(self, addr_a: str, addr_b: str) -> dict: return self.features_pre(parse_address(addr_a), parse_address(addr_b)) def features_pre(self, pa: dict, pb: dict) -> dict: """Same features from ALREADY-PARSED addresses. A candidate table has ~24M pairs over ~12M distinct addresses, so parsing per pair does the same work four times over. `parse_many` parses each address once and this reduces a pair to set operations - the difference between minutes and hours. """ A, B = pa["admin_set"], pb["admin_set"] if not A or not B: # No administrative tail on one side. Report it rather than guessing: an empty # address is the single largest error class in this problem and the decision # layer must be able to see that this feature abstained. return {"geo_exact": 0.0, "geo_equiv": 0.0, "geo_conflict": 0.0, "geo_pc2": 0.0, "geo_valid": 0.0} inter = A & B best = float(len(inter)) for x in A - B: e = self.equiv.get(x) if e: best += max((e.get(y, 0.0) for y in B - A), default=0.0) denom = max(len(A), len(B)) exact = len(inter) / denom equiv = min(1.0, best / denom) pcm = 0.0 if pa["pc2"] and pb["pc2"]: pcm = 1.0 if pa["pc2"] == pb["pc2"] else -1.0 else: # fall back to the mined majority ga = {self.pc2.get(x) for x in A} - {None} gb = {self.pc2.get(x) for x in B} - {None} if ga and gb: pcm = 1.0 if ga & gb else -1.0 conflict = 1.0 if (equiv == 0.0 and pcm < 0) else 0.0 return {"geo_exact": exact, "geo_equiv": equiv, "geo_conflict": conflict, "geo_pc2": pcm, "geo_valid": 1.0} FEATURE_NAMES = ["geo_exact", "geo_equiv", "geo_conflict", "geo_pc2", "geo_valid"] def parse_many(addresses) -> list[dict]: """Parse a column of addresses once, for `features_pre`.""" return [parse_address(a) for a in addresses]