"""Candidate head-only render policy; audio bytes, types and events stay intact.""" import math import os import threading import numpy as np class HeadGate: def __init__(self, threshold=None): self.threshold = float(os.environ.get('HEL720_HEAD_RMS', '0.001') if threshold is None else threshold) if not math.isfinite(self.threshold) or self.threshold < 0: raise ValueError('HEL720_HEAD_RMS must be finite and >= 0 (0 disables)') self._lock = threading.Lock() self.leading = True def reset(self): with self._lock: self.leading = True def classify(self, frame): # Called on original 16k PCM at ASR ingress, BEFORE feature batching. # Synthetic idle never rearms a running utterance (stream starvation). with self._lock: if frame.type != 0: return False status = (frame.userdata or {}).get('status') if status == 'start': self.leading = True rms = float(np.sqrt(np.mean(np.square(frame.data, dtype=np.float64)))) closed = self.threshold > 0 and self.leading and rms <= self.threshold if not closed: self.leading = False if status == 'end': self.leading = True return closed def render_speech(frames): return any(f.type == 0 and not getattr(f, 'hel720_head_closed', False) for f in frames)