Skip to content

Commit 2292082

Browse files
committed
feat(vad): add Silero VAD adapter
1 parent 79a0ed2 commit 2292082

6 files changed

Lines changed: 155 additions & 0 deletions

File tree

README_zh.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,13 @@ from funasr import AutoModel
239239
model = AutoModel(model="paraformer-zh", vad_model="fsmn-vad", punc_model="ct-punc", spk_model="cam++", device="cuda")
240240
result = model.generate(input="https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/asr_example_zh.wav", hotword="关键词 20")
241241

242+
# 使用 Silero VAD(先安装:python -m pip install "funasr[silero]")
243+
model = AutoModel(
244+
model="paraformer-zh", vad_model="silero-vad", device="cpu",
245+
vad_kwargs={"silero_threshold": 0.5, "silero_min_silence_duration_ms": 100},
246+
)
247+
result = model.generate(input="audio.wav")
248+
242249
# 中/英/日 + 中文方言
243250
model = AutoModel(model="FunAudioLLM/Fun-ASR-Nano-2512", hub="hf", trust_remote_code=True,
244251
vad_model="fsmn-vad", vad_kwargs={"max_single_segment_time": 30000}, device="cuda")

funasr/auto/auto_model.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,12 @@ def build_model(**kwargs):
536536
kwargs contains the resolved configuration.
537537
"""
538538
assert "model" in kwargs
539+
# Silero VAD is loaded by its optional Python package rather than a
540+
# FunASR model repository. Supplying model_conf keeps it on the normal
541+
# AutoModel construction path while bypassing hub config resolution.
542+
if kwargs["model"] in {"silero-vad", "silero_vad"}:
543+
kwargs.setdefault("model_conf", {})
544+
kwargs["model"] = "SileroVad"
539545
if "model_conf" not in kwargs:
540546
logging.info("download models from model hub: {}".format(kwargs.get("hub", "ms")))
541547
kwargs = download_model(**kwargs)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"""Silero VAD adapter for the FunASR AutoModel pipeline."""

funasr/models/silero_vad/model.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
"""Adapter that makes Silero VAD return FunASR-compatible millisecond segments."""
2+
3+
import time
4+
5+
import torch
6+
7+
from funasr.register import tables
8+
from funasr.utils.load_utils import load_audio_text_image_video
9+
10+
11+
@tables.register("model_classes", "SileroVad")
12+
class SileroVad(torch.nn.Module):
13+
"""Offline Silero VAD adapter used by ``AutoModel(vad_model='silero-vad')``.
14+
15+
Requires the official ``silero-vad`` Python package.
16+
"""
17+
18+
def __init__(self, **kwargs):
19+
super().__init__()
20+
self.anchor = torch.nn.Parameter(torch.empty(0), requires_grad=False)
21+
try:
22+
from silero_vad import get_speech_timestamps, load_silero_vad
23+
except ImportError as error:
24+
raise ImportError(
25+
"Silero VAD requires the optional dependency. Install it with "
26+
'`python -m pip install "funasr[silero]"` or '
27+
"`python -m pip install silero-vad`."
28+
) from error
29+
self.model = load_silero_vad(onnx=kwargs.get("silero_onnx", False))
30+
self.get_speech_timestamps = get_speech_timestamps
31+
32+
@staticmethod
33+
def _split_long_segments(segments, max_single_segment_time):
34+
if not max_single_segment_time:
35+
return segments
36+
limit_ms = int(max_single_segment_time)
37+
split = []
38+
for start, end in segments:
39+
while end - start > limit_ms:
40+
split.append([start, start + limit_ms])
41+
start += limit_ms
42+
split.append([start, end])
43+
return split
44+
45+
def inference(self, data_in, key=None, **kwargs):
46+
sample_rate = int(kwargs.get("silero_sampling_rate", 16000))
47+
if sample_rate not in (8000, 16000):
48+
raise ValueError("Silero VAD supports silero_sampling_rate=8000 or 16000")
49+
audio_list = load_audio_text_image_video(
50+
data_in,
51+
fs=sample_rate,
52+
audio_fs=kwargs.get("fs", sample_rate),
53+
data_type=kwargs.get("data_type", "sound"),
54+
)
55+
if not isinstance(audio_list, list):
56+
audio_list = [audio_list]
57+
58+
started = time.perf_counter()
59+
results = []
60+
for index, audio in enumerate(audio_list):
61+
waveform = torch.as_tensor(audio, dtype=torch.float32).flatten().cpu()
62+
timestamps = self.get_speech_timestamps(
63+
waveform,
64+
self.model,
65+
sampling_rate=sample_rate,
66+
threshold=kwargs.get("silero_threshold", 0.5),
67+
min_speech_duration_ms=kwargs.get("silero_min_speech_duration_ms", 250),
68+
min_silence_duration_ms=kwargs.get("silero_min_silence_duration_ms", 100),
69+
speech_pad_ms=kwargs.get("silero_speech_pad_ms", 30),
70+
)
71+
segments = [
72+
[int(item["start"] * 1000 / sample_rate), int(item["end"] * 1000 / sample_rate)]
73+
for item in timestamps
74+
]
75+
segments = self._split_long_segments(
76+
segments, kwargs.get("max_single_segment_time")
77+
)
78+
results.append({"key": key[index] if key else str(index), "value": segments})
79+
elapsed = time.perf_counter() - started
80+
total_samples = sum(len(torch.as_tensor(audio)) for audio in audio_list)
81+
return results, {"batch_data_time": total_samples / sample_rate, "forward": elapsed}

setup.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@
4848
"train": [
4949
"rapidfuzz>=3.0.0",
5050
],
51+
"silero": [
52+
"silero-vad>=6.0.0",
53+
],
5154
# all: The modules should be optionally installled due to some reason.
5255
# Please consider moving them to "install" occasionally
5356
"all": [

tests/test_silero_vad_adapter.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import unittest
2+
from importlib.util import find_spec
3+
from unittest.mock import patch
4+
5+
import torch
6+
7+
from funasr.auto.auto_model import AutoModel
8+
from funasr.models.silero_vad.model import SileroVad
9+
10+
11+
@unittest.skipUnless(find_spec("silero_vad"), "silero-vad is not installed")
12+
class TestSileroVadAdapter(unittest.TestCase):
13+
def _timestamps_stub(self, waveform, model, sampling_rate, **options):
14+
self.assertEqual(sampling_rate, 16000)
15+
self.assertEqual(options["threshold"], 0.6)
16+
return [{"start": 1600, "end": 17600}]
17+
18+
def _load_stub(self, *args, **kwargs):
19+
self.assertEqual(kwargs, {"onnx": False})
20+
return torch.nn.Identity()
21+
22+
@patch("silero_vad.get_speech_timestamps")
23+
@patch("silero_vad.load_silero_vad")
24+
def test_returns_funasr_millisecond_segments_and_honors_max_length(self, load_model, timestamps):
25+
load_model.side_effect = self._load_stub
26+
timestamps.side_effect = self._timestamps_stub
27+
model = SileroVad()
28+
results, metadata = model.inference(
29+
data_in=[torch.zeros(32000)],
30+
key=["sample"],
31+
silero_threshold=0.6,
32+
max_single_segment_time=500,
33+
)
34+
35+
self.assertEqual(results, [{"key": "sample", "value": [[100, 600], [600, 1100]]}])
36+
self.assertEqual(metadata["batch_data_time"], 2.0)
37+
load_model.assert_called_once_with(onnx=False)
38+
39+
@patch("silero_vad.get_speech_timestamps")
40+
@patch("silero_vad.load_silero_vad")
41+
def test_rejects_unsupported_sampling_rate(self, load_model, timestamps):
42+
load_model.side_effect = self._load_stub
43+
model = SileroVad()
44+
with self.assertRaisesRegex(ValueError, "8000 or 16000"):
45+
model.inference(data_in=[torch.zeros(16000)], silero_sampling_rate=44100)
46+
47+
@patch("silero_vad.get_speech_timestamps")
48+
@patch("silero_vad.load_silero_vad")
49+
def test_auto_model_alias_uses_the_existing_vad_build_path(self, load_model, timestamps):
50+
load_model.side_effect = self._load_stub
51+
model, resolved = AutoModel.build_model(model="silero-vad", device="cpu")
52+
self.assertIsInstance(model, SileroVad)
53+
self.assertEqual(resolved["model"], "SileroVad")
54+
55+
56+
if __name__ == "__main__":
57+
unittest.main()

0 commit comments

Comments
 (0)