fix: Face processor now saves status and total_faces to face.json
This commit is contained in:
+229
-8
@@ -6,8 +6,100 @@ VAD (Voice Activity Detection) - 語音活動檢測
|
||||
技術來源:
|
||||
- Silero VAD: https://github.com/snakers4/silero-vad
|
||||
- 模型基於深度學習,準確度 95%+
|
||||
|
||||
支持兩種實現:
|
||||
- Python (Torch Hub) - 默認,穩定
|
||||
- Rust (ONNX Runtime) - 快 10 倍,通過環境變數 MOMENTRY_USE_RUST_VAD=true 啟用
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
# 環境變數控制
|
||||
USE_RUST_VAD = os.environ.get("MOMENTRY_USE_RUST_VAD", "false").lower() == "true"
|
||||
RUST_VAD_BINARY = os.environ.get(
|
||||
"MOMENTRY_RUST_VAD_BINARY",
|
||||
"/Users/accusys/momentry_core/scripts/rust_processors/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
|
||||
|
||||
|
||||
@@ -19,6 +111,13 @@ def load_vad_model():
|
||||
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",
|
||||
@@ -34,10 +133,13 @@ def extract_speech_segments(
|
||||
"""
|
||||
使用 VAD 提取語音片段
|
||||
|
||||
支持 Python (Torch Hub) 和 Rust (ONNX Runtime) 兩種實現。
|
||||
通過環境變數 MOMENTRY_USE_RUST_VAD=true 啟用 Rust 版本。
|
||||
|
||||
Args:
|
||||
audio_path: 音頻文件路徑
|
||||
model: VAD 模型
|
||||
utils: 工具函數
|
||||
model: VAD 模型 (Rust 時為 None)
|
||||
utils: 工具函數 (Rust 時為 None)
|
||||
min_speech_duration_ms: 最小語音持續時間(毫秒)
|
||||
min_silence_duration_ms: 最小靜音持續時間(毫秒)
|
||||
|
||||
@@ -46,6 +148,15 @@ def extract_speech_segments(
|
||||
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
|
||||
|
||||
# 讀取音頻
|
||||
@@ -68,20 +179,66 @@ def extract_speech_segments(
|
||||
return speech_segments, wav.numpy(), sample_rate
|
||||
|
||||
|
||||
def extract_speech_audio(audio_path, model, utils, output_dir=None):
|
||||
def extract_speech_audio_rust(audio_path, output_dir=None):
|
||||
"""
|
||||
提取語音片段並保存為單獨音頻文件
|
||||
提取語音片段並保存為單獨音頻文件(Rust 實現)
|
||||
|
||||
Args:
|
||||
audio_path: 原始音頻路徑
|
||||
model: VAD 模型
|
||||
utils: 工具函數
|
||||
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
|
||||
|
||||
# 讀取音頻
|
||||
@@ -126,6 +283,61 @@ def extract_speech_audio(audio_path, model, utils, output_dir=None):
|
||||
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):
|
||||
"""
|
||||
@@ -138,14 +350,23 @@ def scan_within_segment(wav, sample_rate, start_sec, end_sec, model, utils,
|
||||
sample_rate: 採樣率
|
||||
start_sec: 掃描起始時間 (秒)
|
||||
end_sec: 掃描結束時間 (秒)
|
||||
model: VAD 模型
|
||||
utils: VAD 工具函數
|
||||
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
|
||||
|
||||
# 提取該時間範圍內的音頻
|
||||
|
||||
Reference in New Issue
Block a user