File size: 5,261 Bytes
bc3f388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()