feat: add GET /api/v1/cluster-results endpoint for Studio face groups

- src/api/profile.rs: new get_cluster_results_handler
  - Query param file_hash (Studio passes ?file_hash=)
  - Builds face_groups from tkg_nodes + trace_profiles (same grouping as
    face-groups handler) with group_id/cluster_id/name/trace_ids/
    trace_count/representative_trace
  - Scrolls _faces for the file, groups faces by frame into frames[]
    - face_id = hex point id (matches identities.rs convention)
    - timestamp = frame / fps (from videos table)
    - cluster_id = group of the face's trace_id; unassigned faces skipped
  - Response: { success, file_uuid, face_groups, frames } matching Studio
    PeopleView.vue expected format
This commit is contained in:
Accusys
2026-07-31 11:58:36 +08:00
parent aab727b297
commit d36132d93a
+174
View File
@@ -1115,6 +1115,176 @@ pub async fn get_face_groups_handler(
}))
}
// ─── Cluster Results (Studio-compatible) ───
#[derive(Deserialize)]
pub struct ClusterResultsQuery {
pub file_hash: String,
}
#[derive(Debug, Serialize)]
pub struct ClusterResultsFace {
pub face_id: String,
pub confidence: f64,
pub cluster_id: Option<i32>,
}
#[derive(Debug, Serialize)]
pub struct ClusterResultsFrame {
pub frame: i64,
pub timestamp: f64,
pub faces: Vec<ClusterResultsFace>,
}
#[derive(Debug, Serialize)]
pub struct ClusterResultsGroup {
pub group_id: i32,
pub cluster_id: i32,
pub name: String,
pub trace_ids: Vec<i32>,
pub trace_count: i32,
pub representative_trace: i32,
}
#[derive(Debug, Serialize)]
pub struct ClusterResultsResponse {
pub success: bool,
pub file_uuid: String,
pub face_groups: Vec<ClusterResultsGroup>,
pub frames: Vec<ClusterResultsFrame>,
}
pub async fn get_cluster_results_handler(
State(state): State<AppState>,
Extension(_auth): Extension<UserAuth>,
Query(params): Query<ClusterResultsQuery>,
) -> Result<Json<ClusterResultsResponse>, StatusCode> {
let file_uuid = params.file_hash;
let tkg_table = schema::table_name("tkg_nodes");
let tp_table = schema::table_name("trace_profiles");
// 1. Build face groups (same grouping logic as face-groups handler)
let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(&format!(
"SELECT COALESCE(tp.name, tn.label) as name, \
COALESCE(tp.properties, tn.properties) as properties \
FROM {} tn \
LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
AND tp.trace_id = (tn.properties->>'trace_id')::int \
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
ORDER BY (COALESCE(tp.properties, tn.properties)->>'trace_id')::int",
tkg_table, tp_table
))
.bind(&file_uuid)
.fetch_all(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[ClusterResults] DB error: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let mut groups: HashMap<String, Vec<i32>> = HashMap::new();
for (name, properties) in rows {
let trace_id = properties
.get("trace_id")
.and_then(|v| v.as_i64())
.map(|v| v as i32)
.unwrap_or(0);
if !(name.starts_with("Face Trace ") || name.starts_with("Trace ")) {
groups.entry(name).or_default().push(trace_id);
}
}
// trace_id -> cluster_id mapping for frame faces
let mut trace_to_cluster: HashMap<i32, i32> = HashMap::new();
let face_groups: Vec<ClusterResultsGroup> = groups
.into_iter()
.enumerate()
.map(|(idx, (name, trace_ids))| {
let group_id = (idx + 1) as i32;
for tid in &trace_ids {
trace_to_cluster.insert(*tid, group_id);
}
ClusterResultsGroup {
group_id,
cluster_id: group_id,
name,
trace_count: trace_ids.len() as i32,
representative_trace: trace_ids.first().copied().unwrap_or(0),
trace_ids,
}
})
.collect();
// 2. Get fps for frame -> timestamp conversion
let videos_table = schema::table_name("videos");
let fps: f64 = sqlx::query_scalar(&format!(
"SELECT fps FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[ClusterResults] fps query failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?
.unwrap_or(0.0);
// 3. Scroll _faces for this file and group by frame
let face_filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": &file_uuid}}
]
});
let points = state
.qdrant
.scroll_all_points("_faces", face_filter, 1000)
.await
.map_err(|e| {
tracing::error!("[ClusterResults] Qdrant scroll failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let mut frames_map: HashMap<i64, Vec<ClusterResultsFace>> = HashMap::new();
for p in &points {
let payload = &p["payload"];
let frame = payload["frame"].as_i64().unwrap_or(0);
let trace_id = payload["trace_id"].as_i64().map(|t| t as i32).unwrap_or(0);
let point_id = p["id"].as_u64().unwrap_or(0);
let confidence = payload["confidence"].as_f64().unwrap_or(0.0);
// Only include faces that belong to a group (Studio skips unassigned)
let cluster_id = trace_to_cluster.get(&trace_id).copied();
if cluster_id.is_none() {
continue;
}
frames_map.entry(frame).or_default().push(ClusterResultsFace {
face_id: format!("{:x}", point_id),
confidence,
cluster_id,
});
}
let mut frames: Vec<ClusterResultsFrame> = frames_map
.into_iter()
.map(|(frame, faces)| ClusterResultsFrame {
frame,
timestamp: if fps > 0.0 { frame as f64 / fps } else { 0.0 },
faces,
})
.collect();
frames.sort_by_key(|f| f.frame);
Ok(Json(ClusterResultsResponse {
success: true,
file_uuid,
face_groups,
frames,
}))
}
// ─── Similar Group Suggestion ───
#[derive(Deserialize)]
@@ -1329,6 +1499,10 @@ pub fn profile_routes() -> axum::Router<AppState> {
"/api/v1/file/:file_uuid/face-groups/similar",
get(get_similar_group_handler),
)
.route(
"/api/v1/cluster-results",
get(get_cluster_results_handler),
)
.route(
"/api/v1/file/:file_uuid/groups/merge",
post(merge_groups_handler),