"""Deterministic speaker-disjoint, label-aware train/validation/test splitting.""" from __future__ import annotations import math import random from collections import Counter, defaultdict from pathlib import Path from typing import Any from buddi_asr.data.manifest import ( ManifestRecord, read_manifest, rebase_audio_path, write_manifest, ) from buddi_asr.errors import ManifestError SPLIT_ORDER = ("train", "validation", "test") def _validate_ratios(ratios: dict[str, float]) -> dict[str, float]: if set(ratios) != set(SPLIT_ORDER): raise ManifestError("ratios must contain exactly train, validation, and test") if any(not isinstance(value, (int, float)) or value <= 0 for value in ratios.values()): raise ManifestError("all split ratios must be positive numbers") total = float(sum(ratios.values())) if not math.isclose(total, 1.0, rel_tol=0, abs_tol=1e-8): raise ManifestError(f"split ratios must sum to 1.0, got {total}") return {name: float(ratios[name]) for name in SPLIT_ORDER} def _label_key(record: ManifestRecord) -> str: return "\u241f".join((record.source, record.language, record.category, record.text)) def _objective( totals: dict[str, int], labels: dict[str, Counter[str]], target_totals: dict[str, float], target_labels: dict[str, dict[str, float]], all_labels: tuple[str, ...], *, label_weight: float, ) -> float: total_cost = sum( ((totals[name] - target_totals[name]) ** 2) / max(target_totals[name], 1.0) for name in SPLIT_ORDER ) label_cost = 0.0 for name in SPLIT_ORDER: for label in all_labels: target = target_labels[name][label] label_cost += ((labels[name][label] - target) ** 2) / max(target, 1.0) return total_cost + label_weight * label_cost def assign_speaker_disjoint_splits( records: list[ManifestRecord], *, ratios: dict[str, float], seed: int, label_weight: float = 0.25, ) -> dict[str, list[ManifestRecord]]: ratios = _validate_ratios(ratios) if len({record.speaker_id for record in records}) < len(SPLIT_ORDER): raise ManifestError("At least three distinct speakers are required for three-way splitting") groups: dict[str, list[ManifestRecord]] = defaultdict(list) for record in records: groups[record.speaker_id].append(record) global_labels = Counter(_label_key(record) for record in records) all_labels = tuple(sorted(global_labels)) target_totals = {name: len(records) * ratios[name] for name in SPLIT_ORDER} target_labels = { name: {label: global_labels[label] * ratios[name] for label in all_labels} for name in SPLIT_ORDER } rng = random.Random(seed) tie_breakers = {speaker: rng.random() for speaker in groups} ordered_groups = sorted( groups.items(), key=lambda item: ( -len(item[1]), -len({_label_key(record) for record in item[1]}), tie_breakers[item[0]], item[0], ), ) assignments: dict[str, list[ManifestRecord]] = {name: [] for name in SPLIT_ORDER} totals = {name: 0 for name in SPLIT_ORDER} label_totals = {name: Counter() for name in SPLIT_ORDER} for group_index, (_, group_records) in enumerate(ordered_groups): group_labels = Counter(_label_key(record) for record in group_records) # Seed every split with one speaker. Choosing the largest remaining target # first avoids an empty evaluation split for small datasets. if group_index < len(SPLIT_ORDER): candidate_names = [ name for name in SPLIT_ORDER if not assignments[name] ] else: candidate_names = list(SPLIT_ORDER) scored: list[tuple[float, float, str]] = [] for name in candidate_names: candidate_totals = dict(totals) candidate_labels = {key: Counter(value) for key, value in label_totals.items()} candidate_totals[name] += len(group_records) candidate_labels[name].update(group_labels) score = _objective( candidate_totals, candidate_labels, target_totals, target_labels, all_labels, label_weight=label_weight, ) deficit = target_totals[name] - totals[name] scored.append((score, -deficit, name)) _, _, chosen = min(scored) assignments[chosen].extend(group_records) totals[chosen] += len(group_records) label_totals[chosen].update(group_labels) for offset, name in enumerate(SPLIT_ORDER): split_rng = random.Random(seed + offset + 1) split_rng.shuffle(assignments[name]) return assignments def split_manifest( input_manifest: str | Path, output_dir: str | Path, *, ratios: dict[str, float] | None = None, seed: int = 42, label_weight: float = 0.25, ) -> dict[str, Any]: input_path = Path(input_manifest).resolve() destination = Path(output_dir).resolve() destination.mkdir(parents=True, exist_ok=True) ratios = ratios or {"train": 0.8, "validation": 0.1, "test": 0.1} records = list(read_manifest(input_path)) assignments = assign_speaker_disjoint_splits( records, ratios=ratios, seed=seed, label_weight=label_weight ) paths: dict[str, str] = {} counts: dict[str, int] = {} speakers_by_split: dict[str, set[str]] = {} for name in SPLIT_ORDER: output_path = destination / f"{name}.jsonl" rebased: list[ManifestRecord] = [] for record in assignments[name]: updated = rebase_audio_path(record, input_path, output_path) updated.split = name rebased.append(updated) write_manifest(rebased, output_path) paths[name] = str(output_path) counts[name] = len(rebased) speakers_by_split[name] = {record.speaker_id for record in rebased} for left_index, left in enumerate(SPLIT_ORDER): for right in SPLIT_ORDER[left_index + 1 :]: overlap = speakers_by_split[left] & speakers_by_split[right] if overlap: raise AssertionError(f"Internal split error: {left}/{right} speaker overlap") return { "input": str(input_path), "seed": seed, "ratios_requested": _validate_ratios(ratios), "records": len(records), "counts": counts, "actual_ratios": { name: counts[name] / len(records) if records else 0.0 for name in SPLIT_ORDER }, "speakers": {name: len(speakers_by_split[name]) for name in SPLIT_ORDER}, "paths": paths, "speaker_overlap": 0, }