"""Streaming detection: slide a fixed window over audio and smooth the scores. ``StreamingDetector`` is the online form (feed blocks, get events); the device runs the same logic. ``score_stream`` is the batched offline form used for evaluation and hard-negative mining; both give the same scores. """ from __future__ import annotations from collections import deque from collections.abc import Callable from dataclasses import dataclass import numpy as np import torch from vitakws.features import FeatureConfig, LogMel, logmel_numpy # windows [N, samples] float32 -> class probabilities [N, classes] InferFn = Callable[[np.ndarray], np.ndarray] @dataclass class StreamConfig: sample_rate: int = 16000 window_seconds: float = 1.5 hop_seconds: float = 0.1 smooth_windows: int = 3 # moving average over this many hops threshold: float = 0.5 refractory_seconds: float = 2.0 @property def window(self) -> int: return int(round(self.window_seconds * self.sample_rate)) @property def hop(self) -> int: return int(round(self.hop_seconds * self.sample_rate)) @property def refractory_hops(self) -> int: return max(1, int(round(self.refractory_seconds / self.hop_seconds))) @dataclass class Detection: time: float # seconds from stream start, at the end of the firing window keyword: int # class index score: float def torch_infer_fn(model: torch.nn.Module, frontend: LogMel, device: str = "cpu") -> InferFn: model = model.to(device).eval() frontend = frontend.to(device).eval() @torch.no_grad() def infer(windows: np.ndarray) -> np.ndarray: x = torch.from_numpy(np.ascontiguousarray(windows)).to(device) return torch.softmax(model(frontend(x)), dim=1).cpu().numpy() return infer def onnx_infer_fn(onnx_path: str, feat_cfg: FeatureConfig) -> InferFn: """Runs the exported model with the numpy front end, as the device would.""" import onnxruntime as ort session = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"]) name = session.get_inputs()[0].name def infer(windows: np.ndarray) -> np.ndarray: feats = np.stack([logmel_numpy(w, feat_cfg) for w in windows])[:, None] logits = session.run(None, {name: feats.astype(np.float32)})[0] logits = logits - logits.max(axis=1, keepdims=True) exp = np.exp(logits) return exp / exp.sum(axis=1, keepdims=True) return infer def smooth(probs: np.ndarray, width: int) -> np.ndarray: """Causal moving average over the last ``width`` rows (fewer at the start).""" if width <= 1 or len(probs) == 0: return probs csum = np.cumsum(np.vstack([np.zeros((1, probs.shape[1])), probs]), axis=0) idx = np.arange(1, len(probs) + 1) lo = np.maximum(idx - width, 0) return (csum[idx] - csum[lo]) / (idx - lo)[:, None] def score_stream( wave: np.ndarray, infer: InferFn, cfg: StreamConfig, batch_size: int = 256 ) -> np.ndarray: """Smoothed class probabilities for every hop, shape [num_windows, classes]. Row ``i`` is the window ending at sample ``window + i * hop``. Audio shorter than one window is left-padded with zeros. """ wave = np.asarray(wave, dtype=np.float32) if len(wave) < cfg.window: wave = np.concatenate([np.zeros(cfg.window - len(wave), dtype=np.float32), wave]) starts = np.arange(0, len(wave) - cfg.window + 1, cfg.hop) out = [] for i in range(0, len(starts), batch_size): batch = np.stack([wave[s : s + cfg.window] for s in starts[i : i + batch_size]]) out.append(infer(batch)) return smooth(np.concatenate(out), cfg.smooth_windows) def window_end_times(num_windows: int, cfg: StreamConfig) -> np.ndarray: return (cfg.window + np.arange(num_windows) * cfg.hop) / cfg.sample_rate def detect(probs: np.ndarray, keyword_ids: list[int], cfg: StreamConfig) -> list[Detection]: """Turn smoothed probabilities into detections with a refractory period.""" scores = probs[:, keyword_ids] best = scores.max(axis=1) times = window_end_times(len(probs), cfg) events, i = [], 0 while i < len(best): if best[i] >= cfg.threshold: keyword = keyword_ids[int(scores[i].argmax())] events.append(Detection(float(times[i]), keyword, float(best[i]))) i += cfg.refractory_hops else: i += 1 return events class StreamingDetector: """Online detector. Feed audio blocks of any size; get back the detections they complete.""" def __init__(self, infer: InferFn, keyword_ids: list[int], cfg: StreamConfig): self.infer = infer self.keyword_ids = keyword_ids self.cfg = cfg self.reset() def reset(self) -> None: self._buffer = np.zeros(0, dtype=np.float32) self._consumed = 0 # samples dropped from the front of the buffer self._history: deque[np.ndarray] = deque(maxlen=max(1, self.cfg.smooth_windows)) self._cooldown = 0 def accept(self, block: np.ndarray) -> list[Detection]: cfg = self.cfg self._buffer = np.concatenate([self._buffer, np.asarray(block, dtype=np.float32)]) events = [] while len(self._buffer) >= cfg.window: probs = self.infer(self._buffer[None, : cfg.window])[0] self._history.append(probs) end_time = (self._consumed + cfg.window) / cfg.sample_rate self._buffer = self._buffer[cfg.hop :] self._consumed += cfg.hop if self._cooldown > 0: self._cooldown -= 1 continue mean = np.mean(self._history, axis=0)[self.keyword_ids] if mean.max() >= cfg.threshold: events.append( Detection(end_time, self.keyword_ids[int(mean.argmax())], float(mean.max())) ) self._cooldown = cfg.refractory_hops - 1 return events