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:
@@ -77,15 +77,12 @@ def get_video_path(file_uuid):
|
|||||||
|
|
||||||
|
|
||||||
def extract_key_frame(video_path, frame_num, fps, output_path):
|
def extract_key_frame(video_path, frame_num, fps, output_path):
|
||||||
"""Extract a specific frame from video using ffmpeg."""
|
"""Extract a specific frame from video using ffmpeg select filter (precise frame)."""
|
||||||
if fps <= 0:
|
|
||||||
return False
|
|
||||||
timestamp = frame_num / fps
|
|
||||||
try:
|
try:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
["ffmpeg", "-y", "-ss", f"{timestamp:.3f}",
|
["ffmpeg", "-y", "-i", video_path,
|
||||||
"-i", video_path,
|
"-vf", f"select=eq(n\\,{frame_num}),scale=640:-1",
|
||||||
"-vframes", "1", "-vf", "scale=640:-1", "-q:v", "5",
|
"-vframes", "1", "-q:v", "5",
|
||||||
output_path],
|
output_path],
|
||||||
capture_output=True, timeout=30
|
capture_output=True, timeout=30
|
||||||
)
|
)
|
||||||
@@ -95,11 +92,14 @@ def extract_key_frame(video_path, frame_num, fps, output_path):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def crop_key_face(key_frame_path, bbox, output_path):
|
def crop_key_face(key_frame_path, bbox, output_path, video_width=1920):
|
||||||
"""Crop key_face from key_frame using bbox."""
|
"""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"]
|
x, y, w, h = bbox["x"], bbox["y"], bbox["width"], bbox["height"]
|
||||||
if w <= 0 or h <= 0:
|
if w <= 0 or h <= 0:
|
||||||
return False
|
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:
|
try:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
["ffmpeg", "-y", "-i", key_frame_path,
|
["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}},
|
{"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:
|
if not points:
|
||||||
@@ -155,6 +155,7 @@ def build_trace_profiles(file_uuid=None, dry_run=False):
|
|||||||
"frame": pl["frame"],
|
"frame": pl["frame"],
|
||||||
"bbox": pl.get("bbox", {}),
|
"bbox": pl.get("bbox", {}),
|
||||||
"confidence": pl.get("confidence", 0.0),
|
"confidence": pl.get("confidence", 0.0),
|
||||||
|
"capture_quality": pl.get("capture_quality", 0),
|
||||||
})
|
})
|
||||||
|
|
||||||
print(f" {len(points)} points, {len(traces)} traces")
|
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")
|
print(f" Video not found, skipping key_frame extraction")
|
||||||
video_path = None
|
video_path = None
|
||||||
|
|
||||||
# Get FPS from DB
|
# Get FPS and width from DB
|
||||||
fps = 30.0
|
fps = 30.0
|
||||||
|
video_width = 1920
|
||||||
if video_path:
|
if video_path:
|
||||||
psql = "/opt/homebrew/Cellar/libpq/18.4/bin/psql"
|
psql = "/opt/homebrew/Cellar/libpq/18.4/bin/psql"
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
[psql, "-U", "accusys", "-d", "momentry", "-t", "-A", "-c",
|
[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
|
capture_output=True, text=True
|
||||||
)
|
)
|
||||||
if result.returncode == 0 and result.stdout.strip():
|
if result.returncode == 0 and result.stdout.strip():
|
||||||
|
parts = result.stdout.strip().split('|')
|
||||||
try:
|
try:
|
||||||
fps = float(result.stdout.strip())
|
fps = float(parts[0])
|
||||||
except ValueError:
|
video_width = int(parts[1])
|
||||||
|
except (ValueError, IndexError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
for tid, faces in sorted(traces.items()):
|
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]
|
frames = [f["frame"] for f in faces]
|
||||||
confidences = [f["confidence"] 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)
|
frame_count = len(faces)
|
||||||
start_frame = min(frames)
|
start_frame = min(frames)
|
||||||
end_frame = max(frames)
|
end_frame = max(frames)
|
||||||
avg_confidence = sum(confidences) / frame_count if frame_count > 0 else 0.0
|
avg_confidence = sum(confidences) / frame_count if frame_count > 0 else 0.0
|
||||||
|
|
||||||
# Representative frame: highest confidence
|
# Representative frame: highest capture_quality
|
||||||
best = max(faces, key=lambda f: f["confidence"])
|
best = max(faces, key=lambda f: f.get("capture_quality", 0))
|
||||||
best_frame = best["frame"]
|
best_frame = best["frame"]
|
||||||
best_bbox = best["bbox"]
|
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}")
|
trace_dir = os.path.join(OUTPUT_DIR, fid, f"trace_{tid}")
|
||||||
profile_path = os.path.join(trace_dir, "trace_profile.json")
|
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,
|
"frame_count": frame_count,
|
||||||
"start_frame": start_frame,
|
"start_frame": start_frame,
|
||||||
"end_frame": end_frame,
|
"end_frame": end_frame,
|
||||||
|
"best_frame": best_frame,
|
||||||
"avg_confidence": round(avg_confidence, 6),
|
"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_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,
|
"key_face": "key_face.jpg" if os.path.exists(face_path) else None,
|
||||||
"status": "pending",
|
"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
|
# 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:
|
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):
|
if os.path.exists(face_path):
|
||||||
profile["key_face"] = "key_face.jpg"
|
profile["key_face"] = "key_face.jpg"
|
||||||
|
|
||||||
|
|||||||
@@ -123,7 +123,16 @@ class FaceProcessorVision:
|
|||||||
"""
|
"""
|
||||||
print(f"[FACE_V2] Step 1: Vision detection (face only)...")
|
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):
|
if not os.path.exists(SWIFT_BIN) and not os.path.exists(SWIFT_BIN_DEBUG):
|
||||||
build_dir = os.path.join(SCRIPT_DIR, "swift_processors")
|
build_dir = os.path.join(SCRIPT_DIR, "swift_processors")
|
||||||
print(f"[FACE_V2] Building swift_face in {build_dir}...")
|
print(f"[FACE_V2] Building swift_face in {build_dir}...")
|
||||||
@@ -147,7 +156,8 @@ class FaceProcessorVision:
|
|||||||
cmd.extend(["--uuid", self.uuid])
|
cmd.extend(["--uuid", self.uuid])
|
||||||
|
|
||||||
print(f"[FACE_V2] Running: {' '.join(cmd)}")
|
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_conf = os.environ.get("FACE_MIN_CONFIDENCE", "not set (default 0.5)")
|
||||||
min_size = os.environ.get("FACE_MIN_SIZE", "not set (default 1)")
|
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}")
|
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
|
"trace_id": face_idx, # Use face_idx as unique identifier within frame
|
||||||
"bbox": {"x": x, "y": y, "width": w, "height": h},
|
"bbox": {"x": x, "y": y, "width": w, "height": h},
|
||||||
"confidence": face.get("confidence", 0.5),
|
"confidence": face.get("confidence", 0.5),
|
||||||
|
"capture_quality": face.get("captureQuality", 0),
|
||||||
"embedding": emb,
|
"embedding": emb,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -263,6 +274,7 @@ class FaceProcessorVision:
|
|||||||
faces.append({
|
faces.append({
|
||||||
"x": x, "y": y, "width": w, "height": h,
|
"x": x, "y": y, "width": w, "height": h,
|
||||||
"confidence": face.get("confidence", 0.5),
|
"confidence": face.get("confidence", 0.5),
|
||||||
|
"captureQuality": face.get("captureQuality", 0),
|
||||||
"pose_angle": {
|
"pose_angle": {
|
||||||
"angle": pose_angle,
|
"angle": pose_angle,
|
||||||
"roll": pose_info.get("roll", 0),
|
"roll": pose_info.get("roll", 0),
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ def run_face_tracker(
|
|||||||
"width": bbox.get("width", f.get("width", 0)),
|
"width": bbox.get("width", f.get("width", 0)),
|
||||||
"height": bbox.get("height", f.get("height", 0)),
|
"height": bbox.get("height", f.get("height", 0)),
|
||||||
"confidence": f.get("confidence", 0.0),
|
"confidence": f.get("confidence", 0.0),
|
||||||
|
"captureQuality": f.get("captureQuality", 0.0),
|
||||||
}
|
}
|
||||||
if "landmarks" in f:
|
if "landmarks" in f:
|
||||||
face["landmarks"] = f["landmarks"]
|
face["landmarks"] = f["landmarks"]
|
||||||
@@ -97,12 +98,40 @@ def run_face_tracker(
|
|||||||
|
|
||||||
print(f"[TRACE] Processing {len(face_data.get('frames', {}))} frames")
|
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 = (
|
file_uuid = (
|
||||||
face_json_path.split("/")[-1]
|
face_json_path.split("/")[-1]
|
||||||
.replace(".face.json", "")
|
.replace(".face.json", "")
|
||||||
.replace("_traced.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)
|
# Load cut boundaries from cut.json (same directory as face.json)
|
||||||
cut_boundaries = None
|
cut_boundaries = None
|
||||||
@@ -118,7 +147,7 @@ def run_face_tracker(
|
|||||||
print(f"[TRACE] Loaded {len(cut_boundaries)} cut boundaries")
|
print(f"[TRACE] Loaded {len(cut_boundaries)} cut boundaries")
|
||||||
|
|
||||||
face_data = track_faces(
|
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)
|
# Merge traces within same cut (same person re-appearing after occlusion/pose change)
|
||||||
|
|||||||
@@ -39,8 +39,9 @@ struct SwiftFace: ParsableCommand {
|
|||||||
print("[SwiftFace] Video: \(width)x\(height), \(String(format: "%.1f", fps))fps, \(totalFrames) frames")
|
print("[SwiftFace] Video: \(width)x\(height), \(String(format: "%.1f", fps))fps, \(totalFrames) frames")
|
||||||
|
|
||||||
// Read face detection settings from environment variables (with defaults)
|
// Read face detection settings from environment variables (with defaults)
|
||||||
let MIN_CONFIDENCE = Double(ProcessInfo.processInfo.environment["FACE_MIN_CONFIDENCE"] ?? "0.75") ?? 0.75
|
// Keep in sync with src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT
|
||||||
let MIN_SIZE = Int(ProcessInfo.processInfo.environment["FACE_MIN_SIZE"] ?? "64") ?? 64
|
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)")
|
print("[SwiftFace] Settings: MIN_CONFIDENCE=\(MIN_CONFIDENCE), MIN_SIZE=\(MIN_SIZE)")
|
||||||
|
|
||||||
let generator = AVAssetImageGenerator(asset: asset)
|
let generator = AVAssetImageGenerator(asset: asset)
|
||||||
@@ -109,15 +110,17 @@ struct SwiftFace: ParsableCommand {
|
|||||||
let handler = VNImageRequestHandler(cvPixelBuffer: pb, options: [:])
|
let handler = VNImageRequestHandler(cvPixelBuffer: pb, options: [:])
|
||||||
let detectReq = VNDetectFaceRectanglesRequest()
|
let detectReq = VNDetectFaceRectanglesRequest()
|
||||||
let lmReq = VNDetectFaceLandmarksRequest()
|
let lmReq = VNDetectFaceLandmarksRequest()
|
||||||
|
let captureQReq = VNDetectFaceCaptureQualityRequest()
|
||||||
|
|
||||||
do {
|
do {
|
||||||
try handler.perform([detectReq, lmReq])
|
try handler.perform([detectReq, lmReq, captureQReq])
|
||||||
} catch {
|
} catch {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
let faceObservations = detectReq.results ?? []
|
let faceObservations = detectReq.results ?? []
|
||||||
let landmarkObservations = lmReq.results ?? []
|
let landmarkObservations = lmReq.results ?? []
|
||||||
|
let captureQualityObs = captureQReq.results ?? []
|
||||||
guard !faceObservations.isEmpty || !landmarkObservations.isEmpty else {
|
guard !faceObservations.isEmpty || !landmarkObservations.isEmpty else {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -148,11 +151,31 @@ struct SwiftFace: ParsableCommand {
|
|||||||
let faceX = Int(bb.origin.x * imgW)
|
let faceX = Int(bb.origin.x * imgW)
|
||||||
let faceY = Int((1.0 - bb.origin.y - bb.size.height) * imgH)
|
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] = [
|
var faceData: [String: Any] = [
|
||||||
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
|
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
|
||||||
"width": faceW, "height": faceH],
|
"width": faceW, "height": faceH],
|
||||||
"confidence": Double(lmObs.confidence),
|
"confidence": Double(lmObs.confidence),
|
||||||
"captureQuality": Double(lmObs.value(forKey: "faceCaptureQuality") as? Double ?? 0),
|
"captureQuality": captureQ,
|
||||||
]
|
]
|
||||||
|
|
||||||
// Pose from landmark observation
|
// Pose from landmark observation
|
||||||
@@ -222,7 +245,7 @@ struct SwiftFace: ParsableCommand {
|
|||||||
|
|
||||||
// Quality filtering for unmatched face rects
|
// 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 faceW = Int(fBB.size.width * imgW)
|
||||||
let faceH = Int(fBB.size.height * imgH)
|
let faceH = Int(fBB.size.height * imgH)
|
||||||
@@ -232,11 +255,30 @@ struct SwiftFace: ParsableCommand {
|
|||||||
let faceX = Int(fBB.origin.x * imgW)
|
let faceX = Int(fBB.origin.x * imgW)
|
||||||
let faceY = Int((1.0 - fBB.origin.y - fBB.size.height) * imgH)
|
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] = [
|
var faceData: [String: Any] = [
|
||||||
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
|
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
|
||||||
"width": faceW, "height": faceH],
|
"width": faceW, "height": faceH],
|
||||||
"confidence": Double(faceObs.confidence),
|
"confidence": Double(faceObs.confidence),
|
||||||
"captureQuality": Double(faceObs.faceCaptureQuality ?? 0),
|
"captureQuality": captureQ,
|
||||||
]
|
]
|
||||||
if let yaw = faceObs.yaw?.doubleValue,
|
if let yaw = faceObs.yaw?.doubleValue,
|
||||||
let roll = faceObs.roll?.doubleValue {
|
let roll = faceObs.roll?.doubleValue {
|
||||||
|
|||||||
@@ -137,11 +137,46 @@ def match_faces(
|
|||||||
if not previous_faces:
|
if not previous_faces:
|
||||||
return {i: -1 for i in range(len(current_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:
|
if cut_boundaries and prev_frame is not None and curr_frame is not None:
|
||||||
for cf in cut_boundaries:
|
for cf in cut_boundaries:
|
||||||
if prev_frame < cf <= curr_frame:
|
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 = {}
|
matches = {}
|
||||||
used_prev = set()
|
used_prev = set()
|
||||||
|
|||||||
@@ -126,6 +126,7 @@ def push_face_embeddings_batch(file_uuid: str, faces: list, publisher=None) -> i
|
|||||||
"trace_id": face.get("trace_id", 0),
|
"trace_id": face.get("trace_id", 0),
|
||||||
"bbox": face["bbox"],
|
"bbox": face["bbox"],
|
||||||
"confidence": face.get("confidence", 0.5),
|
"confidence": face.get("confidence", 0.5),
|
||||||
|
"capture_quality": face.get("capture_quality", 0.0),
|
||||||
"identity_id": None,
|
"identity_id": None,
|
||||||
"identity_uuid": None,
|
"identity_uuid": None,
|
||||||
"stranger_id": None,
|
"stranger_id": None,
|
||||||
|
|||||||
+4
-3
@@ -501,11 +501,12 @@ async fn register_single_file(
|
|||||||
|
|
||||||
let status = "registered";
|
let status = "registered";
|
||||||
let _ = sqlx::query(&format!(
|
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
|
videos_table
|
||||||
))
|
))
|
||||||
.bind(&file_uuid).bind(&canonical_path).bind(&final_name).bind(&final_file_type)
|
.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(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)
|
.bind(&probe_json).bind(status).bind(&content_hash_val)
|
||||||
.execute(db.pool()).await;
|
.execute(db.pool()).await;
|
||||||
|
|
||||||
@@ -808,8 +809,8 @@ async fn register_file(
|
|||||||
// Convert face_settings to serde_json::Value for create_monitor_job
|
// Convert face_settings to serde_json::Value for create_monitor_job
|
||||||
let face_settings_json = req.face_settings.as_ref().map(|fs| {
|
let face_settings_json = req.face_settings.as_ref().map(|fs| {
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"min_confidence": fs.min_confidence.unwrap_or(0.75),
|
"min_confidence": fs.min_confidence.unwrap_or(config::FACE_MIN_CONFIDENCE_DEFAULT),
|
||||||
"min_size": fs.min_size.unwrap_or(64)
|
"min_size": fs.min_size.unwrap_or(config::FACE_MIN_SIZE_DEFAULT)
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
|
|||||||
@@ -429,6 +429,8 @@ pub struct UnassignedTrace {
|
|||||||
pub best_face_frame: i64,
|
pub best_face_frame: i64,
|
||||||
pub best_face_confidence: f64,
|
pub best_face_confidence: f64,
|
||||||
pub best_face_bbox: Option<serde_json::Value>,
|
pub best_face_bbox: Option<serde_json::Value>,
|
||||||
|
pub avg_capture_quality: f64,
|
||||||
|
pub best_capture_quality: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
@@ -484,6 +486,8 @@ async fn list_unassigned_traces(
|
|||||||
best_point_id: i64,
|
best_point_id: i64,
|
||||||
best_frame: i64,
|
best_frame: i64,
|
||||||
best_bbox: Option<serde_json::Value>,
|
best_bbox: Option<serde_json::Value>,
|
||||||
|
sum_capture_quality: f64,
|
||||||
|
best_capture_quality: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut trace_map: BTreeMap<(String, i32), TraceAgg> = BTreeMap::new();
|
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 frame = payload["frame"].as_i64().unwrap_or(0);
|
||||||
let confidence = payload["confidence"].as_f64().unwrap_or(0.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 point_id = point["id"].as_i64().unwrap_or(0);
|
||||||
|
|
||||||
let entry = trace_map.entry((file_uuid, trace_id)).or_default();
|
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 {
|
if frame > entry.end_frame {
|
||||||
entry.end_frame = 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 {
|
if confidence > entry.best_confidence {
|
||||||
entry.best_confidence = confidence;
|
entry.best_confidence = confidence;
|
||||||
entry.best_point_id = point_id;
|
entry.best_point_id = point_id;
|
||||||
@@ -540,6 +549,12 @@ async fn list_unassigned_traces(
|
|||||||
best_face_frame: agg.best_frame,
|
best_face_frame: agg.best_frame,
|
||||||
best_face_confidence: agg.best_confidence,
|
best_face_confidence: agg.best_confidence,
|
||||||
best_face_bbox: agg.best_bbox,
|
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();
|
.collect();
|
||||||
|
|
||||||
|
|||||||
@@ -968,6 +968,8 @@ pub struct FaceSearchItem {
|
|||||||
pub end_frame: i64,
|
pub end_frame: i64,
|
||||||
pub frame_count: i32,
|
pub frame_count: i32,
|
||||||
pub avg_confidence: f64,
|
pub avg_confidence: f64,
|
||||||
|
pub avg_capture_quality: f64,
|
||||||
|
pub best_capture_quality: f64,
|
||||||
pub thumbnail_url: String,
|
pub thumbnail_url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1101,6 +1103,7 @@ async fn search_file_faces(
|
|||||||
let data_sql = format!(
|
let data_sql = format!(
|
||||||
"SELECT tp.trace_id, tp.file_uuid, COALESCE(tp.name, 'Unassigned') as name, \
|
"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.start_frame, tp.end_frame, tp.frame_count, tp.avg_confidence, \
|
||||||
|
tp.avg_capture_quality, tp.best_capture_quality, \
|
||||||
v.file_name \
|
v.file_name \
|
||||||
FROM {} tp \
|
FROM {} tp \
|
||||||
LEFT JOIN {} v ON tp.file_uuid = v.file_uuid \
|
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 end_frame: i64 = r.get("end_frame");
|
||||||
let frame_count: i32 = r.get("frame_count");
|
let frame_count: i32 = r.get("frame_count");
|
||||||
let avg_confidence: f64 = r.try_get("avg_confidence").ok().unwrap_or(0.0);
|
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 {
|
FaceSearchItem {
|
||||||
trace_id,
|
trace_id,
|
||||||
@@ -1159,6 +1164,8 @@ async fn search_file_faces(
|
|||||||
end_frame,
|
end_frame,
|
||||||
frame_count,
|
frame_count,
|
||||||
avg_confidence: (avg_confidence * 1000.0).round() / 1000.0,
|
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),
|
thumbnail_url: format!("/api/v1/trace-thumb/{}/{}", file_uuid, trace_id),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -819,6 +819,8 @@ pub struct IdentityTraceInfo {
|
|||||||
pub first_sec: f64,
|
pub first_sec: f64,
|
||||||
pub last_sec: f64,
|
pub last_sec: f64,
|
||||||
pub avg_confidence: f64,
|
pub avg_confidence: f64,
|
||||||
|
pub avg_capture_quality: f64,
|
||||||
|
pub best_capture_quality: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
@@ -1088,6 +1090,15 @@ pub async fn get_identity_traces(
|
|||||||
.filter_map(|p| p["payload"]["confidence"].as_f64())
|
.filter_map(|p| p["payload"]["confidence"].as_f64())
|
||||||
.sum::<f64>()
|
.sum::<f64>()
|
||||||
/ frame_count as f64;
|
/ frame_count as f64;
|
||||||
|
let avg_capture_quality = points
|
||||||
|
.iter()
|
||||||
|
.filter_map(|p| p["payload"]["capture_quality"].as_f64())
|
||||||
|
.sum::<f64>()
|
||||||
|
/ 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);
|
let fps = fps_cache.get(file_uuid).copied().unwrap_or(30.0);
|
||||||
|
|
||||||
traces.push(IdentityTraceInfo {
|
traces.push(IdentityTraceInfo {
|
||||||
@@ -1107,6 +1118,8 @@ pub async fn get_identity_traces(
|
|||||||
0.0
|
0.0
|
||||||
},
|
},
|
||||||
avg_confidence: (avg_confidence * 10000.0).round() / 10000.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));
|
traces.sort_by(|a, b| a.trace_id.cmp(&b.trace_id));
|
||||||
|
|||||||
@@ -1728,6 +1728,142 @@ async fn get_appearance_handler(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Face Landmarks Endpoint ──
|
||||||
|
|
||||||
|
#[derive(Debug, serde::Deserialize)]
|
||||||
|
struct FaceLandmarksQuery {
|
||||||
|
frame: i64,
|
||||||
|
bbox_x: Option<f64>,
|
||||||
|
bbox_y: Option<f64>,
|
||||||
|
bbox_w: Option<f64>,
|
||||||
|
bbox_h: Option<f64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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<serde_json::Value>,
|
||||||
|
landmarks: serde_json::Value,
|
||||||
|
lips: serde_json::Value,
|
||||||
|
faces: Vec<FaceBBox>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_face_landmarks_handler(
|
||||||
|
State(_state): State<crate::api::types::AppState>,
|
||||||
|
Path(file_uuid): Path<String>,
|
||||||
|
Query(params): Query<FaceLandmarksQuery>,
|
||||||
|
) -> Result<axum::Json<FaceLandmarksResponse>, 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<FaceBBox> = 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<crate::api::types::AppState> {
|
pub fn pose_appearance_routes() -> Router<crate::api::types::AppState> {
|
||||||
Router::new()
|
Router::new()
|
||||||
.route("/api/v1/file/:file_uuid/pose", get(get_pose_handler))
|
.route("/api/v1/file/:file_uuid/pose", get(get_pose_handler))
|
||||||
@@ -1735,4 +1871,8 @@ pub fn pose_appearance_routes() -> Router<crate::api::types::AppState> {
|
|||||||
"/api/v1/file/:file_uuid/appearance",
|
"/api/v1/file/:file_uuid/appearance",
|
||||||
get(get_appearance_handler),
|
get(get_appearance_handler),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/file/:file_uuid/face-landmarks",
|
||||||
|
get(get_face_landmarks_handler),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-5
@@ -11,7 +11,10 @@ use std::time::Instant;
|
|||||||
|
|
||||||
use super::types::AppState;
|
use super::types::AppState;
|
||||||
use crate::core::cache::{keys, RedisCache};
|
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::schema;
|
||||||
use crate::core::db::{
|
use crate::core::db::{
|
||||||
Database, MonitorJobStatus, PostgresDb, ProgressMessage, RedisClient, VideoRecord, VideoStatus,
|
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).
|
// (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() {
|
let face_settings_json = if let Some(fs) = req.face_settings.as_ref() {
|
||||||
Some(serde_json::json!({
|
Some(serde_json::json!({
|
||||||
"min_confidence": fs.min_confidence.unwrap_or(0.5),
|
"min_confidence": fs.min_confidence.unwrap_or(FACE_MIN_CONFIDENCE_DEFAULT),
|
||||||
"min_size": fs.min_size.unwrap_or(1)
|
"min_size": fs.min_size.unwrap_or(FACE_MIN_SIZE_DEFAULT)
|
||||||
}))
|
}))
|
||||||
} else if let Some(v) = face_filter.as_ref() {
|
} else if let Some(v) = face_filter.as_ref() {
|
||||||
let min_conf_pct = v
|
let min_conf_pct = v
|
||||||
.get("min_confidence")
|
.get("min_confidence")
|
||||||
.and_then(|x| x.as_f64())
|
.and_then(|x| x.as_f64())
|
||||||
.unwrap_or(50.0);
|
.unwrap_or(FACE_FILTER_CONFIDENCE_PCT_DEFAULT);
|
||||||
let min_size = v.get("min_size").and_then(|x| x.as_i64()).unwrap_or(1) as i32;
|
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!({
|
Some(serde_json::json!({
|
||||||
"min_confidence": min_conf_pct / 100.0,
|
"min_confidence": min_conf_pct / 100.0,
|
||||||
"min_size": min_size
|
"min_size": min_size
|
||||||
|
|||||||
@@ -96,6 +96,8 @@ struct TraceInfo {
|
|||||||
best_face_frame: i64,
|
best_face_frame: i64,
|
||||||
best_face_confidence: f64,
|
best_face_confidence: f64,
|
||||||
best_face_bbox: Option<serde_json::Value>,
|
best_face_bbox: Option<serde_json::Value>,
|
||||||
|
avg_capture_quality: f64,
|
||||||
|
best_face_capture_quality: f64,
|
||||||
sample_face_id: Option<String>,
|
sample_face_id: Option<String>,
|
||||||
thumbnail_url: String,
|
thumbnail_url: String,
|
||||||
}
|
}
|
||||||
@@ -173,6 +175,11 @@ async fn list_traces_sorted(
|
|||||||
best_point_id: i64,
|
best_point_id: i64,
|
||||||
best_frame: i64,
|
best_frame: i64,
|
||||||
best_bbox: Option<serde_json::Value>,
|
best_bbox: Option<serde_json::Value>,
|
||||||
|
sum_capture_quality: f64,
|
||||||
|
best_capture_quality: f64,
|
||||||
|
best_capture_point_id: i64,
|
||||||
|
best_capture_frame: i64,
|
||||||
|
best_capture_bbox: Option<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut trace_data: HashMap<i32, TraceAgg> = HashMap::new();
|
let mut trace_data: HashMap<i32, TraceAgg> = 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 trace_id = payload["trace_id"].as_i64().unwrap_or(0) as i32;
|
||||||
let frame = payload["frame"].as_i64().unwrap_or(0);
|
let frame = payload["frame"].as_i64().unwrap_or(0);
|
||||||
let confidence = payload["confidence"].as_f64().unwrap_or(0.5);
|
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);
|
let point_id = point["id"].as_i64().unwrap_or(0);
|
||||||
|
|
||||||
if confidence < min_confidence || confidence > max_confidence {
|
if confidence < min_confidence || confidence > max_confidence {
|
||||||
@@ -197,17 +205,29 @@ async fn list_traces_sorted(
|
|||||||
best_point_id: 0,
|
best_point_id: 0,
|
||||||
best_frame: 0,
|
best_frame: 0,
|
||||||
best_bbox: None,
|
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.face_count += 1;
|
||||||
entry.start_frame = entry.start_frame.min(frame);
|
entry.start_frame = entry.start_frame.min(frame);
|
||||||
entry.end_frame = entry.end_frame.max(frame);
|
entry.end_frame = entry.end_frame.max(frame);
|
||||||
entry.sum_confidence += confidence;
|
entry.sum_confidence += confidence;
|
||||||
|
entry.sum_capture_quality += capture_quality;
|
||||||
if confidence > entry.best_confidence {
|
if confidence > entry.best_confidence {
|
||||||
entry.best_confidence = confidence;
|
entry.best_confidence = confidence;
|
||||||
entry.best_point_id = point_id;
|
entry.best_point_id = point_id;
|
||||||
entry.best_frame = frame;
|
entry.best_frame = frame;
|
||||||
entry.best_bbox = payload.get("bbox").cloned();
|
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
|
// Filter by min_faces and sort
|
||||||
@@ -222,6 +242,8 @@ async fn list_traces_sorted(
|
|||||||
i64,
|
i64,
|
||||||
f64,
|
f64,
|
||||||
Option<serde_json::Value>,
|
Option<serde_json::Value>,
|
||||||
|
f64,
|
||||||
|
f64,
|
||||||
)> = trace_data
|
)> = trace_data
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|(_, agg)| agg.face_count >= min_faces)
|
.filter(|(_, agg)| agg.face_count >= min_faces)
|
||||||
@@ -232,6 +254,11 @@ async fn list_traces_sorted(
|
|||||||
} else {
|
} else {
|
||||||
0.0
|
0.0
|
||||||
};
|
};
|
||||||
|
let avg_cq = if agg.face_count > 0 {
|
||||||
|
agg.sum_capture_quality / agg.face_count as f64
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
(
|
(
|
||||||
tid,
|
tid,
|
||||||
agg.face_count,
|
agg.face_count,
|
||||||
@@ -243,6 +270,8 @@ async fn list_traces_sorted(
|
|||||||
agg.best_frame,
|
agg.best_frame,
|
||||||
agg.best_confidence,
|
agg.best_confidence,
|
||||||
agg.best_bbox,
|
agg.best_bbox,
|
||||||
|
avg_cq,
|
||||||
|
agg.best_capture_quality,
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -267,7 +296,7 @@ async fn list_traces_sorted(
|
|||||||
let traces: Vec<TraceInfo> = traces_vec
|
let traces: Vec<TraceInfo> = traces_vec
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(
|
.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,
|
trace_id: tid,
|
||||||
face_count: fc,
|
face_count: fc,
|
||||||
start_frame: sf,
|
start_frame: sf,
|
||||||
@@ -280,6 +309,8 @@ async fn list_traces_sorted(
|
|||||||
best_face_frame: bff,
|
best_face_frame: bff,
|
||||||
best_face_confidence: bfc,
|
best_face_confidence: bfc,
|
||||||
best_face_bbox: bfb,
|
best_face_bbox: bfb,
|
||||||
|
avg_capture_quality: acq,
|
||||||
|
best_face_capture_quality: bcq,
|
||||||
sample_face_id: None,
|
sample_face_id: None,
|
||||||
thumbnail_url: format!("/api/v1/file/{}/trace/{}/thumbnail", file_uuid, tid),
|
thumbnail_url: format!("/api/v1/file/{}/trace/{}/thumbnail", file_uuid, tid),
|
||||||
},
|
},
|
||||||
@@ -321,6 +352,7 @@ struct TraceFaceItem {
|
|||||||
width: Option<i32>,
|
width: Option<i32>,
|
||||||
height: Option<i32>,
|
height: Option<i32>,
|
||||||
confidence: f64,
|
confidence: f64,
|
||||||
|
capture_quality: f64,
|
||||||
interpolated: bool,
|
interpolated: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -438,6 +470,7 @@ async fn list_trace_faces(
|
|||||||
width: Some(mid_w),
|
width: Some(mid_w),
|
||||||
height: Some(mid_h),
|
height: Some(mid_h),
|
||||||
confidence: 0.0,
|
confidence: 0.0,
|
||||||
|
capture_quality: 0.0,
|
||||||
interpolated: true,
|
interpolated: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -447,6 +480,7 @@ async fn list_trace_faces(
|
|||||||
// Add the real detection
|
// Add the real detection
|
||||||
let frame_val = frame;
|
let frame_val = frame;
|
||||||
let ft = (frame_val as f64 / fps * 10.0).round() / 10.0;
|
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 {
|
faces.push(TraceFaceItem {
|
||||||
id,
|
id,
|
||||||
start_frame: frame_val,
|
start_frame: frame_val,
|
||||||
@@ -458,6 +492,7 @@ async fn list_trace_faces(
|
|||||||
width: Some(w),
|
width: Some(w),
|
||||||
height: Some(h),
|
height: Some(h),
|
||||||
confidence: conf as f64,
|
confidence: conf as f64,
|
||||||
|
capture_quality,
|
||||||
interpolated: false,
|
interpolated: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -579,7 +614,8 @@ where
|
|||||||
if conf <= 0.7 {
|
if conf <= 0.7 {
|
||||||
return None;
|
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 {
|
Some(Candidate {
|
||||||
frame: payload["frame"].as_i64().unwrap_or(0),
|
frame: payload["frame"].as_i64().unwrap_or(0),
|
||||||
x: bbox["x"].as_f64()? as i32,
|
x: bbox["x"].as_f64()? as i32,
|
||||||
|
|||||||
@@ -97,6 +97,8 @@ pub enum SearchResult {
|
|||||||
end_time: Option<f64>,
|
end_time: Option<f64>,
|
||||||
key_frame: Option<String>,
|
key_frame: Option<String>,
|
||||||
key_face: Option<String>,
|
key_face: Option<String>,
|
||||||
|
avg_capture_quality: Option<f64>,
|
||||||
|
best_capture_quality: Option<f64>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,6 +331,8 @@ pub struct PeopleResult {
|
|||||||
pub key_frame: Option<String>,
|
pub key_frame: Option<String>,
|
||||||
pub key_face: Option<String>,
|
pub key_face: Option<String>,
|
||||||
pub avg_confidence: Option<f64>,
|
pub avg_confidence: Option<f64>,
|
||||||
|
pub avg_capture_quality: Option<f64>,
|
||||||
|
pub best_capture_quality: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn search_chunks(
|
async fn search_chunks(
|
||||||
@@ -604,6 +608,7 @@ async fn search_persons_internal(
|
|||||||
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
|
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
|
||||||
tp.start_frame, tp.end_frame, tp.frame_count, \
|
tp.start_frame, tp.end_frame, tp.frame_count, \
|
||||||
tp.key_frame, tp.key_face, tp.avg_confidence, \
|
tp.key_frame, tp.key_face, tp.avg_confidence, \
|
||||||
|
tp.avg_capture_quality, tp.best_capture_quality, \
|
||||||
n.external_id \
|
n.external_id \
|
||||||
FROM {} tp \
|
FROM {} tp \
|
||||||
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
|
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
|
||||||
@@ -643,6 +648,8 @@ async fn search_persons_internal(
|
|||||||
Option<String>,
|
Option<String>,
|
||||||
Option<String>,
|
Option<String>,
|
||||||
Option<f64>,
|
Option<f64>,
|
||||||
|
Option<f64>,
|
||||||
|
Option<f64>,
|
||||||
Option<String>,
|
Option<String>,
|
||||||
)> = sqlx::query_as(&sql).fetch_all(db.pool()).await?;
|
)> = sqlx::query_as(&sql).fetch_all(db.pool()).await?;
|
||||||
|
|
||||||
@@ -658,6 +665,8 @@ async fn search_persons_internal(
|
|||||||
key_frame,
|
key_frame,
|
||||||
key_face,
|
key_face,
|
||||||
avg_confidence,
|
avg_confidence,
|
||||||
|
avg_capture_quality,
|
||||||
|
best_capture_quality,
|
||||||
external_id,
|
external_id,
|
||||||
) in rows
|
) in rows
|
||||||
{
|
{
|
||||||
@@ -679,6 +688,8 @@ async fn search_persons_internal(
|
|||||||
end_time: None,
|
end_time: None,
|
||||||
key_frame,
|
key_frame,
|
||||||
key_face,
|
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, \
|
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
|
||||||
tp.start_frame, tp.end_frame, tp.frame_count, \
|
tp.start_frame, tp.end_frame, tp.frame_count, \
|
||||||
tp.key_frame, tp.key_face, tp.avg_confidence, \
|
tp.key_frame, tp.key_face, tp.avg_confidence, \
|
||||||
|
tp.avg_capture_quality, tp.best_capture_quality, \
|
||||||
n.external_id \
|
n.external_id \
|
||||||
FROM {} tp \
|
FROM {} tp \
|
||||||
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
|
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
|
||||||
@@ -819,6 +831,8 @@ async fn search_people_by_query(
|
|||||||
Option<String>,
|
Option<String>,
|
||||||
Option<String>,
|
Option<String>,
|
||||||
Option<f64>,
|
Option<f64>,
|
||||||
|
Option<f64>,
|
||||||
|
Option<f64>,
|
||||||
Option<String>,
|
Option<String>,
|
||||||
)> = sqlx::query_as(&sql).fetch_all(db.pool()).await?;
|
)> = sqlx::query_as(&sql).fetch_all(db.pool()).await?;
|
||||||
|
|
||||||
@@ -833,6 +847,8 @@ async fn search_people_by_query(
|
|||||||
key_frame,
|
key_frame,
|
||||||
key_face,
|
key_face,
|
||||||
avg_confidence,
|
avg_confidence,
|
||||||
|
avg_capture_quality,
|
||||||
|
best_capture_quality,
|
||||||
external_id,
|
external_id,
|
||||||
) in rows
|
) in rows
|
||||||
{
|
{
|
||||||
@@ -850,6 +866,8 @@ async fn search_people_by_query(
|
|||||||
key_frame,
|
key_frame,
|
||||||
key_face,
|
key_face,
|
||||||
avg_confidence,
|
avg_confidence,
|
||||||
|
avg_capture_quality,
|
||||||
|
best_capture_quality,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+22
-10
@@ -1421,6 +1421,7 @@ pub async fn exec_trace_search(
|
|||||||
let sql = format!(
|
let sql = format!(
|
||||||
"SELECT tp.file_uuid, tp.trace_id, tp.name, tp.start_frame, tp.end_frame, \
|
"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.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_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) \
|
tp.vlm_setting, tp.vlm_lighting, COALESCE(v.file_name, ''), COALESCE(v.fps, 25.0) \
|
||||||
FROM {} tp \
|
FROM {} tp \
|
||||||
@@ -1459,14 +1460,17 @@ pub async fn exec_trace_search(
|
|||||||
let key_frame: Option<String> = row.get(6);
|
let key_frame: Option<String> = row.get(6);
|
||||||
let status: Option<String> = row.get(7);
|
let status: Option<String> = row.get(7);
|
||||||
let avg_confidence: Option<f64> = row.get(8);
|
let avg_confidence: Option<f64> = row.get(8);
|
||||||
let vlm_description: Option<String> = row.get(9);
|
let avg_capture_quality: Option<f64> = row.get(9);
|
||||||
let vlm_clothing: Option<String> = row.get(10);
|
let best_capture_quality: Option<f64> = row.get(10);
|
||||||
let vlm_tags: Option<Vec<String>> = row.get(11);
|
let best_confidence: Option<f64> = row.get(11);
|
||||||
let vlm_location: Option<String> = row.get(12);
|
let vlm_description: Option<String> = row.get(12);
|
||||||
let vlm_setting: Option<String> = row.get(13);
|
let vlm_clothing: Option<String> = row.get(13);
|
||||||
let vlm_lighting: Option<String> = row.get(14);
|
let vlm_tags: Option<Vec<String>> = row.get(14);
|
||||||
let file_name: String = row.get(15);
|
let vlm_location: Option<String> = row.get(15);
|
||||||
let fps: f64 = row.get(16);
|
let vlm_setting: Option<String> = row.get(16);
|
||||||
|
let vlm_lighting: Option<String> = 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 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);
|
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,
|
"key_frame": key_frame,
|
||||||
"status": status,
|
"status": status,
|
||||||
"avg_confidence": avg_confidence,
|
"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_description": vlm_description,
|
||||||
"vlm_clothing": vlm_clothing,
|
"vlm_clothing": vlm_clothing,
|
||||||
"vlm_tags": vlm_tags,
|
"vlm_tags": vlm_tags,
|
||||||
@@ -1652,6 +1659,7 @@ pub async fn exec_face_profile_search(
|
|||||||
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
|
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
|
||||||
tp.start_frame, tp.end_frame, tp.frame_count, \
|
tp.start_frame, tp.end_frame, tp.frame_count, \
|
||||||
tp.key_frame, tp.key_face, tp.avg_confidence, \
|
tp.key_frame, tp.key_face, tp.avg_confidence, \
|
||||||
|
tp.avg_capture_quality, tp.best_capture_quality, \
|
||||||
n.external_id \
|
n.external_id \
|
||||||
FROM {} tp \
|
FROM {} tp \
|
||||||
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
|
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<String> = row.get(6);
|
let key_frame: Option<String> = row.get(6);
|
||||||
let key_face: Option<String> = row.get(7);
|
let key_face: Option<String> = row.get(7);
|
||||||
let avg_confidence: Option<f64> = row.get(8);
|
let avg_confidence: Option<f64> = row.get(8);
|
||||||
let external_id: Option<String> = row.get(9);
|
let avg_capture_quality: Option<f64> = row.get(9);
|
||||||
|
let best_capture_quality: Option<f64> = row.get(10);
|
||||||
|
let external_id: Option<String> = row.get(11);
|
||||||
|
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"card_type": "face_profile",
|
"card_type": "face_profile",
|
||||||
@@ -1704,7 +1714,9 @@ pub async fn exec_face_profile_search(
|
|||||||
"frame_count": frame_count,
|
"frame_count": frame_count,
|
||||||
"key_frame": key_frame,
|
"key_frame": key_frame,
|
||||||
"key_face": key_face,
|
"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();
|
.collect();
|
||||||
|
|||||||
@@ -145,6 +145,13 @@ pub static MONGODB_DATABASE: Lazy<String> =
|
|||||||
pub static QDRANT_COLLECTION: Lazy<String> =
|
pub static QDRANT_COLLECTION: Lazy<String> =
|
||||||
Lazy::new(|| env::var("QDRANT_COLLECTION").unwrap_or_else(|_| "momentry_rule1".to_string()));
|
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 {
|
pub mod processor {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use uuid::Uuid;
|
|||||||
|
|
||||||
use super::{schema, Database, QdrantDb};
|
use super::{schema, Database, QdrantDb};
|
||||||
use crate::core::chunk::types::{Chunk, ChunkRule, ChunkType};
|
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::synonym::normalize_chinese_query;
|
||||||
use crate::core::text::{
|
use crate::core::text::{
|
||||||
global_synonym_expander,
|
global_synonym_expander,
|
||||||
@@ -1028,6 +1029,7 @@ impl PostgresDb {
|
|||||||
"content_hash TEXT",
|
"content_hash TEXT",
|
||||||
"proxy_path TEXT",
|
"proxy_path TEXT",
|
||||||
"audio_track TEXT",
|
"audio_track TEXT",
|
||||||
|
"face_filter JSONB",
|
||||||
];
|
];
|
||||||
for col in &video_cols {
|
for col in &video_cols {
|
||||||
let (col_name, col_def) = col.split_once(' ').unwrap_or((col, ""));
|
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?;
|
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) ──
|
// ── 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(
|
sqlx::query(
|
||||||
"CREATE INDEX IF NOT EXISTS idx_trace_profiles_file_uuid ON trace_profiles(file_uuid)",
|
"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)
|
.fetch_optional(&self.pool)
|
||||||
.await?;
|
.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 {
|
let row = if let Some(job_id) = existing_id {
|
||||||
// Update existing job
|
// Update existing job
|
||||||
|
|||||||
+12
-1
@@ -42,7 +42,8 @@ pub async fn upsert_trace_profile(
|
|||||||
// Use LEFT JOIN to get tkg_nodes data for backfilling
|
// Use LEFT JOIN to get tkg_nodes data for backfilling
|
||||||
let sql = format!(
|
let sql = format!(
|
||||||
"INSERT INTO {tp_table} (file_uuid, trace_id, name, start_frame, end_frame, \
|
"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, \
|
SELECT $1, $2, $3, \
|
||||||
COALESCE((tn.properties->>'start_frame')::bigint, tp.start_frame), \
|
COALESCE((tn.properties->>'start_frame')::bigint, tp.start_frame), \
|
||||||
COALESCE((tn.properties->>'end_frame')::bigint, tp.end_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), \
|
COALESCE(tn.properties->>'key_face', tp.key_face), \
|
||||||
'pending', \
|
'pending', \
|
||||||
COALESCE((tn.properties->>'avg_confidence')::double precision, tp.avg_confidence), \
|
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) \
|
COALESCE($4::jsonb, tn.properties, '{{}}'::jsonb) \
|
||||||
FROM (VALUES (1)) AS dummy \
|
FROM (VALUES (1)) AS dummy \
|
||||||
LEFT JOIN {tkg_table} tn ON tn.file_uuid = $1 \
|
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_frame = COALESCE(EXCLUDED.key_frame, {tp_table}.key_frame), \
|
||||||
key_face = COALESCE(EXCLUDED.key_face, {tp_table}.key_face), \
|
key_face = COALESCE(EXCLUDED.key_face, {tp_table}.key_face), \
|
||||||
avg_confidence = COALESCE(EXCLUDED.avg_confidence, {tp_table}.avg_confidence), \
|
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()",
|
updated_at = NOW()",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -173,7 +173,11 @@ impl FilterEngine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Apply landmark analysis rule
|
/// 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 {
|
if !config.enabled {
|
||||||
return RuleResult {
|
return RuleResult {
|
||||||
enabled: false,
|
enabled: false,
|
||||||
@@ -233,7 +237,11 @@ impl FilterEngine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Apply MediaPipe verification rule
|
/// 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 {
|
if !config.enabled {
|
||||||
return RuleResult {
|
return RuleResult {
|
||||||
enabled: false,
|
enabled: false,
|
||||||
@@ -276,7 +284,11 @@ impl FilterEngine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Apply embedding similarity rule
|
/// 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 {
|
if !config.enabled {
|
||||||
return RuleResult {
|
return RuleResult {
|
||||||
enabled: false,
|
enabled: false,
|
||||||
@@ -308,7 +320,11 @@ impl FilterEngine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Apply temporal consistency rule
|
/// 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 {
|
if !config.enabled {
|
||||||
return RuleResult {
|
return RuleResult {
|
||||||
enabled: false,
|
enabled: false,
|
||||||
@@ -319,7 +335,9 @@ impl FilterEngine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(consecutive) = features.consecutive_frames {
|
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 {
|
if consecutive < min_consecutive {
|
||||||
return RuleResult {
|
return RuleResult {
|
||||||
@@ -344,40 +362,52 @@ impl FilterEngine {
|
|||||||
pub fn default_filter_config() -> FilterRuleConfig {
|
pub fn default_filter_config() -> FilterRuleConfig {
|
||||||
let mut rules = HashMap::new();
|
let mut rules = HashMap::new();
|
||||||
|
|
||||||
rules.insert("landmark_analysis".to_string(), RuleConfig {
|
rules.insert(
|
||||||
enabled: true,
|
"landmark_analysis".to_string(),
|
||||||
weight: 0.3,
|
RuleConfig {
|
||||||
thresholds: serde_json::json!({
|
enabled: true,
|
||||||
"eye_ratio_min": 0.25,
|
weight: 0.3,
|
||||||
"eye_ratio_max": 0.55,
|
thresholds: serde_json::json!({
|
||||||
"nose_ratio_min": 0.08,
|
"eye_ratio_min": 0.25,
|
||||||
"pose_score_max": 0.8
|
"eye_ratio_max": 0.55,
|
||||||
}),
|
"nose_ratio_min": 0.08,
|
||||||
});
|
"pose_score_max": 0.8
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
rules.insert("mediapipe_verification".to_string(), RuleConfig {
|
rules.insert(
|
||||||
enabled: true,
|
"mediapipe_verification".to_string(),
|
||||||
weight: 0.2,
|
RuleConfig {
|
||||||
thresholds: serde_json::json!({
|
enabled: true,
|
||||||
"min_iou": 0.3
|
weight: 0.2,
|
||||||
}),
|
thresholds: serde_json::json!({
|
||||||
});
|
"min_iou": 0.3
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
rules.insert("embedding_similarity".to_string(), RuleConfig {
|
rules.insert(
|
||||||
enabled: true,
|
"embedding_similarity".to_string(),
|
||||||
weight: 0.3,
|
RuleConfig {
|
||||||
thresholds: serde_json::json!({
|
enabled: true,
|
||||||
"min_similarity": 0.70
|
weight: 0.3,
|
||||||
}),
|
thresholds: serde_json::json!({
|
||||||
});
|
"min_similarity": 0.70
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
rules.insert("temporal_consistency".to_string(), RuleConfig {
|
rules.insert(
|
||||||
enabled: true,
|
"temporal_consistency".to_string(),
|
||||||
weight: 0.2,
|
RuleConfig {
|
||||||
thresholds: serde_json::json!({
|
enabled: true,
|
||||||
"min_consecutive_frames": 3
|
weight: 0.2,
|
||||||
}),
|
thresholds: serde_json::json!({
|
||||||
});
|
"min_consecutive_frames": 3
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
FilterRuleConfig {
|
FilterRuleConfig {
|
||||||
version: "1.0".to_string(),
|
version: "1.0".to_string(),
|
||||||
@@ -403,6 +433,7 @@ mod tests {
|
|||||||
face_id: "test_001".to_string(),
|
face_id: "test_001".to_string(),
|
||||||
file_uuid: "test".to_string(),
|
file_uuid: "test".to_string(),
|
||||||
frame: 0,
|
frame: 0,
|
||||||
|
bbox_size: Some(80),
|
||||||
eye_ratio: Some(0.37),
|
eye_ratio: Some(0.37),
|
||||||
nose_ratio: Some(0.15),
|
nose_ratio: Some(0.15),
|
||||||
pose_score: Some(0.1),
|
pose_score: Some(0.1),
|
||||||
@@ -429,13 +460,14 @@ mod tests {
|
|||||||
face_id: "test_002".to_string(),
|
face_id: "test_002".to_string(),
|
||||||
file_uuid: "test".to_string(),
|
file_uuid: "test".to_string(),
|
||||||
frame: 671,
|
frame: 671,
|
||||||
eye_ratio: Some(0.33),
|
bbox_size: Some(40),
|
||||||
nose_ratio: Some(0.02), // Abnormal
|
eye_ratio: Some(0.60), // Abnormal (above max 0.55)
|
||||||
pose_score: Some(0.08),
|
nose_ratio: Some(0.02), // Abnormal
|
||||||
mediapipe_detected: Some(false), // Not detected
|
pose_score: Some(0.9), // Abnormal (above max 0.8)
|
||||||
|
mediapipe_detected: Some(false), // Not detected
|
||||||
mediapipe_iou: Some(0.0),
|
mediapipe_iou: Some(0.0),
|
||||||
embedding_similarity: Some(0.15), // Low similarity
|
embedding_similarity: Some(0.05), // Very low similarity
|
||||||
consecutive_frames: Some(1), // Single frame
|
consecutive_frames: Some(1), // Single frame
|
||||||
total_frames_detected: Some(1),
|
total_frames_detected: Some(1),
|
||||||
apple_vision_confidence: Some(0.84),
|
apple_vision_confidence: Some(0.84),
|
||||||
mediapipe_confidence: None,
|
mediapipe_confidence: None,
|
||||||
|
|||||||
@@ -2,17 +2,21 @@ use anyhow::{Context, Result};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::core::config::{FACE_FILTER_CONFIDENCE_PCT_DEFAULT, FACE_MIN_SIZE_DEFAULT};
|
||||||
|
|
||||||
/// Version of the file profile schema.
|
/// Version of the file profile schema.
|
||||||
const PROFILE_VERSION: &str = "1.0";
|
const PROFILE_VERSION: &str = "1.0";
|
||||||
|
|
||||||
// ─── Data Types ───
|
// ─── Data Types ───
|
||||||
|
|
||||||
/// Per-file face detection thresholds. `min_confidence` is 0–100 (%),
|
/// 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)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct FaceFilterSettings {
|
pub struct FaceFilterSettings {
|
||||||
pub min_confidence: f64,
|
pub min_confidence: f64,
|
||||||
pub min_size: i32,
|
pub min_size: i32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub min_capture_quality: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FaceFilterSettings {
|
impl FaceFilterSettings {
|
||||||
@@ -20,8 +24,9 @@ impl FaceFilterSettings {
|
|||||||
/// Filter later for display; detect everything first.
|
/// Filter later for display; detect everything first.
|
||||||
pub fn defaults() -> Self {
|
pub fn defaults() -> Self {
|
||||||
Self {
|
Self {
|
||||||
min_confidence: 50.0,
|
min_confidence: FACE_FILTER_CONFIDENCE_PCT_DEFAULT,
|
||||||
min_size: 1,
|
min_size: FACE_MIN_SIZE_DEFAULT,
|
||||||
|
min_capture_quality: 0.0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -378,7 +383,19 @@ pub struct FaceTraceProfile {
|
|||||||
pub frame_count: i64,
|
pub frame_count: i64,
|
||||||
pub start_frame: i64,
|
pub start_frame: i64,
|
||||||
pub end_frame: i64,
|
pub end_frame: i64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub best_frame: Option<i64>,
|
||||||
pub avg_confidence: Option<f64>,
|
pub avg_confidence: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub best_confidence: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub avg_capture_quality: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub best_capture_quality: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub avg_bbox: Option<serde_json::Value>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub best_bbox: Option<serde_json::Value>,
|
||||||
pub key_frame: Option<String>, // filename: key_frame.jpg
|
pub key_frame: Option<String>, // filename: key_frame.jpg
|
||||||
pub key_face: Option<String>, // filename: key_face.jpg
|
pub key_face: Option<String>, // filename: key_face.jpg
|
||||||
pub status: String, // pending / bound / merged
|
pub status: String, // pending / bound / merged
|
||||||
@@ -406,7 +423,13 @@ impl FaceTraceProfile {
|
|||||||
frame_count: i64,
|
frame_count: i64,
|
||||||
start_frame: i64,
|
start_frame: i64,
|
||||||
end_frame: i64,
|
end_frame: i64,
|
||||||
|
best_frame: i64,
|
||||||
avg_confidence: Option<f64>,
|
avg_confidence: Option<f64>,
|
||||||
|
avg_capture_quality: Option<f64>,
|
||||||
|
best_confidence: f64,
|
||||||
|
best_capture_quality: f64,
|
||||||
|
avg_bbox: serde_json::Value,
|
||||||
|
best_bbox: Option<serde_json::Value>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
version: PROFILE_VERSION.to_string(),
|
version: PROFILE_VERSION.to_string(),
|
||||||
@@ -416,7 +439,13 @@ impl FaceTraceProfile {
|
|||||||
frame_count,
|
frame_count,
|
||||||
start_frame,
|
start_frame,
|
||||||
end_frame,
|
end_frame,
|
||||||
|
best_frame: Some(best_frame),
|
||||||
avg_confidence,
|
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_frame: None,
|
||||||
key_face: None,
|
key_face: None,
|
||||||
status: "pending".to_string(),
|
status: "pending".to_string(),
|
||||||
|
|||||||
@@ -107,8 +107,10 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_asr_result_serialization() {
|
fn test_asr_result_serialization() {
|
||||||
let result = AsrResult {
|
let result = AsrResult {
|
||||||
|
status: None,
|
||||||
language: Some("en".to_string()),
|
language: Some("en".to_string()),
|
||||||
language_probability: Some(0.95),
|
language_probability: Some(0.95),
|
||||||
|
segment_count: 2,
|
||||||
segments: vec![
|
segments: vec![
|
||||||
AsrSegment {
|
AsrSegment {
|
||||||
start_time: 0.0,
|
start_time: 0.0,
|
||||||
@@ -116,6 +118,7 @@ mod tests {
|
|||||||
start_frame: Some(0),
|
start_frame: Some(0),
|
||||||
end_frame: Some(60),
|
end_frame: Some(60),
|
||||||
text: "Hello world".to_string(),
|
text: "Hello world".to_string(),
|
||||||
|
confidence: 0.95,
|
||||||
},
|
},
|
||||||
AsrSegment {
|
AsrSegment {
|
||||||
start_time: 2.5,
|
start_time: 2.5,
|
||||||
@@ -123,6 +126,7 @@ mod tests {
|
|||||||
start_frame: Some(60),
|
start_frame: Some(60),
|
||||||
end_frame: Some(120),
|
end_frame: Some(120),
|
||||||
text: "Test speech".to_string(),
|
text: "Test speech".to_string(),
|
||||||
|
confidence: 0.9,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
@@ -157,6 +161,7 @@ mod tests {
|
|||||||
start_frame: Some(0),
|
start_frame: Some(0),
|
||||||
end_frame: Some(24),
|
end_frame: Some(24),
|
||||||
text: String::new(),
|
text: String::new(),
|
||||||
|
confidence: 0.0,
|
||||||
};
|
};
|
||||||
assert_eq!(segment.start_time, 0.0);
|
assert_eq!(segment.start_time, 0.0);
|
||||||
assert_eq!(segment.end_time, 1.0);
|
assert_eq!(segment.end_time, 1.0);
|
||||||
@@ -166,9 +171,11 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_asr_result_empty_segments() {
|
fn test_asr_result_empty_segments() {
|
||||||
let result = AsrResult {
|
let result = AsrResult {
|
||||||
|
status: None,
|
||||||
language: None,
|
language: None,
|
||||||
language_probability: None,
|
language_probability: None,
|
||||||
segments: vec![],
|
segments: vec![],
|
||||||
|
segment_count: 0,
|
||||||
};
|
};
|
||||||
assert!(result.language.is_none());
|
assert!(result.language.is_none());
|
||||||
assert!(result.segments.is_empty());
|
assert!(result.segments.is_empty());
|
||||||
|
|||||||
@@ -214,6 +214,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_asrx_result_serialization() {
|
fn test_asrx_result_serialization() {
|
||||||
let result = AsrxResult {
|
let result = AsrxResult {
|
||||||
|
status: None,
|
||||||
language: Some("en".to_string()),
|
language: Some("en".to_string()),
|
||||||
segments: vec![AsrxSegment {
|
segments: vec![AsrxSegment {
|
||||||
start_time: 0.0,
|
start_time: 0.0,
|
||||||
@@ -227,6 +228,7 @@ mod tests {
|
|||||||
quality: None,
|
quality: None,
|
||||||
}],
|
}],
|
||||||
embeddings: None,
|
embeddings: None,
|
||||||
|
segment_count: 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
let json = serde_json::to_string(&result).unwrap();
|
let json = serde_json::to_string(&result).unwrap();
|
||||||
@@ -255,9 +257,11 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_asrx_result_empty_segments() {
|
fn test_asrx_result_empty_segments() {
|
||||||
let result = AsrxResult {
|
let result = AsrxResult {
|
||||||
|
status: None,
|
||||||
language: None,
|
language: None,
|
||||||
segments: vec![],
|
segments: vec![],
|
||||||
embeddings: None,
|
embeddings: None,
|
||||||
|
segment_count: 0,
|
||||||
};
|
};
|
||||||
assert!(result.segments.is_empty());
|
assert!(result.segments.is_empty());
|
||||||
assert!(result.language.is_none());
|
assert!(result.language.is_none());
|
||||||
|
|||||||
@@ -53,6 +53,8 @@ pub struct Face {
|
|||||||
pub width: i32,
|
pub width: i32,
|
||||||
pub height: i32,
|
pub height: i32,
|
||||||
pub confidence: f32,
|
pub confidence: f32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub capture_quality: Option<f32>,
|
||||||
pub embedding: Option<Vec<f32>>,
|
pub embedding: Option<Vec<f32>>,
|
||||||
pub landmarks: Option<serde_json::Value>,
|
pub landmarks: Option<serde_json::Value>,
|
||||||
pub pose_angle: Option<serde_json::Value>,
|
pub pose_angle: Option<serde_json::Value>,
|
||||||
@@ -148,8 +150,10 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_face_result_serialization() {
|
fn test_face_result_serialization() {
|
||||||
let result = FaceResult {
|
let result = FaceResult {
|
||||||
|
status: None,
|
||||||
frame_count: 100,
|
frame_count: 100,
|
||||||
fps: 30.0,
|
fps: 30.0,
|
||||||
|
total_faces: 1,
|
||||||
frames: vec![FaceFrame {
|
frames: vec![FaceFrame {
|
||||||
frame: 0,
|
frame: 0,
|
||||||
timestamp: 0.0,
|
timestamp: 0.0,
|
||||||
@@ -160,6 +164,7 @@ mod tests {
|
|||||||
width: 50,
|
width: 50,
|
||||||
height: 60,
|
height: 60,
|
||||||
confidence: 0.95,
|
confidence: 0.95,
|
||||||
|
capture_quality: Some(0.9),
|
||||||
embedding: Some(vec![0.1, 0.2, 0.3]),
|
embedding: Some(vec![0.1, 0.2, 0.3]),
|
||||||
landmarks: Some(serde_json::json!([[10.0, 20.0], [30.0, 40.0]])),
|
landmarks: Some(serde_json::json!([[10.0, 20.0], [30.0, 40.0]])),
|
||||||
pose_angle: None,
|
pose_angle: None,
|
||||||
@@ -216,9 +221,11 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_face_result_empty_frames() {
|
fn test_face_result_empty_frames() {
|
||||||
let result = FaceResult {
|
let result = FaceResult {
|
||||||
|
status: None,
|
||||||
frame_count: 0,
|
frame_count: 0,
|
||||||
fps: 0.0,
|
fps: 0.0,
|
||||||
frames: vec![],
|
frames: vec![],
|
||||||
|
total_faces: 0,
|
||||||
};
|
};
|
||||||
assert!(result.frames.is_empty());
|
assert!(result.frames.is_empty());
|
||||||
}
|
}
|
||||||
@@ -232,6 +239,7 @@ mod tests {
|
|||||||
width: 10,
|
width: 10,
|
||||||
height: 10,
|
height: 10,
|
||||||
confidence: 0.5,
|
confidence: 0.5,
|
||||||
|
capture_quality: None,
|
||||||
embedding: None,
|
embedding: None,
|
||||||
landmarks: None,
|
landmarks: None,
|
||||||
pose_angle: None,
|
pose_angle: None,
|
||||||
@@ -249,6 +257,7 @@ mod tests {
|
|||||||
width: 50,
|
width: 50,
|
||||||
height: 60,
|
height: 60,
|
||||||
confidence: 0.95,
|
confidence: 0.95,
|
||||||
|
capture_quality: Some(0.8),
|
||||||
embedding: Some(vec![0.1; 512]),
|
embedding: Some(vec![0.1; 512]),
|
||||||
landmarks: None,
|
landmarks: None,
|
||||||
pose_angle: None,
|
pose_angle: None,
|
||||||
|
|||||||
+73
-10
@@ -20,6 +20,7 @@ struct FacePoint {
|
|||||||
w: f64,
|
w: f64,
|
||||||
h: f64,
|
h: f64,
|
||||||
confidence: f64,
|
confidence: f64,
|
||||||
|
capture_quality: f64,
|
||||||
point_id: Option<String>,
|
point_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,6 +122,7 @@ fn parse_face_points(points: Vec<serde_json::Value>) -> Vec<FacePoint> {
|
|||||||
w,
|
w,
|
||||||
h,
|
h,
|
||||||
confidence: payload["confidence"].as_f64().unwrap_or(0.5),
|
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()),
|
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_w: f64,
|
||||||
sum_h: f64,
|
sum_h: f64,
|
||||||
sum_confidence: f64,
|
sum_confidence: f64,
|
||||||
|
sum_capture_quality: f64,
|
||||||
frames: Vec<(i64, f64, f64, f64, f64)>, // (frame, x, y, w, h)
|
frames: Vec<(i64, f64, f64, f64, f64)>, // (frame, x, y, w, h)
|
||||||
best_frame: i64,
|
best_frame: i64,
|
||||||
best_confidence: f64,
|
best_confidence: f64,
|
||||||
best_point_id: Option<String>,
|
best_point_id: Option<String>,
|
||||||
|
cq_best_frame: i64,
|
||||||
|
cq_best_quality: f64,
|
||||||
|
cq_best_point_id: Option<String>,
|
||||||
|
cq_best_bbox: Option<serde_json::Value>,
|
||||||
|
best_bbox: Option<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut traces: HashMap<i64, TraceAgg> = HashMap::new();
|
let mut traces: HashMap<i64, TraceAgg> = HashMap::new();
|
||||||
@@ -1151,10 +1159,16 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
sum_w: 0.0,
|
sum_w: 0.0,
|
||||||
sum_h: 0.0,
|
sum_h: 0.0,
|
||||||
sum_confidence: 0.0,
|
sum_confidence: 0.0,
|
||||||
|
sum_capture_quality: 0.0,
|
||||||
frames: vec![],
|
frames: vec![],
|
||||||
best_frame: 0,
|
best_frame: 0,
|
||||||
best_confidence: 0.0,
|
best_confidence: 0.0,
|
||||||
best_point_id: None,
|
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.frame_count += 1;
|
||||||
entry.start_f = entry.start_f.min(p.frame);
|
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_w += p.w;
|
||||||
entry.sum_h += p.h;
|
entry.sum_h += p.h;
|
||||||
entry.sum_confidence += p.confidence;
|
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));
|
entry.frames.push((p.frame, p.x, p.y, p.w, p.h));
|
||||||
// Track best face (highest confidence)
|
// Track best face (highest confidence)
|
||||||
if p.confidence > entry.best_confidence {
|
if p.confidence > entry.best_confidence {
|
||||||
entry.best_confidence = p.confidence;
|
entry.best_confidence = p.confidence;
|
||||||
entry.best_frame = p.frame;
|
entry.best_frame = p.frame;
|
||||||
entry.best_point_id = p.point_id.clone();
|
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
|
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!({
|
let props = serde_json::json!({
|
||||||
"trace_id": tid,
|
"trace_id": tid,
|
||||||
"frame_count": agg.frame_count,
|
"frame_count": agg.frame_count,
|
||||||
"start_frame": agg.start_f,
|
"start_frame": agg.start_f,
|
||||||
"end_frame": agg.end_f,
|
"end_frame": agg.end_f,
|
||||||
"key_frame": agg.best_frame,
|
"key_frame": agg.cq_best_frame,
|
||||||
"key_face": agg.best_point_id.as_deref().unwrap_or(""),
|
"key_face": agg.cq_best_point_id.as_deref().unwrap_or(""),
|
||||||
"avg_bbox": {
|
"avg_bbox": {
|
||||||
"x": (agg.sum_x / agg.frame_count as f64).round() as i64,
|
"x": (agg.sum_x / agg.frame_count as f64).round() as i64,
|
||||||
"y": (agg.sum_y / 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,
|
"width": (agg.sum_w / agg.frame_count as f64).round() as i64,
|
||||||
"height": (agg.sum_h / 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_yaw": (avg_yaw * 1000.0).round() / 1000.0,
|
||||||
"avg_pitch": (avg_pitch * 1000.0).round() / 1000.0,
|
"avg_pitch": (avg_pitch * 1000.0).round() / 1000.0,
|
||||||
"avg_roll": (avg_roll * 1000.0).round() / 1000.0,
|
"avg_roll": (avg_roll * 1000.0).round() / 1000.0,
|
||||||
"pose_count": pose_count,
|
"pose_count": pose_count,
|
||||||
"avg_confidence": (avg_confidence * 1000.0).round() / 1000.0,
|
"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",
|
"status": "pending",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1277,13 +1320,19 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
agg.frame_count,
|
agg.frame_count,
|
||||||
agg.start_f,
|
agg.start_f,
|
||||||
agg.end_f,
|
agg.end_f,
|
||||||
|
agg.cq_best_frame,
|
||||||
Some(avg_confidence),
|
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
|
// Extract key_frame JPEG bytes via ffmpeg pipe
|
||||||
// Use select=eq(n\,frame) for VFR compatibility (decoded index, not time-based)
|
// Use select=eq(n\,frame) for VFR compatibility (decoded index, not time-based)
|
||||||
let key_frame_jpeg: Option<Vec<u8>> = video_path.as_ref().and_then(|vp| {
|
let key_frame_jpeg: Option<Vec<u8>> = 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")
|
let output = std::process::Command::new("ffmpeg")
|
||||||
.args(["-y", "-v", "quiet", "-i"])
|
.args(["-y", "-v", "quiet", "-i"])
|
||||||
.arg(vp)
|
.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<Vec<u8>> = key_frame_jpeg.as_ref().and_then(|kf| {
|
let key_face_jpeg: Option<Vec<u8>> = 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
|
let (bf, bx, by, bw, bh) = agg
|
||||||
.frames
|
.frames
|
||||||
.iter()
|
.iter()
|
||||||
.find(|(f, _, _, _, _)| *f == agg.best_frame)?;
|
.find(|(f, _, _, _, _)| *f == agg.cq_best_frame)?;
|
||||||
let (bx, by, bw, bh) = (*bx, *by, *bw, *bh);
|
let (bx, by, bw, bh) = (*bx, *by, *bw, *bh);
|
||||||
|
|
||||||
// Validate bbox: must have positive dimensions
|
// 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}/
|
// Save all three files to output/{file_uuid}/{trace_id}/
|
||||||
let mut key_frame_file = agg.best_frame.to_string();
|
let mut key_frame_file = agg.cq_best_frame.to_string();
|
||||||
let mut key_face_file = agg.best_point_id.as_deref().unwrap_or("").to_string();
|
let mut key_face_file = agg.cq_best_point_id.as_deref().unwrap_or("").to_string();
|
||||||
|
|
||||||
match trace_profile.save(
|
match trace_profile.save(
|
||||||
output_dir,
|
output_dir,
|
||||||
@@ -1416,7 +1465,7 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
|
|
||||||
if need_retry {
|
if need_retry {
|
||||||
if let Some(ref vp) = video_path {
|
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
|
// Retry key_frame extraction
|
||||||
if !kf_path.exists() {
|
if !kf_path.exists() {
|
||||||
if let Ok(output) = std::process::Command::new("ffmpeg")
|
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
|
let (_, bx, by, bw, bh) = agg
|
||||||
.frames
|
.frames
|
||||||
.iter()
|
.iter()
|
||||||
.find(|(f, _, _, _, _)| *f == agg.best_frame)
|
.find(|(f, _, _, _, _)| *f == agg.cq_best_frame)
|
||||||
.cloned()
|
.cloned()
|
||||||
.unwrap_or((0, 0.0, 0.0, 100.0, 100.0));
|
.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_frame": key_frame_file,
|
||||||
"key_face": key_face_file,
|
"key_face": key_face_file,
|
||||||
"avg_bbox": props["avg_bbox"].clone(),
|
"avg_bbox": props["avg_bbox"].clone(),
|
||||||
|
"best_bbox": props["best_bbox"].clone(),
|
||||||
"avg_yaw": props["avg_yaw"].clone(),
|
"avg_yaw": props["avg_yaw"].clone(),
|
||||||
"avg_pitch": props["avg_pitch"].clone(),
|
"avg_pitch": props["avg_pitch"].clone(),
|
||||||
"avg_roll": props["avg_roll"].clone(),
|
"avg_roll": props["avg_roll"].clone(),
|
||||||
"pose_count": pose_count,
|
"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",
|
"status": "pending",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -3601,6 +3655,7 @@ mod tests {
|
|||||||
w: 50.0,
|
w: 50.0,
|
||||||
h: 50.0,
|
h: 50.0,
|
||||||
confidence: 0.9,
|
confidence: 0.9,
|
||||||
|
capture_quality: 0.0,
|
||||||
point_id: None,
|
point_id: None,
|
||||||
},
|
},
|
||||||
FacePoint {
|
FacePoint {
|
||||||
@@ -3611,6 +3666,7 @@ mod tests {
|
|||||||
w: 50.0,
|
w: 50.0,
|
||||||
h: 50.0,
|
h: 50.0,
|
||||||
confidence: 0.9,
|
confidence: 0.9,
|
||||||
|
capture_quality: 0.0,
|
||||||
point_id: None,
|
point_id: None,
|
||||||
},
|
},
|
||||||
FacePoint {
|
FacePoint {
|
||||||
@@ -3621,6 +3677,7 @@ mod tests {
|
|||||||
w: 50.0,
|
w: 50.0,
|
||||||
h: 50.0,
|
h: 50.0,
|
||||||
confidence: 0.9,
|
confidence: 0.9,
|
||||||
|
capture_quality: 0.0,
|
||||||
point_id: None,
|
point_id: None,
|
||||||
},
|
},
|
||||||
FacePoint {
|
FacePoint {
|
||||||
@@ -3631,6 +3688,7 @@ mod tests {
|
|||||||
w: 50.0,
|
w: 50.0,
|
||||||
h: 50.0,
|
h: 50.0,
|
||||||
confidence: 0.9,
|
confidence: 0.9,
|
||||||
|
capture_quality: 0.0,
|
||||||
point_id: None,
|
point_id: None,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -3661,6 +3719,7 @@ mod tests {
|
|||||||
w: 100.0,
|
w: 100.0,
|
||||||
h: 100.0,
|
h: 100.0,
|
||||||
confidence: 0.9,
|
confidence: 0.9,
|
||||||
|
capture_quality: 0.0,
|
||||||
point_id: None,
|
point_id: None,
|
||||||
},
|
},
|
||||||
FacePoint {
|
FacePoint {
|
||||||
@@ -3671,6 +3730,7 @@ mod tests {
|
|||||||
w: 100.0,
|
w: 100.0,
|
||||||
h: 100.0,
|
h: 100.0,
|
||||||
confidence: 0.9,
|
confidence: 0.9,
|
||||||
|
capture_quality: 0.0,
|
||||||
point_id: None,
|
point_id: None,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -3692,6 +3752,7 @@ mod tests {
|
|||||||
w: 100.0,
|
w: 100.0,
|
||||||
h: 100.0,
|
h: 100.0,
|
||||||
confidence: 0.9,
|
confidence: 0.9,
|
||||||
|
capture_quality: 0.0,
|
||||||
point_id: None,
|
point_id: None,
|
||||||
},
|
},
|
||||||
FacePoint {
|
FacePoint {
|
||||||
@@ -3702,6 +3763,7 @@ mod tests {
|
|||||||
w: 100.0,
|
w: 100.0,
|
||||||
h: 100.0,
|
h: 100.0,
|
||||||
confidence: 0.9,
|
confidence: 0.9,
|
||||||
|
capture_quality: 0.0,
|
||||||
point_id: None,
|
point_id: None,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -3722,6 +3784,7 @@ mod tests {
|
|||||||
w: 100.0,
|
w: 100.0,
|
||||||
h: 100.0,
|
h: 100.0,
|
||||||
confidence: 0.9,
|
confidence: 0.9,
|
||||||
|
capture_quality: 0.0,
|
||||||
point_id: None,
|
point_id: None,
|
||||||
}];
|
}];
|
||||||
let index = build_frame_index(&points);
|
let index = build_frame_index(&points);
|
||||||
|
|||||||
@@ -21,7 +21,9 @@ static FACE_TRACE_INFLIGHT: LazyLock<tokio::sync::Mutex<std::collections::HashSe
|
|||||||
LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
|
LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
|
||||||
|
|
||||||
use crate::core::chunk::rule1_ingest;
|
use crate::core::chunk::rule1_ingest;
|
||||||
use crate::core::config::OUTPUT_DIR;
|
use crate::core::config::{
|
||||||
|
FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT, OUTPUT_DIR,
|
||||||
|
};
|
||||||
use crate::core::db::qdrant_db::QdrantDb;
|
use crate::core::db::qdrant_db::QdrantDb;
|
||||||
use crate::core::db::{
|
use crate::core::db::{
|
||||||
schema, MonitorJobStatus, PostgresDb, ProcessorJobStatus, RedisClient, VectorPayload,
|
schema, MonitorJobStatus, PostgresDb, ProcessorJobStatus, RedisClient, VectorPayload,
|
||||||
@@ -464,8 +466,14 @@ impl JobWorker {
|
|||||||
// Read face_settings from job and set environment variables for face processor
|
// Read face_settings from job and set environment variables for face processor
|
||||||
let mut face_settings_backup: Option<(String, String)> = None;
|
let mut face_settings_backup: Option<(String, String)> = None;
|
||||||
if let Some(ref fs) = job.face_settings {
|
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_confidence = fs
|
||||||
let min_size = fs.get("min_size").and_then(|v| v.as_i64()).unwrap_or(1) as i32;
|
.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!(
|
tracing::info!(
|
||||||
"[WORKER] Job {} face_settings: CONFIDENCE={}, SIZE={}",
|
"[WORKER] Job {} face_settings: CONFIDENCE={}, SIZE={}",
|
||||||
job.uuid,
|
job.uuid,
|
||||||
|
|||||||
Reference in New Issue
Block a user