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,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/README.md
CHANGED
|
@@ -1,3 +1,175 @@
|
|
|
1
|
-
#
|
|
1
|
+
# react-native-face-match-sdk
|
|
2
2
|
|
|
3
|
-
|
|
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.1.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
|
+
`publishConfig.access` is `restricted`, so `npm publish` creates a **private**
|
|
169
|
+
package. That needs a paid npm plan. Before making it public, check the licence
|
|
170
|
+
of both model files and choose a licence for the code.
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
npm pack --dry-run # check exactly which files will be published
|
|
174
|
+
npm publish
|
|
175
|
+
```
|
|
@@ -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,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
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
package com.facematch.sdk
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.graphics.Bitmap
|
|
5
|
+
import android.graphics.BitmapFactory
|
|
6
|
+
import android.graphics.Matrix
|
|
7
|
+
import android.net.Uri
|
|
8
|
+
import androidx.exifinterface.media.ExifInterface
|
|
9
|
+
import java.io.File
|
|
10
|
+
import java.io.FileInputStream
|
|
11
|
+
import java.io.InputStream
|
|
12
|
+
|
|
13
|
+
object BitmapUtils {
|
|
14
|
+
private const val MAX_SOURCE_BYTES = 64L * 1024L * 1024L
|
|
15
|
+
private const val MAX_DECODED_DIMENSION = 4096
|
|
16
|
+
private const val MAX_DECODED_PIXELS = 8L * 1024L * 1024L
|
|
17
|
+
|
|
18
|
+
fun decode(context: Context, uriString: String): Bitmap {
|
|
19
|
+
require(uriString.isNotBlank()) { "Image URI must not be empty" }
|
|
20
|
+
val uri = validateUri(context, Uri.parse(uriString))
|
|
21
|
+
validateKnownSize(context, uri)
|
|
22
|
+
|
|
23
|
+
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
|
24
|
+
open(context, uri).use { BitmapFactory.decodeStream(it, null, bounds) }
|
|
25
|
+
require(bounds.outWidth > 0 && bounds.outHeight > 0) {
|
|
26
|
+
"Unsupported or unreadable image"
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
var sampleSize = 1
|
|
30
|
+
while (
|
|
31
|
+
bounds.outWidth / sampleSize > MAX_DECODED_DIMENSION ||
|
|
32
|
+
bounds.outHeight / sampleSize > MAX_DECODED_DIMENSION ||
|
|
33
|
+
(bounds.outWidth.toLong() / sampleSize) * (bounds.outHeight.toLong() / sampleSize) > MAX_DECODED_PIXELS
|
|
34
|
+
) {
|
|
35
|
+
sampleSize *= 2
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
val options = BitmapFactory.Options().apply {
|
|
39
|
+
inSampleSize = sampleSize
|
|
40
|
+
inPreferredConfig = Bitmap.Config.ARGB_8888
|
|
41
|
+
}
|
|
42
|
+
val bitmap = open(context, uri).use { stream ->
|
|
43
|
+
BitmapFactory.decodeStream(stream, null, options)
|
|
44
|
+
?: throw IllegalArgumentException("Unsupported or unreadable image")
|
|
45
|
+
}
|
|
46
|
+
val orientation = runCatching {
|
|
47
|
+
open(context, uri).use { stream ->
|
|
48
|
+
ExifInterface(stream).getAttributeInt(
|
|
49
|
+
ExifInterface.TAG_ORIENTATION,
|
|
50
|
+
ExifInterface.ORIENTATION_NORMAL
|
|
51
|
+
)
|
|
52
|
+
}
|
|
53
|
+
}.getOrDefault(ExifInterface.ORIENTATION_NORMAL)
|
|
54
|
+
return orient(bitmap, orientation)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private fun validateUri(context: Context, uri: Uri): Uri {
|
|
58
|
+
return when (uri.scheme?.lowercase()) {
|
|
59
|
+
"content" -> {
|
|
60
|
+
require(!uri.authority.isNullOrBlank()) { "Content URI must include an authority" }
|
|
61
|
+
uri
|
|
62
|
+
}
|
|
63
|
+
"android.resource" -> uri
|
|
64
|
+
"file" -> {
|
|
65
|
+
val path = requireNotNull(uri.path) { "File URI must include a path" }
|
|
66
|
+
val target = File(path).canonicalFile
|
|
67
|
+
val allowedRoots = listOf(
|
|
68
|
+
context.filesDir,
|
|
69
|
+
context.cacheDir,
|
|
70
|
+
context.noBackupFilesDir,
|
|
71
|
+
context.codeCacheDir
|
|
72
|
+
).map { it.canonicalFile }
|
|
73
|
+
require(allowedRoots.any { root ->
|
|
74
|
+
target == root || target.path.startsWith(root.path + File.separator)
|
|
75
|
+
}) { "File URI must point to app-private storage" }
|
|
76
|
+
Uri.fromFile(target)
|
|
77
|
+
}
|
|
78
|
+
else -> throw IllegalArgumentException(
|
|
79
|
+
"Only content://, android.resource://, and app-private file:// images are supported"
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
private fun validateKnownSize(context: Context, uri: Uri) {
|
|
85
|
+
val length = when (uri.scheme?.lowercase()) {
|
|
86
|
+
"file" -> File(requireNotNull(uri.path)).length()
|
|
87
|
+
"content", "android.resource" -> runCatching {
|
|
88
|
+
context.contentResolver.openAssetFileDescriptor(uri, "r")?.use { it.length }
|
|
89
|
+
}.getOrNull() ?: -1L
|
|
90
|
+
else -> -1L
|
|
91
|
+
}
|
|
92
|
+
require(length <= 0L || length <= MAX_SOURCE_BYTES) { "Image file is too large" }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
private fun open(context: Context, uri: Uri): InputStream {
|
|
96
|
+
return when (uri.scheme?.lowercase()) {
|
|
97
|
+
"content", "android.resource" -> context.contentResolver.openInputStream(uri)
|
|
98
|
+
"file" -> FileInputStream(File(requireNotNull(uri.path)))
|
|
99
|
+
null, "" -> FileInputStream(File(uri.toString()))
|
|
100
|
+
else -> throw IllegalArgumentException("Only local content:// and file:// images are supported")
|
|
101
|
+
} ?: throw IllegalArgumentException("Unable to open image: $uri")
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private fun orient(source: Bitmap, orientation: Int): Bitmap {
|
|
105
|
+
val matrix = Matrix()
|
|
106
|
+
when (orientation) {
|
|
107
|
+
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f)
|
|
108
|
+
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
|
|
109
|
+
ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.setScale(1f, -1f)
|
|
110
|
+
ExifInterface.ORIENTATION_TRANSPOSE -> {
|
|
111
|
+
matrix.setRotate(90f)
|
|
112
|
+
matrix.postScale(-1f, 1f)
|
|
113
|
+
}
|
|
114
|
+
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
|
|
115
|
+
ExifInterface.ORIENTATION_TRANSVERSE -> {
|
|
116
|
+
matrix.setRotate(-90f)
|
|
117
|
+
matrix.postScale(-1f, 1f)
|
|
118
|
+
}
|
|
119
|
+
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f)
|
|
120
|
+
else -> return source
|
|
121
|
+
}
|
|
122
|
+
return Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
|
|
123
|
+
.also { if (it !== source) source.recycle() }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
fun rotateDegrees(source: Bitmap, degrees: Int): Bitmap {
|
|
127
|
+
if (degrees % 360 == 0) return source
|
|
128
|
+
val matrix = Matrix().apply { postRotate(degrees.toFloat()) }
|
|
129
|
+
return Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
|
|
130
|
+
.also { if (it !== source) source.recycle() }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
fun mirrorHorizontal(source: Bitmap): Bitmap {
|
|
134
|
+
val matrix = Matrix().apply { preScale(-1f, 1f) }
|
|
135
|
+
return Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
|
|
136
|
+
.also { if (it !== source) source.recycle() }
|
|
137
|
+
}
|
|
138
|
+
}
|