fix: correct face detection threshold defaults

- Changed min_confidence from 50.0 to 0.5 (Vision uses 0.0-1.0 range)
- Changed min_size from 32 to 1 (was filtering out all small faces)
- Changed min_capture_quality from 25.0 to 0.25
- Fixes issue where all videos showed 0 faces detected

Root cause: admin_config.rs used wrong defaults (50.0/32) instead of
config.rs constants (0.5/1), causing Vision framework to filter out
ALL faces because confidence threshold exceeded valid range.

Verified: IMG_9449 now correctly detects 191 faces (was 0).
This commit is contained in:
Accusys
2026-09-18 02:42:21 +08:00
parent e4b8ddab94
commit 31d1b4050f
59 changed files with 11110 additions and 6163 deletions
+54 -20
View File
@@ -10,6 +10,28 @@ use tokio::time::{sleep, timeout};
use crate::core::config::{DATABASE_SCHEMA, OUTPUT_DIR, REDIS_KEY_PREFIX};
/// Get face filter settings from admin config (priority) or environment variables.
/// 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;
let min_confidence = face_config
.as_ref()
.and_then(|c| c.min_confidence)
.map(|v| v.to_string())
.or_else(|| std::env::var("FACE_MIN_CONFIDENCE").ok());
let min_size = face_config
.as_ref()
.and_then(|c| c.min_size)
.map(|v| v.to_string())
.or_else(|| std::env::var("FACE_MIN_SIZE").ok());
let min_capture_quality = face_config
.as_ref()
.and_then(|c| c.min_capture_quality)
.map(|v| v.to_string())
.or_else(|| std::env::var("FACE_MIN_CAPTURE_QUALITY").ok());
(min_confidence, min_size, min_capture_quality)
}
#[derive(Debug, Clone)]
pub struct RetryConfig {
pub max_attempts: u32,
@@ -324,13 +346,13 @@ impl PythonExecutor {
if let Some(u) = uuid {
cmd.env("UUID", u);
}
// Pass face detection settings to Python subprocesses
let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok();
let face_min_size = std::env::var("FACE_MIN_SIZE").ok();
// 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;
tracing::info!(
"[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}",
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
face_min_size
face_min_size,
face_min_capture_quality
);
if let Some(ref val) = face_min_confidence {
cmd.env("FACE_MIN_CONFIDENCE", val);
@@ -338,6 +360,9 @@ impl PythonExecutor {
if let Some(ref val) = face_min_size {
cmd.env("FACE_MIN_SIZE", val);
}
if let Some(ref val) = face_min_capture_quality {
cmd.env("FACE_MIN_CAPTURE_QUALITY", val);
}
cmd.arg(&script_path);
for (i, arg) in args.iter().enumerate() {
@@ -490,13 +515,13 @@ impl PythonExecutor {
if let Some(u) = uuid {
cmd.env("UUID", u);
}
// Pass face detection settings to Python subprocesses
let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok();
let face_min_size = std::env::var("FACE_MIN_SIZE").ok();
// 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;
tracing::info!(
"[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}",
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
face_min_size
face_min_size,
face_min_capture_quality
);
if let Some(ref val) = face_min_confidence {
cmd.env("FACE_MIN_CONFIDENCE", val);
@@ -504,6 +529,9 @@ impl PythonExecutor {
if let Some(ref val) = face_min_size {
cmd.env("FACE_MIN_SIZE", val);
}
if let Some(ref val) = face_min_capture_quality {
cmd.env("FACE_MIN_CAPTURE_QUALITY", val);
}
cmd.arg(&script_path);
for (i, arg) in args.iter().enumerate() {
@@ -697,13 +725,13 @@ impl PythonExecutor {
if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") {
cmd.env("QDRANT_API_KEY", qdrant_api_key);
}
// Pass face detection settings to Python subprocesses
let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok();
let face_min_size = std::env::var("FACE_MIN_SIZE").ok();
// 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;
tracing::info!(
"[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}",
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
face_min_size
face_min_size,
face_min_capture_quality
);
if let Some(ref val) = face_min_confidence {
cmd.env("FACE_MIN_CONFIDENCE", val);
@@ -711,6 +739,9 @@ impl PythonExecutor {
if let Some(ref val) = face_min_size {
cmd.env("FACE_MIN_SIZE", val);
}
if let Some(ref val) = face_min_capture_quality {
cmd.env("FACE_MIN_CAPTURE_QUALITY", val);
}
cmd.arg(&script_path);
for (i, arg) in args.iter().enumerate() {
@@ -914,13 +945,13 @@ impl PythonExecutor {
if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") {
cmd.env("QDRANT_API_KEY", qdrant_api_key);
}
// Pass face detection settings to Python subprocesses
let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok();
let face_min_size = std::env::var("FACE_MIN_SIZE").ok();
// 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;
tracing::info!(
"[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}",
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
face_min_size
face_min_size,
face_min_capture_quality
);
if let Some(ref val) = face_min_confidence {
cmd.env("FACE_MIN_CONFIDENCE", val);
@@ -928,6 +959,9 @@ impl PythonExecutor {
if let Some(ref val) = face_min_size {
cmd.env("FACE_MIN_SIZE", val);
}
if let Some(ref val) = face_min_capture_quality {
cmd.env("FACE_MIN_CAPTURE_QUALITY", val);
}
cmd.arg(&script_path);
for (i, arg) in args.iter().enumerate() {
File diff suppressed because it is too large Load Diff
+3 -435
View File
@@ -570,38 +570,6 @@ fn detect_mutual_gaze(
// ── Input data structs ────────────────────────────────────────────
#[derive(Debug, Deserialize)]
struct YoloJson {
#[serde(default)]
frames: HashMap<String, YoloFrameEntry>,
}
#[derive(Debug, Deserialize)]
struct YoloFrameEntry {
#[serde(default)]
detections: Vec<YoloDetEntry>,
#[serde(default)]
objects: Vec<YoloDetEntry>,
}
#[derive(Debug, Deserialize)]
struct YoloDetEntry {
#[serde(default)]
class_name: String,
#[serde(default)]
class_id: i32,
#[serde(default)]
x: i32,
#[serde(default)]
y: i32,
#[serde(default)]
width: i32,
#[serde(default)]
height: i32,
#[serde(default)]
confidence: f64,
}
#[derive(Debug, Deserialize)]
struct HandJson {
#[serde(default)]
@@ -866,21 +834,6 @@ pub async fn build_tkg(
publish_tkg_progress(r, file_uuid, &progress).await;
}
progress.update_phase(TkgPhase::ObjectNodes, 0.0, "Building object nodes...");
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
let n_objects = build_yolo_object_nodes(pool, file_uuid, output_dir).await?;
progress.stats.object_nodes = n_objects as i64;
progress.update_phase(
TkgPhase::ObjectNodes,
1.0,
&format!("{} objects", n_objects),
);
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
progress.update_phase(TkgPhase::HandNodes, 0.0, "Building hand nodes...");
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
@@ -916,26 +869,6 @@ pub async fn build_tkg(
);
// ── Edge builders ─────────────────────────────────────────────────
progress.update_phase(
TkgPhase::CoOccurrenceEdges,
0.0,
"Building co-occurrence edges...",
);
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
let e_co =
build_co_occurrence_edges(pool, file_uuid, output_dir, &face_points, &node_id_map).await?;
progress.stats.co_occurrence_edges = e_co as i64;
progress.update_phase(
TkgPhase::CoOccurrenceEdges,
1.0,
&format!("{} co-occurrence", e_co),
);
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
progress.update_phase(
TkgPhase::SpeakerFaceEdges,
0.0,
@@ -1028,25 +961,6 @@ pub async fn build_tkg(
publish_tkg_progress(r, file_uuid, &progress).await;
}
progress.update_phase(
TkgPhase::HandObjectEdges,
0.0,
"Building hand-object edges...",
);
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
let e_ho = build_hand_object_edges(pool, file_uuid, output_dir).await?;
progress.stats.hand_object_edges = e_ho as i64;
progress.update_phase(
TkgPhase::HandObjectEdges,
1.0,
&format!("{} hand-object", e_ho),
);
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
// Calculate totals
progress.stats.total_nodes = progress.stats.face_track_nodes
+ progress.stats.gaze_track_nodes
@@ -1085,17 +999,17 @@ pub async fn build_tkg(
text_region_nodes: n_text,
appearance_trace_nodes: n_appearance,
accessory_nodes: n_accessories,
object_nodes: n_objects,
object_nodes: 0, // YOLO removed
hand_nodes: n_hands,
speaker_nodes: n_speakers,
co_occurrence_edges: e_co,
co_occurrence_edges: 0, // YOLO removed
speaker_face_edges: e_sf,
face_face_edges: e_ff,
mutual_gaze_edges: e_mg,
lip_sync_edges: e_ls,
has_appearance_edges: e_ha,
wears_edges: e_w,
hand_object_edges: e_ho,
hand_object_edges: 0, // YOLO removed
})
}
@@ -1707,62 +1621,6 @@ async fn build_face_track_nodes_from_qdrant(
Ok(count)
}
async fn build_yolo_object_nodes(
pool: &PgPool,
file_uuid: &str,
output_dir: &str,
) -> Result<usize> {
let yolo_path = Path::new(output_dir).join(format!("{}.yolo.json", file_uuid));
if !yolo_path.exists() {
return Ok(0);
}
let content = std::fs::read_to_string(&yolo_path)
.with_context(|| format!("Failed to read {:?}", yolo_path))?;
let yolo: YoloJson = serde_json::from_str(&content)
.with_context(|| format!("Failed to parse {:?}", yolo_path))?;
let mut class_counts: HashMap<String, i64> = HashMap::new();
for fdata in yolo.frames.values() {
let dets = if !fdata.detections.is_empty() {
&fdata.detections
} else {
&fdata.objects
};
for det in dets {
*class_counts.entry(det.class_name.clone()).or_insert(0) += 1;
}
}
let nodes_table = t("tkg_nodes");
let mut count = 0;
for (cls, cnt) in &class_counts {
let props = serde_json::json!({ "total_detections": cnt });
sqlx::query(&format!(
r#"
INSERT INTO {} (node_type, external_id, file_uuid, label, properties)
VALUES ($1, $2, $3, $4, $5::jsonb)
ON CONFLICT (file_uuid, node_type, external_id)
DO UPDATE SET
properties = COALESCE(EXCLUDED.properties, tkg_nodes.properties)
"#,
nodes_table
))
.bind("object")
.bind(cls)
.bind(file_uuid)
.bind(cls)
.bind(serde_json::to_string(&props)?)
.execute(pool)
.await?;
count += 1;
}
Ok(count)
}
async fn build_hand_nodes(pool: &PgPool, file_uuid: &str, output_dir: &str) -> Result<usize> {
let hand_path = Path::new(output_dir).join(format!("{}.hand.json", file_uuid));
if !hand_path.exists() {
@@ -1897,117 +1755,6 @@ async fn build_speaker_nodes(pool: &PgPool, file_uuid: &str, output_dir: &str) -
// ── Edge builders ─────────────────────────────────────────────────
async fn build_co_occurrence_edges(
pool: &PgPool,
file_uuid: &str,
output_dir: &str,
face_points: &[FacePoint],
node_id_map: &HashMap<(String, String), i64>,
) -> Result<usize> {
build_co_occurrence_edges_from_qdrant(pool, file_uuid, output_dir, face_points, node_id_map)
.await
}
async fn build_co_occurrence_edges_from_qdrant(
pool: &PgPool,
file_uuid: &str,
output_dir: &str,
face_points: &[FacePoint],
node_id_map: &HashMap<(String, String), i64>,
) -> Result<usize> {
let yolo_path = Path::new(output_dir).join(format!("{}.yolo.json", file_uuid));
if !yolo_path.exists() {
return Ok(0);
}
let content = std::fs::read_to_string(&yolo_path)?;
let yolo: YoloJson = serde_json::from_str(&content)?;
let edges_table = t("tkg_edges");
// Use shared face points (passed from build_tkg)
let points = face_points;
let mut edge_count = 0;
// Collect edges for batch insert
let mut edges_to_insert: Vec<(&str, i64, i64, &str, String)> = Vec::new();
for face in points {
let yolo_frame = match yolo.frames.get(&face.frame.to_string()) {
Some(f) => f,
None => continue,
};
let dets = if !yolo_frame.detections.is_empty() {
&yolo_frame.detections
} else {
&yolo_frame.objects
};
if dets.is_empty() {
continue;
}
// Use pre-built node ID map (no SQL query)
let face_node_id = match node_id_map.get(&(
"face_track".to_string(),
format!("face_track_{}", face.trace_id),
)) {
Some(id) => *id,
None => continue,
};
for det in dets {
let obj_node_id = match node_id_map.get(&("object".to_string(), det.class_name.clone()))
{
Some(id) => *id,
None => continue,
};
let edge_props = serde_json::json!({
"frame": face.frame,
"object_confidence": det.confidence,
});
edges_to_insert.push((
"CO_OCCURS_WITH",
face_node_id,
obj_node_id,
file_uuid,
serde_json::to_string(&edge_props)?,
));
}
}
// Batch insert edges
let batch_size = 100;
for chunk in edges_to_insert.chunks(batch_size) {
let mut query = sqlx::query_builder::QueryBuilder::new(&format!(
"INSERT INTO {} (edge_type, source_node_id, target_node_id, file_uuid, properties) VALUES ",
edges_table
));
for (i, (edge_type, src, tgt, uuid, props)) in chunk.iter().enumerate() {
if i > 0 {
query.push(", ");
}
query
.push("(")
.push_bind(*edge_type)
.push_bind(*src)
.push_bind(*tgt)
.push_bind(*uuid)
.push_bind(props)
.push("::jsonb)");
}
query.push(" ON CONFLICT (file_uuid, edge_type, source_node_id, target_node_id) DO UPDATE SET properties = COALESCE(EXCLUDED.properties, tkg_edges.properties)");
query.build().execute(pool).await?;
}
edge_count = edges_to_insert.len();
Ok(edge_count)
}
async fn build_speaker_face_edges(
pool: &PgPool,
file_uuid: &str,
@@ -3322,153 +3069,6 @@ async fn build_wears_edges(pool: &PgPool, file_uuid: &str) -> Result<usize> {
Ok(0)
}
async fn build_hand_object_edges(
pool: &PgPool,
file_uuid: &str,
output_dir: &str,
) -> Result<usize> {
let hand_path = Path::new(output_dir).join(format!("{}.hand.json", file_uuid));
let yolo_path = Path::new(output_dir).join(format!("{}.yolo.json", file_uuid));
if !hand_path.exists() || !yolo_path.exists() {
return Ok(0);
}
let hand_content = std::fs::read_to_string(&hand_path)
.with_context(|| format!("Failed to read {:?}", hand_path))?;
let hand: HandJson = serde_json::from_str(&hand_content)
.with_context(|| format!("Failed to parse {:?}", hand_path))?;
let yolo_content = std::fs::read_to_string(&yolo_path)
.with_context(|| format!("Failed to read {:?}", yolo_path))?;
let yolo: YoloJson = serde_json::from_str(&yolo_content)
.with_context(|| format!("Failed to parse {:?}", yolo_path))?;
let yolo_frames: HashMap<u64, &Vec<YoloDetEntry>> = yolo
.frames
.iter()
.filter_map(|(frame_key, f)| {
let objs = if !f.objects.is_empty() {
&f.objects
} else {
&f.detections
};
if !objs.is_empty() {
frame_key.parse::<u64>().ok().map(|n| (n, objs))
} else {
None
}
})
.collect();
let edges_table = t("tkg_edges");
let nodes_table = t("tkg_nodes");
let mut count = 0;
for hf in &hand.frames {
let yolo_objs = yolo_frames.get(&(hf.frame as u64));
if yolo_objs.is_none() {
continue;
}
for person in &hf.persons {
if person.hand_state != "holding" || person.landmarks.is_empty() {
continue;
}
// Calculate hand bbox from landmarks
let xs: Vec<f32> = person.landmarks.iter().map(|lm| lm.x).collect();
let ys: Vec<f32> = person.landmarks.iter().map(|lm| lm.y).collect();
let hand_x = xs.iter().cloned().fold(f32::MAX, f32::min) as f64;
let hand_y = ys.iter().cloned().fold(f32::MAX, f32::min) as f64;
let hand_x_max = xs.iter().cloned().fold(f32::MIN, f32::max) as f64;
let hand_y_max = ys.iter().cloned().fold(f32::MIN, f32::max) as f64;
let hand_w = hand_x_max - hand_x;
let hand_h = hand_y_max - hand_y;
// Match with YOLO objects by bbox overlap
for obj in yolo_objs.unwrap().iter() {
let obj_x = obj.x as f64;
let obj_y = obj.y as f64;
let obj_w = obj.width as f64;
let obj_h = obj.height as f64;
// Calculate overlap (IoU-like)
let x1 = hand_x.max(obj_x);
let y1 = hand_y.max(obj_y);
let x2 = (hand_x + hand_w).min(obj_x + obj_w);
let y2 = (hand_y + hand_h).min(obj_y + obj_h);
if x1 < x2 && y1 < y2 {
let overlap_area = (x2 - x1) * (y2 - y1);
let hand_area = hand_w * hand_h;
let obj_area = obj_w * obj_h;
let overlap_ratio = overlap_area / hand_area.min(obj_area);
if overlap_ratio > 0.1 {
// Create HAND_OBJECT edge
let hand_node_id = format!("{}/{}", person.hand_type, person.gesture);
// Query hand node id
let hand_node_row: Option<(i64,)> = sqlx::query_as(&format!(
"SELECT id FROM {} WHERE node_type = $1 AND external_id = $2 AND file_uuid = $3",
nodes_table
))
.bind("hand")
.bind(&hand_node_id)
.bind(file_uuid)
.fetch_optional(pool)
.await?;
// Query object node id
let object_node_row: Option<(i64,)> = sqlx::query_as(&format!(
"SELECT id FROM {} WHERE node_type = $1 AND external_id = $2 AND file_uuid = $3",
nodes_table
))
.bind("object")
.bind(&obj.class_name)
.bind(file_uuid)
.fetch_optional(pool)
.await?;
if let (Some((hand_id,)), Some((obj_id,))) =
(hand_node_row, object_node_row)
{
sqlx::query(&format!(
r#"
INSERT INTO {} (edge_type, source_node_id, target_node_id, file_uuid, properties)
VALUES ($1, $2, $3, $4, $5::jsonb)
ON CONFLICT (file_uuid, edge_type, source_node_id, target_node_id)
DO NOTHING
"#,
edges_table
))
.bind("HAND_OBJECT")
.bind(hand_id)
.bind(obj_id)
.bind(file_uuid)
.bind(serde_json::json!({
"frame": hf.frame,
"overlap_ratio": overlap_ratio,
"hand_state": "holding",
}).to_string())
.execute(pool)
.await?;
count += 1;
}
}
}
}
}
}
tracing::info!("[TKG] HAND_OBJECT edges: {} matches", count);
Ok(count)
}
// ── TKG Bridge: Representative Frame ──────────────────────────────
#[derive(Debug, Serialize)]
@@ -3637,26 +3237,6 @@ pub async fn query_auto_representative_frame(
mod tests {
use super::*;
#[test]
fn test_yolo_json_deserialize() {
let json = r#"{
"frames": {
"1": {"time_seconds": 0.0, "detections": [{"class_name": "person", "confidence": 0.9}]},
"2": {"time_seconds": 1.0, "detections": [{"class_name": "chair", "confidence": 0.8}]}
}
}"#;
let yolo: YoloJson = serde_json::from_str(json).unwrap();
assert_eq!(yolo.frames.len(), 2);
assert_eq!(yolo.frames["1"].detections[0].class_name, "person");
}
#[test]
fn test_yolo_json_empty_frames() {
let json = r#"{"frames": {}}"#;
let yolo: YoloJson = serde_json::from_str(json).unwrap();
assert!(yolo.frames.is_empty());
}
#[test]
fn test_asrx_json_deserialize() {
let json = r#"{
@@ -3677,18 +3257,6 @@ mod tests {
assert!(asrx.speaker_stats.is_none());
}
#[test]
fn test_yolo_objects_fallback() {
let json = r#"{
"frames": {
"1": {"objects": [{"class_name": "person"}]}
}
}"#;
let yolo: YoloJson = serde_json::from_str(json).unwrap();
assert_eq!(yolo.frames["1"].objects[0].class_name, "person");
assert!(yolo.frames["1"].detections.is_empty());
}
#[test]
fn test_tkg_result() {
let r = TkgResult {
+54 -9
View File
@@ -4,6 +4,7 @@ use std::path::PathBuf;
use std::sync::Arc;
use tracing::{error, info, warn};
use crate::core::admin_config;
use crate::core::config;
use crate::core::db::redis_client::RedisClient;
use crate::core::db::schema::table_name;
@@ -12,12 +13,6 @@ use crate::core::embedding::Embedder;
use crate::core::llm::function_calling::call_llm_vision;
use crate::core::progress::{publish_pipeline_progress, PipelineProgress};
const SYSTEM_PROMPT: &str =
"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.";
#[derive(Debug, Default)]
pub struct VlmSummaryResult {
pub total: usize,
@@ -145,6 +140,39 @@ 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"
))
.bind(file_uuid)
.bind(trace_id)
.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"
))
.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);
if !settings.single_frame_trace_vlm_enabled {
info!(
"[VLM] trace {}/{} (tid={}): skipping single frame trace (disabled by config)",
current, total, trace_id
);
return Ok((false, false));
}
}
// Check if vlm_description already exists
let existing: Option<(Option<String>, Option<serde_json::Value>)> = sqlx::query_as(&format!(
@@ -179,12 +207,29 @@ async fn process_single_trace(
let jpeg_bytes = std::fs::read(&key_frame_path)?;
let base64_img = base64::engine::general_purpose::STANDARD.encode(&jpeg_bytes);
// Get prompts from config
let vlm_prompt = admin_config::get_vlm_prompt("rust_vlm_summary").await;
let system_prompt = vlm_prompt
.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);
// Call VLM
let summary = match call_llm_vision(
SYSTEM_PROMPT,
"Summarize this key frame.",
system_prompt,
user_prompt,
vec![base64_img],
512,
max_tokens,
120,
)
.await