@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,648 @@
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/plate-recognition/index.ts
31
+ var plate_recognition_exports = {};
32
+ __export(plate_recognition_exports, {
33
+ default: () => PlateRecognitionAddon
34
+ });
35
+ module.exports = __toCommonJS(plate_recognition_exports);
36
+
37
+ // src/catalogs/plate-recognition-models.ts
38
+ var import_types = require("@camstack/types");
39
+ var HF_REPO = "camstack/camstack-models";
40
+ var PLATE_TEXT_LABELS = [
41
+ { id: "text", name: "Plate Text" }
42
+ ];
43
+ var PLATE_RECOGNITION_MODELS = [
44
+ {
45
+ id: "paddleocr-latin",
46
+ name: "PaddleOCR Latin",
47
+ description: "PaddleOCR recognition model for Latin-script license plates",
48
+ inputSize: { width: 320, height: 48 },
49
+ labels: PLATE_TEXT_LABELS,
50
+ formats: {
51
+ onnx: {
52
+ url: (0, import_types.hfModelUrl)(HF_REPO, "plateRecognition/paddleocr/onnx/camstack-paddleocr-latin-rec.onnx"),
53
+ sizeMB: 7.5
54
+ },
55
+ openvino: {
56
+ url: (0, import_types.hfModelUrl)(HF_REPO, "plateRecognition/paddleocr/openvino/camstack-paddleocr-latin.xml"),
57
+ sizeMB: 4
58
+ }
59
+ }
60
+ },
61
+ {
62
+ id: "paddleocr-en",
63
+ name: "PaddleOCR English",
64
+ description: "PaddleOCR recognition model optimized for English license plates",
65
+ inputSize: { width: 320, height: 48 },
66
+ labels: PLATE_TEXT_LABELS,
67
+ formats: {
68
+ onnx: {
69
+ url: (0, import_types.hfModelUrl)(HF_REPO, "plateRecognition/paddleocr/onnx/camstack-paddleocr-en-rec.onnx"),
70
+ sizeMB: 7.5
71
+ },
72
+ openvino: {
73
+ url: (0, import_types.hfModelUrl)(HF_REPO, "plateRecognition/paddleocr/openvino/camstack-paddleocr-en.xml"),
74
+ sizeMB: 4
75
+ }
76
+ }
77
+ }
78
+ ];
79
+
80
+ // src/shared/image-utils.ts
81
+ var import_sharp = __toESM(require("sharp"));
82
+ async function cropRegion(jpeg, roi) {
83
+ return (0, import_sharp.default)(jpeg).extract({
84
+ left: Math.round(roi.x),
85
+ top: Math.round(roi.y),
86
+ width: Math.round(roi.w),
87
+ height: Math.round(roi.h)
88
+ }).jpeg().toBuffer();
89
+ }
90
+ async function resizeAndNormalize(jpeg, targetWidth, targetHeight, normalization, layout) {
91
+ const { data } = await (0, import_sharp.default)(jpeg).resize(targetWidth, targetHeight).removeAlpha().raw().toBuffer({ resolveWithObject: true });
92
+ const numPixels = targetWidth * targetHeight;
93
+ const float32 = new Float32Array(3 * numPixels);
94
+ const mean = [0.485, 0.456, 0.406];
95
+ const std = [0.229, 0.224, 0.225];
96
+ if (layout === "nchw") {
97
+ for (let i = 0; i < numPixels; i++) {
98
+ const srcBase = i * 3;
99
+ for (let c = 0; c < 3; c++) {
100
+ const raw = data[srcBase + c] / 255;
101
+ let val;
102
+ if (normalization === "zero-one") {
103
+ val = raw;
104
+ } else if (normalization === "imagenet") {
105
+ val = (raw - mean[c]) / std[c];
106
+ } else {
107
+ val = data[srcBase + c];
108
+ }
109
+ float32[c * numPixels + i] = val;
110
+ }
111
+ }
112
+ } else {
113
+ for (let i = 0; i < numPixels; i++) {
114
+ const srcBase = i * 3;
115
+ for (let c = 0; c < 3; c++) {
116
+ const raw = data[srcBase + c] / 255;
117
+ let val;
118
+ if (normalization === "zero-one") {
119
+ val = raw;
120
+ } else if (normalization === "imagenet") {
121
+ val = (raw - mean[c]) / std[c];
122
+ } else {
123
+ val = data[srcBase + c];
124
+ }
125
+ float32[i * 3 + c] = val;
126
+ }
127
+ }
128
+ }
129
+ return float32;
130
+ }
131
+
132
+ // src/shared/postprocess/paddleocr.ts
133
+ function ctcDecode(output, seqLen, numChars, charset) {
134
+ let totalLogScore = 0;
135
+ const rawIndices = [];
136
+ for (let t = 0; t < seqLen; t++) {
137
+ const offset = t * numChars;
138
+ let bestIdx = 0;
139
+ let bestVal = output[offset];
140
+ for (let c = 1; c < numChars; c++) {
141
+ const val = output[offset + c];
142
+ if (val > bestVal) {
143
+ bestVal = val;
144
+ bestIdx = c;
145
+ }
146
+ }
147
+ rawIndices.push(bestIdx);
148
+ totalLogScore += bestVal;
149
+ }
150
+ const collapsed = [];
151
+ for (let i = 0; i < rawIndices.length; i++) {
152
+ const cur = rawIndices[i];
153
+ if (i === 0 || cur !== rawIndices[i - 1]) {
154
+ collapsed.push(cur);
155
+ }
156
+ }
157
+ const filtered = collapsed.filter((idx) => idx !== 0);
158
+ const text = filtered.map((idx) => charset[idx] ?? "").join("");
159
+ const confidence = seqLen > 0 ? totalLogScore / seqLen : 0;
160
+ return { text, confidence };
161
+ }
162
+
163
+ // src/shared/engine-resolver.ts
164
+ var fs = __toESM(require("fs"));
165
+ var path2 = __toESM(require("path"));
166
+
167
+ // src/shared/node-engine.ts
168
+ var path = __toESM(require("path"));
169
+ var BACKEND_TO_PROVIDER = {
170
+ cpu: "cpu",
171
+ coreml: "coreml",
172
+ cuda: "cuda",
173
+ tensorrt: "tensorrt",
174
+ dml: "dml"
175
+ };
176
+ var BACKEND_TO_DEVICE = {
177
+ cpu: "cpu",
178
+ coreml: "gpu-mps",
179
+ cuda: "gpu-cuda",
180
+ tensorrt: "tensorrt"
181
+ };
182
+ var NodeInferenceEngine = class {
183
+ constructor(modelPath, backend) {
184
+ this.modelPath = modelPath;
185
+ this.backend = backend;
186
+ this.device = BACKEND_TO_DEVICE[backend] ?? "cpu";
187
+ }
188
+ runtime = "onnx";
189
+ device;
190
+ session = null;
191
+ async initialize() {
192
+ const ort = await import("onnxruntime-node");
193
+ const provider = BACKEND_TO_PROVIDER[this.backend] ?? "cpu";
194
+ const absModelPath = path.isAbsolute(this.modelPath) ? this.modelPath : path.resolve(process.cwd(), this.modelPath);
195
+ const sessionOptions = {
196
+ executionProviders: [provider]
197
+ };
198
+ this.session = await ort.InferenceSession.create(absModelPath, sessionOptions);
199
+ }
200
+ async run(input, inputShape) {
201
+ if (!this.session) {
202
+ throw new Error("NodeInferenceEngine: not initialized \u2014 call initialize() first");
203
+ }
204
+ const ort = await import("onnxruntime-node");
205
+ const sess = this.session;
206
+ const inputName = sess.inputNames[0];
207
+ const tensor = new ort.Tensor("float32", input, [...inputShape]);
208
+ const feeds = { [inputName]: tensor };
209
+ const results = await sess.run(feeds);
210
+ const outputName = sess.outputNames[0];
211
+ const outputTensor = results[outputName];
212
+ return outputTensor.data;
213
+ }
214
+ async runMultiOutput(input, inputShape) {
215
+ if (!this.session) {
216
+ throw new Error("NodeInferenceEngine: not initialized \u2014 call initialize() first");
217
+ }
218
+ const ort = await import("onnxruntime-node");
219
+ const sess = this.session;
220
+ const inputName = sess.inputNames[0];
221
+ const tensor = new ort.Tensor("float32", input, [...inputShape]);
222
+ const feeds = { [inputName]: tensor };
223
+ const results = await sess.run(feeds);
224
+ const out = {};
225
+ for (const name of sess.outputNames) {
226
+ out[name] = results[name].data;
227
+ }
228
+ return out;
229
+ }
230
+ async dispose() {
231
+ this.session = null;
232
+ }
233
+ };
234
+
235
+ // src/shared/python-engine.ts
236
+ var import_node_child_process = require("child_process");
237
+ var PythonInferenceEngine = class {
238
+ constructor(pythonPath, scriptPath, runtime, modelPath, extraArgs = []) {
239
+ this.pythonPath = pythonPath;
240
+ this.scriptPath = scriptPath;
241
+ this.modelPath = modelPath;
242
+ this.extraArgs = extraArgs;
243
+ this.runtime = runtime;
244
+ const runtimeDeviceMap = {
245
+ onnx: "cpu",
246
+ coreml: "gpu-mps",
247
+ pytorch: "cpu",
248
+ openvino: "cpu",
249
+ tflite: "cpu"
250
+ };
251
+ this.device = runtimeDeviceMap[runtime];
252
+ }
253
+ runtime;
254
+ device;
255
+ process = null;
256
+ receiveBuffer = Buffer.alloc(0);
257
+ pendingResolve = null;
258
+ pendingReject = null;
259
+ async initialize() {
260
+ const args = [this.scriptPath, this.modelPath, ...this.extraArgs];
261
+ this.process = (0, import_node_child_process.spawn)(this.pythonPath, args, {
262
+ stdio: ["pipe", "pipe", "pipe"]
263
+ });
264
+ if (!this.process.stdout || !this.process.stdin) {
265
+ throw new Error("PythonInferenceEngine: failed to create process pipes");
266
+ }
267
+ this.process.stderr?.on("data", (chunk) => {
268
+ process.stderr.write(`[python-engine] ${chunk.toString()}`);
269
+ });
270
+ this.process.on("error", (err) => {
271
+ this.pendingReject?.(err);
272
+ this.pendingReject = null;
273
+ this.pendingResolve = null;
274
+ });
275
+ this.process.on("exit", (code) => {
276
+ if (code !== 0) {
277
+ const err = new Error(`PythonInferenceEngine: process exited with code ${code}`);
278
+ this.pendingReject?.(err);
279
+ this.pendingReject = null;
280
+ this.pendingResolve = null;
281
+ }
282
+ });
283
+ this.process.stdout.on("data", (chunk) => {
284
+ this.receiveBuffer = Buffer.concat([this.receiveBuffer, chunk]);
285
+ this._tryReceive();
286
+ });
287
+ await new Promise((resolve2, reject) => {
288
+ const timeout = setTimeout(() => resolve2(), 2e3);
289
+ this.process?.on("error", (err) => {
290
+ clearTimeout(timeout);
291
+ reject(err);
292
+ });
293
+ this.process?.on("exit", (code) => {
294
+ clearTimeout(timeout);
295
+ if (code !== 0) {
296
+ reject(new Error(`PythonInferenceEngine: process exited early with code ${code}`));
297
+ }
298
+ });
299
+ });
300
+ }
301
+ _tryReceive() {
302
+ if (this.receiveBuffer.length < 4) return;
303
+ const length = this.receiveBuffer.readUInt32LE(0);
304
+ if (this.receiveBuffer.length < 4 + length) return;
305
+ const jsonBytes = this.receiveBuffer.subarray(4, 4 + length);
306
+ this.receiveBuffer = this.receiveBuffer.subarray(4 + length);
307
+ const resolve2 = this.pendingResolve;
308
+ const reject = this.pendingReject;
309
+ this.pendingResolve = null;
310
+ this.pendingReject = null;
311
+ if (!resolve2) return;
312
+ try {
313
+ const parsed = JSON.parse(jsonBytes.toString("utf8"));
314
+ resolve2(parsed);
315
+ } catch (err) {
316
+ reject?.(err instanceof Error ? err : new Error(String(err)));
317
+ }
318
+ }
319
+ /** Send JPEG buffer, receive JSON detection results */
320
+ async runJpeg(jpeg) {
321
+ if (!this.process?.stdin) {
322
+ throw new Error("PythonInferenceEngine: process not initialized");
323
+ }
324
+ return new Promise((resolve2, reject) => {
325
+ this.pendingResolve = resolve2;
326
+ this.pendingReject = reject;
327
+ const lengthBuf = Buffer.allocUnsafe(4);
328
+ lengthBuf.writeUInt32LE(jpeg.length, 0);
329
+ this.process.stdin.write(Buffer.concat([lengthBuf, jpeg]));
330
+ });
331
+ }
332
+ /** IInferenceEngine.run — wraps runJpeg for compatibility */
333
+ async run(_input, _inputShape) {
334
+ throw new Error(
335
+ "PythonInferenceEngine: use runJpeg() directly \u2014 this engine operates on JPEG input"
336
+ );
337
+ }
338
+ /** IInferenceEngine.runMultiOutput — not supported by Python engine (operates on JPEG input) */
339
+ async runMultiOutput(_input, _inputShape) {
340
+ throw new Error(
341
+ "PythonInferenceEngine: runMultiOutput() is not supported \u2014 this engine operates on JPEG input"
342
+ );
343
+ }
344
+ async dispose() {
345
+ if (this.process) {
346
+ this.process.stdin?.end();
347
+ this.process.kill("SIGTERM");
348
+ this.process = null;
349
+ }
350
+ }
351
+ };
352
+
353
+ // src/shared/engine-resolver.ts
354
+ var AUTO_BACKEND_PRIORITY = ["coreml", "cuda", "tensorrt", "cpu"];
355
+ var BACKEND_TO_FORMAT = {
356
+ cpu: "onnx",
357
+ coreml: "coreml",
358
+ cuda: "onnx",
359
+ tensorrt: "onnx"
360
+ };
361
+ var RUNTIME_TO_FORMAT = {
362
+ onnx: "onnx",
363
+ coreml: "coreml",
364
+ openvino: "openvino",
365
+ tflite: "tflite",
366
+ pytorch: "pt"
367
+ };
368
+ function modelFilePath(modelsDir, modelEntry, format) {
369
+ const formatEntry = modelEntry.formats[format];
370
+ if (!formatEntry) {
371
+ throw new Error(`Model ${modelEntry.id} has no ${format} format`);
372
+ }
373
+ const urlParts = formatEntry.url.split("/");
374
+ const filename = urlParts[urlParts.length - 1] ?? `${modelEntry.id}.${format}`;
375
+ return path2.join(modelsDir, filename);
376
+ }
377
+ function modelExists(filePath) {
378
+ try {
379
+ return fs.existsSync(filePath);
380
+ } catch {
381
+ return false;
382
+ }
383
+ }
384
+ async function resolveEngine(options) {
385
+ const { runtime, backend, modelEntry, modelsDir, downloadModel } = options;
386
+ let selectedFormat;
387
+ let selectedBackend;
388
+ if (runtime === "auto") {
389
+ const available = await probeOnnxBackends();
390
+ let chosen = null;
391
+ for (const b of AUTO_BACKEND_PRIORITY) {
392
+ if (!available.includes(b)) continue;
393
+ const fmt = BACKEND_TO_FORMAT[b];
394
+ if (!fmt) continue;
395
+ if (!modelEntry.formats[fmt]) continue;
396
+ chosen = { backend: b, format: fmt };
397
+ break;
398
+ }
399
+ if (!chosen) {
400
+ throw new Error(
401
+ `resolveEngine: no compatible backend found for model ${modelEntry.id}. Available backends: ${available.join(", ")}`
402
+ );
403
+ }
404
+ selectedFormat = chosen.format;
405
+ selectedBackend = chosen.backend;
406
+ } else {
407
+ const fmt = RUNTIME_TO_FORMAT[runtime];
408
+ if (!fmt) {
409
+ throw new Error(`resolveEngine: unsupported runtime "${runtime}"`);
410
+ }
411
+ if (!modelEntry.formats[fmt]) {
412
+ throw new Error(
413
+ `resolveEngine: model ${modelEntry.id} has no ${fmt} format for runtime ${runtime}`
414
+ );
415
+ }
416
+ selectedFormat = fmt;
417
+ selectedBackend = runtime === "onnx" ? backend || "cpu" : runtime;
418
+ }
419
+ let modelPath = modelFilePath(modelsDir, modelEntry, selectedFormat);
420
+ if (!modelExists(modelPath)) {
421
+ if (downloadModel) {
422
+ const formatEntry = modelEntry.formats[selectedFormat];
423
+ modelPath = await downloadModel(formatEntry.url, modelsDir);
424
+ } else {
425
+ throw new Error(
426
+ `resolveEngine: model file not found at ${modelPath} and no downloadModel function provided`
427
+ );
428
+ }
429
+ }
430
+ if (selectedFormat === "onnx" || selectedFormat === "coreml") {
431
+ const engine = new NodeInferenceEngine(modelPath, selectedBackend);
432
+ await engine.initialize();
433
+ return { engine, format: selectedFormat, modelPath };
434
+ }
435
+ const { pythonPath } = options;
436
+ const PYTHON_SCRIPT_MAP = {
437
+ coreml: "coreml_inference.py",
438
+ pytorch: "pytorch_inference.py",
439
+ openvino: "openvino_inference.py"
440
+ };
441
+ const effectiveRuntime = runtime === "auto" ? selectedBackend : runtime;
442
+ const scriptName = PYTHON_SCRIPT_MAP[effectiveRuntime];
443
+ if (scriptName && pythonPath) {
444
+ const scriptPath = path2.join(__dirname, "../../python", scriptName);
445
+ const inputSize = Math.max(modelEntry.inputSize.width, modelEntry.inputSize.height);
446
+ const engine = new PythonInferenceEngine(pythonPath, scriptPath, effectiveRuntime, modelPath, [
447
+ `--input-size=${inputSize}`,
448
+ `--confidence=0.25`
449
+ ]);
450
+ await engine.initialize();
451
+ return { engine, format: selectedFormat, modelPath };
452
+ }
453
+ const fallbackPath = modelFilePath(modelsDir, modelEntry, "onnx");
454
+ if (modelEntry.formats["onnx"] && modelExists(fallbackPath)) {
455
+ const engine = new NodeInferenceEngine(fallbackPath, "cpu");
456
+ await engine.initialize();
457
+ return { engine, format: "onnx", modelPath: fallbackPath };
458
+ }
459
+ throw new Error(
460
+ `resolveEngine: format ${selectedFormat} is not yet supported by NodeInferenceEngine, no Python runtime is available, and no ONNX fallback exists`
461
+ );
462
+ }
463
+ async function probeOnnxBackends() {
464
+ const available = ["cpu"];
465
+ try {
466
+ const ort = await import("onnxruntime-node");
467
+ const providers = ort.env?.webgl?.disabled !== void 0 ? ort.InferenceSession?.getAvailableProviders?.() ?? [] : [];
468
+ for (const p of providers) {
469
+ const normalized = p.toLowerCase().replace("executionprovider", "");
470
+ if (normalized === "coreml") available.push("coreml");
471
+ else if (normalized === "cuda") available.push("cuda");
472
+ else if (normalized === "tensorrt") available.push("tensorrt");
473
+ }
474
+ } catch {
475
+ }
476
+ if (process.platform === "darwin" && !available.includes("coreml")) {
477
+ available.push("coreml");
478
+ }
479
+ return [...new Set(available)];
480
+ }
481
+
482
+ // src/addons/plate-recognition/index.ts
483
+ var fs2 = __toESM(require("fs"));
484
+ var path3 = __toESM(require("path"));
485
+ var PLATE_TEXT_LABEL = { id: "plate-text", name: "Plate Text" };
486
+ var PLATE_TEXT_LABELS2 = [PLATE_TEXT_LABEL];
487
+ var PLATE_REC_CLASS_MAP = { mapping: {}, preserveOriginal: true };
488
+ function loadCharset(modelsDir, modelId) {
489
+ const dictNames = [
490
+ `camstack-${modelId}-dict.txt`,
491
+ `camstack-paddleocr-latin-dict.txt`,
492
+ `camstack-paddleocr-en-dict.txt`
493
+ ];
494
+ for (const name of dictNames) {
495
+ const dictPath = path3.join(modelsDir, name);
496
+ if (fs2.existsSync(dictPath)) {
497
+ const lines = fs2.readFileSync(dictPath, "utf-8").split("\n").filter((l) => l.length > 0);
498
+ return ["", ...lines, " "];
499
+ }
500
+ }
501
+ throw new Error(`PlateRecognitionAddon: dict.txt not found in ${modelsDir}`);
502
+ }
503
+ var CHARSET = [];
504
+ var REQUIRED_STEPS = [
505
+ { slot: "cropper", outputClasses: ["plate"], description: "Requires a plate detector" }
506
+ ];
507
+ var PlateRecognitionAddon = class {
508
+ id = "plate-recognition";
509
+ slot = "classifier";
510
+ inputClasses = ["plate"];
511
+ outputClasses = ["plate-text:*"];
512
+ slotPriority = 0;
513
+ requiredSteps = REQUIRED_STEPS;
514
+ manifest = {
515
+ id: "plate-recognition",
516
+ name: "License Plate Recognition (OCR)",
517
+ version: "0.1.0",
518
+ description: "PaddleOCR-based license plate text recognition",
519
+ packageName: "@camstack/addon-vision",
520
+ slot: "classifier",
521
+ inputClasses: ["plate"],
522
+ outputClasses: ["plate-text:*"],
523
+ requiredSteps: REQUIRED_STEPS,
524
+ supportsCustomModels: false,
525
+ mayRequirePython: false,
526
+ defaultConfig: {
527
+ modelId: "paddleocr-latin",
528
+ runtime: "auto",
529
+ backend: "cpu",
530
+ minConfidence: 0.5
531
+ }
532
+ };
533
+ engine;
534
+ modelEntry;
535
+ minConfidence = 0.5;
536
+ async initialize(ctx) {
537
+ const cfg = ctx.addonConfig;
538
+ const modelId = cfg["modelId"] ?? "paddleocr-latin";
539
+ const runtime = cfg["runtime"] ?? "auto";
540
+ const backend = cfg["backend"] ?? "cpu";
541
+ this.minConfidence = cfg["minConfidence"] ?? 0.5;
542
+ const entry = PLATE_RECOGNITION_MODELS.find((m) => m.id === modelId);
543
+ if (!entry) {
544
+ throw new Error(`PlateRecognitionAddon: unknown modelId "${modelId}"`);
545
+ }
546
+ this.modelEntry = entry;
547
+ CHARSET = loadCharset(ctx.locationPaths.models, modelId);
548
+ const resolved = await resolveEngine({
549
+ runtime,
550
+ backend,
551
+ modelEntry: entry,
552
+ modelsDir: ctx.locationPaths.models
553
+ });
554
+ this.engine = resolved.engine;
555
+ }
556
+ async classify(input) {
557
+ const start = Date.now();
558
+ const { width: inputW, height: inputH } = this.modelEntry.inputSize;
559
+ const plateCrop = await cropRegion(input.frame.data, input.roi);
560
+ const normalized = await resizeAndNormalize(plateCrop, inputW, inputH, "zero-one", "nchw");
561
+ const output = await this.engine.run(normalized, [1, 3, inputH, inputW]);
562
+ const numChars = CHARSET.length;
563
+ const seqLen = output.length / numChars;
564
+ const { text, confidence } = ctcDecode(output, seqLen, numChars, CHARSET);
565
+ if (confidence < this.minConfidence || text.trim().length === 0) {
566
+ return {
567
+ classifications: [],
568
+ inferenceMs: Date.now() - start,
569
+ modelId: this.modelEntry.id
570
+ };
571
+ }
572
+ return {
573
+ classifications: [
574
+ {
575
+ class: "plate-text",
576
+ score: confidence,
577
+ text
578
+ }
579
+ ],
580
+ inferenceMs: Date.now() - start,
581
+ modelId: this.modelEntry.id
582
+ };
583
+ }
584
+ async shutdown() {
585
+ await this.engine?.dispose();
586
+ }
587
+ getConfigSchema() {
588
+ return {
589
+ sections: [
590
+ {
591
+ id: "model",
592
+ title: "Model",
593
+ columns: 1,
594
+ fields: [
595
+ {
596
+ key: "modelId",
597
+ label: "Model",
598
+ type: "model-selector",
599
+ catalog: [...PLATE_RECOGNITION_MODELS],
600
+ allowCustom: false,
601
+ allowConversion: false,
602
+ acceptFormats: ["onnx", "openvino"],
603
+ requiredMetadata: ["inputSize", "labels", "outputFormat"],
604
+ outputFormatHint: "ocr"
605
+ }
606
+ ]
607
+ },
608
+ {
609
+ id: "thresholds",
610
+ title: "Recognition Settings",
611
+ columns: 1,
612
+ fields: [
613
+ {
614
+ key: "minConfidence",
615
+ label: "Minimum Confidence",
616
+ type: "slider",
617
+ min: 0.1,
618
+ max: 1,
619
+ step: 0.05,
620
+ default: 0.5
621
+ }
622
+ ]
623
+ }
624
+ ]
625
+ };
626
+ }
627
+ getClassMap() {
628
+ return PLATE_REC_CLASS_MAP;
629
+ }
630
+ getModelCatalog() {
631
+ return [...PLATE_RECOGNITION_MODELS];
632
+ }
633
+ getAvailableModels() {
634
+ return [];
635
+ }
636
+ getActiveLabels() {
637
+ return PLATE_TEXT_LABELS2;
638
+ }
639
+ async probe() {
640
+ return {
641
+ available: true,
642
+ runtime: this.engine?.runtime ?? "onnx",
643
+ device: this.engine?.device ?? "cpu",
644
+ capabilities: ["fp32"]
645
+ };
646
+ }
647
+ };
648
+ //# sourceMappingURL=index.js.map