@masumdev/rn-camera-ai-tflite 0.0.0-stage → 0.2.0

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 (121) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +405 -2
  3. package/lib/commonjs/detector/TFLiteCatAnalyzer.js +609 -0
  4. package/lib/commonjs/detector/TFLiteCatAnalyzer.js.map +1 -0
  5. package/lib/commonjs/detector/TFLiteFaceRecognizer.js +690 -0
  6. package/lib/commonjs/detector/TFLiteFaceRecognizer.js.map +1 -0
  7. package/lib/commonjs/detector/TFLiteObjectDetector.js +392 -0
  8. package/lib/commonjs/detector/TFLiteObjectDetector.js.map +1 -0
  9. package/lib/commonjs/detector/index.js +50 -0
  10. package/lib/commonjs/detector/index.js.map +1 -0
  11. package/lib/commonjs/detector/modelLoader.js +139 -0
  12. package/lib/commonjs/detector/modelLoader.js.map +1 -0
  13. package/lib/commonjs/detector/workletFrameHelper.js +233 -0
  14. package/lib/commonjs/detector/workletFrameHelper.js.map +1 -0
  15. package/lib/commonjs/index.js +39 -0
  16. package/lib/commonjs/index.js.map +1 -0
  17. package/lib/commonjs/package.json +1 -0
  18. package/lib/commonjs/parser/blazeFaceParser.js +771 -0
  19. package/lib/commonjs/parser/blazeFaceParser.js.map +1 -0
  20. package/lib/commonjs/parser/catParser.js +752 -0
  21. package/lib/commonjs/parser/catParser.js.map +1 -0
  22. package/lib/commonjs/parser/index.js +39 -0
  23. package/lib/commonjs/parser/index.js.map +1 -0
  24. package/lib/commonjs/parser/outputParser.js +196 -0
  25. package/lib/commonjs/parser/outputParser.js.map +1 -0
  26. package/lib/commonjs/types/cat.js +6 -0
  27. package/lib/commonjs/types/cat.js.map +1 -0
  28. package/lib/commonjs/types/index.js +28 -0
  29. package/lib/commonjs/types/index.js.map +1 -0
  30. package/lib/commonjs/types/resize-plugin.d.ts +20 -0
  31. package/lib/commonjs/types/tflite.js +6 -0
  32. package/lib/commonjs/types/tflite.js.map +1 -0
  33. package/lib/module/detector/TFLiteCatAnalyzer.js +605 -0
  34. package/lib/module/detector/TFLiteCatAnalyzer.js.map +1 -0
  35. package/lib/module/detector/TFLiteFaceRecognizer.js +684 -0
  36. package/lib/module/detector/TFLiteFaceRecognizer.js.map +1 -0
  37. package/lib/module/detector/TFLiteObjectDetector.js +386 -0
  38. package/lib/module/detector/TFLiteObjectDetector.js.map +1 -0
  39. package/lib/module/detector/index.js +7 -0
  40. package/lib/module/detector/index.js.map +1 -0
  41. package/lib/module/detector/modelLoader.js +133 -0
  42. package/lib/module/detector/modelLoader.js.map +1 -0
  43. package/lib/module/detector/workletFrameHelper.js +226 -0
  44. package/lib/module/detector/workletFrameHelper.js.map +1 -0
  45. package/lib/module/index.js +6 -0
  46. package/lib/module/index.js.map +1 -0
  47. package/lib/module/package.json +1 -0
  48. package/lib/module/parser/blazeFaceParser.js +756 -0
  49. package/lib/module/parser/blazeFaceParser.js.map +1 -0
  50. package/lib/module/parser/catParser.js +739 -0
  51. package/lib/module/parser/catParser.js.map +1 -0
  52. package/lib/module/parser/index.js +6 -0
  53. package/lib/module/parser/index.js.map +1 -0
  54. package/lib/module/parser/outputParser.js +192 -0
  55. package/lib/module/parser/outputParser.js.map +1 -0
  56. package/lib/module/types/cat.js +4 -0
  57. package/lib/module/types/cat.js.map +1 -0
  58. package/lib/module/types/index.js +5 -0
  59. package/lib/module/types/index.js.map +1 -0
  60. package/lib/module/types/resize-plugin.d.ts +20 -0
  61. package/lib/module/types/tflite.js +4 -0
  62. package/lib/module/types/tflite.js.map +1 -0
  63. package/lib/typescript/commonjs/detector/TFLiteCatAnalyzer.d.ts +6 -0
  64. package/lib/typescript/commonjs/detector/TFLiteCatAnalyzer.d.ts.map +1 -0
  65. package/lib/typescript/commonjs/detector/TFLiteFaceRecognizer.d.ts +59 -0
  66. package/lib/typescript/commonjs/detector/TFLiteFaceRecognizer.d.ts.map +1 -0
  67. package/lib/typescript/commonjs/detector/TFLiteObjectDetector.d.ts +41 -0
  68. package/lib/typescript/commonjs/detector/TFLiteObjectDetector.d.ts.map +1 -0
  69. package/lib/typescript/commonjs/detector/index.d.ts +5 -0
  70. package/lib/typescript/commonjs/detector/index.d.ts.map +1 -0
  71. package/lib/typescript/commonjs/detector/modelLoader.d.ts +23 -0
  72. package/lib/typescript/commonjs/detector/modelLoader.d.ts.map +1 -0
  73. package/lib/typescript/commonjs/detector/workletFrameHelper.d.ts +40 -0
  74. package/lib/typescript/commonjs/detector/workletFrameHelper.d.ts.map +1 -0
  75. package/lib/typescript/commonjs/index.d.ts +4 -0
  76. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  77. package/lib/typescript/commonjs/package.json +1 -0
  78. package/lib/typescript/commonjs/parser/blazeFaceParser.d.ts +68 -0
  79. package/lib/typescript/commonjs/parser/blazeFaceParser.d.ts.map +1 -0
  80. package/lib/typescript/commonjs/parser/catParser.d.ts +61 -0
  81. package/lib/typescript/commonjs/parser/catParser.d.ts.map +1 -0
  82. package/lib/typescript/commonjs/parser/index.d.ts +4 -0
  83. package/lib/typescript/commonjs/parser/index.d.ts.map +1 -0
  84. package/lib/typescript/commonjs/parser/outputParser.d.ts +17 -0
  85. package/lib/typescript/commonjs/parser/outputParser.d.ts.map +1 -0
  86. package/lib/typescript/commonjs/types/cat.d.ts +109 -0
  87. package/lib/typescript/commonjs/types/cat.d.ts.map +1 -0
  88. package/lib/typescript/commonjs/types/index.d.ts +3 -0
  89. package/lib/typescript/commonjs/types/index.d.ts.map +1 -0
  90. package/lib/typescript/commonjs/types/tflite.d.ts +233 -0
  91. package/lib/typescript/commonjs/types/tflite.d.ts.map +1 -0
  92. package/lib/typescript/module/detector/TFLiteCatAnalyzer.d.ts +6 -0
  93. package/lib/typescript/module/detector/TFLiteCatAnalyzer.d.ts.map +1 -0
  94. package/lib/typescript/module/detector/TFLiteFaceRecognizer.d.ts +59 -0
  95. package/lib/typescript/module/detector/TFLiteFaceRecognizer.d.ts.map +1 -0
  96. package/lib/typescript/module/detector/TFLiteObjectDetector.d.ts +41 -0
  97. package/lib/typescript/module/detector/TFLiteObjectDetector.d.ts.map +1 -0
  98. package/lib/typescript/module/detector/index.d.ts +5 -0
  99. package/lib/typescript/module/detector/index.d.ts.map +1 -0
  100. package/lib/typescript/module/detector/modelLoader.d.ts +23 -0
  101. package/lib/typescript/module/detector/modelLoader.d.ts.map +1 -0
  102. package/lib/typescript/module/detector/workletFrameHelper.d.ts +40 -0
  103. package/lib/typescript/module/detector/workletFrameHelper.d.ts.map +1 -0
  104. package/lib/typescript/module/index.d.ts +4 -0
  105. package/lib/typescript/module/index.d.ts.map +1 -0
  106. package/lib/typescript/module/package.json +1 -0
  107. package/lib/typescript/module/parser/blazeFaceParser.d.ts +68 -0
  108. package/lib/typescript/module/parser/blazeFaceParser.d.ts.map +1 -0
  109. package/lib/typescript/module/parser/catParser.d.ts +61 -0
  110. package/lib/typescript/module/parser/catParser.d.ts.map +1 -0
  111. package/lib/typescript/module/parser/index.d.ts +4 -0
  112. package/lib/typescript/module/parser/index.d.ts.map +1 -0
  113. package/lib/typescript/module/parser/outputParser.d.ts +17 -0
  114. package/lib/typescript/module/parser/outputParser.d.ts.map +1 -0
  115. package/lib/typescript/module/types/cat.d.ts +109 -0
  116. package/lib/typescript/module/types/cat.d.ts.map +1 -0
  117. package/lib/typescript/module/types/index.d.ts +3 -0
  118. package/lib/typescript/module/types/index.d.ts.map +1 -0
  119. package/lib/typescript/module/types/tflite.d.ts +233 -0
  120. package/lib/typescript/module/types/tflite.d.ts.map +1 -0
  121. package/package.json +116 -4
@@ -0,0 +1,690 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.TFLiteFaceRecognizerImpl = void 0;
7
+ exports.createTFLiteFaceRecognizer = createTFLiteFaceRecognizer;
8
+ var _rnCameraAi = require("@masumdev/rn-camera-ai");
9
+ var _blazeFaceParser = require("../parser/blazeFaceParser.js");
10
+ var _modelLoader = require("./modelLoader.js");
11
+ let cachedResizer = undefined;
12
+ let cachedFrameConverter = undefined;
13
+ function tryGetResizePlugin() {
14
+ const current = cachedResizer;
15
+ if (current !== undefined) {
16
+ return current;
17
+ }
18
+ try {
19
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
20
+ const plugin = require('vision-camera-resize-plugin');
21
+ if (typeof plugin?.resize === 'function') {
22
+ cachedResizer = plugin;
23
+ return plugin;
24
+ }
25
+ } catch {
26
+ // Not installed
27
+ }
28
+ cachedResizer = null;
29
+ return null;
30
+ }
31
+ function tryGetFrameConverter() {
32
+ const current = cachedFrameConverter;
33
+ if (current !== undefined) {
34
+ return current;
35
+ }
36
+ try {
37
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
38
+ const visionCamera = require('react-native-vision-camera');
39
+ if (typeof visionCamera?.HybridFrameConverter?.convertFrameToImage === 'function') {
40
+ cachedFrameConverter = visionCamera.HybridFrameConverter;
41
+ return cachedFrameConverter;
42
+ }
43
+ } catch {
44
+ // Not loaded
45
+ }
46
+ cachedFrameConverter = null;
47
+ return null;
48
+ }
49
+ function createSafeSynchronizable(initial, fixedType = false) {
50
+ try {
51
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
52
+ const worklets = require('react-native-worklets');
53
+ if (typeof worklets?.createSynchronizable === 'function') {
54
+ return fixedType ? worklets.createSynchronizable(initial, {
55
+ fixedType: true
56
+ }) : worklets.createSynchronizable(initial);
57
+ }
58
+ } catch {
59
+ // Fallback for test environments
60
+ }
61
+ let value = initial;
62
+ return {
63
+ getBlocking: () => value,
64
+ setBlocking: nextValue => {
65
+ value = nextValue;
66
+ }
67
+ };
68
+ }
69
+ function toArrayBuffer(view) {
70
+ 'worklet';
71
+
72
+ const underlying = view.buffer;
73
+ if (view.byteOffset === 0 && view.byteLength === underlying.byteLength) {
74
+ return underlying;
75
+ }
76
+ return underlying.slice(view.byteOffset, view.byteOffset + view.byteLength);
77
+ }
78
+ function convertRawPixelDataToRgb(buffer, pixelFormat, width, height) {
79
+ 'worklet';
80
+
81
+ const src = new Uint8Array(buffer);
82
+ const expectedPixels = Math.max(0, Math.floor(width) * Math.floor(height));
83
+ if (pixelFormat === 'RGB') {
84
+ const expectedBytes = expectedPixels * 3;
85
+ if (src.byteLength === expectedBytes) {
86
+ return buffer;
87
+ }
88
+ const copyLen = Math.min(src.byteLength, expectedBytes);
89
+ const out = new Uint8Array(expectedBytes);
90
+ out.set(src.subarray(0, copyLen));
91
+ return out.buffer;
92
+ }
93
+ const out = new Uint8Array(expectedPixels * 3);
94
+ const count = Math.min(expectedPixels, Math.floor(src.byteLength / 4));
95
+ if (pixelFormat === 'BGRA' || pixelFormat === 'BGRX') {
96
+ for (let i = 0; i < count; i++) {
97
+ const s = i * 4;
98
+ const d = i * 3;
99
+ out[d] = src[s + 2];
100
+ out[d + 1] = src[s + 1];
101
+ out[d + 2] = src[s];
102
+ }
103
+ } else {
104
+ for (let i = 0; i < count; i++) {
105
+ const s = i * 4;
106
+ const d = i * 3;
107
+ out[d] = src[s];
108
+ out[d + 1] = src[s + 1];
109
+ out[d + 2] = src[s + 2];
110
+ }
111
+ }
112
+ return out.buffer;
113
+ }
114
+ function convertRgbUint8ToNormalizedFloat32Buffer(rgbBuffer) {
115
+ 'worklet';
116
+
117
+ const bytes = new Uint8Array(rgbBuffer);
118
+ const floats = new Float32Array(bytes.byteLength);
119
+ for (let i = 0; i < bytes.byteLength; i++) {
120
+ floats[i] = (bytes[i] - 127.5) / 127.5;
121
+ }
122
+ return floats.buffer;
123
+ }
124
+ function extractAntiSpoofScoreFromOutputs(rawOutputs) {
125
+ 'worklet';
126
+
127
+ if (!rawOutputs || !Array.isArray(rawOutputs) || rawOutputs.length === 0) {
128
+ return undefined;
129
+ }
130
+ const first = rawOutputs[0];
131
+ let values = null;
132
+ if (first instanceof Float32Array) {
133
+ values = first;
134
+ } else if (first instanceof ArrayBuffer) {
135
+ const usable = first.byteLength - first.byteLength % 4;
136
+ values = usable > 0 ? new Float32Array(first, 0, usable / 4) : null;
137
+ } else if (ArrayBuffer.isView(first)) {
138
+ const view = first;
139
+ const usable = view.byteLength - view.byteLength % 4;
140
+ values = usable > 0 ? new Float32Array(view.buffer, view.byteOffset, usable / 4) : null;
141
+ } else if (Array.isArray(first)) {
142
+ values = first;
143
+ }
144
+ if (!values || values.length === 0) {
145
+ return undefined;
146
+ }
147
+ if (values.length === 1) {
148
+ const v = values[0];
149
+ return Number.isFinite(v) ? Math.max(0, Math.min(1, v)) : undefined;
150
+ }
151
+ // Standard 2-class or 3-class [spoof, real, ...] logits or probabilities
152
+ const spoofVal = Number.isFinite(values[0]) ? values[0] : 0;
153
+ const realVal = Number.isFinite(values[1]) ? values[1] : 0;
154
+ if (spoofVal >= 0 && realVal >= 0 && Math.abs(spoofVal + realVal - 1) < 0.05) {
155
+ return Math.max(0, Math.min(1, realVal));
156
+ }
157
+ const maxLogit = Math.max(spoofVal, realVal);
158
+ const expSpoof = Math.exp(spoofVal - maxLogit);
159
+ const expReal = Math.exp(realVal - maxLogit);
160
+ return expReal / Math.max(1e-6, expSpoof + expReal);
161
+ }
162
+ function extractEmbeddingFromOutputs(rawEmbeddingOutputs) {
163
+ 'worklet';
164
+
165
+ if (!rawEmbeddingOutputs || !Array.isArray(rawEmbeddingOutputs) || rawEmbeddingOutputs.length === 0) {
166
+ return [];
167
+ }
168
+ const first = rawEmbeddingOutputs[0];
169
+ if (first instanceof Float32Array) {
170
+ return (0, _blazeFaceParser.l2NormalizeEmbedding)(first);
171
+ }
172
+ if (first instanceof ArrayBuffer) {
173
+ const usable = first.byteLength - first.byteLength % 4;
174
+ return usable > 0 ? (0, _blazeFaceParser.l2NormalizeEmbedding)(new Float32Array(first, 0, usable / 4)) : [];
175
+ }
176
+ if (ArrayBuffer.isView(first)) {
177
+ const view = first;
178
+ const usable = view.byteLength - view.byteLength % 4;
179
+ return usable > 0 ? (0, _blazeFaceParser.l2NormalizeEmbedding)(new Float32Array(view.buffer, view.byteOffset, usable / 4)) : [];
180
+ }
181
+ if (Array.isArray(first)) {
182
+ return (0, _blazeFaceParser.l2NormalizeEmbedding)(first);
183
+ }
184
+ return [];
185
+ }
186
+ function createTFLiteWorkletProcessFaceFrame(params) {
187
+ const {
188
+ disposedSync,
189
+ readySync,
190
+ modelSync,
191
+ embeddingModelSync,
192
+ faceMeshModelSync,
193
+ antiSpoofModelSync,
194
+ confidenceSync,
195
+ similaritySync,
196
+ livenessThresholdSync,
197
+ enableLiveness,
198
+ iouSync,
199
+ maxResultsSync,
200
+ lastFrameTimeSync,
201
+ wasThrottledSync,
202
+ enrolledFacesSync,
203
+ lastEmbeddingSync,
204
+ lastLandmarksSync,
205
+ minFrameIntervalMs,
206
+ inputWidth,
207
+ inputHeight,
208
+ anchors,
209
+ frameConverter,
210
+ fallbackResizePlugin
211
+ } = params;
212
+ return frame => {
213
+ 'worklet';
214
+
215
+ if (disposedSync.getBlocking()) {
216
+ throw new Error('Cannot process frame: face recognizer is disposed');
217
+ }
218
+ const activeModel = modelSync.getBlocking();
219
+ if (!readySync.getBlocking() || !activeModel) {
220
+ wasThrottledSync.setBlocking(false);
221
+ return [];
222
+ }
223
+ if (minFrameIntervalMs > 0) {
224
+ const now = Date.now();
225
+ const prevTime = lastFrameTimeSync.getBlocking();
226
+ if (prevTime > 0 && now - prevTime < minFrameIntervalMs) {
227
+ wasThrottledSync.setBlocking(true);
228
+ return [];
229
+ }
230
+ lastFrameTimeSync.setBlocking(now);
231
+ }
232
+ wasThrottledSync.setBlocking(false);
233
+ let rgbBuffer = null;
234
+ let needs180Correction = false;
235
+ let sourceAspectRatio = 1.0;
236
+ const frameRecord = typeof frame === 'object' && frame !== null ? frame : null;
237
+ if (frameRecord && typeof frameRecord.width === 'number' && typeof frameRecord.height === 'number' && frameRecord.width > 0 && frameRecord.height > 0) {
238
+ const longSide = Math.max(frameRecord.width, frameRecord.height);
239
+ const shortSide = Math.min(frameRecord.width, frameRecord.height);
240
+ sourceAspectRatio = longSide / shortSide;
241
+ }
242
+ const isVc5Frame = frameRecord !== null && typeof frameRecord.getPixelBuffer === 'function';
243
+ if (!isVc5Frame && fallbackResizePlugin && frame) {
244
+ try {
245
+ const resized = fallbackResizePlugin.resize(frame, {
246
+ scale: {
247
+ width: inputWidth,
248
+ height: inputHeight
249
+ },
250
+ pixelFormat: 'rgb',
251
+ dataType: 'uint8'
252
+ });
253
+ if (resized?.buffer instanceof ArrayBuffer) {
254
+ rgbBuffer = resized.buffer;
255
+ } else if (resized?.buffer && ArrayBuffer.isView(resized.buffer)) {
256
+ rgbBuffer = toArrayBuffer(resized.buffer);
257
+ } else if (typeof resized?.toArrayBuffer === 'function') {
258
+ rgbBuffer = resized.toArrayBuffer();
259
+ }
260
+ } catch {
261
+ // Fallback below
262
+ }
263
+ }
264
+ if (!rgbBuffer && isVc5Frame && frameConverter) {
265
+ if (frameRecord?.isValid === false) {
266
+ return [];
267
+ }
268
+ if (frameRecord?.orientation === 'left' || frameRecord?.orientation === 'right') {
269
+ needs180Correction = true;
270
+ }
271
+ let sourceImage = null;
272
+ let resizedImage = null;
273
+ try {
274
+ sourceImage = frameConverter.convertFrameToImage(frame);
275
+ if (sourceImage.width > 0 && sourceImage.height > 0) {
276
+ const longSide = Math.max(sourceImage.width, sourceImage.height);
277
+ const shortSide = Math.min(sourceImage.width, sourceImage.height);
278
+ sourceAspectRatio = longSide / shortSide;
279
+ }
280
+ resizedImage = sourceImage.width !== inputWidth || sourceImage.height !== inputHeight ? sourceImage.resize(inputWidth, inputHeight) : sourceImage;
281
+ const rawPixelData = resizedImage.toRawPixelData(false);
282
+ rgbBuffer = convertRawPixelDataToRgb(rawPixelData.buffer, rawPixelData.pixelFormat, rawPixelData.width > 0 ? rawPixelData.width : inputWidth, rawPixelData.height > 0 ? rawPixelData.height : inputHeight);
283
+ } finally {
284
+ if (resizedImage && resizedImage !== sourceImage && typeof resizedImage.dispose === 'function') {
285
+ resizedImage.dispose();
286
+ }
287
+ if (sourceImage && typeof sourceImage.dispose === 'function') {
288
+ sourceImage.dispose();
289
+ }
290
+ }
291
+ }
292
+ if (!rgbBuffer && frame) {
293
+ if (frame instanceof ArrayBuffer) {
294
+ rgbBuffer = frame;
295
+ } else if (ArrayBuffer.isView(frame)) {
296
+ rgbBuffer = toArrayBuffer(frame);
297
+ } else if (frameRecord) {
298
+ if (frameRecord.buffer instanceof ArrayBuffer) {
299
+ rgbBuffer = frameRecord.buffer;
300
+ } else if (frameRecord.buffer && ArrayBuffer.isView(frameRecord.buffer)) {
301
+ rgbBuffer = toArrayBuffer(frameRecord.buffer);
302
+ } else if (typeof frameRecord.toArrayBuffer === 'function') {
303
+ rgbBuffer = frameRecord.toArrayBuffer();
304
+ }
305
+ }
306
+ }
307
+ if (!rgbBuffer) {
308
+ rgbBuffer = new ArrayBuffer(inputWidth * inputHeight * 3);
309
+ }
310
+
311
+ // MediaPipe BlazeFace takes Float32 [-1, 1] input; fall back to raw buffer if model is quantized
312
+ let rawOutputs;
313
+ const expectedUint8Bytes = inputWidth * inputHeight * 3;
314
+ if (rgbBuffer.byteLength === expectedUint8Bytes) {
315
+ const floatBuffer = convertRgbUint8ToNormalizedFloat32Buffer(rgbBuffer);
316
+ try {
317
+ rawOutputs = activeModel.runSync([floatBuffer]);
318
+ } catch {
319
+ rawOutputs = activeModel.runSync([rgbBuffer]);
320
+ }
321
+ } else {
322
+ rawOutputs = activeModel.runSync([rgbBuffer]);
323
+ }
324
+ if (!rawOutputs || !Array.isArray(rawOutputs) || rawOutputs.length < 2) {
325
+ return [];
326
+ }
327
+ const faces = (0, _blazeFaceParser.decodeBlazeFaceOutputs)(rawOutputs, anchors, {
328
+ confidenceThreshold: confidenceSync.getBlocking(),
329
+ iouThreshold: iouSync.getBlocking(),
330
+ maxResults: maxResultsSync.getBlocking(),
331
+ inputWidth,
332
+ inputHeight,
333
+ frameAspectRatio: sourceAspectRatio
334
+ });
335
+ if (faces.length === 0) {
336
+ return [];
337
+ }
338
+ const activeFaceMeshModel = faceMeshModelSync.getBlocking();
339
+ if (activeFaceMeshModel) {
340
+ for (let i = 0; i < faces.length; i++) {
341
+ try {
342
+ const roiBox = (0, _blazeFaceParser.expandFaceRoiBox)(faces[i].boundingBox, 1.28);
343
+ const meshInputBuffer = (0, _blazeFaceParser.cropAndResizeFaceToNormalized01Float32Buffer)(rgbBuffer, inputWidth, inputHeight, roiBox, 192, 192);
344
+ const rawMeshOutputs = activeFaceMeshModel.runSync([meshInputBuffer]);
345
+ const meshDecoded = (0, _blazeFaceParser.decodeFaceMeshOutputs)(rawMeshOutputs, roiBox, 192);
346
+ if (meshDecoded && meshDecoded.landmarks.length === 468) {
347
+ faces[i] = {
348
+ ...faces[i],
349
+ boundingBox: meshDecoded.tightBox,
350
+ landmarks: meshDecoded.landmarks
351
+ };
352
+ }
353
+ } catch {
354
+ // Keep 6-point BlazeFace landmarks if mesh inference fails
355
+ }
356
+ }
357
+ }
358
+ if (needs180Correction) {
359
+ for (let i = 0; i < faces.length; i++) {
360
+ const box = faces[i].boundingBox;
361
+ const correctedLandmarks = faces[i].landmarks?.map(lm => ({
362
+ ...lm,
363
+ x: Math.max(0, Math.min(1, 1 - lm.x)),
364
+ y: Math.max(0, Math.min(1, 1 - lm.y))
365
+ }));
366
+ faces[i] = {
367
+ ...faces[i],
368
+ boundingBox: {
369
+ x: Math.max(0, Math.min(1, 1 - box.x - box.width)),
370
+ y: Math.max(0, Math.min(1, 1 - box.y - box.height)),
371
+ width: box.width,
372
+ height: box.height
373
+ },
374
+ landmarks: correctedLandmarks
375
+ };
376
+ }
377
+ }
378
+ const enrolledProfiles = enrolledFacesSync.getBlocking();
379
+ const similarityThreshold = similaritySync.getBlocking();
380
+ const livenessThreshold = livenessThresholdSync.getBlocking();
381
+ const activeEmbeddingModel = embeddingModelSync.getBlocking();
382
+ const activeAntiSpoofModel = antiSpoofModelSync.getBlocking();
383
+ for (let i = 0; i < faces.length; i++) {
384
+ let face = faces[i];
385
+ let descriptor = [];
386
+ if (enableLiveness) {
387
+ let externalSpoofScore = undefined;
388
+ if (activeAntiSpoofModel) {
389
+ try {
390
+ const spoofRoi = (0, _blazeFaceParser.expandFaceRoiBox)(face.boundingBox, 1.5);
391
+ const spoofInput = (0, _blazeFaceParser.cropAndResizeFaceToNormalized01Float32Buffer)(rgbBuffer, inputWidth, inputHeight, spoofRoi, 80, 80);
392
+ const spoofOutputs = activeAntiSpoofModel.runSync([spoofInput]);
393
+ externalSpoofScore = extractAntiSpoofScoreFromOutputs(spoofOutputs);
394
+ } catch {
395
+ externalSpoofScore = undefined;
396
+ }
397
+ }
398
+ const livenessMetrics = (0, _blazeFaceParser.computeFaceLivenessMetrics)(rgbBuffer, inputWidth, inputHeight, face.boundingBox, face.landmarks, livenessThreshold, externalSpoofScore);
399
+ face = {
400
+ ...face,
401
+ liveness: livenessMetrics
402
+ };
403
+ faces[i] = face;
404
+ }
405
+ if (activeEmbeddingModel) {
406
+ try {
407
+ const faceCropFloatBuffer = (0, _blazeFaceParser.cropAndResizeFaceToFloat32Buffer)(rgbBuffer, inputWidth, inputHeight, face.boundingBox, 112, 112);
408
+ const embOutputs = activeEmbeddingModel.runSync([faceCropFloatBuffer]);
409
+ descriptor = extractEmbeddingFromOutputs(embOutputs);
410
+ } catch {
411
+ descriptor = [];
412
+ }
413
+ }
414
+ if (descriptor.length === 0) {
415
+ descriptor = (0, _blazeFaceParser.extractFaceDescriptorFromRgbAndLandmarks)(rgbBuffer, inputWidth, inputHeight, face.boundingBox, face.landmarks);
416
+ }
417
+
418
+ // Cache primary (highest-confidence) face embedding for 1-tap enrollment
419
+ if (i === 0 && descriptor.length > 0) {
420
+ lastEmbeddingSync.setBlocking(descriptor);
421
+ lastLandmarksSync.setBlocking(face.landmarks ?? null);
422
+ }
423
+ if (enrolledProfiles.length > 0 && descriptor.length > 0) {
424
+ let bestProfile = null;
425
+ let bestSimilarity = -1;
426
+ for (let p = 0; p < enrolledProfiles.length; p++) {
427
+ const sim = (0, _blazeFaceParser.cosineSimilarity)(descriptor, enrolledProfiles[p].embedding);
428
+ if (sim > bestSimilarity) {
429
+ bestSimilarity = sim;
430
+ bestProfile = enrolledProfiles[p];
431
+ }
432
+ }
433
+ if (bestProfile && bestSimilarity >= similarityThreshold) {
434
+ faces[i] = {
435
+ ...face,
436
+ label: bestProfile.name,
437
+ confidence: bestSimilarity,
438
+ identity: {
439
+ id: bestProfile.id,
440
+ name: bestProfile.name,
441
+ similarity: bestSimilarity,
442
+ isRecognized: true
443
+ }
444
+ };
445
+ } else {
446
+ faces[i] = {
447
+ ...face,
448
+ label: 'Unknown Face',
449
+ identity: {
450
+ id: 'unknown',
451
+ name: 'Unknown Face',
452
+ similarity: Math.max(0, bestSimilarity),
453
+ isRecognized: false
454
+ }
455
+ };
456
+ }
457
+ }
458
+ }
459
+ return faces;
460
+ };
461
+ }
462
+
463
+ /**
464
+ * Concrete implementation of the TFLite Face Detection & Recognition CameraProcessor.
465
+ */
466
+ class TFLiteFaceRecognizerImpl {
467
+ name = 'TFLiteFaceRecognizer';
468
+ constructor(config, model, activeDelegate, embeddingModel = null, faceMeshModel = null, antiSpoofModel = null) {
469
+ this.id = `tflite-face-recognizer-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
470
+ this._config = config;
471
+ this._activeDelegate = activeDelegate;
472
+ this._status = 'ready';
473
+ this._confidenceThreshold = typeof config.confidenceThreshold === 'number' && Number.isFinite(config.confidenceThreshold) ? Math.max(0.05, Math.min(0.99, config.confidenceThreshold)) : 0.55;
474
+ this._similarityThreshold = typeof config.similarityThreshold === 'number' && Number.isFinite(config.similarityThreshold) ? Math.max(0.1, Math.min(0.99, config.similarityThreshold)) : 0.75;
475
+ this._livenessThreshold = typeof config.livenessThreshold === 'number' && Number.isFinite(config.livenessThreshold) ? Math.max(0.1, Math.min(0.99, config.livenessThreshold)) : 0.62;
476
+ this._iouThreshold = typeof config.iouThreshold === 'number' && Number.isFinite(config.iouThreshold) ? Math.max(0.05, Math.min(0.95, config.iouThreshold)) : 0.3;
477
+ this._maxResults = typeof config.maxResults === 'number' && Number.isFinite(config.maxResults) && config.maxResults >= 0 ? Math.floor(config.maxResults) : 5;
478
+ const fps = config.targetFps ?? 24;
479
+ const minFrameIntervalMs = fps > 0 ? 1000 / fps : 0;
480
+ const initialFaces = Array.isArray(config.initialFaces) ? config.initialFaces.slice() : [];
481
+ this._disposedSync = createSafeSynchronizable(false, true);
482
+ this._readySync = createSafeSynchronizable(true, true);
483
+ this._modelSync = createSafeSynchronizable(model, false);
484
+ this._embeddingModelSync = createSafeSynchronizable(embeddingModel, false);
485
+ this._faceMeshModelSync = createSafeSynchronizable(faceMeshModel, false);
486
+ this._antiSpoofModelSync = createSafeSynchronizable(antiSpoofModel, false);
487
+ this._confidenceSync = createSafeSynchronizable(this._confidenceThreshold, true);
488
+ this._similaritySync = createSafeSynchronizable(this._similarityThreshold, true);
489
+ this._livenessThresholdSync = createSafeSynchronizable(this._livenessThreshold, true);
490
+ this._iouSync = createSafeSynchronizable(this._iouThreshold, true);
491
+ this._maxResultsSync = createSafeSynchronizable(this._maxResults, true);
492
+ this._lastFrameTimeSync = createSafeSynchronizable(0, true);
493
+ this.wasThrottledSync = createSafeSynchronizable(false, true);
494
+ this._enrolledFacesSync = createSafeSynchronizable(initialFaces, false);
495
+ this._lastEmbeddingSync = createSafeSynchronizable(null, false);
496
+ this._lastLandmarksSync = createSafeSynchronizable(null, false);
497
+ const resolvedInputW = config.inputWidth ?? 192;
498
+ const resolvedInputH = config.inputHeight ?? 192;
499
+ const anchors = resolvedInputW === 192 ? (0, _blazeFaceParser.generateBlazeFaceFullRangeAnchors)() : (0, _blazeFaceParser.generateBlazeFaceAnchors)();
500
+ this.processFrameWorklet = createTFLiteWorkletProcessFaceFrame({
501
+ disposedSync: this._disposedSync,
502
+ readySync: this._readySync,
503
+ modelSync: this._modelSync,
504
+ embeddingModelSync: this._embeddingModelSync,
505
+ faceMeshModelSync: this._faceMeshModelSync,
506
+ antiSpoofModelSync: this._antiSpoofModelSync,
507
+ confidenceSync: this._confidenceSync,
508
+ similaritySync: this._similaritySync,
509
+ livenessThresholdSync: this._livenessThresholdSync,
510
+ enableLiveness: config.enableLiveness !== false,
511
+ iouSync: this._iouSync,
512
+ maxResultsSync: this._maxResultsSync,
513
+ lastFrameTimeSync: this._lastFrameTimeSync,
514
+ wasThrottledSync: this.wasThrottledSync,
515
+ enrolledFacesSync: this._enrolledFacesSync,
516
+ lastEmbeddingSync: this._lastEmbeddingSync,
517
+ lastLandmarksSync: this._lastLandmarksSync,
518
+ minFrameIntervalMs,
519
+ inputWidth: resolvedInputW,
520
+ inputHeight: resolvedInputH,
521
+ anchors,
522
+ frameConverter: tryGetFrameConverter(),
523
+ fallbackResizePlugin: tryGetResizePlugin()
524
+ });
525
+ }
526
+ get status() {
527
+ return this._status;
528
+ }
529
+ get activeDelegate() {
530
+ return this._activeDelegate;
531
+ }
532
+ get confidenceThreshold() {
533
+ return this._confidenceThreshold;
534
+ }
535
+ get similarityThreshold() {
536
+ return this._similarityThreshold;
537
+ }
538
+ get livenessThreshold() {
539
+ return this._livenessThreshold;
540
+ }
541
+ get targetFps() {
542
+ return this._config.targetFps ?? 24;
543
+ }
544
+ setConfidenceThreshold(threshold) {
545
+ if (Number.isFinite(threshold)) {
546
+ this._confidenceThreshold = Math.max(0.05, Math.min(0.99, threshold));
547
+ this._confidenceSync.setBlocking(this._confidenceThreshold);
548
+ }
549
+ }
550
+ setSimilarityThreshold(threshold) {
551
+ if (Number.isFinite(threshold)) {
552
+ this._similarityThreshold = Math.max(0.1, Math.min(0.99, threshold));
553
+ this._similaritySync.setBlocking(this._similarityThreshold);
554
+ }
555
+ }
556
+ setLivenessThreshold(threshold) {
557
+ if (Number.isFinite(threshold)) {
558
+ this._livenessThreshold = Math.max(0.1, Math.min(0.99, threshold));
559
+ this._livenessThresholdSync.setBlocking(this._livenessThreshold);
560
+ }
561
+ }
562
+ hasRecentFaceEmbedding() {
563
+ const emb = this._lastEmbeddingSync.getBlocking();
564
+ return Array.isArray(emb) && emb.length > 0;
565
+ }
566
+ getLastDetectedLandmarks() {
567
+ return this._lastLandmarksSync.getBlocking();
568
+ }
569
+ enrollFace(name, embedding) {
570
+ const trimmedName = name.trim() || 'Person';
571
+ const normalized = (0, _blazeFaceParser.l2NormalizeEmbedding)(embedding);
572
+ const profile = {
573
+ id: `face-profile-${Date.now()}-${Math.floor(Math.random() * 10000)}`,
574
+ name: trimmedName,
575
+ embedding: normalized,
576
+ createdAt: Date.now()
577
+ };
578
+ const existing = this._enrolledFacesSync.getBlocking();
579
+ const updated = [...existing, profile];
580
+ this._enrolledFacesSync.setBlocking(updated);
581
+ return profile;
582
+ }
583
+ enrollLastDetectedFace(name) {
584
+ const latestEmbedding = this._lastEmbeddingSync.getBlocking();
585
+ if (!latestEmbedding || latestEmbedding.length === 0) {
586
+ return null;
587
+ }
588
+ return this.enrollFace(name, latestEmbedding);
589
+ }
590
+ removeEnrolledFace(id) {
591
+ const existing = this._enrolledFacesSync.getBlocking();
592
+ const filtered = existing.filter(item => item.id !== id);
593
+ if (filtered.length === existing.length) {
594
+ return false;
595
+ }
596
+ this._enrolledFacesSync.setBlocking(filtered);
597
+ return true;
598
+ }
599
+ clearEnrolledFaces() {
600
+ this._enrolledFacesSync.setBlocking([]);
601
+ }
602
+ getEnrolledFaces() {
603
+ return this._enrolledFacesSync.getBlocking().slice();
604
+ }
605
+ processFrame(frame) {
606
+ try {
607
+ return this.processFrameWorklet(frame);
608
+ } catch (err) {
609
+ throw new _rnCameraAi.InferenceError(err instanceof Error ? err.message : 'Face inference execution failed', 'INFERENCE_ERROR', err);
610
+ }
611
+ }
612
+ async initialize() {
613
+ if (this._disposedSync.getBlocking()) {
614
+ const loaded = await (0, _modelLoader.loadModelWithFallback)(this._config.model, {
615
+ useGpu: this._config.useGpu,
616
+ platform: this._config.platform,
617
+ onDelegateFallback: this._config.onDelegateFallback,
618
+ loadModel: this._config.loadModel
619
+ });
620
+ this._modelSync.setBlocking(loaded.model);
621
+ this._activeDelegate = loaded.activeDelegate;
622
+ this._disposedSync.setBlocking(false);
623
+ }
624
+ this._status = 'ready';
625
+ this._readySync.setBlocking(true);
626
+ this._lastFrameTimeSync.setBlocking(0);
627
+ this.wasThrottledSync.setBlocking(false);
628
+ }
629
+ dispose() {
630
+ this._disposedSync.setBlocking(true);
631
+ this._readySync.setBlocking(false);
632
+ this._status = 'idle';
633
+ this._lastFrameTimeSync.setBlocking(0);
634
+ this.wasThrottledSync.setBlocking(false);
635
+ }
636
+ }
637
+
638
+ /**
639
+ * Creates and initializes a MediaPipe BlazeFace + Identity Recognition processor.
640
+ */
641
+ exports.TFLiteFaceRecognizerImpl = TFLiteFaceRecognizerImpl;
642
+ async function createTFLiteFaceRecognizer(config) {
643
+ const loaded = await (0, _modelLoader.loadModelWithFallback)(config?.model, {
644
+ useGpu: config?.useGpu,
645
+ platform: config?.platform,
646
+ onDelegateFallback: config?.onDelegateFallback,
647
+ loadModel: config?.loadModel
648
+ });
649
+ let loadedEmbeddingModel = null;
650
+ if (config?.embeddingModel !== undefined && config?.embeddingModel !== null) {
651
+ try {
652
+ const embLoaded = await (0, _modelLoader.loadModelWithFallback)(config.embeddingModel, {
653
+ useGpu: config?.useGpu,
654
+ platform: config?.platform,
655
+ loadModel: config?.loadModel
656
+ });
657
+ loadedEmbeddingModel = embLoaded.model;
658
+ } catch {
659
+ loadedEmbeddingModel = null;
660
+ }
661
+ }
662
+ let loadedFaceMeshModel = null;
663
+ if (config?.faceMeshModel !== undefined && config?.faceMeshModel !== null) {
664
+ try {
665
+ const meshLoaded = await (0, _modelLoader.loadModelWithFallback)(config.faceMeshModel, {
666
+ useGpu: config?.useGpu,
667
+ platform: config?.platform,
668
+ loadModel: config?.loadModel
669
+ });
670
+ loadedFaceMeshModel = meshLoaded.model;
671
+ } catch {
672
+ loadedFaceMeshModel = null;
673
+ }
674
+ }
675
+ let loadedAntiSpoofModel = null;
676
+ if (config?.antiSpoofModel !== undefined && config?.antiSpoofModel !== null) {
677
+ try {
678
+ const spoofLoaded = await (0, _modelLoader.loadModelWithFallback)(config.antiSpoofModel, {
679
+ useGpu: config?.useGpu,
680
+ platform: config?.platform,
681
+ loadModel: config?.loadModel
682
+ });
683
+ loadedAntiSpoofModel = spoofLoaded.model;
684
+ } catch {
685
+ loadedAntiSpoofModel = null;
686
+ }
687
+ }
688
+ return new TFLiteFaceRecognizerImpl(config, loaded.model, loaded.activeDelegate, loadedEmbeddingModel, loadedFaceMeshModel, loadedAntiSpoofModel);
689
+ }
690
+ //# sourceMappingURL=TFLiteFaceRecognizer.js.map