feat: fsmn vad => onnx runtime

This commit is contained in:
Harold 2025-12-19 14:27:32 +08:00
parent c82787b7d7
commit 81ccabd5e6
8 changed files with 278 additions and 61 deletions

View file

@ -2,7 +2,7 @@ import asyncio
import time import time
import numpy as np import numpy as np
from dataclasses import dataclass from dataclasses import dataclass
from funasr import AutoModel from funasr_onnx import Fsmn_vad_online
from config.logger import setup_logging from config.logger import setup_logging
from .base import VADProviderBase, VADStream from .base import VADProviderBase, VADStream
@ -21,20 +21,20 @@ class FsmnVADOptions:
sample_rate: int = 16000 # 16kHz sample_rate: int = 16000 # 16kHz
chunk_size_ms: int = 100 # streaming chunk size in ms chunk_size_ms: int = 100 # streaming chunk size in ms
# FSMN model parameters (passed to AutoModel) # FSMN model parameters (can override models/fsmn_vad_onnx/config.yaml defaults)
min_silence_duration_ms: int = 500 # silence detection duration (ms) min_silence_duration_ms: int = 500 # silence detection duration (ms)
speech_noise_threshold: float = 0.6 # speech/noise threshold, higher = stricter speech_noise_threshold: float = 0.6 # speech/noise threshold, higher = stricter
sil_to_speech_time_thres: int = 150 # silence→speech transition time (ms), higher = less noise sensitive sil_to_speech_time_thres: int = 150 # silence→speech transition time (ms)
class VADProvider(VADProviderBase): class VADProvider(VADProviderBase):
"""FSMN VAD provider using FunASR""" """FSMN VAD provider using ONNX Runtime for fast CPU inference"""
def __init__(self, config: dict): def __init__(self, config: dict):
super().__init__() super().__init__()
model_name = config.get("model", "fsmn-vad") model_dir = config.get("model_dir", "models/fsmn_vad_onnx")
model_revision = config.get("model_revision", "v2.0.4") quantize = config.get("quantize", True)
# Parse config # Parse config
self._opts = FsmnVADOptions( self._opts = FsmnVADOptions(
@ -46,14 +46,24 @@ class VADProvider(VADProviderBase):
sil_to_speech_time_thres=int(config.get("sil_to_speech_time_thres", 150)), sil_to_speech_time_thres=int(config.get("sil_to_speech_time_thres", 150)),
) )
# Pass FSMN model parameters to AutoModel # Load ONNX model with ONNX Runtime
self._model = AutoModel( self._model = Fsmn_vad_online(
model=model_name, model_dir=model_dir,
model_revision=model_revision, quantize=quantize,
max_end_silence_time=self._opts.min_silence_duration_ms, max_end_sil=self._opts.min_silence_duration_ms,
speech_noise_thres=self._opts.speech_noise_threshold, )
sil_to_speech_time_thres=self._opts.sil_to_speech_time_thres,
disable_pbar=True, # disable progress bar # Override VAD parameters at runtime (these override config.yaml defaults)
vad_opts = self._model.vad_scorer.vad_opts
vad_opts.max_end_silence_time = self._opts.min_silence_duration_ms
vad_opts.speech_noise_thres = self._opts.speech_noise_threshold
vad_opts.sil_to_speech_time_thres = self._opts.sil_to_speech_time_thres
logger.bind(tag=TAG).info(
f"Loaded FSMN VAD ONNX model from {model_dir} (quantize={quantize}, "
f"max_end_sil={self._opts.min_silence_duration_ms}ms, "
f"speech_noise_thres={self._opts.speech_noise_threshold}, "
f"sil_to_speech_time={self._opts.sil_to_speech_time_thres}ms)"
) )
@ -107,8 +117,8 @@ class FsmnVADStream(VADStream):
input_audios: bytearray = bytearray() input_audios: bytearray = bytearray()
inference_audios: bytearray = bytearray() inference_audios: bytearray = bytearray()
# FSMN cache for streaming (reset on speech end) # FSMN ONNX cache for streaming (reset on speech end)
fsmn_cache = {} fsmn_param_dict = {"in_cache": [], "is_final": False}
while not self._is_closed: while not self._is_closed:
try: try:
@ -130,13 +140,8 @@ class FsmnVADStream(VADStream):
) )
chunk_float32 = chunk_int16.astype(np.float32) / 32768.0 chunk_float32 = chunk_int16.astype(np.float32) / 32768.0
# Run FSMN inference # Run FSMN ONNX inference
res = self._model.generate( res = self._model(chunk_float32, param_dict=fsmn_param_dict)
input=chunk_float32,
cache=fsmn_cache,
is_final=False,
chunk_size=self._opts.chunk_size_ms
)
inference_duration = time.perf_counter() - inference_start inference_duration = time.perf_counter() - inference_start
@ -168,10 +173,10 @@ class FsmnVADStream(VADStream):
def _copy_speech_buffer() -> bytes: def _copy_speech_buffer() -> bytes:
return bytes(self._speech_buffer[:speech_buffer_index]) return bytes(self._speech_buffer[:speech_buffer_index])
# Parse FSMN result # Parse FSMN ONNX result
# res format: [{"key": "xxx", "value": [[start_ms, end_ms], ...]}] # res format: [[[start_ms, end_ms], ...]] or []
if res and len(res) > 0 and res[0].get("value"): if res and len(res) > 0 and len(res[0]) > 0:
seg = res[0]["value"][0] # Take first segment seg = res[0][0] # Take first segment from first batch
seg_start, seg_end = seg[0], seg[1] seg_start, seg_end = seg[0], seg[1]
if seg_start >= 0 and seg_end == -1: if seg_start >= 0 and seg_end == -1:
@ -216,7 +221,7 @@ class FsmnVADStream(VADStream):
# Reset for next utterance # Reset for next utterance
speech_duration = 0.0 speech_duration = 0.0
fsmn_cache = {} fsmn_param_dict = {"in_cache": [], "is_final": False}
_reset_write_cursor() _reset_write_cursor()
elif seg_start > 0 and seg_end > 0: elif seg_start > 0 and seg_end > 0:

View file

@ -493,8 +493,8 @@ VAD:
# Reference: https://huggingface.co/funasr/fsmn-vad # Reference: https://huggingface.co/funasr/fsmn-vad
FsmnVAD: FsmnVAD:
type: fsmn type: fsmn
model: fsmn-vad model_dir: models/fsmn_vad_onnx # ONNX model directory
model_revision: v2.0.4 quantize: true # use INT8 quantized model (faster)
chunk_size_ms: 100 # streaming chunk size in ms chunk_size_ms: 100 # streaming chunk size in ms
min_silence_duration_ms: 400 # silence detection duration (ms) min_silence_duration_ms: 400 # silence detection duration (ms)
speech_noise_threshold: 0.6 # speech/noise threshold (0.6-0.9), higher = stricter speech_noise_threshold: 0.6 # speech/noise threshold (0.6-0.9), higher = stricter

View file

@ -0,0 +1,8 @@
<Nnet>
<Splice> 400 400
[ 0 ]
<AddShift> 400 400
<LearnRateCoef> 0 [ -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 ]
<Rescale> 400 400
<LearnRateCoef> 0 [ 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 ]
</Nnet>

View file

@ -0,0 +1,56 @@
frontend: WavFrontendOnline
frontend_conf:
fs: 16000
window: hamming
n_mels: 80
frame_length: 25
frame_shift: 10
dither: 0.0
lfr_m: 5
lfr_n: 1
model: FsmnVADStreaming
model_conf:
sample_rate: 16000
detect_mode: 1
snr_mode: 0
max_end_silence_time: 800
max_start_silence_time: 3000
do_start_point_detection: True
do_end_point_detection: True
window_size_ms: 200
sil_to_speech_time_thres: 150
speech_to_sil_time_thres: 150
speech_2_noise_ratio: 1.0
do_extend: 1
lookback_time_start_point: 200
lookahead_time_end_point: 100
max_single_segment_time: 60000
snr_thres: -100.0
noise_frame_num_used_for_snr: 100
decibel_thres: -100.0
speech_noise_thres: 0.6
fe_prior_thres: 0.0001
silence_pdf_num: 1
sil_pdf_ids: [0]
speech_noise_thresh_low: -0.1
speech_noise_thresh_high: 0.3
output_frame_probs: False
frame_in_ms: 10
frame_length_ms: 25
encoder: FSMN
encoder_conf:
input_dim: 400
input_affine_dim: 140
fsmn_layers: 4
linear_dim: 250
proj_dim: 128
lorder: 20
rorder: 0
lstride: 1
rstride: 0
output_affine_dim: 140
output_dim: 248

Binary file not shown.

View file

@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""
Export FSMN VAD model to ONNX format for faster inference on CPU.
Usage:
python scripts/export_fsmn_onnx.py
Output:
./models/fsmn_vad_onnx/ - ONNX model files
"""
import os
import sys
from pathlib import Path
# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
def export_fsmn_to_onnx(
model_name: str = "iic/speech_fsmn_vad_zh-cn-16k-common-pytorch",
model_revision: str = "v2.0.4",
output_dir: str = "./models/fsmn_vad_onnx",
quantize: bool = True,
device: str = "cpu",
):
"""
Export FSMN VAD model to ONNX format.
Args:
model_name: ModelScope model name
model_revision: Model revision/version
output_dir: Output directory for ONNX files
quantize: Whether to quantize to INT8 (smaller, faster on CPU)
device: Device for loading PyTorch model
"""
from funasr import AutoModel
print(f"Loading FSMN VAD model: {model_name} (revision: {model_revision})")
print(f"Device: {device}")
# Load PyTorch model
model = AutoModel(
model=model_name,
model_revision=model_revision,
device=device,
disable_pbar=False,
)
# Create output directory
os.makedirs(output_dir, exist_ok=True)
print(f"\nExporting to ONNX...")
print(f" Output directory: {output_dir}")
print(f" Quantize (INT8): {quantize}")
# Export to ONNX
res = model.export(
quantize=quantize,
output_dir=output_dir,
)
print(f"\n✅ Export success!")
print(f" ONNX files saved to: {output_dir}")
# List exported files
print(f"\nExported files:")
for f in Path(output_dir).glob("*"):
size_mb = f.stat().st_size / (1024 * 1024)
print(f" - {f.name} ({size_mb:.2f} MB)")
return res
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Export FSMN VAD to ONNX")
parser.add_argument(
"--model",
default="iic/speech_fsmn_vad_zh-cn-16k-common-pytorch",
help="ModelScope model name"
)
parser.add_argument(
"--revision",
default="v2.0.4",
help="Model revision"
)
parser.add_argument(
"--output-dir",
default="./models/fsmn_vad_onnx",
help="Output directory"
)
parser.add_argument(
"--no-quantize",
action="store_true",
help="Disable INT8 quantization (use FP32)"
)
parser.add_argument(
"--device",
default="cpu",
choices=["cpu", "cuda"],
help="Device for loading model"
)
args = parser.parse_args()
export_fsmn_to_onnx(
model_name=args.model,
model_revision=args.revision,
output_dir=args.output_dir,
quantize=not args.no_quantize,
device=args.device,
)

View file

@ -1,12 +1,12 @@
""" """
FSMN VAD Stream Test Script FSMN VAD Stream Test Script (ONNX Version)
This script tests FSMN VAD with audio files, simulating the streaming behavior: This script tests FSMN VAD ONNX with audio files, simulating the streaming behavior:
1. Load an audio file 1. Load an audio file
2. Convert to 16kHz mono PCM 2. Convert to 16kHz mono PCM
3. Split into 60ms chunks (simulating WebSocket protocol) 3. Split into 60ms chunks (simulating WebSocket protocol)
4. Feed chunks to FSMN VAD stream 4. Feed chunks to FSMN VAD ONNX stream
5. Print VAD events (START_OF_SPEECH, END_OF_SPEECH) 5. Print VAD events (START_OF_SPEECH, END_OF_SPEECH)
Usage: Usage:
@ -136,41 +136,55 @@ class VADEvent:
# ============================================================================ # ============================================================================
class FsmnVADTester: class FsmnVADTester:
"""Test FSMN VAD with audio file input""" """Test FSMN VAD ONNX with audio file input"""
def __init__( def __init__(
self, self,
model_dir: str = "models/fsmn_vad_onnx",
quantize: bool = True,
chunk_size_ms: int = 100, chunk_size_ms: int = 100,
min_silence_duration_ms: int = 500, min_silence_duration_ms: int = 500,
speech_noise_threshold: float = 0.6, speech_noise_threshold: float = 0.6,
sil_to_speech_time_thres: int = 150,
prefix_padding_duration: float = 0.3, prefix_padding_duration: float = 0.3,
): ):
self.model_dir = model_dir
self.quantize = quantize
self.chunk_size_ms = chunk_size_ms self.chunk_size_ms = chunk_size_ms
self.min_silence_duration_ms = min_silence_duration_ms self.min_silence_duration_ms = min_silence_duration_ms
self.speech_noise_threshold = speech_noise_threshold self.speech_noise_threshold = speech_noise_threshold
self.sil_to_speech_time_thres = sil_to_speech_time_thres
self.prefix_padding_duration = prefix_padding_duration self.prefix_padding_duration = prefix_padding_duration
self.sample_rate = 16000 self.sample_rate = 16000
# Initialize FSMN model # Initialize FSMN ONNX model
self._init_model() self._init_model()
def _init_model(self): def _init_model(self):
"""Initialize FSMN VAD model""" """Initialize FSMN VAD ONNX model"""
try: try:
from funasr import AutoModel from funasr_onnx import Fsmn_vad_online
except ImportError: except ImportError:
print("Error: funasr is required. Install with: pip install funasr") print("Error: funasr_onnx is required. Install with: pip install funasr-onnx")
sys.exit(1) sys.exit(1)
print("\nInitializing FSMN VAD model...") print(f"\nInitializing FSMN VAD ONNX model from {self.model_dir}...")
self.model = AutoModel( self.model = Fsmn_vad_online(
model="fsmn-vad", model_dir=self.model_dir,
model_revision="v2.0.4", quantize=self.quantize,
disable_pbar=True, # disable progress bar max_end_sil=self.min_silence_duration_ms,
max_end_silence_time=self.min_silence_duration_ms,
speech_noise_thres=self.speech_noise_threshold,
) )
print("Model initialized.")
# Override VAD parameters at runtime
vad_opts = self.model.vad_scorer.vad_opts
vad_opts.max_end_silence_time = self.min_silence_duration_ms
vad_opts.speech_noise_thres = self.speech_noise_threshold
vad_opts.sil_to_speech_time_thres = self.sil_to_speech_time_thres
print(f"Model initialized (quantize={self.quantize}).")
print(f" max_end_silence_time: {vad_opts.max_end_silence_time}ms")
print(f" speech_noise_thres: {vad_opts.speech_noise_thres}")
print(f" sil_to_speech_time_thres: {vad_opts.sil_to_speech_time_thres}ms")
def process_audio_file(self, file_path: str, input_chunk_ms: int = 60, verbose: bool = False) -> List[dict]: def process_audio_file(self, file_path: str, input_chunk_ms: int = 60, verbose: bool = False) -> List[dict]:
""" """
@ -202,7 +216,7 @@ class FsmnVADTester:
speech_buffer_index = 0 speech_buffer_index = 0
# State # State
fsmn_cache = {} fsmn_param_dict = {"in_cache": [], "is_final": False}
speaking = False speaking = False
speech_start_ms = 0 speech_start_ms = 0
speech_duration = 0.0 speech_duration = 0.0
@ -247,13 +261,8 @@ class FsmnVADTester:
chunk_int16 = np.frombuffer(inference_buffer[:chunk_bytes], dtype=np.int16) chunk_int16 = np.frombuffer(inference_buffer[:chunk_bytes], dtype=np.int16)
chunk_float32 = chunk_int16.astype(np.float32) / 32768.0 chunk_float32 = chunk_int16.astype(np.float32) / 32768.0
# Run FSMN inference (is_final=False for streaming scenario) # Run FSMN ONNX inference
res = self.model.generate( res = self.model(chunk_float32, param_dict=fsmn_param_dict)
input=chunk_float32,
cache=fsmn_cache,
is_final=False,
chunk_size=self.chunk_size_ms,
)
inference_duration = time.perf_counter() - inference_start inference_duration = time.perf_counter() - inference_start
total_inference_time += inference_duration total_inference_time += inference_duration
@ -261,9 +270,8 @@ class FsmnVADTester:
# Verbose output: show raw FSMN result # Verbose output: show raw FSMN result
if verbose: if verbose:
value = res[0].get("value", []) if res and len(res) > 0 else []
print(f" [{current_time_ms:6.0f}ms] inference #{inference_count:3d} | " print(f" [{current_time_ms:6.0f}ms] inference #{inference_count:3d} | "
f"result={value} | " f"result={res} | "
f"time={inference_duration*1000:.2f}ms") f"time={inference_duration*1000:.2f}ms")
# Copy to speech buffer # Copy to speech buffer
@ -273,9 +281,9 @@ class FsmnVADTester:
speech_buffer[speech_buffer_index:speech_buffer_index + to_copy] = input_buffer[:to_copy] speech_buffer[speech_buffer_index:speech_buffer_index + to_copy] = input_buffer[:to_copy]
speech_buffer_index += to_copy speech_buffer_index += to_copy
# Parse FSMN result # Parse FSMN ONNX result: [[[start, end], ...]]
if res and len(res) > 0 and res[0].get("value"): if res and len(res) > 0 and len(res[0]) > 0:
seg = res[0]["value"][0] seg = res[0][0] # First segment from first batch
seg_start, seg_end = seg[0], seg[1] seg_start, seg_end = seg[0], seg[1]
if seg_start >= 0 and seg_end == -1: if seg_start >= 0 and seg_end == -1:
@ -320,7 +328,7 @@ class FsmnVADTester:
# Reset state # Reset state
speech_duration = 0.0 speech_duration = 0.0
fsmn_cache = {} fsmn_param_dict = {"in_cache": [], "is_final": False}
reset_write_cursor() reset_write_cursor()
elif seg_start > 0 and seg_end > 0: elif seg_start > 0 and seg_end > 0:
@ -353,13 +361,14 @@ class FsmnVADTester:
def main(): def main():
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="Test FSMN VAD with audio file", description="Test FSMN VAD ONNX with audio file",
formatter_class=argparse.RawDescriptionHelpFormatter, formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=""" epilog="""
Examples: Examples:
python test_fsmn_vad_stream.py test_audio.wav python test_fsmn_vad_stream.py test_audio.wav
python test_fsmn_vad_stream.py test_audio.mp3 --input-chunk-ms 100 python test_fsmn_vad_stream.py test_audio.mp3 --input-chunk-ms 100
python test_fsmn_vad_stream.py test_audio.wav --min-silence-ms 800 python test_fsmn_vad_stream.py test_audio.wav --min-silence-ms 800
python test_fsmn_vad_stream.py test_audio.wav --no-quantize
""" """
) )
@ -369,6 +378,19 @@ Examples:
help="Path to audio file (wav, mp3, etc.)" help="Path to audio file (wav, mp3, etc.)"
) )
parser.add_argument(
"--model-dir",
type=str,
default="models/fsmn_vad_onnx",
help="ONNX model directory (default: models/fsmn_vad_onnx)"
)
parser.add_argument(
"--no-quantize",
action="store_true",
help="Use FP32 model instead of INT8 quantized model"
)
parser.add_argument( parser.add_argument(
"--input-chunk-ms", "--input-chunk-ms",
type=int, type=int,
@ -397,6 +419,13 @@ Examples:
help="Speech noise threshold (default: 0.6)" help="Speech noise threshold (default: 0.6)"
) )
parser.add_argument(
"--sil-to-speech-time",
type=int,
default=150,
help="Silence to speech transition time in ms (default: 150)"
)
parser.add_argument( parser.add_argument(
"--prefix-padding", "--prefix-padding",
type=float, type=float,
@ -419,9 +448,12 @@ Examples:
# Create tester and run # Create tester and run
tester = FsmnVADTester( tester = FsmnVADTester(
model_dir=args.model_dir,
quantize=not args.no_quantize,
chunk_size_ms=args.fsmn_chunk_ms, chunk_size_ms=args.fsmn_chunk_ms,
min_silence_duration_ms=args.min_silence_ms, min_silence_duration_ms=args.min_silence_ms,
speech_noise_threshold=args.speech_noise_threshold, speech_noise_threshold=args.speech_noise_threshold,
sil_to_speech_time_thres=args.sil_to_speech_time,
prefix_padding_duration=args.prefix_padding, prefix_padding_duration=args.prefix_padding,
) )