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
|
||||
|
||||
# 提取該時間範圍內的音頻
|
||||
|
||||
Executable
+33
@@ -0,0 +1,33 @@
|
||||
#!/bin/bash
|
||||
# Check for relative paths in documentation
|
||||
|
||||
set -e
|
||||
|
||||
DOCS_DIR="/Users/accusys/momentry_core/docs_v1.0"
|
||||
|
||||
echo "=== Checking for Relative Paths in Documentation ==="
|
||||
echo ""
|
||||
|
||||
FOUND_ISSUES=0
|
||||
|
||||
# Find all markdown files
|
||||
while IFS= read -r -d '' file; do
|
||||
# Check for relative paths (src/, scripts/, .env, target/) that are not absolute
|
||||
RELATIVE=$(grep -n "src/\|scripts/\|\.env\|target/" "$file" 2>/dev/null | grep -v "/Users/accusys" | grep -v "node_modules" || true)
|
||||
|
||||
if [ -n "$RELATIVE" ]; then
|
||||
echo "❌ Relative paths found in: $file"
|
||||
echo "$RELATIVE"
|
||||
echo ""
|
||||
FOUND_ISSUES=1
|
||||
fi
|
||||
done < <(find "$DOCS_DIR" -name "*.md" -type f -print0)
|
||||
|
||||
if [ $FOUND_ISSUES -eq 0 ]; then
|
||||
echo "✅ All documents use absolute paths"
|
||||
else
|
||||
echo ""
|
||||
echo "⚠️ Please fix relative paths to use absolute paths"
|
||||
echo "Example: src/api/scan.rs → /Users/accusys/momentry_core/src/api/scan.rs"
|
||||
exit 1
|
||||
fi
|
||||
@@ -39,6 +39,7 @@ def embed(texts: list[str]) -> list[list[float]]:
|
||||
|
||||
@app.route("/v1/embeddings", methods=["POST"])
|
||||
def embeddings():
|
||||
start_time = time.time()
|
||||
data = request.get_json()
|
||||
texts = data.get("input", [])
|
||||
if isinstance(texts, str):
|
||||
@@ -46,10 +47,26 @@ def embeddings():
|
||||
if not texts:
|
||||
return jsonify({"error": "empty input"}), 400
|
||||
try:
|
||||
# Tokenize to get token count
|
||||
inputs = TOKENIZER(texts, padding=True, truncation=True, return_tensors="pt")
|
||||
total_tokens = inputs["input_ids"].shape[1] * len(texts)
|
||||
|
||||
# Generate embeddings
|
||||
emb = embed(texts)
|
||||
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
result = {
|
||||
"data": [{"embedding": e, "index": i} for i, e in enumerate(emb)],
|
||||
"model": "embeddinggemma-300m",
|
||||
"usage": {
|
||||
"prompt_tokens": total_tokens,
|
||||
"completion_tokens": 0,
|
||||
"total_tokens": total_tokens
|
||||
},
|
||||
"timings": {
|
||||
"duration_ms": duration_ms
|
||||
}
|
||||
}
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
|
||||
@@ -45,8 +45,33 @@ def run_sql(sql: str) -> str:
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def already_packed(file_uuid: str, phase: int) -> bool:
|
||||
"""Return True if a prior phase package already exists for this file_uuid
|
||||
(RELEASE_INFO.txt records the File UUID). Prevents re-packing on every
|
||||
job reprocess cycle, which filled the disk with duplicated timestamp dirs."""
|
||||
phase_dir = RELEASE_DIR / f"phase{phase}"
|
||||
if not phase_dir.is_dir():
|
||||
return False
|
||||
for pkg in phase_dir.iterdir():
|
||||
if not pkg.is_dir():
|
||||
continue
|
||||
info = pkg / "RELEASE_INFO.txt"
|
||||
if not info.is_file():
|
||||
continue
|
||||
try:
|
||||
content = info.read_text(errors="ignore")
|
||||
except OSError:
|
||||
continue
|
||||
if f"File UUID: {file_uuid}" in content and f"Phase: {phase}" in content:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def pack_phase(file_uuid: str, phase: int) -> Path:
|
||||
"""Package deliverables for phase 1 or 2."""
|
||||
if already_packed(file_uuid, phase):
|
||||
print(f"[RELEASE] Phase {phase} already packaged for {file_uuid}, skipping")
|
||||
return RELEASE_DIR / f"phase{phase}" / "latest"
|
||||
phase_dir = RELEASE_DIR / f"phase{phase}"
|
||||
stamp = ts()
|
||||
pkg_dir = phase_dir / f"{VERSION}_{stamp}"
|
||||
|
||||
Generated
+440
-2
@@ -169,6 +169,18 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bit_field"
|
||||
version = "0.10.3"
|
||||
@@ -208,12 +220,24 @@ version = "1.25.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder-lite"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.4.6"
|
||||
@@ -284,6 +308,22 @@ version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
@@ -324,6 +364,16 @@ version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"
|
||||
dependencies = [
|
||||
"pem-rfc7468",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.7"
|
||||
@@ -361,6 +411,16 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "exr"
|
||||
version = "1.74.2"
|
||||
@@ -378,6 +438,12 @@ dependencies = [
|
||||
"zune-inflate",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "fax"
|
||||
version = "0.2.7"
|
||||
@@ -410,6 +476,21 @@ dependencies = [
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
|
||||
dependencies = [
|
||||
"foreign-types-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types-shared"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
@@ -480,6 +561,34 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hmac-sha256"
|
||||
version = "1.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec9d92d097f4749b64e8cc33d924d9f40a2d4eb91402b458014b781f5733d60f"
|
||||
|
||||
[[package]]
|
||||
name = "hound"
|
||||
version = "3.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f"
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"itoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.3.0"
|
||||
@@ -694,6 +803,12 @@ version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.3"
|
||||
@@ -715,6 +830,22 @@ dependencies = [
|
||||
"imgref",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lzma-rust2"
|
||||
version = "0.15.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e20f57f9918e5bd7bc58c22cdd70a6afc7375d4dd9683af5f2b34bd3d2bba619"
|
||||
|
||||
[[package]]
|
||||
name = "matrixmultiply"
|
||||
version = "0.3.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"rawpointer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "maybe-rayon"
|
||||
version = "0.1.1"
|
||||
@@ -761,6 +892,38 @@ dependencies = [
|
||||
"pxfm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "native-tls"
|
||||
version = "0.2.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"openssl",
|
||||
"openssl-probe",
|
||||
"openssl-sys",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ndarray"
|
||||
version = "0.17.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d"
|
||||
dependencies = [
|
||||
"matrixmultiply",
|
||||
"num-complex",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
"portable-atomic",
|
||||
"portable-atomic-util",
|
||||
"rawpointer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "new_debug_unreachable"
|
||||
version = "1.0.6"
|
||||
@@ -863,6 +1026,73 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "openssl"
|
||||
version = "0.10.81"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cfg-if",
|
||||
"foreign-types",
|
||||
"libc",
|
||||
"openssl-macros",
|
||||
"openssl-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openssl-macros"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openssl-probe"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-sys"
|
||||
version = "0.9.117"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ort"
|
||||
version = "2.0.0-rc.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4336a1e2b38848325241c72889086886004e589b7c74f335e60a8e8db5138a0b"
|
||||
dependencies = [
|
||||
"ndarray",
|
||||
"ort-sys",
|
||||
"smallvec",
|
||||
"tracing",
|
||||
"ureq 3.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ort-sys"
|
||||
version = "2.0.0-rc.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf211e3776eea6aec988552fa118dd746d70e1b1e5e244058d1c98015f3e5872"
|
||||
dependencies = [
|
||||
"hmac-sha256",
|
||||
"lzma-rust2",
|
||||
"ureq 3.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
version = "1.0.15"
|
||||
@@ -875,12 +1105,33 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.18.1"
|
||||
@@ -894,6 +1145,21 @@ dependencies = [
|
||||
"miniz_oxide 0.8.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic-util"
|
||||
version = "0.2.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
|
||||
dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.6"
|
||||
@@ -1093,6 +1359,12 @@ dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rawpointer"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
|
||||
|
||||
[[package]]
|
||||
name = "rayon"
|
||||
version = "1.12.0"
|
||||
@@ -1143,11 +1415,29 @@ dependencies = [
|
||||
name = "rust_processors"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"hound",
|
||||
"image",
|
||||
"ndarray",
|
||||
"ort",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"ureq",
|
||||
"tempfile",
|
||||
"ureq 2.12.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1191,6 +1481,38 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "schannel"
|
||||
version = "0.1.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"core-foundation",
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
"security-framework-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework-sys"
|
||||
version = "2.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
@@ -1261,6 +1583,17 @@ version = "1.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
|
||||
|
||||
[[package]]
|
||||
name = "socks"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0c3dbbd9ae980613c6dd8e28a9407b50509d3803b57624d5dfe8315218cd58b"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"libc",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
@@ -1312,6 +1645,19 @@ dependencies = [
|
||||
"syn 3.0.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.20"
|
||||
@@ -1356,6 +1702,25 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"pin-project-lite",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.36"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
@@ -1374,7 +1739,7 @@ version = "2.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"flate2",
|
||||
"log",
|
||||
"once_cell",
|
||||
@@ -1386,6 +1751,36 @@ dependencies = [
|
||||
"webpki-roots 0.26.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ureq"
|
||||
version = "3.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"der",
|
||||
"log",
|
||||
"native-tls",
|
||||
"percent-encoding",
|
||||
"rustls-pki-types",
|
||||
"socks",
|
||||
"ureq-proto",
|
||||
"utf8-zero",
|
||||
"webpki-root-certs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ureq-proto"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "url"
|
||||
version = "2.5.8"
|
||||
@@ -1398,6 +1793,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf8-zero"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.0.4"
|
||||
@@ -1421,6 +1822,12 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
@@ -1487,6 +1894,15 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-root-certs"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "0.26.11"
|
||||
@@ -1511,6 +1927,28 @@ version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
|
||||
dependencies = [
|
||||
"winapi-i686-pc-windows-gnu",
|
||||
"winapi-x86_64-pc-windows-gnu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-i686-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-x86_64-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
|
||||
@@ -16,6 +16,10 @@ path = "src/bin/rust_pose.rs"
|
||||
name = "rust_face_cluster"
|
||||
path = "src/bin/rust_face_cluster.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_vad"
|
||||
path = "src/bin/rust_vad.rs"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
@@ -23,5 +27,14 @@ clap = { version = "4", features = ["derive"] }
|
||||
image = "0.25"
|
||||
ureq = { version = "2", features = ["json"] }
|
||||
|
||||
# VAD dependencies
|
||||
ort = { version = "2.0.0-rc.13", features = ["download-binaries"] }
|
||||
hound = "3.5"
|
||||
ndarray = "0.17"
|
||||
anyhow = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 2
|
||||
@@ -0,0 +1,140 @@
|
||||
use clap::Parser;
|
||||
use anyhow::Result;
|
||||
use serde_json::json;
|
||||
use std::time::Instant;
|
||||
|
||||
use rust_processors::vad::{SileroVad, AudioReader, SpeechSegment};
|
||||
use rust_processors::vad::segment::SegmentCollector;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_vad")]
|
||||
#[command(about = "Silero VAD ONNX (Rust implementation)")]
|
||||
struct Cli {
|
||||
/// Input audio file (WAV 16kHz mono)
|
||||
#[arg(short, long)]
|
||||
audio: String,
|
||||
|
||||
/// ONNX model path
|
||||
#[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")]
|
||||
model: String,
|
||||
|
||||
/// Speech probability threshold
|
||||
#[arg(long, default_value = "0.5")]
|
||||
threshold: f32,
|
||||
|
||||
/// Minimum speech duration (milliseconds)
|
||||
#[arg(long, default_value = "500")]
|
||||
min_speech: u32,
|
||||
|
||||
/// Minimum silence duration (milliseconds)
|
||||
#[arg(long, default_value = "300")]
|
||||
min_silence: u32,
|
||||
|
||||
/// Chunk size (samples)
|
||||
#[arg(long, default_value = "512")]
|
||||
chunk_size: usize,
|
||||
|
||||
/// Output format
|
||||
#[arg(long, default_value = "json")]
|
||||
format: String,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
println!("[VAD] Loading model: {}", cli.model);
|
||||
let start_load = Instant::now();
|
||||
let mut vad = SileroVad::new(&cli.model)?;
|
||||
println!("[VAD] Model loaded in {:.2}s", start_load.elapsed().as_secs_f32());
|
||||
|
||||
println!("[VAD] Loading audio: {}", cli.audio);
|
||||
let audio = AudioReader::from_wav(&cli.audio)?;
|
||||
let samples = audio.samples();
|
||||
let sample_rate = audio.sample_rate();
|
||||
let duration = audio.duration();
|
||||
|
||||
println!("[VAD] Audio: {} samples, {} Hz, {:.2}s",
|
||||
samples.len(), sample_rate, duration);
|
||||
|
||||
// 檢測語音
|
||||
println!("[VAD] Detecting speech...");
|
||||
let start_detect = Instant::now();
|
||||
|
||||
let mut collector = SegmentCollector::new(
|
||||
cli.threshold,
|
||||
cli.min_speech,
|
||||
cli.min_silence
|
||||
);
|
||||
|
||||
// 分塊處理
|
||||
for i in (0..samples.len()).step_by(cli.chunk_size) {
|
||||
let end = (i + cli.chunk_size).min(samples.len());
|
||||
let chunk = &samples[i..end];
|
||||
|
||||
// 如果塊太小,填充零
|
||||
let mut chunk_vec = chunk.to_vec();
|
||||
if chunk_vec.len() < cli.chunk_size {
|
||||
chunk_vec.resize(cli.chunk_size, 0.0);
|
||||
}
|
||||
|
||||
// 檢測
|
||||
let speech_prob = vad.detect(&chunk_vec)?;
|
||||
|
||||
// 時間戳
|
||||
let timestamp = i as f32 / sample_rate as f32;
|
||||
|
||||
// 收集片段
|
||||
collector.process(timestamp, speech_prob);
|
||||
}
|
||||
|
||||
// 結束處理
|
||||
let end_timestamp = samples.len() as f32 / sample_rate as f32;
|
||||
collector.finalize(end_timestamp);
|
||||
|
||||
let segments = collector.segments();
|
||||
let detect_time = start_detect.elapsed().as_secs_f32();
|
||||
|
||||
println!("[VAD] Detection completed in {:.2}s", detect_time);
|
||||
println!("[VAD] Found {} speech segments", segments.len());
|
||||
|
||||
// 計算統計
|
||||
let total_speech: f32 = segments.iter().map(|s| s.duration()).sum();
|
||||
let speech_ratio = total_speech / duration;
|
||||
|
||||
println!("[VAD] Total speech: {:.2}s ({:.1}%)", total_speech, speech_ratio * 100.0);
|
||||
println!("[VAD] Processing speed: {:.2}x real-time", duration / detect_time);
|
||||
|
||||
// 輸出結果
|
||||
match cli.format.as_str() {
|
||||
"json" => {
|
||||
let output = json!({
|
||||
"audio_file": cli.audio,
|
||||
"sample_rate": sample_rate,
|
||||
"duration": duration,
|
||||
"segments": segments.iter().map(|s| json!({
|
||||
"start": s.start_sec,
|
||||
"end": s.end_sec,
|
||||
"duration": s.duration()
|
||||
})).collect::<Vec<_>>(),
|
||||
"statistics": {
|
||||
"segment_count": segments.len(),
|
||||
"total_speech": total_speech,
|
||||
"speech_ratio": speech_ratio,
|
||||
"detect_time": detect_time
|
||||
}
|
||||
});
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
}
|
||||
"text" => {
|
||||
for seg in segments {
|
||||
println!("{:.2} - {:.2} ({:.2}s)",
|
||||
seg.start_sec, seg.end_sec, seg.duration());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
anyhow::bail!("Unknown output format: {}", cli.format);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod vad;
|
||||
@@ -0,0 +1,42 @@
|
||||
use anyhow::{Context, Result};
|
||||
use hound::WavReader;
|
||||
|
||||
pub struct AudioReader {
|
||||
samples: Vec<f32>,
|
||||
sample_rate: u32,
|
||||
}
|
||||
|
||||
impl AudioReader {
|
||||
pub fn from_wav(path: &str) -> Result<Self> {
|
||||
let reader = WavReader::open(path)
|
||||
.context("Failed to open WAV file")?;
|
||||
|
||||
let spec = reader.spec();
|
||||
let sample_rate = spec.sample_rate;
|
||||
|
||||
// 轉換為 f32,範圍 [-1.0, 1.0]
|
||||
let samples: Vec<f32> = reader.into_samples::<i16>()
|
||||
.map(|s| {
|
||||
s.map(|v| v as f32 / 32768.0)
|
||||
.unwrap_or(0.0)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Self {
|
||||
samples,
|
||||
sample_rate,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn samples(&self) -> &[f32] {
|
||||
&self.samples
|
||||
}
|
||||
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
pub fn duration(&self) -> f32 {
|
||||
self.samples.len() as f32 / self.sample_rate as f32
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod onnx;
|
||||
pub mod audio;
|
||||
pub mod segment;
|
||||
|
||||
pub use onnx::SileroVad;
|
||||
pub use audio::AudioReader;
|
||||
pub use segment::SpeechSegment;
|
||||
@@ -0,0 +1,100 @@
|
||||
use anyhow::{Context, Result};
|
||||
use ort::session::{Session, builder::GraphOptimizationLevel};
|
||||
use ort::value::Value;
|
||||
use ndarray::IxDyn;
|
||||
|
||||
pub struct SileroVad {
|
||||
session: Session,
|
||||
state: Vec<f32>, // [2, 1, 128] = 256 elements
|
||||
context: Vec<f32>, // [1, 64] for 16kHz
|
||||
sample_rate: i64,
|
||||
context_size: usize, // 64 for 16kHz, 32 for 8kHz
|
||||
}
|
||||
|
||||
impl SileroVad {
|
||||
pub fn new(model_path: &str) -> Result<Self> {
|
||||
let session = Session::builder()?
|
||||
.with_optimization_level(GraphOptimizationLevel::Level1)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to set optimization level: {}", e))?
|
||||
.commit_from_file(model_path)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to load model: {}", e))?;
|
||||
|
||||
let sample_rate = 16000;
|
||||
let context_size = if sample_rate == 16000 { 64 } else { 32 };
|
||||
|
||||
Ok(Self {
|
||||
session,
|
||||
state: vec![0.0; 256], // [2, 1, 128] = 256
|
||||
context: vec![0.0; context_size], // [1, 64]
|
||||
sample_rate,
|
||||
context_size,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn detect(&mut self, audio_chunk: &[f32]) -> Result<f32> {
|
||||
// 拼接 context 和當前塊
|
||||
let mut input_with_context = Vec::with_capacity(self.context_size + audio_chunk.len());
|
||||
input_with_context.extend_from_slice(&self.context);
|
||||
input_with_context.extend_from_slice(audio_chunk);
|
||||
|
||||
// 準備輸入
|
||||
let input_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[1, input_with_context.len()]),
|
||||
input_with_context.clone()
|
||||
).context("Failed to create input array")?;
|
||||
|
||||
let state_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[2, 1, 128]),
|
||||
self.state.clone()
|
||||
).context("Failed to create state array")?;
|
||||
|
||||
let sr_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[]), // 標量
|
||||
vec![self.sample_rate]
|
||||
).context("Failed to create sr array")?;
|
||||
|
||||
// 創建 ONNX Value
|
||||
let input_value = Value::from_array(input_array)
|
||||
.context("Failed to create input value")?;
|
||||
let state_value = Value::from_array(state_array)
|
||||
.context("Failed to create state value")?;
|
||||
let sr_value = Value::from_array(sr_array)
|
||||
.context("Failed to create sr value")?;
|
||||
|
||||
// 運行推理
|
||||
let inputs = ort::inputs![
|
||||
"input" => input_value,
|
||||
"state" => state_value,
|
||||
"sr" => sr_value,
|
||||
];
|
||||
|
||||
let outputs = self.session.run(inputs)
|
||||
.context("Failed to run inference")?;
|
||||
|
||||
// 提取輸出
|
||||
let output = outputs["output"].try_extract_tensor::<f32>()
|
||||
.context("Failed to extract output")?;
|
||||
|
||||
// output 是 (&Shape, &[f32]) tuple
|
||||
let output_data = output.1;
|
||||
let speech_prob = output_data[0];
|
||||
|
||||
// 更新隱藏狀態
|
||||
let state_n = outputs["stateN"].try_extract_tensor::<f32>()
|
||||
.context("Failed to extract stateN")?;
|
||||
|
||||
// state_n 是 (&Shape, &[f32]) tuple
|
||||
let state_data = state_n.1;
|
||||
self.state = state_data.to_vec();
|
||||
|
||||
// 更新 context(當前輸入的最後 context_size 個樣本)
|
||||
self.context = input_with_context[input_with_context.len() - self.context_size..].to_vec();
|
||||
|
||||
Ok(speech_prob)
|
||||
}
|
||||
|
||||
pub fn reset_state(&mut self) {
|
||||
self.state = vec![0.0; 256];
|
||||
self.context = vec![0.0; self.context_size];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SpeechSegment {
|
||||
pub start_sec: f32,
|
||||
pub end_sec: f32,
|
||||
}
|
||||
|
||||
impl SpeechSegment {
|
||||
pub fn new(start_sec: f32, end_sec: f32) -> Self {
|
||||
Self { start_sec, end_sec }
|
||||
}
|
||||
|
||||
pub fn duration(&self) -> f32 {
|
||||
self.end_sec - self.start_sec
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SegmentCollector {
|
||||
segments: Vec<SpeechSegment>,
|
||||
current_start: Option<f32>,
|
||||
threshold: f32,
|
||||
min_speech_duration: f32,
|
||||
min_silence_duration: f32,
|
||||
silence_start: Option<f32>,
|
||||
}
|
||||
|
||||
impl SegmentCollector {
|
||||
pub fn new(threshold: f32, min_speech_ms: u32, min_silence_ms: u32) -> Self {
|
||||
Self {
|
||||
segments: Vec::new(),
|
||||
current_start: None,
|
||||
threshold,
|
||||
min_speech_duration: min_speech_ms as f32 / 1000.0,
|
||||
min_silence_duration: min_silence_ms as f32 / 1000.0,
|
||||
silence_start: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn process(&mut self, timestamp: f32, speech_prob: f32) {
|
||||
if speech_prob >= self.threshold {
|
||||
// 語音
|
||||
if self.current_start.is_none() {
|
||||
self.current_start = Some(timestamp);
|
||||
}
|
||||
self.silence_start = None;
|
||||
} else {
|
||||
// 靜音
|
||||
if self.current_start.is_some() {
|
||||
if self.silence_start.is_none() {
|
||||
self.silence_start = Some(timestamp);
|
||||
}
|
||||
|
||||
// 檢查是否結束語音段
|
||||
if let Some(silence_start) = self.silence_start {
|
||||
let silence_duration = timestamp - silence_start;
|
||||
if silence_duration >= self.min_silence_duration {
|
||||
// 結束語音段
|
||||
if let Some(start) = self.current_start {
|
||||
let duration = silence_start - start;
|
||||
if duration >= self.min_speech_duration {
|
||||
self.segments.push(SpeechSegment::new(start, silence_start));
|
||||
}
|
||||
}
|
||||
self.current_start = None;
|
||||
self.silence_start = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finalize(&mut self, end_timestamp: f32) {
|
||||
// 處理最後一個段
|
||||
if let Some(start) = self.current_start {
|
||||
let duration = end_timestamp - start;
|
||||
if duration >= self.min_speech_duration {
|
||||
self.segments.push(SpeechSegment::new(start, end_timestamp));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn segments(&self) -> &[SpeechSegment] {
|
||||
&self.segments
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,40 @@ struct SwiftFace: ParsableCommand {
|
||||
}
|
||||
}
|
||||
|
||||
// Match face observation by bbox to extract faceprint (embedding)
|
||||
var embedding: [Float]? = nil
|
||||
if #available(macOS 14, *) {
|
||||
var matchCount = 0
|
||||
for faceObs in faceObservations {
|
||||
let fBB = faceObs.boundingBox
|
||||
let ix = max(bb.minX, fBB.origin.x)
|
||||
let iy = max(bb.minY, fBB.origin.y)
|
||||
let iw = min(bb.maxX, fBB.origin.x + fBB.width) - ix
|
||||
let ih = min(bb.maxY, fBB.origin.y + fBB.height) - iy
|
||||
if iw <= 0 || ih <= 0 { continue }
|
||||
let intersection = iw * ih
|
||||
let union = bb.width * bb.height + fBB.width * fBB.height - intersection
|
||||
if intersection / union > 0.5 {
|
||||
matchCount += 1
|
||||
// Try to extract faceprint
|
||||
if let fp = faceObs.value(forKey: "faceprint") as? NSObject {
|
||||
if let desc = fp.value(forKey: "descriptor") as? NSObject {
|
||||
if let elems = desc.value(forKey: "elements") as? [NSNumber] {
|
||||
embedding = elems.map { Float($0.doubleValue) }
|
||||
} else {
|
||||
print("[DEBUG] No elements in descriptor")
|
||||
}
|
||||
} else {
|
||||
print("[DEBUG] No descriptor in faceprint")
|
||||
}
|
||||
} else {
|
||||
print("[DEBUG] No faceprint in faceObs (frame \(frameNumber), match \(matchCount))")
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var faceData: [String: Any] = [
|
||||
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
|
||||
"width": faceW, "height": faceH],
|
||||
@@ -178,6 +212,11 @@ struct SwiftFace: ParsableCommand {
|
||||
"captureQuality": captureQ,
|
||||
]
|
||||
|
||||
// Add embedding if available
|
||||
if let emb = embedding {
|
||||
faceData["embedding"] = emb
|
||||
}
|
||||
|
||||
// Pose from landmark observation
|
||||
if let yaw = lmObs.yaw?.doubleValue,
|
||||
let roll = lmObs.roll?.doubleValue {
|
||||
|
||||
Executable
+83
@@ -0,0 +1,83 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Scene VLM Test Script
|
||||
# This script tests the Scene VLM functionality with a real video
|
||||
|
||||
set -e
|
||||
|
||||
echo "=== Scene VLM Test Script ==="
|
||||
|
||||
# Configuration
|
||||
UUID="3677f81d232e59f13453d737ceb582cb"
|
||||
VIDEO_NAME="Gamma Carry Saves the World..mp4"
|
||||
OUTPUT_DIR="/Users/accusys/momentry/output"
|
||||
|
||||
# Check if video is registered
|
||||
echo "1. Checking if video is registered..."
|
||||
if [ -f "$OUTPUT_DIR/$UUID.probe.json" ]; then
|
||||
echo " ✅ Video registered: $UUID"
|
||||
else
|
||||
echo " ❌ Video not registered: $UUID"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if CUT data exists
|
||||
echo "2. Checking if CUT data exists..."
|
||||
if [ -f "$OUTPUT_DIR/$UUID.cut.json" ]; then
|
||||
echo " ✅ CUT data exists"
|
||||
cut_count=$(python3 -c "import json; data=json.load(open('$OUTPUT_DIR/$UUID.cut.json')); print(len(data.get('scenes', [])))")
|
||||
echo " Scenes: $cut_count"
|
||||
else
|
||||
echo " ❌ No CUT data"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if scenes.json already exists
|
||||
echo "3. Checking if scenes.json already exists..."
|
||||
if [ -f "$OUTPUT_DIR/$UUID.scenes.json" ]; then
|
||||
echo " ⚠️ scenes.json already exists"
|
||||
echo " Do you want to re-generate? (y/n)"
|
||||
read -r answer
|
||||
if [ "$answer" != "y" ]; then
|
||||
echo " Skipping generation"
|
||||
exit 0
|
||||
fi
|
||||
echo " Removing old scenes.json and frames..."
|
||||
rm -f "$OUTPUT_DIR/$UUID.scenes.json"
|
||||
rm -rf "$OUTPUT_DIR/$UUID/scenes"
|
||||
fi
|
||||
|
||||
# Enable Scene VLM
|
||||
echo "4. Enabling Scene VLM..."
|
||||
export MOMENTRY_SCENE_VLM_ENABLED=true
|
||||
export MOMENTRY_SCENE_VLM_INTERVAL=10
|
||||
export MOMENTRY_SCENE_VLM_SAMPLES=10
|
||||
export MOMENTRY_SCENE_VLM_USE_CUTS=true
|
||||
export MOMENTRY_SCENE_VLM_MAX_WORKERS=10
|
||||
|
||||
echo " ✅ Scene VLM enabled"
|
||||
|
||||
# Run processor (this would normally be done by worker)
|
||||
echo "5. Testing Scene VLM processor..."
|
||||
echo " (This would normally be done by worker automatically)"
|
||||
|
||||
# Check if Rust binary exists
|
||||
if [ -f "target/debug/momentry" ]; then
|
||||
echo " Using debug binary..."
|
||||
BINARY="target/debug/momentry"
|
||||
elif [ -f "target/release/momentry" ]; then
|
||||
echo " Using release binary..."
|
||||
BINARY="target/release/momentry"
|
||||
else
|
||||
echo " ❌ No binary found, building..."
|
||||
cargo build --bin momentry
|
||||
BINARY="target/debug/momentry"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=== Test Complete ==="
|
||||
echo ""
|
||||
echo "To enable Scene VLM in production, set:"
|
||||
echo " export MOMENTRY_SCENE_VLM_ENABLED=true"
|
||||
echo ""
|
||||
echo "The worker will automatically run Scene VLM after CUT completes."
|
||||
Reference in New Issue
Block a user