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,541 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
response::Json,
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::Row;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::types::AppState;
|
||||
use crate::core::db::schema;
|
||||
use crate::core::face_filter_engine::{
|
||||
default_filter_config, FaceFilterFeatures, FaceFilterResult, FilterEngine, FilterRecommendation,
|
||||
FilterRuleConfig, RuleResult,
|
||||
};
|
||||
|
||||
/// Request to filter faces
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct FilterFacesRequest {
|
||||
pub rules: Option<FilterRuleConfig>,
|
||||
}
|
||||
|
||||
/// Response for filter faces
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct FilterFacesResponse {
|
||||
pub total_faces: i32,
|
||||
pub passed: i32,
|
||||
pub filtered: i32,
|
||||
pub filtered_faces: Vec<FilteredFaceInfo>,
|
||||
pub filter_stats: serde_json::Value,
|
||||
}
|
||||
|
||||
/// Info about a filtered face
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct FilteredFaceInfo {
|
||||
pub face_id: String,
|
||||
pub frame: i32,
|
||||
pub reasons: Vec<String>,
|
||||
}
|
||||
|
||||
/// Request to get faces with filtering
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GetFacesRequest {
|
||||
pub source: Option<String>, // "all" | "apple_vision" | "mediapipe"
|
||||
pub page: Option<usize>,
|
||||
pub page_size: Option<usize>,
|
||||
}
|
||||
|
||||
/// Response for get faces
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct GetFacesResponse {
|
||||
pub faces: Vec<FaceInfo>,
|
||||
pub pagination: PaginationInfo,
|
||||
pub source_summary: SourceSummary,
|
||||
}
|
||||
|
||||
/// Face info
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct FaceInfo {
|
||||
pub face_id: String,
|
||||
pub frame: i32,
|
||||
pub primary_source: String,
|
||||
pub primary_confidence: f64,
|
||||
pub detection_sources: Vec<SourceInfo>,
|
||||
pub filter_features: Option<FaceFilterFeatures>,
|
||||
}
|
||||
|
||||
/// Source info
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SourceInfo {
|
||||
pub source_type: String,
|
||||
pub confidence: f64,
|
||||
}
|
||||
|
||||
/// Pagination info
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct PaginationInfo {
|
||||
pub page: usize,
|
||||
pub page_size: usize,
|
||||
pub total: i64,
|
||||
pub total_pages: usize,
|
||||
}
|
||||
|
||||
/// Source summary
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SourceSummary {
|
||||
pub apple_vision: i64,
|
||||
pub mediapipe: i64,
|
||||
pub merged_unique: i64,
|
||||
}
|
||||
|
||||
/// Filter stats response
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct FilterStatsResponse {
|
||||
pub total_faces: i64,
|
||||
by_category: serde_json::Value,
|
||||
}
|
||||
|
||||
/// Filter rules request
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct SaveFilterRulesRequest {
|
||||
pub rule_name: String,
|
||||
pub rules: FilterRuleConfig,
|
||||
pub is_active: Option<bool>,
|
||||
}
|
||||
|
||||
/// Filter rules response
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct FilterRulesResponse {
|
||||
pub rules: Vec<FilterRuleInfo>,
|
||||
}
|
||||
|
||||
/// Filter rule info
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct FilterRuleInfo {
|
||||
pub id: i32,
|
||||
pub rule_name: String,
|
||||
pub rules: FilterRuleConfig,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
/// Get all faces with optional filtering
|
||||
pub async fn get_faces(
|
||||
State(state): State<AppState>,
|
||||
Path(file_uuid): Path<String>,
|
||||
req: Option<Json<GetFacesRequest>>,
|
||||
) -> Result<Json<GetFacesResponse>, StatusCode> {
|
||||
let req = req.map(|r| r.0).unwrap_or(GetFacesRequest {
|
||||
source: None,
|
||||
page: Some(1),
|
||||
page_size: Some(50),
|
||||
});
|
||||
|
||||
let page = req.page.unwrap_or(1);
|
||||
let page_size = req.page_size.unwrap_or(50);
|
||||
let offset = (page - 1) * page_size;
|
||||
|
||||
// Get total count
|
||||
let filter_table = schema::table_name("face_filter_features");
|
||||
let count_query = format!(
|
||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1",
|
||||
filter_table
|
||||
);
|
||||
|
||||
let total: i64 = sqlx::query_scalar(&count_query)
|
||||
.bind(&file_uuid)
|
||||
.fetch_one(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
// Get faces with filter features
|
||||
let faces_query = format!(
|
||||
"SELECT face_id, frame, primary_source, apple_vision_confidence, mediapipe_confidence,
|
||||
eye_ratio, nose_ratio, pose_score, mediapipe_detected, mediapipe_iou,
|
||||
embedding_similarity, consecutive_frames, total_frames_detected
|
||||
FROM {}
|
||||
WHERE file_uuid = $1
|
||||
ORDER BY frame ASC
|
||||
LIMIT $2 OFFSET $3",
|
||||
filter_table
|
||||
);
|
||||
|
||||
let rows = sqlx::query(&faces_query)
|
||||
.bind(&file_uuid)
|
||||
.bind(page_size as i64)
|
||||
.bind(offset as i64)
|
||||
.fetch_all(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
// Build response
|
||||
let faces: Vec<FaceInfo> = rows
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let face_id: String = row.get(0);
|
||||
let frame: i32 = row.get(1);
|
||||
let primary_source: Option<String> = row.get(2);
|
||||
let av_conf: Option<f64> = row.get(3);
|
||||
let mp_conf: Option<f64> = row.get(4);
|
||||
|
||||
FaceInfo {
|
||||
face_id: face_id.clone(),
|
||||
frame,
|
||||
primary_source: primary_source.clone().unwrap_or("apple_vision".to_string()),
|
||||
primary_confidence: av_conf.unwrap_or(0.0),
|
||||
detection_sources: vec![
|
||||
SourceInfo {
|
||||
source_type: "apple_vision".to_string(),
|
||||
confidence: av_conf.unwrap_or(0.0),
|
||||
},
|
||||
SourceInfo {
|
||||
source_type: "mediapipe".to_string(),
|
||||
confidence: mp_conf.unwrap_or(0.0),
|
||||
},
|
||||
],
|
||||
filter_features: Some(FaceFilterFeatures {
|
||||
face_id,
|
||||
file_uuid: file_uuid.clone(),
|
||||
frame,
|
||||
eye_ratio: row.get(5),
|
||||
nose_ratio: row.get(6),
|
||||
pose_score: row.get(7),
|
||||
mediapipe_detected: row.get(8),
|
||||
mediapipe_iou: row.get(9),
|
||||
embedding_similarity: row.get(10),
|
||||
consecutive_frames: row.get(11),
|
||||
total_frames_detected: row.get(12),
|
||||
apple_vision_confidence: av_conf,
|
||||
mediapipe_confidence: mp_conf,
|
||||
primary_source,
|
||||
}),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Get source summary
|
||||
let summary_query = format!(
|
||||
"SELECT
|
||||
COUNT(*) FILTER (WHERE primary_source = 'apple_vision') as apple_vision,
|
||||
COUNT(*) FILTER (WHERE primary_source = 'mediapipe') as mediapipe,
|
||||
COUNT(*) as merged_unique
|
||||
FROM {}
|
||||
WHERE file_uuid = $1",
|
||||
filter_table
|
||||
);
|
||||
|
||||
let summary_row = sqlx::query(&summary_query)
|
||||
.bind(&file_uuid)
|
||||
.fetch_one(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let apple_vision: i64 = summary_row.get(0);
|
||||
let mediapipe: i64 = summary_row.get(1);
|
||||
let merged_unique: i64 = summary_row.get(2);
|
||||
|
||||
let total_pages = ((total as f64) / (page_size as f64)).ceil() as usize;
|
||||
|
||||
Ok(Json(GetFacesResponse {
|
||||
faces,
|
||||
pagination: PaginationInfo {
|
||||
page,
|
||||
page_size,
|
||||
total,
|
||||
total_pages,
|
||||
},
|
||||
source_summary: SourceSummary {
|
||||
apple_vision,
|
||||
mediapipe,
|
||||
merged_unique,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
/// Get filter report for a single face
|
||||
pub async fn get_face_filter_report(
|
||||
State(state): State<AppState>,
|
||||
Path((file_uuid, face_id)): Path<(String, String)>,
|
||||
) -> Result<Json<FaceFilterResult>, StatusCode> {
|
||||
let filter_table = schema::table_name("face_filter_features");
|
||||
|
||||
let row = sqlx::query(&format!(
|
||||
"SELECT face_id, frame, eye_ratio, nose_ratio, pose_score,
|
||||
mediapipe_detected, mediapipe_iou, embedding_similarity,
|
||||
consecutive_frames, total_frames_detected,
|
||||
apple_vision_confidence, mediapipe_confidence, primary_source
|
||||
FROM {}
|
||||
WHERE file_uuid = $1 AND face_id = $2",
|
||||
filter_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.bind(&face_id)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
match row {
|
||||
Some(row) => {
|
||||
let features = FaceFilterFeatures {
|
||||
face_id: row.get(0),
|
||||
file_uuid: file_uuid.clone(),
|
||||
frame: row.get(1),
|
||||
eye_ratio: row.get(2),
|
||||
nose_ratio: row.get(3),
|
||||
pose_score: row.get(4),
|
||||
mediapipe_detected: row.get(5),
|
||||
mediapipe_iou: row.get(6),
|
||||
embedding_similarity: row.get(7),
|
||||
consecutive_frames: row.get(8),
|
||||
total_frames_detected: row.get(9),
|
||||
apple_vision_confidence: row.get(10),
|
||||
mediapipe_confidence: row.get(11),
|
||||
primary_source: row.get(12),
|
||||
};
|
||||
|
||||
// Apply default filter rules
|
||||
let config = default_filter_config();
|
||||
let engine = FilterEngine::new(config);
|
||||
|
||||
let result = engine.filter_face(&features).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
Ok(Json(result))
|
||||
}
|
||||
None => Err(StatusCode::NOT_FOUND),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply filter rules to all faces
|
||||
pub async fn filter_faces(
|
||||
State(state): State<AppState>,
|
||||
Path(file_uuid): Path<String>,
|
||||
req: Json<FilterFacesRequest>,
|
||||
) -> Result<Json<FilterFacesResponse>, StatusCode> {
|
||||
let filter_table = schema::table_name("face_filter_features");
|
||||
|
||||
// Get all faces for this file
|
||||
let rows = sqlx::query(&format!(
|
||||
"SELECT face_id, frame, eye_ratio, nose_ratio, pose_score,
|
||||
mediapipe_detected, mediapipe_iou, embedding_similarity,
|
||||
consecutive_frames, total_frames_detected,
|
||||
apple_vision_confidence, mediapipe_confidence, primary_source
|
||||
FROM {}
|
||||
WHERE file_uuid = $1",
|
||||
filter_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_all(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let total_faces = rows.len() as i32;
|
||||
|
||||
// Use provided rules or default
|
||||
let config = req.0.rules.clone().unwrap_or_else(default_filter_config);
|
||||
let engine = FilterEngine::new(config);
|
||||
|
||||
// Apply filters
|
||||
let mut passed = 0;
|
||||
let mut filtered = 0;
|
||||
let mut filtered_faces = Vec::new();
|
||||
let mut filter_stats: HashMap<String, i64> = HashMap::new();
|
||||
|
||||
for row in rows {
|
||||
let features = FaceFilterFeatures {
|
||||
face_id: row.get(0),
|
||||
file_uuid: file_uuid.clone(),
|
||||
frame: row.get(1),
|
||||
eye_ratio: row.get(2),
|
||||
nose_ratio: row.get(3),
|
||||
pose_score: row.get(4),
|
||||
mediapipe_detected: row.get(5),
|
||||
mediapipe_iou: row.get(6),
|
||||
embedding_similarity: row.get(7),
|
||||
consecutive_frames: row.get(8),
|
||||
total_frames_detected: row.get(9),
|
||||
apple_vision_confidence: row.get(10),
|
||||
mediapipe_confidence: row.get(11),
|
||||
primary_source: row.get(12),
|
||||
};
|
||||
|
||||
let result = engine.filter_face(&features).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
if result.recommendation == FilterRecommendation::Accept {
|
||||
passed += 1;
|
||||
} else {
|
||||
filtered += 1;
|
||||
|
||||
// Count reasons before moving
|
||||
for reason in &result.reasons {
|
||||
let key = if reason.contains("eye_ratio") || reason.contains("nose_ratio") || reason.contains("pose_score") {
|
||||
"landmark".to_string()
|
||||
} else if reason.contains("MediaPipe") {
|
||||
"mediapipe".to_string()
|
||||
} else if reason.contains("embedding") {
|
||||
"embedding".to_string()
|
||||
} else if reason.contains("frame") {
|
||||
"temporal".to_string()
|
||||
} else {
|
||||
"other".to_string()
|
||||
};
|
||||
|
||||
*filter_stats.entry(key).or_insert(0) += 1;
|
||||
}
|
||||
|
||||
filtered_faces.push(FilteredFaceInfo {
|
||||
face_id: result.face_id,
|
||||
frame: result.frame,
|
||||
reasons: result.reasons,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let filter_stats_json = serde_json::to_value(&filter_stats).unwrap_or_default();
|
||||
|
||||
Ok(Json(FilterFacesResponse {
|
||||
total_faces,
|
||||
passed,
|
||||
filtered,
|
||||
filtered_faces,
|
||||
filter_stats: filter_stats_json,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Get filter statistics
|
||||
pub async fn get_filter_stats(
|
||||
State(state): State<AppState>,
|
||||
Path(file_uuid): Path<String>,
|
||||
) -> Result<Json<FilterStatsResponse>, StatusCode> {
|
||||
let filter_table = schema::table_name("face_filter_features");
|
||||
|
||||
let row = sqlx::query(&format!(
|
||||
"SELECT
|
||||
COUNT(*) as total,
|
||||
COUNT(*) FILTER (WHERE primary_source = 'apple_vision') as apple_vision,
|
||||
COUNT(*) FILTER (WHERE primary_source = 'mediapipe') as mediapipe,
|
||||
AVG(eye_ratio) as avg_eye_ratio,
|
||||
AVG(nose_ratio) as avg_nose_ratio,
|
||||
AVG(pose_score) as avg_pose_score,
|
||||
COUNT(*) FILTER (WHERE mediapipe_detected = true) as mediapipe_detected_count,
|
||||
AVG(embedding_similarity) as avg_embedding_similarity,
|
||||
AVG(consecutive_frames) as avg_consecutive_frames
|
||||
FROM {}
|
||||
WHERE file_uuid = $1",
|
||||
filter_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_one(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let stats = serde_json::json!({
|
||||
"total_faces": row.get::<i64, _>(0),
|
||||
"by_source": {
|
||||
"apple_vision": row.get::<i64, _>(1),
|
||||
"mediapipe": row.get::<i64, _>(2),
|
||||
},
|
||||
"by_quality": {
|
||||
"avg_eye_ratio": row.get::<Option<f64>, _>(3),
|
||||
"avg_nose_ratio": row.get::<Option<f64>, _>(4),
|
||||
"avg_pose_score": row.get::<Option<f64>, _>(5),
|
||||
"mediapipe_verified": row.get::<i64, _>(6),
|
||||
"avg_embedding_similarity": row.get::<Option<f64>, _>(7),
|
||||
"avg_consecutive_frames": row.get::<Option<f64>, _>(8),
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Json(FilterStatsResponse {
|
||||
total_faces: row.get(0),
|
||||
by_category: stats,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Save filter rules
|
||||
pub async fn save_filter_rules(
|
||||
State(state): State<AppState>,
|
||||
Path(file_uuid): Path<String>,
|
||||
req: Json<SaveFilterRulesRequest>,
|
||||
) -> Result<Json<FilterRuleInfo>, StatusCode> {
|
||||
let rules_table = schema::table_name("filter_rules");
|
||||
|
||||
let is_active = req.is_active.unwrap_or(true);
|
||||
|
||||
let row = sqlx::query(&format!(
|
||||
"INSERT INTO {} (file_uuid, rule_name, rules, is_active)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (file_uuid, rule_name)
|
||||
DO UPDATE SET rules = EXCLUDED.rules, is_active = EXCLUDED.is_active, updated_at = CURRENT_TIMESTAMP
|
||||
RETURNING id, rule_name, rules, is_active, created_at::TEXT, updated_at::TEXT",
|
||||
rules_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.bind(&req.rule_name)
|
||||
.bind(serde_json::to_value(&req.rules).unwrap())
|
||||
.bind(is_active)
|
||||
.fetch_one(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let rules: FilterRuleConfig = serde_json::from_value(row.get(2)).unwrap();
|
||||
|
||||
Ok(Json(FilterRuleInfo {
|
||||
id: row.get(0),
|
||||
rule_name: row.get(1),
|
||||
rules,
|
||||
is_active: row.get(3),
|
||||
created_at: row.get(4),
|
||||
updated_at: row.get(5),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Get filter rules
|
||||
pub async fn get_filter_rules(
|
||||
State(state): State<AppState>,
|
||||
Path(file_uuid): Path<String>,
|
||||
) -> Result<Json<FilterRulesResponse>, StatusCode> {
|
||||
let rules_table = schema::table_name("filter_rules");
|
||||
|
||||
let rows = sqlx::query(&format!(
|
||||
"SELECT id, rule_name, rules, is_active, created_at::TEXT, updated_at::TEXT
|
||||
FROM {}
|
||||
WHERE file_uuid = $1
|
||||
ORDER BY created_at DESC",
|
||||
rules_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_all(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let rules: Vec<FilterRuleInfo> = rows
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let rules: FilterRuleConfig = serde_json::from_value(row.get(2)).unwrap();
|
||||
FilterRuleInfo {
|
||||
id: row.get(0),
|
||||
rule_name: row.get(1),
|
||||
rules,
|
||||
is_active: row.get(3),
|
||||
created_at: row.get(4),
|
||||
updated_at: row.get(5),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Json(FilterRulesResponse { rules }))
|
||||
}
|
||||
|
||||
/// Create router for face filter API
|
||||
pub fn face_filter_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/api/v1/file/{file_uuid}/faces", get(get_faces))
|
||||
.route("/api/v1/file/{file_uuid}/face/{face_id}/filter-report", get(get_face_filter_report))
|
||||
.route("/api/v1/file/{file_uuid}/faces/filter", post(filter_faces))
|
||||
.route("/api/v1/file/{file_uuid}/filter-stats", get(get_filter_stats))
|
||||
.route("/api/v1/file/{file_uuid}/filter-rules", get(get_filter_rules))
|
||||
.route("/api/v1/file/{file_uuid}/filter-rules", post(save_filter_rules))
|
||||
}
|
||||
@@ -4,6 +4,7 @@ pub mod auth;
|
||||
pub mod checkin_api;
|
||||
pub mod cluster_agent;
|
||||
pub mod docs;
|
||||
pub mod face_filter;
|
||||
pub mod files;
|
||||
pub mod health;
|
||||
pub mod identities;
|
||||
|
||||
@@ -15,6 +15,7 @@ use super::auth;
|
||||
use super::checkin_api;
|
||||
use super::cluster_agent;
|
||||
use super::docs;
|
||||
use super::face_filter;
|
||||
use super::files;
|
||||
use super::health;
|
||||
use super::health::{health, health_consistency, health_detailed};
|
||||
@@ -134,6 +135,7 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
.merge(checkin_api::checkin_routes())
|
||||
.merge(cluster_agent::cluster_agent_routes())
|
||||
.merge(profile::profile_routes())
|
||||
.merge(face_filter::face_filter_routes())
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
state.api_state.clone(),
|
||||
unified_auth,
|
||||
|
||||
@@ -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