File size: 4,058 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
"""Build leakage-free training and pseudo-label pools (DECISIONS.md D05).

Removes from both pools every dev/test verse AND every near-duplicate of one
(collapsed-key similarity >= 0.95), because epic verses repeat.

Outputs:
  data/processed/dcs_train_pool.jsonl   gold-split training pool (all DCS texts)
  data/processed/itihasa_pool.jsonl     bitext pseudo-label pool

Usage:
  python -I src/data/build_pools.py --config configs/pools.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(p):
    with open(p, 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


class Blocker:
    """Prefix/suffix buckets over held-out keys, for near-duplicate lookup."""

    def __init__(self, keys, pre=10):
        self.pre = pre
        self.keys = keys
        self.buckets = collections.defaultdict(list)
        for k in keys:
            if len(k) >= pre:
                self.buckets[k[:pre]].append(k)
                self.buckets["~" + k[-pre:]].append(k)

    def is_near_dup(self, k, thr):
        if not k:
            return False
        cands = set(self.buckets.get(k[: self.pre], ())) | \
                set(self.buckets.get("~" + k[-self.pre:], ()))
        for kh in cands:
            if abs(len(kh) - len(k)) > 0.25 * max(len(k), len(kh)):
                continue
            if Levenshtein.normalized_similarity(k, kh, score_cutoff=thr) >= thr:
                return True
        return False


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", required=True)
    ap.add_argument("--seed", type=int, required=True)
    a = ap.parse_args()
    cfg = yaml.safe_load(open(a.config, encoding="utf-8"))
    thr = float(cfg["threshold"])
    sd = cfg["paths"]["splits_dir"]

    held_ids = set()
    for f in ("overlap_dev.ids", "overlap_test.ids"):
        with open(os.path.join(sd, f), encoding="utf-8") as fh:
            held_ids |= {l.strip() for l in fh if l.strip()}
    print(f"held-out overlap ids      : {len(held_ids)}")

    ov = {r["id"]: r for r in read_jsonl(cfg["paths"]["overlap"])}
    held = [ov[i] for i in held_ids if i in ov]
    assert len(held) == len(held_ids), "frozen id not found in overlap.jsonl"

    held_dcs_ids = {r["dcs_id"] for r in held}
    held_iti_ids = {r["itihasa_id"] for r in held}
    held_keys = {collapse_for_match(r["sanskrit_raw"]) for r in held}
    blocker = Blocker(held_keys)
    print(f"distinct held-out keys    : {len(held_keys)}")

    def filter_pool(src, id_field_exclude, label):
        kept, drop_id, drop_dup = [], 0, 0
        for r in read_jsonl(src):
            if r["id"] in id_field_exclude:
                drop_id += 1
                continue
            if blocker.is_near_dup(collapse_for_match(r["sanskrit_raw"]), thr):
                drop_dup += 1
                continue
            kept.append(r)
        print(f"{label:22s} kept={len(kept):7d} "
              f"dropped_exact_id={drop_id:5d} dropped_near_dup={drop_dup:5d}")
        return kept

    dcs_keep = filter_pool(cfg["paths"]["dcs_all"], held_dcs_ids, "dcs_train_pool")
    n = write_jsonl(cfg["paths"]["out_dcs_pool"], dcs_keep)
    print(f"wrote {n} -> {cfg['paths']['out_dcs_pool']}")

    iti_keep = filter_pool(cfg["paths"]["itihasa"], held_iti_ids, "itihasa_pool")
    n = write_jsonl(cfg["paths"]["out_iti_pool"], iti_keep)
    print(f"wrote {n} -> {cfg['paths']['out_iti_pool']}")


if __name__ == "__main__":
    main()