Files
momentry_core/tools/cli/swift/facenet_embedding.swift
T
Accusys af028ab8f4 feat: restructure tools directory
新結構:
- tools/script/ (Python 處理器腳本)
- tools/cli/ (Swift/Rust CLI 工具)

遷移內容:
- Python 腳本: ASR, Face, Pose, Cut, OCR, VLM, Embedding, Identity
- Swift CLI: 24 個 Swift 處理器和測試文件
- Rust CLI: Face Cluster, Appearance, Pose

保留向後兼容:
- 舊路徑 scripts/ 仍然存在
- 環境變數可配置新路徑

文檔:
- tools/README.md
- docs_v1.0/DESIGN/Tools_Directory_Restructure.md
2026-09-27 12:04:23 +08:00

192 lines
8.1 KiB
Swift

import Foundation
import Vision
import CoreML
import ArgumentParser
import AVFoundation
/// FaceNet CoreML Embedding Generator
/// Reads face.json, extracts face regions, generates 512-dim embeddings via FaceNet
@main
struct FaceNetEmbedding: ParsableCommand {
@Argument(help: "Video file path")
var videoPath: String
@Argument(help: "Input face.json path")
var inputPath: String
@Argument(help: "Output face.json path")
var outputPath: String
@Option(name: .long, help: "UUID for logging")
var uuid: String = ""
mutating func run() throws {
let startTime = Date()
print("[FaceNet] Loading FaceNet CoreML model...")
// Load FaceNet CoreML model
let modelURL = URL(fileURLWithPath: "/Users/accusys/momentry_core/models/facenet512.mlpackage/Data/com.apple.CoreML/model.mlmodel")
let compiledURL = try MLModel.compileModel(at: modelURL)
let model = try MLModel(contentsOf: compiledURL)
print("[FaceNet] Model loaded (ANE+GPU+CPU)")
// Load face.json
let faceData = try Data(contentsOf: URL(fileURLWithPath: inputPath))
var faceJson = try JSONSerialization.jsonObject(with: faceData) as! [String: Any]
var frames = faceJson["frames"] as! [[String: Any]]
let fps = faceJson["fps"] as! Double
print("[FaceNet] Loaded \(frames.count) frames from \(inputPath)")
// Load video
let asset = AVURLAsset(url: URL(fileURLWithPath: videoPath))
let generator = AVAssetImageGenerator(asset: asset)
generator.requestedTimeToleranceBefore = .zero
generator.requestedTimeToleranceAfter = .zero
generator.appliesPreferredTrackTransform = true
var embeddingCount = 0
var processedFrames = 0
// Process frames in batches
for i in 0..<frames.count {
var frame = frames[i]
let frameNumber = frame["frame"] as! Int
var faces = frame["faces"] as! [[String: Any]]
if faces.isEmpty { continue }
// Extract frame image
let time = CMTime(seconds: Double(frameNumber) / fps, preferredTimescale: 1000)
guard let imageRef = try? generator.copyCGImage(at: time, actualTime: nil) else {
print("[FaceNet] Failed to extract frame \(frameNumber)")
continue
}
// Process each face in this frame
for j in 0..<faces.count {
var face = faces[j]
// Skip if already has embedding
if face["embedding"] != nil {
embeddingCount += 1
continue
}
// Get face bbox
guard let bbox = face["bbox"] as? [String: Int] else { continue }
let x = bbox["x"]!
let y = bbox["y"]!
let w = bbox["width"]!
let h = bbox["height"]!
// Extract face region
// Note: CGImage coordinates are bottom-up, so flip Y
let flippedY = imageRef.height - y - h
let faceRect = CGRect(x: max(0, x), y: max(0, flippedY), width: min(w, imageRef.width - x), height: min(h, imageRef.height - flippedY))
guard let faceImage = imageRef.cropping(to: faceRect) else {
continue
}
// Resize to 160x160 and convert to MLMultiArray
guard let resizedImage = resizeImage(faceImage, to: CGSize(width: 160, height: 160)) else {
continue
}
guard let inputArray = cgImageToMLMultiArray(resizedImage) else {
continue
}
// Generate embedding via CoreML
let inputFeatures = try MLDictionaryFeatureProvider(dictionary: ["input": inputArray])
let outputFeatures = try model.prediction(from: inputFeatures)
if let output = outputFeatures.featureValue(for: "var_2167")?.multiArrayValue {
// Convert MLMultiArray to [Float]
let embeddingArray = (0..<output.count).map { Float(output[$0].doubleValue) }
// Add embedding to face
face["embedding"] = embeddingArray
faces[j] = face
embeddingCount += 1
}
}
frame["faces"] = faces
frames[i] = frame
processedFrames += 1
if processedFrames % 50 == 0 {
print("[FaceNet] Processed \(processedFrames)/\(frames.count) frames, \(embeddingCount) embeddings")
}
}
// Save updated face.json
faceJson["frames"] = frames
let outputData = try JSONSerialization.data(withJSONObject: faceJson)
try outputData.write(to: URL(fileURLWithPath: outputPath))
let elapsed = Date().timeIntervalSince(startTime)
print("[FaceNet] Done: \(embeddingCount) embeddings in \(String(format: "%.1f", elapsed))s → \(outputPath)")
}
private func resizeImage(_ image: CGImage, to size: CGSize) -> CGImage? {
let width = Int(size.width)
let height = Int(size.height)
let bytesPerPixel = 4
let bytesPerRow = width * bytesPerPixel
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
context.interpolationQuality = .high
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
return context.makeImage()
}
private func cgImageToMLMultiArray(_ image: CGImage) -> MLMultiArray? {
let width = image.width
let height = image.height
// Create MLMultiArray with shape [1, 3, 160, 160] (batch, channels, height, width)
guard let array = try? MLMultiArray(shape: [1, 3, NSNumber(value: height), NSNumber(value: width)], dataType: .float32) else {
return nil
}
// Create CGContext to read pixel data
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }
var rawData = [UInt8](repeating: 0, count: width * height * 4)
guard let context = CGContext(data: &rawData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
return nil
}
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
// Convert RGB to MLMultiArray (normalized to [0, 1])
// FaceNet expects [batch, channels, height, width]
for y in 0..<height {
for x in 0..<width {
let pixelIndex = (y * width + x) * 4
let r = Float(rawData[pixelIndex]) / 255.0
let g = Float(rawData[pixelIndex + 1]) / 255.0
let b = Float(rawData[pixelIndex + 2]) / 255.0
// [batch, channels, height, width]
// R channel: [0, 0, y, x]
// G channel: [0, 1, y, x]
// B channel: [0, 2, y, x]
let rIndex = 0 * 3 * height * width + 0 * height * width + y * width + x
let gIndex = 0 * 3 * height * width + 1 * height * width + y * width + x
let bIndex = 0 * 3 * height * width + 2 * height * width + y * width + x
array[rIndex] = NSNumber(value: r)
array[gIndex] = NSNumber(value: g)
array[bIndex] = NSNumber(value: b)
}
}
return array
}
}