@masumdev/rn-camera-ai-tflite 0.1.0 → 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 (58) hide show
  1. package/README.md +32 -1
  2. package/lib/commonjs/detector/TFLiteCatAnalyzer.js +609 -0
  3. package/lib/commonjs/detector/TFLiteCatAnalyzer.js.map +1 -0
  4. package/lib/commonjs/detector/index.js +11 -0
  5. package/lib/commonjs/detector/index.js.map +1 -1
  6. package/lib/commonjs/detector/workletFrameHelper.js +233 -0
  7. package/lib/commonjs/detector/workletFrameHelper.js.map +1 -0
  8. package/lib/commonjs/parser/catParser.js +752 -0
  9. package/lib/commonjs/parser/catParser.js.map +1 -0
  10. package/lib/commonjs/parser/index.js +11 -0
  11. package/lib/commonjs/parser/index.js.map +1 -1
  12. package/lib/commonjs/types/cat.js +6 -0
  13. package/lib/commonjs/types/cat.js.map +1 -0
  14. package/lib/commonjs/types/index.js +11 -0
  15. package/lib/commonjs/types/index.js.map +1 -1
  16. package/lib/module/detector/TFLiteCatAnalyzer.js +605 -0
  17. package/lib/module/detector/TFLiteCatAnalyzer.js.map +1 -0
  18. package/lib/module/detector/index.js +1 -0
  19. package/lib/module/detector/index.js.map +1 -1
  20. package/lib/module/detector/workletFrameHelper.js +226 -0
  21. package/lib/module/detector/workletFrameHelper.js.map +1 -0
  22. package/lib/module/parser/catParser.js +739 -0
  23. package/lib/module/parser/catParser.js.map +1 -0
  24. package/lib/module/parser/index.js +1 -0
  25. package/lib/module/parser/index.js.map +1 -1
  26. package/lib/module/types/cat.js +4 -0
  27. package/lib/module/types/cat.js.map +1 -0
  28. package/lib/module/types/index.js +1 -0
  29. package/lib/module/types/index.js.map +1 -1
  30. package/lib/typescript/commonjs/detector/TFLiteCatAnalyzer.d.ts +6 -0
  31. package/lib/typescript/commonjs/detector/TFLiteCatAnalyzer.d.ts.map +1 -0
  32. package/lib/typescript/commonjs/detector/index.d.ts +1 -0
  33. package/lib/typescript/commonjs/detector/index.d.ts.map +1 -1
  34. package/lib/typescript/commonjs/detector/workletFrameHelper.d.ts +40 -0
  35. package/lib/typescript/commonjs/detector/workletFrameHelper.d.ts.map +1 -0
  36. package/lib/typescript/commonjs/parser/catParser.d.ts +61 -0
  37. package/lib/typescript/commonjs/parser/catParser.d.ts.map +1 -0
  38. package/lib/typescript/commonjs/parser/index.d.ts +1 -0
  39. package/lib/typescript/commonjs/parser/index.d.ts.map +1 -1
  40. package/lib/typescript/commonjs/types/cat.d.ts +109 -0
  41. package/lib/typescript/commonjs/types/cat.d.ts.map +1 -0
  42. package/lib/typescript/commonjs/types/index.d.ts +1 -0
  43. package/lib/typescript/commonjs/types/index.d.ts.map +1 -1
  44. package/lib/typescript/module/detector/TFLiteCatAnalyzer.d.ts +6 -0
  45. package/lib/typescript/module/detector/TFLiteCatAnalyzer.d.ts.map +1 -0
  46. package/lib/typescript/module/detector/index.d.ts +1 -0
  47. package/lib/typescript/module/detector/index.d.ts.map +1 -1
  48. package/lib/typescript/module/detector/workletFrameHelper.d.ts +40 -0
  49. package/lib/typescript/module/detector/workletFrameHelper.d.ts.map +1 -0
  50. package/lib/typescript/module/parser/catParser.d.ts +61 -0
  51. package/lib/typescript/module/parser/catParser.d.ts.map +1 -0
  52. package/lib/typescript/module/parser/index.d.ts +1 -0
  53. package/lib/typescript/module/parser/index.d.ts.map +1 -1
  54. package/lib/typescript/module/types/cat.d.ts +109 -0
  55. package/lib/typescript/module/types/cat.d.ts.map +1 -0
  56. package/lib/typescript/module/types/index.d.ts +1 -0
  57. package/lib/typescript/module/types/index.d.ts.map +1 -1
  58. package/package.json +5 -10
@@ -0,0 +1,752 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.analyzeCatCoatAndColors = analyzeCatCoatAndColors;
7
+ exports.computeCatFACSMetrics = computeCatFACSMetrics;
8
+ exports.cropRgbToUint8Buffer = cropRgbToUint8Buffer;
9
+ exports.decodeBreedProbabilities = decodeBreedProbabilities;
10
+ exports.decodeCatFaceLandmarks = decodeCatFaceLandmarks;
11
+ exports.decodeDeepLabCatMask = decodeDeepLabCatMask;
12
+ exports.deletterboxNormalizedBox = deletterboxNormalizedBox;
13
+ exports.extractCatIdentityDescriptor = extractCatIdentityDescriptor;
14
+ exports.fuseBreedPredictions = fuseBreedPredictions;
15
+ exports.letterboxRgbToFloat01Buffer = letterboxRgbToFloat01Buffer;
16
+ var _blazeFaceParser = require("./blazeFaceParser.js");
17
+ const CAT_RIGHT_EYE_SET = [3, 4, 5, 6, 7, 36, 37, 38];
18
+ const CAT_LEFT_EYE_SET = [1, 8, 9, 10, 11, 39, 40, 41];
19
+ const CAT_RIGHT_EAR_SET = [22, 23, 24, 25, 26];
20
+ const CAT_LEFT_EAR_SET = [27, 28, 29, 30, 31];
21
+ const CAT_MOUTH_CHIN_SET = [0, 2, 16, 17, 18, 19, 20, 21, 46, 47];
22
+ function extractNumericVector(tensor, isUint8 = false) {
23
+ 'worklet';
24
+
25
+ if (tensor === null || tensor === undefined) {
26
+ return null;
27
+ }
28
+ if (isUint8) {
29
+ if (tensor instanceof Uint8Array) {
30
+ return tensor;
31
+ }
32
+ if (tensor instanceof ArrayBuffer) {
33
+ return new Uint8Array(tensor);
34
+ }
35
+ if (ArrayBuffer.isView(tensor)) {
36
+ const view = tensor;
37
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
38
+ }
39
+ }
40
+ if (tensor instanceof Float32Array) {
41
+ return tensor;
42
+ }
43
+ if (tensor instanceof ArrayBuffer) {
44
+ const usable = tensor.byteLength - tensor.byteLength % 4;
45
+ return usable > 0 ? new Float32Array(tensor, 0, usable / 4) : [];
46
+ }
47
+ if (ArrayBuffer.isView(tensor)) {
48
+ const view = tensor;
49
+ if (view instanceof Uint8Array) {
50
+ return view;
51
+ }
52
+ const usable = view.byteLength - view.byteLength % 4;
53
+ return usable > 0 ? new Float32Array(view.buffer, view.byteOffset, usable / 4) : [];
54
+ }
55
+ if (Array.isArray(tensor)) {
56
+ if (tensor.length > 0 && Array.isArray(tensor[0])) {
57
+ return tensor[0];
58
+ }
59
+ return tensor;
60
+ }
61
+ return null;
62
+ }
63
+ function clamp01(val) {
64
+ 'worklet';
65
+
66
+ return val < 0 ? 0 : val > 1 ? 1 : val;
67
+ }
68
+ function normalizeBreedAlias(rawLabel) {
69
+ 'worklet';
70
+
71
+ const trimmed = rawLabel.trim();
72
+ const lower = trimmed.toLowerCase();
73
+ if (lower === 'sphynx - hairless' || lower === 'canadian hairless') {
74
+ return 'Sphynx';
75
+ }
76
+ if (lower === 'applehead siamese') {
77
+ return 'Siamese';
78
+ }
79
+ if (lower === 'tiger') {
80
+ return 'Tabby';
81
+ }
82
+ return trimmed;
83
+ }
84
+
85
+ /**
86
+ * Crops an RGB uint8 image buffer to a normalized ROI and scales into a uint8 [0, 255] tensor buffer.
87
+ */
88
+ function cropRgbToUint8Buffer(rgbBuffer, imgWidth, imgHeight, roiBox, targetWidth, targetHeight) {
89
+ 'worklet';
90
+
91
+ const bytes = new Uint8Array(rgbBuffer);
92
+ const out = new Uint8Array(targetWidth * targetHeight * 3);
93
+ const x0 = clamp01(roiBox.x);
94
+ const y0 = clamp01(roiBox.y);
95
+ const bw = Math.max(0.04, Math.min(1 - x0, roiBox.width));
96
+ const bh = Math.max(0.04, Math.min(1 - y0, roiBox.height));
97
+ let dstIdx = 0;
98
+ for (let ty = 0; ty < targetHeight; ty++) {
99
+ const ny = y0 + (ty + 0.5) / targetHeight * bh;
100
+ const sy = Math.max(0, Math.min(imgHeight - 1, Math.floor(ny * imgHeight)));
101
+ const rowBase = sy * imgWidth;
102
+ for (let tx = 0; tx < targetWidth; tx++) {
103
+ const nx = x0 + (tx + 0.5) / targetWidth * bw;
104
+ const sx = Math.max(0, Math.min(imgWidth - 1, Math.floor(nx * imgWidth)));
105
+ const srcIdx = (rowBase + sx) * 3;
106
+ if (srcIdx + 2 < bytes.byteLength) {
107
+ out[dstIdx++] = bytes[srcIdx];
108
+ out[dstIdx++] = bytes[srcIdx + 1];
109
+ out[dstIdx++] = bytes[srcIdx + 2];
110
+ } else {
111
+ out[dstIdx++] = 128;
112
+ out[dstIdx++] = 128;
113
+ out[dstIdx++] = 128;
114
+ }
115
+ }
116
+ }
117
+ return out.buffer;
118
+ }
119
+
120
+ /**
121
+ * Letterboxes an RGB uint8 image region preserving aspect ratio into a square Float32 [0.0, 1.0]
122
+ * tensor expected by `cat_face_localizer.tflite` (224x224).
123
+ */
124
+ function letterboxRgbToFloat01Buffer(rgbBuffer, imgWidth, imgHeight, targetSize = 224, roiBox = {
125
+ x: 0,
126
+ y: 0,
127
+ width: 1,
128
+ height: 1
129
+ }) {
130
+ 'worklet';
131
+
132
+ const bytes = new Uint8Array(rgbBuffer);
133
+ const out = new Float32Array(targetSize * targetSize * 3);
134
+ const x0 = clamp01(roiBox.x);
135
+ const y0 = clamp01(roiBox.y);
136
+ const bw = Math.max(0.04, Math.min(1 - x0, roiBox.width));
137
+ const bh = Math.max(0.04, Math.min(1 - y0, roiBox.height));
138
+ const roiPxW = Math.max(1, bw * imgWidth);
139
+ const roiPxH = Math.max(1, bh * imgHeight);
140
+ const scale = Math.min(targetSize / roiPxW, targetSize / roiPxH);
141
+ const scaledW = Math.max(1, Math.round(roiPxW * scale));
142
+ const scaledH = Math.max(1, Math.round(roiPxH * scale));
143
+ const padX = Math.floor((targetSize - scaledW) / 2);
144
+ const padY = Math.floor((targetSize - scaledH) / 2);
145
+ for (let ty = 0; ty < scaledH; ty++) {
146
+ const outY = padY + ty;
147
+ if (outY < 0 || outY >= targetSize) continue;
148
+ const ny = y0 + (ty + 0.5) / scaledH * bh;
149
+ const sy = Math.max(0, Math.min(imgHeight - 1, Math.floor(ny * imgHeight)));
150
+ const rowBase = sy * imgWidth;
151
+ for (let tx = 0; tx < scaledW; tx++) {
152
+ const outX = padX + tx;
153
+ if (outX < 0 || outX >= targetSize) continue;
154
+ const nx = x0 + (tx + 0.5) / scaledW * bw;
155
+ const sx = Math.max(0, Math.min(imgWidth - 1, Math.floor(nx * imgWidth)));
156
+ const srcIdx = (rowBase + sx) * 3;
157
+ const dstIdx = (outY * targetSize + outX) * 3;
158
+ if (srcIdx + 2 < bytes.byteLength) {
159
+ out[dstIdx] = bytes[srcIdx] / 255.0;
160
+ out[dstIdx + 1] = bytes[srcIdx + 1] / 255.0;
161
+ out[dstIdx + 2] = bytes[srcIdx + 2] / 255.0;
162
+ }
163
+ }
164
+ }
165
+ return {
166
+ buffer: out.buffer,
167
+ meta: {
168
+ roiBox: {
169
+ x: x0,
170
+ y: y0,
171
+ width: bw,
172
+ height: bh
173
+ },
174
+ normWidth: scaledW / targetSize,
175
+ normHeight: scaledH / targetSize,
176
+ padNormX: padX / targetSize,
177
+ padNormY: padY / targetSize
178
+ }
179
+ };
180
+ }
181
+
182
+ /**
183
+ * Un-letterboxes [xmin, ymin, xmax, ymax] output from `cat_face_localizer.tflite` back into full-frame [0, 1] box.
184
+ */
185
+ function deletterboxNormalizedBox(rawOutputs, meta) {
186
+ 'worklet';
187
+
188
+ if (!rawOutputs || !Array.isArray(rawOutputs) || rawOutputs.length === 0) {
189
+ return null;
190
+ }
191
+ const arr = extractNumericVector(rawOutputs[0], false);
192
+ if (!arr || arr.length < 4) {
193
+ return null;
194
+ }
195
+ const rx1 = Number.isFinite(arr[0]) ? clamp01(arr[0]) : 0;
196
+ const ry1 = Number.isFinite(arr[1]) ? clamp01(arr[1]) : 0;
197
+ const rx2 = Number.isFinite(arr[2]) ? clamp01(arr[2]) : 1;
198
+ const ry2 = Number.isFinite(arr[3]) ? clamp01(arr[3]) : 1;
199
+ const lx1 = Math.min(rx1, rx2);
200
+ const lx2 = Math.max(rx1, rx2);
201
+ const ly1 = Math.min(ry1, ry2);
202
+ const ly2 = Math.max(ry1, ry2);
203
+ const ux1 = clamp01((lx1 - meta.padNormX) / Math.max(0.01, meta.normWidth));
204
+ const ux2 = clamp01((lx2 - meta.padNormX) / Math.max(0.01, meta.normWidth));
205
+ const uy1 = clamp01((ly1 - meta.padNormY) / Math.max(0.01, meta.normHeight));
206
+ const uy2 = clamp01((ly2 - meta.padNormY) / Math.max(0.01, meta.normHeight));
207
+ const fw = ux2 - ux1;
208
+ const fh = uy2 - uy1;
209
+ if (fw < 0.04 || fh < 0.04) {
210
+ return null;
211
+ }
212
+ const fullX = clamp01(meta.roiBox.x + ux1 * meta.roiBox.width);
213
+ const fullY = clamp01(meta.roiBox.y + uy1 * meta.roiBox.height);
214
+ const fullW = Math.min(1 - fullX, fw * meta.roiBox.width);
215
+ const fullH = Math.min(1 - fullY, fh * meta.roiBox.height);
216
+ if (fullW < 0.02 || fullH < 0.02) {
217
+ return null;
218
+ }
219
+ return {
220
+ x: fullX,
221
+ y: fullY,
222
+ width: fullW,
223
+ height: fullH
224
+ };
225
+ }
226
+
227
+ /**
228
+ * Decodes top-K cat breed candidates from either Float32 or Quantized Uint8 softmax/logit output tensors.
229
+ */
230
+ function decodeBreedProbabilities(rawOutputs, labels, source, isQuantizedUint8 = false, topK = 3) {
231
+ 'worklet';
232
+
233
+ if (!rawOutputs || !Array.isArray(rawOutputs) || rawOutputs.length === 0 || !labels || labels.length === 0) {
234
+ return [];
235
+ }
236
+ const vec = extractNumericVector(rawOutputs[0], isQuantizedUint8);
237
+ if (!vec || vec.length === 0) {
238
+ return [];
239
+ }
240
+ const count = Math.min(labels.length, vec.length);
241
+ const scores = new Array(count);
242
+ let sum = 0;
243
+ let needsSoftmax = false;
244
+ let maxVal = -Infinity;
245
+ for (let i = 0; i < count; i++) {
246
+ const raw = vec[i];
247
+ const v = Number.isFinite(raw) ? isQuantizedUint8 ? raw / 255.0 : raw : 0;
248
+ scores[i] = v;
249
+ sum += v;
250
+ if (v < 0 || v > 1.001) {
251
+ needsSoftmax = true;
252
+ }
253
+ if (v > maxVal) {
254
+ maxVal = v;
255
+ }
256
+ }
257
+ if (needsSoftmax || sum <= 0.01) {
258
+ let expSum = 0;
259
+ for (let i = 0; i < count; i++) {
260
+ const e = Math.exp(scores[i] - maxVal);
261
+ scores[i] = e;
262
+ expSum += e;
263
+ }
264
+ const denom = Math.max(1e-6, expSum);
265
+ for (let i = 0; i < count; i++) {
266
+ scores[i] /= denom;
267
+ }
268
+ } else if (Math.abs(sum - 1) > 0.01) {
269
+ for (let i = 0; i < count; i++) {
270
+ scores[i] /= sum;
271
+ }
272
+ }
273
+ const ranked = new Array(count);
274
+ for (let i = 0; i < count; i++) {
275
+ ranked[i] = {
276
+ breed: normalizeBreedAlias(labels[i]),
277
+ confidence: clamp01(scores[i]),
278
+ source
279
+ };
280
+ }
281
+ ranked.sort((a, b) => b.confidence - a.confidence);
282
+ return ranked.slice(0, Math.max(1, topK));
283
+ }
284
+
285
+ /**
286
+ * Merges and temporally smooths predictions across 67-breed and 12-pedigree breed engines.
287
+ */
288
+ function fuseBreedPredictions(breed67, breed12, emaMap, alpha = 0.38, topK = 3) {
289
+ 'worklet';
290
+
291
+ const combined = {};
292
+ for (let i = 0; i < breed67.length; i++) {
293
+ const c = breed67[i];
294
+ const key = normalizeBreedAlias(c.breed);
295
+ if (!combined[key]) {
296
+ combined[key] = {
297
+ score: 0,
298
+ weight: 0,
299
+ has67: false,
300
+ has12: false
301
+ };
302
+ }
303
+ combined[key].score += c.confidence * 0.48;
304
+ combined[key].weight += 0.48;
305
+ combined[key].has67 = true;
306
+ }
307
+ for (let i = 0; i < breed12.length; i++) {
308
+ const c = breed12[i];
309
+ const key = normalizeBreedAlias(c.breed);
310
+ if (!combined[key]) {
311
+ combined[key] = {
312
+ score: 0,
313
+ weight: 0,
314
+ has67: false,
315
+ has12: false
316
+ };
317
+ }
318
+ combined[key].score += c.confidence * 0.52;
319
+ combined[key].weight += 0.52;
320
+ combined[key].has12 = true;
321
+ }
322
+ const allKeys = Object.keys(emaMap);
323
+ for (let i = 0; i < allKeys.length; i++) {
324
+ const k = allKeys[i];
325
+ if (!combined[k]) {
326
+ const decayed = emaMap[k] * (1 - alpha);
327
+ if (decayed < 0.02) {
328
+ delete emaMap[k];
329
+ } else {
330
+ emaMap[k] = decayed;
331
+ }
332
+ }
333
+ }
334
+ const nextKeys = Object.keys(combined);
335
+ for (let i = 0; i < nextKeys.length; i++) {
336
+ const k = nextKeys[i];
337
+ const entry = combined[k];
338
+ const inst = entry.weight > 0 ? entry.score / entry.weight : entry.score;
339
+ const prev = emaMap[k] ?? inst;
340
+ emaMap[k] = prev * (1 - alpha) + inst * alpha;
341
+ }
342
+ const out = [];
343
+ const finalKeys = Object.keys(emaMap);
344
+ for (let i = 0; i < finalKeys.length; i++) {
345
+ const breed = finalKeys[i];
346
+ const entry = combined[breed];
347
+ const src = entry?.has67 && entry?.has12 ? 'ensemble' : entry?.has12 ? 'oxford12' : 'breed67';
348
+ out.push({
349
+ breed,
350
+ confidence: clamp01(emaMap[breed]),
351
+ source: src
352
+ });
353
+ }
354
+ out.sort((a, b) => b.confidence - a.confidence);
355
+ return out.slice(0, Math.max(1, topK));
356
+ }
357
+
358
+ /**
359
+ * Decodes [1, 96] normalized landmark outputs from `cat_face_landmarks_full.tflite` into 48 full-frame landmarks.
360
+ */
361
+ function decodeCatFaceLandmarks(rawOutputs, cropBox) {
362
+ 'worklet';
363
+
364
+ if (!rawOutputs || !Array.isArray(rawOutputs) || rawOutputs.length === 0) {
365
+ return null;
366
+ }
367
+ const vec = extractNumericVector(rawOutputs[0], false);
368
+ if (!vec || vec.length < 96) {
369
+ return null;
370
+ }
371
+ const landmarks = new Array(48);
372
+ for (let i = 0; i < 48; i++) {
373
+ const rx = vec[i * 2];
374
+ const ry = vec[i * 2 + 1];
375
+ const nx = Number.isFinite(rx) ? clamp01(rx) : 0.5;
376
+ const ny = Number.isFinite(ry) ? clamp01(ry) : 0.5;
377
+ let type = undefined;
378
+ if (i === 4) type = 'rightEye';else if (i === 8) type = 'leftEye';else if (i === 13 || i === 43) type = 'noseTip';else if (i === 24) type = 'rightEar';else if (i === 29) type = 'leftEar';else if (i === 18) type = 'mouth';
379
+ landmarks[i] = {
380
+ x: clamp01(cropBox.x + nx * cropBox.width),
381
+ y: clamp01(cropBox.y + ny * cropBox.height),
382
+ type
383
+ };
384
+ }
385
+ return landmarks;
386
+ }
387
+ function measureClusterSpan(landmarks, indices) {
388
+ 'worklet';
389
+
390
+ let minX = 1;
391
+ let maxX = 0;
392
+ let minY = 1;
393
+ let maxY = 0;
394
+ let sumX = 0;
395
+ let sumY = 0;
396
+ let count = 0;
397
+ for (let i = 0; i < indices.length; i++) {
398
+ const pt = landmarks[indices[i]];
399
+ if (!pt) continue;
400
+ if (pt.x < minX) minX = pt.x;
401
+ if (pt.x > maxX) maxX = pt.x;
402
+ if (pt.y < minY) minY = pt.y;
403
+ if (pt.y > maxY) maxY = pt.y;
404
+ sumX += pt.x;
405
+ sumY += pt.y;
406
+ count++;
407
+ }
408
+ const safeCount = Math.max(1, count);
409
+ return {
410
+ minX,
411
+ maxX,
412
+ minY,
413
+ maxY,
414
+ cx: sumX / safeCount,
415
+ cy: sumY / safeCount
416
+ };
417
+ }
418
+
419
+ /**
420
+ * Computes CatFACS facial muscle & posture metrics (slow-blink eyes, airplane ears, meow/mouth opening)
421
+ * and synthesizes feline affective mood directly from 48 CatFLW landmarks.
422
+ */
423
+ function computeCatFACSMetrics(landmarks48) {
424
+ 'worklet';
425
+
426
+ const rOuter = landmarks48[4];
427
+ const lOuter = landmarks48[8];
428
+ const dxEyes = (lOuter?.x ?? 0.65) - (rOuter?.x ?? 0.35);
429
+ const dyEyes = (lOuter?.y ?? 0.45) - (rOuter?.y ?? 0.45);
430
+ const iod = Math.max(0.03, Math.sqrt(dxEyes * dxEyes + dyEyes * dyEyes));
431
+ const headTiltDeg = Number((Math.atan2(dyEyes, dxEyes) * 180 / Math.PI).toFixed(1));
432
+ const eyeMidY = ((rOuter?.y ?? 0.45) + (lOuter?.y ?? 0.45)) * 0.5;
433
+ const rEyeSpan = measureClusterSpan(landmarks48, CAT_RIGHT_EYE_SET);
434
+ const lEyeSpan = measureClusterSpan(landmarks48, CAT_LEFT_EYE_SET);
435
+ const rEyeOpen = (rEyeSpan.maxY - rEyeSpan.minY) / Math.max(0.01, rEyeSpan.maxX - rEyeSpan.minX);
436
+ const lEyeOpen = (lEyeSpan.maxY - lEyeSpan.minY) / Math.max(0.01, lEyeSpan.maxX - lEyeSpan.minX);
437
+ const eyeApertureRatio = Number(((rEyeOpen + lEyeOpen) * 0.5).toFixed(3));
438
+ const isSlowBlinking = eyeApertureRatio < 0.29;
439
+ const rEarSpan = measureClusterSpan(landmarks48, CAT_RIGHT_EAR_SET);
440
+ const lEarSpan = measureClusterSpan(landmarks48, CAT_LEFT_EAR_SET);
441
+ const avgEarTipHeight = (eyeMidY - rEarSpan.minY + (eyeMidY - lEarSpan.minY)) * 0.5;
442
+ const earElevationRatio = Number(Math.max(0, avgEarTipHeight / iod).toFixed(3));
443
+ const earOuterSpan = Math.abs(lEarSpan.maxX - rEarSpan.minX);
444
+ const earSpreadRatio = Number((earOuterSpan / iod).toFixed(3));
445
+ const isAirplaneEars = earElevationRatio < 0.42 || earSpreadRatio > 2.45;
446
+ const mouthSpan = measureClusterSpan(landmarks48, CAT_MOUTH_CHIN_SET);
447
+ const mouthOpenRatio = Number(((mouthSpan.maxY - mouthSpan.minY) / Math.max(0.02, iod)).toFixed(3));
448
+ const isVocalizing = mouthOpenRatio >= 0.48;
449
+ let mood = 'alert_curious';
450
+ let moodLabel = 'Alert & Curious';
451
+ let moodConfidence = 0.78;
452
+ if (isVocalizing) {
453
+ mood = 'vocalizing';
454
+ moodLabel = 'Vocalizing / Meow';
455
+ moodConfidence = Math.min(0.95, 0.7 + (mouthOpenRatio - 0.48) * 0.6);
456
+ } else if (isAirplaneEars) {
457
+ mood = 'annoyed_defensive';
458
+ moodLabel = 'Guarded (Airplane Ears)';
459
+ moodConfidence = 0.84;
460
+ } else if (eyeApertureRatio < 0.17) {
461
+ mood = 'sleepy';
462
+ moodLabel = 'Sleepy / Drowsy';
463
+ moodConfidence = 0.86;
464
+ } else if (isSlowBlinking) {
465
+ mood = 'calm_affectionate';
466
+ moodLabel = 'Relaxed (Slow-Blink)';
467
+ moodConfidence = 0.88;
468
+ } else if (eyeApertureRatio >= 0.50 && earElevationRatio >= 0.62) {
469
+ mood = 'playful_hunting';
470
+ moodLabel = 'Playful / Focused';
471
+ moodConfidence = 0.82;
472
+ }
473
+ return {
474
+ eyeApertureRatio,
475
+ isSlowBlinking,
476
+ earElevationRatio,
477
+ earSpreadRatio,
478
+ isAirplaneEars,
479
+ mouthOpenRatio,
480
+ isVocalizing,
481
+ headTiltDeg,
482
+ mood,
483
+ moodLabel,
484
+ moodConfidence: Number(moodConfidence.toFixed(2))
485
+ };
486
+ }
487
+
488
+ /**
489
+ * Downsamples MediaPipe DeepLab-V3 [1, 257, 257, 21] semantic segmentation output into a compact
490
+ * feline pixel mask (class 8 = cat) with tight bounding box and area coverage ratio.
491
+ */
492
+ function decodeDeepLabCatMask(rawOutputs, catClassIndex = 8, gridSize = 24, tensorSize = 257, numClasses = 21) {
493
+ 'worklet';
494
+
495
+ if (!rawOutputs || !Array.isArray(rawOutputs) || rawOutputs.length === 0) {
496
+ return null;
497
+ }
498
+ const vec = extractNumericVector(rawOutputs[0], false);
499
+ if (!vec || vec.length < tensorSize * numClasses) {
500
+ return null;
501
+ }
502
+ const mask = new Array(gridSize * gridSize);
503
+ let fgCount = 0;
504
+ let minGx = gridSize;
505
+ let minGy = gridSize;
506
+ let maxGx = -1;
507
+ let maxGy = -1;
508
+ for (let gy = 0; gy < gridSize; gy++) {
509
+ const sy = Math.min(tensorSize - 1, Math.floor((gy + 0.5) / gridSize * tensorSize));
510
+ for (let gx = 0; gx < gridSize; gx++) {
511
+ const sx = Math.min(tensorSize - 1, Math.floor((gx + 0.5) / gridSize * tensorSize));
512
+ const base = (sy * tensorSize + sx) * numClasses;
513
+ if (base + numClasses > vec.length) {
514
+ mask[gy * gridSize + gx] = 0;
515
+ continue;
516
+ }
517
+ let bestCls = 0;
518
+ let bestScore = vec[base];
519
+ for (let c = 1; c < numClasses; c++) {
520
+ const s = vec[base + c];
521
+ if (s > bestScore) {
522
+ bestScore = s;
523
+ bestCls = c;
524
+ }
525
+ }
526
+ const isCat = bestCls === catClassIndex ? 1 : 0;
527
+ mask[gy * gridSize + gx] = isCat;
528
+ if (isCat === 1) {
529
+ fgCount++;
530
+ if (gx < minGx) minGx = gx;
531
+ if (gy < minGy) minGy = gy;
532
+ if (gx > maxGx) maxGx = gx;
533
+ if (gy > maxGy) maxGy = gy;
534
+ }
535
+ }
536
+ }
537
+ const totalCells = gridSize * gridSize;
538
+ const coverageRatio = Number((fgCount / Math.max(1, totalCells)).toFixed(3));
539
+ const tightBounds = maxGx >= minGx && maxGy >= minGy ? {
540
+ x: minGx / gridSize,
541
+ y: minGy / gridSize,
542
+ width: (maxGx - minGx + 1) / gridSize,
543
+ height: (maxGy - minGy + 1) / gridSize
544
+ } : undefined;
545
+ return {
546
+ maskWidth: gridSize,
547
+ maskHeight: gridSize,
548
+ foregroundMask: mask,
549
+ coverageRatio,
550
+ tightBounds
551
+ };
552
+ }
553
+ function toHex2(v) {
554
+ 'worklet';
555
+
556
+ const clamped = Math.max(0, Math.min(255, Math.round(v)));
557
+ const hex = clamped.toString(16).toUpperCase();
558
+ return hex.length === 1 ? `0${hex}` : hex;
559
+ }
560
+
561
+ /**
562
+ * Extracts dominant coat colors, pattern estimate, and shot sharpness optimality from an RGB cat region,
563
+ * ignoring background pixels when DeepLab cat segmentation mask cells are available.
564
+ */
565
+ function analyzeCatCoatAndColors(rgbBuffer, imgWidth, imgHeight, roiBox, segMask) {
566
+ 'worklet';
567
+
568
+ const bytes = new Uint8Array(rgbBuffer);
569
+ const x0 = clamp01(roiBox.x);
570
+ const y0 = clamp01(roiBox.y);
571
+ const bw = Math.max(0.05, Math.min(1 - x0, roiBox.width));
572
+ const bh = Math.max(0.05, Math.min(1 - y0, roiBox.height));
573
+ const useMask = Boolean(segMask) && segMask.coverageRatio >= 0.04 && segMask.foregroundMask.length === segMask.maskWidth * segMask.maskHeight;
574
+ const bucketNames = ['Orange / Ginger', 'Cream / Fawn', 'Snow White', 'Ash / Grey', 'Charcoal Black', 'Chocolate / Brown'];
575
+ const counts = [0, 0, 0, 0, 0, 0];
576
+ const sumR = [0, 0, 0, 0, 0, 0];
577
+ const sumG = [0, 0, 0, 0, 0, 0];
578
+ const sumB = [0, 0, 0, 0, 0, 0];
579
+ const steps = 16;
580
+ let totalPixels = 0;
581
+ let lumSum = 0;
582
+ let edgeEnergy = 0;
583
+ let prevLum = -1;
584
+ for (let gy = 0; gy < steps; gy++) {
585
+ const ny = y0 + (gy + 0.5) / steps * bh;
586
+ const py = Math.max(0, Math.min(imgHeight - 1, Math.floor(ny * imgHeight)));
587
+ prevLum = -1;
588
+ for (let gx = 0; gx < steps; gx++) {
589
+ const nx = x0 + (gx + 0.5) / steps * bw;
590
+ if (useMask && segMask) {
591
+ const mx = Math.min(segMask.maskWidth - 1, Math.max(0, Math.floor(nx * segMask.maskWidth)));
592
+ const my = Math.min(segMask.maskHeight - 1, Math.max(0, Math.floor(ny * segMask.maskHeight)));
593
+ if (segMask.foregroundMask[my * segMask.maskWidth + mx] === 0) {
594
+ continue;
595
+ }
596
+ } else {
597
+ // Without segmentation mask, focus inside elliptical inner 75% core to avoid edges
598
+ const rx = ((gx + 0.5) / steps - 0.5) * 2;
599
+ const ry = ((gy + 0.5) / steps - 0.5) * 2;
600
+ if (rx * rx + ry * ry > 0.92) {
601
+ continue;
602
+ }
603
+ }
604
+ const px = Math.max(0, Math.min(imgWidth - 1, Math.floor(nx * imgWidth)));
605
+ const idx = (py * imgWidth + px) * 3;
606
+ if (idx + 2 >= bytes.byteLength) continue;
607
+ const r = bytes[idx];
608
+ const g = bytes[idx + 1];
609
+ const b = bytes[idx + 2];
610
+ const maxC = Math.max(r, g, b);
611
+ const minC = Math.min(r, g, b);
612
+ const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
613
+ const sat = maxC > 0 ? (maxC - minC) / maxC : 0;
614
+ lumSum += lum;
615
+ if (prevLum >= 0) {
616
+ edgeEnergy += Math.abs(lum - prevLum);
617
+ }
618
+ prevLum = lum;
619
+ totalPixels++;
620
+ let bucketIdx = 3; // Ash Grey default
621
+ if (lum > 0.78 && sat < 0.22) {
622
+ bucketIdx = 2; // Snow White
623
+ } else if (lum < 0.25 && sat < 0.35) {
624
+ bucketIdx = 4; // Charcoal Black
625
+ } else if (r > g + 14 && r > b + 22 && sat >= 0.24) {
626
+ if (lum >= 0.52) {
627
+ bucketIdx = 0; // Orange / Ginger
628
+ } else if (lum >= 0.36 && g - b < 35) {
629
+ bucketIdx = 5; // Chocolate / Brown
630
+ } else {
631
+ bucketIdx = 0;
632
+ }
633
+ } else if (lum >= 0.60 && r >= b + 10) {
634
+ bucketIdx = 1; // Cream / Fawn
635
+ }
636
+ counts[bucketIdx]++;
637
+ sumR[bucketIdx] += r;
638
+ sumG[bucketIdx] += g;
639
+ sumB[bucketIdx] += b;
640
+ }
641
+ }
642
+ const swatches = [];
643
+ if (totalPixels > 0) {
644
+ for (let i = 0; i < 6; i++) {
645
+ if (counts[i] <= 0) continue;
646
+ const pct = Math.round(counts[i] / totalPixels * 100);
647
+ if (pct < 8) continue;
648
+ const avgR = sumR[i] / counts[i];
649
+ const avgG = sumG[i] / counts[i];
650
+ const avgB = sumB[i] / counts[i];
651
+ swatches.push({
652
+ hex: `#${toHex2(avgR)}${toHex2(avgG)}${toHex2(avgB)}`,
653
+ name: bucketNames[i],
654
+ percentage: pct
655
+ });
656
+ }
657
+ swatches.sort((a, b) => b.percentage - a.percentage);
658
+ }
659
+ const orangePct = totalPixels > 0 ? counts[0] / totalPixels * 100 : 0;
660
+ const creamPct = totalPixels > 0 ? counts[1] / totalPixels * 100 : 0;
661
+ const whitePct = totalPixels > 0 ? counts[2] / totalPixels * 100 : 0;
662
+ const greyPct = totalPixels > 0 ? counts[3] / totalPixels * 100 : 0;
663
+ const blackPct = totalPixels > 0 ? counts[4] / totalPixels * 100 : 0;
664
+ const brownPct = totalPixels > 0 ? counts[5] / totalPixels * 100 : 0;
665
+ const meanEdge = totalPixels > 0 ? edgeEnergy / totalPixels : 0;
666
+ let coatPattern = 'Solid / Shaded Coat';
667
+ if (orangePct + creamPct >= 15 && blackPct + greyPct + brownPct >= 15 && whitePct >= 14) {
668
+ coatPattern = 'Calico / Tricolor';
669
+ } else if ((blackPct + greyPct >= 22 || orangePct >= 22) && whitePct >= 20) {
670
+ coatPattern = 'Bicolor / Tuxedo';
671
+ } else if (orangePct >= 20 && creamPct >= 14) {
672
+ coatPattern = 'Ginger / Oyen Tabby';
673
+ } else if (orangePct >= 55) {
674
+ coatPattern = 'Solid Ginger / Oyen';
675
+ } else if (meanEdge >= 0.065) {
676
+ coatPattern = 'Tabby / Mackerel Stripe';
677
+ } else if (whitePct >= 65) {
678
+ coatPattern = 'Solid Snow White';
679
+ } else if (blackPct >= 60) {
680
+ coatPattern = 'Solid Charcoal Black';
681
+ } else if (greyPct >= 55) {
682
+ coatPattern = 'Solid Ash / Blue';
683
+ }
684
+ const avgLum = totalPixels > 0 ? lumSum / totalPixels : 0.5;
685
+ const lightScore = 1 - Math.min(1, Math.abs(avgLum - 0.5) * 1.9);
686
+ const sharpScore = Math.min(1, meanEdge / 0.07);
687
+ const framingScore = useMask && segMask ? Math.min(1, segMask.coverageRatio / 0.25) : 0.8;
688
+ const shotOptimalityScore = Math.round((lightScore * 0.4 + sharpScore * 0.35 + framingScore * 0.25) * 100);
689
+ return {
690
+ swatches: swatches.slice(0, 3),
691
+ coatPattern,
692
+ shotOptimalityScore: Math.max(0, Math.min(100, shotOptimalityScore))
693
+ };
694
+ }
695
+
696
+ /**
697
+ * Extracts a compact 96-D L2-normalized feline appearance & landmark geometry embedding
698
+ * for 1-tap personal Cat ID matching via cosine similarity.
699
+ */
700
+ function extractCatIdentityDescriptor(rgbBuffer, imgWidth, imgHeight, catBox, landmarks48) {
701
+ 'worklet';
702
+
703
+ const bytes = new Uint8Array(rgbBuffer);
704
+ const features = [];
705
+ const grid = 6;
706
+ const x0 = clamp01(catBox.x);
707
+ const y0 = clamp01(catBox.y);
708
+ const bw = Math.max(0.05, Math.min(1 - x0, catBox.width));
709
+ const bh = Math.max(0.05, Math.min(1 - y0, catBox.height));
710
+ const lums = [];
711
+ const rgDiffs = [];
712
+ for (let gy = 0; gy < grid; gy++) {
713
+ const ny = y0 + (gy + 0.5) / grid * bh;
714
+ const py = Math.max(0, Math.min(imgHeight - 1, Math.floor(ny * imgHeight)));
715
+ for (let gx = 0; gx < grid; gx++) {
716
+ const nx = x0 + (gx + 0.5) / grid * bw;
717
+ const px = Math.max(0, Math.min(imgWidth - 1, Math.floor(nx * imgWidth)));
718
+ const idx = (py * imgWidth + px) * 3;
719
+ const r = idx + 2 < bytes.byteLength ? bytes[idx] : 128;
720
+ const g = idx + 2 < bytes.byteLength ? bytes[idx + 1] : 128;
721
+ const b = idx + 2 < bytes.byteLength ? bytes[idx + 2] : 128;
722
+ lums.push((0.299 * r + 0.587 * g + 0.114 * b) / 255);
723
+ rgDiffs.push((r - b) / 255);
724
+ }
725
+ }
726
+ let meanL = 0;
727
+ for (let i = 0; i < lums.length; i++) meanL += lums[i];
728
+ meanL /= Math.max(1, lums.length);
729
+ for (let i = 0; i < lums.length; i++) {
730
+ features.push(lums[i] - meanL);
731
+ features.push(rgDiffs[i]);
732
+ }
733
+ if (landmarks48 && landmarks48.length >= 48) {
734
+ const anchorIndices = [4, 8, 13, 18, 24, 29, 36, 40, 43, 46, 0, 2];
735
+ const rEye = landmarks48[4];
736
+ const lEye = landmarks48[8];
737
+ const cx = ((rEye?.x ?? 0.5) + (lEye?.x ?? 0.5)) * 0.5;
738
+ const cy = ((rEye?.y ?? 0.5) + (lEye?.y ?? 0.5)) * 0.5;
739
+ const iod = Math.max(0.02, Math.hypot((lEye?.x ?? 0.6) - (rEye?.x ?? 0.4), (lEye?.y ?? 0.5) - (rEye?.y ?? 0.5)));
740
+ for (let i = 0; i < anchorIndices.length; i++) {
741
+ const lm = landmarks48[anchorIndices[i]];
742
+ features.push(((lm?.x ?? cx) - cx) / iod);
743
+ features.push(((lm?.y ?? cy) - cy) / iod);
744
+ }
745
+ } else {
746
+ for (let i = 0; i < 24; i++) {
747
+ features.push(0);
748
+ }
749
+ }
750
+ return (0, _blazeFaceParser.l2NormalizeEmbedding)(features);
751
+ }
752
+ //# sourceMappingURL=catParser.js.map