tempest-react-sdk 0.69.0 → 0.70.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.
Files changed (77) hide show
  1. package/README.md +1 -1
  2. package/dist/vision/core/canvas.cjs +1 -1
  3. package/dist/vision/core/canvas.cjs.map +1 -1
  4. package/dist/vision/core/canvas.js +37 -13
  5. package/dist/vision/core/canvas.js.map +1 -1
  6. package/dist/vision/core/dtypes.cjs +2 -0
  7. package/dist/vision/core/dtypes.cjs.map +1 -0
  8. package/dist/vision/core/dtypes.js +33 -0
  9. package/dist/vision/core/dtypes.js.map +1 -0
  10. package/dist/vision/core/graph.cjs +1 -1
  11. package/dist/vision/core/graph.cjs.map +1 -1
  12. package/dist/vision/core/graph.js +10 -2
  13. package/dist/vision/core/graph.js.map +1 -1
  14. package/dist/vision/core/metadata.cjs +2 -2
  15. package/dist/vision/core/metadata.cjs.map +1 -1
  16. package/dist/vision/core/metadata.js +103 -13
  17. package/dist/vision/core/metadata.js.map +1 -1
  18. package/dist/vision/core/providers.cjs +1 -1
  19. package/dist/vision/core/providers.cjs.map +1 -1
  20. package/dist/vision/core/providers.js +9 -6
  21. package/dist/vision/core/providers.js.map +1 -1
  22. package/dist/vision/core/session.cjs +1 -1
  23. package/dist/vision/core/session.cjs.map +1 -1
  24. package/dist/vision/core/session.js +115 -27
  25. package/dist/vision/core/session.js.map +1 -1
  26. package/dist/vision/fusion.cjs +1 -1
  27. package/dist/vision/fusion.cjs.map +1 -1
  28. package/dist/vision/fusion.js +28 -23
  29. package/dist/vision/fusion.js.map +1 -1
  30. package/dist/vision/index.cjs +1 -1
  31. package/dist/vision/index.cjs.map +1 -1
  32. package/dist/vision/index.js +20 -19
  33. package/dist/vision/index.js.map +1 -1
  34. package/dist/vision/io/image.cjs +1 -1
  35. package/dist/vision/io/image.cjs.map +1 -1
  36. package/dist/vision/io/image.js +55 -20
  37. package/dist/vision/io/image.js.map +1 -1
  38. package/dist/vision/postprocess/detection.cjs +1 -1
  39. package/dist/vision/postprocess/detection.cjs.map +1 -1
  40. package/dist/vision/postprocess/detection.js +42 -51
  41. package/dist/vision/postprocess/detection.js.map +1 -1
  42. package/dist/vision/postprocess/segmentation.cjs +1 -1
  43. package/dist/vision/postprocess/segmentation.cjs.map +1 -1
  44. package/dist/vision/postprocess/segmentation.js +45 -31
  45. package/dist/vision/postprocess/segmentation.js.map +1 -1
  46. package/dist/vision/preprocess/pipeline.cjs +1 -1
  47. package/dist/vision/preprocess/pipeline.cjs.map +1 -1
  48. package/dist/vision/preprocess/pipeline.js +24 -25
  49. package/dist/vision/preprocess/pipeline.js.map +1 -1
  50. package/dist/vision/tasks/base.cjs +1 -1
  51. package/dist/vision/tasks/base.cjs.map +1 -1
  52. package/dist/vision/tasks/base.js +22 -7
  53. package/dist/vision/tasks/base.js.map +1 -1
  54. package/dist/vision/tasks/classifier.cjs +1 -1
  55. package/dist/vision/tasks/classifier.cjs.map +1 -1
  56. package/dist/vision/tasks/classifier.js +64 -55
  57. package/dist/vision/tasks/classifier.js.map +1 -1
  58. package/dist/vision/tasks/detectClassify.cjs +1 -1
  59. package/dist/vision/tasks/detectClassify.cjs.map +1 -1
  60. package/dist/vision/tasks/detectClassify.js +80 -69
  61. package/dist/vision/tasks/detectClassify.js.map +1 -1
  62. package/dist/vision/tasks/detector.cjs +1 -1
  63. package/dist/vision/tasks/detector.cjs.map +1 -1
  64. package/dist/vision/tasks/detector.js +74 -68
  65. package/dist/vision/tasks/detector.js.map +1 -1
  66. package/dist/vision/tasks/segmenter.cjs +1 -1
  67. package/dist/vision/tasks/segmenter.cjs.map +1 -1
  68. package/dist/vision/tasks/segmenter.js +85 -62
  69. package/dist/vision/tasks/segmenter.js.map +1 -1
  70. package/dist/vision/types.cjs +1 -1
  71. package/dist/vision/types.cjs.map +1 -1
  72. package/dist/vision/types.js +24 -4
  73. package/dist/vision/types.js.map +1 -1
  74. package/dist/vision.cjs +1 -1
  75. package/dist/vision.d.ts +1153 -777
  76. package/dist/vision.js +22 -21
  77. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"metadata.js","names":[],"sources":["../../../src/vision/core/metadata.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Read the metadata an exporter baked into a `.onnx` file.\n *\n * `onnxruntime-web` exposes input/output metadata but **not** the model's\n * custom metadata map, which is where Ultralytics writes `names`, `task` and\n * `imgsz`. The Python SDK gets it for free from\n * `InferenceSession.get_modelmeta().custom_metadata_map`; in the browser the\n * only way to the same information is to read it out of the file, so this\n * module walks just enough of the ModelProto wire format to collect\n * `metadata_props`.\n *\n * It never throws and never allocates unbounded: a truncated, hostile or\n * simply unexpected file yields an empty map, and every caller treats that as\n * \"the model says nothing\", falling back to what it was given.\n */\n\n/** Field number of `metadata_props` in `ModelProto` (repeated StringStringEntryProto). */\nconst MODEL_METADATA_PROPS_FIELD = 14;\n\n/** Field numbers of `key` and `value` in `StringStringEntryProto`. */\nconst ENTRY_KEY_FIELD = 1;\nconst ENTRY_VALUE_FIELD = 2;\n\n/** Protobuf wire types this reader understands. */\nconst WIRE_VARINT = 0;\nconst WIRE_FIXED64 = 1;\nconst WIRE_LENGTH_DELIMITED = 2;\nconst WIRE_FIXED32 = 5;\n\n/**\n * Hard ceiling on a single length-delimited field, as a guard against a corrupt\n * length turning into a huge slice. Model metadata values are strings — a class\n * name map for thousands of classes still fits well inside this.\n */\nconst MAX_FIELD_BYTES = 1 << 20;\n\n/** A cursor over a byte range, tracking its own position. */\ninterface Cursor {\n readonly bytes: Uint8Array;\n readonly end: number;\n pos: number;\n}\n\n/**\n * Read a base-128 varint.\n *\n * @param cursor Cursor to advance.\n * @returns The value, or `null` when the varint is truncated or overlong\n * (beyond the 64-bit range protobuf allows).\n */\nfunction readVarint(cursor: Cursor): number | null {\n let result = 0;\n let shift = 0;\n while (cursor.pos < cursor.end) {\n const byte = cursor.bytes[cursor.pos]!;\n cursor.pos += 1;\n result += (byte & 0x7f) * 2 ** shift;\n if ((byte & 0x80) === 0) return result;\n shift += 7;\n if (shift > 63) return null;\n }\n return null;\n}\n\n/**\n * Skip a field whose contents are not needed.\n *\n * @param cursor Cursor to advance past the field's payload.\n * @param wireType Wire type read from the field's tag.\n * @returns `true` when the field was skipped, `false` when the stream is\n * unreadable from here (unknown wire type or truncated payload).\n */\nfunction skipField(cursor: Cursor, wireType: number): boolean {\n switch (wireType) {\n case WIRE_VARINT:\n return readVarint(cursor) !== null;\n case WIRE_FIXED64:\n cursor.pos += 8;\n return cursor.pos <= cursor.end;\n case WIRE_LENGTH_DELIMITED: {\n const length = readVarint(cursor);\n if (length === null) return false;\n cursor.pos += length;\n return cursor.pos <= cursor.end;\n }\n case WIRE_FIXED32:\n cursor.pos += 4;\n return cursor.pos <= cursor.end;\n default:\n return false;\n }\n}\n\n/**\n * Read a length-delimited payload as a byte range.\n *\n * @param cursor Cursor to advance past the payload.\n * @returns Start and end offsets of the payload, or `null` when the length is\n * truncated, overruns the buffer, or exceeds {@link MAX_FIELD_BYTES}.\n */\nfunction readLengthDelimited(cursor: Cursor): { start: number; end: number } | null {\n const length = readVarint(cursor);\n if (length === null || length > MAX_FIELD_BYTES) return null;\n const start = cursor.pos;\n const end = start + length;\n if (end > cursor.end) return null;\n cursor.pos = end;\n return { start, end };\n}\n\n/**\n * Decode one `StringStringEntryProto` into a key/value pair.\n *\n * @param bytes The model buffer.\n * @param start Offset the entry's payload starts at.\n * @param end Offset the entry's payload ends at.\n * @returns The pair, or `null` when either half is missing or undecodable.\n */\nfunction readEntry(\n bytes: Uint8Array,\n start: number,\n end: number,\n): readonly [string, string] | null {\n const cursor: Cursor = { bytes, end, pos: start };\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n let key: string | null = null;\n let value: string | null = null;\n\n while (cursor.pos < end) {\n const tag = readVarint(cursor);\n if (tag === null) return null;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (\n wireType === WIRE_LENGTH_DELIMITED &&\n (field === ENTRY_KEY_FIELD || field === ENTRY_VALUE_FIELD)\n ) {\n const range = readLengthDelimited(cursor);\n if (range === null) return null;\n const text = decoder.decode(bytes.subarray(range.start, range.end));\n if (field === ENTRY_KEY_FIELD) key = text;\n else value = text;\n continue;\n }\n if (!skipField(cursor, wireType)) return null;\n }\n\n if (key === null || value === null) return null;\n return [key, value];\n}\n\n/**\n * Collect a model's custom metadata map straight out of its bytes.\n *\n * @param model The `.onnx` file contents.\n * @returns Key/value metadata — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export — or an empty object when the file carries none or\n * cannot be walked.\n */\nexport function readModelMetadata(\n model: Uint8Array | ArrayBufferLike,\n): Readonly<Record<string, string>> {\n const bytes = model instanceof Uint8Array ? model : new Uint8Array(model);\n const cursor: Cursor = { bytes, end: bytes.length, pos: 0 };\n const metadata: Record<string, string> = {};\n\n while (cursor.pos < cursor.end) {\n const tag = readVarint(cursor);\n if (tag === null) break;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (field === MODEL_METADATA_PROPS_FIELD && wireType === WIRE_LENGTH_DELIMITED) {\n const range = readLengthDelimited(cursor);\n if (range === null) break;\n const entry = readEntry(bytes, range.start, range.end);\n if (entry) metadata[entry[0]] = entry[1];\n continue;\n }\n if (!skipField(cursor, wireType)) break;\n }\n\n return metadata;\n}\n\n/**\n * Read the class names an export baked into the model metadata.\n *\n * Ultralytics writes `names` as the Python `repr` of a `dict[int, str]` — e.g.\n * `\"{0: 'deworm', 1: 'not_deworm'}\"`. The value is parsed structurally (never\n * evaluated), and anything unparseable, non-`dict`, or not keyed by contiguous\n * integers from zero is rejected whole rather than half-applied: a partial name\n * map would silently mislabel predictions.\n *\n * @param metadata A model's custom metadata map.\n * @returns Class names in class-id order, or `null` when the model carries no\n * usable `names` entry.\n */\nexport function modelNames(\n metadata: Readonly<Record<string, string>> | undefined,\n): readonly string[] | null {\n return parseNames(metadata?.names);\n}\n\n/**\n * Parse a `repr`-encoded `dict[int, str]` class map.\n *\n * Split out of {@link modelNames} because the same encoding is reused by a\n * fused pipeline, which carries one class map per stage and therefore cannot\n * store both under the single `names` key Ultralytics uses.\n *\n * @param encoded The encoded map — e.g. `\"{0: 'deworm', 1: 'not_deworm'}\"`.\n * @returns Class names in class-id order, or `null` when the value is missing,\n * unparseable, not a `dict`, or not keyed by contiguous integers from zero.\n */\nexport function parseNames(encoded: string | undefined): readonly string[] | null {\n const raw = encoded?.trim();\n if (!raw || !raw.startsWith(\"{\") || !raw.endsWith(\"}\")) return null;\n\n const body = raw.slice(1, -1).trim();\n if (!body) return null;\n\n const names = new Map<number, string>();\n const entryPattern = /(-?\\d+)\\s*:\\s*(?:'((?:[^'\\\\]|\\\\.)*)'|\"((?:[^\"\\\\]|\\\\.)*)\")/g;\n let consumed = 0;\n for (const match of body.matchAll(entryPattern)) {\n const id = Number(match[1]);\n const text = match[2] ?? match[3];\n if (!Number.isInteger(id) || text === undefined) return null;\n names.set(id, unescapeQuoted(text));\n consumed += match[0].length;\n }\n if (names.size === 0) return null;\n\n const separators = body.length - consumed;\n if (separators > names.size * 3) return null;\n\n const ordered: string[] = [];\n for (let id = 0; id < names.size; id += 1) {\n const name = names.get(id);\n if (name === undefined) return null;\n ordered.push(name);\n }\n return ordered;\n}\n\n/**\n * Resolve the backslash escapes Python's `repr` emits inside a quoted string.\n *\n * @param text The quoted string's contents, escapes intact.\n * @returns The same text with `\\\\`, `\\'`, `\\\"`, `\\n`, `\\r` and `\\t` resolved.\n */\nfunction unescapeQuoted(text: string): string {\n return text.replace(/\\\\(.)/g, (_, char: string) => {\n if (char === \"n\") return \"\\n\";\n if (char === \"r\") return \"\\r\";\n if (char === \"t\") return \"\\t\";\n return char;\n });\n}\n"],"mappings":"AAmDA,SAAS,EAAW,GAA+B;CAC/C,IAAI,IAAS,GACT,IAAQ;CACZ,OAAO,EAAO,MAAM,EAAO,MAAK;EAC5B,IAAM,IAAO,EAAO,MAAM,EAAO;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CAAE,KAAK,MAAS,KAAA,GAAW,OAAO;EAExD,AADA,EAAM,IAAI,GAAI,EAAe,CAAI,CAAC,GAClC,KAAY,EAAM,EAAE,CAAC;CACzB;CAIA,IAHI,EAAM,SAAS,KAEA,EAAK,SAAS,IAChB,EAAM,OAAO,GAAG,OAAO;CAExC,IAAM,IAAoB,CAAC;CAC3B,KAAK,IAAI,IAAK,GAAG,IAAK,EAAM,MAAM,KAAM,GAAG;EACvC,IAAM,IAAO,EAAM,IAAI,CAAE;EACzB,IAAI,MAAS,KAAA,GAAW,OAAO;EAC/B,EAAQ,KAAK,CAAI;CACrB;CACA,OAAO;AACX;AAQA,SAAS,EAAe,GAAsB;CAC1C,OAAO,EAAK,QAAQ,WAAW,GAAG,MAC1B,MAAS,MAAY,OACrB,MAAS,MAAY,OACrB,MAAS,MAAY,MAClB,CACV;AACL"}
1
+ {"version":3,"file":"metadata.js","names":[],"sources":["../../../src/vision/core/metadata.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Read the metadata an exporter baked into a `.onnx` file.\n *\n * `onnxruntime-web` exposes input/output metadata but **not** the model's\n * custom metadata map, which is where Ultralytics writes `names`, `task` and\n * `imgsz`. The Python SDK gets it for free from\n * `InferenceSession.get_modelmeta().custom_metadata_map`; in the browser the\n * only way to the same information is to read it out of the file, so this\n * module walks just enough of the ModelProto wire format to collect\n * `metadata_props`.\n *\n * It never throws and never allocates unbounded: a truncated, hostile or\n * simply unexpected file yields an empty map, and every caller treats that as\n * \"the model says nothing\", falling back to what it was given.\n */\n\n/** Field number of `metadata_props` in `ModelProto` (repeated StringStringEntryProto). */\nconst MODEL_METADATA_PROPS_FIELD = 14;\n\n/** Field number of `graph` in `ModelProto` (GraphProto). */\nconst MODEL_GRAPH_FIELD = 7;\n\n/** Field number of `input` in `GraphProto` (repeated ValueInfoProto). */\nconst GRAPH_INPUT_FIELD = 11;\n\n/** Field numbers of `name` and `type` in `ValueInfoProto`. */\nconst VALUE_INFO_NAME_FIELD = 1;\nconst VALUE_INFO_TYPE_FIELD = 2;\n\n/** Field number of `tensor_type` in `TypeProto` (TypeProto.Tensor). */\nconst TYPE_TENSOR_FIELD = 1;\n\n/** Field number of `elem_type` in `TypeProto.Tensor` (a `TensorProto.DataType`). */\nconst TENSOR_ELEM_TYPE_FIELD = 1;\n\n/** Field numbers of `key` and `value` in `StringStringEntryProto`. */\nconst ENTRY_KEY_FIELD = 1;\nconst ENTRY_VALUE_FIELD = 2;\n\n/** Protobuf wire types this reader understands. */\nconst WIRE_VARINT = 0;\nconst WIRE_FIXED64 = 1;\nconst WIRE_LENGTH_DELIMITED = 2;\nconst WIRE_FIXED32 = 5;\n\n/**\n * Hard ceiling on a single length-delimited field, as a guard against a corrupt\n * length turning into a huge slice. Model metadata values are strings — a class\n * name map for thousands of classes still fits well inside this.\n *\n * It applies to leaf fields being read *out* of the file, not to the messages\n * walked *through* to reach them. The `graph` of a real export is the file: 21.79\n * MB on a reported YOLO detector. Applying this ceiling there made the reader\n * give up on every model anyone would actually load, and give up silently.\n */\nconst MAX_FIELD_BYTES = 1 << 20;\n\n/** A cursor over a byte range, tracking its own position. */\ninterface Cursor {\n readonly bytes: Uint8Array;\n readonly end: number;\n pos: number;\n}\n\n/**\n * Read a base-128 varint.\n *\n * @param cursor Cursor to advance.\n * @returns The value, or `null` when the varint is truncated or overlong\n * (beyond the 64-bit range protobuf allows).\n */\nfunction readVarint(cursor: Cursor): number | null {\n let result = 0;\n let shift = 0;\n while (cursor.pos < cursor.end) {\n const byte = cursor.bytes[cursor.pos]!;\n cursor.pos += 1;\n result += (byte & 0x7f) * 2 ** shift;\n if ((byte & 0x80) === 0) return result;\n shift += 7;\n if (shift > 63) return null;\n }\n return null;\n}\n\n/**\n * Skip a field whose contents are not needed.\n *\n * @param cursor Cursor to advance past the field's payload.\n * @param wireType Wire type read from the field's tag.\n * @returns `true` when the field was skipped, `false` when the stream is\n * unreadable from here (unknown wire type or truncated payload).\n */\nfunction skipField(cursor: Cursor, wireType: number): boolean {\n switch (wireType) {\n case WIRE_VARINT:\n return readVarint(cursor) !== null;\n case WIRE_FIXED64:\n cursor.pos += 8;\n return cursor.pos <= cursor.end;\n case WIRE_LENGTH_DELIMITED: {\n const length = readVarint(cursor);\n if (length === null) return false;\n cursor.pos += length;\n return cursor.pos <= cursor.end;\n }\n case WIRE_FIXED32:\n cursor.pos += 4;\n return cursor.pos <= cursor.end;\n default:\n return false;\n }\n}\n\n/**\n * Read a length-delimited payload as a byte range.\n *\n * @param cursor Cursor to advance past the payload.\n * @param maxBytes Largest payload to accept, defaulting to\n * {@link MAX_FIELD_BYTES}. Pass the buffer length when descending into a\n * message whose size is the file's size rather than a leaf value's.\n * @returns Start and end offsets of the payload, or `null` when the length is\n * truncated, overruns the buffer, or exceeds `maxBytes`.\n */\nfunction readLengthDelimited(\n cursor: Cursor,\n maxBytes: number = MAX_FIELD_BYTES,\n): { start: number; end: number } | null {\n const length = readVarint(cursor);\n if (length === null || length > maxBytes) return null;\n const start = cursor.pos;\n const end = start + length;\n if (end > cursor.end) return null;\n cursor.pos = end;\n return { start, end };\n}\n\n/**\n * Decode one `StringStringEntryProto` into a key/value pair.\n *\n * @param bytes The model buffer.\n * @param start Offset the entry's payload starts at.\n * @param end Offset the entry's payload ends at.\n * @returns The pair, or `null` when either half is missing or undecodable.\n */\nfunction readEntry(\n bytes: Uint8Array,\n start: number,\n end: number,\n): readonly [string, string] | null {\n const cursor: Cursor = { bytes, end, pos: start };\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n let key: string | null = null;\n let value: string | null = null;\n\n while (cursor.pos < end) {\n const tag = readVarint(cursor);\n if (tag === null) return null;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (\n wireType === WIRE_LENGTH_DELIMITED &&\n (field === ENTRY_KEY_FIELD || field === ENTRY_VALUE_FIELD)\n ) {\n const range = readLengthDelimited(cursor);\n if (range === null) return null;\n const text = decoder.decode(bytes.subarray(range.start, range.end));\n if (field === ENTRY_KEY_FIELD) key = text;\n else value = text;\n continue;\n }\n if (!skipField(cursor, wireType)) return null;\n }\n\n if (key === null || value === null) return null;\n return [key, value];\n}\n\n/**\n * Collect a model's custom metadata map straight out of its bytes.\n *\n * @param model The `.onnx` file contents.\n * @returns Key/value metadata — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export — or an empty object when the file carries none or\n * cannot be walked.\n */\nexport function readModelMetadata(\n model: Uint8Array | ArrayBufferLike,\n): Readonly<Record<string, string>> {\n const bytes = model instanceof Uint8Array ? model : new Uint8Array(model);\n const cursor: Cursor = { bytes, end: bytes.length, pos: 0 };\n const metadata: Record<string, string> = {};\n\n while (cursor.pos < cursor.end) {\n const tag = readVarint(cursor);\n if (tag === null) break;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (field === MODEL_METADATA_PROPS_FIELD && wireType === WIRE_LENGTH_DELIMITED) {\n const range = readLengthDelimited(cursor);\n if (range === null) break;\n const entry = readEntry(bytes, range.start, range.end);\n if (entry) metadata[entry[0]] = entry[1];\n continue;\n }\n if (!skipField(cursor, wireType)) break;\n }\n\n return metadata;\n}\n\n/**\n * Read the element type of a `TypeProto.Tensor` message.\n *\n * @param bytes The whole model buffer.\n * @param start Offset of the message's first byte.\n * @param end Offset one past its last byte.\n * @returns The `TensorProto.DataType` value, or `null` when the message\n * carries none or cannot be walked.\n */\nfunction readTensorElemType(bytes: Uint8Array, start: number, end: number): number | null {\n const cursor: Cursor = { bytes, end, pos: start };\n while (cursor.pos < cursor.end) {\n const tag = readVarint(cursor);\n if (tag === null) return null;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (field === TENSOR_ELEM_TYPE_FIELD && wireType === WIRE_VARINT) {\n return readVarint(cursor);\n }\n if (!skipField(cursor, wireType)) return null;\n }\n return null;\n}\n\n/**\n * Read the element type out of a `TypeProto`, which wraps the tensor type.\n *\n * @param bytes The whole model buffer.\n * @param start Offset of the message's first byte.\n * @param end Offset one past its last byte.\n * @returns The `TensorProto.DataType` value, or `null` for a non-tensor type\n * (sequence, map, optional) or an unreadable message.\n */\nfunction readTypeElemType(bytes: Uint8Array, start: number, end: number): number | null {\n const cursor: Cursor = { bytes, end, pos: start };\n while (cursor.pos < cursor.end) {\n const tag = readVarint(cursor);\n if (tag === null) return null;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (field === TYPE_TENSOR_FIELD && wireType === WIRE_LENGTH_DELIMITED) {\n const range = readLengthDelimited(cursor);\n if (range === null) return null;\n return readTensorElemType(bytes, range.start, range.end);\n }\n if (!skipField(cursor, wireType)) return null;\n }\n return null;\n}\n\n/**\n * Read one `ValueInfoProto` into a name/element-type pair.\n *\n * @param bytes The whole model buffer.\n * @param start Offset of the message's first byte.\n * @param end Offset one past its last byte.\n * @returns The pair, or `null` when either half is missing or unreadable.\n */\nfunction readValueInfo(\n bytes: Uint8Array,\n start: number,\n end: number,\n): readonly [string, number] | null {\n const cursor: Cursor = { bytes, end, pos: start };\n let name: string | null = null;\n let elemType: number | null = null;\n while (cursor.pos < cursor.end) {\n const tag = readVarint(cursor);\n if (tag === null) return null;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (wireType === WIRE_LENGTH_DELIMITED) {\n const range = readLengthDelimited(cursor);\n if (range === null) return null;\n if (field === VALUE_INFO_NAME_FIELD) {\n name = new TextDecoder(\"utf-8\", { fatal: false }).decode(\n bytes.subarray(range.start, range.end),\n );\n } else if (field === VALUE_INFO_TYPE_FIELD) {\n elemType = readTypeElemType(bytes, range.start, range.end);\n }\n continue;\n }\n if (!skipField(cursor, wireType)) return null;\n }\n if (name === null || elemType === null) return null;\n return [name, elemType];\n}\n\n/**\n * Read the element type each graph input declares.\n *\n * `onnxruntime-web` does not expose this. `session.inputMetadata` is\n * `undefined` on 1.20.1 — the same version where `declaredShapesFrom` comes\n * back empty — so the declared types have to come from the file, which the SDK\n * already downloads and walks for {@link readModelMetadata}. Same bytes, one\n * more pass, no extra request.\n *\n * @param model The `.onnx` file contents.\n * @returns Input name → `TensorProto.DataType` value. An empty object when the\n * file carries no readable graph, which every caller treats as \"assume\n * float32\" — the behaviour before any of this existed.\n */\nexport function readModelInputTypes(\n model: Uint8Array | ArrayBufferLike,\n): Readonly<Record<string, number>> {\n const bytes = model instanceof Uint8Array ? model : new Uint8Array(model);\n const cursor: Cursor = { bytes, end: bytes.length, pos: 0 };\n const types: Record<string, number> = {};\n\n while (cursor.pos < cursor.end) {\n const tag = readVarint(cursor);\n if (tag === null) break;\n const field = tag >>> 3;\n const wireType = tag & 0x07;\n if (field === MODEL_GRAPH_FIELD && wireType === WIRE_LENGTH_DELIMITED) {\n const graph = readLengthDelimited(cursor, bytes.length);\n if (graph === null) break;\n const inner: Cursor = { bytes, end: graph.end, pos: graph.start };\n while (inner.pos < inner.end) {\n const innerTag = readVarint(inner);\n if (innerTag === null) break;\n const innerField = innerTag >>> 3;\n const innerWire = innerTag & 0x07;\n if (innerField === GRAPH_INPUT_FIELD && innerWire === WIRE_LENGTH_DELIMITED) {\n const range = readLengthDelimited(inner);\n if (range === null) break;\n const info = readValueInfo(bytes, range.start, range.end);\n if (info) types[info[0]] = info[1];\n continue;\n }\n if (!skipField(inner, innerWire)) break;\n }\n continue;\n }\n if (!skipField(cursor, wireType)) break;\n }\n\n return types;\n}\n\n/**\n * Read the class names an export baked into the model metadata.\n *\n * Ultralytics writes `names` as the Python `repr` of a `dict[int, str]` — e.g.\n * `\"{0: 'deworm', 1: 'not_deworm'}\"`. The value is parsed structurally (never\n * evaluated), and anything unparseable, non-`dict`, or not keyed by contiguous\n * integers from zero is rejected whole rather than half-applied: a partial name\n * map would silently mislabel predictions.\n *\n * @param metadata A model's custom metadata map.\n * @returns Class names in class-id order, or `null` when the model carries no\n * usable `names` entry.\n */\nexport function modelNames(\n metadata: Readonly<Record<string, string>> | undefined,\n): readonly string[] | null {\n return parseNames(metadata?.names);\n}\n\n/**\n * Parse a `repr`-encoded `dict[int, str]` class map.\n *\n * Split out of {@link modelNames} because the same encoding is reused by a\n * fused pipeline, which carries one class map per stage and therefore cannot\n * store both under the single `names` key Ultralytics uses.\n *\n * @param encoded The encoded map — e.g. `\"{0: 'deworm', 1: 'not_deworm'}\"`.\n * @returns Class names in class-id order, or `null` when the value is missing,\n * unparseable, not a `dict`, or not keyed by contiguous integers from zero.\n */\nexport function parseNames(encoded: string | undefined): readonly string[] | null {\n const raw = encoded?.trim();\n if (!raw || !raw.startsWith(\"{\") || !raw.endsWith(\"}\")) return null;\n\n const body = raw.slice(1, -1).trim();\n if (!body) return null;\n\n const names = new Map<number, string>();\n const entryPattern = /(-?\\d+)\\s*:\\s*(?:'((?:[^'\\\\]|\\\\.)*)'|\"((?:[^\"\\\\]|\\\\.)*)\")/g;\n let consumed = 0;\n for (const match of body.matchAll(entryPattern)) {\n const id = Number(match[1]);\n const text = match[2] ?? match[3];\n if (!Number.isInteger(id) || text === undefined) return null;\n names.set(id, unescapeQuoted(text));\n consumed += match[0].length;\n }\n if (names.size === 0) return null;\n\n const separators = body.length - consumed;\n if (separators > names.size * 3) return null;\n\n const ordered: string[] = [];\n for (let id = 0; id < names.size; id += 1) {\n const name = names.get(id);\n if (name === undefined) return null;\n ordered.push(name);\n }\n return ordered;\n}\n\n/**\n * Resolve the backslash escapes Python's `repr` emits inside a quoted string.\n *\n * @param text The quoted string's contents, escapes intact.\n * @returns The same text with `\\\\`, `\\'`, `\\\"`, `\\n`, `\\r` and `\\t` resolved.\n */\nfunction unescapeQuoted(text: string): string {\n return text.replace(/\\\\(.)/g, (_, char: string) => {\n if (char === \"n\") return \"\\n\";\n if (char === \"r\") return \"\\r\";\n if (char === \"t\") return \"\\t\";\n return char;\n });\n}\n"],"mappings":"AAwEA,SAAS,EAAW,GAA+B;CAC/C,IAAI,IAAS,GACT,IAAQ;CACZ,OAAO,EAAO,MAAM,EAAO,MAAK;EAC5B,IAAM,IAAO,EAAO,MAAM,EAAO;EAGjC,IAFA,EAAO,OA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M,IAAI,GAAI,EAAe,CAAI,CAAC,GAClC,KAAY,EAAM,EAAE,CAAC;CACzB;CAIA,IAHI,EAAM,SAAS,KAEA,EAAK,SAAS,IAChB,EAAM,OAAO,GAAG,OAAO;CAExC,IAAM,IAAoB,CAAC;CAC3B,KAAK,IAAI,IAAK,GAAG,IAAK,EAAM,MAAM,KAAM,GAAG;EACvC,IAAM,IAAO,EAAM,IAAI,CAAE;EACzB,IAAI,MAAS,KAAA,GAAW,OAAO;EAC/B,EAAQ,KAAK,CAAI;CACrB;CACA,OAAO;AACX;AAQA,SAAS,EAAe,GAAsB;CAC1C,OAAO,EAAK,QAAQ,WAAW,GAAG,MAC1B,MAAS,MAAY,OACrB,MAAS,MAAY,OACrB,MAAS,MAAY,MAClB,CACV;AACL"}
@@ -1,2 +1,2 @@
1
- var e=[`webgpu`,`wasm`],t=`wasm`;function n(t){return t===void 0||t.length===0?[...e]:[...t]}async function r(e){let t=await i();return e.filter(e=>{switch(e){case`webgpu`:return t;case`webnn`:return typeof navigator<`u`&&`ml`in navigator;default:return!0}})}async function i(){let e=globalThis.navigator?.gpu;if(e===void 0)return!1;try{return await e.requestAdapter()!==null}catch{return!1}}exports.DEFAULT_PROVIDERS=e,exports.FALLBACK_PROVIDER=t,exports.detectProviders=r,exports.resolveProviders=n;
1
+ var e=[`webgpu`,`wasm`],t=`wasm`;function n(e){return typeof e==`string`?e:e.name}function r(t){return t===void 0||t.length===0?[...e]:[...t]}async function i(e){let t=e.some(e=>n(e)===`webgpu`)?await a():!1;return e.filter(e=>{switch(n(e)){case`webgpu`:return t;case`webnn`:return typeof navigator<`u`&&`ml`in navigator;default:return!0}})}async function a(){let e=globalThis.navigator?.gpu;if(e===void 0)return!1;try{return await e.requestAdapter()!==null}catch{return!1}}exports.DEFAULT_PROVIDERS=e,exports.FALLBACK_PROVIDER=t,exports.detectProviders=i,exports.providerName=n,exports.resolveProviders=r;
2
2
  //# sourceMappingURL=providers.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"providers.cjs","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * The provider ORT-Web can always run, whatever the device.\n *\n * Used as the floor when capability detection rules everything else out. Passing\n * ORT a list it cannot satisfy is not a graceful failure — `InferenceSession.create`\n * rejects with \"no available backend found\" and the page gets no inference at\n * all, which is worse than the slow-but-working fallback the warning describes.\n */\nexport const FALLBACK_PROVIDER = \"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/**\n * Narrow a provider list to the ones this browser can actually offer.\n *\n * ORT-Web exposes no equivalent of Node's `session.getProviders()`, so there is\n * no way to ask which provider a session ended up on. What the browser *does*\n * answer is whether the underlying API exists at all — no `navigator.gpu`, or no\n * adapter behind it, means `webgpu` was never going to run — and that covers the\n * case that actually bites: a page asking for WebGPU on a device without it,\n * silently getting WASM, and being several times slower than intended with no\n * error to point at.\n *\n * This is best-effort by construction. A provider that survives here can still\n * fail inside ORT for a reason the browser does not surface (a missing shader\n * feature, an exhausted device), so a surviving entry means \"not ruled out\",\n * not \"confirmed running\". Anything this function does not know how to test is\n * kept rather than dropped: guessing a provider away would be worse than\n * admitting ignorance about it.\n *\n * @param requested Providers in preference order, already resolved.\n * @returns The subset that is not ruled out, in the same order.\n */\nexport async function detectProviders(requested: readonly string[]): Promise<string[]> {\n const webgpu = await hasWebGpuAdapter();\n return requested.filter((provider) => {\n switch (provider) {\n case \"webgpu\":\n return webgpu;\n case \"webnn\":\n return typeof navigator !== \"undefined\" && \"ml\" in navigator;\n default:\n return true;\n }\n });\n}\n\n/**\n * Whether this environment exposes a WebGPU adapter.\n *\n * `navigator.gpu` existing is not enough — a browser can ship the API and still\n * hand back no adapter (a blocklisted driver, a headless context, a machine with\n * no suitable GPU), which is exactly the configuration where a page asks for\n * WebGPU and quietly runs on WASM.\n */\nasync function hasWebGpuAdapter(): Promise<boolean> {\n const gpu = (\n globalThis.navigator as { gpu?: { requestAdapter(): Promise<unknown> } } | undefined\n )?.gpu;\n if (gpu === undefined) {\n return false;\n }\n try {\n return (await gpu.requestAdapter()) !== null;\n } catch {\n return false;\n }\n}\n"],"mappings":"AAeA,IAAa,EAAuC,CAAC,SAAU,MAAM,EAUxD,EAAoB,OAOjC,SAAgB,EAAiB,EAAyC,CAOtE,OANI,IAAc,IAAA,IAGd,EAAU,SAAW,EACd,CAAC,GAAG,CAAiB,EAEzB,CAAC,GAAG,CAAS,CACxB,CAuBA,eAAsB,EAAgB,EAAiD,CACnF,IAAM,EAAS,MAAM,EAAiB,EACtC,OAAO,EAAU,OAAQ,GAAa,CAClC,OAAQ,EAAR,CACI,IAAK,SACD,OAAO,EACX,IAAK,QACD,OAAO,OAAO,UAAc,KAAe,OAAQ,UACvD,QACI,MAAO,EACf,CACJ,CAAC,CACL,CAUA,eAAe,GAAqC,CAChD,IAAM,EACF,WAAW,WACZ,IACH,GAAI,IAAQ,IAAA,GACR,MAAO,GAEX,GAAI,CACA,OAAQ,MAAM,EAAI,eAAe,IAAO,IAC5C,MAAQ,CACJ,MAAO,EACX,CACJ"}
1
+ {"version":3,"file":"providers.cjs","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * The provider ORT-Web can always run, whatever the device.\n *\n * Used as the floor when capability detection rules everything else out. Passing\n * ORT a list it cannot satisfy is not a graceful failure — `InferenceSession.create`\n * rejects with \"no available backend found\" and the page gets no inference at\n * all, which is worse than the slow-but-working fallback the warning describes.\n */\nexport const FALLBACK_PROVIDER = \"wasm\";\n\n/**\n * One execution provider: its name, or ORT's config object for it.\n *\n * The object form carries provider options straight through to\n * `InferenceSession.create` — `{ name: \"webgpu\", preferredLayout: \"NHWC\" }`,\n * `{ name: \"wasm\" }` — which a bare name cannot express.\n */\nexport type ProviderSpec = string | { readonly name: string; readonly [option: string]: unknown };\n\n/**\n * The provider name a spec refers to.\n *\n * @param spec A provider name or config object.\n */\nexport function providerName(spec: ProviderSpec): string {\n return typeof spec === \"string\" ? spec : spec.name;\n}\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order, as names or\n * config objects; `undefined` or empty returns the default.\n */\nexport function resolveProviders<T extends ProviderSpec = string>(\n requested?: readonly T[],\n): (T | string)[] {\n if (requested === undefined || requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n\n/**\n * Narrow a provider list to the ones this browser can actually offer.\n *\n * ORT-Web exposes no equivalent of Node's `session.getProviders()`, so there is\n * no way to ask which provider a session ended up on. What the browser *does*\n * answer is whether the underlying API exists at all — no `navigator.gpu`, or no\n * adapter behind it, means `webgpu` was never going to run — and that covers the\n * case that actually bites: a page asking for WebGPU on a device without it,\n * silently getting WASM, and being several times slower than intended with no\n * error to point at.\n *\n * This is best-effort by construction. A provider that survives here can still\n * fail inside ORT for a reason the browser does not surface (a missing shader\n * feature, an exhausted device), so a surviving entry means \"not ruled out\",\n * not \"confirmed running\". Anything this function does not know how to test is\n * kept rather than dropped: guessing a provider away would be worse than\n * admitting ignorance about it.\n *\n * The WebGPU adapter is only requested when `webgpu` is in the list. Asking\n * unconditionally cost every WASM-only session a `requestAdapter()` round trip\n * and, on a machine without a GPU, a \"No available adapters\" console warning\n * per `create`.\n *\n * @param requested Providers in preference order, already resolved, as names\n * or config objects.\n * @returns The subset that is not ruled out, in the same order and form.\n */\nexport async function detectProviders<T extends ProviderSpec>(\n requested: readonly T[],\n): Promise<T[]> {\n const webgpu = requested.some((spec) => providerName(spec) === \"webgpu\")\n ? await hasWebGpuAdapter()\n : false;\n return requested.filter((spec) => {\n switch (providerName(spec)) {\n case \"webgpu\":\n return webgpu;\n case \"webnn\":\n return typeof navigator !== \"undefined\" && \"ml\" in navigator;\n default:\n return true;\n }\n });\n}\n\n/**\n * Whether this environment exposes a WebGPU adapter.\n *\n * `navigator.gpu` existing is not enough — a browser can ship the API and still\n * hand back no adapter (a blocklisted driver, a headless context, a machine with\n * no suitable GPU), which is exactly the configuration where a page asks for\n * WebGPU and quietly runs on WASM.\n */\nasync function hasWebGpuAdapter(): Promise<boolean> {\n const gpu = (\n globalThis.navigator as { gpu?: { requestAdapter(): Promise<unknown> } } | undefined\n )?.gpu;\n if (gpu === undefined) {\n return false;\n }\n try {\n return (await gpu.requestAdapter()) !== null;\n } catch {\n return false;\n }\n}\n"],"mappings":"AAeA,IAAa,EAAuC,CAAC,SAAU,MAAM,EAUxD,EAAoB,OAgBjC,SAAgB,EAAa,EAA4B,CACrD,OAAO,OAAO,GAAS,SAAW,EAAO,EAAK,IAClD,CAQA,SAAgB,EACZ,EACc,CAId,OAHI,IAAc,IAAA,IAAa,EAAU,SAAW,EACzC,CAAC,GAAG,CAAiB,EAEzB,CAAC,GAAG,CAAS,CACxB,CA6BA,eAAsB,EAClB,EACY,CACZ,IAAM,EAAS,EAAU,KAAM,GAAS,EAAa,CAAI,IAAM,QAAQ,EACjE,MAAM,EAAiB,EACvB,GACN,OAAO,EAAU,OAAQ,GAAS,CAC9B,OAAQ,EAAa,CAAI,EAAzB,CACI,IAAK,SACD,OAAO,EACX,IAAK,QACD,OAAO,OAAO,UAAc,KAAe,OAAQ,UACvD,QACI,MAAO,EACf,CACJ,CAAC,CACL,CAUA,eAAe,GAAqC,CAChD,IAAM,EACF,WAAW,WACZ,IACH,GAAI,IAAQ,IAAA,GACR,MAAO,GAEX,GAAI,CACA,OAAQ,MAAM,EAAI,eAAe,IAAO,IAC5C,MAAQ,CACJ,MAAO,EACX,CACJ"}
@@ -1,19 +1,22 @@
1
1
  //#region src/vision/core/providers.ts
2
2
  var e = ["webgpu", "wasm"], t = "wasm";
3
- function n(t) {
3
+ function n(e) {
4
+ return typeof e == "string" ? e : e.name;
5
+ }
6
+ function r(t) {
4
7
  return t === void 0 || t.length === 0 ? [...e] : [...t];
5
8
  }
6
- async function r(e) {
7
- let t = await i();
9
+ async function i(e) {
10
+ let t = e.some((e) => n(e) === "webgpu") ? await a() : !1;
8
11
  return e.filter((e) => {
9
- switch (e) {
12
+ switch (n(e)) {
10
13
  case "webgpu": return t;
11
14
  case "webnn": return typeof navigator < "u" && "ml" in navigator;
12
15
  default: return !0;
13
16
  }
14
17
  });
15
18
  }
16
- async function i() {
19
+ async function a() {
17
20
  let e = globalThis.navigator?.gpu;
18
21
  if (e === void 0) return !1;
19
22
  try {
@@ -23,6 +26,6 @@ async function i() {
23
26
  }
24
27
  }
25
28
  //#endregion
26
- export { e as DEFAULT_PROVIDERS, t as FALLBACK_PROVIDER, r as detectProviders, n as resolveProviders };
29
+ export { e as DEFAULT_PROVIDERS, t as FALLBACK_PROVIDER, i as detectProviders, n as providerName, r as resolveProviders };
27
30
 
28
31
  //# sourceMappingURL=providers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"providers.js","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * The provider ORT-Web can always run, whatever the device.\n *\n * Used as the floor when capability detection rules everything else out. Passing\n * ORT a list it cannot satisfy is not a graceful failure — `InferenceSession.create`\n * rejects with \"no available backend found\" and the page gets no inference at\n * all, which is worse than the slow-but-working fallback the warning describes.\n */\nexport const FALLBACK_PROVIDER = \"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/**\n * Narrow a provider list to the ones this browser can actually offer.\n *\n * ORT-Web exposes no equivalent of Node's `session.getProviders()`, so there is\n * no way to ask which provider a session ended up on. What the browser *does*\n * answer is whether the underlying API exists at all — no `navigator.gpu`, or no\n * adapter behind it, means `webgpu` was never going to run — and that covers the\n * case that actually bites: a page asking for WebGPU on a device without it,\n * silently getting WASM, and being several times slower than intended with no\n * error to point at.\n *\n * This is best-effort by construction. A provider that survives here can still\n * fail inside ORT for a reason the browser does not surface (a missing shader\n * feature, an exhausted device), so a surviving entry means \"not ruled out\",\n * not \"confirmed running\". Anything this function does not know how to test is\n * kept rather than dropped: guessing a provider away would be worse than\n * admitting ignorance about it.\n *\n * @param requested Providers in preference order, already resolved.\n * @returns The subset that is not ruled out, in the same order.\n */\nexport async function detectProviders(requested: readonly string[]): Promise<string[]> {\n const webgpu = await hasWebGpuAdapter();\n return requested.filter((provider) => {\n switch (provider) {\n case \"webgpu\":\n return webgpu;\n case \"webnn\":\n return typeof navigator !== \"undefined\" && \"ml\" in navigator;\n default:\n return true;\n }\n });\n}\n\n/**\n * Whether this environment exposes a WebGPU adapter.\n *\n * `navigator.gpu` existing is not enough — a browser can ship the API and still\n * hand back no adapter (a blocklisted driver, a headless context, a machine with\n * no suitable GPU), which is exactly the configuration where a page asks for\n * WebGPU and quietly runs on WASM.\n */\nasync function hasWebGpuAdapter(): Promise<boolean> {\n const gpu = (\n globalThis.navigator as { gpu?: { requestAdapter(): Promise<unknown> } } | undefined\n )?.gpu;\n if (gpu === undefined) {\n return false;\n }\n try {\n return (await gpu.requestAdapter()) !== null;\n } catch {\n return false;\n }\n}\n"],"mappings":";AAeA,IAAa,IAAuC,CAAC,UAAU,MAAM,GAUxD,IAAoB;AAOjC,SAAgB,EAAiB,GAAyC;CAOtE,OANI,MAAc,KAAA,KAGd,EAAU,WAAW,IACd,CAAC,GAAG,CAAiB,IAEzB,CAAC,GAAG,CAAS;AACxB;AAuBA,eAAsB,EAAgB,GAAiD;CACnF,IAAM,IAAS,MAAM,EAAiB;CACtC,OAAO,EAAU,QAAQ,MAAa;EAClC,QAAQ,GAAR;GACI,KAAK,UACD,OAAO;GACX,KAAK,SACD,OAAO,OAAO,YAAc,OAAe,QAAQ;GACvD,SACI,OAAO;EACf;CACJ,CAAC;AACL;AAUA,eAAe,IAAqC;CAChD,IAAM,IACF,WAAW,WACZ;CACH,IAAI,MAAQ,KAAA,GACR,OAAO;CAEX,IAAI;EACA,OAAQ,MAAM,EAAI,eAAe,MAAO;CAC5C,QAAQ;EACJ,OAAO;CACX;AACJ"}
1
+ {"version":3,"file":"providers.js","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * The provider ORT-Web can always run, whatever the device.\n *\n * Used as the floor when capability detection rules everything else out. Passing\n * ORT a list it cannot satisfy is not a graceful failure — `InferenceSession.create`\n * rejects with \"no available backend found\" and the page gets no inference at\n * all, which is worse than the slow-but-working fallback the warning describes.\n */\nexport const FALLBACK_PROVIDER = \"wasm\";\n\n/**\n * One execution provider: its name, or ORT's config object for it.\n *\n * The object form carries provider options straight through to\n * `InferenceSession.create` — `{ name: \"webgpu\", preferredLayout: \"NHWC\" }`,\n * `{ name: \"wasm\" }` — which a bare name cannot express.\n */\nexport type ProviderSpec = string | { readonly name: string; readonly [option: string]: unknown };\n\n/**\n * The provider name a spec refers to.\n *\n * @param spec A provider name or config object.\n */\nexport function providerName(spec: ProviderSpec): string {\n return typeof spec === \"string\" ? spec : spec.name;\n}\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order, as names or\n * config objects; `undefined` or empty returns the default.\n */\nexport function resolveProviders<T extends ProviderSpec = string>(\n requested?: readonly T[],\n): (T | string)[] {\n if (requested === undefined || requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n\n/**\n * Narrow a provider list to the ones this browser can actually offer.\n *\n * ORT-Web exposes no equivalent of Node's `session.getProviders()`, so there is\n * no way to ask which provider a session ended up on. What the browser *does*\n * answer is whether the underlying API exists at all — no `navigator.gpu`, or no\n * adapter behind it, means `webgpu` was never going to run — and that covers the\n * case that actually bites: a page asking for WebGPU on a device without it,\n * silently getting WASM, and being several times slower than intended with no\n * error to point at.\n *\n * This is best-effort by construction. A provider that survives here can still\n * fail inside ORT for a reason the browser does not surface (a missing shader\n * feature, an exhausted device), so a surviving entry means \"not ruled out\",\n * not \"confirmed running\". Anything this function does not know how to test is\n * kept rather than dropped: guessing a provider away would be worse than\n * admitting ignorance about it.\n *\n * The WebGPU adapter is only requested when `webgpu` is in the list. Asking\n * unconditionally cost every WASM-only session a `requestAdapter()` round trip\n * and, on a machine without a GPU, a \"No available adapters\" console warning\n * per `create`.\n *\n * @param requested Providers in preference order, already resolved, as names\n * or config objects.\n * @returns The subset that is not ruled out, in the same order and form.\n */\nexport async function detectProviders<T extends ProviderSpec>(\n requested: readonly T[],\n): Promise<T[]> {\n const webgpu = requested.some((spec) => providerName(spec) === \"webgpu\")\n ? await hasWebGpuAdapter()\n : false;\n return requested.filter((spec) => {\n switch (providerName(spec)) {\n case \"webgpu\":\n return webgpu;\n case \"webnn\":\n return typeof navigator !== \"undefined\" && \"ml\" in navigator;\n default:\n return true;\n }\n });\n}\n\n/**\n * Whether this environment exposes a WebGPU adapter.\n *\n * `navigator.gpu` existing is not enough — a browser can ship the API and still\n * hand back no adapter (a blocklisted driver, a headless context, a machine with\n * no suitable GPU), which is exactly the configuration where a page asks for\n * WebGPU and quietly runs on WASM.\n */\nasync function hasWebGpuAdapter(): Promise<boolean> {\n const gpu = (\n globalThis.navigator as { gpu?: { requestAdapter(): Promise<unknown> } } | undefined\n )?.gpu;\n if (gpu === undefined) {\n return false;\n }\n try {\n return (await gpu.requestAdapter()) !== null;\n } catch {\n return false;\n }\n}\n"],"mappings":";AAeA,IAAa,IAAuC,CAAC,UAAU,MAAM,GAUxD,IAAoB;AAgBjC,SAAgB,EAAa,GAA4B;CACrD,OAAO,OAAO,KAAS,WAAW,IAAO,EAAK;AAClD;AAQA,SAAgB,EACZ,GACc;CAId,OAHI,MAAc,KAAA,KAAa,EAAU,WAAW,IACzC,CAAC,GAAG,CAAiB,IAEzB,CAAC,GAAG,CAAS;AACxB;AA6BA,eAAsB,EAClB,GACY;CACZ,IAAM,IAAS,EAAU,MAAM,MAAS,EAAa,CAAI,MAAM,QAAQ,IACjE,MAAM,EAAiB,IACvB;CACN,OAAO,EAAU,QAAQ,MAAS;EAC9B,QAAQ,EAAa,CAAI,GAAzB;GACI,KAAK,UACD,OAAO;GACX,KAAK,SACD,OAAO,OAAO,YAAc,OAAe,QAAQ;GACvD,SACI,OAAO;EACf;CACJ,CAAC;AACL;AAUA,eAAe,IAAqC;CAChD,IAAM,IACF,WAAW,WACZ;CACH,IAAI,MAAQ,KAAA,GACR,OAAO;CAEX,IAAI;EACA,OAAQ,MAAM,EAAI,eAAe,MAAO;CAC5C,QAAQ;EACJ,OAAO;CACX;AACJ"}
@@ -1,2 +1,2 @@
1
- const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./exceptions.cjs"),n=require("./graph.cjs"),r=require("./metadata.cjs"),i=require("./providers.cjs");let a=require("onnxruntime-web");a=e.__toESM(a,1);async function o(e){try{let t=await fetch(e);return t.ok?new Uint8Array(await t.arrayBuffer()):(s(e,`HTTP ${t.status} ${t.statusText}`),e)}catch(t){return s(e,t.message),e}}function s(e,t){console.warn(`[@ort-vision-sdk/web] Could not fetch ${e} to read its metadata (${t}). Letting ONNX Runtime load it instead: the model will work, but its baked-in class names are unavailable, so labels fall back to class_0, class_1, ... Pass \`labels\` explicitly to name them.`)}function c(e,t){let n=e.filter(e=>!t.includes(e));n.length!==0&&console.warn(`This browser cannot offer the requested execution provider(s) ${JSON.stringify(n)}; the session will run on ${JSON.stringify(t)}. Inference still produces correct results, on the fallback provider.`)}var l=class e{_session;providers;_metadata;requestedProviders;constructor(e,t,n,r){this._session=e,this.providers=t,this._metadata=n,this.requestedProviders=r}static async create(n,s={}){let l=i.resolveProviders(s.providers),u=await i.detectProviders(l),d=u.length>0?u:[i.FALLBACK_PROVIDER];s.providers!==void 0&&s.providers.length>0&&c(l,d);let f={...s.sessionOptions??{},executionProviders:d},p=s.readMetadata!==!1,m=typeof n==`string`&&p?await o(n):n,h=p&&typeof m!=`string`?r.readModelMetadata(m):{},g;try{g=(typeof m==`string`||m instanceof Uint8Array,await a.InferenceSession.create(m,f))}catch(e){throw new t.ModelLoadError(`Failed to load ONNX model: ${e.message}`,{cause:e})}return new e(g,d,h,l)}get inputNames(){return this._session.inputNames}get inputName(){let e=this._session.inputNames[0];if(e===void 0)throw new t.InferenceError(`Model has no inputs.`);return e}get outputNames(){return this._session.outputNames}get inputShapes(){return n.declaredShapesFrom(this._session.inputMetadata)}get inputShape(){return this.inputShapes[0]??[]}get outputShapes(){return n.declaredShapesFrom(this._session.outputMetadata)}get outputShape(){return this.outputShapes[0]??[]}get metadata(){return this._metadata}async release(){await this._session.release().catch(()=>void 0)}get raw(){return this._session}async run(e){try{return await this._session.run(e)}catch(e){throw new t.InferenceError(`Inference failed: ${e.message}`,{cause:e})}}};exports.OrtSession=l;
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./exceptions.cjs"),n=require("./dtypes.cjs"),r=require("./graph.cjs"),i=require("./metadata.cjs"),a=require("./providers.cjs");let o=require("onnxruntime-web");o=e.__toESM(o,1);var s=`ort_vision_sdk.graph_optimization`,c=`CAcSDm9ydC12aXNpb24tc2RrOjoKEAoBeBIBeSIISWRlbnRpdHkSBHdhcm1aDwoBeBIKCggIARIECgIIAWIPCgF5EgoKCAgBEgQKAggBQgQKABAN`,l=new Map;function u(e){let t=e.map(a.providerName).join(`,`),n=l.get(t);return n===void 0&&(n=(async()=>{try{let t=Uint8Array.from(atob(c),e=>e.charCodeAt(0));await(await o.InferenceSession.create(t,{executionProviders:e})).release()}catch{return}})(),l.set(t,n)),n}function d(){console.warn(`[@ort-vision-sdk/web] This model was pre-optimized by optimize_model, which targets the WASM backend; on WebGPU some of its fused nodes fall back to the CPU. For WebGPU, ship the original export instead.`)}var f=`ort_vision_sdk.quantization`;function p(e,t){if(t[`ort_vision_sdk.quantization`]===void 0)return[...e];let n=e.filter(e=>a.providerName(e)!==`webgpu`);return n.length===e.length?n:(console.warn(`[@ort-vision-sdk/web] This model was quantized by quantize_model (${t[f]}); ONNX Runtime Web's WebGPU backend cannot run its quantized operators, so it runs on WASM.`),n.length>0?n:[a.FALLBACK_PROVIDER])}var m=`ort-vision-sdk-models`;async function h(e,t){let n=t===null?null:await _(t);if(n!==null){let t=await n.match(e).catch(()=>void 0);if(t!==void 0)return new Uint8Array(await t.arrayBuffer())}try{let t=await fetch(e);if(!t.ok)return v(e,`HTTP ${t.status} ${t.statusText}`),e;let r=await t.arrayBuffer();return n!==null&&await g(n,e,r),new Uint8Array(r)}catch(t){return v(e,t.message),e}}async function g(e,t,n){try{await e.put(t,new Response(n))}catch{return}}async function _(e){if(typeof caches>`u`)return null;try{return await caches.open(e)}catch{return null}}function v(e,t){console.warn(`[@ort-vision-sdk/web] Could not fetch ${e} to read its metadata (${t}). Letting ONNX Runtime load it instead: the model will work, but its baked-in class names are unavailable, so labels fall back to class_0, class_1, ... Pass \`labels\` explicitly to name them.`)}function y(e,t){let n=e.filter(e=>!t.includes(e));n.length!==0&&console.warn(`This browser cannot offer the requested execution provider(s) ${JSON.stringify(n)}; the session will run on ${JSON.stringify(t)}. Inference still produces correct results, on the fallback provider.`)}function b(e){let t=i.readModelInputTypes(e),r={};for(let[e,i]of Object.entries(t))r[e]=n.tensorTypeFor(i);return r}function x(){console.warn(`Could not read any input type from this model's bytes; feeds will be built as float32. A half-precision model will fail at inference with 'Unexpected input data type'. Please report this with the model that produced it.`)}function S(e){let r=Object.entries(e).filter(([,e])=>e===`float16`);if(r.length===0||n.hasFloat16Array())return;let i=r.map(([e])=>e).join(`, `);throw new t.ModelLoadError(`This model declares half-precision input(s) [${i}], but this environment has no Float16Array, which ONNX Runtime requires for a float16 tensor. Use a float32 export of the model, or run in a browser that supports Float16Array.`)}var C=class e{_session;providers;_metadata;requestedProviders;_inputTypes;constructor(e,t,n,r,i={}){this._session=e,this.providers=t,this._metadata=n,this.requestedProviders=r,this._inputTypes=i}_runQueue=Promise.resolve();static async create(n,r={}){let s=a.resolveProviders(r.providers),c=r.readMetadata!==!1,l=r.cache===!0?m:r.cache?r.cache:null,f=typeof n==`string`&&(c||l!==null),g=a.detectProviders(s).then(e=>e.length>0?e:[a.FALLBACK_PROVIDER]),[_,v]=await Promise.all([g,f?h(n,l):Promise.resolve(n),f?g.then(u):Promise.resolve()]),C=c&&typeof v!=`string`?i.readModelMetadata(v):{},w=p(_,C),T=s.map(a.providerName),E=w.map(a.providerName);r.providers!==void 0&&r.providers.length>0&&y(T,_.map(a.providerName)),C[`ort_vision_sdk.graph_optimization`]!==void 0&&E.includes(`webgpu`)&&d();let D={...C[`ort_vision_sdk.graph_optimization`]!==void 0&&r.sessionOptions?.graphOptimizationLevel===void 0?{graphOptimizationLevel:`disabled`}:{},...r.sessionOptions??{},executionProviders:w},O=typeof v==`string`?{}:b(v);typeof v!=`string`&&Object.keys(O).length===0&&x(),S(O);let k;try{k=(typeof v==`string`||v instanceof Uint8Array,await o.InferenceSession.create(v,D))}catch(e){throw new t.ModelLoadError(`Failed to load ONNX model: ${e.message}`,{cause:e})}return new e(k,E,C,T,O)}get inputDtypes(){return this.inputNames.map(e=>this._inputTypes[e]??`float32`)}get inputDtype(){return this._inputTypes[this.inputName]??`float32`}get inputNames(){return this._session.inputNames}get inputName(){let e=this._session.inputNames[0];if(e===void 0)throw new t.InferenceError(`Model has no inputs.`);return e}get outputNames(){return this._session.outputNames}get inputShapes(){return r.declaredShapesFrom(this._session.inputMetadata)}get inputShape(){return this.inputShapes[0]??[]}get outputShapes(){return r.declaredShapesFrom(this._session.outputMetadata)}get outputShape(){return this.outputShapes[0]??[]}get metadata(){return this._metadata}async release(){await this._session.release().catch(()=>void 0)}get raw(){return this._session}run(e){let t=this._runQueue.then(()=>this._runNow(e));return this._runQueue=t.catch(()=>void 0),t}async _runNow(e){try{return await this._session.run(this._asDeclaredTypes(e))}catch(e){throw new t.InferenceError(`Inference failed: ${e.message}`,{cause:e})}}_asDeclaredTypes(e){let t=null;for(let[r,i]of Object.entries(e)){let a=this._inputTypes[r];if(a===void 0||a===i.type||!(i.data instanceof Float32Array))continue;let s=n.toFeedData(i.data,a);s!==i.data&&(t??={...e},t[r]=new o.Tensor(a,s,i.dims))}return t??e}};exports.DEFAULT_MODEL_CACHE=m,exports.GRAPH_OPTIMIZATION_KEY=s,exports.OrtSession=C,exports.QUANTIZATION_KEY=f;
2
2
  //# sourceMappingURL=session.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"session.cjs","names":[],"sources":["../../../src/vision/core/session.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { type DeclaredShape, declaredShapesFrom } from \"./graph\";\nimport { readModelMetadata } from \"./metadata\";\nimport { FALLBACK_PROVIDER, detectProviders, resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\n/**\n * Fetch a model URL as bytes so its metadata can be read.\n *\n * Falls back to the URL itself when the fetch fails, letting ORT try its own\n * load path: losing the metadata map is a downgrade, but failing to load a model\n * that ORT could have fetched would be a regression.\n *\n * @param url Where the `.onnx` lives.\n * @returns The model bytes, or the original URL when they could not be fetched.\n */\nasync function fetchModel(url: string): Promise<Uint8Array | string> {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n warnMetadataUnavailable(url, `HTTP ${response.status} ${response.statusText}`);\n return url;\n }\n return new Uint8Array(await response.arrayBuffer());\n } catch (err) {\n warnMetadataUnavailable(url, (err as Error).message);\n return url;\n }\n}\n\n/**\n * Warn that a model's metadata could not be read, and say what that costs.\n *\n * The fallback itself is right — losing the metadata beats failing a load that\n * ORT could have completed on its own — but it used to be silent, and the\n * symptom it produces is remote from the cause: class names come back as\n * `class_0`, `class_1`, ... with nothing anywhere explaining why. Whoever hits\n * this needs to be told that passing `labels` is the way out.\n *\n * @param url The model URL that could not be fetched here.\n * @param reason What went wrong, as reported by `fetch`.\n */\nfunction warnMetadataUnavailable(url: string, reason: string): void {\n console.warn(\n `[@ort-vision-sdk/web] Could not fetch ${url} to read its metadata (${reason}). ` +\n \"Letting ONNX Runtime load it instead: the model will work, but its baked-in \" +\n \"class names are unavailable, so labels fall back to class_0, class_1, ... \" +\n \"Pass `labels` explicitly to name them.\",\n );\n}\n\nexport interface OrtSessionOptions {\n /**\n * Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}.\n *\n * Naming one explicitly also opts into a `console.warn` when this browser\n * cannot offer it, instead of falling back in silence.\n */\n readonly providers?: readonly string[];\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n /**\n * Whether to read the model's custom metadata map (`names`, `task`, `imgsz`).\n * Defaults to `true`.\n *\n * The runtime does not expose that map, so it is read from the file itself —\n * which means a URL model is fetched here and handed to ORT as bytes instead\n * of letting ORT fetch it. That is the same single download either way, and\n * it is what lets a task resolve its labels off the model. Set to `false` to\n * keep the URL path untouched and leave {@link OrtSession.metadata} empty.\n *\n * `false` is also the escape hatch when a device cannot afford the bytes: the\n * fetched buffer is dropped before ORT builds the graph (see\n * {@link OrtSession.create}), but ORT's own load path still keeps the model out\n * of reach of anything the SDK holds. A session built this way resolves its\n * input size from the graph as usual — only the class names are lost, so a\n * caller taking this route has to pass `labels` itself.\n */\n readonly readMetadata?: boolean;\n}\n\n/**\n * Warn when a provider named explicitly by the caller is not going to run.\n *\n * Only explicit requests are worth a warning. The default list exists precisely\n * so that falling from `webgpu` to `wasm` is the expected outcome — but a caller\n * who wrote `providers: [\"webgpu\"]` and lands on WASM has a page several times\n * slower than intended and nothing in the console to explain it.\n *\n * @param requested Providers that were asked for.\n * @param effective Providers that survived capability detection.\n */\nfunction warnOnDroppedProviders(requested: readonly string[], effective: readonly string[]): void {\n const dropped = requested.filter((provider) => !effective.includes(provider));\n if (dropped.length === 0) {\n return;\n }\n console.warn(\n `This browser cannot offer the requested execution provider(s) ${JSON.stringify(dropped)}; ` +\n `the session will run on ${JSON.stringify(effective)}. Inference still produces correct ` +\n \"results, on the fallback provider.\",\n );\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names and the shapes the graph declares,\n * manages execution-provider selection, provides a typed {@link OrtSession.run}\n * method, and releases the native session through {@link OrtSession.release}.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n /**\n * Execution providers this session is expected to run on.\n *\n * The requested list narrowed to what this browser can actually offer — a\n * `webgpu` entry survives only where an adapter exists. Best-effort: ORT-Web\n * exposes no way to ask which provider a session ended up on, so an entry\n * here means \"not ruled out\", not \"confirmed\". See\n * {@link requestedProviders} for what was asked for.\n *\n * When nothing survives — a caller asking for `webgpu` alone on a device\n * without it — this falls back to {@link FALLBACK_PROVIDER}, which ORT-Web\n * can always run. Handing ORT the unsatisfiable list instead makes\n * `InferenceSession.create` reject with \"no available backend found\", so the\n * page gets no inference at all rather than the slow-but-working fallback\n * the `console.warn` describes. Measured in a real Chromium, where\n * `navigator.gpu` exists but yields no adapter.\n */\n public readonly providers: readonly string[],\n private readonly _metadata: Readonly<Record<string, string>>,\n /**\n * Execution providers that were asked for, after defaults were applied.\n *\n * Kept separate because ORT-Web falls back silently: a page that asks for\n * `webgpu` on a device without it runs on WASM and is told nothing.\n */\n public readonly requestedProviders: readonly string[],\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * The metadata map is read **before** the session is built, and that order is\n * load-bearing on memory-constrained devices. ORT copies the model into its\n * WASM heap and then allocates the graph and the weights on top of that copy;\n * a `readModelMetadata` call placed after `InferenceSession.create` keeps the\n * JavaScript-side buffer reachable across the whole build, so a 5 MB model\n * costs 5 MB of JS heap plus 5 MB of WASM heap plus the weights at the same\n * instant. Reading first makes the buffer collectable as soon as ORT has copied\n * it — on a phone that was the difference between a session and\n * `Can't create a session. failed to allocate a buffer of size N`.\n *\n * @param model Either a URL string, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list, pass-through `SessionOptions`, and whether to\n * read the model's metadata map (see {@link OrtSessionOptions.readMetadata}).\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const requested = resolveProviders(options.providers);\n const detected = await detectProviders(requested);\n const providers = detected.length > 0 ? detected : [FALLBACK_PROVIDER];\n if (options.providers !== undefined && options.providers.length > 0) {\n warnOnDroppedProviders(requested, providers);\n }\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n const wantsMetadata = options.readMetadata !== false;\n const source = typeof model === \"string\" && wantsMetadata ? await fetchModel(model) : model;\n const metadata =\n wantsMetadata && typeof source !== \"string\" ? readModelMetadata(source) : {};\n\n let session: ort.InferenceSession;\n try {\n if (typeof source === \"string\") {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else if (source instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n source as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers, metadata, requested);\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /**\n * Shapes the graph declares for its inputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Empty shapes mean the runtime\n * reported no metadata — either a non-tensor input, or an `onnxruntime-web`\n * older than 1.21, which predates input metadata.\n */\n get inputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.inputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first input, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get inputShape(): DeclaredShape {\n return this.inputShapes[0] ?? [];\n }\n\n /**\n * Shapes the graph declares for its outputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Reading them is how a task can\n * tell how many classes a head emits without being told.\n */\n get outputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.outputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first output, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get outputShape(): DeclaredShape {\n return this.outputShapes[0] ?? [];\n }\n\n /**\n * The model's custom metadata map — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export.\n *\n * Read from the model's bytes at load time, since the runtime does not expose\n * it. Empty when the session was created with `readMetadata: false`, from a\n * URL that could not be fetched here, or from a model carrying no metadata.\n */\n get metadata(): Readonly<Record<string, string>> {\n return this._metadata;\n }\n\n /**\n * Release the native session and free its memory.\n *\n * Call it when a session is discarded while the page lives on — rebuilding a\n * task at a different input size, swapping in a newer model. A failure from\n * the runtime is ignored: a session being torn down has nothing left to fail\n * at, and the caller is already moving on.\n */\n async release(): Promise<void> {\n await this._session.release().catch(() => undefined);\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * @param feeds Map of input name to `ort.Tensor`. Keys must match {@link inputNames}.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n async run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(feeds);\n return result as Record<string, ort.Tensor>;\n } catch (err) {\n throw new InferenceError(`Inference failed: ${(err as Error).message}`, { cause: err });\n }\n }\n}\n"],"mappings":"0NA0BA,eAAe,EAAW,EAA2C,CACjE,GAAI,CACA,IAAM,EAAW,MAAM,MAAM,CAAG,EAKhC,OAJK,EAAS,GAIP,IAAI,WAAW,MAAM,EAAS,YAAY,CAAC,GAH9C,EAAwB,EAAK,QAAQ,EAAS,OAAO,GAAG,EAAS,YAAY,EACtE,EAGf,OAAS,EAAK,CAEV,OADA,EAAwB,EAAM,EAAc,OAAO,EAC5C,CACX,CACJ,CAcA,SAAS,EAAwB,EAAa,EAAsB,CAChE,QAAQ,KACJ,yCAAyC,EAAI,yBAAyB,EAAO,kMAIjF,CACJ,CA2CA,SAAS,EAAuB,EAA8B,EAAoC,CAC9F,IAAM,EAAU,EAAU,OAAQ,GAAa,CAAC,EAAU,SAAS,CAAQ,CAAC,EACxE,EAAQ,SAAW,GAGvB,QAAQ,KACJ,iEAAiE,KAAK,UAAU,CAAO,EAAE,4BAC1D,KAAK,UAAU,CAAS,EAAE,sEAE7D,CACJ,CASA,IAAa,EAAb,MAAa,CAAW,CAEC,SAkBD,UACC,UAOD,mBA3BpB,YACI,EAkBA,EACA,EAOA,EACF,CA3BmB,KAAA,SAAA,EAkBD,KAAA,UAAA,EACC,KAAA,UAAA,EAOD,KAAA,mBAAA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,IAAM,CAAC,CACpC,CAUA,IAAI,UAA6C,CAC7C,OAAO,KAAK,SAChB,CAUA,MAAM,SAAyB,CAC3B,MAAM,KAAK,SAAS,QAAQ,CAAC,CAAC,UAAY,IAAA,EAAS,CACvD,CAGA,IAAI,KAA4B,CAC5B,OAAO,KAAK,QAChB,CAQA,MAAM,IAAI,EAAwE,CAC9E,GAAI,CAEA,OAAO,MADc,KAAK,SAAS,IAAI,CAAK,CAEhD,OAAS,EAAK,CACV,MAAM,IAAI,EAAA,eAAe,qBAAsB,EAAc,UAAW,CAAE,MAAO,CAAI,CAAC,CAC1F,CACJ,CACJ"}
1
+ {"version":3,"file":"session.cjs","names":[],"sources":["../../../src/vision/core/session.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { DEFAULT_TENSOR_TYPE, hasFloat16Array, tensorTypeFor, toFeedData } from \"./dtypes\";\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { type DeclaredShape, declaredShapesFrom } from \"./graph\";\nimport { readModelInputTypes, readModelMetadata } from \"./metadata\";\nimport {\n FALLBACK_PROVIDER,\n type ProviderSpec,\n detectProviders,\n providerName,\n resolveProviders,\n} from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\n/**\n * Metadata key naming the level a model was graph-optimized at offline.\n *\n * Written by the Python SDK's `optimize_model`; both test suites pin the same\n * string, so a rename on one side fails. See {@link OrtSession.create} for what\n * the session does when it finds it.\n */\nexport const GRAPH_OPTIMIZATION_KEY = \"ort_vision_sdk.graph_optimization\";\n\n/**\n * An 84-byte ONNX model — one `Identity` on a float `[1]` — used to start the runtime.\n *\n * Generated with `onnx.helper` (opset 13, IR 7, producer `ort-vision-sdk`).\n * See {@link warmRuntime} for why it exists.\n */\nconst RUNTIME_PROBE_MODEL =\n \"CAcSDm9ydC12aXNpb24tc2RrOjoKEAoBeBIBeSIISWRlbnRpdHkSBHdhcm1aDwoBeBIKCggIARIECgIIAWIPCgF5EgoKCAgBEgQKAggBQgQKABAN\";\n\n/** Runtime start-ups already begun on this page, keyed by provider names. */\nconst runtimeWarmups = new Map<string, Promise<void>>();\n\n/**\n * Start ONNX Runtime's backends for a provider list, once per page.\n *\n * ORT downloads and compiles its WebAssembly binary — 12.8 MB for the plain\n * WASM build, 25.9 MB for the one carrying WebGPU — inside the first\n * `InferenceSession.create`. {@link OrtSession.create} only reaches that call\n * after it has downloaded the model, so on a real network the two largest\n * downloads of a page load ran one after the other. Creating and releasing a\n * session on a tiny model while the real one downloads lets them overlap; the\n * real `create` then finds the runtime ready.\n *\n * A failure here is swallowed: the real `create` runs against the same runtime\n * and reports the same problem with the right model in the message.\n *\n * @param specs Providers the real session will use.\n * @returns Settles when the runtime is up, or when starting it failed.\n */\nfunction warmRuntime(specs: readonly ProviderSpec[]): Promise<void> {\n const key = specs.map(providerName).join(\",\");\n let pending = runtimeWarmups.get(key);\n if (pending === undefined) {\n pending = (async () => {\n try {\n const probe = Uint8Array.from(atob(RUNTIME_PROBE_MODEL), (c) => c.charCodeAt(0));\n const session = await ortRuntime.InferenceSession.create(probe, {\n executionProviders:\n specs as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n });\n await session.release();\n } catch {\n return;\n }\n })();\n runtimeWarmups.set(key, pending);\n }\n return pending;\n}\n\n/**\n * Warn that a model optimized offline is about to run on WebGPU.\n *\n * `optimize_model` fuses operators for the CPU, which is what the WASM backend\n * runs. On WebGPU some of those fused nodes have no GPU kernel: on a\n * YOLO11n-seg, ONNX Runtime placed 2 nodes on the CPU for the optimized file\n * and none for the original, so every inference pays GPU↔CPU copies. The SDK\n * cannot swap the file, so it says which one to ship.\n */\nfunction warnPreOptimizedOnWebGpu(): void {\n console.warn(\n \"[@ort-vision-sdk/web] This model was pre-optimized by optimize_model, which targets the \" +\n \"WASM backend; on WebGPU some of its fused nodes fall back to the CPU. For WebGPU, ship \" +\n \"the original export instead.\",\n );\n}\n\n/**\n * Metadata key the Python SDK's `quantize_model` writes on an INT8 model.\n *\n * Mirrored by `QUANTIZATION_KEY` in the Python SDK; both test suites pin the\n * string. See {@link keepQuantizedOffWebGpu} for what a session does with it.\n */\nexport const QUANTIZATION_KEY = \"ort_vision_sdk.quantization\";\n\n/**\n * Drop `webgpu` from the providers of a model `quantize_model` produced.\n *\n * ONNX Runtime Web's WebGPU `DequantizeLinear` rejects the quantized bias such\n * a model carries — `scale and zero-point inputs must have the same rank` —\n * so the first `predict()` fails; and a variant with the bias left in float\n * ran but returned different detections than WASM for the same file. The\n * model is fine on WASM, which is also where INT8 pays (52.7 ms vs 68.4 ms on\n * a YOLO11n-seg), so the session runs there and says so.\n *\n * @param specs Providers that survived detection.\n * @param metadata The model's metadata map.\n * @returns `specs` without `webgpu` when the model is marked quantized; the\n * WASM fallback when nothing else is left.\n */\nfunction keepQuantizedOffWebGpu(\n specs: readonly ProviderSpec[],\n metadata: Readonly<Record<string, string>>,\n): ProviderSpec[] {\n if (metadata[QUANTIZATION_KEY] === undefined) return [...specs];\n const kept = specs.filter((spec) => providerName(spec) !== \"webgpu\");\n if (kept.length === specs.length) return kept;\n console.warn(\n `[@ort-vision-sdk/web] This model was quantized by quantize_model (${metadata[QUANTIZATION_KEY]}); ` +\n \"ONNX Runtime Web's WebGPU backend cannot run its quantized operators, so it runs on WASM.\",\n );\n return kept.length > 0 ? kept : [FALLBACK_PROVIDER];\n}\n\n/** Cache Storage bucket used when {@link OrtSessionOptions.cache} is `true`. */\nexport const DEFAULT_MODEL_CACHE = \"ort-vision-sdk-models\";\n\n/**\n * Fetch a model URL as bytes so its metadata can be read.\n *\n * Falls back to the URL itself when the fetch fails, letting ORT try its own\n * load path: losing the metadata map is a downgrade, but failing to load a model\n * that ORT could have fetched would be a regression.\n *\n * @param url Where the `.onnx` lives.\n * @param cacheName Cache Storage bucket to read from and fill, or `null` to\n * always go to the network.\n * @returns The model bytes, or the original URL when they could not be fetched.\n */\nasync function fetchModel(url: string, cacheName: string | null): Promise<Uint8Array | string> {\n const cache = cacheName === null ? null : await openCache(cacheName);\n if (cache !== null) {\n const hit = await cache.match(url).catch(() => undefined);\n if (hit !== undefined) return new Uint8Array(await hit.arrayBuffer());\n }\n try {\n const response = await fetch(url);\n if (!response.ok) {\n warnMetadataUnavailable(url, `HTTP ${response.status} ${response.statusText}`);\n return url;\n }\n const buffer = await response.arrayBuffer();\n if (cache !== null) await storeModel(cache, url, buffer);\n return new Uint8Array(buffer);\n } catch (err) {\n warnMetadataUnavailable(url, (err as Error).message);\n return url;\n }\n}\n\n/**\n * Put a model's bytes into the cache, never failing the load over it.\n *\n * Stores a fresh `Response` built from bytes already read rather than a\n * `clone()` of the network response: one read, and nothing that can throw\n * synchronously outside the guard. Awaited on purpose — a `put` left running\n * would keep its copy of the model reachable while ORT builds the session, the\n * same doubled peak {@link OrtSession.create} orders its reads to avoid.\n *\n * @param cache The open bucket.\n * @param url Cache key.\n * @param buffer The model.\n */\nasync function storeModel(cache: Cache, url: string, buffer: ArrayBuffer): Promise<void> {\n try {\n await cache.put(url, new Response(buffer));\n } catch {\n return;\n }\n}\n\n/**\n * Open a Cache Storage bucket, or report that there is none to open.\n *\n * Cache Storage only exists in secure contexts (HTTPS, `localhost`), and a\n * browser may refuse it outright — private windows, blocked site data, an\n * exhausted quota. None of that is worth failing a model load over: the model\n * is fetched from the network as if caching had not been asked for. A failed\n * `put` is swallowed for the same reason — see {@link storeModel}.\n *\n * @param name Bucket name.\n * @returns The cache, or `null` when this environment cannot provide one.\n */\nasync function openCache(name: string): Promise<Cache | null> {\n if (typeof caches === \"undefined\") return null;\n try {\n return await caches.open(name);\n } catch {\n return null;\n }\n}\n\n/**\n * Warn that a model's metadata could not be read, and say what that costs.\n *\n * The fallback itself is right — losing the metadata beats failing a load that\n * ORT could have completed on its own — but it used to be silent, and the\n * symptom it produces is remote from the cause: class names come back as\n * `class_0`, `class_1`, ... with nothing anywhere explaining why. Whoever hits\n * this needs to be told that passing `labels` is the way out.\n *\n * @param url The model URL that could not be fetched here.\n * @param reason What went wrong, as reported by `fetch`.\n */\nfunction warnMetadataUnavailable(url: string, reason: string): void {\n console.warn(\n `[@ort-vision-sdk/web] Could not fetch ${url} to read its metadata (${reason}). ` +\n \"Letting ONNX Runtime load it instead: the model will work, but its baked-in \" +\n \"class names are unavailable, so labels fall back to class_0, class_1, ... \" +\n \"Pass `labels` explicitly to name them.\",\n );\n}\n\nexport interface OrtSessionOptions {\n /**\n * Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}.\n *\n * Each entry is a name (`\"webgpu\"`, `\"wasm\"`) or ORT's config object for that\n * provider, which passes provider options through untouched —\n * `{ name: \"webgpu\", preferredLayout: \"NHWC\" }`.\n *\n * Naming one explicitly also opts into a `console.warn` when this browser\n * cannot offer it, instead of falling back in silence.\n */\n readonly providers?: readonly ProviderSpec[];\n /**\n * Keep a URL model in the browser's Cache Storage between page loads.\n *\n * `true` uses the {@link DEFAULT_MODEL_CACHE} bucket; a string names the\n * bucket. A later `create` with the same URL reads the bytes from the cache\n * instead of the network — for a model of several megabytes, the bulk of\n * what a returning visitor waits for. Defaults to `false`.\n *\n * The URL is the cache key and nothing expires it: publish a changed model\n * under a new URL (`yolo.v2.onnx`, `?v=2`) or a new bucket name, or delete\n * the bucket with `caches.delete(name)`. Ignored for models passed as bytes,\n * and silently skipped where Cache Storage is unavailable (non-secure\n * contexts, blocked site data).\n */\n readonly cache?: boolean | string;\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n /**\n * Whether to read the model's custom metadata map (`names`, `task`, `imgsz`).\n * Defaults to `true`.\n *\n * The runtime does not expose that map, so it is read from the file itself —\n * which means a URL model is fetched here and handed to ORT as bytes instead\n * of letting ORT fetch it. That is the same single download either way, and\n * it is what lets a task resolve its labels off the model. Set to `false` to\n * keep the URL path untouched (unless {@link cache} is set, which needs the\n * bytes) and leave {@link OrtSession.metadata} empty.\n *\n * `false` is also the escape hatch when a device cannot afford the bytes: the\n * fetched buffer is dropped before ORT builds the graph (see\n * {@link OrtSession.create}), but ORT's own load path still keeps the model out\n * of reach of anything the SDK holds. A session built this way resolves its\n * input size from the graph as usual — only the class names are lost, so a\n * caller taking this route has to pass `labels` itself.\n */\n readonly readMetadata?: boolean;\n}\n\n/**\n * Warn when a provider named explicitly by the caller is not going to run.\n *\n * Only explicit requests are worth a warning. The default list exists precisely\n * so that falling from `webgpu` to `wasm` is the expected outcome — but a caller\n * who wrote `providers: [\"webgpu\"]` and lands on WASM has a page several times\n * slower than intended and nothing in the console to explain it.\n *\n * @param requested Providers that were asked for.\n * @param effective Providers that survived capability detection.\n */\nfunction warnOnDroppedProviders(requested: readonly string[], effective: readonly string[]): void {\n const dropped = requested.filter((provider) => !effective.includes(provider));\n if (dropped.length === 0) {\n return;\n }\n console.warn(\n `This browser cannot offer the requested execution provider(s) ${JSON.stringify(dropped)}; ` +\n `the session will run on ${JSON.stringify(effective)}. Inference still produces correct ` +\n \"results, on the fallback provider.\",\n );\n}\n\n/**\n * Name the tensor type of every graph input, straight from the model bytes.\n *\n * @param model The `.onnx` file contents.\n * @returns Input name → tensor type name. Empty when the file carries no\n * readable graph, which callers read as \"assume float32\".\n */\nfunction declaredInputTypes(model: Uint8Array | ArrayBufferLike): Readonly<Record<string, string>> {\n const declared = readModelInputTypes(model);\n const named: Record<string, string> = {};\n for (const [name, elemType] of Object.entries(declared)) {\n named[name] = tensorTypeFor(elemType);\n }\n return named;\n}\n\n/**\n * Warn when the model's bytes were in hand but no input type came back.\n *\n * Every ONNX graph declares at least one input, so an empty result from bytes\n * means the reader failed, not that the model said nothing. Without this the\n * failure is invisible: the session falls back to float32, which is right for\n * most models and wrong for exactly the half-precision ones this reader exists\n * to support — so it looks like nothing is broken until a `predict()` throws\n * `Unexpected input data type`. That is how a 1 MB ceiling on the graph\n * descent shipped in 0.9.0 and reached a consumer.\n */\nfunction warnOnUnreadableTypes(): void {\n console.warn(\n \"Could not read any input type from this model's bytes; feeds will be built as float32. \" +\n \"A half-precision model will fail at inference with 'Unexpected input data type'. \" +\n \"Please report this with the model that produced it.\",\n );\n}\n\n/**\n * Refuse a half-precision model in an environment that cannot feed one.\n *\n * ORT requires a real `Float16Array` for a `float16` tensor — the same bits in\n * a `Uint16Array` are rejected — and not every browser has one yet. Without\n * this check the session builds happily and the first `predict()` throws from\n * inside the preprocessing, which is both later and further from the cause.\n *\n * @param inputTypes Tensor type per input name.\n * @throws {@link ModelLoadError} when the graph wants half precision and the\n * runtime has no `Float16Array`.\n */\nfunction assertFeedableTypes(inputTypes: Readonly<Record<string, string>>): void {\n const half = Object.entries(inputTypes).filter(([, type]) => type === \"float16\");\n if (half.length === 0 || hasFloat16Array()) return;\n const names = half.map(([name]) => name).join(\", \");\n throw new ModelLoadError(\n `This model declares half-precision input(s) [${names}], but this environment has no ` +\n \"Float16Array, which ONNX Runtime requires for a float16 tensor. Use a float32 export \" +\n \"of the model, or run in a browser that supports Float16Array.\",\n );\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names and the shapes the graph declares,\n * manages execution-provider selection, provides a typed {@link OrtSession.run}\n * method, and releases the native session through {@link OrtSession.release}.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n /**\n * Execution providers this session is expected to run on.\n *\n * The requested list narrowed to what this browser can actually offer — a\n * `webgpu` entry survives only where an adapter exists. Best-effort: ORT-Web\n * exposes no way to ask which provider a session ended up on, so an entry\n * here means \"not ruled out\", not \"confirmed\". See\n * {@link requestedProviders} for what was asked for.\n *\n * When nothing survives — a caller asking for `webgpu` alone on a device\n * without it — this falls back to {@link FALLBACK_PROVIDER}, which ORT-Web\n * can always run. Handing ORT the unsatisfiable list instead makes\n * `InferenceSession.create` reject with \"no available backend found\", so the\n * page gets no inference at all rather than the slow-but-working fallback\n * the `console.warn` describes. Measured in a real Chromium, where\n * `navigator.gpu` exists but yields no adapter.\n */\n public readonly providers: readonly string[],\n private readonly _metadata: Readonly<Record<string, string>>,\n /**\n * Execution providers that were asked for, after defaults were applied.\n *\n * Kept separate because ORT-Web falls back silently: a page that asks for\n * `webgpu` on a device without it runs on WASM and is told nothing.\n */\n public readonly requestedProviders: readonly string[],\n /**\n * Tensor type each input declares, keyed by input name.\n *\n * Read from the model file, not from the session: `inputMetadata` is\n * `undefined` on `onnxruntime-web` 1.20.1. Empty when the bytes were never\n * in hand — a URL loaded with `readMetadata: false` — in which case every\n * feed is built as float32, the behaviour before this existed.\n */\n private readonly _inputTypes: Readonly<Record<string, string>> = {},\n ) {}\n\n /**\n * Tail of the run queue: settles when the latest queued run has finished.\n *\n * See {@link run} for why runs are serialized.\n */\n private _runQueue: Promise<unknown> = Promise.resolve();\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * The metadata map is read **before** the session is built, and that order is\n * load-bearing on memory-constrained devices. ORT copies the model into its\n * WASM heap and then allocates the graph and the weights on top of that copy;\n * a `readModelMetadata` call placed after `InferenceSession.create` keeps the\n * JavaScript-side buffer reachable across the whole build, so a 5 MB model\n * costs 5 MB of JS heap plus 5 MB of WASM heap plus the weights at the same\n * instant. Reading first makes the buffer collectable as soon as ORT has copied\n * it — on a phone that was the difference between a session and\n * `Can't create a session. failed to allocate a buffer of size N`.\n *\n * The provider probe and the model download run concurrently: neither\n * depends on the other, and on a real GPU `requestAdapter()` is not free.\n * When the model is downloaded here, ORT's runtime is started alongside the\n * download too — see {@link warmRuntime}.\n *\n * A model whose metadata carries {@link GRAPH_OPTIMIZATION_KEY} was already\n * optimized offline by the Python SDK's `optimize_model`, so it is loaded\n * with `graphOptimizationLevel: \"disabled\"` instead of paying the optimizer a\n * second time — measured on a YOLO11n-seg under WASM, 29 ms of session\n * creation down to 12 ms with unchanged inference time. An explicit\n * `graphOptimizationLevel` in `sessionOptions` always wins. The mark is read\n * with the rest of the metadata, so `readMetadata: false` skips it too.\n *\n * @param model Either a URL string, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list, pass-through `SessionOptions`, and whether to\n * read the model's metadata map (see {@link OrtSessionOptions.readMetadata}).\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const requested = resolveProviders(options.providers);\n const wantsMetadata = options.readMetadata !== false;\n const cacheName =\n options.cache === true ? DEFAULT_MODEL_CACHE : options.cache ? options.cache : null;\n const shouldFetch = typeof model === \"string\" && (wantsMetadata || cacheName !== null);\n const detection = detectProviders(requested).then((detected) =>\n detected.length > 0 ? detected : [FALLBACK_PROVIDER],\n );\n const [detected, source] = await Promise.all([\n detection,\n shouldFetch ? fetchModel(model, cacheName) : Promise.resolve(model),\n shouldFetch ? detection.then(warmRuntime) : Promise.resolve(),\n ]);\n const metadata =\n wantsMetadata && typeof source !== \"string\" ? readModelMetadata(source) : {};\n const specs = keepQuantizedOffWebGpu(detected, metadata);\n const requestedNames = requested.map(providerName);\n const providers = specs.map(providerName);\n if (options.providers !== undefined && options.providers.length > 0) {\n warnOnDroppedProviders(requestedNames, detected.map(providerName));\n }\n if (metadata[GRAPH_OPTIMIZATION_KEY] !== undefined && providers.includes(\"webgpu\")) {\n warnPreOptimizedOnWebGpu();\n }\n const preOptimized =\n metadata[GRAPH_OPTIMIZATION_KEY] !== undefined &&\n options.sessionOptions?.graphOptimizationLevel === undefined;\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(preOptimized ? { graphOptimizationLevel: \"disabled\" as const } : {}),\n ...(options.sessionOptions ?? {}),\n executionProviders: specs as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n const inputTypes = typeof source !== \"string\" ? declaredInputTypes(source) : {};\n if (typeof source !== \"string\" && Object.keys(inputTypes).length === 0) {\n warnOnUnreadableTypes();\n }\n assertFeedableTypes(inputTypes);\n\n let session: ort.InferenceSession;\n try {\n if (typeof source === \"string\") {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else if (source instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n source as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers, metadata, requestedNames, inputTypes);\n }\n\n /**\n * Tensor type each input declares, in declaration order.\n *\n * `\"float32\"` for a normal export, `\"float16\"` for one exported with\n * `half=True`. ORT matches a feed's type against this exactly, so the tasks\n * read it and convert at the feed boundary.\n */\n get inputDtypes(): readonly string[] {\n return this.inputNames.map((name) => this._inputTypes[name] ?? DEFAULT_TENSOR_TYPE);\n }\n\n /** Tensor type the first input declares. */\n get inputDtype(): string {\n return this._inputTypes[this.inputName] ?? DEFAULT_TENSOR_TYPE;\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /**\n * Shapes the graph declares for its inputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Empty shapes mean the runtime\n * reported no metadata — either a non-tensor input, or an `onnxruntime-web`\n * older than 1.21, which predates input metadata.\n */\n get inputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.inputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first input, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get inputShape(): DeclaredShape {\n return this.inputShapes[0] ?? [];\n }\n\n /**\n * Shapes the graph declares for its outputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Reading them is how a task can\n * tell how many classes a head emits without being told.\n */\n get outputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.outputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first output, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get outputShape(): DeclaredShape {\n return this.outputShapes[0] ?? [];\n }\n\n /**\n * The model's custom metadata map — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export.\n *\n * Read from the model's bytes at load time, since the runtime does not expose\n * it. Empty when the session was created with `readMetadata: false`, from a\n * URL that could not be fetched here, or from a model carrying no metadata.\n */\n get metadata(): Readonly<Record<string, string>> {\n return this._metadata;\n }\n\n /**\n * Release the native session and free its memory.\n *\n * Call it when a session is discarded while the page lives on — rebuilding a\n * task at a different input size, swapping in a newer model. A failure from\n * the runtime is ignored: a session being torn down has nothing left to fail\n * at, and the caller is already moving on.\n */\n async release(): Promise<void> {\n await this._session.release().catch(() => undefined);\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * Runs on one session are serialized. ONNX Runtime Web refuses a second\n * `run` while one is in flight — it rejects with `Session already started` —\n * so two overlapping `predict()` calls on the same task used to fail. Queued\n * here, they overlap where they can: while one run executes (in a worker,\n * with `env.wasm.proxy`, or on the GPU), the next `predict()` decodes and\n * preprocesses its frame and only waits for its turn at the runtime. A run\n * that fails does not block the ones behind it.\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 run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n const turn = this._runQueue.then(() => this._runNow(feeds));\n this._runQueue = turn.catch(() => undefined);\n return turn;\n }\n\n /**\n * Execute one run immediately; only {@link run}'s queue calls this.\n *\n * @param feeds Map of input name to `ort.Tensor`.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n private async _runNow(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(this._asDeclaredTypes(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 * Rebuild any feed whose type does not match what its input declares.\n *\n * ORT matches feed types against the graph exactly: a float32 tensor against\n * a `half=True` export fails the run with `Unexpected input data type`. Every\n * preprocessing path in this SDK produces `Float32Array`, on purpose — the\n * normalization arithmetic belongs in single precision — so the conversion\n * happens here, once, at the only boundary all of them pass through. A feed\n * that already carries the declared type is handed on untouched, so a caller\n * building its own half tensor pays nothing.\n *\n * @param feeds The tensors to run with.\n * @returns The same mapping, with mismatched float32 feeds converted.\n */\n private _asDeclaredTypes(feeds: Record<string, ort.Tensor>): Record<string, ort.Tensor> {\n let converted: Record<string, ort.Tensor> | null = null;\n for (const [name, tensor] of Object.entries(feeds)) {\n const declared = this._inputTypes[name];\n if (declared === undefined || declared === tensor.type) continue;\n if (!(tensor.data instanceof Float32Array)) continue;\n const data = toFeedData(tensor.data, declared);\n if (data === tensor.data) continue;\n converted ??= { ...feeds };\n converted[name] = new ortRuntime.Tensor(\n declared as \"float16\",\n data as unknown as Float32Array,\n tensor.dims as number[],\n );\n }\n return converted ?? feeds;\n }\n}\n"],"mappings":"oPA8BA,IAAa,EAAyB,oCAQhC,EACF,mHAGE,EAAiB,IAAI,IAmB3B,SAAS,EAAY,EAA+C,CAChE,IAAM,EAAM,EAAM,IAAI,EAAA,YAAY,CAAC,CAAC,KAAK,GAAG,EACxC,EAAU,EAAe,IAAI,CAAG,EAgBpC,OAfI,IAAY,IAAA,KACZ,GAAW,SAAY,CACnB,GAAI,CACA,IAAM,E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U,SAAW,KAAK,QAAQ,CAAK,CAAC,EAE1D,MADA,MAAK,UAAY,EAAK,UAAY,IAAA,EAAS,EACpC,CACX,CAQA,MAAc,QAAQ,EAAwE,CAC1F,GAAI,CAEA,OAAO,MADc,KAAK,SAAS,IAAI,KAAK,iBAAiB,CAAK,CAAC,CAEvE,OAAS,EAAK,CACV,MAAM,IAAI,EAAA,eAAe,qBAAsB,EAAc,UAAW,CAAE,MAAO,CAAI,CAAC,CAC1F,CACJ,CAgBA,iBAAyB,EAA+D,CACpF,IAAI,EAA+C,KACnD,IAAK,GAAM,CAAC,EAAM,KAAW,OAAO,QAAQ,CAAK,EAAG,CAChD,IAAM,EAAW,KAAK,YAAY,GAElC,GADI,IAAa,IAAA,IAAa,IAAa,EAAO,MAC9C,EAAE,EAAO,gBAAgB,cAAe,SAC5C,IAAM,EAAO,EAAA,WAAW,EAAO,KAAM,CAAQ,EACzC,IAAS,EAAO,OACpB,IAAc,CAAE,GAAG,CAAM,EACzB,EAAU,GAAQ,IAAI,EAAW,OAC7B,EACA,EACA,EAAO,IACX,EACJ,CACA,OAAO,GAAa,CACxB,CACJ"}
@@ -1,45 +1,119 @@
1
1
  import { InferenceError as e, ModelLoadError as t } from "./exceptions.js";
2
- import { declaredShapesFrom as n } from "./graph.js";
3
- import { readModelMetadata as r } from "./metadata.js";
4
- import { FALLBACK_PROVIDER as i, detectProviders as a, resolveProviders as o } from "./providers.js";
5
- import * as s from "onnxruntime-web";
2
+ import { hasFloat16Array as n, tensorTypeFor as r, toFeedData as i } from "./dtypes.js";
3
+ import { declaredShapesFrom as a } from "./graph.js";
4
+ import { readModelInputTypes as o, readModelMetadata as s } from "./metadata.js";
5
+ import { FALLBACK_PROVIDER as c, detectProviders as l, providerName as u, resolveProviders as d } from "./providers.js";
6
+ import * as f from "onnxruntime-web";
6
7
  //#region src/vision/core/session.ts
7
- async function c(e) {
8
+ var p = "ort_vision_sdk.graph_optimization", m = "CAcSDm9ydC12aXNpb24tc2RrOjoKEAoBeBIBeSIISWRlbnRpdHkSBHdhcm1aDwoBeBIKCggIARIECgIIAWIPCgF5EgoKCAgBEgQKAggBQgQKABAN", h = /* @__PURE__ */ new Map();
9
+ function g(e) {
10
+ let t = e.map(u).join(","), n = h.get(t);
11
+ return n === void 0 && (n = (async () => {
12
+ try {
13
+ let t = Uint8Array.from(atob(m), (e) => e.charCodeAt(0));
14
+ await (await f.InferenceSession.create(t, { executionProviders: e })).release();
15
+ } catch {
16
+ return;
17
+ }
18
+ })(), h.set(t, n)), n;
19
+ }
20
+ function _() {
21
+ console.warn("[@ort-vision-sdk/web] This model was pre-optimized by optimize_model, which targets the WASM backend; on WebGPU some of its fused nodes fall back to the CPU. For WebGPU, ship the original export instead.");
22
+ }
23
+ var v = "ort_vision_sdk.quantization";
24
+ function y(e, t) {
25
+ if (t["ort_vision_sdk.quantization"] === void 0) return [...e];
26
+ let n = e.filter((e) => u(e) !== "webgpu");
27
+ return n.length === e.length ? n : (console.warn(`[@ort-vision-sdk/web] This model was quantized by quantize_model (${t[v]}); ONNX Runtime Web's WebGPU backend cannot run its quantized operators, so it runs on WASM.`), n.length > 0 ? n : [c]);
28
+ }
29
+ var b = "ort-vision-sdk-models";
30
+ async function x(e, t) {
31
+ let n = t === null ? null : await C(t);
32
+ if (n !== null) {
33
+ let t = await n.match(e).catch(() => void 0);
34
+ if (t !== void 0) return new Uint8Array(await t.arrayBuffer());
35
+ }
8
36
  try {
9
37
  let t = await fetch(e);
10
- return t.ok ? new Uint8Array(await t.arrayBuffer()) : (l(e, `HTTP ${t.status} ${t.statusText}`), e);
38
+ if (!t.ok) return w(e, `HTTP ${t.status} ${t.statusText}`), e;
39
+ let r = await t.arrayBuffer();
40
+ return n !== null && await S(n, e, r), new Uint8Array(r);
11
41
  } catch (t) {
12
- return l(e, t.message), e;
42
+ return w(e, t.message), e;
13
43
  }
14
44
  }
15
- function l(e, t) {
45
+ async function S(e, t, n) {
46
+ try {
47
+ await e.put(t, new Response(n));
48
+ } catch {
49
+ return;
50
+ }
51
+ }
52
+ async function C(e) {
53
+ if (typeof caches > "u") return null;
54
+ try {
55
+ return await caches.open(e);
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+ function w(e, t) {
16
61
  console.warn(`[@ort-vision-sdk/web] Could not fetch ${e} to read its metadata (${t}). Letting ONNX Runtime load it instead: the model will work, but its baked-in class names are unavailable, so labels fall back to class_0, class_1, ... Pass \`labels\` explicitly to name them.`);
17
62
  }
18
- function u(e, t) {
63
+ function T(e, t) {
19
64
  let n = e.filter((e) => !t.includes(e));
20
65
  n.length !== 0 && console.warn(`This browser cannot offer the requested execution provider(s) ${JSON.stringify(n)}; the session will run on ${JSON.stringify(t)}. Inference still produces correct results, on the fallback provider.`);
21
66
  }
22
- var d = class l {
67
+ function E(e) {
68
+ let t = o(e), n = {};
69
+ for (let [e, i] of Object.entries(t)) n[e] = r(i);
70
+ return n;
71
+ }
72
+ function D() {
73
+ console.warn("Could not read any input type from this model's bytes; feeds will be built as float32. A half-precision model will fail at inference with 'Unexpected input data type'. Please report this with the model that produced it.");
74
+ }
75
+ function O(e) {
76
+ let r = Object.entries(e).filter(([, e]) => e === "float16");
77
+ if (r.length === 0 || n()) return;
78
+ let i = r.map(([e]) => e).join(", ");
79
+ throw new t(`This model declares half-precision input(s) [${i}], but this environment has no Float16Array, which ONNX Runtime requires for a float16 tensor. Use a float32 export of the model, or run in a browser that supports Float16Array.`);
80
+ }
81
+ var k = class n {
23
82
  _session;
24
83
  providers;
25
84
  _metadata;
26
85
  requestedProviders;
27
- constructor(e, t, n, r) {
28
- this._session = e, this.providers = t, this._metadata = n, this.requestedProviders = r;
29
- }
30
- static async create(e, n = {}) {
31
- let d = o(n.providers), f = await a(d), p = f.length > 0 ? f : [i];
32
- n.providers !== void 0 && n.providers.length > 0 && u(d, p);
33
- let m = {
34
- ...n.sessionOptions ?? {},
35
- executionProviders: p
36
- }, h = n.readMetadata !== !1, g = typeof e == "string" && h ? await c(e) : e, _ = h && typeof g != "string" ? r(g) : {}, v;
86
+ _inputTypes;
87
+ constructor(e, t, n, r, i = {}) {
88
+ this._session = e, this.providers = t, this._metadata = n, this.requestedProviders = r, this._inputTypes = i;
89
+ }
90
+ _runQueue = Promise.resolve();
91
+ static async create(e, r = {}) {
92
+ let i = d(r.providers), a = r.readMetadata !== !1, o = r.cache === !0 ? b : r.cache ? r.cache : null, p = typeof e == "string" && (a || o !== null), m = l(i).then((e) => e.length > 0 ? e : [c]), [h, v] = await Promise.all([
93
+ m,
94
+ p ? x(e, o) : Promise.resolve(e),
95
+ p ? m.then(g) : Promise.resolve()
96
+ ]), S = a && typeof v != "string" ? s(v) : {}, C = y(h, S), w = i.map(u), k = C.map(u);
97
+ r.providers !== void 0 && r.providers.length > 0 && T(w, h.map(u)), S["ort_vision_sdk.graph_optimization"] !== void 0 && k.includes("webgpu") && _();
98
+ let A = {
99
+ ...S["ort_vision_sdk.graph_optimization"] !== void 0 && r.sessionOptions?.graphOptimizationLevel === void 0 ? { graphOptimizationLevel: "disabled" } : {},
100
+ ...r.sessionOptions ?? {},
101
+ executionProviders: C
102
+ }, j = typeof v == "string" ? {} : E(v);
103
+ typeof v != "string" && Object.keys(j).length === 0 && D(), O(j);
104
+ let M;
37
105
  try {
38
- v = (typeof g == "string" || g instanceof Uint8Array, await s.InferenceSession.create(g, m));
106
+ M = (typeof v == "string" || v instanceof Uint8Array, await f.InferenceSession.create(v, A));
39
107
  } catch (e) {
40
108
  throw new t(`Failed to load ONNX model: ${e.message}`, { cause: e });
41
109
  }
42
- return new l(v, p, _, d);
110
+ return new n(M, k, S, w, j);
111
+ }
112
+ get inputDtypes() {
113
+ return this.inputNames.map((e) => this._inputTypes[e] ?? "float32");
114
+ }
115
+ get inputDtype() {
116
+ return this._inputTypes[this.inputName] ?? "float32";
43
117
  }
44
118
  get inputNames() {
45
119
  return this._session.inputNames;
@@ -53,13 +127,13 @@ var d = class l {
53
127
  return this._session.outputNames;
54
128
  }
55
129
  get inputShapes() {
56
- return n(this._session.inputMetadata);
130
+ return a(this._session.inputMetadata);
57
131
  }
58
132
  get inputShape() {
59
133
  return this.inputShapes[0] ?? [];
60
134
  }
61
135
  get outputShapes() {
62
- return n(this._session.outputMetadata);
136
+ return a(this._session.outputMetadata);
63
137
  }
64
138
  get outputShape() {
65
139
  return this.outputShapes[0] ?? [];
@@ -73,15 +147,29 @@ var d = class l {
73
147
  get raw() {
74
148
  return this._session;
75
149
  }
76
- async run(t) {
150
+ run(e) {
151
+ let t = this._runQueue.then(() => this._runNow(e));
152
+ return this._runQueue = t.catch(() => void 0), t;
153
+ }
154
+ async _runNow(t) {
77
155
  try {
78
- return await this._session.run(t);
156
+ return await this._session.run(this._asDeclaredTypes(t));
79
157
  } catch (t) {
80
158
  throw new e(`Inference failed: ${t.message}`, { cause: t });
81
159
  }
82
160
  }
161
+ _asDeclaredTypes(e) {
162
+ let t = null;
163
+ for (let [n, r] of Object.entries(e)) {
164
+ let a = this._inputTypes[n];
165
+ if (a === void 0 || a === r.type || !(r.data instanceof Float32Array)) continue;
166
+ let o = i(r.data, a);
167
+ o !== r.data && (t ??= { ...e }, t[n] = new f.Tensor(a, o, r.dims));
168
+ }
169
+ return t ?? e;
170
+ }
83
171
  };
84
172
  //#endregion
85
- export { d as OrtSession };
173
+ export { b as DEFAULT_MODEL_CACHE, p as GRAPH_OPTIMIZATION_KEY, k as OrtSession, v as QUANTIZATION_KEY };
86
174
 
87
175
  //# sourceMappingURL=session.js.map