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.. bestOverlap { bestOverlap = overlap if let cq = cqObs.faceCaptureQuality { captureQ = Double(cq) } } } // 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) } } } 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..