feat: face clustering pipeline improvements and Rust/Swift face processing
- Add Rust face processor module (detection, embedding, tracking, qdrant) - Add Facenet CoreML/ONNX conversion scripts and tests - Refactor swift_face into Sources/swift_face with ArgumentParser support - Update store_traced_faces to handle face.json correctly - Fix ASRX parsing and TKG bbox reading from Qdrant - Improve admin_config and trace_agent APIs - Add M4 workspace docs for face clustering, dedup, and Facenet validation - Fix worker heartbeat TTL (poll_interval x 3, min 60s) for offline detection
This commit is contained in:
@@ -0,0 +1,402 @@
|
||||
import Foundation
|
||||
import Vision
|
||||
import ArgumentParser
|
||||
import AVFoundation
|
||||
|
||||
/// Swift Face Processor - Apple Vision Framework for face detection + pose
|
||||
/// Uses AVAssetImageGenerator for reliable frame access (no AVAssetReader corruption).
|
||||
@main
|
||||
struct SwiftFace: ParsableCommand {
|
||||
@Argument(help: "Video file path")
|
||||
var inputPath: String
|
||||
|
||||
@Argument(help: "Output JSON path")
|
||||
var outputPath: String
|
||||
|
||||
@Option(name: .long, help: "Sample interval (frames, default=3)")
|
||||
var sampleInterval: Int = 3
|
||||
|
||||
@Option(name: .long, help: "UUID for logging")
|
||||
var uuid: String = ""
|
||||
|
||||
mutating func run() throws {
|
||||
let startTime = Date()
|
||||
print("[SwiftFace] Vision-based face detection: \(inputPath)")
|
||||
|
||||
let url = URL(fileURLWithPath: inputPath)
|
||||
let asset = AVAsset(url: url)
|
||||
|
||||
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
|
||||
print("[SwiftFace] No video track found")
|
||||
return
|
||||
}
|
||||
|
||||
let fps = videoTrack.nominalFrameRate
|
||||
let duration = CMTimeGetSeconds(asset.duration)
|
||||
let totalFrames = Int(duration * Double(fps))
|
||||
let width = Int(videoTrack.naturalSize.width)
|
||||
let height = Int(videoTrack.naturalSize.height)
|
||||
print("[SwiftFace] Video: \(width)x\(height), \(String(format: "%.1f", fps))fps, \(totalFrames) frames")
|
||||
|
||||
// Read face detection settings from environment variables (with defaults)
|
||||
// Keep in sync with src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT
|
||||
let MIN_CONFIDENCE = Double(ProcessInfo.processInfo.environment["FACE_MIN_CONFIDENCE"] ?? "0.5") ?? 0.5
|
||||
let MIN_SIZE = Int(ProcessInfo.processInfo.environment["FACE_MIN_SIZE"] ?? "1") ?? 1
|
||||
print("[SwiftFace] Settings: MIN_CONFIDENCE=\(MIN_CONFIDENCE), MIN_SIZE=\(MIN_SIZE)")
|
||||
|
||||
let generator = AVAssetImageGenerator(asset: asset)
|
||||
generator.requestedTimeToleranceBefore = .zero
|
||||
generator.requestedTimeToleranceAfter = .zero
|
||||
generator.appliesPreferredTrackTransform = true
|
||||
|
||||
var allFrames: [[String: Any]] = []
|
||||
var processedCount = 0
|
||||
var checkedCount = 0
|
||||
|
||||
let frameInterval = TimeInterval(sampleInterval) / Double(fps)
|
||||
|
||||
// Process in batches of 1000 frames to avoid memory pressure
|
||||
let batchSize = 1000
|
||||
let totalSamples = totalFrames / sampleInterval
|
||||
|
||||
for batchStart in stride(from: 0, to: totalSamples, by: batchSize) {
|
||||
let batchEnd = min(batchStart + batchSize, totalSamples)
|
||||
var times: [NSValue] = []
|
||||
|
||||
for i in batchStart..<batchEnd {
|
||||
let seconds = Double(i) * frameInterval
|
||||
let cmTime = CMTime(seconds: seconds, preferredTimescale: 1000)
|
||||
times.append(NSValue(time: cmTime))
|
||||
}
|
||||
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var batchError: Error? = nil
|
||||
|
||||
generator.generateCGImagesAsynchronously(forTimes: times) { requestedTime, cgImage, actualTime, result, error in
|
||||
defer { semaphore.signal() }
|
||||
|
||||
checkedCount += 1
|
||||
|
||||
guard result == .succeeded, let cgImage = cgImage else {
|
||||
if let error = error {
|
||||
fputs("[SwiftFace] Frame error at \(CMTimeGetSeconds(requestedTime)): \(error.localizedDescription)\n", stderr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Convert CGImage to CVPixelBuffer for Vision
|
||||
var pixelBuffer: CVPixelBuffer?
|
||||
let attrs: [CFString: Any] = [
|
||||
kCVPixelBufferCGImageCompatibilityKey: true,
|
||||
kCVPixelBufferCGBitmapContextCompatibilityKey: true,
|
||||
kCVPixelBufferWidthKey: cgImage.width,
|
||||
kCVPixelBufferHeightKey: cgImage.height,
|
||||
]
|
||||
CVPixelBufferCreate(kCFAllocatorDefault, cgImage.width, cgImage.height,
|
||||
kCVPixelFormatType_32BGRA, attrs as CFDictionary, &pixelBuffer)
|
||||
|
||||
guard let pb = pixelBuffer else { return }
|
||||
|
||||
CVPixelBufferLockBaseAddress(pb, [])
|
||||
defer { CVPixelBufferUnlockBaseAddress(pb, []) }
|
||||
|
||||
let context = CGContext(data: CVPixelBufferGetBaseAddress(pb),
|
||||
width: cgImage.width, height: cgImage.height,
|
||||
bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pb),
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)!
|
||||
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height))
|
||||
|
||||
let handler = VNImageRequestHandler(cvPixelBuffer: pb, options: [:])
|
||||
let detectReq = VNDetectFaceRectanglesRequest()
|
||||
let lmReq = VNDetectFaceLandmarksRequest()
|
||||
let captureQReq = VNDetectFaceCaptureQualityRequest()
|
||||
|
||||
do {
|
||||
try handler.perform([detectReq, lmReq, captureQReq])
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
let faceObservations = detectReq.results ?? []
|
||||
let landmarkObservations = lmReq.results ?? []
|
||||
let captureQualityObs = captureQReq.results ?? []
|
||||
guard !faceObservations.isEmpty || !landmarkObservations.isEmpty else {
|
||||
return
|
||||
}
|
||||
|
||||
let seconds = CMTimeGetSeconds(actualTime)
|
||||
let frameNumber = Int((seconds * Double(fps)).rounded())
|
||||
var frameFaces: [[String: Any]] = []
|
||||
|
||||
// Use actual CGImage size (may differ from naturalSize after transform)
|
||||
let imgW = CGFloat(cgImage.width)
|
||||
let imgH = CGFloat(cgImage.height)
|
||||
|
||||
// Process landmark observations FIRST (each has bbox + landmarks, self-consistent)
|
||||
// Quality filtering - uses MIN_CONFIDENCE and MIN_SIZE from outer scope
|
||||
|
||||
for lmObs in landmarkObservations {
|
||||
// Confidence filter
|
||||
let lmConf = Double(lmObs.confidence)
|
||||
if lmConf < MIN_CONFIDENCE { continue }
|
||||
|
||||
let bb = lmObs.boundingBox
|
||||
let faceW = Int(bb.size.width * imgW)
|
||||
let faceH = Int(bb.size.height * imgH)
|
||||
|
||||
// Size filter
|
||||
if faceW < MIN_SIZE || faceH < MIN_SIZE { continue }
|
||||
|
||||
let faceX = Int(bb.origin.x * imgW)
|
||||
let faceY = Int((1.0 - bb.origin.y - bb.size.height) * imgH)
|
||||
|
||||
// Match capture quality request by bbox overlap (landmarks request
|
||||
// results don't populate faceCaptureQuality on macOS)
|
||||
var captureQ = 0.0
|
||||
var bestOverlap: CGFloat = 0
|
||||
for cqObs in captureQualityObs {
|
||||
let cb = cqObs.boundingBox
|
||||
let ix = max(bb.minX, cb.minX)
|
||||
let iy = max(bb.minY, cb.minY)
|
||||
let iw = min(bb.maxX, cb.maxX) - ix
|
||||
let ih = min(bb.maxY, cb.maxY) - iy
|
||||
if iw <= 0 || ih <= 0 { continue }
|
||||
let overlap = (iw * ih) / (bb.width * bb.height)
|
||||
if overlap > bestOverlap {
|
||||
bestOverlap = overlap
|
||||
if let cq = cqObs.faceCaptureQuality {
|
||||
captureQ = Double(cq)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Calculate quality from size, confidence, pose if API didn't provide it
|
||||
if captureQ == 0.0 {
|
||||
let faceArea = Double(faceW * faceH)
|
||||
let imgArea = Double(imgW * imgH)
|
||||
let sizeScore = min(1.0, (faceArea / imgArea) * 4.0) // Normalize, larger = better
|
||||
let confScore = lmConf // Already 0-1
|
||||
|
||||
// Pose score (frontal = 1.0, profile = 0.0)
|
||||
var poseScore = 1.0
|
||||
if let yaw = lmObs.yaw?.doubleValue {
|
||||
poseScore = max(0.0, 1.0 - abs(yaw) / 90.0)
|
||||
}
|
||||
|
||||
// Weighted combination
|
||||
captureQ = sizeScore * 0.3 + confScore * 0.4 + poseScore * 0.3
|
||||
}
|
||||
|
||||
// Match face observation by bbox to extract faceprint (embedding)
|
||||
var embedding: [Float]? = nil
|
||||
if #available(macOS 14, *) {
|
||||
var matchCount = 0
|
||||
for faceObs in faceObservations {
|
||||
let fBB = faceObs.boundingBox
|
||||
let ix = max(bb.minX, fBB.origin.x)
|
||||
let iy = max(bb.minY, fBB.origin.y)
|
||||
let iw = min(bb.maxX, fBB.origin.x + fBB.width) - ix
|
||||
let ih = min(bb.maxY, fBB.origin.y + fBB.height) - iy
|
||||
if iw <= 0 || ih <= 0 { continue }
|
||||
let intersection = iw * ih
|
||||
let union = bb.width * bb.height + fBB.width * fBB.height - intersection
|
||||
if intersection / union > 0.5 {
|
||||
matchCount += 1
|
||||
// Try to extract faceprint
|
||||
if let fp = faceObs.value(forKey: "faceprint") as? NSObject {
|
||||
if let desc = fp.value(forKey: "descriptor") as? NSObject {
|
||||
if let elems = desc.value(forKey: "elements") as? [NSNumber] {
|
||||
embedding = elems.map { Float($0.doubleValue) }
|
||||
} else {
|
||||
print("[DEBUG] No elements in descriptor")
|
||||
}
|
||||
} else {
|
||||
print("[DEBUG] No descriptor in faceprint")
|
||||
}
|
||||
} else {
|
||||
print("[DEBUG] No faceprint in faceObs (frame \(frameNumber), match \(matchCount))")
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var faceData: [String: Any] = [
|
||||
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
|
||||
"width": faceW, "height": faceH],
|
||||
"confidence": Double(lmObs.confidence),
|
||||
"captureQuality": captureQ,
|
||||
]
|
||||
|
||||
// Add embedding if available
|
||||
if let emb = embedding {
|
||||
faceData["embedding"] = emb
|
||||
}
|
||||
|
||||
// Pose from landmark observation
|
||||
if let yaw = lmObs.yaw?.doubleValue,
|
||||
let roll = lmObs.roll?.doubleValue {
|
||||
var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw]
|
||||
if let pitch = lmObs.pitch?.doubleValue {
|
||||
poseInfo["pitch"] = pitch
|
||||
}
|
||||
faceData["pose"] = poseInfo
|
||||
}
|
||||
|
||||
// Landmarks with Y-flip (macOS image coords: bottom-left -> top-left)
|
||||
if let lms = lmObs.landmarks {
|
||||
let imgSize = CGSize(width: imgW, height: imgH)
|
||||
let leftEye = lms.leftEye?.pointsInImage(imageSize: imgSize) ?? []
|
||||
let rightEye = lms.rightEye?.pointsInImage(imageSize: imgSize) ?? []
|
||||
let nose = lms.nose?.pointsInImage(imageSize: imgSize) ?? []
|
||||
|
||||
if !leftEye.isEmpty || !rightEye.isEmpty || !nose.isEmpty {
|
||||
var lm: [String: [[Double]]] = [:]
|
||||
if !leftEye.isEmpty {
|
||||
lm["left_eye"] = leftEye.map { [Double($0.x), Double(imgH - $0.y)] }
|
||||
}
|
||||
if !rightEye.isEmpty {
|
||||
lm["right_eye"] = rightEye.map { [Double($0.x), Double(imgH - $0.y)] }
|
||||
}
|
||||
if !nose.isEmpty {
|
||||
lm["nose"] = nose.map { [Double($0.x), Double(imgH - $0.y)] }
|
||||
}
|
||||
faceData["landmarks"] = lm
|
||||
}
|
||||
|
||||
let outer = lms.outerLips?.pointsInImage(imageSize: imgSize) ?? []
|
||||
let inner = lms.innerLips?.pointsInImage(imageSize: imgSize) ?? []
|
||||
if !outer.isEmpty || !inner.isEmpty {
|
||||
faceData["lips"] = [
|
||||
"outer_lips": outer.map { [Double($0.x), Double(imgH - $0.y)] },
|
||||
"inner_lips": inner.map { [Double($0.x), Double(imgH - $0.y)] }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
frameFaces.append(faceData)
|
||||
}
|
||||
|
||||
// Output face rect observations that the landmark detector missed.
|
||||
// Match against ALL landmark observations via IoU to avoid duplicates.
|
||||
for faceObs in faceObservations {
|
||||
let fBB = faceObs.boundingBox
|
||||
var matched = false
|
||||
for lmObs in landmarkObservations {
|
||||
let lBB = lmObs.boundingBox
|
||||
let ix = max(fBB.origin.x, lBB.origin.x)
|
||||
let iy = max(fBB.origin.y, lBB.origin.y)
|
||||
let iw = min(fBB.maxX, lBB.maxX) - ix
|
||||
let ih = min(fBB.maxY, lBB.maxY) - iy
|
||||
if iw <= 0 || ih <= 0 { continue }
|
||||
let intersection = iw * ih
|
||||
let union = fBB.width * fBB.height + lBB.width * lBB.height - intersection
|
||||
if intersection / union > 0.3 {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched { continue }
|
||||
|
||||
// Quality filtering for unmatched face rects
|
||||
|
||||
if Double(faceObs.confidence) < MIN_CONFIDENCE { continue }
|
||||
|
||||
let faceW = Int(fBB.size.width * imgW)
|
||||
let faceH = Int(fBB.size.height * imgH)
|
||||
if faceW < MIN_SIZE || faceH < MIN_SIZE { continue }
|
||||
|
||||
// Unmatched face rect: output without landmarks
|
||||
let faceX = Int(fBB.origin.x * imgW)
|
||||
let faceY = Int((1.0 - fBB.origin.y - fBB.size.height) * imgH)
|
||||
|
||||
// Match capture quality request by bbox overlap
|
||||
var captureQ = 0.0
|
||||
var bestOverlap: CGFloat = 0
|
||||
for cqObs in captureQualityObs {
|
||||
let cb = cqObs.boundingBox
|
||||
let ix = max(fBB.minX, cb.minX)
|
||||
let iy = max(fBB.minY, cb.minY)
|
||||
let iw = min(fBB.maxX, cb.maxX) - ix
|
||||
let ih = min(fBB.maxY, cb.maxY) - iy
|
||||
if iw <= 0 || ih <= 0 { continue }
|
||||
let overlap = (iw * ih) / (fBB.width * fBB.height)
|
||||
if overlap > bestOverlap {
|
||||
bestOverlap = overlap
|
||||
if let cq = cqObs.faceCaptureQuality {
|
||||
captureQ = Double(cq)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Calculate quality from size and confidence if API didn't provide it
|
||||
if captureQ == 0.0 {
|
||||
let faceArea = Double(faceW * faceH)
|
||||
let imgArea = Double(imgW * imgH)
|
||||
let sizeScore = min(1.0, (faceArea / imgArea) * 4.0) // Normalize, larger = better
|
||||
let confScore = Double(faceObs.confidence) // Already 0-1
|
||||
|
||||
// Weighted combination (no pose available for unmatched faces)
|
||||
captureQ = sizeScore * 0.5 + confScore * 0.5
|
||||
}
|
||||
|
||||
var faceData: [String: Any] = [
|
||||
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
|
||||
"width": faceW, "height": faceH],
|
||||
"confidence": Double(faceObs.confidence),
|
||||
"captureQuality": captureQ,
|
||||
]
|
||||
if let yaw = faceObs.yaw?.doubleValue,
|
||||
let roll = faceObs.roll?.doubleValue {
|
||||
var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw]
|
||||
if let pitch = faceObs.pitch?.doubleValue {
|
||||
poseInfo["pitch"] = pitch
|
||||
}
|
||||
faceData["pose"] = poseInfo
|
||||
}
|
||||
frameFaces.append(faceData)
|
||||
}
|
||||
|
||||
if !frameFaces.isEmpty {
|
||||
allFrames.append([
|
||||
"frame": frameNumber,
|
||||
"timestamp": seconds,
|
||||
"faces": frameFaces,
|
||||
])
|
||||
processedCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for batch to complete
|
||||
for _ in batchStart..<batchEnd {
|
||||
semaphore.wait()
|
||||
}
|
||||
|
||||
let elapsed = Date().timeIntervalSince(startTime)
|
||||
let pct = Int(Double(min(batchEnd, totalSamples)) / Double(totalSamples) * 100)
|
||||
print("[SwiftFace] \(processedCount) frames with faces, \(pct)% complete, \(Int(elapsed))s elapsed")
|
||||
fflush(stdout)
|
||||
}
|
||||
|
||||
generator.cancelAllCGImageGeneration()
|
||||
|
||||
let output: [String: Any] = [
|
||||
"frame_count": allFrames.count,
|
||||
"fps": Double(fps),
|
||||
"frames": allFrames,
|
||||
]
|
||||
|
||||
guard let jsonData = try? JSONSerialization.data(withJSONObject: output, options: []),
|
||||
let jsonString = String(data: jsonData, encoding: .utf8) else {
|
||||
print("[SwiftFace] Failed to serialize JSON")
|
||||
return
|
||||
}
|
||||
|
||||
let outputURL = URL(fileURLWithPath: outputPath)
|
||||
try jsonString.write(to: outputURL, atomically: false, encoding: .utf8)
|
||||
|
||||
let elapsed = Date().timeIntervalSince(startTime)
|
||||
print("[SwiftFace] Done: \(allFrames.count) frames, \(String(format: "%.1f", elapsed))s → \(outputPath)")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user