pysilero-vad 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Michael Hansen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include requirements.txt
2
+ include pysilero_vad/models/*.onnx
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.1
2
+ Name: pysilero_vad
3
+ Version: 2.0.0
4
+ Summary: Pre-packaged voice activity detector using silero-vad
5
+ Home-page: http://github.com/rhasspy/pysilero-vad
6
+ Author: Michael Hansen
7
+ Author-email: mike@rhasspy.org
8
+ License: MIT
9
+ Keywords: voice activity vad
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3.7
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE.md
21
+ Requires-Dist: onnxruntime<2,>=1.18.0
22
+ Requires-Dist: numpy<2
23
+
24
+ # pySilero VAD
25
+
26
+ A pre-packaged voice activity detector using [silero-vad](https://github.com/snakers4/silero-vad).
27
+
28
+ ``` sh
29
+ pip install pysilero-vad
30
+ ```
31
+
32
+ ``` python
33
+ from pysilero_vad import SileroVoiceActivityDetector
34
+
35
+ vad = SileroVoiceActivityDetector()
36
+
37
+ # Audio must be 16Khz, 16-bit mono PCM
38
+ if vad(audio_bytes) >= 0.5:
39
+ print("Speech")
40
+ else:
41
+ print("Silence")
42
+ ```
43
+
@@ -0,0 +1,20 @@
1
+ # pySilero VAD
2
+
3
+ A pre-packaged voice activity detector using [silero-vad](https://github.com/snakers4/silero-vad).
4
+
5
+ ``` sh
6
+ pip install pysilero-vad
7
+ ```
8
+
9
+ ``` python
10
+ from pysilero_vad import SileroVoiceActivityDetector
11
+
12
+ vad = SileroVoiceActivityDetector()
13
+
14
+ # Audio must be 16Khz, 16-bit mono PCM
15
+ if vad(audio_bytes) >= 0.5:
16
+ print("Speech")
17
+ else:
18
+ print("Silence")
19
+ ```
20
+
@@ -0,0 +1,107 @@
1
+ import logging
2
+ from pathlib import Path
3
+ from typing import Final, Iterable, Union
4
+
5
+ import numpy as np
6
+ import onnxruntime
7
+
8
+ _RATE: Final = 16000 # Khz
9
+ _MAX_WAV: Final = 32767
10
+ _DIR = Path(__file__).parent
11
+ _DEFAULT_ONNX_PATH = _DIR / "models" / "silero_vad.onnx"
12
+ _CONTEXT_SIZE: Final = 64 # 16Khz
13
+ _CHUNK_SAMPLES: Final = 512
14
+ _CHUNK_BYTES: Final = _CHUNK_SAMPLES * 2 # 16-bit
15
+
16
+ _LOGGER = logging.getLogger()
17
+
18
+
19
+ class InvalidChunkSizeError(Exception):
20
+ """Error raised when chunk size is not correct."""
21
+
22
+
23
+ class SileroVoiceActivityDetector:
24
+ """Detects speech/silence using Silero VAD.
25
+
26
+ https://github.com/snakers4/silero-vad
27
+ """
28
+
29
+ def __init__(self, onnx_path: Union[str, Path] = _DEFAULT_ONNX_PATH) -> None:
30
+ onnx_path = str(onnx_path)
31
+
32
+ opts = onnxruntime.SessionOptions()
33
+ opts.inter_op_num_threads = 1
34
+ opts.intra_op_num_threads = 1
35
+
36
+ self.session = onnxruntime.InferenceSession(
37
+ onnx_path, providers=["CPUExecutionProvider"], sess_options=opts
38
+ )
39
+
40
+ self._context = np.zeros((1, _CONTEXT_SIZE), dtype=np.float32)
41
+ self._state = np.zeros((2, 1, 128), dtype=np.float32)
42
+ self._sr = np.array(_RATE, dtype=np.int64)
43
+
44
+ @staticmethod
45
+ def chunk_samples() -> int:
46
+ """Return number of samples required for an audio chunk."""
47
+ return _CHUNK_SAMPLES
48
+
49
+ @staticmethod
50
+ def chunk_bytes() -> int:
51
+ """Return number of bytes required for an audio chunk."""
52
+ return _CHUNK_BYTES
53
+
54
+ def reset(self) -> None:
55
+ """Reset state."""
56
+ self._state = np.zeros((2, 1, 128)).astype("float32")
57
+
58
+ def __call__(self, audio: bytes) -> float:
59
+ """Return probability of speech [0-1] in a single audio chunk.
60
+
61
+ Audio *must* be 512 samples of 16Khz 16-bit mono PCM.
62
+ """
63
+ return self.process_chunk(audio)
64
+
65
+ def process_chunk(self, audio: bytes) -> float:
66
+ """Return probability of speech [0-1] in a single audio chunk.
67
+
68
+ Audio *must* be 512 samples of 16Khz 16-bit mono PCM.
69
+ """
70
+ if len(audio) != _CHUNK_BYTES:
71
+ # Window size is fixed at 512 samples in v5
72
+ raise InvalidChunkSizeError
73
+
74
+ audio_array = np.frombuffer(audio, dtype=np.int16).astype(np.float32) / _MAX_WAV
75
+
76
+ # Add batch dimension and context
77
+ audio_array = np.concatenate(
78
+ (self._context, audio_array[np.newaxis, :]), axis=1
79
+ )
80
+ self._context = audio_array[:, -_CONTEXT_SIZE:]
81
+
82
+ # ort_inputs = {"input": audio_array, "state": self._state, "sr": self._sr}
83
+ ort_inputs = {
84
+ "input": audio_array[:, : _CHUNK_SAMPLES + _CONTEXT_SIZE],
85
+ "state": self._state,
86
+ "sr": self._sr,
87
+ }
88
+ ort_outs = self.session.run(None, ort_inputs)
89
+ out, self._state = ort_outs
90
+
91
+ return out.squeeze()
92
+
93
+ def process_chunks(self, audio: bytes) -> Iterable[float]:
94
+ """Return probability of speech in audio [0-1] for each chunk of audio.
95
+
96
+ Audio must be 16Khz 16-bit mono PCM.
97
+ """
98
+ if len(audio) < _CHUNK_BYTES:
99
+ # Window size is fixed at 512 samples in v5
100
+ raise InvalidChunkSizeError
101
+
102
+ num_audio_bytes = len(audio)
103
+ audio_idx = 0
104
+
105
+ while (audio_idx + _CHUNK_BYTES) < num_audio_bytes:
106
+ yield self.process_chunk(audio[audio_idx : audio_idx + _CHUNK_BYTES])
107
+ audio_idx += _CHUNK_BYTES
File without changes
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.1
2
+ Name: pysilero-vad
3
+ Version: 2.0.0
4
+ Summary: Pre-packaged voice activity detector using silero-vad
5
+ Home-page: http://github.com/rhasspy/pysilero-vad
6
+ Author: Michael Hansen
7
+ Author-email: mike@rhasspy.org
8
+ License: MIT
9
+ Keywords: voice activity vad
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3.7
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE.md
21
+ Requires-Dist: onnxruntime<2,>=1.18.0
22
+ Requires-Dist: numpy<2
23
+
24
+ # pySilero VAD
25
+
26
+ A pre-packaged voice activity detector using [silero-vad](https://github.com/snakers4/silero-vad).
27
+
28
+ ``` sh
29
+ pip install pysilero-vad
30
+ ```
31
+
32
+ ``` python
33
+ from pysilero_vad import SileroVoiceActivityDetector
34
+
35
+ vad = SileroVoiceActivityDetector()
36
+
37
+ # Audio must be 16Khz, 16-bit mono PCM
38
+ if vad(audio_bytes) >= 0.5:
39
+ print("Speech")
40
+ else:
41
+ print("Silence")
42
+ ```
43
+
@@ -0,0 +1,15 @@
1
+ LICENSE.md
2
+ MANIFEST.in
3
+ README.md
4
+ requirements.txt
5
+ setup.cfg
6
+ setup.py
7
+ pysilero_vad/__init__.py
8
+ pysilero_vad/py.typed
9
+ pysilero_vad.egg-info/PKG-INFO
10
+ pysilero_vad.egg-info/SOURCES.txt
11
+ pysilero_vad.egg-info/dependency_links.txt
12
+ pysilero_vad.egg-info/requires.txt
13
+ pysilero_vad.egg-info/top_level.txt
14
+ pysilero_vad/models/silero_vad.onnx
15
+ tests/test_vad.py
@@ -0,0 +1,2 @@
1
+ onnxruntime<2,>=1.18.0
2
+ numpy<2
@@ -0,0 +1 @@
1
+ pysilero_vad
@@ -0,0 +1,2 @@
1
+ onnxruntime>=1.18.0,<2
2
+ numpy<2
@@ -0,0 +1,21 @@
1
+ [flake8]
2
+ max-line-length = 88
3
+ ignore =
4
+ E501,
5
+ W503,
6
+ E203,
7
+ D202,
8
+ W504
9
+
10
+ [isort]
11
+ multi_line_output = 3
12
+ include_trailing_comma = True
13
+ force_grid_wrap = 0
14
+ use_parentheses = True
15
+ line_length = 88
16
+ indent = " "
17
+
18
+ [egg_info]
19
+ tag_build =
20
+ tag_date = 0
21
+
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env python3
2
+ from pathlib import Path
3
+
4
+ import setuptools
5
+ from setuptools import setup
6
+
7
+ this_dir = Path(__file__).parent
8
+ module_dir = this_dir / "pysilero_vad"
9
+
10
+ # -----------------------------------------------------------------------------
11
+
12
+ # Load README in as long description
13
+ long_description: str = ""
14
+ readme_path = this_dir / "README.md"
15
+ if readme_path.is_file():
16
+ long_description = readme_path.read_text(encoding="utf-8")
17
+
18
+ requirements = []
19
+ requirements_path = this_dir / "requirements.txt"
20
+ if requirements_path.is_file():
21
+ with open(requirements_path, "r", encoding="utf-8") as requirements_file:
22
+ requirements = requirements_file.read().splitlines()
23
+
24
+ # -----------------------------------------------------------------------------
25
+
26
+ setup(
27
+ name="pysilero_vad",
28
+ version="2.0.0",
29
+ description="Pre-packaged voice activity detector using silero-vad",
30
+ long_description=long_description,
31
+ long_description_content_type="text/markdown",
32
+ url="http://github.com/rhasspy/pysilero-vad",
33
+ author="Michael Hansen",
34
+ author_email="mike@rhasspy.org",
35
+ license="MIT",
36
+ packages=setuptools.find_packages(),
37
+ package_data={
38
+ "pysilero_vad": ["py.typed", "models/silero_vad.onnx"],
39
+ },
40
+ install_requires=requirements,
41
+ classifiers=[
42
+ "Development Status :: 3 - Alpha",
43
+ "Intended Audience :: Developers",
44
+ "Topic :: Multimedia :: Sound/Audio :: Speech",
45
+ "License :: OSI Approved :: MIT License",
46
+ "Programming Language :: Python :: 3.7",
47
+ "Programming Language :: Python :: 3.8",
48
+ "Programming Language :: Python :: 3.9",
49
+ "Programming Language :: Python :: 3.10",
50
+ "Programming Language :: Python :: 3.11",
51
+ ],
52
+ keywords="voice activity vad",
53
+ )
@@ -0,0 +1,44 @@
1
+ import wave
2
+ from pathlib import Path
3
+ from typing import Union
4
+
5
+ import pytest
6
+ from pysilero_vad import SileroVoiceActivityDetector, InvalidChunkSizeError
7
+
8
+ _DIR = Path(__file__).parent
9
+
10
+
11
+ def _load_wav(wav_path: Union[str, Path]) -> bytes:
12
+ """Return audio bytes from a WAV file."""
13
+ with wave.open(str(wav_path), "rb") as wav_file:
14
+ assert wav_file.getframerate() == 16000
15
+ assert wav_file.getsampwidth() == 2
16
+ assert wav_file.getnchannels() == 1
17
+
18
+ return wav_file.readframes(wav_file.getnframes())
19
+
20
+
21
+ def test_silence() -> None:
22
+ """Test VAD on recorded silence."""
23
+ vad = SileroVoiceActivityDetector()
24
+ assert all(p < 0.5 for p in vad.process_chunks(_load_wav(_DIR / "silence.wav")))
25
+
26
+
27
+ def test_speech() -> None:
28
+ """Test VAD on recorded speech."""
29
+ vad = SileroVoiceActivityDetector()
30
+ assert any(p >= 0.5 for p in vad.process_chunks(_load_wav(_DIR / "speech.wav")))
31
+
32
+ def test_invalid_chunk_size() -> None:
33
+ """Test that chunk size must be 512 samples."""
34
+ vad = SileroVoiceActivityDetector()
35
+
36
+ # Should work
37
+ vad(bytes(SileroVoiceActivityDetector.chunk_bytes()))
38
+
39
+ # Should fail
40
+ with pytest.raises(InvalidChunkSizeError):
41
+ vad(bytes(SileroVoiceActivityDetector.chunk_bytes() * 2))
42
+
43
+ with pytest.raises(InvalidChunkSizeError):
44
+ vad(bytes(SileroVoiceActivityDetector.chunk_bytes() // 2))