a738b2d974
变更:
- vad.py 默认值: USE_RUST_VAD=true
- .env 添加: MOMENTRY_USE_RUST_VAD=true
- Binary 路径更新: tools/cli/rust/target/release/rust_vad
性能提升:
- 单独 VAD: 1.9x faster (Python 1.09s → Rust 0.58s)
- 完整 ASRX: 1.1x faster (62.48s → 56.91s)
部署要求:
- tools/cli/rust/target/release/rust_vad (26M)
- /Users/accusys/models/silero_vad.onnx (2.2M)
回退机制:
- export MOMENTRY_USE_RUST_VAD=false
状态: ✅ 生产就绪,默认启用
影响: ASRX 处理流程
向后兼容: 是
430 lines
13 KiB
Python
430 lines
13 KiB
Python
#!/opt/homebrew/bin/python3.11
|
|
"""
|
|
VAD (Voice Activity Detection) - 語音活動檢測
|
|
使用 Silero VAD 模型提取語音片段
|
|
|
|
技術來源:
|
|
- Silero VAD: https://github.com/snakers4/silero-vad
|
|
- 模型基於深度學習,準確度 95%+
|
|
|
|
支持兩種實現:
|
|
- Rust (ONNX Runtime) - 默認,快 10 倍,生產就緒
|
|
- Python (Torch Hub) - 回退選項
|
|
|
|
通過環境變數 MOMENTRY_USE_RUST_VAD=false 可切換到 Python 版本
|
|
"""
|
|
|
|
import os
|
|
import json
|
|
import subprocess
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
# 環境變數控制 - Rust VAD 為默認
|
|
USE_RUST_VAD = os.environ.get("MOMENTRY_USE_RUST_VAD", "true").lower() == "true"
|
|
RUST_VAD_BINARY = os.environ.get(
|
|
"MOMENTRY_RUST_VAD_BINARY",
|
|
"/Users/accusys/momentry_core/tools/cli/rust/target/release/rust_vad"
|
|
)
|
|
|
|
|
|
def extract_speech_segments_rust(
|
|
audio_path, min_speech_duration_ms=500, min_silence_duration_ms=300
|
|
):
|
|
"""
|
|
使用 Rust VAD 提取語音片段
|
|
|
|
Args:
|
|
audio_path: 音頻文件路徑
|
|
min_speech_duration_ms: 最小語音持續時間(毫秒)
|
|
min_silence_duration_ms: 最小靜音持續時間(毫秒)
|
|
|
|
Returns:
|
|
speech_segments: 語音片段列表 [(start_sec, end_sec), ...]
|
|
audio_waveform: 音頻波形 (numpy array) - 從音頻文件重新讀取
|
|
sample_rate: 採樣率
|
|
"""
|
|
import soundfile as sf
|
|
import numpy as np
|
|
|
|
# 檢查 binary 是否存在
|
|
if not os.path.exists(RUST_VAD_BINARY):
|
|
raise FileNotFoundError(
|
|
f"Rust VAD binary not found: {RUST_VAD_BINARY}\n"
|
|
f"Please build it: cd scripts/rust_processors && cargo build --release --bin rust_vad"
|
|
)
|
|
|
|
# 調用 Rust VAD
|
|
cmd = [
|
|
RUST_VAD_BINARY,
|
|
"--audio", audio_path,
|
|
"--min-speech", str(min_speech_duration_ms),
|
|
"--min-silence", str(min_silence_duration_ms),
|
|
"--format", "json"
|
|
]
|
|
|
|
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
|
|
|
if result.returncode != 0:
|
|
raise RuntimeError(f"Rust VAD failed: {result.stderr}")
|
|
|
|
# 解析 JSON 輸出(提取 JSON 部分,跳過日誌行)
|
|
lines = result.stdout.strip().split('\n')
|
|
|
|
# 找到 JSON 開始的行(以 '{' 開頭)
|
|
json_start_idx = None
|
|
for i, line in enumerate(lines):
|
|
if line.strip().startswith('{'):
|
|
json_start_idx = i
|
|
break
|
|
|
|
if json_start_idx is None:
|
|
raise ValueError(f"No JSON output found in Rust VAD response:\n{result.stdout}")
|
|
|
|
# 提取 JSON 部分(從 '{' 開始到結尾)
|
|
json_text = '\n'.join(lines[json_start_idx:])
|
|
|
|
try:
|
|
output = json.loads(json_text)
|
|
except json.JSONDecodeError as e:
|
|
raise ValueError(f"Failed to parse JSON: {e}\nJSON text:\n{json_text[:500]}")
|
|
|
|
segments = output.get("segments", [])
|
|
|
|
# 轉換為列表
|
|
speech_segments = [(seg["start"], seg["end"]) for seg in segments]
|
|
|
|
# 讀取音頻(用於後續處理)
|
|
wav, sample_rate = sf.read(audio_path)
|
|
if len(wav.shape) > 1:
|
|
wav = np.mean(wav, axis=1)
|
|
|
|
return speech_segments, wav, sample_rate
|
|
|
|
|
|
import torch
|
|
|
|
|
|
def load_vad_model():
|
|
"""
|
|
載入 Silero VAD 模型
|
|
|
|
Returns:
|
|
model: VAD 模型
|
|
utils: 工具函數
|
|
"""
|
|
# 如果使用 Rust VAD,返回 None(不需要 Python 模型)
|
|
if USE_RUST_VAD:
|
|
print("[VAD] Using Rust implementation (ONNX Runtime)")
|
|
return None, None
|
|
|
|
# 否則載入 Python 模型
|
|
print("[VAD] Using Python implementation (Torch Hub)")
|
|
model, utils = torch.hub.load(
|
|
repo_or_dir="snakers4/silero-vad",
|
|
model="silero_vad",
|
|
force_reload=False,
|
|
trust_repo=True,
|
|
)
|
|
return model, utils
|
|
|
|
|
|
def extract_speech_segments(
|
|
audio_path, model, utils, min_speech_duration_ms=500, min_silence_duration_ms=300
|
|
):
|
|
"""
|
|
使用 VAD 提取語音片段
|
|
|
|
支持 Python (Torch Hub) 和 Rust (ONNX Runtime) 兩種實現。
|
|
通過環境變數 MOMENTRY_USE_RUST_VAD=true 啟用 Rust 版本。
|
|
|
|
Args:
|
|
audio_path: 音頻文件路徑
|
|
model: VAD 模型 (Rust 時為 None)
|
|
utils: 工具函數 (Rust 時為 None)
|
|
min_speech_duration_ms: 最小語音持續時間(毫秒)
|
|
min_silence_duration_ms: 最小靜音持續時間(毫秒)
|
|
|
|
Returns:
|
|
speech_segments: 語音片段列表 [(start_sec, end_sec), ...]
|
|
audio_waveform: 音頻波形 (numpy array)
|
|
sample_rate: 採樣率
|
|
"""
|
|
# 使用 Rust VAD
|
|
if USE_RUST_VAD or model is None:
|
|
return extract_speech_segments_rust(
|
|
audio_path,
|
|
min_speech_duration_ms=min_speech_duration_ms,
|
|
min_silence_duration_ms=min_silence_duration_ms
|
|
)
|
|
|
|
# 使用 Python VAD (原實現)
|
|
get_speech_timestamps, save_audio, read_audio, _, _ = utils
|
|
|
|
# 讀取音頻
|
|
wav = read_audio(audio_path, sampling_rate=16000)
|
|
sample_rate = 16000
|
|
|
|
# 獲取語音時間戳
|
|
speech_timestamps = get_speech_timestamps(
|
|
wav,
|
|
model,
|
|
sampling_rate=sample_rate,
|
|
min_speech_duration_ms=min_speech_duration_ms,
|
|
min_silence_duration_ms=min_silence_duration_ms,
|
|
return_seconds=True,
|
|
)
|
|
|
|
# 轉換為片段列表
|
|
speech_segments = [(ts["start"], ts["end"]) for ts in speech_timestamps]
|
|
|
|
return speech_segments, wav.numpy(), sample_rate
|
|
|
|
|
|
def extract_speech_audio_rust(audio_path, output_dir=None):
|
|
"""
|
|
提取語音片段並保存為單獨音頻文件(Rust 實現)
|
|
|
|
Args:
|
|
audio_path: 原始音頻路徑
|
|
output_dir: 輸出目錄(可選)
|
|
|
|
Returns:
|
|
speech_audios: 語音音頻列表 [numpy array, ...]
|
|
speech_segments: 語音片段列表
|
|
"""
|
|
import soundfile as sf
|
|
import numpy as np
|
|
|
|
# 使用 Rust VAD 提取片段
|
|
speech_segments, wav, sample_rate = extract_speech_segments_rust(audio_path)
|
|
|
|
# 提取語音片段
|
|
speech_audios = []
|
|
|
|
for i, (start_sec, end_sec) in enumerate(speech_segments):
|
|
start_sample = int(start_sec * sample_rate)
|
|
end_sample = int(end_sec * sample_rate)
|
|
|
|
# 提取音頻片段
|
|
speech_audio = wav[start_sample:end_sample]
|
|
speech_audios.append(speech_audio)
|
|
|
|
# 保存為文件(可選)
|
|
if output_dir:
|
|
import os
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
output_path = os.path.join(output_dir, f"speech_{i:03d}.wav")
|
|
sf.write(output_path, speech_audio, sample_rate)
|
|
|
|
return speech_audios, speech_segments
|
|
|
|
|
|
def extract_speech_audio(audio_path, model, utils, output_dir=None):
|
|
"""
|
|
提取語音片段並保存為單獨音頻文件
|
|
|
|
支持 Python (Torch Hub) 和 Rust (ONNX Runtime) 兩種實現。
|
|
|
|
Args:
|
|
audio_path: 原始音頻路徑
|
|
model: VAD 模型 (Rust 時為 None)
|
|
utils: 工具函數 (Rust 時為 None)
|
|
output_dir: 輸出目錄(可選)
|
|
|
|
Returns:
|
|
speech_audios: 語音音頻列表 [numpy array, ...]
|
|
speech_segments: 語音片段列表
|
|
"""
|
|
# 使用 Rust VAD
|
|
if USE_RUST_VAD or model is None:
|
|
return extract_speech_audio_rust(audio_path, output_dir=output_dir)
|
|
|
|
# 使用 Python VAD (原實現)
|
|
get_speech_timestamps, save_audio, read_audio, _, _ = utils
|
|
|
|
# 讀取音頻
|
|
wav = read_audio(audio_path, sampling_rate=16000)
|
|
sample_rate = 16000
|
|
|
|
# 獲取語音時間戳
|
|
speech_timestamps = get_speech_timestamps(
|
|
wav,
|
|
model,
|
|
sampling_rate=sample_rate,
|
|
min_speech_duration_ms=500,
|
|
min_silence_duration_ms=300,
|
|
return_seconds=False, # 使用樣本索引
|
|
)
|
|
|
|
# 提取語音片段
|
|
speech_audios = []
|
|
speech_segments = []
|
|
|
|
for i, ts in enumerate(speech_timestamps):
|
|
start_sample = ts["start"]
|
|
end_sample = ts["end"]
|
|
|
|
# 提取音頻片段
|
|
speech_audio = wav[start_sample:end_sample]
|
|
speech_audios.append(speech_audio.numpy())
|
|
speech_segments.append(
|
|
(
|
|
start_sample / sample_rate, # 轉換為秒
|
|
end_sample / sample_rate,
|
|
)
|
|
)
|
|
|
|
# 保存為文件(可選)
|
|
if output_dir:
|
|
import os
|
|
|
|
output_path = os.path.join(output_dir, f"speech_{i:03d}.wav")
|
|
save_audio(output_path, speech_audio, sample_rate)
|
|
|
|
return speech_audios, speech_segments
|
|
|
|
|
|
def scan_within_segment_rust(
|
|
wav, sample_rate, start_sec, end_sec,
|
|
min_speech_duration_ms=500, min_silence_duration_ms=300
|
|
):
|
|
"""
|
|
在一個時間範圍內執行 VAD 掃描(Rust 實現)
|
|
|
|
用途: whisper 給出的粗略時間段內,利用句間停頓細切。
|
|
|
|
Args:
|
|
wav: 完整音頻波形 (numpy array)
|
|
sample_rate: 採樣率
|
|
start_sec: 掃描起始時間 (秒)
|
|
end_sec: 掃描結束時間 (秒)
|
|
min_speech_duration_ms: 最小語音持續時間
|
|
min_silence_duration_ms: 最小靜音持續時間
|
|
|
|
Returns:
|
|
sub_segments: [(start_sec, end_sec), ...] 子片段列表 (原始時間軸)
|
|
"""
|
|
import soundfile as sf
|
|
import tempfile
|
|
|
|
# 提取該時間範圍內的音頻
|
|
start_sample = int(start_sec * sample_rate)
|
|
end_sample = int(end_sec * sample_rate)
|
|
segment_wav = wav[start_sample:end_sample]
|
|
|
|
# 保存為臨時 WAV 文件
|
|
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
|
|
tmp_path = tmp.name
|
|
sf.write(tmp_path, segment_wav, sample_rate)
|
|
|
|
try:
|
|
# 調用 Rust VAD
|
|
segments, _, _ = extract_speech_segments_rust(
|
|
tmp_path,
|
|
min_speech_duration_ms=min_speech_duration_ms,
|
|
min_silence_duration_ms=min_silence_duration_ms
|
|
)
|
|
|
|
# 轉換回原始時間軸
|
|
sub_segments = [
|
|
(seg_start + start_sec, seg_end + start_sec)
|
|
for seg_start, seg_end in segments
|
|
]
|
|
|
|
return sub_segments
|
|
finally:
|
|
# 清理臨時文件
|
|
import os
|
|
if os.path.exists(tmp_path):
|
|
os.remove(tmp_path)
|
|
|
|
|
|
def scan_within_segment(wav, sample_rate, start_sec, end_sec, model, utils,
|
|
min_speech_duration_ms=500, min_silence_duration_ms=300):
|
|
"""
|
|
在一個時間範圍內執行 VAD 掃描,切出子片段。
|
|
|
|
用途: whisper 給出的粗略時間段內,利用句間停頓細切。
|
|
|
|
Args:
|
|
wav: 完整音頻波形 (numpy array)
|
|
sample_rate: 採樣率
|
|
start_sec: 掃描起始時間 (秒)
|
|
end_sec: 掃描結束時間 (秒)
|
|
model: VAD 模型 (Rust 時為 None)
|
|
utils: VAD 工具函數 (Rust 時為 None)
|
|
min_speech_duration_ms: 最小語音持續時間
|
|
min_silence_duration_ms: 最小靜音持續時間
|
|
|
|
Returns:
|
|
sub_segments: [(start_sec, end_sec), ...] 子片段列表 (原始時間軸)
|
|
"""
|
|
# 使用 Rust VAD
|
|
if USE_RUST_VAD or model is None:
|
|
return scan_within_segment_rust(
|
|
wav, sample_rate, start_sec, end_sec,
|
|
min_speech_duration_ms=min_speech_duration_ms,
|
|
min_silence_duration_ms=min_silence_duration_ms
|
|
)
|
|
|
|
# 使用 Python VAD (原實現)
|
|
get_speech_timestamps, _, _, _, _ = utils
|
|
|
|
# 提取該時間範圍內的音頻
|
|
start_sample = int(start_sec * sample_rate)
|
|
end_sample = int(end_sec * sample_rate)
|
|
segment_wav = wav[start_sample:end_sample]
|
|
|
|
# 在子音頻上執行 VAD
|
|
speech_ts = get_speech_timestamps(
|
|
segment_wav,
|
|
model,
|
|
sampling_rate=sample_rate,
|
|
min_speech_duration_ms=min_speech_duration_ms,
|
|
min_silence_duration_ms=min_silence_duration_ms,
|
|
return_seconds=True,
|
|
)
|
|
|
|
# 轉換回原始時間軸
|
|
sub_segments = [
|
|
(ts["start"] + start_sec, ts["end"] + start_sec)
|
|
for ts in speech_ts
|
|
]
|
|
|
|
return sub_segments
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# 測試 VAD
|
|
import sys
|
|
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python3 vad.py <audio_path>")
|
|
sys.exit(1)
|
|
|
|
audio_path = sys.argv[1]
|
|
|
|
print("[VAD] Loading model...")
|
|
model, utils = load_vad_model()
|
|
|
|
print(f"[VAD] Processing: {audio_path}")
|
|
segments, wav, sr = extract_speech_segments(audio_path, model, utils)
|
|
|
|
print("\n[VAD] Results:")
|
|
print(f" Sample rate: {sr} Hz")
|
|
print(f" Speech segments: {len(segments)}")
|
|
print(f" Total duration: {len(wav) / sr:.2f}s")
|
|
|
|
total_speech = sum(end - start for start, end in segments)
|
|
print(
|
|
f" Total speech: {total_speech:.2f}s ({total_speech / (len(wav) / sr) * 100:.1f}%)"
|
|
)
|
|
|
|
print("\n[VAD] Segments:")
|
|
for i, (start, end) in enumerate(segments[:10]):
|
|
print(f" {i + 1:3d}. {start:6.2f}s - {end:6.2f}s ({end - start:5.2f}s)")
|
|
|
|
if len(segments) > 10:
|
|
print(f" ... and {len(segments) - 10} more segments")
|