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,
|
||||
|
||||
Reference in New Issue
Block a user