feat: restructure tools directory

新結構:
- tools/script/ (Python 處理器腳本)
- tools/cli/ (Swift/Rust CLI 工具)

遷移內容:
- Python 腳本: ASR, Face, Pose, Cut, OCR, VLM, Embedding, Identity
- Swift CLI: 24 個 Swift 處理器和測試文件
- Rust CLI: Face Cluster, Appearance, Pose

保留向後兼容:
- 舊路徑 scripts/ 仍然存在
- 環境變數可配置新路徑

文檔:
- tools/README.md
- docs_v1.0/DESIGN/Tools_Directory_Restructure.md
This commit is contained in:
Accusys
2026-09-27 12:04:23 +08:00
parent db74b11e21
commit af028ab8f4
54 changed files with 15459 additions and 0 deletions
+42
View File
@@ -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
}
}
+7
View File
@@ -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;
+100
View File
@@ -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];
}
}
+86
View File
@@ -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
}
}