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,288 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import PhotosUI
|
|
3
|
+
import React
|
|
4
|
+
import UIKit
|
|
5
|
+
|
|
6
|
+
/// Port of `FaceMatchModule.kt` — promise-based bridge for offline image
|
|
7
|
+
/// detection and matching. Method names, argument order, resolved shapes and
|
|
8
|
+
/// error codes match the Android module exactly.
|
|
9
|
+
@objc(FaceMatchModule)
|
|
10
|
+
final class FaceMatchModule: NSObject {
|
|
11
|
+
|
|
12
|
+
private static let embeddingSize = 512
|
|
13
|
+
|
|
14
|
+
private let queue = DispatchQueue(label: "com.facematch.sdk.module", qos: .userInitiated)
|
|
15
|
+
private var imagePickerDelegate: ImagePickerDelegate?
|
|
16
|
+
|
|
17
|
+
@objc static func requiresMainQueueSetup() -> Bool { false }
|
|
18
|
+
|
|
19
|
+
override init() {
|
|
20
|
+
super.init()
|
|
21
|
+
// Resolve the TTS voices now so the first liveness instruction is not
|
|
22
|
+
// held up by a cold asset lookup when the camera opens.
|
|
23
|
+
LivenessVoice.prewarmVoices()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// MARK: - Model
|
|
27
|
+
|
|
28
|
+
@objc(isModelReady:rejecter:)
|
|
29
|
+
func isModelReady(_ resolve: @escaping RCTPromiseResolveBlock,
|
|
30
|
+
rejecter reject: @escaping RCTPromiseRejectBlock) {
|
|
31
|
+
queue.async {
|
|
32
|
+
resolve(FaceMatchEngine.shared.isReady)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// MARK: - Detection / embeddings
|
|
37
|
+
|
|
38
|
+
@objc(detectFaces:resolver:rejecter:)
|
|
39
|
+
func detectFaces(_ uri: String,
|
|
40
|
+
resolver resolve: @escaping RCTPromiseResolveBlock,
|
|
41
|
+
rejecter reject: @escaping RCTPromiseRejectBlock) {
|
|
42
|
+
withImage(uri, resolve, reject) { image in
|
|
43
|
+
let faces = try FaceMatchEngine.shared.detect(image)
|
|
44
|
+
return [
|
|
45
|
+
"faceCount": faces.count,
|
|
46
|
+
"faces": faces.map { face in
|
|
47
|
+
[
|
|
48
|
+
"left": Double(face.boundingBox.minX),
|
|
49
|
+
"top": Double(face.boundingBox.minY),
|
|
50
|
+
"right": Double(face.boundingBox.maxX),
|
|
51
|
+
"bottom": Double(face.boundingBox.maxY),
|
|
52
|
+
"hasFullLandmarkSet": face.hasFullSet
|
|
53
|
+
] as [String: Any]
|
|
54
|
+
}
|
|
55
|
+
]
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
@objc(generateEmbedding:resolver:rejecter:)
|
|
60
|
+
func generateEmbedding(_ uri: String,
|
|
61
|
+
resolver resolve: @escaping RCTPromiseResolveBlock,
|
|
62
|
+
rejecter reject: @escaping RCTPromiseRejectBlock) {
|
|
63
|
+
withImage(uri, resolve, reject) { image in
|
|
64
|
+
let extraction = try FaceMatchEngine.shared.extract(image)
|
|
65
|
+
return [
|
|
66
|
+
"faceCount": extraction.faceCount,
|
|
67
|
+
"embedding": extraction.embedding.map { Double($0) }
|
|
68
|
+
]
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
@objc(generateReferenceEmbedding:resolver:rejecter:)
|
|
73
|
+
func generateReferenceEmbedding(_ uri: String,
|
|
74
|
+
resolver resolve: @escaping RCTPromiseResolveBlock,
|
|
75
|
+
rejecter reject: @escaping RCTPromiseRejectBlock) {
|
|
76
|
+
withImage(uri, resolve, reject) { image in
|
|
77
|
+
let extraction = try FaceMatchEngine.shared.extractReference(image)
|
|
78
|
+
return [
|
|
79
|
+
"faceCount": extraction.faceCount,
|
|
80
|
+
"embedding": extraction.embedding.map { Double($0) }
|
|
81
|
+
]
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// MARK: - Comparison
|
|
86
|
+
|
|
87
|
+
@objc(compareFaces:selfieUri:resolver:rejecter:)
|
|
88
|
+
func compareFaces(_ referenceUri: String,
|
|
89
|
+
selfieUri: String,
|
|
90
|
+
resolver resolve: @escaping RCTPromiseResolveBlock,
|
|
91
|
+
rejecter reject: @escaping RCTPromiseRejectBlock) {
|
|
92
|
+
compareFacesInternal(
|
|
93
|
+
referenceUri,
|
|
94
|
+
selfieUri,
|
|
95
|
+
AntiSpoofHelper.defaultThreshold,
|
|
96
|
+
resolve,
|
|
97
|
+
reject
|
|
98
|
+
)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
@objc(compareFacesWithThreshold:selfieUri:antiSpoofThreshold:resolver:rejecter:)
|
|
102
|
+
func compareFacesWithThreshold(_ referenceUri: String,
|
|
103
|
+
selfieUri: String,
|
|
104
|
+
antiSpoofThreshold: Double,
|
|
105
|
+
resolver resolve: @escaping RCTPromiseResolveBlock,
|
|
106
|
+
rejecter reject: @escaping RCTPromiseRejectBlock) {
|
|
107
|
+
compareFacesInternal(
|
|
108
|
+
referenceUri,
|
|
109
|
+
selfieUri,
|
|
110
|
+
Float(antiSpoofThreshold),
|
|
111
|
+
resolve,
|
|
112
|
+
reject
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private func compareFacesInternal(_ referenceUri: String,
|
|
117
|
+
_ selfieUri: String,
|
|
118
|
+
_ antiSpoofThreshold: Float,
|
|
119
|
+
_ resolve: @escaping RCTPromiseResolveBlock,
|
|
120
|
+
_ reject: @escaping RCTPromiseRejectBlock) {
|
|
121
|
+
queue.async {
|
|
122
|
+
do {
|
|
123
|
+
let reference = try ImageUtils.decode(uriString: referenceUri)
|
|
124
|
+
let selfie = try ImageUtils.decode(uriString: selfieUri)
|
|
125
|
+
let result = try FaceMatchEngine.shared.compare(
|
|
126
|
+
reference: reference,
|
|
127
|
+
selfie: selfie,
|
|
128
|
+
antiSpoofThreshold: AntiSpoofHelper.sanitizeThreshold(antiSpoofThreshold)
|
|
129
|
+
)
|
|
130
|
+
resolve(result.dictionary)
|
|
131
|
+
} catch {
|
|
132
|
+
Self.reject(reject, error)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
@objc(compareEmbeddings:second:resolver:rejecter:)
|
|
138
|
+
func compareEmbeddings(_ first: NSArray,
|
|
139
|
+
second: NSArray,
|
|
140
|
+
resolver resolve: @escaping RCTPromiseResolveBlock,
|
|
141
|
+
rejecter reject: @escaping RCTPromiseRejectBlock) {
|
|
142
|
+
queue.async {
|
|
143
|
+
do {
|
|
144
|
+
let a = try Self.floats(from: first)
|
|
145
|
+
let b = try Self.floats(from: second)
|
|
146
|
+
resolve(try FaceMatcherHelper.compare(a, b).dictionary)
|
|
147
|
+
} catch {
|
|
148
|
+
Self.reject(reject, error)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
private static func floats(from array: NSArray) throws -> [Float] {
|
|
154
|
+
guard array.count == embeddingSize else {
|
|
155
|
+
throw FaceMatchError(
|
|
156
|
+
"E_FACE_MATCH",
|
|
157
|
+
"Embedding arrays must each contain exactly \(embeddingSize) values"
|
|
158
|
+
)
|
|
159
|
+
}
|
|
160
|
+
return try array.map { element in
|
|
161
|
+
guard let number = element as? NSNumber, number.doubleValue.isFinite else {
|
|
162
|
+
throw FaceMatchError("E_FACE_MATCH", "Embedding values must be finite")
|
|
163
|
+
}
|
|
164
|
+
return number.floatValue
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// MARK: - Capture lifecycle
|
|
169
|
+
|
|
170
|
+
/// Deletes only camera captures created inside this SDK's private cache.
|
|
171
|
+
@objc(discardCapture:resolver:rejecter:)
|
|
172
|
+
func discardCapture(_ uri: String,
|
|
173
|
+
resolver resolve: @escaping RCTPromiseResolveBlock,
|
|
174
|
+
rejecter reject: @escaping RCTPromiseRejectBlock) {
|
|
175
|
+
queue.async {
|
|
176
|
+
resolve(PrivateCaptureStore.deleteIfOwned(uri))
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// MARK: - Image picker
|
|
181
|
+
|
|
182
|
+
@objc(pickImage:rejecter:)
|
|
183
|
+
func pickImage(_ resolve: @escaping RCTPromiseResolveBlock,
|
|
184
|
+
rejecter reject: @escaping RCTPromiseRejectBlock) {
|
|
185
|
+
DispatchQueue.main.async {
|
|
186
|
+
guard let presenter = Self.topViewController() else {
|
|
187
|
+
reject("E_NO_ACTIVITY", "No foreground view controller is available", nil)
|
|
188
|
+
return
|
|
189
|
+
}
|
|
190
|
+
if self.imagePickerDelegate != nil {
|
|
191
|
+
reject("E_PICKER_BUSY", "An image picker is already open", nil)
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
var configuration = PHPickerConfiguration()
|
|
196
|
+
configuration.filter = .images
|
|
197
|
+
configuration.selectionLimit = 1
|
|
198
|
+
|
|
199
|
+
let delegate = ImagePickerDelegate { [weak self] url, error in
|
|
200
|
+
self?.imagePickerDelegate = nil
|
|
201
|
+
if let error {
|
|
202
|
+
reject("E_PICKER", FaceMatchError.message(of: error), error)
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
resolve(url?.absoluteString)
|
|
206
|
+
}
|
|
207
|
+
self.imagePickerDelegate = delegate
|
|
208
|
+
|
|
209
|
+
let picker = PHPickerViewController(configuration: configuration)
|
|
210
|
+
picker.delegate = delegate
|
|
211
|
+
presenter.present(picker, animated: true)
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private static func topViewController() -> UIViewController? {
|
|
216
|
+
let scene = UIApplication.shared.connectedScenes
|
|
217
|
+
.compactMap { $0 as? UIWindowScene }
|
|
218
|
+
.first { $0.activationState == .foregroundActive }
|
|
219
|
+
var controller = (scene?.windows.first { $0.isKeyWindow } ?? scene?.windows.first)?
|
|
220
|
+
.rootViewController
|
|
221
|
+
while let presented = controller?.presentedViewController {
|
|
222
|
+
controller = presented
|
|
223
|
+
}
|
|
224
|
+
return controller
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// MARK: - Helpers
|
|
228
|
+
|
|
229
|
+
private func withImage(_ uri: String,
|
|
230
|
+
_ resolve: @escaping RCTPromiseResolveBlock,
|
|
231
|
+
_ reject: @escaping RCTPromiseRejectBlock,
|
|
232
|
+
_ operation: @escaping (CGImage) throws -> Any) {
|
|
233
|
+
queue.async {
|
|
234
|
+
do {
|
|
235
|
+
resolve(try operation(try ImageUtils.decode(uriString: uri)))
|
|
236
|
+
} catch {
|
|
237
|
+
Self.reject(reject, error)
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private static func reject(_ reject: RCTPromiseRejectBlock, _ error: Error) {
|
|
243
|
+
reject(FaceMatchError.code(of: error), FaceMatchError.message(of: error), error)
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/// Copies the picked asset into the app's temporary directory so the resulting
|
|
248
|
+
/// `file://` URI satisfies the same app-private policy the Android module
|
|
249
|
+
/// enforces, and so no long-lived grant to the photo library is retained.
|
|
250
|
+
private final class ImagePickerDelegate: NSObject, PHPickerViewControllerDelegate {
|
|
251
|
+
private let completion: (URL?, Error?) -> Void
|
|
252
|
+
|
|
253
|
+
init(completion: @escaping (URL?, Error?) -> Void) {
|
|
254
|
+
self.completion = completion
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
|
|
258
|
+
picker.dismiss(animated: true)
|
|
259
|
+
|
|
260
|
+
guard let provider = results.first?.itemProvider,
|
|
261
|
+
provider.canLoadObject(ofClass: UIImage.self) else {
|
|
262
|
+
completion(nil, nil)
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
provider.loadObject(ofClass: UIImage.self) { object, error in
|
|
267
|
+
DispatchQueue.main.async {
|
|
268
|
+
if let error {
|
|
269
|
+
self.completion(nil, error)
|
|
270
|
+
return
|
|
271
|
+
}
|
|
272
|
+
guard let image = object as? UIImage,
|
|
273
|
+
let data = image.jpegData(compressionQuality: 0.95) else {
|
|
274
|
+
self.completion(nil, nil)
|
|
275
|
+
return
|
|
276
|
+
}
|
|
277
|
+
let url = URL(fileURLWithPath: NSTemporaryDirectory())
|
|
278
|
+
.appendingPathComponent("picked-\(UUID().uuidString).jpg")
|
|
279
|
+
do {
|
|
280
|
+
try data.write(to: url, options: .atomic)
|
|
281
|
+
self.completion(url, nil)
|
|
282
|
+
} catch {
|
|
283
|
+
self.completion(nil, error)
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Port of `FaceMatcherHelper.kt` — stateless face comparison.
|
|
4
|
+
///
|
|
5
|
+
/// `faceSimilarityScore` is a sigmoid-calibrated cosine similarity in [0, 100].
|
|
6
|
+
///
|
|
7
|
+
/// Raw cosine from buffalo_sc (MobileFaceNet / ArcFace) embeddings:
|
|
8
|
+
/// Genuine (same-person) pairs : ~0.38 - 0.65
|
|
9
|
+
/// Impostor (different person) : ~0.05 - 0.32
|
|
10
|
+
///
|
|
11
|
+
/// score = sigmoid(K * (rawCosine - MID)) * 100, K = 47, MID = 0.338
|
|
12
|
+
///
|
|
13
|
+
/// Key calibration points:
|
|
14
|
+
/// raw 0.375 -> ~85 % (low genuine / long age gap)
|
|
15
|
+
/// raw 0.351 -> ~65 % (Possible Match boundary)
|
|
16
|
+
/// raw 0.320 -> ~30 % (upper documented impostor range)
|
|
17
|
+
/// raw 0.200 -> <1 % (clear impostor)
|
|
18
|
+
///
|
|
19
|
+
/// These constants must stay in sync with the Kotlin matcher and the Python
|
|
20
|
+
/// backend's `matcher.py`, otherwise iOS scores drift away from the shared
|
|
21
|
+
/// acceptance thresholds used by the app screens.
|
|
22
|
+
enum FaceMatcherHelper {
|
|
23
|
+
private static let sigMid = 0.338
|
|
24
|
+
private static let sigK = 47.0
|
|
25
|
+
|
|
26
|
+
private static let thresholdMatch: Float = 80.0
|
|
27
|
+
private static let thresholdPossible: Float = 65.0
|
|
28
|
+
|
|
29
|
+
enum MatchStatus: String {
|
|
30
|
+
case match = "match"
|
|
31
|
+
case possibleMatch = "possible_match"
|
|
32
|
+
case noMatch = "no_match"
|
|
33
|
+
|
|
34
|
+
var label: String {
|
|
35
|
+
switch self {
|
|
36
|
+
case .match: return "Match"
|
|
37
|
+
case .possibleMatch: return "Possible Match"
|
|
38
|
+
case .noMatch: return "No Match"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
struct MatchResult {
|
|
44
|
+
/// Sigmoid-calibrated similarity for this pair — 0.0 to 100.0.
|
|
45
|
+
let faceSimilarityScore: Float
|
|
46
|
+
let matchStatus: MatchStatus
|
|
47
|
+
let isMatch: Bool
|
|
48
|
+
|
|
49
|
+
var dictionary: [String: Any] {
|
|
50
|
+
[
|
|
51
|
+
"similarityScore": Double(faceSimilarityScore),
|
|
52
|
+
"status": matchStatus.rawValue,
|
|
53
|
+
"label": matchStatus.label,
|
|
54
|
+
"isMatch": isMatch
|
|
55
|
+
]
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// Map raw cosine in [0, 1] to a calibrated score in [0, 100].
|
|
60
|
+
private static func sigmoidScore(_ rawCosine: Double) -> Float {
|
|
61
|
+
Float(1.0 / (1.0 + exp(-sigK * (rawCosine - sigMid))) * 100.0)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
static func compare(_ first: [Float], _ second: [Float]) throws -> MatchResult {
|
|
65
|
+
guard first.count == second.count else {
|
|
66
|
+
throw FaceMatchError(
|
|
67
|
+
"E_FACE_MATCH",
|
|
68
|
+
"Embedding size mismatch: \(first.count) vs \(second.count)"
|
|
69
|
+
)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
var dot = 0.0
|
|
73
|
+
var normFirst = 0.0
|
|
74
|
+
var normSecond = 0.0
|
|
75
|
+
for index in first.indices {
|
|
76
|
+
let a = Double(first[index])
|
|
77
|
+
let b = Double(second[index])
|
|
78
|
+
guard a.isFinite, b.isFinite else {
|
|
79
|
+
throw FaceMatchError("E_FACE_MATCH", "Embedding values must be finite")
|
|
80
|
+
}
|
|
81
|
+
dot += a * b
|
|
82
|
+
normFirst += a * a
|
|
83
|
+
normSecond += b * b
|
|
84
|
+
}
|
|
85
|
+
guard normFirst > 1e-12, normSecond > 1e-12 else {
|
|
86
|
+
throw FaceMatchError("E_FACE_MATCH", "Embeddings must have non-zero norm")
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let rawCosine = min(max(dot / (normFirst * normSecond).squareRoot(), 0.0), 1.0)
|
|
90
|
+
let faceSimilarityScore = (sigmoidScore(rawCosine) * 100).rounded() / 100
|
|
91
|
+
|
|
92
|
+
let matchStatus: MatchStatus
|
|
93
|
+
if faceSimilarityScore >= thresholdMatch {
|
|
94
|
+
matchStatus = .match
|
|
95
|
+
} else if faceSimilarityScore >= thresholdPossible {
|
|
96
|
+
matchStatus = .possibleMatch
|
|
97
|
+
} else {
|
|
98
|
+
matchStatus = .noMatch
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return MatchResult(
|
|
102
|
+
faceSimilarityScore: faceSimilarityScore,
|
|
103
|
+
matchStatus: matchStatus,
|
|
104
|
+
isMatch: matchStatus == .match
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import CoreGraphics
|
|
2
|
+
import Foundation
|
|
3
|
+
import UIKit
|
|
4
|
+
|
|
5
|
+
/// Port of `FaceOverlayView.kt`.
|
|
6
|
+
///
|
|
7
|
+
/// By design this view draws only the oval frame, its corner brackets and a
|
|
8
|
+
/// thin edge progress arc — never text, cards or cues that sit over the face.
|
|
9
|
+
/// All instructions live in the React Native strip outside the preview so the
|
|
10
|
+
/// camera feed stays completely visible.
|
|
11
|
+
///
|
|
12
|
+
/// Android points are density-independent pixels; on iOS a point already is,
|
|
13
|
+
/// so the `dp()` values port across unchanged.
|
|
14
|
+
final class FaceOverlayView: UIView {
|
|
15
|
+
private enum Guide {
|
|
16
|
+
case searching, warn, positioning, active, complete
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
private let colorSearch = UIColor(red: 0.58, green: 0.64, blue: 0.72, alpha: 1) // #94A3B8
|
|
20
|
+
private let colorWarn = UIColor(red: 0.97, green: 0.44, blue: 0.44, alpha: 1) // #F87171
|
|
21
|
+
private let colorAmber = UIColor(red: 0.98, green: 0.75, blue: 0.14, alpha: 1) // #FBBF24
|
|
22
|
+
private let colorGreen = UIColor(red: 0.20, green: 0.83, blue: 0.60, alpha: 1) // #34D399
|
|
23
|
+
private let colorInk = UIColor(red: 0.96, green: 0.96, blue: 0.98, alpha: 1) // #F4F6FB
|
|
24
|
+
|
|
25
|
+
private var frameResult = FaceFrameResult(rect: nil, landmarks: nil, imageWidth: 1, imageHeight: 1)
|
|
26
|
+
private var progress = LivenessProgress(
|
|
27
|
+
currentAction: nil,
|
|
28
|
+
completedActions: [],
|
|
29
|
+
isComplete: false,
|
|
30
|
+
promptKey: .positionFace
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
private var displayLink: CADisplayLink?
|
|
34
|
+
private var startTime: CFTimeInterval = 0
|
|
35
|
+
private var elapsedMs: Double = 0
|
|
36
|
+
|
|
37
|
+
override init(frame: CGRect) {
|
|
38
|
+
super.init(frame: frame)
|
|
39
|
+
backgroundColor = .clear
|
|
40
|
+
isOpaque = false
|
|
41
|
+
isUserInteractionEnabled = false
|
|
42
|
+
contentMode = .redraw
|
|
43
|
+
// draw(_:) rasterises a view the size of the whole camera frame on
|
|
44
|
+
// every tick. Letting Core Animation run that on its own thread keeps
|
|
45
|
+
// the per-frame cost off the main thread, where React Native is doing
|
|
46
|
+
// its own layout and mounting work for the same events.
|
|
47
|
+
layer.drawsAsynchronously = true
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
required init?(coder: NSCoder) {
|
|
51
|
+
fatalError("init(coder:) is not supported")
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
override func didMoveToWindow() {
|
|
55
|
+
super.didMoveToWindow()
|
|
56
|
+
if window == nil { stopAnimating() } else { startAnimating() }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
func update(frame result: FaceFrameResult, progress newProgress: LivenessProgress) {
|
|
60
|
+
frameResult = result
|
|
61
|
+
progress = newProgress
|
|
62
|
+
if displayLink == nil { setNeedsDisplay() }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
func reset() {
|
|
66
|
+
frameResult = FaceFrameResult(rect: nil, landmarks: nil, imageWidth: 1, imageHeight: 1)
|
|
67
|
+
progress = LivenessProgress(
|
|
68
|
+
currentAction: nil,
|
|
69
|
+
completedActions: [],
|
|
70
|
+
isComplete: false,
|
|
71
|
+
promptKey: .positionFace
|
|
72
|
+
)
|
|
73
|
+
setNeedsDisplay()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
func stopAnimating() {
|
|
77
|
+
displayLink?.invalidate()
|
|
78
|
+
displayLink = nil
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private func startAnimating() {
|
|
82
|
+
guard displayLink == nil else { return }
|
|
83
|
+
startTime = 0
|
|
84
|
+
let link = CADisplayLink(target: self, selector: #selector(tick(_:)))
|
|
85
|
+
// The pulse and scan arc read fine at 30fps, and halving the redraw
|
|
86
|
+
// rate leaves the main thread free for React Native's mounting work.
|
|
87
|
+
link.preferredFramesPerSecond = 30
|
|
88
|
+
link.add(to: .main, forMode: .common)
|
|
89
|
+
displayLink = link
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
@objc private func tick(_ link: CADisplayLink) {
|
|
93
|
+
if startTime == 0 { startTime = link.timestamp }
|
|
94
|
+
elapsedMs = (link.timestamp - startTime) * 1000
|
|
95
|
+
setNeedsDisplay()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
override func draw(_ rect: CGRect) {
|
|
99
|
+
guard let context = UIGraphicsGetCurrentContext() else { return }
|
|
100
|
+
let width = bounds.width
|
|
101
|
+
let height = bounds.height
|
|
102
|
+
guard width > 0, height > 0 else { return }
|
|
103
|
+
|
|
104
|
+
let guide = resolveGuide(frameResult, progress)
|
|
105
|
+
let accent: UIColor
|
|
106
|
+
switch guide {
|
|
107
|
+
case .searching: accent = colorSearch
|
|
108
|
+
case .warn: accent = colorWarn
|
|
109
|
+
case .positioning: accent = colorAmber
|
|
110
|
+
case .active, .complete: accent = colorGreen
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
let ovalWidth = min(width * 0.68, 300)
|
|
114
|
+
let ovalHeight = max(min(ovalWidth * 1.32, height * 0.72), 170)
|
|
115
|
+
let centerX = width / 2
|
|
116
|
+
let centerY = height * 0.46
|
|
117
|
+
let oval = CGRect(
|
|
118
|
+
x: centerX - ovalWidth / 2,
|
|
119
|
+
y: centerY - ovalHeight / 2,
|
|
120
|
+
width: ovalWidth,
|
|
121
|
+
height: ovalHeight
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
let pulse = CGFloat(0.5 + 0.5 * sin(elapsedMs / 520.0))
|
|
125
|
+
|
|
126
|
+
context.setLineCap(.round)
|
|
127
|
+
context.setLineJoin(.round)
|
|
128
|
+
|
|
129
|
+
// Faint track.
|
|
130
|
+
let trackPath = UIBezierPath(ovalIn: oval)
|
|
131
|
+
trackPath.lineWidth = 2.5
|
|
132
|
+
if guide == .searching {
|
|
133
|
+
context.saveGState()
|
|
134
|
+
context.setLineDash(phase: 0, lengths: [3, 9])
|
|
135
|
+
accent.withAlphaComponent(0.7).setStroke()
|
|
136
|
+
trackPath.stroke()
|
|
137
|
+
context.restoreGState()
|
|
138
|
+
} else {
|
|
139
|
+
accent.withAlphaComponent(0.28).setStroke()
|
|
140
|
+
trackPath.stroke()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if guide != .searching {
|
|
144
|
+
let ring = UIBezierPath(ovalIn: oval)
|
|
145
|
+
ring.lineWidth = 4
|
|
146
|
+
accent.withAlphaComponent(0.96).setStroke()
|
|
147
|
+
ring.stroke()
|
|
148
|
+
|
|
149
|
+
let glow = UIBezierPath(ovalIn: oval)
|
|
150
|
+
glow.lineWidth = 10 + 8 * pulse
|
|
151
|
+
accent.withAlphaComponent(0.08 + 0.14 * pulse).setStroke()
|
|
152
|
+
glow.stroke()
|
|
153
|
+
} else {
|
|
154
|
+
// Rotating scan arc while looking for a face.
|
|
155
|
+
let head = CGFloat(elapsedMs / 6).truncatingRemainder(dividingBy: 360)
|
|
156
|
+
for index in 0..<4 {
|
|
157
|
+
let path = arcPath(in: oval, startDegrees: head - CGFloat(index) * 14 - 22, sweepDegrees: 20)
|
|
158
|
+
path.lineWidth = 4
|
|
159
|
+
colorSearch.withAlphaComponent(0.6 - CGFloat(index) * 0.13).setStroke()
|
|
160
|
+
path.stroke()
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Corner brackets frame the target while the face is being placed.
|
|
165
|
+
if guide == .searching || guide == .positioning || guide == .warn {
|
|
166
|
+
drawCornerBrackets(oval: oval, accent: accent)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Edge progress arc for the current step's confidence — drawn on the
|
|
170
|
+
// frame edge only, never across the face.
|
|
171
|
+
if guide == .active && progress.actionProgress > 0.01 {
|
|
172
|
+
let sweep = 360 * CGFloat(min(max(progress.actionProgress, 0), 1))
|
|
173
|
+
let path = arcPath(in: oval, startDegrees: -90, sweepDegrees: sweep)
|
|
174
|
+
path.lineWidth = 5
|
|
175
|
+
colorGreen.withAlphaComponent(0.98).setStroke()
|
|
176
|
+
path.stroke()
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Completed-step ticks along the top of the frame.
|
|
180
|
+
if (1...6).contains(progress.stepCount) {
|
|
181
|
+
drawStepTicks(oval: oval)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
private func resolveGuide(_ result: FaceFrameResult, _ state: LivenessProgress) -> Guide {
|
|
186
|
+
if state.isComplete { return .complete }
|
|
187
|
+
if result.hasMultipleFaces { return .warn }
|
|
188
|
+
if !result.hasFace { return .searching }
|
|
189
|
+
if result.antiSpoof?.status == .error { return .warn }
|
|
190
|
+
if result.antiSpoof?.status == .spoof { return .warn }
|
|
191
|
+
if result.antiSpoof == nil { return .positioning }
|
|
192
|
+
if !result.isPositioned && state.cueAction == nil { return .positioning }
|
|
193
|
+
return .active
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/// Android's `Canvas.drawArc` on a RectF; UIKit has no elliptical arc, so a
|
|
197
|
+
/// circular arc is scaled into the oval. Both use degrees measured from
|
|
198
|
+
/// 3 o'clock, increasing clockwise in a y-down space.
|
|
199
|
+
private func arcPath(in oval: CGRect, startDegrees: CGFloat, sweepDegrees: CGFloat) -> UIBezierPath {
|
|
200
|
+
let radius: CGFloat = 0.5
|
|
201
|
+
let path = UIBezierPath(
|
|
202
|
+
arcCenter: .zero,
|
|
203
|
+
radius: radius,
|
|
204
|
+
startAngle: startDegrees * .pi / 180,
|
|
205
|
+
endAngle: (startDegrees + sweepDegrees) * .pi / 180,
|
|
206
|
+
clockwise: sweepDegrees >= 0
|
|
207
|
+
)
|
|
208
|
+
var transform = CGAffineTransform(translationX: oval.midX, y: oval.midY)
|
|
209
|
+
transform = transform.scaledBy(x: oval.width, y: oval.height)
|
|
210
|
+
path.apply(transform)
|
|
211
|
+
return path
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private func drawCornerBrackets(oval: CGRect, accent: UIColor) {
|
|
215
|
+
let length: CGFloat = 24
|
|
216
|
+
let gap: CGFloat = 12
|
|
217
|
+
let path = UIBezierPath()
|
|
218
|
+
let left = oval.minX - gap
|
|
219
|
+
let top = oval.minY - gap
|
|
220
|
+
let right = oval.maxX + gap
|
|
221
|
+
let bottom = oval.maxY + gap
|
|
222
|
+
|
|
223
|
+
func segment(_ from: CGPoint, _ to: CGPoint) {
|
|
224
|
+
path.move(to: from)
|
|
225
|
+
path.addLine(to: to)
|
|
226
|
+
}
|
|
227
|
+
segment(CGPoint(x: left, y: top + length), CGPoint(x: left, y: top))
|
|
228
|
+
segment(CGPoint(x: left, y: top), CGPoint(x: left + length, y: top))
|
|
229
|
+
segment(CGPoint(x: right - length, y: top), CGPoint(x: right, y: top))
|
|
230
|
+
segment(CGPoint(x: right, y: top), CGPoint(x: right, y: top + length))
|
|
231
|
+
segment(CGPoint(x: left, y: bottom - length), CGPoint(x: left, y: bottom))
|
|
232
|
+
segment(CGPoint(x: left, y: bottom), CGPoint(x: left + length, y: bottom))
|
|
233
|
+
segment(CGPoint(x: right - length, y: bottom), CGPoint(x: right, y: bottom))
|
|
234
|
+
segment(CGPoint(x: right, y: bottom), CGPoint(x: right, y: bottom - length))
|
|
235
|
+
|
|
236
|
+
path.lineWidth = 3
|
|
237
|
+
path.lineCapStyle = .round
|
|
238
|
+
accent.withAlphaComponent(0.9).setStroke()
|
|
239
|
+
path.stroke()
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private func drawStepTicks(oval: CGRect) {
|
|
243
|
+
let count = progress.stepCount
|
|
244
|
+
let done = min(max(progress.stepIndex, 0), count)
|
|
245
|
+
let dotRadius: CGFloat = 3.5
|
|
246
|
+
let gap: CGFloat = 13
|
|
247
|
+
let totalWidth = CGFloat(count - 1) * gap
|
|
248
|
+
var x = oval.midX - totalWidth / 2
|
|
249
|
+
let y = oval.minY - 30
|
|
250
|
+
|
|
251
|
+
for index in 0..<count {
|
|
252
|
+
if index < done {
|
|
253
|
+
colorGreen.setFill()
|
|
254
|
+
UIBezierPath(
|
|
255
|
+
arcCenter: CGPoint(x: x, y: y),
|
|
256
|
+
radius: dotRadius,
|
|
257
|
+
startAngle: 0,
|
|
258
|
+
endAngle: .pi * 2,
|
|
259
|
+
clockwise: true
|
|
260
|
+
).fill()
|
|
261
|
+
} else if index == done {
|
|
262
|
+
colorAmber.withAlphaComponent(0.95).setFill()
|
|
263
|
+
UIBezierPath(
|
|
264
|
+
arcCenter: CGPoint(x: x, y: y),
|
|
265
|
+
radius: dotRadius + 1.5,
|
|
266
|
+
startAngle: 0,
|
|
267
|
+
endAngle: .pi * 2,
|
|
268
|
+
clockwise: true
|
|
269
|
+
).fill()
|
|
270
|
+
} else {
|
|
271
|
+
let path = UIBezierPath(
|
|
272
|
+
arcCenter: CGPoint(x: x, y: y),
|
|
273
|
+
radius: dotRadius,
|
|
274
|
+
startAngle: 0,
|
|
275
|
+
endAngle: .pi * 2,
|
|
276
|
+
clockwise: true
|
|
277
|
+
)
|
|
278
|
+
path.lineWidth = 1.5
|
|
279
|
+
colorInk.withAlphaComponent(0.4).setStroke()
|
|
280
|
+
path.stroke()
|
|
281
|
+
}
|
|
282
|
+
x += gap
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|