fix: add min_capture_quality to FaceFilterSettings + trace profile fixes
- Add min_capture_quality to FaceFilterSettings (file_profile.rs) - Fix store_traced_faces.py: load embeddings from Qdrant with_vector=True - Fix face_tracker.py: force new traces when frame_gap > 30 - Fix backfill_trace_profiles.py: key_frame select=eq(n,N), bbox scaling, best_frame - Add best_frame to FaceTraceProfile (Rust + Python) - Fix min_capture_quality persistence in file-profile API
This commit is contained in:
+22
-10
@@ -1421,6 +1421,7 @@ pub async fn exec_trace_search(
|
||||
let sql = format!(
|
||||
"SELECT tp.file_uuid, tp.trace_id, tp.name, tp.start_frame, tp.end_frame, \
|
||||
tp.frame_count, tp.key_frame, tp.status, tp.avg_confidence, \
|
||||
tp.avg_capture_quality, tp.best_capture_quality, tp.best_confidence, \
|
||||
tp.vlm_description, tp.vlm_clothing, tp.vlm_tags, tp.vlm_location, \
|
||||
tp.vlm_setting, tp.vlm_lighting, COALESCE(v.file_name, ''), COALESCE(v.fps, 25.0) \
|
||||
FROM {} tp \
|
||||
@@ -1459,14 +1460,17 @@ pub async fn exec_trace_search(
|
||||
let key_frame: Option<String> = row.get(6);
|
||||
let status: Option<String> = row.get(7);
|
||||
let avg_confidence: Option<f64> = row.get(8);
|
||||
let vlm_description: Option<String> = row.get(9);
|
||||
let vlm_clothing: Option<String> = row.get(10);
|
||||
let vlm_tags: Option<Vec<String>> = row.get(11);
|
||||
let vlm_location: Option<String> = row.get(12);
|
||||
let vlm_setting: Option<String> = row.get(13);
|
||||
let vlm_lighting: Option<String> = row.get(14);
|
||||
let file_name: String = row.get(15);
|
||||
let fps: f64 = row.get(16);
|
||||
let avg_capture_quality: Option<f64> = row.get(9);
|
||||
let best_capture_quality: Option<f64> = row.get(10);
|
||||
let best_confidence: Option<f64> = row.get(11);
|
||||
let vlm_description: Option<String> = row.get(12);
|
||||
let vlm_clothing: Option<String> = row.get(13);
|
||||
let vlm_tags: Option<Vec<String>> = row.get(14);
|
||||
let vlm_location: Option<String> = row.get(15);
|
||||
let vlm_setting: Option<String> = row.get(16);
|
||||
let vlm_lighting: Option<String> = row.get(17);
|
||||
let file_name: String = row.get(18);
|
||||
let fps: f64 = row.get(19);
|
||||
|
||||
let start_time = start_frame.map(|f| (f as f64 / fps).round() / 100.0);
|
||||
let end_time = end_frame.map(|f| (f as f64 / fps).round() / 100.0);
|
||||
@@ -1485,6 +1489,9 @@ pub async fn exec_trace_search(
|
||||
"key_frame": key_frame,
|
||||
"status": status,
|
||||
"avg_confidence": avg_confidence,
|
||||
"best_confidence": best_confidence,
|
||||
"avg_capture_quality": avg_capture_quality,
|
||||
"best_capture_quality": best_capture_quality,
|
||||
"vlm_description": vlm_description,
|
||||
"vlm_clothing": vlm_clothing,
|
||||
"vlm_tags": vlm_tags,
|
||||
@@ -1652,6 +1659,7 @@ pub async fn exec_face_profile_search(
|
||||
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
|
||||
tp.start_frame, tp.end_frame, tp.frame_count, \
|
||||
tp.key_frame, tp.key_face, tp.avg_confidence, \
|
||||
tp.avg_capture_quality, tp.best_capture_quality, \
|
||||
n.external_id \
|
||||
FROM {} tp \
|
||||
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
|
||||
@@ -1691,7 +1699,9 @@ pub async fn exec_face_profile_search(
|
||||
let key_frame: Option<String> = row.get(6);
|
||||
let key_face: Option<String> = row.get(7);
|
||||
let avg_confidence: Option<f64> = row.get(8);
|
||||
let external_id: Option<String> = row.get(9);
|
||||
let avg_capture_quality: Option<f64> = row.get(9);
|
||||
let best_capture_quality: Option<f64> = row.get(10);
|
||||
let external_id: Option<String> = row.get(11);
|
||||
|
||||
serde_json::json!({
|
||||
"card_type": "face_profile",
|
||||
@@ -1704,7 +1714,9 @@ pub async fn exec_face_profile_search(
|
||||
"frame_count": frame_count,
|
||||
"key_frame": key_frame,
|
||||
"key_face": key_face,
|
||||
"avg_confidence": avg_confidence
|
||||
"avg_confidence": avg_confidence,
|
||||
"avg_capture_quality": avg_capture_quality,
|
||||
"best_capture_quality": best_capture_quality
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -145,6 +145,13 @@ pub static MONGODB_DATABASE: Lazy<String> =
|
||||
pub static QDRANT_COLLECTION: Lazy<String> =
|
||||
Lazy::new(|| env::var("QDRANT_COLLECTION").unwrap_or_else(|_| "momentry_rule1".to_string()));
|
||||
|
||||
// ─── Face detection thresholds (single source of truth) ───
|
||||
// Defaults mirror Apple Vision native detection (0.5 confidence / 1px min size).
|
||||
// Keep scripts/swift_processors/swift_face.swift and scripts/face_processor.py in sync.
|
||||
pub const FACE_MIN_CONFIDENCE_DEFAULT: f64 = 0.5; // detection threshold (0-1)
|
||||
pub const FACE_MIN_SIZE_DEFAULT: i32 = 1; // detection min face size (px)
|
||||
pub const FACE_FILTER_CONFIDENCE_PCT_DEFAULT: f64 = 50.0; // videos.face_filter (0-100%)
|
||||
|
||||
pub mod processor {
|
||||
use super::*;
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ use uuid::Uuid;
|
||||
|
||||
use super::{schema, Database, QdrantDb};
|
||||
use crate::core::chunk::types::{Chunk, ChunkRule, ChunkType};
|
||||
use crate::core::config::{FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT};
|
||||
use crate::core::text::synonym::normalize_chinese_query;
|
||||
use crate::core::text::{
|
||||
global_synonym_expander,
|
||||
@@ -1028,6 +1029,7 @@ impl PostgresDb {
|
||||
"content_hash TEXT",
|
||||
"proxy_path TEXT",
|
||||
"audio_track TEXT",
|
||||
"face_filter JSONB",
|
||||
];
|
||||
for col in &video_cols {
|
||||
let (col_name, col_def) = col.split_once(' ').unwrap_or((col, ""));
|
||||
@@ -1268,7 +1270,29 @@ impl PostgresDb {
|
||||
sqlx::query("CREATE TABLE IF NOT EXISTS strangers (id SERIAL PRIMARY KEY, file_uuid TEXT, trace_id INTEGER, metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?;
|
||||
|
||||
// ── 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 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, best_confidence DOUBLE PRECISION, avg_capture_quality DOUBLE PRECISION, best_capture_quality DOUBLE PRECISION, avg_bbox JSONB, best_bbox JSONB, 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?;
|
||||
// Migration: add new fields to existing trace_profiles tables (safe no-op if columns exist)
|
||||
sqlx::query(
|
||||
"ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_confidence DOUBLE PRECISION",
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS avg_capture_quality DOUBLE PRECISION",
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_capture_quality DOUBLE PRECISION",
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS avg_bbox JSONB")
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_bbox JSONB")
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"CREATE INDEX IF NOT EXISTS idx_trace_profiles_file_uuid ON trace_profiles(file_uuid)",
|
||||
)
|
||||
@@ -1971,7 +1995,13 @@ impl PostgresDb {
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
let face_settings_json = face_settings.map(|v| v.to_string()).unwrap_or_else(|| "{\"min_confidence\": 0.75, \"min_size\": 64}".to_string());
|
||||
let face_settings_json = face_settings.map(|v| v.to_string()).unwrap_or_else(|| {
|
||||
serde_json::json!({
|
||||
"min_confidence": FACE_MIN_CONFIDENCE_DEFAULT,
|
||||
"min_size": FACE_MIN_SIZE_DEFAULT
|
||||
})
|
||||
.to_string()
|
||||
});
|
||||
|
||||
let row = if let Some(job_id) = existing_id {
|
||||
// Update existing job
|
||||
|
||||
+12
-1
@@ -42,7 +42,8 @@ pub async fn upsert_trace_profile(
|
||||
// Use LEFT JOIN to get tkg_nodes data for backfilling
|
||||
let sql = format!(
|
||||
"INSERT INTO {tp_table} (file_uuid, trace_id, name, start_frame, end_frame, \
|
||||
frame_count, key_frame, key_face, status, avg_confidence, properties) \
|
||||
frame_count, key_frame, key_face, status, avg_confidence, \
|
||||
best_confidence, avg_capture_quality, best_capture_quality, avg_bbox, best_bbox, properties) \
|
||||
SELECT $1, $2, $3, \
|
||||
COALESCE((tn.properties->>'start_frame')::bigint, tp.start_frame), \
|
||||
COALESCE((tn.properties->>'end_frame')::bigint, tp.end_frame), \
|
||||
@@ -51,6 +52,11 @@ pub async fn upsert_trace_profile(
|
||||
COALESCE(tn.properties->>'key_face', tp.key_face), \
|
||||
'pending', \
|
||||
COALESCE((tn.properties->>'avg_confidence')::double precision, tp.avg_confidence), \
|
||||
COALESCE((tn.properties->>'best_confidence')::double precision, tp.best_confidence), \
|
||||
COALESCE((tn.properties->>'avg_capture_quality')::double precision, tp.avg_capture_quality), \
|
||||
COALESCE((tn.properties->>'best_capture_quality')::double precision, tp.best_capture_quality), \
|
||||
COALESCE((tn.properties->>'avg_bbox')::jsonb, tp.avg_bbox), \
|
||||
COALESCE((tn.properties->>'best_bbox')::jsonb, tp.best_bbox), \
|
||||
COALESCE($4::jsonb, tn.properties, '{{}}'::jsonb) \
|
||||
FROM (VALUES (1)) AS dummy \
|
||||
LEFT JOIN {tkg_table} tn ON tn.file_uuid = $1 \
|
||||
@@ -64,6 +70,11 @@ pub async fn upsert_trace_profile(
|
||||
key_frame = COALESCE(EXCLUDED.key_frame, {tp_table}.key_frame), \
|
||||
key_face = COALESCE(EXCLUDED.key_face, {tp_table}.key_face), \
|
||||
avg_confidence = COALESCE(EXCLUDED.avg_confidence, {tp_table}.avg_confidence), \
|
||||
best_confidence = COALESCE(EXCLUDED.best_confidence, {tp_table}.best_confidence), \
|
||||
avg_capture_quality = COALESCE(EXCLUDED.avg_capture_quality, {tp_table}.avg_capture_quality), \
|
||||
best_capture_quality = COALESCE(EXCLUDED.best_capture_quality, {tp_table}.best_capture_quality), \
|
||||
avg_bbox = COALESCE(EXCLUDED.avg_bbox, {tp_table}.avg_bbox), \
|
||||
best_bbox = COALESCE(EXCLUDED.best_bbox, {tp_table}.best_bbox), \
|
||||
updated_at = NOW()",
|
||||
);
|
||||
|
||||
|
||||
@@ -8,26 +8,26 @@ pub struct FaceFilterFeatures {
|
||||
pub face_id: String,
|
||||
pub file_uuid: String,
|
||||
pub frame: i32,
|
||||
|
||||
|
||||
// Bbox size (pre-computed as min(width, height))
|
||||
pub bbox_size: Option<i32>,
|
||||
|
||||
|
||||
// Landmark geometric features
|
||||
pub eye_ratio: Option<f64>,
|
||||
pub nose_ratio: Option<f64>,
|
||||
pub pose_score: Option<f64>,
|
||||
|
||||
|
||||
// MediaPipe verification features
|
||||
pub mediapipe_detected: Option<bool>,
|
||||
pub mediapipe_iou: Option<f64>,
|
||||
|
||||
|
||||
// Embedding similarity features
|
||||
pub embedding_similarity: Option<f64>,
|
||||
|
||||
|
||||
// Temporal consistency features
|
||||
pub consecutive_frames: Option<i32>,
|
||||
pub total_frames_detected: Option<i32>,
|
||||
|
||||
|
||||
// Source information
|
||||
pub apple_vision_confidence: Option<f64>,
|
||||
pub mediapipe_confidence: Option<f64>,
|
||||
@@ -173,7 +173,11 @@ impl FilterEngine {
|
||||
}
|
||||
|
||||
/// Apply landmark analysis rule
|
||||
fn apply_landmark_analysis(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||
fn apply_landmark_analysis(
|
||||
&self,
|
||||
features: &FaceFilterFeatures,
|
||||
config: &RuleConfig,
|
||||
) -> RuleResult {
|
||||
if !config.enabled {
|
||||
return RuleResult {
|
||||
enabled: false,
|
||||
@@ -190,7 +194,7 @@ impl FilterEngine {
|
||||
if let Some(eye_ratio) = features.eye_ratio {
|
||||
let min = config.thresholds["eye_ratio_min"].as_f64().unwrap_or(0.25);
|
||||
let max = config.thresholds["eye_ratio_max"].as_f64().unwrap_or(0.55);
|
||||
|
||||
|
||||
if eye_ratio < min || eye_ratio > max {
|
||||
score -= 0.25;
|
||||
reasons.push(format!("eye_ratio abnormal ({:.3})", eye_ratio));
|
||||
@@ -200,7 +204,7 @@ impl FilterEngine {
|
||||
// Check nose ratio
|
||||
if let Some(nose_ratio) = features.nose_ratio {
|
||||
let min = config.thresholds["nose_ratio_min"].as_f64().unwrap_or(0.08);
|
||||
|
||||
|
||||
if nose_ratio < min {
|
||||
score -= 0.25;
|
||||
reasons.push(format!("nose_ratio too low ({:.3})", nose_ratio));
|
||||
@@ -210,7 +214,7 @@ impl FilterEngine {
|
||||
// Check pose score
|
||||
if let Some(pose_score) = features.pose_score {
|
||||
let max = config.thresholds["pose_score_max"].as_f64().unwrap_or(0.8);
|
||||
|
||||
|
||||
if pose_score > max {
|
||||
score -= 0.25;
|
||||
reasons.push(format!("pose_score too high ({:.3})", pose_score));
|
||||
@@ -233,7 +237,11 @@ impl FilterEngine {
|
||||
}
|
||||
|
||||
/// Apply MediaPipe verification rule
|
||||
fn apply_mediapipe_verification(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||
fn apply_mediapipe_verification(
|
||||
&self,
|
||||
features: &FaceFilterFeatures,
|
||||
config: &RuleConfig,
|
||||
) -> RuleResult {
|
||||
if !config.enabled {
|
||||
return RuleResult {
|
||||
enabled: false,
|
||||
@@ -256,7 +264,7 @@ impl FilterEngine {
|
||||
// Check IoU if available
|
||||
if let Some(iou) = features.mediapipe_iou {
|
||||
let min_iou = config.thresholds["min_iou"].as_f64().unwrap_or(0.3);
|
||||
|
||||
|
||||
if iou < min_iou {
|
||||
return RuleResult {
|
||||
enabled: true,
|
||||
@@ -276,7 +284,11 @@ impl FilterEngine {
|
||||
}
|
||||
|
||||
/// Apply embedding similarity rule
|
||||
fn apply_embedding_similarity(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||
fn apply_embedding_similarity(
|
||||
&self,
|
||||
features: &FaceFilterFeatures,
|
||||
config: &RuleConfig,
|
||||
) -> RuleResult {
|
||||
if !config.enabled {
|
||||
return RuleResult {
|
||||
enabled: false,
|
||||
@@ -288,7 +300,7 @@ impl FilterEngine {
|
||||
|
||||
if let Some(similarity) = features.embedding_similarity {
|
||||
let min_similarity = config.thresholds["min_similarity"].as_f64().unwrap_or(0.70);
|
||||
|
||||
|
||||
if similarity < min_similarity {
|
||||
return RuleResult {
|
||||
enabled: true,
|
||||
@@ -308,7 +320,11 @@ impl FilterEngine {
|
||||
}
|
||||
|
||||
/// Apply temporal consistency rule
|
||||
fn apply_temporal_consistency(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||
fn apply_temporal_consistency(
|
||||
&self,
|
||||
features: &FaceFilterFeatures,
|
||||
config: &RuleConfig,
|
||||
) -> RuleResult {
|
||||
if !config.enabled {
|
||||
return RuleResult {
|
||||
enabled: false,
|
||||
@@ -319,8 +335,10 @@ impl FilterEngine {
|
||||
}
|
||||
|
||||
if let Some(consecutive) = features.consecutive_frames {
|
||||
let min_consecutive = config.thresholds["min_consecutive_frames"].as_i64().unwrap_or(3) as i32;
|
||||
|
||||
let min_consecutive = config.thresholds["min_consecutive_frames"]
|
||||
.as_i64()
|
||||
.unwrap_or(3) as i32;
|
||||
|
||||
if consecutive < min_consecutive {
|
||||
return RuleResult {
|
||||
enabled: true,
|
||||
@@ -343,42 +361,54 @@ impl FilterEngine {
|
||||
/// Default filter configuration
|
||||
pub fn default_filter_config() -> FilterRuleConfig {
|
||||
let mut rules = HashMap::new();
|
||||
|
||||
rules.insert("landmark_analysis".to_string(), RuleConfig {
|
||||
enabled: true,
|
||||
weight: 0.3,
|
||||
thresholds: serde_json::json!({
|
||||
"eye_ratio_min": 0.25,
|
||||
"eye_ratio_max": 0.55,
|
||||
"nose_ratio_min": 0.08,
|
||||
"pose_score_max": 0.8
|
||||
}),
|
||||
});
|
||||
|
||||
rules.insert("mediapipe_verification".to_string(), RuleConfig {
|
||||
enabled: true,
|
||||
weight: 0.2,
|
||||
thresholds: serde_json::json!({
|
||||
"min_iou": 0.3
|
||||
}),
|
||||
});
|
||||
|
||||
rules.insert("embedding_similarity".to_string(), RuleConfig {
|
||||
enabled: true,
|
||||
weight: 0.3,
|
||||
thresholds: serde_json::json!({
|
||||
"min_similarity": 0.70
|
||||
}),
|
||||
});
|
||||
|
||||
rules.insert("temporal_consistency".to_string(), RuleConfig {
|
||||
enabled: true,
|
||||
weight: 0.2,
|
||||
thresholds: serde_json::json!({
|
||||
"min_consecutive_frames": 3
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
rules.insert(
|
||||
"landmark_analysis".to_string(),
|
||||
RuleConfig {
|
||||
enabled: true,
|
||||
weight: 0.3,
|
||||
thresholds: serde_json::json!({
|
||||
"eye_ratio_min": 0.25,
|
||||
"eye_ratio_max": 0.55,
|
||||
"nose_ratio_min": 0.08,
|
||||
"pose_score_max": 0.8
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
rules.insert(
|
||||
"mediapipe_verification".to_string(),
|
||||
RuleConfig {
|
||||
enabled: true,
|
||||
weight: 0.2,
|
||||
thresholds: serde_json::json!({
|
||||
"min_iou": 0.3
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
rules.insert(
|
||||
"embedding_similarity".to_string(),
|
||||
RuleConfig {
|
||||
enabled: true,
|
||||
weight: 0.3,
|
||||
thresholds: serde_json::json!({
|
||||
"min_similarity": 0.70
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
rules.insert(
|
||||
"temporal_consistency".to_string(),
|
||||
RuleConfig {
|
||||
enabled: true,
|
||||
weight: 0.2,
|
||||
thresholds: serde_json::json!({
|
||||
"min_consecutive_frames": 3
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
FilterRuleConfig {
|
||||
version: "1.0".to_string(),
|
||||
rules,
|
||||
@@ -398,11 +428,12 @@ mod tests {
|
||||
fn test_filter_engine_accept() {
|
||||
let config = default_filter_config();
|
||||
let engine = FilterEngine::new(config);
|
||||
|
||||
|
||||
let features = FaceFilterFeatures {
|
||||
face_id: "test_001".to_string(),
|
||||
file_uuid: "test".to_string(),
|
||||
frame: 0,
|
||||
bbox_size: Some(80),
|
||||
eye_ratio: Some(0.37),
|
||||
nose_ratio: Some(0.15),
|
||||
pose_score: Some(0.1),
|
||||
@@ -415,7 +446,7 @@ mod tests {
|
||||
mediapipe_confidence: Some(0.9),
|
||||
primary_source: Some("apple_vision".to_string()),
|
||||
};
|
||||
|
||||
|
||||
let result = engine.filter_face(&features).unwrap();
|
||||
assert_eq!(result.recommendation, FilterRecommendation::Accept);
|
||||
}
|
||||
@@ -424,24 +455,25 @@ mod tests {
|
||||
fn test_filter_engine_reject() {
|
||||
let config = default_filter_config();
|
||||
let engine = FilterEngine::new(config);
|
||||
|
||||
|
||||
let features = FaceFilterFeatures {
|
||||
face_id: "test_002".to_string(),
|
||||
file_uuid: "test".to_string(),
|
||||
frame: 671,
|
||||
eye_ratio: Some(0.33),
|
||||
nose_ratio: Some(0.02), // Abnormal
|
||||
pose_score: Some(0.08),
|
||||
mediapipe_detected: Some(false), // Not detected
|
||||
bbox_size: Some(40),
|
||||
eye_ratio: Some(0.60), // Abnormal (above max 0.55)
|
||||
nose_ratio: Some(0.02), // Abnormal
|
||||
pose_score: Some(0.9), // Abnormal (above max 0.8)
|
||||
mediapipe_detected: Some(false), // Not detected
|
||||
mediapipe_iou: Some(0.0),
|
||||
embedding_similarity: Some(0.15), // Low similarity
|
||||
consecutive_frames: Some(1), // Single frame
|
||||
embedding_similarity: Some(0.05), // Very low similarity
|
||||
consecutive_frames: Some(1), // Single frame
|
||||
total_frames_detected: Some(1),
|
||||
apple_vision_confidence: Some(0.84),
|
||||
mediapipe_confidence: None,
|
||||
primary_source: Some("apple_vision".to_string()),
|
||||
};
|
||||
|
||||
|
||||
let result = engine.filter_face(&features).unwrap();
|
||||
assert_eq!(result.recommendation, FilterRecommendation::Reject);
|
||||
}
|
||||
|
||||
@@ -2,17 +2,21 @@ use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::core::config::{FACE_FILTER_CONFIDENCE_PCT_DEFAULT, FACE_MIN_SIZE_DEFAULT};
|
||||
|
||||
/// Version of the file profile schema.
|
||||
const PROFILE_VERSION: &str = "1.0";
|
||||
|
||||
// ─── Data Types ───
|
||||
|
||||
/// Per-file face detection thresholds. `min_confidence` is 0–100 (%),
|
||||
/// `min_size` is px. Mirrors `videos.face_filter` DB column (same units).
|
||||
/// `min_size` is px, `min_capture_quality` is 0–1. Mirrors `videos.face_filter` DB column.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FaceFilterSettings {
|
||||
pub min_confidence: f64,
|
||||
pub min_size: i32,
|
||||
#[serde(default)]
|
||||
pub min_capture_quality: f64,
|
||||
}
|
||||
|
||||
impl FaceFilterSettings {
|
||||
@@ -20,8 +24,9 @@ impl FaceFilterSettings {
|
||||
/// Filter later for display; detect everything first.
|
||||
pub fn defaults() -> Self {
|
||||
Self {
|
||||
min_confidence: 50.0,
|
||||
min_size: 1,
|
||||
min_confidence: FACE_FILTER_CONFIDENCE_PCT_DEFAULT,
|
||||
min_size: FACE_MIN_SIZE_DEFAULT,
|
||||
min_capture_quality: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -378,7 +383,19 @@ pub struct FaceTraceProfile {
|
||||
pub frame_count: i64,
|
||||
pub start_frame: i64,
|
||||
pub end_frame: i64,
|
||||
#[serde(default)]
|
||||
pub best_frame: Option<i64>,
|
||||
pub avg_confidence: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub best_confidence: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub avg_capture_quality: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub best_capture_quality: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub avg_bbox: Option<serde_json::Value>,
|
||||
#[serde(default)]
|
||||
pub best_bbox: Option<serde_json::Value>,
|
||||
pub key_frame: Option<String>, // filename: key_frame.jpg
|
||||
pub key_face: Option<String>, // filename: key_face.jpg
|
||||
pub status: String, // pending / bound / merged
|
||||
@@ -406,7 +423,13 @@ impl FaceTraceProfile {
|
||||
frame_count: i64,
|
||||
start_frame: i64,
|
||||
end_frame: i64,
|
||||
best_frame: i64,
|
||||
avg_confidence: Option<f64>,
|
||||
avg_capture_quality: Option<f64>,
|
||||
best_confidence: f64,
|
||||
best_capture_quality: f64,
|
||||
avg_bbox: serde_json::Value,
|
||||
best_bbox: Option<serde_json::Value>,
|
||||
) -> Self {
|
||||
Self {
|
||||
version: PROFILE_VERSION.to_string(),
|
||||
@@ -416,7 +439,13 @@ impl FaceTraceProfile {
|
||||
frame_count,
|
||||
start_frame,
|
||||
end_frame,
|
||||
best_frame: Some(best_frame),
|
||||
avg_confidence,
|
||||
best_confidence: Some(best_confidence),
|
||||
avg_capture_quality,
|
||||
best_capture_quality: Some(best_capture_quality),
|
||||
avg_bbox: Some(avg_bbox),
|
||||
best_bbox,
|
||||
key_frame: None,
|
||||
key_face: None,
|
||||
status: "pending".to_string(),
|
||||
|
||||
@@ -107,8 +107,10 @@ mod tests {
|
||||
#[test]
|
||||
fn test_asr_result_serialization() {
|
||||
let result = AsrResult {
|
||||
status: None,
|
||||
language: Some("en".to_string()),
|
||||
language_probability: Some(0.95),
|
||||
segment_count: 2,
|
||||
segments: vec![
|
||||
AsrSegment {
|
||||
start_time: 0.0,
|
||||
@@ -116,6 +118,7 @@ mod tests {
|
||||
start_frame: Some(0),
|
||||
end_frame: Some(60),
|
||||
text: "Hello world".to_string(),
|
||||
confidence: 0.95,
|
||||
},
|
||||
AsrSegment {
|
||||
start_time: 2.5,
|
||||
@@ -123,6 +126,7 @@ mod tests {
|
||||
start_frame: Some(60),
|
||||
end_frame: Some(120),
|
||||
text: "Test speech".to_string(),
|
||||
confidence: 0.9,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -157,6 +161,7 @@ mod tests {
|
||||
start_frame: Some(0),
|
||||
end_frame: Some(24),
|
||||
text: String::new(),
|
||||
confidence: 0.0,
|
||||
};
|
||||
assert_eq!(segment.start_time, 0.0);
|
||||
assert_eq!(segment.end_time, 1.0);
|
||||
@@ -166,9 +171,11 @@ mod tests {
|
||||
#[test]
|
||||
fn test_asr_result_empty_segments() {
|
||||
let result = AsrResult {
|
||||
status: None,
|
||||
language: None,
|
||||
language_probability: None,
|
||||
segments: vec![],
|
||||
segment_count: 0,
|
||||
};
|
||||
assert!(result.language.is_none());
|
||||
assert!(result.segments.is_empty());
|
||||
|
||||
@@ -214,6 +214,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_asrx_result_serialization() {
|
||||
let result = AsrxResult {
|
||||
status: None,
|
||||
language: Some("en".to_string()),
|
||||
segments: vec![AsrxSegment {
|
||||
start_time: 0.0,
|
||||
@@ -227,6 +228,7 @@ mod tests {
|
||||
quality: None,
|
||||
}],
|
||||
embeddings: None,
|
||||
segment_count: 1,
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&result).unwrap();
|
||||
@@ -255,9 +257,11 @@ mod tests {
|
||||
#[test]
|
||||
fn test_asrx_result_empty_segments() {
|
||||
let result = AsrxResult {
|
||||
status: None,
|
||||
language: None,
|
||||
segments: vec![],
|
||||
embeddings: None,
|
||||
segment_count: 0,
|
||||
};
|
||||
assert!(result.segments.is_empty());
|
||||
assert!(result.language.is_none());
|
||||
|
||||
@@ -53,6 +53,8 @@ pub struct Face {
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub confidence: f32,
|
||||
#[serde(default)]
|
||||
pub capture_quality: Option<f32>,
|
||||
pub embedding: Option<Vec<f32>>,
|
||||
pub landmarks: Option<serde_json::Value>,
|
||||
pub pose_angle: Option<serde_json::Value>,
|
||||
@@ -148,8 +150,10 @@ mod tests {
|
||||
#[test]
|
||||
fn test_face_result_serialization() {
|
||||
let result = FaceResult {
|
||||
status: None,
|
||||
frame_count: 100,
|
||||
fps: 30.0,
|
||||
total_faces: 1,
|
||||
frames: vec![FaceFrame {
|
||||
frame: 0,
|
||||
timestamp: 0.0,
|
||||
@@ -160,6 +164,7 @@ mod tests {
|
||||
width: 50,
|
||||
height: 60,
|
||||
confidence: 0.95,
|
||||
capture_quality: Some(0.9),
|
||||
embedding: Some(vec![0.1, 0.2, 0.3]),
|
||||
landmarks: Some(serde_json::json!([[10.0, 20.0], [30.0, 40.0]])),
|
||||
pose_angle: None,
|
||||
@@ -216,9 +221,11 @@ mod tests {
|
||||
#[test]
|
||||
fn test_face_result_empty_frames() {
|
||||
let result = FaceResult {
|
||||
status: None,
|
||||
frame_count: 0,
|
||||
fps: 0.0,
|
||||
frames: vec![],
|
||||
total_faces: 0,
|
||||
};
|
||||
assert!(result.frames.is_empty());
|
||||
}
|
||||
@@ -232,6 +239,7 @@ mod tests {
|
||||
width: 10,
|
||||
height: 10,
|
||||
confidence: 0.5,
|
||||
capture_quality: None,
|
||||
embedding: None,
|
||||
landmarks: None,
|
||||
pose_angle: None,
|
||||
@@ -249,6 +257,7 @@ mod tests {
|
||||
width: 50,
|
||||
height: 60,
|
||||
confidence: 0.95,
|
||||
capture_quality: Some(0.8),
|
||||
embedding: Some(vec![0.1; 512]),
|
||||
landmarks: None,
|
||||
pose_angle: None,
|
||||
|
||||
+73
-10
@@ -20,6 +20,7 @@ struct FacePoint {
|
||||
w: f64,
|
||||
h: f64,
|
||||
confidence: f64,
|
||||
capture_quality: f64,
|
||||
point_id: Option<String>,
|
||||
}
|
||||
|
||||
@@ -121,6 +122,7 @@ fn parse_face_points(points: Vec<serde_json::Value>) -> Vec<FacePoint> {
|
||||
w,
|
||||
h,
|
||||
confidence: payload["confidence"].as_f64().unwrap_or(0.5),
|
||||
capture_quality: payload["capture_quality"].as_f64().unwrap_or(0.0),
|
||||
point_id: p["id"].as_u64().map(|id| id.to_string()),
|
||||
})
|
||||
})
|
||||
@@ -1134,10 +1136,16 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
sum_w: f64,
|
||||
sum_h: f64,
|
||||
sum_confidence: f64,
|
||||
sum_capture_quality: f64,
|
||||
frames: Vec<(i64, f64, f64, f64, f64)>, // (frame, x, y, w, h)
|
||||
best_frame: i64,
|
||||
best_confidence: f64,
|
||||
best_point_id: Option<String>,
|
||||
cq_best_frame: i64,
|
||||
cq_best_quality: f64,
|
||||
cq_best_point_id: Option<String>,
|
||||
cq_best_bbox: Option<serde_json::Value>,
|
||||
best_bbox: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
let mut traces: HashMap<i64, TraceAgg> = HashMap::new();
|
||||
@@ -1151,10 +1159,16 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
sum_w: 0.0,
|
||||
sum_h: 0.0,
|
||||
sum_confidence: 0.0,
|
||||
sum_capture_quality: 0.0,
|
||||
frames: vec![],
|
||||
best_frame: 0,
|
||||
best_confidence: 0.0,
|
||||
best_point_id: None,
|
||||
cq_best_frame: 0,
|
||||
cq_best_quality: 0.0,
|
||||
cq_best_point_id: None,
|
||||
cq_best_bbox: None,
|
||||
best_bbox: None,
|
||||
});
|
||||
entry.frame_count += 1;
|
||||
entry.start_f = entry.start_f.min(p.frame);
|
||||
@@ -1164,12 +1178,31 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
entry.sum_w += p.w;
|
||||
entry.sum_h += p.h;
|
||||
entry.sum_confidence += p.confidence;
|
||||
entry.sum_capture_quality += p.capture_quality;
|
||||
entry.frames.push((p.frame, p.x, p.y, p.w, p.h));
|
||||
// Track best face (highest confidence)
|
||||
if p.confidence > entry.best_confidence {
|
||||
entry.best_confidence = p.confidence;
|
||||
entry.best_frame = p.frame;
|
||||
entry.best_point_id = p.point_id.clone();
|
||||
entry.best_bbox = Some(serde_json::json!({
|
||||
"x": p.x.round() as i64,
|
||||
"y": p.y.round() as i64,
|
||||
"width": p.w.round() as i64,
|
||||
"height": p.h.round() as i64,
|
||||
}));
|
||||
}
|
||||
// Track best capture quality face (used for key frame / key face set)
|
||||
if p.capture_quality > entry.cq_best_quality {
|
||||
entry.cq_best_quality = p.capture_quality;
|
||||
entry.cq_best_frame = p.frame;
|
||||
entry.cq_best_point_id = p.point_id.clone();
|
||||
entry.cq_best_bbox = Some(serde_json::json!({
|
||||
"x": p.x.round() as i64,
|
||||
"y": p.y.round() as i64,
|
||||
"width": p.w.round() as i64,
|
||||
"height": p.h.round() as i64,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1210,24 +1243,34 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
0.0
|
||||
};
|
||||
|
||||
let avg_capture_quality = if agg.frame_count > 0 {
|
||||
agg.sum_capture_quality / agg.frame_count as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let props = serde_json::json!({
|
||||
"trace_id": tid,
|
||||
"frame_count": agg.frame_count,
|
||||
"start_frame": agg.start_f,
|
||||
"end_frame": agg.end_f,
|
||||
"key_frame": agg.best_frame,
|
||||
"key_face": agg.best_point_id.as_deref().unwrap_or(""),
|
||||
"key_frame": agg.cq_best_frame,
|
||||
"key_face": agg.cq_best_point_id.as_deref().unwrap_or(""),
|
||||
"avg_bbox": {
|
||||
"x": (agg.sum_x / agg.frame_count as f64).round() as i64,
|
||||
"y": (agg.sum_y / agg.frame_count as f64).round() as i64,
|
||||
"width": (agg.sum_w / agg.frame_count as f64).round() as i64,
|
||||
"height": (agg.sum_h / agg.frame_count as f64).round() as i64,
|
||||
},
|
||||
"best_bbox": agg.cq_best_bbox,
|
||||
"avg_yaw": (avg_yaw * 1000.0).round() / 1000.0,
|
||||
"avg_pitch": (avg_pitch * 1000.0).round() / 1000.0,
|
||||
"avg_roll": (avg_roll * 1000.0).round() / 1000.0,
|
||||
"pose_count": pose_count,
|
||||
"avg_confidence": (avg_confidence * 1000.0).round() / 1000.0,
|
||||
"best_confidence": (agg.best_confidence * 1000.0).round() / 1000.0,
|
||||
"avg_capture_quality": (avg_capture_quality * 1000.0).round() / 1000.0,
|
||||
"best_capture_quality": (agg.cq_best_quality * 1000.0).round() / 1000.0,
|
||||
"status": "pending",
|
||||
});
|
||||
|
||||
@@ -1277,13 +1320,19 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
agg.frame_count,
|
||||
agg.start_f,
|
||||
agg.end_f,
|
||||
agg.cq_best_frame,
|
||||
Some(avg_confidence),
|
||||
Some(avg_capture_quality),
|
||||
agg.best_confidence,
|
||||
agg.cq_best_quality,
|
||||
props["avg_bbox"].clone(),
|
||||
agg.cq_best_bbox.clone(),
|
||||
);
|
||||
|
||||
// Extract key_frame JPEG bytes via ffmpeg pipe
|
||||
// Use select=eq(n\,frame) for VFR compatibility (decoded index, not time-based)
|
||||
let key_frame_jpeg: Option<Vec<u8>> = video_path.as_ref().and_then(|vp| {
|
||||
let select = format!("select=eq(n\\,{})", agg.best_frame);
|
||||
let select = format!("select=eq(n\\,{})", agg.cq_best_frame);
|
||||
let output = std::process::Command::new("ffmpeg")
|
||||
.args(["-y", "-v", "quiet", "-i"])
|
||||
.arg(vp)
|
||||
@@ -1311,13 +1360,13 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
}
|
||||
});
|
||||
|
||||
// Crop key_face JPEG bytes from key_frame using representative bbox (best confidence frame)
|
||||
// Crop key_face JPEG bytes from key_frame using representative bbox (best capture quality frame)
|
||||
let key_face_jpeg: Option<Vec<u8>> = key_frame_jpeg.as_ref().and_then(|kf| {
|
||||
// Find bbox for best_frame from trace frames
|
||||
// Find bbox for cq_best_frame from trace frames
|
||||
let (bf, bx, by, bw, bh) = agg
|
||||
.frames
|
||||
.iter()
|
||||
.find(|(f, _, _, _, _)| *f == agg.best_frame)?;
|
||||
.find(|(f, _, _, _, _)| *f == agg.cq_best_frame)?;
|
||||
let (bx, by, bw, bh) = (*bx, *by, *bw, *bh);
|
||||
|
||||
// Validate bbox: must have positive dimensions
|
||||
@@ -1364,8 +1413,8 @@ 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();
|
||||
let mut key_frame_file = agg.cq_best_frame.to_string();
|
||||
let mut key_face_file = agg.cq_best_point_id.as_deref().unwrap_or("").to_string();
|
||||
|
||||
match trace_profile.save(
|
||||
output_dir,
|
||||
@@ -1416,7 +1465,7 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
|
||||
if need_retry {
|
||||
if let Some(ref vp) = video_path {
|
||||
let select = format!("select=eq(n\\,{})", agg.best_frame);
|
||||
let select = format!("select=eq(n\\,{})", agg.cq_best_frame);
|
||||
// Retry key_frame extraction
|
||||
if !kf_path.exists() {
|
||||
if let Ok(output) = std::process::Command::new("ffmpeg")
|
||||
@@ -1455,7 +1504,7 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
let (_, bx, by, bw, bh) = agg
|
||||
.frames
|
||||
.iter()
|
||||
.find(|(f, _, _, _, _)| *f == agg.best_frame)
|
||||
.find(|(f, _, _, _, _)| *f == agg.cq_best_frame)
|
||||
.cloned()
|
||||
.unwrap_or((0, 0.0, 0.0, 100.0, 100.0));
|
||||
|
||||
@@ -1533,10 +1582,15 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
"key_frame": key_frame_file,
|
||||
"key_face": key_face_file,
|
||||
"avg_bbox": props["avg_bbox"].clone(),
|
||||
"best_bbox": props["best_bbox"].clone(),
|
||||
"avg_yaw": props["avg_yaw"].clone(),
|
||||
"avg_pitch": props["avg_pitch"].clone(),
|
||||
"avg_roll": props["avg_roll"].clone(),
|
||||
"pose_count": pose_count,
|
||||
"avg_confidence": props["avg_confidence"].clone(),
|
||||
"best_confidence": props["best_confidence"].clone(),
|
||||
"avg_capture_quality": props["avg_capture_quality"].clone(),
|
||||
"best_capture_quality": props["best_capture_quality"].clone(),
|
||||
"status": "pending",
|
||||
});
|
||||
|
||||
@@ -3601,6 +3655,7 @@ mod tests {
|
||||
w: 50.0,
|
||||
h: 50.0,
|
||||
confidence: 0.9,
|
||||
capture_quality: 0.0,
|
||||
point_id: None,
|
||||
},
|
||||
FacePoint {
|
||||
@@ -3611,6 +3666,7 @@ mod tests {
|
||||
w: 50.0,
|
||||
h: 50.0,
|
||||
confidence: 0.9,
|
||||
capture_quality: 0.0,
|
||||
point_id: None,
|
||||
},
|
||||
FacePoint {
|
||||
@@ -3621,6 +3677,7 @@ mod tests {
|
||||
w: 50.0,
|
||||
h: 50.0,
|
||||
confidence: 0.9,
|
||||
capture_quality: 0.0,
|
||||
point_id: None,
|
||||
},
|
||||
FacePoint {
|
||||
@@ -3631,6 +3688,7 @@ mod tests {
|
||||
w: 50.0,
|
||||
h: 50.0,
|
||||
confidence: 0.9,
|
||||
capture_quality: 0.0,
|
||||
point_id: None,
|
||||
},
|
||||
];
|
||||
@@ -3661,6 +3719,7 @@ mod tests {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
confidence: 0.9,
|
||||
capture_quality: 0.0,
|
||||
point_id: None,
|
||||
},
|
||||
FacePoint {
|
||||
@@ -3671,6 +3730,7 @@ mod tests {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
confidence: 0.9,
|
||||
capture_quality: 0.0,
|
||||
point_id: None,
|
||||
},
|
||||
];
|
||||
@@ -3692,6 +3752,7 @@ mod tests {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
confidence: 0.9,
|
||||
capture_quality: 0.0,
|
||||
point_id: None,
|
||||
},
|
||||
FacePoint {
|
||||
@@ -3702,6 +3763,7 @@ mod tests {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
confidence: 0.9,
|
||||
capture_quality: 0.0,
|
||||
point_id: None,
|
||||
},
|
||||
];
|
||||
@@ -3722,6 +3784,7 @@ mod tests {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
confidence: 0.9,
|
||||
capture_quality: 0.0,
|
||||
point_id: None,
|
||||
}];
|
||||
let index = build_frame_index(&points);
|
||||
|
||||
Reference in New Issue
Block a user