From 23c6f6374209c099e0a6e309b0e9ef6ee55ee602 Mon Sep 17 00:00:00 2001 From: Accusys Date: Wed, 5 Aug 2026 21:40:07 +0800 Subject: [PATCH] feat: add face search API at trace level for People page FS filtering - GET /api/v1/file/:file_uuid/faces/search - q parameter: trace_id substring, frame fall-through, range overlap, name substring - binding filter: assigned/unassigned - min_confidence filter - Pagination with page/page_size - Response includes trace_id, file_uuid, file_name, name, start_frame, end_frame, frame_count, thumbnail_url - SQL-based filtering with indexes on name/file_uuid for performance --- src/api/identity_api.rs | 230 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 230 insertions(+) diff --git a/src/api/identity_api.rs b/src/api/identity_api.rs index f9b7f123..1d737e31 100644 --- a/src/api/identity_api.rs +++ b/src/api/identity_api.rs @@ -38,6 +38,10 @@ pub fn identity_routes() -> Router { get(get_identity_faces), ) .route("/api/v1/file/:file_uuid/faces", get(get_file_faces)) + .route( + "/api/v1/file/:file_uuid/faces/search", + get(search_file_faces), + ) .route("/api/v1/resource/register", post(register_resource)) .route("/api/v1/resource/heartbeat", post(heartbeat_resource)) .route("/api/v1/resources", get(list_resources)) @@ -943,6 +947,232 @@ async fn get_file_faces( })) } +// --- Face Search (Trace Level) --- + +#[derive(Debug, Deserialize)] +pub struct FacesSearchQuery { + q: Option, + binding: Option, + min_confidence: Option, + page: Option, + page_size: Option, +} + +#[derive(Debug, Serialize)] +pub struct FaceSearchItem { + pub trace_id: i32, + pub file_uuid: String, + pub file_name: String, + pub name: String, + pub start_frame: i64, + pub end_frame: i64, + pub frame_count: i32, + pub avg_confidence: f64, + pub thumbnail_url: String, +} + +#[derive(Debug, Serialize)] +pub struct FacesSearchResponse { + pub success: bool, + pub total: i64, + pub page: usize, + pub page_size: usize, + pub data: Vec, +} + +async fn search_file_faces( + State(state): State, + Path(file_uuid): Path, + Query(params): Query, +) -> Result, (StatusCode, String)> { + let page = params.page.unwrap_or(1).max(1); + let page_size = params.page_size.unwrap_or(50).min(200).max(1); + let offset = ((page - 1) as i64) * (page_size as i64); + + let tp_table = crate::core::db::schema::table_name("trace_profiles"); + let video_table = crate::core::db::schema::table_name("videos"); + + // Build WHERE clause based on q parameter + let mut where_clauses = vec!["tp.file_uuid = $1".to_string()]; + let mut param_idx = 2i32; + + if let Some(ref q) = params.q { + let trimmed = q.trim(); + if !trimmed.is_empty() { + // Parse q to determine search type + if let Some((a_str, b_str)) = trimmed.split_once('-') { + // a-b range: check if both parts are numbers + if let (Ok(a), Ok(b)) = (a_str.parse::(), b_str.parse::()) { + // Range overlap: start_frame <= b AND end_frame >= a + where_clauses.push(format!( + "(tp.start_frame <= ${} AND tp.end_frame >= ${})", + param_idx, + param_idx + 1 + )); + param_idx += 2; + } else { + // Not valid range, treat as name substring + where_clauses.push(format!( + "COALESCE(tp.name, 'Unassigned') ILIKE ${}", + param_idx + )); + param_idx += 1; + } + } else if let Ok(num) = trimmed.parse::() { + // Pure number: could be trace_id substring OR frame fall-through + // Use OR to match both + where_clauses.push(format!( + "(tp.trace_id::text LIKE ${} OR (${} BETWEEN tp.start_frame AND tp.end_frame))", + param_idx, + param_idx + 1 + )); + param_idx += 2; + } else { + // Text: name substring + where_clauses.push(format!( + "COALESCE(tp.name, 'Unassigned') ILIKE ${}", + param_idx + )); + param_idx += 1; + } + } + } + + // binding filter + if let Some(ref binding) = params.binding { + match binding.as_str() { + "assigned" => { + where_clauses.push("tp.name IS NOT NULL".to_string()); + } + "unassigned" => { + where_clauses.push("tp.name IS NULL".to_string()); + } + _ => {} + } + } + + // min_confidence filter + if let Some(mc) = params.min_confidence { + where_clauses.push(format!("tp.avg_confidence >= ${}", param_idx)); + param_idx += 1; + } + + let where_sql = where_clauses.join(" AND "); + + // Count total + let count_sql = format!( + "SELECT COUNT(*) FROM {} tp WHERE {}", + tp_table, where_sql + ); + + let mut count_query = sqlx::query_scalar::<_, i64>(&count_sql).bind(&file_uuid); + if let Some(ref q) = params.q { + let trimmed = q.trim(); + if !trimmed.is_empty() { + if let Some((a_str, b_str)) = trimmed.split_once('-') { + if let (Ok(a), Ok(b)) = (a_str.parse::(), b_str.parse::()) { + count_query = count_query.bind(a).bind(b); + } else { + count_query = count_query.bind(format!("%{}%", trimmed)); + } + } else if let Ok(num) = trimmed.parse::() { + count_query = count_query.bind(format!("%{}%", num)).bind(num); + } else { + count_query = count_query.bind(format!("%{}%", trimmed)); + } + } + } + if let Some(ref binding) = params.binding { + if binding == "assigned" || binding == "unassigned" { + // No additional bind needed + } + } + if let Some(mc) = params.min_confidence { + count_query = count_query.bind(mc); + } + + let total = count_query + .fetch_optional(state.db.pool()) + .await + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))? + .unwrap_or(0); + + // Fetch paginated data + let data_sql = format!( + "SELECT tp.trace_id, tp.file_uuid, COALESCE(tp.name, 'Unassigned') as name, \ + tp.start_frame, tp.end_frame, tp.frame_count, tp.avg_confidence, \ + v.file_name \ + FROM {} tp \ + LEFT JOIN {} v ON tp.file_uuid = v.file_uuid \ + WHERE {} \ + ORDER BY tp.start_frame ASC \ + LIMIT ${} OFFSET ${}", + tp_table, video_table, where_sql, param_idx, param_idx + 1 + ); + + let mut data_query = sqlx::query(&data_sql).bind(&file_uuid); + if let Some(ref q) = params.q { + let trimmed = q.trim(); + if !trimmed.is_empty() { + if let Some((a_str, b_str)) = trimmed.split_once('-') { + if let (Ok(a), Ok(b)) = (a_str.parse::(), b_str.parse::()) { + data_query = data_query.bind(a).bind(b); + } else { + data_query = data_query.bind(format!("%{}%", trimmed)); + } + } else if let Ok(num) = trimmed.parse::() { + data_query = data_query.bind(format!("%{}%", num)).bind(num); + } else { + data_query = data_query.bind(format!("%{}%", trimmed)); + } + } + } + if let Some(mc) = params.min_confidence { + data_query = data_query.bind(mc); + } + data_query = data_query.bind(page_size as i64).bind(offset); + + let rows = data_query + .fetch_all(state.db.pool()) + .await + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; + + let data: Vec = rows + .into_iter() + .map(|r| { + use sqlx::Row; + let trace_id: i32 = r.get("trace_id"); + let file_uuid: String = r.get("file_uuid"); + let file_name: String = r.get("file_name"); + let name: String = r.get("name"); + let start_frame: i64 = r.get("start_frame"); + let end_frame: i64 = r.get("end_frame"); + let frame_count: i32 = r.get("frame_count"); + let avg_confidence: f64 = r.try_get("avg_confidence").ok().unwrap_or(0.0); + + FaceSearchItem { + trace_id, + file_uuid: file_uuid.clone(), + file_name, + name, + start_frame, + end_frame, + frame_count, + avg_confidence: (avg_confidence * 1000.0).round() / 1000.0, + thumbnail_url: format!("/api/v1/trace-thumb/{}/{}", file_uuid, trace_id), + } + }) + .collect(); + + Ok(Json(FacesSearchResponse { + success: true, + total, + page, + page_size, + data, + })) +} + // --- List Face Candidates --- #[derive(Debug, Serialize)]