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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/FaceMatch.podspec +55 -0
  2. package/LICENSE +21 -0
  3. package/README.md +190 -2
  4. package/android/build.gradle +59 -0
  5. package/android/consumer-rules.pro +5 -0
  6. package/android/src/main/AndroidManifest.xml +11 -0
  7. package/android/src/main/java/com/facematch/sdk/AntiSpoofHelper.kt +216 -0
  8. package/android/src/main/java/com/facematch/sdk/BitmapUtils.kt +138 -0
  9. package/android/src/main/java/com/facematch/sdk/CameraFrameView.kt +75 -0
  10. package/android/src/main/java/com/facematch/sdk/FaceAlignmentHelper.kt +156 -0
  11. package/android/src/main/java/com/facematch/sdk/FaceCameraView.kt +628 -0
  12. package/android/src/main/java/com/facematch/sdk/FaceCameraViewManager.kt +79 -0
  13. package/android/src/main/java/com/facematch/sdk/FaceCandidateFilter.kt +65 -0
  14. package/android/src/main/java/com/facematch/sdk/FaceDetectionHelper.kt +225 -0
  15. package/android/src/main/java/com/facematch/sdk/FaceEmbeddingHelper.kt +242 -0
  16. package/android/src/main/java/com/facematch/sdk/FaceFrameAnalyzer.kt +228 -0
  17. package/android/src/main/java/com/facematch/sdk/FaceMatchModule.kt +249 -0
  18. package/android/src/main/java/com/facematch/sdk/FaceMatchPackage.kt +14 -0
  19. package/android/src/main/java/com/facematch/sdk/FaceMatchRuntime.kt +138 -0
  20. package/android/src/main/java/com/facematch/sdk/FaceMatcherHelper.kt +92 -0
  21. package/android/src/main/java/com/facematch/sdk/FaceOverlayView.kt +236 -0
  22. package/android/src/main/java/com/facematch/sdk/LivenessDetector.kt +483 -0
  23. package/android/src/main/java/com/facematch/sdk/LivenessPrompts.kt +137 -0
  24. package/android/src/main/java/com/facematch/sdk/LivenessVoice.kt +270 -0
  25. package/android/src/main/java/com/facematch/sdk/PrivateCaptureStore.kt +50 -0
  26. package/ios/Sources/AntiSpoofHelper.swift +239 -0
  27. package/ios/Sources/FaceAlignmentHelper.swift +169 -0
  28. package/ios/Sources/FaceCameraView.swift +1161 -0
  29. package/ios/Sources/FaceCameraViewManager.m +28 -0
  30. package/ios/Sources/FaceCameraViewManager.swift +57 -0
  31. package/ios/Sources/FaceCandidateFilter.swift +62 -0
  32. package/ios/Sources/FaceDetectionHelper.swift +283 -0
  33. package/ios/Sources/FaceEmbeddingHelper.swift +188 -0
  34. package/ios/Sources/FaceFrameAnalyzer.swift +179 -0
  35. package/ios/Sources/FaceFrameResult.swift +96 -0
  36. package/ios/Sources/FaceMatchBundle.swift +26 -0
  37. package/ios/Sources/FaceMatchEngine.swift +136 -0
  38. package/ios/Sources/FaceMatchError.swift +40 -0
  39. package/ios/Sources/FaceMatchModule.m +55 -0
  40. package/ios/Sources/FaceMatchModule.swift +288 -0
  41. package/ios/Sources/FaceMatcherHelper.swift +107 -0
  42. package/ios/Sources/FaceOverlayView.swift +285 -0
  43. package/ios/Sources/ImageUtils.swift +322 -0
  44. package/ios/Sources/LivenessDetector.swift +505 -0
  45. package/ios/Sources/LivenessPrompts.swift +121 -0
  46. package/ios/Sources/LivenessVoice.swift +229 -0
  47. package/ios/Sources/OnnxRuntime/ORTShim.h +91 -0
  48. package/ios/Sources/OnnxRuntime/ORTShim.mm +260 -0
  49. package/ios/Sources/PrivateCaptureStore.swift +71 -0
  50. package/ios/Sources/VisionFaceFallback.swift +95 -0
  51. package/ios/onnxruntime-c.podspec +47 -0
  52. package/models/anti_spoof_minifasnet_v2.onnx +0 -0
  53. package/models/w600k_mbf.onnx +0 -0
  54. package/package.json +47 -4
  55. package/react-native.config.js +16 -0
  56. package/src/FaceCameraView.tsx +75 -0
  57. package/src/FaceMatch.ts +66 -0
  58. package/src/index.ts +4 -0
  59. package/src/types.ts +87 -0
@@ -0,0 +1,55 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "FaceMatch"
7
+ s.version = package["version"]
8
+ s.summary = "Offline on-device face liveness + face matching for React Native (iOS)."
9
+ s.description = <<-DESC
10
+ iOS half of #{package["name"]}. Same two ONNX models, same ML Kit face
11
+ detector, same alignment template and the same sigmoid score calibration as
12
+ the Android half, so similarity scores are comparable across platforms.
13
+ DESC
14
+ s.homepage = "https://www.npmjs.com/package/#{package["name"]}"
15
+ s.license = { :type => package["license"] }
16
+ s.author = package["author"]
17
+ s.platforms = { :ios => "15.5" }
18
+ s.source = { :path => "." }
19
+
20
+ s.source_files = "ios/Sources/**/*.{swift,h,m,mm}"
21
+ s.resources = ["models/*.onnx"]
22
+
23
+ s.swift_version = "5.0"
24
+ s.static_framework = true
25
+
26
+ # React Native (host app provides the RN pods).
27
+ s.dependency "React-Core"
28
+
29
+ # Bundled on-device face detection. Same detector and the same
30
+ # classification probabilities as `com.google.mlkit:face-detection` on
31
+ # Android, so LivenessDetector uses identical thresholds on both platforms.
32
+ s.dependency "GoogleMLKit/FaceDetection", "~> 8.0.0"
33
+
34
+ # Must stay pinned to the same version as onnxruntime-android in
35
+ # android/build.gradle so both platforms produce identical embeddings and
36
+ # anti-spoof scores.
37
+ #
38
+ # The trunk onnxruntime-c pod can no longer be downloaded, so the host app's
39
+ # Podfile must point at ios/onnxruntime-c.podspec in this package (see
40
+ # README). ios/Sources/OnnxRuntime/ORTShim.{h,mm} provides the ORT* classes
41
+ # on top of it in place of onnxruntime-objc.
42
+ s.dependency "onnxruntime-c", "1.22.0"
43
+
44
+ s.libraries = "c++"
45
+ # The ObjC++ shim converts ONNX Runtime's C++ exceptions into NSError; make
46
+ # ARC exception-safe so nothing leaks when that happens.
47
+ s.compiler_flags = "-fobjc-arc-exceptions"
48
+
49
+ s.pod_target_xcconfig = {
50
+ "DEFINES_MODULE" => "YES",
51
+ "CLANG_ENABLE_MODULES" => "YES",
52
+ "CLANG_CXX_LANGUAGE_STANDARD" => "c++17",
53
+ "OTHER_CPLUSPLUSFLAGS" => "$(inherited) -fvisibility=hidden -fvisibility-inlines-hidden"
54
+ }
55
+ end
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 androidmasterid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,191 @@
1
- # Temporary Holding Version
1
+ # react-native-face-match-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Offline, on-device face liveness, passive anti-spoofing and face matching for
4
+ React Native apps on Android and iOS. Everything runs on the phone: ML Kit finds
5
+ the face, and two bundled ONNX models check that it is real and produce a
6
+ 512-value face embedding. No network calls are made.
7
+
8
+ The app that uses this package writes no native code. Autolinking registers the
9
+ Android package and the iOS pod.
10
+
11
+ ## Requirements
12
+
13
+ | | Minimum |
14
+ | --- | --- |
15
+ | React Native | 0.76 or newer, New Architecture on or off |
16
+ | Android | minSdk 24, Kotlin, Java 17 (compileSdk and minSdk come from the app) |
17
+ | iOS | 15.5 (needed by ML Kit face detection) |
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install react-native-face-match-sdk
23
+ # or, while developing the SDK locally:
24
+ npm install ../react-native-face-match-sdk
25
+ ```
26
+
27
+ ### Installing from a local folder
28
+
29
+ `npm install ../react-native-face-match-sdk` creates a symlink, and Metro does not
30
+ follow symlinks outside the app by default. Add both of these to the app's
31
+ `metro.config.js` while developing against a local copy:
32
+
33
+ ```js
34
+ const path = require('path');
35
+ const sdkPath = path.resolve(__dirname, '../react-native-face-match-sdk');
36
+
37
+ const config = {
38
+ watchFolders: [sdkPath],
39
+ resolver: {
40
+ // Resolve react / react-native from the app, not from the SDK folder.
41
+ nodeModulesPaths: [path.join(__dirname, 'node_modules')],
42
+ },
43
+ };
44
+ ```
45
+
46
+ Installing the packed tarball avoids this, because it is copied into
47
+ `node_modules` like any npm package:
48
+
49
+ ```bash
50
+ cd ../react-native-face-match-sdk && npm pack
51
+ cd ../your-app && npm install ../react-native-face-match-sdk/react-native-face-match-sdk-1.0.3.tgz
52
+ ```
53
+
54
+ ### Android
55
+
56
+ Nothing else to do. The package's manifest already declares the `CAMERA`
57
+ permission. Ask for it at runtime before showing the camera.
58
+
59
+ If the app registered `FaceMatchPackage` by hand, or included a local
60
+ `:face-match` Gradle module, remove both. Registering the package twice crashes
61
+ the app at startup.
62
+
63
+ ### iOS
64
+
65
+ 1. Set the platform in `ios/Podfile` to at least 15.5:
66
+
67
+ ```ruby
68
+ platform :ios, '15.5'
69
+ ```
70
+
71
+ 2. Add this line inside the app target in `ios/Podfile`. The public
72
+ `onnxruntime-c` pod can no longer be downloaded, so this package ships a
73
+ SHA-pinned podspec that takes the same framework from Microsoft's NuGet
74
+ package:
75
+
76
+ ```ruby
77
+ pod 'onnxruntime-c', :podspec => '../node_modules/react-native-face-match-sdk/ios/onnxruntime-c.podspec'
78
+ ```
79
+
80
+ 3. Make sure `ios/<App>/Info.plist` has `NSCameraUsageDescription`.
81
+
82
+ 4. Install pods:
83
+
84
+ ```bash
85
+ cd ios && pod install
86
+ ```
87
+
88
+ The app's other pods must also target iOS 15.5 or higher. If `pod install`
89
+ warns about a lower deployment target, raise it in the Podfile's
90
+ `post_install` block.
91
+
92
+ ## Usage
93
+
94
+ ### Camera with liveness and auto-capture
95
+
96
+ ```tsx
97
+ import React, {useRef} from 'react';
98
+ import {FaceCamera, type FaceCameraHandle} from 'react-native-face-match-sdk';
99
+
100
+ export function FaceCheck() {
101
+ const camera = useRef<FaceCameraHandle>(null);
102
+
103
+ return (
104
+ <FaceCamera
105
+ ref={camera}
106
+ style={{width: 300, height: 400}}
107
+ autoStart
108
+ requireLiveness
109
+ autoCaptureOnLiveness
110
+ brightenOnLowLight
111
+ voiceLanguage="en"
112
+ voiceGender="female"
113
+ onCameraState={e => {
114
+ if (e.nativeEvent.state === 'started') camera.current?.startLiveness();
115
+ }}
116
+ onLiveness={e => console.log('liveness', e.nativeEvent)}
117
+ onCapture={e => console.log('embedding length', e.nativeEvent.embedding.length)}
118
+ onError={e => console.warn(e.nativeEvent.code, e.nativeEvent.message)}
119
+ />
120
+ );
121
+ }
122
+ ```
123
+
124
+ Commands on the ref: `startCamera()`, `stopCamera()`, `capture()` and
125
+ `startLiveness(actions?)`. With no actions, the native side picks a blink and one
126
+ movement in random order, then a neutral hold so the photo is taken straight-on.
127
+
128
+ Props are applied when the view is created, but commands can be dropped if they
129
+ arrive before the native view exists. Prefer `autoStart`, and re-send
130
+ `startCamera()` until `onCameraState` reports `started` if you need to be sure.
131
+
132
+ ### Matching
133
+
134
+ ```ts
135
+ import {FaceMatch} from 'react-native-face-match-sdk';
136
+
137
+ const ready = await FaceMatch.isModelReady();
138
+ const reference = await FaceMatch.generateReferenceEmbedding(referencePhotoUri);
139
+ const result = await FaceMatch.compareEmbeddings(reference.embedding, captured.embedding);
140
+ // `captured` is the nativeEvent from FaceCamera's onCapture.
141
+ // result: { similarityScore, status: 'match' | 'possible_match' | 'no_match', label, isMatch }
142
+ ```
143
+
144
+ Other calls: `pickImage()`, `detectFaces(uri)`, `generateEmbedding(uri)`,
145
+ `compareFaces(referenceUri, selfieUri, {antiSpoofThreshold})` and
146
+ `discardCapture(uri)`. Call `discardCapture` once you are done with a captured
147
+ photo so it does not stay on the device.
148
+
149
+ The similarity score is calibrated to 0-100. 80 and above is a match and 65-79 is
150
+ a possible match.
151
+
152
+ ## What is in the package
153
+
154
+ ```
155
+ android/ Kotlin module (com.facematch.sdk), CameraX, ML Kit, ONNX Runtime 1.22.0
156
+ ios/Sources/ Swift + ObjC module, AVFoundation, ML Kit, ONNX Runtime 1.22.0 C API wrapper
157
+ models/ w600k_mbf.onnx (embedding), anti_spoof_minifasnet_v2.onnx (anti-spoof), shared by both platforms
158
+ src/ TypeScript API: FaceMatch, FaceCamera and types
159
+ docs/ Design notes for each platform (not published to npm)
160
+ ```
161
+
162
+ Both platforms load the same two model files from `models/`. Keep ONNX Runtime at the same
163
+ version in `android/build.gradle` and `FaceMatch.podspec` so both platforms give
164
+ the same scores.
165
+
166
+ ## Publishing
167
+
168
+ The package is published publicly on npm. To release a new version:
169
+
170
+ ```bash
171
+ npm version patch # bumps package.json and creates a git tag
172
+ git push origin main --tags
173
+ npm pack --dry-run # check exactly which files will be published
174
+ npm publish
175
+ ```
176
+
177
+ ## License
178
+
179
+ The SDK source code is released under the [MIT License](LICENSE).
180
+
181
+ The bundled model files in `models/` are third-party works and keep their own
182
+ licenses. The MIT License does not apply to them:
183
+
184
+ | File | Origin | License |
185
+ |------|--------|---------|
186
+ | `anti_spoof_minifasnet_v2.onnx` | MiniVision [Silent-Face-Anti-Spoofing](https://github.com/minivision-ai/Silent-Face-Anti-Spoofing) (`2.7_80x80_MiniFASNetV2`, converted to ONNX) | Apache-2.0 |
187
+ | `w600k_mbf.onnx` | [InsightFace](https://github.com/deepinsight/insightface) WebFace600K MobileFaceNet | InsightFace states its pretrained models are for **non-commercial research purposes only** |
188
+
189
+ If you use this SDK in a commercial product, check the InsightFace terms and get
190
+ a commercial license from InsightFace, or replace `w600k_mbf.onnx` with a face
191
+ embedding model whose license allows commercial use.
@@ -0,0 +1,59 @@
1
+ apply plugin: "com.android.library"
2
+ apply plugin: "org.jetbrains.kotlin.android"
3
+
4
+ def safeExtGet(prop, fallback) {
5
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
6
+ }
7
+
8
+ android {
9
+ namespace "com.facematch.sdk"
10
+ compileSdk safeExtGet("compileSdkVersion", 35)
11
+
12
+ defaultConfig {
13
+ minSdkVersion safeExtGet("minSdkVersion", 24)
14
+ consumerProguardFiles "consumer-rules.pro"
15
+ }
16
+
17
+ compileOptions {
18
+ sourceCompatibility JavaVersion.VERSION_17
19
+ targetCompatibility JavaVersion.VERSION_17
20
+ }
21
+
22
+ kotlinOptions {
23
+ jvmTarget = "17"
24
+ }
25
+
26
+ // The two ONNX models live once at the package root and are shared with iOS.
27
+ sourceSets {
28
+ main {
29
+ assets.srcDirs += ["../models"]
30
+ }
31
+ }
32
+
33
+ packagingOptions {
34
+ resources {
35
+ excludes += ["META-INF/DEPENDENCIES", "META-INF/LICENSE", "META-INF/LICENSE.txt"]
36
+ }
37
+ }
38
+ }
39
+
40
+ dependencies {
41
+ implementation("com.facebook.react:react-android")
42
+ implementation("androidx.core:core-ktx:1.15.0")
43
+ implementation("androidx.exifinterface:exifinterface:1.3.7")
44
+ implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
45
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
46
+
47
+ def cameraxVersion = "1.3.1"
48
+ implementation("androidx.camera:camera-core:${cameraxVersion}")
49
+ implementation("androidx.camera:camera-camera2:${cameraxVersion}")
50
+ implementation("androidx.camera:camera-lifecycle:${cameraxVersion}")
51
+ implementation("androidx.camera:camera-view:${cameraxVersion}")
52
+
53
+ // Both artifacts package their models/native runtimes in the APK and work offline.
54
+ // Use versions that include 16 KB page-size compatible Android native libraries.
55
+ // Keep onnxruntime-android in sync with onnxruntime-c in FaceMatch.podspec.
56
+ implementation("com.google.mlkit:face-detection:16.1.7")
57
+ implementation("com.microsoft.onnxruntime:onnxruntime-android:1.22.0")
58
+ testImplementation("junit:junit:4.13.2")
59
+ }
@@ -0,0 +1,5 @@
1
+ -keep class ai.onnxruntime.** { *; }
2
+ -keepclassmembers class ai.onnxruntime.** { *; }
3
+ -dontwarn ai.onnxruntime.**
4
+ -keep class com.google.mlkit.** { *; }
5
+ -dontwarn com.google.mlkit.**
@@ -0,0 +1,11 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
3
+ <uses-permission android:name="android.permission.CAMERA" />
4
+ <uses-feature android:name="android.hardware.camera" android:required="false" />
5
+ <uses-feature android:name="android.hardware.camera.front" android:required="false" />
6
+ <queries>
7
+ <intent>
8
+ <action android:name="android.intent.action.TTS_SERVICE" />
9
+ </intent>
10
+ </queries>
11
+ </manifest>
@@ -0,0 +1,216 @@
1
+ package com.facematch.sdk
2
+
3
+ import ai.onnxruntime.OnnxTensor
4
+ import ai.onnxruntime.OrtEnvironment
5
+ import ai.onnxruntime.OrtSession
6
+ import android.content.Context
7
+ import android.graphics.Bitmap
8
+ import android.graphics.RectF
9
+ import android.util.Log
10
+ import java.nio.FloatBuffer
11
+ import kotlin.math.ceil
12
+ import kotlin.math.exp
13
+ import kotlin.math.floor
14
+
15
+ enum class AntiSpoofStatus(val wireName: String) {
16
+ REAL("real"),
17
+ SPOOF("spoof"),
18
+ ERROR("error")
19
+ }
20
+
21
+ data class AntiSpoofResult(
22
+ val status: AntiSpoofStatus,
23
+ val realScore: Float?,
24
+ val threshold: Float,
25
+ val errorMessage: String? = null
26
+ )
27
+
28
+ /**
29
+ * Offline MiniFASNetV2 inference using MiniVision's official
30
+ * 2.7_80x80_MiniFASNetV2 checkpoint converted to ONNX.
31
+ *
32
+ * The model expects a 2.7x expanded face crop as raw BGR float32 CHW data and
33
+ * emits three logits. Upstream class index 1 is REAL; indices 0 and 2 are
34
+ * presentation attacks.
35
+ */
36
+ class AntiSpoofHelper(context: Context) {
37
+ companion object {
38
+ // Active head-motion + blink liveness is already mandatory. A 0.55
39
+ // passive threshold keeps the second, complementary check enabled
40
+ // without rejecting genuine captures for ordinary lighting variation.
41
+ // Lowered from 0.60 to improve real-world lighting tolerance.
42
+ const val DEFAULT_THRESHOLD = 0.55f
43
+ private const val TAG = "FaceMatchAntiSpoof"
44
+ private const val MODEL_FILE = "anti_spoof_minifasnet_v2.onnx"
45
+ private const val INPUT_SIZE = 80
46
+ private const val CROP_SCALE = 2.7f
47
+ private const val REAL_CLASS_INDEX = 1
48
+
49
+ fun sanitizeThreshold(value: Float): Float =
50
+ if (value.isFinite()) value.coerceIn(0f, 1f) else DEFAULT_THRESHOLD
51
+ }
52
+
53
+ private val env = OrtEnvironment.getEnvironment()
54
+ private val session: OrtSession?
55
+ private val initializationError: String?
56
+
57
+ val isReady: Boolean get() = session != null
58
+
59
+ init {
60
+ var loadedSession: OrtSession? = null
61
+ var loadError: String? = null
62
+ try {
63
+ require(context.assets.list("")?.contains(MODEL_FILE) == true) {
64
+ "Anti-spoof model is missing from Android assets: $MODEL_FILE"
65
+ }
66
+ val bytes = context.assets.open(MODEL_FILE).use { it.readBytes() }
67
+ loadedSession = env.createSession(bytes, OrtSession.SessionOptions())
68
+ if (BuildConfig.DEBUG) {
69
+ Log.i(TAG, "Initialized $MODEL_FILE (${bytes.size} bytes, CPU ONNX Runtime)")
70
+ }
71
+ } catch (error: Throwable) {
72
+ loadError = error.message ?: "Unable to initialize passive anti-spoof model"
73
+ if (BuildConfig.DEBUG) {
74
+ Log.e(TAG, loadError, error)
75
+ } else {
76
+ Log.e(TAG, "Passive anti-spoof model initialization failed")
77
+ }
78
+ }
79
+ session = loadedSession
80
+ initializationError = loadError
81
+ }
82
+
83
+ @Synchronized
84
+ fun classify(bitmap: Bitmap, faceBounds: RectF, requestedThreshold: Float): AntiSpoofResult {
85
+ val threshold = sanitizeThreshold(requestedThreshold)
86
+ val activeSession = session ?: return AntiSpoofResult(
87
+ AntiSpoofStatus.ERROR,
88
+ null,
89
+ threshold,
90
+ initializationError ?: "Passive anti-spoof model is unavailable"
91
+ )
92
+
93
+ return try {
94
+ buildTensor(bitmap, faceBounds).use { tensor ->
95
+ val inputName = activeSession.inputNames.first()
96
+ activeSession.run(mapOf(inputName to tensor)).use { output ->
97
+ val logits = extractLogits(activeSession, output)
98
+ ?: throw IllegalStateException("MiniFASNetV2 returned an invalid output")
99
+ require(logits.size > REAL_CLASS_INDEX) {
100
+ "MiniFASNetV2 output has ${logits.size} classes; expected 3"
101
+ }
102
+ val realScore = softmax(logits)[REAL_CLASS_INDEX]
103
+ val status = if (realScore >= threshold) {
104
+ AntiSpoofStatus.REAL
105
+ } else {
106
+ AntiSpoofStatus.SPOOF
107
+ }
108
+ if (BuildConfig.DEBUG) {
109
+ val margin = (realScore - threshold) * 100f
110
+ if (status == AntiSpoofStatus.SPOOF) {
111
+ Log.w(TAG, "SPOOF rejected: realScore=$realScore threshold=$threshold margin=${margin}%")
112
+ } else {
113
+ Log.d(TAG, "REAL accepted: realScore=$realScore threshold=$threshold margin=${margin}%")
114
+ }
115
+ }
116
+ AntiSpoofResult(status, realScore, threshold)
117
+ }
118
+ }
119
+ } catch (error: Throwable) {
120
+ val message = error.message ?: "Passive anti-spoof inference failed"
121
+ if (BuildConfig.DEBUG) {
122
+ Log.e(TAG, message, error)
123
+ } else {
124
+ Log.e(TAG, "Passive anti-spoof inference failed")
125
+ }
126
+ AntiSpoofResult(AntiSpoofStatus.ERROR, null, threshold, message)
127
+ }
128
+ }
129
+
130
+ private fun buildTensor(bitmap: Bitmap, bounds: RectF): OnnxTensor {
131
+ require(bitmap.width > 1 && bitmap.height > 1) { "Camera frame is too small" }
132
+ require(bounds.width() > 1f && bounds.height() > 1f) { "Detected face bounds are invalid" }
133
+
134
+ val crop = expandedCrop(bitmap, bounds)
135
+ val resized = Bitmap.createScaledBitmap(crop, INPUT_SIZE, INPUT_SIZE, true)
136
+ if (resized !== crop && !crop.isRecycled) crop.recycle()
137
+
138
+ try {
139
+ val pixels = IntArray(INPUT_SIZE * INPUT_SIZE)
140
+ resized.getPixels(pixels, 0, INPUT_SIZE, 0, 0, INPUT_SIZE, INPUT_SIZE)
141
+ val buffer = FloatBuffer.allocate(3 * INPUT_SIZE * INPUT_SIZE)
142
+
143
+ // Upstream images are read by OpenCV, so preserve its BGR channel order.
144
+ for (channel in 0..2) {
145
+ for (pixel in pixels) {
146
+ val value = when (channel) {
147
+ 0 -> pixel and 0xFF
148
+ 1 -> (pixel shr 8) and 0xFF
149
+ else -> (pixel shr 16) and 0xFF
150
+ }
151
+ buffer.put(value.toFloat())
152
+ }
153
+ }
154
+ buffer.rewind()
155
+ return OnnxTensor.createTensor(
156
+ env,
157
+ buffer,
158
+ longArrayOf(1L, 3L, INPUT_SIZE.toLong(), INPUT_SIZE.toLong())
159
+ )
160
+ } finally {
161
+ if (!resized.isRecycled) resized.recycle()
162
+ }
163
+ }
164
+
165
+ private fun expandedCrop(bitmap: Bitmap, bounds: RectF): Bitmap {
166
+ val scale = minOf(
167
+ (bitmap.height - 1f) / bounds.height(),
168
+ (bitmap.width - 1f) / bounds.width(),
169
+ CROP_SCALE
170
+ )
171
+ val width = bounds.width() * scale
172
+ val height = bounds.height() * scale
173
+ val centerX = bounds.centerX()
174
+ val centerY = bounds.centerY()
175
+
176
+ var left = centerX - width / 2f
177
+ var top = centerY - height / 2f
178
+ var right = centerX + width / 2f
179
+ var bottom = centerY + height / 2f
180
+
181
+ if (left < 0f) { right -= left; left = 0f }
182
+ if (top < 0f) { bottom -= top; top = 0f }
183
+ if (right > bitmap.width - 1f) {
184
+ left -= right - bitmap.width + 1f
185
+ right = bitmap.width - 1f
186
+ }
187
+ if (bottom > bitmap.height - 1f) {
188
+ top -= bottom - bitmap.height + 1f
189
+ bottom = bitmap.height - 1f
190
+ }
191
+
192
+ val x0 = floor(left).toInt().coerceIn(0, bitmap.width - 1)
193
+ val y0 = floor(top).toInt().coerceIn(0, bitmap.height - 1)
194
+ val x1 = ceil(right).toInt().coerceIn(x0, bitmap.width - 1)
195
+ val y1 = ceil(bottom).toInt().coerceIn(y0, bitmap.height - 1)
196
+ return Bitmap.createBitmap(bitmap, x0, y0, x1 - x0 + 1, y1 - y0 + 1)
197
+ }
198
+
199
+ private fun extractLogits(session: OrtSession, result: OrtSession.Result): FloatArray? {
200
+ val tensor = result.get(session.outputNames.first()).orElse(null) as? OnnxTensor ?: return null
201
+ return when (val value = tensor.value) {
202
+ is Array<*> -> @Suppress("UNCHECKED_CAST")
203
+ (value as? Array<FloatArray>)?.firstOrNull()
204
+ is FloatArray -> value
205
+ else -> null
206
+ }
207
+ }
208
+
209
+ private fun softmax(logits: FloatArray): FloatArray {
210
+ val max = logits.maxOrNull() ?: return FloatArray(0)
211
+ val exponentials = DoubleArray(logits.size) { exp((logits[it] - max).toDouble()) }
212
+ val sum = exponentials.sum()
213
+ require(sum > 0.0 && sum.isFinite()) { "MiniFASNetV2 produced non-finite logits" }
214
+ return FloatArray(logits.size) { (exponentials[it] / sum).toFloat() }
215
+ }
216
+ }