@camstack/addon-vision 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 (109) hide show
  1. package/dist/addons/animal-classifier/index.d.mts +25 -0
  2. package/dist/addons/animal-classifier/index.d.ts +25 -0
  3. package/dist/addons/animal-classifier/index.js +652 -0
  4. package/dist/addons/animal-classifier/index.js.map +1 -0
  5. package/dist/addons/animal-classifier/index.mjs +10 -0
  6. package/dist/addons/animal-classifier/index.mjs.map +1 -0
  7. package/dist/addons/audio-classification/index.d.mts +31 -0
  8. package/dist/addons/audio-classification/index.d.ts +31 -0
  9. package/dist/addons/audio-classification/index.js +572 -0
  10. package/dist/addons/audio-classification/index.js.map +1 -0
  11. package/dist/addons/audio-classification/index.mjs +8 -0
  12. package/dist/addons/audio-classification/index.mjs.map +1 -0
  13. package/dist/addons/bird-global-classifier/index.d.mts +26 -0
  14. package/dist/addons/bird-global-classifier/index.d.ts +26 -0
  15. package/dist/addons/bird-global-classifier/index.js +658 -0
  16. package/dist/addons/bird-global-classifier/index.js.map +1 -0
  17. package/dist/addons/bird-global-classifier/index.mjs +10 -0
  18. package/dist/addons/bird-global-classifier/index.mjs.map +1 -0
  19. package/dist/addons/bird-nabirds-classifier/index.d.mts +28 -0
  20. package/dist/addons/bird-nabirds-classifier/index.d.ts +28 -0
  21. package/dist/addons/bird-nabirds-classifier/index.js +700 -0
  22. package/dist/addons/bird-nabirds-classifier/index.js.map +1 -0
  23. package/dist/addons/bird-nabirds-classifier/index.mjs +10 -0
  24. package/dist/addons/bird-nabirds-classifier/index.mjs.map +1 -0
  25. package/dist/addons/camera-native-detection/index.d.mts +32 -0
  26. package/dist/addons/camera-native-detection/index.d.ts +32 -0
  27. package/dist/addons/camera-native-detection/index.js +99 -0
  28. package/dist/addons/camera-native-detection/index.js.map +1 -0
  29. package/dist/addons/camera-native-detection/index.mjs +7 -0
  30. package/dist/addons/camera-native-detection/index.mjs.map +1 -0
  31. package/dist/addons/face-detection/index.d.mts +24 -0
  32. package/dist/addons/face-detection/index.d.ts +24 -0
  33. package/dist/addons/face-detection/index.js +720 -0
  34. package/dist/addons/face-detection/index.js.map +1 -0
  35. package/dist/addons/face-detection/index.mjs +10 -0
  36. package/dist/addons/face-detection/index.mjs.map +1 -0
  37. package/dist/addons/face-recognition/index.d.mts +24 -0
  38. package/dist/addons/face-recognition/index.d.ts +24 -0
  39. package/dist/addons/face-recognition/index.js +603 -0
  40. package/dist/addons/face-recognition/index.js.map +1 -0
  41. package/dist/addons/face-recognition/index.mjs +9 -0
  42. package/dist/addons/face-recognition/index.mjs.map +1 -0
  43. package/dist/addons/motion-detection/index.d.mts +26 -0
  44. package/dist/addons/motion-detection/index.d.ts +26 -0
  45. package/dist/addons/motion-detection/index.js +273 -0
  46. package/dist/addons/motion-detection/index.js.map +1 -0
  47. package/dist/addons/motion-detection/index.mjs +8 -0
  48. package/dist/addons/motion-detection/index.mjs.map +1 -0
  49. package/dist/addons/object-detection/index.d.mts +26 -0
  50. package/dist/addons/object-detection/index.d.ts +26 -0
  51. package/dist/addons/object-detection/index.js +1214 -0
  52. package/dist/addons/object-detection/index.js.map +1 -0
  53. package/dist/addons/object-detection/index.mjs +10 -0
  54. package/dist/addons/object-detection/index.mjs.map +1 -0
  55. package/dist/addons/plate-detection/index.d.mts +25 -0
  56. package/dist/addons/plate-detection/index.d.ts +25 -0
  57. package/dist/addons/plate-detection/index.js +646 -0
  58. package/dist/addons/plate-detection/index.js.map +1 -0
  59. package/dist/addons/plate-detection/index.mjs +10 -0
  60. package/dist/addons/plate-detection/index.mjs.map +1 -0
  61. package/dist/addons/plate-recognition/index.d.mts +25 -0
  62. package/dist/addons/plate-recognition/index.d.ts +25 -0
  63. package/dist/addons/plate-recognition/index.js +648 -0
  64. package/dist/addons/plate-recognition/index.js.map +1 -0
  65. package/dist/addons/plate-recognition/index.mjs +9 -0
  66. package/dist/addons/plate-recognition/index.mjs.map +1 -0
  67. package/dist/chunk-3MQFUDRU.mjs +260 -0
  68. package/dist/chunk-3MQFUDRU.mjs.map +1 -0
  69. package/dist/chunk-5AIQSN32.mjs +227 -0
  70. package/dist/chunk-5AIQSN32.mjs.map +1 -0
  71. package/dist/chunk-5JJZGKL7.mjs +186 -0
  72. package/dist/chunk-5JJZGKL7.mjs.map +1 -0
  73. package/dist/chunk-6OR5TE7A.mjs +101 -0
  74. package/dist/chunk-6OR5TE7A.mjs.map +1 -0
  75. package/dist/chunk-AYBFB7ID.mjs +763 -0
  76. package/dist/chunk-AYBFB7ID.mjs.map +1 -0
  77. package/dist/chunk-B3R66MPF.mjs +219 -0
  78. package/dist/chunk-B3R66MPF.mjs.map +1 -0
  79. package/dist/chunk-DTOAB2CE.mjs +79 -0
  80. package/dist/chunk-DTOAB2CE.mjs.map +1 -0
  81. package/dist/chunk-ISOIDU4U.mjs +54 -0
  82. package/dist/chunk-ISOIDU4U.mjs.map +1 -0
  83. package/dist/chunk-J4WRYHHY.mjs +212 -0
  84. package/dist/chunk-J4WRYHHY.mjs.map +1 -0
  85. package/dist/chunk-KUO2BVFY.mjs +90 -0
  86. package/dist/chunk-KUO2BVFY.mjs.map +1 -0
  87. package/dist/chunk-LPI42WL6.mjs +324 -0
  88. package/dist/chunk-LPI42WL6.mjs.map +1 -0
  89. package/dist/chunk-MEVASN3P.mjs +305 -0
  90. package/dist/chunk-MEVASN3P.mjs.map +1 -0
  91. package/dist/chunk-PDSHDDPV.mjs +255 -0
  92. package/dist/chunk-PDSHDDPV.mjs.map +1 -0
  93. package/dist/chunk-Q3SQOYG6.mjs +218 -0
  94. package/dist/chunk-Q3SQOYG6.mjs.map +1 -0
  95. package/dist/chunk-QIMDG34B.mjs +229 -0
  96. package/dist/chunk-QIMDG34B.mjs.map +1 -0
  97. package/dist/index.d.mts +171 -0
  98. package/dist/index.d.ts +171 -0
  99. package/dist/index.js +3463 -0
  100. package/dist/index.js.map +1 -0
  101. package/dist/index.mjs +111 -0
  102. package/dist/index.mjs.map +1 -0
  103. package/package.json +49 -0
  104. package/python/__pycache__/coreml_inference.cpython-313.pyc +0 -0
  105. package/python/__pycache__/openvino_inference.cpython-313.pyc +0 -0
  106. package/python/__pycache__/pytorch_inference.cpython-313.pyc +0 -0
  107. package/python/coreml_inference.py +319 -0
  108. package/python/openvino_inference.py +247 -0
  109. package/python/pytorch_inference.py +255 -0
@@ -0,0 +1,603 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/addons/face-recognition/index.ts
31
+ var face_recognition_exports = {};
32
+ __export(face_recognition_exports, {
33
+ default: () => FaceRecognitionAddon
34
+ });
35
+ module.exports = __toCommonJS(face_recognition_exports);
36
+
37
+ // src/catalogs/face-recognition-models.ts
38
+ var import_types = require("@camstack/types");
39
+ var HF_REPO = "camstack/camstack-models";
40
+ var FACE_EMBEDDING_LABELS = [
41
+ { id: "embedding", name: "Face Embedding" }
42
+ ];
43
+ var FACE_RECOGNITION_MODELS = [
44
+ {
45
+ id: "arcface-r100",
46
+ name: "ArcFace R100",
47
+ description: "ArcFace ResNet-100 \u2014 high-accuracy face recognition embeddings",
48
+ inputSize: { width: 112, height: 112 },
49
+ inputLayout: "nhwc",
50
+ labels: FACE_EMBEDDING_LABELS,
51
+ formats: {
52
+ onnx: {
53
+ url: (0, import_types.hfModelUrl)(HF_REPO, "faceRecognition/arcface/onnx/camstack-arcface-arcface.onnx"),
54
+ sizeMB: 130
55
+ },
56
+ coreml: {
57
+ url: (0, import_types.hfModelUrl)(HF_REPO, "faceRecognition/arcface/coreml/camstack-arcface-r100.mlpackage"),
58
+ sizeMB: 65
59
+ },
60
+ openvino: {
61
+ url: (0, import_types.hfModelUrl)(HF_REPO, "faceRecognition/arcface/openvino/camstack-arcface-r100.xml"),
62
+ sizeMB: 65
63
+ }
64
+ }
65
+ }
66
+ ];
67
+
68
+ // src/shared/image-utils.ts
69
+ var import_sharp = __toESM(require("sharp"));
70
+ async function cropRegion(jpeg, roi) {
71
+ return (0, import_sharp.default)(jpeg).extract({
72
+ left: Math.round(roi.x),
73
+ top: Math.round(roi.y),
74
+ width: Math.round(roi.w),
75
+ height: Math.round(roi.h)
76
+ }).jpeg().toBuffer();
77
+ }
78
+ async function resizeAndNormalize(jpeg, targetWidth, targetHeight, normalization, layout) {
79
+ const { data } = await (0, import_sharp.default)(jpeg).resize(targetWidth, targetHeight).removeAlpha().raw().toBuffer({ resolveWithObject: true });
80
+ const numPixels = targetWidth * targetHeight;
81
+ const float32 = new Float32Array(3 * numPixels);
82
+ const mean = [0.485, 0.456, 0.406];
83
+ const std = [0.229, 0.224, 0.225];
84
+ if (layout === "nchw") {
85
+ for (let i = 0; i < numPixels; i++) {
86
+ const srcBase = i * 3;
87
+ for (let c = 0; c < 3; c++) {
88
+ const raw = data[srcBase + c] / 255;
89
+ let val;
90
+ if (normalization === "zero-one") {
91
+ val = raw;
92
+ } else if (normalization === "imagenet") {
93
+ val = (raw - mean[c]) / std[c];
94
+ } else {
95
+ val = data[srcBase + c];
96
+ }
97
+ float32[c * numPixels + i] = val;
98
+ }
99
+ }
100
+ } else {
101
+ for (let i = 0; i < numPixels; i++) {
102
+ const srcBase = i * 3;
103
+ for (let c = 0; c < 3; c++) {
104
+ const raw = data[srcBase + c] / 255;
105
+ let val;
106
+ if (normalization === "zero-one") {
107
+ val = raw;
108
+ } else if (normalization === "imagenet") {
109
+ val = (raw - mean[c]) / std[c];
110
+ } else {
111
+ val = data[srcBase + c];
112
+ }
113
+ float32[i * 3 + c] = val;
114
+ }
115
+ }
116
+ }
117
+ return float32;
118
+ }
119
+
120
+ // src/shared/postprocess/arcface.ts
121
+ function l2Normalize(vec) {
122
+ let sumSq = 0;
123
+ for (let i = 0; i < vec.length; i++) {
124
+ sumSq += vec[i] * vec[i];
125
+ }
126
+ const norm = Math.sqrt(sumSq);
127
+ if (norm === 0) return new Float32Array(vec.length);
128
+ const out = new Float32Array(vec.length);
129
+ for (let i = 0; i < vec.length; i++) {
130
+ out[i] = vec[i] / norm;
131
+ }
132
+ return out;
133
+ }
134
+
135
+ // src/shared/engine-resolver.ts
136
+ var fs = __toESM(require("fs"));
137
+ var path2 = __toESM(require("path"));
138
+
139
+ // src/shared/node-engine.ts
140
+ var path = __toESM(require("path"));
141
+ var BACKEND_TO_PROVIDER = {
142
+ cpu: "cpu",
143
+ coreml: "coreml",
144
+ cuda: "cuda",
145
+ tensorrt: "tensorrt",
146
+ dml: "dml"
147
+ };
148
+ var BACKEND_TO_DEVICE = {
149
+ cpu: "cpu",
150
+ coreml: "gpu-mps",
151
+ cuda: "gpu-cuda",
152
+ tensorrt: "tensorrt"
153
+ };
154
+ var NodeInferenceEngine = class {
155
+ constructor(modelPath, backend) {
156
+ this.modelPath = modelPath;
157
+ this.backend = backend;
158
+ this.device = BACKEND_TO_DEVICE[backend] ?? "cpu";
159
+ }
160
+ runtime = "onnx";
161
+ device;
162
+ session = null;
163
+ async initialize() {
164
+ const ort = await import("onnxruntime-node");
165
+ const provider = BACKEND_TO_PROVIDER[this.backend] ?? "cpu";
166
+ const absModelPath = path.isAbsolute(this.modelPath) ? this.modelPath : path.resolve(process.cwd(), this.modelPath);
167
+ const sessionOptions = {
168
+ executionProviders: [provider]
169
+ };
170
+ this.session = await ort.InferenceSession.create(absModelPath, sessionOptions);
171
+ }
172
+ async run(input, inputShape) {
173
+ if (!this.session) {
174
+ throw new Error("NodeInferenceEngine: not initialized \u2014 call initialize() first");
175
+ }
176
+ const ort = await import("onnxruntime-node");
177
+ const sess = this.session;
178
+ const inputName = sess.inputNames[0];
179
+ const tensor = new ort.Tensor("float32", input, [...inputShape]);
180
+ const feeds = { [inputName]: tensor };
181
+ const results = await sess.run(feeds);
182
+ const outputName = sess.outputNames[0];
183
+ const outputTensor = results[outputName];
184
+ return outputTensor.data;
185
+ }
186
+ async runMultiOutput(input, inputShape) {
187
+ if (!this.session) {
188
+ throw new Error("NodeInferenceEngine: not initialized \u2014 call initialize() first");
189
+ }
190
+ const ort = await import("onnxruntime-node");
191
+ const sess = this.session;
192
+ const inputName = sess.inputNames[0];
193
+ const tensor = new ort.Tensor("float32", input, [...inputShape]);
194
+ const feeds = { [inputName]: tensor };
195
+ const results = await sess.run(feeds);
196
+ const out = {};
197
+ for (const name of sess.outputNames) {
198
+ out[name] = results[name].data;
199
+ }
200
+ return out;
201
+ }
202
+ async dispose() {
203
+ this.session = null;
204
+ }
205
+ };
206
+
207
+ // src/shared/python-engine.ts
208
+ var import_node_child_process = require("child_process");
209
+ var PythonInferenceEngine = class {
210
+ constructor(pythonPath, scriptPath, runtime, modelPath, extraArgs = []) {
211
+ this.pythonPath = pythonPath;
212
+ this.scriptPath = scriptPath;
213
+ this.modelPath = modelPath;
214
+ this.extraArgs = extraArgs;
215
+ this.runtime = runtime;
216
+ const runtimeDeviceMap = {
217
+ onnx: "cpu",
218
+ coreml: "gpu-mps",
219
+ pytorch: "cpu",
220
+ openvino: "cpu",
221
+ tflite: "cpu"
222
+ };
223
+ this.device = runtimeDeviceMap[runtime];
224
+ }
225
+ runtime;
226
+ device;
227
+ process = null;
228
+ receiveBuffer = Buffer.alloc(0);
229
+ pendingResolve = null;
230
+ pendingReject = null;
231
+ async initialize() {
232
+ const args = [this.scriptPath, this.modelPath, ...this.extraArgs];
233
+ this.process = (0, import_node_child_process.spawn)(this.pythonPath, args, {
234
+ stdio: ["pipe", "pipe", "pipe"]
235
+ });
236
+ if (!this.process.stdout || !this.process.stdin) {
237
+ throw new Error("PythonInferenceEngine: failed to create process pipes");
238
+ }
239
+ this.process.stderr?.on("data", (chunk) => {
240
+ process.stderr.write(`[python-engine] ${chunk.toString()}`);
241
+ });
242
+ this.process.on("error", (err) => {
243
+ this.pendingReject?.(err);
244
+ this.pendingReject = null;
245
+ this.pendingResolve = null;
246
+ });
247
+ this.process.on("exit", (code) => {
248
+ if (code !== 0) {
249
+ const err = new Error(`PythonInferenceEngine: process exited with code ${code}`);
250
+ this.pendingReject?.(err);
251
+ this.pendingReject = null;
252
+ this.pendingResolve = null;
253
+ }
254
+ });
255
+ this.process.stdout.on("data", (chunk) => {
256
+ this.receiveBuffer = Buffer.concat([this.receiveBuffer, chunk]);
257
+ this._tryReceive();
258
+ });
259
+ await new Promise((resolve2, reject) => {
260
+ const timeout = setTimeout(() => resolve2(), 2e3);
261
+ this.process?.on("error", (err) => {
262
+ clearTimeout(timeout);
263
+ reject(err);
264
+ });
265
+ this.process?.on("exit", (code) => {
266
+ clearTimeout(timeout);
267
+ if (code !== 0) {
268
+ reject(new Error(`PythonInferenceEngine: process exited early with code ${code}`));
269
+ }
270
+ });
271
+ });
272
+ }
273
+ _tryReceive() {
274
+ if (this.receiveBuffer.length < 4) return;
275
+ const length = this.receiveBuffer.readUInt32LE(0);
276
+ if (this.receiveBuffer.length < 4 + length) return;
277
+ const jsonBytes = this.receiveBuffer.subarray(4, 4 + length);
278
+ this.receiveBuffer = this.receiveBuffer.subarray(4 + length);
279
+ const resolve2 = this.pendingResolve;
280
+ const reject = this.pendingReject;
281
+ this.pendingResolve = null;
282
+ this.pendingReject = null;
283
+ if (!resolve2) return;
284
+ try {
285
+ const parsed = JSON.parse(jsonBytes.toString("utf8"));
286
+ resolve2(parsed);
287
+ } catch (err) {
288
+ reject?.(err instanceof Error ? err : new Error(String(err)));
289
+ }
290
+ }
291
+ /** Send JPEG buffer, receive JSON detection results */
292
+ async runJpeg(jpeg) {
293
+ if (!this.process?.stdin) {
294
+ throw new Error("PythonInferenceEngine: process not initialized");
295
+ }
296
+ return new Promise((resolve2, reject) => {
297
+ this.pendingResolve = resolve2;
298
+ this.pendingReject = reject;
299
+ const lengthBuf = Buffer.allocUnsafe(4);
300
+ lengthBuf.writeUInt32LE(jpeg.length, 0);
301
+ this.process.stdin.write(Buffer.concat([lengthBuf, jpeg]));
302
+ });
303
+ }
304
+ /** IInferenceEngine.run — wraps runJpeg for compatibility */
305
+ async run(_input, _inputShape) {
306
+ throw new Error(
307
+ "PythonInferenceEngine: use runJpeg() directly \u2014 this engine operates on JPEG input"
308
+ );
309
+ }
310
+ /** IInferenceEngine.runMultiOutput — not supported by Python engine (operates on JPEG input) */
311
+ async runMultiOutput(_input, _inputShape) {
312
+ throw new Error(
313
+ "PythonInferenceEngine: runMultiOutput() is not supported \u2014 this engine operates on JPEG input"
314
+ );
315
+ }
316
+ async dispose() {
317
+ if (this.process) {
318
+ this.process.stdin?.end();
319
+ this.process.kill("SIGTERM");
320
+ this.process = null;
321
+ }
322
+ }
323
+ };
324
+
325
+ // src/shared/engine-resolver.ts
326
+ var AUTO_BACKEND_PRIORITY = ["coreml", "cuda", "tensorrt", "cpu"];
327
+ var BACKEND_TO_FORMAT = {
328
+ cpu: "onnx",
329
+ coreml: "coreml",
330
+ cuda: "onnx",
331
+ tensorrt: "onnx"
332
+ };
333
+ var RUNTIME_TO_FORMAT = {
334
+ onnx: "onnx",
335
+ coreml: "coreml",
336
+ openvino: "openvino",
337
+ tflite: "tflite",
338
+ pytorch: "pt"
339
+ };
340
+ function modelFilePath(modelsDir, modelEntry, format) {
341
+ const formatEntry = modelEntry.formats[format];
342
+ if (!formatEntry) {
343
+ throw new Error(`Model ${modelEntry.id} has no ${format} format`);
344
+ }
345
+ const urlParts = formatEntry.url.split("/");
346
+ const filename = urlParts[urlParts.length - 1] ?? `${modelEntry.id}.${format}`;
347
+ return path2.join(modelsDir, filename);
348
+ }
349
+ function modelExists(filePath) {
350
+ try {
351
+ return fs.existsSync(filePath);
352
+ } catch {
353
+ return false;
354
+ }
355
+ }
356
+ async function resolveEngine(options) {
357
+ const { runtime, backend, modelEntry, modelsDir, downloadModel } = options;
358
+ let selectedFormat;
359
+ let selectedBackend;
360
+ if (runtime === "auto") {
361
+ const available = await probeOnnxBackends();
362
+ let chosen = null;
363
+ for (const b of AUTO_BACKEND_PRIORITY) {
364
+ if (!available.includes(b)) continue;
365
+ const fmt = BACKEND_TO_FORMAT[b];
366
+ if (!fmt) continue;
367
+ if (!modelEntry.formats[fmt]) continue;
368
+ chosen = { backend: b, format: fmt };
369
+ break;
370
+ }
371
+ if (!chosen) {
372
+ throw new Error(
373
+ `resolveEngine: no compatible backend found for model ${modelEntry.id}. Available backends: ${available.join(", ")}`
374
+ );
375
+ }
376
+ selectedFormat = chosen.format;
377
+ selectedBackend = chosen.backend;
378
+ } else {
379
+ const fmt = RUNTIME_TO_FORMAT[runtime];
380
+ if (!fmt) {
381
+ throw new Error(`resolveEngine: unsupported runtime "${runtime}"`);
382
+ }
383
+ if (!modelEntry.formats[fmt]) {
384
+ throw new Error(
385
+ `resolveEngine: model ${modelEntry.id} has no ${fmt} format for runtime ${runtime}`
386
+ );
387
+ }
388
+ selectedFormat = fmt;
389
+ selectedBackend = runtime === "onnx" ? backend || "cpu" : runtime;
390
+ }
391
+ let modelPath = modelFilePath(modelsDir, modelEntry, selectedFormat);
392
+ if (!modelExists(modelPath)) {
393
+ if (downloadModel) {
394
+ const formatEntry = modelEntry.formats[selectedFormat];
395
+ modelPath = await downloadModel(formatEntry.url, modelsDir);
396
+ } else {
397
+ throw new Error(
398
+ `resolveEngine: model file not found at ${modelPath} and no downloadModel function provided`
399
+ );
400
+ }
401
+ }
402
+ if (selectedFormat === "onnx" || selectedFormat === "coreml") {
403
+ const engine = new NodeInferenceEngine(modelPath, selectedBackend);
404
+ await engine.initialize();
405
+ return { engine, format: selectedFormat, modelPath };
406
+ }
407
+ const { pythonPath } = options;
408
+ const PYTHON_SCRIPT_MAP = {
409
+ coreml: "coreml_inference.py",
410
+ pytorch: "pytorch_inference.py",
411
+ openvino: "openvino_inference.py"
412
+ };
413
+ const effectiveRuntime = runtime === "auto" ? selectedBackend : runtime;
414
+ const scriptName = PYTHON_SCRIPT_MAP[effectiveRuntime];
415
+ if (scriptName && pythonPath) {
416
+ const scriptPath = path2.join(__dirname, "../../python", scriptName);
417
+ const inputSize = Math.max(modelEntry.inputSize.width, modelEntry.inputSize.height);
418
+ const engine = new PythonInferenceEngine(pythonPath, scriptPath, effectiveRuntime, modelPath, [
419
+ `--input-size=${inputSize}`,
420
+ `--confidence=0.25`
421
+ ]);
422
+ await engine.initialize();
423
+ return { engine, format: selectedFormat, modelPath };
424
+ }
425
+ const fallbackPath = modelFilePath(modelsDir, modelEntry, "onnx");
426
+ if (modelEntry.formats["onnx"] && modelExists(fallbackPath)) {
427
+ const engine = new NodeInferenceEngine(fallbackPath, "cpu");
428
+ await engine.initialize();
429
+ return { engine, format: "onnx", modelPath: fallbackPath };
430
+ }
431
+ throw new Error(
432
+ `resolveEngine: format ${selectedFormat} is not yet supported by NodeInferenceEngine, no Python runtime is available, and no ONNX fallback exists`
433
+ );
434
+ }
435
+ async function probeOnnxBackends() {
436
+ const available = ["cpu"];
437
+ try {
438
+ const ort = await import("onnxruntime-node");
439
+ const providers = ort.env?.webgl?.disabled !== void 0 ? ort.InferenceSession?.getAvailableProviders?.() ?? [] : [];
440
+ for (const p of providers) {
441
+ const normalized = p.toLowerCase().replace("executionprovider", "");
442
+ if (normalized === "coreml") available.push("coreml");
443
+ else if (normalized === "cuda") available.push("cuda");
444
+ else if (normalized === "tensorrt") available.push("tensorrt");
445
+ }
446
+ } catch {
447
+ }
448
+ if (process.platform === "darwin" && !available.includes("coreml")) {
449
+ available.push("coreml");
450
+ }
451
+ return [...new Set(available)];
452
+ }
453
+
454
+ // src/addons/face-recognition/index.ts
455
+ var IDENTITY_LABEL = { id: "identity", name: "Identity" };
456
+ var IDENTITY_LABELS = [IDENTITY_LABEL];
457
+ var FACE_REC_CLASS_MAP = { mapping: {}, preserveOriginal: true };
458
+ var REQUIRED_STEPS = [
459
+ { slot: "cropper", outputClasses: ["face"], description: "Requires a face detector" }
460
+ ];
461
+ var FaceRecognitionAddon = class {
462
+ id = "face-recognition";
463
+ slot = "classifier";
464
+ inputClasses = ["face"];
465
+ outputClasses = ["identity:*"];
466
+ slotPriority = 0;
467
+ requiredSteps = REQUIRED_STEPS;
468
+ manifest = {
469
+ id: "face-recognition",
470
+ name: "Face Recognition",
471
+ version: "0.1.0",
472
+ description: "ArcFace-based face recognition \u2014 produces 512-d identity embeddings",
473
+ packageName: "@camstack/addon-vision",
474
+ slot: "classifier",
475
+ inputClasses: ["face"],
476
+ outputClasses: ["identity:*"],
477
+ requiredSteps: REQUIRED_STEPS,
478
+ supportsCustomModels: false,
479
+ mayRequirePython: false,
480
+ defaultConfig: {
481
+ modelId: "arcface-r100",
482
+ runtime: "auto",
483
+ backend: "cpu"
484
+ }
485
+ };
486
+ engine;
487
+ modelEntry;
488
+ async initialize(ctx) {
489
+ const cfg = ctx.addonConfig;
490
+ const modelId = cfg["modelId"] ?? "arcface-r100";
491
+ const runtime = cfg["runtime"] ?? "auto";
492
+ const backend = cfg["backend"] ?? "cpu";
493
+ const entry = FACE_RECOGNITION_MODELS.find((m) => m.id === modelId);
494
+ if (!entry) {
495
+ throw new Error(`FaceRecognitionAddon: unknown modelId "${modelId}"`);
496
+ }
497
+ this.modelEntry = entry;
498
+ const resolved = await resolveEngine({
499
+ runtime,
500
+ backend,
501
+ modelEntry: entry,
502
+ modelsDir: ctx.locationPaths.models
503
+ });
504
+ this.engine = resolved.engine;
505
+ }
506
+ async classify(input) {
507
+ const start = Date.now();
508
+ const { width: inputW, height: inputH } = this.modelEntry.inputSize;
509
+ const faceCrop = await cropRegion(input.frame.data, input.roi);
510
+ const layout = this.modelEntry.inputLayout ?? "nhwc";
511
+ const normalization = this.modelEntry.inputNormalization ?? "zero-one";
512
+ const normalized = await resizeAndNormalize(faceCrop, inputW, inputH, normalization, layout);
513
+ const rawEmbedding = await this.engine.run(normalized, [1, inputH, inputW, 3]);
514
+ const embedding = l2Normalize(rawEmbedding);
515
+ return {
516
+ classifications: [
517
+ {
518
+ class: "identity",
519
+ score: 1,
520
+ embedding
521
+ }
522
+ ],
523
+ inferenceMs: Date.now() - start,
524
+ modelId: this.modelEntry.id
525
+ };
526
+ }
527
+ async shutdown() {
528
+ await this.engine?.dispose();
529
+ }
530
+ getConfigSchema() {
531
+ return {
532
+ sections: [
533
+ {
534
+ id: "model",
535
+ title: "Model",
536
+ columns: 1,
537
+ fields: [
538
+ {
539
+ key: "modelId",
540
+ label: "Model",
541
+ type: "model-selector",
542
+ catalog: [...FACE_RECOGNITION_MODELS],
543
+ allowCustom: false,
544
+ allowConversion: false,
545
+ acceptFormats: ["onnx", "coreml", "openvino"],
546
+ requiredMetadata: ["inputSize", "labels", "outputFormat"],
547
+ outputFormatHint: "embedding"
548
+ }
549
+ ]
550
+ },
551
+ {
552
+ id: "runtime",
553
+ title: "Runtime",
554
+ columns: 2,
555
+ fields: [
556
+ {
557
+ key: "runtime",
558
+ label: "Runtime",
559
+ type: "select",
560
+ options: [
561
+ { value: "auto", label: "Auto (recommended)" },
562
+ { value: "onnx", label: "ONNX Runtime" },
563
+ { value: "coreml", label: "CoreML (Apple)" }
564
+ ]
565
+ },
566
+ {
567
+ key: "backend",
568
+ label: "Backend",
569
+ type: "select",
570
+ dependsOn: { runtime: "onnx" },
571
+ options: [
572
+ { value: "cpu", label: "CPU" },
573
+ { value: "coreml", label: "CoreML" },
574
+ { value: "cuda", label: "CUDA (NVIDIA)" }
575
+ ]
576
+ }
577
+ ]
578
+ }
579
+ ]
580
+ };
581
+ }
582
+ getClassMap() {
583
+ return FACE_REC_CLASS_MAP;
584
+ }
585
+ getModelCatalog() {
586
+ return [...FACE_RECOGNITION_MODELS];
587
+ }
588
+ getAvailableModels() {
589
+ return [];
590
+ }
591
+ getActiveLabels() {
592
+ return IDENTITY_LABELS;
593
+ }
594
+ async probe() {
595
+ return {
596
+ available: true,
597
+ runtime: this.engine?.runtime ?? "onnx",
598
+ device: this.engine?.device ?? "cpu",
599
+ capabilities: ["fp32"]
600
+ };
601
+ }
602
+ };
603
+ //# sourceMappingURL=index.js.map