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,79 @@
1
+ package com.facematch.sdk
2
+
3
+ import com.facebook.react.bridge.ReadableArray
4
+ import com.facebook.react.uimanager.SimpleViewManager
5
+ import com.facebook.react.uimanager.ThemedReactContext
6
+ import com.facebook.react.uimanager.annotations.ReactProp
7
+
8
+ class FaceCameraViewManager : SimpleViewManager<FaceCameraView>() {
9
+ companion object {
10
+ const val NAME = "FaceCameraView"
11
+ private const val START_CAMERA = 1
12
+ private const val STOP_CAMERA = 2
13
+ private const val CAPTURE = 3
14
+ private const val START_LIVENESS = 4
15
+ }
16
+
17
+ override fun getName(): String = NAME
18
+
19
+ override fun createViewInstance(reactContext: ThemedReactContext) = FaceCameraView(reactContext)
20
+
21
+ @ReactProp(name = "requireLiveness", defaultBoolean = true)
22
+ fun setRequireLiveness(view: FaceCameraView, value: Boolean) = view.setRequireLiveness(value)
23
+
24
+ @ReactProp(name = "autoStart", defaultBoolean = false)
25
+ fun setAutoStart(view: FaceCameraView, value: Boolean) = view.setAutoStart(value)
26
+
27
+ @ReactProp(name = "autoCaptureOnLiveness", defaultBoolean = false)
28
+ fun setAutoCaptureOnLiveness(view: FaceCameraView, value: Boolean) =
29
+ view.setAutoCaptureOnLiveness(value)
30
+
31
+ @ReactProp(name = "antiSpoofThreshold", defaultFloat = AntiSpoofHelper.DEFAULT_THRESHOLD)
32
+ fun setAntiSpoofThreshold(view: FaceCameraView, value: Float) =
33
+ view.setAntiSpoofThreshold(value)
34
+
35
+ @ReactProp(name = "brightenOnLowLight", defaultBoolean = true)
36
+ fun setBrightenOnLowLight(view: FaceCameraView, value: Boolean) =
37
+ view.setBrightenOnLowLight(value)
38
+
39
+ @ReactProp(name = "voiceLanguage")
40
+ fun setVoiceLanguage(view: FaceCameraView, value: String?) =
41
+ view.setVoiceLanguage(value ?: "none")
42
+
43
+ @ReactProp(name = "voiceGender")
44
+ fun setVoiceGender(view: FaceCameraView, value: String?) =
45
+ view.setVoiceGender(value ?: "female")
46
+
47
+ override fun getCommandsMap(): Map<String, Int> = mapOf(
48
+ "startCamera" to START_CAMERA,
49
+ "stopCamera" to STOP_CAMERA,
50
+ "capture" to CAPTURE,
51
+ "startLiveness" to START_LIVENESS
52
+ )
53
+
54
+ override fun receiveCommand(root: FaceCameraView, commandId: Int, args: ReadableArray?) {
55
+ when (commandId) {
56
+ START_CAMERA -> root.startCamera()
57
+ STOP_CAMERA -> root.stopCamera()
58
+ CAPTURE -> root.capture()
59
+ START_LIVENESS -> root.startLiveness(
60
+ args?.getArray(0)?.let { array ->
61
+ List(array.size()) { index -> array.getString(index) }.filterNotNull()
62
+ }
63
+ )
64
+ }
65
+ }
66
+
67
+ override fun getExportedCustomDirectEventTypeConstants(): Map<String, Any> = mapOf(
68
+ "topFaceState" to mapOf("registrationName" to "onFaceState"),
69
+ "topLiveness" to mapOf("registrationName" to "onLiveness"),
70
+ "topCapture" to mapOf("registrationName" to "onCapture"),
71
+ "topError" to mapOf("registrationName" to "onError"),
72
+ "topCameraState" to mapOf("registrationName" to "onCameraState")
73
+ )
74
+
75
+ override fun onDropViewInstance(view: FaceCameraView) {
76
+ view.dispose()
77
+ super.onDropViewInstance(view)
78
+ }
79
+ }
@@ -0,0 +1,65 @@
1
+ package com.facematch.sdk
2
+
3
+ import android.graphics.RectF
4
+
5
+ /**
6
+ * Removes the small, incomplete and overlapping detections that ML Kit can
7
+ * occasionally report around a single high-resolution face. The largest face
8
+ * is the subject; another detection is counted only when it is a credible,
9
+ * spatially distinct second person.
10
+ */
11
+ object FaceCandidateFilter {
12
+ fun <T> significant(
13
+ candidates: List<T>,
14
+ bounds: (T) -> RectF,
15
+ hasFullLandmarks: (T) -> Boolean
16
+ ): List<T> {
17
+ if (candidates.isEmpty()) return emptyList()
18
+
19
+ val sorted = candidates.sortedByDescending { area(bounds(it)) }
20
+ val primary = sorted.first()
21
+ val primaryBounds = bounds(primary)
22
+ if (!isValid(primaryBounds)) return emptyList()
23
+
24
+ val accepted = mutableListOf(primary)
25
+ sorted.drop(1).forEach { candidate ->
26
+ val candidateBounds = bounds(candidate)
27
+ val isCredibleSecondFace =
28
+ isValid(candidateBounds) &&
29
+ hasFullLandmarks(candidate) &&
30
+ area(candidateBounds) >= area(primaryBounds) * MIN_SECONDARY_AREA_RATIO &&
31
+ minSide(candidateBounds) >= minSide(primaryBounds) * MIN_SECONDARY_SIDE_RATIO &&
32
+ aspectRatio(candidateBounds) in MIN_ASPECT_RATIO..MAX_ASPECT_RATIO &&
33
+ accepted.none { overlapOverSmaller(candidateBounds, bounds(it)) >= MAX_DUPLICATE_OVERLAP }
34
+
35
+ if (isCredibleSecondFace) accepted += candidate
36
+ }
37
+ return accepted
38
+ }
39
+
40
+ private fun isValid(rect: RectF): Boolean =
41
+ rect.left.isFinite() && rect.top.isFinite() &&
42
+ rect.right.isFinite() && rect.bottom.isFinite() &&
43
+ rect.width() > 1f && rect.height() > 1f
44
+
45
+ private fun area(rect: RectF): Float = rect.width() * rect.height()
46
+
47
+ private fun minSide(rect: RectF): Float = minOf(rect.width(), rect.height())
48
+
49
+ private fun aspectRatio(rect: RectF): Float = rect.width() / rect.height()
50
+
51
+ private fun overlapOverSmaller(first: RectF, second: RectF): Float {
52
+ val intersectionWidth = (minOf(first.right, second.right) -
53
+ maxOf(first.left, second.left)).coerceAtLeast(0f)
54
+ val intersectionHeight = (minOf(first.bottom, second.bottom) -
55
+ maxOf(first.top, second.top)).coerceAtLeast(0f)
56
+ val smallerArea = minOf(area(first), area(second))
57
+ return if (smallerArea <= 0f) 0f else intersectionWidth * intersectionHeight / smallerArea
58
+ }
59
+
60
+ private const val MIN_SECONDARY_AREA_RATIO = 0.28f
61
+ private const val MIN_SECONDARY_SIDE_RATIO = 0.45f
62
+ private const val MIN_ASPECT_RATIO = 0.55f
63
+ private const val MAX_ASPECT_RATIO = 1.65f
64
+ private const val MAX_DUPLICATE_OVERLAP = 0.35f
65
+ }
@@ -0,0 +1,225 @@
1
+ package com.facematch.sdk
2
+
3
+ import android.graphics.Bitmap
4
+ import android.graphics.PointF
5
+ import android.graphics.RectF
6
+ import com.google.mlkit.vision.common.InputImage
7
+ import com.google.mlkit.vision.face.Face
8
+ import com.google.mlkit.vision.face.FaceDetection
9
+ import com.google.mlkit.vision.face.FaceDetectorOptions
10
+ import com.google.mlkit.vision.face.FaceLandmark
11
+ import kotlinx.coroutines.suspendCancellableCoroutine
12
+ import kotlin.coroutines.resume
13
+ import kotlin.coroutines.resumeWithException
14
+
15
+ /**
16
+ * Detected face with 5-point landmarks in source-image pixel coordinates.
17
+ *
18
+ * Landmark order matches the InsightFace image-coordinate convention:
19
+ * image-left eye, image-right eye, nose tip, image-left mouth, image-right mouth
20
+ *
21
+ * ML Kit's LEFT/RIGHT constants are anatomical (relative to the subject), so
22
+ * ordering each symmetric pair by x-coordinate is essential. It also makes
23
+ * alignment identical for ordinary reference photos and mirrored selfies.
24
+ *
25
+ * @param landmarks Flat [x0,y0, x1,y1, …] array (10 floats).
26
+ * @param boundingBox Axis-aligned bounding box in source-image pixels.
27
+ * @param hasFullSet True when all 5 ML Kit landmarks were present;
28
+ * False means some positions were estimated from the bbox.
29
+ */
30
+ data class DetectedFace(
31
+ val landmarks: FloatArray,
32
+ val boundingBox: RectF,
33
+ val hasFullSet: Boolean
34
+ ) {
35
+ val bboxArea: Float get() = boundingBox.width() * boundingBox.height()
36
+
37
+ /** Minimum side length in pixels — faces smaller than 80px produce poor embeddings. */
38
+ val minSide: Float get() = minOf(boundingBox.width(), boundingBox.height())
39
+
40
+ override fun equals(other: Any?) = other is DetectedFace &&
41
+ landmarks.contentEquals(other.landmarks) && boundingBox == other.boundingBox
42
+
43
+ override fun hashCode() = 31 * landmarks.contentHashCode() + boundingBox.hashCode()
44
+ }
45
+
46
+ /**
47
+ * Wraps ML Kit Face Detection as a Kotlin suspend function.
48
+ *
49
+ * Uses PERFORMANCE_MODE_ACCURATE with all landmarks enabled so we always
50
+ * obtain the 5 points needed for InsightFace-style alignment.
51
+ *
52
+ * The model runs entirely on-device via Google Play Services — no network
53
+ * calls are made.
54
+ */
55
+ class FaceDetectionHelper {
56
+
57
+ companion object {
58
+ /** Reject faces smaller than this — 50px is the practical minimum for
59
+ * MobileFaceNet to produce a useful embedding. ID document photos
60
+ * often have faces occupying only a small portion of the image. */
61
+ private const val MIN_FACE_PX = 50f
62
+
63
+ /** Upscale images whose longest side is smaller than this before
64
+ * detection — ensures tiny faces in ID/passport photos are found. */
65
+ private const val DETECT_MIN_SIDE = 480
66
+
67
+ /** Downscale images whose longest side exceeds this — avoids wasted
68
+ * computation and OOM on very large photos. */
69
+ private const val DETECT_MAX_SIDE = 1920
70
+
71
+ /**
72
+ * Resize [bitmap] so its longest side falls within
73
+ * [DETECT_MIN_SIDE]..[DETECT_MAX_SIDE]. Returns the original
74
+ * bitmap unchanged when already in range.
75
+ */
76
+ fun prepareForDetection(bitmap: Bitmap): Bitmap {
77
+ val longest = maxOf(bitmap.width, bitmap.height)
78
+ val scale = when {
79
+ longest < DETECT_MIN_SIDE -> DETECT_MIN_SIDE.toFloat() / longest
80
+ longest > DETECT_MAX_SIDE -> DETECT_MAX_SIDE.toFloat() / longest
81
+ else -> return bitmap
82
+ }
83
+ val nw = maxOf(1, (bitmap.width * scale).toInt())
84
+ val nh = maxOf(1, (bitmap.height * scale).toInt())
85
+ return Bitmap.createScaledBitmap(bitmap, nw, nh, true)
86
+ }
87
+ }
88
+
89
+ private val detector = FaceDetection.getClient(
90
+ FaceDetectorOptions.Builder()
91
+ .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
92
+ .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
93
+ // No classification: [DetectedFace] carries landmarks and a bounding
94
+ // box only, so the smile / eye-open probabilities this used to request
95
+ // were computed and then discarded on every capture-path detect.
96
+ // Per-frame liveness classification lives in FaceFrameAnalyzer, which
97
+ // still asks for CLASSIFICATION_MODE_ALL because it does read them.
98
+ .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_NONE)
99
+ .setMinFaceSize(0.05f) // 5% — handles faces in ID/passport documents
100
+ .build()
101
+ )
102
+
103
+ /**
104
+ * Detect all faces in [bitmap] and return them sorted largest-first.
105
+ * Each [DetectedFace] carries 5-point landmarks suitable for alignment.
106
+ *
107
+ * The bitmap is first resized to the optimal detection range
108
+ * [DETECT_MIN_SIDE, DETECT_MAX_SIDE] so that faces in tiny ID photos
109
+ * are reliably found without sacrificing performance on large images.
110
+ *
111
+ * Returns an empty list when no face is found.
112
+ */
113
+ suspend fun detectFaces(bitmap: Bitmap): List<DetectedFace> {
114
+ val prepared = prepareForDetection(bitmap)
115
+ // Scale factor to map detected landmarks/boxes back to original coordinates
116
+ val scaleX = bitmap.width.toFloat() / prepared.width.toFloat()
117
+ val scaleY = bitmap.height.toFloat() / prepared.height.toFloat()
118
+
119
+ return suspendCancellableCoroutine { cont ->
120
+ val image = InputImage.fromBitmap(prepared, 0)
121
+ detector.process(image)
122
+ .addOnSuccessListener { faces ->
123
+ val result = faces
124
+ .map { it.toDetectedFace(scaleX, scaleY) }
125
+ .filter { it.minSide >= MIN_FACE_PX }
126
+ .sortedByDescending { it.bboxArea }
127
+ cont.resume(result)
128
+ }
129
+ .addOnFailureListener { e ->
130
+ cont.resumeWithException(e)
131
+ }
132
+ }
133
+ }
134
+
135
+ /** Release detector resources. Call from Activity.onDestroy(). */
136
+ fun close() = detector.close()
137
+
138
+ // -----------------------------------------------------------------------
139
+ // ML Kit Face → DetectedFace
140
+ // -----------------------------------------------------------------------
141
+
142
+ private fun Face.toDetectedFace(scaleX: Float = 1f, scaleY: Float = 1f): DetectedFace {
143
+ // Attempt to read all 5 ML Kit landmarks
144
+ val subjectLeftEye = getLandmark(FaceLandmark.LEFT_EYE)?.position
145
+ val subjectRightEye = getLandmark(FaceLandmark.RIGHT_EYE)?.position
146
+ val noseTip = getLandmark(FaceLandmark.NOSE_BASE)?.position
147
+ val subjectLeftMouth = getLandmark(FaceLandmark.MOUTH_LEFT)?.position
148
+ val subjectRightMouth = getLandmark(FaceLandmark.MOUTH_RIGHT)?.position
149
+
150
+ val hasAll = subjectLeftEye != null && subjectRightEye != null && noseTip != null &&
151
+ subjectLeftMouth != null && subjectRightMouth != null
152
+
153
+ // Fall back to geometric estimates from the bounding box when a
154
+ // landmark is missing (rare but can happen with partially occluded faces).
155
+ val cx = boundingBox.exactCenterX()
156
+ val cy = boundingBox.exactCenterY()
157
+ val w = boundingBox.width()
158
+ val h = boundingBox.height()
159
+
160
+ val (imageLeftEye, imageRightEye) = orderHorizontalPair(
161
+ subjectLeftEye,
162
+ subjectRightEye,
163
+ cx,
164
+ cy - h * 0.10f,
165
+ w * 0.15f
166
+ )
167
+ val nx = noseTip?.x ?: cx
168
+ val ny = noseTip?.y ?: cy
169
+ val (imageLeftMouth, imageRightMouth) = orderHorizontalPair(
170
+ subjectLeftMouth,
171
+ subjectRightMouth,
172
+ cx,
173
+ cy + h * 0.20f,
174
+ w * 0.10f
175
+ )
176
+
177
+ // Scale all coordinates back to original (pre-resize) bitmap space
178
+ return DetectedFace(
179
+ landmarks = floatArrayOf(
180
+ imageLeftEye.x * scaleX, imageLeftEye.y * scaleY,
181
+ imageRightEye.x * scaleX, imageRightEye.y * scaleY,
182
+ nx * scaleX, ny * scaleY,
183
+ imageLeftMouth.x * scaleX, imageLeftMouth.y * scaleY,
184
+ imageRightMouth.x * scaleX, imageRightMouth.y * scaleY
185
+ ),
186
+ boundingBox = RectF(
187
+ boundingBox.left * scaleX,
188
+ boundingBox.top * scaleY,
189
+ boundingBox.right * scaleX,
190
+ boundingBox.bottom * scaleY
191
+ ),
192
+ hasFullSet = hasAll
193
+ )
194
+ }
195
+
196
+ /**
197
+ * Returns a symmetric landmark pair in image-left to image-right order.
198
+ * When ML Kit omits one point, its position relative to the face centre is
199
+ * used to place the fallback on the opposite side without assuming whether
200
+ * the input bitmap is mirrored.
201
+ */
202
+ private fun orderHorizontalPair(
203
+ first: PointF?,
204
+ second: PointF?,
205
+ centerX: Float,
206
+ fallbackY: Float,
207
+ halfSeparation: Float
208
+ ): Pair<PointF, PointF> {
209
+ if (first != null && second != null) {
210
+ return if (first.x <= second.x) first to second else second to first
211
+ }
212
+
213
+ val detected = first ?: second
214
+ if (detected == null) {
215
+ return PointF(centerX - halfSeparation, fallbackY) to
216
+ PointF(centerX + halfSeparation, fallbackY)
217
+ }
218
+
219
+ return if (detected.x <= centerX) {
220
+ detected to PointF(centerX + halfSeparation, fallbackY)
221
+ } else {
222
+ PointF(centerX - halfSeparation, fallbackY) to detected
223
+ }
224
+ }
225
+ }
@@ -0,0 +1,242 @@
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.Matrix
9
+ import java.io.Closeable
10
+ import java.nio.FloatBuffer
11
+ import kotlin.math.sqrt
12
+
13
+ /**
14
+ * Offline 512-dimensional MobileFaceNet/ArcFace embedding inference.
15
+ *
16
+ * Input images are already aligned to the InsightFace 112x112 template. The
17
+ * model receives natural RGB normalised by `(pixel - 127.5) / 128`, matching
18
+ * its standard training and export preprocessing.
19
+ */
20
+ class FaceEmbeddingHelper(context: Context) : Closeable {
21
+ companion object {
22
+ private const val MODEL_FILE = "w600k_mbf.onnx"
23
+ private const val INPUT_SIZE = FaceAlignmentHelper.FACE_SIZE
24
+ private const val MEAN = 127.5f
25
+ private const val STD = 128.0f
26
+ }
27
+
28
+ private val env = OrtEnvironment.getEnvironment()
29
+ private val session: OrtSession
30
+
31
+ init {
32
+ require(context.assets.list("")?.contains(MODEL_FILE) == true) {
33
+ "Model not found in assets. Copy $MODEL_FILE to app/src/main/assets and rebuild."
34
+ }
35
+ val modelBytes = context.assets.open(MODEL_FILE).use { it.readBytes() }
36
+ session = env.createSession(modelBytes, OrtSession.SessionOptions())
37
+ }
38
+
39
+ /**
40
+ * Produces one L2-normalised identity embedding. Normal and mirrored
41
+ * inference results are fused to reduce sensitivity to minor pose,
42
+ * illumination and landmark differences between reference and live images.
43
+ */
44
+ fun getEmbedding(face: Bitmap): FloatArray? {
45
+ return getAugmentedEmbedding(face, includeDocumentNormalization = false)
46
+ }
47
+
48
+ /**
49
+ * Produces a reference template that is less sensitive to faded prints,
50
+ * scanner contrast and colour ageing in identity-document photographs.
51
+ * The ordinary and gently tone-normalised templates are fused on the unit
52
+ * hypersphere; neither template can independently force a match.
53
+ */
54
+ fun getReferenceEmbedding(face: Bitmap): FloatArray? {
55
+ return getAugmentedEmbedding(face, includeDocumentNormalization = true)
56
+ }
57
+
58
+ private fun getAugmentedEmbedding(
59
+ face: Bitmap,
60
+ includeDocumentNormalization: Boolean
61
+ ): FloatArray? {
62
+ val primary = runEmbedding(face) ?: return null
63
+ val embeddings = mutableListOf(primary)
64
+ flippedEmbedding(face)?.let(embeddings::add)
65
+
66
+ if (includeDocumentNormalization) {
67
+ val normalised = normalizeDocumentTone(face)
68
+ try {
69
+ runEmbedding(normalised)?.let(embeddings::add)
70
+ flippedEmbedding(normalised)?.let(embeddings::add)
71
+ } finally {
72
+ if (normalised !== face && !normalised.isRecycled) normalised.recycle()
73
+ }
74
+ }
75
+
76
+ return fuse(embeddings) ?: primary
77
+ }
78
+
79
+ private fun flippedEmbedding(face: Bitmap): FloatArray? {
80
+ // Horizontal-flip test-time augmentation is standard for ArcFace.
81
+ val matrix = Matrix().apply { preScale(-1f, 1f) }
82
+ val mirrored = Bitmap.createBitmap(
83
+ face,
84
+ 0,
85
+ 0,
86
+ face.width,
87
+ face.height,
88
+ matrix,
89
+ true
90
+ )
91
+ return try {
92
+ runEmbedding(mirrored)
93
+ } finally {
94
+ if (mirrored !== face && !mirrored.isRecycled) mirrored.recycle()
95
+ }
96
+ }
97
+
98
+ private fun fuse(embeddings: List<FloatArray>): FloatArray? {
99
+ if (embeddings.isEmpty()) return null
100
+ val sum = FloatArray(embeddings.first().size)
101
+ embeddings.forEach { embedding ->
102
+ if (embedding.size != sum.size) return null
103
+ embedding.forEachIndexed { index, value -> sum[index] += value }
104
+ }
105
+ return l2Normalize(sum)
106
+ }
107
+
108
+ /**
109
+ * Applies a restrained luminance percentile stretch. Blending only 35% of
110
+ * the correction preserves identity texture while reducing the domain gap
111
+ * between an old printed/scanned document and a current camera image.
112
+ */
113
+ private fun normalizeDocumentTone(source: Bitmap): Bitmap {
114
+ val width = source.width
115
+ val height = source.height
116
+ val pixels = IntArray(width * height)
117
+ source.getPixels(pixels, 0, width, 0, 0, width, height)
118
+
119
+ val histogram = IntArray(256)
120
+ pixels.forEach { pixel ->
121
+ val red = (pixel shr 16) and 0xFF
122
+ val green = (pixel shr 8) and 0xFF
123
+ val blue = pixel and 0xFF
124
+ histogram[(77 * red + 150 * green + 29 * blue) shr 8]++
125
+ }
126
+
127
+ val lowTarget = (pixels.size * 0.02f).toInt()
128
+ val highTarget = (pixels.size * 0.98f).toInt()
129
+ var cumulative = 0
130
+ var low = 0
131
+ var high = 255
132
+ for (level in histogram.indices) {
133
+ cumulative += histogram[level]
134
+ if (cumulative >= lowTarget) {
135
+ low = level
136
+ break
137
+ }
138
+ }
139
+ cumulative = 0
140
+ for (level in histogram.indices) {
141
+ cumulative += histogram[level]
142
+ if (cumulative >= highTarget) {
143
+ high = level
144
+ break
145
+ }
146
+ }
147
+ if (high - low < 32) return source
148
+
149
+ val range = (high - low).toFloat()
150
+ pixels.indices.forEach { index ->
151
+ val pixel = pixels[index]
152
+ val alpha = (pixel ushr 24) and 0xFF
153
+ val red = (pixel shr 16) and 0xFF
154
+ val green = (pixel shr 8) and 0xFF
155
+ val blue = pixel and 0xFF
156
+ val luminance = (77 * red + 150 * green + 29 * blue) shr 8
157
+ val stretched = ((luminance - low) * 255f / range).coerceIn(0f, 255f)
158
+ val delta = ((stretched - luminance) * 0.35f).toInt()
159
+ pixels[index] = (alpha shl 24) or
160
+ ((red + delta).coerceIn(0, 255) shl 16) or
161
+ ((green + delta).coerceIn(0, 255) shl 8) or
162
+ (blue + delta).coerceIn(0, 255)
163
+ }
164
+ return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888)
165
+ }
166
+
167
+ private fun runEmbedding(face: Bitmap): FloatArray? = try {
168
+ buildTensor(face).use { tensor ->
169
+ val inputName = session.inputNames.first()
170
+ session.run(mapOf(inputName to tensor)).use { result ->
171
+ extractEmbedding(result)?.let(::l2Normalize)
172
+ }
173
+ }
174
+ } catch (_: Exception) {
175
+ null
176
+ }
177
+
178
+ private fun buildTensor(bitmap: Bitmap): OnnxTensor {
179
+ val scaledRaw = if (bitmap.width != INPUT_SIZE || bitmap.height != INPUT_SIZE) {
180
+ Bitmap.createScaledBitmap(bitmap, INPUT_SIZE, INPUT_SIZE, true)
181
+ } else {
182
+ bitmap
183
+ }
184
+ val scaled = if (scaledRaw.config == Bitmap.Config.ARGB_8888) {
185
+ scaledRaw
186
+ } else {
187
+ scaledRaw.copy(Bitmap.Config.ARGB_8888, false)
188
+ }
189
+
190
+ try {
191
+ val pixels = IntArray(INPUT_SIZE * INPUT_SIZE)
192
+ scaled.getPixels(pixels, 0, INPUT_SIZE, 0, 0, INPUT_SIZE, INPUT_SIZE)
193
+
194
+ val buffer = FloatBuffer.allocate(3 * INPUT_SIZE * INPUT_SIZE)
195
+ for (channelIndex in 0..2) {
196
+ for (pixel in pixels) {
197
+ val channel = when (channelIndex) {
198
+ 0 -> (pixel shr 16) and 0xFF
199
+ 1 -> (pixel shr 8) and 0xFF
200
+ else -> pixel and 0xFF
201
+ }
202
+ buffer.put((channel.toFloat() - MEAN) / STD)
203
+ }
204
+ }
205
+ buffer.rewind()
206
+ return OnnxTensor.createTensor(
207
+ env,
208
+ buffer,
209
+ longArrayOf(1L, 3L, INPUT_SIZE.toLong(), INPUT_SIZE.toLong())
210
+ )
211
+ } finally {
212
+ if (scaled !== bitmap && !scaled.isRecycled) scaled.recycle()
213
+ if (scaledRaw !== bitmap && scaledRaw !== scaled && !scaledRaw.isRecycled) {
214
+ scaledRaw.recycle()
215
+ }
216
+ }
217
+ }
218
+
219
+ private fun extractEmbedding(result: OrtSession.Result): FloatArray? {
220
+ val outputName = session.outputNames.first()
221
+ val tensor = result.get(outputName).orElse(null) as? OnnxTensor ?: return null
222
+ return when (val value = tensor.value) {
223
+ is Array<*> -> @Suppress("UNCHECKED_CAST")
224
+ (value as? Array<FloatArray>)?.firstOrNull()
225
+ is FloatArray -> value
226
+ else -> null
227
+ }
228
+ }
229
+
230
+ private fun l2Normalize(embedding: FloatArray): FloatArray? {
231
+ val squaredNorm = embedding.fold(0.0) { sum, value ->
232
+ sum + value.toDouble() * value
233
+ }
234
+ val norm = sqrt(squaredNorm).toFloat()
235
+ if (!norm.isFinite() || norm < 1e-6f) return null
236
+ return FloatArray(embedding.size) { embedding[it] / norm }
237
+ }
238
+
239
+ override fun close() {
240
+ session.close()
241
+ }
242
+ }