"""Fixed-window dataset and the kind-balanced sampler.""" from __future__ import annotations from collections import Counter import numpy as np import torch from torch.utils.data import Dataset, WeightedRandomSampler from vitakws.data import audio from vitakws.data.augment import Augmenter, fit_length, speed_perturb from vitakws.data.manifest import KEYWORD_KIND, Item, LabelMap # Seconds of audio kept after the keyword ends. Training randomises it so the # model fires anywhere in this range; evaluation uses the middle. TRAIL_RANGE = (0.05, 0.40) TRAIL_EVAL = 0.20 def place_keyword( wave: np.ndarray, kw_end: int, window: int, trail: int, ) -> np.ndarray: """Cut a window that ends ``trail`` samples after the keyword, zero-padding outside the clip. Aligning on the keyword end mirrors streaming use: the detector sees the keyword slide in from the right and must fire shortly after it finishes. Whatever follows in the clip (a command spoken right after) stays in the window. """ end = kw_end + trail start = end - window out = np.zeros(window, dtype=np.float32) src_lo, src_hi = max(start, 0), min(end, len(wave)) if src_hi > src_lo: out[src_lo - start : src_hi - start] = wave[src_lo:src_hi] return out class KwsDataset(Dataset): """Returns (waveform [window], class index, item index).""" def __init__( self, items: list[Item], label_map: LabelMap, sample_rate: int, window_seconds: float, augmenter: Augmenter | None = None, train: bool = False, seed: int = 0, align_short_negatives: float = 0.0, context_files: list[str] | None = None, context_prob: float = 0.0, context_gap_s: tuple[float, float] = (0.0, 0.3), context_gain_db: tuple[float, float] = (-10.0, 3.0), trail_range: tuple[float, float] = TRAIL_RANGE, ): self.items = items self.label_map = label_map self.sample_rate = sample_rate self.window = int(round(window_seconds * sample_rate)) self.augmenter = augmenter self.train = train self.seed = seed self.align_short_negatives = align_short_negatives self.context_files = context_files or [] self.context_prob = context_prob self.context_gap_s = context_gap_s self.context_gain_db = context_gain_db # A negative lower bound also trains on keywords cut before their end (fire earlier). self.trail_range = tuple(trail_range) self.targets = [label_map.index(i.label) for i in items] self._rng: np.random.Generator | None = None def __len__(self) -> int: return len(self.items) def _rng_for(self, index: int) -> np.random.Generator: if not self.train: return np.random.default_rng([self.seed, index]) if self._rng is None: info = torch.utils.data.get_worker_info() # torch reseeds every worker each epoch, so this differs per worker and epoch. base = info.seed if info is not None else int(torch.randint(0, 2**31, (1,))) self._rng = np.random.default_rng([self.seed, base]) return self._rng def _load_keyword(self, item: Item, rng: np.random.Generator) -> np.ndarray: sr = self.sample_rate wave = audio.load(item.audio, sr) kw_end = len(wave) if item.kw_end is None else int(round(item.kw_end * sr)) if self.train and self.augmenter is not None: factor = self.augmenter.random_speed(rng) if factor != 1.0: wave = speed_perturb(wave, factor, sr) kw_end = int(round(kw_end / factor)) trail = rng.uniform(*self.trail_range) if self.train else TRAIL_EVAL kw_end = min(kw_end, len(wave)) out = place_keyword(wave, kw_end, self.window, int(round(trail * sr))) if self.train and self.context_files and rng.random() < self.context_prob: self._add_context(out, wave, kw_end, int(round(trail * sr)), rng) return out def _add_context(self, out: np.ndarray, wave: np.ndarray, kw_end: int, trail: int, rng: np.random.Generator) -> None: """Put other speech in the zero padding before the clip starts, in place.""" sr = self.sample_rate lead = self.window - (kw_end + trail) - int(round(rng.uniform(*self.context_gap_s) * sr)) if lead < int(0.15 * sr): return path = self.context_files[int(rng.integers(len(self.context_files)))] file_sr, frames = audio.info(path) total = frames / file_sr start = float(rng.uniform(0.0, max(total - lead / sr, 0.0))) ctx = audio.load(path, sr, start=start, duration=min(lead / sr, total))[:lead] ref = np.sqrt(np.mean(wave**2) + 1e-10) rms = np.sqrt(np.mean(ctx**2) + 1e-10) if rms < 1e-4: return ctx = ctx * (ref / rms) * 10 ** (rng.uniform(*self.context_gain_db) / 20) out[lead - len(ctx) : lead] += ctx.astype(np.float32) def _load_negative(self, item: Item, rng: np.random.Generator) -> np.ndarray: sr = self.sample_rate file_sr, frames = audio.info(item.audio) total = frames / file_sr factor = self.augmenter.random_speed(rng) if self.train and self.augmenter else 1.0 need = self.window / sr * factor if total > need: start = float(rng.uniform(0.0, total - need)) if self.train else (total - need) / 2.0 wave = audio.load(item.audio, sr, start=start, duration=need) else: wave = audio.load(item.audio, sr) wave = speed_perturb(wave, factor, sr) # A near-miss phrase sliding through the detector passes the exact position # keyword clips are trained at (ending just before the window's right edge). # Placing short negatives there too stops position from telling the classes apart. if len(wave) < self.window and self.align_short_negatives > 0: if not self.train: return place_keyword(wave, len(wave), self.window, int(round(TRAIL_EVAL * sr))) if rng.random() < self.align_short_negatives: trail = int(round(rng.uniform(*self.trail_range) * sr)) return place_keyword(wave, len(wave), self.window, trail) return fit_length(wave, self.window, rng if self.train else None) def __getitem__(self, index: int): item = self.items[index] rng = self._rng_for(index) if item.kind == KEYWORD_KIND: wave = self._load_keyword(item, rng) else: wave = self._load_negative(item, rng) if self.augmenter is not None: wave = self.augmenter(wave, rng, is_background=item.kind == "background") return torch.from_numpy(wave), self.targets[index], index def balanced_sampler( items: list[Item], kind_ratios: dict[str, float], num_samples: int, window_seconds: float, max_windows: float = 50.0, generator: torch.Generator | None = None, ) -> WeightedRandomSampler: """Draw kinds at fixed ratios regardless of how many files each kind has. Inside a kind, a file is weighted by how many windows it holds (capped), so an hour-long negative recording is not sampled as rarely as a one-second clip. An optional per-item ``sample_weight`` manifest field scales that weight. """ present = Counter(i.kind for i in items) ratios = {k: v for k, v in kind_ratios.items() if v > 0 and present.get(k, 0) > 0} if not ratios: raise ValueError( f"kind_ratios {kind_ratios} selects nothing; kinds in the data: {dict(present)}" ) total_ratio = sum(ratios.values()) raw = np.array( [ min(max(i.duration / window_seconds, 1.0), max_windows) * float(i.extra.get("sample_weight", 1.0)) if i.kind in ratios else 0.0 for i in items ] ) weights = np.zeros(len(items)) for kind, ratio in ratios.items(): mask = np.array([i.kind == kind for i in items]) weights[mask] = raw[mask] / raw[mask].sum() * ratio / total_ratio return WeightedRandomSampler( torch.from_numpy(weights), num_samples=num_samples, replacement=True, generator=generator )