react-native-face-match-sdk 0.0.0-stage → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/FaceMatch.podspec +55 -0
  2. package/LICENSE +21 -0
  3. package/README.md +190 -2
  4. package/android/build.gradle +59 -0
  5. package/android/consumer-rules.pro +5 -0
  6. package/android/src/main/AndroidManifest.xml +11 -0
  7. package/android/src/main/java/com/facematch/sdk/AntiSpoofHelper.kt +216 -0
  8. package/android/src/main/java/com/facematch/sdk/BitmapUtils.kt +138 -0
  9. package/android/src/main/java/com/facematch/sdk/CameraFrameView.kt +75 -0
  10. package/android/src/main/java/com/facematch/sdk/FaceAlignmentHelper.kt +156 -0
  11. package/android/src/main/java/com/facematch/sdk/FaceCameraView.kt +628 -0
  12. package/android/src/main/java/com/facematch/sdk/FaceCameraViewManager.kt +79 -0
  13. package/android/src/main/java/com/facematch/sdk/FaceCandidateFilter.kt +65 -0
  14. package/android/src/main/java/com/facematch/sdk/FaceDetectionHelper.kt +225 -0
  15. package/android/src/main/java/com/facematch/sdk/FaceEmbeddingHelper.kt +242 -0
  16. package/android/src/main/java/com/facematch/sdk/FaceFrameAnalyzer.kt +228 -0
  17. package/android/src/main/java/com/facematch/sdk/FaceMatchModule.kt +249 -0
  18. package/android/src/main/java/com/facematch/sdk/FaceMatchPackage.kt +14 -0
  19. package/android/src/main/java/com/facematch/sdk/FaceMatchRuntime.kt +138 -0
  20. package/android/src/main/java/com/facematch/sdk/FaceMatcherHelper.kt +92 -0
  21. package/android/src/main/java/com/facematch/sdk/FaceOverlayView.kt +236 -0
  22. package/android/src/main/java/com/facematch/sdk/LivenessDetector.kt +483 -0
  23. package/android/src/main/java/com/facematch/sdk/LivenessPrompts.kt +137 -0
  24. package/android/src/main/java/com/facematch/sdk/LivenessVoice.kt +270 -0
  25. package/android/src/main/java/com/facematch/sdk/PrivateCaptureStore.kt +50 -0
  26. package/ios/Sources/AntiSpoofHelper.swift +239 -0
  27. package/ios/Sources/FaceAlignmentHelper.swift +169 -0
  28. package/ios/Sources/FaceCameraView.swift +1161 -0
  29. package/ios/Sources/FaceCameraViewManager.m +28 -0
  30. package/ios/Sources/FaceCameraViewManager.swift +57 -0
  31. package/ios/Sources/FaceCandidateFilter.swift +62 -0
  32. package/ios/Sources/FaceDetectionHelper.swift +283 -0
  33. package/ios/Sources/FaceEmbeddingHelper.swift +188 -0
  34. package/ios/Sources/FaceFrameAnalyzer.swift +179 -0
  35. package/ios/Sources/FaceFrameResult.swift +96 -0
  36. package/ios/Sources/FaceMatchBundle.swift +26 -0
  37. package/ios/Sources/FaceMatchEngine.swift +136 -0
  38. package/ios/Sources/FaceMatchError.swift +40 -0
  39. package/ios/Sources/FaceMatchModule.m +55 -0
  40. package/ios/Sources/FaceMatchModule.swift +288 -0
  41. package/ios/Sources/FaceMatcherHelper.swift +107 -0
  42. package/ios/Sources/FaceOverlayView.swift +285 -0
  43. package/ios/Sources/ImageUtils.swift +322 -0
  44. package/ios/Sources/LivenessDetector.swift +505 -0
  45. package/ios/Sources/LivenessPrompts.swift +121 -0
  46. package/ios/Sources/LivenessVoice.swift +229 -0
  47. package/ios/Sources/OnnxRuntime/ORTShim.h +91 -0
  48. package/ios/Sources/OnnxRuntime/ORTShim.mm +260 -0
  49. package/ios/Sources/PrivateCaptureStore.swift +71 -0
  50. package/ios/Sources/VisionFaceFallback.swift +95 -0
  51. package/ios/onnxruntime-c.podspec +47 -0
  52. package/models/anti_spoof_minifasnet_v2.onnx +0 -0
  53. package/models/w600k_mbf.onnx +0 -0
  54. package/package.json +47 -4
  55. package/react-native.config.js +16 -0
  56. package/src/FaceCameraView.tsx +75 -0
  57. package/src/FaceMatch.ts +66 -0
  58. package/src/index.ts +4 -0
  59. package/src/types.ts +87 -0
@@ -0,0 +1,28 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #import <React/RCTViewManager.h>
3
+
4
+ // Bridges the Swift FaceCameraViewManager to React Native. Prop and command
5
+ // names must stay identical to the Android ViewManager so one JS component
6
+ // drives both platforms.
7
+ @interface RCT_EXTERN_MODULE (FaceCameraViewManager, RCTViewManager)
8
+
9
+ RCT_EXPORT_VIEW_PROPERTY(requireLiveness, BOOL)
10
+ RCT_EXPORT_VIEW_PROPERTY(autoStart, BOOL)
11
+ RCT_EXPORT_VIEW_PROPERTY(autoCaptureOnLiveness, BOOL)
12
+ RCT_EXPORT_VIEW_PROPERTY(antiSpoofThreshold, float)
13
+ RCT_EXPORT_VIEW_PROPERTY(brightenOnLowLight, BOOL)
14
+ RCT_EXPORT_VIEW_PROPERTY(voiceLanguage, NSString)
15
+ RCT_EXPORT_VIEW_PROPERTY(voiceGender, NSString)
16
+
17
+ RCT_EXPORT_VIEW_PROPERTY(onFaceState, RCTDirectEventBlock)
18
+ RCT_EXPORT_VIEW_PROPERTY(onLiveness, RCTDirectEventBlock)
19
+ RCT_EXPORT_VIEW_PROPERTY(onCapture, RCTDirectEventBlock)
20
+ RCT_EXPORT_VIEW_PROPERTY(onError, RCTDirectEventBlock)
21
+ RCT_EXPORT_VIEW_PROPERTY(onCameraState, RCTDirectEventBlock)
22
+
23
+ RCT_EXTERN_METHOD(startCamera : (nonnull NSNumber *)reactTag)
24
+ RCT_EXTERN_METHOD(stopCamera : (nonnull NSNumber *)reactTag)
25
+ RCT_EXTERN_METHOD(capture : (nonnull NSNumber *)reactTag)
26
+ RCT_EXTERN_METHOD(startLiveness : (nonnull NSNumber *)reactTag actions : (NSArray *)actions)
27
+
28
+ @end
@@ -0,0 +1,57 @@
1
+ import Foundation
2
+ import React
3
+ import UIKit
4
+
5
+ /// Port of `FaceCameraViewManager.kt`.
6
+ ///
7
+ /// A legacy `RCTViewManager`, deliberately matching the Android
8
+ /// `SimpleViewManager`. `RCTReactNativeFactory` enables
9
+ /// `useNativeViewConfigsInBridgelessMode`, so RN 0.79's Fabric interop layer
10
+ /// serves `requireNativeComponent('FaceCameraView')` and the numeric command
11
+ /// map without any extra registration. The class name minus "Manager" is the
12
+ /// component name the interop resolves, so do not rename it.
13
+ @objc(FaceCameraViewManager)
14
+ final class FaceCameraViewManager: RCTViewManager {
15
+
16
+ override func view() -> UIView! {
17
+ FaceCameraView(frame: .zero)
18
+ }
19
+
20
+ override static func requiresMainQueueSetup() -> Bool { true }
21
+
22
+ // MARK: - Commands
23
+ //
24
+ // The interop prepends the reactTag to every command's arguments, so each
25
+ // selector takes it first. The JS-visible name is the selector up to the
26
+ // first colon, matching Android's getCommandsMap() keys.
27
+
28
+ @objc func startCamera(_ reactTag: NSNumber) {
29
+ withView(reactTag) { $0.startCamera() }
30
+ }
31
+
32
+ @objc func stopCamera(_ reactTag: NSNumber) {
33
+ withView(reactTag) { $0.stopCamera() }
34
+ }
35
+
36
+ @objc func capture(_ reactTag: NSNumber) {
37
+ withView(reactTag) { $0.capture() }
38
+ }
39
+
40
+ @objc func startLiveness(_ reactTag: NSNumber, actions: NSArray?) {
41
+ let names = (actions as? [Any])?.compactMap { $0 as? String }
42
+ withView(reactTag) { $0.startLiveness(names) }
43
+ }
44
+
45
+ private func withView(_ reactTag: NSNumber, _ body: @escaping (FaceCameraView) -> Void) {
46
+ let resolve: () -> Void = { [weak self] in
47
+ guard let view = self?.bridge?.uiManager?.view(forReactTag: reactTag) as? FaceCameraView
48
+ else { return }
49
+ body(view)
50
+ }
51
+ if Thread.isMainThread {
52
+ resolve()
53
+ } else {
54
+ DispatchQueue.main.async(execute: resolve)
55
+ }
56
+ }
57
+ }
@@ -0,0 +1,62 @@
1
+ import CoreGraphics
2
+
3
+ /// Port of `FaceCandidateFilter.kt`.
4
+ ///
5
+ /// Removes the small, incomplete and overlapping detections that ML Kit can
6
+ /// occasionally report around a single high-resolution face. The largest face
7
+ /// is the subject; another detection is counted only when it is a credible,
8
+ /// spatially distinct second person.
9
+ enum FaceCandidateFilter {
10
+ private static let minSecondaryAreaRatio: CGFloat = 0.28
11
+ private static let minSecondarySideRatio: CGFloat = 0.45
12
+ private static let minAspectRatio: CGFloat = 0.55
13
+ private static let maxAspectRatio: CGFloat = 1.65
14
+ private static let maxDuplicateOverlap: CGFloat = 0.35
15
+
16
+ static func significant<T>(
17
+ _ candidates: [T],
18
+ bounds: (T) -> CGRect,
19
+ hasFullLandmarks: (T) -> Bool
20
+ ) -> [T] {
21
+ if candidates.isEmpty { return [] }
22
+
23
+ let sorted = candidates.sorted { area(bounds($0)) > area(bounds($1)) }
24
+ guard let primary = sorted.first else { return [] }
25
+ let primaryBounds = bounds(primary)
26
+ if !isValid(primaryBounds) { return [] }
27
+
28
+ var accepted = [primary]
29
+ for candidate in sorted.dropFirst() {
30
+ let candidateBounds = bounds(candidate)
31
+ let isCredibleSecondFace =
32
+ isValid(candidateBounds) &&
33
+ hasFullLandmarks(candidate) &&
34
+ area(candidateBounds) >= area(primaryBounds) * minSecondaryAreaRatio &&
35
+ minSide(candidateBounds) >= minSide(primaryBounds) * minSecondarySideRatio &&
36
+ (minAspectRatio...maxAspectRatio).contains(aspectRatio(candidateBounds)) &&
37
+ !accepted.contains { overlapOverSmaller(candidateBounds, bounds($0)) >= maxDuplicateOverlap }
38
+
39
+ if isCredibleSecondFace { accepted.append(candidate) }
40
+ }
41
+ return accepted
42
+ }
43
+
44
+ private static func isValid(_ rect: CGRect) -> Bool {
45
+ rect.origin.x.isFinite && rect.origin.y.isFinite &&
46
+ rect.width.isFinite && rect.height.isFinite &&
47
+ rect.width > 1 && rect.height > 1
48
+ }
49
+
50
+ private static func area(_ rect: CGRect) -> CGFloat { rect.width * rect.height }
51
+
52
+ private static func minSide(_ rect: CGRect) -> CGFloat { min(rect.width, rect.height) }
53
+
54
+ private static func aspectRatio(_ rect: CGRect) -> CGFloat { rect.width / rect.height }
55
+
56
+ private static func overlapOverSmaller(_ first: CGRect, _ second: CGRect) -> CGFloat {
57
+ let intersectionWidth = max(min(first.maxX, second.maxX) - max(first.minX, second.minX), 0)
58
+ let intersectionHeight = max(min(first.maxY, second.maxY) - max(first.minY, second.minY), 0)
59
+ let smallerArea = min(area(first), area(second))
60
+ return smallerArea <= 0 ? 0 : intersectionWidth * intersectionHeight / smallerArea
61
+ }
62
+ }
@@ -0,0 +1,283 @@
1
+ import CoreGraphics
2
+ import Foundation
3
+ import MLKitFaceDetection
4
+ import MLKitVision
5
+ import UIKit
6
+ import os
7
+
8
+ /// Detected face with 5-point landmarks in source-image pixel coordinates.
9
+ ///
10
+ /// Landmark order matches the InsightFace image-coordinate convention:
11
+ /// image-left eye, image-right eye, nose tip, image-left mouth, image-right mouth
12
+ ///
13
+ /// ML Kit's LEFT/RIGHT constants are anatomical (relative to the subject), so
14
+ /// ordering each symmetric pair by x-coordinate is essential. It also makes
15
+ /// alignment identical for ordinary reference photos and mirrored selfies.
16
+ struct DetectedFace {
17
+ /// Flat [x0,y0, x1,y1, ...] array (10 values) in source-image pixels.
18
+ let landmarks: [CGFloat]
19
+ /// Axis-aligned bounding box in source-image pixels, top-left origin.
20
+ let boundingBox: CGRect
21
+ /// True when all 5 ML Kit landmarks were present; false means some
22
+ /// positions were estimated from the bounding box.
23
+ let hasFullSet: Bool
24
+
25
+ var bboxArea: CGFloat { boundingBox.width * boundingBox.height }
26
+
27
+ /// Minimum side length in pixels — faces smaller than this produce poor
28
+ /// embeddings.
29
+ var minSide: CGFloat { min(boundingBox.width, boundingBox.height) }
30
+ }
31
+
32
+ /// Port of `FaceDetectionHelper.kt`.
33
+ ///
34
+ /// Uses ML Kit's accurate mode with all landmarks enabled so we always obtain
35
+ /// the 5 points needed for InsightFace-style alignment. The model is bundled
36
+ /// in the app — no network calls are made.
37
+ final class FaceDetectionHelper {
38
+ /// Reject faces smaller than this — 50px is the practical minimum for
39
+ /// MobileFaceNet to produce a useful embedding. ID document photos often
40
+ /// have faces occupying only a small portion of the image.
41
+ private static let minFacePx: CGFloat = 50
42
+
43
+ /// Upscale images whose longest side is smaller than this before detection
44
+ /// — ensures tiny faces in ID/passport photos are found.
45
+ private static let detectMinSide = 480
46
+
47
+ /// Downscale images whose longest side exceeds this — avoids wasted
48
+ /// computation and memory spikes on very large photos.
49
+ private static let detectMaxSide = 1920
50
+
51
+ private let detector: FaceDetector
52
+
53
+ init() {
54
+ let options = FaceDetectorOptions()
55
+ options.performanceMode = .accurate
56
+ options.landmarkMode = .all
57
+ // No classification: `DetectedFace` carries landmarks and a bounding box
58
+ // only, so the smile / eye-open probabilities this used to request were
59
+ // computed and then discarded on every capture-path detect. Per-frame
60
+ // liveness classification lives in FaceFrameAnalyzer, which still asks for
61
+ // `.all` because it does read them.
62
+ options.classificationMode = .none
63
+ options.minFaceSize = 0.05 // 5% — handles faces in ID/passport documents
64
+ detector = FaceDetector.faceDetector(options: options)
65
+ }
66
+
67
+ /// Resize `image` so its longest side falls within
68
+ /// `detectMinSide...detectMaxSide`. Returns the original when already in range.
69
+ static func prepareForDetection(_ image: CGImage) -> CGImage {
70
+ let longest = max(image.width, image.height)
71
+ let scale: CGFloat
72
+ if longest < detectMinSide {
73
+ scale = CGFloat(detectMinSide) / CGFloat(longest)
74
+ } else if longest > detectMaxSide {
75
+ scale = CGFloat(detectMaxSide) / CGFloat(longest)
76
+ } else {
77
+ return ImageUtils.standardized(image)
78
+ }
79
+ let width = max(1, Int((CGFloat(image.width) * scale).rounded()))
80
+ let height = max(1, Int((CGFloat(image.height) * scale).rounded()))
81
+ return ImageUtils.scaled(image, width: width, height: height)
82
+ }
83
+
84
+ /// Detect all faces and return them sorted largest-first. Each result
85
+ /// carries 5-point landmarks suitable for alignment.
86
+ ///
87
+ /// Synchronous: callers must already be on a background queue.
88
+ func detectFaces(_ image: CGImage) throws -> [DetectedFace] {
89
+ let prepared = Self.prepareForDetection(image)
90
+ // Scale factor to map detected landmarks/boxes back to original coords.
91
+ let scaleX = CGFloat(image.width) / CGFloat(prepared.width)
92
+ let scaleY = CGFloat(image.height) / CGFloat(prepared.height)
93
+
94
+ // 1. ML Kit on the prepared image — identical to Android.
95
+ var found = try runMLKit(prepared)
96
+ .map { detectedFace(from: $0, scaleX: scaleX, scaleY: scaleY) }
97
+ .filter { $0.minSide >= Self.minFacePx }
98
+ var stage = "mlkit"
99
+
100
+ // 2. ML Kit with a border. The iOS ML Kit model routinely misses faces
101
+ // that fill (or are cut by) the frame — typical of stored profile /
102
+ // registration photos — which the Android model still finds.
103
+ if found.isEmpty, let padded = Self.padded(prepared) {
104
+ let pad = padded.pad
105
+ found = try runMLKit(padded.image)
106
+ .map { offsetFace($0, by: CGPoint(x: -pad, y: -pad)) }
107
+ .map { Self.scaled($0, scaleX: scaleX, scaleY: scaleY) }
108
+ .filter { $0.minSide >= Self.minFacePx }
109
+ stage = "mlkit-padded"
110
+ }
111
+
112
+ // 3. Apple Vision as a last resort; it supplies the same 5 points.
113
+ if found.isEmpty {
114
+ found = VisionFaceFallback.detect(prepared)
115
+ .map { Self.scaled($0, scaleX: scaleX, scaleY: scaleY) }
116
+ .filter { $0.minSide >= Self.minFacePx }
117
+ stage = "vision"
118
+ }
119
+
120
+ #if DEBUG
121
+ os_log(
122
+ "%{public}@",
123
+ log: Self.log,
124
+ type: .info,
125
+ "detect: \(image.width)x\(image.height) bpc=\(image.bitsPerComponent) "
126
+ + "bpp=\(image.bitsPerPixel) faces=\(found.count) stage=\(stage)"
127
+ )
128
+ #endif
129
+
130
+ return found.sorted { $0.bboxArea > $1.bboxArea }
131
+ }
132
+
133
+ private static let log = OSLog(subsystem: "com.facematch.sdk", category: "Detect")
134
+
135
+ private func runMLKit(_ image: CGImage) throws -> [Face] {
136
+ let visionImage = VisionImage(image: UIImage(cgImage: image))
137
+ visionImage.orientation = .up
138
+ do {
139
+ return try detector.results(in: visionImage)
140
+ } catch {
141
+ throw FaceMatchError("E_FACE_MATCH", error.localizedDescription)
142
+ }
143
+ }
144
+
145
+ /// Centres `image` on a mid-grey canvas 25% larger on every side.
146
+ private static func padded(_ image: CGImage) -> (image: CGImage, pad: CGFloat)? {
147
+ let pad = (CGFloat(max(image.width, image.height)) * 0.25).rounded()
148
+ let width = image.width + Int(pad) * 2
149
+ let height = image.height + Int(pad) * 2
150
+ guard let context = CGContext(
151
+ data: nil,
152
+ width: width,
153
+ height: height,
154
+ bitsPerComponent: 8,
155
+ bytesPerRow: 0,
156
+ space: CGColorSpaceCreateDeviceRGB(),
157
+ bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue
158
+ | CGBitmapInfo.byteOrder32Little.rawValue
159
+ ) else { return nil }
160
+ context.setFillColor(gray: 0.5, alpha: 1)
161
+ context.fill(CGRect(x: 0, y: 0, width: width, height: height))
162
+ context.draw(image, in: CGRect(x: pad, y: pad, width: CGFloat(image.width), height: CGFloat(image.height)))
163
+ guard let result = context.makeImage() else { return nil }
164
+ return (result, pad)
165
+ }
166
+
167
+ private static func scaled(_ face: DetectedFace, scaleX: CGFloat, scaleY: CGFloat) -> DetectedFace {
168
+ if scaleX == 1, scaleY == 1 { return face }
169
+ let landmarks = face.landmarks.enumerated().map { index, value in
170
+ value * (index % 2 == 0 ? scaleX : scaleY)
171
+ }
172
+ let box = face.boundingBox
173
+ return DetectedFace(
174
+ landmarks: landmarks,
175
+ boundingBox: CGRect(
176
+ x: box.minX * scaleX,
177
+ y: box.minY * scaleY,
178
+ width: box.width * scaleX,
179
+ height: box.height * scaleY
180
+ ),
181
+ hasFullSet: face.hasFullSet
182
+ )
183
+ }
184
+
185
+ // MARK: - ML Kit Face -> DetectedFace
186
+
187
+ private func offsetFace(_ face: Face, by offset: CGPoint) -> DetectedFace {
188
+ let raw = detectedFace(from: face, scaleX: 1, scaleY: 1)
189
+ let landmarks = raw.landmarks.enumerated().map { index, value in
190
+ value + (index % 2 == 0 ? offset.x : offset.y)
191
+ }
192
+ return DetectedFace(
193
+ landmarks: landmarks,
194
+ boundingBox: raw.boundingBox.offsetBy(dx: offset.x, dy: offset.y),
195
+ hasFullSet: raw.hasFullSet
196
+ )
197
+ }
198
+
199
+ private func detectedFace(from face: Face, scaleX: CGFloat, scaleY: CGFloat) -> DetectedFace {
200
+ let subjectLeftEye = face.landmark(ofType: .leftEye)?.position
201
+ let subjectRightEye = face.landmark(ofType: .rightEye)?.position
202
+ let noseTip = face.landmark(ofType: .noseBase)?.position
203
+ let subjectLeftMouth = face.landmark(ofType: .mouthLeft)?.position
204
+ let subjectRightMouth = face.landmark(ofType: .mouthRight)?.position
205
+
206
+ let hasAll = subjectLeftEye != nil && subjectRightEye != nil && noseTip != nil &&
207
+ subjectLeftMouth != nil && subjectRightMouth != nil
208
+
209
+ // Fall back to geometric estimates from the bounding box when a
210
+ // landmark is missing (rare, but happens with partial occlusion).
211
+ let box = face.frame
212
+ let centerX = box.midX
213
+ let centerY = box.midY
214
+ let width = box.width
215
+ let height = box.height
216
+
217
+ let (imageLeftEye, imageRightEye) = Self.orderHorizontalPair(
218
+ subjectLeftEye,
219
+ subjectRightEye,
220
+ centerX: centerX,
221
+ fallbackY: centerY - height * 0.10,
222
+ halfSeparation: width * 0.15
223
+ )
224
+ let noseX = noseTip?.x ?? centerX
225
+ let noseY = noseTip?.y ?? centerY
226
+ let (imageLeftMouth, imageRightMouth) = Self.orderHorizontalPair(
227
+ subjectLeftMouth,
228
+ subjectRightMouth,
229
+ centerX: centerX,
230
+ fallbackY: centerY + height * 0.20,
231
+ halfSeparation: width * 0.10
232
+ )
233
+
234
+ // Scale all coordinates back to original (pre-resize) image space.
235
+ return DetectedFace(
236
+ landmarks: [
237
+ imageLeftEye.x * scaleX, imageLeftEye.y * scaleY,
238
+ imageRightEye.x * scaleX, imageRightEye.y * scaleY,
239
+ noseX * scaleX, noseY * scaleY,
240
+ imageLeftMouth.x * scaleX, imageLeftMouth.y * scaleY,
241
+ imageRightMouth.x * scaleX, imageRightMouth.y * scaleY
242
+ ],
243
+ boundingBox: CGRect(
244
+ x: box.minX * scaleX,
245
+ y: box.minY * scaleY,
246
+ width: box.width * scaleX,
247
+ height: box.height * scaleY
248
+ ),
249
+ hasFullSet: hasAll
250
+ )
251
+ }
252
+
253
+ /// Returns a symmetric landmark pair in image-left to image-right order.
254
+ /// When ML Kit omits one point, its position relative to the face centre is
255
+ /// used to place the fallback on the opposite side without assuming whether
256
+ /// the input image is mirrored.
257
+ static func orderHorizontalPair(
258
+ _ first: VisionPoint?,
259
+ _ second: VisionPoint?,
260
+ centerX: CGFloat,
261
+ fallbackY: CGFloat,
262
+ halfSeparation: CGFloat
263
+ ) -> (CGPoint, CGPoint) {
264
+ if let first, let second {
265
+ let a = CGPoint(x: first.x, y: first.y)
266
+ let b = CGPoint(x: second.x, y: second.y)
267
+ return a.x <= b.x ? (a, b) : (b, a)
268
+ }
269
+
270
+ guard let detected = first ?? second else {
271
+ return (
272
+ CGPoint(x: centerX - halfSeparation, y: fallbackY),
273
+ CGPoint(x: centerX + halfSeparation, y: fallbackY)
274
+ )
275
+ }
276
+
277
+ let point = CGPoint(x: detected.x, y: detected.y)
278
+ if point.x <= centerX {
279
+ return (point, CGPoint(x: centerX + halfSeparation, y: fallbackY))
280
+ }
281
+ return (CGPoint(x: centerX - halfSeparation, y: fallbackY), point)
282
+ }
283
+ }
@@ -0,0 +1,188 @@
1
+ import CoreGraphics
2
+ import Foundation
3
+
4
+ /// Port of `FaceEmbeddingHelper.kt`.
5
+ ///
6
+ /// Offline 512-dimensional MobileFaceNet/ArcFace embedding inference.
7
+ ///
8
+ /// Input images are already aligned to the InsightFace 112x112 template. The
9
+ /// model receives natural RGB normalised by `(pixel - 127.5) / 128`, matching
10
+ /// its standard training and export preprocessing.
11
+ final class FaceEmbeddingHelper {
12
+ private static let modelName = "w600k_mbf"
13
+ private static let inputSize = FaceAlignmentHelper.faceSize
14
+ private static let mean: Float = 127.5
15
+ private static let std: Float = 128.0
16
+
17
+ private let session: ORTSession
18
+ private let inputName: String
19
+ private let outputName: String
20
+ private let lock = NSLock()
21
+
22
+ init() throws {
23
+ guard let path = FaceMatchBundle.modelPath(named: Self.modelName) else {
24
+ throw FaceMatchError(
25
+ "E_EMBEDDING",
26
+ "Model not found in the app bundle. Add \(Self.modelName).onnx to the package's models/ folder and run pod install again."
27
+ )
28
+ }
29
+ let env = try ORTEnv(loggingLevel: ORTLoggingLevel.warning)
30
+ session = try ORTSession(env: env, modelPath: path, sessionOptions: try ORTSessionOptions())
31
+ guard let input = try session.inputNames().first,
32
+ let output = try session.outputNames().first else {
33
+ throw FaceMatchError("E_EMBEDDING", "Embedding model exposes no input/output")
34
+ }
35
+ inputName = input
36
+ outputName = output
37
+ }
38
+
39
+ /// Produces one L2-normalised identity embedding. Normal and mirrored
40
+ /// inference results are fused to reduce sensitivity to minor pose,
41
+ /// illumination and landmark differences between reference and live images.
42
+ func embedding(for face: CGImage) -> [Float]? {
43
+ augmentedEmbedding(face, includeDocumentNormalization: false)
44
+ }
45
+
46
+ /// Produces a reference template that is less sensitive to faded prints,
47
+ /// scanner contrast and colour ageing in identity-document photographs.
48
+ /// The ordinary and gently tone-normalised templates are fused on the unit
49
+ /// hypersphere; neither template can independently force a match.
50
+ func referenceEmbedding(for face: CGImage) -> [Float]? {
51
+ augmentedEmbedding(face, includeDocumentNormalization: true)
52
+ }
53
+
54
+ private func augmentedEmbedding(
55
+ _ face: CGImage,
56
+ includeDocumentNormalization: Bool
57
+ ) -> [Float]? {
58
+ guard let primary = runEmbedding(face) else { return nil }
59
+ var embeddings = [primary]
60
+ if let flipped = flippedEmbedding(face) { embeddings.append(flipped) }
61
+
62
+ if includeDocumentNormalization, let normalised = normalizeDocumentTone(face) {
63
+ if let toned = runEmbedding(normalised) { embeddings.append(toned) }
64
+ if let tonedFlip = flippedEmbedding(normalised) { embeddings.append(tonedFlip) }
65
+ }
66
+
67
+ return fuse(embeddings) ?? primary
68
+ }
69
+
70
+ private func flippedEmbedding(_ face: CGImage) -> [Float]? {
71
+ // Horizontal-flip test-time augmentation is standard for ArcFace.
72
+ runEmbedding(ImageUtils.mirrorHorizontal(face))
73
+ }
74
+
75
+ private func fuse(_ embeddings: [[Float]]) -> [Float]? {
76
+ guard let first = embeddings.first else { return nil }
77
+ var sum = [Float](repeating: 0, count: first.count)
78
+ for embedding in embeddings {
79
+ guard embedding.count == sum.count else { return nil }
80
+ for index in embedding.indices { sum[index] += embedding[index] }
81
+ }
82
+ return Self.l2Normalize(sum)
83
+ }
84
+
85
+ /// Applies a restrained luminance percentile stretch. Blending only 35% of
86
+ /// the correction preserves identity texture while reducing the domain gap
87
+ /// between an old printed/scanned document and a current camera image.
88
+ private func normalizeDocumentTone(_ source: CGImage) -> CGImage? {
89
+ let width = source.width
90
+ let height = source.height
91
+ var pixels = ImageUtils.argbPixels(of: source)
92
+
93
+ var histogram = [Int](repeating: 0, count: 256)
94
+ for pixel in pixels {
95
+ let red = Int((pixel >> 16) & 0xFF)
96
+ let green = Int((pixel >> 8) & 0xFF)
97
+ let blue = Int(pixel & 0xFF)
98
+ histogram[(77 * red + 150 * green + 29 * blue) >> 8] += 1
99
+ }
100
+
101
+ let lowTarget = Int(Float(pixels.count) * 0.02)
102
+ let highTarget = Int(Float(pixels.count) * 0.98)
103
+ var cumulative = 0
104
+ var low = 0
105
+ var high = 255
106
+ for level in histogram.indices {
107
+ cumulative += histogram[level]
108
+ if cumulative >= lowTarget { low = level; break }
109
+ }
110
+ cumulative = 0
111
+ for level in histogram.indices {
112
+ cumulative += histogram[level]
113
+ if cumulative >= highTarget { high = level; break }
114
+ }
115
+ if high - low < 32 { return nil }
116
+
117
+ let range = Float(high - low)
118
+ for index in pixels.indices {
119
+ let pixel = pixels[index]
120
+ let alpha = (pixel >> 24) & 0xFF
121
+ let red = Int((pixel >> 16) & 0xFF)
122
+ let green = Int((pixel >> 8) & 0xFF)
123
+ let blue = Int(pixel & 0xFF)
124
+ let luminance = (77 * red + 150 * green + 29 * blue) >> 8
125
+ let stretched = min(max((Float(luminance - low) * 255 / range), 0), 255)
126
+ let delta = Int((stretched - Float(luminance)) * 0.35)
127
+ pixels[index] = (alpha << 24)
128
+ | (UInt32(min(max(red + delta, 0), 255)) << 16)
129
+ | (UInt32(min(max(green + delta, 0), 255)) << 8)
130
+ | UInt32(min(max(blue + delta, 0), 255))
131
+ }
132
+ return ImageUtils.image(fromARGB: pixels, width: width, height: height)
133
+ }
134
+
135
+ private func runEmbedding(_ face: CGImage) -> [Float]? {
136
+ lock.lock()
137
+ defer { lock.unlock() }
138
+ do {
139
+ let tensor = try buildTensor(face)
140
+ let outputs = try session.run(
141
+ withInputs: [inputName: tensor],
142
+ outputNames: [outputName],
143
+ runOptions: nil
144
+ )
145
+ guard let output = outputs[outputName] else { return nil }
146
+ let data = try output.tensorData() as Data
147
+ let values = data.withUnsafeBytes { Array($0.bindMemory(to: Float.self)) }
148
+ return Self.l2Normalize(values)
149
+ } catch {
150
+ return nil
151
+ }
152
+ }
153
+
154
+ private func buildTensor(_ image: CGImage) throws -> ORTValue {
155
+ let size = Self.inputSize
156
+ let scaled = ImageUtils.scaled(image, width: size, height: size)
157
+ let pixels = ImageUtils.argbPixels(of: scaled)
158
+
159
+ var values = [Float](repeating: 0, count: 3 * size * size)
160
+ var offset = 0
161
+ for channelIndex in 0..<3 {
162
+ for pixel in pixels {
163
+ let channel: UInt32
164
+ switch channelIndex {
165
+ case 0: channel = (pixel >> 16) & 0xFF // red
166
+ case 1: channel = (pixel >> 8) & 0xFF // green
167
+ default: channel = pixel & 0xFF // blue
168
+ }
169
+ values[offset] = (Float(channel) - Self.mean) / Self.std
170
+ offset += 1
171
+ }
172
+ }
173
+
174
+ let data = NSMutableData(bytes: values, length: values.count * MemoryLayout<Float>.stride)
175
+ return try ORTValue(
176
+ tensorData: data,
177
+ elementType: ORTTensorElementDataType.float,
178
+ shape: [1, 3, NSNumber(value: size), NSNumber(value: size)]
179
+ )
180
+ }
181
+
182
+ static func l2Normalize(_ embedding: [Float]) -> [Float]? {
183
+ let squaredNorm = embedding.reduce(0.0) { $0 + Double($1) * Double($1) }
184
+ let norm = Float(squaredNorm.squareRoot())
185
+ guard norm.isFinite, norm >= 1e-6 else { return nil }
186
+ return embedding.map { $0 / norm }
187
+ }
188
+ }