tempest-react-sdk 0.38.2 → 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/bin/lib/design/collect.mjs +19 -0
- package/bin/lib/design/functions.mjs +5 -0
- package/bin/lib/design/index.mjs +8 -3
- package/bin/lib/design/index.test.mjs +31 -0
- package/bin/lib/design/scan.mjs +34 -2
- package/bin/lib/design/scan.test.mjs +78 -0
- package/bin/lib/doctor/doctor.e2e.test.mjs +85 -0
- package/bin/tempest.mjs +90 -6
- package/dist/audio/level-meter.cjs.map +1 -1
- package/dist/audio/level-meter.js.map +1 -1
- package/dist/audio/use-audio-recorder.cjs.map +1 -1
- package/dist/audio/use-audio-recorder.js.map +1 -1
- package/dist/auth/passkey.cjs.map +1 -1
- package/dist/auth/passkey.js.map +1 -1
- package/dist/auth/use-passkey.cjs.map +1 -1
- package/dist/auth/use-passkey.js.map +1 -1
- package/dist/br/BrazilMap.cjs.map +1 -1
- package/dist/br/BrazilMap.js.map +1 -1
- package/dist/br/BrazilStateCitySelect.cjs.map +1 -1
- package/dist/br/BrazilStateCitySelect.js.map +1 -1
- package/dist/br/BrazilStateMap.cjs.map +1 -1
- package/dist/br/BrazilStateMap.js.map +1 -1
- package/dist/br/PixQRCode.cjs.map +1 -1
- package/dist/br/PixQRCode.js.map +1 -1
- package/dist/br/boleto.cjs.map +1 -1
- package/dist/br/boleto.js.map +1 -1
- package/dist/br/pix.cjs.map +1 -1
- package/dist/br/pix.js.map +1 -1
- package/dist/br.d.ts +8 -0
- package/dist/capture/media-recorder.cjs.map +1 -1
- package/dist/capture/media-recorder.js.map +1 -1
- package/dist/capture/use-barcode-scanner.cjs.map +1 -1
- package/dist/capture/use-barcode-scanner.js.map +1 -1
- package/dist/capture/use-screen-capture.cjs.map +1 -1
- package/dist/capture/use-screen-capture.js.map +1 -1
- package/dist/capture/use-speech-recognition.cjs.map +1 -1
- package/dist/capture/use-speech-recognition.js.map +1 -1
- package/dist/capture/use-video-recorder.cjs.map +1 -1
- package/dist/capture/use-video-recorder.js.map +1 -1
- package/dist/charts/types.cjs.map +1 -1
- package/dist/charts/types.js.map +1 -1
- package/dist/charts.d.ts +8 -0
- package/dist/components/AIChat/AIChat.cjs.map +1 -1
- package/dist/components/AIChat/AIChat.js.map +1 -1
- package/dist/components/AIChat/AIChatComposer.cjs.map +1 -1
- package/dist/components/AIChat/AIChatComposer.js.map +1 -1
- package/dist/components/AIChat/AIChatTurn.cjs.map +1 -1
- package/dist/components/AIChat/AIChatTurn.js.map +1 -1
- package/dist/components/AppBar/AppBar.cjs.map +1 -1
- package/dist/components/AppBar/AppBar.js.map +1 -1
- package/dist/components/AudioPlayer/AudioPlayer.cjs.map +1 -1
- package/dist/components/AudioPlayer/AudioPlayer.js.map +1 -1
- package/dist/components/AudioRecorder/AudioRecorder.cjs.map +1 -1
- package/dist/components/AudioRecorder/AudioRecorder.js.map +1 -1
- package/dist/components/BarcodeScanner/BarcodeScanner.cjs.map +1 -1
- package/dist/components/BarcodeScanner/BarcodeScanner.js.map +1 -1
- package/dist/components/Button/Button.cjs.map +1 -1
- package/dist/components/Button/Button.js.map +1 -1
- package/dist/components/Calendar/Calendar.cjs.map +1 -1
- package/dist/components/Calendar/Calendar.js.map +1 -1
- package/dist/components/Carousel/Carousel.cjs.map +1 -1
- package/dist/components/Carousel/Carousel.js.map +1 -1
- package/dist/components/Chat/Chat.cjs.map +1 -1
- package/dist/components/Chat/Chat.js.map +1 -1
- package/dist/components/ChipInput/ChipInput.cjs.map +1 -1
- package/dist/components/ChipInput/ChipInput.js.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.js.map +1 -1
- package/dist/components/Combobox/Combobox.cjs.map +1 -1
- package/dist/components/Combobox/Combobox.js.map +1 -1
- package/dist/components/Command/Command.cjs.map +1 -1
- package/dist/components/Command/Command.js.map +1 -1
- package/dist/components/ConfirmDialog/ConfirmDialog.cjs.map +1 -1
- package/dist/components/ConfirmDialog/ConfirmDialog.js.map +1 -1
- package/dist/components/ContextMenu/ContextMenu.cjs.map +1 -1
- package/dist/components/ContextMenu/ContextMenu.js.map +1 -1
- package/dist/components/CopyButton/CopyButton.cjs.map +1 -1
- package/dist/components/CopyButton/CopyButton.js.map +1 -1
- package/dist/components/DataTable/DataTable.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.js.map +1 -1
- package/dist/components/DataTable/DataTable.module.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.module.js.map +1 -1
- package/dist/components/DataTable/EditableCell.cjs.map +1 -1
- package/dist/components/DataTable/EditableCell.js.map +1 -1
- package/dist/components/DatePicker/DatePicker.cjs.map +1 -1
- package/dist/components/DatePicker/DatePicker.js.map +1 -1
- package/dist/components/DateRangePicker/DateRangePicker.cjs.map +1 -1
- package/dist/components/DateRangePicker/DateRangePicker.js.map +1 -1
- package/dist/components/Drawer/Drawer.cjs.map +1 -1
- package/dist/components/Drawer/Drawer.js.map +1 -1
- package/dist/components/DropdownMenu/DropdownMenu.cjs.map +1 -1
- package/dist/components/DropdownMenu/DropdownMenu.js.map +1 -1
- package/dist/components/Dropzone/Dropzone.cjs.map +1 -1
- package/dist/components/Dropzone/Dropzone.js.map +1 -1
- package/dist/components/FileUpload/FileUpload.cjs.map +1 -1
- package/dist/components/FileUpload/FileUpload.js.map +1 -1
- package/dist/components/FilterBar/FilterBar.cjs.map +1 -1
- package/dist/components/FilterBar/FilterBar.js.map +1 -1
- package/dist/components/ImageCropper/ImageCropper.cjs.map +1 -1
- package/dist/components/ImageCropper/ImageCropper.js.map +1 -1
- package/dist/components/InstallBanner/InstallBanner.cjs.map +1 -1
- package/dist/components/InstallBanner/InstallBanner.js.map +1 -1
- package/dist/components/Kanban/Kanban.cjs.map +1 -1
- package/dist/components/Kanban/Kanban.js.map +1 -1
- package/dist/components/Lightbox/Lightbox.cjs.map +1 -1
- package/dist/components/Lightbox/Lightbox.js.map +1 -1
- package/dist/components/ListTile/ListTile.cjs.map +1 -1
- package/dist/components/ListTile/ListTile.js.map +1 -1
- package/dist/components/Markdown/Markdown.cjs.map +1 -1
- package/dist/components/Markdown/Markdown.js.map +1 -1
- package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
- package/dist/components/Markdown/markdown-parse.js.map +1 -1
- package/dist/components/Menubar/Menubar.cjs.map +1 -1
- package/dist/components/Menubar/Menubar.js.map +1 -1
- package/dist/components/Modal/Modal.cjs.map +1 -1
- package/dist/components/Modal/Modal.js.map +1 -1
- package/dist/components/ModalsManager/ModalsManager.cjs.map +1 -1
- package/dist/components/ModalsManager/ModalsManager.js.map +1 -1
- package/dist/components/MultiSelect/MultiSelect.cjs.map +1 -1
- package/dist/components/MultiSelect/MultiSelect.js.map +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.cjs.map +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.js.map +1 -1
- package/dist/components/NotificationCenter/NotificationCenter.cjs.map +1 -1
- package/dist/components/NotificationCenter/NotificationCenter.js.map +1 -1
- package/dist/components/Page/Page.cjs.map +1 -1
- package/dist/components/Page/Page.js.map +1 -1
- package/dist/components/Pagination/Pagination.cjs.map +1 -1
- package/dist/components/Pagination/Pagination.js.map +1 -1
- package/dist/components/PasswordInput/PasswordInput.cjs.map +1 -1
- package/dist/components/PasswordInput/PasswordInput.js.map +1 -1
- package/dist/components/PinInput/PinInput.cjs.map +1 -1
- package/dist/components/PinInput/PinInput.js.map +1 -1
- package/dist/components/Popover/Popover.cjs.map +1 -1
- package/dist/components/Popover/Popover.js.map +1 -1
- package/dist/components/Progress/Progress.cjs.map +1 -1
- package/dist/components/Progress/Progress.js.map +1 -1
- package/dist/components/QRCode/qr-encode.cjs.map +1 -1
- package/dist/components/QRCode/qr-encode.js.map +1 -1
- package/dist/components/Radio/Radio.cjs.map +1 -1
- package/dist/components/Radio/Radio.js.map +1 -1
- package/dist/components/RangeSlider/RangeSlider.cjs.map +1 -1
- package/dist/components/RangeSlider/RangeSlider.js.map +1 -1
- package/dist/components/RatingStars/RatingStars.cjs.map +1 -1
- package/dist/components/RatingStars/RatingStars.js.map +1 -1
- package/dist/components/RefreshIndicator/RefreshIndicator.cjs.map +1 -1
- package/dist/components/RefreshIndicator/RefreshIndicator.js.map +1 -1
- package/dist/components/Resizable/Resizable.cjs.map +1 -1
- package/dist/components/Resizable/Resizable.js.map +1 -1
- package/dist/components/Scheduler/Scheduler.cjs.map +1 -1
- package/dist/components/Scheduler/Scheduler.js.map +1 -1
- package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
- package/dist/components/Sidebar/Sidebar.js.map +1 -1
- package/dist/components/SignaturePad/SignaturePad.cjs.map +1 -1
- package/dist/components/SignaturePad/SignaturePad.js.map +1 -1
- package/dist/components/Slider/Slider.cjs.map +1 -1
- package/dist/components/Slider/Slider.js.map +1 -1
- package/dist/components/Sparkline/Sparkline.cjs.map +1 -1
- package/dist/components/Sparkline/Sparkline.js.map +1 -1
- package/dist/components/StepperInput/StepperInput.cjs.map +1 -1
- package/dist/components/StepperInput/StepperInput.js.map +1 -1
- package/dist/components/Table/Table.cjs.map +1 -1
- package/dist/components/Table/Table.js.map +1 -1
- package/dist/components/TimePicker/TimePicker.cjs.map +1 -1
- package/dist/components/TimePicker/TimePicker.js.map +1 -1
- package/dist/components/Toast/ToastProvider.cjs.map +1 -1
- package/dist/components/Toast/ToastProvider.js.map +1 -1
- package/dist/components/Tour/Tour.cjs.map +1 -1
- package/dist/components/Tour/Tour.js.map +1 -1
- package/dist/components/Transfer/Transfer.cjs.map +1 -1
- package/dist/components/Transfer/Transfer.js.map +1 -1
- package/dist/components/TreeView/TreeView.cjs.map +1 -1
- package/dist/components/TreeView/TreeView.js.map +1 -1
- package/dist/components/VirtualList/VirtualList.cjs.map +1 -1
- package/dist/components/VirtualList/VirtualList.js.map +1 -1
- package/dist/components/VirtualTable/VirtualTable.cjs.map +1 -1
- package/dist/components/VirtualTable/VirtualTable.js.map +1 -1
- package/dist/components/Wizard/Wizard.cjs.map +1 -1
- package/dist/components/Wizard/Wizard.js.map +1 -1
- package/dist/editor/RichTextEditor.cjs.map +1 -1
- package/dist/editor/RichTextEditor.js.map +1 -1
- package/dist/forms/FormField.cjs.map +1 -1
- package/dist/forms/FormField.js.map +1 -1
- package/dist/geo/TrajectoryMap.cjs.map +1 -1
- package/dist/geo/TrajectoryMap.js.map +1 -1
- package/dist/geo/estimate.cjs.map +1 -1
- package/dist/geo/estimate.js.map +1 -1
- package/dist/geo/projection.cjs.map +1 -1
- package/dist/geo/projection.js.map +1 -1
- package/dist/hooks/use-event-listener.cjs.map +1 -1
- package/dist/hooks/use-event-listener.js.map +1 -1
- package/dist/hooks/use-local-storage.cjs.map +1 -1
- package/dist/hooks/use-local-storage.js.map +1 -1
- package/dist/hooks/use-sortable.cjs.map +1 -1
- package/dist/hooks/use-sortable.js.map +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/errors.cjs.map +1 -1
- package/dist/http/errors.js.map +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/upload-with-progress.cjs.map +1 -1
- package/dist/http/upload-with-progress.js.map +1 -1
- package/dist/i18n/I18nProvider.cjs.map +1 -1
- package/dist/i18n/I18nProvider.js.map +1 -1
- package/dist/imaging/canvas.cjs.map +1 -1
- package/dist/imaging/canvas.js.map +1 -1
- package/dist/imaging.d.ts +5 -0
- package/dist/logger/logger.cjs.map +1 -1
- package/dist/logger/logger.js.map +1 -1
- package/dist/oauth/GoogleSignIn.cjs.map +1 -1
- package/dist/oauth/GoogleSignIn.js.map +1 -1
- package/dist/offline/create-offline-sync.cjs.map +1 -1
- package/dist/offline/create-offline-sync.js.map +1 -1
- package/dist/perf/cache-size.cjs +1 -1
- package/dist/perf/cache-size.cjs.map +1 -1
- package/dist/perf/cache-size.js +27 -6
- package/dist/perf/cache-size.js.map +1 -1
- package/dist/sse/create-event-stream.cjs.map +1 -1
- package/dist/sse/create-event-stream.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/sw/background-sync.cjs.map +1 -1
- package/dist/sw/background-sync.js.map +1 -1
- package/dist/sw/cache.cjs.map +1 -1
- package/dist/sw/cache.js.map +1 -1
- package/dist/sw.d.ts +12 -0
- package/dist/tabular/compact.cjs.map +1 -1
- package/dist/tabular/compact.js.map +1 -1
- package/dist/tabular/predictor.cjs.map +1 -1
- package/dist/tabular/predictor.js.map +1 -1
- package/dist/tabular.d.ts +7 -2
- package/dist/tempest-react-sdk.d.ts +133 -6
- package/dist/theme/ThemeProvider.cjs.map +1 -1
- package/dist/theme/ThemeProvider.js.map +1 -1
- package/dist/theme/color.cjs.map +1 -1
- package/dist/theme/color.js.map +1 -1
- package/dist/theme/create-theme.cjs.map +1 -1
- package/dist/theme/create-theme.js.map +1 -1
- package/dist/theme/data-viz-ramps.cjs +1 -1
- package/dist/theme/data-viz-ramps.cjs.map +1 -1
- package/dist/theme/data-viz-ramps.js +1 -1
- package/dist/theme/data-viz-ramps.js.map +1 -1
- package/dist/utils/storage.cjs.map +1 -1
- package/dist/utils/storage.js.map +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/graph.cjs.map +1 -1
- package/dist/vision/core/graph.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/providers.cjs.map +1 -1
- package/dist/vision/core/providers.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/core/timing.cjs.map +1 -1
- package/dist/vision/core/timing.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/io/image.cjs.map +1 -1
- package/dist/vision/io/image.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/luminance.cjs.map +1 -1
- package/dist/vision/luminance.js.map +1 -1
- package/dist/vision/postprocess/classification.cjs.map +1 -1
- package/dist/vision/postprocess/classification.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/image.cjs.map +1 -1
- package/dist/vision/preprocess/image.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/classifier.cjs.map +1 -1
- package/dist/vision/tasks/classifier.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 -956
- package/dist/vision.js +25 -22
- package/dist/vite/tempest-icons.cjs.map +1 -1
- package/dist/vite/tempest-icons.js.map +1 -1
- package/dist/vite/tempest-pwa-icons.cjs.map +1 -1
- package/dist/vite/tempest-pwa-icons.js.map +1 -1
- package/dist/ws/create-web-socket.cjs.map +1 -1
- package/dist/ws/create-web-socket.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"canvas.js","names":[],"sources":["../../../src/vision/core/canvas.ts"],"sourcesContent":["/**\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":["/**\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":"
|
|
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":["/**\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":";
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.cjs","names":[],"sources":["../../../src/vision/core/graph.ts"],"sourcesContent":["/**\n * What the ONNX graph itself says about its inputs.\n *\n * The resolution a session must be fed at is a property of the exported model,\n * not of the configuration around it. Feeding a 640x640 tensor to a graph\n * exported at 224x224 makes ORT abort the run with\n * `Got invalid dimensions for input: images ... Got: 640 Expected: 224`, and the\n * caller has no way to see that coming from the outside — the number lives in\n * the file. So the SDK reads it from the graph and treats any configured size as\n * a fallback for when the graph leaves it open.\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\n/**\n * One declared dimension: a number when the graph pins it, `null` when the\n * dimension is symbolic (dynamic).\n */\nexport type DeclaredDim = number | null;\n\n/** A declared input/output shape, dynamic axes appearing as `null`. */\nexport type DeclaredShape = readonly DeclaredDim[];\n\n/**\n * Convert ORT value metadata into declared shapes.\n *\n * @param metadata Metadata as reported by `InferenceSession.inputMetadata`, or\n * `undefined` on ORT builds that predate it (added in onnxruntime 1.21).\n * @returns One shape per value, in declaration order. Non-tensor values and\n * builds without metadata yield empty shapes, which read as \"nothing\n * declared\" everywhere downstream.\n */\nexport function declaredShapesFrom(\n metadata: readonly ort.InferenceSession.ValueMetadata[] | undefined,\n): readonly DeclaredShape[] {\n if (metadata === undefined) return [];\n return metadata.map((value) =>\n value.isTensor\n ? value.shape.map((dim) =>\n typeof dim === \"number\" && Number.isInteger(dim) && dim > 0 ? dim : null,\n )\n : [],\n );\n}\n\n/**\n * Read the spatial input size out of a declared NCHW shape.\n *\n * @param shape The declared shape of the model's image input.\n * @returns `[width, height]` in pixels, or `null` when the shape is not 4D or\n * leaves either spatial axis dynamic — in which case the model accepts more\n * than one resolution and there is nothing to correct.\n */\nexport function spatialInputSize(shape: DeclaredShape): readonly [number, number] | null {\n if (shape.length !== 4) return null;\n const height = shape[2];\n const width = shape[3];\n if (height === null || height === undefined || width === null || width === undefined)\n return null;\n return [width, height];\n}\n\n/**\n * Infer how many classes a YOLO detection/segmentation head emits.\n *\n * Such a head declares `(B, 4 + nc, N)` — four box coordinates stacked above one\n * score per class, over `N` candidate anchors. `N` is in the thousands and the\n * batch is 1, so the channel axis is the smallest static axis above 1.\n *\n * @param shape Declared shape of the model's first output.\n * @returns The class count, or `null` when the shape leaves it undeterminable —\n * fully dynamic, or too small to hold boxes plus at least one class.\n */\nexport function detectionNumClasses(shape: DeclaredShape): number | null {\n const staticDims = shape.filter((dim): dim is number => dim !== null && dim > 1);\n if (staticDims.length === 0) return null;\n const channels = Math.min(...staticDims);\n if (channels < 5) return null;\n return channels - 4;\n}\n\n/**\n * Infer how many classes a classification head emits.\n *\n * A classifier declares `(B, nc)`, so the count is the last static axis.\n *\n * @param shape Declared shape of the model's first output.\n * @returns The class count, or `null` when the last axis is dynamic or absent.\n */\nexport function classificationNumClasses(shape: DeclaredShape): number | null {\n const last = shape[shape.length - 1];\n if (last === null || last === undefined || last < 1) return null;\n return last;\n}\n\nexport interface ResolveInputSizeOptions {\n /** Declared shape of the model's image input, from {@link declaredShapesFrom}. */\n readonly graphShape?: DeclaredShape;\n /** Size the caller asked for, if any. */\n readonly requested?: readonly [number, number];\n /** Size to use when neither the graph nor the caller pins one. */\n readonly fallback: readonly [number, number];\n}\n\n/**\n * Decide the input size a task will preprocess to.\n *\n * Precedence is graph → caller → fallback. The graph wins over an explicit\n * `inputSize` because a static shape is not a preference, it is what ORT will\n * accept: honoring the caller there would only turn a fixable mismatch into a\n * failed run. A disagreement is a configuration bug in the caller, so it is\n * reported through `console.warn` instead of being swallowed.\n *\n * @param options Graph shape, requested size and per-task fallback.\n * @returns The `[width, height]` to preprocess to.\n */\nexport function resolveInputSize(options: ResolveInputSizeOptions): readonly [number, number] {\n const graph = options.graphShape === undefined ? null : spatialInputSize(options.graphShape);\n const requested = options.requested;\n if (graph === null) return requested ?? options.fallback;\n if (requested !== undefined && (requested[0] !== graph[0] || requested[1] !== graph[1])) {\n console.warn(\n `[ort-vision-sdk] The model declares a ${graph[0]}x${graph[1]} input; ` +\n `ignoring the requested ${requested[0]}x${requested[1]}, which ONNX Runtime would reject.`,\n );\n }\n return graph;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"graph.cjs","names":[],"sources":["../../../src/vision/core/graph.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * What the ONNX graph itself says about its inputs.\n *\n * The resolution a session must be fed at is a property of the exported model,\n * not of the configuration around it. Feeding a 640x640 tensor to a graph\n * exported at 224x224 makes ORT abort the run with\n * `Got invalid dimensions for input: images ... Got: 640 Expected: 224`, and the\n * caller has no way to see that coming from the outside — the number lives in\n * the file. So the SDK reads it from the graph and treats any configured size as\n * a fallback for when the graph leaves it open.\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\n/**\n * One declared dimension: a number when the graph pins it, `null` when the\n * dimension is symbolic (dynamic).\n */\nexport type DeclaredDim = number | null;\n\n/** A declared input/output shape, dynamic axes appearing as `null`. */\nexport type DeclaredShape = readonly DeclaredDim[];\n\n/**\n * Convert ORT value metadata into declared shapes.\n *\n * @param metadata Metadata as reported by `InferenceSession.inputMetadata`, or\n * `undefined` on ORT builds that predate it (added in onnxruntime 1.21).\n * @returns One shape per value, in declaration order. Non-tensor values and\n * builds without metadata yield empty shapes, which read as \"nothing\n * declared\" everywhere downstream.\n */\nexport function declaredShapesFrom(\n metadata: readonly ort.InferenceSession.ValueMetadata[] | undefined,\n): readonly DeclaredShape[] {\n if (metadata === undefined) return [];\n return metadata.map((value) =>\n value.isTensor\n ? value.shape.map((dim) =>\n typeof dim === \"number\" && Number.isInteger(dim) && dim > 0 ? dim : null,\n )\n : [],\n );\n}\n\n/**\n * Read the spatial input size out of a declared NCHW shape.\n *\n * @param shape The declared shape of the model's image input.\n * @returns `[width, height]` in pixels, or `null` when the shape is not 4D or\n * leaves either spatial axis dynamic — in which case the model accepts more\n * than one resolution and there is nothing to correct.\n */\nexport function spatialInputSize(shape: DeclaredShape): readonly [number, number] | null {\n if (shape.length !== 4) return null;\n const height = shape[2];\n const width = shape[3];\n if (height === null || height === undefined || width === null || width === undefined)\n return null;\n return [width, height];\n}\n\n/**\n * Infer how many classes a YOLO detection/segmentation head emits.\n *\n * Such a head declares `(B, 4 + nc, N)` — four box coordinates stacked above one\n * score per class, over `N` candidate anchors. `N` is in the thousands and the\n * batch is 1, so the channel axis is the smallest static axis above 1.\n *\n * @param shape Declared shape of the model's first output.\n * @returns The class count, or `null` when the shape leaves it undeterminable —\n * fully dynamic, or too small to hold boxes plus at least one class.\n */\nexport function detectionNumClasses(shape: DeclaredShape): number | null {\n const staticDims = shape.filter((dim): dim is number => dim !== null && dim > 1);\n if (staticDims.length === 0) return null;\n const channels = Math.min(...staticDims);\n if (channels < 5) return null;\n return channels - 4;\n}\n\n/**\n * Infer how many classes a classification head emits.\n *\n * A classifier declares `(B, nc)`, so the count is the last static axis.\n *\n * @param shape Declared shape of the model's first output.\n * @returns The class count, or `null` when the last axis is dynamic or absent.\n */\nexport function classificationNumClasses(shape: DeclaredShape): number | null {\n const last = shape[shape.length - 1];\n if (last === null || last === undefined || last < 1) return null;\n return last;\n}\n\nexport interface ResolveInputSizeOptions {\n /** Declared shape of the model's image input, from {@link declaredShapesFrom}. */\n readonly graphShape?: DeclaredShape;\n /** Size the caller asked for, if any. */\n readonly requested?: readonly [number, number];\n /** Size to use when neither the graph nor the caller pins one. */\n readonly fallback: readonly [number, number];\n}\n\n/**\n * Decide the input size a task will preprocess to.\n *\n * Precedence is graph → caller → fallback. The graph wins over an explicit\n * `inputSize` because a static shape is not a preference, it is what ORT will\n * accept: honoring the caller there would only turn a fixable mismatch into a\n * failed run. A disagreement is a configuration bug in the caller, so it is\n * reported through `console.warn` instead of being swallowed.\n *\n * @param options Graph shape, requested size and per-task fallback.\n * @returns The `[width, height]` to preprocess to.\n */\nexport function resolveInputSize(options: ResolveInputSizeOptions): readonly [number, number] {\n const graph = options.graphShape === undefined ? null : spatialInputSize(options.graphShape);\n const requested = options.requested;\n if (graph === null) return requested ?? options.fallback;\n if (requested !== undefined && (requested[0] !== graph[0] || requested[1] !== graph[1])) {\n console.warn(\n `[ort-vision-sdk] The model declares a ${graph[0]}x${graph[1]} input; ` +\n `ignoring the requested ${requested[0]}x${requested[1]}, which ONNX Runtime would reject.`,\n );\n }\n return graph;\n}\n"],"mappings":"AAiCA,SAAgB,EACZ,EACwB,CAExB,OADI,IAAa,IAAA,GAAkB,CAAC,EAC7B,EAAS,IAAK,GACjB,EAAM,SACA,EAAM,MAAM,IAAK,GACb,OAAO,GAAQ,UAAY,OAAO,UAAU,CAAG,GAAK,EAAM,EAAI,EAAM,IACxE,EACA,CAAC,CACX,CACJ,CAUA,SAAgB,EAAiB,EAAwD,CACrF,GAAI,EAAM,SAAW,EAAG,OAAO,KAC/B,IAAM,EAAS,EAAM,GACf,EAAQ,EAAM,GAGpB,OAFI,GAAW,MAAgC,GAAU,KAC9C,KACJ,CAAC,EAAO,CAAM,CACzB,CAaA,SAAgB,EAAoB,EAAqC,CACrE,IAAM,EAAa,EAAM,OAAQ,GAAuB,IAAQ,MAAQ,EAAM,CAAC,EAC/E,GAAI,EAAW,SAAW,EAAG,OAAO,KACpC,IAAM,EAAW,KAAK,IAAI,GAAG,CAAU,EAEvC,OADI,EAAW,EAAU,KAClB,EAAW,CACtB,CAUA,SAAgB,EAAyB,EAAqC,CAC1E,IAAM,EAAO,EAAM,EAAM,OAAS,GAElC,OADI,GAAS,MAA8B,EAAO,EAAU,KACrD,CACX,CAuBA,SAAgB,EAAiB,EAA6D,CAC1F,IAAM,EAAQ,EAAQ,aAAe,IAAA,GAAY,KAAO,EAAiB,EAAQ,UAAU,EACrF,EAAY,EAAQ,UAQ1B,OAPI,IAAU,KAAa,GAAa,EAAQ,UAC5C,IAAc,IAAA,KAAc,EAAU,KAAO,EAAM,IAAM,EAAU,KAAO,EAAM,KAChF,QAAQ,KACJ,yCAAyC,EAAM,GAAG,GAAG,EAAM,GAAG,iCAChC,EAAU,GAAG,GAAG,EAAU,GAAG,mCAC/D,EAEG,EACX"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.js","names":[],"sources":["../../../src/vision/core/graph.ts"],"sourcesContent":["/**\n * What the ONNX graph itself says about its inputs.\n *\n * The resolution a session must be fed at is a property of the exported model,\n * not of the configuration around it. Feeding a 640x640 tensor to a graph\n * exported at 224x224 makes ORT abort the run with\n * `Got invalid dimensions for input: images ... Got: 640 Expected: 224`, and the\n * caller has no way to see that coming from the outside — the number lives in\n * the file. So the SDK reads it from the graph and treats any configured size as\n * a fallback for when the graph leaves it open.\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\n/**\n * One declared dimension: a number when the graph pins it, `null` when the\n * dimension is symbolic (dynamic).\n */\nexport type DeclaredDim = number | null;\n\n/** A declared input/output shape, dynamic axes appearing as `null`. */\nexport type DeclaredShape = readonly DeclaredDim[];\n\n/**\n * Convert ORT value metadata into declared shapes.\n *\n * @param metadata Metadata as reported by `InferenceSession.inputMetadata`, or\n * `undefined` on ORT builds that predate it (added in onnxruntime 1.21).\n * @returns One shape per value, in declaration order. Non-tensor values and\n * builds without metadata yield empty shapes, which read as \"nothing\n * declared\" everywhere downstream.\n */\nexport function declaredShapesFrom(\n metadata: readonly ort.InferenceSession.ValueMetadata[] | undefined,\n): readonly DeclaredShape[] {\n if (metadata === undefined) return [];\n return metadata.map((value) =>\n value.isTensor\n ? value.shape.map((dim) =>\n typeof dim === \"number\" && Number.isInteger(dim) && dim > 0 ? dim : null,\n )\n : [],\n );\n}\n\n/**\n * Read the spatial input size out of a declared NCHW shape.\n *\n * @param shape The declared shape of the model's image input.\n * @returns `[width, height]` in pixels, or `null` when the shape is not 4D or\n * leaves either spatial axis dynamic — in which case the model accepts more\n * than one resolution and there is nothing to correct.\n */\nexport function spatialInputSize(shape: DeclaredShape): readonly [number, number] | null {\n if (shape.length !== 4) return null;\n const height = shape[2];\n const width = shape[3];\n if (height === null || height === undefined || width === null || width === undefined)\n return null;\n return [width, height];\n}\n\n/**\n * Infer how many classes a YOLO detection/segmentation head emits.\n *\n * Such a head declares `(B, 4 + nc, N)` — four box coordinates stacked above one\n * score per class, over `N` candidate anchors. `N` is in the thousands and the\n * batch is 1, so the channel axis is the smallest static axis above 1.\n *\n * @param shape Declared shape of the model's first output.\n * @returns The class count, or `null` when the shape leaves it undeterminable —\n * fully dynamic, or too small to hold boxes plus at least one class.\n */\nexport function detectionNumClasses(shape: DeclaredShape): number | null {\n const staticDims = shape.filter((dim): dim is number => dim !== null && dim > 1);\n if (staticDims.length === 0) return null;\n const channels = Math.min(...staticDims);\n if (channels < 5) return null;\n return channels - 4;\n}\n\n/**\n * Infer how many classes a classification head emits.\n *\n * A classifier declares `(B, nc)`, so the count is the last static axis.\n *\n * @param shape Declared shape of the model's first output.\n * @returns The class count, or `null` when the last axis is dynamic or absent.\n */\nexport function classificationNumClasses(shape: DeclaredShape): number | null {\n const last = shape[shape.length - 1];\n if (last === null || last === undefined || last < 1) return null;\n return last;\n}\n\nexport interface ResolveInputSizeOptions {\n /** Declared shape of the model's image input, from {@link declaredShapesFrom}. */\n readonly graphShape?: DeclaredShape;\n /** Size the caller asked for, if any. */\n readonly requested?: readonly [number, number];\n /** Size to use when neither the graph nor the caller pins one. */\n readonly fallback: readonly [number, number];\n}\n\n/**\n * Decide the input size a task will preprocess to.\n *\n * Precedence is graph → caller → fallback. The graph wins over an explicit\n * `inputSize` because a static shape is not a preference, it is what ORT will\n * accept: honoring the caller there would only turn a fixable mismatch into a\n * failed run. A disagreement is a configuration bug in the caller, so it is\n * reported through `console.warn` instead of being swallowed.\n *\n * @param options Graph shape, requested size and per-task fallback.\n * @returns The `[width, height]` to preprocess to.\n */\nexport function resolveInputSize(options: ResolveInputSizeOptions): readonly [number, number] {\n const graph = options.graphShape === undefined ? null : spatialInputSize(options.graphShape);\n const requested = options.requested;\n if (graph === null) return requested ?? options.fallback;\n if (requested !== undefined && (requested[0] !== graph[0] || requested[1] !== graph[1])) {\n console.warn(\n `[ort-vision-sdk] The model declares a ${graph[0]}x${graph[1]} input; ` +\n `ignoring the requested ${requested[0]}x${requested[1]}, which ONNX Runtime would reject.`,\n );\n }\n return graph;\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"graph.js","names":[],"sources":["../../../src/vision/core/graph.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * What the ONNX graph itself says about its inputs.\n *\n * The resolution a session must be fed at is a property of the exported model,\n * not of the configuration around it. Feeding a 640x640 tensor to a graph\n * exported at 224x224 makes ORT abort the run with\n * `Got invalid dimensions for input: images ... Got: 640 Expected: 224`, and the\n * caller has no way to see that coming from the outside — the number lives in\n * the file. So the SDK reads it from the graph and treats any configured size as\n * a fallback for when the graph leaves it open.\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\n/**\n * One declared dimension: a number when the graph pins it, `null` when the\n * dimension is symbolic (dynamic).\n */\nexport type DeclaredDim = number | null;\n\n/** A declared input/output shape, dynamic axes appearing as `null`. */\nexport type DeclaredShape = readonly DeclaredDim[];\n\n/**\n * Convert ORT value metadata into declared shapes.\n *\n * @param metadata Metadata as reported by `InferenceSession.inputMetadata`, or\n * `undefined` on ORT builds that predate it (added in onnxruntime 1.21).\n * @returns One shape per value, in declaration order. Non-tensor values and\n * builds without metadata yield empty shapes, which read as \"nothing\n * declared\" everywhere downstream.\n */\nexport function declaredShapesFrom(\n metadata: readonly ort.InferenceSession.ValueMetadata[] | undefined,\n): readonly DeclaredShape[] {\n if (metadata === undefined) return [];\n return metadata.map((value) =>\n value.isTensor\n ? value.shape.map((dim) =>\n typeof dim === \"number\" && Number.isInteger(dim) && dim > 0 ? dim : null,\n )\n : [],\n );\n}\n\n/**\n * Read the spatial input size out of a declared NCHW shape.\n *\n * @param shape The declared shape of the model's image input.\n * @returns `[width, height]` in pixels, or `null` when the shape is not 4D or\n * leaves either spatial axis dynamic — in which case the model accepts more\n * than one resolution and there is nothing to correct.\n */\nexport function spatialInputSize(shape: DeclaredShape): readonly [number, number] | null {\n if (shape.length !== 4) return null;\n const height = shape[2];\n const width = shape[3];\n if (height === null || height === undefined || width === null || width === undefined)\n return null;\n return [width, height];\n}\n\n/**\n * Infer how many classes a YOLO detection/segmentation head emits.\n *\n * Such a head declares `(B, 4 + nc, N)` — four box coordinates stacked above one\n * score per class, over `N` candidate anchors. `N` is in the thousands and the\n * batch is 1, so the channel axis is the smallest static axis above 1.\n *\n * @param shape Declared shape of the model's first output.\n * @returns The class count, or `null` when the shape leaves it undeterminable —\n * fully dynamic, or too small to hold boxes plus at least one class.\n */\nexport function detectionNumClasses(shape: DeclaredShape): number | null {\n const staticDims = shape.filter((dim): dim is number => dim !== null && dim > 1);\n if (staticDims.length === 0) return null;\n const channels = Math.min(...staticDims);\n if (channels < 5) return null;\n return channels - 4;\n}\n\n/**\n * Infer how many classes a classification head emits.\n *\n * A classifier declares `(B, nc)`, so the count is the last static axis.\n *\n * @param shape Declared shape of the model's first output.\n * @returns The class count, or `null` when the last axis is dynamic or absent.\n */\nexport function classificationNumClasses(shape: DeclaredShape): number | null {\n const last = shape[shape.length - 1];\n if (last === null || last === undefined || last < 1) return null;\n return last;\n}\n\nexport interface ResolveInputSizeOptions {\n /** Declared shape of the model's image input, from {@link declaredShapesFrom}. */\n readonly graphShape?: DeclaredShape;\n /** Size the caller asked for, if any. */\n readonly requested?: readonly [number, number];\n /** Size to use when neither the graph nor the caller pins one. */\n readonly fallback: readonly [number, number];\n}\n\n/**\n * Decide the input size a task will preprocess to.\n *\n * Precedence is graph → caller → fallback. The graph wins over an explicit\n * `inputSize` because a static shape is not a preference, it is what ORT will\n * accept: honoring the caller there would only turn a fixable mismatch into a\n * failed run. A disagreement is a configuration bug in the caller, so it is\n * reported through `console.warn` instead of being swallowed.\n *\n * @param options Graph shape, requested size and per-task fallback.\n * @returns The `[width, height]` to preprocess to.\n */\nexport function resolveInputSize(options: ResolveInputSizeOptions): readonly [number, number] {\n const graph = options.graphShape === undefined ? null : spatialInputSize(options.graphShape);\n const requested = options.requested;\n if (graph === null) return requested ?? options.fallback;\n if (requested !== undefined && (requested[0] !== graph[0] || requested[1] !== graph[1])) {\n console.warn(\n `[ort-vision-sdk] The model declares a ${graph[0]}x${graph[1]} input; ` +\n `ignoring the requested ${requested[0]}x${requested[1]}, which ONNX Runtime would reject.`,\n );\n }\n return graph;\n}\n"],"mappings":";AAiCA,SAAgB,EACZ,GACwB;CAExB,OADI,MAAa,KAAA,IAAkB,CAAC,IAC7B,EAAS,KAAK,MACjB,EAAM,WACA,EAAM,MAAM,KAAK,MACb,OAAO,KAAQ,YAAY,OAAO,UAAU,CAAG,KAAK,IAAM,IAAI,IAAM,IACxE,IACA,CAAC,CACX;AACJ;AAUA,SAAgB,EAAiB,GAAwD;CACrF,IAAI,EAAM,WAAW,GAAG,OAAO;CAC/B,IAAM,IAAS,EAAM,IACf,IAAQ,EAAM;CAGpB,OAFI,KAAW,QAAgC,KAAU,OAC9C,OACJ,CAAC,GAAO,CAAM;AACzB;AAaA,SAAgB,EAAoB,GAAqC;CACrE,IAAM,IAAa,EAAM,QAAQ,MAAuB,MAAQ,QAAQ,IAAM,CAAC;CAC/E,IAAI,EAAW,WAAW,GAAG,OAAO;CACpC,IAAM,IAAW,KAAK,IAAI,GAAG,CAAU;CAEvC,OADI,IAAW,IAAU,OAClB,IAAW;AACtB;AAUA,SAAgB,EAAyB,GAAqC;CAC1E,IAAM,IAAO,EAAM,EAAM,SAAS;CAElC,OADI,KAAS,QAA8B,IAAO,IAAU,OACrD;AACX;AAuBA,SAAgB,EAAiB,GAA6D;CAC1F,IAAM,IAAQ,EAAQ,eAAe,KAAA,IAAY,OAAO,EAAiB,EAAQ,UAAU,GACrF,IAAY,EAAQ;CAQ1B,OAPI,MAAU,OAAa,KAAa,EAAQ,YAC5C,MAAc,KAAA,MAAc,EAAU,OAAO,EAAM,MAAM,EAAU,OAAO,EAAM,OAChF,QAAQ,KACJ,yCAAyC,EAAM,GAAG,GAAG,EAAM,GAAG,iCAChC,EAAU,GAAG,GAAG,EAAU,GAAG,mCAC/D,GAEG;AACX"}
|
|
@@ -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":["/**\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":"AAkDA,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,EA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|
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,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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"}
|
|
@@ -71,7 +71,10 @@ function i(i) {
|
|
|
71
71
|
return s;
|
|
72
72
|
}
|
|
73
73
|
function 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":["/**\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":"AAkDA,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;C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AO;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,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,IAAM,IAAQ,EAAO,KACf,IAAM,IAAQ;CAGpB,OAFI,IAAM,EAAO,MAAY,QAC7B,EAAO,MAAM,GACN;EAAE;EAAO;CAAI;AACxB;AAUA,SAAS,EACL,GACA,GACA,GACgC;CAChC,IAAM,IAAiB;EAAE;EAAO;EAAK,KAAK;CAAM,GAC1C,IAAU,IAAI,YAAY,SAAS,EAAE,OAAO,GAAM,CAAC,GACrD,IAAqB,MACrB,IAAuB;CAE3B,OAAO,EAAO,MAAM,IAAK;EACrB,IAA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AAG,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers.cjs","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order; `undefined` returns the default.\n */\nexport function resolveProviders(requested?: readonly string[]): string[] {\n if (requested === undefined) {\n return [...DEFAULT_PROVIDERS];\n }\n if (requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"providers.cjs","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order; `undefined` returns the default.\n */\nexport function resolveProviders(requested?: readonly string[]): string[] {\n if (requested === undefined) {\n return [...DEFAULT_PROVIDERS];\n }\n if (requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n"],"mappings":"AAeA,IAAa,EAAuC,CAAC,SAAU,MAAM,EAOrE,SAAgB,EAAiB,EAAyC,CAOtE,OANI,IAAc,IAAA,IAGd,EAAU,SAAW,EACd,CAAC,GAAG,CAAiB,EAEzB,CAAC,GAAG,CAAS,CACxB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers.js","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order; `undefined` returns the default.\n */\nexport function resolveProviders(requested?: readonly string[]): string[] {\n if (requested === undefined) {\n return [...DEFAULT_PROVIDERS];\n }\n if (requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"providers.js","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order; `undefined` returns the default.\n */\nexport function resolveProviders(requested?: readonly string[]): string[] {\n if (requested === undefined) {\n return [...DEFAULT_PROVIDERS];\n }\n if (requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n"],"mappings":";AAeA,IAAa,IAAuC,CAAC,UAAU,MAAM;AAOrE,SAAgB,EAAiB,GAAyC;CAOtE,OANI,MAAc,KAAA,KAGd,EAAU,WAAW,IACd,CAAC,GAAG,CAAiB,IAEzB,CAAC,GAAG,CAAS;AACxB"}
|
|
@@ -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":["/**\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":"0NAyBA,eAAe,EAAW,EAA2C,CACjE,GAAI,CACA,IAAM,EAAW,MAAM,MAAM,CAAG,EAEhC,OADK,EAAS,GACP,IAAI,WAAW,MAAM,EAAS,YAAY,CAAC,EADzB,CAE7B,MAAQ,CACJ,OAAO,CACX,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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AW,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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A,eAAe,sBAAsB,EAEnD,OAAO,CACX,CAGA,IAAI,aAAiC,CACjC,OAAO,KAAK,SAAS,WACzB,CASA,IAAI,aAAwC,CACxC,OAAO,EAAA,mBACH,KAAK,SAAS,aAElB,CACJ,CAOA,IAAI,YAA4B,CAC5B,OAAO,KAAK,YAAY,IAAM,CAAC,CACnC,CAQA,IAAI,cAAyC,CACzC,OAAO,EAAA,mBACH,KAAK,SAAS,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"}
|
|
@@ -7,12 +7,15 @@ import * as a from "onnxruntime-web";
|
|
|
7
7
|
async function o(e) {
|
|
8
8
|
try {
|
|
9
9
|
let t = await fetch(e);
|
|
10
|
-
return t.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":["/**\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":";;;;;;AAyBA,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,G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K;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>;\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AAW;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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timing.cjs","names":[],"sources":["../../../src/vision/core/timing.ts"],"sourcesContent":["/**\n * Per-stage timing for a single `predict()` call.\n *\n * Populates the `speed` field every `Results` envelope carries, mirroring\n * Ultralytics' `results[0].speed`. All values are milliseconds measured with\n * `performance.now()`.\n */\n\n/**\n * Stage durations of one inference, in milliseconds.\n *\n * `preprocess`, `inference` and `postprocess` are the three keys Ultralytics\n * reports, measured over the same boundaries. `load` is specific to this SDK:\n * `predict()` accepts a URL, `Blob` or DOM element and decodes it internally,\n * so the fetch/decode cost would otherwise be invisible — and on a cold cache\n * it dominates everything else.\n */\nexport interface Speed {\n /** Fetching and decoding the input into an `RGBImage`. */\n load: number;\n /** Letterbox/resize, normalization and tensor packing. */\n preprocess: number;\n /** The ONNX Runtime forward pass. */\n inference: number;\n /** Decoding raw outputs into results (NMS, mask assembly, top-k). */\n postprocess: number;\n}\n\n/**\n * Accumulate stage durations while a `predict()` call runs.\n *\n * Each `stage()` call closes the previous stage: the elapsed time since the\n * last boundary is attributed to the name given. This keeps the call sites\n * free of paired start/stop bookkeeping and guarantees the four stages tile\n * the whole call without gaps.\n */\nexport class SpeedTimer {\n private _last: number;\n private readonly _speed: Speed = {\n load: 0,\n preprocess: 0,\n inference: 0,\n postprocess: 0,\n };\n\n constructor() {\n this._last = performance.now();\n }\n\n /**\n * Attribute the time elapsed since the previous boundary to `stage`.\n *\n * @param stage Which stage just finished.\n */\n stage(stage: keyof Speed): void {\n const now = performance.now();\n this._speed[stage] += now - this._last;\n this._last = now;\n }\n\n /**\n * The accumulated durations.\n *\n * @returns The `speed` object to hand to the `Results` envelope.\n */\n speed(): Speed {\n return { ...this._speed };\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"timing.cjs","names":[],"sources":["../../../src/vision/core/timing.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Per-stage timing for a single `predict()` call.\n *\n * Populates the `speed` field every `Results` envelope carries, mirroring\n * Ultralytics' `results[0].speed`. All values are milliseconds measured with\n * `performance.now()`.\n */\n\n/**\n * Stage durations of one inference, in milliseconds.\n *\n * `preprocess`, `inference` and `postprocess` are the three keys Ultralytics\n * reports, measured over the same boundaries. `load` is specific to this SDK:\n * `predict()` accepts a URL, `Blob` or DOM element and decodes it internally,\n * so the fetch/decode cost would otherwise be invisible — and on a cold cache\n * it dominates everything else.\n */\nexport interface Speed {\n /** Fetching and decoding the input into an `RGBImage`. */\n load: number;\n /** Letterbox/resize, normalization and tensor packing. */\n preprocess: number;\n /** The ONNX Runtime forward pass. */\n inference: number;\n /** Decoding raw outputs into results (NMS, mask assembly, top-k). */\n postprocess: number;\n}\n\n/**\n * Accumulate stage durations while a `predict()` call runs.\n *\n * Each `stage()` call closes the previous stage: the elapsed time since the\n * last boundary is attributed to the name given. This keeps the call sites\n * free of paired start/stop bookkeeping and guarantees the four stages tile\n * the whole call without gaps.\n */\nexport class SpeedTimer {\n private _last: number;\n private readonly _speed: Speed = {\n load: 0,\n preprocess: 0,\n inference: 0,\n postprocess: 0,\n };\n\n constructor() {\n this._last = performance.now();\n }\n\n /**\n * Attribute the time elapsed since the previous boundary to `stage`.\n *\n * @param stage Which stage just finished.\n */\n stage(stage: keyof Speed): void {\n const now = performance.now();\n this._speed[stage] += now - this._last;\n this._last = now;\n }\n\n /**\n * The accumulated durations.\n *\n * @returns The `speed` object to hand to the `Results` envelope.\n */\n speed(): Speed {\n return { ...this._speed };\n }\n}\n"],"mappings":"AAqCA,IAAa,EAAb,KAAwB,CACpB,MACA,OAAiC,CAC7B,KAAM,EACN,WAAY,EACZ,UAAW,EACX,YAAa,CACjB,EAEA,aAAc,CACV,KAAK,MAAQ,YAAY,IAAI,CACjC,CAOA,MAAM,EAA0B,CAC5B,IAAM,EAAM,YAAY,IAAI,EAC5B,KAAK,OAAO,IAAU,EAAM,KAAK,MACjC,KAAK,MAAQ,CACjB,CAOA,OAAe,CACX,MAAO,CAAE,GAAG,KAAK,MAAO,CAC5B,CACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timing.js","names":[],"sources":["../../../src/vision/core/timing.ts"],"sourcesContent":["/**\n * Per-stage timing for a single `predict()` call.\n *\n * Populates the `speed` field every `Results` envelope carries, mirroring\n * Ultralytics' `results[0].speed`. All values are milliseconds measured with\n * `performance.now()`.\n */\n\n/**\n * Stage durations of one inference, in milliseconds.\n *\n * `preprocess`, `inference` and `postprocess` are the three keys Ultralytics\n * reports, measured over the same boundaries. `load` is specific to this SDK:\n * `predict()` accepts a URL, `Blob` or DOM element and decodes it internally,\n * so the fetch/decode cost would otherwise be invisible — and on a cold cache\n * it dominates everything else.\n */\nexport interface Speed {\n /** Fetching and decoding the input into an `RGBImage`. */\n load: number;\n /** Letterbox/resize, normalization and tensor packing. */\n preprocess: number;\n /** The ONNX Runtime forward pass. */\n inference: number;\n /** Decoding raw outputs into results (NMS, mask assembly, top-k). */\n postprocess: number;\n}\n\n/**\n * Accumulate stage durations while a `predict()` call runs.\n *\n * Each `stage()` call closes the previous stage: the elapsed time since the\n * last boundary is attributed to the name given. This keeps the call sites\n * free of paired start/stop bookkeeping and guarantees the four stages tile\n * the whole call without gaps.\n */\nexport class SpeedTimer {\n private _last: number;\n private readonly _speed: Speed = {\n load: 0,\n preprocess: 0,\n inference: 0,\n postprocess: 0,\n };\n\n constructor() {\n this._last = performance.now();\n }\n\n /**\n * Attribute the time elapsed since the previous boundary to `stage`.\n *\n * @param stage Which stage just finished.\n */\n stage(stage: keyof Speed): void {\n const now = performance.now();\n this._speed[stage] += now - this._last;\n this._last = now;\n }\n\n /**\n * The accumulated durations.\n *\n * @returns The `speed` object to hand to the `Results` envelope.\n */\n speed(): Speed {\n return { ...this._speed };\n }\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"timing.js","names":[],"sources":["../../../src/vision/core/timing.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Per-stage timing for a single `predict()` call.\n *\n * Populates the `speed` field every `Results` envelope carries, mirroring\n * Ultralytics' `results[0].speed`. All values are milliseconds measured with\n * `performance.now()`.\n */\n\n/**\n * Stage durations of one inference, in milliseconds.\n *\n * `preprocess`, `inference` and `postprocess` are the three keys Ultralytics\n * reports, measured over the same boundaries. `load` is specific to this SDK:\n * `predict()` accepts a URL, `Blob` or DOM element and decodes it internally,\n * so the fetch/decode cost would otherwise be invisible — and on a cold cache\n * it dominates everything else.\n */\nexport interface Speed {\n /** Fetching and decoding the input into an `RGBImage`. */\n load: number;\n /** Letterbox/resize, normalization and tensor packing. */\n preprocess: number;\n /** The ONNX Runtime forward pass. */\n inference: number;\n /** Decoding raw outputs into results (NMS, mask assembly, top-k). */\n postprocess: number;\n}\n\n/**\n * Accumulate stage durations while a `predict()` call runs.\n *\n * Each `stage()` call closes the previous stage: the elapsed time since the\n * last boundary is attributed to the name given. This keeps the call sites\n * free of paired start/stop bookkeeping and guarantees the four stages tile\n * the whole call without gaps.\n */\nexport class SpeedTimer {\n private _last: number;\n private readonly _speed: Speed = {\n load: 0,\n preprocess: 0,\n inference: 0,\n postprocess: 0,\n };\n\n constructor() {\n this._last = performance.now();\n }\n\n /**\n * Attribute the time elapsed since the previous boundary to `stage`.\n *\n * @param stage Which stage just finished.\n */\n stage(stage: keyof Speed): void {\n const now = performance.now();\n this._speed[stage] += now - this._last;\n this._last = now;\n }\n\n /**\n * The accumulated durations.\n *\n * @returns The `speed` object to hand to the `Results` envelope.\n */\n speed(): Speed {\n return { ...this._speed };\n }\n}\n"],"mappings":";AAqCA,IAAa,IAAb,MAAwB;CACpB;CACA,SAAiC;EAC7B,MAAM;EACN,YAAY;EACZ,WAAW;EACX,aAAa;CACjB;CAEA,cAAc;EACV,KAAK,QAAQ,YAAY,IAAI;CACjC;CAOA,MAAM,GAA0B;EAC5B,IAAM,IAAM,YAAY,IAAI;EAE5B,AADA,KAAK,OAAO,MAAU,IAAM,KAAK,OACjC,KAAK,QAAQ;CACjB;CAOA,QAAe;EACX,OAAO,EAAE,GAAG,KAAK,OAAO;CAC5B;AACJ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
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,MAAM,GAAG,EAC3B,GAAI,EAAM,SAAW,EAAG,OAAO,KAC/B,IAAM,EAAQ,OAAO,EAAM,EAAE,EACvB,EAAS,OAAO,EAAM,EAAE,EAG9B,MAFI,CAAC,OAAO,UAAU,CAAK,GAAK,CAAC,OAAO,UAAU,CAAM,GACpD,EAAQ,GAAK,EAAS,EAAU,KAC7B,CAAC,EAAO,CAAM,CACzB,CASA,SAAS,EAAY,EAAyB,EAA0B,CACpE,GAAI,CAAC,EAAK,OAAO,EAC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