Download src/data/build_pools.py from AjayRangoji/Translation_Guided_Sandhi_Splitting_Experiment_Guide: direct link, hf CLI and curl.
- Browser
- Download file 4.06 kB
-
https://huggingface.co/datasets/AjayRangoji/Translation_Guided_Sandhi_Splitting_Experiment_Guide/resolve/main/src/data/build_pools.py
- Command line
-
hf download hf://datasets/AjayRangoji/Translation_Guided_Sandhi_Splitting_Experiment_Guide/src/data/build_pools.py
-
curl -L -o build_pools.py https://huggingface.co/datasets/AjayRangoji/Translation_Guided_Sandhi_Splitting_Experiment_Guide/resolve/main/src/data/build_pools.py
4.06 kB
| """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() | |