amlc-work / code /scripts /build_translit_lexicon.py
Arushhh's picture
code snapshot
0dd5490 verified
Raw History Blame Contribute Delete
7.95 kB
"""Learn an Indic-script -> Latin token lexicon from TRAINING pairs only (position-aligned tokens),
plus an address-token lexicon by co-occurrence, and measure coverage on the TEST vendor files.
Uses only the provided data. Output: artifacts/translit_name_lexicon.json, artifacts/translit_addr_lexicon.json"""
import duckdb, json, os, time
import pandas as pd
pd.set_option("display.width", 250)
R=os.environ.get('ROOT','/data/amlc'); OUT=f'{R}/artifacts'; os.makedirs(OUT, exist_ok=True); t0=time.time()
con=duckdb.connect(f'{R}/amlc.duckdb'); con.execute(f"SET threads=12; SET memory_limit='100GB'; SET preserve_insertion_order=false; SET temp_directory='{R}/duck_tmp';")
P=lambda *a: print(*a, f"[{time.time()-t0:.0f}s]", flush=True)
INDIC=r"[\p{Devanagari}\p{Bengali}\p{Gurmukhi}\p{Gujarati}\p{Tamil}\p{Telugu}\p{Kannada}\p{Malayalam}]"
NN="trim(regexp_replace(regexp_replace(lower(strip_accents(business_name)),'[^a-z0-9]+',' ','g'),'\\s+',' ','g'))"
con.execute("CREATE OR REPLACE VIEW s23 AS SELECT *, 'S2' src FROM s2 UNION ALL SELECT *, 'S3' src FROM s3")
con.execute("CREATE OR REPLACE VIEW t23 AS SELECT *, 'S2' src FROM t2 UNION ALL SELECT *, 'S3' src FROM t3")
# ---- NAME lexicon: vendor Indic tokens aligned by position with S1 name tokens (same token count holds for 100% of such pairs)
# NOTE: the join is materialized into al_base BEFORE applying the length-equality filter, as a separate
# statement. Combining a WHERE predicate that spans two joined relations (len(split(y.business_name))
# = len(split(x.nn))) with the unmaterialized 3-way join makes DuckDB pick a catastrophic query plan
# that spills 100+GB to temp disk (observed OOM). Splitting into materialize-then-filter avoids that;
# both steps together run in well under a minute on this box.
con.execute(f"""CREATE OR REPLACE TABLE al_base AS
SELECT y.business_name bname, x.nn nn
FROM pairs p JOIN (SELECT entity_id, {NN} nn FROM s1) x ON x.entity_id=p.a JOIN s23 y ON y.entity_id=p.b
WHERE regexp_matches(y.business_name,'{INDIC}')""")
con.execute(f"""CREATE OR REPLACE TABLE al AS
SELECT unnest(string_split(trim(regexp_replace(bname,'\\s+',' ','g')),' ')) itok, unnest(string_split(nn,' ')) ltok
FROM al_base
WHERE len(string_split(trim(regexp_replace(bname,'\\s+',' ','g')),' '))=len(string_split(nn,' '))""")
con.execute("DROP TABLE al_base")
con.execute("CREATE OR REPLACE TABLE lex AS SELECT itok, ltok, n, n*1.0/sum(n) OVER (PARTITION BY itok) purity, sum(n) OVER (PARTITION BY itok) total FROM (SELECT itok, ltok, count(*) n FROM al WHERE regexp_matches(itok,'"+INDIC+"') GROUP BY 1,2) QUALIFY row_number() OVER (PARTITION BY itok ORDER BY n DESC)=1")
lex=con.execute("SELECT itok, ltok, n, purity, total FROM lex ORDER BY total DESC").df()
P("name lexicon entries", len(lex), "| occurrences covered", int(lex.total.sum()), "| purity>=0.8 share by occurrence", round(lex[lex.purity>=0.8].total.sum()/lex.total.sum(),4))
# also keep the top-3 alternatives per token (spelling variants like shree/shri/sri) for fuzzy use
alts=con.execute("SELECT itok, list(ltok ORDER BY n DESC)[1:3] alts FROM (SELECT itok, ltok, count(*) n FROM al WHERE regexp_matches(itok,'"+INDIC+"') GROUP BY 1,2) GROUP BY 1").df()
altmap=dict(zip(alts.itok, alts.alts.map(list)))
name_lex={r.itok: {"latin": r.ltok, "alts": altmap.get(r.itok, [r.ltok]), "purity": round(float(r.purity),3), "n": int(r.total)} for r in lex.itertuples()}
json.dump(name_lex, open(f'{OUT}/translit_name_lexicon.json','w'), ensure_ascii=False, indent=0)
# ---- coverage on TEST vendor names
cov=con.execute(f"""WITH tt AS (SELECT unnest(string_split(trim(regexp_replace(business_name,'\\s+',' ','g')),' ')) itok FROM t23 WHERE regexp_matches(business_name,'{INDIC}'))
SELECT count(*) occ, sum(CASE WHEN l.itok IS NOT NULL THEN 1 ELSE 0 END) covered, count(distinct tt.itok) n_types, count(distinct CASE WHEN l.itok IS NOT NULL THEN tt.itok END) covered_types
FROM tt LEFT JOIN lex l ON l.itok=tt.itok WHERE regexp_matches(tt.itok,'{INDIC}')""").df()
P("TEST name coverage:", cov.to_dict('records'))
unc=con.execute(f"""WITH tt AS (SELECT unnest(string_split(trim(regexp_replace(business_name,'\\s+',' ','g')),' ')) itok FROM t23 WHERE regexp_matches(business_name,'{INDIC}'))
SELECT tt.itok, count(*) n FROM tt LEFT JOIN lex l ON l.itok=tt.itok WHERE l.itok IS NULL AND regexp_matches(tt.itok,'{INDIC}') GROUP BY 1 ORDER BY n DESC LIMIT 25""").df()
print("top uncovered test tokens:", dict(zip(unc.itok, unc.n)))
print("share of test vendor names (Indic) fully covered:", con.execute(f"""WITH tn AS (SELECT entity_id, unnest(string_split(trim(regexp_replace(business_name,'\\s+',' ','g')),' ')) tok FROM t23 WHERE regexp_matches(business_name,'{INDIC}')),
ind AS (SELECT entity_id, tok FROM tn WHERE regexp_matches(tok,'{INDIC}')),
unc AS (SELECT distinct entity_id FROM ind LEFT JOIN lex ON lex.itok=ind.tok WHERE lex.itok IS NULL)
SELECT round(1 - (SELECT count(*) FROM unc)*1.0/(SELECT count(distinct entity_id) FROM ind),4)""").fetchone()[0])
P("name coverage done")
# ---- ADDRESS lexicon: Indic tokens in vendor addresses -> most co-occurring S1 address token (state/city names)
# Wrapped in try/except: this step does a genuine (and legitimate) per-pair cross product between
# Indic address tokens and Latin address tokens via LATERAL unnest, so it is inherently heavier than
# the name lexicon. If it still fails on this box, fall back to an empty address lexicon rather than
# lose the (more important) name lexicon results already written above.
try:
con.execute(f"""CREATE OR REPLACE TABLE aal AS
SELECT itok, ltok FROM (
SELECT unnest(string_split(trim(regexp_replace(regexp_replace(y.business_address,'[,]',' ','g'),'\\s+',' ','g')),' ')) itok,
string_split(trim(regexp_replace(regexp_replace(lower(strip_accents(x.business_address)),'[^a-z0-9]+',' ','g'),'\\s+',' ','g')),' ') ltoks
FROM (SELECT * FROM pairs WHERE random()<0.10) p JOIN s1 x ON x.entity_id=p.a JOIN s23 y ON y.entity_id=p.b WHERE regexp_matches(y.business_address,'{INDIC}')
), LATERAL (SELECT unnest(ltoks) ltok) WHERE regexp_matches(itok,'{INDIC}')""")
# score by lift: P(ltok | itok) / P(ltok overall in S1 addresses)
con.execute("CREATE OR REPLACE TABLE s1tokfreq AS SELECT tok, count(*) f FROM (SELECT unnest(string_split(trim(regexp_replace(regexp_replace(lower(strip_accents(business_address)),'[^a-z0-9]+',' ','g'),'\\s+',' ','g')),' ')) tok FROM s1) GROUP BY 1")
alex=con.execute("""SELECT itok, ltok, n, cond, lift FROM (
SELECT itok, ltok, n, n*1.0/sum(n) OVER (PARTITION BY itok) cond, (n*1.0/sum(n) OVER (PARTITION BY itok)) / (f*1.0/(SELECT sum(f) FROM s1tokfreq)) lift, sum(n) OVER (PARTITION BY itok) tot
FROM (SELECT itok, ltok, count(*) n FROM aal GROUP BY 1,2) c JOIN s1tokfreq s ON s.tok=c.ltok)
QUALIFY row_number() OVER (PARTITION BY itok ORDER BY cond*lift DESC)=1 ORDER BY tot DESC""").df()
P("address lexicon entries", len(alex)); print(alex.head(30).to_string(index=False))
json.dump({r.itok: {"latin": r.ltok, "cond": round(float(r.cond),3), "n": int(r.n)} for r in alex.itertuples()}, open(f'{OUT}/translit_addr_lexicon.json','w'), ensure_ascii=False, indent=0)
acov=con.execute(f"""WITH tt AS (SELECT unnest(string_split(trim(regexp_replace(regexp_replace(business_address,'[,]',' ','g'),'\\s+',' ','g')),' ')) itok FROM t23 WHERE regexp_matches(business_address,'{INDIC}'))
SELECT count(*) occ, sum(CASE WHEN l.itok IS NOT NULL THEN 1 ELSE 0 END) covered, count(distinct tt.itok) n_types FROM tt LEFT JOIN (SELECT distinct itok FROM aal) l ON l.itok=tt.itok WHERE regexp_matches(tt.itok,'{INDIC}')""").df()
P("TEST address Indic-token coverage:", acov.to_dict('records'))
except Exception as e:
import traceback; traceback.print_exc()
P("ADDRESS lexicon step FAILED, writing empty fallback:", repr(e))
json.dump({}, open(f'{OUT}/translit_addr_lexicon.json','w'))
P("DONE; files:", os.listdir(OUT))