diff --git a/scripts/backfill_trace_profiles.py b/scripts/backfill_trace_profiles.py index 804330a4..940faec1 100644 --- a/scripts/backfill_trace_profiles.py +++ b/scripts/backfill_trace_profiles.py @@ -77,15 +77,12 @@ def get_video_path(file_uuid): def extract_key_frame(video_path, frame_num, fps, output_path): - """Extract a specific frame from video using ffmpeg.""" - if fps <= 0: - return False - timestamp = frame_num / fps + """Extract a specific frame from video using ffmpeg select filter (precise frame).""" try: result = subprocess.run( - ["ffmpeg", "-y", "-ss", f"{timestamp:.3f}", - "-i", video_path, - "-vframes", "1", "-vf", "scale=640:-1", "-q:v", "5", + ["ffmpeg", "-y", "-i", video_path, + "-vf", f"select=eq(n\\,{frame_num}),scale=640:-1", + "-vframes", "1", "-q:v", "5", output_path], capture_output=True, timeout=30 ) @@ -95,11 +92,14 @@ def extract_key_frame(video_path, frame_num, fps, output_path): return False -def crop_key_face(key_frame_path, bbox, output_path): - """Crop key_face from key_frame using bbox.""" +def crop_key_face(key_frame_path, bbox, output_path, video_width=1920): + """Crop key_face from key_frame using bbox (scaled to key_frame resolution).""" x, y, w, h = bbox["x"], bbox["y"], bbox["width"], bbox["height"] if w <= 0 or h <= 0: return False + # Scale bbox to key_frame resolution (640px wide) + scale = 640.0 / video_width + x, y, w, h = int(x * scale), int(y * scale), int(w * scale), int(h * scale) try: result = subprocess.run( ["ffmpeg", "-y", "-i", key_frame_path, @@ -139,7 +139,7 @@ def build_trace_profiles(file_uuid=None, dry_run=False): {"key": "trace_id", "range": {"gte": 0}}, ] }, - with_payload={"include": ["frame", "trace_id", "bbox", "confidence"]} + with_payload={"include": ["frame", "trace_id", "bbox", "confidence", "capture_quality"]} ) if not points: @@ -155,6 +155,7 @@ def build_trace_profiles(file_uuid=None, dry_run=False): "frame": pl["frame"], "bbox": pl.get("bbox", {}), "confidence": pl.get("confidence", 0.0), + "capture_quality": pl.get("capture_quality", 0), }) print(f" {len(points)} points, {len(traces)} traces") @@ -165,19 +166,22 @@ def build_trace_profiles(file_uuid=None, dry_run=False): print(f" Video not found, skipping key_frame extraction") video_path = None - # Get FPS from DB + # Get FPS and width from DB fps = 30.0 + video_width = 1920 if video_path: psql = "/opt/homebrew/Cellar/libpq/18.4/bin/psql" result = subprocess.run( [psql, "-U", "accusys", "-d", "momentry", "-t", "-A", "-c", - f"SELECT COALESCE(fps, 30.0) FROM videos WHERE file_uuid = '{fid}'"], + f"SELECT COALESCE(fps, 30.0), COALESCE(width, 1920) FROM videos WHERE file_uuid = '{fid}'"], capture_output=True, text=True ) if result.returncode == 0 and result.stdout.strip(): + parts = result.stdout.strip().split('|') try: - fps = float(result.stdout.strip()) - except ValueError: + fps = float(parts[0]) + video_width = int(parts[1]) + except (ValueError, IndexError): pass for tid, faces in sorted(traces.items()): @@ -186,15 +190,30 @@ def build_trace_profiles(file_uuid=None, dry_run=False): frames = [f["frame"] for f in faces] confidences = [f["confidence"] for f in faces] + capture_qualities = [f.get("capture_quality", 0) for f in faces] + bboxes = [f.get("bbox", {}) for f in faces if f.get("bbox")] frame_count = len(faces) start_frame = min(frames) end_frame = max(frames) avg_confidence = sum(confidences) / frame_count if frame_count > 0 else 0.0 - # Representative frame: highest confidence - best = max(faces, key=lambda f: f["confidence"]) + # Representative frame: highest capture_quality + best = max(faces, key=lambda f: f.get("capture_quality", 0)) best_frame = best["frame"] best_bbox = best["bbox"] + best_confidence = best["confidence"] + cq_best_quality = best.get("capture_quality", 0) + + # Average bbox (approximate centroid) + avg_bbox = {} + if bboxes: + avg_bbox = { + "x": int(sum(b.get("x", 0) for b in bboxes) / len(bboxes)), + "y": int(sum(b.get("y", 0) for b in bboxes) / len(bboxes)), + "width": int(sum(b.get("width", 0) for b in bboxes) / len(bboxes)), + "height": int(sum(b.get("height", 0) for b in bboxes) / len(bboxes)), + } + avg_capture_quality = sum(capture_qualities) / frame_count if frame_count > 0 else 0.0 trace_dir = os.path.join(OUTPUT_DIR, fid, f"trace_{tid}") profile_path = os.path.join(trace_dir, "trace_profile.json") @@ -209,7 +228,13 @@ def build_trace_profiles(file_uuid=None, dry_run=False): "frame_count": frame_count, "start_frame": start_frame, "end_frame": end_frame, + "best_frame": best_frame, "avg_confidence": round(avg_confidence, 6), + "best_confidence": round(best_confidence, 6), + "avg_capture_quality": round(avg_capture_quality, 6), + "best_capture_quality": round(cq_best_quality, 6), + "avg_bbox": avg_bbox, + "best_bbox": best_bbox, "key_frame": "key_frame.jpg" if os.path.exists(kf_path) else None, "key_face": "key_face.jpg" if os.path.exists(face_path) else None, "status": "pending", @@ -230,7 +255,7 @@ def build_trace_profiles(file_uuid=None, dry_run=False): # Crop key_face.jpg from key_frame if not exists if not os.path.exists(face_path) and os.path.exists(kf_path) and best_bbox: - crop_key_face(kf_path, best_bbox, face_path) + crop_key_face(kf_path, best_bbox, face_path, video_width) if os.path.exists(face_path): profile["key_face"] = "key_face.jpg" diff --git a/scripts/face_processor.py b/scripts/face_processor.py index d7ba5c95..f71853f4 100644 --- a/scripts/face_processor.py +++ b/scripts/face_processor.py @@ -123,7 +123,16 @@ class FaceProcessorVision: """ print(f"[FACE_V2] Step 1: Vision detection (face only)...") - # Build swift_face if needed + # Build swift_face if missing or stale (source newer than binary) + src = os.path.join(SCRIPT_DIR, "swift_processors", "swift_face.swift") + def _stale(bin_path): + return os.path.exists(bin_path) and os.path.exists(src) and \ + os.path.getmtime(src) > os.path.getmtime(bin_path) + if _stale(SWIFT_BIN): + print(f"[FACE_V2] swift_face release binary stale (source newer), removing to force rebuild...") + os.remove(SWIFT_BIN) + if _stale(SWIFT_BIN_DEBUG): + os.remove(SWIFT_BIN_DEBUG) if not os.path.exists(SWIFT_BIN) and not os.path.exists(SWIFT_BIN_DEBUG): build_dir = os.path.join(SCRIPT_DIR, "swift_processors") print(f"[FACE_V2] Building swift_face in {build_dir}...") @@ -147,7 +156,8 @@ class FaceProcessorVision: cmd.extend(["--uuid", self.uuid]) print(f"[FACE_V2] Running: {' '.join(cmd)}") - # Log face detection settings being passed to swift_face + # Log face detection settings being passed to swift_face. + # Defaults mirror src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT (0.5 / 1). min_conf = os.environ.get("FACE_MIN_CONFIDENCE", "not set (default 0.5)") min_size = os.environ.get("FACE_MIN_SIZE", "not set (default 1)") print(f"[FACE_V2] Settings passed to swift_face: FACE_MIN_CONFIDENCE={min_conf}, FACE_MIN_SIZE={min_size}") @@ -250,6 +260,7 @@ class FaceProcessorVision: "trace_id": face_idx, # Use face_idx as unique identifier within frame "bbox": {"x": x, "y": y, "width": w, "height": h}, "confidence": face.get("confidence", 0.5), + "capture_quality": face.get("captureQuality", 0), "embedding": emb, }) @@ -263,6 +274,7 @@ class FaceProcessorVision: faces.append({ "x": x, "y": y, "width": w, "height": h, "confidence": face.get("confidence", 0.5), + "captureQuality": face.get("captureQuality", 0), "pose_angle": { "angle": pose_angle, "roll": pose_info.get("roll", 0), diff --git a/scripts/store_traced_faces.py b/scripts/store_traced_faces.py index 39029867..b95a9f31 100644 --- a/scripts/store_traced_faces.py +++ b/scripts/store_traced_faces.py @@ -61,6 +61,7 @@ def run_face_tracker( "width": bbox.get("width", f.get("width", 0)), "height": bbox.get("height", f.get("height", 0)), "confidence": f.get("confidence", 0.0), + "captureQuality": f.get("captureQuality", 0.0), } if "landmarks" in f: face["landmarks"] = f["landmarks"] @@ -97,12 +98,40 @@ def run_face_tracker( print(f"[TRACE] Processing {len(face_data.get('frames', {}))} frames") - # Embeddings no longer loaded from DB - use IoU-only tracking + # Load embeddings from Qdrant _faces collection file_uuid = ( face_json_path.split("/")[-1] .replace(".face.json", "") .replace("_traced.json", "") ) + print(f"[TRACE] Loading embeddings from Qdrant for {file_uuid}...") + try: + from qdrant_faces import get_file_faces + qdrant_points = get_file_faces(file_uuid, with_vector=True) + # Build lookup: (frame, x, y) -> embedding + emb_lookup = {} + for p in qdrant_points: + pl = p.get("payload", {}) + frame = pl.get("frame") + bbox = pl.get("bbox", {}) + x, y = bbox.get("x"), bbox.get("y") + vec = p.get("vector") + if frame is not None and vec: + emb_lookup[(frame, x, y)] = vec + print(f"[TRACE] Loaded {len(emb_lookup)} embeddings from Qdrant") + + # Attach embeddings to face data + attached = 0 + for fnum_str, frm_data in face_data.get("frames", {}).items(): + fnum = int(fnum_str) + for face in frm_data.get("faces", []): + key = (fnum, face.get("x"), face.get("y")) + if key in emb_lookup: + face["embedding"] = emb_lookup[key] + attached += 1 + print(f"[TRACE] Attached {attached} embeddings to face data") + except Exception as e: + print(f"[TRACE] Warning: Failed to load embeddings from Qdrant: {e}") # Load cut boundaries from cut.json (same directory as face.json) cut_boundaries = None @@ -118,7 +147,7 @@ def run_face_tracker( print(f"[TRACE] Loaded {len(cut_boundaries)} cut boundaries") face_data = track_faces( - face_data, use_embedding=False, cut_boundaries=cut_boundaries + face_data, use_embedding=True, cut_boundaries=cut_boundaries ) # Merge traces within same cut (same person re-appearing after occlusion/pose change) diff --git a/scripts/swift_processors/swift_face.swift b/scripts/swift_processors/swift_face.swift index 67a66432..fe67ccca 100644 --- a/scripts/swift_processors/swift_face.swift +++ b/scripts/swift_processors/swift_face.swift @@ -39,8 +39,9 @@ struct SwiftFace: ParsableCommand { print("[SwiftFace] Video: \(width)x\(height), \(String(format: "%.1f", fps))fps, \(totalFrames) frames") // Read face detection settings from environment variables (with defaults) - let MIN_CONFIDENCE = Double(ProcessInfo.processInfo.environment["FACE_MIN_CONFIDENCE"] ?? "0.75") ?? 0.75 - let MIN_SIZE = Int(ProcessInfo.processInfo.environment["FACE_MIN_SIZE"] ?? "64") ?? 64 + // Keep in sync with src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT + let MIN_CONFIDENCE = Double(ProcessInfo.processInfo.environment["FACE_MIN_CONFIDENCE"] ?? "0.5") ?? 0.5 + let MIN_SIZE = Int(ProcessInfo.processInfo.environment["FACE_MIN_SIZE"] ?? "1") ?? 1 print("[SwiftFace] Settings: MIN_CONFIDENCE=\(MIN_CONFIDENCE), MIN_SIZE=\(MIN_SIZE)") let generator = AVAssetImageGenerator(asset: asset) @@ -109,15 +110,17 @@ struct SwiftFace: ParsableCommand { let handler = VNImageRequestHandler(cvPixelBuffer: pb, options: [:]) let detectReq = VNDetectFaceRectanglesRequest() let lmReq = VNDetectFaceLandmarksRequest() + let captureQReq = VNDetectFaceCaptureQualityRequest() do { - try handler.perform([detectReq, lmReq]) + try handler.perform([detectReq, lmReq, captureQReq]) } catch { return } let faceObservations = detectReq.results ?? [] let landmarkObservations = lmReq.results ?? [] + let captureQualityObs = captureQReq.results ?? [] guard !faceObservations.isEmpty || !landmarkObservations.isEmpty else { return } @@ -148,11 +151,31 @@ struct SwiftFace: ParsableCommand { let faceX = Int(bb.origin.x * imgW) let faceY = Int((1.0 - bb.origin.y - bb.size.height) * imgH) + // Match capture quality request by bbox overlap (landmarks request + // results don't populate faceCaptureQuality on macOS) + var captureQ = 0.0 + var bestOverlap: CGFloat = 0 + for cqObs in captureQualityObs { + let cb = cqObs.boundingBox + let ix = max(bb.minX, cb.minX) + let iy = max(bb.minY, cb.minY) + let iw = min(bb.maxX, cb.maxX) - ix + let ih = min(bb.maxY, cb.maxY) - iy + if iw <= 0 || ih <= 0 { continue } + let overlap = (iw * ih) / (bb.width * bb.height) + if overlap > bestOverlap { + bestOverlap = overlap + if let cq = cqObs.faceCaptureQuality { + captureQ = Double(cq) + } + } + } + var faceData: [String: Any] = [ "bbox": ["x": max(0, faceX), "y": max(0, faceY), "width": faceW, "height": faceH], "confidence": Double(lmObs.confidence), - "captureQuality": Double(lmObs.value(forKey: "faceCaptureQuality") as? Double ?? 0), + "captureQuality": captureQ, ] // Pose from landmark observation @@ -222,7 +245,7 @@ struct SwiftFace: ParsableCommand { // Quality filtering for unmatched face rects - if faceObs.confidence < MIN_CONFIDENCE { continue } + if Double(faceObs.confidence) < MIN_CONFIDENCE { continue } let faceW = Int(fBB.size.width * imgW) let faceH = Int(fBB.size.height * imgH) @@ -232,11 +255,30 @@ struct SwiftFace: ParsableCommand { let faceX = Int(fBB.origin.x * imgW) let faceY = Int((1.0 - fBB.origin.y - fBB.size.height) * imgH) + // Match capture quality request by bbox overlap + var captureQ = 0.0 + var bestOverlap: CGFloat = 0 + for cqObs in captureQualityObs { + let cb = cqObs.boundingBox + let ix = max(fBB.minX, cb.minX) + let iy = max(fBB.minY, cb.minY) + let iw = min(fBB.maxX, cb.maxX) - ix + let ih = min(fBB.maxY, cb.maxY) - iy + if iw <= 0 || ih <= 0 { continue } + let overlap = (iw * ih) / (fBB.width * fBB.height) + if overlap > bestOverlap { + bestOverlap = overlap + if let cq = cqObs.faceCaptureQuality { + captureQ = Double(cq) + } + } + } + var faceData: [String: Any] = [ "bbox": ["x": max(0, faceX), "y": max(0, faceY), "width": faceW, "height": faceH], "confidence": Double(faceObs.confidence), - "captureQuality": Double(faceObs.faceCaptureQuality ?? 0), + "captureQuality": captureQ, ] if let yaw = faceObs.yaw?.doubleValue, let roll = faceObs.roll?.doubleValue { diff --git a/scripts/utils/face_tracker.py b/scripts/utils/face_tracker.py index add6943f..5f722b35 100755 --- a/scripts/utils/face_tracker.py +++ b/scripts/utils/face_tracker.py @@ -137,11 +137,46 @@ def match_faces( if not previous_faces: return {i: -1 for i in range(len(current_faces))} - # If a scene cut exists between prev and current frame, force all new traces + # If frame gap is too large, force new traces (likely crossed multiple scenes) + if frame_gap is not None and frame_gap > 30: + return {i: -1 for i in range(len(current_faces))} + + # If a scene cut exists between prev and current frame, only continue + # traces for faces matching the previous frame with high IoU (same person + # in the same position across the cut); unmatched faces get new traces. if cut_boundaries and prev_frame is not None and curr_frame is not None: for cf in cut_boundaries: if prev_frame < cf <= curr_frame: - return {i: -1 for i in range(len(current_faces))} + matches = {} + used_prev = set() + for curr_idx, curr_face in enumerate(current_faces): + best_prev_idx = -1 + best_iou = 0.0 + curr_bbox = { + "x": curr_face["x"], + "y": curr_face["y"], + "width": curr_face["width"], + "height": curr_face["height"], + } + for prev_idx, prev_face in enumerate(previous_faces): + if prev_idx in used_prev: + continue + prev_bbox = { + "x": prev_face["x"], + "y": prev_face["y"], + "width": prev_face["width"], + "height": prev_face["height"], + } + iou = calculate_bbox_iou(curr_bbox, prev_bbox) + if iou > best_iou: + best_iou = iou + best_prev_idx = prev_idx + if best_prev_idx >= 0 and best_iou > 0.5: + matches[curr_idx] = best_prev_idx + used_prev.add(best_prev_idx) + else: + matches[curr_idx] = -1 + return matches matches = {} used_prev = set() diff --git a/scripts/utils/qdrant_faces.py b/scripts/utils/qdrant_faces.py index 8864ad20..0d52bf0d 100644 --- a/scripts/utils/qdrant_faces.py +++ b/scripts/utils/qdrant_faces.py @@ -126,6 +126,7 @@ def push_face_embeddings_batch(file_uuid: str, faces: list, publisher=None) -> i "trace_id": face.get("trace_id", 0), "bbox": face["bbox"], "confidence": face.get("confidence", 0.5), + "capture_quality": face.get("capture_quality", 0.0), "identity_id": None, "identity_uuid": None, "stranger_id": None, diff --git a/src/api/files.rs b/src/api/files.rs index 4a7bd5a3..146ee6f6 100644 --- a/src/api/files.rs +++ b/src/api/files.rs @@ -501,11 +501,12 @@ async fn register_single_file( let status = "registered"; let _ = sqlx::query(&format!( - "INSERT INTO {} (file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, status, content_hash, registration_time) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NOW()) ON CONFLICT (file_uuid) DO UPDATE SET file_path = EXCLUDED.file_path, file_name = EXCLUDED.file_name, status = EXCLUDED.status, content_hash = EXCLUDED.content_hash, duration = EXCLUDED.duration, width = EXCLUDED.width, height = EXCLUDED.height, fps = EXCLUDED.fps, probe_json = EXCLUDED.probe_json", + "INSERT INTO {} (file_uuid, file_path, file_name, file_type, duration, width, height, fps, total_frames, probe_json, status, content_hash, registration_time) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, NOW()) ON CONFLICT (file_uuid) DO UPDATE SET file_path = EXCLUDED.file_path, file_name = EXCLUDED.file_name, status = EXCLUDED.status, content_hash = EXCLUDED.content_hash, duration = EXCLUDED.duration, width = EXCLUDED.width, height = EXCLUDED.height, fps = EXCLUDED.fps, total_frames = EXCLUDED.total_frames, probe_json = EXCLUDED.probe_json", videos_table )) .bind(&file_uuid).bind(&canonical_path).bind(&final_name).bind(&final_file_type) .bind(duration).bind(width as i32).bind(height as i32).bind(fps) + .bind(total_frames as i64) .bind(&probe_json).bind(status).bind(&content_hash_val) .execute(db.pool()).await; @@ -808,8 +809,8 @@ async fn register_file( // Convert face_settings to serde_json::Value for create_monitor_job let face_settings_json = req.face_settings.as_ref().map(|fs| { serde_json::json!({ - "min_confidence": fs.min_confidence.unwrap_or(0.75), - "min_size": fs.min_size.unwrap_or(64) + "min_confidence": fs.min_confidence.unwrap_or(config::FACE_MIN_CONFIDENCE_DEFAULT), + "min_size": fs.min_size.unwrap_or(config::FACE_MIN_SIZE_DEFAULT) }) }); tokio::spawn(async move { diff --git a/src/api/identities.rs b/src/api/identities.rs index cf41c7a6..711e4578 100644 --- a/src/api/identities.rs +++ b/src/api/identities.rs @@ -429,6 +429,8 @@ pub struct UnassignedTrace { pub best_face_frame: i64, pub best_face_confidence: f64, pub best_face_bbox: Option, + pub avg_capture_quality: f64, + pub best_capture_quality: f64, } #[derive(Debug, Serialize)] @@ -484,6 +486,8 @@ async fn list_unassigned_traces( best_point_id: i64, best_frame: i64, best_bbox: Option, + sum_capture_quality: f64, + best_capture_quality: f64, } let mut trace_map: BTreeMap<(String, i32), TraceAgg> = BTreeMap::new(); @@ -499,6 +503,7 @@ async fn list_unassigned_traces( } let frame = payload["frame"].as_i64().unwrap_or(0); let confidence = payload["confidence"].as_f64().unwrap_or(0.0); + let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0); let point_id = point["id"].as_i64().unwrap_or(0); let entry = trace_map.entry((file_uuid, trace_id)).or_default(); @@ -509,6 +514,10 @@ async fn list_unassigned_traces( if frame > entry.end_frame { entry.end_frame = frame; } + entry.sum_capture_quality += capture_quality; + if capture_quality > entry.best_capture_quality { + entry.best_capture_quality = capture_quality; + } if confidence > entry.best_confidence { entry.best_confidence = confidence; entry.best_point_id = point_id; @@ -540,6 +549,12 @@ async fn list_unassigned_traces( best_face_frame: agg.best_frame, best_face_confidence: agg.best_confidence, best_face_bbox: agg.best_bbox, + avg_capture_quality: if agg.frame_count > 0 { + agg.sum_capture_quality / agg.frame_count as f64 + } else { + 0.0 + }, + best_capture_quality: agg.best_capture_quality, }) .collect(); diff --git a/src/api/identity_api.rs b/src/api/identity_api.rs index 1d737e31..02501151 100644 --- a/src/api/identity_api.rs +++ b/src/api/identity_api.rs @@ -968,6 +968,8 @@ pub struct FaceSearchItem { pub end_frame: i64, pub frame_count: i32, pub avg_confidence: f64, + pub avg_capture_quality: f64, + pub best_capture_quality: f64, pub thumbnail_url: String, } @@ -1101,6 +1103,7 @@ async fn search_file_faces( 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, \ + tp.avg_capture_quality, tp.best_capture_quality, \ v.file_name \ FROM {} tp \ LEFT JOIN {} v ON tp.file_uuid = v.file_uuid \ @@ -1149,6 +1152,8 @@ async fn search_file_faces( 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); + let avg_capture_quality: f64 = r.try_get("avg_capture_quality").ok().unwrap_or(0.0); + let best_capture_quality: f64 = r.try_get("best_capture_quality").ok().unwrap_or(0.0); FaceSearchItem { trace_id, @@ -1159,6 +1164,8 @@ async fn search_file_faces( end_frame, frame_count, avg_confidence: (avg_confidence * 1000.0).round() / 1000.0, + avg_capture_quality: (avg_capture_quality * 1000.0).round() / 1000.0, + best_capture_quality: (best_capture_quality * 1000.0).round() / 1000.0, thumbnail_url: format!("/api/v1/trace-thumb/{}/{}", file_uuid, trace_id), } }) diff --git a/src/api/identity_binding.rs b/src/api/identity_binding.rs index 09b5f9a2..cf76018c 100644 --- a/src/api/identity_binding.rs +++ b/src/api/identity_binding.rs @@ -819,6 +819,8 @@ pub struct IdentityTraceInfo { pub first_sec: f64, pub last_sec: f64, pub avg_confidence: f64, + pub avg_capture_quality: f64, + pub best_capture_quality: f64, } #[derive(Debug, Serialize)] @@ -1088,6 +1090,15 @@ pub async fn get_identity_traces( .filter_map(|p| p["payload"]["confidence"].as_f64()) .sum::() / frame_count as f64; + let avg_capture_quality = points + .iter() + .filter_map(|p| p["payload"]["capture_quality"].as_f64()) + .sum::() + / frame_count as f64; + let best_capture_quality = points + .iter() + .filter_map(|p| p["payload"]["capture_quality"].as_f64()) + .fold(0.0_f64, f64::max); let fps = fps_cache.get(file_uuid).copied().unwrap_or(30.0); traces.push(IdentityTraceInfo { @@ -1107,6 +1118,8 @@ pub async fn get_identity_traces( 0.0 }, avg_confidence: (avg_confidence * 10000.0).round() / 10000.0, + avg_capture_quality: (avg_capture_quality * 10000.0).round() / 10000.0, + best_capture_quality: (best_capture_quality * 10000.0).round() / 10000.0, }); } traces.sort_by(|a, b| a.trace_id.cmp(&b.trace_id)); diff --git a/src/api/media_api.rs b/src/api/media_api.rs index a4665838..13a5a221 100644 --- a/src/api/media_api.rs +++ b/src/api/media_api.rs @@ -1728,6 +1728,142 @@ async fn get_appearance_handler( })) } +// ── Face Landmarks Endpoint ── + +#[derive(Debug, serde::Deserialize)] +struct FaceLandmarksQuery { + frame: i64, + bbox_x: Option, + bbox_y: Option, + bbox_w: Option, + bbox_h: Option, +} + +#[derive(Debug, serde::Serialize)] +struct FaceBBox { + x: i64, + y: i64, + width: i64, + height: i64, + confidence: f64, +} + +#[derive(Debug, serde::Serialize)] +struct FaceLandmarksResponse { + frame: i64, + x: i64, + y: i64, + width: i64, + height: i64, + confidence: f64, + pose_angle: Option, + landmarks: serde_json::Value, + lips: serde_json::Value, + faces: Vec, +} + +async fn get_face_landmarks_handler( + State(_state): State, + Path(file_uuid): Path, + Query(params): Query, +) -> Result, StatusCode> { + use crate::core::config::OUTPUT_DIR; + + let output_dir = OUTPUT_DIR.as_str(); + let face_path = std::path::Path::new(output_dir).join(format!("{}.face.json", file_uuid)); + + if !face_path.exists() { + tracing::error!("[get_face_landmarks] File not found: {}", face_path.display()); + return Err(StatusCode::NOT_FOUND); + } + + let content = std::fs::read_to_string(&face_path).map_err(|e| { + tracing::error!("[get_face_landmarks] Failed to read face.json: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + let data: serde_json::Value = serde_json::from_str(&content).map_err(|e| { + tracing::error!("[get_face_landmarks] Failed to parse face.json: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + let frames = data + .get("frames") + .and_then(|v| v.as_array()) + .ok_or(StatusCode::NOT_FOUND)?; + + let frame_data = frames + .iter() + .find(|f| f.get("frame").and_then(|v| v.as_i64()) == Some(params.frame)) + .ok_or(StatusCode::NOT_FOUND)?; + + let faces = frame_data + .get("faces") + .and_then(|v| v.as_array()) + .ok_or(StatusCode::NOT_FOUND)?; + + if faces.is_empty() { + return Err(StatusCode::NOT_FOUND); + } + + // Select the face closest to the provided bbox center (if given), otherwise the first face. + let selected = match (params.bbox_x, params.bbox_y, params.bbox_w, params.bbox_h) { + (Some(bx), Some(by), Some(bw), Some(bh)) => { + const MAX_CENTER_DIST: f64 = 100.0; + let tcx = bx + bw / 2.0; + let tcy = by + bh / 2.0; + let mut best_dist = f64::MAX; + let mut best = None; + for face in faces { + let x = face.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0); + let y = face.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0); + let w = face.get("width").and_then(|v| v.as_f64()).unwrap_or(0.0); + let h = face.get("height").and_then(|v| v.as_f64()).unwrap_or(0.0); + let cx = x + w / 2.0; + let cy = y + h / 2.0; + let dist = (cx - tcx).abs() + (cy - tcy).abs(); + if dist < best_dist && dist < MAX_CENTER_DIST { + best_dist = dist; + best = Some(face); + } + } + best.ok_or(StatusCode::NOT_FOUND)? + } + _ => &faces[0], + }; + + // All faces in this frame (bbox + confidence only) for other-face overlays. + let faces_out: Vec = faces + .iter() + .map(|face| FaceBBox { + x: face.get("x").and_then(|v| v.as_i64()).unwrap_or(0), + y: face.get("y").and_then(|v| v.as_i64()).unwrap_or(0), + width: face.get("width").and_then(|v| v.as_i64()).unwrap_or(0), + height: face.get("height").and_then(|v| v.as_i64()).unwrap_or(0), + confidence: face.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0), + }) + .collect(); + + Ok(axum::Json(FaceLandmarksResponse { + frame: params.frame, + x: selected.get("x").and_then(|v| v.as_i64()).unwrap_or(0), + y: selected.get("y").and_then(|v| v.as_i64()).unwrap_or(0), + width: selected.get("width").and_then(|v| v.as_i64()).unwrap_or(0), + height: selected.get("height").and_then(|v| v.as_i64()).unwrap_or(0), + confidence: selected.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0), + pose_angle: selected.get("pose_angle").cloned().or_else(|| selected.get("pose").cloned()), + landmarks: selected + .get("landmarks") + .cloned() + .unwrap_or(serde_json::Value::Null), + lips: selected + .get("lips") + .cloned() + .unwrap_or(serde_json::Value::Null), + faces: faces_out, + })) +} + pub fn pose_appearance_routes() -> Router { Router::new() .route("/api/v1/file/:file_uuid/pose", get(get_pose_handler)) @@ -1735,4 +1871,8 @@ pub fn pose_appearance_routes() -> Router { "/api/v1/file/:file_uuid/appearance", get(get_appearance_handler), ) + .route( + "/api/v1/file/:file_uuid/face-landmarks", + get(get_face_landmarks_handler), + ) } diff --git a/src/api/processing.rs b/src/api/processing.rs index 82bccd82..0ecd9405 100644 --- a/src/api/processing.rs +++ b/src/api/processing.rs @@ -11,7 +11,10 @@ use std::time::Instant; use super::types::AppState; use crate::core::cache::{keys, RedisCache}; -use crate::core::config::REDIS_KEY_PREFIX; +use crate::core::config::{ + FACE_FILTER_CONFIDENCE_PCT_DEFAULT, FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT, + REDIS_KEY_PREFIX, +}; use crate::core::db::schema; use crate::core::db::{ Database, MonitorJobStatus, PostgresDb, ProgressMessage, RedisClient, VideoRecord, VideoStatus, @@ -279,15 +282,18 @@ async fn trigger_processing( // (videos.face_filter, min_confidence 0-100) → None (caller uses Apple Vision defaults 0.5/1). let face_settings_json = if let Some(fs) = req.face_settings.as_ref() { Some(serde_json::json!({ - "min_confidence": fs.min_confidence.unwrap_or(0.5), - "min_size": fs.min_size.unwrap_or(1) + "min_confidence": fs.min_confidence.unwrap_or(FACE_MIN_CONFIDENCE_DEFAULT), + "min_size": fs.min_size.unwrap_or(FACE_MIN_SIZE_DEFAULT) })) } else if let Some(v) = face_filter.as_ref() { let min_conf_pct = v .get("min_confidence") .and_then(|x| x.as_f64()) - .unwrap_or(50.0); - let min_size = v.get("min_size").and_then(|x| x.as_i64()).unwrap_or(1) as i32; + .unwrap_or(FACE_FILTER_CONFIDENCE_PCT_DEFAULT); + let min_size = v + .get("min_size") + .and_then(|x| x.as_i64()) + .unwrap_or(FACE_MIN_SIZE_DEFAULT as i64) as i32; Some(serde_json::json!({ "min_confidence": min_conf_pct / 100.0, "min_size": min_size diff --git a/src/api/trace_agent_api.rs b/src/api/trace_agent_api.rs index 8f6e9b6e..684550e7 100644 --- a/src/api/trace_agent_api.rs +++ b/src/api/trace_agent_api.rs @@ -96,6 +96,8 @@ struct TraceInfo { best_face_frame: i64, best_face_confidence: f64, best_face_bbox: Option, + avg_capture_quality: f64, + best_face_capture_quality: f64, sample_face_id: Option, thumbnail_url: String, } @@ -173,6 +175,11 @@ async fn list_traces_sorted( best_point_id: i64, best_frame: i64, best_bbox: Option, + sum_capture_quality: f64, + best_capture_quality: f64, + best_capture_point_id: i64, + best_capture_frame: i64, + best_capture_bbox: Option, } let mut trace_data: HashMap = HashMap::new(); @@ -181,6 +188,7 @@ async fn list_traces_sorted( let trace_id = payload["trace_id"].as_i64().unwrap_or(0) as i32; let frame = payload["frame"].as_i64().unwrap_or(0); let confidence = payload["confidence"].as_f64().unwrap_or(0.5); + let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0); let point_id = point["id"].as_i64().unwrap_or(0); if confidence < min_confidence || confidence > max_confidence { @@ -197,17 +205,29 @@ async fn list_traces_sorted( best_point_id: 0, best_frame: 0, best_bbox: None, + sum_capture_quality: 0.0, + best_capture_quality: 0.0, + best_capture_point_id: 0, + best_capture_frame: 0, + best_capture_bbox: None, }); entry.face_count += 1; entry.start_frame = entry.start_frame.min(frame); entry.end_frame = entry.end_frame.max(frame); entry.sum_confidence += confidence; + entry.sum_capture_quality += capture_quality; if confidence > entry.best_confidence { entry.best_confidence = confidence; entry.best_point_id = point_id; entry.best_frame = frame; entry.best_bbox = payload.get("bbox").cloned(); } + if capture_quality > entry.best_capture_quality { + entry.best_capture_quality = capture_quality; + entry.best_capture_point_id = point_id; + entry.best_capture_frame = frame; + entry.best_capture_bbox = payload.get("bbox").cloned(); + } } // Filter by min_faces and sort @@ -222,6 +242,8 @@ async fn list_traces_sorted( i64, f64, Option, + f64, + f64, )> = trace_data .into_iter() .filter(|(_, agg)| agg.face_count >= min_faces) @@ -232,6 +254,11 @@ async fn list_traces_sorted( } else { 0.0 }; + let avg_cq = if agg.face_count > 0 { + agg.sum_capture_quality / agg.face_count as f64 + } else { + 0.0 + }; ( tid, agg.face_count, @@ -243,6 +270,8 @@ async fn list_traces_sorted( agg.best_frame, agg.best_confidence, agg.best_bbox, + avg_cq, + agg.best_capture_quality, ) }) .collect(); @@ -267,7 +296,7 @@ async fn list_traces_sorted( let traces: Vec = traces_vec .into_iter() .map( - |(tid, fc, sf, ef, dur, conf, bfid, bff, bfc, bfb)| TraceInfo { + |(tid, fc, sf, ef, dur, conf, bfid, bff, bfc, bfb, acq, bcq)| TraceInfo { trace_id: tid, face_count: fc, start_frame: sf, @@ -280,6 +309,8 @@ async fn list_traces_sorted( best_face_frame: bff, best_face_confidence: bfc, best_face_bbox: bfb, + avg_capture_quality: acq, + best_face_capture_quality: bcq, sample_face_id: None, thumbnail_url: format!("/api/v1/file/{}/trace/{}/thumbnail", file_uuid, tid), }, @@ -321,6 +352,7 @@ struct TraceFaceItem { width: Option, height: Option, confidence: f64, + capture_quality: f64, interpolated: bool, } @@ -438,6 +470,7 @@ async fn list_trace_faces( width: Some(mid_w), height: Some(mid_h), confidence: 0.0, + capture_quality: 0.0, interpolated: true, }); } @@ -447,6 +480,7 @@ async fn list_trace_faces( // Add the real detection let frame_val = frame; let ft = (frame_val as f64 / fps * 10.0).round() / 10.0; + let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0); faces.push(TraceFaceItem { id, start_frame: frame_val, @@ -458,6 +492,7 @@ async fn list_trace_faces( width: Some(w), height: Some(h), confidence: conf as f64, + capture_quality, interpolated: false, }); } @@ -579,7 +614,8 @@ where if conf <= 0.7 { return None; } - let score = (w as f64 * h as f64) * conf; + let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0); + let score = (w as f64 * h as f64) * conf * (0.2 + capture_quality); Some(Candidate { frame: payload["frame"].as_i64().unwrap_or(0), x: bbox["x"].as_f64()? as i32, diff --git a/src/api/universal_search.rs b/src/api/universal_search.rs index a310fcd6..2da95550 100644 --- a/src/api/universal_search.rs +++ b/src/api/universal_search.rs @@ -97,6 +97,8 @@ pub enum SearchResult { end_time: Option, key_frame: Option, key_face: Option, + avg_capture_quality: Option, + best_capture_quality: Option, }, } @@ -329,6 +331,8 @@ pub struct PeopleResult { pub key_frame: Option, pub key_face: Option, pub avg_confidence: Option, + pub avg_capture_quality: Option, + pub best_capture_quality: Option, } async fn search_chunks( @@ -604,6 +608,7 @@ async fn search_persons_internal( "SELECT tp.file_uuid, tp.trace_id, tp.name, \ tp.start_frame, tp.end_frame, tp.frame_count, \ tp.key_frame, tp.key_face, tp.avg_confidence, \ + tp.avg_capture_quality, tp.best_capture_quality, \ n.external_id \ FROM {} tp \ LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \ @@ -643,6 +648,8 @@ async fn search_persons_internal( Option, Option, Option, + Option, + Option, Option, )> = sqlx::query_as(&sql).fetch_all(db.pool()).await?; @@ -658,6 +665,8 @@ async fn search_persons_internal( key_frame, key_face, avg_confidence, + avg_capture_quality, + best_capture_quality, external_id, ) in rows { @@ -679,6 +688,8 @@ async fn search_persons_internal( end_time: None, key_frame, key_face, + avg_capture_quality, + best_capture_quality, }); } @@ -780,6 +791,7 @@ async fn search_people_by_query( "SELECT tp.file_uuid, tp.trace_id, tp.name, \ tp.start_frame, tp.end_frame, tp.frame_count, \ tp.key_frame, tp.key_face, tp.avg_confidence, \ + tp.avg_capture_quality, tp.best_capture_quality, \ n.external_id \ FROM {} tp \ LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \ @@ -819,6 +831,8 @@ async fn search_people_by_query( Option, Option, Option, + Option, + Option, Option, )> = sqlx::query_as(&sql).fetch_all(db.pool()).await?; @@ -833,6 +847,8 @@ async fn search_people_by_query( key_frame, key_face, avg_confidence, + avg_capture_quality, + best_capture_quality, external_id, ) in rows { @@ -850,6 +866,8 @@ async fn search_people_by_query( key_frame, key_face, avg_confidence, + avg_capture_quality, + best_capture_quality, }); } diff --git a/src/core/agent/tools.rs b/src/core/agent/tools.rs index 20e9b1c0..3c2f09c4 100644 --- a/src/core/agent/tools.rs +++ b/src/core/agent/tools.rs @@ -1421,6 +1421,7 @@ pub async fn exec_trace_search( let sql = format!( "SELECT tp.file_uuid, tp.trace_id, tp.name, tp.start_frame, tp.end_frame, \ tp.frame_count, tp.key_frame, tp.status, tp.avg_confidence, \ + tp.avg_capture_quality, tp.best_capture_quality, tp.best_confidence, \ tp.vlm_description, tp.vlm_clothing, tp.vlm_tags, tp.vlm_location, \ tp.vlm_setting, tp.vlm_lighting, COALESCE(v.file_name, ''), COALESCE(v.fps, 25.0) \ FROM {} tp \ @@ -1459,14 +1460,17 @@ pub async fn exec_trace_search( let key_frame: Option = row.get(6); let status: Option = row.get(7); let avg_confidence: Option = row.get(8); - let vlm_description: Option = row.get(9); - let vlm_clothing: Option = row.get(10); - let vlm_tags: Option> = row.get(11); - let vlm_location: Option = row.get(12); - let vlm_setting: Option = row.get(13); - let vlm_lighting: Option = row.get(14); - let file_name: String = row.get(15); - let fps: f64 = row.get(16); + let avg_capture_quality: Option = row.get(9); + let best_capture_quality: Option = row.get(10); + let best_confidence: Option = row.get(11); + let vlm_description: Option = row.get(12); + let vlm_clothing: Option = row.get(13); + let vlm_tags: Option> = row.get(14); + let vlm_location: Option = row.get(15); + let vlm_setting: Option = row.get(16); + let vlm_lighting: Option = row.get(17); + let file_name: String = row.get(18); + let fps: f64 = row.get(19); let start_time = start_frame.map(|f| (f as f64 / fps).round() / 100.0); let end_time = end_frame.map(|f| (f as f64 / fps).round() / 100.0); @@ -1485,6 +1489,9 @@ pub async fn exec_trace_search( "key_frame": key_frame, "status": status, "avg_confidence": avg_confidence, + "best_confidence": best_confidence, + "avg_capture_quality": avg_capture_quality, + "best_capture_quality": best_capture_quality, "vlm_description": vlm_description, "vlm_clothing": vlm_clothing, "vlm_tags": vlm_tags, @@ -1652,6 +1659,7 @@ pub async fn exec_face_profile_search( "SELECT tp.file_uuid, tp.trace_id, tp.name, \ tp.start_frame, tp.end_frame, tp.frame_count, \ tp.key_frame, tp.key_face, tp.avg_confidence, \ + tp.avg_capture_quality, tp.best_capture_quality, \ n.external_id \ FROM {} tp \ LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \ @@ -1691,7 +1699,9 @@ pub async fn exec_face_profile_search( let key_frame: Option = row.get(6); let key_face: Option = row.get(7); let avg_confidence: Option = row.get(8); - let external_id: Option = row.get(9); + let avg_capture_quality: Option = row.get(9); + let best_capture_quality: Option = row.get(10); + let external_id: Option = row.get(11); serde_json::json!({ "card_type": "face_profile", @@ -1704,7 +1714,9 @@ pub async fn exec_face_profile_search( "frame_count": frame_count, "key_frame": key_frame, "key_face": key_face, - "avg_confidence": avg_confidence + "avg_confidence": avg_confidence, + "avg_capture_quality": avg_capture_quality, + "best_capture_quality": best_capture_quality }) }) .collect(); diff --git a/src/core/config.rs b/src/core/config.rs index 0bd74e11..da52f483 100644 --- a/src/core/config.rs +++ b/src/core/config.rs @@ -145,6 +145,13 @@ pub static MONGODB_DATABASE: Lazy = pub static QDRANT_COLLECTION: Lazy = Lazy::new(|| env::var("QDRANT_COLLECTION").unwrap_or_else(|_| "momentry_rule1".to_string())); +// ─── Face detection thresholds (single source of truth) ─── +// Defaults mirror Apple Vision native detection (0.5 confidence / 1px min size). +// Keep scripts/swift_processors/swift_face.swift and scripts/face_processor.py in sync. +pub const FACE_MIN_CONFIDENCE_DEFAULT: f64 = 0.5; // detection threshold (0-1) +pub const FACE_MIN_SIZE_DEFAULT: i32 = 1; // detection min face size (px) +pub const FACE_FILTER_CONFIDENCE_PCT_DEFAULT: f64 = 50.0; // videos.face_filter (0-100%) + pub mod processor { use super::*; diff --git a/src/core/db/postgres_db.rs b/src/core/db/postgres_db.rs index 97338347..24d0d759 100644 --- a/src/core/db/postgres_db.rs +++ b/src/core/db/postgres_db.rs @@ -10,6 +10,7 @@ use uuid::Uuid; use super::{schema, Database, QdrantDb}; use crate::core::chunk::types::{Chunk, ChunkRule, ChunkType}; +use crate::core::config::{FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT}; use crate::core::text::synonym::normalize_chinese_query; use crate::core::text::{ global_synonym_expander, @@ -1028,6 +1029,7 @@ impl PostgresDb { "content_hash TEXT", "proxy_path TEXT", "audio_track TEXT", + "face_filter JSONB", ]; for col in &video_cols { let (col_name, col_def) = col.split_once(' ').unwrap_or((col, "")); @@ -1268,7 +1270,29 @@ impl PostgresDb { sqlx::query("CREATE TABLE IF NOT EXISTS strangers (id SERIAL PRIMARY KEY, file_uuid TEXT, trace_id INTEGER, metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?; // ── Trace Profiles (VLM metadata for face traces) ── - sqlx::query("CREATE TABLE IF NOT EXISTS trace_profiles (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, trace_id INTEGER NOT NULL, name VARCHAR(255), start_frame BIGINT, end_frame BIGINT, frame_count INTEGER, key_frame VARCHAR(255), key_face VARCHAR(255), status VARCHAR(50) DEFAULT 'pending', avg_confidence DOUBLE PRECISION, vlm_description TEXT, vlm_clothing TEXT, vlm_tags TEXT[], vlm_location VARCHAR(255), vlm_setting VARCHAR(255), vlm_lighting VARCHAR(100), vlm_weather VARCHAR(100), vlm_hand_objects TEXT, vlm_has_plants BOOLEAN, vlm_has_animals BOOLEAN, vlm_background TEXT, vlm_bg_tags TEXT[], vlm_model VARCHAR(64), metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?; + sqlx::query("CREATE TABLE IF NOT EXISTS trace_profiles (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, trace_id INTEGER NOT NULL, name VARCHAR(255), start_frame BIGINT, end_frame BIGINT, frame_count INTEGER, key_frame VARCHAR(255), key_face VARCHAR(255), status VARCHAR(50) DEFAULT 'pending', avg_confidence DOUBLE PRECISION, best_confidence DOUBLE PRECISION, avg_capture_quality DOUBLE PRECISION, best_capture_quality DOUBLE PRECISION, avg_bbox JSONB, best_bbox JSONB, vlm_description TEXT, vlm_clothing TEXT, vlm_tags TEXT[], vlm_location VARCHAR(255), vlm_setting VARCHAR(255), vlm_lighting VARCHAR(100), vlm_weather VARCHAR(100), vlm_hand_objects TEXT, vlm_has_plants BOOLEAN, vlm_has_animals BOOLEAN, vlm_background TEXT, vlm_bg_tags TEXT[], vlm_model VARCHAR(64), metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?; + // Migration: add new fields to existing trace_profiles tables (safe no-op if columns exist) + sqlx::query( + "ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_confidence DOUBLE PRECISION", + ) + .execute(pool) + .await?; + sqlx::query( + "ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS avg_capture_quality DOUBLE PRECISION", + ) + .execute(pool) + .await?; + sqlx::query( + "ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_capture_quality DOUBLE PRECISION", + ) + .execute(pool) + .await?; + sqlx::query("ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS avg_bbox JSONB") + .execute(pool) + .await?; + sqlx::query("ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_bbox JSONB") + .execute(pool) + .await?; sqlx::query( "CREATE INDEX IF NOT EXISTS idx_trace_profiles_file_uuid ON trace_profiles(file_uuid)", ) @@ -1971,7 +1995,13 @@ impl PostgresDb { .fetch_optional(&self.pool) .await?; - let face_settings_json = face_settings.map(|v| v.to_string()).unwrap_or_else(|| "{\"min_confidence\": 0.75, \"min_size\": 64}".to_string()); + let face_settings_json = face_settings.map(|v| v.to_string()).unwrap_or_else(|| { + serde_json::json!({ + "min_confidence": FACE_MIN_CONFIDENCE_DEFAULT, + "min_size": FACE_MIN_SIZE_DEFAULT + }) + .to_string() + }); let row = if let Some(job_id) = existing_id { // Update existing job diff --git a/src/core/db/schema.rs b/src/core/db/schema.rs index c16574b5..7b79535f 100644 --- a/src/core/db/schema.rs +++ b/src/core/db/schema.rs @@ -42,7 +42,8 @@ pub async fn upsert_trace_profile( // Use LEFT JOIN to get tkg_nodes data for backfilling let sql = format!( "INSERT INTO {tp_table} (file_uuid, trace_id, name, start_frame, end_frame, \ - frame_count, key_frame, key_face, status, avg_confidence, properties) \ + frame_count, key_frame, key_face, status, avg_confidence, \ + best_confidence, avg_capture_quality, best_capture_quality, avg_bbox, best_bbox, properties) \ SELECT $1, $2, $3, \ COALESCE((tn.properties->>'start_frame')::bigint, tp.start_frame), \ COALESCE((tn.properties->>'end_frame')::bigint, tp.end_frame), \ @@ -51,6 +52,11 @@ pub async fn upsert_trace_profile( COALESCE(tn.properties->>'key_face', tp.key_face), \ 'pending', \ COALESCE((tn.properties->>'avg_confidence')::double precision, tp.avg_confidence), \ + COALESCE((tn.properties->>'best_confidence')::double precision, tp.best_confidence), \ + COALESCE((tn.properties->>'avg_capture_quality')::double precision, tp.avg_capture_quality), \ + COALESCE((tn.properties->>'best_capture_quality')::double precision, tp.best_capture_quality), \ + COALESCE((tn.properties->>'avg_bbox')::jsonb, tp.avg_bbox), \ + COALESCE((tn.properties->>'best_bbox')::jsonb, tp.best_bbox), \ COALESCE($4::jsonb, tn.properties, '{{}}'::jsonb) \ FROM (VALUES (1)) AS dummy \ LEFT JOIN {tkg_table} tn ON tn.file_uuid = $1 \ @@ -64,6 +70,11 @@ pub async fn upsert_trace_profile( key_frame = COALESCE(EXCLUDED.key_frame, {tp_table}.key_frame), \ key_face = COALESCE(EXCLUDED.key_face, {tp_table}.key_face), \ avg_confidence = COALESCE(EXCLUDED.avg_confidence, {tp_table}.avg_confidence), \ + best_confidence = COALESCE(EXCLUDED.best_confidence, {tp_table}.best_confidence), \ + avg_capture_quality = COALESCE(EXCLUDED.avg_capture_quality, {tp_table}.avg_capture_quality), \ + best_capture_quality = COALESCE(EXCLUDED.best_capture_quality, {tp_table}.best_capture_quality), \ + avg_bbox = COALESCE(EXCLUDED.avg_bbox, {tp_table}.avg_bbox), \ + best_bbox = COALESCE(EXCLUDED.best_bbox, {tp_table}.best_bbox), \ updated_at = NOW()", ); diff --git a/src/core/face_filter_engine.rs b/src/core/face_filter_engine.rs index 454693f7..480f2f2e 100644 --- a/src/core/face_filter_engine.rs +++ b/src/core/face_filter_engine.rs @@ -8,26 +8,26 @@ pub struct FaceFilterFeatures { pub face_id: String, pub file_uuid: String, pub frame: i32, - + // Bbox size (pre-computed as min(width, height)) pub bbox_size: Option, - + // Landmark geometric features pub eye_ratio: Option, pub nose_ratio: Option, pub pose_score: Option, - + // MediaPipe verification features pub mediapipe_detected: Option, pub mediapipe_iou: Option, - + // Embedding similarity features pub embedding_similarity: Option, - + // Temporal consistency features pub consecutive_frames: Option, pub total_frames_detected: Option, - + // Source information pub apple_vision_confidence: Option, pub mediapipe_confidence: Option, @@ -173,7 +173,11 @@ impl FilterEngine { } /// Apply landmark analysis rule - fn apply_landmark_analysis(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult { + fn apply_landmark_analysis( + &self, + features: &FaceFilterFeatures, + config: &RuleConfig, + ) -> RuleResult { if !config.enabled { return RuleResult { enabled: false, @@ -190,7 +194,7 @@ impl FilterEngine { 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)); @@ -200,7 +204,7 @@ impl FilterEngine { // 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)); @@ -210,7 +214,7 @@ impl FilterEngine { // 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)); @@ -233,7 +237,11 @@ impl FilterEngine { } /// Apply MediaPipe verification rule - fn apply_mediapipe_verification(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult { + fn apply_mediapipe_verification( + &self, + features: &FaceFilterFeatures, + config: &RuleConfig, + ) -> RuleResult { if !config.enabled { return RuleResult { enabled: false, @@ -256,7 +264,7 @@ impl FilterEngine { // 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, @@ -276,7 +284,11 @@ impl FilterEngine { } /// Apply embedding similarity rule - fn apply_embedding_similarity(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult { + fn apply_embedding_similarity( + &self, + features: &FaceFilterFeatures, + config: &RuleConfig, + ) -> RuleResult { if !config.enabled { return RuleResult { enabled: false, @@ -288,7 +300,7 @@ impl FilterEngine { 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, @@ -308,7 +320,11 @@ impl FilterEngine { } /// Apply temporal consistency rule - fn apply_temporal_consistency(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult { + fn apply_temporal_consistency( + &self, + features: &FaceFilterFeatures, + config: &RuleConfig, + ) -> RuleResult { if !config.enabled { return RuleResult { enabled: false, @@ -319,8 +335,10 @@ impl FilterEngine { } if let Some(consecutive) = features.consecutive_frames { - let min_consecutive = config.thresholds["min_consecutive_frames"].as_i64().unwrap_or(3) as i32; - + let min_consecutive = config.thresholds["min_consecutive_frames"] + .as_i64() + .unwrap_or(3) as i32; + if consecutive < min_consecutive { return RuleResult { enabled: true, @@ -343,42 +361,54 @@ impl FilterEngine { /// 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 - }), - }); - + + 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, @@ -398,11 +428,12 @@ mod tests { 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, + bbox_size: Some(80), eye_ratio: Some(0.37), nose_ratio: Some(0.15), pose_score: Some(0.1), @@ -415,7 +446,7 @@ mod tests { 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); } @@ -424,24 +455,25 @@ mod tests { 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 + bbox_size: Some(40), + eye_ratio: Some(0.60), // Abnormal (above max 0.55) + nose_ratio: Some(0.02), // Abnormal + pose_score: Some(0.9), // Abnormal (above max 0.8) + mediapipe_detected: Some(false), // Not detected mediapipe_iou: Some(0.0), - embedding_similarity: Some(0.15), // Low similarity - consecutive_frames: Some(1), // Single frame + embedding_similarity: Some(0.05), // Very 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); } diff --git a/src/core/file_profile.rs b/src/core/file_profile.rs index 6c2f5de5..afba2a36 100644 --- a/src/core/file_profile.rs +++ b/src/core/file_profile.rs @@ -2,17 +2,21 @@ use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; +use crate::core::config::{FACE_FILTER_CONFIDENCE_PCT_DEFAULT, FACE_MIN_SIZE_DEFAULT}; + /// Version of the file profile schema. const PROFILE_VERSION: &str = "1.0"; // ─── Data Types ─── /// Per-file face detection thresholds. `min_confidence` is 0–100 (%), -/// `min_size` is px. Mirrors `videos.face_filter` DB column (same units). +/// `min_size` is px, `min_capture_quality` is 0–1. Mirrors `videos.face_filter` DB column. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FaceFilterSettings { pub min_confidence: f64, pub min_size: i32, + #[serde(default)] + pub min_capture_quality: f64, } impl FaceFilterSettings { @@ -20,8 +24,9 @@ impl FaceFilterSettings { /// Filter later for display; detect everything first. pub fn defaults() -> Self { Self { - min_confidence: 50.0, - min_size: 1, + min_confidence: FACE_FILTER_CONFIDENCE_PCT_DEFAULT, + min_size: FACE_MIN_SIZE_DEFAULT, + min_capture_quality: 0.0, } } } @@ -378,7 +383,19 @@ pub struct FaceTraceProfile { pub frame_count: i64, pub start_frame: i64, pub end_frame: i64, + #[serde(default)] + pub best_frame: Option, pub avg_confidence: Option, + #[serde(default)] + pub best_confidence: Option, + #[serde(default)] + pub avg_capture_quality: Option, + #[serde(default)] + pub best_capture_quality: Option, + #[serde(default)] + pub avg_bbox: Option, + #[serde(default)] + pub best_bbox: Option, pub key_frame: Option, // filename: key_frame.jpg pub key_face: Option, // filename: key_face.jpg pub status: String, // pending / bound / merged @@ -406,7 +423,13 @@ impl FaceTraceProfile { frame_count: i64, start_frame: i64, end_frame: i64, + best_frame: i64, avg_confidence: Option, + avg_capture_quality: Option, + best_confidence: f64, + best_capture_quality: f64, + avg_bbox: serde_json::Value, + best_bbox: Option, ) -> Self { Self { version: PROFILE_VERSION.to_string(), @@ -416,7 +439,13 @@ impl FaceTraceProfile { frame_count, start_frame, end_frame, + best_frame: Some(best_frame), avg_confidence, + best_confidence: Some(best_confidence), + avg_capture_quality, + best_capture_quality: Some(best_capture_quality), + avg_bbox: Some(avg_bbox), + best_bbox, key_frame: None, key_face: None, status: "pending".to_string(), diff --git a/src/core/processor/asr.rs b/src/core/processor/asr.rs index e3a104e6..02a8ec3a 100644 --- a/src/core/processor/asr.rs +++ b/src/core/processor/asr.rs @@ -107,8 +107,10 @@ mod tests { #[test] fn test_asr_result_serialization() { let result = AsrResult { + status: None, language: Some("en".to_string()), language_probability: Some(0.95), + segment_count: 2, segments: vec![ AsrSegment { start_time: 0.0, @@ -116,6 +118,7 @@ mod tests { start_frame: Some(0), end_frame: Some(60), text: "Hello world".to_string(), + confidence: 0.95, }, AsrSegment { start_time: 2.5, @@ -123,6 +126,7 @@ mod tests { start_frame: Some(60), end_frame: Some(120), text: "Test speech".to_string(), + confidence: 0.9, }, ], }; @@ -157,6 +161,7 @@ mod tests { start_frame: Some(0), end_frame: Some(24), text: String::new(), + confidence: 0.0, }; assert_eq!(segment.start_time, 0.0); assert_eq!(segment.end_time, 1.0); @@ -166,9 +171,11 @@ mod tests { #[test] fn test_asr_result_empty_segments() { let result = AsrResult { + status: None, language: None, language_probability: None, segments: vec![], + segment_count: 0, }; assert!(result.language.is_none()); assert!(result.segments.is_empty()); diff --git a/src/core/processor/asrx.rs b/src/core/processor/asrx.rs index 1fa477a9..444f793f 100644 --- a/src/core/processor/asrx.rs +++ b/src/core/processor/asrx.rs @@ -214,6 +214,7 @@ mod tests { #[test] fn test_asrx_result_serialization() { let result = AsrxResult { + status: None, language: Some("en".to_string()), segments: vec![AsrxSegment { start_time: 0.0, @@ -227,6 +228,7 @@ mod tests { quality: None, }], embeddings: None, + segment_count: 1, }; let json = serde_json::to_string(&result).unwrap(); @@ -255,9 +257,11 @@ mod tests { #[test] fn test_asrx_result_empty_segments() { let result = AsrxResult { + status: None, language: None, segments: vec![], embeddings: None, + segment_count: 0, }; assert!(result.segments.is_empty()); assert!(result.language.is_none()); diff --git a/src/core/processor/face.rs b/src/core/processor/face.rs index ac2f82c2..1215c1c2 100644 --- a/src/core/processor/face.rs +++ b/src/core/processor/face.rs @@ -53,6 +53,8 @@ pub struct Face { pub width: i32, pub height: i32, pub confidence: f32, + #[serde(default)] + pub capture_quality: Option, pub embedding: Option>, pub landmarks: Option, pub pose_angle: Option, @@ -148,8 +150,10 @@ mod tests { #[test] fn test_face_result_serialization() { let result = FaceResult { + status: None, frame_count: 100, fps: 30.0, + total_faces: 1, frames: vec![FaceFrame { frame: 0, timestamp: 0.0, @@ -160,6 +164,7 @@ mod tests { width: 50, height: 60, confidence: 0.95, + capture_quality: Some(0.9), embedding: Some(vec![0.1, 0.2, 0.3]), landmarks: Some(serde_json::json!([[10.0, 20.0], [30.0, 40.0]])), pose_angle: None, @@ -216,9 +221,11 @@ mod tests { #[test] fn test_face_result_empty_frames() { let result = FaceResult { + status: None, frame_count: 0, fps: 0.0, frames: vec![], + total_faces: 0, }; assert!(result.frames.is_empty()); } @@ -232,6 +239,7 @@ mod tests { width: 10, height: 10, confidence: 0.5, + capture_quality: None, embedding: None, landmarks: None, pose_angle: None, @@ -249,6 +257,7 @@ mod tests { width: 50, height: 60, confidence: 0.95, + capture_quality: Some(0.8), embedding: Some(vec![0.1; 512]), landmarks: None, pose_angle: None, diff --git a/src/core/processor/tkg.rs b/src/core/processor/tkg.rs index 4562e556..b343a374 100644 --- a/src/core/processor/tkg.rs +++ b/src/core/processor/tkg.rs @@ -20,6 +20,7 @@ struct FacePoint { w: f64, h: f64, confidence: f64, + capture_quality: f64, point_id: Option, } @@ -121,6 +122,7 @@ fn parse_face_points(points: Vec) -> Vec { w, h, confidence: payload["confidence"].as_f64().unwrap_or(0.5), + capture_quality: payload["capture_quality"].as_f64().unwrap_or(0.0), point_id: p["id"].as_u64().map(|id| id.to_string()), }) }) @@ -1134,10 +1136,16 @@ async fn build_face_track_nodes_from_qdrant( sum_w: f64, sum_h: f64, sum_confidence: f64, + sum_capture_quality: f64, frames: Vec<(i64, f64, f64, f64, f64)>, // (frame, x, y, w, h) best_frame: i64, best_confidence: f64, best_point_id: Option, + cq_best_frame: i64, + cq_best_quality: f64, + cq_best_point_id: Option, + cq_best_bbox: Option, + best_bbox: Option, } let mut traces: HashMap = HashMap::new(); @@ -1151,10 +1159,16 @@ async fn build_face_track_nodes_from_qdrant( sum_w: 0.0, sum_h: 0.0, sum_confidence: 0.0, + sum_capture_quality: 0.0, frames: vec![], best_frame: 0, best_confidence: 0.0, best_point_id: None, + cq_best_frame: 0, + cq_best_quality: 0.0, + cq_best_point_id: None, + cq_best_bbox: None, + best_bbox: None, }); entry.frame_count += 1; entry.start_f = entry.start_f.min(p.frame); @@ -1164,12 +1178,31 @@ async fn build_face_track_nodes_from_qdrant( entry.sum_w += p.w; entry.sum_h += p.h; entry.sum_confidence += p.confidence; + entry.sum_capture_quality += p.capture_quality; entry.frames.push((p.frame, p.x, p.y, p.w, p.h)); // Track best face (highest confidence) if p.confidence > entry.best_confidence { entry.best_confidence = p.confidence; entry.best_frame = p.frame; entry.best_point_id = p.point_id.clone(); + entry.best_bbox = Some(serde_json::json!({ + "x": p.x.round() as i64, + "y": p.y.round() as i64, + "width": p.w.round() as i64, + "height": p.h.round() as i64, + })); + } + // Track best capture quality face (used for key frame / key face set) + if p.capture_quality > entry.cq_best_quality { + entry.cq_best_quality = p.capture_quality; + entry.cq_best_frame = p.frame; + entry.cq_best_point_id = p.point_id.clone(); + entry.cq_best_bbox = Some(serde_json::json!({ + "x": p.x.round() as i64, + "y": p.y.round() as i64, + "width": p.w.round() as i64, + "height": p.h.round() as i64, + })); } } @@ -1210,24 +1243,34 @@ async fn build_face_track_nodes_from_qdrant( 0.0 }; + let avg_capture_quality = if agg.frame_count > 0 { + agg.sum_capture_quality / agg.frame_count as f64 + } else { + 0.0 + }; + let props = serde_json::json!({ "trace_id": tid, "frame_count": agg.frame_count, "start_frame": agg.start_f, "end_frame": agg.end_f, - "key_frame": agg.best_frame, - "key_face": agg.best_point_id.as_deref().unwrap_or(""), + "key_frame": agg.cq_best_frame, + "key_face": agg.cq_best_point_id.as_deref().unwrap_or(""), "avg_bbox": { "x": (agg.sum_x / agg.frame_count as f64).round() as i64, "y": (agg.sum_y / agg.frame_count as f64).round() as i64, "width": (agg.sum_w / agg.frame_count as f64).round() as i64, "height": (agg.sum_h / agg.frame_count as f64).round() as i64, }, + "best_bbox": agg.cq_best_bbox, "avg_yaw": (avg_yaw * 1000.0).round() / 1000.0, "avg_pitch": (avg_pitch * 1000.0).round() / 1000.0, "avg_roll": (avg_roll * 1000.0).round() / 1000.0, "pose_count": pose_count, "avg_confidence": (avg_confidence * 1000.0).round() / 1000.0, + "best_confidence": (agg.best_confidence * 1000.0).round() / 1000.0, + "avg_capture_quality": (avg_capture_quality * 1000.0).round() / 1000.0, + "best_capture_quality": (agg.cq_best_quality * 1000.0).round() / 1000.0, "status": "pending", }); @@ -1277,13 +1320,19 @@ async fn build_face_track_nodes_from_qdrant( agg.frame_count, agg.start_f, agg.end_f, + agg.cq_best_frame, Some(avg_confidence), + Some(avg_capture_quality), + agg.best_confidence, + agg.cq_best_quality, + props["avg_bbox"].clone(), + agg.cq_best_bbox.clone(), ); // Extract key_frame JPEG bytes via ffmpeg pipe // Use select=eq(n\,frame) for VFR compatibility (decoded index, not time-based) let key_frame_jpeg: Option> = video_path.as_ref().and_then(|vp| { - let select = format!("select=eq(n\\,{})", agg.best_frame); + let select = format!("select=eq(n\\,{})", agg.cq_best_frame); let output = std::process::Command::new("ffmpeg") .args(["-y", "-v", "quiet", "-i"]) .arg(vp) @@ -1311,13 +1360,13 @@ async fn build_face_track_nodes_from_qdrant( } }); - // Crop key_face JPEG bytes from key_frame using representative bbox (best confidence frame) + // Crop key_face JPEG bytes from key_frame using representative bbox (best capture quality frame) let key_face_jpeg: Option> = key_frame_jpeg.as_ref().and_then(|kf| { - // Find bbox for best_frame from trace frames + // Find bbox for cq_best_frame from trace frames let (bf, bx, by, bw, bh) = agg .frames .iter() - .find(|(f, _, _, _, _)| *f == agg.best_frame)?; + .find(|(f, _, _, _, _)| *f == agg.cq_best_frame)?; let (bx, by, bw, bh) = (*bx, *by, *bw, *bh); // Validate bbox: must have positive dimensions @@ -1364,8 +1413,8 @@ async fn build_face_track_nodes_from_qdrant( }); // Save all three files to output/{file_uuid}/{trace_id}/ - let mut key_frame_file = agg.best_frame.to_string(); - let mut key_face_file = agg.best_point_id.as_deref().unwrap_or("").to_string(); + let mut key_frame_file = agg.cq_best_frame.to_string(); + let mut key_face_file = agg.cq_best_point_id.as_deref().unwrap_or("").to_string(); match trace_profile.save( output_dir, @@ -1416,7 +1465,7 @@ async fn build_face_track_nodes_from_qdrant( if need_retry { if let Some(ref vp) = video_path { - let select = format!("select=eq(n\\,{})", agg.best_frame); + let select = format!("select=eq(n\\,{})", agg.cq_best_frame); // Retry key_frame extraction if !kf_path.exists() { if let Ok(output) = std::process::Command::new("ffmpeg") @@ -1455,7 +1504,7 @@ async fn build_face_track_nodes_from_qdrant( let (_, bx, by, bw, bh) = agg .frames .iter() - .find(|(f, _, _, _, _)| *f == agg.best_frame) + .find(|(f, _, _, _, _)| *f == agg.cq_best_frame) .cloned() .unwrap_or((0, 0.0, 0.0, 100.0, 100.0)); @@ -1533,10 +1582,15 @@ async fn build_face_track_nodes_from_qdrant( "key_frame": key_frame_file, "key_face": key_face_file, "avg_bbox": props["avg_bbox"].clone(), + "best_bbox": props["best_bbox"].clone(), "avg_yaw": props["avg_yaw"].clone(), "avg_pitch": props["avg_pitch"].clone(), "avg_roll": props["avg_roll"].clone(), "pose_count": pose_count, + "avg_confidence": props["avg_confidence"].clone(), + "best_confidence": props["best_confidence"].clone(), + "avg_capture_quality": props["avg_capture_quality"].clone(), + "best_capture_quality": props["best_capture_quality"].clone(), "status": "pending", }); @@ -3601,6 +3655,7 @@ mod tests { w: 50.0, h: 50.0, confidence: 0.9, + capture_quality: 0.0, point_id: None, }, FacePoint { @@ -3611,6 +3666,7 @@ mod tests { w: 50.0, h: 50.0, confidence: 0.9, + capture_quality: 0.0, point_id: None, }, FacePoint { @@ -3621,6 +3677,7 @@ mod tests { w: 50.0, h: 50.0, confidence: 0.9, + capture_quality: 0.0, point_id: None, }, FacePoint { @@ -3631,6 +3688,7 @@ mod tests { w: 50.0, h: 50.0, confidence: 0.9, + capture_quality: 0.0, point_id: None, }, ]; @@ -3661,6 +3719,7 @@ mod tests { w: 100.0, h: 100.0, confidence: 0.9, + capture_quality: 0.0, point_id: None, }, FacePoint { @@ -3671,6 +3730,7 @@ mod tests { w: 100.0, h: 100.0, confidence: 0.9, + capture_quality: 0.0, point_id: None, }, ]; @@ -3692,6 +3752,7 @@ mod tests { w: 100.0, h: 100.0, confidence: 0.9, + capture_quality: 0.0, point_id: None, }, FacePoint { @@ -3702,6 +3763,7 @@ mod tests { w: 100.0, h: 100.0, confidence: 0.9, + capture_quality: 0.0, point_id: None, }, ]; @@ -3722,6 +3784,7 @@ mod tests { w: 100.0, h: 100.0, confidence: 0.9, + capture_quality: 0.0, point_id: None, }]; let index = build_frame_index(&points); diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index e566538f..7012d6a8 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -21,7 +21,9 @@ static FACE_TRACE_INFLIGHT: LazyLock = None; if let Some(ref fs) = job.face_settings { - let min_confidence = fs.get("min_confidence").and_then(|v| v.as_f64()).unwrap_or(0.5); - let min_size = fs.get("min_size").and_then(|v| v.as_i64()).unwrap_or(1) as i32; + let min_confidence = fs + .get("min_confidence") + .and_then(|v| v.as_f64()) + .unwrap_or(FACE_MIN_CONFIDENCE_DEFAULT); + let min_size = fs + .get("min_size") + .and_then(|v| v.as_i64()) + .unwrap_or(FACE_MIN_SIZE_DEFAULT as i64) as i32; tracing::info!( "[WORKER] Job {} face_settings: CONFIDENCE={}, SIZE={}", job.uuid,