File size: 15,411 Bytes
0dd5490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""End-to-end smoke test for src.blocking and src.make_candidate_tsv on a tiny synthetic dataset.

Run with `python tests/test_blocking_smoke.py` (or pytest). Exercises the scipy fallback backend,
the sparse_dot_topn backend when importable, --max-s1 sampling, and the candidate TSV helper.
The data contains the hard cases from docs/dataset_findings.md: an Indic-script vendor name, a
domain-form name, a complete rename (both with matching addresses), an empty vendor address,
templated name collisions, orphans, singletons and a third country.
"""
import json
import os
import random
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
HEADER = "entity_id\tbusiness_name\tbusiness_address\tcountry\n"

US_A = ["Holloway", "Prime", "Westbrook", "Summit", "Riverside", "Oakridge", "Maple", "Cedar", "Liberty", "Pioneer",
        "Harbor", "Evergreen", "Golden", "Granite", "Falcon", "Keystone", "Bluebird", "Ironwood", "Sterling", "Magnolia"]
US_B = ["Dental", "Pediatric", "Seafood", "Consulting", "Logistics", "Realty", "Bakery", "Auto", "Learning", "Fitness"]
US_C = ["Group", "LLC", "Inc", "Services", "Center", "Co"]
US_ST = ["Elm", "Oak", "Westchester", "Montebello", "Ellis", "Fawn", "Center", "Lake", "Hill", "Pine", "Cedar", "Sunset"]
US_TY = [("Street", "St"), ("Road", "Rd"), ("Drive", "Dr"), ("Avenue", "Ave"), ("Court", "Ct")]
US_CITY = [("High Point", "NC"), ("Phoenix", "AZ"), ("Tahlequah", "OK"), ("Fort Worth", "TX"), ("Morganton", "NC"), ("Spicewood", "TX")]
IN_A = ["Shree", "Aditya", "Krishna", "Ganesh", "Lakshmi", "Balaji", "Durga", "Sai", "Om", "Vishnu", "Maruti", "Surya"]
IN_B = ["Marketing", "Properties", "Traders", "Enterprises", "Textiles", "Pharma", "Constructions", "Motors", "Foods"]
IN_C = ["Private Limited", "LLP", "Pvt Ltd", "Limited"]
IN_LOC = ["Gulmohar Colony", "Subhash Nagar", "MG Road", "Civil Lines", "Banjara Hills", "Salt Lake"]
IN_CITY = [("Bhopal", "Madhya Pradesh"), ("New Delhi", "Delhi"), ("Bengaluru", "Karnataka"), ("Hyderabad", "Telangana"),
           ("Kolkata", "West Bengal"), ("Pune", "Maharashtra")]
FR_A = ["Boulangerie", "Atelier", "Maison", "Cabinet", "Garage", "Pharmacie", "Librairie", "Brasserie"]
FR_B = ["Dupont", "Martin", "Lefèvre", "Moreau", "Bernard", "Petit", "Rousseau", "Fontaine"]
FR_C = ["SARL", "SAS", "EURL", "SA"]
FR_ST = ["de la Paix", "Victor Hugo", "des Lilas", "Pasteur", "du Moulin", "Jean Jaurès"]
FR_CITY = [("Lille", "Hauts-de-France"), ("Bordeaux", "Nouvelle-Aquitaine"), ("Nantes", "Pays de la Loire")]


def _typo(s, rng):
    if len(s) < 5:
        return s
    i = rng.randrange(1, len(s) - 2)
    return s[:i] + s[i + 1] + s[i] + s[i + 2:]


def _make_entity(country, rng):
    if country == "US":
        name = f"{rng.choice(US_A)} {rng.choice(US_B)} {rng.choice(US_C)}"
        full, ab = rng.choice(US_TY)
        city, st = rng.choice(US_CITY)
        street = f"{rng.choice(US_ST)} {full}"
        return name, f"{rng.randint(10, 19999)} {street}, {city}, {st}", (full, ab)
    if country == "India":
        name = f"{rng.choice(IN_A)} {rng.choice(IN_B)} {rng.choice(IN_C)}"
        city, st = rng.choice(IN_CITY)
        return name, f"{rng.randint(1, 999)}/{rng.randint(1, 99)}, {rng.choice(IN_LOC)}, {city}, {st}", ("Road", "Rd")
    name = f"{rng.choice(FR_A)} {rng.choice(FR_B)} {rng.choice(FR_C)}"
    city, reg = rng.choice(FR_CITY)
    return name, f"{rng.randint(1, 200)} rue {rng.choice(FR_ST)}, {city}, {reg}", ("rue", "R.")


def _noisy(name, addr, abbr, rng):
    r = rng.random()
    if r < 0.2:
        name = name.upper()
    elif r < 0.35:
        name = _typo(name, rng)
    elif r < 0.45:
        name = "-- " + name
    elif r < 0.55:
        name = " ".join(name.split()[:-1]) or name
    r = rng.random()
    if r < 0.3:
        addr = addr.replace(abbr[0], abbr[1]).upper()
    elif r < 0.4:
        parts = addr.split(", ")
        addr = ", ".join(parts[:1] + ["null"] + parts[1:])
    elif r < 0.5:
        addr = ", ".join(addr.split(", ")[:-1])
    elif r < 0.53:
        addr = ""
    return name, addr


def make_dataset(d: Path, seed: int = 7, n_per_country: int = 90):
    rng = random.Random(seed)
    s1, s2, s3, gt = [], [], [], []
    ids = iter(rng.sample(range(10_000, 99_999), 5000))
    special = {}

    def add_entity(country, name, addr, abbr, copies):
        sid = f"S1-{next(ids)}"
        s1.append((sid, name, addr, country))
        matched = []
        for src, (vn, va) in copies:
            vid = f"{src}-{next(ids)}"
            (s2 if src == "S2" else s3).append((vid, vn, va, country))
            matched.append(vid)
        gt.append((sid, ",".join(matched)))
        return sid, matched

    for country in ("US", "India", "France"):
        for i in range(n_per_country):
            name, addr, abbr = _make_entity(country, rng)
            if i < 8 and country == "US":  # templated name collision block
                name = "Primary Care Group"
            n_copies = rng.choice([0, 1, 2, 3, 3, 4])
            copies = [(rng.choice(["S2", "S3"]), _noisy(name, addr, abbr, rng)) for _ in range(n_copies)]
            add_entity(country, name, addr, abbr, copies)
        for src in ("S2", "S3"):  # orphans
            for _ in range(40):
                name, addr, abbr = _make_entity(country, rng)
                (s2 if src == "S2" else s3).append((f"{src}-{next(ids)}", *_noisy(name, addr, abbr, rng), country))

    special["indic"] = add_entity("India", "Ram Marketing Private Limited", "KH NO. 570/13, West Delhi, New Delhi, Delhi", None,
                                  [("S2", ("राम मार्केटिंग प्राइवेट लिमिटेड", "KH NO. -570/13, WEST DELHI, NEW DELHI, Delhi"))])
    special["domain"] = add_entity("US", "Dutta International School", "1795 Westchester Drive, High Point, NC", None,
                                   [("S3", ("duttainternationalschool.com", "1795 Westchester Dr, High Point, NC"))])
    special["rename"] = add_entity("US", "Universal Finance Group", "17560 Ellis Road, Tahlequah, OK", None,
                                   [("S2", ("Avitavowex", "17560 ELLIS RD, TAHLEQUAH, OK"))])
    special["empty_addr"] = add_entity("US", "Holloway Peak Seafood Inc", "105 Elm Street, Morganton, NC", None,
                                       [("S3", ("Holloway Peak Seafood Inc", ""))])
    rng.shuffle(s2)
    rng.shuffle(s3)
    for fn, rows in (("s1.tsv", s1), ("s2.tsv", s2), ("s3.tsv", s3)):
        with open(d / fn, "w", encoding="utf-8") as f:
            f.write(HEADER)
            f.writelines("\t".join(r) + "\n" for r in rows)
    with open(d / "gt.tsv", "w", encoding="utf-8") as f:
        f.write("source1_entity_id\tmatched_entity_ids\n")
        f.writelines(f"{a}\t{b}\n" for a, b in gt)
    return special


def _simple_norm(x):
    import re
    import unicodedata

    x = "".join(c for c in unicodedata.normalize("NFKD", x) if not unicodedata.combining(c)).lower()
    return re.sub(r"[^\w]+", " ", x).strip()


def write_norm_parquets(d: Path, special) -> Path:
    """Mimic scripts/preprocess_normalize.py output (lowercased country, list-typed address
    tokens, Indic name transliterated with legal words dropped, one null name_translit)."""
    import polars as pl

    nd = d / "norm"
    nd.mkdir(exist_ok=True)
    indic_vid = special["indic"][1][0]
    domain_vid = special["domain"][1][0]
    for tbl, fn in (("s1", "s1.tsv"), ("s2", "s2.tsv"), ("s3", "s3.tsv")):
        rows = [ln.split("\t") for ln in (d / fn).read_text(encoding="utf-8").split("\n")[1:] if ln]
        recs = []
        for eid, name, addr, country in rows:
            core = _simple_norm(name)
            translit = core
            if eid == indic_vid:
                translit = "ram marketing"  # what the lexicon would give
            if eid == domain_vid:
                translit = None  # exercise the name_core fallback
            recs.append({
                "entity_id": eid, "country": country.lower(), "name_core": core, "name_translit": translit,
                "name_spaceless": core.replace(" ", ""),
                "addr_tokens_translit": [t for t in _simple_norm(addr).split() if t != "null"],
                "raw_name": name, "raw_address": addr,
            })
        df = pl.DataFrame(recs, schema={"entity_id": pl.Utf8, "country": pl.Utf8, "name_core": pl.Utf8,
                                        "name_translit": pl.Utf8, "name_spaceless": pl.Utf8,
                                        "addr_tokens_translit": pl.List(pl.Utf8), "raw_name": pl.Utf8,
                                        "raw_address": pl.Utf8})
        df.write_parquet(nd / f"{tbl}.parquet")
        df.write_parquet(nd / f"t{tbl[1]}.parquet")  # same content as a stand-in test split
    return nd


def _run(args, cwd=ROOT):
    env = dict(os.environ, PYTHONPATH=str(ROOT))
    if sys.platform == "darwin":  # fork-based worker pools need this on macOS only
        env.setdefault("OBJC_DISABLE_INITIALIZE_FORK_SAFETY", "YES")
    r = subprocess.run([sys.executable, *args], cwd=cwd, env=env, capture_output=True, text=True)
    if r.returncode != 0:
        print(r.stdout[-5000:], r.stderr[-5000:])
        raise AssertionError(f"command failed: {args}")
    return r.stdout


def _has_sdt():
    try:
        import sparse_dot_topn  # noqa: F401  (availability check)
        return True
    except ImportError:
        return False


def run_case(d: Path, special, backend, extra=(), tag=None, inputs=None):
    import polars as pl

    tag = tag or backend
    out = d / f"cands_{tag}.parquet"
    inputs = inputs or ["--s1", str(d / "s1.tsv"), "--s2", str(d / "s2.tsv"), "--s3", str(d / "s3.tsv")]
    stdout = _run(["-m", "src.blocking", *inputs,
                   "--gt", str(d / "gt.tsv"), "--out", str(out), "--backend", backend, "--workers", "2",
                   "--max-df", "0.1", *extra])
    m = json.loads((d / f"cands_{tag}.metrics.json").read_text())
    ev = m["eval"]
    union = ev["pair_recall"]["overall"]["union"]
    assert isinstance(union, float) and 0.0 <= union <= 1.0
    for f in ("f_name", "f_nameaddr", "f_addr", "f_word", "from_reverse"):
        assert isinstance(ev["pair_recall"]["overall"][f], float)
    assert {c.lower() for c in ev["pair_recall"]["by_country"]} <= {"us", "india", "france"}
    assert set(ev["pair_recall"]["by_source"]) == {"S2", "S3"}
    assert m["cands_per_s1"]["max"] >= 1 and 0 < m["reduction_ratio"] < 1
    assert "k_x1.0" in ev["sweeps"] and "revcap_0" in ev["sweeps"] and "nameaddr" in ev["recall_at_k"]
    if "--reverse-cap" not in extra:  # the full-K sweep config must reproduce the run itself
        assert abs(ev["sweeps"]["k_x1.0"]["union_pair_recall"] - union) < 1e-9
        assert ev["sweeps"]["k_x1.0"]["pairs"] == m["n_pairs"]
    c = pl.read_parquet(out)
    for col in ("rank_name", "rank_nameaddr", "rank_addr", "rank_word", "rank_rev", "is_match"):
        assert col in c.columns, col
    assert (c.get_column("f_name") == c.get_column("rank_name").is_not_null()).all()
    assert c.select(["s1_id", "cand_id"]).is_duplicated().sum() == 0
    assert c.filter(~pl.col("cand_id").str.starts_with("S2-") & ~pl.col("cand_id").str.starts_with("S3-")).height == 0
    got = set(zip(c.get_column("s1_id").to_list(), c.get_column("cand_id").to_list()))
    sampled = "--max-s1" in extra
    queried = set(c.get_column("s1_id").to_list())
    for k, (sid, matched) in special.items():
        if sampled and sid not in queried:
            continue
        for vid in matched:
            assert (sid, vid) in got, f"{tag}: special case {k} pair ({sid},{vid}) missing"
    print(f"[{tag}] union pair recall={union:.4f} entity_any={ev['entity_any_found']['overall']['union']:.4f} "
          f"pairs={m['n_pairs']} cands/S1={m['cands_per_s1']['mean']} rr={m['reduction_ratio']:.4f}")
    return m, out, stdout


def test_smoke():
    import polars as pl

    d = Path(tempfile.mkdtemp(prefix="blocktest_"))
    special = make_dataset(d)
    m_scipy, out_scipy, stdout = run_case(d, special, "scipy")
    print(stdout[stdout.find("===== BLOCKING"):] if "BLOCKING" in stdout else stdout[-3000:])
    assert m_scipy["eval"]["pair_recall"]["overall"]["union"] >= 0.9
    if _has_sdt():
        m_sdt, out_sdt, _ = run_case(d, special, "sdt")
        a = m_scipy["eval"]["pair_recall"]["overall"]["union"]
        b = m_sdt["eval"]["pair_recall"]["overall"]["union"]
        assert abs(a - b) < 0.02, (a, b)
        # identical tf-idf, so the two backends must agree on cosines of shared pairs
        j = pl.read_parquet(out_scipy).join(pl.read_parquet(out_sdt), on=["s1_id", "cand_id"], suffix="_b")
        assert j.height > 0.9 * pl.read_parquet(out_scipy).height
        assert (j.get_column("sim_nameaddr") - j.get_column("sim_nameaddr_b")).abs().max() < 1e-4
    else:
        print("sparse_dot_topn not importable: sdt backend skipped")
    m_s, _, _ = run_case(d, special, "scipy", extra=("--max-s1", "120", "--no-fill-sims", "--reverse-cap", "5"), tag="sample")
    assert m_s["n_query_s1"] == 120 and m_s["n_pool_total"] == m_scipy["n_pool_total"]
    assert m_s["eval"]["n_query_s1"] == 120
    cs = pl.read_parquet(d / "cands_sample.parquet")
    fwd = pl.any_horizontal("f_name", "f_nameaddr", "f_addr", "f_word")
    assert cs.filter(~fwd).group_by("s1_id").len().get_column("len").max() <= 5  # reverse cap honoured
    # pre-normalised parquet input (scripts/preprocess_normalize.py layout)
    nd = write_norm_parquets(d, special)
    backend = "sdt" if _has_sdt() else "scipy"
    m_n, out_n, _ = run_case(d, special, backend, tag="normdir", inputs=["--norm-dir", str(nd), "--split", "train"])
    assert m_n["eval"]["pair_recall"]["overall"]["union"] >= 0.9
    assert set(m_n["countries"]) == {"us", "india", "france"}
    cn = pl.read_parquet(out_n)
    assert set(cn.get_column("country").unique().to_list()) == {"us", "india", "france"}
    ind_sid, ind_vids = special["indic"]  # transliterated Indic name now also matches by name
    assert cn.filter((pl.col("s1_id") == ind_sid) & (pl.col("cand_id") == ind_vids[0])).get_column("sim_name")[0] > 0.3
    out_t = d / "cands_normdir_test.parquet"
    _run(["-m", "src.blocking", "--norm-dir", str(nd), "--split", "test", "--out", str(out_t), "--backend", backend,
          "--workers", "2", "--max-df", "0.1"])
    assert pl.read_parquet(out_t).height == cn.height and "is_match" not in pl.read_parquet(out_t).columns
    print(f"[normdir] train union={m_n['eval']['pair_recall']['overall']['union']:.4f}; test split rows={cn.height}")
    # challenge TSV
    tsv = d / "candidate_pairs.tsv"
    _run(["-m", "src.make_candidate_tsv", "--candidates", str(out_scipy), "--s1", str(d / "s1.tsv"), "--out", str(tsv)])
    lines = tsv.read_text(encoding="utf-8").split("\n")
    assert lines[0] == "source1_entity_id\tcandidate_entity_ids"
    rows = [ln.split("\t") for ln in lines[1:] if ln]
    s1_ids = [ln.split("\t")[0] for ln in (d / "s1.tsv").read_text(encoding="utf-8").split("\n")[1:] if ln]
    assert [r[0] for r in rows] == s1_ids
    for r in rows:
        assert len(r) == 2
        ids = [x for x in r[1].split(",") if x]
        assert len(ids) == len(set(ids)) and all(x[:3] in ("S2-", "S3-") for x in ids)
    print(f"candidate_pairs.tsv OK: {len(rows)} rows; data in {d}")


if __name__ == "__main__":
    test_smoke()