react-native-face-match-sdk 0.0.0-stage → 1.0.1
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/README.md +174 -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 +38 -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,505 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
enum LivenessAction: String, CaseIterable {
|
|
4
|
+
case blink = "blink"
|
|
5
|
+
case smile = "smile"
|
|
6
|
+
case left = "left"
|
|
7
|
+
case right = "right"
|
|
8
|
+
case up = "up"
|
|
9
|
+
case near = "near"
|
|
10
|
+
case far = "far"
|
|
11
|
+
case hold = "hold"
|
|
12
|
+
|
|
13
|
+
var prompt: LivenessPrompt {
|
|
14
|
+
switch self {
|
|
15
|
+
case .blink: return .blink
|
|
16
|
+
case .smile: return .smile
|
|
17
|
+
case .left: return .turnLeft
|
|
18
|
+
case .right: return .turnRight
|
|
19
|
+
case .up: return .lookUp
|
|
20
|
+
case .near: return .comeCloser
|
|
21
|
+
case .far: return .goBack
|
|
22
|
+
case .hold: return .holdStill
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
struct LivenessProgress {
|
|
28
|
+
let currentAction: LivenessAction?
|
|
29
|
+
let completedActions: [LivenessAction]
|
|
30
|
+
let isComplete: Bool
|
|
31
|
+
let promptKey: LivenessPrompt
|
|
32
|
+
let cueAction: LivenessAction?
|
|
33
|
+
/// Confidence toward completing the current action, 0..1 (overlay meter).
|
|
34
|
+
let actionProgress: Float
|
|
35
|
+
let stepIndex: Int
|
|
36
|
+
let stepCount: Int
|
|
37
|
+
|
|
38
|
+
init(
|
|
39
|
+
currentAction: LivenessAction?,
|
|
40
|
+
completedActions: [LivenessAction],
|
|
41
|
+
isComplete: Bool,
|
|
42
|
+
promptKey: LivenessPrompt,
|
|
43
|
+
cueAction: LivenessAction? = nil,
|
|
44
|
+
actionProgress: Float = 0,
|
|
45
|
+
stepIndex: Int = 0,
|
|
46
|
+
stepCount: Int = 0
|
|
47
|
+
) {
|
|
48
|
+
self.currentAction = currentAction
|
|
49
|
+
self.completedActions = completedActions
|
|
50
|
+
self.isComplete = isComplete
|
|
51
|
+
self.promptKey = promptKey
|
|
52
|
+
self.cueAction = cueAction
|
|
53
|
+
self.actionProgress = actionProgress
|
|
54
|
+
self.stepIndex = stepIndex
|
|
55
|
+
self.stepCount = stepCount
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
var instruction: String { promptKey.en }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Port of `LivenessDetector.kt` — a deterministic active-liveness state machine.
|
|
62
|
+
///
|
|
63
|
+
/// Every session runs exactly three steps: a blink (which a photo cannot do) and
|
|
64
|
+
/// one movement challenge in a randomised order, then a short neutral hold. Only
|
|
65
|
+
/// ONE movement is ever drawn, so a session never asks the user to turn left and
|
|
66
|
+
/// then right — the QA complaint this shape was built to fix.
|
|
67
|
+
///
|
|
68
|
+
/// Because the challenge set is short, the anti-photo guarantee rests on the
|
|
69
|
+
/// blink's open -> closed -> open transition rather than on step count, and the
|
|
70
|
+
/// anti-replay guarantee rests on the passive MiniFASNetV2 model: it runs on
|
|
71
|
+
/// every analysed frame, `passiveConfidenceOk()` additionally requires most of
|
|
72
|
+
/// the recent window to have scored REAL before liveness may complete, and
|
|
73
|
+
/// `extractLive()` re-checks the captured still fail-closed. The user must
|
|
74
|
+
/// return to a neutral face between steps, and per-step and total timeouts reset
|
|
75
|
+
/// the flow.
|
|
76
|
+
///
|
|
77
|
+
/// Every constant below is deliberately identical to the Kotlin original: ML
|
|
78
|
+
/// Kit reports the same probabilities and Euler angles on both platforms, so
|
|
79
|
+
/// the thresholds must not be re-tuned per platform.
|
|
80
|
+
final class LivenessDetector {
|
|
81
|
+
private enum Constants {
|
|
82
|
+
// Every *Frames constant is denominated in analysis frames, which run at
|
|
83
|
+
// roughly 15 fps (~67 ms) here — so one frame trimmed is ~67 ms off every
|
|
84
|
+
// session that passes through the gate.
|
|
85
|
+
//
|
|
86
|
+
// requiredStableFrames stays at 2: at ~134 ms it is already negligible,
|
|
87
|
+
// and a single frame would let one noisy yaw estimate satisfy the only
|
|
88
|
+
// movement challenge in the session.
|
|
89
|
+
static let requiredStableFrames = 2
|
|
90
|
+
static let requiredNeutralFrames = 2
|
|
91
|
+
static let finalStableFrames = 2
|
|
92
|
+
/// Long enough to cover the shutter latency that follows it, no longer.
|
|
93
|
+
static let holdFrames = 5
|
|
94
|
+
static let neutralDegrees: Float = 10
|
|
95
|
+
static let headYawTarget: Float = 18
|
|
96
|
+
static let headPitchTarget: Float = 14
|
|
97
|
+
static let minLuminance: Float = 42
|
|
98
|
+
static let eyeOpenThreshold: Float = 0.55
|
|
99
|
+
static let eyeClosedMaximum: Float = 0.55
|
|
100
|
+
static let eyeClosedAverage: Float = 0.42
|
|
101
|
+
static let smileThreshold: Float = 0.62
|
|
102
|
+
/// Inter-step gates: loose, so a naturally wide mouth cannot stall them.
|
|
103
|
+
static let smileNeutralMax: Float = 0.70
|
|
104
|
+
/// The terminal hold only: the frame auto-capture photographs.
|
|
105
|
+
static let smileCaptureMax: Float = 0.45
|
|
106
|
+
static let distanceNearRatio: Float = 1.20
|
|
107
|
+
static let distanceFarRatio: Float = 0.82
|
|
108
|
+
// 13 s was sized for the smile step that no longer exists. 9 s is still
|
|
109
|
+
// ~3x the p95 of the two remaining steps with room for one missed blink on
|
|
110
|
+
// a slow device. The 45 s session budget is unchanged, so a hesitant user
|
|
111
|
+
// gets another retryStep rather than losing the session outright.
|
|
112
|
+
static let stepTimeoutMs: Int64 = 9_000
|
|
113
|
+
static let challengeTimeoutMs: Int64 = 45_000
|
|
114
|
+
/// Consecutive out-of-frame frames tolerated while an action is being
|
|
115
|
+
/// performed. A deliberate head turn briefly pushes the face box past
|
|
116
|
+
/// the loose bounds; abandoning the step on the first such frame made
|
|
117
|
+
/// the prompt oscillate several times a second, which both spammed
|
|
118
|
+
/// React Native with re-renders and made the turn hard to complete.
|
|
119
|
+
static let outOfFrameGraceFrames = 3
|
|
120
|
+
/// Consecutive spoof frames tolerated before earned progress is dropped.
|
|
121
|
+
static let spoofGraceFrames = 3
|
|
122
|
+
static let passiveWindowFrames = 10
|
|
123
|
+
static let passiveMinRealFrames = 7
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private var actions: [LivenessAction] = []
|
|
127
|
+
private var currentIndex = 0
|
|
128
|
+
private var needsNeutral = true
|
|
129
|
+
private var stableFrames = 0
|
|
130
|
+
private var neutralFrames = 0
|
|
131
|
+
private var blinkClosedSeen = false
|
|
132
|
+
private var baselineFill: Float = 0
|
|
133
|
+
private var actionProgressValue: Float = 0
|
|
134
|
+
private var stepDeadlineMs: Int64 = 0
|
|
135
|
+
private var challengeStartedMs: Int64 = 0
|
|
136
|
+
private var outOfFrameFrames = 0
|
|
137
|
+
private var spoofFrames = 0
|
|
138
|
+
/// Rolling window of recent passive anti-spoof verdicts, newest last.
|
|
139
|
+
private var passiveWindow: [Bool] = []
|
|
140
|
+
|
|
141
|
+
init() {
|
|
142
|
+
actions = Self.randomChallenge()
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
@discardableResult
|
|
146
|
+
func reset(_ requested: [String]? = nil) -> LivenessProgress {
|
|
147
|
+
let mapped = requested?
|
|
148
|
+
.compactMap { LivenessAction(rawValue: $0.lowercased()) }
|
|
149
|
+
.reduce(into: [LivenessAction]()) { result, action in
|
|
150
|
+
if !result.contains(action) { result.append(action) }
|
|
151
|
+
}
|
|
152
|
+
actions = (mapped?.isEmpty == false
|
|
153
|
+
? Self.withTerminalHold(mapped!)
|
|
154
|
+
: Self.randomChallenge())
|
|
155
|
+
currentIndex = 0
|
|
156
|
+
needsNeutral = true
|
|
157
|
+
stableFrames = 0
|
|
158
|
+
neutralFrames = 0
|
|
159
|
+
blinkClosedSeen = false
|
|
160
|
+
baselineFill = 0
|
|
161
|
+
actionProgressValue = 0
|
|
162
|
+
stepDeadlineMs = 0
|
|
163
|
+
outOfFrameFrames = 0
|
|
164
|
+
spoofFrames = 0
|
|
165
|
+
passiveWindow.removeAll(keepingCapacity: true)
|
|
166
|
+
challengeStartedMs = Self.nowMs()
|
|
167
|
+
return progress(.getReady)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
func update(_ frame: FaceFrameResult) -> LivenessProgress {
|
|
171
|
+
if !frame.hasFace {
|
|
172
|
+
pauseCurrentSignal()
|
|
173
|
+
return progress(.positionFace)
|
|
174
|
+
}
|
|
175
|
+
if frame.hasMultipleFaces {
|
|
176
|
+
resetAllProgress()
|
|
177
|
+
return progress(.multipleFaces)
|
|
178
|
+
}
|
|
179
|
+
switch frame.antiSpoof?.status {
|
|
180
|
+
case .some(.real):
|
|
181
|
+
spoofFrames = 0
|
|
182
|
+
recordPassive(true)
|
|
183
|
+
// Motion and lighting make individual frame scores fluctuate, and a
|
|
184
|
+
// spoof frame never advances a step either way. Only a sustained run of
|
|
185
|
+
// them discards the progress already earned, so one noisy score no
|
|
186
|
+
// longer costs the user the whole step.
|
|
187
|
+
case .some(.spoof):
|
|
188
|
+
recordPassive(false)
|
|
189
|
+
spoofFrames += 1
|
|
190
|
+
if spoofFrames >= Constants.spoofGraceFrames { pauseCurrentSignal() }
|
|
191
|
+
return progress(.spoofBlocked)
|
|
192
|
+
case .some(.error):
|
|
193
|
+
recordPassive(false)
|
|
194
|
+
resetAllProgress()
|
|
195
|
+
return progress(.spoofBlocked)
|
|
196
|
+
case .none:
|
|
197
|
+
pauseCurrentSignal()
|
|
198
|
+
return progress(.verifyReal)
|
|
199
|
+
}
|
|
200
|
+
if currentIndex >= actions.count {
|
|
201
|
+
return progress(.verifying)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
let action = actions[currentIndex]
|
|
205
|
+
let performing = !needsNeutral
|
|
206
|
+
|
|
207
|
+
// Strict framing gate before each step; a looser one while a move is in
|
|
208
|
+
// progress so a deliberate head turn / lean is not rejected mid-action.
|
|
209
|
+
if !performing && frame.luminance < Constants.minLuminance {
|
|
210
|
+
pauseCurrentSignal()
|
|
211
|
+
return progress(.lowLight)
|
|
212
|
+
}
|
|
213
|
+
if !performing && !frame.isPositioned {
|
|
214
|
+
pauseCurrentSignal()
|
|
215
|
+
return progress(positionPrompt(frame))
|
|
216
|
+
}
|
|
217
|
+
if performing && !frame.looselyInFrame {
|
|
218
|
+
outOfFrameFrames += 1
|
|
219
|
+
if outOfFrameFrames >= Constants.outOfFrameGraceFrames {
|
|
220
|
+
pauseCurrentSignal()
|
|
221
|
+
needsNeutral = true
|
|
222
|
+
outOfFrameFrames = 0
|
|
223
|
+
return progress(.keepInFrame)
|
|
224
|
+
}
|
|
225
|
+
// Within the grace window the step keeps evaluating, so a normal
|
|
226
|
+
// turn does not bounce the user back to "look straight".
|
|
227
|
+
} else {
|
|
228
|
+
outOfFrameFrames = 0
|
|
229
|
+
}
|
|
230
|
+
if abs(frame.roll) > 26 {
|
|
231
|
+
pauseCurrentSignal()
|
|
232
|
+
return progress(.holdUpright)
|
|
233
|
+
}
|
|
234
|
+
if Self.nowMs() - challengeStartedMs > Constants.challengeTimeoutMs {
|
|
235
|
+
resetAllProgress()
|
|
236
|
+
return progress(.tooSlow)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
let leftEye = frame.leftEyeOpenProbability
|
|
240
|
+
let rightEye = frame.rightEyeOpenProbability
|
|
241
|
+
let smile = frame.smilingProbability ?? 0
|
|
242
|
+
let eyesOpen = (leftEye ?? 1) >= Constants.eyeOpenThreshold &&
|
|
243
|
+
(rightEye ?? 1) >= Constants.eyeOpenThreshold
|
|
244
|
+
var eyesClosed = false
|
|
245
|
+
if let leftEye, let rightEye {
|
|
246
|
+
eyesClosed = leftEye <= Constants.eyeClosedMaximum &&
|
|
247
|
+
rightEye <= Constants.eyeClosedMaximum &&
|
|
248
|
+
(leftEye + rightEye) / 2 <= Constants.eyeClosedAverage
|
|
249
|
+
}
|
|
250
|
+
let poseNeutral = abs(frame.yaw) < Constants.neutralDegrees &&
|
|
251
|
+
abs(frame.pitch) < Constants.neutralDegrees
|
|
252
|
+
let neutral = poseNeutral && eyesOpen && smile < Constants.smileNeutralMax
|
|
253
|
+
// Only the terminal hold — the frame auto-capture actually photographs —
|
|
254
|
+
// demands a non-smiling face. A relaxed wide mouth must not be able to
|
|
255
|
+
// stall every inter-step gate, which is what the old single 0.35 bound did.
|
|
256
|
+
let captureNeutral = neutral && smile < Constants.smileCaptureMax
|
|
257
|
+
|
|
258
|
+
if needsNeutral {
|
|
259
|
+
actionProgressValue = 0
|
|
260
|
+
neutralFrames = neutral ? neutralFrames + 1 : 0
|
|
261
|
+
if neutralFrames >= Constants.requiredNeutralFrames {
|
|
262
|
+
needsNeutral = false
|
|
263
|
+
neutralFrames = 0
|
|
264
|
+
blinkClosedSeen = false
|
|
265
|
+
stableFrames = 0
|
|
266
|
+
baselineFill = frame.faceFill
|
|
267
|
+
stepDeadlineMs = Self.nowMs() + Constants.stepTimeoutMs
|
|
268
|
+
return progress(action.prompt, cueAction: action, actionProgress: 0)
|
|
269
|
+
}
|
|
270
|
+
return progress(.lookStraight)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if Self.nowMs() > stepDeadlineMs {
|
|
274
|
+
pauseCurrentSignal()
|
|
275
|
+
needsNeutral = true
|
|
276
|
+
return progress(.retryStep)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
switch action {
|
|
280
|
+
case .blink:
|
|
281
|
+
return updateBlink(eyesOpen: eyesOpen, eyesClosed: eyesClosed, poseNeutral: poseNeutral)
|
|
282
|
+
case .smile:
|
|
283
|
+
return updateSmile(smile)
|
|
284
|
+
case .hold:
|
|
285
|
+
return updateHold(captureNeutral)
|
|
286
|
+
case .near:
|
|
287
|
+
return updateDistance(frame, closer: true)
|
|
288
|
+
case .far:
|
|
289
|
+
return updateDistance(frame, closer: false)
|
|
290
|
+
case .left, .right, .up:
|
|
291
|
+
return updateHeadPose(frame, action: action)
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
func isComplete() -> Bool { currentIndex >= actions.count }
|
|
296
|
+
|
|
297
|
+
/// `poseNeutral` deliberately excludes the smile term: the blink is finished
|
|
298
|
+
/// the moment the eyes reopen on a straight head, and a lingering grin from a
|
|
299
|
+
/// previous step must not hold a completed blink open.
|
|
300
|
+
private func updateBlink(eyesOpen: Bool, eyesClosed: Bool, poseNeutral: Bool) -> LivenessProgress {
|
|
301
|
+
if !blinkClosedSeen {
|
|
302
|
+
actionProgressValue = 0.12
|
|
303
|
+
if eyesClosed {
|
|
304
|
+
blinkClosedSeen = true
|
|
305
|
+
stableFrames = 0
|
|
306
|
+
actionProgressValue = 0.6
|
|
307
|
+
return progress(.openEyes, cueAction: .blink, actionProgress: actionProgressValue)
|
|
308
|
+
}
|
|
309
|
+
return progress(.blink, cueAction: .blink, actionProgress: actionProgressValue)
|
|
310
|
+
}
|
|
311
|
+
stableFrames = (eyesOpen && poseNeutral) ? stableFrames + 1 : 0
|
|
312
|
+
actionProgressValue = min(
|
|
313
|
+
max(0.6 + 0.4 * Float(stableFrames) / Float(Constants.finalStableFrames), 0),
|
|
314
|
+
1
|
|
315
|
+
)
|
|
316
|
+
if stableFrames >= Constants.finalStableFrames { return completeCurrentAction() }
|
|
317
|
+
return progress(
|
|
318
|
+
eyesOpen ? .holdStill : .openEyes,
|
|
319
|
+
cueAction: .blink,
|
|
320
|
+
actionProgress: actionProgressValue
|
|
321
|
+
)
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
private func updateSmile(_ smile: Float) -> LivenessProgress {
|
|
325
|
+
actionProgressValue = min(max(smile / Constants.smileThreshold, 0), 1)
|
|
326
|
+
stableFrames = smile >= Constants.smileThreshold ? stableFrames + 1 : 0
|
|
327
|
+
if stableFrames >= Constants.requiredStableFrames { return completeCurrentAction() }
|
|
328
|
+
return progress(
|
|
329
|
+
smile >= Constants.smileThreshold * 0.5 ? .holdSmile : .smile,
|
|
330
|
+
cueAction: .smile,
|
|
331
|
+
actionProgress: actionProgressValue
|
|
332
|
+
)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/// The terminal settle step. Auto-capture fires the instant liveness
|
|
336
|
+
/// completes, so this is the only step whose predicate describes the frame the
|
|
337
|
+
/// shutter is about to photograph: straight-on, eyes open, not mid-grin.
|
|
338
|
+
///
|
|
339
|
+
/// The counter decays instead of resetting, because at `holdFrames` > 2 a hard
|
|
340
|
+
/// reset meant one involuntary blink threw away the whole window and charged
|
|
341
|
+
/// the user for it twice.
|
|
342
|
+
private func updateHold(_ captureNeutral: Bool) -> LivenessProgress {
|
|
343
|
+
stableFrames = captureNeutral ? stableFrames + 1 : max(0, stableFrames - 1)
|
|
344
|
+
actionProgressValue = min(max(Float(stableFrames) / Float(Constants.holdFrames), 0), 1)
|
|
345
|
+
if stableFrames >= Constants.holdFrames {
|
|
346
|
+
// The challenge set is short by design, so the passive model has to
|
|
347
|
+
// have agreed across the recent window — not merely on this frame —
|
|
348
|
+
// before the session is allowed to finish.
|
|
349
|
+
guard passiveConfidenceOk() else {
|
|
350
|
+
return progress(.verifyReal, cueAction: .hold, actionProgress: actionProgressValue)
|
|
351
|
+
}
|
|
352
|
+
return completeCurrentAction()
|
|
353
|
+
}
|
|
354
|
+
return progress(.holdStill, cueAction: .hold, actionProgress: actionProgressValue)
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
private func recordPassive(_ real: Bool) {
|
|
358
|
+
passiveWindow.append(real)
|
|
359
|
+
if passiveWindow.count > Constants.passiveWindowFrames {
|
|
360
|
+
passiveWindow.removeFirst(passiveWindow.count - Constants.passiveWindowFrames)
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/// True once the passive model has scored REAL on most of the recent window.
|
|
365
|
+
/// A full window is required, so a session cannot complete on a handful of
|
|
366
|
+
/// frames that happened to pass.
|
|
367
|
+
private func passiveConfidenceOk() -> Bool {
|
|
368
|
+
passiveWindow.count >= Constants.passiveWindowFrames &&
|
|
369
|
+
passiveWindow.filter { $0 }.count >= Constants.passiveMinRealFrames
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
private func updateDistance(_ frame: FaceFrameResult, closer: Bool) -> LivenessProgress {
|
|
373
|
+
if baselineFill <= 0 { baselineFill = frame.faceFill }
|
|
374
|
+
let base = baselineFill
|
|
375
|
+
let ratio = base > 0 ? frame.faceFill / base : 1
|
|
376
|
+
let reached = closer
|
|
377
|
+
? (ratio >= Constants.distanceNearRatio || frame.faceFill >= 0.80)
|
|
378
|
+
: (ratio <= Constants.distanceFarRatio || frame.faceFill <= 0.20)
|
|
379
|
+
actionProgressValue = closer
|
|
380
|
+
? min(max((ratio - 1) / (Constants.distanceNearRatio - 1), 0), 1)
|
|
381
|
+
: min(max((1 - ratio) / (1 - Constants.distanceFarRatio), 0), 1)
|
|
382
|
+
stableFrames = reached ? stableFrames + 1 : 0
|
|
383
|
+
if stableFrames >= Constants.requiredStableFrames { return completeCurrentAction() }
|
|
384
|
+
let action: LivenessAction = closer ? .near : .far
|
|
385
|
+
return progress(action.prompt, cueAction: action, actionProgress: actionProgressValue)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
private func updateHeadPose(_ frame: FaceFrameResult, action: LivenessAction) -> LivenessProgress {
|
|
389
|
+
// The preview is mirrored, so the signs follow the user's screen direction.
|
|
390
|
+
let value: Float
|
|
391
|
+
let target: Float
|
|
392
|
+
switch action {
|
|
393
|
+
case .left: value = frame.yaw; target = Constants.headYawTarget
|
|
394
|
+
case .right: value = -frame.yaw; target = Constants.headYawTarget
|
|
395
|
+
case .up: value = frame.pitch; target = Constants.headPitchTarget
|
|
396
|
+
default: value = 0; target = 1
|
|
397
|
+
}
|
|
398
|
+
actionProgressValue = min(max(value / target, 0), 1)
|
|
399
|
+
stableFrames = value >= target ? stableFrames + 1 : 0
|
|
400
|
+
if stableFrames >= Constants.requiredStableFrames { return completeCurrentAction() }
|
|
401
|
+
return progress(action.prompt, cueAction: action, actionProgress: actionProgressValue)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
private func completeCurrentAction() -> LivenessProgress {
|
|
405
|
+
currentIndex += 1
|
|
406
|
+
stableFrames = 0
|
|
407
|
+
neutralFrames = 0
|
|
408
|
+
blinkClosedSeen = false
|
|
409
|
+
baselineFill = 0
|
|
410
|
+
actionProgressValue = 1
|
|
411
|
+
needsNeutral = currentIndex < actions.count
|
|
412
|
+
return currentIndex >= actions.count ? progress(.livenessOk) : progress(.stepDone)
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
private func positionPrompt(_ frame: FaceFrameResult) -> LivenessPrompt {
|
|
416
|
+
let fill = frame.faceFill
|
|
417
|
+
if (0.01...0.20).contains(fill) { return .moveCloser }
|
|
418
|
+
if fill > 0.74 { return .moveAway }
|
|
419
|
+
return .centerFace
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
private func pauseCurrentSignal() {
|
|
423
|
+
stableFrames = 0
|
|
424
|
+
neutralFrames = 0
|
|
425
|
+
blinkClosedSeen = false
|
|
426
|
+
actionProgressValue = 0
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
private func resetCurrentSignal() {
|
|
430
|
+
pauseCurrentSignal()
|
|
431
|
+
needsNeutral = true
|
|
432
|
+
baselineFill = 0
|
|
433
|
+
stepDeadlineMs = 0
|
|
434
|
+
outOfFrameFrames = 0
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private func resetAllProgress() {
|
|
438
|
+
currentIndex = 0
|
|
439
|
+
resetCurrentSignal()
|
|
440
|
+
challengeStartedMs = Self.nowMs()
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/// A blink plus exactly ONE movement, in a random order, then a neutral hold —
|
|
444
|
+
/// always three steps.
|
|
445
|
+
///
|
|
446
|
+
/// Exactly one movement is drawn, so `.left` and `.right` can never both be
|
|
447
|
+
/// asked in the same session: the old code drew one *or two* from a pool
|
|
448
|
+
/// holding both, which asked ~17% of users to turn left and then right for no
|
|
449
|
+
/// added security. `.smile` is gone from the set entirely — ML Kit's
|
|
450
|
+
/// classifier rarely crossed the 0.62 bar for a closed-mouth smile, making it
|
|
451
|
+
/// the single biggest source of step timeouts, and the blink already covers
|
|
452
|
+
/// everything a printed photo cannot do.
|
|
453
|
+
///
|
|
454
|
+
/// `.hold` is still appended last and never appears in the pool. Auto-capture
|
|
455
|
+
/// fires the instant liveness completes, so the final step has to leave the
|
|
456
|
+
/// user straight-on with eyes open; when a turn or a blink could land last,
|
|
457
|
+
/// the captured still caught them mid-action and `extractLive()` failed the
|
|
458
|
+
/// whole session.
|
|
459
|
+
///
|
|
460
|
+
/// `.up` stays out of the pool: it has never been reachable from a random
|
|
461
|
+
/// session, so `headPitchTarget` is unvalidated on real devices. It remains
|
|
462
|
+
/// available through an explicit `startLiveness(['up'])`.
|
|
463
|
+
///
|
|
464
|
+
/// This leaves 6 ordered sequences (3 movements x 2 orders) where the old set
|
|
465
|
+
/// had 48. That is a deliberate trade: replay resistance rests on the passive
|
|
466
|
+
/// MiniFASNetV2 check — per frame, across the window in `passiveConfidenceOk`,
|
|
467
|
+
/// and fail-closed again on the captured still — not on challenge entropy. Do
|
|
468
|
+
/// not lower `AntiSpoofHelper.defaultThreshold` to compensate for anything.
|
|
469
|
+
private static func randomChallenge() -> [LivenessAction] {
|
|
470
|
+
// `randomElement()` on a non-empty literal cannot fail.
|
|
471
|
+
let movement: LivenessAction = [.left, .right, .near].randomElement() ?? .left
|
|
472
|
+
return ([.blink, movement] as [LivenessAction]).shuffled() + [.hold]
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/// Guarantees the terminal neutral settle for an explicitly requested action
|
|
476
|
+
/// list too. Without this, `startLiveness(['blink','left'])` ended on the turn
|
|
477
|
+
/// and auto-capture photographed the user mid-turn — the exact failure the
|
|
478
|
+
/// terminal hold exists to prevent, and which the explicit path silently
|
|
479
|
+
/// bypassed while `randomChallenge()` appended it.
|
|
480
|
+
private static func withTerminalHold(_ requested: [LivenessAction]) -> [LivenessAction] {
|
|
481
|
+
guard requested.last != .hold else { return requested }
|
|
482
|
+
return requested.filter { $0 != .hold } + [.hold]
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private func progress(
|
|
486
|
+
_ promptKey: LivenessPrompt,
|
|
487
|
+
cueAction: LivenessAction? = nil,
|
|
488
|
+
actionProgress: Float? = nil
|
|
489
|
+
) -> LivenessProgress {
|
|
490
|
+
LivenessProgress(
|
|
491
|
+
currentAction: currentIndex < actions.count ? actions[currentIndex] : nil,
|
|
492
|
+
completedActions: Array(actions.prefix(currentIndex)),
|
|
493
|
+
isComplete: currentIndex >= actions.count,
|
|
494
|
+
promptKey: promptKey,
|
|
495
|
+
cueAction: cueAction,
|
|
496
|
+
actionProgress: min(max(actionProgress ?? actionProgressValue, 0), 1),
|
|
497
|
+
stepIndex: min(max(currentIndex, 0), actions.count),
|
|
498
|
+
stepCount: actions.count
|
|
499
|
+
)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
private static func nowMs() -> Int64 {
|
|
503
|
+
Int64(DispatchTime.now().uptimeNanoseconds / 1_000_000)
|
|
504
|
+
}
|
|
505
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Port of `LivenessPrompts.kt`.
|
|
4
|
+
///
|
|
5
|
+
/// Every user-facing liveness / positioning prompt as a stable key with an
|
|
6
|
+
/// English and a Hindi string. The detector only ever emits a key; the
|
|
7
|
+
/// on-screen strip and the spoken voice both resolve it to the language the
|
|
8
|
+
/// caller chose, so the two never drift apart.
|
|
9
|
+
///
|
|
10
|
+
/// `spoken` marks the prompts that voice guidance reads aloud. Fast
|
|
11
|
+
/// intermediate states (mid-blink, "look straight" between every step, silent
|
|
12
|
+
/// confirmations) are shown on screen but never spoken, so the voice stays calm.
|
|
13
|
+
///
|
|
14
|
+
/// The raw values are the wire `promptKey` values shared with Android and must
|
|
15
|
+
/// not change.
|
|
16
|
+
enum LivenessPrompt: String, CaseIterable {
|
|
17
|
+
case getReady = "GET_READY"
|
|
18
|
+
case positionFace = "POSITION_FACE"
|
|
19
|
+
case keepInFrame = "KEEP_IN_FRAME"
|
|
20
|
+
case moveCloser = "MOVE_CLOSER"
|
|
21
|
+
case moveAway = "MOVE_AWAY"
|
|
22
|
+
case centerFace = "CENTER_FACE"
|
|
23
|
+
case holdUpright = "HOLD_UPRIGHT"
|
|
24
|
+
case multipleFaces = "MULTIPLE_FACES"
|
|
25
|
+
case lowLight = "LOW_LIGHT"
|
|
26
|
+
case verifyReal = "VERIFY_REAL"
|
|
27
|
+
case spoofBlocked = "SPOOF_BLOCKED"
|
|
28
|
+
case lookStraight = "LOOK_STRAIGHT"
|
|
29
|
+
case blink = "BLINK"
|
|
30
|
+
case openEyes = "OPEN_EYES"
|
|
31
|
+
case smile = "SMILE"
|
|
32
|
+
case holdSmile = "HOLD_SMILE"
|
|
33
|
+
case turnLeft = "TURN_LEFT"
|
|
34
|
+
case turnRight = "TURN_RIGHT"
|
|
35
|
+
case lookUp = "LOOK_UP"
|
|
36
|
+
case comeCloser = "COME_CLOSER"
|
|
37
|
+
case goBack = "GO_BACK"
|
|
38
|
+
case holdStill = "HOLD_STILL"
|
|
39
|
+
case stepDone = "STEP_DONE"
|
|
40
|
+
case retryStep = "RETRY_STEP"
|
|
41
|
+
case tooSlow = "TOO_SLOW"
|
|
42
|
+
case verifying = "VERIFYING"
|
|
43
|
+
case livenessOk = "LIVENESS_OK"
|
|
44
|
+
|
|
45
|
+
var en: String {
|
|
46
|
+
switch self {
|
|
47
|
+
case .getReady: return "Get ready"
|
|
48
|
+
case .positionFace: return "Position your face in the frame"
|
|
49
|
+
case .keepInFrame: return "Keep your face inside the frame"
|
|
50
|
+
case .moveCloser: return "Move a little closer"
|
|
51
|
+
case .moveAway: return "Move a little away"
|
|
52
|
+
case .centerFace: return "Center your face"
|
|
53
|
+
case .holdUpright: return "Keep your head upright"
|
|
54
|
+
case .multipleFaces: return "Only one person allowed"
|
|
55
|
+
case .lowLight: return "Move to better lighting"
|
|
56
|
+
case .verifyReal: return "Checking it's really you"
|
|
57
|
+
case .spoofBlocked: return "Use your real face, not a photo or screen"
|
|
58
|
+
case .lookStraight: return "Look straight at the camera"
|
|
59
|
+
case .blink: return "Please blink your eyes"
|
|
60
|
+
case .openEyes: return "Now open your eyes"
|
|
61
|
+
case .smile: return "Please smile"
|
|
62
|
+
case .holdSmile: return "Hold that smile"
|
|
63
|
+
case .turnLeft: return "Please turn your head to the left"
|
|
64
|
+
case .turnRight: return "Please turn your head to the right"
|
|
65
|
+
case .lookUp: return "Please tilt your head up"
|
|
66
|
+
case .comeCloser: return "Please move slightly closer"
|
|
67
|
+
case .goBack: return "Please move slightly away"
|
|
68
|
+
case .holdStill: return "Hold still"
|
|
69
|
+
case .stepDone: return "Good, next step"
|
|
70
|
+
case .retryStep: return "Let's try that step again"
|
|
71
|
+
case .tooSlow: return "That took too long, starting again"
|
|
72
|
+
case .verifying: return "Verifying"
|
|
73
|
+
case .livenessOk: return "Liveness verified"
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
var hi: String {
|
|
78
|
+
switch self {
|
|
79
|
+
case .getReady: return "तैयार हो जाइए"
|
|
80
|
+
case .positionFace: return "अपना चेहरा फ्रेम के अंदर रखें"
|
|
81
|
+
case .keepInFrame: return "चेहरे को फ्रेम के अंदर रखें"
|
|
82
|
+
case .moveCloser: return "थोड़ा पास आएँ"
|
|
83
|
+
case .moveAway: return "थोड़ा पीछे जाएँ"
|
|
84
|
+
case .centerFace: return "चेहरे को बीच में रखें"
|
|
85
|
+
case .holdUpright: return "अपना सिर सीधा रखें"
|
|
86
|
+
case .multipleFaces: return "केवल एक व्यक्ति की अनुमति है"
|
|
87
|
+
case .lowLight: return "बेहतर रोशनी में आएँ"
|
|
88
|
+
case .verifyReal: return "जाँच हो रही है कि यह वाकई आप हैं"
|
|
89
|
+
case .spoofBlocked: return "असली चेहरा दिखाएँ, फ़ोटो या स्क्रीन नहीं"
|
|
90
|
+
case .lookStraight: return "कैमरे की ओर सीधे देखें"
|
|
91
|
+
case .blink: return "कृपया अपनी आँखें झपकाएँ"
|
|
92
|
+
case .openEyes: return "अब अपनी आँखें खोलें"
|
|
93
|
+
case .smile: return "कृपया मुस्कुराएँ"
|
|
94
|
+
case .holdSmile: return "मुस्कान बनाए रखें"
|
|
95
|
+
case .turnLeft: return "कृपया अपना सिर बाईं ओर घुमाएँ"
|
|
96
|
+
case .turnRight: return "कृपया अपना सिर दाईं ओर घुमाएँ"
|
|
97
|
+
case .lookUp: return "कृपया अपना सिर ऊपर करें"
|
|
98
|
+
case .comeCloser: return "कृपया थोड़ा पास आएँ"
|
|
99
|
+
case .goBack: return "कृपया थोड़ा पीछे जाएँ"
|
|
100
|
+
case .holdStill: return "स्थिर रहें"
|
|
101
|
+
case .stepDone: return "बढ़िया, अगला चरण"
|
|
102
|
+
case .retryStep: return "यह चरण फिर से करें"
|
|
103
|
+
case .tooSlow: return "बहुत समय लग गया, फिर से शुरू"
|
|
104
|
+
case .verifying: return "सत्यापन हो रहा है"
|
|
105
|
+
case .livenessOk: return "जीवंतता सत्यापित"
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
var spoken: Bool {
|
|
110
|
+
switch self {
|
|
111
|
+
case .verifyReal, .lookStraight, .openEyes, .holdSmile, .stepDone, .verifying:
|
|
112
|
+
return false
|
|
113
|
+
default:
|
|
114
|
+
return true
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
func localized(_ language: String) -> String {
|
|
119
|
+
language.lowercased() == "hi" ? hi : en
|
|
120
|
+
}
|
|
121
|
+
}
|