"""Build the DCS n Itihasa overlap set (DECISIONS.md D04, D16). Stage 1: exact match on the collapsed key (IAST, spaces removed, nasals folded). Stage 2: fuzzy match for the remainder, blocked by prefix/suffix buckets so we never do the full 92k x 93k product. A pair is kept only if normalised similarity >= threshold (default 0.95) and the match is one-to-one; ambiguous DCS verses matching several Itihasa verses, and vice versa, are dropped rather than guessed. Usage: python -I src/data/overlap.py --config configs/overlap.yaml --seed 13 """ from __future__ import annotations import argparse import collections import json import os import sys sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) import yaml # noqa: E402 from rapidfuzz.distance import Levenshtein # noqa: E402 from data.normalize import collapse_for_match # noqa: E402 def read_jsonl(path): with open(path, encoding="utf-8") as fh: for line in fh: yield json.loads(line) def write_jsonl(path, records): os.makedirs(os.path.dirname(path), exist_ok=True) tmp = path + ".tmp" n = 0 with open(tmp, "w", encoding="utf-8") as fh: for r in records: fh.write(json.dumps(r, ensure_ascii=False) + "\n") n += 1 os.replace(tmp, path) return n def build(cfg): thr = float(cfg["threshold"]) pre = int(cfg.get("bucket_prefix", 10)) dcs = {r["id"]: r for r in read_jsonl(cfg["paths"]["dcs_epics"])} iti = {r["id"]: r for r in read_jsonl(cfg["paths"]["itihasa"])} print(f"dcs epic verses : {len(dcs)}") print(f"itihasa verses : {len(iti)}") dkey = {i: collapse_for_match(r["sanskrit_raw"]) for i, r in dcs.items()} ikey = {i: collapse_for_match(r["sanskrit_raw"]) for i, r in iti.items()} # ---- stage 1: exact collapsed-key match ------------------------------- by_exact = collections.defaultdict(list) for i, k in dkey.items(): by_exact[k].append(i) pairs = {} # iti_id -> (dcs_id, sim, stage) used_dcs = {} # dcs_id -> iti_id ambiguous = 0 for ii, k in ikey.items(): cands = by_exact.get(k) if not cands: continue if len(cands) > 1: ambiguous += 1 continue pairs[ii] = (cands[0], 1.0, "exact") # resolve many-itihasa-to-one-dcs rev = collections.defaultdict(list) for ii, (di, _, _) in pairs.items(): rev[di].append(ii) for di, iis in rev.items(): if len(iis) > 1: ambiguous += len(iis) for ii in iis: pairs.pop(ii, None) else: used_dcs[di] = iis[0] print(f"stage 1 exact : {len(pairs)} pairs ({ambiguous} dropped ambiguous)") # ---- stage 2: fuzzy on the remainder ---------------------------------- rem_i = [i for i in ikey if i not in pairs] free_d = [i for i in dkey if i not in used_dcs] buckets = collections.defaultdict(list) for di in free_d: k = dkey[di] buckets[k[:pre]].append(di) buckets["~" + k[-pre:]].append(di) fuzzy = {} for ii in rem_i: k = ikey[ii] if not k: continue cands = set(buckets.get(k[:pre], ())) | set(buckets.get("~" + k[-pre:], ())) best, best_sim = None, 0.0 for di in cands: kd = dkey[di] if abs(len(kd) - len(k)) > 0.25 * max(len(k), len(kd)): continue s = Levenshtein.normalized_similarity(k, kd, score_cutoff=thr) if s > best_sim: best, best_sim = di, s if best is not None and best_sim >= thr: fuzzy.setdefault(best, []).append((ii, best_sim)) added = 0 for di, lst in fuzzy.items(): if len(lst) > 1: # one DCS verse claimed by several: ambiguous ambiguous += len(lst) continue ii, s = lst[0] pairs[ii] = (di, s, "fuzzy") used_dcs[di] = ii added += 1 print(f"stage 2 fuzzy : {added} pairs (threshold {thr})") out = [] for ii, (di, sim, stage) in pairs.items(): d, t = dcs[di], iti[ii] out.append({ "id": f"ov:{di}", "dcs_id": di, "itihasa_id": ii, "sanskrit_raw": d["sanskrit_raw"], "sanskrit_gold": d["sanskrit_gold"], "itihasa_raw": t["sanskrit_raw"], "english": t["english"], "source": d["source"], "chapter": d.get("chapter", ""), "n_words": d.get("n_words", 0), "n_cpd": d.get("n_cpd", 0), "match_sim": round(sim, 4), "match_stage": stage, }) out.sort(key=lambda r: r["id"]) n = write_jsonl(cfg["paths"]["out_overlap"], out) print(f"TOTAL overlap : {n} verses " f"({100.0*n/len(iti):.1f}% of Itihasa, {100.0*n/len(dcs):.1f}% of DCS epics)") print(f"ambiguous dropped: {ambiguous}") return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--config", required=True) ap.add_argument("--seed", type=int, required=True) a = ap.parse_args() build(yaml.safe_load(open(a.config, encoding="utf-8"))) if __name__ == "__main__": main()