fix: Face processor now saves status and total_faces to face.json
This commit is contained in:
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user