fix: Face processor now saves status and total_faces to face.json
This commit is contained in:
@@ -14,17 +14,29 @@ use crate::core::config::{DATABASE_SCHEMA, OUTPUT_DIR, REDIS_KEY_PREFIX};
|
||||
/// Returns (min_confidence, min_size, min_capture_quality) as Option<String>.
|
||||
async fn get_face_settings() -> (Option<String>, Option<String>, Option<String>) {
|
||||
let face_config = crate::core::admin_config::get_filter_config("face").await;
|
||||
|
||||
|
||||
// Priority: Environment variable (runtime override) > Admin config (default)
|
||||
let min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok()
|
||||
.or_else(|| face_config.as_ref().and_then(|c| c.min_confidence).map(|v| v.to_string()));
|
||||
|
||||
let min_size = std::env::var("FACE_MIN_SIZE").ok()
|
||||
.or_else(|| face_config.as_ref().and_then(|c| c.min_size).map(|v| v.to_string()));
|
||||
|
||||
let min_capture_quality = std::env::var("FACE_MIN_CAPTURE_QUALITY").ok()
|
||||
.or_else(|| face_config.as_ref().and_then(|c| c.min_capture_quality).map(|v| v.to_string()));
|
||||
|
||||
let min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok().or_else(|| {
|
||||
face_config
|
||||
.as_ref()
|
||||
.and_then(|c| c.min_confidence)
|
||||
.map(|v| v.to_string())
|
||||
});
|
||||
|
||||
let min_size = std::env::var("FACE_MIN_SIZE").ok().or_else(|| {
|
||||
face_config
|
||||
.as_ref()
|
||||
.and_then(|c| c.min_size)
|
||||
.map(|v| v.to_string())
|
||||
});
|
||||
|
||||
let min_capture_quality = std::env::var("FACE_MIN_CAPTURE_QUALITY").ok().or_else(|| {
|
||||
face_config
|
||||
.as_ref()
|
||||
.and_then(|c| c.min_capture_quality)
|
||||
.map(|v| v.to_string())
|
||||
});
|
||||
|
||||
(min_confidence, min_size, min_capture_quality)
|
||||
}
|
||||
|
||||
@@ -343,7 +355,8 @@ impl PythonExecutor {
|
||||
cmd.env("UUID", u);
|
||||
}
|
||||
// Pass face detection settings to Python subprocesses (from admin config or env)
|
||||
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
|
||||
let (face_min_confidence, face_min_size, face_min_capture_quality) =
|
||||
get_face_settings().await;
|
||||
tracing::info!(
|
||||
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
|
||||
face_min_confidence,
|
||||
@@ -512,7 +525,8 @@ impl PythonExecutor {
|
||||
cmd.env("UUID", u);
|
||||
}
|
||||
// Pass face detection settings to Python subprocesses (from admin config or env)
|
||||
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
|
||||
let (face_min_confidence, face_min_size, face_min_capture_quality) =
|
||||
get_face_settings().await;
|
||||
tracing::info!(
|
||||
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
|
||||
face_min_confidence,
|
||||
@@ -722,7 +736,8 @@ impl PythonExecutor {
|
||||
cmd.env("QDRANT_API_KEY", qdrant_api_key);
|
||||
}
|
||||
// Pass face detection settings to Python subprocesses (from admin config or env)
|
||||
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
|
||||
let (face_min_confidence, face_min_size, face_min_capture_quality) =
|
||||
get_face_settings().await;
|
||||
tracing::info!(
|
||||
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
|
||||
face_min_confidence,
|
||||
@@ -942,7 +957,8 @@ impl PythonExecutor {
|
||||
cmd.env("QDRANT_API_KEY", qdrant_api_key);
|
||||
}
|
||||
// Pass face detection settings to Python subprocesses (from admin config or env)
|
||||
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
|
||||
let (face_min_confidence, face_min_size, face_min_capture_quality) =
|
||||
get_face_settings().await;
|
||||
tracing::info!(
|
||||
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
|
||||
face_min_confidence,
|
||||
@@ -1266,9 +1282,9 @@ impl PythonExecutor {
|
||||
|
||||
tracing::info!("[{}] Starting rust: {:?}", log_prefix, cmd);
|
||||
|
||||
let mut child = cmd.spawn().with_context(|| {
|
||||
format!("Failed to run Rust processor {:?}", bin_path)
|
||||
})?;
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.with_context(|| format!("Failed to run Rust processor {:?}", bin_path))?;
|
||||
let child_pid = child.id();
|
||||
|
||||
let stdout = child.stdout.take().context("Failed to capture stdout")?;
|
||||
|
||||
@@ -31,6 +31,14 @@ impl FaceResult {
|
||||
self.status = Some(FaceStatus::from_face_count(self.total_faces));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save_to_file(&self, path: &str) -> Result<()> {
|
||||
let json = serde_json::to_string_pretty(self)
|
||||
.context("Failed to serialize FaceResult")?;
|
||||
std::fs::write(path, json)
|
||||
.context("Failed to write face.json")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn no_faces(frame_count: u64, fps: f64) -> Self {
|
||||
FaceResult {
|
||||
@@ -120,6 +128,7 @@ pub async fn process_face(
|
||||
serde_json::from_str(&json_str).context("Failed to parse existing FACE output")?;
|
||||
|
||||
result.compute_status();
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[FACE] Loaded from SwiftFacePose: status={}, {} frames, {} total faces",
|
||||
@@ -233,6 +242,7 @@ pub async fn process_face(
|
||||
let json_str = std::fs::read_to_string(output_path).context("Failed to read FACE output")?;
|
||||
let mut result: FaceResult = serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
|
||||
result.compute_status();
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[FACE] Swift result: status={}, {} frames, {} total faces",
|
||||
@@ -272,6 +282,7 @@ pub async fn process_face(
|
||||
serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
|
||||
|
||||
result.compute_status();
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[FACE] Result: status={}, {} frames, {} total faces",
|
||||
|
||||
@@ -110,8 +110,8 @@ pub async fn process_face_cluster(
|
||||
Ok(_) => {
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read FACE_CLUSTER output")?;
|
||||
let result: FaceClusterResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse FACE_CLUSTER output")?;
|
||||
let result: FaceClusterResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse FACE_CLUSTER output")?;
|
||||
tracing::info!(
|
||||
"[FACE_CLUSTER] Rust Result: {} clusters, {} frames",
|
||||
result.clusters.len(),
|
||||
|
||||
@@ -14,6 +14,7 @@ pub mod heuristic_scene;
|
||||
pub mod ocr;
|
||||
pub mod pose;
|
||||
pub mod scene_classification;
|
||||
pub mod scene_vlm;
|
||||
pub mod tkg;
|
||||
pub mod vlm_summary;
|
||||
|
||||
@@ -188,6 +189,7 @@ pub use scene_classification::{
|
||||
load_scene_from_file, process_scene_classification, SceneClassificationResult, ScenePrediction,
|
||||
SceneSegment,
|
||||
};
|
||||
pub use scene_vlm::SceneVlmProcessor;
|
||||
pub use tkg::{
|
||||
build_tkg, query_auto_representative_frame, FrameTraceInfo, MainIdentityInfo,
|
||||
RepresentativeFrameResult, TkgResult,
|
||||
|
||||
@@ -734,7 +734,16 @@ pub async fn build_tkg(
|
||||
if let Some(r) = redis.as_ref() {
|
||||
publish_tkg_progress(r, file_uuid, &progress).await;
|
||||
}
|
||||
let n_face = build_face_track_nodes(pool, file_uuid, &pose_data, &face_points, false, &mut progress, &redis).await?;
|
||||
let n_face = build_face_track_nodes(
|
||||
pool,
|
||||
file_uuid,
|
||||
&pose_data,
|
||||
&face_points,
|
||||
false,
|
||||
&mut progress,
|
||||
&redis,
|
||||
)
|
||||
.await?;
|
||||
progress.stats.face_track_nodes = n_face as i64;
|
||||
progress.update_phase(
|
||||
TkgPhase::FaceTrackNodes,
|
||||
@@ -1043,8 +1052,16 @@ pub async fn backfill_trace_dirs(
|
||||
file_uuid
|
||||
);
|
||||
|
||||
let n =
|
||||
build_face_track_nodes_from_qdrant(pool, file_uuid, &pose_data, &face_points, true, &mut TkgProgress::new(file_uuid), &None).await?;
|
||||
let n = build_face_track_nodes_from_qdrant(
|
||||
pool,
|
||||
file_uuid,
|
||||
&pose_data,
|
||||
&face_points,
|
||||
true,
|
||||
&mut TkgProgress::new(file_uuid),
|
||||
&None,
|
||||
)
|
||||
.await?;
|
||||
tracing::info!(
|
||||
"[TKG-BACKFILL] backfilled {} face_track artifact dirs for {}",
|
||||
n,
|
||||
@@ -1062,7 +1079,16 @@ async fn build_face_track_nodes(
|
||||
progress: &mut TkgProgress,
|
||||
redis: &Option<Arc<RedisClient>>,
|
||||
) -> Result<usize> {
|
||||
build_face_track_nodes_from_qdrant(pool, file_uuid, pose_data, face_points, skip_existing, progress, redis).await
|
||||
build_face_track_nodes_from_qdrant(
|
||||
pool,
|
||||
file_uuid,
|
||||
pose_data,
|
||||
face_points,
|
||||
skip_existing,
|
||||
progress,
|
||||
redis,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn build_face_track_nodes_from_qdrant(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use anyhow::Result;
|
||||
use base64::Engine;
|
||||
use futures_util::stream::{self, StreamExt};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tracing::{error, info, warn};
|
||||
@@ -60,7 +61,7 @@ pub async fn generate_vlm_summaries(
|
||||
}
|
||||
|
||||
info!(
|
||||
"[VLM] Starting VLM summary generation for {}: {} traces",
|
||||
"[VLM] Starting VLM summary generation for {}: {} traces (parallel processing)",
|
||||
file_uuid, total
|
||||
);
|
||||
info!(
|
||||
@@ -73,22 +74,48 @@ pub async fn generate_vlm_summaries(
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for (i, &trace_id) in trace_ids.iter().enumerate() {
|
||||
let current = i + 1;
|
||||
// Parallel processing with max 5 concurrent tasks
|
||||
let max_concurrent = 5;
|
||||
info!(
|
||||
"[VLM] Processing {} traces with max {} concurrent",
|
||||
total, max_concurrent
|
||||
);
|
||||
|
||||
// Update progress
|
||||
if let Some(ref r) = redis {
|
||||
let mut pp = PipelineProgress::new(file_uuid);
|
||||
pp.update_stage(
|
||||
"vlm_summary",
|
||||
current as f64 / total as f64,
|
||||
"running",
|
||||
Some(format!("{}/{}", current, total)),
|
||||
);
|
||||
let _ = publish_pipeline_progress(r.as_ref(), file_uuid, &pp).await;
|
||||
}
|
||||
let trace_ids_owned: Vec<i32> = trace_ids.into_iter().collect();
|
||||
|
||||
match process_single_trace(db, file_uuid, trace_id, output_dir, current, total).await {
|
||||
let results: Vec<_> = stream::iter(trace_ids_owned.into_iter().enumerate())
|
||||
.map(|(i, trace_id)| {
|
||||
let db_clone = db.clone();
|
||||
let file_uuid = file_uuid.to_string();
|
||||
let output_dir = output_dir.to_string();
|
||||
let redis_clone = redis.clone();
|
||||
async move {
|
||||
let current = i + 1;
|
||||
let total = total;
|
||||
|
||||
// Update progress
|
||||
if let Some(ref r) = redis_clone {
|
||||
let mut pp = PipelineProgress::new(&file_uuid);
|
||||
pp.update_stage(
|
||||
"vlm_summary",
|
||||
current as f64 / total as f64,
|
||||
"running",
|
||||
Some(format!("{}/{}", current, total)),
|
||||
);
|
||||
let _ = publish_pipeline_progress(r.as_ref(), &file_uuid, &pp).await;
|
||||
}
|
||||
|
||||
process_single_trace(&db_clone, &file_uuid, trace_id, &output_dir, current, total)
|
||||
.await
|
||||
}
|
||||
})
|
||||
.buffer_unordered(max_concurrent)
|
||||
.collect()
|
||||
.await;
|
||||
|
||||
// Aggregate results
|
||||
for res in results {
|
||||
match res {
|
||||
Ok((summarized, embedded)) => {
|
||||
if summarized {
|
||||
result.summarized += 1;
|
||||
@@ -99,10 +126,7 @@ pub async fn generate_vlm_summaries(
|
||||
}
|
||||
Err(e) => {
|
||||
result.errors += 1;
|
||||
error!(
|
||||
"[VLM] trace {}/{} (tid={}): {}",
|
||||
current, total, trace_id, e
|
||||
);
|
||||
error!("[VLM] Error processing trace: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -140,7 +164,7 @@ async fn process_single_trace(
|
||||
) -> Result<(bool, bool)> {
|
||||
let trace_id_i64 = trace_id as i64;
|
||||
let tp_table = table_name("trace_profiles");
|
||||
|
||||
|
||||
// Check frame_count and skip single frame trace if disabled
|
||||
let frame_count: Option<i32> = sqlx::query_scalar(&format!(
|
||||
"SELECT frame_count FROM {tp_table} WHERE file_uuid = $1 AND trace_id = $2"
|
||||
@@ -150,21 +174,22 @@ async fn process_single_trace(
|
||||
.fetch_optional(db.pool())
|
||||
.await?
|
||||
.flatten();
|
||||
|
||||
|
||||
// If this is a single frame trace, check configuration
|
||||
if frame_count == Some(1) {
|
||||
let v_table = table_name("videos");
|
||||
let settings: Option<crate::core::file_profile::FaceFilterSettings> = sqlx::query_scalar(&format!(
|
||||
"SELECT face_filter FROM {v_table} WHERE file_uuid = $1"
|
||||
))
|
||||
let settings: Option<crate::core::file_profile::FaceFilterSettings> = sqlx::query_scalar(
|
||||
&format!("SELECT face_filter FROM {v_table} WHERE file_uuid = $1"),
|
||||
)
|
||||
.bind(file_uuid)
|
||||
.fetch_optional(db.pool())
|
||||
.await?
|
||||
.flatten()
|
||||
.and_then(|v| serde_json::from_value(v).ok());
|
||||
|
||||
let settings = settings.unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults);
|
||||
|
||||
|
||||
let settings =
|
||||
settings.unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults);
|
||||
|
||||
if !settings.single_frame_trace_vlm_enabled {
|
||||
info!(
|
||||
"[VLM] trace {}/{} (tid={}): skipping single frame trace (disabled by config)",
|
||||
@@ -186,7 +211,8 @@ async fn process_single_trace(
|
||||
.flatten();
|
||||
|
||||
let (existing_desc, existing_embed) = existing.unwrap_or((None, None));
|
||||
let need_vlm = existing_desc.is_none() || existing_desc.as_ref().map(|s| s.is_empty()).unwrap_or(true);
|
||||
let need_vlm =
|
||||
existing_desc.is_none() || existing_desc.as_ref().map(|s| s.is_empty()).unwrap_or(true);
|
||||
let need_embed = existing_embed.is_none();
|
||||
|
||||
let summary = if need_vlm {
|
||||
@@ -213,16 +239,13 @@ async fn process_single_trace(
|
||||
.as_ref()
|
||||
.and_then(|p| p.system_prompt.as_deref())
|
||||
.unwrap_or("You are a scene analysis assistant for a video surveillance/DAM system. Given a video key frame, write a concise summary (2-4 sentences, in the same language as the user) describing: what is happening, the people present (clothing/appearance), the setting/location, and any notable objects or actions. Be factual and specific.");
|
||||
|
||||
|
||||
let user_prompt = vlm_prompt
|
||||
.as_ref()
|
||||
.and_then(|p| p.user_prompt.as_deref())
|
||||
.unwrap_or("Summarize this key frame.");
|
||||
|
||||
let max_tokens = vlm_prompt
|
||||
.as_ref()
|
||||
.map(|p| p.max_tokens)
|
||||
.unwrap_or(512);
|
||||
|
||||
let max_tokens = vlm_prompt.as_ref().map(|p| p.max_tokens).unwrap_or(900);
|
||||
|
||||
// Call VLM
|
||||
let summary = match call_llm_vision(
|
||||
@@ -277,9 +300,11 @@ async fn process_single_trace(
|
||||
trace_id_i64,
|
||||
);
|
||||
if profile_path.exists() {
|
||||
if let Some(mut profile) =
|
||||
crate::core::file_profile::FaceTraceProfile::load(output_dir, file_uuid, trace_id_i64)
|
||||
{
|
||||
if let Some(mut profile) = crate::core::file_profile::FaceTraceProfile::load(
|
||||
output_dir,
|
||||
file_uuid,
|
||||
trace_id_i64,
|
||||
) {
|
||||
profile.vlm_summary = Some(summary.clone());
|
||||
if let Err(e) = profile.save(output_dir, None, None) {
|
||||
warn!(
|
||||
@@ -340,13 +365,7 @@ async fn process_single_trace(
|
||||
// Store in Qdrant (using u64 ID) with trace_id in payload
|
||||
let qdrant = QdrantDb::new();
|
||||
if let Err(e) = qdrant
|
||||
.upsert_vlm_embedding(
|
||||
point_id,
|
||||
&vector,
|
||||
file_uuid,
|
||||
trace_id,
|
||||
&summary,
|
||||
)
|
||||
.upsert_vlm_embedding(point_id, &vector, file_uuid, trace_id, &summary)
|
||||
.await
|
||||
{
|
||||
warn!(
|
||||
|
||||
Reference in New Issue
Block a user