feat: implement face filter API for GUI filtering mechanism
- Database schema: face_filter_features and filter_rules tables
- Core engine: FilterEngine with 4 filter rules (landmark, mediapipe, embedding, temporal)
- API endpoints:
- GET /faces - Get faces with filtering
- GET /face/{id}/filter-report - Get filter report for single face
- POST /faces/filter - Apply filter rules
- GET /filter-stats - Get filter statistics
- GET/POST /filter-rules - Manage filter rules
- API documentation for Studio team with examples
- Based on FaceNet analysis results from WD and KOBA videos
This commit is contained in:
@@ -0,0 +1,445 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Filter feature data for a single face
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FaceFilterFeatures {
|
||||
pub face_id: String,
|
||||
pub file_uuid: String,
|
||||
pub frame: 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>,
|
||||
pub primary_source: Option<String>,
|
||||
}
|
||||
|
||||
/// Filter rule configuration
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FilterRuleConfig {
|
||||
pub version: String,
|
||||
pub rules: HashMap<String, RuleConfig>,
|
||||
pub overall_thresholds: OverallThresholds,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RuleConfig {
|
||||
pub enabled: bool,
|
||||
pub weight: f64,
|
||||
pub thresholds: serde_json::Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OverallThresholds {
|
||||
pub auto_accept: f64,
|
||||
pub auto_reject: f64,
|
||||
pub review_range: (f64, f64),
|
||||
}
|
||||
|
||||
/// Filter result for a single face
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FaceFilterResult {
|
||||
pub face_id: String,
|
||||
pub frame: i32,
|
||||
pub overall_confidence: f64,
|
||||
pub recommendation: FilterRecommendation,
|
||||
pub rule_results: HashMap<String, RuleResult>,
|
||||
pub reasons: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FilterRecommendation {
|
||||
Accept,
|
||||
Review,
|
||||
Reject,
|
||||
}
|
||||
|
||||
/// Result of applying a single rule
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RuleResult {
|
||||
pub enabled: bool,
|
||||
pub score: f64,
|
||||
pub passed: bool,
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// Filter engine for applying rules to face data
|
||||
pub struct FilterEngine {
|
||||
config: FilterRuleConfig,
|
||||
}
|
||||
|
||||
impl FilterEngine {
|
||||
/// Create a new filter engine with the given configuration
|
||||
pub fn new(config: FilterRuleConfig) -> Self {
|
||||
Self { config }
|
||||
}
|
||||
|
||||
/// Apply all filter rules to a single face
|
||||
pub fn filter_face(&self, features: &FaceFilterFeatures) -> Result<FaceFilterResult> {
|
||||
let mut rule_results = HashMap::new();
|
||||
let mut total_score: f64 = 0.0;
|
||||
let mut total_weight: f64 = 0.0;
|
||||
let mut reasons = Vec::new();
|
||||
|
||||
// Apply landmark analysis rule
|
||||
if let Some(rule_config) = self.config.rules.get("landmark_analysis") {
|
||||
let result = self.apply_landmark_analysis(features, rule_config);
|
||||
total_score += result.score * rule_config.weight;
|
||||
total_weight += rule_config.weight;
|
||||
if let Some(reason) = &result.reason {
|
||||
reasons.push(reason.clone());
|
||||
}
|
||||
rule_results.insert("landmark_analysis".to_string(), result);
|
||||
}
|
||||
|
||||
// Apply MediaPipe verification rule
|
||||
if let Some(rule_config) = self.config.rules.get("mediapipe_verification") {
|
||||
let result = self.apply_mediapipe_verification(features, rule_config);
|
||||
total_score += result.score * rule_config.weight;
|
||||
total_weight += rule_config.weight;
|
||||
if let Some(reason) = &result.reason {
|
||||
reasons.push(reason.clone());
|
||||
}
|
||||
rule_results.insert("mediapipe_verification".to_string(), result);
|
||||
}
|
||||
|
||||
// Apply embedding similarity rule
|
||||
if let Some(rule_config) = self.config.rules.get("embedding_similarity") {
|
||||
let result = self.apply_embedding_similarity(features, rule_config);
|
||||
total_score += result.score * rule_config.weight;
|
||||
total_weight += rule_config.weight;
|
||||
if let Some(reason) = &result.reason {
|
||||
reasons.push(reason.clone());
|
||||
}
|
||||
rule_results.insert("embedding_similarity".to_string(), result);
|
||||
}
|
||||
|
||||
// Apply temporal consistency rule
|
||||
if let Some(rule_config) = self.config.rules.get("temporal_consistency") {
|
||||
let result = self.apply_temporal_consistency(features, rule_config);
|
||||
total_score += result.score * rule_config.weight;
|
||||
total_weight += rule_config.weight;
|
||||
if let Some(reason) = &result.reason {
|
||||
reasons.push(reason.clone());
|
||||
}
|
||||
rule_results.insert("temporal_consistency".to_string(), result);
|
||||
}
|
||||
|
||||
// Calculate overall confidence
|
||||
let overall_confidence = if total_weight > 0.0 {
|
||||
total_score / total_weight
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Determine recommendation
|
||||
let recommendation = if overall_confidence >= self.config.overall_thresholds.auto_accept {
|
||||
FilterRecommendation::Accept
|
||||
} else if overall_confidence <= self.config.overall_thresholds.auto_reject {
|
||||
FilterRecommendation::Reject
|
||||
} else {
|
||||
FilterRecommendation::Review
|
||||
};
|
||||
|
||||
Ok(FaceFilterResult {
|
||||
face_id: features.face_id.clone(),
|
||||
frame: features.frame,
|
||||
overall_confidence,
|
||||
recommendation,
|
||||
rule_results,
|
||||
reasons,
|
||||
})
|
||||
}
|
||||
|
||||
/// Apply landmark analysis rule
|
||||
fn apply_landmark_analysis(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||
if !config.enabled {
|
||||
return RuleResult {
|
||||
enabled: false,
|
||||
score: 1.0,
|
||||
passed: true,
|
||||
reason: None,
|
||||
};
|
||||
}
|
||||
|
||||
let mut score: f64 = 1.0;
|
||||
let mut reasons = Vec::new();
|
||||
|
||||
// Check eye ratio
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
|
||||
let score = score.max(0.0_f64);
|
||||
let passed = score >= 0.5;
|
||||
|
||||
RuleResult {
|
||||
enabled: true,
|
||||
score,
|
||||
passed,
|
||||
reason: if reasons.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(reasons.join(", "))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply MediaPipe verification rule
|
||||
fn apply_mediapipe_verification(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||
if !config.enabled {
|
||||
return RuleResult {
|
||||
enabled: false,
|
||||
score: 1.0,
|
||||
passed: true,
|
||||
reason: None,
|
||||
};
|
||||
}
|
||||
|
||||
// If MediaPipe didn't detect this face, lower the score
|
||||
if features.mediapipe_detected == Some(false) {
|
||||
return RuleResult {
|
||||
enabled: true,
|
||||
score: 0.3,
|
||||
passed: false,
|
||||
reason: Some("MediaPipe did not detect this face".to_string()),
|
||||
};
|
||||
}
|
||||
|
||||
// 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,
|
||||
score: 0.5,
|
||||
passed: false,
|
||||
reason: Some(format!("MediaPipe IoU too low ({:.3})", iou)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
RuleResult {
|
||||
enabled: true,
|
||||
score: 1.0,
|
||||
passed: true,
|
||||
reason: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply embedding similarity rule
|
||||
fn apply_embedding_similarity(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||
if !config.enabled {
|
||||
return RuleResult {
|
||||
enabled: false,
|
||||
score: 1.0,
|
||||
passed: true,
|
||||
reason: None,
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
score: similarity / min_similarity,
|
||||
passed: false,
|
||||
reason: Some(format!("Low embedding similarity ({:.3})", similarity)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
RuleResult {
|
||||
enabled: true,
|
||||
score: 1.0,
|
||||
passed: true,
|
||||
reason: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply temporal consistency rule
|
||||
fn apply_temporal_consistency(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||
if !config.enabled {
|
||||
return RuleResult {
|
||||
enabled: false,
|
||||
score: 1.0,
|
||||
passed: true,
|
||||
reason: None,
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(consecutive) = features.consecutive_frames {
|
||||
let min_consecutive = config.thresholds["min_consecutive_frames"].as_i64().unwrap_or(3) as i32;
|
||||
|
||||
if consecutive < min_consecutive {
|
||||
return RuleResult {
|
||||
enabled: true,
|
||||
score: (consecutive as f64) / (min_consecutive as f64),
|
||||
passed: false,
|
||||
reason: Some(format!("Single frame detection ({})", consecutive)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
RuleResult {
|
||||
enabled: true,
|
||||
score: 1.0,
|
||||
passed: true,
|
||||
reason: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}),
|
||||
});
|
||||
|
||||
FilterRuleConfig {
|
||||
version: "1.0".to_string(),
|
||||
rules,
|
||||
overall_thresholds: OverallThresholds {
|
||||
auto_accept: 0.7,
|
||||
auto_reject: 0.3,
|
||||
review_range: (0.3, 0.7),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
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,
|
||||
eye_ratio: Some(0.37),
|
||||
nose_ratio: Some(0.15),
|
||||
pose_score: Some(0.1),
|
||||
mediapipe_detected: Some(true),
|
||||
mediapipe_iou: Some(0.8),
|
||||
embedding_similarity: Some(0.85),
|
||||
consecutive_frames: Some(15),
|
||||
total_frames_detected: Some(15),
|
||||
apple_vision_confidence: Some(0.85),
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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
|
||||
mediapipe_iou: Some(0.0),
|
||||
embedding_similarity: Some(0.15), // 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);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ pub mod chunk;
|
||||
pub mod config;
|
||||
pub mod db;
|
||||
pub mod embedding;
|
||||
pub mod face_filter_engine;
|
||||
pub mod file_lifecycle;
|
||||
pub mod file_profile;
|
||||
pub mod frame_cache;
|
||||
|
||||
Reference in New Issue
Block a user