File size: 19,745 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""Tests for src.normalize, built from real records quoted in docs/eda_raw_output_*.txt and DuckDB
samples. Run with `python -m pytest tests/test_normalize.py` or `python tests/test_normalize.py`."""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from src.normalize import (AddrNorm, NameNorm, blocking_keys, clean_text, country_key,  # noqa: E402
                           fix_encoding, normalize_address, normalize_name, normalize_record,
                           transliterate_indic)


# ------------------------------------------------------------------ clean_text / encoding
def test_mojibake_and_c1():
    assert fix_encoding("BLOCK Â\x80\x93 EF") == "BLOCK - EF"
    assert fix_encoding("#302 Challaâ\x80\x99S Janakiram") == "#302 Challa'S Janakiram"
    assert fix_encoding("D\x92accueil SARL") == "D'accueil SARL"
    assert clean_text("BLOCK Â\x80\x93 EF, JOYOS HUB TOWN") == "block ef joyos hub town"
    assert clean_text("Next To Dâ\x80\x99Mart") == "next to dmart"
    assert "\x80" not in clean_text("GREATER KAILASH Â\x80\x93I, NEW DELHI")


def test_clean_text_accents_and_junk():
    assert clean_text("XM Résorts LLC") == "xm resorts llc"
    assert clean_text("Residents & Fïls EURL") == "residents and fils eurl"
    assert clean_text("Technology Peregrine Trades Private Límited") == \
        "technology peregrine trades private limited"
    assert clean_text(">> Capital  Partners [LLC]") == "capital partners llc"
    assert clean_text("-- Foo Bar <<") == "foo bar"
    assert clean_text("##702 FRANKLIN DR", strip_prefixes=False) == "702 franklin dr"
    assert clean_text("SXZ California  LLC | www.sxzcalifo.com") == "sxz california llc"
    assert clean_text("M/s athang fishery (india) private limited") == \
        "athang fishery india private limited"
    assert clean_text("Dr VISWA TRADERS LIMITED") == "viswa traders limited"
    assert clean_text("viprivate.c0m") == "viprivate"
    assert clean_text("26739 Saddle Rock Lane, null, New Caney", strip_prefixes=False) == \
        "26739 saddle rock lane new caney"
    # '/' and '-' survive only inside digit-bearing tokens; letter hyphens are dehyphenated
    assert clean_text("C-6/24/1, Safdar Jung", strip_prefixes=False) == "c-6/24/1 safdar jung"
    assert clean_text("PATRIOT-MINISTRIES") == "patriot ministries"
    assert clean_text("ST.-NAZAIRE") == "st nazaire"


# ------------------------------------------------------------------ names
def test_generic_append_keeps_generic_words():
    a = normalize_name("Orthopedic Crystal Care Associates Co", "US")
    b = normalize_name("Orthopedic Crystal Associates Co Services", "US")
    assert a.legal == "co" and b.legal == "co"
    assert a.core == "orthopedic crystal care associates"
    assert b.core == "orthopedic crystal associates services"   # 'services' kept, 'co' stripped


def test_legal_suffix_positions():
    n = normalize_name("LLC Valley Lfgoy Ashford", "US")
    assert n.legal == "llc" and n.core == "valley lfgoy ashford"
    assert n.tokens == ["valley", "lfgoy", "ashford"]
    assert normalize_name("Valley Legacy Ashford LLC", "US").core == "valley legacy ashford"
    assert normalize_name("Indo Consultancy Ltd-Pvt", "India").legal == "pvt ltd"
    assert normalize_name("Indo Consultancy Pvt Ltd", "India").legal == "pvt ltd"
    n = normalize_name("Pvt. EFS Print Ventures Ltd.", "India")
    assert (n.core, n.legal) == ("efs print ventures", "pvt ltd")
    n = normalize_name("Tlc LLP Shipping", "India")          # suffix moved to the middle
    assert (n.core, n.legal) == ("tlc shipping", "llp")
    n = normalize_name("Software Esteem Pharmaceuticals Private (Ltd)", "India")
    assert (n.core, n.legal) == ("software esteem pharmaceuticals", "pvt ltd")
    assert normalize_name("United Softhace [Limited]", "India").legal == "ltd"
    assert normalize_name("Faia Atlantic Kodiak Incorporated", "US").legal == "inc"
    assert normalize_name("Life Infotech Private", "India").core == "life infotech"
    assert normalize_name("Life Infotech Private Limited", "India").core == "life infotech"
    assert normalize_name("Allied Coalition ([Inc])", "US").core == "allied coalition"
    assert normalize_name("LLC LLC Foo Bar", "US").legal == "llc"   # doubled
    # 'Private' moved to the front or scrambled next to 'Limited'
    assert normalize_name("Private Asian Transcripts Ltd", "India").core == "asian transcripts"
    assert normalize_name("Hari Marketing Pivaet Limited", "India").core == "hari marketing"
    assert normalize_name("Golden Printers Limited", "India").core == "golden printers"
    assert normalize_name("Private Wealth Group", "US").core == "private wealth group"
    assert normalize_name("Marshall + Perry [Corporation]", "US").core == \
        normalize_name("Marshall & Perry", "US").core


def test_legal_france():
    n = normalize_name("SA Tourisme Societe Participations", "France")
    assert (n.core, n.legal) == ("tourisme societe participations", "sa")
    assert normalize_name("CHAMOND SANTE INTERNATIONAL SÀRL", "France").legal == "sarl"
    assert normalize_name("QW SECTION S.A.S.", "France").legal == "sas"
    assert normalize_name("Ex Amicale Distribution S.A.S.U.", "France").legal == "sasu"
    n = normalize_name("Ets Entraide SARL", "France")
    assert n.core == "entraide" and set(n.legal.split()) == {"sarl", "ets"}
    assert normalize_name("Residents & Fïls EURL", "France").core == "residents and fils"
    assert normalize_name("Ge Ecole [EURL]", "France").core == "ge ecole"


def test_name_noise_forms():
    assert normalize_name("Royal Gcomc Works [Center]", "US").core == "royal gcomc works center"
    assert normalize_name("XM Résorts LLC", "US").core == "xm resorts"
    assert normalize_name("Payne Énterprises", "US").core == "payne enterprises"
    assert normalize_name("Human-Rights  Trust", "US").core == "human rights trust"
    assert normalize_name("PIATEK LORA AND KEGLEY GLOBAL LLC", "US").core == "piatek lora and kegley global"
    assert normalize_name("Piatek, Loera and Kegley Global LLC", "US").core == "piatek loera and kegley global"
    assert normalize_name("6yan Solutions Company", "India").core == "gyan solutions"
    assert normalize_name("Tech 50ftware", "India").core == "tech software"
    assert normalize_name(">> Ear N0se & Throat Care, Inc Authority", "US").core == \
        "ear nose and throat care authority"
    assert normalize_name("M/s athang fishery (india) private limited", "India").core == \
        "athang fishery india"
    assert normalize_name("Dr VISWA TRADERS LIMITED", "India").core == "viswa traders"
    assert normalize_name("Abby  Defeo (ID: 1996)", "US").core == "abby defeo"
    assert normalize_name("BHARDWAJ CONSULTANTS GROUP #99032", "India").core == "bhardwaj consultants group"
    assert normalize_name("Fcs Trading | www.fcstradin.com", "India").core == "fcs trading"
    assert normalize_name("Rochette's  Peak Pub", "US").core == normalize_name("Rochette's Peak Pub", "US").core


def test_domain_and_handle_forms():
    n = normalize_name("shylabrothersprivate.com", "India")
    assert n.is_domain_form and n.spaceless == "shylabrothersprivate"
    n = normalize_name("duttainternationalschool.com", "India")
    assert n.is_domain_form and n.spaceless == normalize_name("Dutta International School", "India").spaceless
    assert normalize_name("viprivate.c0m", "India").spaceless == "viprivate"
    assert normalize_name("Dr mangalshreeenclave.com", "India").spaceless == "mangalshreeenclave"
    assert normalize_name("CARMELSLUSSMD.COM", "US").is_domain_form
    n = normalize_name("#BUSHSANTORO", "US")
    assert n.is_domain_form and n.core == "bushsantoro"
    assert not normalize_name("Dutta International School", "India").is_domain_form


def test_alias_forms():
    n = normalize_name("Belovera Sys f/k/a Big Seafood", "US")
    assert "big seafood" in n.alt_names and "belovera sys" in n.alt_names
    assert n.core == "big seafood"
    n = normalize_name("Nylavera+ formerly: Precision Legacy Old", "US")
    assert n.core == "precision legacy old" and "nylavera" in n.alt_names
    n = normalize_name("Miralum dba Optimal Freight Group", "US")
    assert n.alt_names == ["miralum", "optimal freight group"]
    n = normalize_name("Solfaye Sys DBA Digital Infra Private Limited", "India")
    assert (n.core, n.legal) == ("digital infra", "pvt ltd")
    assert normalize_name("Nexarc Formerly Novelle Hovnanian Inc", "US").core == "novelle hovnanian"
    assert normalize_name("Lyrazeph formerly known as Stewart, Almendarez and Mason LLC", "US").core == \
        "stewart almendarez and mason"
    assert normalize_name("Verafayevera née Vauriens Comite SAS", "France").core == "vauriens comite"
    # plain 'Nee' is a surname, not an alias marker; leading 'Aka' is a name word
    assert normalize_name("Ashlan Nee Service", "US").alt_names == []
    assert normalize_name("Aka & Frères SA", "France").alt_names == []


def test_indic_names():
    n = normalize_name("श्री ऑल केयर "
                       "प्राइवेट लिमिटेड",
                       "India")  # 'श्री ऑल केयर प्राइवेट लिमिटेड'
    assert n.has_indic_script and n.legal == "pvt ltd" and len(n.tokens) == 3
    n = normalize_name("సూర్య యునైటెడ్ "
                       "ఎంటర్‌ప్రైజెస్ "
                       "లిమిటెడ్", "India")  # Telugu, with ZWNJ
    assert n.has_indic_script and n.legal == "ltd" and "‌" not in n.core
    assert not normalize_name("Sree All Care Private Limited", "India").has_indic_script
    assert transliterate_indic("दिल्ली") is None


# ------------------------------------------------------------------ addresses
def test_us_addresses():
    a = normalize_address("TX, ##702 FRANKLIN DR, ALLEN", "US")
    assert a.street_number == "702" and a.state == "texas" and a.city == "allen"
    assert "franklin" in a.tokens and "drive" in a.tokens
    b = normalize_address("702 Franklin Drive, Allen, TX", "US")
    assert set(a.tokens) == set(b.tokens) and b.city == "allen"
    a = normalize_address("0400 D STREET, GALT, CA", "US")
    assert a.street_number == "400" and a.state == "california" and a.city == "galt"
    a = normalize_address("2103 1/2 Creekshire Dr, Sugar Land, Texas", "US")
    assert a.street_number == "2103" and a.numbers == ["2103"] and "1/2" not in a.tokens
    assert a.city == "sugar land"
    a = normalize_address("26739 Saddle Rock Lane, null, New Caney, Texas", "US")
    assert "null" not in a.tokens and a.city == "new caney" and "null" not in " ".join(a.parts)
    a = normalize_address("3728 600, PO BOX 4156, ALEXANDRIA, IN", "US")
    assert "4156" not in a.numbers and "box" not in a.tokens and a.state == "indiana"
    assert a.city == "alexandria" and a.street_number == "3728"
    a = normalize_address("Illinois, Tinley Park, 18410 Pine Cone Drive, # UNIT 4", "US")
    assert a.city == "tinley park" and a.street_number == "18410" and a.state == "illinois"
    a = normalize_address("15 Entin Ter, Warwick, New York", "US")
    assert "terrace" in a.tokens and a.state == "new york"
    a = normalize_address("3315 FREMONT SAINT, PEORIA, IL", "US")   # 'Saint' noise for 'Street'
    assert "street" in a.tokens and "saint" not in a.tokens
    a = normalize_address("8686 Larknpur Ln, Saint John, Indiana", "US")
    assert a.city == "saint john" and "lane" in a.tokens
    assert normalize_address("Jenks, NULL, 225 Main Street, Oklahoma", "US").city == "jenks"
    assert normalize_address("004906 161rd Ter, <NULL>, Beaverton, Oregon", "US").street_number == "4906"
    # no street number: the street-type part is the street; US trailing 'City'/'CDP' noise is dropped
    assert normalize_address("Texas, Missouri City, Kenforest Drive", "US").city == "missouri"
    assert normalize_address("11337  TAYLOR PINES DR, MARYLAND HEIGHTS CDP, MO", "US").city == "maryland heights"
    assert normalize_address("301 Ann Street, Granite CTIY, Oklahoma", "US").city == "granite"
    assert normalize_address("672-676 CHESHIRE RD, OH, DELAWARE", "US").state == "ohio"   # code beats city name
    assert normalize_address("Racine, 1235 W Lawn Avenue, PMB 8031, Wisconsin", "US").numbers == ["1235"]
    assert normalize_address("", "US") == AddrNorm()


def test_india_addresses():
    a = normalize_address("H.NO 677 C-6/24/1, SAFAR JUNG DEVLP AREA, NEW DELHI, "
                          "दिल्ली", "India")   # दिल्ली
    assert a.state == "delhi" and a.street_number == "677" and a.city == "new delhi"
    assert "c-6/24/1" in a.tokens and {"6", "24", "1"} <= set(a.numbers)
    assert normalize_address("C-6/24/1, Safdar Jung Devlp Area, New Delhi, Delhi", "India").state == "delhi"
    a = normalize_address("Hyderabad, Ameerpet, 8-3-224/8/B/27, TG", "India")
    assert a.state == "telangana" and a.street_number == "8"
    a = normalize_address("#16-1-4/1, Mahabubnagar H.o, Mahabub Nagar, TG", "India")
    assert a.street_number == "16" and a.city == "mahabub nagar"
    a = normalize_address("Taragana P.O.Pallasahi, Ichhapur, Bhadrak, Orissa", "India")
    assert a.state == "odisha"
    assert normalize_address("Dl-126 Basanti Colony, Rourkela, OD, Sundargarh", "India").state == "odisha"
    a = normalize_address("FLAT NO:406, FLORA APRATMENTS, ROAD NO:2, BANJARA HILLS, HYDERABAD, "
                          "Andhra Pradesh", "India")
    assert a.street_number == "406" and a.city == "hyderabad" and a.state == "andhra pradesh"
    assert "no" not in a.tokens
    a = normalize_address("#401 P-31 Sunder Mohan Avenue, Kolkata, Calcutta, WB", "India")
    assert a.state == "west bengal" and a.tokens.count("kolkata") == 2   # legacy name folded
    assert normalize_address("Megha Arcade, Bengaluru, Bangalore, KA", "India").city == "bengaluru"
    a = normalize_address("Door No 301, Nashik, MH", "India")
    assert a.street_number == "301" and a.state == "maharashtra"
    a = normalize_address("A-153 Fourth Floor Sector-19 Dwarka, New Delhi, South West Delhi, "
                          "दिल्ली", "India")
    assert a.street_number == "153" and "sector" in a.tokens and "19" in a.tokens
    a = normalize_address("NO 516 REWA CHAMBERS31 NEW MARINE LINES, MUMBAI, Maharashtra", "India")
    assert a.street_number == "516"
    a = normalize_address("Sco ##8 Sandy Square Near Paras Down Town Sqauar, Zirakpur, <NULL>, PB", "India")
    assert a.state == "punjab" and a.city == "zirakpur"
    # every Indic state part seen in the data maps to a Latin state name
    for indic, latin in [("महाराष्ट्र", "maharashtra"),
                         ("ગુજરાત", "gujarat"),
                         ("తెలంగాణ", "telangana"),
                         ("ಕರ್ನಾಟಕ", "karnataka"),
                         ("ଓଡ଼ିଶା", "odisha")]:
        assert normalize_address("12 MG ROAD, PUNE, " + indic, "India").state == latin


def test_france_addresses():
    a = normalize_address("63 R. DE DIEPPE, LILLE, Hauts-de-France", "France")
    assert "rue" in a.tokens and a.city == "lille" and a.state == "hauts de france"
    assert a.street_number == "63"
    a = normalize_address("17 BIS ALLÉE CARLE VERNET, PESSAC", "France")
    assert a.street_number == "17" and "allee" in a.tokens and "bis" not in a.tokens
    assert a.city == "pessac"
    assert normalize_address("X, ST.-NAZAIRE", "France").city == "saint nazaire"
    assert normalize_address("X, ST-NAZAIRE", "France").city == "saint nazaire"
    assert normalize_address("2 Allée des Magnolias, Saint-Nazaire, Pays de la Loire", "France").city == \
        "saint nazaire"
    a = normalize_address("3 Rue César Franck, LA TESTE DE BUCH", "France")
    b = normalize_address("3 Rue César Franck, La Teste-de-Buch, Nouvelle-Aquitaine", "France")
    assert a.city == b.city == "la teste de buch"
    a = normalize_address("BORDEAUX, Gironde, 97 R DES ORANGERS", "France")
    assert a.city == "bordeaux" and a.district == "gironde" and a.state == "" and a.street_number == "97"
    a = normalize_address("27 R FERNAND MARIN, Gironde, BORDEAUX", "France")
    assert a.city == "bordeaux"
    a = normalize_address("N° 55 Rue Masséna, Calais, Hauts-de-France", "France")
    assert a.street_number == "55" and "massena" in a.tokens and "no" not in a.tokens
    a = normalize_address("Nº 50 CITÉ LAFON, BORDEAUX, Gironde", "France")
    assert a.street_number == "50"
    assert normalize_address("(127) RUE JEAN-RENAUD DANDICOLLE, BORDEAUX", "France").street_number == "127"
    a = normalize_address("10 CH. DE LA COTONNIÈRE, LILLE", "France")
    assert "chemin" in a.tokens and "cotonniere" in a.tokens
    a = normalize_address("Lille, 2 Imp. Becker", "France")
    assert "impasse" in a.tokens and a.city == "lille"
    assert "saint" in normalize_address("Lille, Hauts-de-France, 6 PL Saint Andre", "France").tokens
    a = normalize_address("8 b Avenue des Sports, Pornic, Pays de la Loire", "France")
    assert a.street_number == "8" and "b" not in a.tokens
    assert normalize_address("29bis R. Scribe, Nantes, Pays de la Loire", "France").street_number == "29"
    a = normalize_address("Rue Darras, Lille", "France")      # street number dropped by the vendor
    assert a.city == "lille" and a.street == "rue darras"


# ------------------------------------------------------------------ record / blocking / countries
def test_record_and_blocking():
    rec = normalize_record("Piatek, Loera and Kegley Global LLC", "702 Franklin Drive, Allen, TX", "US")
    assert rec["name_legal"] == "llc" and rec["addr_city"] == "allen" and rec["country"] == "us"
    assert "us|cs|allen|702" in rec["blocking_keys"]
    rec2 = normalize_record("PIATEK LORA AND KEGLEY GLOBAL LLC", "TX, ##702 FRANKLIN DR, ALLEN", "US")
    assert set(rec["blocking_keys"]) & set(rec2["blocking_keys"])
    keys = blocking_keys(normalize_name("Belovera Sys f/k/a Big Seafood", "US"), None, "US")
    assert "us|ns|bigseafood" in keys and "us|ns|beloverasys" in keys
    n = normalize_name("Valley Legacy Ashford LLC", "US")
    a = normalize_address("400 D Street, Unit 320, Galt, CA", "US")
    assert "us|cr|galt|ashford" in blocking_keys(n, a, "US", token_df={"valley": 900, "legacy": 50, "ashford": 3})


def test_open_country_set():
    assert country_key("USA") == "us" and country_key(" India ") == "india" and country_key("FRANCE") == "france"
    assert country_key("Deutschland") == "deutschland"
    n = normalize_name("Müller & Söhne GmbH", "Deutschland")
    assert isinstance(n, NameNorm) and n.core.startswith("muller and sohne")
    a = normalize_address("Hauptstraße 5, Berlin", "Deutschland")
    assert a.city == "berlin" and a.state == ""
    assert normalize_name("", "US") == NameNorm()


if __name__ == "__main__":
    import inspect
    import re as _re

    src = inspect.getsource(sys.modules[__name__])
    n_asserts = len(_re.findall(r"^\s+assert ", src, flags=_re.M))
    tests = [(k, v) for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
    failed = 0
    for name, fn in tests:
        try:
            fn()
            print(f"PASS {name}")
        except AssertionError as e:  # pragma: no cover
            failed += 1
            import traceback
            tb = traceback.extract_tb(e.__traceback__)[-1]
            print(f"FAIL {name} (line {tb.lineno}): {tb.line}")
    print(f"{len(tests) - failed}/{len(tests)} tests passed, {n_asserts} assert statements")
    sys.exit(1 if failed else 0)