fix: add min_capture_quality to FaceFilterSettings + trace profile fixes

- Add min_capture_quality to FaceFilterSettings (file_profile.rs)
- Fix store_traced_faces.py: load embeddings from Qdrant with_vector=True
- Fix face_tracker.py: force new traces when frame_gap > 30
- Fix backfill_trace_profiles.py: key_frame select=eq(n,N), bbox scaling, best_frame
- Add best_frame to FaceTraceProfile (Rust + Python)
- Fix min_capture_quality persistence in file-profile API
This commit is contained in:
Accusys
2026-08-13 10:12:21 +08:00
parent 71172fa354
commit 39e9ce4c3b
25 changed files with 723 additions and 131 deletions
+42 -17
View File
@@ -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"
+14 -2
View File
@@ -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),
+31 -2
View File
@@ -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)
+48 -6
View File
@@ -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 {
+37 -2
View File
@@ -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()
+1
View File
@@ -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,