@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.
- package/README.md +32 -1
- package/lib/commonjs/detector/TFLiteCatAnalyzer.js +609 -0
- package/lib/commonjs/detector/TFLiteCatAnalyzer.js.map +1 -0
- package/lib/commonjs/detector/index.js +11 -0
- package/lib/commonjs/detector/index.js.map +1 -1
- package/lib/commonjs/detector/workletFrameHelper.js +233 -0
- package/lib/commonjs/detector/workletFrameHelper.js.map +1 -0
- package/lib/commonjs/parser/catParser.js +752 -0
- package/lib/commonjs/parser/catParser.js.map +1 -0
- package/lib/commonjs/parser/index.js +11 -0
- package/lib/commonjs/parser/index.js.map +1 -1
- package/lib/commonjs/types/cat.js +6 -0
- package/lib/commonjs/types/cat.js.map +1 -0
- package/lib/commonjs/types/index.js +11 -0
- package/lib/commonjs/types/index.js.map +1 -1
- package/lib/module/detector/TFLiteCatAnalyzer.js +605 -0
- package/lib/module/detector/TFLiteCatAnalyzer.js.map +1 -0
- package/lib/module/detector/index.js +1 -0
- package/lib/module/detector/index.js.map +1 -1
- package/lib/module/detector/workletFrameHelper.js +226 -0
- package/lib/module/detector/workletFrameHelper.js.map +1 -0
- package/lib/module/parser/catParser.js +739 -0
- package/lib/module/parser/catParser.js.map +1 -0
- package/lib/module/parser/index.js +1 -0
- package/lib/module/parser/index.js.map +1 -1
- package/lib/module/types/cat.js +4 -0
- package/lib/module/types/cat.js.map +1 -0
- package/lib/module/types/index.js +1 -0
- package/lib/module/types/index.js.map +1 -1
- package/lib/typescript/commonjs/detector/TFLiteCatAnalyzer.d.ts +6 -0
- package/lib/typescript/commonjs/detector/TFLiteCatAnalyzer.d.ts.map +1 -0
- package/lib/typescript/commonjs/detector/index.d.ts +1 -0
- package/lib/typescript/commonjs/detector/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/detector/workletFrameHelper.d.ts +40 -0
- package/lib/typescript/commonjs/detector/workletFrameHelper.d.ts.map +1 -0
- package/lib/typescript/commonjs/parser/catParser.d.ts +61 -0
- package/lib/typescript/commonjs/parser/catParser.d.ts.map +1 -0
- package/lib/typescript/commonjs/parser/index.d.ts +1 -0
- package/lib/typescript/commonjs/parser/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/types/cat.d.ts +109 -0
- package/lib/typescript/commonjs/types/cat.d.ts.map +1 -0
- package/lib/typescript/commonjs/types/index.d.ts +1 -0
- package/lib/typescript/commonjs/types/index.d.ts.map +1 -1
- package/lib/typescript/module/detector/TFLiteCatAnalyzer.d.ts +6 -0
- package/lib/typescript/module/detector/TFLiteCatAnalyzer.d.ts.map +1 -0
- package/lib/typescript/module/detector/index.d.ts +1 -0
- package/lib/typescript/module/detector/index.d.ts.map +1 -1
- package/lib/typescript/module/detector/workletFrameHelper.d.ts +40 -0
- package/lib/typescript/module/detector/workletFrameHelper.d.ts.map +1 -0
- package/lib/typescript/module/parser/catParser.d.ts +61 -0
- package/lib/typescript/module/parser/catParser.d.ts.map +1 -0
- package/lib/typescript/module/parser/index.d.ts +1 -0
- package/lib/typescript/module/parser/index.d.ts.map +1 -1
- package/lib/typescript/module/types/cat.d.ts +109 -0
- package/lib/typescript/module/types/cat.d.ts.map +1 -0
- package/lib/typescript/module/types/index.d.ts +1 -0
- package/lib/typescript/module/types/index.d.ts.map +1 -1
- package/package.json +5 -10
package/README.md
CHANGED
|
@@ -25,9 +25,11 @@ Provides worklet-safe, GPU-accelerated on-device machine learning inference for
|
|
|
25
25
|
- Real-time identity matching against stored embedding profiles with configurable cosine similarity threshold.
|
|
26
26
|
- **🔄 Universal Asset Resolution**:
|
|
27
27
|
- Supports Metro asset bundles (`require('./model.tflite')`), local filesystem URIs (`file:///...`), and remote URLs (`https://...`).
|
|
28
|
-
-
|
|
28
|
+
- **Worklet-Safe Execution**:
|
|
29
29
|
- Implements the `CameraProcessor` interface from `@masumdev/rn-camera-ai`.
|
|
30
30
|
- Runs in dedicated background worklet threads with zero garbage collection spikes and 0% JS-thread lag.
|
|
31
|
+
- **Multi-Model Cat Vision (`createTFLiteCatAnalyzer`)**:
|
|
32
|
+
- Staggered 6-model feline pipeline (COCO SSD cat gate + Close-Up Fallback, Dual 67 + Oxford-12 Breed Ensemble, 2-stage 48-pt CatFLW face mesh & CatFACS mood, DeepLabV3 class-8 segmentation + fur coat color swatches, and 1-tap 96-D Cat ID).
|
|
31
33
|
|
|
32
34
|
---
|
|
33
35
|
|
|
@@ -370,6 +372,35 @@ Exported for building custom inference loops or testing:
|
|
|
370
372
|
|
|
371
373
|
---
|
|
372
374
|
|
|
375
|
+
## Multi-Model Cat Vision Analyzer (`createTFLiteCatAnalyzer`)
|
|
376
|
+
|
|
377
|
+
Orchestrates up to 6 staggered on-device `.tflite` models inside a single worklet `CameraProcessor`:
|
|
378
|
+
|
|
379
|
+
- **`detectorModel`**: COCO SSD species & scene context gate (`detect.tflite`) with optional DeepLab/Oxford-12 **Close-Up Fallback**.
|
|
380
|
+
- **`breed67Model` & `breed12Model`**: Dual breed classifiers fused with Exponential Moving Average (EMA) smoothing (`'ensemble' | '67' | '12'`).
|
|
381
|
+
- **`catFaceLocalizerModel` & `catFaceLandmarksModel`**: 2-stage tight face ROI localization (letterboxed 224x224) + 48-point CatFLW keypoints (384x384) driving `CatFACSMetrics` (slow-blink, airplane ears, vocalizing, head tilt). *(Note: CatFLW weights are typically distributed under CC BY-NC 4.0 for non-commercial use while this library package remains MIT.)*
|
|
382
|
+
- **`segmentationModel`**: MediaPipe DeepLab-V3 (257x257, Pascal VOC class `8 = cat`) generating a downsampled silhouette mask, dominant fur hex swatches, coat pattern classification, and shot optimality score.
|
|
383
|
+
- **1-Tap Cat ID**: `enrollLastDetectedCat(name, breedHint)` captures a 96-D L2-normalized descriptor matching cats across sessions via cosine similarity.
|
|
384
|
+
|
|
385
|
+
```tsx
|
|
386
|
+
const analyzer = await createTFLiteCatAnalyzer({
|
|
387
|
+
detectorModel: require('./assets/models/detect.tflite'),
|
|
388
|
+
detectorLabels: COCO_91_LABELS,
|
|
389
|
+
detectorLabelOffset: 1,
|
|
390
|
+
breed67Model: require('./assets/models/cat_breed_67.tflite'),
|
|
391
|
+
breed67Labels: CAT_BREED_67_LABELS,
|
|
392
|
+
breed12Model: require('./assets/models/cat_breed_oxford12.tflite'),
|
|
393
|
+
breed12Labels: CAT_BREED_12_LABELS,
|
|
394
|
+
catFaceLocalizerModel: require('./assets/models/cat_face_localizer.tflite'),
|
|
395
|
+
catFaceLandmarksModel: require('./assets/models/cat_face_landmarks_full.tflite'),
|
|
396
|
+
segmentationModel: require('./assets/models/deeplab_v3.tflite'),
|
|
397
|
+
initialMode: 'all',
|
|
398
|
+
initialBreedEngine: 'ensemble',
|
|
399
|
+
});
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
---
|
|
403
|
+
|
|
373
404
|
## License
|
|
374
405
|
|
|
375
406
|
MIT © [Ma'sum](https://github.com/masumrpg) — [masumdev.id](https://lib.masumdev.id)
|
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.createTFLiteCatAnalyzer = createTFLiteCatAnalyzer;
|
|
7
|
+
var _rnCameraAi = require("@masumdev/rn-camera-ai");
|
|
8
|
+
var _blazeFaceParser = require("../parser/blazeFaceParser.js");
|
|
9
|
+
var _catParser = require("../parser/catParser.js");
|
|
10
|
+
var _outputParser = require("../parser/outputParser.js");
|
|
11
|
+
var _modelLoader = require("./modelLoader.js");
|
|
12
|
+
var _workletFrameHelper = require("./workletFrameHelper.js");
|
|
13
|
+
const FULL_FRAME_BOX = {
|
|
14
|
+
x: 0,
|
|
15
|
+
y: 0,
|
|
16
|
+
width: 1,
|
|
17
|
+
height: 1
|
|
18
|
+
};
|
|
19
|
+
const CLOSEUP_ROI_BOX = {
|
|
20
|
+
x: 0.08,
|
|
21
|
+
y: 0.08,
|
|
22
|
+
width: 0.84,
|
|
23
|
+
height: 0.84
|
|
24
|
+
};
|
|
25
|
+
function buildSceneContextTags(allDetections) {
|
|
26
|
+
'worklet';
|
|
27
|
+
|
|
28
|
+
const tags = [];
|
|
29
|
+
const seen = {};
|
|
30
|
+
for (let i = 0; i < allDetections.length; i++) {
|
|
31
|
+
const lbl = allDetections[i].label.toLowerCase();
|
|
32
|
+
let tag = null;
|
|
33
|
+
if (lbl === 'bowl' || lbl === 'cup') tag = 'Bowl Nearby (Feeding)';else if (lbl === 'bed' || lbl === 'couch') tag = 'Resting Spot';else if (lbl === 'person') tag = 'With Owner';else if (lbl === 'bird' || lbl === 'mouse') tag = 'Prey Focus Alert';else if (lbl === 'dog') tag = 'Dog Companion';else if (lbl === 'potted plant') tag = 'Indoor Plant';
|
|
34
|
+
if (tag && !seen[tag]) {
|
|
35
|
+
seen[tag] = true;
|
|
36
|
+
tags.push(tag);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return tags;
|
|
40
|
+
}
|
|
41
|
+
function createCatWorkletProcessor(params) {
|
|
42
|
+
const {
|
|
43
|
+
disposedSync,
|
|
44
|
+
readySync,
|
|
45
|
+
detectorModelSync,
|
|
46
|
+
breed67ModelSync,
|
|
47
|
+
breed12ModelSync,
|
|
48
|
+
catFaceLocalizerSync,
|
|
49
|
+
catFaceLandmarksSync,
|
|
50
|
+
segmentationModelSync,
|
|
51
|
+
modeSync,
|
|
52
|
+
breedEngineSync,
|
|
53
|
+
confidenceSync,
|
|
54
|
+
similaritySync,
|
|
55
|
+
closeUpFallbackSync,
|
|
56
|
+
lastFrameTimeSync,
|
|
57
|
+
tickCounterSync,
|
|
58
|
+
missCounterSync,
|
|
59
|
+
wasThrottledSync,
|
|
60
|
+
enrolledCatsSync,
|
|
61
|
+
lastEmbeddingSync,
|
|
62
|
+
lastBreedHintSync,
|
|
63
|
+
cacheSync,
|
|
64
|
+
minFrameIntervalMs,
|
|
65
|
+
detectorInputWidth,
|
|
66
|
+
detectorInputHeight,
|
|
67
|
+
detectorLabels,
|
|
68
|
+
detectorLabelOffset,
|
|
69
|
+
breed67Labels,
|
|
70
|
+
breed12Labels,
|
|
71
|
+
segmentationCatClassIndex,
|
|
72
|
+
frameConverter,
|
|
73
|
+
resizePlugin
|
|
74
|
+
} = params;
|
|
75
|
+
return frame => {
|
|
76
|
+
'worklet';
|
|
77
|
+
|
|
78
|
+
if (disposedSync.getBlocking()) {
|
|
79
|
+
throw new Error('Cannot process frame: cat analyzer is disposed');
|
|
80
|
+
}
|
|
81
|
+
const detectorModel = detectorModelSync.getBlocking();
|
|
82
|
+
if (!readySync.getBlocking() || !detectorModel) {
|
|
83
|
+
wasThrottledSync.setBlocking(false);
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
if (minFrameIntervalMs > 0) {
|
|
87
|
+
const now = Date.now();
|
|
88
|
+
const prev = lastFrameTimeSync.getBlocking();
|
|
89
|
+
if (prev > 0 && now - prev < minFrameIntervalMs) {
|
|
90
|
+
wasThrottledSync.setBlocking(true);
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
lastFrameTimeSync.setBlocking(now);
|
|
94
|
+
}
|
|
95
|
+
wasThrottledSync.setBlocking(false);
|
|
96
|
+
const extracted = (0, _workletFrameHelper.extractRgbUint8Frame)(frame, 384, frameConverter, resizePlugin);
|
|
97
|
+
if (!extracted) {
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
const {
|
|
101
|
+
buffer: rgbBuf,
|
|
102
|
+
width: frameW,
|
|
103
|
+
height: frameH,
|
|
104
|
+
needs180Correction
|
|
105
|
+
} = extracted;
|
|
106
|
+
|
|
107
|
+
// Stage 1: COCO SSD Object Detection (finds cats + companion props)
|
|
108
|
+
const ssdInput = frameW === detectorInputWidth && frameH === detectorInputHeight ? rgbBuf : (0, _catParser.cropRgbToUint8Buffer)(rgbBuf, frameW, frameH, FULL_FRAME_BOX, detectorInputWidth, detectorInputHeight);
|
|
109
|
+
const ssdOutputs = detectorModel.runSync([ssdInput]);
|
|
110
|
+
const ssdDetections = Array.isArray(ssdOutputs) && ssdOutputs.length >= 3 ? (0, _outputParser.parseDetectionOutputs)(ssdOutputs, {
|
|
111
|
+
confidenceThreshold: Math.min(0.35, confidenceSync.getBlocking()),
|
|
112
|
+
maxResults: 12,
|
|
113
|
+
labels: detectorLabels,
|
|
114
|
+
labelOffset: detectorLabelOffset
|
|
115
|
+
}) : [];
|
|
116
|
+
const confThreshold = confidenceSync.getBlocking();
|
|
117
|
+
const catDetections = [];
|
|
118
|
+
for (let i = 0; i < ssdDetections.length; i++) {
|
|
119
|
+
const d = ssdDetections[i];
|
|
120
|
+
if (d.label.toLowerCase() === 'cat' && d.confidence >= confThreshold) {
|
|
121
|
+
catDetections.push(d);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const sceneContextTags = buildSceneContextTags(ssdDetections);
|
|
125
|
+
const mode = modeSync.getBlocking();
|
|
126
|
+
const breedEngine = breedEngineSync.getBlocking();
|
|
127
|
+
const breed67Model = breed67ModelSync.getBlocking();
|
|
128
|
+
const breed12Model = breed12ModelSync.getBlocking();
|
|
129
|
+
const localizerModel = catFaceLocalizerSync.getBlocking();
|
|
130
|
+
const landmarksModel = catFaceLandmarksSync.getBlocking();
|
|
131
|
+
const segModel = segmentationModelSync.getBlocking();
|
|
132
|
+
const cache = cacheSync.getBlocking();
|
|
133
|
+
let activeTargetBox = catDetections.length > 0 ? catDetections[0].boundingBox : null;
|
|
134
|
+
let isSyntheticCloseUp = false;
|
|
135
|
+
|
|
136
|
+
// Optional close-up fallback gated by DeepLab or strong breed classifier confidence
|
|
137
|
+
if (!activeTargetBox && closeUpFallbackSync.getBlocking()) {
|
|
138
|
+
let gatePassed = false;
|
|
139
|
+
let segGateSummary = undefined;
|
|
140
|
+
if (segModel) {
|
|
141
|
+
try {
|
|
142
|
+
const segInput = (0, _blazeFaceParser.cropAndResizeFaceToFloat32Buffer)(rgbBuf, frameW, frameH, FULL_FRAME_BOX, 257, 257);
|
|
143
|
+
const segOut = segModel.runSync([segInput]);
|
|
144
|
+
const summary = (0, _catParser.decodeDeepLabCatMask)(segOut, segmentationCatClassIndex, 24, 257, 21);
|
|
145
|
+
if (summary && summary.coverageRatio >= 0.06) {
|
|
146
|
+
segGateSummary = summary;
|
|
147
|
+
gatePassed = true;
|
|
148
|
+
}
|
|
149
|
+
} catch {
|
|
150
|
+
// Ignore segmentation error during close-up check
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (!gatePassed && breed12Model) {
|
|
154
|
+
try {
|
|
155
|
+
const b12Input = (0, _catParser.cropRgbToUint8Buffer)(rgbBuf, frameW, frameH, CLOSEUP_ROI_BOX, 224, 224);
|
|
156
|
+
const b12Out = breed12Model.runSync([b12Input]);
|
|
157
|
+
const top12 = (0, _catParser.decodeBreedProbabilities)(b12Out, breed12Labels, 'oxford12', true, 1);
|
|
158
|
+
if (top12.length > 0 && top12[0].confidence >= 0.52) {
|
|
159
|
+
gatePassed = true;
|
|
160
|
+
}
|
|
161
|
+
} catch {
|
|
162
|
+
// Ignore error during gate check
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (gatePassed) {
|
|
166
|
+
isSyntheticCloseUp = true;
|
|
167
|
+
activeTargetBox = segGateSummary?.tightBounds ?? CLOSEUP_ROI_BOX;
|
|
168
|
+
if (segGateSummary) {
|
|
169
|
+
cache.segmentation = segGateSummary;
|
|
170
|
+
}
|
|
171
|
+
catDetections.push({
|
|
172
|
+
id: 'cat-closeup-0',
|
|
173
|
+
label: 'cat (Close-Up)',
|
|
174
|
+
confidence: 0.85,
|
|
175
|
+
boundingBox: activeTargetBox
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (catDetections.length === 0 || !activeTargetBox) {
|
|
180
|
+
const misses = missCounterSync.getBlocking() + 1;
|
|
181
|
+
missCounterSync.setBlocking(misses);
|
|
182
|
+
if (misses > 4) {
|
|
183
|
+
cache.topBreeds = [];
|
|
184
|
+
cache.emaMap = {};
|
|
185
|
+
cache.faceBoundingBox = undefined;
|
|
186
|
+
cache.landmarks48 = undefined;
|
|
187
|
+
cache.moodMetrics = undefined;
|
|
188
|
+
cache.segmentation = undefined;
|
|
189
|
+
cache.coatSwatches = undefined;
|
|
190
|
+
cache.coatPattern = undefined;
|
|
191
|
+
cache.shotOptimalityScore = undefined;
|
|
192
|
+
}
|
|
193
|
+
return [];
|
|
194
|
+
}
|
|
195
|
+
missCounterSync.setBlocking(0);
|
|
196
|
+
const tick = tickCounterSync.getBlocking();
|
|
197
|
+
tickCounterSync.setBlocking(tick + 1);
|
|
198
|
+
const runBreed = mode === 'breed' || mode === 'all' && tick % 3 === 0;
|
|
199
|
+
const runFaceMood = mode === 'face_mood' || mode === 'identity' || mode === 'all' && tick % 3 === 1;
|
|
200
|
+
const runSegmentation = mode === 'segmentation' || mode === 'identity' || mode === 'all' && tick % 3 === 2;
|
|
201
|
+
|
|
202
|
+
// Stage 2A: Cat Breed Classification (67-Class, 12-Class AutoML Edge, or Ensemble)
|
|
203
|
+
if (runBreed && (breed67Model || breed12Model)) {
|
|
204
|
+
let list67 = [];
|
|
205
|
+
let list12 = [];
|
|
206
|
+
if (breed67Model && (breedEngine === '67' || breedEngine === 'ensemble') && breed67Labels.length > 0) {
|
|
207
|
+
try {
|
|
208
|
+
const inp67 = (0, _blazeFaceParser.cropAndResizeFaceToNormalized01Float32Buffer)(rgbBuf, frameW, frameH, activeTargetBox, 224, 224);
|
|
209
|
+
const out67 = breed67Model.runSync([inp67]);
|
|
210
|
+
list67 = (0, _catParser.decodeBreedProbabilities)(out67, breed67Labels, 'breed67', false, 5);
|
|
211
|
+
} catch {
|
|
212
|
+
list67 = [];
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (breed12Model && (breedEngine === '12' || breedEngine === 'ensemble') && breed12Labels.length > 0) {
|
|
216
|
+
try {
|
|
217
|
+
const inp12 = (0, _catParser.cropRgbToUint8Buffer)(rgbBuf, frameW, frameH, activeTargetBox, 224, 224);
|
|
218
|
+
const out12 = breed12Model.runSync([inp12]);
|
|
219
|
+
list12 = (0, _catParser.decodeBreedProbabilities)(out12, breed12Labels, 'oxford12', true, 5);
|
|
220
|
+
} catch {
|
|
221
|
+
list12 = [];
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (breedEngine === '67' && list67.length > 0) {
|
|
225
|
+
cache.topBreeds = (0, _catParser.fuseBreedPredictions)(list67, [], cache.emaMap, 0.42, 3);
|
|
226
|
+
} else if (breedEngine === '12' && list12.length > 0) {
|
|
227
|
+
cache.topBreeds = (0, _catParser.fuseBreedPredictions)([], list12, cache.emaMap, 0.42, 3);
|
|
228
|
+
} else if (list67.length > 0 || list12.length > 0) {
|
|
229
|
+
cache.topBreeds = (0, _catParser.fuseBreedPredictions)(list67, list12, cache.emaMap, 0.38, 3);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Stage 2B: Cat Face Localizer + 48 CatFLW Landmarks + CatFACS Mood
|
|
234
|
+
if (runFaceMood && localizerModel) {
|
|
235
|
+
try {
|
|
236
|
+
const searchRoi = (0, _blazeFaceParser.expandFaceRoiBox)(activeTargetBox, 1.08);
|
|
237
|
+
const {
|
|
238
|
+
buffer: lbBuf,
|
|
239
|
+
meta: lbMeta
|
|
240
|
+
} = (0, _catParser.letterboxRgbToFloat01Buffer)(rgbBuf, frameW, frameH, 224, searchRoi);
|
|
241
|
+
const locOut = localizerModel.runSync([lbBuf]);
|
|
242
|
+
const faceBox = (0, _catParser.deletterboxNormalizedBox)(locOut, lbMeta);
|
|
243
|
+
if (faceBox) {
|
|
244
|
+
cache.faceBoundingBox = faceBox;
|
|
245
|
+
if (landmarksModel) {
|
|
246
|
+
const cropBox = (0, _blazeFaceParser.expandFaceRoiBox)(faceBox, 1.2);
|
|
247
|
+
const lmInput = (0, _blazeFaceParser.cropAndResizeFaceToNormalized01Float32Buffer)(rgbBuf, frameW, frameH, cropBox, 384, 384);
|
|
248
|
+
const lmOut = landmarksModel.runSync([lmInput]);
|
|
249
|
+
const pts48 = (0, _catParser.decodeCatFaceLandmarks)(lmOut, cropBox);
|
|
250
|
+
if (pts48 && pts48.length === 48) {
|
|
251
|
+
cache.landmarks48 = pts48;
|
|
252
|
+
cache.moodMetrics = (0, _catParser.computeCatFACSMetrics)(pts48);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
} catch {
|
|
257
|
+
// Keep prior cached landmarks/mood gracefully on transient failure
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Stage 2C: DeepLabV3 Cat Segmentation & Masked Coat Color/Pattern Analysis
|
|
262
|
+
if (runSegmentation || !cache.coatSwatches) {
|
|
263
|
+
if (segModel && runSegmentation && !isSyntheticCloseUp) {
|
|
264
|
+
try {
|
|
265
|
+
const segInp = (0, _blazeFaceParser.cropAndResizeFaceToFloat32Buffer)(rgbBuf, frameW, frameH, FULL_FRAME_BOX, 257, 257);
|
|
266
|
+
const segOut = segModel.runSync([segInp]);
|
|
267
|
+
const decodedMask = (0, _catParser.decodeDeepLabCatMask)(segOut, segmentationCatClassIndex, 24, 257, 21);
|
|
268
|
+
if (decodedMask) {
|
|
269
|
+
cache.segmentation = decodedMask;
|
|
270
|
+
}
|
|
271
|
+
} catch {
|
|
272
|
+
// Retain cached mask if seg inference fails
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const coatAnalysis = (0, _catParser.analyzeCatCoatAndColors)(rgbBuf, frameW, frameH, activeTargetBox, cache.segmentation);
|
|
276
|
+
cache.coatSwatches = coatAnalysis.swatches;
|
|
277
|
+
cache.coatPattern = coatAnalysis.coatPattern;
|
|
278
|
+
cache.shotOptimalityScore = coatAnalysis.shotOptimalityScore;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Stage 2D: 96-D Personal Cat Re-Identification Descriptor & Enrolled Match
|
|
282
|
+
const descriptorRoi = cache.faceBoundingBox ?? activeTargetBox;
|
|
283
|
+
const descriptor = (0, _catParser.extractCatIdentityDescriptor)(rgbBuf, frameW, frameH, descriptorRoi, cache.landmarks48);
|
|
284
|
+
if (descriptor.length > 0) {
|
|
285
|
+
lastEmbeddingSync.setBlocking(descriptor);
|
|
286
|
+
lastBreedHintSync.setBlocking(cache.topBreeds[0]?.breed);
|
|
287
|
+
}
|
|
288
|
+
const enrolledCats = enrolledCatsSync.getBlocking();
|
|
289
|
+
const simThreshold = similaritySync.getBlocking();
|
|
290
|
+
let matchedIdentity = undefined;
|
|
291
|
+
if (enrolledCats.length > 0 && descriptor.length > 0) {
|
|
292
|
+
let bestCat = null;
|
|
293
|
+
let bestSim = -1;
|
|
294
|
+
for (let i = 0; i < enrolledCats.length; i++) {
|
|
295
|
+
const sim = (0, _blazeFaceParser.cosineSimilarity)(descriptor, enrolledCats[i].embedding);
|
|
296
|
+
if (sim > bestSim) {
|
|
297
|
+
bestSim = sim;
|
|
298
|
+
bestCat = enrolledCats[i];
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (bestCat && bestSim >= simThreshold) {
|
|
302
|
+
matchedIdentity = {
|
|
303
|
+
id: bestCat.id,
|
|
304
|
+
name: bestCat.name,
|
|
305
|
+
similarity: bestSim,
|
|
306
|
+
isRecognized: true
|
|
307
|
+
};
|
|
308
|
+
} else {
|
|
309
|
+
matchedIdentity = {
|
|
310
|
+
id: 'unknown-cat',
|
|
311
|
+
name: 'Unknown Cat',
|
|
312
|
+
similarity: Math.max(0, bestSim),
|
|
313
|
+
isRecognized: false
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
const primaryMeta = {
|
|
318
|
+
isCat: true,
|
|
319
|
+
faceBoundingBox: cache.faceBoundingBox,
|
|
320
|
+
topBreeds: cache.topBreeds.slice(),
|
|
321
|
+
moodMetrics: cache.moodMetrics,
|
|
322
|
+
coatSwatches: cache.coatSwatches,
|
|
323
|
+
coatPattern: cache.coatPattern,
|
|
324
|
+
sceneContextTags,
|
|
325
|
+
segmentation: cache.segmentation,
|
|
326
|
+
shotOptimalityScore: cache.shotOptimalityScore
|
|
327
|
+
};
|
|
328
|
+
const topBreedName = cache.topBreeds[0]?.breed;
|
|
329
|
+
const primaryLabel = matchedIdentity?.isRecognized ? `${matchedIdentity.name}${topBreedName ? ` (${topBreedName})` : ''}` : topBreedName ?? catDetections[0].label;
|
|
330
|
+
catDetections[0] = {
|
|
331
|
+
...catDetections[0],
|
|
332
|
+
label: primaryLabel,
|
|
333
|
+
confidence: cache.topBreeds[0]?.confidence ?? catDetections[0].confidence,
|
|
334
|
+
landmarks: cache.landmarks48,
|
|
335
|
+
identity: matchedIdentity,
|
|
336
|
+
cat: primaryMeta
|
|
337
|
+
};
|
|
338
|
+
if (needs180Correction) {
|
|
339
|
+
for (let i = 0; i < catDetections.length; i++) {
|
|
340
|
+
const b = catDetections[i].boundingBox;
|
|
341
|
+
const fixedLandmarks = catDetections[i].landmarks?.map(lm => ({
|
|
342
|
+
...lm,
|
|
343
|
+
x: Math.max(0, Math.min(1, 1 - lm.x)),
|
|
344
|
+
y: Math.max(0, Math.min(1, 1 - lm.y))
|
|
345
|
+
}));
|
|
346
|
+
const fixedFaceBox = catDetections[i].cat?.faceBoundingBox ? {
|
|
347
|
+
x: Math.max(0, Math.min(1, 1 - catDetections[i].cat.faceBoundingBox.x - catDetections[i].cat.faceBoundingBox.width)),
|
|
348
|
+
y: Math.max(0, Math.min(1, 1 - catDetections[i].cat.faceBoundingBox.y - catDetections[i].cat.faceBoundingBox.height)),
|
|
349
|
+
width: catDetections[i].cat.faceBoundingBox.width,
|
|
350
|
+
height: catDetections[i].cat.faceBoundingBox.height
|
|
351
|
+
} : undefined;
|
|
352
|
+
catDetections[i] = {
|
|
353
|
+
...catDetections[i],
|
|
354
|
+
boundingBox: {
|
|
355
|
+
x: Math.max(0, Math.min(1, 1 - b.x - b.width)),
|
|
356
|
+
y: Math.max(0, Math.min(1, 1 - b.y - b.height)),
|
|
357
|
+
width: b.width,
|
|
358
|
+
height: b.height
|
|
359
|
+
},
|
|
360
|
+
landmarks: fixedLandmarks,
|
|
361
|
+
cat: catDetections[i].cat ? {
|
|
362
|
+
...catDetections[i].cat,
|
|
363
|
+
faceBoundingBox: fixedFaceBox
|
|
364
|
+
} : undefined
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
cacheSync.setBlocking(cache);
|
|
369
|
+
return catDetections;
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
class TFLiteCatAnalyzerImpl {
|
|
373
|
+
name = 'TFLiteCatAnalyzer';
|
|
374
|
+
constructor(config, models) {
|
|
375
|
+
this.id = `tflite-cat-analyzer-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
|
|
376
|
+
this._config = config;
|
|
377
|
+
this._activeDelegate = models.activeDelegate;
|
|
378
|
+
this._status = 'ready';
|
|
379
|
+
this.loadedModels = {
|
|
380
|
+
detector: true,
|
|
381
|
+
breed67: Boolean(models.breed67),
|
|
382
|
+
breed12: Boolean(models.breed12),
|
|
383
|
+
catFaceLocalizer: Boolean(models.catFaceLocalizer),
|
|
384
|
+
catFaceLandmarks: Boolean(models.catFaceLandmarks),
|
|
385
|
+
segmentation: Boolean(models.segmentation)
|
|
386
|
+
};
|
|
387
|
+
this._analysisMode = config.initialMode ?? 'all';
|
|
388
|
+
this._breedEngine = config.initialBreedEngine ?? 'ensemble';
|
|
389
|
+
this._confidenceThreshold = typeof config.confidenceThreshold === 'number' && Number.isFinite(config.confidenceThreshold) ? Math.max(0.1, Math.min(0.95, config.confidenceThreshold)) : 0.42;
|
|
390
|
+
this._similarityThreshold = typeof config.similarityThreshold === 'number' && Number.isFinite(config.similarityThreshold) ? Math.max(0.2, Math.min(0.99, config.similarityThreshold)) : 0.72;
|
|
391
|
+
this._closeUpFallback = config.closeUpFallback !== false;
|
|
392
|
+
const fps = config.targetFps ?? 15;
|
|
393
|
+
const minFrameIntervalMs = fps > 0 ? 1000 / fps : 0;
|
|
394
|
+
this._disposedSync = (0, _workletFrameHelper.createWorkletSyncRef)(false, true);
|
|
395
|
+
this._readySync = (0, _workletFrameHelper.createWorkletSyncRef)(true, true);
|
|
396
|
+
this._detectorModelSync = (0, _workletFrameHelper.createWorkletSyncRef)(models.detector, false);
|
|
397
|
+
this._breed67ModelSync = (0, _workletFrameHelper.createWorkletSyncRef)(models.breed67, false);
|
|
398
|
+
this._breed12ModelSync = (0, _workletFrameHelper.createWorkletSyncRef)(models.breed12, false);
|
|
399
|
+
this._catFaceLocalizerSync = (0, _workletFrameHelper.createWorkletSyncRef)(models.catFaceLocalizer, false);
|
|
400
|
+
this._catFaceLandmarksSync = (0, _workletFrameHelper.createWorkletSyncRef)(models.catFaceLandmarks, false);
|
|
401
|
+
this._segmentationModelSync = (0, _workletFrameHelper.createWorkletSyncRef)(models.segmentation, false);
|
|
402
|
+
this._modeSync = (0, _workletFrameHelper.createWorkletSyncRef)(this._analysisMode, false);
|
|
403
|
+
this._breedEngineSync = (0, _workletFrameHelper.createWorkletSyncRef)(this._breedEngine, false);
|
|
404
|
+
this._confidenceSync = (0, _workletFrameHelper.createWorkletSyncRef)(this._confidenceThreshold, true);
|
|
405
|
+
this._similaritySync = (0, _workletFrameHelper.createWorkletSyncRef)(this._similarityThreshold, true);
|
|
406
|
+
this._closeUpFallbackSync = (0, _workletFrameHelper.createWorkletSyncRef)(this._closeUpFallback, true);
|
|
407
|
+
this._lastFrameTimeSync = (0, _workletFrameHelper.createWorkletSyncRef)(0, true);
|
|
408
|
+
this._tickCounterSync = (0, _workletFrameHelper.createWorkletSyncRef)(0, true);
|
|
409
|
+
this._missCounterSync = (0, _workletFrameHelper.createWorkletSyncRef)(0, true);
|
|
410
|
+
this.wasThrottledSync = (0, _workletFrameHelper.createWorkletSyncRef)(false, true);
|
|
411
|
+
this._enrolledCatsSync = (0, _workletFrameHelper.createWorkletSyncRef)(Array.isArray(config.initialCats) ? config.initialCats.slice() : [], false);
|
|
412
|
+
this._lastEmbeddingSync = (0, _workletFrameHelper.createWorkletSyncRef)(null, false);
|
|
413
|
+
this._lastBreedHintSync = (0, _workletFrameHelper.createWorkletSyncRef)(undefined, false);
|
|
414
|
+
this._cacheSync = (0, _workletFrameHelper.createWorkletSyncRef)({
|
|
415
|
+
topBreeds: [],
|
|
416
|
+
emaMap: {}
|
|
417
|
+
}, false);
|
|
418
|
+
this.processFrameWorklet = createCatWorkletProcessor({
|
|
419
|
+
disposedSync: this._disposedSync,
|
|
420
|
+
readySync: this._readySync,
|
|
421
|
+
detectorModelSync: this._detectorModelSync,
|
|
422
|
+
breed67ModelSync: this._breed67ModelSync,
|
|
423
|
+
breed12ModelSync: this._breed12ModelSync,
|
|
424
|
+
catFaceLocalizerSync: this._catFaceLocalizerSync,
|
|
425
|
+
catFaceLandmarksSync: this._catFaceLandmarksSync,
|
|
426
|
+
segmentationModelSync: this._segmentationModelSync,
|
|
427
|
+
modeSync: this._modeSync,
|
|
428
|
+
breedEngineSync: this._breedEngineSync,
|
|
429
|
+
confidenceSync: this._confidenceSync,
|
|
430
|
+
similaritySync: this._similaritySync,
|
|
431
|
+
closeUpFallbackSync: this._closeUpFallbackSync,
|
|
432
|
+
lastFrameTimeSync: this._lastFrameTimeSync,
|
|
433
|
+
tickCounterSync: this._tickCounterSync,
|
|
434
|
+
missCounterSync: this._missCounterSync,
|
|
435
|
+
wasThrottledSync: this.wasThrottledSync,
|
|
436
|
+
enrolledCatsSync: this._enrolledCatsSync,
|
|
437
|
+
lastEmbeddingSync: this._lastEmbeddingSync,
|
|
438
|
+
lastBreedHintSync: this._lastBreedHintSync,
|
|
439
|
+
cacheSync: this._cacheSync,
|
|
440
|
+
minFrameIntervalMs,
|
|
441
|
+
detectorInputWidth: config.detectorInputWidth ?? 300,
|
|
442
|
+
detectorInputHeight: config.detectorInputHeight ?? 300,
|
|
443
|
+
detectorLabels: config.detectorLabels,
|
|
444
|
+
detectorLabelOffset: config.detectorLabelOffset ?? 1,
|
|
445
|
+
breed67Labels: config.breed67Labels ?? [],
|
|
446
|
+
breed12Labels: config.breed12Labels ?? [],
|
|
447
|
+
segmentationCatClassIndex: config.segmentationCatClassIndex ?? 8,
|
|
448
|
+
frameConverter: (0, _workletFrameHelper.getOptionalFrameConverter)(),
|
|
449
|
+
resizePlugin: (0, _workletFrameHelper.getOptionalResizePlugin)()
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
get status() {
|
|
453
|
+
return this._status;
|
|
454
|
+
}
|
|
455
|
+
get activeDelegate() {
|
|
456
|
+
return this._activeDelegate;
|
|
457
|
+
}
|
|
458
|
+
get analysisMode() {
|
|
459
|
+
return this._analysisMode;
|
|
460
|
+
}
|
|
461
|
+
get breedEngine() {
|
|
462
|
+
return this._breedEngine;
|
|
463
|
+
}
|
|
464
|
+
get confidenceThreshold() {
|
|
465
|
+
return this._confidenceThreshold;
|
|
466
|
+
}
|
|
467
|
+
get similarityThreshold() {
|
|
468
|
+
return this._similarityThreshold;
|
|
469
|
+
}
|
|
470
|
+
get closeUpFallback() {
|
|
471
|
+
return this._closeUpFallback;
|
|
472
|
+
}
|
|
473
|
+
get targetFps() {
|
|
474
|
+
return this._config.targetFps ?? 15;
|
|
475
|
+
}
|
|
476
|
+
setAnalysisMode(mode) {
|
|
477
|
+
this._analysisMode = mode;
|
|
478
|
+
this._modeSync.setBlocking(mode);
|
|
479
|
+
}
|
|
480
|
+
setBreedEngine(engine) {
|
|
481
|
+
this._breedEngine = engine;
|
|
482
|
+
this._breedEngineSync.setBlocking(engine);
|
|
483
|
+
}
|
|
484
|
+
setConfidenceThreshold(threshold) {
|
|
485
|
+
if (Number.isFinite(threshold)) {
|
|
486
|
+
this._confidenceThreshold = Math.max(0.1, Math.min(0.95, threshold));
|
|
487
|
+
this._confidenceSync.setBlocking(this._confidenceThreshold);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
setSimilarityThreshold(threshold) {
|
|
491
|
+
if (Number.isFinite(threshold)) {
|
|
492
|
+
this._similarityThreshold = Math.max(0.2, Math.min(0.99, threshold));
|
|
493
|
+
this._similaritySync.setBlocking(this._similarityThreshold);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
setCloseUpFallback(enabled) {
|
|
497
|
+
this._closeUpFallback = Boolean(enabled);
|
|
498
|
+
this._closeUpFallbackSync.setBlocking(this._closeUpFallback);
|
|
499
|
+
}
|
|
500
|
+
enrollLastDetectedCat(name, breedHint) {
|
|
501
|
+
const lastEmb = this._lastEmbeddingSync.getBlocking();
|
|
502
|
+
if (!lastEmb || lastEmb.length === 0) {
|
|
503
|
+
return null;
|
|
504
|
+
}
|
|
505
|
+
const hint = breedHint ?? this._lastBreedHintSync.getBlocking();
|
|
506
|
+
return this.enrollCat(name, lastEmb, hint);
|
|
507
|
+
}
|
|
508
|
+
enrollCat(name, embedding, breedHint) {
|
|
509
|
+
const cleanName = name.trim() || `Cat ${this._enrolledCatsSync.getBlocking().length + 1}`;
|
|
510
|
+
const arr = Array.from(embedding);
|
|
511
|
+
const profile = {
|
|
512
|
+
id: `cat-${Date.now()}-${Math.floor(Math.random() * 10000)}`,
|
|
513
|
+
name: cleanName,
|
|
514
|
+
breedHint,
|
|
515
|
+
embedding: arr,
|
|
516
|
+
createdAt: Date.now()
|
|
517
|
+
};
|
|
518
|
+
const nextList = [...this._enrolledCatsSync.getBlocking(), profile];
|
|
519
|
+
this._enrolledCatsSync.setBlocking(nextList);
|
|
520
|
+
return profile;
|
|
521
|
+
}
|
|
522
|
+
removeEnrolledCat(id) {
|
|
523
|
+
const prev = this._enrolledCatsSync.getBlocking();
|
|
524
|
+
const next = prev.filter(c => c.id !== id);
|
|
525
|
+
if (next.length === prev.length) return false;
|
|
526
|
+
this._enrolledCatsSync.setBlocking(next);
|
|
527
|
+
return true;
|
|
528
|
+
}
|
|
529
|
+
clearEnrolledCats() {
|
|
530
|
+
this._enrolledCatsSync.setBlocking([]);
|
|
531
|
+
}
|
|
532
|
+
getEnrolledCats() {
|
|
533
|
+
return this._enrolledCatsSync.getBlocking().slice();
|
|
534
|
+
}
|
|
535
|
+
hasRecentCatEmbedding() {
|
|
536
|
+
const emb = this._lastEmbeddingSync.getBlocking();
|
|
537
|
+
return Boolean(emb && emb.length > 0);
|
|
538
|
+
}
|
|
539
|
+
processFrame(frame) {
|
|
540
|
+
try {
|
|
541
|
+
return this.processFrameWorklet(frame);
|
|
542
|
+
} catch (err) {
|
|
543
|
+
throw new _rnCameraAi.InferenceError(err instanceof Error ? err.message : 'TFLite cat analyzer inference failed', 'INFERENCE_ERROR', err);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
async initialize() {
|
|
547
|
+
if (this._disposedSync.getBlocking()) {
|
|
548
|
+
const loaded = await loadCatModels(this._config);
|
|
549
|
+
this._detectorModelSync.setBlocking(loaded.detector);
|
|
550
|
+
this._breed67ModelSync.setBlocking(loaded.breed67);
|
|
551
|
+
this._breed12ModelSync.setBlocking(loaded.breed12);
|
|
552
|
+
this._catFaceLocalizerSync.setBlocking(loaded.catFaceLocalizer);
|
|
553
|
+
this._catFaceLandmarksSync.setBlocking(loaded.catFaceLandmarks);
|
|
554
|
+
this._segmentationModelSync.setBlocking(loaded.segmentation);
|
|
555
|
+
this._activeDelegate = loaded.activeDelegate;
|
|
556
|
+
this._disposedSync.setBlocking(false);
|
|
557
|
+
}
|
|
558
|
+
this._status = 'ready';
|
|
559
|
+
this._readySync.setBlocking(true);
|
|
560
|
+
this._lastFrameTimeSync.setBlocking(0);
|
|
561
|
+
this.wasThrottledSync.setBlocking(false);
|
|
562
|
+
}
|
|
563
|
+
dispose() {
|
|
564
|
+
this._disposedSync.setBlocking(true);
|
|
565
|
+
this._readySync.setBlocking(false);
|
|
566
|
+
this._status = 'idle';
|
|
567
|
+
this._lastFrameTimeSync.setBlocking(0);
|
|
568
|
+
this.wasThrottledSync.setBlocking(false);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
async function loadOptionalModel(source, opts) {
|
|
572
|
+
if (source === undefined || source === null) {
|
|
573
|
+
return null;
|
|
574
|
+
}
|
|
575
|
+
try {
|
|
576
|
+
const res = await (0, _modelLoader.loadModelWithFallback)(source, opts);
|
|
577
|
+
return res.model;
|
|
578
|
+
} catch {
|
|
579
|
+
return null;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
async function loadCatModels(config) {
|
|
583
|
+
const loaderOpts = {
|
|
584
|
+
useGpu: config.useGpu,
|
|
585
|
+
platform: config.platform,
|
|
586
|
+
onDelegateFallback: config.onDelegateFallback,
|
|
587
|
+
loadModel: config.loadModel
|
|
588
|
+
};
|
|
589
|
+
const detectorLoaded = await (0, _modelLoader.loadModelWithFallback)(config.detectorModel, loaderOpts);
|
|
590
|
+
const [breed67, breed12, catFaceLocalizer, catFaceLandmarks, segmentation] = await Promise.all([loadOptionalModel(config.breed67Model, loaderOpts), loadOptionalModel(config.breed12Model, loaderOpts), loadOptionalModel(config.catFaceLocalizerModel, loaderOpts), loadOptionalModel(config.catFaceLandmarksModel, loaderOpts), loadOptionalModel(config.segmentationModel, loaderOpts)]);
|
|
591
|
+
return {
|
|
592
|
+
detector: detectorLoaded.model,
|
|
593
|
+
activeDelegate: detectorLoaded.activeDelegate,
|
|
594
|
+
breed67,
|
|
595
|
+
breed12,
|
|
596
|
+
catFaceLocalizer,
|
|
597
|
+
catFaceLandmarks,
|
|
598
|
+
segmentation
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Creates and initializes a Multi-Model On-Device Feline Vision CameraProcessor.
|
|
604
|
+
*/
|
|
605
|
+
async function createTFLiteCatAnalyzer(config) {
|
|
606
|
+
const models = await loadCatModels(config);
|
|
607
|
+
return new TFLiteCatAnalyzerImpl(config, models);
|
|
608
|
+
}
|
|
609
|
+
//# sourceMappingURL=TFLiteCatAnalyzer.js.map
|