File size: 3,697 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
"""Freeze the overlap dev/test splits (DECISIONS.md D04, D17).

Eligibility: only overlap pairs whose DCS and Itihasa raw text are IDENTICAL
once whitespace is ignored. The guide requires dropping verses whose raw text
differs between the two sources; we can afford that because ~15k such pairs
exist and we need ~2.5k.

Sampling is by CHAPTER, never by individual verse, so that near-duplicate
verses inside a chapter cannot straddle dev/test and the training pool.

Outputs (never regenerated once written):
  data/splits/overlap_dev.ids
  data/splits/overlap_test.ids

Usage:
  python -I src/data/make_splits.py --config configs/splits.yaml --seed 13
"""
from __future__ import annotations

import argparse
import collections
import json
import os
import random
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

import yaml  # noqa: E402

from data.normalize import normalize_iast  # noqa: E402


def _nospace(s: str) -> str:
    return normalize_iast(s).replace(" ", "")


def main() -> None:
    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"))

    dev_target = int(cfg["dev_size"])
    test_target = int(cfg["test_size"])
    out_dir = cfg["paths"]["splits_dir"]

    for name in ("overlap_dev.ids", "overlap_test.ids"):
        p = os.path.join(out_dir, name)
        if os.path.exists(p):
            raise SystemExit(
                f"REFUSING to overwrite frozen split {p}. "
                "Test ids are frozen before training and never regenerated."
            )

    rows = [json.loads(l) for l in
            open(cfg["paths"]["overlap"], encoding="utf-8")]
    strict = [r for r in rows
              if r["match_stage"] == "exact"
              and _nospace(r["sanskrit_raw"]) == _nospace(r["itihasa_raw"])]
    print(f"eligible (strict identical) : {len(strict)} / {len(rows)}")

    by_chapter: dict[str, list[dict]] = collections.defaultdict(list)
    for r in strict:
        by_chapter[r["chapter"]].append(r)
    chapters = sorted(by_chapter)
    print(f"eligible chapters           : {len(chapters)}")

    rng = random.Random(a.seed)
    rng.shuffle(chapters)

    def take(target: int, pool: list[str]) -> tuple[list[str], list[str]]:
        picked, n = [], 0
        rest = []
        for ch in pool:
            if n < target:
                picked.append(ch)
                n += len(by_chapter[ch])
            else:
                rest.append(ch)
        return picked, rest

    test_ch, remaining = take(test_target, chapters)
    dev_ch, _ = take(dev_target, remaining)

    assert not (set(test_ch) & set(dev_ch)), "dev/test chapter overlap"

    os.makedirs(out_dir, exist_ok=True)
    for name, chs in (("overlap_dev", dev_ch), ("overlap_test", test_ch)):
        ids = sorted(r["id"] for ch in chs for r in by_chapter[ch])
        with open(os.path.join(out_dir, f"{name}.ids"), "w",
                  encoding="utf-8") as fh:
            fh.write("\n".join(ids) + "\n")
        print(f"{name:13s} chapters={len(chs):4d} verses={len(ids):5d}")

    with open(os.path.join(out_dir, "PROVENANCE.md"), "w",
              encoding="utf-8") as fh:
        fh.write(
            f"Frozen {__import__('datetime').date.today()} by make_splits.py\n"
            f"seed={a.seed} config={a.config}\n"
            f"eligible strict pairs={len(strict)} chapters={len(chapters)}\n"
            f"dev chapters={len(dev_ch)} test chapters={len(test_ch)}\n"
            "Sampled by chapter. NEVER regenerate these files.\n"
        )


if __name__ == "__main__":
    main()