File size: 4,264 Bytes
2640ad4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""Frozen streaming VAD shared by data building, demo and server.

Silero VAD (at 8 or 16 kHz, 32 ms frames) run causally, then a loudness gate and a start/stop hysteresis
state machine. Input audio at any rate is resampled to VadConfig.sr; segments are in seconds. The server must
use the same VadConfig as the data build (Silero gives slightly different probabilities at 8 vs 16 kHz). Run lengths are whole frames: start/stop need 7 frames (224 ms), so
speech_stop fires 224 ms after speech_end. Live serving must keep >= 0.6 s of audio before a declared
speech_start so the 0.3 s clip pre-roll used in training can be reproduced.
"""
import math
from dataclasses import dataclass

import numpy as np
import pandas as pd
import soxr
import torch
from silero_vad import load_silero_vad


@dataclass(frozen=True)
class VadConfig:
    sr: int  # rate Silero runs at: 8000 or 16000 (no default: must match the server)
    start_thr: float = 0.7
    stop_thr: float = 0.55
    start_s: float = 0.2
    stop_s: float = 0.2
    # loudness gate: frame is silence if > gate_db below the speaker's own running speech level
    # (gate_quantile of dB over frames with prob >= gate_conf_thr in the past level_window_s)
    gate_db: float = 25.0  # 15 cut quiet turn endings (4x more end_mismatch drops on 500 validation calls)
    gate_conf_thr: float = 0.9
    gate_quantile: float = 0.9
    level_window_s: float = 60.0
    gate_floor_db: float | None = None  # absolute floor used before any confident speech; None = no gate

    def __post_init__(self):
        assert self.sr in (8000, 16000), "Silero VAD supports 8000 or 16000 Hz"

    @property
    def frame(self) -> int:
        return self.sr * 32 // 1000  # 32 ms: 256 samples at 8 kHz, 512 at 16 kHz


@dataclass(frozen=True)
class Segment:
    start: float  # first speech frame of the run (s)
    end: float  # first silent frame (s)
    fire: float  # when speech_stop was declared (s)

    @property
    def dur(self) -> float:
        return self.end - self.start


_model = None


def speech_probs(wav: np.ndarray, cfg: VadConfig) -> np.ndarray:
    """Per-frame Silero probabilities. audio_forward feeds frames sequentially with carried state (causal)."""
    global _model
    if _model is None:
        _model = load_silero_vad()
    _model.reset_states()
    with torch.no_grad():
        return _model.audio_forward(torch.from_numpy(wav), cfg.sr)[0].numpy()


def frame_db(wav: np.ndarray, cfg: VadConfig) -> np.ndarray:
    n = len(wav) // cfg.frame
    return 10 * np.log10((wav[: n * cfg.frame].reshape(n, cfg.frame) ** 2).mean(1) + 1e-10)


def gate(probs: np.ndarray, db: np.ndarray, cfg: VadConfig) -> np.ndarray:
    """Zero frames more than gate_db below the speaker's own speech level (causal rolling quantile)."""
    window = round(cfg.level_window_s * cfg.sr / cfg.frame)
    confident = pd.Series(np.where(probs >= cfg.gate_conf_thr, db, np.nan))
    level = confident.rolling(window, min_periods=1).quantile(cfg.gate_quantile).to_numpy()
    floor = -np.inf if cfg.gate_floor_db is None else cfg.gate_floor_db
    return np.where(db < np.where(np.isnan(level), floor, level - cfg.gate_db), 0.0, probs)


def state_machine(probs: np.ndarray, cfg: VadConfig) -> list[Segment]:
    fs = cfg.frame / cfg.sr
    n_on, n_off = math.ceil(cfg.start_s / fs), math.ceil(cfg.stop_s / fs)
    segments, speaking, run, run_start, seg_start = [], False, 0, 0, 0
    for i, p in enumerate(probs):
        if not (p < cfg.stop_thr if speaking else p >= cfg.start_thr):
            run = 0
            continue
        if run == 0:
            run_start = i
        run += 1
        if not speaking and run == n_on:
            speaking, run, seg_start = True, 0, run_start
        elif speaking and run == n_off:
            segments.append(Segment(seg_start * fs, run_start * fs, (i + 1) * fs))
            speaking, run = False, 0
    return segments


def detect(wav: np.ndarray, sr: int, cfg: VadConfig) -> list[Segment]:
    """Speech segments (in seconds) of a mono float32 signal at sample rate sr."""
    if sr != cfg.sr:
        wav = soxr.resample(wav, sr, cfg.sr).astype(np.float32)
    db = frame_db(wav, cfg)
    return state_machine(gate(speech_probs(wav, cfg)[: len(db)], db, cfg), cfg)