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.
Files changed (58) hide show
  1. package/FaceMatch.podspec +55 -0
  2. package/README.md +174 -2
  3. package/android/build.gradle +59 -0
  4. package/android/consumer-rules.pro +5 -0
  5. package/android/src/main/AndroidManifest.xml +11 -0
  6. package/android/src/main/java/com/facematch/sdk/AntiSpoofHelper.kt +216 -0
  7. package/android/src/main/java/com/facematch/sdk/BitmapUtils.kt +138 -0
  8. package/android/src/main/java/com/facematch/sdk/CameraFrameView.kt +75 -0
  9. package/android/src/main/java/com/facematch/sdk/FaceAlignmentHelper.kt +156 -0
  10. package/android/src/main/java/com/facematch/sdk/FaceCameraView.kt +628 -0
  11. package/android/src/main/java/com/facematch/sdk/FaceCameraViewManager.kt +79 -0
  12. package/android/src/main/java/com/facematch/sdk/FaceCandidateFilter.kt +65 -0
  13. package/android/src/main/java/com/facematch/sdk/FaceDetectionHelper.kt +225 -0
  14. package/android/src/main/java/com/facematch/sdk/FaceEmbeddingHelper.kt +242 -0
  15. package/android/src/main/java/com/facematch/sdk/FaceFrameAnalyzer.kt +228 -0
  16. package/android/src/main/java/com/facematch/sdk/FaceMatchModule.kt +249 -0
  17. package/android/src/main/java/com/facematch/sdk/FaceMatchPackage.kt +14 -0
  18. package/android/src/main/java/com/facematch/sdk/FaceMatchRuntime.kt +138 -0
  19. package/android/src/main/java/com/facematch/sdk/FaceMatcherHelper.kt +92 -0
  20. package/android/src/main/java/com/facematch/sdk/FaceOverlayView.kt +236 -0
  21. package/android/src/main/java/com/facematch/sdk/LivenessDetector.kt +483 -0
  22. package/android/src/main/java/com/facematch/sdk/LivenessPrompts.kt +137 -0
  23. package/android/src/main/java/com/facematch/sdk/LivenessVoice.kt +270 -0
  24. package/android/src/main/java/com/facematch/sdk/PrivateCaptureStore.kt +50 -0
  25. package/ios/Sources/AntiSpoofHelper.swift +239 -0
  26. package/ios/Sources/FaceAlignmentHelper.swift +169 -0
  27. package/ios/Sources/FaceCameraView.swift +1161 -0
  28. package/ios/Sources/FaceCameraViewManager.m +28 -0
  29. package/ios/Sources/FaceCameraViewManager.swift +57 -0
  30. package/ios/Sources/FaceCandidateFilter.swift +62 -0
  31. package/ios/Sources/FaceDetectionHelper.swift +283 -0
  32. package/ios/Sources/FaceEmbeddingHelper.swift +188 -0
  33. package/ios/Sources/FaceFrameAnalyzer.swift +179 -0
  34. package/ios/Sources/FaceFrameResult.swift +96 -0
  35. package/ios/Sources/FaceMatchBundle.swift +26 -0
  36. package/ios/Sources/FaceMatchEngine.swift +136 -0
  37. package/ios/Sources/FaceMatchError.swift +40 -0
  38. package/ios/Sources/FaceMatchModule.m +55 -0
  39. package/ios/Sources/FaceMatchModule.swift +288 -0
  40. package/ios/Sources/FaceMatcherHelper.swift +107 -0
  41. package/ios/Sources/FaceOverlayView.swift +285 -0
  42. package/ios/Sources/ImageUtils.swift +322 -0
  43. package/ios/Sources/LivenessDetector.swift +505 -0
  44. package/ios/Sources/LivenessPrompts.swift +121 -0
  45. package/ios/Sources/LivenessVoice.swift +229 -0
  46. package/ios/Sources/OnnxRuntime/ORTShim.h +91 -0
  47. package/ios/Sources/OnnxRuntime/ORTShim.mm +260 -0
  48. package/ios/Sources/PrivateCaptureStore.swift +71 -0
  49. package/ios/Sources/VisionFaceFallback.swift +95 -0
  50. package/ios/onnxruntime-c.podspec +47 -0
  51. package/models/anti_spoof_minifasnet_v2.onnx +0 -0
  52. package/models/w600k_mbf.onnx +0 -0
  53. package/package.json +38 -4
  54. package/react-native.config.js +16 -0
  55. package/src/FaceCameraView.tsx +75 -0
  56. package/src/FaceMatch.ts +66 -0
  57. package/src/index.ts +4 -0
  58. package/src/types.ts +87 -0
@@ -0,0 +1,270 @@
1
+ package com.facematch.sdk
2
+
3
+ import android.content.Context
4
+ import android.content.Intent
5
+ import android.os.Handler
6
+ import android.os.Looper
7
+ import android.speech.tts.TextToSpeech
8
+ import android.speech.tts.Voice
9
+ import java.util.Locale
10
+
11
+ /**
12
+ * Speaks liveness prompts through the platform text-to-speech engine in the
13
+ * caller's chosen language (English or Hindi). A prompt is spoken once when it
14
+ * first appears; repeats of the same prompt are ignored.
15
+ *
16
+ * Prompts are never dropped, only deferred. Two things used to swallow them:
17
+ * - the engine binds asynchronously (0.5–3 s on a cold start), and every
18
+ * prompt raised before it reported ready was discarded. The camera only
19
+ * re-emits a prompt when the step changes, so the opening instruction was
20
+ * simply never heard and the voice "started a few steps late";
21
+ * - a prompt raised within [MIN_GAP_MS] of the previous one was discarded
22
+ * for good, so a quick step change left that step silent.
23
+ * Now the newest prompt is held as pending and spoken as soon as the engine is
24
+ * ready and the gap has elapsed — the latest instruction always wins.
25
+ *
26
+ * Main thread only (the camera's ML Kit callbacks already run there).
27
+ */
28
+ class LivenessVoice(context: Context) {
29
+
30
+ private companion object {
31
+ const val MIN_GAP_MS = 1400L
32
+ // Slightly under the engine default: clearer for step-by-step guidance.
33
+ const val SPEECH_RATE = 0.95f
34
+
35
+ // Google TTS voice ids carry no gender field. These are its offline
36
+ // India voices; any id not listed here is treated as unknown gender.
37
+ val FEMALE_VOICE_CODES = setOf("ahp", "cxx", "ena", "enc", "hia", "hic")
38
+ val MALE_VOICE_CODES = setOf("end", "ene", "hid", "hie")
39
+ }
40
+
41
+ private val main = Handler(Looper.getMainLooper())
42
+ private val appContext = context.applicationContext
43
+ // Resolved per use: if a bind fails, SharedTts drops that engine and the
44
+ // next lookup rebinds instead of this view holding a dead instance.
45
+ private val engine: TextToSpeech get() = SharedTts.obtain(appContext)
46
+ private var language = "none"
47
+ private var gender = "female"
48
+ private var lastKey: String? = null
49
+ private var lastSpokeAt = 0L
50
+ private var pendingKey: String? = null
51
+ private var pendingText: String? = null
52
+ private val flushRunnable = Runnable { flush() }
53
+ private val onEngineReady: () -> Unit = {
54
+ applyLanguage()
55
+ flush()
56
+ }
57
+
58
+ init {
59
+ // Start binding now (a no-op when the module already prewarmed it).
60
+ SharedTts.obtain(appContext)
61
+ SharedTts.whenReady(onEngineReady)
62
+ }
63
+
64
+ fun setLanguage(value: String) {
65
+ val normalized = value.lowercase()
66
+ if (normalized == language) return
67
+ language = normalized
68
+ lastKey = null
69
+ if (normalized == "none") {
70
+ clearPending()
71
+ runCatching { engine.stop() }
72
+ } else if (SharedTts.isReady) {
73
+ applyLanguage()
74
+ }
75
+ }
76
+
77
+ /** "female" (default) or "male" — preferred voice; falls back to any India voice. */
78
+ fun setGender(value: String) {
79
+ val normalized = if (value.lowercase() == "male") "male" else "female"
80
+ if (normalized == gender) return
81
+ gender = normalized
82
+ if (SharedTts.isReady) applyLanguage()
83
+ }
84
+
85
+ /** Announce a prompt. [key] is the [LivenessPrompt] name; [text] is already localized. */
86
+ fun speak(key: String, text: String) {
87
+ if (language == "none" || text.isBlank()) return
88
+ if (key == lastKey && pendingKey == null) return
89
+ pendingKey = key
90
+ pendingText = text
91
+ flush()
92
+ }
93
+
94
+ /** Forget the last prompt so the next call speaks even if the key is unchanged. */
95
+ fun resetSpokenHistory() {
96
+ lastKey = null
97
+ }
98
+
99
+ fun stop() {
100
+ clearPending()
101
+ runCatching { engine.stop() }
102
+ }
103
+
104
+ fun shutdown() {
105
+ // The engine is shared and application-lifetime; only this view's
106
+ // pending work and its ready callback are released here.
107
+ stop()
108
+ SharedTts.removeReadyCallback(onEngineReady)
109
+ }
110
+
111
+ private fun flush() {
112
+ main.removeCallbacks(flushRunnable)
113
+ val key = pendingKey ?: return
114
+ val text = pendingText ?: return
115
+ if (language == "none") {
116
+ clearPending()
117
+ return
118
+ }
119
+ // Not bound yet: onEngineReady flushes the moment it is.
120
+ if (!SharedTts.isReady) return
121
+ val wait = MIN_GAP_MS - (System.currentTimeMillis() - lastSpokeAt)
122
+ if (wait > 0) {
123
+ main.postDelayed(flushRunnable, wait)
124
+ return
125
+ }
126
+ pendingKey = null
127
+ pendingText = null
128
+ if (key == lastKey) return
129
+ lastKey = key
130
+ lastSpokeAt = System.currentTimeMillis()
131
+ engine.speak(text, TextToSpeech.QUEUE_FLUSH, null, key)
132
+ }
133
+
134
+ private fun clearPending() {
135
+ main.removeCallbacks(flushRunnable)
136
+ pendingKey = null
137
+ pendingText = null
138
+ }
139
+
140
+ private fun applyLanguage() {
141
+ val locale = when (language) {
142
+ "hi" -> Locale("hi", "IN")
143
+ "en" -> Locale("en", "IN")
144
+ else -> return
145
+ }
146
+ val tts = engine
147
+ runCatching { tts.setSpeechRate(SPEECH_RATE) }
148
+ // setLanguage alone keeps whatever voice the engine defaults to for the
149
+ // locale — or, when en-IN data is missing, silently falls back to a US
150
+ // voice. Pick an installed India voice explicitly, in the chosen gender.
151
+ val voice = pickIndiaVoice(tts, locale)
152
+ if (voice != null && runCatching { tts.setVoice(voice) }.getOrDefault(TextToSpeech.ERROR) == TextToSpeech.SUCCESS) {
153
+ return
154
+ }
155
+ val result = runCatching { tts.setLanguage(locale) }.getOrDefault(TextToSpeech.LANG_NOT_SUPPORTED)
156
+ if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
157
+ // Fall back to whatever English the device has.
158
+ if (language == "en") runCatching { tts.setLanguage(Locale.ENGLISH) }
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Best installed voice for [locale] in India: offline before network (no
164
+ * stall on a slow connection), the preferred gender when it can be told,
165
+ * then highest quality and lowest latency.
166
+ */
167
+ private fun pickIndiaVoice(tts: TextToSpeech, locale: Locale): Voice? {
168
+ val voices = runCatching { tts.voices }.getOrNull().orEmpty()
169
+ val india = voices.filter { voice ->
170
+ voice.locale.language == locale.language &&
171
+ voice.locale.country.equals("IN", ignoreCase = true) &&
172
+ !voice.features.orEmpty().contains(TextToSpeech.Engine.KEY_FEATURE_NOT_INSTALLED)
173
+ }
174
+ if (india.isEmpty()) return null
175
+ val offline = india.filter { !it.isNetworkConnectionRequired }.ifEmpty { india }
176
+ val preferred = offline.filter { genderOf(it) == gender }.ifEmpty {
177
+ // Unknown gender beats a known opposite one.
178
+ offline.filter { genderOf(it) == null }.ifEmpty { offline }
179
+ }
180
+ return preferred.maxWithOrNull(compareBy<Voice>({ it.quality }, { -it.latency }))
181
+ }
182
+
183
+ private fun genderOf(voice: Voice): String? {
184
+ val name = voice.name.lowercase()
185
+ if ("female" in name) return "female"
186
+ if ("male" in name) return "male"
187
+ // Google ids look like "en-in-x-ene-local" / "hi-in-x-hia-network".
188
+ val code = name.split('-').getOrNull(3) ?: return null
189
+ return when (code) {
190
+ in FEMALE_VOICE_CODES -> "female"
191
+ in MALE_VOICE_CODES -> "male"
192
+ else -> null
193
+ }
194
+ }
195
+ }
196
+
197
+ /**
198
+ * One application-lifetime [TextToSpeech] engine shared by every camera view.
199
+ *
200
+ * Binding the platform TTS service is slow on a cold start, and a per-view
201
+ * engine paid that cost on every session — right when the first instruction
202
+ * needs to be heard. [prewarm] is called when the FaceMatch module loads, so
203
+ * the engine is normally bound before the camera even opens. If binding fails
204
+ * the engine is discarded so the next session retries instead of staying mute.
205
+ *
206
+ * Main thread only.
207
+ */
208
+ internal object SharedTts {
209
+ private const val GOOGLE_TTS = "com.google.android.tts"
210
+ private val main = Handler(Looper.getMainLooper())
211
+ private var engine: TextToSpeech? = null
212
+ private val readyCallbacks = mutableListOf<() -> Unit>()
213
+
214
+ var isReady = false
215
+ private set
216
+
217
+ fun prewarm(context: Context) {
218
+ val appContext = context.applicationContext
219
+ if (Looper.myLooper() == Looper.getMainLooper()) obtain(appContext)
220
+ else main.post { obtain(appContext) }
221
+ }
222
+
223
+ fun obtain(context: Context): TextToSpeech {
224
+ engine?.let { return it }
225
+ isReady = false
226
+ lateinit var created: TextToSpeech
227
+ val listener = TextToSpeech.OnInitListener { status ->
228
+ // Posted: the listener can fire synchronously from the constructor
229
+ // when no engine is installed, before `created` is assigned.
230
+ main.post {
231
+ if (engine !== created) return@post
232
+ if (status == TextToSpeech.SUCCESS) {
233
+ isReady = true
234
+ val callbacks = readyCallbacks.toList()
235
+ readyCallbacks.clear()
236
+ callbacks.forEach { it() }
237
+ } else {
238
+ runCatching { created.shutdown() }
239
+ engine = null
240
+ }
241
+ }
242
+ }
243
+ // Prefer Google's engine: it ships offline en-IN and hi-IN voices in
244
+ // both genders, while several OEM default engines have no India voice
245
+ // and read Hindi/English prompts with a foreign accent.
246
+ created = if (hasEngine(context, GOOGLE_TTS)) {
247
+ TextToSpeech(context.applicationContext, listener, GOOGLE_TTS)
248
+ } else {
249
+ TextToSpeech(context.applicationContext, listener)
250
+ }
251
+ engine = created
252
+ return created
253
+ }
254
+
255
+ /** Needs the TTS_SERVICE <queries> entry (in this library's manifest) on API 30+. */
256
+ private fun hasEngine(context: Context, packageName: String): Boolean = runCatching {
257
+ context.packageManager
258
+ .queryIntentServices(Intent(TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE), 0)
259
+ .any { it.serviceInfo?.packageName == packageName }
260
+ }.getOrDefault(false)
261
+
262
+ /** Runs [callback] now if the engine is bound, otherwise once it is. */
263
+ fun whenReady(callback: () -> Unit) {
264
+ if (isReady) callback() else readyCallbacks.add(callback)
265
+ }
266
+
267
+ fun removeReadyCallback(callback: () -> Unit) {
268
+ readyCallbacks.remove(callback)
269
+ }
270
+ }
@@ -0,0 +1,50 @@
1
+ package com.facematch.sdk
2
+
3
+ import android.content.Context
4
+ import android.net.Uri
5
+ import java.io.File
6
+ import java.util.UUID
7
+
8
+ /** Strictly scoped lifecycle management for temporary biometric captures. */
9
+ object PrivateCaptureStore {
10
+ private const val DIRECTORY = "face-match"
11
+ private const val PREFIX = "capture-"
12
+ private const val SUFFIX = ".jpg"
13
+
14
+ fun create(context: Context): File {
15
+ val directory = directory(context)
16
+ if (!directory.exists() && !directory.mkdirs()) {
17
+ throw FaceMatchException("E_CAPTURE_FILE", "Unable to create the capture directory")
18
+ }
19
+ require(directory.isDirectory) { "Private capture path is not a directory" }
20
+ return File(directory, "$PREFIX${UUID.randomUUID()}$SUFFIX")
21
+ }
22
+
23
+ fun deleteIfOwned(context: Context, uriString: String): Boolean {
24
+ val uri = Uri.parse(uriString)
25
+ if (uri.scheme?.lowercase() != "file") return false
26
+ val path = uri.path ?: return false
27
+ val directory = directory(context).canonicalFile
28
+ val target = File(path).canonicalFile
29
+ if (target.parentFile != directory || !isCapture(target)) return false
30
+ return !target.exists() || target.delete()
31
+ }
32
+
33
+ fun clear(context: Context) {
34
+ val directory = directory(context).canonicalFile
35
+ val files = directory.listFiles() ?: return
36
+ files.forEach { candidate ->
37
+ runCatching {
38
+ val target = candidate.canonicalFile
39
+ if (target.parentFile == directory && target.isFile && isCapture(target)) {
40
+ target.delete()
41
+ }
42
+ }
43
+ }
44
+ }
45
+
46
+ private fun directory(context: Context) = File(context.cacheDir, DIRECTORY)
47
+
48
+ private fun isCapture(file: File) =
49
+ file.name.startsWith(PREFIX) && file.name.endsWith(SUFFIX)
50
+ }
@@ -0,0 +1,239 @@
1
+ import CoreGraphics
2
+ import Foundation
3
+ import os
4
+
5
+ enum AntiSpoofStatus: String {
6
+ case real = "real"
7
+ case spoof = "spoof"
8
+ case error = "error"
9
+ }
10
+
11
+ struct AntiSpoofResult {
12
+ let status: AntiSpoofStatus
13
+ let realScore: Float?
14
+ let threshold: Float
15
+ let errorMessage: String?
16
+
17
+ init(_ status: AntiSpoofStatus, _ realScore: Float?, _ threshold: Float, _ errorMessage: String? = nil) {
18
+ self.status = status
19
+ self.realScore = realScore
20
+ self.threshold = threshold
21
+ self.errorMessage = errorMessage
22
+ }
23
+ }
24
+
25
+ /// Port of `AntiSpoofHelper.kt`.
26
+ ///
27
+ /// Offline MiniFASNetV2 inference using MiniVision's official
28
+ /// 2.7_80x80_MiniFASNetV2 checkpoint converted to ONNX.
29
+ ///
30
+ /// The model expects a 2.7x expanded face crop as raw BGR float32 CHW data and
31
+ /// emits three logits. Upstream class index 1 is REAL; indices 0 and 2 are
32
+ /// presentation attacks.
33
+ final class AntiSpoofHelper {
34
+ /// Active head-motion + blink liveness is already mandatory. A 0.60 passive
35
+ /// threshold keeps the second, complementary check enabled without
36
+ /// rejecting genuine captures for ordinary lighting variation.
37
+ static let defaultThreshold: Float = 0.60
38
+
39
+ private static let modelName = "anti_spoof_minifasnet_v2"
40
+ private static let inputSize = 80
41
+ private static let cropScale: CGFloat = 2.7
42
+ private static let realClassIndex = 1
43
+ private static let log = OSLog(subsystem: "com.facematch.sdk", category: "AntiSpoof")
44
+
45
+ static func sanitizeThreshold(_ value: Float) -> Float {
46
+ value.isFinite ? min(max(value, 0), 1) : defaultThreshold
47
+ }
48
+
49
+ private let lock = NSLock()
50
+ private var session: ORTSession?
51
+ private var inputName: String?
52
+ private var outputName: String?
53
+ private let initializationError: String?
54
+
55
+ var isReady: Bool { session != nil }
56
+
57
+ init() {
58
+ var loadedSession: ORTSession?
59
+ var loadError: String?
60
+ do {
61
+ guard let path = FaceMatchBundle.modelPath(named: Self.modelName) else {
62
+ throw FaceMatchError(
63
+ "E_ANTI_SPOOF_MODEL",
64
+ "Anti-spoof model is missing from the app bundle: \(Self.modelName).onnx"
65
+ )
66
+ }
67
+ let env = try ORTEnv(loggingLevel: ORTLoggingLevel.warning)
68
+ loadedSession = try ORTSession(
69
+ env: env,
70
+ modelPath: path,
71
+ sessionOptions: try ORTSessionOptions()
72
+ )
73
+ inputName = try loadedSession?.inputNames().first
74
+ outputName = try loadedSession?.outputNames().first
75
+ #if DEBUG
76
+ os_log("Initialized %{public}@.onnx (CPU ONNX Runtime)", log: Self.log, type: .info, Self.modelName)
77
+ #endif
78
+ } catch {
79
+ loadError = FaceMatchError.message(of: error)
80
+ #if DEBUG
81
+ os_log("%{public}@", log: Self.log, type: .error, loadError ?? "")
82
+ #else
83
+ os_log("Passive anti-spoof model initialization failed", log: Self.log, type: .error)
84
+ #endif
85
+ }
86
+ session = loadedSession
87
+ initializationError = loadError
88
+ }
89
+
90
+ func classify(_ image: CGImage, faceBounds: CGRect, requestedThreshold: Float) -> AntiSpoofResult {
91
+ let threshold = Self.sanitizeThreshold(requestedThreshold)
92
+ lock.lock()
93
+ defer { lock.unlock() }
94
+
95
+ guard let session, let inputName, let outputName else {
96
+ return AntiSpoofResult(
97
+ .error,
98
+ nil,
99
+ threshold,
100
+ initializationError ?? "Passive anti-spoof model is unavailable"
101
+ )
102
+ }
103
+
104
+ do {
105
+ let tensor = try buildTensor(image, bounds: faceBounds)
106
+ let outputs = try session.run(
107
+ withInputs: [inputName: tensor],
108
+ outputNames: [outputName],
109
+ runOptions: nil
110
+ )
111
+ guard let output = outputs[outputName] else {
112
+ throw FaceMatchError("E_ANTI_SPOOF_MODEL", "MiniFASNetV2 returned an invalid output")
113
+ }
114
+ let logits = try floats(from: output)
115
+ guard logits.count > Self.realClassIndex else {
116
+ throw FaceMatchError(
117
+ "E_ANTI_SPOOF_MODEL",
118
+ "MiniFASNetV2 output has \(logits.count) classes; expected 3"
119
+ )
120
+ }
121
+ let realScore = try softmax(logits)[Self.realClassIndex]
122
+ let status: AntiSpoofStatus = realScore >= threshold ? .real : .spoof
123
+ #if DEBUG
124
+ os_log(
125
+ "%{public}@: realScore=%{public}.4f threshold=%{public}.2f",
126
+ log: Self.log,
127
+ type: status == .spoof ? .error : .debug,
128
+ status == .spoof ? "SPOOF rejected" : "REAL accepted",
129
+ realScore,
130
+ threshold
131
+ )
132
+ #endif
133
+ return AntiSpoofResult(status, realScore, threshold)
134
+ } catch {
135
+ let message = FaceMatchError.message(of: error)
136
+ #if DEBUG
137
+ os_log("%{public}@", log: Self.log, type: .error, message)
138
+ #else
139
+ os_log("Passive anti-spoof inference failed", log: Self.log, type: .error)
140
+ #endif
141
+ return AntiSpoofResult(.error, nil, threshold, message)
142
+ }
143
+ }
144
+
145
+ private func buildTensor(_ image: CGImage, bounds: CGRect) throws -> ORTValue {
146
+ guard image.width > 1, image.height > 1 else {
147
+ throw FaceMatchError("E_ANTI_SPOOF_MODEL", "Camera frame is too small")
148
+ }
149
+ guard bounds.width > 1, bounds.height > 1 else {
150
+ throw FaceMatchError("E_ANTI_SPOOF_MODEL", "Detected face bounds are invalid")
151
+ }
152
+
153
+ let crop = try expandedCrop(image, bounds: bounds)
154
+ let size = Self.inputSize
155
+ let resized = ImageUtils.scaled(crop, width: size, height: size)
156
+ let pixels = ImageUtils.argbPixels(of: resized)
157
+
158
+ var values = [Float](repeating: 0, count: 3 * size * size)
159
+ // Upstream images are read by OpenCV, so preserve its BGR channel order.
160
+ var offset = 0
161
+ for channel in 0..<3 {
162
+ for pixel in pixels {
163
+ let value: UInt32
164
+ switch channel {
165
+ case 0: value = pixel & 0xFF // blue
166
+ case 1: value = (pixel >> 8) & 0xFF // green
167
+ default: value = (pixel >> 16) & 0xFF // red
168
+ }
169
+ values[offset] = Float(value)
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
+ private func expandedCrop(_ image: CGImage, bounds: CGRect) throws -> CGImage {
183
+ let imageWidth = CGFloat(image.width)
184
+ let imageHeight = CGFloat(image.height)
185
+ let scale = min(
186
+ (imageHeight - 1) / bounds.height,
187
+ (imageWidth - 1) / bounds.width,
188
+ Self.cropScale
189
+ )
190
+ let width = bounds.width * scale
191
+ let height = bounds.height * scale
192
+ let centerX = bounds.midX
193
+ let centerY = bounds.midY
194
+
195
+ var left = centerX - width / 2
196
+ var top = centerY - height / 2
197
+ var right = centerX + width / 2
198
+ var bottom = centerY + height / 2
199
+
200
+ if left < 0 { right -= left; left = 0 }
201
+ if top < 0 { bottom -= top; top = 0 }
202
+ if right > imageWidth - 1 {
203
+ left -= right - imageWidth + 1
204
+ right = imageWidth - 1
205
+ }
206
+ if bottom > imageHeight - 1 {
207
+ top -= bottom - imageHeight + 1
208
+ bottom = imageHeight - 1
209
+ }
210
+
211
+ let x0 = min(max(left.rounded(.down), 0), imageWidth - 1)
212
+ let y0 = min(max(top.rounded(.down), 0), imageHeight - 1)
213
+ let x1 = min(max(right.rounded(.up), x0), imageWidth - 1)
214
+ let y1 = min(max(bottom.rounded(.up), y0), imageHeight - 1)
215
+
216
+ let rect = CGRect(x: x0, y: y0, width: x1 - x0 + 1, height: y1 - y0 + 1)
217
+ guard let crop = ImageUtils.crop(image, to: rect) else {
218
+ throw FaceMatchError("E_ANTI_SPOOF_MODEL", "Unable to crop the face region")
219
+ }
220
+ return crop
221
+ }
222
+
223
+ private func floats(from value: ORTValue) throws -> [Float] {
224
+ let data = try value.tensorData() as Data
225
+ return data.withUnsafeBytes { raw in
226
+ Array(raw.bindMemory(to: Float.self))
227
+ }
228
+ }
229
+
230
+ private func softmax(_ logits: [Float]) throws -> [Float] {
231
+ guard let maximum = logits.max() else { return [] }
232
+ let exponentials = logits.map { exp(Double($0 - maximum)) }
233
+ let sum = exponentials.reduce(0, +)
234
+ guard sum > 0, sum.isFinite else {
235
+ throw FaceMatchError("E_ANTI_SPOOF_MODEL", "MiniFASNetV2 produced non-finite logits")
236
+ }
237
+ return exponentials.map { Float($0 / sum) }
238
+ }
239
+ }