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
+14
View File
@@ -22,6 +22,7 @@ pub fn admin_config_routes() -> Router<AppState> {
put(update_vlm_prompt),
)
.route("/api/v1/admin/config/reload", post(reload_config))
.route("/api/v1/admin/settings", get(get_settings))
}
pub async fn get_config(State(state): State<AppState>) -> Result<Json<Value>, StatusCode> {
@@ -88,3 +89,16 @@ pub async fn reload_config(State(state): State<AppState>) -> Result<Json<Value>,
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}
// Settings endpoint - alias for /admin/config for frontend compatibility
pub async fn get_settings(
State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
let config = state.admin_config_manager.get_full_config().await;
Ok(Json(serde_json::to_value(config).map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to serialize config: {}", e),
)
})?))
}
+1
View File
@@ -88,6 +88,7 @@ async fn login(
let body = serde_json::json!({
"success": true,
"token": jwt_token.clone(),
"jwt": jwt_token,
"api_key": DEMO_USER_API_KEY.clone(),
"user": {
+685
View File
@@ -0,0 +1,685 @@
//! Phase-based pipeline progress API (V2).
//!
//! Exposes two endpoints consumed by the Studio frontend:
//! GET /api/v1/pipeline/phases → phase config (from config/pipeline_flows.json)
//! GET /api/v1/file/:file_uuid/progress → per-phase / per-processor progress
//!
//! Progress is computed from Redis per-processor status + PostgreSQL
//! `processor_results`, then clamped with a per-file Redis high-water mark so a
//! phase never moves backwards during a run. The high-water mark is cleared by
//! the worker when a new job starts (see `job_worker.rs`).
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;
use axum::{
extract::{Path, State},
http::StatusCode,
response::Json,
routing::get,
Router,
};
use serde::{Deserialize, Serialize};
use sqlx::Row;
use super::types::AppState;
use crate::core::config::REDIS_KEY_PREFIX;
use crate::core::db::{schema, RedisClient};
// ── Config (config/pipeline_flows.json) ─────────────────────────────────────
#[derive(Debug, Clone, Deserialize)]
struct RawStage {
name: String,
#[serde(default)]
progress_weight: f64,
#[serde(default)]
dependencies: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, Default)]
struct RawFlow {
#[serde(default)]
stages: Vec<RawStage>,
}
#[derive(Debug, Clone, Deserialize)]
struct RawPhase {
#[serde(default)]
id: i64,
name: String,
#[serde(default)]
name_en: Option<String>,
#[serde(default)]
progress_weight: f64,
#[serde(default)]
processors: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, Default)]
struct RawConfig {
#[serde(default)]
phases: Vec<RawPhase>,
#[serde(default)]
flows: HashMap<String, RawFlow>,
}
#[derive(Debug, Clone)]
struct ProcDef {
name: String,
weight: f64,
depends_on: Vec<String>,
}
#[derive(Debug, Clone)]
struct PhaseDef {
key: String,
order: i64,
weight: f64,
processors: Vec<ProcDef>,
}
fn load_config() -> &'static RawConfig {
static CFG: OnceLock<RawConfig> = OnceLock::new();
CFG.get_or_init(|| {
let candidates = [
crate::core::path_utils::config_dir().join("pipeline_flows.json"),
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config/pipeline_flows.json"),
];
for path in candidates {
if let Ok(s) = std::fs::read_to_string(&path) {
if let Ok(cfg) = serde_json::from_str::<RawConfig>(&s) {
return cfg;
}
}
}
tracing::warn!("file_progress: pipeline_flows.json not found, using empty phase config");
RawConfig::default()
})
}
fn phase_defs() -> &'static Vec<PhaseDef> {
static DEFS: OnceLock<Vec<PhaseDef>> = OnceLock::new();
DEFS.get_or_init(|| build_phase_defs(load_config()))
}
fn build_phase_defs(cfg: &RawConfig) -> Vec<PhaseDef> {
let mut stage_meta: HashMap<String, (f64, Vec<String>)> = HashMap::new();
if let Some(flow) = cfg.flows.get("register") {
for s in &flow.stages {
stage_meta.insert(s.name.clone(), (s.progress_weight, s.dependencies.clone()));
}
}
let mut defs: Vec<PhaseDef> = cfg
.phases
.iter()
.enumerate()
.map(|(i, p)| {
let processors: Vec<ProcDef> = p
.processors
.iter()
.map(|name| {
let (w, deps) = stage_meta.get(name).cloned().unwrap_or((0.0, Vec::new()));
let weight = if w > 0.0 { w } else { 1.0 };
ProcDef {
name: name.clone(),
weight,
depends_on: deps,
}
})
.collect();
PhaseDef {
key: p.name_en.clone().unwrap_or_else(|| p.name.clone()),
order: if p.id != 0 { p.id } else { i as i64 + 1 },
weight: if p.progress_weight > 0.0 {
p.progress_weight
} else {
1.0
},
processors,
}
})
.collect();
defs.sort_by_key(|d| d.order);
defs
}
// ── Aggregation ─────────────────────────────────────────────────────────────
/// Resolved input for phase aggregation (one entry per processor).
#[derive(Debug, Clone)]
struct PhaseAggInput {
weight: f64,
applicable: bool,
status: String,
progress: f64,
}
/// Compute a phase's weighted progress (0..1) and status from its processors.
/// Only applicable processors contribute to the denominator; once the file is
/// completed the phase is forced to 1.0.
fn aggregate_phase(procs: &[PhaseAggInput], file_completed: bool) -> (f64, String) {
let mut total_weight = 0.0;
let mut weighted = 0.0;
let mut any_running = false;
let mut any_failed = false;
for p in procs {
match p.status.as_str() {
"running" | "processing" => any_running = true,
"failed" | "error" => any_failed = true,
_ => {}
}
if p.applicable {
total_weight += p.weight;
weighted += p.weight * p.progress;
}
}
let progress = if file_completed {
1.0
} else if total_weight > 0.0 {
(weighted / total_weight).clamp(0.0, 1.0)
} else {
0.0
};
let status = if progress >= 1.0 {
"completed"
} else if any_failed {
"failed"
} else if any_running || progress > 0.0 {
"running"
} else {
"pending"
};
(progress, status.to_string())
}
// ── Response types ──────────────────────────────────────────────────────────
#[derive(Debug, Serialize)]
struct PhaseProcessorResponse {
name: String,
weight: f64,
depends_on: Vec<String>,
}
#[derive(Debug, Serialize)]
struct PhaseConfigResponse {
name: String,
weight: f64,
processors: Vec<PhaseProcessorResponse>,
}
#[derive(Debug, Serialize)]
struct PhasesResponse {
phases: Vec<PhaseConfigResponse>,
}
#[derive(Debug, Serialize)]
struct ProcessorProgressDetail {
name: String,
status: String,
progress: f64,
}
#[derive(Debug, Serialize)]
struct PhaseProgressDetail {
status: String,
progress: f64,
processors: HashMap<String, ProcessorProgressDetail>,
}
#[derive(Debug, Serialize)]
struct FileProgressResponse {
file_uuid: String,
overall_progress: f64,
current_phase: Option<String>,
phases: HashMap<String, PhaseProgressDetail>,
}
// ── Routes ──────────────────────────────────────────────────────────────────
pub fn file_progress_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/pipeline/phases", get(get_pipeline_phases))
.route("/api/v1/file/:file_uuid/progress", get(get_file_progress))
}
/// Static phase configuration for the frontend.
async fn get_pipeline_phases() -> Json<PhasesResponse> {
let phases = phase_defs()
.iter()
.map(|p| PhaseConfigResponse {
name: p.key.clone(),
weight: p.weight,
processors: p
.processors
.iter()
.map(|pr| PhaseProcessorResponse {
name: pr.name.clone(),
weight: pr.weight,
depends_on: pr.depends_on.clone(),
})
.collect(),
})
.collect();
Json(PhasesResponse { phases })
}
/// Per-phase / per-processor progress for a file.
async fn get_file_progress(
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<FileProgressResponse>, StatusCode> {
let defs = phase_defs();
// 1. Video status + processing status
let videos_table = schema::table_name("videos");
let video_row = sqlx::query(&format!(
"SELECT COALESCE(status::text, '') AS status, \
COALESCE(processing_status::text, '') AS ps \
FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("file_progress video query failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let (video_status, status_phase, active_set) = match video_row {
Some(r) => {
let status: String = r.try_get("status").unwrap_or_default();
let ps: String = r.try_get("ps").unwrap_or_default();
let parsed = serde_json::from_str::<serde_json::Value>(&ps).ok();
let phase = parsed
.as_ref()
.and_then(|v| v.get("phase").and_then(|p| p.as_str()))
.unwrap_or_default()
.to_string();
let active: HashSet<String> = parsed
.as_ref()
.and_then(|v| v.get("active_processors").and_then(|a| a.as_array()))
.map(|arr| {
arr.iter()
.filter_map(|x| x.as_str())
.map(|s| s.to_lowercase())
.collect()
})
.unwrap_or_default();
(status, phase, active)
}
None => (String::new(), String::new(), HashSet::new()),
};
let file_completed = video_status == "completed" || status_phase == "COMPLETED";
// 2. PostgreSQL processor_results (latest status per processor)
let pr_table = schema::table_name("processor_results");
let pr_rows = sqlx::query(&format!(
"SELECT DISTINCT ON (processor) processor, status FROM {} \
WHERE uuid = $1 ORDER BY processor, id DESC",
pr_table
))
.bind(&file_uuid)
.fetch_all(state.db.pool())
.await
.unwrap_or_default();
let mut db_status: HashMap<String, String> = HashMap::new();
for r in &pr_rows {
let processor: String = r.try_get("processor").unwrap_or_default();
let status: String = r.try_get("status").unwrap_or_default();
db_status.insert(processor.to_lowercase(), status.to_lowercase());
}
// 3. Redis per-processor realtime status
let redis = RedisClient::new().ok();
let prefix = REDIS_KEY_PREFIX.as_str();
let mut redis_status: HashMap<String, (String, f64)> = HashMap::new();
if let Some(redis) = redis.as_ref() {
if let Ok(mut conn) = redis.get_conn().await {
for p in defs.iter().flat_map(|d| d.processors.iter()) {
if redis_status.contains_key(&p.name) {
continue;
}
let key = format!("{}job:{}:processor:{}", prefix, file_uuid, p.name);
let fields: HashMap<String, String> = redis::cmd("HGETALL")
.arg(&key)
.query_async(&mut conn)
.await
.unwrap_or_default();
if fields.is_empty() {
continue;
}
let status = fields
.get("status")
.map(|s| s.to_lowercase())
.unwrap_or_else(|| "pending".to_string());
let current: f64 = fields
.get("current")
.and_then(|v| v.parse().ok())
.unwrap_or(0.0);
let total: f64 = fields
.get("total")
.and_then(|v| v.parse().ok())
.unwrap_or(0.0);
let progress = if status == "completed" || status == "skipped" {
1.0
} else if total > 0.0 {
(current / total).clamp(0.0, 1.0)
} else {
0.0
};
redis_status.insert(p.name.clone(), (status, progress));
}
}
}
// 4. TKG progress (Redis :tkg key)
let mut tkg_status = ("pending".to_string(), 0.0_f64);
if let Some(redis) = redis.as_ref() {
if let Ok(mut conn) = redis.get_conn().await {
let key = format!("{}progress:{}:tkg", prefix, file_uuid);
let val: Option<String> = redis::cmd("GET")
.arg(&key)
.query_async(&mut conn)
.await
.ok();
if let Some(s) = val {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&s) {
let phase = v.get("phase").and_then(|p| p.as_str()).unwrap_or("");
let progress = v
.get("overall_progress")
.and_then(|p| p.as_f64())
.unwrap_or(0.0)
.clamp(0.0, 1.0);
let status = if phase == "completed" {
"completed"
} else if phase == "failed" {
"failed"
} else if progress > 0.0 {
"running"
} else {
"pending"
};
tkg_status = (status.to_string(), progress);
}
}
}
}
// 5. Assemble per-phase progress
let mut phases_out: HashMap<String, PhaseProgressDetail> = HashMap::new();
let mut ordered: Vec<(String, f64, String)> = Vec::new();
for def in defs.iter() {
let mut procs_out: HashMap<String, ProcessorProgressDetail> = HashMap::new();
let mut resolved: Vec<PhaseAggInput> = Vec::with_capacity(def.processors.len());
for p in def.processors.iter() {
let is_tkg = p.name == "tkg";
let has_signal = if is_tkg {
tkg_status.0 != "pending" || tkg_status.1 > 0.0
} else {
redis_status.contains_key(&p.name) || db_status.contains_key(&p.name)
};
// A processor counts toward the phase only when it is part of this
// job (active_processors) or has already produced a signal. This
// avoids a phase reporting 100% while sibling processors are still
// pending, and avoids stalling on processors that never run.
let applicable = file_completed || has_signal || active_set.contains(&p.name);
let (mut status, mut progress) = if is_tkg {
(tkg_status.0.clone(), tkg_status.1)
} else if let Some((s, pr)) = redis_status.get(&p.name) {
(s.clone(), *pr)
} else if let Some(s) = db_status.get(&p.name) {
let pr = if s == "completed" || s == "skipped" {
1.0
} else {
0.0
};
(s.clone(), pr)
} else {
("pending".to_string(), 0.0_f64)
};
if file_completed {
status = "completed".to_string();
progress = 1.0;
}
resolved.push(PhaseAggInput {
weight: p.weight,
applicable,
status: status.clone(),
progress,
});
let name = p.name.clone();
procs_out.insert(
name.clone(),
ProcessorProgressDetail {
name,
status,
progress,
},
);
}
let (phase_progress, phase_status) = aggregate_phase(&resolved, file_completed);
phases_out.insert(
def.key.clone(),
PhaseProgressDetail {
status: phase_status.clone(),
progress: phase_progress,
processors: procs_out,
},
);
ordered.push((def.key.clone(), phase_progress, phase_status));
}
// 6. Apply monotonic high-water mark (never regress within a run)
if let Some(redis) = redis.as_ref() {
if let Ok(mut conn) = redis.get_conn().await {
let hwm_key = format!("{}progress:{}:phase_hwm", prefix, file_uuid);
let stored: Option<String> = redis::cmd("GET")
.arg(&hwm_key)
.query_async(&mut conn)
.await
.ok();
let mut hwm: HashMap<String, f64> = stored
.and_then(|s| serde_json::from_str::<HashMap<String, f64>>(&s).ok())
.unwrap_or_default();
for (key, phase) in phases_out.iter_mut() {
let prev = hwm.get(key).copied().unwrap_or(0.0);
if prev > phase.progress {
phase.progress = prev;
}
if phase.progress >= 1.0 {
phase.status = "completed".to_string();
}
hwm.insert(key.clone(), phase.progress);
}
for entry in ordered.iter_mut() {
if let Some(phase) = phases_out.get(&entry.0) {
entry.1 = phase.progress;
entry.2 = phase.status.clone();
}
}
if let Ok(json) = serde_json::to_string(&hwm) {
let _: Result<(), _> = redis::cmd("SET")
.arg(&hwm_key)
.arg(&json)
.query_async(&mut conn)
.await;
}
}
}
// 7. Overall + current phase
let overall = ordered
.iter()
.map(|(key, progress, _)| {
let weight = defs
.iter()
.find(|d| d.key == *key)
.map(|d| d.weight)
.unwrap_or(0.0);
weight * progress
})
.sum::<f64>()
.clamp(0.0, 1.0);
let current_phase = ordered
.iter()
.find(|(_, progress, status)| *progress < 1.0 && status != "completed")
.map(|(key, _, _)| key.clone());
Ok(Json(FileProgressResponse {
file_uuid,
overall_progress: overall,
current_phase,
phases: phases_out,
}))
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_config() -> RawConfig {
let json = r#"{
"phases": [
{"id": 1, "name": "基础分析", "name_en": "Foundation", "progress_weight": 0.15, "processors": ["cut"]},
{"id": 2, "name": "核心处理", "name_en": "Core Processing", "progress_weight": 0.60, "processors": ["asr", "face", "ocr"]}
],
"flows": {
"register": {
"stages": [
{"name": "asr", "progress_weight": 0.35, "dependencies": []},
{"name": "face", "progress_weight": 0.35, "dependencies": []},
{"name": "ocr", "progress_weight": 0.30, "dependencies": []}
]
}
}
}"#;
serde_json::from_str(json).expect("sample config parses")
}
#[test]
fn builds_phases_sorted_with_weights() {
let defs = build_phase_defs(&sample_config());
assert_eq!(defs.len(), 2);
assert_eq!(defs[0].key, "Foundation");
assert_eq!(defs[1].key, "Core Processing");
let total: f64 = defs.iter().map(|d| d.weight).sum();
assert!((total - 0.75).abs() < 1e-9, "weights sum, got {total}");
}
#[test]
fn processor_weights_default_when_missing() {
let defs = build_phase_defs(&sample_config());
let core = &defs[1];
let asr = core.processors.iter().find(|p| p.name == "asr").unwrap();
assert!((asr.weight - 0.35).abs() < 1e-9);
let foundation = &defs[0];
assert_eq!(foundation.processors[0].name, "cut");
// "cut" has no stage meta → default weight 1.0
assert!((foundation.processors[0].weight - 1.0).abs() < 1e-9);
}
fn agg(weight: f64, applicable: bool, status: &str, progress: f64) -> PhaseAggInput {
PhaseAggInput {
weight,
applicable,
status: status.to_string(),
progress,
}
}
#[test]
fn phase_progress_is_weighted_over_applicable() {
// asr done (0.35), face half (0.35), ocr pending (0.30) — all applicable
let procs = vec![
agg(0.35, true, "completed", 1.0),
agg(0.35, true, "running", 0.5),
agg(0.30, true, "pending", 0.0),
];
let (progress, status) = aggregate_phase(&procs, false);
assert!((progress - 0.525).abs() < 1e-9, "got {progress}");
assert_eq!(status, "running");
}
#[test]
fn pending_siblings_prevent_premature_completion() {
// Only asr finished; face/ocr applicable but not started → not 100%
let procs = vec![
agg(0.35, true, "completed", 1.0),
agg(0.35, true, "pending", 0.0),
agg(0.30, true, "pending", 0.0),
];
let (progress, status) = aggregate_phase(&procs, false);
assert!((progress - 0.35).abs() < 1e-9, "got {progress}");
assert_eq!(status, "running");
}
#[test]
fn non_applicable_processors_are_ignored() {
// asr done+applicable; face/ocr not applicable (never ran)
let procs = vec![
agg(0.35, true, "completed", 1.0),
agg(0.35, false, "pending", 0.0),
agg(0.30, false, "pending", 0.0),
];
let (progress, status) = aggregate_phase(&procs, false);
assert!((progress - 1.0).abs() < 1e-9, "got {progress}");
assert_eq!(status, "completed");
}
#[test]
fn no_applicable_processors_is_pending() {
let procs = vec![
agg(0.35, false, "pending", 0.0),
agg(0.35, false, "pending", 0.0),
];
let (progress, status) = aggregate_phase(&procs, false);
assert_eq!(progress, 0.0);
assert_eq!(status, "pending");
}
#[test]
fn failure_marks_phase_failed() {
let procs = vec![
agg(0.5, true, "completed", 1.0),
agg(0.5, true, "failed", 0.0),
];
let (progress, status) = aggregate_phase(&procs, false);
assert!((progress - 0.5).abs() < 1e-9, "got {progress}");
assert_eq!(status, "failed");
}
#[test]
fn completed_file_forces_full_progress() {
let procs = vec![agg(0.35, true, "pending", 0.0)];
let (progress, status) = aggregate_phase(&procs, true);
assert_eq!(progress, 1.0);
assert_eq!(status, "completed");
}
}
+78 -34
View File
@@ -121,6 +121,7 @@ async fn list_files(
total_chunks: chunk_count,
file_size: None,
modified_time: None,
thumbnail_url: None,
}]
} else {
vec![]
@@ -149,21 +150,7 @@ async fn list_files(
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("MarkBase API parse error: {}", e)))?;
let mut all_files: Vec<FileItem> = Vec::new();
// Convert MarkBase files to FileItem
for mb_file in markbase_files {
all_files.push(FileItem {
file_uuid: mb_file.file_uuid.unwrap_or_default(),
file_name: mb_file.name,
file_path: mb_file.file_path.unwrap_or_default(),
status: "unregistered".to_string(),
is_registered: false,
total_chunks: 0,
file_size: Some(mb_file.size),
modified_time: Some(mb_file.modified),
});
}
// Get registered files from database
let table = crate::core::db::schema::table_name("videos");
let registered: Vec<(String, String, String, String, Option<i64>, Option<String>)> = sqlx::query_as(&format!(
@@ -173,28 +160,73 @@ async fn list_files(
.fetch_all(state.db.pool())
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
// Build registered map
let registered_map: std::collections::HashMap<String, (String, String, String, Option<i64>, Option<String>)> = registered
.into_iter()
.map(|(uuid, name, path, status, size, mtime)| (path, (uuid, name, status, size, mtime)))
.collect();
// Merge: update registration status for matching files
for file in &mut all_files {
if let Some((uuid, name, status, size, mtime)) = registered_map.get(&file.file_path) {
file.file_uuid = uuid.clone();
file.status = status.clone();
file.is_registered = status != "pending";
file.file_size = size.map(|s| s as u64);
file.modified_time = mtime.clone();
// Build registered lookup maps by path and by name.
// MarkBase only returns name/size/modified (no path), so name is the reliable key.
let mut registered_by_path: std::collections::HashMap<String, (String, String, String, Option<i64>, Option<String>)> =
std::collections::HashMap::new();
let mut registered_by_name: std::collections::HashMap<String, (String, String, String, Option<i64>, Option<String>)> =
std::collections::HashMap::new();
for (uuid, name, path, status, size, mtime) in registered {
registered_by_path.insert(
path.clone(),
(uuid.clone(), path.clone(), status.clone(), size, mtime.clone()),
);
registered_by_name.insert(name, (uuid, path, status, size, mtime));
}
// Convert MarkBase files to FileItem, merging registration info by path or name
for mb_file in markbase_files {
// Skip hidden/system files
let name_lower = mb_file.name.to_lowercase();
if name_lower == ".ds_store" || name_lower.ends_with(".sqlite") {
continue;
}
let name = mb_file.name;
let mb_path = mb_file.file_path.clone().unwrap_or_default();
let matched = if !mb_path.is_empty() {
registered_by_path.get(&mb_path)
} else {
registered_by_name.get(&name)
};
if let Some((uuid, path, status, size, mtime)) = matched {
all_files.push(FileItem {
file_uuid: uuid.clone(),
file_name: name,
file_path: path.clone(),
status: status.clone(),
is_registered: status != "pending",
total_chunks: 0,
file_size: size.map(|s| s as u64),
modified_time: mtime.clone(),
thumbnail_url: None,
});
} else {
// Not registered: synthesize a path so the client can still preview it
let synth_path = std::env::var("MOMENTRY_SFTP_ROOT")
.ok()
.map(|root| format!("{}/{}", root.trim_end_matches('/'), name))
.unwrap_or_default();
all_files.push(FileItem {
file_uuid: mb_file.file_uuid.unwrap_or_default(),
file_name: name,
file_path: synth_path,
status: "unregistered".to_string(),
is_registered: false,
total_chunks: 0,
file_size: Some(mb_file.size),
modified_time: Some(mb_file.modified),
thumbnail_url: None,
});
}
}
// Add files that are in database but not in MarkBase (registered but moved/deleted)
let all_paths: std::collections::HashSet<String> = all_files.iter().map(|f| f.file_path.clone()).collect();
for (path, (uuid, name, status, size, mtime)) in &registered_map {
if !all_paths.contains(path) {
let all_names: std::collections::HashSet<String> = all_files.iter().map(|f| f.file_name.clone()).collect();
for (name, (uuid, path, status, size, mtime)) in &registered_by_name {
if !all_names.contains(name) && !all_paths.contains(path) {
all_files.push(FileItem {
file_uuid: uuid.clone(),
file_name: name.clone(),
@@ -204,10 +236,20 @@ async fn list_files(
total_chunks: 0,
file_size: size.map(|s| s as u64),
modified_time: mtime.clone(),
thumbnail_url: None,
});
}
}
// Add thumbnail URLs for all video files
for file in &mut all_files {
let path_lower = file.file_path.to_lowercase();
if path_lower.ends_with(".mp4") || path_lower.ends_with(".mov") || path_lower.ends_with(".avi") || path_lower.ends_with(".mkv") {
file.thumbnail_url = Some(format!("/api/v1/file/thumbnail?path={}&frame=0", urlencoding::encode(&file.file_path)));
}
}
let total = all_files.len() as i64;
// Apply pagination
@@ -287,6 +329,8 @@ pub struct FileItem {
pub file_size: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub modified_time: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_url: Option<String>,
}
#[derive(Debug, Serialize)]
+20 -4
View File
@@ -6,6 +6,7 @@ use axum::{
};
use sha2::{Digest, Sha256};
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tokio::sync::Semaphore;
use crate::core::auth::jwt;
@@ -45,7 +46,9 @@ pub struct ApiState {
/// handshake rate and the kernel starts RST-ing connections.
static REQUEST_PERMITS: OnceLock<Arc<Semaphore>> = OnceLock::new();
const REQUEST_CONCURRENCY_DEFAULT: usize = 40;
const REQUEST_CONCURRENCY_DEFAULT: usize = 256;
/// How long a request waits for a free slot before being rejected with 429.
const REQUEST_WAIT_TIMEOUT: Duration = Duration::from_secs(10);
fn request_semaphore() -> &'static Arc<Semaphore> {
REQUEST_PERMITS.get_or_init(|| {
@@ -68,10 +71,23 @@ pub async fn concurrency_limit(request: Request, next: Next) -> Response {
return next.run(request).await;
}
let permit = match request_semaphore().clone().try_acquire_owned() {
Ok(p) => p,
let permit = match tokio::time::timeout(
REQUEST_WAIT_TIMEOUT,
request_semaphore().clone().acquire_owned(),
)
.await
{
Ok(Ok(p)) => p,
Ok(Err(_)) => {
tracing::error!("[Concurrency] semaphore closed {} {}", request.method(), path);
return (
StatusCode::SERVICE_UNAVAILABLE,
"server busy: limiter unavailable",
)
.into_response();
}
Err(_) => {
tracing::warn!("[Concurrency] rejected {} {} (429)", request.method(), path);
tracing::warn!("[Concurrency] wait timeout {} {} (429)", request.method(), path);
return (
StatusCode::TOO_MANY_REQUESTS,
[("retry-after", "1")],
+1
View File
@@ -7,6 +7,7 @@ pub mod checkin_api;
pub mod cluster_agent;
pub mod docs;
pub mod face_filter;
pub mod file_progress;
pub mod files;
pub mod health;
pub mod identities;
+6 -4
View File
@@ -854,10 +854,12 @@ async fn get_processor_counts(
.map(|v| v as u32);
}
segment_count = json
.get("segments")
.and_then(|v| v.as_array())
.map(|arr| arr.len() as u32);
if proc_name != "scene" {
segment_count = json
.get("segments")
.and_then(|v| v.as_array())
.map(|arr| arr.len() as u32);
}
chunk_count = json
.get("child_chunks")
.and_then(|v| v.as_array())
+113
View File
@@ -1317,6 +1317,7 @@ pub fn scan_routes() -> Router<AppState> {
get(get_ingestion_status),
)
.route("/api/v1/stats/file/:file_uuid", get(get_file_stats))
.route("/api/v1/file/:file_uuid/scene-vlm-stats", get(get_scene_vlm_stats))
.route(
"/api/v1/stats/pipeline/:file_uuid",
get(get_pipeline_progress_handler),
@@ -1517,6 +1518,62 @@ async fn get_pipeline_progress_handler(
},
);
// Check scene_vlm progress from scenes.json
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
if std::path::Path::new(&scenes_path).exists() {
if let Ok(scenes_json) = std::fs::read_to_string(&scenes_path) {
if let Ok(scenes_data) = serde_json::from_str::<serde_json::Value>(&scenes_json) {
let total_scenes = scenes_data
.get("total_scenes")
.and_then(|v| v.as_i64())
.unwrap_or(0) as i64;
let vlm_done = scenes_data
.get("scenes")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter(|s| {
let status = s.get("vlm_status").and_then(|v| v.as_str());
status == Some("completed") || status == Some("done")
})
.count() as i64
})
.unwrap_or(0);
let scene_vlm_status = if total_scenes == 0 {
"completed"
} else if vlm_done == total_scenes {
"completed"
} else if vlm_done > 0 {
"running"
} else {
"pending"
};
let scene_vlm_progress = if total_scenes == 0 {
1.0
} else if vlm_done > 0 {
vlm_done as f64 / total_scenes as f64
} else {
0.0
};
pp.update_stage(
"scene_vlm",
scene_vlm_progress,
scene_vlm_status,
if total_scenes == 0 {
Some("no scenes".to_string())
} else {
Some(format!("{}/{}", vlm_done, total_scenes))
},
);
}
}
}
// Check face dedup from actual face_cluster.json content
// Always check if processors_done, regardless of tkg_node_count (A-10 fix)
if processors_done {
@@ -1585,3 +1642,59 @@ async fn get_pipeline_progress_handler(
Ok(Json(pp))
}
/// Quick scene VLM stats endpoint (fast, no Qdrant queries)
async fn get_scene_vlm_stats(
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<SceneVlmStats>, StatusCode> {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
if !std::path::Path::new(&scenes_path).exists() {
return Ok(Json(SceneVlmStats::default()));
}
let scenes_json = std::fs::read_to_string(&scenes_path)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let scenes_data: serde_json::Value = serde_json::from_str(&scenes_json)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let total_scenes = scenes_data
.get("total_scenes")
.and_then(|v| v.as_i64())
.unwrap_or(0);
let status = scenes_data
.get("status")
.and_then(|v| v.as_str())
.unwrap_or("pending")
.to_string();
let scenes_array = scenes_data
.get("scenes")
.and_then(|v| v.as_array())
.map(|arr| arr.len() as i64)
.unwrap_or(0);
let vlm_done = scenes_data
.get("scenes")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter(|s| {
let vlm_status = s.get("vlm_status").and_then(|v| v.as_str());
vlm_status == Some("completed") || vlm_status == Some("done")
})
.count() as i64
})
.unwrap_or(0);
Ok(Json(SceneVlmStats {
total_scenes: total_scenes.max(scenes_array),
status,
vlm_done,
vlm_total: total_scenes.max(scenes_array),
}))
}
+2
View File
@@ -18,6 +18,7 @@ use super::checkin_api;
use super::cluster_agent;
use super::docs;
use super::face_filter;
use super::file_progress;
use super::files;
use super::health;
use super::health::{health, health_consistency, health_detailed, health_queue};
@@ -138,6 +139,7 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
.merge(agent_api::agent_routes())
.merge(agent_search::agent_search_routes())
.merge(processing::processing_routes())
.merge(file_progress::file_progress_routes())
.merge(media_api::bbox_routes())
.merge(media_api::media_proxy_routes())
.merge(media_api::pose_appearance_routes())
+75
View File
@@ -5,6 +5,77 @@ use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::error;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PipelineFlow {
pub name: String,
pub description: String,
pub version: String,
#[serde(default)]
pub enabled: bool,
pub stages: Vec<PipelineStage>,
#[serde(skip_serializing_if = "Option::is_none")]
pub dependencies: Option<Vec<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineStage {
pub name: String,
pub processor_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default)]
pub required: bool,
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub timeout_secs: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool: Option<ToolSelection>,
#[serde(skip_serializing_if = "Option::is_none")]
pub condition: Option<StageCondition>,
#[serde(skip_serializing_if = "Option::is_none")]
pub on_failure: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Map<String, serde_json::Value>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolSelection {
pub name: String,
pub priority: u8,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default)]
pub parameters: serde_json::Map<String, serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub usage_notes: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StageCondition {
#[serde(skip_serializing_if = "Option::is_none")]
pub depends_on: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub skip_if_exists: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub run_if_missing: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PipelineConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default = "default_max_concurrent_stages")]
pub max_concurrent_stages: u32,
#[serde(default)]
pub default_timeout_secs: u32,
pub flows: HashMap<String, PipelineFlow>,
}
fn default_max_concurrent_stages() -> u32 {
3
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct VlmPrompt {
#[serde(skip_serializing_if = "Option::is_none")]
@@ -381,6 +452,8 @@ pub struct AdminConfig {
pub admin_settings: AdminSettings,
#[serde(default)]
pub search: SearchConfig,
#[serde(default)]
pub pipeline: PipelineConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -407,6 +480,8 @@ pub struct PartialAdminConfig {
pub admin_settings: Option<AdminSettings>,
#[serde(skip_serializing_if = "Option::is_none")]
pub search: Option<SearchConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pipeline: Option<PipelineConfig>,
}
pub struct AdminConfigManager {
+1
View File
@@ -684,6 +684,7 @@ impl ProcessorType {
ProcessorType::Ocr,
ProcessorType::Face,
ProcessorType::FaceCluster,
ProcessorType::Scene, // Scene VLM processor
// ProcessorType::Pose, // Disabled in production pipeline
// ProcessorType::Hand, // Disabled in production pipeline
// ProcessorType::Appearance, // Disabled in production pipeline
+10
View File
@@ -746,6 +746,8 @@ pub fn count_face_artifacts(output_dir: &str, file_uuid: &str) -> FaceArtifactsC
pub struct SceneProfile {
pub version: String,
pub file_uuid: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub processor: Option<crate::core::processor::ProcessorInfo>,
pub status: SceneStatus,
pub video_info: VideoInfo,
pub config: SceneConfig,
@@ -885,9 +887,17 @@ pub struct SceneAttributes {
impl SceneProfile {
pub fn new(file_uuid: &str, video_info: VideoInfo, config: SceneConfig) -> Self {
use crate::core::processor::{ProcessorInfo, PROCESSOR_VERSION};
Self {
version: "1.0".to_string(),
file_uuid: file_uuid.to_string(),
processor: Some(ProcessorInfo {
name: "scene_vlm".to_string(),
tool: "ffmpeg_scene_detect".to_string(),
version: PROCESSOR_VERSION.to_string(),
config: Some(serde_json::to_value(&config).unwrap_or(serde_json::json!({}))),
}),
status: SceneStatus::Pending,
video_info,
config,
+60
View File
@@ -0,0 +1,60 @@
use serde::{ser::Serializer, Serialize};
use std::io::{self, Write};
pub struct RoundedFloatFormatter {
decimals: usize,
}
impl RoundedFloatFormatter {
pub fn new(decimals: usize) -> Self {
Self { decimals }
}
}
impl serde_json::ser::Formatter for RoundedFloatFormatter {
fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> io::Result<()>
where
W: ?Sized + io::Write,
{
let rounded = if self.decimals == 0 {
value.round()
} else {
let factor = 10_f64.powi(self.decimals as i32);
(value * factor).round() / factor
};
write!(writer, "{:.1$}", rounded, self.decimals)
}
fn write_f32<W>(&mut self, writer: &mut W, value: f32) -> io::Result<()>
where
W: ?Sized + io::Write,
{
let rounded = if self.decimals == 0 {
f64::from(value).round() as f32
} else {
let factor = 10_f32.powi(self.decimals as i32);
(value * factor).round() / factor
};
write!(writer, "{:.1$}", rounded, self.decimals)
}
}
pub fn to_string_pretty_rounded<T: Serialize>(value: &T, decimals: usize) -> serde_json::Result<String> {
let mut buf = Vec::new();
let formatter = RoundedFloatFormatter::new(decimals);
let mut ser = serde_json::Serializer::with_formatter(&mut buf, formatter);
value.serialize(&mut ser)?;
String::from_utf8(buf)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
.map_err(|e| serde_json::Error::io(e))
}
pub fn write_file_pretty_rounded<T: Serialize>(
value: &T,
path: &str,
decimals: usize,
) -> anyhow::Result<()> {
let json = to_string_pretty_rounded(value, decimals)?;
std::fs::write(path, json)?;
Ok(())
}
+2
View File
@@ -18,11 +18,13 @@ pub mod health_agent;
pub mod identity;
pub mod init;
pub mod ingestion;
pub mod json_formatter;
pub mod llm;
pub mod overlay;
pub mod path_utils;
pub mod person_identity;
pub mod pipeline;
pub mod pipeline_config;
pub mod probe;
pub mod processor;
pub mod progress;
+178
View File
@@ -0,0 +1,178 @@
//! Declarative pipeline flow configuration (`config/pipeline_flows.json`).
//!
//! This module is the single source of truth for *how* the worker executes each
//! pipeline stage. In particular, the `parallel` flag on a stage declares whether
//! that stage runs in the background (non-blocking) or sequentially (the caller
//! waits for it to finish). The worker reads `parallel` from here instead of
//! hardcoding the execution mode per stage.
//!
//! Example: the `scene` stage (Scene VLM) is declared `"parallel": true`, so the
//! worker dispatches it to a background task rather than awaiting it inline in the
//! poll loop.
//!
//! Loaded once and cached. Edit `config/pipeline_flows.json` and restart the worker
//! to apply changes.
use std::collections::HashMap;
use std::sync::OnceLock;
use serde::Deserialize;
fn default_true() -> bool {
true
}
/// A single stage within a flow (one processor).
#[derive(Debug, Clone, Deserialize)]
pub struct Stage {
pub name: String,
#[serde(default)]
pub processor_type: String,
/// `true` = may run concurrently / dispatched to a background task (non-blocking).
/// `false` = sequential, the caller waits for completion.
#[serde(default = "default_true")]
pub parallel: bool,
#[serde(default)]
pub dependencies: Vec<String>,
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub timeout_secs: u64,
}
/// An ordered collection of stages (e.g. the `register` flow).
#[derive(Debug, Clone, Deserialize, Default)]
pub struct Flow {
#[serde(default)]
pub name: String,
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub stages: Vec<Stage>,
}
/// A phase grouping (used for the progress UI and concurrency ceilings).
#[derive(Debug, Clone, Deserialize, Default)]
pub struct Phase {
#[serde(default)]
pub id: i64,
#[serde(default)]
pub name_en: Option<String>,
#[serde(default)]
pub parallel_strategy: String,
#[serde(default)]
pub max_concurrent: Option<u32>,
#[serde(default)]
pub processors: Vec<String>,
}
/// Root of `config/pipeline_flows.json`.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct PipelineFlows {
#[serde(default)]
pub version: String,
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub max_concurrent_stages: u32,
#[serde(default)]
pub default_timeout_secs: u64,
#[serde(default)]
pub phases: Vec<Phase>,
#[serde(default)]
pub flows: HashMap<String, Flow>,
}
static CONFIG: OnceLock<PipelineFlows> = OnceLock::new();
/// Get the loaded pipeline flow configuration (loaded once, cached).
pub fn get() -> &'static PipelineFlows {
CONFIG.get_or_init(load)
}
fn load() -> PipelineFlows {
let candidates = [
crate::core::path_utils::config_dir().join("pipeline_flows.json"),
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config/pipeline_flows.json"),
];
for path in candidates {
match std::fs::read_to_string(&path) {
Ok(s) => match serde_json::from_str::<PipelineFlows>(&s) {
Ok(cfg) => {
tracing::info!(
"pipeline_config: loaded {} (version={}, {} flows)",
path.display(),
cfg.version,
cfg.flows.len()
);
return cfg;
}
Err(e) => {
tracing::warn!("pipeline_config: failed to parse {}: {}", path.display(), e)
}
},
Err(_) => continue,
}
}
tracing::warn!("pipeline_config: pipeline_flows.json not found, using defaults");
PipelineFlows {
default_timeout_secs: 3600,
..Default::default()
}
}
impl PipelineFlows {
/// Look up a stage by flow name and stage/processor name.
pub fn stage(&self, flow: &str, name: &str) -> Option<&Stage> {
self.flows.get(flow)?.stages.iter().find(|s| s.name == name)
}
/// Whether a stage is declared to run in parallel (non-blocking).
///
/// Unknown stages default to `true` (parallel / non-blocking) so that a
/// missing config entry never reintroduces blocking behavior.
pub fn is_parallel(&self, flow: &str, name: &str) -> bool {
self.stage(flow, name).map(|s| s.parallel).unwrap_or(true)
}
/// Declared dependencies for a stage (empty when unknown).
pub fn dependencies(&self, flow: &str, name: &str) -> Vec<String> {
self.stage(flow, name)
.map(|s| s.dependencies.clone())
.unwrap_or_default()
}
/// Effective timeout for a stage (falls back to `default_timeout_secs`).
pub fn timeout_secs(&self, flow: &str, name: &str) -> u64 {
self.stage(flow, name)
.map(|s| s.timeout_secs)
.filter(|&t| t > 0)
.unwrap_or(self.default_timeout_secs)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_unknown_stage_defaults_parallel() {
let cfg = PipelineFlows::default();
assert!(cfg.is_parallel("register", "does_not_exist"));
assert!(cfg.dependencies("register", "does_not_exist").is_empty());
}
#[test]
fn test_scene_declared_parallel() {
// The shipped config declares the scene stage as parallel.
let cfg = get();
assert!(
cfg.is_parallel("register", "scene"),
"scene stage must be parallel in pipeline_flows.json"
);
assert_eq!(
cfg.dependencies("register", "scene"),
vec!["cut".to_string()]
);
}
}
+44 -3
View File
@@ -2,10 +2,13 @@ use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use super::executor::PythonExecutor;
use super::metadata::ProcessorMetadata;
use super::AsrStatus;
#[derive(Debug, Serialize, Deserialize)]
pub struct AsrResult {
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<ProcessorMetadata>,
#[serde(default)]
pub status: Option<AsrStatus>,
pub language: Option<String>,
@@ -24,8 +27,35 @@ impl AsrResult {
}
}
pub fn add_metadata(&mut self, processor_name: &str, tool: &str, file_uuid: Option<&str>) {
use chrono::Utc;
use super::metadata::{ProcessorInfo, Timestamps, SourceInfo};
let metadata = ProcessorMetadata {
processor: ProcessorInfo {
name: processor_name.to_string(),
tool: tool.to_string(),
version: super::metadata::PROCESSOR_VERSION.to_string(),
config: None,
},
timestamps: Timestamps {
created_at: Utc::now(),
updated_at: None,
processing_time_ms: None,
},
source: file_uuid.map(|uuid| SourceInfo {
file_uuid: uuid.to_string(),
video_info: None,
}),
custom: None,
};
self.metadata = Some(metadata);
}
pub fn no_audio_track() -> Self {
AsrResult {
metadata: None,
status: Some(AsrStatus::NoAudioTrack),
language: None,
language_probability: None,
@@ -36,6 +66,7 @@ impl AsrResult {
pub fn silent_audio() -> Self {
AsrResult {
metadata: None,
status: Some(AsrStatus::SilentAudio),
language: None,
language_probability: None,
@@ -126,11 +157,13 @@ pub async fn process_asr(
let whisper_result: WhisperJsonOutput =
serde_json::from_str(&json_str).context("Failed to parse whisper output")?;
std::fs::copy(&json_path, output_path)
.context("Failed to copy whisper output to target path")?;
let mut result = convert_whisper_to_asr(whisper_result);
result.compute_status();
result.add_metadata("asr", "whisper_mlx", uuid);
// Save with metadata and precision optimization
crate::core::json_formatter::write_file_pretty_rounded(&result, output_path, 2)
.context("Failed to write ASR output")?;
tracing::info!(
"[ASR] Whisper result: status={}, {} segments, language: {:?}",
@@ -175,6 +208,11 @@ async fn process_asr_python(
serde_json::from_str(&json_str).context("Failed to parse ASR output")?;
result.compute_status();
result.add_metadata("asr", "python_whisper", uuid);
// Save with metadata and precision optimization
crate::core::json_formatter::write_file_pretty_rounded(&result, output_path, 2)
.context("Failed to write ASR output")?;
tracing::info!(
"[ASR] Python result: status={}, {} segments, language: {:?}",
@@ -223,6 +261,7 @@ fn convert_whisper_to_asr(whisper: WhisperJsonOutput) -> AsrResult {
.collect();
AsrResult {
metadata: None,
status: None,
language: whisper.language,
language_probability: None,
@@ -238,6 +277,7 @@ mod tests {
#[test]
fn test_asr_result_serialization() {
let result = AsrResult {
metadata: None,
status: None,
language: Some("en".to_string()),
language_probability: Some(0.95),
@@ -302,6 +342,7 @@ mod tests {
#[test]
fn test_asr_result_empty_segments() {
let result = AsrResult {
metadata: None,
status: None,
language: None,
language_probability: None,
+210 -2
View File
@@ -3,10 +3,13 @@ use serde::{Deserialize, Serialize};
use tokio::process::Command;
use super::executor::PythonExecutor;
use super::metadata::ProcessorMetadata;
use super::AsrStatus;
#[derive(Debug, Serialize, Deserialize)]
pub struct AsrxResult {
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<ProcessorMetadata>,
#[serde(default)]
pub status: Option<AsrStatus>,
pub language: Option<String>,
@@ -23,8 +26,41 @@ impl AsrxResult {
self.status = Some(AsrStatus::from_segments(self.segment_count));
}
pub fn add_metadata(&mut self, processor_name: &str, tool: &str, file_uuid: Option<&str>) {
use super::metadata::{ProcessorInfo, SourceInfo, Timestamps};
use chrono::Utc;
let metadata = ProcessorMetadata {
processor: ProcessorInfo {
name: processor_name.to_string(),
tool: tool.to_string(),
version: super::metadata::PROCESSOR_VERSION.to_string(),
config: None,
},
timestamps: Timestamps {
created_at: Utc::now(),
updated_at: None,
processing_time_ms: None,
},
source: file_uuid.map(|uuid| SourceInfo {
file_uuid: uuid.to_string(),
video_info: None,
}),
custom: None,
};
self.metadata = Some(metadata);
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write asrx.json")?;
Ok(())
}
pub fn no_audio_track() -> Self {
AsrxResult {
metadata: None,
status: Some(AsrStatus::NoAudioTrack),
language: None,
segments: vec![],
@@ -35,6 +71,7 @@ impl AsrxResult {
pub fn silent_audio() -> Self {
AsrxResult {
metadata: None,
status: Some(AsrStatus::SilentAudio),
language: None,
segments: vec![],
@@ -71,8 +108,175 @@ pub async fn process_asrx(
) -> Result<AsrxResult> {
tracing::info!("[ASRX] Starting speaker diarization: {}", video_path);
// Use Python processor (Swift ASRX disabled - requires GUI authorization)
tracing::info!("[ASRX] Using Python processor");
use super::tool_selector::ToolSelector;
let executor = PythonExecutor::new()?;
let selector = ToolSelector::new("asrx");
if let Some(tool) = selector.select_tool(&executor).await? {
tracing::info!(
"[ASRX] Using {} from config (priority {})",
tool.name,
tool.parameters
.get("priority")
.and_then(|v| v.as_u64())
.unwrap_or(99)
);
match tool.name.as_str() {
"swift" => {
let swift_path = tool.path;
let args = if !tool.args.is_empty() {
tool.args
.iter()
.map(|a| {
a.replace("{video_path}", video_path)
.replace("{output_path}", output_path)
.replace("{file_uuid}", uuid.unwrap_or(""))
})
.collect()
} else {
let mut args = vec![video_path.to_string(), output_path.to_string()];
if let Some(u) = uuid {
args.push("--uuid".to_string());
args.push(u.to_string());
}
args
};
let output = tokio::process::Command::new(&swift_path)
.args(&args)
.output()
.await
.context("Failed to execute asrx_swift")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[ASRX] Swift processor failed: {}", stderr);
anyhow::bail!("Swift ASRX failed: {}", stderr);
}
let json_str =
std::fs::read_to_string(output_path).context("Failed to read ASRX output")?;
let mut result: AsrxResult =
serde_json::from_str(&json_str).context("Failed to parse ASRX output")?;
result.compute_status();
result.add_metadata("asrx", "swift_asrx", uuid);
result.save_to_file(output_path)?;
tracing::info!(
"[ASRX] Swift result: status={}, {} segments",
result
.status
.as_ref()
.map(|s| s.to_string())
.unwrap_or_default(),
result.segment_count
);
return Ok(result);
}
"rust" => {
let rust_path = tool.path;
let mut cmd = tokio::process::Command::new(&rust_path);
cmd.arg(video_path).arg(output_path);
if let Some(u) = uuid {
cmd.arg("--uuid").arg(u);
cmd.arg("--file-uuid").arg(u);
}
cmd.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
.process_group(0);
let output = cmd.output().await.context("Failed to execute rust_asrx")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[ASRX] Rust processor failed: {}", stderr);
anyhow::bail!("Rust ASRX failed: {}", stderr);
}
let json_str =
std::fs::read_to_string(output_path).context("Failed to read ASRX output")?;
let mut result: AsrxResult =
serde_json::from_str(&json_str).context("Failed to parse ASRX output")?;
result.compute_status();
result.add_metadata("asrx", "rust_asrx", uuid);
result.save_to_file(output_path)?;
tracing::info!(
"[ASRX] Rust result: status={}, {} segments",
result
.status
.as_ref()
.map(|s| s.to_string())
.unwrap_or_default(),
result.segment_count
);
return Ok(result);
}
"python" => {
let script_path = tool.path;
if !script_path.exists() {
tracing::error!("[ASRX] Script not found: {:?}", script_path);
anyhow::bail!("asrx_processor.py not found");
}
let mut cmd = tokio::process::Command::new(executor.python_path());
cmd.arg(&script_path).arg(video_path).arg(output_path);
if let Some(u) = uuid {
cmd.arg("--uuid").arg(u);
cmd.arg("--file-uuid").arg(u);
}
cmd.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
.process_group(0);
let output = cmd
.output()
.await
.context("Failed to execute asrx_processor.py")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[ASRX] Python processor failed: {}", stderr);
anyhow::bail!("Python ASRX failed: {}", stderr);
}
let json_str =
std::fs::read_to_string(output_path).context("Failed to read ASRX output")?;
let mut result: AsrxResult =
serde_json::from_str(&json_str).context("Failed to parse ASRX output")?;
result.compute_status();
result.add_metadata("asrx", "pyannote_diarization", uuid);
result.save_to_file(output_path)?;
tracing::info!(
"[ASRX] Python result: status={}, {} segments",
result
.status
.as_ref()
.map(|s| s.to_string())
.unwrap_or_default(),
result.segment_count
);
return Ok(result);
}
_ => {
tracing::warn!("[ASRX] Unknown tool from config: {}", tool.name);
}
}
}
tracing::warn!("[ASRX] No tool available from config, falling back to Python");
process_asrx_python(video_path, output_path, uuid).await
}
@@ -183,6 +387,8 @@ async fn process_asrx_python(
serde_json::from_str(&json_str).context("Failed to parse ASRX output")?;
result.compute_status();
result.add_metadata("asrx", "pyannote_diarization", uuid);
result.save_to_file(output_path)?;
tracing::info!(
"[ASRX] Result: status={}, {} segments",
@@ -204,6 +410,7 @@ mod tests {
#[test]
fn test_asrx_result_serialization() {
let result = AsrxResult {
metadata: None,
status: None,
language: Some("en".to_string()),
segments: vec![AsrxSegment {
@@ -247,6 +454,7 @@ mod tests {
#[test]
fn test_asrx_result_empty_segments() {
let result = AsrxResult {
metadata: None,
status: None,
language: None,
segments: vec![],
+43 -4
View File
@@ -4,11 +4,14 @@ use std::process::Command;
use std::time::Duration;
use super::executor::PythonExecutor;
use super::metadata::ProcessorMetadata;
const CUT_TIMEOUT: Duration = Duration::from_secs(3600);
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CutResult {
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<ProcessorMetadata>,
pub frame_count: u64,
#[serde(serialize_with = "round_two")]
pub fps: f64,
@@ -35,14 +38,43 @@ where
serializer.serialize_f64((v * 100.0).round() / 100.0)
}
impl CutResult {
pub fn add_metadata(&mut self, processor_name: &str, tool: &str, file_uuid: Option<&str>) {
use chrono::Utc;
use super::metadata::{ProcessorInfo, Timestamps, SourceInfo};
let metadata = ProcessorMetadata {
processor: ProcessorInfo {
name: processor_name.to_string(),
tool: tool.to_string(),
version: super::metadata::PROCESSOR_VERSION.to_string(),
config: None,
},
timestamps: Timestamps {
created_at: Utc::now(),
updated_at: None,
processing_time_ms: None,
},
source: file_uuid.map(|uuid| SourceInfo {
file_uuid: uuid.to_string(),
video_info: None,
}),
custom: None,
};
self.metadata = Some(metadata);
}
}
pub async fn process_cut(
video_path: &str,
output_path: &str,
uuid: Option<&str>,
) -> Result<CutResult> {
// Try native ffmpeg-based scene detection first
let result = try_native_cut(video_path);
if let Ok(r) = result {
let mut result = try_native_cut(video_path);
if let Ok(mut r) = result {
r.add_metadata("cut", "ffmpeg_native", uuid);
let json = serde_json::to_string_pretty(&r)?;
std::fs::write(output_path, &json)
.with_context(|| format!("Failed to write {:?}", output_path))?;
@@ -55,11 +87,13 @@ pub async fn process_cut(
let script_path = executor.script_path("cut_processor.py");
if !script_path.exists() {
let empty_result = CutResult {
let mut empty_result = CutResult {
metadata: None,
frame_count: 0,
fps: 0.0,
scenes: vec![],
};
empty_result.add_metadata("cut", "none", uuid);
let json = serde_json::to_string_pretty(&empty_result)?;
std::fs::write(output_path, &json)
.with_context(|| format!("Failed to write {:?}", output_path))?;
@@ -78,8 +112,10 @@ pub async fn process_cut(
.with_context(|| format!("Failed to run {:?}", script_path))?;
let json_str = std::fs::read_to_string(output_path).context("Failed to read CUT output")?;
let result: CutResult =
let mut result: CutResult =
serde_json::from_str(&json_str).context("Failed to parse CUT output")?;
result.add_metadata("cut", "python_scenedetect", uuid);
Ok(result)
}
@@ -216,6 +252,7 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
}
Ok(CutResult {
metadata: None,
frame_count: total_frames,
fps,
scenes,
@@ -265,6 +302,7 @@ mod tests {
#[test]
fn test_cut_result_serialization() {
let result = CutResult {
metadata: None,
frame_count: 100,
fps: 30.0,
scenes: vec![CutScene {
@@ -305,6 +343,7 @@ mod tests {
#[test]
fn test_empty_scenes() {
let result = CutResult {
metadata: None,
frame_count: 0,
fps: 0.0,
scenes: vec![],
+40 -6
View File
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use std::time::Duration;
use super::executor::PythonExecutor;
use super::metadata::ProcessorMetadata;
use super::FaceStatus;
const FACE_TIMEOUT: Duration = Duration::from_secs(7200);
@@ -38,6 +39,8 @@ pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FaceResult {
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<ProcessorMetadata>,
#[serde(default)]
pub status: Option<FaceStatus>,
pub frame_count: u64,
@@ -45,8 +48,6 @@ pub struct FaceResult {
pub frames: Vec<FaceFrame>,
#[serde(default)]
pub total_faces: usize,
#[serde(default)]
pub metadata: Option<serde_json::Value>,
}
impl FaceResult {
@@ -63,20 +64,48 @@ impl FaceResult {
}
}
pub fn add_metadata(&mut self, processor_name: &str, tool: &str, file_uuid: Option<&str>) {
use chrono::Utc;
use super::metadata::{ProcessorInfo, Timestamps, SourceInfo, VideoInfo};
let video_info = None;
let metadata = ProcessorMetadata {
processor: ProcessorInfo {
name: processor_name.to_string(),
tool: tool.to_string(),
version: super::metadata::PROCESSOR_VERSION.to_string(),
config: None,
},
timestamps: Timestamps {
created_at: Utc::now(),
updated_at: None,
processing_time_ms: None,
},
source: file_uuid.map(|uuid| SourceInfo {
file_uuid: uuid.to_string(),
video_info,
}),
custom: None,
};
self.metadata = Some(metadata);
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
let json = serde_json::to_string_pretty(self).context("Failed to serialize FaceResult")?;
std::fs::write(path, json).context("Failed to write face.json")?;
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write face.json")?;
Ok(())
}
pub fn no_faces(frame_count: u64, fps: f64) -> Self {
FaceResult {
metadata: None,
status: Some(FaceStatus::NoFaces),
frame_count,
fps,
frames: vec![],
total_faces: 0,
metadata: None,
}
}
}
@@ -162,6 +191,7 @@ pub async fn process_face(
serde_json::from_str(&json_str).context("Failed to parse existing FACE output")?;
result.compute_status();
result.add_metadata("face", "swift_face", uuid);
result.save_to_file(output_path)?;
tracing::info!(
@@ -288,6 +318,7 @@ pub async fn process_face(
let mut result: FaceResult =
serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
result.compute_status();
result.add_metadata("face", "swift_face", uuid);
// Store embeddings to Qdrant and remove from JSON
if let Some(file_uuid) = uuid {
@@ -357,6 +388,7 @@ pub async fn process_face(
serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
result.compute_status();
result.add_metadata("face", "python_face_processor", uuid);
// Execute face tracking
tracing::info!("[FACE] Starting face tracking");
@@ -478,6 +510,7 @@ async fn run_face_with_config(
let mut result: FaceResult =
serde_json::from_str(&json_str).context("Failed to parse Swift FACE output")?;
result.compute_status();
result.add_metadata("face", "swift_face", uuid);
result.save_to_file(output_path)?;
if let Some(uid) = uuid {
@@ -520,6 +553,7 @@ async fn run_face_with_config(
let mut result: FaceResult = serde_json::from_str(&json_str)
.context("Failed to parse Python FACE output")?;
result.compute_status();
result.add_metadata("face", "python_face_processor", uuid);
result.save_to_file(output_path)?;
if let Some(uid) = uuid {
@@ -549,11 +583,11 @@ mod tests {
#[test]
fn test_face_result_serialization() {
let result = FaceResult {
metadata: None,
status: None,
frame_count: 100,
fps: 30.0,
total_faces: 1,
metadata: None,
frames: vec![FaceFrame {
frame: 0,
timestamp: 0.0,
+26 -2
View File
@@ -427,13 +427,37 @@ pub fn track_faces(
.collect();
// Store traces in metadata
face_data.metadata = Some(serde_json::json!({
let trace_custom = serde_json::json!({
"traces": trace_stats,
"trace_stats": {
"total_traces": next_trace_id,
"active_traces": trace_stats.len(),
}
}));
});
if let Some(ref mut metadata) = face_data.metadata {
metadata.custom = Some(trace_custom);
} else {
// Create new metadata with trace info
use super::metadata::{ProcessorMetadata, ProcessorInfo, Timestamps};
use chrono::Utc;
face_data.metadata = Some(ProcessorMetadata {
processor: ProcessorInfo {
name: "face_tracker".to_string(),
tool: "rust_face_tracker".to_string(),
version: super::metadata::PROCESSOR_VERSION.to_string(),
config: None,
},
timestamps: Timestamps {
created_at: Utc::now(),
updated_at: None,
processing_time_ms: None,
},
source: None,
custom: Some(trace_custom),
});
}
tracing::info!("✅ Tracking complete: {} traces", trace_stats.len());
+93
View File
@@ -0,0 +1,93 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
pub const PROCESSOR_VERSION: &str = "1.0.0";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessorMetadata {
pub processor: ProcessorInfo,
pub timestamps: Timestamps,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<SourceInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
pub custom: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessorInfo {
pub name: String,
pub tool: String,
pub version: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub config: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Timestamps {
pub created_at: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
pub updated_at: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processing_time_ms: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceInfo {
pub file_uuid: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub video_info: Option<VideoInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoInfo {
pub duration_sec: f64,
pub fps: f64,
pub width: u32,
pub height: u32,
pub total_frames: u32,
}
impl ProcessorMetadata {
pub fn new(name: String, tool: String) -> Self {
Self {
processor: ProcessorInfo {
name,
tool,
version: PROCESSOR_VERSION.to_string(),
config: None,
},
timestamps: Timestamps {
created_at: Utc::now(),
updated_at: None,
processing_time_ms: None,
},
source: None,
custom: None,
}
}
pub fn with_config(mut self, config: serde_json::Value) -> Self {
self.processor.config = Some(config);
self
}
pub fn with_source(mut self, file_uuid: String, video_info: Option<VideoInfo>) -> Self {
self.source = Some(SourceInfo {
file_uuid,
video_info,
});
self
}
pub fn with_custom(mut self, custom: serde_json::Value) -> Self {
self.custom = Some(custom);
self
}
pub fn with_processing_time(mut self, start: DateTime<Utc>) -> Self {
let end = Utc::now();
self.timestamps.updated_at = Some(end);
self.timestamps.processing_time_ms = Some((end - start).num_milliseconds());
self
}
}
+4
View File
@@ -12,6 +12,7 @@ pub mod face_recognition;
pub mod face_tracker;
pub mod hand;
pub mod heuristic_scene;
pub mod metadata;
pub mod ocr;
pub mod pose;
pub mod scene_classification;
@@ -195,5 +196,8 @@ pub use tkg::{
build_tkg, query_auto_representative_frame, FrameTraceInfo, MainIdentityInfo,
RepresentativeFrameResult, TkgResult,
};
pub use metadata::{
ProcessorMetadata, ProcessorInfo, Timestamps, SourceInfo, VideoInfo, PROCESSOR_VERSION,
};
pub mod processor_config_v3;
pub mod tool_selector;
+44 -1
View File
@@ -4,6 +4,7 @@ use std::collections::HashSet;
use std::time::Duration;
use super::executor::PythonExecutor;
use super::metadata::ProcessorMetadata;
const OCR_TIMEOUT: Duration = Duration::from_secs(7200);
@@ -17,11 +18,47 @@ const TEXT_SIMILARITY_THRESHOLD: f64 = 0.5;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OcrResult {
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<ProcessorMetadata>,
pub frame_count: u64,
pub fps: f64,
pub frames: Vec<OcrFrame>,
}
impl OcrResult {
pub fn add_metadata(&mut self, processor_name: &str, tool: &str, file_uuid: Option<&str>) {
use super::metadata::{ProcessorInfo, SourceInfo, Timestamps};
use chrono::Utc;
let metadata = ProcessorMetadata {
processor: ProcessorInfo {
name: processor_name.to_string(),
tool: tool.to_string(),
version: super::metadata::PROCESSOR_VERSION.to_string(),
config: None,
},
timestamps: Timestamps {
created_at: Utc::now(),
updated_at: None,
processing_time_ms: None,
},
source: file_uuid.map(|uuid| SourceInfo {
file_uuid: uuid.to_string(),
video_info: None,
}),
custom: None,
};
self.metadata = Some(metadata);
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write ocr.json")?;
Ok(())
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OcrFrame {
pub frame: u64,
@@ -272,6 +309,7 @@ pub async fn process_ocr(
if !script_path.exists() {
tracing::warn!("[OCR] Script not found, returning empty result");
return Ok(OcrResult {
metadata: None,
frame_count: 0,
fps: 0.0,
frames: vec![],
@@ -293,9 +331,12 @@ pub async fn process_ocr(
let json_str = std::fs::read_to_string(output_path).context("Failed to read OCR output")?;
let result: OcrResult =
let mut result: OcrResult =
serde_json::from_str(&json_str).context("Failed to parse OCR output")?;
result.add_metadata("ocr", "swift_ocr", uuid);
result.save_to_file(output_path)?;
tracing::info!("[OCR] Result: {} frames", result.frames.len());
Ok(result)
@@ -308,6 +349,7 @@ mod tests {
#[test]
fn test_ocr_result_serialization() {
let result = OcrResult {
metadata: None,
frame_count: 100,
fps: 30.0,
frames: vec![OcrFrame {
@@ -354,6 +396,7 @@ mod tests {
#[test]
fn test_ocr_result_empty_frames() {
let result = OcrResult {
metadata: None,
frame_count: 0,
fps: 0.0,
frames: vec![],
+3 -1
View File
@@ -19,13 +19,15 @@ pub async fn process_asr_module(
state.get_processor(ProcessorType::Asr).start(1);
}
let asr_result = momentry_core::core::processor::process_asr(
let mut asr_result = momentry_core::core::processor::process_asr(
video_path,
asr_path.to_str().unwrap(),
Some(uuid),
)
.await?;
asr_result.add_metadata("asr", "whisper_mlx", Some(uuid));
let asr_json = serde_json::to_string_pretty(&asr_result)?;
std::fs::write(asr_path, &asr_json)?;
+3 -1
View File
@@ -19,13 +19,15 @@ pub async fn process_asrx_module(
state.get_processor(ProcessorType::Asrx).start(1);
}
let asrx_result = momentry_core::core::processor::process_asrx(
let mut asrx_result = momentry_core::core::processor::process_asrx(
video_path,
asrx_path.to_str().unwrap(),
Some(uuid),
)
.await?;
asrx_result.add_metadata("asrx", "pyannote_diarization", Some(uuid));
let asrx_json = serde_json::to_string_pretty(&asrx_result)?;
std::fs::write(asrx_path, &asrx_json)?;
+216 -28
View File
@@ -26,6 +26,86 @@ const FACE_IO_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(600);
static FACE_TRACE_INFLIGHT: LazyLock<tokio::sync::Mutex<std::collections::HashSet<String>>> =
LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
/// Bounds concurrent Scene VLM runs. Scene VLM can take hours per file and each run
/// loads frames + calls the multimodal LLM; without a bound, dispatching many files
/// in parallel would exhaust memory. One at a time mirrors the previous inline
/// (sequential) behavior without blocking the worker poll loop.
static SCENE_VLM_SEM: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(1));
/// Tracks uuids with a Scene VLM task currently spawned (or queued for a permit).
/// Prevents the per-poll loop from spawning duplicate tasks before `scenes.json`
/// exists. Cleared by the spawned task when it finishes.
static SCENE_VLM_INFLIGHT: LazyLock<tokio::sync::Mutex<std::collections::HashSet<String>>> =
LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
/// Resolve a processor's dependencies, preferring the declarative
/// `config/pipeline_flows.json` (`register` flow) and falling back to the built-in
/// `ProcessorType::dependencies()` when the stage is not declared. Names in the
/// config that do not map to a `ProcessorType` (e.g. `tkg`) are ignored.
fn stage_dependencies(
processor_type: crate::core::db::ProcessorType,
) -> Vec<crate::core::db::ProcessorType> {
use crate::core::db::ProcessorType;
let cfg = crate::core::pipeline_config::get();
match cfg.stage("register", processor_type.as_str()) {
Some(stage) => stage
.dependencies
.iter()
.filter_map(|name| ProcessorType::from_db_str(name))
.collect(),
None => processor_type.dependencies(),
}
}
/// Ensure an existing processor output file records its metadata (tool/version/time).
///
/// When the worker skips a processor because its output file already exists, the
/// processor itself never runs to add metadata. Upstream writers (e.g. SwiftFacePose)
/// can emit face.json/ocr.json without a metadata block, leaving tool/version/time
/// unrecorded. This patches such files in place; it is a no-op when metadata is present
/// or for processors that do not use the embedded metadata convention.
fn ensure_output_metadata(
processor_type: crate::core::db::ProcessorType,
output_path: &std::path::Path,
uuid: &str,
) {
use crate::core::db::ProcessorType;
let json_str = match std::fs::read_to_string(output_path) {
Ok(s) => s,
Err(_) => return,
};
let path = output_path.to_string_lossy();
match processor_type {
ProcessorType::Face => {
if let Ok(mut result) =
serde_json::from_str::<crate::core::processor::FaceResult>(&json_str)
{
if result.metadata.is_none() {
result.add_metadata("face", "swift_face", Some(uuid));
match result.save_to_file(&path) {
Ok(()) => info!("[METADATA] Wrote face tool/version/time for {}", uuid),
Err(e) => warn!("Failed to write face metadata for {}: {}", uuid, e),
}
}
}
}
ProcessorType::Ocr => {
if let Ok(mut result) =
serde_json::from_str::<crate::core::processor::OcrResult>(&json_str)
{
if result.metadata.is_none() {
result.add_metadata("ocr", "swift_ocr", Some(uuid));
match result.save_to_file(&path) {
Ok(()) => info!("[METADATA] Wrote ocr tool/version/time for {}", uuid),
Err(e) => warn!("Failed to write ocr metadata for {}: {}", uuid, e),
}
}
}
}
_ => {}
}
}
use crate::api::files::{register_single_file, unregister_internal};
use crate::core::chunk::rule1_ingest;
use crate::core::config::{FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT, OUTPUT_DIR};
@@ -830,14 +910,14 @@ impl JobWorker {
.await?;
// Clear any stale PipelineProgress from previous jobs
let progress_key = format!(
"{}progress:{}:pipeline",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
job.uuid
);
let prefix = crate::core::config::REDIS_KEY_PREFIX.as_str();
let progress_key = format!("{}progress:{}:pipeline", prefix, job.uuid);
// Also reset the phase progress high-water mark used by the phases API
let phase_hwm_key = format!("{}progress:{}:phase_hwm", prefix, job.uuid);
if let Ok(mut conn) = self.redis.get_conn().await {
let _: Option<String> = redis::cmd("DEL")
.arg(&progress_key)
.arg(&phase_hwm_key)
.query_async(&mut conn)
.await
.ok();
@@ -1011,6 +1091,9 @@ impl JobWorker {
"Processor {} output file exists, marking completed and skipping",
processor_type.as_str()
);
// The processor is not run on this path, so ensure the pre-existing
// output still records its processor metadata (tool/version/time).
ensure_output_metadata(*processor_type, &output_path, &job.uuid);
self.db
.update_processor_progress(
&job.uuid,
@@ -1737,7 +1820,7 @@ impl JobWorker {
}
// Check dependencies: all dependent processors must be completed
let deps = processor_type.dependencies();
let deps = stage_dependencies(*processor_type);
if !deps.is_empty() {
let mut any_dep_failed = false;
let all_deps_met =
@@ -2605,7 +2688,7 @@ impl JobWorker {
}
// Check if all dependencies are met
let deps = processor_type.dependencies();
let deps = stage_dependencies(processor_type);
let deps_met = deps.iter().all(|dep| completed_set.contains(dep));
if !deps_met {
@@ -2802,16 +2885,76 @@ impl JobWorker {
false
};
if !scene_vlm_complete {
info!("[Scene VLM] Starting for {} after CUT completion", uuid);
// Guard on `scene_vlm_exhausted`: once retry_count >= 3 the job is
// marked failed elsewhere, so re-spawning would only create a tight
// retry loop now that dispatch is non-blocking.
if !scene_vlm_complete && !scene_vlm_exhausted {
// Execution mode is declared in config/pipeline_flows.json:
// "parallel": true → dispatch to a background task (non-blocking)
// "parallel": false → await inline (blocking, original behavior)
let scene_parallel =
crate::core::pipeline_config::get().is_parallel("register", "scene");
match self.process_scene_vlm(uuid, &output_dir).await {
Ok(_) => info!("[Scene VLM] ✅ Completed for {}", uuid),
Err(e) => {
warn!("[Scene VLM] ❌ Failed for {}: {}", uuid, e);
// 標 failed + retry_count++,讓 job 保持 running 由 poll 重試(上限 3 次)
if let Err(e2) = self.db.mark_scene_vlm_failed(uuid).await {
error!("[Scene VLM] Failed to mark {} failed: {}", uuid, e2);
if scene_parallel {
// Non-blocking: spawn so Scene VLM (which can run for hours) does not
// block the worker poll loop. Guarded by SCENE_VLM_INFLIGHT to avoid
// duplicate spawns on each poll, and SCENE_VLM_SEM to bound concurrency.
let mut inflight = SCENE_VLM_INFLIGHT.lock().await;
if inflight.insert(uuid.to_string()) {
drop(inflight);
info!(
"[Scene VLM] (parallel) dispatching for {} after CUT completion",
uuid
);
let db = self.db.clone();
let uuid_owned = uuid.to_string();
let output_dir_owned = output_dir.clone();
tokio::spawn(async move {
let _permit = match SCENE_VLM_SEM.acquire().await {
Ok(p) => p,
Err(_) => {
SCENE_VLM_INFLIGHT.lock().await.remove(&uuid_owned);
return;
}
};
match Self::process_scene_vlm(
db.clone(),
&uuid_owned,
&output_dir_owned,
)
.await
{
Ok(_) => info!("[Scene VLM] ✅ Completed for {}", uuid_owned),
Err(e) => {
warn!("[Scene VLM] ❌ Failed for {}: {}", uuid_owned, e);
// 標 failed + retry_count++,讓 job 保持 running 由 poll 重試(上限 3 次)
if let Err(e2) = db.mark_scene_vlm_failed(&uuid_owned).await {
error!(
"[Scene VLM] Failed to mark {} failed: {}",
uuid_owned, e2
);
}
}
}
SCENE_VLM_INFLIGHT.lock().await.remove(&uuid_owned);
});
} else {
drop(inflight);
debug!("[Scene VLM] already in-flight for {}, skipping spawn", uuid);
}
} else {
info!(
"[Scene VLM] (blocking) Starting for {} after CUT completion",
uuid
);
match Self::process_scene_vlm(self.db.clone(), uuid, &output_dir).await {
Ok(_) => info!("[Scene VLM] ✅ Completed for {}", uuid),
Err(e) => {
warn!("[Scene VLM] ❌ Failed for {}: {}", uuid, e);
// 標 failed + retry_count++,讓 job 保持 running 由 poll 重試(上限 3 次)
if let Err(e2) = self.db.mark_scene_vlm_failed(uuid).await {
error!("[Scene VLM] Failed to mark {} failed: {}", uuid, e2);
}
}
}
}
@@ -4349,11 +4492,20 @@ impl JobWorker {
Ok(())
}
pub async fn process_scene_vlm(&self, uuid: &str, output_dir: &str) -> anyhow::Result<()> {
/// Run Scene VLM for a file.
///
/// This is an associated function (not a method) so it can be dispatched to a
/// background task with only the `Arc<PostgresDb>` it needs — see the `parallel`
/// handling in `check_and_complete_job`.
pub async fn process_scene_vlm(
db: Arc<PostgresDb>,
uuid: &str,
output_dir: &str,
) -> anyhow::Result<()> {
use crate::core::processor::scene_vlm::SceneVlmProcessor;
// Mark Scene VLM as running in processor_results
self.db.upsert_scene_vlm_result(uuid, "running").await?;
db.upsert_scene_vlm_result(uuid, "running").await?;
let (_enabled, interval_sec, samples, use_cuts, max_workers) =
crate::core::config::get_scene_vlm_config();
@@ -4363,8 +4515,7 @@ impl JobWorker {
// return Ok(());
// }
let video = self
.db
let video = db
.get_video_by_uuid(uuid)
.await?
.ok_or_else(|| anyhow::anyhow!("Video not found: {}", uuid))?;
@@ -4380,7 +4531,7 @@ impl JobWorker {
"[Scene VLM] Invalid video metadata for {}, marking complete (not applicable)",
uuid
);
self.db.upsert_scene_vlm_result(uuid, "completed").await?;
db.upsert_scene_vlm_result(uuid, "completed").await?;
return Ok(());
}
@@ -4428,8 +4579,7 @@ impl JobWorker {
);
// Update progress: frames extracted
self.db
.update_scene_vlm_progress(uuid, extracted.len() as i32, total_scenes as i32)
db.update_scene_vlm_progress(uuid, extracted.len() as i32, total_scenes as i32)
.await?;
// Generate VLM descriptions for extracted frames
@@ -4499,8 +4649,7 @@ impl JobWorker {
processed += 1;
// Update progress every 10 scenes
if processed % 10 == 0 || processed == total_scenes {
self.db
.update_scene_vlm_progress(uuid, processed as i32, total_scenes as i32)
db.update_scene_vlm_progress(uuid, processed as i32, total_scenes as i32)
.await?;
}
}
@@ -4582,7 +4731,7 @@ impl JobWorker {
.bind(scene.has_cut)
.bind(scene.cut_count as i32)
.bind("pending")
.execute(self.db.pool())
.execute(db.pool())
.await?;
let embedding = embedder.embed_document(desc).await?;
@@ -4616,7 +4765,7 @@ impl JobWorker {
.bind(format!("{:x}", point_id))
.bind(&profile.file_uuid)
.bind(scene.index as i32)
.execute(self.db.pool())
.execute(db.pool())
.await?;
indexed += 1;
@@ -4628,7 +4777,27 @@ impl JobWorker {
);
// Mark Scene VLM as completed
self.db.upsert_scene_vlm_result(uuid, "completed").await?;
db.upsert_scene_vlm_result(uuid, "completed").await?;
// Update Redis progress for scene_vlm
if let Ok(redis) = crate::core::db::RedisClient::new() {
if let Ok(mut conn) = redis.get_conn().await {
let prefix = crate::core::config::REDIS_KEY_PREFIX.as_str();
let redis_key = format!("{}progress:{}:pipeline", prefix, uuid);
let _: Result<(), _> = redis::AsyncCommands::set(
&mut conn,
&redis_key,
serde_json::json!({
"stage": "scene_vlm",
"progress": 1.0,
"status": "completed",
"detail": format!("{} scenes processed", profile.total_scenes)
})
.to_string(),
)
.await;
}
}
Ok(())
}
@@ -4657,4 +4826,23 @@ mod tests {
assert!(config.enabled);
assert!(config.max_concurrent >= 1);
}
#[test]
fn test_stage_dependencies_from_config() {
use crate::core::db::ProcessorType;
assert_eq!(
stage_dependencies(ProcessorType::Asrx),
vec![ProcessorType::Cut, ProcessorType::Asr]
);
assert_eq!(
stage_dependencies(ProcessorType::Scene),
vec![ProcessorType::Cut]
);
assert_eq!(
stage_dependencies(ProcessorType::FaceCluster),
vec![ProcessorType::Face]
);
// Stages without declared dependencies resolve to none.
assert!(stage_dependencies(ProcessorType::Cut).is_empty());
}
}
+20 -5
View File
@@ -705,13 +705,16 @@ impl ProcessorPool {
ProcessorType::Cut => {
let cut_path =
std::path::Path::new(&output_dir).join(format!("{}.cut.json", job.uuid));
let result = if cut_path.exists() {
let mut result: processor::CutResult = if cut_path.exists() {
let content =
std::fs::read_to_string(&cut_path).context("Failed to read cut.json")?;
serde_json::from_str(&content).context("Failed to parse cut.json")?
} else {
processor::process_cut(video_path, output_path.to_str().unwrap(), uuid).await?
};
result.add_metadata("cut", "ffmpeg_native", uuid);
let chunks_produced = result.scenes.len() as i32;
tracing::info!(
"CUT completed, storing {} scenes for {}",
@@ -751,13 +754,16 @@ impl ProcessorPool {
})
}
ProcessorType::Ocr => {
let result = processor::process_ocr(
let mut result = processor::process_ocr(
video_path,
output_path.to_str().unwrap(),
uuid,
Some(&sample_frames),
)
.await?;
result.add_metadata("ocr", "swift_ocr", uuid);
let chunks_produced = result.frames.len() as i32;
tracing::info!(
"OCR completed, storing {} frames for {}",
@@ -798,13 +804,16 @@ impl ProcessorPool {
})
}
ProcessorType::Face => {
let result = processor::process_face(
let mut result = processor::process_face(
video_path,
output_path.to_str().unwrap(),
uuid,
Some(&sample_frames),
)
.await?;
result.add_metadata("face", "swift_face", uuid);
let chunks_produced = result.frames.len() as i32;
let face_status = result.status.clone();
let total_faces = result.total_faces;
@@ -1022,8 +1031,11 @@ impl ProcessorPool {
})
}
ProcessorType::Asr => {
let result =
let mut result =
processor::process_asr(video_path, output_path.to_str().unwrap(), uuid).await?;
result.add_metadata("asr", "whisper_mlx", uuid);
let chunks_produced = result.segments.len() as i32;
let asr_status = result.status.clone();
let segment_count = result.segment_count;
@@ -1073,9 +1085,12 @@ impl ProcessorPool {
})
}
ProcessorType::Asrx => {
let result =
let mut result =
processor::process_asrx(video_path, output_path.to_str().unwrap(), uuid)
.await?;
result.add_metadata("asrx", "pyannote_diarization", uuid);
let chunks_produced = result.segments.len() as i32;
let asr_status = result.status.clone();
let segment_count = result.segment_count;