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