"""Leakage-safe splits. Unit of assignment = near-duplicate cluster of documents; groups = author group and venue so that no author/venue group straddles train and test when ``author_safe``/``venue_safe`` are set. Held-out discipline(s) and the earliest period can be carved out entirely. Deterministic given seed.""" from __future__ import annotations import hashlib import random from collections import defaultdict from dataclasses import dataclass, field from htr.data.schema import SplitAssignment @dataclass class SplitConfig: seed: int = 20261109 train: float = 0.8 val: float = 0.1 test: float = 0.1 heldout_disciplines: list[str] = field(default_factory=list) heldout_before_year: int | None = None # documents with pub_year < this go to heldout_period author_safe: bool = True venue_safe: bool = False def _stable_rand(key: str, seed: int) -> float: h = hashlib.sha256(f"{seed}:{key}".encode()).hexdigest() return int(h[:12], 16) / 16**12 def assign_splits(docs: list[dict], clusters: dict[str, str], cfg: SplitConfig, fixed: dict[str, str] | None = None) -> list[SplitAssignment]: """``docs``: dicts with doc_id, author_group, venue, subject_area, pub_year. ``clusters``: doc_id → cluster id. Union-find over cluster + author group (+ venue) builds leakage groups; groups are then hashed into splits. ``fixed`` = previously published assignments (doc_id → split) that must not change (passages already rewritten); any group containing a fixed document inherits that split (conflicts → 'quarantine').""" parent: dict[str, str] = {} def find(x: str) -> str: while parent.setdefault(x, x) != x: parent[x] = parent[parent[x]] x = parent[x] return x def union(a: str, b: str) -> None: ra, rb = find(a), find(b) if ra != rb: parent[rb] = ra for d in docs: did = d["doc_id"] union(f"doc:{did}", f"clu:{clusters.get(did, did)}") if cfg.author_safe and d.get("author_group"): union(f"doc:{did}", f"auth:{d['author_group']}") if cfg.venue_safe and d.get("venue"): union(f"doc:{did}", f"venue:{d['venue']}") fixed = fixed or {} group_fixed: dict[str, set[str]] = defaultdict(set) for did, sp in fixed.items(): group_fixed[find(f"doc:{did}")].add(sp) out: list[SplitAssignment] = [] for d in docs: did = d["doc_id"] g = find(f"doc:{did}") if g in group_fixed: fs = group_fixed[g] sp = next(iter(fs)) if len(fs) == 1 else "quarantine" out.append(SplitAssignment(doc_id=did, split=sp, group_keys={"group": g, "cluster": clusters.get(did, did), "author_group": d.get("author_group") or "", "venue": d.get("venue") or "", "fixed": "1"})) continue keys = {"group": g, "cluster": clusters.get(did, did), "author_group": d.get("author_group") or "", "venue": d.get("venue") or ""} if d.get("subject_area") in cfg.heldout_disciplines: out.append(SplitAssignment(doc_id=did, split="heldout_domain", group_keys=keys)) continue if cfg.heldout_before_year and d.get("pub_year") and d["pub_year"] < cfg.heldout_before_year: out.append(SplitAssignment(doc_id=did, split="heldout_period", group_keys=keys)) continue r = _stable_rand(g, cfg.seed) split = "train" if r < cfg.train else ("val" if r < cfg.train + cfg.val else "test") out.append(SplitAssignment(doc_id=did, split=split, group_keys=keys)) return out def split_summary(assignments: list[SplitAssignment]) -> dict[str, int]: c: dict[str, int] = defaultdict(int) for a in assignments: c[a.split] += 1 return dict(sorted(c.items())) def check_no_group_leak(assignments: list[SplitAssignment]) -> list[str]: seen: dict[str, set[str]] = defaultdict(set) for a in assignments: seen[a.group_keys["group"]].add(a.split) return [g for g, s in seen.items() if len(s - {"heldout_domain", "heldout_period"}) > 1] def shuffled(items: list, seed: int) -> list: r = random.Random(seed) items = list(items) r.shuffle(items) return items