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,
|
||||
|
||||
Reference in New Issue
Block a user