{"version":3,"file":"metadata.cjs","names":[],"sources":["../../../src/vision/core/metadata.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Read the metadata an exporter baked into a `.onnx` file.\n *\n * `onnxruntime-web` exposes input/output metadata but **not** the model's\n * custom metadata map, which is where Ultralytics writes `names`, `task` and\n * `imgsz`. The Python SDK gets it for free from\n * `InferenceSession.get_modelmeta().custom_metadata_map`; in the browser the\n * only way to the same information is to read it out of the file, so this\n * module walks just enough of the ModelProto wire format to collect\n * `metadata_props`.\n *\n * It never throws and never allocates unbounded: a truncated, hostile or\n * simply unexpected file yields an empty map, and every caller treats that as\n * \"the model says nothing\", falling back to what it was given.\n */\n\n/** Field number of `metadata_props` in `ModelProto` (repeated StringStringEntryProto). */\nconst MODEL_METADATA_PROPS_FIELD = 14;\n\n/** Field numbers of `key` and `value` in `StringStringEntryProto`. */\nconst ENTRY_KEY_FIELD = 1;\nconst ENTRY_VALUE_FIELD = 2;\n\n/** Protobuf wire types this reader understands. */\nconst WIRE_VARINT = 0;\nconst WIRE_FIXED64 = 1;\nconst WIRE_LENGTH_DELIMITED = 2;\nconst WIRE_FIXED32 = 5;\n\n/**\n * Hard ceiling on a single length-delimited field, as a guard against a corrupt\n * length turning into a huge slice. Model metadata values are strings — a class\n * name map for thousands of classes still fits well inside this.\n */\nconst MAX_FIELD_BYTES = 1 << 20;\n\n/** A cursor over a byte range, tracking its own position. */\ninterface Cursor {\n    readonly bytes: Uint8Array;\n    readonly end: number;\n    pos: number;\n}\n\n/**\n * Read a base-128 varint.\n *\n * @param cursor Cursor to advance.\n * @returns The value, or `null` when the varint is truncated or overlong\n *   (beyond the 64-bit range protobuf allows).\n */\nfunction readVarint(cursor: Cursor): number | null {\n    let result = 0;\n    let shift = 0;\n    while (cursor.pos < cursor.end) {\n        const byte = cursor.bytes[cursor.pos]!;\n        cursor.pos += 1;\n        result += (byte & 0x7f) * 2 ** shift;\n        if ((byte & 0x80) === 0) return result;\n        shift += 7;\n        if (shift > 63) return null;\n    }\n    return null;\n}\n\n/**\n * Skip a field whose contents are not needed.\n *\n * @param cursor Cursor to advance past the field's payload.\n * @param wireType Wire type read from the field's tag.\n * @returns `true` when the field was skipped, `false` when the stream is\n *   unreadable from here (unknown wire type or truncated payload).\n */\nfunction skipField(cursor: Cursor, wireType: number): boolean {\n    switch (wireType) {\n        case WIRE_VARINT:\n            return readVarint(cursor) !== null;\n        case WIRE_FIXED64:\n            cursor.pos += 8;\n            return cursor.pos <= cursor.end;\n        case WIRE_LENGTH_DELIMITED: {\n            const length = readVarint(cursor);\n            if (length === null) return false;\n            cursor.pos += length;\n            return cursor.pos <= cursor.end;\n        }\n        case WIRE_FIXED32:\n            cursor.pos += 4;\n            return cursor.pos <= cursor.end;\n        default:\n            return false;\n    }\n}\n\n/**\n * Read a length-delimited payload as a byte range.\n *\n * @param cursor Cursor to advance past the payload.\n * @returns Start and end offsets of the payload, or `null` when the length is\n *   truncated, overruns the buffer, or exceeds {@link MAX_FIELD_BYTES}.\n */\nfunction readLengthDelimited(cursor: Cursor): { start: number; end: number } | null {\n    const length = readVarint(cursor);\n    if (length === null || length > MAX_FIELD_BYTES) return null;\n    const start = cursor.pos;\n    const end = start + length;\n    if (end > cursor.end) return null;\n    cursor.pos = end;\n    return { start, end };\n}\n\n/**\n * Decode one `StringStringEntryProto` into a key/value pair.\n *\n * @param bytes The model buffer.\n * @param start Offset the entry's payload starts at.\n * @param end Offset the entry's payload ends at.\n * @returns The pair, or `null` when either half is missing or undecodable.\n */\nfunction readEntry(\n    bytes: Uint8Array,\n    start: number,\n    end: number,\n): readonly [string, string] | null {\n    const cursor: Cursor = { bytes, end, pos: start };\n    const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n    let key: string | null = null;\n    let value: string | null = null;\n\n    while (cursor.pos < end) {\n        const tag = readVarint(cursor);\n        if (tag === null) return null;\n        const field = tag >>> 3;\n        const wireType = tag & 0x07;\n        if (\n            wireType === WIRE_LENGTH_DELIMITED &&\n            (field === ENTRY_KEY_FIELD || field === ENTRY_VALUE_FIELD)\n        ) {\n            const range = readLengthDelimited(cursor);\n            if (range === null) return null;\n            const text = decoder.decode(bytes.subarray(range.start, range.end));\n            if (field === ENTRY_KEY_FIELD) key = text;\n            else value = text;\n            continue;\n        }\n        if (!skipField(cursor, wireType)) return null;\n    }\n\n    if (key === null || value === null) return null;\n    return [key, value];\n}\n\n/**\n * Collect a model's custom metadata map straight out of its bytes.\n *\n * @param model The `.onnx` file contents.\n * @returns Key/value metadata — `names`, `task`, `imgsz`, ... for an\n *   Ultralytics export — or an empty object when the file carries none or\n *   cannot be walked.\n */\nexport function readModelMetadata(\n    model: Uint8Array | ArrayBufferLike,\n): Readonly<Record<string, string>> {\n    const bytes = model instanceof Uint8Array ? model : new Uint8Array(model);\n    const cursor: Cursor = { bytes, end: bytes.length, pos: 0 };\n    const metadata: Record<string, string> = {};\n\n    while (cursor.pos < cursor.end) {\n        const tag = readVarint(cursor);\n        if (tag === null) break;\n        const field = tag >>> 3;\n        const wireType = tag & 0x07;\n        if (field === MODEL_METADATA_PROPS_FIELD && wireType === WIRE_LENGTH_DELIMITED) {\n            const range = readLengthDelimited(cursor);\n            if (range === null) break;\n            const entry = readEntry(bytes, range.start, range.end);\n            if (entry) metadata[entry[0]] = entry[1];\n            continue;\n        }\n        if (!skipField(cursor, wireType)) break;\n    }\n\n    return metadata;\n}\n\n/**\n * Read the class names an export baked into the model metadata.\n *\n * Ultralytics writes `names` as the Python `repr` of a `dict[int, str]` — e.g.\n * `\"{0: 'deworm', 1: 'not_deworm'}\"`. The value is parsed structurally (never\n * evaluated), and anything unparseable, non-`dict`, or not keyed by contiguous\n * integers from zero is rejected whole rather than half-applied: a partial name\n * map would silently mislabel predictions.\n *\n * @param metadata A model's custom metadata map.\n * @returns Class names in class-id order, or `null` when the model carries no\n *   usable `names` entry.\n */\nexport function modelNames(\n    metadata: Readonly<Record<string, string>> | undefined,\n): readonly string[] | null {\n    return parseNames(metadata?.names);\n}\n\n/**\n * Parse a `repr`-encoded `dict[int, str]` class map.\n *\n * Split out of {@link modelNames} because the same encoding is reused by a\n * fused pipeline, which carries one class map per stage and therefore cannot\n * store both under the single `names` key Ultralytics uses.\n *\n * @param encoded The encoded map — e.g. `\"{0: 'deworm', 1: 'not_deworm'}\"`.\n * @returns Class names in class-id order, or `null` when the value is missing,\n *   unparseable, not a `dict`, or not keyed by contiguous integers from zero.\n */\nexport function parseNames(encoded: string | undefined): readonly string[] | null {\n    const raw = encoded?.trim();\n    if (!raw || !raw.startsWith(\"{\") || !raw.endsWith(\"}\")) return null;\n\n    const body = raw.slice(1, -1).trim();\n    if (!body) return null;\n\n    const names = new Map<number, string>();\n    const entryPattern = /(-?\\d+)\\s*:\\s*(?:'((?:[^'\\\\]|\\\\.)*)'|\"((?:[^\"\\\\]|\\\\.)*)\")/g;\n    let consumed = 0;\n    for (const match of body.matchAll(entryPattern)) {\n        const id = Number(match[1]);\n        const text = match[2] ?? match[3];\n        if (!Number.isInteger(id) || text === undefined) return null;\n        names.set(id, unescapeQuoted(text));\n        consumed += match[0].length;\n    }\n    if (names.size === 0) return null;\n\n    const separators = body.length - consumed;\n    if (separators > names.size * 3) return null;\n\n    const ordered: string[] = [];\n    for (let id = 0; id < names.size; id += 1) {\n        const name = names.get(id);\n        if (name === undefined) return null;\n        ordered.push(name);\n    }\n    return ordered;\n}\n\n/**\n * Resolve the backslash escapes Python's `repr` emits inside a quoted string.\n *\n * @param text The quoted string's contents, escapes intact.\n * @returns The same text with `\\\\`, `\\'`, `\\\"`, `\\n`, `\\r` and `\\t` resolved.\n */\nfunction unescapeQuoted(text: string): string {\n    return text.replace(/\\\\(.)/g, (_, char: string) => {\n        if (char === \"n\") return \"\\n\";\n        if (char === \"r\") return \"\\r\";\n        if (char === \"t\") return \"\\t\";\n        return char;\n    });\n}\n"],"mappings":"AAmDA,SAAS,EAAW,EAA+B,CAC/C,IAAI,E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