Streaming turn detection for ONNX Runtime

Detect end of turn, interruption and voice activity from synchronized 16 kHz audio channels. This package runs the published v2 model on CPU with ONNX Runtime and no PyTorch dependency. It includes streaming state, peer-channel history, and a mode for one speaker plus a playback activity signal.

The FP32 graphs total 21.55 MB. We compared them with the upstream v2 PyTorch runtime on 46,752 output decisions from real dialogues and overlapping meeting speech. All tested threshold decisions agreed. The largest absolute probability difference was 0.0001171. This checks conversion parity on the tested recordings. Accuracy on new domains remains unmeasured.

On the tested Apple Silicon Mac, the fresh Python environment occupied 73% less disk space than the fresh upstream PyTorch environment. Both use Python 3.12 with the common dependencies pinned below.

Install and run on two speakers

Use Python 3.12. Install the runtime and download the model.

python -m pip install 'huggingface-hub==2.4.0' 'numpy==2.5.5' 'onnxruntime==1.32.0' 'scipy==1.18.1' 'soundfile==0.14.0'
hf download strangelab/streaming-turn-detection-onnx --local-dir turn-model

Save the following Python block as analyze.py. Run it with two synchronized mono WAV files at 16 kHz. For a real example, download the first two headset tracks from the AMI Meeting Corpus. Track 0 · Track 1 · AMI data and CC BY 4.0 terms

python analyze.py turn-model IS1001c.Headset-0.wav IS1001c.Headset-1.wav --start 365 --seconds 30

The example reports 1,496 frames per channel. Each 160 ms input step produces eight 20 ms scores per channel. For a live stream, call model.stream(channels=2) once and pass synchronized blocks to stream.push([channel_0, channel_1]). A final partial step stays buffered. See the original model card for the recommended rules that use these scores to decide when to respond.

"""CPU streaming reader for the exported model. No PyTorch dependency."""

import json
from pathlib import Path

import numpy as np
import onnxruntime as ort
from scipy.fft import rfft
from scipy.signal import resample_poly


class Model:
    def __init__(self, directory, threads=1):
        directory = Path(directory)
        self.config = json.loads((directory/"config.json").read_text())
        self.step = self.config["step_samples"]
        self.history = self.config["history_samples"]
        options = ort.SessionOptions()
        options.intra_op_num_threads = threads
        options.inter_op_num_threads = 1
        self.encode = ort.InferenceSession(str(directory/"encode.onnx"),options,providers=["CPUExecutionProvider"])
        self.decide = ort.InferenceSession(str(directory/"decide.onnx"),options,providers=["CPUExecutionProvider"])
        with np.load(directory/"frontend.npz",allow_pickle=False) as frontend:
            self.window = frontend["window"]
            self.filters = frontend["filterbank"]
        self.hop = 160
        self.nfft = len(self.window)
        self.frames = self.config["output_frames"]
        self.lags = np.asarray(self.config["rest_lags"],dtype=np.int64)
        self.hist_frames = self.frames + int(self.lags.max())
        self.indices = (self.hist_frames-self.frames + np.arange(self.frames))[:,None]-self.lags[None,:]
        self.state_names = [state.name for state in self.encode.get_inputs()[1:]]

    def stream(self, channels=1, lowpass=True, readout=None):
        if channels < 1:
            raise ValueError("At least one channel is required")
        if readout is None:
            readout = self.config["default_multichannel_readout"] if channels > 1 else self.config["default_mono_readout"]
        if readout not in (0,2,3):
            raise ValueError("Supported readouts are 0, 2 and 3")
        return Stream(self, channels, lowpass, readout)

    def mel(self, tail, samples, lowpass):
        window = np.concatenate([tail,samples])
        if lowpass:
            window = resample_poly(resample_poly(window,1,2),2,1)[:len(window)]
        recent = window[-(self.nfft-self.hop+self.step):]
        frames = np.lib.stride_tricks.sliding_window_view(recent,self.nfft)[::self.hop]
        spectrum = np.abs(rfft(frames*self.window,axis=-1))**2
        energy = np.maximum(spectrum@self.filters.T,1e-10)
        return np.ascontiguousarray(((np.log(energy)+10.)/5.).T[None],dtype=np.float32)


class Stream:
    def __init__(self, model, channels, lowpass, readout):
        self.model, self.channels, self.lowpass = model,channels,lowpass
        self.readout = np.asarray(readout,dtype=np.float32)
        self.reset()

    def reset(self):
        m = self.model
        initial = {key:np.zeros(m.config["state_shapes"][key],dtype=np.float32) for key in m.state_names}
        initial["key_positions"].fill(-1e9)
        self.states = [initial.copy() for _ in range(self.channels)]
        self.pending = [np.zeros(0,dtype=np.float32) for _ in range(self.channels)]
        self.tails = [np.zeros(m.history,dtype=np.float32) for _ in range(self.channels)]
        self.activity = np.zeros((self.channels,4,m.hist_frames),dtype=np.float32)
        self.playback = np.zeros(m.hist_frames,dtype=np.float32)

    def rest(self, channel, activity_offset, playback_supplied):
        m = self.model
        flag = np.ones((m.frames,1),dtype=np.float32)
        if self.channels > 1:
            other = np.delete(self.activity,channel,axis=0)
            peer_vad = other[:,activity_offset].max(axis=0)[m.indices]
            peer_claim = other[:,activity_offset+2].max(axis=0)[m.indices]
            return np.concatenate([peer_vad,peer_claim,flag],axis=1)
        if playback_supplied:
            peer_vad = self.playback[m.indices]
            return np.concatenate([peer_vad,np.zeros_like(peer_vad),flag],axis=1)
        return np.zeros((m.frames,2*len(m.lags)+1),dtype=np.float32)

    def push(self, chunks, rest_activity=None):
        m = self.model
        if len(chunks) != self.channels:
            raise ValueError("Supply one 16 kHz mono chunk per channel")
        if rest_activity is not None and self.channels != 1:
            raise ValueError("Playback activity is used only with one input channel")
        inputs = [np.asarray(chunk,dtype=np.float32) for chunk in chunks]
        if any(chunk.ndim != 1 for chunk in inputs):
            raise ValueError("Each channel must be a one-dimensional sample array")
        self.pending = [np.concatenate([buffer,chunk]) for buffer,chunk in zip(self.pending,inputs)]
        output = {key:[[] for _ in self.pending] for key in ("eot","int","vad")}
        steps = min(map(len,self.pending))//m.step
        for index in range(steps):
            hidden, current = [], []
            for channel in range(self.channels):
                seg,self.pending[channel] = self.pending[channel][:m.step],self.pending[channel][m.step:]
                tail = self.tails[channel]
                mel = m.mel(tail,seg,self.lowpass)
                self.tails[channel] = seg[-m.history:].copy()
                h,activity,*cache = m.encode.run(None,{"mel":mel,**self.states[channel]})
                self.states[channel] = dict(zip(m.state_names,cache))
                current.append(activity)
                hidden.append(h)
                self.activity[channel] = np.concatenate([self.activity[channel,:,m.frames:],activity],axis=1)
            if rest_activity is not None:
                start = index*m.frames
                vals = np.asarray(rest_activity[start:start+m.frames],dtype=np.float32)
                vals = np.pad(vals,(0,m.frames-len(vals)),constant_values=vals[-1] if len(vals) else 0)
                self.playback = np.concatenate([self.playback[m.frames:],vals])
            for channel in range(self.channels):
                end, interrupt = m.decide.run(None,{"hidden":hidden[channel],"readout":self.readout,
                    "rest_eot":self.rest(channel,0,rest_activity is not None),
                    "rest_int":self.rest(channel,1,rest_activity is not None)})
                output["eot"][channel].append(end)
                output["int"][channel].append(interrupt)
                output["vad"][channel].append(current[channel][0])
        return {name:[np.concatenate(group) if group else np.zeros(0,dtype=np.float32) for group in channels]
                for name,channels in output.items()}


if __name__ == "__main__":
    import argparse
    import soundfile as sf

    parser = argparse.ArgumentParser()
    parser.add_argument("model")
    parser.add_argument("channels", nargs="+")
    parser.add_argument("--start", type=float, default=0)
    parser.add_argument("--seconds", type=float, default=30)
    args = parser.parse_args()
    audio = []
    for source in args.channels:
        with sf.SoundFile(source) as handle:
            if handle.samplerate != 16000 or handle.channels != 1:
                raise ValueError("Inputs must be mono WAV files at 16 kHz")
            handle.seek(round(16000 * args.start))
            audio.append(handle.read(round(16000 * args.seconds), dtype="float32"))
    if len(set(map(len, audio))) != 1:
        raise ValueError("The channel files must cover the same time interval")
    model = Model(args.model)
    result = model.stream(channels=len(audio)).push(audio)
    thresholds = {"eot": .32 if len(audio) > 1 else .36,
                  "int": .70 if len(audio) > 1 else .74, "vad": .50}
    counts = {name: [int((seq > thresholds[name]).sum()) for seq in series]
              for name, series in result.items()}
    print(json.dumps({"channels": len(audio), "frames_per_channel": len(result["eot"][0]),
                      "threshold_counts": counts}))

Attribution

This is an ONNX conversion of p99lab’s public v2 model from p99turn 2.0.0. The learned weights stayed in float32. The graph uses explicit attention cache inputs and outputs. The example uses SciPy for the upstream low-pass and log-mel calculation. The original license and notice are included. Pinned upstream model and guidance

Downloads last month
19
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for strangelab/streaming-turn-detection-onnx

Quantized
(1)
this model