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.
- package/FaceMatch.podspec +55 -0
- package/LICENSE +21 -0
- package/README.md +190 -2
- package/android/build.gradle +59 -0
- package/android/consumer-rules.pro +5 -0
- package/android/src/main/AndroidManifest.xml +11 -0
- package/android/src/main/java/com/facematch/sdk/AntiSpoofHelper.kt +216 -0
- package/android/src/main/java/com/facematch/sdk/BitmapUtils.kt +138 -0
- package/android/src/main/java/com/facematch/sdk/CameraFrameView.kt +75 -0
- package/android/src/main/java/com/facematch/sdk/FaceAlignmentHelper.kt +156 -0
- package/android/src/main/java/com/facematch/sdk/FaceCameraView.kt +628 -0
- package/android/src/main/java/com/facematch/sdk/FaceCameraViewManager.kt +79 -0
- package/android/src/main/java/com/facematch/sdk/FaceCandidateFilter.kt +65 -0
- package/android/src/main/java/com/facematch/sdk/FaceDetectionHelper.kt +225 -0
- package/android/src/main/java/com/facematch/sdk/FaceEmbeddingHelper.kt +242 -0
- package/android/src/main/java/com/facematch/sdk/FaceFrameAnalyzer.kt +228 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatchModule.kt +249 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatchPackage.kt +14 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatchRuntime.kt +138 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatcherHelper.kt +92 -0
- package/android/src/main/java/com/facematch/sdk/FaceOverlayView.kt +236 -0
- package/android/src/main/java/com/facematch/sdk/LivenessDetector.kt +483 -0
- package/android/src/main/java/com/facematch/sdk/LivenessPrompts.kt +137 -0
- package/android/src/main/java/com/facematch/sdk/LivenessVoice.kt +270 -0
- package/android/src/main/java/com/facematch/sdk/PrivateCaptureStore.kt +50 -0
- package/ios/Sources/AntiSpoofHelper.swift +239 -0
- package/ios/Sources/FaceAlignmentHelper.swift +169 -0
- package/ios/Sources/FaceCameraView.swift +1161 -0
- package/ios/Sources/FaceCameraViewManager.m +28 -0
- package/ios/Sources/FaceCameraViewManager.swift +57 -0
- package/ios/Sources/FaceCandidateFilter.swift +62 -0
- package/ios/Sources/FaceDetectionHelper.swift +283 -0
- package/ios/Sources/FaceEmbeddingHelper.swift +188 -0
- package/ios/Sources/FaceFrameAnalyzer.swift +179 -0
- package/ios/Sources/FaceFrameResult.swift +96 -0
- package/ios/Sources/FaceMatchBundle.swift +26 -0
- package/ios/Sources/FaceMatchEngine.swift +136 -0
- package/ios/Sources/FaceMatchError.swift +40 -0
- package/ios/Sources/FaceMatchModule.m +55 -0
- package/ios/Sources/FaceMatchModule.swift +288 -0
- package/ios/Sources/FaceMatcherHelper.swift +107 -0
- package/ios/Sources/FaceOverlayView.swift +285 -0
- package/ios/Sources/ImageUtils.swift +322 -0
- package/ios/Sources/LivenessDetector.swift +505 -0
- package/ios/Sources/LivenessPrompts.swift +121 -0
- package/ios/Sources/LivenessVoice.swift +229 -0
- package/ios/Sources/OnnxRuntime/ORTShim.h +91 -0
- package/ios/Sources/OnnxRuntime/ORTShim.mm +260 -0
- package/ios/Sources/PrivateCaptureStore.swift +71 -0
- package/ios/Sources/VisionFaceFallback.swift +95 -0
- package/ios/onnxruntime-c.podspec +47 -0
- package/models/anti_spoof_minifasnet_v2.onnx +0 -0
- package/models/w600k_mbf.onnx +0 -0
- package/package.json +47 -4
- package/react-native.config.js +16 -0
- package/src/FaceCameraView.tsx +75 -0
- package/src/FaceMatch.ts +66 -0
- package/src/index.ts +4 -0
- package/src/types.ts +87 -0
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import CoreGraphics
|
|
2
|
+
import Foundation
|
|
3
|
+
import MLKitFaceDetection
|
|
4
|
+
import MLKitVision
|
|
5
|
+
import os
|
|
6
|
+
import UIKit
|
|
7
|
+
|
|
8
|
+
/// Port of `FaceFrameAnalyzer.kt`, backed by the bundled, on-device ML Kit
|
|
9
|
+
/// face detector.
|
|
10
|
+
///
|
|
11
|
+
/// Unlike Android this is a plain synchronous transform: the camera view calls
|
|
12
|
+
/// `analyze` on its own serial analysis queue, and `AVCaptureVideoDataOutput`
|
|
13
|
+
/// with `alwaysDiscardsLateVideoFrames` provides the same keep-only-latest
|
|
14
|
+
/// backpressure that `STRATEGY_KEEP_ONLY_LATEST` gives on CameraX.
|
|
15
|
+
final class FaceFrameAnalyzer {
|
|
16
|
+
#if DEBUG
|
|
17
|
+
fileprivate static let debugLog = OSLog(subsystem: "com.facematch.sdk", category: "Analyzer")
|
|
18
|
+
#endif
|
|
19
|
+
|
|
20
|
+
private let detector: FaceDetector
|
|
21
|
+
private let classifyAntiSpoof: (CGImage, CGRect, Float) -> AntiSpoofResult
|
|
22
|
+
private var antiSpoofThreshold = AntiSpoofHelper.defaultThreshold
|
|
23
|
+
private let thresholdLock = NSLock()
|
|
24
|
+
|
|
25
|
+
init(classifyAntiSpoof: @escaping (CGImage, CGRect, Float) -> AntiSpoofResult) {
|
|
26
|
+
self.classifyAntiSpoof = classifyAntiSpoof
|
|
27
|
+
let options = FaceDetectorOptions()
|
|
28
|
+
options.performanceMode = .fast
|
|
29
|
+
options.landmarkMode = .all
|
|
30
|
+
options.classificationMode = .all
|
|
31
|
+
options.minFaceSize = 0.12
|
|
32
|
+
options.isTrackingEnabled = true
|
|
33
|
+
detector = FaceDetector.faceDetector(options: options)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
func setAntiSpoofThreshold(_ value: Float) {
|
|
37
|
+
thresholdLock.lock()
|
|
38
|
+
antiSpoofThreshold = AntiSpoofHelper.sanitizeThreshold(value)
|
|
39
|
+
thresholdLock.unlock()
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private var currentThreshold: Float {
|
|
43
|
+
thresholdLock.lock()
|
|
44
|
+
defer { thresholdLock.unlock() }
|
|
45
|
+
return antiSpoofThreshold
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/// `image` must already be upright.
|
|
49
|
+
func analyze(_ image: CGImage) -> FaceFrameResult {
|
|
50
|
+
let imageWidth = image.width
|
|
51
|
+
let imageHeight = image.height
|
|
52
|
+
let luminance = ImageUtils.luminance(of: image)
|
|
53
|
+
|
|
54
|
+
let visionImage = VisionImage(image: UIImage(cgImage: image))
|
|
55
|
+
visionImage.orientation = .up
|
|
56
|
+
|
|
57
|
+
let faces: [Face]
|
|
58
|
+
do {
|
|
59
|
+
faces = try detector.results(in: visionImage)
|
|
60
|
+
} catch {
|
|
61
|
+
#if DEBUG
|
|
62
|
+
os_log(
|
|
63
|
+
"ML Kit detection failed: %{public}@",
|
|
64
|
+
log: Self.debugLog,
|
|
65
|
+
type: .error,
|
|
66
|
+
error.localizedDescription
|
|
67
|
+
)
|
|
68
|
+
#endif
|
|
69
|
+
return FaceFrameResult(
|
|
70
|
+
rect: nil,
|
|
71
|
+
landmarks: nil,
|
|
72
|
+
imageWidth: imageWidth,
|
|
73
|
+
imageHeight: imageHeight,
|
|
74
|
+
luminance: luminance
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let significantFaces = FaceCandidateFilter.significant(
|
|
79
|
+
faces,
|
|
80
|
+
bounds: { $0.frame },
|
|
81
|
+
hasFullLandmarks: { Self.hasRequiredLandmarks($0) }
|
|
82
|
+
)
|
|
83
|
+
let face = significantFaces.first
|
|
84
|
+
let faceCount = significantFaces.count
|
|
85
|
+
|
|
86
|
+
#if DEBUG
|
|
87
|
+
// Separating the two counts distinguishes "ML Kit saw nothing" from
|
|
88
|
+
// "FaceCandidateFilter rejected everything it saw".
|
|
89
|
+
if faces.count != faceCount {
|
|
90
|
+
os_log(
|
|
91
|
+
"ML Kit raw=%d significant=%d",
|
|
92
|
+
log: Self.debugLog,
|
|
93
|
+
type: .info,
|
|
94
|
+
faces.count,
|
|
95
|
+
faceCount
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
#endif
|
|
99
|
+
|
|
100
|
+
let frame = (face.map {
|
|
101
|
+
Self.frameResult(from: $0, imageWidth: imageWidth, imageHeight: imageHeight, faceCount: faceCount)
|
|
102
|
+
} ?? FaceFrameResult(
|
|
103
|
+
rect: nil,
|
|
104
|
+
landmarks: nil,
|
|
105
|
+
imageWidth: imageWidth,
|
|
106
|
+
imageHeight: imageHeight
|
|
107
|
+
)).with(luminance: luminance)
|
|
108
|
+
|
|
109
|
+
// Passive anti-spoofing is deliberately evaluated after ML Kit face
|
|
110
|
+
// detection and before the active-liveness state machine. More than one
|
|
111
|
+
// face fails closed before any identity inference.
|
|
112
|
+
guard let face, faceCount == 1 else { return frame }
|
|
113
|
+
return frame.with(
|
|
114
|
+
antiSpoof: classifyAntiSpoof(image, face.frame, currentThreshold)
|
|
115
|
+
)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private static func hasRequiredLandmarks(_ face: Face) -> Bool {
|
|
119
|
+
face.landmark(ofType: .leftEye) != nil &&
|
|
120
|
+
face.landmark(ofType: .rightEye) != nil &&
|
|
121
|
+
face.landmark(ofType: .noseBase) != nil &&
|
|
122
|
+
face.landmark(ofType: .mouthLeft) != nil &&
|
|
123
|
+
face.landmark(ofType: .mouthRight) != nil
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private static func frameResult(
|
|
127
|
+
from face: Face,
|
|
128
|
+
imageWidth: Int,
|
|
129
|
+
imageHeight: Int,
|
|
130
|
+
faceCount: Int
|
|
131
|
+
) -> FaceFrameResult {
|
|
132
|
+
let box = face.frame
|
|
133
|
+
let centerX = box.midX
|
|
134
|
+
let centerY = box.midY
|
|
135
|
+
let width = box.width
|
|
136
|
+
let height = box.height
|
|
137
|
+
|
|
138
|
+
func x(_ type: FaceLandmarkType, _ fallback: CGFloat) -> CGFloat {
|
|
139
|
+
face.landmark(ofType: type)?.position.x ?? fallback
|
|
140
|
+
}
|
|
141
|
+
func y(_ type: FaceLandmarkType, _ fallback: CGFloat) -> CGFloat {
|
|
142
|
+
face.landmark(ofType: type)?.position.y ?? fallback
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
let leftEyeX = x(.leftEye, centerX - width * 0.15)
|
|
146
|
+
let leftEyeY = y(.leftEye, centerY - height * 0.10)
|
|
147
|
+
let rightEyeX = x(.rightEye, centerX + width * 0.15)
|
|
148
|
+
let rightEyeY = y(.rightEye, centerY - height * 0.10)
|
|
149
|
+
let noseX = x(.noseBase, centerX)
|
|
150
|
+
let noseY = y(.noseBase, centerY + height * 0.02)
|
|
151
|
+
let mouthLeftX = x(.mouthLeft, centerX - width * 0.12)
|
|
152
|
+
let mouthLeftY = y(.mouthLeft, centerY + height * 0.20)
|
|
153
|
+
let mouthRightX = x(.mouthRight, centerX + width * 0.12)
|
|
154
|
+
let mouthRightY = y(.mouthRight, centerY + height * 0.20)
|
|
155
|
+
|
|
156
|
+
return FaceFrameResult(
|
|
157
|
+
rect: box,
|
|
158
|
+
landmarks: [
|
|
159
|
+
leftEyeX, leftEyeY,
|
|
160
|
+
rightEyeX, rightEyeY,
|
|
161
|
+
noseX, noseY,
|
|
162
|
+
mouthLeftX, mouthLeftY,
|
|
163
|
+
mouthRightX, mouthRightY
|
|
164
|
+
],
|
|
165
|
+
imageWidth: imageWidth,
|
|
166
|
+
imageHeight: imageHeight,
|
|
167
|
+
yaw: Float(face.headEulerAngleY),
|
|
168
|
+
pitch: Float(face.headEulerAngleX),
|
|
169
|
+
roll: Float(face.headEulerAngleZ),
|
|
170
|
+
leftEyeOpenProbability: face.hasLeftEyeOpenProbability
|
|
171
|
+
? Float(face.leftEyeOpenProbability) : nil,
|
|
172
|
+
rightEyeOpenProbability: face.hasRightEyeOpenProbability
|
|
173
|
+
? Float(face.rightEyeOpenProbability) : nil,
|
|
174
|
+
smilingProbability: face.hasSmilingProbability
|
|
175
|
+
? Float(face.smilingProbability) : nil,
|
|
176
|
+
faceCount: faceCount
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import CoreGraphics
|
|
2
|
+
import Foundation
|
|
3
|
+
|
|
4
|
+
/// A single, upright camera-frame result used by guidance and liveness.
|
|
5
|
+
/// Port of the `FaceFrameResult` data class in `FaceFrameAnalyzer.kt`.
|
|
6
|
+
struct FaceFrameResult {
|
|
7
|
+
let rect: CGRect?
|
|
8
|
+
let landmarks: [CGFloat]?
|
|
9
|
+
let imageWidth: Int
|
|
10
|
+
let imageHeight: Int
|
|
11
|
+
/// Mean perceived brightness of the frame, 0 (black) to 255 (white).
|
|
12
|
+
var luminance: Float = 255
|
|
13
|
+
var yaw: Float = 0
|
|
14
|
+
var pitch: Float = 0
|
|
15
|
+
var roll: Float = 0
|
|
16
|
+
var leftEyeOpenProbability: Float?
|
|
17
|
+
var rightEyeOpenProbability: Float?
|
|
18
|
+
var smilingProbability: Float?
|
|
19
|
+
var antiSpoof: AntiSpoofResult?
|
|
20
|
+
var faceCount: Int
|
|
21
|
+
|
|
22
|
+
init(
|
|
23
|
+
rect: CGRect?,
|
|
24
|
+
landmarks: [CGFloat]?,
|
|
25
|
+
imageWidth: Int,
|
|
26
|
+
imageHeight: Int,
|
|
27
|
+
luminance: Float = 255,
|
|
28
|
+
yaw: Float = 0,
|
|
29
|
+
pitch: Float = 0,
|
|
30
|
+
roll: Float = 0,
|
|
31
|
+
leftEyeOpenProbability: Float? = nil,
|
|
32
|
+
rightEyeOpenProbability: Float? = nil,
|
|
33
|
+
smilingProbability: Float? = nil,
|
|
34
|
+
antiSpoof: AntiSpoofResult? = nil,
|
|
35
|
+
faceCount: Int? = nil
|
|
36
|
+
) {
|
|
37
|
+
self.rect = rect
|
|
38
|
+
self.landmarks = landmarks
|
|
39
|
+
self.imageWidth = imageWidth
|
|
40
|
+
self.imageHeight = imageHeight
|
|
41
|
+
self.luminance = luminance
|
|
42
|
+
self.yaw = yaw
|
|
43
|
+
self.pitch = pitch
|
|
44
|
+
self.roll = roll
|
|
45
|
+
self.leftEyeOpenProbability = leftEyeOpenProbability
|
|
46
|
+
self.rightEyeOpenProbability = rightEyeOpenProbability
|
|
47
|
+
self.smilingProbability = smilingProbability
|
|
48
|
+
self.antiSpoof = antiSpoof
|
|
49
|
+
self.faceCount = faceCount ?? (rect == nil ? 0 : 1)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
var hasFace: Bool { rect != nil }
|
|
53
|
+
var hasMultipleFaces: Bool { faceCount > 1 }
|
|
54
|
+
|
|
55
|
+
var isGoodPose: Bool {
|
|
56
|
+
hasFace && abs(yaw) <= 12 && abs(roll) <= 15 && abs(pitch) <= 12
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// Face-box width as a fraction of the frame width — the distance proxy.
|
|
60
|
+
var faceFill: Float {
|
|
61
|
+
guard let box = rect, imageWidth > 0 else { return 0 }
|
|
62
|
+
return Float(box.width) / Float(imageWidth)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// Strict framing gate that must hold before a liveness step begins.
|
|
66
|
+
var isPositioned: Bool {
|
|
67
|
+
guard let box = rect, imageWidth > 0, imageHeight > 0 else { return false }
|
|
68
|
+
let centerX = Float(box.midX) / Float(imageWidth)
|
|
69
|
+
let centerY = Float(box.midY) / Float(imageHeight)
|
|
70
|
+
return (0.25...0.75).contains(centerX) &&
|
|
71
|
+
(0.20...0.72).contains(centerY) &&
|
|
72
|
+
(0.22...0.72).contains(faceFill)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/// Loose framing check used while a head turn / lean is in progress.
|
|
76
|
+
var looselyInFrame: Bool {
|
|
77
|
+
guard let box = rect, imageWidth > 0, imageHeight > 0 else { return false }
|
|
78
|
+
let centerX = Float(box.midX) / Float(imageWidth)
|
|
79
|
+
let centerY = Float(box.midY) / Float(imageHeight)
|
|
80
|
+
return (0.12...0.88).contains(centerX) &&
|
|
81
|
+
(0.10...0.85).contains(centerY) &&
|
|
82
|
+
(0.14...0.88).contains(faceFill)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
func with(luminance: Float) -> FaceFrameResult {
|
|
86
|
+
var copy = self
|
|
87
|
+
copy.luminance = luminance
|
|
88
|
+
return copy
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
func with(antiSpoof: AntiSpoofResult?) -> FaceFrameResult {
|
|
92
|
+
var copy = self
|
|
93
|
+
copy.antiSpoof = antiSpoof
|
|
94
|
+
return copy
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Resolves the bundled ONNX models.
|
|
4
|
+
///
|
|
5
|
+
/// CocoaPods puts `s.resources` in the app bundle for a static library build
|
|
6
|
+
/// and in the pod's own framework bundle when the host uses `use_frameworks!`,
|
|
7
|
+
/// so both are checked.
|
|
8
|
+
enum FaceMatchBundle {
|
|
9
|
+
static func modelPath(named name: String) -> String? {
|
|
10
|
+
let candidates: [Bundle] = [Bundle(for: BundleToken.self), Bundle.main]
|
|
11
|
+
for bundle in candidates {
|
|
12
|
+
if let path = bundle.path(forResource: name, ofType: "onnx") {
|
|
13
|
+
return path
|
|
14
|
+
}
|
|
15
|
+
// use_frameworks! with a resource bundle.
|
|
16
|
+
if let bundleURL = bundle.url(forResource: "FaceMatch", withExtension: "bundle"),
|
|
17
|
+
let nested = Bundle(url: bundleURL),
|
|
18
|
+
let path = nested.path(forResource: name, ofType: "onnx") {
|
|
19
|
+
return path
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return nil
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
private final class BundleToken {}
|
|
26
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import CoreGraphics
|
|
2
|
+
import Foundation
|
|
3
|
+
|
|
4
|
+
struct FaceExtraction {
|
|
5
|
+
let embedding: [Float]
|
|
6
|
+
let faceCount: Int
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/// Port of `FaceMatchRuntime.kt` — the shared application-lifetime inference
|
|
10
|
+
/// engine used by both the native module and the camera view.
|
|
11
|
+
final class FaceMatchEngine {
|
|
12
|
+
private let detector = FaceDetectionHelper()
|
|
13
|
+
private let embedder: FaceEmbeddingHelper?
|
|
14
|
+
private let antiSpoof = AntiSpoofHelper()
|
|
15
|
+
/// Serialises every ONNX / ML Kit call, mirroring the Kotlin
|
|
16
|
+
/// `inferenceMutex`. Never taken recursively.
|
|
17
|
+
private let inferenceLock = NSLock()
|
|
18
|
+
|
|
19
|
+
private let embedderError: String?
|
|
20
|
+
|
|
21
|
+
static let shared = FaceMatchEngine()
|
|
22
|
+
|
|
23
|
+
private init() {
|
|
24
|
+
var helper: FaceEmbeddingHelper?
|
|
25
|
+
var failure: String?
|
|
26
|
+
do {
|
|
27
|
+
helper = try FaceEmbeddingHelper()
|
|
28
|
+
} catch {
|
|
29
|
+
failure = FaceMatchError.message(of: error)
|
|
30
|
+
}
|
|
31
|
+
embedder = helper
|
|
32
|
+
embedderError = failure
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
var isReady: Bool { antiSpoof.isReady && embedder != nil }
|
|
36
|
+
|
|
37
|
+
func classifyAntiSpoof(
|
|
38
|
+
_ image: CGImage,
|
|
39
|
+
faceBounds: CGRect,
|
|
40
|
+
threshold: Float
|
|
41
|
+
) -> AntiSpoofResult {
|
|
42
|
+
antiSpoof.classify(image, faceBounds: faceBounds, requestedThreshold: threshold)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
func detect(_ image: CGImage) throws -> [DetectedFace] {
|
|
46
|
+
inferenceLock.lock()
|
|
47
|
+
defer { inferenceLock.unlock() }
|
|
48
|
+
return significantFaces(try detector.detectFaces(image))
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
func extract(_ image: CGImage) throws -> FaceExtraction {
|
|
52
|
+
inferenceLock.lock()
|
|
53
|
+
defer { inferenceLock.unlock() }
|
|
54
|
+
let faces = significantFaces(try detector.detectFaces(image))
|
|
55
|
+
return try extractDetectedFace(image, faces: faces, isReference: false)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// Enhanced template path for old, printed or scanned identity photos.
|
|
59
|
+
func extractReference(_ image: CGImage) throws -> FaceExtraction {
|
|
60
|
+
inferenceLock.lock()
|
|
61
|
+
defer { inferenceLock.unlock() }
|
|
62
|
+
let faces = significantFaces(try detector.detectFaces(image))
|
|
63
|
+
return try extractDetectedFace(image, faces: faces, isReference: true)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// Fail-closed extraction path for live selfies and face comparison.
|
|
67
|
+
func extractLive(
|
|
68
|
+
_ image: CGImage,
|
|
69
|
+
threshold: Float = AntiSpoofHelper.defaultThreshold
|
|
70
|
+
) throws -> FaceExtraction {
|
|
71
|
+
inferenceLock.lock()
|
|
72
|
+
defer { inferenceLock.unlock() }
|
|
73
|
+
|
|
74
|
+
let faces = significantFaces(try detector.detectFaces(image))
|
|
75
|
+
if faces.isEmpty { throw FaceMatchError.noFace }
|
|
76
|
+
if faces.count > 1 { throw FaceMatchError.multipleFacesLive }
|
|
77
|
+
|
|
78
|
+
let passiveResult = antiSpoof.classify(
|
|
79
|
+
image,
|
|
80
|
+
faceBounds: faces[0].boundingBox,
|
|
81
|
+
requestedThreshold: threshold
|
|
82
|
+
)
|
|
83
|
+
switch passiveResult.status {
|
|
84
|
+
case .real:
|
|
85
|
+
break
|
|
86
|
+
case .spoof:
|
|
87
|
+
throw FaceMatchError.spoof
|
|
88
|
+
case .error:
|
|
89
|
+
throw FaceMatchError(
|
|
90
|
+
"E_ANTI_SPOOF_MODEL",
|
|
91
|
+
passiveResult.errorMessage ?? "Passive anti-spoofing is unavailable"
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
return try extractDetectedFace(image, faces: faces, isReference: false)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
func compare(
|
|
98
|
+
reference: CGImage,
|
|
99
|
+
selfie: CGImage,
|
|
100
|
+
antiSpoofThreshold: Float = AntiSpoofHelper.defaultThreshold
|
|
101
|
+
) throws -> FaceMatcherHelper.MatchResult {
|
|
102
|
+
let referenceEmbedding = try extractReference(reference).embedding
|
|
103
|
+
let selfieEmbedding = try extractLive(selfie, threshold: antiSpoofThreshold).embedding
|
|
104
|
+
return try FaceMatcherHelper.compare(referenceEmbedding, selfieEmbedding)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/// Apply the same face-selection policy to uploads and camera captures.
|
|
108
|
+
private func significantFaces(_ detected: [DetectedFace]) -> [DetectedFace] {
|
|
109
|
+
FaceCandidateFilter.significant(
|
|
110
|
+
detected,
|
|
111
|
+
bounds: { $0.boundingBox },
|
|
112
|
+
hasFullLandmarks: { $0.hasFullSet }
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private func extractDetectedFace(
|
|
117
|
+
_ image: CGImage,
|
|
118
|
+
faces: [DetectedFace],
|
|
119
|
+
isReference: Bool
|
|
120
|
+
) throws -> FaceExtraction {
|
|
121
|
+
if faces.isEmpty { throw FaceMatchError.noFace }
|
|
122
|
+
if faces.count > 1 { throw FaceMatchError.multipleFacesUpload }
|
|
123
|
+
guard let embedder else {
|
|
124
|
+
throw FaceMatchError("E_EMBEDDING", embedderError ?? "Embedding model is unavailable")
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
let (cropped, landmarks) = FaceAlignmentHelper.cropFaceRegion(image, face: faces[0])
|
|
128
|
+
let aligned = try FaceAlignmentHelper.alignFace(cropped, srcLandmarks: landmarks)
|
|
129
|
+
|
|
130
|
+
let embedding = isReference
|
|
131
|
+
? embedder.referenceEmbedding(for: aligned)
|
|
132
|
+
: embedder.embedding(for: aligned)
|
|
133
|
+
guard let embedding else { throw FaceMatchError.embedding }
|
|
134
|
+
return FaceExtraction(embedding: embedding, faceCount: faces.count)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Mirrors `FaceMatchException` in the Android module. The `code` strings are
|
|
4
|
+
/// part of the cross-platform contract consumed by `onError` in JS, so they
|
|
5
|
+
/// must stay identical to the Kotlin side.
|
|
6
|
+
struct FaceMatchError: LocalizedError {
|
|
7
|
+
let code: String
|
|
8
|
+
let message: String
|
|
9
|
+
|
|
10
|
+
init(_ code: String, _ message: String) {
|
|
11
|
+
self.code = code
|
|
12
|
+
self.message = message
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
var errorDescription: String? { message }
|
|
16
|
+
|
|
17
|
+
static func code(of error: Error) -> String {
|
|
18
|
+
(error as? FaceMatchError)?.code ?? "E_FACE_MATCH"
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
static func message(of error: Error) -> String {
|
|
22
|
+
(error as? FaceMatchError)?.message ?? error.localizedDescription
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Shared with FaceMatchEngine / FaceCameraView so the strings never drift.
|
|
26
|
+
static let noFace = FaceMatchError("E_NO_FACE", "No face detected in the image")
|
|
27
|
+
static let multipleFacesUpload = FaceMatchError(
|
|
28
|
+
"E_MULTIPLE_FACES",
|
|
29
|
+
"Multiple faces detected. Choose an image containing one person."
|
|
30
|
+
)
|
|
31
|
+
static let multipleFacesLive = FaceMatchError(
|
|
32
|
+
"E_MULTIPLE_FACES",
|
|
33
|
+
"Multiple faces detected. Only one person is allowed"
|
|
34
|
+
)
|
|
35
|
+
static let spoof = FaceMatchError(
|
|
36
|
+
"E_ANTI_SPOOF",
|
|
37
|
+
"We could not confirm a live face. Please try again in clear, even lighting."
|
|
38
|
+
)
|
|
39
|
+
static let embedding = FaceMatchError("E_EMBEDDING", "Could not generate a face embedding")
|
|
40
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
#import <React/RCTBridgeModule.h>
|
|
2
|
+
|
|
3
|
+
// Exported to JS as `NativeModules.FaceMatch`, matching the Android module's
|
|
4
|
+
// NAME constant so src/FaceMatch.ts works unchanged on both platforms.
|
|
5
|
+
@interface RCT_EXTERN_REMAP_MODULE (FaceMatch, FaceMatchModule, NSObject)
|
|
6
|
+
|
|
7
|
+
RCT_EXTERN_METHOD(isModelReady : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
|
|
8
|
+
|
|
9
|
+
RCT_EXTERN_METHOD(pickImage : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject)
|
|
10
|
+
|
|
11
|
+
RCT_EXTERN_METHOD(detectFaces
|
|
12
|
+
: (NSString *)uri resolver
|
|
13
|
+
: (RCTPromiseResolveBlock)resolve rejecter
|
|
14
|
+
: (RCTPromiseRejectBlock)reject)
|
|
15
|
+
|
|
16
|
+
RCT_EXTERN_METHOD(generateEmbedding
|
|
17
|
+
: (NSString *)uri resolver
|
|
18
|
+
: (RCTPromiseResolveBlock)resolve rejecter
|
|
19
|
+
: (RCTPromiseRejectBlock)reject)
|
|
20
|
+
|
|
21
|
+
RCT_EXTERN_METHOD(generateReferenceEmbedding
|
|
22
|
+
: (NSString *)uri resolver
|
|
23
|
+
: (RCTPromiseResolveBlock)resolve rejecter
|
|
24
|
+
: (RCTPromiseRejectBlock)reject)
|
|
25
|
+
|
|
26
|
+
RCT_EXTERN_METHOD(compareFaces
|
|
27
|
+
: (NSString *)referenceUri selfieUri
|
|
28
|
+
: (NSString *)selfieUri resolver
|
|
29
|
+
: (RCTPromiseResolveBlock)resolve rejecter
|
|
30
|
+
: (RCTPromiseRejectBlock)reject)
|
|
31
|
+
|
|
32
|
+
RCT_EXTERN_METHOD(compareFacesWithThreshold
|
|
33
|
+
: (NSString *)referenceUri selfieUri
|
|
34
|
+
: (NSString *)selfieUri antiSpoofThreshold
|
|
35
|
+
: (double)antiSpoofThreshold resolver
|
|
36
|
+
: (RCTPromiseResolveBlock)resolve rejecter
|
|
37
|
+
: (RCTPromiseRejectBlock)reject)
|
|
38
|
+
|
|
39
|
+
RCT_EXTERN_METHOD(compareEmbeddings
|
|
40
|
+
: (NSArray *)first second
|
|
41
|
+
: (NSArray *)second resolver
|
|
42
|
+
: (RCTPromiseResolveBlock)resolve rejecter
|
|
43
|
+
: (RCTPromiseRejectBlock)reject)
|
|
44
|
+
|
|
45
|
+
RCT_EXTERN_METHOD(discardCapture
|
|
46
|
+
: (NSString *)uri resolver
|
|
47
|
+
: (RCTPromiseResolveBlock)resolve rejecter
|
|
48
|
+
: (RCTPromiseRejectBlock)reject)
|
|
49
|
+
|
|
50
|
+
+ (BOOL)requiresMainQueueSetup
|
|
51
|
+
{
|
|
52
|
+
return NO;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
@end
|