feat: declarative pipeline config, non-blocking Scene VLM, rust_asrx

Consolidated snapshot (previously WIP in working tree).

- core/pipeline_config: new module loading config/pipeline_flows.json as the
  source of truth for stage execution mode (parallel/blocking) and dependencies
- worker/job_worker: dispatch Scene VLM to a background task when the stage is
  declared parallel, unblocking the worker poll loop; resolve processor
  dependencies from pipeline_flows.json (fallback to built-in)
- config/pipeline_flows.json: asrx depends on [cut, asr]
- scripts/fix_stuck_jobs: fix UTC timezone comparison, raise default threshold
  to 6h, skip jobs with recent processor activity
- rust_asrx: Rust speaker diarization CLI + processor wiring
- processor metadata helper; fast_face_clustering script; file_progress pipeline
  API; scan API; VAD updates
This commit is contained in:
Accusys
2026-10-15 13:01:12 +08:00
parent 667e279768
commit 882e31ab96
76 changed files with 10117 additions and 300 deletions
+138
View File
@@ -0,0 +1,138 @@
//! Speaker clustering: faithful port of `speaker_cluster_fixed.py`
//! (agglomerative average-linkage with cosine distance).
/// Cosine distance matrix `[n][n]` for L2-normalized embeddings.
/// `dist[i][j] = 1 - dot(e_i, e_j)`.
pub fn cosine_distances(embeddings: &[Vec<f32>]) -> Vec<Vec<f32>> {
let n = embeddings.len();
let mut d = vec![vec![0f32; n]; n];
for i in 0..n {
for j in (i + 1)..n {
let dot: f32 = embeddings[i]
.iter()
.zip(embeddings[j].iter())
.map(|(a, b)| a * b)
.sum();
let v = 1.0 - dot;
d[i][j] = v;
d[j][i] = v;
}
}
d
}
/// Port of `estimate_n_speakers_from_embeddings`; result clamped to `[2, max]`.
pub fn estimate_n_speakers(distances: &[Vec<f32>], max_speakers: usize) -> usize {
let n = distances.len();
if n < 2 {
return 2;
}
let sample = n.min(200);
let mut min_distances = Vec::with_capacity(sample);
for i in 0..sample {
let mut row = distances[i].clone();
row.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
if row.len() > 1 {
min_distances.push(row[1]);
}
}
if min_distances.is_empty() {
return 2;
}
let avg = min_distances.iter().sum::<f32>() / min_distances.len() as f32;
let threshold = avg * 1.5;
let m = min_distances.len();
let mut assigned = vec![false; m];
let mut n_speakers = 1usize;
for i in 0..m {
if assigned[i] {
continue;
}
n_speakers += 1;
for j in (i + 1)..m {
if assigned[j] {
continue;
}
let idx_i = if n > 200 { i * (n / 200) } else { i };
let idx_j = if n > 200 { j * (n / 200) } else { j };
if idx_i < n && idx_j < n && distances[idx_i][idx_j] < threshold {
assigned[j] = true;
}
}
}
n_speakers.clamp(2, max_speakers.max(2))
}
/// Agglomerative clustering (average linkage) using a precomputed distance
/// matrix, stopping at `k` clusters. Returns a label per point.
pub fn agglomerative(distances: &[Vec<f32>], k: usize) -> Vec<usize> {
let n = distances.len();
if n == 0 {
return Vec::new();
}
if k >= n {
return (0..n).collect();
}
let mut d = distances.to_vec();
let mut root: Vec<usize> = (0..n).collect(); // union-find representative
let mut active = vec![true; n];
let mut size = vec![1usize; n];
let mut remaining = n;
while remaining > k {
let mut best_i = 0;
let mut best_j = 1;
let mut best = f32::INFINITY;
for i in 0..n {
if !active[i] {
continue;
}
for j in (i + 1)..n {
if active[j] && d[i][j] < best {
best = d[i][j];
best_i = i;
best_j = j;
}
}
}
// Merge best_j into best_i (UPGMA average linkage update).
let (i, j) = (best_i, best_j);
let si = size[i] as f32;
let sj = size[j] as f32;
for x in 0..n {
if x == i || x == j || !active[x] {
continue;
}
let v = (si * d[i][x] + sj * d[j][x]) / (si + sj);
d[i][x] = v;
d[x][i] = v;
}
size[i] += size[j];
active[j] = false;
root[j] = i;
remaining -= 1;
}
let find = |root: &Vec<usize>, mut x: usize| -> usize {
while root[x] != x {
x = root[x];
}
x
};
let mut label_of: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
let mut labels = vec![0usize; n];
let mut next = 0usize;
for p in 0..n {
let r = find(&root, p);
let label = *label_of.entry(r).or_insert_with(|| {
let l = next;
next += 1;
l
});
labels[p] = label;
}
labels
}
+192
View File
@@ -0,0 +1,192 @@
//! Rust-native speaker diarization (ASRX) building blocks.
//!
//! - `Frontend`: speechbrain-compatible fbank frontend (framing, STFT via
//! rustfft, mel filterbank, log-dB, sentence mean-normalization).
//! - `Ecapa`: ECAPA-TDNN speaker-embedding network (ONNX, `feats -> embedding`).
pub mod cluster;
use anyhow::{Context, Result};
use ndarray::IxDyn;
use ort::session::{builder::GraphOptimizationLevel, Session};
use ort::value::Value;
use rustfft::num_complex::Complex;
use rustfft::FftPlanner;
pub const SAMPLE_RATE: usize = 16000;
pub const N_FFT: usize = 400;
pub const HOP_LENGTH: usize = 160;
pub const WIN_LENGTH: usize = 400;
pub const N_BINS: usize = N_FFT / 2 + 1; // 201
pub const N_MELS: usize = 80;
const PAD: usize = N_FFT / 2;
const AMIN: f32 = 1e-10;
const TOP_DB: f32 = 80.0;
const MULTIPLIER: f32 = 10.0;
/// speechbrain-compatible log-mel frontend.
pub struct Frontend {
window: Vec<f32>,
mel: Vec<f32>, // [N_BINS * N_MELS], row-major (freq-major)
planner: FftPlanner<f32>,
}
impl Frontend {
/// Load the hamming window (400 f32) and the mel matrix (201x80 f32).
pub fn new(window_path: &str, mel_path: &str) -> Result<Self> {
let window = read_f32_file(window_path)?;
if window.len() != WIN_LENGTH {
anyhow::bail!(
"window file has {} values, expected {}",
window.len(),
WIN_LENGTH
);
}
let mel = read_f32_file(mel_path)?;
if mel.len() != N_BINS * N_MELS {
anyhow::bail!(
"mel file has {} values, expected {}",
mel.len(),
N_BINS * N_MELS
);
}
Ok(Self {
window,
mel,
planner: FftPlanner::new(),
})
}
/// Compute log-mel features [n_frames, N_MELS] (flattened) for a waveform.
///
/// Mirrors speechbrain `Fbank` with `mean_var_norm(norm_type="sentence",
/// std_norm=False)`: center-padded framing, power spectrum, mel matmul,
/// amplitude-to-dB with top_db clipping, then per-utterance mean removal.
pub fn compute_feats(&mut self, samples: &[f32]) -> (Vec<f32>, usize) {
let n = samples.len();
if n == 0 {
return (Vec::new(), 0);
}
let n_frames = 1 + n / HOP_LENGTH;
let mut fbank = vec![0f32; n_frames * N_MELS];
let fft = self.planner.plan_fft_forward(N_FFT);
let mut buffer = vec![Complex::new(0f32, 0f32); N_FFT];
for t in 0..n_frames {
let base = t * HOP_LENGTH;
for k in 0..N_FFT {
let idx = base + k;
let s = if idx >= PAD {
let si = idx - PAD;
if si < n {
samples[si]
} else {
0.0
}
} else {
0.0
};
buffer[k] = Complex::new(s * self.window[k], 0.0);
}
fft.process(&mut buffer);
let row = &mut fbank[t * N_MELS..(t + 1) * N_MELS];
for m in 0..N_MELS {
let mut acc = 0.0f32;
for b in 0..N_BINS {
let p = buffer[b].re * buffer[b].re + buffer[b].im * buffer[b].im;
acc += self.mel[b * N_MELS + m] * p;
}
row[m] = acc;
}
}
// amplitude_to_DB: 10*log10(clamp(x, amin)) with db_multiplier = 0.
let mut db_max = f32::NEG_INFINITY;
for v in fbank.iter_mut() {
*v = MULTIPLIER * v.max(AMIN).log10();
if *v > db_max {
db_max = *v;
}
}
let floor = db_max - TOP_DB;
for v in fbank.iter_mut() {
if *v < floor {
*v = floor;
}
}
// sentence mean normalization (std_norm=False -> subtract mean only)
let mut mean = vec![0f32; N_MELS];
for t in 0..n_frames {
for m in 0..N_MELS {
mean[m] += fbank[t * N_MELS + m];
}
}
let inv = 1.0 / n_frames as f32;
for m in 0..N_MELS {
mean[m] *= inv;
}
for t in 0..n_frames {
for m in 0..N_MELS {
fbank[t * N_MELS + m] -= mean[m];
}
}
(fbank, n_frames)
}
}
/// ECAPA-TDNN speaker embedding network (ONNX).
pub struct Ecapa {
session: Session,
}
impl Ecapa {
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 ECAPA model: {}", e))?;
Ok(Self { session })
}
/// Run the embedding network on features [n_frames, N_MELS]; returns 192-d.
pub fn embed(&mut self, feats: &[f32], n_frames: usize) -> Result<Vec<f32>> {
let input = ndarray::Array::from_shape_vec(IxDyn(&[1, n_frames, N_MELS]), feats.to_vec())
.context("Failed to create ECAPA input array")?;
let input_value = Value::from_array(input).context("Failed to create input value")?;
let inputs = ort::inputs!["feats" => input_value];
let outputs = self.session.run(inputs).context("Failed to run ECAPA")?;
let out = outputs["embedding"]
.try_extract_tensor::<f32>()
.context("Failed to extract embedding")?;
Ok(out.1.to_vec())
}
}
fn read_f32_file(path: &str) -> Result<Vec<f32>> {
let bytes = std::fs::read(path).with_context(|| format!("Failed to read {}", path))?;
if bytes.len() % 4 != 0 {
anyhow::bail!("{} length not a multiple of 4", path);
}
let mut out = Vec::with_capacity(bytes.len() / 4);
for chunk in bytes.chunks_exact(4) {
out.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
}
Ok(out)
}
/// L2-normalize a vector in place.
pub fn l2_normalize(v: &mut [f32]) {
let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
if norm > 0.0 {
for x in v.iter_mut() {
*x /= norm;
}
}
}