tempest-react-sdk 0.19.1 → 0.21.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 +5 -5
- package/dist/tempest-react-sdk.cjs +3 -3
- package/dist/tempest-react-sdk.cjs.map +1 -1
- package/dist/tempest-react-sdk.d.ts +209 -0
- package/dist/tempest-react-sdk.js +951 -852
- package/dist/tempest-react-sdk.js.map +1 -1
- package/dist/vision.cjs +1 -1
- package/dist/vision.cjs.map +1 -1
- package/dist/vision.d.ts +142 -0
- package/dist/vision.js +499 -354
- package/dist/vision.js.map +1 -1
- package/package.json +1 -1
package/dist/vision.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vision.cjs","sources":["../src/vision/core/exceptions.ts","../src/vision/types.ts","../src/vision/results.ts","../src/vision/labels.ts","../src/vision/core/providers.ts","../src/vision/core/session.ts","../src/vision/core/canvas.ts","../src/vision/io/image.ts","../src/vision/preprocess/image.ts","../src/vision/postprocess/classification.ts","../src/vision/postprocess/detection.ts","../src/vision/postprocess/segmentation.ts","../src/vision/tasks/base.ts","../src/vision/tasks/classifier.ts","../src/vision/tasks/detector.ts","../src/vision/tasks/segmenter.ts","../src/vision/index.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","/**\n * Public output types returned by the SDK's vision tasks.\n *\n * These types form the contract between the SDK and its callers. They mirror\n * the Python `ort-vision-sdk` output dataclasses 1-to-1.\n *\n * Naming is intentionally compatible with the Ultralytics / torchvision idiom\n * (`cls`, `conf`, `box`, `xyxy`, `xywh`, normalized variants) so code ported\n * from those projects keeps working with minimal edits. The original verbose\n * names (`classId`, `className`, `confidence`, `bbox`) are still populated for\n * backwards compatibility.\n */\n\nimport { ImageLoadError } from \"./core/exceptions\";\n\n/**\n * HWC RGB uint8 image — the canonical image format used across the SDK.\n *\n * `data.length` must equal `width * height * 3`. The buffer is laid out row\n * by row, top-to-bottom, with each pixel as `[R, G, B]`.\n */\nexport class RGBImage {\n constructor(\n public readonly data: Uint8Array,\n public readonly width: number,\n public readonly height: number,\n ) {\n if (data.length !== width * height * 3) {\n throw new ImageLoadError(\n `RGBImage data length ${data.length} does not match width * height * 3 = ${\n width * height * 3\n }.`,\n );\n }\n }\n}\n\n/**\n * Axis-aligned bounding box in absolute pixel coordinates (xyxy format).\n *\n * Coordinates refer to the original input image (before any internal resize),\n * so callers can map detections back onto their source image without any\n * additional bookkeeping.\n */\nexport class BoundingBox {\n constructor(\n public readonly x1: number,\n public readonly y1: number,\n public readonly x2: number,\n public readonly y2: number,\n ) {}\n\n /** Box width in pixels (clamped to non-negative). */\n get width(): number {\n return Math.max(0, this.x2 - this.x1);\n }\n\n /** Box height in pixels (clamped to non-negative). */\n get height(): number {\n return Math.max(0, this.y2 - this.y1);\n }\n\n /** Box area in pixels squared. */\n get area(): number {\n return this.width * this.height;\n }\n\n /** The box as `[x1, y1, x2, y2]` in absolute pixels (Ultralytics-style). */\n get xyxy(): readonly [number, number, number, number] {\n return [this.x1, this.y1, this.x2, this.y2];\n }\n\n /**\n * The box as `[cx, cy, w, h]` with `(cx, cy)` at the center.\n *\n * Matches Ultralytics' `boxes.xywh` and YOLO's native head format. For the\n * top-left `[x, y, w, h]` convention, use {@link asXywh}.\n */\n get xywh(): readonly [number, number, number, number] {\n return [(this.x1 + this.x2) / 2, (this.y1 + this.y2) / 2, this.width, this.height];\n }\n\n /**\n * The box as `[x1, y1, x2, y2]` normalized to `[0, 1]`.\n *\n * @param origShape `[height, width]` of the source image, in pixels.\n */\n xyxyn(origShape: readonly [number, number]): readonly [number, number, number, number] {\n const [h, w] = origShape;\n if (w <= 0 || h <= 0) return [0, 0, 0, 0];\n return [this.x1 / w, this.y1 / h, this.x2 / w, this.y2 / h];\n }\n\n /**\n * The box as `[cx, cy, w, h]` normalized to `[0, 1]`.\n *\n * @param origShape `[height, width]` of the source image, in pixels.\n */\n xywhn(origShape: readonly [number, number]): readonly [number, number, number, number] {\n const [h, w] = origShape;\n if (w <= 0 || h <= 0) return [0, 0, 0, 0];\n const [cx, cy, bw, bh] = this.xywh;\n return [cx / w, cy / h, bw / w, bh / h];\n }\n\n /** Returns `[x1, y1, x2, y2]`. */\n asXyxy(): readonly [number, number, number, number] {\n return [this.x1, this.y1, this.x2, this.y2];\n }\n\n /**\n * Returns `[x, y, width, height]` with `(x, y)` at the **top-left**.\n *\n * Note: this is the top-left convention. Ultralytics' `xywh` getter uses\n * **center** coordinates — for that, read {@link xywh}.\n */\n asXywh(): readonly [number, number, number, number] {\n return [this.x1, this.y1, this.width, this.height];\n }\n\n /** Returns `[x1, y1, x2, y2]` truncated to integers, useful for slicing arrays. */\n asIntXyxy(): readonly [number, number, number, number] {\n return [Math.trunc(this.x1), Math.trunc(this.y1), Math.trunc(this.x2), Math.trunc(this.y2)];\n }\n}\n\n/**\n * Probability assigned to a single class for a classification prediction.\n *\n * `cls` / `name` / `conf` are Ultralytics-style aliases populated alongside\n * the verbose `classId` / `className` / `probability` fields.\n */\nexport interface ClassProbability {\n readonly classId: number;\n readonly className: string;\n readonly probability: number;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `probability` (Ultralytics-style). */\n readonly conf: number;\n}\n\n/**\n * Output of an image classification inference.\n */\nexport interface ClassificationResult {\n readonly classId: number;\n readonly className: string;\n readonly confidence: number;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `confidence` (Ultralytics-style). */\n readonly conf: number;\n /** The original input image as an HWC RGB uint8 array. */\n readonly image: RGBImage;\n /**\n * Probabilities per class, sorted in descending order. The first entry\n * mirrors `classId`, `className`, and `confidence`. When `topK` was passed\n * to `predict`, the array is truncated to that length.\n */\n readonly probabilities: readonly ClassProbability[];\n}\n\n/**\n * Single detected object produced by an object-detection model.\n */\nexport interface DetectionResult {\n readonly classId: number;\n readonly className: string;\n readonly confidence: number;\n readonly bbox: BoundingBox;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `confidence` (Ultralytics-style). */\n readonly conf: number;\n /** Alias for `bbox` (Ultralytics-style). */\n readonly box: BoundingBox;\n /**\n * The original image cropped to `bbox`, HWC RGB uint8. Empty boxes\n * (zero area) yield a zero-sized `RGBImage`.\n */\n readonly croppedImage: RGBImage;\n}\n\n/**\n * Single-channel binary or grayscale mask, laid out row-major.\n *\n * `data.length` must equal `width * height`. For binary masks, values are\n * `0` (background) or `255` (foreground); soft masks may use the full\n * `[0, 255]` range.\n */\nexport class Mask {\n constructor(\n public readonly data: Uint8Array,\n public readonly width: number,\n public readonly height: number,\n ) {\n if (data.length !== width * height) {\n throw new ImageLoadError(\n `Mask data length ${data.length} does not match width * height = ${\n width * height\n }.`,\n );\n }\n }\n}\n\n/**\n * Single segmented instance produced by an instance-segmentation model.\n *\n * Mirrors {@link DetectionResult} and adds the per-instance binary mask\n * plus a \"ready-to-display\" background-removed crop.\n */\nexport interface SegmentationResult {\n readonly classId: number;\n readonly className: string;\n readonly confidence: number;\n readonly bbox: BoundingBox;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `confidence` (Ultralytics-style). */\n readonly conf: number;\n /** Alias for `bbox` (Ultralytics-style). */\n readonly box: BoundingBox;\n /**\n * Binary mask cropped to `bbox`. Values are `0` (background) or `255`\n * (foreground). Empty boxes yield a zero-sized `Mask`.\n */\n readonly mask: Mask;\n /**\n * The original image cropped to `bbox` with background pixels (where\n * `mask.data[i] === 0`) zeroed out. Empty boxes yield a zero-sized\n * `RGBImage`.\n */\n readonly segmentedImage: RGBImage;\n}\n","/**\n * Per-image result envelopes — Ultralytics-style `Results` for the SDK.\n *\n * Each `predict()` call returns a 1-element array of these envelopes,\n * mirroring `YOLO(\"img.jpg\")`. Each envelope holds:\n *\n * - A bulk-array view of the predictions (`Boxes`, `Probs`, `Masks`) with\n * the exact attribute names Ultralytics uses (`xyxy`, `xywh`, `xyxyn`,\n * `xywhn`, `cls`, `conf`, `data`, `top1`, `top5`).\n * - Per-instance dataclasses (`DetectionResult`, `SegmentationResult`,\n * `ClassProbability`) for callers who prefer the OO interface.\n * - `names`: `Record<number, string>` matching Ultralytics' `model.names`.\n * - `origImg` / `origShape` / `path`: provenance for the original input.\n */\n\nimport {\n type ClassificationResult,\n type DetectionResult,\n type RGBImage,\n type SegmentationResult,\n} from \"./types\";\n\n/**\n * Bulk numpy-style view of detected boxes for a single image.\n *\n * Mirrors Ultralytics' `Boxes` interface. Coordinates in {@link xyxy} and\n * {@link xywh} are absolute pixels in the original image; the `*n` variants\n * are normalized to `[0, 1]` using `origShape`.\n */\nexport class Boxes {\n /**\n * @param xyxy Flat array of length `4 * N` in `[x1, y1, x2, y2, ...]` order.\n * @param cls One class index per box, length `N`.\n * @param conf One confidence per box, length `N`.\n * @param origShape `[height, width]` of the original image.\n */\n constructor(\n public readonly xyxy: Float32Array,\n public readonly cls: Int32Array,\n public readonly conf: Float32Array,\n public readonly origShape: readonly [number, number],\n ) {}\n\n /** Number of detected boxes. */\n get length(): number {\n return this.cls.length;\n }\n\n /** `[N, 4]` shape of the `xyxy` view. */\n get shape(): readonly [number, number] {\n return [this.length, 4];\n }\n\n /** Boxes as `[N, 4]` `[cx, cy, w, h]` flat array in absolute pixels. */\n get xywh(): Float32Array {\n const out = new Float32Array(this.xyxy.length);\n for (let i = 0; i < this.length; i++) {\n const x1 = this.xyxy[i * 4] as number;\n const y1 = this.xyxy[i * 4 + 1] as number;\n const x2 = this.xyxy[i * 4 + 2] as number;\n const y2 = this.xyxy[i * 4 + 3] as number;\n out[i * 4] = (x1 + x2) / 2;\n out[i * 4 + 1] = (y1 + y2) / 2;\n out[i * 4 + 2] = x2 - x1;\n out[i * 4 + 3] = y2 - y1;\n }\n return out;\n }\n\n /** Boxes as `[N, 4]` `[x1, y1, x2, y2]` normalized to `[0, 1]`. */\n get xyxyn(): Float32Array {\n const [h, w] = this.origShape;\n const out = new Float32Array(this.xyxy.length);\n if (this.length === 0 || w <= 0 || h <= 0) return out;\n for (let i = 0; i < this.length; i++) {\n out[i * 4] = (this.xyxy[i * 4] as number) / w;\n out[i * 4 + 1] = (this.xyxy[i * 4 + 1] as number) / h;\n out[i * 4 + 2] = (this.xyxy[i * 4 + 2] as number) / w;\n out[i * 4 + 3] = (this.xyxy[i * 4 + 3] as number) / h;\n }\n return out;\n }\n\n /** Boxes as `[N, 4]` `[cx, cy, w, h]` normalized to `[0, 1]`. */\n get xywhn(): Float32Array {\n const xywh = this.xywh;\n const [h, w] = this.origShape;\n if (this.length === 0 || w <= 0 || h <= 0) return xywh;\n for (let i = 0; i < this.length; i++) {\n xywh[i * 4] = (xywh[i * 4] as number) / w;\n xywh[i * 4 + 1] = (xywh[i * 4 + 1] as number) / h;\n xywh[i * 4 + 2] = (xywh[i * 4 + 2] as number) / w;\n xywh[i * 4 + 3] = (xywh[i * 4 + 3] as number) / h;\n }\n return xywh;\n }\n\n /**\n * Concatenated `[N, 6]` array of `[x1, y1, x2, y2, conf, cls]`.\n *\n * Matches Ultralytics' `boxes.data`.\n */\n get data(): Float32Array {\n const out = new Float32Array(this.length * 6);\n for (let i = 0; i < this.length; i++) {\n out[i * 6] = this.xyxy[i * 4] as number;\n out[i * 6 + 1] = this.xyxy[i * 4 + 1] as number;\n out[i * 6 + 2] = this.xyxy[i * 4 + 2] as number;\n out[i * 6 + 3] = this.xyxy[i * 4 + 3] as number;\n out[i * 6 + 4] = this.conf[i] as number;\n out[i * 6 + 5] = this.cls[i] as number;\n }\n return out;\n }\n}\n\n/**\n * Top-k classification probabilities for a single image.\n *\n * Mirrors Ultralytics' `Probs` interface.\n */\nexport class Probs {\n /** @param data `[numClasses]` per-class probabilities, indexed by class id. */\n constructor(public readonly data: Float32Array) {}\n\n /** Number of classes. */\n get length(): number {\n return this.data.length;\n }\n\n /** `[numClasses]` shape of the underlying vector. */\n get shape(): readonly [number] {\n return [this.length];\n }\n\n /** Index of the most probable class. */\n get top1(): number {\n if (this.data.length === 0) return 0;\n let best = 0;\n let bestVal = this.data[0] as number;\n for (let i = 1; i < this.data.length; i++) {\n const v = this.data[i] as number;\n if (v > bestVal) {\n best = i;\n bestVal = v;\n }\n }\n return best;\n }\n\n /** Probability of the top-1 class. */\n get top1conf(): number {\n if (this.data.length === 0) return 0;\n return this.data[this.top1] as number;\n }\n\n /** Indices of the top-5 most probable classes, descending. */\n get top5(): Int32Array {\n return this._topK(5).indices;\n }\n\n /** Probabilities of the top-5 classes, descending. */\n get top5conf(): Float32Array {\n return this._topK(5).values;\n }\n\n private _topK(k: number): { indices: Int32Array; values: Float32Array } {\n const n = Math.min(k, this.data.length);\n const order: number[] = [];\n for (let i = 0; i < this.data.length; i++) order.push(i);\n order.sort((a, b) => (this.data[b] as number) - (this.data[a] as number));\n const indices = new Int32Array(n);\n const values = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n indices[i] = order[i] as number;\n values[i] = this.data[order[i] as number] as number;\n }\n return { indices, values };\n }\n}\n\n/**\n * Per-instance binary masks for a single image.\n *\n * Each mask is cropped to its instance's bounding box. To paint masks onto\n * a full-image canvas, use `xyxy[i]` as the top-left target.\n */\nexport class Masks {\n /**\n * @param data Per-instance binary masks (`Mask` objects from `types.ts`).\n * @param xyxy Flat `[N, 4]` of bounding-box coordinates in original pixels.\n * @param origShape `[height, width]` of the original image.\n */\n constructor(\n public readonly data: ReadonlyArray<{\n readonly data: Uint8Array;\n readonly width: number;\n readonly height: number;\n }>,\n public readonly xyxy: Float32Array,\n public readonly origShape: readonly [number, number],\n ) {}\n\n /** Number of instance masks. */\n get length(): number {\n return this.data.length;\n }\n\n /** `[N]` shape of the masks collection. */\n get shape(): readonly [number] {\n return [this.length];\n }\n\n [Symbol.iterator](): Iterator<{\n readonly data: Uint8Array;\n readonly width: number;\n readonly height: number;\n }> {\n return this.data[Symbol.iterator]();\n }\n}\n\n/**\n * Per-image detection envelope (Ultralytics-style `Results`).\n *\n * Iterating yields per-instance {@link DetectionResult} entries, so legacy\n * code that did `for (const d of detector.predict(img))` only needs an\n * extra `[0]` to bridge:\n *\n * ```typescript\n * for (const d of (await detector.predict(img))[0]) {\n * console.log(d.cls, d.conf, d.box.xyxy);\n * }\n * ```\n *\n * For numpy-style bulk access, use the `boxes` collection.\n */\nexport class DetectionResults implements Iterable<DetectionResult> {\n constructor(\n public readonly boxes: Boxes,\n public readonly detections: readonly DetectionResult[],\n public readonly names: Readonly<Record<number, string>>,\n public readonly origImg: RGBImage,\n public readonly origShape: readonly [number, number],\n public readonly path: string | null = null,\n public readonly speed: Readonly<Record<string, number>> = {},\n ) {}\n\n /** Number of surviving detections. */\n get length(): number {\n return this.detections.length;\n }\n\n /** Index into the per-instance detections. */\n get(index: number): DetectionResult | undefined {\n return this.detections[index];\n }\n\n [Symbol.iterator](): Iterator<DetectionResult> {\n return this.detections[Symbol.iterator]();\n }\n}\n\n/**\n * Per-image classification envelope (Ultralytics-style `Results`).\n */\nexport class ClassificationResults {\n constructor(\n public readonly probs: Probs,\n public readonly result: ClassificationResult,\n public readonly names: Readonly<Record<number, string>>,\n public readonly origImg: RGBImage,\n public readonly origShape: readonly [number, number],\n public readonly path: string | null = null,\n public readonly speed: Readonly<Record<string, number>> = {},\n ) {}\n\n /** Top-1 class index (Ultralytics-style alias). */\n get cls(): number {\n return this.probs.top1;\n }\n\n /** Top-1 confidence (Ultralytics-style alias). */\n get conf(): number {\n return this.probs.top1conf;\n }\n\n /** Top-1 class name. */\n get name(): string {\n return this.names[this.cls] ?? `class_${this.cls}`;\n }\n\n /** Per-class probability list, sorted descending (legacy field). */\n get probabilities(): readonly ClassificationResult[\"probabilities\"][number][] {\n return this.result.probabilities;\n }\n}\n\n/**\n * Per-image instance-segmentation envelope (Ultralytics-style `Results`).\n *\n * Iterating yields per-instance {@link SegmentationResult} entries. `boxes`\n * and `masks` mirror Ultralytics' bulk-array views.\n */\nexport class SegmentationResults implements Iterable<SegmentationResult> {\n constructor(\n public readonly boxes: Boxes,\n public readonly masks: Masks,\n public readonly detections: readonly SegmentationResult[],\n public readonly names: Readonly<Record<number, string>>,\n public readonly origImg: RGBImage,\n public readonly origShape: readonly [number, number],\n public readonly path: string | null = null,\n public readonly speed: Readonly<Record<string, number>> = {},\n ) {}\n\n /** Number of surviving instances. */\n get length(): number {\n return this.detections.length;\n }\n\n /** Index into the per-instance results. */\n get(index: number): SegmentationResult | undefined {\n return this.detections[index];\n }\n\n [Symbol.iterator](): Iterator<SegmentationResult> {\n return this.detections[Symbol.iterator]();\n }\n}\n","/**\n * Class label resolution: presets, lists, dicts, or auto-generated.\n *\n * Tasks call {@link resolveLabels} once at construction time to turn whatever\n * the caller passed (preset name, array, dict, or `null`) into an ordered\n * array of class names indexed by class id.\n *\n * In the browser there is no filesystem, so this module does not load labels\n * from a path — fetch the file yourself and pass an array.\n */\n\nimport { LabelMapError } from \"./core/exceptions\";\n\n/**\n * Anything accepted by {@link resolveLabels}.\n *\n * - `string[]` / `readonly string[]`: explicit names indexed by class id.\n * - `Record<number, string>`: sparse mapping (gaps filled with `class_<id>`).\n * - `string`: a preset name (e.g. `\"coco\"`).\n * - `null` / `undefined`: auto-generate `class_0` ... `class_{numClasses-1}`.\n */\nexport type LabelSpec = readonly string[] | Record<number, string> | string | null | undefined;\n\n/** COCO 2017 80-class labels in canonical class-id order. */\nexport const COCO_CLASSES: readonly string[] = Object.freeze([\n \"person\",\n \"bicycle\",\n \"car\",\n \"motorcycle\",\n \"airplane\",\n \"bus\",\n \"train\",\n \"truck\",\n \"boat\",\n \"traffic light\",\n \"fire hydrant\",\n \"stop sign\",\n \"parking meter\",\n \"bench\",\n \"bird\",\n \"cat\",\n \"dog\",\n \"horse\",\n \"sheep\",\n \"cow\",\n \"elephant\",\n \"bear\",\n \"zebra\",\n \"giraffe\",\n \"backpack\",\n \"umbrella\",\n \"handbag\",\n \"tie\",\n \"suitcase\",\n \"frisbee\",\n \"skis\",\n \"snowboard\",\n \"sports ball\",\n \"kite\",\n \"baseball bat\",\n \"baseball glove\",\n \"skateboard\",\n \"surfboard\",\n \"tennis racket\",\n \"bottle\",\n \"wine glass\",\n \"cup\",\n \"fork\",\n \"knife\",\n \"spoon\",\n \"bowl\",\n \"banana\",\n \"apple\",\n \"sandwich\",\n \"orange\",\n \"broccoli\",\n \"carrot\",\n \"hot dog\",\n \"pizza\",\n \"donut\",\n \"cake\",\n \"chair\",\n \"couch\",\n \"potted plant\",\n \"bed\",\n \"dining table\",\n \"toilet\",\n \"tv\",\n \"laptop\",\n \"mouse\",\n \"remote\",\n \"keyboard\",\n \"cell phone\",\n \"microwave\",\n \"oven\",\n \"toaster\",\n \"sink\",\n \"refrigerator\",\n \"book\",\n \"clock\",\n \"vase\",\n \"scissors\",\n \"teddy bear\",\n \"hair drier\",\n \"toothbrush\",\n]);\n\nconst PRESETS: Readonly<Record<string, readonly string[]>> = {\n coco: COCO_CLASSES,\n};\n\nexport interface ResolveLabelsOptions {\n /**\n * Expected number of classes.\n *\n * - When `spec` is `null`/`undefined`, this is required to auto-generate names.\n * - When `spec` is provided, it validates that the resolved length matches.\n */\n readonly numClasses?: number;\n}\n\n/**\n * Resolve a labels specification into an ordered array of class names.\n *\n * @throws {@link LabelMapError} if the spec is invalid, the preset is unknown,\n * or the resolved length disagrees with `numClasses`.\n */\nexport function resolveLabels(\n spec: LabelSpec,\n options: ResolveLabelsOptions = {},\n): readonly string[] {\n const labels = resolve(spec, options.numClasses);\n if (options.numClasses !== undefined && labels.length !== options.numClasses) {\n throw new LabelMapError(\n `Resolved ${labels.length} labels but the model has ${options.numClasses} classes.`,\n );\n }\n return labels;\n}\n\nfunction resolve(spec: LabelSpec, numClasses: number | undefined): readonly string[] {\n if (spec === null || spec === undefined) {\n if (numClasses === undefined) {\n throw new LabelMapError(\n \"Cannot auto-generate labels without numClasses. Pass an explicit labels spec or numClasses.\",\n );\n }\n return Array.from({ length: numClasses }, (_, i) => `class_${i}`);\n }\n\n if (Array.isArray(spec)) {\n return [...spec];\n }\n\n if (typeof spec === \"string\") {\n const preset = PRESETS[spec];\n if (preset !== undefined) {\n return preset;\n }\n throw new LabelMapError(\n `Unknown labels preset: ${JSON.stringify(spec)}. Known presets: ${Object.keys(PRESETS).join(\", \")}.`,\n );\n }\n\n if (typeof spec === \"object\") {\n const map = spec as Record<number, string>;\n const ids = Object.keys(map).map((k) => Number(k));\n if (ids.length === 0) {\n return [];\n }\n const maxId = Math.max(...ids);\n return Array.from({ length: maxId + 1 }, (_, i) => map[i] ?? `class_${i}`);\n }\n\n throw new LabelMapError(`Unsupported labels spec type: ${typeof spec}.`);\n}\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","/**\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 { resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\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\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names, manages execution-provider\n * selection, and provides a typed {@link OrtSession.run} method.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n public readonly providers: readonly string[],\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * @param model Either a URL string fetched by ORT, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list and pass-through `SessionOptions`.\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\n let session: ort.InferenceSession;\n try {\n if (typeof model === \"string\") {\n session = await ortRuntime.InferenceSession.create(model, sessionOptions);\n } else if (model instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(model, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n model 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);\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 /** 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","/**\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/** Get a 2D context from a canvas, throwing a typed error if the browser refuses. */\nexport function get2DContext(canvas: Canvas2D): Context2D {\n const ctx = canvas.getContext(\"2d\") 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","/**\n * Image loading utilities — convert any supported source into the canonical\n * {@link RGBImage} format.\n *\n * Browser-only: uses `fetch`, `createImageBitmap`, and a Canvas 2D context to\n * decode arbitrary inputs into a tightly-packed `Uint8Array` of HWC RGB pixels.\n */\n\nimport { createCanvas, get2DContext, imageDataToRGB } from \"../core/canvas\";\nimport { ImageLoadError } from \"../core/exceptions\";\nimport { RGBImage } from \"../types\";\n\n/** Anything {@link loadImage} accepts as an image input. */\nexport type ImageInput =\n | string\n | Blob\n | HTMLImageElement\n | HTMLCanvasElement\n | OffscreenCanvas\n | ImageBitmap\n | ImageData\n | RGBImage;\n\n/**\n * Load an image from any supported source into a HWC uint8 RGB array.\n *\n * @throws {@link ImageLoadError} if the source cannot be decoded or has an unsupported shape.\n */\nexport async function loadImage(source: ImageInput): Promise<RGBImage> {\n if (source instanceof RGBImage) {\n return source;\n }\n\n if (typeof ImageData !== \"undefined\" && source instanceof ImageData) {\n return imageDataToRGB(source);\n }\n\n if (typeof source === \"string\") {\n return loadFromUrl(source);\n }\n\n if (typeof Blob !== \"undefined\" && source instanceof Blob) {\n return loadFromBlob(source);\n }\n\n if (typeof HTMLImageElement !== \"undefined\" && source instanceof HTMLImageElement) {\n await waitForImageElement(source);\n return drawableToRGB(source, source.naturalWidth, source.naturalHeight);\n }\n\n if (typeof HTMLCanvasElement !== \"undefined\" && source instanceof HTMLCanvasElement) {\n return drawableToRGB(source, source.width, source.height);\n }\n\n if (typeof OffscreenCanvas !== \"undefined\" && source instanceof OffscreenCanvas) {\n return drawableToRGB(source, source.width, source.height);\n }\n\n if (typeof ImageBitmap !== \"undefined\" && source instanceof ImageBitmap) {\n return drawableToRGB(source, source.width, source.height);\n }\n\n throw new ImageLoadError(\n `Unsupported image source type: ${Object.prototype.toString.call(source)}`,\n );\n}\n\nasync function loadFromUrl(url: string): Promise<RGBImage> {\n let response: Response;\n try {\n response = await fetch(url);\n } catch (err) {\n throw new ImageLoadError(`Failed to fetch image from ${url}: ${(err as Error).message}`, {\n cause: err,\n });\n }\n if (!response.ok) {\n throw new ImageLoadError(\n `Failed to fetch image from ${url}: HTTP ${response.status} ${response.statusText}`,\n );\n }\n const blob = await response.blob();\n return loadFromBlob(blob);\n}\n\nasync function loadFromBlob(blob: Blob): Promise<RGBImage> {\n let bitmap: ImageBitmap;\n try {\n bitmap = await createImageBitmap(blob);\n } catch (err) {\n throw new ImageLoadError(`Failed to decode image blob: ${(err as Error).message}`, {\n cause: err,\n });\n }\n try {\n return drawableToRGB(bitmap, bitmap.width, bitmap.height);\n } finally {\n bitmap.close();\n }\n}\n\nfunction waitForImageElement(img: HTMLImageElement): Promise<void> {\n if (img.complete && img.naturalWidth > 0) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const onLoad = (): void => {\n cleanup();\n resolve();\n };\n const onError = (): void => {\n cleanup();\n reject(new ImageLoadError(\"Failed to load HTMLImageElement (load event errored)\"));\n };\n const cleanup = (): void => {\n img.removeEventListener(\"load\", onLoad);\n img.removeEventListener(\"error\", onError);\n };\n img.addEventListener(\"load\", onLoad, { once: true });\n img.addEventListener(\"error\", onError, { once: true });\n });\n}\n\nfunction drawableToRGB(drawable: CanvasImageSource, width: number, height: number): RGBImage {\n if (width === 0 || height === 0) {\n throw new ImageLoadError(`Cannot load image with zero dimension (${width}x${height}).`);\n }\n const canvas = createCanvas(width, height);\n const ctx = get2DContext(canvas);\n ctx.drawImage(drawable, 0, 0);\n const imageData = ctx.getImageData(0, 0, width, height);\n return imageDataToRGB(imageData);\n}\n","/**\n * Composable image preprocessing primitives (resize, normalize, letterbox, layout).\n *\n * Mirrors the Python `preprocess.image` module. Operates on the canonical\n * {@link RGBImage} (HWC RGB uint8) and produces uint8 or float32 buffers\n * depending on the operation.\n */\n\nimport * as ortRuntime from \"onnxruntime-web\";\nimport type * as ort from \"onnxruntime-web\";\n\nimport { createCanvas, get2DContext, imageDataToRGB, rgbToImageData } from \"../core/canvas\";\nimport { RGBImage } from \"../types\";\n\n/** Resize an image to `(targetWidth, targetHeight)` using high-quality canvas resampling. */\nexport function resize(image: RGBImage, targetWidth: number, targetHeight: number): RGBImage {\n if (targetWidth <= 0 || targetHeight <= 0) {\n throw new Error(`Invalid resize target ${targetWidth}x${targetHeight}.`);\n }\n if (targetWidth === image.width && targetHeight === image.height) {\n return image;\n }\n\n const srcCanvas = createCanvas(image.width, image.height);\n const srcCtx = get2DContext(srcCanvas);\n srcCtx.putImageData(rgbToImageData(image), 0, 0);\n\n const dstCanvas = createCanvas(targetWidth, targetHeight);\n const dstCtx = get2DContext(dstCanvas);\n dstCtx.imageSmoothingEnabled = true;\n dstCtx.imageSmoothingQuality = \"high\";\n dstCtx.drawImage(srcCanvas as CanvasImageSource, 0, 0, targetWidth, targetHeight);\n\n const imageData = dstCtx.getImageData(0, 0, targetWidth, targetHeight);\n return imageDataToRGB(imageData);\n}\n\n/**\n * Convert a uint8 image to a normalized float32 array (HWC layout preserved).\n *\n * Applies `(pixel * scale - mean) / std` channel-wise.\n */\nexport function normalize(\n image: RGBImage,\n mean: readonly [number, number, number],\n std: readonly [number, number, number],\n scale: number = 1 / 255,\n): Float32Array {\n const out = new Float32Array(image.data.length);\n const data = image.data;\n const m0 = mean[0];\n const m1 = mean[1];\n const m2 = mean[2];\n const s0 = std[0];\n const s1 = std[1];\n const s2 = std[2];\n for (let i = 0; i < data.length; i += 3) {\n out[i] = ((data[i] as number) * scale - m0) / s0;\n out[i + 1] = ((data[i + 1] as number) * scale - m1) / s1;\n out[i + 2] = ((data[i + 2] as number) * scale - m2) / s2;\n }\n return out;\n}\n\n/** Convert a uint8 image to a `Float32Array` in `[0, 1]` (HWC layout preserved). */\nexport function toFloat32(image: RGBImage, scale: number = 1 / 255): Float32Array {\n const out = new Float32Array(image.data.length);\n const data = image.data;\n for (let i = 0; i < data.length; i++) {\n out[i] = (data[i] as number) * scale;\n }\n return out;\n}\n\n/**\n * Transpose interleaved HWC data to planar CHW layout.\n *\n * @param hwc Source array of length `width * height * channels`.\n */\nexport function toCHW(\n hwc: Float32Array,\n width: number,\n height: number,\n channels: number = 3,\n): Float32Array {\n const expected = width * height * channels;\n if (hwc.length !== expected) {\n throw new Error(\n `toCHW: expected length ${expected} for ${width}x${height}x${channels}, got ${hwc.length}.`,\n );\n }\n const chw = new Float32Array(expected);\n const plane = width * height;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const hwcBase = (y * width + x) * channels;\n const planeIdx = y * width + x;\n for (let c = 0; c < channels; c++) {\n chw[c * plane + planeIdx] = hwc[hwcBase + c] as number;\n }\n }\n }\n return chw;\n}\n\n/** Wrap a Float32 buffer into an `ort.Tensor`. */\nexport function toFloat32Tensor(data: Float32Array, dims: readonly number[]): ort.Tensor {\n return new ortRuntime.Tensor(\"float32\", data, dims as number[]);\n}\n\n/**\n * Convert an HWC uint8 image to a CHW `Float32Array` scaled to `[0, 1]`.\n *\n * Mirrors `torchvision.transforms.ToTensor()` semantics: HWC → CHW,\n * `uint8 → float32 / 255`. Useful as input to YOLO-style detectors that\n * don't require ImageNet normalization.\n *\n * @returns CHW `Float32Array` of length `width * height * 3`.\n */\nexport function toTensor(image: RGBImage): Float32Array {\n const f32 = toFloat32(image);\n return toCHW(f32, image.width, image.height, 3);\n}\n\n/**\n * Convert an HWC BGR uint8 buffer (OpenCV layout) to the SDK's HWC RGB.\n *\n * Use when you receive image bytes from `cv2.imencode` over the wire and\n * want to feed them to the SDK without going through a canvas decode.\n *\n * @param bgr Flat BGR Uint8Array of length `width * height * 3`.\n */\nexport function fromCv2(bgr: Uint8Array, width: number, height: number): RGBImage {\n if (bgr.length !== width * height * 3) {\n throw new Error(\n `fromCv2: data length ${bgr.length} does not match width * height * 3 = ${width * height * 3}.`,\n );\n }\n const rgb = new Uint8Array(bgr.length);\n for (let i = 0; i < bgr.length; i += 3) {\n rgb[i] = bgr[i + 2] as number;\n rgb[i + 1] = bgr[i + 1] as number;\n rgb[i + 2] = bgr[i] as number;\n }\n return new RGBImage(rgb, width, height);\n}\n\n/**\n * Convert the SDK's HWC RGB image to an HWC BGR `Uint8Array` (OpenCV layout).\n *\n * Useful for round-tripping data to a Python OpenCV consumer.\n */\nexport function toCv2(image: RGBImage): Uint8Array {\n const rgb = image.data;\n const bgr = new Uint8Array(rgb.length);\n for (let i = 0; i < rgb.length; i += 3) {\n bgr[i] = rgb[i + 2] as number;\n bgr[i + 1] = rgb[i + 1] as number;\n bgr[i + 2] = rgb[i] as number;\n }\n return bgr;\n}\n\nexport interface LetterboxResult {\n /** The padded image at the target size. */\n readonly image: RGBImage;\n /** The factor applied to the original image (`< 1` if downscaled). */\n readonly scale: number;\n /** Horizontal padding in pixels (left side; right side has the same or +1). */\n readonly padLeft: number;\n /** Vertical padding in pixels (top side). */\n readonly padTop: number;\n}\n\n/**\n * Resize preserving aspect ratio, padding to `(targetWidth, targetHeight)`\n * with a constant fill color.\n *\n * Standard YOLO preprocessing — returning `scale` and `padLeft`/`padTop`\n * lets callers map detections back to the original image coordinates.\n */\nexport function letterbox(\n image: RGBImage,\n targetWidth: number,\n targetHeight: number,\n fill: readonly [number, number, number] = [114, 114, 114],\n): LetterboxResult {\n const scale = Math.min(targetWidth / image.width, targetHeight / image.height);\n const newW = Math.round(image.width * scale);\n const newH = Math.round(image.height * scale);\n const resized = resize(image, newW, newH);\n\n const out = new Uint8Array(targetWidth * targetHeight * 3);\n const f0 = fill[0];\n const f1 = fill[1];\n const f2 = fill[2];\n for (let i = 0; i < out.length; i += 3) {\n out[i] = f0;\n out[i + 1] = f1;\n out[i + 2] = f2;\n }\n\n const padLeft = Math.floor((targetWidth - newW) / 2);\n const padTop = Math.floor((targetHeight - newH) / 2);\n const rowBytes = newW * 3;\n for (let y = 0; y < newH; y++) {\n const srcOffset = y * rowBytes;\n const dstOffset = ((padTop + y) * targetWidth + padLeft) * 3;\n out.set(resized.data.subarray(srcOffset, srcOffset + rowBytes), dstOffset);\n }\n\n return {\n image: new RGBImage(out, targetWidth, targetHeight),\n scale,\n padLeft,\n padTop,\n };\n}\n","/**\n * Classification head postprocessing — softmax + top-k.\n */\n\n/** Apply numerically-stable softmax to a 1-D vector of logits. */\nexport function softmax(logits: Float32Array | readonly number[]): Float32Array {\n const n = logits.length;\n const out = new Float32Array(n);\n let max = -Infinity;\n for (let i = 0; i < n; i++) {\n const v = logits[i] as number;\n if (v > max) max = v;\n }\n let sum = 0;\n for (let i = 0; i < n; i++) {\n const e = Math.exp((logits[i] as number) - max);\n out[i] = e;\n sum += e;\n }\n for (let i = 0; i < n; i++) {\n out[i] = (out[i] as number) / sum;\n }\n return out;\n}\n\nexport interface TopKResult {\n readonly indices: Int32Array;\n readonly values: Float32Array;\n}\n\n/**\n * Return the top-k entries of a 1-D probability vector, sorted descending.\n *\n * @param k Number of entries to return; `null` returns all entries.\n */\nexport function topK(probabilities: Float32Array, k: number | null): TopKResult {\n const n = probabilities.length;\n const kEff = k === null ? n : Math.min(Math.max(0, k), n);\n\n const idx = new Array<number>(n);\n for (let i = 0; i < n; i++) idx[i] = i;\n idx.sort((a, b) => (probabilities[b] as number) - (probabilities[a] as number));\n\n const indices = new Int32Array(kEff);\n const values = new Float32Array(kEff);\n for (let i = 0; i < kEff; i++) {\n const j = idx[i] as number;\n indices[i] = j;\n values[i] = probabilities[j] as number;\n }\n return { indices, values };\n}\n","/**\n * Detection head postprocessing: anchor-free YOLO decoding + non-maximum suppression.\n *\n * The shared {@link decodeYoloAnchors} helper does the per-anchor work that\n * is identical for plain detection and segmentation (transpose, xywh→xyxy,\n * letterbox unmap, per-class NMS, sort & cap). {@link decodeYolo} is a thin\n * wrapper around it; the segmentation module ({@link ./segmentation.js})\n * calls the helper directly so it can also recover the per-anchor mask\n * coefficients.\n *\n * Works for any YOLO export with the post-v8 anchor-free head:\n * **YOLOv8 / v9 / v10 / v11 / v12** detect heads, all of which share the\n * `[1, 4 + nc, N]` output layout.\n */\n\nimport { BoundingBox } from \"../types\";\n\n/**\n * Greedy non-maximum suppression on axis-aligned bounding boxes.\n *\n * Mirrors `torchvision.ops.nms` (keeps boxes with the highest score, drops\n * any subsequent box whose IoU exceeds the threshold).\n *\n * @param boxes Flat array of length `4 * N` in xyxy order: `[x1,y1,x2,y2, ...]`.\n * @param scores Detection score per box, length `N`.\n * @param iouThreshold Boxes with IoU above this threshold relative to a kept box are suppressed.\n * @returns Indices of kept boxes, in descending score order.\n */\nexport function nms(boxes: Float32Array, scores: Float32Array, iouThreshold: number): Int32Array {\n const n = scores.length;\n if (n === 0) return new Int32Array(0);\n\n const areas = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const x1 = boxes[i * 4] as number;\n const y1 = boxes[i * 4 + 1] as number;\n const x2 = boxes[i * 4 + 2] as number;\n const y2 = boxes[i * 4 + 3] as number;\n areas[i] = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);\n }\n\n const order = new Array<number>(n);\n for (let i = 0; i < n; i++) order[i] = i;\n order.sort((a, b) => (scores[b] as number) - (scores[a] as number));\n\n const suppressed = new Uint8Array(n);\n const keep: number[] = [];\n\n for (let oi = 0; oi < order.length; oi++) {\n const i = order[oi] as number;\n if (suppressed[i]) continue;\n keep.push(i);\n\n const ax1 = boxes[i * 4] as number;\n const ay1 = boxes[i * 4 + 1] as number;\n const ax2 = boxes[i * 4 + 2] as number;\n const ay2 = boxes[i * 4 + 3] as number;\n const ai = areas[i] as number;\n\n for (let oj = oi + 1; oj < order.length; oj++) {\n const j = order[oj] as number;\n if (suppressed[j]) continue;\n\n const bx1 = boxes[j * 4] as number;\n const by1 = boxes[j * 4 + 1] as number;\n const bx2 = boxes[j * 4 + 2] as number;\n const by2 = boxes[j * 4 + 3] as number;\n\n const ix1 = Math.max(ax1, bx1);\n const iy1 = Math.max(ay1, by1);\n const ix2 = Math.min(ax2, bx2);\n const iy2 = Math.min(ay2, by2);\n const iw = Math.max(0, ix2 - ix1);\n const ih = Math.max(0, iy2 - iy1);\n const inter = iw * ih;\n const union = ai + (areas[j] as number) - inter;\n const iou = union > 0 ? inter / union : 0;\n if (iou > iouThreshold) suppressed[j] = 1;\n }\n }\n\n return Int32Array.from(keep);\n}\n\n/**\n * Per-class NMS — boxes are suppressed only by other boxes of the same class.\n *\n * Mirrors `torchvision.ops.batched_nms`.\n *\n * @param boxes Flat array of length `4 * N` in xyxy order.\n * @param scores Detection score per box, length `N`.\n * @param idxs Class index per box, length `N`. Boxes with different `idxs`\n * never suppress each other.\n * @param iouThreshold IoU threshold for suppression within a class.\n */\nexport function batchedNms(\n boxes: Float32Array,\n scores: Float32Array,\n idxs: Int32Array,\n iouThreshold: number,\n): Int32Array {\n if (scores.length === 0) return new Int32Array(0);\n\n const byClass = new Map<number, number[]>();\n for (let i = 0; i < idxs.length; i++) {\n const c = idxs[i] as number;\n const list = byClass.get(c);\n if (list === undefined) byClass.set(c, [i]);\n else list.push(i);\n }\n\n const keep: number[] = [];\n for (const indices of byClass.values()) {\n const m = indices.length;\n const subBoxes = new Float32Array(m * 4);\n const subScores = new Float32Array(m);\n for (let k = 0; k < m; k++) {\n const i = indices[k] as number;\n subBoxes[k * 4] = boxes[i * 4] as number;\n subBoxes[k * 4 + 1] = boxes[i * 4 + 1] as number;\n subBoxes[k * 4 + 2] = boxes[i * 4 + 2] as number;\n subBoxes[k * 4 + 3] = boxes[i * 4 + 3] as number;\n subScores[k] = scores[i] as number;\n }\n const subKeep = nms(subBoxes, subScores, iouThreshold);\n for (let k = 0; k < subKeep.length; k++) {\n keep.push(indices[subKeep[k] as number] as number);\n }\n }\n\n keep.sort((a, b) => (scores[b] as number) - (scores[a] as number));\n return Int32Array.from(keep);\n}\n\nexport interface DecodeYoloAnchorsOptions {\n /** Number of class-score channels following the 4 box channels. */\n readonly numClasses: number;\n readonly originalWidth: number;\n readonly originalHeight: number;\n readonly padLeft: number;\n readonly padTop: number;\n readonly scale: number;\n readonly confThreshold: number;\n readonly iouThreshold: number;\n readonly maxDetections: number;\n}\n\nexport interface DecodedAnchors {\n /** Indices into the original `numAnchors` axis, in descending confidence order. */\n readonly anchorIndices: Int32Array;\n /** `[k, 4]` boxes in original-image pixel coords, flat row-major xyxy. */\n readonly boxesXyxy: Float32Array;\n /** Predicted class id per survivor. */\n readonly classIds: Int32Array;\n /** Confidence per survivor. */\n readonly confidences: Float32Array;\n}\n\n/**\n * Shared YOLO per-anchor decode used by both detection and segmentation\n * (v8 / v9 / v10 / v11 / v12).\n *\n * Only the first `4 + numClasses` channels are read; later channels (e.g.\n * mask coefficients) are ignored — callers can fetch them via the returned\n * {@link DecodedAnchors.anchorIndices}.\n *\n * @param data Flat per-anchor output, length `channels * numAnchors`.\n * @param dims Dims as reported by ORT, e.g. `[1, 84, 8400]` (det) or\n * `[1, 116, 8400]` (seg). The leading batch dim must be 1.\n */\nexport function decodeYoloAnchors(\n data: Float32Array,\n dims: readonly number[],\n options: DecodeYoloAnchorsOptions,\n): DecodedAnchors {\n let normalized = dims;\n if (normalized.length === 3) {\n if (normalized[0] !== 1) {\n throw new Error(`decodeYoloAnchors: expected batch size 1, got ${normalized[0]}.`);\n }\n normalized = [normalized[1] as number, normalized[2] as number];\n }\n if (normalized.length !== 2) {\n throw new Error(\n `decodeYoloAnchors: expected 2-D output after batch removal, got dims=${JSON.stringify(dims)}.`,\n );\n }\n const channels = normalized[0] as number;\n const numAnchors = normalized[1] as number;\n\n const {\n numClasses,\n originalWidth,\n originalHeight,\n padLeft,\n padTop,\n scale,\n confThreshold,\n iouThreshold,\n maxDetections,\n } = options;\n\n if (numClasses < 1 || numClasses + 4 > channels) {\n throw new Error(\n `decodeYoloAnchors: invalid numClasses=${numClasses} for channels=${channels}.`,\n );\n }\n if (data.length !== channels * numAnchors) {\n throw new Error(\n `decodeYoloAnchors: data length ${data.length} does not match channels*numAnchors=${channels * numAnchors}.`,\n );\n }\n\n type Candidate = {\n anchorIdx: number;\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n classId: number;\n confidence: number;\n };\n const candidates: Candidate[] = [];\n\n for (let a = 0; a < numAnchors; a++) {\n let bestCls = 0;\n let bestScore = -Infinity;\n for (let c = 0; c < numClasses; c++) {\n const s = data[(4 + c) * numAnchors + a];\n if (s !== undefined && s > bestScore) {\n bestScore = s;\n bestCls = c;\n }\n }\n if (bestScore < confThreshold) continue;\n\n const cx = data[a] as number;\n const cy = data[numAnchors + a] as number;\n const w = data[2 * numAnchors + a] as number;\n const h = data[3 * numAnchors + a] as number;\n\n let x1 = cx - w / 2;\n let y1 = cy - h / 2;\n let x2 = cx + w / 2;\n let y2 = cy + h / 2;\n\n x1 = (x1 - padLeft) / scale;\n y1 = (y1 - padTop) / scale;\n x2 = (x2 - padLeft) / scale;\n y2 = (y2 - padTop) / scale;\n\n x1 = Math.max(0, Math.min(originalWidth, x1));\n y1 = Math.max(0, Math.min(originalHeight, y1));\n x2 = Math.max(0, Math.min(originalWidth, x2));\n y2 = Math.max(0, Math.min(originalHeight, y2));\n\n candidates.push({ anchorIdx: a, x1, y1, x2, y2, classId: bestCls, confidence: bestScore });\n }\n\n if (candidates.length === 0) return emptyDecoded();\n\n // Build flat arrays then delegate to batchedNms — same algorithm as before\n // but funnelled through the public per-class NMS helper.\n const flatBoxes = new Float32Array(candidates.length * 4);\n const scoresArr = new Float32Array(candidates.length);\n const idxsArr = new Int32Array(candidates.length);\n for (let i = 0; i < candidates.length; i++) {\n const c = candidates[i] as Candidate;\n flatBoxes[i * 4] = c.x1;\n flatBoxes[i * 4 + 1] = c.y1;\n flatBoxes[i * 4 + 2] = c.x2;\n flatBoxes[i * 4 + 3] = c.y2;\n scoresArr[i] = c.confidence;\n idxsArr[i] = c.classId;\n }\n const kept = batchedNms(flatBoxes, scoresArr, idxsArr, iouThreshold);\n if (kept.length === 0) return emptyDecoded();\n\n const limited = Array.from(kept).slice(0, maxDetections);\n const k = limited.length;\n const anchorIndices = new Int32Array(k);\n const boxesXyxy = new Float32Array(k * 4);\n const classIds = new Int32Array(k);\n const confidences = new Float32Array(k);\n for (let i = 0; i < k; i++) {\n const c = candidates[limited[i] as number] as Candidate;\n anchorIndices[i] = c.anchorIdx;\n boxesXyxy[i * 4] = c.x1;\n boxesXyxy[i * 4 + 1] = c.y1;\n boxesXyxy[i * 4 + 2] = c.x2;\n boxesXyxy[i * 4 + 3] = c.y2;\n classIds[i] = c.classId;\n confidences[i] = c.confidence;\n }\n return { anchorIndices, boxesXyxy, classIds, confidences };\n}\n\nfunction emptyDecoded(): DecodedAnchors {\n return {\n anchorIndices: new Int32Array(0),\n boxesXyxy: new Float32Array(0),\n classIds: new Int32Array(0),\n confidences: new Float32Array(0),\n };\n}\n\nexport interface DecodeYoloOptions {\n readonly originalWidth: number;\n readonly originalHeight: number;\n readonly padLeft: number;\n readonly padTop: number;\n readonly scale: number;\n readonly confThreshold: number;\n readonly iouThreshold: number;\n readonly maxDetections: number;\n}\n\nexport interface DecodedDetection {\n readonly bbox: BoundingBox;\n readonly classId: number;\n readonly confidence: number;\n}\n\n/**\n * Decode an anchor-free YOLO detection output into a list of detections.\n *\n * Works for **YOLOv8 / v9 / v10 / v11 / v12** detect heads.\n *\n * Expected raw shape: `[1, 4 + numClasses, N]`. `numClasses` is inferred\n * from the channel count.\n */\nexport function decodeYolo(\n output: Float32Array,\n outputDims: readonly number[],\n options: DecodeYoloOptions,\n): DecodedDetection[] {\n const channels = outputDims.length === 3 ? outputDims[1] : outputDims[0];\n if (channels === undefined || channels < 5) {\n throw new Error(`decodeYolo: invalid output channel count ${channels} (expected >= 5).`);\n }\n const numClasses = channels - 4;\n\n const decoded = decodeYoloAnchors(output, outputDims, {\n numClasses,\n ...options,\n });\n\n const results: DecodedDetection[] = [];\n for (let i = 0; i < decoded.classIds.length; i++) {\n results.push({\n bbox: new BoundingBox(\n decoded.boxesXyxy[i * 4] as number,\n decoded.boxesXyxy[i * 4 + 1] as number,\n decoded.boxesXyxy[i * 4 + 2] as number,\n decoded.boxesXyxy[i * 4 + 3] as number,\n ),\n classId: decoded.classIds[i] as number,\n confidence: decoded.confidences[i] as number,\n });\n }\n return results;\n}\n\nlet _warnedDecodeYoloV8 = false;\nlet _warnedDecodeYoloV8Anchors = false;\n\n/**\n * @deprecated since 0.2.0 — use {@link decodeYolo}. Same behavior; the\n * decoder covers v8/v9/v10/v11/v12 detect heads. Will be removed in 0.3.0.\n */\nexport function decodeYoloV8(\n output: Float32Array,\n outputDims: readonly number[],\n options: DecodeYoloOptions,\n): DecodedDetection[] {\n if (!_warnedDecodeYoloV8) {\n _warnedDecodeYoloV8 = true;\n console.warn(\n \"[@ort-vision-sdk/web] decodeYoloV8 is deprecated since 0.2.0; use decodeYolo. \" +\n \"The alias will be removed in 0.3.0.\",\n );\n }\n return decodeYolo(output, outputDims, options);\n}\n\n/**\n * @deprecated since 0.2.0 — use {@link decodeYoloAnchors}. Will be removed in 0.3.0.\n */\nexport function decodeYoloV8Anchors(\n data: Float32Array,\n dims: readonly number[],\n options: DecodeYoloAnchorsOptions,\n): DecodedAnchors {\n if (!_warnedDecodeYoloV8Anchors) {\n _warnedDecodeYoloV8Anchors = true;\n console.warn(\n \"[@ort-vision-sdk/web] decodeYoloV8Anchors is deprecated since 0.2.0; use decodeYoloAnchors. \" +\n \"The alias will be removed in 0.3.0.\",\n );\n }\n return decodeYoloAnchors(data, dims, options);\n}\n\n/** @deprecated since 0.2.0 — use {@link DecodeYoloAnchorsOptions}. */\nexport type DecodeYoloV8AnchorsOptions = DecodeYoloAnchorsOptions;\n\n/** @deprecated since 0.2.0 — use {@link DecodeYoloOptions}. */\nexport type DecodeYoloV8Options = DecodeYoloOptions;\n","/**\n * Segmentation head postprocessing: YOLO instance-segmentation decoding.\n *\n * Compatible with YOLOv8-seg / YOLOv11-seg exports (and any later seg head\n * sharing the layout). The model produces two output tensors:\n *\n * - `output0` of shape `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — the\n * same per-anchor predictions as plain YOLO detection plus an extra\n * `numMaskCoefs` (typically 32) channels of mask coefficients.\n * - `output1` of shape `(1, numMaskCoefs, maskH, maskW)` — a set of \"prototype\"\n * masks shared across all anchors.\n *\n * The per-anchor decode (xywh→xyxy, undo letterbox, per-class NMS, sort & cap)\n * is delegated to {@link decodeYoloAnchors}; this module only handles the\n * mask-specific work: matmul against prototypes, sigmoid, bilinear resize and\n * thresholding.\n */\n\nimport { decodeYoloAnchors } from \"./detection\";\nimport { BoundingBox, Mask } from \"../types\";\n\nexport interface DecodeYoloSegOptions {\n readonly numClasses: number;\n /** Model input `[width, height]` (post-letterbox). */\n readonly inputWidth: number;\n readonly inputHeight: number;\n /** Original image `[width, height]`. */\n readonly originalWidth: number;\n readonly originalHeight: number;\n /** Letterbox horizontal padding in input-tensor pixels. */\n readonly padLeft: number;\n /** Letterbox vertical padding in input-tensor pixels. */\n readonly padTop: number;\n /** Letterbox scale factor. */\n readonly scale: number;\n readonly confThreshold: number;\n readonly iouThreshold: number;\n readonly maxDetections: number;\n /** Probability cutoff applied to the soft mask. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface DecodedSegmentation {\n readonly bbox: BoundingBox;\n readonly classId: number;\n readonly confidence: number;\n /** Binary mask cropped to `bbox`. Width/height match `bbox.asIntXyxy()` extents. */\n readonly mask: Mask;\n}\n\n/**\n * Decode YOLO segmentation raw outputs into a list of segmented instances.\n *\n * Compatible with YOLOv8-seg / YOLOv11-seg.\n *\n * @param perAnchorData Flat `output0`, length `(4 + numClasses + numMaskCoefs) * numAnchors`.\n * @param perAnchorDims Dims as reported by ORT, e.g. `[1, 116, 8400]`.\n * @param prototypeData Flat `output1`, length `numMaskCoefs * maskH * maskW`.\n * @param prototypeDims Dims as reported by ORT, e.g. `[1, 32, 160, 160]`.\n */\nexport function decodeYoloSeg(\n perAnchorData: Float32Array,\n perAnchorDims: readonly number[],\n prototypeData: Float32Array,\n prototypeDims: readonly number[],\n options: DecodeYoloSegOptions,\n): DecodedSegmentation[] {\n // Strip batch dim from prototypes; perAnchor batch is validated by the helper.\n let pDims = prototypeDims;\n if (pDims.length === 4) {\n if (pDims[0] !== 1) {\n throw new Error(`decodeYoloSeg: expected batch size 1 in prototypes, got ${pDims[0]}.`);\n }\n pDims = [pDims[1] as number, pDims[2] as number, pDims[3] as number];\n }\n if (pDims.length !== 3) {\n throw new Error(\n `decodeYoloSeg: expected 3-D prototypes after batch removal, got dims=${JSON.stringify(prototypeDims)}.`,\n );\n }\n const numMaskCoefs = pDims[0] as number;\n const maskH = pDims[1] as number;\n const maskW = pDims[2] as number;\n\n const channels = perAnchorDims.length === 3 ? perAnchorDims[1] : perAnchorDims[0];\n const numAnchors = perAnchorDims.length === 3 ? perAnchorDims[2] : perAnchorDims[1];\n if (channels === undefined || numAnchors === undefined) {\n throw new Error(\n `decodeYoloSeg: cannot read channels/numAnchors from dims=${JSON.stringify(perAnchorDims)}.`,\n );\n }\n\n const expectedChannels = 4 + options.numClasses + numMaskCoefs;\n if (channels !== expectedChannels) {\n throw new Error(\n `decodeYoloSeg: channels=${channels} does not match 4 + numClasses(${options.numClasses}) + numMaskCoefs(${numMaskCoefs}) = ${expectedChannels}.`,\n );\n }\n if (prototypeData.length !== numMaskCoefs * maskH * maskW) {\n throw new Error(\n `decodeYoloSeg: prototype length ${prototypeData.length} does not match dims=${JSON.stringify(prototypeDims)}.`,\n );\n }\n\n const decoded = decodeYoloAnchors(perAnchorData, perAnchorDims, {\n numClasses: options.numClasses,\n originalWidth: options.originalWidth,\n originalHeight: options.originalHeight,\n padLeft: options.padLeft,\n padTop: options.padTop,\n scale: options.scale,\n confThreshold: options.confThreshold,\n iouThreshold: options.iouThreshold,\n maxDetections: options.maxDetections,\n });\n\n if (decoded.anchorIndices.length === 0) return [];\n\n const maskThreshold = options.maskThreshold ?? 0.5;\n const scaleX = maskW / options.inputWidth;\n const scaleY = maskH / options.inputHeight;\n const protoPlane = maskH * maskW;\n const coefBase = (4 + options.numClasses) * numAnchors;\n\n const results: DecodedSegmentation[] = [];\n\n for (let i = 0; i < decoded.anchorIndices.length; i++) {\n const a = decoded.anchorIndices[i] as number;\n const x1 = decoded.boxesXyxy[i * 4] as number;\n const y1 = decoded.boxesXyxy[i * 4 + 1] as number;\n const x2 = decoded.boxesXyxy[i * 4 + 2] as number;\n const y2 = decoded.boxesXyxy[i * 4 + 3] as number;\n const bbox = new BoundingBox(x1, y1, x2, y2);\n const classId = decoded.classIds[i] as number;\n const confidence = decoded.confidences[i] as number;\n\n const bboxW = Math.max(0, Math.trunc(x2) - Math.trunc(x1));\n const bboxH = Math.max(0, Math.trunc(y2) - Math.trunc(y1));\n\n if (bboxW === 0 || bboxH === 0) {\n results.push({ bbox, classId, confidence, mask: new Mask(new Uint8Array(0), 0, 0) });\n continue;\n }\n\n // Bbox in input-tensor coords, then in low-res mask coords.\n const ibx1 = x1 * options.scale + options.padLeft;\n const iby1 = y1 * options.scale + options.padTop;\n const ibx2 = x2 * options.scale + options.padLeft;\n const iby2 = y2 * options.scale + options.padTop;\n\n const mbx1 = Math.max(0, Math.floor(ibx1 * scaleX));\n const mby1 = Math.max(0, Math.floor(iby1 * scaleY));\n const mbx2 = Math.min(maskW, Math.ceil(ibx2 * scaleX));\n const mby2 = Math.min(maskH, Math.ceil(iby2 * scaleY));\n\n if (mbx2 <= mbx1 || mby2 <= mby1) {\n results.push({\n bbox,\n classId,\n confidence,\n mask: new Mask(new Uint8Array(bboxW * bboxH), bboxW, bboxH),\n });\n continue;\n }\n\n // Compute soft mask only within the prototype region under this bbox.\n const cropW = mbx2 - mbx1;\n const cropH = mby2 - mby1;\n const softCrop = new Float32Array(cropW * cropH);\n for (let y = 0; y < cropH; y++) {\n const py = mby1 + y;\n for (let x = 0; x < cropW; x++) {\n const px = mbx1 + x;\n let sum = 0;\n for (let kk = 0; kk < numMaskCoefs; kk++) {\n const coef = perAnchorData[coefBase + kk * numAnchors + a];\n const proto = prototypeData[kk * protoPlane + py * maskW + px];\n sum += coef * proto;\n }\n softCrop[y * cropW + x] = sigmoid(sum);\n }\n }\n\n const resized = resizeBilinear(softCrop, cropW, cropH, bboxW, bboxH);\n const binary = new Uint8Array(bboxW * bboxH);\n for (let j = 0; j < binary.length; j++) {\n binary[j] = resized[j] >= maskThreshold ? 255 : 0;\n }\n\n results.push({ bbox, classId, confidence, mask: new Mask(binary, bboxW, bboxH) });\n }\n\n return results;\n}\n\nfunction sigmoid(x: number): number {\n if (x >= 0) {\n return 1 / (1 + Math.exp(-x));\n }\n const e = Math.exp(x);\n return e / (1 + e);\n}\n\nlet _warnedDecodeYoloV8Seg = false;\n\n/** @deprecated since 0.2.0 — use {@link decodeYoloSeg}. Will be removed in 0.3.0. */\nexport function decodeYoloV8Seg(\n perAnchorData: Float32Array,\n perAnchorDims: readonly number[],\n prototypeData: Float32Array,\n prototypeDims: readonly number[],\n options: DecodeYoloSegOptions,\n): DecodedSegmentation[] {\n if (!_warnedDecodeYoloV8Seg) {\n _warnedDecodeYoloV8Seg = true;\n console.warn(\n \"[@ort-vision-sdk/web] decodeYoloV8Seg is deprecated since 0.2.0; use decodeYoloSeg. \" +\n \"The alias will be removed in 0.3.0.\",\n );\n }\n return decodeYoloSeg(perAnchorData, perAnchorDims, prototypeData, prototypeDims, options);\n}\n\n/** @deprecated since 0.2.0 — use {@link DecodeYoloSegOptions}. */\nexport type DecodeYoloV8SegOptions = DecodeYoloSegOptions;\n\nfunction resizeBilinear(\n src: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number,\n): Float32Array {\n const out = new Float32Array(targetWidth * targetHeight);\n if (targetWidth === 0 || targetHeight === 0 || srcWidth === 0 || srcHeight === 0) {\n return out;\n }\n if (targetWidth === srcWidth && targetHeight === srcHeight) {\n out.set(src);\n return out;\n }\n const sx = srcWidth / targetWidth;\n const sy = srcHeight / targetHeight;\n for (let y = 0; y < targetHeight; y++) {\n const yy = (y + 0.5) * sy - 0.5;\n const y0 = Math.max(0, Math.floor(yy));\n const y1 = Math.min(srcHeight - 1, y0 + 1);\n const wy = Math.max(0, Math.min(1, yy - y0));\n for (let x = 0; x < targetWidth; x++) {\n const xx = (x + 0.5) * sx - 0.5;\n const x0 = Math.max(0, Math.floor(xx));\n const x1 = Math.min(srcWidth - 1, x0 + 1);\n const wx = Math.max(0, Math.min(1, xx - x0));\n const v00 = src[y0 * srcWidth + x0];\n const v01 = src[y0 * srcWidth + x1];\n const v10 = src[y1 * srcWidth + x0];\n const v11 = src[y1 * srcWidth + x1];\n const top = v00 * (1 - wx) + v01 * wx;\n const bot = v10 * (1 - wx) + v11 * wx;\n out[y * targetWidth + x] = top * (1 - wy) + bot * wy;\n }\n }\n return out;\n}\n","/**\n * Common foundation for task-oriented vision SDK objects.\n *\n * The base only owns the {@link OrtSession} — label resolution lives in each\n * subclass because how `numClasses` is read from the model differs per task.\n */\n\nimport type { OrtSession } from \"../core/session\";\n\nexport abstract class VisionTask {\n protected constructor(protected readonly _session: OrtSession) {}\n\n /** The underlying {@link OrtSession} used to run inference. */\n get session(): OrtSession {\n return this._session;\n }\n}\n","/**\n * Image classification task using ONNX Runtime Web.\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { softmax, topK } from \"../postprocess/classification\";\nimport { normalize, resize, toCHW, toFloat32Tensor } from \"../preprocess/image\";\nimport { ClassificationResults, Probs } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type ClassProbability, type ClassificationResult, type RGBImage } from \"../types\";\n\nconst IMAGENET_MEAN: readonly [number, number, number] = [0.485, 0.456, 0.406];\nconst IMAGENET_STD: readonly [number, number, number] = [0.229, 0.224, 0.225];\n\nexport interface ClassifierOptions extends OrtSessionOptions {\n /** Class label spec — see {@link resolveLabels}. */\n readonly labels: LabelSpec;\n /**\n * Number of classes the model can predict. Required when `labels` is `null`\n * or when you want to validate that the supplied labels match the model.\n */\n readonly numClasses?: number;\n /** Model input `[width, height]` in pixels. Defaults to `[224, 224]`. */\n readonly inputSize?: readonly [number, number];\n /** Per-channel RGB mean used for normalization. Defaults to ImageNet. */\n readonly mean?: readonly [number, number, number];\n /** Per-channel RGB standard deviation. Defaults to ImageNet. */\n readonly std?: readonly [number, number, number];\n /**\n * If `true` (default), apply softmax to the raw model output. Set to\n * `false` for models whose final layer already produces a probability\n * distribution.\n */\n readonly applySoftmax?: boolean;\n}\n\nexport interface ClassifierPredictOptions {\n /**\n * If set, the per-class probability list in `results[0].result.probabilities`\n * is truncated to the top-K entries. The bulk `probs` view always exposes\n * the full vector.\n */\n readonly topK?: number;\n}\n\n/**\n * Image classifier wrapping an ONNX model with ImageNet-style preprocessing.\n *\n * `predict()` returns `Promise<ClassificationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes a `probs`\n * collection (`top1`, `top1conf`, `top5`, `top5conf`, `data`) plus the\n * legacy per-class probability list with names already resolved.\n *\n * Defaults: 224×224 RGB input, `float32` normalized with ImageNet mean/std,\n * NCHW layout, batch size 1, softmax applied to the raw output.\n *\n * @example\n * ```typescript\n * const clf = await Classifier.create(\"/models/resnet50.onnx\", {\n * labels: [\"tench\", \"goldfish\", ...] // 1000 ImageNet labels\n * });\n * const r = (await clf.predict(\"/images/dog.jpg\"))[0];\n * console.log(r.cls, r.conf, r.name);\n * console.log(r.probs.top5, r.probs.top5conf);\n * ```\n */\nexport class Classifier extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _mean: readonly [number, number, number],\n private readonly _std: readonly [number, number, number],\n private readonly _applySoftmax: boolean,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: ClassifierOptions): Promise<Classifier> {\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels, { numClasses: options.numClasses });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Classifier(\n session,\n labels,\n names,\n options.inputSize ?? [224, 224],\n options.mean ?? IMAGENET_MEAN,\n options.std ?? IMAGENET_STD,\n options.applySoftmax ?? true,\n );\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model can predict. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: ClassifierPredictOptions = {},\n ): Promise<ClassificationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run classification on a single image. */\n async predict(\n image: ImageInput,\n options: ClassifierPredictOptions = {},\n ): Promise<ClassificationResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const tensor = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n const firstOutputName = this._session.outputNames[0];\n if (firstOutputName === undefined) {\n throw new Error(\"Classifier model has no outputs.\");\n }\n const raw = outputs[firstOutputName];\n if (raw === undefined) {\n throw new Error(\n `Classifier model output ${firstOutputName} missing from run() result.`,\n );\n }\n const fullProbs = this._postprocess(raw.data as Float32Array);\n\n const { indices, values } = topK(fullProbs, options.topK ?? null);\n const probabilities: ClassProbability[] = [];\n for (let i = 0; i < indices.length; i++) {\n const id = indices[i] as number;\n const className = this._labels[id] ?? `class_${id}`;\n probabilities.push({\n classId: id,\n className,\n probability: values[i] as number,\n cls: id,\n name: className,\n conf: values[i] as number,\n });\n }\n if (probabilities.length === 0) {\n throw new Error(\"Classifier produced no probabilities (empty output).\");\n }\n\n const top = probabilities[0] as ClassProbability;\n const result: ClassificationResult = {\n classId: top.classId,\n className: top.className,\n confidence: top.probability,\n cls: top.classId,\n name: top.className,\n conf: top.probability,\n image: original,\n probabilities,\n };\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new ClassificationResults(\n new Probs(fullProbs),\n result,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): ort.Tensor {\n const [tw, th] = this._inputSize;\n const resized = resize(image, tw, th);\n const normalized = normalize(resized, this._mean, this._std);\n const chw = toCHW(normalized, resized.width, resized.height, 3);\n return toFloat32Tensor(chw, [1, 3, resized.height, resized.width]);\n }\n\n private _postprocess(raw: Float32Array): Float32Array {\n return this._applySoftmax ? softmax(raw) : new Float32Array(raw);\n }\n}\n","/**\n * Object detection task using anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYolo } from \"../postprocess/detection\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, DetectionResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type DetectionResult, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the model's detection head.\n *\n * - `\"yolo\"`: anchor-free YOLO head with output shape `[1, 4 + nc, N]` —\n * covers YOLOv8, v9, v10, v11, v12, v26 detect exports.\n *\n * The SDK does **not** auto-detect the head from the model — the caller is\n * responsible for picking a head that matches their export. Future families\n * (v5/v6/v7 with `[1, N, 5+nc]`) will be added as new literal members.\n */\nexport type DetectorHead = \"yolo\";\n\nexport interface DetectorOptions extends OrtSessionOptions {\n /**\n * Decoder family for the detection head. Default `\"yolo\"` covers\n * YOLOv8/v9/v10/v11/v12/v26.\n */\n readonly head?: DetectorHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of detections per image. */\n readonly maxDetections?: number;\n}\n\nexport interface DetectorPredictOptions {\n /** Override the default confidence threshold. */\n readonly confThreshold?: number;\n /** Override the default IoU threshold. */\n readonly iouThreshold?: number;\n /**\n * If set, keep only detections whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Object detector for anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n *\n * `predict()` returns `Promise<DetectionResults[]>` (length 1 for a single\n * image), mirroring Ultralytics' `YOLO(\"img.jpg\")`. Iterate the envelope for\n * per-instance dataclasses, or use the bulk `boxes` view (`.xyxy`, `.xywh`,\n * `.xyxyn`, `.xywhn`, `.cls`, `.conf`).\n *\n * @example\n * ```typescript\n * const det = await Detector.create(\"/models/yolov8n.onnx\");\n * const results = await det.predict(\"/images/street.jpg\");\n * const r = results[0];\n * console.log(r.boxes.xyxy, r.boxes.cls, r.boxes.conf, r.names);\n * for (const d of r) {\n * console.log(d.cls, d.conf, d.box.xyxy);\n * }\n * ```\n */\nexport class Detector extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: DetectorHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: DetectorOptions = {}): Promise<Detector> {\n const head: DetectorHead = options.head ?? \"yolo\";\n if (head !== \"yolo\") {\n throw new Error(`Unsupported detector head '${head}'. Supported: 'yolo'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Detector(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): DetectorHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /**\n * Alias for {@link predict} — call the detector like a torch `nn.Module`.\n *\n * Use as `det.call(img)` since JavaScript class instances are not callable;\n * for direct invocation, prefer `det.predict(img)`. The full\n * {@link DetectorPredictOptions} (including `classes`) is supported.\n */\n async call(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n return this.predict(image, options);\n }\n\n /** Run detection on a single image. */\n async predict(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n\n const firstOutputName = this._session.outputNames[0];\n if (firstOutputName === undefined) {\n throw new Error(\"Detector model has no outputs.\");\n }\n const raw = outputs[firstOutputName];\n if (raw === undefined) {\n throw new Error(`Detector model output ${firstOutputName} missing from run() result.`);\n }\n\n const decodedAll = decodeYolo(raw.data as Float32Array, raw.dims, {\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n });\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new DetectionResults(\n this._buildBoxes(detections, orig),\n detections,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n ): DetectionResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let cropped: RGBImage;\n if (cx2 > cx1 && cy2 > cy1) {\n const cw = cx2 - cx1;\n const ch = cy2 - cy1;\n const out = new Uint8Array(cw * ch * 3);\n for (let row = 0; row < ch; row++) {\n const srcOffset = ((cy1 + row) * original.width + cx1) * 3;\n out.set(original.data.subarray(srcOffset, srcOffset + cw * 3), row * cw * 3);\n }\n cropped = new RGBImage(out, cw, ch);\n } else {\n cropped = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n croppedImage: cropped,\n };\n }\n\n private _buildBoxes(\n detections: readonly DetectionResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as DetectionResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n}\n","/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new SegmentationResults(\n this._buildBoxes(detections, orig),\n this._buildMasks(detections, orig),\n detections,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n","/**\n * `tempest-react-sdk/vision` — browser computer-vision inference with ONNX\n * Runtime Web (classification, detection, segmentation).\n *\n * Vendored from `@mauriciobenjamin700/ort-vision-sdk-web@0.2.1` (MIT, same\n * author) so it ships inside this SDK without an extra package install.\n * `onnxruntime-web` stays an optional peer dependency — install it (and ship\n * the matching `.wasm` files) only when you use this subpath.\n *\n * Do not hand-edit — regenerate with `npm run vendor:vision`.\n */\n\nexport {\n BoundingBox,\n Mask,\n RGBImage,\n type ClassProbability,\n type ClassificationResult,\n type DetectionResult,\n type SegmentationResult,\n} from \"./types\";\n\nexport {\n Boxes,\n ClassificationResults,\n DetectionResults,\n Masks,\n Probs,\n SegmentationResults,\n} from \"./results\";\n\nexport { COCO_CLASSES, type LabelSpec, type ResolveLabelsOptions, resolveLabels } from \"./labels\";\n\nexport {\n ImageLoadError,\n InferenceError,\n LabelMapError,\n ModelLoadError,\n OrtVisionError,\n ProviderNotAvailableError,\n} from \"./core/exceptions\";\n\nexport { type ModelSource, type OrtSessionOptions, OrtSession } from \"./core/session\";\nexport { DEFAULT_PROVIDERS, resolveProviders } from \"./core/providers\";\n\nexport { type ImageInput, loadImage } from \"./io/image\";\n\nexport {\n type LetterboxResult,\n fromCv2,\n letterbox,\n normalize,\n resize,\n toCHW,\n toCv2,\n toFloat32,\n toFloat32Tensor,\n toTensor,\n} from \"./preprocess/image\";\n\nexport { type TopKResult, softmax, topK } from \"./postprocess/classification\";\n\nexport {\n type DecodeYoloAnchorsOptions,\n type DecodeYoloOptions,\n type DecodeYoloV8AnchorsOptions,\n type DecodeYoloV8Options,\n type DecodedAnchors,\n type DecodedDetection,\n batchedNms,\n decodeYolo,\n decodeYoloAnchors,\n decodeYoloV8,\n decodeYoloV8Anchors,\n nms,\n} from \"./postprocess/detection\";\n\nexport {\n type DecodeYoloSegOptions,\n type DecodeYoloV8SegOptions,\n type DecodedSegmentation,\n decodeYoloSeg,\n decodeYoloV8Seg,\n} from \"./postprocess/segmentation\";\n\nexport { VisionTask } from \"./tasks/base\";\nexport {\n type ClassifierOptions,\n type ClassifierPredictOptions,\n Classifier,\n} from \"./tasks/classifier\";\nexport {\n type DetectorHead,\n type DetectorOptions,\n type DetectorPredictOptions,\n Detector,\n} from \"./tasks/detector\";\nexport {\n type SegmenterHead,\n type SegmenterOptions,\n type SegmenterPredictOptions,\n Segmenter,\n} from \"./tasks/segmenter\";\n\nexport const VERSION: string = \"0.2.1\";\n"],"names":["OrtVisionError","message","options","ModelLoadError","InferenceError","ProviderNotAvailableError","ImageLoadError","LabelMapError","RGBImage","data","width","height","BoundingBox","x1","y1","x2","y2","origShape","h","w","cx","cy","bw","bh","Mask","Boxes","xyxy","cls","conf","out","i","xywh","Probs","best","bestVal","v","k","n","order","b","indices","values","Masks","DetectionResults","boxes","detections","names","origImg","path","speed","index","ClassificationResults","probs","result","SegmentationResults","masks","COCO_CLASSES","PRESETS","resolveLabels","spec","labels","resolve","numClasses","_","preset","map","ids","maxId","DEFAULT_PROVIDERS","resolveProviders","requested","OrtSession","_session","providers","model","sessionOptions","session","ortRuntime","err","name","feeds","createCanvas","c","get2DContext","canvas","ctx","imageDataToRGB","imageData","rgb","j","rgbToImageData","image","loadImage","source","loadFromUrl","loadFromBlob","waitForImageElement","drawableToRGB","url","response","blob","bitmap","img","reject","onLoad","cleanup","onError","drawable","resize","targetWidth","targetHeight","srcCanvas","dstCanvas","dstCtx","normalize","mean","std","scale","m0","m1","m2","s0","s1","s2","toFloat32","toCHW","hwc","channels","expected","chw","plane","y","x","hwcBase","planeIdx","toFloat32Tensor","dims","toTensor","f32","fromCv2","bgr","toCv2","letterbox","fill","newW","newH","resized","f0","f1","f2","padLeft","padTop","rowBytes","srcOffset","dstOffset","softmax","logits","max","sum","e","topK","probabilities","kEff","idx","a","nms","scores","iouThreshold","areas","suppressed","keep","oi","ax1","ay1","ax2","ay2","ai","oj","bx1","by1","bx2","by2","ix1","iy1","ix2","iy2","iw","ih","inter","union","batchedNms","idxs","byClass","list","m","subBoxes","subScores","subKeep","decodeYoloAnchors","normalized","numAnchors","originalWidth","originalHeight","confThreshold","maxDetections","candidates","bestCls","bestScore","s","emptyDecoded","flatBoxes","scoresArr","idxsArr","kept","limited","anchorIndices","boxesXyxy","classIds","confidences","decodeYolo","output","outputDims","decoded","results","_warnedDecodeYoloV8","_warnedDecodeYoloV8Anchors","decodeYoloV8","decodeYoloV8Anchors","decodeYoloSeg","perAnchorData","perAnchorDims","prototypeData","prototypeDims","pDims","numMaskCoefs","maskH","maskW","expectedChannels","maskThreshold","scaleX","scaleY","protoPlane","coefBase","bbox","classId","confidence","bboxW","bboxH","ibx1","iby1","ibx2","iby2","mbx1","mby1","mbx2","mby2","cropW","cropH","softCrop","py","px","kk","coef","proto","sigmoid","resizeBilinear","binary","_warnedDecodeYoloV8Seg","decodeYoloV8Seg","src","srcWidth","srcHeight","sx","sy","yy","y0","wy","xx","x0","wx","v00","v01","v10","v11","top","bot","VisionTask","IMAGENET_MEAN","IMAGENET_STD","Classifier","_labels","_names","_inputSize","_mean","_std","_applySoftmax","original","tensor","outputs","firstOutputName","raw","fullProbs","id","className","orig","tw","th","Detector","_head","_confThreshold","_iouThreshold","_maxDetections","head","decodedAll","allowed","d","lb","cx1","cy1","cx2","cy2","cropped","cw","ch","row","Segmenter","_maskThreshold","perAnchor","prototypes","t","shapes","mask","segmentedImage","finalMask","mw","mh","segData","srcRowOffset","dstRowOffset","maskRowOffset","col","trimmed","VERSION"],"mappings":"iZAOO,MAAMA,UAAuB,KAAM,CACtC,YAAYC,EAAiBC,EAAwB,CACjD,MAAMD,EAASC,CAAO,EACtB,KAAK,KAAO,WAAW,IAC3B,CACJ,CAGO,MAAMC,WAAuBH,CAAe,CAAC,CAG7C,MAAMI,WAAuBJ,CAAe,CAAC,CAG7C,MAAMK,WAAkCL,CAAe,CAAC,CAGxD,MAAMM,UAAuBN,CAAe,CAAC,CAG7C,MAAMO,UAAsBP,CAAe,CAAC,CCN5C,MAAMQ,CAAS,CAClB,YACoBC,EACAC,EACAC,EAClB,CACE,GAJgB,KAAA,KAAAF,EACA,KAAA,MAAAC,EACA,KAAA,OAAAC,EAEZF,EAAK,SAAWC,EAAQC,EAAS,EACjC,M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,EAAK,EAAI,EAAI,CAAC,EAAIiS,EAAE,KAAK,GACzBjS,EAAK,EAAI,EAAI,CAAC,EAAIiS,EAAE,KAAK,GACzBhS,EAAI,CAAC,EAAIgS,EAAE,QACX/R,EAAK,CAAC,EAAI+R,EAAE,UAChB,CACA,OAAO,IAAIlS,GAAMC,EAAMC,EAAKC,EAAMX,CAAS,CAC/C,CAEQ,YACJ4B,EACA5B,EACK,CACL,MAAMS,EAAO,IAAI,aAAamB,EAAW,OAAS,CAAC,EACnD,QAASf,EAAI,EAAGA,EAAIe,EAAW,OAAQf,IAAK,CACxC,MAAM6R,EAAI9Q,EAAWf,CAAC,EACtBJ,EAAKI,EAAI,CAAC,EAAI6R,EAAE,KAAK,GACrBjS,EAAKI,EAAI,EAAI,CAAC,EAAI6R,EAAE,KAAK,GACzBjS,EAAKI,EAAI,EAAI,CAAC,EAAI6R,EAAE,KAAK,GACzBjS,EAAKI,EAAI,EAAI,CAAC,EAAI6R,EAAE,KAAK,EAC7B,CACA,OAAO,IAAIjR,GACPG,EAAW,IAAK8Q,GAAMA,EAAE,IAAI,EAC5BjS,EACAT,CAAA,CAER,CACJ,CCnQO,MAAMqU,GAAkB"}
|
|
1
|
+
{"version":3,"file":"vision.cjs","sources":["../src/vision/core/exceptions.ts","../src/vision/types.ts","../src/vision/results.ts","../src/vision/labels.ts","../src/vision/core/providers.ts","../src/vision/core/session.ts","../src/vision/core/canvas.ts","../src/vision/io/image.ts","../src/vision/preprocess/image.ts","../src/vision/postprocess/classification.ts","../src/vision/postprocess/detection.ts","../src/vision/postprocess/segmentation.ts","../src/vision/tasks/base.ts","../src/vision/tasks/classifier.ts","../src/vision/tasks/detector.ts","../src/vision/tasks/segmenter.ts","../src/vision/index.ts","../src/vision/use-camera-stream.ts","../src/vision/luminance.ts","../src/vision/use-live-luminance.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","/**\n * Public output types returned by the SDK's vision tasks.\n *\n * These types form the contract between the SDK and its callers. They mirror\n * the Python `ort-vision-sdk` output dataclasses 1-to-1.\n *\n * Naming is intentionally compatible with the Ultralytics / torchvision idiom\n * (`cls`, `conf`, `box`, `xyxy`, `xywh`, normalized variants) so code ported\n * from those projects keeps working with minimal edits. The original verbose\n * names (`classId`, `className`, `confidence`, `bbox`) are still populated for\n * backwards compatibility.\n */\n\nimport { ImageLoadError } from \"./core/exceptions\";\n\n/**\n * HWC RGB uint8 image — the canonical image format used across the SDK.\n *\n * `data.length` must equal `width * height * 3`. The buffer is laid out row\n * by row, top-to-bottom, with each pixel as `[R, G, B]`.\n */\nexport class RGBImage {\n constructor(\n public readonly data: Uint8Array,\n public readonly width: number,\n public readonly height: number,\n ) {\n if (data.length !== width * height * 3) {\n throw new ImageLoadError(\n `RGBImage data length ${data.length} does not match width * height * 3 = ${\n width * height * 3\n }.`,\n );\n }\n }\n}\n\n/**\n * Axis-aligned bounding box in absolute pixel coordinates (xyxy format).\n *\n * Coordinates refer to the original input image (before any internal resize),\n * so callers can map detections back onto their source image without any\n * additional bookkeeping.\n */\nexport class BoundingBox {\n constructor(\n public readonly x1: number,\n public readonly y1: number,\n public readonly x2: number,\n public readonly y2: number,\n ) {}\n\n /** Box width in pixels (clamped to non-negative). */\n get width(): number {\n return Math.max(0, this.x2 - this.x1);\n }\n\n /** Box height in pixels (clamped to non-negative). */\n get height(): number {\n return Math.max(0, this.y2 - this.y1);\n }\n\n /** Box area in pixels squared. */\n get area(): number {\n return this.width * this.height;\n }\n\n /** The box as `[x1, y1, x2, y2]` in absolute pixels (Ultralytics-style). */\n get xyxy(): readonly [number, number, number, number] {\n return [this.x1, this.y1, this.x2, this.y2];\n }\n\n /**\n * The box as `[cx, cy, w, h]` with `(cx, cy)` at the center.\n *\n * Matches Ultralytics' `boxes.xywh` and YOLO's native head format. For the\n * top-left `[x, y, w, h]` convention, use {@link asXywh}.\n */\n get xywh(): readonly [number, number, number, number] {\n return [(this.x1 + this.x2) / 2, (this.y1 + this.y2) / 2, this.width, this.height];\n }\n\n /**\n * The box as `[x1, y1, x2, y2]` normalized to `[0, 1]`.\n *\n * @param origShape `[height, width]` of the source image, in pixels.\n */\n xyxyn(origShape: readonly [number, number]): readonly [number, number, number, number] {\n const [h, w] = origShape;\n if (w <= 0 || h <= 0) return [0, 0, 0, 0];\n return [this.x1 / w, this.y1 / h, this.x2 / w, this.y2 / h];\n }\n\n /**\n * The box as `[cx, cy, w, h]` normalized to `[0, 1]`.\n *\n * @param origShape `[height, width]` of the source image, in pixels.\n */\n xywhn(origShape: readonly [number, number]): readonly [number, number, number, number] {\n const [h, w] = origShape;\n if (w <= 0 || h <= 0) return [0, 0, 0, 0];\n const [cx, cy, bw, bh] = this.xywh;\n return [cx / w, cy / h, bw / w, bh / h];\n }\n\n /** Returns `[x1, y1, x2, y2]`. */\n asXyxy(): readonly [number, number, number, number] {\n return [this.x1, this.y1, this.x2, this.y2];\n }\n\n /**\n * Returns `[x, y, width, height]` with `(x, y)` at the **top-left**.\n *\n * Note: this is the top-left convention. Ultralytics' `xywh` getter uses\n * **center** coordinates — for that, read {@link xywh}.\n */\n asXywh(): readonly [number, number, number, number] {\n return [this.x1, this.y1, this.width, this.height];\n }\n\n /** Returns `[x1, y1, x2, y2]` truncated to integers, useful for slicing arrays. */\n asIntXyxy(): readonly [number, number, number, number] {\n return [Math.trunc(this.x1), Math.trunc(this.y1), Math.trunc(this.x2), Math.trunc(this.y2)];\n }\n}\n\n/**\n * Probability assigned to a single class for a classification prediction.\n *\n * `cls` / `name` / `conf` are Ultralytics-style aliases populated alongside\n * the verbose `classId` / `className` / `probability` fields.\n */\nexport interface ClassProbability {\n readonly classId: number;\n readonly className: string;\n readonly probability: number;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `probability` (Ultralytics-style). */\n readonly conf: number;\n}\n\n/**\n * Output of an image classification inference.\n */\nexport interface ClassificationResult {\n readonly classId: number;\n readonly className: string;\n readonly confidence: number;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `confidence` (Ultralytics-style). */\n readonly conf: number;\n /** The original input image as an HWC RGB uint8 array. */\n readonly image: RGBImage;\n /**\n * Probabilities per class, sorted in descending order. The first entry\n * mirrors `classId`, `className`, and `confidence`. When `topK` was passed\n * to `predict`, the array is truncated to that length.\n */\n readonly probabilities: readonly ClassProbability[];\n}\n\n/**\n * Single detected object produced by an object-detection model.\n */\nexport interface DetectionResult {\n readonly classId: number;\n readonly className: string;\n readonly confidence: number;\n readonly bbox: BoundingBox;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `confidence` (Ultralytics-style). */\n readonly conf: number;\n /** Alias for `bbox` (Ultralytics-style). */\n readonly box: BoundingBox;\n /**\n * The original image cropped to `bbox`, HWC RGB uint8. Empty boxes\n * (zero area) yield a zero-sized `RGBImage`.\n */\n readonly croppedImage: RGBImage;\n}\n\n/**\n * Single-channel binary or grayscale mask, laid out row-major.\n *\n * `data.length` must equal `width * height`. For binary masks, values are\n * `0` (background) or `255` (foreground); soft masks may use the full\n * `[0, 255]` range.\n */\nexport class Mask {\n constructor(\n public readonly data: Uint8Array,\n public readonly width: number,\n public readonly height: number,\n ) {\n if (data.length !== width * height) {\n throw new ImageLoadError(\n `Mask data length ${data.length} does not match width * height = ${\n width * height\n }.`,\n );\n }\n }\n}\n\n/**\n * Single segmented instance produced by an instance-segmentation model.\n *\n * Mirrors {@link DetectionResult} and adds the per-instance binary mask\n * plus a \"ready-to-display\" background-removed crop.\n */\nexport interface SegmentationResult {\n readonly classId: number;\n readonly className: string;\n readonly confidence: number;\n readonly bbox: BoundingBox;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `confidence` (Ultralytics-style). */\n readonly conf: number;\n /** Alias for `bbox` (Ultralytics-style). */\n readonly box: BoundingBox;\n /**\n * Binary mask cropped to `bbox`. Values are `0` (background) or `255`\n * (foreground). Empty boxes yield a zero-sized `Mask`.\n */\n readonly mask: Mask;\n /**\n * The original image cropped to `bbox` with background pixels (where\n * `mask.data[i] === 0`) zeroed out. Empty boxes yield a zero-sized\n * `RGBImage`.\n */\n readonly segmentedImage: RGBImage;\n}\n","/**\n * Per-image result envelopes — Ultralytics-style `Results` for the SDK.\n *\n * Each `predict()` call returns a 1-element array of these envelopes,\n * mirroring `YOLO(\"img.jpg\")`. Each envelope holds:\n *\n * - A bulk-array view of the predictions (`Boxes`, `Probs`, `Masks`) with\n * the exact attribute names Ultralytics uses (`xyxy`, `xywh`, `xyxyn`,\n * `xywhn`, `cls`, `conf`, `data`, `top1`, `top5`).\n * - Per-instance dataclasses (`DetectionResult`, `SegmentationResult`,\n * `ClassProbability`) for callers who prefer the OO interface.\n * - `names`: `Record<number, string>` matching Ultralytics' `model.names`.\n * - `origImg` / `origShape` / `path`: provenance for the original input.\n */\n\nimport {\n type ClassificationResult,\n type DetectionResult,\n type RGBImage,\n type SegmentationResult,\n} from \"./types\";\n\n/**\n * Bulk numpy-style view of detected boxes for a single image.\n *\n * Mirrors Ultralytics' `Boxes` interface. Coordinates in {@link xyxy} and\n * {@link xywh} are absolute pixels in the original image; the `*n` variants\n * are normalized to `[0, 1]` using `origShape`.\n */\nexport class Boxes {\n /**\n * @param xyxy Flat array of length `4 * N` in `[x1, y1, x2, y2, ...]` order.\n * @param cls One class index per box, length `N`.\n * @param conf One confidence per box, length `N`.\n * @param origShape `[height, width]` of the original image.\n */\n constructor(\n public readonly xyxy: Float32Array,\n public readonly cls: Int32Array,\n public readonly conf: Float32Array,\n public readonly origShape: readonly [number, number],\n ) {}\n\n /** Number of detected boxes. */\n get length(): number {\n return this.cls.length;\n }\n\n /** `[N, 4]` shape of the `xyxy` view. */\n get shape(): readonly [number, number] {\n return [this.length, 4];\n }\n\n /** Boxes as `[N, 4]` `[cx, cy, w, h]` flat array in absolute pixels. */\n get xywh(): Float32Array {\n const out = new Float32Array(this.xyxy.length);\n for (let i = 0; i < this.length; i++) {\n const x1 = this.xyxy[i * 4] as number;\n const y1 = this.xyxy[i * 4 + 1] as number;\n const x2 = this.xyxy[i * 4 + 2] as number;\n const y2 = this.xyxy[i * 4 + 3] as number;\n out[i * 4] = (x1 + x2) / 2;\n out[i * 4 + 1] = (y1 + y2) / 2;\n out[i * 4 + 2] = x2 - x1;\n out[i * 4 + 3] = y2 - y1;\n }\n return out;\n }\n\n /** Boxes as `[N, 4]` `[x1, y1, x2, y2]` normalized to `[0, 1]`. */\n get xyxyn(): Float32Array {\n const [h, w] = this.origShape;\n const out = new Float32Array(this.xyxy.length);\n if (this.length === 0 || w <= 0 || h <= 0) return out;\n for (let i = 0; i < this.length; i++) {\n out[i * 4] = (this.xyxy[i * 4] as number) / w;\n out[i * 4 + 1] = (this.xyxy[i * 4 + 1] as number) / h;\n out[i * 4 + 2] = (this.xyxy[i * 4 + 2] as number) / w;\n out[i * 4 + 3] = (this.xyxy[i * 4 + 3] as number) / h;\n }\n return out;\n }\n\n /** Boxes as `[N, 4]` `[cx, cy, w, h]` normalized to `[0, 1]`. */\n get xywhn(): Float32Array {\n const xywh = this.xywh;\n const [h, w] = this.origShape;\n if (this.length === 0 || w <= 0 || h <= 0) return xywh;\n for (let i = 0; i < this.length; i++) {\n xywh[i * 4] = (xywh[i * 4] as number) / w;\n xywh[i * 4 + 1] = (xywh[i * 4 + 1] as number) / h;\n xywh[i * 4 + 2] = (xywh[i * 4 + 2] as number) / w;\n xywh[i * 4 + 3] = (xywh[i * 4 + 3] as number) / h;\n }\n return xywh;\n }\n\n /**\n * Concatenated `[N, 6]` array of `[x1, y1, x2, y2, conf, cls]`.\n *\n * Matches Ultralytics' `boxes.data`.\n */\n get data(): Float32Array {\n const out = new Float32Array(this.length * 6);\n for (let i = 0; i < this.length; i++) {\n out[i * 6] = this.xyxy[i * 4] as number;\n out[i * 6 + 1] = this.xyxy[i * 4 + 1] as number;\n out[i * 6 + 2] = this.xyxy[i * 4 + 2] as number;\n out[i * 6 + 3] = this.xyxy[i * 4 + 3] as number;\n out[i * 6 + 4] = this.conf[i] as number;\n out[i * 6 + 5] = this.cls[i] as number;\n }\n return out;\n }\n}\n\n/**\n * Top-k classification probabilities for a single image.\n *\n * Mirrors Ultralytics' `Probs` interface.\n */\nexport class Probs {\n /** @param data `[numClasses]` per-class probabilities, indexed by class id. */\n constructor(public readonly data: Float32Array) {}\n\n /** Number of classes. */\n get length(): number {\n return this.data.length;\n }\n\n /** `[numClasses]` shape of the underlying vector. */\n get shape(): readonly [number] {\n return [this.length];\n }\n\n /** Index of the most probable class. */\n get top1(): number {\n if (this.data.length === 0) return 0;\n let best = 0;\n let bestVal = this.data[0] as number;\n for (let i = 1; i < this.data.length; i++) {\n const v = this.data[i] as number;\n if (v > bestVal) {\n best = i;\n bestVal = v;\n }\n }\n return best;\n }\n\n /** Probability of the top-1 class. */\n get top1conf(): number {\n if (this.data.length === 0) return 0;\n return this.data[this.top1] as number;\n }\n\n /** Indices of the top-5 most probable classes, descending. */\n get top5(): Int32Array {\n return this._topK(5).indices;\n }\n\n /** Probabilities of the top-5 classes, descending. */\n get top5conf(): Float32Array {\n return this._topK(5).values;\n }\n\n private _topK(k: number): { indices: Int32Array; values: Float32Array } {\n const n = Math.min(k, this.data.length);\n const order: number[] = [];\n for (let i = 0; i < this.data.length; i++) order.push(i);\n order.sort((a, b) => (this.data[b] as number) - (this.data[a] as number));\n const indices = new Int32Array(n);\n const values = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n indices[i] = order[i] as number;\n values[i] = this.data[order[i] as number] as number;\n }\n return { indices, values };\n }\n}\n\n/**\n * Per-instance binary masks for a single image.\n *\n * Each mask is cropped to its instance's bounding box. To paint masks onto\n * a full-image canvas, use `xyxy[i]` as the top-left target.\n */\nexport class Masks {\n /**\n * @param data Per-instance binary masks (`Mask` objects from `types.ts`).\n * @param xyxy Flat `[N, 4]` of bounding-box coordinates in original pixels.\n * @param origShape `[height, width]` of the original image.\n */\n constructor(\n public readonly data: ReadonlyArray<{\n readonly data: Uint8Array;\n readonly width: number;\n readonly height: number;\n }>,\n public readonly xyxy: Float32Array,\n public readonly origShape: readonly [number, number],\n ) {}\n\n /** Number of instance masks. */\n get length(): number {\n return this.data.length;\n }\n\n /** `[N]` shape of the masks collection. */\n get shape(): readonly [number] {\n return [this.length];\n }\n\n [Symbol.iterator](): Iterator<{\n readonly data: Uint8Array;\n readonly width: number;\n readonly height: number;\n }> {\n return this.data[Symbol.iterator]();\n }\n}\n\n/**\n * Per-image detection envelope (Ultralytics-style `Results`).\n *\n * Iterating yields per-instance {@link DetectionResult} entries, so legacy\n * code that did `for (const d of detector.predict(img))` only needs an\n * extra `[0]` to bridge:\n *\n * ```typescript\n * for (const d of (await detector.predict(img))[0]) {\n * console.log(d.cls, d.conf, d.box.xyxy);\n * }\n * ```\n *\n * For numpy-style bulk access, use the `boxes` collection.\n */\nexport class DetectionResults implements Iterable<DetectionResult> {\n constructor(\n public readonly boxes: Boxes,\n public readonly detections: readonly DetectionResult[],\n public readonly names: Readonly<Record<number, string>>,\n public readonly origImg: RGBImage,\n public readonly origShape: readonly [number, number],\n public readonly path: string | null = null,\n public readonly speed: Readonly<Record<string, number>> = {},\n ) {}\n\n /** Number of surviving detections. */\n get length(): number {\n return this.detections.length;\n }\n\n /** Index into the per-instance detections. */\n get(index: number): DetectionResult | undefined {\n return this.detections[index];\n }\n\n [Symbol.iterator](): Iterator<DetectionResult> {\n return this.detections[Symbol.iterator]();\n }\n}\n\n/**\n * Per-image classification envelope (Ultralytics-style `Results`).\n */\nexport class ClassificationResults {\n constructor(\n public readonly probs: Probs,\n public readonly result: ClassificationResult,\n public readonly names: Readonly<Record<number, string>>,\n public readonly origImg: RGBImage,\n public readonly origShape: readonly [number, number],\n public readonly path: string | null = null,\n public readonly speed: Readonly<Record<string, number>> = {},\n ) {}\n\n /** Top-1 class index (Ultralytics-style alias). */\n get cls(): number {\n return this.probs.top1;\n }\n\n /** Top-1 confidence (Ultralytics-style alias). */\n get conf(): number {\n return this.probs.top1conf;\n }\n\n /** Top-1 class name. */\n get name(): string {\n return this.names[this.cls] ?? `class_${this.cls}`;\n }\n\n /** Per-class probability list, sorted descending (legacy field). */\n get probabilities(): readonly ClassificationResult[\"probabilities\"][number][] {\n return this.result.probabilities;\n }\n}\n\n/**\n * Per-image instance-segmentation envelope (Ultralytics-style `Results`).\n *\n * Iterating yields per-instance {@link SegmentationResult} entries. `boxes`\n * and `masks` mirror Ultralytics' bulk-array views.\n */\nexport class SegmentationResults implements Iterable<SegmentationResult> {\n constructor(\n public readonly boxes: Boxes,\n public readonly masks: Masks,\n public readonly detections: readonly SegmentationResult[],\n public readonly names: Readonly<Record<number, string>>,\n public readonly origImg: RGBImage,\n public readonly origShape: readonly [number, number],\n public readonly path: string | null = null,\n public readonly speed: Readonly<Record<string, number>> = {},\n ) {}\n\n /** Number of surviving instances. */\n get length(): number {\n return this.detections.length;\n }\n\n /** Index into the per-instance results. */\n get(index: number): SegmentationResult | undefined {\n return this.detections[index];\n }\n\n [Symbol.iterator](): Iterator<SegmentationResult> {\n return this.detections[Symbol.iterator]();\n }\n}\n","/**\n * Class label resolution: presets, lists, dicts, or auto-generated.\n *\n * Tasks call {@link resolveLabels} once at construction time to turn whatever\n * the caller passed (preset name, array, dict, or `null`) into an ordered\n * array of class names indexed by class id.\n *\n * In the browser there is no filesystem, so this module does not load labels\n * from a path — fetch the file yourself and pass an array.\n */\n\nimport { LabelMapError } from \"./core/exceptions\";\n\n/**\n * Anything accepted by {@link resolveLabels}.\n *\n * - `string[]` / `readonly string[]`: explicit names indexed by class id.\n * - `Record<number, string>`: sparse mapping (gaps filled with `class_<id>`).\n * - `string`: a preset name (e.g. `\"coco\"`).\n * - `null` / `undefined`: auto-generate `class_0` ... `class_{numClasses-1}`.\n */\nexport type LabelSpec = readonly string[] | Record<number, string> | string | null | undefined;\n\n/** COCO 2017 80-class labels in canonical class-id order. */\nexport const COCO_CLASSES: readonly string[] = Object.freeze([\n \"person\",\n \"bicycle\",\n \"car\",\n \"motorcycle\",\n \"airplane\",\n \"bus\",\n \"train\",\n \"truck\",\n \"boat\",\n \"traffic light\",\n \"fire hydrant\",\n \"stop sign\",\n \"parking meter\",\n \"bench\",\n \"bird\",\n \"cat\",\n \"dog\",\n \"horse\",\n \"sheep\",\n \"cow\",\n \"elephant\",\n \"bear\",\n \"zebra\",\n \"giraffe\",\n \"backpack\",\n \"umbrella\",\n \"handbag\",\n \"tie\",\n \"suitcase\",\n \"frisbee\",\n \"skis\",\n \"snowboard\",\n \"sports ball\",\n \"kite\",\n \"baseball bat\",\n \"baseball glove\",\n \"skateboard\",\n \"surfboard\",\n \"tennis racket\",\n \"bottle\",\n \"wine glass\",\n \"cup\",\n \"fork\",\n \"knife\",\n \"spoon\",\n \"bowl\",\n \"banana\",\n \"apple\",\n \"sandwich\",\n \"orange\",\n \"broccoli\",\n \"carrot\",\n \"hot dog\",\n \"pizza\",\n \"donut\",\n \"cake\",\n \"chair\",\n \"couch\",\n \"potted plant\",\n \"bed\",\n \"dining table\",\n \"toilet\",\n \"tv\",\n \"laptop\",\n \"mouse\",\n \"remote\",\n \"keyboard\",\n \"cell phone\",\n \"microwave\",\n \"oven\",\n \"toaster\",\n \"sink\",\n \"refrigerator\",\n \"book\",\n \"clock\",\n \"vase\",\n \"scissors\",\n \"teddy bear\",\n \"hair drier\",\n \"toothbrush\",\n]);\n\nconst PRESETS: Readonly<Record<string, readonly string[]>> = {\n coco: COCO_CLASSES,\n};\n\nexport interface ResolveLabelsOptions {\n /**\n * Expected number of classes.\n *\n * - When `spec` is `null`/`undefined`, this is required to auto-generate names.\n * - When `spec` is provided, it validates that the resolved length matches.\n */\n readonly numClasses?: number;\n}\n\n/**\n * Resolve a labels specification into an ordered array of class names.\n *\n * @throws {@link LabelMapError} if the spec is invalid, the preset is unknown,\n * or the resolved length disagrees with `numClasses`.\n */\nexport function resolveLabels(\n spec: LabelSpec,\n options: ResolveLabelsOptions = {},\n): readonly string[] {\n const labels = resolve(spec, options.numClasses);\n if (options.numClasses !== undefined && labels.length !== options.numClasses) {\n throw new LabelMapError(\n `Resolved ${labels.length} labels but the model has ${options.numClasses} classes.`,\n );\n }\n return labels;\n}\n\nfunction resolve(spec: LabelSpec, numClasses: number | undefined): readonly string[] {\n if (spec === null || spec === undefined) {\n if (numClasses === undefined) {\n throw new LabelMapError(\n \"Cannot auto-generate labels without numClasses. Pass an explicit labels spec or numClasses.\",\n );\n }\n return Array.from({ length: numClasses }, (_, i) => `class_${i}`);\n }\n\n if (Array.isArray(spec)) {\n return [...spec];\n }\n\n if (typeof spec === \"string\") {\n const preset = PRESETS[spec];\n if (preset !== undefined) {\n return preset;\n }\n throw new LabelMapError(\n `Unknown labels preset: ${JSON.stringify(spec)}. Known presets: ${Object.keys(PRESETS).join(\", \")}.`,\n );\n }\n\n if (typeof spec === \"object\") {\n const map = spec as Record<number, string>;\n const ids = Object.keys(map).map((k) => Number(k));\n if (ids.length === 0) {\n return [];\n }\n const maxId = Math.max(...ids);\n return Array.from({ length: maxId + 1 }, (_, i) => map[i] ?? `class_${i}`);\n }\n\n throw new LabelMapError(`Unsupported labels spec type: ${typeof spec}.`);\n}\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","/**\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 { resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\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\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names, manages execution-provider\n * selection, and provides a typed {@link OrtSession.run} method.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n public readonly providers: readonly string[],\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * @param model Either a URL string fetched by ORT, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list and pass-through `SessionOptions`.\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\n let session: ort.InferenceSession;\n try {\n if (typeof model === \"string\") {\n session = await ortRuntime.InferenceSession.create(model, sessionOptions);\n } else if (model instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(model, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n model 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);\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 /** 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","/**\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/** Get a 2D context from a canvas, throwing a typed error if the browser refuses. */\nexport function get2DContext(canvas: Canvas2D): Context2D {\n const ctx = canvas.getContext(\"2d\") 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","/**\n * Image loading utilities — convert any supported source into the canonical\n * {@link RGBImage} format.\n *\n * Browser-only: uses `fetch`, `createImageBitmap`, and a Canvas 2D context to\n * decode arbitrary inputs into a tightly-packed `Uint8Array` of HWC RGB pixels.\n */\n\nimport { createCanvas, get2DContext, imageDataToRGB } from \"../core/canvas\";\nimport { ImageLoadError } from \"../core/exceptions\";\nimport { RGBImage } from \"../types\";\n\n/** Anything {@link loadImage} accepts as an image input. */\nexport type ImageInput =\n | string\n | Blob\n | HTMLImageElement\n | HTMLCanvasElement\n | OffscreenCanvas\n | ImageBitmap\n | ImageData\n | RGBImage;\n\n/**\n * Load an image from any supported source into a HWC uint8 RGB array.\n *\n * @throws {@link ImageLoadError} if the source cannot be decoded or has an unsupported shape.\n */\nexport async function loadImage(source: ImageInput): Promise<RGBImage> {\n if (source instanceof RGBImage) {\n return source;\n }\n\n if (typeof ImageData !== \"undefined\" && source instanceof ImageData) {\n return imageDataToRGB(source);\n }\n\n if (typeof source === \"string\") {\n return loadFromUrl(source);\n }\n\n if (typeof Blob !== \"undefined\" && source instanceof Blob) {\n return loadFromBlob(source);\n }\n\n if (typeof HTMLImageElement !== \"undefined\" && source instanceof HTMLImageElement) {\n await waitForImageElement(source);\n return drawableToRGB(source, source.naturalWidth, source.naturalHeight);\n }\n\n if (typeof HTMLCanvasElement !== \"undefined\" && source instanceof HTMLCanvasElement) {\n return drawableToRGB(source, source.width, source.height);\n }\n\n if (typeof OffscreenCanvas !== \"undefined\" && source instanceof OffscreenCanvas) {\n return drawableToRGB(source, source.width, source.height);\n }\n\n if (typeof ImageBitmap !== \"undefined\" && source instanceof ImageBitmap) {\n return drawableToRGB(source, source.width, source.height);\n }\n\n throw new ImageLoadError(\n `Unsupported image source type: ${Object.prototype.toString.call(source)}`,\n );\n}\n\nasync function loadFromUrl(url: string): Promise<RGBImage> {\n let response: Response;\n try {\n response = await fetch(url);\n } catch (err) {\n throw new ImageLoadError(`Failed to fetch image from ${url}: ${(err as Error).message}`, {\n cause: err,\n });\n }\n if (!response.ok) {\n throw new ImageLoadError(\n `Failed to fetch image from ${url}: HTTP ${response.status} ${response.statusText}`,\n );\n }\n const blob = await response.blob();\n return loadFromBlob(blob);\n}\n\nasync function loadFromBlob(blob: Blob): Promise<RGBImage> {\n let bitmap: ImageBitmap;\n try {\n bitmap = await createImageBitmap(blob);\n } catch (err) {\n throw new ImageLoadError(`Failed to decode image blob: ${(err as Error).message}`, {\n cause: err,\n });\n }\n try {\n return drawableToRGB(bitmap, bitmap.width, bitmap.height);\n } finally {\n bitmap.close();\n }\n}\n\nfunction waitForImageElement(img: HTMLImageElement): Promise<void> {\n if (img.complete && img.naturalWidth > 0) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const onLoad = (): void => {\n cleanup();\n resolve();\n };\n const onError = (): void => {\n cleanup();\n reject(new ImageLoadError(\"Failed to load HTMLImageElement (load event errored)\"));\n };\n const cleanup = (): void => {\n img.removeEventListener(\"load\", onLoad);\n img.removeEventListener(\"error\", onError);\n };\n img.addEventListener(\"load\", onLoad, { once: true });\n img.addEventListener(\"error\", onError, { once: true });\n });\n}\n\nfunction drawableToRGB(drawable: CanvasImageSource, width: number, height: number): RGBImage {\n if (width === 0 || height === 0) {\n throw new ImageLoadError(`Cannot load image with zero dimension (${width}x${height}).`);\n }\n const canvas = createCanvas(width, height);\n const ctx = get2DContext(canvas);\n ctx.drawImage(drawable, 0, 0);\n const imageData = ctx.getImageData(0, 0, width, height);\n return imageDataToRGB(imageData);\n}\n","/**\n * Composable image preprocessing primitives (resize, normalize, letterbox, layout).\n *\n * Mirrors the Python `preprocess.image` module. Operates on the canonical\n * {@link RGBImage} (HWC RGB uint8) and produces uint8 or float32 buffers\n * depending on the operation.\n */\n\nimport * as ortRuntime from \"onnxruntime-web\";\nimport type * as ort from \"onnxruntime-web\";\n\nimport { createCanvas, get2DContext, imageDataToRGB, rgbToImageData } from \"../core/canvas\";\nimport { RGBImage } from \"../types\";\n\n/** Resize an image to `(targetWidth, targetHeight)` using high-quality canvas resampling. */\nexport function resize(image: RGBImage, targetWidth: number, targetHeight: number): RGBImage {\n if (targetWidth <= 0 || targetHeight <= 0) {\n throw new Error(`Invalid resize target ${targetWidth}x${targetHeight}.`);\n }\n if (targetWidth === image.width && targetHeight === image.height) {\n return image;\n }\n\n const srcCanvas = createCanvas(image.width, image.height);\n const srcCtx = get2DContext(srcCanvas);\n srcCtx.putImageData(rgbToImageData(image), 0, 0);\n\n const dstCanvas = createCanvas(targetWidth, targetHeight);\n const dstCtx = get2DContext(dstCanvas);\n dstCtx.imageSmoothingEnabled = true;\n dstCtx.imageSmoothingQuality = \"high\";\n dstCtx.drawImage(srcCanvas as CanvasImageSource, 0, 0, targetWidth, targetHeight);\n\n const imageData = dstCtx.getImageData(0, 0, targetWidth, targetHeight);\n return imageDataToRGB(imageData);\n}\n\n/**\n * Convert a uint8 image to a normalized float32 array (HWC layout preserved).\n *\n * Applies `(pixel * scale - mean) / std` channel-wise.\n */\nexport function normalize(\n image: RGBImage,\n mean: readonly [number, number, number],\n std: readonly [number, number, number],\n scale: number = 1 / 255,\n): Float32Array {\n const out = new Float32Array(image.data.length);\n const data = image.data;\n const m0 = mean[0];\n const m1 = mean[1];\n const m2 = mean[2];\n const s0 = std[0];\n const s1 = std[1];\n const s2 = std[2];\n for (let i = 0; i < data.length; i += 3) {\n out[i] = ((data[i] as number) * scale - m0) / s0;\n out[i + 1] = ((data[i + 1] as number) * scale - m1) / s1;\n out[i + 2] = ((data[i + 2] as number) * scale - m2) / s2;\n }\n return out;\n}\n\n/** Convert a uint8 image to a `Float32Array` in `[0, 1]` (HWC layout preserved). */\nexport function toFloat32(image: RGBImage, scale: number = 1 / 255): Float32Array {\n const out = new Float32Array(image.data.length);\n const data = image.data;\n for (let i = 0; i < data.length; i++) {\n out[i] = (data[i] as number) * scale;\n }\n return out;\n}\n\n/**\n * Transpose interleaved HWC data to planar CHW layout.\n *\n * @param hwc Source array of length `width * height * channels`.\n */\nexport function toCHW(\n hwc: Float32Array,\n width: number,\n height: number,\n channels: number = 3,\n): Float32Array {\n const expected = width * height * channels;\n if (hwc.length !== expected) {\n throw new Error(\n `toCHW: expected length ${expected} for ${width}x${height}x${channels}, got ${hwc.length}.`,\n );\n }\n const chw = new Float32Array(expected);\n const plane = width * height;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const hwcBase = (y * width + x) * channels;\n const planeIdx = y * width + x;\n for (let c = 0; c < channels; c++) {\n chw[c * plane + planeIdx] = hwc[hwcBase + c] as number;\n }\n }\n }\n return chw;\n}\n\n/** Wrap a Float32 buffer into an `ort.Tensor`. */\nexport function toFloat32Tensor(data: Float32Array, dims: readonly number[]): ort.Tensor {\n return new ortRuntime.Tensor(\"float32\", data, dims as number[]);\n}\n\n/**\n * Convert an HWC uint8 image to a CHW `Float32Array` scaled to `[0, 1]`.\n *\n * Mirrors `torchvision.transforms.ToTensor()` semantics: HWC → CHW,\n * `uint8 → float32 / 255`. Useful as input to YOLO-style detectors that\n * don't require ImageNet normalization.\n *\n * @returns CHW `Float32Array` of length `width * height * 3`.\n */\nexport function toTensor(image: RGBImage): Float32Array {\n const f32 = toFloat32(image);\n return toCHW(f32, image.width, image.height, 3);\n}\n\n/**\n * Convert an HWC BGR uint8 buffer (OpenCV layout) to the SDK's HWC RGB.\n *\n * Use when you receive image bytes from `cv2.imencode` over the wire and\n * want to feed them to the SDK without going through a canvas decode.\n *\n * @param bgr Flat BGR Uint8Array of length `width * height * 3`.\n */\nexport function fromCv2(bgr: Uint8Array, width: number, height: number): RGBImage {\n if (bgr.length !== width * height * 3) {\n throw new Error(\n `fromCv2: data length ${bgr.length} does not match width * height * 3 = ${width * height * 3}.`,\n );\n }\n const rgb = new Uint8Array(bgr.length);\n for (let i = 0; i < bgr.length; i += 3) {\n rgb[i] = bgr[i + 2] as number;\n rgb[i + 1] = bgr[i + 1] as number;\n rgb[i + 2] = bgr[i] as number;\n }\n return new RGBImage(rgb, width, height);\n}\n\n/**\n * Convert the SDK's HWC RGB image to an HWC BGR `Uint8Array` (OpenCV layout).\n *\n * Useful for round-tripping data to a Python OpenCV consumer.\n */\nexport function toCv2(image: RGBImage): Uint8Array {\n const rgb = image.data;\n const bgr = new Uint8Array(rgb.length);\n for (let i = 0; i < rgb.length; i += 3) {\n bgr[i] = rgb[i + 2] as number;\n bgr[i + 1] = rgb[i + 1] as number;\n bgr[i + 2] = rgb[i] as number;\n }\n return bgr;\n}\n\nexport interface LetterboxResult {\n /** The padded image at the target size. */\n readonly image: RGBImage;\n /** The factor applied to the original image (`< 1` if downscaled). */\n readonly scale: number;\n /** Horizontal padding in pixels (left side; right side has the same or +1). */\n readonly padLeft: number;\n /** Vertical padding in pixels (top side). */\n readonly padTop: number;\n}\n\n/**\n * Resize preserving aspect ratio, padding to `(targetWidth, targetHeight)`\n * with a constant fill color.\n *\n * Standard YOLO preprocessing — returning `scale` and `padLeft`/`padTop`\n * lets callers map detections back to the original image coordinates.\n */\nexport function letterbox(\n image: RGBImage,\n targetWidth: number,\n targetHeight: number,\n fill: readonly [number, number, number] = [114, 114, 114],\n): LetterboxResult {\n const scale = Math.min(targetWidth / image.width, targetHeight / image.height);\n const newW = Math.round(image.width * scale);\n const newH = Math.round(image.height * scale);\n const resized = resize(image, newW, newH);\n\n const out = new Uint8Array(targetWidth * targetHeight * 3);\n const f0 = fill[0];\n const f1 = fill[1];\n const f2 = fill[2];\n for (let i = 0; i < out.length; i += 3) {\n out[i] = f0;\n out[i + 1] = f1;\n out[i + 2] = f2;\n }\n\n const padLeft = Math.floor((targetWidth - newW) / 2);\n const padTop = Math.floor((targetHeight - newH) / 2);\n const rowBytes = newW * 3;\n for (let y = 0; y < newH; y++) {\n const srcOffset = y * rowBytes;\n const dstOffset = ((padTop + y) * targetWidth + padLeft) * 3;\n out.set(resized.data.subarray(srcOffset, srcOffset + rowBytes), dstOffset);\n }\n\n return {\n image: new RGBImage(out, targetWidth, targetHeight),\n scale,\n padLeft,\n padTop,\n };\n}\n","/**\n * Classification head postprocessing — softmax + top-k.\n */\n\n/** Apply numerically-stable softmax to a 1-D vector of logits. */\nexport function softmax(logits: Float32Array | readonly number[]): Float32Array {\n const n = logits.length;\n const out = new Float32Array(n);\n let max = -Infinity;\n for (let i = 0; i < n; i++) {\n const v = logits[i] as number;\n if (v > max) max = v;\n }\n let sum = 0;\n for (let i = 0; i < n; i++) {\n const e = Math.exp((logits[i] as number) - max);\n out[i] = e;\n sum += e;\n }\n for (let i = 0; i < n; i++) {\n out[i] = (out[i] as number) / sum;\n }\n return out;\n}\n\nexport interface TopKResult {\n readonly indices: Int32Array;\n readonly values: Float32Array;\n}\n\n/**\n * Return the top-k entries of a 1-D probability vector, sorted descending.\n *\n * @param k Number of entries to return; `null` returns all entries.\n */\nexport function topK(probabilities: Float32Array, k: number | null): TopKResult {\n const n = probabilities.length;\n const kEff = k === null ? n : Math.min(Math.max(0, k), n);\n\n const idx = new Array<number>(n);\n for (let i = 0; i < n; i++) idx[i] = i;\n idx.sort((a, b) => (probabilities[b] as number) - (probabilities[a] as number));\n\n const indices = new Int32Array(kEff);\n const values = new Float32Array(kEff);\n for (let i = 0; i < kEff; i++) {\n const j = idx[i] as number;\n indices[i] = j;\n values[i] = probabilities[j] as number;\n }\n return { indices, values };\n}\n","/**\n * Detection head postprocessing: anchor-free YOLO decoding + non-maximum suppression.\n *\n * The shared {@link decodeYoloAnchors} helper does the per-anchor work that\n * is identical for plain detection and segmentation (transpose, xywh→xyxy,\n * letterbox unmap, per-class NMS, sort & cap). {@link decodeYolo} is a thin\n * wrapper around it; the segmentation module ({@link ./segmentation.js})\n * calls the helper directly so it can also recover the per-anchor mask\n * coefficients.\n *\n * Works for any YOLO export with the post-v8 anchor-free head:\n * **YOLOv8 / v9 / v10 / v11 / v12** detect heads, all of which share the\n * `[1, 4 + nc, N]` output layout.\n */\n\nimport { BoundingBox } from \"../types\";\n\n/**\n * Greedy non-maximum suppression on axis-aligned bounding boxes.\n *\n * Mirrors `torchvision.ops.nms` (keeps boxes with the highest score, drops\n * any subsequent box whose IoU exceeds the threshold).\n *\n * @param boxes Flat array of length `4 * N` in xyxy order: `[x1,y1,x2,y2, ...]`.\n * @param scores Detection score per box, length `N`.\n * @param iouThreshold Boxes with IoU above this threshold relative to a kept box are suppressed.\n * @returns Indices of kept boxes, in descending score order.\n */\nexport function nms(boxes: Float32Array, scores: Float32Array, iouThreshold: number): Int32Array {\n const n = scores.length;\n if (n === 0) return new Int32Array(0);\n\n const areas = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const x1 = boxes[i * 4] as number;\n const y1 = boxes[i * 4 + 1] as number;\n const x2 = boxes[i * 4 + 2] as number;\n const y2 = boxes[i * 4 + 3] as number;\n areas[i] = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);\n }\n\n const order = new Array<number>(n);\n for (let i = 0; i < n; i++) order[i] = i;\n order.sort((a, b) => (scores[b] as number) - (scores[a] as number));\n\n const suppressed = new Uint8Array(n);\n const keep: number[] = [];\n\n for (let oi = 0; oi < order.length; oi++) {\n const i = order[oi] as number;\n if (suppressed[i]) continue;\n keep.push(i);\n\n const ax1 = boxes[i * 4] as number;\n const ay1 = boxes[i * 4 + 1] as number;\n const ax2 = boxes[i * 4 + 2] as number;\n const ay2 = boxes[i * 4 + 3] as number;\n const ai = areas[i] as number;\n\n for (let oj = oi + 1; oj < order.length; oj++) {\n const j = order[oj] as number;\n if (suppressed[j]) continue;\n\n const bx1 = boxes[j * 4] as number;\n const by1 = boxes[j * 4 + 1] as number;\n const bx2 = boxes[j * 4 + 2] as number;\n const by2 = boxes[j * 4 + 3] as number;\n\n const ix1 = Math.max(ax1, bx1);\n const iy1 = Math.max(ay1, by1);\n const ix2 = Math.min(ax2, bx2);\n const iy2 = Math.min(ay2, by2);\n const iw = Math.max(0, ix2 - ix1);\n const ih = Math.max(0, iy2 - iy1);\n const inter = iw * ih;\n const union = ai + (areas[j] as number) - inter;\n const iou = union > 0 ? inter / union : 0;\n if (iou > iouThreshold) suppressed[j] = 1;\n }\n }\n\n return Int32Array.from(keep);\n}\n\n/**\n * Per-class NMS — boxes are suppressed only by other boxes of the same class.\n *\n * Mirrors `torchvision.ops.batched_nms`.\n *\n * @param boxes Flat array of length `4 * N` in xyxy order.\n * @param scores Detection score per box, length `N`.\n * @param idxs Class index per box, length `N`. Boxes with different `idxs`\n * never suppress each other.\n * @param iouThreshold IoU threshold for suppression within a class.\n */\nexport function batchedNms(\n boxes: Float32Array,\n scores: Float32Array,\n idxs: Int32Array,\n iouThreshold: number,\n): Int32Array {\n if (scores.length === 0) return new Int32Array(0);\n\n const byClass = new Map<number, number[]>();\n for (let i = 0; i < idxs.length; i++) {\n const c = idxs[i] as number;\n const list = byClass.get(c);\n if (list === undefined) byClass.set(c, [i]);\n else list.push(i);\n }\n\n const keep: number[] = [];\n for (const indices of byClass.values()) {\n const m = indices.length;\n const subBoxes = new Float32Array(m * 4);\n const subScores = new Float32Array(m);\n for (let k = 0; k < m; k++) {\n const i = indices[k] as number;\n subBoxes[k * 4] = boxes[i * 4] as number;\n subBoxes[k * 4 + 1] = boxes[i * 4 + 1] as number;\n subBoxes[k * 4 + 2] = boxes[i * 4 + 2] as number;\n subBoxes[k * 4 + 3] = boxes[i * 4 + 3] as number;\n subScores[k] = scores[i] as number;\n }\n const subKeep = nms(subBoxes, subScores, iouThreshold);\n for (let k = 0; k < subKeep.length; k++) {\n keep.push(indices[subKeep[k] as number] as number);\n }\n }\n\n keep.sort((a, b) => (scores[b] as number) - (scores[a] as number));\n return Int32Array.from(keep);\n}\n\nexport interface DecodeYoloAnchorsOptions {\n /** Number of class-score channels following the 4 box channels. */\n readonly numClasses: number;\n readonly originalWidth: number;\n readonly originalHeight: number;\n readonly padLeft: number;\n readonly padTop: number;\n readonly scale: number;\n readonly confThreshold: number;\n readonly iouThreshold: number;\n readonly maxDetections: number;\n}\n\nexport interface DecodedAnchors {\n /** Indices into the original `numAnchors` axis, in descending confidence order. */\n readonly anchorIndices: Int32Array;\n /** `[k, 4]` boxes in original-image pixel coords, flat row-major xyxy. */\n readonly boxesXyxy: Float32Array;\n /** Predicted class id per survivor. */\n readonly classIds: Int32Array;\n /** Confidence per survivor. */\n readonly confidences: Float32Array;\n}\n\n/**\n * Shared YOLO per-anchor decode used by both detection and segmentation\n * (v8 / v9 / v10 / v11 / v12).\n *\n * Only the first `4 + numClasses` channels are read; later channels (e.g.\n * mask coefficients) are ignored — callers can fetch them via the returned\n * {@link DecodedAnchors.anchorIndices}.\n *\n * @param data Flat per-anchor output, length `channels * numAnchors`.\n * @param dims Dims as reported by ORT, e.g. `[1, 84, 8400]` (det) or\n * `[1, 116, 8400]` (seg). The leading batch dim must be 1.\n */\nexport function decodeYoloAnchors(\n data: Float32Array,\n dims: readonly number[],\n options: DecodeYoloAnchorsOptions,\n): DecodedAnchors {\n let normalized = dims;\n if (normalized.length === 3) {\n if (normalized[0] !== 1) {\n throw new Error(`decodeYoloAnchors: expected batch size 1, got ${normalized[0]}.`);\n }\n normalized = [normalized[1] as number, normalized[2] as number];\n }\n if (normalized.length !== 2) {\n throw new Error(\n `decodeYoloAnchors: expected 2-D output after batch removal, got dims=${JSON.stringify(dims)}.`,\n );\n }\n const channels = normalized[0] as number;\n const numAnchors = normalized[1] as number;\n\n const {\n numClasses,\n originalWidth,\n originalHeight,\n padLeft,\n padTop,\n scale,\n confThreshold,\n iouThreshold,\n maxDetections,\n } = options;\n\n if (numClasses < 1 || numClasses + 4 > channels) {\n throw new Error(\n `decodeYoloAnchors: invalid numClasses=${numClasses} for channels=${channels}.`,\n );\n }\n if (data.length !== channels * numAnchors) {\n throw new Error(\n `decodeYoloAnchors: data length ${data.length} does not match channels*numAnchors=${channels * numAnchors}.`,\n );\n }\n\n type Candidate = {\n anchorIdx: number;\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n classId: number;\n confidence: number;\n };\n const candidates: Candidate[] = [];\n\n for (let a = 0; a < numAnchors; a++) {\n let bestCls = 0;\n let bestScore = -Infinity;\n for (let c = 0; c < numClasses; c++) {\n const s = data[(4 + c) * numAnchors + a];\n if (s !== undefined && s > bestScore) {\n bestScore = s;\n bestCls = c;\n }\n }\n if (bestScore < confThreshold) continue;\n\n const cx = data[a] as number;\n const cy = data[numAnchors + a] as number;\n const w = data[2 * numAnchors + a] as number;\n const h = data[3 * numAnchors + a] as number;\n\n let x1 = cx - w / 2;\n let y1 = cy - h / 2;\n let x2 = cx + w / 2;\n let y2 = cy + h / 2;\n\n x1 = (x1 - padLeft) / scale;\n y1 = (y1 - padTop) / scale;\n x2 = (x2 - padLeft) / scale;\n y2 = (y2 - padTop) / scale;\n\n x1 = Math.max(0, Math.min(originalWidth, x1));\n y1 = Math.max(0, Math.min(originalHeight, y1));\n x2 = Math.max(0, Math.min(originalWidth, x2));\n y2 = Math.max(0, Math.min(originalHeight, y2));\n\n candidates.push({ anchorIdx: a, x1, y1, x2, y2, classId: bestCls, confidence: bestScore });\n }\n\n if (candidates.length === 0) return emptyDecoded();\n\n // Build flat arrays then delegate to batchedNms — same algorithm as before\n // but funnelled through the public per-class NMS helper.\n const flatBoxes = new Float32Array(candidates.length * 4);\n const scoresArr = new Float32Array(candidates.length);\n const idxsArr = new Int32Array(candidates.length);\n for (let i = 0; i < candidates.length; i++) {\n const c = candidates[i] as Candidate;\n flatBoxes[i * 4] = c.x1;\n flatBoxes[i * 4 + 1] = c.y1;\n flatBoxes[i * 4 + 2] = c.x2;\n flatBoxes[i * 4 + 3] = c.y2;\n scoresArr[i] = c.confidence;\n idxsArr[i] = c.classId;\n }\n const kept = batchedNms(flatBoxes, scoresArr, idxsArr, iouThreshold);\n if (kept.length === 0) return emptyDecoded();\n\n const limited = Array.from(kept).slice(0, maxDetections);\n const k = limited.length;\n const anchorIndices = new Int32Array(k);\n const boxesXyxy = new Float32Array(k * 4);\n const classIds = new Int32Array(k);\n const confidences = new Float32Array(k);\n for (let i = 0; i < k; i++) {\n const c = candidates[limited[i] as number] as Candidate;\n anchorIndices[i] = c.anchorIdx;\n boxesXyxy[i * 4] = c.x1;\n boxesXyxy[i * 4 + 1] = c.y1;\n boxesXyxy[i * 4 + 2] = c.x2;\n boxesXyxy[i * 4 + 3] = c.y2;\n classIds[i] = c.classId;\n confidences[i] = c.confidence;\n }\n return { anchorIndices, boxesXyxy, classIds, confidences };\n}\n\nfunction emptyDecoded(): DecodedAnchors {\n return {\n anchorIndices: new Int32Array(0),\n boxesXyxy: new Float32Array(0),\n classIds: new Int32Array(0),\n confidences: new Float32Array(0),\n };\n}\n\nexport interface DecodeYoloOptions {\n readonly originalWidth: number;\n readonly originalHeight: number;\n readonly padLeft: number;\n readonly padTop: number;\n readonly scale: number;\n readonly confThreshold: number;\n readonly iouThreshold: number;\n readonly maxDetections: number;\n}\n\nexport interface DecodedDetection {\n readonly bbox: BoundingBox;\n readonly classId: number;\n readonly confidence: number;\n}\n\n/**\n * Decode an anchor-free YOLO detection output into a list of detections.\n *\n * Works for **YOLOv8 / v9 / v10 / v11 / v12** detect heads.\n *\n * Expected raw shape: `[1, 4 + numClasses, N]`. `numClasses` is inferred\n * from the channel count.\n */\nexport function decodeYolo(\n output: Float32Array,\n outputDims: readonly number[],\n options: DecodeYoloOptions,\n): DecodedDetection[] {\n const channels = outputDims.length === 3 ? outputDims[1] : outputDims[0];\n if (channels === undefined || channels < 5) {\n throw new Error(`decodeYolo: invalid output channel count ${channels} (expected >= 5).`);\n }\n const numClasses = channels - 4;\n\n const decoded = decodeYoloAnchors(output, outputDims, {\n numClasses,\n ...options,\n });\n\n const results: DecodedDetection[] = [];\n for (let i = 0; i < decoded.classIds.length; i++) {\n results.push({\n bbox: new BoundingBox(\n decoded.boxesXyxy[i * 4] as number,\n decoded.boxesXyxy[i * 4 + 1] as number,\n decoded.boxesXyxy[i * 4 + 2] as number,\n decoded.boxesXyxy[i * 4 + 3] as number,\n ),\n classId: decoded.classIds[i] as number,\n confidence: decoded.confidences[i] as number,\n });\n }\n return results;\n}\n\nlet _warnedDecodeYoloV8 = false;\nlet _warnedDecodeYoloV8Anchors = false;\n\n/**\n * @deprecated since 0.2.0 — use {@link decodeYolo}. Same behavior; the\n * decoder covers v8/v9/v10/v11/v12 detect heads. Will be removed in 0.3.0.\n */\nexport function decodeYoloV8(\n output: Float32Array,\n outputDims: readonly number[],\n options: DecodeYoloOptions,\n): DecodedDetection[] {\n if (!_warnedDecodeYoloV8) {\n _warnedDecodeYoloV8 = true;\n console.warn(\n \"[@ort-vision-sdk/web] decodeYoloV8 is deprecated since 0.2.0; use decodeYolo. \" +\n \"The alias will be removed in 0.3.0.\",\n );\n }\n return decodeYolo(output, outputDims, options);\n}\n\n/**\n * @deprecated since 0.2.0 — use {@link decodeYoloAnchors}. Will be removed in 0.3.0.\n */\nexport function decodeYoloV8Anchors(\n data: Float32Array,\n dims: readonly number[],\n options: DecodeYoloAnchorsOptions,\n): DecodedAnchors {\n if (!_warnedDecodeYoloV8Anchors) {\n _warnedDecodeYoloV8Anchors = true;\n console.warn(\n \"[@ort-vision-sdk/web] decodeYoloV8Anchors is deprecated since 0.2.0; use decodeYoloAnchors. \" +\n \"The alias will be removed in 0.3.0.\",\n );\n }\n return decodeYoloAnchors(data, dims, options);\n}\n\n/** @deprecated since 0.2.0 — use {@link DecodeYoloAnchorsOptions}. */\nexport type DecodeYoloV8AnchorsOptions = DecodeYoloAnchorsOptions;\n\n/** @deprecated since 0.2.0 — use {@link DecodeYoloOptions}. */\nexport type DecodeYoloV8Options = DecodeYoloOptions;\n","/**\n * Segmentation head postprocessing: YOLO instance-segmentation decoding.\n *\n * Compatible with YOLOv8-seg / YOLOv11-seg exports (and any later seg head\n * sharing the layout). The model produces two output tensors:\n *\n * - `output0` of shape `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — the\n * same per-anchor predictions as plain YOLO detection plus an extra\n * `numMaskCoefs` (typically 32) channels of mask coefficients.\n * - `output1` of shape `(1, numMaskCoefs, maskH, maskW)` — a set of \"prototype\"\n * masks shared across all anchors.\n *\n * The per-anchor decode (xywh→xyxy, undo letterbox, per-class NMS, sort & cap)\n * is delegated to {@link decodeYoloAnchors}; this module only handles the\n * mask-specific work: matmul against prototypes, sigmoid, bilinear resize and\n * thresholding.\n */\n\nimport { decodeYoloAnchors } from \"./detection\";\nimport { BoundingBox, Mask } from \"../types\";\n\nexport interface DecodeYoloSegOptions {\n readonly numClasses: number;\n /** Model input `[width, height]` (post-letterbox). */\n readonly inputWidth: number;\n readonly inputHeight: number;\n /** Original image `[width, height]`. */\n readonly originalWidth: number;\n readonly originalHeight: number;\n /** Letterbox horizontal padding in input-tensor pixels. */\n readonly padLeft: number;\n /** Letterbox vertical padding in input-tensor pixels. */\n readonly padTop: number;\n /** Letterbox scale factor. */\n readonly scale: number;\n readonly confThreshold: number;\n readonly iouThreshold: number;\n readonly maxDetections: number;\n /** Probability cutoff applied to the soft mask. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface DecodedSegmentation {\n readonly bbox: BoundingBox;\n readonly classId: number;\n readonly confidence: number;\n /** Binary mask cropped to `bbox`. Width/height match `bbox.asIntXyxy()` extents. */\n readonly mask: Mask;\n}\n\n/**\n * Decode YOLO segmentation raw outputs into a list of segmented instances.\n *\n * Compatible with YOLOv8-seg / YOLOv11-seg.\n *\n * @param perAnchorData Flat `output0`, length `(4 + numClasses + numMaskCoefs) * numAnchors`.\n * @param perAnchorDims Dims as reported by ORT, e.g. `[1, 116, 8400]`.\n * @param prototypeData Flat `output1`, length `numMaskCoefs * maskH * maskW`.\n * @param prototypeDims Dims as reported by ORT, e.g. `[1, 32, 160, 160]`.\n */\nexport function decodeYoloSeg(\n perAnchorData: Float32Array,\n perAnchorDims: readonly number[],\n prototypeData: Float32Array,\n prototypeDims: readonly number[],\n options: DecodeYoloSegOptions,\n): DecodedSegmentation[] {\n // Strip batch dim from prototypes; perAnchor batch is validated by the helper.\n let pDims = prototypeDims;\n if (pDims.length === 4) {\n if (pDims[0] !== 1) {\n throw new Error(`decodeYoloSeg: expected batch size 1 in prototypes, got ${pDims[0]}.`);\n }\n pDims = [pDims[1] as number, pDims[2] as number, pDims[3] as number];\n }\n if (pDims.length !== 3) {\n throw new Error(\n `decodeYoloSeg: expected 3-D prototypes after batch removal, got dims=${JSON.stringify(prototypeDims)}.`,\n );\n }\n const numMaskCoefs = pDims[0] as number;\n const maskH = pDims[1] as number;\n const maskW = pDims[2] as number;\n\n const channels = perAnchorDims.length === 3 ? perAnchorDims[1] : perAnchorDims[0];\n const numAnchors = perAnchorDims.length === 3 ? perAnchorDims[2] : perAnchorDims[1];\n if (channels === undefined || numAnchors === undefined) {\n throw new Error(\n `decodeYoloSeg: cannot read channels/numAnchors from dims=${JSON.stringify(perAnchorDims)}.`,\n );\n }\n\n const expectedChannels = 4 + options.numClasses + numMaskCoefs;\n if (channels !== expectedChannels) {\n throw new Error(\n `decodeYoloSeg: channels=${channels} does not match 4 + numClasses(${options.numClasses}) + numMaskCoefs(${numMaskCoefs}) = ${expectedChannels}.`,\n );\n }\n if (prototypeData.length !== numMaskCoefs * maskH * maskW) {\n throw new Error(\n `decodeYoloSeg: prototype length ${prototypeData.length} does not match dims=${JSON.stringify(prototypeDims)}.`,\n );\n }\n\n const decoded = decodeYoloAnchors(perAnchorData, perAnchorDims, {\n numClasses: options.numClasses,\n originalWidth: options.originalWidth,\n originalHeight: options.originalHeight,\n padLeft: options.padLeft,\n padTop: options.padTop,\n scale: options.scale,\n confThreshold: options.confThreshold,\n iouThreshold: options.iouThreshold,\n maxDetections: options.maxDetections,\n });\n\n if (decoded.anchorIndices.length === 0) return [];\n\n const maskThreshold = options.maskThreshold ?? 0.5;\n const scaleX = maskW / options.inputWidth;\n const scaleY = maskH / options.inputHeight;\n const protoPlane = maskH * maskW;\n const coefBase = (4 + options.numClasses) * numAnchors;\n\n const results: DecodedSegmentation[] = [];\n\n for (let i = 0; i < decoded.anchorIndices.length; i++) {\n const a = decoded.anchorIndices[i] as number;\n const x1 = decoded.boxesXyxy[i * 4] as number;\n const y1 = decoded.boxesXyxy[i * 4 + 1] as number;\n const x2 = decoded.boxesXyxy[i * 4 + 2] as number;\n const y2 = decoded.boxesXyxy[i * 4 + 3] as number;\n const bbox = new BoundingBox(x1, y1, x2, y2);\n const classId = decoded.classIds[i] as number;\n const confidence = decoded.confidences[i] as number;\n\n const bboxW = Math.max(0, Math.trunc(x2) - Math.trunc(x1));\n const bboxH = Math.max(0, Math.trunc(y2) - Math.trunc(y1));\n\n if (bboxW === 0 || bboxH === 0) {\n results.push({ bbox, classId, confidence, mask: new Mask(new Uint8Array(0), 0, 0) });\n continue;\n }\n\n // Bbox in input-tensor coords, then in low-res mask coords.\n const ibx1 = x1 * options.scale + options.padLeft;\n const iby1 = y1 * options.scale + options.padTop;\n const ibx2 = x2 * options.scale + options.padLeft;\n const iby2 = y2 * options.scale + options.padTop;\n\n const mbx1 = Math.max(0, Math.floor(ibx1 * scaleX));\n const mby1 = Math.max(0, Math.floor(iby1 * scaleY));\n const mbx2 = Math.min(maskW, Math.ceil(ibx2 * scaleX));\n const mby2 = Math.min(maskH, Math.ceil(iby2 * scaleY));\n\n if (mbx2 <= mbx1 || mby2 <= mby1) {\n results.push({\n bbox,\n classId,\n confidence,\n mask: new Mask(new Uint8Array(bboxW * bboxH), bboxW, bboxH),\n });\n continue;\n }\n\n // Compute soft mask only within the prototype region under this bbox.\n const cropW = mbx2 - mbx1;\n const cropH = mby2 - mby1;\n const softCrop = new Float32Array(cropW * cropH);\n for (let y = 0; y < cropH; y++) {\n const py = mby1 + y;\n for (let x = 0; x < cropW; x++) {\n const px = mbx1 + x;\n let sum = 0;\n for (let kk = 0; kk < numMaskCoefs; kk++) {\n const coef = perAnchorData[coefBase + kk * numAnchors + a];\n const proto = prototypeData[kk * protoPlane + py * maskW + px];\n sum += coef * proto;\n }\n softCrop[y * cropW + x] = sigmoid(sum);\n }\n }\n\n const resized = resizeBilinear(softCrop, cropW, cropH, bboxW, bboxH);\n const binary = new Uint8Array(bboxW * bboxH);\n for (let j = 0; j < binary.length; j++) {\n binary[j] = resized[j] >= maskThreshold ? 255 : 0;\n }\n\n results.push({ bbox, classId, confidence, mask: new Mask(binary, bboxW, bboxH) });\n }\n\n return results;\n}\n\nfunction sigmoid(x: number): number {\n if (x >= 0) {\n return 1 / (1 + Math.exp(-x));\n }\n const e = Math.exp(x);\n return e / (1 + e);\n}\n\nlet _warnedDecodeYoloV8Seg = false;\n\n/** @deprecated since 0.2.0 — use {@link decodeYoloSeg}. Will be removed in 0.3.0. */\nexport function decodeYoloV8Seg(\n perAnchorData: Float32Array,\n perAnchorDims: readonly number[],\n prototypeData: Float32Array,\n prototypeDims: readonly number[],\n options: DecodeYoloSegOptions,\n): DecodedSegmentation[] {\n if (!_warnedDecodeYoloV8Seg) {\n _warnedDecodeYoloV8Seg = true;\n console.warn(\n \"[@ort-vision-sdk/web] decodeYoloV8Seg is deprecated since 0.2.0; use decodeYoloSeg. \" +\n \"The alias will be removed in 0.3.0.\",\n );\n }\n return decodeYoloSeg(perAnchorData, perAnchorDims, prototypeData, prototypeDims, options);\n}\n\n/** @deprecated since 0.2.0 — use {@link DecodeYoloSegOptions}. */\nexport type DecodeYoloV8SegOptions = DecodeYoloSegOptions;\n\nfunction resizeBilinear(\n src: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number,\n): Float32Array {\n const out = new Float32Array(targetWidth * targetHeight);\n if (targetWidth === 0 || targetHeight === 0 || srcWidth === 0 || srcHeight === 0) {\n return out;\n }\n if (targetWidth === srcWidth && targetHeight === srcHeight) {\n out.set(src);\n return out;\n }\n const sx = srcWidth / targetWidth;\n const sy = srcHeight / targetHeight;\n for (let y = 0; y < targetHeight; y++) {\n const yy = (y + 0.5) * sy - 0.5;\n const y0 = Math.max(0, Math.floor(yy));\n const y1 = Math.min(srcHeight - 1, y0 + 1);\n const wy = Math.max(0, Math.min(1, yy - y0));\n for (let x = 0; x < targetWidth; x++) {\n const xx = (x + 0.5) * sx - 0.5;\n const x0 = Math.max(0, Math.floor(xx));\n const x1 = Math.min(srcWidth - 1, x0 + 1);\n const wx = Math.max(0, Math.min(1, xx - x0));\n const v00 = src[y0 * srcWidth + x0];\n const v01 = src[y0 * srcWidth + x1];\n const v10 = src[y1 * srcWidth + x0];\n const v11 = src[y1 * srcWidth + x1];\n const top = v00 * (1 - wx) + v01 * wx;\n const bot = v10 * (1 - wx) + v11 * wx;\n out[y * targetWidth + x] = top * (1 - wy) + bot * wy;\n }\n }\n return out;\n}\n","/**\n * Common foundation for task-oriented vision SDK objects.\n *\n * The base only owns the {@link OrtSession} — label resolution lives in each\n * subclass because how `numClasses` is read from the model differs per task.\n */\n\nimport type { OrtSession } from \"../core/session\";\n\nexport abstract class VisionTask {\n protected constructor(protected readonly _session: OrtSession) {}\n\n /** The underlying {@link OrtSession} used to run inference. */\n get session(): OrtSession {\n return this._session;\n }\n}\n","/**\n * Image classification task using ONNX Runtime Web.\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { softmax, topK } from \"../postprocess/classification\";\nimport { normalize, resize, toCHW, toFloat32Tensor } from \"../preprocess/image\";\nimport { ClassificationResults, Probs } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type ClassProbability, type ClassificationResult, type RGBImage } from \"../types\";\n\nconst IMAGENET_MEAN: readonly [number, number, number] = [0.485, 0.456, 0.406];\nconst IMAGENET_STD: readonly [number, number, number] = [0.229, 0.224, 0.225];\n\nexport interface ClassifierOptions extends OrtSessionOptions {\n /** Class label spec — see {@link resolveLabels}. */\n readonly labels: LabelSpec;\n /**\n * Number of classes the model can predict. Required when `labels` is `null`\n * or when you want to validate that the supplied labels match the model.\n */\n readonly numClasses?: number;\n /** Model input `[width, height]` in pixels. Defaults to `[224, 224]`. */\n readonly inputSize?: readonly [number, number];\n /** Per-channel RGB mean used for normalization. Defaults to ImageNet. */\n readonly mean?: readonly [number, number, number];\n /** Per-channel RGB standard deviation. Defaults to ImageNet. */\n readonly std?: readonly [number, number, number];\n /**\n * If `true` (default), apply softmax to the raw model output. Set to\n * `false` for models whose final layer already produces a probability\n * distribution.\n */\n readonly applySoftmax?: boolean;\n}\n\nexport interface ClassifierPredictOptions {\n /**\n * If set, the per-class probability list in `results[0].result.probabilities`\n * is truncated to the top-K entries. The bulk `probs` view always exposes\n * the full vector.\n */\n readonly topK?: number;\n}\n\n/**\n * Image classifier wrapping an ONNX model with ImageNet-style preprocessing.\n *\n * `predict()` returns `Promise<ClassificationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes a `probs`\n * collection (`top1`, `top1conf`, `top5`, `top5conf`, `data`) plus the\n * legacy per-class probability list with names already resolved.\n *\n * Defaults: 224×224 RGB input, `float32` normalized with ImageNet mean/std,\n * NCHW layout, batch size 1, softmax applied to the raw output.\n *\n * @example\n * ```typescript\n * const clf = await Classifier.create(\"/models/resnet50.onnx\", {\n * labels: [\"tench\", \"goldfish\", ...] // 1000 ImageNet labels\n * });\n * const r = (await clf.predict(\"/images/dog.jpg\"))[0];\n * console.log(r.cls, r.conf, r.name);\n * console.log(r.probs.top5, r.probs.top5conf);\n * ```\n */\nexport class Classifier extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _mean: readonly [number, number, number],\n private readonly _std: readonly [number, number, number],\n private readonly _applySoftmax: boolean,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: ClassifierOptions): Promise<Classifier> {\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels, { numClasses: options.numClasses });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Classifier(\n session,\n labels,\n names,\n options.inputSize ?? [224, 224],\n options.mean ?? IMAGENET_MEAN,\n options.std ?? IMAGENET_STD,\n options.applySoftmax ?? true,\n );\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model can predict. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: ClassifierPredictOptions = {},\n ): Promise<ClassificationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run classification on a single image. */\n async predict(\n image: ImageInput,\n options: ClassifierPredictOptions = {},\n ): Promise<ClassificationResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const tensor = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n const firstOutputName = this._session.outputNames[0];\n if (firstOutputName === undefined) {\n throw new Error(\"Classifier model has no outputs.\");\n }\n const raw = outputs[firstOutputName];\n if (raw === undefined) {\n throw new Error(\n `Classifier model output ${firstOutputName} missing from run() result.`,\n );\n }\n const fullProbs = this._postprocess(raw.data as Float32Array);\n\n const { indices, values } = topK(fullProbs, options.topK ?? null);\n const probabilities: ClassProbability[] = [];\n for (let i = 0; i < indices.length; i++) {\n const id = indices[i] as number;\n const className = this._labels[id] ?? `class_${id}`;\n probabilities.push({\n classId: id,\n className,\n probability: values[i] as number,\n cls: id,\n name: className,\n conf: values[i] as number,\n });\n }\n if (probabilities.length === 0) {\n throw new Error(\"Classifier produced no probabilities (empty output).\");\n }\n\n const top = probabilities[0] as ClassProbability;\n const result: ClassificationResult = {\n classId: top.classId,\n className: top.className,\n confidence: top.probability,\n cls: top.classId,\n name: top.className,\n conf: top.probability,\n image: original,\n probabilities,\n };\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new ClassificationResults(\n new Probs(fullProbs),\n result,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): ort.Tensor {\n const [tw, th] = this._inputSize;\n const resized = resize(image, tw, th);\n const normalized = normalize(resized, this._mean, this._std);\n const chw = toCHW(normalized, resized.width, resized.height, 3);\n return toFloat32Tensor(chw, [1, 3, resized.height, resized.width]);\n }\n\n private _postprocess(raw: Float32Array): Float32Array {\n return this._applySoftmax ? softmax(raw) : new Float32Array(raw);\n }\n}\n","/**\n * Object detection task using anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYolo } from \"../postprocess/detection\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, DetectionResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type DetectionResult, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the model's detection head.\n *\n * - `\"yolo\"`: anchor-free YOLO head with output shape `[1, 4 + nc, N]` —\n * covers YOLOv8, v9, v10, v11, v12, v26 detect exports.\n *\n * The SDK does **not** auto-detect the head from the model — the caller is\n * responsible for picking a head that matches their export. Future families\n * (v5/v6/v7 with `[1, N, 5+nc]`) will be added as new literal members.\n */\nexport type DetectorHead = \"yolo\";\n\nexport interface DetectorOptions extends OrtSessionOptions {\n /**\n * Decoder family for the detection head. Default `\"yolo\"` covers\n * YOLOv8/v9/v10/v11/v12/v26.\n */\n readonly head?: DetectorHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of detections per image. */\n readonly maxDetections?: number;\n}\n\nexport interface DetectorPredictOptions {\n /** Override the default confidence threshold. */\n readonly confThreshold?: number;\n /** Override the default IoU threshold. */\n readonly iouThreshold?: number;\n /**\n * If set, keep only detections whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Object detector for anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n *\n * `predict()` returns `Promise<DetectionResults[]>` (length 1 for a single\n * image), mirroring Ultralytics' `YOLO(\"img.jpg\")`. Iterate the envelope for\n * per-instance dataclasses, or use the bulk `boxes` view (`.xyxy`, `.xywh`,\n * `.xyxyn`, `.xywhn`, `.cls`, `.conf`).\n *\n * @example\n * ```typescript\n * const det = await Detector.create(\"/models/yolov8n.onnx\");\n * const results = await det.predict(\"/images/street.jpg\");\n * const r = results[0];\n * console.log(r.boxes.xyxy, r.boxes.cls, r.boxes.conf, r.names);\n * for (const d of r) {\n * console.log(d.cls, d.conf, d.box.xyxy);\n * }\n * ```\n */\nexport class Detector extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: DetectorHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: DetectorOptions = {}): Promise<Detector> {\n const head: DetectorHead = options.head ?? \"yolo\";\n if (head !== \"yolo\") {\n throw new Error(`Unsupported detector head '${head}'. Supported: 'yolo'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Detector(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): DetectorHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /**\n * Alias for {@link predict} — call the detector like a torch `nn.Module`.\n *\n * Use as `det.call(img)` since JavaScript class instances are not callable;\n * for direct invocation, prefer `det.predict(img)`. The full\n * {@link DetectorPredictOptions} (including `classes`) is supported.\n */\n async call(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n return this.predict(image, options);\n }\n\n /** Run detection on a single image. */\n async predict(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n\n const firstOutputName = this._session.outputNames[0];\n if (firstOutputName === undefined) {\n throw new Error(\"Detector model has no outputs.\");\n }\n const raw = outputs[firstOutputName];\n if (raw === undefined) {\n throw new Error(`Detector model output ${firstOutputName} missing from run() result.`);\n }\n\n const decodedAll = decodeYolo(raw.data as Float32Array, raw.dims, {\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n });\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new DetectionResults(\n this._buildBoxes(detections, orig),\n detections,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n ): DetectionResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let cropped: RGBImage;\n if (cx2 > cx1 && cy2 > cy1) {\n const cw = cx2 - cx1;\n const ch = cy2 - cy1;\n const out = new Uint8Array(cw * ch * 3);\n for (let row = 0; row < ch; row++) {\n const srcOffset = ((cy1 + row) * original.width + cx1) * 3;\n out.set(original.data.subarray(srcOffset, srcOffset + cw * 3), row * cw * 3);\n }\n cropped = new RGBImage(out, cw, ch);\n } else {\n cropped = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n croppedImage: cropped,\n };\n }\n\n private _buildBoxes(\n detections: readonly DetectionResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as DetectionResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n}\n","/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new SegmentationResults(\n this._buildBoxes(detections, orig),\n this._buildMasks(detections, orig),\n detections,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n","/**\n * `tempest-react-sdk/vision` — browser computer-vision inference with ONNX\n * Runtime Web (classification, detection, segmentation).\n *\n * Vendored from `@mauriciobenjamin700/ort-vision-sdk-web@0.2.1` (MIT, same\n * author) so it ships inside this SDK without an extra package install.\n * `onnxruntime-web` stays an optional peer dependency — install it (and ship\n * the matching `.wasm` files) only when you use this subpath.\n *\n * Do not hand-edit — regenerate with `npm run vendor:vision`.\n */\n\nexport {\n BoundingBox,\n Mask,\n RGBImage,\n type ClassProbability,\n type ClassificationResult,\n type DetectionResult,\n type SegmentationResult,\n} from \"./types\";\n\nexport {\n Boxes,\n ClassificationResults,\n DetectionResults,\n Masks,\n Probs,\n SegmentationResults,\n} from \"./results\";\n\nexport { COCO_CLASSES, type LabelSpec, type ResolveLabelsOptions, resolveLabels } from \"./labels\";\n\nexport {\n ImageLoadError,\n InferenceError,\n LabelMapError,\n ModelLoadError,\n OrtVisionError,\n ProviderNotAvailableError,\n} from \"./core/exceptions\";\n\nexport { type ModelSource, type OrtSessionOptions, OrtSession } from \"./core/session\";\nexport { DEFAULT_PROVIDERS, resolveProviders } from \"./core/providers\";\n\nexport { type ImageInput, loadImage } from \"./io/image\";\n\nexport {\n type LetterboxResult,\n fromCv2,\n letterbox,\n normalize,\n resize,\n toCHW,\n toCv2,\n toFloat32,\n toFloat32Tensor,\n toTensor,\n} from \"./preprocess/image\";\n\nexport { type TopKResult, softmax, topK } from \"./postprocess/classification\";\n\nexport {\n type DecodeYoloAnchorsOptions,\n type DecodeYoloOptions,\n type DecodeYoloV8AnchorsOptions,\n type DecodeYoloV8Options,\n type DecodedAnchors,\n type DecodedDetection,\n batchedNms,\n decodeYolo,\n decodeYoloAnchors,\n decodeYoloV8,\n decodeYoloV8Anchors,\n nms,\n} from \"./postprocess/detection\";\n\nexport {\n type DecodeYoloSegOptions,\n type DecodeYoloV8SegOptions,\n type DecodedSegmentation,\n decodeYoloSeg,\n decodeYoloV8Seg,\n} from \"./postprocess/segmentation\";\n\nexport { VisionTask } from \"./tasks/base\";\nexport {\n type ClassifierOptions,\n type ClassifierPredictOptions,\n Classifier,\n} from \"./tasks/classifier\";\nexport {\n type DetectorHead,\n type DetectorOptions,\n type DetectorPredictOptions,\n Detector,\n} from \"./tasks/detector\";\nexport {\n type SegmenterHead,\n type SegmenterOptions,\n type SegmenterPredictOptions,\n Segmenter,\n} from \"./tasks/segmenter\";\n\nexport const VERSION: string = \"0.2.1\";\n","import { useEffect, useRef, useState, type RefObject } from \"react\";\n\n/** Lifecycle status of the camera stream. */\nexport type CameraStreamStatus = \"idle\" | \"loading\" | \"ready\" | \"error\";\n\n/** Classified reason a camera stream could not be acquired. */\nexport type CameraStreamErrorKind =\n | \"unsupported\"\n | \"permission-denied\"\n | \"no-camera\"\n | \"in-use\"\n | \"insecure\"\n | \"unknown\";\n\n/** A classified camera error with a human-readable, English message. */\nexport interface CameraStreamError {\n kind: CameraStreamErrorKind;\n message: string;\n}\n\n/** Options for {@link useCameraStream}. */\nexport interface UseCameraStreamOptions {\n /**\n * Constraints passed to `getUserMedia`. Defaults to the rear\n * (\"environment\") camera at Full-HD ideal resolution with audio off.\n * Read when the stream (re)starts — change it and call `retry()` to apply.\n */\n constraints?: MediaStreamConstraints;\n}\n\n/** Value returned by {@link useCameraStream}. */\nexport interface UseCameraStreamApi {\n /** Current lifecycle status. */\n status: CameraStreamStatus;\n /** The classified error, or `null` while not in the `error` status. */\n error: CameraStreamError | null;\n /** Attach to a `<video ref={…} />`. The stream is wired to it once ready. */\n videoRef: RefObject<HTMLVideoElement | null>;\n /** Manually re-attempt after an error (e.g. the user changed permissions). */\n retry: () => void;\n}\n\n/** Rear-camera Full-HD defaults used when no `constraints` are supplied. */\nconst DEFAULT_CONSTRAINTS: MediaStreamConstraints = {\n video: {\n facingMode: { ideal: \"environment\" },\n width: { ideal: 1920 },\n height: { ideal: 1080 },\n },\n audio: false,\n};\n\n/**\n * Map an unknown failure into a {@link CameraStreamError}. Secure-context and\n * environment checks run first (they are the reason `getUserMedia` is missing\n * or rejects), then the `DOMException.name` is mapped to a stable `kind`.\n */\nfunction classifyError(err: unknown): CameraStreamError {\n if (typeof window === \"undefined\") {\n return { kind: \"unsupported\", message: \"Camera is unavailable in this environment.\" };\n }\n if (!window.isSecureContext) {\n return {\n kind: \"insecure\",\n message: \"Camera access requires a secure (HTTPS) connection.\",\n };\n }\n if (err instanceof DOMException) {\n switch (err.name) {\n case \"NotAllowedError\":\n case \"SecurityError\":\n return {\n kind: \"permission-denied\",\n message: \"Camera permission denied. Enable access in your browser settings.\",\n };\n case \"NotFoundError\":\n case \"OverconstrainedError\":\n return {\n kind: \"no-camera\",\n message: \"No camera available on this device.\",\n };\n case \"NotReadableError\":\n case \"AbortError\":\n return {\n kind: \"in-use\",\n message: \"The camera is in use by another app. Close it and try again.\",\n };\n }\n }\n return {\n kind: \"unknown\",\n message:\n err instanceof Error ? err.message : \"Unexpected error while accessing the camera.\",\n };\n}\n\n/**\n * Acquire a `MediaStream` via `getUserMedia`, attach it to a `<video>` element,\n * and expose status/error so the page can render permission and error states.\n * The stream is automatically released on unmount or retry.\n *\n * Defaults to the rear (\"environment\") camera; desktops fall back to whatever\n * single camera they expose. Pass `options.constraints` to override.\n *\n * Implementation notes:\n * - Cleanup detaches the stream from a *snapshotted* video node, so it releases\n * the same element it attached to even if the page remounts the `<video>`.\n * - When `getUserMedia` is missing, an insecure context is the usual cause, so\n * the hook prefers that (actionable) error; otherwise it reports `unsupported`.\n * - `video.play()` rejections are swallowed: autoplay may be blocked, but the\n * user gesture that opened the camera usually counts and playback resumes on\n * the next interaction.\n *\n * @param options - optional configuration (see {@link UseCameraStreamOptions}).\n * @returns The stream status, classified error, a `videoRef` to attach, and a\n * `retry()` to re-attempt acquisition.\n */\nexport function useCameraStream(options: UseCameraStreamOptions = {}): UseCameraStreamApi {\n const [status, setStatus] = useState<CameraStreamStatus>(\"loading\");\n const [error, setError] = useState<CameraStreamError | null>(null);\n const [retryToken, setRetryToken] = useState(0);\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const constraintsRef = useRef<MediaStreamConstraints>(\n options.constraints ?? DEFAULT_CONSTRAINTS,\n );\n constraintsRef.current = options.constraints ?? DEFAULT_CONSTRAINTS;\n\n useEffect(() => {\n let cancelled = false;\n let stream: MediaStream | null = null;\n let attachedVideo: HTMLVideoElement | null = null;\n\n async function start(): Promise<void> {\n setStatus(\"loading\");\n setError(null);\n\n if (\n typeof navigator === \"undefined\" ||\n !navigator.mediaDevices ||\n typeof navigator.mediaDevices.getUserMedia !== \"function\"\n ) {\n if (!cancelled) {\n setError(\n typeof window !== \"undefined\" && !window.isSecureContext\n ? classifyError(null)\n : {\n kind: \"unsupported\",\n message: \"Camera capture is not supported in this browser.\",\n },\n );\n setStatus(\"error\");\n }\n return;\n }\n\n try {\n stream = await navigator.mediaDevices.getUserMedia(constraintsRef.current);\n if (cancelled) {\n stream.getTracks().forEach((track) => track.stop());\n return;\n }\n const video = videoRef.current;\n if (!video) {\n stream.getTracks().forEach((track) => track.stop());\n return;\n }\n attachedVideo = video;\n video.srcObject = stream;\n await video.play().catch(() => undefined);\n if (!cancelled) setStatus(\"ready\");\n } catch (err) {\n if (!cancelled) {\n setError(classifyError(err));\n setStatus(\"error\");\n }\n }\n }\n\n void start();\n\n return () => {\n cancelled = true;\n if (stream) {\n stream.getTracks().forEach((track) => track.stop());\n }\n if (attachedVideo) {\n attachedVideo.srcObject = null;\n }\n };\n }, [retryToken]);\n\n return {\n status,\n error,\n videoRef,\n retry: () => setRetryToken((n) => n + 1),\n };\n}\n","/**\n * Frame-brightness helpers — measure the mean luminance of an already-decoded\n * `<img>`, `<video>` or `<canvas>` so a UI can reject underexposed captures\n * before paying the cost of downstream inference.\n *\n * These are framework-agnostic pure functions; {@link useLiveLuminance} wires\n * {@link computeImageLuminance} into a React `requestAnimationFrame` loop for\n * live camera feedback.\n */\n\n/**\n * Longest edge (in pixels) the source is downsampled to before sampling.\n * Averaging over a small downsample is statistically equivalent for a\n * brightness threshold and orders of magnitude faster than reading every pixel\n * of a full-resolution camera frame.\n */\nexport const LUMINANCE_SAMPLE_MAX_EDGE = 256;\n\n/** Drawable source we can sample luminance from — image, video, or canvas. */\nexport type LuminanceSource = HTMLImageElement | HTMLVideoElement | HTMLCanvasElement;\n\n/** Natural pixel size of the source (`0`/`0` while it is still unloaded). */\nfunction sourceSize(source: LuminanceSource): { width: number; height: number } {\n if (source instanceof HTMLVideoElement) {\n return { width: source.videoWidth, height: source.videoHeight };\n }\n if (source instanceof HTMLCanvasElement) {\n return { width: source.width, height: source.height };\n }\n return {\n width: source.naturalWidth || source.width,\n height: source.naturalHeight || source.height,\n };\n}\n\n/**\n * Mean BT.709 luminance (`0.2126*R + 0.7152*G + 0.0722*B`) of a decoded\n * `<img>`, `<video>` or `<canvas>`, scaled to `0..255`.\n *\n * The source is downsampled so its longest edge is at most\n * {@link LUMINANCE_SAMPLE_MAX_EDGE} before pixels are read. The 2D context is\n * created with `willReadFrequently` so repeated sampling (live feedback) stays\n * on the fast path.\n *\n * Pass `reusableCanvas` to avoid allocating a fresh canvas every frame in a hot\n * loop; when omitted a one-shot detached canvas is created.\n *\n * @param source - the image/video/canvas to sample.\n * @param reusableCanvas - optional canvas reused across frames to avoid GC churn.\n * @returns The mean luminance in `0..255`, or `0` when the source is unloaded\n * (zero-sized) or a 2D context is unavailable.\n */\nexport function computeImageLuminance(\n source: LuminanceSource,\n reusableCanvas?: HTMLCanvasElement,\n): number {\n const { width: srcW, height: srcH } = sourceSize(source);\n if (srcW === 0 || srcH === 0) return 0;\n\n const scale = Math.min(1, LUMINANCE_SAMPLE_MAX_EDGE / Math.max(srcW, srcH));\n const w = Math.max(1, Math.round(srcW * scale));\n const h = Math.max(1, Math.round(srcH * scale));\n\n const canvas = reusableCanvas ?? document.createElement(\"canvas\");\n canvas.width = w;\n canvas.height = h;\n const ctx = canvas.getContext(\"2d\", { willReadFrequently: true });\n if (!ctx) return 0;\n ctx.drawImage(source, 0, 0, w, h);\n\n const data = ctx.getImageData(0, 0, w, h).data;\n let sum = 0;\n const pixelCount = w * h;\n for (let i = 0; i < data.length; i += 4) {\n sum += 0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2];\n }\n return sum / pixelCount;\n}\n\n/**\n * Whether a measured luminance clears a brightness threshold.\n *\n * `threshold` is intentionally required — a sensible value is\n * application-specific (it depends on the model, the lighting the model was\n * trained on, and the acceptable false-reject rate), so the SDK does not bake\n * in a default.\n *\n * @param luminance - measured mean luminance in `0..255`.\n * @param threshold - minimum acceptable luminance in `0..255`.\n * @returns `true` when `luminance >= threshold`.\n */\nexport function isLuminanceAcceptable(luminance: number, threshold: number): boolean {\n return luminance >= threshold;\n}\n\n/**\n * Error raised when a captured frame is too dark to be analysed reliably.\n * Carries the measured luminance and the threshold it failed so callers can\n * surface actionable feedback.\n */\nexport class LowLuminanceError extends Error {\n /** Measured mean luminance, `0..255`. */\n readonly luminance: number;\n /** Threshold that was checked against, `0..255`. */\n readonly threshold: number;\n\n /**\n * @param luminance - the measured mean luminance in `0..255`.\n * @param threshold - the threshold the measurement failed to reach.\n */\n constructor(luminance: number, threshold: number) {\n super(\"Image is too dark to analyse. Capture again in a brighter environment.\");\n this.name = \"LowLuminanceError\";\n this.luminance = luminance;\n this.threshold = threshold;\n }\n}\n","import { useEffect, useRef, useState, type RefObject } from \"react\";\nimport { computeImageLuminance } from \"./luminance\";\n\n/** Options for {@link useLiveLuminance}. */\nexport interface UseLiveLuminanceOptions {\n /** When `false` the loop is paused (e.g. while a capture is in flight). Default: `true`. */\n enabled?: boolean;\n /** Throttle measurements in milliseconds. Default: `160` (~6 fps), plenty for UX. */\n intervalMs?: number;\n}\n\n/**\n * Sample mean luminance from a `<video>` source on a `requestAnimationFrame`\n * loop and expose the rolling value. Sampling is throttled by `intervalMs` and\n * paused whenever `enabled` is `false` or the video is not ready yet\n * (`readyState < 2` or `videoWidth === 0`).\n *\n * One offscreen canvas is reused across frames to avoid GC pressure. Designed\n * to feed a live brightness bar / border color on a camera page.\n *\n * @param videoRef - ref to the `<video>` element to sample.\n * @param options - optional configuration (see {@link UseLiveLuminanceOptions}).\n * @returns The rolling mean luminance in `0..255` (`0` until the first sample).\n */\nexport function useLiveLuminance(\n videoRef: RefObject<HTMLVideoElement | null>,\n { enabled = true, intervalMs = 160 }: UseLiveLuminanceOptions = {},\n): number {\n const [luminance, setLuminance] = useState(0);\n const canvasRef = useRef<HTMLCanvasElement | null>(null);\n\n useEffect(() => {\n if (!enabled) return;\n if (typeof window === \"undefined\") return;\n if (!canvasRef.current) canvasRef.current = document.createElement(\"canvas\");\n\n let rafId = 0;\n let lastSampledAt = 0;\n\n const tick = (timestamp: number): void => {\n const video = videoRef.current;\n if (!video || video.readyState < 2 || video.videoWidth === 0) {\n rafId = window.requestAnimationFrame(tick);\n return;\n }\n if (timestamp - lastSampledAt >= intervalMs) {\n lastSampledAt = timestamp;\n setLuminance(computeImageLuminance(video, canvasRef.current ?? undefined));\n }\n rafId = window.requestAnimationFrame(tick);\n };\n\n rafId = window.requestAnimationFrame(tick);\n return () => window.cancelAnimationFrame(rafId);\n }, [videoRef, enabled, intervalMs]);\n\n return luminance;\n}\n"],"names":["OrtVisionError","message","options","ModelLoadError","InferenceError","ProviderNotAvailableError","ImageLoadError","LabelMapError","RGBImage","data","width","height","BoundingBox","x1","y1","x2","y2","origShape","h","w","cx","cy","bw","bh","Mask","Boxes","xyxy","cls","conf","out","i","xywh","Probs","best","bestVal","v","k","n","order","b","indices","values","Masks","DetectionResults","boxes","detections","names","origImg","path","speed","index","ClassificationResults","probs","result","SegmentationResults","masks","COCO_CLASSES","PRESETS","resolveLabels","spec","labels","resolve","numClasses","_","preset","map","ids","maxId","DEFAULT_PROVIDERS","resolveProviders","requested","OrtSession","_session","providers","model","sessionOptions","session","ortRuntime","err","name","feeds","createCanvas","c","get2DContext","canvas","ctx","imageDataToRGB","imageData","rgb","j","rgbToImageData","image","loadImage","source","loadFromUrl","loadFromBlob","waitForImageElement","drawableToRGB","url","response","blob","bitmap","img","reject","onLoad","cleanup","onError","drawable","resize","targetWidth","targetHeight","srcCanvas","dstCanvas","dstCtx","normalize","mean","std","scale","m0","m1","m2","s0","s1","s2","toFloat32","toCHW","hwc","channels","expected","chw","plane","y","x","hwcBase","planeIdx","toFloat32Tensor","dims","toTensor","f32","fromCv2","bgr","toCv2","letterbox","fill","newW","newH","resized","f0","f1","f2","padLeft","padTop","rowBytes","srcOffset","dstOffset","softmax","logits","max","sum","e","topK","probabilities","kEff","idx","a","nms","scores","iouThreshold","areas","suppressed","keep","oi","ax1","ay1","ax2","ay2","ai","oj","bx1","by1","bx2","by2","ix1","iy1","ix2","iy2","iw","ih","inter","union","batchedNms","idxs","byClass","list","m","subBoxes","subScores","subKeep","decodeYoloAnchors","normalized","numAnchors","originalWidth","originalHeight","confThreshold","maxDetections","candidates","bestCls","bestScore","s","emptyDecoded","flatBoxes","scoresArr","idxsArr","kept","limited","anchorIndices","boxesXyxy","classIds","confidences","decodeYolo","output","outputDims","decoded","results","_warnedDecodeYoloV8","_warnedDecodeYoloV8Anchors","decodeYoloV8","decodeYoloV8Anchors","decodeYoloSeg","perAnchorData","perAnchorDims","prototypeData","prototypeDims","pDims","numMaskCoefs","maskH","maskW","expectedChannels","maskThreshold","scaleX","scaleY","protoPlane","coefBase","bbox","classId","confidence","bboxW","bboxH","ibx1","iby1","ibx2","iby2","mbx1","mby1","mbx2","mby2","cropW","cropH","softCrop","py","px","kk","coef","proto","sigmoid","resizeBilinear","binary","_warnedDecodeYoloV8Seg","decodeYoloV8Seg","src","srcWidth","srcHeight","sx","sy","yy","y0","wy","xx","x0","wx","v00","v01","v10","v11","top","bot","VisionTask","IMAGENET_MEAN","IMAGENET_STD","Classifier","_labels","_names","_inputSize","_mean","_std","_applySoftmax","original","tensor","outputs","firstOutputName","raw","fullProbs","id","className","orig","tw","th","Detector","_head","_confThreshold","_iouThreshold","_maxDetections","head","decodedAll","allowed","d","lb","cx1","cy1","cx2","cy2","cropped","cw","ch","row","Segmenter","_maskThreshold","perAnchor","prototypes","t","shapes","mask","segmentedImage","finalMask","mw","mh","segData","srcRowOffset","dstRowOffset","maskRowOffset","col","trimmed","VERSION","DEFAULT_CONSTRAINTS","classifyError","useCameraStream","status","setStatus","useState","error","setError","retryToken","setRetryToken","videoRef","useRef","constraintsRef","useEffect","cancelled","stream","attachedVideo","start","track","video","LUMINANCE_SAMPLE_MAX_EDGE","sourceSize","computeImageLuminance","reusableCanvas","srcW","srcH","pixelCount","isLuminanceAcceptable","luminance","threshold","LowLuminanceError","useLiveLuminance","enabled","intervalMs","setLuminance","canvasRef","rafId","lastSampledAt","tick","timestamp"],"mappings":"oaAOO,MAAMA,UAAuB,KAAM,CACtC,YAAYC,EAAiBC,EAAwB,CACjD,MAAMD,EAASC,CAAO,EACtB,KAAK,KAAO,WAAW,IAC3B,CACJ,CAGO,MAAMC,WAAuBH,CAAe,CAAC,CAG7C,MAAMI,WAAuBJ,CAAe,CAAC,CAG7C,MAAMK,WAAkCL,CAAe,CAAC,CAGxD,MAAMM,UAAuBN,CAAe,CAAC,CAG7C,MAAMO,UAAsBP,CAAe,CAAC,CCN5C,MAAMQ,CAAS,CAClB,YACoBC,EACAC,EACAC,EAClB,CACE,GAJgB,KAAA,KAAAF,EACA,KAAA,MAAAC,EACA,KAAA,OAAAC,EAEZF,EAAK,SAAWC,EAAQC,EAAS,EACjC,MAAM,IAAIL,EACN,wBAAwBG,EAAK,MAAM,wCAC/BC,EAAQC,EAAS,CACrB,GAAA,CAGZ,CAXoB,KACA,MACA,MAUxB,CASO,MAAMC,EAAY,CACrB,YACoBC,EACAC,EACA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A,UAAA9B,EACA,KAAA,KAAA+B,EACA,KAAA,MAAAC,CACjB,CAPiB,MACA,OACA,MACA,QACA,UACA,KACA,MAIpB,IAAI,KAAc,CACd,OAAO,KAAK,MAAM,IACtB,CAGA,IAAI,MAAe,CACf,OAAO,KAAK,MAAM,QACtB,CAGA,IAAI,MAAe,CACf,OAAO,KAAK,MAAM,KAAK,GAAG,GAAK,SAAS,KAAK,GAAG,EACpD,CAGA,IAAI,eAA0E,CAC1E,OAAO,KAAK,OAAO,aACvB,CACJ,CAQO,MAAMK,EAA4D,CACrE,YACoBV,EACAW,EACAV,EACAC,EACAC,EACA9B,EACA+B,EAAsB,KACtBC,EAA0C,CAAA,EAC5D,CARkB,KAAA,MAAAL,EACA,KAAA,MAAAW,EACA,KAAA,WAAAV,EACA,KAAA,MAAAC,EACA,KAAA,QAAAC,EACA,KAAA,UAAA9B,EACA,KAAA,KAAA+B,EACA,KAAA,MAAAC,CACjB,CARiB,MACA,MACA,WACA,MACA,QACA,UACA,KACA,MAIpB,IAAI,QAAiB,CACjB,OAAO,KAAK,WAAW,MAC3B,CAGA,IAAIC,EAA+C,CAC/C,OAAO,KAAK,WAAWA,CAAK,CAChC,CAEA,CAAC,OAAO,QAAQ,GAAkC,CAC9C,OAAO,KAAK,WAAW,OAAO,QAAQ,EAAA,CAC1C,CACJ,CCjTO,MAAMM,GAAkC,OAAO,OAAO,CACzD,SACA,UACA,MACA,aACA,WACA,MACA,QACA,QACA,OACA,gBACA,eACA,YACA,gBACA,QACA,OACA,MACA,MACA,QACA,QACA,MACA,WACA,OACA,QACA,UACA,WACA,WACA,UACA,MACA,WACA,UACA,OACA,YACA,cACA,OACA,eACA,iBACA,aACA,YACA,gBACA,SACA,aACA,MACA,OACA,QACA,QACA,OACA,SACA,QACA,WACA,SACA,WACA,SACA,UACA,QACA,QACA,OACA,QACA,QACA,eACA,MACA,eACA,SACA,KACA,SACA,QACA,SACA,WACA,aACA,YACA,OACA,UACA,OACA,eACA,OACA,QACA,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