@camstack/addon-post-analysis 0.1.1

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 (80) hide show
  1. package/dist/embedding-encoder/index.js +928 -0
  2. package/dist/embedding-encoder/index.js.map +1 -0
  3. package/dist/embedding-encoder/index.mjs +888 -0
  4. package/dist/embedding-encoder/index.mjs.map +1 -0
  5. package/dist/enrichment-engine/index.js +774 -0
  6. package/dist/enrichment-engine/index.js.map +1 -0
  7. package/dist/enrichment-engine/index.mjs +774 -0
  8. package/dist/enrichment-engine/index.mjs.map +1 -0
  9. package/dist/ffmpeg-config-DRONlBsj.mjs +56 -0
  10. package/dist/ffmpeg-config-DRONlBsj.mjs.map +1 -0
  11. package/dist/ffmpeg-config-uANz3sV5.js +73 -0
  12. package/dist/ffmpeg-config-uANz3sV5.js.map +1 -0
  13. package/dist/pipeline-analytics/@mf-types/compiled-types/pipeline-analytics/widgets/AudioHistoryChart.d.ts +4 -0
  14. package/dist/pipeline-analytics/@mf-types/compiled-types/pipeline-analytics/widgets/AudioMetricsPanel.d.ts +10 -0
  15. package/dist/pipeline-analytics/@mf-types/compiled-types/pipeline-analytics/widgets/DetectionHistoryChart.d.ts +4 -0
  16. package/dist/pipeline-analytics/@mf-types/compiled-types/pipeline-analytics/widgets/MotionHistoryChart.d.ts +4 -0
  17. package/dist/pipeline-analytics/@mf-types/compiled-types/pipeline-analytics/widgets/OccupancyHistoryChart.d.ts +4 -0
  18. package/dist/pipeline-analytics/@mf-types/compiled-types/pipeline-analytics/widgets/OccupancyPanel.d.ts +10 -0
  19. package/dist/pipeline-analytics/@mf-types/compiled-types/pipeline-analytics/widgets/chart-utils.d.ts +97 -0
  20. package/dist/pipeline-analytics/@mf-types/compiled-types/pipeline-analytics/widgets/index.d.ts +27 -0
  21. package/dist/pipeline-analytics/@mf-types/widgets.d.ts +2 -0
  22. package/dist/pipeline-analytics/@mf-types.d.ts +3 -0
  23. package/dist/pipeline-analytics/@mf-types.zip +0 -0
  24. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_sdk__loadShare__.mjs-h5aXOPSA.mjs +12 -0
  25. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.mjs-46iNwbxa.mjs +16 -0
  26. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.mjs-Db6yh4op.mjs +15 -0
  27. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-DoWbefqS.mjs +104 -0
  28. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-52bfkwC8.mjs +85 -0
  29. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-CVrnrGED.mjs +62 -0
  30. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare__react__loadShare__.mjs-DuO9h7li.mjs +85 -0
  31. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare__react__loadShare__.mjs_commonjs-proxy-CmqNjq44.mjs +29 -0
  32. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-BsyrX6NO.mjs +36 -0
  33. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare__react_mf_2_dom__loadShare__.mjs-Dp8hqYOB.mjs +45 -0
  34. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-CA8cCIEl.mjs +6 -0
  35. package/dist/pipeline-analytics/__mfe_internal__addon_pipeline_analytics_widgets__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-BZjEt71l.mjs +34 -0
  36. package/dist/pipeline-analytics/_stub.js +1397 -0
  37. package/dist/pipeline-analytics/_virtual_mf-localSharedImportMap___mfe_internal__addon_pipeline_analytics_widgets-Bfo-or09.mjs +156 -0
  38. package/dist/pipeline-analytics/client-DdXDZxzK.mjs +10063 -0
  39. package/dist/pipeline-analytics/getErrorShape-BPSzUA7W-TlK8ipWe.mjs +211 -0
  40. package/dist/pipeline-analytics/hostInit-CqUKNfOr.mjs +168 -0
  41. package/dist/pipeline-analytics/index-B4OKsa9p.mjs +2603 -0
  42. package/dist/pipeline-analytics/index-B7r1koiV.mjs +19109 -0
  43. package/dist/pipeline-analytics/index-CRN37Hr9.mjs +15195 -0
  44. package/dist/pipeline-analytics/index-DRx99znz.mjs +1617 -0
  45. package/dist/pipeline-analytics/index-DyYvUfc7.mjs +725 -0
  46. package/dist/pipeline-analytics/index-k0CA0h_r.mjs +185 -0
  47. package/dist/pipeline-analytics/index-kIgjN-uq.mjs +435 -0
  48. package/dist/pipeline-analytics/index-xncRG7-x.mjs +2713 -0
  49. package/dist/pipeline-analytics/index.js +2563 -0
  50. package/dist/pipeline-analytics/index.js.map +1 -0
  51. package/dist/pipeline-analytics/index.mjs +2564 -0
  52. package/dist/pipeline-analytics/index.mjs.map +1 -0
  53. package/dist/pipeline-analytics/jsx-runtime-4ro1c69i.mjs +55 -0
  54. package/dist/pipeline-analytics/remoteEntry.js +2973 -0
  55. package/dist/pipeline-analytics/virtualExposes-8FzWTdq3.mjs +42 -0
  56. package/dist/playlist-generator-EhPaB7Hn.js +48 -0
  57. package/dist/playlist-generator-EhPaB7Hn.js.map +1 -0
  58. package/dist/playlist-generator-VTkgn53O.mjs +48 -0
  59. package/dist/playlist-generator-VTkgn53O.mjs.map +1 -0
  60. package/dist/recording/index.js +257 -0
  61. package/dist/recording/index.js.map +1 -0
  62. package/dist/recording/index.mjs +235 -0
  63. package/dist/recording/index.mjs.map +1 -0
  64. package/dist/recording-coordinator-C2sATEhe.js +1052 -0
  65. package/dist/recording-coordinator-C2sATEhe.js.map +1 -0
  66. package/dist/recording-coordinator-DuP3BUTV.mjs +1012 -0
  67. package/dist/recording-coordinator-DuP3BUTV.mjs.map +1 -0
  68. package/dist/recording-db-gOgaoQh0.js +348 -0
  69. package/dist/recording-db-gOgaoQh0.js.map +1 -0
  70. package/dist/recording-db-lIkSMTLq.mjs +348 -0
  71. package/dist/recording-db-lIkSMTLq.mjs.map +1 -0
  72. package/dist/recording-service-facade-B9lG6OFn.mjs +123 -0
  73. package/dist/recording-service-facade-B9lG6OFn.mjs.map +1 -0
  74. package/dist/recording-service-facade-Do1PKlAL.js +123 -0
  75. package/dist/recording-service-facade-Do1PKlAL.js.map +1 -0
  76. package/dist/storage-estimator-CRpoQc9j.js +72 -0
  77. package/dist/storage-estimator-CRpoQc9j.js.map +1 -0
  78. package/dist/storage-estimator-DzD8gWJH.mjs +72 -0
  79. package/dist/storage-estimator-DzD8gWJH.mjs.map +1 -0
  80. package/package.json +148 -0
@@ -0,0 +1,888 @@
1
+ import { BACKEND_TO_FORMAT as BACKEND_TO_FORMAT$1, RUNTIME_TO_FORMAT as RUNTIME_TO_FORMAT$1, PYTHON_SCRIPT, BaseAddon, embeddingEncoderCapability } from "@camstack/types";
2
+ import { ModelDownloadService } from "@camstack/core";
3
+ import * as path from "node:path";
4
+ import * as fs from "node:fs";
5
+ import sharp from "sharp";
6
+ import { spawn } from "node:child_process";
7
+ const CLIP_IMAGE_MODELS = [
8
+ {
9
+ id: "clip-vit-b32",
10
+ name: "CLIP ViT-B/32",
11
+ description: "OpenAI CLIP ViT-B/32 — fast, 512-dim, int8 quantized (85 MB)",
12
+ inputSize: { width: 224, height: 224 },
13
+ labels: [],
14
+ inputLayout: "nchw",
15
+ inputNormalization: "none",
16
+ formats: {
17
+ onnx: {
18
+ url: "https://huggingface.co/Xenova/clip-vit-base-patch32/resolve/main/onnx/vision_model_quantized.onnx",
19
+ sizeMB: 85
20
+ }
21
+ }
22
+ },
23
+ {
24
+ id: "clip-vit-b16",
25
+ name: "CLIP ViT-B/16",
26
+ description: "OpenAI CLIP ViT-B/16 — higher accuracy, 512-dim, int8 quantized (83 MB)",
27
+ inputSize: { width: 224, height: 224 },
28
+ labels: [],
29
+ inputLayout: "nchw",
30
+ inputNormalization: "none",
31
+ formats: {
32
+ onnx: {
33
+ url: "https://huggingface.co/Xenova/clip-vit-base-patch16/resolve/main/onnx/vision_model_quantized.onnx",
34
+ sizeMB: 83
35
+ }
36
+ }
37
+ },
38
+ {
39
+ id: "siglip2-b16-256",
40
+ name: "SigLIP2 Base/16 256",
41
+ description: "Google SigLIP2 — superior scene understanding, 768-dim, int8 quantized (90 MB)",
42
+ inputSize: { width: 256, height: 256 },
43
+ labels: [],
44
+ inputLayout: "nchw",
45
+ inputNormalization: "none",
46
+ formats: {
47
+ onnx: {
48
+ url: "https://huggingface.co/onnx-community/siglip2-base-patch16-256-ONNX/resolve/main/onnx/vision_model_quantized.onnx",
49
+ sizeMB: 90
50
+ }
51
+ }
52
+ }
53
+ ];
54
+ const CLIP_TEXT_MODELS = [
55
+ {
56
+ id: "clip-vit-b32-text",
57
+ name: "CLIP ViT-B/32 Text Encoder",
58
+ description: "Text encoder for CLIP ViT-B/32, int8 quantized (62 MB)",
59
+ inputSize: { width: 0, height: 0 },
60
+ labels: [],
61
+ formats: {
62
+ onnx: {
63
+ url: "https://huggingface.co/Xenova/clip-vit-base-patch32/resolve/main/onnx/text_model_quantized.onnx",
64
+ sizeMB: 62
65
+ }
66
+ }
67
+ },
68
+ {
69
+ id: "clip-vit-b16-text",
70
+ name: "CLIP ViT-B/16 Text Encoder",
71
+ description: "Text encoder for CLIP ViT-B/16, int8 quantized (62 MB)",
72
+ inputSize: { width: 0, height: 0 },
73
+ labels: [],
74
+ formats: {
75
+ onnx: {
76
+ url: "https://huggingface.co/Xenova/clip-vit-base-patch16/resolve/main/onnx/text_model_quantized.onnx",
77
+ sizeMB: 62
78
+ }
79
+ }
80
+ },
81
+ {
82
+ id: "siglip2-b16-256-text",
83
+ name: "SigLIP2 Base/16 256 Text Encoder",
84
+ description: "Text encoder for SigLIP2, int8 quantized (270 MB)",
85
+ inputSize: { width: 0, height: 0 },
86
+ labels: [],
87
+ formats: {
88
+ onnx: {
89
+ url: "https://huggingface.co/onnx-community/siglip2-base-patch16-256-ONNX/resolve/main/onnx/text_model_quantized.onnx",
90
+ sizeMB: 270
91
+ }
92
+ }
93
+ }
94
+ ];
95
+ const noop = () => {
96
+ };
97
+ function createNoopLogger() {
98
+ const logger = {
99
+ debug: noop,
100
+ info: noop,
101
+ warn: noop,
102
+ error: noop,
103
+ child: () => logger,
104
+ withTags: (_tags) => logger
105
+ };
106
+ return logger;
107
+ }
108
+ const BACKEND_TO_DEVICE$1 = {
109
+ cpu: "cpu",
110
+ coreml: "gpu-mps",
111
+ cuda: "gpu-cuda",
112
+ tensorrt: "tensorrt"
113
+ };
114
+ class NodeRawTensorEngine {
115
+ constructor(modelPath, backend, logger) {
116
+ this.modelPath = modelPath;
117
+ this.backend = backend;
118
+ this.device = BACKEND_TO_DEVICE$1[backend] ?? "cpu";
119
+ this.log = logger ?? createNoopLogger();
120
+ }
121
+ runtime = "onnx";
122
+ device;
123
+ session = null;
124
+ log;
125
+ async initialize() {
126
+ const ort = await import("onnxruntime-node");
127
+ const provider = this.backend === "coreml" ? "coreml" : this.backend === "cuda" ? "cuda" : "cpu";
128
+ const absModelPath = path.isAbsolute(this.modelPath) ? this.modelPath : path.resolve(process.cwd(), this.modelPath);
129
+ this.session = await ort.InferenceSession.create(absModelPath, {
130
+ executionProviders: [provider]
131
+ });
132
+ this.log.info("ONNX session loaded", { meta: { modelPath: absModelPath, backend: this.backend, provider } });
133
+ }
134
+ async run(input, inputShape) {
135
+ if (!this.session) {
136
+ throw new Error("NodeRawTensorEngine: not initialized — call initialize() first");
137
+ }
138
+ const ort = await import("onnxruntime-node");
139
+ const sess = this.session;
140
+ const inputName = sess.inputNames[0];
141
+ const tensor = new ort.Tensor("float32", input, [...inputShape]);
142
+ const feeds = { [inputName]: tensor };
143
+ const start = Date.now();
144
+ let results;
145
+ try {
146
+ results = await sess.run(feeds);
147
+ } catch (err) {
148
+ const error = err instanceof Error ? err : new Error(String(err));
149
+ this.log.error("Inference failed", { meta: { error: error.message } });
150
+ throw error;
151
+ }
152
+ const outputName = sess.outputNames[0];
153
+ this.log.debug("Inference complete", { meta: { durationMs: Date.now() - start, outputKeys: [outputName], preprocessMode: "raw-tensor" } });
154
+ return results[outputName].data;
155
+ }
156
+ async dispose() {
157
+ this.session = null;
158
+ this.log.debug("Session disposed");
159
+ }
160
+ }
161
+ async function letterbox(jpeg, targetSize) {
162
+ const meta = await sharp(jpeg).metadata();
163
+ const originalWidth = meta.width ?? 0;
164
+ const originalHeight = meta.height ?? 0;
165
+ const scale = Math.min(targetSize / originalWidth, targetSize / originalHeight);
166
+ const scaledWidth = Math.round(originalWidth * scale);
167
+ const scaledHeight = Math.round(originalHeight * scale);
168
+ const padX = Math.floor((targetSize - scaledWidth) / 2);
169
+ const padY = Math.floor((targetSize - scaledHeight) / 2);
170
+ const { data } = await sharp(jpeg).resize(scaledWidth, scaledHeight).extend({
171
+ top: padY,
172
+ bottom: targetSize - scaledHeight - padY,
173
+ left: padX,
174
+ right: targetSize - scaledWidth - padX,
175
+ background: { r: 114, g: 114, b: 114 }
176
+ }).removeAlpha().raw().toBuffer({ resolveWithObject: true });
177
+ const numPixels = targetSize * targetSize;
178
+ const float32 = new Float32Array(3 * numPixels);
179
+ for (let i = 0; i < numPixels; i++) {
180
+ const srcBase = i * 3;
181
+ float32[0 * numPixels + i] = data[srcBase] / 255;
182
+ float32[1 * numPixels + i] = data[srcBase + 1] / 255;
183
+ float32[2 * numPixels + i] = data[srcBase + 2] / 255;
184
+ }
185
+ return { data: float32, scale, padX, padY, originalWidth, originalHeight };
186
+ }
187
+ async function resizeAndNormalize(jpeg, targetWidth, targetHeight, normalization, layout) {
188
+ const { data } = await sharp(jpeg).resize(targetWidth, targetHeight, { fit: "fill" }).removeAlpha().raw().toBuffer({ resolveWithObject: true });
189
+ const numPixels = targetWidth * targetHeight;
190
+ const float32 = new Float32Array(3 * numPixels);
191
+ const mean = [0.485, 0.456, 0.406];
192
+ const std = [0.229, 0.224, 0.225];
193
+ if (layout === "nchw") {
194
+ for (let i = 0; i < numPixels; i++) {
195
+ const srcBase = i * 3;
196
+ for (let c = 0; c < 3; c++) {
197
+ const raw = data[srcBase + c] / 255;
198
+ let val;
199
+ if (normalization === "zero-one") {
200
+ val = raw;
201
+ } else if (normalization === "imagenet") {
202
+ val = (raw - mean[c]) / std[c];
203
+ } else {
204
+ val = data[srcBase + c];
205
+ }
206
+ float32[c * numPixels + i] = val;
207
+ }
208
+ }
209
+ } else {
210
+ for (let i = 0; i < numPixels; i++) {
211
+ const srcBase = i * 3;
212
+ for (let c = 0; c < 3; c++) {
213
+ const raw = data[srcBase + c] / 255;
214
+ let val;
215
+ if (normalization === "zero-one") {
216
+ val = raw;
217
+ } else if (normalization === "imagenet") {
218
+ val = (raw - mean[c]) / std[c];
219
+ } else {
220
+ val = data[srcBase + c];
221
+ }
222
+ float32[i * 3 + c] = val;
223
+ }
224
+ }
225
+ }
226
+ return float32;
227
+ }
228
+ const BACKEND_TO_PROVIDER = {
229
+ cpu: "cpu",
230
+ coreml: "coreml",
231
+ cuda: "cuda",
232
+ tensorrt: "tensorrt",
233
+ dml: "dml"
234
+ };
235
+ const BACKEND_TO_DEVICE = {
236
+ cpu: "cpu",
237
+ coreml: "gpu-mps",
238
+ cuda: "gpu-cuda",
239
+ tensorrt: "tensorrt"
240
+ };
241
+ class NodeInferenceEngine {
242
+ constructor(modelPath, backend, modelMeta, logger) {
243
+ this.modelPath = modelPath;
244
+ this.backend = backend;
245
+ this.modelMeta = modelMeta;
246
+ this.device = BACKEND_TO_DEVICE[backend] ?? "cpu";
247
+ this.log = logger ?? createNoopLogger();
248
+ }
249
+ runtime = "onnx";
250
+ device;
251
+ session = null;
252
+ log;
253
+ async initialize() {
254
+ const ort = await import("onnxruntime-node");
255
+ const provider = BACKEND_TO_PROVIDER[this.backend] ?? "cpu";
256
+ const absModelPath = path.isAbsolute(this.modelPath) ? this.modelPath : path.resolve(process.cwd(), this.modelPath);
257
+ const sessionOptions = {
258
+ executionProviders: [provider]
259
+ };
260
+ this.session = await ort.InferenceSession.create(absModelPath, sessionOptions);
261
+ this.log.info("ONNX session loaded", { meta: { modelPath: absModelPath, backend: this.backend, provider } });
262
+ }
263
+ async infer(input) {
264
+ const jpeg = input.kind === "jpeg" ? input.data : await this.encodeRawAsJpeg(input.data, input.width, input.height, input.format);
265
+ const { data, letterboxMeta } = await this.preprocess(jpeg);
266
+ const { inputSize } = this.modelMeta;
267
+ const inputShape = this.modelMeta.preprocessMode === "letterbox" ? [1, 3, inputSize.height, inputSize.width] : [1, 3, inputSize.height, inputSize.width];
268
+ const start = Date.now();
269
+ let result;
270
+ try {
271
+ result = await this.runSession(data, inputShape);
272
+ } catch (err) {
273
+ const error = err instanceof Error ? err : new Error(String(err));
274
+ this.log.error("Inference failed", { meta: { error: error.message } });
275
+ throw error;
276
+ }
277
+ const durationMs = Date.now() - start;
278
+ if ("tensor" in result) {
279
+ this.log.debug("Inference complete", { meta: { durationMs, outputKeys: ["tensor"], preprocessMode: this.modelMeta.preprocessMode } });
280
+ return { tensor: result.tensor, letterbox: letterboxMeta, inferenceMs: durationMs };
281
+ }
282
+ this.log.debug("Inference complete", { meta: { durationMs, outputKeys: Object.keys(result.tensors), preprocessMode: this.modelMeta.preprocessMode } });
283
+ return { tensors: result.tensors, letterbox: letterboxMeta, inferenceMs: durationMs };
284
+ }
285
+ /** Preprocess JPEG to Float32Array using the configured mode */
286
+ async preprocess(jpeg) {
287
+ const { inputSize, inputNormalization, inputLayout, preprocessMode } = this.modelMeta;
288
+ if (preprocessMode === "letterbox") {
289
+ const targetSize = Math.max(inputSize.width, inputSize.height);
290
+ const result = await letterbox(jpeg, targetSize);
291
+ const letterboxMeta = {
292
+ scale: result.scale,
293
+ padX: result.padX,
294
+ padY: result.padY,
295
+ originalWidth: result.originalWidth,
296
+ originalHeight: result.originalHeight
297
+ };
298
+ return { data: result.data, letterboxMeta };
299
+ }
300
+ const data = await resizeAndNormalize(
301
+ jpeg,
302
+ inputSize.width,
303
+ inputSize.height,
304
+ inputNormalization,
305
+ inputLayout
306
+ );
307
+ return { data };
308
+ }
309
+ async encodeRawAsJpeg(raw, width, height, format) {
310
+ const sharp2 = (await import("sharp")).default;
311
+ const channels = format === "gray" ? 1 : 3;
312
+ return sharp2(raw, { raw: { width, height, channels } }).jpeg({ quality: 80, mozjpeg: false }).toBuffer();
313
+ }
314
+ /** Run an ONNX session with a single input, handling both single and multi-output models */
315
+ async runSession(input, inputShape) {
316
+ if (!this.session) {
317
+ throw new Error("NodeInferenceEngine: not initialized — call initialize() first");
318
+ }
319
+ const ort = await import("onnxruntime-node");
320
+ const sess = this.session;
321
+ const inputName = sess.inputNames[0];
322
+ const tensor = new ort.Tensor("float32", input, [...inputShape]);
323
+ const feeds = { [inputName]: tensor };
324
+ const results = await sess.run(feeds);
325
+ const outputNames = sess.outputNames;
326
+ if (outputNames.length === 1) {
327
+ const outputName = outputNames[0];
328
+ return { tensor: results[outputName].data };
329
+ }
330
+ const tensors = {};
331
+ for (const name of outputNames) {
332
+ tensors[name] = results[name].data;
333
+ }
334
+ return { tensors };
335
+ }
336
+ async run(input, inputShape) {
337
+ const result = await this.runSession(input, inputShape);
338
+ if ("tensor" in result) return result.tensor;
339
+ const firstKey = Object.keys(result.tensors)[0];
340
+ return result.tensors[firstKey];
341
+ }
342
+ async dispose() {
343
+ this.session = null;
344
+ this.log.debug("Session disposed");
345
+ }
346
+ }
347
+ class PythonInferenceEngine {
348
+ constructor(pythonPath, scriptPath, runtime, modelPath, extraArgs = [], logger) {
349
+ this.pythonPath = pythonPath;
350
+ this.scriptPath = scriptPath;
351
+ this.modelPath = modelPath;
352
+ this.extraArgs = extraArgs;
353
+ this.runtime = runtime;
354
+ const runtimeDeviceMap = {
355
+ onnx: "cpu",
356
+ coreml: "gpu-mps",
357
+ pytorch: "cpu",
358
+ openvino: "cpu",
359
+ tflite: "cpu"
360
+ };
361
+ this.device = runtimeDeviceMap[runtime];
362
+ this.log = logger ?? createNoopLogger();
363
+ }
364
+ runtime;
365
+ device;
366
+ process = null;
367
+ receiveBuffer = Buffer.alloc(0);
368
+ pendingResolve = null;
369
+ pendingReject = null;
370
+ log;
371
+ async initialize() {
372
+ const args = [this.scriptPath, this.modelPath, ...this.extraArgs];
373
+ this.process = spawn(this.pythonPath, args, {
374
+ stdio: ["pipe", "pipe", "pipe"]
375
+ });
376
+ if (!this.process.stdout || !this.process.stdin) {
377
+ throw new Error("PythonInferenceEngine: failed to create process pipes");
378
+ }
379
+ this.log.info("Python process started", { meta: { pythonPath: this.pythonPath, scriptPath: this.scriptPath, modelPath: this.modelPath } });
380
+ this.process.stderr?.on("data", (chunk) => {
381
+ const lines = chunk.toString().split("\n");
382
+ for (const line of lines) {
383
+ const trimmed = line.trim();
384
+ if (trimmed) {
385
+ this.log.warn(trimmed);
386
+ }
387
+ }
388
+ });
389
+ this.process.on("error", (err) => {
390
+ this.log.error("Process error", { meta: { error: err.message } });
391
+ this.pendingReject?.(err);
392
+ this.pendingReject = null;
393
+ this.pendingResolve = null;
394
+ });
395
+ this.process.on("exit", (code) => {
396
+ if (code !== 0) {
397
+ this.log.error("Process exited", { meta: { code } });
398
+ const err = new Error(`PythonInferenceEngine: process exited with code ${code}`);
399
+ this.pendingReject?.(err);
400
+ this.pendingReject = null;
401
+ this.pendingResolve = null;
402
+ }
403
+ });
404
+ this.process.stdout.on("data", (chunk) => {
405
+ this.receiveBuffer = Buffer.concat([this.receiveBuffer, chunk]);
406
+ this._tryReceive();
407
+ });
408
+ await new Promise((resolve, reject) => {
409
+ const timeout = setTimeout(() => resolve(), 2e3);
410
+ this.process?.on("error", (err) => {
411
+ clearTimeout(timeout);
412
+ reject(err);
413
+ });
414
+ this.process?.on("exit", (code) => {
415
+ clearTimeout(timeout);
416
+ if (code !== 0) {
417
+ reject(new Error(`PythonInferenceEngine: process exited early with code ${code}`));
418
+ }
419
+ });
420
+ });
421
+ }
422
+ _tryReceive() {
423
+ if (this.receiveBuffer.length < 4) return;
424
+ const length = this.receiveBuffer.readUInt32LE(0);
425
+ if (this.receiveBuffer.length < 4 + length) return;
426
+ const jsonBytes = this.receiveBuffer.subarray(4, 4 + length);
427
+ this.receiveBuffer = this.receiveBuffer.subarray(4 + length);
428
+ const resolve = this.pendingResolve;
429
+ const reject = this.pendingReject;
430
+ this.pendingResolve = null;
431
+ this.pendingReject = null;
432
+ if (!resolve) return;
433
+ try {
434
+ const parsed = JSON.parse(jsonBytes.toString("utf8"));
435
+ resolve(parsed);
436
+ } catch (err) {
437
+ reject?.(err instanceof Error ? err : new Error(String(err)));
438
+ }
439
+ }
440
+ /** Run inference, returning structured detection results. Encodes raw input to JPEG when needed. */
441
+ async infer(input) {
442
+ const start = Date.now();
443
+ const jpeg = input.kind === "jpeg" ? input.data : await this.encodeRawAsJpeg(input.data, input.width, input.height, input.format);
444
+ const result = await this.sendJpeg(jpeg);
445
+ const durationMs = Date.now() - start;
446
+ this.log.debug("Inference complete", { meta: { durationMs } });
447
+ return { structured: result, inferenceMs: durationMs };
448
+ }
449
+ async encodeRawAsJpeg(raw, width, height, format) {
450
+ const sharp2 = (await import("sharp")).default;
451
+ const channels = format === "gray" ? 1 : 3;
452
+ return sharp2(raw, { raw: { width, height, channels } }).jpeg({ quality: 80, mozjpeg: false }).toBuffer();
453
+ }
454
+ /** Send JPEG buffer via binary IPC, receive JSON detection results */
455
+ async sendJpeg(jpeg) {
456
+ if (!this.process?.stdin) {
457
+ throw new Error("PythonInferenceEngine: process not initialized");
458
+ }
459
+ return new Promise((resolve, reject) => {
460
+ this.pendingResolve = resolve;
461
+ this.pendingReject = reject;
462
+ const lengthBuf = Buffer.allocUnsafe(4);
463
+ lengthBuf.writeUInt32LE(jpeg.length, 0);
464
+ this.process.stdin.write(Buffer.concat([lengthBuf, jpeg]));
465
+ });
466
+ }
467
+ async dispose() {
468
+ const proc = this.process;
469
+ if (!proc) return;
470
+ this.process = null;
471
+ proc.stdin?.end();
472
+ proc.kill("SIGTERM");
473
+ const exited = await new Promise((resolve) => {
474
+ const timer = setTimeout(() => {
475
+ resolve(false);
476
+ }, 5e3);
477
+ proc.once("exit", () => {
478
+ clearTimeout(timer);
479
+ resolve(true);
480
+ });
481
+ });
482
+ if (!exited) {
483
+ try {
484
+ proc.kill("SIGKILL");
485
+ } catch {
486
+ }
487
+ this.log.warn("Python process did not exit gracefully — sent SIGKILL");
488
+ } else {
489
+ this.log.debug("Python process terminated");
490
+ }
491
+ }
492
+ }
493
+ const AUTO_BACKEND_PRIORITY = ["coreml", "cuda", "tensorrt", "cpu"];
494
+ const BACKEND_TO_FORMAT = BACKEND_TO_FORMAT$1;
495
+ const RUNTIME_TO_FORMAT = RUNTIME_TO_FORMAT$1;
496
+ function extractModelMeta(entry) {
497
+ return {
498
+ inputSize: entry.inputSize,
499
+ inputNormalization: entry.inputNormalization ?? "zero-one",
500
+ inputLayout: entry.inputLayout ?? "nchw",
501
+ preprocessMode: entry.preprocessMode ?? "letterbox"
502
+ };
503
+ }
504
+ function modelFilePath(modelsDir, modelEntry, format) {
505
+ const formatEntry = modelEntry.formats[format];
506
+ if (!formatEntry) {
507
+ throw new Error(`Model ${modelEntry.id} has no ${format} format`);
508
+ }
509
+ const urlParts = formatEntry.url.split("/");
510
+ const filename = urlParts[urlParts.length - 1] ?? `${modelEntry.id}.${format}`;
511
+ return path.join(modelsDir, filename);
512
+ }
513
+ function modelExists(filePath) {
514
+ try {
515
+ return fs.existsSync(filePath);
516
+ } catch {
517
+ return false;
518
+ }
519
+ }
520
+ async function resolveEngine(options) {
521
+ const { runtime, backend, modelEntry, modelsDir, models } = options;
522
+ const log = options.logger ?? createNoopLogger();
523
+ let selectedFormat;
524
+ let selectedBackend;
525
+ if (runtime === "auto") {
526
+ const available = await probeOnnxBackends();
527
+ let chosen = null;
528
+ for (const b of AUTO_BACKEND_PRIORITY) {
529
+ if (!available.includes(b)) continue;
530
+ const fmt = BACKEND_TO_FORMAT[b];
531
+ if (!fmt) continue;
532
+ if (!modelEntry.formats[fmt]) continue;
533
+ chosen = { backend: b, format: fmt };
534
+ break;
535
+ }
536
+ if (!chosen) {
537
+ throw new Error(
538
+ `resolveEngine: no compatible backend found for model ${modelEntry.id}. Available backends: ${available.join(", ")}`
539
+ );
540
+ }
541
+ selectedFormat = chosen.format;
542
+ selectedBackend = chosen.backend;
543
+ } else {
544
+ const fmt = RUNTIME_TO_FORMAT[runtime];
545
+ if (!fmt) {
546
+ throw new Error(`resolveEngine: unsupported runtime "${runtime}"`);
547
+ }
548
+ if (!modelEntry.formats[fmt]) {
549
+ if (fmt !== "onnx" && modelEntry.formats["onnx"]) {
550
+ selectedFormat = "onnx";
551
+ selectedBackend = backend || "cpu";
552
+ } else {
553
+ throw new Error(
554
+ `resolveEngine: model ${modelEntry.id} has no ${fmt} format for runtime ${runtime}`
555
+ );
556
+ }
557
+ } else {
558
+ selectedFormat = fmt;
559
+ selectedBackend = runtime === "onnx" ? backend || "cpu" : runtime;
560
+ }
561
+ }
562
+ let modelPath;
563
+ if (models) {
564
+ modelPath = await models.ensure(modelEntry.id, selectedFormat);
565
+ } else {
566
+ modelPath = modelFilePath(modelsDir, modelEntry, selectedFormat);
567
+ if (!modelExists(modelPath)) {
568
+ throw new Error(
569
+ `resolveEngine: model file not found at ${modelPath} and no model service provided`
570
+ );
571
+ }
572
+ }
573
+ log.info("Engine resolved", { meta: { format: selectedFormat, backend: selectedBackend, modelId: modelEntry.id } });
574
+ if (selectedFormat === "onnx") {
575
+ const engine = new NodeInferenceEngine(modelPath, selectedBackend, extractModelMeta(modelEntry), options.logger);
576
+ await engine.initialize();
577
+ return { engine, format: selectedFormat, modelPath };
578
+ }
579
+ const effectiveRuntime = runtime === "auto" ? selectedBackend : runtime;
580
+ let { pythonPath } = options;
581
+ if (!pythonPath) {
582
+ const { execFileSync: efs } = await import("node:child_process");
583
+ for (const cmd of ["python3", "python"]) {
584
+ try {
585
+ efs(cmd, ["--version"], { timeout: 3e3, stdio: "ignore" });
586
+ pythonPath = cmd;
587
+ break;
588
+ } catch {
589
+ }
590
+ }
591
+ }
592
+ const scriptName = PYTHON_SCRIPT[effectiveRuntime];
593
+ if (scriptName && pythonPath) {
594
+ const candidates = [
595
+ path.join(__dirname, "../../python", scriptName),
596
+ path.join(__dirname, "../python", scriptName),
597
+ path.join(__dirname, "../../../python", scriptName)
598
+ ];
599
+ const scriptPath = candidates.find((p) => fs.existsSync(p));
600
+ if (!scriptPath) {
601
+ throw new Error(
602
+ `resolveEngine: Python script "${scriptName}" not found. Searched:
603
+ ${candidates.join("\n")}`
604
+ );
605
+ }
606
+ const inputSize = Math.max(modelEntry.inputSize.width, modelEntry.inputSize.height);
607
+ const engine = new PythonInferenceEngine(pythonPath, scriptPath, effectiveRuntime, modelPath, [
608
+ `--input-size=${inputSize}`,
609
+ `--confidence=0.25`
610
+ ], options.logger);
611
+ await engine.initialize();
612
+ return { engine, format: selectedFormat, modelPath };
613
+ }
614
+ const fallbackPath = modelFilePath(modelsDir, modelEntry, "onnx");
615
+ if (modelEntry.formats["onnx"] && modelExists(fallbackPath)) {
616
+ const engine = new NodeInferenceEngine(fallbackPath, "cpu", extractModelMeta(modelEntry), options.logger);
617
+ await engine.initialize();
618
+ return { engine, format: "onnx", modelPath: fallbackPath };
619
+ }
620
+ throw new Error(
621
+ `resolveEngine: format ${selectedFormat} is not yet supported by NodeInferenceEngine, no Python runtime is available, and no ONNX fallback exists`
622
+ );
623
+ }
624
+ async function probeOnnxBackends() {
625
+ const available = ["cpu"];
626
+ try {
627
+ const ort = await import("onnxruntime-node");
628
+ const providers = ort.env?.webgl?.disabled !== void 0 ? ort.InferenceSession.getAvailableProviders?.() ?? [] : [];
629
+ for (const p of providers) {
630
+ const normalized = p.toLowerCase().replace("executionprovider", "");
631
+ if (normalized === "coreml") available.push("coreml");
632
+ else if (normalized === "cuda") available.push("cuda");
633
+ else if (normalized === "tensorrt") available.push("tensorrt");
634
+ }
635
+ } catch {
636
+ }
637
+ if (process.platform === "darwin" && !available.includes("coreml")) {
638
+ available.push("coreml");
639
+ }
640
+ return [...new Set(available)];
641
+ }
642
+ const CLIP_MODEL_META = {
643
+ "clip-vit-b32": {
644
+ imageModelId: "clip-vit-b32",
645
+ textModelId: "clip-vit-b32-text",
646
+ embeddingDim: 512,
647
+ inputSize: 224,
648
+ tokenizerType: "clip"
649
+ },
650
+ "clip-vit-b16": {
651
+ imageModelId: "clip-vit-b16",
652
+ textModelId: "clip-vit-b16-text",
653
+ embeddingDim: 512,
654
+ inputSize: 224,
655
+ tokenizerType: "clip"
656
+ },
657
+ "siglip2-b16-256": {
658
+ imageModelId: "siglip2-b16-256",
659
+ textModelId: "siglip2-b16-256-text",
660
+ embeddingDim: 768,
661
+ inputSize: 256,
662
+ tokenizerType: "siglip"
663
+ }
664
+ };
665
+ const DEFAULT_CLIP_MODEL = "clip-vit-b32";
666
+ function getModelMeta(modelId) {
667
+ return CLIP_MODEL_META[modelId] ?? CLIP_MODEL_META[DEFAULT_CLIP_MODEL];
668
+ }
669
+ const CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073];
670
+ const CLIP_STD = [0.26862954, 0.26130258, 0.27577711];
671
+ function preprocessForClip(rgb, srcWidth, srcHeight, targetWidth, targetHeight) {
672
+ const pixels = targetWidth * targetHeight;
673
+ const result = new Float32Array(3 * pixels);
674
+ for (let y = 0; y < targetHeight; y++) {
675
+ for (let x = 0; x < targetWidth; x++) {
676
+ const srcX = Math.min(Math.floor(x / targetWidth * srcWidth), srcWidth - 1);
677
+ const srcY = Math.min(Math.floor(y / targetHeight * srcHeight), srcHeight - 1);
678
+ const srcIdx = (srcY * srcWidth + srcX) * 3;
679
+ const dstIdx = y * targetWidth + x;
680
+ for (let c = 0; c < 3; c++) {
681
+ const val = (rgb[srcIdx + c] ?? 0) / 255;
682
+ result[c * pixels + dstIdx] = (val - CLIP_MEAN[c]) / CLIP_STD[c];
683
+ }
684
+ }
685
+ }
686
+ return result;
687
+ }
688
+ function l2Normalize(vec) {
689
+ let norm = 0;
690
+ for (let i = 0; i < vec.length; i++) norm += vec[i] * vec[i];
691
+ norm = Math.sqrt(norm);
692
+ if (norm > 0) {
693
+ for (let i = 0; i < vec.length; i++) vec[i] /= norm;
694
+ }
695
+ return vec;
696
+ }
697
+ class EmbeddingEncoderAddon extends BaseAddon {
698
+ imageRawEngine = null;
699
+ textRawEngine = null;
700
+ imagePythonEngine = null;
701
+ textPythonEngine = null;
702
+ models = null;
703
+ isPython = false;
704
+ constructor() {
705
+ super({ modelId: DEFAULT_CLIP_MODEL, runtime: "auto", backend: "cpu" });
706
+ }
707
+ async onInitialize() {
708
+ const modelsDir = await this.ctx.api.storage.resolve.query({ location: "models", relativePath: "" }).catch(() => "camstack-data/models");
709
+ this.models = new ModelDownloadService(modelsDir, []);
710
+ return [{ capability: embeddingEncoderCapability, provider: this }];
711
+ }
712
+ async encode(crop, width, height) {
713
+ await this.ensureImageEngine();
714
+ const meta = getModelMeta(this.config.modelId);
715
+ const start = Date.now();
716
+ if (this.isPython && this.imagePythonEngine) {
717
+ const result = await this.imagePythonEngine.infer({ kind: "jpeg", data: crop });
718
+ const rawEmbedding = result.structured?.["embedding"];
719
+ const embedding = new Float32Array(rawEmbedding);
720
+ return {
721
+ embedding: l2Normalize(embedding),
722
+ inferenceMs: result.inferenceMs ?? Date.now() - start
723
+ };
724
+ }
725
+ const preprocessed = preprocessForClip(crop, width, height, meta.inputSize, meta.inputSize);
726
+ const output = await this.imageRawEngine.run(preprocessed, [1, 3, meta.inputSize, meta.inputSize]);
727
+ const sliced = output.length > meta.embeddingDim ? output.slice(0, meta.embeddingDim) : output;
728
+ return {
729
+ embedding: l2Normalize(new Float32Array(sliced)),
730
+ inferenceMs: Date.now() - start
731
+ };
732
+ }
733
+ async encodeText(text) {
734
+ await this.ensureTextEngine();
735
+ const meta = getModelMeta(this.config.modelId);
736
+ const start = Date.now();
737
+ if (this.isPython && this.textPythonEngine) {
738
+ const textBuffer = Buffer.from(JSON.stringify({ text }), "utf-8");
739
+ const result = await this.textPythonEngine.infer({ kind: "jpeg", data: textBuffer });
740
+ const rawEmbedding = result.structured?.["embedding"];
741
+ const embedding = new Float32Array(rawEmbedding);
742
+ return {
743
+ embedding: l2Normalize(embedding),
744
+ inferenceMs: result.inferenceMs ?? Date.now() - start
745
+ };
746
+ }
747
+ const tokenIds = clipTokenize(text);
748
+ const inputTensor = new Float32Array(tokenIds);
749
+ const output = await this.textRawEngine.run(inputTensor, [1, tokenIds.length]);
750
+ const sliced = output.length > meta.embeddingDim ? output.slice(0, meta.embeddingDim) : output;
751
+ return {
752
+ embedding: l2Normalize(new Float32Array(sliced)),
753
+ inferenceMs: Date.now() - start
754
+ };
755
+ }
756
+ getInfo() {
757
+ const meta = getModelMeta(this.config.modelId);
758
+ return {
759
+ modelId: this.config.modelId,
760
+ embeddingDim: meta.embeddingDim,
761
+ ready: this.imageRawEngine !== null || this.imagePythonEngine !== null
762
+ };
763
+ }
764
+ async ensureImageEngine() {
765
+ if (this.imageRawEngine || this.imagePythonEngine) return;
766
+ const meta = getModelMeta(this.config.modelId);
767
+ const imageEntry = CLIP_IMAGE_MODELS.find((m) => m.id === meta.imageModelId);
768
+ if (!imageEntry) {
769
+ throw new Error(`EmbeddingEncoderAddon: unknown image model "${meta.imageModelId}"`);
770
+ }
771
+ await this.resolveForEntry(imageEntry, "image");
772
+ }
773
+ async ensureTextEngine() {
774
+ if (this.textRawEngine || this.textPythonEngine) return;
775
+ const meta = getModelMeta(this.config.modelId);
776
+ const textEntry = CLIP_TEXT_MODELS.find((m) => m.id === meta.textModelId);
777
+ if (!textEntry) {
778
+ throw new Error(`EmbeddingEncoderAddon: unknown text model "${meta.textModelId}"`);
779
+ }
780
+ await this.resolveForEntry(textEntry, "text");
781
+ }
782
+ async resolveForEntry(entry, target) {
783
+ const runtime = this.config.runtime === "auto" ? "auto" : this.config.runtime === "node" ? "onnx" : this.config.runtime;
784
+ const modelsDir = this.models.getModelsDir();
785
+ const engineLogger = this.ctx.logger.withTags({
786
+ modelId: entry.id,
787
+ runtime: this.config.runtime,
788
+ backend: this.config.backend
789
+ });
790
+ await this.models.ensure(entry.id, "onnx");
791
+ const resolved = await resolveEngine({
792
+ runtime,
793
+ backend: this.config.backend,
794
+ modelEntry: entry,
795
+ modelsDir,
796
+ models: this.models ?? void 0,
797
+ logger: engineLogger
798
+ });
799
+ if (resolved.format !== "onnx") {
800
+ this.isPython = true;
801
+ if (target === "image") {
802
+ this.imagePythonEngine = resolved.engine;
803
+ } else {
804
+ this.textPythonEngine = resolved.engine;
805
+ }
806
+ } else {
807
+ const rawEngine = new NodeRawTensorEngine(resolved.modelPath, this.config.backend, engineLogger);
808
+ await rawEngine.initialize();
809
+ await resolved.engine.dispose();
810
+ if (target === "image") {
811
+ this.imageRawEngine = rawEngine;
812
+ } else {
813
+ this.textRawEngine = rawEngine;
814
+ }
815
+ }
816
+ }
817
+ async onShutdown() {
818
+ await this.imageRawEngine?.dispose();
819
+ await this.textRawEngine?.dispose();
820
+ await this.imagePythonEngine?.dispose();
821
+ await this.textPythonEngine?.dispose();
822
+ }
823
+ // ── Three-level settings API (Phase 3) ──────────────────────────────
824
+ globalSettingsSchema() {
825
+ return this.schema({
826
+ sections: [
827
+ {
828
+ id: "embedding-encoder-settings",
829
+ title: "Embedding Encoder",
830
+ columns: 2,
831
+ fields: [
832
+ {
833
+ type: "text",
834
+ key: "modelId",
835
+ label: "Model ID",
836
+ description: "CLIP model identifier to use for image/text embedding",
837
+ default: DEFAULT_CLIP_MODEL
838
+ },
839
+ {
840
+ type: "select",
841
+ key: "runtime",
842
+ label: "Runtime",
843
+ description: "Inference runtime (auto selects the best available)",
844
+ default: "auto",
845
+ options: [
846
+ { label: "Auto", value: "auto" },
847
+ { label: "Node (ONNX)", value: "node" },
848
+ { label: "Python", value: "python" }
849
+ ]
850
+ },
851
+ {
852
+ type: "select",
853
+ key: "backend",
854
+ label: "Backend",
855
+ description: "Hardware backend for inference acceleration",
856
+ default: "cpu",
857
+ options: [
858
+ { label: "CPU", value: "cpu" },
859
+ { label: "CUDA", value: "cuda" },
860
+ { label: "CoreML", value: "coreml" }
861
+ ]
862
+ }
863
+ ]
864
+ }
865
+ ]
866
+ });
867
+ }
868
+ async onConfigChanged() {
869
+ }
870
+ }
871
+ function clipTokenize(text, maxLength = 77) {
872
+ const SOT_TOKEN = 49406;
873
+ const EOT_TOKEN = 49407;
874
+ const tokens = [SOT_TOKEN];
875
+ for (let i = 0; i < text.length && tokens.length < maxLength - 1; i++) {
876
+ tokens.push(text.charCodeAt(i) + 256);
877
+ }
878
+ tokens.push(EOT_TOKEN);
879
+ while (tokens.length < maxLength) {
880
+ tokens.push(0);
881
+ }
882
+ return tokens;
883
+ }
884
+ export {
885
+ EmbeddingEncoderAddon,
886
+ EmbeddingEncoderAddon as default
887
+ };
888
+ //# sourceMappingURL=index.mjs.map