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