Files
momentry_core/src/api/processing.rs
T
Accusys c4fbbfda4a
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
fix: pipeline log 寫入 output root + processor-counts/json 使用 per-library 路徑
- write_pipeline_timeline: log 寫到 ~/momentry/output (parent of per-lib dir)
- get_processor_counts: 用 get_output_dir_for_file + global fallback
- get_processor_json: 加 State, per-library 優先 + global fallback
- delete_output_files_for_uuid: 同時掃 output root 清 pipeline log
2026-11-19 13:35:24 +08:00

1310 lines
44 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::Json,
routing::{get, post},
Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Instant;
use super::types::AppState;
use crate::core::cache::{keys, RedisCache};
use crate::core::config::{
FACE_FILTER_CONFIDENCE_PCT_DEFAULT, FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT,
REDIS_KEY_PREFIX,
};
use crate::core::db::schema;
use crate::core::db::{
Database, MonitorJobStatus, PostgresDb, ProgressMessage, RedisClient, VideoRecord, VideoStatus,
};
use crate::core::probe::ffprobe;
use crate::worker::processor;
use crate::{Embedder, FileManager};
fn delete_output_files_for_uuid(uuid: &str, output_dir: &str) -> u64 {
let mut deleted_count = 0u64;
// Also scan output root (parent of per-library dir) for pipeline logs
let mut dirs = vec![output_dir.to_string()];
if let Some(parent) = std::path::Path::new(output_dir).parent() {
if parent.file_name().and_then(|n| n.to_str()) == Some("output") {
dirs.push(parent.to_string_lossy().to_string());
}
}
for output_dir in &dirs {
if let Ok(entries) = std::fs::read_dir(output_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
let is_uuid_file = name.starts_with(uuid) && !path.is_dir();
let is_pipeline_log =
name.starts_with("pipeline_") && name.contains(uuid) && name.ends_with(".log");
if is_uuid_file || is_pipeline_log {
if std::fs::remove_file(&path).is_ok() {
deleted_count += 1;
tracing::info!("[FORCE_RESCAN] Deleted output file: {}", name);
}
}
}
}
}
}
deleted_count
}
/// Delete only the output files of the given processors (single-processor re-run).
/// Other processors' outputs (and the combined `{uuid}.json`) are preserved so the
/// rest of the pipeline data stays intact.
fn delete_processor_output_files(uuid: &str, processors: &[String], output_dir: &str) -> u64 {
let mut files: Vec<String> = Vec::new();
for proc in processors {
match proc.as_str() {
"asr" => files.push(format!("{}.asr.json", uuid)),
"asr_asrx" | "asrx" => files.push(format!("{}.asrx.json", uuid)),
"ocr" => files.push(format!("{}.ocr.json", uuid)),
"cut" => files.push(format!("{}.cut.json", uuid)),
"face" => files.push(format!("{}.face.json", uuid)),
"face_cluster" => files.push(format!("{}.face_cluster.json", uuid)),
"face_trace" => files.push(format!("{}.face_traced.json", uuid)),
"scene_vlm" | "scene" => files.push(format!("{}.scenes.json", uuid)),
"pose" => files.push(format!("{}.pose.json", uuid)),
"hand" => files.push(format!("{}.hand.json", uuid)),
"appearance" => files.push(format!("{}.appearance.json", uuid)),
"tkg" => files.push(format!("{}.tkg.json", uuid)),
_ => continue,
}
}
let mut deleted_count = 0u64;
for name in files {
let path = std::path::Path::new(output_dir).join(&name);
if path.exists() && std::fs::remove_file(&path).is_ok() {
tracing::info!("[FORCE_RESCAN] Deleted output file: {}", name);
deleted_count += 1;
}
}
deleted_count
}
#[derive(Debug, Serialize)]
struct JobListResponse {
jobs: Vec<JobInfoResponse>,
count: i64,
page: usize,
page_size: usize,
}
#[derive(Debug, Deserialize)]
struct JobsQuery {
page: Option<usize>,
page_size: Option<usize>,
status: Option<String>,
}
#[derive(Debug, Serialize)]
struct JobInfoResponse {
id: i32,
uuid: String,
status: String,
current_processor: Option<String>,
progress_current: i32,
progress_total: i32,
created_at: String,
started_at: Option<String>,
}
#[derive(Debug, Serialize)]
struct JobDetailResponse {
id: i32,
uuid: String,
status: String,
current_processor: Option<String>,
progress_current: i32,
progress_total: i32,
processors: Vec<ProcessorInfoResponse>,
created_at: String,
started_at: Option<String>,
updated_at: Option<String>,
queue_position: Option<i32>,
}
#[derive(Debug, Serialize)]
struct ProcessorInfoResponse {
processor_type: String,
status: String,
started_at: Option<String>,
completed_at: Option<String>,
duration_secs: Option<f64>,
error_message: Option<String>,
}
#[derive(Debug, Deserialize)]
struct CacheToggleRequest {
enabled: bool,
}
#[derive(Debug, Serialize)]
struct CacheToggleResponse {
success: bool,
cache_enabled: bool,
message: String,
}
#[derive(Debug, Deserialize)]
struct AutoPipelineToggleRequest {
enabled: bool,
}
#[derive(Debug, Serialize)]
struct AutoPipelineToggleResponse {
success: bool,
auto_pipeline_enabled: bool,
message: String,
}
#[derive(Debug, Deserialize)]
struct WatcherAutoRegisterToggleRequest {
enabled: bool,
}
#[derive(Debug, Serialize)]
struct WatcherAutoRegisterToggleResponse {
success: bool,
watcher_auto_register_enabled: bool,
message: String,
}
#[derive(Debug, Deserialize)]
struct FaceSettings {
min_confidence: Option<f64>,
min_size: Option<i32>,
}
#[derive(Debug, Deserialize)]
struct ProcessRequest {
rules: Option<Vec<String>>,
processors: Option<Vec<String>>,
face_settings: Option<FaceSettings>,
#[serde(default)]
force: bool,
}
#[derive(Debug, Serialize, Deserialize)]
struct ProgressResponse {
file_uuid: String,
user: Option<String>,
group: Option<String>,
file_name: Option<String>,
duration: Option<f64>,
overall_progress: u32,
cpu_percent: Option<f64>,
gpu_percent: Option<f64>,
memory_percent: Option<f64>,
memory_mb: Option<u64>,
system: Option<SystemHealthInfo>,
processors: Vec<ProcessorProgressInfo>,
}
#[derive(Debug, Serialize, Deserialize)]
struct SystemHealthInfo {
cpu_idle_pct: f64,
memory_available_mb: u64,
memory_total_mb: u64,
memory_used_pct: f64,
gpu_available: bool,
gpu_utilization_pct: Option<f64>,
gpu_memory_used_pct: Option<f64>,
dynamic_concurrency: u32,
config_concurrency: u32,
running_processors: u32,
}
#[derive(Debug, Serialize, Deserialize)]
struct ProcessorProgressInfo {
name: String,
status: String,
current: u32,
total: u32,
progress: u32,
message: String,
frames_processed: i32,
chunks_produced: i32,
retry_count: i32,
eta_seconds: Option<i64>,
}
fn get_system_stats() -> (Option<f64>, Option<f64>, Option<f64>, Option<u64>) {
use std::process::Command;
let pid = std::process::id().to_string();
let cpu = Command::new("ps")
.args(["-p", &pid, "-o", "%cpu="])
.output()
.ok()
.and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok());
let (mem_percent, mem_rss) = Command::new("ps")
.args(["-p", &pid, "-o", "%mem=,rss="])
.output()
.ok()
.map(|o| {
let output = String::from_utf8_lossy(&o.stdout);
let parts: Vec<&str> = output.split_whitespace().collect();
let percent = parts.first().and_then(|s| s.parse().ok());
let rss = parts.get(1).and_then(|s| s.parse().ok());
(percent, rss)
})
.unwrap_or((None, None));
let gpu = Command::new("nvidia-smi")
.args([
"--query-gpu=utilization.gpu",
"--format=csv,noheader,nounits",
])
.output()
.ok()
.and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok());
let mem_mb = mem_rss.map(|r: u64| r / 1024);
(cpu, mem_percent, gpu, mem_mb)
}
async fn trigger_processing(
State(state): State<AppState>,
Path(uuid): Path<String>,
Json(req): Json<ProcessRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let videos_table = schema::table_name("videos");
let row: Option<(
String,
String,
String,
Option<String>,
String,
Option<String>,
Option<serde_json::Value>,
)> = sqlx::query_as(&format!(
"SELECT file_uuid, file_path, file_name, file_type, COALESCE(processing_status::text, 'REGISTERED'), content_hash, face_filter FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("DB error: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let (file_uuid, file_path, file_name, file_type, processing_status, content_hash, face_filter) =
row.ok_or(StatusCode::NOT_FOUND)?;
if processing_status == "PROCESSING" || processing_status == "QUEUED" {
return Err(StatusCode::CONFLICT);
}
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let output_path = std::path::Path::new(&output_dir).join(format!("{}.monitor.json", file_uuid));
let monitor_jobs_table = schema::table_name("monitor_jobs");
let redis = RedisClient::new().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut conn = redis
.get_conn()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let valid: std::collections::HashSet<&str> = crate::core::db::ProcessorType::all()
.iter()
.map(|p| p.as_str())
.collect();
let processors_to_run: Vec<String> = if let Some(procs) = &req.processors {
procs
.iter()
.filter(|s| valid.contains(s.as_str()))
.map(|s| s.to_string())
.collect()
} else {
crate::core::db::ProcessorType::all()
.iter()
.map(|p| p.as_str().to_string())
.collect()
};
// 確保 monitor_job 存在
let existing_id: Option<i32> = sqlx::query_scalar(&format!(
"SELECT id FROM {monitor_jobs_table} WHERE uuid = $1"
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// Convert face_settings to serde_json::Value for create_monitor_job.
// Priority: explicit request settings (0-1) → persisted per-file settings
// (videos.face_filter, min_confidence 0-100) → None (caller uses Apple Vision defaults 0.5/1).
let face_settings_json = if let Some(fs) = req.face_settings.as_ref() {
Some(serde_json::json!({
"min_confidence": fs.min_confidence.unwrap_or(FACE_MIN_CONFIDENCE_DEFAULT),
"min_size": fs.min_size.unwrap_or(FACE_MIN_SIZE_DEFAULT)
}))
} else if let Some(v) = face_filter.as_ref() {
let min_conf_pct = v
.get("min_confidence")
.and_then(|x| x.as_f64())
.unwrap_or(FACE_FILTER_CONFIDENCE_PCT_DEFAULT);
let min_size = v
.get("min_size")
.and_then(|x| x.as_i64())
.unwrap_or(FACE_MIN_SIZE_DEFAULT as i64) as i32;
Some(serde_json::json!({
"min_confidence": min_conf_pct / 100.0,
"min_size": min_size
}))
} else {
None
};
if let Some(job_id) = existing_id {
// Clean up stale processor_results from previous runs
// Old entries with status='running' from a dead worker session
// would block the worker from actually running processors.
// For single-processor re-runs, only the requested processors are reset
// so other processors' completed results are preserved.
let pr_table = schema::table_name("processor_results");
if processors_to_run.is_empty() {
sqlx::query(&format!("DELETE FROM {pr_table} WHERE job_id = $1"))
.bind(job_id)
.execute(state.db.pool())
.await
.map_err(|e| {
tracing::error!(
"[TRIGGER] Failed to clean processor_results for job {}: {}",
job_id,
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
} else {
sqlx::query(&format!(
"DELETE FROM {pr_table} WHERE job_id = $1 AND (processor = ANY($2) OR processor_type = ANY($2))"
))
.bind(job_id)
.bind(&processors_to_run)
.execute(state.db.pool())
.await
.map_err(|e| {
tracing::error!(
"[TRIGGER] Failed to clean processor_results for job {}: {}",
job_id,
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
// Scene VLM rows are file-keyed with job_id = NULL, delete them separately
if processors_to_run
.iter()
.any(|p| p == "scene_vlm" || p == "scene")
{
sqlx::query(&format!(
"DELETE FROM {pr_table} WHERE file_uuid = $1 AND processor_type = 'scene_vlm'"
))
.bind(&file_uuid)
.execute(state.db.pool())
.await
.map_err(|e| {
tracing::error!(
"[TRIGGER] Failed to clean scene_vlm results for {}: {}",
file_uuid,
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
}
}
tracing::info!("[TRIGGER] Cleaned processor_results for job {}", job_id);
// If force=true, delete output files to force re-processing
if req.force {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let deleted_count = if processors_to_run.is_empty() {
// Full re-scan: delete all output files
delete_output_files_for_uuid(&file_uuid, &output_dir)
} else {
// Single-processor re-run: delete only that processor's output
delete_processor_output_files(&file_uuid, &processors_to_run, &output_dir)
};
tracing::info!(
"[TRIGGER] Force re-scan: deleted {} output files for {} (processors={:?})",
deleted_count,
file_uuid,
processors_to_run
);
// Re-running ASR/OCR/Scene VLM must also rebuild the search index:
// - asr/asrx/ocr → Rule 1 re-chunking + re-vectorize (chunk table + momentry_rule1)
// - scene_vlm → _scenes collection regeneration
// Signal the worker via Redis so the Rule 1 guard doesn't skip re-chunking
// just because old chunks still exist.
let rebuild_procs = ["asr", "asr_asrx", "asrx", "ocr", "scene_vlm", "scene"];
let needs_rebuild = processors_to_run.is_empty()
|| processors_to_run
.iter()
.any(|p| rebuild_procs.contains(&p.as_str()));
if needs_rebuild {
let key = format!("{}rerun_rebuild:{}", REDIS_KEY_PREFIX.as_str(), file_uuid);
let flag_value = if processors_to_run.is_empty() {
"all".to_string()
} else {
processors_to_run.join(",")
};
let _: Result<String, _> = redis::cmd("SET")
.arg(&key)
.arg(&flag_value)
.arg("EX")
.arg(86400)
.query_async(&mut conn)
.await;
tracing::info!(
"[TRIGGER] Set rerun_rebuild flag for {} = {}",
file_uuid,
flag_value
);
}
}
// Update existing job with new face_settings if provided
if let Some(ref fs_json) = face_settings_json {
sqlx::query(&format!(
"UPDATE {monitor_jobs_table} SET face_settings = $1::jsonb WHERE id = $2"
))
.bind(&fs_json.to_string())
.bind(job_id)
.execute(state.db.pool())
.await
.map_err(|e| {
tracing::error!(
"[TRIGGER] Failed to update face_settings for job {}: {}",
job_id,
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
}
} else {
state
.db
.create_monitor_job(&file_uuid, Some(&file_path), face_settings_json.as_ref())
.await
.map_err(|e| {
tracing::error!(
"[TRIGGER] Failed to create monitor job for {}: {}",
file_uuid,
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
}
// UPDATE processors + reset 狀態讓 worker 可 pickup
sqlx::query(&format!(
"UPDATE {monitor_jobs_table} SET processors = $1::text[], status = 'pending' WHERE uuid = $2"
))
.bind(&processors_to_run)
.bind(&file_uuid)
.execute(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[TRIGGER] Failed to update monitor job for {}: {}", file_uuid, e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
// Update videos.processing_status to PROCESSING immediately
let processor_names_upper: Vec<String> =
processors_to_run.iter().map(|p| p.to_uppercase()).collect();
let progress: serde_json::Map<String, serde_json::Value> = processors_to_run
.iter()
.map(|p| {
(
p.to_uppercase(),
serde_json::json!({
"current_frame": 0, "total_frames": 0, "percentage": 0, "status": "pending"
}),
)
})
.collect();
let status = serde_json::json!({
"phase": "QUEUED",
"active_processors": processor_names_upper,
"total_frames": 0,
"progress": progress
});
sqlx::query(&format!(
"UPDATE {videos_table} SET status = 'queued', processing_status = $1, updated_at = CURRENT_TIMESTAMP WHERE file_uuid = $2"
))
.bind(&status)
.bind(&file_uuid)
.execute(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[TRIGGER] Failed to update processing status for {}: {}", file_uuid, e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let processors_to_run_refs: Vec<&str> = processors_to_run.iter().map(|s| s.as_str()).collect();
let notification = serde_json::json!({
"action": "process",
"file_uuid": file_uuid,
"file_path": file_path,
"file_name": file_name,
"file_type": file_type,
"content_hash": content_hash,
"output_dir": output_dir,
"processors": processors_to_run_refs,
});
let notification_key = format!("{}notifications", REDIS_KEY_PREFIX.as_str());
let _: Result<(), _> = redis::cmd("PUBLISH")
.arg(&notification_key)
.arg(notification.to_string())
.query_async(&mut conn)
.await;
tracing::info!(
"[TRIGGER] Published processing notification for {}",
file_uuid
);
Ok(Json(serde_json::json!({
"success": true,
"message": "Processing triggered",
"file_uuid": file_uuid,
})))
}
async fn download_json(
State(state): State<AppState>,
Path((file_uuid, processor)): Path<(String, String)>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let path = std::path::Path::new(&output_dir).join(format!("{}.{}.json", file_uuid, processor));
let content = tokio::fs::read_to_string(&path)
.await
.map_err(|_| StatusCode::NOT_FOUND)?;
Ok(Json(
serde_json::from_str(&content).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
))
}
async fn get_chunk_by_path(
State(state): State<AppState>,
Path((file_uuid, chunk_id)): Path<(String, String)>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let table = schema::table_name("chunk");
let row: Option<serde_json::Value> = sqlx::query_scalar(&format!(
"SELECT row_to_json(t) FROM (SELECT * FROM {} WHERE uuid = $1 AND chunk_id = $2) t",
table
))
.bind(&file_uuid)
.bind(&chunk_id)
.fetch_optional(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
row.map(Json).ok_or(StatusCode::NOT_FOUND)
}
async fn get_progress(file_uuid: Path<String>) -> Result<Json<serde_json::Value>, StatusCode> {
let file_uuid = file_uuid.0;
let redis = RedisClient::new().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut conn = redis
.get_conn()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let key = format!("{}progress:{}", REDIS_KEY_PREFIX.as_str(), file_uuid);
let processor_map: HashMap<String, String> = redis::cmd("HGETALL")
.arg(&key)
.query_async(&mut conn)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let (cpu, mem_pct, gpu, mem_mb) = get_system_stats();
let sys = SystemHealthInfo {
cpu_idle_pct: cpu.map(|c: f64| 100.0 - c).unwrap_or(0.0),
memory_available_mb: mem_mb.unwrap_or(0),
memory_total_mb: 0,
memory_used_pct: mem_pct.unwrap_or(0.0),
gpu_available: gpu.is_some(),
gpu_utilization_pct: gpu,
gpu_memory_used_pct: None,
dynamic_concurrency: 0,
config_concurrency: 0,
running_processors: 0,
};
let pg = PostgresDb::init()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let video = pg
.get_video_by_uuid(&file_uuid)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let processors: Vec<ProcessorProgressInfo> = processor_map
.into_iter()
.filter_map(|(name, json_str)| {
let msg: ProgressMessage = serde_json::from_str(&json_str).ok()?;
let current = msg.data.current.unwrap_or(0) as u32;
let total = msg.data.total.unwrap_or(0) as u32;
let progress = if total > 0 {
((current as f64 / total as f64) * 100.0) as u32
} else {
0
};
Some(ProcessorProgressInfo {
name,
status: msg.msg_type,
current,
total,
progress,
message: msg.data.message.unwrap_or_default(),
frames_processed: 0,
chunks_produced: 0,
retry_count: 0,
eta_seconds: None,
})
})
.collect();
// Fetch TKG and Agent progress from Redis
let tkg_key = format!("{}progress:{}:tkg", REDIS_KEY_PREFIX.as_str(), file_uuid);
let agent_key = format!("{}progress:{}:agent", REDIS_KEY_PREFIX.as_str(), file_uuid);
let tkg_progress: Option<serde_json::Value> = if let Ok(mut c) = redis.get_conn().await {
let val: Option<String> = redis::cmd("GET")
.arg(&tkg_key)
.query_async(&mut c)
.await
.ok();
val.and_then(|s| serde_json::from_str(&s).ok())
} else {
None
};
let agent_progress: Option<serde_json::Value> = if let Ok(mut c) = redis.get_conn().await {
let val: Option<String> = redis::cmd("GET")
.arg(&agent_key)
.query_async(&mut c)
.await
.ok();
val.and_then(|s| serde_json::from_str(&s).ok())
} else {
None
};
let overall = if processors.is_empty() {
0
} else {
let sum: u64 = processors.iter().map(|p| p.progress as u64).sum();
(sum / processors.len() as u64) as u32
};
Ok(Json(serde_json::json!({
"file_uuid": file_uuid,
"file_name": video.as_ref().map(|v| &v.file_name),
"duration": video.as_ref().map(|v| v.duration),
"overall_progress": overall,
"cpu_percent": cpu,
"gpu_percent": gpu,
"memory_percent": mem_pct,
"memory_mb": mem_mb,
"system": sys,
"processors": processors,
"tkg_progress": tkg_progress,
"agent_progress": agent_progress,
})))
}
async fn list_jobs(Json(params): Json<JobsQuery>) -> Result<Json<JobListResponse>, StatusCode> {
let pg = PostgresDb::init()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let jobs_table = schema::table_name("monitor_jobs");
let videos_table = schema::table_name("videos");
let page = params.page.unwrap_or(1).max(1);
let page_size = params.page_size.unwrap_or(20).max(1).min(100);
let offset = (page - 1) * page_size;
let mut where_clause = String::new();
if let Some(ref status) = params.status {
where_clause = format!(" WHERE j.status = '{}'", status);
}
let count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {} j{}",
jobs_table, where_clause
))
.fetch_one(pg.pool())
.await
.unwrap_or(0);
let jobs: Vec<(i32, String, String, String, String, Option<String>, i32, i32)> =
sqlx::query_as(&format!(
"SELECT j.id::int, j.uuid, COALESCE(v.file_name, ''), COALESCE(j.status, 'QUEUED'), COALESCE(j.current_processor, ''), v.file_uuid, COALESCE(j.progress_current, 0), COALESCE(j.progress_total, 0) \
FROM {} j LEFT JOIN {} v ON v.file_uuid = j.uuid{} \
ORDER BY j.id DESC LIMIT $1 OFFSET $2",
jobs_table, videos_table, where_clause
))
.bind(page_size as i64)
.bind(offset as i64)
.fetch_all(pg.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let job_list = jobs
.into_iter()
.map(
|(id, uuid, fname, status, cp, _vuuid, pf, tf)| JobInfoResponse {
id,
uuid,
status,
current_processor: Some(cp),
progress_current: pf,
progress_total: tf,
created_at: String::new(),
started_at: None,
},
)
.collect();
Ok(Json(JobListResponse {
jobs: job_list,
count,
page,
page_size,
}))
}
async fn get_job(Path(uuid): Path<String>) -> Result<Json<JobDetailResponse>, StatusCode> {
let pg = PostgresDb::init()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let jobs_table = schema::table_name("monitor_jobs");
let videos_table = schema::table_name("videos");
let job: Option<(i32, String, String, String, Option<String>, i32, i32, String, Option<String>, Option<String>)> =
sqlx::query_as(&format!(
"SELECT j.id::int, j.uuid, COALESCE(v.file_name, 'unknown'), COALESCE(j.status, 'QUEUED'), j.current_processor, \
COALESCE(j.progress_current, 0), COALESCE(j.progress_total, 0), \
COALESCE(j.created_at::text, ''), j.started_at::text, j.updated_at::text \
FROM {} j LEFT JOIN {} v ON v.file_uuid = j.uuid WHERE j.uuid = $1",
jobs_table, videos_table
))
.bind(&uuid)
.fetch_optional(pg.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let (
id,
uuid,
file_name,
status,
current_processor,
pf,
tf,
created_at,
started_at,
updated_at,
) = job.ok_or(StatusCode::NOT_FOUND)?;
// Calculate queue position (pending or queued jobs ahead of this one)
let queue_position = if status == "pending" || status == "queued" {
sqlx::query_scalar::<_, i64>(&format!(
"SELECT COUNT(*) + 1 FROM {} WHERE status IN ('pending', 'queued') AND created_at < (SELECT created_at FROM {} WHERE uuid = $1)",
jobs_table, jobs_table
))
.bind(&uuid)
.fetch_one(pg.pool())
.await
.ok()
.map(|pos| pos as i32)
} else {
None
};
Ok(Json(JobDetailResponse {
id,
uuid,
status,
current_processor,
progress_current: pf,
progress_total: tf,
processors: vec![],
created_at,
started_at,
updated_at,
queue_position,
}))
}
async fn cache_toggle(
State(state): State<AppState>,
Json(req): Json<CacheToggleRequest>,
) -> Json<CacheToggleResponse> {
crate::core::config::set_cache_enabled(req.enabled);
Json(CacheToggleResponse {
success: true,
cache_enabled: req.enabled,
message: format!("Cache {}", if req.enabled { "enabled" } else { "disabled" }),
})
}
async fn auto_pipeline_toggle(
Json(req): Json<AutoPipelineToggleRequest>,
) -> Json<AutoPipelineToggleResponse> {
crate::core::config::set_auto_pipeline_enabled(req.enabled);
Json(AutoPipelineToggleResponse {
success: true,
auto_pipeline_enabled: req.enabled,
message: format!(
"Auto pipeline {}",
if req.enabled { "enabled" } else { "disabled" }
),
})
}
async fn watcher_auto_register_toggle(
Json(req): Json<WatcherAutoRegisterToggleRequest>,
) -> Json<WatcherAutoRegisterToggleResponse> {
crate::core::config::set_watcher_auto_register(req.enabled);
Json(WatcherAutoRegisterToggleResponse {
success: true,
watcher_auto_register_enabled: req.enabled,
message: format!(
"Watcher auto-register {}",
if req.enabled { "enabled" } else { "disabled" }
),
})
}
#[derive(Debug, Serialize, Deserialize)]
struct ProcessorCountInfo {
processor: String,
has_json: bool,
frame_count: Option<u32>,
segment_count: Option<u32>,
chunk_count: Option<u32>,
last_modified: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
struct ProcessorCountsResponse {
file_uuid: String,
output_dir: String,
processors: Vec<ProcessorCountInfo>,
}
/// GET /api/v1/processor-json?file_hash=...&processor=...
/// Serves raw processor output JSON files from the output directory.
/// GET /api/v1/output-completeness
/// 檢查所有影片的產出完整性,回傳缺項清單。
/// 前端用此 API 將有缺項的 completed 卡片改為紅字顯示。
#[derive(serde::Serialize)]
struct OutputCompletenessItem {
file_uuid: String,
file_name: String,
status: String,
is_complete: bool,
missing: Vec<String>,
}
async fn get_output_completeness(
State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let videos_table = schema::table_name("videos");
let rows: Vec<(String, String, String)> = sqlx::query_as(&format!(
"SELECT file_uuid, file_name, status FROM {} WHERE file_type = 'video' ORDER BY file_name",
videos_table
))
.fetch_all(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[output-completeness] DB query failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let mut items = Vec::new();
for (uuid, file_name, status) in rows {
if status != "completed" {
continue; // 只檢查 completed 的影片
}
let mut missing = Vec::new();
// 檢查 JSON 產出
for ext in ["asrx", "cut", "face", "face_cluster", "face_traced", "ocr", "scenes"] {
let path = format!("{}/{}.{}.json", output_dir, uuid, ext);
if !std::path::Path::new(&path).exists() {
missing.push(format!("{}.json", ext));
}
}
// 檢查 trace 目錄(如果有 faces)
let face_json = format!("{}/{}.face.json", output_dir, uuid);
if std::path::Path::new(&face_json).exists() {
if let Ok(content) = std::fs::read_to_string(&face_json) {
if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) {
let total_faces = data
.get("total_faces")
.or_else(|| data.get("data").and_then(|d| d.get("total_faces")))
.and_then(|v| v.as_u64())
.unwrap_or(0);
if total_faces > 0 {
let trace_base = std::path::Path::new(&output_dir).join(&uuid);
if trace_base.is_dir() {
if let Ok(entries) = std::fs::read_dir(&trace_base) {
for entry in entries.filter_map(|e| e.ok()) {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with("trace_") && entry.path().is_dir() {
for f in ["key_face.jpg", "key_frame.jpg", "trace_profile.json"] {
if !entry.path().join(f).exists() {
missing.push(format!("{}/{}", name, f));
}
}
}
}
}
}
}
}
}
}
items.push(OutputCompletenessItem {
file_uuid: uuid,
file_name,
status,
is_complete: missing.is_empty(),
missing,
});
}
let complete_count = items.iter().filter(|i| i.is_complete).count();
let incomplete_count = items.len() - complete_count;
Ok(Json(serde_json::json!({
"total": items.len(),
"complete": complete_count,
"incomplete": incomplete_count,
"items": items,
})))
}
async fn get_processor_json(
State(state): State<AppState>,
Query(params): Query<std::collections::HashMap<String, String>>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let file_uuid = params.get("file_hash").ok_or((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({"error": "Missing file_hash"})),
))?;
let processor = params.get("processor").ok_or((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({"error": "Missing processor"})),
))?;
// Map processor name to output file extension.
let ext = match processor.as_str() {
"asrx" => "asrx",
"face" => "face",
"face_cluster" => "face_cluster",
"face_trace" | "face_traced" => "face_traced",
"ocr" => "ocr",
"cut" => "cut",
"scenes" | "scene_vlm" => "scenes",
"probe" => "probe",
"tkg" => "tkg",
other => other,
};
// Try per-library dir first, then global OUTPUT_DIR (legacy)
let per_lib_dir = crate::core::config::get_output_dir_for_file(file_uuid, state.db.pool()).await;
let global_dir = crate::core::config::OUTPUT_DIR.as_str();
let candidates = [
format!("{}/{}.{}.json", per_lib_dir.trim_end_matches('/'), file_uuid, ext),
format!("{}/{}.{}.json", global_dir.trim_end_matches('/'), file_uuid, ext),
];
let path = candidates.iter().find(|p| std::path::Path::new(p).exists())
.cloned()
.unwrap_or_else(|| candidates[0].clone());
match std::fs::read_to_string(&path) {
Ok(content) => match serde_json::from_str(&content) {
Ok(json) => Ok(Json(json)),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Parse error: {}", e)})),
)),
},
Err(_) => Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": format!("No {} output for {}", processor, file_uuid)})),
)),
}
}
async fn get_processor_counts(
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<ProcessorCountsResponse>, StatusCode> {
let videos_table = schema::table_name("videos");
let full_uuid: Option<String> = sqlx::query_scalar(&format!(
"SELECT file_uuid FROM {} WHERE file_uuid = $1 OR file_uuid LIKE $2",
videos_table
))
.bind(&file_uuid)
.bind(&format!("{}%", file_uuid))
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("DB error: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?
.or_else(|| {
if file_uuid.len() == 32 {
Some(file_uuid.clone())
} else {
None
}
});
let file_uuid = full_uuid.ok_or(StatusCode::NOT_FOUND)?;
// Use per-library output dir (test files live in output/test, not output/demo)
let per_lib_dir = crate::core::config::get_output_dir_for_file(&file_uuid, state.db.pool()).await;
let global_dir = crate::core::config::OUTPUT_DIR.as_str();
let processors = crate::core::db::ProcessorType::all();
let mut results = Vec::new();
for processor in &processors {
let proc_name = processor.as_str();
let json_ext = match proc_name {
"face_trace" => "face_traced",
other => other,
};
let filename = format!("{}.{}.json", file_uuid, json_ext);
let json_path = std::path::Path::new(&per_lib_dir).join(&filename);
let fallback_path = std::path::Path::new(global_dir).join(&filename);
let effective_path = if json_path.exists() { json_path } else { fallback_path };
let has_json = effective_path.exists();
let mut frame_count = None;
let mut segment_count = None;
let mut chunk_count = None;
let mut last_modified = None;
if has_json {
if let Ok(metadata) = std::fs::metadata(&effective_path) {
if let Ok(modified) = metadata.modified() {
let chrono_dt: chrono::DateTime<chrono::Utc> = modified.into();
last_modified = Some(chrono_dt.to_rfc3339());
}
}
if let Ok(content) = std::fs::read_to_string(&effective_path) {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {
// CUT: prioritize scenes count over frame_count
if proc_name == "cut" {
frame_count = json
.get("scenes")
.and_then(|v| v.as_array())
.map(|arr| arr.len() as u32);
} else {
// Standard frame_count field
frame_count = json
.get("frame_count")
.and_then(|v| v.as_u64())
.map(|v| v 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())
.map(|arr| arr.len() as u32)
.or_else(|| {
json.get("parent_chunks")
.and_then(|v| v.as_array())
.map(|arr| arr.len() as u32)
});
if chunk_count.is_none() {
chunk_count = json
.get("chunks")
.and_then(|v| v.as_array())
.map(|arr| arr.len() as u32);
}
}
}
}
// Special handling for face_cluster: query trace_profiles if frame_count is None
if proc_name == "face_cluster" && frame_count.is_none() {
let tp_table = crate::core::db::schema::table_name("trace_profiles");
let trace_count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(DISTINCT trace_id) FROM {} WHERE file_uuid = $1 AND frame_count > 0",
tp_table
))
.bind(&file_uuid)
.fetch_one(state.db.pool())
.await
.unwrap_or(0);
if trace_count > 0 {
frame_count = Some(trace_count as u32);
}
}
results.push(ProcessorCountInfo {
processor: proc_name.to_string(),
has_json,
frame_count,
segment_count,
chunk_count,
last_modified,
});
}
Ok(Json(ProcessorCountsResponse {
file_uuid,
output_dir: per_lib_dir,
processors: results,
}))
}
async fn verify_file_handler(
Path(file_uuid): Path<String>,
) -> Json<crate::verification::FileVerificationReport> {
let report = crate::verification::verifier::verify_file(&file_uuid);
Json(report)
}
/// [DISABLED] FS VLM Summary removed from pipeline (2026-09-22)
/// Scene VLM (moment chunk VLM) remains active
/*
/// Manually trigger VLM summary generation for an existing file.
/// Non-blocking: returns immediately, VLM runs in background.
async fn trigger_vlm_summary(
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Json<serde_json::Value> {
let db = state.db.clone();
let output_dir = crate::core::config::OUTPUT_DIR.clone();
// Check if file has face traces
let tp_table = crate::core::db::schema::table_name("trace_profiles");
let face_count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1"
))
.bind(&file_uuid)
.fetch_one(db.pool())
.await
.unwrap_or(0);
if face_count == 0 {
return Json(serde_json::json!({
"success": false,
"message": "No face traces found for this file",
"file_uuid": file_uuid,
}));
}
// Check how many traces need VLM and/or embedding
let done_count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1 \
AND vlm_description IS NOT NULL AND vlm_description != '' \
AND vlm_embedding IS NOT NULL"
))
.bind(&file_uuid)
.fetch_one(db.pool())
.await
.unwrap_or(0);
let pending = face_count - done_count;
if pending == 0 {
return Json(serde_json::json!({
"success": true,
"message": "All traces already have VLM summaries",
"file_uuid": file_uuid,
"total_traces": face_count,
"already_done": done_count,
}));
}
// Spawn VLM generation in background
let file_uuid_clone = file_uuid.clone();
tokio::spawn(async move {
let redis = crate::core::db::RedisClient::new().ok();
crate::core::processor::vlm_summary::generate_vlm_summaries(
&db, &file_uuid_clone, &output_dir, redis.map(std::sync::Arc::new),
)
.await;
});
Json(serde_json::json!({
"success": true,
"message": format!("VLM summary generation started for {} traces", pending),
"file_uuid": file_uuid,
"total_traces": face_count,
"already_done": done_count,
"pending": pending,
}))
}
*/
pub fn processing_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/output-completeness", get(get_output_completeness))
.route("/api/v1/file/:file_uuid/process", post(trigger_processing))
.route(
"/api/v1/file/:file_uuid/json/:processor",
post(download_json),
)
.route(
"/api/v1/file/:file_uuid/chunk/:chunk_id",
post(get_chunk_by_path),
)
.route("/api/v1/progress/:file_uuid", post(get_progress))
.route("/api/v1/jobs", post(list_jobs))
.route("/api/v1/job/:uuid", get(get_job))
.route("/api/v1/config/cache", post(cache_toggle))
.route("/api/v1/config/auto-pipeline", post(auto_pipeline_toggle))
.route(
"/api/v1/config/watcher-auto-register",
post(watcher_auto_register_toggle),
)
.route(
"/api/v1/file/:file_uuid/processor-counts",
get(get_processor_counts),
)
.route(
"/api/v1/processor-json",
get(get_processor_json),
)
.route("/api/v1/file/:file_uuid/verify", get(verify_file_handler))
// [DISABLED] FS VLM Summary API removed (2026-09-22)
// .route(
// "/api/v1/file/:file_uuid/vlm-summary",
// post(trigger_vlm_summary),
// )
}