tempest-react-sdk 0.38.3 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/vision/core/canvas.cjs +1 -1
- package/dist/vision/core/canvas.cjs.map +1 -1
- package/dist/vision/core/canvas.js +4 -4
- package/dist/vision/core/canvas.js.map +1 -1
- package/dist/vision/core/exceptions.cjs +1 -1
- package/dist/vision/core/exceptions.cjs.map +1 -1
- package/dist/vision/core/exceptions.js +2 -2
- package/dist/vision/core/exceptions.js.map +1 -1
- package/dist/vision/core/metadata.cjs +2 -2
- package/dist/vision/core/metadata.cjs.map +1 -1
- package/dist/vision/core/metadata.js +10 -7
- package/dist/vision/core/metadata.js.map +1 -1
- package/dist/vision/core/session.cjs +1 -1
- package/dist/vision/core/session.cjs.map +1 -1
- package/dist/vision/core/session.js +8 -5
- package/dist/vision/core/session.js.map +1 -1
- package/dist/vision/fusion.cjs +2 -0
- package/dist/vision/fusion.cjs.map +1 -0
- package/dist/vision/fusion.js +42 -0
- package/dist/vision/fusion.js.map +1 -0
- package/dist/vision/index.cjs +1 -1
- package/dist/vision/index.cjs.map +1 -1
- package/dist/vision/index.js +23 -20
- package/dist/vision/index.js.map +1 -1
- package/dist/vision/labels.cjs +1 -1
- package/dist/vision/labels.cjs.map +1 -1
- package/dist/vision/labels.js +7 -4
- package/dist/vision/labels.js.map +1 -1
- package/dist/vision/postprocess/detection.cjs +1 -1
- package/dist/vision/postprocess/detection.cjs.map +1 -1
- package/dist/vision/postprocess/detection.js +3 -10
- package/dist/vision/postprocess/detection.js.map +1 -1
- package/dist/vision/postprocess/segmentation.cjs +1 -1
- package/dist/vision/postprocess/segmentation.cjs.map +1 -1
- package/dist/vision/postprocess/segmentation.js +11 -15
- package/dist/vision/postprocess/segmentation.js.map +1 -1
- package/dist/vision/preprocess/pipeline.cjs +2 -0
- package/dist/vision/preprocess/pipeline.cjs.map +1 -0
- package/dist/vision/preprocess/pipeline.js +61 -0
- package/dist/vision/preprocess/pipeline.js.map +1 -0
- package/dist/vision/results.cjs +1 -1
- package/dist/vision/results.cjs.map +1 -1
- package/dist/vision/results.js +23 -2
- package/dist/vision/results.js.map +1 -1
- package/dist/vision/tasks/base.cjs +1 -1
- package/dist/vision/tasks/base.cjs.map +1 -1
- package/dist/vision/tasks/base.js +9 -2
- package/dist/vision/tasks/base.js.map +1 -1
- package/dist/vision/tasks/detectClassify.cjs +2 -0
- package/dist/vision/tasks/detectClassify.cjs.map +1 -0
- package/dist/vision/tasks/detectClassify.js +221 -0
- package/dist/vision/tasks/detectClassify.js.map +1 -0
- package/dist/vision/tasks/detector.cjs +1 -1
- package/dist/vision/tasks/detector.cjs.map +1 -1
- package/dist/vision/tasks/detector.js +54 -29
- package/dist/vision/tasks/detector.js.map +1 -1
- package/dist/vision/tasks/segmenter.cjs +1 -1
- package/dist/vision/tasks/segmenter.cjs.map +1 -1
- package/dist/vision/tasks/segmenter.js +53 -28
- package/dist/vision/tasks/segmenter.js.map +1 -1
- package/dist/vision/types.cjs.map +1 -1
- package/dist/vision/types.js.map +1 -1
- package/dist/vision.cjs +1 -1
- package/dist/vision.d.ts +1517 -962
- package/dist/vision.js +25 -22
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -279,7 +279,7 @@ Every module is re-exported from the package root — `import { Button, useDebou
|
|
|
279
279
|
| `push` | `WebPushClient`, `WebPushUnsupportedError`, `WebPushPermissionDeniedError`, `usePushSubscription`, `urlBase64ToUint8Array`, `isPushSupported` |
|
|
280
280
|
| `sw` _(also subpath `tempest-react-sdk/sw`)_ | `registerServiceWorker` (opt-in `autoUpdate` poll + reload, no `vite-plugin-pwa`), `skipWaiting`, `unregisterAllServiceWorkers`, `installPushHandler`, `installNotificationClickHandler`, `installSkipWaitingListener`, `installPrecache` (app-shell offline + Navigation Preload), `installRuntimeCache` (per-route caching, incl. `rangeRequests`), `createPartialResponse` (206 range slicing), `installBackgroundSync` (offline mutation queue + `periodicsync`), `registerPeriodicSync` (main-thread periodic sync), `inspectCaches`/`clearCaches` (cache observability) — the React-free `tempest-react-sdk/sw` subpath is ideal for bundling into your own `sw.ts` |
|
|
281
281
|
| `editor` _(subpath `tempest-react-sdk/editor`, opt. peers `@tiptap/react`+`@tiptap/starter-kit`)_ | `RichTextEditor` — themed tiptap v3 rich-text editor with toolbar (tiptap externalized; install it only if you use the editor) |
|
|
282
|
-
| `vision` _(subpath `tempest-react-sdk/vision`, opt. peer `onnxruntime-web`)_ | `Classifier`, `Detector`, `Segmenter` + results/labels/preprocess — on-device ONNX vision inference, vendored from `@mauriciobenjamin700/ort-vision-sdk-web` (onnxruntime-web externalized; install it only if you use vision). Plus browser capture primitives: `useCameraStream` (rear-camera `getUserMedia` + classified errors + `retry()`), `computeImageLuminance`/`isLuminanceAcceptable`/`LowLuminanceError`/`LUMINANCE_SAMPLE_MAX_EDGE` (BT.709 brightness), `useLiveLuminance` (live rAF sampling)
|
|
282
|
+
| `vision` _(subpath `tempest-react-sdk/vision`, opt. peer `onnxruntime-web`)_ | `Classifier`, `Detector`, `Segmenter`, `DetectClassify` (fused detect→classify pipeline) + `warmup()`, `raiseOnEmpty`/`NoDetectionsError`, `LetterboxPipeline`, `readFusionSpec` and results/labels/preprocess — on-device ONNX vision inference, vendored from `@mauriciobenjamin700/ort-vision-sdk-web` (onnxruntime-web externalized; install it only if you use vision). Plus browser capture primitives: `useCameraStream` (rear-camera `getUserMedia` + classified errors + `retry()`), `computeImageLuminance`/`isLuminanceAcceptable`/`LowLuminanceError`/`LUMINANCE_SAMPLE_MAX_EDGE` (BT.709 brightness), `useLiveLuminance` (live rAF sampling) |
|
|
283
283
|
| `tabular` _(subpath `tempest-react-sdk/tabular`, opt. peer `onnxruntime-web`)_ | `TabularPredictor`, `useTabularPredictor` — scikit-learn models exported by `tempest-fastapi-sdk`'s `export_sklearn_to_onnx`, running in the browser with no inference server. Offline by design: `fetchModelBytes`/`isModelCached`/`cacheModelBytes`/`clearModelCache` (Cache Storage, cache-first) plus `configureOrtAssets`/`ortAssetUrls`/`ORT_WASM_ASSETS` for the runtime's WebAssembly binaries, which ONNX Runtime Web fetches at session creation. Import the default `onnxruntime-web` entry — the WebGPU build has no `ai.onnx.ml` kernels |
|
|
284
284
|
| `imaging` _(subpath `tempest-react-sdk/imaging`, no deps)_ | `resizeImage`, `cropImage`, `rotateImage`, `flipImage`, `compressToTarget` (binary-searches quality into a byte budget), `createThumbnails` (several sizes from one decode), `decodeImage`/`readImageInfo`, `encodeImage`, `supportsImageType`/`bestSupportedType`, plus `useImagePreview`/`useImageProcessing`. Canvas only — decodes with EXIF orientation applied (phone photos arrive upright), reports the format actually produced (asking for AVIF where there is no encoder silently returns PNG), and re-encoding drops EXIF, which is the privacy step as much as the bandwidth one |
|
|
285
285
|
| `audio` | `createAudioPlayer`, `playAudio`, `stopAudio`, `useAudio` |
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./exceptions.cjs"),t=require("../types.cjs");function n(t,n){if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(t,n);if(typeof document<`u`){let e=document.createElement(`canvas`);return e.width=t,e.height=n,e}throw new e.ImageLoadError(`No canvas implementation available in this environment.`)}function r(t){let
|
|
1
|
+
const e=require("./exceptions.cjs"),t=require("../types.cjs");function n(t,n){if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(t,n);if(typeof document<`u`){let e=document.createElement(`canvas`);return e.width=t,e.height=n,e}throw new e.ImageLoadError(`No canvas implementation available in this environment.`)}function r(t,n={}){let r=t.getContext(`2d`,n);if(r===null)throw new e.ImageLoadError(`Failed to obtain 2D rendering context.`);return r}function i(n){let{data:r,width:i,height:a}=n;if(r.length!==i*a*4)throw new e.ImageLoadError(`Unexpected ImageData length ${r.length} for ${i}x${a} (expected ${i*a*4}).`);let o=new Uint8Array(i*a*3);for(let e=0,t=0;e<r.length;e+=4,t+=3)o[t]=r[e],o[t+1]=r[e+1],o[t+2]=r[e+2];return new t.RGBImage(o,i,a)}function a(e){let t=new Uint8ClampedArray(e.width*e.height*4);for(let n=0,r=0;n<e.data.length;n+=3,r+=4)t[r]=e.data[n],t[r+1]=e.data[n+1],t[r+2]=e.data[n+2],t[r+3]=255;return new ImageData(t,e.width,e.height)}exports.createCanvas=n,exports.get2DContext=r,exports.imageDataToRGB=i,exports.rgbToImageData=a;
|
|
2
2
|
//# sourceMappingURL=canvas.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"canvas.cjs","names":[],"sources":["../../../src/vision/core/canvas.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Canvas plumbing shared by `io/image.ts` and `preprocess/image.ts`.\n *\n * Browsers and workers expose two canvas types (`HTMLCanvasElement` and\n * `OffscreenCanvas`) with slightly different surfaces. These helpers pick the\n * right one for the current environment, return a unified 2D context, and\n * convert between RGBA `ImageData` and the SDK's canonical HWC RGB\n * `RGBImage`.\n */\n\nimport { ImageLoadError } from \"./exceptions\";\nimport { RGBImage } from \"../types\";\n\nexport type Canvas2D = HTMLCanvasElement | OffscreenCanvas;\nexport type Context2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\n\n/** Allocate a `Canvas2D`, preferring `OffscreenCanvas` when available. */\nexport function createCanvas(width: number, height: number): Canvas2D {\n if (typeof OffscreenCanvas !== \"undefined\") {\n return new OffscreenCanvas(width, height);\n }\n if (typeof document !== \"undefined\") {\n const c = document.createElement(\"canvas\");\n c.width = width;\n c.height = height;\n return c;\n }\n throw new ImageLoadError(\"No canvas implementation available in this environment.\");\n}\n\n
|
|
1
|
+
{"version":3,"file":"canvas.cjs","names":[],"sources":["../../../src/vision/core/canvas.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Canvas plumbing shared by `io/image.ts` and `preprocess/image.ts`.\n *\n * Browsers and workers expose two canvas types (`HTMLCanvasElement` and\n * `OffscreenCanvas`) with slightly different surfaces. These helpers pick the\n * right one for the current environment, return a unified 2D context, and\n * convert between RGBA `ImageData` and the SDK's canonical HWC RGB\n * `RGBImage`.\n */\n\nimport { ImageLoadError } from \"./exceptions\";\nimport { RGBImage } from \"../types\";\n\nexport type Canvas2D = HTMLCanvasElement | OffscreenCanvas;\nexport type Context2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\n\n/** Allocate a `Canvas2D`, preferring `OffscreenCanvas` when available. */\nexport function createCanvas(width: number, height: number): Canvas2D {\n if (typeof OffscreenCanvas !== \"undefined\") {\n return new OffscreenCanvas(width, height);\n }\n if (typeof document !== \"undefined\") {\n const c = document.createElement(\"canvas\");\n c.width = width;\n c.height = height;\n return c;\n }\n throw new ImageLoadError(\"No canvas implementation available in this environment.\");\n}\n\n/**\n * Get a 2D context from a canvas, throwing a typed error if the browser refuses.\n *\n * @param canvas The canvas to obtain a context for.\n * @param options Context attributes, forwarded verbatim. `willReadFrequently`\n * tells the browser the canvas is read back with `getImageData` repeatedly,\n * which moves the backing store to software: faster readback, slower\n * compositing. Whether it pays depends on the surface, so it is the caller's\n * call rather than a default here.\n */\nexport function get2DContext(\n canvas: Canvas2D,\n options: CanvasRenderingContext2DSettings = {},\n): Context2D {\n const ctx = canvas.getContext(\"2d\", options) as Context2D | null;\n if (ctx === null) {\n throw new ImageLoadError(\"Failed to obtain 2D rendering context.\");\n }\n return ctx;\n}\n\n/** Convert RGBA `ImageData` into the canonical HWC RGB `RGBImage`. */\nexport function imageDataToRGB(imageData: ImageData): RGBImage {\n const { data, width, height } = imageData;\n if (data.length !== width * height * 4) {\n throw new ImageLoadError(\n `Unexpected ImageData length ${data.length} for ${width}x${height} (expected ${\n width * height * 4\n }).`,\n );\n }\n const rgb = new Uint8Array(width * height * 3);\n for (let i = 0, j = 0; i < data.length; i += 4, j += 3) {\n rgb[j] = data[i] as number;\n rgb[j + 1] = data[i + 1] as number;\n rgb[j + 2] = data[i + 2] as number;\n }\n return new RGBImage(rgb, width, height);\n}\n\n/** Convert an `RGBImage` into RGBA `ImageData` (alpha forced to 255). */\nexport function rgbToImageData(image: RGBImage): ImageData {\n const data = new Uint8ClampedArray(image.width * image.height * 4);\n for (let i = 0, j = 0; i < image.data.length; i += 3, j += 4) {\n data[j] = image.data[i] as number;\n data[j + 1] = image.data[i + 1] as number;\n data[j + 2] = image.data[i + 2] as number;\n data[j + 3] = 255;\n }\n return new ImageData(data, image.width, image.height);\n}\n"],"mappings":"8DAkBA,SAAgB,EAAa,EAAe,EAA0B,CAClE,GAAI,OAAO,gBAAoB,IAC3B,OAAO,IAAI,gBAAgB,EAAO,CAAM,EAE5C,GAAI,OAAO,SAAa,IAAa,CACjC,IAAM,EAAI,SAAS,cAAc,QAAQ,EAGzC,MAFA,GAAE,MAAQ,EACV,EAAE,OAAS,EACJ,CACX,CACA,MAAM,IAAI,EAAA,eAAe,yDAAyD,CACtF,CAYA,SAAgB,EACZ,EACA,EAA4C,CAAC,EACpC,CACT,IAAM,EAAM,EAAO,WAAW,KAAM,CAAO,EAC3C,GAAI,IAAQ,KACR,MAAM,IAAI,EAAA,eAAe,wCAAwC,EAErE,OAAO,CACX,CAGA,SAAgB,EAAe,EAAgC,CAC3D,GAAM,CAAE,OAAM,QAAO,UAAW,EAChC,GAAI,EAAK,SAAW,EAAQ,EAAS,EACjC,MAAM,IAAI,EAAA,eACN,+BAA+B,EAAK,OAAO,OAAO,EAAM,GAAG,EAAO,aAC9D,EAAQ,EAAS,EACpB,GACL,EAEJ,IAAM,EAAM,IAAI,WAAW,EAAQ,EAAS,CAAC,EAC7C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAG,EAAI,EAAK,OAAQ,GAAK,EAAG,GAAK,EACjD,EAAI,GAAK,EAAK,GACd,EAAI,EAAI,GAAK,EAAK,EAAI,GACtB,EAAI,EAAI,GAAK,EAAK,EAAI,GAE1B,OAAO,IAAI,EAAA,SAAS,EAAK,EAAO,CAAM,CAC1C,CAGA,SAAgB,EAAe,EAA4B,CACvD,IAAM,EAAO,IAAI,kBAAkB,EAAM,MAAQ,EAAM,OAAS,CAAC,EACjE,IAAK,IAAI,EAAI,EAAG,EAAI,EAAG,EAAI,EAAM,KAAK,OAAQ,GAAK,EAAG,GAAK,EACvD,EAAK,GAAK,EAAM,KAAK,GACrB,EAAK,EAAI,GAAK,EAAM,KAAK,EAAI,GAC7B,EAAK,EAAI,GAAK,EAAM,KAAK,EAAI,GAC7B,EAAK,EAAI,GAAK,IAElB,OAAO,IAAI,UAAU,EAAM,EAAM,MAAO,EAAM,MAAM,CACxD"}
|
|
@@ -9,10 +9,10 @@ function n(t, n) {
|
|
|
9
9
|
}
|
|
10
10
|
throw new e("No canvas implementation available in this environment.");
|
|
11
11
|
}
|
|
12
|
-
function r(t) {
|
|
13
|
-
let
|
|
14
|
-
if (
|
|
15
|
-
return
|
|
12
|
+
function r(t, n = {}) {
|
|
13
|
+
let r = t.getContext("2d", n);
|
|
14
|
+
if (r === null) throw new e("Failed to obtain 2D rendering context.");
|
|
15
|
+
return r;
|
|
16
16
|
}
|
|
17
17
|
function i(n) {
|
|
18
18
|
let { data: r, width: i, height: a } = n;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"canvas.js","names":[],"sources":["../../../src/vision/core/canvas.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Canvas plumbing shared by `io/image.ts` and `preprocess/image.ts`.\n *\n * Browsers and workers expose two canvas types (`HTMLCanvasElement` and\n * `OffscreenCanvas`) with slightly different surfaces. These helpers pick the\n * right one for the current environment, return a unified 2D context, and\n * convert between RGBA `ImageData` and the SDK's canonical HWC RGB\n * `RGBImage`.\n */\n\nimport { ImageLoadError } from \"./exceptions\";\nimport { RGBImage } from \"../types\";\n\nexport type Canvas2D = HTMLCanvasElement | OffscreenCanvas;\nexport type Context2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\n\n/** Allocate a `Canvas2D`, preferring `OffscreenCanvas` when available. */\nexport function createCanvas(width: number, height: number): Canvas2D {\n if (typeof OffscreenCanvas !== \"undefined\") {\n return new OffscreenCanvas(width, height);\n }\n if (typeof document !== \"undefined\") {\n const c = document.createElement(\"canvas\");\n c.width = width;\n c.height = height;\n return c;\n }\n throw new ImageLoadError(\"No canvas implementation available in this environment.\");\n}\n\n
|
|
1
|
+
{"version":3,"file":"canvas.js","names":[],"sources":["../../../src/vision/core/canvas.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Canvas plumbing shared by `io/image.ts` and `preprocess/image.ts`.\n *\n * Browsers and workers expose two canvas types (`HTMLCanvasElement` and\n * `OffscreenCanvas`) with slightly different surfaces. These helpers pick the\n * right one for the current environment, return a unified 2D context, and\n * convert between RGBA `ImageData` and the SDK's canonical HWC RGB\n * `RGBImage`.\n */\n\nimport { ImageLoadError } from \"./exceptions\";\nimport { RGBImage } from \"../types\";\n\nexport type Canvas2D = HTMLCanvasElement | OffscreenCanvas;\nexport type Context2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\n\n/** Allocate a `Canvas2D`, preferring `OffscreenCanvas` when available. */\nexport function createCanvas(width: number, height: number): Canvas2D {\n if (typeof OffscreenCanvas !== \"undefined\") {\n return new OffscreenCanvas(width, height);\n }\n if (typeof document !== \"undefined\") {\n const c = document.createElement(\"canvas\");\n c.width = width;\n c.height = height;\n return c;\n }\n throw new ImageLoadError(\"No canvas implementation available in this environment.\");\n}\n\n/**\n * Get a 2D context from a canvas, throwing a typed error if the browser refuses.\n *\n * @param canvas The canvas to obtain a context for.\n * @param options Context attributes, forwarded verbatim. `willReadFrequently`\n * tells the browser the canvas is read back with `getImageData` repeatedly,\n * which moves the backing store to software: faster readback, slower\n * compositing. Whether it pays depends on the surface, so it is the caller's\n * call rather than a default here.\n */\nexport function get2DContext(\n canvas: Canvas2D,\n options: CanvasRenderingContext2DSettings = {},\n): Context2D {\n const ctx = canvas.getContext(\"2d\", options) as Context2D | null;\n if (ctx === null) {\n throw new ImageLoadError(\"Failed to obtain 2D rendering context.\");\n }\n return ctx;\n}\n\n/** Convert RGBA `ImageData` into the canonical HWC RGB `RGBImage`. */\nexport function imageDataToRGB(imageData: ImageData): RGBImage {\n const { data, width, height } = imageData;\n if (data.length !== width * height * 4) {\n throw new ImageLoadError(\n `Unexpected ImageData length ${data.length} for ${width}x${height} (expected ${\n width * height * 4\n }).`,\n );\n }\n const rgb = new Uint8Array(width * height * 3);\n for (let i = 0, j = 0; i < data.length; i += 4, j += 3) {\n rgb[j] = data[i] as number;\n rgb[j + 1] = data[i + 1] as number;\n rgb[j + 2] = data[i + 2] as number;\n }\n return new RGBImage(rgb, width, height);\n}\n\n/** Convert an `RGBImage` into RGBA `ImageData` (alpha forced to 255). */\nexport function rgbToImageData(image: RGBImage): ImageData {\n const data = new Uint8ClampedArray(image.width * image.height * 4);\n for (let i = 0, j = 0; i < image.data.length; i += 3, j += 4) {\n data[j] = image.data[i] as number;\n data[j + 1] = image.data[i + 1] as number;\n data[j + 2] = image.data[i + 2] as number;\n data[j + 3] = 255;\n }\n return new ImageData(data, image.width, image.height);\n}\n"],"mappings":";;;AAkBA,SAAgB,EAAa,GAAe,GAA0B;CAClE,IAAI,OAAO,kBAAoB,KAC3B,OAAO,IAAI,gBAAgB,GAAO,CAAM;CAE5C,IAAI,OAAO,WAAa,KAAa;EACjC,IAAM,IAAI,SAAS,cAAc,QAAQ;EAGzC,OAFA,EAAE,QAAQ,GACV,EAAE,SAAS,GACJ;CACX;CACA,MAAM,IAAI,EAAe,yDAAyD;AACtF;AAYA,SAAgB,EACZ,GACA,IAA4C,CAAC,GACpC;CACT,IAAM,IAAM,EAAO,WAAW,MAAM,CAAO;CAC3C,IAAI,MAAQ,MACR,MAAM,IAAI,EAAe,wCAAwC;CAErE,OAAO;AACX;AAGA,SAAgB,EAAe,GAAgC;CAC3D,IAAM,EAAE,SAAM,UAAO,cAAW;CAChC,IAAI,EAAK,WAAW,IAAQ,IAAS,GACjC,MAAM,IAAI,EACN,+BAA+B,EAAK,OAAO,OAAO,EAAM,GAAG,EAAO,aAC9D,IAAQ,IAAS,EACpB,GACL;CAEJ,IAAM,IAAM,IAAI,WAAW,IAAQ,IAAS,CAAC;CAC7C,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,IAAI,EAAK,QAAQ,KAAK,GAAG,KAAK,GAGjD,AAFA,EAAI,KAAK,EAAK,IACd,EAAI,IAAI,KAAK,EAAK,IAAI,IACtB,EAAI,IAAI,KAAK,EAAK,IAAI;CAE1B,OAAO,IAAI,EAAS,GAAK,GAAO,CAAM;AAC1C;AAGA,SAAgB,EAAe,GAA4B;CACvD,IAAM,IAAO,IAAI,kBAAkB,EAAM,QAAQ,EAAM,SAAS,CAAC;CACjE,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,IAAI,EAAM,KAAK,QAAQ,KAAK,GAAG,KAAK,GAIvD,AAHA,EAAK,KAAK,EAAM,KAAK,IACrB,EAAK,IAAI,KAAK,EAAM,KAAK,IAAI,IAC7B,EAAK,IAAI,KAAK,EAAM,KAAK,IAAI,IAC7B,EAAK,IAAI,KAAK;CAElB,OAAO,IAAI,UAAU,GAAM,EAAM,OAAO,EAAM,MAAM;AACxD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name}},t=class extends e{},n=class extends e{},r=class extends e{},i=class extends e{},a=class extends e{};exports.ImageLoadError=i,exports.InferenceError=n,exports.LabelMapError=a,exports.ModelLoadError=t,exports.OrtVisionError=e,exports.ProviderNotAvailableError=r;
|
|
1
|
+
var e=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name}},t=class extends e{},n=class extends e{},r=class extends e{},i=class extends e{},a=class extends e{},o=class extends e{},s=class extends e{};exports.FusionError=s,exports.ImageLoadError=i,exports.InferenceError=n,exports.LabelMapError=a,exports.ModelLoadError=t,exports.NoDetectionsError=o,exports.OrtVisionError=e,exports.ProviderNotAvailableError=r;
|
|
2
2
|
//# sourceMappingURL=exceptions.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exceptions.cjs","names":[],"sources":["../../../src/vision/core/exceptions.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Exceptions raised by the SDK.\n *\n * All exceptions inherit from {@link OrtVisionError}, so callers can catch\n * the base class to handle any SDK-originated failure uniformly.\n */\n\nexport class OrtVisionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/** Raised when an ONNX model cannot be loaded into an inference session. */\nexport class ModelLoadError extends OrtVisionError {}\n\n/** Raised when ONNX Runtime fails while executing a model. */\nexport class InferenceError extends OrtVisionError {}\n\n/** Raised when a requested execution provider is not available. */\nexport class ProviderNotAvailableError extends OrtVisionError {}\n\n/** Raised when an input image cannot be decoded into the canonical format. */\nexport class ImageLoadError extends OrtVisionError {}\n\n/** Raised when class labels cannot be resolved from the supplied spec. */\nexport class LabelMapError extends OrtVisionError {}\n"],"mappings":"AAQA,IAAa,EAAb,cAAoC,KAAM,CACtC,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,IAAI,OAAO,IAC3B,CACJ,EAGa,EAAb,cAAoC,CAAe,CAAC,EAGvC,EAAb,cAAoC,CAAe,CAAC,EAGvC,EAAb,cAA+C,CAAe,CAAC,EAGlD,EAAb,cAAoC,CAAe,CAAC,EAGvC,EAAb,cAAmC,CAAe,CAAC"}
|
|
1
|
+
{"version":3,"file":"exceptions.cjs","names":[],"sources":["../../../src/vision/core/exceptions.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Exceptions raised by the SDK.\n *\n * All exceptions inherit from {@link OrtVisionError}, so callers can catch\n * the base class to handle any SDK-originated failure uniformly.\n */\n\nexport class OrtVisionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/** Raised when an ONNX model cannot be loaded into an inference session. */\nexport class ModelLoadError extends OrtVisionError {}\n\n/** Raised when ONNX Runtime fails while executing a model. */\nexport class InferenceError extends OrtVisionError {}\n\n/** Raised when a requested execution provider is not available. */\nexport class ProviderNotAvailableError extends OrtVisionError {}\n\n/** Raised when an input image cannot be decoded into the canonical format. */\nexport class ImageLoadError extends OrtVisionError {}\n\n/** Raised when class labels cannot be resolved from the supplied spec. */\nexport class LabelMapError extends OrtVisionError {}\n\n/**\n * Raised when a detection task finds nothing and was asked to treat that as an error.\n *\n * Only raised when the caller opts in with `raiseOnEmpty: true`. The default\n * stays an empty result, because \"the model looked and found nothing\" is a\n * successful inference, not a failure — a photo of an empty field is a valid\n * photo. What the flag is for is the opposite situation: a pipeline step whose\n * *precondition* is that something is there, where an empty result means the\n * caller should stop rather than quietly carry on with zero rows.\n *\n * \"Nothing was detected\" and \"nothing was confident enough\" are the same\n * condition here, since the confidence threshold is what decides what counts as\n * a detection in the first place.\n */\nexport class NoDetectionsError extends OrtVisionError {}\n\n/**\n * Raised when a model cannot be driven as a fused detect→classify pipeline.\n *\n * In the browser this means the file carries no `ovs.*` metadata — it is a\n * plain detector or classifier rather than something `ort_vision_sdk.compose`\n * produced — or the graph is missing an output the pipeline contract requires.\n * Building a pipeline is a Python-side build step; the browser only runs one.\n */\nexport class FusionError extends OrtVisionError {}\n"],"mappings":"AAQA,IAAa,EAAb,cAAoC,KAAM,CACtC,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,IAAI,OAAO,IAC3B,CACJ,EAGa,EAAb,cAAoC,CAAe,CAAC,EAGvC,EAAb,cAAoC,CAAe,CAAC,EAGvC,EAAb,cAA+C,CAAe,CAAC,EAGlD,EAAb,cAAoC,CAAe,CAAC,EAGvC,EAAb,cAAmC,CAAe,CAAC,EAgBtC,EAAb,cAAuC,CAAe,CAAC,EAU1C,EAAb,cAAiC,CAAe,CAAC"}
|
|
@@ -3,8 +3,8 @@ var e = class extends Error {
|
|
|
3
3
|
constructor(e, t) {
|
|
4
4
|
super(e, t), this.name = new.target.name;
|
|
5
5
|
}
|
|
6
|
-
}, t = class extends e {}, n = class extends e {}, r = class extends e {}, i = class extends e {}, a = class extends e {};
|
|
6
|
+
}, t = class extends e {}, n = class extends e {}, r = class extends e {}, i = class extends e {}, a = class extends e {}, o = class extends e {}, s = class extends e {};
|
|
7
7
|
//#endregion
|
|
8
|
-
export { i as ImageLoadError, n as InferenceError, a as LabelMapError, t as ModelLoadError, e as OrtVisionError, r as ProviderNotAvailableError };
|
|
8
|
+
export { s as FusionError, i as ImageLoadError, n as InferenceError, a as LabelMapError, t as ModelLoadError, o as NoDetectionsError, e as OrtVisionError, r as ProviderNotAvailableError };
|
|
9
9
|
|
|
10
10
|
//# sourceMappingURL=exceptions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exceptions.js","names":[],"sources":["../../../src/vision/core/exceptions.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Exceptions raised by the SDK.\n *\n * All exceptions inherit from {@link OrtVisionError}, so callers can catch\n * the base class to handle any SDK-originated failure uniformly.\n */\n\nexport class OrtVisionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/** Raised when an ONNX model cannot be loaded into an inference session. */\nexport class ModelLoadError extends OrtVisionError {}\n\n/** Raised when ONNX Runtime fails while executing a model. */\nexport class InferenceError extends OrtVisionError {}\n\n/** Raised when a requested execution provider is not available. */\nexport class ProviderNotAvailableError extends OrtVisionError {}\n\n/** Raised when an input image cannot be decoded into the canonical format. */\nexport class ImageLoadError extends OrtVisionError {}\n\n/** Raised when class labels cannot be resolved from the supplied spec. */\nexport class LabelMapError extends OrtVisionError {}\n"],"mappings":";AAQA,IAAa,IAAb,cAAoC,MAAM;CACtC,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO,IAAI,OAAO;CAC3B;AACJ,GAGa,IAAb,cAAoC,EAAe,CAAC,GAGvC,IAAb,cAAoC,EAAe,CAAC,GAGvC,IAAb,cAA+C,EAAe,CAAC,GAGlD,IAAb,cAAoC,EAAe,CAAC,GAGvC,IAAb,cAAmC,EAAe,CAAC"}
|
|
1
|
+
{"version":3,"file":"exceptions.js","names":[],"sources":["../../../src/vision/core/exceptions.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Exceptions raised by the SDK.\n *\n * All exceptions inherit from {@link OrtVisionError}, so callers can catch\n * the base class to handle any SDK-originated failure uniformly.\n */\n\nexport class OrtVisionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/** Raised when an ONNX model cannot be loaded into an inference session. */\nexport class ModelLoadError extends OrtVisionError {}\n\n/** Raised when ONNX Runtime fails while executing a model. */\nexport class InferenceError extends OrtVisionError {}\n\n/** Raised when a requested execution provider is not available. */\nexport class ProviderNotAvailableError extends OrtVisionError {}\n\n/** Raised when an input image cannot be decoded into the canonical format. */\nexport class ImageLoadError extends OrtVisionError {}\n\n/** Raised when class labels cannot be resolved from the supplied spec. */\nexport class LabelMapError extends OrtVisionError {}\n\n/**\n * Raised when a detection task finds nothing and was asked to treat that as an error.\n *\n * Only raised when the caller opts in with `raiseOnEmpty: true`. The default\n * stays an empty result, because \"the model looked and found nothing\" is a\n * successful inference, not a failure — a photo of an empty field is a valid\n * photo. What the flag is for is the opposite situation: a pipeline step whose\n * *precondition* is that something is there, where an empty result means the\n * caller should stop rather than quietly carry on with zero rows.\n *\n * \"Nothing was detected\" and \"nothing was confident enough\" are the same\n * condition here, since the confidence threshold is what decides what counts as\n * a detection in the first place.\n */\nexport class NoDetectionsError extends OrtVisionError {}\n\n/**\n * Raised when a model cannot be driven as a fused detect→classify pipeline.\n *\n * In the browser this means the file carries no `ovs.*` metadata — it is a\n * plain detector or classifier rather than something `ort_vision_sdk.compose`\n * produced — or the graph is missing an output the pipeline contract requires.\n * Building a pipeline is a Python-side build step; the browser only runs one.\n */\nexport class FusionError extends OrtVisionError {}\n"],"mappings":";AAQA,IAAa,IAAb,cAAoC,MAAM;CACtC,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO,IAAI,OAAO;CAC3B;AACJ,GAGa,IAAb,cAAoC,EAAe,CAAC,GAGvC,IAAb,cAAoC,EAAe,CAAC,GAGvC,IAAb,cAA+C,EAAe,CAAC,GAGlD,IAAb,cAAoC,EAAe,CAAC,GAGvC,IAAb,cAAmC,EAAe,CAAC,GAgBtC,IAAb,cAAuC,EAAe,CAAC,GAU1C,IAAb,cAAiC,EAAe,CAAC"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
function e(e){let t=0,n=0;for(;e.pos<e.end;){let r=e.bytes[e.pos];if(e.pos+=1,t+=(r&127)*2**n,!(r&128))return t;if(n+=7,n>63)return null}return null}function t(t,n){switch(n){case 0:return e(t)!==null;case 1:return t.pos+=8,t.pos<=t.end;case 2:{let n=e(t);return n===null?!1:(t.pos+=n,t.pos<=t.end)}case 5:return t.pos+=4,t.pos<=t.end;default:return!1}}function n(t){let n=e(t);if(n===null||n>1048576)return null;let r=t.pos,i=r+n;return i>t.end?null:(t.pos=i,{start:r,end:i})}function r(r,i,a){let o={bytes:r,end:a,pos:i},s=new TextDecoder(`utf-8`,{fatal:!1}),c=null,l=null;for(;o.pos<a;){let i=e(o);if(i===null)return null;let a=i>>>3,u=i&7;if(u===2&&(a===1||a===2)){let e=n(o);if(e===null)return null;let t=s.decode(r.subarray(e.start,e.end));a===1?c=t:l=t;continue}if(!t(o,u))return null}return c===null||l===null?null:[c,l]}function i(i){let a=i instanceof Uint8Array?i:new Uint8Array(i),o={bytes:a,end:a.length,pos:0},s={};for(;o.pos<o.end;){let i=e(o);if(i===null)break;let c=i>>>3,l=i&7;if(c===14&&l===2){let e=n(o);if(e===null)break;let t=r(a,e.start,e.end);t&&(s[t[0]]=t[1]);continue}if(!t(o,l))break}return s}function a(e){let t=e?.
|
|
2
|
-
`:t===`r`?`\r`:t===`t`?` `:t)}exports.modelNames=a,exports.readModelMetadata=i;
|
|
1
|
+
function e(e){let t=0,n=0;for(;e.pos<e.end;){let r=e.bytes[e.pos];if(e.pos+=1,t+=(r&127)*2**n,!(r&128))return t;if(n+=7,n>63)return null}return null}function t(t,n){switch(n){case 0:return e(t)!==null;case 1:return t.pos+=8,t.pos<=t.end;case 2:{let n=e(t);return n===null?!1:(t.pos+=n,t.pos<=t.end)}case 5:return t.pos+=4,t.pos<=t.end;default:return!1}}function n(t){let n=e(t);if(n===null||n>1048576)return null;let r=t.pos,i=r+n;return i>t.end?null:(t.pos=i,{start:r,end:i})}function r(r,i,a){let o={bytes:r,end:a,pos:i},s=new TextDecoder(`utf-8`,{fatal:!1}),c=null,l=null;for(;o.pos<a;){let i=e(o);if(i===null)return null;let a=i>>>3,u=i&7;if(u===2&&(a===1||a===2)){let e=n(o);if(e===null)return null;let t=s.decode(r.subarray(e.start,e.end));a===1?c=t:l=t;continue}if(!t(o,u))return null}return c===null||l===null?null:[c,l]}function i(i){let a=i instanceof Uint8Array?i:new Uint8Array(i),o={bytes:a,end:a.length,pos:0},s={};for(;o.pos<o.end;){let i=e(o);if(i===null)break;let c=i>>>3,l=i&7;if(c===14&&l===2){let e=n(o);if(e===null)break;let t=r(a,e.start,e.end);t&&(s[t[0]]=t[1]);continue}if(!t(o,l))break}return s}function a(e){return o(e?.names)}function o(e){let t=e?.trim();if(!t||!t.startsWith(`{`)||!t.endsWith(`}`))return null;let n=t.slice(1,-1).trim();if(!n)return null;let r=new Map,i=/(-?\d+)\s*:\s*(?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)")/g,a=0;for(let e of n.matchAll(i)){let t=Number(e[1]),n=e[2]??e[3];if(!Number.isInteger(t)||n===void 0)return null;r.set(t,s(n)),a+=e[0].length}if(r.size===0||n.length-a>r.size*3)return null;let o=[];for(let e=0;e<r.size;e+=1){let t=r.get(e);if(t===void 0)return null;o.push(t)}return o}function s(e){return e.replace(/\\(.)/g,(e,t)=>t===`n`?`
|
|
2
|
+
`:t===`r`?`\r`:t===`t`?` `:t)}exports.modelNames=a,exports.parseNames=o,exports.readModelMetadata=i;
|
|
3
3
|
//# sourceMappingURL=metadata.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metadata.cjs","names":[],"sources":["../../../src/vision/core/metadata.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Read the metadata an exporter baked into a `.onnx` file.\n *\n * `onnxruntime-web` exposes input/output metadata but **not** the model's\n * custom metadata map, which is where Ultralytics writes `names`, `task` and\n * `imgsz`. The Python SDK gets it for free from\n * `InferenceSession.get_modelmeta().custom_metadata_map`; in the browser the\n * only way to the same information is to read it out of the file, so this\n * module walks just enough of the ModelProto wire format to collect\n * `metadata_props`.\n *\n * It never throws and never allocates unbounded: a truncated, hostile or\n * simply unexpected file yields an empty map, and every caller treats that as\n * \"the model says nothing\", falling back to what it was given.\n */\n\n/** Field number of `metadata_props` in `ModelProto` (repeated StringStringEntryProto). */\nconst MODEL_METADATA_PROPS_FIELD = 14;\n\n/** Field numbers of `key` and `value` in `StringStringEntryProto`. */\nconst ENTRY_KEY_FIELD = 1;\nconst ENTRY_VALUE_FIELD = 2;\n\n/** Protobuf wire types this reader understands. */\nconst WIRE_VARINT = 0;\nconst WIRE_FIXED64 = 1;\nconst WIRE_LENGTH_DELIMITED = 2;\nconst WIRE_FIXED32 = 5;\n\n/**\n * Hard ceiling on a single length-delimited field, as a guard against a corrupt\n * length turning into a huge slice. Model metadata values are strings — a class\n * name map for thousands of classes still fits well inside this.\n */\nconst MAX_FIELD_BYTES = 1 << 20;\n\n/** A cursor over a byte range, tracking its own position. */\ninterface Cursor {\n readonly bytes: Uint8Array;\n readonly end: number;\n pos: number;\n}\n\n/**\n * Read a base-128 varint.\n *\n * @param cursor Cursor to advance.\n * @returns The value, or `null` when the varint is truncated or overlong\n * (beyond the 64-bit range protobuf allows).\n */\nfunction readVarint(cursor: Cursor): number | null {\n let result = 0;\n let shift = 0;\n while (cursor.pos < cursor.end) {\n const byte = cursor.bytes[cursor.pos]!;\n cursor.pos += 1;\n result += (byte & 0x7f) * 2 ** shift;\n if ((byte & 0x80) === 0) return result;\n shift += 7;\n if (shift > 63) return null;\n }\n return null;\n}\n\n/**\n * Skip a field whose contents are not needed.\n *\n * @param cursor Cursor to advance past the field's payload.\n * @param wireType Wire type read from the field's tag.\n * @returns `true` when the field was skipped, `false` when the stream is\n * unreadable from here (unknown wire type or truncated payload).\n */\nfunction skipField(cursor: Cursor, wireType: number): boolean {\n switch (wireType) {\n case WIRE_VARINT:\n return readVarint(cursor) !== null;\n case WIRE_FIXED64:\n cursor.pos += 8;\n return cursor.pos <= cursor.end;\n case WIRE_LENGTH_DELIMITED: {\n const length = readVarint(cursor);\n if (length === null) return false;\n cursor.pos += length;\n return cursor.pos <= cursor.end;\n }\n case WIRE_FIXED32:\n cursor.pos += 4;\n return cursor.pos <= cursor.end;\n default:\n return false;\n }\n}\n\n/**\n * Read a length-delimited payload as a byte range.\n *\n * @param cursor Cursor to advance past the payload.\n * @returns Start and end offsets of the payload, or `null` when the length is\n * truncated, overruns the buffer, or exceeds {@link MAX_FIELD_BYTES}.\n */\nfunction readLengthDelimited(cursor: Cursor): { start: number; end: number } | null {\n const length = readVarint(cursor);\n if (length === null || length > MAX_FIELD_BYTES) return null;\n const start = cursor.pos;\n const end = start + length;\n if (end > cursor.end) return null;\n cursor.pos = end;\n return { start, end };\n}\n\n/**\n * Decode one `StringStringEntryProto` into a key/value pair.\n *\n * @param bytes The model buffer.\n * @param start Offset the entry's payload starts at.\n * @param end Offset the entry's payload ends at.\n * @returns The pair, or `null` when either half is missing or undecodable.\n */\nfunction readEntry(\n bytes: Uint8Array,\n start: number,\n end: number,\n): readonly [string, string] | null {\n const cursor: Cursor = { bytes, end, pos: start };\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n let key: string | null = null;\n let value: string | null = null;\n\n while (cursor.pos < end) {\n const tag = readVarint(cursor);\n if (tag === null) return null;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (\n wireType === WIRE_LENGTH_DELIMITED &&\n (field === ENTRY_KEY_FIELD || field === ENTRY_VALUE_FIELD)\n ) {\n const range = readLengthDelimited(cursor);\n if (range === null) return null;\n const text = decoder.decode(bytes.subarray(range.start, range.end));\n if (field === ENTRY_KEY_FIELD) key = text;\n else value = text;\n continue;\n }\n if (!skipField(cursor, wireType)) return null;\n }\n\n if (key === null || value === null) return null;\n return [key, value];\n}\n\n/**\n * Collect a model's custom metadata map straight out of its bytes.\n *\n * @param model The `.onnx` file contents.\n * @returns Key/value metadata — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export — or an empty object when the file carries none or\n * cannot be walked.\n */\nexport function readModelMetadata(\n model: Uint8Array | ArrayBufferLike,\n): Readonly<Record<string, string>> {\n const bytes = model instanceof Uint8Array ? model : new Uint8Array(model);\n const cursor: Cursor = { bytes, end: bytes.length, pos: 0 };\n const metadata: Record<string, string> = {};\n\n while (cursor.pos < cursor.end) {\n const tag = readVarint(cursor);\n if (tag === null) break;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (field === MODEL_METADATA_PROPS_FIELD && wireType === WIRE_LENGTH_DELIMITED) {\n const range = readLengthDelimited(cursor);\n if (range === null) break;\n const entry = readEntry(bytes, range.start, range.end);\n if (entry) metadata[entry[0]] = entry[1];\n continue;\n }\n if (!skipField(cursor, wireType)) break;\n }\n\n return metadata;\n}\n\n/**\n * Read the class names an export baked into the model metadata.\n *\n * Ultralytics writes `names` as the Python `repr` of a `dict[int, str]` — e.g.\n * `\"{0: 'deworm', 1: 'not_deworm'}\"`. The value is parsed structurally (never\n * evaluated), and anything unparseable, non-`dict`, or not keyed by contiguous\n * integers from zero is rejected whole rather than half-applied: a partial name\n * map would silently mislabel predictions.\n *\n * @param metadata A model's custom metadata map.\n * @returns Class names in class-id order, or `null` when the model carries no\n * usable `names` entry.\n */\nexport function modelNames(\n metadata: Readonly<Record<string, string>> | undefined,\n): readonly string[] | null {\n const raw = metadata?.names?.trim();\n if (!raw || !raw.startsWith(\"{\") || !raw.endsWith(\"}\")) return null;\n\n const body = raw.slice(1, -1).trim();\n if (!body) return null;\n\n const names = new Map<number, string>();\n const entryPattern = /(-?\\d+)\\s*:\\s*(?:'((?:[^'\\\\]|\\\\.)*)'|\"((?:[^\"\\\\]|\\\\.)*)\")/g;\n let consumed = 0;\n for (const match of body.matchAll(entryPattern)) {\n const id = Number(match[1]);\n const text = match[2] ?? match[3];\n if (!Number.isInteger(id) || text === undefined) return null;\n names.set(id, unescapeQuoted(text));\n consumed += match[0].length;\n }\n if (names.size === 0) return null;\n\n const separators = body.length - consumed;\n if (separators > names.size * 3) return null;\n\n const ordered: string[] = [];\n for (let id = 0; id < names.size; id += 1) {\n const name = names.get(id);\n if (name === undefined) return null;\n ordered.push(name);\n }\n return ordered;\n}\n\n/**\n * Resolve the backslash escapes Python's `repr` emits inside a quoted string.\n *\n * @param text The quoted string's contents, escapes intact.\n * @returns The same text with `\\\\`, `\\'`, `\\\"`, `\\n`, `\\r` and `\\t` resolved.\n */\nfunction unescapeQuoted(text: string): string {\n return text.replace(/\\\\(.)/g, (_, char: string) => {\n if (char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AW,EACf,IAAK,IAAM,KAAS,EAAK,SAAS,CAAY,EAAG,CAC7C,IAAM,EAAK,OAAO,EAAM,EAAE,EACpB,EAAO,EAAM,IAAM,EAAM,GAC/B,GAAI,CAAC,OAAO,UAAU,CAAE,GAAK,IAAS,IAAA,GAAW,OAAO,KACxD,EAAM,IAAI,EAAI,EAAe,CAAI,CAAC,EAClC,GAAY,EAAM,EAAE,CAAC,MACzB,CAIA,GAHI,EAAM,OAAS,GAEA,EAAK,OAAS,EAChB,EAAM,KAAO,EAAG,OAAO,KAExC,IAAM,EAAoB,CAAC,EAC3B,IAAK,IAAI,EAAK,EAAG,EAAK,EAAM,KAAM,GAAM,EAAG,CACvC,IAAM,EAAO,EAAM,IAAI,CAAE,EACzB,GAAI,IAAS,IAAA,GAAW,OAAO,KAC/B,EAAQ,KAAK,CAAI,CACrB,CACA,OAAO,CACX,CAQA,SAAS,EAAe,EAAsB,CAC1C,OAAO,EAAK,QAAQ,UAAW,EAAG,IAC1B,IAAS,IAAY;EACrB,IAAS,IAAY,KACrB,IAAS,IAAY,IAClB,CACV,CACL"}
|
|
1
|
+
{"version":3,"file":"metadata.cjs","names":[],"sources":["../../../src/vision/core/metadata.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Read the metadata an exporter baked into a `.onnx` file.\n *\n * `onnxruntime-web` exposes input/output metadata but **not** the model's\n * custom metadata map, which is where Ultralytics writes `names`, `task` and\n * `imgsz`. The Python SDK gets it for free from\n * `InferenceSession.get_modelmeta().custom_metadata_map`; in the browser the\n * only way to the same information is to read it out of the file, so this\n * module walks just enough of the ModelProto wire format to collect\n * `metadata_props`.\n *\n * It never throws and never allocates unbounded: a truncated, hostile or\n * simply unexpected file yields an empty map, and every caller treats that as\n * \"the model says nothing\", falling back to what it was given.\n */\n\n/** Field number of `metadata_props` in `ModelProto` (repeated StringStringEntryProto). */\nconst MODEL_METADATA_PROPS_FIELD = 14;\n\n/** Field numbers of `key` and `value` in `StringStringEntryProto`. */\nconst ENTRY_KEY_FIELD = 1;\nconst ENTRY_VALUE_FIELD = 2;\n\n/** Protobuf wire types this reader understands. */\nconst WIRE_VARINT = 0;\nconst WIRE_FIXED64 = 1;\nconst WIRE_LENGTH_DELIMITED = 2;\nconst WIRE_FIXED32 = 5;\n\n/**\n * Hard ceiling on a single length-delimited field, as a guard against a corrupt\n * length turning into a huge slice. Model metadata values are strings — a class\n * name map for thousands of classes still fits well inside this.\n */\nconst MAX_FIELD_BYTES = 1 << 20;\n\n/** A cursor over a byte range, tracking its own position. */\ninterface Cursor {\n readonly bytes: Uint8Array;\n readonly end: number;\n pos: number;\n}\n\n/**\n * Read a base-128 varint.\n *\n * @param cursor Cursor to advance.\n * @returns The value, or `null` when the varint is truncated or overlong\n * (beyond the 64-bit range protobuf allows).\n */\nfunction readVarint(cursor: Cursor): number | null {\n let result = 0;\n let shift = 0;\n while (cursor.pos < cursor.end) {\n const byte = cursor.bytes[cursor.pos]!;\n cursor.pos += 1;\n result += (byte & 0x7f) * 2 ** shift;\n if ((byte & 0x80) === 0) return result;\n shift += 7;\n if (shift > 63) return null;\n }\n return null;\n}\n\n/**\n * Skip a field whose contents are not needed.\n *\n * @param cursor Cursor to advance past the field's payload.\n * @param wireType Wire type read from the field's tag.\n * @returns `true` when the field was skipped, `false` when the stream is\n * unreadable from here (unknown wire type or truncated payload).\n */\nfunction skipField(cursor: Cursor, wireType: number): boolean {\n switch (wireType) {\n case WIRE_VARINT:\n return readVarint(cursor) !== null;\n case WIRE_FIXED64:\n cursor.pos += 8;\n return cursor.pos <= cursor.end;\n case WIRE_LENGTH_DELIMITED: {\n const length = readVarint(cursor);\n if (length === null) return false;\n cursor.pos += length;\n return cursor.pos <= cursor.end;\n }\n case WIRE_FIXED32:\n cursor.pos += 4;\n return cursor.pos <= cursor.end;\n default:\n return false;\n }\n}\n\n/**\n * Read a length-delimited payload as a byte range.\n *\n * @param cursor Cursor to advance past the payload.\n * @returns Start and end offsets of the payload, or `null` when the length is\n * truncated, overruns the buffer, or exceeds {@link MAX_FIELD_BYTES}.\n */\nfunction readLengthDelimited(cursor: Cursor): { start: number; end: number } | null {\n const length = readVarint(cursor);\n if (length === null || length > MAX_FIELD_BYTES) return null;\n const start = cursor.pos;\n const end = start + length;\n if (end > cursor.end) return null;\n cursor.pos = end;\n return { start, end };\n}\n\n/**\n * Decode one `StringStringEntryProto` into a key/value pair.\n *\n * @param bytes The model buffer.\n * @param start Offset the entry's payload starts at.\n * @param end Offset the entry's payload ends at.\n * @returns The pair, or `null` when either half is missing or undecodable.\n */\nfunction readEntry(\n bytes: Uint8Array,\n start: number,\n end: number,\n): readonly [string, string] | null {\n const cursor: Cursor = { bytes, end, pos: start };\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n let key: string | null = null;\n let value: string | null = null;\n\n while (cursor.pos < end) {\n const tag = readVarint(cursor);\n if (tag === null) return null;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (\n wireType === WIRE_LENGTH_DELIMITED &&\n (field === ENTRY_KEY_FIELD || field === ENTRY_VALUE_FIELD)\n ) {\n const range = readLengthDelimited(cursor);\n if (range === null) return null;\n const text = decoder.decode(bytes.subarray(range.start, range.end));\n if (field === ENTRY_KEY_FIELD) key = text;\n else value = text;\n continue;\n }\n if (!skipField(cursor, wireType)) return null;\n }\n\n if (key === null || value === null) return null;\n return [key, value];\n}\n\n/**\n * Collect a model's custom metadata map straight out of its bytes.\n *\n * @param model The `.onnx` file contents.\n * @returns Key/value metadata — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export — or an empty object when the file carries none or\n * cannot be walked.\n */\nexport function readModelMetadata(\n model: Uint8Array | ArrayBufferLike,\n): Readonly<Record<string, string>> {\n const bytes = model instanceof Uint8Array ? model : new Uint8Array(model);\n const cursor: Cursor = { bytes, end: bytes.length, pos: 0 };\n const metadata: Record<string, string> = {};\n\n while (cursor.pos < cursor.end) {\n const tag = readVarint(cursor);\n if (tag === null) break;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (field === MODEL_METADATA_PROPS_FIELD && wireType === WIRE_LENGTH_DELIMITED) {\n const range = readLengthDelimited(cursor);\n if (range === null) break;\n const entry = readEntry(bytes, range.start, range.end);\n if (entry) metadata[entry[0]] = entry[1];\n continue;\n }\n if (!skipField(cursor, wireType)) break;\n }\n\n return metadata;\n}\n\n/**\n * Read the class names an export baked into the model metadata.\n *\n * Ultralytics writes `names` as the Python `repr` of a `dict[int, str]` — e.g.\n * `\"{0: 'deworm', 1: 'not_deworm'}\"`. The value is parsed structurally (never\n * evaluated), and anything unparseable, non-`dict`, or not keyed by contiguous\n * integers from zero is rejected whole rather than half-applied: a partial name\n * map would silently mislabel predictions.\n *\n * @param metadata A model's custom metadata map.\n * @returns Class names in class-id order, or `null` when the model carries no\n * usable `names` entry.\n */\nexport function modelNames(\n metadata: Readonly<Record<string, string>> | undefined,\n): readonly string[] | null {\n return parseNames(metadata?.names);\n}\n\n/**\n * Parse a `repr`-encoded `dict[int, str]` class map.\n *\n * Split out of {@link modelNames} because the same encoding is reused by a\n * fused pipeline, which carries one class map per stage and therefore cannot\n * store both under the single `names` key Ultralytics uses.\n *\n * @param encoded The encoded map — e.g. `\"{0: 'deworm', 1: 'not_deworm'}\"`.\n * @returns Class names in class-id order, or `null` when the value is missing,\n * unparseable, not a `dict`, or not keyed by contiguous integers from zero.\n */\nexport function parseNames(encoded: string | undefined): readonly string[] | null {\n const raw = encoded?.trim();\n if (!raw || !raw.startsWith(\"{\") || !raw.endsWith(\"}\")) return null;\n\n const body = raw.slice(1, -1).trim();\n if (!body) return null;\n\n const names = new Map<number, string>();\n const entryPattern = /(-?\\d+)\\s*:\\s*(?:'((?:[^'\\\\]|\\\\.)*)'|\"((?:[^\"\\\\]|\\\\.)*)\")/g;\n let consumed = 0;\n for (const match of body.matchAll(entryPattern)) {\n const id = Number(match[1]);\n const text = match[2] ?? match[3];\n if (!Number.isInteger(id) || text === undefined) return null;\n names.set(id, unescapeQuoted(text));\n consumed += match[0].length;\n }\n if (names.size === 0) return null;\n\n const separators = body.length - consumed;\n if (separators > names.size * 3) return null;\n\n const ordered: string[] = [];\n for (let id = 0; id < names.size; id += 1) {\n const name = names.get(id);\n if (name === undefined) return null;\n ordered.push(name);\n }\n return ordered;\n}\n\n/**\n * Resolve the backslash escapes Python's `repr` emits inside a quoted string.\n *\n * @param text The quoted string's contents, escapes intact.\n * @returns The same text with `\\\\`, `\\'`, `\\\"`, `\\n`, `\\r` and `\\t` resolved.\n */\nfunction unescapeQuoted(text: string): string {\n return text.replace(/\\\\(.)/g, (_, char: string) => {\n if (char === \"n\") return \"\\n\";\n if (char === \"r\") return \"\\r\";\n if (char === \"t\") return \"\\t\";\n return char;\n });\n}\n"],"mappings":"AAmDA,SAAS,EAAW,EAA+B,CAC/C,IAAI,EAAS,EACT,EAAQ,EACZ,KAAO,EAAO,IAAM,EAAO,KAAK,CAC5B,IAAM,EAAO,EAAO,MAAM,EAAO,KAGjC,GAFA,EAAO,KAAO,EACd,IAAW,EAAO,KAAQ,GAAK,EAC/B,EAAK,EAAO,KAAa,OAAO,EAEhC,GADA,GAAS,EACL,EAAQ,GAAI,OAAO,IAC3B,CACA,OAAO,IACX,CAUA,SAAS,EAAU,EAAgB,EAA2B,CAC1D,OAAQ,EAAR,CACI,IAAK,GACD,OAAO,EAAW,CAAM,IAAM,KAClC,IAAK,GAED,MADA,GAAO,KAAO,EACP,EAAO,KAAO,EAAO,IAChC,IAAK,GAAuB,CACxB,IAAM,EAAS,EAAW,CAAM,EAGhC,OAFI,IAAW,KAAa,IAC5B,EAAO,KAAO,EACP,EAAO,KAAO,EAAO,IAChC,CACA,IAAK,GAED,MADA,GAAO,KAAO,EACP,EAAO,KAAO,EAAO,IAChC,QACI,MAAO,EACf,CACJ,CASA,SAAS,EAAoB,EAAuD,CAChF,IAAM,EAAS,EAAW,CAAM,EAChC,GAAI,IAAW,MAAQ,EAAS,QAAiB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a(e) {
|
|
74
|
-
|
|
74
|
+
return o(e?.names);
|
|
75
|
+
}
|
|
76
|
+
function o(e) {
|
|
77
|
+
let t = e?.trim();
|
|
75
78
|
if (!t || !t.startsWith("{") || !t.endsWith("}")) return null;
|
|
76
79
|
let n = t.slice(1, -1).trim();
|
|
77
80
|
if (!n) return null;
|
|
@@ -79,21 +82,21 @@ function a(e) {
|
|
|
79
82
|
for (let e of n.matchAll(i)) {
|
|
80
83
|
let t = Number(e[1]), n = e[2] ?? e[3];
|
|
81
84
|
if (!Number.isInteger(t) || n === void 0) return null;
|
|
82
|
-
r.set(t,
|
|
85
|
+
r.set(t, s(n)), a += e[0].length;
|
|
83
86
|
}
|
|
84
87
|
if (r.size === 0 || n.length - a > r.size * 3) return null;
|
|
85
|
-
let
|
|
88
|
+
let o = [];
|
|
86
89
|
for (let e = 0; e < r.size; e += 1) {
|
|
87
90
|
let t = r.get(e);
|
|
88
91
|
if (t === void 0) return null;
|
|
89
|
-
|
|
92
|
+
o.push(t);
|
|
90
93
|
}
|
|
91
|
-
return
|
|
94
|
+
return o;
|
|
92
95
|
}
|
|
93
|
-
function
|
|
96
|
+
function s(e) {
|
|
94
97
|
return e.replace(/\\(.)/g, (e, t) => t === "n" ? "\n" : t === "r" ? "\r" : t === "t" ? " " : t);
|
|
95
98
|
}
|
|
96
99
|
//#endregion
|
|
97
|
-
export { a as modelNames, i as readModelMetadata };
|
|
100
|
+
export { a as modelNames, o as parseNames, i as readModelMetadata };
|
|
98
101
|
|
|
99
102
|
//# sourceMappingURL=metadata.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metadata.js","names":[],"sources":["../../../src/vision/core/metadata.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Read the metadata an exporter baked into a `.onnx` file.\n *\n * `onnxruntime-web` exposes input/output metadata but **not** the model's\n * custom metadata map, which is where Ultralytics writes `names`, `task` and\n * `imgsz`. The Python SDK gets it for free from\n * `InferenceSession.get_modelmeta().custom_metadata_map`; in the browser the\n * only way to the same information is to read it out of the file, so this\n * module walks just enough of the ModelProto wire format to collect\n * `metadata_props`.\n *\n * It never throws and never allocates unbounded: a truncated, hostile or\n * simply unexpected file yields an empty map, and every caller treats that as\n * \"the model says nothing\", falling back to what it was given.\n */\n\n/** Field number of `metadata_props` in `ModelProto` (repeated StringStringEntryProto). */\nconst MODEL_METADATA_PROPS_FIELD = 14;\n\n/** Field numbers of `key` and `value` in `StringStringEntryProto`. */\nconst ENTRY_KEY_FIELD = 1;\nconst ENTRY_VALUE_FIELD = 2;\n\n/** Protobuf wire types this reader understands. */\nconst WIRE_VARINT = 0;\nconst WIRE_FIXED64 = 1;\nconst WIRE_LENGTH_DELIMITED = 2;\nconst WIRE_FIXED32 = 5;\n\n/**\n * Hard ceiling on a single length-delimited field, as a guard against a corrupt\n * length turning into a huge slice. Model metadata values are strings — a class\n * name map for thousands of classes still fits well inside this.\n */\nconst MAX_FIELD_BYTES = 1 << 20;\n\n/** A cursor over a byte range, tracking its own position. */\ninterface Cursor {\n readonly bytes: Uint8Array;\n readonly end: number;\n pos: number;\n}\n\n/**\n * Read a base-128 varint.\n *\n * @param cursor Cursor to advance.\n * @returns The value, or `null` when the varint is truncated or overlong\n * (beyond the 64-bit range protobuf allows).\n */\nfunction readVarint(cursor: Cursor): number | null {\n let result = 0;\n let shift = 0;\n while (cursor.pos < cursor.end) {\n const byte = cursor.bytes[cursor.pos]!;\n cursor.pos += 1;\n result += (byte & 0x7f) * 2 ** shift;\n if ((byte & 0x80) === 0) return result;\n shift += 7;\n if (shift > 63) return null;\n }\n return null;\n}\n\n/**\n * Skip a field whose contents are not needed.\n *\n * @param cursor Cursor to advance past the field's payload.\n * @param wireType Wire type read from the field's tag.\n * @returns `true` when the field was skipped, `false` when the stream is\n * unreadable from here (unknown wire type or truncated payload).\n */\nfunction skipField(cursor: Cursor, wireType: number): boolean {\n switch (wireType) {\n case WIRE_VARINT:\n return readVarint(cursor) !== null;\n case WIRE_FIXED64:\n cursor.pos += 8;\n return cursor.pos <= cursor.end;\n case WIRE_LENGTH_DELIMITED: {\n const length = readVarint(cursor);\n if (length === null) return false;\n cursor.pos += length;\n return cursor.pos <= cursor.end;\n }\n case WIRE_FIXED32:\n cursor.pos += 4;\n return cursor.pos <= cursor.end;\n default:\n return false;\n }\n}\n\n/**\n * Read a length-delimited payload as a byte range.\n *\n * @param cursor Cursor to advance past the payload.\n * @returns Start and end offsets of the payload, or `null` when the length is\n * truncated, overruns the buffer, or exceeds {@link MAX_FIELD_BYTES}.\n */\nfunction readLengthDelimited(cursor: Cursor): { start: number; end: number } | null {\n const length = readVarint(cursor);\n if (length === null || length > MAX_FIELD_BYTES) return null;\n const start = cursor.pos;\n const end = start + length;\n if (end > cursor.end) return null;\n cursor.pos = end;\n return { start, end };\n}\n\n/**\n * Decode one `StringStringEntryProto` into a key/value pair.\n *\n * @param bytes The model buffer.\n * @param start Offset the entry's payload starts at.\n * @param end Offset the entry's payload ends at.\n * @returns The pair, or `null` when either half is missing or undecodable.\n */\nfunction readEntry(\n bytes: Uint8Array,\n start: number,\n end: number,\n): readonly [string, string] | null {\n const cursor: Cursor = { bytes, end, pos: start };\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n let key: string | null = null;\n let value: string | null = null;\n\n while (cursor.pos < end) {\n const tag = readVarint(cursor);\n if (tag === null) return null;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (\n wireType === WIRE_LENGTH_DELIMITED &&\n (field === ENTRY_KEY_FIELD || field === ENTRY_VALUE_FIELD)\n ) {\n const range = readLengthDelimited(cursor);\n if (range === null) return null;\n const text = decoder.decode(bytes.subarray(range.start, range.end));\n if (field === ENTRY_KEY_FIELD) key = text;\n else value = text;\n continue;\n }\n if (!skipField(cursor, wireType)) return null;\n }\n\n if (key === null || value === null) return null;\n return [key, value];\n}\n\n/**\n * Collect a model's custom metadata map straight out of its bytes.\n *\n * @param model The `.onnx` file contents.\n * @returns Key/value metadata — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export — or an empty object when the file carries none or\n * cannot be walked.\n */\nexport function readModelMetadata(\n model: Uint8Array | ArrayBufferLike,\n): Readonly<Record<string, string>> {\n const bytes = model instanceof Uint8Array ? model : new Uint8Array(model);\n const cursor: Cursor = { bytes, end: bytes.length, pos: 0 };\n const metadata: Record<string, string> = {};\n\n while (cursor.pos < cursor.end) {\n const tag = readVarint(cursor);\n if (tag === null) break;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (field === MODEL_METADATA_PROPS_FIELD && wireType === WIRE_LENGTH_DELIMITED) {\n const range = readLengthDelimited(cursor);\n if (range === null) break;\n const entry = readEntry(bytes, range.start, range.end);\n if (entry) metadata[entry[0]] = entry[1];\n continue;\n }\n if (!skipField(cursor, wireType)) break;\n }\n\n return metadata;\n}\n\n/**\n * Read the class names an export baked into the model metadata.\n *\n * Ultralytics writes `names` as the Python `repr` of a `dict[int, str]` — e.g.\n * `\"{0: 'deworm', 1: 'not_deworm'}\"`. The value is parsed structurally (never\n * evaluated), and anything unparseable, non-`dict`, or not keyed by contiguous\n * integers from zero is rejected whole rather than half-applied: a partial name\n * map would silently mislabel predictions.\n *\n * @param metadata A model's custom metadata map.\n * @returns Class names in class-id order, or `null` when the model carries no\n * usable `names` entry.\n */\nexport function modelNames(\n metadata: Readonly<Record<string, string>> | undefined,\n): readonly string[] | null {\n const raw = metadata?.names?.trim();\n if (!raw || !raw.startsWith(\"{\") || !raw.endsWith(\"}\")) return null;\n\n const body = raw.slice(1, -1).trim();\n if (!body) return null;\n\n const names = new Map<number, string>();\n const entryPattern = /(-?\\d+)\\s*:\\s*(?:'((?:[^'\\\\]|\\\\.)*)'|\"((?:[^\"\\\\]|\\\\.)*)\")/g;\n let consumed = 0;\n for (const match of body.matchAll(entryPattern)) {\n const id = Number(match[1]);\n const text = match[2] ?? match[3];\n if (!Number.isInteger(id) || text === undefined) return null;\n names.set(id, unescapeQuoted(text));\n consumed += match[0].length;\n }\n if (names.size === 0) return null;\n\n const separators = body.length - consumed;\n if (separators > names.size * 3) return null;\n\n const ordered: string[] = [];\n for (let id = 0; id < names.size; id += 1) {\n const name = names.get(id);\n if (name === undefined) return null;\n ordered.push(name);\n }\n return ordered;\n}\n\n/**\n * Resolve the backslash escapes Python's `repr` emits inside a quoted string.\n *\n * @param text The quoted string's contents, escapes intact.\n * @returns The same text with `\\\\`, `\\'`, `\\\"`, `\\n`, `\\r` and `\\t` resolved.\n */\nfunction unescapeQuoted(text: string): string {\n return text.replace(/\\\\(.)/g, (_, char: string) => {\n if (char === \"n\") return \"\\n\";\n if (char === \"r\") return \"\\r\";\n if (char === \"t\") return \"\\t\";\n return char;\n });\n}\n"],"mappings":"AAmDA,SAAS,EAAW,GAA+B;CAC/C,IAAI,IAAS,GACT,IAAQ;CACZ,OAAO,EAAO,MAAM,EAAO,MAAK;EAC5B,IAAM,IAAO,EAAO,MAAM,EAAO;EAGjC,IAFA,EAAO,OAAO,GACd,MAAW,IAAO,OAAQ,KAAK,GAC/B,EAAK,IAAO,MAAa,OAAO;EAEhC,IADA,KAAS,GACL,IAAQ,IAAI,OAAO;CAC3B;CACA,OAAO;AACX;AAUA,SAAS,EAAU,GAAgB,GAA2B;CAC1D,QAAQ,GAAR;EACI,KAAK,GACD,OAAO,EAAW,CAAM,MAAM;EAClC,KAAK,GAED,OADA,EAAO,OAAO,GACP,EAAO,OAAO,EAAO;EAChC,KAAK,GAAuB;GACxB,IAAM,IAAS,EAAW,CAAM;GAGhC,OAFI,MAAW,OAAa,MAC5B,EAAO,OAAO,GACP,EAAO,OAAO,EAAO;EAChC;EACA,KAAK,GAED,OADA,EAAO,OAAO,GACP,EAAO,OAAO,EAAO;EAChC,SACI,OAAO;CACf;AACJ;AASA,SAAS,EAAoB,GAAuD;CAChF,IAAM,IAAS,EAAW,CAAM;CAChC,IAAI,MAAW,QAAQ,IAAS,SAAiB,OAAO;CACxD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G;GACrD,AAAI,MAAO,EAAS,EAAM,MAAM,EAAM;GACtC;EACJ;EACA,IAAI,CAAC,EAAU,GAAQ,CAAQ,GAAG;CACtC;CAEA,OAAO;AACX;AAeA,SAAgB,EACZ,GACwB;CACxB,IAAM,IAAM,GAAU,OAAO,KAAK;CAClC,IAAI,CAAC,KAAO,CAAC,EAAI,WAAW,GAAG,KAAK,CAAC,EAAI,SAAS,GAAG,GAAG,OAAO;CAE/D,IAAM,IAAO,EAAI,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK;CACnC,IAAI,CAAC,GAAM,OAAO;CAElB,IAAM,oBAAQ,IAAI,IAAoB,GAChC,IAAe,8DACjB,IAAW;CACf,KAAK,IAAM,KAAS,EAAK,SAAS,CAAY,GAAG;EAC7C,IAAM,IAAK,OAAO,EAAM,EAAE,GACpB,IAAO,EAAM,MAAM,EAAM;EAC/B,IAAI,CAAC,OAAO,UAAU,CAAE,KAAK,MAAS,KAAA,GAAW,OAAO;EAExD,AADA,EAAM,IAAI,GAAI,EAAe,CAAI,CAAC,GAClC,KAAY,EAAM,EAAE,CAAC;CACzB;CAIA,IAHI,EAAM,SAAS,KAEA,EAAK,SAAS,IAChB,EAAM,OAAO,GAAG,OAAO;CAExC,IAAM,IAAoB,CAAC;CAC3B,KAAK,IAAI,IAAK,GAAG,IAAK,EAAM,MAAM,KAAM,GAAG;EACvC,IAAM,IAAO,EAAM,IAAI,CAAE;EACzB,IAAI,MAAS,KAAA,GAAW,OAAO;EAC/B,EAAQ,KAAK,CAAI;CACrB;CACA,OAAO;AACX;AAQA,SAAS,EAAe,GAAsB;CAC1C,OAAO,EAAK,QAAQ,WAAW,GAAG,MAC1B,MAAS,MAAY,OACrB,MAAS,MAAY,OACrB,MAAS,MAAY,MAClB,CACV;AACL"}
|
|
1
|
+
{"version":3,"file":"metadata.js","names":[],"sources":["../../../src/vision/core/metadata.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Read the metadata an exporter baked into a `.onnx` file.\n *\n * `onnxruntime-web` exposes input/output metadata but **not** the model's\n * custom metadata map, which is where Ultralytics writes `names`, `task` and\n * `imgsz`. The Python SDK gets it for free from\n * `InferenceSession.get_modelmeta().custom_metadata_map`; in the browser the\n * only way to the same information is to read it out of the file, so this\n * module walks just enough of the ModelProto wire format to collect\n * `metadata_props`.\n *\n * It never throws and never allocates unbounded: a truncated, hostile or\n * simply unexpected file yields an empty map, and every caller treats that as\n * \"the model says nothing\", falling back to what it was given.\n */\n\n/** Field number of `metadata_props` in `ModelProto` (repeated StringStringEntryProto). */\nconst MODEL_METADATA_PROPS_FIELD = 14;\n\n/** Field numbers of `key` and `value` in `StringStringEntryProto`. */\nconst ENTRY_KEY_FIELD = 1;\nconst ENTRY_VALUE_FIELD = 2;\n\n/** Protobuf wire types this reader understands. */\nconst WIRE_VARINT = 0;\nconst WIRE_FIXED64 = 1;\nconst WIRE_LENGTH_DELIMITED = 2;\nconst WIRE_FIXED32 = 5;\n\n/**\n * Hard ceiling on a single length-delimited field, as a guard against a corrupt\n * length turning into a huge slice. Model metadata values are strings — a class\n * name map for thousands of classes still fits well inside this.\n */\nconst MAX_FIELD_BYTES = 1 << 20;\n\n/** A cursor over a byte range, tracking its own position. */\ninterface Cursor {\n readonly bytes: Uint8Array;\n readonly end: number;\n pos: number;\n}\n\n/**\n * Read a base-128 varint.\n *\n * @param cursor Cursor to advance.\n * @returns The value, or `null` when the varint is truncated or overlong\n * (beyond the 64-bit range protobuf allows).\n */\nfunction readVarint(cursor: Cursor): number | null {\n let result = 0;\n let shift = 0;\n while (cursor.pos < cursor.end) {\n const byte = cursor.bytes[cursor.pos]!;\n cursor.pos += 1;\n result += (byte & 0x7f) * 2 ** shift;\n if ((byte & 0x80) === 0) return result;\n shift += 7;\n if (shift > 63) return null;\n }\n return null;\n}\n\n/**\n * Skip a field whose contents are not needed.\n *\n * @param cursor Cursor to advance past the field's payload.\n * @param wireType Wire type read from the field's tag.\n * @returns `true` when the field was skipped, `false` when the stream is\n * unreadable from here (unknown wire type or truncated payload).\n */\nfunction skipField(cursor: Cursor, wireType: number): boolean {\n switch (wireType) {\n case WIRE_VARINT:\n return readVarint(cursor) !== null;\n case WIRE_FIXED64:\n cursor.pos += 8;\n return cursor.pos <= cursor.end;\n case WIRE_LENGTH_DELIMITED: {\n const length = readVarint(cursor);\n if (length === null) return false;\n cursor.pos += length;\n return cursor.pos <= cursor.end;\n }\n case WIRE_FIXED32:\n cursor.pos += 4;\n return cursor.pos <= cursor.end;\n default:\n return false;\n }\n}\n\n/**\n * Read a length-delimited payload as a byte range.\n *\n * @param cursor Cursor to advance past the payload.\n * @returns Start and end offsets of the payload, or `null` when the length is\n * truncated, overruns the buffer, or exceeds {@link MAX_FIELD_BYTES}.\n */\nfunction readLengthDelimited(cursor: Cursor): { start: number; end: number } | null {\n const length = readVarint(cursor);\n if (length === null || length > MAX_FIELD_BYTES) return null;\n const start = cursor.pos;\n const end = start + length;\n if (end > cursor.end) return null;\n cursor.pos = end;\n return { start, end };\n}\n\n/**\n * Decode one `StringStringEntryProto` into a key/value pair.\n *\n * @param bytes The model buffer.\n * @param start Offset the entry's payload starts at.\n * @param end Offset the entry's payload ends at.\n * @returns The pair, or `null` when either half is missing or undecodable.\n */\nfunction readEntry(\n bytes: Uint8Array,\n start: number,\n end: number,\n): readonly [string, string] | null {\n const cursor: Cursor = { bytes, end, pos: start };\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n let key: string | null = null;\n let value: string | null = null;\n\n while (cursor.pos < end) {\n const tag = readVarint(cursor);\n if (tag === null) return null;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (\n wireType === WIRE_LENGTH_DELIMITED &&\n (field === ENTRY_KEY_FIELD || field === ENTRY_VALUE_FIELD)\n ) {\n const range = readLengthDelimited(cursor);\n if (range === null) return null;\n const text = decoder.decode(bytes.subarray(range.start, range.end));\n if (field === ENTRY_KEY_FIELD) key = text;\n else value = text;\n continue;\n }\n if (!skipField(cursor, wireType)) return null;\n }\n\n if (key === null || value === null) return null;\n return [key, value];\n}\n\n/**\n * Collect a model's custom metadata map straight out of its bytes.\n *\n * @param model The `.onnx` file contents.\n * @returns Key/value metadata — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export — or an empty object when the file carries none or\n * cannot be walked.\n */\nexport function readModelMetadata(\n model: Uint8Array | ArrayBufferLike,\n): Readonly<Record<string, string>> {\n const bytes = model instanceof Uint8Array ? model : new Uint8Array(model);\n const cursor: Cursor = { bytes, end: bytes.length, pos: 0 };\n const metadata: Record<string, string> = {};\n\n while (cursor.pos < cursor.end) {\n const tag = readVarint(cursor);\n if (tag === null) break;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (field === MODEL_METADATA_PROPS_FIELD && wireType === WIRE_LENGTH_DELIMITED) {\n const range = readLengthDelimited(cursor);\n if (range === null) break;\n const entry = readEntry(bytes, range.start, range.end);\n if (entry) metadata[entry[0]] = entry[1];\n continue;\n }\n if (!skipField(cursor, wireType)) break;\n }\n\n return metadata;\n}\n\n/**\n * Read the class names an export baked into the model metadata.\n *\n * Ultralytics writes `names` as the Python `repr` of a `dict[int, str]` — e.g.\n * `\"{0: 'deworm', 1: 'not_deworm'}\"`. The value is parsed structurally (never\n * evaluated), and anything unparseable, non-`dict`, or not keyed by contiguous\n * integers from zero is rejected whole rather than half-applied: a partial name\n * map would silently mislabel predictions.\n *\n * @param metadata A model's custom metadata map.\n * @returns Class names in class-id order, or `null` when the model carries no\n * usable `names` entry.\n */\nexport function modelNames(\n metadata: Readonly<Record<string, string>> | undefined,\n): readonly string[] | null {\n return parseNames(metadata?.names);\n}\n\n/**\n * Parse a `repr`-encoded `dict[int, str]` class map.\n *\n * Split out of {@link modelNames} because the same encoding is reused by a\n * fused pipeline, which carries one class map per stage and therefore cannot\n * store both under the single `names` key Ultralytics uses.\n *\n * @param encoded The encoded map — e.g. `\"{0: 'deworm', 1: 'not_deworm'}\"`.\n * @returns Class names in class-id order, or `null` when the value is missing,\n * unparseable, not a `dict`, or not keyed by contiguous integers from zero.\n */\nexport function parseNames(encoded: string | undefined): readonly string[] | null {\n const raw = encoded?.trim();\n if (!raw || !raw.startsWith(\"{\") || !raw.endsWith(\"}\")) return null;\n\n const body = raw.slice(1, -1).trim();\n if (!body) return null;\n\n const names = new Map<number, string>();\n const entryPattern = /(-?\\d+)\\s*:\\s*(?:'((?:[^'\\\\]|\\\\.)*)'|\"((?:[^\"\\\\]|\\\\.)*)\")/g;\n let consumed = 0;\n for (const match of body.matchAll(entryPattern)) {\n const id = Number(match[1]);\n const text = match[2] ?? match[3];\n if (!Number.isInteger(id) || text === undefined) return null;\n names.set(id, unescapeQuoted(text));\n consumed += match[0].length;\n }\n if (names.size === 0) return null;\n\n const separators = body.length - consumed;\n if (separators > names.size * 3) return null;\n\n const ordered: string[] = [];\n for (let id = 0; id < names.size; id += 1) {\n const name = names.get(id);\n if (name === undefined) return null;\n ordered.push(name);\n }\n return ordered;\n}\n\n/**\n * Resolve the backslash escapes Python's `repr` emits inside a quoted string.\n *\n * @param text The quoted string's contents, escapes intact.\n * @returns The same text with `\\\\`, `\\'`, `\\\"`, `\\n`, `\\r` and `\\t` resolved.\n */\nfunction unescapeQuoted(text: string): string {\n return text.replace(/\\\\(.)/g, (_, char: string) => {\n if (char === \"n\") return \"\\n\";\n if (char === \"r\") return \"\\r\";\n if (char === \"t\") return \"\\t\";\n return char;\n });\n}\n"],"mappings":"AAmDA,SAAS,EAAW,GAA+B;CAC/C,IAAI,IAAS,GACT,IAAQ;CACZ,OAAO,EAAO,MAAM,EAAO,MAAK;EAC5B,IAAM,IAAO,EAAO,MAAM,EAAO;EAGjC,IAFA,EAAO,OAAO,GACd,MAAW,IAAO,OAAQ,KAAK,GAC/B,EAAK,IAAO,MAAa,OAAO;EAEhC,IADA,KAAS,GACL,IAAQ,IAAI,OAAO;CAC3B;CACA,OAAO;AACX;AAUA,SAAS,EAAU,GAAgB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EAAM,OAAO,GAAG,OAAO;CAExC,IAAM,IAAoB,CAAC;CAC3B,KAAK,IAAI,IAAK,GAAG,IAAK,EAAM,MAAM,KAAM,GAAG;EACvC,IAAM,IAAO,EAAM,IAAI,CAAE;EACzB,IAAI,MAAS,KAAA,GAAW,OAAO;EAC/B,EAAQ,KAAK,CAAI;CACrB;CACA,OAAO;AACX;AAQA,SAAS,EAAe,GAAsB;CAC1C,OAAO,EAAK,QAAQ,WAAW,GAAG,MAC1B,MAAS,MAAY,OACrB,MAAS,MAAY,OACrB,MAAS,MAAY,MAClB,CACV;AACL"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./exceptions.cjs"),n=require("./graph.cjs"),r=require("./metadata.cjs"),i=require("./providers.cjs");let a=require("onnxruntime-web");a=e.__toESM(a,1);async function o(e){try{let t=await fetch(e);return t.ok?new Uint8Array(await t.arrayBuffer()):e}catch{return e}}var
|
|
1
|
+
const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./exceptions.cjs"),n=require("./graph.cjs"),r=require("./metadata.cjs"),i=require("./providers.cjs");let a=require("onnxruntime-web");a=e.__toESM(a,1);async function o(e){try{let t=await fetch(e);return t.ok?new Uint8Array(await t.arrayBuffer()):(s(e,`HTTP ${t.status} ${t.statusText}`),e)}catch(t){return s(e,t.message),e}}function s(e,t){console.warn(`[@ort-vision-sdk/web] Could not fetch ${e} to read its metadata (${t}). Letting ONNX Runtime load it instead: the model will work, but its baked-in class names are unavailable, so labels fall back to class_0, class_1, ... Pass \`labels\` explicitly to name them.`)}var c=class e{_session;providers;_metadata;constructor(e,t,n){this._session=e,this.providers=t,this._metadata=n}static async create(n,s={}){let c=i.resolveProviders(s.providers),l={...s.sessionOptions??{},executionProviders:c},u=s.readMetadata!==!1,d=typeof n==`string`&&u?await o(n):n,f=u&&typeof d!=`string`?r.readModelMetadata(d):{},p;try{p=(typeof d==`string`||d instanceof Uint8Array,await a.InferenceSession.create(d,l))}catch(e){throw new t.ModelLoadError(`Failed to load ONNX model: ${e.message}`,{cause:e})}return new e(p,c,f)}get inputNames(){return this._session.inputNames}get inputName(){let e=this._session.inputNames[0];if(e===void 0)throw new t.InferenceError(`Model has no inputs.`);return e}get outputNames(){return this._session.outputNames}get inputShapes(){return n.declaredShapesFrom(this._session.inputMetadata)}get inputShape(){return this.inputShapes[0]??[]}get outputShapes(){return n.declaredShapesFrom(this._session.outputMetadata)}get outputShape(){return this.outputShapes[0]??[]}get metadata(){return this._metadata}async release(){await this._session.release().catch(()=>void 0)}get raw(){return this._session}async run(e){try{return await this._session.run(e)}catch(e){throw new t.InferenceError(`Inference failed: ${e.message}`,{cause:e})}}};exports.OrtSession=c;
|
|
2
2
|
//# sourceMappingURL=session.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.cjs","names":[],"sources":["../../../src/vision/core/session.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { type DeclaredShape, declaredShapesFrom } from \"./graph\";\nimport { readModelMetadata } from \"./metadata\";\nimport { resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\n/**\n * Fetch a model URL as bytes so its metadata can be read.\n *\n * Falls back to the URL itself when the fetch fails, letting ORT try its own\n * load path: losing the metadata map is a downgrade, but failing to load a model\n * that ORT could have fetched would be a regression.\n *\n * @param url Where the `.onnx` lives.\n * @returns The model bytes, or the original URL when they could not be fetched.\n */\nasync function fetchModel(url: string): Promise<Uint8Array | string> {\n try {\n const response = await fetch(url);\n if (!response.ok) return url;\n return new Uint8Array(await response.arrayBuffer());\n } catch {\n return url;\n }\n}\n\nexport interface OrtSessionOptions {\n /** Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}. */\n readonly providers?: readonly string[];\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n /**\n * Whether to read the model's custom metadata map (`names`, `task`, `imgsz`).\n * Defaults to `true`.\n *\n * The runtime does not expose that map, so it is read from the file itself —\n * which means a URL model is fetched here and handed to ORT as bytes instead\n * of letting ORT fetch it. That is the same single download either way, and\n * it is what lets a task resolve its labels off the model. Set to `false` to\n * keep the URL path untouched and leave {@link OrtSession.metadata} empty.\n *\n * `false` is also the escape hatch when a device cannot afford the bytes: the\n * fetched buffer is dropped before ORT builds the graph (see\n * {@link OrtSession.create}), but ORT's own load path still keeps the model out\n * of reach of anything the SDK holds. A session built this way resolves its\n * input size from the graph as usual — only the class names are lost, so a\n * caller taking this route has to pass `labels` itself.\n */\n readonly readMetadata?: boolean;\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names and the shapes the graph declares,\n * manages execution-provider selection, provides a typed {@link OrtSession.run}\n * method, and releases the native session through {@link OrtSession.release}.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n public readonly providers: readonly string[],\n private readonly _metadata: Readonly<Record<string, string>>,\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * The metadata map is read **before** the session is built, and that order is\n * load-bearing on memory-constrained devices. ORT copies the model into its\n * WASM heap and then allocates the graph and the weights on top of that copy;\n * a `readModelMetadata` call placed after `InferenceSession.create` keeps the\n * JavaScript-side buffer reachable across the whole build, so a 5 MB model\n * costs 5 MB of JS heap plus 5 MB of WASM heap plus the weights at the same\n * instant. Reading first makes the buffer collectable as soon as ORT has copied\n * it — on a phone that was the difference between a session and\n * `Can't create a session. failed to allocate a buffer of size N`.\n *\n * @param model Either a URL string, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list, pass-through `SessionOptions`, and whether to\n * read the model's metadata map (see {@link OrtSessionOptions.readMetadata}).\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const providers = resolveProviders(options.providers);\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n const wantsMetadata = options.readMetadata !== false;\n const source = typeof model === \"string\" && wantsMetadata ? await fetchModel(model) : model;\n const metadata =\n wantsMetadata && typeof source !== \"string\" ? readModelMetadata(source) : {};\n\n let session: ort.InferenceSession;\n try {\n if (typeof source === \"string\") {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else if (source instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n source as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers, metadata);\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /**\n * Shapes the graph declares for its inputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Empty shapes mean the runtime\n * reported no metadata — either a non-tensor input, or an `onnxruntime-web`\n * older than 1.21, which predates input metadata.\n */\n get inputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.inputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first input, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get inputShape(): DeclaredShape {\n return this.inputShapes[0] ?? [];\n }\n\n /**\n * Shapes the graph declares for its outputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Reading them is how a task can\n * tell how many classes a head emits without being told.\n */\n get outputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.outputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first output, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get outputShape(): DeclaredShape {\n return this.outputShapes[0] ?? [];\n }\n\n /**\n * The model's custom metadata map — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export.\n *\n * Read from the model's bytes at load time, since the runtime does not expose\n * it. Empty when the session was created with `readMetadata: false`, from a\n * URL that could not be fetched here, or from a model carrying no metadata.\n */\n get metadata(): Readonly<Record<string, string>> {\n return this._metadata;\n }\n\n /**\n * Release the native session and free its memory.\n *\n * Call it when a session is discarded while the page lives on — rebuilding a\n * task at a different input size, swapping in a newer model. A failure from\n * the runtime is ignored: a session being torn down has nothing left to fail\n * at, and the caller is already moving on.\n */\n async release(): Promise<void> {\n await this._session.release().catch(() => undefined);\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * @param feeds Map of input name to `ort.Tensor`. Keys must match {@link inputNames}.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n async run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(feeds);\n return result as Record<string, ort.Tensor>;\n } catch (err) {\n throw new InferenceError(`Inference failed: ${(err as Error).message}`, { cause: err });\n }\n }\n}\n"],"mappings":"0NA0BA,eAAe,EAAW,EAA2C,CACjE,GAAI,CACA,IAAM,EAAW,MAAM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cAElB,CACJ,CAOA,IAAI,aAA6B,CAC7B,OAAO,KAAK,aAAa,IAAM,CAAC,CACpC,CAUA,IAAI,UAA6C,CAC7C,OAAO,KAAK,SAChB,CAUA,MAAM,SAAyB,CAC3B,MAAM,KAAK,SAAS,QAAQ,CAAC,CAAC,UAAY,IAAA,EAAS,CACvD,CAGA,IAAI,KAA4B,CAC5B,OAAO,KAAK,QAChB,CAQA,MAAM,IAAI,EAAwE,CAC9E,GAAI,CAEA,OAAO,MADc,KAAK,SAAS,IAAI,CAAK,CAEhD,OAAS,EAAK,CACV,MAAM,IAAI,EAAA,eAAe,qBAAsB,EAAc,UAAW,CAAE,MAAO,CAAI,CAAC,CAC1F,CACJ,CACJ"}
|
|
1
|
+
{"version":3,"file":"session.cjs","names":[],"sources":["../../../src/vision/core/session.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { type DeclaredShape, declaredShapesFrom } from \"./graph\";\nimport { readModelMetadata } from \"./metadata\";\nimport { resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\n/**\n * Fetch a model URL as bytes so its metadata can be read.\n *\n * Falls back to the URL itself when the fetch fails, letting ORT try its own\n * load path: losing the metadata map is a downgrade, but failing to load a model\n * that ORT could have fetched would be a regression.\n *\n * @param url Where the `.onnx` lives.\n * @returns The model bytes, or the original URL when they could not be fetched.\n */\nasync function fetchModel(url: string): Promise<Uint8Array | string> {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n warnMetadataUnavailable(url, `HTTP ${response.status} ${response.statusText}`);\n return url;\n }\n return new Uint8Array(await response.arrayBuffer());\n } catch (err) {\n warnMetadataUnavailable(url, (err as Error).message);\n return url;\n }\n}\n\n/**\n * Warn that a model's metadata could not be read, and say what that costs.\n *\n * The fallback itself is right — losing the metadata beats failing a load that\n * ORT could have completed on its own — but it used to be silent, and the\n * symptom it produces is remote from the cause: class names come back as\n * `class_0`, `class_1`, ... with nothing anywhere explaining why. Whoever hits\n * this needs to be told that passing `labels` is the way out.\n *\n * @param url The model URL that could not be fetched here.\n * @param reason What went wrong, as reported by `fetch`.\n */\nfunction warnMetadataUnavailable(url: string, reason: string): void {\n console.warn(\n `[@ort-vision-sdk/web] Could not fetch ${url} to read its metadata (${reason}). ` +\n \"Letting ONNX Runtime load it instead: the model will work, but its baked-in \" +\n \"class names are unavailable, so labels fall back to class_0, class_1, ... \" +\n \"Pass `labels` explicitly to name them.\",\n );\n}\n\nexport interface OrtSessionOptions {\n /** Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}. */\n readonly providers?: readonly string[];\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n /**\n * Whether to read the model's custom metadata map (`names`, `task`, `imgsz`).\n * Defaults to `true`.\n *\n * The runtime does not expose that map, so it is read from the file itself —\n * which means a URL model is fetched here and handed to ORT as bytes instead\n * of letting ORT fetch it. That is the same single download either way, and\n * it is what lets a task resolve its labels off the model. Set to `false` to\n * keep the URL path untouched and leave {@link OrtSession.metadata} empty.\n *\n * `false` is also the escape hatch when a device cannot afford the bytes: the\n * fetched buffer is dropped before ORT builds the graph (see\n * {@link OrtSession.create}), but ORT's own load path still keeps the model out\n * of reach of anything the SDK holds. A session built this way resolves its\n * input size from the graph as usual — only the class names are lost, so a\n * caller taking this route has to pass `labels` itself.\n */\n readonly readMetadata?: boolean;\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names and the shapes the graph declares,\n * manages execution-provider selection, provides a typed {@link OrtSession.run}\n * method, and releases the native session through {@link OrtSession.release}.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n public readonly providers: readonly string[],\n private readonly _metadata: Readonly<Record<string, string>>,\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * The metadata map is read **before** the session is built, and that order is\n * load-bearing on memory-constrained devices. ORT copies the model into its\n * WASM heap and then allocates the graph and the weights on top of that copy;\n * a `readModelMetadata` call placed after `InferenceSession.create` keeps the\n * JavaScript-side buffer reachable across the whole build, so a 5 MB model\n * costs 5 MB of JS heap plus 5 MB of WASM heap plus the weights at the same\n * instant. Reading first makes the buffer collectable as soon as ORT has copied\n * it — on a phone that was the difference between a session and\n * `Can't create a session. failed to allocate a buffer of size N`.\n *\n * @param model Either a URL string, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list, pass-through `SessionOptions`, and whether to\n * read the model's metadata map (see {@link OrtSessionOptions.readMetadata}).\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const providers = resolveProviders(options.providers);\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n const wantsMetadata = options.readMetadata !== false;\n const source = typeof model === \"string\" && wantsMetadata ? await fetchModel(model) : model;\n const metadata =\n wantsMetadata && typeof source !== \"string\" ? readModelMetadata(source) : {};\n\n let session: ort.InferenceSession;\n try {\n if (typeof source === \"string\") {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else if (source instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n source as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers, metadata);\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /**\n * Shapes the graph declares for its inputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Empty shapes mean the runtime\n * reported no metadata — either a non-tensor input, or an `onnxruntime-web`\n * older than 1.21, which predates input metadata.\n */\n get inputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.inputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first input, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get inputShape(): DeclaredShape {\n return this.inputShapes[0] ?? [];\n }\n\n /**\n * Shapes the graph declares for its outputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Reading them is how a task can\n * tell how many classes a head emits without being told.\n */\n get outputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.outputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first output, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get outputShape(): DeclaredShape {\n return this.outputShapes[0] ?? [];\n }\n\n /**\n * The model's custom metadata map — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export.\n *\n * Read from the model's bytes at load time, since the runtime does not expose\n * it. Empty when the session was created with `readMetadata: false`, from a\n * URL that could not be fetched here, or from a model carrying no metadata.\n */\n get metadata(): Readonly<Record<string, string>> {\n return this._metadata;\n }\n\n /**\n * Release the native session and free its memory.\n *\n * Call it when a session is discarded while the page lives on — rebuilding a\n * task at a different input size, swapping in a newer model. A failure from\n * the runtime is ignored: a session being torn down has nothing left to fail\n * at, and the caller is already moving on.\n */\n async release(): Promise<void> {\n await this._session.release().catch(() => undefined);\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * @param feeds Map of input name to `ort.Tensor`. Keys must match {@link inputNames}.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n async run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(feeds);\n return result as Record<string, ort.Tensor>;\n } catch (err) {\n throw new InferenceError(`Inference failed: ${(err as Error).message}`, { cause: err });\n }\n }\n}\n"],"mappings":"0NA0BA,eAAe,EAAW,EAA2C,CACjE,GAAI,CACA,IAAM,EAAW,MAAM,MAAM,CAAG,EAKhC,OAJK,EAAS,GAIP,IAAI,WAAW,MAAM,EAAS,YAAY,CAAC,GAH9C,EAAwB,EAAK,QAAQ,EAAS,OAAO,GAAG,EAAS,YAAY,EACtE,EAGf,OAAS,EAAK,CAEV,OADA,EAAwB,EAAM,EAAc,OAAO,EAC5C,CACX,CACJ,CAcA,SAAS,EAAwB,EAAa,EAAsB,CAChE,QAAQ,KACJ,yCAAyC,EAAI,yBAAyB,EAAO,kMAIjF,CACJ,CAkCA,IAAa,EAAb,MAAa,CAAW,CAEC,SACD,UACC,UAHrB,YACI,EACA,EACA,EACF,CAHmB,KAAA,SAAA,EACD,KAAA,UAAA,EACC,KAAA,UAAA,CAClB,CAoBH,aAAa,OAAO,EAAoB,EAA6B,CAAC,EAAwB,CAC1F,IAAM,EAAY,EAAA,iBAAiB,EAAQ,SAAS,EAC9C,EAAsD,CACxD,GAAI,EAAQ,gBAAkB,CAAC,EAC/B,mBACI,CACR,EACM,EAAgB,EAAQ,eAAiB,GACzC,EAAS,OAAO,GAAU,UAAY,EAAgB,MAAM,EAAW,CAAK,EAAI,EAChF,EACF,GAAiB,OAAO,GAAW,SAAW,EAAA,kBAAkB,CAAM,EAAI,CAAC,EAE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.ok ? new Uint8Array(await t.arrayBuffer()) : e;
|
|
11
|
-
} catch {
|
|
12
|
-
return e;
|
|
10
|
+
return t.ok ? new Uint8Array(await t.arrayBuffer()) : (s(e, `HTTP ${t.status} ${t.statusText}`), e);
|
|
11
|
+
} catch (t) {
|
|
12
|
+
return s(e, t.message), e;
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
-
|
|
15
|
+
function s(e, t) {
|
|
16
|
+
console.warn(`[@ort-vision-sdk/web] Could not fetch ${e} to read its metadata (${t}). Letting ONNX Runtime load it instead: the model will work, but its baked-in class names are unavailable, so labels fall back to class_0, class_1, ... Pass \`labels\` explicitly to name them.`);
|
|
17
|
+
}
|
|
18
|
+
var c = class s {
|
|
16
19
|
_session;
|
|
17
20
|
providers;
|
|
18
21
|
_metadata;
|
|
@@ -72,6 +75,6 @@ var s = class s {
|
|
|
72
75
|
}
|
|
73
76
|
};
|
|
74
77
|
//#endregion
|
|
75
|
-
export {
|
|
78
|
+
export { c as OrtSession };
|
|
76
79
|
|
|
77
80
|
//# sourceMappingURL=session.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","names":[],"sources":["../../../src/vision/core/session.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { type DeclaredShape, declaredShapesFrom } from \"./graph\";\nimport { readModelMetadata } from \"./metadata\";\nimport { resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\n/**\n * Fetch a model URL as bytes so its metadata can be read.\n *\n * Falls back to the URL itself when the fetch fails, letting ORT try its own\n * load path: losing the metadata map is a downgrade, but failing to load a model\n * that ORT could have fetched would be a regression.\n *\n * @param url Where the `.onnx` lives.\n * @returns The model bytes, or the original URL when they could not be fetched.\n */\nasync function fetchModel(url: string): Promise<Uint8Array | string> {\n try {\n const response = await fetch(url);\n if (!response.ok) return url;\n return new Uint8Array(await response.arrayBuffer());\n } catch {\n return url;\n }\n}\n\nexport interface OrtSessionOptions {\n /** Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}. */\n readonly providers?: readonly string[];\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n /**\n * Whether to read the model's custom metadata map (`names`, `task`, `imgsz`).\n * Defaults to `true`.\n *\n * The runtime does not expose that map, so it is read from the file itself —\n * which means a URL model is fetched here and handed to ORT as bytes instead\n * of letting ORT fetch it. That is the same single download either way, and\n * it is what lets a task resolve its labels off the model. Set to `false` to\n * keep the URL path untouched and leave {@link OrtSession.metadata} empty.\n *\n * `false` is also the escape hatch when a device cannot afford the bytes: the\n * fetched buffer is dropped before ORT builds the graph (see\n * {@link OrtSession.create}), but ORT's own load path still keeps the model out\n * of reach of anything the SDK holds. A session built this way resolves its\n * input size from the graph as usual — only the class names are lost, so a\n * caller taking this route has to pass `labels` itself.\n */\n readonly readMetadata?: boolean;\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names and the shapes the graph declares,\n * manages execution-provider selection, provides a typed {@link OrtSession.run}\n * method, and releases the native session through {@link OrtSession.release}.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n public readonly providers: readonly string[],\n private readonly _metadata: Readonly<Record<string, string>>,\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * The metadata map is read **before** the session is built, and that order is\n * load-bearing on memory-constrained devices. ORT copies the model into its\n * WASM heap and then allocates the graph and the weights on top of that copy;\n * a `readModelMetadata` call placed after `InferenceSession.create` keeps the\n * JavaScript-side buffer reachable across the whole build, so a 5 MB model\n * costs 5 MB of JS heap plus 5 MB of WASM heap plus the weights at the same\n * instant. Reading first makes the buffer collectable as soon as ORT has copied\n * it — on a phone that was the difference between a session and\n * `Can't create a session. failed to allocate a buffer of size N`.\n *\n * @param model Either a URL string, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list, pass-through `SessionOptions`, and whether to\n * read the model's metadata map (see {@link OrtSessionOptions.readMetadata}).\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const providers = resolveProviders(options.providers);\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n const wantsMetadata = options.readMetadata !== false;\n const source = typeof model === \"string\" && wantsMetadata ? await fetchModel(model) : model;\n const metadata =\n wantsMetadata && typeof source !== \"string\" ? readModelMetadata(source) : {};\n\n let session: ort.InferenceSession;\n try {\n if (typeof source === \"string\") {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else if (source instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n source as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers, metadata);\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /**\n * Shapes the graph declares for its inputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Empty shapes mean the runtime\n * reported no metadata — either a non-tensor input, or an `onnxruntime-web`\n * older than 1.21, which predates input metadata.\n */\n get inputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.inputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first input, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get inputShape(): DeclaredShape {\n return this.inputShapes[0] ?? [];\n }\n\n /**\n * Shapes the graph declares for its outputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Reading them is how a task can\n * tell how many classes a head emits without being told.\n */\n get outputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.outputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first output, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get outputShape(): DeclaredShape {\n return this.outputShapes[0] ?? [];\n }\n\n /**\n * The model's custom metadata map — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export.\n *\n * Read from the model's bytes at load time, since the runtime does not expose\n * it. Empty when the session was created with `readMetadata: false`, from a\n * URL that could not be fetched here, or from a model carrying no metadata.\n */\n get metadata(): Readonly<Record<string, string>> {\n return this._metadata;\n }\n\n /**\n * Release the native session and free its memory.\n *\n * Call it when a session is discarded while the page lives on — rebuilding a\n * task at a different input size, swapping in a newer model. A failure from\n * the runtime is ignored: a session being torn down has nothing left to fail\n * at, and the caller is already moving on.\n */\n async release(): Promise<void> {\n await this._session.release().catch(() => undefined);\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * @param feeds Map of input name to `ort.Tensor`. Keys must match {@link inputNames}.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n async run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(feeds);\n return result as Record<string, ort.Tensor>;\n } catch (err) {\n throw new InferenceError(`Inference failed: ${(err as Error).message}`, { cause: err });\n }\n }\n}\n"],"mappings":";;;;;;AA0BA,eAAe,EAAW,GAA2C;CACjE,IAAI;EACA,IAAM,IAAW,MAAM,MAAM,CAAG;EAEhC,OADK,EAAS,KACP,IAAI,WAAW,MAAM,EAAS,YAAY,CAAC,IADzB;CAE7B,QAAQ;EACJ,OAAO;CACX;AACJ;AAkCA,IAAa,IAAb,MAAa,EAAW;CAEC;CACD;CACC;CAHrB,YACI,GACA,GACA,GACF;EADmB,AAFA,KAAA,WAAA,GACD,KAAA,YAAA,GACC,KAAA,YAAA;CAClB;CAoBH,aAAa,OAAO,GAAoB,IAA6B,CAAC,GAAwB;EAC1F,IAAM,IAAY,EAAiB,EAAQ,SAAS,GAC9C,IAAsD;GACxD,GAAI,EAAQ,kBAAkB,CAAC;GAC/B,oBACI;EACR,GACM,IAAgB,EAAQ,iBAAiB,IACzC,IAAS,OAAO,KAAU,YAAY,IAAgB,MAAM,EAAW,CAAK,IAAI,GAChF,IACF,KAAiB,OAAO,KAAW,WAAW,EAAkB,CAAM,IAAI,CAAC,GAE3E;EACJ,IAAI;GACA,AAKI,KALA,OAAO,KAAW,YAEX,aAAkB,YADf,MAAM,EAAW,iBAAiB,OAAO,GAAQ,CAAc;EASjF,SAAS,GAAK;GACV,MAAM,IAAI,EAAe,8BAA+B,EAAc,WAAW,EAC7E,OAAO,EACX,CAAC;EACL;EAEA,OAAO,IAAI,EAAW,GAAS,GAAW,CAAQ;CACtD;CAGA,IAAI,aAAgC;EAChC,OAAO,KAAK,SAAS;CACzB;CAGA,IAAI,YAAoB;EACpB,IAAM,IAAO,KAAK,SAAS,WAAW;EACtC,IAAI,MAAS,KAAA,GACT,MAAM,IAAI,EAAe,sBAAsB;EAEnD,OAAO;CACX;CAGA,IAAI,cAAiC;EACjC,OAAO,KAAK,SAAS;CACzB;CASA,IAAI,cAAwC;EACxC,OAAO,EACH,KAAK,SAAS,aAElB;CACJ;CAOA,IAAI,aAA4B;EAC5B,OAAO,KAAK,YAAY,MAAM,CAAC;CACnC;CAQA,IAAI,eAAyC;EACzC,OAAO,EACH,KAAK,SAAS,cAElB;CACJ;CAOA,IAAI,cAA6B;EAC7B,OAAO,KAAK,aAAa,MAAM,CAAC;CACpC;CAUA,IAAI,WAA6C;EAC7C,OAAO,KAAK;CAChB;CAUA,MAAM,UAAyB;EAC3B,MAAM,KAAK,SAAS,QAAQ,CAAC,CAAC,YAAY,KAAA,CAAS;CACvD;CAGA,IAAI,MAA4B;EAC5B,OAAO,KAAK;CAChB;CAQA,MAAM,IAAI,GAAwE;EAC9E,IAAI;GAEA,OAAO,MADc,KAAK,SAAS,IAAI,CAAK;EAEhD,SAAS,GAAK;GACV,MAAM,IAAI,EAAe,qBAAsB,EAAc,WAAW,EAAE,OAAO,EAAI,CAAC;EAC1F;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"session.js","names":[],"sources":["../../../src/vision/core/session.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { type DeclaredShape, declaredShapesFrom } from \"./graph\";\nimport { readModelMetadata } from \"./metadata\";\nimport { resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\n/**\n * Fetch a model URL as bytes so its metadata can be read.\n *\n * Falls back to the URL itself when the fetch fails, letting ORT try its own\n * load path: losing the metadata map is a downgrade, but failing to load a model\n * that ORT could have fetched would be a regression.\n *\n * @param url Where the `.onnx` lives.\n * @returns The model bytes, or the original URL when they could not be fetched.\n */\nasync function fetchModel(url: string): Promise<Uint8Array | string> {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n warnMetadataUnavailable(url, `HTTP ${response.status} ${response.statusText}`);\n return url;\n }\n return new Uint8Array(await response.arrayBuffer());\n } catch (err) {\n warnMetadataUnavailable(url, (err as Error).message);\n return url;\n }\n}\n\n/**\n * Warn that a model's metadata could not be read, and say what that costs.\n *\n * The fallback itself is right — losing the metadata beats failing a load that\n * ORT could have completed on its own — but it used to be silent, and the\n * symptom it produces is remote from the cause: class names come back as\n * `class_0`, `class_1`, ... with nothing anywhere explaining why. Whoever hits\n * this needs to be told that passing `labels` is the way out.\n *\n * @param url The model URL that could not be fetched here.\n * @param reason What went wrong, as reported by `fetch`.\n */\nfunction warnMetadataUnavailable(url: string, reason: string): void {\n console.warn(\n `[@ort-vision-sdk/web] Could not fetch ${url} to read its metadata (${reason}). ` +\n \"Letting ONNX Runtime load it instead: the model will work, but its baked-in \" +\n \"class names are unavailable, so labels fall back to class_0, class_1, ... \" +\n \"Pass `labels` explicitly to name them.\",\n );\n}\n\nexport interface OrtSessionOptions {\n /** Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}. */\n readonly providers?: readonly string[];\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n /**\n * Whether to read the model's custom metadata map (`names`, `task`, `imgsz`).\n * Defaults to `true`.\n *\n * The runtime does not expose that map, so it is read from the file itself —\n * which means a URL model is fetched here and handed to ORT as bytes instead\n * of letting ORT fetch it. That is the same single download either way, and\n * it is what lets a task resolve its labels off the model. Set to `false` to\n * keep the URL path untouched and leave {@link OrtSession.metadata} empty.\n *\n * `false` is also the escape hatch when a device cannot afford the bytes: the\n * fetched buffer is dropped before ORT builds the graph (see\n * {@link OrtSession.create}), but ORT's own load path still keeps the model out\n * of reach of anything the SDK holds. A session built this way resolves its\n * input size from the graph as usual — only the class names are lost, so a\n * caller taking this route has to pass `labels` itself.\n */\n readonly readMetadata?: boolean;\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names and the shapes the graph declares,\n * manages execution-provider selection, provides a typed {@link OrtSession.run}\n * method, and releases the native session through {@link OrtSession.release}.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n public readonly providers: readonly string[],\n private readonly _metadata: Readonly<Record<string, string>>,\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * The metadata map is read **before** the session is built, and that order is\n * load-bearing on memory-constrained devices. ORT copies the model into its\n * WASM heap and then allocates the graph and the weights on top of that copy;\n * a `readModelMetadata` call placed after `InferenceSession.create` keeps the\n * JavaScript-side buffer reachable across the whole build, so a 5 MB model\n * costs 5 MB of JS heap plus 5 MB of WASM heap plus the weights at the same\n * instant. Reading first makes the buffer collectable as soon as ORT has copied\n * it — on a phone that was the difference between a session and\n * `Can't create a session. failed to allocate a buffer of size N`.\n *\n * @param model Either a URL string, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list, pass-through `SessionOptions`, and whether to\n * read the model's metadata map (see {@link OrtSessionOptions.readMetadata}).\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const providers = resolveProviders(options.providers);\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n const wantsMetadata = options.readMetadata !== false;\n const source = typeof model === \"string\" && wantsMetadata ? await fetchModel(model) : model;\n const metadata =\n wantsMetadata && typeof source !== \"string\" ? readModelMetadata(source) : {};\n\n let session: ort.InferenceSession;\n try {\n if (typeof source === \"string\") {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else if (source instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n source as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers, metadata);\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /**\n * Shapes the graph declares for its inputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Empty shapes mean the runtime\n * reported no metadata — either a non-tensor input, or an `onnxruntime-web`\n * older than 1.21, which predates input metadata.\n */\n get inputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.inputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first input, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get inputShape(): DeclaredShape {\n return this.inputShapes[0] ?? [];\n }\n\n /**\n * Shapes the graph declares for its outputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Reading them is how a task can\n * tell how many classes a head emits without being told.\n */\n get outputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.outputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first output, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get outputShape(): DeclaredShape {\n return this.outputShapes[0] ?? [];\n }\n\n /**\n * The model's custom metadata map — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export.\n *\n * Read from the model's bytes at load time, since the runtime does not expose\n * it. Empty when the session was created with `readMetadata: false`, from a\n * URL that could not be fetched here, or from a model carrying no metadata.\n */\n get metadata(): Readonly<Record<string, string>> {\n return this._metadata;\n }\n\n /**\n * Release the native session and free its memory.\n *\n * Call it when a session is discarded while the page lives on — rebuilding a\n * task at a different input size, swapping in a newer model. A failure from\n * the runtime is ignored: a session being torn down has nothing left to fail\n * at, and the caller is already moving on.\n */\n async release(): Promise<void> {\n await this._session.release().catch(() => undefined);\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * @param feeds Map of input name to `ort.Tensor`. Keys must match {@link inputNames}.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n async run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(feeds);\n return result as Record<string, ort.Tensor>;\n } catch (err) {\n throw new InferenceError(`Inference failed: ${(err as Error).message}`, { cause: err });\n }\n }\n}\n"],"mappings":";;;;;;AA0BA,eAAe,EAAW,GAA2C;CACjE,IAAI;EACA,IAAM,IAAW,MAAM,MAAM,CAAG;EAKhC,OAJK,EAAS,KAIP,IAAI,WAAW,MAAM,EAAS,YAAY,CAAC,KAH9C,EAAwB,GAAK,QAAQ,EAAS,OAAO,GAAG,EAAS,YAAY,GACtE;CAGf,SAAS,GAAK;EAEV,OADA,EAAwB,GAAM,EAAc,OAAO,GAC5C;CACX;AACJ;AAcA,SAAS,EAAwB,GAAa,GAAsB;CAChE,QAAQ,KACJ,yCAAyC,EAAI,yBAAyB,EAAO,kMAIjF;AACJ;AAkCA,IAAa,IAAb,MAAa,EAAW;CAEC;CACD;CACC;CAHrB,YACI,GACA,GACA,GACF;EADmB,AAFA,KAAA,WAAA,GACD,KAAA,YAAA,GACC,KAAA,YAAA;CAClB;CAoBH,aAAa,OAAO,GAAoB,IAA6B,CAAC,GAAwB;EAC1F,IAAM,IAAY,EAAiB,EAAQ,SAAS,GAC9C,IAAsD;GACxD,GAAI,EAAQ,kBAAkB,CAAC;GAC/B,oBACI;EACR,GACM,IAAgB,EAAQ,iBA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|
|
|
1
|
+
const e=require("./core/metadata.cjs");var t=`detect_classify`,n=`ovs.`,r=`images`,i=`source_image`,a=`letterbox_scale`,o=`letterbox_pad`,s=`boxes`,c=`scores`,l=`classes`,u=`num_detections`,d=`probs`,f=`kind`,p=`sdk_version`,m=`input_size`,h=`crop_size`,g=`crop_source`,_=`max_detections`,v=`conf_threshold`,y=`iou_threshold`,b=`apply_softmax`,x=`detector_names`,S=`classifier_names`,C=`dynamic`;function w(e){if(!e)return null;let t=e.split(`,`);if(t.length!==2)return null;let n=Number(t[0]),r=Number(t[1]);return!Number.isInteger(n)||!Number.isInteger(r)||n<1||r<1?null:[n,r]}function T(e,t){if(!e)return t;let n=Number(e);return Number.isFinite(n)?n:t}function E(n){if(!n)return null;let r={};for(let[e,t]of Object.entries(n))e.startsWith(`ovs.`)&&(r[e.slice(4)]=t);if(r[f]!==`detect_classify`)return null;let i=w(r[m]),a=w(r[h]);if(i===null||a===null)return null;let o=r[_]??C,s=Number(o),c=o===C||!Number.isInteger(s)||s<1?null:s,l=r[g]===`original`?`original`:`detector_input`;return{kind:t,inputSize:i,cropSize:a,cropSource:l,maxDetections:c,confThreshold:T(r[v],.25),iouThreshold:T(r[y],.45),applySoftmax:(r[b]??`1`)!==`0`,detectorNames:e.parseNames(r[x]),classifierNames:e.parseNames(r[S]),sdkVersion:r[p]??``,needsSourceImage:l===`original`}}exports.FUSION_KIND_DETECT_CLASSIFY=t,exports.INPUT_IMAGE=r,exports.INPUT_PAD=o,exports.INPUT_SCALE=a,exports.INPUT_SOURCE=i,exports.METADATA_PREFIX=n,exports.OUTPUT_BOXES=s,exports.OUTPUT_CLASSES=l,exports.OUTPUT_NUM_DETECTIONS=u,exports.OUTPUT_PROBS=d,exports.OUTPUT_SCORES=c,exports.readFusionSpec=E;
|
|
2
|
+
//# sourceMappingURL=fusion.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fusion.cjs","names":[],"sources":["../../src/vision/fusion.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * The contract a fused pipeline carries inside its own `.onnx` file.\n *\n * A pipeline built by the Python SDK's `ort_vision_sdk.compose` is a single\n * graph that already contains the detector, the crop-and-resize bridge and the\n * classifier. Everything the runtime needs to drive it — the letterbox\n * resolution, the crop resolution, where the crops come from, how many\n * detections the graph emits, the class names of both stages — was decided at\n * fusion time and written into the model's metadata.\n *\n * This module reads it back. It is the browser half of a contract whose other\n * half lives in `ort_vision_sdk/fusion.py`: the same keys, the same encodings,\n * the same fallbacks. A pipeline fused once therefore runs identically in\n * Python and in a browser tab, off the same file.\n *\n * Building a pipeline stays a Python-side build step — there is no ONNX\n * protobuf writer here, and there is no reason for one: fusing is something you\n * do once next to your export pipeline, not in a page load.\n */\n\nimport { parseNames } from \"./core/metadata\";\n\n/**\n * Which tensor the bridge crops the detected boxes out of.\n *\n * - `\"detector_input\"`: the letterboxed tensor already fed to the detector.\n * The fused graph then has a **single** image input, but a small object is\n * cropped out of its downscaled copy.\n * - `\"original\"`: a second, full-resolution image input. The bridge undoes the\n * letterbox transform in-graph and crops at native resolution. Two tensors to\n * feed, still one session and one model load.\n */\nexport type CropSource = \"detector_input\" | \"original\";\n\n/** Value of the `ovs.kind` metadata key for a detector→classifier pipeline. */\nexport const FUSION_KIND_DETECT_CLASSIFY = \"detect_classify\";\n\n/**\n * Namespace for every metadata key the fusion writes.\n *\n * Namespaced on purpose: the detector's own Ultralytics metadata (`names`,\n * `task`, `imgsz`) is carried over into the fused model, and an un-prefixed key\n * would either collide with it or be mistaken for it.\n */\nexport const METADATA_PREFIX = \"ovs.\";\n\n/** Name of the fused graph's letterboxed detector input, `[1, 3, H, W]` float32 in `[0, 1]`. */\nexport const INPUT_IMAGE = \"images\";\n\n/** Name of the full-resolution input. Present only when `cropSource === \"original\"`. */\nexport const INPUT_SOURCE = \"source_image\";\n\n/** Name of the `[1]` float32 letterbox scale factor. Only with `cropSource === \"original\"`. */\nexport const INPUT_SCALE = \"letterbox_scale\";\n\n/** Name of the `[2]` float32 `[padLeft, padTop]`. Only with `cropSource === \"original\"`. */\nexport const INPUT_PAD = \"letterbox_pad\";\n\n/** Name of the `[K, 4]` float32 xyxy output, in **letterboxed** input pixels. */\nexport const OUTPUT_BOXES = \"boxes\";\n\n/** Name of the `[K]` float32 detection-confidence output. */\nexport const OUTPUT_SCORES = \"scores\";\n\n/** Name of the `[K]` int64 detector-class output. */\nexport const OUTPUT_CLASSES = \"classes\";\n\n/** Name of the `[1]` int64 output holding how many of the `K` rows are real. */\nexport const OUTPUT_NUM_DETECTIONS = \"num_detections\";\n\n/** Name of the `[K, numClassifierClasses]` float32 classifier output, one row per box. */\nexport const OUTPUT_PROBS = \"probs\";\n\n/** Everything a fused pipeline declares about how it must be driven. */\nexport interface FusionSpec {\n /** Pipeline family. Only `\"detect_classify\"` exists today. */\n readonly kind: string;\n /** `[width, height]` the detector stage expects — the resolution to letterbox to. */\n readonly inputSize: readonly [number, number];\n /** `[width, height]` every crop is resampled to inside the graph. */\n readonly cropSize: readonly [number, number];\n /** Which tensor the crops are taken from. */\n readonly cropSource: CropSource;\n /**\n * Fixed number of rows `K` every output carries, surplus zero-padded and\n * counted by {@link OUTPUT_NUM_DETECTIONS}. `null` means the graph emits\n * exactly as many rows as survived NMS.\n */\n readonly maxDetections: number | null;\n /** Score threshold baked into the graph's NMS node. */\n readonly confThreshold: number;\n /** IoU threshold baked into the graph's NMS node. */\n readonly iouThreshold: number;\n /** Whether the classifier stage emits logits that still need a softmax. */\n readonly applySoftmax: boolean;\n /** Detector class names in class-id order, or `null` when the fusion recorded none. */\n readonly detectorNames: readonly string[] | null;\n /** Classifier class names in class-id order, or `null`. */\n readonly classifierNames: readonly string[] | null;\n /** Version of `ort-vision-sdk` that produced the file. */\n readonly sdkVersion: string;\n /** Whether driving this pipeline requires feeding the full-resolution input. */\n readonly needsSourceImage: boolean;\n}\n\nconst KEY_KIND = \"kind\";\nconst KEY_SDK_VERSION = \"sdk_version\";\nconst KEY_INPUT_SIZE = \"input_size\";\nconst KEY_CROP_SIZE = \"crop_size\";\nconst KEY_CROP_SOURCE = \"crop_source\";\nconst KEY_MAX_DETECTIONS = \"max_detections\";\nconst KEY_CONF_THRESHOLD = \"conf_threshold\";\nconst KEY_IOU_THRESHOLD = \"iou_threshold\";\nconst KEY_APPLY_SOFTMAX = \"apply_softmax\";\nconst KEY_DETECTOR_NAMES = \"detector_names\";\nconst KEY_CLASSIFIER_NAMES = \"classifier_names\";\n\nconst DYNAMIC = \"dynamic\";\n\n/**\n * Decode a `\"640,640\"` pair.\n *\n * @param raw The encoded pair.\n * @returns `[width, height]`, or `null` when the value is missing or malformed.\n */\nfunction decodeSize(raw: string | undefined): readonly [number, number] | null {\n if (!raw) return null;\n const parts = raw.split(\",\");\n if (parts.length !== 2) return null;\n const width = Number(parts[0]);\n const height = Number(parts[1]);\n if (!Number.isInteger(width) || !Number.isInteger(height)) return null;\n if (width < 1 || height < 1) return null;\n return [width, height];\n}\n\n/**\n * Decode a float, falling back when the value is missing or malformed.\n *\n * @param raw The encoded value.\n * @param fallback Value to use when `raw` cannot be read.\n * @returns The parsed number, or `fallback`.\n */\nfunction decodeFloat(raw: string | undefined, fallback: number): number {\n if (!raw) return fallback;\n const value = Number(raw);\n return Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Read a pipeline spec out of a model's custom metadata.\n *\n * Individual malformed entries fall back to the value a fusion would have used\n * by default — a single bad float is not a reason to reject an otherwise\n * loadable pipeline. A malformed resolution is fatal, because there is no safe\n * default for one.\n *\n * @param metadata A model's custom metadata map, as read by\n * {@link readModelMetadata}.\n * @returns The decoded spec, or `null` when the model is not a fused pipeline —\n * it carries no `ovs.kind` entry, or one naming a pipeline kind this version\n * does not know how to drive.\n */\nexport function readFusionSpec(\n metadata: Readonly<Record<string, string>> | undefined,\n): FusionSpec | null {\n if (!metadata) return null;\n\n const read: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (key.startsWith(METADATA_PREFIX)) read[key.slice(METADATA_PREFIX.length)] = value;\n }\n if (read[KEY_KIND] !== FUSION_KIND_DETECT_CLASSIFY) return null;\n\n const inputSize = decodeSize(read[KEY_INPUT_SIZE]);\n const cropSize = decodeSize(read[KEY_CROP_SIZE]);\n if (inputSize === null || cropSize === null) return null;\n\n const rawMax = read[KEY_MAX_DETECTIONS] ?? DYNAMIC;\n const parsedMax = Number(rawMax);\n const maxDetections =\n rawMax === DYNAMIC || !Number.isInteger(parsedMax) || parsedMax < 1 ? null : parsedMax;\n\n const cropSource: CropSource =\n read[KEY_CROP_SOURCE] === \"original\" ? \"original\" : \"detector_input\";\n\n return {\n kind: FUSION_KIND_DETECT_CLASSIFY,\n inputSize,\n cropSize,\n cropSource,\n maxDetections,\n confThreshold: decodeFloat(read[KEY_CONF_THRESHOLD], 0.25),\n iouThreshold: decodeFloat(read[KEY_IOU_THRESHOLD], 0.45),\n applySoftmax: (read[KEY_APPLY_SOFTMAX] ?? \"1\") !== \"0\",\n detectorNames: parseNames(read[KEY_DETECTOR_NAMES]),\n classifierNames: parseNames(read[KEY_CLASSIFIER_NAMES]),\n sdkVersion: read[KEY_SDK_VERSION] ?? \"\",\n needsSourceImage: cropSource === \"original\",\n };\n}\n"],"mappings":"uCAoCA,IAAa,EAA8B,kBAS9B,EAAkB,OAGlB,EAAc,SAGd,EAAe,eAGf,EAAc,kBAGd,EAAY,gBAGZ,EAAe,QAGf,EAAgB,SAGhB,EAAiB,UAGjB,EAAwB,iBAGxB,EAAe,QAkCtB,EAAW,OACX,EAAkB,cAClB,EAAiB,aACjB,EAAgB,YAChB,EAAkB,cAClB,EAAqB,iBACrB,EAAqB,iBACrB,EAAoB,gBACpB,EAAoB,gBACpB,EAAqB,iBACrB,EAAuB,mBAEvB,EAAU,UAQhB,SAAS,EAAW,EAA2D,CAC3E,GAAI,CAAC,EAAK,OAAO,KACjB,IAAM,EAAQ,EAAI,M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
+
import { parseNames as e } from "./core/metadata.js";
|
|
2
|
+
//#region src/vision/fusion.ts
|
|
3
|
+
var t = "detect_classify", n = "ovs.", r = "images", i = "source_image", a = "letterbox_scale", o = "letterbox_pad", s = "boxes", c = "scores", l = "classes", u = "num_detections", d = "probs", f = "kind", p = "sdk_version", m = "input_size", h = "crop_size", g = "crop_source", _ = "max_detections", v = "conf_threshold", y = "iou_threshold", b = "apply_softmax", x = "detector_names", S = "classifier_names", C = "dynamic";
|
|
4
|
+
function w(e) {
|
|
5
|
+
if (!e) return null;
|
|
6
|
+
let t = e.split(",");
|
|
7
|
+
if (t.length !== 2) return null;
|
|
8
|
+
let n = Number(t[0]), r = Number(t[1]);
|
|
9
|
+
return !Number.isInteger(n) || !Number.isInteger(r) || n < 1 || r < 1 ? null : [n, r];
|
|
10
|
+
}
|
|
11
|
+
function T(e, t) {
|
|
12
|
+
if (!e) return t;
|
|
13
|
+
let n = Number(e);
|
|
14
|
+
return Number.isFinite(n) ? n : t;
|
|
15
|
+
}
|
|
16
|
+
function E(n) {
|
|
17
|
+
if (!n) return null;
|
|
18
|
+
let r = {};
|
|
19
|
+
for (let [e, t] of Object.entries(n)) e.startsWith("ovs.") && (r[e.slice(4)] = t);
|
|
20
|
+
if (r[f] !== "detect_classify") return null;
|
|
21
|
+
let i = w(r[m]), a = w(r[h]);
|
|
22
|
+
if (i === null || a === null) return null;
|
|
23
|
+
let o = r[_] ?? C, s = Number(o), c = o === C || !Number.isInteger(s) || s < 1 ? null : s, l = r[g] === "original" ? "original" : "detector_input";
|
|
24
|
+
return {
|
|
25
|
+
kind: t,
|
|
26
|
+
inputSize: i,
|
|
27
|
+
cropSize: a,
|
|
28
|
+
cropSource: l,
|
|
29
|
+
maxDetections: c,
|
|
30
|
+
confThreshold: T(r[v], .25),
|
|
31
|
+
iouThreshold: T(r[y], .45),
|
|
32
|
+
applySoftmax: (r[b] ?? "1") !== "0",
|
|
33
|
+
detectorNames: e(r[x]),
|
|
34
|
+
classifierNames: e(r[S]),
|
|
35
|
+
sdkVersion: r[p] ?? "",
|
|
36
|
+
needsSourceImage: l === "original"
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
export { t as FUSION_KIND_DETECT_CLASSIFY, r as INPUT_IMAGE, o as INPUT_PAD, a as INPUT_SCALE, i as INPUT_SOURCE, n as METADATA_PREFIX, s as OUTPUT_BOXES, l as OUTPUT_CLASSES, u as OUTPUT_NUM_DETECTIONS, d as OUTPUT_PROBS, c as OUTPUT_SCORES, E as readFusionSpec };
|
|
41
|
+
|
|
42
|
+
//# sourceMappingURL=fusion.js.map
|