Download code/scripts/preprocess_normalize.py from Arushhh/amlc-work: direct link, hf CLI and curl.
- Browser
- Download file 6.52 kB
-
https://huggingface.co/datasets/Arushhh/amlc-work/resolve/main/code/scripts/preprocess_normalize.py
- Command line
-
hf download hf://datasets/Arushhh/amlc-work/code/scripts/preprocess_normalize.py
-
curl -L -o preprocess_normalize.py https://huggingface.co/datasets/Arushhh/amlc-work/resolve/main/code/scripts/preprocess_normalize.py
6.52 kB
| """Apply src/normalize.py to all six tables (train s1,s2,s3 + test t1,t2,t3) with multiprocessing and | |
| attach transliterated names using the learned lexicons. Writes ROOT/norm/<table>.parquet. | |
| Usage on the box: cd /data/amlc/code && ROOT=/data/amlc WORKERS=16 /data/venv/bin/python scripts/preprocess_normalize.py [tables...] | |
| """ | |
| import os, sys, json, time, re, unicodedata | |
| from multiprocessing import Pool | |
| import pyarrow as pa, pyarrow.parquet as pq | |
| HERE=os.path.dirname(os.path.dirname(os.path.abspath(__file__))); sys.path.insert(0, HERE) | |
| from src.normalize import normalize_record | |
| R=os.environ.get('ROOT','/data/amlc'); W=int(os.environ.get('WORKERS','16')); CH=int(os.environ.get('CHUNK','40000')) | |
| INDIC=re.compile(r'[ऀ-]') | |
| NAME_LEX={}; ADDR_LEX={} | |
| LEGAL_LATIN={'private','limited','pvt','ltd','llp','opc','inc','incorporated','corp','corporation','co','company','llc','plc','pc','lp','sa','sarl','sas','sasu','eurl','sci','ei','ets'} | |
| def _load_lex(): | |
| global NAME_LEX, ADDR_LEX | |
| p=f'{R}/artifacts/translit_name_lexicon.json'; q=f'{R}/artifacts/translit_addr_lexicon.json' | |
| if os.path.exists(p): NAME_LEX={k:v['latin'] for k,v in json.load(open(p)).items()} | |
| if os.path.exists(q): ADDR_LEX={k:v['latin'] for k,v in json.load(open(q)).items()} | |
| def _translit_tokens(raw_name): | |
| """Map Indic-script tokens of the RAW name through the lexicon (lexicon keys are raw whitespace tokens).""" | |
| out=[]; unk=0 | |
| for t in raw_name.split(): | |
| if INDIC.search(t): | |
| m=NAME_LEX.get(t) or NAME_LEX.get(t.strip('.,()')) | |
| if m: out.append(m) | |
| else: unk+=1; out.append(t) | |
| else: | |
| t2=unicodedata.normalize('NFKD',t); t2=''.join(c for c in t2 if not unicodedata.combining(c)).lower() | |
| t2=re.sub(r'[^a-z0-9]+',' ',t2).strip() | |
| if t2: out.extend(t2.split()) | |
| return out, unk | |
| def work(args): | |
| ids, names, addrs, countries = args | |
| if not NAME_LEX: _load_lex() | |
| rows=[]; errs=0 | |
| for i,(eid,n,a,c) in enumerate(zip(ids,names,addrs,countries)): | |
| try: | |
| r=normalize_record(n or '', a or '', c or '') | |
| except Exception as e: | |
| errs+=1; r={'country':(c or '').lower(),'name_core':'','name_legal':'','name_tokens':[],'name_spaceless':'','name_alt_names':[],'name_is_domain_form':False,'name_has_indic_script':bool(INDIC.search(n or '')),'name_full':'','addr_tokens':[],'addr_numbers':[],'addr_street_number':'','addr_city':'','addr_state':'','addr_parts':[],'addr_district':'','addr_localities':[],'addr_street':'','blocking_keys':[]} | |
| if r.get('name_has_indic_script'): | |
| toks,unk=_translit_tokens(n or ''); toks=[t for t in toks if t not in LEGAL_LATIN]; r['name_translit_tokens']=toks; r['name_translit_unknown']=unk | |
| else: | |
| r['name_translit_tokens']=r['name_tokens']; r['name_translit_unknown']=0 | |
| r['name_translit']=' '.join(r['name_translit_tokens']) | |
| # address: map Indic tokens (state/city names) through the address lexicon | |
| at=[] | |
| for t in r['addr_tokens']: | |
| if INDIC.search(t): at.append(ADDR_LEX.get(t, t)) | |
| else: at.append(t) | |
| r['addr_tokens_translit']=at | |
| r['entity_id']=eid; r['raw_name']=n or ''; r['raw_address']=a or '' | |
| r.pop('addr_postal',None) | |
| rows.append(r) | |
| return rows, errs | |
| SCHEMA=pa.schema([ | |
| ('entity_id',pa.string()),('country',pa.string()),('raw_name',pa.string()),('raw_address',pa.string()), | |
| ('name_core',pa.string()),('name_legal',pa.string()),('name_tokens',pa.list_(pa.string())),('name_spaceless',pa.string()), | |
| ('name_alt_names',pa.list_(pa.string())),('name_is_domain_form',pa.bool_()),('name_has_indic_script',pa.bool_()),('name_full',pa.string()), | |
| ('name_translit',pa.string()),('name_translit_tokens',pa.list_(pa.string())),('name_translit_unknown',pa.int32()), | |
| ('addr_tokens',pa.list_(pa.string())),('addr_tokens_translit',pa.list_(pa.string())),('addr_numbers',pa.list_(pa.string())), | |
| ('addr_street_number',pa.string()),('addr_city',pa.string()),('addr_state',pa.string()),('addr_parts',pa.list_(pa.string())), | |
| ('addr_district',pa.string()),('addr_localities',pa.list_(pa.string())),('addr_street',pa.string()),('blocking_keys',pa.list_(pa.string())), | |
| ]) | |
| def _to_table(rows): | |
| cols={f.name:[r.get(f.name) for r in rows] for f in SCHEMA} | |
| arrays=[] | |
| for f in SCHEMA: | |
| v=cols[f.name] | |
| if pa.types.is_list(f.type): v=[[str(x) for x in (vv or [])] for vv in v] | |
| elif pa.types.is_string(f.type): v=['' if vv is None else str(vv) for vv in v] | |
| elif pa.types.is_boolean(f.type): v=[bool(vv) for vv in v] | |
| else: v=[int(vv or 0) for vv in v] | |
| # Build the array with an explicit type so an all-empty list column (e.g. name_alt_names with | |
| # no rows matched in this chunk) is still typed list<string>, not the list<null> pyarrow infers | |
| # from an untyped Python list of empty lists — that mismatch broke ParquetWriter.write_table | |
| # across chunks with a fixed schema. | |
| arrays.append(pa.array(v, type=f.type)) | |
| return pa.Table.from_arrays(arrays, schema=SCHEMA) | |
| def run_table(tbl): | |
| t0=time.time(); src=f'{R}/parquet/{tbl}.parquet'; os.makedirs(f'{R}/norm',exist_ok=True); out=f'{R}/norm/{tbl}.parquet' | |
| T=pq.read_table(src, columns=['entity_id','business_name','business_address','country']) | |
| ids=T.column('entity_id').to_pylist(); names=T.column('business_name').to_pylist(); addrs=T.column('business_address').to_pylist(); cs=T.column('country').to_pylist() | |
| n=len(ids); chunks=[(ids[i:i+CH],names[i:i+CH],addrs[i:i+CH],cs[i:i+CH]) for i in range(0,n,CH)] | |
| print(f"[{tbl}] rows={n} chunks={len(chunks)} workers={W}", flush=True) | |
| writer=None; errs=0; done=0 | |
| with Pool(W) as pool: | |
| for rows,e in pool.imap(work, chunks, chunksize=1): | |
| errs+=e; done+=len(rows) | |
| tab=_to_table(rows) | |
| if writer is None: writer=pq.ParquetWriter(out, SCHEMA, compression='zstd') | |
| writer.write_table(tab) | |
| if done % (CH*25) == 0: print(f" {tbl}: {done}/{n} {time.time()-t0:.0f}s", flush=True) | |
| writer.close() | |
| print(f"[{tbl}] done rows={done} errors={errs} {time.time()-t0:.0f}s -> {out}", flush=True) | |
| if __name__=='__main__': | |
| tables=sys.argv[1:] or ['s1','s2','s3','t1','t2','t3'] | |
| _load_lex(); print("lexicons:", len(NAME_LEX), "name tokens,", len(ADDR_LEX), "address tokens", flush=True) | |
| for t in tables: run_table(t) | |
| print("ALL DONE", flush=True) | |