/******/ var __webpack_modules__ = ({

/***/ "./node_modules/onnxruntime-common/dist/lib/backend-impl.js":
/*!******************************************************************!*\
  !*** ./node_modules/onnxruntime-common/dist/lib/backend-impl.js ***!
  \******************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "registerBackend": () => (/* binding */ registerBackend),
/* harmony export */   "resolveBackend": () => (/* binding */ resolveBackend)
/* harmony export */ });
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const backends = {};
const backendsSortedByPriority = [];
/**
 * Register a backend.
 *
 * @param name - the name as a key to lookup as an execution provider.
 * @param backend - the backend object.
 * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority
 * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default.
 *
 * @internal
 */
const registerBackend = (name, backend, priority) => {
    if (backend && typeof backend.init === 'function' && typeof backend.createSessionHandler === 'function') {
        const currentBackend = backends[name];
        if (currentBackend === undefined) {
            backends[name] = { backend, priority };
        }
        else if (currentBackend.priority > priority) {
            // same name is already registered with a higher priority. skip registeration.
            return;
        }
        else if (currentBackend.priority === priority) {
            if (currentBackend.backend !== backend) {
                throw new Error(`cannot register backend "${name}" using priority ${priority}`);
            }
        }
        if (priority >= 0) {
            const i = backendsSortedByPriority.indexOf(name);
            if (i !== -1) {
                backendsSortedByPriority.splice(i, 1);
            }
            for (let i = 0; i < backendsSortedByPriority.length; i++) {
                if (backends[backendsSortedByPriority[i]].priority <= priority) {
                    backendsSortedByPriority.splice(i, 0, name);
                    return;
                }
            }
            backendsSortedByPriority.push(name);
        }
        return;
    }
    throw new TypeError('not a valid backend');
};
/**
 * Resolve backend by specified hints.
 *
 * @param backendHints - a list of execution provider names to lookup. If omitted use registered backends as list.
 * @returns a promise that resolves to the backend.
 *
 * @internal
 */
const resolveBackend = async (backendHints) => {
    const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;
    const errors = [];
    for (const backendName of backendNames) {
        const backendInfo = backends[backendName];
        if (backendInfo) {
            if (backendInfo.initialized) {
                return backendInfo.backend;
            }
            else if (backendInfo.aborted) {
                continue; // current backend is unavailable; try next
            }
            const isInitializing = !!backendInfo.initPromise;
            try {
                if (!isInitializing) {
                    backendInfo.initPromise = backendInfo.backend.init();
                }
                await backendInfo.initPromise;
                backendInfo.initialized = true;
                return backendInfo.backend;
            }
            catch (e) {
                if (!isInitializing) {
                    errors.push({ name: backendName, err: e });
                }
                backendInfo.aborted = true;
            }
            finally {
                delete backendInfo.initPromise;
            }
        }
    }
    throw new Error(`no available backend found. ERR: ${errors.map(e => `[${e.name}] ${e.err}`).join(', ')}`);
};
//# sourceMappingURL=backend-impl.js.map

/***/ }),

/***/ "./node_modules/onnxruntime-common/dist/lib/backend.js":
/*!*************************************************************!*\
  !*** ./node_modules/onnxruntime-common/dist/lib/backend.js ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "registerBackend": () => (/* reexport safe */ _backend_impl__WEBPACK_IMPORTED_MODULE_0__.registerBackend)
/* harmony export */ });
/* harmony import */ var _backend_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend-impl */ "./node_modules/onnxruntime-common/dist/lib/backend-impl.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//# sourceMappingURL=backend.js.map

/***/ }),

/***/ "./node_modules/onnxruntime-common/dist/lib/env-impl.js":
/*!**************************************************************!*\
  !*** ./node_modules/onnxruntime-common/dist/lib/env-impl.js ***!
  \**************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "EnvImpl": () => (/* binding */ EnvImpl)
/* harmony export */ });
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
class EnvImpl {
    constructor() {
        this.wasm = {};
        this.webgl = {};
        this.logLevelInternal = 'warning';
    }
    // TODO standadize the getter and setter convention in env for other fields.
    set logLevel(value) {
        if (value === undefined) {
            return;
        }
        if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {
            throw new Error(`Unsupported logging level: ${value}`);
        }
        this.logLevelInternal = value;
    }
    get logLevel() {
        return this.logLevelInternal;
    }
}
//# sourceMappingURL=env-impl.js.map

/***/ }),

/***/ "./node_modules/onnxruntime-common/dist/lib/env.js":
/*!*********************************************************!*\
  !*** ./node_modules/onnxruntime-common/dist/lib/env.js ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "env": () => (/* binding */ env)
/* harmony export */ });
/* harmony import */ var _env_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env-impl */ "./node_modules/onnxruntime-common/dist/lib/env-impl.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

/**
 * Represent a set of flags as a global singleton.
 */
const env = new _env_impl__WEBPACK_IMPORTED_MODULE_0__.EnvImpl();
//# sourceMappingURL=env.js.map

/***/ }),

/***/ "./node_modules/onnxruntime-common/dist/lib/index.js":
/*!***********************************************************!*\
  !*** ./node_modules/onnxruntime-common/dist/lib/index.js ***!
  \***********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "InferenceSession": () => (/* reexport safe */ _inference_session__WEBPACK_IMPORTED_MODULE_2__.InferenceSession),
/* harmony export */   "Tensor": () => (/* reexport safe */ _tensor__WEBPACK_IMPORTED_MODULE_3__.Tensor),
/* harmony export */   "env": () => (/* reexport safe */ _env__WEBPACK_IMPORTED_MODULE_1__.env),
/* harmony export */   "registerBackend": () => (/* reexport safe */ _backend__WEBPACK_IMPORTED_MODULE_0__.registerBackend)
/* harmony export */ });
/* harmony import */ var _backend__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend */ "./node_modules/onnxruntime-common/dist/lib/backend.js");
/* harmony import */ var _env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./env */ "./node_modules/onnxruntime-common/dist/lib/env.js");
/* harmony import */ var _inference_session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./inference-session */ "./node_modules/onnxruntime-common/dist/lib/inference-session.js");
/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tensor */ "./node_modules/onnxruntime-common/dist/lib/tensor.js");
/* harmony import */ var _onnx_value__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./onnx-value */ "./node_modules/onnxruntime-common/dist/lib/onnx-value.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/**
 * # ONNX Runtime JavaScript API
 *
 * ONNX Runtime JavaScript API is a unified API for all JavaScript usages, including the following NPM packages:
 *
 * - [onnxruntime-node](https://www.npmjs.com/package/onnxruntime-node)
 * - [onnxruntime-web](https://www.npmjs.com/package/onnxruntime-web)
 * - [onnxruntime-react-native](https://www.npmjs.com/package/onnxruntime-react-native)
 *
 * See also:
 * - [Get Started](https://onnxruntime.ai/docs/get-started/with-javascript.html)
 * - [Inference examples](https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js)
 *
 * @packageDocumentation
 */





//# sourceMappingURL=index.js.map

/***/ }),

/***/ "./node_modules/onnxruntime-common/dist/lib/inference-session-impl.js":
/*!****************************************************************************!*\
  !*** ./node_modules/onnxruntime-common/dist/lib/inference-session-impl.js ***!
  \****************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "InferenceSession": () => (/* binding */ InferenceSession)
/* harmony export */ });
/* harmony import */ var _backend_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend-impl */ "./node_modules/onnxruntime-common/dist/lib/backend-impl.js");
/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tensor */ "./node_modules/onnxruntime-common/dist/lib/tensor.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.


class InferenceSession {
    constructor(handler) {
        this.handler = handler;
    }
    async run(feeds, arg1, arg2) {
        const fetches = {};
        let options = {};
        // check inputs
        if (typeof feeds !== 'object' || feeds === null || feeds instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor || Array.isArray(feeds)) {
            throw new TypeError('\'feeds\' must be an object that use input names as keys and OnnxValue as corresponding values.');
        }
        let isFetchesEmpty = true;
        // determine which override is being used
        if (typeof arg1 === 'object') {
            if (arg1 === null) {
                throw new TypeError('Unexpected argument[1]: cannot be null.');
            }
            if (arg1 instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor) {
                throw new TypeError('\'fetches\' cannot be a Tensor');
            }
            if (Array.isArray(arg1)) {
                if (arg1.length === 0) {
                    throw new TypeError('\'fetches\' cannot be an empty array.');
                }
                isFetchesEmpty = false;
                // output names
                for (const name of arg1) {
                    if (typeof name !== 'string') {
                        throw new TypeError('\'fetches\' must be a string array or an object.');
                    }
                    if (this.outputNames.indexOf(name) === -1) {
                        throw new RangeError(`'fetches' contains invalid output name: ${name}.`);
                    }
                    fetches[name] = null;
                }
                if (typeof arg2 === 'object' && arg2 !== null) {
                    options = arg2;
                }
                else if (typeof arg2 !== 'undefined') {
                    throw new TypeError('\'options\' must be an object.');
                }
            }
            else {
                // decide whether arg1 is fetches or options
                // if any output name is present and its value is valid OnnxValue, we consider it fetches
                let isFetches = false;
                const arg1Keys = Object.getOwnPropertyNames(arg1);
                for (const name of this.outputNames) {
                    if (arg1Keys.indexOf(name) !== -1) {
                        const v = arg1[name];
                        if (v === null || v instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor) {
                            isFetches = true;
                            isFetchesEmpty = false;
                            fetches[name] = v;
                        }
                    }
                }
                if (isFetches) {
                    if (typeof arg2 === 'object' && arg2 !== null) {
                        options = arg2;
                    }
                    else if (typeof arg2 !== 'undefined') {
                        throw new TypeError('\'options\' must be an object.');
                    }
                }
                else {
                    options = arg1;
                }
            }
        }
        else if (typeof arg1 !== 'undefined') {
            throw new TypeError('Unexpected argument[1]: must be \'fetches\' or \'options\'.');
        }
        // check if all inputs are in feed
        for (const name of this.inputNames) {
            if (typeof feeds[name] === 'undefined') {
                throw new Error(`input '${name}' is missing in 'feeds'.`);
            }
        }
        // if no fetches is specified, we use the full output names list
        if (isFetchesEmpty) {
            for (const name of this.outputNames) {
                fetches[name] = null;
            }
        }
        // feeds, fetches and options are prepared
        const results = await this.handler.run(feeds, fetches, options);
        const returnValue = {};
        for (const key in results) {
            if (Object.hasOwnProperty.call(results, key)) {
                returnValue[key] = new _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor(results[key].type, results[key].data, results[key].dims);
            }
        }
        return returnValue;
    }
    static async create(arg0, arg1, arg2, arg3) {
        // either load from a file or buffer
        let filePathOrUint8Array;
        let options = {};
        if (typeof arg0 === 'string') {
            filePathOrUint8Array = arg0;
            if (typeof arg1 === 'object' && arg1 !== null) {
                options = arg1;
            }
            else if (typeof arg1 !== 'undefined') {
                throw new TypeError('\'options\' must be an object.');
            }
        }
        else if (arg0 instanceof Uint8Array) {
            filePathOrUint8Array = arg0;
            if (typeof arg1 === 'object' && arg1 !== null) {
                options = arg1;
            }
            else if (typeof arg1 !== 'undefined') {
                throw new TypeError('\'options\' must be an object.');
            }
        }
        else if (arg0 instanceof ArrayBuffer ||
            (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)) {
            const buffer = arg0;
            let byteOffset = 0;
            let byteLength = arg0.byteLength;
            if (typeof arg1 === 'object' && arg1 !== null) {
                options = arg1;
            }
            else if (typeof arg1 === 'number') {
                byteOffset = arg1;
                if (!Number.isSafeInteger(byteOffset)) {
                    throw new RangeError('\'byteOffset\' must be an integer.');
                }
                if (byteOffset < 0 || byteOffset >= buffer.byteLength) {
                    throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);
                }
                byteLength = arg0.byteLength - byteOffset;
                if (typeof arg2 === 'number') {
                    byteLength = arg2;
                    if (!Number.isSafeInteger(byteLength)) {
                        throw new RangeError('\'byteLength\' must be an integer.');
                    }
                    if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {
                        throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);
                    }
                    if (typeof arg3 === 'object' && arg3 !== null) {
                        options = arg3;
                    }
                    else if (typeof arg3 !== 'undefined') {
                        throw new TypeError('\'options\' must be an object.');
                    }
                }
                else if (typeof arg2 !== 'undefined') {
                    throw new TypeError('\'byteLength\' must be a number.');
                }
            }
            else if (typeof arg1 !== 'undefined') {
                throw new TypeError('\'options\' must be an object.');
            }
            filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);
        }
        else {
            throw new TypeError('Unexpected argument[0]: must be \'path\' or \'buffer\'.');
        }
        // get backend hints
        const eps = options.executionProviders || [];
        const backendHints = eps.map(i => typeof i === 'string' ? i : i.name);
        const backend = await (0,_backend_impl__WEBPACK_IMPORTED_MODULE_0__.resolveBackend)(backendHints);
        const handler = await backend.createSessionHandler(filePathOrUint8Array, options);
        return new InferenceSession(handler);
    }
    startProfiling() {
        this.handler.startProfiling();
    }
    endProfiling() {
        this.handler.endProfiling();
    }
    get inputNames() {
        return this.handler.inputNames;
    }
    get outputNames() {
        return this.handler.outputNames;
    }
}
//# sourceMappingURL=inference-session-impl.js.map

/***/ }),

/***/ "./node_modules/onnxruntime-common/dist/lib/inference-session.js":
/*!***********************************************************************!*\
  !*** ./node_modules/onnxruntime-common/dist/lib/inference-session.js ***!
  \***********************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "InferenceSession": () => (/* binding */ InferenceSession)
/* harmony export */ });
/* harmony import */ var _inference_session_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./inference-session-impl */ "./node_modules/onnxruntime-common/dist/lib/inference-session-impl.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

// eslint-disable-next-line @typescript-eslint/naming-convention
const InferenceSession = _inference_session_impl__WEBPACK_IMPORTED_MODULE_0__.InferenceSession;
//# sourceMappingURL=inference-session.js.map

/***/ }),

/***/ "./node_modules/onnxruntime-common/dist/lib/onnx-value.js":
/*!****************************************************************!*\
  !*** ./node_modules/onnxruntime-common/dist/lib/onnx-value.js ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//# sourceMappingURL=onnx-value.js.map

/***/ }),

/***/ "./node_modules/onnxruntime-common/dist/lib/tensor-impl.js":
/*!*****************************************************************!*\
  !*** ./node_modules/onnxruntime-common/dist/lib/tensor-impl.js ***!
  \*****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Tensor": () => (/* binding */ Tensor)
/* harmony export */ });
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && typeof BigInt64Array.from === 'function';
const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && typeof BigUint64Array.from === 'function';
// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.
const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([
    ['float32', Float32Array],
    ['uint8', Uint8Array],
    ['int8', Int8Array],
    ['uint16', Uint16Array],
    ['int16', Int16Array],
    ['int32', Int32Array],
    ['bool', Uint8Array],
    ['float64', Float64Array],
    ['uint32', Uint32Array],
]);
// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.
const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map([
    [Float32Array, 'float32'],
    [Uint8Array, 'uint8'],
    [Int8Array, 'int8'],
    [Uint16Array, 'uint16'],
    [Int16Array, 'int16'],
    [Int32Array, 'int32'],
    [Float64Array, 'float64'],
    [Uint32Array, 'uint32'],
]);
if (isBigInt64ArrayAvailable) {
    NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);
    NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');
}
if (isBigUint64ArrayAvailable) {
    NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);
    NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');
}
/**
 * calculate size from dims.
 *
 * @param dims the dims array. May be an illegal input.
 */
const calculateSize = (dims) => {
    let size = 1;
    for (let i = 0; i < dims.length; i++) {
        const dim = dims[i];
        if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {
            throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);
        }
        if (dim < 0) {
            throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);
        }
        size *= dim;
    }
    return size;
};
class Tensor {
    constructor(arg0, arg1, arg2) {
        let type;
        let data;
        let dims;
        // check whether arg0 is type or data
        if (typeof arg0 === 'string') {
            //
            // Override: constructor(type, data, ...)
            //
            type = arg0;
            dims = arg2;
            if (arg0 === 'string') {
                // string tensor
                if (!Array.isArray(arg1)) {
                    throw new TypeError('A string tensor\'s data must be a string array.');
                }
                // we don't check whether every element in the array is string; this is too slow. we assume it's correct and
                // error will be populated at inference
                data = arg1;
            }
            else {
                // numeric tensor
                const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);
                if (typedArrayConstructor === undefined) {
                    throw new TypeError(`Unsupported tensor type: ${arg0}.`);
                }
                if (Array.isArray(arg1)) {
                    // use 'as any' here because TypeScript's check on type of 'SupportedTypedArrayConstructors.from()' produces
                    // incorrect results.
                    // 'typedArrayConstructor' should be one of the typed array prototype objects.
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    data = typedArrayConstructor.from(arg1);
                }
                else if (arg1 instanceof typedArrayConstructor) {
                    data = arg1;
                }
                else {
                    throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);
                }
            }
        }
        else {
            //
            // Override: constructor(data, ...)
            //
            dims = arg1;
            if (Array.isArray(arg0)) {
                // only boolean[] and string[] is supported
                if (arg0.length === 0) {
                    throw new TypeError('Tensor type cannot be inferred from an empty array.');
                }
                const firstElementType = typeof arg0[0];
                if (firstElementType === 'string') {
                    type = 'string';
                    data = arg0;
                }
                else if (firstElementType === 'boolean') {
                    type = 'bool';
                    // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is
                    // wrong type. We use 'as any' to make it happy.
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    data = Uint8Array.from(arg0);
                }
                else {
                    throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);
                }
            }
            else {
                // get tensor type from TypedArray
                const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor);
                if (mappedType === undefined) {
                    throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);
                }
                type = mappedType;
                data = arg0;
            }
        }
        // type and data is processed, now processing dims
        if (dims === undefined) {
            // assume 1-D tensor if dims omitted
            dims = [data.length];
        }
        else if (!Array.isArray(dims)) {
            throw new TypeError('A tensor\'s dims must be a number array');
        }
        // perform check
        const size = calculateSize(dims);
        if (size !== data.length) {
            throw new Error(`Tensor's size(${size}) does not match data length(${data.length}).`);
        }
        this.dims = dims;
        this.type = type;
        this.data = data;
        this.size = size;
    }
    // #endregion
    /**
     * Create a new tensor object from image object
     *
     * @param buffer - Extracted image buffer data - assuming RGBA format
     * @param imageFormat - input image configuration - required configurations height, width, format
     * @param tensorFormat - output tensor configuration - Default is RGB format
     */
    static bufferToTensor(buffer, options) {
        if (buffer === undefined) {
            throw new Error('Image buffer must be defined');
        }
        if (options.height === undefined || options.width === undefined) {
            throw new Error('Image height and width must be defined');
        }
        const { height, width } = options;
        const norm = options.norm;
        let normMean;
        let normBias;
        if (norm === undefined || norm.mean === undefined) {
            normMean = 255;
        }
        else {
            normMean = norm.mean;
        }
        if (norm === undefined || norm.bias === undefined) {
            normBias = 0;
        }
        else {
            normBias = norm.bias;
        }
        const inputformat = options.bitmapFormat !== undefined ? options.bitmapFormat : 'RGBA';
        // default value is RGBA since imagedata and HTMLImageElement uses it
        const outputformat = options.tensorFormat !== undefined ?
            (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') :
            'RGB';
        const offset = height * width;
        const float32Data = outputformat === 'RGBA' ? new Float32Array(offset * 4) : new Float32Array(offset * 3);
        // Default pointer assignments
        let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
        let rTensorPointer = 0, gTensorPointer = offset, bTensorPointer = offset * 2, aTensorPointer = -1;
        // Updating the pointer assignments based on the input image format
        if (inputformat === 'RGB') {
            step = 3;
            rImagePointer = 0;
            gImagePointer = 1;
            bImagePointer = 2;
            aImagePointer = -1;
        }
        // Updating the pointer assignments based on the output tensor format
        if (outputformat === 'RGBA') {
            aTensorPointer = offset * 3;
        }
        else if (outputformat === 'RBG') {
            rTensorPointer = 0;
            bTensorPointer = offset;
            gTensorPointer = offset * 2;
        }
        else if (outputformat === 'BGR') {
            bTensorPointer = 0;
            gTensorPointer = offset;
            rTensorPointer = offset * 2;
        }
        for (let i = 0; i < offset; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {
            float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias) / normMean;
            float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias) / normMean;
            float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias) / normMean;
            if (aTensorPointer !== -1 && aImagePointer !== -1) {
                float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias) / normMean;
            }
        }
        // Float32Array -> ort.Tensor
        const outputTensor = outputformat === 'RGBA' ? new Tensor('float32', float32Data, [1, 4, height, width]) :
            new Tensor('float32', float32Data, [1, 3, height, width]);
        return outputTensor;
    }
    static async fromImage(image, options) {
        // checking the type of image object
        const isHTMLImageEle = typeof (HTMLImageElement) !== 'undefined' && image instanceof HTMLImageElement;
        const isImageDataEle = typeof (ImageData) !== 'undefined' && image instanceof ImageData;
        const isImageBitmap = typeof (ImageBitmap) !== 'undefined' && image instanceof ImageBitmap;
        const isURL = typeof (String) !== 'undefined' && (image instanceof String || typeof image === 'string');
        let data;
        let tensorConfig = {};
        // filling and checking image configuration options
        if (isHTMLImageEle) {
            // HTMLImageElement - image object - format is RGBA by default
            const canvas = document.createElement('canvas');
            const pixels2DContext = canvas.getContext('2d');
            if (pixels2DContext != null) {
                let height = image.naturalHeight;
                let width = image.naturalWidth;
                if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {
                    height = options.resizedHeight;
                    width = options.resizedWidth;
                }
                if (options !== undefined) {
                    tensorConfig = options;
                    if (options.tensorFormat !== undefined) {
                        throw new Error('Image input config format must be RGBA for HTMLImageElement');
                    }
                    else {
                        tensorConfig.tensorFormat = 'RGBA';
                    }
                    if (options.height !== undefined && options.height !== height) {
                        throw new Error('Image input config height doesn\'t match HTMLImageElement height');
                    }
                    else {
                        tensorConfig.height = height;
                    }
                    if (options.width !== undefined && options.width !== width) {
                        throw new Error('Image input config width doesn\'t match HTMLImageElement width');
                    }
                    else {
                        tensorConfig.width = width;
                    }
                }
                else {
                    tensorConfig.tensorFormat = 'RGBA';
                    tensorConfig.height = height;
                    tensorConfig.width = width;
                }
                canvas.width = width;
                canvas.height = height;
                pixels2DContext.drawImage(image, 0, 0, width, height);
                data = pixels2DContext.getImageData(0, 0, width, height).data;
            }
            else {
                throw new Error('Can not access image data');
            }
        }
        else if (isImageDataEle) {
            // ImageData - image object - format is RGBA by default
            const format = 'RGBA';
            let height;
            let width;
            if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {
                height = options.resizedHeight;
                width = options.resizedWidth;
            }
            else {
                height = image.height;
                width = image.width;
            }
            if (options !== undefined) {
                tensorConfig = options;
                if (options.bitmapFormat !== undefined && options.bitmapFormat !== format) {
                    throw new Error('Image input config format must be RGBA for ImageData');
                }
                else {
                    tensorConfig.bitmapFormat = 'RGBA';
                }
            }
            else {
                tensorConfig.bitmapFormat = 'RGBA';
            }
            tensorConfig.height = height;
            tensorConfig.width = width;
            if (options !== undefined) {
                const tempCanvas = document.createElement('canvas');
                tempCanvas.width = width;
                tempCanvas.height = height;
                const pixels2DContext = tempCanvas.getContext('2d');
                if (pixels2DContext != null) {
                    pixels2DContext.putImageData(image, 0, 0);
                    data = pixels2DContext.getImageData(0, 0, width, height).data;
                }
                else {
                    throw new Error('Can not access image data');
                }
            }
            else {
                data = image.data;
            }
        }
        else if (isImageBitmap) {
            // ImageBitmap - image object - format must be provided by user
            if (options === undefined) {
                throw new Error('Please provide image config with format for Imagebitmap');
            }
            if (options.bitmapFormat !== undefined) {
                throw new Error('Image input config format must be defined for ImageBitmap');
            }
            const pixels2DContext = document.createElement('canvas').getContext('2d');
            if (pixels2DContext != null) {
                const height = image.height;
                const width = image.width;
                pixels2DContext.drawImage(image, 0, 0, width, height);
                data = pixels2DContext.getImageData(0, 0, width, height).data;
                if (options !== undefined) {
                    // using square brackets to avoid TS error - type 'never'
                    if (options.height !== undefined && options.height !== height) {
                        throw new Error('Image input config height doesn\'t match ImageBitmap height');
                    }
                    else {
                        tensorConfig.height = height;
                    }
                    // using square brackets to avoid TS error - type 'never'
                    if (options.width !== undefined && options.width !== width) {
                        throw new Error('Image input config width doesn\'t match ImageBitmap width');
                    }
                    else {
                        tensorConfig.width = width;
                    }
                }
                else {
                    tensorConfig.height = height;
                    tensorConfig.width = width;
                }
                return Tensor.bufferToTensor(data, tensorConfig);
            }
            else {
                throw new Error('Can not access image data');
            }
        }
        else if (isURL) {
            return new Promise((resolve, reject) => {
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                if (!image || !context) {
                    return reject();
                }
                const newImage = new Image();
                newImage.crossOrigin = 'Anonymous';
                newImage.src = image;
                newImage.onload = () => {
                    canvas.width = newImage.width;
                    canvas.height = newImage.height;
                    context.drawImage(newImage, 0, 0, canvas.width, canvas.height);
                    const img = context.getImageData(0, 0, canvas.width, canvas.height);
                    if (options !== undefined) {
                        // using square brackets to avoid TS error - type 'never'
                        if (options.height !== undefined && options.height !== canvas.height) {
                            throw new Error('Image input config height doesn\'t match ImageBitmap height');
                        }
                        else {
                            tensorConfig.height = canvas.height;
                        }
                        // using square brackets to avoid TS error - type 'never'
                        if (options.width !== undefined && options.width !== canvas.width) {
                            throw new Error('Image input config width doesn\'t match ImageBitmap width');
                        }
                        else {
                            tensorConfig.width = canvas.width;
                        }
                    }
                    else {
                        tensorConfig.height = canvas.height;
                        tensorConfig.width = canvas.width;
                    }
                    resolve(Tensor.bufferToTensor(img.data, tensorConfig));
                };
            });
        }
        else {
            throw new Error('Input data provided is not supported - aborted tensor creation');
        }
        if (data !== undefined) {
            return Tensor.bufferToTensor(data, tensorConfig);
        }
        else {
            throw new Error('Input data provided is not supported - aborted tensor creation');
        }
    }
    toImageData(options) {
        var _a, _b;
        const pixels2DContext = document.createElement('canvas').getContext('2d');
        let image;
        if (pixels2DContext != null) {
            // Default values for height and width & format
            const width = this.dims[3];
            const height = this.dims[2];
            const channels = this.dims[1];
            const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';
            const normMean = options !== undefined ? (((_a = options.norm) === null || _a === void 0 ? void 0 : _a.mean) !== undefined ? options.norm.mean : 255) : 255;
            const normBias = options !== undefined ? (((_b = options.norm) === null || _b === void 0 ? void 0 : _b.bias) !== undefined ? options.norm.bias : 0) : 0;
            const offset = height * width;
            if (options !== undefined) {
                if (options.height !== undefined && options.height !== height) {
                    throw new Error('Image output config height doesn\'t match tensor height');
                }
                if (options.width !== undefined && options.width !== width) {
                    throw new Error('Image output config width doesn\'t match tensor width');
                }
                if (options.format !== undefined && (channels === 4 && options.format !== 'RGBA') ||
                    (channels === 3 && (options.format !== 'RGB' && options.format !== 'BGR'))) {
                    throw new Error('Tensor format doesn\'t match input tensor dims');
                }
            }
            // Default pointer assignments
            const step = 4;
            let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
            let rTensorPointer = 0, gTensorPointer = offset, bTensorPointer = offset * 2, aTensorPointer = -1;
            // Updating the pointer assignments based on the input image format
            if (inputformat === 'RGBA') {
                rTensorPointer = 0;
                gTensorPointer = offset;
                bTensorPointer = offset * 2;
                aTensorPointer = offset * 3;
            }
            else if (inputformat === 'RGB') {
                rTensorPointer = 0;
                gTensorPointer = offset;
                bTensorPointer = offset * 2;
            }
            else if (inputformat === 'RBG') {
                rTensorPointer = 0;
                bTensorPointer = offset;
                gTensorPointer = offset * 2;
            }
            image = pixels2DContext.createImageData(width, height);
            for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) {
                image.data[rImagePointer] = (this.data[rTensorPointer++] - normBias) * normMean; // R value
                image.data[gImagePointer] = (this.data[gTensorPointer++] - normBias) * normMean; // G value
                image.data[bImagePointer] = (this.data[bTensorPointer++] - normBias) * normMean; // B value
                image.data[aImagePointer] =
                    aTensorPointer === -1 ? 255 : (this.data[aTensorPointer++] - normBias) * normMean; // A value
            }
        }
        else {
            throw new Error('Can not access image data');
        }
        return image;
    }
    // #endregion
    // #region tensor utilities
    reshape(dims) {
        return new Tensor(this.type, this.data, dims);
    }
}
//# sourceMappingURL=tensor-impl.js.map

/***/ }),

/***/ "./node_modules/onnxruntime-common/dist/lib/tensor.js":
/*!************************************************************!*\
  !*** ./node_modules/onnxruntime-common/dist/lib/tensor.js ***!
  \************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Tensor": () => (/* binding */ Tensor)
/* harmony export */ });
/* harmony import */ var _tensor_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tensor-impl */ "./node_modules/onnxruntime-common/dist/lib/tensor-impl.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

// eslint-disable-next-line @typescript-eslint/naming-convention
const Tensor = _tensor_impl__WEBPACK_IMPORTED_MODULE_0__.Tensor;
//# sourceMappingURL=tensor.js.map

/***/ }),

/***/ "./node_modules/onnxruntime-web/dist/ort-web.min.js":
/*!**********************************************************!*\
  !*** ./node_modules/onnxruntime-web/dist/ort-web.min.js ***!
  \**********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/*!
* ONNX Runtime Web v1.14.0
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
!function(t,e){if(true)module.exports=e(__webpack_require__(/*! onnxruntime-common */ "./node_modules/onnxruntime-common/dist/lib/index.js"));else { var r, n; }}(self,(__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return $.buffer!=C&&H($.buffer),F}function r(){return $.buffer!=C&&H($.buffer),N}function i(){return $.buffer!=C&&H($.buffer),L}function o(){return $.buffer!=C&&H($.buffer),R}function a(){return $.buffer!=C&&H($.buffer),j}var s,u,c;t=t||{},s||(s=void 0!==t?t:{}),s.ready=new Promise((function(t,e){u=t,c=e}));var l,p,f,d,h,g,b=Object.assign({},s),m="./this.program",y=(t,e)=>{throw e},_="object"==typeof window,v="function"==typeof importScripts,w="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,x=s.ENVIRONMENT_IS_PTHREAD||!1,T="";function S(t){return s.locateFile?s.locateFile(t,T):T+t}if(w){let e;T=v?n(908).dirname(T)+"/":"//",g=()=>{h||(d=n(1384),h=n(908))},l=function(t,e){return g(),t=h.normalize(t),d.readFileSync(t,e?void 0:"utf8")},f=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),p=(t,e,n)=>{g(),t=h.normalize(t),d.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1<process.argv.length&&(m=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof ut))throw t})),process.on("unhandledRejection",(function(t){throw t})),y=(t,e)=>{if(J())throw process.exitCode=t,e;e instanceof ut||P("exiting due to exception: "+e),process.exit(t)},s.inspect=function(){return"[Emscripten Module object]"};try{e=n(9925)}catch(t){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),t}n.g.Worker=e.Worker}else(_||v)&&(v?T=self.location.href:"undefined"!=typeof document&&document.currentScript&&(T=document.currentScript.src),_scriptDir&&(T=_scriptDir),T=0!==T.indexOf("blob:")?T.substr(0,T.replace(/[?#].*/,"").lastIndexOf("/")+1):"",w||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},v&&(f=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),p=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));w&&"undefined"==typeof performance&&(n.g.performance=n(6953).performance);var O=console.log.bind(console),A=console.warn.bind(console);w&&(g(),O=t=>d.writeSync(1,t+"\n"),A=t=>d.writeSync(2,t+"\n"));var E,I=s.print||O,P=s.printErr||A;Object.assign(s,b),b=null,s.thisProgram&&(m=s.thisProgram),s.quit&&(y=s.quit),s.wasmBinary&&(E=s.wasmBinary);var D=s.noExitRuntime||!1;"object"!=typeof WebAssembly&&it("no native wasm support detected");var $,k,C,F,N,L,R,j,M=!1,U="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function V(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&U)return U.decode(t.buffer instanceof SharedArrayBuffer?t.slice(e,n):t.subarray(e,n));for(r="";e<n;){var i=t[e++];if(128&i){var o=63&t[e++];if(192==(224&i))r+=String.fromCharCode((31&i)<<6|o);else{var a=63&t[e++];65536>(i=224==(240&i)?(15&i)<<12|o<<6|a:(7&i)<<18|o<<12|a<<6|63&t[e++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function B(t,e){return(t>>>=0)?V(r(),t,e):""}function z(t,e,n,r){if(!(0<r))return 0;var i=n>>>=0;r=n+r-1;for(var o=0;o<t.length;++o){var a=t.charCodeAt(o);if(55296<=a&&57343>=a&&(a=65536+((1023&a)<<10)|1023&t.charCodeAt(++o)),127>=a){if(n>=r)break;e[n++>>>0]=a}else{if(2047>=a){if(n+1>=r)break;e[n++>>>0]=192|a>>6}else{if(65535>=a){if(n+2>=r)break;e[n++>>>0]=224|a>>12}else{if(n+3>=r)break;e[n++>>>0]=240|a>>18,e[n++>>>0]=128|a>>12&63}e[n++>>>0]=128|a>>6&63}e[n++>>>0]=128|63&a}}return e[n>>>0]=0,n-i}function G(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function H(t){C=t,s.HEAP8=F=new Int8Array(t),s.HEAP16=new Int16Array(t),s.HEAP32=L=new Int32Array(t),s.HEAPU8=N=new Uint8Array(t),s.HEAPU16=new Uint16Array(t),s.HEAPU32=R=new Uint32Array(t),s.HEAPF32=new Float32Array(t),s.HEAPF64=j=new Float64Array(t)}x&&(C=s.buffer);var W=s.INITIAL_MEMORY||16777216;if(x)$=s.wasmMemory,C=s.buffer;else if(s.wasmMemory)$=s.wasmMemory;else if(!(($=new WebAssembly.Memory({initial:W/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw P("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),w&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");$&&(C=$.buffer),W=C.byteLength,H(C);var q,X=[],Y=[],K=[],Z=[];function J(){return D||!1}function Q(){var t=s.preRun.shift();X.unshift(t)}var tt,et=0,nt=null,rt=null;function it(t){throw x?postMessage({cmd:"onAbort",arg:t}):s.onAbort&&s.onAbort(t),P(t="Aborted("+t+")"),M=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),c(t),t}function ot(){return tt.startsWith("data:application/octet-stream;base64,")}function at(){var t=tt;try{if(t==tt&&E)return new Uint8Array(E);if(f)return f(t);throw"both async and sync fetching of the wasm failed"}catch(t){it(t)}}tt="ort-wasm-threaded.wasm",ot()||(tt=S(tt));var st={};function ut(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function ct(t){(t=dt.Vb[t])||it(),dt.mc(t)}function lt(t){var e=dt.Cc();if(!e)return 6;dt.ac.push(e),dt.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function pt(t){if(x)return qt(1,1,t);J()||(dt.oc(),s.onExit&&s.onExit(t),M=!0),y(t,new ut(t))}function ft(t,e){if(!e&&x)throw bt(t),"unwind";J()||x||(me(),ht(K),be(0),re[1].length&&ie(1,10),re[2].length&&ie(2,10),dt.oc()),pt(t)}var dt={Yb:[],ac:[],qc:[],Vb:{},fc:function(){x&&dt.Ec()},Pc:function(){},Ec:function(){dt.receiveObjectTransfer=dt.Gc,dt.threadInitTLS=dt.pc,dt.setExitStatus=dt.nc,D=!1},nc:function(){},oc:function(){for(var t of Object.values(dt.Vb))dt.mc(t);for(t of dt.Yb)t.terminate();dt.Yb=[]},mc:function(t){var e=t.Ub;delete dt.Vb[e],dt.Yb.push(t),dt.ac.splice(dt.ac.indexOf(t),1),t.Ub=0,xe(e)},Gc:function(){},pc:function(){dt.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(dt.Bc=t.Ub),n.targetThread&&n.targetThread!=de()){var i=dt.Vb[n.Qc];i?i.postMessage(n,n.transferList):P('Internal error! Worker sent a message "'+r+'" to target pthread '+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?Vt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?ct(n.thread):"killThread"===r?(n=n.thread,r=dt.Vb[n],delete dt.Vb[n],r.terminate(),xe(n),dt.ac.splice(dt.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?dt.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?I("Thread "+n.threadId+": "+n.text):"printErr"===r?P("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?s.onAbort&&s.onAbort(n.arg):r&&P("worker sent an unknown command "+r);dt.Bc=void 0},t.onerror=t=>{throw P("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},w&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:s.mainScriptUrlOrBlob||_scriptDir,wasmMemory:$,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");dt.Yb.push(new Worker(t))},Cc:function(){return 0==dt.Yb.length&&(dt.yc(),dt.Fc(dt.Yb[0])),dt.Yb.pop()}};function ht(t){for(;0<t.length;)t.shift()(s)}function gt(t){var e=Ae();return t=t(),Ee(e),t}function bt(t){if(x)return qt(2,0,t);try{ft(t)}catch(t){t instanceof ut||"unwind"==t||y(1,t)}}s.PThread=dt,s.establishStackSpace=function(){var t=de(),e=i()[t+44>>2>>>0];t=i()[t+48>>2>>>0],Oe(e,e-t),Ee(e)};var mt=[];function yt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=q.get(t)),e}s.invokeEntryPoint=function(t,e){t=yt(t)(e),J()?dt.nc(t):Te(t)};var _t,vt,wt=[],xt=0,Tt=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){o()[this.Sb+4>>2>>>0]=t},this.bc=function(){return o()[this.Sb+4>>2>>>0]},this.wc=function(t){o()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return o()[this.Sb+8>>2>>>0]},this.rc=function(){i()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(i(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(i(),this.Sb>>2,1)},this.cc=function(t){o()[this.Sb+16>>2>>>0]=t},this.tc=function(){return o()[this.Sb+16>>2>>>0]},this.vc=function(){if(De(this.bc()))return o()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Ot(t){return ge(new St(t).Sb)}function At(t,e,n,r){return x?qt(3,1,t,e,n,r):Et(t,e,n,r)}function Et(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return P("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var i=[];return x&&0===i.length?At(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:i},x?(t.Oc="spawnThread",postMessage(t,i),0):lt(t))}function It(t,e,n){return x?qt(4,1,t,e,n):0}function Pt(t,e){if(x)return qt(5,1,t,e)}function Dt(t,e){if(x)return qt(6,1,t,e)}function $t(t,e,n){if(x)return qt(7,1,t,e,n)}function kt(t,e,n){return x?qt(8,1,t,e,n):0}function Ct(t,e){if(x)return qt(9,1,t,e)}function Ft(t,e,n){if(x)return qt(10,1,t,e,n)}function Nt(t,e,n,r){if(x)return qt(11,1,t,e,n,r)}function Lt(t,e,n,r){if(x)return qt(12,1,t,e,n,r)}function Rt(t,e,n,r){if(x)return qt(13,1,t,e,n,r)}function jt(t){if(x)return qt(14,1,t)}function Mt(t,e){if(x)return qt(15,1,t,e)}function Ut(t,e,n){if(x)return qt(16,1,t,e,n)}function Vt(t){Atomics.store(i(),t>>2,1),de()&&we(t),Atomics.compareExchange(i(),t>>2,1,0)}function Bt(t){return o()[t>>>2]+4294967296*i()[t+4>>>2]}function zt(t,e,n,r,i,o){return x?qt(17,1,t,e,n,r,i,o):-52}function Gt(t,e,n,r,i,o){if(x)return qt(18,1,t,e,n,r,i,o)}function Ht(t){var n=G(t)+1,r=he(n);return r&&z(t,e(),r,n),r}function Wt(t,e,n){function r(t){return(t=t.toTimeString().match(/\(([A-Za-z ]+)\)$/))?t[1]:"GMT"}if(x)return qt(19,1,t,e,n);var a=(new Date).getFullYear(),s=new Date(a,0,1),u=new Date(a,6,1);a=s.getTimezoneOffset();var c=u.getTimezoneOffset(),l=Math.max(a,c);i()[t>>2>>>0]=60*l,i()[e>>2>>>0]=Number(a!=c),t=r(s),e=r(u),t=Ht(t),e=Ht(e),c<a?(o()[n>>2>>>0]=t,o()[n+4>>2>>>0]=e):(o()[n>>2>>>0]=e,o()[n+4>>2>>>0]=t)}function qt(t,e){var n=arguments.length-2,r=arguments;return gt((()=>{for(var i=Ie(8*n),o=i>>3,s=0;s<n;s++){var u=r[2+s];a()[o+s>>>0]=u}return ve(t,n,i,e)}))}s.executeNotifiedProxyingQueue=Vt,vt=w?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:x?()=>performance.now()-s.__performance_now_clock_drift:()=>performance.now();var Xt,Yt=[],Kt={};function Zt(){if(!Xt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Kt)void 0===Kt[t]?delete e[t]:e[t]=Kt[t];var n=[];for(t in e)n.push(t+"="+e[t]);Xt=n}return Xt}function Jt(t,n){if(x)return qt(20,1,t,n);var r=0;return Zt().forEach((function(i,a){var s=n+r;for(a=o()[t+4*a>>2>>>0]=s,s=0;s<i.length;++s)e()[a++>>0>>>0]=i.charCodeAt(s);e()[a>>0>>>0]=0,r+=i.length+1})),0}function Qt(t,e){if(x)return qt(21,1,t,e);var n=Zt();o()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),o()[e>>2>>>0]=r,0}function te(t){return x?qt(22,1,t):52}function ee(t,e,n,r){return x?qt(23,1,t,e,n,r):52}function ne(t,e,n,r,i){return x?qt(24,1,t,e,n,r,i):70}var re=[null,[],[]];function ie(t,e){var n=re[t];0===e||10===e?((1===t?I:P)(V(n,0)),n.length=0):n.push(e)}function oe(t,e,n,i){if(x)return qt(25,1,t,e,n,i);for(var a=0,s=0;s<n;s++){var u=o()[e>>2>>>0],c=o()[e+4>>2>>>0];e+=8;for(var l=0;l<c;l++)ie(t,r()[u+l>>>0]);a+=c}return o()[i>>2>>>0]=a,0}var ae=0;function se(t){return 0==t%4&&(0!=t%100||0==t%400)}var ue=[31,29,31,30,31,30,31,31,30,31,30,31],ce=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,o){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function s(t,e){return a(t,e,"0")}function u(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function c(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function l(t){var e=t.Wb;for(t=new Date(new Date(t.Xb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(se(t.getFullYear())?ue:ce)[n];if(!(e>r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=c(new Date(t.getFullYear(),0,4)),n=c(n),0>=u(e,t)?0>=u(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var p=i()[o+40>>2>>>0];for(var f in o={Lc:i()[o>>2>>>0],Kc:i()[o+4>>2>>>0],dc:i()[o+8>>2>>>0],jc:i()[o+12>>2>>>0],ec:i()[o+16>>2>>>0],Xb:i()[o+20>>2>>>0],Tb:i()[o+24>>2>>>0],Wb:i()[o+28>>2>>>0],Rc:i()[o+32>>2>>>0],Jc:i()[o+36>>2>>>0],Mc:p?B(p):""},r=B(r),p={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(f,"g"),p[f]);var d="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),h="January February March April May June July August September October November December".split(" ");for(f in p={"%a":function(t){return d[t.Tb].substring(0,3)},"%A":function(t){return d[t.Tb]},"%b":function(t){return h[t.ec].substring(0,3)},"%B":function(t){return h[t.ec]},"%C":function(t){return s((t.Xb+1900)/100|0,2)},"%d":function(t){return s(t.jc,2)},"%e":function(t){return a(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return s(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12<t&&(t-=12),s(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.ec-1;e+=(se(t.Xb+1900)?ue:ce)[n++]);return s(t.jc+e,3)},"%m":function(t){return s(t.ec+1,2)},"%M":function(t){return s(t.Kc,2)},"%n":function(){return"\n"},"%p":function(t){return 0<=t.dc&&12>t.dc?"AM":"PM"},"%S":function(t){return s(t.Lc,2)},"%t":function(){return"\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return s(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&se(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&se(t.Xb%400-1))&&e++}return s(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return s(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\0\0"),p)r.includes(f)&&(r=r.replace(new RegExp(f,"g"),p[f](o)));return f=function(t){var e=Array(G(t)+1);return z(t,e,0,e.length),e}(r=r.replace(/\0\0/g,"%")),f.length>n?0:(function(t,n){e().set(t,n>>>0)}(f,t),f.length-1)}dt.fc();var pe=[null,pt,bt,At,It,Pt,Dt,$t,kt,Ct,Ft,Nt,Lt,Rt,jt,Mt,Ut,zt,Gt,Wt,Jt,Qt,te,ee,ne,oe],fe={b:function(t){return he(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),xt--),t.ic(!1),wt.push(t),t.sc(),t.vc()},ma:function(t){throw P("Unexpected exception thrown, this is not properly supported - aborting"),M=!0,t},x:function(){Se(0);var t=wt.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&&yt(e)(t.Zb),Ot(t.Zb)}Tt=0},e:function(){var t=Tt;if(!t)return ae=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return ae=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(Pe(o,n,e.Sb+16))return ae=o,t}return ae=n,t},l:function(){var t=Tt;if(!t)return ae=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return ae=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(Pe(o,n,e.Sb+16))return ae=o,t}return ae=n,t},h:function(){var t=Tt;if(!t)return ae=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return ae=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(Pe(o,n,e.Sb+16))return ae=o,t}return ae=n,t},t:Ot,M:function(){var t=wt.pop();t||it("no exception to throw");var e=t.Zb;throw t.kc()||(wt.push(t),t.ic(!0),t.hc(!1),xt++),Tt=e,e},c:function(t,e,n){throw new St(t).fc(e,n),Tt=t,xt++,t},pa:function(){return xt},Fa:function(t){ye(t,!v,1,!_),dt.pc()},T:function(t){x?postMessage({cmd:"cleanupThread",thread:t}):ct(t)},xa:Et,j:function(t){throw Tt||(Tt=t),t},H:It,Ma:Pt,ua:Dt,wa:$t,oa:kt,Ka:Ct,Ca:Ft,Ja:Nt,V:Lt,va:Rt,sa:jt,La:Mt,ta:Ut,Ta:function(){},X:function(){it("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){it("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(t,e,n,r){if(t==e)setTimeout((()=>Vt(r)));else if(x)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=dt.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Bt(t)),i()[e>>2>>>0]=t.getUTCSeconds(),i()[e+4>>2>>>0]=t.getUTCMinutes(),i()[e+8>>2>>>0]=t.getUTCHours(),i()[e+12>>2>>>0]=t.getUTCDate(),i()[e+16>>2>>>0]=t.getUTCMonth(),i()[e+20>>2>>>0]=t.getUTCFullYear()-1900,i()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Bt(t)),i()[e>>2>>>0]=t.getSeconds(),i()[e+4>>2>>>0]=t.getMinutes(),i()[e+8>>2>>>0]=t.getHours(),i()[e+12>>2>>>0]=t.getDate(),i()[e+16>>2>>>0]=t.getMonth(),i()[e+20>>2>>>0]=t.getFullYear()-1900,i()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;i()[e+28>>2>>>0]=r,i()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),i()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(i()[t+20>>2>>>0]+1900,i()[t+16>>2>>>0],i()[t+12>>2>>>0],i()[t+8>>2>>>0],i()[t+4>>2>>>0],i()[t>>2>>>0],0),n=i()[t+32>>2>>>0],r=e.getTimezoneOffset(),o=new Date(e.getFullYear(),0,1),a=new Date(e.getFullYear(),6,1).getTimezoneOffset(),s=o.getTimezoneOffset(),u=Math.min(s,a);return 0>n?i()[t+32>>2>>>0]=Number(a!=s&&u==r):0<n!=(u==r)&&(a=Math.max(s,a),e.setTime(e.getTime()+6e4*((0<n?u:a)-r))),i()[t+24>>2>>>0]=e.getDay(),n=(e.getTime()-o.getTime())/864e5|0,i()[t+28>>2>>>0]=n,i()[t>>2>>>0]=e.getSeconds(),i()[t+4>>2>>>0]=e.getMinutes(),i()[t+8>>2>>>0]=e.getHours(),i()[t+12>>2>>>0]=e.getDate(),i()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:zt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Wt(e,n,r))},y:function(){it("")},U:function(){if(!w&&!v){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";_t||(_t={}),_t[t]||(_t[t]=1,w&&(t="warning: "+t),P(t))}},ra:function(){return 4294901760},B:vt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return w?n(3993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Yt.length=e,n>>=3;for(var r=0;r<e;r++)Yt[r]=a()[n+r>>>0];return(0>t?st[-t-1]:pe[t]).apply(null,Yt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760<t)return!1;for(var n=1;4>=n;n*=2){var i=e*(1+.2/n);i=Math.min(i,t+100663296);var o=Math;i=Math.max(t,i),o=o.min.call(o,4294901760,i+(65536-i%65536)%65536);t:{try{$.grow(o-C.byteLength+65535>>>16),H($.buffer);var a=1;break t}catch(t){}a=void 0}if(a)return!0}return!1},Na:function(){throw"unwind"},Ga:Jt,Ha:Qt,J:ft,I:te,S:ee,ga:ne,R:oe,d:function(){return ae},na:function t(r,i){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(w)try{var e=n(Object(function(){var t=new Error("Cannot find module 'crypto'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>it("randomDevice")}());for(var o=0;o<i;o++)e()[r+o>>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ae();try{return yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ae();try{return yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ae();try{return yt(t)()}catch(t){if(Ee(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ae();try{return yt(t)(e)}catch(t){if(Ee(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ae();try{return yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ae();try{return yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ae();try{return yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var i=Ae();try{return yt(t)(e,n,r)}catch(t){if(Ee(i),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,i){var o=Ae();try{return yt(t)(e,n,r,i)}catch(t){if(Ee(o),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,i,o){var a=Ae();try{return yt(t)(e,n,r,i,o)}catch(t){if(Ee(a),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,i,o){var a=Ae();try{return yt(t)(e,n,r,i,o)}catch(t){if(Ee(a),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,i,o,a){var s=Ae();try{return yt(t)(e,n,r,i,o,a)}catch(t){if(Ee(s),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,i,o,a,s){var u=Ae();try{return yt(t)(e,n,r,i,o,a,s)}catch(t){if(Ee(u),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,i,o,a,s,u,c,l,p){var f=Ae();try{return yt(t)(e,n,r,i,o,a,s,u,c,l,p)}catch(t){if(Ee(f),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,i,o,a,s){var u=Ae();try{return Me(t,e,n,r,i,o,a,s)}catch(t){if(Ee(u),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,i,o,a){var s=Ae();try{return ke(t,e,n,r,i,o,a)}catch(t){if(Ee(s),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,i){var o=Ae();try{return Ue(t,e,n,r,i)}catch(t){if(Ee(o),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var i=Ae();try{return Re(t,e,n,r)}catch(t){if(Ee(i),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ae();try{return $e(t)}catch(t){if(Ee(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ae();try{return je(t,e)}catch(t){if(Ee(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ae();try{return Ce(t,e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ae();try{yt(t)()}catch(t){if(Ee(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ae();try{yt(t)(e)}catch(t){if(Ee(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ae();try{yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var i=Ae();try{yt(t)(e,n,r)}catch(t){if(Ee(i),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var i=Ae();try{yt(t)(e,n,r)}catch(t){if(Ee(i),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,i){var o=Ae();try{yt(t)(e,n,r,i)}catch(t){if(Ee(o),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,i,o){var a=Ae();try{yt(t)(e,n,r,i,o)}catch(t){if(Ee(a),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,i,o,a){var s=Ae();try{yt(t)(e,n,r,i,o,a)}catch(t){if(Ee(s),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,i,o,a,s){var u=Ae();try{yt(t)(e,n,r,i,o,a,s)}catch(t){if(Ee(u),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,i,o,a,s,u){var c=Ae();try{yt(t)(e,n,r,i,o,a,s,u)}catch(t){if(Ee(c),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,i,o,a,s,u,c,l){var p=Ae();try{yt(t)(e,n,r,i,o,a,s,u,c,l)}catch(t){if(Ee(p),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,i,o,a,s,u,c,l,p,f,d,h,g){var b=Ae();try{yt(t)(e,n,r,i,o,a,s,u,c,l,p,f,d,h,g)}catch(t){if(Ee(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,i,o,a,s){var u=Ae();try{Fe(t,e,n,r,i,o,a,s)}catch(t){if(Ee(u),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,i,o,a,s,u,c,l,p){var f=Ae();try{Le(t,e,n,r,i,o,a,s,u,c,l,p)}catch(t){if(Ee(f),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,i,o){var a=Ae();try{Ne(t,e,n,r,i,o)}catch(t){if(Ee(a),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:$||s.wasmMemory,G:function(t){ae=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){s.asm=t.exports,dt.qc.push(s.asm.sb),q=s.asm.ub,Y.unshift(s.asm.Va),k=e,x||(et--,s.monitorRunDependencies&&s.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!E&&(_||v)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at '"+tt+"'";return t.arrayBuffer()})).catch((function(){return at()}));if(p)return new Promise((function(t,e){p(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return at()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){P("failed to asynchronously prepare wasm: "+t),it(t)}))}var r={a:fe};if(x||(et++,s.monitorRunDependencies&&s.monitorRunDependencies(et)),s.instantiateWasm)try{return s.instantiateWasm(r,t)}catch(t){return P("Module.instantiateWasm callback failed with error: "+t),!1}(E||"function"!=typeof WebAssembly.instantiateStreaming||ot()||tt.startsWith("file://")||w||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return P("wasm streaming compile failed: "+t),P("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(c)}(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm.Va).apply(null,arguments)},s._OrtInit=function(){return(s._OrtInit=s.asm.Wa).apply(null,arguments)},s._OrtCreateSessionOptions=function(){return(s._OrtCreateSessionOptions=s.asm.Xa).apply(null,arguments)},s._OrtAppendExecutionProvider=function(){return(s._OrtAppendExecutionProvider=s.asm.Ya).apply(null,arguments)},s._OrtAddSessionConfigEntry=function(){return(s._OrtAddSessionConfigEntry=s.asm.Za).apply(null,arguments)},s._OrtReleaseSessionOptions=function(){return(s._OrtReleaseSessionOptions=s.asm._a).apply(null,arguments)},s._OrtCreateSession=function(){return(s._OrtCreateSession=s.asm.$a).apply(null,arguments)},s._OrtReleaseSession=function(){return(s._OrtReleaseSession=s.asm.ab).apply(null,arguments)},s._OrtGetInputCount=function(){return(s._OrtGetInputCount=s.asm.bb).apply(null,arguments)},s._OrtGetOutputCount=function(){return(s._OrtGetOutputCount=s.asm.cb).apply(null,arguments)},s._OrtGetInputName=function(){return(s._OrtGetInputName=s.asm.db).apply(null,arguments)},s._OrtGetOutputName=function(){return(s._OrtGetOutputName=s.asm.eb).apply(null,arguments)},s._OrtFree=function(){return(s._OrtFree=s.asm.fb).apply(null,arguments)},s._OrtCreateTensor=function(){return(s._OrtCreateTensor=s.asm.gb).apply(null,arguments)},s._OrtGetTensorData=function(){return(s._OrtGetTensorData=s.asm.hb).apply(null,arguments)},s._OrtReleaseTensor=function(){return(s._OrtReleaseTensor=s.asm.ib).apply(null,arguments)},s._OrtCreateRunOptions=function(){return(s._OrtCreateRunOptions=s.asm.jb).apply(null,arguments)},s._OrtAddRunConfigEntry=function(){return(s._OrtAddRunConfigEntry=s.asm.kb).apply(null,arguments)},s._OrtReleaseRunOptions=function(){return(s._OrtReleaseRunOptions=s.asm.lb).apply(null,arguments)},s._OrtRun=function(){return(s._OrtRun=s.asm.mb).apply(null,arguments)},s._OrtEndProfiling=function(){return(s._OrtEndProfiling=s.asm.nb).apply(null,arguments)};var de=s._pthread_self=function(){return(de=s._pthread_self=s.asm.ob).apply(null,arguments)},he=s._malloc=function(){return(he=s._malloc=s.asm.pb).apply(null,arguments)},ge=s._free=function(){return(ge=s._free=s.asm.qb).apply(null,arguments)},be=s._fflush=function(){return(be=s._fflush=s.asm.rb).apply(null,arguments)};s.__emscripten_tls_init=function(){return(s.__emscripten_tls_init=s.asm.sb).apply(null,arguments)};var me=s.___funcs_on_exit=function(){return(me=s.___funcs_on_exit=s.asm.tb).apply(null,arguments)},ye=s.__emscripten_thread_init=function(){return(ye=s.__emscripten_thread_init=s.asm.vb).apply(null,arguments)};s.__emscripten_thread_crashed=function(){return(s.__emscripten_thread_crashed=s.asm.wb).apply(null,arguments)};var _e,ve=s._emscripten_run_in_main_runtime_thread_js=function(){return(ve=s._emscripten_run_in_main_runtime_thread_js=s.asm.xb).apply(null,arguments)},we=s.__emscripten_proxy_execute_task_queue=function(){return(we=s.__emscripten_proxy_execute_task_queue=s.asm.yb).apply(null,arguments)},xe=s.__emscripten_thread_free_data=function(){return(xe=s.__emscripten_thread_free_data=s.asm.zb).apply(null,arguments)},Te=s.__emscripten_thread_exit=function(){return(Te=s.__emscripten_thread_exit=s.asm.Ab).apply(null,arguments)},Se=s._setThrew=function(){return(Se=s._setThrew=s.asm.Bb).apply(null,arguments)},Oe=s._emscripten_stack_set_limits=function(){return(Oe=s._emscripten_stack_set_limits=s.asm.Cb).apply(null,arguments)},Ae=s.stackSave=function(){return(Ae=s.stackSave=s.asm.Db).apply(null,arguments)},Ee=s.stackRestore=function(){return(Ee=s.stackRestore=s.asm.Eb).apply(null,arguments)},Ie=s.stackAlloc=function(){return(Ie=s.stackAlloc=s.asm.Fb).apply(null,arguments)},Pe=s.___cxa_can_catch=function(){return(Pe=s.___cxa_can_catch=s.asm.Gb).apply(null,arguments)},De=s.___cxa_is_pointer_type=function(){return(De=s.___cxa_is_pointer_type=s.asm.Hb).apply(null,arguments)},$e=s.dynCall_j=function(){return($e=s.dynCall_j=s.asm.Ib).apply(null,arguments)},ke=s.dynCall_iiiiij=function(){return(ke=s.dynCall_iiiiij=s.asm.Jb).apply(null,arguments)},Ce=s.dynCall_jii=function(){return(Ce=s.dynCall_jii=s.asm.Kb).apply(null,arguments)},Fe=s.dynCall_viiiiij=function(){return(Fe=s.dynCall_viiiiij=s.asm.Lb).apply(null,arguments)},Ne=s.dynCall_vjji=function(){return(Ne=s.dynCall_vjji=s.asm.Mb).apply(null,arguments)},Le=s.dynCall_viiijjjii=function(){return(Le=s.dynCall_viiijjjii=s.asm.Nb).apply(null,arguments)},Re=s.dynCall_iij=function(){return(Re=s.dynCall_iij=s.asm.Ob).apply(null,arguments)},je=s.dynCall_ji=function(){return(je=s.dynCall_ji=s.asm.Pb).apply(null,arguments)},Me=s.dynCall_iiiiiij=function(){return(Me=s.dynCall_iiiiiij=s.asm.Qb).apply(null,arguments)},Ue=s.dynCall_iiij=function(){return(Ue=s.dynCall_iiij=s.asm.Rb).apply(null,arguments)};function Ve(){function t(){if(!_e&&(_e=!0,s.calledRun=!0,!M)&&(x||ht(Y),u(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),!x)){if(s.postRun)for("function"==typeof s.postRun&&(s.postRun=[s.postRun]);s.postRun.length;){var t=s.postRun.shift();Z.unshift(t)}ht(Z)}}if(!(0<et))if(x)u(s),x||ht(Y),postMessage({cmd:"loaded"});else{if(s.preRun)for("function"==typeof s.preRun&&(s.preRun=[s.preRun]);s.preRun.length;)Q();ht(X),0<et||(s.setStatus?(s.setStatus("Running..."),setTimeout((function(){setTimeout((function(){s.setStatus("")}),1),t()}),1)):t())}}if(s.UTF8ToString=B,s.stringToUTF8=function(t,e,n){return z(t,r(),e,n)},s.lengthBytesUTF8=G,s.keepRuntimeAlive=J,s.wasmMemory=$,s.stackSave=Ae,s.stackRestore=Ee,s.stackAlloc=Ie,s.ExitStatus=ut,s.PThread=dt,rt=function t(){_e||Ve(),_e||(rt=t)},s.preInit)for("function"==typeof s.preInit&&(s.preInit=[s.preInit]);0<s.preInit.length;)s.preInit.pop()();return Ve(),t.ready});t.exports=r},932:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,i;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,i=e}));var o,a,s,u,c,l,p=Object.assign({},e),f="./this.program",d=(t,e)=>{throw e},h="object"==typeof window,g="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=g?n(908).dirname(m)+"/":"//",l=()=>{c||(u=n(1384),c=n(908))},o=function(t,e){return l(),t=c.normalize(t),u.readFileSync(t,e?void 0:"utf8")},s=t=>((t=o(t,!0)).buffer||(t=new Uint8Array(t)),t),a=(t,e,n)=>{l(),t=c.normalize(t),u.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1<process.argv.length&&(f=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof K))throw t})),process.on("unhandledRejection",(function(t){throw t})),d=(t,e)=>{if(w||0<U)throw process.exitCode=t,e;e instanceof K||v("exiting due to exception: "+e),process.exit(t)},e.inspect=function(){return"[Emscripten Module object]"}):(h||g)&&(g?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),_scriptDir&&(m=_scriptDir),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",o=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},g&&(s=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),a=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var y,_=e.print||console.log.bind(console),v=e.printErr||console.warn.bind(console);Object.assign(e,p),p=null,e.thisProgram&&(f=e.thisProgram),e.quit&&(d=e.quit),e.wasmBinary&&(y=e.wasmBinary);var w=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&W("no native wasm support detected");var x,T,S,O,A,E,I=!1,P="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function D(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&P)return P.decode(t.subarray(e,n));for(r="";e<n;){var i=t[e++];if(128&i){var o=63&t[e++];if(192==(224&i))r+=String.fromCharCode((31&i)<<6|o);else{var a=63&t[e++];65536>(i=224==(240&i)?(15&i)<<12|o<<6|a:(7&i)<<18|o<<12|a<<6|63&t[e++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function $(t,e){return(t>>>=0)?D(O,t,e):""}function k(t,e,n,r){if(!(0<r))return 0;var i=n>>>=0;r=n+r-1;for(var o=0;o<t.length;++o){var a=t.charCodeAt(o);if(55296<=a&&57343>=a&&(a=65536+((1023&a)<<10)|1023&t.charCodeAt(++o)),127>=a){if(n>=r)break;e[n++>>>0]=a}else{if(2047>=a){if(n+1>=r)break;e[n++>>>0]=192|a>>6}else{if(65535>=a){if(n+2>=r)break;e[n++>>>0]=224|a>>12}else{if(n+3>=r)break;e[n++>>>0]=240|a>>18,e[n++>>>0]=128|a>>12&63}e[n++>>>0]=128|a>>6&63}e[n++>>>0]=128|63&a}}return e[n>>>0]=0,n-i}function C(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function F(){var t=x.buffer;T=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=A=new Int32Array(t),e.HEAPU8=O=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=E=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var N,L=[],R=[],j=[],M=[],U=0;function V(){var t=e.preRun.shift();L.unshift(t)}var B,z=0,G=null,H=null;function W(t){throw e.onAbort&&e.onAbort(t),v(t="Aborted("+t+")"),I=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),i(t),t}function q(){return B.startsWith("data:application/octet-stream;base64,")}if(B="ort-wasm.wasm",!q()){var X=B;B=e.locateFile?e.locateFile(X,m):m+X}function Y(){var t=B;try{if(t==B&&y)return new Uint8Array(y);if(s)return s(t);throw"both async and sync fetching of the wasm failed"}catch(t){W(t)}}function K(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0<t.length;)t.shift()(e)}var J=[],Q=0,tt=0;function et(t){this.Db=t,this.zb=t-24,this.Ub=function(t){E[this.zb+4>>2>>>0]=t},this.Eb=function(){return E[this.zb+4>>2>>>0]},this.Sb=function(t){E[this.zb+8>>2>>>0]=t},this.Wb=function(){return E[this.zb+8>>2>>>0]},this.Tb=function(){A[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){A[this.zb>>2>>>0]+=1},this.Xb=function(){var t=A[this.zb>>2>>>0];return A[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){E[this.zb+16>>2>>>0]=t},this.Ob=function(){return E[this.zb+16>>2>>>0]},this.Qb=function(){if(Et(this.Eb()))return E[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return _t(new et(t).zb)}var rt=[];function it(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=N.get(t)),e}function ot(t){var e=C(t)+1,n=yt(e);return n&&k(t,S,n,e),n}var at={};function st(){if(!ut){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:f||"./this.program"};for(t in at)void 0===at[t]?delete e[t]:e[t]=at[t];var n=[];for(t in e)n.push(t+"="+e[t]);ut=n}return ut}var ut,ct=[null,[],[]];function lt(t,e){var n=ct[t];0===e||10===e?((1===t?_:v)(D(n,0)),n.length=0):n.push(e)}var pt=0;function ft(t){return 0==t%4&&(0!=t%100||0==t%400)}var dt=[31,29,31,30,31,30,31,31,30,31,30,31],ht=[31,28,31,30,31,30,31,31,30,31,30,31];function gt(t,e,n,r){function i(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function o(t,e){return i(t,e,"0")}function a(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function s(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function u(t){var e=t.Bb;for(t=new Date(new Date(t.Cb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(ft(t.getFullYear())?dt:ht)[n];if(!(e>r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=a(e,t)?0>=a(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var c=A[r+40>>2>>>0];for(var l in r={$b:A[r>>2>>>0],Zb:A[r+4>>2>>>0],Gb:A[r+8>>2>>>0],Kb:A[r+12>>2>>>0],Hb:A[r+16>>2>>>0],Cb:A[r+20>>2>>>0],Ab:A[r+24>>2>>>0],Bb:A[r+28>>2>>>0],bc:A[r+32>>2>>>0],Yb:A[r+36>>2>>>0],ac:c?$(c):""},n=$(n),c={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),c[l]);var p="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),f="January February March April May June July August September October November December".split(" ");for(l in c={"%a":function(t){return p[t.Ab].substring(0,3)},"%A":function(t){return p[t.Ab]},"%b":function(t){return f[t.Hb].substring(0,3)},"%B":function(t){return f[t.Hb]},"%C":function(t){return o((t.Cb+1900)/100|0,2)},"%d":function(t){return o(t.Kb,2)},"%e":function(t){return i(t.Kb,2," ")},"%g":function(t){return u(t).toString().substring(2)},"%G":function(t){return u(t)},"%H":function(t){return o(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12<t&&(t-=12),o(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.Hb-1;e+=(ft(t.Cb+1900)?dt:ht)[n++]);return o(t.Kb+e,3)},"%m":function(t){return o(t.Hb+1,2)},"%M":function(t){return o(t.Zb,2)},"%n":function(){return"\n"},"%p":function(t){return 0<=t.Gb&&12>t.Gb?"AM":"PM"},"%S":function(t){return o(t.$b,2)},"%t":function(){return"\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return o(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&ft(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&ft(t.Cb%400-1))&&e++}return o(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return o(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\0\0"),c)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),c[l](r)));return l=function(t){var e=Array(C(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\0\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return yt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),Q--),t.Jb(!1),J.push(t),t.Nb(),t.Qb()},ia:function(t){throw v("Unexpected exception thrown, this is not properly supported - aborting"),I=!0,t},w:function(){xt(0);var t=J.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&it(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return pt=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return pt=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(At(o,n,e.zb+16))return pt=o,t}return pt=n,t},k:function(){var t=tt;if(!t)return pt=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return pt=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(At(o,n,e.zb+16))return pt=o,t}return pt=n,t},g:function(){var t=tt;if(!t)return pt=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return pt=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(At(o,n,e.zb+16))return pt=o,t}return pt=n,t},s:nt,L:function(){var t=J.pop();t||W("no exception to throw");var e=t.Db;throw t.Lb()||(J.push(t),t.Jb(!0),t.Ib(!1),Q++),tt=e,e},b:function(t,e,n){throw new et(t).Rb(e,n),tt=t,Q++,t},la:function(){return Q},i:function(t){throw tt||(tt=t),t},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},Ha:function(){},Ja:function(){W("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ia:function(){W("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(t,e){t=new Date(1e3*(E[t>>>2]+4294967296*A[t+4>>>2])),A[e>>2>>>0]=t.getUTCSeconds(),A[e+4>>2>>>0]=t.getUTCMinutes(),A[e+8>>2>>>0]=t.getUTCHours(),A[e+12>>2>>>0]=t.getUTCDate(),A[e+16>>2>>>0]=t.getUTCMonth(),A[e+20>>2>>>0]=t.getUTCFullYear()-1900,A[e+24>>2>>>0]=t.getUTCDay(),A[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(E[t>>>2]+4294967296*A[t+4>>>2])),A[e>>2>>>0]=t.getSeconds(),A[e+4>>2>>>0]=t.getMinutes(),A[e+8>>2>>>0]=t.getHours(),A[e+12>>2>>>0]=t.getDate(),A[e+16>>2>>>0]=t.getMonth(),A[e+20>>2>>>0]=t.getFullYear()-1900,A[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);A[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,A[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),A[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(A[t+20>>2>>>0]+1900,A[t+16>>2>>>0],A[t+12>>2>>>0],A[t+8>>2>>>0],A[t+4>>2>>>0],A[t>>2>>>0],0),n=A[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),a=i.getTimezoneOffset(),s=Math.min(a,o);return 0>n?A[t+32>>2>>>0]=Number(o!=a&&s==r):0<n!=(s==r)&&(o=Math.max(a,o),e.setTime(e.getTime()+6e4*((0<n?s:o)-r))),A[t+24>>2>>>0]=e.getDay(),A[t+28>>2>>>0]=(e.getTime()-i.getTime())/864e5|0,A[t>>2>>>0]=e.getSeconds(),A[t+4>>2>>>0]=e.getMinutes(),A[t+8>>2>>>0]=e.getHours(),A[t+12>>2>>>0]=e.getDate(),A[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\(([A-Za-z ]+)\)$/))?t[1]:"GMT"}var i=(new Date).getFullYear(),o=new Date(i,0,1),a=new Date(i,6,1);i=o.getTimezoneOffset();var s=a.getTimezoneOffset();A[t>>2>>>0]=60*Math.max(i,s),A[e>>2>>>0]=Number(i!=s),t=r(o),e=r(a),t=ot(t),e=ot(e),s<i?(E[n>>2>>>0]=t,E[n+4>>2>>>0]=e):(E[n>>2>>>0]=e,E[n+4>>2>>>0]=t)}(e,n,r))},B:function(){W("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){O.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=O.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var i=Math;r=Math.max(t,r),i=i.min.call(i,4294901760,r+(65536-r%65536)%65536);t:{try{x.grow(i-T.byteLength+65535>>>16),F();var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},va:function(t,e){var n=0;return st().forEach((function(r,i){var o=e+n;for(i=E[t+4*i>>2>>>0]=o,o=0;o<r.length;++o)S[i++>>0>>>0]=r.charCodeAt(o);S[i>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=st();E[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),E[e>>2>>>0]=r,0},ba:function(t){w||0<U||(wt(),Z(j),vt(0),ct[1].length&&lt(1,10),ct[2].length&&lt(2,10)),w||0<U||(e.onExit&&e.onExit(t),I=!0),d(t,new K(t))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(t,e,n,r){for(var i=0,o=0;o<n;o++){var a=E[e>>2>>>0],s=E[e+4>>2>>>0];e+=8;for(var u=0;u<s;u++)lt(t,O[a+u>>>0]);i+=s}return E[r>>2>>>0]=i,0},c:function(){return pt},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module 'crypto'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>W("randomDevice")}());for(var i=0;i<r;i++)S[e+i>>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=Tt();try{return it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},fa:function(t,e,n){var r=Tt();try{return it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},J:function(t){var e=Tt();try{return it(t)()}catch(t){if(St(e),t!==t+0)throw t;xt(1,0)}},e:function(t,e){var n=Tt();try{return it(t)(e)}catch(t){if(St(n),t!==t+0)throw t;xt(1,0)}},N:function(t,e,n){var r=Tt();try{return it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},O:function(t,e,n){var r=Tt();try{return it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},j:function(t,e,n){var r=Tt();try{return it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},o:function(t,e,n,r){var i=Tt();try{return it(t)(e,n,r)}catch(t){if(St(i),t!==t+0)throw t;xt(1,0)}},p:function(t,e,n,r,i){var o=Tt();try{return it(t)(e,n,r,i)}catch(t){if(St(o),t!==t+0)throw t;xt(1,0)}},M:function(t,e,n,r,i,o){var a=Tt();try{return it(t)(e,n,r,i,o)}catch(t){if(St(a),t!==t+0)throw t;xt(1,0)}},r:function(t,e,n,r,i,o){var a=Tt();try{return it(t)(e,n,r,i,o)}catch(t){if(St(a),t!==t+0)throw t;xt(1,0)}},v:function(t,e,n,r,i,o,a){var s=Tt();try{return it(t)(e,n,r,i,o,a)}catch(t){if(St(s),t!==t+0)throw t;xt(1,0)}},K:function(t,e,n,r,i,o,a,s){var u=Tt();try{return it(t)(e,n,r,i,o,a,s)}catch(t){if(St(u),t!==t+0)throw t;xt(1,0)}},D:function(t,e,n,r,i,o,a,s,u,c,l,p){var f=Tt();try{return it(t)(e,n,r,i,o,a,s,u,c,l,p)}catch(t){if(St(f),t!==t+0)throw t;xt(1,0)}},X:function(t,e,n,r,i,o,a,s){var u=Tt();try{return Lt(t,e,n,r,i,o,a,s)}catch(t){if(St(u),t!==t+0)throw t;xt(1,0)}},V:function(t,e,n,r,i,o,a){var s=Tt();try{return Pt(t,e,n,r,i,o,a)}catch(t){if(St(s),t!==t+0)throw t;xt(1,0)}},U:function(t,e,n,r,i){var o=Tt();try{return Rt(t,e,n,r,i)}catch(t){if(St(o),t!==t+0)throw t;xt(1,0)}},Z:function(t,e,n,r){var i=Tt();try{return Ft(t,e,n,r)}catch(t){if(St(i),t!==t+0)throw t;xt(1,0)}},W:function(t){var e=Tt();try{return It(t)}catch(t){if(St(e),t!==t+0)throw t;xt(1,0)}},Y:function(t,e){var n=Tt();try{return Nt(t,e)}catch(t){if(St(n),t!==t+0)throw t;xt(1,0)}},T:function(t,e,n){var r=Tt();try{return Dt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},f:function(t){var e=Tt();try{it(t)()}catch(t){if(St(e),t!==t+0)throw t;xt(1,0)}},q:function(t,e){var n=Tt();try{it(t)(e)}catch(t){if(St(n),t!==t+0)throw t;xt(1,0)}},h:function(t,e,n){var r=Tt();try{it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},da:function(t,e,n,r){var i=Tt();try{it(t)(e,n,r)}catch(t){if(St(i),t!==t+0)throw t;xt(1,0)}},l:function(t,e,n,r){var i=Tt();try{it(t)(e,n,r)}catch(t){if(St(i),t!==t+0)throw t;xt(1,0)}},t:function(t,e,n,r,i){var o=Tt();try{it(t)(e,n,r,i)}catch(t){if(St(o),t!==t+0)throw t;xt(1,0)}},u:function(t,e,n,r,i,o){var a=Tt();try{it(t)(e,n,r,i,o)}catch(t){if(St(a),t!==t+0)throw t;xt(1,0)}},x:function(t,e,n,r,i,o,a){var s=Tt();try{it(t)(e,n,r,i,o,a)}catch(t){if(St(s),t!==t+0)throw t;xt(1,0)}},z:function(t,e,n,r,i,o,a,s){var u=Tt();try{it(t)(e,n,r,i,o,a,s)}catch(t){if(St(u),t!==t+0)throw t;xt(1,0)}},ga:function(t,e,n,r,i,o,a,s,u){var c=Tt();try{it(t)(e,n,r,i,o,a,s,u)}catch(t){if(St(c),t!==t+0)throw t;xt(1,0)}},A:function(t,e,n,r,i,o,a,s,u,c,l){var p=Tt();try{it(t)(e,n,r,i,o,a,s,u,c,l)}catch(t){if(St(p),t!==t+0)throw t;xt(1,0)}},C:function(t,e,n,r,i,o,a,s,u,c,l,p,f,d,h,g){var b=Tt();try{it(t)(e,n,r,i,o,a,s,u,c,l,p,f,d,h,g)}catch(t){if(St(b),t!==t+0)throw t;xt(1,0)}},aa:function(t,e,n,r,i,o,a,s){var u=Tt();try{$t(t,e,n,r,i,o,a,s)}catch(t){if(St(u),t!==t+0)throw t;xt(1,0)}},_:function(t,e,n,r,i,o,a,s,u,c,l,p){var f=Tt();try{Ct(t,e,n,r,i,o,a,s,u,c,l,p)}catch(t){if(St(f),t!==t+0)throw t;xt(1,0)}},$:function(t,e,n,r,i,o){var a=Tt();try{kt(t,e,n,r,i,o)}catch(t){if(St(a),t!==t+0)throw t;xt(1,0)}},n:function(t){return t},F:function(t){pt=t},ha:gt,y:function(t,e,n,r){return gt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,x=e.asm.Ka,F(),N=e.asm.ib,R.unshift(e.asm.La),z--,e.monitorRunDependencies&&e.monitorRunDependencies(z),0==z&&(null!==G&&(clearInterval(G),G=null),H&&(t=H,H=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!y&&(h||g)){if("function"==typeof fetch&&!B.startsWith("file://"))return fetch(B,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at '"+B+"'";return t.arrayBuffer()})).catch((function(){return Y()}));if(a)return new Promise((function(t,e){a(B,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return Y()}))}().then((function(t){return WebAssembly.instantiate(t,o)})).then((function(t){return t})).then(t,(function(t){v("failed to asynchronously prepare wasm: "+t),W(t)}))}var o={a:bt};if(z++,e.monitorRunDependencies&&e.monitorRunDependencies(z),e.instantiateWasm)try{return e.instantiateWasm(o,t)}catch(t){return v("Module.instantiateWasm callback failed with error: "+t),!1}(y||"function"!=typeof WebAssembly.instantiateStreaming||q()||B.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(B,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,o).then(n,(function(t){return v("wasm streaming compile failed: "+t),v("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(i)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,yt=e._malloc=function(){return(yt=e._malloc=e.asm.eb).apply(null,arguments)},_t=e._free=function(){return(_t=e._free=e.asm.fb).apply(null,arguments)},vt=e._fflush=function(){return(vt=e._fflush=e.asm.gb).apply(null,arguments)},wt=e.___funcs_on_exit=function(){return(wt=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},xt=e._setThrew=function(){return(xt=e._setThrew=e.asm.jb).apply(null,arguments)},Tt=e.stackSave=function(){return(Tt=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Ot=e.stackAlloc=function(){return(Ot=e.stackAlloc=e.asm.mb).apply(null,arguments)},At=e.___cxa_can_catch=function(){return(At=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Et=e.___cxa_is_pointer_type=function(){return(Et=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},It=e.dynCall_j=function(){return(It=e.dynCall_j=e.asm.pb).apply(null,arguments)},Pt=e.dynCall_iiiiij=function(){return(Pt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Dt=e.dynCall_jii=function(){return(Dt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},$t=e.dynCall_viiiiij=function(){return($t=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Ct=e.dynCall_viiijjjii=function(){return(Ct=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Ft=e.dynCall_iij=function(){return(Ft=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Nt=e.dynCall_ji=function(){return(Nt=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Lt=e.dynCall_iiiiiij=function(){return(Lt=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},Rt=e.dynCall_iiij=function(){return(Rt=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function jt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!I)){if(Z(R),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();M.unshift(t)}Z(M)}}if(!(0<z)){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)V();Z(L),0<z||(e.setStatus?(e.setStatus("Running..."),setTimeout((function(){setTimeout((function(){e.setStatus("")}),1),t()}),1)):t())}}if(e.UTF8ToString=$,e.stringToUTF8=function(t,e,n){return k(t,O,e,n)},e.lengthBytesUTF8=C,e.stackSave=Tt,e.stackRestore=St,e.stackAlloc=Ot,H=function t(){mt||jt(),mt||(H=t)},e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.pop()();return jt(),t.ready});t.exports=r},4537:t=>{"use strict";t.exports=function(t,e){for(var n=new Array(arguments.length-1),r=0,i=2,o=!0;i<arguments.length;)n[r++]=arguments[i++];return new Promise((function(i,a){n[r]=function(t){if(o)if(o=!1,t)a(t);else{for(var e=new Array(arguments.length-1),n=0;n<e.length;)e[n++]=arguments[n];i.apply(null,e)}};try{t.apply(e||null,n)}catch(t){o&&(o=!1,a(t))}}))}},7419:(t,e)=>{"use strict";var n=e;n.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;--e%4>1&&"="===t.charAt(e);)++n;return Math.ceil(3*t.length)/4-n};for(var r=new Array(64),i=new Array(123),o=0;o<64;)i[r[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;n.encode=function(t,e,n){for(var i,o=null,a=[],s=0,u=0;e<n;){var c=t[e++];switch(u){case 0:a[s++]=r[c>>2],i=(3&c)<<4,u=1;break;case 1:a[s++]=r[i|c>>4],i=(15&c)<<2,u=2;break;case 2:a[s++]=r[i|c>>6],a[s++]=r[63&c],u=0}s>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,a)),s=0)}return u&&(a[s++]=r[i],a[s++]=61,1===u&&(a[s++]=61)),o?(s&&o.push(String.fromCharCode.apply(String,a.slice(0,s))),o.join("")):String.fromCharCode.apply(String,a.slice(0,s))};var a="invalid encoding";n.decode=function(t,e,n){for(var r,o=n,s=0,u=0;u<t.length;){var c=t.charCodeAt(u++);if(61===c&&s>1)break;if(void 0===(c=i[c]))throw Error(a);switch(s){case 0:r=c,s=1;break;case 1:e[n++]=r<<2|(48&c)>>4,r=c,s=2;break;case 2:e[n++]=(15&r)<<4|(60&c)>>2,r=c,s=3;break;case 3:e[n++]=(3&r)<<6|c,s=0}}if(1===s)throw Error(a);return n-o},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},9211:t=>{"use strict";function e(){this._listeners={}}t.exports=e,e.prototype.on=function(t,e,n){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:e,ctx:n||this}),this},e.prototype.off=function(t,e){if(void 0===t)this._listeners={};else if(void 0===e)this._listeners[t]=[];else for(var n=this._listeners[t],r=0;r<n.length;)n[r].fn===e?n.splice(r,1):++r;return this},e.prototype.emit=function(t){var e=this._listeners[t];if(e){for(var n=[],r=1;r<arguments.length;)n.push(arguments[r++]);for(r=0;r<e.length;)e[r].fn.apply(e[r++].ctx,n)}return this}},945:t=>{"use strict";function e(t){return"undefined"!=typeof Float32Array?function(){var e=new Float32Array([-0]),n=new Uint8Array(e.buffer),r=128===n[3];function i(t,r,i){e[0]=t,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3]}function o(t,r,i){e[0]=t,r[i]=n[3],r[i+1]=n[2],r[i+2]=n[1],r[i+3]=n[0]}function a(t,r){return n[0]=t[r],n[1]=t[r+1],n[2]=t[r+2],n[3]=t[r+3],e[0]}function s(t,r){return n[3]=t[r],n[2]=t[r+1],n[1]=t[r+2],n[0]=t[r+3],e[0]}t.writeFloatLE=r?i:o,t.writeFloatBE=r?o:i,t.readFloatLE=r?a:s,t.readFloatBE=r?s:a}():function(){function e(t,e,n,r){var i=e<0?1:0;if(i&&(e=-e),0===e)t(1/e>0?0:2147483648,n,r);else if(isNaN(e))t(2143289344,n,r);else if(e>34028234663852886e22)t((i<<31|2139095040)>>>0,n,r);else if(e<11754943508222875e-54)t((i<<31|Math.round(e/1401298464324817e-60))>>>0,n,r);else{var o=Math.floor(Math.log(e)/Math.LN2);t((i<<31|o+127<<23|8388607&Math.round(e*Math.pow(2,-o)*8388608))>>>0,n,r)}}function a(t,e,n){var r=t(e,n),i=2*(r>>31)+1,o=r>>>23&255,a=8388607&r;return 255===o?a?NaN:i*(1/0):0===o?1401298464324817e-60*i*a:i*Math.pow(2,o-150)*(a+8388608)}t.writeFloatLE=e.bind(null,n),t.writeFloatBE=e.bind(null,r),t.readFloatLE=a.bind(null,i),t.readFloatBE=a.bind(null,o)}(),"undefined"!=typeof Float64Array?function(){var e=new Float64Array([-0]),n=new Uint8Array(e.buffer),r=128===n[7];function i(t,r,i){e[0]=t,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3],r[i+4]=n[4],r[i+5]=n[5],r[i+6]=n[6],r[i+7]=n[7]}function o(t,r,i){e[0]=t,r[i]=n[7],r[i+1]=n[6],r[i+2]=n[5],r[i+3]=n[4],r[i+4]=n[3],r[i+5]=n[2],r[i+6]=n[1],r[i+7]=n[0]}function a(t,r){return n[0]=t[r],n[1]=t[r+1],n[2]=t[r+2],n[3]=t[r+3],n[4]=t[r+4],n[5]=t[r+5],n[6]=t[r+6],n[7]=t[r+7],e[0]}function s(t,r){return n[7]=t[r],n[6]=t[r+1],n[5]=t[r+2],n[4]=t[r+3],n[3]=t[r+4],n[2]=t[r+5],n[1]=t[r+6],n[0]=t[r+7],e[0]}t.writeDoubleLE=r?i:o,t.writeDoubleBE=r?o:i,t.readDoubleLE=r?a:s,t.readDoubleBE=r?s:a}():function(){function e(t,e,n,r,i,o){var a=r<0?1:0;if(a&&(r=-r),0===r)t(0,i,o+e),t(1/r>0?0:2147483648,i,o+n);else if(isNaN(r))t(0,i,o+e),t(2146959360,i,o+n);else if(r>17976931348623157e292)t(0,i,o+e),t((a<<31|2146435072)>>>0,i,o+n);else{var s;if(r<22250738585072014e-324)t((s=r/5e-324)>>>0,i,o+e),t((a<<31|s/4294967296)>>>0,i,o+n);else{var u=Math.floor(Math.log(r)/Math.LN2);1024===u&&(u=1023),t(4503599627370496*(s=r*Math.pow(2,-u))>>>0,i,o+e),t((a<<31|u+1023<<20|1048576*s&1048575)>>>0,i,o+n)}}}function a(t,e,n,r,i){var o=t(r,i+e),a=t(r,i+n),s=2*(a>>31)+1,u=a>>>20&2047,c=4294967296*(1048575&a)+o;return 2047===u?c?NaN:s*(1/0):0===u?5e-324*s*c:s*Math.pow(2,u-1075)*(c+4503599627370496)}t.writeDoubleLE=e.bind(null,n,0,4),t.writeDoubleBE=e.bind(null,r,4,0),t.readDoubleLE=a.bind(null,i,0,4),t.readDoubleBE=a.bind(null,o,4,0)}(),t}function n(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function r(t,e,n){e[n]=t>>>24,e[n+1]=t>>>16&255,e[n+2]=t>>>8&255,e[n+3]=255&t}function i(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function o(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}t.exports=e(e)},7199:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}module.exports=inquire},6662:t=>{"use strict";t.exports=function(t,e,n){var r=n||8192,i=r>>>1,o=null,a=r;return function(n){if(n<1||n>i)return t(n);a+n>r&&(o=t(r),a=0);var s=e.call(o,a,a+=n);return 7&a&&(a=1+(7|a)),s}}},4997:(t,e)=>{"use strict";var n=e;n.length=function(t){for(var e=0,n=0,r=0;r<t.length;++r)(n=t.charCodeAt(r))<128?e+=1:n<2048?e+=2:55296==(64512&n)&&56320==(64512&t.charCodeAt(r+1))?(++r,e+=4):e+=3;return e},n.read=function(t,e,n){if(n-e<1)return"";for(var r,i=null,o=[],a=0;e<n;)(r=t[e++])<128?o[a++]=r:r>191&&r<224?o[a++]=(31&r)<<6|63&t[e++]:r>239&&r<365?(r=((7&r)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,o[a++]=55296+(r>>10),o[a++]=56320+(1023&r)):o[a++]=(15&r)<<12|(63&t[e++])<<6|63&t[e++],a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0);return i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))},n.write=function(t,e,n){for(var r,i,o=n,a=0;a<t.length;++a)(r=t.charCodeAt(a))<128?e[n++]=r:r<2048?(e[n++]=r>>6|192,e[n++]=63&r|128):55296==(64512&r)&&56320==(64512&(i=t.charCodeAt(a+1)))?(r=65536+((1023&r)<<10)+(1023&i),++a,e[n++]=r>>18|240,e[n++]=r>>12&63|128,e[n++]=r>>6&63|128,e[n++]=63&r|128):(e[n++]=r>>12|224,e[n++]=r>>6&63|128,e[n++]=63&r|128);return n-o}},3442:(t,e)=>{"use strict";e.__esModule=!0;var n=function(){function t(e){if(!e)throw new TypeError("Invalid argument; `value` has no value.");this.value=t.EMPTY,e&&t.isGuid(e)&&(this.value=e)}return t.isGuid=function(e){var n=e.toString();return e&&(e instanceof t||t.validator.test(n))},t.create=function(){return new t([t.gen(2),t.gen(1),t.gen(1),t.gen(1),t.gen(3)].join("-"))},t.createEmpty=function(){return new t("emptyguid")},t.parse=function(e){return new t(e)},t.raw=function(){return[t.gen(2),t.gen(1),t.gen(1),t.gen(1),t.gen(3)].join("-")},t.gen=function(t){for(var e="",n=0;n<t;n++)e+=(65536*(1+Math.random())|0).toString(16).substring(1);return e},t.prototype.equals=function(e){return t.isGuid(e)&&this.value===e.toString()},t.prototype.isEmpty=function(){return this.value===t.EMPTY},t.prototype.toString=function(){return this.value},t.prototype.toJSON=function(){return{value:this.value}},t.validator=new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$","i"),t.EMPTY="00000000-0000-0000-0000-000000000000",t}();e.Guid=n},3720:t=>{t.exports=n;var e=null;try{e=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(t){}function n(t,e,n){this.low=0|t,this.high=0|e,this.unsigned=!!n}function r(t){return!0===(t&&t.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var i={},o={};function a(t,e){var n,r,a;return e?(a=0<=(t>>>=0)&&t<256)&&(r=o[t])?r:(n=u(t,(0|t)<0?-1:0,!0),a&&(o[t]=n),n):(a=-128<=(t|=0)&&t<128)&&(r=i[t])?r:(n=u(t,t<0?-1:0,!1),a&&(i[t]=n),n)}function s(t,e){if(isNaN(t))return e?m:b;if(e){if(t<0)return m;if(t>=d)return x}else{if(t<=-h)return T;if(t+1>=h)return w}return t<0?s(-t,e).neg():u(t%f|0,t/f|0,e)}function u(t,e,r){return new n(t,e,r)}n.fromInt=a,n.fromNumber=s,n.fromBits=u;var c=Math.pow;function l(t,e,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return b;if("number"==typeof e?(n=e,e=!1):e=!!e,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=t.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return l(t.substring(1),e,n).neg();for(var i=s(c(n,8)),o=b,a=0;a<t.length;a+=8){var u=Math.min(8,t.length-a),p=parseInt(t.substring(a,a+u),n);if(u<8){var f=s(c(n,u));o=o.mul(f).add(s(p))}else o=(o=o.mul(i)).add(s(p))}return o.unsigned=e,o}function p(t,e){return"number"==typeof t?s(t,e):"string"==typeof t?l(t,e):u(t.low,t.high,"boolean"==typeof e?e:t.unsigned)}n.fromString=l,n.fromValue=p;var f=4294967296,d=f*f,h=d/2,g=a(1<<24),b=a(0);n.ZERO=b;var m=a(0,!0);n.UZERO=m;var y=a(1);n.ONE=y;var _=a(1,!0);n.UONE=_;var v=a(-1);n.NEG_ONE=v;var w=u(-1,2147483647,!1);n.MAX_VALUE=w;var x=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=x;var T=u(0,-2147483648,!1);n.MIN_VALUE=T;var S=n.prototype;S.toInt=function(){return this.unsigned?this.low>>>0:this.low},S.toNumber=function(){return this.unsigned?(this.high>>>0)*f+(this.low>>>0):this.high*f+(this.low>>>0)},S.toString=function(t){if((t=t||10)<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(T)){var e=s(t),n=this.div(e),r=n.mul(e).sub(this);return n.toString(t)+r.toInt().toString(t)}return"-"+this.neg().toString(t)}for(var i=s(c(t,6),this.unsigned),o=this,a="";;){var u=o.div(i),l=(o.sub(u.mul(i)).toInt()>>>0).toString(t);if((o=u).isZero())return l+a;for(;l.length<6;)l="0"+l;a=""+l+a}},S.getHighBits=function(){return this.high},S.getHighBitsUnsigned=function(){return this.high>>>0},S.getLowBits=function(){return this.low},S.getLowBitsUnsigned=function(){return this.low>>>0},S.getNumBitsAbs=function(){if(this.isNegative())return this.eq(T)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,e=31;e>0&&0==(t&1<<e);e--);return 0!=this.high?e+33:e+1},S.isZero=function(){return 0===this.high&&0===this.low},S.eqz=S.isZero,S.isNegative=function(){return!this.unsigned&&this.high<0},S.isPositive=function(){return this.unsigned||this.high>=0},S.isOdd=function(){return 1==(1&this.low)},S.isEven=function(){return 0==(1&this.low)},S.equals=function(t){return r(t)||(t=p(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&this.high===t.high&&this.low===t.low},S.eq=S.equals,S.notEquals=function(t){return!this.eq(t)},S.neq=S.notEquals,S.ne=S.notEquals,S.lessThan=function(t){return this.comp(t)<0},S.lt=S.lessThan,S.lessThanOrEqual=function(t){return this.comp(t)<=0},S.lte=S.lessThanOrEqual,S.le=S.lessThanOrEqual,S.greaterThan=function(t){return this.comp(t)>0},S.gt=S.greaterThan,S.greaterThanOrEqual=function(t){return this.comp(t)>=0},S.gte=S.greaterThanOrEqual,S.ge=S.greaterThanOrEqual,S.compare=function(t){if(r(t)||(t=p(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},S.comp=S.compare,S.negate=function(){return!this.unsigned&&this.eq(T)?T:this.not().add(y)},S.neg=S.negate,S.add=function(t){r(t)||(t=p(t));var e=this.high>>>16,n=65535&this.high,i=this.low>>>16,o=65535&this.low,a=t.high>>>16,s=65535&t.high,c=t.low>>>16,l=0,f=0,d=0,h=0;return d+=(h+=o+(65535&t.low))>>>16,f+=(d+=i+c)>>>16,l+=(f+=n+s)>>>16,l+=e+a,u((d&=65535)<<16|(h&=65535),(l&=65535)<<16|(f&=65535),this.unsigned)},S.subtract=function(t){return r(t)||(t=p(t)),this.add(t.neg())},S.sub=S.subtract,S.multiply=function(t){if(this.isZero())return b;if(r(t)||(t=p(t)),e)return u(e.mul(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned);if(t.isZero())return b;if(this.eq(T))return t.isOdd()?T:b;if(t.eq(T))return this.isOdd()?T:b;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(g)&&t.lt(g))return s(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,i=65535&this.high,o=this.low>>>16,a=65535&this.low,c=t.high>>>16,l=65535&t.high,f=t.low>>>16,d=65535&t.low,h=0,m=0,y=0,_=0;return y+=(_+=a*d)>>>16,m+=(y+=o*d)>>>16,y&=65535,m+=(y+=a*f)>>>16,h+=(m+=i*d)>>>16,m&=65535,h+=(m+=o*f)>>>16,m&=65535,h+=(m+=a*l)>>>16,h+=n*d+i*f+o*l+a*c,u((y&=65535)<<16|(_&=65535),(h&=65535)<<16|(m&=65535),this.unsigned)},S.mul=S.multiply,S.divide=function(t){if(r(t)||(t=p(t)),t.isZero())throw Error("division by zero");var n,i,o;if(e)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?u((this.unsigned?e.div_u:e.div_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?m:b;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return m;if(t.gt(this.shru(1)))return _;o=m}else{if(this.eq(T))return t.eq(y)||t.eq(v)?T:t.eq(T)?y:(n=this.shr(1).div(t).shl(1)).eq(b)?t.isNegative()?y:v:(i=this.sub(t.mul(n)),o=n.add(i.div(t)));if(t.eq(T))return this.unsigned?m:b;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=b}for(i=this;i.gte(t);){n=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var a=Math.ceil(Math.log(n)/Math.LN2),l=a<=48?1:c(2,a-48),f=s(n),d=f.mul(t);d.isNegative()||d.gt(i);)d=(f=s(n-=l,this.unsigned)).mul(t);f.isZero()&&(f=y),o=o.add(f),i=i.sub(d)}return o},S.div=S.divide,S.modulo=function(t){return r(t)||(t=p(t)),e?u((this.unsigned?e.rem_u:e.rem_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},S.mod=S.modulo,S.rem=S.modulo,S.not=function(){return u(~this.low,~this.high,this.unsigned)},S.and=function(t){return r(t)||(t=p(t)),u(this.low&t.low,this.high&t.high,this.unsigned)},S.or=function(t){return r(t)||(t=p(t)),u(this.low|t.low,this.high|t.high,this.unsigned)},S.xor=function(t){return r(t)||(t=p(t)),u(this.low^t.low,this.high^t.high,this.unsigned)},S.shiftLeft=function(t){return r(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?u(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):u(0,this.low<<t-32,this.unsigned)},S.shl=S.shiftLeft,S.shiftRight=function(t){return r(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?u(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):u(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},S.shr=S.shiftRight,S.shiftRightUnsigned=function(t){if(r(t)&&(t=t.toInt()),0==(t&=63))return this;var e=this.high;return t<32?u(this.low>>>t|e<<32-t,e>>>t,this.unsigned):u(32===t?e:e>>>t-32,0,this.unsigned)},S.shru=S.shiftRightUnsigned,S.shr_u=S.shiftRightUnsigned,S.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},S.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},S.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},S.toBytesLE=function(){var t=this.high,e=this.low;return[255&e,e>>>8&255,e>>>16&255,e>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},S.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,e>>>24,e>>>16&255,e>>>8&255,255&e]},n.fromBytes=function(t,e,r){return r?n.fromBytesLE(t,e):n.fromBytesBE(t,e)},n.fromBytesLE=function(t,e){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},n.fromBytesBE=function(t,e){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)}},1446:(t,e,n)=>{"use strict";var r,i,o,a=n(2100),s=a.Reader,u=a.Writer,c=a.util,l=a.roots.default||(a.roots.default={});l.onnx=((o={}).Version=(r={},(i=Object.create(r))[r[0]="_START_VERSION"]=0,i[r[1]="IR_VERSION_2017_10_10"]=1,i[r[2]="IR_VERSION_2017_10_30"]=2,i[r[3]="IR_VERSION_2017_11_3"]=3,i[r[4]="IR_VERSION_2019_1_22"]=4,i[r[5]="IR_VERSION"]=5,i),o.AttributeProto=function(){function t(t){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.name="",t.prototype.refAttrName="",t.prototype.docString="",t.prototype.type=0,t.prototype.f=0,t.prototype.i=c.Long?c.Long.fromBits(0,0,!1):0,t.prototype.s=c.newBuffer([]),t.prototype.t=null,t.prototype.g=null,t.prototype.floats=c.emptyArray,t.prototype.ints=c.emptyArray,t.prototype.strings=c.emptyArray,t.prototype.tensors=c.emptyArray,t.prototype.graphs=c.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.name&&t.hasOwnProperty("name")&&e.uint32(10).string(t.name),null!=t.f&&t.hasOwnProperty("f")&&e.uint32(21).float(t.f),null!=t.i&&t.hasOwnProperty("i")&&e.uint32(24).int64(t.i),null!=t.s&&t.hasOwnProperty("s")&&e.uint32(34).bytes(t.s),null!=t.t&&t.hasOwnProperty("t")&&l.onnx.TensorProto.encode(t.t,e.uint32(42).fork()).ldelim(),null!=t.g&&t.hasOwnProperty("g")&&l.onnx.GraphProto.encode(t.g,e.uint32(50).fork()).ldelim(),null!=t.floats&&t.floats.length){e.uint32(58).fork();for(var n=0;n<t.floats.length;++n)e.float(t.floats[n]);e.ldelim()}if(null!=t.ints&&t.ints.length){for(e.uint32(66).fork(),n=0;n<t.ints.length;++n)e.int64(t.ints[n]);e.ldelim()}if(null!=t.strings&&t.strings.length)for(n=0;n<t.strings.length;++n)e.uint32(74).bytes(t.strings[n]);if(null!=t.tensors&&t.tensors.length)for(n=0;n<t.tensors.length;++n)l.onnx.TensorProto.encode(t.tensors[n],e.uint32(82).fork()).ldelim();if(null!=t.graphs&&t.graphs.length)for(n=0;n<t.graphs.length;++n)l.onnx.GraphProto.encode(t.graphs[n],e.uint32(90).fork()).ldelim();return null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(106).string(t.docString),null!=t.type&&t.hasOwnProperty("type")&&e.uint32(160).int32(t.type),null!=t.refAttrName&&t.hasOwnProperty("refAttrName")&&e.uint32(170).string(t.refAttrName),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.AttributeProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.name=t.string();break;case 21:r.refAttrName=t.string();break;case 13:r.docString=t.string();break;case 20:r.type=t.int32();break;case 2:r.f=t.float();break;case 3:r.i=t.int64();break;case 4:r.s=t.bytes();break;case 5:r.t=l.onnx.TensorProto.decode(t,t.uint32());break;case 6:r.g=l.onnx.GraphProto.decode(t,t.uint32());break;case 7:if(r.floats&&r.floats.length||(r.floats=[]),2==(7&i))for(var o=t.uint32()+t.pos;t.pos<o;)r.floats.push(t.float());else r.floats.push(t.float());break;case 8:if(r.ints&&r.ints.length||(r.ints=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.ints.push(t.int64());else r.ints.push(t.int64());break;case 9:r.strings&&r.strings.length||(r.strings=[]),r.strings.push(t.bytes());break;case 10:r.tensors&&r.tensors.length||(r.tensors=[]),r.tensors.push(l.onnx.TensorProto.decode(t,t.uint32()));break;case 11:r.graphs&&r.graphs.length||(r.graphs=[]),r.graphs.push(l.onnx.GraphProto.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.name&&t.hasOwnProperty("name")&&!c.isString(t.name))return"name: string expected";if(null!=t.refAttrName&&t.hasOwnProperty("refAttrName")&&!c.isString(t.refAttrName))return"refAttrName: string expected";if(null!=t.docString&&t.hasOwnProperty("docString")&&!c.isString(t.docString))return"docString: string expected";if(null!=t.type&&t.hasOwnProperty("type"))switch(t.type){default:return"type: enum value expected";case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:}if(null!=t.f&&t.hasOwnProperty("f")&&"number"!=typeof t.f)return"f: number expected";if(null!=t.i&&t.hasOwnProperty("i")&&!(c.isInteger(t.i)||t.i&&c.isInteger(t.i.low)&&c.isInteger(t.i.high)))return"i: integer|Long expected";if(null!=t.s&&t.hasOwnProperty("s")&&!(t.s&&"number"==typeof t.s.length||c.isString(t.s)))return"s: buffer expected";if(null!=t.t&&t.hasOwnProperty("t")&&(n=l.onnx.TensorProto.verify(t.t)))return"t."+n;if(null!=t.g&&t.hasOwnProperty("g")&&(n=l.onnx.GraphProto.verify(t.g)))return"g."+n;if(null!=t.floats&&t.hasOwnProperty("floats")){if(!Array.isArray(t.floats))return"floats: array expected";for(var e=0;e<t.floats.length;++e)if("number"!=typeof t.floats[e])return"floats: number[] expected"}if(null!=t.ints&&t.hasOwnProperty("ints")){if(!Array.isArray(t.ints))return"ints: array expected";for(e=0;e<t.ints.length;++e)if(!(c.isInteger(t.ints[e])||t.ints[e]&&c.isInteger(t.ints[e].low)&&c.isInteger(t.ints[e].high)))return"ints: integer|Long[] expected"}if(null!=t.strings&&t.hasOwnProperty("strings")){if(!Array.isArray(t.strings))return"strings: array expected";for(e=0;e<t.strings.length;++e)if(!(t.strings[e]&&"number"==typeof t.strings[e].length||c.isString(t.strings[e])))return"strings: buffer[] expected"}if(null!=t.tensors&&t.hasOwnProperty("tensors")){if(!Array.isArray(t.tensors))return"tensors: array expected";for(e=0;e<t.tensors.length;++e)if(n=l.onnx.TensorProto.verify(t.tensors[e]))return"tensors."+n}if(null!=t.graphs&&t.hasOwnProperty("graphs")){if(!Array.isArray(t.graphs))return"graphs: array expected";for(e=0;e<t.graphs.length;++e){var n;if(n=l.onnx.GraphProto.verify(t.graphs[e]))return"graphs."+n}}return null},t.fromObject=function(t){if(t instanceof l.onnx.AttributeProto)return t;var e=new l.onnx.AttributeProto;switch(null!=t.name&&(e.name=String(t.name)),null!=t.refAttrName&&(e.refAttrName=String(t.refAttrName)),null!=t.docString&&(e.docString=String(t.docString)),t.type){case"UNDEFINED":case 0:e.type=0;break;case"FLOAT":case 1:e.type=1;break;case"INT":case 2:e.type=2;break;case"STRING":case 3:e.type=3;break;case"TENSOR":case 4:e.type=4;break;case"GRAPH":case 5:e.type=5;break;case"FLOATS":case 6:e.type=6;break;case"INTS":case 7:e.type=7;break;case"STRINGS":case 8:e.type=8;break;case"TENSORS":case 9:e.type=9;break;case"GRAPHS":case 10:e.type=10}if(null!=t.f&&(e.f=Number(t.f)),null!=t.i&&(c.Long?(e.i=c.Long.fromValue(t.i)).unsigned=!1:"string"==typeof t.i?e.i=parseInt(t.i,10):"number"==typeof t.i?e.i=t.i:"object"==typeof t.i&&(e.i=new c.LongBits(t.i.low>>>0,t.i.high>>>0).toNumber())),null!=t.s&&("string"==typeof t.s?c.base64.decode(t.s,e.s=c.newBuffer(c.base64.length(t.s)),0):t.s.length&&(e.s=t.s)),null!=t.t){if("object"!=typeof t.t)throw TypeError(".onnx.AttributeProto.t: object expected");e.t=l.onnx.TensorProto.fromObject(t.t)}if(null!=t.g){if("object"!=typeof t.g)throw TypeError(".onnx.AttributeProto.g: object expected");e.g=l.onnx.GraphProto.fromObject(t.g)}if(t.floats){if(!Array.isArray(t.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");e.floats=[];for(var n=0;n<t.floats.length;++n)e.floats[n]=Number(t.floats[n])}if(t.ints){if(!Array.isArray(t.ints))throw TypeError(".onnx.AttributeProto.ints: array expected");for(e.ints=[],n=0;n<t.ints.length;++n)c.Long?(e.ints[n]=c.Long.fromValue(t.ints[n])).unsigned=!1:"string"==typeof t.ints[n]?e.ints[n]=parseInt(t.ints[n],10):"number"==typeof t.ints[n]?e.ints[n]=t.ints[n]:"object"==typeof t.ints[n]&&(e.ints[n]=new c.LongBits(t.ints[n].low>>>0,t.ints[n].high>>>0).toNumber())}if(t.strings){if(!Array.isArray(t.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(e.strings=[],n=0;n<t.strings.length;++n)"string"==typeof t.strings[n]?c.base64.decode(t.strings[n],e.strings[n]=c.newBuffer(c.base64.length(t.strings[n])),0):t.strings[n].length&&(e.strings[n]=t.strings[n])}if(t.tensors){if(!Array.isArray(t.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");for(e.tensors=[],n=0;n<t.tensors.length;++n){if("object"!=typeof t.tensors[n])throw TypeError(".onnx.AttributeProto.tensors: object expected");e.tensors[n]=l.onnx.TensorProto.fromObject(t.tensors[n])}}if(t.graphs){if(!Array.isArray(t.graphs))throw TypeError(".onnx.AttributeProto.graphs: array expected");for(e.graphs=[],n=0;n<t.graphs.length;++n){if("object"!=typeof t.graphs[n])throw TypeError(".onnx.AttributeProto.graphs: object expected");e.graphs[n]=l.onnx.GraphProto.fromObject(t.graphs[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.floats=[],n.ints=[],n.strings=[],n.tensors=[],n.graphs=[]),e.defaults){if(n.name="",n.f=0,c.Long){var r=new c.Long(0,0,!1);n.i=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.i=e.longs===String?"0":0;e.bytes===String?n.s="":(n.s=[],e.bytes!==Array&&(n.s=c.newBuffer(n.s))),n.t=null,n.g=null,n.docString="",n.type=e.enums===String?"UNDEFINED":0,n.refAttrName=""}if(null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.f&&t.hasOwnProperty("f")&&(n.f=e.json&&!isFinite(t.f)?String(t.f):t.f),null!=t.i&&t.hasOwnProperty("i")&&("number"==typeof t.i?n.i=e.longs===String?String(t.i):t.i:n.i=e.longs===String?c.Long.prototype.toString.call(t.i):e.longs===Number?new c.LongBits(t.i.low>>>0,t.i.high>>>0).toNumber():t.i),null!=t.s&&t.hasOwnProperty("s")&&(n.s=e.bytes===String?c.base64.encode(t.s,0,t.s.length):e.bytes===Array?Array.prototype.slice.call(t.s):t.s),null!=t.t&&t.hasOwnProperty("t")&&(n.t=l.onnx.TensorProto.toObject(t.t,e)),null!=t.g&&t.hasOwnProperty("g")&&(n.g=l.onnx.GraphProto.toObject(t.g,e)),t.floats&&t.floats.length){n.floats=[];for(var i=0;i<t.floats.length;++i)n.floats[i]=e.json&&!isFinite(t.floats[i])?String(t.floats[i]):t.floats[i]}if(t.ints&&t.ints.length)for(n.ints=[],i=0;i<t.ints.length;++i)"number"==typeof t.ints[i]?n.ints[i]=e.longs===String?String(t.ints[i]):t.ints[i]:n.ints[i]=e.longs===String?c.Long.prototype.toString.call(t.ints[i]):e.longs===Number?new c.LongBits(t.ints[i].low>>>0,t.ints[i].high>>>0).toNumber():t.ints[i];if(t.strings&&t.strings.length)for(n.strings=[],i=0;i<t.strings.length;++i)n.strings[i]=e.bytes===String?c.base64.encode(t.strings[i],0,t.strings[i].length):e.bytes===Array?Array.prototype.slice.call(t.strings[i]):t.strings[i];if(t.tensors&&t.tensors.length)for(n.tensors=[],i=0;i<t.tensors.length;++i)n.tensors[i]=l.onnx.TensorProto.toObject(t.tensors[i],e);if(t.graphs&&t.graphs.length)for(n.graphs=[],i=0;i<t.graphs.length;++i)n.graphs[i]=l.onnx.GraphProto.toObject(t.graphs[i],e);return null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),null!=t.type&&t.hasOwnProperty("type")&&(n.type=e.enums===String?l.onnx.AttributeProto.AttributeType[t.type]:t.type),null!=t.refAttrName&&t.hasOwnProperty("refAttrName")&&(n.refAttrName=t.refAttrName),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t.AttributeType=function(){var t={},e=Object.create(t);return e[t[0]="UNDEFINED"]=0,e[t[1]="FLOAT"]=1,e[t[2]="INT"]=2,e[t[3]="STRING"]=3,e[t[4]="TENSOR"]=4,e[t[5]="GRAPH"]=5,e[t[6]="FLOATS"]=6,e[t[7]="INTS"]=7,e[t[8]="STRINGS"]=8,e[t[9]="TENSORS"]=9,e[t[10]="GRAPHS"]=10,e}(),t}(),o.ValueInfoProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.name="",t.prototype.type=null,t.prototype.docString="",t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.name&&t.hasOwnProperty("name")&&e.uint32(10).string(t.name),null!=t.type&&t.hasOwnProperty("type")&&l.onnx.TypeProto.encode(t.type,e.uint32(18).fork()).ldelim(),null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(26).string(t.docString),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.ValueInfoProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.name=t.string();break;case 2:r.type=l.onnx.TypeProto.decode(t,t.uint32());break;case 3:r.docString=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.name&&t.hasOwnProperty("name")&&!c.isString(t.name))return"name: string expected";if(null!=t.type&&t.hasOwnProperty("type")){var e=l.onnx.TypeProto.verify(t.type);if(e)return"type."+e}return null!=t.docString&&t.hasOwnProperty("docString")&&!c.isString(t.docString)?"docString: string expected":null},t.fromObject=function(t){if(t instanceof l.onnx.ValueInfoProto)return t;var e=new l.onnx.ValueInfoProto;if(null!=t.name&&(e.name=String(t.name)),null!=t.type){if("object"!=typeof t.type)throw TypeError(".onnx.ValueInfoProto.type: object expected");e.type=l.onnx.TypeProto.fromObject(t.type)}return null!=t.docString&&(e.docString=String(t.docString)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.name="",n.type=null,n.docString=""),null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.type&&t.hasOwnProperty("type")&&(n.type=l.onnx.TypeProto.toObject(t.type,e)),null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),o.NodeProto=function(){function t(t){if(this.input=[],this.output=[],this.attribute=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.input=c.emptyArray,t.prototype.output=c.emptyArray,t.prototype.name="",t.prototype.opType="",t.prototype.domain="",t.prototype.attribute=c.emptyArray,t.prototype.docString="",t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.input&&t.input.length)for(var n=0;n<t.input.length;++n)e.uint32(10).string(t.input[n]);if(null!=t.output&&t.output.length)for(n=0;n<t.output.length;++n)e.uint32(18).string(t.output[n]);if(null!=t.name&&t.hasOwnProperty("name")&&e.uint32(26).string(t.name),null!=t.opType&&t.hasOwnProperty("opType")&&e.uint32(34).string(t.opType),null!=t.attribute&&t.attribute.length)for(n=0;n<t.attribute.length;++n)l.onnx.AttributeProto.encode(t.attribute[n],e.uint32(42).fork()).ldelim();return null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(50).string(t.docString),null!=t.domain&&t.hasOwnProperty("domain")&&e.uint32(58).string(t.domain),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.NodeProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.input&&r.input.length||(r.input=[]),r.input.push(t.string());break;case 2:r.output&&r.output.length||(r.output=[]),r.output.push(t.string());break;case 3:r.name=t.string();break;case 4:r.opType=t.string();break;case 7:r.domain=t.string();break;case 5:r.attribute&&r.attribute.length||(r.attribute=[]),r.attribute.push(l.onnx.AttributeProto.decode(t,t.uint32()));break;case 6:r.docString=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.input&&t.hasOwnProperty("input")){if(!Array.isArray(t.input))return"input: array expected";for(var e=0;e<t.input.length;++e)if(!c.isString(t.input[e]))return"input: string[] expected"}if(null!=t.output&&t.hasOwnProperty("output")){if(!Array.isArray(t.output))return"output: array expected";for(e=0;e<t.output.length;++e)if(!c.isString(t.output[e]))return"output: string[] expected"}if(null!=t.name&&t.hasOwnProperty("name")&&!c.isString(t.name))return"name: string expected";if(null!=t.opType&&t.hasOwnProperty("opType")&&!c.isString(t.opType))return"opType: string expected";if(null!=t.domain&&t.hasOwnProperty("domain")&&!c.isString(t.domain))return"domain: string expected";if(null!=t.attribute&&t.hasOwnProperty("attribute")){if(!Array.isArray(t.attribute))return"attribute: array expected";for(e=0;e<t.attribute.length;++e){var n=l.onnx.AttributeProto.verify(t.attribute[e]);if(n)return"attribute."+n}}return null!=t.docString&&t.hasOwnProperty("docString")&&!c.isString(t.docString)?"docString: string expected":null},t.fromObject=function(t){if(t instanceof l.onnx.NodeProto)return t;var e=new l.onnx.NodeProto;if(t.input){if(!Array.isArray(t.input))throw TypeError(".onnx.NodeProto.input: array expected");e.input=[];for(var n=0;n<t.input.length;++n)e.input[n]=String(t.input[n])}if(t.output){if(!Array.isArray(t.output))throw TypeError(".onnx.NodeProto.output: array expected");for(e.output=[],n=0;n<t.output.length;++n)e.output[n]=String(t.output[n])}if(null!=t.name&&(e.name=String(t.name)),null!=t.opType&&(e.opType=String(t.opType)),null!=t.domain&&(e.domain=String(t.domain)),t.attribute){if(!Array.isArray(t.attribute))throw TypeError(".onnx.NodeProto.attribute: array expected");for(e.attribute=[],n=0;n<t.attribute.length;++n){if("object"!=typeof t.attribute[n])throw TypeError(".onnx.NodeProto.attribute: object expected");e.attribute[n]=l.onnx.AttributeProto.fromObject(t.attribute[n])}}return null!=t.docString&&(e.docString=String(t.docString)),e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.input=[],n.output=[],n.attribute=[]),e.defaults&&(n.name="",n.opType="",n.docString="",n.domain=""),t.input&&t.input.length){n.input=[];for(var r=0;r<t.input.length;++r)n.input[r]=t.input[r]}if(t.output&&t.output.length)for(n.output=[],r=0;r<t.output.length;++r)n.output[r]=t.output[r];if(null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.opType&&t.hasOwnProperty("opType")&&(n.opType=t.opType),t.attribute&&t.attribute.length)for(n.attribute=[],r=0;r<t.attribute.length;++r)n.attribute[r]=l.onnx.AttributeProto.toObject(t.attribute[r],e);return null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),null!=t.domain&&t.hasOwnProperty("domain")&&(n.domain=t.domain),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),o.ModelProto=function(){function t(t){if(this.opsetImport=[],this.metadataProps=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.irVersion=c.Long?c.Long.fromBits(0,0,!1):0,t.prototype.opsetImport=c.emptyArray,t.prototype.producerName="",t.prototype.producerVersion="",t.prototype.domain="",t.prototype.modelVersion=c.Long?c.Long.fromBits(0,0,!1):0,t.prototype.docString="",t.prototype.graph=null,t.prototype.metadataProps=c.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.irVersion&&t.hasOwnProperty("irVersion")&&e.uint32(8).int64(t.irVersion),null!=t.producerName&&t.hasOwnProperty("producerName")&&e.uint32(18).string(t.producerName),null!=t.producerVersion&&t.hasOwnProperty("producerVersion")&&e.uint32(26).string(t.producerVersion),null!=t.domain&&t.hasOwnProperty("domain")&&e.uint32(34).string(t.domain),null!=t.modelVersion&&t.hasOwnProperty("modelVersion")&&e.uint32(40).int64(t.modelVersion),null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(50).string(t.docString),null!=t.graph&&t.hasOwnProperty("graph")&&l.onnx.GraphProto.encode(t.graph,e.uint32(58).fork()).ldelim(),null!=t.opsetImport&&t.opsetImport.length)for(var n=0;n<t.opsetImport.length;++n)l.onnx.OperatorSetIdProto.encode(t.opsetImport[n],e.uint32(66).fork()).ldelim();if(null!=t.metadataProps&&t.metadataProps.length)for(n=0;n<t.metadataProps.length;++n)l.onnx.StringStringEntryProto.encode(t.metadataProps[n],e.uint32(114).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.ModelProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.irVersion=t.int64();break;case 8:r.opsetImport&&r.opsetImport.length||(r.opsetImport=[]),r.opsetImport.push(l.onnx.OperatorSetIdProto.decode(t,t.uint32()));break;case 2:r.producerName=t.string();break;case 3:r.producerVersion=t.string();break;case 4:r.domain=t.string();break;case 5:r.modelVersion=t.int64();break;case 6:r.docString=t.string();break;case 7:r.graph=l.onnx.GraphProto.decode(t,t.uint32());break;case 14:r.metadataProps&&r.metadataProps.length||(r.metadataProps=[]),r.metadataProps.push(l.onnx.StringStringEntryProto.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.irVersion&&t.hasOwnProperty("irVersion")&&!(c.isInteger(t.irVersion)||t.irVersion&&c.isInteger(t.irVersion.low)&&c.isInteger(t.irVersion.high)))return"irVersion: integer|Long expected";if(null!=t.opsetImport&&t.hasOwnProperty("opsetImport")){if(!Array.isArray(t.opsetImport))return"opsetImport: array expected";for(var e=0;e<t.opsetImport.length;++e)if(n=l.onnx.OperatorSetIdProto.verify(t.opsetImport[e]))return"opsetImport."+n}if(null!=t.producerName&&t.hasOwnProperty("producerName")&&!c.isString(t.producerName))return"producerName: string expected";if(null!=t.producerVersion&&t.hasOwnProperty("producerVersion")&&!c.isString(t.producerVersion))return"producerVersion: string expected";if(null!=t.domain&&t.hasOwnProperty("domain")&&!c.isString(t.domain))return"domain: string expected";if(null!=t.modelVersion&&t.hasOwnProperty("modelVersion")&&!(c.isInteger(t.modelVersion)||t.modelVersion&&c.isInteger(t.modelVersion.low)&&c.isInteger(t.modelVersion.high)))return"modelVersion: integer|Long expected";if(null!=t.docString&&t.hasOwnProperty("docString")&&!c.isString(t.docString))return"docString: string expected";if(null!=t.graph&&t.hasOwnProperty("graph")&&(n=l.onnx.GraphProto.verify(t.graph)))return"graph."+n;if(null!=t.metadataProps&&t.hasOwnProperty("metadataProps")){if(!Array.isArray(t.metadataProps))return"metadataProps: array expected";for(e=0;e<t.metadataProps.length;++e){var n;if(n=l.onnx.StringStringEntryProto.verify(t.metadataProps[e]))return"metadataProps."+n}}return null},t.fromObject=function(t){if(t instanceof l.onnx.ModelProto)return t;var e=new l.onnx.ModelProto;if(null!=t.irVersion&&(c.Long?(e.irVersion=c.Long.fromValue(t.irVersion)).unsigned=!1:"string"==typeof t.irVersion?e.irVersion=parseInt(t.irVersion,10):"number"==typeof t.irVersion?e.irVersion=t.irVersion:"object"==typeof t.irVersion&&(e.irVersion=new c.LongBits(t.irVersion.low>>>0,t.irVersion.high>>>0).toNumber())),t.opsetImport){if(!Array.isArray(t.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");e.opsetImport=[];for(var n=0;n<t.opsetImport.length;++n){if("object"!=typeof t.opsetImport[n])throw TypeError(".onnx.ModelProto.opsetImport: object expected");e.opsetImport[n]=l.onnx.OperatorSetIdProto.fromObject(t.opsetImport[n])}}if(null!=t.producerName&&(e.producerName=String(t.producerName)),null!=t.producerVersion&&(e.producerVersion=String(t.producerVersion)),null!=t.domain&&(e.domain=String(t.domain)),null!=t.modelVersion&&(c.Long?(e.modelVersion=c.Long.fromValue(t.modelVersion)).unsigned=!1:"string"==typeof t.modelVersion?e.modelVersion=parseInt(t.modelVersion,10):"number"==typeof t.modelVersion?e.modelVersion=t.modelVersion:"object"==typeof t.modelVersion&&(e.modelVersion=new c.LongBits(t.modelVersion.low>>>0,t.modelVersion.high>>>0).toNumber())),null!=t.docString&&(e.docString=String(t.docString)),null!=t.graph){if("object"!=typeof t.graph)throw TypeError(".onnx.ModelProto.graph: object expected");e.graph=l.onnx.GraphProto.fromObject(t.graph)}if(t.metadataProps){if(!Array.isArray(t.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(e.metadataProps=[],n=0;n<t.metadataProps.length;++n){if("object"!=typeof t.metadataProps[n])throw TypeError(".onnx.ModelProto.metadataProps: object expected");e.metadataProps[n]=l.onnx.StringStringEntryProto.fromObject(t.metadataProps[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.opsetImport=[],n.metadataProps=[]),e.defaults){if(c.Long){var r=new c.Long(0,0,!1);n.irVersion=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.irVersion=e.longs===String?"0":0;n.producerName="",n.producerVersion="",n.domain="",c.Long?(r=new c.Long(0,0,!1),n.modelVersion=e.longs===String?r.toString():e.longs===Number?r.toNumber():r):n.modelVersion=e.longs===String?"0":0,n.docString="",n.graph=null}if(null!=t.irVersion&&t.hasOwnProperty("irVersion")&&("number"==typeof t.irVersion?n.irVersion=e.longs===String?String(t.irVersion):t.irVersion:n.irVersion=e.longs===String?c.Long.prototype.toString.call(t.irVersion):e.longs===Number?new c.LongBits(t.irVersion.low>>>0,t.irVersion.high>>>0).toNumber():t.irVersion),null!=t.producerName&&t.hasOwnProperty("producerName")&&(n.producerName=t.producerName),null!=t.producerVersion&&t.hasOwnProperty("producerVersion")&&(n.producerVersion=t.producerVersion),null!=t.domain&&t.hasOwnProperty("domain")&&(n.domain=t.domain),null!=t.modelVersion&&t.hasOwnProperty("modelVersion")&&("number"==typeof t.modelVersion?n.modelVersion=e.longs===String?String(t.modelVersion):t.modelVersion:n.modelVersion=e.longs===String?c.Long.prototype.toString.call(t.modelVersion):e.longs===Number?new c.LongBits(t.modelVersion.low>>>0,t.modelVersion.high>>>0).toNumber():t.modelVersion),null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),null!=t.graph&&t.hasOwnProperty("graph")&&(n.graph=l.onnx.GraphProto.toObject(t.graph,e)),t.opsetImport&&t.opsetImport.length){n.opsetImport=[];for(var i=0;i<t.opsetImport.length;++i)n.opsetImport[i]=l.onnx.OperatorSetIdProto.toObject(t.opsetImport[i],e)}if(t.metadataProps&&t.metadataProps.length)for(n.metadataProps=[],i=0;i<t.metadataProps.length;++i)n.metadataProps[i]=l.onnx.StringStringEntryProto.toObject(t.metadataProps[i],e);return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),o.StringStringEntryProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.key="",t.prototype.value="",t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.key&&t.hasOwnProperty("key")&&e.uint32(10).string(t.key),null!=t.value&&t.hasOwnProperty("value")&&e.uint32(18).string(t.value),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.StringStringEntryProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.key=t.string();break;case 2:r.value=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.key&&t.hasOwnProperty("key")&&!c.isString(t.key)?"key: string expected":null!=t.value&&t.hasOwnProperty("value")&&!c.isString(t.value)?"value: string expected":null},t.fromObject=function(t){if(t instanceof l.onnx.StringStringEntryProto)return t;var e=new l.onnx.StringStringEntryProto;return null!=t.key&&(e.key=String(t.key)),null!=t.value&&(e.value=String(t.value)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.key="",n.value=""),null!=t.key&&t.hasOwnProperty("key")&&(n.key=t.key),null!=t.value&&t.hasOwnProperty("value")&&(n.value=t.value),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),o.TensorAnnotation=function(){function t(t){if(this.quantParameterTensorNames=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.tensorName="",t.prototype.quantParameterTensorNames=c.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.tensorName&&t.hasOwnProperty("tensorName")&&e.uint32(10).string(t.tensorName),null!=t.quantParameterTensorNames&&t.quantParameterTensorNames.length)for(var n=0;n<t.quantParameterTensorNames.length;++n)l.onnx.StringStringEntryProto.encode(t.quantParameterTensorNames[n],e.uint32(18).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.TensorAnnotation;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.tensorName=t.string();break;case 2:r.quantParameterTensorNames&&r.quantParameterTensorNames.length||(r.quantParameterTensorNames=[]),r.quantParameterTensorNames.push(l.onnx.StringStringEntryProto.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.tensorName&&t.hasOwnProperty("tensorName")&&!c.isString(t.tensorName))return"tensorName: string expected";if(null!=t.quantParameterTensorNames&&t.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(t.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var e=0;e<t.quantParameterTensorNames.length;++e){var n=l.onnx.StringStringEntryProto.verify(t.quantParameterTensorNames[e]);if(n)return"quantParameterTensorNames."+n}}return null},t.fromObject=function(t){if(t instanceof l.onnx.TensorAnnotation)return t;var e=new l.onnx.TensorAnnotation;if(null!=t.tensorName&&(e.tensorName=String(t.tensorName)),t.quantParameterTensorNames){if(!Array.isArray(t.quantParameterTensorNames))throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");e.quantParameterTensorNames=[];for(var n=0;n<t.quantParameterTensorNames.length;++n){if("object"!=typeof t.quantParameterTensorNames[n])throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");e.quantParameterTensorNames[n]=l.onnx.StringStringEntryProto.fromObject(t.quantParameterTensorNames[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.quantParameterTensorNames=[]),e.defaults&&(n.tensorName=""),null!=t.tensorName&&t.hasOwnProperty("tensorName")&&(n.tensorName=t.tensorName),t.quantParameterTensorNames&&t.quantParameterTensorNames.length){n.quantParameterTensorNames=[];for(var r=0;r<t.quantParameterTensorNames.length;++r)n.quantParameterTensorNames[r]=l.onnx.StringStringEntryProto.toObject(t.quantParameterTensorNames[r],e)}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),o.GraphProto=function(){function t(t){if(this.node=[],this.initializer=[],this.input=[],this.output=[],this.valueInfo=[],this.quantizationAnnotation=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.node=c.emptyArray,t.prototype.name="",t.prototype.initializer=c.emptyArray,t.prototype.docString="",t.prototype.input=c.emptyArray,t.prototype.output=c.emptyArray,t.prototype.valueInfo=c.emptyArray,t.prototype.quantizationAnnotation=c.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.node&&t.node.length)for(var n=0;n<t.node.length;++n)l.onnx.NodeProto.encode(t.node[n],e.uint32(10).fork()).ldelim();if(null!=t.name&&t.hasOwnProperty("name")&&e.uint32(18).string(t.name),null!=t.initializer&&t.initializer.length)for(n=0;n<t.initializer.length;++n)l.onnx.TensorProto.encode(t.initializer[n],e.uint32(42).fork()).ldelim();if(null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(82).string(t.docString),null!=t.input&&t.input.length)for(n=0;n<t.input.length;++n)l.onnx.ValueInfoProto.encode(t.input[n],e.uint32(90).fork()).ldelim();if(null!=t.output&&t.output.length)for(n=0;n<t.output.length;++n)l.onnx.ValueInfoProto.encode(t.output[n],e.uint32(98).fork()).ldelim();if(null!=t.valueInfo&&t.valueInfo.length)for(n=0;n<t.valueInfo.length;++n)l.onnx.ValueInfoProto.encode(t.valueInfo[n],e.uint32(106).fork()).ldelim();if(null!=t.quantizationAnnotation&&t.quantizationAnnotation.length)for(n=0;n<t.quantizationAnnotation.length;++n)l.onnx.TensorAnnotation.encode(t.quantizationAnnotation[n],e.uint32(114).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.GraphProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.node&&r.node.length||(r.node=[]),r.node.push(l.onnx.NodeProto.decode(t,t.uint32()));break;case 2:r.name=t.string();break;case 5:r.initializer&&r.initializer.length||(r.initializer=[]),r.initializer.push(l.onnx.TensorProto.decode(t,t.uint32()));break;case 10:r.docString=t.string();break;case 11:r.input&&r.input.length||(r.input=[]),r.input.push(l.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 12:r.output&&r.output.length||(r.output=[]),r.output.push(l.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 13:r.valueInfo&&r.valueInfo.length||(r.valueInfo=[]),r.valueInfo.push(l.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 14:r.quantizationAnnotation&&r.quantizationAnnotation.length||(r.quantizationAnnotation=[]),r.quantizationAnnotation.push(l.onnx.TensorAnnotation.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.node&&t.hasOwnProperty("node")){if(!Array.isArray(t.node))return"node: array expected";for(var e=0;e<t.node.length;++e)if(n=l.onnx.NodeProto.verify(t.node[e]))return"node."+n}if(null!=t.name&&t.hasOwnProperty("name")&&!c.isString(t.name))return"name: string expected";if(null!=t.initializer&&t.hasOwnProperty("initializer")){if(!Array.isArray(t.initializer))return"initializer: array expected";for(e=0;e<t.initializer.length;++e)if(n=l.onnx.TensorProto.verify(t.initializer[e]))return"initializer."+n}if(null!=t.docString&&t.hasOwnProperty("docString")&&!c.isString(t.docString))return"docString: string expected";if(null!=t.input&&t.hasOwnProperty("input")){if(!Array.isArray(t.input))return"input: array expected";for(e=0;e<t.input.length;++e)if(n=l.onnx.ValueInfoProto.verify(t.input[e]))return"input."+n}if(null!=t.output&&t.hasOwnProperty("output")){if(!Array.isArray(t.output))return"output: array expected";for(e=0;e<t.output.length;++e)if(n=l.onnx.ValueInfoProto.verify(t.output[e]))return"output."+n}if(null!=t.valueInfo&&t.hasOwnProperty("valueInfo")){if(!Array.isArray(t.valueInfo))return"valueInfo: array expected";for(e=0;e<t.valueInfo.length;++e)if(n=l.onnx.ValueInfoProto.verify(t.valueInfo[e]))return"valueInfo."+n}if(null!=t.quantizationAnnotation&&t.hasOwnProperty("quantizationAnnotation")){if(!Array.isArray(t.quantizationAnnotation))return"quantizationAnnotation: array expected";for(e=0;e<t.quantizationAnnotation.length;++e){var n;if(n=l.onnx.TensorAnnotation.verify(t.quantizationAnnotation[e]))return"quantizationAnnotation."+n}}return null},t.fromObject=function(t){if(t instanceof l.onnx.GraphProto)return t;var e=new l.onnx.GraphProto;if(t.node){if(!Array.isArray(t.node))throw TypeError(".onnx.GraphProto.node: array expected");e.node=[];for(var n=0;n<t.node.length;++n){if("object"!=typeof t.node[n])throw TypeError(".onnx.GraphProto.node: object expected");e.node[n]=l.onnx.NodeProto.fromObject(t.node[n])}}if(null!=t.name&&(e.name=String(t.name)),t.initializer){if(!Array.isArray(t.initializer))throw TypeError(".onnx.GraphProto.initializer: array expected");for(e.initializer=[],n=0;n<t.initializer.length;++n){if("object"!=typeof t.initializer[n])throw TypeError(".onnx.GraphProto.initializer: object expected");e.initializer[n]=l.onnx.TensorProto.fromObject(t.initializer[n])}}if(null!=t.docString&&(e.docString=String(t.docString)),t.input){if(!Array.isArray(t.input))throw TypeError(".onnx.GraphProto.input: array expected");for(e.input=[],n=0;n<t.input.length;++n){if("object"!=typeof t.input[n])throw TypeError(".onnx.GraphProto.input: object expected");e.input[n]=l.onnx.ValueInfoProto.fromObject(t.input[n])}}if(t.output){if(!Array.isArray(t.output))throw TypeError(".onnx.GraphProto.output: array expected");for(e.output=[],n=0;n<t.output.length;++n){if("object"!=typeof t.output[n])throw TypeError(".onnx.GraphProto.output: object expected");e.output[n]=l.onnx.ValueInfoProto.fromObject(t.output[n])}}if(t.valueInfo){if(!Array.isArray(t.valueInfo))throw TypeError(".onnx.GraphProto.valueInfo: array expected");for(e.valueInfo=[],n=0;n<t.valueInfo.length;++n){if("object"!=typeof t.valueInfo[n])throw TypeError(".onnx.GraphProto.valueInfo: object expected");e.valueInfo[n]=l.onnx.ValueInfoProto.fromObject(t.valueInfo[n])}}if(t.quantizationAnnotation){if(!Array.isArray(t.quantizationAnnotation))throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");for(e.quantizationAnnotation=[],n=0;n<t.quantizationAnnotation.length;++n){if("object"!=typeof t.quantizationAnnotation[n])throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");e.quantizationAnnotation[n]=l.onnx.TensorAnnotation.fromObject(t.quantizationAnnotation[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.node=[],n.initializer=[],n.input=[],n.output=[],n.valueInfo=[],n.quantizationAnnotation=[]),e.defaults&&(n.name="",n.docString=""),t.node&&t.node.length){n.node=[];for(var r=0;r<t.node.length;++r)n.node[r]=l.onnx.NodeProto.toObject(t.node[r],e)}if(null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),t.initializer&&t.initializer.length)for(n.initializer=[],r=0;r<t.initializer.length;++r)n.initializer[r]=l.onnx.TensorProto.toObject(t.initializer[r],e);if(null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),t.input&&t.input.length)for(n.input=[],r=0;r<t.input.length;++r)n.input[r]=l.onnx.ValueInfoProto.toObject(t.input[r],e);if(t.output&&t.output.length)for(n.output=[],r=0;r<t.output.length;++r)n.output[r]=l.onnx.ValueInfoProto.toObject(t.output[r],e);if(t.valueInfo&&t.valueInfo.length)for(n.valueInfo=[],r=0;r<t.valueInfo.length;++r)n.valueInfo[r]=l.onnx.ValueInfoProto.toObject(t.valueInfo[r],e);if(t.quantizationAnnotation&&t.quantizationAnnotation.length)for(n.quantizationAnnotation=[],r=0;r<t.quantizationAnnotation.length;++r)n.quantizationAnnotation[r]=l.onnx.TensorAnnotation.toObject(t.quantizationAnnotation[r],e);return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),o.TensorProto=function(){function t(t){if(this.dims=[],this.floatData=[],this.int32Data=[],this.stringData=[],this.int64Data=[],this.externalData=[],this.doubleData=[],this.uint64Data=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.dims=c.emptyArray,t.prototype.dataType=0,t.prototype.segment=null,t.prototype.floatData=c.emptyArray,t.prototype.int32Data=c.emptyArray,t.prototype.stringData=c.emptyArray,t.prototype.int64Data=c.emptyArray,t.prototype.name="",t.prototype.docString="",t.prototype.rawData=c.newBuffer([]),t.prototype.externalData=c.emptyArray,t.prototype.dataLocation=0,t.prototype.doubleData=c.emptyArray,t.prototype.uint64Data=c.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.dims&&t.dims.length){e.uint32(10).fork();for(var n=0;n<t.dims.length;++n)e.int64(t.dims[n]);e.ldelim()}if(null!=t.dataType&&t.hasOwnProperty("dataType")&&e.uint32(16).int32(t.dataType),null!=t.segment&&t.hasOwnProperty("segment")&&l.onnx.TensorProto.Segment.encode(t.segment,e.uint32(26).fork()).ldelim(),null!=t.floatData&&t.floatData.length){for(e.uint32(34).fork(),n=0;n<t.floatData.length;++n)e.float(t.floatData[n]);e.ldelim()}if(null!=t.int32Data&&t.int32Data.length){for(e.uint32(42).fork(),n=0;n<t.int32Data.length;++n)e.int32(t.int32Data[n]);e.ldelim()}if(null!=t.stringData&&t.stringData.length)for(n=0;n<t.stringData.length;++n)e.uint32(50).bytes(t.stringData[n]);if(null!=t.int64Data&&t.int64Data.length){for(e.uint32(58).fork(),n=0;n<t.int64Data.length;++n)e.int64(t.int64Data[n]);e.ldelim()}if(null!=t.name&&t.hasOwnProperty("name")&&e.uint32(66).string(t.name),null!=t.rawData&&t.hasOwnProperty("rawData")&&e.uint32(74).bytes(t.rawData),null!=t.doubleData&&t.doubleData.length){for(e.uint32(82).fork(),n=0;n<t.doubleData.length;++n)e.double(t.doubleData[n]);e.ldelim()}if(null!=t.uint64Data&&t.uint64Data.length){for(e.uint32(90).fork(),n=0;n<t.uint64Data.length;++n)e.uint64(t.uint64Data[n]);e.ldelim()}if(null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(98).string(t.docString),null!=t.externalData&&t.externalData.length)for(n=0;n<t.externalData.length;++n)l.onnx.StringStringEntryProto.encode(t.externalData[n],e.uint32(106).fork()).ldelim();return null!=t.dataLocation&&t.hasOwnProperty("dataLocation")&&e.uint32(112).int32(t.dataLocation),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.TensorProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:if(r.dims&&r.dims.length||(r.dims=[]),2==(7&i))for(var o=t.uint32()+t.pos;t.pos<o;)r.dims.push(t.int64());else r.dims.push(t.int64());break;case 2:r.dataType=t.int32();break;case 3:r.segment=l.onnx.TensorProto.Segment.decode(t,t.uint32());break;case 4:if(r.floatData&&r.floatData.length||(r.floatData=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.floatData.push(t.float());else r.floatData.push(t.float());break;case 5:if(r.int32Data&&r.int32Data.length||(r.int32Data=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.int32Data.push(t.int32());else r.int32Data.push(t.int32());break;case 6:r.stringData&&r.stringData.length||(r.stringData=[]),r.stringData.push(t.bytes());break;case 7:if(r.int64Data&&r.int64Data.length||(r.int64Data=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.int64Data.push(t.int64());else r.int64Data.push(t.int64());break;case 8:r.name=t.string();break;case 12:r.docString=t.string();break;case 9:r.rawData=t.bytes();break;case 13:r.externalData&&r.externalData.length||(r.externalData=[]),r.externalData.push(l.onnx.StringStringEntryProto.decode(t,t.uint32()));break;case 14:r.dataLocation=t.int32();break;case 10:if(r.doubleData&&r.doubleData.length||(r.doubleData=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.doubleData.push(t.double());else r.doubleData.push(t.double());break;case 11:if(r.uint64Data&&r.uint64Data.length||(r.uint64Data=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.uint64Data.push(t.uint64());else r.uint64Data.push(t.uint64());break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.dims&&t.hasOwnProperty("dims")){if(!Array.isArray(t.dims))return"dims: array expected";for(var e=0;e<t.dims.length;++e)if(!(c.isInteger(t.dims[e])||t.dims[e]&&c.isInteger(t.dims[e].low)&&c.isInteger(t.dims[e].high)))return"dims: integer|Long[] expected"}if(null!=t.dataType&&t.hasOwnProperty("dataType")&&!c.isInteger(t.dataType))return"dataType: integer expected";if(null!=t.segment&&t.hasOwnProperty("segment")&&(n=l.onnx.TensorProto.Segment.verify(t.segment)))return"segment."+n;if(null!=t.floatData&&t.hasOwnProperty("floatData")){if(!Array.isArray(t.floatData))return"floatData: array expected";for(e=0;e<t.floatData.length;++e)if("number"!=typeof t.floatData[e])return"floatData: number[] expected"}if(null!=t.int32Data&&t.hasOwnProperty("int32Data")){if(!Array.isArray(t.int32Data))return"int32Data: array expected";for(e=0;e<t.int32Data.length;++e)if(!c.isInteger(t.int32Data[e]))return"int32Data: integer[] expected"}if(null!=t.stringData&&t.hasOwnProperty("stringData")){if(!Array.isArray(t.stringData))return"stringData: array expected";for(e=0;e<t.stringData.length;++e)if(!(t.stringData[e]&&"number"==typeof t.stringData[e].length||c.isString(t.stringData[e])))return"stringData: buffer[] expected"}if(null!=t.int64Data&&t.hasOwnProperty("int64Data")){if(!Array.isArray(t.int64Data))return"int64Data: array expected";for(e=0;e<t.int64Data.length;++e)if(!(c.isInteger(t.int64Data[e])||t.int64Data[e]&&c.isInteger(t.int64Data[e].low)&&c.isInteger(t.int64Data[e].high)))return"int64Data: integer|Long[] expected"}if(null!=t.name&&t.hasOwnProperty("name")&&!c.isString(t.name))return"name: string expected";if(null!=t.docString&&t.hasOwnProperty("docString")&&!c.isString(t.docString))return"docString: string expected";if(null!=t.rawData&&t.hasOwnProperty("rawData")&&!(t.rawData&&"number"==typeof t.rawData.length||c.isString(t.rawData)))return"rawData: buffer expected";if(null!=t.externalData&&t.hasOwnProperty("externalData")){if(!Array.isArray(t.externalData))return"externalData: array expected";for(e=0;e<t.externalData.length;++e){var n;if(n=l.onnx.StringStringEntryProto.verify(t.externalData[e]))return"externalData."+n}}if(null!=t.dataLocation&&t.hasOwnProperty("dataLocation"))switch(t.dataLocation){default:return"dataLocation: enum value expected";case 0:case 1:}if(null!=t.doubleData&&t.hasOwnProperty("doubleData")){if(!Array.isArray(t.doubleData))return"doubleData: array expected";for(e=0;e<t.doubleData.length;++e)if("number"!=typeof t.doubleData[e])return"doubleData: number[] expected"}if(null!=t.uint64Data&&t.hasOwnProperty("uint64Data")){if(!Array.isArray(t.uint64Data))return"uint64Data: array expected";for(e=0;e<t.uint64Data.length;++e)if(!(c.isInteger(t.uint64Data[e])||t.uint64Data[e]&&c.isInteger(t.uint64Data[e].low)&&c.isInteger(t.uint64Data[e].high)))return"uint64Data: integer|Long[] expected"}return null},t.fromObject=function(t){if(t instanceof l.onnx.TensorProto)return t;var e=new l.onnx.TensorProto;if(t.dims){if(!Array.isArray(t.dims))throw TypeError(".onnx.TensorProto.dims: array expected");e.dims=[];for(var n=0;n<t.dims.length;++n)c.Long?(e.dims[n]=c.Long.fromValue(t.dims[n])).unsigned=!1:"string"==typeof t.dims[n]?e.dims[n]=parseInt(t.dims[n],10):"number"==typeof t.dims[n]?e.dims[n]=t.dims[n]:"object"==typeof t.dims[n]&&(e.dims[n]=new c.LongBits(t.dims[n].low>>>0,t.dims[n].high>>>0).toNumber())}if(null!=t.dataType&&(e.dataType=0|t.dataType),null!=t.segment){if("object"!=typeof t.segment)throw TypeError(".onnx.TensorProto.segment: object expected");e.segment=l.onnx.TensorProto.Segment.fromObject(t.segment)}if(t.floatData){if(!Array.isArray(t.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(e.floatData=[],n=0;n<t.floatData.length;++n)e.floatData[n]=Number(t.floatData[n])}if(t.int32Data){if(!Array.isArray(t.int32Data))throw TypeError(".onnx.TensorProto.int32Data: array expected");for(e.int32Data=[],n=0;n<t.int32Data.length;++n)e.int32Data[n]=0|t.int32Data[n]}if(t.stringData){if(!Array.isArray(t.stringData))throw TypeError(".onnx.TensorProto.stringData: array expected");for(e.stringData=[],n=0;n<t.stringData.length;++n)"string"==typeof t.stringData[n]?c.base64.decode(t.stringData[n],e.stringData[n]=c.newBuffer(c.base64.length(t.stringData[n])),0):t.stringData[n].length&&(e.stringData[n]=t.stringData[n])}if(t.int64Data){if(!Array.isArray(t.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");for(e.int64Data=[],n=0;n<t.int64Data.length;++n)c.Long?(e.int64Data[n]=c.Long.fromValue(t.int64Data[n])).unsigned=!1:"string"==typeof t.int64Data[n]?e.int64Data[n]=parseInt(t.int64Data[n],10):"number"==typeof t.int64Data[n]?e.int64Data[n]=t.int64Data[n]:"object"==typeof t.int64Data[n]&&(e.int64Data[n]=new c.LongBits(t.int64Data[n].low>>>0,t.int64Data[n].high>>>0).toNumber())}if(null!=t.name&&(e.name=String(t.name)),null!=t.docString&&(e.docString=String(t.docString)),null!=t.rawData&&("string"==typeof t.rawData?c.base64.decode(t.rawData,e.rawData=c.newBuffer(c.base64.length(t.rawData)),0):t.rawData.length&&(e.rawData=t.rawData)),t.externalData){if(!Array.isArray(t.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(e.externalData=[],n=0;n<t.externalData.length;++n){if("object"!=typeof t.externalData[n])throw TypeError(".onnx.TensorProto.externalData: object expected");e.externalData[n]=l.onnx.StringStringEntryProto.fromObject(t.externalData[n])}}switch(t.dataLocation){case"DEFAULT":case 0:e.dataLocation=0;break;case"EXTERNAL":case 1:e.dataLocation=1}if(t.doubleData){if(!Array.isArray(t.doubleData))throw TypeError(".onnx.TensorProto.doubleData: array expected");for(e.doubleData=[],n=0;n<t.doubleData.length;++n)e.doubleData[n]=Number(t.doubleData[n])}if(t.uint64Data){if(!Array.isArray(t.uint64Data))throw TypeError(".onnx.TensorProto.uint64Data: array expected");for(e.uint64Data=[],n=0;n<t.uint64Data.length;++n)c.Long?(e.uint64Data[n]=c.Long.fromValue(t.uint64Data[n])).unsigned=!0:"string"==typeof t.uint64Data[n]?e.uint64Data[n]=parseInt(t.uint64Data[n],10):"number"==typeof t.uint64Data[n]?e.uint64Data[n]=t.uint64Data[n]:"object"==typeof t.uint64Data[n]&&(e.uint64Data[n]=new c.LongBits(t.uint64Data[n].low>>>0,t.uint64Data[n].high>>>0).toNumber(!0))}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.dims=[],n.floatData=[],n.int32Data=[],n.stringData=[],n.int64Data=[],n.doubleData=[],n.uint64Data=[],n.externalData=[]),e.defaults&&(n.dataType=0,n.segment=null,n.name="",e.bytes===String?n.rawData="":(n.rawData=[],e.bytes!==Array&&(n.rawData=c.newBuffer(n.rawData))),n.docString="",n.dataLocation=e.enums===String?"DEFAULT":0),t.dims&&t.dims.length){n.dims=[];for(var r=0;r<t.dims.length;++r)"number"==typeof t.dims[r]?n.dims[r]=e.longs===String?String(t.dims[r]):t.dims[r]:n.dims[r]=e.longs===String?c.Long.prototype.toString.call(t.dims[r]):e.longs===Number?new c.LongBits(t.dims[r].low>>>0,t.dims[r].high>>>0).toNumber():t.dims[r]}if(null!=t.dataType&&t.hasOwnProperty("dataType")&&(n.dataType=t.dataType),null!=t.segment&&t.hasOwnProperty("segment")&&(n.segment=l.onnx.TensorProto.Segment.toObject(t.segment,e)),t.floatData&&t.floatData.length)for(n.floatData=[],r=0;r<t.floatData.length;++r)n.floatData[r]=e.json&&!isFinite(t.floatData[r])?String(t.floatData[r]):t.floatData[r];if(t.int32Data&&t.int32Data.length)for(n.int32Data=[],r=0;r<t.int32Data.length;++r)n.int32Data[r]=t.int32Data[r];if(t.stringData&&t.stringData.length)for(n.stringData=[],r=0;r<t.stringData.length;++r)n.stringData[r]=e.bytes===String?c.base64.encode(t.stringData[r],0,t.stringData[r].length):e.bytes===Array?Array.prototype.slice.call(t.stringData[r]):t.stringData[r];if(t.int64Data&&t.int64Data.length)for(n.int64Data=[],r=0;r<t.int64Data.length;++r)"number"==typeof t.int64Data[r]?n.int64Data[r]=e.longs===String?String(t.int64Data[r]):t.int64Data[r]:n.int64Data[r]=e.longs===String?c.Long.prototype.toString.call(t.int64Data[r]):e.longs===Number?new c.LongBits(t.int64Data[r].low>>>0,t.int64Data[r].high>>>0).toNumber():t.int64Data[r];if(null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.rawData&&t.hasOwnProperty("rawData")&&(n.rawData=e.bytes===String?c.base64.encode(t.rawData,0,t.rawData.length):e.bytes===Array?Array.prototype.slice.call(t.rawData):t.rawData),t.doubleData&&t.doubleData.length)for(n.doubleData=[],r=0;r<t.doubleData.length;++r)n.doubleData[r]=e.json&&!isFinite(t.doubleData[r])?String(t.doubleData[r]):t.doubleData[r];if(t.uint64Data&&t.uint64Data.length)for(n.uint64Data=[],r=0;r<t.uint64Data.length;++r)"number"==typeof t.uint64Data[r]?n.uint64Data[r]=e.longs===String?String(t.uint64Data[r]):t.uint64Data[r]:n.uint64Data[r]=e.longs===String?c.Long.prototype.toString.call(t.uint64Data[r]):e.longs===Number?new c.LongBits(t.uint64Data[r].low>>>0,t.uint64Data[r].high>>>0).toNumber(!0):t.uint64Data[r];if(null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),t.externalData&&t.externalData.length)for(n.externalData=[],r=0;r<t.externalData.length;++r)n.externalData[r]=l.onnx.StringStringEntryProto.toObject(t.externalData[r],e);return null!=t.dataLocation&&t.hasOwnProperty("dataLocation")&&(n.dataLocation=e.enums===String?l.onnx.TensorProto.DataLocation[t.dataLocation]:t.dataLocation),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t.DataType=function(){var t={},e=Object.create(t);return e[t[0]="UNDEFINED"]=0,e[t[1]="FLOAT"]=1,e[t[2]="UINT8"]=2,e[t[3]="INT8"]=3,e[t[4]="UINT16"]=4,e[t[5]="INT16"]=5,e[t[6]="INT32"]=6,e[t[7]="INT64"]=7,e[t[8]="STRING"]=8,e[t[9]="BOOL"]=9,e[t[10]="FLOAT16"]=10,e[t[11]="DOUBLE"]=11,e[t[12]="UINT32"]=12,e[t[13]="UINT64"]=13,e[t[14]="COMPLEX64"]=14,e[t[15]="COMPLEX128"]=15,e[t[16]="BFLOAT16"]=16,e}(),t.Segment=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.begin=c.Long?c.Long.fromBits(0,0,!1):0,t.prototype.end=c.Long?c.Long.fromBits(0,0,!1):0,t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.begin&&t.hasOwnProperty("begin")&&e.uint32(8).int64(t.begin),null!=t.end&&t.hasOwnProperty("end")&&e.uint32(16).int64(t.end),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.TensorProto.Segment;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.begin=t.int64();break;case 2:r.end=t.int64();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.begin&&t.hasOwnProperty("begin")&&!(c.isInteger(t.begin)||t.begin&&c.isInteger(t.begin.low)&&c.isInteger(t.begin.high))?"begin: integer|Long expected":null!=t.end&&t.hasOwnProperty("end")&&!(c.isInteger(t.end)||t.end&&c.isInteger(t.end.low)&&c.isInteger(t.end.high))?"end: integer|Long expected":null},t.fromObject=function(t){if(t instanceof l.onnx.TensorProto.Segment)return t;var e=new l.onnx.TensorProto.Segment;return null!=t.begin&&(c.Long?(e.begin=c.Long.fromValue(t.begin)).unsigned=!1:"string"==typeof t.begin?e.begin=parseInt(t.begin,10):"number"==typeof t.begin?e.begin=t.begin:"object"==typeof t.begin&&(e.begin=new c.LongBits(t.begin.low>>>0,t.begin.high>>>0).toNumber())),null!=t.end&&(c.Long?(e.end=c.Long.fromValue(t.end)).unsigned=!1:"string"==typeof t.end?e.end=parseInt(t.end,10):"number"==typeof t.end?e.end=t.end:"object"==typeof t.end&&(e.end=new c.LongBits(t.end.low>>>0,t.end.high>>>0).toNumber())),e},t.toObject=function(t,e){e||(e={});var n={};if(e.defaults){if(c.Long){var r=new c.Long(0,0,!1);n.begin=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.begin=e.longs===String?"0":0;c.Long?(r=new c.Long(0,0,!1),n.end=e.longs===String?r.toString():e.longs===Number?r.toNumber():r):n.end=e.longs===String?"0":0}return null!=t.begin&&t.hasOwnProperty("begin")&&("number"==typeof t.begin?n.begin=e.longs===String?String(t.begin):t.begin:n.begin=e.longs===String?c.Long.prototype.toString.call(t.begin):e.longs===Number?new c.LongBits(t.begin.low>>>0,t.begin.high>>>0).toNumber():t.begin),null!=t.end&&t.hasOwnProperty("end")&&("number"==typeof t.end?n.end=e.longs===String?String(t.end):t.end:n.end=e.longs===String?c.Long.prototype.toString.call(t.end):e.longs===Number?new c.LongBits(t.end.low>>>0,t.end.high>>>0).toNumber():t.end),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),t.DataLocation=function(){var t={},e=Object.create(t);return e[t[0]="DEFAULT"]=0,e[t[1]="EXTERNAL"]=1,e}(),t}(),o.TensorShapeProto=function(){function t(t){if(this.dim=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.dim=c.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.dim&&t.dim.length)for(var n=0;n<t.dim.length;++n)l.onnx.TensorShapeProto.Dimension.encode(t.dim[n],e.uint32(10).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.TensorShapeProto;t.pos<n;){var i=t.uint32();i>>>3==1?(r.dim&&r.dim.length||(r.dim=[]),r.dim.push(l.onnx.TensorShapeProto.Dimension.decode(t,t.uint32()))):t.skipType(7&i)}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.dim&&t.hasOwnProperty("dim")){if(!Array.isArray(t.dim))return"dim: array expected";for(var e=0;e<t.dim.length;++e){var n=l.onnx.TensorShapeProto.Dimension.verify(t.dim[e]);if(n)return"dim."+n}}return null},t.fromObject=function(t){if(t instanceof l.onnx.TensorShapeProto)return t;var e=new l.onnx.TensorShapeProto;if(t.dim){if(!Array.isArray(t.dim))throw TypeError(".onnx.TensorShapeProto.dim: array expected");e.dim=[];for(var n=0;n<t.dim.length;++n){if("object"!=typeof t.dim[n])throw TypeError(".onnx.TensorShapeProto.dim: object expected");e.dim[n]=l.onnx.TensorShapeProto.Dimension.fromObject(t.dim[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.dim=[]),t.dim&&t.dim.length){n.dim=[];for(var r=0;r<t.dim.length;++r)n.dim[r]=l.onnx.TensorShapeProto.Dimension.toObject(t.dim[r],e)}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t.Dimension=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}var e;return t.prototype.dimValue=c.Long?c.Long.fromBits(0,0,!1):0,t.prototype.dimParam="",t.prototype.denotation="",Object.defineProperty(t.prototype,"value",{get:c.oneOfGetter(e=["dimValue","dimParam"]),set:c.oneOfSetter(e)}),t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.dimValue&&t.hasOwnProperty("dimValue")&&e.uint32(8).int64(t.dimValue),null!=t.dimParam&&t.hasOwnProperty("dimParam")&&e.uint32(18).string(t.dimParam),null!=t.denotation&&t.hasOwnProperty("denotation")&&e.uint32(26).string(t.denotation),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.TensorShapeProto.Dimension;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.dimValue=t.int64();break;case 2:r.dimParam=t.string();break;case 3:r.denotation=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";var e={};if(null!=t.dimValue&&t.hasOwnProperty("dimValue")&&(e.value=1,!(c.isInteger(t.dimValue)||t.dimValue&&c.isInteger(t.dimValue.low)&&c.isInteger(t.dimValue.high))))return"dimValue: integer|Long expected";if(null!=t.dimParam&&t.hasOwnProperty("dimParam")){if(1===e.value)return"value: multiple values";if(e.value=1,!c.isString(t.dimParam))return"dimParam: string expected"}return null!=t.denotation&&t.hasOwnProperty("denotation")&&!c.isString(t.denotation)?"denotation: string expected":null},t.fromObject=function(t){if(t instanceof l.onnx.TensorShapeProto.Dimension)return t;var e=new l.onnx.TensorShapeProto.Dimension;return null!=t.dimValue&&(c.Long?(e.dimValue=c.Long.fromValue(t.dimValue)).unsigned=!1:"string"==typeof t.dimValue?e.dimValue=parseInt(t.dimValue,10):"number"==typeof t.dimValue?e.dimValue=t.dimValue:"object"==typeof t.dimValue&&(e.dimValue=new c.LongBits(t.dimValue.low>>>0,t.dimValue.high>>>0).toNumber())),null!=t.dimParam&&(e.dimParam=String(t.dimParam)),null!=t.denotation&&(e.denotation=String(t.denotation)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.denotation=""),null!=t.dimValue&&t.hasOwnProperty("dimValue")&&("number"==typeof t.dimValue?n.dimValue=e.longs===String?String(t.dimValue):t.dimValue:n.dimValue=e.longs===String?c.Long.prototype.toString.call(t.dimValue):e.longs===Number?new c.LongBits(t.dimValue.low>>>0,t.dimValue.high>>>0).toNumber():t.dimValue,e.oneofs&&(n.value="dimValue")),null!=t.dimParam&&t.hasOwnProperty("dimParam")&&(n.dimParam=t.dimParam,e.oneofs&&(n.value="dimParam")),null!=t.denotation&&t.hasOwnProperty("denotation")&&(n.denotation=t.denotation),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),t}(),o.TypeProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}var e;return t.prototype.tensorType=null,t.prototype.denotation="",Object.defineProperty(t.prototype,"value",{get:c.oneOfGetter(e=["tensorType"]),set:c.oneOfSetter(e)}),t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.tensorType&&t.hasOwnProperty("tensorType")&&l.onnx.TypeProto.Tensor.encode(t.tensorType,e.uint32(10).fork()).ldelim(),null!=t.denotation&&t.hasOwnProperty("denotation")&&e.uint32(50).string(t.denotation),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.TypeProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.tensorType=l.onnx.TypeProto.Tensor.decode(t,t.uint32());break;case 6:r.denotation=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.tensorType&&t.hasOwnProperty("tensorType")){var e=l.onnx.TypeProto.Tensor.verify(t.tensorType);if(e)return"tensorType."+e}return null!=t.denotation&&t.hasOwnProperty("denotation")&&!c.isString(t.denotation)?"denotation: string expected":null},t.fromObject=function(t){if(t instanceof l.onnx.TypeProto)return t;var e=new l.onnx.TypeProto;if(null!=t.tensorType){if("object"!=typeof t.tensorType)throw TypeError(".onnx.TypeProto.tensorType: object expected");e.tensorType=l.onnx.TypeProto.Tensor.fromObject(t.tensorType)}return null!=t.denotation&&(e.denotation=String(t.denotation)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.denotation=""),null!=t.tensorType&&t.hasOwnProperty("tensorType")&&(n.tensorType=l.onnx.TypeProto.Tensor.toObject(t.tensorType,e),e.oneofs&&(n.value="tensorType")),null!=t.denotation&&t.hasOwnProperty("denotation")&&(n.denotation=t.denotation),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t.Tensor=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.elemType=0,t.prototype.shape=null,t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.elemType&&t.hasOwnProperty("elemType")&&e.uint32(8).int32(t.elemType),null!=t.shape&&t.hasOwnProperty("shape")&&l.onnx.TensorShapeProto.encode(t.shape,e.uint32(18).fork()).ldelim(),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.TypeProto.Tensor;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.elemType=t.int32();break;case 2:r.shape=l.onnx.TensorShapeProto.decode(t,t.uint32());break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.elemType&&t.hasOwnProperty("elemType")&&!c.isInteger(t.elemType))return"elemType: integer expected";if(null!=t.shape&&t.hasOwnProperty("shape")){var e=l.onnx.TensorShapeProto.verify(t.shape);if(e)return"shape."+e}return null},t.fromObject=function(t){if(t instanceof l.onnx.TypeProto.Tensor)return t;var e=new l.onnx.TypeProto.Tensor;if(null!=t.elemType&&(e.elemType=0|t.elemType),null!=t.shape){if("object"!=typeof t.shape)throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");e.shape=l.onnx.TensorShapeProto.fromObject(t.shape)}return e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.elemType=0,n.shape=null),null!=t.elemType&&t.hasOwnProperty("elemType")&&(n.elemType=t.elemType),null!=t.shape&&t.hasOwnProperty("shape")&&(n.shape=l.onnx.TensorShapeProto.toObject(t.shape,e)),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),t}(),o.OperatorSetIdProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.domain="",t.prototype.version=c.Long?c.Long.fromBits(0,0,!1):0,t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.domain&&t.hasOwnProperty("domain")&&e.uint32(10).string(t.domain),null!=t.version&&t.hasOwnProperty("version")&&e.uint32(16).int64(t.version),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof s||(t=s.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new l.onnx.OperatorSetIdProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.domain=t.string();break;case 2:r.version=t.int64();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.domain&&t.hasOwnProperty("domain")&&!c.isString(t.domain)?"domain: string expected":null!=t.version&&t.hasOwnProperty("version")&&!(c.isInteger(t.version)||t.version&&c.isInteger(t.version.low)&&c.isInteger(t.version.high))?"version: integer|Long expected":null},t.fromObject=function(t){if(t instanceof l.onnx.OperatorSetIdProto)return t;var e=new l.onnx.OperatorSetIdProto;return null!=t.domain&&(e.domain=String(t.domain)),null!=t.version&&(c.Long?(e.version=c.Long.fromValue(t.version)).unsigned=!1:"string"==typeof t.version?e.version=parseInt(t.version,10):"number"==typeof t.version?e.version=t.version:"object"==typeof t.version&&(e.version=new c.LongBits(t.version.low>>>0,t.version.high>>>0).toNumber())),e},t.toObject=function(t,e){e||(e={});var n={};if(e.defaults)if(n.domain="",c.Long){var r=new c.Long(0,0,!1);n.version=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.version=e.longs===String?"0":0;return null!=t.domain&&t.hasOwnProperty("domain")&&(n.domain=t.domain),null!=t.version&&t.hasOwnProperty("version")&&("number"==typeof t.version?n.version=e.longs===String?String(t.version):t.version:n.version=e.longs===String?c.Long.prototype.toString.call(t.version):e.longs===Number?new c.LongBits(t.version.low>>>0,t.version.high>>>0).toNumber():t.version),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),o),t.exports=l},2100:(t,e,n)=>{"use strict";t.exports=n(9482)},9482:(t,e,n)=>{"use strict";var r=e;function i(){r.util._configure(),r.Writer._configure(r.BufferWriter),r.Reader._configure(r.BufferReader)}r.build="minimal",r.Writer=n(1173),r.BufferWriter=n(3155),r.Reader=n(1408),r.BufferReader=n(593),r.util=n(9693),r.rpc=n(5994),r.roots=n(5054),r.configure=i,i()},1408:(t,e,n)=>{"use strict";t.exports=u;var r,i=n(9693),o=i.LongBits,a=i.utf8;function s(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function u(t){this.buf=t,this.pos=0,this.len=t.length}var c,l="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new u(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new u(t);throw Error("illegal buffer")},p=function(){return i.Buffer?function(t){return(u.create=function(t){return i.Buffer.isBuffer(t)?new r(t):l(t)})(t)}:l};function f(){var t=new o(0,0),e=0;if(!(this.len-this.pos>4)){for(;e<3;++e){if(this.pos>=this.len)throw s(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw s(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function d(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}function h(){if(this.pos+8>this.len)throw s(this,8);return new o(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}u.create=p(),u.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,u.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return c;if((this.pos+=5)>this.len)throw this.pos=this.len,s(this,10);return c}),u.prototype.int32=function(){return 0|this.uint32()},u.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},u.prototype.bool=function(){return 0!==this.uint32()},u.prototype.fixed32=function(){if(this.pos+4>this.len)throw s(this,4);return d(this.buf,this.pos+=4)},u.prototype.sfixed32=function(){if(this.pos+4>this.len)throw s(this,4);return 0|d(this.buf,this.pos+=4)},u.prototype.float=function(){if(this.pos+4>this.len)throw s(this,4);var t=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},u.prototype.double=function(){if(this.pos+8>this.len)throw s(this,4);var t=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},u.prototype.bytes=function(){var t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw s(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(e,n):e===n?new this.buf.constructor(0):this._slice.call(this.buf,e,n)},u.prototype.string=function(){var t=this.bytes();return a.read(t,0,t.length)},u.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw s(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw s(this)}while(128&this.buf[this.pos++]);return this},u.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},u._configure=function(t){r=t,u.create=p(),r._configure();var e=i.Long?"toLong":"toNumber";i.merge(u.prototype,{int64:function(){return f.call(this)[e](!1)},uint64:function(){return f.call(this)[e](!0)},sint64:function(){return f.call(this).zzDecode()[e](!1)},fixed64:function(){return h.call(this)[e](!0)},sfixed64:function(){return h.call(this)[e](!1)}})}},593:(t,e,n)=>{"use strict";t.exports=o;var r=n(1408);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(t){r.call(this,t)}o._configure=function(){i.Buffer&&(o.prototype._slice=i.Buffer.prototype.slice)},o.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},o._configure()},5054:t=>{"use strict";t.exports={}},5994:(t,e,n)=>{"use strict";e.Service=n(7948)},7948:(t,e,n)=>{"use strict";t.exports=i;var r=n(9693);function i(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(e),this.responseDelimited=Boolean(n)}(i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function t(e,n,i,o,a){if(!o)throw TypeError("request must be specified");var s=this;if(!a)return r.asPromise(t,s,e,n,i,o);if(s.rpcImpl)try{return s.rpcImpl(e,n[s.requestDelimited?"encodeDelimited":"encode"](o).finish(),(function(t,n){if(t)return s.emit("error",t,e),a(t);if(null!==n){if(!(n instanceof i))try{n=i[s.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return s.emit("error",t,e),a(t)}return s.emit("data",n,e),a(null,n)}s.end(!0)}))}catch(t){return s.emit("error",t,e),void setTimeout((function(){a(t)}),0)}else setTimeout((function(){a(Error("already ended"))}),0)},i.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(t,e,n)=>{"use strict";t.exports=i;var r=n(9693);function i(t,e){this.lo=t>>>0,this.hi=e>>>0}var o=i.zero=new i(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var a=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(t){if(0===t)return o;var e=t<0;e&&(t=-t);var n=t>>>0,r=(t-n)/4294967296>>>0;return e&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new i(n,r)},i.from=function(t){if("number"==typeof t)return i.fromNumber(t);if(r.isString(t)){if(!r.Long)return i.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new i(t.low>>>0,t.high>>>0):o},i.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var e=1+~this.lo>>>0,n=~this.hi>>>0;return e||(n=n+1>>>0),-(e+4294967296*n)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var s=String.prototype.charCodeAt;i.fromHash=function(t){return t===a?o:new i((s.call(t,0)|s.call(t,1)<<8|s.call(t,2)<<16|s.call(t,3)<<24)>>>0,(s.call(t,4)|s.call(t,5)<<8|s.call(t,6)<<16|s.call(t,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},i.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},i.prototype.length=function(){var t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}},9693:function(t,e,n){"use strict";var r=e;function i(t,e,n){for(var r=Object.keys(e),i=0;i<r.length;++i)void 0!==t[r[i]]&&n||(t[r[i]]=e[r[i]]);return t}function o(t){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),n&&i(this,n)}return(e.prototype=Object.create(Error.prototype)).constructor=e,Object.defineProperty(e.prototype,"name",{get:function(){return t}}),e.prototype.toString=function(){return this.name+": "+this.message},e}r.asPromise=n(4537),r.base64=n(7419),r.EventEmitter=n(9211),r.float=n(945),r.inquire=n(7199),r.utf8=n(4997),r.pool=n(6662),r.LongBits=n(1945),r.isNode=Boolean(void 0!==n.g&&n.g&&n.g.process&&n.g.process.versions&&n.g.process.versions.node),r.global=r.isNode&&n.g||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},r.isString=function(t){return"string"==typeof t||t instanceof String},r.isObject=function(t){return t&&"object"==typeof t},r.isset=r.isSet=function(t,e){var n=t[e];return!(null==n||!t.hasOwnProperty(e))&&("object"!=typeof n||(Array.isArray(n)?n.length:Object.keys(n).length)>0)},r.Buffer=function(){try{var t=r.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(t){return"number"==typeof t?r.Buffer?r._Buffer_allocUnsafe(t):new r.Array(t):r.Buffer?r._Buffer_from(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(t){return t?r.LongBits.from(t).toHash():r.LongBits.zeroHash},r.longFromHash=function(t,e){var n=r.LongBits.fromHash(t);return r.Long?r.Long.fromBits(n.lo,n.hi,e):n.toNumber(Boolean(e))},r.merge=i,r.lcFirst=function(t){return t.charAt(0).toLowerCase()+t.substring(1)},r.newError=o,r.ProtocolError=o("ProtocolError"),r.oneOfGetter=function(t){for(var e={},n=0;n<t.length;++n)e[t[n]]=1;return function(){for(var t=Object.keys(this),n=t.length-1;n>-1;--n)if(1===e[t[n]]&&void 0!==this[t[n]]&&null!==this[t[n]])return t[n]}},r.oneOfSetter=function(t){return function(e){for(var n=0;n<t.length;++n)t[n]!==e&&delete this[t[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r._configure=function(){var t=r.Buffer;t?(r._Buffer_from=t.from!==Uint8Array.from&&t.from||function(e,n){return new t(e,n)},r._Buffer_allocUnsafe=t.allocUnsafe||function(e){return new t(e)}):r._Buffer_from=r._Buffer_allocUnsafe=null}},1173:(t,e,n)=>{"use strict";t.exports=p;var r,i=n(9693),o=i.LongBits,a=i.base64,s=i.utf8;function u(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}function c(){}function l(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function p(){this.len=0,this.head=new u(c,0,0),this.tail=this.head,this.states=null}var f=function(){return i.Buffer?function(){return(p.create=function(){return new r})()}:function(){return new p}};function d(t,e,n){e[n]=255&t}function h(t,e){this.len=t,this.next=void 0,this.val=e}function g(t,e,n){for(;t.hi;)e[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=127&t.lo|128,t.lo=t.lo>>>7;e[n++]=t.lo}function b(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}p.create=f(),p.alloc=function(t){return new i.Array(t)},i.Array!==Array&&(p.alloc=i.pool(p.alloc,i.Array.prototype.subarray)),p.prototype._push=function(t,e,n){return this.tail=this.tail.next=new u(t,e,n),this.len+=e,this},h.prototype=Object.create(u.prototype),h.prototype.fn=function(t,e,n){for(;t>127;)e[n++]=127&t|128,t>>>=7;e[n]=t},p.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new h((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},p.prototype.int32=function(t){return t<0?this._push(g,10,o.fromNumber(t)):this.uint32(t)},p.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},p.prototype.uint64=function(t){var e=o.from(t);return this._push(g,e.length(),e)},p.prototype.int64=p.prototype.uint64,p.prototype.sint64=function(t){var e=o.from(t).zzEncode();return this._push(g,e.length(),e)},p.prototype.bool=function(t){return this._push(d,1,t?1:0)},p.prototype.fixed32=function(t){return this._push(b,4,t>>>0)},p.prototype.sfixed32=p.prototype.fixed32,p.prototype.fixed64=function(t){var e=o.from(t);return this._push(b,4,e.lo)._push(b,4,e.hi)},p.prototype.sfixed64=p.prototype.fixed64,p.prototype.float=function(t){return this._push(i.float.writeFloatLE,4,t)},p.prototype.double=function(t){return this._push(i.float.writeDoubleLE,8,t)};var m=i.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var r=0;r<t.length;++r)e[n+r]=t[r]};p.prototype.bytes=function(t){var e=t.length>>>0;if(!e)return this._push(d,1,0);if(i.isString(t)){var n=p.alloc(e=a.length(t));a.decode(t,n,0),t=n}return this.uint32(e)._push(m,e,t)},p.prototype.string=function(t){var e=s.length(t);return e?this.uint32(e)._push(s.write,e,t):this._push(d,1,0)},p.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new u(c,0,0),this.len=0,this},p.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new u(c,0,0),this.len=0),this},p.prototype.ldelim=function(){var t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this},p.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e},p._configure=function(t){r=t,p.create=f(),r._configure()}},3155:(t,e,n)=>{"use strict";t.exports=o;var r=n(1173);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(){r.call(this)}function a(t,e,n){t.length<40?i.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}o._configure=function(){o.alloc=i._Buffer_allocUnsafe,o.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(t,e,n){e.set(t,n)}:function(t,e,n){if(t.copy)t.copy(e,n,0,t.length);else for(var r=0;r<t.length;)e[n++]=t[r++]}},o.prototype.bytes=function(t){i.isString(t)&&(t=i._Buffer_from(t,"base64"));var e=t.length>>>0;return this.uint32(e),e&&this._push(o.writeBytesBuffer,e,t),this},o.prototype.string=function(t){var e=i.Buffer.byteLength(t);return this.uint32(e),e&&this._push(a,e,t),this},o._configure()},7714:(t,e,n)=>{"use strict";e.R=void 0;const r=n(6919),i=n(7448);e.R=new class{async init(){}async createSessionHandler(t,e){const n=new r.Session(e);return await n.loadModel(t),new i.OnnxjsSessionHandler(n)}}},4200:(t,e,n)=>{"use strict";e.c8=e.rX=void 0;const r=n(1670),i=n(5381),o=n(2157),a=n(2306);e.rX=()=>{if(("number"!=typeof r.env.wasm.initTimeout||r.env.wasm.initTimeout<0)&&(r.env.wasm.initTimeout=0),"boolean"!=typeof r.env.wasm.simd&&(r.env.wasm.simd=!0),"boolean"!=typeof r.env.wasm.proxy&&(r.env.wasm.proxy=!1),"number"!=typeof r.env.wasm.numThreads||!Number.isInteger(r.env.wasm.numThreads)||r.env.wasm.numThreads<=0){const t="undefined"==typeof navigator?(0,i.cpus)().length:navigator.hardwareConcurrency;r.env.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},e.c8=new class{async init(){(0,e.rX)(),await(0,o.initWasm)()}async createSessionHandler(t,e){const n=new a.OnnxruntimeWebAssemblySessionHandler;return await n.loadModel(t,e),Promise.resolve(n)}}},6018:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||Object.prototype.hasOwnProperty.call(e,n)||r(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),i(n(1670),e);const o=n(1670);{const t=n(7714).R;(0,o.registerBackend)("webgl",t,-10)}{const t=n(4200).c8;(0,o.registerBackend)("cpu",t,10),(0,o.registerBackend)("wasm",t,10),(0,o.registerBackend)("xnnpack",t,9)}},246:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createAttributeWithCacheKey=void 0;class n{constructor(t){Object.assign(this,t)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map((t=>`${this[t]}`)).join(";")),this._cacheKey}}e.createAttributeWithCacheKey=t=>new n(t)},7778:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Attribute=void 0;const r=n(1446),i=n(9395),o=n(9162),a=n(2517);var s=i.onnxruntime.experimental.fbs;class u{constructor(t){if(this._attributes=new Map,null!=t){for(const e of t)e instanceof r.onnx.AttributeProto?this._attributes.set(e.name,[u.getValue(e),u.getType(e)]):e instanceof s.Attribute&&this._attributes.set(e.name(),[u.getValue(e),u.getType(e)]);if(this._attributes.size<t.length)throw new Error("duplicated attribute names")}}set(t,e,n){this._attributes.set(t,[n,e])}delete(t){this._attributes.delete(t)}getFloat(t,e){return this.get(t,"float",e)}getInt(t,e){return this.get(t,"int",e)}getString(t,e){return this.get(t,"string",e)}getTensor(t,e){return this.get(t,"tensor",e)}getFloats(t,e){return this.get(t,"floats",e)}getInts(t,e){return this.get(t,"ints",e)}getStrings(t,e){return this.get(t,"strings",e)}getTensors(t,e){return this.get(t,"tensors",e)}get(t,e,n){const r=this._attributes.get(t);if(void 0===r){if(void 0!==n)return n;throw new Error(`required attribute not found: ${t}`)}if(r[1]!==e)throw new Error(`type mismatch: expected ${e} but got ${r[1]}`);return r[0]}static getType(t){const e=t instanceof r.onnx.AttributeProto?t.type:t.type();switch(e){case r.onnx.AttributeProto.AttributeType.FLOAT:return"float";case r.onnx.AttributeProto.AttributeType.INT:return"int";case r.onnx.AttributeProto.AttributeType.STRING:return"string";case r.onnx.AttributeProto.AttributeType.TENSOR:return"tensor";case r.onnx.AttributeProto.AttributeType.FLOATS:return"floats";case r.onnx.AttributeProto.AttributeType.INTS:return"ints";case r.onnx.AttributeProto.AttributeType.STRINGS:return"strings";case r.onnx.AttributeProto.AttributeType.TENSORS:return"tensors";default:throw new Error(`attribute type is not supported yet: ${r.onnx.AttributeProto.AttributeType[e]}`)}}static getValue(t){const e=t instanceof r.onnx.AttributeProto?t.type:t.type();if(e===r.onnx.AttributeProto.AttributeType.GRAPH||e===r.onnx.AttributeProto.AttributeType.GRAPHS)throw new Error("graph attribute is not supported yet");const n=this.getValueNoCheck(t);if(e===r.onnx.AttributeProto.AttributeType.INT&&a.LongUtil.isLong(n))return a.LongUtil.longToNumber(n);if(e===r.onnx.AttributeProto.AttributeType.INTS){const t=n,e=new Array(t.length);for(let n=0;n<t.length;n++){const r=t[n];e[n]=a.LongUtil.longToNumber(r)}return e}if(e===r.onnx.AttributeProto.AttributeType.TENSOR)return t instanceof r.onnx.AttributeProto?o.Tensor.fromProto(n):o.Tensor.fromOrtTensor(n);if(e===r.onnx.AttributeProto.AttributeType.TENSORS){if(t instanceof r.onnx.AttributeProto)return n.map((t=>o.Tensor.fromProto(t)));if(t instanceof s.Attribute)return n.map((t=>o.Tensor.fromOrtTensor(t)))}if(e===r.onnx.AttributeProto.AttributeType.STRING&&t instanceof r.onnx.AttributeProto){const t=n;return(0,a.decodeUtf8String)(t)}return e===r.onnx.AttributeProto.AttributeType.STRINGS&&t instanceof r.onnx.AttributeProto?n.map(a.decodeUtf8String):n}static getValueNoCheck(t){return t instanceof r.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(t):this.getValueNoCheckFromOrtFormat(t)}static getValueNoCheckFromOnnxFormat(t){switch(t.type){case r.onnx.AttributeProto.AttributeType.FLOAT:return t.f;case r.onnx.AttributeProto.AttributeType.INT:return t.i;case r.onnx.AttributeProto.AttributeType.STRING:return t.s;case r.onnx.AttributeProto.AttributeType.TENSOR:return t.t;case r.onnx.AttributeProto.AttributeType.GRAPH:return t.g;case r.onnx.AttributeProto.AttributeType.FLOATS:return t.floats;case r.onnx.AttributeProto.AttributeType.INTS:return t.ints;case r.onnx.AttributeProto.AttributeType.STRINGS:return t.strings;case r.onnx.AttributeProto.AttributeType.TENSORS:return t.tensors;case r.onnx.AttributeProto.AttributeType.GRAPHS:return t.graphs;default:throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[t.type]}`)}}static getValueNoCheckFromOrtFormat(t){switch(t.type()){case s.AttributeType.FLOAT:return t.f();case s.AttributeType.INT:return t.i();case s.AttributeType.STRING:return t.s();case s.AttributeType.TENSOR:return t.t();case s.AttributeType.GRAPH:return t.g();case s.AttributeType.FLOATS:return t.floatsArray();case s.AttributeType.INTS:{const e=[];for(let n=0;n<t.intsLength();n++)e.push(t.ints(n));return e}case s.AttributeType.STRINGS:{const e=[];for(let n=0;n<t.stringsLength();n++)e.push(t.strings(n));return e}case s.AttributeType.TENSORS:{const e=[];for(let n=0;n<t.tensorsLength();n++)e.push(t.tensors(n));return e}default:throw new Error(`unsupported attribute type: ${s.AttributeType[t.type()]}`)}}}e.Attribute=u},7091:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.resolveBackend=e.backend=void 0;const r=n(5038),i=new Map;async function o(t){const n=e.backend;if(void 0!==n[t]&&function(t){const e=t;return"initialize"in e&&"function"==typeof e.initialize&&"createSessionHandler"in e&&"function"==typeof e.createSessionHandler&&"dispose"in e&&"function"==typeof e.dispose}(n[t])){const e=n[t];let r=e.initialize();if("object"==typeof r&&"then"in r&&(r=await r),r)return i.set(t,e),e}}e.backend={webgl:new r.WebGLBackend},e.resolveBackend=async function t(e){if(!e)return t(["webgl"]);{const t="string"==typeof e?[e]:e;for(const e of t){const t=i.get(e);if(t)return t;const n=await o(e);if(n)return n}}throw new Error("no available backend to use")}},5038:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLBackend=void 0;const r=n(1670),i=n(6231),o=n(6416),a=n(7305);e.WebGLBackend=class{get contextId(){return r.env.webgl.contextId}set contextId(t){r.env.webgl.contextId=t}get matmulMaxBatchSize(){return r.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(t){r.env.webgl.matmulMaxBatchSize=t}get textureCacheMode(){return r.env.webgl.textureCacheMode}set textureCacheMode(t){r.env.webgl.textureCacheMode=t}get pack(){return r.env.webgl.pack}set pack(t){r.env.webgl.pack=t}get async(){return r.env.webgl.async}set async(t){r.env.webgl.async=t}initialize(){try{return this.glContext=(0,a.createWebGLContext)(this.contextId),"number"!=typeof this.matmulMaxBatchSize&&(this.matmulMaxBatchSize=16),"string"!=typeof this.textureCacheMode&&(this.textureCacheMode="full"),"boolean"!=typeof this.pack&&(this.pack=!1),"boolean"!=typeof this.async&&(this.async=!1),i.Logger.setWithEnv(r.env),i.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(t){return i.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${t}`),!1}}createSessionHandler(t){return new o.WebGLSessionHandler(this,t)}dispose(){this.glContext.dispose()}}},5107:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CoordsGlslLib=void 0;const r=n(2517),i=n(8520),o=n(5060),a=n(7859),s=n(9390);class u extends i.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new i.GlslLibRoutine("\n      vec2 offsetToCoords(int offset, int width, int height) {\n        int t = offset / width;\n        int s = offset - t*width;\n        vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);\n        return coords;\n      }\n      ")}}coordsToOffset(){return{coordsToOffset:new i.GlslLibRoutine("\n      int coordsToOffset(vec2 coords, int width, int height) {\n        float s = coords.s * float(width);\n        float t = coords.t * float(height);\n        int offset = int(t) * width + int(s);\n        return offset;\n      }\n      ")}}getOutputSamplingSnippet(){const t=this.context.outputTextureLayout;return t.isPacked?this.getPackedOutputSamplingSnippet(t):this.getUnpackedOutputSamplingSnippet(t)}getPackedOutputSamplingSnippet(t){const e=t.unpackedShape,n=[t.width,t.height],r={},a="getOutputCoords";switch(e.length){case 0:r[a]=this.getOutputScalarCoords();break;case 1:r[a]=this.getOutputPacked1DCoords(e,n);break;case 2:r[a]=this.getOutputPacked2DCoords(e,n);break;case 3:r[a]=this.getOutputPacked3DCoords(e,n);break;default:r[a]=this.getOutputPackedNDCoords(e,n)}const s=`\n      void setOutput(vec4 val) {\n        ${(0,o.getGlsl)(this.context.glContext.version).output} = val;\n      }\n    `;return r.floatTextureSetRGBA=new i.GlslLibRoutine(s),r}getUnpackedOutputSamplingSnippet(t){const e=t.unpackedShape,n=[t.width,t.height],r={},a="getOutputCoords";switch(e.length){case 0:r[a]=this.getOutputScalarCoords();break;case 1:r[a]=this.getOutputUnpacked1DCoords(e,n);break;case 2:r[a]=this.getOutputUnpacked2DCoords(e,n);break;case 3:r[a]=this.getOutputUnpacked3DCoords(e,n);break;case 4:r[a]=this.getOutputUnpacked4DCoords(e,n);break;case 5:r[a]=this.getOutputUnpacked5DCoords(e,n);break;case 6:r[a]=this.getOutputUnpacked6DCoords(e,n);break;default:throw new Error(`Unsupported output dimensionality: ${e.length}`)}const s=`\n        void setOutput(float val) {\n          ${(0,o.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0);\n        }\n    `;return r.floatTextureSetR=new i.GlslLibRoutine(s),r}getOutputScalarCoords(){return new i.GlslLibRoutine("\n      int getOutputCoords() {\n        return 0;\n      }\n    ")}getOutputPacked1DCoords(t,e){const n=e;let r="";return 1===n[0]?(r=`\n          int getOutputCoords() {\n            return 2 * int(TexCoords.y * ${n[1]}.0);\n          }\n        `,new i.GlslLibRoutine(r)):1===n[1]?(r=`\n          int getOutputCoords() {\n            return 2 * int(TexCoords.x * ${n[0]}.0);\n          }\n        `,new i.GlslLibRoutine(r)):(r=`\n        int getOutputCoords() {\n          ivec2 resTexRC = ivec2(TexCoords.xy *\n                                 vec2(${n[0]}, ${n[1]}));\n          return 2 * (resTexRC.y * ${n[0]} + resTexRC.x);\n        }\n      `,new i.GlslLibRoutine(r))}getOutputPacked2DCoords(t,e){let n="";if(r.ArrayUtil.arraysEqual(t,e))return n=`\n        ivec2 getOutputCoords() {\n          return 2 * ivec2(TexCoords.xy * vec2(${e[0]}, ${e[1]}));\n        }\n      `,new i.GlslLibRoutine(n);const o=e,a=Math.ceil(t[1]/2);return n=`\n        ivec2 getOutputCoords() {\n          ivec2 resTexRC = ivec2(TexCoords.xy *\n                                vec2(${o[0]}, ${o[1]}));\n\n          int index = resTexRC.y * ${o[0]} + resTexRC.x;\n\n          // reverse r and c order for packed texture\n          int r = imod(index, ${a}) * 2;\n          int c = 2 * (index / ${a});\n\n          return ivec2(r, c);\n        }\n      `,new i.GlslLibRoutine(n)}getOutputPacked3DCoords(t,e){const n=[e[0],e[1]],r=Math.ceil(t[2]/2),o=r*Math.ceil(t[1]/2),a=`\n        ivec3 getOutputCoords() {\n          ivec2 resTexRC = ivec2(TexCoords.xy *\n                                vec2(${n[0]}, ${n[1]}));\n          int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n          int b = index / ${o};\n          index -= b * ${o};\n\n          // reverse r and c order for packed texture\n          int r = imod(index, ${r}) * 2;\n          int c = 2 * (index / ${r});\n\n          return ivec3(b, r, c);\n        }\n      `;return new i.GlslLibRoutine(a)}getOutputPackedNDCoords(t,e){const n=[e[0],e[1]],r=Math.ceil(t[t.length-1]/2),o=r*Math.ceil(t[t.length-2]/2);let a=o,s="",u="b, r, c";for(let e=2;e<t.length-1;e++)a*=t[t.length-e-1],s=`\n      int b${e} = index / ${a};\n      index -= b${e} * ${a};\n    `+s,u=`b${e}, `+u;const c=`\n      ivec${t.length} getOutputCoords() {\n        ivec2 resTexRC = ivec2(TexCoords.xy *\n                              vec2(${n[0]}, ${n[1]}));\n        int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n        ${s}\n\n        int b = index / ${o};\n        index -= b * ${o};\n\n        // reverse r and c order for packed texture\n        int r = imod(index, ${r}) * 2;\n        int c = 2 * (index / ${r});\n\n        return ivec${t.length}(${u});\n      }\n    `;return new i.GlslLibRoutine(c)}getOutputUnpacked1DCoords(t,e){const n=`\n        int getOutputCoords() {\n          ivec2 resTexRC = ivec2(TexCoords.xy *\n                                vec2(${e[0]}, ${e[1]}));\n          return resTexRC.y * ${e[0]} + resTexRC.x;\n        }\n      `;return new i.GlslLibRoutine(n)}getOutputUnpacked2DCoords(t,e){const n=`\n        ivec2 getOutputCoords() {\n          ivec2 resTexRC = ivec2(TexCoords.xy *\n                                vec2(${e[0]}, ${e[1]}));\n          int index = resTexRC.y * ${e[0]} + resTexRC.x;\n          int r = index / ${t[1]};\n          int c = index - r * ${t[1]};\n          return ivec2(r, c);\n        }\n      `;return new i.GlslLibRoutine(n)}getOutputUnpacked3DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const a=["r","c","d"],s=o.map(((t,e)=>`int ${a[e]} = index / ${t}; ${e===o.length-1?`int ${a[e+1]} = index - ${a[e]} * ${t}`:`index -= ${a[e]} * ${t}`};`)).join("");return n=`\n        ivec3 getOutputCoords() {\n          ivec2 resTexRC = ivec2(TexCoords.xy *\n                                vec2(${e[0]}, ${e[1]}));\n          int index = resTexRC.y * ${e[0]} + resTexRC.x;\n          ${s}\n          return ivec3(r, c, d);\n        }\n      `,new i.GlslLibRoutine(n)}getOutputUnpacked4DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const a=["r","c","d","d2"],s=o.map(((t,e)=>`int ${a[e]} = index / ${t}; ${e===o.length-1?`int ${a[e+1]} = index - ${a[e]} * ${t}`:`index -= ${a[e]} * ${t}`};`)).join("");return n=`\n      ivec4 getOutputCoords() {\n          ivec2 resTexRC = ivec2(TexCoords.xy *\n                                vec2(${e[0]}, ${e[1]}));\n          int index = resTexRC.y * ${e[0]} + resTexRC.x;\n          ${s}\n          return ivec4(r, c, d, d2);\n        }\n      `,new i.GlslLibRoutine(n)}getOutputUnpacked5DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const a=["r","c","d","d2","d3"],s=o.map(((t,e)=>`int ${a[e]} = index / ${t}; ${e===o.length-1?`int ${a[e+1]} = index - ${a[e]} * ${t}`:`index -= ${a[e]} * ${t}`};`)).join("");return n=`\n      ivec5 getOutputCoords() {\n          ivec2 resTexRC = ivec2(TexCoords.xy *\n                                vec2(${e[0]}, ${e[1]}));\n          int index = resTexRC.y * ${e[0]} + resTexRC.x;\n          ${s}\n          return ivec5(r, c, d, d2, d3);\n        }\n      `,new i.GlslLibRoutine(n)}getOutputUnpacked6DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const a=["r","c","d","d2","d3","d4"],s=o.map(((t,e)=>`int ${a[e]} = index / ${t}; ${e===o.length-1?`int ${a[e+1]} = index - ${a[e]} * ${t}`:`index -= ${a[e]} * ${t}`};`)).join("");return n=`\n     ivec6 getOutputCoords() {\n         ivec2 resTexRC = ivec2(TexCoords.xy *\n                               vec2(${e[0]}, ${e[1]}));\n         int index = resTexRC.y * ${e[0]} + resTexRC.x;\n         ${s}\n         return ivec6(r, c, d, d2, d3, d4);\n       }\n     `,new i.GlslLibRoutine(n)}getCommonUtilFuncs(){const t={};let e="uvFromFlat";t[e]=new i.GlslLibRoutine("\n    vec2 uvFromFlat(int texNumR, int texNumC, int index) {\n      int texC = index / texNumR;\n      int texR = index - texC * texNumR;\n      // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to\n      //       v.\n      return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);\n    }\n    "),e="packedUVfrom1D",t[e]=new i.GlslLibRoutine("\n      vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n        int texelIndex = index / 2;\n        int texR = texelIndex / texNumC;\n        int texC = texelIndex - texR * texNumC;\n        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n      }\n      "),e="packedUVfrom2D",t[e]=new i.GlslLibRoutine("\n      vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {\n        int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n        int texR = texelIndex / texNumC;\n        int texC = texelIndex - texR * texNumC;\n        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n      }\n      "),e="packedUVfrom3D",t[e]=new i.GlslLibRoutine("\n      vec2 packedUVfrom3D(int texNumR, int texNumC,\n          int texelsInBatch, int texelsInLogicalRow, int b,\n          int row, int col) {\n        int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n        int texR = index / texNumC;\n        int texC = index - texR * texNumC;\n        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n      }\n      "),e="sampleTexture";const n=(0,o.getGlsl)(this.context.glContext.version);return t[e]=new i.GlslLibRoutine(`\n        float sampleTexture(sampler2D textureSampler, vec2 uv) {\n            return ${n.texture2D}(textureSampler, uv).r;\n        }`),t}getInputsSamplingSnippets(){const t={},e=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach(((n,r)=>{const i=this.context.inputTextureLayouts[r],o=(0,s.generateShaderFuncNameFromInputSamplerName)(n);i.isPacked?t[o]=this.getPackedSamplerFromInput(o,n,i):t[o]=this.getUnpackedSamplerFromInput(o,n,i);const a=(0,s.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n);i.unpackedShape.length<=e.unpackedShape.length&&(i.isPacked?t[a]=this.getPackedSamplerAtOutputCoords(a,i,e,n):t[a]=this.getUnpackedSamplerAtOutputCoords(a,i,e,n))})),t}getPackedSamplerAtOutputCoords(t,e,n,o){const a=e.unpackedShape,u=n.unpackedShape,c=o,l=(0,s.generateShaderFuncNameFromInputSamplerName)(c),p=a.length,f=u.length,d=r.BroadcastUtil.getBroadcastDims(a,u),h=(0,s.getCoordsDataType)(f),g=f-p;let b;const m=(0,s.getGlChannels)();b=0===p?"":f<2&&d.length>=1?"coords = 0;":d.map((t=>`coords.${m[t+g]} = 0;`)).join("\n");let y="";y=f<2&&p>0?"coords":a.map(((t,e)=>`coords.${m[e+g]}`)).join(", ");let _="return outputValue;";const v=1===r.ShapeUtil.size(a),w=1===r.ShapeUtil.size(u);if(1!==p||v||w){if(v&&!w)_=1===f?"\n          return vec4(outputValue.x, outputValue.x, 0., 0.);\n        ":"\n          return vec4(outputValue.x);\n        ";else if(d.length){const t=p-2,e=p-1;d.indexOf(t)>-1&&d.indexOf(e)>-1?_="return vec4(outputValue.x);":d.indexOf(t)>-1?_="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":d.indexOf(e)>-1&&(_="return vec4(outputValue.xx, outputValue.zz);")}}else _="\n        return vec4(outputValue.xy, outputValue.xy);\n      ";const x=`\n      vec4 ${t}() {\n        ${h} coords = getOutputCoords();\n        \n        int lastDim = coords.${m[f-1]};\n        coords.${m[f-1]} = coords.${m[f-2]};\n        coords.${m[f-2]} = lastDim;\n      \n        ${b}\n        vec4 outputValue = ${l}(${y});\n        ${_}\n      }\n    `;return new i.GlslLibRoutine(x,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(t,e,n,o){const a=[n.width,n.height],u=[e.width,e.height],c=e.unpackedShape.length,l=n.unpackedShape.length,p=e.unpackedShape,f=n.unpackedShape,d=(0,s.generateShaderFuncNameFromInputSamplerName)(o);if(c===l&&r.ArrayUtil.arraysEqual(u,a)){const e=`\n          float ${t}() {\n            return sampleTexture(${o}, TexCoords);\n          }\n        `;return new i.GlslLibRoutine(e,["coordinates.sampleTexture"])}const h=(0,s.getCoordsDataType)(l),g=r.BroadcastUtil.getBroadcastDims(p,f),b=l-c;let m;const y=(0,s.getGlChannels)();m=0===c?"":l<2&&g.length>=1?"coords = 0;":g.map((t=>`coords.${y[t+b]} = 0;`)).join("\n");let _="";_=l<2&&c>0?"coords":e.unpackedShape.map(((t,e)=>`coords.${y[e+b]}`)).join(", ");const v=`\n        float ${t}() {\n          ${h} coords = getOutputCoords();\n          ${m}\n          return ${d}(${_});\n        }\n      `;return new i.GlslLibRoutine(v,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(t,e,n){switch(n.unpackedShape.length){case 0:return this.getPackedSamplerScalar(t,e);case 1:return this.getPackedSampler1D(t,e,n);case 2:return this.getPackedSampler2D(t,e,n);case 3:return this.getPackedSampler3D(t,e,n);default:return this.getPackedSamplerND(t,e,n)}}getUnpackedSamplerFromInput(t,e,n){const r=n.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(t,e,n);case 1:return this.getUnpackedSampler1D(t,e,n);case 2:return this.getUnpackedSampler2D(t,e,n);case 3:return this.getUnpackedSampler3D(t,e,n);case 4:return this.getUnpackedSampler4D(t,e,n);case 5:return this.getUnpackedSampler5D(t,e,n);case 6:return this.getUnpackedSampler6D(t,e,n);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(t,e){const n=`\n          vec4 ${t}() {\n            return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${e}, halfCR);\n          }\n        `;return new i.GlslLibRoutine(n)}getPackedSampler1D(t,e,n){const r=[n.width,n.height],a=[r[1],r[0]],s=(0,o.getGlsl)(this.context.glContext.version),u=`vec4 ${t}(int index) {\n      vec2 uv = packedUVfrom1D(\n      ${a[0]}, ${a[1]}, index);\n      return ${s.texture2D}(${e}, uv);\n    }`;return new i.GlslLibRoutine(u,["coordinates.packedUVfrom1D"])}getPackedSampler2D(t,e,n){const a=n.unpackedShape,s=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),c=s[0],l=s[1];if(null!=s&&r.ArrayUtil.arraysEqual(a,s)){const n=`vec4 ${t}(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${l}.0, ${c}.0);\n        return ${u.texture2D}(${e}, uv);\n      }`;return new i.GlslLibRoutine(n)}const p=s,f=Math.ceil(a[1]/2),d=`vec4 ${t}(int row, int col) {\n      vec2 uv = packedUVfrom2D(${p[1]}, ${p[0]}, ${f}, row, col);\n      return ${u.texture2D}(${e}, uv);\n    }`;return new i.GlslLibRoutine(d,["coordinates.packedUVfrom2D"])}getPackedSampler3D(t,e,n){const r=n.unpackedShape,a=[n.width,n.height],u=[a[0],a[1]],c=(0,o.getGlsl)(this.context.glContext.version);if(1===r[0]){const o=r.slice(1),a=[1,2],u=(0,s.squeezeInputShape)(r,o),c=["b","row","col"],l=JSON.parse(JSON.stringify(n));l.unpackedShape=u;const p=this.getPackedSamplerFromInput(t,e,l),f=`${p.routineBody}\n      vec4 ${t}(int b, int row, int col) {\n        return ${t}(${(0,s.getSqueezedParams)(c,a)});\n      } `;return new i.GlslLibRoutine(f,p.dependencies)}const l=u[0],p=u[1],f=Math.ceil(r[2]/2),d=`vec4 ${t}(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        ${p}, ${l}, ${f*Math.ceil(r[1]/2)}, ${f}, b, row, col);\n      return ${c.texture2D}(${e}, uv);}`;return new i.GlslLibRoutine(d,["coordinates.packedUVfrom3D"])}getPackedSamplerND(t,e,n){const r=n.unpackedShape,a=r.length,s=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),c=[s[0],s[1]],l=c[1],p=c[0],f=Math.ceil(r[a-1]/2);let d=f*Math.ceil(r[a-2]/2),h="int b, int row, int col",g=`b * ${d} + (row / 2) * ${f} + (col / 2)`;for(let t=2;t<a-1;t++)h=`int b${t}, `+h,d*=r[a-t-1],g=`b${t} * ${d} + `+g;const b=`vec4 ${t}(${h}) {\n      int index = ${g};\n      int texR = index / ${p};\n      int texC = index - texR * ${p};\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${l});\n      return ${u.texture2D}(${e}, uv);\n    }`;return new i.GlslLibRoutine(b)}getUnpackedSamplerScalar(t,e,n){const[r,o]=[n.width,n.height];if(1===r&&1===o){const n=`\n          float ${t}() {\n            return sampleTexture(${e}, halfCR);\n          }\n        `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const a=`\n        float ${t}() {\n          int offset_${e} = coordsToOffset(TexCoords, ${r}, ${o});\n          vec2 uv = uvFromFlat(${r}, ${o}, offset_${e});\n          return sampleTexture(${e}, uv);\n        }\n      `;return new i.GlslLibRoutine(a,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler1D(t,e,n){const r=n.width,o=n.height;if(1===o&&1===r){const n=`\n        float ${t}(int index) {\n          return sampleTexture(${e}, halfCR);\n        }\n      `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}if(1===o){const n=`\n          float ${t}(int index) {\n            vec2 uv = vec2((float(index) + 0.5) / ${r}.0, 0.5);\n            return sampleTexture(${e}, uv);\n          }\n        `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}if(1===r){const n=`\n          float ${t}(int index) {\n            vec2 uv = vec2(0.5, (float(index) + 0.5) / ${o}.0);\n            return sampleTexture(${e}, uv);\n          }\n        `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const a=`\n        float ${t}(int index) {\n          vec2 uv = uvFromFlat(${r}, ${o}, index);\n          return sampleTexture(${e}, uv);\n        }\n      `;return new i.GlslLibRoutine(a,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler2D(t,e,n){const o=n.unpackedShape,u=[n.height,n.width];if(null!=u&&r.ArrayUtil.arraysEqual(o,u)){const n=`\n          float ${t}(int row, int col) {\n            vec2 uv = (vec2(row, col) + halfCR) / vec2(${u[1]}.0, ${u[0]}.0);\n            return sampleTexture(${e}, uv);\n          }\n        `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const{newShape:c,keptDims:l}=(0,a.squeezeShape)(o),p=c;if(p.length<o.length){const r=(0,s.squeezeInputShape)(o,p),a=JSON.parse(JSON.stringify(n));a.unpackedShape=r;const u=["col","row"],c=`\n          ${this.getUnpackedSamplerFromInput(t,e,a).routineBody}\n          float ${t}(int row, int col) {\n            return ${t}(${(0,s.getSqueezedParams)(u,l)});\n          }\n        `;return new i.GlslLibRoutine(c,["coordinates.sampleTexture"])}const f=u[1],d=u[0];if(1===d){const n=`\n          float ${t}(int row, int col) {\n            int offset_${e} = coordsToOffset(TexCoords, ${f}, ${d});\n            float index = dot(vec3(row, col, offset_${e}), vec3(${o[1]}, 1, 1));\n            vec2 uv = vec2(0.5, (index + 0.5) / ${f}.0);\n            return sampleTexture(${e}, uv);\n          }\n        `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture","coordinates.coordsToOffset"])}if(1===f){const n=`\n          float ${t}(int row, int col) {\n            int offset_${e} = coordsToOffset(TexCoords, ${f}, ${d});\n            float index = dot(vec3(row, col, offset_${e}), vec3(${o[1]}, 1, 1));\n            vec2 uv = vec2((index + 0.5) / ${d}.0, 0.5);\n            return sampleTexture(${e}, uv);\n          }\n        `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture","coordinates.coordsToOffset"])}const h=`\n        float ${t}(int row, int col) {\n          int index = col * ${o[1]} + row;\n          vec2 uv = uvFromFlat(${f}, ${d}, index);\n          return sampleTexture(${e}, uv);\n        }\n      `;return new i.GlslLibRoutine(h,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler3D(t,e,n){const r=n.unpackedShape,o=r[1]*r[2],u=r[2],{newShape:c,keptDims:l}=(0,a.squeezeShape)(r),p=c;if(p.length<r.length){const o=(0,s.squeezeInputShape)(r,p),a=["batch","col","row"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const c=this.getUnpackedSamplerFromInput(t,e,u),f=l.reverse(),d=`\n          ${c.routineBody}\n          float ${t}(int batch, int row, int col) {\n            return ${t}(${(0,s.getSqueezedParams)(a,f)});\n          }\n        `;return new i.GlslLibRoutine(d,c.dependencies)}const f=`\n          float ${t}(int depth, int row, int col) {\n            // Explicitly use integer operations as dot() only works on floats.\n            int index = depth * ${o} + col * ${u} + row;\n            vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n            return sampleTexture(${e}, uv);\n          }\n      `;return new i.GlslLibRoutine(f,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler4D(t,e,n){const r=n.unpackedShape,o=r[3],a=r[2]*o,s=`\n        float ${t}(int row, int col, int depth, int depth2) {\n          int index = row * ${r[1]*a} + col * ${a} +\n              depth2 * ${o} + depth;\n          vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n          return sampleTexture(${e}, uv);\n        }\n      `;return new i.GlslLibRoutine(s,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler5D(t,e,n){const r=n.unpackedShape,o=r[4],u=r[3]*o,c=r[2]*u,l=r[1]*c,{newShape:p,keptDims:f}=(0,a.squeezeShape)(r);if(p.length<r.length){const o=(0,s.squeezeInputShape)(r,p),a=["row","col","depth","depth2","depth3"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const c=`\n          ${this.getUnpackedSamplerFromInput(t,e,u).routineBody}\n          float ${t}(int row, int col, int depth, int depth2, int depth3) {\n            return ${t}(${(0,s.getSqueezedParams)(a,f)});\n          }\n        `;return new i.GlslLibRoutine(c,["coordinates.sampleTexture","coordinates.uvFromFlat"])}const d=`\n        float ${t}(int row, int col, int depth, int depth2, int depth3) {\n          int index = row * ${l} + col * ${c} + depth * ${u} +\n          depth3 * ${o} + depth2;\n          vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n          return sampleTexture(${e}, uv);\n        }\n      `;return new i.GlslLibRoutine(d,["coordinates.sampleTexture","coordinates.uvFromFlat"])}getUnpackedSampler6D(t,e,n){const r=n.unpackedShape,o=r[5],u=r[4]*o,c=r[3]*u,l=r[2]*c,p=r[1]*l,{newShape:f,keptDims:d}=(0,a.squeezeShape)(r);if(f.length<r.length){const o=(0,s.squeezeInputShape)(r,f),a=["row","col","depth","depth2","depth3","depth4"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const c=`\n            ${this.getUnpackedSamplerFromInput(t,e,u).routineBody}\n            float ${t}(int row, int col, int depth,\n              int depth2, int depth3, int depth4) {\n              return ${t}(${(0,s.getSqueezedParams)(a,d)});\n            }\n          `;return new i.GlslLibRoutine(c,["coordinates.sampleTexture","coordinates.uvFromFlat"])}const h=`\n          float ${t}(int row, int col, int depth,\n            int depth2, int depth3, int depth4) {\n            int index = row * ${p} + col * ${l} + depth * ${c} +\n            depth2 * ${u} + depth3 * ${o} + depth4;\n            vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n            return sampleTexture(${e}, uv);\n          }\n        `;return new i.GlslLibRoutine(h,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}toVec(){const t=this.context.outputTextureLayout,e=t.shape.length,n=t.strides,r=t.width,o=t.height,a=[];for(let t=0;t<e-1;++t)a.push(`\n        c[${t}] = offset / ${n[t]};`),a.push(`\n        offset -= c[${t}] * ${n[t]};`);a.push(`\n        c[${e-1}] = offset;`);const s=`\n      void toVec(vec2 texCoords, out int c[${e}]) {\n        int offset = coordsToOffset(texCoords, ${r}, ${o});\n        ${a.join("")}\n      }\n      void toVec(int offset, out int c[${e}]) {\n        ${a.join("")}\n      }\n    `;return{toVec:new i.GlslLibRoutine(s,["coordinates.coordsToOffset"])}}valueFrom(){const t={};return this.context.programInfo.inputNames.forEach(((e,n)=>{const r=this.context.inputTextureLayouts[n],o=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let a=`_${e}`;t[a]=new i.GlslLibRoutine(this.getValueFromSingle(e,o,r.width,r.height,!1),[`shapeUtils.indicesToOffset${a}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),a+="_T",t[a]=new i.GlslLibRoutine(this.getValueFromSingle(e,o,r.width,r.height,!0),[`shapeUtils.indicesToOffset${a}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])})),t}getValueFromSingle(t,e,n,r,i){let a=`_${t}`;return i&&(a+="_T"),`\n        float ${a}(int m[${e}]) {\n          int offset = indicesToOffset${a}(m);\n          vec2 coords = offsetToCoords(offset, ${n}, ${r});\n          float value = getColorAsFloat(${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${t}, coords));\n          return value;\n        }\n        `}getPackedValueFrom(t,e,n,r,i){let a=`_${t}_Pack`;return i&&(a+="_T"),`\n        vec4 ${a}(int m[${e}]) {\n          int offset = indicesToOffset_${t}(m);\n          vec2 coords = offsetToCoords(offset, ${n}, ${r});\n          return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${t}, coords);\n        }\n        `}}e.CoordsGlslLib=u},8520:(t,e)=>{"use strict";var n;Object.defineProperty(e,"__esModule",{value:!0}),e.TopologicalSortGlslRoutines=e.GlslLibRoutineNode=e.GlslLibRoutine=e.GlslLib=e.GlslContext=e.FunctionType=void 0,(n=e.FunctionType||(e.FunctionType={}))[n.ValueBased=0]="ValueBased",n[n.Positional=1]="Positional",e.GlslContext=class{constructor(t,e,n,r){this.glContext=t,this.programInfo=e,this.inputTextureLayouts=n,this.outputTextureLayout=r}},e.GlslLib=class{constructor(t){this.context=t}},e.GlslLibRoutine=class{constructor(t,e){this.routineBody=t,this.dependencies=e}},e.GlslLibRoutineNode=class{constructor(t,e,n){this.name=t,this.dependencies=n||[],e&&(this.routineBody=e)}addDependency(t){t&&this.dependencies.push(t)}},e.TopologicalSortGlslRoutines=class{static returnOrderedNodes(t){if(!t||0===t.length)return[];if(1===t.length)return t;const e=new Set,n=new Set,r=new Array;return this.createOrderedNodes(t,e,n,r),r}static createOrderedNodes(t,e,n,r){for(let i=0;i<t.length;++i)this.dfsTraverse(t[i],e,n,r)}static dfsTraverse(t,e,n,r){if(!t||n.has(t.name))return;if(e.has(t.name))throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader.");e.add(t.name);const i=t.dependencies;if(i&&i.length>0)for(let t=0;t<i.length;++t)this.dfsTraverse(i[t],e,n,r);r.push(t),n.add(t.name),e.delete(t.name)}}},7341:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.EncodingGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new r.GlslLibRoutine("highp vec4 encode(highp float f) {\n        return vec4(f, 0.0, 0.0, 0.0);\n      }\n        ")}}decodeFloat32(){return{decode:new r.GlslLibRoutine("highp float decode(highp vec4 rgba) {\n        return rgba.r;\n      }\n        ")}}encodeUint8(){const t=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new r.GlslLibRoutine(`\n      highp vec4 encode(highp float f) {\n        highp float F = abs(f);\n        highp float Sign = step(0.0,-f);\n        highp float Exponent = floor(log2(F));\n        highp float Mantissa = (exp2(- Exponent) * F);\n        Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));\n        highp vec4 rgba;\n        rgba[0] = 128.0 * Sign  + floor(Exponent*exp2(-1.0));\n        rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);\n        rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));\n        rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));\n        ${t}\n        rgba = rgba / 255.0; // values need to be normalized to [0,1]\n        return rgba;\n    }\n        `)}}decodeUint8(){const t=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new r.GlslLibRoutine(`\n        highp float decode(highp vec4 rgba) {\n          rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]\n          ${t}\n          highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;\n          highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;\n          highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);\n          highp float Result =  Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));\n          return Result;\n      }\n        `)}}static isLittleEndian(){const t=new ArrayBuffer(4),e=new Uint32Array(t),n=new Uint8Array(t);if(e[0]=3735928559,239===n[0])return!0;if(222===n[0])return!1;throw new Error("unknown endianness")}}e.EncodingGlslLib=i},9894:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FragColorGlslLib=void 0;const r=n(8520),i=n(5060);class o extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const t=(0,i.getGlsl)(this.context.glContext.version);return{setFragColor:new r.GlslLibRoutine(`\n        void setFragColor(float value) {\n            ${t.output} = encode(value);\n        }\n        `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new r.GlslLibRoutine("\n        float getColorAsFloat(vec4 color) {\n            return decode(color);\n        }\n        ",["encoding.decode"])}}}e.FragColorGlslLib=o},2848:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.replaceInlines=void 0;const n=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;e.replaceInlines=function(t){const e={};let r;for(;null!==(r=n.exec(t));){const t=r[3].split(",").map((t=>{const e=t.trim().split(" ");return e&&2===e.length?{type:e[0],name:e[1]}:null})).filter((t=>null!==t));e[r[2]]={params:t,body:r[4]}}for(const n in e){const i="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",n),o=new RegExp(i,"gm");for(;null!==(r=o.exec(t));){const i=r[1],o=r[2],a=r[3].split(","),s=i?`${i} ${o};`:"";let u=e[n].body,c="";e[n].params.forEach(((t,e)=>{t&&(c+=`${t.type} ${t.name} = ${a[e]};\n`)})),u=`${c}\n ${u}`,u=u.replace("return",`${o} = `);const l=`\n      ${s}\n      {\n        ${u}\n      }\n      `;t=t.replace(r[0],l)}}return t.replace(n,"")}},8879:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.GlslPreprocessor=void 0;const r=n(8520),i=n(2848),o=n(5483),a=n(5060);e.GlslPreprocessor=class{constructor(t,e,n,i){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new r.GlslContext(t,e,n,i),Object.keys(o.glslRegistry).forEach((t=>{const e=new o.glslRegistry[t](this.context);this.libs[t]=e}));const a=this.glslLibRoutineDependencyGraph;for(const t in this.libs){const e=this.libs[t].getFunctions();for(const n in e){const i=t+"."+n;let o;a[i]?(o=a[i],o.routineBody=e[n].routineBody):(o=new r.GlslLibRoutineNode(i,e[n].routineBody),a[i]=o);const s=e[n].dependencies;if(s)for(let t=0;t<s.length;++t)if(a[s[t]])o.addDependency(a[s[t]]);else{const e=new r.GlslLibRoutineNode(s[t]);a[s[t]]=e,o.addDependency(e)}}}}preprocess(){const t=this.context.programInfo;let e=t.shaderSource;return this.context.programInfo.hasMain||(e=`${e}\n      ${(0,a.getDefaultFragShaderMain)(this.context.glContext.version,this.context.outputTextureLayout.shape.length)}`),e=(0,i.replaceInlines)(e),`${(0,a.getFragShaderPreamble)(this.context.glContext.version)}\n    ${this.getUniforms(t.inputNames,t.variables)}\n    ${this.getImports(e)}\n    ${e}`}getImports(t){const e=this.selectGlslLibRoutinesToBeIncluded(t);if(0===e.length)return"";let n="";for(let t=0;t<e.length;++t){if(!e[t].routineBody)throw new Error(`Missing body for the Glsl Library routine: ${e[t].name}`);n+=e[t].routineBody+"\n"}return n}selectGlslLibRoutinesToBeIncluded(t){const e=[];return Object.keys(this.glslLibRoutineDependencyGraph).forEach((n=>{const r=n.split(".")[1];-1!==t.indexOf(r)&&e.push(this.glslLibRoutineDependencyGraph[n])})),r.TopologicalSortGlslRoutines.returnOrderedNodes(e)}getUniforms(t,e){const n=[];if(t)for(const e of t)n.push(`uniform sampler2D ${e};`);if(e)for(const t of e)n.push(`uniform ${t.type} ${t.name}${t.arrayLength?`[${t.arrayLength}]`:""};`);return n.join("\n")}}},5483:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.glslRegistry=void 0;const r=n(5107),i=n(7341),o=n(9894),a=n(2655),s=n(3891);e.glslRegistry={encoding:i.EncodingGlslLib,fragcolor:o.FragColorGlslLib,vec:s.VecGlslLib,shapeUtils:a.ShapeUtilsGlslLib,coordinates:r.CoordsGlslLib}},2655:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ShapeUtilsGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.bcastIndex()),this.bcastMatmulIndex()),this.offsetToIndices()),this.indicesToOffset()),this.incrementIndices())}getCustomTypes(){return{}}bcastIndex(){const t=this.context.outputTextureLayout.shape.length,e={};return this.context.programInfo.inputNames.forEach(((n,i)=>{const o=this.context.inputTextureLayouts[i].unpackedShape;if(o.length<=t){const i=o.length,a=t-i,s=`bcastIndices_${n}`;let u="";for(let t=0;t<i;++t)u+=`\n          realIndices[${t}] = int( mod(float(bcastedIndices[${a+t}]), ${o[t]}.0) );\n          `;const c=`\n        void ${s} (int bcastedIndices[${t}], out int realIndices[${i}]) {\n          ${u}\n        }\n        `;e[s]=new r.GlslLibRoutine(c)}})),e}bcastMatmulIndex(){const t=this.context.outputTextureLayout.shape.length,e={};return this.context.programInfo.inputNames.forEach(((n,i)=>{const o=this.context.inputTextureLayouts[i].shape;if(!(o.length<2||o.length>t)){const i=o.length,a=t-i,s=`bcastMatmulIndices_${n}`;let u="";for(let t=0;t<i-2;++t)u+=`\n          realIndices[${t}] = int( mod(float(bcastedIndices[${a+t}]), ${o[t]}.0) );\n          `;const c=`\n        void ${s}(int bcastedIndices[${t}], out int realIndices[${i}]) {\n          ${u}\n          realIndices[${i-1}] = bcastedIndices[${t-1}];\n          realIndices[${i-2}] = bcastedIndices[${t-2}];\n        }\n        `;e[s]=new r.GlslLibRoutine(c)}})),e}indicesToOffset(){const t={};return this.context.programInfo.inputNames.forEach(((e,n)=>{const o=this.context.inputTextureLayouts[n].shape,a=this.context.inputTextureLayouts[n].strides,s=o.length;let u=`indicesToOffset_${e}`;t[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,s,a)),u=`indicesToOffset_${e}_T`,t[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,s,a.slice().reverse()))})),t}static indexToOffsetSingle(t,e,n){let r="";for(let t=e-1;t>=0;--t)r+=`\n        offset += indices[${t}] * ${n[t]};\n        `;return`\n      int ${t}(int indices[${e}]) {\n        int offset = 0;\n        ${r}\n        return offset;\n      }\n      `}offsetToIndices(){const t={};return this.context.programInfo.inputNames.forEach(((e,n)=>{const o=this.context.inputTextureLayouts[n].shape,a=this.context.inputTextureLayouts[n].strides,s=o.length;let u=`offsetToIndices_${e}`;t[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,s,a)),u=`offsetToIndices_${e}_T`,t[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,s,a.slice().reverse()))})),t}static offsetToIndicesSingle(t,e,n){const r=[];for(let t=0;t<e-1;++t)r.push(`\n      indices[${t}] = offset / ${n[t]};`),r.push(`\n        offset -= indices[${t}] * ${n[t]};`);return r.push(`\n      indices[${e-1}] = offset;`),`\n      void ${t}(int offset, out int indices[${e}]) {\n        ${r.join("")}\n      }\n      `}incrementIndices(){const t={};return this.context.programInfo.inputNames.forEach(((e,n)=>{const i=this.context.inputTextureLayouts[n].shape,o=i.length,a=`incrementIndices_${e}`;let s="";for(let t=0;t<o;++t)s+=`\n        shape[${t}] = ${i[t]};`;const u=`\n        void ${a}(int axis, out int indices[${o}]) {\n          int shape[${o}];\n          ${s};\n          for(int i = ${o} -1 ; i >= 0; --i) {\n            if(i > axis) continue;\n            indices[i] += 1;\n            if(indices[i] < shape[i]) {\n              break;\n            }\n            indices[i] = 0;\n          }\n        }\n        `;t[a]=new r.GlslLibRoutine(u)})),t}}e.ShapeUtilsGlslLib=i},5060:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getDefaultFragShaderMain=e.getFragShaderPreamble=e.getVertexShaderSource=e.getGlsl=void 0;const n={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},r={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function i(t){return 1===t?n:r}e.getGlsl=i,e.getVertexShaderSource=function(t){const e=i(t);return`${e.version}\n      precision highp float;\n      ${e.attribute} vec3 position;\n      ${e.attribute} vec2 textureCoord;\n\n      ${e.varyingVertex} vec2 TexCoords;\n\n      void main()\n      {\n          gl_Position = vec4(position, 1.0);\n          TexCoords = textureCoord;\n      }`},e.getFragShaderPreamble=function(t){const e=i(t);return`${e.version}\n    precision highp float;\n    precision highp int;\n    precision highp sampler2D;\n    ${e.varyingFrag} vec2 TexCoords;\n    ${e.outputDeclaration}\n    const vec2 halfCR = vec2(0.5, 0.5);\n\n    // Custom vector types to handle higher dimenalities.\n    struct ivec5\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n    };\n\n    struct ivec6\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n      int v;\n    };\n\n    int imod(int x, int y) {\n      return x - y * (x / y);\n    }\n\n    `},e.getDefaultFragShaderMain=function(t,e){return`\n  void main() {\n    int indices[${e}];\n    toVec(TexCoords, indices);\n    vec4 result = vec4(process(indices));\n    ${i(t).output} = result;\n  }\n  `}},3891:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.VecGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const t=this.context.outputTextureLayout.shape.length,e={add:"+=",sub:"-=",mul:"*=",div:"/="},n={};for(const i in e){const o=`${i}Vec`;let a="";for(let n=0;n<t;++n)a+=`\n          dest[${n}] ${e[i]} src[${n}];\n          `;const s=`\n        void ${o}(int src[${t}], out int dest[${t}]) {\n          ${a}\n        }\n        `;n[o]=new r.GlslLibRoutine(s)}return n}copyVec(){const t=this.context.outputTextureLayout.shape.length;let e="";for(let n=0;n<t;++n)e+=`\n        dest[${n}] = src[${n}];\n        `;const n=`\n      void copyVec(int src[${t}], out int dest[${t}]) {\n        ${e}\n      }\n      `;return{copyVec:new r.GlslLibRoutine(n)}}setVecItem(){const t=this.context.outputTextureLayout.shape.length;let e=`\n        if(index < 0)\n            index =${t} + index;\n        if (index == 0)\n            m[0] = value;\n        `;for(let n=1;n<t-1;++n)e+=`\n        else if (index == ${n})\n            m[${n}] = value;\n            `;e+=`\n        else\n            m[${t-1}] = value;\n        `;const n=`\n      void setVecItem(out int m[${t}], int index, int value) {\n        ${e}\n      }\n        `;return{setVecItem:new r.GlslLibRoutine(n)}}getVecItem(){const t=this.context.outputTextureLayout.shape.length;let e=`\n        if(index < 0)\n            index = ${t} + index;\n        if (index == 0)\n            return m[0];\n      `;for(let n=1;n<t-1;++n)e+=`\n        else if (index == ${n})\n            return m[${n}];\n      `;e+=`\n        else\n            return m[${t-1}];\n        `;const n=`\n      int getVecItem(int m[${t}], int index) {\n        ${e}\n      }\n    `;return{getVecItem:new r.GlslLibRoutine(n)}}}e.VecGlslLib=i},8316:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLInferenceHandler=void 0;const r=n(6231),i=n(9162),o=n(2517),a=n(2403),s=n(7019),u=n(8710),c=n(5611),l=n(4057),p=n(2039);e.WebGLInferenceHandler=class{constructor(t){this.session=t,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(t,e){return(0,l.calculateTextureWidthAndHeight)(this.session.layoutStrategy,t,e)}executeProgram(t,e){if(e.length<t.inputNames.length)throw new Error(`Input size mustn't be less than ${t.inputNames.length}.`);if(t.inputNames.length!==t.inputTypes.length)throw new Error("input names size does not match input types");const n=[];for(let r=0;r<t.inputNames.length;++r)n[r]=this.getOrCreateTextureData(e[r],t.inputTypes[r]);const r=((t,e)=>{const n=e.map((t=>`${t.unpackedShape.join(",")};${t.width}x${t.height}`)).join("_");let r=t.name;return t.cacheHint&&(r+="["+t.cacheHint+"]"),r+=":"+n,r})(t,n);let i=this.session.programManager.getArtifact(r);const o=i?i.programInfo:"function"==typeof t.get?t.get():t,a=(0,l.createTextureLayoutFromTextureType)(this.session.layoutStrategy,o.output.dims,o.output.textureType),s=this.createTextureData(a,o.output.type);return i||(i=this.session.programManager.build(o,n,s),this.session.programManager.setArtifact(r,i)),this.runProgram(i,n,s),s}run(t,e){return this.executeProgram(t,e).tensor}runProgram(t,e,n){for(let n=0;n<e.length;++n)if(!!e[n].isPacked!=(t.programInfo.inputTypes[n]===p.TextureType.packed))throw new Error(`input[${n}] property packed inconsistent`);if(!!n.isPacked!=(t.programInfo.output.textureType===p.TextureType.packed))throw new Error("output property packed inconsistent");this.session.programManager.run(t,e,n)}getOrCreateTextureData(t,e){let n=this.getTextureData(t.dataId,e===p.TextureType.packed);if(!n&&(n=this.getTextureData(t.dataId,e!==p.TextureType.packed),n))return e===p.TextureType.packed?this.pack(n):this.unpack(n);if(!n){const r=(0,l.createTextureLayoutFromTextureType)(this.session.layoutStrategy,t.dims,e);if(e===p.TextureType.packedLastDimension){const n=1,r=4,i=t.dims;if(4===i.length){const o=[i[0],Math.ceil(i[1]*i[2]*i[3]/r)],a=(0,l.createTextureLayoutFromTextureType)(this.session.layoutStrategy,o,e);let s=t.numberData;if(i[1]*i[2]*i[3]%r!=0){const e=i[0],o=i[1]*i[2]*i[3],a=Math.ceil(o*n/r)*r;s=new Float32Array(e*a);for(let r=0;r<e;++r){const e=r*o,i=r*a+r%n*o;s.set(t.numberData.subarray(e,e+o),i)}}return this.createTextureData(a,t.type,s,t,1)}}if(e===p.TextureType.packed){const e=(0,l.createTextureLayoutFromShape)(this.session.layoutStrategy,t.dims,1,[],{reverseWH:!0}),r=this.createTextureData(e,t.type,t.numberData,t,1);n=this.pack(r)}else n=this.createTextureData(r,t.type,t.numberData,t,1)}return n}createTextureDataFromLayoutBindTensor(t,e,n,r){return this.createTextureData(t,e,n,r,1)}createTextureData(t,e,n,i,o){r.Logger.verbose("InferenceHandler",`Creating TextureData: layout:[${JSON.stringify(t)}]`);const a=this.session.textureManager.createTextureFromLayout(e,t,n,o);return this.createTextureDataFromTexture(t,e,a,i)}reshapeUnpacked(t,e){const n=this.getOrCreateTextureData(t,p.TextureType.unpacked),r={channels:n.channels,height:n.height,width:n.width,shape:0!==e.length?e:[1],strides:o.ShapeUtil.computeStrides(e),unpackedShape:e};return this.createTextureDataFromTexture(r,t.type,n.texture).tensor}reshapePacked(t,e){const n=this.getOrCreateTextureData(t,p.TextureType.packed);if((0,s.isReshapeCheap)(t.dims,e)){const r={channels:n.channels,height:n.height,width:n.width,shape:0!==e.length?e:[1],strides:o.ShapeUtil.computeStrides(e),unpackedShape:e,isPacked:!0};return this.createTextureDataFromTexture(r,t.type,n.texture).tensor}const r=(0,s.processDims3D)(t.dims),i=(0,s.processDims3D)(e),a=this.reshapePacked(t,r),u=this.run((0,s.createPackedReshape3DProgramInfoLoader)(this,a,i),[a]);return this.reshapePacked(u,e)}cast(t,e){const n=this.getOrCreateTextureData(t,p.TextureType.unpacked);return this.createTextureDataFromTexture(n,e,n.texture).tensor}createTextureDataFromTexture(t,e,n,r,o){const a=Object.assign(Object.assign({},t),{tensor:r||new i.Tensor(t.unpackedShape,e,(t=>this.readTexture(a)),(async t=>this.readTextureAsync(a)),void 0,o),texture:n});return this.setTextureData(a.tensor.dataId,a,t.isPacked),a}getTextureData(t,e=!1){return this.session.isInitializer(t)?this.session.getTextureData(t,e):e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,n=!1){this.session.isInitializer(t)?this.session.setTextureData(t,e,n):(n?this.packedTextureDataCache:this.unpackedTextureDataCache).set(t,e)}isTextureLayoutCached(t,e=!1){return!!this.getTextureData(t.dataId,e)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((t=>this.session.textureManager.releaseTexture(t))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((t=>this.session.textureManager.releaseTexture(t))),this.unpackedTextureDataCache=new Map}readTexture(t){return t.isPacked?this.readTexture(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,t))}async readTextureAsync(t){return t.isPacked?this.readTextureAsync(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,t))}pack(t){return this.executeProgram((0,a.createPackProgramInfoLoader)(this,t.tensor),[t.tensor])}unpack(t){return this.executeProgram((0,c.createUnpackProgramInfoLoader)(this,t.tensor),[t.tensor])}}},1640:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.WEBGL_OP_RESOLVE_RULES=void 0;const a=n(2898),s=o(n(7839)),u=n(4196),c=n(2069),l=n(8138),p=n(9663),f=n(5193),d=n(7992),h=n(1253),g=n(4776),b=n(6572),m=n(3346),y=n(5623),_=n(2870),v=n(2143),w=n(4939),x=n(718),T=n(2268),S=n(8117),O=n(2278),A=n(5524),E=n(5975),I=n(3933),P=n(6558),D=n(5723),$=n(3738),k=o(n(4909)),C=n(8428),F=n(9793);e.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",k.abs],["Acos","","7+",k.acos],["Add","","7+",s.add],["And","","7+",s.and],["Asin","","7+",k.asin],["Atan","","7+",k.atan],["AveragePool","","7+",v.averagePool,v.parseAveragePoolAttributes],["BatchNormalization","","7+",a.batchNormalization,a.parseBatchNormalizationAttributes],["Cast","","6+",u.cast,u.parseCastAttributes],["Ceil","","6+",k.ceil],["Clip","","6-10",k.clip,k.parseClipAttributes],["Clip","","11+",k.clipV11],["Concat","","4+",c.concat,c.parseConcatAttributes],["Conv","","1+",l.conv,l.parseConvAttributes],["ConvTranspose","","1+",p.convTranspose,p.parseConvTransposeAttributes],["Cos","","7+",k.cos],["Div","","7+",s.div],["Dropout","","7+",k.identity],["DepthToSpace","","1+",f.depthToSpace,f.parseDepthToSpaceAttributes],["Equal","","7+",s.equal],["Elu","","6+",k.elu,k.parseEluAttributes],["Exp","","6+",k.exp],["Flatten","","1+",d.flatten,d.parseFlattenAttributes],["Floor","","6+",k.floor],["FusedConv","com.microsoft","1+",l.conv,l.parseConvAttributes],["Gather","","1+",h.gather,h.parseGatherAttributes],["Gemm","","7-10",g.gemm,g.parseGemmAttributesV7],["Gemm","","11+",g.gemm,g.parseGemmAttributesV11],["GlobalAveragePool","","1+",v.globalAveragePool,v.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",v.globalMaxPool],["Greater","","7+",s.greater],["Identity","","1+",k.identity],["ImageScaler","","1+",b.imageScaler,b.parseImageScalerAttributes],["InstanceNormalization","","6+",m.instanceNormalization,m.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",k.leakyRelu,k.parseLeakyReluAttributes],["Less","","7+",s.less],["Log","","6+",k.log],["MatMul","","1+",y.matMul,y.parseMatMulAttributes],["MaxPool","","1+",v.maxPool,v.parseMaxPoolAttributes],["Mul","","7+",s.mul],["Neg","","6+",k.neg],["Not","","1+",k.not],["Or","","7+",s.or],["Pad","","2-10",_.padV2,_.parsePadAttributesV2],["Pad","","11+",_.padV11,_.parsePadAttributesV11],["Pow","","7+",s.pow],["PRelu","","7+",s.pRelu],["ReduceLogSum","","1+",w.reduceLogSum,w.parseReduceAttributes],["ReduceMax","","1+",w.reduceMax,w.parseReduceAttributes],["ReduceMean","","1+",w.reduceMean,w.parseReduceAttributes],["ReduceMin","","1+",w.reduceMin,w.parseReduceAttributes],["ReduceProd","","1+",w.reduceProd,w.parseReduceAttributes],["ReduceSum","","1-12",w.reduceSum,w.parseReduceAttributes],["ReduceSumSquare","","1+",w.reduceLogSumSquare,w.parseReduceAttributes],["Relu","","6+",k.relu],["Reshape","","5+",x.reshape],["Resize","","10",T.resize,T.parseResizeAttributesV10],["Resize","","11+",T.resize,T.parseResizeAttributesV11],["Shape","","1+",S.shape],["Sigmoid","","6+",k.sigmoid],["Sin","","7+",k.sin],["Slice","","10+",O.sliceV10],["Slice","","1-9",O.slice,O.parseSliceAttributes],["Softmax","","1-12",A.softmax,A.parseSoftmaxAttributes],["Softmax","","13+",A.softmaxV13,A.parseSoftmaxAttributesV13],["Split","","2-12",E.split,E.parseSplitAttributes],["Sqrt","","6+",k.sqrt],["Squeeze","","1-12",I.squeeze,I.parseSqueezeAttributes],["Squeeze","","13+",I.squeezeV13],["Sub","","7+",s.sub],["Sum","","6+",P.sum],["Tan","","7+",k.tan],["Tanh","","6+",k.tanh],["Tile","","6+",D.tile],["Transpose","","1+",$.transpose,$.parseTransposeAttributes],["Upsample","","7-8",F.upsample,F.parseUpsampleAttributesV7],["Upsample","","9",F.upsample,F.parseUpsampleAttributesV9],["Unsqueeze","","1-12",C.unsqueeze,C.parseUnsqueezeAttributes],["Unsqueeze","","13+",C.unsqueezeV13],["Xor","","7+",s.xor]]},2898:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseBatchNormalizationAttributes=e.batchNormalization=void 0;const r=n(246),i=n(5060),o=n(2039),a={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]};e.batchNormalization=(t,e,n)=>(u(e),[t.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>s(t,e,n)}),e)]),e.parseBatchNormalizationAttributes=t=>{const e=t.attributes.getFloat("epsilon",1e-5),n=t.attributes.getFloat("momentum",.9),i=t.attributes.getInt("spatial",1);return(0,r.createAttributeWithCacheKey)({epsilon:e,momentum:n,spatial:i})};const s=(t,e,n)=>{const r=(0,i.getGlsl)(t.session.backend.glContext.version),s=e[0].dims.length,[u,c]=t.calculateTextureWidthAndHeight(e[1].dims,o.TextureType.unpacked),l=`\n  float process(int[${s}] indices) {\n    vec2 position = offsetToCoords(indices[1], ${u}, ${c});\n    float scale = getColorAsFloat(${r.texture2D}(Scale, position));\n    float mean = getColorAsFloat(${r.texture2D}(Mean, position));\n    float variance = getColorAsFloat(${r.texture2D}(Variance, position));\n    float b = getColorAsFloat(${r.texture2D}(B, position));\n\n    return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n.epsilon})) ) + b;\n  }`;return Object.assign(Object.assign({},a),{output:{dims:e[0].dims,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:l})},u=t=>{if(!t||5!==t.length)throw new Error("BatchNormalization requires 5 inputs.");const e=t[0],n=t[1],r=t[2],i=t[3],o=t[4];if(e.dims.length<3||1!==n.dims.length||1!==r.dims.length||1!==i.dims.length||1!==o.dims.length)throw new Error("invalid input shape.");if(n.dims[0]!==e.dims[1]||r.dims[0]!==e.dims[1]||i.dims[0]!==e.dims[1]||o.dims[0]!==e.dims[1])throw new Error("invalid input shape.");if("float32"!==e.type&&"float64"!==e.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type||"float32"!==i.type&&"float64"!==i.type||"float32"!==o.type&&"float64"!==o.type)throw new Error("invalid input tensor types.")}},7839:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.xor=e.sub=e.pRelu=e.pow=e.or=e.mul=e.less=e.greater=e.equal=e.div=e.and=e.add=e.glslPRelu=e.glslPow=e.glslXor=e.glslOr=e.glslAnd=e.glslLess=e.glslGreater=e.glslEqual=e.glslSub=e.glslMul=e.glslDiv=e.glslAdd=void 0;const r=n(2517),i=n(8520),o=n(5060),a=n(2039);function s(){const t="add_";return{body:`\n  float ${t}(float a, float b) {\n    return a + b;\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    return v1 + v2;\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}function u(){const t="div_";return{body:`\n  float ${t}(float a, float b) {\n    return a / b;\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    return v1 / v2;\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}function c(){const t="mul_";return{body:`\n  float ${t}(float a, float b) {\n    return a * b;\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    return v1 * v2;\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}function l(){const t="sub_";return{body:`\n  float ${t}(float a, float b) {\n    return a - b;\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    return v1 - v2;\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}function p(){const t="equal_";return{body:`\n  float ${t}(float a, float b) {\n    return float(a == b);\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    return vec4(equal(v1, v2));\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}function f(){const t="greater_";return{body:`\n  float ${t}(float a, float b) {\n    return float(a > b);\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    return vec4( v1.r > v2.r ,\n      v1.g > v2.g,\n      v1.b > v2.b,\n      v1.a > v2.a );\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}function d(){const t="less_";return{body:`\n  float ${t}(float a, float b) {\n    return float(a < b);\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    return vec4( v1.r < v2.r ,\n                v1.g < v2.g,\n                v1.b < v2.b,\n                v1.a < v2.a );\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}function h(){const t="and_";return{body:`\n  float ${t}(float a, float b) {\n    return float( bool(a) && bool(b) );\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    bvec4 b1 = bvec4(v1);\n    bvec4 b2 = bvec4(v2);\n    return vec4( b1.r && b2.r ,\n                b1.g && b2.g,\n                b1.b && b2.b,\n                b1.a && b2.a );\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}function g(){const t="or_";return{body:`\n  float ${t}(float a, float b) {\n    return float( bool(a) || bool(b) );\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    bvec4 b1 = bvec4(v1);\n    bvec4 b2 = bvec4(v2);\n    return vec4( b1.r || b2.r ,\n                b1.g || b2.g,\n                b1.b || b2.b,\n                b1.a || b2.a );\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}function b(){const t="xor_";return{body:`\n  float ${t}(float a, float b) {\n    return float( bool(a) ^^ bool(b) );\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    bvec4 b1 = bvec4(v1);\n    bvec4 b2 = bvec4(v2);\n    return vec4( b1.r ^^ b2.r ,\n                b1.g ^^ b2.g,\n                b1.b ^^ b2.b,\n                b1.a ^^ b2.a );\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}function m(){return function(t){const e=`${t}_`;return{body:`\n  float ${e}(float a, float b) {\n    return ${t}(a, b);\n  }\n  vec4 ${e}(vec4 v1, vec4 v2) {\n    return ${t}(v1, v2);\n  }\n  `,name:e,type:i.FunctionType.ValueBased}}("pow")}function y(){const t="prelu_";return{body:`\n  float ${t}(float a, float b) {\n    return a < 0.0 ? a * b: a;\n  }\n  vec4 ${t}(vec4 v1, vec4 v2) {\n    return vec4(\n      v1.r < 0.0 ? v1.r * v2.r: v1.r,\n      v1.g < 0.0 ? v1.g * v2.g: v1.g,\n      v1.b < 0.0 ? v1.b * v2.b: v1.b,\n      v1.a < 0.0 ? v1.a * v2.a: v1.a\n      );\n  }\n  `,name:t,type:i.FunctionType.ValueBased}}e.glslAdd=s,e.glslDiv=u,e.glslMul=c,e.glslSub=l,e.glslEqual=p,e.glslGreater=f,e.glslLess=d,e.glslAnd=h,e.glslOr=g,e.glslXor=b,e.glslPow=m,e.glslPRelu=y;const _=(t,e,n,r=e[0].type,i)=>{const o=t.session.pack?a.TextureType.packed:a.TextureType.unpacked;return{name:n.name,inputNames:["A","B"],inputTypes:[o,o],cacheHint:i,get:()=>v(t,e,n,r)}},v=(t,e,n,i=e[0].type)=>{const s=t.session.pack?a.TextureType.packed:a.TextureType.unpacked,u=!r.ShapeUtil.areEqual(e[0].dims,e[1].dims);let c=e[0].dims;const l=t.session.pack;if(u){const a=r.BroadcastUtil.calcShape(e[0].dims,e[1].dims,!1);if(!a)throw new Error("Can't perform binary op on the given tensors");c=a;const u=c.length,p=0!==e[0].dims.length?e[0].dims.length:1,f=0!==e[1].dims.length?e[1].dims.length:1,d=0!==e[0].dims.length?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",h=0!==e[1].dims.length?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",g=(0,o.getGlsl)(t.session.backend.glContext.version),b=l?`\n      ${n.body}\n      void main() {\n        vec4 a = getAAtOutCoords();\n        vec4 b = getBAtOutCoords();\n        vec4 result = ${n.name}(a, b);\n        ${g.output} = result;\n      }`:`\n      ${n.body}\n      float process(int indices[${u}]) {\n        int aindices[${p}];\n        int bindices[${f}];\n        ${d}\n        ${h}\n        return ${n.name}(_A(aindices), _B(bindices));\n      }`;return{name:n.name,inputNames:["A","B"],inputTypes:[s,s],output:{dims:c,type:i,textureType:s},shaderSource:b,hasMain:l}}const p=(0,o.getGlsl)(t.session.backend.glContext.version),f=`\n    ${n.body}\n    void main() {\n      vec4 v1 = ${p.texture2D}(A, TexCoords);\n      vec4 v2 = ${p.texture2D}(B, TexCoords);\n      vec4 result = ${n.name}(v1, v2);\n      ${p.output} = result;\n    }\n    `;return{name:n.name,inputNames:["A","B"],inputTypes:[s,s],output:{dims:e[0].dims,type:i,textureType:s},shaderSource:f,hasMain:!0}};e.add=(t,e)=>[t.run(_(t,e,s()),e)],e.and=(t,e)=>[t.run(_(t,e,h(),"bool"),e)],e.div=(t,e)=>[t.run(_(t,e,u()),e)],e.equal=(t,e)=>[t.run(_(t,e,p(),"bool"),e)],e.greater=(t,e)=>[t.run(_(t,e,f(),"bool"),e)],e.less=(t,e)=>[t.run(_(t,e,d(),"bool"),e)],e.mul=(t,e)=>[t.run(_(t,e,c()),e)],e.or=(t,e)=>[t.run(_(t,e,g(),"bool"),e)],e.pow=(t,e)=>[t.run(_(t,e,m()),e)],e.pRelu=(t,e)=>[t.run(_(t,e,y()),e)],e.sub=(t,e)=>[t.run(_(t,e,l()),e)],e.xor=(t,e)=>[t.run(_(t,e,b(),"bool"),e)]},4196:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseCastAttributes=e.cast=void 0;const r=n(2517);e.cast=(t,e,n)=>(i(e),[t.cast(e[0],n)]),e.parseCastAttributes=t=>r.ProtoUtil.tensorDataTypeFromProto(t.attributes.getInt("to"));const i=t=>{if(!t||1!==t.length)throw new Error("Cast requires 1 input.");if("string"===t[0].type)throw new Error("Invalid input type.")}},1163:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedConcatProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(9390),a=n(2827);e.createPackedConcatProgramInfoLoader=(t,e,n)=>{const u=(c=e.length,l=n.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:c},((t,e)=>`X${e}`)),inputTypes:Array(c).fill(i.TextureType.packed),cacheHint:l});var c,l;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,u)=>{const c=n[0].dims.slice();if(u>=c.length||u<-1*c.length)throw new Error("axis specified for concat doesn't match input dimensionality");u<0&&(u=c.length+u);const l=c.slice(0);for(let t=1;t<n.length;t++){const e=n[t].dims.slice();for(let t=0;t<c.length;t++)if(t===u)l[u]+=e[t];else if(c[t]!==e[t])throw new Error("non concat dimensions must match")}const p=l.length,f=(0,a.getChannels)("coords",p),d=(0,o.getCoordsDataType)(p),h=(0,a.unpackFromChannel)(),g=n.map((t=>t.dims)),b=(0,o.getGlChannels)(p),m=new Array(g.length-1);m[0]=g[0][u];for(let t=1;t<m.length;t++)m[t]=m[t-1]+g[t][u];const y=b[u],_=b.slice(-2),v=b.join();let w=`if (${y} < ${m[0]}) {\n        return getChannel(\n            getX0(${v}), vec2(${_.join()}));\n        }`;for(let t=1;t<m.length;t++){const e=m[t-1];w+=`\n            if (${y} < ${m[t]}  && ${y} >= ${m[t-1]}) {\n              return getChannel(\n                getX${t}(${s(b,y,e)}),\n                vec2(${s(_,y,e)}));\n            }`}const x=m.length,T=m[m.length-1];w+=`\n            return getChannel(\n              getX${x}(${s(b,y,T)}),\n              vec2(${s(_,y,T)}));`;const S=(0,r.getGlsl)(t.session.backend.glContext.version),O=`\n          ${h}\n          float getValue(${b.map((t=>"int "+t))}) {\n            ${w}\n          }\n\n          void main() {\n            ${d} coords = getOutputCoords();\n            int lastDim = coords.${b[p-1]};\n            coords.${b[p-1]} = coords.${b[p-2]};\n            coords.${b[p-2]} = lastDim;\n\n            vec4 result = vec4(getValue(${f}), 0., 0., 0.);\n\n            ${f[p-1]} = ${f[p-1]} + 1;\n            if (${f[p-1]} < ${l[p-1]}) {\n              result.g = getValue(${f});\n            }\n\n            ${f[p-2]} = ${f[p-2]} + 1;\n            if (${f[p-2]} < ${l[p-2]}) {\n              result.a = getValue(${f});\n            }\n\n            ${f[p-1]} = ${f[p-1]} - 1;\n            if (${f[p-2]} < ${l[p-2]} &&\n                ${f[p-1]} < ${l[p-1]}) {\n              result.b = getValue(${f});\n            }\n            ${S.output} = result;\n          }\n        `;return Object.assign(Object.assign({},e),{output:{dims:l,type:n[0].type,textureType:i.TextureType.packed},shaderSource:O,hasMain:!0})})(t,u,e,n.axis)})};const s=(t,e,n)=>{const r=t.indexOf(e);return t.map(((t,e)=>e===r?`${t} - ${n}`:t)).join()}},2069:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseConcatAttributes=e.concat=void 0;const r=n(246),i=n(2039),o=n(1163);e.concat=(t,e,n)=>(p(e),t.session.pack&&e[0].dims.length>1?[t.run((0,o.createPackedConcatProgramInfoLoader)(t,e,n),e)]:[t.run(a(t,e,n),e)]);const a=(t,e,n)=>{const r=(o=e.length,a=n.cacheKey,{name:"Concat",inputNames:Array.from({length:o},((t,e)=>`X${e}`)),inputTypes:Array(o).fill(i.TextureType.unpacked),cacheHint:a});var o,a;return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const o=n[0].dims.slice();if(r>=o.length||r<-1*o.length)throw new Error("axis specified for concat doesn't match input dimensionality");r<0&&(r=o.length+r);const a=o.slice(0);for(let t=1;t<n.length;t++){const e=n[t].dims.slice();for(let t=0;t<o.length;t++)if(t===r)a[r]+=e[t];else if(o[t]!==e[t])throw new Error("non concat dimensions must match")}const p=a.length,f=new Array(n.length);let d=0;for(let t=0;t<f.length;++t)d+=n[t].dims[r],f[t]=d;let h="";h=n.length<5?s(f):u(f);const g=`\n        ${c(n.length,p)}\n        ${l(f)}\n        ${h}\n        float process(int indices[${p}]) {\n          int textureIndex = getTextureWhereDataResides (indices[${r}]);\n\n          if(textureIndex != 0) {\n            indices[${r}] = indices[${r}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));\n          }\n\n          return fetchDataFromCorrectTexture(textureIndex, indices);\n        }`;return Object.assign(Object.assign({},e),{output:{dims:a,type:n[0].type,textureType:i.TextureType.unpacked},shaderSource:g})})(0,r,e,n.axis)})},s=t=>`int getTextureWhereDataResides(int index) {\n      ${t.map(((t,e)=>`if(index<${t}) {return ${e};}\n`)).join("")}\n    }`,u=t=>s(t),c=(t,e)=>{const n=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e}]) {`];for(let e=0;e<t;++e)0===e?n.push(`\tif (textureIndex == ${e}) { return _X${e}(indices); }`):e===t-1?n.push(`\telse { return _X${e}(indices); }`):n.push(`\telse if (textureIndex == ${e}) { return _X${e}(indices); }`);return n.push("\t}"),n.join("\n")},l=t=>{const e=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let n=0;n<t.length;++n)0===n?e.push(`\tif (index == ${n}) { return ${t[n]}; }`):n===t.length-1?e.push(`\telse { return ${t[n]}; }`):e.push(`\telse if (index == ${n}) { return ${t[n]}; }`);return e.push("\t}"),e.join("\n")};e.parseConcatAttributes=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis")});const p=t=>{if(!t||t.length<1)throw new Error("too few inputs");const e=t[0].type,n=t[0].dims.length;if("string"===e)throw new Error("string tensor is not supported yet");for(const r of t){if(r.type!==e)throw new Error("input tensors should be one type");if(r.dims.length!==n)throw new Error("input tensors should have the same shape")}}},4770:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createUnpackedGroupedConvProgramInfoLoader=void 0;const r=n(6231),i=n(5060),o=n(2039),a=n(8138),s=n(2823);e.createUnpackedGroupedConvProgramInfoLoader=(t,e,n)=>{const u=(c=e.length>2,l=n.cacheKey,{name:"GroupedConv",inputNames:c?["X","W","Bias"]:["X","W"],inputTypes:c?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:l});var c,l;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,u)=>{const c=e.length>2?"value += getBias(output_channel);":"",l=e[0].dims.slice(),p=e[1].dims.slice(),f=p[0]/u.group;r.Logger.verbose("GroupedConv",`autpPad:${u.autoPad}, dilations:${u.dilations}, group:${u.group}, kernelShape:${u.kernelShape}, pads:${u.pads}, strides:${u.strides}`);const d=(0,a.calculateOutputShape)(l,p,u.dilations,u.pads,u.strides),h=(0,i.getGlsl)(t.session.backend.glContext.version),{activationFunction:g,applyActivation:b}=(0,s.getActivationSnippet)(u),m=`\n  const ivec2 strides = ivec2(${u.strides[0]}, ${u.strides[1]});\n  const ivec2 pads = ivec2(${u.pads[0]}, ${u.pads[1]});\n  ${g}\n  void main() {\n    ivec4 coords = getOutputCoords();\n    int batch = coords.x;\n    int output_channel = coords.y;\n    ivec2 xRCCorner = coords.zw * strides - pads;\n    int group_id = output_channel / ${f};\n\n    float value = 0.0;\n    for (int wInChannel = 0; wInChannel < ${p[1]}; wInChannel++) {\n      int input_channel = group_id * ${p[1]} + wInChannel;\n      for (int wHeight = 0; wHeight < ${p[2]}; wHeight++) {\n        int xHeight = xRCCorner.x + wHeight * ${u.dilations[0]};\n\n        if (xHeight < 0 || xHeight >= ${l[2]}) {\n          continue;\n        }\n\n        for (int wWidth = 0; wWidth < ${p[3]}; wWidth++) {\n          int xWidth = xRCCorner.y + wWidth * ${u.dilations[1]};\n          if (xWidth < 0 || xWidth >= ${l[3]}) {\n            continue;\n          }\n\n          float xVal = getX(batch, input_channel, xWidth, xHeight);\n          float wVal = getW(output_channel, wInChannel, wWidth, wHeight);\n          value += xVal*wVal;\n        }\n      }\n    }\n    ${c}\n    ${b}\n    ${h.output} = vec4(value, .0, .0, .0);\n  }\n`;return Object.assign(Object.assign({},n),{output:{dims:d,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:m,hasMain:!0})})(t,e,u,n)})}},1386:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.conv2DPacked=e.conv2DPackedPointwise=void 0;const r=n(8138),i=n(8555),o=n(708);e.conv2DPackedPointwise=(t,e,n)=>{const i=e[0].dims,a=e[1].dims,s=(0,r.calculateOutputShape)(i,a,n.dilations,n.pads,n.strides),u=t.reshapePacked(e[0],[i[1],i[2]*i[3]]),c=t.reshapePacked(e[1],[a[0],a[1]]),l=e.length>2?[c,u,e[2]]:[c,u],p=t.run((0,o.createPackedMatmulProgramInfoLoader)(t,l,n),l);return t.reshapePacked(p,s)},e.conv2DPacked=(t,e,n)=>{const a=e[0].dims,s=e[1].dims,u=(0,r.calculateOutputShape)(a,s,n.dilations,n.pads,n.strides),c=t.run((0,i.createPackedIm2ColProgramInfoLoader)(t,e[0],e[1],u,n),[e[0]]),l=t.reshapePacked(e[1],[s[0],s[1]*s[2]*s[3]]),p=3===e.length?[l,c,e[2]]:[l,c],f=t.run((0,o.createPackedMatmulProgramInfoLoader)(t,p,n),p);return t.reshapePacked(f,u)}},9663:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseConvTransposeAttributes=e.convTranspose=void 0;const r=n(246),i=n(5060),o=n(2039),a=n(2823),s=(t,e,n,r,i,o)=>(t-1)*e+n+(r-1)*i+1-o,u=(t,e,n,r,i)=>{const o=Math.floor(t/2);"SAME_UPPER"===e?(n[r]=o,n[i]=t-o):"SAME_LOWER"===e&&(n[r]=t-o,n[i]=o)};e.convTranspose=(t,e,n)=>(f(e,n),c(t,e,n));const c=(t,e,n)=>{const r=p(n,e);return[l(t,e,r)]},l=(t,e,n)=>t.run(((t,e,n)=>{const r=(s=e.length>2,u=n.cacheKey,{name:"ConvTranspose",inputNames:s?["X","W","B"]:["X","W"],inputTypes:s?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:u});var s,u;return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const s=e.length>2?"getB(output_channel)":"0.0",u=e[0].dims,c=e[1].dims,l=c[1],p=c[0]/r.group,f=[e[0].dims[0],e[1].dims[1]*r.group,...r.outputShape],d=(0,i.getGlsl)(t.session.backend.glContext.version),{activationFunction:h,applyActivation:g}=(0,a.getActivationSnippet)(r),b=`\n  const ivec2 strides = ivec2(${r.strides[0]}, ${r.strides[1]});\n  const ivec2 pads = ivec2(${r.pads[0]}, ${r.pads[1]});\n  ${h}\n  void main() {\n    ivec4 coords = getOutputCoords();\n    int batch = coords.x;\n    int output_channel = coords.y;\n\n    ivec2 loc = coords.zw + pads;\n\n    int group_id = output_channel / ${l};\n    int wOutChannel = output_channel - group_id * ${l};\n\n    float value = ${s};\n    for (int inChannelOffset = 0; inChannelOffset < ${p}; inChannelOffset++) {\n      int input_channel = group_id * ${p} + inChannelOffset;\n      for (int wWOff = 0; wWOff < ${c[2]}; wWOff++) {\n        for (int wHOff = 0; wHOff < ${c[3]}; wHOff++) {\n          ivec2 wOff = ivec2(wWOff * ${r.dilations[0]}, wHOff * ${r.dilations[1]});\n          ivec2 wLoc = loc - wOff;\n          ivec2 wLocIn = wLoc / strides;\n          if (\n            wLocIn * strides == wLoc &&\n            wLocIn.x >= 0 && wLocIn.x < ${u[2]} &&\n            wLocIn.y >= 0 && wLocIn.y < ${u[3]}\n          ) {\n            float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);\n            float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);\n            value += xVal * wVal;\n          }\n        }\n      }\n    }\n    ${g}\n    ${d.output} = vec4(value, .0, .0, .0);\n  }\n`;return Object.assign(Object.assign({},n),{output:{dims:f,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:b,hasMain:!0})})(t,e,r,n)})})(t,e,n),e),p=(t,e)=>{const n=t.kernelShape.slice();if(0===t.kernelShape.length)for(let t=2;t<e[1].dims.length;++t)n.push(e[1].dims[t]);const r=t.pads.slice(),i=t.outputShape.slice();((t,e,n,r,i,o,a,c)=>{const l=t.length-2,p=0===c.length;for(let f=0;f<l;++f){const d=p?t[f+2]*o[f]:c[f],h=s(t[f+2],o[f],i[f],e[f],n[f],d);u(h,r,i,f,f+l),p&&c.push(o[f]*(t[f+2]-1)+a[f]+(e[f]-1)*n[f]+1-i[f]-i[f+l])}})(e[0].dims,n,t.dilations,t.autoPad,r,t.strides,t.outputPadding,i);const o=Object.assign({},t);return Object.assign(o,{kernelShape:n,pads:r,outputShape:i,cacheKey:t.cacheKey}),o};e.parseConvTransposeAttributes=t=>{const e=t.attributes,n=(0,a.parseInternalActivationAttributes)(e),i=e.getString("auto_pad","NOTSET"),o=e.getInts("dilations",[1,1]),s=e.getInt("group",1),u=e.getInts("kernel_shape",[]),c=e.getInts("output_padding",[0,0]),l=e.getInts("output_shape",[]),p=e.getInts("pads",[0,0,0,0]),f=e.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:s,kernelShape:u,outputPadding:c,outputShape:l,pads:p,strides:f},n))};const f=(t,e)=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==t[0].dims.length||4!==t[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(t[0].dims[1]!==t[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const n=t[1].dims[1]*e.group;if(3===t.length&&(1!==t[2].dims.length||t[2].dims[0]!==n))throw new Error("invalid bias");const r=t[0].dims.length-2;if(e.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(e.strides.length!==r)throw new Error(`strides should be ${r}D`);if(e.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(e.outputPadding.length!==r)throw new Error(`output_padding should be ${r}D`);if(0!==e.kernelShape.length&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==e.outputShape.length&&e.outputShape.length!==t[0].dims.length-2)throw new Error("invalid output shape");if("float32"!==t[0].type||"float32"!==t[1].type)throw new Error("ConvTranspose input(X,W) should be float tensor");if(3===t.length&&"float32"!==t[2].type)throw new Error("ConvTranspose input(bias) should be float tensor")}},8138:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseConvAttributes=e.conv=e.calculateOutputShape=void 0;const r=n(246),i=n(2517),o=n(4770),a=n(1386),s=n(9828),u=n(2823),c=n(3248),l=n(5623);e.calculateOutputShape=(t,e,n,r,i)=>{const o=t[0],a=t.slice(2),s=a.length,u=e[0],c=e.slice(2).map(((t,e)=>t+(t-1)*(n[e]-1))),l=a.map(((t,e)=>t+r[e]+r[e+s])).map(((t,e)=>Math.floor((t-c[e]+i[e])/i[e])));return[o,u].concat(...l)},e.conv=(t,e,n)=>(g(e,n),p(t,e,n));const p=(t,e,n)=>{const r=h(n,e),i=t.session.pack,s=1===r.kernelShape[0]&&1===r.kernelShape[1];return r.group>1?[t.run((0,o.createUnpackedGroupedConvProgramInfoLoader)(t,e,r),e)]:s&&i?[f(t,e,r)]:i&&4===e[0].dims.length&&1===e[0].dims[0]&&!s?[(0,a.conv2DPacked)(t,e,r)]:[d(t,e,r)]},f=(t,n,r)=>{const i=n[0].dims,o=n[1].dims,a=(0,e.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),s=t.reshapeUnpacked(n[0],[i[1],i[2]*i[3]]),u=t.reshapeUnpacked(n[1],[o[0],o[1]]),c=n.length>2?[u,s,n[2]]:[u,s],p=t.run((0,l.createMatmulProgramInfoLoader)(c,r),c);return t.reshapeUnpacked(p,a)},d=(t,n,r)=>{const i=n[0].dims,o=n[1].dims,a=(0,e.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),u=t.run((0,c.createIm2ColProgramInfoLoader)(t,n[0],n[1],a,r),[n[0]]),l=3===n.length?[u,n[1],n[2]]:[u,n[1]];return t.run((0,s.createDotProductProgramInfoLoader)(t,n,a,r),l)},h=(t,e)=>{const n=t.kernelShape.slice();if(0===t.kernelShape.length)for(let t=2;t<e[1].dims.length;++t)n.push(e[1].dims[t]);const r=t.pads.slice();i.PoolConvUtil.adjustPadsBasedOnAutoPad(e[0].dims,t.strides,t.dilations,n,r,t.autoPad);const o=Object.assign({},t);return Object.assign(o,{kernelShape:n,pads:r,cacheKey:t.cacheKey}),o};e.parseConvAttributes=t=>{const e=t.attributes,n=(0,u.parseInternalActivationAttributes)(e),i=e.getString("auto_pad","NOTSET"),o=e.getInts("dilations",[1,1]),a=e.getInt("group",1),s=e.getInts("kernel_shape",[]),c=e.getInts("pads",[0,0,0,0]),l=e.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:a,kernelShape:s,pads:c,strides:l},n))};const g=(t,e)=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==t[0].dims.length||4!==t[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(t[0].dims[1]!==t[1].dims[1]*e.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===t.length&&(1!==t[2].dims.length||t[1].dims[0]!==t[2].dims[0]))throw new Error("invalid bias");const n=t[0].dims.length-2;if(e.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(e.strides.length!==n)throw new Error(`strides should be ${n}D`);if(e.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==e.kernelShape.length&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if("float32"!==t[0].type||"float32"!==t[1].type)throw new Error("Conv input(X,W) should be float tensor");if(3===t.length&&"float32"!==t[2].type)throw new Error("Conv input(bias) should be float tensor")}},5193:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseDepthToSpaceAttributes=e.depthToSpace=void 0;const r=n(3738);e.depthToSpace=(t,e,n)=>{i(e);const o=n.blocksize,a=o*o,s="DCR"===n.mode?[0,3,4,1,5,2]:[0,1,4,2,5,3],u="DCR"===n.mode?[e[0].dims[0],o,o,e[0].dims[1]/a,e[0].dims[2],e[0].dims[3]]:[e[0].dims[0],e[0].dims[1]/a,o,o,e[0].dims[2],e[0].dims[3]],c=t.reshapeUnpacked(e[0],u),l={perm:s,cacheKey:`${s}`},[p]=(0,r.transpose)(t,[c],l),f=[e[0].dims[0],e[0].dims[1]/a,e[0].dims[2]*o,e[0].dims[3]*o];return[t.reshapeUnpacked(p,f)]},e.parseDepthToSpaceAttributes=t=>{const e=t.attributes.getInt("blocksize");if(e<1)throw new Error(`blocksize must be >= 1, but got : ${e} for DepthToSpace`);const n=t.attributes.getString("mode","DCR");if("DCR"!==n&&"CRD"!==n)throw new Error(`unrecognized mode: ${n} for DepthToSpace`);return{mode:n,blocksize:e}};const i=t=>{if(1!==t.length)throw new Error(`DepthToSpace expect 1 inputs, but got ${t.length}`);if("string"===t[0].type||4!==t[0].dims.length)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},9828:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createDotProductProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),a=n(2823),s=n(3248);e.createDotProductProgramInfoLoader=(t,e,n,u)=>{const c=((t,e)=>({name:"ConvDotProduct",inputNames:t?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:t?[o.TextureType.unpacked,o.TextureType.packedLastDimension,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.packedLastDimension],cacheKey:e.activationCacheKey}))(e.length>2,u);return Object.assign(Object.assign({},c),{get:()=>((t,e,n,u,c)=>{const l=n[0].dims,p=n[1].dims,f=[p[0],Math.ceil(l[1]*p[2]*p[3]/4)],d=(0,s.calculateIm2ColDims)(l,p,u),[h,g]=t.calculateTextureWidthAndHeight(f,o.TextureType.packedLastDimension),b=r.ShapeUtil.computeStrides(d),[m,y]=t.calculateTextureWidthAndHeight(d,o.TextureType.packedLastDimension),_=u.length,v=n.length<3?"0.0":"_B(b)",w=Math.ceil(l[1]*p[2]*p[3]/4),{activationFunction:x,applyActivation:T}=(0,a.getActivationSnippet)(c),S=(0,i.getGlsl)(t.session.backend.glContext.version),O=`\n${x}\nfloat process(int indices[${_}]) {\n  int b[1];\n  b[0] = indices[1];\n  int im2col[4];\n  im2col[0] = indices[0];\n  im2col[1] = indices[2];\n  im2col[2] = indices[3];\n  int im2colOffset = im2col[0] * ${b[0]} + im2col[1] * ${b[1]} + im2col[2] * ${b[2]};\n  int kernelOffset = indices[1] * ${f[1]};\n  float value = ${v};\n  for (int i = 0; i < ${w}; ++i) {\n    vec2 im2colCoords = offsetToCoords(im2colOffset, ${m}, ${y});\n    vec2 kernelCoords = offsetToCoords(kernelOffset, ${h}, ${g});\n    value += dot(${S.texture2D}(Im2Col, im2colCoords), ${S.texture2D}(K, kernelCoords));\n    ++im2colOffset;\n    ++kernelOffset;\n  }\n  ${T}\n  return value;\n}`;return Object.assign(Object.assign({},e),{output:{dims:u,type:n[0].type,textureType:o.TextureType.unpacked},shaderSource:O})})(t,c,e,n,u)})}},7992:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseFlattenAttributes=e.flatten=void 0;const r=n(2517);e.flatten=(t,e,n)=>{i(e,n);const o=r.ShapeUtil.flattenShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.parseFlattenAttributes=t=>t.attributes.getInt("axis",1);const i=(t,e)=>{if(!t||1!==t.length)throw new Error("Flatten requires 1 input.");const n=t[0].dims.length;if(0===n)throw new Error("scalar tensor is not supported.");if(e<-n||e>n)throw new Error("Invalid axis");if("string"===t[0].type)throw new Error("string tensor is not supported.")}},2823:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseInternalActivationAttributes=e.getActivationSnippet=void 0;const r=n(2517),i=n(4909);e.getActivationSnippet=function(t){let e;switch(t.activation){case"Relu":e=(0,i.glslRelu)();break;case"Sigmoid":e=(0,i.glslSigmoid)();break;case"Clip":e=(0,i.glslClip)(t.clipMin,t.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const n=e.name;return{activationFunction:e.body,applyActivation:`value = ${n}_(value);`}},e.parseInternalActivationAttributes=t=>{const e=t.getString("activation","");if("Clip"===e){const[n,i]=t.getFloats("activation_params",[r.MIN_CLIP,r.MAX_CLIP]);return{activation:e,clipMax:i,clipMin:n,activationCacheKey:`${e}:${n},${i}`}}return{activation:e,activationCacheKey:e}}},1253:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseGatherAttributes=e.gather=void 0;const r=n(246),i=n(782),o=n(2517),a=n(2039);e.gather=(t,e,n)=>(c(e,n.axis),[t.run(u(t,e,n),e)]),e.parseGatherAttributes=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",0)});const s={name:"Gather",inputNames:["A","B"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked]},u=(t,e,n)=>{const r=Object.assign(Object.assign({},s),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const i=n[0].dims.slice(),s=n[1].dims.slice(),u=new Array(i.length+s.length-1);r=o.ShapeUtil.normalizeAxis(r,i.length);const c=[];for(let t=0;t<u.length;t++)t<r?(u[t]=i[t],c.push(`inputIdx[${t}] = outputIdx[${t}];`)):t<r+s.length?(u[t]=s[t-r],c.push(`indexDataIdx[${t-r}] = outputIdx[${t}];`)):(u[t]=i[t-s.length+1],c.push(`inputIdx[${t-s.length+1}] = outputIdx[${t}];`));const l=`\n      float process(int outputIdx[${u.length||1}]) {\n        int inputIdx[${i.length}];\n        int indexDataIdx[${s.length||1}];\n        indexDataIdx[0] = 0;\n        ${c.join("\n        ")}\n        int idx = int(_B(indexDataIdx));\n        inputIdx[${r}] = idx < 0 ? idx + ${i[r]} : idx;\n        return _A(inputIdx);\n      }`;return Object.assign(Object.assign({},e),{output:{dims:u,type:n[0].type,textureType:a.TextureType.unpacked},shaderSource:l})})(0,r,e,n.axis)})},c=(t,e)=>{if(!t||2!==t.length)throw new Error("Gather requires 2 inputs.");const n=t[0].dims.length;if(n<1)throw new Error("Invalid input shape.");if(e<-n||e>n-1)throw new Error("Invalid axis.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invaid input type.");if("int32"!==t[1].type&&"int16"!==t[1].type)throw new Error("Invaid input type.")}},4776:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseGemmAttributesV11=e.parseGemmAttributesV7=e.gemm=void 0;const r=n(246),i=n(2517),o=n(2039);e.gemm=(t,e,n)=>(c(e,n),[t.run(s(e,n),e)]);const a=(t,e)=>{const n=0!==t.attributes.getInt("transA",0),i=0!==t.attributes.getInt("transB",0),o=t.attributes.getFloat("alpha",1),a=t.attributes.getFloat("beta",1);return(0,r.createAttributeWithCacheKey)({transA:n,transB:i,alpha:o,beta:a,isOptionalC:e})};e.parseGemmAttributesV7=t=>a(t,!1),e.parseGemmAttributesV11=t=>a(t,!0);const s=(t,e)=>{const n={name:"Gemm",inputNames:3===t.length?["A","B","C"]:["A","B"],inputTypes:3===t.length?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],key:e.cacheKey};return Object.assign(Object.assign({},n),{get:()=>u(n,t,e)})},u=(t,e,n)=>{const r=e[0].dims.slice(),a=e[1].dims.slice(),[s,u]=i.GemmUtil.getShapeOfGemmResult(r,n.transA,a,n.transB,3===e.length?e[2].dims:void 0),c=[s,u];if(!c)throw new Error("Can't use gemm on the given tensors");let l=r[r.length-1],p="";n.transA&&(l=r[0]),n.transA&&n.transB?p="value += _A_T(a) * _B_T(b);":n.transA&&!n.transB?p="value += _A_T(a) * _B(b);":!n.transA&&n.transB?p="value += _A(a) * _B_T(b);":n.transA||n.transB||(p="value += _A(a) * _B(b);");const f=c.length,d=`\n      float process(int indices[${f}]) {\n          int a[${f}];\n          int b[${f}];\n          ${3===e.length?`int c[${e[2].dims.length}];`:""}\n\n          copyVec(indices, a);\n          copyVec(indices, b);\n          ${3===e.length?"bcastIndices_C(indices, c);":""}\n\n          float value = 0.0;\n          for (int k=0; k<${l}; ++k) {\n              a[${f-1}] = k;\n              b[${f-2}] = k;\n              ${p}\n          }\n\n          value = value * alpha;\n          ${3===e.length?"value += beta * _C(c);":""}\n          return value;\n      }`;return Object.assign(Object.assign({},t),{output:{dims:c,type:e[0].type,textureType:o.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:n.alpha},{name:"beta",type:"float",data:n.beta}],shaderSource:d})},c=(t,e)=>{if(!t)throw new Error("Input is missing");if(e.isOptionalC&&(t.length<2||t.length>3))throw new Error("Invaid input shape.");if(!e.isOptionalC&&3!==t.length)throw new Error("Gemm requires 3 inputs");if(3===t.length&&1!==t[2].dims.length&&2!==t[2].dims.length)throw new Error("Invalid input shape of C");if("float32"!==t[0].type&&"float64"!==t[0].type||"float32"!==t[1].type&&"float64"!==t[1].type||3===t.length&&"float32"!==t[2].type&&"float64"!==t[2].type)throw new Error("Invalid input type.");if(t[0].type!==t[1].type||3===t.length&&t[0].type!==t[2].type)throw new Error("Input types are mismatched")}},8555:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedIm2ColProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(2827);e.createPackedIm2ColProgramInfoLoader=(t,e,n,a,s)=>{const u=(c=s.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[i.TextureType.packed],cacheHint:c});var c;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,a,s,u)=>{const c=n.dims,l=a.dims,p=s.length,f=[l[1]*l[2]*l[3],s[2]*s[3]],d=l[2]*l[3],h=(0,o.unpackFromChannel)(),g=(0,r.getGlsl)(t.session.backend.glContext.version);let b="";for(let t=0;t<=1;t++)for(let e=0;e<=1;e++)b+=`\n            blockIndex = rc.x + ${e};\n            pos = rc.y + ${t};\n\n            if(blockIndex < ${f[1]} && pos < ${f[0]}) {\n              offsetY = int(blockIndex / (${s[p-1]})) * ${u.strides[0]} -\n                ${u.pads[0]};\n              d0 = offsetY + ${u.dilations[0]} * (imod(pos, ${d}) / ${l[2]});\n\n              if(d0 < ${c[2]} && d0 >= 0) {\n                offsetX = imod(blockIndex, ${s[p-1]}) * ${u.strides[1]} -\n                  ${u.pads[1]};\n                d1 = offsetX + ${u.dilations[1]} * imod(imod(pos, ${d}), ${l[2]});\n\n                if(d1 < ${c[3]} && d1 >= 0) {\n\n                  ch = int(float(pos)/ ${d}.);\n                    innerDims = vec2(d0, d1);\n                    result[${2*t+e}] = getChannel(\n                      getA(0, ch, int(innerDims.x),\n                      int(innerDims.y)), innerDims);\n                }\n              }\n            }\n\n          `;const m=`\n      ${h}\n\n      void main() {\n        ivec2 rc = getOutputCoords();\n          vec4 result = vec4(0.0);\n          int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n          vec2 innerDims;\n          ${b}\n          ${g.output} = result;\n      }\n            `;return Object.assign(Object.assign({},e),{output:{dims:f,type:n.type,textureType:i.TextureType.packed},shaderSource:m,hasMain:!0})})(t,u,e,n,a,s)})}},3248:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.calculateIm2ColDims=e.createIm2ColProgramInfoLoader=void 0;const r=n(2039);e.createIm2ColProgramInfoLoader=(t,n,i,o,a)=>{const s=(u=a.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[r.TextureType.unpacked],cacheHint:u});var u;return Object.assign(Object.assign({},s),{get:()=>((t,n,i,o,a,s)=>{const u=i.dims,c=o.dims,l=a.length,p=(0,e.calculateIm2ColDims)(u,c,a,4),f=`\n        const int XC = ${u[1]};\n        const int XH = ${u[2]};\n        const int XW = ${u[3]};\n        const int KH = ${s.kernelShape[0]};\n        const int KW = ${s.kernelShape[1]};\n        const int dilationH = ${s.dilations[0]};\n        const int dilationW = ${s.dilations[1]};\n        const int strideH = ${s.strides[0]};\n        const int strideW = ${s.strides[1]};\n        const int padH = ${s.pads[0]};\n        const int padW = ${s.pads[1]};\n        const int KHKW = KH*KW;\n        const int XCKHKW = XC * KHKW;\n        const int outputChannels = 4;\n        vec4 process(int indices[${l}]) {\n          int b  = indices[0]; // batch size\n          int oh = indices[1] * strideH - padH; //output height\n          int ow = indices[2] * strideW - padW; //output width\n          int p = indices[3] * outputChannels; //patch\n          vec4 value = vec4(0.0);\n          for(int i=0; i < outputChannels; ++i) {\n            if(p < XCKHKW) {\n              int patchC = p / KHKW;\n              int patchH = (p - patchC*KHKW) / KW;\n              int patchW = (p - patchC*KHKW) - patchH * KW;\n              int xh2 = oh + patchH * dilationH;\n              int xw2 = ow + patchW * dilationW;\n              int x[${u.length}];\n              x[0] = b;\n              x[1] = patchC;\n              x[2] = xh2;\n              x[3] = xw2;\n              if(xh2 >= 0 &&\n                  xh2 < XH &&\n                  xw2 >= 0 &&\n                  xw2 < XW) {\n                value[i] = _X(x);\n              }\n            }\n            ++p;\n          }\n          return value;\n        }\n        `;return Object.assign(Object.assign({},n),{output:{dims:p,type:i.type,textureType:r.TextureType.packedLastDimension},shaderSource:f})})(0,s,n,i,o,a)})},e.calculateIm2ColDims=(t,e,n,r=4)=>[n[0],n[2],n[3],Math.ceil(t[1]*e[2]*e[3]/r)]},6572:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseImageScalerAttributes=e.imageScaler=void 0;const r=n(246),i=n(2039);e.imageScaler=(t,e,n)=>(u(e),[t.run(a(t,e,n),e)]),e.parseImageScalerAttributes=t=>{const e=t.attributes.getFloat("scale"),n=t.attributes.getFloats("bias");return(0,r.createAttributeWithCacheKey)({scale:e,bias:n})};const o={name:"ImageScaler",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},a=(t,e,n)=>{const r=Object.assign(Object.assign({},o),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const o=n[0].dims.slice(),a=o.length,u=`\n      ${s(r.bias.length)}\n      float process(int indices[${a}]) {\n        return _X(indices) * scale + getBias(bias, indices[1]);\n      }`;return Object.assign(Object.assign({},e),{output:{dims:o,type:n[0].type,textureType:i.TextureType.unpacked},variables:[{name:"bias",type:"float",arrayLength:r.bias.length,data:r.bias},{name:"scale",type:"float",data:r.scale}],shaderSource:u})})(0,r,e,n)})},s=t=>{const e=[`float getBias(float bias[${t}], int channel) {`];for(let n=0;n<t;++n)0===n?e.push(`\tif (channel == ${n}) { return bias[${n}]; }`):n===t-1?e.push(`\telse { return bias[${n}]; }`):e.push(`\telse if (channel == ${n}) { return bias[${n}]; }`);return e.push("\t}"),e.join("\n")},u=t=>{if(!t||1!==t.length)throw new Error("ImageScaler requires 1 input.");if(4!==t[0].dims.length)throw new Error("Invalid input shape.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")}},3346:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseInstanceNormalizationAttributes=e.instanceNormalization=void 0;const r=n(5060),i=n(2039);e.instanceNormalization=(t,e,n)=>{c(e);const r=t.run(a(e[0]),e);return[t.run(u(t,e[0],n,r.dims),[e[0],r,e[1],e[2]])]},e.parseInstanceNormalizationAttributes=t=>t.attributes.getFloat("epsilon",1e-5);const o={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},a=t=>Object.assign(Object.assign({},o),{get:()=>((t,e)=>{const n=e.dims.slice(),r=n[1],o=n[2]*n[3],a=[n[0],r],s=`\n      vec4 process(int[2] indices) {\n        vec4 v = vec4(0.0);\n        int a[4];\n        a[0] = indices[0];\n        a[1] = indices[1];\n        float temp = 0.0;\n        for(int a2=0; a2<${n[2]}; a2++) {\n          a[2] = a2;\n          for(int a3=0; a3<${n[3]}; a3++) {\n            a[3] = a3;\n            float x = _X(a);\n            temp += x;\n          }\n        }\n        float mean = temp / float(${o});\n        temp = 0.0;\n        for(int a2=0; a2<${n[2]}; a2++) {\n          a[2] = a2;\n          for(int a3=0; a3<${n[3]}; a3++) {\n            a[3] = a3;\n            float x = _X(a);\n            temp += (x - mean) * (x - mean);\n          }\n        }\n        v.r = mean;\n        v.g = temp / float(${o});\n\n        return v;\n      }`;return Object.assign(Object.assign({},t),{output:{dims:a,type:e.type,textureType:i.TextureType.packedLastDimension},shaderSource:s})})(o,t)}),s={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[i.TextureType.unpacked,i.TextureType.packedLastDimension,i.TextureType.unpacked,i.TextureType.unpacked]},u=(t,e,n,o)=>{const a=Object.assign(Object.assign({},s),{cacheHint:`${n}`});return Object.assign(Object.assign({},a),{get:()=>((t,e,n,o,a)=>{const s=(0,r.getGlsl)(t.session.backend.glContext.version),[u,c]=t.calculateTextureWidthAndHeight(a,i.TextureType.packedLastDimension),[l,p]=[u/4,c],f=`\n      vec4 get_MeanAndVariance(int[2] mv) {\n        int offset = indicesToOffset_MeanAndVariance(mv);\n        vec2 coords = offsetToCoords(offset, ${l}, ${p});\n        return ${s.texture2D}(MeanAndVariance, coords);\n      }\n\n      float process(int[4] indices) {\n        int mv[2];\n        mv[0] = indices[0];\n        mv[1] = indices[1];\n        vec4 mean_and_variance = get_MeanAndVariance(mv);\n        float mean = mean_and_variance.r;\n        float variance = mean_and_variance.g;\n\n        int sb[1];\n        sb[0] = indices[1];\n        float scale = _Scale(sb);\n        float b = _B(sb);\n\n        return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;\n      }`;return Object.assign(Object.assign({},e),{output:{dims:n.dims,type:n.type,textureType:i.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:o}],shaderSource:f})})(t,a,e,n,o)})},c=t=>{if(!t||3!==t.length)throw new Error("InstanceNormalization requires 3 inputs.");const e=t[0],n=t[1],r=t[2];if(e.dims.length<3||1!==n.dims.length||1!==r.dims.length)throw new Error("Invalid input shape.");if(n.dims[0]!==e.dims[1]||r.dims[0]!==e.dims[1])throw new Error("Input shapes are mismatched.");if("float32"!==e.type&&"float64"!==e.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type)throw new Error("Invalid input type.");if(4!==t[0].dims.length)throw new Error("Only support 4-D input shape.")}},708:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedMatmulProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),a=n(9390),s=n(2823),u=n(5623);e.createPackedMatmulProgramInfoLoader=(t,e,n)=>{const c=(l=e.length>2,p=n.activationCacheKey,{name:"MatMul (packed)",inputNames:l?["A","B","Bias"]:["A","B"],inputTypes:l?[o.TextureType.packed,o.TextureType.packed,o.TextureType.packed]:[o.TextureType.packed,o.TextureType.packed],cacheHint:p});var l,p;return Object.assign(Object.assign({},c),{get:()=>((t,e,n,c)=>{const l=n.length>2,p=l?"value += getBiasForMatmul();":"",f=n[0].dims,d=n[1].dims,h=r.BroadcastUtil.calcShape(f,d,!0),g=!r.ShapeUtil.areEqual(n[0].dims,n[1].dims);if(!h)throw new Error("Can't use matmul on the given tensors");const b=f[f.length-1],m=Math.ceil(b/2),y=f.length,_=d.length,v=(0,i.getGlsl)(t.session.backend.glContext.version),w=(0,a.getCoordsDataType)(h.length),x=h.length,T=(0,a.getGlChannels)(),{activationFunction:S,applyActivation:O}=(0,s.getActivationSnippet)(c),A=l?`${(0,u.getBiasForMatmul)(w,T,n[2].dims,h,!0)}`:"",E=g?`${function(t,e,n,i){let o=[],a=[];const s=n[0].dims,u=n[1].dims,c=s.length,l=u.length,p=i.length,f=p-c,d=p-l;o=s.map(((t,n)=>`coords.${e[n+f]}`)),o[c-1]="i*2",o.join(", "),a=u.map(((t,n)=>`coords.${e[n+d]}`)),a[l-2]="i*2",a.join(", ");const h=r.BroadcastUtil.getBroadcastDims(s,i),g=r.BroadcastUtil.getBroadcastDims(u,i),b=h.map((t=>`coords.${e[t+f]} = 0;`)).join("\n"),m=g.map((t=>`coords.${e[t+d]} = 0;`)).join("\n"),y=`int lastDim = coords.${e[p-1]};\n  coords.${e[p-1]} = coords.${e[p-2]};\n  coords.${e[p-2]} = lastDim;`;return`\nvec4 getAAtOutCoordsMatmul(int i) {\n  ${t} coords = getOutputCoords();\n  ${y}\n  ${b}\n  vec4 outputValue = getA(${o});\n  return outputValue;\n}\n\nvec4 getBAtOutCoordsMatmul(int i) {\n  ${t} coords = getOutputCoords();\n  ${y}\n  ${m}\n  vec4 outputValue = getB(${a});\n  return outputValue;\n}`}(w,T,n,h)}`:"",I=g?"getAAtOutCoordsMatmul(i)":`getA(${function(t,e){let n="";for(let r=0;r<e-2;r++)n+=`rc.${t[r]}, `;return n+=`rc.${t[e-2]}, i*2`,n}(T,y)})`,P=g?"getBAtOutCoordsMatmul(i)":`getB(${function(t,e){let n="";for(let r=0;r<e-2;r++)n+=`rc.${t[r]}, `;return n+=`i*2, rc.${t[e-1]}`,n}(T,_)})`,D=`\n            ${E}\n            ${A}\n            ${S}\n            void main() {\n              ${g?"":`${w} rc =\n          getOutputCoords(); int lastDim = rc.${T[x-1]}; rc.${T[x-1]} =\n          rc.${T[x-2]}; rc.${T[x-2]} = lastDim;\n      `}\n\n              vec4 value = vec4(0);\n              for (int i = 0; i < ${m}; i++) {\n                vec4 a = ${I};\n                vec4 b = ${P};\n\n                value += (a.rrbb * b.rgrg);\n                value += (a.ggaa * b.baba);\n              }\n              ${p}\n              ${O}\n              ${v.output} = value;\n            }`;return Object.assign(Object.assign({},e),{output:{dims:h,type:n[0].type,textureType:o.TextureType.packed},shaderSource:D,hasMain:!0})})(t,c,e,n)})}},5623:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getBiasForMatmul=e.createMatmulProgramInfoLoader=e.parseMatMulAttributes=e.matMul=void 0;const r=n(2517),i=n(2039),o=n(9390),a=n(2823),s=n(708);function u(t,e){const n=(s=t.length>2,u=e.activationCacheKey,{name:"MatMul",inputNames:s?["A","B","Bias"]:["A","B"],inputTypes:s?[i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked]:[i.TextureType.unpacked,i.TextureType.unpacked],cacheHint:u});var s,u;return Object.assign(Object.assign({},n),{get:()=>function(t,e,n){const s=e[0].dims,u=e[1].dims,c=r.BroadcastUtil.calcShape(s,u,!0);if(!c)throw new Error("Can't use matmul on the given tensors");const p=(0,o.getCoordsDataType)(c.length),f=(0,o.getGlChannels)(),{activationFunction:d,applyActivation:h}=(0,a.getActivationSnippet)(n),g=e.length>2,b=g?"value += getBiasForMatmul();":"",m=g?`${l(p,f,e[2].dims,c,!1)}`:"",y=c.length,_=s.length,v=u.length,w=`\n    ${d}\n    ${m}\n    float process(int indices[${y}]) {\n        int a[${_}];\n        int b[${v}];\n        bcastMatmulIndices_A(indices, a);\n        bcastMatmulIndices_B(indices, b);\n\n        float value;\n        for (int k=0; k<${s[s.length-1]}; ++k) {\n            a[${_-1}] = k;\n            b[${v-2}] = k;\n            value += _A(a) * _B(b);\n        }\n        ${b}\n        ${h}\n        return value;\n    }`;return Object.assign(Object.assign({},t),{output:{dims:c,type:e[0].type,textureType:i.TextureType.unpacked},shaderSource:w})}(n,t,e)})}e.matMul=(t,e,n)=>(c(e),t.session.pack?[t.run((0,s.createPackedMatmulProgramInfoLoader)(t,e,n),e)]:[t.run(u(e,n),e)]),e.parseMatMulAttributes=t=>(0,a.parseInternalActivationAttributes)(t.attributes),e.createMatmulProgramInfoLoader=u;const c=t=>{if(!t||2!==t.length)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.");if("float32"!==t[0].type&&"float64"!==t[0].type||"float32"!==t[1].type&&"float64"!==t[1].type)throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")};function l(t,e,n,i,o){let a="";const s=n.length,u=i.length,c=u-s;a=u<2&&s>0?"coords":n.map(((t,n)=>`coords.${e[n+c]}`)).join(", ");const l=r.BroadcastUtil.getBroadcastDims(n,i).map((t=>`coords.${e[t+c]} = 0;`)).join("\n");let p="vec4(outputValue.xx, outputValue.yy)";return 1===r.ShapeUtil.size(n)&&(p="vec4(outputValue.x)"),o?`\nvec4 getBiasForMatmul() {\n  ${t} coords = getOutputCoords();\n  ${l}\n  vec4 outputValue = getBias(${a});\n  return ${p};\n}`:`\nfloat getBiasForMatmul() {\n  ${t} coords = getOutputCoords();\n  ${l}\n  return getBias(coords.x);\n}`}e.getBiasForMatmul=l},2403:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(9390),a=n(2827),s={name:"pack",inputNames:["A"],inputTypes:[i.TextureType.unpackedReversed]};e.createPackProgramInfoLoader=(t,e)=>Object.assign(Object.assign({},s),{get:()=>((t,e)=>{const n=(0,r.getGlsl)(t.session.backend.glContext.version),u=e.dims,c=u.length,l=e.dims.length,p=(0,o.getCoordsDataType)(l),f=(0,a.getChannels)("rc",l),d=(h=l,g=f,b=u[u.length-2],m=u[u.length-1],0===h||1===h?"":`\n    int r = ${g[h-2]};\n    int c = ${g[h-1]};\n    int rp1 = ${g[h-2]} + 1;\n    int cp1 = ${g[h-1]} + 1;\n    bool rEdge = rp1 >= ${m};\n    bool cEdge = cp1 >= ${b};\n    `);var h,g,b,m;let y;y=0===c?[1,1]:1===c?[u[0],1]:[u[l-1],u[l-2]];const _=function(t,e,n){if(0===t)return"false";if(1===t)return`rc > ${e[0]}`;let r="";for(let i=t-2;i<t;i++)r+=`${n[i]} >= ${e[i-t+2]}`,i<t-1&&(r+="||");return r}(l,y,f),v=function(t,e){const n=t.length;if(0===n)return"getA(), 0, 0, 0";if(1===n)return`getA(rc),\n            rc + 1 >= ${t[0]} ? 0. : getA(rc + 1),\n            0, 0`;let r="";if(n>2)for(let t=0;t<n-2;++t)r+=`${e[t]},`;return`getA(${r}r, c),\n          rEdge ? 0. : getA(${r}rp1, c),\n          cEdge ? 0. : getA(${r}r, cp1),\n          rEdge || cEdge ? 0. : getA(${r}rp1, cp1)`}(u,f),w=`\n        void main() {\n          ${p} rc = getOutputCoords();\n\n          if(${_}) {\n            ${n.output} = vec4(0);\n          } else {\n            ${d}\n\n            ${n.output} = vec4(${v});\n          }\n        }\n      `;return Object.assign(Object.assign({},s),{hasMain:!0,output:{dims:e.dims,type:e.type,textureType:i.TextureType.packed},shaderSource:w})})(t,e)})},2827:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.unpackFromChannel=e.getChannels=e.getVecChannels=void 0;const r=n(9390);function i(t,e){return(0,r.getGlChannels)(e).map((e=>`${t}.${e}`))}e.getVecChannels=i,e.getChannels=function(t,e){return 1===e?[t]:i(t,e)},e.unpackFromChannel=function(){return"\n    float getChannel(vec4 frag, int dim) {\n      int modCoord = imod(dim, 2);\n      return modCoord == 0 ? frag.r : frag.g;\n    }\n\n    float getChannel(vec4 frag, vec2 innerDims) {\n      vec2 modCoord = mod(innerDims, 2.);\n      return modCoord.x == 0. ?\n        (modCoord.y == 0. ? frag.r : frag.g) :\n        (modCoord.y == 0. ? frag.b : frag.a);\n    }\n  "}},2870:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parsePadAttributesV11=e.padV11=e.parsePadAttributesV2=e.padV2=void 0;const r=n(246),i=n(2517),o=n(5060),a=n(2039),s={name:"Pad",inputNames:["A"],inputTypes:[a.TextureType.unpacked]};e.padV2=(t,e,n)=>(l(e),[t.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>c(t,e[0],n)}),e)]),e.parsePadAttributesV2=t=>{const e=t.attributes.getString("mode","constant"),n=t.attributes.getFloat("value",0),i=t.attributes.getInts("pads");return(0,r.createAttributeWithCacheKey)({mode:e,value:n,pads:i})},e.padV11=(t,n,r)=>{p(n);const i=u(t,n,r);return(0,e.padV2)(t,[n[0]],i)},e.parsePadAttributesV11=t=>t.attributes.getString("mode","constant");const u=(t,e,n)=>{if(!t.session.isInitializer(e[1].dataId)||e.length>=3&&!t.session.isInitializer(e[2].dataId))throw new Error("dynamic pad attributes are not allowed");const i=Array.from(e[1].integerData),o=e.length>=3?e[2].floatData[0]:0;return(0,r.createAttributeWithCacheKey)({mode:n,pads:i,value:o})},c=(t,e,n)=>{const r=i.ShapeUtil.padShape(e.dims.slice(),n.pads),o=r.length,s=`\n      ${f(t,e,n)}\n      float process(int[${o}] indices) {\n          return padA(indices);\n      }`;return{name:"Pad",inputNames:["A"],inputTypes:[a.TextureType.unpacked],output:{dims:r,type:e.type,textureType:a.TextureType.unpacked},shaderSource:s}},l=t=>{if(!t||1!==t.length)throw new Error("Pad requires 1 input");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")},p=t=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Pad requires 2 or 3 inputs");if("int32"!==t[1].type)throw new Error("Invalid input type.");if(t.length>=3&&"string"===t[2].type)throw new Error("Invalid input type.")},f=(t,e,n)=>{const r=(0,o.getGlsl)(t.session.backend.glContext.version),[s,u]=t.calculateTextureWidthAndHeight(e.dims,a.TextureType.unpacked),c=i.ShapeUtil.computeStrides(e.dims);switch(n.mode){case"constant":return d(r,e.dims,c,s,u,n.pads,n.value);case"reflect":return h(r,e.dims,c,s,u,n.pads);case"edge":return g(r,e.dims,c,s,u,n.pads);default:throw new Error("Invalid mode")}},d=(t,e,n,r,i,o,a)=>{const s=e.length;let u="";for(let t=s-1;t>=0;--t)u+=`\n        k = m[${t}] - ${o[t]};\n        if (k < 0)  return constant;\n        if (k >= ${e[t]}) return constant;\n        offset += k * ${n[t]};\n        `;return`\n      float padA(int m[${s}]) {\n        const float constant = float(${a});\n        int offset = 0;\n        int k = 0;\n        ${u}\n        vec2 coords = offsetToCoords(offset, ${r}, ${i});\n        float value = getColorAsFloat(${t.texture2D}(A, coords));\n        return value;\n      }\n      `},h=(t,e,n,r,i,o)=>{const a=e.length;let s="";for(let t=a-1;t>=0;--t)s+=`\n        k = m[${t}] - ${o[t]};\n        if (k < 0) { k = -k; }\n        {\n          const int _2n_1 = ${2*(e[t]-1)};\n          k = int( mod( float(k), float(_2n_1) ) ) ;\n          if(k >= ${e[t]}) { k = _2n_1 - k; }\n        }\n        offset += k * ${n[t]};\n        `;return`\n      float padA(int m[${a}]) {\n        int offset = 0;\n        int k = 0;\n        ${s}\n        vec2 coords = offsetToCoords(offset, ${r}, ${i});\n        float value = getColorAsFloat(${t.texture2D}(A, coords));\n        return value;\n      }\n      `},g=(t,e,n,r,i,o)=>{const a=e.length;let s="";for(let t=a-1;t>=0;--t)s+=`\n        k = m[${t}] - ${o[t]};\n        if (k < 0)  k = 0;\n        if (k >= ${e[t]}) k = ${e[t]-1};\n        offset += k * ${n[t]};\n      `;return`\n      float padA(int m[${a}]) {\n        int offset = 0;\n        int k = 0;\n        ${s}\n        vec2 coords = offsetToCoords(offset, ${r}, ${i});\n        float value = getColorAsFloat(${t.texture2D}(A, coords));\n        return value;\n      }\n      `}},2143:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.globalMaxPool=e.parseMaxPoolAttributes=e.maxPool=e.parseGlobalAveragePoolAttributes=e.globalAveragePool=e.parseAveragePoolAttributes=e.averagePool=void 0;const r=n(246),i=n(2517),o=n(2039);e.averagePool=(t,e,n)=>{p(e);const r={name:"AveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[t.run(Object.assign(Object.assign({},r),{get:()=>a(e,r,!1,n)}),e)]},e.parseAveragePoolAttributes=t=>{const e=t.attributes.getString("auto_pad","NOTSET"),n=t.attributes.getInt("ceil_mode",0),i=0!==t.attributes.getInt("count_include_pad",0),o=t.attributes.getInts("kernel_shape"),a=t.attributes.getInts("strides",[]),s=t.attributes.getInts("pads",[]);if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,r.createAttributeWithCacheKey)({autoPad:e,ceilMode:n,countIncludePad:i,kernelShape:o,strides:a,pads:s})};const a=(t,e,n,r)=>{const[a,s]=u(t,r,n),c=i.ShapeUtil.size(a.kernelShape);let l="";a.countIncludePad?l+=`value /= float(${c});`:l+=`value /= float(${c} - pad);`;const p=`\n        ${f(t[0].dims,a,"value += _X(x);",l,"0.0")}\n      `;return Object.assign(Object.assign({},e),{output:{dims:s,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:p})};e.globalAveragePool=(t,e,n)=>{p(e);const r={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:`${n.countIncludePad}`};return[t.run(Object.assign(Object.assign({},r),{get:()=>a(e,r,!0,n)}),e)]},e.parseGlobalAveragePoolAttributes=t=>{const e=0!==t.attributes.getInt("count_include_pad",0);return(0,r.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:e,kernelShape:[],strides:[],pads:[]})},e.maxPool=(t,e,n)=>{p(e);const r={name:"MaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[t.run(Object.assign(Object.assign({},r),{get:()=>s(e,r,!1,n)}),e)]},e.parseMaxPoolAttributes=t=>{const e=t.attributes.getString("auto_pad","NOTSET"),n=t.attributes.getInt("ceil_mode",0),i=t.attributes.getInts("kernel_shape"),o=t.attributes.getInts("strides",[]),a=t.attributes.getInts("pads",[]),s=t.attributes.getInt("storage_order",0),u=t.attributes.getInts("dilations",[]);if(0!==s)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,r.createAttributeWithCacheKey)({autoPad:e,ceilMode:n,countIncludePad:!1,kernelShape:i,strides:o,pads:a,storageOrder:s,dilations:u})};const s=(t,e,n,r)=>{const[i,a]=u(t,r,n),s=`\n      ${f(t[0].dims,i,"\n      value = max(_X(x), value);\n    ","","-1e5")}\n    `;return Object.assign(Object.assign({},e),{output:{dims:a,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:s})},u=(t,e,n)=>{const r=t[0].dims.slice(),o=Object.hasOwnProperty.call(e,"dilations"),a=e.kernelShape.slice(),s=e.strides.slice(),u=o?e.dilations.slice():[],c=e.pads.slice();i.PoolConvUtil.adjustPoolAttributes(n,r,a,s,u,c);const l=i.PoolConvUtil.computePoolOutputShape(n,r,s,u,a,c,e.autoPad),p=Object.assign({},e);return o?Object.assign(p,{kernelShape:a,strides:s,pads:c,dilations:u,cacheKey:e.cacheKey}):Object.assign(p,{kernelShape:a,strides:s,pads:c,cacheKey:e.cacheKey}),[p,l]},c={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},l={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};e.globalMaxPool=(t,e)=>(p(e),[t.run(Object.assign(Object.assign({},l),{get:()=>s(e,l,!0,c)}),e)]);const p=t=>{if(!t||1!==t.length)throw new Error("Pool ops requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")},f=(t,e,n,r,o)=>{const a=t.length;if(e.kernelShape.length<=2){const i=e.kernelShape[e.kernelShape.length-1],s=e.strides[e.strides.length-1],u=e.pads[e.pads.length/2-1],c=e.pads[e.pads.length-1],l=t[a-1];let p="",f="",d="";if(p=u+c!==0?`\n          for (int i = 0; i < ${i}; i++) {\n            x[${a} - 1] = indices[${a} - 1] * ${s} - ${u} + i;\n            if (x[${a} - 1] < 0 || x[${a} - 1] >= ${l}) {\n              pad++;\n              continue;\n            }\n            ${n}\n          }`:`\n          for (int i = 0; i < ${i}; i++) {\n            x[${a} - 1] = indices[${a} - 1] * ${s} - ${u} + i;\n            ${n}\n          }`,2===e.kernelShape.length){const n=e.kernelShape[e.kernelShape.length-2],r=e.strides[e.strides.length-2],o=e.pads[e.pads.length/2-2],s=e.pads[e.pads.length-2],u=t[a-2];f=o+s!==0?`\n            for (int j = 0; j < ${n}; j++) {\n              x[${a} - 2] = indices[${a} - 2] * ${r} - ${o} + j;\n              if (x[${a} - 2] < 0 || x[${a} - 2] >= ${u}) {\n                pad+= ${i};\n                continue;\n              }\n          `:`\n            for (int j = 0; j < ${n}; j++) {\n              x[${a} - 2] = indices[${a} - 2] * ${r} - ${o} + j;\n            `,d="\n          }\n        "}return`\n        float process(int indices[${a}]) {\n          int x[${a}];\n          copyVec(indices, x);\n\n          float value = ${o};\n          int pad = 0;\n          ${f}\n          ${p}\n          ${d}\n          ${r}\n          return value;\n        }\n      `}{const s=i.ShapeUtil.size(e.kernelShape),u=i.ShapeUtil.computeStrides(e.kernelShape),c=u.length,l=e.pads.length,p=h(c),f=d(t,"inputDims"),g=d(e.pads,"pads"),b=d(u,"kernelStrides"),m=d(e.strides,"strides");let y="";return y=e.pads.reduce(((t,e)=>t+e))?`\n            if (x[j] >= inputDims[j] || x[j] < 0) {\n              pad++;\n              isPad = true;\n              break;\n            }\n          }\n          if (!isPad) {\n            ${n}\n          }`:`\n          }\n          ${n}\n        `,`\n        ${p}\n        float process(int indices[${a}]) {\n          int x[${a}];\n          copyVec(indices, x);\n          int offset[${c}];\n          int pads[${l}];\n          int inputDims[${a}];\n          int kernelStrides[${c}];\n          int strides[${c}];\n          ${g}\n          ${f}\n          ${m}\n          ${b}\n\n          float value = ${o};\n          int pad = 0;\n          bool isPad = false;\n          for (int i = 0; i < ${s}; i++) {\n            offsetToIndices(i, kernelStrides, offset);\n            isPad = false;\n            for (int j = ${a} - ${c}; j < ${a}; j++) {\n              x[j] = indices[j] * strides[j - ${a} + ${c}]\n                + offset[j - ${a} + ${c}] - pads[j - 2];\n              ${y}\n          }\n          ${r}\n\n          return value;\n        }\n      `}},d=(t,e)=>{let n="";for(let r=0;r<t.length;r++)n+=`\n      ${e}[${r}] = ${t[r]};\n    `;return n},h=t=>`\n  void offsetToIndices(int offset, int[${t}] strides, out int[${t}] indices) {\n    if (${t} == 0) {\n      return;\n    }\n    for (int i = 0; i < ${t} - 1; ++i) {\n      indices[i] = offset / strides[i];\n      offset -= indices[i] * strides[i];\n    }\n    indices[${t} - 1] = offset;\n  }`},4939:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.reduceLogSumSquare=e.reduceLogSum=e.reduceProd=e.reduceMin=e.reduceMax=e.reduceMean=e.reduceSum=e.parseReduceAttributes=void 0;const r=n(246),i=n(782),o=n(2517),a=n(2039),s=(t,e,n,r,i)=>{c(e);const o={name:r,inputNames:["A"],inputTypes:[a.TextureType.unpacked]};return[t.run(Object.assign(Object.assign({},o),{cacheHint:n.cacheKey,get:()=>u(t,e,n,r,i,o)}),e)]};e.parseReduceAttributes=t=>{const e=t.attributes.getInts("axes",[]),n=1===t.attributes.getInt("keepdims",1);return(0,r.createAttributeWithCacheKey)({axes:e,keepDims:n})};const u=(t,e,n,r,i,s)=>{const u=[],c=e[0].dims.length||1,l=[],p=o.ShapeUtil.normalizeAxes(n.axes,e[0].dims.length),f=i(e,p);let d=f[1];for(let t=0;t<e[0].dims.length;t++)p.indexOf(t)>=0||0===p.length?(n.keepDims&&u.push(1),d=`\n          for(int j${t} = 0; j${t} < ${e[0].dims[t]}; j${t}++) {\n            inputIdx[${t}] = j${t};\n            ${d}\n          }`):(l.push(`inputIdx[${t}] = outputIdx[${u.length}];`),u.push(e[0].dims[t]));const h=`\n      float process(int outputIdx[${u.length||1}]) {\n        float value;                 // final result\n        int inputIdx[${c}];      // addressing input data\n        ${l.join("\n")}\n        ${f[0]}       // init ops for reduce max/min\n        ${d}\n        ${f[2]}       // final computation for reduce mean\n        return value;\n      }`;return Object.assign(Object.assign({},s),{output:{dims:u,type:e[0].type,textureType:a.TextureType.unpacked},shaderSource:h})},c=t=>{if(!t||1!==t.length)throw new Error("Reduce op requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.")};e.reduceSum=(t,e,n)=>s(t,e,n,"ReduceSum",(()=>["value = 0.0;","value += _A(inputIdx);",""])),e.reduceMean=(t,e,n)=>s(t,e,n,"ReduceMean",((t,e)=>{let n=1;for(let r=0;r<t[0].dims.length;r++)(e.indexOf(r)>=0||0===e.length)&&(n*=t[0].dims[r]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${n}.;`]})),e.reduceMax=(t,e,n)=>s(t,e,n,"ReduceMax",((t,e)=>{const n=[];for(let r=0;r<t[0].dims.length;r++)(e.indexOf(r)>=0||0===e.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]})),e.reduceMin=(t,e,n)=>s(t,e,n,"ReduceMin",((t,e)=>{const n=[];for(let r=0;r<t[0].dims.length;r++)(e.indexOf(r)>=0||0===e.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]})),e.reduceProd=(t,e,n)=>s(t,e,n,"ReduceProd",(()=>["value = 1.0;","value *= _A(inputIdx);",""])),e.reduceLogSum=(t,e,n)=>s(t,e,n,"ReduceLogSum",(()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"])),e.reduceLogSumSquare=(t,e,n)=>s(t,e,n,"ReduceLogSumSquare",(()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""]))},7019:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isReshapeCheap=e.processDims3D=e.createPackedReshape3DProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),a=n(2827);e.createPackedReshape3DProgramInfoLoader=(t,e,n)=>{const s=(t=>({name:"Reshape (packed)",inputTypes:[o.TextureType.packed],inputNames:["A"],cacheHint:`${t}`}))(n);return Object.assign(Object.assign({},s),{get:()=>((t,e,n,s)=>{const u=e.dims,c=s;let l="";for(let t=0;t<4;t++){let e="";switch(t){case 0:e="outputCoords = rc;";break;case 1:e="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:e="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:e="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}l+=`\n        ${e}\n        ${t>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""}\n          int flattenedIndex = getFlattenedIndex(outputCoords);\n\n          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);\n          vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n          result[${t}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);\n\n        ${t>0?"}":""}\n      `}const p=(0,i.getGlsl)(t.session.backend.glContext.version),f=`\n      ${function(t){const e=r.ShapeUtil.computeStrides(t),n=["b","r","c"],i="index";return`\n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\n      ${e.map(((t,r)=>`int ${n[r]} = ${i} / ${t}; ${r===e.length-1?`int ${n[r+1]} = ${i} - ${n[r]} * ${t}`:`index -= ${n[r]} * ${t}`};`)).join("")}\n      return ivec3(b, r, c);\n    }\n  `}(u)}\n      ${function(t){const e=r.ShapeUtil.computeStrides(t);return`\n  int getFlattenedIndex(ivec3 coords) {\n    // reverse y, z order\n    return coords.x * ${e[0]} + coords.z * ${e[1]} + coords.y;\n  }\n`}(c)}\n      ${(0,a.unpackFromChannel)()}\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n\n        vec4 result = vec4(0.0);\n\n        ivec3 outputCoords;\n        int rows = ${c[2]};\n        int cols = ${c[1]};\n\n        ${l}\n        ${p.output} = result;\n      }\n    `;return Object.assign(Object.assign({},n),{output:{dims:c,type:e.type,textureType:o.TextureType.packed},shaderSource:f,hasMain:!0})})(t,e,s,n)})},e.processDims3D=function(t){if(0===t.length)return[1,1,1];let e=1;for(let n=0;n<t.length-2;++n)e*=t[n];return[e,t.length>1?t[t.length-2]:1,t[t.length-1]]},e.isReshapeCheap=function(t,e){let n=!1;return n=0===t.length||0===e.length||(t.length<2||e.length<2?t[t.length-1]===e[e.length-1]:t[t.length-1]===e[e.length-1]&&t[t.length-2]===e[e.length-2]),n}},718:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.reshape=void 0;const r=n(2517);e.reshape=(t,e)=>{const n=r.ShapeUtil.calculateReshapedDims(e[0].dims,e[1].integerData);return t.session.pack?[t.reshapePacked(e[0],n)]:[t.reshapeUnpacked(e[0],n)]}},2268:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseResizeAttributesV11=e.parseResizeAttributesV10=e.resize=void 0;const r=n(5060),i=n(2039),o=n(9390),a=n(2827),s=n(9793),u={name:"Resize",inputNames:["A"],inputTypes:[i.TextureType.packed]};e.resize=(t,e,n)=>((0,s.validateInputs)(e,n),[t.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>c(t,e,n)}),e)]),e.parseResizeAttributesV10=t=>(0,s.parseUpsampleAttributes)(t,10),e.parseResizeAttributesV11=t=>(0,s.parseUpsampleAttributes)(t,11);const c=(t,e,n)=>{const s=(0,r.getGlsl)(t.session.backend.glContext.version),[c,p]=l(e,n);if(c.every((t=>1===t))&&"tf_crop_and_resize"!==n.coordinateTransformMode)return Object.assign(Object.assign({},u),{output:{dims:p,type:e[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:`void main() {\n                    vec4 v = ${s.texture2D}(X, TexCoords);\n                    ${s.output} = v;\n                }`});const f=p.length;if(f<2)throw new Error(`output dimension should be at least 2, but got ${f}`);const d=p[f-2],h=p[f-1],g=e[0].dims;if(f!==g.length)throw new Error(`output dimension should match input ${g.length}, but got ${f}`);const b=g[f-2],m=g[f-1],y=c[f-2],_=c[f-1];let v="";if("linear"!==n.mode)throw new Error(`resize (packed) does not support mode: '${n.mode}'`);switch(n.coordinateTransformMode){case"asymmetric":v="\n                    vec4 getSourceFracIndex(ivec4 coords) {\n                        return vec4(coords) / scaleWHWH;\n                    }\n                ";break;case"half_pixel":v="\n                    vec4 getSourceFracIndex(ivec4 coords) {\n                        return (vec4(coords) + 0.5) / scaleWHWH - 0.5;\n                    }\n                ";break;case"pytorch_half_pixel":v=`\n                    vec4 getSourceFracIndex(ivec4 coords) {\n                        vec4 fcoords = vec4(coords);\n                        return vec4(\n                            ${h}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,\n                            ${d}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,\n                            ${h}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,\n                            ${d}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0\n                          );\n                    }\n                `;break;case"align_corners":v=`\n                    vec4 getSourceFracIndex(ivec4 coords) {\n                        vec4 resized = vec4(${h}.0 - 1.0, ${d}.0 - 1.0, ${h}.0 - 1.0,\n                            ${d}.0 - 1.0);\n                        vec4 original = vec4(${m}.0 - 1.0, ${b}.0 - 1.0, ${m}.0 - 1.0,\n                            ${b}.0 - 1.0);\n                        vec4 new_scale = original / resized;\n                        return vec4(coords) * new_scale;\n                    }\n                `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode:                                 '${n.coordinateTransformMode}'`)}const w=(0,o.getCoordsDataType)(f),x=`\n            const vec2 inputWH = vec2(${b}.0, ${m}.0);\n            const vec4 scaleWHWH = vec4(float(${y}), float(${_}), float(${y}), float(${_}));\n            ${(0,a.unpackFromChannel)()}\n            ${v}\n            float getAValue(int x10, int r, int c, int d) {\n                return getChannel(getA(x10, r, c, d), vec2(c, d));\n            }\n            void main() {\n                ${w} rc = getOutputCoords();\n\n                int batch = rc[0];\n                int depth = rc[1];\n\n                // retrieve the 4 coordinates that is used in the 4 packed output values.\n                ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);\n\n                // calculate the source index in fraction\n                vec4 sourceFrac = getSourceFracIndex(coords);\n\n                // get the lower and upper bound of the 4 values that will be packed into one texel.\n                ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));\n                ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));\n                ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));\n                ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));\n\n                bool hasNextRow = rc.w < ${d-1};\n                bool hasNextCol = rc.z < ${h-1};\n\n                // pack x00, x01, x10, x11's top-left corner into one vec4 structure\n                vec4 topLeft = vec4(\n                    getAValue(batch, depth, x00.x, x00.y),\n                    hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,\n                    hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,\n                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);\n\n                // pack x00, x01, x10, x11's top-right corner into one vec4 structure\n                vec4 topRight = vec4(\n                    getAValue(batch, depth, x00.x, x00.w),\n                    hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,\n                    hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,\n                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);\n\n                // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure\n                vec4 bottomLeft = vec4(\n                    getAValue(batch, depth, x00.z, x00.y),\n                    hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,\n                    hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,\n                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);\n\n                // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure\n                vec4 bottomRight = vec4(\n                    getAValue(batch, depth, x00.z, x00.w),\n                    hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,\n                    hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,\n                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);\n\n                // calculate the interpolation fraction on u and v direction\n                vec4 frac = vec4(sourceFrac) - floor(sourceFrac);\n                vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));\n\n                vec4 top = mix(topLeft, topRight, clampFrac.ywyw);\n                vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);\n                vec4 newValue = mix(top, bottom, clampFrac.xxzz);\n\n                ${s.output} = vec4(newValue);\n            }\n        `;return Object.assign(Object.assign({},u),{output:{dims:p,type:e[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:x})},l=(t,e)=>{const n=t[0].dims;let r,i=e.scales;if(0===i.length){const o=t[e.scalesInputIdx];if(o&&0!==o.size){if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");i=p(o,e.mode,e.isResize)}else{const o=t[e.sizesInputIdx];if(!o||0===o.size)throw new Error("Either scales or sizes MUST be provided as input.");r=Array.from(o.integerData),i=f(r,n,e.mode,e.isResize)}}else if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const o=r||n.map(((t,e)=>Math.floor(t*i[e])));return[i,o]},p=(t,e,n)=>{const r=Array.from(t.floatData);return(0,s.scalesValidation)(r,e,n),r},f=(t,e,n,r)=>{const i=e.length,o=new Array(i);for(let n=0,r=i;n<r;n++)if(0===e[n]){if(0!==t[n])throw new Error("Input dim is zero but required output dim is non-zero.");o[n]=1}else o[n]=t[n]/e[n];return(0,s.scalesValidation)(o,n,r),o}},8117:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.shape=void 0;const r=n(9162);e.shape=(t,e)=>(i(e),[new r.Tensor([e[0].dims.length],"int32",void 0,void 0,new Int32Array(e[0].dims))]);const i=t=>{if(!t||1!==t.length)throw new Error("Shape requires 1 input.")}},2278:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.sliceV10=e.parseSliceAttributes=e.slice=void 0;const r=n(246),i=n(782),o=n(2517),a=n(2039),s={name:"Slice",inputNames:["A"],inputTypes:[a.TextureType.unpacked]};e.slice=(t,e,n)=>(c(e),[t.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>u(t,e[0],n)}),e)]),e.parseSliceAttributes=t=>{const e=t.attributes.getInts("starts"),n=t.attributes.getInts("ends"),i=t.attributes.getInts("axes",[]);return(0,r.createAttributeWithCacheKey)({starts:e,ends:n,axes:i})};const u=(t,e,n)=>{const r=0===n.axes.length?e.dims.slice(0).map(((t,e)=>e)):n.axes,i=o.ShapeUtil.normalizeAxes(r,e.dims.length),u=n.starts.map(((t,n)=>t>e.dims[i[n]]-1?e.dims[i[n]]:o.ShapeUtil.normalizeAxis(t,e.dims[i[n]]))),c=n.ends.map(((t,n)=>t>e.dims[i[n]]-1?e.dims[i[n]]:o.ShapeUtil.normalizeAxis(t,e.dims[i[n]]))),l=e.dims.slice(),p=[];for(let t=0;t<i.length;t++)l[i[t]]=c[t]-u[t],u[t]>0&&p.push(`outputIdx[${i[t]}] += ${u[t]};`);const f=`\n      float process(int outputIdx[${l.length}]) {\n        ${p.join("\n      ")}\n        return _A(outputIdx);\n      }`;return Object.assign(Object.assign({},s),{output:{dims:l,type:e.type,textureType:a.TextureType.unpacked},shaderSource:f})},c=t=>{if(!t||1!==t.length)throw new Error("Slice requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.")};e.sliceV10=(t,e)=>{p(e);const n=l(t,e);return[t.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>u(t,e[0],n)}),[e[0]])]};const l=(t,e)=>{if(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)||e.length>=4&&!t.session.isInitializer(e[3].dataId)||e.length>=5&&!t.session.isInitializer(e[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(e.length>=5&&e[4].integerData.some((t=>1!==t)))throw new Error("currently non-1 steps is not supported for Slice");const n=Array.from(e[1].integerData),r=Array.from(e[2].integerData),i=e.length>=4?Array.from(e[3].integerData):[];return{starts:n,ends:r,axes:i,cacheKey:`${i};${n};${r}`}},p=t=>{if(!t||t.length<3||t.length>5)throw new Error("Invalid input number.");if("int32"!==t[1].type||1!==t[1].dims.length)throw new Error("Invalid input type.");if("int32"!==t[2].type||1!==t[2].dims.length)throw new Error("Invalid input type.");if(t.length>=4&&("int32"!==t[3].type||1!==t[3].dims.length))throw new Error("Invalid input type.");if(t.length>=5&&("int32"!==t[4].type||1!==t[4].dims.length))throw new Error("Invalid input type.")}},5524:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.softmaxV13=e.parseSoftmaxAttributesV13=e.parseSoftmaxAttributes=e.softmax=void 0;const r=n(246),i=n(2517),o=n(5060),a=n(2039),s=n(3738),u={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[a.TextureType.unpacked]},c={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked]},l={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked,a.TextureType.unpacked]};e.softmax=(t,e,n)=>{g(e);const r=e[0].dims.slice(),o=i.ShapeUtil.normalizeAxis(n.axis,r.length),a=i.ShapeUtil.sizeToDimension(r,o),s=i.ShapeUtil.sizeFromDimension(r,o);return p(t,e,n,a,s)},e.parseSoftmaxAttributes=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",1)}),e.parseSoftmaxAttributesV13=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",-1)}),e.softmaxV13=(t,e,n)=>{g(e);const o=e[0].dims.slice(),a=i.ShapeUtil.normalizeAxis(n.axis,o.length),u=o.length,c=a!==u-1,l=[];let f,d=[],h=[];c&&(d=Array.from({length:u}).map(((t,e)=>e)),d[a]=u-1,d[u-1]=a,d.map((t=>l.push(o[t]))),f=(0,r.createAttributeWithCacheKey)({perm:d}),h=(0,s.transpose)(t,e,f));const b=c?i.ShapeUtil.sizeToDimension(l,u-1):i.ShapeUtil.sizeToDimension(o,u-1),m=c?i.ShapeUtil.sizeFromDimension(l,u-1):i.ShapeUtil.sizeFromDimension(o,u-1),y=p(t,c?h:e,n,b,m);return c?(0,s.transpose)(t,y,f):y};const p=(t,e,n,r,i)=>{const o=f(t,e[0],r,i,[r]),a=t.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>o}),e),s=d(t,e[0],r,i,o.output.dims,[r]),p=t.run(Object.assign(Object.assign({},c),{cacheHint:n.cacheKey,get:()=>s}),[e[0],a]),g=h(t,e[0],r,i,o.output.dims,s.output.dims);return[t.run(Object.assign(Object.assign({},l),{cacheHint:n.cacheKey,get:()=>g}),[e[0],a,p])]},f=(t,e,n,r,i)=>{const[s,c]=t.calculateTextureWidthAndHeight(e.dims,a.TextureType.unpacked),l=i.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length)throw new Error("Dimensionality of the output should be 1");if(i[0]!==n)throw new Error("Shape of the output should be equal to logical row count");const p=(0,o.getGlsl)(t.session.backend.glContext.version),f=`\n      float process(int[${l}] indices) {\n        int logical_row_start_offset = indices[0] * ${r};\n\n        float max = getColorAsFloat(${p.texture2D}(A, offsetToCoords(logical_row_start_offset, ${s},\n        ${c} )));\n        for(int i=1; i<${r}; ++i)\n        {\n          float current = getColorAsFloat(${p.texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n            ${s}, ${c})));\n          if(current > max)\n          max = current;\n        }\n\n        return max;\n      }`;return Object.assign(Object.assign({},u),{output:{dims:i,type:e.type,textureType:a.TextureType.unpacked},shaderSource:f})},d=(t,e,n,r,i,s)=>{const[u,l]=t.calculateTextureWidthAndHeight(e.dims,a.TextureType.unpacked),p=s.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==s.length)throw new Error("Dimensionality of the output should be 1");if(s[0]!==n)throw new Error("Shape of the output should be equal to logical row count");if(1!==i.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const f=`\n      float process(int[${p}] indices) {\n        int logical_row_start_offset = indices[0] * ${r};\n\n        float norm_factor = 0.0;\n        float max = _Max(indices);\n        for(int i=0; i<${r}; ++i)\n        {\n          norm_factor += exp(getColorAsFloat(${(0,o.getGlsl)(t.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n            ${u}, ${l}))) - max);\n        }\n\n        return norm_factor;\n      }`;return Object.assign(Object.assign({},c),{output:{dims:s,type:e.type,textureType:a.TextureType.unpacked},shaderSource:f})},h=(t,e,n,r,i,o)=>{const[s,u]=t.calculateTextureWidthAndHeight(e.dims,a.TextureType.unpacked),c=e.dims.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length||1!==o.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n||o[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const p=`\n      float process(int[${c}] indices) {\n\n      // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)\n      int offset = coordsToOffset(TexCoords, ${s}, ${u});\n\n      //determine the logical row for this index\n      int logical_row_index[1];\n      logical_row_index[0] = offset / ${r};\n\n      float norm_factor = _Norm(logical_row_index);\n\n      // avoid possible division by 0\n      // if norm_facor is 0, all elements are zero\n      // if so, return 0\n      if(norm_factor == 0.0)\n        return 0.0;\n\n      return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;\n    }`;return Object.assign(Object.assign({},l),{output:{dims:e.dims,type:e.type,textureType:a.TextureType.unpacked},shaderSource:p})},g=t=>{if(!t||1!==t.length)throw new Error("Softmax requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type")}},5975:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseSplitAttributes=e.split=void 0;const r=n(246),i=n(2517),o=n(2039),a={name:"Split",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};e.split=(t,e,n)=>{c(e);const r=i.ShapeUtil.normalizeAxis(n.axis,e[0].dims.length),o=s(t,e,r,n),l=[];for(let i=0;i<o;++i)l.push(t.run(Object.assign(Object.assign({},a),{cacheHint:`${n.cacheKey};${i}`,get:()=>u(t,e[0],n,r,i)}),e));return l},e.parseSplitAttributes=t=>{const e=t.attributes.getInt("axis",0),n=t.attributes.getInts("split",[]),i=t.outputs.length;return(0,r.createAttributeWithCacheKey)({axis:e,split:n,numOutputs:i})};const s=(t,e,n,r)=>{const[,o]=i.SplitUtil.splitShape(e[0].dims,n,r.split,r.numOutputs);return o.length},u=(t,e,n,r,s)=>{const[u,c]=i.SplitUtil.splitShape(e.dims,r,n.split,n.numOutputs),l=c[s],p=u[s],f=`\n      float process(int indices[${p.length}]) {\n        indices[${r}] += ${l};\n        return _A(indices);\n      }\n    `;return Object.assign(Object.assign({},a),{cacheHint:`${n.cacheKey}:${s}`,output:{dims:p,type:e.type,textureType:o.TextureType.unpacked},shaderSource:f})},c=t=>{if(!t||1!==t.length)throw new Error("Split requires one input.");if("int8"!==t[0].type&&"uint8"!==t[0].type&&"int16"!==t[0].type&&"uint16"!==t[0].type&&"int32"!==t[0].type&&"uint32"!==t[0].type&&"float32"!==t[0].type&&"float64"!==t[0].type&&"bool"!==t[0].type)throw new Error("Invalid input type.")}},3933:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseSqueezeAttributes=e.squeezeV13=e.squeeze=void 0;const r=n(2517);e.squeeze=(t,e,n)=>{i(e);const o=r.ShapeUtil.squeezeShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.squeezeV13=(t,n)=>(o(n),(0,e.squeeze)(t,[n[0]],Array.from(n[1].integerData))),e.parseSqueezeAttributes=t=>t.attributes.getInts("axes");const i=t=>{if(!t||1!==t.length)throw new Error("Squeeze requires 1 input.");if("string"===t[0].type)throw new Error("invalid input tensor types.")},o=t=>{if(!t||2!==t.length)throw new Error("Squeeze requires 2 inputs.");if("int32"!==t[1].type)throw new Error("Invalid input type.")}},6558:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.sum=void 0;const r=n(5060),i=n(2039);e.sum=(t,e)=>{a(e);const n={name:"Sum",inputNames:e.map(((t,e)=>`X${e}`)),inputTypes:new Array(e.length).fill(i.TextureType.unpacked)};return[t.run(Object.assign(Object.assign({},n),{get:()=>o(t,e,n)}),e)]};const o=(t,e,n)=>{const o=(0,r.getGlsl)(t.session.backend.glContext.version),a=e[0].dims.slice(),s=`\n      void main() {\n        vec4 result = ${e.map(((t,e)=>`${o.texture2D}(X${e},TexCoords)`)).join(" + ")};\n        ${o.output} = result;\n      }\n    `;return Object.assign(Object.assign({},n),{output:{dims:a,type:e[0].type,textureType:i.TextureType.unpacked},hasMain:!0,shaderSource:s})},a=t=>{if(!t||0===t.length)throw new Error("Sum requires inputs.");const e=t[0].dims.length;for(let n=1;n<t.length;n++){if(e!==t[n].dims.length)throw new Error("Input shapes are mismatched.");for(let r=0;r<e;r++)if(t[0].dims[r]!==t[n].dims[r])throw new Error("Input shapes are not matched.")}if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.");for(let e=1;e<t.length;e++)if(t[0].type!==t[e].type)throw new Error("Input types are not matched.")}},5723:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.tile=void 0;const r=n(782),i=n(2039);e.tile=(t,e)=>{a(e);const n={name:"Tile",inputNames:["A"],inputTypes:[i.TextureType.unpacked]};return[t.run(Object.assign(Object.assign({},n),{get:()=>o(t,e,n)}),e)]};const o=(t,e,n)=>{const r=e[0].dims.slice(),o=new Array(r.length),a=[];for(let t=0;t<r.length;t++)o[t]=r[t]*e[1].numberData[t],a.push(`inputIdx[${t}] = int(mod(float(outputIdx[${t}]), ${r[t]}.));`);const s=o.length,u=`\n      float process(int outputIdx[${s}]) {\n        int inputIdx[${s}];\n        ${a.join("\n")}\n        return _A(inputIdx);\n      }\n    `;return Object.assign(Object.assign({},n),{output:{dims:o,type:e[0].type,textureType:i.TextureType.unpacked},shaderSource:u})},a=t=>{if(!t||2!==t.length)throw new Error("Tile requires 2 input.");if(1!==t[1].dims.length)throw new Error("The second input shape must 1 dimension.");if(t[1].dims[0]!==t[0].dims.length)throw new Error("Invalid input shape.");if(-1===r.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.");if("int32"!==t[1].type&&"int16"!==t[1].type)throw new Error("Invalid repeat type.")}},3738:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseTransposeAttributes=e.transpose=void 0;const r=n(246),i=n(2517),o=n(2039),a={name:"Transpose",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};e.transpose=(t,e,n)=>(p(e),[t.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>s(t,e[0],n.perm)}),e)]),e.parseTransposeAttributes=t=>(0,r.createAttributeWithCacheKey)({perm:t.attributes.getInts("perm",[])});const s=(t,e,n)=>{const r=e.dims;n=u(r,n);const i=c(r,n),s=r.length,p=`\n      ${l("perm",n,s)}\n      float process(int indices[${s}]) {\n        int a[${s}];\n        perm(a, indices);\n        return _A(a);\n      }`;return Object.assign(Object.assign({},a),{output:{dims:i,type:e.type,textureType:o.TextureType.unpacked},shaderSource:p})},u=(t,e)=>(e&&e.length!==t.length&&(e=[...t.keys()].reverse()),e),c=(t,e)=>(e=u(t,e),i.ShapeUtil.sortBasedOnPerm(t,e)),l=(t,e,n)=>{const r=[];r.push(`void ${t}(out int a[${n}], int src[${n}]) {`);for(let t=0;t<n;++t)r.push(`\ta[${e[t]}]=src[${t}];`);return r.push("\t}"),r.join("\n")},p=t=>{if(!t||1!==t.length)throw new Error("Transpose requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("input should be float tensor")}},8710:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.encodeAsUint8=void 0;const r=n(5060),i=n(2039);e.encodeAsUint8=(t,e)=>{const n=e.shape,o=(0,r.getGlsl)(t.session.backend.glContext.version),a=`\n    const float FLOAT_MAX = 1.70141184e38;\n    const float FLOAT_MIN = 1.17549435e-38;\n\n    bool isNaN(float val) {\n      return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n    }\n\n    highp vec4 encodeAsUint8(highp float v) {\n      if (isNaN(v)) {\n        return vec4(255, 255, 255, 255);\n      }\n\n      highp float av = abs(v);\n\n      if(av < FLOAT_MIN) {\n        return vec4(0.0, 0.0, 0.0, 0.0);\n      } else if(v > FLOAT_MAX) {\n        return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n      } else if(v < -FLOAT_MAX) {\n        return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;\n      }\n\n      highp vec4 c = vec4(0,0,0,0);\n\n      highp float e = floor(log2(av));\n      highp float m = exp2(fract(log2(av))) - 1.0;\n\n      c[2] = floor(128.0 * m);\n      m -= c[2] / 128.0;\n      c[1] = floor(32768.0 * m);\n      m -= c[1] / 32768.0;\n      c[0] = floor(8388608.0 * m);\n\n      highp float ebias = e + 127.0;\n      c[3] = floor(ebias / 2.0);\n      ebias -= c[3] * 2.0;\n      c[2] += floor(ebias) * 128.0;\n\n      c[3] += 128.0 * step(0.0, -v);\n\n      return c / 255.0;\n    }\n\n    void main() {\n      float value = ${o.texture2D}(X,TexCoords).r;\n      ${o.output} = encodeAsUint8(value);\n    }`,s={name:"Uint8Encode",inputTypes:[i.TextureType.unpacked],inputNames:["X"],output:{dims:n,type:e.tensor.type,textureType:i.TextureType.downloadUint8AsFloat},shaderSource:a,hasMain:!0};return t.executeProgram(s,[e.tensor])}},4909:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.tanh=e.tan=e.sqrt=e.sin=e.sigmoid=e.relu=e.not=e.neg=e.log=e.parseLeakyReluAttributes=e.leakyRelu=e.identity=e.floor=e.exp=e.parseEluAttributes=e.elu=e.cos=e.ceil=e.clipV11=e.parseClipAttributes=e.clip=e.atan=e.asin=e.acos=e.abs=e.glslTanh=e.glslTan=e.glslSqrt=e.glslSigmoid=e.glslRelu=e.glslSin=e.glslNot=e.glslNeg=e.glslLog=e.glslLeakyRelu=e.glslIdentity=e.glslClip=e.glslFloor=e.glslExp=e.glslElu=e.glslCos=e.glslCeil=e.glslAtan=e.glslAsin=e.glslAcos=e.glslAbs=void 0;const r=n(246),i=n(2517),o=n(8520),a=n(5060),s=n(2039);function u(){return P("abs")}function c(){return P("acos")}function l(){return P("asin")}function p(){return P("atan")}function f(){return P("ceil")}function d(){return P("cos")}function h(t){const e="elu";return{body:`\n  const float alpha = float(${t});\n\n  float ${e}_(float a) {\n    return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;\n  }\n  vec4 ${e}_(vec4 v) {\n    return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w));\n  }\n  `,name:e,type:o.FunctionType.ValueBased}}function g(){return P("exp")}function b(){return P("floor")}function m(t,e){const n="clip";return{body:`\n  const float min = float(${t});\n  const float max = float(${e});\n\n  float ${n}_(float a) {\n    return clamp(a, min, max);\n  }\n  vec4 ${n}_(vec4 v) {\n    return clamp(v, min, max);\n  }\n  `,name:n,type:o.FunctionType.ValueBased}}function y(){const t="indentity";return{body:`\n  float ${t}_(float a) {\n    return a;\n  }\n  vec4 ${t}_(vec4 v) {\n    return v;\n  }\n  `,name:t,type:o.FunctionType.ValueBased}}function _(t){const e="leakyRelu";return{body:`\n  const float alpha = float(${t});\n\n  float ${e}_(float a) {\n    return a < 0.0 ? a * alpha : a;\n  }\n  vec4 ${e}_(vec4 v) {\n    return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w));\n  }\n  `,name:e,type:o.FunctionType.ValueBased}}function v(){return P("log")}function w(){const t="neg";return{body:`\n  float ${t}_(float a) {\n    return -a;\n  }\n  vec4 ${t}_(vec4 v) {\n    return -v;\n  }\n  `,name:t,type:o.FunctionType.ValueBased}}function x(){const t="not";return{body:`\n  float ${t}_(float a) {\n    return float( ! bool(a) );\n  }\n  bool ${t}_(bool a) {\n    return !a;\n  }\n  vec4 ${t}_(vec4 v) {\n    return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));\n  }\n  bvec4 ${t}_(bvec4 v) {\n    return bvec4(!v.x, !v.y, !v.z, !v.w);\n  }\n  `,name:t,type:o.FunctionType.ValueBased}}function T(){return P("sin")}function S(){const t="relu";return{body:`\n  float ${t}_(float a) {\n    return max( a, 0.0 );\n  }\n  vec4 ${t}_(vec4 v) {\n    return max( v, 0.0 );\n  }\n  `,name:t,type:o.FunctionType.ValueBased}}function O(){const t="sigmoid";return{body:`\n  float ${t}_(float a) {\n    return 1.0 / (1.0 + exp(-a));\n  }\n  vec4 ${t}_(vec4 v) {\n    return 1.0 / (1.0 + exp(-v));\n  }\n  `,name:t,type:o.FunctionType.ValueBased}}function A(){return P("sqrt")}function E(){return P("tan")}function I(){const t="tanh";return{body:`\n  float ${t}_(float a) {\n    a = clamp(a, -10., 10.);\n    a = exp(2.*a);\n    return (a - 1.) / (a + 1.);\n  }\n  vec4 ${t}_(vec4 v) {\n    v = clamp(v, -10., 10.);\n    v = exp(2.*v);\n    return (v - 1.) / (v + 1.);\n  }\n  `,name:t,type:o.FunctionType.ValueBased}}function P(t){return{body:`\n  float ${t}_(float a) {\n    return ${t}(a);\n  }\n  vec4 ${t}_(vec4 v) {\n    return ${t}(v);\n  }\n  `,name:t,type:o.FunctionType.ValueBased}}e.glslAbs=u,e.glslAcos=c,e.glslAsin=l,e.glslAtan=p,e.glslCeil=f,e.glslCos=d,e.glslElu=h,e.glslExp=g,e.glslFloor=b,e.glslClip=m,e.glslIdentity=y,e.glslLeakyRelu=_,e.glslLog=v,e.glslNeg=w,e.glslNot=x,e.glslSin=T,e.glslRelu=S,e.glslSigmoid=O,e.glslSqrt=A,e.glslTan=E,e.glslTanh=I;const D=(t,e,n,r)=>{const i=t.session.pack?s.TextureType.packed:s.TextureType.unpacked,o={name:n.name,inputTypes:[i],inputNames:["A"],cacheHint:r};return Object.assign(Object.assign({},o),{get:()=>((t,e,n,r)=>{const i=t.session.pack?s.TextureType.packed:s.TextureType.unpacked,o=(0,a.getGlsl)(t.session.backend.glContext.version);return Object.assign(Object.assign({},e),{output:{dims:n.dims,type:n.type,textureType:i},shaderSource:`\n     ${r.body}\n     void main() {\n       vec4 v = ${o.texture2D}(A, TexCoords);\n       v = ${r.name}_(v);\n       ${o.output} = v;\n     }\n     `,hasMain:!0})})(t,o,e,n)})};e.abs=(t,e)=>[t.run(D(t,e[0],u()),e)],e.acos=(t,e)=>[t.run(D(t,e[0],c()),e)],e.asin=(t,e)=>[t.run(D(t,e[0],l()),e)],e.atan=(t,e)=>[t.run(D(t,e[0],p()),e)],e.clip=(t,e,n)=>[t.run(D(t,e[0],m(n.min,n.max),n.cacheKey),e)],e.parseClipAttributes=t=>(0,r.createAttributeWithCacheKey)({min:t.attributes.getFloat("min",i.MIN_CLIP),max:t.attributes.getFloat("max",i.MAX_CLIP)}),e.clipV11=(t,n)=>{const r=$(t,n);return(0,e.clip)(t,[n[0]],r)};const $=(t,e)=>{if(e.length>=3&&(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const n=e.length>=3?e[1].numberData[0]:i.MIN_CLIP,o=e.length>=3?e[2].numberData[0]:i.MAX_CLIP;return(0,r.createAttributeWithCacheKey)({min:n,max:o})};e.ceil=(t,e)=>[t.run(D(t,e[0],f()),e)],e.cos=(t,e)=>[t.run(D(t,e[0],d()),e)],e.elu=(t,e,n)=>[t.run(D(t,e[0],h(n.alpha),n.cacheKey),e)],e.parseEluAttributes=t=>(0,r.createAttributeWithCacheKey)({alpha:t.attributes.getFloat("alpha",1)}),e.exp=(t,e)=>[t.run(D(t,e[0],g()),e)],e.floor=(t,e)=>[t.run(D(t,e[0],b()),e)],e.identity=(t,e)=>[t.run(D(t,e[0],y()),e)],e.leakyRelu=(t,e,n)=>[t.run(D(t,e[0],_(n.alpha),n.cacheKey),e)],e.parseLeakyReluAttributes=t=>(0,r.createAttributeWithCacheKey)({alpha:t.attributes.getFloat("alpha",.01)}),e.log=(t,e)=>[t.run(D(t,e[0],v()),e)],e.neg=(t,e)=>[t.run(D(t,e[0],w()),e)],e.not=(t,e)=>[t.run(D(t,e[0],x()),e)],e.relu=(t,e)=>[t.run(D(t,e[0],S()),e)],e.sigmoid=(t,e)=>[t.run(D(t,e[0],O()),e)],e.sin=(t,e)=>[t.run(D(t,e[0],T()),e)],e.sqrt=(t,e)=>[t.run(D(t,e[0],A()),e)],e.tan=(t,e)=>[t.run(D(t,e[0],E()),e)],e.tanh=(t,e)=>[t.run(D(t,e[0],I()),e)]},5611:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createUnpackProgramInfoLoader=e.createUnpackProgramInfo=void 0;const r=n(5060),i=n(2039),o=n(9390),a=n(2827),s={name:"unpack",inputNames:["A"],inputTypes:[i.TextureType.packed]};e.createUnpackProgramInfo=(t,e)=>{const n=e.dims.length,u=(0,a.getChannels)("rc",n),c=u.slice(-2),l=(0,o.getCoordsDataType)(n),p=(0,a.unpackFromChannel)(),f=0===e.dims.length?"":function(t,e){if(1===t)return"rc";let n="";for(let r=0;r<t;r++)n+=e[r],r<t-1&&(n+=",");return n}(n,u),d=n<=1?"rc":`vec2(${c.join(",")})`,h=`\n    ${p}\n    void main() {\n      ${l} rc = getOutputCoords();\n\n       // Sample the texture with the coords to get the rgba channel value.\n       vec4 packedInput = getA(${f});\n\n       ${(0,r.getGlsl)(t.session.backend.glContext.version).output} = vec4(getChannel(packedInput, ${d}), 0, 0, 0);\n     }\n   `;return Object.assign(Object.assign({},s),{hasMain:!0,output:{dims:e.dims,type:e.type,textureType:i.TextureType.unpacked},shaderSource:h})},e.createUnpackProgramInfoLoader=(t,n)=>Object.assign(Object.assign({},s),{get:()=>(0,e.createUnpackProgramInfo)(t,n)})},8428:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseUnsqueezeAttributes=e.unsqueezeV13=e.unsqueeze=void 0;const r=n(2517);e.unsqueeze=(t,e,n)=>{i(e);const o=r.ShapeUtil.unsqueezeShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.unsqueezeV13=(t,n)=>(o(n),(0,e.unsqueeze)(t,[n[0]],Array.from(n[1].integerData))),e.parseUnsqueezeAttributes=t=>t.attributes.getInts("axes");const i=t=>{if(!t||1!==t.length)throw new Error("Unsqueeze requires 1 input.");if("string"===t[0].type)throw new Error("invalid input tensor types.")},o=t=>{if(!t||2!==t.length)throw new Error("Unsqueeze requires 2 inputs.");if("int32"!==t[1].type)throw new Error("Invalid input type.")}},9793:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.scalesValidation=e.validateInputs=e.parseUpsampleAttributes=e.parseUpsampleAttributesV9=e.parseUpsampleAttributesV7=e.upsample=void 0;const r=n(246),i=n(5060),o=n(2039),a={name:"Upsample",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};e.upsample=(t,n,r)=>((0,e.validateInputs)(n,r),[t.run(Object.assign(Object.assign({},a),{cacheHint:r.cacheKey,get:()=>s(t,n,r)}),n)]),e.parseUpsampleAttributesV7=t=>(0,e.parseUpsampleAttributes)(t,7),e.parseUpsampleAttributesV9=t=>(0,e.parseUpsampleAttributes)(t,9),e.parseUpsampleAttributes=(t,n)=>{const i=n>=10,o=t.attributes.getString("mode","nearest");if("nearest"!==o&&"linear"!==o&&(n<11||"cubic"!==o))throw new Error(`unrecognized mode: ${o}`);let a=[];n<9&&(a=t.attributes.getFloats("scales"),(0,e.scalesValidation)(a,o,i));const s=t.attributes.getFloat("extrapolation_value",0),u=n>10?t.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(-1===["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(u))throw new Error(`coordinate_transform_mode '${u}' is not supported`);const c="tf_crop_and_resize"===u,l=c,p="nearest"===o&&n>=11?t.attributes.getString("nearest_mode","round_prefer_floor"):"";if(-1===["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(p))throw new Error(`nearest_mode '${p}' is not supported`);const f=t.attributes.getFloat("cubic_coeff_a",-.75),d=0!==t.attributes.getInt("exclude_outside",0);if(d&&"cubic"!==o)throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const h=n<11||"nearest"===o&&"asymmetric"===u&&"floor"===p;let g=0,b=0,m=0;return n>10?t.inputs.length>2?(g=1,b=2,m=3):(b=1,m=2):9===n&&(b=1),(0,r.createAttributeWithCacheKey)({opset:n,isResize:i,mode:o,scales:a,extrapolationValue:s,coordinateTransformMode:u,useExtrapolation:l,needRoiInput:c,nearestMode:p,cubicCoefficientA:f,excludeOutside:d,useNearest2xOptimization:h,roiInputIdx:g,scalesInputIdx:b,sizesInputIdx:m})};const s=(t,e,n)=>{const r=(0,i.getGlsl)(t.session.backend.glContext.version),[s,u]=t.calculateTextureWidthAndHeight(e[0].dims,o.TextureType.unpacked),c=e[0].dims.map(((t,e)=>Math.floor(t*n.scales[e]))),[l,p]=t.calculateTextureWidthAndHeight(c,o.TextureType.unpacked),f=c.length,d=new Array(f),h=new Array(f);let g=`\n      int output_pitches[${f}];\n      int input_pitches[${f}];\n      `;for(let t=f-1;t>=0;t--)d[t]=t===f-1?1:d[t+1]*c[t+1],h[t]=t===f-1?1:h[t+1]*e[0].dims[t+1],g+=`\n        output_pitches[${t}] = ${d[t]};\n        input_pitches[${t}] = ${h[t]};\n        `;const b=`\n      float getInputFloat(int index) {\n        vec2 coords = offsetToCoords(index, ${s}, ${u});\n        float value = getColorAsFloat(${r.texture2D}(X, coords));\n        return value;\n      }\n      `,m="nearest"===n.mode?`\n    ${b}\n    float process(int indices[${f}]) {\n      int input_index = 0;\n      int output_index = coordsToOffset(TexCoords, ${l}, ${p});\n\n      ${g}\n\n      int d, m;\n      for (int dim = 0; dim < ${f}; ++dim) {\n        d = output_index / output_pitches[dim];\n        m = output_index - d * output_pitches[dim];\n        output_index = m;\n\n        if (scales[dim] != 1 && d > 0) {\n          int d2 = d / scales[dim];\n          m = d - d2 * scales[dim];\n          d = d2;\n        }\n        input_index += input_pitches[dim] * d;\n      }\n\n      return getInputFloat(input_index);\n    }`:4===f?`\n    ${b}\n    float process(int indices[4]) {\n      int input_index = 0;\n      int output_index = coordsToOffset(TexCoords, ${l}, ${p});\n\n      ${g}\n\n      int m;\n      int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;\n      index_of_dim0 = output_index / output_pitches[0];\n      m = output_index - index_of_dim0 * output_pitches[0];\n      index_of_dim1 = m / output_pitches[1];\n      m = m - index_of_dim1 * output_pitches[1];\n      index_of_dim2 = m / output_pitches[2];\n      m = m - index_of_dim2 * output_pitches[2];\n      index_of_dim3 = m;\n\n      int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;\n      index_of_input_dim2 = index_of_dim2 / scales[2];\n      y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];\n      index_of_input_dim3 = index_of_dim3 / scales[3];\n      x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];\n\n      input_index = index_of_dim0 * input_pitches[0] +\n            index_of_dim1 * input_pitches[1] +\n            index_of_input_dim2 * input_pitches[2] +\n            index_of_input_dim3;\n\n      float x00 = getInputFloat(input_index);\n      float x10, x01, x11;\n\n      bool end_of_dim2 = false;\n      if (index_of_input_dim2 == (${e[0].dims[2]} - 1)) {\n        // It's the end in dimension 2\n        x01 = x00;\n        end_of_dim2 = true;\n      } else {\n        x01 = getInputFloat(input_index + input_pitches[2]);\n      }\n\n      if (index_of_input_dim3 == (input_pitches[2] - 1)) {\n        // It's the end in dimension 3\n        x10 = x00;\n        x11 = x01;\n      }\n      else {\n        x10 = getInputFloat(input_index + 1);\n        x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);\n      }\n\n      float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);\n      float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);\n      return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);\n    }`:`\n    ${b}\n    float process(int indices[2]) {\n      int input_index = 0;\n      int output_index = coordsToOffset(TexCoords, ${l}, ${p});\n\n      ${g}\n\n      int m;\n      int index_of_dim0, index_of_dim1;\n      index_of_dim0 = output_index / output_pitches[0];\n      m = output_index - index_of_dim0 * output_pitches[0];\n      index_of_dim1 = m;\n\n      int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;\n      index_of_input_dim0 = index_of_dim0 / scales[0];\n      y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];\n      index_of_input_dim1 = index_of_dim1 / scales[1];\n      x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];\n\n      input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;\n\n      float x00 = getInputFloat(input_index);\n      float x10, x01, x11;\n\n      bool end_of_dim0 = false;\n      if (index_of_input_dim0 == (${e[0].dims[0]} - 1)) {\n        // It's the end in dimension 0\n        x01 = x00;\n        end_of_dim0 = true;\n      } else {\n        x01 = getInputFloat(input_index + input_pitches[0]);\n      }\n\n      if (index_of_input_dim1 == (input_pitches[0] - 1)) {\n        // It's the end in dimension 1\n        x10 = x00;\n        x11 = x01;\n      }\n      else {\n        x10 = getInputFloat(input_index + 1);\n        x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);\n      }\n\n      float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);\n      float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);\n      return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);\n    }`;return Object.assign(Object.assign({},a),{output:{dims:c,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:m,variables:[{name:"scales",type:"int",arrayLength:n.scales.length,data:n.scales.map((t=>Math.ceil(t)))}]})};e.validateInputs=(t,e)=>{if(!t||e.opset<9&&1!==t.length||e.opset>=9&&e.opset<11&&2!==t.length||e.opset>=11&&t.length<2)throw new Error("invalid inputs.");if(e.scales.length>0&&t[0].dims.length!==e.scales.length)throw new Error("Invalid input shape.");if("string"===t[0].type)throw new Error("Invalid input tensor types.")},e.scalesValidation=(t,e,n)=>{if(n){for(const e of t)if(e<=0)throw new Error("Scale value should be greater than 0.")}else for(const e of t)if(e<1)throw new Error("Scale value should be greater than or equal to 1.");if(!("linear"!==e&&"cubic"!==e||2===t.length||4===t.length&&1===t[0]&&1===t[1]))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic')         or 4-D inputs with the corresponding outermost 2 scale values being 1         in the ${n?"Resize":"Upsample"} opeartor.`)}},1958:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ProgramManager=void 0;const r=n(1670),i=n(6231),o=n(8879),a=n(5060);e.ProgramManager=class{constructor(t,e,n){this.profiler=t,this.glContext=e,this.textureLayoutStrategy=n,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,e){this.repo.set(t,e)}run(t,e,n){var r;this.profiler.event("op",`ProgramManager.run ${null!==(r=t.programInfo.name)&&void 0!==r?r:"unknown kernel"}`,(()=>{var r;const o=this.glContext.gl,a=t.program;o.useProgram(a);try{this.bindOutput(n),this.attributesBound||this.bindAttributes(t.attribLocations),this.bindUniforms(t.uniformLocations,null!==(r=t.programInfo.variables)&&void 0!==r?r:[],e)}catch(e){throw i.Logger.error("ProgramManager",t.programInfo.shaderSource),e}this.profiler.event("backend","GlContext.draw()",(()=>{this.glContext.draw()}))}),this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach((t=>this.glContext.deleteProgram(t.program)))}build(t,e,n){return this.profiler.event("backend","ProgramManager.build",(()=>{const r=new o.GlslPreprocessor(this.glContext,t,e,n),i=r.preprocess(),a=this.compile(i);return{programInfo:t,program:a,uniformLocations:this.getUniformLocations(a,r.context.programInfo.inputNames,r.context.programInfo.variables),attribLocations:this.getAttribLocations(a)}}))}compile(t){if(!this.vertexShader){i.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const t=(0,a.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(t,this.glContext.gl.VERTEX_SHADER)}r.env.debug&&i.Logger.verbose("ProrgramManager",`FragShader:\n${t}\n`);const e=this.glContext.compileShader(t,this.glContext.gl.FRAGMENT_SHADER),n=this.glContext.createProgram(this.vertexShader,e);return this.glContext.deleteShader(e),n}bindOutput(t){const e=t.width,n=t.height;i.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${e}/${n}, shape=${t.shape}, type=${t.tensor.type}`),this.glContext.attachFramebuffer(t.texture,e,n)}bindAttributes(t){const e=t.position,n=t.textureCoord;this.glContext.setVertexAttributes(e,n),this.attributesBound=!0}bindUniforms(t,e,n){var r;const i=this.glContext.gl;let o=0;for(const{name:a,type:s,location:u,arrayLength:c}of t){const t=null===(r=e.find((t=>t.name===a)))||void 0===r?void 0:r.data;if("sampler2D"!==s&&!t)throw new Error(`variable '${a}' does not have data defined in program info`);switch(s){case"sampler2D":this.bindTexture(n[o],u,o),o++;break;case"float":c?i.uniform1fv(u,t):i.uniform1f(u,t);break;case"int":c?i.uniform1iv(u,t):i.uniform1i(u,t);break;default:throw new Error(`Uniform not implemented: ${s}`)}}}bindTexture(t,e,n){this.glContext.bindTextureToUniform(t.texture,n,e)}getAttribLocations(t){return{position:this.getAttribLocation(t,"position"),textureCoord:this.getAttribLocation(t,"textureCoord")}}getUniformLocations(t,e,n){const r=[];if(e)for(const n of e)r.push({name:n,type:"sampler2D",location:this.getUniformLocation(t,n)});if(n)for(const e of n)r.push(Object.assign(Object.assign({},e),{location:this.getUniformLocation(t,e.name)}));return r}getUniformLocation(t,e){const n=this.glContext.gl.getUniformLocation(t,e);if(null===n)throw new Error(`Uniform ${e} not found.`);return n}getAttribLocation(t,e){return this.glContext.gl.getAttribLocation(t,e)}}},6416:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLSessionHandler=void 0;const r=n(6231),i=n(1047),o=n(8316),a=n(1640),s=n(1958),u=n(7859),c=n(5702);e.WebGLSessionHandler=class{constructor(t,e){this.backend=t,this.context=e,this.layoutStrategy=new u.PreferLogicalStrategy(t.glContext.maxTextureSize),this.programManager=new s.ProgramManager(this.context.profiler,t.glContext,this.layoutStrategy),this.textureManager=new c.TextureManager(t.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:"full"===t.textureCacheMode}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=t.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new o.WebGLInferenceHandler(this)}onGraphInitialized(t){const e=t.getValues().filter((t=>-1===t.from&&t.tensor)).map((t=>t.tensor.dataId));this.initializers=new Set(e)}isInitializer(t){return!!this.initializers&&this.initializers.has(t)}addInitializer(t){this.initializers.add(t)}getTextureData(t,e){return e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,n=!1){r.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),n?this.packedTextureDataCache.set(t,e):this.unpackedTextureDataCache.set(t,e)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((t=>this.textureManager.releaseTexture(t,!0))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((t=>this.textureManager.releaseTexture(t,!0))),this.unpackedTextureDataCache=new Map}resolve(t,e,n){const r=(0,i.resolveOperator)(t,e,a.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(t,n):t}}}},7769:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Uint8DataEncoder=e.RGBAFloatDataEncoder=e.RedFloat32DataEncoder=void 0;const r=n(6231);e.RedFloat32DataEncoder=class{constructor(t,e=1){if(1===e)this.internalFormat=t.R32F,this.format=t.RED,this.textureType=t.FLOAT,this.channelSize=e;else{if(4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA32F,this.format=t.RGBA,this.textureType=t.FLOAT,this.channelSize=e}}encode(t,e){let n,i;return t.constructor!==Float32Array&&(r.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),i=new Float32Array(t)),e*this.channelSize>t.length?(r.Logger.warning("Encoder","Source data too small. Allocating larger array"),i=t,n=this.allocate(e*this.channelSize),i.forEach(((t,e)=>n[e]=t))):(i=t,n=i),n}allocate(t){return new Float32Array(4*t)}decode(t,e){return 1===this.channelSize?t.filter(((t,e)=>e%4==0)).subarray(0,e):t.subarray(0,e)}},e.RGBAFloatDataEncoder=class{constructor(t,e=1,n){if(1!==e&&4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA,this.format=t.RGBA,this.channelSize=e,this.textureType=n||t.FLOAT}encode(t,e){let n=t;return 1===this.channelSize&&(r.Logger.verbose("Encoder","Exploding into a larger array"),n=this.allocate(e),t.forEach(((t,e)=>n[4*e]=t))),n}allocate(t){return new Float32Array(4*t)}decode(t,e){return 1===this.channelSize?t.filter(((t,e)=>e%4==0)).subarray(0,e):t.subarray(0,e)}},e.Uint8DataEncoder=class{constructor(t,e=1){if(this.channelSize=4,1===e)this.internalFormat=t.ALPHA,this.format=t.ALPHA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e;else{if(4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA,this.format=t.RGBA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e}}encode(t,e){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}allocate(t){return new Uint8Array(t*this.channelSize)}decode(t,e){if(t instanceof Uint8Array)return t.subarray(0,e);throw new Error(`Invalid array type: ${t.constructor}`)}}},7859:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getBatchDim=e.sizeToSquarishShape=e.getRowsCols=e.sizeFromShape=e.isInt=e.parseAxisParam=e.squeezeShape=e.PreferLogicalStrategy=e.AlwaysKeepOriginalSizeStrategy=void 0;const r=n(6231),i=n(2517);function o(t,e){const n=[],r=[],i=null!=e&&Array.isArray(e)&&0===e.length,o=null==e||i?null:a(e,t).sort();let s=0;for(let e=0;e<t.length;++e){if(null!=o){if(o[s]===e&&1!==t[e])throw new Error(`Can't squeeze axis ${e} since its dim '${t[e]}' is not 1`);(null==o[s]||o[s]>e)&&1===t[e]&&(n.push(t[e]),r.push(e)),o[s]<=e&&s++}1!==t[e]&&(n.push(t[e]),r.push(e))}return{newShape:n,keptDims:r}}function a(t,e){const n=e.length;return t=null==t?e.map(((t,e)=>e)):[].concat(t),(0,i.assert)(t.every((t=>t>=-n&&t<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${t}`)),(0,i.assert)(t.every(s),(()=>`All values in axis param must be integers but got axis ${t}`)),t.map((t=>t<0?n+t:t))}function s(t){return t%1==0}function u(t){if(0===t.length)return 1;let e=t[0];for(let n=1;n<t.length;n++)e*=t[n];return e}function c(t){const e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}e.AlwaysKeepOriginalSizeStrategy=class{constructor(t){this.maxTextureSize=t}computeTextureWH(t,e){if(0===t.length)return[1,1];const n=this.maxTextureSize;if(e&&void 0!==e.breakAxis){const i=e.breakAxis>=t.length?1:t.slice(e.breakAxis).reduce(((t,e)=>t*e)),o=e.breakAxis<=0?1:t.slice(0,e.breakAxis).reduce(((t,e)=>t*e));if(!(i>n||o>n))return[i,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}`)}const i=t.reduce(((t,e)=>t*e));let o=Math.floor(Math.sqrt(i));for(;o<n&&o<i&&i%o!=0;o++);if(o>=n||i%o!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${t}`);return[o,i/o]}},e.PreferLogicalStrategy=class{constructor(t){this.maxTextureSize=t}computeTextureWH(t,e){const n=this.computeTexture(t,e);return e&&e.isPacked&&(n[0]/=2,n[1]/=2),e&&e.reverseWH?[n[1],n[0]]:n}computeTexture(t,e){const n=e&&e.isPacked;if(0===t.length)return n?[2,2]:[1,1];let i=this.maxTextureSize;if(e&&void 0!==e.breakAxis){const n=e.breakAxis>=t.length?1:t.slice(e.breakAxis).reduce(((t,e)=>t*e)),o=e.breakAxis<=0?1:t.slice(0,e.breakAxis).reduce(((t,e)=>t*e));if(!(n>i||o>i))return[n,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}`)}let a=t.slice(0);if(n&&(i*=2,a=a.map(((t,e)=>e>=a.length-2?a[e]%2==0?a[e]:a[e]+1:a[e])),1===a.length&&(a=[2,a[0]])),2!==a.length){const t=o(a);a=t.newShape}const s=u(a);return a.length<=1&&s<=i?[1,s]:2===a.length&&a[0]<=i&&a[1]<=i?a:3===a.length&&a[0]*a[1]<=i&&a[2]<=i?[a[0]*a[1],a[2]]:3===a.length&&a[0]<=i&&a[1]*a[2]<=i?[a[0],a[1]*a[2]]:4===a.length&&a[0]*a[1]*a[2]<=i&&a[3]<=i?[a[0]*a[1]*a[2],a[3]]:4===a.length&&a[0]<=i&&a[1]*a[2]*a[3]<=i?[a[0],a[1]*a[2]*a[3]]:n?c(s/4).map((t=>2*t)):c(s)}},e.squeezeShape=o,e.parseAxisParam=a,e.isInt=s,e.sizeFromShape=u,e.getRowsCols=function(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]},e.sizeToSquarishShape=c,e.getBatchDim=function(t,e=2){return u(t.slice(0,t.length-e))}},4057:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createTextureLayoutFromShape=e.calculateTextureWidthAndHeight=e.createTextureLayoutFromTextureType=void 0;const r=n(2517),i=n(2039);e.createTextureLayoutFromTextureType=(t,n,r)=>{const o=r===i.TextureType.unpacked||r===i.TextureType.unpackedReversed?1:4,a=r===i.TextureType.packed,s=r===i.TextureType.unpackedReversed||r===i.TextureType.packed,u=r===i.TextureType.packedLastDimension?n.length-1:void 0,c=r===i.TextureType.packedLastDimension?n.map(((t,e)=>e===n.length-1?4*t:t)):void 0;return(0,e.createTextureLayoutFromShape)(t,n,o,c,{isPacked:a,reverseWH:s,breakAxis:u})},e.calculateTextureWidthAndHeight=(t,n,r)=>{const i=(0,e.createTextureLayoutFromTextureType)(t,n,r);return[i.width,i.height]},e.createTextureLayoutFromShape=(t,e,n=1,i,o)=>{const a=!(!o||!o.isPacked),[s,u]=t.computeTextureWH(a&&i||e,o),c=e.length;let l=e.slice(0);if(0===c&&(l=[1]),1===n)i=e;else if(a){if(4!==n)throw new Error("a packed texture must be 4-channel");i=e,c>0&&(l[c-1]=Math.ceil(l[c-1]/2)),c>1&&(l[c-2]=Math.ceil(l[c-2]/2))}else if(!i)throw new Error("Unpacked shape is needed when using channels > 1");return{width:s,height:u,channels:n,isPacked:a,shape:l,strides:r.ShapeUtil.computeStrides(l),unpackedShape:i,reversedWH:o&&o.reverseWH}}},5702:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TextureManager=void 0;const r=n(6231);e.TextureManager=class{constructor(t,e,n,r){this.glContext=t,this.layoutStrategy=e,this.profiler=n,this.config=r,this.pendingRead=new Map,r.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(t,e,n,i){const o=this.toEncoderType(t),a=this.glContext.getEncoder(o,e.channels||1,i);if(e.isPacked&&1===i)throw new Error("not implemented");const s=e.width,u=e.height;let c,l;if(this.config.reuseTextures){c=`${s}x${u}_${a.format}_${a.internalFormat}_${a.textureType}`,l=this.inUseTextures.get(c),l||(l=[],this.inUseTextures.set(c,l));const e=this.idleTextures.get(c);if(e&&e.length>0){const r=e.pop();return l.push(r),1===i&&this.glContext.updateTexture(r,s,u,a,this.toTextureData(t,n)),r}}r.Logger.verbose("TextureManager",`Creating new texture of size ${e.width}x${e.height}`);const p=this.glContext.allocateTexture(s,u,a,this.toTextureData(t,n));return this.config.reuseTextures&&(l.push(p),this.textureLookup.set(p,c)),p}readTexture(t,e,n){return n||(n=1),this.profiler.event("backend","TextureManager.readTexture",(()=>{const r=t.shape.reduce(((t,e)=>t*e))*n,i=this.glContext.readTexture(t.texture,t.width,t.height,r,this.toEncoderType(e),n);return this.toTensorData(e,i)}))}async readTextureAsync(t,e,n){const r=t.tensor.dataId;if(n||(n=1),this.pendingRead.has(r)){const t=this.pendingRead.get(r);return new Promise((e=>null==t?void 0:t.push(e)))}return this.profiler.event("backend","TextureManager.readTextureAsync",(async()=>{this.pendingRead.set(r,[]);const i=t.shape.reduce(((t,e)=>t*e))*n;await this.glContext.createAndWaitForFence();const o=this.glContext.readTexture(t.texture,t.width,t.height,i,this.toEncoderType(e),n),a=this.toTensorData(e,o),s=this.pendingRead.get(r);return this.pendingRead.delete(r),null==s||s.forEach((t=>t(a))),a}))}readUint8TextureAsFloat(t){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",(()=>{const e=t.shape.reduce(((t,e)=>t*e)),n=this.glContext.readTexture(t.texture,t.width,t.height,4*e,"byte",4);return new Float32Array(n.buffer,n.byteOffset,e)}))}releaseTexture(t,e){let n;if(this.config.reuseTextures&&(n=this.textureLookup.get(t.texture),n)){e&&this.textureLookup.delete(n);const r=this.inUseTextures.get(n);if(r){const e=r.indexOf(t.texture);if(-1!==e){r.splice(e,1);let i=this.idleTextures.get(n);i||(i=[],this.idleTextures.set(n,i)),i.push(t.texture)}}}n&&!e||(r.Logger.verbose("TextureManager",`Deleting texture of size ${t.width}x${t.height}`),this.glContext.deleteTexture(t.texture))}toTensorData(t,e){switch(t){case"int16":return e instanceof Int16Array?e:Int16Array.from(e);case"int32":return e instanceof Int32Array?e:Int32Array.from(e);case"int8":return e instanceof Int8Array?e:Int8Array.from(e);case"uint16":return e instanceof Uint16Array?e:Uint16Array.from(e);case"uint32":return e instanceof Uint32Array?e:Uint32Array.from(e);case"uint8":case"bool":return e instanceof Uint8Array?e:Uint8Array.from(e);case"float32":return e instanceof Float32Array?e:Float32Array.from(e);case"float64":return e instanceof Float64Array?e:Float64Array.from(e);default:throw new Error(`TensorData type ${t} is not supported`)}}toTextureData(t,e){if(e)return e instanceof Float32Array?e:new Float32Array(e)}toEncoderType(t){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},2039:(t,e)=>{"use strict";var n;Object.defineProperty(e,"__esModule",{value:!0}),e.TextureType=void 0,(n=e.TextureType||(e.TextureType={}))[n.unpacked=0]="unpacked",n[n.unpackedReversed=1]="unpackedReversed",n[n.packed=2]="packed",n[n.downloadUint8AsFloat=3]="downloadUint8AsFloat",n[n.packedLastDimension=4]="packedLastDimension"},9390:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getGlChannels=e.getCoordsDataType=e.getSqueezedParams=e.squeezeInputShape=e.generateShaderFuncNameFromInputSamplerNameAtOutCoords=e.generateShaderFuncNameFromInputSamplerName=e.repeatedTry=e.getPackedShape=void 0;const r=n(2517);e.getPackedShape=function(t){const e=t.length;return t.slice(0,e-1).concat(t[e-1]/4)},e.repeatedTry=async function(t,e=(t=>0),n){return new Promise(((r,i)=>{let o=0;const a=()=>{if(t())return void r();o++;const s=e(o);null!=n&&o>=n?i():setTimeout(a,s)};a()}))},e.generateShaderFuncNameFromInputSamplerName=function(t){return(0,r.assert)(void 0!==t&&0!==t.length,(()=>"empty string found for sampler name")),"get"+t.charAt(0).toUpperCase()+t.slice(1)},e.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(t){return(0,r.assert)(void 0!==t&&0!==t.length,(()=>"empty string found for sampler name")),"get"+t.charAt(0).toUpperCase()+t.slice(1)+"AtOutCoords"},e.squeezeInputShape=function(t,e){let n=JSON.parse(JSON.stringify(t));return n=e,n},e.getSqueezedParams=function(t,e){return e.map((e=>t[e])).join(", ")},e.getCoordsDataType=function(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error(`GPU for rank ${t} is not yet supported`)},e.getGlChannels=function(t=6){return["x","y","z","w","u","v"].slice(0,t)}},7305:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createNewWebGLContext=e.createWebGLContext=void 0;const r=n(6231),i=n(1713),o={};function a(t){const e=function(){if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas)throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}const t=document.createElement("canvas");return t.width=1,t.height=1,t}();let n;const o={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!t||"webgl2"===t)&&(n=e.getContext("webgl2",o),n))try{return new i.WebGLContext(n,2)}catch(t){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${t}`)}if((!t||"webgl"===t)&&(n=e.getContext("webgl",o)||e.getContext("experimental-webgl",o),n))try{return new i.WebGLContext(n,1)}catch(t){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t}`)}throw new Error("WebGL is not supported")}e.createWebGLContext=function t(e){let n;e&&"webgl2"!==e||!("webgl2"in o)?e&&"webgl"!==e||!("webgl"in o)||(n=o.webgl):n=o.webgl2,n=n||a(e),e=e||1===n.version?"webgl":"webgl2";const r=n.gl;return o[e]=n,r.isContextLost()?(delete o[e],t(e)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),n)},e.createNewWebGLContext=a},1713:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLContext=e.linearSearchLastTrue=void 0;const a=n(1670),s=o(n(7769)),u=n(9390);function c(t){let e=0;for(;e<t.length&&t[e]();++e);return e-1}e.linearSearchLastTrue=c,e.WebGLContext=class{constructor(t,e){this.frameBufferBound=!1,this.itemsToPoll=[],this.gl=t,this.version=e,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(t,e,n,r){const i=this.gl,o=i.createTexture();i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE);const a=r?n.encode(r,t*e):null;return i.texImage2D(i.TEXTURE_2D,0,n.internalFormat,t,e,0,n.format,n.textureType,a),this.checkError(),o}updateTexture(t,e,n,r,i){const o=this.gl;o.bindTexture(o.TEXTURE_2D,t);const a=r.encode(i,e*n);o.texSubImage2D(o.TEXTURE_2D,0,0,0,e,n,r.format,r.textureType,a),this.checkError()}attachFramebuffer(t,e,n){const r=this.gl;r.bindTexture(r.TEXTURE_2D,t),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t,0),this.checkError(),r.viewport(0,0,e,n),r.scissor(0,0,e,n)}readTexture(t,e,n,r,i,o){const a=this.gl;o||(o=1),this.frameBufferBound||this.attachFramebuffer(t,e,n);const s=this.getEncoder(i,o),u=s.allocate(e*n);return a.bindTexture(a.TEXTURE_2D,t),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t,0),a.readPixels(0,0,e,n,a.RGBA,s.textureType,u),this.checkError(),s.decode(u,r)}isFramebufferReady(){return!0}getActiveTexture(){const t=this.gl;return"TEXTURE"+(t.getParameter(this.gl.ACTIVE_TEXTURE)-t.TEXTURE0)}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(t,e){const n=this.gl;n.vertexAttribPointer(t,3,n.FLOAT,!1,20,0),n.enableVertexAttribArray(t),-1!==e&&(n.vertexAttribPointer(e,2,n.FLOAT,!1,20,12),n.enableVertexAttribArray(e)),this.checkError()}createProgram(t,e){const n=this.gl,r=n.createProgram();return n.attachShader(r,t),n.attachShader(r,e),n.linkProgram(r),r}compileShader(t,e){const n=this.gl,r=n.createShader(e);if(!r)throw new Error(`createShader() returned null with type ${e}`);if(n.shaderSource(r,t),n.compileShader(r),!1===n.getShaderParameter(r,n.COMPILE_STATUS))throw new Error(`Failed to compile shader: ${n.getShaderInfoLog(r)}\nShader source:\n${t}`);return r}deleteShader(t){this.gl.deleteShader(t)}bindTextureToUniform(t,e,n){const r=this.gl;r.activeTexture(r.TEXTURE0+e),this.checkError(),r.bindTexture(r.TEXTURE_2D,t),this.checkError(),r.uniform1i(n,e),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(a.env.debug){const t=this.gl,e=t.getError();let n="";switch(e){case t.NO_ERROR:return;case t.INVALID_ENUM:n="INVALID_ENUM";break;case t.INVALID_VALUE:n="INVALID_VALUE";break;case t.INVALID_OPERATION:n="INVALID_OPERATION";break;case t.INVALID_FRAMEBUFFER_OPERATION:n="INVALID_FRAMEBUFFER_OPERATION";break;case t.OUT_OF_MEMORY:n="OUT_OF_MEMORY";break;case t.CONTEXT_LOST_WEBGL:n="CONTEXT_LOST_WEBGL";break;default:n=`Unknown WebGL Error: ${e.toString(16)}`}throw new Error(n)}}deleteTexture(t){this.gl.deleteTexture(t)}deleteProgram(t){this.gl.deleteProgram(t)}getEncoder(t,e,n=0){if(2===this.version)return new s.RedFloat32DataEncoder(this.gl,e);switch(t){case"float":return 1===n||this.isRenderFloat32Supported?new s.RGBAFloatDataEncoder(this.gl,e):new s.RGBAFloatDataEncoder(this.gl,e,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new s.Uint8DataEncoder(this.gl,e);default:throw new Error(`Invalid dataType: ${t}`)}}clearActiveTextures(){const t=this.gl;for(let e=0;e<this.maxTextureImageUnits;++e)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,null)}dispose(){if(this.disposed)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteFramebuffer(this.framebuffer),t.bindBuffer(t.ARRAY_BUFFER,null),t.deleteBuffer(this.vertexbuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.finish(),this.disposed=!0}createDefaultGeometry(){return new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0])}createVertexbuffer(){const t=this.gl,e=t.createBuffer();if(!e)throw new Error("createBuffer() returned null");const n=this.createDefaultGeometry();return t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW),this.checkError(),e}createFramebuffer(){const t=this.gl.createFramebuffer();if(!t)throw new Error("createFramebuffer returned null");return t}queryVitalParameters(){const t=this.gl;if(this.isFloatTextureAttachableToFrameBuffer=this.checkFloatTextureAttachableToFrameBuffer(),this.isRenderFloat32Supported=this.checkRenderFloat32(),this.isFloat32DownloadSupported=this.checkFloat32Download(),1===this.version&&!this.textureHalfFloatExtension&&!this.isRenderFloat32Supported)throw new Error("both float32 and float16 TextureType are not supported");this.isBlendSupported=!this.isRenderFloat32Supported||this.checkFloat32Blend(),this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxTextureImageUnits=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.version}getExtensions(){2===this.version?(this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float"),this.disjointTimerQueryWebgl2Extension=this.gl.getExtension("EXT_disjoint_timer_query_webgl2")):(this.textureFloatExtension=this.gl.getExtension("OES_texture_float"),this.textureHalfFloatExtension=this.gl.getExtension("OES_texture_half_float"))}checkFloatTextureAttachableToFrameBuffer(){const t=this.gl,e=t.createTexture();t.bindTexture(t.TEXTURE_2D,e);const n=2===this.version?t.RGBA32F:t.RGBA;t.texImage2D(t.TEXTURE_2D,0,n,1,1,0,t.RGBA,t.FLOAT,null);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0);const i=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(e),t.deleteFramebuffer(r),i}checkRenderFloat32(){if(2===this.version){if(!this.colorBufferFloatExtension)return!1}else if(!this.textureFloatExtension)return!1;return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Download(){if(2===this.version){if(!this.colorBufferFloatExtension)return!1}else{if(!this.textureFloatExtension)return!1;if(!this.gl.getExtension("WEBGL_color_buffer_float"))return!1}return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Blend(){const t=this.gl;let e,n,r,i,o;try{e=t.createTexture(),n=t.createFramebuffer(),t.bindTexture(t.TEXTURE_2D,e);const a=2===this.version?t.RGBA32F:t.RGBA;return t.texImage2D(t.TEXTURE_2D,0,a,1,1,0,t.RGBA,t.FLOAT,null),t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),t.enable(t.BLEND),r=t.createShader(t.VERTEX_SHADER),!!r&&(t.shaderSource(r,"void main(){}"),t.compileShader(r),i=t.createShader(t.FRAGMENT_SHADER),!!i&&(t.shaderSource(i,"precision highp float;void main(){gl_FragColor=vec4(0.5);}"),t.compileShader(i),o=t.createProgram(),!!o&&(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),t.useProgram(o),t.drawArrays(t.POINTS,0,1),t.getError()===t.NO_ERROR)))}finally{t.disable(t.BLEND),o&&t.deleteProgram(o),r&&t.deleteShader(r),i&&t.deleteShader(i),n&&(t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteFramebuffer(n)),e&&(t.bindTexture(t.TEXTURE_2D,null),t.deleteTexture(e))}}beginTimer(){if(2===this.version&&this.disjointTimerQueryWebgl2Extension){const t=this.gl,e=this.disjointTimerQueryWebgl2Extension,n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}throw new Error("WebGL1 profiling currently not supported.")}endTimer(){if(2!==this.version||!this.disjointTimerQueryWebgl2Extension)throw new Error("WebGL1 profiling currently not supported");{const t=this.gl,e=this.disjointTimerQueryWebgl2Extension;t.endQuery(e.TIME_ELAPSED_EXT)}}isTimerResultAvailable(t){let e=!1,n=!1;if(2!==this.version||!this.disjointTimerQueryWebgl2Extension)throw new Error("WebGL1 profiling currently not supported");{const r=this.gl,i=this.disjointTimerQueryWebgl2Extension;e=r.getQueryParameter(t,r.QUERY_RESULT_AVAILABLE),n=r.getParameter(i.GPU_DISJOINT_EXT)}return e&&!n}getTimerResult(t){let e=0;if(2!==this.version)throw new Error("WebGL1 profiling currently not supported");{const n=this.gl;e=n.getQueryParameter(t,n.QUERY_RESULT),n.deleteQuery(t)}return e/1e6}async waitForQueryAndGetTime(t){return await(0,u.repeatedTry)((()=>this.isTimerResultAvailable(t))),this.getTimerResult(t)}async createAndWaitForFence(){const t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e;const n=t,r=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),e=null===r?()=>!0:()=>{const t=n.clientWaitSync(r,0,0);return t===n.ALREADY_SIGNALED||t===n.CONDITION_SATISFIED},{query:r,isFencePassed:e}}async pollFence(t){return new Promise((e=>{this.addItemToPoll((()=>t.isFencePassed()),(()=>e()))}))}pollItems(){const t=c(this.itemsToPoll.map((t=>t.isDoneFn)));for(let e=0;e<=t;++e){const{resolveFn:t}=this.itemsToPoll[e];t()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}async addItemToPoll(t,e){this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||await(0,u.repeatedTry)((()=>(this.pollItems(),0===this.itemsToPoll.length)))}}},1036:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ExecutionPlan=void 0;const r=n(6231);class i{constructor(t,e){this.op=t,this.node=e}}e.ExecutionPlan=class{constructor(t,e,n){this.graph=t,this.profiler=n,this.initialize(e)}initialize(t){this.profiler.event("session","ExecutionPlan.initialize",(()=>{const e=this.graph.getNodes();if(e.length!==t.length)throw new Error("The size of nodes and OPs do not match.");this._ops=t.map(((t,n)=>new i(t,e[n]))),this.reset(),this._starter=[],this._ops.forEach(((t,e)=>{let n=!0;for(const e of t.node.inputs)if(!this._values[e]&&-1===this.graph.getInputIndices().indexOf(e)){n=!1;break}n&&this._starter.push(e)}))}))}reset(){this._values=this.graph.getValues().map((t=>t.tensor))}async execute(t,e){return this.profiler.event("session","ExecutionPlan.execute",(async()=>{this.reset();const n=t.createInferenceHandler(),i=this.graph.getInputIndices();if(e.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${e.length} expected: ${i.length}`);e.forEach(((t,e)=>{const n=i[e];this._values[n]=t}));const o=this._starter.slice(0),a=this.graph.getValues(),s=this.graph.getNodes();let u=0;for(;u<o.length;){const t=o[u++],e=this._ops[t],i=e.node.inputs.map((t=>this._values[t]));if(-1!==i.indexOf(void 0))throw new Error(`unresolved input detected: op: ${e.node}`);const c=i;r.Logger.verbose("ExecPlan",`Runing op:${e.node.name} (${c.map(((t,n)=>`'${e.node.inputs[n]}': ${t.type}[${t.dims.join(",")}]`)).join(", ")})`);const l=await this.profiler.event("node",e.node.name,(async()=>e.op.impl(n,c,e.op.context)));if(l.length!==e.node.outputs.length)throw new Error("the size of output does not match model definition.");l.forEach(((t,n)=>{const r=e.node.outputs[n];if(this._values[r])throw new Error(`output [${r}] already has value: op:${e.node.name}`);this._values[r]=t}));const p=new Set;l.forEach(((t,n)=>{const r=e.node.outputs[n];for(const t of a[r].to){const e=s[t];let n=!0;for(const t of e.inputs)if(!this._values[t]){n=!1;break}n&&p.add(t)}})),o.push(...p)}const c=[];for(let t=0;t<this.graph.getOutputIndices().length;t++){const e=this.graph.getOutputIndices()[t],n=this._values[e];if(void 0===n)throw new Error(`required output [${e}] does not have value`);0===e?await n.getData():n.data,c.push(n)}return r.Logger.verbose("ExecPlan","disposing of inferenceHandler"),n.dispose(),c}))}}},7070:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Graph=void 0;const r=n(1446),i=n(7778),o=n(9395),a=n(9162),s=n(2517);var u=o.onnxruntime.experimental.fbs;e.Graph={from:(t,e)=>new p(t,e)};class c{constructor(t){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,t&&(this.type=s.ProtoUtil.tensorValueTypeFromProto(t.type.tensorType))}get from(){return this._from}get to(){return this._to}}class l{constructor(t,e){t instanceof r.onnx.NodeProto?(this.name=t.name,this.opType=t.opType,this.attributes=new i.Attribute(t.attribute)):t instanceof u.Node&&(this.name=null!=e?e:t.name(),this.opType=t.opType(),this.attributes=new i.Attribute(s.ProtoUtil.tensorAttributesFromORTFormat(t))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class p{constructor(t,e){if(!t)throw new TypeError("graph is empty");this.buildGraph(t),this.transformGraph(e),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(t){if(t instanceof r.onnx.GraphProto)this.buildGraphFromOnnxFormat(t);else{if(!(t instanceof u.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(t)}}buildGraphFromOnnxFormat(t){const e=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const n=new Map;if(!t.input)throw new Error("missing information in graph: input");const r=[];for(const n of t.input){if(e.has(n.name))throw new Error(`duplicated input name: ${n.name}`);const t=this._allData.push(new c(n))-1;e.set(n.name,t),r.push(n.name)}if(!t.initializer)throw new Error("missing information in graph: initializer");for(const n of t.initializer){let t=e.get(n.name);if(void 0===t){const r=new c;r.type={shape:{dims:s.ProtoUtil.tensorDimsFromProto(n.dims)},tensorType:s.ProtoUtil.tensorDataTypeFromProto(n.dataType)},t=this._allData.push(r)-1,e.set(n.name,t)}this._allData[t]._from=-1,this._allData[t].tensor=a.Tensor.fromProto(n)}for(let t=0;t<this._allData.length;t++)this._allData[t].tensor||(this._allInputIndices.push(t),this._allInputNames.push(r[t]));if(!t.output)throw new Error("missing information in graph: output");for(const n of t.output){if(e.has(n.name))throw new Error(`duplicated output name: ${n.name}`);const t=this._allData.push(new c(n))-1;e.set(n.name,t),this._allOutputIndices.push(t),this._allOutputNames.push(n.name)}if(!t.node)throw new Error("missing information in graph: node");for(const e of t.node){if(!e.name)for(let t=0;;t++){const r=`unnamed_${e.opType}_${t}`;if(!n.has(r)){e.name=r;break}}if(n.has(e.name))throw new Error(`duplicated node name: ${e.name}`);const t=this._nodes.push(new l(e))-1;n.set(e.name,t)}for(let n=0;n<this._nodes.length;n++){const r=this._nodes[n],i=t.node[n];if(!i.output)throw new Error(`missing output for node: ${i.name}`);for(const t of i.output){let o=e.get(t);if(void 0===o&&(o=this._allData.push(new c)-1,e.set(t,o)),r.outputs.push(o),void 0!==this._allData[o]._from)throw new Error(`multiple nodes output to one data value: ${o}`);if(this._allData[o]._from=n,"Constant"===i.opType){if(!i.attribute||1!==i.attribute.length||!i.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!i.output||1!==i.output.length)throw new Error("missing output or incorrect number of outputs for this Constant operator");r.outputs.pop(),r.executeNode=!1,this._allData[o]._from=-1,this._allData[o].tensor=a.Tensor.fromProto(i.attribute[0].t)}}}for(let n=0;n<this._nodes.length;n++){const r=this._nodes[n],i=t.node[n];if(!i.input)throw new Error(`missing input for node: ${i.name}`);for(const t of i.input){const o=e.get(t);if(void 0===o){if(""===t&&3===i.input.length&&"Resize"===i.opType)continue;throw new Error(`unrecognized input '${t}' for node: ${i.name}`)}r.inputs.push(o),this._allData[o]._to.push(n)}}return!0}buildGraphFromOrtFormat(t){var e,n,r;const i=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const o=new Map,p=[];for(let o=0;o<t.inputsLength();o++){const a=t.inputs(o);if(i.has(a))throw new Error(`duplicated input name: ${a}`);for(let o=0;o<t.nodeArgsLength();o++)if((null===(e=t.nodeArgs(o))||void 0===e?void 0:e.name())===a){const e=new c;if((null===(r=null===(n=t.nodeArgs(o))||void 0===n?void 0:n.type())||void 0===r?void 0:r.valueType())!==u.TypeInfoValue.tensor_type)throw new Error("Unexpected value type for the nodeArg.");const l=t.nodeArgs(o).type().value(new u.TensorTypeAndShape),f=s.ProtoUtil.tensorDataTypeFromProto(l.elemType()),d=l.shape(),h=[];for(let t=0;t<d.dimLength();t++)h.push(s.LongUtil.longToNumber(d.dim(t).value().dimValue()));e.type={shape:{dims:h},tensorType:f};const g=this._allData.push(e)-1;i.set(a,g),p.push(a)}}for(let e=0;e<t.initializersLength();e++){const n=t.initializers(e);let r=i.get(n.name());if(void 0===r){const t=new c,e=s.ProtoUtil.tensorDimsFromORTFormat(n),o=s.ProtoUtil.tensorDataTypeFromProto(n.dataType());t.type={shape:{dims:e},tensorType:o},r=this._allData.push(t)-1,i.set(n.name(),r)}this._allData[r]._from=-1,this._allData[r].tensor=a.Tensor.fromOrtTensor(n)}for(let t=0;t<this._allData.length;t++)this._allData[t].tensor||(this._allInputIndices.push(t),this._allInputNames.push(p[t]));for(let e=0;e<t.outputsLength();e++){const n=t.outputs(e);if(i.has(n))throw new Error(`duplicated output name: ${n}`);const r=this._allData.push(new c)-1;i.set(n,r),this._allOutputIndices.push(r),this._allOutputNames.push(n)}if(!t.nodes)throw new Error("missing information in graph: node");for(let e=0;e<t.nodesLength();e++){const n=t.nodes(e);let r=n.name();if(!r)for(let t=0;r=`unnamed_${n.opType()}_${t}`,o.has(r);t++);if(o.has(r))throw new Error(`duplicated node name: ${r}`);const i=this._nodes.push(new l(n,r))-1;o.set(r,i)}for(let e=0;e<this._nodes.length;e++){const n=this._nodes[e],r=t.nodes(e);if(null==r)throw new Error(`No node exists at index ${e}`);if(0===(null==r?void 0:r.outputsLength()))throw new Error(`missing output for node: ${r.name}`);for(let t=0;t<(null==r?void 0:r.outputsLength());t++){const o=null==r?void 0:r.outputs(t);let s=i.get(o);if(void 0===s&&(s=this._allData.push(new c)-1,i.set(o,s)),n.outputs.push(s),void 0!==this._allData[s]._from)throw new Error(`multiple nodes output to one data value: ${s}`);if(this._allData[s]._from=e,"Constant"===r.opType()){if(1!==r.attributesLength()||!r.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(1!==r.outputsLength())throw new Error("missing output or incorrect number of outputs for this Constant operator");n.outputs.pop(),n.executeNode=!1,this._allData[s]._from=-1,this._allData[s].tensor=a.Tensor.fromOrtTensor(r.attributes(0).t())}}}for(let e=0;e<this._nodes.length;e++){const n=this._nodes[e],r=t.nodes(e);if(0===r.inputsLength())throw new Error(`missing input for node: ${r.name}`);for(let t=0;t<r.inputsLength();t++){const o=r.inputs(t),a=i.get(o);if(void 0===a)throw new Error(`unrecognized input '${o}' for node: ${r.name()}`);n.inputs.push(a),this._allData[a]._to.push(e)}}}checkIsAcyclic(){const t=new Set;this._allInputIndices.forEach((e=>{this._allData[e]._to.forEach((e=>{t.add(e)}))}));const e=Array.from(t),n=new Array(this._nodes.length).fill("white");for(;e.length>0;){const t=e.pop();"gray"===n[t]?n[t]="black":(e.push(t),n[t]="gray",this._nodes[t].outputs.forEach((r=>{const i=this._allData[r];if(void 0!==i.tensor)throw new Error("node outputs should not be initialized");if(i._from!==t)throw new Error("from property of the Value object doesn't match index of Node being processed");i._to.forEach((t=>{if("gray"===n[t])throw new Error("model graph is cyclic");"white"===n[t]&&e.push(t)}))})))}}transformGraph(t){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),t&&t.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let t=0;for(let e=0;e<this._nodes.length;e++)this._nodes[e].executeNode?t>0&&(this._nodes[e].inputs.forEach((n=>{const r=this._allData[n]._to.indexOf(e+t);-1!==r&&(this._allData[n]._to[r]=e)})),this._nodes[e].outputs.forEach((n=>{this._allData[n]._from&&this._allData[n]._from===e+t&&(this._allData[n]._from=e)}))):(t++,this._nodes[e].outputs.forEach((t=>{this._allData[t]._from=-2})),this._nodes.splice(e,1),e--);t=0;for(let e=0;e<this._allData.length;e++)if(-2!==this._allData[e].from||-1!==this._allOutputIndices.indexOf(e+t)){if(t>0){let n=-1;void 0!==this._allData[e].from&&-1!==this._allData[e].from?(n=this._nodes[this._allData[e].from].outputs.indexOf(e+t),-1!==n&&(this._nodes[this._allData[e].from].outputs[n]=e)):(n=this._allInputIndices.indexOf(e+t),-1!==n&&(this._allInputIndices[n]=e)),this._allData[e].to.forEach((r=>{n=this._nodes[r].inputs.indexOf(e+t),-1!==n&&(this._nodes[r].inputs[n]=e)})),0===this._allData[e].to.length&&(n=this._allOutputIndices.indexOf(e+t),-1!==n&&(this._allOutputIndices[n]=e))}}else t++,this._allData.splice(e,1),e--}deleteNode(t){const e=this._nodes[t];if(e.outputs.length>1)for(let t=1;t<e.outputs.length;t++)if(this._allData[e.outputs[t]].to.length>0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ");e.executeNode=!1;const n=e.inputs[0],r=e.outputs[0],i=this._allData[r].to,o=this._allData[n].to.indexOf(t);if(-1===o)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[n].to.splice(o,1),this._allData[r]._to=[];const a=this._allOutputIndices.indexOf(r);if(-1!==a&&(this._allOutputIndices[a]=n),i&&i.length>0)for(const t of i){const e=this._nodes[t].inputs.indexOf(r);if(-1===e)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[t].inputs[e]=n,this._allData[n].to.push(t)}}removeAllDropoutNodes(){let t=0;for(const e of this._nodes){if("Dropout"===e.opType){if(1!==e.inputs.length)throw new Error("Dropout nodes should only contain one input. ");if(1!==e.outputs.length&&2!==e.outputs.length)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(2===e.outputs.length&&0!==this._allData[e.outputs[1]]._to.length)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(t)}t++}}removeAllIdentityNodes(){let t=0;for(const e of this._nodes)"Identity"===e.opType&&this.deleteNode(t),t++}isActivation(t){switch(t.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const t of this._nodes)if("Conv"===t.opType){const e=this._allData[t.outputs[0]]._to;if(1===e.length&&this.isActivation(this._nodes[e[0]])){const n=this._nodes[e[0]];if("Clip"===n.opType)if(1===n.inputs.length)try{t.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch(e){t.attributes.set("activation_params","floats",[s.MIN_CLIP,s.MAX_CLIP])}else{if(!(n.inputs.length>=3&&void 0!==this._allData[n.inputs[1]].tensor&&void 0!==this._allData[n.inputs[2]].tensor))continue;t.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]])}t.attributes.set("activation","string",n.opType),this.deleteNode(e[0])}}}}},6231:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.now=e.Profiler=e.Logger=void 0;const n={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},r={none:new class{log(t,e,n){}},console:new class{log(t,e,n){console.log(`${this.color(t)} ${n?"[35m"+n+"[0m ":""}${e}`)}color(t){switch(t){case"verbose":return"[34;40mv[0m";case"info":return"[32mi[0m";case"warning":return"[30;43mw[0m";case"error":return"[31;40me[0m";case"fatal":return"[101mf[0m";default:throw new Error(`unsupported severity: ${t}`)}}}},i={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let o={"":i};function a(t,e,n,r){if(void 0===e)return i=t,{verbose:a.verbose.bind(null,i),info:a.info.bind(null,i),warning:a.warning.bind(null,i),error:a.error.bind(null,i),fatal:a.fatal.bind(null,i)};if(void 0===n)s(t,e);else if("number"==typeof n&&void 0===r)s(t,e);else if("string"==typeof n&&void 0===r)s(t,n,0,e);else{if("string"!=typeof n||"number"!=typeof r)throw new TypeError("input is valid");s(t,n,0,e)}var i}function s(t,e,i,a){const s=o[a||""]||o[""];n[t]<n[s.minimalSeverity]||(s.logDateTime&&(e=`${(new Date).toISOString()}|${e}`),s.logSourceLocation,r[s.provider].log(t,e,a))}!function(t){function e(t){o={},n("",t||{})}function n(t,n){if("*"===t)e(n);else{const e=o[t]||i;o[t]={provider:n.provider||e.provider,minimalSeverity:n.minimalSeverity||e.minimalSeverity,logDateTime:void 0===n.logDateTime?e.logDateTime:n.logDateTime,logSourceLocation:void 0===n.logSourceLocation?e.logSourceLocation:n.logSourceLocation}}}t.verbose=function(e,n){t("verbose",e,n)},t.info=function(e,n){t("info",e,n)},t.warning=function(e,n){t("warning",e,n)},t.error=function(e,n){t("error",e,n)},t.fatal=function(e,n){t("fatal",e,n)},t.reset=e,t.set=n,t.setWithEnv=function(t){const e={};t.logLevel&&(e.minimalSeverity=t.logLevel),n("",e)}}(a||(a={})),e.Logger=a;class u{constructor(t,e,n,r,i,o){this.category=t,this.name=e,this.startTime=n,this.endCallback=r,this.timer=i,this.ctx=o}end(){return this.endCallback(this)}async checkTimer(){if(void 0===this.ctx||void 0===this.timer)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}}class c{constructor(t,e,n,r){this.category=t,this.name=e,this.startTime=n,this.endTime=r}}e.Profiler=class{static create(t){return void 0===t?new this:new this(t.maxNumberEvents,t.flushBatchSize,t.flushIntervalInMilliseconds)}constructor(t,e,n){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=void 0===t?1e4:t,this._flushBatchSize=void 0===e?10:e,this._flushIntervalInMilliseconds=void 0===n?5e3:n}start(){this._started=!0,this._timingEvents=[],this._flushTime=(0,e.now)(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer])}event(t,e,n,r){const i=this._started?this.begin(t,e,r):void 0;let o=!1;const a=n();if(a&&"function"==typeof a.then)return o=!0,new Promise(((t,e)=>{a.then((async e=>{i&&await i.end(),t(e)}),(async t=>{i&&await i.end(),e(t)}))}));if(!o&&i){const t=i.end();if(t&&"function"==typeof t.then)return new Promise(((e,n)=>{t.then((()=>{e(a)}),(t=>{n(t)}))}))}return a}begin(t,n,r){if(!this._started)throw new Error("profiler is not started yet");if(void 0===r){const r=(0,e.now)();return this.flush(r),new u(t,n,r,(t=>this.endSync(t)))}{const e=r.beginTimer();return new u(t,n,0,(async t=>this.end(t)),e,r)}}async end(t){const e=await t.checkTimer();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new c(t.category,t.name,t.startTime,e)),this.flush(e))}endSync(t){const n=(0,e.now)();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new c(t.category,t.name,t.startTime,n)),this.flush(n))}logOneEvent(t){e.Logger.verbose(`Profiler.${t.category}`,`${(t.endTime-t.startTime).toFixed(2)}ms on event '${t.name}' at ${t.endTime.toFixed(2)}`)}flush(t){if(this._timingEvents.length-this._flushPointer>=this._flushBatchSize||t-this._flushTime>=this._flushIntervalInMilliseconds){for(const t=this._flushPointer;this._flushPointer<t+this._flushBatchSize&&this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer]);this._flushTime=(0,e.now)()}}get started(){return this._started}},e.now="undefined"!=typeof performance&&performance.now?()=>performance.now():Date.now},2644:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Model=void 0;const r=n(5686),i=n(1446),o=n(7070),a=n(9395),s=n(2517);var u=a.onnxruntime.experimental.fbs;e.Model=class{constructor(){}load(t,e,n){if(!n)try{return void this.loadFromOnnxFormat(t,e)}catch(t){if(void 0!==n)throw t}this.loadFromOrtFormat(t,e)}loadFromOnnxFormat(t,e){const n=i.onnx.ModelProto.decode(t);if(s.LongUtil.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map((t=>({domain:t.domain,version:s.LongUtil.longToNumber(t.version)}))),this._graph=o.Graph.from(n.graph,e)}loadFromOrtFormat(t,e){const n=new r.flatbuffers.ByteBuffer(t),i=u.InferenceSession.getRootAsInferenceSession(n).model();if(s.LongUtil.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let t=0;t<i.opsetImportLength();t++){const e=i.opsetImport(t);this._opsets.push({domain:null==e?void 0:e.domain(),version:s.LongUtil.longToNumber(e.version())})}this._graph=o.Graph.from(i.graph(),e)}get graph(){return this._graph}get opsets(){return this._opsets}}},782:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FLOAT_TYPES=e.INT_TYPES=e.NUMBER_TYPES=void 0,e.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],e.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],e.FLOAT_TYPES=["float32","float64"]},1047:(t,e)=>{"use strict";function n(t,e){if(e.endsWith("+")){const n=Number.parseInt(e.substring(0,e.length-1),10);return!isNaN(n)&&n<=t}if(2===e.split("-").length){const n=e.split("-"),r=Number.parseInt(n[0],10),i=Number.parseInt(n[1],10);return!isNaN(r)&&!isNaN(i)&&r<=t&&t<=i}return Number.parseInt(e,10)===t}Object.defineProperty(e,"__esModule",{value:!0}),e.resolveOperator=void 0,e.resolveOperator=function(t,e,r){for(const i of r){const r=i[0],o=i[1],a=i[2],s=i[3],u=i[4];if(t.opType===r)for(const t of e)if((t.domain===o||"ai.onnx"===t.domain&&""===o)&&n(t.version,a))return{opImpl:s,opInit:u}}throw new TypeError(`cannot resolve operator '${t.opType}' with opsets: ${e.map((t=>`${t.domain||"ai.onnx"} v${t.version}`)).join(", ")}`)}},9395:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.onnxruntime=void 0;const r=n(5686);var i,o;i=e.onnxruntime||(e.onnxruntime={}),function(t){let e;!function(t){t[t.UNDEFINED=0]="UNDEFINED",t[t.FLOAT=1]="FLOAT",t[t.INT=2]="INT",t[t.STRING=3]="STRING",t[t.TENSOR=4]="TENSOR",t[t.GRAPH=5]="GRAPH",t[t.FLOATS=6]="FLOATS",t[t.INTS=7]="INTS",t[t.STRINGS=8]="STRINGS",t[t.TENSORS=9]="TENSORS",t[t.GRAPHS=10]="GRAPHS",t[t.SPARSE_TENSOR=11]="SPARSE_TENSOR",t[t.SPARSE_TENSORS=12]="SPARSE_TENSORS"}(e=t.AttributeType||(t.AttributeType={}))}((o=i.experimental||(i.experimental={})).fbs||(o.fbs={})),function(t){!function(t){!function(t){let e;!function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.VALUE=1]="VALUE",t[t.PARAM=2]="PARAM"}(e=t.DimensionValueType||(t.DimensionValueType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.UNDEFINED=0]="UNDEFINED",t[t.FLOAT=1]="FLOAT",t[t.UINT8=2]="UINT8",t[t.INT8=3]="INT8",t[t.UINT16=4]="UINT16",t[t.INT16=5]="INT16",t[t.INT32=6]="INT32",t[t.INT64=7]="INT64",t[t.STRING=8]="STRING",t[t.BOOL=9]="BOOL",t[t.FLOAT16=10]="FLOAT16",t[t.DOUBLE=11]="DOUBLE",t[t.UINT32=12]="UINT32",t[t.UINT64=13]="UINT64",t[t.COMPLEX64=14]="COMPLEX64",t[t.COMPLEX128=15]="COMPLEX128",t[t.BFLOAT16=16]="BFLOAT16"}(e=t.TensorDataType||(t.TensorDataType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.Primitive=0]="Primitive",t[t.Fused=1]="Fused"}(e=t.NodeType||(t.NodeType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.NONE=0]="NONE",t[t.tensor_type=1]="tensor_type",t[t.sequence_type=2]="sequence_type",t[t.map_type=3]="map_type"}(e=t.TypeInfoValue||(t.TypeInfoValue={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsShape(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsShape(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}dim(e,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new t.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}dimLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}static startShape(t){t.startObject(1)}static addDim(t,e){t.addFieldOffset(0,e,0)}static createDimVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startDimVector(t,e){t.startVector(4,e,4)}static endShape(t){return t.endObject()}static createShape(t,e){return n.startShape(t),n.addDim(t,e),n.endShape(t)}}e.Shape=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimension(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimension(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}value(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}denotation(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimension(t){t.startObject(2)}static addValue(t,e){t.addFieldOffset(0,e,0)}static addDenotation(t,e){t.addFieldOffset(1,e,0)}static endDimension(t){return t.endObject()}static createDimension(t,e,r){return n.startDimension(t),n.addValue(t,e),n.addDenotation(t,r),n.endDimension(t)}}e.Dimension=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimensionValue(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimensionValue(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}dimType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt8(this.bb_pos+e):t.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}dimParam(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimensionValue(t){t.startObject(3)}static addDimType(e,n){e.addFieldInt8(0,n,t.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static addDimParam(t,e){t.addFieldOffset(2,e,0)}static endDimensionValue(t){return t.endObject()}static createDimensionValue(t,e,r,i){return n.startDimensionValue(t),n.addDimType(t,e),n.addDimValue(t,r),n.addDimParam(t,i),n.endDimensionValue(t)}}e.DimensionValue=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensorTypeAndShape(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensorTypeAndShape(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}elemType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}shape(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startTensorTypeAndShape(t){t.startObject(2)}static addElemType(e,n){e.addFieldInt32(0,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(t,e){t.addFieldOffset(1,e,0)}static endTensorTypeAndShape(t){return t.endObject()}static createTensorTypeAndShape(t,e,r){return n.startTensorTypeAndShape(t),n.addElemType(t,e),n.addShape(t,r),n.endTensorTypeAndShape(t)}}e.TensorTypeAndShape=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMapType(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMapType(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}keyType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}valueType(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startMapType(t){t.startObject(2)}static addKeyType(e,n){e.addFieldInt32(0,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(t,e){t.addFieldOffset(1,e,0)}static endMapType(t){return t.endObject()}static createMapType(t,e,r){return n.startMapType(t),n.addKeyType(t,e),n.addValueType(t,r),n.endMapType(t)}}e.MapType=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSequenceType(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSequenceType(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}elemType(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSequenceType(t){t.startObject(1)}static addElemType(t,e){t.addFieldOffset(0,e,0)}static endSequenceType(t){return t.endObject()}static createSequenceType(t,e){return n.startSequenceType(t),n.addElemType(t,e),n.endSequenceType(t)}}e.SequenceType=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){(t.fbs||(t.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(t,e,n,r){return t.prep(4,12),t.writeInt32(r),t.writeInt32(n),t.writeInt32(e),t.offset()}}}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNodeEdge(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNodeEdge(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}nodeIndex(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb_pos+t):0}inputEdges(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*e,this.bb):null}inputEdgesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}outputEdges(e,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*e,this.bb):null}outputEdgesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNodeEdge(t){t.startObject(3)}static addNodeIndex(t,e){t.addFieldInt32(0,e,0)}static addInputEdges(t,e){t.addFieldOffset(1,e,0)}static startInputEdgesVector(t,e){t.startVector(12,e,4)}static addOutputEdges(t,e){t.addFieldOffset(2,e,0)}static startOutputEdgesVector(t,e){t.startVector(12,e,4)}static endNodeEdge(t){return t.endObject()}static createNodeEdge(t,e,r,i){return n.startNodeEdge(t),n.addNodeIndex(t,e),n.addInputEdges(t,r),n.addOutputEdges(t,i),n.endNodeEdge(t)}}e.NodeEdge=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNode(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNode(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}sinceVersion(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):0}index(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint32(this.bb_pos+t):0}opType(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.NodeType.Primitive}executionProviderType(t){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__string(this.bb_pos+e,t):null}inputs(t,e){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}attributes(e,n){let r=this.bb.__offset(this.bb_pos,24);return r?(n||new t.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}attributesLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCounts(t){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.readInt32(this.bb.__vector(this.bb_pos+e)+4*t):0}inputArgCountsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCountsArray(){let t=this.bb.__offset(this.bb_pos,26);return t?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}implicitInputs(t,e){let n=this.bb.__offset(this.bb_pos,28);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}implicitInputsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNode(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDomain(t,e){t.addFieldOffset(2,e,0)}static addSinceVersion(t,e){t.addFieldInt32(3,e,0)}static addIndex(t,e){t.addFieldInt32(4,e,0)}static addOpType(t,e){t.addFieldOffset(5,e,0)}static addType(e,n){e.addFieldInt32(6,n,t.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(t,e){t.addFieldOffset(7,e,0)}static addInputs(t,e){t.addFieldOffset(8,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(9,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addAttributes(t,e){t.addFieldOffset(10,e,0)}static createAttributesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startAttributesVector(t,e){t.startVector(4,e,4)}static addInputArgCounts(t,e){t.addFieldOffset(11,e,0)}static createInputArgCountsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addInt32(e[n]);return t.endVector()}static startInputArgCountsVector(t,e){t.startVector(4,e,4)}static addImplicitInputs(t,e){t.addFieldOffset(12,e,0)}static createImplicitInputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startImplicitInputsVector(t,e){t.startVector(4,e,4)}static endNode(t){return t.endObject()}static createNode(t,e,r,i,o,a,s,u,c,l,p,f,d,h){return n.startNode(t),n.addName(t,e),n.addDocString(t,r),n.addDomain(t,i),n.addSinceVersion(t,o),n.addIndex(t,a),n.addOpType(t,s),n.addType(t,u),n.addExecutionProviderType(t,c),n.addInputs(t,l),n.addOutputs(t,p),n.addAttributes(t,f),n.addInputArgCounts(t,d),n.addImplicitInputs(t,h),n.endNode(t)}}e.Node=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsValueInfo(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsValueInfo(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startValueInfo(t){t.startObject(3)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldOffset(2,e,0)}static endValueInfo(t){return t.endObject()}static createValueInfo(t,e,r,i){return n.startValueInfo(t),n.addName(t,e),n.addDocString(t,r),n.addType(t,i),n.endValueInfo(t)}}e.ValueInfo=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTypeInfo(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTypeInfo(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}denotation(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}valueType(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb_pos+e):t.experimental.fbs.TypeInfoValue.NONE}value(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}static startTypeInfo(t){t.startObject(3)}static addDenotation(t,e){t.addFieldOffset(0,e,0)}static addValueType(e,n){e.addFieldInt8(1,n,t.experimental.fbs.TypeInfoValue.NONE)}static addValue(t,e){t.addFieldOffset(2,e,0)}static endTypeInfo(t){return t.endObject()}static createTypeInfo(t,e,r,i){return n.startTypeInfo(t),n.addDenotation(t,e),n.addValueType(t,r),n.addValue(t,i),n.endTypeInfo(t)}}e.TypeInfo=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){class e{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsOperatorSetId(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsOperatorSetId(t,n){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}domain(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}version(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}static startOperatorSetId(t){t.startObject(2)}static addDomain(t,e){t.addFieldOffset(0,e,0)}static addVersion(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static endOperatorSetId(t){return t.endObject()}static createOperatorSetId(t,n,r){return e.startOperatorSetId(t),e.addDomain(t,n),e.addVersion(t,r),e.endOperatorSetId(t)}}t.OperatorSetId=e}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensor(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensor(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}dataType(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}rawData(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}rawDataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}rawDataArray(){let t=this.bb.__offset(this.bb_pos,12);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}stringData(t,e){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}stringDataLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}static startTensor(t){t.startObject(6)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static addDataType(e,n){e.addFieldInt32(3,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(t,e){t.addFieldOffset(4,e,0)}static createRawDataVector(t,e){t.startVector(1,e.length,1);for(let n=e.length-1;n>=0;n--)t.addInt8(e[n]);return t.endVector()}static startRawDataVector(t,e){t.startVector(1,e,1)}static addStringData(t,e){t.addFieldOffset(5,e,0)}static createStringDataVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startStringDataVector(t,e){t.startVector(4,e,4)}static endTensor(t){return t.endObject()}static createTensor(t,e,r,i,o,a,s){return n.startTensor(t),n.addName(t,e),n.addDocString(t,r),n.addDims(t,i),n.addDataType(t,o),n.addRawData(t,a),n.addStringData(t,s),n.endTensor(t)}}e.Tensor=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSparseTensor(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSparseTensor(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}values(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}indices(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSparseTensor(t){t.startObject(3)}static addValues(t,e){t.addFieldOffset(0,e,0)}static addIndices(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static endSparseTensor(t){return t.endObject()}static createSparseTensor(t,e,r,i){return n.startSparseTensor(t),n.addValues(t,e),n.addIndices(t,r),n.addDims(t,i),n.endSparseTensor(t)}}e.SparseTensor=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsAttribute(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsAttribute(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.AttributeType.UNDEFINED}f(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readFloat32(this.bb_pos+t):0}i(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}s(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}t(e){let n=this.bb.__offset(this.bb_pos,16);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}g(e){let n=this.bb.__offset(this.bb_pos,18);return n?(e||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}floats(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.readFloat32(this.bb.__vector(this.bb_pos+e)+4*t):0}floatsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}floatsArray(){let t=this.bb.__offset(this.bb_pos,20);return t?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}ints(t){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}intsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}strings(t,e){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}stringsLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}tensors(e,n){let r=this.bb.__offset(this.bb_pos,26);return r?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}tensorsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}graphs(e,n){let r=this.bb.__offset(this.bb_pos,28);return r?(n||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}graphsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startAttribute(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(e,n){e.addFieldInt32(2,n,t.experimental.fbs.AttributeType.UNDEFINED)}static addF(t,e){t.addFieldFloat32(3,e,0)}static addI(t,e){t.addFieldInt64(4,e,t.createLong(0,0))}static addS(t,e){t.addFieldOffset(5,e,0)}static addT(t,e){t.addFieldOffset(6,e,0)}static addG(t,e){t.addFieldOffset(7,e,0)}static addFloats(t,e){t.addFieldOffset(8,e,0)}static createFloatsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addFloat32(e[n]);return t.endVector()}static startFloatsVector(t,e){t.startVector(4,e,4)}static addInts(t,e){t.addFieldOffset(9,e,0)}static createIntsVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startIntsVector(t,e){t.startVector(8,e,8)}static addStrings(t,e){t.addFieldOffset(10,e,0)}static createStringsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startStringsVector(t,e){t.startVector(4,e,4)}static addTensors(t,e){t.addFieldOffset(11,e,0)}static createTensorsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startTensorsVector(t,e){t.startVector(4,e,4)}static addGraphs(t,e){t.addFieldOffset(12,e,0)}static createGraphsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startGraphsVector(t,e){t.startVector(4,e,4)}static endAttribute(t){return t.endObject()}static createAttribute(t,e,r,i,o,a,s,u,c,l,p,f,d,h){return n.startAttribute(t),n.addName(t,e),n.addDocString(t,r),n.addType(t,i),n.addF(t,o),n.addI(t,a),n.addS(t,s),n.addT(t,u),n.addG(t,c),n.addFloats(t,l),n.addInts(t,p),n.addStrings(t,f),n.addTensors(t,d),n.addGraphs(t,h),n.endAttribute(t)}}e.Attribute=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsGraph(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsGraph(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}initializers(e,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}initializersLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeArgs(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}nodeArgsLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}nodes(e,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new t.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}nodesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}maxNodeIndex(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readUint32(this.bb_pos+t):0}nodeEdges(e,n){let r=this.bb.__offset(this.bb_pos,12);return r?(n||new t.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}nodeEdgesLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}inputs(t,e){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__vector_len(this.bb_pos+t):0}sparseInitializers(e,n){let r=this.bb.__offset(this.bb_pos,18);return r?(n||new t.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}sparseInitializersLength(){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__vector_len(this.bb_pos+t):0}static startGraph(t){t.startObject(8)}static addInitializers(t,e){t.addFieldOffset(0,e,0)}static createInitializersVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startInitializersVector(t,e){t.startVector(4,e,4)}static addNodeArgs(t,e){t.addFieldOffset(1,e,0)}static createNodeArgsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startNodeArgsVector(t,e){t.startVector(4,e,4)}static addNodes(t,e){t.addFieldOffset(2,e,0)}static createNodesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startNodesVector(t,e){t.startVector(4,e,4)}static addMaxNodeIndex(t,e){t.addFieldInt32(3,e,0)}static addNodeEdges(t,e){t.addFieldOffset(4,e,0)}static createNodeEdgesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startNodeEdgesVector(t,e){t.startVector(4,e,4)}static addInputs(t,e){t.addFieldOffset(5,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(6,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addSparseInitializers(t,e){t.addFieldOffset(7,e,0)}static createSparseInitializersVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startSparseInitializersVector(t,e){t.startVector(4,e,4)}static endGraph(t){return t.endObject()}static createGraph(t,e,r,i,o,a,s,u,c){return n.startGraph(t),n.addInitializers(t,e),n.addNodeArgs(t,r),n.addNodes(t,i),n.addMaxNodeIndex(t,o),n.addNodeEdges(t,a),n.addInputs(t,s),n.addOutputs(t,u),n.addSparseInitializers(t,c),n.endGraph(t)}}e.Graph=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsModel(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsModel(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}irVersion(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}opsetImport(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}opsetImportLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}producerName(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}producerVersion(t){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,t):null}modelVersion(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}docString(t){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__string(this.bb_pos+e,t):null}graph(e){let n=this.bb.__offset(this.bb_pos,18);return n?(e||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}graphDocString(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__string(this.bb_pos+e,t):null}static startModel(t){t.startObject(9)}static addIrVersion(t,e){t.addFieldInt64(0,e,t.createLong(0,0))}static addOpsetImport(t,e){t.addFieldOffset(1,e,0)}static createOpsetImportVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startOpsetImportVector(t,e){t.startVector(4,e,4)}static addProducerName(t,e){t.addFieldOffset(2,e,0)}static addProducerVersion(t,e){t.addFieldOffset(3,e,0)}static addDomain(t,e){t.addFieldOffset(4,e,0)}static addModelVersion(t,e){t.addFieldInt64(5,e,t.createLong(0,0))}static addDocString(t,e){t.addFieldOffset(6,e,0)}static addGraph(t,e){t.addFieldOffset(7,e,0)}static addGraphDocString(t,e){t.addFieldOffset(8,e,0)}static endModel(t){return t.endObject()}static createModel(t,e,r,i,o,a,s,u,c,l){return n.startModel(t),n.addIrVersion(t,e),n.addOpsetImport(t,r),n.addProducerName(t,i),n.addProducerVersion(t,o),n.addDomain(t,a),n.addModelVersion(t,s),n.addDocString(t,u),n.addGraph(t,c),n.addGraphDocString(t,l),n.endModel(t)}}e.Model=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){class e{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsKernelCreateInfos(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKernelCreateInfos(t,n){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}nodeIndices(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb.__vector(this.bb_pos+e)+4*t):0}nodeIndicesLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeIndicesArray(){let t=this.bb.__offset(this.bb_pos,4);return t?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}kernelDefHashes(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}kernelDefHashesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startKernelCreateInfos(t){t.startObject(2)}static addNodeIndices(t,e){t.addFieldOffset(0,e,0)}static createNodeIndicesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addInt32(e[n]);return t.endVector()}static startNodeIndicesVector(t,e){t.startVector(4,e,4)}static addKernelDefHashes(t,e){t.addFieldOffset(1,e,0)}static createKernelDefHashesVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startKernelDefHashesVector(t,e){t.startVector(8,e,8)}static endKernelCreateInfos(t){return t.endObject()}static createKernelCreateInfos(t,n,r){return e.startKernelCreateInfos(t),e.addNodeIndices(t,n),e.addKernelDefHashes(t,r),e.endKernelCreateInfos(t)}}t.KernelCreateInfos=e}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSubGraphSessionState(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSubGraphSessionState(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}graphId(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}sessionState(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSubGraphSessionState(t){t.startObject(2)}static addGraphId(t,e){t.addFieldOffset(0,e,0)}static addSessionState(t,e){t.addFieldOffset(1,e,0)}static endSubGraphSessionState(t){let e=t.endObject();return t.requiredField(e,4),e}static createSubGraphSessionState(t,e,r){return n.startSubGraphSessionState(t),n.addGraphId(t,e),n.addSessionState(t,r),n.endSubGraphSessionState(t)}}e.SubGraphSessionState=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSessionState(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSessionState(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}kernels(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}subGraphSessionStates(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}subGraphSessionStatesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSessionState(t){t.startObject(2)}static addKernels(t,e){t.addFieldOffset(0,e,0)}static addSubGraphSessionStates(t,e){t.addFieldOffset(1,e,0)}static createSubGraphSessionStatesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startSubGraphSessionStatesVector(t,e){t.startVector(4,e,4)}static endSessionState(t){return t.endObject()}static createSessionState(t,e,r){return n.startSessionState(t),n.addKernels(t,e),n.addSubGraphSessionStates(t,r),n.endSessionState(t)}}e.SessionState=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsInferenceSession(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInferenceSession(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static bufferHasIdentifier(t){return t.__has_identifier("ORTM")}ortVersion(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}model(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}sessionState(e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startInferenceSession(t){t.startObject(3)}static addOrtVersion(t,e){t.addFieldOffset(0,e,0)}static addModel(t,e){t.addFieldOffset(1,e,0)}static addSessionState(t,e){t.addFieldOffset(2,e,0)}static endInferenceSession(t){return t.endObject()}static finishInferenceSessionBuffer(t,e){t.finish(e,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(t,e){t.finish(e,"ORTM",!0)}static createInferenceSession(t,e,r,i){return n.startInferenceSession(t),n.addOrtVersion(t,e),n.addModel(t,r),n.addSessionState(t,i),n.endInferenceSession(t)}}e.InferenceSession=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={}))},7448:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.OnnxjsSessionHandler=void 0;const r=n(1670),i=n(9162);e.OnnxjsSessionHandler=class{constructor(t){this.session=t,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(t,e,n){const o=new Map;for(const e in t)if(Object.hasOwnProperty.call(t,e)){const n=t[e];o.set(e,new i.Tensor(n.dims,n.type,void 0,void 0,n.data))}const a=await this.session.run(o),s={};return a.forEach(((t,e)=>{s[e]=new r.Tensor(t.type,t.data,t.dims)})),s}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Session=void 0;const r=n(7067),i=n(1296),o=n(7091),a=n(1036),s=n(6231),u=n(2644);e.Session=class{constructor(t={}){this._initialized=!1,this.backendHint=t.backendHint,this.profiler=s.Profiler.create(t.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(t,e,n){await this.profiler.event("session","Session.loadModel",(async()=>{const a=await(0,o.resolveBackend)(this.backendHint);if(this.sessionHandler=a.createSessionHandler(this.context),this._model=new u.Model,"string"==typeof t){const e=t.endsWith(".ort");if("undefined"==typeof fetch){const n=await(0,i.promisify)(r.readFile)(t);this.initialize(n,e)}else{const n=await fetch(t),r=await n.arrayBuffer();this.initialize(new Uint8Array(r),e)}}else if(ArrayBuffer.isView(t))this.initialize(t);else{const r=new Uint8Array(t,e||0,n||t.byteLength);this.initialize(r)}}))}initialize(t,e){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",(()=>{const n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(t,n,e),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new a.ExecutionPlan(this._model.graph,this._ops,this.profiler)})),this._initialized=!0}async run(t){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",(async()=>{const e=this.normalizeAndValidateInputs(t),n=await this._executionPlan.execute(this.sessionHandler,e);return this.createOutput(n)}))}normalizeAndValidateInputs(t){const e=this._model.graph.getInputNames();if(Array.isArray(t)){if(t.length!==e.length)throw new Error(`incorrect input array length: expected ${e.length} but got ${t.length}`)}else{if(t.size!==e.length)throw new Error(`incorrect input map size: expected ${e.length} but got ${t.size}`);const n=new Array(t.size);let r=0;for(let i=0;i<e.length;++i){const o=t.get(e[i]);if(!o)throw new Error(`missing input tensor for: '${name}'`);n[r++]=o}t=n}if(this.context.graphInputTypes&&0!==this.context.graphInputTypes.length&&this.context.graphInputDims&&0!==this.context.graphInputDims.length)this.validateInputTensorDims(this.context.graphInputDims,t,!1);else{const e=this._model.graph.getInputIndices(),n=this._model.graph.getValues(),r=new Array(e.length);for(let i=0;i<e.length;++i){const o=n[e[i]];r[i]=o.type.shape.dims,this.context.graphInputTypes.push(o.type.tensorType),this.context.graphInputDims.push(t[i].dims)}this.validateInputTensorDims(r,t,!0)}return this.validateInputTensorTypes(this.context.graphInputTypes,t),t}validateInputTensorTypes(t,e){for(let n=0;n<e.length;n++){const r=t[n],i=e[n].type;if(r!==i)throw new Error(`input tensor[${n}] check failed: expected type '${r}' but got ${i}`)}}validateInputTensorDims(t,e,n){for(let r=0;r<e.length;r++){const i=t[r],o=e[r].dims;if(!this.compareTensorDims(i,o,n))throw new Error(`input tensor[${r}] check failed: expected shape '[${i.join(",")}]' but got [${o.join(",")}]`)}}compareTensorDims(t,e,n){if(t.length!==e.length)return!1;for(let r=0;r<t.length;++r)if(t[r]!==e[r]&&(!n||0!==t[r]))return!1;return!0}createOutput(t){const e=this._model.graph.getOutputNames();if(t.length!==e.length)throw new Error("expected number of outputs do not match number of generated outputs");const n=new Map;for(let r=0;r<e.length;++r)n.set(e[r],t[r]);return n}initializeOps(t){const e=t.getNodes();this._ops=new Array(e.length);for(let n=0;n<e.length;n++)this._ops[n]=this.sessionHandler.resolve(e[n],this._model.opsets,t)}}},9162:function(t,e,n){"use strict";var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Tensor=void 0;const i=n(3442),o=r(n(3720)),a=n(1446),s=n(9395),u=n(2517);var c=s.onnxruntime.experimental.fbs;class l{get data(){if(void 0===this.cache){const t=this.dataProvider(this.dataId);if(t.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=t}return this.cache}get stringData(){if("string"!==this.type)throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if("string"!==this.type)return this.data;throw new TypeError("type cannot be non-number (string)")}get(t){return this.data[u.ShapeUtil.indicesToOffset(t,this.strides)]}set(t,e){this.data[u.ShapeUtil.indicesToOffset(t,this.strides)]=e}async getData(){return void 0===this.cache&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=u.ShapeUtil.computeStrides(this.dims)),this._strides}constructor(t,e,n,r,o,a=i.Guid.create()){this.dims=t,this.type=e,this.dataProvider=n,this.asyncDataProvider=r,this.cache=o,this.dataId=a,this.size=u.ShapeUtil.validateDimsAndCalcSize(t);const s=this.size,c=void 0===n&&void 0===r&&void 0===o;if(void 0!==o&&o.length!==s)throw new RangeError("Input dims doesn't match data length.");if("string"===e){if(!(void 0===o||Array.isArray(o)&&o.every((t=>"string"==typeof t))))throw new TypeError("cache should be a string array");c&&(this.cache=new Array(s))}else{if(void 0!==o){const t=f(e);if(!(o instanceof t))throw new TypeError(`cache should be type ${t.name}`)}if(c){const t=new ArrayBuffer(s*function(t){switch(t){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${t}`)}}(e));this.cache=function(t,e){return new(f(e))(t)}(t,e)}}}static fromProto(t){if(!t)throw new Error("cannot construct Value from an empty tensor");const e=u.ProtoUtil.tensorDataTypeFromProto(t.dataType),n=u.ProtoUtil.tensorDimsFromProto(t.dims),r=new l(n,e);if("string"===e)t.stringData.forEach(((t,e)=>{r.data[e]=(0,u.decodeUtf8String)(t)}));else if(t.rawData&&"number"==typeof t.rawData.byteLength&&t.rawData.byteLength>0){const e=r.data,n=new DataView(t.rawData.buffer,t.rawData.byteOffset,t.rawData.byteLength),i=p(t.dataType),o=t.rawData.byteLength/i;if(t.rawData.byteLength%i!=0)throw new Error("invalid buffer length");if(e.length!==o)throw new Error("buffer length mismatch");for(let r=0;r<o;r++){const o=h(n,t.dataType,r*i);e[r]=o}}else{let e;switch(t.dataType){case a.onnx.TensorProto.DataType.FLOAT:e=t.floatData;break;case a.onnx.TensorProto.DataType.INT32:case a.onnx.TensorProto.DataType.INT16:case a.onnx.TensorProto.DataType.UINT16:case a.onnx.TensorProto.DataType.INT8:case a.onnx.TensorProto.DataType.UINT8:case a.onnx.TensorProto.DataType.BOOL:e=t.int32Data;break;case a.onnx.TensorProto.DataType.INT64:e=t.int64Data;break;case a.onnx.TensorProto.DataType.DOUBLE:e=t.doubleData;break;case a.onnx.TensorProto.DataType.UINT32:case a.onnx.TensorProto.DataType.UINT64:e=t.uint64Data;break;default:throw new Error("unspecific error")}if(null==e)throw new Error("failed to populate data from a tensorproto value");const n=r.data;if(n.length!==e.length)throw new Error("array length mismatch");for(let r=0;r<e.length;r++){const i=e[r];o.default.isLong(i)?n[r]=d(i,t.dataType):n[r]=i}}return r}static fromData(t,e,n){return new l(e,n,void 0,void 0,t)}static fromOrtTensor(t){if(!t)throw new Error("cannot construct Value from an empty tensor");const e=u.ProtoUtil.tensorDimsFromORTFormat(t),n=u.ProtoUtil.tensorDataTypeFromProto(t.dataType()),r=new l(e,n);if("string"===n)for(let e=0;e<t.stringDataLength();e++)r.data[e]=t.stringData(e);else if(t.rawDataArray()&&"number"==typeof t.rawDataLength()&&t.rawDataLength()>0){const e=r.data,n=new DataView(t.rawDataArray().buffer,t.rawDataArray().byteOffset,t.rawDataLength()),i=p(t.dataType()),o=t.rawDataLength()/i;if(t.rawDataLength()%i!=0)throw new Error("invalid buffer length");if(e.length!==o)throw new Error("buffer length mismatch");for(let r=0;r<o;r++){const o=h(n,t.dataType(),r*i);e[r]=o}}return r}}function p(t){switch(t){case a.onnx.TensorProto.DataType.UINT8:case a.onnx.TensorProto.DataType.INT8:case a.onnx.TensorProto.DataType.BOOL:return 1;case a.onnx.TensorProto.DataType.UINT16:case a.onnx.TensorProto.DataType.INT16:return 2;case a.onnx.TensorProto.DataType.FLOAT:case a.onnx.TensorProto.DataType.INT32:case a.onnx.TensorProto.DataType.UINT32:return 4;case a.onnx.TensorProto.DataType.INT64:case a.onnx.TensorProto.DataType.DOUBLE:case a.onnx.TensorProto.DataType.UINT64:return 8;default:throw new Error(`cannot calculate sizeof() on type ${a.onnx.TensorProto.DataType[t]}`)}}function f(t){switch(t){case"bool":case"uint8":return Uint8Array;case"int8":return Int8Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"float32":return Float32Array;case"float64":return Float64Array;default:throw new Error("unspecified error")}}function d(t,e){if(e===a.onnx.TensorProto.DataType.INT64||e===c.TensorDataType.INT64){if(t.greaterThanOrEqual(2147483648)||t.lessThan(-2147483648))throw new TypeError("int64 is not supported")}else{if(e!==a.onnx.TensorProto.DataType.UINT32&&e!==c.TensorDataType.UINT32&&e!==a.onnx.TensorProto.DataType.UINT64&&e!==c.TensorDataType.UINT64)throw new TypeError(`not a LONG type: ${a.onnx.TensorProto.DataType[e]}`);if(t.greaterThanOrEqual(4294967296)||t.lessThan(0))throw new TypeError("uint64 is not supported")}return t.toNumber()}function h(t,e,n){switch(e){case a.onnx.TensorProto.DataType.BOOL:case a.onnx.TensorProto.DataType.UINT8:return t.getUint8(n);case a.onnx.TensorProto.DataType.INT8:return t.getInt8(n);case a.onnx.TensorProto.DataType.UINT16:return t.getUint16(n,!0);case a.onnx.TensorProto.DataType.INT16:return t.getInt16(n,!0);case a.onnx.TensorProto.DataType.FLOAT:return t.getFloat32(n,!0);case a.onnx.TensorProto.DataType.INT32:return t.getInt32(n,!0);case a.onnx.TensorProto.DataType.UINT32:return t.getUint32(n,!0);case a.onnx.TensorProto.DataType.INT64:return d(o.default.fromBits(t.getUint32(n,!0),t.getUint32(n+4,!0),!1),e);case a.onnx.TensorProto.DataType.DOUBLE:return t.getFloat64(n,!0);case a.onnx.TensorProto.DataType.UINT64:return d(o.default.fromBits(t.getUint32(n,!0),t.getUint32(n+4,!0),!0),e);default:throw new Error(`cannot read from DataView for type ${a.onnx.TensorProto.DataType[e]}`)}}e.Tensor=l},2517:function(t,e,n){"use strict";var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.decodeUtf8String=e.MAX_CLIP=e.MIN_CLIP=e.PoolConvUtil=e.ReduceUtil=e.SplitUtil=e.MathUtil=e.ShapeUtil=e.LongUtil=e.ProtoUtil=e.GemmUtil=e.arrayCopyHelper=e.BroadcastUtil=e.MatMulUtil=e.ArrayUtil=e.assert=e.checkInputsShape=void 0;const i=n(5686),o=r(n(3720)),a=n(1446),s=n(9162);e.checkInputsShape=function(t,...e){if(!t||t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].dims||t[n].dims.length!==e[n])return!1;return!0},e.assert=function(t,e){if(!t)throw new Error("string"==typeof e?e:e())},e.ArrayUtil=class{static arraysEqual(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}};class u{static preprocessInputShapes(t,e){return[1===t.length?[1,t[0]]:t,1===e.length?[e[0],1]:e]}static postprocessOutputShape(t,e,n){1===e&&t.splice(t.length-2,1),1===n&&t.pop()}static calcMatMulShape(t,e){return t[1]!==e[0]?void 0:[t[0],e[1]]}}e.MatMulUtil=u;class c{static calcShape(t,e,n=!1){const r=t.length,i=e.length;if(0===r)return e;if(0===i)return t;const o=Math.max(t.length,e.length),a=new Array(o);if(n){if(r<2||i<2)return;const n=u.calcMatMulShape([t[r-2],t[r-1]],[e[i-2],e[i-1]]);if(void 0===n)return;[a[o-2],a[o-1]]=n}for(let s=n?3:1;s<=o;s++){const n=r-s<0?1:t[r-s],u=i-s<0?1:e[i-s];if(n!==u&&n>1&&u>1)return;a[o-s]=Math.max(n,u)}return a}static index(t,e){const n=new Array(e.length);return c.fillIndex(t,e,n),n}static fillIndex(t,e,n){const r=t.length-e.length;for(let i=0;i<e.length;i++)n[i]=t[r+i]%e[i]}static calc(t,e,n,r,i){const o=c.calcShape(t.dims,e.dims);if(o){if(r&&!f.areEqual(o,t.dims))return;const a=f.size(o),u=r?t:new s.Tensor(o,i||t.type);if(0===o.length)u.set([],n(t.get([]),e.get([])));else{const r=new Array(o.length),i=new Array(t.dims.length),s=new Array(e.dims.length);let l,p=0,f=0,d=!1,h=!1;0===t.dims.length&&(p=t.get([]),d=!0),0===e.dims.length&&(f=e.get([]),h=!0);for(let g=0;g<a;g++){l=g;for(let t=o.length-1;t>=0;t--)r[t]=l%o[t],l=Math.floor(l/o[t]);d||(c.fillIndex(r,t.dims,i),p=t.get(i)),h||(c.fillIndex(r,e.dims,s),f=e.get(s)),u.set(r,n(p,f))}}return u}}static isValidBroadcast(t,e){const n=t.length,r=e.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(1!==t[n-i]&&t[n-i]!==e[r-i])return!1;return!0}static getBroadcastDims(t,e){const n=t.length,r=[];for(let i=0;i<n;i++){const o=n-1-i,a=t[o]||1;(e[e.length-1-i]||1)>1&&1===a&&r.unshift(o)}return r}}e.BroadcastUtil=c,e.arrayCopyHelper=function(t,e,n,r,i){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)t[n+o]=e[r+o]},e.GemmUtil=class{static getShapeOfGemmResult(t,e,n,r,i){if(2!==t.length||2!==n.length)throw new Error("shape need to be of size 2");let o,a,s;e?(o=t[1],a=t[0]):(o=t[0],a=t[1]);let u=-1;if(r?(s=n[0],u=1):(s=n[1],u=0),n[u]!==a)throw new Error("dimension mismatch");if(o<=0||s<=0||a<=0)throw new Error("invalid shape specified");if(i&&!c.isValidBroadcast(i,[o,s]))throw new Error("gemm: invalid bias shape for broadcast");return[o,s,a]}};class l{static tensorDataTypeFromProto(t){switch(t){case a.onnx.TensorProto.DataType.INT8:return"int8";case a.onnx.TensorProto.DataType.UINT8:return"uint8";case a.onnx.TensorProto.DataType.BOOL:return"bool";case a.onnx.TensorProto.DataType.INT16:return"int16";case a.onnx.TensorProto.DataType.UINT16:return"uint16";case a.onnx.TensorProto.DataType.INT32:return"int32";case a.onnx.TensorProto.DataType.UINT32:return"uint32";case a.onnx.TensorProto.DataType.FLOAT:return"float32";case a.onnx.TensorProto.DataType.DOUBLE:return"float64";case a.onnx.TensorProto.DataType.STRING:return"string";case a.onnx.TensorProto.DataType.INT64:return"int32";case a.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${a.onnx.TensorProto.DataType[t]}`)}}static tensorDataTypeStringToEnum(t){switch(t){case"int8":return a.onnx.TensorProto.DataType.INT8;case"uint8":return a.onnx.TensorProto.DataType.UINT8;case"bool":return a.onnx.TensorProto.DataType.BOOL;case"int16":return a.onnx.TensorProto.DataType.INT16;case"uint16":return a.onnx.TensorProto.DataType.UINT16;case"int32":return a.onnx.TensorProto.DataType.INT32;case"uint32":return a.onnx.TensorProto.DataType.UINT32;case"float32":return a.onnx.TensorProto.DataType.FLOAT;case"float64":return a.onnx.TensorProto.DataType.DOUBLE;case"string":return a.onnx.TensorProto.DataType.STRING;case"int64":return a.onnx.TensorProto.DataType.INT64;case"uint64":return a.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${t}`)}}static tensorDimsFromProto(t){return t.map((t=>o.default.isLong(t)?t.toNumber():t))}static tensorValueTypeFromProto(t){return{tensorType:l.tensorDataTypeFromProto(t.elemType),shape:{dims:l.tensorDimsFromProto(t.shape.dim.map((t=>t.dimValue)))}}}static tensorDimsFromORTFormat(t){const e=[];for(let n=0;n<t.dimsLength();n++)e.push(p.longToNumber(t.dims(n)));return e}static tensorAttributesFromORTFormat(t){const e=[];for(let n=0;n<t.attributesLength();n++)e.push(t.attributes(n));return e}}e.ProtoUtil=l;class p{static longToNumber(t,e){return o.default.isLong(t)?t.toNumber():t instanceof i.flatbuffers.Long?o.default.fromValue({low:t.low,high:t.high,unsigned:null!=e&&e}).toNumber():t}static isLong(t){return o.default.isLong(t)||t instanceof i.flatbuffers.Long}}e.LongUtil=p;class f{static size(t){return f.getSizeFromDimensionRange(t,0,t.length)}static sizeFromDimension(t,e){if(e<0||e>t.length)throw new Error(`invalid dimension of ${e} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return f.getSizeFromDimensionRange(t,e,t.length)}static sizeToDimension(t,e){if(e<0||e>t.length)throw new Error(`invalid dimension of ${e} for sizeToDimension as Tensor has ${t.length} dimensions.`);return f.getSizeFromDimensionRange(t,0,e)}static getSizeFromDimensionRange(t,e,n){let r=1;for(let i=e;i<n;i++){if(t[i]<=0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");r*=t[i]}return r}static computeStrides(t){const e=t.length;if(0===e)return[];if(1===e)return[1];const n=new Array(e);n[e-1]=1,n[e-2]=t[e-1];for(let r=e-3;r>=0;--r)n[r]=n[r+1]*t[r+1];return n}static transpose(t){return t.slice().reverse()}static indicesToOffset(t,e,n){void 0===n&&(n=t.length);let r=0;for(let i=0;i<n;++i)r+=e[i]*t[i];return r}static offsetToIndices(t,e){const n=e.length;if(0===n)return[];if(1===n)return[t*e[0]];const r=new Array(e.length);for(let n=0;n<r.length-1;++n)r[n]=Math.floor(t/e[n]),t-=r[n]*e[n];return r[r.length-1]=t,r}static normalizeAxis(t,e){if(t<-e&&t>=e)throw new Error("unsupported axis for this operation.");return t<0?t+e:t}static normalizeAxes(t,e){return t.map((t=>this.normalizeAxis(t,e)))}static incrementIndex(t,e,n){if(0===e.length||0===t.length)throw new Error("Index incrementing unsupported for scalar Tensor");if(void 0===n)n=e.length;else if(n<=0||n>e.length)throw new Error("Incorrect axis to increment on");for(let r=n-1;r>=0&&(t[r]++,!(t[r]<e[r]));--r)t[r]=0}static calculateReshapedDims(t,e){if(0===e.length){if(0===t.length||1===f.size(t))return[];throw new Error("cannot reshape to a scalar Tensor")}const n=e.length,r=new Array(n);let i=-1,o=1;for(let a=0;a<n;a++){if(e[a]<-1)throw new Error("a dimension in shape hints cannot be less than -1");if(-1===e[a]){if(-1!==i)throw new Error("at most one dimension in shape hints can be -1");i=a}else{if(0===e[a]){if(a>=t.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");r[a]=t[a]}else r[a]=e[a];o*=r[a]}}const a=f.size(t);if(-1!==i){if(a%o!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t}] Output shape: [${e}]`);r[i]=a/o}else if(o!==a)throw new Error("reshapedDims and originalDims don't have matching sizes");return r}static sortBasedOnPerm(t,e){return e?e.map((e=>t[e])):t.slice().reverse()}static padShape(t,e){const n=t.length;return t.map(((t,r)=>t+e[r]+e[r+n]))}static areEqual(t,e){return t.length===e.length&&t.every(((t,n)=>t===e[n]))}static validateDimsAndCalcSize(t){if(t.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let e=1;for(const n of t){if(!Number.isInteger(n))throw new TypeError(`Invalid shape: ${n} is not an integer`);if(n<0||n>2147483647)throw new TypeError(`Invalid shape: length ${n} is not allowed`);e*=n}return e}static flattenShape(t,e){e<0&&(e+=t.length);const n=t.reduce(((t,e)=>t*e),1),r=t.slice(e).reduce(((t,e)=>t*e),1);return[n/r,r]}static squeezeShape(t,e){const n=new Array;e=f.normalizeAxes(e,t.length);for(let r=0;r<t.length;r++){const i=e.indexOf(r)>=0;if(i&&1!==t[r])throw new Error("squeeze an axis of size different than 1");(0===e.length&&t[r]>1||e.length>0&&!i)&&n.push(t[r])}return n}static unsqueezeShape(t,e){const n=new Array(t.length+e.length);n.fill(0);for(let t=0;t<e.length;t++){const r=f.normalizeAxis(e[t],n.length);if(r>=n.length)throw new Error("'axes' has an out of range axis");if(0!==n[r])throw new Error("'axes' has a duplicate axis");n[r]=1}let r=0;for(let e=0;e<n.length;e++)0===n[e]&&(n[e]=t[r++]);if(r!==t.length)throw new Error("the unsqueezed dimension could not be established");return n}}e.ShapeUtil=f,e.MathUtil=class{static sqr(t,e,n,r,i){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)t[n+o]+=Math.pow(e[r+o],2)}static axpy(t,e,n,r,i,o){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let a=0;a<i;a++)t[n+a]+=o*e[r+a]}static powx(t,e,n,r,i,o){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let a=0;a<i;a++)t[n+a]=Math.pow(e[r+a],o)}static mul(t,e,n,r,i){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)t[n+o]=e[r+o]*t[n+o]}};class d{static splitShape(t,e,n,r){if(0===n.length){if(!r)throw new Error("need to know number of outputs when the 'split' attribute is not specified");d.determineSplit(t[e],r,n)}const i=[],o=[0];for(let r=0;r<n.length;++r){0!==r&&o.push(o[r-1]+n[r-1]);const a=t.slice();a[e]=n[r],i.push(a)}return[i,o]}static determineSplit(t,e,n){if(t%e!=0)throw new Error("cannot split tensor to equal sized parts");for(let r=0;r<e;++r)n.push(t/e)}}e.SplitUtil=d;class h{static calcReduce(t,e,n,r,i){const o=t.dims.slice(0);0===e.length&&o.forEach(((t,n)=>e.push(n)));const a=h.calcReduceShape(o,e,!0),u=f.size(a),l=new s.Tensor(a,t.type),p=f.computeStrides(a),d=f.computeStrides(o),g=new Array(o.length);for(let n=0;n<u;n++){const a=f.offsetToIndices(n,p);c.fillIndex(a,o,g),l.set(a,h.calcReduceByAxis(t.numberData,e,o,0,f.indicesToOffset(g,d),r,i))}return n?l:new s.Tensor(h.calcReduceShape(o,e,n),l.type,void 0,void 0,l.data,l.dataId)}static calcReduceByAxis(t,e,n,r,i,o,a){let s=0;if(r>=e.length)return o(t[i]);const u=e[r],c=u>=n.length?1:f.size(n.slice(u+1));for(let l=0;l<n[u];l++)s=0===l?h.calcReduceByAxis(t,e,n,r+1,i,o,a):a(s,h.calcReduceByAxis(t,e,n,r+1,i,o,a)),i+=c;return s}static calcReduceShape(t,e,n){const r=t.slice();for(let t=0;t<e.length;t++)r[e[t]]=n?1:0;return r.filter((t=>0!==t))}}e.ReduceUtil=h;class g{static adjustPoolAttributes(t,e,n,r,i,o){if(!t&&n.length!==e.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let t=0;t<e.length-2;t++)t>=n.length?n.push(e[t+2]):n[t]=e[t+2];for(let t=0;t<n.length;t++)if(t<r.length){if(r[t]<0)throw new Error("strides should be greater than or equal to 1")}else r.push(1);for(let t=0;t<n.length;t++)if(t<i.length){if(i[t]<0)throw new Error("dilations should be greater than or equal to 1")}else i.push(1);for(let t=0;t<2*n.length;t++)if(t<o.length){if(o[t]<0)throw new Error("pad should be greater than or equal to 1")}else o.push(0);for(let t=0;t<n.length;t++){if(n[t]<=0)throw new Error("kernel shapes need to be greater than 0");if(o[t]>=n[t]||o[t+n.length]>=n[t])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,e,n,r,i,o){if(o){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(e.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let a=0;a<t.length-2;a++)g.adjustPadAndReturnShape(t[a+2],e[a],n[a],r[a],i,a,a+t.length-2,o)}}static computePoolOutputShape(t,e,n,r,i,o,a){if(e.length<=0)throw new Error("input shape must be of size greater than 0");const s=[e[0],e[1]];return g.computeShapeHelper(t,e,s,n,r,i,o,a),s}static computeConvOutputShape(t,e,n,r,i,o,a){if(t.length<=0||e.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");const s=[t[0],e[0]];return g.computeShapeHelper(!1,t,s,n,r,i,o,a),s}static computeShapeHelper(t,e,n,r,i,o,a,s){if(t)for(let t=0;t<e.length-2;t++)n.push(1);else for(let t=0;t<e.length-2;t++)n.push(g.adjustPadAndReturnShape(e[t+2],r[t],i[t],o[t],a,t,t+e.length-2,s))}static adjustPadAndReturnShape(t,e,n,r,i,o,a,s){const u=n*(r-1)+1;if(!s||"NOTSET"===s)return Math.floor((t+i[o]+i[a]-u)/e+1);switch(s){case"VALID":return i[o]=0,i[a]=0,Math.floor((t-u)/e+1);case"SAME_LOWER":case"SAME_UPPER":if(1!==n)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{const n=((t+e-1)/e-1)*e+r-t;return i[o]="SAME_LOWER"===s?Math.floor((n+1)/2):Math.floor(n/2),i[a]=n-i[o],Math.floor((t+n-r)/e+1)}default:throw new Error("Unsupported AutoPad type")}}}e.PoolConvUtil=g,e.MIN_CLIP=-34028234663852886e22,e.MAX_CLIP=34028234663852886e22,e.decodeUtf8String=function(t){return(new TextDecoder).decode(t)}},7967:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,i)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,o])=>{const a=n?n+t:t;if("object"==typeof o)(0,e.iterateExtraOptions)(o,a+".",r,i);else if("string"==typeof o||"number"==typeof o)i(a,o.toString());else{if("boolean"!=typeof o)throw new Error("Can't handle extra config type: "+typeof o);i(a,o?"1":"0")}}))}},2157:function(t,e,n){"use strict";var r,i=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),o=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),a=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&i(e,t,n);return o(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=e.initWasm=void 0;const s=n(1670),u=a(n(349)),c=n(6361),l=()=>!!s.env.wasm.proxy&&"undefined"!=typeof document;let p,f,d,h=!1,g=!1,b=!1;const m=[],y=[],_=[],v=[],w=[],x=[],T=()=>{if(h||!g||b||!p)throw new Error("worker not ready")},S=t=>{switch(t.data.type){case"init-wasm":h=!1,t.data.err?(b=!0,f[1](t.data.err)):(g=!0,f[0]());break;case"init-ort":t.data.err?d[1](t.data.err):d[0]();break;case"create_allocate":t.data.err?m.shift()[1](t.data.err):m.shift()[0](t.data.out);break;case"create_finalize":t.data.err?y.shift()[1](t.data.err):y.shift()[0](t.data.out);break;case"create":t.data.err?_.shift()[1](t.data.err):_.shift()[0](t.data.out);break;case"release":t.data.err?v.shift()[1](t.data.err):v.shift()[0]();break;case"run":t.data.err?w.shift()[1](t.data.err):w.shift()[0](t.data.out);break;case"end-profiling":t.data.err?x.shift()[1](t.data.err):x.shift()[0]()}},O="undefined"!=typeof document?null===(r=null===document||void 0===document?void 0:document.currentScript)||void 0===r?void 0:r.src:void 0;e.initWasm=async()=>{if(l()){if(g)return;if(h)throw new Error("multiple calls to 'initWasm()' detected.");if(b)throw new Error("previous call to 'initWasm()' failed.");return h=!0,void 0===s.env.wasm.wasmPaths&&O&&0!==O.indexOf("blob:")&&(s.env.wasm.wasmPaths=O.substr(0,+O.lastIndexOf("/")+1)),new Promise(((t,e)=>{null==p||p.terminate(),p=n(9710).Z(),p.onmessage=S,f=[t,e];const r={type:"init-wasm",in:s.env.wasm};p.postMessage(r)}))}return(0,c.initializeWebAssembly)(s.env.wasm)},e.initOrt=async(t,e)=>{if(l())return T(),new Promise(((n,r)=>{d=[n,r];const i={type:"init-ort",in:{numThreads:t,loggingLevel:e}};p.postMessage(i)}));u.initOrt(t,e)},e.createSessionAllocate=async t=>l()?(T(),new Promise(((e,n)=>{m.push([e,n]);const r={type:"create_allocate",in:{model:t}};p.postMessage(r,[t.buffer])}))):u.createSessionAllocate(t),e.createSessionFinalize=async(t,e)=>l()?(T(),new Promise(((n,r)=>{y.push([n,r]);const i={type:"create_finalize",in:{modeldata:t,options:e}};p.postMessage(i)}))):u.createSessionFinalize(t,e),e.createSession=async(t,e)=>l()?(T(),new Promise(((n,r)=>{_.push([n,r]);const i={type:"create",in:{model:t,options:e}};p.postMessage(i,[t.buffer])}))):u.createSession(t,e),e.releaseSession=async t=>{if(l())return T(),new Promise(((e,n)=>{v.push([e,n]);const r={type:"release",in:t};p.postMessage(r)}));u.releaseSession(t)},e.run=async(t,e,n,r,i)=>l()?(T(),new Promise(((o,a)=>{w.push([o,a]);const s={type:"run",in:{sessionId:t,inputIndices:e,inputs:n,outputIndices:r,options:i}};p.postMessage(s,u.extractTransferableBuffers(n))}))):u.run(t,e,n,r,i),e.endProfiling=async t=>{if(l())return T(),new Promise(((e,n)=>{x.push([e,n]);const r={type:"end-profiling",in:t};p.postMessage(r)}));u.endProfiling(t)}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(7967),i=n(4983),o=n(6361);e.setRunOptions=t=>{const e=(0,o.getInstance)();let n=0;const a=[],s=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))s.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))s.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(s.terminate=!1);let o=0;if(void 0!==(null==t?void 0:t.tag)&&(o=(0,i.allocWasmString)(t.tag,a)),n=e._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,o),0===n)throw new Error("Can't create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const o=(0,i.allocWasmString)(t,a),s=(0,i.allocWasmString)(r,a);if(0!==e._OrtAddRunConfigEntry(n,o,s))throw new Error(`Can't set a run config entry: ${t} - ${r}`)})),[n,a]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),a.forEach(e._free),t}}},2306:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.OnnxruntimeWebAssemblySessionHandler=void 0;const r=n(2806),i=n(1670),o=n(2850),a=n(2157);let s;e.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(t){const e=await fetch(t),n=await e.arrayBuffer();return(0,a.createSessionAllocate)(new Uint8Array(n))}async loadModel(t,e){if(s||(await(0,a.initOrt)(i.env.wasm.numThreads,(t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}})(i.env.logLevel)),s=!0),"string"==typeof t)if("undefined"==typeof fetch){const n=await(0,o.promisify)(r.readFile)(t);[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSession)(n,e)}else{const n=await this.createSessionAllocate(t);[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSessionFinalize)(n,e)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSession)(t,e)}async dispose(){return(0,a.releaseSession)(this.sessionId)}async run(t,e,n){const r=[],o=[];Object.entries(t).forEach((t=>{const e=t[0],n=t[1],i=this.inputNames.indexOf(e);if(-1===i)throw new Error(`invalid input '${e}'`);r.push(n),o.push(i)}));const s=[];Object.entries(e).forEach((t=>{const e=t[0],n=this.outputNames.indexOf(e);if(-1===n)throw new Error(`invalid output '${e}'`);s.push(n)}));const u=await(0,a.run)(this.sessionId,o,r.map((t=>[t.type,t.dims,t.data])),s,n),c={};for(let t=0;t<u.length;t++)c[this.outputNames[s[t]]]=new i.Tensor(u[t][0],u[t][2],u[t][1]);return c}startProfiling(){}endProfiling(){(0,a.endProfiling)(this.sessionId)}}},4919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(7967),i=n(4983),o=n(6361);e.setSessionOptions=t=>{const e=(0,o.getInstance)();let n=0;const a=[],s=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(s);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(s.graphOptimizationLevel="all");const u=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(s.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(s.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(s.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(s.executionMode="sequential");const c=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(s.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,i.allocWasmString)(t.logId,a)),void 0===(null==t?void 0:t.logSeverityLevel))s.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))s.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(s.enableProfiling=!1),n=e._OrtCreateSessionOptions(u,!!s.enableCpuMemArena,!!s.enableMemPattern,c,!!s.enableProfiling,0,l,s.logSeverityLevel,s.logVerbosityLevel),0===n)throw new Error("Can't create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const a=(0,i.allocWasmString)(e,n);if(0!==(0,o.getInstance)()._OrtAppendExecutionProvider(t,a))throw new Error(`Can't append execution provider: ${e}`)}})(n,t.executionProviders,a),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const o=(0,i.allocWasmString)(t,a),s=(0,i.allocWasmString)(r,a);if(0!==e._OrtAddSessionConfigEntry(n,o,s))throw new Error(`Can't set a session config entry: ${t} - ${r}`)})),[n,a]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),a.forEach(e._free),t}}},4983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(6361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),i=n.lengthBytesUTF8(t)+1,o=n._malloc(i);return n.stringToUTF8(t,o,i),e.push(o),o}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),i=n(4919),o=n(4983),a=n(6361);e.initOrt=(t,e)=>{const n=(0,a.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can't initialize onnxruntime. error code = ${n}`)};const s=new Map;e.createSessionAllocate=t=>{const e=(0,a.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,a.getInstance)();let r=0,o=0,u=[];try{if([o,u]=(0,i.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],o),0===r)throw new Error("Can't create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(o),u.forEach(n._free)}const c=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),p=[],f=[],d=[],h=[];for(let t=0;t<c;t++){const e=n._OrtGetInputName(r,t);if(0===e)throw new Error("Can't get an input name");f.push(e),p.push(n.UTF8ToString(e))}for(let t=0;t<l;t++){const e=n._OrtGetOutputName(r,t);if(0===e)throw new Error("Can't get an output name");h.push(e),d.push(n.UTF8ToString(e))}return s.set(r,[r,f,h]),[r,p,d]},e.createSession=(t,n)=>{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,a.getInstance)(),n=s.get(t);if(!n)throw new Error("invalid session id");const r=n[0],i=n[1],o=n[2];i.forEach(e._OrtFree),o.forEach(e._OrtFree),e._OrtReleaseSession(r),s.delete(t)};const u=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},c=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,i,p)=>{const f=(0,a.getInstance)(),d=s.get(t);if(!d)throw new Error("invalid session id");const h=d[0],g=d[1],b=d[2],m=e.length,y=i.length;let _=0,v=[];const w=[],x=[];try{[_,v]=(0,r.setRunOptions)(p);for(let t=0;t<m;t++){const e=n[t][0],r=n[t][1],i=n[t][2];let a,s;if(Array.isArray(i)){s=4*i.length,a=f._malloc(s),x.push(a);let t=a/4;for(let e=0;e<i.length;e++){if("string"!=typeof i[e])throw new TypeError(`tensor data at index ${e} is not a string`);f.HEAPU32[t++]=(0,o.allocWasmString)(i[e],x)}}else s=i.byteLength,a=f._malloc(s),x.push(a),f.HEAPU8.set(new Uint8Array(i.buffer,i.byteOffset,s),a);const c=f.stackSave(),l=f.stackAlloc(4*r.length);try{let t=l/4;r.forEach((e=>f.HEAP32[t++]=e));const n=f._OrtCreateTensor(u(e),a,s,l,r.length);if(0===n)throw new Error("Can't create a tensor");w.push(n)}finally{f.stackRestore(c)}}const t=f.stackSave(),a=f.stackAlloc(4*m),s=f.stackAlloc(4*m),d=f.stackAlloc(4*y),T=f.stackAlloc(4*y);try{let n=a/4,r=s/4,o=d/4,u=T/4;for(let t=0;t<m;t++)f.HEAPU32[n++]=w[t],f.HEAPU32[r++]=g[e[t]];for(let t=0;t<y;t++)f.HEAPU32[o++]=0,f.HEAPU32[u++]=b[i[t]];let p=f._OrtRun(h,s,a,m,T,y,d,_);const v=[];if(0===p)for(let t=0;t<y;t++){const e=f.HEAPU32[d/4+t],n=f.stackSave(),r=f.stackAlloc(16);let i,o=0;try{if(p=f._OrtGetTensorData(e,r,r+4,r+8,r+12),0!==p)throw new Error(`Can't access output tensor data. error code = ${p}`);let t=r/4;const a=f.HEAPU32[t++];o=f.HEAPU32[t++];const s=f.HEAPU32[t++],u=f.HEAPU32[t++],d=[];for(let t=0;t<u;t++)d.push(f.HEAPU32[s/4+t]);f._OrtFree(s);const h=0===d.length?1:d.reduce(((t,e)=>t*e));if(i=c(a),"string"===i){const t=[];let e=o/4;for(let n=0;n<h;n++){const r=f.HEAPU32[e++],i=n===h-1?void 0:f.HEAPU32[e]-r;t.push(f.UTF8ToString(r,i))}v.push([i,d,t])}else{const t=new(l(i))(h);new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(f.HEAPU8.subarray(o,o+t.byteLength)),v.push([i,d,t])}}finally{f.stackRestore(n),"string"===i&&o&&f._free(o),f._OrtReleaseTensor(e)}}if(0===p)return v;throw new Error(`failed to call OrtRun(). error code = ${p}.`)}finally{f.stackRestore(t)}}finally{w.forEach(f._OrtReleaseTensor),x.forEach(f._free),f._OrtReleaseRunOptions(_),v.forEach(f._free)}},e.endProfiling=t=>{const e=(0,a.getInstance)(),n=s.get(t);if(!n)throw new Error("invalid session id");const r=n[0],i=e._OrtEndProfiling(r);if(0===i)throw new Error("Can't get an profile file name");e._OrtFree(i)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},6361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e},a=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const s=o(n(6449)),u=a(n(932)),c=n(3474);let l,p=!1,f=!1,d=!1;const h=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(p)return Promise.resolve();if(f)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(d)throw new Error("previous call to 'initializeWebAssembly()' failed.");f=!0;const e=t.initTimeout,r=t.numThreads,i=t.simd,o=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),a=i&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),g="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=h(!1,o),m=h(a,o),y="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let _=!1;const v=[];if(e>0&&v.push(new Promise((t=>{setTimeout((()=>{_=!0,t()}),e)}))),v.push(new Promise(((t,e)=>{const r=o?c:u.default,i={locateFile:(t,e)=>o&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(4154)],{type:"text/javascript"})):t===b?null!=y?y:(null!=g?g:e)+m:e+t};if(o)if("undefined"==typeof Blob)i.mainScriptUrlOrBlob=s.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;i.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(i).then((e=>{f=!1,p=!0,l=e,t()}),(t=>{f=!1,d=!0,e(t)}))}))),await Promise.race(v),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(p&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!p||f||d||(f=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,f=!1,p=!1,d=!0)}},9710:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(477),i=n.n(r);function o(){return i()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1<process.argv.length&&(m=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof ct))throw t})),process.on("unhandledRejection",(function(t){throw t})),g=(t,e)=>{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&L)return L.decode(t.buffer instanceof SharedArrayBuffer?t.slice(e,n):t.subarray(e,n));for(r="";e<n;){var a=t[e++];if(128&a){var i=63&t[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var o=63&t[e++];65536>(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var i=0;i<t.length;++i){var o=t.charCodeAt(i);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0<t.length;)t.shift()(u)}function yt(t){var e=Ee();return t=t(),Me(e),t}function bt(t){if(O)return $t(2,0,t);try{pt(t)}catch(t){t instanceof ct||"unwind"==t||g(1,t)}}u.PThread=ht,u.establishStackSpace=function(){var t=he(),e=a()[t+44>>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s<o?(i()[n>>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u<n;u++){var c=r[2+u];o()[i+u>>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u<a.length;++u)e()[o++>>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u<n;u++){var c=i()[e>>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l<s;l++)ae(t,r()[c+l>>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function u(t,e){return o(t,e,"0")}function c(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function s(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function l(t){var e=t.Wb;for(t=new Date(new Date(t.Xb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(ue(t.getFullYear())?ce:se)[n];if(!(e>r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12<t&&(t-=12),u(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.ec-1;e+=(ue(t.Xb+1900)?ce:se)[n++]);return u(t.jc+e,3)},"%m":function(t){return u(t.ec+1,2)},"%M":function(t){return u(t.Kc,2)},"%n":function(){return"\\n"},"%p":function(t){return 0<=t.dc&&12>t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&&gt(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},l:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},h:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},t:Tt,M:function(){var t=_t.pop();t||at("no exception to throw");var e=t.Zb;throw t.kc()||(_t.push(t),t.ic(!0),t.hc(!1),Ot++),At=e,e},c:function(t,e,n){throw new St(t).fc(e,n),At=t,Ot++,t},pa:function(){return Ot},Fa:function(t){ge(t,!w,1,!v),ht.pc()},T:function(t){O?postMessage({cmd:"cleanupThread",thread:t}):st(t)},xa:Mt,j:function(t){throw At||(At=t),t},H:Ct,Ma:xt,ua:Rt,wa:jt,oa:kt,Ka:Dt,Ca:Pt,Ja:Ut,V:Ft,va:It,sa:Wt,La:Ht,ta:Lt,Ta:function(){},X:function(){at("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){at("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(t,e,n,r){if(t==e)setTimeout((()=>zt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0<n!=(c==r)&&(o=Math.max(u,o),e.setTime(e.getTime()+6e4*((0<n?c:o)-r))),a()[t+24>>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r<e;r++)Xt[r]=o()[n+r>>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760<t)return!1;for(var n=1;4>=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i<a;i++)e()[r+i>>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0<et))if(O)c(u),O||dt(X),postMessage({cmd:"loaded"});else{if(u.preRun)for("function"==typeof u.preRun&&(u.preRun=[u.preRun]);u.preRun.length;)K();dt(q),0<et||(u.setStatus?(u.setStatus("Running..."),setTimeout((function(){setTimeout((function(){u.setStatus("")}),1),t()}),1)):t())}}if(u.UTF8ToString=Y,u.stringToUTF8=function(t,e,n){return B(t,r(),e,n)},u.lengthBytesUTF8=G,u.keepRuntimeAlive=Q,u.wasmMemory=j,u.stackSave=Ee,u.stackRestore=Me,u.stackAlloc=Ce,u.ExitStatus=ct,u.PThread=ht,rt=function t(){ve||ze(),ve||(rt=t)},u.preInit)for("function"==typeof u.preInit&&(u.preInit=[u.preInit]);0<u.preInit.length;)u.preInit.pop()();return ze(),t.ready});t.exports=r},932:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1<process.argv.length&&(p=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof J))throw t})),process.on("unhandledRejection",(function(t){throw t})),h=(t,e)=>{if(_||0<L)throw process.exitCode=t,e;e instanceof J||w("exiting due to exception: "+e),process.exit(t)},e.inspect=function(){return"[Emscripten Module object]"}):(d||y)&&(y?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),_scriptDir&&(m=_scriptDir),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",i=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&x)return x.decode(t.subarray(e,n));for(r="";e<n;){var a=t[e++];if(128&a){var i=63&t[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var o=63&t[e++];65536>(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var i=0;i<t.length;++i){var o=t.charCodeAt(i);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0<t.length;)t.shift()(e)}var Q=[],K=0,tt=0;function et(t){this.Db=t,this.zb=t-24,this.Ub=function(t){M[this.zb+4>>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function i(t,e){return a(t,e,"0")}function o(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function u(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function c(t){var e=t.Bb;for(t=new Date(new Date(t.Cb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(pt(t.getFullYear())?ht:dt)[n];if(!(e>r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12<t&&(t-=12),i(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.Hb-1;e+=(pt(t.Cb+1900)?ht:dt)[n++]);return i(t.Kb+e,3)},"%m":function(t){return i(t.Hb+1,2)},"%M":function(t){return i(t.Zb,2)},"%n":function(){return"\\n"},"%p":function(t){return 0<=t.Gb&&12>t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},k:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},g:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},s:nt,L:function(){var t=Q.pop();t||V("no exception to throw");var e=t.Db;throw t.Lb()||(Q.push(t),t.Jb(!0),t.Ib(!1),K++),tt=e,e},b:function(t,e,n){throw new et(t).Rb(e,n),tt=t,K++,t},la:function(){return K},i:function(t){throw tt||(tt=t),t},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},Ha:function(){},Ja:function(){V("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ia:function(){V("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0<n!=(u==r)&&(i=Math.max(o,i),e.setTime(e.getTime()+6e4*((0<n?u:i)-r))),E[t+24>>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u<a?(M[n>>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i<r.length;++i)S[a++>>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0<L||(_t(),Z(W),wt(0),st[1].length&&lt(1,10),st[2].length&&lt(2,10)),_||0<L||(e.onExit&&e.onExit(t),C=!0),h(t,new J(t))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(t,e,n,r){for(var a=0,i=0;i<n;i++){var o=M[e>>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c<u;c++)lt(t,T[o+c>>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a<r;a++)S[e+a>>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0<B)){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)z();Z(F),0<B||(e.setStatus?(e.setStatus("Running..."),setTimeout((function(){setTimeout((function(){e.setStatus("")}),1),t()}),1)):t())}}if(e.UTF8ToString=j,e.stringToUTF8=function(t,e,n){return k(t,T,e,n)},e.lengthBytesUTF8=D,e.stackSave=At,e.stackRestore=St,e.stackAlloc=Tt,N=function t(){mt||Wt(),mt||(N=t)},e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.pop()();return Wt(),t.ready});t.exports=r},967:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t<s;t++){const e=n._OrtGetInputName(r,t);if(0===e)throw new Error("Can\'t get an input name");p.push(e),f.push(n.UTF8ToString(e))}for(let t=0;t<l;t++){const e=n._OrtGetOutputName(r,t);if(0===e)throw new Error("Can\'t get an output name");d.push(e),h.push(n.UTF8ToString(e))}return u.set(r,[r,p,d]),[r,f,h]},e.createSession=(t,n)=>{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;t<m;t++){const e=n[t][0],r=n[t][1],a=n[t][2];let o,u;if(Array.isArray(a)){u=4*a.length,o=p._malloc(u),O.push(o);let t=o/4;for(let e=0;e<a.length;e++){if("string"!=typeof a[e])throw new TypeError(`tensor data at index ${e} is not a string`);p.HEAPU32[t++]=(0,i.allocWasmString)(a[e],O)}}else u=a.byteLength,o=p._malloc(u),O.push(o),p.HEAPU8.set(new Uint8Array(a.buffer,a.byteOffset,u),o);const s=p.stackSave(),l=p.stackAlloc(4*r.length);try{let t=l/4;r.forEach((e=>p.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;t<m;t++)p.HEAPU32[n++]=_[t],p.HEAPU32[r++]=y[e[t]];for(let t=0;t<g;t++)p.HEAPU32[i++]=0,p.HEAPU32[c++]=b[a[t]];let f=p._OrtRun(d,u,o,m,A,g,h,v);const w=[];if(0===f)for(let t=0;t<g;t++){const e=p.HEAPU32[h/4+t],n=p.stackSave(),r=p.stackAlloc(16);let a,i=0;try{if(f=p._OrtGetTensorData(e,r,r+4,r+8,r+12),0!==f)throw new Error(`Can\'t access output tensor data. error code = ${f}`);let t=r/4;const o=p.HEAPU32[t++];i=p.HEAPU32[t++];const u=p.HEAPU32[t++],c=p.HEAPU32[t++],h=[];for(let t=0;t<c;t++)h.push(p.HEAPU32[u/4+t]);p._OrtFree(u);const d=0===h.length?1:h.reduce(((t,e)=>t*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n<d;n++){const r=p.HEAPU32[e++],a=n===d-1?void 0:p.HEAPU32[e]-r;t.push(p.UTF8ToString(r,a))}w.push([a,h,t])}else{const t=new(l(a))(d);new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(p.HEAPU8.subarray(i,i+t.byteLength)),w.push([a,h,t])}}finally{p.stackRestore(n),"string"===a&&i&&p._free(i),p._OrtReleaseTensor(e)}}if(0===f)return w;throw new Error(`failed to call OrtRun(). error code = ${f}.`)}finally{p.stackRestore(t)}}finally{_.forEach(p._OrtReleaseTensor),O.forEach(p._free),p._OrtReleaseRunOptions(v),w.forEach(p._free)}},e.endProfiling=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),o=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n',"Worker",void 0,void 0)}},477:t=>{"use strict";t.exports=function(t,e,n,r){var i=self||window;try{try{var o;try{o=new i.Blob([t])}catch(e){(o=new(i.BlobBuilder||i.WebKitBlobBuilder||i.MozBlobBuilder||i.MSBlobBuilder)).append(t),o=o.getBlob()}var a=i.URL||i.webkitURL,s=a.createObjectURL(o),u=new i[e](s,n);return a.revokeObjectURL(s),u}catch(r){return new i[e]("data:application/javascript,".concat(encodeURIComponent(t)),n)}}catch(t){if(!r)throw Error("Inline worker is not supported");return new i[e](r,n)}}},4154:t=>{"use strict";t.exports='"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\n'},1670:t=>{"use strict";t.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(t,e,n)=>{"use strict";n.r(e),n.d(e,{flatbuffers:()=>r});var r={};r.Offset,r.Table,r.SIZEOF_SHORT=2,r.SIZEOF_INT=4,r.FILE_IDENTIFIER_LENGTH=4,r.SIZE_PREFIX_LENGTH=4,r.Encoding={UTF8_BYTES:1,UTF16_STRING:2},r.int32=new Int32Array(2),r.float32=new Float32Array(r.int32.buffer),r.float64=new Float64Array(r.int32.buffer),r.isLittleEndian=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0],r.Long=function(t,e){this.low=0|t,this.high=0|e},r.Long.create=function(t,e){return 0==t&&0==e?r.Long.ZERO:new r.Long(t,e)},r.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},r.Long.prototype.equals=function(t){return this.low==t.low&&this.high==t.high},r.Long.ZERO=new r.Long(0,0),r.Builder=function(t){if(t)e=t;else var e=1024;this.bb=r.ByteBuffer.allocate(e),this.space=e,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},r.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},r.Builder.prototype.forceDefaults=function(t){this.force_defaults=t},r.Builder.prototype.dataBuffer=function(){return this.bb},r.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},r.Builder.prototype.prep=function(t,e){t>this.minalign&&(this.minalign=t);for(var n=1+~(this.bb.capacity()-this.space+e)&t-1;this.space<n+t+e;){var i=this.bb.capacity();this.bb=r.Builder.growByteBuffer(this.bb),this.space+=this.bb.capacity()-i}this.pad(n)},r.Builder.prototype.pad=function(t){for(var e=0;e<t;e++)this.bb.writeInt8(--this.space,0)},r.Builder.prototype.writeInt8=function(t){this.bb.writeInt8(this.space-=1,t)},r.Builder.prototype.writeInt16=function(t){this.bb.writeInt16(this.space-=2,t)},r.Builder.prototype.writeInt32=function(t){this.bb.writeInt32(this.space-=4,t)},r.Builder.prototype.writeInt64=function(t){this.bb.writeInt64(this.space-=8,t)},r.Builder.prototype.writeFloat32=function(t){this.bb.writeFloat32(this.space-=4,t)},r.Builder.prototype.writeFloat64=function(t){this.bb.writeFloat64(this.space-=8,t)},r.Builder.prototype.addInt8=function(t){this.prep(1,0),this.writeInt8(t)},r.Builder.prototype.addInt16=function(t){this.prep(2,0),this.writeInt16(t)},r.Builder.prototype.addInt32=function(t){this.prep(4,0),this.writeInt32(t)},r.Builder.prototype.addInt64=function(t){this.prep(8,0),this.writeInt64(t)},r.Builder.prototype.addFloat32=function(t){this.prep(4,0),this.writeFloat32(t)},r.Builder.prototype.addFloat64=function(t){this.prep(8,0),this.writeFloat64(t)},r.Builder.prototype.addFieldInt8=function(t,e,n){(this.force_defaults||e!=n)&&(this.addInt8(e),this.slot(t))},r.Builder.prototype.addFieldInt16=function(t,e,n){(this.force_defaults||e!=n)&&(this.addInt16(e),this.slot(t))},r.Builder.prototype.addFieldInt32=function(t,e,n){(this.force_defaults||e!=n)&&(this.addInt32(e),this.slot(t))},r.Builder.prototype.addFieldInt64=function(t,e,n){!this.force_defaults&&e.equals(n)||(this.addInt64(e),this.slot(t))},r.Builder.prototype.addFieldFloat32=function(t,e,n){(this.force_defaults||e!=n)&&(this.addFloat32(e),this.slot(t))},r.Builder.prototype.addFieldFloat64=function(t,e,n){(this.force_defaults||e!=n)&&(this.addFloat64(e),this.slot(t))},r.Builder.prototype.addFieldOffset=function(t,e,n){(this.force_defaults||e!=n)&&(this.addOffset(e),this.slot(t))},r.Builder.prototype.addFieldStruct=function(t,e,n){e!=n&&(this.nested(e),this.slot(t))},r.Builder.prototype.nested=function(t){if(t!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")},r.Builder.prototype.notNested=function(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")},r.Builder.prototype.slot=function(t){this.vtable[t]=this.offset()},r.Builder.prototype.offset=function(){return this.bb.capacity()-this.space},r.Builder.growByteBuffer=function(t){var e=t.capacity();if(3221225472&e)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");var n=e<<1,i=r.ByteBuffer.allocate(n);return i.setPosition(n-e),i.bytes().set(t.bytes(),n-e),i},r.Builder.prototype.addOffset=function(t){this.prep(r.SIZEOF_INT,0),this.writeInt32(this.offset()-t+r.SIZEOF_INT)},r.Builder.prototype.startObject=function(t){this.notNested(),null==this.vtable&&(this.vtable=[]),this.vtable_in_use=t;for(var e=0;e<t;e++)this.vtable[e]=0;this.isNested=!0,this.object_start=this.offset()},r.Builder.prototype.endObject=function(){if(null==this.vtable||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);for(var t=this.offset(),e=this.vtable_in_use-1;e>=0&&0==this.vtable[e];e--);for(var n=e+1;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);var i=(n+2)*r.SIZEOF_SHORT;this.addInt16(i);var o=0,a=this.space;t:for(e=0;e<this.vtables.length;e++){var s=this.bb.capacity()-this.vtables[e];if(i==this.bb.readInt16(s)){for(var u=r.SIZEOF_SHORT;u<i;u+=r.SIZEOF_SHORT)if(this.bb.readInt16(a+u)!=this.bb.readInt16(s+u))continue t;o=this.vtables[e];break}}return o?(this.space=this.bb.capacity()-t,this.bb.writeInt32(this.space,o-t)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-t,this.offset()-t)),this.isNested=!1,t},r.Builder.prototype.finish=function(t,e,n){var i=n?r.SIZE_PREFIX_LENGTH:0;if(e){var o=e;if(this.prep(this.minalign,r.SIZEOF_INT+r.FILE_IDENTIFIER_LENGTH+i),o.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var a=r.FILE_IDENTIFIER_LENGTH-1;a>=0;a--)this.writeInt8(o.charCodeAt(a))}this.prep(this.minalign,r.SIZEOF_INT+i),this.addOffset(t),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},r.Builder.prototype.finishSizePrefixed=function(t,e){this.finish(t,e,!0)},r.Builder.prototype.requiredField=function(t,e){var n=this.bb.capacity()-t,r=n-this.bb.readInt32(n);if(0==this.bb.readInt16(r+e))throw new Error("FlatBuffers: field "+e+" must be set")},r.Builder.prototype.startVector=function(t,e,n){this.notNested(),this.vector_num_elems=e,this.prep(r.SIZEOF_INT,t*e),this.prep(n,t*e)},r.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},r.Builder.prototype.createString=function(t){if(t instanceof Uint8Array)var e=t;else{e=[];for(var n=0;n<t.length;){var r,i=t.charCodeAt(n++);(r=i<55296||i>=56320?i:(i<<10)+t.charCodeAt(n++)+-56613888)<128?e.push(r):(r<2048?e.push(r>>6&31|192):(r<65536?e.push(r>>12&15|224):e.push(r>>18&7|240,r>>12&63|128),e.push(r>>6&63|128)),e.push(63&r|128))}}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length),n=0;for(var o=this.space,a=this.bb.bytes();n<e.length;n++)a[o++]=e[n];return this.endVector()},r.Builder.prototype.createLong=function(t,e){return r.Long.create(t,e)},r.ByteBuffer=function(t){this.bytes_=t,this.position_=0},r.ByteBuffer.allocate=function(t){return new r.ByteBuffer(new Uint8Array(t))},r.ByteBuffer.prototype.clear=function(){this.position_=0},r.ByteBuffer.prototype.bytes=function(){return this.bytes_},r.ByteBuffer.prototype.position=function(){return this.position_},r.ByteBuffer.prototype.setPosition=function(t){this.position_=t},r.ByteBuffer.prototype.capacity=function(){return this.bytes_.length},r.ByteBuffer.prototype.readInt8=function(t){return this.readUint8(t)<<24>>24},r.ByteBuffer.prototype.readUint8=function(t){return this.bytes_[t]},r.ByteBuffer.prototype.readInt16=function(t){return this.readUint16(t)<<16>>16},r.ByteBuffer.prototype.readUint16=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8},r.ByteBuffer.prototype.readInt32=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24},r.ByteBuffer.prototype.readUint32=function(t){return this.readInt32(t)>>>0},r.ByteBuffer.prototype.readInt64=function(t){return new r.Long(this.readInt32(t),this.readInt32(t+4))},r.ByteBuffer.prototype.readUint64=function(t){return new r.Long(this.readUint32(t),this.readUint32(t+4))},r.ByteBuffer.prototype.readFloat32=function(t){return r.int32[0]=this.readInt32(t),r.float32[0]},r.ByteBuffer.prototype.readFloat64=function(t){return r.int32[r.isLittleEndian?0:1]=this.readInt32(t),r.int32[r.isLittleEndian?1:0]=this.readInt32(t+4),r.float64[0]},r.ByteBuffer.prototype.writeInt8=function(t,e){this.bytes_[t]=e},r.ByteBuffer.prototype.writeUint8=function(t,e){this.bytes_[t]=e},r.ByteBuffer.prototype.writeInt16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},r.ByteBuffer.prototype.writeUint16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},r.ByteBuffer.prototype.writeInt32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},r.ByteBuffer.prototype.writeUint32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},r.ByteBuffer.prototype.writeInt64=function(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)},r.ByteBuffer.prototype.writeUint64=function(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)},r.ByteBuffer.prototype.writeFloat32=function(t,e){r.float32[0]=e,this.writeInt32(t,r.int32[0])},r.ByteBuffer.prototype.writeFloat64=function(t,e){r.float64[0]=e,this.writeInt32(t,r.int32[r.isLittleEndian?0:1]),this.writeInt32(t+4,r.int32[r.isLittleEndian?1:0])},r.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length<this.position_+r.SIZEOF_INT+r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");for(var t="",e=0;e<r.FILE_IDENTIFIER_LENGTH;e++)t+=String.fromCharCode(this.readInt8(this.position_+r.SIZEOF_INT+e));return t},r.ByteBuffer.prototype.__offset=function(t,e){var n=t-this.readInt32(t);return e<this.readInt16(n)?this.readInt16(n+e):0},r.ByteBuffer.prototype.__union=function(t,e){return t.bb_pos=e+this.readInt32(e),t.bb=this,t},r.ByteBuffer.prototype.__string=function(t,e){t+=this.readInt32(t);var n=this.readInt32(t),i="",o=0;if(t+=r.SIZEOF_INT,e===r.Encoding.UTF8_BYTES)return this.bytes_.subarray(t,t+n);for(;o<n;){var a,s=this.readUint8(t+o++);if(s<192)a=s;else{var u=this.readUint8(t+o++);if(s<224)a=(31&s)<<6|63&u;else{var c=this.readUint8(t+o++);a=s<240?(15&s)<<12|(63&u)<<6|63&c:(7&s)<<18|(63&u)<<12|(63&c)<<6|63&this.readUint8(t+o++)}}a<65536?i+=String.fromCharCode(a):(a-=65536,i+=String.fromCharCode(55296+(a>>10),56320+(1023&a)))}return i},r.ByteBuffer.prototype.__indirect=function(t){return t+this.readInt32(t)},r.ByteBuffer.prototype.__vector=function(t){return t+this.readInt32(t)+r.SIZEOF_INT},r.ByteBuffer.prototype.__vector_len=function(t){return this.readInt32(t+this.readInt32(t))},r.ByteBuffer.prototype.__has_identifier=function(t){if(t.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var e=0;e<r.FILE_IDENTIFIER_LENGTH;e++)if(t.charCodeAt(e)!=this.readInt8(this.position_+r.SIZEOF_INT+e))return!1;return!0},r.ByteBuffer.prototype.createLong=function(t,e){return r.Long.create(t,e)}}},__webpack_module_cache__={};function __nested_webpack_require_546802__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var n=__webpack_module_cache__[t]={exports:{}};return __webpack_modules__[t].call(n.exports,n,n.exports,__nested_webpack_require_546802__),n.exports}__nested_webpack_require_546802__.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return __nested_webpack_require_546802__.d(e,{a:e}),e},__nested_webpack_require_546802__.d=(t,e)=>{for(var n in e)__nested_webpack_require_546802__.o(e,n)&&!__nested_webpack_require_546802__.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},__nested_webpack_require_546802__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),__nested_webpack_require_546802__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),__nested_webpack_require_546802__.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var __nested_webpack_exports__=__nested_webpack_require_546802__(6018);return __nested_webpack_exports__})()));
//# sourceMappingURL=ort-web.min.js.map

/***/ }),

/***/ "?2ce3":
/*!**********************************!*\
  !*** onnxruntime-node (ignored) ***!
  \**********************************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?7a2c":
/*!********************!*\
  !*** fs (ignored) ***!
  \********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?a42a":
/*!**********************!*\
  !*** path (ignored) ***!
  \**********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?2b25":
/*!***********************!*\
  !*** sharp (ignored) ***!
  \***********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?569f":
/*!********************!*\
  !*** fs (ignored) ***!
  \********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?3f59":
/*!**********************!*\
  !*** path (ignored) ***!
  \**********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?154a":
/*!*********************!*\
  !*** url (ignored) ***!
  \*********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "./node_modules/@huggingface/jinja/dist/index.js":
/*!*******************************************************!*\
  !*** ./node_modules/@huggingface/jinja/dist/index.js ***!
  \*******************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Environment": () => (/* binding */ Environment),
/* harmony export */   "Interpreter": () => (/* binding */ Interpreter),
/* harmony export */   "Template": () => (/* binding */ Template),
/* harmony export */   "parse": () => (/* binding */ parse),
/* harmony export */   "tokenize": () => (/* binding */ tokenize)
/* harmony export */ });
// src/lexer.ts
var TOKEN_TYPES = Object.freeze({
  Text: "Text",
  // The text between Jinja statements or expressions
  NumericLiteral: "NumericLiteral",
  // e.g., 123
  BooleanLiteral: "BooleanLiteral",
  // true or false
  StringLiteral: "StringLiteral",
  // 'string'
  Identifier: "Identifier",
  // Variables, functions, etc.
  Equals: "Equals",
  // =
  OpenParen: "OpenParen",
  // (
  CloseParen: "CloseParen",
  // )
  OpenStatement: "OpenStatement",
  // {%
  CloseStatement: "CloseStatement",
  // %}
  OpenExpression: "OpenExpression",
  // {{
  CloseExpression: "CloseExpression",
  // }}
  OpenSquareBracket: "OpenSquareBracket",
  // [
  CloseSquareBracket: "CloseSquareBracket",
  // ]
  OpenCurlyBracket: "OpenCurlyBracket",
  // {
  CloseCurlyBracket: "CloseCurlyBracket",
  // }
  Comma: "Comma",
  // ,
  Dot: "Dot",
  // .
  Colon: "Colon",
  // :
  Pipe: "Pipe",
  // |
  CallOperator: "CallOperator",
  // ()
  AdditiveBinaryOperator: "AdditiveBinaryOperator",
  // + -
  MultiplicativeBinaryOperator: "MultiplicativeBinaryOperator",
  // * / %
  ComparisonBinaryOperator: "ComparisonBinaryOperator",
  // < > <= >= == !=
  UnaryOperator: "UnaryOperator",
  // ! - +
  // Keywords
  Set: "Set",
  If: "If",
  For: "For",
  In: "In",
  Is: "Is",
  NotIn: "NotIn",
  Else: "Else",
  EndIf: "EndIf",
  ElseIf: "ElseIf",
  EndFor: "EndFor",
  And: "And",
  Or: "Or",
  Not: "UnaryOperator"
});
var KEYWORDS = Object.freeze({
  set: TOKEN_TYPES.Set,
  for: TOKEN_TYPES.For,
  in: TOKEN_TYPES.In,
  is: TOKEN_TYPES.Is,
  if: TOKEN_TYPES.If,
  else: TOKEN_TYPES.Else,
  endif: TOKEN_TYPES.EndIf,
  elif: TOKEN_TYPES.ElseIf,
  endfor: TOKEN_TYPES.EndFor,
  and: TOKEN_TYPES.And,
  or: TOKEN_TYPES.Or,
  not: TOKEN_TYPES.Not,
  "not in": TOKEN_TYPES.NotIn,
  // Literals
  true: TOKEN_TYPES.BooleanLiteral,
  false: TOKEN_TYPES.BooleanLiteral
});
var Token = class {
  /**
   * Constructs a new Token.
   * @param {string} value The raw value as seen inside the source code.
   * @param {TokenType} type The type of token.
   */
  constructor(value, type) {
    this.value = value;
    this.type = type;
  }
};
function isWord(char) {
  return /\w/.test(char);
}
function isInteger(char) {
  return /[0-9]/.test(char);
}
var ORDERED_MAPPING_TABLE = [
  // Control sequences
  ["{%", TOKEN_TYPES.OpenStatement],
  ["%}", TOKEN_TYPES.CloseStatement],
  ["{{", TOKEN_TYPES.OpenExpression],
  ["}}", TOKEN_TYPES.CloseExpression],
  // Single character tokens
  ["(", TOKEN_TYPES.OpenParen],
  [")", TOKEN_TYPES.CloseParen],
  ["{", TOKEN_TYPES.OpenCurlyBracket],
  ["}", TOKEN_TYPES.CloseCurlyBracket],
  ["[", TOKEN_TYPES.OpenSquareBracket],
  ["]", TOKEN_TYPES.CloseSquareBracket],
  [",", TOKEN_TYPES.Comma],
  [".", TOKEN_TYPES.Dot],
  [":", TOKEN_TYPES.Colon],
  ["|", TOKEN_TYPES.Pipe],
  // Comparison operators
  ["<=", TOKEN_TYPES.ComparisonBinaryOperator],
  [">=", TOKEN_TYPES.ComparisonBinaryOperator],
  ["==", TOKEN_TYPES.ComparisonBinaryOperator],
  ["!=", TOKEN_TYPES.ComparisonBinaryOperator],
  ["<", TOKEN_TYPES.ComparisonBinaryOperator],
  [">", TOKEN_TYPES.ComparisonBinaryOperator],
  // Arithmetic operators
  ["+", TOKEN_TYPES.AdditiveBinaryOperator],
  ["-", TOKEN_TYPES.AdditiveBinaryOperator],
  ["*", TOKEN_TYPES.MultiplicativeBinaryOperator],
  ["/", TOKEN_TYPES.MultiplicativeBinaryOperator],
  ["%", TOKEN_TYPES.MultiplicativeBinaryOperator],
  // Assignment operator
  ["=", TOKEN_TYPES.Equals]
];
var ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([
  ["n", "\n"],
  // New line
  ["t", "	"],
  // Horizontal tab
  ["r", "\r"],
  // Carriage return
  ["b", "\b"],
  // Backspace
  ["f", "\f"],
  // Form feed
  ["v", "\v"],
  // Vertical tab
  ["'", "'"],
  // Single quote
  ['"', '"'],
  // Double quote
  ["\\", "\\"]
  // Backslash
]);
function preprocess(template, options = {}) {
  if (template.endsWith("\n")) {
    template = template.slice(0, -1);
  }
  template = template.replace(/{#.*?#}/gs, "{##}");
  if (options.lstrip_blocks) {
    template = template.replace(/^[ \t]*({[#%])/gm, "$1");
  }
  if (options.trim_blocks) {
    template = template.replace(/([#%]})\n/g, "$1");
  }
  return template.replace(/{##}/g, "").replace(/-%}\s*/g, "%}").replace(/\s*{%-/g, "{%").replace(/-}}\s*/g, "}}").replace(/\s*{{-/g, "{{");
}
function tokenize(source, options = {}) {
  const tokens = [];
  const src = preprocess(source, options);
  let cursorPosition = 0;
  const consumeWhile = (predicate) => {
    let str = "";
    while (predicate(src[cursorPosition])) {
      if (src[cursorPosition] === "\\") {
        ++cursorPosition;
        if (cursorPosition >= src.length)
          throw new SyntaxError("Unexpected end of input");
        const escaped = src[cursorPosition++];
        const unescaped = ESCAPE_CHARACTERS.get(escaped);
        if (unescaped === void 0) {
          throw new SyntaxError(`Unexpected escaped character: ${escaped}`);
        }
        str += unescaped;
        continue;
      }
      str += src[cursorPosition++];
      if (cursorPosition >= src.length)
        throw new SyntaxError("Unexpected end of input");
    }
    return str;
  };
  main:
    while (cursorPosition < src.length) {
      const lastTokenType = tokens.at(-1)?.type;
      if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression) {
        let text = "";
        while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression
        !(src[cursorPosition] === "{" && (src[cursorPosition + 1] === "%" || src[cursorPosition + 1] === "{"))) {
          text += src[cursorPosition++];
        }
        if (text.length > 0) {
          tokens.push(new Token(text, TOKEN_TYPES.Text));
          continue;
        }
      }
      consumeWhile((char2) => /\s/.test(char2));
      const char = src[cursorPosition];
      if (char === "-" || char === "+") {
        const lastTokenType2 = tokens.at(-1)?.type;
        if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) {
          throw new SyntaxError(`Unexpected character: ${char}`);
        }
        switch (lastTokenType2) {
          case TOKEN_TYPES.Identifier:
          case TOKEN_TYPES.NumericLiteral:
          case TOKEN_TYPES.BooleanLiteral:
          case TOKEN_TYPES.StringLiteral:
          case TOKEN_TYPES.CloseParen:
          case TOKEN_TYPES.CloseSquareBracket:
            break;
          default: {
            ++cursorPosition;
            const num = consumeWhile(isInteger);
            tokens.push(
              new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator)
            );
            continue;
          }
        }
      }
      for (const [char2, token] of ORDERED_MAPPING_TABLE) {
        const slice2 = src.slice(cursorPosition, cursorPosition + char2.length);
        if (slice2 === char2) {
          tokens.push(new Token(char2, token));
          cursorPosition += char2.length;
          continue main;
        }
      }
      if (char === "'" || char === '"') {
        ++cursorPosition;
        const str = consumeWhile((c) => c !== char);
        tokens.push(new Token(str, TOKEN_TYPES.StringLiteral));
        ++cursorPosition;
        continue;
      }
      if (isInteger(char)) {
        const num = consumeWhile(isInteger);
        tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral));
        continue;
      }
      if (isWord(char)) {
        const word = consumeWhile(isWord);
        const type = Object.hasOwn(KEYWORDS, word) ? KEYWORDS[word] : TOKEN_TYPES.Identifier;
        if (type === TOKEN_TYPES.In && tokens.at(-1)?.type === TOKEN_TYPES.Not) {
          tokens.pop();
          tokens.push(new Token("not in", TOKEN_TYPES.NotIn));
        } else {
          tokens.push(new Token(word, type));
        }
        continue;
      }
      throw new SyntaxError(`Unexpected character: ${char}`);
    }
  return tokens;
}

// src/ast.ts
var Statement = class {
  type = "Statement";
};
var Program = class extends Statement {
  constructor(body) {
    super();
    this.body = body;
  }
  type = "Program";
};
var If = class extends Statement {
  constructor(test, body, alternate) {
    super();
    this.test = test;
    this.body = body;
    this.alternate = alternate;
  }
  type = "If";
};
var For = class extends Statement {
  constructor(loopvar, iterable, body) {
    super();
    this.loopvar = loopvar;
    this.iterable = iterable;
    this.body = body;
  }
  type = "For";
};
var SetStatement = class extends Statement {
  constructor(assignee, value) {
    super();
    this.assignee = assignee;
    this.value = value;
  }
  type = "Set";
};
var Expression = class extends Statement {
  type = "Expression";
};
var MemberExpression = class extends Expression {
  constructor(object, property, computed) {
    super();
    this.object = object;
    this.property = property;
    this.computed = computed;
  }
  type = "MemberExpression";
};
var CallExpression = class extends Expression {
  constructor(callee, args) {
    super();
    this.callee = callee;
    this.args = args;
  }
  type = "CallExpression";
};
var Identifier = class extends Expression {
  /**
   * @param {string} value The name of the identifier
   */
  constructor(value) {
    super();
    this.value = value;
  }
  type = "Identifier";
};
var Literal = class extends Expression {
  constructor(value) {
    super();
    this.value = value;
  }
  type = "Literal";
};
var NumericLiteral = class extends Literal {
  type = "NumericLiteral";
};
var StringLiteral = class extends Literal {
  type = "StringLiteral";
};
var BooleanLiteral = class extends Literal {
  type = "BooleanLiteral";
};
var ArrayLiteral = class extends Literal {
  type = "ArrayLiteral";
};
var TupleLiteral = class extends Literal {
  type = "TupleLiteral";
};
var ObjectLiteral = class extends Literal {
  type = "ObjectLiteral";
};
var BinaryExpression = class extends Expression {
  constructor(operator, left, right) {
    super();
    this.operator = operator;
    this.left = left;
    this.right = right;
  }
  type = "BinaryExpression";
};
var FilterExpression = class extends Expression {
  constructor(operand, filter) {
    super();
    this.operand = operand;
    this.filter = filter;
  }
  type = "FilterExpression";
};
var TestExpression = class extends Expression {
  constructor(operand, negate, test) {
    super();
    this.operand = operand;
    this.negate = negate;
    this.test = test;
  }
  type = "TestExpression";
};
var UnaryExpression = class extends Expression {
  constructor(operator, argument) {
    super();
    this.operator = operator;
    this.argument = argument;
  }
  type = "UnaryExpression";
};
var SliceExpression = class extends Expression {
  constructor(start = void 0, stop = void 0, step = void 0) {
    super();
    this.start = start;
    this.stop = stop;
    this.step = step;
  }
  type = "SliceExpression";
};
var KeywordArgumentExpression = class extends Expression {
  constructor(key, value) {
    super();
    this.key = key;
    this.value = value;
  }
  type = "KeywordArgumentExpression";
};

// src/parser.ts
function parse(tokens) {
  const program = new Program([]);
  let current = 0;
  function expect(type, error) {
    const prev = tokens[current++];
    if (!prev || prev.type !== type) {
      throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`);
    }
    return prev;
  }
  function parseAny() {
    switch (tokens[current].type) {
      case TOKEN_TYPES.Text:
        return parseText();
      case TOKEN_TYPES.OpenStatement:
        return parseJinjaStatement();
      case TOKEN_TYPES.OpenExpression:
        return parseJinjaExpression();
      default:
        throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`);
    }
  }
  function not(...types) {
    return current + types.length <= tokens.length && types.some((type, i) => type !== tokens[current + i].type);
  }
  function is(...types) {
    return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type);
  }
  function parseText() {
    return new StringLiteral(expect(TOKEN_TYPES.Text, "Expected text token").value);
  }
  function parseJinjaStatement() {
    expect(TOKEN_TYPES.OpenStatement, "Expected opening statement token");
    let result;
    switch (tokens[current].type) {
      case TOKEN_TYPES.Set:
        ++current;
        result = parseSetStatement();
        expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
        break;
      case TOKEN_TYPES.If:
        ++current;
        result = parseIfStatement();
        expect(TOKEN_TYPES.OpenStatement, "Expected {% token");
        expect(TOKEN_TYPES.EndIf, "Expected endif token");
        expect(TOKEN_TYPES.CloseStatement, "Expected %} token");
        break;
      case TOKEN_TYPES.For:
        ++current;
        result = parseForStatement();
        expect(TOKEN_TYPES.OpenStatement, "Expected {% token");
        expect(TOKEN_TYPES.EndFor, "Expected endfor token");
        expect(TOKEN_TYPES.CloseStatement, "Expected %} token");
        break;
      default:
        throw new SyntaxError(`Unknown statement type: ${tokens[current].type}`);
    }
    return result;
  }
  function parseJinjaExpression() {
    expect(TOKEN_TYPES.OpenExpression, "Expected opening expression token");
    const result = parseExpression();
    expect(TOKEN_TYPES.CloseExpression, "Expected closing expression token");
    return result;
  }
  function parseSetStatement() {
    const left = parseExpression();
    if (is(TOKEN_TYPES.Equals)) {
      ++current;
      const value = parseSetStatement();
      return new SetStatement(left, value);
    }
    return left;
  }
  function parseIfStatement() {
    const test = parseExpression();
    expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
    const body = [];
    const alternate = [];
    while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && (tokens[current + 1]?.type === TOKEN_TYPES.ElseIf || tokens[current + 1]?.type === TOKEN_TYPES.Else || tokens[current + 1]?.type === TOKEN_TYPES.EndIf))) {
      body.push(parseAny());
    }
    if (tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type !== TOKEN_TYPES.EndIf) {
      ++current;
      if (is(TOKEN_TYPES.ElseIf)) {
        expect(TOKEN_TYPES.ElseIf, "Expected elseif token");
        alternate.push(parseIfStatement());
      } else {
        expect(TOKEN_TYPES.Else, "Expected else token");
        expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
        while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.EndIf)) {
          alternate.push(parseAny());
        }
      }
    }
    return new If(test, body, alternate);
  }
  function parseExpressionSequence(primary = false) {
    const fn = primary ? parsePrimaryExpression : parseExpression;
    const expressions = [fn()];
    const isTuple = is(TOKEN_TYPES.Comma);
    while (isTuple) {
      ++current;
      expressions.push(fn());
      if (!is(TOKEN_TYPES.Comma)) {
        break;
      }
    }
    return isTuple ? new TupleLiteral(expressions) : expressions[0];
  }
  function parseForStatement() {
    const loopVariable = parseExpressionSequence(true);
    if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) {
      throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`);
    }
    expect(TOKEN_TYPES.In, "Expected `in` keyword following loop variable");
    const iterable = parseExpression();
    expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
    const body = [];
    while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor)) {
      body.push(parseAny());
    }
    return new For(loopVariable, iterable, body);
  }
  function parseExpression() {
    return parseTernaryExpression();
  }
  function parseTernaryExpression() {
    const a = parseLogicalOrExpression();
    if (is(TOKEN_TYPES.If)) {
      ++current;
      const predicate = parseLogicalOrExpression();
      expect(TOKEN_TYPES.Else, "Expected else token");
      const b = parseLogicalOrExpression();
      return new If(predicate, [a], [b]);
    }
    return a;
  }
  function parseLogicalOrExpression() {
    let left = parseLogicalAndExpression();
    while (is(TOKEN_TYPES.Or)) {
      const operator = tokens[current];
      ++current;
      const right = parseLogicalAndExpression();
      left = new BinaryExpression(operator, left, right);
    }
    return left;
  }
  function parseLogicalAndExpression() {
    let left = parseLogicalNegationExpression();
    while (is(TOKEN_TYPES.And)) {
      const operator = tokens[current];
      ++current;
      const right = parseLogicalNegationExpression();
      left = new BinaryExpression(operator, left, right);
    }
    return left;
  }
  function parseLogicalNegationExpression() {
    let right;
    while (is(TOKEN_TYPES.Not)) {
      const operator = tokens[current];
      ++current;
      const arg = parseLogicalNegationExpression();
      right = new UnaryExpression(operator, arg);
    }
    return right ?? parseComparisonExpression();
  }
  function parseComparisonExpression() {
    let left = parseAdditiveExpression();
    while (is(TOKEN_TYPES.ComparisonBinaryOperator) || is(TOKEN_TYPES.In) || is(TOKEN_TYPES.NotIn)) {
      const operator = tokens[current];
      ++current;
      const right = parseAdditiveExpression();
      left = new BinaryExpression(operator, left, right);
    }
    return left;
  }
  function parseAdditiveExpression() {
    let left = parseMultiplicativeExpression();
    while (is(TOKEN_TYPES.AdditiveBinaryOperator)) {
      const operator = tokens[current];
      ++current;
      const right = parseMultiplicativeExpression();
      left = new BinaryExpression(operator, left, right);
    }
    return left;
  }
  function parseCallMemberExpression() {
    const member = parseMemberExpression();
    if (is(TOKEN_TYPES.OpenParen)) {
      return parseCallExpression(member);
    }
    return member;
  }
  function parseCallExpression(callee) {
    let callExpression = new CallExpression(callee, parseArgs());
    if (is(TOKEN_TYPES.OpenParen)) {
      callExpression = parseCallExpression(callExpression);
    }
    return callExpression;
  }
  function parseArgs() {
    expect(TOKEN_TYPES.OpenParen, "Expected opening parenthesis for arguments list");
    const args = parseArgumentsList();
    expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis for arguments list");
    return args;
  }
  function parseArgumentsList() {
    const args = [];
    while (!is(TOKEN_TYPES.CloseParen)) {
      let argument = parseExpression();
      if (is(TOKEN_TYPES.Equals)) {
        ++current;
        if (!(argument instanceof Identifier)) {
          throw new SyntaxError(`Expected identifier for keyword argument`);
        }
        const value = parseExpression();
        argument = new KeywordArgumentExpression(argument, value);
      }
      args.push(argument);
      if (is(TOKEN_TYPES.Comma)) {
        ++current;
      }
    }
    return args;
  }
  function parseMemberExpressionArgumentsList() {
    const slices = [];
    let isSlice = false;
    while (!is(TOKEN_TYPES.CloseSquareBracket)) {
      if (is(TOKEN_TYPES.Colon)) {
        slices.push(void 0);
        ++current;
        isSlice = true;
      } else {
        slices.push(parseExpression());
        if (is(TOKEN_TYPES.Colon)) {
          ++current;
          isSlice = true;
        }
      }
    }
    if (slices.length === 0) {
      throw new SyntaxError(`Expected at least one argument for member/slice expression`);
    }
    if (isSlice) {
      if (slices.length > 3) {
        throw new SyntaxError(`Expected 0-3 arguments for slice expression`);
      }
      return new SliceExpression(...slices);
    }
    return slices[0];
  }
  function parseMemberExpression() {
    let object = parsePrimaryExpression();
    while (is(TOKEN_TYPES.Dot) || is(TOKEN_TYPES.OpenSquareBracket)) {
      const operator = tokens[current];
      ++current;
      let property;
      const computed = operator.type !== TOKEN_TYPES.Dot;
      if (computed) {
        property = parseMemberExpressionArgumentsList();
        expect(TOKEN_TYPES.CloseSquareBracket, "Expected closing square bracket");
      } else {
        property = parsePrimaryExpression();
        if (property.type !== "Identifier") {
          throw new SyntaxError(`Expected identifier following dot operator`);
        }
      }
      object = new MemberExpression(object, property, computed);
    }
    return object;
  }
  function parseMultiplicativeExpression() {
    let left = parseTestExpression();
    while (is(TOKEN_TYPES.MultiplicativeBinaryOperator)) {
      const operator = tokens[current];
      ++current;
      const right = parseTestExpression();
      left = new BinaryExpression(operator, left, right);
    }
    return left;
  }
  function parseTestExpression() {
    let operand = parseFilterExpression();
    while (is(TOKEN_TYPES.Is)) {
      ++current;
      const negate = is(TOKEN_TYPES.Not);
      if (negate) {
        ++current;
      }
      let filter = parsePrimaryExpression();
      if (filter instanceof BooleanLiteral) {
        filter = new Identifier(filter.value.toString());
      }
      if (!(filter instanceof Identifier)) {
        throw new SyntaxError(`Expected identifier for the test`);
      }
      operand = new TestExpression(operand, negate, filter);
    }
    return operand;
  }
  function parseFilterExpression() {
    let operand = parseCallMemberExpression();
    while (is(TOKEN_TYPES.Pipe)) {
      ++current;
      let filter = parsePrimaryExpression();
      if (!(filter instanceof Identifier)) {
        throw new SyntaxError(`Expected identifier for the filter`);
      }
      if (is(TOKEN_TYPES.OpenParen)) {
        filter = parseCallExpression(filter);
      }
      operand = new FilterExpression(operand, filter);
    }
    return operand;
  }
  function parsePrimaryExpression() {
    const token = tokens[current];
    switch (token.type) {
      case TOKEN_TYPES.NumericLiteral:
        ++current;
        return new NumericLiteral(Number(token.value));
      case TOKEN_TYPES.StringLiteral:
        ++current;
        return new StringLiteral(token.value);
      case TOKEN_TYPES.BooleanLiteral:
        ++current;
        return new BooleanLiteral(token.value === "true");
      case TOKEN_TYPES.Identifier:
        ++current;
        return new Identifier(token.value);
      case TOKEN_TYPES.OpenParen: {
        ++current;
        const expression = parseExpressionSequence();
        if (tokens[current].type !== TOKEN_TYPES.CloseParen) {
          throw new SyntaxError(`Expected closing parenthesis, got ${tokens[current].type} instead`);
        }
        ++current;
        return expression;
      }
      case TOKEN_TYPES.OpenSquareBracket: {
        ++current;
        const values = [];
        while (!is(TOKEN_TYPES.CloseSquareBracket)) {
          values.push(parseExpression());
          if (is(TOKEN_TYPES.Comma)) {
            ++current;
          }
        }
        ++current;
        return new ArrayLiteral(values);
      }
      case TOKEN_TYPES.OpenCurlyBracket: {
        ++current;
        const values = /* @__PURE__ */ new Map();
        while (!is(TOKEN_TYPES.CloseCurlyBracket)) {
          const key = parseExpression();
          expect(TOKEN_TYPES.Colon, "Expected colon between key and value in object literal");
          const value = parseExpression();
          values.set(key, value);
          if (is(TOKEN_TYPES.Comma)) {
            ++current;
          }
        }
        ++current;
        return new ObjectLiteral(values);
      }
      default:
        throw new SyntaxError(`Unexpected token: ${token.type}`);
    }
  }
  while (current < tokens.length) {
    program.body.push(parseAny());
  }
  return program;
}

// src/utils.ts
function range(start, stop, step = 1) {
  if (stop === void 0) {
    stop = start;
    start = 0;
  }
  const result = [];
  for (let i = start; i < stop; i += step) {
    result.push(i);
  }
  return result;
}
function slice(array, start, stop, step = 1) {
  const direction = Math.sign(step);
  if (direction >= 0) {
    start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length);
    stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length);
  } else {
    start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1);
    stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1);
  }
  const result = [];
  for (let i = start; direction * i < direction * stop; i += step) {
    result.push(array[i]);
  }
  return result;
}
function titleCase(value) {
  return value.replace(/\b\w/g, (c) => c.toUpperCase());
}

// src/runtime.ts
var RuntimeValue = class {
  type = "RuntimeValue";
  value;
  /**
   * A collection of built-in functions for this type.
   */
  builtins = /* @__PURE__ */ new Map();
  /**
   * Creates a new RuntimeValue.
   */
  constructor(value = void 0) {
    this.value = value;
  }
  /**
   * Determines truthiness or falsiness of the runtime value.
   * This function should be overridden by subclasses if it has custom truthiness criteria.
   * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise.
   */
  __bool__() {
    return new BooleanValue(!!this.value);
  }
};
var NumericValue = class extends RuntimeValue {
  type = "NumericValue";
};
var StringValue = class extends RuntimeValue {
  type = "StringValue";
  builtins = /* @__PURE__ */ new Map([
    [
      "upper",
      new FunctionValue(() => {
        return new StringValue(this.value.toUpperCase());
      })
    ],
    [
      "lower",
      new FunctionValue(() => {
        return new StringValue(this.value.toLowerCase());
      })
    ],
    [
      "strip",
      new FunctionValue(() => {
        return new StringValue(this.value.trim());
      })
    ],
    [
      "title",
      new FunctionValue(() => {
        return new StringValue(titleCase(this.value));
      })
    ],
    ["length", new NumericValue(this.value.length)]
  ]);
};
var BooleanValue = class extends RuntimeValue {
  type = "BooleanValue";
};
var ObjectValue = class extends RuntimeValue {
  type = "ObjectValue";
  /**
   * NOTE: necessary to override since all JavaScript arrays are considered truthy,
   * while only non-empty Python arrays are consider truthy.
   *
   * e.g.,
   *  - JavaScript:  {} && 5 -> 5
   *  - Python:      {} and 5 -> {}
   */
  __bool__() {
    return new BooleanValue(this.value.size > 0);
  }
  builtins = /* @__PURE__ */ new Map([
    [
      "get",
      new FunctionValue(([key, defaultValue]) => {
        if (!(key instanceof StringValue)) {
          throw new Error(`Object key must be a string: got ${key.type}`);
        }
        return this.value.get(key.value) ?? defaultValue ?? new NullValue();
      })
    ],
    [
      "items",
      new FunctionValue(() => {
        return new ArrayValue(
          Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))
        );
      })
    ]
  ]);
};
var ArrayValue = class extends RuntimeValue {
  type = "ArrayValue";
  builtins = /* @__PURE__ */ new Map([["length", new NumericValue(this.value.length)]]);
  /**
   * NOTE: necessary to override since all JavaScript arrays are considered truthy,
   * while only non-empty Python arrays are consider truthy.
   *
   * e.g.,
   *  - JavaScript:  [] && 5 -> 5
   *  - Python:      [] and 5 -> []
   */
  __bool__() {
    return new BooleanValue(this.value.length > 0);
  }
};
var TupleValue = class extends ArrayValue {
  type = "TupleValue";
};
var FunctionValue = class extends RuntimeValue {
  type = "FunctionValue";
};
var NullValue = class extends RuntimeValue {
  type = "NullValue";
};
var UndefinedValue = class extends RuntimeValue {
  type = "UndefinedValue";
};
var Environment = class {
  constructor(parent) {
    this.parent = parent;
  }
  /**
   * The variables declared in this environment.
   */
  variables = /* @__PURE__ */ new Map([
    [
      "namespace",
      new FunctionValue((args) => {
        if (args.length === 0) {
          return new ObjectValue(/* @__PURE__ */ new Map());
        }
        if (args.length !== 1 || !(args[0] instanceof ObjectValue)) {
          throw new Error("`namespace` expects either zero arguments or a single object argument");
        }
        return args[0];
      })
    ]
  ]);
  /**
   * The tests available in this environment.
   */
  tests = /* @__PURE__ */ new Map([
    ["boolean", (operand) => operand.type === "BooleanValue"],
    ["callable", (operand) => operand instanceof FunctionValue],
    [
      "odd",
      (operand) => {
        if (operand.type !== "NumericValue") {
          throw new Error(`Cannot apply test "odd" to type: ${operand.type}`);
        }
        return operand.value % 2 !== 0;
      }
    ],
    [
      "even",
      (operand) => {
        if (operand.type !== "NumericValue") {
          throw new Error(`Cannot apply test "even" to type: ${operand.type}`);
        }
        return operand.value % 2 === 0;
      }
    ],
    ["false", (operand) => operand.type === "BooleanValue" && !operand.value],
    ["true", (operand) => operand.type === "BooleanValue" && operand.value],
    ["number", (operand) => operand.type === "NumericValue"],
    ["integer", (operand) => operand.type === "NumericValue" && Number.isInteger(operand.value)],
    ["iterable", (operand) => operand instanceof ArrayValue || operand instanceof StringValue],
    [
      "lower",
      (operand) => {
        const str = operand.value;
        return operand.type === "StringValue" && str === str.toLowerCase();
      }
    ],
    [
      "upper",
      (operand) => {
        const str = operand.value;
        return operand.type === "StringValue" && str === str.toUpperCase();
      }
    ],
    ["none", (operand) => operand.type === "NullValue"],
    ["defined", (operand) => operand.type !== "UndefinedValue"],
    ["undefined", (operand) => operand.type === "UndefinedValue"],
    ["equalto", (a, b) => a.value === b.value]
  ]);
  /**
   * Set the value of a variable in the current environment.
   */
  set(name, value) {
    return this.declareVariable(name, convertToRuntimeValues(value));
  }
  declareVariable(name, value) {
    if (this.variables.has(name)) {
      throw new SyntaxError(`Variable already declared: ${name}`);
    }
    this.variables.set(name, value);
    return value;
  }
  // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue {
  // 	const env = this.resolve(name);
  // 	env.variables.set(name, value);
  // 	return value;
  // }
  /**
   * Set variable in the current scope.
   * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information.
   */
  setVariable(name, value) {
    this.variables.set(name, value);
    return value;
  }
  /**
   * Resolve the environment in which the variable is declared.
   * @param {string} name The name of the variable.
   * @returns {Environment} The environment in which the variable is declared.
   */
  resolve(name) {
    if (this.variables.has(name)) {
      return this;
    }
    if (this.parent) {
      return this.parent.resolve(name);
    }
    throw new Error(`Unknown variable: ${name}`);
  }
  lookupVariable(name) {
    try {
      return this.resolve(name).variables.get(name) ?? new UndefinedValue();
    } catch {
      return new UndefinedValue();
    }
  }
};
var Interpreter = class {
  global;
  constructor(env) {
    this.global = env ?? new Environment();
  }
  /**
   * Run the program.
   */
  run(program) {
    return this.evaluate(program, this.global);
  }
  /**
   * Evaluates expressions following the binary operation type.
   */
  evaluateBinaryExpression(node, environment) {
    const left = this.evaluate(node.left, environment);
    switch (node.operator.value) {
      case "and":
        return left.__bool__().value ? this.evaluate(node.right, environment) : left;
      case "or":
        return left.__bool__().value ? left : this.evaluate(node.right, environment);
    }
    const right = this.evaluate(node.right, environment);
    switch (node.operator.value) {
      case "==":
        return new BooleanValue(left.value == right.value);
      case "!=":
        return new BooleanValue(left.value != right.value);
    }
    if (left instanceof UndefinedValue || right instanceof UndefinedValue) {
      throw new Error("Cannot perform operation on undefined values");
    } else if (left instanceof NullValue || right instanceof NullValue) {
      throw new Error("Cannot perform operation on null values");
    } else if (left instanceof NumericValue && right instanceof NumericValue) {
      switch (node.operator.value) {
        case "+":
          return new NumericValue(left.value + right.value);
        case "-":
          return new NumericValue(left.value - right.value);
        case "*":
          return new NumericValue(left.value * right.value);
        case "/":
          return new NumericValue(left.value / right.value);
        case "%":
          return new NumericValue(left.value % right.value);
        case "<":
          return new BooleanValue(left.value < right.value);
        case ">":
          return new BooleanValue(left.value > right.value);
        case ">=":
          return new BooleanValue(left.value >= right.value);
        case "<=":
          return new BooleanValue(left.value <= right.value);
      }
    } else if (left instanceof ArrayValue && right instanceof ArrayValue) {
      switch (node.operator.value) {
        case "+":
          return new ArrayValue(left.value.concat(right.value));
      }
    } else if (right instanceof ArrayValue) {
      const member = right.value.find((x) => x.value === left.value) !== void 0;
      switch (node.operator.value) {
        case "in":
          return new BooleanValue(member);
        case "not in":
          return new BooleanValue(!member);
      }
    }
    if (left instanceof StringValue || right instanceof StringValue) {
      switch (node.operator.value) {
        case "+":
          return new StringValue(left.value.toString() + right.value.toString());
      }
    }
    if (left instanceof StringValue && right instanceof StringValue) {
      switch (node.operator.value) {
        case "in":
          return new BooleanValue(right.value.includes(left.value));
        case "not in":
          return new BooleanValue(!right.value.includes(left.value));
      }
    }
    if (left instanceof StringValue && right instanceof ObjectValue) {
      switch (node.operator.value) {
        case "in":
          return new BooleanValue(right.value.has(left.value));
        case "not in":
          return new BooleanValue(!right.value.has(left.value));
      }
    }
    throw new SyntaxError(`Unknown operator "${node.operator.value}" between ${left.type} and ${right.type}`);
  }
  /**
   * Evaluates expressions following the filter operation type.
   */
  evaluateFilterExpression(node, environment) {
    const operand = this.evaluate(node.operand, environment);
    if (node.filter.type === "Identifier") {
      const filter = node.filter;
      if (operand instanceof ArrayValue) {
        switch (filter.value) {
          case "list":
            return operand;
          case "first":
            return operand.value[0];
          case "last":
            return operand.value[operand.value.length - 1];
          case "length":
            return new NumericValue(operand.value.length);
          case "reverse":
            return new ArrayValue(operand.value.reverse());
          case "sort":
            return new ArrayValue(
              operand.value.sort((a, b) => {
                if (a.type !== b.type) {
                  throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`);
                }
                switch (a.type) {
                  case "NumericValue":
                    return a.value - b.value;
                  case "StringValue":
                    return a.value.localeCompare(b.value);
                  default:
                    throw new Error(`Cannot compare type: ${a.type}`);
                }
              })
            );
          default:
            throw new Error(`Unknown ArrayValue filter: ${filter.value}`);
        }
      } else if (operand instanceof StringValue) {
        switch (filter.value) {
          case "length":
            return new NumericValue(operand.value.length);
          case "upper":
            return new StringValue(operand.value.toUpperCase());
          case "lower":
            return new StringValue(operand.value.toLowerCase());
          case "title":
            return new StringValue(titleCase(operand.value));
          case "capitalize":
            return new StringValue(operand.value.charAt(0).toUpperCase() + operand.value.slice(1));
          case "trim":
            return new StringValue(operand.value.trim());
          default:
            throw new Error(`Unknown StringValue filter: ${filter.value}`);
        }
      } else if (operand instanceof NumericValue) {
        switch (filter.value) {
          case "abs":
            return new NumericValue(Math.abs(operand.value));
          default:
            throw new Error(`Unknown NumericValue filter: ${filter.value}`);
        }
      } else if (operand instanceof ObjectValue) {
        switch (filter.value) {
          case "items":
            return new ArrayValue(
              Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))
            );
          case "length":
            return new NumericValue(operand.value.size);
          default:
            throw new Error(`Unknown ObjectValue filter: ${filter.value}`);
        }
      }
      throw new Error(`Cannot apply filter "${filter.value}" to type: ${operand.type}`);
    } else if (node.filter.type === "CallExpression") {
      const filter = node.filter;
      if (filter.callee.type !== "Identifier") {
        throw new Error(`Unknown filter: ${filter.callee.type}`);
      }
      const filterName = filter.callee.value;
      if (operand instanceof ArrayValue) {
        switch (filterName) {
          case "selectattr": {
            if (operand.value.some((x) => !(x instanceof ObjectValue))) {
              throw new Error("`selectattr` can only be applied to array of objects");
            }
            if (filter.args.some((x) => x.type !== "StringLiteral")) {
              throw new Error("arguments of `selectattr` must be strings");
            }
            const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment));
            let testFunction;
            if (testName) {
              const test = environment.tests.get(testName.value);
              if (!test) {
                throw new Error(`Unknown test: ${testName.value}`);
              }
              testFunction = test;
            } else {
              testFunction = (...x) => x[0].__bool__().value;
            }
            const filtered = operand.value.filter((item) => {
              const a = item.value.get(attr.value);
              if (a) {
                return testFunction(a, value);
              }
              return false;
            });
            return new ArrayValue(filtered);
          }
        }
        throw new Error(`Unknown ArrayValue filter: ${filterName}`);
      } else {
        throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`);
      }
    }
    throw new Error(`Unknown filter: ${node.filter.type}`);
  }
  /**
   * Evaluates expressions following the test operation type.
   */
  evaluateTestExpression(node, environment) {
    const operand = this.evaluate(node.operand, environment);
    const test = environment.tests.get(node.test.value);
    if (!test) {
      throw new Error(`Unknown test: ${node.test.value}`);
    }
    const result = test(operand);
    return new BooleanValue(node.negate ? !result : result);
  }
  /**
   * Evaluates expressions following the unary operation type.
   */
  evaluateUnaryExpression(node, environment) {
    const argument = this.evaluate(node.argument, environment);
    switch (node.operator.value) {
      case "not":
        return new BooleanValue(!argument.value);
      default:
        throw new SyntaxError(`Unknown operator: ${node.operator.value}`);
    }
  }
  evalProgram(program, environment) {
    return this.evaluateBlock(program.body, environment);
  }
  evaluateBlock(statements, environment) {
    let result = "";
    for (const statement of statements) {
      const lastEvaluated = this.evaluate(statement, environment);
      if (lastEvaluated.type !== "NullValue" && lastEvaluated.type !== "UndefinedValue") {
        result += lastEvaluated.value;
      }
    }
    return new StringValue(result);
  }
  evaluateIdentifier(node, environment) {
    return environment.lookupVariable(node.value);
  }
  evaluateCallExpression(expr, environment) {
    const args = [];
    const kwargs = /* @__PURE__ */ new Map();
    for (const argument of expr.args) {
      if (argument.type === "KeywordArgumentExpression") {
        const kwarg = argument;
        kwargs.set(kwarg.key.value, this.evaluate(kwarg.value, environment));
      } else {
        args.push(this.evaluate(argument, environment));
      }
    }
    if (kwargs.size > 0) {
      args.push(new ObjectValue(kwargs));
    }
    const fn = this.evaluate(expr.callee, environment);
    if (fn.type !== "FunctionValue") {
      throw new Error(`Cannot call something that is not a function: got ${fn.type}`);
    }
    return fn.value(args, environment);
  }
  evaluateSliceExpression(object, expr, environment) {
    if (!(object instanceof ArrayValue || object instanceof StringValue)) {
      throw new Error("Slice object must be an array or string");
    }
    const start = this.evaluate(expr.start, environment);
    const stop = this.evaluate(expr.stop, environment);
    const step = this.evaluate(expr.step, environment);
    if (!(start instanceof NumericValue || start instanceof UndefinedValue)) {
      throw new Error("Slice start must be numeric or undefined");
    }
    if (!(stop instanceof NumericValue || stop instanceof UndefinedValue)) {
      throw new Error("Slice stop must be numeric or undefined");
    }
    if (!(step instanceof NumericValue || step instanceof UndefinedValue)) {
      throw new Error("Slice step must be numeric or undefined");
    }
    if (object instanceof ArrayValue) {
      return new ArrayValue(slice(object.value, start.value, stop.value, step.value));
    } else {
      return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join(""));
    }
  }
  evaluateMemberExpression(expr, environment) {
    const object = this.evaluate(expr.object, environment);
    let property;
    if (expr.computed) {
      if (expr.property.type === "SliceExpression") {
        return this.evaluateSliceExpression(object, expr.property, environment);
      } else {
        property = this.evaluate(expr.property, environment);
      }
    } else {
      property = new StringValue(expr.property.value);
    }
    let value;
    if (object instanceof ObjectValue) {
      if (!(property instanceof StringValue)) {
        throw new Error(`Cannot access property with non-string: got ${property.type}`);
      }
      value = object.value.get(property.value) ?? object.builtins.get(property.value);
    } else if (object instanceof ArrayValue || object instanceof StringValue) {
      if (property instanceof NumericValue) {
        value = object.value.at(property.value);
        if (object instanceof StringValue) {
          value = new StringValue(object.value.at(property.value));
        }
      } else if (property instanceof StringValue) {
        value = object.builtins.get(property.value);
      } else {
        throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`);
      }
    } else {
      if (!(property instanceof StringValue)) {
        throw new Error(`Cannot access property with non-string: got ${property.type}`);
      }
      value = object.builtins.get(property.value);
    }
    return value instanceof RuntimeValue ? value : new UndefinedValue();
  }
  evaluateSet(node, environment) {
    const rhs = this.evaluate(node.value, environment);
    if (node.assignee.type === "Identifier") {
      const variableName = node.assignee.value;
      environment.setVariable(variableName, rhs);
    } else if (node.assignee.type === "MemberExpression") {
      const member = node.assignee;
      const object = this.evaluate(member.object, environment);
      if (!(object instanceof ObjectValue)) {
        throw new Error("Cannot assign to member of non-object");
      }
      if (member.property.type !== "Identifier") {
        throw new Error("Cannot assign to member with non-identifier property");
      }
      object.value.set(member.property.value, rhs);
    } else {
      throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`);
    }
    return new NullValue();
  }
  evaluateIf(node, environment) {
    const test = this.evaluate(node.test, environment);
    return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment);
  }
  evaluateFor(node, environment) {
    const scope = new Environment(environment);
    const iterable = this.evaluate(node.iterable, scope);
    if (!(iterable instanceof ArrayValue)) {
      throw new Error(`Expected iterable type in for loop: got ${iterable.type}`);
    }
    let result = "";
    for (let i = 0; i < iterable.value.length; ++i) {
      const loop = /* @__PURE__ */ new Map([
        ["index", new NumericValue(i + 1)],
        ["index0", new NumericValue(i)],
        ["revindex", new NumericValue(iterable.value.length - i)],
        ["revindex0", new NumericValue(iterable.value.length - i - 1)],
        ["first", new BooleanValue(i === 0)],
        ["last", new BooleanValue(i === iterable.value.length - 1)],
        ["length", new NumericValue(iterable.value.length)],
        ["previtem", i > 0 ? iterable.value[i - 1] : new UndefinedValue()],
        ["nextitem", i < iterable.value.length - 1 ? iterable.value[i + 1] : new UndefinedValue()]
      ]);
      scope.setVariable("loop", new ObjectValue(loop));
      const current = iterable.value[i];
      if (node.loopvar.type === "Identifier") {
        scope.setVariable(node.loopvar.value, current);
      } else if (node.loopvar.type === "TupleLiteral") {
        const loopvar = node.loopvar;
        if (current.type !== "ArrayValue") {
          throw new Error(`Cannot unpack non-iterable type: ${current.type}`);
        }
        const c = current;
        if (loopvar.value.length !== c.value.length) {
          throw new Error(`Too ${loopvar.value.length > c.value.length ? "few" : "many"} items to unpack`);
        }
        for (let j = 0; j < loopvar.value.length; ++j) {
          if (loopvar.value[j].type !== "Identifier") {
            throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`);
          }
          scope.setVariable(loopvar.value[j].value, c.value[j]);
        }
      }
      const evaluated = this.evaluateBlock(node.body, scope);
      result += evaluated.value;
    }
    return new StringValue(result);
  }
  evaluate(statement, environment) {
    if (statement === void 0)
      return new UndefinedValue();
    switch (statement.type) {
      case "Program":
        return this.evalProgram(statement, environment);
      case "Set":
        return this.evaluateSet(statement, environment);
      case "If":
        return this.evaluateIf(statement, environment);
      case "For":
        return this.evaluateFor(statement, environment);
      case "NumericLiteral":
        return new NumericValue(Number(statement.value));
      case "StringLiteral":
        return new StringValue(statement.value);
      case "BooleanLiteral":
        return new BooleanValue(statement.value);
      case "ArrayLiteral":
        return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment)));
      case "TupleLiteral":
        return new TupleValue(statement.value.map((x) => this.evaluate(x, environment)));
      case "ObjectLiteral": {
        const mapping = /* @__PURE__ */ new Map();
        for (const [key, value] of statement.value) {
          const evaluatedKey = this.evaluate(key, environment);
          if (!(evaluatedKey instanceof StringValue)) {
            throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`);
          }
          mapping.set(evaluatedKey.value, this.evaluate(value, environment));
        }
        return new ObjectValue(mapping);
      }
      case "Identifier":
        return this.evaluateIdentifier(statement, environment);
      case "CallExpression":
        return this.evaluateCallExpression(statement, environment);
      case "MemberExpression":
        return this.evaluateMemberExpression(statement, environment);
      case "UnaryExpression":
        return this.evaluateUnaryExpression(statement, environment);
      case "BinaryExpression":
        return this.evaluateBinaryExpression(statement, environment);
      case "FilterExpression":
        return this.evaluateFilterExpression(statement, environment);
      case "TestExpression":
        return this.evaluateTestExpression(statement, environment);
      default:
        throw new SyntaxError(`Unknown node type: ${statement.type}`);
    }
  }
};
function convertToRuntimeValues(input) {
  switch (typeof input) {
    case "number":
      return new NumericValue(input);
    case "string":
      return new StringValue(input);
    case "boolean":
      return new BooleanValue(input);
    case "object":
      if (input === null) {
        return new NullValue();
      } else if (Array.isArray(input)) {
        return new ArrayValue(input.map(convertToRuntimeValues));
      } else {
        return new ObjectValue(
          new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)]))
        );
      }
    case "function":
      return new FunctionValue((args, _scope) => {
        const result = input(...args.map((x) => x.value)) ?? null;
        return convertToRuntimeValues(result);
      });
    default:
      throw new Error(`Cannot convert to runtime value: ${input}`);
  }
}

// src/index.ts
var Template = class {
  parsed;
  /**
   * @param {string} template The template string
   */
  constructor(template) {
    const tokens = tokenize(template, {
      lstrip_blocks: true,
      trim_blocks: true
    });
    this.parsed = parse(tokens);
  }
  render(items) {
    const env = new Environment();
    env.set("false", false);
    env.set("true", true);
    env.set("raise_exception", (args) => {
      throw new Error(args);
    });
    env.set("range", range);
    for (const [key, value] of Object.entries(items)) {
      env.set(key, value);
    }
    const interpreter = new Interpreter(env);
    const result = interpreter.run(this.parsed);
    return result.value;
  }
};



/***/ }),

/***/ "./src/backends/onnx.js":
/*!******************************!*\
  !*** ./src/backends/onnx.js ***!
  \******************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

var onnxruntime_node__WEBPACK_IMPORTED_MODULE_0___namespace_cache;
var onnxruntime_web__WEBPACK_IMPORTED_MODULE_1___namespace_cache;
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ONNX": () => (/* binding */ ONNX),
/* harmony export */   "executionProviders": () => (/* binding */ executionProviders)
/* harmony export */ });
/* harmony import */ var onnxruntime_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! onnxruntime-node */ "?2ce3");
/* harmony import */ var onnxruntime_web__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! onnxruntime-web */ "./node_modules/onnxruntime-web/dist/ort-web.min.js");
/**
 * @file Handler file for choosing the correct version of ONNX Runtime, based on the environment.
 * Ideally, we could import the `onnxruntime-web` and `onnxruntime-node` packages only when needed,
 * but dynamic imports don't seem to work with the current webpack version and/or configuration.
 * This is possibly due to the experimental nature of top-level await statements.
 * So, we just import both packages, and use the appropriate one based on the environment:
 *   - When running in node, we use `onnxruntime-node`.
 *   - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled).
 * 
 * This module is not directly exported, but can be accessed through the environment variables:
 * ```javascript
 * import { env } from '@xenova/transformers';
 * console.log(env.backends.onnx);
 * ```
 * 
 * @module backends/onnx
 */

// NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`.
// In either case, we select the default export if it exists, otherwise we use the named export.



/** @type {import('onnxruntime-web')} The ONNX runtime module. */
let ONNX;

const executionProviders = [
    // 'webgpu',
    'wasm'
];

if (typeof process !== 'undefined' && process?.release?.name === 'node') {
    // Running in a node-like environment.
    ONNX = onnxruntime_node__WEBPACK_IMPORTED_MODULE_0__ ?? /*#__PURE__*/ (onnxruntime_node__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (onnxruntime_node__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(onnxruntime_node__WEBPACK_IMPORTED_MODULE_0__, 2)));

    // Add `cpu` execution provider, with higher precedence that `wasm`.
    executionProviders.unshift('cpu');

} else {
    // Running in a browser-environment
    ONNX = onnxruntime_web__WEBPACK_IMPORTED_MODULE_1__ ?? /*#__PURE__*/ (onnxruntime_web__WEBPACK_IMPORTED_MODULE_1___namespace_cache || (onnxruntime_web__WEBPACK_IMPORTED_MODULE_1___namespace_cache = __webpack_require__.t(onnxruntime_web__WEBPACK_IMPORTED_MODULE_1__, 2)));

    // SIMD for WebAssembly does not operate correctly in some recent versions of iOS (16.4.x).
    // As a temporary fix, we disable it for now.
    // For more information, see: https://github.com/microsoft/onnxruntime/issues/15644
    const isIOS = typeof navigator !== 'undefined' && /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);
    if (isIOS) {
        ONNX.env.wasm.simd = false;
    }
}


/***/ }),

/***/ "./src/configs.js":
/*!************************!*\
  !*** ./src/configs.js ***!
  \************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "AutoConfig": () => (/* binding */ AutoConfig),
/* harmony export */   "PretrainedConfig": () => (/* binding */ PretrainedConfig)
/* harmony export */ });
/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/hub.js */ "./src/utils/hub.js");

/**
 * @file Helper module for using model configs. For more information, see the corresponding
 * [Python documentation](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoConfig).
 * 
 * **Example:** Load an `AutoConfig`.
 * 
 * ```javascript
 * import { AutoConfig } from '@xenova/transformers';
 * let config = await AutoConfig.from_pretrained('bert-base-uncased');
 * console.log(config);
 * // PretrainedConfig {
 * //   "model_type": "bert",
 * //   "is_encoder_decoder": false,
 * //   "architectures": [
 * //       "BertForMaskedLM"
 * //   ],
 * //   "vocab_size": 30522
 * //   "num_attention_heads": 12,
 * //   "num_hidden_layers": 12,
 * //   "hidden_size": 768,
 * //   "max_position_embeddings": 512,
 * //   ...
 * // }
 * ```
 * 
 * @module configs
 */



/**
 * @typedef {import('./utils/hub.js').PretrainedOptions} PretrainedOptions
 */


/**
 * Loads a config from the specified path.
 * @param {string} pretrained_model_name_or_path The path to the config directory.
 * @param {PretrainedOptions} options Additional options for loading the config.
 * @returns {Promise<Array>} A promise that resolves with information about the loaded config.
 */
async function loadConfig(pretrained_model_name_or_path, options) {
    let info = await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_0__.getModelJSON)(pretrained_model_name_or_path, 'config.json', true, options);
    return info;
}

/**
 * Base class for all configuration classes. For more information, see the corresponding
 * [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).
 */
class PretrainedConfig {
    // NOTE: Typo in original

    /**
     * Create a new PreTrainedTokenizer instance.
     * @param {Object} configJSON The JSON of the config.
     */
    constructor(configJSON) {
        this.model_type = null;
        this.is_encoder_decoder = false;

        Object.assign(this, configJSON);
    }

    /**
     * Loads a pre-trained config from the given `pretrained_model_name_or_path`. 
     * 
     * @param {string} pretrained_model_name_or_path The path to the pre-trained config.
     * @param {PretrainedOptions} options Additional options for loading the config.
     * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
     * 
     * @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
     */
    static async from_pretrained(pretrained_model_name_or_path, {
        progress_callback = null,
        config = null,
        cache_dir = null,
        local_files_only = false,
        revision = 'main',
    } = {}) {

        let data = config ?? await loadConfig(pretrained_model_name_or_path, {
            progress_callback,
            config,
            cache_dir,
            local_files_only,
            revision,
        })
        return new this(data);
    }
}

/**
 * Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.
 * 
 * @example
 * let config = await AutoConfig.from_pretrained('bert-base-uncased'); 
 */
class AutoConfig {
    /** @type {PretrainedConfig.from_pretrained} */
    static async from_pretrained(...args) {
        return PretrainedConfig.from_pretrained(...args);
    }
}


/***/ }),

/***/ "./src/env.js":
/*!********************!*\
  !*** ./src/env.js ***!
  \********************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "env": () => (/* binding */ env)
/* harmony export */ });
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "?569f");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! path */ "?3f59");
/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! url */ "?154a");
/* harmony import */ var _backends_onnx_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./backends/onnx.js */ "./src/backends/onnx.js");
/**
 * @file Module used to configure Transformers.js.
 * 
 * **Example:** Disable remote models.
 * ```javascript
 * import { env } from '@xenova/transformers';
 * env.allowRemoteModels = false;
 * ```
 * 
 * **Example:** Set local model path.
 * ```javascript
 * import { env } from '@xenova/transformers';
 * env.localModelPath = '/path/to/local/models/';
 * ```
 * 
 * **Example:** Set cache directory.
 * ```javascript
 * import { env } from '@xenova/transformers';
 * env.cacheDir = '/path/to/cache/directory/';
 * ```
 * 
 * @module env
 */






const { env: onnx_env } = _backends_onnx_js__WEBPACK_IMPORTED_MODULE_3__.ONNX;

const VERSION = '2.17.2';

// Check if various APIs are available (depends on environment)
const WEB_CACHE_AVAILABLE = typeof self !== 'undefined' && 'caches' in self;
const FS_AVAILABLE = !isEmpty(fs__WEBPACK_IMPORTED_MODULE_0__); // check if file system is available
const PATH_AVAILABLE = !isEmpty(path__WEBPACK_IMPORTED_MODULE_1__); // check if path is available

const RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE;

const __dirname = RUNNING_LOCALLY
    ? path__WEBPACK_IMPORTED_MODULE_1__.dirname(path__WEBPACK_IMPORTED_MODULE_1__.dirname(url__WEBPACK_IMPORTED_MODULE_2__.fileURLToPath("file:///home/runner/work/transformers.js/transformers.js/src/env.js")))
    : './';

// Only used for environments with access to file system
const DEFAULT_CACHE_DIR = RUNNING_LOCALLY
    ? path__WEBPACK_IMPORTED_MODULE_1__.join(__dirname, '/.cache/')
    : null;

// Set local model path, based on available APIs
const DEFAULT_LOCAL_MODEL_PATH = '/models/';
const localModelPath = RUNNING_LOCALLY
    ? path__WEBPACK_IMPORTED_MODULE_1__.join(__dirname, DEFAULT_LOCAL_MODEL_PATH)
    : DEFAULT_LOCAL_MODEL_PATH;

if (onnx_env?.wasm) {
    // Set path to wasm files. This is needed when running in a web worker.
    // https://onnxruntime.ai/docs/api/js/interfaces/Env.WebAssemblyFlags.html#wasmPaths
    // We use remote wasm files by default to make it easier for newer users.
    // In practice, users should probably self-host the necessary .wasm files.
    onnx_env.wasm.wasmPaths = RUNNING_LOCALLY
        ? path__WEBPACK_IMPORTED_MODULE_1__.join(__dirname, '/dist/')
        : `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;
}

/**
 * Global variable used to control execution. This provides users a simple way to configure Transformers.js.
 * @property {Object} backends Expose environment variables of different backends,
 * allowing users to set these variables if they want to.
 * @property {string} __dirname Directory name of module. Useful for resolving local paths.
 * @property {string} version This version of Transformers.js.
 * @property {boolean} allowRemoteModels Whether to allow loading of remote files, defaults to `true`.
 * If set to `false`, it will have the same effect as setting `local_files_only=true` when loading pipelines, models, tokenizers, processors, etc.
 * @property {string} remoteHost Host URL to load models from. Defaults to the Hugging Face Hub.
 * @property {string} remotePathTemplate Path template to fill in and append to `remoteHost` when loading models.
 * @property {boolean} allowLocalModels Whether to allow loading of local files, defaults to `true`.
 * If set to `false`, it will skip the local file check and try to load the model from the remote host.
 * @property {string} localModelPath Path to load local models from. Defaults to `/models/`.
 * @property {boolean} useFS Whether to use the file system to load files. By default, it is `true` if available.
 * @property {boolean} useBrowserCache Whether to use Cache API to cache models. By default, it is `true` if available.
 * @property {boolean} useFSCache Whether to use the file system to cache files. By default, it is `true` if available.
 * @property {string} cacheDir The directory to use for caching files with the file system. By default, it is `./.cache`.
 * @property {boolean} useCustomCache Whether to use a custom cache system (defined by `customCache`), defaults to `false`.
 * @property {Object} customCache The custom cache to use. Defaults to `null`. Note: this must be an object which
 * implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache
 */
const env = {
    /////////////////// Backends settings ///////////////////
    backends: {
        // onnxruntime-web/onnxruntime-node
        onnx: onnx_env,

        // TensorFlow.js
        tfjs: {},
    },

    __dirname,
    version: VERSION,

    /////////////////// Model settings ///////////////////
    allowRemoteModels: true,
    remoteHost: 'https://huggingface.co/',
    remotePathTemplate: '{model}/resolve/{revision}/',

    allowLocalModels: true,
    localModelPath: localModelPath,
    useFS: FS_AVAILABLE,

    /////////////////// Cache settings ///////////////////
    useBrowserCache: WEB_CACHE_AVAILABLE,

    useFSCache: FS_AVAILABLE,
    cacheDir: DEFAULT_CACHE_DIR,

    useCustomCache: false,
    customCache: null,
    //////////////////////////////////////////////////////
}


/**
 * @param {Object} obj
 * @private
 */
function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}



/***/ }),

/***/ "./src/models.js":
/*!***********************!*\
  !*** ./src/models.js ***!
  \***********************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ASTForAudioClassification": () => (/* binding */ ASTForAudioClassification),
/* harmony export */   "ASTModel": () => (/* binding */ ASTModel),
/* harmony export */   "ASTPreTrainedModel": () => (/* binding */ ASTPreTrainedModel),
/* harmony export */   "AlbertForMaskedLM": () => (/* binding */ AlbertForMaskedLM),
/* harmony export */   "AlbertForQuestionAnswering": () => (/* binding */ AlbertForQuestionAnswering),
/* harmony export */   "AlbertForSequenceClassification": () => (/* binding */ AlbertForSequenceClassification),
/* harmony export */   "AlbertModel": () => (/* binding */ AlbertModel),
/* harmony export */   "AlbertPreTrainedModel": () => (/* binding */ AlbertPreTrainedModel),
/* harmony export */   "AutoModel": () => (/* binding */ AutoModel),
/* harmony export */   "AutoModelForAudioClassification": () => (/* binding */ AutoModelForAudioClassification),
/* harmony export */   "AutoModelForAudioFrameClassification": () => (/* binding */ AutoModelForAudioFrameClassification),
/* harmony export */   "AutoModelForCTC": () => (/* binding */ AutoModelForCTC),
/* harmony export */   "AutoModelForCausalLM": () => (/* binding */ AutoModelForCausalLM),
/* harmony export */   "AutoModelForDepthEstimation": () => (/* binding */ AutoModelForDepthEstimation),
/* harmony export */   "AutoModelForDocumentQuestionAnswering": () => (/* binding */ AutoModelForDocumentQuestionAnswering),
/* harmony export */   "AutoModelForImageClassification": () => (/* binding */ AutoModelForImageClassification),
/* harmony export */   "AutoModelForImageFeatureExtraction": () => (/* binding */ AutoModelForImageFeatureExtraction),
/* harmony export */   "AutoModelForImageMatting": () => (/* binding */ AutoModelForImageMatting),
/* harmony export */   "AutoModelForImageSegmentation": () => (/* binding */ AutoModelForImageSegmentation),
/* harmony export */   "AutoModelForImageToImage": () => (/* binding */ AutoModelForImageToImage),
/* harmony export */   "AutoModelForMaskGeneration": () => (/* binding */ AutoModelForMaskGeneration),
/* harmony export */   "AutoModelForMaskedLM": () => (/* binding */ AutoModelForMaskedLM),
/* harmony export */   "AutoModelForObjectDetection": () => (/* binding */ AutoModelForObjectDetection),
/* harmony export */   "AutoModelForQuestionAnswering": () => (/* binding */ AutoModelForQuestionAnswering),
/* harmony export */   "AutoModelForSemanticSegmentation": () => (/* binding */ AutoModelForSemanticSegmentation),
/* harmony export */   "AutoModelForSeq2SeqLM": () => (/* binding */ AutoModelForSeq2SeqLM),
/* harmony export */   "AutoModelForSequenceClassification": () => (/* binding */ AutoModelForSequenceClassification),
/* harmony export */   "AutoModelForSpeechSeq2Seq": () => (/* binding */ AutoModelForSpeechSeq2Seq),
/* harmony export */   "AutoModelForTextToSpectrogram": () => (/* binding */ AutoModelForTextToSpectrogram),
/* harmony export */   "AutoModelForTextToWaveform": () => (/* binding */ AutoModelForTextToWaveform),
/* harmony export */   "AutoModelForTokenClassification": () => (/* binding */ AutoModelForTokenClassification),
/* harmony export */   "AutoModelForVision2Seq": () => (/* binding */ AutoModelForVision2Seq),
/* harmony export */   "AutoModelForXVector": () => (/* binding */ AutoModelForXVector),
/* harmony export */   "AutoModelForZeroShotObjectDetection": () => (/* binding */ AutoModelForZeroShotObjectDetection),
/* harmony export */   "BartForConditionalGeneration": () => (/* binding */ BartForConditionalGeneration),
/* harmony export */   "BartForSequenceClassification": () => (/* binding */ BartForSequenceClassification),
/* harmony export */   "BartModel": () => (/* binding */ BartModel),
/* harmony export */   "BartPretrainedModel": () => (/* binding */ BartPretrainedModel),
/* harmony export */   "BaseModelOutput": () => (/* binding */ BaseModelOutput),
/* harmony export */   "BeitForImageClassification": () => (/* binding */ BeitForImageClassification),
/* harmony export */   "BeitModel": () => (/* binding */ BeitModel),
/* harmony export */   "BeitPreTrainedModel": () => (/* binding */ BeitPreTrainedModel),
/* harmony export */   "BertForMaskedLM": () => (/* binding */ BertForMaskedLM),
/* harmony export */   "BertForQuestionAnswering": () => (/* binding */ BertForQuestionAnswering),
/* harmony export */   "BertForSequenceClassification": () => (/* binding */ BertForSequenceClassification),
/* harmony export */   "BertForTokenClassification": () => (/* binding */ BertForTokenClassification),
/* harmony export */   "BertModel": () => (/* binding */ BertModel),
/* harmony export */   "BertPreTrainedModel": () => (/* binding */ BertPreTrainedModel),
/* harmony export */   "BlenderbotForConditionalGeneration": () => (/* binding */ BlenderbotForConditionalGeneration),
/* harmony export */   "BlenderbotModel": () => (/* binding */ BlenderbotModel),
/* harmony export */   "BlenderbotPreTrainedModel": () => (/* binding */ BlenderbotPreTrainedModel),
/* harmony export */   "BlenderbotSmallForConditionalGeneration": () => (/* binding */ BlenderbotSmallForConditionalGeneration),
/* harmony export */   "BlenderbotSmallModel": () => (/* binding */ BlenderbotSmallModel),
/* harmony export */   "BlenderbotSmallPreTrainedModel": () => (/* binding */ BlenderbotSmallPreTrainedModel),
/* harmony export */   "BloomForCausalLM": () => (/* binding */ BloomForCausalLM),
/* harmony export */   "BloomModel": () => (/* binding */ BloomModel),
/* harmony export */   "BloomPreTrainedModel": () => (/* binding */ BloomPreTrainedModel),
/* harmony export */   "CLIPModel": () => (/* binding */ CLIPModel),
/* harmony export */   "CLIPPreTrainedModel": () => (/* binding */ CLIPPreTrainedModel),
/* harmony export */   "CLIPSegForImageSegmentation": () => (/* binding */ CLIPSegForImageSegmentation),
/* harmony export */   "CLIPSegModel": () => (/* binding */ CLIPSegModel),
/* harmony export */   "CLIPSegPreTrainedModel": () => (/* binding */ CLIPSegPreTrainedModel),
/* harmony export */   "CLIPTextModelWithProjection": () => (/* binding */ CLIPTextModelWithProjection),
/* harmony export */   "CLIPVisionModelWithProjection": () => (/* binding */ CLIPVisionModelWithProjection),
/* harmony export */   "CamembertForMaskedLM": () => (/* binding */ CamembertForMaskedLM),
/* harmony export */   "CamembertForQuestionAnswering": () => (/* binding */ CamembertForQuestionAnswering),
/* harmony export */   "CamembertForSequenceClassification": () => (/* binding */ CamembertForSequenceClassification),
/* harmony export */   "CamembertForTokenClassification": () => (/* binding */ CamembertForTokenClassification),
/* harmony export */   "CamembertModel": () => (/* binding */ CamembertModel),
/* harmony export */   "CamembertPreTrainedModel": () => (/* binding */ CamembertPreTrainedModel),
/* harmony export */   "CausalLMOutput": () => (/* binding */ CausalLMOutput),
/* harmony export */   "CausalLMOutputWithPast": () => (/* binding */ CausalLMOutputWithPast),
/* harmony export */   "ChineseCLIPModel": () => (/* binding */ ChineseCLIPModel),
/* harmony export */   "ChineseCLIPPreTrainedModel": () => (/* binding */ ChineseCLIPPreTrainedModel),
/* harmony export */   "ClapAudioModelWithProjection": () => (/* binding */ ClapAudioModelWithProjection),
/* harmony export */   "ClapModel": () => (/* binding */ ClapModel),
/* harmony export */   "ClapPreTrainedModel": () => (/* binding */ ClapPreTrainedModel),
/* harmony export */   "ClapTextModelWithProjection": () => (/* binding */ ClapTextModelWithProjection),
/* harmony export */   "CodeGenForCausalLM": () => (/* binding */ CodeGenForCausalLM),
/* harmony export */   "CodeGenModel": () => (/* binding */ CodeGenModel),
/* harmony export */   "CodeGenPreTrainedModel": () => (/* binding */ CodeGenPreTrainedModel),
/* harmony export */   "ConvBertForMaskedLM": () => (/* binding */ ConvBertForMaskedLM),
/* harmony export */   "ConvBertForQuestionAnswering": () => (/* binding */ ConvBertForQuestionAnswering),
/* harmony export */   "ConvBertForSequenceClassification": () => (/* binding */ ConvBertForSequenceClassification),
/* harmony export */   "ConvBertForTokenClassification": () => (/* binding */ ConvBertForTokenClassification),
/* harmony export */   "ConvBertModel": () => (/* binding */ ConvBertModel),
/* harmony export */   "ConvBertPreTrainedModel": () => (/* binding */ ConvBertPreTrainedModel),
/* harmony export */   "ConvNextForImageClassification": () => (/* binding */ ConvNextForImageClassification),
/* harmony export */   "ConvNextModel": () => (/* binding */ ConvNextModel),
/* harmony export */   "ConvNextPreTrainedModel": () => (/* binding */ ConvNextPreTrainedModel),
/* harmony export */   "ConvNextV2ForImageClassification": () => (/* binding */ ConvNextV2ForImageClassification),
/* harmony export */   "ConvNextV2Model": () => (/* binding */ ConvNextV2Model),
/* harmony export */   "ConvNextV2PreTrainedModel": () => (/* binding */ ConvNextV2PreTrainedModel),
/* harmony export */   "DPTForDepthEstimation": () => (/* binding */ DPTForDepthEstimation),
/* harmony export */   "DPTModel": () => (/* binding */ DPTModel),
/* harmony export */   "DPTPreTrainedModel": () => (/* binding */ DPTPreTrainedModel),
/* harmony export */   "DebertaForMaskedLM": () => (/* binding */ DebertaForMaskedLM),
/* harmony export */   "DebertaForQuestionAnswering": () => (/* binding */ DebertaForQuestionAnswering),
/* harmony export */   "DebertaForSequenceClassification": () => (/* binding */ DebertaForSequenceClassification),
/* harmony export */   "DebertaForTokenClassification": () => (/* binding */ DebertaForTokenClassification),
/* harmony export */   "DebertaModel": () => (/* binding */ DebertaModel),
/* harmony export */   "DebertaPreTrainedModel": () => (/* binding */ DebertaPreTrainedModel),
/* harmony export */   "DebertaV2ForMaskedLM": () => (/* binding */ DebertaV2ForMaskedLM),
/* harmony export */   "DebertaV2ForQuestionAnswering": () => (/* binding */ DebertaV2ForQuestionAnswering),
/* harmony export */   "DebertaV2ForSequenceClassification": () => (/* binding */ DebertaV2ForSequenceClassification),
/* harmony export */   "DebertaV2ForTokenClassification": () => (/* binding */ DebertaV2ForTokenClassification),
/* harmony export */   "DebertaV2Model": () => (/* binding */ DebertaV2Model),
/* harmony export */   "DebertaV2PreTrainedModel": () => (/* binding */ DebertaV2PreTrainedModel),
/* harmony export */   "DeiTForImageClassification": () => (/* binding */ DeiTForImageClassification),
/* harmony export */   "DeiTModel": () => (/* binding */ DeiTModel),
/* harmony export */   "DeiTPreTrainedModel": () => (/* binding */ DeiTPreTrainedModel),
/* harmony export */   "DepthAnythingForDepthEstimation": () => (/* binding */ DepthAnythingForDepthEstimation),
/* harmony export */   "DepthAnythingPreTrainedModel": () => (/* binding */ DepthAnythingPreTrainedModel),
/* harmony export */   "DetrForObjectDetection": () => (/* binding */ DetrForObjectDetection),
/* harmony export */   "DetrForSegmentation": () => (/* binding */ DetrForSegmentation),
/* harmony export */   "DetrModel": () => (/* binding */ DetrModel),
/* harmony export */   "DetrObjectDetectionOutput": () => (/* binding */ DetrObjectDetectionOutput),
/* harmony export */   "DetrPreTrainedModel": () => (/* binding */ DetrPreTrainedModel),
/* harmony export */   "DetrSegmentationOutput": () => (/* binding */ DetrSegmentationOutput),
/* harmony export */   "Dinov2ForImageClassification": () => (/* binding */ Dinov2ForImageClassification),
/* harmony export */   "Dinov2Model": () => (/* binding */ Dinov2Model),
/* harmony export */   "Dinov2PreTrainedModel": () => (/* binding */ Dinov2PreTrainedModel),
/* harmony export */   "DistilBertForMaskedLM": () => (/* binding */ DistilBertForMaskedLM),
/* harmony export */   "DistilBertForQuestionAnswering": () => (/* binding */ DistilBertForQuestionAnswering),
/* harmony export */   "DistilBertForSequenceClassification": () => (/* binding */ DistilBertForSequenceClassification),
/* harmony export */   "DistilBertForTokenClassification": () => (/* binding */ DistilBertForTokenClassification),
/* harmony export */   "DistilBertModel": () => (/* binding */ DistilBertModel),
/* harmony export */   "DistilBertPreTrainedModel": () => (/* binding */ DistilBertPreTrainedModel),
/* harmony export */   "DonutSwinModel": () => (/* binding */ DonutSwinModel),
/* harmony export */   "DonutSwinPreTrainedModel": () => (/* binding */ DonutSwinPreTrainedModel),
/* harmony export */   "EfficientNetForImageClassification": () => (/* binding */ EfficientNetForImageClassification),
/* harmony export */   "EfficientNetModel": () => (/* binding */ EfficientNetModel),
/* harmony export */   "EfficientNetPreTrainedModel": () => (/* binding */ EfficientNetPreTrainedModel),
/* harmony export */   "ElectraForMaskedLM": () => (/* binding */ ElectraForMaskedLM),
/* harmony export */   "ElectraForQuestionAnswering": () => (/* binding */ ElectraForQuestionAnswering),
/* harmony export */   "ElectraForSequenceClassification": () => (/* binding */ ElectraForSequenceClassification),
/* harmony export */   "ElectraForTokenClassification": () => (/* binding */ ElectraForTokenClassification),
/* harmony export */   "ElectraModel": () => (/* binding */ ElectraModel),
/* harmony export */   "ElectraPreTrainedModel": () => (/* binding */ ElectraPreTrainedModel),
/* harmony export */   "EsmForMaskedLM": () => (/* binding */ EsmForMaskedLM),
/* harmony export */   "EsmForSequenceClassification": () => (/* binding */ EsmForSequenceClassification),
/* harmony export */   "EsmForTokenClassification": () => (/* binding */ EsmForTokenClassification),
/* harmony export */   "EsmModel": () => (/* binding */ EsmModel),
/* harmony export */   "EsmPreTrainedModel": () => (/* binding */ EsmPreTrainedModel),
/* harmony export */   "FalconForCausalLM": () => (/* binding */ FalconForCausalLM),
/* harmony export */   "FalconModel": () => (/* binding */ FalconModel),
/* harmony export */   "FalconPreTrainedModel": () => (/* binding */ FalconPreTrainedModel),
/* harmony export */   "FastViTForImageClassification": () => (/* binding */ FastViTForImageClassification),
/* harmony export */   "FastViTModel": () => (/* binding */ FastViTModel),
/* harmony export */   "FastViTPreTrainedModel": () => (/* binding */ FastViTPreTrainedModel),
/* harmony export */   "GLPNForDepthEstimation": () => (/* binding */ GLPNForDepthEstimation),
/* harmony export */   "GLPNModel": () => (/* binding */ GLPNModel),
/* harmony export */   "GLPNPreTrainedModel": () => (/* binding */ GLPNPreTrainedModel),
/* harmony export */   "GPT2LMHeadModel": () => (/* binding */ GPT2LMHeadModel),
/* harmony export */   "GPT2Model": () => (/* binding */ GPT2Model),
/* harmony export */   "GPT2PreTrainedModel": () => (/* binding */ GPT2PreTrainedModel),
/* harmony export */   "GPTBigCodeForCausalLM": () => (/* binding */ GPTBigCodeForCausalLM),
/* harmony export */   "GPTBigCodeModel": () => (/* binding */ GPTBigCodeModel),
/* harmony export */   "GPTBigCodePreTrainedModel": () => (/* binding */ GPTBigCodePreTrainedModel),
/* harmony export */   "GPTJForCausalLM": () => (/* binding */ GPTJForCausalLM),
/* harmony export */   "GPTJModel": () => (/* binding */ GPTJModel),
/* harmony export */   "GPTJPreTrainedModel": () => (/* binding */ GPTJPreTrainedModel),
/* harmony export */   "GPTNeoForCausalLM": () => (/* binding */ GPTNeoForCausalLM),
/* harmony export */   "GPTNeoModel": () => (/* binding */ GPTNeoModel),
/* harmony export */   "GPTNeoPreTrainedModel": () => (/* binding */ GPTNeoPreTrainedModel),
/* harmony export */   "GPTNeoXForCausalLM": () => (/* binding */ GPTNeoXForCausalLM),
/* harmony export */   "GPTNeoXModel": () => (/* binding */ GPTNeoXModel),
/* harmony export */   "GPTNeoXPreTrainedModel": () => (/* binding */ GPTNeoXPreTrainedModel),
/* harmony export */   "HubertForCTC": () => (/* binding */ HubertForCTC),
/* harmony export */   "HubertForSequenceClassification": () => (/* binding */ HubertForSequenceClassification),
/* harmony export */   "HubertModel": () => (/* binding */ HubertModel),
/* harmony export */   "HubertPreTrainedModel": () => (/* binding */ HubertPreTrainedModel),
/* harmony export */   "ImageMattingOutput": () => (/* binding */ ImageMattingOutput),
/* harmony export */   "LlamaForCausalLM": () => (/* binding */ LlamaForCausalLM),
/* harmony export */   "LlamaModel": () => (/* binding */ LlamaModel),
/* harmony export */   "LlamaPreTrainedModel": () => (/* binding */ LlamaPreTrainedModel),
/* harmony export */   "LongT5ForConditionalGeneration": () => (/* binding */ LongT5ForConditionalGeneration),
/* harmony export */   "LongT5Model": () => (/* binding */ LongT5Model),
/* harmony export */   "LongT5PreTrainedModel": () => (/* binding */ LongT5PreTrainedModel),
/* harmony export */   "M2M100ForConditionalGeneration": () => (/* binding */ M2M100ForConditionalGeneration),
/* harmony export */   "M2M100Model": () => (/* binding */ M2M100Model),
/* harmony export */   "M2M100PreTrainedModel": () => (/* binding */ M2M100PreTrainedModel),
/* harmony export */   "MBartForCausalLM": () => (/* binding */ MBartForCausalLM),
/* harmony export */   "MBartForConditionalGeneration": () => (/* binding */ MBartForConditionalGeneration),
/* harmony export */   "MBartForSequenceClassification": () => (/* binding */ MBartForSequenceClassification),
/* harmony export */   "MBartModel": () => (/* binding */ MBartModel),
/* harmony export */   "MBartPreTrainedModel": () => (/* binding */ MBartPreTrainedModel),
/* harmony export */   "MPNetForMaskedLM": () => (/* binding */ MPNetForMaskedLM),
/* harmony export */   "MPNetForQuestionAnswering": () => (/* binding */ MPNetForQuestionAnswering),
/* harmony export */   "MPNetForSequenceClassification": () => (/* binding */ MPNetForSequenceClassification),
/* harmony export */   "MPNetForTokenClassification": () => (/* binding */ MPNetForTokenClassification),
/* harmony export */   "MPNetModel": () => (/* binding */ MPNetModel),
/* harmony export */   "MPNetPreTrainedModel": () => (/* binding */ MPNetPreTrainedModel),
/* harmony export */   "MT5ForConditionalGeneration": () => (/* binding */ MT5ForConditionalGeneration),
/* harmony export */   "MT5Model": () => (/* binding */ MT5Model),
/* harmony export */   "MT5PreTrainedModel": () => (/* binding */ MT5PreTrainedModel),
/* harmony export */   "MarianMTModel": () => (/* binding */ MarianMTModel),
/* harmony export */   "MarianModel": () => (/* binding */ MarianModel),
/* harmony export */   "MarianPreTrainedModel": () => (/* binding */ MarianPreTrainedModel),
/* harmony export */   "MaskedLMOutput": () => (/* binding */ MaskedLMOutput),
/* harmony export */   "MistralForCausalLM": () => (/* binding */ MistralForCausalLM),
/* harmony export */   "MistralModel": () => (/* binding */ MistralModel),
/* harmony export */   "MistralPreTrainedModel": () => (/* binding */ MistralPreTrainedModel),
/* harmony export */   "MobileBertForMaskedLM": () => (/* binding */ MobileBertForMaskedLM),
/* harmony export */   "MobileBertForQuestionAnswering": () => (/* binding */ MobileBertForQuestionAnswering),
/* harmony export */   "MobileBertForSequenceClassification": () => (/* binding */ MobileBertForSequenceClassification),
/* harmony export */   "MobileBertModel": () => (/* binding */ MobileBertModel),
/* harmony export */   "MobileBertPreTrainedModel": () => (/* binding */ MobileBertPreTrainedModel),
/* harmony export */   "MobileViTForImageClassification": () => (/* binding */ MobileViTForImageClassification),
/* harmony export */   "MobileViTModel": () => (/* binding */ MobileViTModel),
/* harmony export */   "MobileViTPreTrainedModel": () => (/* binding */ MobileViTPreTrainedModel),
/* harmony export */   "MobileViTV2ForImageClassification": () => (/* binding */ MobileViTV2ForImageClassification),
/* harmony export */   "MobileViTV2Model": () => (/* binding */ MobileViTV2Model),
/* harmony export */   "MobileViTV2PreTrainedModel": () => (/* binding */ MobileViTV2PreTrainedModel),
/* harmony export */   "ModelOutput": () => (/* binding */ ModelOutput),
/* harmony export */   "MptForCausalLM": () => (/* binding */ MptForCausalLM),
/* harmony export */   "MptModel": () => (/* binding */ MptModel),
/* harmony export */   "MptPreTrainedModel": () => (/* binding */ MptPreTrainedModel),
/* harmony export */   "NomicBertModel": () => (/* binding */ NomicBertModel),
/* harmony export */   "NomicBertPreTrainedModel": () => (/* binding */ NomicBertPreTrainedModel),
/* harmony export */   "OPTForCausalLM": () => (/* binding */ OPTForCausalLM),
/* harmony export */   "OPTModel": () => (/* binding */ OPTModel),
/* harmony export */   "OPTPreTrainedModel": () => (/* binding */ OPTPreTrainedModel),
/* harmony export */   "OwlViTForObjectDetection": () => (/* binding */ OwlViTForObjectDetection),
/* harmony export */   "OwlViTModel": () => (/* binding */ OwlViTModel),
/* harmony export */   "OwlViTPreTrainedModel": () => (/* binding */ OwlViTPreTrainedModel),
/* harmony export */   "Owlv2ForObjectDetection": () => (/* binding */ Owlv2ForObjectDetection),
/* harmony export */   "Owlv2Model": () => (/* binding */ Owlv2Model),
/* harmony export */   "Owlv2PreTrainedModel": () => (/* binding */ Owlv2PreTrainedModel),
/* harmony export */   "PhiForCausalLM": () => (/* binding */ PhiForCausalLM),
/* harmony export */   "PhiModel": () => (/* binding */ PhiModel),
/* harmony export */   "PhiPreTrainedModel": () => (/* binding */ PhiPreTrainedModel),
/* harmony export */   "PreTrainedModel": () => (/* binding */ PreTrainedModel),
/* harmony export */   "PretrainedMixin": () => (/* binding */ PretrainedMixin),
/* harmony export */   "QuestionAnsweringModelOutput": () => (/* binding */ QuestionAnsweringModelOutput),
/* harmony export */   "Qwen2ForCausalLM": () => (/* binding */ Qwen2ForCausalLM),
/* harmony export */   "Qwen2Model": () => (/* binding */ Qwen2Model),
/* harmony export */   "Qwen2PreTrainedModel": () => (/* binding */ Qwen2PreTrainedModel),
/* harmony export */   "ResNetForImageClassification": () => (/* binding */ ResNetForImageClassification),
/* harmony export */   "ResNetModel": () => (/* binding */ ResNetModel),
/* harmony export */   "ResNetPreTrainedModel": () => (/* binding */ ResNetPreTrainedModel),
/* harmony export */   "RoFormerForMaskedLM": () => (/* binding */ RoFormerForMaskedLM),
/* harmony export */   "RoFormerForQuestionAnswering": () => (/* binding */ RoFormerForQuestionAnswering),
/* harmony export */   "RoFormerForSequenceClassification": () => (/* binding */ RoFormerForSequenceClassification),
/* harmony export */   "RoFormerForTokenClassification": () => (/* binding */ RoFormerForTokenClassification),
/* harmony export */   "RoFormerModel": () => (/* binding */ RoFormerModel),
/* harmony export */   "RoFormerPreTrainedModel": () => (/* binding */ RoFormerPreTrainedModel),
/* harmony export */   "RobertaForMaskedLM": () => (/* binding */ RobertaForMaskedLM),
/* harmony export */   "RobertaForQuestionAnswering": () => (/* binding */ RobertaForQuestionAnswering),
/* harmony export */   "RobertaForSequenceClassification": () => (/* binding */ RobertaForSequenceClassification),
/* harmony export */   "RobertaForTokenClassification": () => (/* binding */ RobertaForTokenClassification),
/* harmony export */   "RobertaModel": () => (/* binding */ RobertaModel),
/* harmony export */   "RobertaPreTrainedModel": () => (/* binding */ RobertaPreTrainedModel),
/* harmony export */   "SamImageSegmentationOutput": () => (/* binding */ SamImageSegmentationOutput),
/* harmony export */   "SamModel": () => (/* binding */ SamModel),
/* harmony export */   "SamPreTrainedModel": () => (/* binding */ SamPreTrainedModel),
/* harmony export */   "SegformerForImageClassification": () => (/* binding */ SegformerForImageClassification),
/* harmony export */   "SegformerForSemanticSegmentation": () => (/* binding */ SegformerForSemanticSegmentation),
/* harmony export */   "SegformerModel": () => (/* binding */ SegformerModel),
/* harmony export */   "SegformerPreTrainedModel": () => (/* binding */ SegformerPreTrainedModel),
/* harmony export */   "Seq2SeqLMOutput": () => (/* binding */ Seq2SeqLMOutput),
/* harmony export */   "SequenceClassifierOutput": () => (/* binding */ SequenceClassifierOutput),
/* harmony export */   "SiglipModel": () => (/* binding */ SiglipModel),
/* harmony export */   "SiglipPreTrainedModel": () => (/* binding */ SiglipPreTrainedModel),
/* harmony export */   "SiglipTextModel": () => (/* binding */ SiglipTextModel),
/* harmony export */   "SiglipVisionModel": () => (/* binding */ SiglipVisionModel),
/* harmony export */   "SpeechT5ForSpeechToText": () => (/* binding */ SpeechT5ForSpeechToText),
/* harmony export */   "SpeechT5ForTextToSpeech": () => (/* binding */ SpeechT5ForTextToSpeech),
/* harmony export */   "SpeechT5HifiGan": () => (/* binding */ SpeechT5HifiGan),
/* harmony export */   "SpeechT5Model": () => (/* binding */ SpeechT5Model),
/* harmony export */   "SpeechT5PreTrainedModel": () => (/* binding */ SpeechT5PreTrainedModel),
/* harmony export */   "SqueezeBertForMaskedLM": () => (/* binding */ SqueezeBertForMaskedLM),
/* harmony export */   "SqueezeBertForQuestionAnswering": () => (/* binding */ SqueezeBertForQuestionAnswering),
/* harmony export */   "SqueezeBertForSequenceClassification": () => (/* binding */ SqueezeBertForSequenceClassification),
/* harmony export */   "SqueezeBertModel": () => (/* binding */ SqueezeBertModel),
/* harmony export */   "SqueezeBertPreTrainedModel": () => (/* binding */ SqueezeBertPreTrainedModel),
/* harmony export */   "StableLmForCausalLM": () => (/* binding */ StableLmForCausalLM),
/* harmony export */   "StableLmModel": () => (/* binding */ StableLmModel),
/* harmony export */   "StableLmPreTrainedModel": () => (/* binding */ StableLmPreTrainedModel),
/* harmony export */   "Starcoder2ForCausalLM": () => (/* binding */ Starcoder2ForCausalLM),
/* harmony export */   "Starcoder2Model": () => (/* binding */ Starcoder2Model),
/* harmony export */   "Starcoder2PreTrainedModel": () => (/* binding */ Starcoder2PreTrainedModel),
/* harmony export */   "Swin2SRForImageSuperResolution": () => (/* binding */ Swin2SRForImageSuperResolution),
/* harmony export */   "Swin2SRModel": () => (/* binding */ Swin2SRModel),
/* harmony export */   "Swin2SRPreTrainedModel": () => (/* binding */ Swin2SRPreTrainedModel),
/* harmony export */   "SwinForImageClassification": () => (/* binding */ SwinForImageClassification),
/* harmony export */   "SwinModel": () => (/* binding */ SwinModel),
/* harmony export */   "SwinPreTrainedModel": () => (/* binding */ SwinPreTrainedModel),
/* harmony export */   "T5ForConditionalGeneration": () => (/* binding */ T5ForConditionalGeneration),
/* harmony export */   "T5Model": () => (/* binding */ T5Model),
/* harmony export */   "T5PreTrainedModel": () => (/* binding */ T5PreTrainedModel),
/* harmony export */   "TableTransformerForObjectDetection": () => (/* binding */ TableTransformerForObjectDetection),
/* harmony export */   "TableTransformerModel": () => (/* binding */ TableTransformerModel),
/* harmony export */   "TableTransformerObjectDetectionOutput": () => (/* binding */ TableTransformerObjectDetectionOutput),
/* harmony export */   "TableTransformerPreTrainedModel": () => (/* binding */ TableTransformerPreTrainedModel),
/* harmony export */   "TokenClassifierOutput": () => (/* binding */ TokenClassifierOutput),
/* harmony export */   "TrOCRForCausalLM": () => (/* binding */ TrOCRForCausalLM),
/* harmony export */   "TrOCRPreTrainedModel": () => (/* binding */ TrOCRPreTrainedModel),
/* harmony export */   "UniSpeechForCTC": () => (/* binding */ UniSpeechForCTC),
/* harmony export */   "UniSpeechForSequenceClassification": () => (/* binding */ UniSpeechForSequenceClassification),
/* harmony export */   "UniSpeechModel": () => (/* binding */ UniSpeechModel),
/* harmony export */   "UniSpeechPreTrainedModel": () => (/* binding */ UniSpeechPreTrainedModel),
/* harmony export */   "UniSpeechSatForAudioFrameClassification": () => (/* binding */ UniSpeechSatForAudioFrameClassification),
/* harmony export */   "UniSpeechSatForCTC": () => (/* binding */ UniSpeechSatForCTC),
/* harmony export */   "UniSpeechSatForSequenceClassification": () => (/* binding */ UniSpeechSatForSequenceClassification),
/* harmony export */   "UniSpeechSatModel": () => (/* binding */ UniSpeechSatModel),
/* harmony export */   "UniSpeechSatPreTrainedModel": () => (/* binding */ UniSpeechSatPreTrainedModel),
/* harmony export */   "ViTForImageClassification": () => (/* binding */ ViTForImageClassification),
/* harmony export */   "ViTModel": () => (/* binding */ ViTModel),
/* harmony export */   "ViTPreTrainedModel": () => (/* binding */ ViTPreTrainedModel),
/* harmony export */   "VisionEncoderDecoderModel": () => (/* binding */ VisionEncoderDecoderModel),
/* harmony export */   "VitMatteForImageMatting": () => (/* binding */ VitMatteForImageMatting),
/* harmony export */   "VitMattePreTrainedModel": () => (/* binding */ VitMattePreTrainedModel),
/* harmony export */   "VitsModel": () => (/* binding */ VitsModel),
/* harmony export */   "VitsModelOutput": () => (/* binding */ VitsModelOutput),
/* harmony export */   "VitsPreTrainedModel": () => (/* binding */ VitsPreTrainedModel),
/* harmony export */   "Wav2Vec2BertForCTC": () => (/* binding */ Wav2Vec2BertForCTC),
/* harmony export */   "Wav2Vec2BertForSequenceClassification": () => (/* binding */ Wav2Vec2BertForSequenceClassification),
/* harmony export */   "Wav2Vec2BertModel": () => (/* binding */ Wav2Vec2BertModel),
/* harmony export */   "Wav2Vec2BertPreTrainedModel": () => (/* binding */ Wav2Vec2BertPreTrainedModel),
/* harmony export */   "Wav2Vec2ForAudioFrameClassification": () => (/* binding */ Wav2Vec2ForAudioFrameClassification),
/* harmony export */   "Wav2Vec2ForCTC": () => (/* binding */ Wav2Vec2ForCTC),
/* harmony export */   "Wav2Vec2ForSequenceClassification": () => (/* binding */ Wav2Vec2ForSequenceClassification),
/* harmony export */   "Wav2Vec2Model": () => (/* binding */ Wav2Vec2Model),
/* harmony export */   "Wav2Vec2PreTrainedModel": () => (/* binding */ Wav2Vec2PreTrainedModel),
/* harmony export */   "WavLMForAudioFrameClassification": () => (/* binding */ WavLMForAudioFrameClassification),
/* harmony export */   "WavLMForCTC": () => (/* binding */ WavLMForCTC),
/* harmony export */   "WavLMForSequenceClassification": () => (/* binding */ WavLMForSequenceClassification),
/* harmony export */   "WavLMForXVector": () => (/* binding */ WavLMForXVector),
/* harmony export */   "WavLMModel": () => (/* binding */ WavLMModel),
/* harmony export */   "WavLMPreTrainedModel": () => (/* binding */ WavLMPreTrainedModel),
/* harmony export */   "WhisperForConditionalGeneration": () => (/* binding */ WhisperForConditionalGeneration),
/* harmony export */   "WhisperModel": () => (/* binding */ WhisperModel),
/* harmony export */   "WhisperPreTrainedModel": () => (/* binding */ WhisperPreTrainedModel),
/* harmony export */   "XLMForQuestionAnswering": () => (/* binding */ XLMForQuestionAnswering),
/* harmony export */   "XLMForSequenceClassification": () => (/* binding */ XLMForSequenceClassification),
/* harmony export */   "XLMForTokenClassification": () => (/* binding */ XLMForTokenClassification),
/* harmony export */   "XLMModel": () => (/* binding */ XLMModel),
/* harmony export */   "XLMPreTrainedModel": () => (/* binding */ XLMPreTrainedModel),
/* harmony export */   "XLMRobertaForMaskedLM": () => (/* binding */ XLMRobertaForMaskedLM),
/* harmony export */   "XLMRobertaForQuestionAnswering": () => (/* binding */ XLMRobertaForQuestionAnswering),
/* harmony export */   "XLMRobertaForSequenceClassification": () => (/* binding */ XLMRobertaForSequenceClassification),
/* harmony export */   "XLMRobertaForTokenClassification": () => (/* binding */ XLMRobertaForTokenClassification),
/* harmony export */   "XLMRobertaModel": () => (/* binding */ XLMRobertaModel),
/* harmony export */   "XLMRobertaPreTrainedModel": () => (/* binding */ XLMRobertaPreTrainedModel),
/* harmony export */   "XLMWithLMHeadModel": () => (/* binding */ XLMWithLMHeadModel),
/* harmony export */   "XVectorOutput": () => (/* binding */ XVectorOutput),
/* harmony export */   "YolosForObjectDetection": () => (/* binding */ YolosForObjectDetection),
/* harmony export */   "YolosModel": () => (/* binding */ YolosModel),
/* harmony export */   "YolosObjectDetectionOutput": () => (/* binding */ YolosObjectDetectionOutput),
/* harmony export */   "YolosPreTrainedModel": () => (/* binding */ YolosPreTrainedModel)
/* harmony export */ });
/* harmony import */ var _configs_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./configs.js */ "./src/configs.js");
/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/core.js */ "./src/utils/core.js");
/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/hub.js */ "./src/utils/hub.js");
/* harmony import */ var _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/generation.js */ "./src/utils/generation.js");
/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/tensor.js */ "./src/utils/tensor.js");
/* harmony import */ var _backends_onnx_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./backends/onnx.js */ "./src/backends/onnx.js");
/* harmony import */ var _transformers_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./transformers.js */ "./src/transformers.js");

/**
 * @file Definitions of all models available in Transformers.js.
 * 
 * **Example:** Load and run an `AutoModel`.
 * 
 * ```javascript
 * import { AutoModel, AutoTokenizer } from '@xenova/transformers';
 *
 * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');
 * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased');
 *
 * let inputs = await tokenizer('I love transformers!');
 * let { logits } = await model(inputs);
 * // Tensor {
 * //     data: Float32Array(183132) [-7.117443084716797, -7.107812881469727, -7.092104911804199, ...]
 * //     dims: (3) [1, 6, 30522],
 * //     type: "float32",
 * //     size: 183132,
 * // }
 * ```
 * 
 * We also provide other `AutoModel`s (listed below), which you can use in the same way as the Python library. For example:
 * 
 * **Example:** Load and run an `AutoModelForSeq2SeqLM`.
 * ```javascript
 * import { AutoModelForSeq2SeqLM, AutoTokenizer } from '@xenova/transformers';
 * 
 * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/t5-small');
 * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small');
 *
 * let { input_ids } = await tokenizer('translate English to German: I love transformers!');
 * let outputs = await model.generate(input_ids);
 * let decoded = tokenizer.decode(outputs[0], { skip_special_tokens: true });
 * // 'Ich liebe Transformatoren!'
 * ```
 * 
 * @module models
 */













const { InferenceSession, Tensor: ONNXTensor, env } = _backends_onnx_js__WEBPACK_IMPORTED_MODULE_5__.ONNX;

/** @typedef {import('onnxruntime-web').InferenceSession} InferenceSession */

//////////////////////////////////////////////////
// Model types: used internally
const MODEL_TYPES = {
    EncoderOnly: 0,
    EncoderDecoder: 1,
    Seq2Seq: 2,
    Vision2Seq: 3,
    DecoderOnly: 4,
    MaskGeneration: 5,
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Helper functions

// NOTE: These will be populated fully later
const MODEL_TYPE_MAPPING = new Map();
const MODEL_NAME_TO_CLASS_MAPPING = new Map();
const MODEL_CLASS_TO_NAME_MAPPING = new Map();


/**
 * Constructs an InferenceSession using a model file located at the specified path.
 * @param {string} pretrained_model_name_or_path The path to the directory containing the model file.
 * @param {string} fileName The name of the model file.
 * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model.
 * @returns {Promise<InferenceSession>} A Promise that resolves to an InferenceSession object.
 * @private
 */
async function constructSession(pretrained_model_name_or_path, fileName, options) {
    // TODO add option for user to force specify their desired execution provider
    let modelFileName = `onnx/${fileName}${options.quantized ? '_quantized' : ''}.onnx`;
    let buffer = await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelFile)(pretrained_model_name_or_path, modelFileName, true, options);

    try {
        return await InferenceSession.create(buffer, {
            executionProviders: _backends_onnx_js__WEBPACK_IMPORTED_MODULE_5__.executionProviders,
        });
    } catch (err) {
        // If the execution provided was only wasm, throw the error
        if (_backends_onnx_js__WEBPACK_IMPORTED_MODULE_5__.executionProviders.length === 1 && _backends_onnx_js__WEBPACK_IMPORTED_MODULE_5__.executionProviders[0] === 'wasm') {
            throw err;
        }

        console.warn(err);
        console.warn(
            'Something went wrong during model construction (most likely a missing operation). ' +
            'Using `wasm` as a fallback. '
        )
        return await InferenceSession.create(buffer, {
            executionProviders: ['wasm']
        });
    }
}

/**
 * Validate model inputs
 * @param {InferenceSession} session The InferenceSession object that will be run.
 * @param {Record<string, Tensor>} inputs The inputs to check.
 * @returns {Record<string, Tensor>} The checked inputs.
 * @throws {Error} If any inputs are missing.
 * @private
 */
function validateInputs(session, inputs) {
    /**
     * NOTE: Create either a shallow or deep copy based on `onnx.wasm.proxy`
     * @type {Record<string, Tensor>}
     */
    const checkedInputs = Object.create(null);
    const missingInputs = [];
    for (const inputName of session.inputNames) {
        const tensor = inputs[inputName];
        // Rare case where one of the model's input names corresponds to a built-in
        // object name (e.g., toString), which would cause a simple (!tensor) check to fail,
        // because it's not undefined but a function.
        if (!(tensor instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor)) {
            missingInputs.push(inputName);
            continue;
        }
        // NOTE: When `env.wasm.proxy is true` the tensor is moved across the Worker
        // boundary, transferring ownership to the worker and invalidating the tensor.
        // So, in this case, we simply sacrifice a clone for it.
        checkedInputs[inputName] = env.wasm.proxy ? tensor.clone() : tensor;
    }
    if (missingInputs.length > 0) {
        throw new Error(
            `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(', ')}.`);
    }

    const numInputsProvided = Object.keys(inputs).length;
    const numInputsNeeded = session.inputNames.length;
    if (numInputsProvided > numInputsNeeded) {
        // No missing inputs, but too many inputs were provided.
        // Warn the user and ignore the extra inputs.
        let ignored = Object.keys(inputs).filter(inputName => !session.inputNames.includes(inputName));
        console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(', ')}".`);
    }

    return checkedInputs;
}

/**
 * Executes an InferenceSession using the specified inputs.
 * NOTE: `inputs` must contain at least the input names of the model.
 *  - If additional inputs are passed, they will be ignored.
 *  - If inputs are missing, an error will be thrown.
 * 
 * @param {InferenceSession} session The InferenceSession object to run.
 * @param {Object} inputs An object that maps input names to input tensors.
 * @returns {Promise<Object>} A Promise that resolves to an object that maps output names to output tensors.
 * @private
 */
async function sessionRun(session, inputs) {
    const checkedInputs = validateInputs(session, inputs);
    try {
        // @ts-ignore
        let output = await session.run(checkedInputs);
        output = replaceTensors(output);
        return output;
    } catch (e) {
        // This usually occurs when the inputs are of the wrong type.
        console.error(`An error occurred during model execution: "${e}".`);
        console.error('Inputs given to model:', checkedInputs);
        throw e;
    }
}

/**
 * Replaces ONNX Tensor objects with custom Tensor objects to support additional functions.
 * @param {Object} obj The object to replace tensor objects in.
 * @returns {Object} The object with tensor objects replaced by custom Tensor objects.
 * @private
 */
function replaceTensors(obj) {
    for (let prop in obj) {
        if (obj[prop] instanceof ONNXTensor) {
            obj[prop] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor(obj[prop]);
        } else if (typeof obj[prop] === 'object') {
            replaceTensors(obj[prop]);
        }
    }
    return obj;
}


/**
 * Converts an array or Tensor of integers to an int64 Tensor.
 * @param {Array|Tensor} items The input integers to be converted.
 * @returns {Tensor} The int64 Tensor with the converted values.
 * @throws {Error} If the input array is empty or the input is a batched Tensor and not all sequences have the same length.
 * @private
 */
function toI64Tensor(items) {
    if (items instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor) {
        return items;
    }
    // items is an array
    if (items.length === 0) {
        throw Error("items must be non-empty");
    }

    if (Array.isArray(items[0])) {
        // batched
        if (items.some(x => x.length !== items[0].length)) {
            throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.")
        }

        return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('int64',
            BigInt64Array.from(items.flat().map(x => BigInt(x))),
            [items.length, items[0].length]
        );
    } else {
        //flat
        return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('int64',
            BigInt64Array.from(items.map(x => BigInt(x))),
            [1, items.length]
        );
    }
}

/**
 * Prepares an attention mask for a sequence of tokens based on configuration options.
 * @param {Object} self The calling object instance.
 * @param {Tensor} tokens The input tokens.
 * @returns {Tensor} The attention mask tensor.
 * @private
 */
function prepareAttentionMask(self, tokens) {

    // Prepare attention mask
    let pad_token_id = self.config.pad_token_id ?? null;
    let eos_token_id = self.config.eos_token_id ?? null;
    if ((0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.isIntegralNumber)(eos_token_id)) {
        eos_token_id = [eos_token_id];
    }

    let is_pad_token_in_inputs = tokens.indexOf(pad_token_id) !== -1;
    let is_pad_token_not_equal_to_eos_token_id = (eos_token_id === null) || !eos_token_id.includes(pad_token_id)

    if (is_pad_token_in_inputs && is_pad_token_not_equal_to_eos_token_id) {
        let data = BigInt64Array.from(
            // Note: != so that int matches bigint
            // @ts-ignore
            tokens.data.map(x => x != pad_token_id)
        )
        return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('int64', data, tokens.dims)
    } else {
        return (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.ones_like)(tokens);
    }
}

/**
 * Add position IDs to the feeds object.
 * @param {Object} session The inference session.
 * @param {Object} feeds The input to the model.
 * @param {boolean} use_cache_branch Whether to use the cache branch of the model.
 * @returns {void}
 * @private
 */
function preparePositionIds(session, feeds, use_cache_branch) {
    if (!session.inputNames.includes('position_ids')) return;

    const data = new BigInt64Array(feeds.attention_mask.data.length);

    // Compute cumulative sum of the attention mask along the sequence length dimension
    for (let i = 0; i < feeds.attention_mask.dims[0]; ++i) {
        let start = i * feeds.attention_mask.dims[1];
        let sum = BigInt(0);
        for (let j = 0; j < feeds.attention_mask.dims[1]; ++j) {
            const index = start + j;
            if (feeds.attention_mask.data[index] === 0n) {
                data[index] = BigInt(1);
            } else { // === 1n
                data[index] = sum;
                sum += feeds.attention_mask.data[index];
            }
        }
    }

    feeds.position_ids = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('int64', data, feeds.attention_mask.dims);

    if (use_cache_branch) {
        feeds.position_ids = feeds.position_ids.slice(null, -1).unsqueeze_(-1);
    }
}

/**
 * Creates a boolean tensor with a single value.
 * @param {boolean} value The value of the tensor.
 * @returns {Tensor} The boolean tensor.
 * @private
 */
function boolTensor(value) {
    return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('bool', [value], [1]);
}

// JS doesn't support mixins, so we define some reused functions here, and allow "this" to be passed in
/**
 * Perform forward pass on the seq2seq model (both encoder and decoder).
 * @param {Object} self The seq2seq model object.
 * @param {Object} model_inputs The input object for the model containing encoder and decoder inputs.
 * @returns {Promise<Seq2SeqLMOutput>} Promise that resolves with the output of the seq2seq model.
 * @private
 */
async function seq2seqForward(self, model_inputs) {

    let { encoder_outputs, past_key_values } = model_inputs;

    if (!encoder_outputs) {
        // Encoder outputs are not given, so we must compute them.
        encoder_outputs = (await encoderForward(self, model_inputs)).last_hidden_state;
    }
    let decoderFeeds = {
        input_ids: model_inputs.decoder_input_ids,
        encoder_hidden_states: encoder_outputs,
    };
    const use_cache_branch = !!past_key_values;

    if (self.decoder_merged_session.inputNames.includes('use_cache_branch')) {
        decoderFeeds.use_cache_branch = boolTensor(use_cache_branch);
    }

    if (self.decoder_merged_session.inputNames.includes('encoder_attention_mask')) {
        decoderFeeds.encoder_attention_mask = model_inputs.attention_mask
    }

    preparePositionIds(self.decoder_merged_session, decoderFeeds, use_cache_branch);
    self.addPastKeyValues(decoderFeeds, past_key_values);

    const decoderResults = await sessionRun(self.decoder_merged_session, decoderFeeds);
    let logits = decoderResults.logits;
    past_key_values = self.getPastKeyValues(decoderResults, past_key_values);

    // Get cross attention and/or decoder attentions if they are present
    const attns = self.getAttentions(decoderResults);

    return new Seq2SeqLMOutput({ logits, past_key_values, encoder_outputs, ...attns });
}

/**
 * Start the beam search process for the seq2seq model.
 * @param {PreTrainedModel} self The seq2seq model object.
 * @param {Tensor} inputTokenIds Array of input token ids for each input sequence.
 * @param {Object} generation_config The generation config.
 * @param {number} numOutputTokens The maximum number of output tokens for the model.
 * @returns {Object[]} Array of beam search objects.
 * @private
 */
function seq2seqStartBeams(self, inputTokenIds, generation_config, numOutputTokens) {
    let beams = [];
    let beamId = 0;

    // @ts-ignore
    const requires_attention_mask = self.requires_attention_mask ?? true;

    // decoder_input_ids == output_token_ids
    let decoder_input_ids =
        generation_config.decoder_input_ids
        ?? generation_config.decoder_start_token_id
        ?? generation_config.bos_token_id
        ?? generation_config.eos_token_id;

    // Support input as tensor or list
    // TODO support batched decoder_input_ids
    if (decoder_input_ids instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor) {
        decoder_input_ids = decoder_input_ids.tolist().flat();
    } else if (!Array.isArray(decoder_input_ids)) {
        decoder_input_ids = [decoder_input_ids];
    }

    for (let tokens of inputTokenIds) {
        // TODO: Improve
        // Currently, just add back batch dimension.
        // In future, allow for true parallel execution
        tokens.dims = [1, ...tokens.dims]

        // Create beam
        let start = {
            inputs: tokens,
            encoder_outputs: null,
            prev_model_outputs: null,

            output_token_ids: decoder_input_ids,
            done: false,
            score: 0,
            id: beamId++ // assign unique id to beams
        }

        if (requires_attention_mask) {
            start.attention_mask = prepareAttentionMask(self, tokens);
        }

        beams.push(start);
    }

    return beams;
}

/**
 * Run beam search on the seq2seq model for a single beam.
 * @param {PreTrainedModel} self The seq2seq model object.
 * @param {Object} beam The beam search object for which to run the model.
 * @param {Object} options options
 * @param {string} [options.input_name='input_ids'] The name of the input tensor for the encoder.
 * @returns {Promise<Object>} Promise that resolves with the output of the seq2seq model for the given beam.
 * @private
 */
async function seq2seqRunBeam(self, beam) {
    const input_name = self.main_input_name;

    let decoder_input_ids = beam.output_token_ids;
    if (beam.prev_model_outputs) {
        // After the first step, `prev_model_outputs` won't be null.
        // So, we cut decoder_input_ids if past is used
        decoder_input_ids = decoder_input_ids.slice(-1);
    }

    // 1. Prepare
    let model_inputs = {
        [input_name]: beam.inputs,
        decoder_input_ids: toI64Tensor(decoder_input_ids),
        encoder_outputs: beam.encoder_outputs,
        past_key_values: beam.prev_model_outputs?.past_key_values,
    }
    if (beam.attention_mask) {
        model_inputs.attention_mask = beam.attention_mask
    }

    // 2. Run
    let output = await self.forward(model_inputs);

    // 3. Update
    beam.prev_model_outputs = output;
    beam.encoder_outputs = output.encoder_outputs;

    return output;
}

/**
 * Update a beam with a new token ID.
 * @param {Object} beam The beam to update.
 * @param {number} newTokenId The new token ID to add to the beam's output.
 * @private
 */
function seq2seqUpdatebeam(beam, newTokenId) {
    beam.output_token_ids = [...beam.output_token_ids, newTokenId];
}

/**
 * Forward pass of an encoder model.
 * @param {Object} self The encoder model.
 * @param {Object} model_inputs The input data to be used for the forward pass.
 * @returns {Promise<Object>} Promise that resolves with an object containing the model's outputs.
 * @private
 */
async function encoderForward(self, model_inputs) {
    const encoderFeeds = Object.create(null);
    for (const key of self.session.inputNames) {
        encoderFeeds[key] = model_inputs[key];
    }
    if (self.session.inputNames.includes('token_type_ids') && !encoderFeeds.token_type_ids) {
        // Assign default `token_type_ids` (all zeroes) to the `encoderFeeds` if the model expects it,
        // but they weren't created by the tokenizer.
        encoderFeeds.token_type_ids = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor(
            'int64',
            new BigInt64Array(encoderFeeds.input_ids.data.length),
            encoderFeeds.input_ids.dims
        )
    }
    return await sessionRun(self.session, encoderFeeds);
}


/**
 * Forward pass of a decoder model.
 * @param {Object} self The decoder model.
 * @param {Object} model_inputs The input data to be used for the forward pass.
 * @returns {Promise<Object>} Promise that resolves with an object containing the logits and past key values.
 * @private
 */
async function decoderForward(self, model_inputs) {
    let { input_ids, past_key_values, attention_mask } = model_inputs;
    let decoderFeeds = {
        input_ids: input_ids,
        attention_mask: attention_mask ?? prepareAttentionMask(self, input_ids),
    }
    const use_cache_branch = !!past_key_values;

    if (self.session.inputNames.includes('use_cache_branch')) {
        decoderFeeds.use_cache_branch = boolTensor(use_cache_branch);
    }

    preparePositionIds(self.session, decoderFeeds, use_cache_branch);

    self.addPastKeyValues(decoderFeeds, past_key_values);

    let decoderResults = await sessionRun(self.session, decoderFeeds);

    let logits = decoderResults.logits;

    past_key_values = self.getPastKeyValues(decoderResults, past_key_values);
    return { logits, past_key_values };
}

/**
 * Starts the generation of text by initializing the beams for the given input token IDs.
 * @param {Object} self The text generation model object.
 * @param {Tensor} inputTokenIds An tensor of input token IDs to generate text from.
 * @param {Object} generation_config The generation config.
 * @param {number} numOutputTokens The maximum number of tokens to generate for each beam.
 * @param {Tensor} [inputs_attention_mask] The attention mask tensor for the input token IDs.
 * @returns {Object[]} An array of beams initialized with the given inputs and parameters.
 * @private
 */
function decoderStartBeams(self, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) {
    let beams = [];

    let beamId = 0;
    for (let tokens of inputTokenIds) {
        let output_token_ids = tokens.tolist().map(Number);

        // TODO: Improve
        // Currently, just add back batch dimension.
        // In future, allow for true parallel execution
        tokens.dims = [1, ...tokens.dims]

        let attn_mask;
        if (inputs_attention_mask) {
            attn_mask = inputs_attention_mask[beamId];
            attn_mask.dims = [1, ...attn_mask.dims]

        } else {
            attn_mask = prepareAttentionMask(self, tokens)
        }

        let start = {
            input: tokens,
            model_input_ids: tokens,
            attention_mask: attn_mask,
            prev_model_outputs: null,

            output_token_ids: output_token_ids,
            num_output_tokens: numOutputTokens,

            done: false,
            score: 0,
            id: beamId++ // assign unique id to beams
        }

        beams.push(start);
    }
    return beams;
}

/**
 * Runs a single step of the text generation process for a given beam.
 *
 * @param {Object} self The decoder object.
 * @param {Object} beam The beam to run.
 * @param {Tensor} beam.input The input tensor.
 * @param {Tensor} beam.model_input_ids The input ids to the model.
 * @param {Tensor} beam.attention_mask The attention mask.
 * @param {Object} beam.prev_model_outputs The past key values.
 * @param {number[]} beam.output_token_ids The output token ids.
 * @returns {Promise<Object>} The output of the generation step.
 * @private
 */
async function decoderRunBeam(self, beam) {
    let attnMaskData = new BigInt64Array(beam.output_token_ids.length).fill(1n)

    // 1. Prepare
    let model_inputs = {
        input_ids: beam.model_input_ids,
        attention_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor(
            'int64',
            attnMaskData,
            [1, attnMaskData.length]
        ),
        past_key_values: beam.prev_model_outputs?.past_key_values,
    }

    // 2. Run
    let output = await self.forward(model_inputs);

    // 3. Update
    beam.prev_model_outputs = output;

    return output;
}

/**
 * Update a beam with a new token ID.
 * @param {Object} beam The beam to update.
 * @param {number} newTokenId The new token ID to add to the beam's output.
 * @private
 */
function decoderUpdatebeam(beam, newTokenId) {
    beam.output_token_ids = [...beam.output_token_ids, newTokenId];
    beam.model_input_ids = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('int64', [BigInt(newTokenId)], [1, 1]);
}

//////////////////////////////////////////////////

//////////////////////////////////////////////////
/**
 * A base class for pre-trained models that provides the model configuration and an ONNX session.
 */
class PreTrainedModel extends _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.Callable {
    main_input_name = 'input_ids';

    /**
     * Creates a new instance of the `PreTrainedModel` class.
     * @param {Object} config The model configuration.
     * @param {any} session session for the model.
     */
    constructor(config, session) {
        super();

        this.config = config;
        this.session = session;

        const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);
        const modelType = MODEL_TYPE_MAPPING.get(modelName);

        this.can_generate = false;
        this._runBeam = null;
        this._getStartBeams = null;
        this._updateBeam = null;
        this._forward = null;
        if (modelType === MODEL_TYPES.DecoderOnly) {
            this.can_generate = true;

            this._runBeam = decoderRunBeam;
            this._getStartBeams = decoderStartBeams;
            this._updateBeam = decoderUpdatebeam;
            this._forward = decoderForward;

        } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {
            this.can_generate = true;

            this._runBeam = seq2seqRunBeam;
            this._getStartBeams = seq2seqStartBeams;
            this._updateBeam = seq2seqUpdatebeam;
            this._forward = seq2seqForward;

        } else if (modelType === MODEL_TYPES.EncoderDecoder) {
            this._forward = encoderForward;

        } else { // should be MODEL_TYPES.EncoderOnly
            this._forward = encoderForward;
        }
    }

    /**
    * Disposes of all the ONNX sessions that were created during inference.
    * @returns {Promise<unknown[]>} An array of promises, one for each ONNX session that is being disposed.
    * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
    */
    async dispose() {
        const promises = [];
        for (let key of Object.keys(this)) {
            const item = this[key];
            // @ts-ignore
            if (item instanceof InferenceSession) {
                promises.push(item.handler.dispose())
            }
        }
        return await Promise.all(promises);
    }

    /**
     * Instantiate one of the model classes of the library from a pretrained model.
     * 
     * The model class to instantiate is selected based on the `model_type` property of the config object
     * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
     * 
     * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
     * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
     *   Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
     *   user or organization name, like `dbmdz/bert-base-german-cased`.
     * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.
     * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model.
     * 
     * @returns {Promise<PreTrainedModel>} A new instance of the `PreTrainedModel` class.
     */
    static async from_pretrained(pretrained_model_name_or_path, {
        quantized = true,
        progress_callback = null,
        config = null,
        cache_dir = null,
        local_files_only = false,
        revision = 'main',
        model_file_name = null,
    } = {}) {

        let options = {
            quantized,
            progress_callback,
            config,
            cache_dir,
            local_files_only,
            revision,
            model_file_name,
        }

        const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this);
        const modelType = MODEL_TYPE_MAPPING.get(modelName);

        let info;
        if (modelType === MODEL_TYPES.DecoderOnly) {
            info = await Promise.all([
                _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
                constructSession(pretrained_model_name_or_path, options.model_file_name ?? 'decoder_model_merged', options),
                (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, 'generation_config.json', false, options),
            ]);

        } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {
            info = await Promise.all([
                _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
                constructSession(pretrained_model_name_or_path, 'encoder_model', options),
                constructSession(pretrained_model_name_or_path, 'decoder_model_merged', options),
                (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, 'generation_config.json', false, options),
            ]);

        } else if (modelType === MODEL_TYPES.MaskGeneration) {
            info = await Promise.all([
                _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
                constructSession(pretrained_model_name_or_path, 'vision_encoder', options),
                constructSession(pretrained_model_name_or_path, 'prompt_encoder_mask_decoder', options),
            ]);

        } else if (modelType === MODEL_TYPES.EncoderDecoder) {
            info = await Promise.all([
                _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
                constructSession(pretrained_model_name_or_path, 'encoder_model', options),
                constructSession(pretrained_model_name_or_path, 'decoder_model_merged', options),
            ]);

        } else { // should be MODEL_TYPES.EncoderOnly
            if (modelType !== MODEL_TYPES.EncoderOnly) {
                console.warn(`Model type for '${modelName ?? config?.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`)
            }
            info = await Promise.all([
                _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
                constructSession(pretrained_model_name_or_path, options.model_file_name ?? 'model', options)
            ]);
        }

        // @ts-ignore
        return new this(...info);
    }

    /**
     * Runs the model with the provided inputs
     * @param {Object} model_inputs Object containing input tensors
     * @returns {Promise<Object>} Object containing output tensors
     */
    async _call(model_inputs) {
        return await this.forward(model_inputs);
    }

    /**
     * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method
     * will be chosen based on the model type.
     * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.
     * @returns {Promise<Object>} The output data from the model in the format specified in the ONNX model.
     * @throws {Error} This method must be implemented in subclasses.
     */
    async forward(model_inputs) {
        return await this._forward(this, model_inputs);
    }

    /**
     * @param {import('./utils/generation.js').GenerationConfigType} generation_config 
     * @param {number} input_ids_seq_length The starting sequence length for the input ids.
     * @returns {LogitsProcessorList}
     * @private
     */
    _get_logits_processor(
        generation_config,
        input_ids_seq_length,
        // encoder_input_ids, TODO
        // prefix_allowed_tokens_fn, TODO
        logits_processor = null
    ) {
        const processors = new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.LogitsProcessorList();

        // if (generation_config.diversity_penalty !== null && generation_config.diversity_penalty > 0.0) {
        //     processors.push(new HammingDiversityLogitsProcessor(
        //         generation_config.diversity_penalty,
        //         generation_config.num_beams,
        //         generation_config.num_beam_groups
        //     ));
        // }

        // if (generation_config.encoder_repetition_penalty !== null && generation_config.encoder_repetition_penalty !== 1.0) {
        //     processors.push(new EncoderRepetitionPenaltyLogitsProcessor(
        //         generation_config.encoder_repetition_penalty,
        //         encoder_input_ids
        //     ));
        // }

        if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1.0) {
            processors.push(new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty));
        }

        if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) {
            processors.push(new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size));
        }

        // if (generation_config.encoder_no_repeat_ngram_size !== null && generation_config.encoder_no_repeat_ngram_size > 0) {
        //     if (this.config.is_encoder_decoder) {
        //         processors.push(new EncoderNoRepeatNGramLogitsProcessor(
        //             generation_config.encoder_no_repeat_ngram_size,
        //             encoder_input_ids
        //         ));
        //     } else {
        //         throw new Error("It's impossible to use `encoder_no_repeat_ngram_size` with decoder-only architecture");
        //     }
        // }

        if (generation_config.bad_words_ids !== null) {
            processors.push(new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id));
        }

        if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) {
            processors.push(new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id));
        }

        if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) {
            processors.push(new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.MinNewTokensLengthLogitsProcessor(
                input_ids_seq_length,
                generation_config.min_new_tokens,
                generation_config.eos_token_id
            ));
        }

        // if (prefix_allowed_tokens_fn !== null) {
        //     processors.push(new PrefixConstrainedLogitsProcessor(
        //         prefix_allowed_tokens_fn,
        //         generation_config.num_beams / generation_config.num_beam_groups
        //     ));
        // }


        if (generation_config.forced_bos_token_id !== null) {
            processors.push(new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id));
        }

        if (generation_config.forced_eos_token_id !== null) {
            processors.push(new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.ForcedEOSTokenLogitsProcessor(
                generation_config.max_length,
                generation_config.forced_eos_token_id
            ));
        }

        // if (generation_config.remove_invalid_values === true) {
        //     processors.push(new InfNanRemoveLogitsProcessor());
        // }

        // if (generation_config.exponential_decay_length_penalty !== null) {
        //     processors.push(new ExponentialDecayLengthPenalty(
        //         generation_config.exponential_decay_length_penalty,
        //         generation_config.eos_token_id,
        //         input_ids_seq_length
        //     ));
        // }

        // if (generation_config.suppress_tokens !== null) {
        //     processors.push(new SuppressTokensLogitsProcessor(generation_config.suppress_tokens));
        // }

        if (generation_config.begin_suppress_tokens !== null) {
            let begin_index = (input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null)
                ? input_ids_seq_length
                : input_ids_seq_length + 1;

            if (generation_config.forced_decoder_ids !== null) {
                // generation starts after the last token that is forced
                begin_index += generation_config.forced_decoder_ids[generation_config.forced_decoder_ids.length - 1][0];
            }
            processors.push(new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index));
        }

        if (generation_config.forced_decoder_ids !== null) {
            processors.push(new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.ForceTokensLogitsProcessor(generation_config.forced_decoder_ids));
        }

        if (logits_processor !== null) {
            processors.extend(logits_processor)
        }

        // `LogitNormalization` should always be the last logit processor, when present
        // if (generation_config.renormalize_logits === true) {
        //     processors.push(new LogitNormalization());
        // }

        return processors;
    }

    /**
     * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.
     * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.
     * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters.
     * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation.
     */
    _get_generation_config(generation_config) {
        // Create empty generation config (contains defaults)
        // We pass `this.config` so that if `eos_token_id` or `bos_token_id` exist in the model's config, we will use them
        let gen_config = new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.GenerationConfig(this.config);

        // Apply model's generation config, if it exists
        if ('generation_config' in this) {
            Object.assign(gen_config, this.generation_config);
        }

        // Finally, use any generation config specified by the user
        // when calling `generate`
        if (generation_config !== null) {
            Object.assign(gen_config, generation_config);
        }
        return gen_config;
    }

    /**
     * @typedef {import('./utils/maths.js').TypedArray} TypedArray
     */

    /**
     * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput
     * @typedef {Object} DecoderOutput
     * 
     * Generates text based on the given inputs and generation configuration using the model.
     * @param {Tensor|Array|TypedArray} inputs An array of input token IDs.
     * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used.
     * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created.
     * @param {Object} options options
     * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs.
     * @returns {Promise<number[][]|EncoderDecoderOutput|DecoderOutput>} An array of generated output sequences, where each sequence is an array of token IDs.
     * @throws {Error} Throws an error if the inputs array is empty.
     */
    async generate(
        inputs,
        generation_config = null,
        logits_processor = null,
        {
            inputs_attention_mask = null
        } = {},
    ) {
        if (!this.can_generate) {
            const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);
            let errorMessage = `The current model class (${modelName}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`

            const modelType = this.config.model_type;
            const possibleInfo =
                MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(modelType)
                ?? MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(modelType)
                ?? MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(modelType)
                // ?? MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES.get(modelType) // TODO
                ?? MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(modelType);

            if (possibleInfo) {
                // TODO: support multiple possible classes
                errorMessage += ` Please use the following class instead: '${possibleInfo[0]}'`;
            }
            throw Error(errorMessage);
        }

        if (!(inputs instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor) && !(0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.isTypedArray)(inputs) && !Array.isArray(inputs)) {
            throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${inputs.constructor.name}".`);
        }

        let input_ids_seq_length;

        // Prepare `input_ids` which will be used for auto-regressive generation
        // TODO: Update to align with HF transformers' implementation
        if (this.config.is_encoder_decoder) {
            // Generating from the encoder outputs
            input_ids_seq_length = 0;

        } else {
            input_ids_seq_length = inputs instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor ? inputs.dims.at(-1) : inputs.length;

            // decoder-only
            if (input_ids_seq_length === 0) {
                throw Error("Must supply a non-empty array of input token ids.")
            }
        }

        // Update generation config with defaults
        generation_config = this._get_generation_config(generation_config);

        logits_processor = logits_processor ?? new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.LogitsProcessorList()

        // Update logits processor
        logits_processor = this._get_logits_processor(
            generation_config,
            input_ids_seq_length,
            logits_processor
        )

        /** @type {number[]} */
        let eos_token_ids = generation_config.eos_token_id;
        if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) {
            eos_token_ids = [eos_token_ids];
        }

        // TODO implement early_stopping
        // https://huggingface.co/blog/how-to-generate

        let numOutputTokens = 1;
        const maxOutputTokens = numOutputTokens + (generation_config.max_new_tokens ?? Infinity);

        // Only use max length if max_new_tokens is not provided
        const useMaxLength = Number.isInteger(generation_config.max_length) && (generation_config.max_new_tokens ?? null) === null;
        let sampler = _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.Sampler.getSampler(generation_config);

        // @ts-ignore
        let beams = this.getStartBeams(inputs, generation_config, numOutputTokens, inputs_attention_mask);

        while (beams.some(x => !x.done) && numOutputTokens < maxOutputTokens) {
            let newest_beams = [];
            for (let beam of beams) {
                if (beam.done) {
                    // Add this beam back into the pool
                    newest_beams.push(beam);
                    continue
                }
                if (useMaxLength && beam.output_token_ids.length >= generation_config.max_length) {
                    // Set this beam to done and add it back into the pool
                    beam.done = true;
                    newest_beams.push(beam);
                    continue
                }

                // @ts-ignore
                let output = await this.runBeam(beam);

                // add attentions/scores to beam only if user requested
                if (generation_config.output_attentions) {
                    this.addAttentionsToBeam(beam, output);
                }
                if (generation_config.output_scores) {
                    // TODO add
                }

                // Logits are of the form [batch_size, out_seq_length, vocab_size]
                // In most cases, this will be [batch_size, 1, vocab_size]
                // So, we select the last token's logits:
                // (equivalent to `logits = outputs.logits[:, -1, :]`)
                let logits = output.logits.slice(null, -1, null);

                // Apply logits processor
                logits_processor(beam.output_token_ids, logits);

                let sampledTokens = sampler(logits);
                for (let [newTokenId, logProb] of sampledTokens) {
                    // use previous beam as a starting point
                    let newBeam = { ...beam };

                    // update new beam
                    // @ts-ignore
                    this.updateBeam(newBeam, newTokenId);

                    newBeam.score += logProb;

                    if (eos_token_ids && eos_token_ids.includes(newTokenId)) {
                        newBeam.done = true;
                    }

                    newest_beams.push(newBeam);
                }
            }
            ++numOutputTokens;

            // Next, we get the best beams, per ID
            newest_beams = this.groupBeams(newest_beams).map(
                group => group
                    .sort((a, b) => b.score - a.score)      // sort by score
                    .slice(0, generation_config.num_beams)  // remove outside beam width
            );

            // Flatten beams
            beams = newest_beams.flat();

            // Run callback
            if (generation_config.callback_function) {
                generation_config.callback_function(beams);
            }
        }

        // TODO: Ensure that we can return non-batched outputs

        const groupedBeams = this.groupBeams(beams);

        const getFlattened = (key) => groupedBeams.map(
            batch => {
                if (generation_config.num_return_sequences > 1) {
                    return batch.slice(0, generation_config.num_return_sequences).map(x => x[key]);
                } else {
                    return [batch[0][key]];
                }
            }
        ).flat(); // Flatten across batches (depth=1)

        const sequences = getFlattened('output_token_ids'); // [1, seqLength]

        if (generation_config.return_dict_in_generate) {
            // NOTE: `decoder_attentions` and `cross_attentions` should be:
            //    list (one element for each generated token)
            //    of list (one element for each layer of the decoder)
            //    of torch.FloatTensor of shape (batch_size, num_heads, generated_length, sequence_length)
            // However, since we are only generating one batch at a time, they are of the form:
            //   list (batches)
            //   of list (one element for each generated token)
            //   of list (one element for each layer of the decoder)
            //   of torch.FloatTensor of shape (1, num_heads, generated_length, sequence_length)
            // 
            // TODO: In future (when true parallelism, we should be able to return the correct shape)

            const decoder_attentions = getFlattened('decoder_attentions');
            const cross_attentions = getFlattened('cross_attentions');

            return {
                sequences,

                decoder_attentions,
                cross_attentions,
            }
        } else {
            return sequences;
        }
    }

    /**
     * Helper function to add attentions to beam
     * @param {Object} beam 
     * @param {Object} output
     * @private 
     */
    addAttentionsToBeam(beam, output) {
        if (this.config.is_encoder_decoder) {
            if (!output.cross_attentions || output.cross_attentions.length === 0) {
                throw Error(
                    "`output_attentions` is true, but the model did not produce cross-attentions. " +
                    "This is most likely because the model was not exported with `output_attentions=True`."
                )
            }
            if (!beam.cross_attentions) {
                beam.cross_attentions = [];
            }
            beam.cross_attentions.push(output.cross_attentions);
        }

        if (!output.decoder_attentions || output.decoder_attentions.length === 0) {
            throw Error(
                "`output_attentions` is true, but the model did not produce decoder-attentions. " +
                "This is most likely because the model was not exported with `output_attentions=True`."
            )
        }
        if (!beam.decoder_attentions) {
            beam.decoder_attentions = [];
        }
        beam.decoder_attentions.push(output.decoder_attentions);
    }

    /**
     * Groups an array of beam objects by their ids.
     *
     * @param {Array} beams The array of beam objects to group.
     * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id.
     */
    groupBeams(beams) {
        // Group beams by their ids
        const groups = Object.create(null);
        for (const obj of beams) {
            if (groups[obj.id] === undefined) {
                groups[obj.id] = [obj];
            } else {
                groups[obj.id].push(obj);
            }
        }

        return Object.values(groups);
    }

    /**
     * Returns an object containing past key values from the given decoder results object.
     *
     * @param {Object} decoderResults The decoder results object.
     * @param {Object} pastKeyValues The previous past key values.
     * @returns {Object} An object containing past key values.
     */
    getPastKeyValues(decoderResults, pastKeyValues) {

        const pkvs = Object.create(null);

        for (const name in decoderResults) {
            if (name.startsWith('present')) {
                let newName = name.replace('present', 'past_key_values');

                if (pastKeyValues && name.includes('encoder')) {
                    // Optimization introduced by optimum to reuse past key values. So, we just replace the constant
                    // outputs with the previous past key values.
                    // https://github.com/huggingface/optimum/blob/0bf2c05fb7e1182b52d21b703cfc95fd9e4ea3dc/optimum/onnxruntime/base.py#L677-L704
                    pkvs[newName] = pastKeyValues[newName];
                } else {
                    pkvs[newName] = decoderResults[name];
                }
            }
        }
        return pkvs;
    }

    /**
     * Returns an object containing attentions from the given decoder results object.
     *
     * @param {Object} decoderResults The decoder results object.
     * @returns {Object} An object containing attentions.
     */
    getAttentions(decoderResults) {
        const attns = Object.create(null);

        for (const attnName of ['cross_attentions', 'decoder_attentions']) {
            const result = [];
            for (const name in decoderResults) {
                if (name.startsWith(attnName)) {
                    const index = name.split('.').pop()
                    result[index] = decoderResults[name];
                }
            }
            attns[attnName] = result;
        }
        return attns;
    }

    /**
     * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.
     *
     * @param {Object} decoderFeeds The decoder feeds object to add past key values to.
     * @param {Object} pastKeyValues An object containing past key values.
     */
    addPastKeyValues(decoderFeeds, pastKeyValues) {
        if (pastKeyValues) {
            Object.assign(decoderFeeds, pastKeyValues)
        } else {
            // TODO support batches (i.e., batch_size > 1)
            const batch_size = 1;

            // @ts-ignore
            if (this.config.is_encoder_decoder && (this.add_encoder_pkv ?? true)) {
                // @ts-ignore
                let encoder_dims = [batch_size, this.num_encoder_heads, 0, this.encoder_dim_kv];
                // @ts-ignore
                let decoder_dims = [batch_size, this.num_decoder_heads, 0, this.decoder_dim_kv];
                // @ts-ignore
                for (let i = 0; i < this.num_decoder_layers; ++i) {
                    decoderFeeds[`past_key_values.${i}.encoder.key`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], encoder_dims)
                    decoderFeeds[`past_key_values.${i}.encoder.value`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], encoder_dims)
                    decoderFeeds[`past_key_values.${i}.decoder.key`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], decoder_dims)
                    decoderFeeds[`past_key_values.${i}.decoder.value`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], decoder_dims)
                }
            } else if (this.config.model_type === 'falcon') {
                // NOTE: Custom implementation for Falcon
                // @ts-ignore
                let dims = [batch_size * this.num_heads, 0, this.dim_kv]
                // @ts-ignore
                for (let i = 0; i < this.num_layers; ++i) {
                    decoderFeeds[`past_key_values.${i}.key`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], dims)
                    decoderFeeds[`past_key_values.${i}.value`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], dims)
                }
            } else if (this.config.multi_query) { // e.g., for `gpt_bigcode`
                // @ts-ignore
                let dims = [batch_size * this.num_heads, 0, 2 * this.dim_kv]
                // @ts-ignore
                for (let i = 0; i < this.num_layers; ++i) {
                    decoderFeeds[`past_key_values.${i}.key_value`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], dims)
                }
            } else if (this.config.model_type === 'bloom') {
                // NOTE: Custom implementation for Bloom

                // @ts-ignore
                let keyDims = [batch_size * this.num_heads, this.dim_kv, 0] // [batch_size x num_heads,64,past_sequence_length]
                // @ts-ignore
                let valueDims = [batch_size * this.num_heads, 0, this.dim_kv] // [batch_size x num_heads,past_sequence_length,64]
                // @ts-ignore
                for (let i = 0; i < this.num_layers; ++i) {
                    decoderFeeds[`past_key_values.${i}.key`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], keyDims)
                    decoderFeeds[`past_key_values.${i}.value`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], valueDims)
                }
            } else { // Decoder-only
                // @ts-ignore
                let dims = [batch_size, this.num_heads, 0, this.dim_kv]
                // @ts-ignore
                for (let i = 0; i < this.num_layers; ++i) {
                    decoderFeeds[`past_key_values.${i}.key`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], dims)
                    decoderFeeds[`past_key_values.${i}.value`] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', [], dims)
                }
            }
        }
    }

    /**
     * Initializes and returns the beam for text generation task
     * @param {Tensor} inputTokenIds The input token ids.
     * @param {Object} generation_config The generation config.
     * @param {number} numOutputTokens The number of tokens to be generated.
     * @param {Tensor} inputs_attention_mask Optional input attention mask.
     * @returns {any} A Beam object representing the initialized beam.
     * @private
     */
    getStartBeams(inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) {
        return this._getStartBeams(this, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask)
    }

    /**
     * Runs a single step of the beam search generation algorithm.
     * @param {any} beam The current beam being generated.
     * @returns {Promise<any>} The updated beam after a single generation step.
     * @private
     */
    async runBeam(beam) {
        return await this._runBeam(this, beam);
    }

    /**
     * Update a beam with a new token ID.
     * @param {Object} beam The beam to update.
     * @param {number} newTokenId The new token ID to add to the beam's output.
     * @private
     */
    updateBeam(beam, newTokenId) {
        return this._updateBeam(beam, newTokenId);
    }
}

//////////////////////////////////////////////////
// Base model output class
class ModelOutput { }

/**
 * Base class for model's outputs, with potential hidden states and attentions.
 */
class BaseModelOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model.
     * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
     * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
     */
    constructor({ last_hidden_state, hidden_states = null, attentions = null }) {
        super();
        this.last_hidden_state = last_hidden_state;
        this.hidden_states = hidden_states;
        this.attentions = attentions;
    }
}
//////////////////////////////////////////////////
// Bert models
class BertPreTrainedModel extends PreTrainedModel { }
class BertModel extends BertPreTrainedModel { }

/**
 * BertForMaskedLM is a class representing a BERT model for masked language modeling.
 */
class BertForMaskedLM extends BertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * BertForSequenceClassification is a class representing a BERT model for sequence classification.
 */
class BertForSequenceClassification extends BertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * BertForTokenClassification is a class representing a BERT model for token classification.
 */
class BertForTokenClassification extends BertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * BertForQuestionAnswering is a class representing a BERT model for question answering.
 */
class BertForQuestionAnswering extends BertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// NomicBert models
class NomicBertPreTrainedModel extends PreTrainedModel { }
class NomicBertModel extends NomicBertPreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// RoFormer models
class RoFormerPreTrainedModel extends PreTrainedModel { }

/**
 * The bare RoFormer Model transformer outputting raw hidden-states without any specific head on top.
 */
class RoFormerModel extends RoFormerPreTrainedModel { }

/**
 * RoFormer Model with a `language modeling` head on top.
 */
class RoFormerForMaskedLM extends RoFormerPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * RoFormer Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
 */
class RoFormerForSequenceClassification extends RoFormerPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * RoFormer Model with a token classification head on top (a linear layer on top of the hidden-states output)
 * e.g. for Named-Entity-Recognition (NER) tasks.
 */
class RoFormerForTokenClassification extends RoFormerPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * RoFormer Model with a span classification head on top for extractive question-answering tasks like SQuAD
 * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
 */
class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
// TODO: Add RoFormerForCausalLM and RoFormerForMultipleChoice
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// ConvBert models
class ConvBertPreTrainedModel extends PreTrainedModel { }

/**
 * The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.
 */
class ConvBertModel extends ConvBertPreTrainedModel { }

/**
 * ConvBERT Model with a language modeling head on top.
 */
class ConvBertForMaskedLM extends ConvBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
 */
class ConvBertForSequenceClassification extends ConvBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output)
 * e.g. for Named-Entity-Recognition (NER) tasks.
 */
class ConvBertForTokenClassification extends ConvBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD
 * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`)
 */
class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Electra models
class ElectraPreTrainedModel extends PreTrainedModel { }

/**
 * The bare Electra Model transformer outputting raw hidden-states without any specific head on top.
 * Identical to the BERT model except that it uses an additional linear layer between the embedding
 * layer and the encoder if the hidden size and embedding size are different.
 */
class ElectraModel extends ElectraPreTrainedModel { }
// TODO add ElectraForPreTraining
/**
 * Electra model with a language modeling head on top.
 */
class ElectraForMaskedLM extends ElectraPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
 */
class ElectraForSequenceClassification extends ElectraPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * Electra model with a token classification head on top.
 */
class ElectraForTokenClassification extends ElectraPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * LECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD
 * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
 */
class ElectraForQuestionAnswering extends ElectraPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// CamemBERT models
class CamembertPreTrainedModel extends PreTrainedModel { }

/**
 * The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.
 */
class CamembertModel extends CamembertPreTrainedModel { }

/**
 * CamemBERT Model with a `language modeling` head on top.
 */
class CamembertForMaskedLM extends CamembertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
 */
class CamembertForSequenceClassification extends CamembertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
 */
class CamembertForTokenClassification extends CamembertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * CamemBERT Model with a span classification head on top for extractive question-answering tasks
 */
class CamembertForQuestionAnswering extends CamembertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// DeBERTa models
class DebertaPreTrainedModel extends PreTrainedModel { }

/**
 * The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.
 */
class DebertaModel extends DebertaPreTrainedModel { }

/**
 * DeBERTa Model with a `language modeling` head on top.
 */
class DebertaForMaskedLM extends DebertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
 */
class DebertaForSequenceClassification extends DebertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
 */
class DebertaForTokenClassification extends DebertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
 * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
 */
class DebertaForQuestionAnswering extends DebertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// DeBERTa-v2 models
class DebertaV2PreTrainedModel extends PreTrainedModel { }

/**
 * The bare DeBERTa-V2 Model transformer outputting raw hidden-states without any specific head on top.
 */
class DebertaV2Model extends DebertaV2PreTrainedModel { }

/**
 * DeBERTa-V2 Model with a `language modeling` head on top.
 */
class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * DeBERTa-V2 Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
 */
class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * DeBERTa-V2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
 */
class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * DeBERTa-V2 Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
 * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
 */
class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// DistilBert models
class DistilBertPreTrainedModel extends PreTrainedModel { }
class DistilBertModel extends DistilBertPreTrainedModel { }

/**
 * DistilBertForSequenceClassification is a class representing a DistilBERT model for sequence classification.
 */
class DistilBertForSequenceClassification extends DistilBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * DistilBertForTokenClassification is a class representing a DistilBERT model for token classification.
 */
class DistilBertForTokenClassification extends DistilBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}


/**
 * DistilBertForQuestionAnswering is a class representing a DistilBERT model for question answering.
 */
class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}

/**
 * DistilBertForMaskedLM is a class representing a DistilBERT model for masking task.
 */
class DistilBertForMaskedLM extends DistilBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// ESM models
class EsmPreTrainedModel extends PreTrainedModel { }

/**
 * The bare ESM Model transformer outputting raw hidden-states without any specific head on top.
 */
class EsmModel extends EsmPreTrainedModel { }

/**
 * ESM Model with a `language modeling` head on top.
 */
class EsmForMaskedLM extends EsmPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
 */
class EsmForSequenceClassification extends EsmPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * ESM Model with a token classification head on top (a linear layer on top of the hidden-states output)
 * e.g. for Named-Entity-Recognition (NER) tasks.
 */
class EsmForTokenClassification extends EsmPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// MobileBert models
class MobileBertPreTrainedModel extends PreTrainedModel { }
class MobileBertModel extends MobileBertPreTrainedModel { }

/**
 * MobileBertForMaskedLM is a class representing a MobileBERT model for masking task.
 */
class MobileBertForMaskedLM extends MobileBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
 */
class MobileBertForSequenceClassification extends MobileBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * MobileBert Model with a span classification head on top for extractive question-answering tasks
 */
class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// MPNet models
class MPNetPreTrainedModel extends PreTrainedModel { }

/**
 * The bare MPNet Model transformer outputting raw hidden-states without any specific head on top.
 */
class MPNetModel extends MPNetPreTrainedModel { }

/**
 * MPNetForMaskedLM is a class representing a MPNet model for masked language modeling.
 */
class MPNetForMaskedLM extends MPNetPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * MPNetForSequenceClassification is a class representing a MPNet model for sequence classification.
 */
class MPNetForSequenceClassification extends MPNetPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * MPNetForTokenClassification is a class representing a MPNet model for token classification.
 */
class MPNetForTokenClassification extends MPNetPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * MPNetForQuestionAnswering is a class representing a MPNet model for question answering.
 */
class MPNetForQuestionAnswering extends MPNetPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// SqueezeBert models
class SqueezeBertPreTrainedModel extends PreTrainedModel { }
class SqueezeBertModel extends SqueezeBertPreTrainedModel { }
class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}
class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Albert models
class AlbertPreTrainedModel extends PreTrainedModel { }
class AlbertModel extends AlbertPreTrainedModel { }
class AlbertForSequenceClassification extends AlbertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
class AlbertForQuestionAnswering extends AlbertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
class AlbertForMaskedLM extends AlbertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// T5 models
class T5PreTrainedModel extends PreTrainedModel { };

class T5Model extends T5PreTrainedModel { }

/**
 * T5Model is a class representing a T5 model for conditional generation.
 */
class T5ForConditionalGeneration extends T5PreTrainedModel {

    /**
     * Creates a new instance of the `T5ForConditionalGeneration` class.
     * @param {Object} config The model configuration.
     * @param {any} session session for the model.
     * @param {any} decoder_merged_session session for the decoder.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.num_decoder_layers;
        this.num_decoder_heads = this.config.num_heads;
        this.decoder_dim_kv = this.config.d_kv;

        this.num_encoder_layers = this.config.num_layers;
        this.num_encoder_heads = this.config.num_heads;
        this.encoder_dim_kv = this.config.d_kv;
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// LONGT5 models
/**
 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
 */
class LongT5PreTrainedModel extends PreTrainedModel { };

/**
 * The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top.
 */
class LongT5Model extends LongT5PreTrainedModel { }

/**
 * LONGT5 Model with a `language modeling` head on top.
 */
class LongT5ForConditionalGeneration extends LongT5PreTrainedModel {
    /**
     * Creates a new instance of the `LongT5ForConditionalGeneration` class.
     * @param {Object} config The model configuration.
     * @param {any} session session for the model.
     * @param {any} decoder_merged_session session for the decoder.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.num_decoder_layers;
        this.num_decoder_heads = this.config.num_heads;
        this.decoder_dim_kv = this.config.d_kv;

        this.num_encoder_layers = this.config.num_layers;
        this.num_encoder_heads = this.config.num_heads;
        this.encoder_dim_kv = this.config.d_kv;
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// MT5 models
class MT5PreTrainedModel extends PreTrainedModel { };

class MT5Model extends MT5PreTrainedModel { }

/**
 * A class representing a conditional sequence-to-sequence model based on the MT5 architecture.
 */
class MT5ForConditionalGeneration extends MT5PreTrainedModel {

    /**
     * Creates a new instance of the `MT5ForConditionalGeneration` class.
     * @param {any} config The model configuration.
     * @param {any} session The ONNX session containing the encoder weights.
     * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.num_decoder_layers;
        this.num_decoder_heads = this.config.num_heads;
        this.decoder_dim_kv = this.config.d_kv;

        this.num_encoder_layers = this.config.num_layers;
        this.num_encoder_heads = this.config.num_heads;
        this.encoder_dim_kv = this.config.d_kv;
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Bart models
class BartPretrainedModel extends PreTrainedModel { };

/**
 * The bare BART Model outputting raw hidden-states without any specific head on top.
 */
class BartModel extends BartPretrainedModel { }

/**
 * The BART Model with a language modeling head. Can be used for summarization.
 */
class BartForConditionalGeneration extends BartPretrainedModel {

    /**
     * Creates a new instance of the `BartForConditionalGeneration` class.
     * @param {Object} config The configuration object for the Bart model.
     * @param {Object} session The ONNX session used to execute the model.
     * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
     * @param {Object} generation_config The generation configuration object.
     */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.decoder_layers;
        this.num_decoder_heads = this.config.decoder_attention_heads;
        this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;

        this.num_encoder_layers = this.config.encoder_layers;
        this.num_encoder_heads = this.config.encoder_attention_heads;
        this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }

}

/**
 * Bart model with a sequence classification/head on top (a linear layer on top of the pooled output)
 */
class BartForSequenceClassification extends BartPretrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

//////////////////////////////////////////////////

//////////////////////////////////////////////////
// MBart models
class MBartPreTrainedModel extends PreTrainedModel { };

/**
 * The bare MBART Model outputting raw hidden-states without any specific head on top.
 */
class MBartModel extends MBartPreTrainedModel { }

/**
 * The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models.
 */
class MBartForConditionalGeneration extends MBartPreTrainedModel {

    /**
     * Creates a new instance of the `MBartForConditionalGeneration` class.
     * @param {Object} config The configuration object for the Bart model.
     * @param {Object} session The ONNX session used to execute the model.
     * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
     * @param {Object} generation_config The generation configuration object.
     */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.decoder_layers;
        this.num_decoder_heads = this.config.decoder_attention_heads;
        this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;

        this.num_encoder_layers = this.config.encoder_layers;
        this.num_encoder_heads = this.config.encoder_attention_heads;
        this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }

}

/**
 * MBart model with a sequence classification/head on top (a linear layer on top of the pooled output).
 */
class MBartForSequenceClassification extends MBartPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}


class MBartForCausalLM extends MBartPreTrainedModel {
    /**
     * Creates a new instance of the `MBartForCausalLM` class.
     * @param {Object} config Configuration object for the model.
     * @param {Object} decoder_merged_session ONNX Session object for the decoder.
     * @param {Object} generation_config Configuration object for the generation process.
     */
    constructor(config, decoder_merged_session, generation_config) {
        super(config, decoder_merged_session);
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.decoder_layers;
        this.num_decoder_heads = this.config.decoder_attention_heads;
        this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;

        this.num_encoder_layers = this.config.encoder_layers;
        this.num_encoder_heads = this.config.encoder_attention_heads;
        this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Blenderbot models
class BlenderbotPreTrainedModel extends PreTrainedModel { };

/**
 * The bare Blenderbot Model outputting raw hidden-states without any specific head on top.
 */
class BlenderbotModel extends BlenderbotPreTrainedModel { }

/**
 * The Blenderbot Model with a language modeling head. Can be used for summarization.
 */
class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel {

    /**
     * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
     * @param {any} config The model configuration.
     * @param {any} session The ONNX session containing the encoder weights.
     * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.decoder_layers;
        this.num_decoder_heads = this.config.decoder_attention_heads;
        this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;

        this.num_encoder_layers = this.config.encoder_layers;
        this.num_encoder_heads = this.config.encoder_attention_heads;
        this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Blenderbot models
class BlenderbotSmallPreTrainedModel extends PreTrainedModel { };

/**
 * The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top.
 */
class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel { }

/**
 * The BlenderbotSmall Model with a language modeling head. Can be used for summarization.
 */
class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel {

    /**
     * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
     * @param {any} config The model configuration.
     * @param {any} session The ONNX session containing the encoder weights.
     * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.decoder_layers;
        this.num_decoder_heads = this.config.decoder_attention_heads;
        this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;

        this.num_encoder_layers = this.config.encoder_layers;
        this.num_encoder_heads = this.config.encoder_attention_heads;
        this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Roberta models
class RobertaPreTrainedModel extends PreTrainedModel { }
class RobertaModel extends RobertaPreTrainedModel { }

/**
 * RobertaForMaskedLM class for performing masked language modeling on Roberta models.
 */
class RobertaForMaskedLM extends RobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * RobertaForSequenceClassification class for performing sequence classification on Roberta models.
 */
class RobertaForSequenceClassification extends RobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * RobertaForTokenClassification class for performing token classification on Roberta models.
 */
class RobertaForTokenClassification extends RobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * RobertaForQuestionAnswering class for performing question answering on Roberta models.
 */
class RobertaForQuestionAnswering extends RobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// XLM models
/**
 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
 */
class XLMPreTrainedModel extends PreTrainedModel { }

/**
 * The bare XLM Model transformer outputting raw hidden-states without any specific head on top.
 */
class XLMModel extends XLMPreTrainedModel { }

/**
 * The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
 */
class XLMWithLMHeadModel extends XLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)
 */
class XLMForSequenceClassification extends XLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * XLM Model with a token classification head on top (a linear layer on top of the hidden-states output)
 */
class XLMForTokenClassification extends XLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * XLM Model with a span classification head on top for extractive question-answering tasks
 */
class XLMForQuestionAnswering extends XLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// XLMRoberta models
class XLMRobertaPreTrainedModel extends PreTrainedModel { }
class XLMRobertaModel extends XLMRobertaPreTrainedModel { }

/**
 * XLMRobertaForMaskedLM class for performing masked language modeling on XLMRoberta models.
 */
class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    async _call(model_inputs) {
        return new MaskedLMOutput(await super._call(model_inputs));
    }
}

/**
 * XLMRobertaForSequenceClassification class for performing sequence classification on XLMRoberta models.
 */
class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * XLMRobertaForTokenClassification class for performing token classification on XLMRoberta models.
 */
class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * XLMRobertaForQuestionAnswering class for performing question answering on XLMRoberta models.
 */
class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    async _call(model_inputs) {
        return new QuestionAnsweringModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Audio Spectrogram Transformer (AST) models
class ASTPreTrainedModel extends PreTrainedModel { };

/**
 * The bare AST Model transformer outputting raw hidden-states without any specific head on top.
 */
class ASTModel extends ASTPreTrainedModel { }

/**
 * Audio Spectrogram Transformer model with an audio classification head on top
 * (a linear layer on top of the pooled output) e.g. for datasets like AudioSet, Speech Commands v2.
 */
class ASTForAudioClassification extends ASTPreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Whisper models
class WhisperPreTrainedModel extends PreTrainedModel { };

/**
 * WhisperModel class for training Whisper models without a language model head.
 */
class WhisperModel extends WhisperPreTrainedModel { }

/**
 * WhisperForConditionalGeneration class for generating conditional outputs from Whisper models.
 */
class WhisperForConditionalGeneration extends WhisperPreTrainedModel {

    requires_attention_mask = false;
    main_input_name = 'input_features';

    /**
     * Creates a new instance of the `WhisperForConditionalGeneration` class.
     * @param {Object} config Configuration object for the model.
     * @param {Object} session ONNX Session object for the model.
     * @param {Object} decoder_merged_session ONNX Session object for the decoder.
     * @param {Object} generation_config Configuration object for the generation process.
     */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.decoder_layers;
        this.num_decoder_heads = this.config.decoder_attention_heads;
        this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;

        this.num_encoder_layers = this.config.encoder_layers;
        this.num_encoder_heads = this.config.encoder_attention_heads;
        this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }

    /**
     * @typedef {Object} WhisperGenerationConfig
     * @extends GenerationConfig
     * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.
     * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps
     * with the text. This can be used with or without the `return_timestamps` option. To get word-level
     * timestamps, use the tokenizer to group the tokens into words.
     * @property {number} [num_frames=null]  The number of audio frames available in this chunk. This is only used generating word-level timestamps.
     */

    /**
     * Generates outputs based on input and generation configuration.
     * @param {Object} inputs Input data for the model.
     * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process.
     * @param {Object} logits_processor Optional logits processor object.
     * @returns {Promise<Object>} Promise object represents the generated outputs.
     */
    async generate(
        inputs,
        generation_config = null,
        logits_processor = null,
        // {
        //     return_timestamps = null,
        //     return_token_timestamps = null,
        //     language = null,
        //     task = null,
        // } = {},
    ) {
        // Create generation config object
        generation_config = this._get_generation_config(generation_config);


        // Whisper has additional options for returning timestamps
        generation_config.return_timestamps ??= false;

        // TODO add language and task

        if (generation_config.return_timestamps) {
            logits_processor = [new _utils_generation_js__WEBPACK_IMPORTED_MODULE_3__.WhisperTimeStampLogitsProcessor(generation_config)]
        }

        if (generation_config.return_token_timestamps) {
            generation_config.output_attentions = true;
            generation_config.return_dict_in_generate = true;

            if (generation_config.task === 'translate') {
                console.warn("Token-level timestamps may not be reliable for task 'translate'.")
            }

            if (!generation_config.alignment_heads) {
                throw new Error(
                    "Model generation config has no `alignment_heads`, token-level timestamps not available. " +
                    "See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config."
                )
            }
        }

        const outputs = await super.generate(inputs, generation_config, logits_processor);

        if (generation_config.return_token_timestamps && generation_config.alignment_heads) {
            outputs["token_timestamps"] = this._extract_token_timestamps(
                outputs,
                generation_config.alignment_heads,
                generation_config.num_frames,
            )
        }

        return outputs
    }

    /**
     * Calculates token-level timestamps using the encoder-decoder cross-attentions and
     * dynamic time-warping (DTW) to map each output token to a position in the input audio.
     * @param {Object} generate_outputs Outputs generated by the model
     * @param {Tensor[][][]} generate_outputs.cross_attentions The cross attentions output by the model
     * @param {Tensor[][][]} generate_outputs.decoder_attentions The decoder attentions output by the model
     * @param {number[][]} generate_outputs.sequences The sequences output by the model
     * @param {number[][]} alignment_heads Alignment heads of the model
     * @param {number} [num_frames=null] Number of frames in the input audio.
     * @param {number} [time_precision=0.02] Precision of the timestamps in seconds
     * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token
     */
    _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) {
        if (!generate_outputs.cross_attentions) {
            throw new Error(
                "Model outputs must contain cross attentions to extract timestamps. " +
                "This is most likely because the model was not exported with `output_attentions=True`."
            )
        }

        let median_filter_width = this.config.median_filter_width;
        if (median_filter_width === undefined) {
            console.warn("Model config has no `median_filter_width`, using default value of 7.")
            median_filter_width = 7;
        }

        const batchedMatrices = generate_outputs.cross_attentions.map(batch => {
            // Create a list with `decoder_layers` elements, each a tensor of shape
            // (batch size, attention_heads, output length, input length).
            let cross_attentions = Array.from({ length: this.config.decoder_layers },
                (_, i) => (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.cat)(batch.map(x => x[i]), 2)
            );

            let weights = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.stack)(alignment_heads.map(([l, h]) => {
                return num_frames
                    ? cross_attentions[l].slice(null, h, null, [0, num_frames])
                    : cross_attentions[l].slice(null, h);
            }));
            weights = weights.transpose(1, 0, 2, 3)

            let [std, calculatedMean] = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.std_mean)(weights, -2, 0, true);

            // Normalize and smoothen the weights.
            let smoothedWeights = weights.clone(); // [1, 8, seqLength, 1500]

            for (let a = 0; a < smoothedWeights.dims[0]; ++a) {
                let aTensor = smoothedWeights[a]; // [8, seqLength, 1500]

                for (let b = 0; b < aTensor.dims[0]; ++b) {
                    let bTensor = aTensor[b]; // [seqLength, 1500]

                    const stdTensor = std[a][b][0]; // [1500]
                    const meanTensor = calculatedMean[a][b][0]; // [1500]

                    for (let c = 0; c < bTensor.dims[0]; ++c) {

                        let cTensor = bTensor[c]; // [1500]
                        for (let d = 0; d < cTensor.data.length; ++d) {
                            cTensor.data[d] = (cTensor.data[d] - meanTensor.data[d]) / stdTensor.data[d]
                        }

                        // Apply median filter.
                        cTensor.data.set((0,_transformers_js__WEBPACK_IMPORTED_MODULE_6__.medianFilter)(cTensor.data, median_filter_width))
                    }
                }
            }

            // Average the different cross-attention heads.
            const matrix = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.mean)(smoothedWeights, 1);
            return matrix;
        });

        const timestampsShape = [generate_outputs.sequences.length, generate_outputs.sequences[0].length];

        const timestamps = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor(
            'float32',
            new Float32Array(timestampsShape[0] * timestampsShape[1]),
            timestampsShape
        );

        // Perform dynamic time warping on each element of the batch.
        for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) {
            // NOTE: Since we run only one batch at a time, we can squeeze to get the same dimensions
            // as the python implementation
            const matrix = batchedMatrices[batch_idx].neg().squeeze_(0);
            let [text_indices, time_indices] = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.dynamicTimeWarping)(matrix);

            let diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]);
            let jumps = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)([1], diffs).map(x => !!x); // convert to boolean

            let jump_times = [];
            for (let i = 0; i < jumps.length; ++i) {
                if (jumps[i]) {
                    jump_times.push(time_indices[i] * time_precision);
                    // NOTE: No point in rounding here, since we set to Float32Array later
                }
            }
            timestamps[batch_idx].data.set(jump_times, 1)
        }

        return timestamps;
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
/**
 * Vision Encoder-Decoder model based on OpenAI's GPT architecture for image captioning and other vision tasks
 */
class VisionEncoderDecoderModel extends PreTrainedModel {
    main_input_name = 'pixel_values';

    /**
     * Creates a new instance of the `VisionEncoderDecoderModel` class.
     * @param {Object} config The configuration object specifying the hyperparameters and other model settings.
     * @param {Object} session The ONNX session containing the encoder model.
     * @param {any} decoder_merged_session The ONNX session containing the merged decoder model.
     * @param {Object} generation_config Configuration object for the generation process.
     */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        // Extract configs
        const encoderConfig = this.config.encoder;
        const decoderConfig = this.config.decoder;

        // Validate encoder
        const encoderModelType = encoderConfig.model_type;
        const encoderModel =
            MODEL_MAPPING_NAMES_ENCODER_ONLY.get(encoderModelType)
            ?? MODEL_MAPPING_NAMES_ENCODER_DECODER.get(encoderModelType);
        if (!encoderModel) {
            console.warn(`Model type for encoder '${encoderModelType}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`);
        }

        // Validate decoder
        const decoderModel = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(decoderConfig.model_type);
        if (!decoderModel) {
            throw new Error(`Unable to construct \`VisionEncoderDecoder\` due to unsupported decoder: "${this.config.decoder.model_type}"`);
        }

        // @ts-ignore
        const decoderModelClass = decoderModel[1];
        // @ts-ignore
        const decoder = new decoderModelClass(decoderConfig, decoder_merged_session, generation_config);

        this.add_encoder_pkv = 'num_decoder_layers' in decoder;
        if (this.add_encoder_pkv) {
            // Decoder is part of an encoder-decoder model
            this.num_decoder_layers = decoder.num_decoder_layers;
            this.num_decoder_heads = decoder.num_decoder_heads;
            this.decoder_dim_kv = decoder.decoder_dim_kv;

            this.num_encoder_layers = decoder.num_encoder_layers;
            this.num_encoder_heads = decoder.num_encoder_heads;
            this.encoder_dim_kv = decoder.encoder_dim_kv;

        } else {
            // Decoder is a decoder-only model
            this.num_layers = decoder.num_layers;
            this.num_heads = decoder.num_heads;
            this.dim_kv = decoder.dim_kv;
        }
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// CLIP models
class CLIPPreTrainedModel extends PreTrainedModel { }

/**
 * CLIP Text and Vision Model with a projection layers on top
 * 
 * **Example:** Perform zero-shot image classification with a `CLIPModel`.
 * 
 * ```javascript
 * import { AutoTokenizer, AutoProcessor, CLIPModel, RawImage } from '@xenova/transformers';
 * 
 * // Load tokenizer, processor, and model
 * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16');
 * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');
 * let model = await CLIPModel.from_pretrained('Xenova/clip-vit-base-patch16');
 * 
 * // Run tokenization
 * let texts = ['a photo of a car', 'a photo of a football match']
 * let text_inputs = tokenizer(texts, { padding: true, truncation: true });
 * 
 * // Read image and run processor
 * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
 * let image_inputs = await processor(image);
 * 
 * // Run model with both text and pixel inputs
 * let output = await model({ ...text_inputs, ...image_inputs });
 * // {
 * //   logits_per_image: Tensor {
 * //     dims: [ 1, 2 ],
 * //     data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ],
 * //   },
 * //   logits_per_text: Tensor {
 * //     dims: [ 2, 1 ],
 * //     data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ],
 * //   },
 * //   text_embeds: Tensor {
 * //     dims: [ 2, 512 ],
 * //     data: Float32Array(1024) [ ... ],
 * //   },
 * //   image_embeds: Tensor {
 * //     dims: [ 1, 512 ],
 * //     data: Float32Array(512) [ ... ],
 * //   }
 * // }
 * ```
 */
class CLIPModel extends CLIPPreTrainedModel { }

/**
 * CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output)
 * 
 * **Example:** Compute text embeddings with `CLIPTextModelWithProjection`.
 * 
 * ```javascript
 * import { AutoTokenizer, CLIPTextModelWithProjection } from '@xenova/transformers';
 * 
 * // Load tokenizer and text model
 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16');
 * const text_model = await CLIPTextModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16');
 * 
 * // Run tokenization
 * let texts = ['a photo of a car', 'a photo of a football match'];
 * let text_inputs = tokenizer(texts, { padding: true, truncation: true });
 * 
 * // Compute embeddings
 * const { text_embeds } = await text_model(text_inputs);
 * // Tensor {
 * //   dims: [ 2, 512 ],
 * //   type: 'float32',
 * //   data: Float32Array(1024) [ ... ],
 * //   size: 1024
 * // }
 * ```
 */
class CLIPTextModelWithProjection extends CLIPPreTrainedModel {

    /** @type {PreTrainedModel.from_pretrained} */
    static async from_pretrained(pretrained_model_name_or_path, options = {}) {
        // Update default model file name if not provided
        options.model_file_name ??= 'text_model';
        return super.from_pretrained(pretrained_model_name_or_path, options);
    }
}

/**
 * CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output)
 * 
 * **Example:** Compute vision embeddings with `CLIPVisionModelWithProjection`.
 * 
 * ```javascript
 * import { AutoProcessor, CLIPVisionModelWithProjection, RawImage} from '@xenova/transformers';
 * 
 * // Load processor and vision model
 * const processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');
 * const vision_model = await CLIPVisionModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16');
 * 
 * // Read image and run processor
 * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
 * let image_inputs = await processor(image);
 * 
 * // Compute embeddings
 * const { image_embeds } = await vision_model(image_inputs);
 * // Tensor {
 * //   dims: [ 1, 512 ],
 * //   type: 'float32',
 * //   data: Float32Array(512) [ ... ],
 * //   size: 512
 * // }
 * ```
 */
class CLIPVisionModelWithProjection extends CLIPPreTrainedModel {
    /** @type {PreTrainedModel.from_pretrained} */
    static async from_pretrained(pretrained_model_name_or_path, options = {}) {
        // Update default model file name if not provided
        options.model_file_name ??= 'vision_model';
        return super.from_pretrained(pretrained_model_name_or_path, options);
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// SigLIP models
class SiglipPreTrainedModel extends PreTrainedModel { }

/**
 * SigLIP Text and Vision Model with a projection layers on top
 * 
 * **Example:** Perform zero-shot image classification with a `SiglipModel`.
 * 
 * ```javascript
 * import { AutoTokenizer, AutoProcessor, SiglipModel, RawImage } from '@xenova/transformers';
 * 
 * // Load tokenizer, processor, and model
 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224');
 * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224');
 * const model = await SiglipModel.from_pretrained('Xenova/siglip-base-patch16-224');
 * 
 * // Run tokenization
 * const texts = ['a photo of 2 cats', 'a photo of 2 dogs'];
 * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });
 * 
 * // Read image and run processor
 * const image = await RawImage.read('http://images.cocodataset.org/val2017/000000039769.jpg');
 * const image_inputs = await processor(image);
 * 
 * // Run model with both text and pixel inputs
 * const output = await model({ ...text_inputs, ...image_inputs });
 * // {
 * //   logits_per_image: Tensor {
 * //     dims: [ 1, 2 ],
 * //     data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ],
 * //   },
 * //   logits_per_text: Tensor {
 * //     dims: [ 2, 1 ],
 * //     data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ],
 * //   },
 * //   text_embeds: Tensor {
 * //     dims: [ 2, 768 ],
 * //     data: Float32Array(1536) [ ... ],
 * //   },
 * //   image_embeds: Tensor {
 * //     dims: [ 1, 768 ],
 * //     data: Float32Array(768) [ ... ],
 * //   }
 * // }
 * ```
 */
class SiglipModel extends SiglipPreTrainedModel { }

/**
 * The text model from SigLIP without any head or projection on top.
 * 
 * **Example:** Compute text embeddings with `SiglipTextModel`.
 * 
 * ```javascript
 * import { AutoTokenizer, SiglipTextModel } from '@xenova/transformers';
 * 
 * // Load tokenizer and text model
 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224');
 * const text_model = await SiglipTextModel.from_pretrained('Xenova/siglip-base-patch16-224');
 * 
 * // Run tokenization
 * const texts = ['a photo of 2 cats', 'a photo of 2 dogs'];
 * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });
 * 
 * // Compute embeddings
 * const { pooler_output } = await text_model(text_inputs);
 * // Tensor {
 * //   dims: [ 2, 768 ],
 * //   type: 'float32',
 * //   data: Float32Array(1536) [ ... ],
 * //   size: 1536
 * // }
 * ```
 */
class SiglipTextModel extends SiglipPreTrainedModel {

    /** @type {PreTrainedModel.from_pretrained} */
    static async from_pretrained(pretrained_model_name_or_path, options = {}) {
        // Update default model file name if not provided
        options.model_file_name ??= 'text_model';
        return super.from_pretrained(pretrained_model_name_or_path, options);
    }
}

/**
 * The vision model from SigLIP without any head or projection on top.
 * 
 * **Example:** Compute vision embeddings with `SiglipVisionModel`.
 * 
 * ```javascript
 * import { AutoProcessor, SiglipVisionModel, RawImage} from '@xenova/transformers';
 * 
 * // Load processor and vision model
 * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224');
 * const vision_model = await SiglipVisionModel.from_pretrained('Xenova/siglip-base-patch16-224');
 * 
 * // Read image and run processor
 * const image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
 * const image_inputs = await processor(image);
 * 
 * // Compute embeddings
 * const { pooler_output } = await vision_model(image_inputs);
 * // Tensor {
 * //   dims: [ 1, 768 ],
 * //   type: 'float32',
 * //   data: Float32Array(768) [ ... ],
 * //   size: 768
 * // }
 * ```
 */
class SiglipVisionModel extends CLIPPreTrainedModel {
    /** @type {PreTrainedModel.from_pretrained} */
    static async from_pretrained(pretrained_model_name_or_path, options = {}) {
        // Update default model file name if not provided
        options.model_file_name ??= 'vision_model';
        return super.from_pretrained(pretrained_model_name_or_path, options);
    }
}
//////////////////////////////////////////////////
// ChineseCLIP models
class ChineseCLIPPreTrainedModel extends PreTrainedModel { }

class ChineseCLIPModel extends ChineseCLIPPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// CLIPSeg models
class CLIPSegPreTrainedModel extends PreTrainedModel { }

class CLIPSegModel extends CLIPSegPreTrainedModel { }

/**
 * CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation.
 * 
 * **Example:** Perform zero-shot image segmentation with a `CLIPSegForImageSegmentation` model.
 * 
 * ```javascript
 * import { AutoTokenizer, AutoProcessor, CLIPSegForImageSegmentation, RawImage } from '@xenova/transformers';
 * 
 * // Load tokenizer, processor, and model
 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clipseg-rd64-refined');
 * const processor = await AutoProcessor.from_pretrained('Xenova/clipseg-rd64-refined');
 * const model = await CLIPSegForImageSegmentation.from_pretrained('Xenova/clipseg-rd64-refined');
 * 
 * // Run tokenization
 * const texts = ['a glass', 'something to fill', 'wood', 'a jar'];
 * const text_inputs = tokenizer(texts, { padding: true, truncation: true });
 * 
 * // Read image and run processor
 * const image = await RawImage.read('https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true');
 * const image_inputs = await processor(image);
 * 
 * // Run model with both text and pixel inputs
 * const { logits } = await model({ ...text_inputs, ...image_inputs });
 * // logits: Tensor {
 * //   dims: [4, 352, 352],
 * //   type: 'float32',
 * //   data: Float32Array(495616) [ ... ],
 * //   size: 495616
 * // }
 * ```
 * 
 * You can visualize the predictions as follows:
 * ```javascript
 * const preds = logits
 *   .unsqueeze_(1)
 *   .sigmoid_()
 *   .mul_(255)
 *   .round_()
 *   .to('uint8');
 * 
 * for (let i = 0; i < preds.dims[0]; ++i) {
 *   const img = RawImage.fromTensor(preds[i]);
 *   img.save(`prediction_${i}.png`);
 * }
 * ```
 */
class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// GPT2 models
class GPT2PreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `GPT2PreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.n_head
        this.num_layers = this.config.n_layer
        this.dim_kv = this.config.n_embd / this.num_heads;
    }
}

class GPT2Model extends GPT2PreTrainedModel { }

/**
 * GPT-2 language model head on top of the GPT-2 base model. This model is suitable for text generation tasks.
 */
class GPT2LMHeadModel extends GPT2PreTrainedModel { }
// export class GPT2ForSequenceClassification extends GPT2PreTrainedModel {
// TODO
// }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// GPTNeo models
class GPTNeoPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `GPTNeoPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.num_heads;
        this.num_layers = this.config.num_layers;
        this.dim_kv = this.config.hidden_size / this.num_heads;
    }
}
class GPTNeoModel extends GPTNeoPreTrainedModel { }

class GPTNeoForCausalLM extends GPTNeoPreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// GPTNeoX models
class GPTNeoXPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `GPTNeoXPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.num_attention_heads;
        this.num_layers = this.config.num_hidden_layers;
        this.dim_kv = this.config.hidden_size / this.num_heads;
    }
}
class GPTNeoXModel extends GPTNeoXPreTrainedModel { }

class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// GPT-J models
class GPTJPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `GPTJPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.n_head
        this.num_layers = this.config.n_layer
        this.dim_kv = this.config.n_embd / this.num_heads;
    }
}

class GPTJModel extends GPTJPreTrainedModel { }

class GPTJForCausalLM extends GPTJPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// GPTBigCode models
class GPTBigCodePreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `GPTBigCodePreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.n_head
        this.num_layers = this.config.n_layer
        this.dim_kv = this.config.n_embd / this.num_heads;
    }
}

class GPTBigCodeModel extends GPTBigCodePreTrainedModel { }

class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// CodeGen models
class CodeGenPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `CodeGenPreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.n_head
        this.num_layers = this.config.n_layer
        this.dim_kv = this.config.n_embd / this.num_heads;
    }
}
/**
 * CodeGenModel is a class representing a code generation model without a language model head.
 */
class CodeGenModel extends CodeGenPreTrainedModel { }

/**
 * CodeGenForCausalLM is a class that represents a code generation model based on the GPT-2 architecture. It extends the `CodeGenPreTrainedModel` class.
 */
class CodeGenForCausalLM extends CodeGenPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// LLama models

/**
 * The bare LLama Model outputting raw hidden-states without any specific head on top.
 */
class LlamaPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `LlamaPreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.num_key_value_heads ?? this.config.num_attention_heads
        this.num_layers = this.config.num_hidden_layers
        this.dim_kv = this.config.hidden_size / this.config.num_attention_heads
    }
}
/**
 * The bare LLaMA Model outputting raw hidden-states without any specific head on top.
 */
class LlamaModel extends LlamaPreTrainedModel { }

class LlamaForCausalLM extends LlamaPreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Qwen2 models

/**
 * The bare Qwen2 Model outputting raw hidden-states without any specific head on top.
 */
class Qwen2PreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `Qwen2PreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.num_key_value_heads ?? this.config.num_attention_heads
        this.num_layers = this.config.num_hidden_layers
        this.dim_kv = this.config.hidden_size / this.config.num_attention_heads
    }
}
/**
 * The bare Qwen2 Model outputting raw hidden-states without any specific head on top.
 */
class Qwen2Model extends Qwen2PreTrainedModel { }

class Qwen2ForCausalLM extends Qwen2PreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Phi models

class PhiPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `PhiPreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id;

        this.num_heads = this.config.num_attention_heads;
        this.num_layers = this.config.num_hidden_layers;
        this.dim_kv = this.config.hidden_size / this.num_heads;
    }
}
/**
 * The bare Phi Model outputting raw hidden-states without any specific head on top.
 */
class PhiModel extends PhiPreTrainedModel { }

class PhiForCausalLM extends PhiPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Bloom models
/**
 * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
 */
class BloomPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `BloomPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.n_head
        this.num_layers = this.config.n_layer
        this.dim_kv = this.config.hidden_size / this.num_heads;
    }
}

/**
 * The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.
 */
class BloomModel extends BloomPreTrainedModel { }

/**
 * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
 */
class BloomForCausalLM extends BloomPreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// MPT models
class MptPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `MptPreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.n_heads
        this.num_layers = this.config.n_layers
        this.dim_kv = this.config.d_model / this.num_heads;
    }
}

/**
 * The bare Mpt Model transformer outputting raw hidden-states without any specific head on top.
 */
class MptModel extends MptPreTrainedModel { }

/**
 * The MPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
 */
class MptForCausalLM extends MptPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// OPT models
class OPTPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `OPTPreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.num_attention_heads;
        this.num_layers = this.config.num_hidden_layers;
        this.dim_kv = this.config.hidden_size / this.num_heads;
    }
}

/**
 * The bare OPT Model outputting raw hidden-states without any specific head on top.
 */
class OPTModel extends OPTPreTrainedModel { }

/**
 * The OPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
 */
class OPTForCausalLM extends OPTPreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
class ViTPreTrainedModel extends PreTrainedModel { }
class ViTModel extends ViTPreTrainedModel { }
class ViTForImageClassification extends ViTPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
class FastViTPreTrainedModel extends PreTrainedModel { }
class FastViTModel extends FastViTPreTrainedModel { }
class FastViTForImageClassification extends FastViTPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
class VitMattePreTrainedModel extends PreTrainedModel { }

/**
 * ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes.
 * 
 * **Example:** Perform image matting with a `VitMatteForImageMatting` model.
 * ```javascript
 * import { AutoProcessor, VitMatteForImageMatting, RawImage } from '@xenova/transformers';
 * 
 * // Load processor and model
 * const processor = await AutoProcessor.from_pretrained('Xenova/vitmatte-small-distinctions-646');
 * const model = await VitMatteForImageMatting.from_pretrained('Xenova/vitmatte-small-distinctions-646');
 * 
 * // Load image and trimap
 * const image = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_image.png');
 * const trimap = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_trimap.png');
 * 
 * // Prepare image + trimap for the model
 * const inputs = await processor(image, trimap);
 * 
 * // Predict alpha matte
 * const { alphas } = await model(inputs);
 * // Tensor {
 * //   dims: [ 1, 1, 640, 960 ],
 * //   type: 'float32',
 * //   size: 614400,
 * //   data: Float32Array(614400) [ 0.9894027709960938, 0.9970508813858032, ... ]
 * // }
 * ```
 * 
 * You can visualize the alpha matte as follows:
 * ```javascript
 * import { Tensor, cat } from '@xenova/transformers';
 * 
 * // Visualize predicted alpha matte
 * const imageTensor = image.toTensor();
 * 
 * // Convert float (0-1) alpha matte to uint8 (0-255)
 * const alphaChannel = alphas
 *   .squeeze(0)
 *   .mul_(255)
 *   .clamp_(0, 255)
 *   .round_()
 *   .to('uint8');
 * 
 * // Concatenate original image with predicted alpha
 * const imageData = cat([imageTensor, alphaChannel], 0);
 * 
 * // Save output image
 * const outputImage = RawImage.fromTensor(imageData);
 * outputImage.save('output.png');
 * ```
 */
class VitMatteForImageMatting extends VitMattePreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new ImageMattingOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
class MobileViTPreTrainedModel extends PreTrainedModel { }
class MobileViTModel extends MobileViTPreTrainedModel { }
class MobileViTForImageClassification extends MobileViTPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
// TODO: MobileViTForSemanticSegmentation

//////////////////////////////////////////////////

//////////////////////////////////////////////////
class MobileViTV2PreTrainedModel extends PreTrainedModel { }
class MobileViTV2Model extends MobileViTV2PreTrainedModel { }
class MobileViTV2ForImageClassification extends MobileViTV2PreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
// TODO: MobileViTV2ForSemanticSegmentation

//////////////////////////////////////////////////

//////////////////////////////////////////////////
class OwlViTPreTrainedModel extends PreTrainedModel { }
class OwlViTModel extends OwlViTPreTrainedModel { }
class OwlViTForObjectDetection extends OwlViTPreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
class Owlv2PreTrainedModel extends PreTrainedModel { }
class Owlv2Model extends Owlv2PreTrainedModel { }
class Owlv2ForObjectDetection extends Owlv2PreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Beit Models
class BeitPreTrainedModel extends PreTrainedModel { }
class BeitModel extends BeitPreTrainedModel { }
class BeitForImageClassification extends BeitPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
class DetrPreTrainedModel extends PreTrainedModel { }
class DetrModel extends DetrPreTrainedModel { }
class DetrForObjectDetection extends DetrPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new DetrObjectDetectionOutput(await super._call(model_inputs));
    }
}

class DetrForSegmentation extends DetrPreTrainedModel {
    /**
     * Runs the model with the provided inputs
     * @param {Object} model_inputs Model inputs
     * @returns {Promise<DetrSegmentationOutput>} Object containing segmentation outputs
     */
    async _call(model_inputs) {
        return new DetrSegmentationOutput(await super._call(model_inputs));
    }
}

class DetrObjectDetectionOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Classification logits (including no-object) for all queries.
     * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).
     * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).
     */
    constructor({ logits, pred_boxes }) {
        super();
        this.logits = logits;
        this.pred_boxes = pred_boxes;
    }
}

class DetrSegmentationOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits The output logits of the model.
     * @param {Tensor} output.pred_boxes Predicted boxes.
     * @param {Tensor} output.pred_masks Predicted masks.
     */
    constructor({ logits, pred_boxes, pred_masks }) {
        super();
        this.logits = logits;
        this.pred_boxes = pred_boxes;
        this.pred_masks = pred_masks;
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
class TableTransformerPreTrainedModel extends PreTrainedModel { }

/**
 * The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)
 * outputting raw hidden-states without any specific head on top.
 */
class TableTransformerModel extends TableTransformerPreTrainedModel { }

/**
 * Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)
 * with object detection heads on top, for tasks such as COCO detection.
 */
class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new TableTransformerObjectDetectionOutput(await super._call(model_inputs));
    }
}
class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
class DeiTPreTrainedModel extends PreTrainedModel { }
class DeiTModel extends DeiTPreTrainedModel { }
class DeiTForImageClassification extends DeiTPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
/**
 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
 */
class ResNetPreTrainedModel extends PreTrainedModel { }

/**
 * The bare ResNet model outputting raw features without any specific head on top.
 */
class ResNetModel extends ResNetPreTrainedModel { }

/**
 * ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.
 */
class ResNetForImageClassification extends ResNetPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
class SwinPreTrainedModel extends PreTrainedModel { }
class SwinModel extends SwinPreTrainedModel { }
class SwinForImageClassification extends SwinPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
class Swin2SRPreTrainedModel extends PreTrainedModel { }

/**
 * The bare Swin2SR Model transformer outputting raw hidden-states without any specific head on top.
 */
class Swin2SRModel extends Swin2SRPreTrainedModel { }

/**
 * Swin2SR Model transformer with an upsampler head on top for image super resolution and restoration.
 * 
 * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`.
 * 
 * ```javascript
 * import { AutoProcessor, Swin2SRForImageSuperResolution, RawImage } from '@xenova/transformers';
 * 
 * // Load processor and model
 * const model_id = 'Xenova/swin2SR-classical-sr-x2-64';
 * const processor = await AutoProcessor.from_pretrained(model_id);
 * const model = await Swin2SRForImageSuperResolution.from_pretrained(model_id);
 * 
 * // Prepare model inputs
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';
 * const image = await RawImage.fromURL(url);
 * const inputs = await processor(image);
 * 
 * // Run model
 * const outputs = await model(inputs);
 * 
 * // Convert Tensor to RawImage
 * const output = outputs.reconstruction.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');
 * const outputImage = RawImage.fromTensor(output);
 * // RawImage {
 * //   data: Uint8Array(786432) [ 41, 31, 24, ... ],
 * //   width: 512,
 * //   height: 512,
 * //   channels: 3
 * // }
 * ```
 */
class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
class DPTPreTrainedModel extends PreTrainedModel { }

/**
 * The bare DPT Model transformer outputting raw hidden-states without any specific head on top.
 */
class DPTModel extends DPTPreTrainedModel { }

/**
 * DPT Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.
 * 
 * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`.
 * ```javascript
 * import { DPTForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@xenova/transformers';
 * 
 * // Load model and processor
 * const model_id = 'Xenova/dpt-hybrid-midas';
 * const model = await DPTForDepthEstimation.from_pretrained(model_id);
 * const processor = await AutoProcessor.from_pretrained(model_id);
 * 
 * // Load image from URL
 * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg';
 * const image = await RawImage.fromURL(url);
 * 
 * // Prepare image for the model
 * const inputs = await processor(image);
 * 
 * // Run model
 * const { predicted_depth } = await model(inputs);
 * 
 * // Interpolate to original size
 * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false);
 * 
 * // Visualize the prediction
 * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');
 * const depth = RawImage.fromTensor(formatted);
 * // RawImage {
 * //   data: Uint8Array(307200) [ 85, 85, 84, ... ],
 * //   width: 640,
 * //   height: 480,
 * //   channels: 1
 * // }
 * ```
 */
class DPTForDepthEstimation extends DPTPreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
class DepthAnythingPreTrainedModel extends PreTrainedModel { }

/**
 * Depth Anything Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.
 */
class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
class GLPNPreTrainedModel extends PreTrainedModel { }

/**
 * The bare GLPN encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.
 */
class GLPNModel extends GLPNPreTrainedModel { }

/**
 * GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2.
 * 
 * **Example:** Depth estimation w/ `Xenova/glpn-kitti`.
 * ```javascript
 * import { GLPNForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@xenova/transformers';
 * 
 * // Load model and processor
 * const model_id = 'Xenova/glpn-kitti';
 * const model = await GLPNForDepthEstimation.from_pretrained(model_id);
 * const processor = await AutoProcessor.from_pretrained(model_id);
 * 
 * // Load image from URL
 * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg';
 * const image = await RawImage.fromURL(url);
 * 
 * // Prepare image for the model
 * const inputs = await processor(image);
 * 
 * // Run model
 * const { predicted_depth } = await model(inputs);
 * 
 * // Interpolate to original size
 * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false);
 * 
 * // Visualize the prediction
 * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');
 * const depth = RawImage.fromTensor(formatted);
 * // RawImage {
 * //   data: Uint8Array(307200) [ 207, 169, 154, ... ],
 * //   width: 640,
 * //   height: 480,
 * //   channels: 1
 * // }
 * ```
 */
class GLPNForDepthEstimation extends GLPNPreTrainedModel { }
//////////////////////////////////////////////////

//////////////////////////////////////////////////
class DonutSwinPreTrainedModel extends PreTrainedModel { }

/**
 * The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top.
 * 
 * **Example:** Step-by-step Document Parsing.
 * 
 * ```javascript
 * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@xenova/transformers';
 * 
 * // Choose model to use
 * const model_id = 'Xenova/donut-base-finetuned-cord-v2';
 * 
 * // Prepare image inputs
 * const processor = await AutoProcessor.from_pretrained(model_id);
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/receipt.png';
 * const image = await RawImage.read(url);
 * const image_inputs = await processor(image);
 * 
 * // Prepare decoder inputs
 * const tokenizer = await AutoTokenizer.from_pretrained(model_id);
 * const task_prompt = '<s_cord-v2>';
 * const decoder_input_ids = tokenizer(task_prompt, {
 *   add_special_tokens: false,
 * }).input_ids;
 * 
 * // Create the model
 * const model = await AutoModelForVision2Seq.from_pretrained(model_id);
 * 
 * // Run inference
 * const output = await model.generate(image_inputs.pixel_values, {
 *   decoder_input_ids,
 *   max_length: model.config.decoder.max_position_embeddings,
 * });
 * 
 * // Decode output
 * const decoded = tokenizer.batch_decode(output)[0];
 * // <s_cord-v2><s_menu><s_nm> CINNAMON SUGAR</s_nm><s_unitprice> 17,000</s_unitprice><s_cnt> 1 x</s_cnt><s_price> 17,000</s_price></s_menu><s_sub_total><s_subtotal_price> 17,000</s_subtotal_price></s_sub_total><s_total><s_total_price> 17,000</s_total_price><s_cashprice> 20,000</s_cashprice><s_changeprice> 3,000</s_changeprice></s_total></s>
 * ```
 * 
 * **Example:** Step-by-step Document Visual Question Answering (DocVQA)
 * 
 * ```javascript
 * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@xenova/transformers';
 * 
 * // Choose model to use
 * const model_id = 'Xenova/donut-base-finetuned-docvqa';
 * 
 * // Prepare image inputs
 * const processor = await AutoProcessor.from_pretrained(model_id);
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';
 * const image = await RawImage.read(url);
 * const image_inputs = await processor(image);
 * 
 * // Prepare decoder inputs
 * const tokenizer = await AutoTokenizer.from_pretrained(model_id);
 * const question = 'What is the invoice number?';
 * const task_prompt = `<s_docvqa><s_question>${question}</s_question><s_answer>`;
 * const decoder_input_ids = tokenizer(task_prompt, {
 *   add_special_tokens: false,
 * }).input_ids;
 * 
 * // Create the model
 * const model = await AutoModelForVision2Seq.from_pretrained(model_id);
 * 
 * // Run inference
 * const output = await model.generate(image_inputs.pixel_values, {
 *   decoder_input_ids,
 *   max_length: model.config.decoder.max_position_embeddings,
 * });
 * 
 * // Decode output
 * const decoded = tokenizer.batch_decode(output)[0];
 * // <s_docvqa><s_question> What is the invoice number?</s_question><s_answer> us-001</s_answer></s>
 * ```
 */
class DonutSwinModel extends DonutSwinPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
class ConvNextPreTrainedModel extends PreTrainedModel { }

/**
 * The bare ConvNext model outputting raw features without any specific head on top.
 */
class ConvNextModel extends ConvNextPreTrainedModel { }

/**
 * ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.
 */
class ConvNextForImageClassification extends ConvNextPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
class ConvNextV2PreTrainedModel extends PreTrainedModel { }

/**
 * The bare ConvNextV2 model outputting raw features without any specific head on top.
 */
class ConvNextV2Model extends ConvNextV2PreTrainedModel { }

/**
 * ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.
 */
class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
class Dinov2PreTrainedModel extends PreTrainedModel { }

/**
 * The bare DINOv2 Model transformer outputting raw hidden-states without any specific head on top.
 */
class Dinov2Model extends Dinov2PreTrainedModel { }

/**
 * Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet.
 */
class Dinov2ForImageClassification extends Dinov2PreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
class YolosPreTrainedModel extends PreTrainedModel { }
class YolosModel extends YolosPreTrainedModel { }
class YolosForObjectDetection extends YolosPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new YolosObjectDetectionOutput(await super._call(model_inputs));
    }
}

class YolosObjectDetectionOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Classification logits (including no-object) for all queries.
     * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).
     * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).
     */
    constructor({ logits, pred_boxes }) {
        super();
        this.logits = logits;
        this.pred_boxes = pred_boxes;
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
class SamPreTrainedModel extends PreTrainedModel { }

/**
 * Segment Anything Model (SAM) for generating segmentation masks, given an input image
 * and optional 2D location and bounding boxes.
 * 
 * **Example:** Perform mask generation w/ `Xenova/sam-vit-base`.
 * ```javascript
 * import { SamModel, AutoProcessor, RawImage } from '@xenova/transformers';
 * 
 * const model = await SamModel.from_pretrained('Xenova/sam-vit-base');
 * const processor = await AutoProcessor.from_pretrained('Xenova/sam-vit-base');
 * 
 * const img_url = 'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png';
 * const raw_image = await RawImage.read(img_url);
 * const input_points = [[[450, 600]]] // 2D localization of a window
 * 
 * const inputs = await processor(raw_image, input_points);
 * const outputs = await model(inputs);
 * 
 * const masks = await processor.post_process_masks(outputs.pred_masks, inputs.original_sizes, inputs.reshaped_input_sizes);
 * // [
 * //   Tensor {
 * //     dims: [ 1, 3, 1764, 2646 ],
 * //     type: 'bool',
 * //     data: Uint8Array(14002632) [ ... ],
 * //     size: 14002632
 * //   }
 * // ]
 * const scores = outputs.iou_scores;
 * // Tensor {
 * //   dims: [ 1, 1, 3 ],
 * //   type: 'float32',
 * //   data: Float32Array(3) [
 * //     0.8892380595207214,
 * //     0.9311248064041138,
 * //     0.983696699142456
 * //   ],
 * //   size: 3
 * // }
 * ```
 */
class SamModel extends SamPreTrainedModel {
    /**
     * Creates a new instance of the `SamModel` class.
     * @param {Object} config The configuration object specifying the hyperparameters and other model settings.
     * @param {Object} vision_encoder The ONNX session containing the vision encoder model.
     * @param {any} prompt_encoder_mask_decoder The ONNX session containing the prompt encoder and mask decoder model.
     */
    constructor(config, vision_encoder, prompt_encoder_mask_decoder) {
        super(config, vision_encoder);
        this.prompt_encoder_mask_decoder = prompt_encoder_mask_decoder;
    }

    /**
     * Compute image embeddings and positional image embeddings, given the pixel values of an image.
     * @param {Object} model_inputs Object containing the model inputs.
     * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`.
     * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings.
     */
    async get_image_embeddings({ pixel_values }) {
        // in:
        //  - pixel_values: tensor.float32[batch_size,3,1024,1024]
        // 
        // out:
        //  - image_embeddings: tensor.float32[batch_size,256,64,64]
        //  - image_positional_embeddings: tensor.float32[batch_size,256,64,64]
        return await encoderForward(this, { pixel_values })
    }

    /**
     * @typedef {Object} SamModelInputs Object containing the model inputs.
     * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.
     * These can be obtained using a `SamProcessor`.
     * @property {Tensor} input_points Input 2D spatial points with shape `(batch_size, num_points, 2)`.
     * This is used by the prompt encoder to encode the prompt.
     * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.
     * This is used by the prompt encoder to encode the prompt. There are 4 types of labels:
     *  - `1`: the point is a point that contains the object of interest
     *  - `0`: the point is a point that does not contain the object of interest
     *  - `-1`: the point corresponds to the background
     *  - `-10`: the point is a padding point, thus should be ignored by the prompt encoder
     * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder.
     * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder.
     */

    /**
     * @param {SamModelInputs} model_inputs Object containing the model inputs.
     * @returns {Promise<Object>} The output of the model.
     */
    async forward(model_inputs) {
        if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) {
            // Compute the image embeddings if they are missing
            model_inputs = {
                ...model_inputs,
                ...(await this.get_image_embeddings(model_inputs))
            }
        }

        if (!model_inputs.input_labels) {
            // Set default input labels if they are missing
            const shape = model_inputs.input_points.dims.slice(0, -1);
            const numElements = shape.reduce((a, b) => a * b, 1);
            model_inputs.input_labels = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor(
                'int64',
                new BigInt64Array(numElements).fill(1n),
                shape
            );
        }

        // Returns:
        //  - iou_scores: tensor.float32[batch_size,point_batch_size,3]
        //  - pred_masks: tensor.float32[batch_size,point_batch_size,3,256,256]
        return await sessionRun(this.prompt_encoder_mask_decoder, {
            input_points: model_inputs.input_points,
            input_labels: model_inputs.input_labels,
            image_embeddings: model_inputs.image_embeddings,
            image_positional_embeddings: model_inputs.image_positional_embeddings,
        });
    }

    /**
     * Runs the model with the provided inputs
     * @param {Object} model_inputs Model inputs
     * @returns {Promise<SamImageSegmentationOutput>} Object containing segmentation outputs
     */
    async _call(model_inputs) {
        return new SamImageSegmentationOutput(await super._call(model_inputs));
    }
}


/**
 * Base class for Segment-Anything model's output.
 */
class SamImageSegmentationOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.iou_scores The output logits of the model.
     * @param {Tensor} output.pred_masks Predicted boxes.
     */
    constructor({ iou_scores, pred_masks }) {
        super();
        this.iou_scores = iou_scores;
        this.pred_masks = pred_masks;
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// MarianMT models
class MarianPreTrainedModel extends PreTrainedModel { };

class MarianModel extends MarianPreTrainedModel { }

class MarianMTModel extends MarianPreTrainedModel {

    /**
     * Creates a new instance of the `MarianMTModel` class.
    * @param {Object} config The model configuration object.
    * @param {Object} session The ONNX session object.
    * @param {any} decoder_merged_session 
    * @param {any} generation_config 
    */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.decoder_layers;
        this.num_decoder_heads = this.config.decoder_attention_heads;
        this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;

        this.num_encoder_layers = this.config.encoder_layers;
        this.num_encoder_heads = this.config.encoder_attention_heads;
        this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// M2M100 models
class M2M100PreTrainedModel extends PreTrainedModel { };

class M2M100Model extends M2M100PreTrainedModel { }

class M2M100ForConditionalGeneration extends M2M100PreTrainedModel {

    /**
     * Creates a new instance of the `M2M100ForConditionalGeneration` class.
    * @param {Object} config The model configuration object.
    * @param {Object} session The ONNX session object.
    * @param {any} decoder_merged_session 
    * @param {any} generation_config 
    */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.decoder_layers;
        this.num_decoder_heads = this.config.decoder_attention_heads;
        this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;

        this.num_encoder_layers = this.config.encoder_layers;
        this.num_encoder_heads = this.config.encoder_attention_heads;
        this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }

}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Wav2Vec2 models
class Wav2Vec2PreTrainedModel extends PreTrainedModel { };

/**
 * The bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top.
 * 
 * **Example:** Load and run a `Wav2Vec2Model` for feature extraction.
 * 
 * ```javascript
 * import { AutoProcessor, AutoModel, read_audio } from '@xenova/transformers';
 * 
 * // Read and preprocess audio
 * const processor = await AutoProcessor.from_pretrained('Xenova/mms-300m');
 * const audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);
 * const inputs = await processor(audio);
 * 
 * // Run model with inputs
 * const model = await AutoModel.from_pretrained('Xenova/mms-300m');
 * const output = await model(inputs);
 * // {
 * //   last_hidden_state: Tensor {
 * //     dims: [ 1, 1144, 1024 ],
 * //     type: 'float32',
 * //     data: Float32Array(1171456) [ ... ],
 * //     size: 1171456
 * //   }
 * // }
 * ```
 */
class Wav2Vec2Model extends Wav2Vec2PreTrainedModel { }

class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    async _call(model_inputs) {
        return new CausalLMOutput(await super._call(model_inputs));
    }
}

class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * Wav2Vec2 Model with a frame classification head on top for tasks like Speaker Diarization.
 */
class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// UniSpeech models
class UniSpeechPreTrainedModel extends PreTrainedModel { };

/**
 * The bare UniSpeech Model transformer outputting raw hidden-states without any specific head on top.
 */
class UniSpeechModel extends UniSpeechPreTrainedModel { }

/**
 * UniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
 */
class UniSpeechForCTC extends UniSpeechPreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    async _call(model_inputs) {
        return new CausalLMOutput(await super._call(model_inputs));
    }
}

/**
 * UniSpeech Model with a sequence classification head on top (a linear layer over the pooled output).
 */
class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// UniSpeechSat models
class UniSpeechSatPreTrainedModel extends PreTrainedModel { };

/**
 * The bare UniSpeechSat Model transformer outputting raw hidden-states without any specific head on top.
 */
class UniSpeechSatModel extends UniSpeechSatPreTrainedModel { }

/**
 * UniSpeechSat Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
 */
class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    async _call(model_inputs) {
        return new CausalLMOutput(await super._call(model_inputs));
    }
}

/**
 * UniSpeechSat Model with a sequence classification head on top (a linear layer over the pooled output).
 */
class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * UniSpeechSat Model with a frame classification head on top for tasks like Speaker Diarization.
 */
class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Wav2Vec2Bert models
class Wav2Vec2BertPreTrainedModel extends PreTrainedModel { };

/**
 * The bare Wav2Vec2Bert Model transformer outputting raw hidden-states without any specific head on top.
 */
class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel { }

/**
 * Wav2Vec2Bert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
 */
class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    async _call(model_inputs) {
        return new CausalLMOutput(await super._call(model_inputs));
    }
}

/**
 * Wav2Vec2Bert Model with a sequence classification head on top (a linear layer over the pooled output).
 */
class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Hubert models
class HubertPreTrainedModel extends PreTrainedModel { }

/**
 * The bare Hubert Model transformer outputting raw hidden-states without any specific head on top.
 * 
 * **Example:** Load and run a `HubertModel` for feature extraction.
 * 
 * ```javascript
 * import { AutoProcessor, AutoModel, read_audio } from '@xenova/transformers';
 * 
 * // Read and preprocess audio
 * const processor = await AutoProcessor.from_pretrained('Xenova/hubert-base-ls960');
 * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000);
 * const inputs = await processor(audio);
 * 
 * // Load and run model with inputs
 * const model = await AutoModel.from_pretrained('Xenova/hubert-base-ls960');
 * const output = await model(inputs);
 * // {
 * //   last_hidden_state: Tensor {
 * //     dims: [ 1, 549, 768 ],
 * //     type: 'float32',
 * //     data: Float32Array(421632) [0.0682469978928566, 0.08104046434164047, -0.4975186586380005, ...],
 * //     size: 421632
 * //   }
 * // }
 * ```
 */
class HubertModel extends Wav2Vec2PreTrainedModel { }

/**
 * Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
 */
class HubertForCTC extends Wav2Vec2PreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    async _call(model_inputs) {
        return new CausalLMOutput(await super._call(model_inputs));
    }
}

/**
 * Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting.
 */
class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// WavLM models
/**
 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
 */
class WavLMPreTrainedModel extends PreTrainedModel { };

/**
 * The bare WavLM Model transformer outputting raw hidden-states without any specific head on top.
 * 
 * **Example:** Load and run a `WavLMModel` for feature extraction.
 * 
 * ```javascript
 * import { AutoProcessor, AutoModel, read_audio } from '@xenova/transformers';
 * 
 * // Read and preprocess audio
 * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base');
 * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000);
 * const inputs = await processor(audio);
 * 
 * // Run model with inputs
 * const model = await AutoModel.from_pretrained('Xenova/wavlm-base');
 * const output = await model(inputs);
 * // {
 * //   last_hidden_state: Tensor {
 * //     dims: [ 1, 549, 768 ],
 * //     type: 'float32',
 * //     data: Float32Array(421632) [-0.349443256855011, -0.39341306686401367,  0.022836603224277496, ...],
 * //     size: 421632
 * //   }
 * // }
 * ```
 */
class WavLMModel extends WavLMPreTrainedModel { }

/**
 * WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
 */
class WavLMForCTC extends WavLMPreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    async _call(model_inputs) {
        return new CausalLMOutput(await super._call(model_inputs));
    }
}

/**
 * WavLM Model with a sequence classification head on top (a linear layer over the pooled output).
 */
class WavLMForSequenceClassification extends WavLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}

/**
 * WavLM Model with an XVector feature extraction head on top for tasks like Speaker Verification.
 * 
 * **Example:** Extract speaker embeddings with `WavLMForXVector`.
 * ```javascript
 * import { AutoProcessor, AutoModel, read_audio } from '@xenova/transformers';
 * 
 * // Read and preprocess audio
 * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sv');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
 * const audio = await read_audio(url, 16000);
 * const inputs = await processor(audio);
 * 
 * // Run model with inputs
 * const model = await AutoModel.from_pretrained('Xenova/wavlm-base-plus-sv');
 * const outputs = await model(inputs);
 * // {
 * //   logits: Tensor {
 * //     dims: [ 1, 512 ],
 * //     type: 'float32',
 * //     data: Float32Array(512) [0.5847219228744507, ...],
 * //     size: 512
 * //   },
 * //   embeddings: Tensor {
 * //     dims: [ 1, 512 ],
 * //     type: 'float32',
 * //     data: Float32Array(512) [-0.09079201519489288, ...],
 * //     size: 512
 * //   }
 * // }
 * ```
 */
class WavLMForXVector extends WavLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<XVectorOutput>} An object containing the model's output logits and speaker embeddings.
     */
    async _call(model_inputs) {
        return new XVectorOutput(await super._call(model_inputs));
    }
}

/**
 * WavLM Model with a frame classification head on top for tasks like Speaker Diarization.
 * 
 * **Example:** Perform speaker diarization with `WavLMForAudioFrameClassification`.
 * ```javascript
 * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@xenova/transformers';
 * 
 * // Read and preprocess audio
 * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sd');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
 * const audio = await read_audio(url, 16000);
 * const inputs = await processor(audio);
 * 
 * // Run model with inputs
 * const model = await AutoModelForAudioFrameClassification.from_pretrained('Xenova/wavlm-base-plus-sd');
 * const { logits } = await model(inputs);
 * // {
 * //   logits: Tensor {
 * //     dims: [ 1, 549, 2 ],  // [batch_size, num_frames, num_speakers]
 * //     type: 'float32',
 * //     data: Float32Array(1098) [-3.5301010608673096, ...],
 * //     size: 1098
 * //   }
 * // }
 * 
 * const labels = logits[0].sigmoid().tolist().map(
 *     frames => frames.map(speaker => speaker > 0.5 ? 1 : 0)
 * );
 * console.log(labels); // labels is a one-hot array of shape (num_frames, num_speakers)
 * // [
 * //     [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
 * //     [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
 * //     [0, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1],
 * //     ...
 * // ]
 * ```
 */
class WavLMForAudioFrameClassification extends WavLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    async _call(model_inputs) {
        return new TokenClassifierOutput(await super._call(model_inputs));
    }
}

//////////////////////////////////////////////////
// SpeechT5 models
/**
 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
 */
class SpeechT5PreTrainedModel extends PreTrainedModel { };

/**
 * The bare SpeechT5 Encoder-Decoder Model outputting raw hidden-states without any specific pre- or post-nets.
 */
class SpeechT5Model extends SpeechT5PreTrainedModel { };

/**
 * SpeechT5 Model with a speech encoder and a text decoder.
 * 
 * **Example:** Generate speech from text with `SpeechT5ForSpeechToText`.
 * ```javascript
 * import { AutoTokenizer, AutoProcessor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, Tensor } from '@xenova/transformers';
 * 
 * // Load the tokenizer and processor
 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/speecht5_tts');
 * const processor = await AutoProcessor.from_pretrained('Xenova/speecht5_tts');
 * 
 * // Load the models
 * // NOTE: We use the unquantized versions as they are more accurate
 * const model = await SpeechT5ForTextToSpeech.from_pretrained('Xenova/speecht5_tts', { quantized: false });
 * const vocoder = await SpeechT5HifiGan.from_pretrained('Xenova/speecht5_hifigan', { quantized: false });
 * 
 * // Load speaker embeddings from URL
 * const speaker_embeddings_data = new Float32Array(
 *     await (await fetch('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin')).arrayBuffer()
 * );
 * const speaker_embeddings = new Tensor(
 *     'float32',
 *     speaker_embeddings_data,
 *     [1, speaker_embeddings_data.length]
 * )
 * 
 * // Run tokenization
 * const { input_ids } = tokenizer('Hello, my dog is cute');
 * 
 * // Generate waveform
 * const { waveform } = await model.generate_speech(input_ids, speaker_embeddings, { vocoder });
 * console.log(waveform)
 * // Tensor {
 * //   dims: [ 26112 ],
 * //   type: 'float32',
 * //   size: 26112,
 * //   data: Float32Array(26112) [ -0.00043630177970044315, -0.00018082228780258447, ... ],
 * // }
 * ```
 */
class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel { }

/**
 * SpeechT5 Model with a text encoder and a speech decoder.
 */
class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel {

    /**
     * Creates a new instance of the `SpeechT5ForTextToSpeech` class.
     * @param {Object} config The model configuration.
     * @param {any} session session for the model.
     * @param {any} decoder_merged_session session for the decoder.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, decoder_merged_session, generation_config) {
        super(config, session);
        this.decoder_merged_session = decoder_merged_session;
        this.generation_config = generation_config;

        this.num_decoder_layers = this.config.decoder_layers;
        this.num_decoder_heads = this.config.decoder_attention_heads;
        this.decoder_dim_kv = this.config.hidden_size / this.num_decoder_heads;

        this.num_encoder_layers = this.config.encoder_layers;
        this.num_encoder_heads = this.config.encoder_attention_heads;
        this.encoder_dim_kv = this.config.hidden_size / this.num_encoder_heads;
    }

    /**
     * @typedef {Object} SpeechOutput
     * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape
     * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided
     * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.
     * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape
     * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.
     */

    /**
     * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder.
     * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary.
     * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings.
     * @param {Object} options Optional parameters for generating speech.
     * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value.
     * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence.
     * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence.
     * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram.
     * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers.
     * @returns {Promise<SpeechOutput>} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors.
     */
    async generate_speech(input_values, speaker_embeddings, {
        threshold = 0.5,
        minlenratio = 0.0,
        maxlenratio = 20.0,
        vocoder = null,
        // output_cross_attentions = false, // TODO add
    } = {}) {

        const model_inputs = {
            input_ids: input_values
        }

        const { encoder_outputs, encoder_attention_mask } = await encoderForward(this, model_inputs);

        const r = encoder_outputs.dims[1] / this.config.reduction_factor;
        const maxlen = Math.floor(r * maxlenratio);
        const minlen = Math.floor(r * minlenratio);

        const num_mel_bins = this.config.num_mel_bins;

        let spectrogramParts = [];
        let past_key_values = null;
        let decoder_outputs = null;
        let idx = 0;

        while (true) {
            ++idx;

            const use_cache_branch = boolTensor(!!decoder_outputs);
            let output_sequence;
            if (decoder_outputs) {
                output_sequence = decoder_outputs.output_sequence_out;
            } else {
                output_sequence = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor(
                    'float32',
                    new Float32Array(num_mel_bins),
                    [1, 1, num_mel_bins],
                )
            }
            let decoderFeeds = {
                use_cache_branch,
                output_sequence,
                encoder_attention_mask: encoder_attention_mask,
                speaker_embeddings: speaker_embeddings,
                encoder_hidden_states: encoder_outputs,
            };

            this.addPastKeyValues(decoderFeeds, past_key_values);
            decoder_outputs = await sessionRun(this.decoder_merged_session, decoderFeeds);
            past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values);

            const { prob, spectrum } = decoder_outputs;
            spectrogramParts.push(spectrum);

            if (idx >= minlen && (
                // Finished when stop token or maximum length is reached.
                Array.from(prob.data).filter(p => p >= threshold).length > 0 || idx >= maxlen
            )) {
                break;
            }
        }

        const spectrogram = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.cat)(spectrogramParts);
        const { waveform } = await sessionRun(vocoder.session, { spectrogram });

        return {
            spectrogram,
            waveform,
            // cross_attentions: null, // TODO add
        }
    }
}

/**
 * HiFi-GAN vocoder.
 * 
 * See [SpeechT5ForSpeechToText](./models#module_models.SpeechT5ForSpeechToText) for example usage.
 */
class SpeechT5HifiGan extends PreTrainedModel {
    main_input_name = 'spectrogram';
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// TrOCR models
class TrOCRPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `TrOCRPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id;

        this.num_encoder_layers = this.num_decoder_layers = this.config.decoder_layers;
        this.num_encoder_heads = this.num_decoder_heads = this.config.decoder_attention_heads;
        this.encoder_dim_kv = this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
    }
}

/**
 * The TrOCR Decoder with a language modeling head.
 */
class TrOCRForCausalLM extends TrOCRPreTrainedModel { }

//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Mistral models
/**
 * The bare Mistral Model outputting raw hidden-states without any specific head on top.
 */
class MistralPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `MistralPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.num_key_value_heads;
        this.num_layers = this.config.num_hidden_layers;
        this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
    }
}

class MistralModel extends MistralPreTrainedModel { }

class MistralForCausalLM extends MistralPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Starcoder2 models
/**
 * The bare Starcoder2 Model outputting raw hidden-states without any specific head on top.
 */
class Starcoder2PreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `Starcoder2PreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.num_key_value_heads;
        this.num_layers = this.config.num_hidden_layers;
        this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
    }
}

class Starcoder2Model extends Starcoder2PreTrainedModel { }

class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// Falcon models
/**
 * The bare Falcon Model outputting raw hidden-states without any specific head on top.
 */
class FalconPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `FalconPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.num_attention_heads;
        this.num_layers = this.config.num_hidden_layers;
        this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
    }
}

class FalconModel extends FalconPreTrainedModel { }

class FalconForCausalLM extends FalconPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// CLAP models
class ClapPreTrainedModel extends PreTrainedModel { }

class ClapModel extends ClapPreTrainedModel { }

/**
 * CLAP Text Model with a projection layer on top (a linear layer on top of the pooled output).
 * 
 * **Example:** Compute text embeddings with `ClapTextModelWithProjection`.
 * 
 * ```javascript
 * import { AutoTokenizer, ClapTextModelWithProjection } from '@xenova/transformers';
 * 
 * // Load tokenizer and text model
 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clap-htsat-unfused');
 * const text_model = await ClapTextModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused');
 * 
 * // Run tokenization
 * const texts = ['a sound of a cat', 'a sound of a dog'];
 * const text_inputs = tokenizer(texts, { padding: true, truncation: true });
 * 
 * // Compute embeddings
 * const { text_embeds } = await text_model(text_inputs);
 * // Tensor {
 * //   dims: [ 2, 512 ],
 * //   type: 'float32',
 * //   data: Float32Array(1024) [ ... ],
 * //   size: 1024
 * // }
 * ```
 */
class ClapTextModelWithProjection extends ClapPreTrainedModel {

    /** @type {PreTrainedModel.from_pretrained} */
    static async from_pretrained(pretrained_model_name_or_path, options = {}) {
        // Update default model file name if not provided
        options.model_file_name ??= 'text_model';
        return super.from_pretrained(pretrained_model_name_or_path, options);
    }
}

/**
 * CLAP Audio Model with a projection layer on top (a linear layer on top of the pooled output).
 * 
 * **Example:** Compute audio embeddings with `ClapAudioModelWithProjection`.
 * 
 * ```javascript
 * import { AutoProcessor, ClapAudioModelWithProjection, read_audio } from '@xenova/transformers';
 * 
 * // Load processor and audio model
 * const processor = await AutoProcessor.from_pretrained('Xenova/clap-htsat-unfused');
 * const audio_model = await ClapAudioModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused');
 * 
 * // Read audio and run processor
 * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav');
 * const audio_inputs = await processor(audio);
 * 
 * // Compute embeddings
 * const { audio_embeds } = await audio_model(audio_inputs);
 * // Tensor {
 * //   dims: [ 1, 512 ],
 * //   type: 'float32',
 * //   data: Float32Array(512) [ ... ],
 * //   size: 512
 * // }
 * ```
 */
class ClapAudioModelWithProjection extends ClapPreTrainedModel {
    /** @type {PreTrainedModel.from_pretrained} */
    static async from_pretrained(pretrained_model_name_or_path, options = {}) {
        // Update default model file name if not provided
        options.model_file_name ??= 'audio_model';
        return super.from_pretrained(pretrained_model_name_or_path, options);
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// VITS models
class VitsPreTrainedModel extends PreTrainedModel { }

/**
 * The complete VITS model, for text-to-speech synthesis.
 * 
 * **Example:** Generate speech from text with `VitsModel`.
 * ```javascript
 * import { AutoTokenizer, VitsModel } from '@xenova/transformers';
 * 
 * // Load the tokenizer and model
 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/mms-tts-eng');
 * const model = await VitsModel.from_pretrained('Xenova/mms-tts-eng');
 * 
 * // Run tokenization
 * const inputs = tokenizer('I love transformers');
 * 
 * // Generate waveform
 * const { waveform } = await model(inputs);
 * // Tensor {
 * //   dims: [ 1, 35328 ],
 * //   type: 'float32',
 * //   data: Float32Array(35328) [ ... ],
 * //   size: 35328,
 * // }
 * ```
 */
class VitsModel extends VitsPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<VitsModelOutput>} The outputs for the VITS model.
     */
    async _call(model_inputs) {
        return new VitsModelOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Segformer models
class SegformerPreTrainedModel extends PreTrainedModel { }

/**
 * The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.
 */
class SegformerModel extends SegformerPreTrainedModel { }

/**
 * SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden states) e.g. for ImageNet.
 */
class SegformerForImageClassification extends SegformerPreTrainedModel { }

/**
 * SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes.
 */
class SegformerForSemanticSegmentation extends SegformerPreTrainedModel { }

//////////////////////////////////////////////////

//////////////////////////////////////////////////
// StableLm models
class StableLmPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `StableLmPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config, session, generation_config) {
        super(config, session);
        this.generation_config = generation_config;

        // config doesn't contain pad_token_id, so we assume it is the eos_token_id
        this.config.pad_token_id = this.config.eos_token_id

        this.num_heads = this.config.num_attention_heads;
        this.num_layers = this.config.num_hidden_layers;
        this.dim_kv = this.config.hidden_size / this.num_heads;
    }
}

/**
 * The bare StableLm Model transformer outputting raw hidden-states without any specific head on top.
 */
class StableLmModel extends StableLmPreTrainedModel { }

/**
 * StableLm Model with a `language modeling` head on top for Causal Language Modeling (with past).
 */
class StableLmForCausalLM extends StableLmPreTrainedModel { }
//////////////////////////////////////////////////


//////////////////////////////////////////////////
class EfficientNetPreTrainedModel extends PreTrainedModel { }

/**
 * The bare EfficientNet model outputting raw features without any specific head on top.
 */
class EfficientNetModel extends EfficientNetPreTrainedModel { }

/**
 * EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features).
 */
class EfficientNetForImageClassification extends EfficientNetPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    async _call(model_inputs) {
        return new SequenceClassifierOutput(await super._call(model_inputs));
    }
}
//////////////////////////////////////////////////


//////////////////////////////////////////////////
// AutoModels, used to simplify construction of PreTrainedModels
// (uses config to instantiate correct class)

/**
 * Base class of all AutoModels. Contains the `from_pretrained` function
 * which is used to instantiate pretrained models.
 */
class PretrainedMixin {
    /**
     * Mapping from model type to model class.
     * @type {Map<string, Object>[]}
     */
    static MODEL_CLASS_MAPPINGS = null;

    /**
     * Whether to attempt to instantiate the base class (`PretrainedModel`) if 
     * the model type is not found in the mapping.
     */
    static BASE_IF_FAIL = false;


    /** @type {PreTrainedModel.from_pretrained} */
    static async from_pretrained(pretrained_model_name_or_path, {
        quantized = true,
        progress_callback = null,
        config = null,
        cache_dir = null,
        local_files_only = false,
        revision = 'main',
        model_file_name = null,
    } = {}) {

        let options = {
            quantized,
            progress_callback,
            config,
            cache_dir,
            local_files_only,
            revision,
            model_file_name,
        }
        config = await _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options);
        if (!options.config) {
            // If no config was passed, reuse this config for future processing
            options.config = config;
        }

        if (!this.MODEL_CLASS_MAPPINGS) {
            throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: " + this.name);
        }

        for (let MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) {
            const modelInfo = MODEL_CLASS_MAPPING.get(config.model_type);
            if (!modelInfo) {
                continue; // Item not found in this mapping
            }
            return await modelInfo[1].from_pretrained(pretrained_model_name_or_path, options);
        }

        if (this.BASE_IF_FAIL) {
            console.warn(`Unknown model class "${config.model_type}", attempting to construct from base class.`);
            return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options);
        } else {
            throw Error(`Unsupported model type: ${config.model_type}`)
        }
    }
}

const MODEL_MAPPING_NAMES_ENCODER_ONLY = new Map([
    ['bert', ['BertModel', BertModel]],
    ['nomic_bert', ['NomicBertModel', NomicBertModel]],
    ['roformer', ['RoFormerModel', RoFormerModel]],
    ['electra', ['ElectraModel', ElectraModel]],
    ['esm', ['EsmModel', EsmModel]],
    ['convbert', ['ConvBertModel', ConvBertModel]],
    ['camembert', ['CamembertModel', CamembertModel]],
    ['deberta', ['DebertaModel', DebertaModel]],
    ['deberta-v2', ['DebertaV2Model', DebertaV2Model]],
    ['mpnet', ['MPNetModel', MPNetModel]],
    ['albert', ['AlbertModel', AlbertModel]],
    ['distilbert', ['DistilBertModel', DistilBertModel]],
    ['roberta', ['RobertaModel', RobertaModel]],
    ['xlm', ['XLMModel', XLMModel]],
    ['xlm-roberta', ['XLMRobertaModel', XLMRobertaModel]],
    ['clap', ['ClapModel', ClapModel]],
    ['clip', ['CLIPModel', CLIPModel]],
    ['clipseg', ['CLIPSegModel', CLIPSegModel]],
    ['chinese_clip', ['ChineseCLIPModel', ChineseCLIPModel]],
    ['siglip', ['SiglipModel', SiglipModel]],
    ['mobilebert', ['MobileBertModel', MobileBertModel]],
    ['squeezebert', ['SqueezeBertModel', SqueezeBertModel]],
    ['wav2vec2', ['Wav2Vec2Model', Wav2Vec2Model]],
    ['wav2vec2-bert', ['Wav2Vec2BertModel', Wav2Vec2BertModel]],
    ['unispeech', ['UniSpeechModel', UniSpeechModel]],
    ['unispeech-sat', ['UniSpeechSatModel', UniSpeechSatModel]],
    ['hubert', ['HubertModel', HubertModel]],
    ['wavlm', ['WavLMModel', WavLMModel]],
    ['audio-spectrogram-transformer', ['ASTModel', ASTModel]],
    ['vits', ['VitsModel', VitsModel]],

    ['detr', ['DetrModel', DetrModel]],
    ['table-transformer', ['TableTransformerModel', TableTransformerModel]],
    ['vit', ['ViTModel', ViTModel]],
    ['fastvit', ['FastViTModel', FastViTModel]],
    ['mobilevit', ['MobileViTModel', MobileViTModel]],
    ['mobilevitv2', ['MobileViTV2Model', MobileViTV2Model]],
    ['owlvit', ['OwlViTModel', OwlViTModel]],
    ['owlv2', ['Owlv2Model', Owlv2Model]],
    ['beit', ['BeitModel', BeitModel]],
    ['deit', ['DeiTModel', DeiTModel]],
    ['convnext', ['ConvNextModel', ConvNextModel]],
    ['convnextv2', ['ConvNextV2Model', ConvNextV2Model]],
    ['dinov2', ['Dinov2Model', Dinov2Model]],
    ['resnet', ['ResNetModel', ResNetModel]],
    ['swin', ['SwinModel', SwinModel]],
    ['swin2sr', ['Swin2SRModel', Swin2SRModel]],
    ['donut-swin', ['DonutSwinModel', DonutSwinModel]],
    ['yolos', ['YolosModel', YolosModel]],
    ['dpt', ['DPTModel', DPTModel]],
    ['glpn', ['GLPNModel', GLPNModel]],

    ['hifigan', ['SpeechT5HifiGan', SpeechT5HifiGan]],
    ['efficientnet', ['EfficientNetModel', EfficientNetModel]],

]);

const MODEL_MAPPING_NAMES_ENCODER_DECODER = new Map([
    ['t5', ['T5Model', T5Model]],
    ['longt5', ['LongT5Model', LongT5Model]],
    ['mt5', ['MT5Model', MT5Model]],
    ['bart', ['BartModel', BartModel]],
    ['mbart', ['MBartModel', MBartModel]],
    ['marian', ['MarianModel', MarianModel]],
    ['whisper', ['WhisperModel', WhisperModel]],
    ['m2m_100', ['M2M100Model', M2M100Model]],
    ['blenderbot', ['BlenderbotModel', BlenderbotModel]],
    ['blenderbot-small', ['BlenderbotSmallModel', BlenderbotSmallModel]],
]);


const MODEL_MAPPING_NAMES_DECODER_ONLY = new Map([
    ['bloom', ['BloomModel', BloomModel]],
    ['gpt2', ['GPT2Model', GPT2Model]],
    ['gptj', ['GPTJModel', GPTJModel]],
    ['gpt_bigcode', ['GPTBigCodeModel', GPTBigCodeModel]],
    ['gpt_neo', ['GPTNeoModel', GPTNeoModel]],
    ['gpt_neox', ['GPTNeoXModel', GPTNeoXModel]],
    ['codegen', ['CodeGenModel', CodeGenModel]],
    ['llama', ['LlamaModel', LlamaModel]],
    ['qwen2', ['Qwen2Model', Qwen2Model]],
    ['phi', ['PhiModel', PhiModel]],
    ['mpt', ['MptModel', MptModel]],
    ['opt', ['OPTModel', OPTModel]],
    ['mistral', ['MistralModel', MistralModel]],
    ['starcoder2', ['Starcoder2Model', Starcoder2Model]],
    ['falcon', ['FalconModel', FalconModel]],
]);

const MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = new Map([
    ['speecht5', ['SpeechT5ForSpeechToText', SpeechT5ForSpeechToText]],
    ['whisper', ['WhisperForConditionalGeneration', WhisperForConditionalGeneration]],
]);

const MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = new Map([
    ['speecht5', ['SpeechT5ForTextToSpeech', SpeechT5ForTextToSpeech]],
]);

const MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = new Map([
    ['vits', ['VitsModel', VitsModel]],
]);

const MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = new Map([
    ['bert', ['BertForSequenceClassification', BertForSequenceClassification]],
    ['roformer', ['RoFormerForSequenceClassification', RoFormerForSequenceClassification]],
    ['electra', ['ElectraForSequenceClassification', ElectraForSequenceClassification]],
    ['esm', ['EsmForSequenceClassification', EsmForSequenceClassification]],
    ['convbert', ['ConvBertForSequenceClassification', ConvBertForSequenceClassification]],
    ['camembert', ['CamembertForSequenceClassification', CamembertForSequenceClassification]],
    ['deberta', ['DebertaForSequenceClassification', DebertaForSequenceClassification]],
    ['deberta-v2', ['DebertaV2ForSequenceClassification', DebertaV2ForSequenceClassification]],
    ['mpnet', ['MPNetForSequenceClassification', MPNetForSequenceClassification]],
    ['albert', ['AlbertForSequenceClassification', AlbertForSequenceClassification]],
    ['distilbert', ['DistilBertForSequenceClassification', DistilBertForSequenceClassification]],
    ['roberta', ['RobertaForSequenceClassification', RobertaForSequenceClassification]],
    ['xlm', ['XLMForSequenceClassification', XLMForSequenceClassification]],
    ['xlm-roberta', ['XLMRobertaForSequenceClassification', XLMRobertaForSequenceClassification]],
    ['bart', ['BartForSequenceClassification', BartForSequenceClassification]],
    ['mbart', ['MBartForSequenceClassification', MBartForSequenceClassification]],
    ['mobilebert', ['MobileBertForSequenceClassification', MobileBertForSequenceClassification]],
    ['squeezebert', ['SqueezeBertForSequenceClassification', SqueezeBertForSequenceClassification]],
]);

const MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = new Map([
    ['bert', ['BertForTokenClassification', BertForTokenClassification]],
    ['roformer', ['RoFormerForTokenClassification', RoFormerForTokenClassification]],
    ['electra', ['ElectraForTokenClassification', ElectraForTokenClassification]],
    ['esm', ['EsmForTokenClassification', EsmForTokenClassification]],
    ['convbert', ['ConvBertForTokenClassification', ConvBertForTokenClassification]],
    ['camembert', ['CamembertForTokenClassification', CamembertForTokenClassification]],
    ['deberta', ['DebertaForTokenClassification', DebertaForTokenClassification]],
    ['deberta-v2', ['DebertaV2ForTokenClassification', DebertaV2ForTokenClassification]],
    ['mpnet', ['MPNetForTokenClassification', MPNetForTokenClassification]],
    ['distilbert', ['DistilBertForTokenClassification', DistilBertForTokenClassification]],
    ['roberta', ['RobertaForTokenClassification', RobertaForTokenClassification]],
    ['xlm', ['XLMForTokenClassification', XLMForTokenClassification]],
    ['xlm-roberta', ['XLMRobertaForTokenClassification', XLMRobertaForTokenClassification]],
]);

const MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = new Map([
    ['t5', ['T5ForConditionalGeneration', T5ForConditionalGeneration]],
    ['longt5', ['LongT5ForConditionalGeneration', LongT5ForConditionalGeneration]],
    ['mt5', ['MT5ForConditionalGeneration', MT5ForConditionalGeneration]],
    ['bart', ['BartForConditionalGeneration', BartForConditionalGeneration]],
    ['mbart', ['MBartForConditionalGeneration', MBartForConditionalGeneration]],
    ['marian', ['MarianMTModel', MarianMTModel]],
    ['m2m_100', ['M2M100ForConditionalGeneration', M2M100ForConditionalGeneration]],
    ['blenderbot', ['BlenderbotForConditionalGeneration', BlenderbotForConditionalGeneration]],
    ['blenderbot-small', ['BlenderbotSmallForConditionalGeneration', BlenderbotSmallForConditionalGeneration]],
]);

const MODEL_WITH_LM_HEAD_MAPPING_NAMES = new Map([
    ['bloom', ['BloomForCausalLM', BloomForCausalLM]],
    ['gpt2', ['GPT2LMHeadModel', GPT2LMHeadModel]],
    ['gptj', ['GPTJForCausalLM', GPTJForCausalLM]],
    ['gpt_bigcode', ['GPTBigCodeForCausalLM', GPTBigCodeForCausalLM]],
    ['gpt_neo', ['GPTNeoForCausalLM', GPTNeoForCausalLM]],
    ['gpt_neox', ['GPTNeoXForCausalLM', GPTNeoXForCausalLM]],
    ['codegen', ['CodeGenForCausalLM', CodeGenForCausalLM]],
    ['llama', ['LlamaForCausalLM', LlamaForCausalLM]],
    ['qwen2', ['Qwen2ForCausalLM', Qwen2ForCausalLM]],
    ['phi', ['PhiForCausalLM', PhiForCausalLM]],
    ['mpt', ['MptForCausalLM', MptForCausalLM]],
    ['opt', ['OPTForCausalLM', OPTForCausalLM]],
    ['mbart', ['MBartForCausalLM', MBartForCausalLM]],
    ['mistral', ['MistralForCausalLM', MistralForCausalLM]],
    ['starcoder2', ['Starcoder2ForCausalLM', Starcoder2ForCausalLM]],
    ['falcon', ['FalconForCausalLM', FalconForCausalLM]],
    ['trocr', ['TrOCRForCausalLM', TrOCRForCausalLM]],
    ['stablelm', ['StableLmForCausalLM', StableLmForCausalLM]],
]);

const MODEL_FOR_MASKED_LM_MAPPING_NAMES = new Map([
    ['bert', ['BertForMaskedLM', BertForMaskedLM]],
    ['roformer', ['RoFormerForMaskedLM', RoFormerForMaskedLM]],
    ['electra', ['ElectraForMaskedLM', ElectraForMaskedLM]],
    ['esm', ['EsmForMaskedLM', EsmForMaskedLM]],
    ['convbert', ['ConvBertForMaskedLM', ConvBertForMaskedLM]],
    ['camembert', ['CamembertForMaskedLM', CamembertForMaskedLM]],
    ['deberta', ['DebertaForMaskedLM', DebertaForMaskedLM]],
    ['deberta-v2', ['DebertaV2ForMaskedLM', DebertaV2ForMaskedLM]],
    ['mpnet', ['MPNetForMaskedLM', MPNetForMaskedLM]],
    ['albert', ['AlbertForMaskedLM', AlbertForMaskedLM]],
    ['distilbert', ['DistilBertForMaskedLM', DistilBertForMaskedLM]],
    ['roberta', ['RobertaForMaskedLM', RobertaForMaskedLM]],
    ['xlm', ['XLMWithLMHeadModel', XLMWithLMHeadModel]],
    ['xlm-roberta', ['XLMRobertaForMaskedLM', XLMRobertaForMaskedLM]],
    ['mobilebert', ['MobileBertForMaskedLM', MobileBertForMaskedLM]],
    ['squeezebert', ['SqueezeBertForMaskedLM', SqueezeBertForMaskedLM]],
]);

const MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = new Map([
    ['bert', ['BertForQuestionAnswering', BertForQuestionAnswering]],
    ['roformer', ['RoFormerForQuestionAnswering', RoFormerForQuestionAnswering]],
    ['electra', ['ElectraForQuestionAnswering', ElectraForQuestionAnswering]],
    ['convbert', ['ConvBertForQuestionAnswering', ConvBertForQuestionAnswering]],
    ['camembert', ['CamembertForQuestionAnswering', CamembertForQuestionAnswering]],
    ['deberta', ['DebertaForQuestionAnswering', DebertaForQuestionAnswering]],
    ['deberta-v2', ['DebertaV2ForQuestionAnswering', DebertaV2ForQuestionAnswering]],
    ['mpnet', ['MPNetForQuestionAnswering', MPNetForQuestionAnswering]],
    ['albert', ['AlbertForQuestionAnswering', AlbertForQuestionAnswering]],
    ['distilbert', ['DistilBertForQuestionAnswering', DistilBertForQuestionAnswering]],
    ['roberta', ['RobertaForQuestionAnswering', RobertaForQuestionAnswering]],
    ['xlm', ['XLMForQuestionAnswering', XLMForQuestionAnswering]],
    ['xlm-roberta', ['XLMRobertaForQuestionAnswering', XLMRobertaForQuestionAnswering]],
    ['mobilebert', ['MobileBertForQuestionAnswering', MobileBertForQuestionAnswering]],
    ['squeezebert', ['SqueezeBertForQuestionAnswering', SqueezeBertForQuestionAnswering]],
]);

const MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = new Map([
    ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]],
]);

const MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = new Map([
    ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]],
]);

const MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = new Map([
    ['vit', ['ViTForImageClassification', ViTForImageClassification]],
    ['fastvit', ['FastViTForImageClassification', FastViTForImageClassification]],
    ['mobilevit', ['MobileViTForImageClassification', MobileViTForImageClassification]],
    ['mobilevitv2', ['MobileViTV2ForImageClassification', MobileViTV2ForImageClassification]],
    ['beit', ['BeitForImageClassification', BeitForImageClassification]],
    ['deit', ['DeiTForImageClassification', DeiTForImageClassification]],
    ['convnext', ['ConvNextForImageClassification', ConvNextForImageClassification]],
    ['convnextv2', ['ConvNextV2ForImageClassification', ConvNextV2ForImageClassification]],
    ['dinov2', ['Dinov2ForImageClassification', Dinov2ForImageClassification]],
    ['resnet', ['ResNetForImageClassification', ResNetForImageClassification]],
    ['swin', ['SwinForImageClassification', SwinForImageClassification]],
    ['segformer', ['SegformerForImageClassification', SegformerForImageClassification]],
    ['efficientnet', ['EfficientNetForImageClassification', EfficientNetForImageClassification]],
]);

const MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = new Map([
    ['detr', ['DetrForObjectDetection', DetrForObjectDetection]],
    ['table-transformer', ['TableTransformerForObjectDetection', TableTransformerForObjectDetection]],
    ['yolos', ['YolosForObjectDetection', YolosForObjectDetection]],
]);

const MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = new Map([
    ['owlvit', ['OwlViTForObjectDetection', OwlViTForObjectDetection]],
    ['owlv2', ['Owlv2ForObjectDetection', Owlv2ForObjectDetection]],
]);

const MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = new Map([
    ['detr', ['DetrForSegmentation', DetrForSegmentation]],
    ['clipseg', ['CLIPSegForImageSegmentation', CLIPSegForImageSegmentation]],
]);

const MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = new Map([
    ['segformer', ['SegformerForSemanticSegmentation', SegformerForSemanticSegmentation]],
]);

const MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = new Map([
    ['sam', ['SamModel', SamModel]],
]);

const MODEL_FOR_CTC_MAPPING_NAMES = new Map([
    ['wav2vec2', ['Wav2Vec2ForCTC', Wav2Vec2ForCTC]],
    ['wav2vec2-bert', ['Wav2Vec2BertForCTC', Wav2Vec2BertForCTC]],
    ['unispeech', ['UniSpeechForCTC', UniSpeechForCTC]],
    ['unispeech-sat', ['UniSpeechSatForCTC', UniSpeechSatForCTC]],
    ['wavlm', ['WavLMForCTC', WavLMForCTC]],
    ['hubert', ['HubertForCTC', HubertForCTC]],
]);

const MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = new Map([
    ['wav2vec2', ['Wav2Vec2ForSequenceClassification', Wav2Vec2ForSequenceClassification]],
    ['wav2vec2-bert', ['Wav2Vec2BertForSequenceClassification', Wav2Vec2BertForSequenceClassification]],
    ['unispeech', ['UniSpeechForSequenceClassification', UniSpeechForSequenceClassification]],
    ['unispeech-sat', ['UniSpeechSatForSequenceClassification', UniSpeechSatForSequenceClassification]],
    ['wavlm', ['WavLMForSequenceClassification', WavLMForSequenceClassification]],
    ['hubert', ['HubertForSequenceClassification', HubertForSequenceClassification]],
    ['audio-spectrogram-transformer', ['ASTForAudioClassification', ASTForAudioClassification]],
]);

const MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = new Map([
    ['wavlm', ['WavLMForXVector', WavLMForXVector]],
]);

const MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = new Map([
    ['unispeech-sat', ['UniSpeechSatForAudioFrameClassification', UniSpeechSatForAudioFrameClassification]],
    ['wavlm', ['WavLMForAudioFrameClassification', WavLMForAudioFrameClassification]],
    ['wav2vec2', ['Wav2Vec2ForAudioFrameClassification', Wav2Vec2ForAudioFrameClassification]],
]);

const MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = new Map([
    ['vitmatte', ['VitMatteForImageMatting', VitMatteForImageMatting]],
]);

const MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = new Map([
    ['swin2sr', ['Swin2SRForImageSuperResolution', Swin2SRForImageSuperResolution]],
])

const MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = new Map([
    ['dpt', ['DPTForDepthEstimation', DPTForDepthEstimation]],
    ['depth_anything', ['DepthAnythingForDepthEstimation', DepthAnythingForDepthEstimation]],
    ['glpn', ['GLPNForDepthEstimation', GLPNForDepthEstimation]],
])

// NOTE: This is custom to Transformers.js, and is necessary because certain models
// (e.g., CLIP) are split into vision and text components
const MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = new Map([
    ['clip', ['CLIPVisionModelWithProjection', CLIPVisionModelWithProjection]],
    ['siglip', ['SiglipVisionModel', SiglipVisionModel]],
])

const MODEL_CLASS_TYPE_MAPPING = [
    [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly],
    [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder],
    [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly],
    [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],
    [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],
    [MODEL_WITH_LM_HEAD_MAPPING_NAMES, MODEL_TYPES.DecoderOnly],
    [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq],
    [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration],
    [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],
    [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],

    // Custom:
    [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
];

for (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) {
    // @ts-ignore
    for (const [name, model] of mappings.values()) {
        MODEL_TYPE_MAPPING.set(name, type);
        MODEL_CLASS_TO_NAME_MAPPING.set(model, name);
        MODEL_NAME_TO_CLASS_MAPPING.set(name, model);
    }
}

const CUSTOM_MAPPING = [
    ['CLIPTextModelWithProjection', CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly],
    ['SiglipTextModel', SiglipTextModel, MODEL_TYPES.EncoderOnly],
    ['ClapTextModelWithProjection', ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly],
    ['ClapAudioModelWithProjection', ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly],
]
for (const [name, model, type] of CUSTOM_MAPPING) {
    MODEL_TYPE_MAPPING.set(name, type);
    MODEL_CLASS_TO_NAME_MAPPING.set(model, name);
    MODEL_NAME_TO_CLASS_MAPPING.set(name, model);
}


/**
 * Helper class which is used to instantiate pretrained models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModel.from_pretrained('bert-base-uncased');
 */
class AutoModel extends PretrainedMixin {
    /** @type {Map<string, Object>[]} */
    // @ts-ignore
    static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map(x => x[0]);
    static BASE_IF_FAIL = true;
}

/**
 * Helper class which is used to instantiate pretrained sequence classification models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForSequenceClassification.from_pretrained('distilbert-base-uncased-finetuned-sst-2-english');
 */
class AutoModelForSequenceClassification extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained token classification models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForTokenClassification.from_pretrained('Davlan/distilbert-base-multilingual-cased-ner-hrl');
 */
class AutoModelForTokenClassification extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained sequence-to-sequence models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForSeq2SeqLM.from_pretrained('t5-small');
 */
class AutoModelForSeq2SeqLM extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained sequence-to-sequence speech-to-text models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForSpeechSeq2Seq.from_pretrained('openai/whisper-tiny.en');
 */
class AutoModelForSpeechSeq2Seq extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained sequence-to-sequence text-to-spectrogram models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForTextToSpectrogram.from_pretrained('microsoft/speecht5_tts');
 */
class AutoModelForTextToSpectrogram extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained text-to-waveform models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForTextToSpectrogram.from_pretrained('facebook/mms-tts-eng');
 */
class AutoModelForTextToWaveform extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained causal language models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForCausalLM.from_pretrained('gpt2');
 */
class AutoModelForCausalLM extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_WITH_LM_HEAD_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained masked language models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForMaskedLM.from_pretrained('bert-base-uncased');
 */
class AutoModelForMaskedLM extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASKED_LM_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained question answering models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForQuestionAnswering.from_pretrained('distilbert-base-cased-distilled-squad');
 */
class AutoModelForQuestionAnswering extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained vision-to-sequence models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForVision2Seq.from_pretrained('nlpconnect/vit-gpt2-image-captioning');
 */
class AutoModelForVision2Seq extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained image classification models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForImageClassification.from_pretrained('google/vit-base-patch16-224');
 */
class AutoModelForImageClassification extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForImageSegmentation.from_pretrained('facebook/detr-resnet-50-panoptic');
 */
class AutoModelForImageSegmentation extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForSemanticSegmentation.from_pretrained('nvidia/segformer-b3-finetuned-cityscapes-1024-1024');
 */
class AutoModelForSemanticSegmentation extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES];
}

/**
 * Helper class which is used to instantiate pretrained object detection models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForObjectDetection.from_pretrained('facebook/detr-resnet-50');
 */
class AutoModelForObjectDetection extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES];
}

class AutoModelForZeroShotObjectDetection extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES];
}


/**
 * Helper class which is used to instantiate pretrained mask generation models with the `from_pretrained` function.
 * The chosen model class is determined by the type specified in the model config.
 * 
 * @example
 * let model = await AutoModelForMaskGeneration.from_pretrained('Xenova/sam-vit-base');
 */
class AutoModelForMaskGeneration extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES];
}

class AutoModelForCTC extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CTC_MAPPING_NAMES];
}

class AutoModelForAudioClassification extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES];
}

class AutoModelForXVector extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES];
}

class AutoModelForAudioFrameClassification extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES];
}

class AutoModelForDocumentQuestionAnswering extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES];
}

class AutoModelForImageMatting extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES];
}

class AutoModelForImageToImage extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES];
}

class AutoModelForDepthEstimation extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES];
}

class AutoModelForImageFeatureExtraction extends PretrainedMixin {
    static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES];
}

//////////////////////////////////////////////////

//////////////////////////////////////////////////
class Seq2SeqLMOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits The output logits of the model.
     * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model.
     * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model.
     * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
     * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
     */
    constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) {
        super();
        this.logits = logits;
        this.past_key_values = past_key_values;
        this.encoder_outputs = encoder_outputs;
        this.decoder_attentions = decoder_attentions;
        this.cross_attentions = cross_attentions;
    }
}

/**
 * Base class for outputs of sentence classification models.
 */
class SequenceClassifierOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax).
     */
    constructor({ logits }) {
        super();
        this.logits = logits;
    }
}

/**
 * Base class for outputs of XVector models.
 */
class XVectorOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`.
     * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`.
     */
    constructor({ logits, embeddings }) {
        super();
        this.logits = logits;
        this.embeddings = embeddings;
    }
}

/**
 * Base class for outputs of token classification models.
 */
class TokenClassifierOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Classification scores (before SoftMax).
     */
    constructor({ logits }) {
        super();
        this.logits = logits;
    }
}

/**
 * Base class for masked language models outputs.
 */
class MaskedLMOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
     */
    constructor({ logits }) {
        super();
        this.logits = logits;
    }
}

/**
 * Base class for outputs of question answering models.
 */
class QuestionAnsweringModelOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.start_logits Span-start scores (before SoftMax).
     * @param {Tensor} output.end_logits Span-end scores (before SoftMax).
     */
    constructor({ start_logits, end_logits }) {
        super();
        this.start_logits = start_logits;
        this.end_logits = end_logits;
    }
}


/**
 * Base class for causal language model (or autoregressive) outputs.
 */
class CausalLMOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).
     */
    constructor({ logits }) {
        super();
        this.logits = logits;
    }
}

/**
 * Base class for causal language model (or autoregressive) outputs.
 */
class CausalLMOutputWithPast extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).
     * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks)
     * that can be used (see `past_key_values` input) to speed up sequential decoding.
     */
    constructor({ logits, past_key_values }) {
        super();
        this.logits = logits;
        this.past_key_values = past_key_values;
    }
}

class ImageMattingOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`.
     */
    constructor({ alphas }) {
        super();
        this.alphas = alphas;
    }
}

/**
 * Describes the outputs for the VITS model.
 */
class VitsModelOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`.
     * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model.
     * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform.
     */
    constructor({ waveform, spectrogram }) {
        super();
        this.waveform = waveform;
        this.spectrogram = spectrogram;
    }
}


/***/ }),

/***/ "./src/pipelines.js":
/*!**************************!*\
  !*** ./src/pipelines.js ***!
  \**************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "AudioClassificationPipeline": () => (/* binding */ AudioClassificationPipeline),
/* harmony export */   "AutomaticSpeechRecognitionPipeline": () => (/* binding */ AutomaticSpeechRecognitionPipeline),
/* harmony export */   "DepthEstimationPipeline": () => (/* binding */ DepthEstimationPipeline),
/* harmony export */   "DocumentQuestionAnsweringPipeline": () => (/* binding */ DocumentQuestionAnsweringPipeline),
/* harmony export */   "FeatureExtractionPipeline": () => (/* binding */ FeatureExtractionPipeline),
/* harmony export */   "FillMaskPipeline": () => (/* binding */ FillMaskPipeline),
/* harmony export */   "ImageClassificationPipeline": () => (/* binding */ ImageClassificationPipeline),
/* harmony export */   "ImageFeatureExtractionPipeline": () => (/* binding */ ImageFeatureExtractionPipeline),
/* harmony export */   "ImageSegmentationPipeline": () => (/* binding */ ImageSegmentationPipeline),
/* harmony export */   "ImageToImagePipeline": () => (/* binding */ ImageToImagePipeline),
/* harmony export */   "ImageToTextPipeline": () => (/* binding */ ImageToTextPipeline),
/* harmony export */   "ObjectDetectionPipeline": () => (/* binding */ ObjectDetectionPipeline),
/* harmony export */   "Pipeline": () => (/* binding */ Pipeline),
/* harmony export */   "QuestionAnsweringPipeline": () => (/* binding */ QuestionAnsweringPipeline),
/* harmony export */   "SummarizationPipeline": () => (/* binding */ SummarizationPipeline),
/* harmony export */   "Text2TextGenerationPipeline": () => (/* binding */ Text2TextGenerationPipeline),
/* harmony export */   "TextClassificationPipeline": () => (/* binding */ TextClassificationPipeline),
/* harmony export */   "TextGenerationPipeline": () => (/* binding */ TextGenerationPipeline),
/* harmony export */   "TextToAudioPipeline": () => (/* binding */ TextToAudioPipeline),
/* harmony export */   "TokenClassificationPipeline": () => (/* binding */ TokenClassificationPipeline),
/* harmony export */   "TranslationPipeline": () => (/* binding */ TranslationPipeline),
/* harmony export */   "ZeroShotAudioClassificationPipeline": () => (/* binding */ ZeroShotAudioClassificationPipeline),
/* harmony export */   "ZeroShotClassificationPipeline": () => (/* binding */ ZeroShotClassificationPipeline),
/* harmony export */   "ZeroShotImageClassificationPipeline": () => (/* binding */ ZeroShotImageClassificationPipeline),
/* harmony export */   "ZeroShotObjectDetectionPipeline": () => (/* binding */ ZeroShotObjectDetectionPipeline),
/* harmony export */   "pipeline": () => (/* binding */ pipeline)
/* harmony export */ });
/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tokenizers.js */ "./src/tokenizers.js");
/* harmony import */ var _models_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./models.js */ "./src/models.js");
/* harmony import */ var _processors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./processors.js */ "./src/processors.js");
/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/core.js */ "./src/utils/core.js");
/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/maths.js */ "./src/utils/maths.js");
/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/audio.js */ "./src/utils/audio.js");
/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/tensor.js */ "./src/utils/tensor.js");
/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/image.js */ "./src/utils/image.js");
/**
 * @file Pipelines provide a high-level, easy to use, API for running machine learning models.
 * 
 * **Example:** Instantiate pipeline using the `pipeline` function.
 * ```javascript
 * import { pipeline } from '@xenova/transformers';
 * 
 * const classifier = await pipeline('sentiment-analysis');
 * const output = await classifier('I love transformers!');
 * // [{'label': 'POSITIVE', 'score': 0.999817686}]
 * ```
 * 
 * @module pipelines
 */













/**
 * @typedef {string | RawImage | URL} ImageInput
 * @typedef {ImageInput|ImageInput[]} ImagePipelineInputs
 */

/**
 * Prepare images for further tasks.
 * @param {ImagePipelineInputs} images images to prepare.
 * @returns {Promise<RawImage[]>} returns processed images.
 * @private
 */
async function prepareImages(images) {
    if (!Array.isArray(images)) {
        images = [images];
    }

    // Possibly convert any non-images to images
    return await Promise.all(images.map(x => _utils_image_js__WEBPACK_IMPORTED_MODULE_7__.RawImage.read(x)));
}

/**
 * @typedef {string | URL | Float32Array | Float64Array} AudioInput
 * @typedef {AudioInput|AudioInput[]} AudioPipelineInputs
 */

/**
 * Prepare audios for further tasks.
 * @param {AudioPipelineInputs} audios audios to prepare.
 * @param {number} sampling_rate sampling rate of the audios.
 * @returns {Promise<Float32Array[]>} The preprocessed audio data.
 * @private
 */
async function prepareAudios(audios, sampling_rate) {
    if (!Array.isArray(audios)) {
        audios = [audios];
    }

    return await Promise.all(audios.map(x => {
        if (typeof x === 'string' || x instanceof URL) {
            return (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.read_audio)(x, sampling_rate);
        } else if (x instanceof Float64Array) {
            return new Float32Array(x);
        }
        return x;
    }));
}

/**
 * @typedef {Object} BoundingBox
 * @property {number} xmin The minimum x coordinate of the bounding box.
 * @property {number} ymin The minimum y coordinate of the bounding box.
 * @property {number} xmax The maximum x coordinate of the bounding box.
 * @property {number} ymax The maximum y coordinate of the bounding box.
 */

/**
 * Helper function to convert list [xmin, xmax, ymin, ymax] into object { "xmin": xmin, ... }
 * @param {number[]} box The bounding box as a list.
 * @param {boolean} asInteger Whether to cast to integers.
 * @returns {BoundingBox} The bounding box as an object.
 * @private
 */
function get_bounding_box(box, asInteger) {
    if (asInteger) {
        box = box.map(x => x | 0);
    }
    const [xmin, ymin, xmax, ymax] = box;

    return { xmin, ymin, xmax, ymax };
}


/**
 * @callback DisposeType Disposes the item.
 * @returns {Promise<void>} A promise that resolves when the item has been disposed.
 * 
 * @typedef {Object} Disposable
 * @property {DisposeType} dispose A promise that resolves when the pipeline has been disposed.
 */

/**
 * The Pipeline class is the class from which all pipelines inherit.
 * Refer to this class for methods shared across different pipelines.
 * @extends Callable
 */
class Pipeline extends _utils_core_js__WEBPACK_IMPORTED_MODULE_3__.Callable {
    /**
     * Create a new Pipeline.
     * @param {Object} options An object containing the following properties:
     * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks.
     * @param {PreTrainedModel} [options.model] The model used by the pipeline.
     * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any).
     * @param {Processor} [options.processor=null] The processor used by the pipeline (if any).
     */
    constructor({ task, model, tokenizer = null, processor = null }) {
        super();
        this.task = task;
        this.model = model;
        this.tokenizer = tokenizer;
        this.processor = processor;
    }

    /** @type {DisposeType} */
    async dispose() {
        await this.model.dispose();
    }
}

/**
 * @typedef {Object} ModelTokenizerConstructorArgs
 * @property {string} task The task of the pipeline. Useful for specifying subtasks.
 * @property {PreTrainedModel} model The model used by the pipeline.
 * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.
 * 
 * @typedef {ModelTokenizerConstructorArgs} TextPipelineConstructorArgs An object used to instantiate a text-based pipeline.
 */

/**
 * @typedef {Object} ModelProcessorConstructorArgs
 * @property {string} task The task of the pipeline. Useful for specifying subtasks.
 * @property {PreTrainedModel} model The model used by the pipeline.
 * @property {Processor} processor The processor used by the pipeline.
 * 
 * @typedef {ModelProcessorConstructorArgs} AudioPipelineConstructorArgs An object used to instantiate an audio-based pipeline.
 * @typedef {ModelProcessorConstructorArgs} ImagePipelineConstructorArgs An object used to instantiate an image-based pipeline.
 */


/**
 * @typedef {Object} ModelTokenizerProcessorConstructorArgs
 * @property {string} task The task of the pipeline. Useful for specifying subtasks.
 * @property {PreTrainedModel} model The model used by the pipeline.
 * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.
 * @property {Processor} processor The processor used by the pipeline.
 * 
 * @typedef {ModelTokenizerProcessorConstructorArgs} TextAudioPipelineConstructorArgs An object used to instantiate a text- and audio-based pipeline.
 * @typedef {ModelTokenizerProcessorConstructorArgs} TextImagePipelineConstructorArgs An object used to instantiate a text- and image-based pipeline.
 */

/**
 * @typedef {Object} TextClassificationSingle
 * @property {string} label The label predicted.
 * @property {number} score The corresponding probability.
 * @typedef {TextClassificationSingle[]} TextClassificationOutput
 * 
 * @typedef {Object} TextClassificationPipelineOptions Parameters specific to text classification pipelines.
 * @property {number} [topk=1] The number of top predictions to be returned.
 * 
 * @callback TextClassificationPipelineCallback Classify the text(s) given as inputs.
 * @param {string|string[]} texts The input text(s) to be classified.
 * @param {TextClassificationPipelineOptions} [options] The options to use for text classification.
 * @returns {Promise<TextClassificationOutput|TextClassificationOutput[]>} An array or object containing the predicted labels and scores.
 * 
 * @typedef {TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable} TextClassificationPipelineType
 */

/**
 * Text classification pipeline using any `ModelForSequenceClassification`.
 *
 * **Example:** Sentiment-analysis w/ `Xenova/distilbert-base-uncased-finetuned-sst-2-english`.
 * ```javascript
 * const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');
 * const output = await classifier('I love transformers!');
 * // [{ label: 'POSITIVE', score: 0.999788761138916 }]
 * ```
 * 
 * **Example:** Multilingual sentiment-analysis w/ `Xenova/bert-base-multilingual-uncased-sentiment` (and return top 5 classes).
 * ```javascript
 * const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');
 * const output = await classifier('Le meilleur film de tous les temps.', { topk: 5 });
 * // [
 * //   { label: '5 stars', score: 0.9610759615898132 },
 * //   { label: '4 stars', score: 0.03323351591825485 },
 * //   { label: '3 stars', score: 0.0036155181005597115 },
 * //   { label: '1 star', score: 0.0011325967498123646 },
 * //   { label: '2 stars', score: 0.0009423971059732139 }
 * // ]
 * ```
 * 
 * **Example:** Toxic comment classification w/ `Xenova/toxic-bert` (and return all classes).
 * ```javascript
 * const classifier = await pipeline('text-classification', 'Xenova/toxic-bert');
 * const output = await classifier('I hate you!', { topk: null });
 * // [
 * //   { label: 'toxic', score: 0.9593140482902527 },
 * //   { label: 'insult', score: 0.16187334060668945 },
 * //   { label: 'obscene', score: 0.03452680632472038 },
 * //   { label: 'identity_hate', score: 0.0223250575363636 },
 * //   { label: 'threat', score: 0.019197041168808937 },
 * //   { label: 'severe_toxic', score: 0.005651099607348442 }
 * // ]
 * ```
 */
class TextClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ (Pipeline)) {

    /**
     * Create a new TextClassificationPipeline.
     * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {TextClassificationPipelineCallback} */
    async _call(texts, {
        topk = 1
    } = {}) {

        // Run tokenization
        const model_inputs = this.tokenizer(texts, {
            padding: true,
            truncation: true,
        });

        // Run model
        const outputs = await this.model(model_inputs)

        // TODO: Use softmax tensor function
        const function_to_apply =
            this.model.config.problem_type === 'multi_label_classification'
                ? batch => batch.sigmoid().data
                : batch => (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(batch.data); // single_label_classification (default)

        const id2label = this.model.config.id2label;

        const toReturn = [];
        for (const batch of outputs.logits) {
            const output = function_to_apply(batch);
            const scores = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.getTopItems)(output, topk);

            const vals = scores.map(x => ({
                label: id2label[x[0]],
                score: x[1],
            }));
            if (topk === 1) {
                toReturn.push(...vals);
            } else {
                toReturn.push(vals);
            }
        }

        return Array.isArray(texts) || topk === 1 ? /** @type {TextClassificationOutput} */ (toReturn) : /** @type {TextClassificationOutput[]} */ (toReturn)[0];
    }
}

/**
 * @typedef {Object} TokenClassificationSingle
 * @property {string} word The token/word classified. This is obtained by decoding the selected tokens.
 * @property {number} score The corresponding probability for `entity`.
 * @property {string} entity The entity predicted for that token/word.
 * @property {number} index The index of the corresponding token in the sentence.
 * @property {number} [start] The index of the start of the corresponding entity in the sentence.
 * @property {number} [end] The index of the end of the corresponding entity in the sentence.
 * @typedef {TokenClassificationSingle[]} TokenClassificationOutput
 * 
 * @typedef {Object} TokenClassificationPipelineOptions Parameters specific to token classification pipelines.
 * @property {string[]} [ignore_labels] A list of labels to ignore.
 * 
 * @callback TokenClassificationPipelineCallback Classify each token of the text(s) given as inputs.
 * @param {string|string[]} texts One or several texts (or one list of texts) for token classification.
 * @param {TokenClassificationPipelineOptions} [options] The options to use for token classification.
 * @returns {Promise<TokenClassificationOutput|TokenClassificationOutput[]>} The result.
 * 
 * @typedef {TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable} TokenClassificationPipelineType
 */

/**
 * Named Entity Recognition pipeline using any `ModelForTokenClassification`.
 * 
 * **Example:** Perform named entity recognition with `Xenova/bert-base-NER`.
 * ```javascript
 * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');
 * const output = await classifier('My name is Sarah and I live in London');
 * // [
 * //   { entity: 'B-PER', score: 0.9980202913284302, index: 4, word: 'Sarah' },
 * //   { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' }
 * // ]
 * ```
 * 
 * **Example:** Perform named entity recognition with `Xenova/bert-base-NER` (and return all labels).
 * ```javascript
 * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');
 * const output = await classifier('Sarah lives in the United States of America', { ignore_labels: [] });
 * // [
 * //   { entity: 'B-PER', score: 0.9966587424278259, index: 1, word: 'Sarah' },
 * //   { entity: 'O', score: 0.9987385869026184, index: 2, word: 'lives' },
 * //   { entity: 'O', score: 0.9990072846412659, index: 3, word: 'in' },
 * //   { entity: 'O', score: 0.9988298416137695, index: 4, word: 'the' },
 * //   { entity: 'B-LOC', score: 0.9995510578155518, index: 5, word: 'United' },
 * //   { entity: 'I-LOC', score: 0.9990395307540894, index: 6, word: 'States' },
 * //   { entity: 'I-LOC', score: 0.9986724853515625, index: 7, word: 'of' },
 * //   { entity: 'I-LOC', score: 0.9975294470787048, index: 8, word: 'America' }
 * // ]
 * ```
 */
class TokenClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ (Pipeline)) {

    /**
     * Create a new TokenClassificationPipeline.
     * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {TokenClassificationPipelineCallback} */
    async _call(texts, {
        ignore_labels = ['O'],
    } = {}) {

        const isBatched = Array.isArray(texts);

        // Run tokenization
        const model_inputs = this.tokenizer(isBatched ? texts : [texts], {
            padding: true,
            truncation: true,
        });

        // Run model
        const outputs = await this.model(model_inputs)

        const logits = outputs.logits;
        const id2label = this.model.config.id2label;

        const toReturn = [];
        for (let i = 0; i < logits.dims[0]; ++i) {
            const ids = model_inputs.input_ids[i];
            const batch = logits[i];

            // List of tokens that aren't ignored
            const tokens = [];
            for (let j = 0; j < batch.dims[0]; ++j) {
                const tokenData = batch[j];
                const topScoreIndex = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.max)(tokenData.data)[1];

                const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`;
                if (ignore_labels.includes(entity)) {
                    // We predicted a token that should be ignored. So, we skip it.
                    continue;
                }

                // TODO add option to keep special tokens?
                const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true });
                if (word === '') {
                    // Was a special token. So, we skip it.
                    continue;
                }

                const scores = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(tokenData.data);

                tokens.push({
                    entity: entity,
                    score: scores[topScoreIndex],
                    index: j,
                    word: word,

                    // TODO: null for now, but will add
                    start: null,
                    end: null,
                });
            }
            toReturn.push(tokens);
        }
        return isBatched ? toReturn : toReturn[0];
    }
}

/**
 * @typedef {Object} QuestionAnsweringOutput
 * @property {number} score The probability associated to the answer.
 * @property {number} [start] The character start index of the answer (in the tokenized version of the input).
 * @property {number} [end] The character end index of the answer (in the tokenized version of the input).
 * @property {string} answer The answer to the question.
 * 
 * @typedef {Object} QuestionAnsweringPipelineOptions Parameters specific to question answering pipelines.
 * @property {number} [topk=1] The number of top answer predictions to be returned.
 * 
 * @callback QuestionAnsweringPipelineCallback Answer the question(s) given as inputs by using the context(s).
 * @param {string|string[]} question One or several question(s) (must be used in conjunction with the `context` argument).
 * @param {string|string[]} context One or several context(s) associated with the question(s) (must be used in conjunction with the `question` argument).
 * @param {QuestionAnsweringPipelineOptions} [options] The options to use for question answering.
 * @returns {Promise<QuestionAnsweringOutput|QuestionAnsweringOutput[]>} An array or object containing the predicted answers and scores.
 * 
 * @typedef {TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable} QuestionAnsweringPipelineType
 */

/**
 * Question Answering pipeline using any `ModelForQuestionAnswering`.
 * 
 * **Example:** Run question answering with `Xenova/distilbert-base-uncased-distilled-squad`.
 * ```javascript
 * const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad');
 * const question = 'Who was Jim Henson?';
 * const context = 'Jim Henson was a nice puppet.';
 * const output = await answerer(question, context);
 * // {
 * //   answer: "a nice puppet",
 * //   score: 0.5768911502526741
 * // }
 * ```
 */
class QuestionAnsweringPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ (Pipeline)) {

    /**
     * Create a new QuestionAnsweringPipeline.
     * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {QuestionAnsweringPipelineCallback} */
    async _call(question, context, {
        topk = 1
    } = {}) {

        // Run tokenization
        const inputs = this.tokenizer(question, {
            text_pair: context,
            padding: true,
            truncation: true,
        });

        const output = await this.model(inputs);

        /** @type {QuestionAnsweringOutput[]} */
        const toReturn = [];
        for (let j = 0; j < output.start_logits.dims[0]; ++j) {
            const ids = inputs.input_ids[j];
            const sepIndex = ids.indexOf(this.tokenizer.sep_token_id);

            const s1 = Array.from((0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(output.start_logits[j].data))
                .map((x, i) => [x, i])
                .filter(x => x[1] > sepIndex);
            const e1 = Array.from((0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(output.end_logits[j].data))
                .map((x, i) => [x, i])
                .filter(x => x[1] > sepIndex);

            const options = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_3__.product)(s1, e1)
                .filter(x => x[0][1] <= x[1][1])
                .map(x => [x[0][1], x[1][1], x[0][0] * x[1][0]])
                .sort((a, b) => b[2] - a[2]);

            for (let k = 0; k < Math.min(options.length, topk); ++k) {
                const [start, end, score] = options[k];

                const answer_tokens = [...ids].slice(start, end + 1)

                const answer = this.tokenizer.decode(answer_tokens, {
                    skip_special_tokens: true,
                });

                // TODO add start and end?
                // NOTE: HF returns character index
                toReturn.push({
                    answer, score
                });
            }
        }

        // Mimic HF's return type based on topk
        return (topk === 1) ? toReturn[0] : toReturn;
    }
}


/**
 * @typedef {Object} FillMaskSingle
 * @property {string} sequence The corresponding input with the mask token prediction.
 * @property {number} score The corresponding probability.
 * @property {number} token The predicted token id (to replace the masked one).
 * @property {string} token_str The predicted token (to replace the masked one).
 * @typedef {FillMaskSingle[]} FillMaskOutput
 * 
 * @typedef {Object} FillMaskPipelineOptions Parameters specific to fill mask pipelines.
 * @property {number} [topk=5] When passed, overrides the number of predictions to return.
 * 
 * @callback FillMaskPipelineCallback Fill the masked token in the text(s) given as inputs.
 * @param {string|string[]} texts One or several texts (or one list of prompts) with masked tokens.
 * @param {FillMaskPipelineOptions} [options] The options to use for masked language modelling.
 * @returns {Promise<FillMaskOutput|FillMaskOutput[]>} An array of objects containing the score, predicted token, predicted token string,
 * and the sequence with the predicted token filled in, or an array of such arrays (one for each input text).
 * If only one input text is given, the output will be an array of objects.
 * @throws {Error} When the mask token is not found in the input text.
 * 
 * @typedef {TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable} FillMaskPipelineType
 */

/**
 * Masked language modeling prediction pipeline using any `ModelWithLMHead`.
 * 
 * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-uncased`.
 * ```javascript
 * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');
 * const output = await unmasker('The goal of life is [MASK].');
 * // [
 * //   { token_str: 'survival', score: 0.06137419492006302, token: 8115, sequence: 'The goal of life is survival.' },
 * //   { token_str: 'love', score: 0.03902450203895569, token: 1567, sequence: 'The goal of life is love.' },
 * //   { token_str: 'happiness', score: 0.03253183513879776, token: 9266, sequence: 'The goal of life is happiness.' },
 * //   { token_str: 'freedom', score: 0.018736306577920914, token: 4438, sequence: 'The goal of life is freedom.' },
 * //   { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' }
 * // ]
 * ```
 * 
 * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-cased` (and return top result).
 * ```javascript
 * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');
 * const output = await unmasker('The Milky Way is a [MASK] galaxy.', { topk: 1 });
 * // [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }]
 * ```
 */
class FillMaskPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ (Pipeline)) {

    /**
     * Create a new FillMaskPipeline.
     * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {FillMaskPipelineCallback} */
    async _call(texts, {
        topk = 5
    } = {}) {

        // Run tokenization
        const model_inputs = this.tokenizer(texts, {
            padding: true,
            truncation: true,
        });

        // Run model
        const outputs = await this.model(model_inputs)

        const toReturn = [];

        for (let i = 0; i < model_inputs.input_ids.dims[0]; ++i) {
            const ids = model_inputs.input_ids[i];
            const mask_token_index = ids.indexOf(this.tokenizer.mask_token_id)

            if (mask_token_index === -1) {
                throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`)
            }
            const logits = outputs.logits[i];
            const itemLogits = logits[mask_token_index];

            const scores = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.getTopItems)((0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(itemLogits.data), topk);

            toReturn.push(scores.map(x => {
                const sequence = [...ids];
                sequence[mask_token_index] = x[0];

                return {
                    score: x[1],
                    token: x[0],
                    token_str: this.tokenizer.model.vocab[x[0]],
                    sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }),
                }
            }));
        }
        return Array.isArray(texts) ? toReturn : toReturn[0];
    }
}


/**
 * @typedef {Object} Text2TextGenerationSingle
 * @property {string} generated_text The generated text.
 * @typedef {Text2TextGenerationSingle[]} Text2TextGenerationOutput
 * 
 * @callback Text2TextGenerationPipelineCallback Generate the output text(s) using text(s) given as inputs.
 * @param {string|string[]} texts Input text for the encoder.
 * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model.
 * @returns {Promise<Text2TextGenerationOutput|Text2TextGenerationOutput[]>}
 * 
 * @typedef {TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable} Text2TextGenerationPipelineType
 */

/**
 * Text2TextGenerationPipeline class for generating text using a model that performs text-to-text generation tasks.
 * 
 * **Example:** Text-to-text generation w/ `Xenova/LaMini-Flan-T5-783M`.
 * ```javascript
 * const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M');
 * const output = await generator('how can I become more healthy?', {
 *   max_new_tokens: 100,
 * });
 * // [{ generated_text: "To become more healthy, you can: 1. Eat a balanced diet with plenty of fruits, vegetables, whole grains, lean proteins, and healthy fats. 2. Stay hydrated by drinking plenty of water. 3. Get enough sleep and manage stress levels. 4. Avoid smoking and excessive alcohol consumption. 5. Regularly exercise and maintain a healthy weight. 6. Practice good hygiene and sanitation. 7. Seek medical attention if you experience any health issues." }]
 * ```
 */
class Text2TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ (Pipeline)) {
    /** @type {'generated_text'} */
    _key = 'generated_text';

    /**
     * Create a new Text2TextGenerationPipeline.
     * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {Text2TextGenerationPipelineCallback} */
    async _call(texts, generate_kwargs = {}) {
        if (!Array.isArray(texts)) {
            texts = [texts];
        }


        // Add global prefix, if present
        if (this.model.config.prefix) {
            texts = texts.map(x => this.model.config.prefix + x)
        }

        // Handle task specific params:
        const task_specific_params = this.model.config.task_specific_params
        if (task_specific_params && task_specific_params[this.task]) {
            // Add prefixes, if present
            if (task_specific_params[this.task].prefix) {
                texts = texts.map(x => task_specific_params[this.task].prefix + x)
            }

            // TODO update generation config
        }

        const tokenizer = this.tokenizer;
        const tokenizer_options = {
            padding: true,
            truncation: true,
        }
        let input_ids;
        if (this instanceof TranslationPipeline && '_build_translation_inputs' in tokenizer) {
            // TODO: move to Translation pipeline?
            // Currently put here to avoid code duplication
            // @ts-ignore
            input_ids = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs).input_ids;

        } else {
            input_ids = tokenizer(texts, tokenizer_options).input_ids;
        }

        const outputTokenIds = await this.model.generate(input_ids, generate_kwargs);

        return tokenizer.batch_decode(outputTokenIds, {
            skip_special_tokens: true,
        }).map(text => ({ [this._key]: text }));
    }
}


/**
 * @typedef {Object} SummarizationSingle
 * @property {string} summary_text The summary text.
 * @typedef {SummarizationSingle[]} SummarizationOutput
 * 
 * @callback SummarizationPipelineCallback Summarize the text(s) given as inputs.
 * @param {string|string[]} texts One or several articles (or one list of articles) to summarize.
 * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model.
 * @returns {Promise<SummarizationOutput|SummarizationOutput[]>}
 * 
 * @typedef {TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable} SummarizationPipelineType
 */

/**
 * A pipeline for summarization tasks, inheriting from Text2TextGenerationPipeline.
 * 
 * **Example:** Summarization w/ `Xenova/distilbart-cnn-6-6`.
 * ```javascript
 * const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6');
 * const text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, ' +
 *   'and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. ' +
 *   'During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest ' +
 *   'man-made structure in the world, a title it held for 41 years until the Chrysler Building in New ' +
 *   'York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to ' +
 *   'the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the ' +
 *   'Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second ' +
 *   'tallest free-standing structure in France after the Millau Viaduct.';
 * const output = await generator(text, {
 *   max_new_tokens: 100,
 * });
 * // [{ summary_text: ' The Eiffel Tower is about the same height as an 81-storey building and the tallest structure in Paris. It is the second tallest free-standing structure in France after the Millau Viaduct.' }]
 * ```
 */
class SummarizationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {
    /** @type {'summary_text'} */
    _key = 'summary_text';

    /**
     * Create a new SummarizationPipeline.
     * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }
}


/**
 * @typedef {Object} TranslationSingle
 * @property {string} translation_text The translated text.
 * @typedef {TranslationSingle[]} TranslationOutput
 * 
 * @callback TranslationPipelineCallback Translate the text(s) given as inputs.
 * @param {string|string[]} texts Texts to be translated.
 * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model.
 * @returns {Promise<TranslationOutput|TranslationOutput[]>}
 * 
 * @typedef {TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable} TranslationPipelineType
 */

/**
 * Translates text from one language to another.
 * 
 * **Example:** Multilingual translation w/ `Xenova/nllb-200-distilled-600M`.
 * 
 * See [here](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200)
 * for the full list of languages and their corresponding codes.
 * 
 * ```javascript
 * const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');
 * const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', {
 *   src_lang: 'hin_Deva', // Hindi
 *   tgt_lang: 'fra_Latn', // French
 * });
 * // [{ translation_text: 'La vie est comme une boîte à chocolat.' }]
 * ```
 * 
 * **Example:** Multilingual translation w/ `Xenova/m2m100_418M`.
 * 
 * See [here](https://huggingface.co/facebook/m2m100_418M#languages-covered)
 * for the full list of languages and their corresponding codes.
 * 
 * ```javascript
 * const translator = await pipeline('translation', 'Xenova/m2m100_418M');
 * const output = await translator('生活就像一盒巧克力。', {
 *   src_lang: 'zh', // Chinese
 *   tgt_lang: 'en', // English
 * });
 * // [{ translation_text: 'Life is like a box of chocolate.' }]
 * ```
 * 
 * **Example:** Multilingual translation w/ `Xenova/mbart-large-50-many-to-many-mmt`.
 * 
 * See [here](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered)
 * for the full list of languages and their corresponding codes.
 * 
 * ```javascript
 * const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt');
 * const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', {
 *   src_lang: 'hi_IN', // Hindi
 *   tgt_lang: 'fr_XX', // French
 * });
 * // [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }]
 * ```
 */
class TranslationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {
    /** @type {'translation_text'} */
    _key = 'translation_text';

    /**
     * Create a new TranslationPipeline.
     * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }
}

function isChat(x) {
    return Array.isArray(x) && x.every(x => 'role' in x && 'content' in x);
}

/**
 * @typedef {import('./tokenizers.js').Message[]} Chat
 * 
 * @typedef {Object} TextGenerationSingle
 * @property {string|Chat} generated_text The generated text.
 * @typedef {TextGenerationSingle[]} TextGenerationOutput
 * 
 * @typedef {Object} TextGenerationSpecificParams Parameters specific to text-generation pipelines.
 * @property {boolean} [add_special_tokens] Whether or not to add special tokens when tokenizing the sequences.
 * @property {boolean} [return_full_text=true] If set to `false` only added text is returned, otherwise the full text is returned.
 * @typedef {import('./utils/generation.js').GenerationConfigType & TextGenerationSpecificParams} TextGenerationConfig
 * 
 * @callback TextGenerationPipelineCallback Complete the prompt(s) given as inputs.
 * @param {string|string[]|Chat|Chat[]} texts One or several prompts (or one list of prompts) to complete.
 * @param {TextGenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.
 * @returns {Promise<TextGenerationOutput|TextGenerationOutput[]>} An array or object containing the generated texts.
 * 
 * @typedef {TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable} TextGenerationPipelineType
 */

/**
 * Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`.
 * This pipeline predicts the words that will follow a specified text prompt.
 * NOTE: For the full list of generation parameters, see [`GenerationConfig`](./utils/generation#module_utils/generation.GenerationConfig).
 * 
 * **Example:** Text generation with `Xenova/distilgpt2` (default settings).
 * ```javascript
 * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');
 * const text = 'I enjoy walking with my cute dog,';
 * const output = await generator(text);
 * // [{ generated_text: "I enjoy walking with my cute dog, and I love to play with the other dogs." }]
 * ```
 * 
 * **Example:** Text generation with `Xenova/distilgpt2` (custom settings).
 * ```javascript
 * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');
 * const text = 'Once upon a time, there was';
 * const output = await generator(text, {
 *   temperature: 2,
 *   max_new_tokens: 10,
 *   repetition_penalty: 1.5,
 *   no_repeat_ngram_size: 2,
 *   num_beams: 2,
 *   num_return_sequences: 2,
 * });
 * // [{
 * //   "generated_text": "Once upon a time, there was an abundance of information about the history and activities that"
 * // }, {
 * //   "generated_text": "Once upon a time, there was an abundance of information about the most important and influential"
 * // }]
 * ```
 * 
 * **Example:** Run code generation with `Xenova/codegen-350M-mono`.
 * ```javascript
 * const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono');
 * const text = 'def fib(n):';
 * const output = await generator(text, {
 *   max_new_tokens: 44,
 * });
 * // [{
 * //   generated_text: 'def fib(n):\n' +
 * //     '    if n == 0:\n' +
 * //     '        return 0\n' +
 * //     '    elif n == 1:\n' +
 * //     '        return 1\n' +
 * //     '    else:\n' +
 * //     '        return fib(n-1) + fib(n-2)\n'
 * // }]
 * ```
 */
class TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ (Pipeline)) {

    /**
     * Create a new TextGenerationPipeline.
     * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {TextGenerationPipelineCallback} */
    async _call(texts, generate_kwargs = {}) {
        let isBatched = false;
        let isChatInput = false;

        // Normalize inputs
        /** @type {string[]} */
        let inputs;
        if (typeof texts === 'string') {
            inputs = texts = [texts];
        } else if (Array.isArray(texts) && texts.every(x => typeof x === 'string')) {
            isBatched = true;
            inputs = /** @type {string[]} */(texts);
        } else {
            if (isChat(texts)) {
                texts = [/** @type {Chat} */(texts)];
            } else if (Array.isArray(texts) && texts.every(isChat)) {
                isBatched = true;
            } else {
                throw new Error('Input must be a string, an array of strings, a Chat, or an array of Chats');
            }
            isChatInput = true;

            // If the input is a chat, we need to apply the chat template
            inputs = /** @type {string[]} */(/** @type {Chat[]} */ (texts).map(
                x => this.tokenizer.apply_chat_template(x, {
                    tokenize: false,
                    add_generation_prompt: true,
                })
            ));
        }

        // By default, do not add special tokens
        const add_special_tokens = generate_kwargs.add_special_tokens ?? false;

        // By default, return full text
        const return_full_text = isChatInput
            ? false
            : generate_kwargs.return_full_text ?? true;

        this.tokenizer.padding_side = 'left';
        const { input_ids, attention_mask } = this.tokenizer(inputs, {
            add_special_tokens,
            padding: true,
            truncation: true,
        });

        const outputTokenIds = await this.model.generate(input_ids, generate_kwargs, null, {
            inputs_attention_mask: attention_mask
        });

        let decoded = this.tokenizer.batch_decode(outputTokenIds, {
            skip_special_tokens: true,
        });


        let promptLengths;
        if (!return_full_text && input_ids.dims.at(-1) > 0) {
            promptLengths = this.tokenizer.batch_decode(input_ids, {
                skip_special_tokens: true,
            }).map(x => x.length);
        }

        /** @type {TextGenerationOutput[]} */
        const toReturn = Array.from({ length: texts.length }, _ => []);
        for (let i = 0; i < decoded.length; ++i) {
            const textIndex = Math.floor(i / outputTokenIds.length * texts.length);

            if (promptLengths) {
                // Trim the decoded text to only include the generated part
                decoded[i] = decoded[i].slice(promptLengths[textIndex]);
            }
            toReturn[textIndex].push({
                generated_text: isChatInput
                    ? [
                        ...((/** @type {Chat[]} */(texts)[textIndex])),
                        { role: 'assistant', content: decoded[i] },
                    ]
                    : decoded[i]
            });
        }
        return (!isBatched && toReturn.length === 1) ? toReturn[0] : toReturn;
    }
}

/**
 * @typedef {Object} ZeroShotClassificationOutput
 * @property {string} sequence The sequence for which this is the output.
 * @property {string[]} labels The labels sorted by order of likelihood.
 * @property {number[]} scores The probabilities for each of the labels.
 * 
 * @typedef {Object} ZeroShotClassificationPipelineOptions Parameters specific to zero-shot classification pipelines.
 * @property {string} [hypothesis_template="This example is {}."] The template used to turn each
 * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder.
 * @property {boolean} [multi_label=false] Whether or not multiple candidate labels can be true.
 * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence
 * is 1. If `true`, the labels are considered independent and probabilities are normalized for each
 * candidate by doing a softmax of the entailment score vs. the contradiction score.
 * 
 * @callback ZeroShotClassificationPipelineCallback Classify the sequence(s) given as inputs.
 * @param {string|string[]} texts The sequence(s) to classify, will be truncated if the model input is too large.
 * @param {string|string[]} candidate_labels The set of possible class labels to classify each sequence into.
 * Can be a single label, a string of comma-separated labels, or a list of labels.
 * @param {ZeroShotClassificationPipelineOptions} [options] The options to use for zero-shot classification.
 * @returns {Promise<ZeroShotClassificationOutput|ZeroShotClassificationOutput[]>} An array or object containing the predicted labels and scores.
 * 
 * @typedef {TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable} ZeroShotClassificationPipelineType
 */

/**
 * NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification`
 * trained on NLI (natural language inference) tasks. Equivalent of `text-classification`
 * pipelines, but these models don't require a hardcoded number of potential classes, they
 * can be chosen at runtime. It usually means it's slower but it is **much** more flexible.
 * 
 * **Example:** Zero shot classification with `Xenova/mobilebert-uncased-mnli`.
 * ```javascript
 * const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli');
 * const text = 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.';
 * const labels = [ 'mobile', 'billing', 'website', 'account access' ];
 * const output = await classifier(text, labels);
 * // {
 * //   sequence: 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.',
 * //   labels: [ 'mobile', 'website', 'billing', 'account access' ],
 * //   scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ]
 * // }
 * ```
 * 
 * **Example:** Zero shot classification with `Xenova/nli-deberta-v3-xsmall` (multi-label).
 * ```javascript
 * const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall');
 * const text = 'I have a problem with my iphone that needs to be resolved asap!';
 * const labels = [ 'urgent', 'not urgent', 'phone', 'tablet', 'computer' ];
 * const output = await classifier(text, labels, { multi_label: true });
 * // {
 * //   sequence: 'I have a problem with my iphone that needs to be resolved asap!',
 * //   labels: [ 'urgent', 'phone', 'computer', 'tablet', 'not urgent' ],
 * //   scores: [ 0.9958870956360275, 0.9923963400697035, 0.002333537946160235, 0.0015134138567598765, 0.0010699384208377163 ]
 * // }
 * ```
 */
class ZeroShotClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ (Pipeline)) {
    /**
     * Create a new ZeroShotClassificationPipeline.
     * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);

        // Use model config to get label2id mapping
        this.label2id = Object.fromEntries(
            Object.entries((/** @type {any} */(this).model).config.label2id).map(
                ([k, v]) => [k.toLowerCase(), v]
            )
        );

        this.entailment_id = this.label2id['entailment'];
        if (this.entailment_id === undefined) {
            console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.");
            this.entailment_id = 2;
        }

        this.contradiction_id = this.label2id['contradiction'] ?? this.label2id['not_entailment'];
        if (this.contradiction_id === undefined) {
            console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.");
            this.contradiction_id = 0;
        }
    }

    /** @type {ZeroShotClassificationPipelineCallback} */
    async _call(texts, candidate_labels, {
        hypothesis_template = "This example is {}.",
        multi_label = false,
    } = {}) {

        const isBatched = Array.isArray(texts);
        if (!isBatched) {
            texts = [/** @type {string} */ (texts)];
        }
        if (!Array.isArray(candidate_labels)) {
            candidate_labels = [candidate_labels];
        }

        // Insert labels into hypothesis template
        const hypotheses = candidate_labels.map(
            x => hypothesis_template.replace('{}', x)
        );

        // How to perform the softmax over the logits:
        //  - true:  softmax over the entailment vs. contradiction dim for each label independently
        //  - false: softmax the "entailment" logits over all candidate labels
        const softmaxEach = multi_label || candidate_labels.length === 1;

        /** @type {ZeroShotClassificationOutput[]} */
        const toReturn = [];
        for (const premise of texts) {
            const entails_logits = [];

            for (const hypothesis of hypotheses) {
                const inputs = this.tokenizer(premise, {
                    text_pair: hypothesis,
                    padding: true,
                    truncation: true,
                })
                const outputs = await this.model(inputs)

                if (softmaxEach) {
                    entails_logits.push([
                        outputs.logits.data[this.contradiction_id],
                        outputs.logits.data[this.entailment_id]
                    ])
                } else {
                    entails_logits.push(outputs.logits.data[this.entailment_id])
                }
            }

            /** @type {number[]} */
            const scores = softmaxEach
                ? entails_logits.map(x => (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(x)[1])
                : (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(entails_logits);

            // Sort by scores (desc) and return scores with indices
            const scores_sorted = scores
                .map((x, i) => [x, i])
                .sort((a, b) => (b[0] - a[0]));

            toReturn.push({
                sequence: premise,
                labels: scores_sorted.map(x => candidate_labels[x[1]]),
                scores: scores_sorted.map(x => x[0]),
            });
        }
        return isBatched ? toReturn : toReturn[0];
    }
}

/**
 * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines.
 * @property {'none'|'mean'|'cls'} [pooling="none"] The pooling method to use.
 * @property {boolean} [normalize=false] Whether or not to normalize the embeddings in the last dimension.
 * @property {boolean} [quantize=false] Whether or not to quantize the embeddings.
 * @property {'binary'|'ubinary'} [precision='binary'] The precision to use for quantization. 
 * 
 * @callback FeatureExtractionPipelineCallback Extract the features of the input(s).
 * @param {string|string[]} texts One or several texts (or one list of texts) to get the features of.
 * @param {FeatureExtractionPipelineOptions} [options] The options to use for feature extraction.
 * @returns {Promise<Tensor>} The features computed by the model.
 * 
 * @typedef {TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable} FeatureExtractionPipelineType
 */

/**
 * Feature extraction pipeline using no model head. This pipeline extracts the hidden
 * states from the base transformer, which can be used as features in downstream tasks.
 * 
 * **Example:** Run feature extraction with `bert-base-uncased` (without pooling/normalization).
 * ```javascript
 * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });
 * const output = await extractor('This is a simple test.');
 * // Tensor {
 * //   type: 'float32',
 * //   data: Float32Array [0.05939924716949463, 0.021655935794115067, ...],
 * //   dims: [1, 8, 768]
 * // }
 * ```
 * 
 * **Example:** Run feature extraction with `bert-base-uncased` (with pooling/normalization).
 * ```javascript
 * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });
 * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });
 * // Tensor {
 * //   type: 'float32',
 * //   data: Float32Array [0.03373778983950615, -0.010106077417731285, ...],
 * //   dims: [1, 768]
 * // }
 * ```
 * 
 * **Example:** Calculating embeddings with `sentence-transformers` models.
 * ```javascript
 * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
 * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });
 * // Tensor {
 * //   type: 'float32',
 * //   data: Float32Array [0.09094982594251633, -0.014774246141314507, ...],
 * //   dims: [1, 384]
 * // }
 * ```
 * **Example:** Calculating binary embeddings with `sentence-transformers` models.
 * ```javascript
 * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
 * const output = await extractor('This is a simple test.', { pooling: 'mean', quantize: true, precision: 'binary' });
 * // Tensor {
 * //   type: 'int8',
 * //   data: Int8Array [49, 108, 24, ...],
 * //   dims: [1, 48]
 * // }
 * ```
 */
class FeatureExtractionPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ (Pipeline)) {
    /**
     * Create a new FeatureExtractionPipeline.
     * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {FeatureExtractionPipelineCallback} */
    async _call(texts, {
        pooling = /** @type {'none'} */('none'),
        normalize = false,
        quantize = false,
        precision = /** @type {'binary'} */('binary'),
    } = {}) {

        // Run tokenization
        const model_inputs = this.tokenizer(texts, {
            padding: true,
            truncation: true,
        });

        // Run model
        const outputs = await this.model(model_inputs)

        // TODO: Provide warning to the user that they might be using model which was not exported
        // specifically for feature extraction
        // console.log(this.model.config)
        // console.log(outputs)

        /** @type {Tensor} */
        let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings;
        if (pooling === 'none') {
            // Skip pooling
        } else if (pooling === 'mean') {
            result = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_6__.mean_pooling)(result, model_inputs.attention_mask);
        } else if (pooling === 'cls') {
            result = result.slice(null, 0);
        } else {
            throw Error(`Pooling method '${pooling}' not supported.`);
        }

        if (normalize) {
            result = result.normalize(2, -1);
        }

        if (quantize) {
            result = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_6__.quantize_embeddings)(result, precision);
        }

        return result;
    }
}


/**
 * @typedef {Object} ImageFeatureExtractionPipelineOptions Parameters specific to image feature extraction pipelines.
 * @property {boolean} [pool=null] Whether or not to return the pooled output. If set to `false`, the model will return the raw hidden states.
 * 
 * @callback ImageFeatureExtractionPipelineCallback Extract the features of the input(s).
 * @param {ImagePipelineInputs} images One or several images (or one list of images) to get the features of.
 * @param {ImageFeatureExtractionPipelineOptions} [options] The options to use for image feature extraction.
 * @returns {Promise<Tensor>} The image features computed by the model.
 * 
 * @typedef {ImagePipelineConstructorArgs & ImageFeatureExtractionPipelineCallback & Disposable} ImageFeatureExtractionPipelineType
 */

/**
 * Image feature extraction pipeline using no model head. This pipeline extracts the hidden
 * states from the base transformer, which can be used as features in downstream tasks.
 * 
 * **Example:** Perform image feature extraction with `Xenova/vit-base-patch16-224-in21k`.
 * ```javascript
 * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/vit-base-patch16-224-in21k');
 * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';
 * const features = await image_feature_extractor(url);
 * // Tensor {
 * //   dims: [ 1, 197, 768 ],
 * //   type: 'float32',
 * //   data: Float32Array(151296) [ ... ],
 * //   size: 151296
 * // }
 * ```
 * 
 * **Example:** Compute image embeddings with `Xenova/clip-vit-base-patch32`.
 * ```javascript
 * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/clip-vit-base-patch32');
 * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';
 * const features = await image_feature_extractor(url);
 * // Tensor {
 * //   dims: [ 1, 512 ],
 * //   type: 'float32',
 * //   data: Float32Array(512) [ ... ],
 * //   size: 512
 * // }
 * ```
 */
class ImageFeatureExtractionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ (Pipeline)) {
    /**
     * Create a new ImageFeatureExtractionPipeline.
     * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {ImageFeatureExtractionPipelineCallback} */
    async _call(images, {
        pool = null,
    } = {}) {

        const preparedImages = await prepareImages(images);
        const { pixel_values } = await this.processor(preparedImages);
        const outputs = await this.model({ pixel_values });

        /** @type {Tensor} */
        let result;
        if (pool) {
            if (!('pooler_output' in outputs)) {
                throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`);
            }
            result = outputs.pooler_output;

        } else {
            result = outputs.last_hidden_state ?? outputs.logits ?? outputs.image_embeds;
        }
        return result;
    }
}

// TODO
// export class SentenceSimilarityPipeline extends Pipeline {
// }

/**
 * @typedef {Object} AudioClassificationSingle
 * @property {string} label The label predicted.
 * @property {number} score The corresponding probability.
 * @typedef {AudioClassificationSingle[]} AudioClassificationOutput
 * 
 * @typedef {Object} AudioClassificationPipelineOptions Parameters specific to audio classification pipelines.
 * @property {number} [topk=null] The number of top labels that will be returned by the pipeline.
 * If the provided number is `null` or higher than the number of labels available in the model configuration,
 * it will default to the number of labels.
 * 
 * @callback AudioClassificationPipelineCallback Classify the sequence(s) given as inputs.
 * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:
 * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate
 * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.
 * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.
 * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).
 * @param {AudioClassificationPipelineOptions} [options] The options to use for audio classification.
 * @returns {Promise<AudioClassificationOutput|AudioClassificationOutput[]>} An array or object containing the predicted labels and scores.
 * 
 * @typedef {AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable} AudioClassificationPipelineType
 */

/**
 * Audio classification pipeline using any `AutoModelForAudioClassification`.
 * This pipeline predicts the class of a raw waveform or an audio file.
 * 
 * **Example:** Perform audio classification with `Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech`.
 * ```javascript
 * const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
 * const output = await classifier(url);
 * // [
 * //   { label: 'male', score: 0.9981542229652405 },
 * //   { label: 'female', score: 0.001845747814513743 }
 * // ]
 * ```
 * 
 * **Example:** Perform audio classification with `Xenova/ast-finetuned-audioset-10-10-0.4593` and return top 4 results.
 * ```javascript
 * const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav';
 * const output = await classifier(url, { topk: 4 });
 * // [
 * //   { label: 'Meow', score: 0.5617874264717102 },
 * //   { label: 'Cat', score: 0.22365376353263855 },
 * //   { label: 'Domestic animals, pets', score: 0.1141069084405899 },
 * //   { label: 'Animal', score: 0.08985692262649536 },
 * // ]
 * ```
 */
class AudioClassificationPipeline extends (/** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ (Pipeline)) {

    /**
     * Create a new AudioClassificationPipeline.
     * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {AudioClassificationPipelineCallback} */
    async _call(audio, {
        topk = null
    } = {}) {

        const single = !Array.isArray(audio);

        const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
        const preparedAudios = await prepareAudios(audio, sampling_rate);

        const id2label = this.model.config.id2label;

        const toReturn = [];
        for (const aud of preparedAudios) {
            const inputs = await this.processor(aud);
            const output = await this.model(inputs);
            const logits = output.logits[0];

            const scores = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.getTopItems)((0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(logits.data), topk);

            const vals = scores.map(x => ({
                label: /** @type {string} */ (id2label[x[0]]),
                score: /** @type {number} */ (x[1]),
            }));

            if (topk === 1) {
                toReturn.push(...vals);
            } else {
                toReturn.push(vals);
            }
        }
        return !single || topk === 1 ? /** @type {AudioClassificationOutput} */ (toReturn) : /** @type {AudioClassificationOutput[]} */ (toReturn)[0];
    }
}

/**
 * @typedef {Object} ZeroShotAudioClassificationOutput
 * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.
 * @property {number} score The score attributed by the model for that label (between 0 and 1).
 * 
 * @typedef {Object} ZeroShotAudioClassificationPipelineOptions Parameters specific to zero-shot audio classification pipelines.
 * @property {string} [hypothesis_template="This is a sound of {}."] The sentence used in conjunction with `candidate_labels`
 * to attempt the audio classification by replacing the placeholder with the candidate_labels.
 * Then likelihood is estimated by using `logits_per_audio`.
 * 
 * @callback ZeroShotAudioClassificationPipelineCallback Classify the sequence(s) given as inputs.
 * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:
 * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate
 * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.
 * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.
 * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).
 * @param {string[]} candidate_labels The candidate labels for this audio.
 * @param {ZeroShotAudioClassificationPipelineOptions} [options] The options to use for zero-shot audio classification.
 * @returns {Promise<ZeroShotAudioClassificationOutput[]|ZeroShotAudioClassificationOutput[][]>} An array of objects containing the predicted labels and scores.
 * 
 * @typedef {TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable} ZeroShotAudioClassificationPipelineType
 */

/**
 * Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you
 * provide an audio and a set of `candidate_labels`.
 * 
 * **Example**: Perform zero-shot audio classification with `Xenova/clap-htsat-unfused`.
 * ```javascript
 * const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused');
 * const audio = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/dog_barking.wav';
 * const candidate_labels = ['dog', 'vaccum cleaner'];
 * const scores = await classifier(audio, candidate_labels);
 * // [
 * //   { score: 0.9993992447853088, label: 'dog' },
 * //   { score: 0.0006007603369653225, label: 'vaccum cleaner' }
 * // ]
 * ```
 */
class ZeroShotAudioClassificationPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ (Pipeline)) {

    /**
     * Create a new ZeroShotAudioClassificationPipeline.
     * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {ZeroShotAudioClassificationPipelineCallback} */
    async _call(audio, candidate_labels, {
        hypothesis_template = "This is a sound of {}."
    } = {}) {

        const single = !Array.isArray(audio);
        if (single) {
            audio = [/** @type {AudioInput} */ (audio)];
        }

        // Insert label into hypothesis template 
        const texts = candidate_labels.map(
            x => hypothesis_template.replace('{}', x)
        );

        // Run tokenization
        const text_inputs = this.tokenizer(texts, {
            padding: true,
            truncation: true,
        });

        const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
        const preparedAudios = await prepareAudios(audio, sampling_rate);

        const toReturn = [];
        for (const aud of preparedAudios) {
            const audio_inputs = await this.processor(aud);

            // Run model with both text and audio inputs
            const output = await this.model({ ...text_inputs, ...audio_inputs });

            // Compute softmax per audio
            const probs = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(output.logits_per_audio.data);

            toReturn.push([...probs].map((x, i) => ({
                score: x,
                label: candidate_labels[i]
            })));
        }
        return single ? toReturn[0] : toReturn;
    }
}

/**
 * @typedef {{stride: number[], input_features: Tensor, is_last: boolean, tokens?: number[], token_timestamps?: number[]}} ChunkCallbackItem
 * @callback ChunkCallback
 * @param {ChunkCallbackItem} chunk The chunk to process.
 */

/**
 * @typedef {Object} Chunk
 * @property {[number, number]} timestamp The start and end timestamp of the chunk in seconds.
 * @property {string} text The recognized text.
 */

/**
 * @typedef {Object} AutomaticSpeechRecognitionOutput
 * @property {string} text The recognized text.
 * @property {Chunk[]} [chunks] When using `return_timestamps`, the `chunks` will become a list
 * containing all the various text chunks identified by the model.
 * 
 * @typedef {Object} AutomaticSpeechRecognitionSpecificParams Parameters specific to automatic-speech-recognition pipelines.
 * @property {boolean|'word'} [kwargs.return_timestamps] Whether to return timestamps or not. Default is `false`.
 * @property {number} [kwargs.chunk_length_s] The length of audio chunks to process in seconds. Default is 0 (no chunking).
 * @property {number} [kwargs.stride_length_s] The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`.
 * @property {ChunkCallback} [kwargs.chunk_callback] Callback function to be called with each chunk processed.
 * @property {boolean} [kwargs.force_full_sequences] Whether to force outputting full sequences or not. Default is `false`.
 * @property {string} [kwargs.language] The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known.
 * @property {string} [kwargs.task] The task to perform. Default is `null`, meaning it should be auto-detected.
 * @property {number[][]} [kwargs.forced_decoder_ids] A list of pairs of integers which indicates a mapping from generation indices to token indices
 * that will be forced before sampling. For example, [[1, 123]] means the second generated token will always be a token of index 123.
 * @property {number} [num_frames] The number of frames in the input audio.
 * @typedef {import('./utils/generation.js').GenerationConfigType & AutomaticSpeechRecognitionSpecificParams} AutomaticSpeechRecognitionConfig
 * 
 * @callback AutomaticSpeechRecognitionPipelineCallback Transcribe the audio sequence(s) given as inputs to text.
 * @param {AudioPipelineInputs} audio The input audio file(s) to be transcribed. The input is either:
 * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate
 * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.
 * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.
 * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).
 * @param {AutomaticSpeechRecognitionConfig} [options] Additional keyword arguments to pass along to the generate method of the model.
 * @returns {Promise<AutomaticSpeechRecognitionOutput|AutomaticSpeechRecognitionOutput[]>} An object containing the transcription text and optionally timestamps if `return_timestamps` is `true`.
 * 
 * @typedef {TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable} AutomaticSpeechRecognitionPipelineType
 */

/**
 * Pipeline that aims at extracting spoken text contained within some audio.
 *
 * **Example:** Transcribe English.
 * ```javascript
 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
 * const output = await transcriber(url);
 * // { text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country." }
 * ```
 * 
 * **Example:** Transcribe English w/ timestamps.
 * ```javascript
 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
 * const output = await transcriber(url, { return_timestamps: true });
 * // {
 * //   text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country."
 * //   chunks: [
 * //     { timestamp: [0, 8],  text: " And so my fellow Americans ask not what your country can do for you" }
 * //     { timestamp: [8, 11], text: " ask what you can do for your country." }
 * //   ]
 * // }
 * ```
 * 
 * **Example:** Transcribe English w/ word-level timestamps.
 * ```javascript
 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
 * const output = await transcriber(url, { return_timestamps: 'word' });
 * // {
 * //   "text": " And so my fellow Americans ask not what your country can do for you ask what you can do for your country.",
 * //   "chunks": [
 * //     { "text": " And", "timestamp": [0, 0.78] },
 * //     { "text": " so", "timestamp": [0.78, 1.06] },
 * //     { "text": " my", "timestamp": [1.06, 1.46] },
 * //     ...
 * //     { "text": " for", "timestamp": [9.72, 9.92] },
 * //     { "text": " your", "timestamp": [9.92, 10.22] },
 * //     { "text": " country.", "timestamp": [10.22, 13.5] }
 * //   ]
 * // }
 * ```
 * 
 * **Example:** Transcribe French.
 * ```javascript
 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';
 * const output = await transcriber(url, { language: 'french', task: 'transcribe' });
 * // { text: " J'adore, j'aime, je n'aime pas, je déteste." }
 * ```
 * 
 * **Example:** Translate French to English.
 * ```javascript
 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';
 * const output = await transcriber(url, { language: 'french', task: 'translate' });
 * // { text: " I love, I like, I don't like, I hate." }
 * ```
 * 
 * **Example:** Transcribe/translate audio longer than 30 seconds.
 * ```javascript
 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/ted_60.wav';
 * const output = await transcriber(url, { chunk_length_s: 30, stride_length_s: 5 });
 * // { text: " So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up" }
 * ```
 */
class AutomaticSpeechRecognitionPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ (Pipeline)) {

    /**
     * Create a new AutomaticSpeechRecognitionPipeline.
     * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {AutomaticSpeechRecognitionPipelineCallback} */
    async _call(audio, kwargs = {}) {
        switch (this.model.config.model_type) {
            case 'whisper':
                return this._call_whisper(audio, kwargs)
            case 'wav2vec2':
            case 'wav2vec2-bert':
            case 'unispeech':
            case 'unispeech-sat':
            case 'hubert':
                return this._call_wav2vec2(audio, kwargs)
            default:
                throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)
        }
    }

    /**
     * @type {AutomaticSpeechRecognitionPipelineCallback}
     * @private
     */
    async _call_wav2vec2(audio, kwargs = {}) {
        // TODO use kwargs

        if (kwargs.language) {
            console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".');
        }
        if (kwargs.task) {
            console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');
        }

        const single = !Array.isArray(audio);
        if (single) {
            audio = [/** @type {AudioInput} */ (audio)];
        }

        const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
        const preparedAudios = await prepareAudios(audio, sampling_rate);

        const toReturn = [];
        for (const aud of preparedAudios) {
            const inputs = await this.processor(aud);
            const output = await this.model(inputs);
            const logits = output.logits[0];

            const predicted_ids = [];
            for (const item of logits) {
                predicted_ids.push((0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.max)(item.data)[1])
            }
            const predicted_sentences = this.tokenizer.decode(predicted_ids)
            toReturn.push({ text: predicted_sentences })
        }
        return single ? toReturn[0] : toReturn;
    }

    /**
     * @type {AutomaticSpeechRecognitionPipelineCallback}
     * @private
     */
    async _call_whisper(audio, kwargs = {}) {

        const return_timestamps = kwargs.return_timestamps ?? false;
        const chunk_length_s = kwargs.chunk_length_s ?? 0;
        const chunk_callback = kwargs.chunk_callback ?? null;
        const force_full_sequences = kwargs.force_full_sequences ?? false;
        let stride_length_s = kwargs.stride_length_s ?? null;

        if (return_timestamps === 'word') {
            kwargs['return_token_timestamps'] = true;
        }

        const language = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_3__.pop)(kwargs, 'language', null);
        const task = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_3__.pop)(kwargs, 'task', null);

        if (language || task || return_timestamps) {
            if (kwargs.forced_decoder_ids) {
                throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.")
            }
            // @ts-ignore
            const decoder_prompt_ids = this.tokenizer.get_decoder_prompt_ids({ language, task, no_timestamps: !return_timestamps })
            if (decoder_prompt_ids.length > 0) {
                kwargs.forced_decoder_ids = decoder_prompt_ids;
            }
        }

        const single = !Array.isArray(audio);
        if (single) {
            audio = [/** @type {AudioInput} */ (audio)];
        }

        const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions;
        const hop_length = this.processor.feature_extractor.config.hop_length;

        const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
        const preparedAudios = await prepareAudios(audio, sampling_rate);

        const toReturn = [];
        for (const aud of preparedAudios) {
            /** @type {ChunkCallbackItem[]} */
            let chunks = [];
            if (chunk_length_s > 0) {
                if (stride_length_s === null) {
                    stride_length_s = chunk_length_s / 6;
                } else if (chunk_length_s <= stride_length_s) {
                    throw Error("`chunk_length_s` must be larger than `stride_length_s`.")
                }

                // TODO support different stride_length_s (for left and right)

                const window = sampling_rate * chunk_length_s;
                const stride = sampling_rate * stride_length_s;
                const jump = window - 2 * stride;
                let offset = 0;

                // Create subarrays of audio with overlaps

                while (offset < aud.length) {
                    const subarr = aud.subarray(offset, offset + window);
                    const feature = await this.processor(subarr);

                    const isFirst = offset === 0;
                    const isLast = offset + jump >= aud.length;
                    chunks.push({
                        stride: [
                            subarr.length,
                            isFirst ? 0 : stride,
                            isLast ? 0 : stride
                        ],
                        input_features: feature.input_features,
                        is_last: isLast
                    })
                    offset += jump;
                }

            } else {
                chunks = [{
                    stride: [aud.length, 0, 0],
                    input_features: (await this.processor(aud)).input_features,
                    is_last: true
                }]
            }

            // Generate for each set of input features
            for (const chunk of chunks) {
                kwargs.num_frames = Math.floor(chunk.stride[0] / hop_length);

                // NOTE: doing sequentially for now
                const data = await this.model.generate(chunk.input_features, kwargs);

                // TODO: Right now we only get top beam
                if (return_timestamps === 'word') {
                    chunk.tokens = data.sequences[0];
                    chunk.token_timestamps = data.token_timestamps.tolist()[0].map(
                        (/** @type {number} */ x) => (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.round)(x, 2)
                    );

                } else {
                    chunk.tokens = data[0];
                }

                // convert stride to seconds
                chunk.stride = chunk.stride.map(x => x / sampling_rate);

                if (chunk_callback !== null) {
                    chunk_callback(chunk)
                }
            }

            // Merge text chunks
            // @ts-ignore
            const [full_text, optional] = this.tokenizer._decode_asr(chunks, {
                time_precision, return_timestamps, force_full_sequences
            });

            toReturn.push({ text: full_text, ...optional })
        }
        return single ? toReturn[0] : toReturn;
    }
}

/**
 * @typedef {Object} ImageToTextSingle
 * @property {string} generated_text The generated text.
 * @typedef {ImageToTextSingle[]} ImageToTextOutput
 * 
 * @callback ImageToTextPipelineCallback Assign labels to the image(s) passed as inputs.
 * @param {ImagePipelineInputs} texts The images to be captioned.
 * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model.
 * @returns {Promise<ImageToTextOutput|ImageToTextOutput[]>} An object (or array of objects) containing the generated text(s).
 * 
 * @typedef {TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable} ImageToTextPipelineType
 */

/**
 * Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image.
 * 
 * **Example:** Generate a caption for an image w/ `Xenova/vit-gpt2-image-captioning`.
 * ```javascript
 * const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
 * const output = await captioner(url);
 * // [{ generated_text: 'a cat laying on a couch with another cat' }]
 * ```
 * 
 * **Example:** Optical Character Recognition (OCR) w/ `Xenova/trocr-small-handwritten`.
 * ```javascript
 * const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwriting.jpg';
 * const output = await captioner(url);
 * // [{ generated_text: 'Mr. Brown commented icily.' }]
 * ```
 */
class ImageToTextPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ (Pipeline)) {

    /**
     * Create a new ImageToTextPipeline.
     * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {ImageToTextPipelineCallback} */
    async _call(images, generate_kwargs = {}) {

        const isBatched = Array.isArray(images);
        const preparedImages = await prepareImages(images);

        const { pixel_values } = await this.processor(preparedImages);

        const toReturn = [];
        for (const batch of pixel_values) {
            batch.dims = [1, ...batch.dims]
            const output = await this.model.generate(batch, generate_kwargs);
            const decoded = this.tokenizer.batch_decode(output, {
                skip_special_tokens: true,
            }).map(x => ({ generated_text: x.trim() }))
            toReturn.push(decoded);
        }

        return isBatched ? toReturn : toReturn[0];
    }
}

/**
 * @typedef {Object} ImageClassificationSingle
 * @property {string} label The label identified by the model.
 * @property {number} score The score attributed by the model for that label.
 * @typedef {ImageClassificationSingle[]} ImageClassificationOutput
 * 
 * @typedef {Object} ImageClassificationPipelineOptions Parameters specific to image classification pipelines.
 * @property {number} [topk=1] The number of top labels that will be returned by the pipeline. 
 * 
 * @callback ImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.
 * @param {ImagePipelineInputs} images The input images(s) to be classified.
 * @param {ImageClassificationPipelineOptions} [options] The options to use for image classification.
 * @returns {Promise<ImageClassificationOutput|ImageClassificationOutput[]>} An array or object containing the predicted labels and scores.
 * 
 * @typedef {ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable} ImageClassificationPipelineType
 */

/**
 * Image classification pipeline using any `AutoModelForImageClassification`.
 * This pipeline predicts the class of an image.
 * 
 * **Example:** Classify an image.
 * ```javascript
 * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
 * const output = await classifier(url);
 * // [
 * //   { label: 'tiger, Panthera tigris', score: 0.632695734500885 },
 * // ]
 * ```
 * 
 * **Example:** Classify an image and return top `n` classes.
 * ```javascript
 * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
 * const output = await classifier(url, { topk: 3 });
 * // [
 * //   { label: 'tiger, Panthera tigris', score: 0.632695734500885 },
 * //   { label: 'tiger cat', score: 0.3634825646877289 },
 * //   { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },
 * // ]
 * ```
 * 
 * **Example:** Classify an image and return all classes.
 * ```javascript
 * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
 * const output = await classifier(url, { topk: 0 });
 * // [
 * //   { label: 'tiger, Panthera tigris', score: 0.632695734500885 },
 * //   { label: 'tiger cat', score: 0.3634825646877289 },
 * //   { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },
 * //   { label: 'jaguar, panther, Panthera onca, Felis onca', score: 0.00035465499968267977 },
 * //   ...
 * // ]
 * ```
 */
class ImageClassificationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ (Pipeline)) {

    /**
     * Create a new ImageClassificationPipeline.
     * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {ImageClassificationPipelineCallback} */
    async _call(images, {
        topk = 1
    } = {}) {

        const isBatched = Array.isArray(images);
        const preparedImages = await prepareImages(images);

        const { pixel_values } = await this.processor(preparedImages);
        const output = await this.model({ pixel_values });

        const id2label = this.model.config.id2label;
        const toReturn = [];
        for (const batch of output.logits) {
            const scores = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.getTopItems)((0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(batch.data), topk);

            const vals = scores.map(x => ({
                label: id2label[x[0]],
                score: x[1],
            }));
            if (topk === 1) {
                toReturn.push(...vals);
            } else {
                toReturn.push(vals);
            }
        }

        return isBatched || topk === 1 ? /** @type {ImageClassificationOutput} */ (toReturn) : /** @type {ImageClassificationOutput[]} */ (toReturn)[0];
    }

}

/**
 * @typedef {Object} ImageSegmentationPipelineOutput
 * @property {string} label The label of the segment.
 * @property {number|null} score The score of the segment.
 * @property {RawImage} mask The mask of the segment.
 * 
 * @typedef {Object} ImageSegmentationPipelineOptions Parameters specific to image segmentation pipelines.
 * @property {number} [threshold=0.5] Probability threshold to filter out predicted masks.
 * @property {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.
 * @property {number} [overlap_mask_area_threshold=0.8] Mask overlap threshold to eliminate small, disconnected segments.
 * @property {null|string} [subtask=null] Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`],
 * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order).
 * @property {number[]} [label_ids_to_fuse=null] List of label ids to fuse. If not set, do not fuse any labels.
 * @property {number[][]} [target_sizes=null] List of target sizes for the input images. If not set, use the original image sizes.
 * 
 * @callback ImageSegmentationPipelineCallback Segment the input images.
 * @param {ImagePipelineInputs} images The input images.
 * @param {ImageSegmentationPipelineOptions} [options] The options to use for image segmentation.
 * @returns {Promise<ImageSegmentationPipelineOutput[]>} The annotated segments.
 * 
 * @typedef {ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable} ImageSegmentationPipelineType
 */

/**
 * Image segmentation pipeline using any `AutoModelForXXXSegmentation`.
 * This pipeline predicts masks of objects and their classes.
 * 
 * **Example:** Perform image segmentation with `Xenova/detr-resnet-50-panoptic`.
 * ```javascript
 * const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
 * const output = await segmenter(url);
 * // [
 * //   { label: 'remote', score: 0.9984649419784546, mask: RawImage { ... } },
 * //   { label: 'cat', score: 0.9994316101074219, mask: RawImage { ... } }
 * // ]
 * ```
 */
class ImageSegmentationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ (Pipeline)) {
    /**
     * Create a new ImageSegmentationPipeline.
     * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);

        this.subtasks_mapping = {
            // Mapping of subtasks to their corresponding post-processing function names.
            panoptic: 'post_process_panoptic_segmentation',
            instance: 'post_process_instance_segmentation',
            semantic: 'post_process_semantic_segmentation'
        }
    }

    /** @type {ImageSegmentationPipelineCallback} */
    async _call(images, {
        threshold = 0.5,
        mask_threshold = 0.5,
        overlap_mask_area_threshold = 0.8,
        label_ids_to_fuse = null,
        target_sizes = null,
        subtask = null,
    } = {}) {
        const isBatched = Array.isArray(images);

        if (isBatched && images.length !== 1) {
            throw Error("Image segmentation pipeline currently only supports a batch size of 1.");
        }

        const preparedImages = await prepareImages(images);
        const imageSizes = preparedImages.map(x => [x.height, x.width]);

        const { pixel_values, pixel_mask } = await this.processor(preparedImages);
        const output = await this.model({ pixel_values, pixel_mask });

        let fn = null;
        if (subtask !== null) {
            fn = this.subtasks_mapping[subtask];
        } else {
            for (let [task, func] of Object.entries(this.subtasks_mapping)) {
                if (func in this.processor.feature_extractor) {
                    fn = this.processor.feature_extractor[func].bind(this.processor.feature_extractor);
                    subtask = task;
                    break;
                }
            }
        }

        const id2label = this.model.config.id2label;

        /** @type {ImageSegmentationPipelineOutput[]} */
        const annotation = [];
        if (subtask === 'panoptic' || subtask === 'instance') {
            const processed = fn(
                output,
                threshold,
                mask_threshold,
                overlap_mask_area_threshold,
                label_ids_to_fuse,
                target_sizes ?? imageSizes, // TODO FIX?
            )[0];

            const segmentation = processed.segmentation;

            for (const segment of processed.segments_info) {
                const maskData = new Uint8ClampedArray(segmentation.data.length);
                for (let i = 0; i < segmentation.data.length; ++i) {
                    if (segmentation.data[i] === segment.id) {
                        maskData[i] = 255;
                    }
                }

                const mask = new _utils_image_js__WEBPACK_IMPORTED_MODULE_7__.RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1)

                annotation.push({
                    score: segment.score,
                    label: id2label[segment.label_id],
                    mask: mask
                })
            }

        } else if (subtask === 'semantic') {
            const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0];

            for (const label of labels) {
                const maskData = new Uint8ClampedArray(segmentation.data.length);
                for (let i = 0; i < segmentation.data.length; ++i) {
                    if (segmentation.data[i] === label) {
                        maskData[i] = 255;
                    }
                }

                const mask = new _utils_image_js__WEBPACK_IMPORTED_MODULE_7__.RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1);

                annotation.push({
                    score: null,
                    label: id2label[label],
                    mask: mask
                });
            }
        } else {
            throw Error(`Subtask ${subtask} not supported.`);
        }

        return annotation;
    }
}

/**
 * @typedef {Object} ZeroShotImageClassificationOutput
 * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.
 * @property {number} score The score attributed by the model for that label (between 0 and 1).
 * 
 * @typedef {Object} ZeroShotImageClassificationPipelineOptions Parameters specific to zero-shot image classification pipelines.
 * @property {string} [hypothesis_template="This is a photo of {}"] The sentence used in conjunction with `candidate_labels`
 * to attempt the image classification by replacing the placeholder with the candidate_labels.
 * Then likelihood is estimated by using `logits_per_image`.
 * 
 * @callback ZeroShotImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.
 * @param {ImagePipelineInputs} images The input images.
 * @param {string[]} candidate_labels The candidate labels for this image.
 * @param {ZeroShotImageClassificationPipelineOptions} [options] The options to use for zero-shot image classification.
 * @returns {Promise<ZeroShotImageClassificationOutput[]|ZeroShotImageClassificationOutput[][]>} An array of objects containing the predicted labels and scores.
 * 
 * @typedef {TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable} ZeroShotImageClassificationPipelineType
 */

/**
 * Zero shot image classification pipeline. This pipeline predicts the class of
 * an image when you provide an image and a set of `candidate_labels`.
 * 
 * **Example:** Zero shot image classification w/ `Xenova/clip-vit-base-patch32`.
 * ```javascript
 * const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
 * const output = await classifier(url, ['tiger', 'horse', 'dog']);
 * // [
 * //   { score: 0.9993917942047119, label: 'tiger' },
 * //   { score: 0.0003519294841680676, label: 'horse' },
 * //   { score: 0.0002562698791734874, label: 'dog' }
 * // ]
 * ```
 */
class ZeroShotImageClassificationPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ (Pipeline)) {
    /**
     * Create a new ZeroShotImageClassificationPipeline.
     * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {ZeroShotImageClassificationPipelineCallback} */
    async _call(images, candidate_labels, {
        hypothesis_template = "This is a photo of {}"
    } = {}) {

        const isBatched = Array.isArray(images);
        const preparedImages = await prepareImages(images);

        // Insert label into hypothesis template 
        const texts = candidate_labels.map(
            x => hypothesis_template.replace('{}', x)
        );

        // Run tokenization
        const text_inputs = this.tokenizer(texts, {
            padding: this.model.config.model_type === 'siglip' ? 'max_length' : true,
            truncation: true,
        });

        // Run processor
        const { pixel_values } = await this.processor(preparedImages);

        // Run model with both text and pixel inputs
        const output = await this.model({ ...text_inputs, pixel_values });

        const function_to_apply =
            this.model.config.model_type === 'siglip'
                ? batch => batch.sigmoid().data
                : batch => (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.softmax)(batch.data);

        // Compare each image with each candidate label
        const toReturn = [];
        for (const batch of output.logits_per_image) {
            // Compute softmax per image
            const probs = function_to_apply(batch);

            const result = [...probs].map((x, i) => ({
                score: x,
                label: candidate_labels[i]
            }));
            result.sort((a, b) => b.score - a.score); // sort by score in descending order
            toReturn.push(result);
        }

        return isBatched ? toReturn : toReturn[0];
    }
}


/**
 * @typedef {Object} ObjectDetectionPipelineSingle
 * @property {string} label The class label identified by the model.
 * @property {number} score The score attributed by the model for that label.
 * @property {BoundingBox} box The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true.
 * @typedef {ObjectDetectionPipelineSingle[]} ObjectDetectionPipelineOutput
 * 
 * @typedef {Object} ObjectDetectionPipelineOptions Parameters specific to object detection pipelines.
 * @property {number} [threshold=0.9] The threshold used to filter boxes by score.
 * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).
 * 
 * @callback ObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
 * @param {ImagePipelineInputs} images The input images.
 * @param {ObjectDetectionPipelineOptions} [options] The options to use for object detection.
 * @returns {Promise<ObjectDetectionPipelineOutput|ObjectDetectionPipelineOutput[]>} A list of objects or a list of list of objects. 
 * 
 * @typedef {ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable} ObjectDetectionPipelineType
 */

/**
 * Object detection pipeline using any `AutoModelForObjectDetection`.
 * This pipeline predicts bounding boxes of objects and their classes.
 * 
 * **Example:** Run object-detection with `Xenova/detr-resnet-50`.
 * ```javascript
 * const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');
 * const img = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
 * const output = await detector(img, { threshold: 0.9 });
 * // [{
 * //   score: 0.9976370930671692,
 * //   label: "remote",
 * //   box: { xmin: 31, ymin: 68, xmax: 190, ymax: 118 }
 * // },
 * // ...
 * // {
 * //   score: 0.9984092116355896,
 * //   label: "cat",
 * //   box: { xmin: 331, ymin: 19, xmax: 649, ymax: 371 }
 * // }]
 * ```
 */
class ObjectDetectionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ (Pipeline)) {

    /**
     * Create a new ObjectDetectionPipeline.
     * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {ObjectDetectionPipelineCallback} */
    async _call(images, {
        threshold = 0.9,
        percentage = false,
    } = {}) {

        const isBatched = Array.isArray(images);

        if (isBatched && images.length !== 1) {
            throw Error("Object detection pipeline currently only supports a batch size of 1.");
        }
        const preparedImages = await prepareImages(images);

        const imageSizes = percentage ? null : preparedImages.map(x => [x.height, x.width]);

        const { pixel_values, pixel_mask } = await this.processor(preparedImages);
        const output = await this.model({ pixel_values, pixel_mask });

        // @ts-ignore
        const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes);

        // Add labels
        const id2label = this.model.config.id2label;

        // Format output
        /** @type {ObjectDetectionPipelineOutput[]} */
        const result = processed.map(batch => (
            batch.boxes.map((box, i) => ({
                score: batch.scores[i],
                label: id2label[batch.classes[i]],
                box: get_bounding_box(box, !percentage),
            }))
        ))

        return isBatched ? result : result[0];
    }
}


/**
 * @typedef {Object} ZeroShotObjectDetectionOutput
 * @property {string} label Text query corresponding to the found object.
 * @property {number} score Score corresponding to the object (between 0 and 1).
 * @property {BoundingBox} box Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true.
 * 
 * @typedef {Object} ZeroShotObjectDetectionPipelineOptions Parameters specific to zero-shot object detection pipelines.
 * @property {number} [threshold=0.1] The probability necessary to make a prediction.
 * @property {number} [topk=null] The number of top predictions that will be returned by the pipeline.
 * If the provided number is `null` or higher than the number of predictions available, it will default
 * to the number of predictions.
 * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).
 * 
 * @callback ZeroShotObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
 * @param {ImagePipelineInputs} images The input images.
 * @param {string[]} candidate_labels What the model should recognize in the image.
 * @param {ZeroShotObjectDetectionPipelineOptions} [options] The options to use for zero-shot object detection.
 * @returns {Promise<ZeroShotObjectDetectionOutput[]|ZeroShotObjectDetectionOutput[][]>} An array of objects containing the predicted labels, scores, and bounding boxes.
 * 
 * @typedef {TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable} ZeroShotObjectDetectionPipelineType
 */

/**
 * Zero-shot object detection pipeline. This pipeline predicts bounding boxes of
 * objects when you provide an image and a set of `candidate_labels`.
 * 
 * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32`.
 * ```javascript
 * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/astronaut.png';
 * const candidate_labels = ['human face', 'rocket', 'helmet', 'american flag'];
 * const output = await detector(url, candidate_labels);
 * // [
 * //   {
 * //     score: 0.24392342567443848,
 * //     label: 'human face',
 * //     box: { xmin: 180, ymin: 67, xmax: 274, ymax: 175 }
 * //   },
 * //   {
 * //     score: 0.15129457414150238,
 * //     label: 'american flag',
 * //     box: { xmin: 0, ymin: 4, xmax: 106, ymax: 513 }
 * //   },
 * //   {
 * //     score: 0.13649864494800568,
 * //     label: 'helmet',
 * //     box: { xmin: 277, ymin: 337, xmax: 511, ymax: 511 }
 * //   },
 * //   {
 * //     score: 0.10262022167444229,
 * //     label: 'rocket',
 * //     box: { xmin: 352, ymin: -1, xmax: 463, ymax: 287 }
 * //   }
 * // ]
 * ```
 * 
 * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32` (returning top 4 matches and setting a threshold).
 * ```javascript
 * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/beach.png';
 * const candidate_labels = ['hat', 'book', 'sunglasses', 'camera'];
 * const output = await detector(url, candidate_labels, { topk: 4, threshold: 0.05 });
 * // [
 * //   {
 * //     score: 0.1606510728597641,
 * //     label: 'sunglasses',
 * //     box: { xmin: 347, ymin: 229, xmax: 429, ymax: 264 }
 * //   },
 * //   {
 * //     score: 0.08935828506946564,
 * //     label: 'hat',
 * //     box: { xmin: 38, ymin: 174, xmax: 258, ymax: 364 }
 * //   },
 * //   {
 * //     score: 0.08530698716640472,
 * //     label: 'camera',
 * //     box: { xmin: 187, ymin: 350, xmax: 260, ymax: 411 }
 * //   },
 * //   {
 * //     score: 0.08349756896495819,
 * //     label: 'book',
 * //     box: { xmin: 261, ymin: 280, xmax: 494, ymax: 425 }
 * //   }
 * // ]
 * ```
 */
class ZeroShotObjectDetectionPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ (Pipeline)) {

    /**
     * Create a new ZeroShotObjectDetectionPipeline.
     * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {ZeroShotObjectDetectionPipelineCallback} */
    async _call(images, candidate_labels, {
        threshold = 0.1,
        topk = null,
        percentage = false,
    } = {}) {

        const isBatched = Array.isArray(images);
        const preparedImages = await prepareImages(images);

        // Run tokenization
        const text_inputs = this.tokenizer(candidate_labels, {
            padding: true,
            truncation: true,
        });

        // Run processor
        const model_inputs = await this.processor(preparedImages);

        // Since non-maximum suppression is performed for exporting, we need to
        // process each image separately. For more information, see:
        // https://github.com/huggingface/optimum/blob/e3b7efb1257c011db907ef40ab340e795cc5684c/optimum/exporters/onnx/model_configs.py#L1028-L1032
        const toReturn = [];
        for (let i = 0; i < preparedImages.length; ++i) {
            const image = preparedImages[i];
            const imageSize = percentage ? null : [[image.height, image.width]];
            const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0);

            // Run model with both text and pixel inputs
            const output = await this.model({ ...text_inputs, pixel_values });

            // @ts-ignore
            const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0];
            let result = processed.boxes.map((box, i) => ({
                score: processed.scores[i],
                label: candidate_labels[processed.classes[i]],
                box: get_bounding_box(box, !percentage),
            })).sort((a, b) => b.score - a.score);
            if (topk !== null) {
                result = result.slice(0, topk);
            }
            toReturn.push(result)
        }

        return isBatched ? toReturn : toReturn[0];
    }
}

/**
 * @typedef {Object} DocumentQuestionAnsweringSingle
 * @property {string} answer The generated text.
 * @typedef {DocumentQuestionAnsweringSingle[]} DocumentQuestionAnsweringOutput
 * 
 * @callback DocumentQuestionAnsweringPipelineCallback Answer the question given as input by using the document.
 * @param {ImageInput} image The image of the document to use.
 * @param {string} question A question to ask of the document.
 * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model.
 * @returns {Promise<DocumentQuestionAnsweringOutput|DocumentQuestionAnsweringOutput[]>} An object (or array of objects) containing the answer(s).
 * 
 * @typedef {TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable} DocumentQuestionAnsweringPipelineType
 */

/**
 * Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`.
 * The inputs/outputs are similar to the (extractive) question answering pipeline; however,
 * the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context.
 * 
 * **Example:** Answer questions about a document with `Xenova/donut-base-finetuned-docvqa`.
 * ```javascript
 * const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa');
 * const image = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';
 * const question = 'What is the invoice number?';
 * const output = await qa_pipeline(image, question);
 * // [{ answer: 'us-001' }]
 * ```
 */
class DocumentQuestionAnsweringPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ (Pipeline)) {

    /**
     * Create a new DocumentQuestionAnsweringPipeline.
     * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {DocumentQuestionAnsweringPipelineCallback} */
    async _call(image, question, generate_kwargs = {}) {

        // NOTE: For now, we only support a batch size of 1

        // Preprocess image
        const preparedImage = (await prepareImages(image))[0];
        const { pixel_values } = await this.processor(preparedImage);

        // Run tokenization
        const task_prompt = `<s_docvqa><s_question>${question}</s_question><s_answer>`;
        const decoder_input_ids = this.tokenizer(task_prompt, {
            add_special_tokens: false,
            padding: true,
            truncation: true,
        }).input_ids;

        // Run model
        const output = await this.model.generate(
            pixel_values,
            {
                ...generate_kwargs,
                decoder_input_ids,
                max_length: this.model.config.decoder.max_position_embeddings,
            }
        );

        // Decode output
        const decoded = this.tokenizer.batch_decode(output)[0];

        // Parse answer
        const match = decoded.match(/<s_answer>(.*?)<\/s_answer>/);
        let answer = null;
        if (match && match.length >= 2) {
            answer = match[1].trim();
        }
        return [{ answer }];
    }
}


/**
 * @typedef {Object} VocoderOptions
 * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder.
 * @typedef {TextAudioPipelineConstructorArgs & VocoderOptions} TextToAudioPipelineConstructorArgs
 */

/**
 * @typedef {Object} TextToAudioOutput
 * @property {Float32Array} audio The generated audio waveform.
 * @property {number} sampling_rate The sampling rate of the generated audio waveform.
 * 
 * @typedef {Object} TextToAudioPipelineOptions Parameters specific to text-to-audio pipelines.
 * @property {Tensor|Float32Array|string|URL} [speaker_embeddings=null] The speaker embeddings (if the model requires it).
 * 
 * @callback TextToAudioPipelineCallback Generates speech/audio from the inputs.
 * @param {string|string[]} texts The text(s) to generate.
 * @param {TextToAudioPipelineOptions} options Parameters passed to the model generation/forward method.
 * @returns {Promise<TextToAudioOutput>} An object containing the generated audio and sampling rate.
 * 
 * @typedef {TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable} TextToAudioPipelineType
 */

/**
 * Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`.
 * This pipeline generates an audio file from an input text and optional other conditional inputs.
 * 
 * **Example:** Generate audio from text with `Xenova/speecht5_tts`.
 * ```javascript
 * const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });
 * const speaker_embeddings = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin';
 * const out = await synthesizer('Hello, my dog is cute', { speaker_embeddings });
 * // {
 * //   audio: Float32Array(26112) [-0.00005657337896991521, 0.00020583874720614403, ...],
 * //   sampling_rate: 16000
 * // }
 * ```
 * 
 * You can then save the audio to a .wav file with the `wavefile` package:
 * ```javascript
 * import wavefile from 'wavefile';
 * import fs from 'fs';
 * 
 * const wav = new wavefile.WaveFile();
 * wav.fromScratch(1, out.sampling_rate, '32f', out.audio);
 * fs.writeFileSync('out.wav', wav.toBuffer());
 * ```
 * 
 * **Example:** Multilingual speech generation with `Xenova/mms-tts-fra`. See [here](https://huggingface.co/models?pipeline_tag=text-to-speech&other=vits&sort=trending) for the full list of available languages (1107).
 * ```javascript
 * const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra');
 * const out = await synthesizer('Bonjour');
 * // {
 * //   audio: Float32Array(23808) [-0.00037693005288019776, 0.0003325853613205254, ...],
 * //   sampling_rate: 16000
 * // }
 * ```
 */
class TextToAudioPipeline extends (/** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ (Pipeline)) {
    DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan"

    /**
     * Create a new TextToAudioPipeline.
     * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);

        // TODO: Find a better way for `pipeline` to set the default vocoder
        this.vocoder = options.vocoder ?? null;
    }


    /** @type {TextToAudioPipelineCallback} */
    async _call(text_inputs, {
        speaker_embeddings = null,
    } = {}) {

        // If this.processor is not set, we are using a `AutoModelForTextToWaveform` model
        if (this.processor) {
            return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings });
        } else {
            return this._call_text_to_waveform(text_inputs);
        }
    }

    async _call_text_to_waveform(text_inputs) {

        // Run tokenization
        const inputs = this.tokenizer(text_inputs, {
            padding: true,
            truncation: true,
        });

        // Generate waveform
        const { waveform } = await this.model(inputs);

        const sampling_rate = this.model.config.sampling_rate;
        return {
            audio: waveform.data,
            sampling_rate,
        }
    }

    async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) {

        // Load vocoder, if not provided
        if (!this.vocoder) {
            console.log('No vocoder specified, using default HifiGan vocoder.');
            this.vocoder = await _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { quantized: false });
        }

        // Load speaker embeddings as Float32Array from path/URL
        if (typeof speaker_embeddings === 'string' || speaker_embeddings instanceof URL) {
            // Load from URL with fetch
            speaker_embeddings = new Float32Array(
                await (await fetch(speaker_embeddings)).arrayBuffer()
            );
        }

        if (speaker_embeddings instanceof Float32Array) {
            speaker_embeddings = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_6__.Tensor(
                'float32',
                speaker_embeddings,
                [1, speaker_embeddings.length]
            )
        } else if (!(speaker_embeddings instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_6__.Tensor)) {
            throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.")
        }

        // Run tokenization
        const { input_ids } = this.tokenizer(text_inputs, {
            padding: true,
            truncation: true,
        });

        // NOTE: At this point, we are guaranteed that `speaker_embeddings` is a `Tensor`
        // @ts-ignore
        const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder });

        const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
        return {
            audio: waveform.data,
            sampling_rate,
        }
    }
}

/**
 * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs.
 * @param {ImagePipelineInputs} images The images to transform.
 * @returns {Promise<RawImage|RawImage[]>} The transformed image or list of images.
 * 
 * @typedef {ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable} ImageToImagePipelineType
 */

/**
 * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input.
 * 
 * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`
 * ```javascript
 * const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';
 * const output = await upscaler(url);
 * // RawImage {
 * //   data: Uint8Array(786432) [ 41, 31, 24,  43, ... ],
 * //   width: 512,
 * //   height: 512,
 * //   channels: 3
 * // }
 * ```
 */
class ImageToImagePipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ (Pipeline)) {
    /**
     * Create a new ImageToImagePipeline.
     * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {ImageToImagePipelineCallback} */
    async _call(images) {

        const preparedImages = await prepareImages(images);
        const inputs = await this.processor(preparedImages);
        const outputs = await this.model(inputs);

        /** @type {RawImage[]} */
        const toReturn = [];
        for (const batch of outputs.reconstruction) {
            const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');
            toReturn.push(_utils_image_js__WEBPACK_IMPORTED_MODULE_7__.RawImage.fromTensor(output));
        }

        return toReturn.length > 1 ? toReturn : toReturn[0];
    }
}

/**
 * @typedef {Object} DepthEstimationPipelineOutput
 * @property {Tensor} predicted_depth The raw depth map predicted by the model.
 * @property {RawImage} depth The processed depth map as an image (with the same size as the input image).
 * 
 * @callback DepthEstimationPipelineCallback Predicts the depth for the image(s) passed as inputs.
 * @param {ImagePipelineInputs} images The images to compute depth for.
 * @returns {Promise<DepthEstimationPipelineOutput|DepthEstimationPipelineOutput[]>} An image or a list of images containing result(s).
 * 
 * @typedef {ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable} DepthEstimationPipelineType
 */

/**
 * Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.
 * 
 * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`
 * ```javascript
 * const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas');
 * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
 * const out = await depth_estimator(url);
 * // {
 * //   predicted_depth: Tensor {
 * //     dims: [ 384, 384 ],
 * //     type: 'float32',
 * //     data: Float32Array(147456) [ 542.859130859375, 545.2833862304688, 546.1649169921875, ... ],
 * //     size: 147456
 * //   },
 * //   depth: RawImage {
 * //     data: Uint8Array(307200) [ 86, 86, 86, ... ],
 * //     width: 640,
 * //     height: 480,
 * //     channels: 1
 * //   }
 * // }
 * ```
 */
class DepthEstimationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ (Pipeline)) {
    /**
     * Create a new DepthEstimationPipeline.
     * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
     */
    constructor(options) {
        super(options);
    }

    /** @type {DepthEstimationPipelineCallback} */
    async _call(images) {

        const preparedImages = await prepareImages(images);

        const inputs = await this.processor(preparedImages);
        const { predicted_depth } = await this.model(inputs);

        const toReturn = [];
        for (let i = 0; i < preparedImages.length; ++i) {
            const prediction = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_6__.interpolate)(predicted_depth[i], preparedImages[i].size.reverse(), 'bilinear', false);
            const formatted = prediction.mul_(255 / (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_4__.max)(prediction.data)[0]).to('uint8');
            toReturn.push({
                predicted_depth: predicted_depth[i],
                depth: _utils_image_js__WEBPACK_IMPORTED_MODULE_7__.RawImage.fromTensor(formatted),
            });
        }

        return toReturn.length > 1 ? toReturn : toReturn[0];
    }
}

const SUPPORTED_TASKS = Object.freeze({
    "text-classification": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": TextClassificationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSequenceClassification,
        "default": {
            // TODO: replace with original
            // "model": "distilbert-base-uncased-finetuned-sst-2-english",
            "model": "Xenova/distilbert-base-uncased-finetuned-sst-2-english",
        },
        "type": "text",
    },
    "token-classification": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": TokenClassificationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForTokenClassification,
        "default": {
            // TODO: replace with original
            // "model": "Davlan/bert-base-multilingual-cased-ner-hrl",
            "model": "Xenova/bert-base-multilingual-cased-ner-hrl",
        },
        "type": "text",
    },
    "question-answering": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": QuestionAnsweringPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForQuestionAnswering,
        "default": {
            // TODO: replace with original
            // "model": "distilbert-base-cased-distilled-squad",
            "model": "Xenova/distilbert-base-cased-distilled-squad",
        },
        "type": "text",
    },

    "fill-mask": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": FillMaskPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForMaskedLM,
        "default": {
            // TODO: replace with original
            // "model": "bert-base-uncased",
            "model": "Xenova/bert-base-uncased",
        },
        "type": "text",
    },
    "summarization": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": SummarizationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSeq2SeqLM,
        "default": {
            // TODO: replace with original
            // "model": "sshleifer/distilbart-cnn-6-6",
            "model": "Xenova/distilbart-cnn-6-6",
        },
        "type": "text",
    },
    "translation": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": TranslationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSeq2SeqLM,
        "default": {
            // TODO: replace with original
            // "model": "t5-small",
            "model": "Xenova/t5-small",
        },
        "type": "text",
    },
    "text2text-generation": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": Text2TextGenerationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSeq2SeqLM,
        "default": {
            // TODO: replace with original
            // "model": "google/flan-t5-small",
            "model": "Xenova/flan-t5-small",
        },
        "type": "text",
    },
    "text-generation": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": TextGenerationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForCausalLM,
        "default": {
            // TODO: replace with original
            // "model": "gpt2",
            "model": "Xenova/gpt2",
        },
        "type": "text",
    },
    "zero-shot-classification": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": ZeroShotClassificationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSequenceClassification,
        "default": {
            // TODO: replace with original
            // "model": "typeform/distilbert-base-uncased-mnli",
            "model": "Xenova/distilbert-base-uncased-mnli",
        },
        "type": "text",
    },
    "audio-classification": {
        "pipeline": AudioClassificationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForAudioClassification,
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "superb/wav2vec2-base-superb-ks",
            "model": "Xenova/wav2vec2-base-superb-ks",
        },
        "type": "audio",
    },
    "zero-shot-audio-classification": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": ZeroShotAudioClassificationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel,
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "laion/clap-htsat-fused",
            "model": "Xenova/clap-htsat-unfused",
        },
        "type": "multimodal",
    },
    "automatic-speech-recognition": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": AutomaticSpeechRecognitionPipeline,
        "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSpeechSeq2Seq, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForCTC],
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "openai/whisper-tiny.en",
            "model": "Xenova/whisper-tiny.en",
        },
        "type": "multimodal",
    },
    "text-to-audio": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": TextToAudioPipeline,
        "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForTextToWaveform, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForTextToSpectrogram],
        "processor": [_processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, /* Some don't use a processor */ null],
        "default": {
            // TODO: replace with original
            // "model": "microsoft/speecht5_tts",
            "model": "Xenova/speecht5_tts",
        },
        "type": "text",
    },
    "image-to-text": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": ImageToTextPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForVision2Seq,
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "nlpconnect/vit-gpt2-image-captioning",
            "model": "Xenova/vit-gpt2-image-captioning",
        },
        "type": "multimodal",
    },

    "image-classification": {
        // no tokenizer
        "pipeline": ImageClassificationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageClassification,
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "google/vit-base-patch16-224",
            "model": "Xenova/vit-base-patch16-224",
        },
        "type": "multimodal",
    },

    "image-segmentation": {
        // no tokenizer
        "pipeline": ImageSegmentationPipeline,
        "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageSegmentation, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSemanticSegmentation],
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "facebook/detr-resnet-50-panoptic",
            "model": "Xenova/detr-resnet-50-panoptic",
        },
        "type": "multimodal",
    },

    "zero-shot-image-classification": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": ZeroShotImageClassificationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel,
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "openai/clip-vit-base-patch32",
            "model": "Xenova/clip-vit-base-patch32",
        },
        "type": "multimodal",
    },

    "object-detection": {
        // no tokenizer
        "pipeline": ObjectDetectionPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForObjectDetection,
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "facebook/detr-resnet-50",
            "model": "Xenova/detr-resnet-50",
        },
        "type": "multimodal",
    },
    "zero-shot-object-detection": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": ZeroShotObjectDetectionPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForZeroShotObjectDetection,
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "google/owlvit-base-patch32",
            "model": "Xenova/owlvit-base-patch32",
        },
        "type": "multimodal",
    },
    "document-question-answering": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": DocumentQuestionAnsweringPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForDocumentQuestionAnswering,
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "naver-clova-ix/donut-base-finetuned-docvqa",
            "model": "Xenova/donut-base-finetuned-docvqa",
        },
        "type": "multimodal",
    },
    "image-to-image": {
        // no tokenizer
        "pipeline": ImageToImagePipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageToImage,
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "caidas/swin2SR-classical-sr-x2-64",
            "model": "Xenova/swin2SR-classical-sr-x2-64",
        },
        "type": "image",
    },
    "depth-estimation": {
        // no tokenizer
        "pipeline": DepthEstimationPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForDepthEstimation,
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "default": {
            // TODO: replace with original
            // "model": "Intel/dpt-large",
            "model": "Xenova/dpt-large",
        },
        "type": "image",
    },

    // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers).
    "feature-extraction": {
        "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer,
        "pipeline": FeatureExtractionPipeline,
        "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel,
        "default": {
            // TODO: replace with original
            // "model": "sentence-transformers/all-MiniLM-L6-v2",
            "model": "Xenova/all-MiniLM-L6-v2",
        },
        "type": "text",
    },
    "image-feature-extraction": {
        "processor": _processors_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor,
        "pipeline": ImageFeatureExtractionPipeline,
        "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageFeatureExtraction, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel],
        "default": {
            // TODO: replace with original
            // "model": "google/vit-base-patch16-224",
            "model": "Xenova/vit-base-patch16-224-in21k",
        },
        "type": "image",
    },
})


// TODO: Add types for TASK_ALIASES
const TASK_ALIASES = Object.freeze({
    "sentiment-analysis": "text-classification",
    "ner": "token-classification",
    // "vqa": "visual-question-answering", // TODO: Add
    "asr": "automatic-speech-recognition",
    "text-to-speech": "text-to-audio",

    // Add for backwards compatibility
    "embeddings": "feature-extraction",
});

/**
 * @typedef {keyof typeof SUPPORTED_TASKS} TaskType
 * @typedef {keyof typeof TASK_ALIASES} AliasType
 * @typedef {TaskType | AliasType} PipelineType All possible pipeline types.
 * @typedef {{[K in TaskType]: InstanceType<typeof SUPPORTED_TASKS[K]["pipeline"]>}} SupportedTasks A mapping of pipeline names to their corresponding pipeline classes.
 * @typedef {{[K in AliasType]: InstanceType<typeof SUPPORTED_TASKS[TASK_ALIASES[K]]["pipeline"]>}} AliasTasks A mapping from pipeline aliases to their corresponding pipeline classes.
 * @typedef {SupportedTasks & AliasTasks} AllTasks A mapping from all pipeline names and aliases to their corresponding pipeline classes.
 */

/**
 * Utility factory method to build a `Pipeline` object.
 * 
 * @template {PipelineType} T The type of pipeline to return.
 * @param {T} task The task defining which pipeline will be returned. Currently accepted tasks are:
 *  - `"audio-classification"`: will return a `AudioClassificationPipeline`.
 *  - `"automatic-speech-recognition"`: will return a `AutomaticSpeechRecognitionPipeline`.
 *  - `"depth-estimation"`: will return a `DepthEstimationPipeline`.
 *  - `"document-question-answering"`: will return a `DocumentQuestionAnsweringPipeline`.
 *  - `"feature-extraction"`: will return a `FeatureExtractionPipeline`.
 *  - `"fill-mask"`: will return a `FillMaskPipeline`.
 *  - `"image-classification"`: will return a `ImageClassificationPipeline`.
 *  - `"image-segmentation"`: will return a `ImageSegmentationPipeline`.
 *  - `"image-to-text"`: will return a `ImageToTextPipeline`.
 *  - `"object-detection"`: will return a `ObjectDetectionPipeline`.
 *  - `"question-answering"`: will return a `QuestionAnsweringPipeline`.
 *  - `"summarization"`: will return a `SummarizationPipeline`.
 *  - `"text2text-generation"`: will return a `Text2TextGenerationPipeline`.
 *  - `"text-classification"` (alias "sentiment-analysis" available): will return a `TextClassificationPipeline`.
 *  - `"text-generation"`: will return a `TextGenerationPipeline`.
 *  - `"token-classification"` (alias "ner" available): will return a `TokenClassificationPipeline`.
 *  - `"translation"`: will return a `TranslationPipeline`.
 *  - `"translation_xx_to_yy"`: will return a `TranslationPipeline`.
 *  - `"zero-shot-classification"`: will return a `ZeroShotClassificationPipeline`.
 *  - `"zero-shot-audio-classification"`: will return a `ZeroShotAudioClassificationPipeline`.
 *  - `"zero-shot-image-classification"`: will return a `ZeroShotImageClassificationPipeline`.
 *  - `"zero-shot-object-detection"`: will return a `ZeroShotObjectDetectionPipeline`.
 * @param {string} [model=null] The name of the pre-trained model to use. If not specified, the default model for the task will be used.
 * @param {import('./utils/hub.js').PretrainedOptions} [options] Optional parameters for the pipeline.
 * @returns {Promise<AllTasks[T]>} A Pipeline object for the specified task.
 * @throws {Error} If an unsupported pipeline is requested.
 */
async function pipeline(
    task,
    model = null,
    {
        quantized = true,
        progress_callback = null,
        config = null,
        cache_dir = null,
        local_files_only = false,
        revision = 'main',
        model_file_name = null,
    } = {}
) {
    // Helper method to construct pipeline

    // Apply aliases
    // @ts-ignore
    task = TASK_ALIASES[task] ?? task;

    // Get pipeline info
    const pipelineInfo = SUPPORTED_TASKS[task.split('_', 1)[0]];
    if (!pipelineInfo) {
        throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`)
    }

    // Use model if specified, otherwise, use default
    if (!model) {
        model = pipelineInfo.default.model
        console.log(`No model specified. Using default model: "${model}".`);
    }

    const pretrainedOptions = {
        quantized,
        progress_callback,
        config,
        cache_dir,
        local_files_only,
        revision,
        model_file_name,
    }

    const classes = new Map([
        ['tokenizer', pipelineInfo.tokenizer],
        ['model', pipelineInfo.model],
        ['processor', pipelineInfo.processor],
    ]);

    // Load model, tokenizer, and processor (if they exist)
    const results = await loadItems(classes, model, pretrainedOptions);
    results.task = task;

    (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(progress_callback, {
        'status': 'ready',
        'task': task,
        'model': model,
    });

    const pipelineClass = pipelineInfo.pipeline;
    return new pipelineClass(results);
}


/**
 * Helper function to get applicable model, tokenizer, or processor classes for a given model.
 * @param {Map<string, any>} mapping The mapping of names to classes, arrays of classes, or null.
 * @param {string} model The name of the model to load.
 * @param {import('./utils/hub.js').PretrainedOptions} pretrainedOptions The options to pass to the `from_pretrained` method.
 * @private
 */
async function loadItems(mapping, model, pretrainedOptions) {

    const result = Object.create(null);

    /**@type {Promise[]} */
    const promises = [];
    for (let [name, cls] of mapping.entries()) {
        if (!cls) continue;

        /**@type {Promise} */
        let promise;
        if (Array.isArray(cls)) {
            promise = new Promise(async (resolve, reject) => {
                let e;
                for (let c of cls) {
                    if (c === null) {
                        // If null, we resolve it immediately, meaning the relevant
                        // class was not found, but it is optional.
                        resolve(null);
                        return;
                    }
                    try {
                        resolve(await c.from_pretrained(model, pretrainedOptions));
                        return;
                    } catch (err) {
                        e = err;
                    }
                }
                reject(e);
            })
        } else {
            promise = cls.from_pretrained(model, pretrainedOptions);
        }

        result[name] = promise;
        promises.push(promise);
    }

    // Wait for all promises to resolve (in parallel)
    await Promise.all(promises);

    // Then assign to result
    for (let [name, promise] of Object.entries(result)) {
        result[name] = await promise;
    }

    return result;
}

/***/ }),

/***/ "./src/processors.js":
/*!***************************!*\
  !*** ./src/processors.js ***!
  \***************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ASTFeatureExtractor": () => (/* binding */ ASTFeatureExtractor),
/* harmony export */   "AutoProcessor": () => (/* binding */ AutoProcessor),
/* harmony export */   "BeitFeatureExtractor": () => (/* binding */ BeitFeatureExtractor),
/* harmony export */   "BitImageProcessor": () => (/* binding */ BitImageProcessor),
/* harmony export */   "CLIPFeatureExtractor": () => (/* binding */ CLIPFeatureExtractor),
/* harmony export */   "ChineseCLIPFeatureExtractor": () => (/* binding */ ChineseCLIPFeatureExtractor),
/* harmony export */   "ClapFeatureExtractor": () => (/* binding */ ClapFeatureExtractor),
/* harmony export */   "ConvNextFeatureExtractor": () => (/* binding */ ConvNextFeatureExtractor),
/* harmony export */   "ConvNextImageProcessor": () => (/* binding */ ConvNextImageProcessor),
/* harmony export */   "DPTFeatureExtractor": () => (/* binding */ DPTFeatureExtractor),
/* harmony export */   "DPTImageProcessor": () => (/* binding */ DPTImageProcessor),
/* harmony export */   "DeiTFeatureExtractor": () => (/* binding */ DeiTFeatureExtractor),
/* harmony export */   "DetrFeatureExtractor": () => (/* binding */ DetrFeatureExtractor),
/* harmony export */   "DonutFeatureExtractor": () => (/* binding */ DonutFeatureExtractor),
/* harmony export */   "EfficientNetImageProcessor": () => (/* binding */ EfficientNetImageProcessor),
/* harmony export */   "FeatureExtractor": () => (/* binding */ FeatureExtractor),
/* harmony export */   "GLPNFeatureExtractor": () => (/* binding */ GLPNFeatureExtractor),
/* harmony export */   "ImageFeatureExtractor": () => (/* binding */ ImageFeatureExtractor),
/* harmony export */   "MobileViTFeatureExtractor": () => (/* binding */ MobileViTFeatureExtractor),
/* harmony export */   "MobileViTImageProcessor": () => (/* binding */ MobileViTImageProcessor),
/* harmony export */   "NougatImageProcessor": () => (/* binding */ NougatImageProcessor),
/* harmony export */   "OwlViTFeatureExtractor": () => (/* binding */ OwlViTFeatureExtractor),
/* harmony export */   "OwlViTProcessor": () => (/* binding */ OwlViTProcessor),
/* harmony export */   "Owlv2ImageProcessor": () => (/* binding */ Owlv2ImageProcessor),
/* harmony export */   "Processor": () => (/* binding */ Processor),
/* harmony export */   "SamImageProcessor": () => (/* binding */ SamImageProcessor),
/* harmony export */   "SamProcessor": () => (/* binding */ SamProcessor),
/* harmony export */   "SeamlessM4TFeatureExtractor": () => (/* binding */ SeamlessM4TFeatureExtractor),
/* harmony export */   "SegformerFeatureExtractor": () => (/* binding */ SegformerFeatureExtractor),
/* harmony export */   "SiglipImageProcessor": () => (/* binding */ SiglipImageProcessor),
/* harmony export */   "SpeechT5FeatureExtractor": () => (/* binding */ SpeechT5FeatureExtractor),
/* harmony export */   "SpeechT5Processor": () => (/* binding */ SpeechT5Processor),
/* harmony export */   "Swin2SRImageProcessor": () => (/* binding */ Swin2SRImageProcessor),
/* harmony export */   "ViTFeatureExtractor": () => (/* binding */ ViTFeatureExtractor),
/* harmony export */   "ViTImageProcessor": () => (/* binding */ ViTImageProcessor),
/* harmony export */   "VitMatteImageProcessor": () => (/* binding */ VitMatteImageProcessor),
/* harmony export */   "Wav2Vec2FeatureExtractor": () => (/* binding */ Wav2Vec2FeatureExtractor),
/* harmony export */   "Wav2Vec2ProcessorWithLM": () => (/* binding */ Wav2Vec2ProcessorWithLM),
/* harmony export */   "WhisperFeatureExtractor": () => (/* binding */ WhisperFeatureExtractor),
/* harmony export */   "WhisperProcessor": () => (/* binding */ WhisperProcessor),
/* harmony export */   "YolosFeatureExtractor": () => (/* binding */ YolosFeatureExtractor)
/* harmony export */ });
/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/core.js */ "./src/utils/core.js");
/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/hub.js */ "./src/utils/hub.js");
/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/maths.js */ "./src/utils/maths.js");
/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/tensor.js */ "./src/utils/tensor.js");
/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/image.js */ "./src/utils/image.js");
/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/audio.js */ "./src/utils/audio.js");

/**
 * @file Processors are used to prepare non-textual inputs (e.g., image or audio) for a model.
 * 
 * **Example:** Using a `WhisperProcessor` to prepare an audio input for a model.
 * ```javascript
 * import { AutoProcessor, read_audio } from '@xenova/transformers';
 *
 * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');
 * let audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);
 * let { input_features } = await processor(audio);
 * // Tensor {
 * //   data: Float32Array(240000) [0.4752984642982483, 0.5597258806228638, 0.56434166431427, ...],
 * //   dims: [1, 80, 3000],
 * //   type: 'float32',
 * //   size: 240000,
 * // }
 * ```
 * 
 * @module processors
 */













// Helper functions

/**
 * Converts bounding boxes from center format to corners format.
 * 
 * @param {number[]} arr The coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height)
 * @returns {number[]} The coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y)
 */
function center_to_corners_format([centerX, centerY, width, height]) {
    return [
        centerX - width / 2,
        centerY - height / 2,
        centerX + width / 2,
        centerY + height / 2
    ];
}

/**
 * Post-processes the outputs of the model (for object detection).
 * @param {Object} outputs The outputs of the model that must be post-processed
 * @param {Tensor} outputs.logits The logits
 * @param {Tensor} outputs.pred_boxes The predicted boxes.
 * @param {number} [threshold=0.5] The threshold to use for the scores.
 * @param {number[][]} [target_sizes=null] The sizes of the original images.
 * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.
 * @return {Object[]} An array of objects containing the post-processed outputs.
 * @private
 */
function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) {
    const out_logits = outputs.logits;
    const out_bbox = outputs.pred_boxes;
    const [batch_size, num_boxes, num_classes] = out_logits.dims;

    if (target_sizes !== null && target_sizes.length !== batch_size) {
        throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
    }
    let toReturn = [];
    for (let i = 0; i < batch_size; ++i) {
        let target_size = target_sizes !== null ? target_sizes[i] : null;
        let info = {
            boxes: [],
            classes: [],
            scores: []
        }
        let logits = out_logits[i];
        let bbox = out_bbox[i];

        for (let j = 0; j < num_boxes; ++j) {
            let logit = logits[j];

            let indices = [];
            let probs;
            if (is_zero_shot) {
                // Get indices of classes with high enough probability
                probs = logit.sigmoid().data;
                for (let k = 0; k < probs.length; ++k) {
                    if (probs[k] > threshold) {
                        indices.push(k);
                    }
                }

            } else {
                // Get most probable class
                let maxIndex = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logit.data)[1];

                if (maxIndex === num_classes - 1) {
                    // This is the background class, skip it
                    continue;
                }
                indices.push(maxIndex);

                // Compute softmax over classes
                probs = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(logit.data);
            }

            for (const index of indices) {

                // Some class has a high enough probability
                /** @type {number[]} */
                let box = bbox[j].data;

                // convert to [x0, y0, x1, y1] format
                box = center_to_corners_format(box)
                if (target_size !== null) {
                    box = box.map((x, i) => x * target_size[(i + 1) % 2])
                }

                info.boxes.push(box);
                info.classes.push(index);
                info.scores.push(probs[index]);
            }
        }
        toReturn.push(info);
    }
    return toReturn;
}

/**
 * Named tuple to indicate the order we are using is (height x width), even though
 * the Graphics’ industry standard is (width x height).
 * @typedef {[height: number, width: number]} HeightWidth
 */

/**
 * Helper function to validate audio inputs.
 * @param {any} audio The audio data.
 * @param {string} feature_extractor The name of the feature extractor.
 * @private
 */
function validate_audio_inputs(audio, feature_extractor) {
    if (!(audio instanceof Float32Array || audio instanceof Float64Array)) {
        throw new Error(
            `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead. ` +
            `If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`
        )
    }
}

/**
 * Helper function to constrain a value to be a multiple of a number.
 * @param {number} val The value to constrain.
 * @param {number} multiple The number to constrain to.
 * @param {number} [minVal=0] The minimum value to constrain to.
 * @param {number} [maxVal=null] The maximum value to constrain to.
 * @returns {number} The constrained value.
 * @private
 */
function constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) {
    const a = val / multiple;
    let x = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.bankers_round)(a) * multiple;

    if (maxVal !== null && x > maxVal) {
        x = Math.floor(a) * multiple;
    }

    if (x < minVal) {
        x = Math.ceil(a) * multiple;
    }

    return x;
}

/**
 * Rounds the height and width down to the closest multiple of size_divisibility
 * @param {[number, number]} size The size of the image
 * @param {number} divisor The divisor to use.
 * @returns {[number, number]} The rounded size.
 */
function enforce_size_divisibility([width, height], divisor) {
    return [
        Math.max(Math.floor(width / divisor), 1) * divisor,
        Math.max(Math.floor(height / divisor), 1) * divisor
    ];
}


/**
 * Base class for feature extractors.
 *
 * @extends Callable
 */
class FeatureExtractor extends _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
    /**
     * Constructs a new FeatureExtractor instance.
     *
     * @param {Object} config The configuration for the feature extractor.
     */
    constructor(config) {
        super();
        this.config = config
    }
}

/**
 * @typedef {object} ImageFeatureExtractorResult
 * @property {Tensor} pixel_values The pixel values of the batched preprocessed images.
 * @property {HeightWidth[]} original_sizes Array of two-dimensional tuples like [[480, 640]].
 * @property {HeightWidth[]} reshaped_input_sizes Array of two-dimensional tuples like [[1000, 1330]].
 */

/**
 * Feature extractor for image models.
 *
 * @extends FeatureExtractor
 */
class ImageFeatureExtractor extends FeatureExtractor {

    /**
     * Constructs a new ImageFeatureExtractor instance.
     *
     * @param {Object} config The configuration for the feature extractor.
     * @param {number[]} config.image_mean The mean values for image normalization.
     * @param {number[]} config.image_std The standard deviation values for image normalization.
     * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range.
     * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values.
     * @param {boolean} config.do_normalize Whether to normalize the image pixel values.
     * @param {boolean} config.do_resize Whether to resize the image.
     * @param {number} config.resample What method to use for resampling.
     * @param {number|Object} config.size The size to resize the image to.
     * @param {boolean} [config.do_flip_channel_order=false] Whether to flip the color channels from RGB to BGR.
     * Can be overridden by the `do_flip_channel_order` parameter in the `preprocess` method.
     */
    constructor(config) {
        super(config);

        this.image_mean = this.config.image_mean ?? this.config.mean;
        this.image_std = this.config.image_std ?? this.config.std;

        this.resample = this.config.resample ?? 2; // 2 => bilinear
        this.do_rescale = this.config.do_rescale ?? true;
        this.rescale_factor = this.config.rescale_factor ?? (1 / 255);
        this.do_normalize = this.config.do_normalize;

        this.do_resize = this.config.do_resize;
        this.do_thumbnail = this.config.do_thumbnail;
        this.size = this.config.size;
        this.size_divisibility = this.config.size_divisibility ?? this.config.size_divisor;

        this.do_center_crop = this.config.do_center_crop;
        this.crop_size = this.config.crop_size;
        this.do_convert_rgb = this.config.do_convert_rgb ?? true;
        this.do_crop_margin = this.config.do_crop_margin;

        this.pad_size = this.config.pad_size;
        this.do_pad = this.config.do_pad;

        if (this.do_pad && !this.pad_size && this.size && this.size.width !== undefined && this.size.height !== undefined) {
            // Should pad, but no pad size specified
            // We infer the pad size from the resize size
            this.pad_size = this.size
        }

        this.do_flip_channel_order = this.config.do_flip_channel_order ?? false;
    }

    /**
     * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
     * corresponding dimension of the specified size.
     * @param {RawImage} image The image to be resized.
     * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to.
     * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.
     * @returns {Promise<RawImage>} The resized image.
     */
    async thumbnail(image, size, resample = 2) {
        const input_height = image.height;
        const input_width = image.width;

        const output_height = size.height;
        const output_width = size.width;

        // We always resize to the smallest of either the input or output size.
        let height = Math.min(input_height, output_height)
        let width = Math.min(input_width, output_width)

        if (height === input_height && width === input_width) {
            return image;
        }
        if (input_height > input_width) {
            width = Math.floor(input_width * height / input_height);
        } else if (input_width > input_height) {
            height = Math.floor(input_height * width / input_width);
        }
        return await image.resize(width, height, { resample });
    }


    /**
     * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).
     * @param {RawImage} image The image to be cropped.
     * @param {number} gray_threshold Value below which pixels are considered to be gray.
     * @returns {Promise<RawImage>} The cropped image.
     */
    async crop_margin(image, gray_threshold = 200) {

        const gray_image = image.clone().grayscale();

        const minValue = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.min)(gray_image.data)[0];
        const maxValue = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(gray_image.data)[0];
        const diff = maxValue - minValue;

        if (diff === 0) {
            return image;
        }

        const threshold = gray_threshold / 255;

        let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0;
        for (let j = 0; j < gray_image.height; ++j) {
            const row = j * gray_image.width;
            for (let i = 0; i < gray_image.width; ++i) {
                if ((gray_image.data[row + i] - minValue) / diff < threshold) {
                    // We have a non-zero pixel, so we update the min/max values accordingly
                    x_min = Math.min(x_min, i);
                    y_min = Math.min(y_min, j);
                    x_max = Math.max(x_max, i);
                    y_max = Math.max(y_max, j);
                }
            }
        }

        image = await image.crop([x_min, y_min, x_max, y_max]);
        return image;
    }

    /**
     * Pad the image by a certain amount.
     * @param {Float32Array} pixelData The pixel data to pad.
     * @param {number[]} imgDims The dimensions of the image (height, width, channels).
     * @param {{width:number; height:number}|number} padSize The dimensions of the padded image.
     * @param {Object} options The options for padding.
     * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.
     * @param {boolean} [options.center=false] Whether to center the image.
     * @param {number} [options.constant_values=0] The constant value to use for padding.
     * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.
     */
    pad_image(pixelData, imgDims, padSize, {
        mode = 'constant',
        center = false,
        constant_values = 0,
    } = {}) {
        const [imageHeight, imageWidth, imageChannels] = imgDims;

        let paddedImageWidth, paddedImageHeight;
        if (typeof padSize === 'number') {
            paddedImageWidth = padSize;
            paddedImageHeight = padSize;
        } else {
            paddedImageWidth = padSize.width;
            paddedImageHeight = padSize.height;
        }

        // Only add padding if there is a difference in size
        if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {
            const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels);
            if (Array.isArray(constant_values)) {
                // Fill with constant values, cycling through the array
                for (let i = 0; i < paddedPixelData.length; ++i) {
                    paddedPixelData[i] = constant_values[i % imageChannels];
                }
            } else if (constant_values !== 0) {
                paddedPixelData.fill(constant_values);
            }

            const [left, top] = center
                ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)]
                : [0, 0];

            // Copy the original image into the padded image
            for (let i = 0; i < imageHeight; ++i) {
                const a = (i + top) * paddedImageWidth;
                const b = i * imageWidth;
                for (let j = 0; j < imageWidth; ++j) {
                    const c = (a + j + left) * imageChannels;
                    const d = (b + j) * imageChannels;
                    for (let k = 0; k < imageChannels; ++k) {
                        paddedPixelData[c + k] = pixelData[d + k];
                    }
                }
            }

            if (mode === 'symmetric') {
                if (center) {
                    throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.');
                    // TODO: Implement this
                }
                const h1 = imageHeight - 1;
                const w1 = imageWidth - 1;
                for (let i = 0; i < paddedImageHeight; ++i) {
                    const a = i * paddedImageWidth;
                    const b = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.calculateReflectOffset)(i, h1) * imageWidth;

                    for (let j = 0; j < paddedImageWidth; ++j) {
                        if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image
                        const c = (a + j) * imageChannels;
                        const d = (b + (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.calculateReflectOffset)(j, w1)) * imageChannels;

                        // Copy channel-wise
                        for (let k = 0; k < imageChannels; ++k) {
                            paddedPixelData[c + k] = pixelData[d + k];
                        }
                    }
                }
            }


            // Update pixel data and image dimensions
            pixelData = paddedPixelData;
            imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]
        }
        return [pixelData, imgDims];
    }

    /**
     * Rescale the image' pixel values by `this.rescale_factor`.
     * @param {Float32Array} pixelData The pixel data to rescale.
     * @returns {void}
     */
    rescale(pixelData) {
        for (let i = 0; i < pixelData.length; ++i) {
            pixelData[i] = this.rescale_factor * pixelData[i];
        }
    }

    /**
     * Find the target (width, height) dimension of the output image after
     * resizing given the input image and the desired size.
     * @param {RawImage} image The image to resize.
     * @param {any} size The size to use for resizing the image. 
     * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.
     */
    get_resize_output_image_size(image, size) {
        // `size` comes in many forms, so we need to handle them all here:
        // 1. `size` is an integer, in which case we resize the image to be a square 

        const [srcWidth, srcHeight] = image.size;

        let shortest_edge;
        let longest_edge;

        if (this.do_thumbnail) {
            // NOTE: custom logic for `Donut` models
            const { height, width } = size;
            shortest_edge = Math.min(height, width)
        }
        // Support both formats for backwards compatibility
        else if (Number.isInteger(size)) {
            shortest_edge = size;
            longest_edge = this.config.max_size ?? shortest_edge;

        } else if (size !== undefined) {
            // Extract known properties from `size`
            shortest_edge = size.shortest_edge;
            longest_edge = size.longest_edge;
        }

        // If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge`
        // while keeping the largest dimension <= `longest_edge`
        if (shortest_edge !== undefined || longest_edge !== undefined) {
            // http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/
            // Try resize so that shortest edge is `shortest_edge` (target)
            const shortResizeFactor = shortest_edge === undefined
                ? 1 // If `shortest_edge` is not set, don't upscale
                : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);

            const newWidth = srcWidth * shortResizeFactor;
            const newHeight = srcHeight * shortResizeFactor;

            // The new width and height might be greater than `longest_edge`, so
            // we downscale again to ensure the largest dimension is `longest_edge` 
            const longResizeFactor = longest_edge === undefined
                ? 1 // If `longest_edge` is not set, don't downscale
                : Math.min(longest_edge / newWidth, longest_edge / newHeight);

            // To avoid certain floating point precision issues, we round to 2 decimal places
            let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2)));
            let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2)));

            if (this.size_divisibility !== undefined) {
                [finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility)
            }
            return [finalWidth, finalHeight];

        } else if (size !== undefined && size.width !== undefined && size.height !== undefined) {
            // If `width` and `height` are set, resize to those dimensions

            let newWidth = size.width;
            let newHeight = size.height;

            // Custom for DPT models
            if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) {

                // determine new height and width
                let scale_height = newHeight / srcHeight;
                let scale_width = newWidth / srcWidth;

                // scale as little as possible
                if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) {
                    // fit width
                    scale_height = scale_width;
                } else {
                    // fit height
                    scale_width = scale_height;
                }

                newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of);
                newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of);
            }

            return [newWidth, newHeight];

        } else if (this.size_divisibility !== undefined) {
            return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility);
        } else {
            throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}`);
        }
    }

    /**
     * Resizes the image.
     * @param {RawImage} image The image to resize.
     * @returns {Promise<RawImage>} The resized image.
     */
    async resize(image) {
        const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size);
        return await image.resize(newWidth, newHeight, {
            resample: this.resample,
        });
    }

    /**
     * @typedef {object} PreprocessedImage
     * @property {HeightWidth} original_size The original size of the image.
     * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.
     * @property {Tensor} pixel_values The pixel values of the preprocessed image.
     */

    /**
     * Preprocesses the given image.
     *
     * @param {RawImage} image The image to preprocess.
     * @param {Object} overrides The overrides for the preprocessing options.
     * @returns {Promise<PreprocessedImage>} The preprocessed image.
     */
    async preprocess(image, {
        do_normalize = null,
        do_pad = null,
        do_convert_rgb = null,
        do_convert_grayscale = null,
        do_flip_channel_order = null,
    } = {}) {
        if (this.do_crop_margin) {
            // NOTE: Specific to nougat processors. This is done before resizing,
            // and can be interpreted as a pre-preprocessing step.
            image = await this.crop_margin(image);
        }

        const [srcWidth, srcHeight] = image.size; // original image size

        // Convert image to RGB if specified in config.
        if (do_convert_rgb ?? this.do_convert_rgb) {
            image = image.rgb();
        } else if (do_convert_grayscale) {
            image = image.grayscale();
        }

        // TODO:
        // For efficiency reasons, it might be best to merge the resize and center crop operations into one.

        // Resize all images
        if (this.do_resize) {
            image = await this.resize(image);
        }

        // Resize the image using thumbnail method.
        if (this.do_thumbnail) {
            image = await this.thumbnail(image, this.size, this.resample);
        }

        if (this.do_center_crop) {

            let crop_width;
            let crop_height;
            if (Number.isInteger(this.crop_size)) {
                crop_width = this.crop_size;
                crop_height = this.crop_size;
            } else {
                crop_width = this.crop_size.width;
                crop_height = this.crop_size.height;
            }

            image = await image.center_crop(crop_width, crop_height);
        }

        /** @type {HeightWidth} */
        const reshaped_input_size = [image.height, image.width];

        // NOTE: All pixel-level manipulation (i.e., modifying `pixelData`)
        // occurs with data in the hwc format (height, width, channels), 
        // to emulate the behavior of the original Python code (w/ numpy).
        let pixelData = Float32Array.from(image.data);
        let imgDims = [image.height, image.width, image.channels];

        if (this.do_rescale) {
            this.rescale(pixelData);
        }

        if (do_normalize ?? this.do_normalize) {
            let image_mean = this.image_mean;
            if (!Array.isArray(this.image_mean)) {
                image_mean = new Array(image.channels).fill(image_mean);
            }

            let image_std = this.image_std;
            if (!Array.isArray(this.image_std)) {
                image_std = new Array(image.channels).fill(image_mean);
            }

            if (image_mean.length !== image.channels || image_std.length !== image.channels) {
                throw new Error(`When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`);
            }

            for (let i = 0; i < pixelData.length; i += image.channels) {
                for (let j = 0; j < image.channels; ++j) {
                    pixelData[i + j] = (pixelData[i + j] - image_mean[j]) / image_std[j];
                }
            }
        }

        // do padding after rescaling/normalizing
        if (do_pad ?? this.do_pad) {
            if (this.pad_size) {
                const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size);
                [pixelData, imgDims] = padded; // Update pixel data and image dimensions
            } else if (this.size_divisibility) {
                const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility);
                [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight });
            }
        }

        if (do_flip_channel_order ?? this.do_flip_channel_order) {
            if (imgDims[2] !== 3) {
                throw new Error('Flipping channel order is only supported for RGB images.');
            }
            // Convert RGB to BGR
            for (let i = 0; i < pixelData.length; i += 3) {
                const temp = pixelData[i];
                pixelData[i] = pixelData[i + 2];
                pixelData[i + 2] = temp;
            }
        }

        const pixel_values = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor('float32', pixelData, imgDims)
            .permute(2, 0, 1); // convert to channel dimension format (hwc -> chw)

        return {
            original_size: [srcHeight, srcWidth],
            reshaped_input_size: reshaped_input_size,
            pixel_values: pixel_values,
        }
    }

    /**
     * Calls the feature extraction process on an array of images,
     * preprocesses each image, and concatenates the resulting
     * features into a single Tensor.
     * @param {RawImage[]} images The image(s) to extract features from.
     * @param {...any} args Additional arguments.
     * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.
     */
    async _call(images, ...args) {
        if (!Array.isArray(images)) {
            images = [images];
        }
        /** @type {PreprocessedImage[]} */
        const imageData = await Promise.all(images.map(x => this.preprocess(x)));

        // Stack pixel values
        const pixel_values = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.stack)(imageData.map(x => x.pixel_values), 0);

        return {
            pixel_values: pixel_values,

            // Original sizes of images
            original_sizes: imageData.map(x => x.original_size),

            // Reshaped sizes of images, before padding or cropping
            reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),
        }
    }

}

class SegformerFeatureExtractor extends ImageFeatureExtractor {

    /**
     * Converts the output of `SegformerForSemanticSegmentation` into semantic segmentation maps.
     * @param {*} outputs Raw outputs of the model.
     * @param {number[][]} [target_sizes=null] List of tuples corresponding to the requested final size
     * (height, width) of each prediction. If unset, predictions will not be resized.
     * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.
     */
    post_process_semantic_segmentation(outputs, target_sizes = null) {

        const logits = outputs.logits;
        const batch_size = logits.dims[0];

        if (target_sizes !== null && target_sizes.length !== batch_size) {
            throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
        }

        const toReturn = [];
        for (let i = 0; i < batch_size; ++i) {
            const target_size = target_sizes !== null ? target_sizes[i] : null;

            let data = logits[i];

            // 1. If target_size is not null, we need to resize the masks to the target size
            if (target_size !== null) {
                // resize the masks to the target size
                data = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.interpolate)(data, target_size, 'bilinear', false);
            }
            const [height, width] = target_size ?? data.dims.slice(-2);

            const segmentation = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor(
                'int32',
                new Int32Array(height * width),
                [height, width]
            );

            // Buffer to store current largest value
            const buffer = data[0].data;
            for (let j = 1; j < data.dims[0]; ++j) {
                const row = data[j].data;
                for (let k = 0; k < row.length; ++k) {
                    if (row[k] > buffer[k]) {
                        buffer[k] = row[k];
                        segmentation.data[k] = j;
                    }
                }
            }

            // Store which objects have labels
            // This is much more efficient that creating a set of the final values
            const hasLabel = new Array(data.dims[0]);
            const out = segmentation.data;
            for (let j = 0; j < out.length; ++j) {
                const index = out[j];
                hasLabel[index] = index;
            }
            /** @type {number[]} The unique list of labels that were detected */
            const labels = hasLabel.filter(x => x !== undefined);

            toReturn.push({ segmentation, labels });
        }
        return toReturn;
    }
}
class DPTFeatureExtractor extends ImageFeatureExtractor { }
class DPTImageProcessor extends DPTFeatureExtractor { } // NOTE: extends DPTFeatureExtractor
class BitImageProcessor extends ImageFeatureExtractor { }
class GLPNFeatureExtractor extends ImageFeatureExtractor { }
class CLIPFeatureExtractor extends ImageFeatureExtractor { }
class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor { }
class SiglipImageProcessor extends ImageFeatureExtractor { }
class ConvNextFeatureExtractor extends ImageFeatureExtractor {
    constructor(config) {
        super(config);

        /**
         * Percentage of the image to crop. Only has an effect if this.size < 384.
         */
        this.crop_pct = this.config.crop_pct ?? (224 / 256);
    }

    async resize(image) {
        const shortest_edge = this.size?.shortest_edge;
        if (shortest_edge === undefined) {
            throw new Error(`Size dictionary must contain 'shortest_edge' key.`);
        }

        if (shortest_edge < 384) {
            // maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
            const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct);

            const [newWidth, newHeight] = this.get_resize_output_image_size(image, {
                shortest_edge: resize_shortest_edge,
            });

            image = await image.resize(newWidth, newHeight, {
                resample: this.resample,
            });

            // then crop to (shortest_edge, shortest_edge)
            image = await image.center_crop(shortest_edge, shortest_edge);
        } else {
            // warping (no cropping) when evaluated at 384 or larger
            image = await image.resize(shortest_edge, shortest_edge, {
                resample: this.resample,
            });
        }

        return image;
    }
}
class ConvNextImageProcessor extends ConvNextFeatureExtractor { }  // NOTE extends ConvNextFeatureExtractor
class ViTFeatureExtractor extends ImageFeatureExtractor { }
class ViTImageProcessor extends ImageFeatureExtractor { }

class EfficientNetImageProcessor extends ImageFeatureExtractor {
    constructor(config) {
        super(config);
        this.include_top = this.config.include_top ?? true;
        if (this.include_top) {
            this.image_std = this.image_std.map(x => x * x);
        }
    }
}


class MobileViTFeatureExtractor extends ImageFeatureExtractor { }
class MobileViTImageProcessor extends MobileViTFeatureExtractor { } // NOTE extends MobileViTFeatureExtractor
class OwlViTFeatureExtractor extends ImageFeatureExtractor {
    /** @type {post_process_object_detection} */
    post_process_object_detection(...args) {
        return post_process_object_detection(...args);
    }
}
class Owlv2ImageProcessor extends OwlViTFeatureExtractor { } // NOTE extends OwlViTFeatureExtractor

class DeiTFeatureExtractor extends ImageFeatureExtractor { }
class BeitFeatureExtractor extends ImageFeatureExtractor { }
class DonutFeatureExtractor extends ImageFeatureExtractor {
    pad_image(pixelData, imgDims, padSize, options = {}) {
        const [imageHeight, imageWidth, imageChannels] = imgDims;

        let image_mean = this.image_mean;
        if (!Array.isArray(this.image_mean)) {
            image_mean = new Array(imageChannels).fill(image_mean);
        }

        let image_std = this.image_std;
        if (!Array.isArray(image_std)) {
            image_std = new Array(imageChannels).fill(image_mean);
        }

        const constant_values = image_mean.map((x, i) => - x / image_std[i]);

        return super.pad_image(pixelData, imgDims, padSize, {
            center: true,

            // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed.
            // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451
            constant_values: constant_values,
            ...options,
        });
    }
}
class NougatImageProcessor extends DonutFeatureExtractor { } // NOTE extends DonutFeatureExtractor

/**
 * @typedef {object} DetrFeatureExtractorResultProps
 * @property {Tensor} pixel_mask
 * @typedef {ImageFeatureExtractorResult & DetrFeatureExtractorResultProps} DetrFeatureExtractorResult
 */

/**
 * Detr Feature Extractor.
 *
 * @extends ImageFeatureExtractor
 */
class DetrFeatureExtractor extends ImageFeatureExtractor {
    /**
     * Calls the feature extraction process on an array of images, preprocesses
     * each image, and concatenates the resulting features into a single Tensor.
     * @param {RawImage[]} images The image(s) to extract features from.
     * @returns {Promise<DetrFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
     */
    async _call(images) {
        const result = await super._call(images);

        // TODO support differently-sized images, for now assume all images are the same size.
        // TODO support different mask sizes (not just 64x64)
        // Currently, just fill pixel mask with 1s
        const maskSize = [result.pixel_values.dims[0], 64, 64];
        const pixel_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor(
            'int64',
            new BigInt64Array(maskSize.reduce((a, b) => a * b)).fill(1n),
            maskSize
        );

        return { ...result, pixel_mask };
    }

    /**
     * Post-processes the outputs of the model (for object detection).
     * @param {Object} outputs The outputs of the model that must be post-processed
     * @param {Tensor} outputs.logits The logits
     * @param {Tensor} outputs.pred_boxes The predicted boxes.
     * @return {Object[]} An array of objects containing the post-processed outputs.
     */

    /** @type {post_process_object_detection} */
    post_process_object_detection(...args) {
        return post_process_object_detection(...args);
    }

    /**
     * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.
     * @param {Tensor} class_logits The class logits.
     * @param {Tensor} mask_logits The mask logits.
     * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.
     * @param {number} num_labels The number of labels.
     * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.
     */
    remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) {

        let mask_probs_item = [];
        let pred_scores_item = [];
        let pred_labels_item = [];

        for (let j = 0; j < class_logits.dims[0]; ++j) {
            let cls = class_logits[j];
            let mask = mask_logits[j];

            let pred_label = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(cls.data)[1];
            if (pred_label === num_labels) {
                // Is the background, so we ignore it
                continue;
            }

            let scores = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(cls.data);
            let pred_score = scores[pred_label];
            if (pred_score > object_mask_threshold) {
                mask_probs_item.push(mask);
                pred_scores_item.push(pred_score);
                pred_labels_item.push(pred_label);
            }
        }

        return [mask_probs_item, pred_scores_item, pred_labels_item];

    }

    /**
     * Checks whether the segment is valid or not.
     * @param {Int32Array} mask_labels Labels for each pixel in the mask.
     * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.
     * @param {number} k The class id of the segment.
     * @param {number} mask_threshold The mask threshold.
     * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
     * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.
     */
    check_segment_validity(
        mask_labels,
        mask_probs,
        k,
        mask_threshold = 0.5,
        overlap_mask_area_threshold = 0.8
    ) {
        // mask_k is a 1D array of indices, indicating where the mask is equal to k
        let mask_k = [];
        let mask_k_area = 0;
        let original_area = 0;

        // Compute the area of all the stuff in query k
        for (let i = 0; i < mask_labels.length; ++i) {
            if (mask_labels[i] === k) {
                mask_k.push(i);
                ++mask_k_area;
            }

            if (mask_probs[k].data[i] >= mask_threshold) {
                ++original_area;
            }
        }
        let mask_exists = mask_k_area > 0 && original_area > 0;

        // Eliminate disconnected tiny segments
        if (mask_exists) {
            // Perform additional check
            let area_ratio = mask_k_area / original_area;
            mask_exists = area_ratio > overlap_mask_area_threshold;
        }

        return [mask_exists, mask_k]
    }

    /**
     * Computes the segments.
     * @param {Tensor[]} mask_probs The mask probabilities.
     * @param {number[]} pred_scores The predicted scores.
     * @param {number[]} pred_labels The predicted labels.
     * @param {number} mask_threshold The mask threshold.
     * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
     * @param {Set<number>} label_ids_to_fuse The label ids to fuse.
     * @param {number[]} target_size The target size of the image.
     * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.
     */
    compute_segments(
        mask_probs,
        pred_scores,
        pred_labels,
        mask_threshold,
        overlap_mask_area_threshold,
        label_ids_to_fuse = null,
        target_size = null,
    ) {
        let [height, width] = target_size ?? mask_probs[0].dims;

        let segmentation = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor(
            'int32',
            new Int32Array(height * width),
            [height, width]
        );
        let segments = [];

        // 1. If target_size is not null, we need to resize the masks to the target size
        if (target_size !== null) {
            // resize the masks to the target size
            for (let i = 0; i < mask_probs.length; ++i) {
                mask_probs[i] = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.interpolate)(mask_probs[i], target_size, 'bilinear', false);
            }
        }

        // 2. Weigh each mask by its prediction score
        // NOTE: `mask_probs` is updated in-place
        // 
        // Temporary storage for the best label/scores for each pixel ([height, width]):
        let mask_labels = new Int32Array(mask_probs[0].data.length);
        let bestScores = new Float32Array(mask_probs[0].data.length);

        for (let i = 0; i < mask_probs.length; ++i) {
            let score = pred_scores[i];

            for (let j = 0; j < mask_probs[i].data.length; ++j) {
                mask_probs[i].data[j] *= score
                if (mask_probs[i].data[j] > bestScores[j]) {
                    mask_labels[j] = i;
                    bestScores[j] = mask_probs[i].data[j];
                }
            }
        }

        let current_segment_id = 0;

        // let stuff_memory_list = {}
        for (let k = 0; k < pred_labels.length; ++k) {
            let pred_class = pred_labels[k];

            // TODO add `should_fuse`
            // let should_fuse = pred_class in label_ids_to_fuse

            // Check if mask exists and large enough to be a segment
            let [mask_exists, mask_k] = this.check_segment_validity(
                mask_labels,
                mask_probs,
                k,
                mask_threshold,
                overlap_mask_area_threshold
            )

            if (!mask_exists) {
                // Nothing to see here
                continue;
            }

            // TODO
            // if (pred_class in stuff_memory_list) {
            //     current_segment_id = stuff_memory_list[pred_class]
            // } else {
            //     current_segment_id += 1;
            // }
            ++current_segment_id;


            // Add current object segment to final segmentation map
            for (let index of mask_k) {
                segmentation.data[index] = current_segment_id;
            }

            segments.push({
                id: current_segment_id,
                label_id: pred_class,
                // was_fused: should_fuse, TODO
                score: pred_scores[k],
            })

            // TODO
            // if(should_fuse){
            //     stuff_memory_list[pred_class] = current_segment_id
            // }
        }

        return [segmentation, segments];
    }

    /**
     * Post-process the model output to generate the final panoptic segmentation.
     * @param {*} outputs The model output to post process
     * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.
     * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.
     * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
     * @param {Set<number>} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.
     * @param {number[][]} [target_sizes=null] The target sizes to resize the masks to.
     * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}
     */
    post_process_panoptic_segmentation(
        outputs,
        threshold = 0.5,
        mask_threshold = 0.5,
        overlap_mask_area_threshold = 0.8,
        label_ids_to_fuse = null,
        target_sizes = null,
    ) {
        if (label_ids_to_fuse === null) {
            console.warn("`label_ids_to_fuse` unset. No instance will be fused.")
            label_ids_to_fuse = new Set();
        }

        const class_queries_logits = outputs.logits; // [batch_size, num_queries, num_classes+1]
        const masks_queries_logits = outputs.pred_masks; // [batch_size, num_queries, height, width]

        const mask_probs = masks_queries_logits.sigmoid()  // [batch_size, num_queries, height, width]

        let [batch_size, num_queries, num_labels] = class_queries_logits.dims;
        num_labels -= 1; // Remove last class (background)

        if (target_sizes !== null && target_sizes.length !== batch_size) {
            throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
        }

        let toReturn = [];
        for (let i = 0; i < batch_size; ++i) {
            let target_size = target_sizes !== null ? target_sizes[i] : null;

            let class_logits = class_queries_logits[i];
            let mask_logits = mask_probs[i];

            let [mask_probs_item, pred_scores_item, pred_labels_item] = this.remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels);

            if (pred_labels_item.length === 0) {
                // No mask found
                let [height, width] = target_size ?? mask_logits.dims.slice(-2);

                let segmentation = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor(
                    'int32',
                    new Int32Array(height * width).fill(-1),
                    [height, width]
                )
                toReturn.push({
                    segmentation: segmentation,
                    segments_info: []
                });
                continue;
            }


            // Get segmentation map and segment information of batch item
            let [segmentation, segments] = this.compute_segments(
                mask_probs_item,
                pred_scores_item,
                pred_labels_item,
                mask_threshold,
                overlap_mask_area_threshold,
                label_ids_to_fuse,
                target_size,
            )

            toReturn.push({
                segmentation: segmentation,
                segments_info: segments
            })
        }

        return toReturn;
    }

    post_process_instance_segmentation() {
        // TODO
        throw Error("Not implemented yet");
    }
}

class YolosFeatureExtractor extends ImageFeatureExtractor {
    /** @type {post_process_object_detection} */
    post_process_object_detection(...args) {
        return post_process_object_detection(...args);
    }
}

/**
 * @typedef {object} SamImageProcessorResult
 * @property {Tensor} pixel_values
 * @property {HeightWidth[]} original_sizes
 * @property {HeightWidth[]} reshaped_input_sizes
 * @property {Tensor} [input_points]
 * @property {Tensor} [input_labels]
 */

class SamImageProcessor extends ImageFeatureExtractor {

    /**
     * 
     * @param {any} input_points 
     * @param {HeightWidth[]} original_sizes 
     * @param {HeightWidth[]} reshaped_input_sizes 
     * @returns {Tensor}
     */
    reshape_input_points(input_points, original_sizes, reshaped_input_sizes) {

        // Make deep copy to avoid altering user's input
        input_points = structuredClone(input_points);
        let shape = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.calculateDimensions)(input_points);

        // TODO: add support for 2D input_points
        if (shape.length === 3) {
            // Correct user's input
            shape = [1, ...shape];
            input_points = [input_points];
        } else if (shape.length !== 4) {
            throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.")
        }

        // Reshape input points
        for (let i = 0; i < input_points.length; ++i) { // batch_size
            let originalImageSize = original_sizes[i];
            let reshapedImageSize = reshaped_input_sizes[i];

            let resizeFactors = [
                reshapedImageSize[0] / originalImageSize[0],
                reshapedImageSize[1] / originalImageSize[1]
            ]

            for (let j = 0; j < input_points[i].length; ++j) { // point_batch_size
                for (let k = 0; k < input_points[i][j].length; ++k) { // nb_points_per_image
                    for (let w = 0; w < input_points[i][j][k].length; ++w) { // 2
                        input_points[i][j][k][w] *= resizeFactors[w];
                    }
                }
            }
        }

        return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor(
            'float32',
            Float32Array.from(input_points.flat(Infinity)),
            shape
        )

    }

    /**
     * 
     * @param {any} input_labels 
     * @param {Tensor} input_points 
     * @returns {Tensor}
     */
    add_input_labels(input_labels, input_points) {
        let shape = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.calculateDimensions)(input_labels);
        if (shape.length === 2) {
            // Correct user's input
            shape = [1, ...shape];
            input_labels = [input_labels];
        } else if (shape.length !== 3) {
            throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.")
        }

        if (shape.some((x, i) => x !== input_points.dims[i])) {
            throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`)
        }
        return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor(
            'int64',
            input_labels.flat(Infinity).map(BigInt),
            shape,
        )
    }
    /**
     * @param {any[]} images The URL(s) of the image(s) to extract features from.
     * @param {any} [input_points] A 3D or 4D array, representing the input points provided by the user.
     * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1.
     * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`.
     * @param {any} [input_labels] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt.
     * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1.
     * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`.
     * @returns {Promise<SamImageProcessorResult>}
     */
    async _call(images, input_points = null, input_labels = null) {
        // TODO allow user to use preprocessed images
        /** @type {SamImageProcessorResult} */
        const processed = await super._call(images);

        if (input_points) {
            processed.input_points = this.reshape_input_points(
                input_points, processed.original_sizes, processed.reshaped_input_sizes
            );
        }

        if (input_labels) {
            if (!processed.input_points) {
                throw Error("`input_points` must be provided if `input_labels` are provided.")
            }
            processed.input_labels = this.add_input_labels(input_labels, processed.input_points);
        }

        return processed;
    }

    /**
     * Remove padding and upscale masks to the original image size.
     * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
     * @param {number[][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.
     * @param {number[][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
     * @param {Object} options Optional parameters for post-processing.
     * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks.
     * @param {boolean} [options.binarize] Whether to binarize the masks.
     * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`.
     * @param {number} [options.pad_size.height] The height the images were padded to.
     * @param {number} [options.pad_size.width] The width the images were padded to.
     * @returns {Tensor[]} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size.
     */
    post_process_masks(masks, original_sizes, reshaped_input_sizes, {
        mask_threshold = 0.0,
        binarize = true,
        pad_size = null,
    } = {}) {
        // masks: [1, 1, 3, 256, 256]

        const output_masks = [];

        pad_size = pad_size ?? this.pad_size;

        const target_image_size = [pad_size.height, pad_size.width];

        for (let i = 0; i < original_sizes.length; ++i) {
            const original_size = original_sizes[i];
            const reshaped_input_size = reshaped_input_sizes[i];

            const mask = masks[i]; // [b, c, h, w]

            // TODO: improve
            const interpolated_masks = [];
            for (let j = 0; j < mask.dims[0]; ++j) {
                const m = mask[j]; // 3d tensor

                // Upscale mask to padded size
                let interpolated_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.interpolate)(m, target_image_size, 'bilinear', false);

                // Crop mask
                interpolated_mask = interpolated_mask.slice(null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]);

                // Downscale mask
                interpolated_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.interpolate)(interpolated_mask, original_size, 'bilinear', false);

                if (binarize) {
                    const binarizedMaskData = new Uint8Array(interpolated_mask.data.length);
                    for (let i = 0; i < interpolated_mask.data.length; ++i) {
                        if (interpolated_mask.data[i] > mask_threshold) {
                            binarizedMaskData[i] = 1;
                        }
                    }
                    interpolated_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor(
                        'bool',
                        binarizedMaskData,
                        interpolated_mask.dims
                    )
                }

                interpolated_masks.push(interpolated_mask);
            }

            output_masks.push((0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.stack)(interpolated_masks));
        }

        return output_masks;
    }
}

class Swin2SRImageProcessor extends ImageFeatureExtractor {
    pad_image(pixelData, imgDims, padSize, options = {}) {
        // NOTE: In this case, `padSize` represents the size of the sliding window for the local attention.
        // In other words, the image is padded so that its width and height are multiples of `padSize`.
        const [imageHeight, imageWidth, imageChannels] = imgDims;

        return super.pad_image(pixelData, imgDims, {
            // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already
            // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19).
            // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`.
            width: imageWidth + (padSize - imageWidth % padSize) % padSize,
            height: imageHeight + (padSize - imageHeight % padSize) % padSize,
        }, {
            mode: 'symmetric',
            center: false,
            constant_values: -1,
            ...options,
        })
    }
}

class VitMatteImageProcessor extends ImageFeatureExtractor {
    /**
     * Calls the feature extraction process on an array of images, preprocesses
     * each image, and concatenates the resulting features into a single Tensor.
     * @param {RawImage[]} images The image(s) to extract features from.
     * @param {RawImage[]} trimaps The trimaps(s) to extract features from.
     * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
     */
    async _call(images, trimaps) {
        if (!Array.isArray(images)) {
            images = [images];
        }
        if (!Array.isArray(trimaps)) {
            trimaps = [trimaps];
        }

        const imageData = await Promise.all(images.map(x => this.preprocess(x)));
        const trimapData = await Promise.all(trimaps.map(x => this.preprocess(x, {
            do_normalize: false,
            do_convert_rgb: false,
            do_convert_grayscale: true,
        })));


        // Stack pixel values
        const pixel_values = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.stack)(imageData.map(
            // Concatenate images and trimaps
            (x, i) => (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.cat)([x.pixel_values, trimapData[i].pixel_values], 0)
        ), 0);

        return {
            pixel_values: pixel_values,

            // Original sizes of images
            original_sizes: imageData.map(x => x.original_size),

            // Reshaped sizes of images, before padding or cropping
            reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),
        }
    }
}

class WhisperFeatureExtractor extends FeatureExtractor {

    constructor(config) {
        super(config);

        // Prefer given `mel_filters` from preprocessor_config.json, or calculate them if they don't exist.
        this.config.mel_filters ??= (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.mel_filter_bank)(
            Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins
            this.config.feature_size, // num_mel_filters
            0.0, // min_frequency
            8000.0, // max_frequency
            this.config.sampling_rate, // sampling_rate
            "slaney", // norm
            "slaney", // mel_scale
        );

        this.window = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.window_function)(this.config.n_fft, 'hann');
    }

    /**
     * Computes the log-Mel spectrogram of the provided audio waveform.
     * @param {Float32Array|Float64Array} waveform The audio waveform to process.
     * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
     */
    _extract_fbank_features(waveform) {
        const { data, dims } = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.spectrogram)(
            waveform,
            this.window, // window
            this.config.n_fft, // frame_length
            this.config.hop_length, // hop_length
            {
                power: 2.0,
                mel_filters: this.config.mel_filters,
                log_mel: 'log10',

                // Custom
                max_num_frames: this.config.nb_max_frames, // 3000
            }
        )

        const maxValue = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(data)[0];

        for (let i = 0; i < data.length; ++i) {
            data[i] = (Math.max(data[i], maxValue - 8.0) + 4.0) / 4.0;
        }

        return { data, dims };
    }

    /**
     * Asynchronously extracts features from a given audio using the provided configuration.
     * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
     * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
     */
    async _call(audio) {
        validate_audio_inputs(audio, 'WhisperFeatureExtractor');

        let waveform;
        if (audio.length > this.config.n_samples) {
            console.warn(
                "Attempting to extract features for audio longer than 30 seconds. " +
                "If using a pipeline to extract transcript from a long audio clip, " +
                "remember to specify `chunk_length_s` and/or `stride_length_s`."
            );
            waveform = audio.slice(0, this.config.n_samples);
        } else {
            // pad with zeros
            waveform = new Float32Array(this.config.n_samples);
            waveform.set(audio);
        }

        const { data, dims } = this._extract_fbank_features(waveform);

        return {
            input_features: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor('float32',
                data,
                [1, ...dims]
            )
        };
    }
}

class Wav2Vec2FeatureExtractor extends FeatureExtractor {

    /**
     * @param {Float32Array} input_values 
     * @returns {Float32Array} 
     */
    _zero_mean_unit_var_norm(input_values) {
        // TODO support batch?
        const sum = input_values.reduce((a, b) => a + b, 0);
        const mean = sum / input_values.length;
        const variance = input_values.reduce((a, b) => a + (b - mean) ** 2, 0) / input_values.length;
        return input_values.map(x => (x - mean) / Math.sqrt(variance + 1e-7));
    }

    /**
     * Asynchronously extracts features from a given audio using the provided configuration.
     * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
     * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors.
     */
    async _call(audio) {
        validate_audio_inputs(audio, 'Wav2Vec2FeatureExtractor');

        if (audio instanceof Float64Array) {
            audio = new Float32Array(audio);
        }

        let input_values = audio;

        // zero-mean and unit-variance normalization
        if (this.config.do_normalize) {
            input_values = this._zero_mean_unit_var_norm(input_values);
        }

        // TODO: allow user to pass in attention mask
        const shape = [1, input_values.length];
        return {
            input_values: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor('float32', input_values, shape),
            attention_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor('int64', new BigInt64Array(input_values.length).fill(1n), shape)
        };
    }
}

class SeamlessM4TFeatureExtractor extends FeatureExtractor {

    constructor(config) {
        super(config);

        const sampling_rate = this.config.sampling_rate;
        const mel_filters = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.mel_filter_bank)(
            256, // num_frequency_bins
            this.config.num_mel_bins, // num_mel_filters
            20, // min_frequency
            Math.floor(sampling_rate / 2), // max_frequency
            sampling_rate, // sampling_rate
            null, // norm
            "kaldi", // mel_scale
            true, // triangularize_in_mel_space
        );

        // Do padding:
        for (let i = 0; i < mel_filters.length; ++i) {
            mel_filters[i].push(0);
        }
        this.mel_filters = mel_filters;

        this.window = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.window_function)(400, 'povey', {
            periodic: false,
        })
    }

    /**
     * Computes the log-Mel spectrogram of the provided audio waveform.
     * @param {Float32Array|Float64Array} waveform The audio waveform to process.
     * @param {number} max_length The maximum number of frames to return.
     * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
     */
    _extract_fbank_features(waveform, max_length) {
        // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`

        // Kaldi compliance: 16-bit signed integers
        // 32768 == 2 ** 15
        waveform = waveform.map((/** @type {number} */ x) => x * 32768)

        return (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.spectrogram)(
            waveform,
            this.window, // window
            400, // frame_length
            160, // hop_length
            {
                fft_length: 512,
                power: 2.0,
                center: false,
                preemphasis: 0.97,
                mel_filters: this.mel_filters,
                log_mel: 'log',
                mel_floor: 1.192092955078125e-07,
                remove_dc_offset: true,

                // Custom
                max_num_frames: max_length,
                transpose: true,
            }
        )
    }

    /**
     * Asynchronously extracts features from a given audio using the provided configuration.
     * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
     * @param {Object} options Optional parameters for feature extraction.
     * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`.
     * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of.
     * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel.
     * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask.
     * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors.
     */
    async _call(audio, {
        padding = true,
        pad_to_multiple_of = 2,
        do_normalize_per_mel_bins = true,
        return_attention_mask = true,
    } = {}) {
        validate_audio_inputs(audio, 'SeamlessM4TFeatureExtractor');

        let features = this._extract_fbank_features(audio, this.config.max_length);

        if (do_normalize_per_mel_bins) {
            const [num_features, feature_size] = features.dims;
            for (let i = 0; i < feature_size; ++i) {
                let sum = 0;
                for (let j = 0; j < num_features; ++j) {
                    sum += features.data[j * feature_size + i];
                }

                const mean = sum / num_features;

                let variance = 0;
                for (let j = 0; j < num_features; ++j) {
                    variance += (features.data[j * feature_size + i] - mean) ** 2;
                }
                variance /= num_features - 1; // NOTE: We use ddof=1

                const std = Math.sqrt(variance + 1e-7);
                for (let j = 0; j < num_features; ++j) {
                    const index = j * feature_size + i;
                    features.data[index] = (features.data[index] - mean) / std;
                }
            }
        }

        let padded_attention_mask;
        if (padding) {
            const [num_frames, num_channels] = features.dims;

            const pad_size = num_frames % pad_to_multiple_of;
            if (pad_size > 0) {
                const padded_data = new Float32Array(num_channels * (num_frames + pad_size));
                padded_data.set(features.data)
                padded_data.fill(this.config.padding_value, features.data.length)

                const numPaddedFrames = num_frames + pad_size;
                features = {
                    data: padded_data,
                    dims: [numPaddedFrames, num_channels],
                }

                if (return_attention_mask) {
                    padded_attention_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor(
                        'int64',
                        new BigInt64Array(numPaddedFrames),
                        [1, numPaddedFrames],
                    )
                    padded_attention_mask.data.fill(1n, 0, num_frames);
                }
            }
        }

        const [num_frames, num_channels] = features.dims;

        const stride = this.config.stride;
        const remainder = num_frames % stride;
        if (remainder !== 0) {
            throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`)
        }

        const input_features = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor('float32',
            features.data,
            features.dims,
        ).view(
            1,
            Math.floor(num_frames / stride),
            num_channels * stride,
        );

        const result = { input_features }

        if (return_attention_mask) {
            const reshapedNumFrames = input_features.dims[1];

            const attention_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor(
                'int64',
                new BigInt64Array(reshapedNumFrames),
                [1, reshapedNumFrames],
            );
            if (padded_attention_mask) {
                for (let i = 1, j = 0; i < num_frames; i += stride, ++j) {
                    attention_mask.data[j] = padded_attention_mask.data[i];
                }
            } else {
                attention_mask.data.fill(1n);
            }

            result.attention_mask = attention_mask;
        }

        return result;
    }
}

class ASTFeatureExtractor extends FeatureExtractor {


    constructor(config) {
        super(config);

        const sampling_rate = this.config.sampling_rate;
        const mel_filters = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.mel_filter_bank)(
            256, // num_frequency_bins
            this.config.num_mel_bins, // num_mel_filters
            20, // min_frequency
            Math.floor(sampling_rate / 2), // max_frequency
            sampling_rate, // sampling_rate
            null, // norm
            "kaldi", // mel_scale
            true, // triangularize_in_mel_space
        );

        // Do padding:
        for (let i = 0; i < mel_filters.length; ++i) {
            mel_filters[i].push(0);
        }
        this.mel_filters = mel_filters;

        this.window = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.window_function)(400, 'hann', {
            periodic: false,
        })

        this.mean = this.config.mean;
        this.std = this.config.std;
    }

    /**
     * Computes the log-Mel spectrogram of the provided audio waveform.
     * @param {Float32Array|Float64Array} waveform The audio waveform to process.
     * @param {number} max_length The maximum number of frames to return.
     * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
     */
    _extract_fbank_features(waveform, max_length) {
        // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`
        return (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.spectrogram)(
            waveform,
            this.window, // window
            400, // frame_length
            160, // hop_length
            {
                fft_length: 512,
                power: 2.0,
                center: false,
                preemphasis: 0.97,
                mel_filters: this.mel_filters,
                log_mel: 'log',
                mel_floor: 1.192092955078125e-07,
                remove_dc_offset: true,

                // Custom
                max_num_frames: max_length,
                transpose: true,
            }
        )
    }


    /**
     * Asynchronously extracts features from a given audio using the provided configuration.
     * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
     * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
     */
    async _call(audio) {
        validate_audio_inputs(audio, 'ASTFeatureExtractor');

        const features = this._extract_fbank_features(audio, this.config.max_length);
        if (this.config.do_normalize) {
            // Normalize the input audio spectrogram to have mean=0, std=0.5
            const denom = this.std * 2;
            for (let i = 0; i < features.data.length; ++i) {
                features.data[i] = (features.data[i] - this.mean) / denom;
            }
        }

        return {
            input_values: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor('float32',
                features.data,
                [1, ...features.dims]
            )
        };
    }
}

class ClapFeatureExtractor extends FeatureExtractor {

    constructor(config) {
        super(config);

        this.mel_filters = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.mel_filter_bank)(
            this.config.nb_frequency_bins, // num_frequency_bins
            this.config.feature_size, // num_mel_filters
            this.config.frequency_min, // min_frequency
            this.config.frequency_max, // max_frequency
            this.config.sampling_rate, // sampling_rate
            null, // norm
            "htk", // mel_scale
        );

        this.mel_filters_slaney = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.mel_filter_bank)(
            this.config.nb_frequency_bins, // num_frequency_bins
            this.config.feature_size, // num_mel_filters
            this.config.frequency_min, // min_frequency
            this.config.frequency_max, // max_frequency
            this.config.sampling_rate, // sampling_rate
            "slaney", // norm
            "slaney", // mel_scale
        );

        this.window = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.window_function)(this.config.fft_window_size, 'hann')

    }


    /**
     * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.
     * 
     * Four different path are possible:
     *   - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram
     *     will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram
     *     are then stacked together. They will later be used for `feature_fusion`.
     *   - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is
     *     padded based on `padding`.
     *   - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded
     *     based on `padding`, and is repeated `4` times.
     *   - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel
     *     spectrogram will be computed on a random crop of the waveform.
     * 
     * @param {Float32Array|Float64Array} waveform The input waveform.
     * @param {number} max_length The maximum length of the waveform.
     * @param {string} truncation The truncation strategy to use.
     * @param {string} padding The padding strategy to use.
     * @returns {{ data: Float32Array; dims: number[]; longer: boolean; }} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length.
     */
    _get_input_mel(waveform, max_length, truncation, padding) {

        /** @type {{ data: Float32Array; dims: number[]}} */
        let input_mel;
        let longer = false;
        const diff = waveform.length - max_length;
        if (diff > 0) {
            if (truncation === 'rand_trunc') {
                longer = true;
                const idx = Math.floor(Math.random() * (diff + 1));
                waveform = waveform.subarray(idx, idx + max_length);

                input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);
                input_mel.dims = [1, ...input_mel.dims]; // "unsqueeze"
            } else {
                // TODO implement fusion strategy
                throw new Error(`Truncation strategy "${truncation}" not implemented`)
            }
        } else {
            if (diff < 0) {
                let padded = new Float64Array(max_length); // already padded with zeros
                padded.set(waveform);

                if (padding === 'repeat') {
                    for (let i = waveform.length; i < max_length; i += waveform.length) {
                        padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i);
                    }
                } else if (padding === 'repeatpad') {
                    for (let i = waveform.length; i < -diff; i += waveform.length) {
                        padded.set(waveform, i);
                    }
                }
                waveform = padded;
            }

            if (truncation === 'fusion') {
                throw new Error(`Truncation strategy "${truncation}" not implemented`)
            }

            input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);
            input_mel.dims = [1, ...input_mel.dims]; // "unsqueeze"
        }

        return {
            ...input_mel,
            longer,
        }
    }

    /**
     * Compute the log-mel spectrogram of the provided `waveform` using the Hann window.
     * In CLAP, two different filter banks are used depending on the truncation pattern:
     *  - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from
     *    calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`
     *    is set to `"fusion"`.
     *  - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used
     *    `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original
     *    implementation when the truncation mode is not `"fusion"`.
     * 
     * @param {Float32Array|Float64Array} waveform The audio waveform to process.
     * @param {number[][]} mel_filters The mel filters to use.
     * @param {number} [max_length=null] The maximum number of frames to return.
     * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
     */
    _extract_fbank_features(waveform, mel_filters, max_length = null) {
        // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`
        return (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.spectrogram)(
            waveform,
            this.window, // window
            this.config.fft_window_size, // frame_length
            this.config.hop_length, // hop_length
            {
                power: 2.0,
                mel_filters,
                log_mel: 'dB',

                // Custom
                max_num_frames: max_length,
                do_pad: false,
                transpose: true,
            }
        )
    }


    /**
     * Asynchronously extracts features from a given audio using the provided configuration.
     * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
     * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
     */
    async _call(audio, {
        max_length = null,
    } = {}) {
        validate_audio_inputs(audio, 'ClapFeatureExtractor');

        // convert to mel spectrogram, truncate and pad if needed.
        const padded_inputs = this._get_input_mel(
            audio,
            max_length ?? this.config.nb_max_samples,
            this.config.truncation,
            this.config.padding,
        );


        return {
            input_features: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor('float32',
                padded_inputs.data,
                [1, ...padded_inputs.dims]
            )
        };
    }
}



class SpeechT5FeatureExtractor extends FeatureExtractor { }

/**
 * Represents a Processor that extracts features from an input.
 * @extends Callable
 */
class Processor extends _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
    /**
     * Creates a new Processor with the given feature extractor.
     * @param {FeatureExtractor} feature_extractor The function used to extract features from the input.
     */
    constructor(feature_extractor) {
        super();
        this.feature_extractor = feature_extractor;
        // TODO use tokenizer here?
    }

    /**
     * Calls the feature_extractor function with the given input.
     * @param {any} input The input to extract features from.
     * @param {...any} args Additional arguments.
     * @returns {Promise<any>} A Promise that resolves with the extracted features.
     */
    async _call(input, ...args) {
        return await this.feature_extractor(input, ...args);
    }
}

class SamProcessor extends Processor {
    /**
     * @borrows SamImageProcessor#_call as _call
     */
    async _call(...args) {
        return await this.feature_extractor(...args);
    }

    /**
     * @borrows SamImageProcessor#post_process_masks as post_process_masks
     */
    post_process_masks(...args) {
        // @ts-ignore
        return this.feature_extractor.post_process_masks(...args);
    }
    /**
     * @borrows SamImageProcessor#reshape_input_points as reshape_input_points
     */
    reshape_input_points(...args) {
        // @ts-ignore
        return this.feature_extractor.reshape_input_points(...args);
    }
}

/**
 * Represents a WhisperProcessor that extracts features from an audio input.
 * @extends Processor
 */
class WhisperProcessor extends Processor {
    /**
     * Calls the feature_extractor function with the given audio input.
     * @param {any} audio The audio input to extract features from.
     * @returns {Promise<any>} A Promise that resolves with the extracted features.
     */
    async _call(audio) {
        return await this.feature_extractor(audio)
    }
}


class Wav2Vec2ProcessorWithLM extends Processor {
    /**
     * Calls the feature_extractor function with the given audio input.
     * @param {any} audio The audio input to extract features from.
     * @returns {Promise<any>} A Promise that resolves with the extracted features.
     */
    async _call(audio) {
        return await this.feature_extractor(audio)
    }
}

class SpeechT5Processor extends Processor {
    /**
     * Calls the feature_extractor function with the given input.
     * @param {any} input The input to extract features from.
     * @returns {Promise<any>} A Promise that resolves with the extracted features.
     */
    async _call(input) {
        return await this.feature_extractor(input)
    }
}

class OwlViTProcessor extends Processor { }


//////////////////////////////////////////////////
/**
 * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function.
 * The chosen processor class is determined by the type specified in the processor config.
 * 
 * **Example:** Load a processor using `from_pretrained`.
 * ```javascript
 * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');
 * ```
 * 
 * **Example:** Run an image through a processor.
 * ```javascript
 * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');
 * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
 * let image_inputs = await processor(image);
 * // {
 * //   "pixel_values": {
 * //     "dims": [ 1, 3, 224, 224 ],
 * //     "type": "float32",
 * //     "data": Float32Array [ -1.558687686920166, -1.558687686920166, -1.5440893173217773, ... ],
 * //     "size": 150528
 * //   },
 * //   "original_sizes": [
 * //     [ 533, 800 ]
 * //   ],
 * //   "reshaped_input_sizes": [
 * //     [ 224, 224 ]
 * //   ]
 * // }
 * ```
 */
class AutoProcessor {
    static FEATURE_EXTRACTOR_CLASS_MAPPING = {
        ImageFeatureExtractor,
        WhisperFeatureExtractor,
        ViTFeatureExtractor,
        MobileViTFeatureExtractor,
        MobileViTImageProcessor,
        OwlViTFeatureExtractor,
        Owlv2ImageProcessor,
        CLIPFeatureExtractor,
        ChineseCLIPFeatureExtractor,
        SiglipImageProcessor,
        ConvNextFeatureExtractor,
        ConvNextImageProcessor,
        SegformerFeatureExtractor,
        BitImageProcessor,
        DPTImageProcessor,
        DPTFeatureExtractor,
        GLPNFeatureExtractor,
        BeitFeatureExtractor,
        DeiTFeatureExtractor,
        DetrFeatureExtractor,
        YolosFeatureExtractor,
        DonutFeatureExtractor,
        NougatImageProcessor,
        EfficientNetImageProcessor,

        ViTImageProcessor,
        VitMatteImageProcessor,
        SamImageProcessor,
        Swin2SRImageProcessor,
        Wav2Vec2FeatureExtractor,
        SeamlessM4TFeatureExtractor,
        SpeechT5FeatureExtractor,
        ASTFeatureExtractor,
        ClapFeatureExtractor,
    }

    static PROCESSOR_CLASS_MAPPING = {
        WhisperProcessor,
        Wav2Vec2ProcessorWithLM,
        SamProcessor,
        SpeechT5Processor,
        OwlViTProcessor,
    }

    /**
     * Instantiate one of the processor classes of the library from a pretrained model.
     * 
     * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object
     * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
     * 
     * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
     * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.
     *   Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
     *   user or organization name, like `dbmdz/bert-base-german-cased`.
     * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.
     * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor.
     * 
     * @returns {Promise<Processor>} A new instance of the Processor class.
     */
    static async from_pretrained(pretrained_model_name_or_path, {
        progress_callback = null,
        config = null,
        cache_dir = null,
        local_files_only = false,
        revision = 'main',
    } = {}) {

        let preprocessorConfig = config ?? await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, 'preprocessor_config.json', true, {
            progress_callback,
            config,
            cache_dir,
            local_files_only,
            revision,
        })

        // Determine feature extractor class
        // TODO: Ensure backwards compatibility with old configs
        let key = preprocessorConfig.feature_extractor_type ?? preprocessorConfig.image_processor_type;
        let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key];

        if (!feature_extractor_class) {
            if (preprocessorConfig.size !== undefined) {
                // Assume ImageFeatureExtractor
                console.warn(`Feature extractor type "${key}" not found, assuming ImageFeatureExtractor due to size parameter in config.`);
                feature_extractor_class = ImageFeatureExtractor;
            } else {
                throw new Error(`Unknown Feature Extractor type: ${key}`);
            }
        }

        // If no associated processor class, use default
        let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor;

        // Instantiate processor and feature extractor
        let feature_extractor = new feature_extractor_class(preprocessorConfig);
        return new processor_class(feature_extractor);
    }
}
//////////////////////////////////////////////////



/***/ }),

/***/ "./src/tokenizers.js":
/*!***************************!*\
  !*** ./src/tokenizers.js ***!
  \***************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "AlbertTokenizer": () => (/* binding */ AlbertTokenizer),
/* harmony export */   "AutoTokenizer": () => (/* binding */ AutoTokenizer),
/* harmony export */   "BartTokenizer": () => (/* binding */ BartTokenizer),
/* harmony export */   "BertTokenizer": () => (/* binding */ BertTokenizer),
/* harmony export */   "BlenderbotSmallTokenizer": () => (/* binding */ BlenderbotSmallTokenizer),
/* harmony export */   "BlenderbotTokenizer": () => (/* binding */ BlenderbotTokenizer),
/* harmony export */   "BloomTokenizer": () => (/* binding */ BloomTokenizer),
/* harmony export */   "CLIPTokenizer": () => (/* binding */ CLIPTokenizer),
/* harmony export */   "CamembertTokenizer": () => (/* binding */ CamembertTokenizer),
/* harmony export */   "CodeGenTokenizer": () => (/* binding */ CodeGenTokenizer),
/* harmony export */   "CodeLlamaTokenizer": () => (/* binding */ CodeLlamaTokenizer),
/* harmony export */   "CohereTokenizer": () => (/* binding */ CohereTokenizer),
/* harmony export */   "ConvBertTokenizer": () => (/* binding */ ConvBertTokenizer),
/* harmony export */   "DebertaTokenizer": () => (/* binding */ DebertaTokenizer),
/* harmony export */   "DebertaV2Tokenizer": () => (/* binding */ DebertaV2Tokenizer),
/* harmony export */   "DistilBertTokenizer": () => (/* binding */ DistilBertTokenizer),
/* harmony export */   "ElectraTokenizer": () => (/* binding */ ElectraTokenizer),
/* harmony export */   "EsmTokenizer": () => (/* binding */ EsmTokenizer),
/* harmony export */   "FalconTokenizer": () => (/* binding */ FalconTokenizer),
/* harmony export */   "GPT2Tokenizer": () => (/* binding */ GPT2Tokenizer),
/* harmony export */   "GPTNeoXTokenizer": () => (/* binding */ GPTNeoXTokenizer),
/* harmony export */   "GemmaTokenizer": () => (/* binding */ GemmaTokenizer),
/* harmony export */   "Grok1Tokenizer": () => (/* binding */ Grok1Tokenizer),
/* harmony export */   "HerbertTokenizer": () => (/* binding */ HerbertTokenizer),
/* harmony export */   "LlamaTokenizer": () => (/* binding */ LlamaTokenizer),
/* harmony export */   "M2M100Tokenizer": () => (/* binding */ M2M100Tokenizer),
/* harmony export */   "MBart50Tokenizer": () => (/* binding */ MBart50Tokenizer),
/* harmony export */   "MBartTokenizer": () => (/* binding */ MBartTokenizer),
/* harmony export */   "MPNetTokenizer": () => (/* binding */ MPNetTokenizer),
/* harmony export */   "MarianTokenizer": () => (/* binding */ MarianTokenizer),
/* harmony export */   "MobileBertTokenizer": () => (/* binding */ MobileBertTokenizer),
/* harmony export */   "NllbTokenizer": () => (/* binding */ NllbTokenizer),
/* harmony export */   "NougatTokenizer": () => (/* binding */ NougatTokenizer),
/* harmony export */   "PreTrainedTokenizer": () => (/* binding */ PreTrainedTokenizer),
/* harmony export */   "Qwen2Tokenizer": () => (/* binding */ Qwen2Tokenizer),
/* harmony export */   "RoFormerTokenizer": () => (/* binding */ RoFormerTokenizer),
/* harmony export */   "RobertaTokenizer": () => (/* binding */ RobertaTokenizer),
/* harmony export */   "SiglipTokenizer": () => (/* binding */ SiglipTokenizer),
/* harmony export */   "SpeechT5Tokenizer": () => (/* binding */ SpeechT5Tokenizer),
/* harmony export */   "SqueezeBertTokenizer": () => (/* binding */ SqueezeBertTokenizer),
/* harmony export */   "T5Tokenizer": () => (/* binding */ T5Tokenizer),
/* harmony export */   "TokenizerModel": () => (/* binding */ TokenizerModel),
/* harmony export */   "VitsTokenizer": () => (/* binding */ VitsTokenizer),
/* harmony export */   "Wav2Vec2CTCTokenizer": () => (/* binding */ Wav2Vec2CTCTokenizer),
/* harmony export */   "WhisperTokenizer": () => (/* binding */ WhisperTokenizer),
/* harmony export */   "XLMRobertaTokenizer": () => (/* binding */ XLMRobertaTokenizer),
/* harmony export */   "XLMTokenizer": () => (/* binding */ XLMTokenizer)
/* harmony export */ });
/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/core.js */ "./src/utils/core.js");
/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/hub.js */ "./src/utils/hub.js");
/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/maths.js */ "./src/utils/maths.js");
/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/tensor.js */ "./src/utils/tensor.js");
/* harmony import */ var _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/data-structures.js */ "./src/utils/data-structures.js");
/* harmony import */ var _huggingface_jinja__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @huggingface/jinja */ "./node_modules/@huggingface/jinja/dist/index.js");

/**
 * @file Tokenizers are used to prepare textual inputs for a model.
 * 
 * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence.
 * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`.
 * ```javascript
 * import { AutoTokenizer } from '@xenova/transformers';
 * 
 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');
 * const { input_ids } = await tokenizer('I love transformers!');
 * // Tensor {
 * //   data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n],
 * //   dims: [1, 6],
 * //   type: 'int64',
 * //   size: 6,
 * // }
 * ```
 * 
 * @module tokenizers
 */













/**
 * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties.
 * @property {boolean} [legacy=false] Whether or not the `legacy` behavior of the tokenizer should be used.
 * @typedef {import('./utils/hub.js').PretrainedOptions & TokenizerProperties} PretrainedTokenizerOptions
 */

/**
 * Loads a tokenizer from the specified path.
 * @param {string} pretrained_model_name_or_path The path to the tokenizer directory.
 * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
 * @returns {Promise<any[]>} A promise that resolves with information about the loaded tokenizer.
 */
async function loadTokenizer(pretrained_model_name_or_path, options) {

    const info = await Promise.all([
        (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, 'tokenizer.json', true, options),
        (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, 'tokenizer_config.json', true, options),
    ])

    // Override legacy option if `options.legacy` is not null
    if (options.legacy !== null) {
        info[1].legacy = options.legacy;
    }
    return info;
}


/**
 * Helper function to split a string on a regex, but keep the delimiters.
 * This is required, because the JavaScript `.split()` method does not keep the delimiters,
 * and wrapping in a capturing group causes issues with existing capturing groups (due to nesting).
 * @param {string} text The text to split.
 * @param {RegExp} regex The regex to split on.
 * @returns {string[]} The split string.
 */
function regexSplit(text, regex) {
    const result = [];
    let prev = 0;
    for (const match of text.matchAll(regex)) {
        const fullMatch = match[0];
        if (prev < match.index) {
            result.push(text.slice(prev, match.index));
        }
        if (fullMatch.length > 0) {
            result.push(fullMatch);
        }
        prev = match.index + fullMatch.length;
    }
    if (prev < text.length) {
        result.push(text.slice(prev));
    }
    return result;
}


/**
 * Helper method to construct a pattern from a config object.
 * @param {Object} pattern The pattern object.
 * @param {boolean} invert Whether to invert the pattern.
 * @returns {RegExp|null} The compiled pattern.
 */
function createPattern(pattern, invert = true) {

    if (pattern.Regex !== undefined) {
        // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \# or \& or \~).
        // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed).
        // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used.
        // For this reason, it is necessary to remove these backslashes before creating the regex.
        // See https://stackoverflow.com/a/63007777/13989043 for more information
        let regex = pattern.Regex.replace(/\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary

        // We also handle special cases where the regex contains invalid (non-JS compatible) syntax.
        for (const [key, value] of PROBLEMATIC_REGEX_MAP) {
            regex = regex.replaceAll(key, value);
        }

        return new RegExp(regex, 'gu');

    } else if (pattern.String !== undefined) {
        const escaped = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.escapeRegExp)(pattern.String);
        // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split()
        return new RegExp(invert ? escaped : `(${escaped})`, 'gu');

    } else {
        console.warn('Unknown pattern type:', pattern)
        return null;
    }
}

/**
 * Helper function to convert an Object to a Map
 * @param {Object} obj The object to convert.
 * @returns {Map<string, any>} The map.
 */
function objectToMap(obj) {
    return new Map(Object.entries(obj));
}

/**
 * Helper function to convert a tensor to a list before decoding.
 * @param {Tensor} tensor The tensor to convert.
 * @returns {number[]} The tensor as a list.
 */
function prepareTensorForDecode(tensor) {
    const dims = tensor.dims;
    switch (dims.length) {
        case 1:
            return tensor.tolist();
        case 2:
            if (dims[0] !== 1) {
                throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.');
            }
            return tensor.tolist()[0];
        default:
            throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`)
    }
}

/**
 * Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms
 * @param {string} text The text to clean up.
 * @returns {string} The cleaned up text.
 */
function clean_up_tokenization(text) {
    // Clean up a list of simple English tokenization artifacts
    // like spaces before punctuations and abbreviated forms
    return text.replace(/ \./g, '.')
        .replace(/ \?/g, '?')
        .replace(/ \!/g, '!')
        .replace(/ ,/g, ',')
        .replace(/ \' /g, "'")
        .replace(/ n\'t/g, "n't")
        .replace(/ \'m/g, "'m")
        .replace(/ \'s/g, "'s")
        .replace(/ \'ve/g, "'ve")
        .replace(/ \'re/g, "'re");
}

/**
 * Helper function to remove accents from a string.
 * @param {string} text The text to remove accents from.
 * @returns {string} The text with accents removed.
 */
function remove_accents(text) {
    return text.replace(/[\u0300-\u036f]/g, '');
}

/**
 * Helper function to lowercase a string and remove accents.
 * @param {string} text The text to lowercase and remove accents from.
 * @returns {string} The lowercased text with accents removed.
 */
function lowercase_and_remove_accent(text) {
    return remove_accents(text.toLowerCase());
}

/**
 * Helper function to fuse consecutive values in an array equal to the specified value.
 * @param {string[]} arr The input array
 * @param {any} value The value to fuse on.
 * @param {Map<string, any>} mapping The mapping from input domain to value.
 */
function fuse(arr, value, mapping) {
    const fused = [];
    let i = 0;
    while (i < arr.length) {
        fused.push(arr[i])
        if ((mapping.get(arr[i]) ?? value) !== value) {
            ++i;
            continue;
        }

        while (i < arr.length && (mapping.get(arr[i]) ?? value) === value) {
            ++i;
        }
    }

    return fused;
}

/**
 * Split a string on whitespace.
 * @param {string} text The text to split.
 * @returns {string[]} The split string.
 */
function whitespace_split(text) {
    return text.match(/\S+/g) || [];
}

const PUNCTUATION_REGEX = '\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E';

// A mapping of regex patterns to their equivalent (but longer) JS-compatible versions.
const PROBLEMATIC_REGEX_MAP = new Map([
    // This uses the case insensitive group modifier, which is not supported in JavaScript.
    // When parsing the regex, an "Invalid group" error is thrown.
    ["(?i:'s|'t|'re|'ve|'m|'ll|'d)", "(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],
])


/**
 * Represent a token added by the user on top of the existing Model vocabulary.
 * AddedToken can be configured to specify the behavior they should have in various situations like:
 *   - Whether they should only match single words
 *   - Whether to include any whitespace on its left or right
 */
class AddedToken {
    /**
     * Creates a new instance of AddedToken.
     * @param {Object} config Added token configuration object.
     * @param {string} config.content The content of the added token.
     * @param {number} config.id The id of the added token.
     * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.
     * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.
     * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.
     * @param {boolean} [config.normalized=false] Whether this token should be normalized.
     * @param {boolean} [config.special=false] Whether this token is special.
     */
    constructor(config) {
        this.content = config.content;
        this.id = config.id;
        this.single_word = config.single_word ?? false;
        this.lstrip = config.lstrip ?? false;
        this.rstrip = config.rstrip ?? false;
        this.special = config.special ?? false;
        this.normalized = config.normalized ?? null;
    }
}

/**
 * Abstract base class for tokenizer models.
 *
 * @extends Callable
 */
class TokenizerModel extends _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
    /**
     * Creates a new instance of TokenizerModel.
     * @param {Object} config The configuration object for the TokenizerModel.
     */
    constructor(config) {
        super();
        this.config = config;

        /** @type {string[]} */
        this.vocab = [];

        /**
         * A mapping of tokens to ids.
         * @type {Map<string, number>}
         */
        this.tokens_to_ids = new Map();

        this.unk_token_id = undefined;
        this.unk_token = undefined;
        this.end_of_word_suffix = undefined;

        /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */
        this.fuse_unk = this.config.fuse_unk ?? false;
    }

    /**
     * Instantiates a new TokenizerModel instance based on the configuration object provided.
     * @param {Object} config The configuration object for the TokenizerModel.
     * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.
     * @returns {TokenizerModel} A new instance of a TokenizerModel.
     * @throws Will throw an error if the TokenizerModel type in the config is not recognized.
     */
    static fromConfig(config, ...args) {
        switch (config.type) {
            case 'WordPiece':
                return new WordPieceTokenizer(config);
            case 'Unigram':
                // @ts-ignore
                return new Unigram(config, ...args);

            case 'BPE':
                return new BPE(config);

            default:
                if (config.vocab) {
                    // @ts-ignore
                    return new LegacyTokenizerModel(config, ...args);
                }
                throw new Error(`Unknown TokenizerModel type: ${config.type}`);
        }
    }

    /**
     * Internal function to call the TokenizerModel instance.
     * @param {string[]} tokens The tokens to encode.
     * @returns {string[]} The encoded token IDs.
     */
    _call(tokens) {
        let ids = this.encode(tokens);
        if (this.fuse_unk) {
            // Fuse unknown tokens
            ids = fuse(ids, this.unk_token_id, this.tokens_to_ids);
        }
        return ids;
    }

    /**
     * Encodes a list of tokens into a list of token IDs.
     * @param {string[]} tokens The tokens to encode.
     * @returns {string[]} The encoded tokens.
     * @throws Will throw an error if not implemented in a subclass.
     */
    encode(tokens) {
        throw Error("encode should be implemented in subclass.")
    }

    /**
     * Converts a list of tokens into a list of token IDs.
     * @param {string[]} tokens The tokens to convert.
     * @returns {number[]} The converted token IDs.
     */
    convert_tokens_to_ids(tokens) {
        return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id);
    }

    /**
     * Converts a list of token IDs into a list of tokens.
     * @param {number[]} ids The token IDs to convert.
     * @returns {string[]} The converted tokens.
     */
    convert_ids_to_tokens(ids) {
        return ids.map(i => this.vocab[i] ?? this.unk_token);
    }
}

/**
 * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens.
 * @extends TokenizerModel
 */
class WordPieceTokenizer extends TokenizerModel {
    /**
     * @param {Object} config The configuration object.
     * @param {Object} config.vocab A mapping of tokens to ids.
     * @param {string} config.unk_token The unknown token string.
     * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.
     * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.
     */
    constructor(config) {
        super(config);
        /**
         * A mapping of tokens to ids.
         * @type {Map<string, number>}
         */
        this.tokens_to_ids = objectToMap(config.vocab);

        /**
         * The id of the unknown token.
         * @type {number}
         */
        this.unk_token_id = this.tokens_to_ids.get(config.unk_token);

        /**
         * The unknown token string.
         * @type {string}
         */
        this.unk_token = config.unk_token;

        /**
         * The maximum number of characters allowed per word.
         * @type {number}
         */
        this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;

        /**
         * An array of tokens.
         * @type {string[]}
         */
        this.vocab = new Array(this.tokens_to_ids.size);
        for (const [key, value] of this.tokens_to_ids) {
            this.vocab[value] = key;
        }
    }

    /**
     * Encodes an array of tokens using WordPiece encoding.
     * @param {string[]} tokens The tokens to encode.
     * @returns {string[]} An array of encoded tokens.
     */
    encode(tokens) {
        const outputTokens = [];
        for (const token of tokens) {
            const chars = [...token];
            if (chars.length > this.max_input_chars_per_word) {
                outputTokens.push(this.unk_token);
                continue;
            }

            let isUnknown = false;
            let start = 0;
            const subTokens = [];

            while (start < chars.length) {
                let end = chars.length;
                let currentSubstring = null;
                while (start < end) {
                    let substr = chars.slice(start, end).join('');

                    if (start > 0) {
                        substr = this.config.continuing_subword_prefix + substr;
                    }
                    if (this.tokens_to_ids.has(substr)) {
                        currentSubstring = substr;
                        break;
                    }

                    --end;
                }
                if (currentSubstring === null) {
                    isUnknown = true;
                    break;
                }
                subTokens.push(currentSubstring);
                start = end;
            }
            if (isUnknown) {
                outputTokens.push(this.unk_token);
            } else {
                outputTokens.push(...subTokens);
            }
        }

        return outputTokens;
    }

}

/**
 * Class representing a Unigram tokenizer model.
 * @extends TokenizerModel
 */
class Unigram extends TokenizerModel {
    /**
     * Create a new Unigram tokenizer model.
     * @param {Object} config The configuration object for the Unigram model.
     * @param {number} config.unk_id The ID of the unknown token
     * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores.
     * @param {Object} moreConfig Additional configuration object for the Unigram model.
     */
    constructor(config, moreConfig) {
        super(config);

        const vocabSize = config.vocab.length;
        this.vocab = new Array(vocabSize);
        this.scores = new Array(vocabSize);
        for (let i = 0; i < vocabSize; ++i) {
            const piece = config.vocab[i];
            this.vocab[i] = piece[0];
            this.scores[i] = piece[1];
        }

        this.unk_token_id = config.unk_id;
        this.unk_token = this.vocab[config.unk_id];

        this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));
        this.bosToken = ' '; // beginning of a sentence token

        this.bosTokenId = this.tokens_to_ids.get(this.bosToken); // NOTE: may be undefined
        this.eosToken = moreConfig.eos_token;

        this.eosTokenId = this.tokens_to_ids.get(this.eosToken);
        this.unkToken = this.vocab[this.unk_token_id];

        this.minScore = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.min)(this.scores)[0];

        this.unkScore = this.minScore - 10.0;
        this.scores[this.unk_token_id] = this.unkScore;

        this.trie = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_4__.CharTrie();
        this.trie.extend(this.vocab);

        // NOTE: `fuse_unk` is hardcoded to true for Unigram models
        // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119
        this.fuse_unk = true;
    }

    /**
     * Populates lattice nodes.
     * @param {TokenLattice} lattice The token lattice to populate with nodes.
     */
    populateNodes(lattice) {
        const sentence = lattice.sentence;
        const len = sentence.length;
        let beginPos = 0;
        while (beginPos < len) {
            const mblen = 1;
            let hasSingleNode = false;
            const tokens = [];

            for (let token of this.trie.commonPrefixSearch(sentence.slice(beginPos))) {
                tokens.push(token);
                const tokenId = this.tokens_to_ids.get(token);
                const tokenScore = this.scores[tokenId];
                const n = token.length;
                lattice.insert(beginPos, n, tokenScore, tokenId);
                if (!hasSingleNode && n === mblen) {
                    hasSingleNode = true;
                }
            }
            if (!hasSingleNode) {
                lattice.insert(beginPos, mblen, this.unkScore, this.unk_token_id);
            }
            beginPos += mblen;
        }
    }

    /**
     * Encodes an array of tokens into an array of subtokens using the unigram model.
     *
     * @param {string} normalized The normalized string.
     * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.
     */
    tokenize(normalized) {
        const lattice = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_4__.TokenLattice(normalized, this.bosTokenId, this.eosTokenId);
        this.populateNodes(lattice);
        return lattice.tokens();
    }

    /**
     * Encodes an array of tokens using Unigram encoding.
     * @param {string[]} tokens The tokens to encode.
     * @returns {string[]} An array of encoded tokens.
     */
    encode(tokens) {
        const toReturn = [];
        for (const token of tokens) {
            const tokenized = this.tokenize(token);
            toReturn.push(...tokenized);
        }
        return toReturn;
    }

}

/**
 * Returns list of utf-8 byte and a mapping to unicode strings.
 * Specifically avoids mapping to whitespace/control characters the BPE code barfs on.
 * @returns {Object} Object with utf-8 byte keys and unicode string values.
 */
const BYTES_TO_UNICODE = (() => {
    // Returns list of utf-8 byte and a mapping to unicode strings.
    // We specifically avoids mapping to whitespace/control characters
    // the bpe code barfs on.

    const bs = [
        ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)),
        ...Array.from({ length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 }, (_, i) => i + "¡".charCodeAt(0)),
        ...Array.from({ length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 }, (_, i) => i + "®".charCodeAt(0)),
    ];
    const cs = bs.slice();
    let n = 0;
    for (let b = 0; b < 256; ++b) {
        if (!bs.includes(b)) {
            bs.push(b);
            cs.push(256 + n);
            n += 1;
        }
    }
    const ccs = cs.map(n => String.fromCharCode(n));
    return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));
})();

const UNICODE_TO_BYTES = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.reverseDictionary)(BYTES_TO_UNICODE);


/**
 * @typedef {Object} BPENode
 * @property {string} token The token associated with the node
 * @property {number} bias A positional bias for the node.
 * @property {number} [score] The score of the node.
 * @property {BPENode} [prev] The previous node in the linked list.
 * @property {BPENode} [next] The next node in the linked list.
 */

/**
 * BPE class for encoding text into Byte-Pair-Encoding (BPE) tokens.
 * @extends TokenizerModel
 */
class BPE extends TokenizerModel {
    /**
     * Create a BPE instance.
     * @param {Object} config The configuration object for BPE.
     * @param {Object} config.vocab A mapping of tokens to ids.
     * @param {string[]} config.merges An array of BPE merges as strings.
     * @param {string} config.unk_token The unknown token used for out of vocabulary words.
     * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.
     * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.
     * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False)
     * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges.
     */
    constructor(config) {
        super(config);

        this.BPE_SPLIT_TOKEN = ' ';

        /** @type {Map<string, number>} */
        this.tokens_to_ids = objectToMap(config.vocab);

        this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
        this.unk_token = config.unk_token;

        this.vocab = new Array(this.tokens_to_ids.size);
        for (const [key, value] of this.tokens_to_ids) {
            this.vocab[value] = key;
        }

        this.bpe_ranks = new Map(config.merges.map((x, i) => [x, i]));
        this.merges = config.merges.map(x => x.split(this.BPE_SPLIT_TOKEN));

        this.end_of_word_suffix = config.end_of_word_suffix;

        // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`)
        this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;

        this.byte_fallback = this.config.byte_fallback ?? false;

        if (this.byte_fallback) {
            this.text_encoder = new TextEncoder();
        }

        this.ignore_merges = this.config.ignore_merges ?? false;

        /** @type {Map<string, string[]>} */
        this.cache = new Map();
    }

    /**
     * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority
     * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.
     * @param {string} token The token to encode.
     * @returns {string[]} The BPE encoded tokens.
     */
    bpe(token) {
        if (token.length === 0) {
            return [];
        }

        const cached = this.cache.get(token);
        if (cached !== undefined) {
            return cached;
        }

        const word = Array.from(token);
        if (this.end_of_word_suffix) {
            word[word.length - 1] += this.end_of_word_suffix;
        }

        let result = [];
        if (word.length > 1) {
            // Create a priority queue to store the nodes that will be merged.
            // The comparator function compares the scores of the nodes.
            const queue = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_4__.PriorityQueue((a, b) => a.score < b.score);

            // Construct a doubly-linked list of nodes that will be inserted into the priority queue,
            // starting with the individual characters. We also populate each node with a positional
            // bias to break ties in the priority queue.
            let startingNode = {
                token: word[0],
                bias: 0,
                prev: null,
                next: null,
            }

            let previousNode = startingNode
            for (let i = 1; i < word.length; ++i) {
                const currentNode = {
                    bias: i / word.length, // Add fractional component to break ties
                    token: word[i],
                    prev: previousNode,
                    next: null,
                }
                previousNode.next = currentNode
                this._add_node(queue, previousNode)
                previousNode = currentNode
            }

            while (!queue.isEmpty()) {
                // Get the next node with the highest priority
                const node = queue.pop();

                // Check that this merge is still possible
                if (node.deleted || !node.next || node.next.deleted) continue;

                // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted.
                // This is because they will both be replaced by a new node representing the merge result.
                node.deleted = true;
                node.next.deleted = true;

                // Next, we fix the node that comes before the current node (i.e., left side of the merge).
                if (node.prev) {

                    // Make a shallow copy of the previous node
                    const newPreviousNode = { ...node.prev };

                    // Mark the old previous node as deleted. This avoids erroneous merges later,
                    // because there may still be references to this node in the priority queue.
                    node.prev.deleted = true;
                    node.prev = newPreviousNode;

                    // Update the reference of the previous node, by pointing its previous node to this new previous node.
                    if (newPreviousNode.prev) {
                        newPreviousNode.prev.next = newPreviousNode;
                    } else {
                        // If the previous of the previous node does not exist, it means that
                        // `newPreviousNode` must be the new `startingNode`.
                        startingNode = newPreviousNode;
                    }
                }

                // Create a new node which represents the result of the merge.
                const merged = {
                    token: node.token + node.next.token,
                    bias: node.bias,
                    prev: node.prev,
                    next: node.next.next,
                }

                // We now consider where we can add the new merged node to the priority queue:
                // 1. prev <-> merged
                if (merged.prev) {
                    merged.prev.next = merged;
                    this._add_node(queue, merged.prev);
                } else {
                    // If `merged.prev` does not exist, then `merged` must be the new `startingNode`.
                    startingNode = merged;
                }

                // 2. merged <-> next
                if (merged.next) {
                    merged.next.prev = merged;
                    this._add_node(queue, merged);
                }
            }

            // Traverse the linked list, starting from the `startingNode`, and collect the tokens.
            for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) {
                result.push(currentNode.token);
            }
        } else {
            result = word;
        }

        // Possibly append suffix
        if (this.continuing_subword_suffix) {
            // Do not append suffix to the last token
            for (let i = 0; i < result.length - 1; ++i) {
                result[i] += this.continuing_subword_suffix;
            }
        }

        // Save the result to the cache
        this.cache.set(token, result);

        return result;
    }


    /**
     * Helper function to add a node to the priority queue.
     * @param {PriorityQueue} queue 
     * @param {BPENode} node
     * @private
     */
    _add_node(queue, node) {
        // `score` is a measure of the merge priority: lower means higher priority
        // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list)
        // We also add a fractional component to the score to break ties (with the earlier character having higher priority)
        const rank = this.bpe_ranks.get(node.token + this.BPE_SPLIT_TOKEN + node.next.token);
        if (rank !== undefined) {
            node.score = rank + node.bias;
            queue.push(node);
        }
    }

    /**
     * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.
     * @param {string[]} tokens The input sequence of tokens to encode.
     * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.
     */
    encode(tokens) {
        const outputTokens = [];

        for (const token of tokens) {
            if (this.ignore_merges && this.tokens_to_ids.has(token)) {
                outputTokens.push(token);
                continue;
            }
            const bpe_token_list = this.bpe(token);

            for (const t of bpe_token_list) {
                if (this.tokens_to_ids.has(t)) {
                    outputTokens.push(t);
                } else {
                    if (this.byte_fallback) {
                        outputTokens.push(
                            ...Array.from(this.text_encoder.encode(t))
                                .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`)
                        );
                    } else {
                        outputTokens.push(this.unk_token);
                    }
                }
            }
        }

        return outputTokens;
    }

}

/**
 * Legacy tokenizer class for tokenizers with only a vocabulary.
 */
class LegacyTokenizerModel extends TokenizerModel {
    /**
     * Create a LegacyTokenizerModel instance.
     * @param {Object} config The configuration object for LegacyTokenizerModel.
     * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.
     * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.
     */
    constructor(config, moreConfig) {
        super(config);

        /**@type {Map<string, number>} */
        this.tokens_to_ids = objectToMap(
            moreConfig.target_lang
                ? config.vocab[moreConfig.target_lang]
                : config.vocab
        );

        this.bos_token = moreConfig.bos_token;
        this.bos_token_id = this.tokens_to_ids.get(this.bos_token);

        this.eos_token = moreConfig.eos_token;
        this.eos_token_id = this.tokens_to_ids.get(this.eos_token);

        this.pad_token = moreConfig.pad_token;
        this.pad_token_id = this.tokens_to_ids.get(this.pad_token);

        this.unk_token = moreConfig.unk_token;
        this.unk_token_id = this.tokens_to_ids.get(this.unk_token);

        this.vocab = new Array(this.tokens_to_ids.size);
        for (const [key, value] of this.tokens_to_ids) {
            this.vocab[value] = key;
        }
    }

    encode(tokens) {
        return tokens;
    }
}


/**
 * A base class for text normalization.
 * @abstract
 */
class Normalizer extends _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
    /**
     * @param {Object} config The configuration object for the normalizer.
     */
    constructor(config) {
        super();
        this.config = config;
    }

    /**
     * Factory method for creating normalizers from config objects.
     * @static
     * @param {Object} config The configuration object for the normalizer.
     * @returns {Normalizer} A Normalizer object.
     * @throws {Error} If an unknown Normalizer type is specified in the config.
     */
    static fromConfig(config) {
        if (config === null) return null;
        switch (config.type) {
            case 'BertNormalizer':
                return new BertNormalizer(config);
            case 'Precompiled':
                return new Precompiled(config);
            case 'Sequence':
                return new NormalizerSequence(config);
            case 'Replace':
                return new Replace(config);
            case 'NFC':
                return new NFC(config);
            case 'NFKC':
                return new NFKC(config);
            case 'NFKD':
                return new NFKD(config);
            case 'Strip':
                return new StripNormalizer(config);
            case 'StripAccents':
                return new StripAccents(config);
            case 'Lowercase':
                return new Lowercase(config);
            case 'Prepend':
                return new Prepend(config);
            default:
                throw new Error(`Unknown Normalizer type: ${config.type}`);
        }
    }

    /**
     * Normalize the input text.
     * @abstract
     * @param {string} text The text to normalize.
     * @returns {string} The normalized text.
     * @throws {Error} If this method is not implemented in a subclass.
     */
    normalize(text) {
        throw Error("normalize should be implemented in subclass.")
    }

    /**
     * Alias for {@link Normalizer#normalize}.
     * @param {string} text The text to normalize.
     * @returns {string} The normalized text.
     */
    _call(text) {
        return this.normalize(text);
    }

}

/**
 * Replace normalizer that replaces occurrences of a pattern with a given string or regular expression.
 * @extends Normalizer
 */
class Replace extends Normalizer {
    /**
     * Normalize the input text by replacing the pattern with the content.
     * @param {string} text The input text to be normalized.
     * @returns {string} The normalized text after replacing the pattern with the content.
     */
    normalize(text) {
        const pattern = createPattern(this.config.pattern);
        return pattern === null
            ? text
            : text.replaceAll(pattern, this.config.content);
    }
}

/**
 * A normalizer that applies Unicode normalization form C (NFC) to the input text.
 * @extends Normalizer
 */
class NFC extends Normalizer {
    /**
     * Normalize the input text by applying Unicode normalization form C (NFC).
     * @param {string} text The input text to be normalized.
     * @returns {string} The normalized text.
     */
    normalize(text) {
        text = text.normalize('NFC')
        return text;
    }
}

/**
 * NFKC Normalizer.
 * @extends Normalizer
 */
class NFKC extends Normalizer {
    /**
     * Normalize text using NFKC normalization.
     * @param {string} text The text to be normalized.
     * @returns {string} The normalized text.
     */
    normalize(text) {
        text = text.normalize('NFKC')
        return text;
    }
}
/**
 * NFKD Normalizer.
 * @extends Normalizer
 */
class NFKD extends Normalizer {
    /**
     * Normalize text using NFKD normalization.
     * @param {string} text The text to be normalized.
     * @returns {string} The normalized text.
     */
    normalize(text) {
        text = text.normalize('NFKD')
        return text;
    }
}

/**
 * A normalizer that strips leading and/or trailing whitespace from the input text.
 */
class StripNormalizer extends Normalizer {
    /**
     * Strip leading and/or trailing whitespace from the input text.
     * @param {string} text The input text.
     * @returns {string} The normalized text.
     */
    normalize(text) {
        if (this.config.strip_left && this.config.strip_right) {
            // Fast path to avoid an extra trim call
            text = text.trim();
        } else {
            if (this.config.strip_left) {
                text = text.trimStart();
            }
            if (this.config.strip_right) {
                text = text.trimEnd();
            }
        }
        return text;
    }
}

/**
 * StripAccents normalizer removes all accents from the text.
 * @extends Normalizer
 */
class StripAccents extends Normalizer {
    /**
     * Remove all accents from the text.
     * @param {string} text The input text.
     * @returns {string} The normalized text without accents.
     */
    normalize(text) {
        text = remove_accents(text);
        return text;
    }
}

/**
 * A Normalizer that lowercases the input string.
 * @extends Normalizer
 */
class Lowercase extends Normalizer {
    /**
     * Lowercases the input string.
     * @param {string} text The text to normalize.
     * @returns {string} The normalized text.
     */
    normalize(text) {
        text = text.toLowerCase();
        return text;
    }
}

/**
 * A Normalizer that prepends a string to the input string.
 * @extends Normalizer
 */
class Prepend extends Normalizer {
    /**
     * Prepends the input string.
     * @param {string} text The text to normalize.
     * @returns {string} The normalized text.
     */
    normalize(text) {
        text = this.config.prepend + text;
        return text;
    }
}

/**
 * A Normalizer that applies a sequence of Normalizers.
 * @extends Normalizer
 */
class NormalizerSequence extends Normalizer {
    /**
   * Create a new instance of NormalizerSequence.
   * @param {Object} config The configuration object.
   * @param {Object[]} config.normalizers An array of Normalizer configuration objects.
   */
    constructor(config) {
        super(config);
        this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x));
    }
    /**
    * Apply a sequence of Normalizers to the input text.
    * @param {string} text The text to normalize.
    * @returns {string} The normalized text.
    */
    normalize(text) {
        return this.normalizers.reduce((t, normalizer) => {
            return normalizer.normalize(t);
        }, text);
    }
}

/**
 * A class representing a normalizer used in BERT tokenization.
 * @extends Normalizer
 */
class BertNormalizer extends Normalizer {
    /**
     * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.
     *
     * @param {string} text The input text to tokenize.
     * @returns {string} The tokenized text with whitespace added around CJK characters.
     */
    _tokenize_chinese_chars(text) {
        /* Adds whitespace around any CJK character. */
        const output = [];
        for (let i = 0; i < text.length; ++i) {
            const char = text[i];
            const cp = char.charCodeAt(0);
            if (this._is_chinese_char(cp)) {
                output.push(" ");
                output.push(char);
                output.push(" ");
            } else {
                output.push(char);
            }
        }
        return output.join("");
    }

    /**
     * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.
     *
     * A "chinese character" is defined as anything in the CJK Unicode block:
     * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
     *
     * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.
     * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.
     * Those alphabets are used to write space-separated words, so they are not treated specially
     * and are handled like all other languages.
     *
     * @param {number} cp The Unicode codepoint to check.
     * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.
     */
    _is_chinese_char(cp) {
        return (
            (cp >= 0x4E00 && cp <= 0x9FFF)
            || (cp >= 0x3400 && cp <= 0x4DBF)
            || (cp >= 0x20000 && cp <= 0x2A6DF)
            || (cp >= 0x2A700 && cp <= 0x2B73F)
            || (cp >= 0x2B740 && cp <= 0x2B81F)
            || (cp >= 0x2B820 && cp <= 0x2CEAF)
            || (cp >= 0xF900 && cp <= 0xFAFF)
            || (cp >= 0x2F800 && cp <= 0x2FA1F)
        )
    }
    /**
     * Strips accents from the given text.
     * @param {string} text The text to strip accents from.
     * @returns {string} The text with accents removed.
     */
    stripAccents(text) {
        return text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
    }


    /**
     * Checks whether `char` is a control character.
     * @param {string} char The character to check.
     * @returns {boolean} Whether `char` is a control character.
     * @private
     */
    _is_control(char) {
        switch (char) {
            case '\t':
            case '\n':
            case '\r':
                // These are technically control characters but we count them as whitespace characters.
                return false;

            default:
                // Check if unicode category starts with C:
                // Cc - Control
                // Cf - Format
                // Co - Private Use
                // Cs - Surrogate
                return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char);
        }
    }

    /**
     * Performs invalid character removal and whitespace cleanup on text.
     * @param {string} text The text to clean.
     * @returns {string} The cleaned text.
     * @private
     */
    _clean_text(text) {
        const output = [];
        for (const char of text) {
            const cp = char.charCodeAt(0);
            if (cp === 0 || cp === 0xFFFD || this._is_control(char)) {
                continue;
            }
            if (/^\s$/.test(char)) { // is whitespace
                output.push(" ");
            } else {
                output.push(char);
            }
        }
        return output.join("");
    }
    /**
     * Normalizes the given text based on the configuration.
     * @param {string} text The text to normalize.
     * @returns {string} The normalized text.
     */
    normalize(text) {
        if (this.config.clean_text) {
            text = this._clean_text(text);
        }

        if (this.config.handle_chinese_chars) {
            text = this._tokenize_chinese_chars(text);
        }

        if (this.config.lowercase) {
            text = text.toLowerCase();

            if (this.config.strip_accents !== false) {
                text = this.stripAccents(text);
            }
        } else if (this.config.strip_accents) {
            text = this.stripAccents(text);
        }

        return text;
    }
}

/**
 * A callable class representing a pre-tokenizer used in tokenization. Subclasses
 * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic.
 * @extends Callable
 */
class PreTokenizer extends _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
    /**
   * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.
   *
   * @static
   * @param {Object} config A configuration object for the pre-tokenizer.
   * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.
   * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.
   */
    static fromConfig(config) {
        if (config === null) return null;

        switch (config.type) {
            case 'BertPreTokenizer':
                return new BertPreTokenizer(config);
            case 'Sequence':
                return new PreTokenizerSequence(config);
            case 'Whitespace':
                return new WhitespacePreTokenizer(config);
            case 'WhitespaceSplit':
                return new WhitespaceSplit(config);
            case 'Metaspace':
                return new MetaspacePreTokenizer(config);

            case 'ByteLevel':
                return new ByteLevelPreTokenizer(config);
            case 'Split':
                return new SplitPreTokenizer(config);
            case 'Punctuation':
                return new PunctuationPreTokenizer(config);
            case 'Digits':
                return new DigitsPreTokenizer(config);
            case 'Replace':
                return new ReplacePreTokenizer(config);
            default:
                throw new Error(`Unknown PreTokenizer type: ${config.type}`);
        }
    }

    /**
     * Method that should be implemented by subclasses to define the specific pre-tokenization logic.
     *
     * @abstract
     * @param {string} text The text to pre-tokenize.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} The pre-tokenized text.
     * @throws {Error} If the method is not implemented in the subclass.
     */
    pre_tokenize_text(text, options) {
        throw Error("pre_tokenize_text should be implemented in subclass.")
    }

    /**
     * Tokenizes the given text into pre-tokens.
     * @param {string|string[]} text The text or array of texts to pre-tokenize.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} An array of pre-tokens.
     */
    pre_tokenize(text, options) {
        return (Array.isArray(text)
            ? text.map(x => this.pre_tokenize_text(x, options))
            : this.pre_tokenize_text(text, options)
        ).flat();
    }

    /**
     * Alias for {@link PreTokenizer#pre_tokenize}.
     * @param {string|string[]} text The text or array of texts to pre-tokenize.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} An array of pre-tokens.
     */
    _call(text, options) {
        return this.pre_tokenize(text, options);
    }
}

/**
 * @extends PreTokenizer
 */
class BertPreTokenizer extends PreTokenizer {
    /**
     * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme
     * similar to that used in the original implementation of BERT.
     * 
     * @param {Object} config The configuration object.
     */
    constructor(config) {
        super();
        // Construct a pattern which matches the rust implementation:
        // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11
        // Equivalent to removing whitespace and splitting on punctuation (both \p{P} and other ascii characters)
        this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu');
    }
    /**
     * Tokenizes a single text using the BERT pre-tokenization scheme.
     * 
     * @param {string} text The text to tokenize.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} An array of tokens.
     */
    pre_tokenize_text(text, options) {
        return text.trim().match(this.pattern) || [];
    }
}

/**
 * A pre-tokenizer that splits text into Byte-Pair-Encoding (BPE) subwords.
 * @extends PreTokenizer
 */
class ByteLevelPreTokenizer extends PreTokenizer {
    /**
     * Creates a new instance of the `ByteLevelPreTokenizer` class.
     * @param {Object} config The configuration object.
     */
    constructor(config) {
        super();
        this.config = config;

        /**
         * @type {boolean} Whether to add a leading space to the first word.
         * This allows to treat the leading word just as any other word.
         */
        this.add_prefix_space = this.config.add_prefix_space;

        /**
         * @type {boolean} Whether the post processing step should trim offsets
         * to avoid including whitespaces.
         * @todo Use this in the pretokenization step.
         */
        this.trim_offsets = this.config.trim_offsets;

        /**
         * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting.
         * Set it to False if you want to use your own splitting. Defaults to true.
         */
        this.use_regex = this.config.use_regex ?? true;
        this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;

        this.byte_encoder = BYTES_TO_UNICODE;
        this.text_encoder = new TextEncoder();
    }

    /**
     * Tokenizes a single piece of text using byte-level tokenization.
     * @param {string} text The text to tokenize.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} An array of tokens.
     */
    pre_tokenize_text(text, options) {
        // Add a leading space if the option is enabled
        if (this.add_prefix_space && !text.startsWith(' ')) {
            text = ' ' + text;
        }

        // Split on whitespace and punctuation
        const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text];

        // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
        return tokens.map(
            token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('')
        );
    }
}

/**
 * @typedef {'removed'|'isolated'|'mergedWithPrevious'|'mergedWithNext'|'contiguous'} SplitDelimiterBehavior
 */

/**
 * Splits text using a given pattern.
 * @extends PreTokenizer
 */
class SplitPreTokenizer extends PreTokenizer {
    /**
     * @param {Object} config The configuration options for the pre-tokenizer.
     * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
     * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.
     * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.
     * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
     * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.
     */
    constructor(config) {
        super();
        this.config = config;
        // TODO support all behaviours (config.behavior)

        this.pattern = createPattern(this.config.pattern, this.config.invert);
    }

    /**
     * Tokenizes text by splitting it using the given pattern.
     * @param {string} text The text to tokenize.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} An array of tokens.
     */
    pre_tokenize_text(text, options) {
        if (this.pattern === null) {
            return [];
        }

        if (this.config.invert) {
            return text.match(this.pattern) || [];
        } else {
            return regexSplit(text, this.pattern);
        }
    }
}

/**
 * Splits text based on punctuation.
 * @extends PreTokenizer
 */
class PunctuationPreTokenizer extends PreTokenizer {
    /**
     * @param {Object} config The configuration options for the pre-tokenizer.
     * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
     */
    constructor(config) {
        super();
        this.config = config;
        this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu');
    }

    /**
     * Tokenizes text by splitting it using the given pattern.
     * @param {string} text The text to tokenize.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} An array of tokens.
     */
    pre_tokenize_text(text, options) {
        return text.match(this.pattern) || [];
    }
}


/**
 * Splits text based on digits.
 * @extends PreTokenizer
 */
class DigitsPreTokenizer extends PreTokenizer {
    /**
     * @param {Object} config The configuration options for the pre-tokenizer.
     * @param {boolean} config.individual_digits Whether to split on individual digits.
     */
    constructor(config) {
        super();
        this.config = config;

        // Construct a pattern which matches the rust implementation:
        const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? '' : '+'}`;
        this.pattern = new RegExp(digit_pattern, 'gu');
    }

    /**
     * Tokenizes text by splitting it using the given pattern.
     * @param {string} text The text to tokenize.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} An array of tokens.
     */
    pre_tokenize_text(text, options) {
        return text.match(this.pattern) || [];
    }
}

/**
 * @typedef {Object} PostProcessedOutput
 * @property {string[]} tokens List of token produced by the post-processor.
 * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor.
 */


/**
 * @typedef {Object} EncodingSingle
 * @property {number[]} input_ids List of token ids to be fed to a model.
 * @property {number[]} attention_mask List of token type ids to be fed to a model
 * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model
 */


/**
 * @extends Callable
 */
class PostProcessor extends _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.Callable {

    /**
     * @param {Object} config The configuration for the post-processor.
     */
    constructor(config) {
        super();
        this.config = config;
    }

    /**
     * Factory method to create a PostProcessor object from a configuration object.
     *
     * @param {Object} config Configuration object representing a PostProcessor.
     * @returns {PostProcessor} A PostProcessor object created from the given configuration.
     * @throws {Error} If an unknown PostProcessor type is encountered.
     */
    static fromConfig(config) {
        if (config === null) return null;
        switch (config.type) {
            case 'TemplateProcessing':
                return new TemplateProcessing(config);

            case 'ByteLevel':
                return new ByteLevelPostProcessor(config);

            case 'RobertaProcessing':
                return new RobertaProcessing(config);
            case 'BertProcessing':
                return new BertProcessing(config);

            case 'Sequence':
                return new PostProcessorSequence(config);
            default:
                throw new Error(`Unknown PostProcessor type: ${config.type}`);
        }
    }

    /**
     * Method to be implemented in subclass to apply post-processing on the given tokens.
     *
     * @param {Array} tokens The input tokens to be post-processed.
     * @param {...*} args Additional arguments required by the post-processing logic.
     * @returns {PostProcessedOutput} The post-processed tokens.
     * @throws {Error} If the method is not implemented in subclass.
     */
    post_process(tokens, ...args) {
        throw Error("post_process should be implemented in subclass.")
    }

    /**
     * Alias for {@link PostProcessor#post_process}.
     * @param {Array} tokens The text or array of texts to post-process.
     * @param {...*} args Additional arguments required by the post-processing logic.
     * @returns {PostProcessedOutput} The post-processed tokens.
     */
    _call(tokens, ...args) {
        return this.post_process(tokens, ...args);
    }
}

/**
 * A post-processor that adds special tokens to the beginning and end of the input.
 */
class BertProcessing extends PostProcessor {
    /**
     * @param {Object} config The configuration for the post-processor.
     * @param {string[]} config.cls The special tokens to add to the beginning of the input.
     * @param {string[]} config.sep The special tokens to add to the end of the input.
     */
    constructor(config) {
        super(config);
        // TODO use all of config: add_prefix_space, trim_offsets

        this.cls = config.cls[0];
        this.sep = config.sep[0];
    }

    /**
     * Adds the special tokens to the beginning and end of the input.
     * @param {string[]} tokens The input tokens.
     * @param {string[]} [tokens_pair=null] An optional second set of input tokens.
     * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.
     */
    post_process(tokens, tokens_pair = null, {
        add_special_tokens = true,
    } = {}) {
        if (add_special_tokens) {
            tokens = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)([this.cls], tokens, [this.sep]);
        }

        let token_type_ids = new Array(tokens.length).fill(0);
        if (tokens_pair !== null) {
            // NOTE: It is intended to add 2 EOS tokens after the first set of tokens
            // https://github.com/huggingface/tokenizers/issues/983
            const middle = (add_special_tokens && this instanceof RobertaProcessing)
                ? [this.sep]
                : [];
            const after = add_special_tokens ? [this.sep] : [];

            tokens = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(tokens, middle, tokens_pair, after);
            token_type_ids = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));
        }
        return { tokens, token_type_ids };
    }
}
class RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing

/**
 * Post processor that replaces special tokens in a template with actual tokens.
 * @extends PostProcessor
 */
class TemplateProcessing extends PostProcessor {
    /**
     * Creates a new instance of `TemplateProcessing`.
     * @param {Object} config The configuration options for the post processor.
     * @param {Array} config.single The template for a single sequence of tokens.
     * @param {Array} config.pair The template for a pair of sequences of tokens.
     */
    constructor(config) {
        super(config);

        this.single = config.single;
        this.pair = config.pair;
    }

    /**
     * Replaces special tokens in the template with actual tokens.
     * @param {string[]} tokens The list of tokens for the first sequence.
     * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
     * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.
     */
    post_process(tokens, tokens_pair = null, {
        add_special_tokens = true,
    } = {}) {
        const type = tokens_pair === null ? this.single : this.pair

        let processedTokens = [];
        let types = [];
        for (const item of type) {
            if ('SpecialToken' in item) {
                if (add_special_tokens) {
                    processedTokens.push(item.SpecialToken.id);
                    types.push(item.SpecialToken.type_id);
                }
            } else if ('Sequence' in item) {
                if (item.Sequence.id === 'A') {
                    processedTokens = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(processedTokens, tokens);
                    types = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(types, new Array(tokens.length).fill(item.Sequence.type_id));

                } else if (item.Sequence.id === 'B') {
                    processedTokens = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(processedTokens, tokens_pair);
                    types = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));
                }
            }
        }
        return { tokens: processedTokens, token_type_ids: types };
    }
}

/**
 * A PostProcessor that returns the given tokens as is.
 * @extends PostProcessor
 */
class ByteLevelPostProcessor extends PostProcessor {
    /**
     * Post process the given tokens.
     * @param {string[]} tokens The list of tokens for the first sequence.
     * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
     * @returns {PostProcessedOutput} An object containing the post-processed tokens.
     */
    post_process(tokens, tokens_pair = null) {
        if (tokens_pair) {
            tokens = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(tokens, tokens_pair);
        }
        return { tokens };
    }
}


/**
 * A post-processor that applies multiple post-processors in sequence.
 */
class PostProcessorSequence extends PostProcessor {

    /**
     * Creates a new instance of PostProcessorSequence.
     * @param {Object} config The configuration object.
     * @param {Object[]} config.processors The list of post-processors to apply.
     */
    constructor(config) {
        super(config);

        this.processors = config.processors.map(x => PostProcessor.fromConfig(x));
    }

    /**
     * Post process the given tokens.
     * @param {string[]} tokens The list of tokens for the first sequence.
     * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
     * @returns {PostProcessedOutput} An object containing the post-processed tokens.
     */
    post_process(tokens, tokens_pair = null, options = {}) {
        let token_type_ids;
        for (const processor of this.processors) {
            if (processor instanceof ByteLevelPostProcessor) {
                // Special case where we need to pass the tokens_pair to the post-processor
                const output = processor.post_process(tokens);
                tokens = output.tokens;
                if (tokens_pair) {
                    const pair_output = processor.post_process(tokens_pair);
                    tokens_pair = pair_output.tokens;
                }
            } else {
                const output = processor.post_process(tokens, tokens_pair, options);
                tokens = output.tokens;
                token_type_ids = output.token_type_ids;
            }
        }
        return { tokens, token_type_ids };
    }
}

/**
 * The base class for token decoders.
 * @extends Callable
 */
class Decoder extends _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.Callable {

    /**
    * Creates an instance of `Decoder`.
    *
    * @param {Object} config The configuration object.
    */
    constructor(config) {
        super();
        this.config = config;

        /** @type {AddedToken[]} */
        this.added_tokens = [];
        this.end_of_word_suffix = null;
        this.trim_offsets = config.trim_offsets;
    }

    /**
   * Creates a decoder instance based on the provided configuration.
   *
   * @param {Object} config The configuration object.
   * @returns {Decoder} A decoder instance.
   * @throws {Error} If an unknown decoder type is provided.
   */
    static fromConfig(config) {
        if (config === null) return null;
        switch (config.type) {
            case 'WordPiece':
                return new WordPieceDecoder(config);
            case 'Metaspace':
                return new MetaspaceDecoder(config);
            case 'ByteLevel':
                return new ByteLevelDecoder(config);

            case 'Replace':
                return new ReplaceDecoder(config);
            case 'ByteFallback':
                return new ByteFallback(config);
            case 'Fuse':
                return new FuseDecoder(config);
            case 'Strip':
                return new StripDecoder(config);

            case 'Sequence':
                return new DecoderSequence(config);

            case 'CTC':
                return new CTCDecoder(config);
            case 'BPEDecoder':
                return new BPEDecoder(config);
            default:
                throw new Error(`Unknown Decoder type: ${config.type}`);
        }
    }

    /**
    * Calls the `decode` method.
    *
    * @param {string[]} tokens The list of tokens.
    * @returns {string} The decoded string.
    */
    _call(tokens) {
        return this.decode(tokens);
    }

    /**
    * Decodes a list of tokens.
    * @param {string[]} tokens The list of tokens.
    * @returns {string} The decoded string.
    */
    decode(tokens) {
        return this.decode_chain(tokens).join('');
    }

    /**
     * Apply the decoder to a list of tokens.
     * 
     * @param {string[]} tokens The list of tokens.
     * @returns {string[]} The decoded list of tokens.
     * @throws {Error} If the `decode_chain` method is not implemented in the subclass.
     */
    decode_chain(tokens) {
        throw Error("`decode_chain` should be implemented in subclass.")
    }

}

class ReplaceDecoder extends Decoder {

    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {
        const pattern = createPattern(this.config.pattern);
        return pattern === null
            ? tokens
            : tokens.map(token => token.replaceAll(pattern, this.config.content))
    }
}


class ByteFallback extends Decoder {
    constructor(config) {
        super(config);

        this.text_decoder = new TextDecoder();
    }

    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {

        const new_tokens = [];
        let previous_byte_tokens = [];

        for (const token of tokens) {
            let bytes = null;
            if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) {
                const byte = parseInt(token.slice(3, 5), 16);
                if (!isNaN(byte)) {
                    bytes = byte;
                }
            }
            if (bytes !== null) {
                previous_byte_tokens.push(bytes);
            } else {
                if (previous_byte_tokens.length > 0) {
                    const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
                    new_tokens.push(string);
                    previous_byte_tokens = [];
                }
                new_tokens.push(token);
            }
        }
        if (previous_byte_tokens.length > 0) {
            const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
            new_tokens.push(string);
            previous_byte_tokens = [];
        }

        return new_tokens;
    }
}

/**
 * Fuse simply fuses all tokens into one big string.
 * It's usually the last decoding step anyway, but this decoder
 * exists incase some decoders need to happen after that step
 */
class FuseDecoder extends Decoder {

    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {
        return [tokens.join('')];
    }
}


class StripDecoder extends Decoder {
    constructor(config) {
        super(config);

        this.content = this.config.content;
        this.start = this.config.start;
        this.stop = this.config.stop;
    }

    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {
        return tokens.map(token => {
            let start_cut = 0;
            for (let i = 0; i < this.start; ++i) {
                if (token[i] === this.content) {
                    start_cut = i + 1;
                    continue;
                } else {
                    break;
                }
            }

            let stop_cut = token.length;
            for (let i = 0; i < this.stop; ++i) {
                const index = token.length - i - 1;
                if (token[index] === this.content) {
                    stop_cut = index;
                    continue;
                } else {
                    break;
                }
            }

            return token.slice(start_cut, stop_cut)
        });
    }
}

/**
 * A decoder that decodes a list of WordPiece tokens into a single string.
 * @extends Decoder
 */
class WordPieceDecoder extends Decoder {

    /**
     * Creates a new instance of WordPieceDecoder.
     * @param {Object} config The configuration object.
     * @param {string} config.prefix The prefix used for WordPiece encoding.
     * @param {boolean} config.cleanup Whether to cleanup the decoded string.
     */
    constructor(config) {
        super(config);
        this.cleanup = config.cleanup;
    }

    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {
        return tokens.map((token, i) => {
            if (i !== 0) {
                if (token.startsWith(this.config.prefix)) {
                    // NOTE: .replace() is intended; only replace first occurrence
                    token = token.replace(this.config.prefix, '');
                } else {
                    token = ' ' + token;
                }
            }
            if (this.cleanup) {
                token = clean_up_tokenization(token)
            }

            return token;
        });
    }
}

/**
 * Byte-level decoder for tokenization output. Inherits from the `Decoder` class.
 * @extends Decoder
 */
class ByteLevelDecoder extends Decoder {

    /**
     * Create a `ByteLevelDecoder` object.
     * @param {Object} config Configuration object.
     */
    constructor(config) {
        super(config);

        this.byte_decoder = UNICODE_TO_BYTES;
        this.text_decoder = new TextDecoder("utf-8", {
            fatal: false,
            ignoreBOM: true,
        });

        this.end_of_word_suffix = null;
    }

    /**
     * Convert an array of tokens to string by decoding each byte.
     * @param {string[]} tokens Array of tokens to be decoded.
     * @returns {string} The decoded string.
     */
    convert_tokens_to_string(tokens) {
        const text = tokens.join('');
        const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c]));
        const decoded_text = this.text_decoder.decode(byteArray);
        return decoded_text;
    }

    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {
        // TODO move to base class (like HF)
        // tokens === filtered_tokens

        // To avoid mixing byte-level and unicode for byte-level BPT
        // we need to build string separately for added tokens and byte-level tokens
        // cf. https://github.com/huggingface/transformers/issues/1133
        const sub_texts = [];
        let current_sub_text = [];
        for (const token of tokens) {
            // tokens sent here are already filtered, so we don't need to do this
            // if (skip_special_tokens && this.all_special_ids.includes(token)) {
            //     continue;
            // }

            if (this.added_tokens.find(x => x.content === token) !== undefined) {
                if (current_sub_text.length > 0) {
                    sub_texts.push(this.convert_tokens_to_string(current_sub_text));
                    current_sub_text = [];
                }
                sub_texts.push(token);
            } else {
                current_sub_text.push(token);
            }
        }
        if (current_sub_text.length > 0) {
            sub_texts.push(this.convert_tokens_to_string(current_sub_text));
        }

        // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options

        return sub_texts;
    }
}

/**
 * The CTC (Connectionist Temporal Classification) decoder.
 * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs
 */
class CTCDecoder extends Decoder {

    constructor(config) {
        super(config);

        this.pad_token = this.config.pad_token;
        this.word_delimiter_token = this.config.word_delimiter_token;
        this.cleanup = this.config.cleanup;
    }
    /**
     * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.
     * @param {string[]} tokens Array of tokens to be decoded.
     * @returns {string} The decoded string.
     */
    convert_tokens_to_string(tokens) {
        if (tokens.length === 0) return '';

        // group same tokens into non-repeating tokens in CTC style decoding
        const grouped_tokens = [tokens[0]];
        for (let i = 1; i < tokens.length; ++i) {
            if (tokens[i] !== grouped_tokens.at(-1)) {
                grouped_tokens.push(tokens[i]);
            }
        }

        // filter self.pad_token which is used as CTC-blank token
        const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token);

        let text = filtered_tokens.join('');
        if (this.cleanup) {
            // cleanup and replace delimiter token
            text = clean_up_tokenization(text)
                .replaceAll(this.word_delimiter_token, ' ')
                .trim();
        }
        return text;
    }


    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {
        return [this.convert_tokens_to_string(tokens)];
    }
}

/**
 * Apply a sequence of decoders.
 * @extends Decoder
 */
class DecoderSequence extends Decoder {

    /**
     * Creates a new instance of DecoderSequence.
     * @param {Object} config The configuration object.
     * @param {Object[]} config.decoders The list of decoders to apply.
     */
    constructor(config) {
        super(config);
        this.decoders = config.decoders.map(x => Decoder.fromConfig(x));
    }

    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {
        // Use reduce to apply each decoder to the tokens
        return this.decoders.reduce((toks, decoder) => {
            return decoder.decode_chain(toks);
        }, tokens);
    }

}

class BPEDecoder extends Decoder {
    constructor(config) {
        super(config);

        this.suffix = this.config.suffix;
    }
    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {
        return tokens.map((token, i) => {
            return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ')
        });
    }
}

// Custom decoder for VITS
class VitsDecoder extends Decoder {
    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {
        let decoded = '';
        for (let i = 1; i < tokens.length; i += 2) {
            decoded += tokens[i];
        }
        return [decoded];
    }
}


/**
 * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested,
 * and returns a list of tokens.
 * @extends PreTokenizer
 */
class MetaspacePreTokenizer extends PreTokenizer {
    /**
     * @param {Object} config The configuration object for the MetaspacePreTokenizer.
     * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token.
     * @param {string} config.replacement The character to replace spaces with.
     * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.
     * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.
     */
    constructor(config) {
        super();

        this.addPrefixSpace = config.add_prefix_space;
        this.replacement = config.replacement;
        this.strRep = config.str_rep || this.replacement;
        this.prepend_scheme = config.prepend_scheme ?? 'always';
    }

    /**
     * This method takes a string, replaces spaces with the replacement character,
     * adds a prefix space if requested, and returns a new list of tokens.
     * @param {string} text The text to pre-tokenize.
     * @param {Object} [options] The options for the pre-tokenization.
     * @param {number} [options.section_index] The index of the section to pre-tokenize.
     * @returns {string[]} A new list of pre-tokenized tokens.
     */
    pre_tokenize_text(text, {
        section_index = undefined,
    } = {}) {

        let normalized = text.replaceAll(' ', this.strRep);

        if (
            // We add a prefix space if:
            //  (1) The addPrefixSpace option is enabled and the normalized
            //      token does not already start with the replacement character.
            (this.addPrefixSpace && !normalized.startsWith(this.replacement))

            // and (2) either:
            //  (a) prepend_scheme is 'always'
            //  (b) prepend_scheme is 'first' and this is the first section
            && (
                this.prepend_scheme === 'always' ||
                (this.prepend_scheme === 'first' && section_index === 0)
            )
        ) {
            normalized = this.strRep + normalized;
        }
        return [normalized];
    }
}

/**
 * MetaspaceDecoder class extends the Decoder class and decodes Metaspace tokenization.
 * @extends Decoder
 */
class MetaspaceDecoder extends Decoder {
    /**
     * Constructs a new MetaspaceDecoder object.
     * @param {Object} config The configuration object for the MetaspaceDecoder.
     * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string.
     * @param {string} config.replacement The string to replace spaces with.
     */
    constructor(config) {
        super(config);

        this.addPrefixSpace = config.add_prefix_space;
        this.replacement = config.replacement;
    }

    /** @type {Decoder['decode_chain']} */
    decode_chain(tokens) {
        const result = [];
        for (let i = 0; i < tokens.length; ++i) {
            let normalized = tokens[i].replaceAll(this.replacement, ' ');
            if (this.addPrefixSpace && i == 0 && normalized.startsWith(' ')) {
                normalized = normalized.substring(1);
            }
            result.push(normalized);
        }
        return result;
    }
}

/**
 * A normalizer that applies a precompiled charsmap.
 * This is useful for applying complex normalizations in C++ and exposing them to JavaScript.
 * @extends Normalizer
 * @param {Object} config The configuration object for the Precompiled normalizer.
 * @param {Object} config.precompiled_charsmap The precompiled charsmap object.
 */
class Precompiled extends Normalizer {
    /**
     * Create a new instance of Precompiled normalizer.
     * @param {Object} config The configuration object.
     * @param {any} config.precompiled_charsmap Precompiled chars mapping.
     */
    constructor(config) {
        super(config);
        this.charsmap = config.precompiled_charsmap;
    }

    /**
     * Normalizes the given text by applying the precompiled charsmap.
     * @param {string} text The text to normalize.
     * @returns {string} The normalized text.
     */
    normalize(text) {
        // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule),
        // there are 5 pre-defined normalization rules:
        //  1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default)
        //  2. nfkc: original NFKC normalization.
        //  3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing)
        //  4. nfkc_cf: nfkc + Unicode case folding.
        //  5. identity: no normalization
        // 
        // For now, we only implement the default (nmt_nfkc).
        // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules.
        // TODO: detect when a different `this.charsmap` is used.

        text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ''); // Remove control characters
        text = text.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm, '\u0020'); // Replace certain characters with a space

        if (text.includes('\uFF5E')) {
            // To match the sentencepiece implementation 100%, we must handle a very strange edge-case.
            // For some reason, the "Fullwidth Tilde" character (\uFF5E) should not be converted to the standard Tilde character (\u007E).
            // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character,
            // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character.
            const parts = text.split('\uFF5E');
            text = parts.map(part => part.normalize('NFKC')).join('\uFF5E');
        } else {
            text = text.normalize('NFKC');
        }

        return text;
    }
}

/**
 * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text.
 * @extends PreTokenizer
 */
class PreTokenizerSequence extends PreTokenizer {
    /**
     * Creates an instance of PreTokenizerSequence.
     * @param {Object} config The configuration object for the pre-tokenizer sequence.
     * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.
     */
    constructor(config) {
        super();
        this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x));
    }

    /**
     * Applies each pre-tokenizer in the sequence to the input text in turn.
     * @param {string} text The text to pre-tokenize.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} The pre-tokenized text.
     */
    pre_tokenize_text(text, options) {
        // Use reduce to apply each tokenizer to the text
        return this.tokenizers.reduce((preTokenizedText, tokenizer) => {
            return tokenizer.pre_tokenize(preTokenizedText, options);
        }, [text]);
    }
}

/**
 * Splits on word boundaries (using the following regular expression: `\w+|[^\w\s]+`).
 */
class WhitespacePreTokenizer extends PreTokenizer {
    /**
     * Creates an instance of WhitespacePreTokenizer.
     * @param {Object} config The configuration object for the pre-tokenizer.
     */
    constructor(config) {
        super();
    }
    /**
     * Pre-tokenizes the input text by splitting it on word boundaries.
     * @param {string} text The text to be pre-tokenized.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.
     */
    pre_tokenize_text(text, options) {
        return text.match(/\w+|[^\w\s]+/g) || [];
    }
}

/**
 * Splits a string of text by whitespace characters into individual tokens.
 * @extends PreTokenizer
 */
class WhitespaceSplit extends PreTokenizer {
    /**
     * Creates an instance of WhitespaceSplit.
     * @param {Object} config The configuration object for the pre-tokenizer.
     */
    constructor(config) {
        super();
    }
    /**
     * Pre-tokenizes the input text by splitting it on whitespace characters.
     * @param {string} text The text to be pre-tokenized.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.
     */
    pre_tokenize_text(text, options) {
        return whitespace_split(text);
    }
}

// NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`)
class ReplacePreTokenizer extends PreTokenizer {
    /**
     * @param {Object} config The configuration options for the pre-tokenizer.
     * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
     * @param {string} config.content What to replace the pattern with.
     */
    constructor(config) {
        super();
        this.config = config;
        this.pattern = createPattern(this.config.pattern);
        this.content = this.config.content;
    }

    /**
     * Pre-tokenizes the input text by replacing certain characters.
     * @param {string} text The text to be pre-tokenized.
     * @param {Object} [options] Additional options for the pre-tokenization logic.
     * @returns {string[]} An array of tokens produced by replacing certain characters.
     */
    pre_tokenize_text(text, options) {
        if (this.pattern === null) {
            return [text];
        }
        return [text.replaceAll(this.pattern, this.config.content)];
    }
}

const SPECIAL_TOKEN_ATTRIBUTES = [
    'bos_token',
    'eos_token',
    'unk_token',
    'sep_token',
    'pad_token',
    'cls_token',
    'mask_token',
    // additional_special_tokens (TODO)
]

/**
 * 
 * Helper function for padding values of an object, which are each arrays.
 * NOTE: No additional checks are made here for validity of arguments.
 * @param {Record<string, any[]>} item The input object.
 * @param {number} length The length to pad to.
 * @param {(key: string) => any} value_fn Determine the value to fill the array, based on its key.
 * @param {'right'|'left'} side Which side to pad the array.
 * @private
 */
function padHelper(item, length, value_fn, side) {
    for (const key of Object.keys(item)) {
        const diff = length - item[key].length;
        const value = value_fn(key);

        const padData = new Array(diff).fill(value);
        item[key] = side === 'right'
            ? (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(item[key], padData)
            : (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(padData, item[key]);
    }
}

/**
 * Helper function for truncating values of an object, which are each arrays.
 * NOTE: No additional checks are made here for validity of arguments.
 * @param {Record<string, any[]>} item The input object.
 * @param {number} length The length to truncate to.
 * @private
 */
function truncateHelper(item, length) {
    // Setting .length to a lower value truncates the array in-place:
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
    for (const key of Object.keys(item)) {
        item[key].length = length;
    }
}


/**
 * @typedef {Object} Message
 * @property {string} role The role of the message (e.g., "user" or "assistant" or "system").
 * @property {string} content The content of the message.
 */

class PreTrainedTokenizer extends _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
    return_token_type_ids = false;

    _default_chat_template = `{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}`;

    /**
     * Create a new PreTrainedTokenizer instance.
     * @param {Object} tokenizerJSON The JSON of the tokenizer.
     * @param {Object} tokenizerConfig The config of the tokenizer.
     */
    constructor(tokenizerJSON, tokenizerConfig) {
        super();

        this._tokenizer_config = tokenizerConfig;

        // Construct parts of the tokenizer from the JSON
        this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer);
        this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer);
        this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig);
        this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor);
        this.decoder = Decoder.fromConfig(tokenizerJSON.decoder);

        // Add added_tokens to model
        this.special_tokens = [];
        this.all_special_ids = [];

        /** @type {AddedToken[]} */
        this.added_tokens = [];
        for (const addedToken of tokenizerJSON.added_tokens) {
            const token = new AddedToken(addedToken);
            this.added_tokens.push(token);

            this.model.tokens_to_ids.set(token.content, token.id);
            this.model.vocab[token.id] = token.content;

            if (token.special) {
                this.special_tokens.push(token.content);
                this.all_special_ids.push(token.id);
            }
        }

        // Update additional_special_tokens
        this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? [];
        this.special_tokens.push(...this.additional_special_tokens);
        this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates

        if (this.decoder) {
            // Slight hack, but it prevents code duplication:
            this.decoder.added_tokens = this.added_tokens;

            // Another slight hack to add `end_of_word_suffix` (if present) to the decoder
            // This is needed for cases where BPE model and ByteLevel decoder are used
            // For more information, see https://github.com/xenova/transformers.js/issues/74
            // TODO: save this to the decoder when exporting?
            this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;
        }


        this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp(
            this.added_tokens.map(x => `${x.lstrip ? '\\s*' : ''}(${(0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.escapeRegExp)(x.content)})${x.rstrip ? '\\s*' : ''}`).join('|')
        ) : null;

        // Set mask token if present (otherwise will be undefined, which is fine)
        this.mask_token = this.getToken('mask_token');
        this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token);

        this.pad_token = this.getToken('pad_token', 'eos_token');
        this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token);

        this.sep_token = this.getToken('sep_token');
        this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token);

        this.unk_token = this.getToken('unk_token');
        this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token);

        this.model_max_length = tokenizerConfig.model_max_length;

        /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */
        this.remove_space = tokenizerConfig.remove_space;

        this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true;
        this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false;

        // TODO allow user to change this
        /** @type {'right'|'left'} */
        this.padding_side = 'right';

        this.legacy = false;

        this.chat_template = tokenizerConfig.chat_template ?? null;
        if (Array.isArray(this.chat_template)) {
            // Chat templates are stored as lists of dicts with fixed key names,
            // we reconstruct that into a single dict while loading them.
            const chat_template = Object.create(null);
            for (const { name, template } of this.chat_template) {
                if (typeof name !== 'string' || typeof template !== 'string') {
                    throw new Error('Chat template must be a list of objects with "name" and "template" properties');
                }
                chat_template[name] = template;
            }
            this.chat_template = chat_template;
        }
        this._compiled_template_cache = new Map();
    }

    /**
     * Returns the value of the first matching key in the tokenizer config object.
     * @param {...string} keys One or more keys to search for in the tokenizer config object.
     * @returns {string|null} The value associated with the first matching key, or null if no match is found.
     * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken".
     */
    getToken(...keys) {
        for (const key of keys) {
            const item = this._tokenizer_config[key];

            if (!item) continue;

            if (typeof item === 'object') {
                if (item.__type === 'AddedToken') {
                    return item.content;
                } else {
                    throw Error(`Unknown token: ${item}`);
                }
            } else {
                return item;
            }
        }
        return null;
    }

    /**
     * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. 
     * 
     * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.
     * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
     * 
     * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.
     * @returns {Promise<PreTrainedTokenizer>} A new instance of the `PreTrainedTokenizer` class.
     */
    static async from_pretrained(pretrained_model_name_or_path, {
        progress_callback = null,
        config = null,
        cache_dir = null,
        local_files_only = false,
        revision = 'main',
        legacy = null,
    } = {}) {

        const info = await loadTokenizer(pretrained_model_name_or_path, {
            progress_callback,
            config,
            cache_dir,
            local_files_only,
            revision,
            legacy,
        })

        // @ts-ignore
        return new this(...info);
    }

    /**
     * @typedef {number[]|number[][]|Tensor} BatchEncodingItem
     * 
     * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.
     * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.
     * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.
     * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.
     */

    /**
     * Encode/tokenize the given text(s).
     * @param {string|string[]} text The text to tokenize.
     * @param {Object} options An optional object containing the following properties:
     * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.
     * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.
     * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
     * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.
     * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.
     * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.
     * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids.
     * @returns {BatchEncoding} Object to be passed to the model.
     */
    _call(
        // Required positional arguments
        text,

        // Optional keyword arguments
        {
            text_pair = null,
            add_special_tokens = true,
            padding = false,
            truncation = null,
            max_length = null,
            return_tensor = true, // Different to HF
            return_token_type_ids = null,
        } = {},
    ) {

        const isBatched = Array.isArray(text);

        /** @type {EncodingSingle[]} */
        let encodedTokens;

        if (isBatched) {
            if (text.length === 0) {
                throw Error('text array must be non-empty')
            }

            if (text_pair !== null) {
                if (!Array.isArray(text_pair)) {
                    throw Error('text_pair must also be an array')

                } else if (text.length !== text_pair.length) {
                    throw Error('text and text_pair must have the same length')
                }

                encodedTokens = text.map(
                    (t, i) => this._encode_plus(t, text_pair[i], { add_special_tokens, return_token_type_ids })
                )

            } else {
                encodedTokens = text.map(x => this._encode_plus(x, null, { add_special_tokens, return_token_type_ids }));
            }

        } else {
            if (text === null || text === undefined) {
                throw Error('text may not be null or undefined')
            }

            if (Array.isArray(text_pair)) {
                throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).')
            }

            // For single input, we just wrap in an array, and then unwrap later.
            encodedTokens = [this._encode_plus(text, text_pair, { add_special_tokens, return_token_type_ids })];
        }
        // At this point, tokens is batched: [batch_size, tokens]
        // However, array may be jagged. So, we pad to max_length

        if (max_length === null) {
            if (padding === 'max_length') {
                max_length = this.model_max_length;
            } else {
                // Calculate max length from sequences
                max_length = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(encodedTokens.map(x => x.input_ids.length))[0];
            }
        } else {
            if (!truncation) {
                console.warn(`Truncation was not explicitly activated but \`max_length\` is provided a specific value, please use \`truncation=true\` to explicitly truncate examples to max length.`)
            }
        }

        // Ensure it is less than model max length
        max_length = Math.min(max_length, this.model_max_length)

        if (padding || truncation) {

            // Perform padding and/or truncation
            for (let i = 0; i < encodedTokens.length; ++i) {
                if (encodedTokens[i].input_ids.length === max_length) {
                    continue;

                } else if (encodedTokens[i].input_ids.length > max_length) {
                    // possibly truncate
                    if (truncation) {
                        truncateHelper(encodedTokens[i], max_length);
                    }

                } else { // t.length < max_length
                    // possibly pad
                    if (padding) {
                        padHelper(
                            encodedTokens[i],
                            max_length,
                            key => key === 'input_ids' ? this.pad_token_id : 0,
                            this.padding_side
                        );
                    }
                }
            }
        }

        const result = {};

        if (return_tensor) {
            if (!(padding && truncation)) {
                // Not, guaranteed that all items have same length, so
                // we perform additional check

                if (
                    encodedTokens.some(x => {
                        for (const key of Object.keys(x)) {
                            if (x[key].length !== encodedTokens[0][key]?.length) {
                                return true;
                            }
                        }
                        return false;
                    })
                ) {
                    throw Error(
                        "Unable to create tensor, you should probably activate truncation and/or padding " +
                        "with 'padding=true' and 'truncation=true' to have batched tensors with the same length."
                    )
                }
            }

            // Now we actually convert to tensor
            // NOTE: In the same way as the python library, we return a batched tensor, regardless of
            // whether we have a single input or multiple inputs.
            const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];

            for (const key of Object.keys(encodedTokens[0])) {
                result[key] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor('int64',
                    BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)),
                    dims
                );
            }

        } else {
            for (const key of Object.keys(encodedTokens[0])) {
                result[key] = encodedTokens.map(x => x[key]);
            }

            // If not returning a tensor, we match the input type
            if (!isBatched) {
                // Input was not batched, so we unwrap
                for (const key of Object.keys(result)) {
                    result[key] = result[key][0];
                }
            }
        }

        return /** @type {BatchEncoding} */(result);
    }

    /**
     * Encodes a single text using the preprocessor pipeline of the tokenizer.
     *
     * @param {string|null} text The text to encode.
     * @returns {string[]|null} The encoded tokens.
     */
    _encode_text(text) {
        if (text === null) return null;

        // Actual function which does encoding, for a single text
        // First, we take care of special tokens. Needed to avoid issues arising from
        // normalization and/or pretokenization (which may not preserve special tokens)
        const sections = this.added_tokens_regex ? text.split(this.added_tokens_regex).filter(x => x) : [text];

        const tokens = sections.map((x, section_index) => {
            const addedToken = this.added_tokens.find(t => t.content === x);
            if (addedToken !== undefined) {
                // Ignore added tokens
                return x
            } else {
                if (this.remove_space === true) {
                    x = x.trim().split(/\s+/).join(' ');
                }
                if (this.do_lowercase_and_remove_accent) {
                    x = lowercase_and_remove_accent(x);
                }

                if (this.normalizer !== null) {
                    x = this.normalizer(x);
                }

                // If, after normalization, this section is empty (e.g., trimming whitespace),
                // we return an empty array
                if (x.length === 0) {
                    return [];
                }

                const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, {
                    section_index,
                }) : [x];

                const tokens = this.model(sectionTokens);

                return tokens;
            }
        }).flat();

        return tokens;
    }

    /**
     * Encodes a single text or a pair of texts using the model's tokenizer.
     *
     * @param {string} text The text to encode.
     * @param {string|null} text_pair The optional second text to encode.
     * @param {Object} options An optional object containing the following properties:
     * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
     * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.
     * @returns {EncodingSingle} An object containing the encoded text.
     * @private
     */
    _encode_plus(text, text_pair = null, {
        add_special_tokens = true,
        return_token_type_ids = null,
    } = {}) {
        // Function called by users to encode possibly multiple texts
        const tokens = this._encode_text(text);
        const tokens2 = this._encode_text(text_pair);

        const combinedTokens = this.post_processor
            ? this.post_processor(tokens, tokens2, { add_special_tokens })
            : { tokens: (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(tokens ?? [], tokens2 ?? []) };

        const input_ids = this.model.convert_tokens_to_ids(combinedTokens.tokens);

        const result = {
            input_ids,
            attention_mask: new Array(input_ids.length).fill(1),
        }
        if ((return_token_type_ids ?? this.return_token_type_ids) && combinedTokens.token_type_ids) {
            result.token_type_ids = combinedTokens.token_type_ids;
        }
        return result;
    }

    /**
     * Encodes a single text or a pair of texts using the model's tokenizer.
     *
     * @param {string} text The text to encode.
     * @param {string|null} text_pair The optional second text to encode.
     * @param {Object} options An optional object containing the following properties:
     * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
     * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.
     * @returns {number[]} An array of token IDs representing the encoded text(s).
     */
    encode(text, text_pair = null, {
        add_special_tokens = true,
        return_token_type_ids = null,
    } = {}) {
        const { input_ids } = this._encode_plus(text, text_pair, {
            add_special_tokens,
            return_token_type_ids,
        });
        return input_ids;
    }

    /**
     * Decode a batch of tokenized sequences.
     * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.
     * @param {Object} decode_args (Optional) Object with decoding arguments.
     * @returns {string[]} List of decoded sequences.
     */
    batch_decode(batch, decode_args = {}) {
        if (batch instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor) {
            batch = batch.tolist();
        }
        return batch.map(x => this.decode(x, decode_args));
    }

    /**
     * Decodes a sequence of token IDs back to a string.
     *
     * @param {number[]|Tensor} token_ids List/Tensor of token IDs to decode.
     * @param {Object} [decode_args={}]
     * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.
     * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.
     *
     * @returns {string} The decoded string.
     * @throws {Error} If `token_ids` is not a non-empty array of integers.
     */
    decode(
        token_ids,
        decode_args = {},
    ) {
        if (token_ids instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor) {
            token_ids = prepareTensorForDecode(token_ids);
        }

        if (!Array.isArray(token_ids) || token_ids.length === 0 || !(0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.isIntegralNumber)(token_ids[0])) {
            throw Error("token_ids must be a non-empty array of integers.");
        }

        return this.decode_single(token_ids, decode_args)
    }

    /**
     * Decode a single list of token ids to a string.
     * @param {number[]} token_ids List of token ids to decode
     * @param {Object} decode_args Optional arguments for decoding
     * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding
     * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.
     * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.
     * @returns {string} The decoded string
     */
    decode_single(
        token_ids,
        {
            skip_special_tokens = false,
            clean_up_tokenization_spaces = null,
        }
    ) {
        let tokens = this.model.convert_ids_to_tokens(token_ids);
        if (skip_special_tokens) {
            tokens = tokens.filter(x => !this.special_tokens.includes(x));
        }

        // If `this.decoder` is null, we just join tokens with a space:
        // https://github.com/huggingface/tokenizers/blob/8edec536a737cb04494b454805be16c020abb14f/tokenizers/src/tokenizer/mod.rs#L835
        /** @type {string} */
        let decoded = this.decoder ? this.decoder(tokens) : tokens.join(' ');

        // Slight hack, but prevents having to pass `skip_special_tokens` to
        // each call to `decode`, which would lead to code duplication.
        if (this.decoder && this.decoder.end_of_word_suffix) {
            decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, ' ');
            if (skip_special_tokens) {
                decoded = decoded.trim();
            }
        }

        if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) {
            decoded = clean_up_tokenization(decoded);
        }

        return decoded;
    }

    get default_chat_template() {
        if (!this._warned_about_chat_template) {
            console.warn(
                "No chat template is defined for this tokenizer - using a default chat template " +
                "that implements the ChatML format. If the default is not appropriate for " +
                "your model, please set `tokenizer.chat_template` to an appropriate template. " +
                "See https://huggingface.co/docs/transformers/main/chat_templating for more information."
            )
            this._warned_about_chat_template = true; // TODO move to logger.warning_once()
        }

        return this._default_chat_template;
    }

    /**
     * Converts a list of message objects with `"role"` and `"content"` keys to a list of token
     * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to
     * determine the format and control tokens to use when converting. When chat_template is None, it will fall back
     * to the default_chat_template specified at the class level.
     * 
     * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.
     * 
     * **Example:** Applying a chat template to a conversation.
     * 
     * ```javascript
     * import { AutoTokenizer } from "@xenova/transformers";
     * 
     * const tokenizer = await AutoTokenizer.from_pretrained("Xenova/mistral-tokenizer-v1");
     * 
     * const chat = [
     *   { "role": "user", "content": "Hello, how are you?" },
     *   { "role": "assistant", "content": "I'm doing great. How can I help you today?" },
     *   { "role": "user", "content": "I'd like to show off how chat templating works!" },
     * ]
     * 
     * const text = tokenizer.apply_chat_template(chat, { tokenize: false });
     * // "<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]"
     * 
     * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });
     * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]
     * ```
     * 
     * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys.
     * @param {Object} options An optional object containing the following properties:
     * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If
     * this is not passed, the model's default chat template will be used instead.
     * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate
     * the start of an assistant message. This is useful when you want to generate a response from the model.
     * Note that this argument will be passed to the chat template, and so it must be supported in the
     * template for this argument to have any effect.
     * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.
     * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.
     * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.
     * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.
     * If not specified, the tokenizer's `max_length` attribute will be used as a default.
     * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.
     * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer.
     * @returns {string | Tensor | number[]| number[][]} The tokenized output.
     */
    apply_chat_template(conversation, {
        chat_template = null,
        add_generation_prompt = false,
        tokenize = true,
        padding = false,
        truncation = false,
        max_length = null,
        return_tensor = true,
        tokenizer_kwargs = {},
        ...kwargs
    } = {}) {

        // First, handle the cases when the model has a dict of multiple templates
        if (
            (this.chat_template && typeof this.chat_template === 'object') ||
            (this.chat_template === null && this.default_chat_template && typeof this.default_chat_template === 'object')
        ) {
            const template_dict = this.chat_template ?? this.default_chat_template; // Guaranteed to be a non-null object

            if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) {
                // The user can pass the name of a template to the chat template argument instead of an entire template
                chat_template = template_dict[chat_template];
            } else if (chat_template === null && 'default' in template_dict) {
                chat_template = template_dict['default'];
            } else if (chat_template === null) {
                throw Error(
                    `This model has multiple chat templates with no default specified! Please either pass a chat ` +
                    `template or the name of the template you wish to use to the 'chat_template' argument. Available ` +
                    `template names are ${Object.keys(template_dict).sort()}.`
                )
            }
        } else {
            // These are the cases when the model has a single template
            // priority: `chat_template` argument > `tokenizer.chat_template` > `tokenizer.default_chat_template
            chat_template ??= this.chat_template ?? this.default_chat_template;
        }
        if (typeof chat_template !== 'string') {
            throw Error(`chat_template must be a string, but got ${typeof chat_template}`);
        }

        // Compilation function uses a cache to avoid recompiling the same template
        let compiledTemplate = this._compiled_template_cache.get(chat_template);
        if (compiledTemplate === undefined) {
            compiledTemplate = new _huggingface_jinja__WEBPACK_IMPORTED_MODULE_5__.Template(chat_template);
            this._compiled_template_cache.set(chat_template, compiledTemplate);
        }

        const special_tokens_map = Object.create(null);
        for (const key of SPECIAL_TOKEN_ATTRIBUTES) {
            const value = this.getToken(key);
            if (value) {
                special_tokens_map[key] = value;
            }
        }

        const rendered = compiledTemplate.render({
            messages: conversation,
            add_generation_prompt: add_generation_prompt,

            ...special_tokens_map,
            ...kwargs,
        });

        if (tokenize) {
            return this._call(rendered, {
                add_special_tokens: false,
                padding,
                truncation,
                max_length,
                return_tensor,
                ...tokenizer_kwargs,
            }).input_ids;
        }

        return rendered;
    }
}

/**
 * BertTokenizer is a class used to tokenize text for BERT models.
 * @extends PreTrainedTokenizer
 */
class BertTokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;
}
/**
 * Albert tokenizer
 * @extends PreTrainedTokenizer
 */
class AlbertTokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;
}
class MobileBertTokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;
}
class SqueezeBertTokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;
}
class DebertaTokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;
}
class DebertaV2Tokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;
}
class HerbertTokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;
}
class ConvBertTokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;
}
class RoFormerTokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;
}
class DistilBertTokenizer extends PreTrainedTokenizer { }
class CamembertTokenizer extends PreTrainedTokenizer { }
class XLMTokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;

    constructor(tokenizerJSON, tokenizerConfig) {
        super(tokenizerJSON, tokenizerConfig);
        console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')
    }
}
class ElectraTokenizer extends PreTrainedTokenizer {
    return_token_type_ids = true;
}

class T5Tokenizer extends PreTrainedTokenizer { }
class GPT2Tokenizer extends PreTrainedTokenizer {
    _default_chat_template = `{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}`
}
class BartTokenizer extends PreTrainedTokenizer { }
class MBartTokenizer extends PreTrainedTokenizer {
    constructor(tokenizerJSON, tokenizerConfig) {
        super(tokenizerJSON, tokenizerConfig);

        this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/;
        this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));
        this.lang_to_token = x => x; // Identity function
    }

    /**
     * Helper function to build translation inputs for an `MBartTokenizer`.
     * @param {string|string[]} raw_inputs The text to tokenize.
     * @param {Object} tokenizer_options Options to be sent to the tokenizer
     * @param {Object} generate_kwargs Generation options.
     * @returns {Object} Object to be passed to the model.
     */
    _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {
        return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);
    }
}
class MBart50Tokenizer extends MBartTokenizer { } // NOTE: extends MBartTokenizer

class RobertaTokenizer extends PreTrainedTokenizer { }

class BloomTokenizer extends GPT2Tokenizer { // NOTE: `GPT2Tokenizer` to get the correct chat template

    constructor(tokenizerJSON, tokenizerConfig) {
        // Override the default (invalid) regex of the pretokenizer.
        // For more information, see https://github.com/xenova/transformers.js/issues/94
        const splitChars = '.,!?\u2026\u3002\uff0c\u3001\u0964\u06d4\u060c';
        const patternObject = tokenizerJSON.pre_tokenizer?.pretokenizers[0]?.pattern;
        if (patternObject && patternObject.Regex === ` ?[^(\\s|[${splitChars}])]+`) {
            patternObject.Regex = ` ?[^\\s${splitChars}]+`;
        }
        super(tokenizerJSON, tokenizerConfig);
    }
}

const SPIECE_UNDERLINE = "▁";

class LlamaTokenizer extends PreTrainedTokenizer {
    _default_chat_template = `{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<<SYS>>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<<SYS>>\n' + system_message + '\n<</SYS>>\n\n' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<<SYS>>\n' + content.strip() + '\n<</SYS>>\n\n' }}{% elif message['role'] == 'assistant' %}{{ ' '  + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`

    DEFAULT_SYSTEM_PROMPT =
        "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your " +
        "answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure " +
        "that your responses are socially unbiased and positive in nature.\n\n" +
        "If a question does not make any sense, or is not factually coherent, explain why instead of answering something not " +
        "correct. If you don't know the answer to a question, please don't share false information."

    constructor(tokenizerJSON, tokenizerConfig) {
        super(tokenizerJSON, tokenizerConfig);
        this.use_default_system_prompt = tokenizerConfig.use_default_system_prompt ?? false;

        this.legacy = tokenizerConfig.legacy ?? true;
        if (!this.legacy) {
            // See https://github.com/huggingface/transformers/pull/24565 for more information
            this.normalizer = null;
            this.pre_tokenizer = new MetaspacePreTokenizer({
                replacement: SPIECE_UNDERLINE,
                add_prefix_space: true,
                prepend_scheme: "first",
            });
        }
    }

    /**
     * Helper function to handle legacy encoding of SPM tokenizers.
     * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387
     * @param {string} text The text to encode.
     * @returns {string[]} The encoded tokens.
     */
    _encode_text(text) {
        if (text === null) return null;

        if (this.legacy || text.length === 0) {
            return super._encode_text(text);
        }

        let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, " "));
        if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) {
            tokens = tokens.slice(1);
        }
        return tokens;
    }

    get default_chat_template() {
        return super.default_chat_template
            .replaceAll('USE_DEFAULT_PROMPT', this.use_default_system_prompt ? 'true' : 'false')
            .replaceAll('DEFAULT_SYSTEM_MESSAGE', this.DEFAULT_SYSTEM_PROMPT.replaceAll("\n", "\\n").replaceAll("'", "\\'"));
    }
}
class CodeLlamaTokenizer extends LlamaTokenizer { } // NOTE: `LlamaTokenizer` to get the correct chat template

class XLMRobertaTokenizer extends PreTrainedTokenizer { }
class MPNetTokenizer extends PreTrainedTokenizer { }

class FalconTokenizer extends PreTrainedTokenizer { }

class GPTNeoXTokenizer extends PreTrainedTokenizer { }

class EsmTokenizer extends PreTrainedTokenizer { }

class Qwen2Tokenizer extends PreTrainedTokenizer { }

class GemmaTokenizer extends PreTrainedTokenizer {
    _default_chat_template = "{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '<start_of_turn>' + role + '\n' + message['content'] | trim + '<end_of_turn>\n' }}{% endfor %}{% if add_generation_prompt %}{{'<start_of_turn>model\n'}}{% endif %}"
}

class Grok1Tokenizer extends PreTrainedTokenizer { }

/**
 * Helper function to build translation inputs for an `NllbTokenizer` or `M2M100Tokenizer`.
 * @param {PreTrainedTokenizer} self The tokenizer instance.
 * @param {string|string[]} raw_inputs The text to tokenize.
 * @param {Object} tokenizer_options Options to be sent to the tokenizer
 * @param {Object} generate_kwargs Generation options.
 * @returns {Object} Object to be passed to the model.
 * @private
 */
function _build_translation_inputs(self, raw_inputs, tokenizer_options, generate_kwargs) {
    if (!('language_codes' in self) || !Array.isArray(self.language_codes)) {
        throw new Error('Tokenizer must have `language_codes` attribute set and it should be an array of language ids.')
    }
    if (!('languageRegex' in self) || !(self.languageRegex instanceof RegExp)) {
        throw new Error('Tokenizer must have `languageRegex` attribute set and it should be a regular expression.')
    }
    if (!('lang_to_token' in self) || typeof self.lang_to_token !== 'function') {
        throw new Error('Tokenizer must have `lang_to_token` attribute set and it should be a function.')
    }
    const src_lang_token = generate_kwargs.src_lang;
    const tgt_lang_token = generate_kwargs.tgt_lang;

    // Check that the target language is valid:
    if (!self.language_codes.includes(tgt_lang_token)) {
        throw new Error(`Target language code "${tgt_lang_token}" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);
    }

    // Allow `src_lang` to be optional. If not set, we'll use the tokenizer's default.
    if (src_lang_token !== undefined) {
        // Check that the source language is valid:
        if (!self.language_codes.includes(src_lang_token)) {
            throw new Error(`Source language code "${src_lang_token}" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);
        }

        // In the same way as the Python library, we override the post-processor
        // to force the source language to be first:
        for (const item of self.post_processor.config.single) {
            if ('SpecialToken' in item && self.languageRegex.test(item.SpecialToken.id)) {
                item.SpecialToken.id = self.lang_to_token(src_lang_token);
                break;
            }
        }
        // TODO: Do the same for pair?
    }

    // Override the `forced_bos_token_id` to force the correct language
    generate_kwargs.forced_bos_token_id = self.model.convert_tokens_to_ids([self.lang_to_token(tgt_lang_token)])[0];

    return self._call(raw_inputs, tokenizer_options);
}

/**
 * The NllbTokenizer class is used to tokenize text for NLLB ("No Language Left Behind") models.
 * 
 * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project
 * that open-sources models capable of delivering high-quality translations directly
 * between any pair of 200+ languages — including low-resource languages like Asturian,
 * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere,
 * regardless of their language preferences. For more information, check out their
 * [paper](https://arxiv.org/abs/2207.04672).
 * 
 * For a list of supported languages (along with their language codes),
 * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200}
 */
class NllbTokenizer extends PreTrainedTokenizer {

    constructor(tokenizerJSON, tokenizerConfig) {
        super(tokenizerJSON, tokenizerConfig);

        this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/;
        this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));
        this.lang_to_token = x => x; // Identity function
    }

    /**
     * Helper function to build translation inputs for an `NllbTokenizer`.
     * @param {string|string[]} raw_inputs The text to tokenize.
     * @param {Object} tokenizer_options Options to be sent to the tokenizer
     * @param {Object} generate_kwargs Generation options.
     * @returns {Object} Object to be passed to the model.
     */
    _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {
        return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);
    }
}

/**
 * The M2M100Tokenizer class is used to tokenize text for M2M100 ("Many-to-Many") models.
 * 
 * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many
 * multilingual translation. It was introduced in this [paper](https://arxiv.org/abs/2010.11125)
 * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository.
 * 
 * For a list of supported languages (along with their language codes),
 * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered}
 */
class M2M100Tokenizer extends PreTrainedTokenizer {
    constructor(tokenizerJSON, tokenizerConfig) {
        super(tokenizerJSON, tokenizerConfig);

        this.languageRegex = /^__[a-z]{2,3}__$/;
        this.language_codes = this.special_tokens
            .filter(x => this.languageRegex.test(x))
            .map(x => x.slice(2, -2));
        this.lang_to_token = x => `__${x}__`;
    }

    /**
     * Helper function to build translation inputs for an `M2M100Tokenizer`.
     * @param {string|string[]} raw_inputs The text to tokenize.
     * @param {Object} tokenizer_options Options to be sent to the tokenizer
     * @param {Object} generate_kwargs Generation options.
     * @returns {Object} Object to be passed to the model.
     */
    _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {
        return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);
    }
}


const WHISPER_LANGUAGES = [
    ["en", "english"],
    ["zh", "chinese"],
    ["de", "german"],
    ["es", "spanish"],
    ["ru", "russian"],
    ["ko", "korean"],
    ["fr", "french"],
    ["ja", "japanese"],
    ["pt", "portuguese"],
    ["tr", "turkish"],
    ["pl", "polish"],
    ["ca", "catalan"],
    ["nl", "dutch"],
    ["ar", "arabic"],
    ["sv", "swedish"],
    ["it", "italian"],
    ["id", "indonesian"],
    ["hi", "hindi"],
    ["fi", "finnish"],
    ["vi", "vietnamese"],
    ["he", "hebrew"],
    ["uk", "ukrainian"],
    ["el", "greek"],
    ["ms", "malay"],
    ["cs", "czech"],
    ["ro", "romanian"],
    ["da", "danish"],
    ["hu", "hungarian"],
    ["ta", "tamil"],
    ["no", "norwegian"],
    ["th", "thai"],
    ["ur", "urdu"],
    ["hr", "croatian"],
    ["bg", "bulgarian"],
    ["lt", "lithuanian"],
    ["la", "latin"],
    ["mi", "maori"],
    ["ml", "malayalam"],
    ["cy", "welsh"],
    ["sk", "slovak"],
    ["te", "telugu"],
    ["fa", "persian"],
    ["lv", "latvian"],
    ["bn", "bengali"],
    ["sr", "serbian"],
    ["az", "azerbaijani"],
    ["sl", "slovenian"],
    ["kn", "kannada"],
    ["et", "estonian"],
    ["mk", "macedonian"],
    ["br", "breton"],
    ["eu", "basque"],
    ["is", "icelandic"],
    ["hy", "armenian"],
    ["ne", "nepali"],
    ["mn", "mongolian"],
    ["bs", "bosnian"],
    ["kk", "kazakh"],
    ["sq", "albanian"],
    ["sw", "swahili"],
    ["gl", "galician"],
    ["mr", "marathi"],
    ["pa", "punjabi"],
    ["si", "sinhala"],
    ["km", "khmer"],
    ["sn", "shona"],
    ["yo", "yoruba"],
    ["so", "somali"],
    ["af", "afrikaans"],
    ["oc", "occitan"],
    ["ka", "georgian"],
    ["be", "belarusian"],
    ["tg", "tajik"],
    ["sd", "sindhi"],
    ["gu", "gujarati"],
    ["am", "amharic"],
    ["yi", "yiddish"],
    ["lo", "lao"],
    ["uz", "uzbek"],
    ["fo", "faroese"],
    ["ht", "haitian creole"],
    ["ps", "pashto"],
    ["tk", "turkmen"],
    ["nn", "nynorsk"],
    ["mt", "maltese"],
    ["sa", "sanskrit"],
    ["lb", "luxembourgish"],
    ["my", "myanmar"],
    ["bo", "tibetan"],
    ["tl", "tagalog"],
    ["mg", "malagasy"],
    ["as", "assamese"],
    ["tt", "tatar"],
    ["haw", "hawaiian"],
    ["ln", "lingala"],
    ["ha", "hausa"],
    ["ba", "bashkir"],
    ["jw", "javanese"],
    ["su", "sundanese"],
]

// @ts-ignore
const WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES);
// @ts-ignore
const WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([
    ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]),
    ...[
        ["burmese", "my"],
        ["valencian", "ca"],
        ["flemish", "nl"],
        ["haitian", "ht"],
        ["letzeburgesch", "lb"],
        ["pushto", "ps"],
        ["panjabi", "pa"],
        ["moldavian", "ro"],
        ["moldovan", "ro"],
        ["sinhalese", "si"],
        ["castilian", "es"],
    ]
]);

/**
 * WhisperTokenizer tokenizer
 * @extends PreTrainedTokenizer
 */
class WhisperTokenizer extends PreTrainedTokenizer {
    _default_chat_template = `{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}`;

    /**
     * Decodes automatic speech recognition (ASR) sequences.
     * @param {Array<{tokens: number[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.
     * @param {Object} options The options to use for decoding.
     * @returns {Array<string|{chunks?: undefined|Array<{language: string|null, timestamp: Array<number|null>, text: string}>}>} The decoded sequences.
     */
    _decode_asr(sequences, {
        return_timestamps = false,
        return_language = false,
        time_precision = null,
        force_full_sequences = true
    } = {}) {
        // Set force_full_sequences=false if you want streaming
        // TODO add support for `return_language`

        // Internal method meant to only be used by asr pipeline.
        // Handles all the little quirks specific to whisper to handle
        // the various options not allowed in other seq2seq models

        // =========== Overview ============
        // - iterate over all outputs
        // - all tokens within output
        // - Each token can be
        //   - language token
        //   - special token
        //   - timestamp token
        //   - text token
        // - We accumulate the text tokens.
        // - We split on end timestamps
        // - Lots of complexity comes from stride and timestamps

        if (time_precision === null) {
            throw Error("Must specify time_precision")
        }
        let last_language = null;

        const returnWordTimestamps = return_timestamps === "word";

        function new_chunk() {
            return { "language": last_language, "timestamp": [null, null], "text": "" };
        }

        // Welcome to the state machine!
        const chunks = [];
        let chunk = new_chunk();
        let time_offset = 0.0;
        const timestamp_begin = this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0] + 1;

        let previous_tokens = [];
        let previous_token_timestamps = [];

        let skip = false;
        let right_stride_start = null;


        const all_special_ids = new Set(this.all_special_ids);

        for (const output of sequences) {
            // NOTE: python version has batches, so it uses [0]
            const token_ids = output.tokens;
            const token_timestamps = returnWordTimestamps ? output.token_timestamps : null;

            // These keep track of timestamps within strides, which need
            // to be skipped and resolve all tokens in a single chunk.
            let last_timestamp = null;
            let first_timestamp = timestamp_begin;

            if ("stride" in output) {
                const [chunk_len, stride_left, stride_right] = output.stride;

                // Offset the timings to account for the other `model_outputs`.
                time_offset -= stride_left;
                right_stride_start = chunk_len - stride_right;

                // Keeping track of timestamps within strides
                // We're going to NOT split on those, and delay until we're
                // out of BOTH stride. Otherwise lots of issues occur and
                // corner cases
                if (stride_left) {
                    first_timestamp = stride_left / time_precision + timestamp_begin;
                }

                if (stride_right) {
                    for (let i = token_ids.length - 1; i >= 0; --i) {
                        const token = token_ids[i];
                        if (token >= timestamp_begin) {
                            // There can be several token in the right stride
                            // But the last one is ALWAYS going to be skipped
                            if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) {
                                break;
                            }
                            last_timestamp = token;
                        }
                    }
                }
            }

            let current_tokens = [];
            let current_token_timestamps = [];

            // - all tokens within output
            for (let i = 0; i < token_ids.length; ++i) {
                const token = token_ids[i];
                // 4 possible states for each token
                // - 1/ Language code
                // - 2/ all other special tokens (which we ignore)
                // - 3/ Timestamp
                // - 4/ Regular text

                if (all_special_ids.has(token)) {
                    const text = this.decode([token]);
                    const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2));

                    if (language !== undefined) {
                        // 1/ Indeed some language
                        // TODO Handle when language is different from the previous
                        // one, and we cannot use timestamped tokens to create chunks
                        if (last_language !== null && language !== last_language && !return_timestamps) {
                            previous_tokens.push(current_tokens);
                            const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0];
                            const resolved_text = this.decode(resolved_tokens);
                            chunk.text = resolved_text;
                            chunks.push(chunk);

                            // Flush all our temporary context
                            previous_tokens = [];
                            current_tokens = [];
                            chunk = new_chunk();
                        }

                        last_language = chunk.language = language;
                    } else {
                        // 2/ This is a regular special token, ignoring it
                    }
                } else if (token >= timestamp_begin) {
                    // 3/ Timestamp token
                    const time = (token - timestamp_begin) * time_precision + time_offset;
                    const rounded_time = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.round)(time, 2);

                    if (last_timestamp !== null && token >= last_timestamp) {
                        // Whisper outputted a timestamp token, but it falls within
                        // our stride, so we're going to skip it for the time being
                        // and resolve this later
                        // Skip is necessary because timestamp tokens always come
                        // by pair, so we need to skip the next one too (which would mark the start of another chunk).
                        skip = true;
                    } else if (skip || (previous_tokens.length > 0 && token < first_timestamp)) {
                        skip = false;
                    } else if (chunk.timestamp[0] === null) {
                        chunk.timestamp[0] = rounded_time;
                    } else {
                        // This is the end of the timestamp chunk
                        if (rounded_time === chunk.timestamp[0]) {
                            // This is a bug in timestamp token output
                            // where we're taking the duplicate token
                            // as a stop where it should be a start.
                            // This is an issue in the underlying model output
                            // Let's just skip it so it becomes de-factor a start agin
                        } else {
                            chunk.timestamp[1] = rounded_time;

                            // Handling merges
                            previous_tokens.push(current_tokens)

                            if (returnWordTimestamps) {
                                previous_token_timestamps.push(current_token_timestamps);
                            }
                            const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(
                                previous_tokens, previous_token_timestamps
                            )

                            const resolved_text = this.decode(resolved_tokens)
                            chunk.text = resolved_text

                            if (returnWordTimestamps) {
                                chunk.words = this.collateWordTimestamps(
                                    resolved_tokens, resolved_token_timestamps, last_language,
                                )
                            }

                            chunks.push(chunk)

                            // Flush all our temporary context
                            previous_tokens = []
                            current_tokens = []
                            previous_token_timestamps = []
                            current_token_timestamps = []
                            chunk = new_chunk()
                        }
                    }

                } else {
                    // 4/ Regular token
                    // We just append to the list of all tokens so we can handle
                    // merges later and decode into text.
                    current_tokens.push(token)

                    if (returnWordTimestamps) {
                        let start_time = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.round)(token_timestamps[i] + time_offset, 2);

                        let end_time;
                        if (i + 1 < token_timestamps.length) {
                            end_time = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.round)(token_timestamps[i + 1] + time_offset, 2);
                        } else {
                            // should never happen
                            end_time = null;
                        }
                        current_token_timestamps.push([start_time, end_time]);
                    }

                }
            }

            if ('stride' in output) {
                const [chunk_len, stride_left, stride_right] = output.stride;
                time_offset += chunk_len - stride_right
            }

            // Leftover tokens
            if (current_tokens.length > 0) {
                previous_tokens.push(current_tokens)
                if (returnWordTimestamps) {
                    previous_token_timestamps.push(current_token_timestamps);
                }
            } else if (previous_tokens.every(p => p.length === 0)) {
                // Flushing previous tokens (END)"
                chunk = new_chunk()
                previous_tokens = []
                current_tokens = []
                previous_token_timestamps = [];
                current_token_timestamps = [];
            }

        }

        if (previous_tokens.length > 0) {
            if (force_full_sequences && return_timestamps) {
                // Last token should always be timestamps, so there shouldn't be
                // leftover
                throw new Error(
                    "Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. " +
                    "Also make sure WhisperTimeStampLogitsProcessor was used during generation."
                );
            }

            // Happens when we don't use timestamps
            const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps);

            // Flushing previous tokens (FINAL)
            const resolved_text = this.decode(resolved_tokens);
            chunk.text = resolved_text;
            if (returnWordTimestamps) {
                chunk.words = this.collateWordTimestamps(
                    resolved_tokens, resolved_token_timestamps, last_language,
                )
            }
            chunks.push(chunk);
        }

        let optional = Object.create(null);

        // Preparing and cleaning up the pipeline output
        const full_text = chunks.map(chunk => chunk.text).join('');
        if (return_timestamps || return_language) {
            for (let i = 0; i < chunks.length; ++i) {
                const chunk = chunks[i];
                if (!return_timestamps) {
                    delete chunk["timestamp"];
                }

                if (!return_language) {
                    delete chunk["language"];
                }
            }
            if (returnWordTimestamps) {
                const new_chunks = [];
                for (const chunk of chunks) {
                    for (const word of chunk.words) {
                        new_chunks.push(word);
                    }
                }
                optional = { "chunks": new_chunks };
            } else {
                optional = { "chunks": chunks };
            }
        }
        return [full_text, optional];

    }

    /**
     * Finds the longest common sequence among the provided sequences.
     * @param {number[][]} sequences An array of sequences of token ids to compare.
     * @returns {number[][]} The longest common sequence found.
     * @throws {Error} If there is a bug within the function.
     * @private
     */
    findLongestCommonSequence(sequences, token_timestamp_sequences = null) {
        // It would be much harder to do O(n) because of fault tolerance.
        // We actually have a really good property which is that the total sequence
        // MUST be those subsequences in order.
        // If token_timestamp_sequences is provided, will split those sequences in
        // exactly the same way.
        let leftSequence = sequences[0];
        let leftLength = leftSequence.length;
        let totalSequence = [];

        const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0;
        let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null;
        let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null;
        for (let i = 1; i < sequences.length; ++i) {
            const rightSequence = sequences[i];
            let max = 0.0;
            let maxIndices = [leftLength, leftLength, 0, 0];
            // Here we're sliding matches
            // [a, b, c, d]
            //          [c, d, f]
            // =        [c] == [d]

            // [a, b, c, d]
            //       [c, d, f]
            // =     [c, d] == [c, d]


            // [a, b, c, d]
            //    [c, d, f]

            // =  [b, c, d] == [c, d, f]

            // [a, b, c, d]
            // [c, d, f]

            // [a, b, c] == [c, d, f]

            // [a, b, c, d]
            // [d, f]

            // [a, b] == [d, f]

            // [a, b, c, d]
            // [f]

            // [a] == [f]

            const rightLength = rightSequence.length;
            for (let j = 1; j < leftLength + rightLength; ++j) {
                const eps = j / 10000.0;
                const leftStart = Math.max(0, leftLength - j);
                const leftStop = Math.min(leftLength, leftLength + rightLength - j);
                const left = leftSequence.slice(leftStart, leftStop);
                const rightStart = Math.max(0, j - leftLength);
                const rightStop = Math.min(rightLength, j);
                const right = rightSequence.slice(rightStart, rightStop);
                if (left.length !== right.length) {
                    throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");
                }
                const matches = left.filter((elem, idx) => elem === right[idx]).length;
                const matching = matches / j + eps;
                if (matches > 1 && matching > max) {
                    max = matching;
                    maxIndices = [leftStart, leftStop, rightStart, rightStop];
                }
            }
            const [leftStart, leftStop, rightStart, rightStop] = maxIndices;
            const leftMid = Math.floor((leftStop + leftStart) / 2);
            const rightMid = Math.floor((rightStop + rightStart) / 2);
            totalSequence.push(...leftSequence.slice(0, leftMid));
            leftSequence = rightSequence.slice(rightMid);
            leftLength = leftSequence.length;

            if (use_token_timestamp_sequences) {
                total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid));
                left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid);
            }
        }
        totalSequence.push(...leftSequence);

        if (use_token_timestamp_sequences) {
            total_token_timestamp_sequence.push(...left_token_timestamp_sequence);
            return [totalSequence, total_token_timestamp_sequence];
        } else {
            return [totalSequence, []];
        }
    }

    /** @private */
    collateWordTimestamps(tokens, token_timestamps, language) {

        const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language);

        const timings = [];
        for (let i = 0; i < words.length; ++i) {
            const indices = token_indices[i];
            timings.push({
                text: words[i],
                timestamp: [
                    token_timestamps[indices.at(0)][0],
                    token_timestamps[indices.at(-1)][1],
                ],
            });
        }
        return timings;
    }

    /**
     * Groups tokens by word. Returns a tuple containing a list of strings with the words,
     * and a list of `token_id` sequences with the tokens making up each word.
     * @param {number[]} tokens 
     * @param {string} [language] 
     * @param {string} prepend_punctionations 
     * @param {string} append_punctuations 
     * 
     * @private
     */
    combineTokensIntoWords(tokens, language, prepend_punctionations = "\"'“¡¿([{-", append_punctuations = "\"'.。,，!！?？:：”)]}、") {
        language = language ?? 'english';

        let words, word_tokens, token_indices;

        if (["chinese", "japanese", "thai", "lao", "myanmar"].includes(language)) {
            // These languages don't typically use spaces.
            [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens)
        } else {
            [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens)
        }

        return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations);
    }

    /** @type {PreTrainedTokenizer['decode']} */
    decode(
        token_ids,
        decode_args,
    ) {
        let text;
        // @ts-ignore
        if (decode_args && decode_args.decode_with_timestamps) {
            if (token_ids instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor) {
                token_ids = prepareTensorForDecode(token_ids);
            }
            text = this.decodeWithTimestamps(token_ids, decode_args);
        } else {
            text = super.decode(token_ids, decode_args);
        }
        // TODO: implement offsets
        // if (decode_args.output_offsets) {
        //     let offsets = this.computeOffsets
        // }
        return text;
    }

    /**
     * @param {number[]} token_ids List of token IDs to decode.
     * @param {Object} decode_args Optional arguments for decoding
     * @private
     */
    decodeWithTimestamps(token_ids, decode_args) {
        const time_precision = decode_args?.time_precision ?? 0.02;

        const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1;
        /**@type {Array} */
        let outputs = [[]];
        for (const token of token_ids) {
            if (token >= timestamp_begin) {
                const timestamp = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.round)((token - timestamp_begin) * time_precision, 2);
                outputs.push(`<|${timestamp}|>`);
                outputs.push([]);
            } else {
                outputs[outputs.length - 1].push(token);
            }
        }
        outputs = outputs.map(
            s => {
                if (typeof s === 'string') {
                    return s;
                } else {
                    return super.decode(s, decode_args);
                }
            }
        )

        return outputs.join('');
    }

    /**
     * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.
     * @param {number[]} tokens 
     * @returns {*}
     * @private
     */
    splitTokensOnUnicode(tokens) {
        const decoded_full = this.decode(tokens, {
            // @ts-ignore
            decode_with_timestamps: true,
        });
        const replacement_char = '\uFFFD';

        const words = []
        const word_tokens = []
        const token_indices = []
        let current_tokens = []
        let current_indices = []
        let unicode_offset = 0

        for (let token_idx = 0; token_idx < tokens.length; ++token_idx) {
            const token = tokens[token_idx];

            current_tokens.push(token);
            current_indices.push(token_idx);

            const decoded = this.decode(current_tokens, {
                // @ts-ignore
                decode_with_timestamps: true,
            });

            if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) {
                words.push(decoded)
                word_tokens.push(current_tokens)
                token_indices.push(current_indices)
                current_tokens = []
                current_indices = []
                unicode_offset += decoded.length;
            }

        }

        return [words, word_tokens, token_indices]
    }

    /**
     * Combine tokens into words by splitting at whitespace and punctuation tokens.
     * @param {number[]} tokens 
     * @private
     */
    splitTokensOnSpaces(tokens) {

        const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens);

        const words = []
        const word_tokens = []
        const token_indices = []

        const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, 'gu');

        for (let i = 0; i < subwords.length; ++i) {

            const subword = subwords[i];
            const subword_tokens = subword_tokens_list[i];
            const subword_indices = subword_indices_list[i];

            // @ts-ignore
            const special = subword_tokens[0] >= this.model.tokens_to_ids.get('<|endoftext|>');
            const with_space = subword.startsWith(' ');
            const trimmed = subword.trim();
            const punctuation = punctuationRegex.test(trimmed);

            if (special || with_space || punctuation || words.length === 0) {
                words.push(subword);
                word_tokens.push(subword_tokens);
                token_indices.push(subword_indices);
            } else {
                const ix = words.length - 1;
                words[ix] += subword;
                word_tokens[ix].push(...subword_tokens);
                token_indices[ix].push(...subword_indices);
            }
        }

        return [words, word_tokens, token_indices];

    }

    /**
     * Merges punctuation tokens with neighboring words.
     * @param {string[]} words 
     * @param {number[][]} tokens 
     * @param {number[][]} indices 
     * @param {string} prepended 
     * @param {string} appended 
     * @private
     */
    mergePunctuations(words, tokens, indices, prepended, appended) {

        const newWords = structuredClone(words);
        const newTokens = structuredClone(tokens);
        const newIndices = structuredClone(indices);


        // prepend punctuations
        let i = newWords.length - 2;
        let j = newWords.length - 1;

        while (i >= 0) {
            if (newWords[i].startsWith(' ') && prepended.includes(newWords[i].trim())) {
                newWords[j] = newWords[i] + newWords[j];
                newTokens[j] = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(newTokens[i], newTokens[j]);
                newIndices[j] = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(newIndices[i], newIndices[j]);
                newWords[i] = '';
                newTokens[i] = [];
                newIndices[i] = [];
            } else {
                j = i;
            }
            --i;
        }

        // append punctuations
        i = 0;
        j = 1;
        while (j < newWords.length) {
            if (!newWords[i].endsWith(' ') && appended.includes(newWords[j])) {
                newWords[i] += newWords[j];
                newTokens[i] = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(newTokens[i], newTokens[j]);
                newIndices[i] = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(newIndices[i], newIndices[j]);
                newWords[j] = '';
                newTokens[j] = [];
                newIndices[j] = [];
            } else {
                i = j;
            }
            ++j;
        }

        return [
            newWords.filter(x => x),
            newTokens.filter(x => x.length > 0),
            newIndices.filter(x => x.length > 0),
        ]
    }

    /**
     * Helper function to build translation inputs for a `WhisperTokenizer`,
     * depending on the language, task, and whether to predict timestamp tokens.
     * 
     * Used to override the prefix tokens appended to the start of the label sequence.
     * 
     * **Example: Get ids for a language**
     * ```javascript
     * // instantiate the tokenizer and set the prefix token to Spanish
     * const tokenizer = await WhisperTokenizer.from_pretrained('Xenova/whisper-tiny');
     * const forced_decoder_ids = tokenizer.get_decoder_prompt_ids({ language: 'spanish' });
     * // [(1, 50262), (2, 50363)]
     * ```
     * 
     * @param {Object} options Options to generate the decoder prompt.
     * @param {string} [options.language] The language of the transcription text.
     * The corresponding language id token is appended to the start of the sequence for multilingual
     * speech recognition and speech translation tasks, e.g. for "Spanish" the token "<|es|>" is appended
     * to the start of sequence.
     * @param {string} [options.task] Task identifier to append at the start of sequence (if any).
     * This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and
     * "translate" for speech translation.
     * @param {boolean} [options.no_timestamps] Whether to add the <|notimestamps|> token at the start of the sequence.
     * @returns {number[][]} The decoder prompt ids.
     */
    get_decoder_prompt_ids({
        language = null,
        task = null,
        no_timestamps = true,
    } = {}) {

        // <|lang_id|> <|task|> <|notimestamps|>

        const forced_decoder_ids = [];

        if (language) {
            // User wishes to specify the language
            language = language.toLowerCase();

            // Map to code from user-friendly name (e.g., "english" -> "en")
            let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language);

            if (language_code === undefined) {
                // User provided something that is not a language name

                if (WHISPER_LANGUAGE_MAPPING.has(language)) {
                    // User provided the language code directly (e.g., "en")
                    language_code = language;

                } else {
                    // User provided something that is not a language code or name
                    const is_language_code = language.length === 2;
                    const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values();

                    throw new Error(`Language "${language}" is not supported. Must be one of: ${JSON.stringify(langs)}`);
                }
            }

            const language_token_id = this.model.tokens_to_ids.get(`<|${language_code}|>`);
            if (language_token_id === undefined) {
                throw new Error(`Unable to find language "${language_code}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`)
            }

            forced_decoder_ids.push(language_token_id);
        } else {
            // No token will be forced, which leaves the model to predict the language
            forced_decoder_ids.push(null);
        }

        if (task) {
            task = task.toLowerCase();
            if (task !== 'transcribe' && task !== 'translate') {
                throw new Error(`Task "${task}" is not supported. Must be one of: ["transcribe", "translate"]`);
            }

            const task_token_id = this.model.tokens_to_ids.get(`<|${task}|>`);
            if (task_token_id === undefined) {
                throw new Error(`Unable to find task "${task}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`)
            }

            forced_decoder_ids.push(task_token_id);
        } else {
            // No token will be forced, which leaves the model to predict the task
            forced_decoder_ids.push(null);
        }

        if (no_timestamps) {
            const no_timestamps_id = this.model.tokens_to_ids.get(`<|notimestamps|>`);
            if (no_timestamps_id === undefined) {
                throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.')
            }

            forced_decoder_ids.push(no_timestamps_id);
        }

        return forced_decoder_ids.map((x, i) => [i + 1, x]).filter(x => x[1] !== null);

    }
}
class CodeGenTokenizer extends PreTrainedTokenizer { }
class CLIPTokenizer extends PreTrainedTokenizer { }
class SiglipTokenizer extends PreTrainedTokenizer { }

/**
 * @todo This model is not yet supported by Hugging Face's "fast" tokenizers library (https://github.com/huggingface/tokenizers).
 * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results.
 */
class MarianTokenizer extends PreTrainedTokenizer {
    /**
     * Create a new MarianTokenizer instance.
     * @param {Object} tokenizerJSON The JSON of the tokenizer.
     * @param {Object} tokenizerConfig The config of the tokenizer.
     */
    constructor(tokenizerJSON, tokenizerConfig) {
        super(tokenizerJSON, tokenizerConfig);

        this.languageRegex = /^(>>\w+<<)\s*/g;

        this.supported_language_codes = this.model.vocab.filter(
            x => this.languageRegex.test(x)
        );

        console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')
    }

    /**
     * Encodes a single text. Overriding this method is necessary since the language codes
     * must be removed before encoding with sentencepiece model.
     * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213
     *
     * @param {string|null} text The text to encode.
     * @returns {Array} The encoded tokens.
     */
    _encode_text(text) {
        if (text === null) return null;

        // Check if text starts with language code:
        const [matchInfo, ...remainder] = text.trim().split(this.languageRegex);

        if (remainder.length === 0) {
            // No language code, encode normally
            return super._encode_text(matchInfo);

        } else if (remainder.length === 2) {
            // Text starts with language code, so we do not encode it with sentencepiece.
            const [language, text] = remainder;

            if (!this.supported_language_codes.includes(language)) {
                console.warn(`Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`)
            }
            return (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)([language], super._encode_text(text));
        }
    }

}

class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { }

class BlenderbotTokenizer extends PreTrainedTokenizer {
    _default_chat_template = `{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ '  ' }}{% endif %}{% endfor %}{{ eos_token }}`;
}
class BlenderbotSmallTokenizer extends BlenderbotTokenizer { } // NOTE `BlenderbotTokenizer` to get the correct chat template

class SpeechT5Tokenizer extends PreTrainedTokenizer { }

class NougatTokenizer extends PreTrainedTokenizer { }

class VitsTokenizer extends PreTrainedTokenizer {

    constructor(tokenizerJSON, tokenizerConfig) {
        super(tokenizerJSON, tokenizerConfig);

        // Custom decoder function
        this.decoder = new VitsDecoder({});
    }
}

class CohereTokenizer extends PreTrainedTokenizer { }

/**
 * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function.
 * The chosen tokenizer class is determined by the type specified in the tokenizer config.
 * 
 * @example
 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');
 */
class AutoTokenizer {
    static TOKENIZER_CLASS_MAPPING = {
        T5Tokenizer,
        DistilBertTokenizer,
        CamembertTokenizer,
        DebertaTokenizer,
        DebertaV2Tokenizer,
        BertTokenizer,
        HerbertTokenizer,
        ConvBertTokenizer,
        RoFormerTokenizer,
        XLMTokenizer,
        ElectraTokenizer,
        MobileBertTokenizer,
        SqueezeBertTokenizer,
        AlbertTokenizer,
        GPT2Tokenizer,
        BartTokenizer,
        MBartTokenizer,
        MBart50Tokenizer,
        RobertaTokenizer,
        WhisperTokenizer,
        CodeGenTokenizer,
        CLIPTokenizer,
        SiglipTokenizer,
        MarianTokenizer,
        BloomTokenizer,
        NllbTokenizer,
        M2M100Tokenizer,
        LlamaTokenizer,
        CodeLlamaTokenizer,
        XLMRobertaTokenizer,
        MPNetTokenizer,
        FalconTokenizer,
        GPTNeoXTokenizer,
        EsmTokenizer,
        Wav2Vec2CTCTokenizer,
        BlenderbotTokenizer,
        BlenderbotSmallTokenizer,
        SpeechT5Tokenizer,
        NougatTokenizer,
        VitsTokenizer,
        Qwen2Tokenizer,
        GemmaTokenizer,
        Grok1Tokenizer,
        CohereTokenizer,

        // Base case:
        PreTrainedTokenizer,
    }


    /**
     * Instantiate one of the tokenizer classes of the library from a pretrained model.
     * 
     * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object
     * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
     * 
     * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
     * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.
     *   Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
     *   user or organization name, like `dbmdz/bert-base-german-cased`.
     * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.
     * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
     * 
     * @returns {Promise<PreTrainedTokenizer>} A new instance of the PreTrainedTokenizer class.
     */
    static async from_pretrained(pretrained_model_name_or_path, {
        quantized = true,
        progress_callback = null,
        config = null,
        cache_dir = null,
        local_files_only = false,
        revision = 'main',
        legacy = null,
    } = {}) {

        const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, {
            quantized,
            progress_callback,
            config,
            cache_dir,
            local_files_only,
            revision,
            legacy,
        })

        // Some tokenizers are saved with the "Fast" suffix, so we remove that if present.
        const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, '') ?? 'PreTrainedTokenizer';

        let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName];
        if (!cls) {
            console.warn(`Unknown tokenizer class "${tokenizerName}", attempting to construct from base class.`);
            cls = PreTrainedTokenizer;
        }
        return new cls(tokenizerJSON, tokenizerConfig);
    }
}


/***/ }),

/***/ "./src/transformers.js":
/*!*****************************!*\
  !*** ./src/transformers.js ***!
  \*****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ASTFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.ASTFeatureExtractor),
/* harmony export */   "ASTForAudioClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ASTForAudioClassification),
/* harmony export */   "ASTModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ASTModel),
/* harmony export */   "ASTPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ASTPreTrainedModel),
/* harmony export */   "AlbertForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertForMaskedLM),
/* harmony export */   "AlbertForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertForQuestionAnswering),
/* harmony export */   "AlbertForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertForSequenceClassification),
/* harmony export */   "AlbertModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertModel),
/* harmony export */   "AlbertPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertPreTrainedModel),
/* harmony export */   "AlbertTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.AlbertTokenizer),
/* harmony export */   "AudioClassificationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.AudioClassificationPipeline),
/* harmony export */   "AutoConfig": () => (/* reexport safe */ _configs_js__WEBPACK_IMPORTED_MODULE_5__.AutoConfig),
/* harmony export */   "AutoModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModel),
/* harmony export */   "AutoModelForAudioClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForAudioClassification),
/* harmony export */   "AutoModelForAudioFrameClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForAudioFrameClassification),
/* harmony export */   "AutoModelForCTC": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForCTC),
/* harmony export */   "AutoModelForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForCausalLM),
/* harmony export */   "AutoModelForDepthEstimation": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForDepthEstimation),
/* harmony export */   "AutoModelForDocumentQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForDocumentQuestionAnswering),
/* harmony export */   "AutoModelForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageClassification),
/* harmony export */   "AutoModelForImageFeatureExtraction": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageFeatureExtraction),
/* harmony export */   "AutoModelForImageMatting": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageMatting),
/* harmony export */   "AutoModelForImageSegmentation": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageSegmentation),
/* harmony export */   "AutoModelForImageToImage": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageToImage),
/* harmony export */   "AutoModelForMaskGeneration": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForMaskGeneration),
/* harmony export */   "AutoModelForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForMaskedLM),
/* harmony export */   "AutoModelForObjectDetection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForObjectDetection),
/* harmony export */   "AutoModelForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForQuestionAnswering),
/* harmony export */   "AutoModelForSemanticSegmentation": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSemanticSegmentation),
/* harmony export */   "AutoModelForSeq2SeqLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSeq2SeqLM),
/* harmony export */   "AutoModelForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSequenceClassification),
/* harmony export */   "AutoModelForSpeechSeq2Seq": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSpeechSeq2Seq),
/* harmony export */   "AutoModelForTextToSpectrogram": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForTextToSpectrogram),
/* harmony export */   "AutoModelForTextToWaveform": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForTextToWaveform),
/* harmony export */   "AutoModelForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForTokenClassification),
/* harmony export */   "AutoModelForVision2Seq": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForVision2Seq),
/* harmony export */   "AutoModelForXVector": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForXVector),
/* harmony export */   "AutoModelForZeroShotObjectDetection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForZeroShotObjectDetection),
/* harmony export */   "AutoProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.AutoProcessor),
/* harmony export */   "AutoTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.AutoTokenizer),
/* harmony export */   "AutomaticSpeechRecognitionPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.AutomaticSpeechRecognitionPipeline),
/* harmony export */   "BartForConditionalGeneration": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BartForConditionalGeneration),
/* harmony export */   "BartForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BartForSequenceClassification),
/* harmony export */   "BartModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BartModel),
/* harmony export */   "BartPretrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BartPretrainedModel),
/* harmony export */   "BartTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BartTokenizer),
/* harmony export */   "BaseModelOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BaseModelOutput),
/* harmony export */   "BeitFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.BeitFeatureExtractor),
/* harmony export */   "BeitForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BeitForImageClassification),
/* harmony export */   "BeitModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BeitModel),
/* harmony export */   "BeitPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BeitPreTrainedModel),
/* harmony export */   "BertForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForMaskedLM),
/* harmony export */   "BertForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForQuestionAnswering),
/* harmony export */   "BertForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForSequenceClassification),
/* harmony export */   "BertForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForTokenClassification),
/* harmony export */   "BertModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertModel),
/* harmony export */   "BertPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertPreTrainedModel),
/* harmony export */   "BertTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BertTokenizer),
/* harmony export */   "BitImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.BitImageProcessor),
/* harmony export */   "BlenderbotForConditionalGeneration": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotForConditionalGeneration),
/* harmony export */   "BlenderbotModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotModel),
/* harmony export */   "BlenderbotPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotPreTrainedModel),
/* harmony export */   "BlenderbotSmallForConditionalGeneration": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotSmallForConditionalGeneration),
/* harmony export */   "BlenderbotSmallModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotSmallModel),
/* harmony export */   "BlenderbotSmallPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotSmallPreTrainedModel),
/* harmony export */   "BlenderbotSmallTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BlenderbotSmallTokenizer),
/* harmony export */   "BlenderbotTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BlenderbotTokenizer),
/* harmony export */   "BloomForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BloomForCausalLM),
/* harmony export */   "BloomModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BloomModel),
/* harmony export */   "BloomPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BloomPreTrainedModel),
/* harmony export */   "BloomTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BloomTokenizer),
/* harmony export */   "CLIPFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.CLIPFeatureExtractor),
/* harmony export */   "CLIPModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPModel),
/* harmony export */   "CLIPPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPPreTrainedModel),
/* harmony export */   "CLIPSegForImageSegmentation": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPSegForImageSegmentation),
/* harmony export */   "CLIPSegModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPSegModel),
/* harmony export */   "CLIPSegPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPSegPreTrainedModel),
/* harmony export */   "CLIPTextModelWithProjection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPTextModelWithProjection),
/* harmony export */   "CLIPTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CLIPTokenizer),
/* harmony export */   "CLIPVisionModelWithProjection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPVisionModelWithProjection),
/* harmony export */   "CamembertForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForMaskedLM),
/* harmony export */   "CamembertForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForQuestionAnswering),
/* harmony export */   "CamembertForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForSequenceClassification),
/* harmony export */   "CamembertForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForTokenClassification),
/* harmony export */   "CamembertModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertModel),
/* harmony export */   "CamembertPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertPreTrainedModel),
/* harmony export */   "CamembertTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CamembertTokenizer),
/* harmony export */   "CausalLMOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CausalLMOutput),
/* harmony export */   "CausalLMOutputWithPast": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CausalLMOutputWithPast),
/* harmony export */   "ChineseCLIPFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.ChineseCLIPFeatureExtractor),
/* harmony export */   "ChineseCLIPModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ChineseCLIPModel),
/* harmony export */   "ChineseCLIPPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ChineseCLIPPreTrainedModel),
/* harmony export */   "ClapAudioModelWithProjection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapAudioModelWithProjection),
/* harmony export */   "ClapFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.ClapFeatureExtractor),
/* harmony export */   "ClapModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapModel),
/* harmony export */   "ClapPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapPreTrainedModel),
/* harmony export */   "ClapTextModelWithProjection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapTextModelWithProjection),
/* harmony export */   "CodeGenForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CodeGenForCausalLM),
/* harmony export */   "CodeGenModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CodeGenModel),
/* harmony export */   "CodeGenPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CodeGenPreTrainedModel),
/* harmony export */   "CodeGenTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CodeGenTokenizer),
/* harmony export */   "CodeLlamaTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CodeLlamaTokenizer),
/* harmony export */   "CohereTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CohereTokenizer),
/* harmony export */   "ConvBertForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForMaskedLM),
/* harmony export */   "ConvBertForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForQuestionAnswering),
/* harmony export */   "ConvBertForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForSequenceClassification),
/* harmony export */   "ConvBertForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForTokenClassification),
/* harmony export */   "ConvBertModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertModel),
/* harmony export */   "ConvBertPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertPreTrainedModel),
/* harmony export */   "ConvBertTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.ConvBertTokenizer),
/* harmony export */   "ConvNextFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.ConvNextFeatureExtractor),
/* harmony export */   "ConvNextForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextForImageClassification),
/* harmony export */   "ConvNextImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.ConvNextImageProcessor),
/* harmony export */   "ConvNextModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextModel),
/* harmony export */   "ConvNextPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextPreTrainedModel),
/* harmony export */   "ConvNextV2ForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextV2ForImageClassification),
/* harmony export */   "ConvNextV2Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextV2Model),
/* harmony export */   "ConvNextV2PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextV2PreTrainedModel),
/* harmony export */   "DPTFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.DPTFeatureExtractor),
/* harmony export */   "DPTForDepthEstimation": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DPTForDepthEstimation),
/* harmony export */   "DPTImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.DPTImageProcessor),
/* harmony export */   "DPTModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DPTModel),
/* harmony export */   "DPTPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DPTPreTrainedModel),
/* harmony export */   "DebertaForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForMaskedLM),
/* harmony export */   "DebertaForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForQuestionAnswering),
/* harmony export */   "DebertaForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForSequenceClassification),
/* harmony export */   "DebertaForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForTokenClassification),
/* harmony export */   "DebertaModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaModel),
/* harmony export */   "DebertaPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaPreTrainedModel),
/* harmony export */   "DebertaTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.DebertaTokenizer),
/* harmony export */   "DebertaV2ForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForMaskedLM),
/* harmony export */   "DebertaV2ForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForQuestionAnswering),
/* harmony export */   "DebertaV2ForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForSequenceClassification),
/* harmony export */   "DebertaV2ForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForTokenClassification),
/* harmony export */   "DebertaV2Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2Model),
/* harmony export */   "DebertaV2PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2PreTrainedModel),
/* harmony export */   "DebertaV2Tokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.DebertaV2Tokenizer),
/* harmony export */   "DeiTFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.DeiTFeatureExtractor),
/* harmony export */   "DeiTForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DeiTForImageClassification),
/* harmony export */   "DeiTModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DeiTModel),
/* harmony export */   "DeiTPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DeiTPreTrainedModel),
/* harmony export */   "DepthAnythingForDepthEstimation": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DepthAnythingForDepthEstimation),
/* harmony export */   "DepthAnythingPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DepthAnythingPreTrainedModel),
/* harmony export */   "DepthEstimationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.DepthEstimationPipeline),
/* harmony export */   "DetrFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.DetrFeatureExtractor),
/* harmony export */   "DetrForObjectDetection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrForObjectDetection),
/* harmony export */   "DetrForSegmentation": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrForSegmentation),
/* harmony export */   "DetrModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrModel),
/* harmony export */   "DetrObjectDetectionOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrObjectDetectionOutput),
/* harmony export */   "DetrPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrPreTrainedModel),
/* harmony export */   "DetrSegmentationOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrSegmentationOutput),
/* harmony export */   "Dinov2ForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2ForImageClassification),
/* harmony export */   "Dinov2Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2Model),
/* harmony export */   "Dinov2PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2PreTrainedModel),
/* harmony export */   "DistilBertForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForMaskedLM),
/* harmony export */   "DistilBertForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForQuestionAnswering),
/* harmony export */   "DistilBertForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForSequenceClassification),
/* harmony export */   "DistilBertForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForTokenClassification),
/* harmony export */   "DistilBertModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertModel),
/* harmony export */   "DistilBertPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertPreTrainedModel),
/* harmony export */   "DistilBertTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.DistilBertTokenizer),
/* harmony export */   "DocumentQuestionAnsweringPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.DocumentQuestionAnsweringPipeline),
/* harmony export */   "DonutFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.DonutFeatureExtractor),
/* harmony export */   "DonutSwinModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DonutSwinModel),
/* harmony export */   "DonutSwinPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DonutSwinPreTrainedModel),
/* harmony export */   "EfficientNetForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EfficientNetForImageClassification),
/* harmony export */   "EfficientNetImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.EfficientNetImageProcessor),
/* harmony export */   "EfficientNetModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EfficientNetModel),
/* harmony export */   "EfficientNetPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EfficientNetPreTrainedModel),
/* harmony export */   "ElectraForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForMaskedLM),
/* harmony export */   "ElectraForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForQuestionAnswering),
/* harmony export */   "ElectraForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForSequenceClassification),
/* harmony export */   "ElectraForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForTokenClassification),
/* harmony export */   "ElectraModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraModel),
/* harmony export */   "ElectraPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraPreTrainedModel),
/* harmony export */   "ElectraTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.ElectraTokenizer),
/* harmony export */   "EsmForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmForMaskedLM),
/* harmony export */   "EsmForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmForSequenceClassification),
/* harmony export */   "EsmForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmForTokenClassification),
/* harmony export */   "EsmModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmModel),
/* harmony export */   "EsmPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmPreTrainedModel),
/* harmony export */   "EsmTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.EsmTokenizer),
/* harmony export */   "FFT": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.FFT),
/* harmony export */   "FalconForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FalconForCausalLM),
/* harmony export */   "FalconModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FalconModel),
/* harmony export */   "FalconPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FalconPreTrainedModel),
/* harmony export */   "FalconTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.FalconTokenizer),
/* harmony export */   "FastViTForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FastViTForImageClassification),
/* harmony export */   "FastViTModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FastViTModel),
/* harmony export */   "FastViTPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FastViTPreTrainedModel),
/* harmony export */   "FeatureExtractionPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractionPipeline),
/* harmony export */   "FeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.FeatureExtractor),
/* harmony export */   "FillMaskPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.FillMaskPipeline),
/* harmony export */   "GLPNFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.GLPNFeatureExtractor),
/* harmony export */   "GLPNForDepthEstimation": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GLPNForDepthEstimation),
/* harmony export */   "GLPNModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GLPNModel),
/* harmony export */   "GLPNPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GLPNPreTrainedModel),
/* harmony export */   "GPT2LMHeadModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPT2LMHeadModel),
/* harmony export */   "GPT2Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPT2Model),
/* harmony export */   "GPT2PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPT2PreTrainedModel),
/* harmony export */   "GPT2Tokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.GPT2Tokenizer),
/* harmony export */   "GPTBigCodeForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTBigCodeForCausalLM),
/* harmony export */   "GPTBigCodeModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTBigCodeModel),
/* harmony export */   "GPTBigCodePreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTBigCodePreTrainedModel),
/* harmony export */   "GPTJForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTJForCausalLM),
/* harmony export */   "GPTJModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTJModel),
/* harmony export */   "GPTJPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTJPreTrainedModel),
/* harmony export */   "GPTNeoForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoForCausalLM),
/* harmony export */   "GPTNeoModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoModel),
/* harmony export */   "GPTNeoPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoPreTrainedModel),
/* harmony export */   "GPTNeoXForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoXForCausalLM),
/* harmony export */   "GPTNeoXModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoXModel),
/* harmony export */   "GPTNeoXPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoXPreTrainedModel),
/* harmony export */   "GPTNeoXTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.GPTNeoXTokenizer),
/* harmony export */   "GemmaTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.GemmaTokenizer),
/* harmony export */   "Grok1Tokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.Grok1Tokenizer),
/* harmony export */   "HerbertTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.HerbertTokenizer),
/* harmony export */   "HubertForCTC": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertForCTC),
/* harmony export */   "HubertForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertForSequenceClassification),
/* harmony export */   "HubertModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertModel),
/* harmony export */   "HubertPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertPreTrainedModel),
/* harmony export */   "ImageClassificationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.ImageClassificationPipeline),
/* harmony export */   "ImageFeatureExtractionPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.ImageFeatureExtractionPipeline),
/* harmony export */   "ImageFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.ImageFeatureExtractor),
/* harmony export */   "ImageMattingOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ImageMattingOutput),
/* harmony export */   "ImageSegmentationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.ImageSegmentationPipeline),
/* harmony export */   "ImageToImagePipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.ImageToImagePipeline),
/* harmony export */   "ImageToTextPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.ImageToTextPipeline),
/* harmony export */   "LlamaForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LlamaForCausalLM),
/* harmony export */   "LlamaModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LlamaModel),
/* harmony export */   "LlamaPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LlamaPreTrainedModel),
/* harmony export */   "LlamaTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.LlamaTokenizer),
/* harmony export */   "LongT5ForConditionalGeneration": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LongT5ForConditionalGeneration),
/* harmony export */   "LongT5Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LongT5Model),
/* harmony export */   "LongT5PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LongT5PreTrainedModel),
/* harmony export */   "M2M100ForConditionalGeneration": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.M2M100ForConditionalGeneration),
/* harmony export */   "M2M100Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.M2M100Model),
/* harmony export */   "M2M100PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.M2M100PreTrainedModel),
/* harmony export */   "M2M100Tokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.M2M100Tokenizer),
/* harmony export */   "MBart50Tokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MBart50Tokenizer),
/* harmony export */   "MBartForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartForCausalLM),
/* harmony export */   "MBartForConditionalGeneration": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartForConditionalGeneration),
/* harmony export */   "MBartForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartForSequenceClassification),
/* harmony export */   "MBartModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartModel),
/* harmony export */   "MBartPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartPreTrainedModel),
/* harmony export */   "MBartTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MBartTokenizer),
/* harmony export */   "MPNetForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForMaskedLM),
/* harmony export */   "MPNetForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForQuestionAnswering),
/* harmony export */   "MPNetForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForSequenceClassification),
/* harmony export */   "MPNetForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForTokenClassification),
/* harmony export */   "MPNetModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetModel),
/* harmony export */   "MPNetPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetPreTrainedModel),
/* harmony export */   "MPNetTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MPNetTokenizer),
/* harmony export */   "MT5ForConditionalGeneration": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MT5ForConditionalGeneration),
/* harmony export */   "MT5Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MT5Model),
/* harmony export */   "MT5PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MT5PreTrainedModel),
/* harmony export */   "MarianMTModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MarianMTModel),
/* harmony export */   "MarianModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MarianModel),
/* harmony export */   "MarianPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MarianPreTrainedModel),
/* harmony export */   "MarianTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MarianTokenizer),
/* harmony export */   "MaskedLMOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MaskedLMOutput),
/* harmony export */   "MistralForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MistralForCausalLM),
/* harmony export */   "MistralModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MistralModel),
/* harmony export */   "MistralPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MistralPreTrainedModel),
/* harmony export */   "MobileBertForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertForMaskedLM),
/* harmony export */   "MobileBertForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertForQuestionAnswering),
/* harmony export */   "MobileBertForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertForSequenceClassification),
/* harmony export */   "MobileBertModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertModel),
/* harmony export */   "MobileBertPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertPreTrainedModel),
/* harmony export */   "MobileBertTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MobileBertTokenizer),
/* harmony export */   "MobileViTFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.MobileViTFeatureExtractor),
/* harmony export */   "MobileViTForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTForImageClassification),
/* harmony export */   "MobileViTImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.MobileViTImageProcessor),
/* harmony export */   "MobileViTModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTModel),
/* harmony export */   "MobileViTPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTPreTrainedModel),
/* harmony export */   "MobileViTV2ForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTV2ForImageClassification),
/* harmony export */   "MobileViTV2Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTV2Model),
/* harmony export */   "MobileViTV2PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTV2PreTrainedModel),
/* harmony export */   "ModelOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ModelOutput),
/* harmony export */   "MptForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MptForCausalLM),
/* harmony export */   "MptModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MptModel),
/* harmony export */   "MptPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MptPreTrainedModel),
/* harmony export */   "NllbTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.NllbTokenizer),
/* harmony export */   "NomicBertModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.NomicBertModel),
/* harmony export */   "NomicBertPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.NomicBertPreTrainedModel),
/* harmony export */   "NougatImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.NougatImageProcessor),
/* harmony export */   "NougatTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.NougatTokenizer),
/* harmony export */   "OPTForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OPTForCausalLM),
/* harmony export */   "OPTModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OPTModel),
/* harmony export */   "OPTPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OPTPreTrainedModel),
/* harmony export */   "ObjectDetectionPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.ObjectDetectionPipeline),
/* harmony export */   "OwlViTFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.OwlViTFeatureExtractor),
/* harmony export */   "OwlViTForObjectDetection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OwlViTForObjectDetection),
/* harmony export */   "OwlViTModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OwlViTModel),
/* harmony export */   "OwlViTPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OwlViTPreTrainedModel),
/* harmony export */   "OwlViTProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.OwlViTProcessor),
/* harmony export */   "Owlv2ForObjectDetection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Owlv2ForObjectDetection),
/* harmony export */   "Owlv2ImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.Owlv2ImageProcessor),
/* harmony export */   "Owlv2Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Owlv2Model),
/* harmony export */   "Owlv2PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Owlv2PreTrainedModel),
/* harmony export */   "PhiForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PhiForCausalLM),
/* harmony export */   "PhiModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PhiModel),
/* harmony export */   "PhiPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PhiPreTrainedModel),
/* harmony export */   "Pipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.Pipeline),
/* harmony export */   "PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PreTrainedModel),
/* harmony export */   "PreTrainedTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.PreTrainedTokenizer),
/* harmony export */   "PretrainedConfig": () => (/* reexport safe */ _configs_js__WEBPACK_IMPORTED_MODULE_5__.PretrainedConfig),
/* harmony export */   "PretrainedMixin": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PretrainedMixin),
/* harmony export */   "Processor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.Processor),
/* harmony export */   "QuestionAnsweringModelOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.QuestionAnsweringModelOutput),
/* harmony export */   "QuestionAnsweringPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.QuestionAnsweringPipeline),
/* harmony export */   "Qwen2ForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2ForCausalLM),
/* harmony export */   "Qwen2Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2Model),
/* harmony export */   "Qwen2PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2PreTrainedModel),
/* harmony export */   "Qwen2Tokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.Qwen2Tokenizer),
/* harmony export */   "RawImage": () => (/* reexport safe */ _utils_image_js__WEBPACK_IMPORTED_MODULE_7__.RawImage),
/* harmony export */   "ResNetForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ResNetForImageClassification),
/* harmony export */   "ResNetModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ResNetModel),
/* harmony export */   "ResNetPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ResNetPreTrainedModel),
/* harmony export */   "RoFormerForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForMaskedLM),
/* harmony export */   "RoFormerForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForQuestionAnswering),
/* harmony export */   "RoFormerForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForSequenceClassification),
/* harmony export */   "RoFormerForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForTokenClassification),
/* harmony export */   "RoFormerModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerModel),
/* harmony export */   "RoFormerPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerPreTrainedModel),
/* harmony export */   "RoFormerTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.RoFormerTokenizer),
/* harmony export */   "RobertaForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForMaskedLM),
/* harmony export */   "RobertaForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForQuestionAnswering),
/* harmony export */   "RobertaForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForSequenceClassification),
/* harmony export */   "RobertaForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForTokenClassification),
/* harmony export */   "RobertaModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaModel),
/* harmony export */   "RobertaPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaPreTrainedModel),
/* harmony export */   "RobertaTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.RobertaTokenizer),
/* harmony export */   "SamImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.SamImageProcessor),
/* harmony export */   "SamImageSegmentationOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SamImageSegmentationOutput),
/* harmony export */   "SamModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SamModel),
/* harmony export */   "SamPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SamPreTrainedModel),
/* harmony export */   "SamProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.SamProcessor),
/* harmony export */   "SeamlessM4TFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.SeamlessM4TFeatureExtractor),
/* harmony export */   "SegformerFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.SegformerFeatureExtractor),
/* harmony export */   "SegformerForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerForImageClassification),
/* harmony export */   "SegformerForSemanticSegmentation": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerForSemanticSegmentation),
/* harmony export */   "SegformerModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerModel),
/* harmony export */   "SegformerPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerPreTrainedModel),
/* harmony export */   "Seq2SeqLMOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Seq2SeqLMOutput),
/* harmony export */   "SequenceClassifierOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SequenceClassifierOutput),
/* harmony export */   "SiglipImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.SiglipImageProcessor),
/* harmony export */   "SiglipModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipModel),
/* harmony export */   "SiglipPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipPreTrainedModel),
/* harmony export */   "SiglipTextModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipTextModel),
/* harmony export */   "SiglipTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.SiglipTokenizer),
/* harmony export */   "SiglipVisionModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipVisionModel),
/* harmony export */   "SpeechT5FeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.SpeechT5FeatureExtractor),
/* harmony export */   "SpeechT5ForSpeechToText": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5ForSpeechToText),
/* harmony export */   "SpeechT5ForTextToSpeech": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5ForTextToSpeech),
/* harmony export */   "SpeechT5HifiGan": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5HifiGan),
/* harmony export */   "SpeechT5Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5Model),
/* harmony export */   "SpeechT5PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5PreTrainedModel),
/* harmony export */   "SpeechT5Processor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.SpeechT5Processor),
/* harmony export */   "SpeechT5Tokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.SpeechT5Tokenizer),
/* harmony export */   "SqueezeBertForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertForMaskedLM),
/* harmony export */   "SqueezeBertForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertForQuestionAnswering),
/* harmony export */   "SqueezeBertForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertForSequenceClassification),
/* harmony export */   "SqueezeBertModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertModel),
/* harmony export */   "SqueezeBertPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertPreTrainedModel),
/* harmony export */   "SqueezeBertTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.SqueezeBertTokenizer),
/* harmony export */   "StableLmForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.StableLmForCausalLM),
/* harmony export */   "StableLmModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.StableLmModel),
/* harmony export */   "StableLmPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.StableLmPreTrainedModel),
/* harmony export */   "Starcoder2ForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Starcoder2ForCausalLM),
/* harmony export */   "Starcoder2Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Starcoder2Model),
/* harmony export */   "Starcoder2PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Starcoder2PreTrainedModel),
/* harmony export */   "SummarizationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.SummarizationPipeline),
/* harmony export */   "Swin2SRForImageSuperResolution": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Swin2SRForImageSuperResolution),
/* harmony export */   "Swin2SRImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.Swin2SRImageProcessor),
/* harmony export */   "Swin2SRModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Swin2SRModel),
/* harmony export */   "Swin2SRPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Swin2SRPreTrainedModel),
/* harmony export */   "SwinForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinForImageClassification),
/* harmony export */   "SwinModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinModel),
/* harmony export */   "SwinPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinPreTrainedModel),
/* harmony export */   "T5ForConditionalGeneration": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.T5ForConditionalGeneration),
/* harmony export */   "T5Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.T5Model),
/* harmony export */   "T5PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.T5PreTrainedModel),
/* harmony export */   "T5Tokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.T5Tokenizer),
/* harmony export */   "TableTransformerForObjectDetection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerForObjectDetection),
/* harmony export */   "TableTransformerModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerModel),
/* harmony export */   "TableTransformerObjectDetectionOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerObjectDetectionOutput),
/* harmony export */   "TableTransformerPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerPreTrainedModel),
/* harmony export */   "Tensor": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor),
/* harmony export */   "Text2TextGenerationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.Text2TextGenerationPipeline),
/* harmony export */   "TextClassificationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.TextClassificationPipeline),
/* harmony export */   "TextGenerationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.TextGenerationPipeline),
/* harmony export */   "TextToAudioPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.TextToAudioPipeline),
/* harmony export */   "TokenClassificationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.TokenClassificationPipeline),
/* harmony export */   "TokenClassifierOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TokenClassifierOutput),
/* harmony export */   "TokenizerModel": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.TokenizerModel),
/* harmony export */   "TrOCRForCausalLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TrOCRForCausalLM),
/* harmony export */   "TrOCRPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TrOCRPreTrainedModel),
/* harmony export */   "TranslationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.TranslationPipeline),
/* harmony export */   "UniSpeechForCTC": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechForCTC),
/* harmony export */   "UniSpeechForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechForSequenceClassification),
/* harmony export */   "UniSpeechModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechModel),
/* harmony export */   "UniSpeechPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechPreTrainedModel),
/* harmony export */   "UniSpeechSatForAudioFrameClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatForAudioFrameClassification),
/* harmony export */   "UniSpeechSatForCTC": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatForCTC),
/* harmony export */   "UniSpeechSatForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatForSequenceClassification),
/* harmony export */   "UniSpeechSatModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatModel),
/* harmony export */   "UniSpeechSatPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatPreTrainedModel),
/* harmony export */   "ViTFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.ViTFeatureExtractor),
/* harmony export */   "ViTForImageClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTForImageClassification),
/* harmony export */   "ViTImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.ViTImageProcessor),
/* harmony export */   "ViTModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTModel),
/* harmony export */   "ViTPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTPreTrainedModel),
/* harmony export */   "VisionEncoderDecoderModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VisionEncoderDecoderModel),
/* harmony export */   "VitMatteForImageMatting": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitMatteForImageMatting),
/* harmony export */   "VitMatteImageProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.VitMatteImageProcessor),
/* harmony export */   "VitMattePreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitMattePreTrainedModel),
/* harmony export */   "VitsModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitsModel),
/* harmony export */   "VitsModelOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitsModelOutput),
/* harmony export */   "VitsPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitsPreTrainedModel),
/* harmony export */   "VitsTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.VitsTokenizer),
/* harmony export */   "Wav2Vec2BertForCTC": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertForCTC),
/* harmony export */   "Wav2Vec2BertForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertForSequenceClassification),
/* harmony export */   "Wav2Vec2BertModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertModel),
/* harmony export */   "Wav2Vec2BertPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertPreTrainedModel),
/* harmony export */   "Wav2Vec2CTCTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.Wav2Vec2CTCTokenizer),
/* harmony export */   "Wav2Vec2FeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.Wav2Vec2FeatureExtractor),
/* harmony export */   "Wav2Vec2ForAudioFrameClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2ForAudioFrameClassification),
/* harmony export */   "Wav2Vec2ForCTC": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2ForCTC),
/* harmony export */   "Wav2Vec2ForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2ForSequenceClassification),
/* harmony export */   "Wav2Vec2Model": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2Model),
/* harmony export */   "Wav2Vec2PreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2PreTrainedModel),
/* harmony export */   "Wav2Vec2ProcessorWithLM": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.Wav2Vec2ProcessorWithLM),
/* harmony export */   "WavLMForAudioFrameClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForAudioFrameClassification),
/* harmony export */   "WavLMForCTC": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForCTC),
/* harmony export */   "WavLMForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForSequenceClassification),
/* harmony export */   "WavLMForXVector": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForXVector),
/* harmony export */   "WavLMModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMModel),
/* harmony export */   "WavLMPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMPreTrainedModel),
/* harmony export */   "WhisperFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.WhisperFeatureExtractor),
/* harmony export */   "WhisperForConditionalGeneration": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WhisperForConditionalGeneration),
/* harmony export */   "WhisperModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WhisperModel),
/* harmony export */   "WhisperPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WhisperPreTrainedModel),
/* harmony export */   "WhisperProcessor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.WhisperProcessor),
/* harmony export */   "WhisperTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.WhisperTokenizer),
/* harmony export */   "XLMForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMForQuestionAnswering),
/* harmony export */   "XLMForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMForSequenceClassification),
/* harmony export */   "XLMForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMForTokenClassification),
/* harmony export */   "XLMModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMModel),
/* harmony export */   "XLMPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMPreTrainedModel),
/* harmony export */   "XLMRobertaForMaskedLM": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForMaskedLM),
/* harmony export */   "XLMRobertaForQuestionAnswering": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForQuestionAnswering),
/* harmony export */   "XLMRobertaForSequenceClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForSequenceClassification),
/* harmony export */   "XLMRobertaForTokenClassification": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForTokenClassification),
/* harmony export */   "XLMRobertaModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaModel),
/* harmony export */   "XLMRobertaPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaPreTrainedModel),
/* harmony export */   "XLMRobertaTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.XLMRobertaTokenizer),
/* harmony export */   "XLMTokenizer": () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.XLMTokenizer),
/* harmony export */   "XLMWithLMHeadModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMWithLMHeadModel),
/* harmony export */   "XVectorOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XVectorOutput),
/* harmony export */   "YolosFeatureExtractor": () => (/* reexport safe */ _processors_js__WEBPACK_IMPORTED_MODULE_4__.YolosFeatureExtractor),
/* harmony export */   "YolosForObjectDetection": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosForObjectDetection),
/* harmony export */   "YolosModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosModel),
/* harmony export */   "YolosObjectDetectionOutput": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosObjectDetectionOutput),
/* harmony export */   "YolosPreTrainedModel": () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosPreTrainedModel),
/* harmony export */   "ZeroShotAudioClassificationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.ZeroShotAudioClassificationPipeline),
/* harmony export */   "ZeroShotClassificationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.ZeroShotClassificationPipeline),
/* harmony export */   "ZeroShotImageClassificationPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.ZeroShotImageClassificationPipeline),
/* harmony export */   "ZeroShotObjectDetectionPipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.ZeroShotObjectDetectionPipeline),
/* harmony export */   "bankers_round": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.bankers_round),
/* harmony export */   "cat": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.cat),
/* harmony export */   "cos_sim": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.cos_sim),
/* harmony export */   "dot": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.dot),
/* harmony export */   "dynamicTimeWarping": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.dynamicTimeWarping),
/* harmony export */   "env": () => (/* reexport safe */ _env_js__WEBPACK_IMPORTED_MODULE_1__.env),
/* harmony export */   "getTopItems": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.getTopItems),
/* harmony export */   "hanning": () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_6__.hanning),
/* harmony export */   "interpolate": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.interpolate),
/* harmony export */   "interpolate_data": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.interpolate_data),
/* harmony export */   "layer_norm": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.layer_norm),
/* harmony export */   "log_softmax": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.log_softmax),
/* harmony export */   "magnitude": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.magnitude),
/* harmony export */   "max": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.max),
/* harmony export */   "mean": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.mean),
/* harmony export */   "mean_pooling": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.mean_pooling),
/* harmony export */   "medianFilter": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.medianFilter),
/* harmony export */   "mel_filter_bank": () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_6__.mel_filter_bank),
/* harmony export */   "min": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.min),
/* harmony export */   "ones": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.ones),
/* harmony export */   "ones_like": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.ones_like),
/* harmony export */   "permute": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.permute),
/* harmony export */   "permute_data": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.permute_data),
/* harmony export */   "pipeline": () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_0__.pipeline),
/* harmony export */   "quantize_embeddings": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.quantize_embeddings),
/* harmony export */   "read_audio": () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_6__.read_audio),
/* harmony export */   "round": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.round),
/* harmony export */   "softmax": () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.softmax),
/* harmony export */   "spectrogram": () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_6__.spectrogram),
/* harmony export */   "stack": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.stack),
/* harmony export */   "std_mean": () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.std_mean),
/* harmony export */   "window_function": () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_6__.window_function)
/* harmony export */ });
/* harmony import */ var _pipelines_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./pipelines.js */ "./src/pipelines.js");
/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./env.js */ "./src/env.js");
/* harmony import */ var _models_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./models.js */ "./src/models.js");
/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tokenizers.js */ "./src/tokenizers.js");
/* harmony import */ var _processors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./processors.js */ "./src/processors.js");
/* harmony import */ var _configs_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./configs.js */ "./src/configs.js");
/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/audio.js */ "./src/utils/audio.js");
/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/image.js */ "./src/utils/image.js");
/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/tensor.js */ "./src/utils/tensor.js");
/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/maths.js */ "./src/utils/maths.js");
/**
 * @file Entry point for the Transformers.js library. Only the exports from this file
 * are available to the end user, and are grouped as follows:
 * 
 * 1. [Pipelines](./pipelines)
 * 2. [Environment variables](./env)
 * 3. [Models](./models)
 * 4. [Tokenizers](./tokenizers)
 * 5. [Processors](./processors)
 * 
 * @module transformers
 */














/***/ }),

/***/ "./src/utils/audio.js":
/*!****************************!*\
  !*** ./src/utils/audio.js ***!
  \****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "hanning": () => (/* binding */ hanning),
/* harmony export */   "mel_filter_bank": () => (/* binding */ mel_filter_bank),
/* harmony export */   "read_audio": () => (/* binding */ read_audio),
/* harmony export */   "spectrogram": () => (/* binding */ spectrogram),
/* harmony export */   "window_function": () => (/* binding */ window_function)
/* harmony export */ });
/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hub.js */ "./src/utils/hub.js");
/* harmony import */ var _maths_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./maths.js */ "./src/utils/maths.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./core.js */ "./src/utils/core.js");
/**
 * @file Helper module for audio processing. 
 * 
 * These functions and classes are only used internally, 
 * meaning an end-user shouldn't need to access anything here.
 * 
 * @module utils/audio
 */






/**
 * Helper function to read audio from a path/URL.
 * @param {string|URL} url The path/URL to load the audio from.
 * @param {number} sampling_rate The sampling rate to use when decoding the audio.
 * @returns {Promise<Float32Array>} The decoded audio as a `Float32Array`.
 */
async function read_audio(url, sampling_rate) {
    if (typeof AudioContext === 'undefined') {
        // Running in node or an environment without AudioContext
        throw Error(
            "Unable to load audio from path/URL since `AudioContext` is not available in your environment. " +
            "Instead, audio data should be passed directly to the pipeline/processor. " +
            "For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing."
        )
    }

    const response = await (await (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getFile)(url)).arrayBuffer();
    const audioCTX = new AudioContext({ sampleRate: sampling_rate });
    if (typeof sampling_rate === 'undefined') {
        console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`)
    }
    const decoded = await audioCTX.decodeAudioData(response);

    /** @type {Float32Array} */
    let audio;

    // We now replicate HuggingFace's `ffmpeg_read` method:
    if (decoded.numberOfChannels === 2) {
        // When downmixing a stereo audio file to mono using the -ac 1 option in FFmpeg,
        // the audio signal is summed across both channels to create a single mono channel.
        // However, if the audio is at full scale (i.e. the highest possible volume level),
        // the summing of the two channels can cause the audio signal to clip or distort.

        // To prevent this clipping, FFmpeg applies a scaling factor of 1/sqrt(2) (~ 0.707)
        // to the audio signal before summing the two channels. This scaling factor ensures
        // that the combined audio signal will not exceed the maximum possible level, even
        // if both channels are at full scale.

        // After applying this scaling factor, the audio signal from both channels is summed
        // to create a single mono channel. It's worth noting that this scaling factor is
        // only applied when downmixing stereo audio to mono using the -ac 1 option in FFmpeg.
        // If you're using a different downmixing method, or if you're not downmixing the
        // audio at all, this scaling factor may not be needed.
        const SCALING_FACTOR = Math.sqrt(2);

        const left = decoded.getChannelData(0);
        const right = decoded.getChannelData(1);

        audio = new Float32Array(left.length);
        for (let i = 0; i < decoded.length; ++i) {
            audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2;
        }

    } else {
        // If the audio is not stereo, we can just use the first channel:
        audio = decoded.getChannelData(0);
    }

    return audio;
}

/**
 * Generates a Hanning window of length M.
 *
 * @param {number} M The length of the Hanning window to generate.
 * @returns {Float64Array} The generated Hanning window.
 */
function hanning(M) {
    if (M < 1) {
        return new Float64Array();
    }
    if (M === 1) {
        return new Float64Array([1]);
    }
    const denom = M - 1;
    const factor = Math.PI / denom;
    const cos_vals = new Float64Array(M);
    for (let i = 0; i < M; ++i) {
        const n = 2 * i - denom;
        cos_vals[i] = 0.5 + 0.5 * Math.cos(factor * n);
    }
    return cos_vals;
}

const HERTZ_TO_MEL_MAPPING = {
    "htk": (/** @type {number} */ freq) => 2595.0 * Math.log10(1.0 + (freq / 700.0)),
    "kaldi": (/** @type {number} */ freq) => 1127.0 * Math.log(1.0 + (freq / 700.0)),
    "slaney": (/** @type {number} */ freq, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = 27.0 / Math.log(6.4)) =>
        freq >= min_log_hertz
            ? min_log_mel + Math.log(freq / min_log_hertz) * logstep
            : 3.0 * freq / 200.0,
}

/**
 * @template {Float32Array|Float64Array|number} T 
 * @param {T} freq 
 * @param {string} [mel_scale]
 * @returns {T}
 */
function hertz_to_mel(freq, mel_scale = "htk") {
    const fn = HERTZ_TO_MEL_MAPPING[mel_scale];
    if (!fn) {
        throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');
    }

    return typeof freq === 'number' ? fn(freq) : freq.map(x => fn(x));
}

const MEL_TO_HERTZ_MAPPING = {
    "htk": (/** @type {number} */ mels) => 700.0 * (10.0 ** (mels / 2595.0) - 1.0),
    "kaldi": (/** @type {number} */ mels) => 700.0 * (Math.exp(mels / 1127.0) - 1.0),
    "slaney": (/** @type {number} */ mels, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = Math.log(6.4) / 27.0) => mels >= min_log_mel
        ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel))
        : 200.0 * mels / 3.0,
}

/**
 * @template {Float32Array|Float64Array|number} T 
 * @param {T} mels 
 * @param {string} [mel_scale]
 * @returns {T}
 */
function mel_to_hertz(mels, mel_scale = "htk") {
    const fn = MEL_TO_HERTZ_MAPPING[mel_scale];
    if (!fn) {
        throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');
    }

    return typeof mels === 'number' ? fn(mels) : mels.map(x => fn(x));
}

/**
* Creates a triangular filter bank.
*
* Adapted from torchaudio and librosa.
*
* @param {Float64Array} fft_freqs Discrete frequencies of the FFT bins in Hz, of shape `(num_frequency_bins,)`.
* @param {Float64Array} filter_freqs Center frequencies of the triangular filters to create, in Hz, of shape `(num_mel_filters,)`.
* @returns {number[][]} of shape `(num_frequency_bins, num_mel_filters)`.
*/
function _create_triangular_filter_bank(fft_freqs, filter_freqs) {
    const filter_diff = Float64Array.from(
        { length: filter_freqs.length - 1 },
        (_, i) => filter_freqs[i + 1] - filter_freqs[i]
    );

    const slopes = Array.from({
        length: fft_freqs.length
    }, () => new Array(filter_freqs.length));

    for (let j = 0; j < fft_freqs.length; ++j) {
        const slope = slopes[j];
        for (let i = 0; i < filter_freqs.length; ++i) {
            slope[i] = filter_freqs[i] - fft_freqs[j];
        }
    }

    const numFreqs = filter_freqs.length - 2;
    const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length));

    for (let j = 0; j < fft_freqs.length; ++j) { // 201
        const slope = slopes[j];
        for (let i = 0; i < numFreqs; ++i) { // 80
            const down = -slope[i] / filter_diff[i];
            const up = slope[i + 2] / filter_diff[i + 1];
            ret[i][j] = Math.max(0, Math.min(down, up));
        }
    }
    return ret;
}

/**
 * Return evenly spaced numbers over a specified interval.
 * @param {number} start The starting value of the sequence.
 * @param {number} end The end value of the sequence.
 * @param {number} num Number of samples to generate.
 * @returns `num` evenly spaced samples, calculated over the interval `[start, stop]`.
 */
function linspace(start, end, num) {
    const step = (end - start) / (num - 1);
    return Float64Array.from({ length: num }, (_, i) => start + step * i);
}

/**
 * Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and
 * various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters
 * are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these
 * features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.
 * @param {number} num_frequency_bins Number of frequencies used to compute the spectrogram (should be the same as in `stft`).
 * @param {number} num_mel_filters Number of mel filters to generate.
 * @param {number} min_frequency Lowest frequency of interest in Hz.
 * @param {number} max_frequency Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.
 * @param {number} sampling_rate Sample rate of the audio waveform.
 * @param {string} [norm] If `"slaney"`, divide the triangular mel weights by the width of the mel band (area normalization).
 * @param {string} [mel_scale] The mel frequency scale to use, `"htk"` or `"slaney"`.
 * @param {boolean} [triangularize_in_mel_space] If this option is enabled, the triangular filter is applied in mel space rather than frequency space.
 * This should be set to `true` in order to get the same results as `torchaudio` when computing mel filters.
 * @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`).
 * This is a projection matrix to go from a spectrogram to a mel spectrogram.
 */
function mel_filter_bank(
    num_frequency_bins,
    num_mel_filters,
    min_frequency,
    max_frequency,
    sampling_rate,
    norm = null,
    mel_scale = "htk",
    triangularize_in_mel_space = false,
) {
    if (norm !== null && norm !== "slaney") {
        throw new Error('norm must be one of null or "slaney"');
    }

    const mel_min = hertz_to_mel(min_frequency, mel_scale);
    const mel_max = hertz_to_mel(max_frequency, mel_scale);
    const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2);

    let filter_freqs = mel_to_hertz(mel_freqs, mel_scale);
    let fft_freqs; // frequencies of FFT bins in Hz

    if (triangularize_in_mel_space) {
        const fft_bin_width = sampling_rate / (num_frequency_bins * 2);
        fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale);
        filter_freqs = mel_freqs;
    } else {
        fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins);
    }

    const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs);

    if (norm !== null && norm === "slaney") {
        // Slaney-style mel is scaled to be approx constant energy per channel
        for (let i = 0; i < num_mel_filters; ++i) {
            const filter = mel_filters[i];
            const enorm = 2.0 / (filter_freqs[i + 2] - filter_freqs[i]);
            for (let j = 0; j < num_frequency_bins; ++j) {
                // Apply this enorm to all frequency bins
                filter[j] *= enorm;
            }
        }
    }

    // TODO warn if there is a zero row

    return mel_filters;

}

/**
 * @template {Float32Array|Float64Array} T
 * Pads an array with a reflected version of itself on both ends.
 * @param {T} array The array to pad.
 * @param {number} left The amount of padding to add to the left.
 * @param {number} right The amount of padding to add to the right.
 * @returns {T} The padded array.
 */
function padReflect(array, left, right) {
    // @ts-ignore
    const padded = new array.constructor(array.length + left + right);
    const w = array.length - 1;

    for (let i = 0; i < array.length; ++i) {
        padded[left + i] = array[i];
    }

    for (let i = 1; i <= left; ++i) {
        padded[left - i] = array[(0,_core_js__WEBPACK_IMPORTED_MODULE_2__.calculateReflectOffset)(i, w)];
    }

    for (let i = 1; i <= right; ++i) {
        padded[w + left + i] = array[(0,_core_js__WEBPACK_IMPORTED_MODULE_2__.calculateReflectOffset)(w - i, w)];
    }

    return padded;
}

/**
 * Helper function to compute `amplitude_to_db` and `power_to_db`.
 * @template {Float32Array|Float64Array} T
 * @param {T} spectrogram 
 * @param {number} factor 
 * @param {number} reference 
 * @param {number} min_value 
 * @param {number} db_range 
 * @returns {T}
 */
function _db_conversion_helper(spectrogram, factor, reference, min_value, db_range) {
    if (reference <= 0) {
        throw new Error('reference must be greater than zero');
    }

    if (min_value <= 0) {
        throw new Error('min_value must be greater than zero');
    }

    reference = Math.max(min_value, reference);

    const logReference = Math.log10(reference);
    for (let i = 0; i < spectrogram.length; ++i) {
        spectrogram[i] = factor * Math.log10(Math.max(min_value, spectrogram[i]) - logReference)
    }

    if (db_range !== null) {
        if (db_range <= 0) {
            throw new Error('db_range must be greater than zero');
        }
        const maxValue = (0,_maths_js__WEBPACK_IMPORTED_MODULE_1__.max)(spectrogram)[0] - db_range;
        for (let i = 0; i < spectrogram.length; ++i) {
            spectrogram[i] = Math.max(spectrogram[i], maxValue);
        }
    }

    return spectrogram;
}

/**
 * Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`,
 * using basic logarithm properties for numerical stability. NOTE: Operates in-place.
 * 
 * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
 * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
 * This means that large variations in energy may not sound all that different if the sound is loud to begin with.
 * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
 * 
 * @template {Float32Array|Float64Array} T
 * @param {T} spectrogram The input amplitude (mel) spectrogram.
 * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.
 * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.
 * @param {number} [min_value=1e-5] The spectrogram will be clipped to this minimum value before conversion to decibels,
 * to avoid taking `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.
 * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the
 * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
 * @returns {T} The modified spectrogram in decibels.
 */
function amplitude_to_db(spectrogram, reference = 1.0, min_value = 1e-5, db_range = null) {
    return _db_conversion_helper(spectrogram, 20.0, reference, min_value, db_range);
}

/**
 * Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`,
 * using basic logarithm properties for numerical stability. NOTE: Operates in-place.
 * 
 * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
 * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
 * This means that large variations in energy may not sound all that different if the sound is loud to begin with.
 * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
 * 
 * Based on the implementation of `librosa.power_to_db`.
 * 
 * @template {Float32Array|Float64Array} T
 * @param {T} spectrogram The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared!
 * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.
 * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.
 * @param {number} [min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels,
 * to avoid taking `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.
 * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the
 * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
 * @returns {T} The modified spectrogram in decibels.
 */
function power_to_db(spectrogram, reference = 1.0, min_value = 1e-10, db_range = null) {
    return _db_conversion_helper(spectrogram, 10.0, reference, min_value, db_range);
}

/**
 * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.
 * 
 * This function can create the following kinds of spectrograms:
 *   - amplitude spectrogram (`power = 1.0`)
 *   - power spectrogram (`power = 2.0`)
 *   - complex-valued spectrogram (`power = None`)
 *   - log spectrogram (use `log_mel` argument)
 *   - mel spectrogram (provide `mel_filters`)
 *   - log-mel spectrogram (provide `mel_filters` and `log_mel`)
 *
 * In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame.
 * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame, 
 * typically the next power of two.
 * 
 * @param {Float32Array|Float64Array} waveform The input waveform of shape `(length,)`. This must be a single real-valued, mono waveform.
 * @param {Float32Array|Float64Array} window The windowing function to apply of shape `(frame_length,)`, including zero-padding if necessary. The actual window length may be
 * shorter than `frame_length`, but we're assuming the array has already been zero-padded.
 * @param {number} frame_length The length of the analysis frames in samples (a.k.a., `fft_length`).
 * @param {number} hop_length The stride between successive analysis frames in samples.
 * @param {Object} options
 * @param {number} [options.fft_length=null] The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have.
 * For optimal speed, this should be a power of two. If `null`, uses `frame_length`.
 * @param {number} [options.power=1.0] If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `null`, returns complex numbers.
 * @param {boolean} [options.center=true] Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `false`, frame
 * `t` will start at time `t * hop_length`.
 * @param {string} [options.pad_mode="reflect"] Padding mode used when `center` is `true`. Possible values are: `"constant"` (pad with zeros),
 * `"edge"` (pad with edge values), `"reflect"` (pads with mirrored values).
 * @param {boolean} [options.onesided=true] If `true`, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1`
 * frequency bins. If `false`, also computes the negative frequencies and returns `fft_length` frequency bins.
 * @param {number} [options.preemphasis=null] Coefficient for a low-pass filter that applies pre-emphasis before the DFT.
 * @param {number[][]} [options.mel_filters=null] The mel filter bank of shape `(num_freq_bins, num_mel_filters)`.
 * If supplied, applies this filter bank to create a mel spectrogram.
 * @param {number} [options.mel_floor=1e-10] Minimum value of mel frequency banks.
 * @param {string} [options.log_mel=null] How to convert the spectrogram to log scale. Possible options are:
 * `null` (don't convert), `"log"` (take the natural logarithm) `"log10"` (take the base-10 logarithm), `"dB"` (convert to decibels).
 * Can only be used when `power` is not `null`.
 * @param {number} [options.reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. For example, use `max(spectrogram)[0]` to set
 * the loudest part to 0 dB. Must be greater than zero.
 * @param {number} [options.min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking `log(0)`.
 * For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an amplitude spectrogram, the value `1e-5` corresponds to -100 dB.
 * Must be greater than zero.
 * @param {number} [options.db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
 * peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
 * @param {boolean} [options.remove_dc_offset=null] Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in
 * order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters.
 * @param {number} [options.max_num_frames=null] If provided, limits the number of frames to compute to this value.
 * @param {boolean} [options.do_pad=true] If `true`, pads the output spectrogram to have `max_num_frames` frames.
 * @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`.
 * @returns {{data: Float32Array, dims: number[]}} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram).
 */
function spectrogram(
    waveform,
    window,
    frame_length,
    hop_length,
    {
        fft_length = null,
        power = 1.0,
        center = true,
        pad_mode = "reflect",
        onesided = true,
        preemphasis = null,
        mel_filters = null,
        mel_floor = 1e-10,
        log_mel = null,
        reference = 1.0,
        min_value = 1e-10,
        db_range = null,
        remove_dc_offset = null,

        // Custom parameters for efficiency reasons
        max_num_frames = null,
        do_pad = true,
        transpose = false,
    } = {}
) {
    const window_length = window.length;
    if (fft_length === null) {
        fft_length = frame_length;
    }
    if (frame_length > fft_length) {
        throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`)
    }

    if (window_length !== frame_length) {
        throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`);
    }

    if (hop_length <= 0) {
        throw new Error("hop_length must be greater than zero");
    }

    if (power === null && mel_filters !== null) {
        throw new Error(
            "You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. " +
            "Specify `power` to fix this issue."
        );
    }

    if (center) {
        if (pad_mode !== 'reflect') {
            throw new Error(`pad_mode="${pad_mode}" not implemented yet.`)
        }
        const half_window = Math.floor((fft_length - 1) / 2) + 1;
        waveform = padReflect(waveform, half_window, half_window);
    }

    // split waveform into frames of frame_length size
    const num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length))

    const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length

    let d1 = num_frames;
    let d1Max = num_frames;

    // If maximum number of frames is provided, we must either pad or truncate
    if (max_num_frames !== null) {
        if (max_num_frames > num_frames) { // input is too short, so we pad
            if (do_pad) {
                d1Max = max_num_frames;
            }
        } else { // input is too long, so we truncate
            d1Max = d1 = max_num_frames;
        }
    }

    // Preallocate arrays to store output.
    const fft = new _maths_js__WEBPACK_IMPORTED_MODULE_1__.FFT(fft_length);
    const inputBuffer = new Float64Array(fft_length);
    const outputBuffer = new Float64Array(fft.outputBufferSize);
    const magnitudes = new Array(d1);

    for (let i = 0; i < d1; ++i) {
        // Populate buffer with waveform data
        const offset = i * hop_length;
        for (let j = 0; j < frame_length; ++j) {
            inputBuffer[j] = waveform[offset + j];
        }

        if (remove_dc_offset) {
            let sum = 0;
            for (let j = 0; j < frame_length; ++j) {
                sum += inputBuffer[j];
            }
            const mean = sum / frame_length;
            for (let j = 0; j < frame_length; ++j) {
                inputBuffer[j] -= mean;
            }
        }

        if (preemphasis !== null) {
            // Done in reverse to avoid copies and distructive modification
            for (let j = frame_length - 1; j >= 1; --j) {
                inputBuffer[j] -= preemphasis * inputBuffer[j - 1];
            }
            inputBuffer[0] *= 1 - preemphasis;
        }

        for (let j = 0; j < window.length; ++j) {
            inputBuffer[j] *= window[j];
        }

        fft.realTransform(outputBuffer, inputBuffer);

        // compute magnitudes
        const row = new Array(num_frequency_bins);
        for (let j = 0; j < row.length; ++j) {
            const j2 = j << 1;
            row[j] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2;
        }
        magnitudes[i] = row;
    }

    if (power !== null && power !== 2) {
        // slight optimization to not sqrt
        const pow = 2 / power; // we use 2 since we already squared
        for (let i = 0; i < magnitudes.length; ++i) {
            const magnitude = magnitudes[i];
            for (let j = 0; j < magnitude.length; ++j) {
                magnitude[j] **= pow;
            }
        }
    }

    // TODO: What if `mel_filters` is null?
    const num_mel_filters = mel_filters.length;

    // Only here do we create Float32Array
    const mel_spec = new Float32Array(num_mel_filters * d1Max);

    // Perform matrix muliplication:
    // mel_spec = mel_filters @ magnitudes.T
    //  - mel_filters.shape=(80, 201)
    //  - magnitudes.shape=(3000, 201) => - magnitudes.T.shape=(201, 3000)
    //  - mel_spec.shape=(80, 3000)
    const dims = transpose ? [d1Max, num_mel_filters] : [num_mel_filters, d1Max];
    for (let i = 0; i < num_mel_filters; ++i) { // num melfilters (e.g., 80)
        const filter = mel_filters[i];
        for (let j = 0; j < d1; ++j) { // num frames (e.g., 3000)
            const magnitude = magnitudes[j];

            let sum = 0;
            for (let k = 0; k < num_frequency_bins; ++k) { // num frequency bins (e.g., 201)
                sum += filter[k] * magnitude[k];
            }

            mel_spec[
                transpose
                    ? j * num_mel_filters + i
                    : i * d1 + j
            ] = Math.max(mel_floor, sum);
        }
    }

    if (power !== null && log_mel !== null) {
        const o = Math.min(mel_spec.length, d1 * num_mel_filters);
        switch (log_mel) {
            case 'log':
                for (let i = 0; i < o; ++i) {
                    mel_spec[i] = Math.log(mel_spec[i]);
                }
                break;
            case 'log10':
                for (let i = 0; i < o; ++i) {
                    mel_spec[i] = Math.log10(mel_spec[i]);
                }
                break;
            case 'dB':
                if (power === 1.0) {
                    // NOTE: operates in-place
                    amplitude_to_db(mel_spec, reference, min_value, db_range);
                } else if (power === 2.0) {
                    power_to_db(mel_spec, reference, min_value, db_range);
                } else {
                    throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`)
                }
                break;
            default:
                throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`);
        }
    }

    return { data: mel_spec, dims };
}

/**
 * Returns an array containing the specified window.
 * @param {number} window_length The length of the window in samples.
 * @param {string} name The name of the window function.
 * @param {Object} options Additional options.
 * @param {boolean} [options.periodic=true] Whether the window is periodic or symmetric.
 * @param {number} [options.frame_length=null] The length of the analysis frames in samples.
 * Provide a value for `frame_length` if the window is smaller than the frame length, so that it will be zero-padded.
 * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.
 * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`.
 */
function window_function(window_length, name, {
    periodic = true,
    frame_length = null,
    center = true,
} = {}) {
    const length = periodic ? window_length + 1 : window_length;
    let window;
    switch (name) {
        case 'boxcar':
            window = new Float64Array(length).fill(1.0);
            break;
        case 'hann':
        case 'hann_window':
            window = hanning(length);
            break;
        case 'povey':
            window = hanning(length).map(x => Math.pow(x, 0.85));
            break;
        default:
            throw new Error(`Unknown window type ${name}.`);
    }
    if (periodic) {
        window = window.subarray(0, window_length);
    }
    if (frame_length === null) {
        return window;
    }
    if (window_length > frame_length) {
        throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`);
    }

    return window;
}


/***/ }),

/***/ "./src/utils/core.js":
/*!***************************!*\
  !*** ./src/utils/core.js ***!
  \***************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Callable": () => (/* binding */ Callable),
/* harmony export */   "calculateDimensions": () => (/* binding */ calculateDimensions),
/* harmony export */   "calculateReflectOffset": () => (/* binding */ calculateReflectOffset),
/* harmony export */   "dispatchCallback": () => (/* binding */ dispatchCallback),
/* harmony export */   "escapeRegExp": () => (/* binding */ escapeRegExp),
/* harmony export */   "exists": () => (/* binding */ exists),
/* harmony export */   "isIntegralNumber": () => (/* binding */ isIntegralNumber),
/* harmony export */   "isTypedArray": () => (/* binding */ isTypedArray),
/* harmony export */   "mergeArrays": () => (/* binding */ mergeArrays),
/* harmony export */   "pop": () => (/* binding */ pop),
/* harmony export */   "product": () => (/* binding */ product),
/* harmony export */   "reverseDictionary": () => (/* binding */ reverseDictionary)
/* harmony export */ });

/**
 * @file Core utility functions/classes for Transformers.js.
 * 
 * These are only used internally, meaning an end-user shouldn't
 * need to access anything here.
 * 
 * @module utils/core
 */

/**
 * Helper function to dispatch progress callbacks.
 *
 * @param {Function} progress_callback The progress callback function to dispatch.
 * @param {any} data The data to pass to the progress callback function.
 * @returns {void}
 * @private
 */
function dispatchCallback(progress_callback, data) {
    if (progress_callback) progress_callback(data);
}

/**
 * Reverses the keys and values of an object.
 *
 * @param {Object} data The object to reverse.
 * @returns {Object} The reversed object.
 * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
 */
function reverseDictionary(data) {
    // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
    return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));
}

/**
 * Escapes regular expression special characters from a string by replacing them with their escaped counterparts.
 *
 * @param {string} string The string to escape.
 * @returns {string} The escaped string.
 */
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

/**
 * A base class for creating callable objects.
 * 
 * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}
 */
const Callable = /** @type {any} */ (class {
    /**
    * Creates a new instance of the Callable class.
    */
    constructor() {
        /**
         * Creates a closure that delegates to a private method '_call' with the given arguments.
         * @type {any}
         * @param {...any} args Zero or more arguments to pass to the '_call' method.
         * @returns {*} The result of calling the '_call' method.
         */
        let closure = function (...args) {
            return closure._call(...args)
        }
        return Object.setPrototypeOf(closure, new.target.prototype)
    }

    /**
     * This method should be implemented in subclasses to provide the
     * functionality of the callable object.
     *
     * @param {any[]} args
     * @throws {Error} If the subclass does not implement the `_call` method.
     */
    _call(...args) {
        throw Error('Must implement _call method in subclass')
    }
});

/**
 * Check if a value is a typed array.
 * @param {*} val The value to check.
 * @returns {boolean} True if the value is a `TypedArray`, false otherwise.
 * 
 * Adapted from https://stackoverflow.com/a/71091338/13989043
 */
function isTypedArray(val) {
    return val?.prototype?.__proto__?.constructor?.name === 'TypedArray';
}


/**
 * Check if a value is an integer.
 * @param {*} x The value to check.
 * @returns {boolean} True if the value is a string, false otherwise.
 */
function isIntegralNumber(x) {
    return Number.isInteger(x) || typeof x === 'bigint'
}

/**
 * Check if a value is exists.
 * @param {*} x The value to check.
 * @returns {boolean} True if the value exists, false otherwise.
 */
function exists(x) {
    return x !== undefined && x !== null;
}

/**
 * Calculates the dimensions of a nested array.
 *
 * @param {any[]} arr The nested array to calculate dimensions for.
 * @returns {number[]} An array containing the dimensions of the input array.
 */
function calculateDimensions(arr) {
    const dimensions = [];
    let current = arr;
    while (Array.isArray(current)) {
        dimensions.push(current.length);
        current = current[0];
    }
    return dimensions;
}

/**
 * Replicate python's .pop() method for objects.
 * @param {Object} obj The object to pop from.
 * @param {string} key The key to pop.
 * @param {*} defaultValue The default value to return if the key does not exist.
 * @returns {*} The value of the popped key.
 * @throws {Error} If the key does not exist and no default value is provided.
 */
function pop(obj, key, defaultValue = undefined) {
    const value = obj[key];
    if (value !== undefined) {
        delete obj[key];
        return value;
    }
    if (defaultValue === undefined) {
        throw Error(`Key ${key} does not exist in object.`)
    }
    return defaultValue;
}

/**
 * Efficiently merge arrays, creating a new copy.
 * Adapted from https://stackoverflow.com/a/6768642/13989043
 * @param  {Array[]} arrs Arrays to merge.
 * @returns {Array} The merged array.
 */
function mergeArrays(...arrs) {
    return Array.prototype.concat.apply([], arrs);
}

/**
 * Compute the Cartesian product of given arrays
 * @param {...Array} a Arrays to compute the product
 * @returns {Array} Returns the computed Cartesian product as an array
 * @private
 */
function product(...a) {
    // Cartesian product of items
    // Adapted from https://stackoverflow.com/a/43053803
    return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e])));
}

/**
 * Calculates the index offset for a given index and window size.
 * @param {number} i The index.
 * @param {number} w The window size.
 * @returns {number} The index offset.
 */
function calculateReflectOffset(i, w) {
    return Math.abs((i + w) % (2 * w) - w);
}


/***/ }),

/***/ "./src/utils/data-structures.js":
/*!**************************************!*\
  !*** ./src/utils/data-structures.js ***!
  \**************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "CharTrie": () => (/* binding */ CharTrie),
/* harmony export */   "PriorityQueue": () => (/* binding */ PriorityQueue),
/* harmony export */   "TokenLattice": () => (/* binding */ TokenLattice)
/* harmony export */ });

/**
 * @file Custom data structures.
 * 
 * These are only used internally, meaning an end-user shouldn't
 * need to access anything here.
 * 
 * @module utils/data-structures
 */


/**
 * Efficient Heap-based Implementation of a Priority Queue.
 * It uses an array-based binary heap, where the root is at index `0`, and the
 * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively.
 * 
 * Adapted from the following sources:
 * - https://stackoverflow.com/a/42919752/13989043 (original)
 * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)
 */
class PriorityQueue {

    /**
     * Create a new PriorityQueue.
     * @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
     */
    constructor(comparator = (a, b) => a > b) {
        this._heap = [];
        this._comparator = comparator;
    }

    /**
     * The size of the queue
     */
    get size() {
        return this._heap.length;
    }

    /**
     * Check if the queue is empty.
     * @returns {boolean} `true` if the queue is empty, `false` otherwise.
     */
    isEmpty() {
        return this.size === 0;
    }

    /**
     * Return the element with the highest priority in the queue.
     * @returns {any} The highest priority element in the queue.
     */
    peek() {
        return this._heap[0];
    }

    /**
     * Add one or more elements to the queue.
     * @param  {...any} values The values to push into the queue.
     * @returns {number} The new size of the queue.
     */
    push(...values) {
        return this.extend(values);
    }

    /**
     * Add multiple elements to the queue.
     * @param {any[]} values The values to push into the queue.
     * @returns {number} The new size of the queue.
     */
    extend(values) {
        for (const value of values) {
            this._heap.push(value);
            this._siftUp();
        }
        return this.size;
    }

    /**
     * Remove and return the element with the highest priority in the queue.
     * @returns {any} The element with the highest priority in the queue.
     */
    pop() {
        const poppedValue = this.peek();
        const bottom = this.size - 1;
        if (bottom > 0) {
            this._swap(0, bottom);
        }
        this._heap.pop();
        this._siftDown();
        return poppedValue;
    }

    /**
     * Replace the element with the highest priority in the queue with a new value.
     * @param {*} value The new value.
     * @returns {*} The replaced value.
     */
    replace(value) {
        const replacedValue = this.peek();
        this._heap[0] = value;
        this._siftDown();
        return replacedValue;
    }

    /**
     * Compute the index for the parent of the node at index `i`.
     * @param {number} i The index of the node to get the parent of.
     * @returns {number} The index of the parent node.
     * @private
     */
    _parent(i) {
        return ((i + 1) >>> 1) - 1;
    }

    /**
     * Compute the index for the left child of the node at index `i`.
     * @param {number} i The index of the node to get the left child of.
     * @returns {number} The index of the left child.
     * @private
     */
    _left(i) {
        return (i << 1) + 1;
    }

    /**
     * Compute the index for the right child of the node at index `i`.
     * @param {number} i The index of the node to get the right child of.
     * @returns {number} The index of the right child.
     * @private
     */
    _right(i) {
        return (i + 1) << 1;
    }

    /**
     * Check if the element at index `i` is greater than the element at index `j`.
     * @param {number} i The index of the first element to compare.
     * @param {number} j The index of the second element to compare.
     * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
     * @private
     */
    _greater(i, j) {
        return this._comparator(this._heap[i], this._heap[j]);
    }

    /**
     * Swap the elements at indices `i` and `j`.
     * @param {number} i The index of the first element to swap.
     * @param {number} j The index of the second element to swap.
     * @private
     */
    _swap(i, j) {
        const temp = this._heap[i];
        this._heap[i] = this._heap[j];
        this._heap[j] = temp;
    }

    /**
     * Maintain the heap property by updating positions in the heap,
     * starting at the last element and moving up the heap.
     * @private
     */
    _siftUp() {
        let node = this.size - 1;
        while (node > 0 && this._greater(node, this._parent(node))) {
            this._swap(node, this._parent(node));
            node = this._parent(node);
        }
    }
    /**
     * Maintain the heap property by updating positions in the heap,
     * starting at the first element and moving down the heap.
     * @private
     */
    _siftDown() {
        let node = 0;
        while (
            (this._left(node) < this.size && this._greater(this._left(node), node)) ||
            (this._right(node) < this.size && this._greater(this._right(node), node))
        ) {
            const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node)))
                ? this._right(node)
                : this._left(node);
            this._swap(node, maxChild);
            node = maxChild;
        }
    }
}

/**
 * A trie structure to efficiently store and search for strings.
 */
class CharTrie {
    constructor() {
        this.root = CharTrieNode.default();
    }

    /**
     * Adds one or more `texts` to the trie.
     * @param {string[]} texts The strings to add to the trie.
     */
    extend(texts) {
        for (let text of texts) {
            this.push(text);
        }
    }

    /**
     * Adds text to the trie.
     * @param {string} text The string to add to the trie.
     */
    push(text) {
        let node = this.root;
        for (let ch of text) {
            let child = node.children.get(ch);
            if (child === undefined) {
                child = CharTrieNode.default();
                node.children.set(ch, child);
            }
            node = child;
        }
        node.isLeaf = true;
    }

    /**
     * Searches the trie for all strings with a common prefix of `text`.
     * @param {string} text The common prefix to search for.
     * @yields {string} Each string in the trie that has `text` as a prefix.
     */
    *commonPrefixSearch(text) {
        let node = this.root;
        let prefix = "";
        for (let i = 0; i < text.length && node !== undefined; ++i) {
            const ch = text[i];
            prefix += ch;
            node = node.children.get(ch);
            if (node !== undefined && node.isLeaf) {
                yield prefix;
            }
        }
    }
}

/**
 * Represents a node in a character trie.
 */
class CharTrieNode {
    /**
     * Create a new CharTrieNode.
     * @param {boolean} isLeaf Whether the node is a leaf node or not.
     * @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
     */
    constructor(isLeaf, children) {
        this.isLeaf = isLeaf;
        this.children = children;
    }

    /**
     * Returns a new `CharTrieNode` instance with default values.
     * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
     */
    static default() {
        return new CharTrieNode(false, new Map());
    }
}

/**
 * A lattice data structure to be used for tokenization.
 */
class TokenLattice {
    /**
     * Creates a new TokenLattice instance.
     *
     * @param {string} sentence The input sentence to be tokenized.
     * @param {number} bosTokenId The beginning-of-sequence token ID.
     * @param {number} eosTokenId The end-of-sequence token ID.
     */
    constructor(sentence, bosTokenId, eosTokenId) {
        this.sentence = sentence;
        this.len = sentence.length;
        this.bosTokenId = bosTokenId;
        this.eosTokenId = eosTokenId;
        this.nodes = [];
        this.beginNodes = Array.from({ length: this.len + 1 }, () => []);
        this.endNodes = Array.from({ length: this.len + 1 }, () => []);

        const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);
        const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);
        this.nodes.push(bos.clone());
        this.nodes.push(eos.clone());
        this.beginNodes[this.len].push(eos);
        this.endNodes[0].push(bos);
    }

    /**
     * Inserts a new token node into the token lattice.
     *
     * @param {number} pos The starting position of the token.
     * @param {number} length The length of the token.
     * @param {number} score The score of the token.
     * @param {number} tokenId The token ID of the token.
     */
    insert(pos, length, score, tokenId) {
        const nodeId = this.nodes.length;
        const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);
        this.beginNodes[pos].push(node);
        this.endNodes[pos + length].push(node);
        this.nodes.push(node);
    }

    /**
     * Implements the Viterbi algorithm to compute the most likely sequence of tokens.
     *
     * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
     */
    viterbi() {
        const len = this.len;
        let pos = 0;
        while (pos <= len) {
            if (this.beginNodes[pos].length == 0) {
                return [];
            }
            for (let rnode of this.beginNodes[pos]) {
                rnode.prev = null;
                let bestScore = 0.0;
                let bestNode = null;
                for (let lnode of this.endNodes[pos]) {
                    const score = lnode.backtraceScore + rnode.score;
                    if (bestNode === null || score > bestScore) {
                        bestNode = lnode.clone();
                        bestScore = score;
                    }
                }

                if (bestNode !== null) {
                    rnode.prev = bestNode;
                    rnode.backtraceScore = bestScore;
                } else {
                    return [];
                }
            }
            ++pos;
        }

        const results = [];
        const root = this.beginNodes[len][0];
        const prev = root.prev;
        if (prev === null) {
            return [];
        }

        let node = prev.clone();
        while (node.prev !== null) {
            results.push(node.clone());
            const n = node.clone();
            node = n.prev.clone();
        }

        results.reverse();
        return results;
    }

    /**
     * @param {TokenLatticeNode} node
     * @returns {string} The array of nodes representing the most likely sequence of tokens.
     */
    piece(node) {
        return this.sentence.slice(node.pos, node.pos + node.length);
    }

    /**
     * @returns {Array} The array of nodes representing the most likely sequence of tokens.
     */
    tokens() {
        const nodes = this.viterbi();
        return nodes.map(x => this.piece(x));
    }

    /**
     * @returns {Array} The array of nodes representing the most likely sequence of tokens.
     */
    tokenIds() {
        const nodes = this.viterbi();
        return nodes.map(x => x.tokenId);
    }
}
class TokenLatticeNode {
    /**
     * Represents a node in a token lattice for a given sentence.
     * @param {number} tokenId The ID of the token associated with this node.
     * @param {number} nodeId The ID of this node.
     * @param {number} pos The starting position of the token in the sentence.
     * @param {number} length The length of the token.
     * @param {number} score The score associated with the token.
     */
    constructor(tokenId, nodeId, pos, length, score) {
        this.tokenId = tokenId;
        this.nodeId = nodeId;
        this.pos = pos;
        this.length = length;
        this.score = score;
        this.prev = null;
        this.backtraceScore = 0.0;
    }

    /**
     * Returns a clone of this node.
     * @returns {TokenLatticeNode} A clone of this node.
     */
    clone() {
        const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);
        n.prev = this.prev;
        n.backtraceScore = this.backtraceScore;
        return n;
    }
}


/***/ }),

/***/ "./src/utils/generation.js":
/*!*********************************!*\
  !*** ./src/utils/generation.js ***!
  \*********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ForceTokensLogitsProcessor": () => (/* binding */ ForceTokensLogitsProcessor),
/* harmony export */   "ForcedBOSTokenLogitsProcessor": () => (/* binding */ ForcedBOSTokenLogitsProcessor),
/* harmony export */   "ForcedEOSTokenLogitsProcessor": () => (/* binding */ ForcedEOSTokenLogitsProcessor),
/* harmony export */   "GenerationConfig": () => (/* binding */ GenerationConfig),
/* harmony export */   "LogitsProcessor": () => (/* binding */ LogitsProcessor),
/* harmony export */   "LogitsProcessorList": () => (/* binding */ LogitsProcessorList),
/* harmony export */   "MinLengthLogitsProcessor": () => (/* binding */ MinLengthLogitsProcessor),
/* harmony export */   "MinNewTokensLengthLogitsProcessor": () => (/* binding */ MinNewTokensLengthLogitsProcessor),
/* harmony export */   "NoBadWordsLogitsProcessor": () => (/* binding */ NoBadWordsLogitsProcessor),
/* harmony export */   "NoRepeatNGramLogitsProcessor": () => (/* binding */ NoRepeatNGramLogitsProcessor),
/* harmony export */   "RepetitionPenaltyLogitsProcessor": () => (/* binding */ RepetitionPenaltyLogitsProcessor),
/* harmony export */   "Sampler": () => (/* binding */ Sampler),
/* harmony export */   "SuppressTokensAtBeginLogitsProcessor": () => (/* binding */ SuppressTokensAtBeginLogitsProcessor),
/* harmony export */   "WhisperTimeStampLogitsProcessor": () => (/* binding */ WhisperTimeStampLogitsProcessor)
/* harmony export */ });
/* harmony import */ var _tensor_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tensor.js */ "./src/utils/tensor.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./core.js */ "./src/utils/core.js");
/* harmony import */ var _maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./maths.js */ "./src/utils/maths.js");

/**
 * @file Classes, functions, and utilities for generation.
 * 
 * @todo Describe how to create a custom `GenerationConfig`.
 * 
 * @module utils/generation
 */




/**
 * A class representing a list of logits processors. A logits processor is a function that modifies the logits
 * output of a language model. This class provides methods for adding new processors and applying all processors to a
 * batch of logits.
 *
 * @extends Callable
 */
class LogitsProcessorList extends _core_js__WEBPACK_IMPORTED_MODULE_1__.Callable {
    /**
     * Constructs a new instance of `LogitsProcessorList`.
     */
    constructor() {
        super();
        this.processors = [];
    }

    /**
     * Adds a new logits processor to the list.
     *
     * @param {LogitsProcessor} item The logits processor function to add.
     */
    push(item) {
        this.processors.push(item);
    }

    /**
     * Adds multiple logits processors to the list.
     *
     * @param {LogitsProcessor[]} items The logits processor functions to add.
     */
    extend(items) {
        this.processors.push(...items);
    }

    /**
     * Applies all logits processors in the list to a batch of logits, modifying them in-place.
     *
     * @param {number[]} input_ids The input IDs for the language model.
     * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single
     *                                                input sequence in the batch.
     */
    _call(input_ids, batchedLogits) {
        // NOTE: This is different from the Python code, since vanilla JS does not support vectorized operations. 
        // As a result, we apply each processor to each item in the batch.
        for (let logits of batchedLogits) {
            // Modifies logits inplace
            this.processors.forEach(
                func => func(input_ids, logits)
            )
        }
    }

    [Symbol.iterator]() {
        return this.processors.values();
    }
}

/**
 * Base class for processing logits.
 * @extends Callable
 */
class LogitsProcessor extends _core_js__WEBPACK_IMPORTED_MODULE_1__.Callable {
    /**
     * Apply the processor to the input logits.
     *
     * @abstract
     * @param {Array} input_ids The input ids.
     * @param {Tensor} logits The logits to process.
     * @throws {Error} Throws an error if `_call` is not implemented in the subclass.
     */
    _call(input_ids, logits) {
        throw Error("`_call` should be implemented in a subclass")
    }
}

/**
 * A logits processor that forces a specific token to be generated by the decoder.
 * 
 * @extends LogitsProcessor
 */
class ForceTokensLogitsProcessor extends LogitsProcessor {
    /**
     * Constructs a new instance of `ForceTokensLogitsProcessor`.
     * 
     * @param {Array} forced_decoder_ids The ids of tokens that should be forced.
     */
    constructor(forced_decoder_ids) {
        super();
        this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []);
    }

    /**
     * Apply the processor to the input logits.
     *
     * @param {Array} input_ids The input ids.
     * @param {Tensor} logits The logits to process.
     * @returns {Tensor} The processed logits.
     */
    _call(input_ids, logits) {
        let map = this.force_token_map[input_ids.length];
        if ((0,_core_js__WEBPACK_IMPORTED_MODULE_1__.exists)(map)) { // There exists a mapping
            logits.data.fill(-Infinity)
            logits.data[map] = 0;
        }
        return logits;
    }
}

/**
 * A LogitsProcessor that forces a BOS token at the beginning of the generated sequence.
 * @extends LogitsProcessor
 */
class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {
    /**
     * Create a ForcedBOSTokenLogitsProcessor.
     * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.
     */
    constructor(bos_token_id) {
        super();
        this.bos_token_id = bos_token_id;
    }

    /**
     * Apply the BOS token forcing to the logits.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The logits with BOS token forcing.
     */
    _call(input_ids, logits) {
        if (input_ids.length === 1) {
            logits.data.fill(-Infinity)
            logits.data[this.bos_token_id] = 0;
        }
        return logits;
    }
}

/**
 * A logits processor that forces end-of-sequence token probability to 1.
 * 
 * @extends LogitsProcessor
 */
class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {
    /**
     * Create a ForcedEOSTokenLogitsProcessor.
     * @param {number} max_length Max length of the sequence.
     * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced.
     */
    constructor(max_length, forced_eos_token_id) {
        super();
        this.max_length = max_length;
        this.forced_eos_token_id = forced_eos_token_id;
    }

    /**
     * Apply the processor to input_ids and logits.
     * 
     * @param {number[]} input_ids The input ids.
     * @param {Tensor} logits The logits tensor.
     */
    _call(input_ids, logits) {
        // console.log('call ForcedEOSTokenLogitsProcessor')
        // TODO
    }
}

/**
 * A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts
 * generating using `begin_index` tokens. This should ensure that the tokens defined by
 * `begin_suppress_tokens` at not sampled at the begining of the generation.
 * @extends LogitsProcessor
 */
class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {
    /**
     * Create a SuppressTokensAtBeginLogitsProcessor.
     * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.
     * @param {number} begin_index The number of tokens to generate before suppressing tokens.
     */
    constructor(begin_suppress_tokens, begin_index) {
        super();
        this.begin_suppress_tokens = begin_suppress_tokens;
        this.begin_index = begin_index;
    }

    /**
     * Apply the BOS token forcing to the logits.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The logits with BOS token forcing.
     */
    _call(input_ids, logits) {
        if (input_ids.length === this.begin_index) {
            for (let token_id of this.begin_suppress_tokens) {
                logits.data[token_id] = -Infinity;
            }
        }
        return logits;
    }
}

/**
 * A LogitsProcessor that handles adding timestamps to generated text.
 * @extends LogitsProcessor
 */
class WhisperTimeStampLogitsProcessor extends LogitsProcessor {
    /**
     * Constructs a new WhisperTimeStampLogitsProcessor.
     * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model.
     * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token.
     * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp.
     * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp.
     * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear.
     */
    constructor(generate_config) {
        super();
        this.eos_token_id = generate_config.eos_token_id;
        this.no_timestamps_token_id = generate_config.no_timestamps_token_id;
        this.timestamp_begin = this.no_timestamps_token_id + 1;

        this.begin_index = (generate_config.forced_decoder_ids || []).length + 2;
        if (generate_config.forced_decoder_ids.slice(-1)[0][1] === this.no_timestamps_token_id) {
            this.begin_index -= 1;
        }
        this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index;

    }

    /**
     * Modify the logits to handle timestamp tokens.
     * @param {Array} input_ids The input sequence of tokens.
     * @param {Tensor} logits The logits output by the model.
     * @returns {Tensor} The modified logits.
     */
    _call(input_ids, logits) {
        const logitsData = /** @type {Float32Array} */(logits.data);

        // suppress <|notimestamps|> which is handled by without_timestamps
        logitsData[this.no_timestamps_token_id] = -Infinity;

        if (input_ids.length === this.begin_index - 1) {
            logitsData.fill(-Infinity);
            logitsData[this.timestamp_begin] = 0;
            return logits;
        }

        // timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly
        const seq = input_ids.slice(this.begin_index);
        const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin;
        const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin;

        if (last_was_timestamp) {
            if (penultimate_was_timestamp) { // has to be non-timestamp
                logitsData.subarray(this.timestamp_begin).fill(-Infinity);
            } else { // cannot be normal text tokens
                logitsData.subarray(0, this.eos_token_id).fill(-Infinity);
            }
        }

        // apply the `max_initial_timestamp` option
        if (input_ids.length === this.begin_index && this.max_initial_timestamp_index !== null) {
            const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index;
            logitsData.subarray(last_allowed + 1).fill(-Infinity);
        }

        // if sum of probability over timestamps is above any other token, sample timestamp
        const logprobs = (0,_maths_js__WEBPACK_IMPORTED_MODULE_2__.log_softmax)(logitsData);
        const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b));
        const max_text_token_logprob = (0,_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logprobs.subarray(0, this.timestamp_begin))[0];

        if (timestamp_logprob > max_text_token_logprob) {
            logitsData.subarray(0, this.timestamp_begin).fill(-Infinity);
        }

        return logits;
    }
}

/**
 * A logits processor that disallows ngrams of a certain size to be repeated.
 * 
 * @extends LogitsProcessor
 */
class NoRepeatNGramLogitsProcessor extends LogitsProcessor {
    /**
     * Create a NoRepeatNGramLogitsProcessor.
     * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.
     */
    constructor(no_repeat_ngram_size) {
        super();
        this.no_repeat_ngram_size = no_repeat_ngram_size;
    }

    /**
     * Generate n-grams from a sequence of token ids.
     * @param {number[]} prevInputIds List of previous input ids
     * @returns {Map<string, number[]>} Map of generated n-grams
     */
    getNgrams(prevInputIds) {
        const curLen = prevInputIds.length;

        /**@type {number[][]} */
        const ngrams = [];
        for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) {
            const ngram = [];
            for (let k = 0; k < this.no_repeat_ngram_size; ++k) {
                ngram.push(prevInputIds[j + k]);
            }
            ngrams.push(ngram);
        }

        /** @type {Map<string, number[]>} */
        const generatedNgram = new Map();
        for (const ngram of ngrams) {
            const prevNgram = ngram.slice(0, ngram.length - 1);
            const prevNgramKey = JSON.stringify(prevNgram);
            const prevNgramValue = generatedNgram.get(prevNgramKey) ?? [];
            prevNgramValue.push(ngram[ngram.length - 1]);
            generatedNgram.set(prevNgramKey, prevNgramValue);
        }
        return generatedNgram;
    }

    /**
     * Generate n-grams from a sequence of token ids.
     * @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
     * @param {number[]} prevInputIds List of previous input ids
     * @returns {number[]} Map of generated n-grams
     */
    getGeneratedNgrams(bannedNgrams, prevInputIds) {
        const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length);
        const banned = bannedNgrams.get(JSON.stringify(ngramIdx)) ?? [];
        return banned;
    }

    /**
     * Calculate banned n-gram tokens
     * @param {number[]} prevInputIds List of previous input ids
     * @returns {number[]} Map of generated n-grams
     */
    calcBannedNgramTokens(prevInputIds) {
        const bannedTokens = [];
        if (prevInputIds.length + 1 < this.no_repeat_ngram_size) {
            // return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet
            return bannedTokens;

        } else {
            const generatedNgrams = this.getNgrams(prevInputIds);
            const bannedTokens = this.getGeneratedNgrams(generatedNgrams, prevInputIds);
            return bannedTokens;
        }
    }

    /**
     * Apply the no-repeat-ngram processor to the logits.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The logits with no-repeat-ngram processing.
     */
    _call(input_ids, logits) {
        const bannedTokens = this.calcBannedNgramTokens(input_ids);

        for (const token of bannedTokens) {
            logits.data[token] = -Infinity;
        }
        return logits;
    }
}

/**
 * A logits processor that penalises repeated output tokens.
 * 
 * @extends LogitsProcessor
 */
class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {
    /**
     * Create a RepetitionPenaltyLogitsProcessor.
     * @param {number} penalty The penalty to apply for repeated tokens.
     */
    constructor(penalty) {
        super();
        this.penalty = penalty;
    }

    /**
     * Apply the repetition penalty to the logits.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The logits with repetition penalty processing.
     */
    _call(input_ids, logits) {
        // Modify the logits corresponding to each element in `input_ids`.
        // As a consequence, the logits corresponding to tokens that appear
        // many times in the output will be penalised more.
        for (const input_id of input_ids) {
            if (logits.data[input_id] < 0) {
                logits.data[input_id] *= this.penalty;
            } else {
                logits.data[input_id] /= this.penalty;
            }
        }
        return logits
    }
}

/**
 * A logits processor that enforces a minimum number of tokens.
 * 
 * @extends LogitsProcessor
 */
class MinLengthLogitsProcessor extends LogitsProcessor {
    /**
     * Create a MinLengthLogitsProcessor.
     * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.
     * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
     */
    constructor(min_length, eos_token_id) {
        super();
        this.min_length = min_length;
        this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
    }

    /**
     * Apply logit processor.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The processed logits.
     */
    _call(input_ids, logits) {
        if (input_ids.length < this.min_length) {
            for (const eos_token of this.eos_token_id) {
                logits.data[eos_token] = -Infinity;
            }
        }

        return logits
    }
}

/**
 * A logits processor that enforces a minimum number of new tokens.
 * 
 * @extends LogitsProcessor
 */
class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {
    /**
     * Create a MinNewTokensLengthLogitsProcessor.
     * @param {number} prompt_length_to_skip The input tokens length.
     * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.
     * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
     */
    constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) {
        super();
        this.prompt_length_to_skip = prompt_length_to_skip;
        this.min_new_tokens = min_new_tokens;
        this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
    }

    /**
     * Apply logit processor.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The processed logits.
     */
    _call(input_ids, logits) {
        const new_tokens_length = input_ids.length - this.prompt_length_to_skip;
        if (new_tokens_length < this.min_new_tokens) {
            for (const eos_token of this.eos_token_id) {
                logits.data[eos_token] = -Infinity;
            }
        }

        return logits
    }
}

class NoBadWordsLogitsProcessor extends LogitsProcessor {
    /**
     * Create a `NoBadWordsLogitsProcessor`.
     * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.
     * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
     */
    constructor(bad_words_ids, eos_token_id) {
        super();
        this.bad_words_ids = bad_words_ids;
        this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
    }

    /**
     * Apply logit processor.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The processed logits.
     */
    _call(input_ids, logits) {

        for (const bad_word_ids of this.bad_words_ids) {
            // Whether to modify the logits of the last token in the bad word id sequence
            let mark = true;

            // For each bad word in the list, if the current sequence of input ids ends with this sequence (excluding the last),
            // then we set the logits of the last bad word id to -Infinity.
            for (let i = 1; i <= bad_word_ids.length - 1 && bad_word_ids.length < input_ids.length; ++i) {

                if (bad_word_ids.at(-i - 1) !== input_ids.at(-i)) {
                    // We have found a mismatch
                    mark = false;
                    break;
                }
            }
            if (mark) {
                logits.data[bad_word_ids.at(-1)] = -Infinity;
            }
        }

        return logits
    }
}

/**
 * @typedef {Object} GenerationConfigType The default configuration parameters.
 * @property {number} [max_length=20] The maximum length the generated tokens can have. Corresponds to the length of the input prompt + `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set.
 * @property {number} [max_new_tokens=null] The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
 * @property {number} [min_length=0] The minimum length of the sequence to be generated. Corresponds to the length of the input prompt + `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set.
 * @property {number} [min_new_tokens=null] The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
 * @property {boolean|"never"} [early_stopping=false] Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
 * - `true`, where the generation stops as soon as there are `num_beams` complete candidates;
 * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates;
 * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).
 * @property {number} [max_time=null] The maximum amount of time you allow the computation to run for in seconds. Generation will still finish the current pass after allocated time has been passed.
 *
 * @property {boolean} [do_sample=false] Whether or not to use sampling; use greedy decoding otherwise.
 * @property {number} [num_beams=1] Number of beams for beam search. 1 means no beam search.
 * @property {number} [num_beam_groups=1] Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
 * @property {number} [penalty_alpha=null] The values balance the model confidence and the degeneration penalty in contrastive search decoding.
 * @property {boolean} [use_cache=true] Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.
 *
 * @property {number} [temperature=1.0] The value used to modulate the next token probabilities.
 * @property {number} [top_k=50] The number of highest probability vocabulary tokens to keep for top-k-filtering.
 * @property {number} [top_p=1.0] If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.
 * @property {number} [typical_p=1.0] Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.
 * @property {number} [epsilon_cutoff=0.0] If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
 * @property {number} [eta_cutoff=0.0] Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
 * @property {number} [diversity_penalty=0.0] This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
 * @property {number} [repetition_penalty=1.0] The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
 * @property {number} [encoder_repetition_penalty=1.0] The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
 * @property {number} [length_penalty=1.0] Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.
 * @property {number} [no_repeat_ngram_size=0] If set to int > 0, all ngrams of that size can only occur once.
 * @property {number[][]} [bad_words_ids=null] List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`.
 * @property {number[][]|number[][][]} [force_words_ids=null] List of token ids that must be generated. If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.
 * @property {boolean} [renormalize_logits=false] Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.
 * @property {Object[]} [constraints=null] Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.
 * 
 * @property {number} [forced_bos_token_id=null] The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for multilingual models like mBART where the first generated token needs to be the target language token.
 * @property {number|number[]} [forced_eos_token_id=null] The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a list to set multiple *end-of-sequence* tokens.
 * @property {boolean} [remove_invalid_values=false] Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.
 * @property {number[]} [exponential_decay_length_penalty=null] This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay.
 * @property {number[]} [suppress_tokens=null] A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
 * @property {number[]} [begin_suppress_tokens=null] A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
 * @property {number[][]} [forced_decoder_ids=null] A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token of index 123.
 * 
 * @property {number} [num_return_sequences=1] The number of independently computed returned sequences for each element in the batch.
 * @property {boolean} [output_attentions=false] Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
 * @property {boolean} [output_hidden_states=false] Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
 * @property {boolean} [output_scores=false] Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
 * @property {boolean} [return_dict_in_generate=false] Whether or not to return a `ModelOutput` instead of a plain tuple.
 * 
 * @property {number} [pad_token_id=null] The id of the *padding* token.
 * @property {number} [bos_token_id=null] The id of the *beginning-of-sequence* token.
 * @property {number|number[]} [eos_token_id=null] The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
 * 
 * @property {number} [encoder_no_repeat_ngram_size=0] If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.
 * @property {number} [decoder_start_token_id=null] If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
 * 
 * @property {Object} [generation_kwargs={}] Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not present in `generate`'s signature will be used in the model forward pass.
 */

/**
 * Class that holds a configuration for a generation task.
 * @type {new (kwargs?: GenerationConfigType) => GenerationConfigType}
 */
const GenerationConfig = /** @type {any} */ (class {

    /**
     * Create a new GenerationConfig object.
     * @param {GenerationConfigType} kwargs 
     */
    constructor(kwargs = {}) {
        // Parameters that control the length of the output
        this.max_length = kwargs.max_length ?? 20;
        this.max_new_tokens = kwargs.max_new_tokens ?? null;
        this.min_length = kwargs.min_length ?? 0;
        this.min_new_tokens = kwargs.min_new_tokens ?? null;
        this.early_stopping = kwargs.early_stopping ?? false;
        this.max_time = kwargs.max_time ?? null;

        // Parameters that control the generation strategy used
        this.do_sample = kwargs.do_sample ?? false;
        this.num_beams = kwargs.num_beams ?? 1;
        this.num_beam_groups = kwargs.num_beam_groups ?? 1;
        this.penalty_alpha = kwargs.penalty_alpha ?? null;
        this.use_cache = kwargs.use_cache ?? true;

        // Parameters for manipulation of the model output logits
        this.temperature = kwargs.temperature ?? 1.0;
        this.top_k = kwargs.top_k ?? 50;
        this.top_p = kwargs.top_p ?? 1.0;
        this.typical_p = kwargs.typical_p ?? 1.0;
        this.epsilon_cutoff = kwargs.epsilon_cutoff ?? 0.0;
        this.eta_cutoff = kwargs.eta_cutoff ?? 0.0;
        this.diversity_penalty = kwargs.diversity_penalty ?? 0.0;
        this.repetition_penalty = kwargs.repetition_penalty ?? 1.0;
        this.encoder_repetition_penalty = kwargs.encoder_repetition_penalty ?? 1.0;
        this.length_penalty = kwargs.length_penalty ?? 1.0;
        this.no_repeat_ngram_size = kwargs.no_repeat_ngram_size ?? 0;
        this.bad_words_ids = kwargs.bad_words_ids ?? null;
        this.force_words_ids = kwargs.force_words_ids ?? null;
        this.renormalize_logits = kwargs.renormalize_logits ?? false;
        this.constraints = kwargs.constraints ?? null;
        this.forced_bos_token_id = kwargs.forced_bos_token_id ?? null;
        this.forced_eos_token_id = kwargs.forced_eos_token_id ?? null;
        this.remove_invalid_values = kwargs.remove_invalid_values ?? false;
        this.exponential_decay_length_penalty = kwargs.exponential_decay_length_penalty ?? null;
        this.suppress_tokens = kwargs.suppress_tokens ?? null;
        this.begin_suppress_tokens = kwargs.begin_suppress_tokens ?? null;
        this.forced_decoder_ids = kwargs.forced_decoder_ids ?? null;

        // Parameters that define the output variables of `generate`
        this.num_return_sequences = kwargs.num_return_sequences ?? 1;
        this.output_attentions = kwargs.output_attentions ?? false;
        this.output_hidden_states = kwargs.output_hidden_states ?? false;
        this.output_scores = kwargs.output_scores ?? false;
        this.return_dict_in_generate = kwargs.return_dict_in_generate ?? false;

        // Special tokens that can be used at generation time
        this.pad_token_id = kwargs.pad_token_id ?? null;
        this.bos_token_id = kwargs.bos_token_id ?? null;
        this.eos_token_id = kwargs.eos_token_id ?? null;

        // Generation parameters exclusive to encoder-decoder models
        this.encoder_no_repeat_ngram_size = kwargs.encoder_no_repeat_ngram_size ?? 0;
        this.decoder_start_token_id = kwargs.decoder_start_token_id ?? null;

        // Wild card
        this.generation_kwargs = kwargs.generation_kwargs ?? {};
    }
});

/**
 * Sampler is a base class for all sampling methods used for text generation.
 */
class Sampler extends _core_js__WEBPACK_IMPORTED_MODULE_1__.Callable {
    /**
     * Creates a new Sampler object with the specified generation config.
     * @param {GenerationConfigType} generation_config The generation config.
     */
    constructor(generation_config) {
        super();
        this.generation_config = generation_config;
    }

    /**
     * Executes the sampler, using the specified logits.
     * @param {Tensor} logits
     * @param {number} index
     * @returns {void}
     */
    _call(logits, index = -1) {
        // Sample from logits, of dims [batch, sequence_length, vocab_size].
        // If index is specified, sample from [batch, index, vocab_size].
        return this.sample(logits, index);
    }

    /**
     * Abstract method for sampling the logits.
     * @param {Tensor} logits
     * @param {number} index
     * @throws {Error}
     */
    sample(logits, index) {
        throw Error("sample should be implemented in subclasses.")
    }

    /**
     * Returns the specified logits as an array, with temperature applied.
     * @param {Tensor} logits
     * @param {number} index
     * @returns {Float32Array}
     */
    getLogits(logits, index) {
        let vocabSize = logits.dims.at(-1);

        let logs = /** @type {Float32Array} */(logits.data);

        if (index === -1) {
            logs = logs.slice(-vocabSize);
        } else {
            let startIndex = index * vocabSize;
            logs = logs.slice(startIndex, startIndex + vocabSize);
        }

        // add temperature
        if (this.generation_config.temperature > 0) {
            logs = logs.map(x => x / this.generation_config.temperature)
        }
        return logs;
    }

    /**
     * Selects an item randomly based on the specified probabilities.
     * @param {Array} probabilities An array of probabilities to use for selection.
     * @returns {number} The index of the selected item.
     */
    randomSelect(probabilities) {
        // Return index of chosen item
        let sumProbabilities = probabilities.reduce((acc, curr) => acc + curr, 0);

        let r = Math.random() * sumProbabilities;
        for (let i = 0; i < probabilities.length; ++i) {
            r -= probabilities[i];
            if (r <= 0) {
                return i;
            }
        }
        return 0; // return first (most probable) as a fallback
    }

    /**
     * Returns a Sampler object based on the specified options.
     * @param {GenerationConfigType} generation_config An object containing options for the sampler.
     * @returns {Sampler} A Sampler object.
     */
    static getSampler(generation_config) {
        // - *greedy decoding*: `num_beams=1` and `do_sample=False`
        // - *contrastive search*: `penalty_alpha>0` and `top_k>1`
        // - *multinomial sampling*: `num_beams=1` and `do_sample=True`
        // - *beam-search decoding*: `num_beams>1` and `do_sample=False`
        // - *beam-search multinomial sampling*: `num_beams>1` and `do_sample=True`
        // - *diverse beam-search decoding*: `num_beams>1` and `num_beam_groups>1`
        // - *constrained beam-search decoding*: `constraints!=None` or `force_words_ids!=None`

        // NOTE: beam search is implemented directly into the generation function
        if (generation_config.do_sample) {
            return new MultinomialSampler(generation_config);

        } else if (generation_config.num_beams > 1) {
            return new BeamSearchSampler(generation_config);

        } else {
            if (generation_config.num_return_sequences > 1) {
                throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`)
            }
            return new GreedySampler(generation_config);
        }
    }
}

/**
 * Class representing a Greedy Sampler.
 * @extends Sampler
 */
class GreedySampler extends Sampler {
    /**
     * Sample the maximum probability of a given logits tensor.
     * @param {Tensor} logits
     * @param {number} [index=-1]
     * @returns {Array} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search).
     */
    sample(logits, index = -1) {
        // NOTE: no need to do log_softmax here since we only take the maximum
        let logs = this.getLogits(logits, index);
        let argmax = (0,_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logs)[1];

        // Note: score is meaningless in this context, since we are performing
        // greedy search (p = 1 => log(p) = 0)
        return [
            [argmax, 0]
        ];
    }
}

/**
 * Class representing a MultinomialSampler.
 * @extends Sampler
 */
class MultinomialSampler extends Sampler {

    /**
     * Sample from the logits.
     * @param {Tensor} logits
     * @param {number} index
     * @returns {Array}
     */
    sample(logits, index = -1) {
        let k = logits.dims.at(-1); // defaults to vocab size
        if (this.generation_config.top_k > 0) {
            k = Math.min(this.generation_config.top_k, k);
        }

        // Get logits of nth token
        const logs = this.getLogits(logits, index);

        // Get top k tokens
        const topLogits = (0,_maths_js__WEBPACK_IMPORTED_MODULE_2__.getTopItems)(logs, k);

        // Compute softmax over logits
        const probabilities = (0,_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(topLogits.map(x => x[1]));

        return Array.from({ length: this.generation_config.num_beams }, () => {
            const sampledIndex = this.randomSelect(probabilities);
            return [
                topLogits[sampledIndex][0], // token id
                Math.log(probabilities[sampledIndex]), // score
            ];
        });
    }
}


/**
 * Class representing a BeamSearchSampler.
 * @extends Sampler
 */
class BeamSearchSampler extends Sampler {

    /**
     * Sample from the logits.
     * @param {Tensor} logits
     * @param {number} index
     * @returns {Array}
     */
    sample(logits, index = -1) {
        let k = logits.dims.at(-1); // defaults to vocab size
        if (this.generation_config.top_k > 0) {
            k = Math.min(this.generation_config.top_k, k);
        }

        // Get logits of nth token
        const logs = this.getLogits(logits, index);

        // Get top k tokens
        const topLogits = (0,_maths_js__WEBPACK_IMPORTED_MODULE_2__.getTopItems)(logs, k);

        // Compute softmax over logits
        const probabilities = (0,_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(topLogits.map(x => x[1]));

        return Array.from({ length: this.generation_config.num_beams }, (_, i) => {
            return [
                topLogits[i][0], // token id
                Math.log(probabilities[i]), // score
            ];
        });
    }
}


/***/ }),

/***/ "./src/utils/hub.js":
/*!**************************!*\
  !*** ./src/utils/hub.js ***!
  \**************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "getFile": () => (/* binding */ getFile),
/* harmony export */   "getModelFile": () => (/* binding */ getModelFile),
/* harmony export */   "getModelJSON": () => (/* binding */ getModelJSON)
/* harmony export */ });
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "?7a2c");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! path */ "?a42a");
/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../env.js */ "./src/env.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./core.js */ "./src/utils/core.js");

/**
 * @file Utility functions to interact with the Hugging Face Hub (https://huggingface.co/models)
 * 
 * @module utils/hub
 */







/**
 * @typedef {Object} PretrainedOptions Options for loading a pretrained model.     
 * @property {boolean?} [quantized=true] Whether to load the 8-bit quantized version of the model (only applicable when loading model files).
 * @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates.
 * @property {Object} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:
 * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).
 * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.
 * @property {string} [cache_dir=null] Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.
 * @property {boolean} [local_files_only=false] Whether or not to only look at local files (e.g., not try downloading the model).
 * @property {string} [revision='main'] The specific model version to use. It can be a branch name, a tag name, or a commit id,
 * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
 * NOTE: This setting is ignored for local requests.
 * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.
 */

class FileResponse {
    /**
     * Mapping from file extensions to MIME types.
     */
    _CONTENT_TYPE_MAP = {
        'txt': 'text/plain',
        'html': 'text/html',
        'css': 'text/css',
        'js': 'text/javascript',
        'json': 'application/json',
        'png': 'image/png',
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'gif': 'image/gif',
    }
    /**
     * Creates a new `FileResponse` object.
     * @param {string|URL} filePath
     */
    constructor(filePath) {
        this.filePath = filePath;
        this.headers = new Headers();

        this.exists = fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(filePath);
        if (this.exists) {
            this.status = 200;
            this.statusText = 'OK';

            let stats = fs__WEBPACK_IMPORTED_MODULE_0__.statSync(filePath);
            this.headers.set('content-length', stats.size.toString());

            this.updateContentType();

            let self = this;
            this.body = new ReadableStream({
                start(controller) {
                    self.arrayBuffer().then(buffer => {
                        controller.enqueue(new Uint8Array(buffer));
                        controller.close();
                    })
                }
            });
        } else {
            this.status = 404;
            this.statusText = 'Not Found';
            this.body = null;
        }
    }

    /**
     * Updates the 'content-type' header property of the response based on the extension of
     * the file specified by the filePath property of the current object.
     * @returns {void}
     */
    updateContentType() {
        // Set content-type header based on file extension
        const extension = this.filePath.toString().split('.').pop().toLowerCase();
        this.headers.set('content-type', this._CONTENT_TYPE_MAP[extension] ?? 'application/octet-stream');
    }

    /**
     * Clone the current FileResponse object.
     * @returns {FileResponse} A new FileResponse object with the same properties as the current object.
     */
    clone() {
        let response = new FileResponse(this.filePath);
        response.exists = this.exists;
        response.status = this.status;
        response.statusText = this.statusText;
        response.headers = new Headers(this.headers);
        return response;
    }

    /**
     * Reads the contents of the file specified by the filePath property and returns a Promise that
     * resolves with an ArrayBuffer containing the file's contents.
     * @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
     * @throws {Error} If the file cannot be read.
     */
    async arrayBuffer() {
        const data = await fs__WEBPACK_IMPORTED_MODULE_0__.promises.readFile(this.filePath);
        return data.buffer;
    }

    /**
     * Reads the contents of the file specified by the filePath property and returns a Promise that
     * resolves with a Blob containing the file's contents.
     * @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.
     * @throws {Error} If the file cannot be read.
     */
    async blob() {
        const data = await fs__WEBPACK_IMPORTED_MODULE_0__.promises.readFile(this.filePath);
        return new Blob([data], { type: this.headers.get('content-type') });
    }

    /**
     * Reads the contents of the file specified by the filePath property and returns a Promise that
     * resolves with a string containing the file's contents.
     * @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.
     * @throws {Error} If the file cannot be read.
     */
    async text() {
        const data = await fs__WEBPACK_IMPORTED_MODULE_0__.promises.readFile(this.filePath, 'utf8');
        return data;
    }

    /**
     * Reads the contents of the file specified by the filePath property and returns a Promise that
     * resolves with a parsed JavaScript object containing the file's contents.
     * 
     * @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
     * @throws {Error} If the file cannot be read.
     */
    async json() {
        return JSON.parse(await this.text());
    }
}

/**
 * Determines whether the given string is a valid URL.
 * @param {string|URL} string The string to test for validity as an URL.
 * @param {string[]} [protocols=null] A list of valid protocols. If specified, the protocol must be in this list.
 * @param {string[]} [validHosts=null] A list of valid hostnames. If specified, the URL's hostname must be in this list.
 * @returns {boolean} True if the string is a valid URL, false otherwise.
 */
function isValidUrl(string, protocols = null, validHosts = null) {
    let url;
    try {
        url = new URL(string);
    } catch (_) {
        return false;
    }
    if (protocols && !protocols.includes(url.protocol)) {
        return false;
    }
    if (validHosts && !validHosts.includes(url.hostname)) {
        return false;
    }
    return true;
}

/**
 * Helper function to get a file, using either the Fetch API or FileSystem API.
 *
 * @param {URL|string} urlOrPath The URL/path of the file to get.
 * @returns {Promise<FileResponse|Response>} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API).
 */
async function getFile(urlOrPath) {

    if (_env_js__WEBPACK_IMPORTED_MODULE_2__.env.useFS && !isValidUrl(urlOrPath, ['http:', 'https:', 'blob:'])) {
        return new FileResponse(urlOrPath);

    } else if (typeof process !== 'undefined' && process?.release?.name === 'node') {
        const IS_CI = !!process.env?.TESTING_REMOTELY;
        const version = _env_js__WEBPACK_IMPORTED_MODULE_2__.env.version;

        const headers = new Headers();
        headers.set('User-Agent', `transformers.js/${version}; is_ci/${IS_CI};`);

        // Check whether we are making a request to the Hugging Face Hub.
        const isHFURL = isValidUrl(urlOrPath, ['http:', 'https:'], ['huggingface.co', 'hf.co']);
        if (isHFURL) {
            // If an access token is present in the environment variables,
            // we add it to the request headers.
            // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback).
            const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;
            if (token) {
                headers.set('Authorization', `Bearer ${token}`);
            }
        }
        return fetch(urlOrPath, { headers });
    } else {
        // Running in a browser-environment, so we use default headers
        // NOTE: We do not allow passing authorization headers in the browser,
        // since this would require exposing the token to the client.
        return fetch(urlOrPath);
    }
}

const ERROR_MAPPING = {
    // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)
    400: 'Bad request error occurred while trying to load file',
    401: 'Unauthorized access to file',
    403: 'Forbidden access to file',
    404: 'Could not locate file',
    408: 'Request timeout error occurred while trying to load file',

    // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)
    500: 'Internal server error error occurred while trying to load file',
    502: 'Bad gateway error occurred while trying to load file',
    503: 'Service unavailable error occurred while trying to load file',
    504: 'Gateway timeout error occurred while trying to load file',
}
/**
 * Helper method to handle fatal errors that occur while trying to load a file from the Hugging Face Hub.
 * @param {number} status The HTTP status code of the error.
 * @param {string} remoteURL The URL of the file that could not be loaded.
 * @param {boolean} fatal Whether to raise an error if the file could not be loaded.
 * @returns {null} Returns `null` if `fatal = true`.
 * @throws {Error} If `fatal = false`.
 */
function handleError(status, remoteURL, fatal) {
    if (!fatal) {
        // File was not loaded correctly, but it is optional.
        // TODO in future, cache the response?
        return null;
    }

    const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`;
    throw Error(`${message}: "${remoteURL}".`);
}

class FileCache {
    /**
     * Instantiate a `FileCache` object.
     * @param {string} path 
     */
    constructor(path) {
        this.path = path;
    }

    /**
     * Checks whether the given request is in the cache.
     * @param {string} request 
     * @returns {Promise<FileResponse | undefined>}
     */
    async match(request) {

        let filePath = path__WEBPACK_IMPORTED_MODULE_1__.join(this.path, request);
        let file = new FileResponse(filePath);

        if (file.exists) {
            return file;
        } else {
            return undefined;
        }
    }

    /**
     * Adds the given response to the cache.
     * @param {string} request 
     * @param {Response|FileResponse} response 
     * @returns {Promise<void>}
     */
    async put(request, response) {
        const buffer = Buffer.from(await response.arrayBuffer());

        let outputPath = path__WEBPACK_IMPORTED_MODULE_1__.join(this.path, request);

        try {
            await fs__WEBPACK_IMPORTED_MODULE_0__.promises.mkdir(path__WEBPACK_IMPORTED_MODULE_1__.dirname(outputPath), { recursive: true });
            await fs__WEBPACK_IMPORTED_MODULE_0__.promises.writeFile(outputPath, buffer);

        } catch (err) {
            console.warn('An error occurred while writing the file to cache:', err)
        }
    }

    // TODO add the rest?
    // addAll(requests: RequestInfo[]): Promise<void>;
    // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;
    // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Request>>;
    // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;
    // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Response>>;
}

/**
 * 
 * @param {FileCache|Cache} cache The cache to search
 * @param {string[]} names The names of the item to search for
 * @returns {Promise<FileResponse|Response|undefined>} The item from the cache, or undefined if not found.
 */
async function tryCache(cache, ...names) {
    for (let name of names) {
        try {
            let result = await cache.match(name);
            if (result) return result;
        } catch (e) {
            continue;
        }
    }
    return undefined;
}

/**
 * 
 * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.
 * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached.
 * 
 * @param {string} path_or_repo_id This can be either:
 * - a string, the *model id* of a model repo on huggingface.co.
 * - a path to a *directory* potentially containing the file.
 * @param {string} filename The name of the file to locate in `path_or_repo`.
 * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.
 * @param {PretrainedOptions} [options] An object containing optional parameters.
 * 
 * @throws Will throw an error if the file is not found and `fatal` is true.
 * @returns {Promise} A Promise that resolves with the file content as a buffer.
 */
async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) {

    if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowLocalModels) {
        // User has disabled local models, so we just make sure other settings are correct.

        if (options.local_files_only) {
            throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).")
        } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowRemoteModels) {
            throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")
        }
    }

    // Initiate file retrieval
    (0,_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, {
        status: 'initiate',
        name: path_or_repo_id,
        file: filename
    })

    // First, check if the a caching backend is available
    // If no caching mechanism available, will download the file every time
    let cache;
    if (!cache && _env_js__WEBPACK_IMPORTED_MODULE_2__.env.useBrowserCache) {
        if (typeof caches === 'undefined') {
            throw Error('Browser cache is not available in this environment.')
        }
        try {
            // In some cases, the browser cache may be visible, but not accessible due to security restrictions.
            // For example, when running an application in an iframe, if a user attempts to load the page in
            // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage':
            // An attempt was made to break through the security policy of the user agent.`
            // So, instead of crashing, we just ignore the error and continue without using the cache.
            cache = await caches.open('transformers-cache');
        } catch (e) {
            console.warn('An error occurred while opening the browser cache:', e);
        }
    }

    if (!cache && _env_js__WEBPACK_IMPORTED_MODULE_2__.env.useFSCache) {
        // TODO throw error if not available

        // If `cache_dir` is not specified, use the default cache directory
        cache = new FileCache(options.cache_dir ?? _env_js__WEBPACK_IMPORTED_MODULE_2__.env.cacheDir);
    }

    if (!cache && _env_js__WEBPACK_IMPORTED_MODULE_2__.env.useCustomCache) {
        // Allow the user to specify a custom cache system.
        if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache) {
            throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.')
        }

        // Check that the required methods are defined:
        if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache.match || !_env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache.put) {
            throw new Error(
                "`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. " +
                "For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache"
            )
        }
        cache = _env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache;
    }

    const revision = options.revision ?? 'main';

    let requestURL = pathJoin(path_or_repo_id, filename);
    let localPath = pathJoin(_env_js__WEBPACK_IMPORTED_MODULE_2__.env.localModelPath, requestURL);

    let remoteURL = pathJoin(
        _env_js__WEBPACK_IMPORTED_MODULE_2__.env.remoteHost,
        _env_js__WEBPACK_IMPORTED_MODULE_2__.env.remotePathTemplate.replaceAll('{model}', path_or_repo_id)
            .replaceAll('{revision}', encodeURIComponent(revision)),
        filename
    );

    // Choose cache key for filesystem cache
    // When using the main revision (default), we use the request URL as the cache key.
    // If a specific revision is requested, we account for this in the cache key.
    let fsCacheKey = revision === 'main' ? requestURL : pathJoin(path_or_repo_id, revision, filename);

    /** @type {string} */
    let cacheKey;
    let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL;

    // Whether to cache the final response in the end.
    let toCacheResponse = false;

    /** @type {Response|FileResponse|undefined} */
    let response;

    if (cache) {
        // A caching system is available, so we try to get the file from it.
        //  1. We first try to get from cache using the local path. In some environments (like deno),
        //     non-URL cache keys are not allowed. In these cases, `response` will be undefined.
        //  2. If no response is found, we try to get from cache using the remote URL or file system cache.
        response = await tryCache(cache, localPath, proposedCacheKey);
    }

    const cacheHit = response !== undefined;

    if (response === undefined) {
        // Caching not available, or file is not cached, so we perform the request

        if (_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowLocalModels) {
            // Accessing local models is enabled, so we try to get the file locally.
            // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally.
            const isURL = isValidUrl(requestURL, ['http:', 'https:']);
            if (!isURL) {
                try {
                    response = await getFile(localPath);
                    cacheKey = localPath; // Update the cache key to be the local path
                } catch (e) {
                    // Something went wrong while trying to get the file locally.
                    // NOTE: error handling is done in the next step (since `response` will be undefined)
                    console.warn(`Unable to load from local path "${localPath}": "${e}"`);
                }
            } else if (options.local_files_only) {
                throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`);
            } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowRemoteModels) {
                throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.`);
            }
        }

        if (response === undefined || response.status === 404) {
            // File not found locally. This means either:
            // - The user has disabled local file access (`env.allowLocalModels=false`)
            // - the path is a valid HTTP url (`response === undefined`)
            // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`)

            if (options.local_files_only || !_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowRemoteModels) {
                // User requested local files only, but the file is not found locally.
                if (fatal) {
                    throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`);
                } else {
                    // File not found, but this file is optional.
                    // TODO in future, cache the response?
                    return null;
                }
            }

            // File not found locally, so we try to download it from the remote server
            response = await getFile(remoteURL);

            if (response.status !== 200) {
                return handleError(response.status, remoteURL, fatal);
            }

            // Success! We use the proposed cache key from earlier
            cacheKey = proposedCacheKey;
        }

        // Only cache the response if:
        toCacheResponse =
            cache                              // 1. A caching system is available
            && typeof Response !== 'undefined' // 2. `Response` is defined (i.e., we are in a browser-like environment)
            && response instanceof Response    // 3. result is a `Response` object (i.e., not a `FileResponse`)
            && response.status === 200         // 4. request was successful (status code 200)
    }

    // Start downloading
    (0,_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, {
        status: 'download',
        name: path_or_repo_id,
        file: filename
    })

    const progressInfo = {
        status: 'progress',
        name: path_or_repo_id,
        file: filename
    }

    /** @type {Uint8Array} */
    let buffer;

    if (!options.progress_callback) {
        // If no progress callback is specified, we can use the `.arrayBuffer()`
        // method to read the response.
        buffer = new Uint8Array(await response.arrayBuffer());

    } else if (
        cacheHit // The item is being read from the cache
        &&
        typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent) // We are in Firefox
    ) {
        // Due to bug in Firefox, we cannot display progress when loading from cache.
        // Fortunately, since this should be instantaneous, this should not impact users too much.
        buffer = new Uint8Array(await response.arrayBuffer());

        // For completeness, we still fire the final progress callback
        (0,_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, {
            ...progressInfo,
            progress: 100,
            loaded: buffer.length,
            total: buffer.length,
        })
    } else {
        buffer = await readResponse(response, data => {
            (0,_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, {
                ...progressInfo,
                ...data,
            })
        })
    }

    if (
        // Only cache web responses
        // i.e., do not cache FileResponses (prevents duplication)
        toCacheResponse && cacheKey
        &&
        // Check again whether request is in cache. If not, we add the response to the cache
        (await cache.match(cacheKey) === undefined)
    ) {
        // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files
        await cache.put(cacheKey, new Response(buffer, {
            headers: response.headers
        }))
            .catch(err => {
                // Do not crash if unable to add to cache (e.g., QuotaExceededError).
                // Rather, log a warning and proceed with execution.
                console.warn(`Unable to add response to browser cache: ${err}.`);
            });

    }

    (0,_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, {
        status: 'done',
        name: path_or_repo_id,
        file: filename
    });

    return buffer;
}

/**
 * Fetches a JSON file from a given path and file name.
 *
 * @param {string} modelPath The path to the directory containing the file.
 * @param {string} fileName The name of the file to fetch.
 * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.
 * @param {PretrainedOptions} [options] An object containing optional parameters.
 * @returns {Promise<Object>} The JSON data parsed into a JavaScript object.
 * @throws Will throw an error if the file is not found and `fatal` is true.
 */
async function getModelJSON(modelPath, fileName, fatal = true, options = {}) {
    let buffer = await getModelFile(modelPath, fileName, fatal, options);
    if (buffer === null) {
        // Return empty object
        return {}
    }

    let decoder = new TextDecoder('utf-8');
    let jsonData = decoder.decode(buffer);

    return JSON.parse(jsonData);
}

/**
 * Read and track progress when reading a Response object
 *
 * @param {any} response The Response object to read
 * @param {function} progress_callback The function to call with progress updates
 * @returns {Promise<Uint8Array>} A Promise that resolves with the Uint8Array buffer
 */
async function readResponse(response, progress_callback) {

    const contentLength = response.headers.get('Content-Length');
    if (contentLength === null) {
        console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.')
    }
    let total = parseInt(contentLength ?? '0');
    let buffer = new Uint8Array(total);
    let loaded = 0;

    const reader = response.body.getReader();
    async function read() {
        const { done, value } = await reader.read();
        if (done) return;

        let newLoaded = loaded + value.length;
        if (newLoaded > total) {
            total = newLoaded;

            // Adding the new data will overflow buffer.
            // In this case, we extend the buffer
            let newBuffer = new Uint8Array(total);

            // copy contents
            newBuffer.set(buffer);

            buffer = newBuffer;
        }
        buffer.set(value, loaded)
        loaded = newLoaded;

        const progress = (loaded / total) * 100;

        // Call your function here
        progress_callback({
            progress: progress,
            loaded: loaded,
            total: total,
        })

        return read();
    }

    // Actually read
    await read();

    return buffer;
}

/**
 * Joins multiple parts of a path into a single path, while handling leading and trailing slashes.
 *
 * @param {...string} parts Multiple parts of a path.
 * @returns {string} A string representing the joined path.
 */
function pathJoin(...parts) {
    // https://stackoverflow.com/a/55142565
    parts = parts.map((part, index) => {
        if (index) {
            part = part.replace(new RegExp('^/'), '');
        }
        if (index !== parts.length - 1) {
            part = part.replace(new RegExp('/$'), '');
        }
        return part;
    })
    return parts.join('/');
}


/***/ }),

/***/ "./src/utils/image.js":
/*!****************************!*\
  !*** ./src/utils/image.js ***!
  \****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "RawImage": () => (/* binding */ RawImage)
/* harmony export */ });
/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hub.js */ "./src/utils/hub.js");
/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../env.js */ "./src/env.js");
/* harmony import */ var _tensor_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./tensor.js */ "./src/utils/tensor.js");
/* harmony import */ var sharp__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! sharp */ "?2b25");

/**
 * @file Helper module for image processing. 
 * 
 * These functions and classes are only used internally, 
 * meaning an end-user shouldn't need to access anything here.
 * 
 * @module utils/image
 */





// Will be empty (or not used) if running in browser or web-worker


const BROWSER_ENV = typeof self !== 'undefined';
const WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope';

let createCanvasFunction;
let ImageDataClass;
let loadImageFunction;
if (BROWSER_ENV) {
    // Running in browser or web-worker
    createCanvasFunction = (/** @type {number} */ width, /** @type {number} */ height) => {
        if (!self.OffscreenCanvas) {
            throw new Error('OffscreenCanvas not supported by this browser.');
        }
        return new self.OffscreenCanvas(width, height)
    };
    loadImageFunction = self.createImageBitmap;
    ImageDataClass = self.ImageData;

} else if (sharp__WEBPACK_IMPORTED_MODULE_3__) {
    // Running in Node.js, electron, or other non-browser environment

    loadImageFunction = async (/**@type {sharp.Sharp}*/img) => {
        const metadata = await img.metadata();
        const rawChannels = metadata.channels;

        let { data, info } = await img.rotate().raw().toBuffer({ resolveWithObject: true });

        const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels);
        if (rawChannels !== undefined && rawChannels !== info.channels) {
            // Make sure the new image has the same number of channels as the input image.
            // This is necessary for grayscale images.
            newImage.convert(rawChannels);
        }
        return newImage;
    }

} else {
    throw new Error('Unable to load image processing library.');
}


// Defined here: https://github.com/python-pillow/Pillow/blob/a405e8406b83f8bfb8916e93971edc7407b8b1ff/src/libImaging/Imaging.h#L262-L268
const RESAMPLING_MAPPING = {
    0: 'nearest',
    1: 'lanczos',
    2: 'bilinear',
    3: 'bicubic',
    4: 'box',
    5: 'hamming',
}

/**
 * Mapping from file extensions to MIME types.
 */
const CONTENT_TYPE_MAP = new Map([
    ['png', 'image/png'],
    ['jpg', 'image/jpeg'],
    ['jpeg', 'image/jpeg'],
    ['gif', 'image/gif'],
]);

class RawImage {

    /**
     * Create a new `RawImage` object.
     * @param {Uint8ClampedArray|Uint8Array} data The pixel data.
     * @param {number} width The width of the image.
     * @param {number} height The height of the image.
     * @param {1|2|3|4} channels The number of channels.
     */
    constructor(data, width, height, channels) {
        this.data = data;
        this.width = width;
        this.height = height;
        this.channels = channels;
    }

    /** 
     * Returns the size of the image (width, height).
     * @returns {[number, number]} The size of the image (width, height).
     */
    get size() {
        return [this.width, this.height];
    }

    /**
     * Helper method for reading an image from a variety of input types.
     * @param {RawImage|string|URL} input 
     * @returns The image object.
     * 
     * **Example:** Read image from a URL.
     * ```javascript
     * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
     * // RawImage {
     * //   "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],
     * //   "width": 800,
     * //   "height": 533,
     * //   "channels": 3
     * // }
     * ```
     */
    static async read(input) {
        if (input instanceof RawImage) {
            return input;
        } else if (typeof input === 'string' || input instanceof URL) {
            return await this.fromURL(input);
        } else {
            throw new Error(`Unsupported input type: ${typeof input}`);
        }
    }


    /**
     * Read an image from a URL or file path.
     * @param {string|URL} url The URL or file path to read the image from.
     * @returns {Promise<RawImage>} The image object.
     */
    static async fromURL(url) {
        let response = await (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getFile)(url);
        if (response.status !== 200) {
            throw new Error(`Unable to read image from "${url}" (${response.status} ${response.statusText})`);
        }
        let blob = await response.blob();
        return this.fromBlob(blob);
    }

    /**
     * Helper method to create a new Image from a blob.
     * @param {Blob} blob The blob to read the image from.
     * @returns {Promise<RawImage>} The image object.
     */
    static async fromBlob(blob) {
        if (BROWSER_ENV) {
            // Running in environment with canvas
            let img = await loadImageFunction(blob);

            const ctx = createCanvasFunction(img.width, img.height).getContext('2d');

            // Draw image to context
            ctx.drawImage(img, 0, 0);

            return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4);

        } else {
            // Use sharp.js to read (and possible resize) the image.
            let img = sharp__WEBPACK_IMPORTED_MODULE_3__(await blob.arrayBuffer());

            return await loadImageFunction(img);
        }
    }

    /**
     * Helper method to create a new Image from a tensor
     * @param {Tensor} tensor 
     */
    static fromTensor(tensor, channel_format = 'CHW') {
        if (tensor.dims.length !== 3) {
            throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`);
        }

        if (channel_format === 'CHW') {
            tensor = tensor.transpose(1, 2, 0);
        } else if (channel_format === 'HWC') {
            // Do nothing
        } else {
            throw new Error(`Unsupported channel format: ${channel_format}`);
        }
        if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) {
            throw new Error(`Unsupported tensor type: ${tensor.type}`);
        }
        switch (tensor.dims[2]) {
            case 1:
            case 2:
            case 3:
            case 4:
                return new RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]);
            default:
                throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`);
        }
    }

    /**
     * Convert the image to grayscale format.
     * @returns {RawImage} `this` to support chaining.
     */
    grayscale() {
        if (this.channels === 1) {
            return this;
        }

        let newData = new Uint8ClampedArray(this.width * this.height * 1);
        switch (this.channels) {
            case 3: // rgb to grayscale
            case 4: // rgba to grayscale
                for (let i = 0, offset = 0; i < this.data.length; i += this.channels) {
                    const red = this.data[i];
                    const green = this.data[i + 1];
                    const blue = this.data[i + 2];

                    newData[offset++] = Math.round(0.2989 * red + 0.5870 * green + 0.1140 * blue);
                }
                break;
            default:
                throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);
        }
        return this._update(newData, this.width, this.height, 1);
    }

    /**
     * Convert the image to RGB format.
     * @returns {RawImage} `this` to support chaining.
     */
    rgb() {
        if (this.channels === 3) {
            return this;
        }

        let newData = new Uint8ClampedArray(this.width * this.height * 3);

        switch (this.channels) {
            case 1: // grayscale to rgb
                for (let i = 0, offset = 0; i < this.data.length; ++i) {
                    newData[offset++] = this.data[i];
                    newData[offset++] = this.data[i];
                    newData[offset++] = this.data[i];
                }
                break;
            case 4: // rgba to rgb
                for (let i = 0, offset = 0; i < this.data.length; i += 4) {
                    newData[offset++] = this.data[i];
                    newData[offset++] = this.data[i + 1];
                    newData[offset++] = this.data[i + 2];
                }
                break;
            default:
                throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);
        }
        return this._update(newData, this.width, this.height, 3);

    }

    /**
     * Convert the image to RGBA format.
     * @returns {RawImage} `this` to support chaining.
     */
    rgba() {
        if (this.channels === 4) {
            return this;
        }

        let newData = new Uint8ClampedArray(this.width * this.height * 4);

        switch (this.channels) {
            case 1: // grayscale to rgba
                for (let i = 0, offset = 0; i < this.data.length; ++i) {
                    newData[offset++] = this.data[i];
                    newData[offset++] = this.data[i];
                    newData[offset++] = this.data[i];
                    newData[offset++] = 255;
                }
                break;
            case 3: // rgb to rgba
                for (let i = 0, offset = 0; i < this.data.length; i += 3) {
                    newData[offset++] = this.data[i];
                    newData[offset++] = this.data[i + 1];
                    newData[offset++] = this.data[i + 2];
                    newData[offset++] = 255;
                }
                break;
            default:
                throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);
        }

        return this._update(newData, this.width, this.height, 4);
    }

    /**
     * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.
     * @param {number} width The width of the new image.
     * @param {number} height The height of the new image.
     * @param {Object} options Additional options for resizing.
     * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.
     * @returns {Promise<RawImage>} `this` to support chaining.
     */
    async resize(width, height, {
        resample = 2,
    } = {}) {

        // Ensure resample method is a string
        let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample;

        if (BROWSER_ENV) {
            // TODO use `resample` in browser environment

            // Store number of channels before resizing
            let numChannels = this.channels;

            // Create canvas object for this image
            let canvas = this.toCanvas();

            // Actually perform resizing using the canvas API
            const ctx = createCanvasFunction(width, height).getContext('2d');

            // Draw image to context, resizing in the process
            ctx.drawImage(canvas, 0, 0, width, height);

            // Create image from the resized data
            let resizedImage = new RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4);

            // Convert back so that image has the same number of channels as before
            return resizedImage.convert(numChannels);

        } else {
            // Create sharp image from raw data, and resize
            let img = this.toSharp();

            switch (resampleMethod) {
                case 'box':
                case 'hamming':
                    if (resampleMethod === 'box' || resampleMethod === 'hamming') {
                        console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`);
                        resampleMethod = 'bilinear';
                    }

                case 'nearest':
                case 'bilinear':
                case 'bicubic':
                    // Perform resizing using affine transform. 
                    // This matches how the python Pillow library does it.
                    img = img.affine([width / this.width, 0, 0, height / this.height], {
                        interpolator: resampleMethod
                    });
                    break;

                case 'lanczos':
                    // https://github.com/python-pillow/Pillow/discussions/5519
                    // https://github.com/lovell/sharp/blob/main/docs/api-resize.md
                    img = img.resize({
                        width, height,
                        fit: 'fill',
                        kernel: 'lanczos3', // PIL Lanczos uses a kernel size of 3 
                    });
                    break;

                default:
                    throw new Error(`Resampling method ${resampleMethod} is not supported.`);
            }

            return await loadImageFunction(img);
        }

    }

    async pad([left, right, top, bottom]) {
        left = Math.max(left, 0);
        right = Math.max(right, 0);
        top = Math.max(top, 0);
        bottom = Math.max(bottom, 0);

        if (left === 0 && right === 0 && top === 0 && bottom === 0) {
            // No padding needed
            return this;
        }

        if (BROWSER_ENV) {
            // Store number of channels before padding
            let numChannels = this.channels;

            // Create canvas object for this image
            let canvas = this.toCanvas();

            let newWidth = this.width + left + right;
            let newHeight = this.height + top + bottom;

            // Create a new canvas of the desired size.
            const ctx = createCanvasFunction(newWidth, newHeight).getContext('2d');

            // Draw image to context, padding in the process
            ctx.drawImage(canvas,
                0, 0, this.width, this.height,
                left, top, newWidth, newHeight
            );

            // Create image from the padded data
            let paddedImage = new RawImage(
                ctx.getImageData(0, 0, newWidth, newHeight).data,
                newWidth, newHeight, 4);

            // Convert back so that image has the same number of channels as before
            return paddedImage.convert(numChannels);

        } else {
            let img = this.toSharp().extend({ left, right, top, bottom });
            return await loadImageFunction(img);
        }
    }

    async crop([x_min, y_min, x_max, y_max]) {
        // Ensure crop bounds are within the image
        x_min = Math.max(x_min, 0);
        y_min = Math.max(y_min, 0);
        x_max = Math.min(x_max, this.width - 1);
        y_max = Math.min(y_max, this.height - 1);

        // Do nothing if the crop is the entire image
        if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) {
            return this;
        }

        const crop_width = x_max - x_min + 1;
        const crop_height = y_max - y_min + 1;

        if (BROWSER_ENV) {
            // Store number of channels before resizing
            const numChannels = this.channels;

            // Create canvas object for this image
            const canvas = this.toCanvas();

            // Create a new canvas of the desired size. This is needed since if the 
            // image is too small, we need to pad it with black pixels.
            const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');

            // Draw image to context, cropping in the process
            ctx.drawImage(canvas,
                x_min, y_min, crop_width, crop_height,
                0, 0, crop_width, crop_height
            );

            // Create image from the resized data
            const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);

            // Convert back so that image has the same number of channels as before
            return resizedImage.convert(numChannels);

        } else {
            // Create sharp image from raw data
            const img = this.toSharp().extract({
                left: x_min,
                top: y_min,
                width: crop_width,
                height: crop_height,
            });

            return await loadImageFunction(img);
        }

    }

    async center_crop(crop_width, crop_height) {
        // If the image is already the desired size, return it
        if (this.width === crop_width && this.height === crop_height) {
            return this;
        }

        // Determine bounds of the image in the new canvas
        let width_offset = (this.width - crop_width) / 2;
        let height_offset = (this.height - crop_height) / 2;


        if (BROWSER_ENV) {
            // Store number of channels before resizing
            let numChannels = this.channels;

            // Create canvas object for this image
            let canvas = this.toCanvas();

            // Create a new canvas of the desired size. This is needed since if the 
            // image is too small, we need to pad it with black pixels.
            const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');

            let sourceX = 0;
            let sourceY = 0;
            let destX = 0;
            let destY = 0;

            if (width_offset >= 0) {
                sourceX = width_offset;
            } else {
                destX = -width_offset;
            }

            if (height_offset >= 0) {
                sourceY = height_offset;
            } else {
                destY = -height_offset;
            }

            // Draw image to context, cropping in the process
            ctx.drawImage(canvas,
                sourceX, sourceY, crop_width, crop_height,
                destX, destY, crop_width, crop_height
            );

            // Create image from the resized data
            let resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);

            // Convert back so that image has the same number of channels as before
            return resizedImage.convert(numChannels);

        } else {
            // Create sharp image from raw data
            let img = this.toSharp();

            if (width_offset >= 0 && height_offset >= 0) {
                // Cropped image lies entirely within the original image
                img = img.extract({
                    left: Math.floor(width_offset),
                    top: Math.floor(height_offset),
                    width: crop_width,
                    height: crop_height,
                })
            } else if (width_offset <= 0 && height_offset <= 0) {
                // Cropped image lies entirely outside the original image,
                // so we add padding
                let top = Math.floor(-height_offset);
                let left = Math.floor(-width_offset);
                img = img.extend({
                    top: top,
                    left: left,

                    // Ensures the resulting image has the desired dimensions
                    right: crop_width - this.width - left,
                    bottom: crop_height - this.height - top,
                });
            } else {
                // Cropped image lies partially outside the original image.
                // We first pad, then crop.

                let y_padding = [0, 0];
                let y_extract = 0;
                if (height_offset < 0) {
                    y_padding[0] = Math.floor(-height_offset);
                    y_padding[1] = crop_height - this.height - y_padding[0];
                } else {
                    y_extract = Math.floor(height_offset);
                }

                let x_padding = [0, 0];
                let x_extract = 0;
                if (width_offset < 0) {
                    x_padding[0] = Math.floor(-width_offset);
                    x_padding[1] = crop_width - this.width - x_padding[0];
                } else {
                    x_extract = Math.floor(width_offset);
                }

                img = img.extend({
                    top: y_padding[0],
                    bottom: y_padding[1],
                    left: x_padding[0],
                    right: x_padding[1],
                }).extract({
                    left: x_extract,
                    top: y_extract,
                    width: crop_width,
                    height: crop_height,
                })
            }

            return await loadImageFunction(img);
        }
    }

    async toBlob(type = 'image/png', quality = 1) {
        if (!BROWSER_ENV) {
            throw new Error('toBlob() is only supported in browser environments.')
        }

        const canvas = this.toCanvas();
        return await canvas.convertToBlob({ type, quality });
    }

    toTensor(channel_format = 'CHW') {
        let tensor = new _tensor_js__WEBPACK_IMPORTED_MODULE_2__.Tensor(
            'uint8',
            new Uint8Array(this.data),
            [this.height, this.width, this.channels]
        );

        if (channel_format === 'HWC') {
            // Do nothing
        } else if (channel_format === 'CHW') { // hwc -> chw
            tensor = tensor.permute(2, 0, 1);
        } else {
            throw new Error(`Unsupported channel format: ${channel_format}`);
        }
        return tensor;
    }

    toCanvas() {
        if (!BROWSER_ENV) {
            throw new Error('toCanvas() is only supported in browser environments.')
        }

        // Clone, and convert data to RGBA before drawing to canvas.
        // This is because the canvas API only supports RGBA
        let cloned = this.clone().rgba();

        // Create canvas object for the cloned image
        let clonedCanvas = createCanvasFunction(cloned.width, cloned.height);

        // Draw image to context
        let data = new ImageDataClass(cloned.data, cloned.width, cloned.height);
        clonedCanvas.getContext('2d').putImageData(data, 0, 0);

        return clonedCanvas;
    }

    /**
     * Helper method to update the image data.
     * @param {Uint8ClampedArray} data The new image data.
     * @param {number} width The new width of the image.
     * @param {number} height The new height of the image.
     * @param {1|2|3|4|null} [channels] The new number of channels of the image.
     * @private
     */
    _update(data, width, height, channels = null) {
        this.data = data;
        this.width = width;
        this.height = height;
        if (channels !== null) {
            this.channels = channels;
        }
        return this;
    }

    /**
     * Clone the image
     * @returns {RawImage} The cloned image
     */
    clone() {
        return new RawImage(this.data.slice(), this.width, this.height, this.channels);
    }

    /**
     * Helper method for converting image to have a certain number of channels
     * @param {number} numChannels The number of channels. Must be 1, 3, or 4.
     * @returns {RawImage} `this` to support chaining.
     */
    convert(numChannels) {
        if (this.channels === numChannels) return this; // Already correct number of channels

        switch (numChannels) {
            case 1:
                this.grayscale();
                break;
            case 3:
                this.rgb();
                break;
            case 4:
                this.rgba();
                break;
            default:
                throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);
        }
        return this;
    }

    /**
     * Save the image to the given path.
     * @param {string} path The path to save the image to.
     */
    async save(path) {

        if (BROWSER_ENV) {
            if (WEBWORKER_ENV) {
                throw new Error('Unable to save an image from a Web Worker.')
            }

            const extension = path.split('.').pop().toLowerCase();
            const mime = CONTENT_TYPE_MAP.get(extension) ?? 'image/png';

            // Convert image to Blob
            const blob = await this.toBlob(mime);

            // Convert the canvas content to a data URL
            const dataURL = URL.createObjectURL(blob);

            // Create an anchor element with the data URL as the href attribute
            const downloadLink = document.createElement('a');
            downloadLink.href = dataURL;

            // Set the download attribute to specify the desired filename for the downloaded image
            downloadLink.download = path;

            // Trigger the download
            downloadLink.click();

            // Clean up: remove the anchor element from the DOM
            downloadLink.remove();

        } else if (!_env_js__WEBPACK_IMPORTED_MODULE_1__.env.useFS) {
            throw new Error('Unable to save the image because filesystem is disabled in this environment.')

        } else {
            const img = this.toSharp();
            return await img.toFile(path);
        }
    }

    toSharp() {
        if (BROWSER_ENV) {
            throw new Error('toSharp() is only supported in server-side environments.')
        }

        return sharp__WEBPACK_IMPORTED_MODULE_3__(this.data, {
            raw: {
                width: this.width,
                height: this.height,
                channels: this.channels
            }
        });
    }
}


/***/ }),

/***/ "./src/utils/maths.js":
/*!****************************!*\
  !*** ./src/utils/maths.js ***!
  \****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "FFT": () => (/* binding */ FFT),
/* harmony export */   "bankers_round": () => (/* binding */ bankers_round),
/* harmony export */   "cos_sim": () => (/* binding */ cos_sim),
/* harmony export */   "dot": () => (/* binding */ dot),
/* harmony export */   "getTopItems": () => (/* binding */ getTopItems),
/* harmony export */   "interpolate_data": () => (/* binding */ interpolate_data),
/* harmony export */   "log_softmax": () => (/* binding */ log_softmax),
/* harmony export */   "magnitude": () => (/* binding */ magnitude),
/* harmony export */   "max": () => (/* binding */ max),
/* harmony export */   "medianFilter": () => (/* binding */ medianFilter),
/* harmony export */   "min": () => (/* binding */ min),
/* harmony export */   "permute_data": () => (/* binding */ permute_data),
/* harmony export */   "round": () => (/* binding */ round),
/* harmony export */   "softmax": () => (/* binding */ softmax)
/* harmony export */ });

/**
 * @file Helper module for mathematical processing. 
 * 
 * These functions and classes are only used internally, 
 * meaning an end-user shouldn't need to access anything here.
 * 
 * @module utils/maths
 */

/**
 * @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray
 * @typedef {BigInt64Array | BigUint64Array} BigTypedArray
 * @typedef {TypedArray | BigTypedArray} AnyTypedArray
 */

/**
 * @param {TypedArray} input
 */
function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = 'bilinear', align_corners = false) {
    // TODO use mode and align_corners

    // Output image dimensions
    const x_scale = out_width / in_width;
    const y_scale = out_height / in_height;

    // Output image
    // @ts-ignore
    const out_img = new input.constructor(out_height * out_width * in_channels);

    // Pre-calculate strides
    const inStride = in_height * in_width;
    const outStride = out_height * out_width;

    for (let i = 0; i < out_height; ++i) {
        for (let j = 0; j < out_width; ++j) {
            // Calculate output offset
            const outOffset = i * out_width + j;

            // Calculate input pixel coordinates
            const x = (j + 0.5) / x_scale - 0.5;
            const y = (i + 0.5) / y_scale - 0.5;

            // Calculate the four nearest input pixels
            // We also check if the input pixel coordinates are within the image bounds
            let x1 = Math.floor(x);
            let y1 = Math.floor(y);
            const x2 = Math.min(x1 + 1, in_width - 1);
            const y2 = Math.min(y1 + 1, in_height - 1);

            x1 = Math.max(x1, 0);
            y1 = Math.max(y1, 0);


            // Calculate the fractional distances between the input pixel and the four nearest pixels
            const s = x - x1;
            const t = y - y1;

            // Perform bilinear interpolation
            const w1 = (1 - s) * (1 - t);
            const w2 = s * (1 - t);
            const w3 = (1 - s) * t;
            const w4 = s * t;

            // Calculate the four nearest input pixel indices
            const yStride = y1 * in_width;
            const xStride = y2 * in_width;
            const idx1 = yStride + x1;
            const idx2 = yStride + x2;
            const idx3 = xStride + x1;
            const idx4 = xStride + x2;

            for (let k = 0; k < in_channels; ++k) {
                // Calculate channel offset
                const cOffset = k * inStride;

                out_img[k * outStride + outOffset] =
                    w1 * input[cOffset + idx1] +
                    w2 * input[cOffset + idx2] +
                    w3 * input[cOffset + idx3] +
                    w4 * input[cOffset + idx4];
            }
        }
    }

    return out_img;
}


/**
 * Helper method to permute a `AnyTypedArray` directly
 * @template {AnyTypedArray} T 
 * @param {T} array 
 * @param {number[]} dims 
 * @param {number[]} axes 
 * @returns {[T, number[]]} The permuted array and the new shape.
 */
function permute_data(array, dims, axes) {
    // Calculate the new shape of the permuted array
    // and the stride of the original array
    const shape = new Array(axes.length);
    const stride = new Array(axes.length);

    for (let i = axes.length - 1, s = 1; i >= 0; --i) {
        stride[i] = s;
        shape[i] = dims[axes[i]];
        s *= shape[i];
    }

    // Precompute inverse mapping of stride
    const invStride = axes.map((_, i) => stride[axes.indexOf(i)]);

    // Create the permuted array with the new shape
    // @ts-ignore
    const permutedData = new array.constructor(array.length);

    // Permute the original array to the new array
    for (let i = 0; i < array.length; ++i) {
        let newIndex = 0;
        for (let j = dims.length - 1, k = i; j >= 0; --j) {
            newIndex += (k % dims[j]) * invStride[j];
            k = Math.floor(k / dims[j]);
        }
        permutedData[newIndex] = array[i];
    }

    return [permutedData, shape];
}


/**
 * Compute the softmax of an array of numbers.
 * @template {TypedArray|number[]} T
 * @param {T} arr The array of numbers to compute the softmax of.
 * @returns {T} The softmax array.
 */
function softmax(arr) {
    // Compute the maximum value in the array
    const maxVal = max(arr)[0];

    // Compute the exponentials of the array values
    const exps = arr.map(x => Math.exp(x - maxVal));

    // Compute the sum of the exponentials
    // @ts-ignore
    const sumExps = exps.reduce((acc, val) => acc + val, 0);

    // Compute the softmax values
    const softmaxArr = exps.map(x => x / sumExps);

    return /** @type {T} */(softmaxArr);
}

/**
 * Calculates the logarithm of the softmax function for the input array.
 * @template {TypedArray|number[]} T
 * @param {T} arr The input array to calculate the log_softmax function for.
 * @returns {T} The resulting log_softmax array.
 */
function log_softmax(arr) {
    // Compute the softmax values
    const softmaxArr = softmax(arr);

    // Apply log formula to each element
    const logSoftmaxArr = softmaxArr.map(x => Math.log(x));

    return /** @type {T} */(logSoftmaxArr);
}

/**
 * Calculates the dot product of two arrays.
 * @param {number[]} arr1 The first array.
 * @param {number[]} arr2 The second array.
 * @returns {number} The dot product of arr1 and arr2.
 */
function dot(arr1, arr2) {
    let result = 0;
    for (let i = 0; i < arr1.length; ++i) {
        result += arr1[i] * arr2[i];
    }
    return result;
}


/**
 * Get the top k items from an iterable, sorted by descending order
 * @param {any[]|TypedArray} items The items to be sorted
 * @param {number|null} [top_k=0] The number of top items to return (default: 0 = return all)
 * @returns {[number, any][]} The top k items, sorted by descending order
 */
function getTopItems(items, top_k = 0) {
    // if top == 0, return all

    items = Array.from(items)
        .map((x, i) => [i, x])            // Get indices ([index, score])
        .sort((a, b) => b[1] - a[1])      // Sort by log probabilities

    if (top_k !== null && top_k > 0) {
        items = items.slice(0, top_k);    // Get top k items
    }

    return items
}

/**
 * Computes the cosine similarity between two arrays.
 *
 * @param {number[]} arr1 The first array.
 * @param {number[]} arr2 The second array.
 * @returns {number} The cosine similarity between the two arrays.
 */
function cos_sim(arr1, arr2) {
    // Calculate dot product of the two arrays
    const dotProduct = dot(arr1, arr2);

    // Calculate the magnitude of the first array
    const magnitudeA = magnitude(arr1);

    // Calculate the magnitude of the second array
    const magnitudeB = magnitude(arr2);

    // Calculate the cosine similarity
    const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB);

    return cosineSimilarity;
}

/**
 * Calculates the magnitude of a given array.
 * @param {number[]} arr The array to calculate the magnitude of.
 * @returns {number} The magnitude of the array.
 */
function magnitude(arr) {
    return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0));
}


/**
 * Returns the value and index of the minimum element in an array.
 * @param {number[]|TypedArray} arr array of numbers.
 * @returns {number[]} the value and index of the minimum element, of the form: [valueOfMin, indexOfMin]
 * @throws {Error} If array is empty.
 */
function min(arr) {
    if (arr.length === 0) throw Error('Array must not be empty');
    let min = arr[0];
    let indexOfMin = 0;
    for (let i = 1; i < arr.length; ++i) {
        if (arr[i] < min) {
            min = arr[i];
            indexOfMin = i;
        }
    }
    return [min, indexOfMin];
}


/**
 * Returns the value and index of the maximum element in an array.
 * @param {number[]|AnyTypedArray} arr array of numbers.
 * @returns {[number, number]} the value and index of the maximum element, of the form: [valueOfMax, indexOfMax]
 * @throws {Error} If array is empty.
 */
function max(arr) {
    if (arr.length === 0) throw Error('Array must not be empty');
    let max = arr[0];
    let indexOfMax = 0;
    for (let i = 1; i < arr.length; ++i) {
        if (arr[i] > max) {
            max = arr[i];
            indexOfMax = i;
        }
    }
    return [Number(max), indexOfMax];
}

function isPowerOfTwo(number) {
    // Check if the number is greater than 0 and has only one bit set to 1
    return (number > 0) && ((number & (number - 1)) === 0);
}

/**
 * Implementation of Radix-4 FFT.
 * 
 * P2FFT class provides functionality for performing Fast Fourier Transform on arrays
 * which are a power of two in length.
 * Code adapted from https://www.npmjs.com/package/fft.js
 */
class P2FFT {
    /**
     * @param {number} size The size of the input array. Must be a power of two larger than 1.
     * @throws {Error} FFT size must be a power of two larger than 1.
     */
    constructor(size) {
        this.size = size | 0; // convert to a 32-bit signed integer
        if (this.size <= 1 || !isPowerOfTwo(this.size))
            throw new Error('FFT size must be a power of two larger than 1');

        this._csize = size << 1;

        this.table = new Float64Array(this.size * 2);
        for (let i = 0; i < this.table.length; i += 2) {
            const angle = Math.PI * i / this.size;
            this.table[i] = Math.cos(angle);
            this.table[i + 1] = -Math.sin(angle);
        }

        // Find size's power of two
        let power = 0;
        for (let t = 1; this.size > t; t <<= 1)
            ++power;

        // Calculate initial step's width:
        //   * If we are full radix-4, it is 2x smaller to give inital len=8
        //   * Otherwise it is the same as `power` to give len=4
        this._width = power % 2 === 0 ? power - 1 : power;

        // Pre-compute bit-reversal patterns
        this._bitrev = new Int32Array(1 << this._width);
        for (let j = 0; j < this._bitrev.length; ++j) {
            this._bitrev[j] = 0;
            for (let shift = 0; shift < this._width; shift += 2) {
                const revShift = this._width - shift - 2;
                this._bitrev[j] |= ((j >>> shift) & 3) << revShift;
            }
        }
    }

    /**
     * Create a complex number array with size `2 * size`
     *
     * @returns {Float64Array} A complex number array with size `2 * size`
     */
    createComplexArray() {
        return new Float64Array(this._csize);
    }

    /**
     * Converts a complex number representation stored in a Float64Array to an array of real numbers.
     * 
     * @param {Float64Array} complex The complex number representation to be converted.
     * @param {number[]} [storage] An optional array to store the result in.
     * @returns {number[]} An array of real numbers representing the input complex number representation.
     */
    fromComplexArray(complex, storage) {
        const res = storage || new Array(complex.length >>> 1);
        for (let i = 0; i < complex.length; i += 2)
            res[i >>> 1] = complex[i];
        return res;
    }

    /**
     * Convert a real-valued input array to a complex-valued output array.
     * @param {Float64Array} input The real-valued input array.
     * @param {Float64Array} [storage] Optional buffer to store the output array.
     * @returns {Float64Array} The complex-valued output array.
     */
    toComplexArray(input, storage) {
        const res = storage || this.createComplexArray();
        for (let i = 0; i < res.length; i += 2) {
            res[i] = input[i >>> 1];
            res[i + 1] = 0;
        }
        return res;
    }

    /**
     * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.
     * 
     * @param {Float64Array} out The output buffer to store the result.
     * @param {Float64Array} data The input data to transform.
     * 
     * @throws {Error} Input and output buffers must be different.
     * 
     * @returns {void}
     */
    transform(out, data) {
        if (out === data)
            throw new Error('Input and output buffers must be different');

        this._transform4(out, data, 1 /* DONE */);
    }

    /**
     * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.
     * The input buffer must contain real values only, while the output buffer will contain complex values. The input and
     * output buffers must be different.
     *
     * @param {Float64Array} out The output buffer.
     * @param {Float64Array} data The input buffer containing real values.
     *
     * @throws {Error} If the input and output buffers are the same.
     */
    realTransform(out, data) {
        if (out === data)
            throw new Error('Input and output buffers must be different');

        this._realTransform4(out, data, 1 /* DONE */);
    }

    /**
     * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.
     * The `out` array must be a different buffer than the `data` array. The `out` array will contain the
     * result of the transformation. The `data` array will not be modified.
     * 
     * @param {Float64Array} out The output buffer for the transformed data.
     * @param {Float64Array} data The input data to transform.
     * @throws {Error} If `out` and `data` refer to the same buffer.
     * @returns {void}
     */
    inverseTransform(out, data) {
        if (out === data)
            throw new Error('Input and output buffers must be different');

        this._transform4(out, data, -1 /* DONE */);
        for (let i = 0; i < out.length; ++i)
            out[i] /= this.size;
    }

    /**
     * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.
     *
     * @param {Float64Array} out The output buffer for the transformed data.
     * @param {Float64Array} data The input buffer of data to be transformed.
     * @param {number} inv A scaling factor to apply to the transform.
     * @returns {void}
     */
    _transform4(out, data, inv) {
        // radix-4 implementation

        const size = this._csize;

        // Initial step (permute and transform)
        const width = this._width;
        let step = 1 << width;
        let len = (size / step) << 1;

        let outOff;
        let t;
        const bitrev = this._bitrev;
        if (len === 4) {
            for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
                const off = bitrev[t];
                this._singleTransform2(data, out, outOff, off, step);
            }
        } else {
            // len === 8
            for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
                const off = bitrev[t];
                this._singleTransform4(data, out, outOff, off, step, inv);
            }
        }

        // Loop through steps in decreasing order
        const table = this.table;
        for (step >>= 2; step >= 2; step >>= 2) {
            len = (size / step) << 1;
            const quarterLen = len >>> 2;

            // Loop through offsets in the data
            for (outOff = 0; outOff < size; outOff += len) {
                // Full case
                const limit = outOff + quarterLen - 1;
                for (let i = outOff, k = 0; i < limit; i += 2, k += step) {
                    const A = i;
                    const B = A + quarterLen;
                    const C = B + quarterLen;
                    const D = C + quarterLen;

                    // Original values
                    const Ar = out[A];
                    const Ai = out[A + 1];
                    const Br = out[B];
                    const Bi = out[B + 1];
                    const Cr = out[C];
                    const Ci = out[C + 1];
                    const Dr = out[D];
                    const Di = out[D + 1];

                    const tableBr = table[k];
                    const tableBi = inv * table[k + 1];
                    const MBr = Br * tableBr - Bi * tableBi;
                    const MBi = Br * tableBi + Bi * tableBr;

                    const tableCr = table[2 * k];
                    const tableCi = inv * table[2 * k + 1];
                    const MCr = Cr * tableCr - Ci * tableCi;
                    const MCi = Cr * tableCi + Ci * tableCr;

                    const tableDr = table[3 * k];
                    const tableDi = inv * table[3 * k + 1];
                    const MDr = Dr * tableDr - Di * tableDi;
                    const MDi = Dr * tableDi + Di * tableDr;

                    // Pre-Final values
                    const T0r = Ar + MCr;
                    const T0i = Ai + MCi;
                    const T1r = Ar - MCr;
                    const T1i = Ai - MCi;
                    const T2r = MBr + MDr;
                    const T2i = MBi + MDi;
                    const T3r = inv * (MBr - MDr);
                    const T3i = inv * (MBi - MDi);

                    // Final values
                    out[A] = T0r + T2r;
                    out[A + 1] = T0i + T2i;
                    out[B] = T1r + T3i;
                    out[B + 1] = T1i - T3r;
                    out[C] = T0r - T2r;
                    out[C + 1] = T0i - T2i;
                    out[D] = T1r - T3i;
                    out[D + 1] = T1i + T3r;
                }
            }
        }
    }

    /**
     * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.
     *
     * @param {Float64Array} data The input buffer of data to be transformed.
     * @param {Float64Array} out The output buffer for the transformed data.
     * @param {number} outOff The offset at which to write the output data.
     * @param {number} off The offset at which to begin reading the input data.
     * @param {number} step The step size for indexing the input data.
     * @returns {void}
     */
    _singleTransform2(data, out, outOff, off, step) {
        // radix-2 implementation
        // NOTE: Only called for len=4

        const evenR = data[off];
        const evenI = data[off + 1];
        const oddR = data[off + step];
        const oddI = data[off + step + 1];

        out[outOff] = evenR + oddR;
        out[outOff + 1] = evenI + oddI;
        out[outOff + 2] = evenR - oddR;
        out[outOff + 3] = evenI - oddI;
    }

    /**
     * Performs radix-4 transformation on input data of length 8
     *
     * @param {Float64Array} data Input data array of length 8
     * @param {Float64Array} out Output data array of length 8
     * @param {number} outOff Index of output array to start writing from
     * @param {number} off Index of input array to start reading from
     * @param {number} step Step size between elements in input array
     * @param {number} inv Scaling factor for inverse transform
     * 
     * @returns {void}
     */
    _singleTransform4(data, out, outOff, off, step, inv) {
        // radix-4
        // NOTE: Only called for len=8
        const step2 = step * 2;
        const step3 = step * 3;

        // Original values
        const Ar = data[off];
        const Ai = data[off + 1];
        const Br = data[off + step];
        const Bi = data[off + step + 1];
        const Cr = data[off + step2];
        const Ci = data[off + step2 + 1];
        const Dr = data[off + step3];
        const Di = data[off + step3 + 1];

        // Pre-Final values
        const T0r = Ar + Cr;
        const T0i = Ai + Ci;
        const T1r = Ar - Cr;
        const T1i = Ai - Ci;
        const T2r = Br + Dr;
        const T2i = Bi + Di;
        const T3r = inv * (Br - Dr);
        const T3i = inv * (Bi - Di);

        // Final values
        out[outOff] = T0r + T2r;
        out[outOff + 1] = T0i + T2i;
        out[outOff + 2] = T1r + T3i;
        out[outOff + 3] = T1i - T3r;
        out[outOff + 4] = T0r - T2r;
        out[outOff + 5] = T0i - T2i;
        out[outOff + 6] = T1r - T3i;
        out[outOff + 7] = T1i + T3r;
    }

    /**
     * Real input radix-4 implementation
     * @param {Float64Array} out Output array for the transformed data
     * @param {Float64Array} data Input array of real data to be transformed
     * @param {number} inv The scale factor used to normalize the inverse transform
     */
    _realTransform4(out, data, inv) {
        // Real input radix-4 implementation
        const size = this._csize;

        // Initial step (permute and transform)
        const width = this._width;
        let step = 1 << width;
        let len = (size / step) << 1;

        let outOff;
        let t;
        const bitrev = this._bitrev;
        if (len === 4) {
            for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
                const off = bitrev[t];
                this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1);
            }
        } else {
            // len === 8
            for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
                const off = bitrev[t];
                this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv);
            }
        }

        // Loop through steps in decreasing order
        const table = this.table;
        for (step >>= 2; step >= 2; step >>= 2) {
            len = (size / step) << 1;
            const halfLen = len >>> 1;
            const quarterLen = halfLen >>> 1;
            const hquarterLen = quarterLen >>> 1;

            // Loop through offsets in the data
            for (outOff = 0; outOff < size; outOff += len) {
                for (let i = 0, k = 0; i <= hquarterLen; i += 2, k += step) {
                    const A = outOff + i;
                    const B = A + quarterLen;
                    const C = B + quarterLen;
                    const D = C + quarterLen;

                    // Original values
                    const Ar = out[A];
                    const Ai = out[A + 1];
                    const Br = out[B];
                    const Bi = out[B + 1];
                    const Cr = out[C];
                    const Ci = out[C + 1];
                    const Dr = out[D];
                    const Di = out[D + 1];

                    // Middle values
                    const MAr = Ar;
                    const MAi = Ai;

                    const tableBr = table[k];
                    const tableBi = inv * table[k + 1];
                    const MBr = Br * tableBr - Bi * tableBi;
                    const MBi = Br * tableBi + Bi * tableBr;

                    const tableCr = table[2 * k];
                    const tableCi = inv * table[2 * k + 1];
                    const MCr = Cr * tableCr - Ci * tableCi;
                    const MCi = Cr * tableCi + Ci * tableCr;

                    const tableDr = table[3 * k];
                    const tableDi = inv * table[3 * k + 1];
                    const MDr = Dr * tableDr - Di * tableDi;
                    const MDi = Dr * tableDi + Di * tableDr;

                    // Pre-Final values
                    const T0r = MAr + MCr;
                    const T0i = MAi + MCi;
                    const T1r = MAr - MCr;
                    const T1i = MAi - MCi;
                    const T2r = MBr + MDr;
                    const T2i = MBi + MDi;
                    const T3r = inv * (MBr - MDr);
                    const T3i = inv * (MBi - MDi);

                    // Final values
                    out[A] = T0r + T2r;
                    out[A + 1] = T0i + T2i;
                    out[B] = T1r + T3i;
                    out[B + 1] = T1i - T3r;

                    // Output final middle point
                    if (i === 0) {
                        out[C] = T0r - T2r;
                        out[C + 1] = T0i - T2i;
                        continue;
                    }

                    // Do not overwrite ourselves
                    if (i === hquarterLen)
                        continue;

                    const SA = outOff + quarterLen - i;
                    const SB = outOff + halfLen - i;

                    out[SA] = T1r - inv * T3i;
                    out[SA + 1] = -T1i - inv * T3r;
                    out[SB] = T0r - inv * T2r;
                    out[SB + 1] = -T0i + inv * T2i;
                }
            }
        }

        // Complete the spectrum by adding its mirrored negative frequency components.
        const half = size >>> 1;
        for (let i = 2; i < half; i += 2) {
            out[size - i] = out[i];
            out[size - i + 1] = -out[i + 1];
        }
    }

    /**
     * Performs a single real input radix-2 transformation on the provided data
     * 
     * @param {Float64Array} data The input data array
     * @param {Float64Array} out The output data array
     * @param {number} outOff The output offset
     * @param {number} off The input offset
     * @param {number} step The step
     * 
     * @returns {void}
     */
    _singleRealTransform2(data, out, outOff, off, step) {
        // radix-2 implementation
        // NOTE: Only called for len=4

        const evenR = data[off];
        const oddR = data[off + step];

        out[outOff] = evenR + oddR;
        out[outOff + 1] = 0;
        out[outOff + 2] = evenR - oddR;
        out[outOff + 3] = 0;
    }

    /**
     * Computes a single real-valued transform using radix-4 algorithm.
     * This method is only called for len=8.
     *
     * @param {Float64Array} data The input data array.
     * @param {Float64Array} out The output data array.
     * @param {number} outOff The offset into the output array.
     * @param {number} off The offset into the input array.
     * @param {number} step The step size for the input array.
     * @param {number} inv The value of inverse.
     */
    _singleRealTransform4(data, out, outOff, off, step, inv) {
        // radix-4
        // NOTE: Only called for len=8
        const step2 = step * 2;
        const step3 = step * 3;

        // Original values
        const Ar = data[off];
        const Br = data[off + step];
        const Cr = data[off + step2];
        const Dr = data[off + step3];

        // Pre-Final values
        const T0r = Ar + Cr;
        const T1r = Ar - Cr;
        const T2r = Br + Dr;
        const T3r = inv * (Br - Dr);

        // Final values
        out[outOff] = T0r + T2r;
        out[outOff + 1] = 0;
        out[outOff + 2] = T1r;
        out[outOff + 3] = -T3r;
        out[outOff + 4] = T0r - T2r;
        out[outOff + 5] = 0;
        out[outOff + 6] = T1r;
        out[outOff + 7] = T3r;
    }
}

/**
 * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays
 * which are not a power of two in length. In such cases, the chirp-z transform is used.
 * 
 * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156
 */
class NP2FFT {

    /**
     * Constructs a new NP2FFT object.
     * @param {number} fft_length The length of the FFT
     */
    constructor(fft_length) {
        // Helper variables
        const a = 2 * (fft_length - 1);
        const b = 2 * (2 * fft_length - 1);
        const nextP2 = 2 ** (Math.ceil(Math.log2(b)))
        this.bufferSize = nextP2;
        this._a = a;

        // Define buffers
        // Compute chirp for transform
        const chirp = new Float64Array(b);
        const ichirp = new Float64Array(nextP2);
        this._chirpBuffer = new Float64Array(nextP2);
        this._buffer1 = new Float64Array(nextP2);
        this._buffer2 = new Float64Array(nextP2);
        this._outBuffer1 = new Float64Array(nextP2);
        this._outBuffer2 = new Float64Array(nextP2);

        // Compute complex exponentiation
        const theta = -2 * Math.PI / fft_length;
        const baseR = Math.cos(theta);
        const baseI = Math.sin(theta);

        // Precompute helper for chirp-z transform
        for (let i = 0; i < b >> 1; ++i) {
            // Compute complex power:
            const e = (i + 1 - fft_length) ** 2 / 2.0;

            // Compute the modulus and argument of the result
            const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e;
            const result_arg = e * Math.atan2(baseI, baseR);

            // Convert the result back to rectangular form
            // and assign to chirp and ichirp
            const i2 = 2 * i;
            chirp[i2] = result_mod * Math.cos(result_arg);
            chirp[i2 + 1] = result_mod * Math.sin(result_arg);

            // conjugate
            ichirp[i2] = chirp[i2];
            ichirp[i2 + 1] = - chirp[i2 + 1];
        }
        this._slicedChirpBuffer = chirp.subarray(a, b);

        // create object to perform Fast Fourier Transforms
        // with `nextP2` complex numbers
        this._f = new P2FFT(nextP2 >> 1);
        this._f.transform(this._chirpBuffer, ichirp);
    }

    _transform(output, input, real) {
        const ib1 = this._buffer1;
        const ib2 = this._buffer2;
        const ob2 = this._outBuffer1;
        const ob3 = this._outBuffer2;
        const cb = this._chirpBuffer;
        const sb = this._slicedChirpBuffer;
        const a = this._a;

        if (real) {
            // Real multiplication
            for (let j = 0; j < sb.length; j += 2) {
                const j2 = j + 1
                const j3 = j >> 1;

                const a_real = input[j3];
                ib1[j] = a_real * sb[j];
                ib1[j2] = a_real * sb[j2];
            }
        } else {
            // Complex multiplication
            for (let j = 0; j < sb.length; j += 2) {
                const j2 = j + 1
                ib1[j] = input[j] * sb[j] - input[j2] * sb[j2];
                ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j];
            }
        }
        this._f.transform(ob2, ib1);

        for (let j = 0; j < cb.length; j += 2) {
            const j2 = j + 1;

            ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2];
            ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j];
        }
        this._f.inverseTransform(ob3, ib2);

        for (let j = 0; j < ob3.length; j += 2) {
            const a_real = ob3[j + a];
            const a_imag = ob3[j + a + 1];
            const b_real = sb[j];
            const b_imag = sb[j + 1];

            output[j] = a_real * b_real - a_imag * b_imag;
            output[j + 1] = a_real * b_imag + a_imag * b_real;
        }
    }

    transform(output, input) {
        this._transform(output, input, false);
    }

    realTransform(output, input) {
        this._transform(output, input, true);
    }
}

class FFT {
    constructor(fft_length) {
        this.fft_length = fft_length;
        this.isPowerOfTwo = isPowerOfTwo(fft_length);
        if (this.isPowerOfTwo) {
            this.fft = new P2FFT(fft_length);
            this.outputBufferSize = 2 * fft_length;
        } else {
            this.fft = new NP2FFT(fft_length);
            this.outputBufferSize = this.fft.bufferSize;
        }
    }

    realTransform(out, input) {
        this.fft.realTransform(out, input);
    }

    transform(out, input) {
        this.fft.transform(out, input);
    }
}


/**
 * Performs median filter on the provided data. Padding is done by mirroring the data.
 * @param {AnyTypedArray} data The input array
 * @param {number} windowSize The window size
 */
function medianFilter(data, windowSize) {

    if (windowSize % 2 === 0 || windowSize <= 0) {
        throw new Error('Window size must be a positive odd number');
    }

    // @ts-ignore
    const outputArray = new data.constructor(data.length);

    // @ts-ignore
    const buffer = new data.constructor(windowSize); // Reusable array for storing values

    const halfWindowSize = Math.floor(windowSize / 2);

    for (let i = 0; i < data.length; ++i) {
        let valuesIndex = 0;

        for (let j = -halfWindowSize; j <= halfWindowSize; ++j) {
            let index = i + j;
            if (index < 0) {
                index = Math.abs(index);
            } else if (index >= data.length) {
                index = 2 * (data.length - 1) - index;
            }

            buffer[valuesIndex++] = data[index];
        }

        buffer.sort();
        outputArray[i] = buffer[halfWindowSize];
    }

    return outputArray;
}

/**
 * Helper function to round a number to a given number of decimals
 * @param {number} num The number to round
 * @param {number} decimals The number of decimals
 * @returns {number} The rounded number
 */
function round(num, decimals) {
    const pow = Math.pow(10, decimals);
    return Math.round(num * pow) / pow;
}

/**
 * Helper function to round a number to the nearest integer, with ties rounded to the nearest even number.
 * Also known as "bankers' rounding". This is the default rounding mode in python. For example:
 * 1.5 rounds to 2 and 2.5 rounds to 2.
 * 
 * @param {number} x The number to round
 * @returns {number} The rounded number
 */
function bankers_round(x) {
    const r = Math.round(x);
    const br = Math.abs(x) % 1 === 0.5 ? (r % 2 === 0 ? r : r - 1) : r;
    return br;
}


/***/ }),

/***/ "./src/utils/tensor.js":
/*!*****************************!*\
  !*** ./src/utils/tensor.js ***!
  \*****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Tensor": () => (/* binding */ Tensor),
/* harmony export */   "cat": () => (/* binding */ cat),
/* harmony export */   "dynamicTimeWarping": () => (/* binding */ dynamicTimeWarping),
/* harmony export */   "interpolate": () => (/* binding */ interpolate),
/* harmony export */   "layer_norm": () => (/* binding */ layer_norm),
/* harmony export */   "mean": () => (/* binding */ mean),
/* harmony export */   "mean_pooling": () => (/* binding */ mean_pooling),
/* harmony export */   "ones": () => (/* binding */ ones),
/* harmony export */   "ones_like": () => (/* binding */ ones_like),
/* harmony export */   "permute": () => (/* binding */ permute),
/* harmony export */   "quantize_embeddings": () => (/* binding */ quantize_embeddings),
/* harmony export */   "stack": () => (/* binding */ stack),
/* harmony export */   "std_mean": () => (/* binding */ std_mean)
/* harmony export */ });
/* harmony import */ var _backends_onnx_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../backends/onnx.js */ "./src/backends/onnx.js");
/* harmony import */ var _maths_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./maths.js */ "./src/utils/maths.js");
/**
 * @file Helper module for `Tensor` processing.
 * 
 * These functions and classes are only used internally, 
 * meaning an end-user shouldn't need to access anything here.
 * 
 * @module utils/tensor
 */






const DataTypeMap = Object.freeze({
    float32: Float32Array,
    float64: Float64Array,
    string: Array, // string[]
    int8: Int8Array,
    uint8: Uint8Array,
    int16: Int16Array,
    uint16: Uint16Array,
    int32: Int32Array,
    uint32: Uint32Array,
    int64: BigInt64Array,
    uint64: BigUint64Array,
    bool: Uint8Array,
});

/**
 * @typedef {keyof typeof DataTypeMap} DataType
 * @typedef {import('./maths.js').AnyTypedArray | any[]} DataArray
 */

const ONNXTensor = _backends_onnx_js__WEBPACK_IMPORTED_MODULE_0__.ONNX.Tensor;

class Tensor {
    /** @type {number[]} Dimensions of the tensor. */
    dims;

    /** @type {DataType} Type of the tensor. */
    type;

    /** @type {DataArray} The data stored in the tensor. */
    data;

    /** @type {number} The number of elements in the tensor. */
    size;

    /**
     * Create a new Tensor or copy an existing Tensor.
     * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
     */
    constructor(...args) {
        if (args[0] instanceof ONNXTensor) {
            // Create shallow copy
            Object.assign(this, args[0]);

        } else {
            // Create new tensor
            Object.assign(this, new ONNXTensor(
                /** @type {DataType} */(args[0]),
                /** @type {Exclude<import('./maths.js').AnyTypedArray, Uint8ClampedArray>} */(args[1]),
                args[2]
            ));
        }

        return new Proxy(this, {
            get: (obj, key) => {
                if (typeof key === 'string') {
                    let index = Number(key);
                    if (Number.isInteger(index)) {
                        // key is an integer (i.e., index)
                        return obj._getitem(index);
                    }
                }
                // @ts-ignore
                return obj[key];
            },
            set: (obj, key, value) => {
                // TODO allow setting of data

                // @ts-ignore
                return obj[key] = value;
            }
        });
    }

    /**
     * Returns an iterator object for iterating over the tensor data in row-major order.
     * If the tensor has more than one dimension, the iterator will yield subarrays.
     * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
     */
    *[Symbol.iterator]() {
        const [iterLength, ...iterDims] = this.dims;

        if (iterDims.length > 0) {
            const iterSize = iterDims.reduce((a, b) => a * b);
            for (let i = 0; i < iterLength; ++i) {
                yield this._subarray(i, iterSize, iterDims);
            }
        } else {
            yield* this.data
        }

    }

    /**
     * Index into a Tensor object.
     * @param {number} index The index to access.
     * @returns {Tensor} The data at the specified index.
     */
    _getitem(index) {
        const [iterLength, ...iterDims] = this.dims;

        index = safeIndex(index, iterLength);

        if (iterDims.length > 0) {
            const iterSize = iterDims.reduce((a, b) => a * b);
            return this._subarray(index, iterSize, iterDims);
        } else {
            return new Tensor(this.type, [this.data[index]], iterDims);
        }
    }

    /**
     * @param {number|bigint} item The item to search for in the tensor
     * @returns {number} The index of the first occurrence of item in the tensor data.
     */
    indexOf(item) {
        for (let index = 0; index < this.data.length; ++index) {
            // Note: == instead of === so we can match Ints with BigInts
            if (this.data[index] == item) {
                return index;
            }
        }
        return -1;
    }

    /**
     * @param {number} index 
     * @param {number} iterSize 
     * @param {any} iterDims 
     * @returns {Tensor}
     */
    _subarray(index, iterSize, iterDims) {
        const o1 = index * iterSize;
        const o2 = (index + 1) * iterSize;

        // We use subarray if available (typed array), otherwise we use slice (normal array)
        const data =
            ('subarray' in this.data)
                ? this.data.subarray(o1, o2)
                : this.data.slice(o1, o2);
        return new Tensor(this.type, data, iterDims);
    }

    /**
     * Returns the value of this tensor as a standard JavaScript Number. This only works
     * for tensors with one element. For other cases, see `Tensor.tolist()`.
     * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
     * @throws {Error} If the tensor has more than one element.
     */
    item() {
        if (this.data.length !== 1) {
            throw new Error(`a Tensor with ${this.data.length} elements cannot be converted to Scalar`);
        }
        return this.data[0];
    }

    /**
     * Convert tensor data to a n-dimensional JS list
     * @returns {Array}
     */
    tolist() {
        return reshape(this.data, this.dims)
    }

    /**
     * Return a new Tensor with the sigmoid function applied to each element.
     * @returns {Tensor} The tensor with the sigmoid function applied.
     */
    sigmoid() {
        return this.clone().sigmoid_();
    }

    /**
     * Applies the sigmoid function to the tensor in place.
     * @returns {Tensor} Returns `this`.
     */
    sigmoid_() {
        for (let i = 0; i < this.data.length; ++i) {
            this.data[i] = 1 / (1 + Math.exp(-this.data[i]));
        }
        return this;
    }

    /**
     * Return a new Tensor with every element multiplied by a constant.
     * @param {number} val The value to multiply by.
     * @returns {Tensor} The new tensor.
     */
    mul(val) {
        return this.clone().mul_(val);
    }

    /**
     * Multiply the tensor by a constant in place.
     * @param {number} val The value to multiply by.
     * @returns {Tensor} Returns `this`.
     */
    mul_(val) {
        for (let i = 0; i < this.data.length; ++i) {
            this.data[i] *= val;
        }
        return this;
    }


    /**
     * Return a new Tensor with every element added by a constant.
     * @param {number} val The value to add by.
     * @returns {Tensor} The new tensor.
     */
    add(val) {
        return this.clone().add_(val);
    }

    /**
     * Add the tensor by a constant in place.
     * @param {number} val The value to add by.
     * @returns {Tensor} Returns `this`.
     */
    add_(val) {
        for (let i = 0; i < this.data.length; ++i) {
            this.data[i] += val;
        }
        return this;
    }
    clone() {
        return new Tensor(this.type, this.data.slice(), this.dims.slice());
    }

    slice(...slices) {
        // This allows for slicing with ranges and numbers
        let newTensorDims = [];
        let newOffsets = [];

        // slices is an array of numbers or arrays of numbers
        // e.g., slices = [0, [1, 3], null, [0, 3]]
        for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {
            let slice = slices[sliceIndex];

            if (slice === null || slice === undefined) {
                // null or undefined means take the whole dimension
                newOffsets.push([0, this.dims[sliceIndex]]);
                newTensorDims.push(this.dims[sliceIndex]);

            } else if (typeof slice === 'number') {
                slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);

                // A number means take a single element
                newOffsets.push([slice, slice + 1]);

            } else if (Array.isArray(slice) && slice.length === 2) {
                // An array of length 2 means take a range of elements

                if (slice[0] > slice[1]) {
                    throw new Error(`Invalid slice: ${slice}`);
                }

                let offsets = [
                    Math.max(slice[0], 0),
                    Math.min(slice[1], this.dims[sliceIndex])
                ];

                newOffsets.push(offsets);
                newTensorDims.push(offsets[1] - offsets[0]);

            } else {
                throw new Error(`Invalid slice: ${slice}`);
            }
        }

        let newDims = newOffsets.map(([start, end]) => end - start);
        let newBufferSize = newDims.reduce((a, b) => a * b);

        // Allocate memory
        // @ts-ignore
        let data = new this.data.constructor(newBufferSize);

        // Precompute strides
        const stride = this.stride();

        for (let i = 0; i < newBufferSize; ++i) {
            let originalIndex = 0;
            for (let j = newDims.length - 1, num = i; j >= 0; --j) {
                const size = newDims[j];
                originalIndex += ((num % size) + newOffsets[j][0]) * stride[j];
                num = Math.floor(num / size);
            }
            data[i] = this.data[originalIndex];
        }
        return new Tensor(this.type, data, newTensorDims);

    }

    /**
     * Return a permuted version of this Tensor, according to the provided dimensions.
     * @param  {...number} dims Dimensions to permute.
     * @returns {Tensor} The permuted tensor.
     */
    permute(...dims) {
        return permute(this, dims);
    }

    // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute()
    transpose(...dims) {
        return this.permute(...dims);
    }

    // TODO add .max() and .min() methods

    /**
     * Returns the sum of each row of the input tensor in the given dimension dim.
     * 
     * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
     * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
     * @returns The summed tensor
     */
    sum(dim = null, keepdim = false) {
        return this.norm(1, dim, keepdim);
    }

    /**
     * Returns the matrix norm or vector norm of a given tensor.
     * @param {number|string} [p='fro'] The order of norm
     * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
     * If dim is None, the norm will be calculated across all dimensions of input.
     * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
     * @returns {Tensor} The norm of the tensor.
     */
    norm(p = 'fro', dim = null, keepdim = false) {
        if (p === 'fro') {
            // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2.
            p = 2;
        } else if (typeof p === 'string') {
            throw Error(`Unsupported norm: ${p}`);
        }

        if (dim === null) {
            // @ts-ignore
            let val = this.data.reduce((a, b) => a + (b ** p), 0) ** (1 / p);
            return new Tensor(this.type, [val], []);
        }

        // Negative indexing
        dim = safeIndex(dim, this.dims.length);

        // Calculate the shape of the resulting array after summation
        const resultDims = this.dims.slice(); // Copy the original dimensions
        resultDims[dim] = 1; // Remove the specified axis

        // Create a new array to store the accumulated values
        // @ts-ignore
        const result = new this.data.constructor(this.data.length / this.dims[dim]);

        // Iterate over the data array
        for (let i = 0; i < this.data.length; ++i) {

            // Calculate the index in the resulting array
            let resultIndex = 0;

            for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
                const size = this.dims[j];
                if (j !== dim) {
                    const index = num % size;
                    resultIndex += index * resultMultiplier;
                    resultMultiplier *= resultDims[j];
                }
                num = Math.floor(num / size);
            }

            // Accumulate the value at the current index
            result[resultIndex] += (this.data[i]) ** p;
        }

        if (p !== 1) {
            for (let i = 0; i < result.length; ++i) {
                result[i] = result[i] ** (1 / p);
            }
        }

        if (!keepdim) {
            resultDims.splice(dim, 1);
        }

        return new Tensor(this.type, result, resultDims);
    }

    /**
     * Performs `L_p` normalization of inputs over specified dimension. Operates in place.
     * @param {number} [p=2] The exponent value in the norm formulation
     * @param {number} [dim=1] The dimension to reduce
     * @returns {Tensor} `this` for operation chaining.
     */
    normalize_(p = 2.0, dim = 1) {
        dim = safeIndex(dim, this.dims.length);

        const norm = this.norm(p, dim, true);

        for (let i = 0; i < this.data.length; ++i) {

            // Calculate the index in the resulting array
            let resultIndex = 0;

            for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
                const size = this.dims[j];
                if (j !== dim) {
                    const index = num % size;
                    resultIndex += index * resultMultiplier;
                    resultMultiplier *= this.dims[j];
                }
                num = Math.floor(num / size);
            }

            // Divide by normalized value
            this.data[i] /= norm.data[resultIndex];
        }

        return this;
    }

    /**
     * Performs `L_p` normalization of inputs over specified dimension.
     * @param {number} [p=2] The exponent value in the norm formulation
     * @param {number} [dim=1] The dimension to reduce
     * @returns {Tensor} The normalized tensor.
     */
    normalize(p = 2.0, dim = 1) {
        return this.clone().normalize_(p, dim);
    }

    /**
     * Compute and return the stride of this tensor.
     * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
     * @returns {number[]} The stride of this tensor.
     */
    stride() {
        return dimsToStride(this.dims);
    }

    /**
     * Returns a tensor with all specified dimensions of input of size 1 removed.
     * 
     * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
     * If you would like a copy, use `tensor.clone()` before squeezing.
     * 
     * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.
     * @returns The squeezed tensor
     */
    squeeze(dim = null) {
        return new Tensor(
            this.type,
            this.data,
            calc_squeeze_dims(this.dims, dim)
        )
    }

    /**
     * In-place version of @see {@link Tensor.squeeze}
     */
    squeeze_(dim = null) {
        this.dims = calc_squeeze_dims(this.dims, dim);
        return this;
    }

    /**
     * Returns a new tensor with a dimension of size one inserted at the specified position.
     * 
     * NOTE: The returned tensor shares the same underlying data with this tensor.
     * 
     * @param {number} dim The index at which to insert the singleton dimension
     * @returns The unsqueezed tensor
     */
    unsqueeze(dim = null) {
        return new Tensor(
            this.type,
            this.data,
            calc_unsqueeze_dims(this.dims, dim)
        );
    }

    /**
     * In-place version of @see {@link Tensor.unsqueeze}
     */
    unsqueeze_(dim = null) {
        this.dims = calc_unsqueeze_dims(this.dims, dim);
        return this;
    }

    /**
     * In-place version of @see {@link Tensor.flatten}
     */
    flatten_(start_dim = 0, end_dim = -1) {
        // TODO validate inputs
        end_dim = (end_dim + this.dims.length) % this.dims.length;

        let dimsToKeepBefore = this.dims.slice(0, start_dim);
        let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);
        let dimsToKeepAfter = this.dims.slice(end_dim + 1);

        this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]
        return this;
    }

    /**
     * Flattens input by reshaping it into a one-dimensional tensor.
     * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
     * and ending with `end_dim` are flattened. The order of elements in input is unchanged.
     * @param {number} start_dim the first dim to flatten
     * @param {number} end_dim the last dim to flatten
     * @returns The flattened tensor.
     */
    flatten(start_dim = 0, end_dim = -1) {
        return this.clone().flatten_(start_dim, end_dim);
    }

    /**
     * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
     * @param  {...number} dims the desired size
     * @returns {Tensor} The tensor with the same data but different shape
     */
    view(...dims) {
        // TODO: validate dims
        let inferredIndex = -1;
        for (let i = 0; i < dims.length; ++i) {
            if (dims[i] === -1) {
                if (inferredIndex !== -1) {
                    throw new Error("Only one dimension can be inferred");
                }
                inferredIndex = i;
            }
        }

        if (inferredIndex !== -1) {
            // Some dimension must be inferred
            const productOther = dims.reduce((product, curr, index) => {
                return index !== inferredIndex ? product * curr : product
            }, 1);

            dims[inferredIndex] = this.data.length / productOther;
        }
        return new Tensor(this.type, this.data, dims); // NOTE: uses same underlying storage
    }

    neg_() {
        for (let i = 0; i < this.data.length; ++i) {
            this.data[i] = -this.data[i];
        }
        return this;
    }
    neg() {
        return this.clone().neg_();
    }

    /**
     * In-place version of @see {@link Tensor.clamp}
     */
    clamp_(min, max) {
        for (let i = 0; i < this.data.length; ++i) {
            this.data[i] = Math.min(Math.max(this.data[i], min), max);
        }
        return this;
    }

    /**
     * Clamps all elements in input into the range [ min, max ]
     * @param {number} min lower-bound of the range to be clamped to
     * @param {number} max upper-bound of the range to be clamped to
     * @returns the output tensor.
     */
    clamp(min, max) {
        return this.clone().clamp_(min, max);
    }

    /**
     * In-place version of @see {@link Tensor.round}
     */
    round_() {
        for (let i = 0; i < this.data.length; ++i) {
            this.data[i] = Math.round(this.data[i]);
        }
        return this;
    }

    /**
     * Rounds elements of input to the nearest integer.
     * @returns the output tensor.
     */
    round() {
        return this.clone().round_();
    }

    /**
     * Performs Tensor dtype conversion.
     * @param {DataType} type The desired data type.
     * @returns {Tensor} The converted tensor.
     */
    to(type) {
        // If the self Tensor already has the correct dtype, then self is returned.
        if (this.type === type) return this;

        // Otherwise, the returned tensor is a copy of self with the desired dtype.
        if (!DataTypeMap.hasOwnProperty(type)) {
            throw new Error(`Unsupported type: ${type}`);
        }
        // @ts-ignore
        return new Tensor(type, DataTypeMap[type].from(this.data), this.dims);
    }
}

/**
 * This creates a nested array of a given type and depth (see examples).
 * 
 * @example
 *   NestArray<string, 1>; // string[]
 * @example
 *   NestArray<number, 2>; // number[][]
 * @example
 *   NestArray<string, 3>; // string[][][] etc.
 * @template T
 * @template {number} Depth
 * @template {never[]} [Acc=[]]
 * @typedef {Acc['length'] extends Depth ? T : NestArray<T[], Depth, [...Acc, never]>} NestArray
 */

/**
 * Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions.
 *
 * @example
 *   reshape([10                    ], [1      ]); // Type: number[]      Value: [10]
 *   reshape([1, 2, 3, 4            ], [2, 2   ]); // Type: number[][]    Value: [[1, 2], [3, 4]]
 *   reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][]  Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
 *   reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2   ]); // Type: number[][]    Value: [[1, 2], [3, 4], [5, 6], [7, 8]]
 * @param {T[]|DataArray} data The input array to reshape.
 * @param {DIM} dimensions The target shape/dimensions.
 * @template T
 * @template {[number]|number[]} DIM
 * @returns {NestArray<T, DIM["length"]>} The reshaped array.
 */
function reshape(data, dimensions) {

    const totalElements = data.length;
    const dimensionSize = dimensions.reduce((a, b) => a * b);

    if (totalElements !== dimensionSize) {
        throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`);
    }

    /** @type {any} */
    let reshapedArray = data;

    for (let i = dimensions.length - 1; i >= 0; i--) {
        reshapedArray = reshapedArray.reduce((acc, val) => {
            let lastArray = acc[acc.length - 1];

            if (lastArray.length < dimensions[i]) {
                lastArray.push(val);
            } else {
                acc.push([val]);
            }

            return acc;
        }, [[]]);
    }

    return reshapedArray[0];
}

/**
 * Permutes a tensor according to the provided axes.
 * @param {any} tensor The input tensor to permute.
 * @param {Array} axes The axes to permute the tensor along.
 * @returns {Tensor} The permuted tensor.
 */
function permute(tensor, axes) {
    const [permutedData, shape] = (0,_maths_js__WEBPACK_IMPORTED_MODULE_1__.permute_data)(tensor.data, tensor.dims, axes);
    return new Tensor(tensor.type, permutedData, shape);
}


/**
 * Interpolates an Tensor to the given size.
 * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w])
 * @param {number[]} size The output size of the image
 * @param {string} mode The interpolation mode
 * @param {boolean} align_corners Whether to align corners.
 * @returns {Tensor} The interpolated tensor.
 */
function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) {

    // Input image dimensions
    const in_channels = input.dims.at(-3) ?? 1;
    const in_height = input.dims.at(-2);
    const in_width = input.dims.at(-1);

    let output = (0,_maths_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_data)(
        /** @type {import('./maths.js').TypedArray}*/(input.data),
        [in_channels, in_height, in_width],
        [out_height, out_width],
        mode,
        align_corners
    );
    return new Tensor(input.type, output, [in_channels, out_height, out_width]);
}

/**
 * Perform mean pooling of the last hidden state followed by a normalization step.
 * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim]
 * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength]
 * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].
 */
function mean_pooling(last_hidden_state, attention_mask) {
    // last_hidden_state: [batchSize, seqLength, embedDim]
    // attention_mask:    [batchSize, seqLength]

    let shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];
    // @ts-ignore
    let returnedData = new last_hidden_state.data.constructor(shape[0] * shape[1]);
    let [batchSize, seqLength, embedDim] = last_hidden_state.dims;

    let outIndex = 0;
    for (let i = 0; i < batchSize; ++i) {
        let offset = i * embedDim * seqLength;

        for (let k = 0; k < embedDim; ++k) {
            let sum = 0;
            let count = 0;

            let attnMaskOffset = i * seqLength;
            let offset2 = offset + k;
            // Pool over all words in sequence
            for (let j = 0; j < seqLength; ++j) {
                // index into attention mask
                let attn = Number(attention_mask.data[attnMaskOffset + j]);

                count += attn;
                sum += last_hidden_state.data[offset2 + j * embedDim] * attn;
            }

            let avg = sum / count;
            returnedData[outIndex++] = avg;
        }
    }

    return new Tensor(
        last_hidden_state.type,
        returnedData,
        shape
    )
}

/**
 * Apply Layer Normalization for last certain number of dimensions.
 * @param {Tensor} input The input tensor
 * @param {number[]} normalized_shape input shape from an expected input of size
 * @param {Object} options The options for the layer normalization
 * @param {number} [options.eps=1e-5] A value added to the denominator for numerical stability.
 * @returns {Tensor} The normalized tensor.
 */
function layer_norm(input, normalized_shape, {
    eps = 1e-5,
} = {}) {
    if (input.dims.length !== 2) {
        throw new Error('`layer_norm` currently only supports 2D input.');
    }

    const [batchSize, featureDim] = input.dims;

    if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) {
        throw new Error('`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.');
    }

    const [std, mean] = std_mean(input, 1, 0, true);

    // @ts-ignore
    const returnedData = new input.data.constructor(input.data.length);

    for (let i = 0; i < batchSize; ++i) {
        const offset = i * featureDim;
        for (let j = 0; j < featureDim; ++j) {
            const offset2 = offset + j;
            returnedData[offset2] = (input.data[offset2] - mean.data[i]) / (std.data[i] + eps);
        }
    }
    return new Tensor(input.type, returnedData, input.dims);
}

/**
 * Helper function to calculate new dimensions when performing a squeeze operation.
 * @param {number[]} dims The dimensions of the tensor.
 * @param {number|number[]|null} dim The dimension(s) to squeeze.
 * @returns The new dimensions.
 * @private
 */
function calc_squeeze_dims(dims, dim) {
    dims = dims.slice();
    if (dim === null) {
        dims = dims.filter((d) => d !== 1);
    } else if (typeof dim === 'number') {
        if (dims[dim] === 1) {
            dims.splice(dim, 1);
        }
    } else if (Array.isArray(dim)) {
        dims = dims.filter((x, i) => {
            return x !== 1 || !dim.includes(i);
        });
    }
    return dims;
}

/**
 * Helper function to calculate new dimensions when performing an unsqueeze operation.
 * @param {number[]} dims The dimensions of the tensor.
 * @param {number} dim The dimension to unsqueeze.
 * @returns The new dimensions.
 * @private
 */
function calc_unsqueeze_dims(dims, dim) {
    // Dimension out of range (e.g., "expected to be in range of [-4, 3], but got 4")
    // + 1 since we allow inserting at the end (i.e. dim = -1)
    dim = safeIndex(dim, dims.length + 1);
    dims = dims.slice();
    // Insert 1 into specified dimension
    dims.splice(dim, 0, 1);
    return dims;
}

/**
 * Safely calculate the index for an array of a given size, allowing negative indexing.
 * @param {number} index The index that will be used.
 * @param {number} size The size of the array.
 * @param {number} [dimension=null] The dimension that the index is for (optional).
 * @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`.
 * 
 * @throws {Error} If the index is out of range.
 * @private
 */
function safeIndex(index, size, dimension = null) {
    if (index < -size || index >= size) {
        throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`);
    }

    if (index < 0) {
        // Negative indexing, ensuring positive index
        index = ((index % size) + size) % size;
    }
    return index;
}

/**
 * Concatenates an array of tensors along a specified dimension.
 * @param {Tensor[]} tensors The array of tensors to concatenate.
 * @param {number} dim The dimension to concatenate along.
 * @returns {Tensor} The concatenated tensor.
 */
function cat(tensors, dim = 0) {
    dim = safeIndex(dim, tensors[0].dims.length);

    // TODO do validation of shapes

    const resultDims = tensors[0].dims.slice();
    resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);

    // Create a new array to store the accumulated values
    const resultSize = resultDims.reduce((a, b) => a * b, 1);
    // @ts-ignore
    const result = new tensors[0].data.constructor(resultSize);

    // Create output tensor of same type as first
    const resultType = tensors[0].type;

    if (dim === 0) {
        // Handle special case for performance reasons

        let offset = 0;
        for (let t of tensors) {
            result.set(t.data, offset);
            offset += t.data.length;
        }

    } else {

        let currentDim = 0;

        for (let t = 0; t < tensors.length; ++t) {
            let tensor = tensors[t];

            // Iterate over the data array
            for (let i = 0; i < tensor.data.length; ++i) {
                // Calculate the index in the resulting array
                let resultIndex = 0;

                for (let j = tensor.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
                    const size = tensor.dims[j];
                    let index = num % size;
                    if (j === dim) {
                        index += currentDim;
                    }
                    resultIndex += index * resultMultiplier;
                    resultMultiplier *= resultDims[j];
                    num = Math.floor(num / size);
                }
                // Accumulate the value at the current index
                result[resultIndex] = tensor.data[i];
            }

            currentDim += tensor.dims[dim];
        }
    }
    return new Tensor(resultType, result, resultDims);
}

/**
 * Stack an array of tensors along a specified dimension.
 * @param {Tensor[]} tensors The array of tensors to stack.
 * @param {number} dim The dimension to stack along.
 * @returns {Tensor} The stacked tensor.
 */
function stack(tensors, dim = 0) {
    // TODO do validation of shapes
    // NOTE: stack expects each tensor to be equal size
    return cat(tensors.map(t => t.unsqueeze(dim)), dim);
}


/**
 * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions.
 * @param {Tensor} input the input tenso
 * @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced.
 * @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1.
 * @param {boolean} keepdim whether the output tensor has dim retained or not.
 * @returns {Tensor[]} A tuple of (std, mean) tensors.
 */
function std_mean(input, dim = null, correction = 1, keepdim = false) {

    if (dim === null) {
        // None to reduce over all dimensions.
        // @ts-ignore
        const sum = input.data.reduce((a, b) => a + b, 0);
        const mean = sum / input.data.length;
        // @ts-ignore
        const std = Math.sqrt(input.data.reduce((a, b) => a + (b - mean) ** 2, 0) / (input.data.length - correction));

        const meanTensor = new Tensor(input.type, [mean], [/* scalar */]);
        const stdTensor = new Tensor(input.type, [std], [/* scalar */]);

        return [stdTensor, meanTensor];
    }

    // Negative indexing
    dim = safeIndex(dim, input.dims.length);

    const meanTensor = mean(input, dim, keepdim);

    // Calculate the shape of the resulting array after summation
    const resultDims = input.dims.slice(); // Copy the original dimensions
    resultDims[dim] = 1; // Remove the specified axis

    // Create a new array to store the accumulated values
    // @ts-ignore
    const result = new input.data.constructor(input.data.length / input.dims[dim]);

    // Iterate over the data array
    for (let i = 0; i < input.data.length; ++i) {

        // Calculate the index in the resulting array
        let resultIndex = 0;

        for (let j = input.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
            const size = input.dims[j];
            if (j !== dim) {
                const index = num % size;
                resultIndex += index * resultMultiplier;
                resultMultiplier *= resultDims[j];
            }
            num = Math.floor(num / size);
        }

        // Accumulate the value at the current index
        result[resultIndex] += (input.data[i] - meanTensor.data[resultIndex]) ** 2;
    }

    for (let i = 0; i < result.length; ++i) {
        result[i] = Math.sqrt(result[i] / (input.dims[dim] - correction));
    }

    if (!keepdim) {
        resultDims.splice(dim, 1);
    }

    const stdTensor = new Tensor(input.type, result, resultDims);

    return [stdTensor, meanTensor];
}


/**
 * Returns the mean value of each row of the input tensor in the given dimension dim.
 * @param {Tensor} input the input tensor.
 * @param {number|null} dim the dimension to reduce.
 * @param {boolean} keepdim whether the output tensor has dim retained or not.
 * @returns A new tensor with means taken along the specified dimension.
 */
function mean(input, dim = null, keepdim = false) {

    if (dim === null) {
        // None to reduce over all dimensions.
        // @ts-ignore
        let val = input.data.reduce((a, b) => a + b, 0);
        return new Tensor(input.type, [val / input.data.length], [/* scalar */]);
    }

    // Negative indexing
    dim = safeIndex(dim, input.dims.length);

    // Calculate the shape of the resulting array after summation
    const resultDims = input.dims.slice(); // Copy the original dimensions
    resultDims[dim] = 1; // Remove the specified axis

    // Create a new array to store the accumulated values
    // @ts-ignore
    const result = new input.data.constructor(input.data.length / input.dims[dim]);

    // Iterate over the data array
    for (let i = 0; i < input.data.length; ++i) {

        // Calculate the index in the resulting array
        let resultIndex = 0;

        for (let j = input.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
            const size = input.dims[j];
            if (j !== dim) {
                const index = num % size;
                resultIndex += index * resultMultiplier;
                resultMultiplier *= resultDims[j];
            }
            num = Math.floor(num / size);
        }

        // Accumulate the value at the current index
        result[resultIndex] += input.data[i];
    }

    if (input.dims[dim] !== 1) {
        for (let i = 0; i < result.length; ++i) {
            result[i] = result[i] / input.dims[dim];
        }
    }

    if (!keepdim) {
        resultDims.splice(dim, 1);
    }

    return new Tensor(input.type, result, resultDims);
}


/**
 *
 * Measures similarity between two temporal sequences (e.g., input audio and output tokens
 * to generate token-level timestamps).
 * @param {Tensor} matrix 
 * @returns {number[][]}
 */
function dynamicTimeWarping(matrix) {
    const [output_length, input_length] = matrix.dims;

    const outputShape = [output_length + 1, input_length + 1];

    const cost = new Tensor(
        'float32',
        new Float32Array(outputShape[0] * outputShape[1]).fill(Infinity),
        outputShape
    );

    const trace = new Tensor(
        'float32',
        new Float32Array(outputShape[0] * outputShape[1]).fill(-1),
        outputShape
    )

    // same as `cost[0][0] = 0`;
    cost[0].data[0] = 0;

    for (let j = 1; j < input_length + 1; ++j) {
        for (let i = 1; i < output_length + 1; ++i) {

            const c0 = cost[i - 1][j - 1].item();
            const c1 = cost[i - 1][j].item();
            const c2 = cost[i][j - 1].item();

            let c, t;
            if (c0 < c1 && c0 < c2) {
                c = c0;
                t = 0;
            } else if (c1 < c0 && c1 < c2) {
                c = c1;
                t = 1;
            } else {
                c = c2;
                t = 2;
            }

            cost[i].data[j] = matrix[i - 1][j - 1].item() + c;
            trace[i].data[j] = t;
        }
    }

    // backtrace
    let i = output_length;
    let j = input_length;

    // @ts-ignore
    trace.data.fill(2, 0, outputShape[1]) // trace[0, :] = 2
    for (let i = 0; i < outputShape[0]; ++i) { // trace[:, 0] = 1
        trace[i].data[0] = 1;
    }

    let text_indices = [];
    let time_indices = [];

    while (i > 0 || j > 0) {
        text_indices.push(i - 1);
        time_indices.push(j - 1);

        const t = trace[i][j].item();
        switch (t) {
            case 0:
                --i; --j;
                break;
            case 1:
                --i;
                break;
            case 2:
                --j;
                break;
            default:
                throw new Error(
                    `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.`
                )
        }
    }

    text_indices.reverse();
    time_indices.reverse();

    return [text_indices, time_indices];

}

function dimsToStride(dims) {
    const stride = new Array(dims.length);
    for (let i = dims.length - 1, s2 = 1; i >= 0; --i) {
        stride[i] = s2;
        s2 *= dims[i];
    }
    return stride;
}

/**
 * Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.
 * @param {number[]} size A sequence of integers defining the shape of the output tensor.
 */
function ones(size) {
    const numElements = size.reduce((a, b) => a * b, 1);
    return new Tensor(
        'int64',
        new BigInt64Array(numElements).fill(1n),
        size
    )
}

/**
 * Returns a tensor filled with the scalar value 1, with the same size as input.
 * @param {Tensor} tensor The size of input will determine size of the output tensor.
 * @returns The ones tensor.
 */
function ones_like(tensor) {
    return ones(tensor.dims);
}

/**
 * Quantizes the embeddings tensor to binary or unsigned binary precision.
 * @param {Tensor} tensor The tensor to quantize.
 * @param {'binary'|'ubinary'} precision The precision to use for quantization.
 * @returns {Tensor} The quantized tensor.
 */
function quantize_embeddings(tensor, precision) {
    if (tensor.dims.length !== 2) {
        throw new Error("The tensor must have 2 dimensions");
    }
    if (tensor.dims.at(-1) % 8 !== 0) {
        throw new Error("The last dimension of the tensor must be a multiple of 8");
    }
    if (!['binary', 'ubinary'].includes(precision)) {
        throw new Error("The precision must be either 'binary' or 'ubinary'");
    }

    const signed = precision === 'binary';
    const dtype = signed ? 'int8' : 'uint8';

    // Create a typed array to store the packed bits
    const cls = signed ? Int8Array : Uint8Array;
    const inputData = tensor.data;
    const outputData = new cls(inputData.length / 8);

    // Iterate over each number in the array
    for (let i = 0; i < inputData.length; ++i) {
        // Determine if the number is greater than 0
        const bit = inputData[i] > 0 ? 1 : 0;

        // Calculate the index in the typed array and the position within the byte
        const arrayIndex = Math.floor(i / 8);
        const bitPosition = i % 8;

        // Pack the bit into the typed array
        outputData[arrayIndex] |= bit << (7 - bitPosition);
        if (signed && bitPosition === 0) {
            outputData[arrayIndex] -= 128;
        }
    };

    return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]);
}


/***/ })

/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/ 
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ 	// Check if module is in cache
/******/ 	var cachedModule = __webpack_module_cache__[moduleId];
/******/ 	if (cachedModule !== undefined) {
/******/ 		return cachedModule.exports;
/******/ 	}
/******/ 	// Create a new module (and put it into the cache)
/******/ 	var module = __webpack_module_cache__[moduleId] = {
/******/ 		// no module.id needed
/******/ 		// no module.loaded needed
/******/ 		exports: {}
/******/ 	};
/******/ 
/******/ 	// Execute the module function
/******/ 	__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 
/******/ 	// Return the exports of the module
/******/ 	return module.exports;
/******/ }
/******/ 
/************************************************************************/
/******/ /* webpack/runtime/create fake namespace object */
/******/ (() => {
/******/ 	var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);
/******/ 	var leafPrototypes;
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 16: return value when it's Promise-like
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = this(value);
/******/ 		if(mode & 8) return value;
/******/ 		if(typeof value === 'object' && value) {
/******/ 			if((mode & 4) && value.__esModule) return value;
/******/ 			if((mode & 16) && typeof value.then === 'function') return value;
/******/ 		}
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		var def = {};
/******/ 		leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
/******/ 		for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
/******/ 			Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));
/******/ 		}
/******/ 		def['default'] = () => (value);
/******/ 		__webpack_require__.d(ns, def);
/******/ 		return ns;
/******/ 	};
/******/ })();
/******/ 
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ 	// define getter functions for harmony exports
/******/ 	__webpack_require__.d = (exports, definition) => {
/******/ 		for(var key in definition) {
/******/ 			if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 				Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 			}
/******/ 		}
/******/ 	};
/******/ })();
/******/ 
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ 	__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/ 
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = (exports) => {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/ })();
/******/ 
/************************************************************************/
/******/ 
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module is referenced by other modules so it can't be inlined
/******/ var __webpack_exports__ = __webpack_require__("./src/transformers.js");
/******/ var __webpack_exports__ASTFeatureExtractor = __webpack_exports__.ASTFeatureExtractor;
/******/ var __webpack_exports__ASTForAudioClassification = __webpack_exports__.ASTForAudioClassification;
/******/ var __webpack_exports__ASTModel = __webpack_exports__.ASTModel;
/******/ var __webpack_exports__ASTPreTrainedModel = __webpack_exports__.ASTPreTrainedModel;
/******/ var __webpack_exports__AlbertForMaskedLM = __webpack_exports__.AlbertForMaskedLM;
/******/ var __webpack_exports__AlbertForQuestionAnswering = __webpack_exports__.AlbertForQuestionAnswering;
/******/ var __webpack_exports__AlbertForSequenceClassification = __webpack_exports__.AlbertForSequenceClassification;
/******/ var __webpack_exports__AlbertModel = __webpack_exports__.AlbertModel;
/******/ var __webpack_exports__AlbertPreTrainedModel = __webpack_exports__.AlbertPreTrainedModel;
/******/ var __webpack_exports__AlbertTokenizer = __webpack_exports__.AlbertTokenizer;
/******/ var __webpack_exports__AudioClassificationPipeline = __webpack_exports__.AudioClassificationPipeline;
/******/ var __webpack_exports__AutoConfig = __webpack_exports__.AutoConfig;
/******/ var __webpack_exports__AutoModel = __webpack_exports__.AutoModel;
/******/ var __webpack_exports__AutoModelForAudioClassification = __webpack_exports__.AutoModelForAudioClassification;
/******/ var __webpack_exports__AutoModelForAudioFrameClassification = __webpack_exports__.AutoModelForAudioFrameClassification;
/******/ var __webpack_exports__AutoModelForCTC = __webpack_exports__.AutoModelForCTC;
/******/ var __webpack_exports__AutoModelForCausalLM = __webpack_exports__.AutoModelForCausalLM;
/******/ var __webpack_exports__AutoModelForDepthEstimation = __webpack_exports__.AutoModelForDepthEstimation;
/******/ var __webpack_exports__AutoModelForDocumentQuestionAnswering = __webpack_exports__.AutoModelForDocumentQuestionAnswering;
/******/ var __webpack_exports__AutoModelForImageClassification = __webpack_exports__.AutoModelForImageClassification;
/******/ var __webpack_exports__AutoModelForImageFeatureExtraction = __webpack_exports__.AutoModelForImageFeatureExtraction;
/******/ var __webpack_exports__AutoModelForImageMatting = __webpack_exports__.AutoModelForImageMatting;
/******/ var __webpack_exports__AutoModelForImageSegmentation = __webpack_exports__.AutoModelForImageSegmentation;
/******/ var __webpack_exports__AutoModelForImageToImage = __webpack_exports__.AutoModelForImageToImage;
/******/ var __webpack_exports__AutoModelForMaskGeneration = __webpack_exports__.AutoModelForMaskGeneration;
/******/ var __webpack_exports__AutoModelForMaskedLM = __webpack_exports__.AutoModelForMaskedLM;
/******/ var __webpack_exports__AutoModelForObjectDetection = __webpack_exports__.AutoModelForObjectDetection;
/******/ var __webpack_exports__AutoModelForQuestionAnswering = __webpack_exports__.AutoModelForQuestionAnswering;
/******/ var __webpack_exports__AutoModelForSemanticSegmentation = __webpack_exports__.AutoModelForSemanticSegmentation;
/******/ var __webpack_exports__AutoModelForSeq2SeqLM = __webpack_exports__.AutoModelForSeq2SeqLM;
/******/ var __webpack_exports__AutoModelForSequenceClassification = __webpack_exports__.AutoModelForSequenceClassification;
/******/ var __webpack_exports__AutoModelForSpeechSeq2Seq = __webpack_exports__.AutoModelForSpeechSeq2Seq;
/******/ var __webpack_exports__AutoModelForTextToSpectrogram = __webpack_exports__.AutoModelForTextToSpectrogram;
/******/ var __webpack_exports__AutoModelForTextToWaveform = __webpack_exports__.AutoModelForTextToWaveform;
/******/ var __webpack_exports__AutoModelForTokenClassification = __webpack_exports__.AutoModelForTokenClassification;
/******/ var __webpack_exports__AutoModelForVision2Seq = __webpack_exports__.AutoModelForVision2Seq;
/******/ var __webpack_exports__AutoModelForXVector = __webpack_exports__.AutoModelForXVector;
/******/ var __webpack_exports__AutoModelForZeroShotObjectDetection = __webpack_exports__.AutoModelForZeroShotObjectDetection;
/******/ var __webpack_exports__AutoProcessor = __webpack_exports__.AutoProcessor;
/******/ var __webpack_exports__AutoTokenizer = __webpack_exports__.AutoTokenizer;
/******/ var __webpack_exports__AutomaticSpeechRecognitionPipeline = __webpack_exports__.AutomaticSpeechRecognitionPipeline;
/******/ var __webpack_exports__BartForConditionalGeneration = __webpack_exports__.BartForConditionalGeneration;
/******/ var __webpack_exports__BartForSequenceClassification = __webpack_exports__.BartForSequenceClassification;
/******/ var __webpack_exports__BartModel = __webpack_exports__.BartModel;
/******/ var __webpack_exports__BartPretrainedModel = __webpack_exports__.BartPretrainedModel;
/******/ var __webpack_exports__BartTokenizer = __webpack_exports__.BartTokenizer;
/******/ var __webpack_exports__BaseModelOutput = __webpack_exports__.BaseModelOutput;
/******/ var __webpack_exports__BeitFeatureExtractor = __webpack_exports__.BeitFeatureExtractor;
/******/ var __webpack_exports__BeitForImageClassification = __webpack_exports__.BeitForImageClassification;
/******/ var __webpack_exports__BeitModel = __webpack_exports__.BeitModel;
/******/ var __webpack_exports__BeitPreTrainedModel = __webpack_exports__.BeitPreTrainedModel;
/******/ var __webpack_exports__BertForMaskedLM = __webpack_exports__.BertForMaskedLM;
/******/ var __webpack_exports__BertForQuestionAnswering = __webpack_exports__.BertForQuestionAnswering;
/******/ var __webpack_exports__BertForSequenceClassification = __webpack_exports__.BertForSequenceClassification;
/******/ var __webpack_exports__BertForTokenClassification = __webpack_exports__.BertForTokenClassification;
/******/ var __webpack_exports__BertModel = __webpack_exports__.BertModel;
/******/ var __webpack_exports__BertPreTrainedModel = __webpack_exports__.BertPreTrainedModel;
/******/ var __webpack_exports__BertTokenizer = __webpack_exports__.BertTokenizer;
/******/ var __webpack_exports__BitImageProcessor = __webpack_exports__.BitImageProcessor;
/******/ var __webpack_exports__BlenderbotForConditionalGeneration = __webpack_exports__.BlenderbotForConditionalGeneration;
/******/ var __webpack_exports__BlenderbotModel = __webpack_exports__.BlenderbotModel;
/******/ var __webpack_exports__BlenderbotPreTrainedModel = __webpack_exports__.BlenderbotPreTrainedModel;
/******/ var __webpack_exports__BlenderbotSmallForConditionalGeneration = __webpack_exports__.BlenderbotSmallForConditionalGeneration;
/******/ var __webpack_exports__BlenderbotSmallModel = __webpack_exports__.BlenderbotSmallModel;
/******/ var __webpack_exports__BlenderbotSmallPreTrainedModel = __webpack_exports__.BlenderbotSmallPreTrainedModel;
/******/ var __webpack_exports__BlenderbotSmallTokenizer = __webpack_exports__.BlenderbotSmallTokenizer;
/******/ var __webpack_exports__BlenderbotTokenizer = __webpack_exports__.BlenderbotTokenizer;
/******/ var __webpack_exports__BloomForCausalLM = __webpack_exports__.BloomForCausalLM;
/******/ var __webpack_exports__BloomModel = __webpack_exports__.BloomModel;
/******/ var __webpack_exports__BloomPreTrainedModel = __webpack_exports__.BloomPreTrainedModel;
/******/ var __webpack_exports__BloomTokenizer = __webpack_exports__.BloomTokenizer;
/******/ var __webpack_exports__CLIPFeatureExtractor = __webpack_exports__.CLIPFeatureExtractor;
/******/ var __webpack_exports__CLIPModel = __webpack_exports__.CLIPModel;
/******/ var __webpack_exports__CLIPPreTrainedModel = __webpack_exports__.CLIPPreTrainedModel;
/******/ var __webpack_exports__CLIPSegForImageSegmentation = __webpack_exports__.CLIPSegForImageSegmentation;
/******/ var __webpack_exports__CLIPSegModel = __webpack_exports__.CLIPSegModel;
/******/ var __webpack_exports__CLIPSegPreTrainedModel = __webpack_exports__.CLIPSegPreTrainedModel;
/******/ var __webpack_exports__CLIPTextModelWithProjection = __webpack_exports__.CLIPTextModelWithProjection;
/******/ var __webpack_exports__CLIPTokenizer = __webpack_exports__.CLIPTokenizer;
/******/ var __webpack_exports__CLIPVisionModelWithProjection = __webpack_exports__.CLIPVisionModelWithProjection;
/******/ var __webpack_exports__CamembertForMaskedLM = __webpack_exports__.CamembertForMaskedLM;
/******/ var __webpack_exports__CamembertForQuestionAnswering = __webpack_exports__.CamembertForQuestionAnswering;
/******/ var __webpack_exports__CamembertForSequenceClassification = __webpack_exports__.CamembertForSequenceClassification;
/******/ var __webpack_exports__CamembertForTokenClassification = __webpack_exports__.CamembertForTokenClassification;
/******/ var __webpack_exports__CamembertModel = __webpack_exports__.CamembertModel;
/******/ var __webpack_exports__CamembertPreTrainedModel = __webpack_exports__.CamembertPreTrainedModel;
/******/ var __webpack_exports__CamembertTokenizer = __webpack_exports__.CamembertTokenizer;
/******/ var __webpack_exports__CausalLMOutput = __webpack_exports__.CausalLMOutput;
/******/ var __webpack_exports__CausalLMOutputWithPast = __webpack_exports__.CausalLMOutputWithPast;
/******/ var __webpack_exports__ChineseCLIPFeatureExtractor = __webpack_exports__.ChineseCLIPFeatureExtractor;
/******/ var __webpack_exports__ChineseCLIPModel = __webpack_exports__.ChineseCLIPModel;
/******/ var __webpack_exports__ChineseCLIPPreTrainedModel = __webpack_exports__.ChineseCLIPPreTrainedModel;
/******/ var __webpack_exports__ClapAudioModelWithProjection = __webpack_exports__.ClapAudioModelWithProjection;
/******/ var __webpack_exports__ClapFeatureExtractor = __webpack_exports__.ClapFeatureExtractor;
/******/ var __webpack_exports__ClapModel = __webpack_exports__.ClapModel;
/******/ var __webpack_exports__ClapPreTrainedModel = __webpack_exports__.ClapPreTrainedModel;
/******/ var __webpack_exports__ClapTextModelWithProjection = __webpack_exports__.ClapTextModelWithProjection;
/******/ var __webpack_exports__CodeGenForCausalLM = __webpack_exports__.CodeGenForCausalLM;
/******/ var __webpack_exports__CodeGenModel = __webpack_exports__.CodeGenModel;
/******/ var __webpack_exports__CodeGenPreTrainedModel = __webpack_exports__.CodeGenPreTrainedModel;
/******/ var __webpack_exports__CodeGenTokenizer = __webpack_exports__.CodeGenTokenizer;
/******/ var __webpack_exports__CodeLlamaTokenizer = __webpack_exports__.CodeLlamaTokenizer;
/******/ var __webpack_exports__CohereTokenizer = __webpack_exports__.CohereTokenizer;
/******/ var __webpack_exports__ConvBertForMaskedLM = __webpack_exports__.ConvBertForMaskedLM;
/******/ var __webpack_exports__ConvBertForQuestionAnswering = __webpack_exports__.ConvBertForQuestionAnswering;
/******/ var __webpack_exports__ConvBertForSequenceClassification = __webpack_exports__.ConvBertForSequenceClassification;
/******/ var __webpack_exports__ConvBertForTokenClassification = __webpack_exports__.ConvBertForTokenClassification;
/******/ var __webpack_exports__ConvBertModel = __webpack_exports__.ConvBertModel;
/******/ var __webpack_exports__ConvBertPreTrainedModel = __webpack_exports__.ConvBertPreTrainedModel;
/******/ var __webpack_exports__ConvBertTokenizer = __webpack_exports__.ConvBertTokenizer;
/******/ var __webpack_exports__ConvNextFeatureExtractor = __webpack_exports__.ConvNextFeatureExtractor;
/******/ var __webpack_exports__ConvNextForImageClassification = __webpack_exports__.ConvNextForImageClassification;
/******/ var __webpack_exports__ConvNextImageProcessor = __webpack_exports__.ConvNextImageProcessor;
/******/ var __webpack_exports__ConvNextModel = __webpack_exports__.ConvNextModel;
/******/ var __webpack_exports__ConvNextPreTrainedModel = __webpack_exports__.ConvNextPreTrainedModel;
/******/ var __webpack_exports__ConvNextV2ForImageClassification = __webpack_exports__.ConvNextV2ForImageClassification;
/******/ var __webpack_exports__ConvNextV2Model = __webpack_exports__.ConvNextV2Model;
/******/ var __webpack_exports__ConvNextV2PreTrainedModel = __webpack_exports__.ConvNextV2PreTrainedModel;
/******/ var __webpack_exports__DPTFeatureExtractor = __webpack_exports__.DPTFeatureExtractor;
/******/ var __webpack_exports__DPTForDepthEstimation = __webpack_exports__.DPTForDepthEstimation;
/******/ var __webpack_exports__DPTImageProcessor = __webpack_exports__.DPTImageProcessor;
/******/ var __webpack_exports__DPTModel = __webpack_exports__.DPTModel;
/******/ var __webpack_exports__DPTPreTrainedModel = __webpack_exports__.DPTPreTrainedModel;
/******/ var __webpack_exports__DebertaForMaskedLM = __webpack_exports__.DebertaForMaskedLM;
/******/ var __webpack_exports__DebertaForQuestionAnswering = __webpack_exports__.DebertaForQuestionAnswering;
/******/ var __webpack_exports__DebertaForSequenceClassification = __webpack_exports__.DebertaForSequenceClassification;
/******/ var __webpack_exports__DebertaForTokenClassification = __webpack_exports__.DebertaForTokenClassification;
/******/ var __webpack_exports__DebertaModel = __webpack_exports__.DebertaModel;
/******/ var __webpack_exports__DebertaPreTrainedModel = __webpack_exports__.DebertaPreTrainedModel;
/******/ var __webpack_exports__DebertaTokenizer = __webpack_exports__.DebertaTokenizer;
/******/ var __webpack_exports__DebertaV2ForMaskedLM = __webpack_exports__.DebertaV2ForMaskedLM;
/******/ var __webpack_exports__DebertaV2ForQuestionAnswering = __webpack_exports__.DebertaV2ForQuestionAnswering;
/******/ var __webpack_exports__DebertaV2ForSequenceClassification = __webpack_exports__.DebertaV2ForSequenceClassification;
/******/ var __webpack_exports__DebertaV2ForTokenClassification = __webpack_exports__.DebertaV2ForTokenClassification;
/******/ var __webpack_exports__DebertaV2Model = __webpack_exports__.DebertaV2Model;
/******/ var __webpack_exports__DebertaV2PreTrainedModel = __webpack_exports__.DebertaV2PreTrainedModel;
/******/ var __webpack_exports__DebertaV2Tokenizer = __webpack_exports__.DebertaV2Tokenizer;
/******/ var __webpack_exports__DeiTFeatureExtractor = __webpack_exports__.DeiTFeatureExtractor;
/******/ var __webpack_exports__DeiTForImageClassification = __webpack_exports__.DeiTForImageClassification;
/******/ var __webpack_exports__DeiTModel = __webpack_exports__.DeiTModel;
/******/ var __webpack_exports__DeiTPreTrainedModel = __webpack_exports__.DeiTPreTrainedModel;
/******/ var __webpack_exports__DepthAnythingForDepthEstimation = __webpack_exports__.DepthAnythingForDepthEstimation;
/******/ var __webpack_exports__DepthAnythingPreTrainedModel = __webpack_exports__.DepthAnythingPreTrainedModel;
/******/ var __webpack_exports__DepthEstimationPipeline = __webpack_exports__.DepthEstimationPipeline;
/******/ var __webpack_exports__DetrFeatureExtractor = __webpack_exports__.DetrFeatureExtractor;
/******/ var __webpack_exports__DetrForObjectDetection = __webpack_exports__.DetrForObjectDetection;
/******/ var __webpack_exports__DetrForSegmentation = __webpack_exports__.DetrForSegmentation;
/******/ var __webpack_exports__DetrModel = __webpack_exports__.DetrModel;
/******/ var __webpack_exports__DetrObjectDetectionOutput = __webpack_exports__.DetrObjectDetectionOutput;
/******/ var __webpack_exports__DetrPreTrainedModel = __webpack_exports__.DetrPreTrainedModel;
/******/ var __webpack_exports__DetrSegmentationOutput = __webpack_exports__.DetrSegmentationOutput;
/******/ var __webpack_exports__Dinov2ForImageClassification = __webpack_exports__.Dinov2ForImageClassification;
/******/ var __webpack_exports__Dinov2Model = __webpack_exports__.Dinov2Model;
/******/ var __webpack_exports__Dinov2PreTrainedModel = __webpack_exports__.Dinov2PreTrainedModel;
/******/ var __webpack_exports__DistilBertForMaskedLM = __webpack_exports__.DistilBertForMaskedLM;
/******/ var __webpack_exports__DistilBertForQuestionAnswering = __webpack_exports__.DistilBertForQuestionAnswering;
/******/ var __webpack_exports__DistilBertForSequenceClassification = __webpack_exports__.DistilBertForSequenceClassification;
/******/ var __webpack_exports__DistilBertForTokenClassification = __webpack_exports__.DistilBertForTokenClassification;
/******/ var __webpack_exports__DistilBertModel = __webpack_exports__.DistilBertModel;
/******/ var __webpack_exports__DistilBertPreTrainedModel = __webpack_exports__.DistilBertPreTrainedModel;
/******/ var __webpack_exports__DistilBertTokenizer = __webpack_exports__.DistilBertTokenizer;
/******/ var __webpack_exports__DocumentQuestionAnsweringPipeline = __webpack_exports__.DocumentQuestionAnsweringPipeline;
/******/ var __webpack_exports__DonutFeatureExtractor = __webpack_exports__.DonutFeatureExtractor;
/******/ var __webpack_exports__DonutSwinModel = __webpack_exports__.DonutSwinModel;
/******/ var __webpack_exports__DonutSwinPreTrainedModel = __webpack_exports__.DonutSwinPreTrainedModel;
/******/ var __webpack_exports__EfficientNetForImageClassification = __webpack_exports__.EfficientNetForImageClassification;
/******/ var __webpack_exports__EfficientNetImageProcessor = __webpack_exports__.EfficientNetImageProcessor;
/******/ var __webpack_exports__EfficientNetModel = __webpack_exports__.EfficientNetModel;
/******/ var __webpack_exports__EfficientNetPreTrainedModel = __webpack_exports__.EfficientNetPreTrainedModel;
/******/ var __webpack_exports__ElectraForMaskedLM = __webpack_exports__.ElectraForMaskedLM;
/******/ var __webpack_exports__ElectraForQuestionAnswering = __webpack_exports__.ElectraForQuestionAnswering;
/******/ var __webpack_exports__ElectraForSequenceClassification = __webpack_exports__.ElectraForSequenceClassification;
/******/ var __webpack_exports__ElectraForTokenClassification = __webpack_exports__.ElectraForTokenClassification;
/******/ var __webpack_exports__ElectraModel = __webpack_exports__.ElectraModel;
/******/ var __webpack_exports__ElectraPreTrainedModel = __webpack_exports__.ElectraPreTrainedModel;
/******/ var __webpack_exports__ElectraTokenizer = __webpack_exports__.ElectraTokenizer;
/******/ var __webpack_exports__EsmForMaskedLM = __webpack_exports__.EsmForMaskedLM;
/******/ var __webpack_exports__EsmForSequenceClassification = __webpack_exports__.EsmForSequenceClassification;
/******/ var __webpack_exports__EsmForTokenClassification = __webpack_exports__.EsmForTokenClassification;
/******/ var __webpack_exports__EsmModel = __webpack_exports__.EsmModel;
/******/ var __webpack_exports__EsmPreTrainedModel = __webpack_exports__.EsmPreTrainedModel;
/******/ var __webpack_exports__EsmTokenizer = __webpack_exports__.EsmTokenizer;
/******/ var __webpack_exports__FFT = __webpack_exports__.FFT;
/******/ var __webpack_exports__FalconForCausalLM = __webpack_exports__.FalconForCausalLM;
/******/ var __webpack_exports__FalconModel = __webpack_exports__.FalconModel;
/******/ var __webpack_exports__FalconPreTrainedModel = __webpack_exports__.FalconPreTrainedModel;
/******/ var __webpack_exports__FalconTokenizer = __webpack_exports__.FalconTokenizer;
/******/ var __webpack_exports__FastViTForImageClassification = __webpack_exports__.FastViTForImageClassification;
/******/ var __webpack_exports__FastViTModel = __webpack_exports__.FastViTModel;
/******/ var __webpack_exports__FastViTPreTrainedModel = __webpack_exports__.FastViTPreTrainedModel;
/******/ var __webpack_exports__FeatureExtractionPipeline = __webpack_exports__.FeatureExtractionPipeline;
/******/ var __webpack_exports__FeatureExtractor = __webpack_exports__.FeatureExtractor;
/******/ var __webpack_exports__FillMaskPipeline = __webpack_exports__.FillMaskPipeline;
/******/ var __webpack_exports__GLPNFeatureExtractor = __webpack_exports__.GLPNFeatureExtractor;
/******/ var __webpack_exports__GLPNForDepthEstimation = __webpack_exports__.GLPNForDepthEstimation;
/******/ var __webpack_exports__GLPNModel = __webpack_exports__.GLPNModel;
/******/ var __webpack_exports__GLPNPreTrainedModel = __webpack_exports__.GLPNPreTrainedModel;
/******/ var __webpack_exports__GPT2LMHeadModel = __webpack_exports__.GPT2LMHeadModel;
/******/ var __webpack_exports__GPT2Model = __webpack_exports__.GPT2Model;
/******/ var __webpack_exports__GPT2PreTrainedModel = __webpack_exports__.GPT2PreTrainedModel;
/******/ var __webpack_exports__GPT2Tokenizer = __webpack_exports__.GPT2Tokenizer;
/******/ var __webpack_exports__GPTBigCodeForCausalLM = __webpack_exports__.GPTBigCodeForCausalLM;
/******/ var __webpack_exports__GPTBigCodeModel = __webpack_exports__.GPTBigCodeModel;
/******/ var __webpack_exports__GPTBigCodePreTrainedModel = __webpack_exports__.GPTBigCodePreTrainedModel;
/******/ var __webpack_exports__GPTJForCausalLM = __webpack_exports__.GPTJForCausalLM;
/******/ var __webpack_exports__GPTJModel = __webpack_exports__.GPTJModel;
/******/ var __webpack_exports__GPTJPreTrainedModel = __webpack_exports__.GPTJPreTrainedModel;
/******/ var __webpack_exports__GPTNeoForCausalLM = __webpack_exports__.GPTNeoForCausalLM;
/******/ var __webpack_exports__GPTNeoModel = __webpack_exports__.GPTNeoModel;
/******/ var __webpack_exports__GPTNeoPreTrainedModel = __webpack_exports__.GPTNeoPreTrainedModel;
/******/ var __webpack_exports__GPTNeoXForCausalLM = __webpack_exports__.GPTNeoXForCausalLM;
/******/ var __webpack_exports__GPTNeoXModel = __webpack_exports__.GPTNeoXModel;
/******/ var __webpack_exports__GPTNeoXPreTrainedModel = __webpack_exports__.GPTNeoXPreTrainedModel;
/******/ var __webpack_exports__GPTNeoXTokenizer = __webpack_exports__.GPTNeoXTokenizer;
/******/ var __webpack_exports__GemmaTokenizer = __webpack_exports__.GemmaTokenizer;
/******/ var __webpack_exports__Grok1Tokenizer = __webpack_exports__.Grok1Tokenizer;
/******/ var __webpack_exports__HerbertTokenizer = __webpack_exports__.HerbertTokenizer;
/******/ var __webpack_exports__HubertForCTC = __webpack_exports__.HubertForCTC;
/******/ var __webpack_exports__HubertForSequenceClassification = __webpack_exports__.HubertForSequenceClassification;
/******/ var __webpack_exports__HubertModel = __webpack_exports__.HubertModel;
/******/ var __webpack_exports__HubertPreTrainedModel = __webpack_exports__.HubertPreTrainedModel;
/******/ var __webpack_exports__ImageClassificationPipeline = __webpack_exports__.ImageClassificationPipeline;
/******/ var __webpack_exports__ImageFeatureExtractionPipeline = __webpack_exports__.ImageFeatureExtractionPipeline;
/******/ var __webpack_exports__ImageFeatureExtractor = __webpack_exports__.ImageFeatureExtractor;
/******/ var __webpack_exports__ImageMattingOutput = __webpack_exports__.ImageMattingOutput;
/******/ var __webpack_exports__ImageSegmentationPipeline = __webpack_exports__.ImageSegmentationPipeline;
/******/ var __webpack_exports__ImageToImagePipeline = __webpack_exports__.ImageToImagePipeline;
/******/ var __webpack_exports__ImageToTextPipeline = __webpack_exports__.ImageToTextPipeline;
/******/ var __webpack_exports__LlamaForCausalLM = __webpack_exports__.LlamaForCausalLM;
/******/ var __webpack_exports__LlamaModel = __webpack_exports__.LlamaModel;
/******/ var __webpack_exports__LlamaPreTrainedModel = __webpack_exports__.LlamaPreTrainedModel;
/******/ var __webpack_exports__LlamaTokenizer = __webpack_exports__.LlamaTokenizer;
/******/ var __webpack_exports__LongT5ForConditionalGeneration = __webpack_exports__.LongT5ForConditionalGeneration;
/******/ var __webpack_exports__LongT5Model = __webpack_exports__.LongT5Model;
/******/ var __webpack_exports__LongT5PreTrainedModel = __webpack_exports__.LongT5PreTrainedModel;
/******/ var __webpack_exports__M2M100ForConditionalGeneration = __webpack_exports__.M2M100ForConditionalGeneration;
/******/ var __webpack_exports__M2M100Model = __webpack_exports__.M2M100Model;
/******/ var __webpack_exports__M2M100PreTrainedModel = __webpack_exports__.M2M100PreTrainedModel;
/******/ var __webpack_exports__M2M100Tokenizer = __webpack_exports__.M2M100Tokenizer;
/******/ var __webpack_exports__MBart50Tokenizer = __webpack_exports__.MBart50Tokenizer;
/******/ var __webpack_exports__MBartForCausalLM = __webpack_exports__.MBartForCausalLM;
/******/ var __webpack_exports__MBartForConditionalGeneration = __webpack_exports__.MBartForConditionalGeneration;
/******/ var __webpack_exports__MBartForSequenceClassification = __webpack_exports__.MBartForSequenceClassification;
/******/ var __webpack_exports__MBartModel = __webpack_exports__.MBartModel;
/******/ var __webpack_exports__MBartPreTrainedModel = __webpack_exports__.MBartPreTrainedModel;
/******/ var __webpack_exports__MBartTokenizer = __webpack_exports__.MBartTokenizer;
/******/ var __webpack_exports__MPNetForMaskedLM = __webpack_exports__.MPNetForMaskedLM;
/******/ var __webpack_exports__MPNetForQuestionAnswering = __webpack_exports__.MPNetForQuestionAnswering;
/******/ var __webpack_exports__MPNetForSequenceClassification = __webpack_exports__.MPNetForSequenceClassification;
/******/ var __webpack_exports__MPNetForTokenClassification = __webpack_exports__.MPNetForTokenClassification;
/******/ var __webpack_exports__MPNetModel = __webpack_exports__.MPNetModel;
/******/ var __webpack_exports__MPNetPreTrainedModel = __webpack_exports__.MPNetPreTrainedModel;
/******/ var __webpack_exports__MPNetTokenizer = __webpack_exports__.MPNetTokenizer;
/******/ var __webpack_exports__MT5ForConditionalGeneration = __webpack_exports__.MT5ForConditionalGeneration;
/******/ var __webpack_exports__MT5Model = __webpack_exports__.MT5Model;
/******/ var __webpack_exports__MT5PreTrainedModel = __webpack_exports__.MT5PreTrainedModel;
/******/ var __webpack_exports__MarianMTModel = __webpack_exports__.MarianMTModel;
/******/ var __webpack_exports__MarianModel = __webpack_exports__.MarianModel;
/******/ var __webpack_exports__MarianPreTrainedModel = __webpack_exports__.MarianPreTrainedModel;
/******/ var __webpack_exports__MarianTokenizer = __webpack_exports__.MarianTokenizer;
/******/ var __webpack_exports__MaskedLMOutput = __webpack_exports__.MaskedLMOutput;
/******/ var __webpack_exports__MistralForCausalLM = __webpack_exports__.MistralForCausalLM;
/******/ var __webpack_exports__MistralModel = __webpack_exports__.MistralModel;
/******/ var __webpack_exports__MistralPreTrainedModel = __webpack_exports__.MistralPreTrainedModel;
/******/ var __webpack_exports__MobileBertForMaskedLM = __webpack_exports__.MobileBertForMaskedLM;
/******/ var __webpack_exports__MobileBertForQuestionAnswering = __webpack_exports__.MobileBertForQuestionAnswering;
/******/ var __webpack_exports__MobileBertForSequenceClassification = __webpack_exports__.MobileBertForSequenceClassification;
/******/ var __webpack_exports__MobileBertModel = __webpack_exports__.MobileBertModel;
/******/ var __webpack_exports__MobileBertPreTrainedModel = __webpack_exports__.MobileBertPreTrainedModel;
/******/ var __webpack_exports__MobileBertTokenizer = __webpack_exports__.MobileBertTokenizer;
/******/ var __webpack_exports__MobileViTFeatureExtractor = __webpack_exports__.MobileViTFeatureExtractor;
/******/ var __webpack_exports__MobileViTForImageClassification = __webpack_exports__.MobileViTForImageClassification;
/******/ var __webpack_exports__MobileViTImageProcessor = __webpack_exports__.MobileViTImageProcessor;
/******/ var __webpack_exports__MobileViTModel = __webpack_exports__.MobileViTModel;
/******/ var __webpack_exports__MobileViTPreTrainedModel = __webpack_exports__.MobileViTPreTrainedModel;
/******/ var __webpack_exports__MobileViTV2ForImageClassification = __webpack_exports__.MobileViTV2ForImageClassification;
/******/ var __webpack_exports__MobileViTV2Model = __webpack_exports__.MobileViTV2Model;
/******/ var __webpack_exports__MobileViTV2PreTrainedModel = __webpack_exports__.MobileViTV2PreTrainedModel;
/******/ var __webpack_exports__ModelOutput = __webpack_exports__.ModelOutput;
/******/ var __webpack_exports__MptForCausalLM = __webpack_exports__.MptForCausalLM;
/******/ var __webpack_exports__MptModel = __webpack_exports__.MptModel;
/******/ var __webpack_exports__MptPreTrainedModel = __webpack_exports__.MptPreTrainedModel;
/******/ var __webpack_exports__NllbTokenizer = __webpack_exports__.NllbTokenizer;
/******/ var __webpack_exports__NomicBertModel = __webpack_exports__.NomicBertModel;
/******/ var __webpack_exports__NomicBertPreTrainedModel = __webpack_exports__.NomicBertPreTrainedModel;
/******/ var __webpack_exports__NougatImageProcessor = __webpack_exports__.NougatImageProcessor;
/******/ var __webpack_exports__NougatTokenizer = __webpack_exports__.NougatTokenizer;
/******/ var __webpack_exports__OPTForCausalLM = __webpack_exports__.OPTForCausalLM;
/******/ var __webpack_exports__OPTModel = __webpack_exports__.OPTModel;
/******/ var __webpack_exports__OPTPreTrainedModel = __webpack_exports__.OPTPreTrainedModel;
/******/ var __webpack_exports__ObjectDetectionPipeline = __webpack_exports__.ObjectDetectionPipeline;
/******/ var __webpack_exports__OwlViTFeatureExtractor = __webpack_exports__.OwlViTFeatureExtractor;
/******/ var __webpack_exports__OwlViTForObjectDetection = __webpack_exports__.OwlViTForObjectDetection;
/******/ var __webpack_exports__OwlViTModel = __webpack_exports__.OwlViTModel;
/******/ var __webpack_exports__OwlViTPreTrainedModel = __webpack_exports__.OwlViTPreTrainedModel;
/******/ var __webpack_exports__OwlViTProcessor = __webpack_exports__.OwlViTProcessor;
/******/ var __webpack_exports__Owlv2ForObjectDetection = __webpack_exports__.Owlv2ForObjectDetection;
/******/ var __webpack_exports__Owlv2ImageProcessor = __webpack_exports__.Owlv2ImageProcessor;
/******/ var __webpack_exports__Owlv2Model = __webpack_exports__.Owlv2Model;
/******/ var __webpack_exports__Owlv2PreTrainedModel = __webpack_exports__.Owlv2PreTrainedModel;
/******/ var __webpack_exports__PhiForCausalLM = __webpack_exports__.PhiForCausalLM;
/******/ var __webpack_exports__PhiModel = __webpack_exports__.PhiModel;
/******/ var __webpack_exports__PhiPreTrainedModel = __webpack_exports__.PhiPreTrainedModel;
/******/ var __webpack_exports__Pipeline = __webpack_exports__.Pipeline;
/******/ var __webpack_exports__PreTrainedModel = __webpack_exports__.PreTrainedModel;
/******/ var __webpack_exports__PreTrainedTokenizer = __webpack_exports__.PreTrainedTokenizer;
/******/ var __webpack_exports__PretrainedConfig = __webpack_exports__.PretrainedConfig;
/******/ var __webpack_exports__PretrainedMixin = __webpack_exports__.PretrainedMixin;
/******/ var __webpack_exports__Processor = __webpack_exports__.Processor;
/******/ var __webpack_exports__QuestionAnsweringModelOutput = __webpack_exports__.QuestionAnsweringModelOutput;
/******/ var __webpack_exports__QuestionAnsweringPipeline = __webpack_exports__.QuestionAnsweringPipeline;
/******/ var __webpack_exports__Qwen2ForCausalLM = __webpack_exports__.Qwen2ForCausalLM;
/******/ var __webpack_exports__Qwen2Model = __webpack_exports__.Qwen2Model;
/******/ var __webpack_exports__Qwen2PreTrainedModel = __webpack_exports__.Qwen2PreTrainedModel;
/******/ var __webpack_exports__Qwen2Tokenizer = __webpack_exports__.Qwen2Tokenizer;
/******/ var __webpack_exports__RawImage = __webpack_exports__.RawImage;
/******/ var __webpack_exports__ResNetForImageClassification = __webpack_exports__.ResNetForImageClassification;
/******/ var __webpack_exports__ResNetModel = __webpack_exports__.ResNetModel;
/******/ var __webpack_exports__ResNetPreTrainedModel = __webpack_exports__.ResNetPreTrainedModel;
/******/ var __webpack_exports__RoFormerForMaskedLM = __webpack_exports__.RoFormerForMaskedLM;
/******/ var __webpack_exports__RoFormerForQuestionAnswering = __webpack_exports__.RoFormerForQuestionAnswering;
/******/ var __webpack_exports__RoFormerForSequenceClassification = __webpack_exports__.RoFormerForSequenceClassification;
/******/ var __webpack_exports__RoFormerForTokenClassification = __webpack_exports__.RoFormerForTokenClassification;
/******/ var __webpack_exports__RoFormerModel = __webpack_exports__.RoFormerModel;
/******/ var __webpack_exports__RoFormerPreTrainedModel = __webpack_exports__.RoFormerPreTrainedModel;
/******/ var __webpack_exports__RoFormerTokenizer = __webpack_exports__.RoFormerTokenizer;
/******/ var __webpack_exports__RobertaForMaskedLM = __webpack_exports__.RobertaForMaskedLM;
/******/ var __webpack_exports__RobertaForQuestionAnswering = __webpack_exports__.RobertaForQuestionAnswering;
/******/ var __webpack_exports__RobertaForSequenceClassification = __webpack_exports__.RobertaForSequenceClassification;
/******/ var __webpack_exports__RobertaForTokenClassification = __webpack_exports__.RobertaForTokenClassification;
/******/ var __webpack_exports__RobertaModel = __webpack_exports__.RobertaModel;
/******/ var __webpack_exports__RobertaPreTrainedModel = __webpack_exports__.RobertaPreTrainedModel;
/******/ var __webpack_exports__RobertaTokenizer = __webpack_exports__.RobertaTokenizer;
/******/ var __webpack_exports__SamImageProcessor = __webpack_exports__.SamImageProcessor;
/******/ var __webpack_exports__SamImageSegmentationOutput = __webpack_exports__.SamImageSegmentationOutput;
/******/ var __webpack_exports__SamModel = __webpack_exports__.SamModel;
/******/ var __webpack_exports__SamPreTrainedModel = __webpack_exports__.SamPreTrainedModel;
/******/ var __webpack_exports__SamProcessor = __webpack_exports__.SamProcessor;
/******/ var __webpack_exports__SeamlessM4TFeatureExtractor = __webpack_exports__.SeamlessM4TFeatureExtractor;
/******/ var __webpack_exports__SegformerFeatureExtractor = __webpack_exports__.SegformerFeatureExtractor;
/******/ var __webpack_exports__SegformerForImageClassification = __webpack_exports__.SegformerForImageClassification;
/******/ var __webpack_exports__SegformerForSemanticSegmentation = __webpack_exports__.SegformerForSemanticSegmentation;
/******/ var __webpack_exports__SegformerModel = __webpack_exports__.SegformerModel;
/******/ var __webpack_exports__SegformerPreTrainedModel = __webpack_exports__.SegformerPreTrainedModel;
/******/ var __webpack_exports__Seq2SeqLMOutput = __webpack_exports__.Seq2SeqLMOutput;
/******/ var __webpack_exports__SequenceClassifierOutput = __webpack_exports__.SequenceClassifierOutput;
/******/ var __webpack_exports__SiglipImageProcessor = __webpack_exports__.SiglipImageProcessor;
/******/ var __webpack_exports__SiglipModel = __webpack_exports__.SiglipModel;
/******/ var __webpack_exports__SiglipPreTrainedModel = __webpack_exports__.SiglipPreTrainedModel;
/******/ var __webpack_exports__SiglipTextModel = __webpack_exports__.SiglipTextModel;
/******/ var __webpack_exports__SiglipTokenizer = __webpack_exports__.SiglipTokenizer;
/******/ var __webpack_exports__SiglipVisionModel = __webpack_exports__.SiglipVisionModel;
/******/ var __webpack_exports__SpeechT5FeatureExtractor = __webpack_exports__.SpeechT5FeatureExtractor;
/******/ var __webpack_exports__SpeechT5ForSpeechToText = __webpack_exports__.SpeechT5ForSpeechToText;
/******/ var __webpack_exports__SpeechT5ForTextToSpeech = __webpack_exports__.SpeechT5ForTextToSpeech;
/******/ var __webpack_exports__SpeechT5HifiGan = __webpack_exports__.SpeechT5HifiGan;
/******/ var __webpack_exports__SpeechT5Model = __webpack_exports__.SpeechT5Model;
/******/ var __webpack_exports__SpeechT5PreTrainedModel = __webpack_exports__.SpeechT5PreTrainedModel;
/******/ var __webpack_exports__SpeechT5Processor = __webpack_exports__.SpeechT5Processor;
/******/ var __webpack_exports__SpeechT5Tokenizer = __webpack_exports__.SpeechT5Tokenizer;
/******/ var __webpack_exports__SqueezeBertForMaskedLM = __webpack_exports__.SqueezeBertForMaskedLM;
/******/ var __webpack_exports__SqueezeBertForQuestionAnswering = __webpack_exports__.SqueezeBertForQuestionAnswering;
/******/ var __webpack_exports__SqueezeBertForSequenceClassification = __webpack_exports__.SqueezeBertForSequenceClassification;
/******/ var __webpack_exports__SqueezeBertModel = __webpack_exports__.SqueezeBertModel;
/******/ var __webpack_exports__SqueezeBertPreTrainedModel = __webpack_exports__.SqueezeBertPreTrainedModel;
/******/ var __webpack_exports__SqueezeBertTokenizer = __webpack_exports__.SqueezeBertTokenizer;
/******/ var __webpack_exports__StableLmForCausalLM = __webpack_exports__.StableLmForCausalLM;
/******/ var __webpack_exports__StableLmModel = __webpack_exports__.StableLmModel;
/******/ var __webpack_exports__StableLmPreTrainedModel = __webpack_exports__.StableLmPreTrainedModel;
/******/ var __webpack_exports__Starcoder2ForCausalLM = __webpack_exports__.Starcoder2ForCausalLM;
/******/ var __webpack_exports__Starcoder2Model = __webpack_exports__.Starcoder2Model;
/******/ var __webpack_exports__Starcoder2PreTrainedModel = __webpack_exports__.Starcoder2PreTrainedModel;
/******/ var __webpack_exports__SummarizationPipeline = __webpack_exports__.SummarizationPipeline;
/******/ var __webpack_exports__Swin2SRForImageSuperResolution = __webpack_exports__.Swin2SRForImageSuperResolution;
/******/ var __webpack_exports__Swin2SRImageProcessor = __webpack_exports__.Swin2SRImageProcessor;
/******/ var __webpack_exports__Swin2SRModel = __webpack_exports__.Swin2SRModel;
/******/ var __webpack_exports__Swin2SRPreTrainedModel = __webpack_exports__.Swin2SRPreTrainedModel;
/******/ var __webpack_exports__SwinForImageClassification = __webpack_exports__.SwinForImageClassification;
/******/ var __webpack_exports__SwinModel = __webpack_exports__.SwinModel;
/******/ var __webpack_exports__SwinPreTrainedModel = __webpack_exports__.SwinPreTrainedModel;
/******/ var __webpack_exports__T5ForConditionalGeneration = __webpack_exports__.T5ForConditionalGeneration;
/******/ var __webpack_exports__T5Model = __webpack_exports__.T5Model;
/******/ var __webpack_exports__T5PreTrainedModel = __webpack_exports__.T5PreTrainedModel;
/******/ var __webpack_exports__T5Tokenizer = __webpack_exports__.T5Tokenizer;
/******/ var __webpack_exports__TableTransformerForObjectDetection = __webpack_exports__.TableTransformerForObjectDetection;
/******/ var __webpack_exports__TableTransformerModel = __webpack_exports__.TableTransformerModel;
/******/ var __webpack_exports__TableTransformerObjectDetectionOutput = __webpack_exports__.TableTransformerObjectDetectionOutput;
/******/ var __webpack_exports__TableTransformerPreTrainedModel = __webpack_exports__.TableTransformerPreTrainedModel;
/******/ var __webpack_exports__Tensor = __webpack_exports__.Tensor;
/******/ var __webpack_exports__Text2TextGenerationPipeline = __webpack_exports__.Text2TextGenerationPipeline;
/******/ var __webpack_exports__TextClassificationPipeline = __webpack_exports__.TextClassificationPipeline;
/******/ var __webpack_exports__TextGenerationPipeline = __webpack_exports__.TextGenerationPipeline;
/******/ var __webpack_exports__TextToAudioPipeline = __webpack_exports__.TextToAudioPipeline;
/******/ var __webpack_exports__TokenClassificationPipeline = __webpack_exports__.TokenClassificationPipeline;
/******/ var __webpack_exports__TokenClassifierOutput = __webpack_exports__.TokenClassifierOutput;
/******/ var __webpack_exports__TokenizerModel = __webpack_exports__.TokenizerModel;
/******/ var __webpack_exports__TrOCRForCausalLM = __webpack_exports__.TrOCRForCausalLM;
/******/ var __webpack_exports__TrOCRPreTrainedModel = __webpack_exports__.TrOCRPreTrainedModel;
/******/ var __webpack_exports__TranslationPipeline = __webpack_exports__.TranslationPipeline;
/******/ var __webpack_exports__UniSpeechForCTC = __webpack_exports__.UniSpeechForCTC;
/******/ var __webpack_exports__UniSpeechForSequenceClassification = __webpack_exports__.UniSpeechForSequenceClassification;
/******/ var __webpack_exports__UniSpeechModel = __webpack_exports__.UniSpeechModel;
/******/ var __webpack_exports__UniSpeechPreTrainedModel = __webpack_exports__.UniSpeechPreTrainedModel;
/******/ var __webpack_exports__UniSpeechSatForAudioFrameClassification = __webpack_exports__.UniSpeechSatForAudioFrameClassification;
/******/ var __webpack_exports__UniSpeechSatForCTC = __webpack_exports__.UniSpeechSatForCTC;
/******/ var __webpack_exports__UniSpeechSatForSequenceClassification = __webpack_exports__.UniSpeechSatForSequenceClassification;
/******/ var __webpack_exports__UniSpeechSatModel = __webpack_exports__.UniSpeechSatModel;
/******/ var __webpack_exports__UniSpeechSatPreTrainedModel = __webpack_exports__.UniSpeechSatPreTrainedModel;
/******/ var __webpack_exports__ViTFeatureExtractor = __webpack_exports__.ViTFeatureExtractor;
/******/ var __webpack_exports__ViTForImageClassification = __webpack_exports__.ViTForImageClassification;
/******/ var __webpack_exports__ViTImageProcessor = __webpack_exports__.ViTImageProcessor;
/******/ var __webpack_exports__ViTModel = __webpack_exports__.ViTModel;
/******/ var __webpack_exports__ViTPreTrainedModel = __webpack_exports__.ViTPreTrainedModel;
/******/ var __webpack_exports__VisionEncoderDecoderModel = __webpack_exports__.VisionEncoderDecoderModel;
/******/ var __webpack_exports__VitMatteForImageMatting = __webpack_exports__.VitMatteForImageMatting;
/******/ var __webpack_exports__VitMatteImageProcessor = __webpack_exports__.VitMatteImageProcessor;
/******/ var __webpack_exports__VitMattePreTrainedModel = __webpack_exports__.VitMattePreTrainedModel;
/******/ var __webpack_exports__VitsModel = __webpack_exports__.VitsModel;
/******/ var __webpack_exports__VitsModelOutput = __webpack_exports__.VitsModelOutput;
/******/ var __webpack_exports__VitsPreTrainedModel = __webpack_exports__.VitsPreTrainedModel;
/******/ var __webpack_exports__VitsTokenizer = __webpack_exports__.VitsTokenizer;
/******/ var __webpack_exports__Wav2Vec2BertForCTC = __webpack_exports__.Wav2Vec2BertForCTC;
/******/ var __webpack_exports__Wav2Vec2BertForSequenceClassification = __webpack_exports__.Wav2Vec2BertForSequenceClassification;
/******/ var __webpack_exports__Wav2Vec2BertModel = __webpack_exports__.Wav2Vec2BertModel;
/******/ var __webpack_exports__Wav2Vec2BertPreTrainedModel = __webpack_exports__.Wav2Vec2BertPreTrainedModel;
/******/ var __webpack_exports__Wav2Vec2CTCTokenizer = __webpack_exports__.Wav2Vec2CTCTokenizer;
/******/ var __webpack_exports__Wav2Vec2FeatureExtractor = __webpack_exports__.Wav2Vec2FeatureExtractor;
/******/ var __webpack_exports__Wav2Vec2ForAudioFrameClassification = __webpack_exports__.Wav2Vec2ForAudioFrameClassification;
/******/ var __webpack_exports__Wav2Vec2ForCTC = __webpack_exports__.Wav2Vec2ForCTC;
/******/ var __webpack_exports__Wav2Vec2ForSequenceClassification = __webpack_exports__.Wav2Vec2ForSequenceClassification;
/******/ var __webpack_exports__Wav2Vec2Model = __webpack_exports__.Wav2Vec2Model;
/******/ var __webpack_exports__Wav2Vec2PreTrainedModel = __webpack_exports__.Wav2Vec2PreTrainedModel;
/******/ var __webpack_exports__Wav2Vec2ProcessorWithLM = __webpack_exports__.Wav2Vec2ProcessorWithLM;
/******/ var __webpack_exports__WavLMForAudioFrameClassification = __webpack_exports__.WavLMForAudioFrameClassification;
/******/ var __webpack_exports__WavLMForCTC = __webpack_exports__.WavLMForCTC;
/******/ var __webpack_exports__WavLMForSequenceClassification = __webpack_exports__.WavLMForSequenceClassification;
/******/ var __webpack_exports__WavLMForXVector = __webpack_exports__.WavLMForXVector;
/******/ var __webpack_exports__WavLMModel = __webpack_exports__.WavLMModel;
/******/ var __webpack_exports__WavLMPreTrainedModel = __webpack_exports__.WavLMPreTrainedModel;
/******/ var __webpack_exports__WhisperFeatureExtractor = __webpack_exports__.WhisperFeatureExtractor;
/******/ var __webpack_exports__WhisperForConditionalGeneration = __webpack_exports__.WhisperForConditionalGeneration;
/******/ var __webpack_exports__WhisperModel = __webpack_exports__.WhisperModel;
/******/ var __webpack_exports__WhisperPreTrainedModel = __webpack_exports__.WhisperPreTrainedModel;
/******/ var __webpack_exports__WhisperProcessor = __webpack_exports__.WhisperProcessor;
/******/ var __webpack_exports__WhisperTokenizer = __webpack_exports__.WhisperTokenizer;
/******/ var __webpack_exports__XLMForQuestionAnswering = __webpack_exports__.XLMForQuestionAnswering;
/******/ var __webpack_exports__XLMForSequenceClassification = __webpack_exports__.XLMForSequenceClassification;
/******/ var __webpack_exports__XLMForTokenClassification = __webpack_exports__.XLMForTokenClassification;
/******/ var __webpack_exports__XLMModel = __webpack_exports__.XLMModel;
/******/ var __webpack_exports__XLMPreTrainedModel = __webpack_exports__.XLMPreTrainedModel;
/******/ var __webpack_exports__XLMRobertaForMaskedLM = __webpack_exports__.XLMRobertaForMaskedLM;
/******/ var __webpack_exports__XLMRobertaForQuestionAnswering = __webpack_exports__.XLMRobertaForQuestionAnswering;
/******/ var __webpack_exports__XLMRobertaForSequenceClassification = __webpack_exports__.XLMRobertaForSequenceClassification;
/******/ var __webpack_exports__XLMRobertaForTokenClassification = __webpack_exports__.XLMRobertaForTokenClassification;
/******/ var __webpack_exports__XLMRobertaModel = __webpack_exports__.XLMRobertaModel;
/******/ var __webpack_exports__XLMRobertaPreTrainedModel = __webpack_exports__.XLMRobertaPreTrainedModel;
/******/ var __webpack_exports__XLMRobertaTokenizer = __webpack_exports__.XLMRobertaTokenizer;
/******/ var __webpack_exports__XLMTokenizer = __webpack_exports__.XLMTokenizer;
/******/ var __webpack_exports__XLMWithLMHeadModel = __webpack_exports__.XLMWithLMHeadModel;
/******/ var __webpack_exports__XVectorOutput = __webpack_exports__.XVectorOutput;
/******/ var __webpack_exports__YolosFeatureExtractor = __webpack_exports__.YolosFeatureExtractor;
/******/ var __webpack_exports__YolosForObjectDetection = __webpack_exports__.YolosForObjectDetection;
/******/ var __webpack_exports__YolosModel = __webpack_exports__.YolosModel;
/******/ var __webpack_exports__YolosObjectDetectionOutput = __webpack_exports__.YolosObjectDetectionOutput;
/******/ var __webpack_exports__YolosPreTrainedModel = __webpack_exports__.YolosPreTrainedModel;
/******/ var __webpack_exports__ZeroShotAudioClassificationPipeline = __webpack_exports__.ZeroShotAudioClassificationPipeline;
/******/ var __webpack_exports__ZeroShotClassificationPipeline = __webpack_exports__.ZeroShotClassificationPipeline;
/******/ var __webpack_exports__ZeroShotImageClassificationPipeline = __webpack_exports__.ZeroShotImageClassificationPipeline;
/******/ var __webpack_exports__ZeroShotObjectDetectionPipeline = __webpack_exports__.ZeroShotObjectDetectionPipeline;
/******/ var __webpack_exports__bankers_round = __webpack_exports__.bankers_round;
/******/ var __webpack_exports__cat = __webpack_exports__.cat;
/******/ var __webpack_exports__cos_sim = __webpack_exports__.cos_sim;
/******/ var __webpack_exports__dot = __webpack_exports__.dot;
/******/ var __webpack_exports__dynamicTimeWarping = __webpack_exports__.dynamicTimeWarping;
/******/ var __webpack_exports__env = __webpack_exports__.env;
/******/ var __webpack_exports__getTopItems = __webpack_exports__.getTopItems;
/******/ var __webpack_exports__hanning = __webpack_exports__.hanning;
/******/ var __webpack_exports__interpolate = __webpack_exports__.interpolate;
/******/ var __webpack_exports__interpolate_data = __webpack_exports__.interpolate_data;
/******/ var __webpack_exports__layer_norm = __webpack_exports__.layer_norm;
/******/ var __webpack_exports__log_softmax = __webpack_exports__.log_softmax;
/******/ var __webpack_exports__magnitude = __webpack_exports__.magnitude;
/******/ var __webpack_exports__max = __webpack_exports__.max;
/******/ var __webpack_exports__mean = __webpack_exports__.mean;
/******/ var __webpack_exports__mean_pooling = __webpack_exports__.mean_pooling;
/******/ var __webpack_exports__medianFilter = __webpack_exports__.medianFilter;
/******/ var __webpack_exports__mel_filter_bank = __webpack_exports__.mel_filter_bank;
/******/ var __webpack_exports__min = __webpack_exports__.min;
/******/ var __webpack_exports__ones = __webpack_exports__.ones;
/******/ var __webpack_exports__ones_like = __webpack_exports__.ones_like;
/******/ var __webpack_exports__permute = __webpack_exports__.permute;
/******/ var __webpack_exports__permute_data = __webpack_exports__.permute_data;
/******/ var __webpack_exports__pipeline = __webpack_exports__.pipeline;
/******/ var __webpack_exports__quantize_embeddings = __webpack_exports__.quantize_embeddings;
/******/ var __webpack_exports__read_audio = __webpack_exports__.read_audio;
/******/ var __webpack_exports__round = __webpack_exports__.round;
/******/ var __webpack_exports__softmax = __webpack_exports__.softmax;
/******/ var __webpack_exports__spectrogram = __webpack_exports__.spectrogram;
/******/ var __webpack_exports__stack = __webpack_exports__.stack;
/******/ var __webpack_exports__std_mean = __webpack_exports__.std_mean;
/******/ var __webpack_exports__window_function = __webpack_exports__.window_function;
/******/ export { __webpack_exports__ASTFeatureExtractor as ASTFeatureExtractor, __webpack_exports__ASTForAudioClassification as ASTForAudioClassification, __webpack_exports__ASTModel as ASTModel, __webpack_exports__ASTPreTrainedModel as ASTPreTrainedModel, __webpack_exports__AlbertForMaskedLM as AlbertForMaskedLM, __webpack_exports__AlbertForQuestionAnswering as AlbertForQuestionAnswering, __webpack_exports__AlbertForSequenceClassification as AlbertForSequenceClassification, __webpack_exports__AlbertModel as AlbertModel, __webpack_exports__AlbertPreTrainedModel as AlbertPreTrainedModel, __webpack_exports__AlbertTokenizer as AlbertTokenizer, __webpack_exports__AudioClassificationPipeline as AudioClassificationPipeline, __webpack_exports__AutoConfig as AutoConfig, __webpack_exports__AutoModel as AutoModel, __webpack_exports__AutoModelForAudioClassification as AutoModelForAudioClassification, __webpack_exports__AutoModelForAudioFrameClassification as AutoModelForAudioFrameClassification, __webpack_exports__AutoModelForCTC as AutoModelForCTC, __webpack_exports__AutoModelForCausalLM as AutoModelForCausalLM, __webpack_exports__AutoModelForDepthEstimation as AutoModelForDepthEstimation, __webpack_exports__AutoModelForDocumentQuestionAnswering as AutoModelForDocumentQuestionAnswering, __webpack_exports__AutoModelForImageClassification as AutoModelForImageClassification, __webpack_exports__AutoModelForImageFeatureExtraction as AutoModelForImageFeatureExtraction, __webpack_exports__AutoModelForImageMatting as AutoModelForImageMatting, __webpack_exports__AutoModelForImageSegmentation as AutoModelForImageSegmentation, __webpack_exports__AutoModelForImageToImage as AutoModelForImageToImage, __webpack_exports__AutoModelForMaskGeneration as AutoModelForMaskGeneration, __webpack_exports__AutoModelForMaskedLM as AutoModelForMaskedLM, __webpack_exports__AutoModelForObjectDetection as AutoModelForObjectDetection, __webpack_exports__AutoModelForQuestionAnswering as AutoModelForQuestionAnswering, __webpack_exports__AutoModelForSemanticSegmentation as AutoModelForSemanticSegmentation, __webpack_exports__AutoModelForSeq2SeqLM as AutoModelForSeq2SeqLM, __webpack_exports__AutoModelForSequenceClassification as AutoModelForSequenceClassification, __webpack_exports__AutoModelForSpeechSeq2Seq as AutoModelForSpeechSeq2Seq, __webpack_exports__AutoModelForTextToSpectrogram as AutoModelForTextToSpectrogram, __webpack_exports__AutoModelForTextToWaveform as AutoModelForTextToWaveform, __webpack_exports__AutoModelForTokenClassification as AutoModelForTokenClassification, __webpack_exports__AutoModelForVision2Seq as AutoModelForVision2Seq, __webpack_exports__AutoModelForXVector as AutoModelForXVector, __webpack_exports__AutoModelForZeroShotObjectDetection as AutoModelForZeroShotObjectDetection, __webpack_exports__AutoProcessor as AutoProcessor, __webpack_exports__AutoTokenizer as AutoTokenizer, __webpack_exports__AutomaticSpeechRecognitionPipeline as AutomaticSpeechRecognitionPipeline, __webpack_exports__BartForConditionalGeneration as BartForConditionalGeneration, __webpack_exports__BartForSequenceClassification as BartForSequenceClassification, __webpack_exports__BartModel as BartModel, __webpack_exports__BartPretrainedModel as BartPretrainedModel, __webpack_exports__BartTokenizer as BartTokenizer, __webpack_exports__BaseModelOutput as BaseModelOutput, __webpack_exports__BeitFeatureExtractor as BeitFeatureExtractor, __webpack_exports__BeitForImageClassification as BeitForImageClassification, __webpack_exports__BeitModel as BeitModel, __webpack_exports__BeitPreTrainedModel as BeitPreTrainedModel, __webpack_exports__BertForMaskedLM as BertForMaskedLM, __webpack_exports__BertForQuestionAnswering as BertForQuestionAnswering, __webpack_exports__BertForSequenceClassification as BertForSequenceClassification, __webpack_exports__BertForTokenClassification as BertForTokenClassification, __webpack_exports__BertModel as BertModel, __webpack_exports__BertPreTrainedModel as BertPreTrainedModel, __webpack_exports__BertTokenizer as BertTokenizer, __webpack_exports__BitImageProcessor as BitImageProcessor, __webpack_exports__BlenderbotForConditionalGeneration as BlenderbotForConditionalGeneration, __webpack_exports__BlenderbotModel as BlenderbotModel, __webpack_exports__BlenderbotPreTrainedModel as BlenderbotPreTrainedModel, __webpack_exports__BlenderbotSmallForConditionalGeneration as BlenderbotSmallForConditionalGeneration, __webpack_exports__BlenderbotSmallModel as BlenderbotSmallModel, __webpack_exports__BlenderbotSmallPreTrainedModel as BlenderbotSmallPreTrainedModel, __webpack_exports__BlenderbotSmallTokenizer as BlenderbotSmallTokenizer, __webpack_exports__BlenderbotTokenizer as BlenderbotTokenizer, __webpack_exports__BloomForCausalLM as BloomForCausalLM, __webpack_exports__BloomModel as BloomModel, __webpack_exports__BloomPreTrainedModel as BloomPreTrainedModel, __webpack_exports__BloomTokenizer as BloomTokenizer, __webpack_exports__CLIPFeatureExtractor as CLIPFeatureExtractor, __webpack_exports__CLIPModel as CLIPModel, __webpack_exports__CLIPPreTrainedModel as CLIPPreTrainedModel, __webpack_exports__CLIPSegForImageSegmentation as CLIPSegForImageSegmentation, __webpack_exports__CLIPSegModel as CLIPSegModel, __webpack_exports__CLIPSegPreTrainedModel as CLIPSegPreTrainedModel, __webpack_exports__CLIPTextModelWithProjection as CLIPTextModelWithProjection, __webpack_exports__CLIPTokenizer as CLIPTokenizer, __webpack_exports__CLIPVisionModelWithProjection as CLIPVisionModelWithProjection, __webpack_exports__CamembertForMaskedLM as CamembertForMaskedLM, __webpack_exports__CamembertForQuestionAnswering as CamembertForQuestionAnswering, __webpack_exports__CamembertForSequenceClassification as CamembertForSequenceClassification, __webpack_exports__CamembertForTokenClassification as CamembertForTokenClassification, __webpack_exports__CamembertModel as CamembertModel, __webpack_exports__CamembertPreTrainedModel as CamembertPreTrainedModel, __webpack_exports__CamembertTokenizer as CamembertTokenizer, __webpack_exports__CausalLMOutput as CausalLMOutput, __webpack_exports__CausalLMOutputWithPast as CausalLMOutputWithPast, __webpack_exports__ChineseCLIPFeatureExtractor as ChineseCLIPFeatureExtractor, __webpack_exports__ChineseCLIPModel as ChineseCLIPModel, __webpack_exports__ChineseCLIPPreTrainedModel as ChineseCLIPPreTrainedModel, __webpack_exports__ClapAudioModelWithProjection as ClapAudioModelWithProjection, __webpack_exports__ClapFeatureExtractor as ClapFeatureExtractor, __webpack_exports__ClapModel as ClapModel, __webpack_exports__ClapPreTrainedModel as ClapPreTrainedModel, __webpack_exports__ClapTextModelWithProjection as ClapTextModelWithProjection, __webpack_exports__CodeGenForCausalLM as CodeGenForCausalLM, __webpack_exports__CodeGenModel as CodeGenModel, __webpack_exports__CodeGenPreTrainedModel as CodeGenPreTrainedModel, __webpack_exports__CodeGenTokenizer as CodeGenTokenizer, __webpack_exports__CodeLlamaTokenizer as CodeLlamaTokenizer, __webpack_exports__CohereTokenizer as CohereTokenizer, __webpack_exports__ConvBertForMaskedLM as ConvBertForMaskedLM, __webpack_exports__ConvBertForQuestionAnswering as ConvBertForQuestionAnswering, __webpack_exports__ConvBertForSequenceClassification as ConvBertForSequenceClassification, __webpack_exports__ConvBertForTokenClassification as ConvBertForTokenClassification, __webpack_exports__ConvBertModel as ConvBertModel, __webpack_exports__ConvBertPreTrainedModel as ConvBertPreTrainedModel, __webpack_exports__ConvBertTokenizer as ConvBertTokenizer, __webpack_exports__ConvNextFeatureExtractor as ConvNextFeatureExtractor, __webpack_exports__ConvNextForImageClassification as ConvNextForImageClassification, __webpack_exports__ConvNextImageProcessor as ConvNextImageProcessor, __webpack_exports__ConvNextModel as ConvNextModel, __webpack_exports__ConvNextPreTrainedModel as ConvNextPreTrainedModel, __webpack_exports__ConvNextV2ForImageClassification as ConvNextV2ForImageClassification, __webpack_exports__ConvNextV2Model as ConvNextV2Model, __webpack_exports__ConvNextV2PreTrainedModel as ConvNextV2PreTrainedModel, __webpack_exports__DPTFeatureExtractor as DPTFeatureExtractor, __webpack_exports__DPTForDepthEstimation as DPTForDepthEstimation, __webpack_exports__DPTImageProcessor as DPTImageProcessor, __webpack_exports__DPTModel as DPTModel, __webpack_exports__DPTPreTrainedModel as DPTPreTrainedModel, __webpack_exports__DebertaForMaskedLM as DebertaForMaskedLM, __webpack_exports__DebertaForQuestionAnswering as DebertaForQuestionAnswering, __webpack_exports__DebertaForSequenceClassification as DebertaForSequenceClassification, __webpack_exports__DebertaForTokenClassification as DebertaForTokenClassification, __webpack_exports__DebertaModel as DebertaModel, __webpack_exports__DebertaPreTrainedModel as DebertaPreTrainedModel, __webpack_exports__DebertaTokenizer as DebertaTokenizer, __webpack_exports__DebertaV2ForMaskedLM as DebertaV2ForMaskedLM, __webpack_exports__DebertaV2ForQuestionAnswering as DebertaV2ForQuestionAnswering, __webpack_exports__DebertaV2ForSequenceClassification as DebertaV2ForSequenceClassification, __webpack_exports__DebertaV2ForTokenClassification as DebertaV2ForTokenClassification, __webpack_exports__DebertaV2Model as DebertaV2Model, __webpack_exports__DebertaV2PreTrainedModel as DebertaV2PreTrainedModel, __webpack_exports__DebertaV2Tokenizer as DebertaV2Tokenizer, __webpack_exports__DeiTFeatureExtractor as DeiTFeatureExtractor, __webpack_exports__DeiTForImageClassification as DeiTForImageClassification, __webpack_exports__DeiTModel as DeiTModel, __webpack_exports__DeiTPreTrainedModel as DeiTPreTrainedModel, __webpack_exports__DepthAnythingForDepthEstimation as DepthAnythingForDepthEstimation, __webpack_exports__DepthAnythingPreTrainedModel as DepthAnythingPreTrainedModel, __webpack_exports__DepthEstimationPipeline as DepthEstimationPipeline, __webpack_exports__DetrFeatureExtractor as DetrFeatureExtractor, __webpack_exports__DetrForObjectDetection as DetrForObjectDetection, __webpack_exports__DetrForSegmentation as DetrForSegmentation, __webpack_exports__DetrModel as DetrModel, __webpack_exports__DetrObjectDetectionOutput as DetrObjectDetectionOutput, __webpack_exports__DetrPreTrainedModel as DetrPreTrainedModel, __webpack_exports__DetrSegmentationOutput as DetrSegmentationOutput, __webpack_exports__Dinov2ForImageClassification as Dinov2ForImageClassification, __webpack_exports__Dinov2Model as Dinov2Model, __webpack_exports__Dinov2PreTrainedModel as Dinov2PreTrainedModel, __webpack_exports__DistilBertForMaskedLM as DistilBertForMaskedLM, __webpack_exports__DistilBertForQuestionAnswering as DistilBertForQuestionAnswering, __webpack_exports__DistilBertForSequenceClassification as DistilBertForSequenceClassification, __webpack_exports__DistilBertForTokenClassification as DistilBertForTokenClassification, __webpack_exports__DistilBertModel as DistilBertModel, __webpack_exports__DistilBertPreTrainedModel as DistilBertPreTrainedModel, __webpack_exports__DistilBertTokenizer as DistilBertTokenizer, __webpack_exports__DocumentQuestionAnsweringPipeline as DocumentQuestionAnsweringPipeline, __webpack_exports__DonutFeatureExtractor as DonutFeatureExtractor, __webpack_exports__DonutSwinModel as DonutSwinModel, __webpack_exports__DonutSwinPreTrainedModel as DonutSwinPreTrainedModel, __webpack_exports__EfficientNetForImageClassification as EfficientNetForImageClassification, __webpack_exports__EfficientNetImageProcessor as EfficientNetImageProcessor, __webpack_exports__EfficientNetModel as EfficientNetModel, __webpack_exports__EfficientNetPreTrainedModel as EfficientNetPreTrainedModel, __webpack_exports__ElectraForMaskedLM as ElectraForMaskedLM, __webpack_exports__ElectraForQuestionAnswering as ElectraForQuestionAnswering, __webpack_exports__ElectraForSequenceClassification as ElectraForSequenceClassification, __webpack_exports__ElectraForTokenClassification as ElectraForTokenClassification, __webpack_exports__ElectraModel as ElectraModel, __webpack_exports__ElectraPreTrainedModel as ElectraPreTrainedModel, __webpack_exports__ElectraTokenizer as ElectraTokenizer, __webpack_exports__EsmForMaskedLM as EsmForMaskedLM, __webpack_exports__EsmForSequenceClassification as EsmForSequenceClassification, __webpack_exports__EsmForTokenClassification as EsmForTokenClassification, __webpack_exports__EsmModel as EsmModel, __webpack_exports__EsmPreTrainedModel as EsmPreTrainedModel, __webpack_exports__EsmTokenizer as EsmTokenizer, __webpack_exports__FFT as FFT, __webpack_exports__FalconForCausalLM as FalconForCausalLM, __webpack_exports__FalconModel as FalconModel, __webpack_exports__FalconPreTrainedModel as FalconPreTrainedModel, __webpack_exports__FalconTokenizer as FalconTokenizer, __webpack_exports__FastViTForImageClassification as FastViTForImageClassification, __webpack_exports__FastViTModel as FastViTModel, __webpack_exports__FastViTPreTrainedModel as FastViTPreTrainedModel, __webpack_exports__FeatureExtractionPipeline as FeatureExtractionPipeline, __webpack_exports__FeatureExtractor as FeatureExtractor, __webpack_exports__FillMaskPipeline as FillMaskPipeline, __webpack_exports__GLPNFeatureExtractor as GLPNFeatureExtractor, __webpack_exports__GLPNForDepthEstimation as GLPNForDepthEstimation, __webpack_exports__GLPNModel as GLPNModel, __webpack_exports__GLPNPreTrainedModel as GLPNPreTrainedModel, __webpack_exports__GPT2LMHeadModel as GPT2LMHeadModel, __webpack_exports__GPT2Model as GPT2Model, __webpack_exports__GPT2PreTrainedModel as GPT2PreTrainedModel, __webpack_exports__GPT2Tokenizer as GPT2Tokenizer, __webpack_exports__GPTBigCodeForCausalLM as GPTBigCodeForCausalLM, __webpack_exports__GPTBigCodeModel as GPTBigCodeModel, __webpack_exports__GPTBigCodePreTrainedModel as GPTBigCodePreTrainedModel, __webpack_exports__GPTJForCausalLM as GPTJForCausalLM, __webpack_exports__GPTJModel as GPTJModel, __webpack_exports__GPTJPreTrainedModel as GPTJPreTrainedModel, __webpack_exports__GPTNeoForCausalLM as GPTNeoForCausalLM, __webpack_exports__GPTNeoModel as GPTNeoModel, __webpack_exports__GPTNeoPreTrainedModel as GPTNeoPreTrainedModel, __webpack_exports__GPTNeoXForCausalLM as GPTNeoXForCausalLM, __webpack_exports__GPTNeoXModel as GPTNeoXModel, __webpack_exports__GPTNeoXPreTrainedModel as GPTNeoXPreTrainedModel, __webpack_exports__GPTNeoXTokenizer as GPTNeoXTokenizer, __webpack_exports__GemmaTokenizer as GemmaTokenizer, __webpack_exports__Grok1Tokenizer as Grok1Tokenizer, __webpack_exports__HerbertTokenizer as HerbertTokenizer, __webpack_exports__HubertForCTC as HubertForCTC, __webpack_exports__HubertForSequenceClassification as HubertForSequenceClassification, __webpack_exports__HubertModel as HubertModel, __webpack_exports__HubertPreTrainedModel as HubertPreTrainedModel, __webpack_exports__ImageClassificationPipeline as ImageClassificationPipeline, __webpack_exports__ImageFeatureExtractionPipeline as ImageFeatureExtractionPipeline, __webpack_exports__ImageFeatureExtractor as ImageFeatureExtractor, __webpack_exports__ImageMattingOutput as ImageMattingOutput, __webpack_exports__ImageSegmentationPipeline as ImageSegmentationPipeline, __webpack_exports__ImageToImagePipeline as ImageToImagePipeline, __webpack_exports__ImageToTextPipeline as ImageToTextPipeline, __webpack_exports__LlamaForCausalLM as LlamaForCausalLM, __webpack_exports__LlamaModel as LlamaModel, __webpack_exports__LlamaPreTrainedModel as LlamaPreTrainedModel, __webpack_exports__LlamaTokenizer as LlamaTokenizer, __webpack_exports__LongT5ForConditionalGeneration as LongT5ForConditionalGeneration, __webpack_exports__LongT5Model as LongT5Model, __webpack_exports__LongT5PreTrainedModel as LongT5PreTrainedModel, __webpack_exports__M2M100ForConditionalGeneration as M2M100ForConditionalGeneration, __webpack_exports__M2M100Model as M2M100Model, __webpack_exports__M2M100PreTrainedModel as M2M100PreTrainedModel, __webpack_exports__M2M100Tokenizer as M2M100Tokenizer, __webpack_exports__MBart50Tokenizer as MBart50Tokenizer, __webpack_exports__MBartForCausalLM as MBartForCausalLM, __webpack_exports__MBartForConditionalGeneration as MBartForConditionalGeneration, __webpack_exports__MBartForSequenceClassification as MBartForSequenceClassification, __webpack_exports__MBartModel as MBartModel, __webpack_exports__MBartPreTrainedModel as MBartPreTrainedModel, __webpack_exports__MBartTokenizer as MBartTokenizer, __webpack_exports__MPNetForMaskedLM as MPNetForMaskedLM, __webpack_exports__MPNetForQuestionAnswering as MPNetForQuestionAnswering, __webpack_exports__MPNetForSequenceClassification as MPNetForSequenceClassification, __webpack_exports__MPNetForTokenClassification as MPNetForTokenClassification, __webpack_exports__MPNetModel as MPNetModel, __webpack_exports__MPNetPreTrainedModel as MPNetPreTrainedModel, __webpack_exports__MPNetTokenizer as MPNetTokenizer, __webpack_exports__MT5ForConditionalGeneration as MT5ForConditionalGeneration, __webpack_exports__MT5Model as MT5Model, __webpack_exports__MT5PreTrainedModel as MT5PreTrainedModel, __webpack_exports__MarianMTModel as MarianMTModel, __webpack_exports__MarianModel as MarianModel, __webpack_exports__MarianPreTrainedModel as MarianPreTrainedModel, __webpack_exports__MarianTokenizer as MarianTokenizer, __webpack_exports__MaskedLMOutput as MaskedLMOutput, __webpack_exports__MistralForCausalLM as MistralForCausalLM, __webpack_exports__MistralModel as MistralModel, __webpack_exports__MistralPreTrainedModel as MistralPreTrainedModel, __webpack_exports__MobileBertForMaskedLM as MobileBertForMaskedLM, __webpack_exports__MobileBertForQuestionAnswering as MobileBertForQuestionAnswering, __webpack_exports__MobileBertForSequenceClassification as MobileBertForSequenceClassification, __webpack_exports__MobileBertModel as MobileBertModel, __webpack_exports__MobileBertPreTrainedModel as MobileBertPreTrainedModel, __webpack_exports__MobileBertTokenizer as MobileBertTokenizer, __webpack_exports__MobileViTFeatureExtractor as MobileViTFeatureExtractor, __webpack_exports__MobileViTForImageClassification as MobileViTForImageClassification, __webpack_exports__MobileViTImageProcessor as MobileViTImageProcessor, __webpack_exports__MobileViTModel as MobileViTModel, __webpack_exports__MobileViTPreTrainedModel as MobileViTPreTrainedModel, __webpack_exports__MobileViTV2ForImageClassification as MobileViTV2ForImageClassification, __webpack_exports__MobileViTV2Model as MobileViTV2Model, __webpack_exports__MobileViTV2PreTrainedModel as MobileViTV2PreTrainedModel, __webpack_exports__ModelOutput as ModelOutput, __webpack_exports__MptForCausalLM as MptForCausalLM, __webpack_exports__MptModel as MptModel, __webpack_exports__MptPreTrainedModel as MptPreTrainedModel, __webpack_exports__NllbTokenizer as NllbTokenizer, __webpack_exports__NomicBertModel as NomicBertModel, __webpack_exports__NomicBertPreTrainedModel as NomicBertPreTrainedModel, __webpack_exports__NougatImageProcessor as NougatImageProcessor, __webpack_exports__NougatTokenizer as NougatTokenizer, __webpack_exports__OPTForCausalLM as OPTForCausalLM, __webpack_exports__OPTModel as OPTModel, __webpack_exports__OPTPreTrainedModel as OPTPreTrainedModel, __webpack_exports__ObjectDetectionPipeline as ObjectDetectionPipeline, __webpack_exports__OwlViTFeatureExtractor as OwlViTFeatureExtractor, __webpack_exports__OwlViTForObjectDetection as OwlViTForObjectDetection, __webpack_exports__OwlViTModel as OwlViTModel, __webpack_exports__OwlViTPreTrainedModel as OwlViTPreTrainedModel, __webpack_exports__OwlViTProcessor as OwlViTProcessor, __webpack_exports__Owlv2ForObjectDetection as Owlv2ForObjectDetection, __webpack_exports__Owlv2ImageProcessor as Owlv2ImageProcessor, __webpack_exports__Owlv2Model as Owlv2Model, __webpack_exports__Owlv2PreTrainedModel as Owlv2PreTrainedModel, __webpack_exports__PhiForCausalLM as PhiForCausalLM, __webpack_exports__PhiModel as PhiModel, __webpack_exports__PhiPreTrainedModel as PhiPreTrainedModel, __webpack_exports__Pipeline as Pipeline, __webpack_exports__PreTrainedModel as PreTrainedModel, __webpack_exports__PreTrainedTokenizer as PreTrainedTokenizer, __webpack_exports__PretrainedConfig as PretrainedConfig, __webpack_exports__PretrainedMixin as PretrainedMixin, __webpack_exports__Processor as Processor, __webpack_exports__QuestionAnsweringModelOutput as QuestionAnsweringModelOutput, __webpack_exports__QuestionAnsweringPipeline as QuestionAnsweringPipeline, __webpack_exports__Qwen2ForCausalLM as Qwen2ForCausalLM, __webpack_exports__Qwen2Model as Qwen2Model, __webpack_exports__Qwen2PreTrainedModel as Qwen2PreTrainedModel, __webpack_exports__Qwen2Tokenizer as Qwen2Tokenizer, __webpack_exports__RawImage as RawImage, __webpack_exports__ResNetForImageClassification as ResNetForImageClassification, __webpack_exports__ResNetModel as ResNetModel, __webpack_exports__ResNetPreTrainedModel as ResNetPreTrainedModel, __webpack_exports__RoFormerForMaskedLM as RoFormerForMaskedLM, __webpack_exports__RoFormerForQuestionAnswering as RoFormerForQuestionAnswering, __webpack_exports__RoFormerForSequenceClassification as RoFormerForSequenceClassification, __webpack_exports__RoFormerForTokenClassification as RoFormerForTokenClassification, __webpack_exports__RoFormerModel as RoFormerModel, __webpack_exports__RoFormerPreTrainedModel as RoFormerPreTrainedModel, __webpack_exports__RoFormerTokenizer as RoFormerTokenizer, __webpack_exports__RobertaForMaskedLM as RobertaForMaskedLM, __webpack_exports__RobertaForQuestionAnswering as RobertaForQuestionAnswering, __webpack_exports__RobertaForSequenceClassification as RobertaForSequenceClassification, __webpack_exports__RobertaForTokenClassification as RobertaForTokenClassification, __webpack_exports__RobertaModel as RobertaModel, __webpack_exports__RobertaPreTrainedModel as RobertaPreTrainedModel, __webpack_exports__RobertaTokenizer as RobertaTokenizer, __webpack_exports__SamImageProcessor as SamImageProcessor, __webpack_exports__SamImageSegmentationOutput as SamImageSegmentationOutput, __webpack_exports__SamModel as SamModel, __webpack_exports__SamPreTrainedModel as SamPreTrainedModel, __webpack_exports__SamProcessor as SamProcessor, __webpack_exports__SeamlessM4TFeatureExtractor as SeamlessM4TFeatureExtractor, __webpack_exports__SegformerFeatureExtractor as SegformerFeatureExtractor, __webpack_exports__SegformerForImageClassification as SegformerForImageClassification, __webpack_exports__SegformerForSemanticSegmentation as SegformerForSemanticSegmentation, __webpack_exports__SegformerModel as SegformerModel, __webpack_exports__SegformerPreTrainedModel as SegformerPreTrainedModel, __webpack_exports__Seq2SeqLMOutput as Seq2SeqLMOutput, __webpack_exports__SequenceClassifierOutput as SequenceClassifierOutput, __webpack_exports__SiglipImageProcessor as SiglipImageProcessor, __webpack_exports__SiglipModel as SiglipModel, __webpack_exports__SiglipPreTrainedModel as SiglipPreTrainedModel, __webpack_exports__SiglipTextModel as SiglipTextModel, __webpack_exports__SiglipTokenizer as SiglipTokenizer, __webpack_exports__SiglipVisionModel as SiglipVisionModel, __webpack_exports__SpeechT5FeatureExtractor as SpeechT5FeatureExtractor, __webpack_exports__SpeechT5ForSpeechToText as SpeechT5ForSpeechToText, __webpack_exports__SpeechT5ForTextToSpeech as SpeechT5ForTextToSpeech, __webpack_exports__SpeechT5HifiGan as SpeechT5HifiGan, __webpack_exports__SpeechT5Model as SpeechT5Model, __webpack_exports__SpeechT5PreTrainedModel as SpeechT5PreTrainedModel, __webpack_exports__SpeechT5Processor as SpeechT5Processor, __webpack_exports__SpeechT5Tokenizer as SpeechT5Tokenizer, __webpack_exports__SqueezeBertForMaskedLM as SqueezeBertForMaskedLM, __webpack_exports__SqueezeBertForQuestionAnswering as SqueezeBertForQuestionAnswering, __webpack_exports__SqueezeBertForSequenceClassification as SqueezeBertForSequenceClassification, __webpack_exports__SqueezeBertModel as SqueezeBertModel, __webpack_exports__SqueezeBertPreTrainedModel as SqueezeBertPreTrainedModel, __webpack_exports__SqueezeBertTokenizer as SqueezeBertTokenizer, __webpack_exports__StableLmForCausalLM as StableLmForCausalLM, __webpack_exports__StableLmModel as StableLmModel, __webpack_exports__StableLmPreTrainedModel as StableLmPreTrainedModel, __webpack_exports__Starcoder2ForCausalLM as Starcoder2ForCausalLM, __webpack_exports__Starcoder2Model as Starcoder2Model, __webpack_exports__Starcoder2PreTrainedModel as Starcoder2PreTrainedModel, __webpack_exports__SummarizationPipeline as SummarizationPipeline, __webpack_exports__Swin2SRForImageSuperResolution as Swin2SRForImageSuperResolution, __webpack_exports__Swin2SRImageProcessor as Swin2SRImageProcessor, __webpack_exports__Swin2SRModel as Swin2SRModel, __webpack_exports__Swin2SRPreTrainedModel as Swin2SRPreTrainedModel, __webpack_exports__SwinForImageClassification as SwinForImageClassification, __webpack_exports__SwinModel as SwinModel, __webpack_exports__SwinPreTrainedModel as SwinPreTrainedModel, __webpack_exports__T5ForConditionalGeneration as T5ForConditionalGeneration, __webpack_exports__T5Model as T5Model, __webpack_exports__T5PreTrainedModel as T5PreTrainedModel, __webpack_exports__T5Tokenizer as T5Tokenizer, __webpack_exports__TableTransformerForObjectDetection as TableTransformerForObjectDetection, __webpack_exports__TableTransformerModel as TableTransformerModel, __webpack_exports__TableTransformerObjectDetectionOutput as TableTransformerObjectDetectionOutput, __webpack_exports__TableTransformerPreTrainedModel as TableTransformerPreTrainedModel, __webpack_exports__Tensor as Tensor, __webpack_exports__Text2TextGenerationPipeline as Text2TextGenerationPipeline, __webpack_exports__TextClassificationPipeline as TextClassificationPipeline, __webpack_exports__TextGenerationPipeline as TextGenerationPipeline, __webpack_exports__TextToAudioPipeline as TextToAudioPipeline, __webpack_exports__TokenClassificationPipeline as TokenClassificationPipeline, __webpack_exports__TokenClassifierOutput as TokenClassifierOutput, __webpack_exports__TokenizerModel as TokenizerModel, __webpack_exports__TrOCRForCausalLM as TrOCRForCausalLM, __webpack_exports__TrOCRPreTrainedModel as TrOCRPreTrainedModel, __webpack_exports__TranslationPipeline as TranslationPipeline, __webpack_exports__UniSpeechForCTC as UniSpeechForCTC, __webpack_exports__UniSpeechForSequenceClassification as UniSpeechForSequenceClassification, __webpack_exports__UniSpeechModel as UniSpeechModel, __webpack_exports__UniSpeechPreTrainedModel as UniSpeechPreTrainedModel, __webpack_exports__UniSpeechSatForAudioFrameClassification as UniSpeechSatForAudioFrameClassification, __webpack_exports__UniSpeechSatForCTC as UniSpeechSatForCTC, __webpack_exports__UniSpeechSatForSequenceClassification as UniSpeechSatForSequenceClassification, __webpack_exports__UniSpeechSatModel as UniSpeechSatModel, __webpack_exports__UniSpeechSatPreTrainedModel as UniSpeechSatPreTrainedModel, __webpack_exports__ViTFeatureExtractor as ViTFeatureExtractor, __webpack_exports__ViTForImageClassification as ViTForImageClassification, __webpack_exports__ViTImageProcessor as ViTImageProcessor, __webpack_exports__ViTModel as ViTModel, __webpack_exports__ViTPreTrainedModel as ViTPreTrainedModel, __webpack_exports__VisionEncoderDecoderModel as VisionEncoderDecoderModel, __webpack_exports__VitMatteForImageMatting as VitMatteForImageMatting, __webpack_exports__VitMatteImageProcessor as VitMatteImageProcessor, __webpack_exports__VitMattePreTrainedModel as VitMattePreTrainedModel, __webpack_exports__VitsModel as VitsModel, __webpack_exports__VitsModelOutput as VitsModelOutput, __webpack_exports__VitsPreTrainedModel as VitsPreTrainedModel, __webpack_exports__VitsTokenizer as VitsTokenizer, __webpack_exports__Wav2Vec2BertForCTC as Wav2Vec2BertForCTC, __webpack_exports__Wav2Vec2BertForSequenceClassification as Wav2Vec2BertForSequenceClassification, __webpack_exports__Wav2Vec2BertModel as Wav2Vec2BertModel, __webpack_exports__Wav2Vec2BertPreTrainedModel as Wav2Vec2BertPreTrainedModel, __webpack_exports__Wav2Vec2CTCTokenizer as Wav2Vec2CTCTokenizer, __webpack_exports__Wav2Vec2FeatureExtractor as Wav2Vec2FeatureExtractor, __webpack_exports__Wav2Vec2ForAudioFrameClassification as Wav2Vec2ForAudioFrameClassification, __webpack_exports__Wav2Vec2ForCTC as Wav2Vec2ForCTC, __webpack_exports__Wav2Vec2ForSequenceClassification as Wav2Vec2ForSequenceClassification, __webpack_exports__Wav2Vec2Model as Wav2Vec2Model, __webpack_exports__Wav2Vec2PreTrainedModel as Wav2Vec2PreTrainedModel, __webpack_exports__Wav2Vec2ProcessorWithLM as Wav2Vec2ProcessorWithLM, __webpack_exports__WavLMForAudioFrameClassification as WavLMForAudioFrameClassification, __webpack_exports__WavLMForCTC as WavLMForCTC, __webpack_exports__WavLMForSequenceClassification as WavLMForSequenceClassification, __webpack_exports__WavLMForXVector as WavLMForXVector, __webpack_exports__WavLMModel as WavLMModel, __webpack_exports__WavLMPreTrainedModel as WavLMPreTrainedModel, __webpack_exports__WhisperFeatureExtractor as WhisperFeatureExtractor, __webpack_exports__WhisperForConditionalGeneration as WhisperForConditionalGeneration, __webpack_exports__WhisperModel as WhisperModel, __webpack_exports__WhisperPreTrainedModel as WhisperPreTrainedModel, __webpack_exports__WhisperProcessor as WhisperProcessor, __webpack_exports__WhisperTokenizer as WhisperTokenizer, __webpack_exports__XLMForQuestionAnswering as XLMForQuestionAnswering, __webpack_exports__XLMForSequenceClassification as XLMForSequenceClassification, __webpack_exports__XLMForTokenClassification as XLMForTokenClassification, __webpack_exports__XLMModel as XLMModel, __webpack_exports__XLMPreTrainedModel as XLMPreTrainedModel, __webpack_exports__XLMRobertaForMaskedLM as XLMRobertaForMaskedLM, __webpack_exports__XLMRobertaForQuestionAnswering as XLMRobertaForQuestionAnswering, __webpack_exports__XLMRobertaForSequenceClassification as XLMRobertaForSequenceClassification, __webpack_exports__XLMRobertaForTokenClassification as XLMRobertaForTokenClassification, __webpack_exports__XLMRobertaModel as XLMRobertaModel, __webpack_exports__XLMRobertaPreTrainedModel as XLMRobertaPreTrainedModel, __webpack_exports__XLMRobertaTokenizer as XLMRobertaTokenizer, __webpack_exports__XLMTokenizer as XLMTokenizer, __webpack_exports__XLMWithLMHeadModel as XLMWithLMHeadModel, __webpack_exports__XVectorOutput as XVectorOutput, __webpack_exports__YolosFeatureExtractor as YolosFeatureExtractor, __webpack_exports__YolosForObjectDetection as YolosForObjectDetection, __webpack_exports__YolosModel as YolosModel, __webpack_exports__YolosObjectDetectionOutput as YolosObjectDetectionOutput, __webpack_exports__YolosPreTrainedModel as YolosPreTrainedModel, __webpack_exports__ZeroShotAudioClassificationPipeline as ZeroShotAudioClassificationPipeline, __webpack_exports__ZeroShotClassificationPipeline as ZeroShotClassificationPipeline, __webpack_exports__ZeroShotImageClassificationPipeline as ZeroShotImageClassificationPipeline, __webpack_exports__ZeroShotObjectDetectionPipeline as ZeroShotObjectDetectionPipeline, __webpack_exports__bankers_round as bankers_round, __webpack_exports__cat as cat, __webpack_exports__cos_sim as cos_sim, __webpack_exports__dot as dot, __webpack_exports__dynamicTimeWarping as dynamicTimeWarping, __webpack_exports__env as env, __webpack_exports__getTopItems as getTopItems, __webpack_exports__hanning as hanning, __webpack_exports__interpolate as interpolate, __webpack_exports__interpolate_data as interpolate_data, __webpack_exports__layer_norm as layer_norm, __webpack_exports__log_softmax as log_softmax, __webpack_exports__magnitude as magnitude, __webpack_exports__max as max, __webpack_exports__mean as mean, __webpack_exports__mean_pooling as mean_pooling, __webpack_exports__medianFilter as medianFilter, __webpack_exports__mel_filter_bank as mel_filter_bank, __webpack_exports__min as min, __webpack_exports__ones as ones, __webpack_exports__ones_like as ones_like, __webpack_exports__permute as permute, __webpack_exports__permute_data as permute_data, __webpack_exports__pipeline as pipeline, __webpack_exports__quantize_embeddings as quantize_embeddings, __webpack_exports__read_audio as read_audio, __webpack_exports__round as round, __webpack_exports__softmax as softmax, __webpack_exports__spectrogram as spectrogram, __webpack_exports__stack as stack, __webpack_exports__std_mean as std_mean, __webpack_exports__window_function as window_function };
/******/ 

//# sourceMappingURL=transformers.js.map