feat: face fix deployment + trace_* regeneration + executor stderr filter fix
- swift_face.swift: frame rounding (.rounded()), conf 0.75, min_size 64 - trace_* directories regenerated for KOBA (37 traces, start_frame 5307) - executor.rs: stderr filter now logs all non-empty stderr (was discarding) - VAD not skippable in ASRX (main_fixed.py Step 2 always runs) - Step 2.5 sentence boundary refinement added - Cluster agent async endpoints + similarity transparency - Keyword search: relationship text extraction, priority ordering - Face fix handoff doc for Studio team
This commit is contained in:
+325
-71
@@ -1,12 +1,15 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
routing::post,
|
||||
routing::{get, post},
|
||||
Extension, Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::LazyLock;
|
||||
use std::time::Instant;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use super::middleware::UserAuth;
|
||||
use super::types::AppState;
|
||||
@@ -14,34 +17,111 @@ use crate::core::config::OUTPUT_DIR;
|
||||
use crate::core::db::schema;
|
||||
use crate::core::processor::{process_face_cluster, FaceClusterResult};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory job registry (one global, shared across requests)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static CLUSTER_JOB_REGISTRY: LazyLock<RwLock<HashMap<String, ClusterJobHandle>>> =
|
||||
LazyLock::new(|| RwLock::new(HashMap::new()));
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ClusterJobStatus {
|
||||
Running,
|
||||
Completed,
|
||||
Failed(String),
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
impl serde::Serialize for ClusterJobStatus {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
serializer.serialize_str(match self {
|
||||
ClusterJobStatus::Running => "running",
|
||||
ClusterJobStatus::Completed => "completed",
|
||||
ClusterJobStatus::Failed(_) => "failed",
|
||||
ClusterJobStatus::Cancelled => "cancelled",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ClusterJobHandle {
|
||||
pub file_uuid: String,
|
||||
pub similarity_threshold: f64,
|
||||
pub status: ClusterJobStatus,
|
||||
pub progress: f64,
|
||||
pub clusters: usize,
|
||||
pub total_traces: usize,
|
||||
pub created_at: Instant,
|
||||
pub cancel_token: tokio_util::sync::CancellationToken,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Request / Response types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ClusterAgentRequest {
|
||||
pub confirm: Option<bool>,
|
||||
pub similarity_threshold: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ClusterAgentResponse {
|
||||
success: bool,
|
||||
job_id: String,
|
||||
file_uuid: String,
|
||||
message: String,
|
||||
clusters: usize,
|
||||
total_traces: usize,
|
||||
status: String,
|
||||
similarity_threshold: f64,
|
||||
}
|
||||
|
||||
pub fn cluster_agent_routes() -> Router<AppState> {
|
||||
Router::new().route(
|
||||
"/api/v1/file/:file_uuid/cluster-agent",
|
||||
post(trigger_cluster_agent),
|
||||
)
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ClusterJobStatusResponse {
|
||||
job_id: String,
|
||||
file_uuid: String,
|
||||
status: String,
|
||||
progress: Option<f64>,
|
||||
message: Option<String>,
|
||||
clusters: usize,
|
||||
total_traces: usize,
|
||||
similarity_threshold: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct CancelJobResponse {
|
||||
success: bool,
|
||||
job_id: String,
|
||||
status: String,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Routes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub fn cluster_agent_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route(
|
||||
"/api/v1/file/:file_uuid/cluster-agent",
|
||||
post(trigger_cluster_agent),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/cluster-job/:job_id",
|
||||
get(get_cluster_job_status).delete(cancel_cluster_job),
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /api/v1/file/:file_uuid/cluster-agent (async, immediate 202)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub async fn trigger_cluster_agent(
|
||||
State(state): State<AppState>,
|
||||
Extension(_auth): Extension<UserAuth>,
|
||||
Path(file_uuid): Path<String>,
|
||||
Json(req): Json<ClusterAgentRequest>,
|
||||
) -> Result<Json<ClusterAgentResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
// Require explicit confirmation to prevent accidental reclustering
|
||||
if !req.confirm.unwrap_or(false) {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
@@ -52,6 +132,37 @@ pub async fn trigger_cluster_agent(
|
||||
})),
|
||||
));
|
||||
}
|
||||
|
||||
// Validate similarity_threshold
|
||||
let similarity_threshold = req.similarity_threshold.unwrap_or(0.65);
|
||||
if !(0.5..=0.95).contains(&similarity_threshold) {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "similarity_threshold must be between 0.5 and 0.95",
|
||||
"provided": similarity_threshold
|
||||
})),
|
||||
));
|
||||
}
|
||||
|
||||
// Check for existing running job for this file
|
||||
let registry = CLUSTER_JOB_REGISTRY.read().await;
|
||||
for (job_id, handle) in registry.iter() {
|
||||
if handle.file_uuid == file_uuid
|
||||
&& matches!(handle.status, ClusterJobStatus::Running)
|
||||
{
|
||||
return Ok(Json(ClusterAgentResponse {
|
||||
success: false,
|
||||
job_id: job_id.clone(),
|
||||
file_uuid,
|
||||
status: "running".to_string(),
|
||||
similarity_threshold: handle.similarity_threshold,
|
||||
}));
|
||||
}
|
||||
}
|
||||
drop(registry);
|
||||
|
||||
// Lookup video to get file_path + total_traces
|
||||
let videos_table = schema::table_name("videos");
|
||||
let row = sqlx::query(&format!(
|
||||
"SELECT file_path, COALESCE(total_frames, 0) as total_frames, COALESCE(fps, 25.0) as fps, probe_json FROM {} WHERE file_uuid = $1",
|
||||
@@ -102,18 +213,47 @@ pub async fn trigger_cluster_agent(
|
||||
}
|
||||
};
|
||||
|
||||
let total_traces = count_total_traces(&state, &file_uuid).await.unwrap_or(0);
|
||||
|
||||
let job_id = format!("cluster_{}_{}", file_uuid, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs());
|
||||
let output_path =
|
||||
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid));
|
||||
let cancel_token = tokio_util::sync::CancellationToken::new();
|
||||
|
||||
// Reset all trace_profiles names to default (Person_N) before re-clustering
|
||||
let traced_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_traced.json", file_uuid));
|
||||
// Register job
|
||||
let handle = ClusterJobHandle {
|
||||
file_uuid: file_uuid.clone(),
|
||||
similarity_threshold,
|
||||
status: ClusterJobStatus::Running,
|
||||
progress: 0.0,
|
||||
clusters: 0,
|
||||
total_traces,
|
||||
created_at: Instant::now(),
|
||||
cancel_token: cancel_token.clone(),
|
||||
};
|
||||
CLUSTER_JOB_REGISTRY
|
||||
.write()
|
||||
.await
|
||||
.insert(job_id.clone(), handle);
|
||||
|
||||
// Reset trace names before re-clustering
|
||||
let traced_path =
|
||||
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_traced.json", file_uuid));
|
||||
if let Ok(content) = std::fs::read_to_string(&traced_path) {
|
||||
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
if let Some(traces) = traced_data.get("traces") {
|
||||
let trace_list = if traces.is_object() {
|
||||
traces.as_object().map(|o| o.keys().filter_map(|k| k.parse::<i64>().ok()).collect::<Vec<_>>())
|
||||
traces.as_object().map(|o| {
|
||||
o.keys()
|
||||
.filter_map(|k| k.parse::<i64>().ok())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
} else if traces.is_array() {
|
||||
traces.as_array().map(|a| a.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect())
|
||||
traces.as_array().map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64()))
|
||||
.collect()
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -132,75 +272,184 @@ pub async fn trigger_cluster_agent(
|
||||
}
|
||||
tracing::info!(
|
||||
"[ClusterAgent] Reset {} trace names to default for {}",
|
||||
all_trace_ids.len(), file_uuid
|
||||
all_trace_ids.len(),
|
||||
file_uuid
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!("[ClusterAgent] Starting face clustering for {}", file_uuid);
|
||||
let result = process_face_cluster(
|
||||
&file_path,
|
||||
output_path.to_str().ok_or_else(|| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": "Invalid output path"})),
|
||||
// Spawn background clustering task
|
||||
let db_clone = state.db.clone();
|
||||
let file_uuid_clone = file_uuid.clone();
|
||||
let file_path_clone = file_path.clone();
|
||||
let output_path_clone = output_path.clone();
|
||||
let cancel_clone = cancel_token.clone();
|
||||
let job_id_clone = job_id.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
// Build frames list
|
||||
let frames = if total_frames > 0 {
|
||||
let fps_val = if fps > 0.0 { fps } else { 30.0 };
|
||||
Some(
|
||||
crate::core::processor::PythonExecutor::compute_8hz_frames(total_frames, fps_val),
|
||||
)
|
||||
})?,
|
||||
Some(&file_uuid),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[ClusterAgent] Clustering failed: {}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": format!("Clustering failed: {}", e)})),
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Run clustering with cancel support
|
||||
let result = process_face_cluster(
|
||||
&file_path_clone,
|
||||
output_path_clone.to_str().unwrap(),
|
||||
Some(&file_uuid_clone),
|
||||
frames.as_deref(),
|
||||
Some(similarity_threshold),
|
||||
)
|
||||
})?;
|
||||
.await;
|
||||
|
||||
update_trace_labels_from_cluster(&state, &file_uuid, &result)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[ClusterAgent] Failed to update trace labels: {}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": e.to_string()})),
|
||||
)
|
||||
})?;
|
||||
let mut registry = CLUSTER_JOB_REGISTRY.write().await;
|
||||
let handle = match registry.get_mut(&job_id_clone) {
|
||||
Some(h) => h,
|
||||
None => return, // cancelled and cleaned up
|
||||
};
|
||||
|
||||
let total_traces = count_total_traces(&state, &file_uuid).await.map_err(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": e.to_string()})),
|
||||
)
|
||||
})?;
|
||||
match result {
|
||||
Ok(cluster_result) => {
|
||||
// Check if cancelled during run
|
||||
if cancel_clone.is_cancelled() {
|
||||
// Don't apply results if cancelled
|
||||
let _ = registry.remove(&job_id_clone);
|
||||
return;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
"[ClusterAgent] Completed for {}: {} clusters, {} traces",
|
||||
file_uuid,
|
||||
result.clusters.len(),
|
||||
total_traces
|
||||
);
|
||||
// Update trace labels
|
||||
let _ = update_trace_labels_from_cluster(
|
||||
&db_clone,
|
||||
&file_uuid_clone,
|
||||
&cluster_result,
|
||||
)
|
||||
.await;
|
||||
|
||||
handle.status = ClusterJobStatus::Completed;
|
||||
handle.progress = 1.0;
|
||||
handle.clusters = cluster_result.clusters.len();
|
||||
tracing::info!(
|
||||
"[ClusterAgent] Completed for {}: {} clusters",
|
||||
file_uuid_clone,
|
||||
cluster_result.clusters.len()
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
if cancel_clone.is_cancelled() {
|
||||
handle.status = ClusterJobStatus::Cancelled;
|
||||
tracing::info!("[ClusterAgent] Cancelled for {}", file_uuid_clone);
|
||||
} else {
|
||||
handle.status = ClusterJobStatus::Failed(e.to_string());
|
||||
tracing::error!("[ClusterAgent] Failed for {}: {}", file_uuid_clone, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up registry after a short delay so GET can still fetch final status
|
||||
let job_id_for_cleanup = job_id_clone.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(300)).await;
|
||||
CLUSTER_JOB_REGISTRY.write().await.remove(&job_id_for_cleanup);
|
||||
});
|
||||
});
|
||||
|
||||
// Return 202 immediately
|
||||
Ok(Json(ClusterAgentResponse {
|
||||
success: true,
|
||||
job_id,
|
||||
file_uuid,
|
||||
message: "Clustering completed".to_string(),
|
||||
clusters: result.clusters.len(),
|
||||
total_traces,
|
||||
status: "running".to_string(),
|
||||
similarity_threshold,
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GET /api/v1/cluster-job/:job_id
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub async fn get_cluster_job_status(
|
||||
Path(job_id): Path<String>,
|
||||
) -> Result<Json<ClusterJobStatusResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let registry = CLUSTER_JOB_REGISTRY.read().await;
|
||||
let handle = registry.get(&job_id).ok_or_else(|| {
|
||||
(
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({"error": "Job not found"})),
|
||||
)
|
||||
})?;
|
||||
|
||||
let (status_str, message) = match &handle.status {
|
||||
ClusterJobStatus::Running => ("running".to_string(), Some("Clustering in progress".to_string())),
|
||||
ClusterJobStatus::Completed => ("completed".to_string(), None),
|
||||
ClusterJobStatus::Failed(msg) => ("failed".to_string(), Some(msg.clone())),
|
||||
ClusterJobStatus::Cancelled => ("cancelled".to_string(), Some("Job was cancelled".to_string())),
|
||||
};
|
||||
|
||||
Ok(Json(ClusterJobStatusResponse {
|
||||
job_id,
|
||||
file_uuid: handle.file_uuid.clone(),
|
||||
status: status_str,
|
||||
progress: if matches!(handle.status, ClusterJobStatus::Running) {
|
||||
Some(handle.progress)
|
||||
} else {
|
||||
Some(if matches!(handle.status, ClusterJobStatus::Completed) { 1.0 } else { handle.progress })
|
||||
},
|
||||
message,
|
||||
clusters: handle.clusters,
|
||||
total_traces: handle.total_traces,
|
||||
similarity_threshold: handle.similarity_threshold,
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DELETE /api/v1/cluster-job/:job_id (cancel)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub async fn cancel_cluster_job(
|
||||
Path(job_id): Path<String>,
|
||||
) -> Result<Json<CancelJobResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let mut registry = CLUSTER_JOB_REGISTRY.write().await;
|
||||
let handle = registry.get_mut(&job_id).ok_or_else(|| {
|
||||
(
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({"error": "Job not found or already finished"})),
|
||||
)
|
||||
})?;
|
||||
|
||||
if !matches!(handle.status, ClusterJobStatus::Running) {
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({"error": "Job not found or already finished"})),
|
||||
));
|
||||
}
|
||||
|
||||
// Trigger cancellation
|
||||
handle.cancel_token.cancel();
|
||||
handle.status = ClusterJobStatus::Cancelled;
|
||||
|
||||
Ok(Json(CancelJobResponse {
|
||||
success: true,
|
||||
job_id,
|
||||
status: "cancelled".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers (reused from original implementation)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async fn update_trace_labels_from_cluster(
|
||||
state: &AppState,
|
||||
db: &crate::core::db::PostgresDb,
|
||||
file_uuid: &str,
|
||||
result: &FaceClusterResult,
|
||||
) -> anyhow::Result<()> {
|
||||
// Build index: (frame, face_index) → real trace_id from face_traced.json
|
||||
// face_cluster.json's trace_id is cluster-internal (always 0), so we match
|
||||
// by frame number + array index to get the actual traced trace_id.
|
||||
let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str())
|
||||
.join(format!("{}.face_traced.json", file_uuid));
|
||||
let mut frame_face_to_trace: HashMap<(u64, usize), i64> = HashMap::new();
|
||||
@@ -233,11 +482,9 @@ async fn update_trace_labels_from_cluster(
|
||||
}
|
||||
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
|
||||
for (trace_id, cluster_id) in &trace_to_cluster {
|
||||
let external_id = format!("trace_{}", trace_id);
|
||||
let label = cluster_id.clone();
|
||||
|
||||
let rows_updated = sqlx::query(&format!(
|
||||
"UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND external_id = $3",
|
||||
tkg_table
|
||||
@@ -245,7 +492,7 @@ async fn update_trace_labels_from_cluster(
|
||||
.bind(&label)
|
||||
.bind(file_uuid)
|
||||
.bind(&external_id)
|
||||
.execute(state.db.pool())
|
||||
.execute(db.pool())
|
||||
.await?
|
||||
.rows_affected();
|
||||
|
||||
@@ -258,12 +505,12 @@ async fn update_trace_labels_from_cluster(
|
||||
.bind(&external_id)
|
||||
.bind(&label)
|
||||
.bind(serde_json::json!({"trace_id": trace_id}))
|
||||
.execute(state.db.pool())
|
||||
.execute(db.pool())
|
||||
.await?;
|
||||
}
|
||||
|
||||
let _ = schema::upsert_trace_profile(
|
||||
state.db.pool(),
|
||||
db.pool(),
|
||||
file_uuid,
|
||||
*trace_id as i32,
|
||||
&label,
|
||||
@@ -272,14 +519,13 @@ async fn update_trace_labels_from_cluster(
|
||||
.await;
|
||||
}
|
||||
|
||||
// Reset unclustered traces (not found in any cluster) to default Person_N
|
||||
if let Some(all_trace_ids) = get_all_trace_ids(file_uuid) {
|
||||
let mut updated_count = 0u64;
|
||||
for tid in &all_trace_ids {
|
||||
if !trace_to_cluster.contains_key(tid) {
|
||||
let name = format!("Person_{}", tid);
|
||||
let _ = schema::upsert_trace_profile(
|
||||
state.db.pool(),
|
||||
db.pool(),
|
||||
file_uuid,
|
||||
*tid as i32,
|
||||
&name,
|
||||
@@ -292,7 +538,8 @@ async fn update_trace_labels_from_cluster(
|
||||
if updated_count > 0 {
|
||||
tracing::info!(
|
||||
"[ClusterAgent] Updated {} unclustered trace names for {}",
|
||||
updated_count, file_uuid
|
||||
updated_count,
|
||||
file_uuid
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -315,13 +562,20 @@ fn get_all_trace_ids(file_uuid: &str) -> Option<Vec<i64>> {
|
||||
if let Some(obj) = traces.as_object() {
|
||||
Some(obj.keys().filter_map(|k| k.parse::<i64>().ok()).collect())
|
||||
} else if let Some(arr) = traces.as_array() {
|
||||
Some(arr.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect())
|
||||
Some(
|
||||
arr.iter()
|
||||
.filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64()))
|
||||
.collect(),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
async fn count_total_traces(state: &AppState, file_uuid: &str) -> anyhow::Result<usize> {
|
||||
async fn count_total_traces(
|
||||
state: &AppState,
|
||||
file_uuid: &str,
|
||||
) -> anyhow::Result<usize> {
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let count: (i64,) = sqlx::query_as(&format!(
|
||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND node_type = 'face_track'",
|
||||
|
||||
+45
-12
@@ -52,7 +52,10 @@ fn ffmpeg_cmd() -> std::process::Command {
|
||||
pub fn bbox_routes() -> Router<crate::api::types::AppState> {
|
||||
Router::new()
|
||||
.route("/api/v1/face-thumbnail", get(face_thumbnail_compat))
|
||||
.route("/api/v1/trace-thumb/:file_uuid/:trace_id", get(trace_thumbnail))
|
||||
.route(
|
||||
"/api/v1/trace-thumb/:file_uuid/:trace_id",
|
||||
get(trace_thumbnail),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/file/:file_uuid/video/bbox",
|
||||
get(bbox_overlay_video),
|
||||
@@ -711,16 +714,42 @@ async fn stream_video(
|
||||
|
||||
if has_range {
|
||||
let (start_sec, dur) = if let (Some(sf), Some(ef)) = (start_frame_param, end_frame_param) {
|
||||
let _fps: f64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COALESCE(fps, 24.0) FROM {} WHERE file_uuid = $1",
|
||||
videos_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.unwrap_or(24.0);
|
||||
(sf / _fps, ((ef - sf).max(0.0) + 1.0) / _fps)
|
||||
// Get fps from DB, but prefer actual fps from nb_frames/duration
|
||||
let (db_fps, nb_frames, duration): (f64, Option<String>, Option<f64>) =
|
||||
sqlx::query_as(&format!(
|
||||
"SELECT COALESCE(fps, 24.0) as fps,
|
||||
probe_json->'streams'->0->>'nb_frames' as nb_frames,
|
||||
duration
|
||||
FROM {} WHERE file_uuid = $1",
|
||||
videos_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.unwrap_or((24.0, None, None));
|
||||
|
||||
let actual_fps =
|
||||
if let (Some(nb), Some(dur)) = (&nb_frames, duration) {
|
||||
if let Ok(n) = nb.parse::<f64>() {
|
||||
if dur > 0.0 && n > 0.0 {
|
||||
let fps = n / dur;
|
||||
tracing::info!(
|
||||
"[stream_video] Using actual fps: {} / {} = {:.2} fps (stored: {:.2})",
|
||||
n, dur, fps, db_fps
|
||||
);
|
||||
fps
|
||||
} else {
|
||||
db_fps
|
||||
}
|
||||
} else {
|
||||
db_fps
|
||||
}
|
||||
} else {
|
||||
db_fps
|
||||
};
|
||||
|
||||
(sf / actual_fps, ((ef - sf).max(0.0) + 1.0) / actual_fps)
|
||||
} else if let (Some(st), Some(et)) = (start_time_param, end_time_param) {
|
||||
(st, et - st)
|
||||
} else if let (Some(s), Some(e)) = (start_legacy, end_legacy) {
|
||||
@@ -887,7 +916,11 @@ async fn trace_thumbnail(
|
||||
}
|
||||
|
||||
let bytes = tokio::fs::read(&key_face_path).await.map_err(|e| {
|
||||
tracing::warn!("[trace-thumb] Failed to read {}: {}", key_face_path.display(), e);
|
||||
tracing::warn!(
|
||||
"[trace-thumb] Failed to read {}: {}",
|
||||
key_face_path.display(),
|
||||
e
|
||||
);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
|
||||
+48
-1
@@ -1244,7 +1244,11 @@ pub async fn get_face_groups_handler(
|
||||
name,
|
||||
trace_count: trace_ids.len() as i32,
|
||||
representative_trace: trace_ids.first().copied().unwrap_or(0),
|
||||
trace_ids: if include_trace_ids { Some(trace_ids) } else { None },
|
||||
trace_ids: if include_trace_ids {
|
||||
Some(trace_ids)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
editable: true,
|
||||
})
|
||||
.collect();
|
||||
@@ -1279,6 +1283,13 @@ pub struct ClusterResultsFrame {
|
||||
pub faces: Vec<ClusterResultsFace>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
pub struct ClusterSimilarityInfo {
|
||||
pub min: f64,
|
||||
pub avg: f64,
|
||||
pub threshold: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ClusterResultsGroup {
|
||||
pub group_id: i32,
|
||||
@@ -1287,6 +1298,7 @@ pub struct ClusterResultsGroup {
|
||||
pub trace_ids: Vec<i32>,
|
||||
pub trace_count: i32,
|
||||
pub representative_trace: i32,
|
||||
pub similarity: Option<ClusterSimilarityInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -1345,6 +1357,38 @@ pub async fn get_cluster_results_handler(
|
||||
|
||||
// trace_id -> cluster_id mapping for frame faces
|
||||
let mut trace_to_cluster: HashMap<i32, i32> = HashMap::new();
|
||||
|
||||
// Load face_cluster.json for similarity data
|
||||
let cluster_similarity: HashMap<String, ClusterSimilarityInfo> = {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
|
||||
let mut map = HashMap::new();
|
||||
if let Ok(content) = std::fs::read_to_string(&fc_path) {
|
||||
if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
if let Some(clusters) = data.get("clusters").and_then(|c| c.as_array()) {
|
||||
for c in clusters {
|
||||
if let (Some(cid), Some(sim)) = (
|
||||
c.get("cluster_id").and_then(|v| v.as_str()),
|
||||
c.get("similarity"),
|
||||
) {
|
||||
if let (Some(min), Some(avg), Some(threshold)) = (
|
||||
sim.get("min").and_then(|v| v.as_f64()),
|
||||
sim.get("avg").and_then(|v| v.as_f64()),
|
||||
sim.get("threshold").and_then(|v| v.as_f64()),
|
||||
) {
|
||||
map.insert(
|
||||
cid.to_string(),
|
||||
ClusterSimilarityInfo { min, avg, threshold },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
map
|
||||
};
|
||||
|
||||
let face_groups: Vec<ClusterResultsGroup> = filtered_groups
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
@@ -1353,6 +1397,8 @@ pub async fn get_cluster_results_handler(
|
||||
for tid in &trace_ids {
|
||||
trace_to_cluster.insert(*tid, group_id);
|
||||
}
|
||||
// Try to find similarity data for this cluster
|
||||
let similarity = cluster_similarity.get(&name).cloned();
|
||||
ClusterResultsGroup {
|
||||
group_id,
|
||||
cluster_id: group_id,
|
||||
@@ -1360,6 +1406,7 @@ pub async fn get_cluster_results_handler(
|
||||
trace_count: trace_ids.len() as i32,
|
||||
representative_trace: trace_ids.first().copied().unwrap_or(0),
|
||||
trace_ids,
|
||||
similarity,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
+55
-8
@@ -1034,7 +1034,8 @@ async fn get_file_stats(
|
||||
let face_clusters = if std::path::Path::new(&face_cluster_path).exists() {
|
||||
if let Ok(content) = std::fs::read_to_string(&face_cluster_path) {
|
||||
if let Ok(cluster_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
cluster_data.get("clusters")
|
||||
cluster_data
|
||||
.get("clusters")
|
||||
.and_then(|c| c.as_array())
|
||||
.map(|a| a.len())
|
||||
.unwrap_or(0)
|
||||
@@ -1247,19 +1248,65 @@ async fn get_pipeline_progress_handler(
|
||||
if processors_done && tkg_node_count > 0 && tkg_edge_count == 0 {
|
||||
pp.update_stage("face_dedup", 1.0, "completed", Some("no faces".to_string()));
|
||||
pp.update_stage("tkg_edges", 1.0, "completed", Some("no faces".to_string()));
|
||||
pp.update_stage("rule2_ingestion", 1.0, "completed", Some("no faces".to_string()));
|
||||
}
|
||||
|
||||
// Check face dedup from face_cluster.json
|
||||
if processors_done && tkg_node_count > 0 {
|
||||
pp.update_stage(
|
||||
"face_dedup",
|
||||
"rule2_ingestion",
|
||||
1.0,
|
||||
"completed",
|
||||
Some(format!("{} tracks", tkg_node_count)),
|
||||
Some("no faces".to_string()),
|
||||
);
|
||||
}
|
||||
|
||||
// Check face dedup from actual face_cluster.json content
|
||||
if processors_done && tkg_node_count > 0 {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let face_cluster_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
|
||||
if std::path::Path::new(&face_cluster_path).exists() {
|
||||
if let Ok(content) = std::fs::read_to_string(&face_cluster_path) {
|
||||
if let Ok(cluster_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
let status = cluster_data
|
||||
.get("status")
|
||||
.and_then(|s| s.as_str())
|
||||
.unwrap_or("");
|
||||
let cluster_count = cluster_data
|
||||
.get("clusters")
|
||||
.and_then(|c| c.as_array())
|
||||
.map(|a| a.len())
|
||||
.unwrap_or(0);
|
||||
|
||||
match status {
|
||||
"has_faces" if cluster_count > 0 => {
|
||||
pp.update_stage(
|
||||
"face_dedup",
|
||||
1.0,
|
||||
"completed",
|
||||
Some(format!("{} persons", cluster_count)),
|
||||
);
|
||||
}
|
||||
"no_faces" | "no_face_json" | "no_embeddings" => {
|
||||
// Clustering ran but found nothing — mark as completed with reason
|
||||
pp.update_stage(
|
||||
"face_dedup",
|
||||
1.0,
|
||||
"completed",
|
||||
Some(format!("ran ({})", status)),
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
// File exists but status unclear — still mark as completed
|
||||
// (the clustering process has finished)
|
||||
pp.update_stage(
|
||||
"face_dedup",
|
||||
1.0,
|
||||
"completed",
|
||||
Some(format!("{} clusters", cluster_count)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Merge with Redis progress: Redis-completed stages override DB state
|
||||
if let Some(ref rp) = redis_progress {
|
||||
for redis_stage in &rp.stages {
|
||||
|
||||
+24
-11
@@ -183,9 +183,7 @@ pub async fn smart_search(
|
||||
let limit = hard_limit.min(page_size);
|
||||
|
||||
let (clean_query, source_filter) = parse_source_filter(&req.query);
|
||||
let chunk_type_filter = source_filter
|
||||
.as_deref()
|
||||
.map(source_filter_to_chunk_type);
|
||||
let chunk_type_filter = source_filter.as_deref().map(source_filter_to_chunk_type);
|
||||
|
||||
// 1. Generate embedding from clean query
|
||||
let embedder = Embedder::new("embeddinggemma-300m".to_string());
|
||||
@@ -235,7 +233,12 @@ pub async fn smart_search(
|
||||
|
||||
// 3. Keyword search via PG ILIKE
|
||||
let keyword_results: Vec<(String, String, f64)> = match db
|
||||
.search_bm25(&clean_query, req.file_uuid.as_deref(), chunk_type_filter, fetch_limit as i64)
|
||||
.search_bm25(
|
||||
&clean_query,
|
||||
req.file_uuid.as_deref(),
|
||||
chunk_type_filter,
|
||||
fetch_limit as i64,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(rows) => {
|
||||
@@ -624,16 +627,19 @@ pub async fn keyword_search(
|
||||
) -> Result<Json<SmartSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let db = &state.db;
|
||||
let page = req.page.unwrap_or(1).max(1);
|
||||
let limit = req.limit.unwrap_or(req.page_size.unwrap_or(5)).max(1);
|
||||
let limit = req.limit.unwrap_or(req.page_size.unwrap_or(50)).max(1);
|
||||
|
||||
let (clean_query, source_filter) = parse_source_filter(&req.query);
|
||||
let chunk_type_filter = source_filter
|
||||
.as_deref()
|
||||
.map(source_filter_to_chunk_type);
|
||||
let chunk_type_filter = source_filter.as_deref().map(source_filter_to_chunk_type);
|
||||
|
||||
// Keyword search via PG BM25
|
||||
let keyword_results = db
|
||||
.search_bm25(&clean_query, req.file_uuid.as_deref(), chunk_type_filter, limit as i64)
|
||||
.search_bm25(
|
||||
&clean_query,
|
||||
req.file_uuid.as_deref(),
|
||||
chunk_type_filter,
|
||||
limit as i64,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("Keyword search failed: {}", e);
|
||||
@@ -655,6 +661,13 @@ pub async fn keyword_search(
|
||||
.get_chunk_by_id_no_embedding(&row.file_uuid, &row.chunk_id)
|
||||
.await
|
||||
{
|
||||
// Use extracted text from BM25 result for relationships, otherwise use chunk's text_content
|
||||
let text = if p.chunk_type == "relationship" {
|
||||
row.text.clone().or_else(|| p.text_content.clone())
|
||||
} else {
|
||||
p.text_content.clone()
|
||||
};
|
||||
|
||||
results.push(SearchResult {
|
||||
id: 0,
|
||||
file_uuid: p.file_uuid.clone(),
|
||||
@@ -666,8 +679,8 @@ pub async fn keyword_search(
|
||||
start_time: p.start_time,
|
||||
end_time: p.end_time,
|
||||
raw_text: None,
|
||||
summary: Some(p.summary.clone()),
|
||||
text_content: p.text_content.clone(),
|
||||
summary: text.clone(),
|
||||
text_content: text,
|
||||
metadata: p.metadata.clone(),
|
||||
similarity: Some(row.bm25_score as f64),
|
||||
file_name: None,
|
||||
|
||||
+61
-17
@@ -268,10 +268,7 @@ pub async fn search_people(
|
||||
})?;
|
||||
|
||||
let total = people.len();
|
||||
Ok(Json(PeopleSearchResponse {
|
||||
people,
|
||||
total,
|
||||
}))
|
||||
Ok(Json(PeopleSearchResponse { people, total }))
|
||||
}
|
||||
|
||||
// --- Internal search functions ---
|
||||
@@ -631,19 +628,44 @@ async fn search_persons_internal(
|
||||
let safe = fuuid.replace('\'', "''");
|
||||
sql.push_str(&format!(" AND tp.file_uuid = '{}'", safe));
|
||||
}
|
||||
sql.push_str(&format!(" ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}", req.page_size.unwrap_or(20)));
|
||||
sql.push_str(&format!(
|
||||
" ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}",
|
||||
req.page_size.unwrap_or(20)
|
||||
));
|
||||
|
||||
let rows: Vec<(String, i32, Option<String>, Option<i64>, Option<i64>, Option<i32>,
|
||||
Option<String>, Option<String>, Option<f64>, Option<String>)> =
|
||||
sqlx::query_as(&sql).fetch_all(db.pool()).await?;
|
||||
let rows: Vec<(
|
||||
String,
|
||||
i32,
|
||||
Option<String>,
|
||||
Option<i64>,
|
||||
Option<i64>,
|
||||
Option<i32>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<f64>,
|
||||
Option<String>,
|
||||
)> = sqlx::query_as(&sql).fetch_all(db.pool()).await?;
|
||||
|
||||
let q_lower = req.query.to_lowercase();
|
||||
let mut results: Vec<SearchResult> = Vec::new();
|
||||
for (fuuid, trace_id, name, start_frame, end_frame, frame_count,
|
||||
key_frame, key_face, avg_confidence, external_id) in rows
|
||||
for (
|
||||
fuuid,
|
||||
trace_id,
|
||||
name,
|
||||
start_frame,
|
||||
end_frame,
|
||||
frame_count,
|
||||
key_frame,
|
||||
key_face,
|
||||
avg_confidence,
|
||||
external_id,
|
||||
) in rows
|
||||
{
|
||||
let name_match = !req.query.is_empty()
|
||||
&& name.as_deref().map(|n| n.to_lowercase().contains(&q_lower)).unwrap_or(false);
|
||||
&& name
|
||||
.as_deref()
|
||||
.map(|n| n.to_lowercase().contains(&q_lower))
|
||||
.unwrap_or(false);
|
||||
let score = if name_match { 0.95 } else { 0.5 };
|
||||
|
||||
results.push(SearchResult::Person {
|
||||
@@ -782,15 +804,37 @@ async fn search_people_by_query(
|
||||
let safe = fuuid.replace('\'', "''");
|
||||
sql.push_str(&format!(" AND tp.file_uuid = '{}'", safe));
|
||||
}
|
||||
sql.push_str(&format!(" ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}", limit));
|
||||
sql.push_str(&format!(
|
||||
" ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}",
|
||||
limit
|
||||
));
|
||||
|
||||
let rows: Vec<(String, i32, Option<String>, Option<i64>, Option<i64>, Option<i32>,
|
||||
Option<String>, Option<String>, Option<f64>, Option<String>)> =
|
||||
sqlx::query_as(&sql).fetch_all(db.pool()).await?;
|
||||
let rows: Vec<(
|
||||
String,
|
||||
i32,
|
||||
Option<String>,
|
||||
Option<i64>,
|
||||
Option<i64>,
|
||||
Option<i32>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<f64>,
|
||||
Option<String>,
|
||||
)> = sqlx::query_as(&sql).fetch_all(db.pool()).await?;
|
||||
|
||||
let mut results: Vec<PeopleResult> = Vec::new();
|
||||
for (fuuid, trace_id, name, start_frame, end_frame, frame_count,
|
||||
key_frame, key_face, avg_confidence, external_id) in rows
|
||||
for (
|
||||
fuuid,
|
||||
trace_id,
|
||||
name,
|
||||
start_frame,
|
||||
end_frame,
|
||||
frame_count,
|
||||
key_frame,
|
||||
key_face,
|
||||
avg_confidence,
|
||||
external_id,
|
||||
) in rows
|
||||
{
|
||||
results.push(PeopleResult {
|
||||
file_uuid: fuuid,
|
||||
|
||||
@@ -22,7 +22,7 @@ async fn main() -> Result<()> {
|
||||
)
|
||||
GROUP BY pc.file_uuid, v.fps
|
||||
ORDER BY COUNT(*) DESC
|
||||
"#
|
||||
"#,
|
||||
)
|
||||
.fetch_all(db.pool())
|
||||
.await?;
|
||||
|
||||
@@ -4,114 +4,112 @@ use std::time::{Duration, Instant};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
dotenv::from_filename("/Users/accusys/momentry_core_0.1/.env.development").ok();
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let pg = PostgresDb::init()
|
||||
.await
|
||||
.context("Failed to init PostgreSQL")?;
|
||||
let qdrant = QdrantDb::new();
|
||||
let embedder = Embedder::new("embeddinggemma-300m".to_string());
|
||||
|
||||
let uuid = "63acd3bb02b5b9dfbb9d6db499fcc864";
|
||||
let chunk_table = momentry_core::core::db::schema::table_name("chunk");
|
||||
|
||||
let rows = sqlx::query_as::<_, (String, String, i64, i64, f64, f64, String)>(&format!(
|
||||
"SELECT chunk_id, text_content, start_frame, end_frame, \
|
||||
start_time, end_time, content::text \
|
||||
// Get all files with unembedded sentence chunks
|
||||
let files: Vec<(String,)> = sqlx::query_as(&format!(
|
||||
"SELECT DISTINCT file_uuid FROM {} \
|
||||
WHERE chunk_type = 'sentence' AND embedding IS NULL \
|
||||
AND text_content IS NOT NULL AND text_content != ''",
|
||||
chunk_table
|
||||
))
|
||||
.fetch_all(pg.pool())
|
||||
.await?;
|
||||
|
||||
println!(
|
||||
"Found {} files with unembedded sentence chunks",
|
||||
files.len()
|
||||
);
|
||||
|
||||
let start = Instant::now();
|
||||
let mut total_stored = 0usize;
|
||||
let mut total_errors = 0usize;
|
||||
let mut total_chunks = 0usize;
|
||||
|
||||
for (file_uuid,) in &files {
|
||||
let rows: Vec<(String, String, i64, i64, f64, f64)> = sqlx::query_as(&format!(
|
||||
"SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time \
|
||||
FROM {} \
|
||||
WHERE file_uuid = $1 \
|
||||
AND chunk_type = 'sentence' \
|
||||
AND embedding IS NULL \
|
||||
AND (text_content IS NOT NULL AND text_content != '') \
|
||||
AND text_content IS NOT NULL AND text_content != '' \
|
||||
ORDER BY id",
|
||||
chunk_table
|
||||
))
|
||||
.bind(uuid)
|
||||
.fetch_all(pg.pool())
|
||||
.await?;
|
||||
chunk_table
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.fetch_all(pg.pool())
|
||||
.await?;
|
||||
|
||||
let total = rows.len();
|
||||
println!(
|
||||
"Found {} sentence chunks without embedding for {}",
|
||||
total, uuid
|
||||
);
|
||||
let count = rows.len();
|
||||
total_chunks += count;
|
||||
println!(" {}: {} chunks to vectorize", file_uuid, count);
|
||||
|
||||
if total == 0 {
|
||||
println!("Nothing to vectorize. Exiting.");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let start = Instant::now();
|
||||
let mut stored = 0usize;
|
||||
let mut errors = 0usize;
|
||||
|
||||
for (chunk_id, text, start_frame, end_frame, start_time, end_time, _content_str) in &rows {
|
||||
if text.is_empty() {
|
||||
if count == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
match embedder.embed_document(text).await {
|
||||
Ok(vector) => {
|
||||
if let Err(e) = pg.store_vector(chunk_id, &vector, uuid).await {
|
||||
eprintln!("[ERROR] PG store failed for {}: {}", chunk_id, e);
|
||||
errors += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let payload = VectorPayload {
|
||||
file_uuid: uuid.to_string(),
|
||||
chunk_id: chunk_id.clone(),
|
||||
chunk_type: "sentence".to_string(),
|
||||
start_frame: *start_frame,
|
||||
end_frame: *end_frame,
|
||||
start_time: *start_time,
|
||||
end_time: *end_time,
|
||||
text: Some(text.clone()),
|
||||
};
|
||||
|
||||
if let Err(e) = qdrant.upsert_vector(chunk_id, &vector, payload).await {
|
||||
eprintln!("[ERROR] Qdrant upsert failed for {}: {}", chunk_id, e);
|
||||
errors += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
stored += 1;
|
||||
if stored % 500 == 0 || stored == total {
|
||||
let elapsed = start.elapsed();
|
||||
let rate = stored as f64 / elapsed.as_secs_f64();
|
||||
let eta = if stored < total {
|
||||
let remaining = Duration::from_secs_f64((total - stored) as f64 / rate);
|
||||
format!(" (ETA: {}s)", remaining.as_secs())
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
println!(
|
||||
" [{}/{}] {:.1}% done | {:.0} vec/s | {} errors{}",
|
||||
stored,
|
||||
total,
|
||||
100.0 * stored as f64 / total as f64,
|
||||
rate,
|
||||
errors,
|
||||
eta,
|
||||
);
|
||||
}
|
||||
for (chunk_id, text, start_frame, end_frame, start_time, end_time) in &rows {
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[ERROR] Embedding failed for {}: {}", chunk_id, e);
|
||||
errors += 1;
|
||||
|
||||
match embedder.embed_document(text).await {
|
||||
Ok(vector) => {
|
||||
if let Err(e) = pg.store_vector(&chunk_id, &vector, file_uuid).await {
|
||||
eprintln!("[ERROR] PG store failed for {}: {}", chunk_id, e);
|
||||
total_errors += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let payload = VectorPayload {
|
||||
file_uuid: file_uuid.clone(),
|
||||
chunk_id: chunk_id.clone(),
|
||||
chunk_type: "sentence".to_string(),
|
||||
start_frame: *start_frame,
|
||||
end_frame: *end_frame,
|
||||
start_time: *start_time,
|
||||
end_time: *end_time,
|
||||
text: Some(text.clone()),
|
||||
};
|
||||
|
||||
if let Err(e) = qdrant.upsert_vector(&chunk_id, &vector, payload).await {
|
||||
eprintln!("[ERROR] Qdrant upsert failed for {}: {}", chunk_id, e);
|
||||
total_errors += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
total_stored += 1;
|
||||
if total_stored % 500 == 0 {
|
||||
let elapsed = start.elapsed();
|
||||
let rate = total_stored as f64 / elapsed.as_secs_f64();
|
||||
println!(
|
||||
" [{}/{}] {:.1} vec/s | {} errors",
|
||||
total_stored, total_chunks, rate, total_errors
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[ERROR] Embedding failed for {}: {}", chunk_id, e);
|
||||
total_errors += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let elapsed = start.elapsed();
|
||||
println!(
|
||||
"\nDone! {}/{} vectors stored ({} errors) in {:.1}s ({:.0} vec/s avg)",
|
||||
stored,
|
||||
total,
|
||||
errors,
|
||||
"\nDone! {}/{} vectors stored ({} errors) in {:.1}s",
|
||||
total_stored,
|
||||
total_chunks,
|
||||
total_errors,
|
||||
elapsed.as_secs_f64(),
|
||||
stored as f64 / elapsed.as_secs_f64(),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
|
||||
+85
-67
@@ -563,7 +563,12 @@ pub async fn exec_smart_search(
|
||||
.filter(|s| !s.is_empty() && *s != "<nil>" && *s != "null");
|
||||
let limit = args.get("limit").and_then(|v| v.as_i64()).unwrap_or(5) as i64;
|
||||
|
||||
tracing::info!("[smart_search] query='{}', file_uuid={:?}, limit={}", query, file_uuid, limit);
|
||||
tracing::info!(
|
||||
"[smart_search] query='{}', file_uuid={:?}, limit={}",
|
||||
query,
|
||||
file_uuid,
|
||||
limit
|
||||
);
|
||||
|
||||
let chunk_table = schema::table_name("chunk");
|
||||
let videos = schema::table_name("videos");
|
||||
@@ -619,7 +624,17 @@ pub async fn exec_smart_search(
|
||||
let cards: Vec<serde_json::Value> = rows
|
||||
.into_iter()
|
||||
.map(
|
||||
|(chunk_id, text_content, start_frame, end_frame, chunk_type, content, fuuid, file_name, fps)| {
|
||||
|(
|
||||
chunk_id,
|
||||
text_content,
|
||||
start_frame,
|
||||
end_frame,
|
||||
chunk_type,
|
||||
content,
|
||||
fuuid,
|
||||
file_name,
|
||||
fps,
|
||||
)| {
|
||||
let source = if let Some(ref c) = content {
|
||||
let text = c.get("text").and_then(|t| t.as_str()).unwrap_or("");
|
||||
let ocr_text = c.get("ocr_text").and_then(|t| t.as_str()).unwrap_or("");
|
||||
@@ -641,8 +656,16 @@ pub async fn exec_smart_search(
|
||||
.map(|t| t.chars().take(150).collect::<String>())
|
||||
.unwrap_or_default();
|
||||
|
||||
let start_time = if fps > 0.0 { start_frame as f64 / fps } else { 0.0 };
|
||||
let end_time = if fps > 0.0 { end_frame as f64 / fps } else { 0.0 };
|
||||
let start_time = if fps > 0.0 {
|
||||
start_frame as f64 / fps
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let end_time = if fps > 0.0 {
|
||||
end_frame as f64 / fps
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
serde_json::json!({
|
||||
"card_type": "chunk",
|
||||
@@ -667,7 +690,8 @@ pub async fn exec_smart_search(
|
||||
"query": query,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
}).to_string())
|
||||
})
|
||||
.to_string())
|
||||
}
|
||||
|
||||
pub async fn exec_identity_text(
|
||||
@@ -1467,15 +1491,13 @@ pub async fn exec_trace_search(
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(
|
||||
serde_json::json!({
|
||||
"tool": "trace_search",
|
||||
"query": query,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
Ok(serde_json::json!({
|
||||
"tool": "trace_search",
|
||||
"query": query,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
})
|
||||
.to_string())
|
||||
}
|
||||
|
||||
/// Semantic search using embedding + Qdrant
|
||||
@@ -1495,7 +1517,12 @@ pub async fn exec_semantic_search(
|
||||
.unwrap_or(10)
|
||||
.min(50) as usize;
|
||||
|
||||
tracing::info!("[exec_semantic_search] query='{}', file_uuid={:?}, limit={}", query, file_uuid, limit);
|
||||
tracing::info!(
|
||||
"[exec_semantic_search] query='{}', file_uuid={:?}, limit={}",
|
||||
query,
|
||||
file_uuid,
|
||||
limit
|
||||
);
|
||||
|
||||
if query.is_empty() {
|
||||
return Err("query is required".to_string());
|
||||
@@ -1503,15 +1530,15 @@ pub async fn exec_semantic_search(
|
||||
|
||||
// Generate embedding
|
||||
let embedder = Embedder::new("embeddinggemma-300m".to_string());
|
||||
let embedding = embedder
|
||||
.embed_query(query)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[exec_semantic_search] Embedding failed: {}", e);
|
||||
format!("Embedding failed: {}", e)
|
||||
})?;
|
||||
let embedding = embedder.embed_query(query).await.map_err(|e| {
|
||||
tracing::error!("[exec_semantic_search] Embedding failed: {}", e);
|
||||
format!("Embedding failed: {}", e)
|
||||
})?;
|
||||
|
||||
tracing::info!("[exec_semantic_search] Embedding generated, dim={}", embedding.len());
|
||||
tracing::info!(
|
||||
"[exec_semantic_search] Embedding generated, dim={}",
|
||||
embedding.len()
|
||||
);
|
||||
|
||||
// Search Qdrant
|
||||
let qdrant = QdrantDb::new();
|
||||
@@ -1526,16 +1553,16 @@ pub async fn exec_semantic_search(
|
||||
})?
|
||||
} else {
|
||||
tracing::info!("[exec_semantic_search] Searching all collections");
|
||||
qdrant
|
||||
.search(&embedding, limit)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[exec_semantic_search] Qdrant search failed: {}", e);
|
||||
format!("Qdrant search failed: {}", e)
|
||||
})?
|
||||
qdrant.search(&embedding, limit).await.map_err(|e| {
|
||||
tracing::error!("[exec_semantic_search] Qdrant search failed: {}", e);
|
||||
format!("Qdrant search failed: {}", e)
|
||||
})?
|
||||
};
|
||||
|
||||
tracing::info!("[exec_semantic_search] Qdrant returned {} hits", search_results.len());
|
||||
tracing::info!(
|
||||
"[exec_semantic_search] Qdrant returned {} hits",
|
||||
search_results.len()
|
||||
);
|
||||
|
||||
// Enrich from PostgreSQL
|
||||
let chunk_table = schema::table_name("chunk");
|
||||
@@ -1543,29 +1570,24 @@ pub async fn exec_semantic_search(
|
||||
|
||||
let mut cards = Vec::new();
|
||||
for hit in search_results.iter() {
|
||||
let row: Option<(
|
||||
String,
|
||||
String,
|
||||
f64,
|
||||
f64,
|
||||
f64,
|
||||
Option<String>,
|
||||
String,
|
||||
)> = sqlx::query_as(&format!(
|
||||
"SELECT c.chunk_id, c.chunk_type, c.start_time, c.end_time, c.fps, \
|
||||
let row: Option<(String, String, f64, f64, f64, Option<String>, String)> =
|
||||
sqlx::query_as(&format!(
|
||||
"SELECT c.chunk_id, c.chunk_type, c.start_time, c.end_time, c.fps, \
|
||||
c.text_content, v.file_name \
|
||||
FROM {} c \
|
||||
JOIN {} v ON v.file_uuid = c.file_uuid \
|
||||
WHERE c.file_uuid = $1 AND c.chunk_id = $2",
|
||||
chunk_table, videos
|
||||
))
|
||||
.bind(&hit.uuid)
|
||||
.bind(&hit.chunk_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|e| format!("PG query failed: {}", e))?;
|
||||
chunk_table, videos
|
||||
))
|
||||
.bind(&hit.uuid)
|
||||
.bind(&hit.chunk_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|e| format!("PG query failed: {}", e))?;
|
||||
|
||||
if let Some((chunk_id, chunk_type, start_time, end_time, fps, text_content, file_name)) = row {
|
||||
if let Some((chunk_id, chunk_type, start_time, end_time, fps, text_content, file_name)) =
|
||||
row
|
||||
{
|
||||
let start_frame = (start_time * fps) as i64;
|
||||
let end_frame = (end_time * fps) as i64;
|
||||
let text_preview = text_content
|
||||
@@ -1590,15 +1612,13 @@ pub async fn exec_semantic_search(
|
||||
}
|
||||
}
|
||||
|
||||
Ok(
|
||||
serde_json::json!({
|
||||
"tool": "semantic_search",
|
||||
"query": query,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
Ok(serde_json::json!({
|
||||
"tool": "semantic_search",
|
||||
"query": query,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
})
|
||||
.to_string())
|
||||
}
|
||||
|
||||
/// Search named face profiles by name — finds face_track TKG nodes whose label
|
||||
@@ -1685,13 +1705,11 @@ pub async fn exec_face_profile_search(
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(
|
||||
serde_json::json!({
|
||||
"tool": "face_profile_search",
|
||||
"query": name,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
Ok(serde_json::json!({
|
||||
"tool": "face_profile_search",
|
||||
"query": name,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
})
|
||||
.to_string())
|
||||
}
|
||||
|
||||
+80
-17
@@ -891,6 +891,34 @@ pub struct ChildChunkResult {
|
||||
pub speaker_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// Extract actual text content from a relationship chunk's content JSON.
|
||||
/// Returns the related sentence text if found, otherwise falls back to empty string.
|
||||
fn extract_relationship_text(content_json: &str) -> String {
|
||||
if let Ok(json) = serde_json::from_str::<serde_json::Value>(content_json) {
|
||||
if let Some(target) = json.get("target_node") {
|
||||
if let Some(label) = target.get("label").and_then(|v| v.as_str()) {
|
||||
if let Some(pos) = label.find(':') {
|
||||
let text_part = label[pos + 1..].trim();
|
||||
if !text_part.is_empty() {
|
||||
return text_part.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(source) = json.get("source_node") {
|
||||
if let Some(label) = source.get("label").and_then(|v| v.as_str()) {
|
||||
if let Some(pos) = label.find(':') {
|
||||
let text_part = label[pos + 1..].trim();
|
||||
if !text_part.is_empty() {
|
||||
return text_part.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
impl PostgresDb {
|
||||
pub fn from_pool(pool: PgPool) -> Self {
|
||||
Self {
|
||||
@@ -1240,8 +1268,14 @@ impl PostgresDb {
|
||||
|
||||
// ── Trace Profiles (VLM metadata for face traces) ──
|
||||
sqlx::query("CREATE TABLE IF NOT EXISTS trace_profiles (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, trace_id INTEGER NOT NULL, name VARCHAR(255), start_frame BIGINT, end_frame BIGINT, frame_count INTEGER, key_frame VARCHAR(255), key_face VARCHAR(255), status VARCHAR(50) DEFAULT 'pending', avg_confidence DOUBLE PRECISION, vlm_description TEXT, vlm_clothing TEXT, vlm_tags TEXT[], vlm_location VARCHAR(255), vlm_setting VARCHAR(255), vlm_lighting VARCHAR(100), vlm_weather VARCHAR(100), vlm_hand_objects TEXT, vlm_has_plants BOOLEAN, vlm_has_animals BOOLEAN, vlm_background TEXT, vlm_bg_tags TEXT[], vlm_model VARCHAR(64), metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?;
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_file_uuid ON trace_profiles(file_uuid)").execute(pool).await?;
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_name ON trace_profiles(name)").execute(pool).await?;
|
||||
sqlx::query(
|
||||
"CREATE INDEX IF NOT EXISTS idx_trace_profiles_file_uuid ON trace_profiles(file_uuid)",
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_name ON trace_profiles(name)")
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_tags ON trace_profiles USING GIN(vlm_tags)").execute(pool).await?;
|
||||
|
||||
// ── Cuts ──
|
||||
@@ -3508,7 +3542,10 @@ impl PostgresDb {
|
||||
use sqlx::Row;
|
||||
|
||||
// Build WHERE clauses dynamically to handle optional params
|
||||
let mut clauses = vec!["text_content ILIKE $2".to_string(), "text_content != ''".to_string()];
|
||||
let mut clauses = vec![
|
||||
"(text_content ILIKE $2 OR content::text ILIKE $2)".to_string(),
|
||||
"COALESCE(text_content, content::text, '') != ''".to_string(),
|
||||
];
|
||||
let mut next_idx = 3;
|
||||
if file_uuid.is_some() {
|
||||
next_idx += 1;
|
||||
@@ -3522,11 +3559,22 @@ impl PostgresDb {
|
||||
let where_sql = clauses.join(" AND ");
|
||||
|
||||
let sql = format!(
|
||||
"SELECT chunk_id, file_uuid, chunk_type, text_content, start_time, end_time, \
|
||||
(1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8))::float8 as score \
|
||||
"SELECT chunk_id, file_uuid, chunk_type, text_content, content::text as content_text, start_time, end_time, \
|
||||
CASE \
|
||||
WHEN text_content ILIKE $2 THEN \
|
||||
(1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8)) \
|
||||
ELSE \
|
||||
(1.0 - (POSITION(LOWER($1) IN LOWER(content::text))::float8 / NULLIF(LENGTH(content::text), 0)::float8)) \
|
||||
END::float8 as score, \
|
||||
CASE chunk_type \
|
||||
WHEN 'sentence' THEN 1 \
|
||||
WHEN 'ocr' THEN 2 \
|
||||
WHEN 'cut' THEN 3 \
|
||||
ELSE 4 \
|
||||
END as priority \
|
||||
FROM {} \
|
||||
WHERE {} \
|
||||
ORDER BY score DESC \
|
||||
ORDER BY priority ASC, score DESC \
|
||||
LIMIT $3",
|
||||
table, where_sql
|
||||
);
|
||||
@@ -3542,17 +3590,32 @@ impl PostgresDb {
|
||||
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| Bm25Result {
|
||||
file_uuid: r.get("file_uuid"),
|
||||
chunk_id: r.get("chunk_id"),
|
||||
chunk_type: r.get("chunk_type"),
|
||||
uuid: r.get("file_uuid"),
|
||||
text: r.get("text_content"),
|
||||
start_time: r.get("start_time"),
|
||||
end_time: r.get("end_time"),
|
||||
bm25_score: r.get("score"),
|
||||
vector_score: 0.0,
|
||||
combined_score: r.get("score"),
|
||||
.map(|r| {
|
||||
let chunk_type: String = r.get("chunk_type");
|
||||
let text: Option<String> = if chunk_type == "relationship" {
|
||||
let content_text: String = r.get("content_text");
|
||||
let extracted = extract_relationship_text(&content_text);
|
||||
if extracted.is_empty() {
|
||||
r.get("text_content")
|
||||
} else {
|
||||
Some(extracted)
|
||||
}
|
||||
} else {
|
||||
r.get("text_content")
|
||||
};
|
||||
|
||||
Bm25Result {
|
||||
file_uuid: r.get("file_uuid"),
|
||||
chunk_id: r.get("chunk_id"),
|
||||
chunk_type: r.get("chunk_type"),
|
||||
uuid: r.get("file_uuid"),
|
||||
text,
|
||||
start_time: r.get("start_time"),
|
||||
end_time: r.get("end_time"),
|
||||
bm25_score: r.get("score"),
|
||||
vector_score: 0.0,
|
||||
combined_score: r.get("score"),
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
+105
-67
@@ -96,7 +96,13 @@ pub struct IngestionState {
|
||||
pub const STAGE_1_PROCESSORS: &[&str] = &["asr", "ocr", "face"];
|
||||
|
||||
/// Stage 2 processors (depend on stage 1)
|
||||
pub const STAGE_2_PROCESSORS: &[&str] = &["asrx", "face_vector", "face_trace", "speaker_vector", "face_cluster"];
|
||||
pub const STAGE_2_PROCESSORS: &[&str] = &[
|
||||
"asrx",
|
||||
"face_vector",
|
||||
"face_trace",
|
||||
"speaker_vector",
|
||||
"face_cluster",
|
||||
];
|
||||
|
||||
/// Stage 3 processors (depend on stage 2 or face)
|
||||
pub const STAGE_3_PROCESSORS: &[&str] = &["pose", "appearance"];
|
||||
@@ -104,9 +110,16 @@ pub const STAGE_3_PROCESSORS: &[&str] = &["pose", "appearance"];
|
||||
/// All processors in order
|
||||
pub const ALL_PROCESSORS: &[&str] = &[
|
||||
"cut", // Registration
|
||||
"asr", "ocr", "face", // Stage 1
|
||||
"asrx", "face_vector", "face_trace", "speaker_vector", "face_cluster", // Stage 2
|
||||
"pose", "appearance", // Stage 3
|
||||
"asr",
|
||||
"ocr",
|
||||
"face", // Stage 1
|
||||
"asrx",
|
||||
"face_vector",
|
||||
"face_trace",
|
||||
"speaker_vector",
|
||||
"face_cluster", // Stage 2
|
||||
"pose",
|
||||
"appearance", // Stage 3
|
||||
];
|
||||
|
||||
/// Get processor dependencies
|
||||
@@ -140,22 +153,22 @@ impl FileLifecycle {
|
||||
/// Create a new lifecycle for a file
|
||||
pub fn new(file_uuid: &str) -> Self {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
|
||||
let mut stage_1_processors = HashMap::new();
|
||||
for proc in STAGE_1_PROCESSORS {
|
||||
stage_1_processors.insert(proc.to_string(), ProcessorState::new("pending"));
|
||||
}
|
||||
|
||||
|
||||
let mut stage_2_processors = HashMap::new();
|
||||
for proc in STAGE_2_PROCESSORS {
|
||||
stage_2_processors.insert(proc.to_string(), ProcessorState::new("pending"));
|
||||
}
|
||||
|
||||
|
||||
let mut stage_3_processors = HashMap::new();
|
||||
for proc in STAGE_3_PROCESSORS {
|
||||
stage_3_processors.insert(proc.to_string(), ProcessorState::new("pending"));
|
||||
}
|
||||
|
||||
|
||||
Self {
|
||||
version: LIFECYCLE_VERSION.to_string(),
|
||||
file_uuid: file_uuid.to_string(),
|
||||
@@ -185,16 +198,22 @@ impl FileLifecycle {
|
||||
/// Create lifecycle from existing outputs (for recovery)
|
||||
pub fn from_existing_outputs(output_dir: &str, file_uuid: &str) -> Self {
|
||||
let mut lifecycle = Self::new(file_uuid);
|
||||
|
||||
|
||||
// Check registration outputs
|
||||
let has_profile = Path::new(output_dir).join(format!("{}.profile.json", file_uuid)).exists();
|
||||
let has_probe = Path::new(output_dir).join(format!("{}.probe.json", file_uuid)).exists();
|
||||
let has_cut = Path::new(output_dir).join(format!("{}.cut.json", file_uuid)).exists();
|
||||
|
||||
let has_profile = Path::new(output_dir)
|
||||
.join(format!("{}.profile.json", file_uuid))
|
||||
.exists();
|
||||
let has_probe = Path::new(output_dir)
|
||||
.join(format!("{}.probe.json", file_uuid))
|
||||
.exists();
|
||||
let has_cut = Path::new(output_dir)
|
||||
.join(format!("{}.cut.json", file_uuid))
|
||||
.exists();
|
||||
|
||||
if has_profile && has_probe && has_cut {
|
||||
lifecycle.mark_stage_completed("registration");
|
||||
}
|
||||
|
||||
|
||||
// Check stage 1 processors
|
||||
for proc in STAGE_1_PROCESSORS {
|
||||
let path = Path::new(output_dir).join(format!("{}.{}.json", file_uuid, proc));
|
||||
@@ -202,33 +221,41 @@ impl FileLifecycle {
|
||||
lifecycle.mark_processor_completed(proc, None);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Check stage 2 processors
|
||||
let has_asrx = Path::new(output_dir).join(format!("{}.asrx.json", file_uuid)).exists();
|
||||
let has_asrx = Path::new(output_dir)
|
||||
.join(format!("{}.asrx.json", file_uuid))
|
||||
.exists();
|
||||
if has_asrx {
|
||||
lifecycle.mark_processor_completed("asrx", None);
|
||||
// speaker_vector comes from asrx
|
||||
lifecycle.mark_processor_completed("speaker_vector", None);
|
||||
}
|
||||
|
||||
|
||||
// face_vector: check if face.json exists (vectors stored in Qdrant)
|
||||
let has_face = Path::new(output_dir).join(format!("{}.face.json", file_uuid)).exists();
|
||||
let has_face = Path::new(output_dir)
|
||||
.join(format!("{}.face.json", file_uuid))
|
||||
.exists();
|
||||
if has_face {
|
||||
lifecycle.mark_processor_completed("face_vector", None);
|
||||
}
|
||||
|
||||
|
||||
// face_trace: check face_traced.json (continuous face tracking)
|
||||
let has_face_traced = Path::new(output_dir).join(format!("{}.face_traced.json", file_uuid)).exists();
|
||||
let has_face_traced = Path::new(output_dir)
|
||||
.join(format!("{}.face_traced.json", file_uuid))
|
||||
.exists();
|
||||
if has_face_traced {
|
||||
lifecycle.mark_processor_completed("face_trace", None);
|
||||
}
|
||||
|
||||
|
||||
// face_cluster: check face_cluster.json (deduplication of traces)
|
||||
let has_face_cluster = Path::new(output_dir).join(format!("{}.face_cluster.json", file_uuid)).exists();
|
||||
let has_face_cluster = Path::new(output_dir)
|
||||
.join(format!("{}.face_cluster.json", file_uuid))
|
||||
.exists();
|
||||
if has_face_cluster {
|
||||
lifecycle.mark_processor_completed("face_cluster", None);
|
||||
}
|
||||
|
||||
|
||||
// Check stage 3 processors
|
||||
for proc in STAGE_3_PROCESSORS {
|
||||
let path = Path::new(output_dir).join(format!("{}.{}.json", file_uuid, proc));
|
||||
@@ -236,7 +263,7 @@ impl FileLifecycle {
|
||||
lifecycle.mark_processor_completed(proc, None);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
lifecycle.update_group_status();
|
||||
lifecycle
|
||||
}
|
||||
@@ -251,8 +278,7 @@ impl FileLifecycle {
|
||||
/// Save lifecycle to disk
|
||||
pub fn save_to_disk(&self, output_dir: &str) -> Result<()> {
|
||||
let path = Self::lifecycle_path(output_dir, &self.file_uuid);
|
||||
let json = serde_json::to_string_pretty(self)
|
||||
.context("Failed to serialize lifecycle")?;
|
||||
let json = serde_json::to_string_pretty(self).context("Failed to serialize lifecycle")?;
|
||||
std::fs::write(&path, json)
|
||||
.with_context(|| format!("Failed to write lifecycle to {}", path.display()))?;
|
||||
tracing::debug!("[Lifecycle] Saved for {}", self.file_uuid);
|
||||
@@ -278,7 +304,7 @@ impl FileLifecycle {
|
||||
pub fn mark_stage_started(&mut self, stage: &str) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
self.updated_at = now.clone();
|
||||
|
||||
|
||||
match stage {
|
||||
"registration" => {
|
||||
self.stages.registration.status = "in_progress".to_string();
|
||||
@@ -313,7 +339,7 @@ impl FileLifecycle {
|
||||
pub fn mark_stage_completed(&mut self, stage: &str) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
self.updated_at = now.clone();
|
||||
|
||||
|
||||
match stage {
|
||||
"registration" => {
|
||||
self.stages.registration.status = "completed".to_string();
|
||||
@@ -343,7 +369,7 @@ impl FileLifecycle {
|
||||
pub fn mark_processor_started(&mut self, processor: &str) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
self.updated_at = now.clone();
|
||||
|
||||
|
||||
let stage = get_stage(processor);
|
||||
let group = match stage {
|
||||
"stage_1" => &mut self.stages.stage_1_processors,
|
||||
@@ -351,12 +377,12 @@ impl FileLifecycle {
|
||||
"stage_3" => &mut self.stages.stage_3_processors,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
|
||||
if let Some(proc_state) = group.processors.get_mut(processor) {
|
||||
proc_state.status = "running".to_string();
|
||||
proc_state.started_at = Some(now);
|
||||
}
|
||||
|
||||
|
||||
// Update group status
|
||||
group.status = "in_progress".to_string();
|
||||
}
|
||||
@@ -365,7 +391,7 @@ impl FileLifecycle {
|
||||
pub fn mark_processor_completed(&mut self, processor: &str, output_count: Option<i64>) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
self.updated_at = now.clone();
|
||||
|
||||
|
||||
let stage = get_stage(processor);
|
||||
let group = match stage {
|
||||
"stage_1" => &mut self.stages.stage_1_processors,
|
||||
@@ -373,13 +399,13 @@ impl FileLifecycle {
|
||||
"stage_3" => &mut self.stages.stage_3_processors,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
|
||||
if let Some(proc_state) = group.processors.get_mut(processor) {
|
||||
proc_state.status = "completed".to_string();
|
||||
proc_state.completed_at = Some(now);
|
||||
proc_state.output_count = output_count;
|
||||
}
|
||||
|
||||
|
||||
self.update_group_status();
|
||||
}
|
||||
|
||||
@@ -387,7 +413,7 @@ impl FileLifecycle {
|
||||
pub fn mark_processor_failed(&mut self, processor: &str, error: &str, retry_count: i32) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
self.updated_at = now.clone();
|
||||
|
||||
|
||||
let stage = get_stage(processor);
|
||||
let group = match stage {
|
||||
"stage_1" => &mut self.stages.stage_1_processors,
|
||||
@@ -395,20 +421,20 @@ impl FileLifecycle {
|
||||
"stage_3" => &mut self.stages.stage_3_processors,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
|
||||
if let Some(proc_state) = group.processors.get_mut(processor) {
|
||||
proc_state.status = "failed".to_string();
|
||||
proc_state.error = Some(error.to_string());
|
||||
proc_state.retry_count = Some(retry_count);
|
||||
}
|
||||
|
||||
|
||||
self.update_group_status();
|
||||
}
|
||||
|
||||
/// Update processor progress
|
||||
pub fn update_processor_progress(&mut self, processor: &str, current: i64, total: i64) {
|
||||
self.updated_at = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
|
||||
let stage = get_stage(processor);
|
||||
let group = match stage {
|
||||
"stage_1" => &mut self.stages.stage_1_processors,
|
||||
@@ -416,7 +442,7 @@ impl FileLifecycle {
|
||||
"stage_3" => &mut self.stages.stage_3_processors,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
|
||||
if let Some(proc_state) = group.processors.get_mut(processor) {
|
||||
proc_state.progress = Some(ProgressInfo { current, total });
|
||||
}
|
||||
@@ -427,11 +453,11 @@ impl FileLifecycle {
|
||||
// Update stage 1
|
||||
let stage_1 = &mut self.stages.stage_1_processors;
|
||||
stage_1.status = compute_group_status(&stage_1.processors);
|
||||
|
||||
|
||||
// Update stage 2
|
||||
let stage_2 = &mut self.stages.stage_2_processors;
|
||||
stage_2.status = compute_group_status(&stage_2.processors);
|
||||
|
||||
|
||||
// Update stage 3
|
||||
let stage_3 = &mut self.stages.stage_3_processors;
|
||||
stage_3.status = compute_group_status(&stage_3.processors);
|
||||
@@ -445,7 +471,7 @@ impl FileLifecycle {
|
||||
if deps.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
for dep in deps {
|
||||
if !self.is_processor_completed(dep) {
|
||||
return false;
|
||||
@@ -463,8 +489,10 @@ impl FileLifecycle {
|
||||
"stage_3" => &self.stages.stage_3_processors,
|
||||
_ => return processor == "cut" && self.stages.registration.status == "completed",
|
||||
};
|
||||
|
||||
group.processors.get(processor)
|
||||
|
||||
group
|
||||
.processors
|
||||
.get(processor)
|
||||
.map(|p| p.status == "completed")
|
||||
.unwrap_or(false)
|
||||
}
|
||||
@@ -472,40 +500,40 @@ impl FileLifecycle {
|
||||
/// Get next processors to run
|
||||
pub fn get_next_processors(&self) -> Vec<String> {
|
||||
let mut next = Vec::new();
|
||||
|
||||
|
||||
// Check stage 1
|
||||
if self.stages.registration.status != "completed" {
|
||||
return next; // Registration must complete first
|
||||
}
|
||||
|
||||
|
||||
for proc in STAGE_1_PROCESSORS {
|
||||
if !self.is_processor_completed(proc) && self.can_run_processor(proc) {
|
||||
next.push(proc.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if !next.is_empty() {
|
||||
return next;
|
||||
}
|
||||
|
||||
|
||||
// Check stage 2
|
||||
for proc in STAGE_2_PROCESSORS {
|
||||
if !self.is_processor_completed(proc) && self.can_run_processor(proc) {
|
||||
next.push(proc.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if !next.is_empty() {
|
||||
return next;
|
||||
}
|
||||
|
||||
|
||||
// Check stage 3
|
||||
for proc in STAGE_3_PROCESSORS {
|
||||
if !self.is_processor_completed(proc) && self.can_run_processor(proc) {
|
||||
next.push(proc.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
next
|
||||
}
|
||||
|
||||
@@ -546,13 +574,13 @@ impl FileLifecycle {
|
||||
pub fn overall_progress(&self) -> f64 {
|
||||
let mut completed = 0;
|
||||
let mut total = 0;
|
||||
|
||||
|
||||
// Registration
|
||||
total += 1;
|
||||
if self.stages.registration.status == "completed" {
|
||||
completed += 1;
|
||||
}
|
||||
|
||||
|
||||
// Stage 1
|
||||
for proc in STAGE_1_PROCESSORS {
|
||||
total += 1;
|
||||
@@ -560,7 +588,7 @@ impl FileLifecycle {
|
||||
completed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Stage 2
|
||||
for proc in STAGE_2_PROCESSORS {
|
||||
total += 1;
|
||||
@@ -568,7 +596,7 @@ impl FileLifecycle {
|
||||
completed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Stage 3
|
||||
for proc in STAGE_3_PROCESSORS {
|
||||
total += 1;
|
||||
@@ -576,14 +604,24 @@ impl FileLifecycle {
|
||||
completed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Rules
|
||||
total += 3;
|
||||
if self.stages.rule_1_ingestion.status == "completed" { completed += 1; }
|
||||
if self.stages.rule_2_ingestion.status == "completed" { completed += 1; }
|
||||
if self.stages.rule_3_ingestion.status == "completed" { completed += 1; }
|
||||
|
||||
if total == 0 { 0.0 } else { (completed as f64 / total as f64) * 100.0 }
|
||||
if self.stages.rule_1_ingestion.status == "completed" {
|
||||
completed += 1;
|
||||
}
|
||||
if self.stages.rule_2_ingestion.status == "completed" {
|
||||
completed += 1;
|
||||
}
|
||||
if self.stages.rule_3_ingestion.status == "completed" {
|
||||
completed += 1;
|
||||
}
|
||||
|
||||
if total == 0 {
|
||||
0.0
|
||||
} else {
|
||||
(completed as f64 / total as f64) * 100.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -630,7 +668,7 @@ fn compute_group_status(processors: &HashMap<String, ProcessorState>) -> String
|
||||
let mut has_failed = false;
|
||||
let mut has_pending = false;
|
||||
let mut completed_count = 0;
|
||||
|
||||
|
||||
for proc in processors.values() {
|
||||
match proc.status.as_str() {
|
||||
"running" => has_running = true,
|
||||
@@ -640,7 +678,7 @@ fn compute_group_status(processors: &HashMap<String, ProcessorState>) -> String
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if has_running {
|
||||
"in_progress".to_string()
|
||||
} else if has_failed {
|
||||
@@ -678,14 +716,14 @@ mod tests {
|
||||
#[test]
|
||||
fn test_can_run_processor() {
|
||||
let mut lifecycle = FileLifecycle::new("test");
|
||||
|
||||
|
||||
// Initially, asrx cannot run (needs cut + asr)
|
||||
assert!(!lifecycle.can_run_processor("asrx"));
|
||||
|
||||
|
||||
// After registration, still cannot run (needs asr)
|
||||
lifecycle.mark_stage_completed("registration");
|
||||
assert!(!lifecycle.can_run_processor("asrx"));
|
||||
|
||||
|
||||
// After asr completes, can run
|
||||
lifecycle.mark_processor_completed("asr", Some(10));
|
||||
assert!(lifecycle.can_run_processor("asrx"));
|
||||
@@ -695,7 +733,7 @@ mod tests {
|
||||
fn test_overall_progress() {
|
||||
let mut lifecycle = FileLifecycle::new("test");
|
||||
assert_eq!(lifecycle.overall_progress(), 0.0);
|
||||
|
||||
|
||||
lifecycle.mark_stage_completed("registration");
|
||||
let progress = lifecycle.overall_progress();
|
||||
assert!(progress > 0.0 && progress < 100.0);
|
||||
|
||||
@@ -418,6 +418,9 @@ impl FaceTraceProfile {
|
||||
std::fs::write(&kf_path, jpeg)
|
||||
.with_context(|| format!("Failed to write {}", kf_path.display()))?;
|
||||
self.key_frame = Some("key_frame.jpg".to_string());
|
||||
} else if dir.join("key_frame.jpg").exists() {
|
||||
// Extraction failed but file already exists on disk: preserve reference
|
||||
self.key_frame = Some("key_frame.jpg".to_string());
|
||||
}
|
||||
|
||||
// Write key_face.jpg
|
||||
@@ -426,6 +429,9 @@ impl FaceTraceProfile {
|
||||
std::fs::write(&face_path, jpeg)
|
||||
.with_context(|| format!("Failed to write {}", face_path.display()))?;
|
||||
self.key_face = Some("key_face.jpg".to_string());
|
||||
} else if dir.join("key_face.jpg").exists() {
|
||||
// Crop failed but file already exists on disk: preserve reference
|
||||
self.key_face = Some("key_face.jpg".to_string());
|
||||
}
|
||||
|
||||
// Write trace_profile.json
|
||||
|
||||
+21
-1
@@ -123,17 +123,37 @@ impl IngestionService {
|
||||
let mut width = 0u32;
|
||||
let mut height = 0u32;
|
||||
let mut fps = 0.0;
|
||||
let mut nb_frames: Option<u64> = None;
|
||||
|
||||
if let Some(ref probe) = probe_result {
|
||||
for stream in &probe.streams {
|
||||
if stream.codec_type.as_deref() == Some("video") {
|
||||
width = stream.width.unwrap_or(0);
|
||||
height = stream.height.unwrap_or(0);
|
||||
if let Some(fps_str) = &stream.r_frame_rate {
|
||||
|
||||
// Get nb_frames first (needed for actual fps calculation)
|
||||
if let Some(nb_frames_str) = &stream.nb_frames {
|
||||
if let Ok(n) = nb_frames_str.parse::<u64>() {
|
||||
nb_frames = Some(n);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate actual fps from nb_frames / duration (more accurate than r_frame_rate)
|
||||
if let Some(frames) = nb_frames {
|
||||
if duration > 0.0 {
|
||||
fps = frames as f64 / duration;
|
||||
info!(
|
||||
"Using actual fps from nb_frames/duration: {} / {} = {:.2} fps",
|
||||
frames, duration, fps
|
||||
);
|
||||
}
|
||||
} else if let Some(fps_str) = &stream.r_frame_rate {
|
||||
// Fallback to r_frame_rate if nb_frames or duration unavailable
|
||||
if let Some((num, den)) = fps_str.split_once('/') {
|
||||
if let (Ok(n), Ok(d)) = (num.parse::<f64>(), den.parse::<f64>()) {
|
||||
if d > 0.0 {
|
||||
fps = n / d;
|
||||
info!("Using r_frame_rate as fps: {} fps", fps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -535,6 +535,8 @@ impl PythonExecutor {
|
||||
Ok(Some(line)) => {
|
||||
if line.starts_with(&format!("{}_", log_prefix)) {
|
||||
tracing::info!("[{}] {}", log_prefix, line);
|
||||
} else if !line.trim().is_empty() {
|
||||
tracing::warn!("[{} stderr] {}", log_prefix, line);
|
||||
}
|
||||
}
|
||||
Ok(None) => stderr_done = true,
|
||||
@@ -738,6 +740,8 @@ impl PythonExecutor {
|
||||
Ok(Some(line)) => {
|
||||
if line.starts_with(&format!("{}_", log_prefix)) {
|
||||
tracing::info!("[{}] {}", log_prefix, line);
|
||||
} else if !line.trim().is_empty() {
|
||||
tracing::warn!("[{} stderr] {}", log_prefix, line);
|
||||
}
|
||||
}
|
||||
Ok(None) => stderr_done = true,
|
||||
@@ -825,6 +829,202 @@ impl PythonExecutor {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Like `run_with_output_idx_and_frames` but accepts a `CancellationToken` so the caller
|
||||
/// can cleanly abort the Python subprocess without leaking processes.
|
||||
pub async fn run_with_output_idx_and_frames_with_cancel(
|
||||
&self,
|
||||
script_name: &str,
|
||||
args: &[&str],
|
||||
uuid: Option<&str>,
|
||||
log_prefix: &str,
|
||||
timeout_duration: Option<Duration>,
|
||||
output_idx: Option<usize>,
|
||||
frames: Option<&[i64]>,
|
||||
cancel: tokio_util::sync::CancellationToken,
|
||||
) -> Result<()> {
|
||||
let script_path = self.scripts_dir.join(script_name);
|
||||
|
||||
if !script_path.exists() {
|
||||
anyhow::bail!("Script not found: {:?}", script_path);
|
||||
}
|
||||
|
||||
self.verify_script_integrity(script_name).context(
|
||||
"Pre-execution integrity check failed — possible version mismatch or corruption",
|
||||
)?;
|
||||
|
||||
let output_path =
|
||||
output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p)));
|
||||
let tmp_path = output_path.as_ref().map(|p| {
|
||||
let mut tmp = p.to_path_buf();
|
||||
tmp.set_extension("json.tmp");
|
||||
tmp
|
||||
});
|
||||
|
||||
let mut cmd = Command::new(&self.python_path);
|
||||
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
|
||||
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
|
||||
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
|
||||
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
|
||||
if let Ok(qdrant_url) = std::env::var("QDRANT_URL") {
|
||||
cmd.env("QDRANT_URL", qdrant_url);
|
||||
}
|
||||
if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") {
|
||||
cmd.env("QDRANT_API_KEY", qdrant_api_key);
|
||||
}
|
||||
cmd.arg(&script_path);
|
||||
|
||||
for (i, arg) in args.iter().enumerate() {
|
||||
if Some(i) == output_idx {
|
||||
if let Some(ref tmp) = tmp_path {
|
||||
cmd.arg(tmp);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
if let Some(u) = uuid {
|
||||
cmd.arg("--uuid").arg(u);
|
||||
}
|
||||
|
||||
// Append extra args (e.g. --threshold) after --uuid
|
||||
// Pass frame list for 8Hz sampling
|
||||
if let Some(frames) = frames {
|
||||
if !frames.is_empty() {
|
||||
let frames_str = Self::format_frames_arg(frames);
|
||||
cmd.arg("--frames").arg(&frames_str);
|
||||
}
|
||||
}
|
||||
|
||||
cmd.stdout(Stdio::piped());
|
||||
cmd.stderr(Stdio::piped());
|
||||
cmd.kill_on_drop(true);
|
||||
cmd.process_group(0);
|
||||
|
||||
tracing::info!("[{}] Starting: {:?}", log_prefix, script_name);
|
||||
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.with_context(|| format!("Failed to run {}", script_name))?;
|
||||
let child_pid = child.id();
|
||||
|
||||
let stdout = child.stdout.take().context("Failed to capture stdout")?;
|
||||
let stderr = child.stderr.take().context("Failed to capture stderr")?;
|
||||
|
||||
let mut stdout_reader = BufReader::new(stdout).lines();
|
||||
let mut stderr_reader = BufReader::new(stderr).lines();
|
||||
|
||||
let run_future = async {
|
||||
let mut stdout_done = false;
|
||||
let mut stderr_done = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
line = stdout_reader.next_line(), if !stdout_done => {
|
||||
match line {
|
||||
Ok(Some(line)) => {
|
||||
if line.starts_with(&format!("{}_", log_prefix)) {
|
||||
tracing::info!("[{}] {}", log_prefix, line);
|
||||
}
|
||||
}
|
||||
Ok(None) => stdout_done = true,
|
||||
Err(e) => tracing::warn!("[{}] stdout error: {}", log_prefix, e),
|
||||
}
|
||||
}
|
||||
line = stderr_reader.next_line(), if !stderr_done => {
|
||||
match line {
|
||||
Ok(Some(line)) => {
|
||||
if line.starts_with(&format!("{}_", log_prefix)) {
|
||||
tracing::info!("[{}] {}", log_prefix, line);
|
||||
} else if !line.trim().is_empty() {
|
||||
tracing::warn!("[{} stderr] {}", log_prefix, line);
|
||||
}
|
||||
}
|
||||
Ok(None) => stderr_done = true,
|
||||
Err(e) => tracing::warn!("[{}] stderr error: {}", log_prefix, e),
|
||||
}
|
||||
}
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!("[{}] Cancelled by caller", log_prefix);
|
||||
if let Some(pid) = child_pid {
|
||||
unsafe { libc::killpg(pid as i32, libc::SIGTERM); }
|
||||
}
|
||||
return Err(anyhow::anyhow!("{} cancelled by caller", script_name));
|
||||
}
|
||||
status = child.wait() => {
|
||||
match status {
|
||||
Ok(status) => {
|
||||
if !status.success() {
|
||||
tracing::error!("[{}] Process failed: {}", log_prefix, status);
|
||||
return Err(anyhow::anyhow!("{} exited with: {}", script_name, status));
|
||||
}
|
||||
tracing::info!("[{}] Completed successfully", log_prefix);
|
||||
}
|
||||
Err(e) => tracing::error!("[{}] wait error: {}", log_prefix, e),
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
let mark_failed = || {
|
||||
if let Some(tmp) = &tmp_path {
|
||||
if tmp.exists() {
|
||||
if let Some(out) = &output_path {
|
||||
let is_valid = std::fs::read_to_string(tmp)
|
||||
.ok()
|
||||
.and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
|
||||
.is_some();
|
||||
if is_valid {
|
||||
let mut partial_path = out.to_path_buf();
|
||||
partial_path.set_extension("json.partial");
|
||||
let _ = std::fs::rename(tmp, &partial_path);
|
||||
tracing::warn!("[Executor] Partial output preserved: {:?}", partial_path);
|
||||
} else {
|
||||
let mut err_path = out.to_path_buf();
|
||||
err_path.set_extension("json.err");
|
||||
let _ = std::fs::rename(tmp, &err_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(duration) = timeout_duration {
|
||||
match timeout(duration, run_future).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(e)) => {
|
||||
mark_failed();
|
||||
return Err(e);
|
||||
}
|
||||
Err(_) => {
|
||||
mark_failed();
|
||||
if let Some(pid) = child_pid {
|
||||
unsafe { libc::killpg(pid as i32, libc::SIGKILL); }
|
||||
}
|
||||
child.kill().await.context("Failed to kill process")?;
|
||||
anyhow::bail!("{} timed out after {:?}", script_name, duration);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if let Err(e) = run_future.await {
|
||||
mark_failed();
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(tmp) = &tmp_path {
|
||||
if tmp.exists() {
|
||||
if let Some(out) = &output_path {
|
||||
let _ = std::fs::rename(tmp, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run_with_output(
|
||||
&self,
|
||||
script_name: &str,
|
||||
|
||||
@@ -17,6 +17,14 @@ pub struct FaceClusterInfo {
|
||||
pub cluster_id: String,
|
||||
pub face_count: usize,
|
||||
pub representative_face: Option<RepresentativeFace>,
|
||||
pub similarity: Option<ClusterSimilarity>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct ClusterSimilarity {
|
||||
pub min: f64,
|
||||
pub avg: f64,
|
||||
pub threshold: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
@@ -55,6 +63,7 @@ pub async fn process_face_cluster(
|
||||
output_path: &str,
|
||||
uuid: Option<&str>,
|
||||
frames: Option<&[i64]>,
|
||||
similarity_threshold: Option<f64>,
|
||||
) -> Result<FaceClusterResult> {
|
||||
let executor = PythonExecutor::new()?;
|
||||
let script_path = executor.script_path("fast_face_clustering_processor.py");
|
||||
@@ -69,13 +78,28 @@ pub async fn process_face_cluster(
|
||||
});
|
||||
}
|
||||
|
||||
// Build args with optional --threshold
|
||||
let distance = similarity_threshold.map(|s| 1.0 - s);
|
||||
let mut args = vec![video_path, output_path];
|
||||
if let Some(d) = distance {
|
||||
let threshold_str = format!("{:.4}", d);
|
||||
args.push("--threshold");
|
||||
args.push(Box::leak(threshold_str.into_boxed_str()) as &str);
|
||||
tracing::info!(
|
||||
"[FACE_CLUSTER] similarity={:.2} → distance={:.4}",
|
||||
similarity_threshold.unwrap_or(0.65),
|
||||
d
|
||||
);
|
||||
}
|
||||
|
||||
executor
|
||||
.run_with_frames(
|
||||
.run_with_output_idx_and_frames(
|
||||
"fast_face_clustering_processor.py",
|
||||
&[video_path, output_path],
|
||||
&args,
|
||||
uuid,
|
||||
"FACE_CLUSTER",
|
||||
Some(FACE_CLUSTER_TIMEOUT),
|
||||
Some(1),
|
||||
frames,
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -96,8 +96,7 @@ pub fn group_ocr_texts_by_zone_and_proximity(
|
||||
|
||||
for frame in frames {
|
||||
// Rule 2: Frame difference detection
|
||||
let current_texts: HashSet<String> =
|
||||
frame.texts.iter().map(|t| t.text.clone()).collect();
|
||||
let current_texts: HashSet<String> = frame.texts.iter().map(|t| t.text.clone()).collect();
|
||||
let similarity = jaccard_similarity(&last_texts, ¤t_texts);
|
||||
|
||||
if !last_texts.is_empty() && similarity < TEXT_SIMILARITY_THRESHOLD {
|
||||
|
||||
+177
-8
@@ -1304,13 +1304,31 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
// Crop key_face JPEG bytes from key_frame using representative bbox (best confidence frame)
|
||||
let key_face_jpeg: Option<Vec<u8>> = key_frame_jpeg.as_ref().and_then(|kf| {
|
||||
// Find bbox for best_frame from trace frames
|
||||
let (_, bx, by, bw, bh) = agg.frames.iter().find(|(f, _, _, _, _)| *f == agg.best_frame)?;
|
||||
let (bf, bx, by, bw, bh) = agg
|
||||
.frames
|
||||
.iter()
|
||||
.find(|(f, _, _, _, _)| *f == agg.best_frame)?;
|
||||
let (bx, by, bw, bh) = (*bx, *by, *bw, *bh);
|
||||
|
||||
// Validate bbox: must have positive dimensions
|
||||
if bw < 2.0 || bh < 2.0 {
|
||||
tracing::warn!(
|
||||
"[TKG] trace {}: invalid bbox {}x{} at ({},{}), skipping key_face",
|
||||
tid,
|
||||
bw,
|
||||
bh,
|
||||
bx,
|
||||
by
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
let crop_filter = format!(
|
||||
"crop={}:{}:{}:{}",
|
||||
(*bw as i64).max(1),
|
||||
(*bh as i64).max(1),
|
||||
(*bx as i64).max(0),
|
||||
(*by as i64).max(0),
|
||||
(bw as i64).max(1),
|
||||
(bh as i64).max(1),
|
||||
(bx as i64).max(0),
|
||||
(by as i64).max(0),
|
||||
);
|
||||
let mut cmd = std::process::Command::new("ffmpeg");
|
||||
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
|
||||
@@ -1336,7 +1354,7 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
// Save all three files to output/{file_uuid}/{trace_id}/
|
||||
let mut key_frame_file = agg.best_frame.to_string();
|
||||
let mut key_face_file = agg.best_point_id.as_deref().unwrap_or("").to_string();
|
||||
|
||||
|
||||
match trace_profile.save(
|
||||
output_dir,
|
||||
key_frame_jpeg.as_deref(),
|
||||
@@ -1347,7 +1365,154 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
key_face_file = "key_face.jpg".to_string();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("[TKG] Failed to save trace_profile for trace {}: {}", tid, e);
|
||||
tracing::error!(
|
||||
"[TKG] Failed to save trace_profile for trace {}: {}",
|
||||
tid,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate all three outputs exist: key_frame.jpg, key_face.jpg, trace_profile.json
|
||||
// If missing, retry extraction on the spot
|
||||
let trace_dir =
|
||||
crate::core::file_profile::FaceTraceProfile::trace_dir(output_dir, file_uuid, *tid);
|
||||
let kf_path = trace_dir.join("key_frame.jpg");
|
||||
let kface_path = trace_dir.join("key_face.jpg");
|
||||
let tp_path =
|
||||
crate::core::file_profile::FaceTraceProfile::profile_path(output_dir, file_uuid, *tid);
|
||||
|
||||
let mut need_retry = false;
|
||||
if !kf_path.exists() {
|
||||
tracing::warn!(
|
||||
"[TKG-VERIFY] trace {}: key_frame.jpg missing, retrying",
|
||||
tid
|
||||
);
|
||||
need_retry = true;
|
||||
}
|
||||
if !kface_path.exists() {
|
||||
tracing::warn!("[TKG-VERIFY] trace {}: key_face.jpg missing, retrying", tid);
|
||||
need_retry = true;
|
||||
}
|
||||
if !tp_path.exists() {
|
||||
tracing::warn!(
|
||||
"[TKG-VERIFY] trace {}: trace_profile.json missing, retrying",
|
||||
tid
|
||||
);
|
||||
need_retry = true;
|
||||
}
|
||||
|
||||
if need_retry {
|
||||
if let Some(ref vp) = video_path {
|
||||
let timestamp = agg.best_frame as f64 / actual_fps;
|
||||
// Retry key_frame extraction
|
||||
if !kf_path.exists() {
|
||||
if let Ok(output) = std::process::Command::new("ffmpeg")
|
||||
.args([
|
||||
"-y",
|
||||
"-v",
|
||||
"quiet",
|
||||
"-ss",
|
||||
&format!("{:.3}", timestamp),
|
||||
"-i",
|
||||
vp,
|
||||
])
|
||||
.args([
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-q:v",
|
||||
"2",
|
||||
"-f",
|
||||
"image2pipe",
|
||||
"-c:v",
|
||||
"mjpeg",
|
||||
"pipe:1",
|
||||
])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
{
|
||||
if output.status.success() && !output.stdout.is_empty() {
|
||||
let _ = std::fs::write(&kf_path, &output.stdout);
|
||||
if kf_path.exists() {
|
||||
tracing::info!(
|
||||
"[TKG-VERIFY] trace {}: key_frame.jpg recovered",
|
||||
tid
|
||||
);
|
||||
key_frame_file = "key_frame.jpg".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Retry key_face crop
|
||||
if !kface_path.exists() && kf_path.exists() {
|
||||
let (_, bx, by, bw, bh) = agg
|
||||
.frames
|
||||
.iter()
|
||||
.find(|(f, _, _, _, _)| *f == agg.best_frame)
|
||||
.cloned()
|
||||
.unwrap_or((0, 0.0, 0.0, 100.0, 100.0));
|
||||
|
||||
// Validate bbox
|
||||
if bw < 2.0 || bh < 2.0 {
|
||||
tracing::warn!(
|
||||
"[TKG-VERIFY] trace {}: invalid bbox {}x{}, skipping key_face retry",
|
||||
tid,
|
||||
bw,
|
||||
bh
|
||||
);
|
||||
} else {
|
||||
let crop_filter = format!(
|
||||
"crop={}:{}:{}:{}",
|
||||
(bw as i64).max(1),
|
||||
(bh as i64).max(1),
|
||||
(bx as i64).max(0),
|
||||
(by as i64).max(0),
|
||||
);
|
||||
if let Ok(kf_bytes) = std::fs::read(&kf_path) {
|
||||
let mut cmd = std::process::Command::new("ffmpeg");
|
||||
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
|
||||
.args(["-frames:v", "1", "-q:v", "2", "-vf"])
|
||||
.arg(&crop_filter)
|
||||
.args(["-f", "image2pipe", "-c:v", "mjpeg", "pipe:1"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null());
|
||||
if let Ok(mut child) = cmd.spawn() {
|
||||
if let Some(ref mut stdin) = child.stdin {
|
||||
use std::io::Write;
|
||||
let _ = stdin.write_all(&kf_bytes);
|
||||
}
|
||||
if let Ok(output) = child.wait_with_output() {
|
||||
if output.status.success() && !output.stdout.is_empty() {
|
||||
let _ = std::fs::write(&kface_path, &output.stdout);
|
||||
if kface_path.exists() {
|
||||
tracing::info!(
|
||||
"[TKG-VERIFY] trace {}: key_face.jpg recovered",
|
||||
tid
|
||||
);
|
||||
key_face_file = "key_face.jpg".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Update trace_profile with recovered file paths, then rewrite profile
|
||||
// (even if it already exists — it may have stale null key_frame/key_face)
|
||||
if kf_path.exists() {
|
||||
trace_profile.key_frame = Some("key_frame.jpg".to_string());
|
||||
}
|
||||
if kface_path.exists() {
|
||||
trace_profile.key_face = Some("key_face.jpg".to_string());
|
||||
}
|
||||
if let Ok(json) = serde_json::to_string_pretty(&trace_profile) {
|
||||
let _ = std::fs::write(&tp_path, json);
|
||||
if tp_path.exists() {
|
||||
tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1399,7 +1564,11 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
count += 1;
|
||||
}
|
||||
|
||||
tracing::info!("[TKG-face_track] built {} face_track nodes for {}", count, file_uuid);
|
||||
tracing::info!(
|
||||
"[TKG-face_track] built {} face_track nodes for {}",
|
||||
count,
|
||||
file_uuid
|
||||
);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
|
||||
+24
-19
@@ -23,8 +23,7 @@ pub fn proxy_output_path(file_path: &str) -> Result<PathBuf> {
|
||||
}
|
||||
|
||||
fn ffmpeg_cmd() -> Command {
|
||||
let ffmpeg_path = std::env::var("MOMENTRY_FFMPEG")
|
||||
.unwrap_or_else(|_| "ffmpeg".to_string());
|
||||
let ffmpeg_path = std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string());
|
||||
let mut cmd = Command::new(&ffmpeg_path);
|
||||
let full_lib = "/opt/homebrew/opt/ffmpeg-full/lib";
|
||||
if std::path::Path::new(full_lib).exists() {
|
||||
@@ -52,15 +51,24 @@ pub async fn generate_proxy(file_path: &str, file_uuid: &str) -> Result<Option<S
|
||||
let status = tokio::task::spawn_blocking(move || {
|
||||
ffmpeg_cmd()
|
||||
.args([
|
||||
"-i", &file_path_owned,
|
||||
"-vf", &format!("scale=-2:{}", PROXY_HEIGHT),
|
||||
"-c:v", "libx264",
|
||||
"-preset", "fast",
|
||||
"-crf", &PROXY_CRF.to_string(),
|
||||
"-c:a", "aac",
|
||||
"-b:a", "128k",
|
||||
"-movflags", "+faststart",
|
||||
"-y", &out_str,
|
||||
"-i",
|
||||
&file_path_owned,
|
||||
"-vf",
|
||||
&format!("scale=-2:{}", PROXY_HEIGHT),
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"fast",
|
||||
"-crf",
|
||||
&PROXY_CRF.to_string(),
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"128k",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
"-y",
|
||||
&out_str,
|
||||
])
|
||||
.status()
|
||||
})
|
||||
@@ -153,10 +161,7 @@ pub async fn probe_audio_track(file_path: &str) -> Result<Option<AudioTrackResul
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0) as i32;
|
||||
|
||||
let duration = json
|
||||
.get("duration")
|
||||
.and_then(|v| v.as_f64())
|
||||
.unwrap_or(0.0);
|
||||
let duration = json.get("duration").and_then(|v| v.as_f64()).unwrap_or(0.0);
|
||||
|
||||
tracing::info!(
|
||||
"[AUDIO_TRACK] {} -> {} (ratio: {:.2}, segments: {})",
|
||||
@@ -180,8 +185,7 @@ pub async fn extract_cut_key_frames(
|
||||
video_path: &str,
|
||||
output_dir: &str,
|
||||
) -> Result<Vec<String>> {
|
||||
let cut_json = PathBuf::from(output_dir)
|
||||
.join(format!("{}.cut.json", file_uuid));
|
||||
let cut_json = PathBuf::from(output_dir).join(format!("{}.cut.json", file_uuid));
|
||||
|
||||
if !cut_json.exists() {
|
||||
tracing::warn!("[CUT_KEY_FRAME] cut.json not found: {}", cut_json.display());
|
||||
@@ -244,7 +248,8 @@ pub async fn extract_cut_key_frames(
|
||||
arr.iter()
|
||||
.filter_map(|s| {
|
||||
if s.get("success").and_then(|b| b.as_bool()) == Some(true) {
|
||||
s.get("output_path").and_then(|p| p.as_str().map(|p| p.to_string()))
|
||||
s.get("output_path")
|
||||
.and_then(|p| p.as_str().map(|p| p.to_string()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -260,4 +265,4 @@ pub async fn extract_cut_key_frames(
|
||||
);
|
||||
|
||||
Ok(scenes)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1316,9 +1316,9 @@ impl JobWorker {
|
||||
}
|
||||
}
|
||||
|
||||
// Check dependencies: all dependent processors must be completed
|
||||
// Special check for FaceCluster: face_traced.json must exist (produced by P2
|
||||
// store_traced_faces.py which runs AFTER process_job completes).
|
||||
// Special guard for FaceCluster: requires face_traced.json to exist.
|
||||
// Without it, clustering produces no_faces even when faces were detected
|
||||
// (the trace file is produced later by store_traced_faces.py in P2 trigger).
|
||||
if *processor_type == crate::core::db::ProcessorType::FaceCluster {
|
||||
let traced_path = format!(
|
||||
"{}/{}.face_traced.json",
|
||||
@@ -1327,14 +1327,15 @@ impl JobWorker {
|
||||
);
|
||||
if !std::path::Path::new(&traced_path).exists() {
|
||||
info!(
|
||||
"Processor {} deferred: face_traced.json not yet ready for {}",
|
||||
processor_type.as_str(),
|
||||
"FaceCluster deferred: face_traced.json not yet ready for {}",
|
||||
job.uuid
|
||||
);
|
||||
started_count += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Check dependencies: all dependent processors must be completed
|
||||
let deps = processor_type.dependencies();
|
||||
if !deps.is_empty() {
|
||||
let mut any_dep_failed = false;
|
||||
|
||||
@@ -886,6 +886,7 @@ impl ProcessorPool {
|
||||
output_path.to_str().unwrap(),
|
||||
uuid,
|
||||
Some(&sample_frames),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
tracing::info!(
|
||||
|
||||
Reference in New Issue
Block a user