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,228 @@
1
+ package com.facematch.sdk
2
+
3
+ import android.graphics.RectF
4
+ import android.graphics.Bitmap
5
+ import androidx.camera.core.ImageAnalysis
6
+ import androidx.camera.core.ImageProxy
7
+ import com.google.mlkit.vision.common.InputImage
8
+ import com.google.mlkit.vision.face.Face
9
+ import com.google.mlkit.vision.face.FaceDetection
10
+ import com.google.mlkit.vision.face.FaceDetectorOptions
11
+ import com.google.mlkit.vision.face.FaceLandmark
12
+ import kotlin.math.abs
13
+
14
+ /** A single, upright camera-frame result used by guidance and liveness. */
15
+ data class FaceFrameResult(
16
+ val rect: RectF?,
17
+ val landmarks: FloatArray?,
18
+ val imageWidth: Int,
19
+ val imageHeight: Int,
20
+ /** Mean perceived brightness of the frame, 0 (black) to 255 (white). */
21
+ val luminance: Float = 255f,
22
+ val yaw: Float = 0f,
23
+ val pitch: Float = 0f,
24
+ val roll: Float = 0f,
25
+ val leftEyeOpenProbability: Float? = null,
26
+ val rightEyeOpenProbability: Float? = null,
27
+ val smilingProbability: Float? = null,
28
+ val antiSpoof: AntiSpoofResult? = null,
29
+ val faceCount: Int = if (rect == null) 0 else 1
30
+ ) {
31
+ val hasFace: Boolean get() = rect != null
32
+ val hasMultipleFaces: Boolean get() = faceCount > 1
33
+ val isGoodPose: Boolean
34
+ get() = hasFace && abs(yaw) <= 12f && abs(roll) <= 15f && abs(pitch) <= 12f
35
+
36
+ /** Face-box width as a fraction of the frame width — the distance proxy. */
37
+ val faceFill: Float
38
+ get() {
39
+ val box = rect ?: return 0f
40
+ if (imageWidth <= 0) return 0f
41
+ return box.width() / imageWidth
42
+ }
43
+
44
+ /** Strict framing gate that must hold before a liveness step begins. */
45
+ val isPositioned: Boolean
46
+ get() {
47
+ val box = rect ?: return false
48
+ if (imageWidth <= 0 || imageHeight <= 0) return false
49
+ val centerX = box.centerX() / imageWidth
50
+ val centerY = box.centerY() / imageHeight
51
+ return centerX in 0.25f..0.75f &&
52
+ centerY in 0.20f..0.72f &&
53
+ faceFill in 0.22f..0.72f
54
+ }
55
+
56
+ /** Loose framing check used while a head turn / lean is in progress. */
57
+ val looselyInFrame: Boolean
58
+ get() {
59
+ val box = rect ?: return false
60
+ if (imageWidth <= 0 || imageHeight <= 0) return false
61
+ val centerX = box.centerX() / imageWidth
62
+ val centerY = box.centerY() / imageHeight
63
+ return centerX in 0.12f..0.88f &&
64
+ centerY in 0.10f..0.85f &&
65
+ faceFill in 0.14f..0.88f
66
+ }
67
+ }
68
+
69
+ /** CameraX analyzer backed by the bundled, on-device ML Kit face detector. */
70
+ class FaceFrameAnalyzer(
71
+ private val onResult: (FaceFrameResult) -> Unit,
72
+ private val onPreviewFrame: (Bitmap) -> Unit,
73
+ private val classifyAntiSpoof: (Bitmap, RectF, Float) -> AntiSpoofResult
74
+ ) : ImageAnalysis.Analyzer {
75
+
76
+ private companion object {
77
+ // Grid resolution for the coarse luminance sample (LUMA_SAMPLES per axis).
78
+ const val LUMA_SAMPLES = 20
79
+ }
80
+
81
+ @Volatile
82
+ private var antiSpoofThreshold = AntiSpoofHelper.DEFAULT_THRESHOLD
83
+
84
+ private val detector = FaceDetection.getClient(
85
+ FaceDetectorOptions.Builder()
86
+ .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST)
87
+ .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
88
+ .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL)
89
+ .enableTracking()
90
+ .setMinFaceSize(0.12f)
91
+ .build()
92
+ )
93
+
94
+ override fun analyze(proxy: ImageProxy) {
95
+ val bitmap = try {
96
+ BitmapUtils.rotateDegrees(proxy.toBitmap(), proxy.imageInfo.rotationDegrees)
97
+ } catch (_: Throwable) {
98
+ proxy.close()
99
+ return
100
+ }
101
+ val imageWidth = bitmap.width
102
+ val imageHeight = bitmap.height
103
+ val luminance = estimateLuminance(bitmap)
104
+
105
+ detector.process(InputImage.fromBitmap(bitmap, 0))
106
+ .addOnSuccessListener { faces ->
107
+ val significantFaces = FaceCandidateFilter.significant(
108
+ faces,
109
+ bounds = { RectF(it.boundingBox) },
110
+ hasFullLandmarks = { it.hasRequiredLandmarks() }
111
+ )
112
+ val face = significantFaces.firstOrNull()
113
+ val faceCount = significantFaces.size
114
+ val frame = (face?.toFrameResult(imageWidth, imageHeight, faceCount)
115
+ ?: FaceFrameResult(null, null, imageWidth, imageHeight))
116
+ .copy(luminance = luminance)
117
+ // Passive anti-spoofing is deliberately evaluated after ML Kit
118
+ // face detection and before the active-liveness state machine.
119
+ // More than one face fails closed before any identity inference.
120
+ onResult(if (face == null || faceCount != 1) frame else frame.copy(
121
+ antiSpoof = classifyAntiSpoof(
122
+ bitmap,
123
+ RectF(face.boundingBox),
124
+ antiSpoofThreshold
125
+ )
126
+ ))
127
+ }
128
+ .addOnFailureListener {
129
+ onResult(
130
+ FaceFrameResult(null, null, imageWidth, imageHeight, luminance = luminance)
131
+ )
132
+ }
133
+ .addOnCompleteListener {
134
+ // ML Kit has finished reading this bitmap. Transfer ownership
135
+ // to the preview renderer, which recycles it when replaced.
136
+ try {
137
+ onPreviewFrame(bitmap)
138
+ } catch (_: Throwable) {
139
+ if (!bitmap.isRecycled) bitmap.recycle()
140
+ }
141
+ proxy.close()
142
+ }
143
+ }
144
+
145
+ fun setAntiSpoofThreshold(value: Float) {
146
+ antiSpoofThreshold = AntiSpoofHelper.sanitizeThreshold(value)
147
+ }
148
+
149
+ /**
150
+ * Mean perceived brightness (0-255) sampled over a coarse grid. Used to
151
+ * detect low-light conditions so the host can boost screen brightness.
152
+ */
153
+ private fun estimateLuminance(bitmap: Bitmap): Float {
154
+ val stepX = (bitmap.width / LUMA_SAMPLES).coerceAtLeast(1)
155
+ val stepY = (bitmap.height / LUMA_SAMPLES).coerceAtLeast(1)
156
+ var sum = 0.0
157
+ var count = 0
158
+ var y = 0
159
+ while (y < bitmap.height) {
160
+ var x = 0
161
+ while (x < bitmap.width) {
162
+ val c = bitmap.getPixel(x, y)
163
+ val r = (c shr 16) and 0xFF
164
+ val g = (c shr 8) and 0xFF
165
+ val b = c and 0xFF
166
+ sum += 0.299 * r + 0.587 * g + 0.114 * b
167
+ count++
168
+ x += stepX
169
+ }
170
+ y += stepY
171
+ }
172
+ return if (count == 0) 255f else (sum / count).toFloat()
173
+ }
174
+
175
+ private fun Face.hasRequiredLandmarks(): Boolean =
176
+ getLandmark(FaceLandmark.LEFT_EYE) != null &&
177
+ getLandmark(FaceLandmark.RIGHT_EYE) != null &&
178
+ getLandmark(FaceLandmark.NOSE_BASE) != null &&
179
+ getLandmark(FaceLandmark.MOUTH_LEFT) != null &&
180
+ getLandmark(FaceLandmark.MOUTH_RIGHT) != null
181
+
182
+ private fun Face.toFrameResult(
183
+ imageWidth: Int,
184
+ imageHeight: Int,
185
+ detectedFaceCount: Int
186
+ ): FaceFrameResult {
187
+ val cx = boundingBox.exactCenterX()
188
+ val cy = boundingBox.exactCenterY()
189
+ val width = boundingBox.width().toFloat()
190
+ val height = boundingBox.height().toFloat()
191
+
192
+ fun x(type: Int, fallback: Float) = getLandmark(type)?.position?.x ?: fallback
193
+ fun y(type: Int, fallback: Float) = getLandmark(type)?.position?.y ?: fallback
194
+
195
+ val leftEyeX = x(FaceLandmark.LEFT_EYE, cx - width * 0.15f)
196
+ val leftEyeY = y(FaceLandmark.LEFT_EYE, cy - height * 0.10f)
197
+ val rightEyeX = x(FaceLandmark.RIGHT_EYE, cx + width * 0.15f)
198
+ val rightEyeY = y(FaceLandmark.RIGHT_EYE, cy - height * 0.10f)
199
+ val noseX = x(FaceLandmark.NOSE_BASE, cx)
200
+ val noseY = y(FaceLandmark.NOSE_BASE, cy + height * 0.02f)
201
+ val mouthLeftX = x(FaceLandmark.MOUTH_LEFT, cx - width * 0.12f)
202
+ val mouthLeftY = y(FaceLandmark.MOUTH_LEFT, cy + height * 0.20f)
203
+ val mouthRightX = x(FaceLandmark.MOUTH_RIGHT, cx + width * 0.12f)
204
+ val mouthRightY = y(FaceLandmark.MOUTH_RIGHT, cy + height * 0.20f)
205
+
206
+ return FaceFrameResult(
207
+ rect = RectF(boundingBox),
208
+ landmarks = floatArrayOf(
209
+ leftEyeX, leftEyeY,
210
+ rightEyeX, rightEyeY,
211
+ noseX, noseY,
212
+ mouthLeftX, mouthLeftY,
213
+ mouthRightX, mouthRightY
214
+ ),
215
+ imageWidth = imageWidth,
216
+ imageHeight = imageHeight,
217
+ yaw = headEulerAngleY,
218
+ pitch = headEulerAngleX,
219
+ roll = headEulerAngleZ,
220
+ leftEyeOpenProbability = leftEyeOpenProbability,
221
+ rightEyeOpenProbability = rightEyeOpenProbability,
222
+ smilingProbability = smilingProbability,
223
+ faceCount = detectedFaceCount
224
+ )
225
+ }
226
+
227
+ fun close() = detector.close()
228
+ }
@@ -0,0 +1,249 @@
1
+ package com.facematch.sdk
2
+
3
+ import android.app.Activity
4
+ import android.content.Intent
5
+ import android.graphics.Bitmap
6
+ import com.facebook.react.bridge.ActivityEventListener
7
+ import com.facebook.react.bridge.Arguments
8
+ import com.facebook.react.bridge.Promise
9
+ import com.facebook.react.bridge.ReactApplicationContext
10
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
11
+ import com.facebook.react.bridge.ReactMethod
12
+ import com.facebook.react.bridge.ReadableArray
13
+ import kotlinx.coroutines.CoroutineScope
14
+ import kotlinx.coroutines.Dispatchers
15
+ import kotlinx.coroutines.SupervisorJob
16
+ import kotlinx.coroutines.cancel
17
+ import kotlinx.coroutines.launch
18
+
19
+ /** Promise-based React Native bridge for offline image detection and matching. */
20
+ class FaceMatchModule(private val reactContext: ReactApplicationContext) :
21
+ ReactContextBaseJavaModule(reactContext), ActivityEventListener {
22
+
23
+ companion object {
24
+ const val NAME = "FaceMatch"
25
+ private const val PICK_IMAGE_REQUEST = 48127
26
+ private const val EMBEDDING_SIZE = 512
27
+ }
28
+
29
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
30
+ private var imagePickerPromise: Promise? = null
31
+
32
+ init {
33
+ reactContext.addActivityEventListener(this)
34
+ // Bind the shared TTS engine now so the first liveness instruction is
35
+ // spoken the moment the camera opens instead of after a cold bind.
36
+ SharedTts.prewarm(reactContext)
37
+ }
38
+
39
+ override fun getName(): String = NAME
40
+
41
+ @ReactMethod
42
+ fun isModelReady(promise: Promise) {
43
+ scope.launch {
44
+ runCatching { FaceMatchRuntime.isReady(reactContext) }
45
+ .onSuccess { promise.resolve(it) }
46
+ .onFailure { promise.reject("E_MODEL", it.message, it) }
47
+ }
48
+ }
49
+
50
+ @ReactMethod
51
+ fun pickImage(promise: Promise) {
52
+ val activity = currentActivity
53
+ if (activity == null) {
54
+ promise.reject("E_NO_ACTIVITY", "No foreground Activity is available")
55
+ return
56
+ }
57
+ if (imagePickerPromise != null) {
58
+ promise.reject("E_PICKER_BUSY", "An image picker is already open")
59
+ return
60
+ }
61
+ imagePickerPromise = promise
62
+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
63
+ addCategory(Intent.CATEGORY_OPENABLE)
64
+ type = "image/*"
65
+ // Keep access scoped to this foreground task. The SDK does not
66
+ // retain a long-lived grant to the user's photo provider.
67
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
68
+ }
69
+ runCatching { activity.startActivityForResult(intent, PICK_IMAGE_REQUEST) }
70
+ .onFailure {
71
+ imagePickerPromise = null
72
+ promise.reject("E_PICKER", it.message, it)
73
+ }
74
+ }
75
+
76
+ @ReactMethod
77
+ fun detectFaces(uri: String, promise: Promise) = withBitmap(uri, promise) { bitmap ->
78
+ val faces = FaceMatchRuntime.get(reactContext).detect(bitmap)
79
+ val result = Arguments.createMap().apply {
80
+ putInt("faceCount", faces.size)
81
+ putArray("faces", Arguments.createArray().also { array ->
82
+ faces.forEach { face ->
83
+ array.pushMap(Arguments.createMap().apply {
84
+ putDouble("left", face.boundingBox.left.toDouble())
85
+ putDouble("top", face.boundingBox.top.toDouble())
86
+ putDouble("right", face.boundingBox.right.toDouble())
87
+ putDouble("bottom", face.boundingBox.bottom.toDouble())
88
+ putBoolean("hasFullLandmarkSet", face.hasFullSet)
89
+ })
90
+ }
91
+ })
92
+ }
93
+ result
94
+ }
95
+
96
+ @ReactMethod
97
+ fun generateEmbedding(uri: String, promise: Promise) = withBitmap(uri, promise) { bitmap ->
98
+ val extraction = FaceMatchRuntime.get(reactContext).extract(bitmap)
99
+ Arguments.createMap().apply {
100
+ putInt("faceCount", extraction.faceCount)
101
+ putArray("embedding", extraction.embedding.toWritableArray())
102
+ }
103
+ }
104
+
105
+ @ReactMethod
106
+ fun generateReferenceEmbedding(uri: String, promise: Promise) = withBitmap(uri, promise) { bitmap ->
107
+ val extraction = FaceMatchRuntime.get(reactContext).extractReference(bitmap)
108
+ Arguments.createMap().apply {
109
+ putInt("faceCount", extraction.faceCount)
110
+ putArray("embedding", extraction.embedding.toWritableArray())
111
+ }
112
+ }
113
+
114
+ @ReactMethod
115
+ fun compareFaces(referenceUri: String, selfieUri: String, promise: Promise) {
116
+ compareFacesInternal(
117
+ referenceUri,
118
+ selfieUri,
119
+ AntiSpoofHelper.DEFAULT_THRESHOLD,
120
+ promise
121
+ )
122
+ }
123
+
124
+ @ReactMethod
125
+ fun compareFacesWithThreshold(
126
+ referenceUri: String,
127
+ selfieUri: String,
128
+ antiSpoofThreshold: Double,
129
+ promise: Promise
130
+ ) {
131
+ compareFacesInternal(referenceUri, selfieUri, antiSpoofThreshold.toFloat(), promise)
132
+ }
133
+
134
+ private fun compareFacesInternal(
135
+ referenceUri: String,
136
+ selfieUri: String,
137
+ antiSpoofThreshold: Float,
138
+ promise: Promise
139
+ ) {
140
+ scope.launch {
141
+ var reference: Bitmap? = null
142
+ var selfie: Bitmap? = null
143
+ try {
144
+ reference = BitmapUtils.decode(reactContext, referenceUri)
145
+ selfie = BitmapUtils.decode(reactContext, selfieUri)
146
+ val result = FaceMatchRuntime.get(reactContext).compare(
147
+ reference,
148
+ selfie,
149
+ AntiSpoofHelper.sanitizeThreshold(antiSpoofThreshold)
150
+ )
151
+ promise.resolve(result.toWritableMap())
152
+ } catch (error: Throwable) {
153
+ reject(promise, error)
154
+ } finally {
155
+ reference?.takeUnless { it.isRecycled }?.recycle()
156
+ selfie?.takeUnless { it.isRecycled }?.recycle()
157
+ }
158
+ }
159
+ }
160
+
161
+ @ReactMethod
162
+ fun compareEmbeddings(first: ReadableArray, second: ReadableArray, promise: Promise) {
163
+ scope.launch {
164
+ try {
165
+ require(first.size() == EMBEDDING_SIZE && second.size() == EMBEDDING_SIZE) {
166
+ "Embedding arrays must each contain exactly $EMBEDDING_SIZE values"
167
+ }
168
+ val a = FloatArray(EMBEDDING_SIZE) { index ->
169
+ first.getDouble(index)
170
+ .also { require(it.isFinite()) { "Embedding values must be finite" } }
171
+ .toFloat()
172
+ }
173
+ val b = FloatArray(EMBEDDING_SIZE) { index ->
174
+ second.getDouble(index)
175
+ .also { require(it.isFinite()) { "Embedding values must be finite" } }
176
+ .toFloat()
177
+ }
178
+ promise.resolve(FaceMatcherHelper.compare(a, b).toWritableMap())
179
+ } catch (error: Throwable) {
180
+ reject(promise, error)
181
+ }
182
+ }
183
+ }
184
+
185
+ /** Deletes only camera captures created inside this SDK's private cache. */
186
+ @ReactMethod
187
+ fun discardCapture(uri: String, promise: Promise) {
188
+ scope.launch {
189
+ runCatching { PrivateCaptureStore.deleteIfOwned(reactContext, uri) }
190
+ .onSuccess { promise.resolve(it) }
191
+ .onFailure { promise.reject("E_CAPTURE_CLEANUP", "Unable to remove private capture") }
192
+ }
193
+ }
194
+
195
+ private fun withBitmap(
196
+ uri: String,
197
+ promise: Promise,
198
+ operation: suspend (Bitmap) -> Any
199
+ ) {
200
+ scope.launch {
201
+ var bitmap: Bitmap? = null
202
+ try {
203
+ bitmap = BitmapUtils.decode(reactContext, uri)
204
+ promise.resolve(operation(bitmap))
205
+ } catch (error: Throwable) {
206
+ reject(promise, error)
207
+ } finally {
208
+ bitmap?.takeUnless { it.isRecycled }?.recycle()
209
+ }
210
+ }
211
+ }
212
+
213
+ private fun reject(promise: Promise, error: Throwable) {
214
+ val code = (error as? FaceMatchException)?.errorCode ?: "E_FACE_MATCH"
215
+ promise.reject(code, error.message ?: "Face matching failed", error)
216
+ }
217
+
218
+ override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
219
+ if (requestCode != PICK_IMAGE_REQUEST) return
220
+ val promise = imagePickerPromise ?: return
221
+ imagePickerPromise = null
222
+ if (resultCode != Activity.RESULT_OK || data?.data == null) {
223
+ promise.resolve(null)
224
+ return
225
+ }
226
+ promise.resolve(requireNotNull(data.data).toString())
227
+ }
228
+
229
+ override fun onNewIntent(intent: Intent) = Unit
230
+
231
+ override fun invalidate() {
232
+ imagePickerPromise?.reject("E_INVALIDATED", "FaceMatch module was invalidated")
233
+ imagePickerPromise = null
234
+ scope.cancel()
235
+ reactContext.removeActivityEventListener(this)
236
+ super.invalidate()
237
+ }
238
+
239
+ private fun FloatArray.toWritableArray() = Arguments.createArray().also { array ->
240
+ forEach { array.pushDouble(it.toDouble()) }
241
+ }
242
+
243
+ private fun FaceMatcherHelper.MatchResult.toWritableMap() = Arguments.createMap().apply {
244
+ putDouble("similarityScore", faceSimilarityScore.toDouble())
245
+ putString("status", matchStatus.name.lowercase())
246
+ putString("label", matchStatus.label)
247
+ putBoolean("isMatch", isMatch)
248
+ }
249
+ }
@@ -0,0 +1,14 @@
1
+ package com.facematch.sdk
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+ class FaceMatchPackage : ReactPackage {
9
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> =
10
+ listOf(FaceMatchModule(reactContext))
11
+
12
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> =
13
+ listOf(FaceCameraViewManager())
14
+ }
@@ -0,0 +1,138 @@
1
+ package com.facematch.sdk
2
+
3
+ import android.content.Context
4
+ import android.graphics.Bitmap
5
+ import android.graphics.RectF
6
+ import kotlinx.coroutines.sync.Mutex
7
+ import kotlinx.coroutines.sync.withLock
8
+
9
+ data class FaceExtraction(val embedding: FloatArray, val faceCount: Int)
10
+
11
+ class FaceMatchException(val errorCode: String, message: String, cause: Throwable? = null) :
12
+ Exception(message, cause)
13
+
14
+ /** Shared application-lifetime inference engine used by both the module and camera view. */
15
+ class FaceMatchEngine(context: Context) {
16
+ private val detector = FaceDetectionHelper()
17
+ private val embedder = FaceEmbeddingHelper(context.applicationContext)
18
+ private val antiSpoof = AntiSpoofHelper(context.applicationContext)
19
+ private val inferenceMutex = Mutex()
20
+
21
+ val isReady: Boolean get() = antiSpoof.isReady
22
+
23
+ fun classifyAntiSpoof(
24
+ bitmap: Bitmap,
25
+ faceBounds: RectF,
26
+ threshold: Float
27
+ ): AntiSpoofResult = antiSpoof.classify(bitmap, faceBounds, threshold)
28
+
29
+ suspend fun detect(bitmap: Bitmap): List<DetectedFace> = inferenceMutex.withLock {
30
+ significantFaces(detector.detectFaces(bitmap))
31
+ }
32
+
33
+ suspend fun extract(bitmap: Bitmap): FaceExtraction = inferenceMutex.withLock {
34
+ val faces = significantFaces(detector.detectFaces(bitmap))
35
+ extractDetectedFace(bitmap, faces, isReference = false)
36
+ }
37
+
38
+ /** Enhanced template path for old, printed or scanned identity photos. */
39
+ suspend fun extractReference(bitmap: Bitmap): FaceExtraction = inferenceMutex.withLock {
40
+ val faces = significantFaces(detector.detectFaces(bitmap))
41
+ extractDetectedFace(bitmap, faces, isReference = true)
42
+ }
43
+
44
+ /** Apply the same face-selection policy to uploads and camera captures. */
45
+ private fun significantFaces(detected: List<DetectedFace>): List<DetectedFace> =
46
+ FaceCandidateFilter.significant(
47
+ detected,
48
+ bounds = DetectedFace::boundingBox,
49
+ hasFullLandmarks = DetectedFace::hasFullSet
50
+ )
51
+
52
+ /** Fail-closed extraction path for live selfies and face comparison. */
53
+ suspend fun extractLive(
54
+ bitmap: Bitmap,
55
+ threshold: Float = AntiSpoofHelper.DEFAULT_THRESHOLD
56
+ ): FaceExtraction = inferenceMutex.withLock {
57
+ val faces = significantFaces(detector.detectFaces(bitmap))
58
+ if (faces.isEmpty()) {
59
+ throw FaceMatchException("E_NO_FACE", "No face detected in the image")
60
+ }
61
+ if (faces.size > 1) {
62
+ throw FaceMatchException(
63
+ "E_MULTIPLE_FACES",
64
+ "Multiple faces detected. Only one person is allowed"
65
+ )
66
+ }
67
+ val passiveResult = antiSpoof.classify(bitmap, faces.first().boundingBox, threshold)
68
+ when (passiveResult.status) {
69
+ AntiSpoofStatus.REAL -> Unit
70
+ AntiSpoofStatus.SPOOF -> throw FaceMatchException(
71
+ "E_ANTI_SPOOF",
72
+ "We could not confirm a live face. Please try again in clear, even lighting."
73
+ )
74
+ AntiSpoofStatus.ERROR -> throw FaceMatchException(
75
+ "E_ANTI_SPOOF_MODEL",
76
+ passiveResult.errorMessage ?: "Passive anti-spoofing is unavailable"
77
+ )
78
+ }
79
+ extractDetectedFace(bitmap, faces, isReference = false)
80
+ }
81
+
82
+ private fun extractDetectedFace(
83
+ bitmap: Bitmap,
84
+ faces: List<DetectedFace>,
85
+ isReference: Boolean
86
+ ): FaceExtraction {
87
+ if (faces.isEmpty()) {
88
+ throw FaceMatchException("E_NO_FACE", "No face detected in the image")
89
+ }
90
+ if (faces.size > 1) {
91
+ throw FaceMatchException(
92
+ "E_MULTIPLE_FACES",
93
+ "Multiple faces detected. Choose an image containing one person."
94
+ )
95
+ }
96
+ val (cropped, landmarks) = FaceAlignmentHelper.cropFaceRegion(bitmap, faces.first())
97
+ val aligned = try {
98
+ FaceAlignmentHelper.alignFace(cropped, landmarks)
99
+ } finally {
100
+ if (cropped !== bitmap && !cropped.isRecycled) cropped.recycle()
101
+ }
102
+ return try {
103
+ val embedding = if (isReference) {
104
+ embedder.getReferenceEmbedding(aligned)
105
+ } else {
106
+ embedder.getEmbedding(aligned)
107
+ }
108
+ ?: throw FaceMatchException("E_EMBEDDING", "Could not generate a face embedding")
109
+ FaceExtraction(embedding, faces.size)
110
+ } finally {
111
+ if (!aligned.isRecycled) aligned.recycle()
112
+ }
113
+ }
114
+
115
+ suspend fun compare(
116
+ reference: Bitmap,
117
+ selfie: Bitmap,
118
+ antiSpoofThreshold: Float = AntiSpoofHelper.DEFAULT_THRESHOLD
119
+ ): FaceMatcherHelper.MatchResult {
120
+ val referenceEmbedding = extractReference(reference).embedding
121
+ val selfieEmbedding = extractLive(selfie, antiSpoofThreshold).embedding
122
+ return FaceMatcherHelper.compare(referenceEmbedding, selfieEmbedding)
123
+ }
124
+
125
+ }
126
+
127
+ object FaceMatchRuntime {
128
+ @Volatile private var instance: FaceMatchEngine? = null
129
+
130
+ fun get(context: Context): FaceMatchEngine {
131
+ instance?.let { return it }
132
+ return synchronized(this) {
133
+ instance ?: FaceMatchEngine(context.applicationContext).also { instance = it }
134
+ }
135
+ }
136
+
137
+ fun isReady(context: Context): Boolean = runCatching { get(context).isReady }.getOrDefault(false)
138
+ }