Files
obsidian-memex-chat/main.js
svemagie a5b1ef8158 fresh
2026-03-31 14:20:47 +02:00

33666 lines
1.5 MiB

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod2) => function __require() {
return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
};
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
mod2
));
var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// node_modules/@xenova/transformers/src/utils/core.js
function dispatchCallback(progress_callback, data) {
if (progress_callback)
progress_callback(data);
}
function reverseDictionary(data) {
return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function isTypedArray(val) {
return val?.prototype?.__proto__?.constructor?.name === "TypedArray";
}
function isIntegralNumber(x) {
return Number.isInteger(x) || typeof x === "bigint";
}
function exists(x) {
return x !== void 0 && x !== null;
}
function calculateDimensions(arr) {
const dimensions = [];
let current = arr;
while (Array.isArray(current)) {
dimensions.push(current.length);
current = current[0];
}
return dimensions;
}
function pop(obj, key, defaultValue = void 0) {
const value = obj[key];
if (value !== void 0) {
delete obj[key];
return value;
}
if (defaultValue === void 0) {
throw Error(`Key ${key} does not exist in object.`);
}
return defaultValue;
}
function mergeArrays(...arrs) {
return Array.prototype.concat.apply([], arrs);
}
function product(...a) {
return a.reduce((a2, b) => a2.flatMap((d) => b.map((e) => [d, e])));
}
function calculateReflectOffset(i, w) {
return Math.abs((i + w) % (2 * w) - w);
}
var Callable;
var init_core = __esm({
"node_modules/@xenova/transformers/src/utils/core.js"() {
Callable = /** @type {any} */
class {
/**
* Creates a new instance of the Callable class.
*/
constructor() {
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");
}
};
}
});
// stub:onnxruntime-node
var require_onnxruntime_node = __commonJS({
"stub:onnxruntime-node"(exports2, module2) {
module2.exports = {};
}
});
// node_modules/onnxruntime-common/dist/ort-common.node.js
var require_ort_common_node = __commonJS({
"node_modules/onnxruntime-common/dist/ort-common.node.js"(exports2) {
(() => {
"use strict";
var e = { d: (t2, r2) => {
for (var n2 in r2)
e.o(r2, n2) && !e.o(t2, n2) && Object.defineProperty(t2, n2, { enumerable: true, get: r2[n2] });
}, o: (e2, t2) => Object.prototype.hasOwnProperty.call(e2, t2), r: (e2) => {
"undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e2, "__esModule", { value: true });
} }, t = {};
e.r(t), e.d(t, { InferenceSession: () => c, Tensor: () => g, env: () => i, registerBackend: () => o });
const r = {}, n = [], o = (e2, t2, o2) => {
if (!t2 || "function" != typeof t2.init || "function" != typeof t2.createSessionHandler)
throw new TypeError("not a valid backend");
{
const i2 = r[e2];
if (void 0 === i2)
r[e2] = { backend: t2, priority: o2 };
else {
if (i2.priority > o2)
return;
if (i2.priority === o2 && i2.backend !== t2)
throw new Error(`cannot register backend "${e2}" using priority ${o2}`);
}
if (o2 >= 0) {
const t3 = n.indexOf(e2);
-1 !== t3 && n.splice(t3, 1);
for (let t4 = 0; t4 < n.length; t4++)
if (r[n[t4]].priority <= o2)
return void n.splice(t4, 0, e2);
n.push(e2);
}
}
}, i = new class {
constructor() {
this.wasm = {}, this.webgl = {}, this.logLevelInternal = "warning";
}
set logLevel(e2) {
if (void 0 !== e2) {
if ("string" != typeof e2 || -1 === ["verbose", "info", "warning", "error", "fatal"].indexOf(e2))
throw new Error(`Unsupported logging level: ${e2}`);
this.logLevelInternal = e2;
}
}
get logLevel() {
return this.logLevelInternal;
}
}(), a = "undefined" != typeof BigInt64Array && "function" == typeof BigInt64Array.from, s = "undefined" != typeof BigUint64Array && "function" == typeof BigUint64Array.from, d = /* @__PURE__ */ new Map([["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array]]), f = /* @__PURE__ */ new Map([[Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"]]);
a && (d.set("int64", BigInt64Array), f.set(BigInt64Array, "int64")), s && (d.set("uint64", BigUint64Array), f.set(BigUint64Array, "uint64"));
class h {
constructor(e2, t2, r2) {
let n2, o2, i2;
if ("string" == typeof e2)
if (n2 = e2, i2 = r2, "string" === e2) {
if (!Array.isArray(t2))
throw new TypeError("A string tensor's data must be a string array.");
o2 = t2;
} else {
const r3 = d.get(e2);
if (void 0 === r3)
throw new TypeError(`Unsupported tensor type: ${e2}.`);
if (Array.isArray(t2))
o2 = r3.from(t2);
else {
if (!(t2 instanceof r3))
throw new TypeError(`A ${n2} tensor's data must be type of ${r3}`);
o2 = t2;
}
}
else if (i2 = t2, Array.isArray(e2)) {
if (0 === e2.length)
throw new TypeError("Tensor type cannot be inferred from an empty array.");
const t3 = typeof e2[0];
if ("string" === t3)
n2 = "string", o2 = e2;
else {
if ("boolean" !== t3)
throw new TypeError(`Invalid element type of data array: ${t3}.`);
n2 = "bool", o2 = Uint8Array.from(e2);
}
} else {
const t3 = f.get(e2.constructor);
if (void 0 === t3)
throw new TypeError(`Unsupported type for tensor data: ${e2.constructor}.`);
n2 = t3, o2 = e2;
}
if (void 0 === i2)
i2 = [o2.length];
else if (!Array.isArray(i2))
throw new TypeError("A tensor's dims must be a number array");
const a2 = ((e3) => {
let t3 = 1;
for (let r3 = 0; r3 < e3.length; r3++) {
const n3 = e3[r3];
if ("number" != typeof n3 || !Number.isSafeInteger(n3))
throw new TypeError(`dims[${r3}] must be an integer, got: ${n3}`);
if (n3 < 0)
throw new RangeError(`dims[${r3}] must be a non-negative integer, got: ${n3}`);
t3 *= n3;
}
return t3;
})(i2);
if (a2 !== o2.length)
throw new Error(`Tensor's size(${a2}) does not match data length(${o2.length}).`);
this.dims = i2, this.type = n2, this.data = o2, this.size = a2;
}
static bufferToTensor(e2, t2) {
if (void 0 === e2)
throw new Error("Image buffer must be defined");
if (void 0 === t2.height || void 0 === t2.width)
throw new Error("Image height and width must be defined");
const { height: r2, width: n2 } = t2, o2 = t2.norm;
let i2, a2;
i2 = void 0 === o2 || void 0 === o2.mean ? 255 : o2.mean, a2 = void 0 === o2 || void 0 === o2.bias ? 0 : o2.bias;
const s2 = void 0 !== t2.bitmapFormat ? t2.bitmapFormat : "RGBA", d2 = void 0 !== t2.tensorFormat && void 0 !== t2.tensorFormat ? t2.tensorFormat : "RGB", f2 = r2 * n2, g2 = "RGBA" === d2 ? new Float32Array(4 * f2) : new Float32Array(3 * f2);
let m2 = 4, c2 = 0, l2 = 1, w2 = 2, u = 3, p = 0, y = f2, b = 2 * f2, v = -1;
"RGB" === s2 && (m2 = 3, c2 = 0, l2 = 1, w2 = 2, u = -1), "RGBA" === d2 ? v = 3 * f2 : "RBG" === d2 ? (p = 0, b = f2, y = 2 * f2) : "BGR" === d2 && (b = 0, y = f2, p = 2 * f2);
for (let t3 = 0; t3 < f2; t3++, c2 += m2, w2 += m2, l2 += m2, u += m2)
g2[p++] = (e2[c2] + a2) / i2, g2[y++] = (e2[l2] + a2) / i2, g2[b++] = (e2[w2] + a2) / i2, -1 !== v && -1 !== u && (g2[v++] = (e2[u] + a2) / i2);
return new h("float32", g2, "RGBA" === d2 ? [1, 4, r2, n2] : [1, 3, r2, n2]);
}
static async fromImage(e2, t2) {
const r2 = "undefined" != typeof HTMLImageElement && e2 instanceof HTMLImageElement, n2 = "undefined" != typeof ImageData && e2 instanceof ImageData, o2 = "undefined" != typeof ImageBitmap && e2 instanceof ImageBitmap, i2 = "undefined" != typeof String && (e2 instanceof String || "string" == typeof e2);
let a2, s2 = {};
if (r2) {
const r3 = document.createElement("canvas"), n3 = r3.getContext("2d");
if (null == n3)
throw new Error("Can not access image data");
{
let o3 = e2.naturalHeight, i3 = e2.naturalWidth;
if (void 0 !== t2 && void 0 !== t2.resizedHeight && void 0 !== t2.resizedWidth && (o3 = t2.resizedHeight, i3 = t2.resizedWidth), void 0 !== t2) {
if (s2 = t2, void 0 !== t2.tensorFormat)
throw new Error("Image input config format must be RGBA for HTMLImageElement");
if (s2.tensorFormat = "RGBA", void 0 !== t2.height && t2.height !== o3)
throw new Error("Image input config height doesn't match HTMLImageElement height");
if (s2.height = o3, void 0 !== t2.width && t2.width !== i3)
throw new Error("Image input config width doesn't match HTMLImageElement width");
s2.width = i3;
} else
s2.tensorFormat = "RGBA", s2.height = o3, s2.width = i3;
r3.width = i3, r3.height = o3, n3.drawImage(e2, 0, 0, i3, o3), a2 = n3.getImageData(0, 0, i3, o3).data;
}
} else {
if (!n2) {
if (o2) {
if (void 0 === t2)
throw new Error("Please provide image config with format for Imagebitmap");
if (void 0 !== t2.bitmapFormat)
throw new Error("Image input config format must be defined for ImageBitmap");
const r3 = document.createElement("canvas").getContext("2d");
if (null != r3) {
const n3 = e2.height, o3 = e2.width;
if (r3.drawImage(e2, 0, 0, o3, n3), a2 = r3.getImageData(0, 0, o3, n3).data, void 0 !== t2) {
if (void 0 !== t2.height && t2.height !== n3)
throw new Error("Image input config height doesn't match ImageBitmap height");
if (s2.height = n3, void 0 !== t2.width && t2.width !== o3)
throw new Error("Image input config width doesn't match ImageBitmap width");
s2.width = o3;
} else
s2.height = n3, s2.width = o3;
return h.bufferToTensor(a2, s2);
}
throw new Error("Can not access image data");
}
if (i2)
return new Promise((r3, n3) => {
const o3 = document.createElement("canvas"), i3 = o3.getContext("2d");
if (!e2 || !i3)
return n3();
const a3 = new Image();
a3.crossOrigin = "Anonymous", a3.src = e2, a3.onload = () => {
o3.width = a3.width, o3.height = a3.height, i3.drawImage(a3, 0, 0, o3.width, o3.height);
const e3 = i3.getImageData(0, 0, o3.width, o3.height);
if (void 0 !== t2) {
if (void 0 !== t2.height && t2.height !== o3.height)
throw new Error("Image input config height doesn't match ImageBitmap height");
if (s2.height = o3.height, void 0 !== t2.width && t2.width !== o3.width)
throw new Error("Image input config width doesn't match ImageBitmap width");
s2.width = o3.width;
} else
s2.height = o3.height, s2.width = o3.width;
r3(h.bufferToTensor(e3.data, s2));
};
});
throw new Error("Input data provided is not supported - aborted tensor creation");
}
{
const r3 = "RGBA";
let n3, o3;
if (void 0 !== t2 && void 0 !== t2.resizedWidth && void 0 !== t2.resizedHeight ? (n3 = t2.resizedHeight, o3 = t2.resizedWidth) : (n3 = e2.height, o3 = e2.width), void 0 !== t2) {
if (s2 = t2, void 0 !== t2.bitmapFormat && t2.bitmapFormat !== r3)
throw new Error("Image input config format must be RGBA for ImageData");
s2.bitmapFormat = "RGBA";
} else
s2.bitmapFormat = "RGBA";
if (s2.height = n3, s2.width = o3, void 0 !== t2) {
const t3 = document.createElement("canvas");
t3.width = o3, t3.height = n3;
const r4 = t3.getContext("2d");
if (null == r4)
throw new Error("Can not access image data");
r4.putImageData(e2, 0, 0), a2 = r4.getImageData(0, 0, o3, n3).data;
} else
a2 = e2.data;
}
}
if (void 0 !== a2)
return h.bufferToTensor(a2, s2);
throw new Error("Input data provided is not supported - aborted tensor creation");
}
toImageData(e2) {
var t2, r2;
const n2 = document.createElement("canvas").getContext("2d");
let o2;
if (null == n2)
throw new Error("Can not access image data");
{
const i2 = this.dims[3], a2 = this.dims[2], s2 = this.dims[1], d2 = void 0 !== e2 && void 0 !== e2.format ? e2.format : "RGB", f2 = void 0 !== e2 && void 0 !== (null === (t2 = e2.norm) || void 0 === t2 ? void 0 : t2.mean) ? e2.norm.mean : 255, h2 = void 0 !== e2 && void 0 !== (null === (r2 = e2.norm) || void 0 === r2 ? void 0 : r2.bias) ? e2.norm.bias : 0, g2 = a2 * i2;
if (void 0 !== e2) {
if (void 0 !== e2.height && e2.height !== a2)
throw new Error("Image output config height doesn't match tensor height");
if (void 0 !== e2.width && e2.width !== i2)
throw new Error("Image output config width doesn't match tensor width");
if (void 0 !== e2.format && 4 === s2 && "RGBA" !== e2.format || 3 === s2 && "RGB" !== e2.format && "BGR" !== e2.format)
throw new Error("Tensor format doesn't match input tensor dims");
}
const m2 = 4;
let c2 = 0, l2 = 1, w2 = 2, u = 3, p = 0, y = g2, b = 2 * g2, v = -1;
"RGBA" === d2 ? (p = 0, y = g2, b = 2 * g2, v = 3 * g2) : "RGB" === d2 ? (p = 0, y = g2, b = 2 * g2) : "RBG" === d2 && (p = 0, b = g2, y = 2 * g2), o2 = n2.createImageData(i2, a2);
for (let e3 = 0; e3 < a2 * i2; c2 += m2, l2 += m2, w2 += m2, u += m2, e3++)
o2.data[c2] = (this.data[p++] - h2) * f2, o2.data[l2] = (this.data[y++] - h2) * f2, o2.data[w2] = (this.data[b++] - h2) * f2, o2.data[u] = -1 === v ? 255 : (this.data[v++] - h2) * f2;
}
return o2;
}
reshape(e2) {
return new h(this.type, this.data, e2);
}
}
const g = h;
class m {
constructor(e2) {
this.handler = e2;
}
async run(e2, t2, r2) {
const n2 = {};
let o2 = {};
if ("object" != typeof e2 || null === e2 || e2 instanceof g || Array.isArray(e2))
throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");
let i2 = true;
if ("object" == typeof t2) {
if (null === t2)
throw new TypeError("Unexpected argument[1]: cannot be null.");
if (t2 instanceof g)
throw new TypeError("'fetches' cannot be a Tensor");
if (Array.isArray(t2)) {
if (0 === t2.length)
throw new TypeError("'fetches' cannot be an empty array.");
i2 = false;
for (const e3 of t2) {
if ("string" != typeof e3)
throw new TypeError("'fetches' must be a string array or an object.");
if (-1 === this.outputNames.indexOf(e3))
throw new RangeError(`'fetches' contains invalid output name: ${e3}.`);
n2[e3] = null;
}
if ("object" == typeof r2 && null !== r2)
o2 = r2;
else if (void 0 !== r2)
throw new TypeError("'options' must be an object.");
} else {
let e3 = false;
const a3 = Object.getOwnPropertyNames(t2);
for (const r3 of this.outputNames)
if (-1 !== a3.indexOf(r3)) {
const o3 = t2[r3];
(null === o3 || o3 instanceof g) && (e3 = true, i2 = false, n2[r3] = o3);
}
if (e3) {
if ("object" == typeof r2 && null !== r2)
o2 = r2;
else if (void 0 !== r2)
throw new TypeError("'options' must be an object.");
} else
o2 = t2;
}
} else if (void 0 !== t2)
throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");
for (const t3 of this.inputNames)
if (void 0 === e2[t3])
throw new Error(`input '${t3}' is missing in 'feeds'.`);
if (i2)
for (const e3 of this.outputNames)
n2[e3] = null;
const a2 = await this.handler.run(e2, n2, o2), s2 = {};
for (const e3 in a2)
Object.hasOwnProperty.call(a2, e3) && (s2[e3] = new g(a2[e3].type, a2[e3].data, a2[e3].dims));
return s2;
}
static async create(e2, t2, o2, i2) {
let a2, s2 = {};
if ("string" == typeof e2) {
if (a2 = e2, "object" == typeof t2 && null !== t2)
s2 = t2;
else if (void 0 !== t2)
throw new TypeError("'options' must be an object.");
} else if (e2 instanceof Uint8Array) {
if (a2 = e2, "object" == typeof t2 && null !== t2)
s2 = t2;
else if (void 0 !== t2)
throw new TypeError("'options' must be an object.");
} else {
if (!(e2 instanceof ArrayBuffer || "undefined" != typeof SharedArrayBuffer && e2 instanceof SharedArrayBuffer))
throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");
{
const r2 = e2;
let n2 = 0, d3 = e2.byteLength;
if ("object" == typeof t2 && null !== t2)
s2 = t2;
else if ("number" == typeof t2) {
if (n2 = t2, !Number.isSafeInteger(n2))
throw new RangeError("'byteOffset' must be an integer.");
if (n2 < 0 || n2 >= r2.byteLength)
throw new RangeError(`'byteOffset' is out of range [0, ${r2.byteLength}).`);
if (d3 = e2.byteLength - n2, "number" == typeof o2) {
if (d3 = o2, !Number.isSafeInteger(d3))
throw new RangeError("'byteLength' must be an integer.");
if (d3 <= 0 || n2 + d3 > r2.byteLength)
throw new RangeError(`'byteLength' is out of range (0, ${r2.byteLength - n2}].`);
if ("object" == typeof i2 && null !== i2)
s2 = i2;
else if (void 0 !== i2)
throw new TypeError("'options' must be an object.");
} else if (void 0 !== o2)
throw new TypeError("'byteLength' must be a number.");
} else if (void 0 !== t2)
throw new TypeError("'options' must be an object.");
a2 = new Uint8Array(r2, n2, d3);
}
}
const d2 = (s2.executionProviders || []).map((e3) => "string" == typeof e3 ? e3 : e3.name), f2 = await (async (e3) => {
const t3 = 0 === e3.length ? n : e3, o3 = [];
for (const e4 of t3) {
const t4 = r[e4];
if (t4) {
if (t4.initialized)
return t4.backend;
if (t4.aborted)
continue;
const r2 = !!t4.initPromise;
try {
return r2 || (t4.initPromise = t4.backend.init()), await t4.initPromise, t4.initialized = true, t4.backend;
} catch (n2) {
r2 || o3.push({ name: e4, err: n2 }), t4.aborted = true;
} finally {
delete t4.initPromise;
}
}
}
throw new Error(`no available backend found. ERR: ${o3.map((e4) => `[${e4.name}] ${e4.err}`).join(", ")}`);
})(d2), h2 = await f2.createSessionHandler(a2, s2);
return new m(h2);
}
startProfiling() {
this.handler.startProfiling();
}
endProfiling() {
this.handler.endProfiling();
}
get inputNames() {
return this.handler.inputNames;
}
get outputNames() {
return this.handler.outputNames;
}
}
const c = m;
var l = exports2;
for (var w in t)
l[w] = t[w];
t.__esModule && Object.defineProperty(l, "__esModule", { value: true });
})();
}
});
// node_modules/onnxruntime-web/dist/ort-web.min.js
var require_ort_web_min = __commonJS({
"node_modules/onnxruntime-web/dist/ort-web.min.js"(exports, module) {
!function(t, e) {
if ("object" == typeof exports && "object" == typeof module)
module.exports = e(require_ort_common_node());
else if ("function" == typeof define && define.amd)
define([], e);
else {
var n = "object" == typeof exports ? e(require_ort_common_node()) : e(t.ort);
for (var r in n)
("object" == typeof exports ? exports : t)[r] = n[r];
}
}(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(t2) {
function e2() {
return $.buffer != C && H($.buffer), F;
}
function r2() {
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;
t2 = t2 || {}, s || (s = void 0 !== t2 ? t2 : {}), s.ready = new Promise(function(t3, e3) {
u = t3, c = e3;
});
var l, p, f, d, h, g, b = Object.assign({}, s), m = "./this.program", y = (t3, e3) => {
throw e3;
}, _ = "object" == typeof window, v = "function" == typeof importScripts, w = "object" == typeof process && "object" == typeof process.versions && false, x = s.ENVIRONMENT_IS_PTHREAD || false, T = "";
function S(t3) {
return s.locateFile ? s.locateFile(t3, T) : T + t3;
}
if (w) {
let e3;
T = v ? n(908).dirname(T) + "/" : "//", g = () => {
h || (d = n(1384), h = n(908));
}, l = function(t3, e4) {
return g(), t3 = h.normalize(t3), d.readFileSync(t3, e4 ? void 0 : "utf8");
}, f = (t3) => ((t3 = l(t3, true)).buffer || (t3 = new Uint8Array(t3)), t3), p = (t3, e4, n2) => {
g(), t3 = h.normalize(t3), d.readFile(t3, function(t4, r3) {
t4 ? n2(t4) : e4(r3.buffer);
});
}, 1 < process.argv.length && (m = process.argv[1].replace(/\\/g, "/")), process.argv.slice(2), process.on("uncaughtException", function(t3) {
if (!(t3 instanceof ut))
throw t3;
}), process.on("unhandledRejection", function(t3) {
throw t3;
}), y = (t3, e4) => {
if (J())
throw process.exitCode = t3, e4;
e4 instanceof ut || P("exiting due to exception: " + e4), process.exit(t3);
}, s.inspect = function() {
return "[Emscripten Module object]";
};
try {
e3 = n(9925);
} catch (t3) {
throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'), t3;
}
n.g.Worker = e3.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 = (t3) => {
var e3 = new XMLHttpRequest();
return e3.open("GET", t3, false), e3.send(null), e3.responseText;
}, v && (f = (t3) => {
var e3 = new XMLHttpRequest();
return e3.open("GET", t3, false), e3.responseType = "arraybuffer", e3.send(null), new Uint8Array(e3.response);
}), p = (t3, e3, n2) => {
var r3 = new XMLHttpRequest();
r3.open("GET", t3, true), r3.responseType = "arraybuffer", r3.onload = () => {
200 == r3.status || 0 == r3.status && r3.response ? e3(r3.response) : n2();
}, r3.onerror = n2, r3.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 = (t3) => d.writeSync(1, t3 + "\n"), A = (t3) => d.writeSync(2, t3 + "\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 || false;
"object" != typeof WebAssembly && it("no native wasm support detected");
var $, k, C, F, N, L, R, j, M = false, U = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0;
function V(t3, e3, n2) {
var r3 = (e3 >>>= 0) + n2;
for (n2 = e3; t3[n2] && !(n2 >= r3); )
++n2;
if (16 < n2 - e3 && t3.buffer && U)
return U.decode(t3.buffer instanceof SharedArrayBuffer ? t3.slice(e3, n2) : t3.subarray(e3, n2));
for (r3 = ""; e3 < n2; ) {
var i2 = t3[e3++];
if (128 & i2) {
var o2 = 63 & t3[e3++];
if (192 == (224 & i2))
r3 += String.fromCharCode((31 & i2) << 6 | o2);
else {
var a2 = 63 & t3[e3++];
65536 > (i2 = 224 == (240 & i2) ? (15 & i2) << 12 | o2 << 6 | a2 : (7 & i2) << 18 | o2 << 12 | a2 << 6 | 63 & t3[e3++]) ? r3 += String.fromCharCode(i2) : (i2 -= 65536, r3 += String.fromCharCode(55296 | i2 >> 10, 56320 | 1023 & i2));
}
} else
r3 += String.fromCharCode(i2);
}
return r3;
}
function B(t3, e3) {
return (t3 >>>= 0) ? V(r2(), t3, e3) : "";
}
function z(t3, e3, n2, r3) {
if (!(0 < r3))
return 0;
var i2 = n2 >>>= 0;
r3 = n2 + r3 - 1;
for (var o2 = 0; o2 < t3.length; ++o2) {
var a2 = t3.charCodeAt(o2);
if (55296 <= a2 && 57343 >= a2 && (a2 = 65536 + ((1023 & a2) << 10) | 1023 & t3.charCodeAt(++o2)), 127 >= a2) {
if (n2 >= r3)
break;
e3[n2++ >>> 0] = a2;
} else {
if (2047 >= a2) {
if (n2 + 1 >= r3)
break;
e3[n2++ >>> 0] = 192 | a2 >> 6;
} else {
if (65535 >= a2) {
if (n2 + 2 >= r3)
break;
e3[n2++ >>> 0] = 224 | a2 >> 12;
} else {
if (n2 + 3 >= r3)
break;
e3[n2++ >>> 0] = 240 | a2 >> 18, e3[n2++ >>> 0] = 128 | a2 >> 12 & 63;
}
e3[n2++ >>> 0] = 128 | a2 >> 6 & 63;
}
e3[n2++ >>> 0] = 128 | 63 & a2;
}
}
return e3[n2 >>> 0] = 0, n2 - i2;
}
function G(t3) {
for (var e3 = 0, n2 = 0; n2 < t3.length; ++n2) {
var r3 = t3.charCodeAt(n2);
127 >= r3 ? e3++ : 2047 >= r3 ? e3 += 2 : 55296 <= r3 && 57343 >= r3 ? (e3 += 4, ++n2) : e3 += 3;
}
return e3;
}
function H(t3) {
C = t3, s.HEAP8 = F = new Int8Array(t3), s.HEAP16 = new Int16Array(t3), s.HEAP32 = L = new Int32Array(t3), s.HEAPU8 = N = new Uint8Array(t3), s.HEAPU16 = new Uint16Array(t3), s.HEAPU32 = R = new Uint32Array(t3), s.HEAPF32 = new Float32Array(t3), s.HEAPF64 = j = new Float64Array(t3);
}
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: true })).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 || false;
}
function Q() {
var t3 = s.preRun.shift();
X.unshift(t3);
}
var tt, et = 0, nt = null, rt = null;
function it(t3) {
throw x ? postMessage({ cmd: "onAbort", arg: t3 }) : s.onAbort && s.onAbort(t3), P(t3 = "Aborted(" + t3 + ")"), M = true, t3 = new WebAssembly.RuntimeError(t3 + ". Build with -sASSERTIONS for more info."), c(t3), t3;
}
function ot() {
return tt.startsWith("data:application/octet-stream;base64,");
}
function at() {
var t3 = tt;
try {
if (t3 == tt && E)
return new Uint8Array(E);
if (f)
return f(t3);
throw "both async and sync fetching of the wasm failed";
} catch (t4) {
it(t4);
}
}
tt = "ort-wasm-threaded.wasm", ot() || (tt = S(tt));
var st = {};
function ut(t3) {
this.name = "ExitStatus", this.message = "Program terminated with exit(" + t3 + ")", this.status = t3;
}
function ct(t3) {
(t3 = dt.Vb[t3]) || it(), dt.mc(t3);
}
function lt(t3) {
var e3 = dt.Cc();
if (!e3)
return 6;
dt.ac.push(e3), dt.Vb[t3.Ub] = e3, e3.Ub = t3.Ub;
var n2 = { cmd: "run", start_routine: t3.Ic, arg: t3.zc, pthread_ptr: t3.Ub };
return e3.$b = () => {
n2.time = performance.now(), e3.postMessage(n2, t3.Nc);
}, e3.loaded && (e3.$b(), delete e3.$b), 0;
}
function pt(t3) {
if (x)
return qt(1, 1, t3);
J() || (dt.oc(), s.onExit && s.onExit(t3), M = true), y(t3, new ut(t3));
}
function ft(t3, e3) {
if (!e3 && x)
throw bt(t3), "unwind";
J() || x || (me(), ht(K), be(0), re[1].length && ie(1, 10), re[2].length && ie(2, 10), dt.oc()), pt(t3);
}
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 = false;
}, nc: function() {
}, oc: function() {
for (var t3 of Object.values(dt.Vb))
dt.mc(t3);
for (t3 of dt.Yb)
t3.terminate();
dt.Yb = [];
}, mc: function(t3) {
var e3 = t3.Ub;
delete dt.Vb[e3], dt.Yb.push(t3), dt.ac.splice(dt.ac.indexOf(t3), 1), t3.Ub = 0, xe(e3);
}, Gc: function() {
}, pc: function() {
dt.qc.forEach((t3) => t3());
}, Fc: function(t3, e3) {
t3.onmessage = (n2) => {
var r3 = (n2 = n2.data).cmd;
if (t3.Ub && (dt.Bc = t3.Ub), n2.targetThread && n2.targetThread != de()) {
var i2 = dt.Vb[n2.Qc];
i2 ? i2.postMessage(n2, n2.transferList) : P('Internal error! Worker sent a message "' + r3 + '" to target pthread ' + n2.targetThread + ", but that thread no longer exists!");
} else
"processProxyingQueue" === r3 ? Vt(n2.queue) : "spawnThread" === r3 ? lt(n2) : "cleanupThread" === r3 ? ct(n2.thread) : "killThread" === r3 ? (n2 = n2.thread, r3 = dt.Vb[n2], delete dt.Vb[n2], r3.terminate(), xe(n2), dt.ac.splice(dt.ac.indexOf(r3), 1), r3.Ub = 0) : "cancelThread" === r3 ? dt.Vb[n2.thread].postMessage({ cmd: "cancel" }) : "loaded" === r3 ? (t3.loaded = true, e3 && e3(t3), t3.$b && (t3.$b(), delete t3.$b)) : "print" === r3 ? I("Thread " + n2.threadId + ": " + n2.text) : "printErr" === r3 ? P("Thread " + n2.threadId + ": " + n2.text) : "alert" === r3 ? alert("Thread " + n2.threadId + ": " + n2.text) : "setimmediate" === n2.target ? t3.postMessage(n2) : "onAbort" === r3 ? s.onAbort && s.onAbort(n2.arg) : r3 && P("worker sent an unknown command " + r3);
dt.Bc = void 0;
}, t3.onerror = (t4) => {
throw P("worker sent an error! " + t4.filename + ":" + t4.lineno + ": " + t4.message), t4;
}, w && (t3.on("message", function(e4) {
t3.onmessage({ data: e4 });
}), t3.on("error", function(e4) {
t3.onerror(e4);
}), t3.on("detachedExit", function() {
})), t3.postMessage({ cmd: "load", urlOrBlob: s.mainScriptUrlOrBlob || _scriptDir, wasmMemory: $, wasmModule: k });
}, yc: function() {
var t3 = S("ort-wasm-threaded.worker.js");
dt.Yb.push(new Worker(t3));
}, Cc: function() {
return 0 == dt.Yb.length && (dt.yc(), dt.Fc(dt.Yb[0])), dt.Yb.pop();
} };
function ht(t3) {
for (; 0 < t3.length; )
t3.shift()(s);
}
function gt(t3) {
var e3 = Ae();
return t3 = t3(), Ee(e3), t3;
}
function bt(t3) {
if (x)
return qt(2, 0, t3);
try {
ft(t3);
} catch (t4) {
t4 instanceof ut || "unwind" == t4 || y(1, t4);
}
}
s.PThread = dt, s.establishStackSpace = function() {
var t3 = de(), e3 = i()[t3 + 44 >> 2 >>> 0];
t3 = i()[t3 + 48 >> 2 >>> 0], Oe(e3, e3 - t3), Ee(e3);
};
var mt = [];
function yt(t3) {
var e3 = mt[t3];
return e3 || (t3 >= mt.length && (mt.length = t3 + 1), mt[t3] = e3 = q.get(t3)), e3;
}
s.invokeEntryPoint = function(t3, e3) {
t3 = yt(t3)(e3), J() ? dt.nc(t3) : Te(t3);
};
var _t, vt, wt = [], xt = 0, Tt = 0;
function St(t3) {
this.Zb = t3, this.Sb = t3 - 24, this.xc = function(t4) {
o()[this.Sb + 4 >> 2 >>> 0] = t4;
}, this.bc = function() {
return o()[this.Sb + 4 >> 2 >>> 0];
}, this.wc = function(t4) {
o()[this.Sb + 8 >> 2 >>> 0] = t4;
}, this.Dc = function() {
return o()[this.Sb + 8 >> 2 >>> 0];
}, this.rc = function() {
i()[this.Sb >> 2 >>> 0] = 0;
}, this.hc = function(t4) {
t4 = t4 ? 1 : 0, e2()[this.Sb + 12 >> 0 >>> 0] = t4;
}, this.uc = function() {
return 0 != e2()[this.Sb + 12 >> 0 >>> 0];
}, this.ic = function(t4) {
t4 = t4 ? 1 : 0, e2()[this.Sb + 13 >> 0 >>> 0] = t4;
}, this.kc = function() {
return 0 != e2()[this.Sb + 13 >> 0 >>> 0];
}, this.fc = function(t4, e3) {
this.cc(0), this.xc(t4), this.wc(e3), this.rc(), this.hc(false), this.ic(false);
}, 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(t4) {
o()[this.Sb + 16 >> 2 >>> 0] = t4;
}, this.tc = function() {
return o()[this.Sb + 16 >> 2 >>> 0];
}, this.vc = function() {
if (De(this.bc()))
return o()[this.Zb >> 2 >>> 0];
var t4 = this.tc();
return 0 !== t4 ? t4 : this.Zb;
};
}
function Ot(t3) {
return ge(new St(t3).Sb);
}
function At(t3, e3, n2, r3) {
return x ? qt(3, 1, t3, e3, n2, r3) : Et(t3, e3, n2, r3);
}
function Et(t3, e3, n2, r3) {
if ("undefined" == typeof SharedArrayBuffer)
return P("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6;
var i2 = [];
return x && 0 === i2.length ? At(t3, e3, n2, r3) : (t3 = { Ic: n2, Ub: t3, zc: r3, Nc: i2 }, x ? (t3.Oc = "spawnThread", postMessage(t3, i2), 0) : lt(t3));
}
function It(t3, e3, n2) {
return x ? qt(4, 1, t3, e3, n2) : 0;
}
function Pt(t3, e3) {
if (x)
return qt(5, 1, t3, e3);
}
function Dt(t3, e3) {
if (x)
return qt(6, 1, t3, e3);
}
function $t(t3, e3, n2) {
if (x)
return qt(7, 1, t3, e3, n2);
}
function kt(t3, e3, n2) {
return x ? qt(8, 1, t3, e3, n2) : 0;
}
function Ct(t3, e3) {
if (x)
return qt(9, 1, t3, e3);
}
function Ft(t3, e3, n2) {
if (x)
return qt(10, 1, t3, e3, n2);
}
function Nt(t3, e3, n2, r3) {
if (x)
return qt(11, 1, t3, e3, n2, r3);
}
function Lt(t3, e3, n2, r3) {
if (x)
return qt(12, 1, t3, e3, n2, r3);
}
function Rt(t3, e3, n2, r3) {
if (x)
return qt(13, 1, t3, e3, n2, r3);
}
function jt(t3) {
if (x)
return qt(14, 1, t3);
}
function Mt(t3, e3) {
if (x)
return qt(15, 1, t3, e3);
}
function Ut(t3, e3, n2) {
if (x)
return qt(16, 1, t3, e3, n2);
}
function Vt(t3) {
Atomics.store(i(), t3 >> 2, 1), de() && we(t3), Atomics.compareExchange(i(), t3 >> 2, 1, 0);
}
function Bt(t3) {
return o()[t3 >>> 2] + 4294967296 * i()[t3 + 4 >>> 2];
}
function zt(t3, e3, n2, r3, i2, o2) {
return x ? qt(17, 1, t3, e3, n2, r3, i2, o2) : -52;
}
function Gt(t3, e3, n2, r3, i2, o2) {
if (x)
return qt(18, 1, t3, e3, n2, r3, i2, o2);
}
function Ht(t3) {
var n2 = G(t3) + 1, r3 = he(n2);
return r3 && z(t3, e2(), r3, n2), r3;
}
function Wt(t3, e3, n2) {
function r3(t4) {
return (t4 = t4.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? t4[1] : "GMT";
}
if (x)
return qt(19, 1, t3, e3, n2);
var a2 = (/* @__PURE__ */ new Date()).getFullYear(), s2 = new Date(a2, 0, 1), u2 = new Date(a2, 6, 1);
a2 = s2.getTimezoneOffset();
var c2 = u2.getTimezoneOffset(), l2 = Math.max(a2, c2);
i()[t3 >> 2 >>> 0] = 60 * l2, i()[e3 >> 2 >>> 0] = Number(a2 != c2), t3 = r3(s2), e3 = r3(u2), t3 = Ht(t3), e3 = Ht(e3), c2 < a2 ? (o()[n2 >> 2 >>> 0] = t3, o()[n2 + 4 >> 2 >>> 0] = e3) : (o()[n2 >> 2 >>> 0] = e3, o()[n2 + 4 >> 2 >>> 0] = t3);
}
function qt(t3, e3) {
var n2 = arguments.length - 2, r3 = arguments;
return gt(() => {
for (var i2 = Ie(8 * n2), o2 = i2 >> 3, s2 = 0; s2 < n2; s2++) {
var u2 = r3[2 + s2];
a()[o2 + s2 >>> 0] = u2;
}
return ve(t3, n2, i2, e3);
});
}
s.executeNotifiedProxyingQueue = Vt, vt = w ? () => {
var t3 = process.hrtime();
return 1e3 * t3[0] + t3[1] / 1e6;
} : x ? () => performance.now() - s.__performance_now_clock_drift : () => performance.now();
var Xt, Yt = [], Kt = {};
function Zt() {
if (!Xt) {
var t3, e3 = { 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 (t3 in Kt)
void 0 === Kt[t3] ? delete e3[t3] : e3[t3] = Kt[t3];
var n2 = [];
for (t3 in e3)
n2.push(t3 + "=" + e3[t3]);
Xt = n2;
}
return Xt;
}
function Jt(t3, n2) {
if (x)
return qt(20, 1, t3, n2);
var r3 = 0;
return Zt().forEach(function(i2, a2) {
var s2 = n2 + r3;
for (a2 = o()[t3 + 4 * a2 >> 2 >>> 0] = s2, s2 = 0; s2 < i2.length; ++s2)
e2()[a2++ >> 0 >>> 0] = i2.charCodeAt(s2);
e2()[a2 >> 0 >>> 0] = 0, r3 += i2.length + 1;
}), 0;
}
function Qt(t3, e3) {
if (x)
return qt(21, 1, t3, e3);
var n2 = Zt();
o()[t3 >> 2 >>> 0] = n2.length;
var r3 = 0;
return n2.forEach(function(t4) {
r3 += t4.length + 1;
}), o()[e3 >> 2 >>> 0] = r3, 0;
}
function te(t3) {
return x ? qt(22, 1, t3) : 52;
}
function ee(t3, e3, n2, r3) {
return x ? qt(23, 1, t3, e3, n2, r3) : 52;
}
function ne(t3, e3, n2, r3, i2) {
return x ? qt(24, 1, t3, e3, n2, r3, i2) : 70;
}
var re = [null, [], []];
function ie(t3, e3) {
var n2 = re[t3];
0 === e3 || 10 === e3 ? ((1 === t3 ? I : P)(V(n2, 0)), n2.length = 0) : n2.push(e3);
}
function oe(t3, e3, n2, i2) {
if (x)
return qt(25, 1, t3, e3, n2, i2);
for (var a2 = 0, s2 = 0; s2 < n2; s2++) {
var u2 = o()[e3 >> 2 >>> 0], c2 = o()[e3 + 4 >> 2 >>> 0];
e3 += 8;
for (var l2 = 0; l2 < c2; l2++)
ie(t3, r2()[u2 + l2 >>> 0]);
a2 += c2;
}
return o()[i2 >> 2 >>> 0] = a2, 0;
}
var ae = 0;
function se(t3) {
return 0 == t3 % 4 && (0 != t3 % 100 || 0 == t3 % 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(t3, n2, r3, o2) {
function a2(t4, e3, n3) {
for (t4 = "number" == typeof t4 ? t4.toString() : t4 || ""; t4.length < e3; )
t4 = n3[0] + t4;
return t4;
}
function s2(t4, e3) {
return a2(t4, e3, "0");
}
function u2(t4, e3) {
function n3(t5) {
return 0 > t5 ? -1 : 0 < t5 ? 1 : 0;
}
var r4;
return 0 === (r4 = n3(t4.getFullYear() - e3.getFullYear())) && 0 === (r4 = n3(t4.getMonth() - e3.getMonth())) && (r4 = n3(t4.getDate() - e3.getDate())), r4;
}
function c2(t4) {
switch (t4.getDay()) {
case 0:
return new Date(t4.getFullYear() - 1, 11, 29);
case 1:
return t4;
case 2:
return new Date(t4.getFullYear(), 0, 3);
case 3:
return new Date(t4.getFullYear(), 0, 2);
case 4:
return new Date(t4.getFullYear(), 0, 1);
case 5:
return new Date(t4.getFullYear() - 1, 11, 31);
case 6:
return new Date(t4.getFullYear() - 1, 11, 30);
}
}
function l2(t4) {
var e3 = t4.Wb;
for (t4 = new Date(new Date(t4.Xb + 1900, 0, 1).getTime()); 0 < e3; ) {
var n3 = t4.getMonth(), r4 = (se(t4.getFullYear()) ? ue : ce)[n3];
if (!(e3 > r4 - t4.getDate())) {
t4.setDate(t4.getDate() + e3);
break;
}
e3 -= r4 - t4.getDate() + 1, t4.setDate(1), 11 > n3 ? t4.setMonth(n3 + 1) : (t4.setMonth(0), t4.setFullYear(t4.getFullYear() + 1));
}
return n3 = new Date(t4.getFullYear() + 1, 0, 4), e3 = c2(new Date(t4.getFullYear(), 0, 4)), n3 = c2(n3), 0 >= u2(e3, t4) ? 0 >= u2(n3, t4) ? t4.getFullYear() + 1 : t4.getFullYear() : t4.getFullYear() - 1;
}
var p2 = i()[o2 + 40 >> 2 >>> 0];
for (var f2 in o2 = { Lc: i()[o2 >> 2 >>> 0], Kc: i()[o2 + 4 >> 2 >>> 0], dc: i()[o2 + 8 >> 2 >>> 0], jc: i()[o2 + 12 >> 2 >>> 0], ec: i()[o2 + 16 >> 2 >>> 0], Xb: i()[o2 + 20 >> 2 >>> 0], Tb: i()[o2 + 24 >> 2 >>> 0], Wb: i()[o2 + 28 >> 2 >>> 0], Rc: i()[o2 + 32 >> 2 >>> 0], Jc: i()[o2 + 36 >> 2 >>> 0], Mc: p2 ? B(p2) : "" }, r3 = B(r3), p2 = { "%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" })
r3 = r3.replace(new RegExp(f2, "g"), p2[f2]);
var d2 = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), h2 = "January February March April May June July August September October November December".split(" ");
for (f2 in p2 = { "%a": function(t4) {
return d2[t4.Tb].substring(0, 3);
}, "%A": function(t4) {
return d2[t4.Tb];
}, "%b": function(t4) {
return h2[t4.ec].substring(0, 3);
}, "%B": function(t4) {
return h2[t4.ec];
}, "%C": function(t4) {
return s2((t4.Xb + 1900) / 100 | 0, 2);
}, "%d": function(t4) {
return s2(t4.jc, 2);
}, "%e": function(t4) {
return a2(t4.jc, 2, " ");
}, "%g": function(t4) {
return l2(t4).toString().substring(2);
}, "%G": function(t4) {
return l2(t4);
}, "%H": function(t4) {
return s2(t4.dc, 2);
}, "%I": function(t4) {
return 0 == (t4 = t4.dc) ? t4 = 12 : 12 < t4 && (t4 -= 12), s2(t4, 2);
}, "%j": function(t4) {
for (var e3 = 0, n3 = 0; n3 <= t4.ec - 1; e3 += (se(t4.Xb + 1900) ? ue : ce)[n3++])
;
return s2(t4.jc + e3, 3);
}, "%m": function(t4) {
return s2(t4.ec + 1, 2);
}, "%M": function(t4) {
return s2(t4.Kc, 2);
}, "%n": function() {
return "\n";
}, "%p": function(t4) {
return 0 <= t4.dc && 12 > t4.dc ? "AM" : "PM";
}, "%S": function(t4) {
return s2(t4.Lc, 2);
}, "%t": function() {
return " ";
}, "%u": function(t4) {
return t4.Tb || 7;
}, "%U": function(t4) {
return s2(Math.floor((t4.Wb + 7 - t4.Tb) / 7), 2);
}, "%V": function(t4) {
var e3 = Math.floor((t4.Wb + 7 - (t4.Tb + 6) % 7) / 7);
if (2 >= (t4.Tb + 371 - t4.Wb - 2) % 7 && e3++, e3)
53 == e3 && (4 == (n3 = (t4.Tb + 371 - t4.Wb) % 7) || 3 == n3 && se(t4.Xb) || (e3 = 1));
else {
e3 = 52;
var n3 = (t4.Tb + 7 - t4.Wb - 1) % 7;
(4 == n3 || 5 == n3 && se(t4.Xb % 400 - 1)) && e3++;
}
return s2(e3, 2);
}, "%w": function(t4) {
return t4.Tb;
}, "%W": function(t4) {
return s2(Math.floor((t4.Wb + 7 - (t4.Tb + 6) % 7) / 7), 2);
}, "%y": function(t4) {
return (t4.Xb + 1900).toString().substring(2);
}, "%Y": function(t4) {
return t4.Xb + 1900;
}, "%z": function(t4) {
var e3 = 0 <= (t4 = t4.Jc);
return t4 = Math.abs(t4) / 60, (e3 ? "+" : "-") + String("0000" + (t4 / 60 * 100 + t4 % 60)).slice(-4);
}, "%Z": function(t4) {
return t4.Mc;
}, "%%": function() {
return "%";
} }, r3 = r3.replace(/%%/g, "\0\0"), p2)
r3.includes(f2) && (r3 = r3.replace(new RegExp(f2, "g"), p2[f2](o2)));
return f2 = function(t4) {
var e3 = Array(G(t4) + 1);
return z(t4, e3, 0, e3.length), e3;
}(r3 = r3.replace(/\0\0/g, "%")), f2.length > n2 ? 0 : (function(t4, n3) {
e2().set(t4, n3 >>> 0);
}(f2, t3), f2.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(t3) {
return he(t3 + 24) + 24;
}, n: function(t3) {
return (t3 = new St(t3)).uc() || (t3.hc(true), xt--), t3.ic(false), wt.push(t3), t3.sc(), t3.vc();
}, ma: function(t3) {
throw P("Unexpected exception thrown, this is not properly supported - aborting"), M = true, t3;
}, x: function() {
Se(0);
var t3 = wt.pop();
if (t3.Hc() && !t3.kc()) {
var e3 = t3.Dc();
e3 && yt(e3)(t3.Zb), Ot(t3.Zb);
}
Tt = 0;
}, e: function() {
var t3 = Tt;
if (!t3)
return ae = 0;
var e3 = new St(t3);
e3.cc(t3);
var n2 = e3.bc();
if (!n2)
return ae = 0, t3;
for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) {
var o2 = r3[i2];
if (0 === o2 || o2 === n2)
break;
if (Pe(o2, n2, e3.Sb + 16))
return ae = o2, t3;
}
return ae = n2, t3;
}, l: function() {
var t3 = Tt;
if (!t3)
return ae = 0;
var e3 = new St(t3);
e3.cc(t3);
var n2 = e3.bc();
if (!n2)
return ae = 0, t3;
for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) {
var o2 = r3[i2];
if (0 === o2 || o2 === n2)
break;
if (Pe(o2, n2, e3.Sb + 16))
return ae = o2, t3;
}
return ae = n2, t3;
}, h: function() {
var t3 = Tt;
if (!t3)
return ae = 0;
var e3 = new St(t3);
e3.cc(t3);
var n2 = e3.bc();
if (!n2)
return ae = 0, t3;
for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) {
var o2 = r3[i2];
if (0 === o2 || o2 === n2)
break;
if (Pe(o2, n2, e3.Sb + 16))
return ae = o2, t3;
}
return ae = n2, t3;
}, t: Ot, M: function() {
var t3 = wt.pop();
t3 || it("no exception to throw");
var e3 = t3.Zb;
throw t3.kc() || (wt.push(t3), t3.ic(true), t3.hc(false), xt++), Tt = e3, e3;
}, c: function(t3, e3, n2) {
throw new St(t3).fc(e3, n2), Tt = t3, xt++, t3;
}, pa: function() {
return xt;
}, Fa: function(t3) {
ye(t3, !v, 1, !_), dt.pc();
}, T: function(t3) {
x ? postMessage({ cmd: "cleanupThread", thread: t3 }) : ct(t3);
}, xa: Et, j: function(t3) {
throw Tt || (Tt = t3), t3;
}, 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 true;
}, za: function(t3, e3, n2, r3) {
if (t3 == e3)
setTimeout(() => Vt(r3));
else if (x)
postMessage({ targetThread: t3, cmd: "processProxyingQueue", queue: r3 });
else {
if (!(t3 = dt.Vb[t3]))
return;
t3.postMessage({ cmd: "processProxyingQueue", queue: r3 });
}
return 1;
}, Ea: function() {
return -1;
}, Pa: function(t3, e3) {
t3 = new Date(1e3 * Bt(t3)), i()[e3 >> 2 >>> 0] = t3.getUTCSeconds(), i()[e3 + 4 >> 2 >>> 0] = t3.getUTCMinutes(), i()[e3 + 8 >> 2 >>> 0] = t3.getUTCHours(), i()[e3 + 12 >> 2 >>> 0] = t3.getUTCDate(), i()[e3 + 16 >> 2 >>> 0] = t3.getUTCMonth(), i()[e3 + 20 >> 2 >>> 0] = t3.getUTCFullYear() - 1900, i()[e3 + 24 >> 2 >>> 0] = t3.getUTCDay(), t3 = (t3.getTime() - Date.UTC(t3.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, i()[e3 + 28 >> 2 >>> 0] = t3;
}, Qa: function(t3, e3) {
t3 = new Date(1e3 * Bt(t3)), i()[e3 >> 2 >>> 0] = t3.getSeconds(), i()[e3 + 4 >> 2 >>> 0] = t3.getMinutes(), i()[e3 + 8 >> 2 >>> 0] = t3.getHours(), i()[e3 + 12 >> 2 >>> 0] = t3.getDate(), i()[e3 + 16 >> 2 >>> 0] = t3.getMonth(), i()[e3 + 20 >> 2 >>> 0] = t3.getFullYear() - 1900, i()[e3 + 24 >> 2 >>> 0] = t3.getDay();
var n2 = new Date(t3.getFullYear(), 0, 1), r3 = (t3.getTime() - n2.getTime()) / 864e5 | 0;
i()[e3 + 28 >> 2 >>> 0] = r3, i()[e3 + 36 >> 2 >>> 0] = -60 * t3.getTimezoneOffset(), r3 = new Date(t3.getFullYear(), 6, 1).getTimezoneOffset(), t3 = 0 | (r3 != (n2 = n2.getTimezoneOffset()) && t3.getTimezoneOffset() == Math.min(n2, r3)), i()[e3 + 32 >> 2 >>> 0] = t3;
}, Ra: function(t3) {
var e3 = new Date(i()[t3 + 20 >> 2 >>> 0] + 1900, i()[t3 + 16 >> 2 >>> 0], i()[t3 + 12 >> 2 >>> 0], i()[t3 + 8 >> 2 >>> 0], i()[t3 + 4 >> 2 >>> 0], i()[t3 >> 2 >>> 0], 0), n2 = i()[t3 + 32 >> 2 >>> 0], r3 = e3.getTimezoneOffset(), o2 = new Date(e3.getFullYear(), 0, 1), a2 = new Date(e3.getFullYear(), 6, 1).getTimezoneOffset(), s2 = o2.getTimezoneOffset(), u2 = Math.min(s2, a2);
return 0 > n2 ? i()[t3 + 32 >> 2 >>> 0] = Number(a2 != s2 && u2 == r3) : 0 < n2 != (u2 == r3) && (a2 = Math.max(s2, a2), e3.setTime(e3.getTime() + 6e4 * ((0 < n2 ? u2 : a2) - r3))), i()[t3 + 24 >> 2 >>> 0] = e3.getDay(), n2 = (e3.getTime() - o2.getTime()) / 864e5 | 0, i()[t3 + 28 >> 2 >>> 0] = n2, i()[t3 >> 2 >>> 0] = e3.getSeconds(), i()[t3 + 4 >> 2 >>> 0] = e3.getMinutes(), i()[t3 + 8 >> 2 >>> 0] = e3.getHours(), i()[t3 + 12 >> 2 >>> 0] = e3.getDate(), i()[t3 + 16 >> 2 >>> 0] = e3.getMonth(), e3.getTime() / 1e3 | 0;
}, Aa: zt, Ba: Gt, Sa: function t3(e3, n2, r3) {
t3.Ac || (t3.Ac = true, Wt(e3, n2, r3));
}, y: function() {
it("");
}, U: function() {
if (!w && !v) {
var t3 = "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[t3] || (_t[t3] = 1, w && (t3 = "warning: " + t3), P(t3));
}
}, ra: function() {
return 4294901760;
}, B: vt, Ia: function(t3, e3, n2) {
r2().copyWithin(t3 >>> 0, e3 >>> 0, e3 + n2 >>> 0);
}, F: function() {
return w ? n(3993).cpus().length : navigator.hardwareConcurrency;
}, Da: function(t3, e3, n2) {
Yt.length = e3, n2 >>= 3;
for (var r3 = 0; r3 < e3; r3++)
Yt[r3] = a()[n2 + r3 >>> 0];
return (0 > t3 ? st[-t3 - 1] : pe[t3]).apply(null, Yt);
}, qa: function(t3) {
var e3 = r2().length;
if ((t3 >>>= 0) <= e3 || 4294901760 < t3)
return false;
for (var n2 = 1; 4 >= n2; n2 *= 2) {
var i2 = e3 * (1 + 0.2 / n2);
i2 = Math.min(i2, t3 + 100663296);
var o2 = Math;
i2 = Math.max(t3, i2), o2 = o2.min.call(o2, 4294901760, i2 + (65536 - i2 % 65536) % 65536);
t: {
try {
$.grow(o2 - C.byteLength + 65535 >>> 16), H($.buffer);
var a2 = 1;
break t;
} catch (t4) {
}
a2 = void 0;
}
if (a2)
return true;
}
return false;
}, Na: function() {
throw "unwind";
}, Ga: Jt, Ha: Qt, J: ft, I: te, S: ee, ga: ne, R: oe, d: function() {
return ae;
}, na: function t3(r3, i2) {
t3.lc || (t3.lc = function() {
if ("object" == typeof crypto && "function" == typeof crypto.getRandomValues) {
var t4 = new Uint8Array(1);
return () => (crypto.getRandomValues(t4), t4[0]);
}
if (w)
try {
var e3 = n(Object(function() {
var t5 = new Error("Cannot find module 'crypto'");
throw t5.code = "MODULE_NOT_FOUND", t5;
}()));
return () => e3.randomBytes(1)[0];
} catch (t5) {
}
return () => it("randomDevice");
}());
for (var o2 = 0; o2 < i2; o2++)
e2()[r3 + o2 >> 0 >>> 0] = t3.lc();
return 0;
}, ia: function(t3, e3, n2) {
var r3 = Ae();
try {
return yt(t3)(e3, n2);
} catch (t4) {
if (Ee(r3), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, ja: function(t3, e3, n2) {
var r3 = Ae();
try {
return yt(t3)(e3, n2);
} catch (t4) {
if (Ee(r3), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, K: function(t3) {
var e3 = Ae();
try {
return yt(t3)();
} catch (t4) {
if (Ee(e3), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, f: function(t3, e3) {
var n2 = Ae();
try {
return yt(t3)(e3);
} catch (t4) {
if (Ee(n2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, P: function(t3, e3, n2) {
var r3 = Ae();
try {
return yt(t3)(e3, n2);
} catch (t4) {
if (Ee(r3), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, Q: function(t3, e3, n2) {
var r3 = Ae();
try {
return yt(t3)(e3, n2);
} catch (t4) {
if (Ee(r3), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, k: function(t3, e3, n2) {
var r3 = Ae();
try {
return yt(t3)(e3, n2);
} catch (t4) {
if (Ee(r3), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, p: function(t3, e3, n2, r3) {
var i2 = Ae();
try {
return yt(t3)(e3, n2, r3);
} catch (t4) {
if (Ee(i2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, q: function(t3, e3, n2, r3, i2) {
var o2 = Ae();
try {
return yt(t3)(e3, n2, r3, i2);
} catch (t4) {
if (Ee(o2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, N: function(t3, e3, n2, r3, i2, o2) {
var a2 = Ae();
try {
return yt(t3)(e3, n2, r3, i2, o2);
} catch (t4) {
if (Ee(a2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, s: function(t3, e3, n2, r3, i2, o2) {
var a2 = Ae();
try {
return yt(t3)(e3, n2, r3, i2, o2);
} catch (t4) {
if (Ee(a2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, w: function(t3, e3, n2, r3, i2, o2, a2) {
var s2 = Ae();
try {
return yt(t3)(e3, n2, r3, i2, o2, a2);
} catch (t4) {
if (Ee(s2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, L: function(t3, e3, n2, r3, i2, o2, a2, s2) {
var u2 = Ae();
try {
return yt(t3)(e3, n2, r3, i2, o2, a2, s2);
} catch (t4) {
if (Ee(u2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, E: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) {
var f2 = Ae();
try {
return yt(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2);
} catch (t4) {
if (Ee(f2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, aa: function(t3, e3, n2, r3, i2, o2, a2, s2) {
var u2 = Ae();
try {
return Me(t3, e3, n2, r3, i2, o2, a2, s2);
} catch (t4) {
if (Ee(u2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, _: function(t3, e3, n2, r3, i2, o2, a2) {
var s2 = Ae();
try {
return ke(t3, e3, n2, r3, i2, o2, a2);
} catch (t4) {
if (Ee(s2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, Z: function(t3, e3, n2, r3, i2) {
var o2 = Ae();
try {
return Ue(t3, e3, n2, r3, i2);
} catch (t4) {
if (Ee(o2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, ca: function(t3, e3, n2, r3) {
var i2 = Ae();
try {
return Re(t3, e3, n2, r3);
} catch (t4) {
if (Ee(i2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, $: function(t3) {
var e3 = Ae();
try {
return $e(t3);
} catch (t4) {
if (Ee(e3), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, ba: function(t3, e3) {
var n2 = Ae();
try {
return je(t3, e3);
} catch (t4) {
if (Ee(n2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, Y: function(t3, e3, n2) {
var r3 = Ae();
try {
return Ce(t3, e3, n2);
} catch (t4) {
if (Ee(r3), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, g: function(t3) {
var e3 = Ae();
try {
yt(t3)();
} catch (t4) {
if (Ee(e3), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, r: function(t3, e3) {
var n2 = Ae();
try {
yt(t3)(e3);
} catch (t4) {
if (Ee(n2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, i: function(t3, e3, n2) {
var r3 = Ae();
try {
yt(t3)(e3, n2);
} catch (t4) {
if (Ee(r3), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, ha: function(t3, e3, n2, r3) {
var i2 = Ae();
try {
yt(t3)(e3, n2, r3);
} catch (t4) {
if (Ee(i2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, m: function(t3, e3, n2, r3) {
var i2 = Ae();
try {
yt(t3)(e3, n2, r3);
} catch (t4) {
if (Ee(i2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, v: function(t3, e3, n2, r3, i2) {
var o2 = Ae();
try {
yt(t3)(e3, n2, r3, i2);
} catch (t4) {
if (Ee(o2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, u: function(t3, e3, n2, r3, i2, o2) {
var a2 = Ae();
try {
yt(t3)(e3, n2, r3, i2, o2);
} catch (t4) {
if (Ee(a2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, O: function(t3, e3, n2, r3, i2, o2, a2) {
var s2 = Ae();
try {
yt(t3)(e3, n2, r3, i2, o2, a2);
} catch (t4) {
if (Ee(s2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, A: function(t3, e3, n2, r3, i2, o2, a2, s2) {
var u2 = Ae();
try {
yt(t3)(e3, n2, r3, i2, o2, a2, s2);
} catch (t4) {
if (Ee(u2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, ka: function(t3, e3, n2, r3, i2, o2, a2, s2, u2) {
var c2 = Ae();
try {
yt(t3)(e3, n2, r3, i2, o2, a2, s2, u2);
} catch (t4) {
if (Ee(c2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, C: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2) {
var p2 = Ae();
try {
yt(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2);
} catch (t4) {
if (Ee(p2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, D: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2) {
var b2 = Ae();
try {
yt(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2);
} catch (t4) {
if (Ee(b2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, fa: function(t3, e3, n2, r3, i2, o2, a2, s2) {
var u2 = Ae();
try {
Fe(t3, e3, n2, r3, i2, o2, a2, s2);
} catch (t4) {
if (Ee(u2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, da: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) {
var f2 = Ae();
try {
Le(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2);
} catch (t4) {
if (Ee(f2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, ea: function(t3, e3, n2, r3, i2, o2) {
var a2 = Ae();
try {
Ne(t3, e3, n2, r3, i2, o2);
} catch (t4) {
if (Ee(a2), t4 !== t4 + 0)
throw t4;
Se(1, 0);
}
}, o: function(t3) {
return t3;
}, a: $ || s.wasmMemory, G: function(t3) {
ae = t3;
}, la: le, z: function(t3, e3, n2, r3) {
return le(t3, e3, n2, r3);
} };
!function() {
function t3(t4, e4) {
s.asm = t4.exports, dt.qc.push(s.asm.sb), q = s.asm.ub, Y.unshift(s.asm.Va), k = e4, x || (et--, s.monitorRunDependencies && s.monitorRunDependencies(et), 0 == et && (null !== nt && (clearInterval(nt), nt = null), rt && (t4 = rt, rt = null, t4())));
}
function e3(e4) {
t3(e4.instance, e4.module);
}
function n2(t4) {
return function() {
if (!E && (_ || v)) {
if ("function" == typeof fetch && !tt.startsWith("file://"))
return fetch(tt, { credentials: "same-origin" }).then(function(t5) {
if (!t5.ok)
throw "failed to load wasm binary file at '" + tt + "'";
return t5.arrayBuffer();
}).catch(function() {
return at();
});
if (p)
return new Promise(function(t5, e4) {
p(tt, function(e5) {
t5(new Uint8Array(e5));
}, e4);
});
}
return Promise.resolve().then(function() {
return at();
});
}().then(function(t5) {
return WebAssembly.instantiate(t5, r3);
}).then(function(t5) {
return t5;
}).then(t4, function(t5) {
P("failed to asynchronously prepare wasm: " + t5), it(t5);
});
}
var r3 = { a: fe };
if (x || (et++, s.monitorRunDependencies && s.monitorRunDependencies(et)), s.instantiateWasm)
try {
return s.instantiateWasm(r3, t3);
} catch (t4) {
return P("Module.instantiateWasm callback failed with error: " + t4), false;
}
(E || "function" != typeof WebAssembly.instantiateStreaming || ot() || tt.startsWith("file://") || w || "function" != typeof fetch ? n2(e3) : fetch(tt, { credentials: "same-origin" }).then(function(t4) {
return WebAssembly.instantiateStreaming(t4, r3).then(e3, function(t5) {
return P("wasm streaming compile failed: " + t5), P("falling back to ArrayBuffer instantiation"), n2(e3);
});
})).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 t3() {
if (!_e && (_e = true, s.calledRun = true, !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 t4 = s.postRun.shift();
Z.unshift(t4);
}
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), t3();
}, 1)) : t3());
}
}
if (s.UTF8ToString = B, s.stringToUTF8 = function(t3, e3, n2) {
return z(t3, r2(), e3, n2);
}, 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 t3() {
_e || Ve(), _e || (rt = t3);
}, s.preInit)
for ("function" == typeof s.preInit && (s.preInit = [s.preInit]); 0 < s.preInit.length; )
s.preInit.pop()();
return Ve(), t2.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(t2) {
var e2, r2, i;
t2 = t2 || {}, e2 || (e2 = void 0 !== t2 ? t2 : {}), e2.ready = new Promise(function(t3, e3) {
r2 = t3, i = e3;
});
var o, a, s, u, c, l, p = Object.assign({}, e2), f = "./this.program", d = (t3, e3) => {
throw e3;
}, h = "object" == typeof window, g = "function" == typeof importScripts, b = "object" == typeof process && "object" == typeof process.versions && false, m = "";
b ? (m = g ? n(908).dirname(m) + "/" : "//", l = () => {
c || (u = n(1384), c = n(908));
}, o = function(t3, e3) {
return l(), t3 = c.normalize(t3), u.readFileSync(t3, e3 ? void 0 : "utf8");
}, s = (t3) => ((t3 = o(t3, true)).buffer || (t3 = new Uint8Array(t3)), t3), a = (t3, e3, n2) => {
l(), t3 = c.normalize(t3), u.readFile(t3, function(t4, r3) {
t4 ? n2(t4) : e3(r3.buffer);
});
}, 1 < process.argv.length && (f = process.argv[1].replace(/\\/g, "/")), process.argv.slice(2), process.on("uncaughtException", function(t3) {
if (!(t3 instanceof K))
throw t3;
}), process.on("unhandledRejection", function(t3) {
throw t3;
}), d = (t3, e3) => {
if (w || 0 < U)
throw process.exitCode = t3, e3;
e3 instanceof K || v("exiting due to exception: " + e3), process.exit(t3);
}, e2.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 = (t3) => {
var e3 = new XMLHttpRequest();
return e3.open("GET", t3, false), e3.send(null), e3.responseText;
}, g && (s = (t3) => {
var e3 = new XMLHttpRequest();
return e3.open("GET", t3, false), e3.responseType = "arraybuffer", e3.send(null), new Uint8Array(e3.response);
}), a = (t3, e3, n2) => {
var r3 = new XMLHttpRequest();
r3.open("GET", t3, true), r3.responseType = "arraybuffer", r3.onload = () => {
200 == r3.status || 0 == r3.status && r3.response ? e3(r3.response) : n2();
}, r3.onerror = n2, r3.send(null);
});
var y, _ = e2.print || console.log.bind(console), v = e2.printErr || console.warn.bind(console);
Object.assign(e2, p), p = null, e2.thisProgram && (f = e2.thisProgram), e2.quit && (d = e2.quit), e2.wasmBinary && (y = e2.wasmBinary);
var w = e2.noExitRuntime || false;
"object" != typeof WebAssembly && W("no native wasm support detected");
var x, T, S, O, A, E, I = false, P = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0;
function D(t3, e3, n2) {
var r3 = (e3 >>>= 0) + n2;
for (n2 = e3; t3[n2] && !(n2 >= r3); )
++n2;
if (16 < n2 - e3 && t3.buffer && P)
return P.decode(t3.subarray(e3, n2));
for (r3 = ""; e3 < n2; ) {
var i2 = t3[e3++];
if (128 & i2) {
var o2 = 63 & t3[e3++];
if (192 == (224 & i2))
r3 += String.fromCharCode((31 & i2) << 6 | o2);
else {
var a2 = 63 & t3[e3++];
65536 > (i2 = 224 == (240 & i2) ? (15 & i2) << 12 | o2 << 6 | a2 : (7 & i2) << 18 | o2 << 12 | a2 << 6 | 63 & t3[e3++]) ? r3 += String.fromCharCode(i2) : (i2 -= 65536, r3 += String.fromCharCode(55296 | i2 >> 10, 56320 | 1023 & i2));
}
} else
r3 += String.fromCharCode(i2);
}
return r3;
}
function $(t3, e3) {
return (t3 >>>= 0) ? D(O, t3, e3) : "";
}
function k(t3, e3, n2, r3) {
if (!(0 < r3))
return 0;
var i2 = n2 >>>= 0;
r3 = n2 + r3 - 1;
for (var o2 = 0; o2 < t3.length; ++o2) {
var a2 = t3.charCodeAt(o2);
if (55296 <= a2 && 57343 >= a2 && (a2 = 65536 + ((1023 & a2) << 10) | 1023 & t3.charCodeAt(++o2)), 127 >= a2) {
if (n2 >= r3)
break;
e3[n2++ >>> 0] = a2;
} else {
if (2047 >= a2) {
if (n2 + 1 >= r3)
break;
e3[n2++ >>> 0] = 192 | a2 >> 6;
} else {
if (65535 >= a2) {
if (n2 + 2 >= r3)
break;
e3[n2++ >>> 0] = 224 | a2 >> 12;
} else {
if (n2 + 3 >= r3)
break;
e3[n2++ >>> 0] = 240 | a2 >> 18, e3[n2++ >>> 0] = 128 | a2 >> 12 & 63;
}
e3[n2++ >>> 0] = 128 | a2 >> 6 & 63;
}
e3[n2++ >>> 0] = 128 | 63 & a2;
}
}
return e3[n2 >>> 0] = 0, n2 - i2;
}
function C(t3) {
for (var e3 = 0, n2 = 0; n2 < t3.length; ++n2) {
var r3 = t3.charCodeAt(n2);
127 >= r3 ? e3++ : 2047 >= r3 ? e3 += 2 : 55296 <= r3 && 57343 >= r3 ? (e3 += 4, ++n2) : e3 += 3;
}
return e3;
}
function F() {
var t3 = x.buffer;
T = t3, e2.HEAP8 = S = new Int8Array(t3), e2.HEAP16 = new Int16Array(t3), e2.HEAP32 = A = new Int32Array(t3), e2.HEAPU8 = O = new Uint8Array(t3), e2.HEAPU16 = new Uint16Array(t3), e2.HEAPU32 = E = new Uint32Array(t3), e2.HEAPF32 = new Float32Array(t3), e2.HEAPF64 = new Float64Array(t3);
}
var N, L = [], R = [], j = [], M = [], U = 0;
function V() {
var t3 = e2.preRun.shift();
L.unshift(t3);
}
var B, z = 0, G = null, H = null;
function W(t3) {
throw e2.onAbort && e2.onAbort(t3), v(t3 = "Aborted(" + t3 + ")"), I = true, t3 = new WebAssembly.RuntimeError(t3 + ". Build with -sASSERTIONS for more info."), i(t3), t3;
}
function q() {
return B.startsWith("data:application/octet-stream;base64,");
}
if (B = "ort-wasm.wasm", !q()) {
var X = B;
B = e2.locateFile ? e2.locateFile(X, m) : m + X;
}
function Y() {
var t3 = B;
try {
if (t3 == B && y)
return new Uint8Array(y);
if (s)
return s(t3);
throw "both async and sync fetching of the wasm failed";
} catch (t4) {
W(t4);
}
}
function K(t3) {
this.name = "ExitStatus", this.message = "Program terminated with exit(" + t3 + ")", this.status = t3;
}
function Z(t3) {
for (; 0 < t3.length; )
t3.shift()(e2);
}
var J = [], Q = 0, tt = 0;
function et(t3) {
this.Db = t3, this.zb = t3 - 24, this.Ub = function(t4) {
E[this.zb + 4 >> 2 >>> 0] = t4;
}, this.Eb = function() {
return E[this.zb + 4 >> 2 >>> 0];
}, this.Sb = function(t4) {
E[this.zb + 8 >> 2 >>> 0] = t4;
}, this.Wb = function() {
return E[this.zb + 8 >> 2 >>> 0];
}, this.Tb = function() {
A[this.zb >> 2 >>> 0] = 0;
}, this.Ib = function(t4) {
S[this.zb + 12 >> 0 >>> 0] = t4 ? 1 : 0;
}, this.Pb = function() {
return 0 != S[this.zb + 12 >> 0 >>> 0];
}, this.Jb = function(t4) {
S[this.zb + 13 >> 0 >>> 0] = t4 ? 1 : 0;
}, this.Lb = function() {
return 0 != S[this.zb + 13 >> 0 >>> 0];
}, this.Rb = function(t4, e3) {
this.Fb(0), this.Ub(t4), this.Sb(e3), this.Tb(), this.Ib(false), this.Jb(false);
}, this.Nb = function() {
A[this.zb >> 2 >>> 0] += 1;
}, this.Xb = function() {
var t4 = A[this.zb >> 2 >>> 0];
return A[this.zb >> 2 >>> 0] = t4 - 1, 1 === t4;
}, this.Fb = function(t4) {
E[this.zb + 16 >> 2 >>> 0] = t4;
}, this.Ob = function() {
return E[this.zb + 16 >> 2 >>> 0];
}, this.Qb = function() {
if (Et(this.Eb()))
return E[this.Db >> 2 >>> 0];
var t4 = this.Ob();
return 0 !== t4 ? t4 : this.Db;
};
}
function nt(t3) {
return _t(new et(t3).zb);
}
var rt = [];
function it(t3) {
var e3 = rt[t3];
return e3 || (t3 >= rt.length && (rt.length = t3 + 1), rt[t3] = e3 = N.get(t3)), e3;
}
function ot(t3) {
var e3 = C(t3) + 1, n2 = yt(e3);
return n2 && k(t3, S, n2, e3), n2;
}
var at = {};
function st() {
if (!ut) {
var t3, e3 = { 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 (t3 in at)
void 0 === at[t3] ? delete e3[t3] : e3[t3] = at[t3];
var n2 = [];
for (t3 in e3)
n2.push(t3 + "=" + e3[t3]);
ut = n2;
}
return ut;
}
var ut, ct = [null, [], []];
function lt(t3, e3) {
var n2 = ct[t3];
0 === e3 || 10 === e3 ? ((1 === t3 ? _ : v)(D(n2, 0)), n2.length = 0) : n2.push(e3);
}
var pt = 0;
function ft(t3) {
return 0 == t3 % 4 && (0 != t3 % 100 || 0 == t3 % 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(t3, e3, n2, r3) {
function i2(t4, e4, n3) {
for (t4 = "number" == typeof t4 ? t4.toString() : t4 || ""; t4.length < e4; )
t4 = n3[0] + t4;
return t4;
}
function o2(t4, e4) {
return i2(t4, e4, "0");
}
function a2(t4, e4) {
function n3(t5) {
return 0 > t5 ? -1 : 0 < t5 ? 1 : 0;
}
var r4;
return 0 === (r4 = n3(t4.getFullYear() - e4.getFullYear())) && 0 === (r4 = n3(t4.getMonth() - e4.getMonth())) && (r4 = n3(t4.getDate() - e4.getDate())), r4;
}
function s2(t4) {
switch (t4.getDay()) {
case 0:
return new Date(t4.getFullYear() - 1, 11, 29);
case 1:
return t4;
case 2:
return new Date(t4.getFullYear(), 0, 3);
case 3:
return new Date(t4.getFullYear(), 0, 2);
case 4:
return new Date(t4.getFullYear(), 0, 1);
case 5:
return new Date(t4.getFullYear() - 1, 11, 31);
case 6:
return new Date(t4.getFullYear() - 1, 11, 30);
}
}
function u2(t4) {
var e4 = t4.Bb;
for (t4 = new Date(new Date(t4.Cb + 1900, 0, 1).getTime()); 0 < e4; ) {
var n3 = t4.getMonth(), r4 = (ft(t4.getFullYear()) ? dt : ht)[n3];
if (!(e4 > r4 - t4.getDate())) {
t4.setDate(t4.getDate() + e4);
break;
}
e4 -= r4 - t4.getDate() + 1, t4.setDate(1), 11 > n3 ? t4.setMonth(n3 + 1) : (t4.setMonth(0), t4.setFullYear(t4.getFullYear() + 1));
}
return n3 = new Date(t4.getFullYear() + 1, 0, 4), e4 = s2(new Date(t4.getFullYear(), 0, 4)), n3 = s2(n3), 0 >= a2(e4, t4) ? 0 >= a2(n3, t4) ? t4.getFullYear() + 1 : t4.getFullYear() : t4.getFullYear() - 1;
}
var c2 = A[r3 + 40 >> 2 >>> 0];
for (var l2 in r3 = { $b: A[r3 >> 2 >>> 0], Zb: A[r3 + 4 >> 2 >>> 0], Gb: A[r3 + 8 >> 2 >>> 0], Kb: A[r3 + 12 >> 2 >>> 0], Hb: A[r3 + 16 >> 2 >>> 0], Cb: A[r3 + 20 >> 2 >>> 0], Ab: A[r3 + 24 >> 2 >>> 0], Bb: A[r3 + 28 >> 2 >>> 0], bc: A[r3 + 32 >> 2 >>> 0], Yb: A[r3 + 36 >> 2 >>> 0], ac: c2 ? $(c2) : "" }, n2 = $(n2), c2 = { "%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" })
n2 = n2.replace(new RegExp(l2, "g"), c2[l2]);
var p2 = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), f2 = "January February March April May June July August September October November December".split(" ");
for (l2 in c2 = { "%a": function(t4) {
return p2[t4.Ab].substring(0, 3);
}, "%A": function(t4) {
return p2[t4.Ab];
}, "%b": function(t4) {
return f2[t4.Hb].substring(0, 3);
}, "%B": function(t4) {
return f2[t4.Hb];
}, "%C": function(t4) {
return o2((t4.Cb + 1900) / 100 | 0, 2);
}, "%d": function(t4) {
return o2(t4.Kb, 2);
}, "%e": function(t4) {
return i2(t4.Kb, 2, " ");
}, "%g": function(t4) {
return u2(t4).toString().substring(2);
}, "%G": function(t4) {
return u2(t4);
}, "%H": function(t4) {
return o2(t4.Gb, 2);
}, "%I": function(t4) {
return 0 == (t4 = t4.Gb) ? t4 = 12 : 12 < t4 && (t4 -= 12), o2(t4, 2);
}, "%j": function(t4) {
for (var e4 = 0, n3 = 0; n3 <= t4.Hb - 1; e4 += (ft(t4.Cb + 1900) ? dt : ht)[n3++])
;
return o2(t4.Kb + e4, 3);
}, "%m": function(t4) {
return o2(t4.Hb + 1, 2);
}, "%M": function(t4) {
return o2(t4.Zb, 2);
}, "%n": function() {
return "\n";
}, "%p": function(t4) {
return 0 <= t4.Gb && 12 > t4.Gb ? "AM" : "PM";
}, "%S": function(t4) {
return o2(t4.$b, 2);
}, "%t": function() {
return " ";
}, "%u": function(t4) {
return t4.Ab || 7;
}, "%U": function(t4) {
return o2(Math.floor((t4.Bb + 7 - t4.Ab) / 7), 2);
}, "%V": function(t4) {
var e4 = Math.floor((t4.Bb + 7 - (t4.Ab + 6) % 7) / 7);
if (2 >= (t4.Ab + 371 - t4.Bb - 2) % 7 && e4++, e4)
53 == e4 && (4 == (n3 = (t4.Ab + 371 - t4.Bb) % 7) || 3 == n3 && ft(t4.Cb) || (e4 = 1));
else {
e4 = 52;
var n3 = (t4.Ab + 7 - t4.Bb - 1) % 7;
(4 == n3 || 5 == n3 && ft(t4.Cb % 400 - 1)) && e4++;
}
return o2(e4, 2);
}, "%w": function(t4) {
return t4.Ab;
}, "%W": function(t4) {
return o2(Math.floor((t4.Bb + 7 - (t4.Ab + 6) % 7) / 7), 2);
}, "%y": function(t4) {
return (t4.Cb + 1900).toString().substring(2);
}, "%Y": function(t4) {
return t4.Cb + 1900;
}, "%z": function(t4) {
var e4 = 0 <= (t4 = t4.Yb);
return t4 = Math.abs(t4) / 60, (e4 ? "+" : "-") + String("0000" + (t4 / 60 * 100 + t4 % 60)).slice(-4);
}, "%Z": function(t4) {
return t4.ac;
}, "%%": function() {
return "%";
} }, n2 = n2.replace(/%%/g, "\0\0"), c2)
n2.includes(l2) && (n2 = n2.replace(new RegExp(l2, "g"), c2[l2](r3)));
return l2 = function(t4) {
var e4 = Array(C(t4) + 1);
return k(t4, e4, 0, e4.length), e4;
}(n2 = n2.replace(/\0\0/g, "%")), l2.length > e3 ? 0 : (S.set(l2, t3 >>> 0), l2.length - 1);
}
var bt = { a: function(t3) {
return yt(t3 + 24) + 24;
}, m: function(t3) {
return (t3 = new et(t3)).Pb() || (t3.Ib(true), Q--), t3.Jb(false), J.push(t3), t3.Nb(), t3.Qb();
}, ia: function(t3) {
throw v("Unexpected exception thrown, this is not properly supported - aborting"), I = true, t3;
}, w: function() {
xt(0);
var t3 = J.pop();
if (t3.Xb() && !t3.Lb()) {
var e3 = t3.Wb();
e3 && it(e3)(t3.Db), nt(t3.Db);
}
tt = 0;
}, d: function() {
var t3 = tt;
if (!t3)
return pt = 0;
var e3 = new et(t3);
e3.Fb(t3);
var n2 = e3.Eb();
if (!n2)
return pt = 0, t3;
for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) {
var o2 = r3[i2];
if (0 === o2 || o2 === n2)
break;
if (At(o2, n2, e3.zb + 16))
return pt = o2, t3;
}
return pt = n2, t3;
}, k: function() {
var t3 = tt;
if (!t3)
return pt = 0;
var e3 = new et(t3);
e3.Fb(t3);
var n2 = e3.Eb();
if (!n2)
return pt = 0, t3;
for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) {
var o2 = r3[i2];
if (0 === o2 || o2 === n2)
break;
if (At(o2, n2, e3.zb + 16))
return pt = o2, t3;
}
return pt = n2, t3;
}, g: function() {
var t3 = tt;
if (!t3)
return pt = 0;
var e3 = new et(t3);
e3.Fb(t3);
var n2 = e3.Eb();
if (!n2)
return pt = 0, t3;
for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) {
var o2 = r3[i2];
if (0 === o2 || o2 === n2)
break;
if (At(o2, n2, e3.zb + 16))
return pt = o2, t3;
}
return pt = n2, t3;
}, s: nt, L: function() {
var t3 = J.pop();
t3 || W("no exception to throw");
var e3 = t3.Db;
throw t3.Lb() || (J.push(t3), t3.Jb(true), t3.Ib(false), Q++), tt = e3, e3;
}, b: function(t3, e3, n2) {
throw new et(t3).Rb(e3, n2), tt = t3, Q++, t3;
}, la: function() {
return Q;
}, i: function(t3) {
throw tt || (tt = t3), t3;
}, 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 true;
}, Da: function(t3, e3) {
t3 = new Date(1e3 * (E[t3 >>> 2] + 4294967296 * A[t3 + 4 >>> 2])), A[e3 >> 2 >>> 0] = t3.getUTCSeconds(), A[e3 + 4 >> 2 >>> 0] = t3.getUTCMinutes(), A[e3 + 8 >> 2 >>> 0] = t3.getUTCHours(), A[e3 + 12 >> 2 >>> 0] = t3.getUTCDate(), A[e3 + 16 >> 2 >>> 0] = t3.getUTCMonth(), A[e3 + 20 >> 2 >>> 0] = t3.getUTCFullYear() - 1900, A[e3 + 24 >> 2 >>> 0] = t3.getUTCDay(), A[e3 + 28 >> 2 >>> 0] = (t3.getTime() - Date.UTC(t3.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0;
}, Ea: function(t3, e3) {
t3 = new Date(1e3 * (E[t3 >>> 2] + 4294967296 * A[t3 + 4 >>> 2])), A[e3 >> 2 >>> 0] = t3.getSeconds(), A[e3 + 4 >> 2 >>> 0] = t3.getMinutes(), A[e3 + 8 >> 2 >>> 0] = t3.getHours(), A[e3 + 12 >> 2 >>> 0] = t3.getDate(), A[e3 + 16 >> 2 >>> 0] = t3.getMonth(), A[e3 + 20 >> 2 >>> 0] = t3.getFullYear() - 1900, A[e3 + 24 >> 2 >>> 0] = t3.getDay();
var n2 = new Date(t3.getFullYear(), 0, 1);
A[e3 + 28 >> 2 >>> 0] = (t3.getTime() - n2.getTime()) / 864e5 | 0, A[e3 + 36 >> 2 >>> 0] = -60 * t3.getTimezoneOffset();
var r3 = new Date(t3.getFullYear(), 6, 1).getTimezoneOffset();
n2 = n2.getTimezoneOffset(), A[e3 + 32 >> 2 >>> 0] = 0 | (r3 != n2 && t3.getTimezoneOffset() == Math.min(n2, r3));
}, Fa: function(t3) {
var e3 = new Date(A[t3 + 20 >> 2 >>> 0] + 1900, A[t3 + 16 >> 2 >>> 0], A[t3 + 12 >> 2 >>> 0], A[t3 + 8 >> 2 >>> 0], A[t3 + 4 >> 2 >>> 0], A[t3 >> 2 >>> 0], 0), n2 = A[t3 + 32 >> 2 >>> 0], r3 = e3.getTimezoneOffset(), i2 = new Date(e3.getFullYear(), 0, 1), o2 = new Date(e3.getFullYear(), 6, 1).getTimezoneOffset(), a2 = i2.getTimezoneOffset(), s2 = Math.min(a2, o2);
return 0 > n2 ? A[t3 + 32 >> 2 >>> 0] = Number(o2 != a2 && s2 == r3) : 0 < n2 != (s2 == r3) && (o2 = Math.max(a2, o2), e3.setTime(e3.getTime() + 6e4 * ((0 < n2 ? s2 : o2) - r3))), A[t3 + 24 >> 2 >>> 0] = e3.getDay(), A[t3 + 28 >> 2 >>> 0] = (e3.getTime() - i2.getTime()) / 864e5 | 0, A[t3 >> 2 >>> 0] = e3.getSeconds(), A[t3 + 4 >> 2 >>> 0] = e3.getMinutes(), A[t3 + 8 >> 2 >>> 0] = e3.getHours(), A[t3 + 12 >> 2 >>> 0] = e3.getDate(), A[t3 + 16 >> 2 >>> 0] = e3.getMonth(), e3.getTime() / 1e3 | 0;
}, sa: function() {
return -52;
}, ta: function() {
}, Ga: function t3(e3, n2, r3) {
t3.Vb || (t3.Vb = true, function(t4, e4, n3) {
function r4(t5) {
return (t5 = t5.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? t5[1] : "GMT";
}
var i2 = (/* @__PURE__ */ new Date()).getFullYear(), o2 = new Date(i2, 0, 1), a2 = new Date(i2, 6, 1);
i2 = o2.getTimezoneOffset();
var s2 = a2.getTimezoneOffset();
A[t4 >> 2 >>> 0] = 60 * Math.max(i2, s2), A[e4 >> 2 >>> 0] = Number(i2 != s2), t4 = r4(o2), e4 = r4(a2), t4 = ot(t4), e4 = ot(e4), s2 < i2 ? (E[n3 >> 2 >>> 0] = t4, E[n3 + 4 >> 2 >>> 0] = e4) : (E[n3 >> 2 >>> 0] = e4, E[n3 + 4 >> 2 >>> 0] = t4);
}(e3, n2, r3));
}, B: function() {
W("");
}, ma: function() {
return 4294901760;
}, I: b ? () => {
var t3 = process.hrtime();
return 1e3 * t3[0] + t3[1] / 1e6;
} : () => performance.now(), xa: function(t3, e3, n2) {
O.copyWithin(t3 >>> 0, e3 >>> 0, e3 + n2 >>> 0);
}, G: function(t3) {
var e3 = O.length;
if (4294901760 < (t3 >>>= 0))
return false;
for (var n2 = 1; 4 >= n2; n2 *= 2) {
var r3 = e3 * (1 + 0.2 / n2);
r3 = Math.min(r3, t3 + 100663296);
var i2 = Math;
r3 = Math.max(t3, r3), i2 = i2.min.call(i2, 4294901760, r3 + (65536 - r3 % 65536) % 65536);
t: {
try {
x.grow(i2 - T.byteLength + 65535 >>> 16), F();
var o2 = 1;
break t;
} catch (t4) {
}
o2 = void 0;
}
if (o2)
return true;
}
return false;
}, va: function(t3, e3) {
var n2 = 0;
return st().forEach(function(r3, i2) {
var o2 = e3 + n2;
for (i2 = E[t3 + 4 * i2 >> 2 >>> 0] = o2, o2 = 0; o2 < r3.length; ++o2)
S[i2++ >> 0 >>> 0] = r3.charCodeAt(o2);
S[i2 >> 0 >>> 0] = 0, n2 += r3.length + 1;
}), 0;
}, wa: function(t3, e3) {
var n2 = st();
E[t3 >> 2 >>> 0] = n2.length;
var r3 = 0;
return n2.forEach(function(t4) {
r3 += t4.length + 1;
}), E[e3 >> 2 >>> 0] = r3, 0;
}, ba: function(t3) {
w || 0 < U || (wt(), Z(j), vt(0), ct[1].length && lt(1, 10), ct[2].length && lt(2, 10)), w || 0 < U || (e2.onExit && e2.onExit(t3), I = true), d(t3, new K(t3));
}, E: function() {
return 52;
}, Q: function() {
return 52;
}, ca: function() {
return 70;
}, P: function(t3, e3, n2, r3) {
for (var i2 = 0, o2 = 0; o2 < n2; o2++) {
var a2 = E[e3 >> 2 >>> 0], s2 = E[e3 + 4 >> 2 >>> 0];
e3 += 8;
for (var u2 = 0; u2 < s2; u2++)
lt(t3, O[a2 + u2 >>> 0]);
i2 += s2;
}
return E[r3 >> 2 >>> 0] = i2, 0;
}, c: function() {
return pt;
}, ja: function t3(e3, r3) {
t3.Mb || (t3.Mb = function() {
if ("object" == typeof crypto && "function" == typeof crypto.getRandomValues) {
var t4 = new Uint8Array(1);
return () => (crypto.getRandomValues(t4), t4[0]);
}
if (b)
try {
var e4 = n(Object(function() {
var t5 = new Error("Cannot find module 'crypto'");
throw t5.code = "MODULE_NOT_FOUND", t5;
}()));
return () => e4.randomBytes(1)[0];
} catch (t5) {
}
return () => W("randomDevice");
}());
for (var i2 = 0; i2 < r3; i2++)
S[e3 + i2 >> 0 >>> 0] = t3.Mb();
return 0;
}, ea: function(t3, e3, n2) {
var r3 = Tt();
try {
return it(t3)(e3, n2);
} catch (t4) {
if (St(r3), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, fa: function(t3, e3, n2) {
var r3 = Tt();
try {
return it(t3)(e3, n2);
} catch (t4) {
if (St(r3), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, J: function(t3) {
var e3 = Tt();
try {
return it(t3)();
} catch (t4) {
if (St(e3), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, e: function(t3, e3) {
var n2 = Tt();
try {
return it(t3)(e3);
} catch (t4) {
if (St(n2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, N: function(t3, e3, n2) {
var r3 = Tt();
try {
return it(t3)(e3, n2);
} catch (t4) {
if (St(r3), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, O: function(t3, e3, n2) {
var r3 = Tt();
try {
return it(t3)(e3, n2);
} catch (t4) {
if (St(r3), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, j: function(t3, e3, n2) {
var r3 = Tt();
try {
return it(t3)(e3, n2);
} catch (t4) {
if (St(r3), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, o: function(t3, e3, n2, r3) {
var i2 = Tt();
try {
return it(t3)(e3, n2, r3);
} catch (t4) {
if (St(i2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, p: function(t3, e3, n2, r3, i2) {
var o2 = Tt();
try {
return it(t3)(e3, n2, r3, i2);
} catch (t4) {
if (St(o2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, M: function(t3, e3, n2, r3, i2, o2) {
var a2 = Tt();
try {
return it(t3)(e3, n2, r3, i2, o2);
} catch (t4) {
if (St(a2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, r: function(t3, e3, n2, r3, i2, o2) {
var a2 = Tt();
try {
return it(t3)(e3, n2, r3, i2, o2);
} catch (t4) {
if (St(a2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, v: function(t3, e3, n2, r3, i2, o2, a2) {
var s2 = Tt();
try {
return it(t3)(e3, n2, r3, i2, o2, a2);
} catch (t4) {
if (St(s2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, K: function(t3, e3, n2, r3, i2, o2, a2, s2) {
var u2 = Tt();
try {
return it(t3)(e3, n2, r3, i2, o2, a2, s2);
} catch (t4) {
if (St(u2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, D: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) {
var f2 = Tt();
try {
return it(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2);
} catch (t4) {
if (St(f2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, X: function(t3, e3, n2, r3, i2, o2, a2, s2) {
var u2 = Tt();
try {
return Lt(t3, e3, n2, r3, i2, o2, a2, s2);
} catch (t4) {
if (St(u2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, V: function(t3, e3, n2, r3, i2, o2, a2) {
var s2 = Tt();
try {
return Pt(t3, e3, n2, r3, i2, o2, a2);
} catch (t4) {
if (St(s2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, U: function(t3, e3, n2, r3, i2) {
var o2 = Tt();
try {
return Rt(t3, e3, n2, r3, i2);
} catch (t4) {
if (St(o2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, Z: function(t3, e3, n2, r3) {
var i2 = Tt();
try {
return Ft(t3, e3, n2, r3);
} catch (t4) {
if (St(i2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, W: function(t3) {
var e3 = Tt();
try {
return It(t3);
} catch (t4) {
if (St(e3), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, Y: function(t3, e3) {
var n2 = Tt();
try {
return Nt(t3, e3);
} catch (t4) {
if (St(n2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, T: function(t3, e3, n2) {
var r3 = Tt();
try {
return Dt(t3, e3, n2);
} catch (t4) {
if (St(r3), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, f: function(t3) {
var e3 = Tt();
try {
it(t3)();
} catch (t4) {
if (St(e3), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, q: function(t3, e3) {
var n2 = Tt();
try {
it(t3)(e3);
} catch (t4) {
if (St(n2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, h: function(t3, e3, n2) {
var r3 = Tt();
try {
it(t3)(e3, n2);
} catch (t4) {
if (St(r3), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, da: function(t3, e3, n2, r3) {
var i2 = Tt();
try {
it(t3)(e3, n2, r3);
} catch (t4) {
if (St(i2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, l: function(t3, e3, n2, r3) {
var i2 = Tt();
try {
it(t3)(e3, n2, r3);
} catch (t4) {
if (St(i2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, t: function(t3, e3, n2, r3, i2) {
var o2 = Tt();
try {
it(t3)(e3, n2, r3, i2);
} catch (t4) {
if (St(o2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, u: function(t3, e3, n2, r3, i2, o2) {
var a2 = Tt();
try {
it(t3)(e3, n2, r3, i2, o2);
} catch (t4) {
if (St(a2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, x: function(t3, e3, n2, r3, i2, o2, a2) {
var s2 = Tt();
try {
it(t3)(e3, n2, r3, i2, o2, a2);
} catch (t4) {
if (St(s2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, z: function(t3, e3, n2, r3, i2, o2, a2, s2) {
var u2 = Tt();
try {
it(t3)(e3, n2, r3, i2, o2, a2, s2);
} catch (t4) {
if (St(u2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, ga: function(t3, e3, n2, r3, i2, o2, a2, s2, u2) {
var c2 = Tt();
try {
it(t3)(e3, n2, r3, i2, o2, a2, s2, u2);
} catch (t4) {
if (St(c2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, A: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2) {
var p2 = Tt();
try {
it(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2);
} catch (t4) {
if (St(p2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, C: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2) {
var b2 = Tt();
try {
it(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2);
} catch (t4) {
if (St(b2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, aa: function(t3, e3, n2, r3, i2, o2, a2, s2) {
var u2 = Tt();
try {
$t(t3, e3, n2, r3, i2, o2, a2, s2);
} catch (t4) {
if (St(u2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, _: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) {
var f2 = Tt();
try {
Ct(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2);
} catch (t4) {
if (St(f2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, $: function(t3, e3, n2, r3, i2, o2) {
var a2 = Tt();
try {
kt(t3, e3, n2, r3, i2, o2);
} catch (t4) {
if (St(a2), t4 !== t4 + 0)
throw t4;
xt(1, 0);
}
}, n: function(t3) {
return t3;
}, F: function(t3) {
pt = t3;
}, ha: gt, y: function(t3, e3, n2, r3) {
return gt(t3, e3, n2, r3);
} };
!function() {
function t3(t4) {
e2.asm = t4.exports, x = e2.asm.Ka, F(), N = e2.asm.ib, R.unshift(e2.asm.La), z--, e2.monitorRunDependencies && e2.monitorRunDependencies(z), 0 == z && (null !== G && (clearInterval(G), G = null), H && (t4 = H, H = null, t4()));
}
function n2(e3) {
t3(e3.instance);
}
function r3(t4) {
return function() {
if (!y && (h || g)) {
if ("function" == typeof fetch && !B.startsWith("file://"))
return fetch(B, { credentials: "same-origin" }).then(function(t5) {
if (!t5.ok)
throw "failed to load wasm binary file at '" + B + "'";
return t5.arrayBuffer();
}).catch(function() {
return Y();
});
if (a)
return new Promise(function(t5, e3) {
a(B, function(e4) {
t5(new Uint8Array(e4));
}, e3);
});
}
return Promise.resolve().then(function() {
return Y();
});
}().then(function(t5) {
return WebAssembly.instantiate(t5, o2);
}).then(function(t5) {
return t5;
}).then(t4, function(t5) {
v("failed to asynchronously prepare wasm: " + t5), W(t5);
});
}
var o2 = { a: bt };
if (z++, e2.monitorRunDependencies && e2.monitorRunDependencies(z), e2.instantiateWasm)
try {
return e2.instantiateWasm(o2, t3);
} catch (t4) {
return v("Module.instantiateWasm callback failed with error: " + t4), false;
}
(y || "function" != typeof WebAssembly.instantiateStreaming || q() || B.startsWith("file://") || b || "function" != typeof fetch ? r3(n2) : fetch(B, { credentials: "same-origin" }).then(function(t4) {
return WebAssembly.instantiateStreaming(t4, o2).then(n2, function(t5) {
return v("wasm streaming compile failed: " + t5), v("falling back to ArrayBuffer instantiation"), r3(n2);
});
})).catch(i);
}(), e2.___wasm_call_ctors = function() {
return (e2.___wasm_call_ctors = e2.asm.La).apply(null, arguments);
}, e2._OrtInit = function() {
return (e2._OrtInit = e2.asm.Ma).apply(null, arguments);
}, e2._OrtCreateSessionOptions = function() {
return (e2._OrtCreateSessionOptions = e2.asm.Na).apply(null, arguments);
}, e2._OrtAppendExecutionProvider = function() {
return (e2._OrtAppendExecutionProvider = e2.asm.Oa).apply(null, arguments);
}, e2._OrtAddSessionConfigEntry = function() {
return (e2._OrtAddSessionConfigEntry = e2.asm.Pa).apply(null, arguments);
}, e2._OrtReleaseSessionOptions = function() {
return (e2._OrtReleaseSessionOptions = e2.asm.Qa).apply(null, arguments);
}, e2._OrtCreateSession = function() {
return (e2._OrtCreateSession = e2.asm.Ra).apply(null, arguments);
}, e2._OrtReleaseSession = function() {
return (e2._OrtReleaseSession = e2.asm.Sa).apply(null, arguments);
}, e2._OrtGetInputCount = function() {
return (e2._OrtGetInputCount = e2.asm.Ta).apply(null, arguments);
}, e2._OrtGetOutputCount = function() {
return (e2._OrtGetOutputCount = e2.asm.Ua).apply(null, arguments);
}, e2._OrtGetInputName = function() {
return (e2._OrtGetInputName = e2.asm.Va).apply(null, arguments);
}, e2._OrtGetOutputName = function() {
return (e2._OrtGetOutputName = e2.asm.Wa).apply(null, arguments);
}, e2._OrtFree = function() {
return (e2._OrtFree = e2.asm.Xa).apply(null, arguments);
}, e2._OrtCreateTensor = function() {
return (e2._OrtCreateTensor = e2.asm.Ya).apply(null, arguments);
}, e2._OrtGetTensorData = function() {
return (e2._OrtGetTensorData = e2.asm.Za).apply(null, arguments);
}, e2._OrtReleaseTensor = function() {
return (e2._OrtReleaseTensor = e2.asm._a).apply(null, arguments);
}, e2._OrtCreateRunOptions = function() {
return (e2._OrtCreateRunOptions = e2.asm.$a).apply(null, arguments);
}, e2._OrtAddRunConfigEntry = function() {
return (e2._OrtAddRunConfigEntry = e2.asm.ab).apply(null, arguments);
}, e2._OrtReleaseRunOptions = function() {
return (e2._OrtReleaseRunOptions = e2.asm.bb).apply(null, arguments);
}, e2._OrtRun = function() {
return (e2._OrtRun = e2.asm.cb).apply(null, arguments);
}, e2._OrtEndProfiling = function() {
return (e2._OrtEndProfiling = e2.asm.db).apply(null, arguments);
};
var mt, yt = e2._malloc = function() {
return (yt = e2._malloc = e2.asm.eb).apply(null, arguments);
}, _t = e2._free = function() {
return (_t = e2._free = e2.asm.fb).apply(null, arguments);
}, vt = e2._fflush = function() {
return (vt = e2._fflush = e2.asm.gb).apply(null, arguments);
}, wt = e2.___funcs_on_exit = function() {
return (wt = e2.___funcs_on_exit = e2.asm.hb).apply(null, arguments);
}, xt = e2._setThrew = function() {
return (xt = e2._setThrew = e2.asm.jb).apply(null, arguments);
}, Tt = e2.stackSave = function() {
return (Tt = e2.stackSave = e2.asm.kb).apply(null, arguments);
}, St = e2.stackRestore = function() {
return (St = e2.stackRestore = e2.asm.lb).apply(null, arguments);
}, Ot = e2.stackAlloc = function() {
return (Ot = e2.stackAlloc = e2.asm.mb).apply(null, arguments);
}, At = e2.___cxa_can_catch = function() {
return (At = e2.___cxa_can_catch = e2.asm.nb).apply(null, arguments);
}, Et = e2.___cxa_is_pointer_type = function() {
return (Et = e2.___cxa_is_pointer_type = e2.asm.ob).apply(null, arguments);
}, It = e2.dynCall_j = function() {
return (It = e2.dynCall_j = e2.asm.pb).apply(null, arguments);
}, Pt = e2.dynCall_iiiiij = function() {
return (Pt = e2.dynCall_iiiiij = e2.asm.qb).apply(null, arguments);
}, Dt = e2.dynCall_jii = function() {
return (Dt = e2.dynCall_jii = e2.asm.rb).apply(null, arguments);
}, $t = e2.dynCall_viiiiij = function() {
return ($t = e2.dynCall_viiiiij = e2.asm.sb).apply(null, arguments);
}, kt = e2.dynCall_vjji = function() {
return (kt = e2.dynCall_vjji = e2.asm.tb).apply(null, arguments);
}, Ct = e2.dynCall_viiijjjii = function() {
return (Ct = e2.dynCall_viiijjjii = e2.asm.ub).apply(null, arguments);
}, Ft = e2.dynCall_iij = function() {
return (Ft = e2.dynCall_iij = e2.asm.vb).apply(null, arguments);
}, Nt = e2.dynCall_ji = function() {
return (Nt = e2.dynCall_ji = e2.asm.wb).apply(null, arguments);
}, Lt = e2.dynCall_iiiiiij = function() {
return (Lt = e2.dynCall_iiiiiij = e2.asm.xb).apply(null, arguments);
}, Rt = e2.dynCall_iiij = function() {
return (Rt = e2.dynCall_iiij = e2.asm.yb).apply(null, arguments);
};
function jt() {
function t3() {
if (!mt && (mt = true, e2.calledRun = true, !I)) {
if (Z(R), r2(e2), e2.onRuntimeInitialized && e2.onRuntimeInitialized(), e2.postRun)
for ("function" == typeof e2.postRun && (e2.postRun = [e2.postRun]); e2.postRun.length; ) {
var t4 = e2.postRun.shift();
M.unshift(t4);
}
Z(M);
}
}
if (!(0 < z)) {
if (e2.preRun)
for ("function" == typeof e2.preRun && (e2.preRun = [e2.preRun]); e2.preRun.length; )
V();
Z(L), 0 < z || (e2.setStatus ? (e2.setStatus("Running..."), setTimeout(function() {
setTimeout(function() {
e2.setStatus("");
}, 1), t3();
}, 1)) : t3());
}
}
if (e2.UTF8ToString = $, e2.stringToUTF8 = function(t3, e3, n2) {
return k(t3, O, e3, n2);
}, e2.lengthBytesUTF8 = C, e2.stackSave = Tt, e2.stackRestore = St, e2.stackAlloc = Ot, H = function t3() {
mt || jt(), mt || (H = t3);
}, e2.preInit)
for ("function" == typeof e2.preInit && (e2.preInit = [e2.preInit]); 0 < e2.preInit.length; )
e2.preInit.pop()();
return jt(), t2.ready;
});
t.exports = r;
}, 4537: (t) => {
"use strict";
t.exports = function(t2, e) {
for (var n = new Array(arguments.length - 1), r = 0, i = 2, o = true; i < arguments.length; )
n[r++] = arguments[i++];
return new Promise(function(i2, a) {
n[r] = function(t3) {
if (o)
if (o = false, t3)
a(t3);
else {
for (var e2 = new Array(arguments.length - 1), n2 = 0; n2 < e2.length; )
e2[n2++] = arguments[n2];
i2.apply(null, e2);
}
};
try {
t2.apply(e || null, n);
} catch (t3) {
o && (o = false, a(t3));
}
});
};
}, 7419: (t, e) => {
"use strict";
var n = e;
n.length = function(t2) {
var e2 = t2.length;
if (!e2)
return 0;
for (var n2 = 0; --e2 % 4 > 1 && "=" === t2.charAt(e2); )
++n2;
return Math.ceil(3 * t2.length) / 4 - n2;
};
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(t2, e2, n2) {
for (var i2, o2 = null, a2 = [], s = 0, u = 0; e2 < n2; ) {
var c = t2[e2++];
switch (u) {
case 0:
a2[s++] = r[c >> 2], i2 = (3 & c) << 4, u = 1;
break;
case 1:
a2[s++] = r[i2 | c >> 4], i2 = (15 & c) << 2, u = 2;
break;
case 2:
a2[s++] = r[i2 | c >> 6], a2[s++] = r[63 & c], u = 0;
}
s > 8191 && ((o2 || (o2 = [])).push(String.fromCharCode.apply(String, a2)), s = 0);
}
return u && (a2[s++] = r[i2], a2[s++] = 61, 1 === u && (a2[s++] = 61)), o2 ? (s && o2.push(String.fromCharCode.apply(String, a2.slice(0, s))), o2.join("")) : String.fromCharCode.apply(String, a2.slice(0, s));
};
var a = "invalid encoding";
n.decode = function(t2, e2, n2) {
for (var r2, o2 = n2, s = 0, u = 0; u < t2.length; ) {
var c = t2.charCodeAt(u++);
if (61 === c && s > 1)
break;
if (void 0 === (c = i[c]))
throw Error(a);
switch (s) {
case 0:
r2 = c, s = 1;
break;
case 1:
e2[n2++] = r2 << 2 | (48 & c) >> 4, r2 = c, s = 2;
break;
case 2:
e2[n2++] = (15 & r2) << 4 | (60 & c) >> 2, r2 = c, s = 3;
break;
case 3:
e2[n2++] = (3 & r2) << 6 | c, s = 0;
}
}
if (1 === s)
throw Error(a);
return n2 - o2;
}, n.test = function(t2) {
return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t2);
};
}, 9211: (t) => {
"use strict";
function e() {
this._listeners = {};
}
t.exports = e, e.prototype.on = function(t2, e2, n) {
return (this._listeners[t2] || (this._listeners[t2] = [])).push({ fn: e2, ctx: n || this }), this;
}, e.prototype.off = function(t2, e2) {
if (void 0 === t2)
this._listeners = {};
else if (void 0 === e2)
this._listeners[t2] = [];
else
for (var n = this._listeners[t2], r = 0; r < n.length; )
n[r].fn === e2 ? n.splice(r, 1) : ++r;
return this;
}, e.prototype.emit = function(t2) {
var e2 = this._listeners[t2];
if (e2) {
for (var n = [], r = 1; r < arguments.length; )
n.push(arguments[r++]);
for (r = 0; r < e2.length; )
e2[r].fn.apply(e2[r++].ctx, n);
}
return this;
};
}, 945: (t) => {
"use strict";
function e(t2) {
return "undefined" != typeof Float32Array ? function() {
var e2 = new Float32Array([-0]), n2 = new Uint8Array(e2.buffer), r2 = 128 === n2[3];
function i2(t3, r3, i3) {
e2[0] = t3, r3[i3] = n2[0], r3[i3 + 1] = n2[1], r3[i3 + 2] = n2[2], r3[i3 + 3] = n2[3];
}
function o2(t3, r3, i3) {
e2[0] = t3, r3[i3] = n2[3], r3[i3 + 1] = n2[2], r3[i3 + 2] = n2[1], r3[i3 + 3] = n2[0];
}
function a(t3, r3) {
return n2[0] = t3[r3], n2[1] = t3[r3 + 1], n2[2] = t3[r3 + 2], n2[3] = t3[r3 + 3], e2[0];
}
function s(t3, r3) {
return n2[3] = t3[r3], n2[2] = t3[r3 + 1], n2[1] = t3[r3 + 2], n2[0] = t3[r3 + 3], e2[0];
}
t2.writeFloatLE = r2 ? i2 : o2, t2.writeFloatBE = r2 ? o2 : i2, t2.readFloatLE = r2 ? a : s, t2.readFloatBE = r2 ? s : a;
}() : function() {
function e2(t3, e3, n2, r2) {
var i2 = e3 < 0 ? 1 : 0;
if (i2 && (e3 = -e3), 0 === e3)
t3(1 / e3 > 0 ? 0 : 2147483648, n2, r2);
else if (isNaN(e3))
t3(2143289344, n2, r2);
else if (e3 > 34028234663852886e22)
t3((i2 << 31 | 2139095040) >>> 0, n2, r2);
else if (e3 < 11754943508222875e-54)
t3((i2 << 31 | Math.round(e3 / 1401298464324817e-60)) >>> 0, n2, r2);
else {
var o2 = Math.floor(Math.log(e3) / Math.LN2);
t3((i2 << 31 | o2 + 127 << 23 | 8388607 & Math.round(e3 * Math.pow(2, -o2) * 8388608)) >>> 0, n2, r2);
}
}
function a(t3, e3, n2) {
var r2 = t3(e3, n2), i2 = 2 * (r2 >> 31) + 1, o2 = r2 >>> 23 & 255, a2 = 8388607 & r2;
return 255 === o2 ? a2 ? NaN : i2 * (1 / 0) : 0 === o2 ? 1401298464324817e-60 * i2 * a2 : i2 * Math.pow(2, o2 - 150) * (a2 + 8388608);
}
t2.writeFloatLE = e2.bind(null, n), t2.writeFloatBE = e2.bind(null, r), t2.readFloatLE = a.bind(null, i), t2.readFloatBE = a.bind(null, o);
}(), "undefined" != typeof Float64Array ? function() {
var e2 = new Float64Array([-0]), n2 = new Uint8Array(e2.buffer), r2 = 128 === n2[7];
function i2(t3, r3, i3) {
e2[0] = t3, r3[i3] = n2[0], r3[i3 + 1] = n2[1], r3[i3 + 2] = n2[2], r3[i3 + 3] = n2[3], r3[i3 + 4] = n2[4], r3[i3 + 5] = n2[5], r3[i3 + 6] = n2[6], r3[i3 + 7] = n2[7];
}
function o2(t3, r3, i3) {
e2[0] = t3, r3[i3] = n2[7], r3[i3 + 1] = n2[6], r3[i3 + 2] = n2[5], r3[i3 + 3] = n2[4], r3[i3 + 4] = n2[3], r3[i3 + 5] = n2[2], r3[i3 + 6] = n2[1], r3[i3 + 7] = n2[0];
}
function a(t3, r3) {
return n2[0] = t3[r3], n2[1] = t3[r3 + 1], n2[2] = t3[r3 + 2], n2[3] = t3[r3 + 3], n2[4] = t3[r3 + 4], n2[5] = t3[r3 + 5], n2[6] = t3[r3 + 6], n2[7] = t3[r3 + 7], e2[0];
}
function s(t3, r3) {
return n2[7] = t3[r3], n2[6] = t3[r3 + 1], n2[5] = t3[r3 + 2], n2[4] = t3[r3 + 3], n2[3] = t3[r3 + 4], n2[2] = t3[r3 + 5], n2[1] = t3[r3 + 6], n2[0] = t3[r3 + 7], e2[0];
}
t2.writeDoubleLE = r2 ? i2 : o2, t2.writeDoubleBE = r2 ? o2 : i2, t2.readDoubleLE = r2 ? a : s, t2.readDoubleBE = r2 ? s : a;
}() : function() {
function e2(t3, e3, n2, r2, i2, o2) {
var a2 = r2 < 0 ? 1 : 0;
if (a2 && (r2 = -r2), 0 === r2)
t3(0, i2, o2 + e3), t3(1 / r2 > 0 ? 0 : 2147483648, i2, o2 + n2);
else if (isNaN(r2))
t3(0, i2, o2 + e3), t3(2146959360, i2, o2 + n2);
else if (r2 > 17976931348623157e292)
t3(0, i2, o2 + e3), t3((a2 << 31 | 2146435072) >>> 0, i2, o2 + n2);
else {
var s;
if (r2 < 22250738585072014e-324)
t3((s = r2 / 5e-324) >>> 0, i2, o2 + e3), t3((a2 << 31 | s / 4294967296) >>> 0, i2, o2 + n2);
else {
var u = Math.floor(Math.log(r2) / Math.LN2);
1024 === u && (u = 1023), t3(4503599627370496 * (s = r2 * Math.pow(2, -u)) >>> 0, i2, o2 + e3), t3((a2 << 31 | u + 1023 << 20 | 1048576 * s & 1048575) >>> 0, i2, o2 + n2);
}
}
}
function a(t3, e3, n2, r2, i2) {
var o2 = t3(r2, i2 + e3), a2 = t3(r2, i2 + n2), s = 2 * (a2 >> 31) + 1, u = a2 >>> 20 & 2047, c = 4294967296 * (1048575 & a2) + o2;
return 2047 === u ? c ? NaN : s * (1 / 0) : 0 === u ? 5e-324 * s * c : s * Math.pow(2, u - 1075) * (c + 4503599627370496);
}
t2.writeDoubleLE = e2.bind(null, n, 0, 4), t2.writeDoubleBE = e2.bind(null, r, 4, 0), t2.readDoubleLE = a.bind(null, i, 0, 4), t2.readDoubleBE = a.bind(null, o, 4, 0);
}(), t2;
}
function n(t2, e2, n2) {
e2[n2] = 255 & t2, e2[n2 + 1] = t2 >>> 8 & 255, e2[n2 + 2] = t2 >>> 16 & 255, e2[n2 + 3] = t2 >>> 24;
}
function r(t2, e2, n2) {
e2[n2] = t2 >>> 24, e2[n2 + 1] = t2 >>> 16 & 255, e2[n2 + 2] = t2 >>> 8 & 255, e2[n2 + 3] = 255 & t2;
}
function i(t2, e2) {
return (t2[e2] | t2[e2 + 1] << 8 | t2[e2 + 2] << 16 | t2[e2 + 3] << 24) >>> 0;
}
function o(t2, e2) {
return (t2[e2] << 24 | t2[e2 + 1] << 16 | t2[e2 + 2] << 8 | t2[e2 + 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(t2, e, n) {
var r = n || 8192, i = r >>> 1, o = null, a = r;
return function(n2) {
if (n2 < 1 || n2 > i)
return t2(n2);
a + n2 > r && (o = t2(r), a = 0);
var s = e.call(o, a, a += n2);
return 7 & a && (a = 1 + (7 | a)), s;
};
};
}, 4997: (t, e) => {
"use strict";
var n = e;
n.length = function(t2) {
for (var e2 = 0, n2 = 0, r = 0; r < t2.length; ++r)
(n2 = t2.charCodeAt(r)) < 128 ? e2 += 1 : n2 < 2048 ? e2 += 2 : 55296 == (64512 & n2) && 56320 == (64512 & t2.charCodeAt(r + 1)) ? (++r, e2 += 4) : e2 += 3;
return e2;
}, n.read = function(t2, e2, n2) {
if (n2 - e2 < 1)
return "";
for (var r, i = null, o = [], a = 0; e2 < n2; )
(r = t2[e2++]) < 128 ? o[a++] = r : r > 191 && r < 224 ? o[a++] = (31 & r) << 6 | 63 & t2[e2++] : r > 239 && r < 365 ? (r = ((7 & r) << 18 | (63 & t2[e2++]) << 12 | (63 & t2[e2++]) << 6 | 63 & t2[e2++]) - 65536, o[a++] = 55296 + (r >> 10), o[a++] = 56320 + (1023 & r)) : o[a++] = (15 & r) << 12 | (63 & t2[e2++]) << 6 | 63 & t2[e2++], 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(t2, e2, n2) {
for (var r, i, o = n2, a = 0; a < t2.length; ++a)
(r = t2.charCodeAt(a)) < 128 ? e2[n2++] = r : r < 2048 ? (e2[n2++] = r >> 6 | 192, e2[n2++] = 63 & r | 128) : 55296 == (64512 & r) && 56320 == (64512 & (i = t2.charCodeAt(a + 1))) ? (r = 65536 + ((1023 & r) << 10) + (1023 & i), ++a, e2[n2++] = r >> 18 | 240, e2[n2++] = r >> 12 & 63 | 128, e2[n2++] = r >> 6 & 63 | 128, e2[n2++] = 63 & r | 128) : (e2[n2++] = r >> 12 | 224, e2[n2++] = r >> 6 & 63 | 128, e2[n2++] = 63 & r | 128);
return n2 - o;
};
}, 3442: (t, e) => {
"use strict";
e.__esModule = true;
var n = function() {
function t2(e2) {
if (!e2)
throw new TypeError("Invalid argument; `value` has no value.");
this.value = t2.EMPTY, e2 && t2.isGuid(e2) && (this.value = e2);
}
return t2.isGuid = function(e2) {
var n2 = e2.toString();
return e2 && (e2 instanceof t2 || t2.validator.test(n2));
}, t2.create = function() {
return new t2([t2.gen(2), t2.gen(1), t2.gen(1), t2.gen(1), t2.gen(3)].join("-"));
}, t2.createEmpty = function() {
return new t2("emptyguid");
}, t2.parse = function(e2) {
return new t2(e2);
}, t2.raw = function() {
return [t2.gen(2), t2.gen(1), t2.gen(1), t2.gen(1), t2.gen(3)].join("-");
}, t2.gen = function(t3) {
for (var e2 = "", n2 = 0; n2 < t3; n2++)
e2 += (65536 * (1 + Math.random()) | 0).toString(16).substring(1);
return e2;
}, t2.prototype.equals = function(e2) {
return t2.isGuid(e2) && this.value === e2.toString();
}, t2.prototype.isEmpty = function() {
return this.value === t2.EMPTY;
}, t2.prototype.toString = function() {
return this.value;
}, t2.prototype.toJSON = function() {
return { value: this.value };
}, t2.validator = new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$", "i"), t2.EMPTY = "00000000-0000-0000-0000-000000000000", t2;
}();
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 (t2) {
}
function n(t2, e2, n2) {
this.low = 0 | t2, this.high = 0 | e2, this.unsigned = !!n2;
}
function r(t2) {
return true === (t2 && t2.__isLong__);
}
n.prototype.__isLong__, Object.defineProperty(n.prototype, "__isLong__", { value: true }), n.isLong = r;
var i = {}, o = {};
function a(t2, e2) {
var n2, r2, a2;
return e2 ? (a2 = 0 <= (t2 >>>= 0) && t2 < 256) && (r2 = o[t2]) ? r2 : (n2 = u(t2, (0 | t2) < 0 ? -1 : 0, true), a2 && (o[t2] = n2), n2) : (a2 = -128 <= (t2 |= 0) && t2 < 128) && (r2 = i[t2]) ? r2 : (n2 = u(t2, t2 < 0 ? -1 : 0, false), a2 && (i[t2] = n2), n2);
}
function s(t2, e2) {
if (isNaN(t2))
return e2 ? m : b;
if (e2) {
if (t2 < 0)
return m;
if (t2 >= d)
return x;
} else {
if (t2 <= -h)
return T;
if (t2 + 1 >= h)
return w;
}
return t2 < 0 ? s(-t2, e2).neg() : u(t2 % f | 0, t2 / f | 0, e2);
}
function u(t2, e2, r2) {
return new n(t2, e2, r2);
}
n.fromInt = a, n.fromNumber = s, n.fromBits = u;
var c = Math.pow;
function l(t2, e2, n2) {
if (0 === t2.length)
throw Error("empty string");
if ("NaN" === t2 || "Infinity" === t2 || "+Infinity" === t2 || "-Infinity" === t2)
return b;
if ("number" == typeof e2 ? (n2 = e2, e2 = false) : e2 = !!e2, (n2 = n2 || 10) < 2 || 36 < n2)
throw RangeError("radix");
var r2;
if ((r2 = t2.indexOf("-")) > 0)
throw Error("interior hyphen");
if (0 === r2)
return l(t2.substring(1), e2, n2).neg();
for (var i2 = s(c(n2, 8)), o2 = b, a2 = 0; a2 < t2.length; a2 += 8) {
var u2 = Math.min(8, t2.length - a2), p2 = parseInt(t2.substring(a2, a2 + u2), n2);
if (u2 < 8) {
var f2 = s(c(n2, u2));
o2 = o2.mul(f2).add(s(p2));
} else
o2 = (o2 = o2.mul(i2)).add(s(p2));
}
return o2.unsigned = e2, o2;
}
function p(t2, e2) {
return "number" == typeof t2 ? s(t2, e2) : "string" == typeof t2 ? l(t2, e2) : u(t2.low, t2.high, "boolean" == typeof e2 ? e2 : t2.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, true);
n.UZERO = m;
var y = a(1);
n.ONE = y;
var _ = a(1, true);
n.UONE = _;
var v = a(-1);
n.NEG_ONE = v;
var w = u(-1, 2147483647, false);
n.MAX_VALUE = w;
var x = u(-1, -1, true);
n.MAX_UNSIGNED_VALUE = x;
var T = u(0, -2147483648, false);
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(t2) {
if ((t2 = t2 || 10) < 2 || 36 < t2)
throw RangeError("radix");
if (this.isZero())
return "0";
if (this.isNegative()) {
if (this.eq(T)) {
var e2 = s(t2), n2 = this.div(e2), r2 = n2.mul(e2).sub(this);
return n2.toString(t2) + r2.toInt().toString(t2);
}
return "-" + this.neg().toString(t2);
}
for (var i2 = s(c(t2, 6), this.unsigned), o2 = this, a2 = ""; ; ) {
var u2 = o2.div(i2), l2 = (o2.sub(u2.mul(i2)).toInt() >>> 0).toString(t2);
if ((o2 = u2).isZero())
return l2 + a2;
for (; l2.length < 6; )
l2 = "0" + l2;
a2 = "" + l2 + a2;
}
}, 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 t2 = 0 != this.high ? this.high : this.low, e2 = 31; e2 > 0 && 0 == (t2 & 1 << e2); e2--)
;
return 0 != this.high ? e2 + 33 : e2 + 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(t2) {
return r(t2) || (t2 = p(t2)), (this.unsigned === t2.unsigned || this.high >>> 31 != 1 || t2.high >>> 31 != 1) && this.high === t2.high && this.low === t2.low;
}, S.eq = S.equals, S.notEquals = function(t2) {
return !this.eq(t2);
}, S.neq = S.notEquals, S.ne = S.notEquals, S.lessThan = function(t2) {
return this.comp(t2) < 0;
}, S.lt = S.lessThan, S.lessThanOrEqual = function(t2) {
return this.comp(t2) <= 0;
}, S.lte = S.lessThanOrEqual, S.le = S.lessThanOrEqual, S.greaterThan = function(t2) {
return this.comp(t2) > 0;
}, S.gt = S.greaterThan, S.greaterThanOrEqual = function(t2) {
return this.comp(t2) >= 0;
}, S.gte = S.greaterThanOrEqual, S.ge = S.greaterThanOrEqual, S.compare = function(t2) {
if (r(t2) || (t2 = p(t2)), this.eq(t2))
return 0;
var e2 = this.isNegative(), n2 = t2.isNegative();
return e2 && !n2 ? -1 : !e2 && n2 ? 1 : this.unsigned ? t2.high >>> 0 > this.high >>> 0 || t2.high === this.high && t2.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(t2).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(t2) {
r(t2) || (t2 = p(t2));
var e2 = this.high >>> 16, n2 = 65535 & this.high, i2 = this.low >>> 16, o2 = 65535 & this.low, a2 = t2.high >>> 16, s2 = 65535 & t2.high, c2 = t2.low >>> 16, l2 = 0, f2 = 0, d2 = 0, h2 = 0;
return d2 += (h2 += o2 + (65535 & t2.low)) >>> 16, f2 += (d2 += i2 + c2) >>> 16, l2 += (f2 += n2 + s2) >>> 16, l2 += e2 + a2, u((d2 &= 65535) << 16 | (h2 &= 65535), (l2 &= 65535) << 16 | (f2 &= 65535), this.unsigned);
}, S.subtract = function(t2) {
return r(t2) || (t2 = p(t2)), this.add(t2.neg());
}, S.sub = S.subtract, S.multiply = function(t2) {
if (this.isZero())
return b;
if (r(t2) || (t2 = p(t2)), e)
return u(e.mul(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned);
if (t2.isZero())
return b;
if (this.eq(T))
return t2.isOdd() ? T : b;
if (t2.eq(T))
return this.isOdd() ? T : b;
if (this.isNegative())
return t2.isNegative() ? this.neg().mul(t2.neg()) : this.neg().mul(t2).neg();
if (t2.isNegative())
return this.mul(t2.neg()).neg();
if (this.lt(g) && t2.lt(g))
return s(this.toNumber() * t2.toNumber(), this.unsigned);
var n2 = this.high >>> 16, i2 = 65535 & this.high, o2 = this.low >>> 16, a2 = 65535 & this.low, c2 = t2.high >>> 16, l2 = 65535 & t2.high, f2 = t2.low >>> 16, d2 = 65535 & t2.low, h2 = 0, m2 = 0, y2 = 0, _2 = 0;
return y2 += (_2 += a2 * d2) >>> 16, m2 += (y2 += o2 * d2) >>> 16, y2 &= 65535, m2 += (y2 += a2 * f2) >>> 16, h2 += (m2 += i2 * d2) >>> 16, m2 &= 65535, h2 += (m2 += o2 * f2) >>> 16, m2 &= 65535, h2 += (m2 += a2 * l2) >>> 16, h2 += n2 * d2 + i2 * f2 + o2 * l2 + a2 * c2, u((y2 &= 65535) << 16 | (_2 &= 65535), (h2 &= 65535) << 16 | (m2 &= 65535), this.unsigned);
}, S.mul = S.multiply, S.divide = function(t2) {
if (r(t2) || (t2 = p(t2)), t2.isZero())
throw Error("division by zero");
var n2, i2, o2;
if (e)
return this.unsigned || -2147483648 !== this.high || -1 !== t2.low || -1 !== t2.high ? u((this.unsigned ? e.div_u : e.div_s)(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned) : this;
if (this.isZero())
return this.unsigned ? m : b;
if (this.unsigned) {
if (t2.unsigned || (t2 = t2.toUnsigned()), t2.gt(this))
return m;
if (t2.gt(this.shru(1)))
return _;
o2 = m;
} else {
if (this.eq(T))
return t2.eq(y) || t2.eq(v) ? T : t2.eq(T) ? y : (n2 = this.shr(1).div(t2).shl(1)).eq(b) ? t2.isNegative() ? y : v : (i2 = this.sub(t2.mul(n2)), o2 = n2.add(i2.div(t2)));
if (t2.eq(T))
return this.unsigned ? m : b;
if (this.isNegative())
return t2.isNegative() ? this.neg().div(t2.neg()) : this.neg().div(t2).neg();
if (t2.isNegative())
return this.div(t2.neg()).neg();
o2 = b;
}
for (i2 = this; i2.gte(t2); ) {
n2 = Math.max(1, Math.floor(i2.toNumber() / t2.toNumber()));
for (var a2 = Math.ceil(Math.log(n2) / Math.LN2), l2 = a2 <= 48 ? 1 : c(2, a2 - 48), f2 = s(n2), d2 = f2.mul(t2); d2.isNegative() || d2.gt(i2); )
d2 = (f2 = s(n2 -= l2, this.unsigned)).mul(t2);
f2.isZero() && (f2 = y), o2 = o2.add(f2), i2 = i2.sub(d2);
}
return o2;
}, S.div = S.divide, S.modulo = function(t2) {
return r(t2) || (t2 = p(t2)), e ? u((this.unsigned ? e.rem_u : e.rem_s)(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned) : this.sub(this.div(t2).mul(t2));
}, S.mod = S.modulo, S.rem = S.modulo, S.not = function() {
return u(~this.low, ~this.high, this.unsigned);
}, S.and = function(t2) {
return r(t2) || (t2 = p(t2)), u(this.low & t2.low, this.high & t2.high, this.unsigned);
}, S.or = function(t2) {
return r(t2) || (t2 = p(t2)), u(this.low | t2.low, this.high | t2.high, this.unsigned);
}, S.xor = function(t2) {
return r(t2) || (t2 = p(t2)), u(this.low ^ t2.low, this.high ^ t2.high, this.unsigned);
}, S.shiftLeft = function(t2) {
return r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63) ? this : t2 < 32 ? u(this.low << t2, this.high << t2 | this.low >>> 32 - t2, this.unsigned) : u(0, this.low << t2 - 32, this.unsigned);
}, S.shl = S.shiftLeft, S.shiftRight = function(t2) {
return r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63) ? this : t2 < 32 ? u(this.low >>> t2 | this.high << 32 - t2, this.high >> t2, this.unsigned) : u(this.high >> t2 - 32, this.high >= 0 ? 0 : -1, this.unsigned);
}, S.shr = S.shiftRight, S.shiftRightUnsigned = function(t2) {
if (r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63))
return this;
var e2 = this.high;
return t2 < 32 ? u(this.low >>> t2 | e2 << 32 - t2, e2 >>> t2, this.unsigned) : u(32 === t2 ? e2 : e2 >>> t2 - 32, 0, this.unsigned);
}, S.shru = S.shiftRightUnsigned, S.shr_u = S.shiftRightUnsigned, S.toSigned = function() {
return this.unsigned ? u(this.low, this.high, false) : this;
}, S.toUnsigned = function() {
return this.unsigned ? this : u(this.low, this.high, true);
}, S.toBytes = function(t2) {
return t2 ? this.toBytesLE() : this.toBytesBE();
}, S.toBytesLE = function() {
var t2 = this.high, e2 = this.low;
return [255 & e2, e2 >>> 8 & 255, e2 >>> 16 & 255, e2 >>> 24, 255 & t2, t2 >>> 8 & 255, t2 >>> 16 & 255, t2 >>> 24];
}, S.toBytesBE = function() {
var t2 = this.high, e2 = this.low;
return [t2 >>> 24, t2 >>> 16 & 255, t2 >>> 8 & 255, 255 & t2, e2 >>> 24, e2 >>> 16 & 255, e2 >>> 8 & 255, 255 & e2];
}, n.fromBytes = function(t2, e2, r2) {
return r2 ? n.fromBytesLE(t2, e2) : n.fromBytesBE(t2, e2);
}, n.fromBytesLE = function(t2, e2) {
return new n(t2[0] | t2[1] << 8 | t2[2] << 16 | t2[3] << 24, t2[4] | t2[5] << 8 | t2[6] << 16 | t2[7] << 24, e2);
}, n.fromBytesBE = function(t2, e2) {
return new n(t2[4] << 24 | t2[5] << 16 | t2[6] << 8 | t2[7], t2[0] << 24 | t2[1] << 16 | t2[2] << 8 | t2[3], e2);
};
}, 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 t2(t3) {
if (this.floats = [], this.ints = [], this.strings = [], this.tensors = [], this.graphs = [], t3)
for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2)
null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
}
return t2.prototype.name = "", t2.prototype.refAttrName = "", t2.prototype.docString = "", t2.prototype.type = 0, t2.prototype.f = 0, t2.prototype.i = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.s = c.newBuffer([]), t2.prototype.t = null, t2.prototype.g = null, t2.prototype.floats = c.emptyArray, t2.prototype.ints = c.emptyArray, t2.prototype.strings = c.emptyArray, t2.prototype.tensors = c.emptyArray, t2.prototype.graphs = c.emptyArray, t2.create = function(e2) {
return new t2(e2);
}, t2.encode = function(t3, e2) {
if (e2 || (e2 = u.create()), null != t3.name && t3.hasOwnProperty("name") && e2.uint32(10).string(t3.name), null != t3.f && t3.hasOwnProperty("f") && e2.uint32(21).float(t3.f), null != t3.i && t3.hasOwnProperty("i") && e2.uint32(24).int64(t3.i), null != t3.s && t3.hasOwnProperty("s") && e2.uint32(34).bytes(t3.s), null != t3.t && t3.hasOwnProperty("t") && l.onnx.TensorProto.encode(t3.t, e2.uint32(42).fork()).ldelim(), null != t3.g && t3.hasOwnProperty("g") && l.onnx.GraphProto.encode(t3.g, e2.uint32(50).fork()).ldelim(), null != t3.floats && t3.floats.length) {
e2.uint32(58).fork();
for (var n2 = 0; n2 < t3.floats.length; ++n2)
e2.float(t3.floats[n2]);
e2.ldelim();
}
if (null != t3.ints && t3.ints.length) {
for (e2.uint32(66).fork(), n2 = 0; n2 < t3.ints.length; ++n2)
e2.int64(t3.ints[n2]);
e2.ldelim();
}
if (null != t3.strings && t3.strings.length)
for (n2 = 0; n2 < t3.strings.length; ++n2)
e2.uint32(74).bytes(t3.strings[n2]);
if (null != t3.tensors && t3.tensors.length)
for (n2 = 0; n2 < t3.tensors.length; ++n2)
l.onnx.TensorProto.encode(t3.tensors[n2], e2.uint32(82).fork()).ldelim();
if (null != t3.graphs && t3.graphs.length)
for (n2 = 0; n2 < t3.graphs.length; ++n2)
l.onnx.GraphProto.encode(t3.graphs[n2], e2.uint32(90).fork()).ldelim();
return null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(106).string(t3.docString), null != t3.type && t3.hasOwnProperty("type") && e2.uint32(160).int32(t3.type), null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && e2.uint32(170).string(t3.refAttrName), e2;
}, t2.encodeDelimited = function(t3, e2) {
return this.encode(t3, e2).ldelim();
}, t2.decode = function(t3, e2) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.AttributeProto(); t3.pos < n2; ) {
var i2 = t3.uint32();
switch (i2 >>> 3) {
case 1:
r2.name = t3.string();
break;
case 21:
r2.refAttrName = t3.string();
break;
case 13:
r2.docString = t3.string();
break;
case 20:
r2.type = t3.int32();
break;
case 2:
r2.f = t3.float();
break;
case 3:
r2.i = t3.int64();
break;
case 4:
r2.s = t3.bytes();
break;
case 5:
r2.t = l.onnx.TensorProto.decode(t3, t3.uint32());
break;
case 6:
r2.g = l.onnx.GraphProto.decode(t3, t3.uint32());
break;
case 7:
if (r2.floats && r2.floats.length || (r2.floats = []), 2 == (7 & i2))
for (var o2 = t3.uint32() + t3.pos; t3.pos < o2; )
r2.floats.push(t3.float());
else
r2.floats.push(t3.float());
break;
case 8:
if (r2.ints && r2.ints.length || (r2.ints = []), 2 == (7 & i2))
for (o2 = t3.uint32() + t3.pos; t3.pos < o2; )
r2.ints.push(t3.int64());
else
r2.ints.push(t3.int64());
break;
case 9:
r2.strings && r2.strings.length || (r2.strings = []), r2.strings.push(t3.bytes());
break;
case 10:
r2.tensors && r2.tensors.length || (r2.tensors = []), r2.tensors.push(l.onnx.TensorProto.decode(t3, t3.uint32()));
break;
case 11:
r2.graphs && r2.graphs.length || (r2.graphs = []), r2.graphs.push(l.onnx.GraphProto.decode(t3, t3.uint32()));
break;
default:
t3.skipType(7 & i2);
}
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
if ("object" != typeof t3 || null === t3)
return "object expected";
if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name))
return "name: string expected";
if (null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && !c.isString(t3.refAttrName))
return "refAttrName: string expected";
if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString))
return "docString: string expected";
if (null != t3.type && t3.hasOwnProperty("type"))
switch (t3.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 != t3.f && t3.hasOwnProperty("f") && "number" != typeof t3.f)
return "f: number expected";
if (null != t3.i && t3.hasOwnProperty("i") && !(c.isInteger(t3.i) || t3.i && c.isInteger(t3.i.low) && c.isInteger(t3.i.high)))
return "i: integer|Long expected";
if (null != t3.s && t3.hasOwnProperty("s") && !(t3.s && "number" == typeof t3.s.length || c.isString(t3.s)))
return "s: buffer expected";
if (null != t3.t && t3.hasOwnProperty("t") && (n2 = l.onnx.TensorProto.verify(t3.t)))
return "t." + n2;
if (null != t3.g && t3.hasOwnProperty("g") && (n2 = l.onnx.GraphProto.verify(t3.g)))
return "g." + n2;
if (null != t3.floats && t3.hasOwnProperty("floats")) {
if (!Array.isArray(t3.floats))
return "floats: array expected";
for (var e2 = 0; e2 < t3.floats.length; ++e2)
if ("number" != typeof t3.floats[e2])
return "floats: number[] expected";
}
if (null != t3.ints && t3.hasOwnProperty("ints")) {
if (!Array.isArray(t3.ints))
return "ints: array expected";
for (e2 = 0; e2 < t3.ints.length; ++e2)
if (!(c.isInteger(t3.ints[e2]) || t3.ints[e2] && c.isInteger(t3.ints[e2].low) && c.isInteger(t3.ints[e2].high)))
return "ints: integer|Long[] expected";
}
if (null != t3.strings && t3.hasOwnProperty("strings")) {
if (!Array.isArray(t3.strings))
return "strings: array expected";
for (e2 = 0; e2 < t3.strings.length; ++e2)
if (!(t3.strings[e2] && "number" == typeof t3.strings[e2].length || c.isString(t3.strings[e2])))
return "strings: buffer[] expected";
}
if (null != t3.tensors && t3.hasOwnProperty("tensors")) {
if (!Array.isArray(t3.tensors))
return "tensors: array expected";
for (e2 = 0; e2 < t3.tensors.length; ++e2)
if (n2 = l.onnx.TensorProto.verify(t3.tensors[e2]))
return "tensors." + n2;
}
if (null != t3.graphs && t3.hasOwnProperty("graphs")) {
if (!Array.isArray(t3.graphs))
return "graphs: array expected";
for (e2 = 0; e2 < t3.graphs.length; ++e2) {
var n2;
if (n2 = l.onnx.GraphProto.verify(t3.graphs[e2]))
return "graphs." + n2;
}
}
return null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.AttributeProto)
return t3;
var e2 = new l.onnx.AttributeProto();
switch (null != t3.name && (e2.name = String(t3.name)), null != t3.refAttrName && (e2.refAttrName = String(t3.refAttrName)), null != t3.docString && (e2.docString = String(t3.docString)), t3.type) {
case "UNDEFINED":
case 0:
e2.type = 0;
break;
case "FLOAT":
case 1:
e2.type = 1;
break;
case "INT":
case 2:
e2.type = 2;
break;
case "STRING":
case 3:
e2.type = 3;
break;
case "TENSOR":
case 4:
e2.type = 4;
break;
case "GRAPH":
case 5:
e2.type = 5;
break;
case "FLOATS":
case 6:
e2.type = 6;
break;
case "INTS":
case 7:
e2.type = 7;
break;
case "STRINGS":
case 8:
e2.type = 8;
break;
case "TENSORS":
case 9:
e2.type = 9;
break;
case "GRAPHS":
case 10:
e2.type = 10;
}
if (null != t3.f && (e2.f = Number(t3.f)), null != t3.i && (c.Long ? (e2.i = c.Long.fromValue(t3.i)).unsigned = false : "string" == typeof t3.i ? e2.i = parseInt(t3.i, 10) : "number" == typeof t3.i ? e2.i = t3.i : "object" == typeof t3.i && (e2.i = new c.LongBits(t3.i.low >>> 0, t3.i.high >>> 0).toNumber())), null != t3.s && ("string" == typeof t3.s ? c.base64.decode(t3.s, e2.s = c.newBuffer(c.base64.length(t3.s)), 0) : t3.s.length && (e2.s = t3.s)), null != t3.t) {
if ("object" != typeof t3.t)
throw TypeError(".onnx.AttributeProto.t: object expected");
e2.t = l.onnx.TensorProto.fromObject(t3.t);
}
if (null != t3.g) {
if ("object" != typeof t3.g)
throw TypeError(".onnx.AttributeProto.g: object expected");
e2.g = l.onnx.GraphProto.fromObject(t3.g);
}
if (t3.floats) {
if (!Array.isArray(t3.floats))
throw TypeError(".onnx.AttributeProto.floats: array expected");
e2.floats = [];
for (var n2 = 0; n2 < t3.floats.length; ++n2)
e2.floats[n2] = Number(t3.floats[n2]);
}
if (t3.ints) {
if (!Array.isArray(t3.ints))
throw TypeError(".onnx.AttributeProto.ints: array expected");
for (e2.ints = [], n2 = 0; n2 < t3.ints.length; ++n2)
c.Long ? (e2.ints[n2] = c.Long.fromValue(t3.ints[n2])).unsigned = false : "string" == typeof t3.ints[n2] ? e2.ints[n2] = parseInt(t3.ints[n2], 10) : "number" == typeof t3.ints[n2] ? e2.ints[n2] = t3.ints[n2] : "object" == typeof t3.ints[n2] && (e2.ints[n2] = new c.LongBits(t3.ints[n2].low >>> 0, t3.ints[n2].high >>> 0).toNumber());
}
if (t3.strings) {
if (!Array.isArray(t3.strings))
throw TypeError(".onnx.AttributeProto.strings: array expected");
for (e2.strings = [], n2 = 0; n2 < t3.strings.length; ++n2)
"string" == typeof t3.strings[n2] ? c.base64.decode(t3.strings[n2], e2.strings[n2] = c.newBuffer(c.base64.length(t3.strings[n2])), 0) : t3.strings[n2].length && (e2.strings[n2] = t3.strings[n2]);
}
if (t3.tensors) {
if (!Array.isArray(t3.tensors))
throw TypeError(".onnx.AttributeProto.tensors: array expected");
for (e2.tensors = [], n2 = 0; n2 < t3.tensors.length; ++n2) {
if ("object" != typeof t3.tensors[n2])
throw TypeError(".onnx.AttributeProto.tensors: object expected");
e2.tensors[n2] = l.onnx.TensorProto.fromObject(t3.tensors[n2]);
}
}
if (t3.graphs) {
if (!Array.isArray(t3.graphs))
throw TypeError(".onnx.AttributeProto.graphs: array expected");
for (e2.graphs = [], n2 = 0; n2 < t3.graphs.length; ++n2) {
if ("object" != typeof t3.graphs[n2])
throw TypeError(".onnx.AttributeProto.graphs: object expected");
e2.graphs[n2] = l.onnx.GraphProto.fromObject(t3.graphs[n2]);
}
}
return e2;
}, t2.toObject = function(t3, e2) {
e2 || (e2 = {});
var n2 = {};
if ((e2.arrays || e2.defaults) && (n2.floats = [], n2.ints = [], n2.strings = [], n2.tensors = [], n2.graphs = []), e2.defaults) {
if (n2.name = "", n2.f = 0, c.Long) {
var r2 = new c.Long(0, 0, false);
n2.i = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2;
} else
n2.i = e2.longs === String ? "0" : 0;
e2.bytes === String ? n2.s = "" : (n2.s = [], e2.bytes !== Array && (n2.s = c.newBuffer(n2.s))), n2.t = null, n2.g = null, n2.docString = "", n2.type = e2.enums === String ? "UNDEFINED" : 0, n2.refAttrName = "";
}
if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.f && t3.hasOwnProperty("f") && (n2.f = e2.json && !isFinite(t3.f) ? String(t3.f) : t3.f), null != t3.i && t3.hasOwnProperty("i") && ("number" == typeof t3.i ? n2.i = e2.longs === String ? String(t3.i) : t3.i : n2.i = e2.longs === String ? c.Long.prototype.toString.call(t3.i) : e2.longs === Number ? new c.LongBits(t3.i.low >>> 0, t3.i.high >>> 0).toNumber() : t3.i), null != t3.s && t3.hasOwnProperty("s") && (n2.s = e2.bytes === String ? c.base64.encode(t3.s, 0, t3.s.length) : e2.bytes === Array ? Array.prototype.slice.call(t3.s) : t3.s), null != t3.t && t3.hasOwnProperty("t") && (n2.t = l.onnx.TensorProto.toObject(t3.t, e2)), null != t3.g && t3.hasOwnProperty("g") && (n2.g = l.onnx.GraphProto.toObject(t3.g, e2)), t3.floats && t3.floats.length) {
n2.floats = [];
for (var i2 = 0; i2 < t3.floats.length; ++i2)
n2.floats[i2] = e2.json && !isFinite(t3.floats[i2]) ? String(t3.floats[i2]) : t3.floats[i2];
}
if (t3.ints && t3.ints.length)
for (n2.ints = [], i2 = 0; i2 < t3.ints.length; ++i2)
"number" == typeof t3.ints[i2] ? n2.ints[i2] = e2.longs === String ? String(t3.ints[i2]) : t3.ints[i2] : n2.ints[i2] = e2.longs === String ? c.Long.prototype.toString.call(t3.ints[i2]) : e2.longs === Number ? new c.LongBits(t3.ints[i2].low >>> 0, t3.ints[i2].high >>> 0).toNumber() : t3.ints[i2];
if (t3.strings && t3.strings.length)
for (n2.strings = [], i2 = 0; i2 < t3.strings.length; ++i2)
n2.strings[i2] = e2.bytes === String ? c.base64.encode(t3.strings[i2], 0, t3.strings[i2].length) : e2.bytes === Array ? Array.prototype.slice.call(t3.strings[i2]) : t3.strings[i2];
if (t3.tensors && t3.tensors.length)
for (n2.tensors = [], i2 = 0; i2 < t3.tensors.length; ++i2)
n2.tensors[i2] = l.onnx.TensorProto.toObject(t3.tensors[i2], e2);
if (t3.graphs && t3.graphs.length)
for (n2.graphs = [], i2 = 0; i2 < t3.graphs.length; ++i2)
n2.graphs[i2] = l.onnx.GraphProto.toObject(t3.graphs[i2], e2);
return null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.type && t3.hasOwnProperty("type") && (n2.type = e2.enums === String ? l.onnx.AttributeProto.AttributeType[t3.type] : t3.type), null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && (n2.refAttrName = t3.refAttrName), n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2.AttributeType = function() {
var t3 = {}, e2 = Object.create(t3);
return e2[t3[0] = "UNDEFINED"] = 0, e2[t3[1] = "FLOAT"] = 1, e2[t3[2] = "INT"] = 2, e2[t3[3] = "STRING"] = 3, e2[t3[4] = "TENSOR"] = 4, e2[t3[5] = "GRAPH"] = 5, e2[t3[6] = "FLOATS"] = 6, e2[t3[7] = "INTS"] = 7, e2[t3[8] = "STRINGS"] = 8, e2[t3[9] = "TENSORS"] = 9, e2[t3[10] = "GRAPHS"] = 10, e2;
}(), t2;
}(), o.ValueInfoProto = function() {
function t2(t3) {
if (t3)
for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2)
null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
}
return t2.prototype.name = "", t2.prototype.type = null, t2.prototype.docString = "", t2.create = function(e2) {
return new t2(e2);
}, t2.encode = function(t3, e2) {
return e2 || (e2 = u.create()), null != t3.name && t3.hasOwnProperty("name") && e2.uint32(10).string(t3.name), null != t3.type && t3.hasOwnProperty("type") && l.onnx.TypeProto.encode(t3.type, e2.uint32(18).fork()).ldelim(), null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(26).string(t3.docString), e2;
}, t2.encodeDelimited = function(t3, e2) {
return this.encode(t3, e2).ldelim();
}, t2.decode = function(t3, e2) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.ValueInfoProto(); t3.pos < n2; ) {
var i2 = t3.uint32();
switch (i2 >>> 3) {
case 1:
r2.name = t3.string();
break;
case 2:
r2.type = l.onnx.TypeProto.decode(t3, t3.uint32());
break;
case 3:
r2.docString = t3.string();
break;
default:
t3.skipType(7 & i2);
}
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
if ("object" != typeof t3 || null === t3)
return "object expected";
if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name))
return "name: string expected";
if (null != t3.type && t3.hasOwnProperty("type")) {
var e2 = l.onnx.TypeProto.verify(t3.type);
if (e2)
return "type." + e2;
}
return null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString) ? "docString: string expected" : null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.ValueInfoProto)
return t3;
var e2 = new l.onnx.ValueInfoProto();
if (null != t3.name && (e2.name = String(t3.name)), null != t3.type) {
if ("object" != typeof t3.type)
throw TypeError(".onnx.ValueInfoProto.type: object expected");
e2.type = l.onnx.TypeProto.fromObject(t3.type);
}
return null != t3.docString && (e2.docString = String(t3.docString)), e2;
}, t2.toObject = function(t3, e2) {
e2 || (e2 = {});
var n2 = {};
return e2.defaults && (n2.name = "", n2.type = null, n2.docString = ""), null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.type && t3.hasOwnProperty("type") && (n2.type = l.onnx.TypeProto.toObject(t3.type, e2)), null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2;
}(), o.NodeProto = function() {
function t2(t3) {
if (this.input = [], this.output = [], this.attribute = [], t3)
for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2)
null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
}
return t2.prototype.input = c.emptyArray, t2.prototype.output = c.emptyArray, t2.prototype.name = "", t2.prototype.opType = "", t2.prototype.domain = "", t2.prototype.attribute = c.emptyArray, t2.prototype.docString = "", t2.create = function(e2) {
return new t2(e2);
}, t2.encode = function(t3, e2) {
if (e2 || (e2 = u.create()), null != t3.input && t3.input.length)
for (var n2 = 0; n2 < t3.input.length; ++n2)
e2.uint32(10).string(t3.input[n2]);
if (null != t3.output && t3.output.length)
for (n2 = 0; n2 < t3.output.length; ++n2)
e2.uint32(18).string(t3.output[n2]);
if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(26).string(t3.name), null != t3.opType && t3.hasOwnProperty("opType") && e2.uint32(34).string(t3.opType), null != t3.attribute && t3.attribute.length)
for (n2 = 0; n2 < t3.attribute.length; ++n2)
l.onnx.AttributeProto.encode(t3.attribute[n2], e2.uint32(42).fork()).ldelim();
return null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(50).string(t3.docString), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(58).string(t3.domain), e2;
}, t2.encodeDelimited = function(t3, e2) {
return this.encode(t3, e2).ldelim();
}, t2.decode = function(t3, e2) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.NodeProto(); t3.pos < n2; ) {
var i2 = t3.uint32();
switch (i2 >>> 3) {
case 1:
r2.input && r2.input.length || (r2.input = []), r2.input.push(t3.string());
break;
case 2:
r2.output && r2.output.length || (r2.output = []), r2.output.push(t3.string());
break;
case 3:
r2.name = t3.string();
break;
case 4:
r2.opType = t3.string();
break;
case 7:
r2.domain = t3.string();
break;
case 5:
r2.attribute && r2.attribute.length || (r2.attribute = []), r2.attribute.push(l.onnx.AttributeProto.decode(t3, t3.uint32()));
break;
case 6:
r2.docString = t3.string();
break;
default:
t3.skipType(7 & i2);
}
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
if ("object" != typeof t3 || null === t3)
return "object expected";
if (null != t3.input && t3.hasOwnProperty("input")) {
if (!Array.isArray(t3.input))
return "input: array expected";
for (var e2 = 0; e2 < t3.input.length; ++e2)
if (!c.isString(t3.input[e2]))
return "input: string[] expected";
}
if (null != t3.output && t3.hasOwnProperty("output")) {
if (!Array.isArray(t3.output))
return "output: array expected";
for (e2 = 0; e2 < t3.output.length; ++e2)
if (!c.isString(t3.output[e2]))
return "output: string[] expected";
}
if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name))
return "name: string expected";
if (null != t3.opType && t3.hasOwnProperty("opType") && !c.isString(t3.opType))
return "opType: string expected";
if (null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain))
return "domain: string expected";
if (null != t3.attribute && t3.hasOwnProperty("attribute")) {
if (!Array.isArray(t3.attribute))
return "attribute: array expected";
for (e2 = 0; e2 < t3.attribute.length; ++e2) {
var n2 = l.onnx.AttributeProto.verify(t3.attribute[e2]);
if (n2)
return "attribute." + n2;
}
}
return null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString) ? "docString: string expected" : null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.NodeProto)
return t3;
var e2 = new l.onnx.NodeProto();
if (t3.input) {
if (!Array.isArray(t3.input))
throw TypeError(".onnx.NodeProto.input: array expected");
e2.input = [];
for (var n2 = 0; n2 < t3.input.length; ++n2)
e2.input[n2] = String(t3.input[n2]);
}
if (t3.output) {
if (!Array.isArray(t3.output))
throw TypeError(".onnx.NodeProto.output: array expected");
for (e2.output = [], n2 = 0; n2 < t3.output.length; ++n2)
e2.output[n2] = String(t3.output[n2]);
}
if (null != t3.name && (e2.name = String(t3.name)), null != t3.opType && (e2.opType = String(t3.opType)), null != t3.domain && (e2.domain = String(t3.domain)), t3.attribute) {
if (!Array.isArray(t3.attribute))
throw TypeError(".onnx.NodeProto.attribute: array expected");
for (e2.attribute = [], n2 = 0; n2 < t3.attribute.length; ++n2) {
if ("object" != typeof t3.attribute[n2])
throw TypeError(".onnx.NodeProto.attribute: object expected");
e2.attribute[n2] = l.onnx.AttributeProto.fromObject(t3.attribute[n2]);
}
}
return null != t3.docString && (e2.docString = String(t3.docString)), e2;
}, t2.toObject = function(t3, e2) {
e2 || (e2 = {});
var n2 = {};
if ((e2.arrays || e2.defaults) && (n2.input = [], n2.output = [], n2.attribute = []), e2.defaults && (n2.name = "", n2.opType = "", n2.docString = "", n2.domain = ""), t3.input && t3.input.length) {
n2.input = [];
for (var r2 = 0; r2 < t3.input.length; ++r2)
n2.input[r2] = t3.input[r2];
}
if (t3.output && t3.output.length)
for (n2.output = [], r2 = 0; r2 < t3.output.length; ++r2)
n2.output[r2] = t3.output[r2];
if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.opType && t3.hasOwnProperty("opType") && (n2.opType = t3.opType), t3.attribute && t3.attribute.length)
for (n2.attribute = [], r2 = 0; r2 < t3.attribute.length; ++r2)
n2.attribute[r2] = l.onnx.AttributeProto.toObject(t3.attribute[r2], e2);
return null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2;
}(), o.ModelProto = function() {
function t2(t3) {
if (this.opsetImport = [], this.metadataProps = [], t3)
for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2)
null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
}
return t2.prototype.irVersion = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.opsetImport = c.emptyArray, t2.prototype.producerName = "", t2.prototype.producerVersion = "", t2.prototype.domain = "", t2.prototype.modelVersion = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.docString = "", t2.prototype.graph = null, t2.prototype.metadataProps = c.emptyArray, t2.create = function(e2) {
return new t2(e2);
}, t2.encode = function(t3, e2) {
if (e2 || (e2 = u.create()), null != t3.irVersion && t3.hasOwnProperty("irVersion") && e2.uint32(8).int64(t3.irVersion), null != t3.producerName && t3.hasOwnProperty("producerName") && e2.uint32(18).string(t3.producerName), null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && e2.uint32(26).string(t3.producerVersion), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(34).string(t3.domain), null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && e2.uint32(40).int64(t3.modelVersion), null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(50).string(t3.docString), null != t3.graph && t3.hasOwnProperty("graph") && l.onnx.GraphProto.encode(t3.graph, e2.uint32(58).fork()).ldelim(), null != t3.opsetImport && t3.opsetImport.length)
for (var n2 = 0; n2 < t3.opsetImport.length; ++n2)
l.onnx.OperatorSetIdProto.encode(t3.opsetImport[n2], e2.uint32(66).fork()).ldelim();
if (null != t3.metadataProps && t3.metadataProps.length)
for (n2 = 0; n2 < t3.metadataProps.length; ++n2)
l.onnx.StringStringEntryProto.encode(t3.metadataProps[n2], e2.uint32(114).fork()).ldelim();
return e2;
}, t2.encodeDelimited = function(t3, e2) {
return this.encode(t3, e2).ldelim();
}, t2.decode = function(t3, e2) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.ModelProto(); t3.pos < n2; ) {
var i2 = t3.uint32();
switch (i2 >>> 3) {
case 1:
r2.irVersion = t3.int64();
break;
case 8:
r2.opsetImport && r2.opsetImport.length || (r2.opsetImport = []), r2.opsetImport.push(l.onnx.OperatorSetIdProto.decode(t3, t3.uint32()));
break;
case 2:
r2.producerName = t3.string();
break;
case 3:
r2.producerVersion = t3.string();
break;
case 4:
r2.domain = t3.string();
break;
case 5:
r2.modelVersion = t3.int64();
break;
case 6:
r2.docString = t3.string();
break;
case 7:
r2.graph = l.onnx.GraphProto.decode(t3, t3.uint32());
break;
case 14:
r2.metadataProps && r2.metadataProps.length || (r2.metadataProps = []), r2.metadataProps.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32()));
break;
default:
t3.skipType(7 & i2);
}
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
if ("object" != typeof t3 || null === t3)
return "object expected";
if (null != t3.irVersion && t3.hasOwnProperty("irVersion") && !(c.isInteger(t3.irVersion) || t3.irVersion && c.isInteger(t3.irVersion.low) && c.isInteger(t3.irVersion.high)))
return "irVersion: integer|Long expected";
if (null != t3.opsetImport && t3.hasOwnProperty("opsetImport")) {
if (!Array.isArray(t3.opsetImport))
return "opsetImport: array expected";
for (var e2 = 0; e2 < t3.opsetImport.length; ++e2)
if (n2 = l.onnx.OperatorSetIdProto.verify(t3.opsetImport[e2]))
return "opsetImport." + n2;
}
if (null != t3.producerName && t3.hasOwnProperty("producerName") && !c.isString(t3.producerName))
return "producerName: string expected";
if (null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && !c.isString(t3.producerVersion))
return "producerVersion: string expected";
if (null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain))
return "domain: string expected";
if (null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && !(c.isInteger(t3.modelVersion) || t3.modelVersion && c.isInteger(t3.modelVersion.low) && c.isInteger(t3.modelVersion.high)))
return "modelVersion: integer|Long expected";
if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString))
return "docString: string expected";
if (null != t3.graph && t3.hasOwnProperty("graph") && (n2 = l.onnx.GraphProto.verify(t3.graph)))
return "graph." + n2;
if (null != t3.metadataProps && t3.hasOwnProperty("metadataProps")) {
if (!Array.isArray(t3.metadataProps))
return "metadataProps: array expected";
for (e2 = 0; e2 < t3.metadataProps.length; ++e2) {
var n2;
if (n2 = l.onnx.StringStringEntryProto.verify(t3.metadataProps[e2]))
return "metadataProps." + n2;
}
}
return null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.ModelProto)
return t3;
var e2 = new l.onnx.ModelProto();
if (null != t3.irVersion && (c.Long ? (e2.irVersion = c.Long.fromValue(t3.irVersion)).unsigned = false : "string" == typeof t3.irVersion ? e2.irVersion = parseInt(t3.irVersion, 10) : "number" == typeof t3.irVersion ? e2.irVersion = t3.irVersion : "object" == typeof t3.irVersion && (e2.irVersion = new c.LongBits(t3.irVersion.low >>> 0, t3.irVersion.high >>> 0).toNumber())), t3.opsetImport) {
if (!Array.isArray(t3.opsetImport))
throw TypeError(".onnx.ModelProto.opsetImport: array expected");
e2.opsetImport = [];
for (var n2 = 0; n2 < t3.opsetImport.length; ++n2) {
if ("object" != typeof t3.opsetImport[n2])
throw TypeError(".onnx.ModelProto.opsetImport: object expected");
e2.opsetImport[n2] = l.onnx.OperatorSetIdProto.fromObject(t3.opsetImport[n2]);
}
}
if (null != t3.producerName && (e2.producerName = String(t3.producerName)), null != t3.producerVersion && (e2.producerVersion = String(t3.producerVersion)), null != t3.domain && (e2.domain = String(t3.domain)), null != t3.modelVersion && (c.Long ? (e2.modelVersion = c.Long.fromValue(t3.modelVersion)).unsigned = false : "string" == typeof t3.modelVersion ? e2.modelVersion = parseInt(t3.modelVersion, 10) : "number" == typeof t3.modelVersion ? e2.modelVersion = t3.modelVersion : "object" == typeof t3.modelVersion && (e2.modelVersion = new c.LongBits(t3.modelVersion.low >>> 0, t3.modelVersion.high >>> 0).toNumber())), null != t3.docString && (e2.docString = String(t3.docString)), null != t3.graph) {
if ("object" != typeof t3.graph)
throw TypeError(".onnx.ModelProto.graph: object expected");
e2.graph = l.onnx.GraphProto.fromObject(t3.graph);
}
if (t3.metadataProps) {
if (!Array.isArray(t3.metadataProps))
throw TypeError(".onnx.ModelProto.metadataProps: array expected");
for (e2.metadataProps = [], n2 = 0; n2 < t3.metadataProps.length; ++n2) {
if ("object" != typeof t3.metadataProps[n2])
throw TypeError(".onnx.ModelProto.metadataProps: object expected");
e2.metadataProps[n2] = l.onnx.StringStringEntryProto.fromObject(t3.metadataProps[n2]);
}
}
return e2;
}, t2.toObject = function(t3, e2) {
e2 || (e2 = {});
var n2 = {};
if ((e2.arrays || e2.defaults) && (n2.opsetImport = [], n2.metadataProps = []), e2.defaults) {
if (c.Long) {
var r2 = new c.Long(0, 0, false);
n2.irVersion = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2;
} else
n2.irVersion = e2.longs === String ? "0" : 0;
n2.producerName = "", n2.producerVersion = "", n2.domain = "", c.Long ? (r2 = new c.Long(0, 0, false), n2.modelVersion = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2) : n2.modelVersion = e2.longs === String ? "0" : 0, n2.docString = "", n2.graph = null;
}
if (null != t3.irVersion && t3.hasOwnProperty("irVersion") && ("number" == typeof t3.irVersion ? n2.irVersion = e2.longs === String ? String(t3.irVersion) : t3.irVersion : n2.irVersion = e2.longs === String ? c.Long.prototype.toString.call(t3.irVersion) : e2.longs === Number ? new c.LongBits(t3.irVersion.low >>> 0, t3.irVersion.high >>> 0).toNumber() : t3.irVersion), null != t3.producerName && t3.hasOwnProperty("producerName") && (n2.producerName = t3.producerName), null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && (n2.producerVersion = t3.producerVersion), null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && ("number" == typeof t3.modelVersion ? n2.modelVersion = e2.longs === String ? String(t3.modelVersion) : t3.modelVersion : n2.modelVersion = e2.longs === String ? c.Long.prototype.toString.call(t3.modelVersion) : e2.longs === Number ? new c.LongBits(t3.modelVersion.low >>> 0, t3.modelVersion.high >>> 0).toNumber() : t3.modelVersion), null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.graph && t3.hasOwnProperty("graph") && (n2.graph = l.onnx.GraphProto.toObject(t3.graph, e2)), t3.opsetImport && t3.opsetImport.length) {
n2.opsetImport = [];
for (var i2 = 0; i2 < t3.opsetImport.length; ++i2)
n2.opsetImport[i2] = l.onnx.OperatorSetIdProto.toObject(t3.opsetImport[i2], e2);
}
if (t3.metadataProps && t3.metadataProps.length)
for (n2.metadataProps = [], i2 = 0; i2 < t3.metadataProps.length; ++i2)
n2.metadataProps[i2] = l.onnx.StringStringEntryProto.toObject(t3.metadataProps[i2], e2);
return n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2;
}(), o.StringStringEntryProto = function() {
function t2(t3) {
if (t3)
for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2)
null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
}
return t2.prototype.key = "", t2.prototype.value = "", t2.create = function(e2) {
return new t2(e2);
}, t2.encode = function(t3, e2) {
return e2 || (e2 = u.create()), null != t3.key && t3.hasOwnProperty("key") && e2.uint32(10).string(t3.key), null != t3.value && t3.hasOwnProperty("value") && e2.uint32(18).string(t3.value), e2;
}, t2.encodeDelimited = function(t3, e2) {
return this.encode(t3, e2).ldelim();
}, t2.decode = function(t3, e2) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.StringStringEntryProto(); t3.pos < n2; ) {
var i2 = t3.uint32();
switch (i2 >>> 3) {
case 1:
r2.key = t3.string();
break;
case 2:
r2.value = t3.string();
break;
default:
t3.skipType(7 & i2);
}
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
return "object" != typeof t3 || null === t3 ? "object expected" : null != t3.key && t3.hasOwnProperty("key") && !c.isString(t3.key) ? "key: string expected" : null != t3.value && t3.hasOwnProperty("value") && !c.isString(t3.value) ? "value: string expected" : null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.StringStringEntryProto)
return t3;
var e2 = new l.onnx.StringStringEntryProto();
return null != t3.key && (e2.key = String(t3.key)), null != t3.value && (e2.value = String(t3.value)), e2;
}, t2.toObject = function(t3, e2) {
e2 || (e2 = {});
var n2 = {};
return e2.defaults && (n2.key = "", n2.value = ""), null != t3.key && t3.hasOwnProperty("key") && (n2.key = t3.key), null != t3.value && t3.hasOwnProperty("value") && (n2.value = t3.value), n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2;
}(), o.TensorAnnotation = function() {
function t2(t3) {
if (this.quantParameterTensorNames = [], t3)
for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2)
null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
}
return t2.prototype.tensorName = "", t2.prototype.quantParameterTensorNames = c.emptyArray, t2.create = function(e2) {
return new t2(e2);
}, t2.encode = function(t3, e2) {
if (e2 || (e2 = u.create()), null != t3.tensorName && t3.hasOwnProperty("tensorName") && e2.uint32(10).string(t3.tensorName), null != t3.quantParameterTensorNames && t3.quantParameterTensorNames.length)
for (var n2 = 0; n2 < t3.quantParameterTensorNames.length; ++n2)
l.onnx.StringStringEntryProto.encode(t3.quantParameterTensorNames[n2], e2.uint32(18).fork()).ldelim();
return e2;
}, t2.encodeDelimited = function(t3, e2) {
return this.encode(t3, e2).ldelim();
}, t2.decode = function(t3, e2) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorAnnotation(); t3.pos < n2; ) {
var i2 = t3.uint32();
switch (i2 >>> 3) {
case 1:
r2.tensorName = t3.string();
break;
case 2:
r2.quantParameterTensorNames && r2.quantParameterTensorNames.length || (r2.quantParameterTensorNames = []), r2.quantParameterTensorNames.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32()));
break;
default:
t3.skipType(7 & i2);
}
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
if ("object" != typeof t3 || null === t3)
return "object expected";
if (null != t3.tensorName && t3.hasOwnProperty("tensorName") && !c.isString(t3.tensorName))
return "tensorName: string expected";
if (null != t3.quantParameterTensorNames && t3.hasOwnProperty("quantParameterTensorNames")) {
if (!Array.isArray(t3.quantParameterTensorNames))
return "quantParameterTensorNames: array expected";
for (var e2 = 0; e2 < t3.quantParameterTensorNames.length; ++e2) {
var n2 = l.onnx.StringStringEntryProto.verify(t3.quantParameterTensorNames[e2]);
if (n2)
return "quantParameterTensorNames." + n2;
}
}
return null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.TensorAnnotation)
return t3;
var e2 = new l.onnx.TensorAnnotation();
if (null != t3.tensorName && (e2.tensorName = String(t3.tensorName)), t3.quantParameterTensorNames) {
if (!Array.isArray(t3.quantParameterTensorNames))
throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");
e2.quantParameterTensorNames = [];
for (var n2 = 0; n2 < t3.quantParameterTensorNames.length; ++n2) {
if ("object" != typeof t3.quantParameterTensorNames[n2])
throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");
e2.quantParameterTensorNames[n2] = l.onnx.StringStringEntryProto.fromObject(t3.quantParameterTensorNames[n2]);
}
}
return e2;
}, t2.toObject = function(t3, e2) {
e2 || (e2 = {});
var n2 = {};
if ((e2.arrays || e2.defaults) && (n2.quantParameterTensorNames = []), e2.defaults && (n2.tensorName = ""), null != t3.tensorName && t3.hasOwnProperty("tensorName") && (n2.tensorName = t3.tensorName), t3.quantParameterTensorNames && t3.quantParameterTensorNames.length) {
n2.quantParameterTensorNames = [];
for (var r2 = 0; r2 < t3.quantParameterTensorNames.length; ++r2)
n2.quantParameterTensorNames[r2] = l.onnx.StringStringEntryProto.toObject(t3.quantParameterTensorNames[r2], e2);
}
return n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2;
}(), o.GraphProto = function() {
function t2(t3) {
if (this.node = [], this.initializer = [], this.input = [], this.output = [], this.valueInfo = [], this.quantizationAnnotation = [], t3)
for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2)
null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
}
return t2.prototype.node = c.emptyArray, t2.prototype.name = "", t2.prototype.initializer = c.emptyArray, t2.prototype.docString = "", t2.prototype.input = c.emptyArray, t2.prototype.output = c.emptyArray, t2.prototype.valueInfo = c.emptyArray, t2.prototype.quantizationAnnotation = c.emptyArray, t2.create = function(e2) {
return new t2(e2);
}, t2.encode = function(t3, e2) {
if (e2 || (e2 = u.create()), null != t3.node && t3.node.length)
for (var n2 = 0; n2 < t3.node.length; ++n2)
l.onnx.NodeProto.encode(t3.node[n2], e2.uint32(10).fork()).ldelim();
if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(18).string(t3.name), null != t3.initializer && t3.initializer.length)
for (n2 = 0; n2 < t3.initializer.length; ++n2)
l.onnx.TensorProto.encode(t3.initializer[n2], e2.uint32(42).fork()).ldelim();
if (null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(82).string(t3.docString), null != t3.input && t3.input.length)
for (n2 = 0; n2 < t3.input.length; ++n2)
l.onnx.ValueInfoProto.encode(t3.input[n2], e2.uint32(90).fork()).ldelim();
if (null != t3.output && t3.output.length)
for (n2 = 0; n2 < t3.output.length; ++n2)
l.onnx.ValueInfoProto.encode(t3.output[n2], e2.uint32(98).fork()).ldelim();
if (null != t3.valueInfo && t3.valueInfo.length)
for (n2 = 0; n2 < t3.valueInfo.length; ++n2)
l.onnx.ValueInfoProto.encode(t3.valueInfo[n2], e2.uint32(106).fork()).ldelim();
if (null != t3.quantizationAnnotation && t3.quantizationAnnotation.length)
for (n2 = 0; n2 < t3.quantizationAnnotation.length; ++n2)
l.onnx.TensorAnnotation.encode(t3.quantizationAnnotation[n2], e2.uint32(114).fork()).ldelim();
return e2;
}, t2.encodeDelimited = function(t3, e2) {
return this.encode(t3, e2).ldelim();
}, t2.decode = function(t3, e2) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.GraphProto(); t3.pos < n2; ) {
var i2 = t3.uint32();
switch (i2 >>> 3) {
case 1:
r2.node && r2.node.length || (r2.node = []), r2.node.push(l.onnx.NodeProto.decode(t3, t3.uint32()));
break;
case 2:
r2.name = t3.string();
break;
case 5:
r2.initializer && r2.initializer.length || (r2.initializer = []), r2.initializer.push(l.onnx.TensorProto.decode(t3, t3.uint32()));
break;
case 10:
r2.docString = t3.string();
break;
case 11:
r2.input && r2.input.length || (r2.input = []), r2.input.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32()));
break;
case 12:
r2.output && r2.output.length || (r2.output = []), r2.output.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32()));
break;
case 13:
r2.valueInfo && r2.valueInfo.length || (r2.valueInfo = []), r2.valueInfo.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32()));
break;
case 14:
r2.quantizationAnnotation && r2.quantizationAnnotation.length || (r2.quantizationAnnotation = []), r2.quantizationAnnotation.push(l.onnx.TensorAnnotation.decode(t3, t3.uint32()));
break;
default:
t3.skipType(7 & i2);
}
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
if ("object" != typeof t3 || null === t3)
return "object expected";
if (null != t3.node && t3.hasOwnProperty("node")) {
if (!Array.isArray(t3.node))
return "node: array expected";
for (var e2 = 0; e2 < t3.node.length; ++e2)
if (n2 = l.onnx.NodeProto.verify(t3.node[e2]))
return "node." + n2;
}
if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name))
return "name: string expected";
if (null != t3.initializer && t3.hasOwnProperty("initializer")) {
if (!Array.isArray(t3.initializer))
return "initializer: array expected";
for (e2 = 0; e2 < t3.initializer.length; ++e2)
if (n2 = l.onnx.TensorProto.verify(t3.initializer[e2]))
return "initializer." + n2;
}
if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString))
return "docString: string expected";
if (null != t3.input && t3.hasOwnProperty("input")) {
if (!Array.isArray(t3.input))
return "input: array expected";
for (e2 = 0; e2 < t3.input.length; ++e2)
if (n2 = l.onnx.ValueInfoProto.verify(t3.input[e2]))
return "input." + n2;
}
if (null != t3.output && t3.hasOwnProperty("output")) {
if (!Array.isArray(t3.output))
return "output: array expected";
for (e2 = 0; e2 < t3.output.length; ++e2)
if (n2 = l.onnx.ValueInfoProto.verify(t3.output[e2]))
return "output." + n2;
}
if (null != t3.valueInfo && t3.hasOwnProperty("valueInfo")) {
if (!Array.isArray(t3.valueInfo))
return "valueInfo: array expected";
for (e2 = 0; e2 < t3.valueInfo.length; ++e2)
if (n2 = l.onnx.ValueInfoProto.verify(t3.valueInfo[e2]))
return "valueInfo." + n2;
}
if (null != t3.quantizationAnnotation && t3.hasOwnProperty("quantizationAnnotation")) {
if (!Array.isArray(t3.quantizationAnnotation))
return "quantizationAnnotation: array expected";
for (e2 = 0; e2 < t3.quantizationAnnotation.length; ++e2) {
var n2;
if (n2 = l.onnx.TensorAnnotation.verify(t3.quantizationAnnotation[e2]))
return "quantizationAnnotation." + n2;
}
}
return null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.GraphProto)
return t3;
var e2 = new l.onnx.GraphProto();
if (t3.node) {
if (!Array.isArray(t3.node))
throw TypeError(".onnx.GraphProto.node: array expected");
e2.node = [];
for (var n2 = 0; n2 < t3.node.length; ++n2) {
if ("object" != typeof t3.node[n2])
throw TypeError(".onnx.GraphProto.node: object expected");
e2.node[n2] = l.onnx.NodeProto.fromObject(t3.node[n2]);
}
}
if (null != t3.name && (e2.name = String(t3.name)), t3.initializer) {
if (!Array.isArray(t3.initializer))
throw TypeError(".onnx.GraphProto.initializer: array expected");
for (e2.initializer = [], n2 = 0; n2 < t3.initializer.length; ++n2) {
if ("object" != typeof t3.initializer[n2])
throw TypeError(".onnx.GraphProto.initializer: object expected");
e2.initializer[n2] = l.onnx.TensorProto.fromObject(t3.initializer[n2]);
}
}
if (null != t3.docString && (e2.docString = String(t3.docString)), t3.input) {
if (!Array.isArray(t3.input))
throw TypeError(".onnx.GraphProto.input: array expected");
for (e2.input = [], n2 = 0; n2 < t3.input.length; ++n2) {
if ("object" != typeof t3.input[n2])
throw TypeError(".onnx.GraphProto.input: object expected");
e2.input[n2] = l.onnx.ValueInfoProto.fromObject(t3.input[n2]);
}
}
if (t3.output) {
if (!Array.isArray(t3.output))
throw TypeError(".onnx.GraphProto.output: array expected");
for (e2.output = [], n2 = 0; n2 < t3.output.length; ++n2) {
if ("object" != typeof t3.output[n2])
throw TypeError(".onnx.GraphProto.output: object expected");
e2.output[n2] = l.onnx.ValueInfoProto.fromObject(t3.output[n2]);
}
}
if (t3.valueInfo) {
if (!Array.isArray(t3.valueInfo))
throw TypeError(".onnx.GraphProto.valueInfo: array expected");
for (e2.valueInfo = [], n2 = 0; n2 < t3.valueInfo.length; ++n2) {
if ("object" != typeof t3.valueInfo[n2])
throw TypeError(".onnx.GraphProto.valueInfo: object expected");
e2.valueInfo[n2] = l.onnx.ValueInfoProto.fromObject(t3.valueInfo[n2]);
}
}
if (t3.quantizationAnnotation) {
if (!Array.isArray(t3.quantizationAnnotation))
throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");
for (e2.quantizationAnnotation = [], n2 = 0; n2 < t3.quantizationAnnotation.length; ++n2) {
if ("object" != typeof t3.quantizationAnnotation[n2])
throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");
e2.quantizationAnnotation[n2] = l.onnx.TensorAnnotation.fromObject(t3.quantizationAnnotation[n2]);
}
}
return e2;
}, t2.toObject = function(t3, e2) {
e2 || (e2 = {});
var n2 = {};
if ((e2.arrays || e2.defaults) && (n2.node = [], n2.initializer = [], n2.input = [], n2.output = [], n2.valueInfo = [], n2.quantizationAnnotation = []), e2.defaults && (n2.name = "", n2.docString = ""), t3.node && t3.node.length) {
n2.node = [];
for (var r2 = 0; r2 < t3.node.length; ++r2)
n2.node[r2] = l.onnx.NodeProto.toObject(t3.node[r2], e2);
}
if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), t3.initializer && t3.initializer.length)
for (n2.initializer = [], r2 = 0; r2 < t3.initializer.length; ++r2)
n2.initializer[r2] = l.onnx.TensorProto.toObject(t3.initializer[r2], e2);
if (null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), t3.input && t3.input.length)
for (n2.input = [], r2 = 0; r2 < t3.input.length; ++r2)
n2.input[r2] = l.onnx.ValueInfoProto.toObject(t3.input[r2], e2);
if (t3.output && t3.output.length)
for (n2.output = [], r2 = 0; r2 < t3.output.length; ++r2)
n2.output[r2] = l.onnx.ValueInfoProto.toObject(t3.output[r2], e2);
if (t3.valueInfo && t3.valueInfo.length)
for (n2.valueInfo = [], r2 = 0; r2 < t3.valueInfo.length; ++r2)
n2.valueInfo[r2] = l.onnx.ValueInfoProto.toObject(t3.valueInfo[r2], e2);
if (t3.quantizationAnnotation && t3.quantizationAnnotation.length)
for (n2.quantizationAnnotation = [], r2 = 0; r2 < t3.quantizationAnnotation.length; ++r2)
n2.quantizationAnnotation[r2] = l.onnx.TensorAnnotation.toObject(t3.quantizationAnnotation[r2], e2);
return n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2;
}(), o.TensorProto = function() {
function t2(t3) {
if (this.dims = [], this.floatData = [], this.int32Data = [], this.stringData = [], this.int64Data = [], this.externalData = [], this.doubleData = [], this.uint64Data = [], t3)
for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2)
null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
}
return t2.prototype.dims = c.emptyArray, t2.prototype.dataType = 0, t2.prototype.segment = null, t2.prototype.floatData = c.emptyArray, t2.prototype.int32Data = c.emptyArray, t2.prototype.stringData = c.emptyArray, t2.prototype.int64Data = c.emptyArray, t2.prototype.name = "", t2.prototype.docString = "", t2.prototype.rawData = c.newBuffer([]), t2.prototype.externalData = c.emptyArray, t2.prototype.dataLocation = 0, t2.prototype.doubleData = c.emptyArray, t2.prototype.uint64Data = c.emptyArray, t2.create = function(e2) {
return new t2(e2);
}, t2.encode = function(t3, e2) {
if (e2 || (e2 = u.create()), null != t3.dims && t3.dims.length) {
e2.uint32(10).fork();
for (var n2 = 0; n2 < t3.dims.length; ++n2)
e2.int64(t3.dims[n2]);
e2.ldelim();
}
if (null != t3.dataType && t3.hasOwnProperty("dataType") && e2.uint32(16).int32(t3.dataType), null != t3.segment && t3.hasOwnProperty("segment") && l.onnx.TensorProto.Segment.encode(t3.segment, e2.uint32(26).fork()).ldelim(), null != t3.floatData && t3.floatData.length) {
for (e2.uint32(34).fork(), n2 = 0; n2 < t3.floatData.length; ++n2)
e2.float(t3.floatData[n2]);
e2.ldelim();
}
if (null != t3.int32Data && t3.int32Data.length) {
for (e2.uint32(42).fork(), n2 = 0; n2 < t3.int32Data.length; ++n2)
e2.int32(t3.int32Data[n2]);
e2.ldelim();
}
if (null != t3.stringData && t3.stringData.length)
for (n2 = 0; n2 < t3.stringData.length; ++n2)
e2.uint32(50).bytes(t3.stringData[n2]);
if (null != t3.int64Data && t3.int64Data.length) {
for (e2.uint32(58).fork(), n2 = 0; n2 < t3.int64Data.length; ++n2)
e2.int64(t3.int64Data[n2]);
e2.ldelim();
}
if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(66).string(t3.name), null != t3.rawData && t3.hasOwnProperty("rawData") && e2.uint32(74).bytes(t3.rawData), null != t3.doubleData && t3.doubleData.length) {
for (e2.uint32(82).fork(), n2 = 0; n2 < t3.doubleData.length; ++n2)
e2.double(t3.doubleData[n2]);
e2.ldelim();
}
if (null != t3.uint64Data && t3.uint64Data.length) {
for (e2.uint32(90).fork(), n2 = 0; n2 < t3.uint64Data.length; ++n2)
e2.uint64(t3.uint64Data[n2]);
e2.ldelim();
}
if (null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(98).string(t3.docString), null != t3.externalData && t3.externalData.length)
for (n2 = 0; n2 < t3.externalData.length; ++n2)
l.onnx.StringStringEntryProto.encode(t3.externalData[n2], e2.uint32(106).fork()).ldelim();
return null != t3.dataLocation && t3.hasOwnProperty("dataLocation") && e2.uint32(112).int32(t3.dataLocation), e2;
}, t2.encodeDelimited = function(t3, e2) {
return this.encode(t3, e2).ldelim();
}, t2.decode = function(t3, e2) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorProto(); t3.pos < n2; ) {
var i2 = t3.uint32();
switch (i2 >>> 3) {
case 1:
if (r2.dims && r2.dims.length || (r2.dims = []), 2 == (7 & i2))
for (var o2 = t3.uint32() + t3.pos; t3.pos < o2; )
r2.dims.push(t3.int64());
else
r2.dims.push(t3.int64());
break;
case 2:
r2.dataType = t3.int32();
break;
case 3:
r2.segment = l.onnx.TensorProto.Segment.decode(t3, t3.uint32());
break;
case 4:
if (r2.floatData && r2.floatData.length || (r2.floatData = []), 2 == (7 & i2))
for (o2 = t3.uint32() + t3.pos; t3.pos < o2; )
r2.floatData.push(t3.float());
else
r2.floatData.push(t3.float());
break;
case 5:
if (r2.int32Data && r2.int32Data.length || (r2.int32Data = []), 2 == (7 & i2))
for (o2 = t3.uint32() + t3.pos; t3.pos < o2; )
r2.int32Data.push(t3.int32());
else
r2.int32Data.push(t3.int32());
break;
case 6:
r2.stringData && r2.stringData.length || (r2.stringData = []), r2.stringData.push(t3.bytes());
break;
case 7:
if (r2.int64Data && r2.int64Data.length || (r2.int64Data = []), 2 == (7 & i2))
for (o2 = t3.uint32() + t3.pos; t3.pos < o2; )
r2.int64Data.push(t3.int64());
else
r2.int64Data.push(t3.int64());
break;
case 8:
r2.name = t3.string();
break;
case 12:
r2.docString = t3.string();
break;
case 9:
r2.rawData = t3.bytes();
break;
case 13:
r2.externalData && r2.externalData.length || (r2.externalData = []), r2.externalData.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32()));
break;
case 14:
r2.dataLocation = t3.int32();
break;
case 10:
if (r2.doubleData && r2.doubleData.length || (r2.doubleData = []), 2 == (7 & i2))
for (o2 = t3.uint32() + t3.pos; t3.pos < o2; )
r2.doubleData.push(t3.double());
else
r2.doubleData.push(t3.double());
break;
case 11:
if (r2.uint64Data && r2.uint64Data.length || (r2.uint64Data = []), 2 == (7 & i2))
for (o2 = t3.uint32() + t3.pos; t3.pos < o2; )
r2.uint64Data.push(t3.uint64());
else
r2.uint64Data.push(t3.uint64());
break;
default:
t3.skipType(7 & i2);
}
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
if ("object" != typeof t3 || null === t3)
return "object expected";
if (null != t3.dims && t3.hasOwnProperty("dims")) {
if (!Array.isArray(t3.dims))
return "dims: array expected";
for (var e2 = 0; e2 < t3.dims.length; ++e2)
if (!(c.isInteger(t3.dims[e2]) || t3.dims[e2] && c.isInteger(t3.dims[e2].low) && c.isInteger(t3.dims[e2].high)))
return "dims: integer|Long[] expected";
}
if (null != t3.dataType && t3.hasOwnProperty("dataType") && !c.isInteger(t3.dataType))
return "dataType: integer expected";
if (null != t3.segment && t3.hasOwnProperty("segment") && (n2 = l.onnx.TensorProto.Segment.verify(t3.segment)))
return "segment." + n2;
if (null != t3.floatData && t3.hasOwnProperty("floatData")) {
if (!Array.isArray(t3.floatData))
return "floatData: array expected";
for (e2 = 0; e2 < t3.floatData.length; ++e2)
if ("number" != typeof t3.floatData[e2])
return "floatData: number[] expected";
}
if (null != t3.int32Data && t3.hasOwnProperty("int32Data")) {
if (!Array.isArray(t3.int32Data))
return "int32Data: array expected";
for (e2 = 0; e2 < t3.int32Data.length; ++e2)
if (!c.isInteger(t3.int32Data[e2]))
return "int32Data: integer[] expected";
}
if (null != t3.stringData && t3.hasOwnProperty("stringData")) {
if (!Array.isArray(t3.stringData))
return "stringData: array expected";
for (e2 = 0; e2 < t3.stringData.length; ++e2)
if (!(t3.stringData[e2] && "number" == typeof t3.stringData[e2].length || c.isString(t3.stringData[e2])))
return "stringData: buffer[] expected";
}
if (null != t3.int64Data && t3.hasOwnProperty("int64Data")) {
if (!Array.isArray(t3.int64Data))
return "int64Data: array expected";
for (e2 = 0; e2 < t3.int64Data.length; ++e2)
if (!(c.isInteger(t3.int64Data[e2]) || t3.int64Data[e2] && c.isInteger(t3.int64Data[e2].low) && c.isInteger(t3.int64Data[e2].high)))
return "int64Data: integer|Long[] expected";
}
if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name))
return "name: string expected";
if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString))
return "docString: string expected";
if (null != t3.rawData && t3.hasOwnProperty("rawData") && !(t3.rawData && "number" == typeof t3.rawData.length || c.isString(t3.rawData)))
return "rawData: buffer expected";
if (null != t3.externalData && t3.hasOwnProperty("externalData")) {
if (!Array.isArray(t3.externalData))
return "externalData: array expected";
for (e2 = 0; e2 < t3.externalData.length; ++e2) {
var n2;
if (n2 = l.onnx.StringStringEntryProto.verify(t3.externalData[e2]))
return "externalData." + n2;
}
}
if (null != t3.dataLocation && t3.hasOwnProperty("dataLocation"))
switch (t3.dataLocation) {
default:
return "dataLocation: enum value expected";
case 0:
case 1:
}
if (null != t3.doubleData && t3.hasOwnProperty("doubleData")) {
if (!Array.isArray(t3.doubleData))
return "doubleData: array expected";
for (e2 = 0; e2 < t3.doubleData.length; ++e2)
if ("number" != typeof t3.doubleData[e2])
return "doubleData: number[] expected";
}
if (null != t3.uint64Data && t3.hasOwnProperty("uint64Data")) {
if (!Array.isArray(t3.uint64Data))
return "uint64Data: array expected";
for (e2 = 0; e2 < t3.uint64Data.length; ++e2)
if (!(c.isInteger(t3.uint64Data[e2]) || t3.uint64Data[e2] && c.isInteger(t3.uint64Data[e2].low) && c.isInteger(t3.uint64Data[e2].high)))
return "uint64Data: integer|Long[] expected";
}
return null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.TensorProto)
return t3;
var e2 = new l.onnx.TensorProto();
if (t3.dims) {
if (!Array.isArray(t3.dims))
throw TypeError(".onnx.TensorProto.dims: array expected");
e2.dims = [];
for (var n2 = 0; n2 < t3.dims.length; ++n2)
c.Long ? (e2.dims[n2] = c.Long.fromValue(t3.dims[n2])).unsigned = false : "string" == typeof t3.dims[n2] ? e2.dims[n2] = parseInt(t3.dims[n2], 10) : "number" == typeof t3.dims[n2] ? e2.dims[n2] = t3.dims[n2] : "object" == typeof t3.dims[n2] && (e2.dims[n2] = new c.LongBits(t3.dims[n2].low >>> 0, t3.dims[n2].high >>> 0).toNumber());
}
if (null != t3.dataType && (e2.dataType = 0 | t3.dataType), null != t3.segment) {
if ("object" != typeof t3.segment)
throw TypeError(".onnx.TensorProto.segment: object expected");
e2.segment = l.onnx.TensorProto.Segment.fromObject(t3.segment);
}
if (t3.floatData) {
if (!Array.isArray(t3.floatData))
throw TypeError(".onnx.TensorProto.floatData: array expected");
for (e2.floatData = [], n2 = 0; n2 < t3.floatData.length; ++n2)
e2.floatData[n2] = Number(t3.floatData[n2]);
}
if (t3.int32Data) {
if (!Array.isArray(t3.int32Data))
throw TypeError(".onnx.TensorProto.int32Data: array expected");
for (e2.int32Data = [], n2 = 0; n2 < t3.int32Data.length; ++n2)
e2.int32Data[n2] = 0 | t3.int32Data[n2];
}
if (t3.stringData) {
if (!Array.isArray(t3.stringData))
throw TypeError(".onnx.TensorProto.stringData: array expected");
for (e2.stringData = [], n2 = 0; n2 < t3.stringData.length; ++n2)
"string" == typeof t3.stringData[n2] ? c.base64.decode(t3.stringData[n2], e2.stringData[n2] = c.newBuffer(c.base64.length(t3.stringData[n2])), 0) : t3.stringData[n2].length && (e2.stringData[n2] = t3.stringData[n2]);
}
if (t3.int64Data) {
if (!Array.isArray(t3.int64Data))
throw TypeError(".onnx.TensorProto.int64Data: array expected");
for (e2.int64Data = [], n2 = 0; n2 < t3.int64Data.length; ++n2)
c.Long ? (e2.int64Data[n2] = c.Long.fromValue(t3.int64Data[n2])).unsigned = false : "string" == typeof t3.int64Data[n2] ? e2.int64Data[n2] = parseInt(t3.int64Data[n2], 10) : "number" == typeof t3.int64Data[n2] ? e2.int64Data[n2] = t3.int64Data[n2] : "object" == typeof t3.int64Data[n2] && (e2.int64Data[n2] = new c.LongBits(t3.int64Data[n2].low >>> 0, t3.int64Data[n2].high >>> 0).toNumber());
}
if (null != t3.name && (e2.name = String(t3.name)), null != t3.docString && (e2.docString = String(t3.docString)), null != t3.rawData && ("string" == typeof t3.rawData ? c.base64.decode(t3.rawData, e2.rawData = c.newBuffer(c.base64.length(t3.rawData)), 0) : t3.rawData.length && (e2.rawData = t3.rawData)), t3.externalData) {
if (!Array.isArray(t3.externalData))
throw TypeError(".onnx.TensorProto.externalData: array expected");
for (e2.externalData = [], n2 = 0; n2 < t3.externalData.length; ++n2) {
if ("object" != typeof t3.externalData[n2])
throw TypeError(".onnx.TensorProto.externalData: object expected");
e2.externalData[n2] = l.onnx.StringStringEntryProto.fromObject(t3.externalData[n2]);
}
}
switch (t3.dataLocation) {
case "DEFAULT":
case 0:
e2.dataLocation = 0;
break;
case "EXTERNAL":
case 1:
e2.dataLocation = 1;
}
if (t3.doubleData) {
if (!Array.isArray(t3.doubleData))
throw TypeError(".onnx.TensorProto.doubleData: array expected");
for (e2.doubleData = [], n2 = 0; n2 < t3.doubleData.length; ++n2)
e2.doubleData[n2] = Number(t3.doubleData[n2]);
}
if (t3.uint64Data) {
if (!Array.isArray(t3.uint64Data))
throw TypeError(".onnx.TensorProto.uint64Data: array expected");
for (e2.uint64Data = [], n2 = 0; n2 < t3.uint64Data.length; ++n2)
c.Long ? (e2.uint64Data[n2] = c.Long.fromValue(t3.uint64Data[n2])).unsigned = true : "string" == typeof t3.uint64Data[n2] ? e2.uint64Data[n2] = parseInt(t3.uint64Data[n2], 10) : "number" == typeof t3.uint64Data[n2] ? e2.uint64Data[n2] = t3.uint64Data[n2] : "object" == typeof t3.uint64Data[n2] && (e2.uint64Data[n2] = new c.LongBits(t3.uint64Data[n2].low >>> 0, t3.uint64Data[n2].high >>> 0).toNumber(true));
}
return e2;
}, t2.toObject = function(t3, e2) {
e2 || (e2 = {});
var n2 = {};
if ((e2.arrays || e2.defaults) && (n2.dims = [], n2.floatData = [], n2.int32Data = [], n2.stringData = [], n2.int64Data = [], n2.doubleData = [], n2.uint64Data = [], n2.externalData = []), e2.defaults && (n2.dataType = 0, n2.segment = null, n2.name = "", e2.bytes === String ? n2.rawData = "" : (n2.rawData = [], e2.bytes !== Array && (n2.rawData = c.newBuffer(n2.rawData))), n2.docString = "", n2.dataLocation = e2.enums === String ? "DEFAULT" : 0), t3.dims && t3.dims.length) {
n2.dims = [];
for (var r2 = 0; r2 < t3.dims.length; ++r2)
"number" == typeof t3.dims[r2] ? n2.dims[r2] = e2.longs === String ? String(t3.dims[r2]) : t3.dims[r2] : n2.dims[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.dims[r2]) : e2.longs === Number ? new c.LongBits(t3.dims[r2].low >>> 0, t3.dims[r2].high >>> 0).toNumber() : t3.dims[r2];
}
if (null != t3.dataType && t3.hasOwnProperty("dataType") && (n2.dataType = t3.dataType), null != t3.segment && t3.hasOwnProperty("segment") && (n2.segment = l.onnx.TensorProto.Segment.toObject(t3.segment, e2)), t3.floatData && t3.floatData.length)
for (n2.floatData = [], r2 = 0; r2 < t3.floatData.length; ++r2)
n2.floatData[r2] = e2.json && !isFinite(t3.floatData[r2]) ? String(t3.floatData[r2]) : t3.floatData[r2];
if (t3.int32Data && t3.int32Data.length)
for (n2.int32Data = [], r2 = 0; r2 < t3.int32Data.length; ++r2)
n2.int32Data[r2] = t3.int32Data[r2];
if (t3.stringData && t3.stringData.length)
for (n2.stringData = [], r2 = 0; r2 < t3.stringData.length; ++r2)
n2.stringData[r2] = e2.bytes === String ? c.base64.encode(t3.stringData[r2], 0, t3.stringData[r2].length) : e2.bytes === Array ? Array.prototype.slice.call(t3.stringData[r2]) : t3.stringData[r2];
if (t3.int64Data && t3.int64Data.length)
for (n2.int64Data = [], r2 = 0; r2 < t3.int64Data.length; ++r2)
"number" == typeof t3.int64Data[r2] ? n2.int64Data[r2] = e2.longs === String ? String(t3.int64Data[r2]) : t3.int64Data[r2] : n2.int64Data[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.int64Data[r2]) : e2.longs === Number ? new c.LongBits(t3.int64Data[r2].low >>> 0, t3.int64Data[r2].high >>> 0).toNumber() : t3.int64Data[r2];
if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.rawData && t3.hasOwnProperty("rawData") && (n2.rawData = e2.bytes === String ? c.base64.encode(t3.rawData, 0, t3.rawData.length) : e2.bytes === Array ? Array.prototype.slice.call(t3.rawData) : t3.rawData), t3.doubleData && t3.doubleData.length)
for (n2.doubleData = [], r2 = 0; r2 < t3.doubleData.length; ++r2)
n2.doubleData[r2] = e2.json && !isFinite(t3.doubleData[r2]) ? String(t3.doubleData[r2]) : t3.doubleData[r2];
if (t3.uint64Data && t3.uint64Data.length)
for (n2.uint64Data = [], r2 = 0; r2 < t3.uint64Data.length; ++r2)
"number" == typeof t3.uint64Data[r2] ? n2.uint64Data[r2] = e2.longs === String ? String(t3.uint64Data[r2]) : t3.uint64Data[r2] : n2.uint64Data[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.uint64Data[r2]) : e2.longs === Number ? new c.LongBits(t3.uint64Data[r2].low >>> 0, t3.uint64Data[r2].high >>> 0).toNumber(true) : t3.uint64Data[r2];
if (null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), t3.externalData && t3.externalData.length)
for (n2.externalData = [], r2 = 0; r2 < t3.externalData.length; ++r2)
n2.externalData[r2] = l.onnx.StringStringEntryProto.toObject(t3.externalData[r2], e2);
return null != t3.dataLocation && t3.hasOwnProperty("dataLocation") && (n2.dataLocation = e2.enums === String ? l.onnx.TensorProto.DataLocation[t3.dataLocation] : t3.dataLocation), n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2.DataType = function() {
var t3 = {}, e2 = Object.create(t3);
return e2[t3[0] = "UNDEFINED"] = 0, e2[t3[1] = "FLOAT"] = 1, e2[t3[2] = "UINT8"] = 2, e2[t3[3] = "INT8"] = 3, e2[t3[4] = "UINT16"] = 4, e2[t3[5] = "INT16"] = 5, e2[t3[6] = "INT32"] = 6, e2[t3[7] = "INT64"] = 7, e2[t3[8] = "STRING"] = 8, e2[t3[9] = "BOOL"] = 9, e2[t3[10] = "FLOAT16"] = 10, e2[t3[11] = "DOUBLE"] = 11, e2[t3[12] = "UINT32"] = 12, e2[t3[13] = "UINT64"] = 13, e2[t3[14] = "COMPLEX64"] = 14, e2[t3[15] = "COMPLEX128"] = 15, e2[t3[16] = "BFLOAT16"] = 16, e2;
}(), t2.Segment = function() {
function t3(t4) {
if (t4)
for (var e2 = Object.keys(t4), n2 = 0; n2 < e2.length; ++n2)
null != t4[e2[n2]] && (this[e2[n2]] = t4[e2[n2]]);
}
return t3.prototype.begin = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.prototype.end = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.create = function(e2) {
return new t3(e2);
}, t3.encode = function(t4, e2) {
return e2 || (e2 = u.create()), null != t4.begin && t4.hasOwnProperty("begin") && e2.uint32(8).int64(t4.begin), null != t4.end && t4.hasOwnProperty("end") && e2.uint32(16).int64(t4.end), e2;
}, t3.encodeDelimited = function(t4, e2) {
return this.encode(t4, e2).ldelim();
}, t3.decode = function(t4, e2) {
t4 instanceof s || (t4 = s.create(t4));
for (var n2 = void 0 === e2 ? t4.len : t4.pos + e2, r2 = new l.onnx.TensorProto.Segment(); t4.pos < n2; ) {
var i2 = t4.uint32();
switch (i2 >>> 3) {
case 1:
r2.begin = t4.int64();
break;
case 2:
r2.end = t4.int64();
break;
default:
t4.skipType(7 & i2);
}
}
return r2;
}, t3.decodeDelimited = function(t4) {
return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32());
}, t3.verify = function(t4) {
return "object" != typeof t4 || null === t4 ? "object expected" : null != t4.begin && t4.hasOwnProperty("begin") && !(c.isInteger(t4.begin) || t4.begin && c.isInteger(t4.begin.low) && c.isInteger(t4.begin.high)) ? "begin: integer|Long expected" : null != t4.end && t4.hasOwnProperty("end") && !(c.isInteger(t4.end) || t4.end && c.isInteger(t4.end.low) && c.isInteger(t4.end.high)) ? "end: integer|Long expected" : null;
}, t3.fromObject = function(t4) {
if (t4 instanceof l.onnx.TensorProto.Segment)
return t4;
var e2 = new l.onnx.TensorProto.Segment();
return null != t4.begin && (c.Long ? (e2.begin = c.Long.fromValue(t4.begin)).unsigned = false : "string" == typeof t4.begin ? e2.begin = parseInt(t4.begin, 10) : "number" == typeof t4.begin ? e2.begin = t4.begin : "object" == typeof t4.begin && (e2.begin = new c.LongBits(t4.begin.low >>> 0, t4.begin.high >>> 0).toNumber())), null != t4.end && (c.Long ? (e2.end = c.Long.fromValue(t4.end)).unsigned = false : "string" == typeof t4.end ? e2.end = parseInt(t4.end, 10) : "number" == typeof t4.end ? e2.end = t4.end : "object" == typeof t4.end && (e2.end = new c.LongBits(t4.end.low >>> 0, t4.end.high >>> 0).toNumber())), e2;
}, t3.toObject = function(t4, e2) {
e2 || (e2 = {});
var n2 = {};
if (e2.defaults) {
if (c.Long) {
var r2 = new c.Long(0, 0, false);
n2.begin = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2;
} else
n2.begin = e2.longs === String ? "0" : 0;
c.Long ? (r2 = new c.Long(0, 0, false), n2.end = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2) : n2.end = e2.longs === String ? "0" : 0;
}
return null != t4.begin && t4.hasOwnProperty("begin") && ("number" == typeof t4.begin ? n2.begin = e2.longs === String ? String(t4.begin) : t4.begin : n2.begin = e2.longs === String ? c.Long.prototype.toString.call(t4.begin) : e2.longs === Number ? new c.LongBits(t4.begin.low >>> 0, t4.begin.high >>> 0).toNumber() : t4.begin), null != t4.end && t4.hasOwnProperty("end") && ("number" == typeof t4.end ? n2.end = e2.longs === String ? String(t4.end) : t4.end : n2.end = e2.longs === String ? c.Long.prototype.toString.call(t4.end) : e2.longs === Number ? new c.LongBits(t4.end.low >>> 0, t4.end.high >>> 0).toNumber() : t4.end), n2;
}, t3.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t3;
}(), t2.DataLocation = function() {
var t3 = {}, e2 = Object.create(t3);
return e2[t3[0] = "DEFAULT"] = 0, e2[t3[1] = "EXTERNAL"] = 1, e2;
}(), t2;
}(), o.TensorShapeProto = function() {
function t2(t3) {
if (this.dim = [], t3)
for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2)
null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
}
return t2.prototype.dim = c.emptyArray, t2.create = function(e2) {
return new t2(e2);
}, t2.encode = function(t3, e2) {
if (e2 || (e2 = u.create()), null != t3.dim && t3.dim.length)
for (var n2 = 0; n2 < t3.dim.length; ++n2)
l.onnx.TensorShapeProto.Dimension.encode(t3.dim[n2], e2.uint32(10).fork()).ldelim();
return e2;
}, t2.encodeDelimited = function(t3, e2) {
return this.encode(t3, e2).ldelim();
}, t2.decode = function(t3, e2) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorShapeProto(); t3.pos < n2; ) {
var i2 = t3.uint32();
i2 >>> 3 == 1 ? (r2.dim && r2.dim.length || (r2.dim = []), r2.dim.push(l.onnx.TensorShapeProto.Dimension.decode(t3, t3.uint32()))) : t3.skipType(7 & i2);
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
if ("object" != typeof t3 || null === t3)
return "object expected";
if (null != t3.dim && t3.hasOwnProperty("dim")) {
if (!Array.isArray(t3.dim))
return "dim: array expected";
for (var e2 = 0; e2 < t3.dim.length; ++e2) {
var n2 = l.onnx.TensorShapeProto.Dimension.verify(t3.dim[e2]);
if (n2)
return "dim." + n2;
}
}
return null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.TensorShapeProto)
return t3;
var e2 = new l.onnx.TensorShapeProto();
if (t3.dim) {
if (!Array.isArray(t3.dim))
throw TypeError(".onnx.TensorShapeProto.dim: array expected");
e2.dim = [];
for (var n2 = 0; n2 < t3.dim.length; ++n2) {
if ("object" != typeof t3.dim[n2])
throw TypeError(".onnx.TensorShapeProto.dim: object expected");
e2.dim[n2] = l.onnx.TensorShapeProto.Dimension.fromObject(t3.dim[n2]);
}
}
return e2;
}, t2.toObject = function(t3, e2) {
e2 || (e2 = {});
var n2 = {};
if ((e2.arrays || e2.defaults) && (n2.dim = []), t3.dim && t3.dim.length) {
n2.dim = [];
for (var r2 = 0; r2 < t3.dim.length; ++r2)
n2.dim[r2] = l.onnx.TensorShapeProto.Dimension.toObject(t3.dim[r2], e2);
}
return n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2.Dimension = function() {
function t3(t4) {
if (t4)
for (var e3 = Object.keys(t4), n2 = 0; n2 < e3.length; ++n2)
null != t4[e3[n2]] && (this[e3[n2]] = t4[e3[n2]]);
}
var e2;
return t3.prototype.dimValue = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.prototype.dimParam = "", t3.prototype.denotation = "", Object.defineProperty(t3.prototype, "value", { get: c.oneOfGetter(e2 = ["dimValue", "dimParam"]), set: c.oneOfSetter(e2) }), t3.create = function(e3) {
return new t3(e3);
}, t3.encode = function(t4, e3) {
return e3 || (e3 = u.create()), null != t4.dimValue && t4.hasOwnProperty("dimValue") && e3.uint32(8).int64(t4.dimValue), null != t4.dimParam && t4.hasOwnProperty("dimParam") && e3.uint32(18).string(t4.dimParam), null != t4.denotation && t4.hasOwnProperty("denotation") && e3.uint32(26).string(t4.denotation), e3;
}, t3.encodeDelimited = function(t4, e3) {
return this.encode(t4, e3).ldelim();
}, t3.decode = function(t4, e3) {
t4 instanceof s || (t4 = s.create(t4));
for (var n2 = void 0 === e3 ? t4.len : t4.pos + e3, r2 = new l.onnx.TensorShapeProto.Dimension(); t4.pos < n2; ) {
var i2 = t4.uint32();
switch (i2 >>> 3) {
case 1:
r2.dimValue = t4.int64();
break;
case 2:
r2.dimParam = t4.string();
break;
case 3:
r2.denotation = t4.string();
break;
default:
t4.skipType(7 & i2);
}
}
return r2;
}, t3.decodeDelimited = function(t4) {
return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32());
}, t3.verify = function(t4) {
if ("object" != typeof t4 || null === t4)
return "object expected";
var e3 = {};
if (null != t4.dimValue && t4.hasOwnProperty("dimValue") && (e3.value = 1, !(c.isInteger(t4.dimValue) || t4.dimValue && c.isInteger(t4.dimValue.low) && c.isInteger(t4.dimValue.high))))
return "dimValue: integer|Long expected";
if (null != t4.dimParam && t4.hasOwnProperty("dimParam")) {
if (1 === e3.value)
return "value: multiple values";
if (e3.value = 1, !c.isString(t4.dimParam))
return "dimParam: string expected";
}
return null != t4.denotation && t4.hasOwnProperty("denotation") && !c.isString(t4.denotation) ? "denotation: string expected" : null;
}, t3.fromObject = function(t4) {
if (t4 instanceof l.onnx.TensorShapeProto.Dimension)
return t4;
var e3 = new l.onnx.TensorShapeProto.Dimension();
return null != t4.dimValue && (c.Long ? (e3.dimValue = c.Long.fromValue(t4.dimValue)).unsigned = false : "string" == typeof t4.dimValue ? e3.dimValue = parseInt(t4.dimValue, 10) : "number" == typeof t4.dimValue ? e3.dimValue = t4.dimValue : "object" == typeof t4.dimValue && (e3.dimValue = new c.LongBits(t4.dimValue.low >>> 0, t4.dimValue.high >>> 0).toNumber())), null != t4.dimParam && (e3.dimParam = String(t4.dimParam)), null != t4.denotation && (e3.denotation = String(t4.denotation)), e3;
}, t3.toObject = function(t4, e3) {
e3 || (e3 = {});
var n2 = {};
return e3.defaults && (n2.denotation = ""), null != t4.dimValue && t4.hasOwnProperty("dimValue") && ("number" == typeof t4.dimValue ? n2.dimValue = e3.longs === String ? String(t4.dimValue) : t4.dimValue : n2.dimValue = e3.longs === String ? c.Long.prototype.toString.call(t4.dimValue) : e3.longs === Number ? new c.LongBits(t4.dimValue.low >>> 0, t4.dimValue.high >>> 0).toNumber() : t4.dimValue, e3.oneofs && (n2.value = "dimValue")), null != t4.dimParam && t4.hasOwnProperty("dimParam") && (n2.dimParam = t4.dimParam, e3.oneofs && (n2.value = "dimParam")), null != t4.denotation && t4.hasOwnProperty("denotation") && (n2.denotation = t4.denotation), n2;
}, t3.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t3;
}(), t2;
}(), o.TypeProto = function() {
function t2(t3) {
if (t3)
for (var e3 = Object.keys(t3), n2 = 0; n2 < e3.length; ++n2)
null != t3[e3[n2]] && (this[e3[n2]] = t3[e3[n2]]);
}
var e2;
return t2.prototype.tensorType = null, t2.prototype.denotation = "", Object.defineProperty(t2.prototype, "value", { get: c.oneOfGetter(e2 = ["tensorType"]), set: c.oneOfSetter(e2) }), t2.create = function(e3) {
return new t2(e3);
}, t2.encode = function(t3, e3) {
return e3 || (e3 = u.create()), null != t3.tensorType && t3.hasOwnProperty("tensorType") && l.onnx.TypeProto.Tensor.encode(t3.tensorType, e3.uint32(10).fork()).ldelim(), null != t3.denotation && t3.hasOwnProperty("denotation") && e3.uint32(50).string(t3.denotation), e3;
}, t2.encodeDelimited = function(t3, e3) {
return this.encode(t3, e3).ldelim();
}, t2.decode = function(t3, e3) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e3 ? t3.len : t3.pos + e3, r2 = new l.onnx.TypeProto(); t3.pos < n2; ) {
var i2 = t3.uint32();
switch (i2 >>> 3) {
case 1:
r2.tensorType = l.onnx.TypeProto.Tensor.decode(t3, t3.uint32());
break;
case 6:
r2.denotation = t3.string();
break;
default:
t3.skipType(7 & i2);
}
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
if ("object" != typeof t3 || null === t3)
return "object expected";
if (null != t3.tensorType && t3.hasOwnProperty("tensorType")) {
var e3 = l.onnx.TypeProto.Tensor.verify(t3.tensorType);
if (e3)
return "tensorType." + e3;
}
return null != t3.denotation && t3.hasOwnProperty("denotation") && !c.isString(t3.denotation) ? "denotation: string expected" : null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.TypeProto)
return t3;
var e3 = new l.onnx.TypeProto();
if (null != t3.tensorType) {
if ("object" != typeof t3.tensorType)
throw TypeError(".onnx.TypeProto.tensorType: object expected");
e3.tensorType = l.onnx.TypeProto.Tensor.fromObject(t3.tensorType);
}
return null != t3.denotation && (e3.denotation = String(t3.denotation)), e3;
}, t2.toObject = function(t3, e3) {
e3 || (e3 = {});
var n2 = {};
return e3.defaults && (n2.denotation = ""), null != t3.tensorType && t3.hasOwnProperty("tensorType") && (n2.tensorType = l.onnx.TypeProto.Tensor.toObject(t3.tensorType, e3), e3.oneofs && (n2.value = "tensorType")), null != t3.denotation && t3.hasOwnProperty("denotation") && (n2.denotation = t3.denotation), n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2.Tensor = function() {
function t3(t4) {
if (t4)
for (var e3 = Object.keys(t4), n2 = 0; n2 < e3.length; ++n2)
null != t4[e3[n2]] && (this[e3[n2]] = t4[e3[n2]]);
}
return t3.prototype.elemType = 0, t3.prototype.shape = null, t3.create = function(e3) {
return new t3(e3);
}, t3.encode = function(t4, e3) {
return e3 || (e3 = u.create()), null != t4.elemType && t4.hasOwnProperty("elemType") && e3.uint32(8).int32(t4.elemType), null != t4.shape && t4.hasOwnProperty("shape") && l.onnx.TensorShapeProto.encode(t4.shape, e3.uint32(18).fork()).ldelim(), e3;
}, t3.encodeDelimited = function(t4, e3) {
return this.encode(t4, e3).ldelim();
}, t3.decode = function(t4, e3) {
t4 instanceof s || (t4 = s.create(t4));
for (var n2 = void 0 === e3 ? t4.len : t4.pos + e3, r2 = new l.onnx.TypeProto.Tensor(); t4.pos < n2; ) {
var i2 = t4.uint32();
switch (i2 >>> 3) {
case 1:
r2.elemType = t4.int32();
break;
case 2:
r2.shape = l.onnx.TensorShapeProto.decode(t4, t4.uint32());
break;
default:
t4.skipType(7 & i2);
}
}
return r2;
}, t3.decodeDelimited = function(t4) {
return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32());
}, t3.verify = function(t4) {
if ("object" != typeof t4 || null === t4)
return "object expected";
if (null != t4.elemType && t4.hasOwnProperty("elemType") && !c.isInteger(t4.elemType))
return "elemType: integer expected";
if (null != t4.shape && t4.hasOwnProperty("shape")) {
var e3 = l.onnx.TensorShapeProto.verify(t4.shape);
if (e3)
return "shape." + e3;
}
return null;
}, t3.fromObject = function(t4) {
if (t4 instanceof l.onnx.TypeProto.Tensor)
return t4;
var e3 = new l.onnx.TypeProto.Tensor();
if (null != t4.elemType && (e3.elemType = 0 | t4.elemType), null != t4.shape) {
if ("object" != typeof t4.shape)
throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");
e3.shape = l.onnx.TensorShapeProto.fromObject(t4.shape);
}
return e3;
}, t3.toObject = function(t4, e3) {
e3 || (e3 = {});
var n2 = {};
return e3.defaults && (n2.elemType = 0, n2.shape = null), null != t4.elemType && t4.hasOwnProperty("elemType") && (n2.elemType = t4.elemType), null != t4.shape && t4.hasOwnProperty("shape") && (n2.shape = l.onnx.TensorShapeProto.toObject(t4.shape, e3)), n2;
}, t3.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t3;
}(), t2;
}(), o.OperatorSetIdProto = function() {
function t2(t3) {
if (t3)
for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2)
null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
}
return t2.prototype.domain = "", t2.prototype.version = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.create = function(e2) {
return new t2(e2);
}, t2.encode = function(t3, e2) {
return e2 || (e2 = u.create()), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(10).string(t3.domain), null != t3.version && t3.hasOwnProperty("version") && e2.uint32(16).int64(t3.version), e2;
}, t2.encodeDelimited = function(t3, e2) {
return this.encode(t3, e2).ldelim();
}, t2.decode = function(t3, e2) {
t3 instanceof s || (t3 = s.create(t3));
for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.OperatorSetIdProto(); t3.pos < n2; ) {
var i2 = t3.uint32();
switch (i2 >>> 3) {
case 1:
r2.domain = t3.string();
break;
case 2:
r2.version = t3.int64();
break;
default:
t3.skipType(7 & i2);
}
}
return r2;
}, t2.decodeDelimited = function(t3) {
return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
}, t2.verify = function(t3) {
return "object" != typeof t3 || null === t3 ? "object expected" : null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain) ? "domain: string expected" : null != t3.version && t3.hasOwnProperty("version") && !(c.isInteger(t3.version) || t3.version && c.isInteger(t3.version.low) && c.isInteger(t3.version.high)) ? "version: integer|Long expected" : null;
}, t2.fromObject = function(t3) {
if (t3 instanceof l.onnx.OperatorSetIdProto)
return t3;
var e2 = new l.onnx.OperatorSetIdProto();
return null != t3.domain && (e2.domain = String(t3.domain)), null != t3.version && (c.Long ? (e2.version = c.Long.fromValue(t3.version)).unsigned = false : "string" == typeof t3.version ? e2.version = parseInt(t3.version, 10) : "number" == typeof t3.version ? e2.version = t3.version : "object" == typeof t3.version && (e2.version = new c.LongBits(t3.version.low >>> 0, t3.version.high >>> 0).toNumber())), e2;
}, t2.toObject = function(t3, e2) {
e2 || (e2 = {});
var n2 = {};
if (e2.defaults)
if (n2.domain = "", c.Long) {
var r2 = new c.Long(0, 0, false);
n2.version = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2;
} else
n2.version = e2.longs === String ? "0" : 0;
return null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), null != t3.version && t3.hasOwnProperty("version") && ("number" == typeof t3.version ? n2.version = e2.longs === String ? String(t3.version) : t3.version : n2.version = e2.longs === String ? c.Long.prototype.toString.call(t3.version) : e2.longs === Number ? new c.LongBits(t3.version.low >>> 0, t3.version.high >>> 0).toNumber() : t3.version), n2;
}, t2.prototype.toJSON = function() {
return this.constructor.toObject(this, a.util.toJSONOptions);
}, t2;
}(), 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(t2, e2) {
return RangeError("index out of range: " + t2.pos + " + " + (e2 || 1) + " > " + t2.len);
}
function u(t2) {
this.buf = t2, this.pos = 0, this.len = t2.length;
}
var c, l = "undefined" != typeof Uint8Array ? function(t2) {
if (t2 instanceof Uint8Array || Array.isArray(t2))
return new u(t2);
throw Error("illegal buffer");
} : function(t2) {
if (Array.isArray(t2))
return new u(t2);
throw Error("illegal buffer");
}, p = function() {
return i.Buffer ? function(t2) {
return (u.create = function(t3) {
return i.Buffer.isBuffer(t3) ? new r(t3) : l(t3);
})(t2);
} : l;
};
function f() {
var t2 = new o(0, 0), e2 = 0;
if (!(this.len - this.pos > 4)) {
for (; e2 < 3; ++e2) {
if (this.pos >= this.len)
throw s(this);
if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 7 * e2) >>> 0, this.buf[this.pos++] < 128)
return t2;
}
return t2.lo = (t2.lo | (127 & this.buf[this.pos++]) << 7 * e2) >>> 0, t2;
}
for (; e2 < 4; ++e2)
if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 7 * e2) >>> 0, this.buf[this.pos++] < 128)
return t2;
if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 28) >>> 0, t2.hi = (t2.hi | (127 & this.buf[this.pos]) >> 4) >>> 0, this.buf[this.pos++] < 128)
return t2;
if (e2 = 0, this.len - this.pos > 4) {
for (; e2 < 5; ++e2)
if (t2.hi = (t2.hi | (127 & this.buf[this.pos]) << 7 * e2 + 3) >>> 0, this.buf[this.pos++] < 128)
return t2;
} else
for (; e2 < 5; ++e2) {
if (this.pos >= this.len)
throw s(this);
if (t2.hi = (t2.hi | (127 & this.buf[this.pos]) << 7 * e2 + 3) >>> 0, this.buf[this.pos++] < 128)
return t2;
}
throw Error("invalid varint encoding");
}
function d(t2, e2) {
return (t2[e2 - 4] | t2[e2 - 3] << 8 | t2[e2 - 2] << 16 | t2[e2 - 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 t2 = this.uint32();
return t2 >>> 1 ^ -(1 & t2) | 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 t2 = i.float.readFloatLE(this.buf, this.pos);
return this.pos += 4, t2;
}, u.prototype.double = function() {
if (this.pos + 8 > this.len)
throw s(this, 4);
var t2 = i.float.readDoubleLE(this.buf, this.pos);
return this.pos += 8, t2;
}, u.prototype.bytes = function() {
var t2 = this.uint32(), e2 = this.pos, n2 = this.pos + t2;
if (n2 > this.len)
throw s(this, t2);
return this.pos += t2, Array.isArray(this.buf) ? this.buf.slice(e2, n2) : e2 === n2 ? new this.buf.constructor(0) : this._slice.call(this.buf, e2, n2);
}, u.prototype.string = function() {
var t2 = this.bytes();
return a.read(t2, 0, t2.length);
}, u.prototype.skip = function(t2) {
if ("number" == typeof t2) {
if (this.pos + t2 > this.len)
throw s(this, t2);
this.pos += t2;
} else
do {
if (this.pos >= this.len)
throw s(this);
} while (128 & this.buf[this.pos++]);
return this;
}, u.prototype.skipType = function(t2) {
switch (t2) {
case 0:
this.skip();
break;
case 1:
this.skip(8);
break;
case 2:
this.skip(this.uint32());
break;
case 3:
for (; 4 != (t2 = 7 & this.uint32()); )
this.skipType(t2);
break;
case 5:
this.skip(4);
break;
default:
throw Error("invalid wire type " + t2 + " at offset " + this.pos);
}
return this;
}, u._configure = function(t2) {
r = t2, u.create = p(), r._configure();
var e2 = i.Long ? "toLong" : "toNumber";
i.merge(u.prototype, { int64: function() {
return f.call(this)[e2](false);
}, uint64: function() {
return f.call(this)[e2](true);
}, sint64: function() {
return f.call(this).zzDecode()[e2](false);
}, fixed64: function() {
return h.call(this)[e2](true);
}, sfixed64: function() {
return h.call(this)[e2](false);
} });
};
}, 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(t2) {
r.call(this, t2);
}
o._configure = function() {
i.Buffer && (o.prototype._slice = i.Buffer.prototype.slice);
}, o.prototype.string = function() {
var t2 = this.uint32();
return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + t2, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + t2, 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(t2, e2, n2) {
if ("function" != typeof t2)
throw TypeError("rpcImpl must be a function");
r.EventEmitter.call(this), this.rpcImpl = t2, this.requestDelimited = Boolean(e2), this.responseDelimited = Boolean(n2);
}
(i.prototype = Object.create(r.EventEmitter.prototype)).constructor = i, i.prototype.rpcCall = function t2(e2, n2, i2, o, a) {
if (!o)
throw TypeError("request must be specified");
var s = this;
if (!a)
return r.asPromise(t2, s, e2, n2, i2, o);
if (s.rpcImpl)
try {
return s.rpcImpl(e2, n2[s.requestDelimited ? "encodeDelimited" : "encode"](o).finish(), function(t3, n3) {
if (t3)
return s.emit("error", t3, e2), a(t3);
if (null !== n3) {
if (!(n3 instanceof i2))
try {
n3 = i2[s.responseDelimited ? "decodeDelimited" : "decode"](n3);
} catch (t4) {
return s.emit("error", t4, e2), a(t4);
}
return s.emit("data", n3, e2), a(null, n3);
}
s.end(true);
});
} catch (t3) {
return s.emit("error", t3, e2), void setTimeout(function() {
a(t3);
}, 0);
}
else
setTimeout(function() {
a(Error("already ended"));
}, 0);
}, i.prototype.end = function(t2) {
return this.rpcImpl && (t2 || 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(t2, e2) {
this.lo = t2 >>> 0, this.hi = e2 >>> 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(t2) {
if (0 === t2)
return o;
var e2 = t2 < 0;
e2 && (t2 = -t2);
var n2 = t2 >>> 0, r2 = (t2 - n2) / 4294967296 >>> 0;
return e2 && (r2 = ~r2 >>> 0, n2 = ~n2 >>> 0, ++n2 > 4294967295 && (n2 = 0, ++r2 > 4294967295 && (r2 = 0))), new i(n2, r2);
}, i.from = function(t2) {
if ("number" == typeof t2)
return i.fromNumber(t2);
if (r.isString(t2)) {
if (!r.Long)
return i.fromNumber(parseInt(t2, 10));
t2 = r.Long.fromString(t2);
}
return t2.low || t2.high ? new i(t2.low >>> 0, t2.high >>> 0) : o;
}, i.prototype.toNumber = function(t2) {
if (!t2 && this.hi >>> 31) {
var e2 = 1 + ~this.lo >>> 0, n2 = ~this.hi >>> 0;
return e2 || (n2 = n2 + 1 >>> 0), -(e2 + 4294967296 * n2);
}
return this.lo + 4294967296 * this.hi;
}, i.prototype.toLong = function(t2) {
return r.Long ? new r.Long(0 | this.lo, 0 | this.hi, Boolean(t2)) : { low: 0 | this.lo, high: 0 | this.hi, unsigned: Boolean(t2) };
};
var s = String.prototype.charCodeAt;
i.fromHash = function(t2) {
return t2 === a ? o : new i((s.call(t2, 0) | s.call(t2, 1) << 8 | s.call(t2, 2) << 16 | s.call(t2, 3) << 24) >>> 0, (s.call(t2, 4) | s.call(t2, 5) << 8 | s.call(t2, 6) << 16 | s.call(t2, 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 t2 = this.hi >> 31;
return this.hi = ((this.hi << 1 | this.lo >>> 31) ^ t2) >>> 0, this.lo = (this.lo << 1 ^ t2) >>> 0, this;
}, i.prototype.zzDecode = function() {
var t2 = -(1 & this.lo);
return this.lo = ((this.lo >>> 1 | this.hi << 31) ^ t2) >>> 0, this.hi = (this.hi >>> 1 ^ t2) >>> 0, this;
}, i.prototype.length = function() {
var t2 = this.lo, e2 = (this.lo >>> 28 | this.hi << 4) >>> 0, n2 = this.hi >>> 24;
return 0 === n2 ? 0 === e2 ? t2 < 16384 ? t2 < 128 ? 1 : 2 : t2 < 2097152 ? 3 : 4 : e2 < 16384 ? e2 < 128 ? 5 : 6 : e2 < 2097152 ? 7 : 8 : n2 < 128 ? 9 : 10;
};
}, 9693: function(t, e, n) {
"use strict";
var r = e;
function i(t2, e2, n2) {
for (var r2 = Object.keys(e2), i2 = 0; i2 < r2.length; ++i2)
void 0 !== t2[r2[i2]] && n2 || (t2[r2[i2]] = e2[r2[i2]]);
return t2;
}
function o(t2) {
function e2(t3, n2) {
if (!(this instanceof e2))
return new e2(t3, n2);
Object.defineProperty(this, "message", { get: function() {
return t3;
} }), Error.captureStackTrace ? Error.captureStackTrace(this, e2) : Object.defineProperty(this, "stack", { value: new Error().stack || "" }), n2 && i(this, n2);
}
return (e2.prototype = Object.create(Error.prototype)).constructor = e2, Object.defineProperty(e2.prototype, "name", { get: function() {
return t2;
} }), e2.prototype.toString = function() {
return this.name + ": " + this.message;
}, e2;
}
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(t2) {
return "number" == typeof t2 && isFinite(t2) && Math.floor(t2) === t2;
}, r.isString = function(t2) {
return "string" == typeof t2 || t2 instanceof String;
}, r.isObject = function(t2) {
return t2 && "object" == typeof t2;
}, r.isset = r.isSet = function(t2, e2) {
var n2 = t2[e2];
return !(null == n2 || !t2.hasOwnProperty(e2)) && ("object" != typeof n2 || (Array.isArray(n2) ? n2.length : Object.keys(n2).length) > 0);
}, r.Buffer = function() {
try {
var t2 = r.inquire("buffer").Buffer;
return t2.prototype.utf8Write ? t2 : null;
} catch (t3) {
return null;
}
}(), r._Buffer_from = null, r._Buffer_allocUnsafe = null, r.newBuffer = function(t2) {
return "number" == typeof t2 ? r.Buffer ? r._Buffer_allocUnsafe(t2) : new r.Array(t2) : r.Buffer ? r._Buffer_from(t2) : "undefined" == typeof Uint8Array ? t2 : new Uint8Array(t2);
}, 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(t2) {
return t2 ? r.LongBits.from(t2).toHash() : r.LongBits.zeroHash;
}, r.longFromHash = function(t2, e2) {
var n2 = r.LongBits.fromHash(t2);
return r.Long ? r.Long.fromBits(n2.lo, n2.hi, e2) : n2.toNumber(Boolean(e2));
}, r.merge = i, r.lcFirst = function(t2) {
return t2.charAt(0).toLowerCase() + t2.substring(1);
}, r.newError = o, r.ProtocolError = o("ProtocolError"), r.oneOfGetter = function(t2) {
for (var e2 = {}, n2 = 0; n2 < t2.length; ++n2)
e2[t2[n2]] = 1;
return function() {
for (var t3 = Object.keys(this), n3 = t3.length - 1; n3 > -1; --n3)
if (1 === e2[t3[n3]] && void 0 !== this[t3[n3]] && null !== this[t3[n3]])
return t3[n3];
};
}, r.oneOfSetter = function(t2) {
return function(e2) {
for (var n2 = 0; n2 < t2.length; ++n2)
t2[n2] !== e2 && delete this[t2[n2]];
};
}, r.toJSONOptions = { longs: String, enums: String, bytes: String, json: true }, r._configure = function() {
var t2 = r.Buffer;
t2 ? (r._Buffer_from = t2.from !== Uint8Array.from && t2.from || function(e2, n2) {
return new t2(e2, n2);
}, r._Buffer_allocUnsafe = t2.allocUnsafe || function(e2) {
return new t2(e2);
}) : 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(t2, e2, n2) {
this.fn = t2, this.len = e2, this.next = void 0, this.val = n2;
}
function c() {
}
function l(t2) {
this.head = t2.head, this.tail = t2.tail, this.len = t2.len, this.next = t2.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(t2, e2, n2) {
e2[n2] = 255 & t2;
}
function h(t2, e2) {
this.len = t2, this.next = void 0, this.val = e2;
}
function g(t2, e2, n2) {
for (; t2.hi; )
e2[n2++] = 127 & t2.lo | 128, t2.lo = (t2.lo >>> 7 | t2.hi << 25) >>> 0, t2.hi >>>= 7;
for (; t2.lo > 127; )
e2[n2++] = 127 & t2.lo | 128, t2.lo = t2.lo >>> 7;
e2[n2++] = t2.lo;
}
function b(t2, e2, n2) {
e2[n2] = 255 & t2, e2[n2 + 1] = t2 >>> 8 & 255, e2[n2 + 2] = t2 >>> 16 & 255, e2[n2 + 3] = t2 >>> 24;
}
p.create = f(), p.alloc = function(t2) {
return new i.Array(t2);
}, i.Array !== Array && (p.alloc = i.pool(p.alloc, i.Array.prototype.subarray)), p.prototype._push = function(t2, e2, n2) {
return this.tail = this.tail.next = new u(t2, e2, n2), this.len += e2, this;
}, h.prototype = Object.create(u.prototype), h.prototype.fn = function(t2, e2, n2) {
for (; t2 > 127; )
e2[n2++] = 127 & t2 | 128, t2 >>>= 7;
e2[n2] = t2;
}, p.prototype.uint32 = function(t2) {
return this.len += (this.tail = this.tail.next = new h((t2 >>>= 0) < 128 ? 1 : t2 < 16384 ? 2 : t2 < 2097152 ? 3 : t2 < 268435456 ? 4 : 5, t2)).len, this;
}, p.prototype.int32 = function(t2) {
return t2 < 0 ? this._push(g, 10, o.fromNumber(t2)) : this.uint32(t2);
}, p.prototype.sint32 = function(t2) {
return this.uint32((t2 << 1 ^ t2 >> 31) >>> 0);
}, p.prototype.uint64 = function(t2) {
var e2 = o.from(t2);
return this._push(g, e2.length(), e2);
}, p.prototype.int64 = p.prototype.uint64, p.prototype.sint64 = function(t2) {
var e2 = o.from(t2).zzEncode();
return this._push(g, e2.length(), e2);
}, p.prototype.bool = function(t2) {
return this._push(d, 1, t2 ? 1 : 0);
}, p.prototype.fixed32 = function(t2) {
return this._push(b, 4, t2 >>> 0);
}, p.prototype.sfixed32 = p.prototype.fixed32, p.prototype.fixed64 = function(t2) {
var e2 = o.from(t2);
return this._push(b, 4, e2.lo)._push(b, 4, e2.hi);
}, p.prototype.sfixed64 = p.prototype.fixed64, p.prototype.float = function(t2) {
return this._push(i.float.writeFloatLE, 4, t2);
}, p.prototype.double = function(t2) {
return this._push(i.float.writeDoubleLE, 8, t2);
};
var m = i.Array.prototype.set ? function(t2, e2, n2) {
e2.set(t2, n2);
} : function(t2, e2, n2) {
for (var r2 = 0; r2 < t2.length; ++r2)
e2[n2 + r2] = t2[r2];
};
p.prototype.bytes = function(t2) {
var e2 = t2.length >>> 0;
if (!e2)
return this._push(d, 1, 0);
if (i.isString(t2)) {
var n2 = p.alloc(e2 = a.length(t2));
a.decode(t2, n2, 0), t2 = n2;
}
return this.uint32(e2)._push(m, e2, t2);
}, p.prototype.string = function(t2) {
var e2 = s.length(t2);
return e2 ? this.uint32(e2)._push(s.write, e2, t2) : 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 t2 = this.head, e2 = this.tail, n2 = this.len;
return this.reset().uint32(n2), n2 && (this.tail.next = t2.next, this.tail = e2, this.len += n2), this;
}, p.prototype.finish = function() {
for (var t2 = this.head.next, e2 = this.constructor.alloc(this.len), n2 = 0; t2; )
t2.fn(t2.val, e2, n2), n2 += t2.len, t2 = t2.next;
return e2;
}, p._configure = function(t2) {
r = t2, 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(t2, e2, n2) {
t2.length < 40 ? i.utf8.write(t2, e2, n2) : e2.utf8Write ? e2.utf8Write(t2, n2) : e2.write(t2, n2);
}
o._configure = function() {
o.alloc = i._Buffer_allocUnsafe, o.writeBytesBuffer = i.Buffer && i.Buffer.prototype instanceof Uint8Array && "set" === i.Buffer.prototype.set.name ? function(t2, e2, n2) {
e2.set(t2, n2);
} : function(t2, e2, n2) {
if (t2.copy)
t2.copy(e2, n2, 0, t2.length);
else
for (var r2 = 0; r2 < t2.length; )
e2[n2++] = t2[r2++];
};
}, o.prototype.bytes = function(t2) {
i.isString(t2) && (t2 = i._Buffer_from(t2, "base64"));
var e2 = t2.length >>> 0;
return this.uint32(e2), e2 && this._push(o.writeBytesBuffer, e2, t2), this;
}, o.prototype.string = function(t2) {
var e2 = i.Buffer.byteLength(t2);
return this.uint32(e2), e2 && this._push(a, e2, t2), 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(t2, e2) {
const n2 = new r.Session(e2);
return await n2.loadModel(t2), new i.OnnxjsSessionHandler(n2);
}
}();
}, 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 = true), "boolean" != typeof r.env.wasm.proxy && (r.env.wasm.proxy = false), "number" != typeof r.env.wasm.numThreads || !Number.isInteger(r.env.wasm.numThreads) || r.env.wasm.numThreads <= 0) {
const t2 = "undefined" == typeof navigator ? (0, i.cpus)().length : navigator.hardwareConcurrency;
r.env.wasm.numThreads = Math.min(4, Math.ceil((t2 || 1) / 2));
}
}, e.c8 = new class {
async init() {
(0, e.rX)(), await (0, o.initWasm)();
}
async createSessionHandler(t2, e2) {
const n2 = new a.OnnxruntimeWebAssemblySessionHandler();
return await n2.loadModel(t2, e2), Promise.resolve(n2);
}
}();
}, 6018: function(t, e, n) {
"use strict";
var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) {
void 0 === r2 && (r2 = n2);
var i2 = Object.getOwnPropertyDescriptor(e2, n2);
i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() {
return e2[n2];
} }), Object.defineProperty(t2, r2, i2);
} : function(t2, e2, n2, r2) {
void 0 === r2 && (r2 = n2), t2[r2] = e2[n2];
}), i = this && this.__exportStar || function(t2, e2) {
for (var n2 in t2)
"default" === n2 || Object.prototype.hasOwnProperty.call(e2, n2) || r(e2, t2, n2);
};
Object.defineProperty(e, "__esModule", { value: true }), i(n(1670), e);
const o = n(1670);
{
const t2 = n(7714).R;
(0, o.registerBackend)("webgl", t2, -10);
}
{
const t2 = n(4200).c8;
(0, o.registerBackend)("cpu", t2, 10), (0, o.registerBackend)("wasm", t2, 10), (0, o.registerBackend)("xnnpack", t2, 9);
}
}, 246: (t, e) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.createAttributeWithCacheKey = void 0;
class n {
constructor(t2) {
Object.assign(this, t2);
}
get cacheKey() {
return this._cacheKey || (this._cacheKey = Object.getOwnPropertyNames(this).sort().map((t2) => `${this[t2]}`).join(";")), this._cacheKey;
}
}
e.createAttributeWithCacheKey = (t2) => new n(t2);
}, 7778: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2) {
if (this._attributes = /* @__PURE__ */ new Map(), null != t2) {
for (const e2 of t2)
e2 instanceof r.onnx.AttributeProto ? this._attributes.set(e2.name, [u.getValue(e2), u.getType(e2)]) : e2 instanceof s.Attribute && this._attributes.set(e2.name(), [u.getValue(e2), u.getType(e2)]);
if (this._attributes.size < t2.length)
throw new Error("duplicated attribute names");
}
}
set(t2, e2, n2) {
this._attributes.set(t2, [n2, e2]);
}
delete(t2) {
this._attributes.delete(t2);
}
getFloat(t2, e2) {
return this.get(t2, "float", e2);
}
getInt(t2, e2) {
return this.get(t2, "int", e2);
}
getString(t2, e2) {
return this.get(t2, "string", e2);
}
getTensor(t2, e2) {
return this.get(t2, "tensor", e2);
}
getFloats(t2, e2) {
return this.get(t2, "floats", e2);
}
getInts(t2, e2) {
return this.get(t2, "ints", e2);
}
getStrings(t2, e2) {
return this.get(t2, "strings", e2);
}
getTensors(t2, e2) {
return this.get(t2, "tensors", e2);
}
get(t2, e2, n2) {
const r2 = this._attributes.get(t2);
if (void 0 === r2) {
if (void 0 !== n2)
return n2;
throw new Error(`required attribute not found: ${t2}`);
}
if (r2[1] !== e2)
throw new Error(`type mismatch: expected ${e2} but got ${r2[1]}`);
return r2[0];
}
static getType(t2) {
const e2 = t2 instanceof r.onnx.AttributeProto ? t2.type : t2.type();
switch (e2) {
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[e2]}`);
}
}
static getValue(t2) {
const e2 = t2 instanceof r.onnx.AttributeProto ? t2.type : t2.type();
if (e2 === r.onnx.AttributeProto.AttributeType.GRAPH || e2 === r.onnx.AttributeProto.AttributeType.GRAPHS)
throw new Error("graph attribute is not supported yet");
const n2 = this.getValueNoCheck(t2);
if (e2 === r.onnx.AttributeProto.AttributeType.INT && a.LongUtil.isLong(n2))
return a.LongUtil.longToNumber(n2);
if (e2 === r.onnx.AttributeProto.AttributeType.INTS) {
const t3 = n2, e3 = new Array(t3.length);
for (let n3 = 0; n3 < t3.length; n3++) {
const r2 = t3[n3];
e3[n3] = a.LongUtil.longToNumber(r2);
}
return e3;
}
if (e2 === r.onnx.AttributeProto.AttributeType.TENSOR)
return t2 instanceof r.onnx.AttributeProto ? o.Tensor.fromProto(n2) : o.Tensor.fromOrtTensor(n2);
if (e2 === r.onnx.AttributeProto.AttributeType.TENSORS) {
if (t2 instanceof r.onnx.AttributeProto)
return n2.map((t3) => o.Tensor.fromProto(t3));
if (t2 instanceof s.Attribute)
return n2.map((t3) => o.Tensor.fromOrtTensor(t3));
}
if (e2 === r.onnx.AttributeProto.AttributeType.STRING && t2 instanceof r.onnx.AttributeProto) {
const t3 = n2;
return (0, a.decodeUtf8String)(t3);
}
return e2 === r.onnx.AttributeProto.AttributeType.STRINGS && t2 instanceof r.onnx.AttributeProto ? n2.map(a.decodeUtf8String) : n2;
}
static getValueNoCheck(t2) {
return t2 instanceof r.onnx.AttributeProto ? this.getValueNoCheckFromOnnxFormat(t2) : this.getValueNoCheckFromOrtFormat(t2);
}
static getValueNoCheckFromOnnxFormat(t2) {
switch (t2.type) {
case r.onnx.AttributeProto.AttributeType.FLOAT:
return t2.f;
case r.onnx.AttributeProto.AttributeType.INT:
return t2.i;
case r.onnx.AttributeProto.AttributeType.STRING:
return t2.s;
case r.onnx.AttributeProto.AttributeType.TENSOR:
return t2.t;
case r.onnx.AttributeProto.AttributeType.GRAPH:
return t2.g;
case r.onnx.AttributeProto.AttributeType.FLOATS:
return t2.floats;
case r.onnx.AttributeProto.AttributeType.INTS:
return t2.ints;
case r.onnx.AttributeProto.AttributeType.STRINGS:
return t2.strings;
case r.onnx.AttributeProto.AttributeType.TENSORS:
return t2.tensors;
case r.onnx.AttributeProto.AttributeType.GRAPHS:
return t2.graphs;
default:
throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[t2.type]}`);
}
}
static getValueNoCheckFromOrtFormat(t2) {
switch (t2.type()) {
case s.AttributeType.FLOAT:
return t2.f();
case s.AttributeType.INT:
return t2.i();
case s.AttributeType.STRING:
return t2.s();
case s.AttributeType.TENSOR:
return t2.t();
case s.AttributeType.GRAPH:
return t2.g();
case s.AttributeType.FLOATS:
return t2.floatsArray();
case s.AttributeType.INTS: {
const e2 = [];
for (let n2 = 0; n2 < t2.intsLength(); n2++)
e2.push(t2.ints(n2));
return e2;
}
case s.AttributeType.STRINGS: {
const e2 = [];
for (let n2 = 0; n2 < t2.stringsLength(); n2++)
e2.push(t2.strings(n2));
return e2;
}
case s.AttributeType.TENSORS: {
const e2 = [];
for (let n2 = 0; n2 < t2.tensorsLength(); n2++)
e2.push(t2.tensors(n2));
return e2;
}
default:
throw new Error(`unsupported attribute type: ${s.AttributeType[t2.type()]}`);
}
}
}
e.Attribute = u;
}, 7091: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.resolveBackend = e.backend = void 0;
const r = n(5038), i = /* @__PURE__ */ new Map();
async function o(t2) {
const n2 = e.backend;
if (void 0 !== n2[t2] && function(t3) {
const e2 = t3;
return "initialize" in e2 && "function" == typeof e2.initialize && "createSessionHandler" in e2 && "function" == typeof e2.createSessionHandler && "dispose" in e2 && "function" == typeof e2.dispose;
}(n2[t2])) {
const e2 = n2[t2];
let r2 = e2.initialize();
if ("object" == typeof r2 && "then" in r2 && (r2 = await r2), r2)
return i.set(t2, e2), e2;
}
}
e.backend = { webgl: new r.WebGLBackend() }, e.resolveBackend = async function t2(e2) {
if (!e2)
return t2(["webgl"]);
{
const t3 = "string" == typeof e2 ? [e2] : e2;
for (const e3 of t3) {
const t4 = i.get(e3);
if (t4)
return t4;
const n2 = await o(e3);
if (n2)
return n2;
}
}
throw new Error("no available backend to use");
};
}, 5038: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2) {
r.env.webgl.contextId = t2;
}
get matmulMaxBatchSize() {
return r.env.webgl.matmulMaxBatchSize;
}
set matmulMaxBatchSize(t2) {
r.env.webgl.matmulMaxBatchSize = t2;
}
get textureCacheMode() {
return r.env.webgl.textureCacheMode;
}
set textureCacheMode(t2) {
r.env.webgl.textureCacheMode = t2;
}
get pack() {
return r.env.webgl.pack;
}
set pack(t2) {
r.env.webgl.pack = t2;
}
get async() {
return r.env.webgl.async;
}
set async(t2) {
r.env.webgl.async = t2;
}
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 = false), "boolean" != typeof this.async && (this.async = false), 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}.`), true;
} catch (t2) {
return i.Logger.warning("WebGLBackend", `Unable to initialize WebGLBackend. ${t2}`), false;
}
}
createSessionHandler(t2) {
return new o.WebGLSessionHandler(this, t2);
}
dispose() {
this.glContext.dispose();
}
};
}, 5107: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2) {
super(t2);
}
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 t2 = this.context.outputTextureLayout;
return t2.isPacked ? this.getPackedOutputSamplingSnippet(t2) : this.getUnpackedOutputSamplingSnippet(t2);
}
getPackedOutputSamplingSnippet(t2) {
const e2 = t2.unpackedShape, n2 = [t2.width, t2.height], r2 = {}, a2 = "getOutputCoords";
switch (e2.length) {
case 0:
r2[a2] = this.getOutputScalarCoords();
break;
case 1:
r2[a2] = this.getOutputPacked1DCoords(e2, n2);
break;
case 2:
r2[a2] = this.getOutputPacked2DCoords(e2, n2);
break;
case 3:
r2[a2] = this.getOutputPacked3DCoords(e2, n2);
break;
default:
r2[a2] = this.getOutputPackedNDCoords(e2, n2);
}
const s2 = `
void setOutput(vec4 val) {
${(0, o.getGlsl)(this.context.glContext.version).output} = val;
}
`;
return r2.floatTextureSetRGBA = new i.GlslLibRoutine(s2), r2;
}
getUnpackedOutputSamplingSnippet(t2) {
const e2 = t2.unpackedShape, n2 = [t2.width, t2.height], r2 = {}, a2 = "getOutputCoords";
switch (e2.length) {
case 0:
r2[a2] = this.getOutputScalarCoords();
break;
case 1:
r2[a2] = this.getOutputUnpacked1DCoords(e2, n2);
break;
case 2:
r2[a2] = this.getOutputUnpacked2DCoords(e2, n2);
break;
case 3:
r2[a2] = this.getOutputUnpacked3DCoords(e2, n2);
break;
case 4:
r2[a2] = this.getOutputUnpacked4DCoords(e2, n2);
break;
case 5:
r2[a2] = this.getOutputUnpacked5DCoords(e2, n2);
break;
case 6:
r2[a2] = this.getOutputUnpacked6DCoords(e2, n2);
break;
default:
throw new Error(`Unsupported output dimensionality: ${e2.length}`);
}
const s2 = `
void setOutput(float val) {
${(0, o.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0);
}
`;
return r2.floatTextureSetR = new i.GlslLibRoutine(s2), r2;
}
getOutputScalarCoords() {
return new i.GlslLibRoutine("\n int getOutputCoords() {\n return 0;\n }\n ");
}
getOutputPacked1DCoords(t2, e2) {
const n2 = e2;
let r2 = "";
return 1 === n2[0] ? (r2 = `
int getOutputCoords() {
return 2 * int(TexCoords.y * ${n2[1]}.0);
}
`, new i.GlslLibRoutine(r2)) : 1 === n2[1] ? (r2 = `
int getOutputCoords() {
return 2 * int(TexCoords.x * ${n2[0]}.0);
}
`, new i.GlslLibRoutine(r2)) : (r2 = `
int getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${n2[0]}, ${n2[1]}));
return 2 * (resTexRC.y * ${n2[0]} + resTexRC.x);
}
`, new i.GlslLibRoutine(r2));
}
getOutputPacked2DCoords(t2, e2) {
let n2 = "";
if (r.ArrayUtil.arraysEqual(t2, e2))
return n2 = `
ivec2 getOutputCoords() {
return 2 * ivec2(TexCoords.xy * vec2(${e2[0]}, ${e2[1]}));
}
`, new i.GlslLibRoutine(n2);
const o2 = e2, a2 = Math.ceil(t2[1] / 2);
return n2 = `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${o2[0]}, ${o2[1]}));
int index = resTexRC.y * ${o2[0]} + resTexRC.x;
// reverse r and c order for packed texture
int r = imod(index, ${a2}) * 2;
int c = 2 * (index / ${a2});
return ivec2(r, c);
}
`, new i.GlslLibRoutine(n2);
}
getOutputPacked3DCoords(t2, e2) {
const n2 = [e2[0], e2[1]], r2 = Math.ceil(t2[2] / 2), o2 = r2 * Math.ceil(t2[1] / 2), a2 = `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${n2[0]}, ${n2[1]}));
int index = resTexRC.y * ${n2[0]} + resTexRC.x;
int b = index / ${o2};
index -= b * ${o2};
// reverse r and c order for packed texture
int r = imod(index, ${r2}) * 2;
int c = 2 * (index / ${r2});
return ivec3(b, r, c);
}
`;
return new i.GlslLibRoutine(a2);
}
getOutputPackedNDCoords(t2, e2) {
const n2 = [e2[0], e2[1]], r2 = Math.ceil(t2[t2.length - 1] / 2), o2 = r2 * Math.ceil(t2[t2.length - 2] / 2);
let a2 = o2, s2 = "", u2 = "b, r, c";
for (let e3 = 2; e3 < t2.length - 1; e3++)
a2 *= t2[t2.length - e3 - 1], s2 = `
int b${e3} = index / ${a2};
index -= b${e3} * ${a2};
` + s2, u2 = `b${e3}, ` + u2;
const c = `
ivec${t2.length} getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${n2[0]}, ${n2[1]}));
int index = resTexRC.y * ${n2[0]} + resTexRC.x;
${s2}
int b = index / ${o2};
index -= b * ${o2};
// reverse r and c order for packed texture
int r = imod(index, ${r2}) * 2;
int c = 2 * (index / ${r2});
return ivec${t2.length}(${u2});
}
`;
return new i.GlslLibRoutine(c);
}
getOutputUnpacked1DCoords(t2, e2) {
const n2 = `
int getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${e2[0]}, ${e2[1]}));
return resTexRC.y * ${e2[0]} + resTexRC.x;
}
`;
return new i.GlslLibRoutine(n2);
}
getOutputUnpacked2DCoords(t2, e2) {
const n2 = `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${e2[0]}, ${e2[1]}));
int index = resTexRC.y * ${e2[0]} + resTexRC.x;
int r = index / ${t2[1]};
int c = index - r * ${t2[1]};
return ivec2(r, c);
}
`;
return new i.GlslLibRoutine(n2);
}
getOutputUnpacked3DCoords(t2, e2) {
let n2 = "";
const r2 = t2.length;
let o2 = null;
r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1];
for (let e3 = r2 - 3; e3 >= 0; --e3)
o2[e3] = o2[e3 + 1] * t2[e3 + 1];
const a2 = ["r", "c", "d"], s2 = o2.map((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`).join("");
return n2 = `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${e2[0]}, ${e2[1]}));
int index = resTexRC.y * ${e2[0]} + resTexRC.x;
${s2}
return ivec3(r, c, d);
}
`, new i.GlslLibRoutine(n2);
}
getOutputUnpacked4DCoords(t2, e2) {
let n2 = "";
const r2 = t2.length;
let o2 = null;
r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1];
for (let e3 = r2 - 3; e3 >= 0; --e3)
o2[e3] = o2[e3 + 1] * t2[e3 + 1];
const a2 = ["r", "c", "d", "d2"], s2 = o2.map((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`).join("");
return n2 = `
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${e2[0]}, ${e2[1]}));
int index = resTexRC.y * ${e2[0]} + resTexRC.x;
${s2}
return ivec4(r, c, d, d2);
}
`, new i.GlslLibRoutine(n2);
}
getOutputUnpacked5DCoords(t2, e2) {
let n2 = "";
const r2 = t2.length;
let o2 = null;
r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1];
for (let e3 = r2 - 3; e3 >= 0; --e3)
o2[e3] = o2[e3 + 1] * t2[e3 + 1];
const a2 = ["r", "c", "d", "d2", "d3"], s2 = o2.map((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`).join("");
return n2 = `
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${e2[0]}, ${e2[1]}));
int index = resTexRC.y * ${e2[0]} + resTexRC.x;
${s2}
return ivec5(r, c, d, d2, d3);
}
`, new i.GlslLibRoutine(n2);
}
getOutputUnpacked6DCoords(t2, e2) {
let n2 = "";
const r2 = t2.length;
let o2 = null;
r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1];
for (let e3 = r2 - 3; e3 >= 0; --e3)
o2[e3] = o2[e3 + 1] * t2[e3 + 1];
const a2 = ["r", "c", "d", "d2", "d3", "d4"], s2 = o2.map((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`).join("");
return n2 = `
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${e2[0]}, ${e2[1]}));
int index = resTexRC.y * ${e2[0]} + resTexRC.x;
${s2}
return ivec6(r, c, d, d2, d3, d4);
}
`, new i.GlslLibRoutine(n2);
}
getCommonUtilFuncs() {
const t2 = {};
let e2 = "uvFromFlat";
t2[e2] = 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 "), e2 = "packedUVfrom1D", t2[e2] = 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 "), e2 = "packedUVfrom2D", t2[e2] = 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 "), e2 = "packedUVfrom3D", t2[e2] = 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 "), e2 = "sampleTexture";
const n2 = (0, o.getGlsl)(this.context.glContext.version);
return t2[e2] = new i.GlslLibRoutine(`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${n2.texture2D}(textureSampler, uv).r;
}`), t2;
}
getInputsSamplingSnippets() {
const t2 = {}, e2 = this.context.outputTextureLayout;
return this.context.programInfo.inputNames.forEach((n2, r2) => {
const i2 = this.context.inputTextureLayouts[r2], o2 = (0, s.generateShaderFuncNameFromInputSamplerName)(n2);
i2.isPacked ? t2[o2] = this.getPackedSamplerFromInput(o2, n2, i2) : t2[o2] = this.getUnpackedSamplerFromInput(o2, n2, i2);
const a2 = (0, s.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n2);
i2.unpackedShape.length <= e2.unpackedShape.length && (i2.isPacked ? t2[a2] = this.getPackedSamplerAtOutputCoords(a2, i2, e2, n2) : t2[a2] = this.getUnpackedSamplerAtOutputCoords(a2, i2, e2, n2));
}), t2;
}
getPackedSamplerAtOutputCoords(t2, e2, n2, o2) {
const a2 = e2.unpackedShape, u2 = n2.unpackedShape, c = o2, l = (0, s.generateShaderFuncNameFromInputSamplerName)(c), p = a2.length, f = u2.length, d = r.BroadcastUtil.getBroadcastDims(a2, u2), 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((t3) => `coords.${m[t3 + g]} = 0;`).join("\n");
let y = "";
y = f < 2 && p > 0 ? "coords" : a2.map((t3, e3) => `coords.${m[e3 + g]}`).join(", ");
let _ = "return outputValue;";
const v = 1 === r.ShapeUtil.size(a2), w = 1 === r.ShapeUtil.size(u2);
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 t3 = p - 2, e3 = p - 1;
d.indexOf(t3) > -1 && d.indexOf(e3) > -1 ? _ = "return vec4(outputValue.x);" : d.indexOf(t3) > -1 ? _ = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : d.indexOf(e3) > -1 && (_ = "return vec4(outputValue.xx, outputValue.zz);");
}
} else
_ = "\n return vec4(outputValue.xy, outputValue.xy);\n ";
const x = `
vec4 ${t2}() {
${h} coords = getOutputCoords();
int lastDim = coords.${m[f - 1]};
coords.${m[f - 1]} = coords.${m[f - 2]};
coords.${m[f - 2]} = lastDim;
${b}
vec4 outputValue = ${l}(${y});
${_}
}
`;
return new i.GlslLibRoutine(x, ["coordinates.getOutputCoords"]);
}
getUnpackedSamplerAtOutputCoords(t2, e2, n2, o2) {
const a2 = [n2.width, n2.height], u2 = [e2.width, e2.height], c = e2.unpackedShape.length, l = n2.unpackedShape.length, p = e2.unpackedShape, f = n2.unpackedShape, d = (0, s.generateShaderFuncNameFromInputSamplerName)(o2);
if (c === l && r.ArrayUtil.arraysEqual(u2, a2)) {
const e3 = `
float ${t2}() {
return sampleTexture(${o2}, TexCoords);
}
`;
return new i.GlslLibRoutine(e3, ["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((t3) => `coords.${y[t3 + b]} = 0;`).join("\n");
let _ = "";
_ = l < 2 && c > 0 ? "coords" : e2.unpackedShape.map((t3, e3) => `coords.${y[e3 + b]}`).join(", ");
const v = `
float ${t2}() {
${h} coords = getOutputCoords();
${m}
return ${d}(${_});
}
`;
return new i.GlslLibRoutine(v, ["coordinates.getOutputCoords"]);
}
getPackedSamplerFromInput(t2, e2, n2) {
switch (n2.unpackedShape.length) {
case 0:
return this.getPackedSamplerScalar(t2, e2);
case 1:
return this.getPackedSampler1D(t2, e2, n2);
case 2:
return this.getPackedSampler2D(t2, e2, n2);
case 3:
return this.getPackedSampler3D(t2, e2, n2);
default:
return this.getPackedSamplerND(t2, e2, n2);
}
}
getUnpackedSamplerFromInput(t2, e2, n2) {
const r2 = n2.unpackedShape;
switch (r2.length) {
case 0:
return this.getUnpackedSamplerScalar(t2, e2, n2);
case 1:
return this.getUnpackedSampler1D(t2, e2, n2);
case 2:
return this.getUnpackedSampler2D(t2, e2, n2);
case 3:
return this.getUnpackedSampler3D(t2, e2, n2);
case 4:
return this.getUnpackedSampler4D(t2, e2, n2);
case 5:
return this.getUnpackedSampler5D(t2, e2, n2);
case 6:
return this.getUnpackedSampler6D(t2, e2, n2);
default:
throw new Error(`Unsupported dimension ${r2.length}-D`);
}
}
getPackedSamplerScalar(t2, e2) {
const n2 = `
vec4 ${t2}() {
return ${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${e2}, halfCR);
}
`;
return new i.GlslLibRoutine(n2);
}
getPackedSampler1D(t2, e2, n2) {
const r2 = [n2.width, n2.height], a2 = [r2[1], r2[0]], s2 = (0, o.getGlsl)(this.context.glContext.version), u2 = `vec4 ${t2}(int index) {
vec2 uv = packedUVfrom1D(
${a2[0]}, ${a2[1]}, index);
return ${s2.texture2D}(${e2}, uv);
}`;
return new i.GlslLibRoutine(u2, ["coordinates.packedUVfrom1D"]);
}
getPackedSampler2D(t2, e2, n2) {
const a2 = n2.unpackedShape, s2 = [n2.width, n2.height], u2 = (0, o.getGlsl)(this.context.glContext.version), c = s2[0], l = s2[1];
if (null != s2 && r.ArrayUtil.arraysEqual(a2, s2)) {
const n3 = `vec4 ${t2}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${l}.0, ${c}.0);
return ${u2.texture2D}(${e2}, uv);
}`;
return new i.GlslLibRoutine(n3);
}
const p = s2, f = Math.ceil(a2[1] / 2), d = `vec4 ${t2}(int row, int col) {
vec2 uv = packedUVfrom2D(${p[1]}, ${p[0]}, ${f}, row, col);
return ${u2.texture2D}(${e2}, uv);
}`;
return new i.GlslLibRoutine(d, ["coordinates.packedUVfrom2D"]);
}
getPackedSampler3D(t2, e2, n2) {
const r2 = n2.unpackedShape, a2 = [n2.width, n2.height], u2 = [a2[0], a2[1]], c = (0, o.getGlsl)(this.context.glContext.version);
if (1 === r2[0]) {
const o2 = r2.slice(1), a3 = [1, 2], u3 = (0, s.squeezeInputShape)(r2, o2), c2 = ["b", "row", "col"], l2 = JSON.parse(JSON.stringify(n2));
l2.unpackedShape = u3;
const p2 = this.getPackedSamplerFromInput(t2, e2, l2), f2 = `${p2.routineBody}
vec4 ${t2}(int b, int row, int col) {
return ${t2}(${(0, s.getSqueezedParams)(c2, a3)});
} `;
return new i.GlslLibRoutine(f2, p2.dependencies);
}
const l = u2[0], p = u2[1], f = Math.ceil(r2[2] / 2), d = `vec4 ${t2}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${p}, ${l}, ${f * Math.ceil(r2[1] / 2)}, ${f}, b, row, col);
return ${c.texture2D}(${e2}, uv);}`;
return new i.GlslLibRoutine(d, ["coordinates.packedUVfrom3D"]);
}
getPackedSamplerND(t2, e2, n2) {
const r2 = n2.unpackedShape, a2 = r2.length, s2 = [n2.width, n2.height], u2 = (0, o.getGlsl)(this.context.glContext.version), c = [s2[0], s2[1]], l = c[1], p = c[0], f = Math.ceil(r2[a2 - 1] / 2);
let d = f * Math.ceil(r2[a2 - 2] / 2), h = "int b, int row, int col", g = `b * ${d} + (row / 2) * ${f} + (col / 2)`;
for (let t3 = 2; t3 < a2 - 1; t3++)
h = `int b${t3}, ` + h, d *= r2[a2 - t3 - 1], g = `b${t3} * ${d} + ` + g;
const b = `vec4 ${t2}(${h}) {
int index = ${g};
int texR = index / ${p};
int texC = index - texR * ${p};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${l});
return ${u2.texture2D}(${e2}, uv);
}`;
return new i.GlslLibRoutine(b);
}
getUnpackedSamplerScalar(t2, e2, n2) {
const [r2, o2] = [n2.width, n2.height];
if (1 === r2 && 1 === o2) {
const n3 = `
float ${t2}() {
return sampleTexture(${e2}, halfCR);
}
`;
return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]);
}
const a2 = `
float ${t2}() {
int offset_${e2} = coordsToOffset(TexCoords, ${r2}, ${o2});
vec2 uv = uvFromFlat(${r2}, ${o2}, offset_${e2});
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(a2, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
}
getUnpackedSampler1D(t2, e2, n2) {
const r2 = n2.width, o2 = n2.height;
if (1 === o2 && 1 === r2) {
const n3 = `
float ${t2}(int index) {
return sampleTexture(${e2}, halfCR);
}
`;
return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]);
}
if (1 === o2) {
const n3 = `
float ${t2}(int index) {
vec2 uv = vec2((float(index) + 0.5) / ${r2}.0, 0.5);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]);
}
if (1 === r2) {
const n3 = `
float ${t2}(int index) {
vec2 uv = vec2(0.5, (float(index) + 0.5) / ${o2}.0);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]);
}
const a2 = `
float ${t2}(int index) {
vec2 uv = uvFromFlat(${r2}, ${o2}, index);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(a2, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]);
}
getUnpackedSampler2D(t2, e2, n2) {
const o2 = n2.unpackedShape, u2 = [n2.height, n2.width];
if (null != u2 && r.ArrayUtil.arraysEqual(o2, u2)) {
const n3 = `
float ${t2}(int row, int col) {
vec2 uv = (vec2(row, col) + halfCR) / vec2(${u2[1]}.0, ${u2[0]}.0);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]);
}
const { newShape: c, keptDims: l } = (0, a.squeezeShape)(o2), p = c;
if (p.length < o2.length) {
const r2 = (0, s.squeezeInputShape)(o2, p), a2 = JSON.parse(JSON.stringify(n2));
a2.unpackedShape = r2;
const u3 = ["col", "row"], c2 = `
${this.getUnpackedSamplerFromInput(t2, e2, a2).routineBody}
float ${t2}(int row, int col) {
return ${t2}(${(0, s.getSqueezedParams)(u3, l)});
}
`;
return new i.GlslLibRoutine(c2, ["coordinates.sampleTexture"]);
}
const f = u2[1], d = u2[0];
if (1 === d) {
const n3 = `
float ${t2}(int row, int col) {
int offset_${e2} = coordsToOffset(TexCoords, ${f}, ${d});
float index = dot(vec3(row, col, offset_${e2}), vec3(${o2[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${f}.0);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]);
}
if (1 === f) {
const n3 = `
float ${t2}(int row, int col) {
int offset_${e2} = coordsToOffset(TexCoords, ${f}, ${d});
float index = dot(vec3(row, col, offset_${e2}), vec3(${o2[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${d}.0, 0.5);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]);
}
const h = `
float ${t2}(int row, int col) {
int index = col * ${o2[1]} + row;
vec2 uv = uvFromFlat(${f}, ${d}, index);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(h, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
}
getUnpackedSampler3D(t2, e2, n2) {
const r2 = n2.unpackedShape, o2 = r2[1] * r2[2], u2 = r2[2], { newShape: c, keptDims: l } = (0, a.squeezeShape)(r2), p = c;
if (p.length < r2.length) {
const o3 = (0, s.squeezeInputShape)(r2, p), a2 = ["batch", "col", "row"], u3 = JSON.parse(JSON.stringify(n2));
u3.unpackedShape = o3;
const c2 = this.getUnpackedSamplerFromInput(t2, e2, u3), f2 = l.reverse(), d = `
${c2.routineBody}
float ${t2}(int batch, int row, int col) {
return ${t2}(${(0, s.getSqueezedParams)(a2, f2)});
}
`;
return new i.GlslLibRoutine(d, c2.dependencies);
}
const f = `
float ${t2}(int depth, int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = depth * ${o2} + col * ${u2} + row;
vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(f, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
}
getUnpackedSampler4D(t2, e2, n2) {
const r2 = n2.unpackedShape, o2 = r2[3], a2 = r2[2] * o2, s2 = `
float ${t2}(int row, int col, int depth, int depth2) {
int index = row * ${r2[1] * a2} + col * ${a2} +
depth2 * ${o2} + depth;
vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(s2, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]);
}
getUnpackedSampler5D(t2, e2, n2) {
const r2 = n2.unpackedShape, o2 = r2[4], u2 = r2[3] * o2, c = r2[2] * u2, l = r2[1] * c, { newShape: p, keptDims: f } = (0, a.squeezeShape)(r2);
if (p.length < r2.length) {
const o3 = (0, s.squeezeInputShape)(r2, p), a2 = ["row", "col", "depth", "depth2", "depth3"], u3 = JSON.parse(JSON.stringify(n2));
u3.unpackedShape = o3;
const c2 = `
${this.getUnpackedSamplerFromInput(t2, e2, u3).routineBody}
float ${t2}(int row, int col, int depth, int depth2, int depth3) {
return ${t2}(${(0, s.getSqueezedParams)(a2, f)});
}
`;
return new i.GlslLibRoutine(c2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]);
}
const d = `
float ${t2}(int row, int col, int depth, int depth2, int depth3) {
int index = row * ${l} + col * ${c} + depth * ${u2} +
depth3 * ${o2} + depth2;
vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(d, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]);
}
getUnpackedSampler6D(t2, e2, n2) {
const r2 = n2.unpackedShape, o2 = r2[5], u2 = r2[4] * o2, c = r2[3] * u2, l = r2[2] * c, p = r2[1] * l, { newShape: f, keptDims: d } = (0, a.squeezeShape)(r2);
if (f.length < r2.length) {
const o3 = (0, s.squeezeInputShape)(r2, f), a2 = ["row", "col", "depth", "depth2", "depth3", "depth4"], u3 = JSON.parse(JSON.stringify(n2));
u3.unpackedShape = o3;
const c2 = `
${this.getUnpackedSamplerFromInput(t2, e2, u3).routineBody}
float ${t2}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${t2}(${(0, s.getSqueezedParams)(a2, d)});
}
`;
return new i.GlslLibRoutine(c2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]);
}
const h = `
float ${t2}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = row * ${p} + col * ${l} + depth * ${c} +
depth2 * ${u2} + depth3 * ${o2} + depth4;
vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index);
return sampleTexture(${e2}, uv);
}
`;
return new i.GlslLibRoutine(h, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
}
toVec() {
const t2 = this.context.outputTextureLayout, e2 = t2.shape.length, n2 = t2.strides, r2 = t2.width, o2 = t2.height, a2 = [];
for (let t3 = 0; t3 < e2 - 1; ++t3)
a2.push(`
c[${t3}] = offset / ${n2[t3]};`), a2.push(`
offset -= c[${t3}] * ${n2[t3]};`);
a2.push(`
c[${e2 - 1}] = offset;`);
const s2 = `
void toVec(vec2 texCoords, out int c[${e2}]) {
int offset = coordsToOffset(texCoords, ${r2}, ${o2});
${a2.join("")}
}
void toVec(int offset, out int c[${e2}]) {
${a2.join("")}
}
`;
return { toVec: new i.GlslLibRoutine(s2, ["coordinates.coordsToOffset"]) };
}
valueFrom() {
const t2 = {};
return this.context.programInfo.inputNames.forEach((e2, n2) => {
const r2 = this.context.inputTextureLayouts[n2], o2 = (r2.unpackedShape.length > 0 ? r2.unpackedShape : r2.shape).length;
let a2 = `_${e2}`;
t2[a2] = new i.GlslLibRoutine(this.getValueFromSingle(e2, o2, r2.width, r2.height, false), [`shapeUtils.indicesToOffset${a2}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]), a2 += "_T", t2[a2] = new i.GlslLibRoutine(this.getValueFromSingle(e2, o2, r2.width, r2.height, true), [`shapeUtils.indicesToOffset${a2}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]);
}), t2;
}
getValueFromSingle(t2, e2, n2, r2, i2) {
let a2 = `_${t2}`;
return i2 && (a2 += "_T"), `
float ${a2}(int m[${e2}]) {
int offset = indicesToOffset${a2}(m);
vec2 coords = offsetToCoords(offset, ${n2}, ${r2});
float value = getColorAsFloat(${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${t2}, coords));
return value;
}
`;
}
getPackedValueFrom(t2, e2, n2, r2, i2) {
let a2 = `_${t2}_Pack`;
return i2 && (a2 += "_T"), `
vec4 ${a2}(int m[${e2}]) {
int offset = indicesToOffset_${t2}(m);
vec2 coords = offsetToCoords(offset, ${n2}, ${r2});
return ${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${t2}, coords);
}
`;
}
}
e.CoordsGlslLib = u;
}, 8520: (t, e) => {
"use strict";
var n;
Object.defineProperty(e, "__esModule", { value: true }), 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(t2, e2, n2, r) {
this.glContext = t2, this.programInfo = e2, this.inputTextureLayouts = n2, this.outputTextureLayout = r;
}
}, e.GlslLib = class {
constructor(t2) {
this.context = t2;
}
}, e.GlslLibRoutine = class {
constructor(t2, e2) {
this.routineBody = t2, this.dependencies = e2;
}
}, e.GlslLibRoutineNode = class {
constructor(t2, e2, n2) {
this.name = t2, this.dependencies = n2 || [], e2 && (this.routineBody = e2);
}
addDependency(t2) {
t2 && this.dependencies.push(t2);
}
}, e.TopologicalSortGlslRoutines = class {
static returnOrderedNodes(t2) {
if (!t2 || 0 === t2.length)
return [];
if (1 === t2.length)
return t2;
const e2 = /* @__PURE__ */ new Set(), n2 = /* @__PURE__ */ new Set(), r = new Array();
return this.createOrderedNodes(t2, e2, n2, r), r;
}
static createOrderedNodes(t2, e2, n2, r) {
for (let i = 0; i < t2.length; ++i)
this.dfsTraverse(t2[i], e2, n2, r);
}
static dfsTraverse(t2, e2, n2, r) {
if (!t2 || n2.has(t2.name))
return;
if (e2.has(t2.name))
throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader.");
e2.add(t2.name);
const i = t2.dependencies;
if (i && i.length > 0)
for (let t3 = 0; t3 < i.length; ++t3)
this.dfsTraverse(i[t3], e2, n2, r);
r.push(t2), n2.add(t2.name), e2.delete(t2.name);
}
};
}, 7341: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.EncodingGlslLib = void 0;
const r = n(8520);
class i extends r.GlslLib {
constructor(t2) {
super(t2);
}
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 t2 = i.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : "";
return { encode: new r.GlslLibRoutine(`
highp vec4 encode(highp float f) {
highp float F = abs(f);
highp float Sign = step(0.0,-f);
highp float Exponent = floor(log2(F));
highp float Mantissa = (exp2(- Exponent) * F);
Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));
highp vec4 rgba;
rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0));
rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);
rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));
rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));
${t2}
rgba = rgba / 255.0; // values need to be normalized to [0,1]
return rgba;
}
`) };
}
decodeUint8() {
const t2 = i.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : "";
return { decode: new r.GlslLibRoutine(`
highp float decode(highp vec4 rgba) {
rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]
${t2}
highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;
highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;
highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);
highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));
return Result;
}
`) };
}
static isLittleEndian() {
const t2 = new ArrayBuffer(4), e2 = new Uint32Array(t2), n2 = new Uint8Array(t2);
if (e2[0] = 3735928559, 239 === n2[0])
return true;
if (222 === n2[0])
return false;
throw new Error("unknown endianness");
}
}
e.EncodingGlslLib = i;
}, 9894: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.FragColorGlslLib = void 0;
const r = n(8520), i = n(5060);
class o extends r.GlslLib {
constructor(t2) {
super(t2);
}
getFunctions() {
return Object.assign(Object.assign({}, this.setFragColor()), this.getColorAsFloat());
}
getCustomTypes() {
return {};
}
setFragColor() {
const t2 = (0, i.getGlsl)(this.context.glContext.version);
return { setFragColor: new r.GlslLibRoutine(`
void setFragColor(float value) {
${t2.output} = encode(value);
}
`, ["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: true }), 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(t2) {
const e2 = {};
let r;
for (; null !== (r = n.exec(t2)); ) {
const t3 = r[3].split(",").map((t4) => {
const e3 = t4.trim().split(" ");
return e3 && 2 === e3.length ? { type: e3[0], name: e3[1] } : null;
}).filter((t4) => null !== t4);
e2[r[2]] = { params: t3, body: r[4] };
}
for (const n2 in e2) {
const i = "(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__", n2), o = new RegExp(i, "gm");
for (; null !== (r = o.exec(t2)); ) {
const i2 = r[1], o2 = r[2], a = r[3].split(","), s = i2 ? `${i2} ${o2};` : "";
let u = e2[n2].body, c = "";
e2[n2].params.forEach((t3, e3) => {
t3 && (c += `${t3.type} ${t3.name} = ${a[e3]};
`);
}), u = `${c}
${u}`, u = u.replace("return", `${o2} = `);
const l = `
${s}
{
${u}
}
`;
t2 = t2.replace(r[0], l);
}
}
return t2.replace(n, "");
};
}, 8879: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.GlslPreprocessor = void 0;
const r = n(8520), i = n(2848), o = n(5483), a = n(5060);
e.GlslPreprocessor = class {
constructor(t2, e2, n2, i2) {
this.libs = {}, this.glslLibRoutineDependencyGraph = {}, this.context = new r.GlslContext(t2, e2, n2, i2), Object.keys(o.glslRegistry).forEach((t3) => {
const e3 = new o.glslRegistry[t3](this.context);
this.libs[t3] = e3;
});
const a2 = this.glslLibRoutineDependencyGraph;
for (const t3 in this.libs) {
const e3 = this.libs[t3].getFunctions();
for (const n3 in e3) {
const i3 = t3 + "." + n3;
let o2;
a2[i3] ? (o2 = a2[i3], o2.routineBody = e3[n3].routineBody) : (o2 = new r.GlslLibRoutineNode(i3, e3[n3].routineBody), a2[i3] = o2);
const s = e3[n3].dependencies;
if (s)
for (let t4 = 0; t4 < s.length; ++t4)
if (a2[s[t4]])
o2.addDependency(a2[s[t4]]);
else {
const e4 = new r.GlslLibRoutineNode(s[t4]);
a2[s[t4]] = e4, o2.addDependency(e4);
}
}
}
}
preprocess() {
const t2 = this.context.programInfo;
let e2 = t2.shaderSource;
return this.context.programInfo.hasMain || (e2 = `${e2}
${(0, a.getDefaultFragShaderMain)(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`), e2 = (0, i.replaceInlines)(e2), `${(0, a.getFragShaderPreamble)(this.context.glContext.version)}
${this.getUniforms(t2.inputNames, t2.variables)}
${this.getImports(e2)}
${e2}`;
}
getImports(t2) {
const e2 = this.selectGlslLibRoutinesToBeIncluded(t2);
if (0 === e2.length)
return "";
let n2 = "";
for (let t3 = 0; t3 < e2.length; ++t3) {
if (!e2[t3].routineBody)
throw new Error(`Missing body for the Glsl Library routine: ${e2[t3].name}`);
n2 += e2[t3].routineBody + "\n";
}
return n2;
}
selectGlslLibRoutinesToBeIncluded(t2) {
const e2 = [];
return Object.keys(this.glslLibRoutineDependencyGraph).forEach((n2) => {
const r2 = n2.split(".")[1];
-1 !== t2.indexOf(r2) && e2.push(this.glslLibRoutineDependencyGraph[n2]);
}), r.TopologicalSortGlslRoutines.returnOrderedNodes(e2);
}
getUniforms(t2, e2) {
const n2 = [];
if (t2)
for (const e3 of t2)
n2.push(`uniform sampler2D ${e3};`);
if (e2)
for (const t3 of e2)
n2.push(`uniform ${t3.type} ${t3.name}${t3.arrayLength ? `[${t3.arrayLength}]` : ""};`);
return n2.join("\n");
}
};
}, 5483: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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: true }), e.ShapeUtilsGlslLib = void 0;
const r = n(8520);
class i extends r.GlslLib {
constructor(t2) {
super(t2);
}
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 t2 = this.context.outputTextureLayout.shape.length, e2 = {};
return this.context.programInfo.inputNames.forEach((n2, i2) => {
const o = this.context.inputTextureLayouts[i2].unpackedShape;
if (o.length <= t2) {
const i3 = o.length, a = t2 - i3, s = `bcastIndices_${n2}`;
let u = "";
for (let t3 = 0; t3 < i3; ++t3)
u += `
realIndices[${t3}] = int( mod(float(bcastedIndices[${a + t3}]), ${o[t3]}.0) );
`;
const c = `
void ${s} (int bcastedIndices[${t2}], out int realIndices[${i3}]) {
${u}
}
`;
e2[s] = new r.GlslLibRoutine(c);
}
}), e2;
}
bcastMatmulIndex() {
const t2 = this.context.outputTextureLayout.shape.length, e2 = {};
return this.context.programInfo.inputNames.forEach((n2, i2) => {
const o = this.context.inputTextureLayouts[i2].shape;
if (!(o.length < 2 || o.length > t2)) {
const i3 = o.length, a = t2 - i3, s = `bcastMatmulIndices_${n2}`;
let u = "";
for (let t3 = 0; t3 < i3 - 2; ++t3)
u += `
realIndices[${t3}] = int( mod(float(bcastedIndices[${a + t3}]), ${o[t3]}.0) );
`;
const c = `
void ${s}(int bcastedIndices[${t2}], out int realIndices[${i3}]) {
${u}
realIndices[${i3 - 1}] = bcastedIndices[${t2 - 1}];
realIndices[${i3 - 2}] = bcastedIndices[${t2 - 2}];
}
`;
e2[s] = new r.GlslLibRoutine(c);
}
}), e2;
}
indicesToOffset() {
const t2 = {};
return this.context.programInfo.inputNames.forEach((e2, n2) => {
const o = this.context.inputTextureLayouts[n2].shape, a = this.context.inputTextureLayouts[n2].strides, s = o.length;
let u = `indicesToOffset_${e2}`;
t2[u] = new r.GlslLibRoutine(i.indexToOffsetSingle(u, s, a)), u = `indicesToOffset_${e2}_T`, t2[u] = new r.GlslLibRoutine(i.indexToOffsetSingle(u, s, a.slice().reverse()));
}), t2;
}
static indexToOffsetSingle(t2, e2, n2) {
let r2 = "";
for (let t3 = e2 - 1; t3 >= 0; --t3)
r2 += `
offset += indices[${t3}] * ${n2[t3]};
`;
return `
int ${t2}(int indices[${e2}]) {
int offset = 0;
${r2}
return offset;
}
`;
}
offsetToIndices() {
const t2 = {};
return this.context.programInfo.inputNames.forEach((e2, n2) => {
const o = this.context.inputTextureLayouts[n2].shape, a = this.context.inputTextureLayouts[n2].strides, s = o.length;
let u = `offsetToIndices_${e2}`;
t2[u] = new r.GlslLibRoutine(i.offsetToIndicesSingle(u, s, a)), u = `offsetToIndices_${e2}_T`, t2[u] = new r.GlslLibRoutine(i.offsetToIndicesSingle(u, s, a.slice().reverse()));
}), t2;
}
static offsetToIndicesSingle(t2, e2, n2) {
const r2 = [];
for (let t3 = 0; t3 < e2 - 1; ++t3)
r2.push(`
indices[${t3}] = offset / ${n2[t3]};`), r2.push(`
offset -= indices[${t3}] * ${n2[t3]};`);
return r2.push(`
indices[${e2 - 1}] = offset;`), `
void ${t2}(int offset, out int indices[${e2}]) {
${r2.join("")}
}
`;
}
incrementIndices() {
const t2 = {};
return this.context.programInfo.inputNames.forEach((e2, n2) => {
const i2 = this.context.inputTextureLayouts[n2].shape, o = i2.length, a = `incrementIndices_${e2}`;
let s = "";
for (let t3 = 0; t3 < o; ++t3)
s += `
shape[${t3}] = ${i2[t3]};`;
const u = `
void ${a}(int axis, out int indices[${o}]) {
int shape[${o}];
${s};
for(int i = ${o} -1 ; i >= 0; --i) {
if(i > axis) continue;
indices[i] += 1;
if(indices[i] < shape[i]) {
break;
}
indices[i] = 0;
}
}
`;
t2[a] = new r.GlslLibRoutine(u);
}), t2;
}
}
e.ShapeUtilsGlslLib = i;
}, 5060: (t, e) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2) {
return 1 === t2 ? n : r;
}
e.getGlsl = i, e.getVertexShaderSource = function(t2) {
const e2 = i(t2);
return `${e2.version}
precision highp float;
${e2.attribute} vec3 position;
${e2.attribute} vec2 textureCoord;
${e2.varyingVertex} vec2 TexCoords;
void main()
{
gl_Position = vec4(position, 1.0);
TexCoords = textureCoord;
}`;
}, e.getFragShaderPreamble = function(t2) {
const e2 = i(t2);
return `${e2.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${e2.varyingFrag} vec2 TexCoords;
${e2.outputDeclaration}
const vec2 halfCR = vec2(0.5, 0.5);
// Custom vector types to handle higher dimenalities.
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
int imod(int x, int y) {
return x - y * (x / y);
}
`;
}, e.getDefaultFragShaderMain = function(t2, e2) {
return `
void main() {
int indices[${e2}];
toVec(TexCoords, indices);
vec4 result = vec4(process(indices));
${i(t2).output} = result;
}
`;
};
}, 3891: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.VecGlslLib = void 0;
const r = n(8520);
class i extends r.GlslLib {
constructor(t2) {
super(t2);
}
getCustomTypes() {
return {};
}
getFunctions() {
return Object.assign(Object.assign(Object.assign(Object.assign({}, this.binaryVecFunctions()), this.copyVec()), this.setVecItem()), this.getVecItem());
}
binaryVecFunctions() {
const t2 = this.context.outputTextureLayout.shape.length, e2 = { add: "+=", sub: "-=", mul: "*=", div: "/=" }, n2 = {};
for (const i2 in e2) {
const o = `${i2}Vec`;
let a = "";
for (let n3 = 0; n3 < t2; ++n3)
a += `
dest[${n3}] ${e2[i2]} src[${n3}];
`;
const s = `
void ${o}(int src[${t2}], out int dest[${t2}]) {
${a}
}
`;
n2[o] = new r.GlslLibRoutine(s);
}
return n2;
}
copyVec() {
const t2 = this.context.outputTextureLayout.shape.length;
let e2 = "";
for (let n3 = 0; n3 < t2; ++n3)
e2 += `
dest[${n3}] = src[${n3}];
`;
const n2 = `
void copyVec(int src[${t2}], out int dest[${t2}]) {
${e2}
}
`;
return { copyVec: new r.GlslLibRoutine(n2) };
}
setVecItem() {
const t2 = this.context.outputTextureLayout.shape.length;
let e2 = `
if(index < 0)
index =${t2} + index;
if (index == 0)
m[0] = value;
`;
for (let n3 = 1; n3 < t2 - 1; ++n3)
e2 += `
else if (index == ${n3})
m[${n3}] = value;
`;
e2 += `
else
m[${t2 - 1}] = value;
`;
const n2 = `
void setVecItem(out int m[${t2}], int index, int value) {
${e2}
}
`;
return { setVecItem: new r.GlslLibRoutine(n2) };
}
getVecItem() {
const t2 = this.context.outputTextureLayout.shape.length;
let e2 = `
if(index < 0)
index = ${t2} + index;
if (index == 0)
return m[0];
`;
for (let n3 = 1; n3 < t2 - 1; ++n3)
e2 += `
else if (index == ${n3})
return m[${n3}];
`;
e2 += `
else
return m[${t2 - 1}];
`;
const n2 = `
int getVecItem(int m[${t2}], int index) {
${e2}
}
`;
return { getVecItem: new r.GlslLibRoutine(n2) };
}
}
e.VecGlslLib = i;
}, 8316: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2) {
this.session = t2, this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
}
calculateTextureWidthAndHeight(t2, e2) {
return (0, l.calculateTextureWidthAndHeight)(this.session.layoutStrategy, t2, e2);
}
executeProgram(t2, e2) {
if (e2.length < t2.inputNames.length)
throw new Error(`Input size mustn't be less than ${t2.inputNames.length}.`);
if (t2.inputNames.length !== t2.inputTypes.length)
throw new Error("input names size does not match input types");
const n2 = [];
for (let r3 = 0; r3 < t2.inputNames.length; ++r3)
n2[r3] = this.getOrCreateTextureData(e2[r3], t2.inputTypes[r3]);
const r2 = ((t3, e3) => {
const n3 = e3.map((t4) => `${t4.unpackedShape.join(",")};${t4.width}x${t4.height}`).join("_");
let r3 = t3.name;
return t3.cacheHint && (r3 += "[" + t3.cacheHint + "]"), r3 += ":" + n3, r3;
})(t2, n2);
let i2 = this.session.programManager.getArtifact(r2);
const o2 = i2 ? i2.programInfo : "function" == typeof t2.get ? t2.get() : t2, a2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, o2.output.dims, o2.output.textureType), s2 = this.createTextureData(a2, o2.output.type);
return i2 || (i2 = this.session.programManager.build(o2, n2, s2), this.session.programManager.setArtifact(r2, i2)), this.runProgram(i2, n2, s2), s2;
}
run(t2, e2) {
return this.executeProgram(t2, e2).tensor;
}
runProgram(t2, e2, n2) {
for (let n3 = 0; n3 < e2.length; ++n3)
if (!!e2[n3].isPacked != (t2.programInfo.inputTypes[n3] === p.TextureType.packed))
throw new Error(`input[${n3}] property packed inconsistent`);
if (!!n2.isPacked != (t2.programInfo.output.textureType === p.TextureType.packed))
throw new Error("output property packed inconsistent");
this.session.programManager.run(t2, e2, n2);
}
getOrCreateTextureData(t2, e2) {
let n2 = this.getTextureData(t2.dataId, e2 === p.TextureType.packed);
if (!n2 && (n2 = this.getTextureData(t2.dataId, e2 !== p.TextureType.packed), n2))
return e2 === p.TextureType.packed ? this.pack(n2) : this.unpack(n2);
if (!n2) {
const r2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, t2.dims, e2);
if (e2 === p.TextureType.packedLastDimension) {
const n3 = 1, r3 = 4, i2 = t2.dims;
if (4 === i2.length) {
const o2 = [i2[0], Math.ceil(i2[1] * i2[2] * i2[3] / r3)], a2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, o2, e2);
let s2 = t2.numberData;
if (i2[1] * i2[2] * i2[3] % r3 != 0) {
const e3 = i2[0], o3 = i2[1] * i2[2] * i2[3], a3 = Math.ceil(o3 * n3 / r3) * r3;
s2 = new Float32Array(e3 * a3);
for (let r4 = 0; r4 < e3; ++r4) {
const e4 = r4 * o3, i3 = r4 * a3 + r4 % n3 * o3;
s2.set(t2.numberData.subarray(e4, e4 + o3), i3);
}
}
return this.createTextureData(a2, t2.type, s2, t2, 1);
}
}
if (e2 === p.TextureType.packed) {
const e3 = (0, l.createTextureLayoutFromShape)(this.session.layoutStrategy, t2.dims, 1, [], { reverseWH: true }), r3 = this.createTextureData(e3, t2.type, t2.numberData, t2, 1);
n2 = this.pack(r3);
} else
n2 = this.createTextureData(r2, t2.type, t2.numberData, t2, 1);
}
return n2;
}
createTextureDataFromLayoutBindTensor(t2, e2, n2, r2) {
return this.createTextureData(t2, e2, n2, r2, 1);
}
createTextureData(t2, e2, n2, i2, o2) {
r.Logger.verbose("InferenceHandler", `Creating TextureData: layout:[${JSON.stringify(t2)}]`);
const a2 = this.session.textureManager.createTextureFromLayout(e2, t2, n2, o2);
return this.createTextureDataFromTexture(t2, e2, a2, i2);
}
reshapeUnpacked(t2, e2) {
const n2 = this.getOrCreateTextureData(t2, p.TextureType.unpacked), r2 = { channels: n2.channels, height: n2.height, width: n2.width, shape: 0 !== e2.length ? e2 : [1], strides: o.ShapeUtil.computeStrides(e2), unpackedShape: e2 };
return this.createTextureDataFromTexture(r2, t2.type, n2.texture).tensor;
}
reshapePacked(t2, e2) {
const n2 = this.getOrCreateTextureData(t2, p.TextureType.packed);
if ((0, s.isReshapeCheap)(t2.dims, e2)) {
const r3 = { channels: n2.channels, height: n2.height, width: n2.width, shape: 0 !== e2.length ? e2 : [1], strides: o.ShapeUtil.computeStrides(e2), unpackedShape: e2, isPacked: true };
return this.createTextureDataFromTexture(r3, t2.type, n2.texture).tensor;
}
const r2 = (0, s.processDims3D)(t2.dims), i2 = (0, s.processDims3D)(e2), a2 = this.reshapePacked(t2, r2), u2 = this.run((0, s.createPackedReshape3DProgramInfoLoader)(this, a2, i2), [a2]);
return this.reshapePacked(u2, e2);
}
cast(t2, e2) {
const n2 = this.getOrCreateTextureData(t2, p.TextureType.unpacked);
return this.createTextureDataFromTexture(n2, e2, n2.texture).tensor;
}
createTextureDataFromTexture(t2, e2, n2, r2, o2) {
const a2 = Object.assign(Object.assign({}, t2), { tensor: r2 || new i.Tensor(t2.unpackedShape, e2, (t3) => this.readTexture(a2), async (t3) => this.readTextureAsync(a2), void 0, o2), texture: n2 });
return this.setTextureData(a2.tensor.dataId, a2, t2.isPacked), a2;
}
getTextureData(t2, e2 = false) {
return this.session.isInitializer(t2) ? this.session.getTextureData(t2, e2) : e2 ? this.packedTextureDataCache.get(t2) : this.unpackedTextureDataCache.get(t2);
}
setTextureData(t2, e2, n2 = false) {
this.session.isInitializer(t2) ? this.session.setTextureData(t2, e2, n2) : (n2 ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(t2, e2);
}
isTextureLayoutCached(t2, e2 = false) {
return !!this.getTextureData(t2.dataId, e2);
}
dispose() {
this.session.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach((t2) => this.session.textureManager.releaseTexture(t2)), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach((t2) => this.session.textureManager.releaseTexture(t2)), this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
}
readTexture(t2) {
return t2.isPacked ? this.readTexture(this.unpack(t2)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTexture(t2, t2.tensor.type, t2.channels) : this.session.textureManager.readUint8TextureAsFloat((0, u.encodeAsUint8)(this, t2));
}
async readTextureAsync(t2) {
return t2.isPacked ? this.readTextureAsync(this.unpack(t2)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTextureAsync(t2, t2.tensor.type, t2.channels) : this.session.textureManager.readUint8TextureAsFloat((0, u.encodeAsUint8)(this, t2));
}
pack(t2) {
return this.executeProgram((0, a.createPackProgramInfoLoader)(this, t2.tensor), [t2.tensor]);
}
unpack(t2) {
return this.executeProgram((0, c.createUnpackProgramInfoLoader)(this, t2.tensor), [t2.tensor]);
}
};
}, 1640: function(t, e, n) {
"use strict";
var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) {
void 0 === r2 && (r2 = n2);
var i2 = Object.getOwnPropertyDescriptor(e2, n2);
i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() {
return e2[n2];
} }), Object.defineProperty(t2, r2, i2);
} : function(t2, e2, n2, r2) {
void 0 === r2 && (r2 = n2), t2[r2] = e2[n2];
}), i = this && this.__setModuleDefault || (Object.create ? function(t2, e2) {
Object.defineProperty(t2, "default", { enumerable: true, value: e2 });
} : function(t2, e2) {
t2.default = e2;
}), o = this && this.__importStar || function(t2) {
if (t2 && t2.__esModule)
return t2;
var e2 = {};
if (null != t2)
for (var n2 in t2)
"default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2);
return i(e2, t2), e2;
};
Object.defineProperty(e, "__esModule", { value: true }), 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: true }), 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 = (t2, e2, n2) => (u(e2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: n2.cacheKey, get: () => s(t2, e2, n2) }), e2)]), e.parseBatchNormalizationAttributes = (t2) => {
const e2 = t2.attributes.getFloat("epsilon", 1e-5), n2 = t2.attributes.getFloat("momentum", 0.9), i2 = t2.attributes.getInt("spatial", 1);
return (0, r.createAttributeWithCacheKey)({ epsilon: e2, momentum: n2, spatial: i2 });
};
const s = (t2, e2, n2) => {
const r2 = (0, i.getGlsl)(t2.session.backend.glContext.version), s2 = e2[0].dims.length, [u2, c] = t2.calculateTextureWidthAndHeight(e2[1].dims, o.TextureType.unpacked), l = `
float process(int[${s2}] indices) {
vec2 position = offsetToCoords(indices[1], ${u2}, ${c});
float scale = getColorAsFloat(${r2.texture2D}(Scale, position));
float mean = getColorAsFloat(${r2.texture2D}(Mean, position));
float variance = getColorAsFloat(${r2.texture2D}(Variance, position));
float b = getColorAsFloat(${r2.texture2D}(B, position));
return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n2.epsilon})) ) + b;
}`;
return Object.assign(Object.assign({}, a), { output: { dims: e2[0].dims, type: e2[0].type, textureType: o.TextureType.unpacked }, shaderSource: l });
}, u = (t2) => {
if (!t2 || 5 !== t2.length)
throw new Error("BatchNormalization requires 5 inputs.");
const e2 = t2[0], n2 = t2[1], r2 = t2[2], i2 = t2[3], o2 = t2[4];
if (e2.dims.length < 3 || 1 !== n2.dims.length || 1 !== r2.dims.length || 1 !== i2.dims.length || 1 !== o2.dims.length)
throw new Error("invalid input shape.");
if (n2.dims[0] !== e2.dims[1] || r2.dims[0] !== e2.dims[1] || i2.dims[0] !== e2.dims[1] || o2.dims[0] !== e2.dims[1])
throw new Error("invalid input shape.");
if ("float32" !== e2.type && "float64" !== e2.type || "float32" !== n2.type && "float64" !== n2.type || "float32" !== r2.type && "float64" !== r2.type || "float32" !== i2.type && "float64" !== i2.type || "float32" !== o2.type && "float64" !== o2.type)
throw new Error("invalid input tensor types.");
};
}, 7839: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 t2 = "add_";
return { body: `
float ${t2}(float a, float b) {
return a + b;
}
vec4 ${t2}(vec4 v1, vec4 v2) {
return v1 + v2;
}
`, name: t2, type: i.FunctionType.ValueBased };
}
function u() {
const t2 = "div_";
return { body: `
float ${t2}(float a, float b) {
return a / b;
}
vec4 ${t2}(vec4 v1, vec4 v2) {
return v1 / v2;
}
`, name: t2, type: i.FunctionType.ValueBased };
}
function c() {
const t2 = "mul_";
return { body: `
float ${t2}(float a, float b) {
return a * b;
}
vec4 ${t2}(vec4 v1, vec4 v2) {
return v1 * v2;
}
`, name: t2, type: i.FunctionType.ValueBased };
}
function l() {
const t2 = "sub_";
return { body: `
float ${t2}(float a, float b) {
return a - b;
}
vec4 ${t2}(vec4 v1, vec4 v2) {
return v1 - v2;
}
`, name: t2, type: i.FunctionType.ValueBased };
}
function p() {
const t2 = "equal_";
return { body: `
float ${t2}(float a, float b) {
return float(a == b);
}
vec4 ${t2}(vec4 v1, vec4 v2) {
return vec4(equal(v1, v2));
}
`, name: t2, type: i.FunctionType.ValueBased };
}
function f() {
const t2 = "greater_";
return { body: `
float ${t2}(float a, float b) {
return float(a > b);
}
vec4 ${t2}(vec4 v1, vec4 v2) {
return vec4( v1.r > v2.r ,
v1.g > v2.g,
v1.b > v2.b,
v1.a > v2.a );
}
`, name: t2, type: i.FunctionType.ValueBased };
}
function d() {
const t2 = "less_";
return { body: `
float ${t2}(float a, float b) {
return float(a < b);
}
vec4 ${t2}(vec4 v1, vec4 v2) {
return vec4( v1.r < v2.r ,
v1.g < v2.g,
v1.b < v2.b,
v1.a < v2.a );
}
`, name: t2, type: i.FunctionType.ValueBased };
}
function h() {
const t2 = "and_";
return { body: `
float ${t2}(float a, float b) {
return float( bool(a) && bool(b) );
}
vec4 ${t2}(vec4 v1, vec4 v2) {
bvec4 b1 = bvec4(v1);
bvec4 b2 = bvec4(v2);
return vec4( b1.r && b2.r ,
b1.g && b2.g,
b1.b && b2.b,
b1.a && b2.a );
}
`, name: t2, type: i.FunctionType.ValueBased };
}
function g() {
const t2 = "or_";
return { body: `
float ${t2}(float a, float b) {
return float( bool(a) || bool(b) );
}
vec4 ${t2}(vec4 v1, vec4 v2) {
bvec4 b1 = bvec4(v1);
bvec4 b2 = bvec4(v2);
return vec4( b1.r || b2.r ,
b1.g || b2.g,
b1.b || b2.b,
b1.a || b2.a );
}
`, name: t2, type: i.FunctionType.ValueBased };
}
function b() {
const t2 = "xor_";
return { body: `
float ${t2}(float a, float b) {
return float( bool(a) ^^ bool(b) );
}
vec4 ${t2}(vec4 v1, vec4 v2) {
bvec4 b1 = bvec4(v1);
bvec4 b2 = bvec4(v2);
return vec4( b1.r ^^ b2.r ,
b1.g ^^ b2.g,
b1.b ^^ b2.b,
b1.a ^^ b2.a );
}
`, name: t2, type: i.FunctionType.ValueBased };
}
function m() {
return function(t2) {
const e2 = `${t2}_`;
return { body: `
float ${e2}(float a, float b) {
return ${t2}(a, b);
}
vec4 ${e2}(vec4 v1, vec4 v2) {
return ${t2}(v1, v2);
}
`, name: e2, type: i.FunctionType.ValueBased };
}("pow");
}
function y() {
const t2 = "prelu_";
return { body: `
float ${t2}(float a, float b) {
return a < 0.0 ? a * b: a;
}
vec4 ${t2}(vec4 v1, vec4 v2) {
return vec4(
v1.r < 0.0 ? v1.r * v2.r: v1.r,
v1.g < 0.0 ? v1.g * v2.g: v1.g,
v1.b < 0.0 ? v1.b * v2.b: v1.b,
v1.a < 0.0 ? v1.a * v2.a: v1.a
);
}
`, name: t2, 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 _ = (t2, e2, n2, r2 = e2[0].type, i2) => {
const o2 = t2.session.pack ? a.TextureType.packed : a.TextureType.unpacked;
return { name: n2.name, inputNames: ["A", "B"], inputTypes: [o2, o2], cacheHint: i2, get: () => v(t2, e2, n2, r2) };
}, v = (t2, e2, n2, i2 = e2[0].type) => {
const s2 = t2.session.pack ? a.TextureType.packed : a.TextureType.unpacked, u2 = !r.ShapeUtil.areEqual(e2[0].dims, e2[1].dims);
let c2 = e2[0].dims;
const l2 = t2.session.pack;
if (u2) {
const a2 = r.BroadcastUtil.calcShape(e2[0].dims, e2[1].dims, false);
if (!a2)
throw new Error("Can't perform binary op on the given tensors");
c2 = a2;
const u3 = c2.length, p3 = 0 !== e2[0].dims.length ? e2[0].dims.length : 1, f3 = 0 !== e2[1].dims.length ? e2[1].dims.length : 1, d2 = 0 !== e2[0].dims.length ? "bcastIndices_A(indices, aindices);" : "aindices[0] = 0;", h2 = 0 !== e2[1].dims.length ? "bcastIndices_B(indices, bindices);" : "bindices[0] = 0;", g2 = (0, o.getGlsl)(t2.session.backend.glContext.version), b2 = l2 ? `
${n2.body}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = ${n2.name}(a, b);
${g2.output} = result;
}` : `
${n2.body}
float process(int indices[${u3}]) {
int aindices[${p3}];
int bindices[${f3}];
${d2}
${h2}
return ${n2.name}(_A(aindices), _B(bindices));
}`;
return { name: n2.name, inputNames: ["A", "B"], inputTypes: [s2, s2], output: { dims: c2, type: i2, textureType: s2 }, shaderSource: b2, hasMain: l2 };
}
const p2 = (0, o.getGlsl)(t2.session.backend.glContext.version), f2 = `
${n2.body}
void main() {
vec4 v1 = ${p2.texture2D}(A, TexCoords);
vec4 v2 = ${p2.texture2D}(B, TexCoords);
vec4 result = ${n2.name}(v1, v2);
${p2.output} = result;
}
`;
return { name: n2.name, inputNames: ["A", "B"], inputTypes: [s2, s2], output: { dims: e2[0].dims, type: i2, textureType: s2 }, shaderSource: f2, hasMain: true };
};
e.add = (t2, e2) => [t2.run(_(t2, e2, s()), e2)], e.and = (t2, e2) => [t2.run(_(t2, e2, h(), "bool"), e2)], e.div = (t2, e2) => [t2.run(_(t2, e2, u()), e2)], e.equal = (t2, e2) => [t2.run(_(t2, e2, p(), "bool"), e2)], e.greater = (t2, e2) => [t2.run(_(t2, e2, f(), "bool"), e2)], e.less = (t2, e2) => [t2.run(_(t2, e2, d(), "bool"), e2)], e.mul = (t2, e2) => [t2.run(_(t2, e2, c()), e2)], e.or = (t2, e2) => [t2.run(_(t2, e2, g(), "bool"), e2)], e.pow = (t2, e2) => [t2.run(_(t2, e2, m()), e2)], e.pRelu = (t2, e2) => [t2.run(_(t2, e2, y()), e2)], e.sub = (t2, e2) => [t2.run(_(t2, e2, l()), e2)], e.xor = (t2, e2) => [t2.run(_(t2, e2, b(), "bool"), e2)];
}, 4196: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseCastAttributes = e.cast = void 0;
const r = n(2517);
e.cast = (t2, e2, n2) => (i(e2), [t2.cast(e2[0], n2)]), e.parseCastAttributes = (t2) => r.ProtoUtil.tensorDataTypeFromProto(t2.attributes.getInt("to"));
const i = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Cast requires 1 input.");
if ("string" === t2[0].type)
throw new Error("Invalid input type.");
};
}, 1163: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.createPackedConcatProgramInfoLoader = void 0;
const r = n(5060), i = n(2039), o = n(9390), a = n(2827);
e.createPackedConcatProgramInfoLoader = (t2, e2, n2) => {
const u = (c = e2.length, l = n2.cacheKey, { name: "Concat (packed)", inputNames: Array.from({ length: c }, (t3, e3) => `X${e3}`), inputTypes: Array(c).fill(i.TextureType.packed), cacheHint: l });
var c, l;
return Object.assign(Object.assign({}, u), { get: () => ((t3, e3, n3, u2) => {
const c2 = n3[0].dims.slice();
if (u2 >= c2.length || u2 < -1 * c2.length)
throw new Error("axis specified for concat doesn't match input dimensionality");
u2 < 0 && (u2 = c2.length + u2);
const l2 = c2.slice(0);
for (let t4 = 1; t4 < n3.length; t4++) {
const e4 = n3[t4].dims.slice();
for (let t5 = 0; t5 < c2.length; t5++)
if (t5 === u2)
l2[u2] += e4[t5];
else if (c2[t5] !== e4[t5])
throw new Error("non concat dimensions must match");
}
const p = l2.length, f = (0, a.getChannels)("coords", p), d = (0, o.getCoordsDataType)(p), h = (0, a.unpackFromChannel)(), g = n3.map((t4) => t4.dims), b = (0, o.getGlChannels)(p), m = new Array(g.length - 1);
m[0] = g[0][u2];
for (let t4 = 1; t4 < m.length; t4++)
m[t4] = m[t4 - 1] + g[t4][u2];
const y = b[u2], _ = b.slice(-2), v = b.join();
let w = `if (${y} < ${m[0]}) {
return getChannel(
getX0(${v}), vec2(${_.join()}));
}`;
for (let t4 = 1; t4 < m.length; t4++) {
const e4 = m[t4 - 1];
w += `
if (${y} < ${m[t4]} && ${y} >= ${m[t4 - 1]}) {
return getChannel(
getX${t4}(${s(b, y, e4)}),
vec2(${s(_, y, e4)}));
}`;
}
const x = m.length, T = m[m.length - 1];
w += `
return getChannel(
getX${x}(${s(b, y, T)}),
vec2(${s(_, y, T)}));`;
const S = (0, r.getGlsl)(t3.session.backend.glContext.version), O = `
${h}
float getValue(${b.map((t4) => "int " + t4)}) {
${w}
}
void main() {
${d} coords = getOutputCoords();
int lastDim = coords.${b[p - 1]};
coords.${b[p - 1]} = coords.${b[p - 2]};
coords.${b[p - 2]} = lastDim;
vec4 result = vec4(getValue(${f}), 0., 0., 0.);
${f[p - 1]} = ${f[p - 1]} + 1;
if (${f[p - 1]} < ${l2[p - 1]}) {
result.g = getValue(${f});
}
${f[p - 2]} = ${f[p - 2]} + 1;
if (${f[p - 2]} < ${l2[p - 2]}) {
result.a = getValue(${f});
}
${f[p - 1]} = ${f[p - 1]} - 1;
if (${f[p - 2]} < ${l2[p - 2]} &&
${f[p - 1]} < ${l2[p - 1]}) {
result.b = getValue(${f});
}
${S.output} = result;
}
`;
return Object.assign(Object.assign({}, e3), { output: { dims: l2, type: n3[0].type, textureType: i.TextureType.packed }, shaderSource: O, hasMain: true });
})(t2, u, e2, n2.axis) });
};
const s = (t2, e2, n2) => {
const r2 = t2.indexOf(e2);
return t2.map((t3, e3) => e3 === r2 ? `${t3} - ${n2}` : t3).join();
};
}, 2069: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseConcatAttributes = e.concat = void 0;
const r = n(246), i = n(2039), o = n(1163);
e.concat = (t2, e2, n2) => (p(e2), t2.session.pack && e2[0].dims.length > 1 ? [t2.run((0, o.createPackedConcatProgramInfoLoader)(t2, e2, n2), e2)] : [t2.run(a(t2, e2, n2), e2)]);
const a = (t2, e2, n2) => {
const r2 = (o2 = e2.length, a2 = n2.cacheKey, { name: "Concat", inputNames: Array.from({ length: o2 }, (t3, e3) => `X${e3}`), inputTypes: Array(o2).fill(i.TextureType.unpacked), cacheHint: a2 });
var o2, a2;
return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => {
const o3 = n3[0].dims.slice();
if (r3 >= o3.length || r3 < -1 * o3.length)
throw new Error("axis specified for concat doesn't match input dimensionality");
r3 < 0 && (r3 = o3.length + r3);
const a3 = o3.slice(0);
for (let t4 = 1; t4 < n3.length; t4++) {
const e4 = n3[t4].dims.slice();
for (let t5 = 0; t5 < o3.length; t5++)
if (t5 === r3)
a3[r3] += e4[t5];
else if (o3[t5] !== e4[t5])
throw new Error("non concat dimensions must match");
}
const p2 = a3.length, f = new Array(n3.length);
let d = 0;
for (let t4 = 0; t4 < f.length; ++t4)
d += n3[t4].dims[r3], f[t4] = d;
let h = "";
h = n3.length < 5 ? s(f) : u(f);
const g = `
${c(n3.length, p2)}
${l(f)}
${h}
float process(int indices[${p2}]) {
int textureIndex = getTextureWhereDataResides (indices[${r3}]);
if(textureIndex != 0) {
indices[${r3}] = indices[${r3}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));
}
return fetchDataFromCorrectTexture(textureIndex, indices);
}`;
return Object.assign(Object.assign({}, e3), { output: { dims: a3, type: n3[0].type, textureType: i.TextureType.unpacked }, shaderSource: g });
})(0, r2, e2, n2.axis) });
}, s = (t2) => `int getTextureWhereDataResides(int index) {
${t2.map((t3, e2) => `if(index<${t3}) {return ${e2};}
`).join("")}
}`, u = (t2) => s(t2), c = (t2, e2) => {
const n2 = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e2}]) {`];
for (let e3 = 0; e3 < t2; ++e3)
0 === e3 ? n2.push(` if (textureIndex == ${e3}) { return _X${e3}(indices); }`) : e3 === t2 - 1 ? n2.push(` else { return _X${e3}(indices); }`) : n2.push(` else if (textureIndex == ${e3}) { return _X${e3}(indices); }`);
return n2.push(" }"), n2.join("\n");
}, l = (t2) => {
const e2 = ["int getSizeInConcatAxisValueFromIndex(int index) {"];
for (let n2 = 0; n2 < t2.length; ++n2)
0 === n2 ? e2.push(` if (index == ${n2}) { return ${t2[n2]}; }`) : n2 === t2.length - 1 ? e2.push(` else { return ${t2[n2]}; }`) : e2.push(` else if (index == ${n2}) { return ${t2[n2]}; }`);
return e2.push(" }"), e2.join("\n");
};
e.parseConcatAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis") });
const p = (t2) => {
if (!t2 || t2.length < 1)
throw new Error("too few inputs");
const e2 = t2[0].type, n2 = t2[0].dims.length;
if ("string" === e2)
throw new Error("string tensor is not supported yet");
for (const r2 of t2) {
if (r2.type !== e2)
throw new Error("input tensors should be one type");
if (r2.dims.length !== n2)
throw new Error("input tensors should have the same shape");
}
};
}, 4770: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.createUnpackedGroupedConvProgramInfoLoader = void 0;
const r = n(6231), i = n(5060), o = n(2039), a = n(8138), s = n(2823);
e.createUnpackedGroupedConvProgramInfoLoader = (t2, e2, n2) => {
const u = (c = e2.length > 2, l = n2.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: () => ((t3, e3, n3, u2) => {
const c2 = e3.length > 2 ? "value += getBias(output_channel);" : "", l2 = e3[0].dims.slice(), p = e3[1].dims.slice(), f = p[0] / u2.group;
r.Logger.verbose("GroupedConv", `autpPad:${u2.autoPad}, dilations:${u2.dilations}, group:${u2.group}, kernelShape:${u2.kernelShape}, pads:${u2.pads}, strides:${u2.strides}`);
const d = (0, a.calculateOutputShape)(l2, p, u2.dilations, u2.pads, u2.strides), h = (0, i.getGlsl)(t3.session.backend.glContext.version), { activationFunction: g, applyActivation: b } = (0, s.getActivationSnippet)(u2), m = `
const ivec2 strides = ivec2(${u2.strides[0]}, ${u2.strides[1]});
const ivec2 pads = ivec2(${u2.pads[0]}, ${u2.pads[1]});
${g}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
int output_channel = coords.y;
ivec2 xRCCorner = coords.zw * strides - pads;
int group_id = output_channel / ${f};
float value = 0.0;
for (int wInChannel = 0; wInChannel < ${p[1]}; wInChannel++) {
int input_channel = group_id * ${p[1]} + wInChannel;
for (int wHeight = 0; wHeight < ${p[2]}; wHeight++) {
int xHeight = xRCCorner.x + wHeight * ${u2.dilations[0]};
if (xHeight < 0 || xHeight >= ${l2[2]}) {
continue;
}
for (int wWidth = 0; wWidth < ${p[3]}; wWidth++) {
int xWidth = xRCCorner.y + wWidth * ${u2.dilations[1]};
if (xWidth < 0 || xWidth >= ${l2[3]}) {
continue;
}
float xVal = getX(batch, input_channel, xWidth, xHeight);
float wVal = getW(output_channel, wInChannel, wWidth, wHeight);
value += xVal*wVal;
}
}
}
${c2}
${b}
${h.output} = vec4(value, .0, .0, .0);
}
`;
return Object.assign(Object.assign({}, n3), { output: { dims: d, type: e3[0].type, textureType: o.TextureType.unpacked }, shaderSource: m, hasMain: true });
})(t2, e2, u, n2) });
};
}, 1386: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.conv2DPacked = e.conv2DPackedPointwise = void 0;
const r = n(8138), i = n(8555), o = n(708);
e.conv2DPackedPointwise = (t2, e2, n2) => {
const i2 = e2[0].dims, a = e2[1].dims, s = (0, r.calculateOutputShape)(i2, a, n2.dilations, n2.pads, n2.strides), u = t2.reshapePacked(e2[0], [i2[1], i2[2] * i2[3]]), c = t2.reshapePacked(e2[1], [a[0], a[1]]), l = e2.length > 2 ? [c, u, e2[2]] : [c, u], p = t2.run((0, o.createPackedMatmulProgramInfoLoader)(t2, l, n2), l);
return t2.reshapePacked(p, s);
}, e.conv2DPacked = (t2, e2, n2) => {
const a = e2[0].dims, s = e2[1].dims, u = (0, r.calculateOutputShape)(a, s, n2.dilations, n2.pads, n2.strides), c = t2.run((0, i.createPackedIm2ColProgramInfoLoader)(t2, e2[0], e2[1], u, n2), [e2[0]]), l = t2.reshapePacked(e2[1], [s[0], s[1] * s[2] * s[3]]), p = 3 === e2.length ? [l, c, e2[2]] : [l, c], f = t2.run((0, o.createPackedMatmulProgramInfoLoader)(t2, p, n2), p);
return t2.reshapePacked(f, u);
};
}, 9663: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseConvTransposeAttributes = e.convTranspose = void 0;
const r = n(246), i = n(5060), o = n(2039), a = n(2823), s = (t2, e2, n2, r2, i2, o2) => (t2 - 1) * e2 + n2 + (r2 - 1) * i2 + 1 - o2, u = (t2, e2, n2, r2, i2) => {
const o2 = Math.floor(t2 / 2);
"SAME_UPPER" === e2 ? (n2[r2] = o2, n2[i2] = t2 - o2) : "SAME_LOWER" === e2 && (n2[r2] = t2 - o2, n2[i2] = o2);
};
e.convTranspose = (t2, e2, n2) => (f(e2, n2), c(t2, e2, n2));
const c = (t2, e2, n2) => {
const r2 = p(n2, e2);
return [l(t2, e2, r2)];
}, l = (t2, e2, n2) => t2.run(((t3, e3, n3) => {
const r2 = (s2 = e3.length > 2, u2 = n3.cacheKey, { name: "ConvTranspose", inputNames: s2 ? ["X", "W", "B"] : ["X", "W"], inputTypes: s2 ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], cacheHint: u2 });
var s2, u2;
return Object.assign(Object.assign({}, r2), { get: () => ((t4, e4, n4, r3) => {
const s3 = e4.length > 2 ? "getB(output_channel)" : "0.0", u3 = e4[0].dims, c2 = e4[1].dims, l2 = c2[1], p2 = c2[0] / r3.group, f2 = [e4[0].dims[0], e4[1].dims[1] * r3.group, ...r3.outputShape], d = (0, i.getGlsl)(t4.session.backend.glContext.version), { activationFunction: h, applyActivation: g } = (0, a.getActivationSnippet)(r3), b = `
const ivec2 strides = ivec2(${r3.strides[0]}, ${r3.strides[1]});
const ivec2 pads = ivec2(${r3.pads[0]}, ${r3.pads[1]});
${h}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
int output_channel = coords.y;
ivec2 loc = coords.zw + pads;
int group_id = output_channel / ${l2};
int wOutChannel = output_channel - group_id * ${l2};
float value = ${s3};
for (int inChannelOffset = 0; inChannelOffset < ${p2}; inChannelOffset++) {
int input_channel = group_id * ${p2} + inChannelOffset;
for (int wWOff = 0; wWOff < ${c2[2]}; wWOff++) {
for (int wHOff = 0; wHOff < ${c2[3]}; wHOff++) {
ivec2 wOff = ivec2(wWOff * ${r3.dilations[0]}, wHOff * ${r3.dilations[1]});
ivec2 wLoc = loc - wOff;
ivec2 wLocIn = wLoc / strides;
if (
wLocIn * strides == wLoc &&
wLocIn.x >= 0 && wLocIn.x < ${u3[2]} &&
wLocIn.y >= 0 && wLocIn.y < ${u3[3]}
) {
float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);
float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);
value += xVal * wVal;
}
}
}
}
${g}
${d.output} = vec4(value, .0, .0, .0);
}
`;
return Object.assign(Object.assign({}, n4), { output: { dims: f2, type: e4[0].type, textureType: o.TextureType.unpacked }, shaderSource: b, hasMain: true });
})(t3, e3, r2, n3) });
})(t2, e2, n2), e2), p = (t2, e2) => {
const n2 = t2.kernelShape.slice();
if (0 === t2.kernelShape.length)
for (let t3 = 2; t3 < e2[1].dims.length; ++t3)
n2.push(e2[1].dims[t3]);
const r2 = t2.pads.slice(), i2 = t2.outputShape.slice();
((t3, e3, n3, r3, i3, o3, a2, c2) => {
const l2 = t3.length - 2, p2 = 0 === c2.length;
for (let f2 = 0; f2 < l2; ++f2) {
const d = p2 ? t3[f2 + 2] * o3[f2] : c2[f2], h = s(t3[f2 + 2], o3[f2], i3[f2], e3[f2], n3[f2], d);
u(h, r3, i3, f2, f2 + l2), p2 && c2.push(o3[f2] * (t3[f2 + 2] - 1) + a2[f2] + (e3[f2] - 1) * n3[f2] + 1 - i3[f2] - i3[f2 + l2]);
}
})(e2[0].dims, n2, t2.dilations, t2.autoPad, r2, t2.strides, t2.outputPadding, i2);
const o2 = Object.assign({}, t2);
return Object.assign(o2, { kernelShape: n2, pads: r2, outputShape: i2, cacheKey: t2.cacheKey }), o2;
};
e.parseConvTransposeAttributes = (t2) => {
const e2 = t2.attributes, n2 = (0, a.parseInternalActivationAttributes)(e2), i2 = e2.getString("auto_pad", "NOTSET"), o2 = e2.getInts("dilations", [1, 1]), s2 = e2.getInt("group", 1), u2 = e2.getInts("kernel_shape", []), c2 = e2.getInts("output_padding", [0, 0]), l2 = e2.getInts("output_shape", []), p2 = e2.getInts("pads", [0, 0, 0, 0]), f2 = e2.getInts("strides", [1, 1]);
return (0, r.createAttributeWithCacheKey)(Object.assign({ autoPad: i2, dilations: o2, group: s2, kernelShape: u2, outputPadding: c2, outputShape: l2, pads: p2, strides: f2 }, n2));
};
const f = (t2, e2) => {
if (!t2 || 2 !== t2.length && 3 !== t2.length)
throw new Error("Conv requires 2 or 3 inputs");
if (4 !== t2[0].dims.length || 4 !== t2[1].dims.length)
throw new Error("currently only support 2-dimensional conv");
if (t2[0].dims[1] !== t2[1].dims[0])
throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");
const n2 = t2[1].dims[1] * e2.group;
if (3 === t2.length && (1 !== t2[2].dims.length || t2[2].dims[0] !== n2))
throw new Error("invalid bias");
const r2 = t2[0].dims.length - 2;
if (e2.dilations.length !== r2)
throw new Error(`dilations should be ${r2}D`);
if (e2.strides.length !== r2)
throw new Error(`strides should be ${r2}D`);
if (e2.pads.length !== 2 * r2)
throw new Error(`pads should be ${2 * r2}D`);
if (e2.outputPadding.length !== r2)
throw new Error(`output_padding should be ${r2}D`);
if (0 !== e2.kernelShape.length && e2.kernelShape.length !== t2[1].dims.length - 2)
throw new Error("invalid kernel shape");
if (0 !== e2.outputShape.length && e2.outputShape.length !== t2[0].dims.length - 2)
throw new Error("invalid output shape");
if ("float32" !== t2[0].type || "float32" !== t2[1].type)
throw new Error("ConvTranspose input(X,W) should be float tensor");
if (3 === t2.length && "float32" !== t2[2].type)
throw new Error("ConvTranspose input(bias) should be float tensor");
};
}, 8138: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2, n2, r2, i2) => {
const o2 = t2[0], a2 = t2.slice(2), s2 = a2.length, u2 = e2[0], c2 = e2.slice(2).map((t3, e3) => t3 + (t3 - 1) * (n2[e3] - 1)), l2 = a2.map((t3, e3) => t3 + r2[e3] + r2[e3 + s2]).map((t3, e3) => Math.floor((t3 - c2[e3] + i2[e3]) / i2[e3]));
return [o2, u2].concat(...l2);
}, e.conv = (t2, e2, n2) => (g(e2, n2), p(t2, e2, n2));
const p = (t2, e2, n2) => {
const r2 = h(n2, e2), i2 = t2.session.pack, s2 = 1 === r2.kernelShape[0] && 1 === r2.kernelShape[1];
return r2.group > 1 ? [t2.run((0, o.createUnpackedGroupedConvProgramInfoLoader)(t2, e2, r2), e2)] : s2 && i2 ? [f(t2, e2, r2)] : i2 && 4 === e2[0].dims.length && 1 === e2[0].dims[0] && !s2 ? [(0, a.conv2DPacked)(t2, e2, r2)] : [d(t2, e2, r2)];
}, f = (t2, n2, r2) => {
const i2 = n2[0].dims, o2 = n2[1].dims, a2 = (0, e.calculateOutputShape)(i2, o2, r2.dilations, r2.pads, r2.strides), s2 = t2.reshapeUnpacked(n2[0], [i2[1], i2[2] * i2[3]]), u2 = t2.reshapeUnpacked(n2[1], [o2[0], o2[1]]), c2 = n2.length > 2 ? [u2, s2, n2[2]] : [u2, s2], p2 = t2.run((0, l.createMatmulProgramInfoLoader)(c2, r2), c2);
return t2.reshapeUnpacked(p2, a2);
}, d = (t2, n2, r2) => {
const i2 = n2[0].dims, o2 = n2[1].dims, a2 = (0, e.calculateOutputShape)(i2, o2, r2.dilations, r2.pads, r2.strides), u2 = t2.run((0, c.createIm2ColProgramInfoLoader)(t2, n2[0], n2[1], a2, r2), [n2[0]]), l2 = 3 === n2.length ? [u2, n2[1], n2[2]] : [u2, n2[1]];
return t2.run((0, s.createDotProductProgramInfoLoader)(t2, n2, a2, r2), l2);
}, h = (t2, e2) => {
const n2 = t2.kernelShape.slice();
if (0 === t2.kernelShape.length)
for (let t3 = 2; t3 < e2[1].dims.length; ++t3)
n2.push(e2[1].dims[t3]);
const r2 = t2.pads.slice();
i.PoolConvUtil.adjustPadsBasedOnAutoPad(e2[0].dims, t2.strides, t2.dilations, n2, r2, t2.autoPad);
const o2 = Object.assign({}, t2);
return Object.assign(o2, { kernelShape: n2, pads: r2, cacheKey: t2.cacheKey }), o2;
};
e.parseConvAttributes = (t2) => {
const e2 = t2.attributes, n2 = (0, u.parseInternalActivationAttributes)(e2), i2 = e2.getString("auto_pad", "NOTSET"), o2 = e2.getInts("dilations", [1, 1]), a2 = e2.getInt("group", 1), s2 = e2.getInts("kernel_shape", []), c2 = e2.getInts("pads", [0, 0, 0, 0]), l2 = e2.getInts("strides", [1, 1]);
return (0, r.createAttributeWithCacheKey)(Object.assign({ autoPad: i2, dilations: o2, group: a2, kernelShape: s2, pads: c2, strides: l2 }, n2));
};
const g = (t2, e2) => {
if (!t2 || 2 !== t2.length && 3 !== t2.length)
throw new Error("Conv requires 2 or 3 inputs");
if (4 !== t2[0].dims.length || 4 !== t2[1].dims.length)
throw new Error("currently only support 2-dimensional conv");
if (t2[0].dims[1] !== t2[1].dims[1] * e2.group)
throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");
if (3 === t2.length && (1 !== t2[2].dims.length || t2[1].dims[0] !== t2[2].dims[0]))
throw new Error("invalid bias");
const n2 = t2[0].dims.length - 2;
if (e2.dilations.length !== n2)
throw new Error(`dilations should be ${n2}D`);
if (e2.strides.length !== n2)
throw new Error(`strides should be ${n2}D`);
if (e2.pads.length !== 2 * n2)
throw new Error(`pads should be ${2 * n2}D`);
if (0 !== e2.kernelShape.length && e2.kernelShape.length !== t2[1].dims.length - 2)
throw new Error("invalid kernel shape");
if ("float32" !== t2[0].type || "float32" !== t2[1].type)
throw new Error("Conv input(X,W) should be float tensor");
if (3 === t2.length && "float32" !== t2[2].type)
throw new Error("Conv input(bias) should be float tensor");
};
}, 5193: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseDepthToSpaceAttributes = e.depthToSpace = void 0;
const r = n(3738);
e.depthToSpace = (t2, e2, n2) => {
i(e2);
const o = n2.blocksize, a = o * o, s = "DCR" === n2.mode ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3], u = "DCR" === n2.mode ? [e2[0].dims[0], o, o, e2[0].dims[1] / a, e2[0].dims[2], e2[0].dims[3]] : [e2[0].dims[0], e2[0].dims[1] / a, o, o, e2[0].dims[2], e2[0].dims[3]], c = t2.reshapeUnpacked(e2[0], u), l = { perm: s, cacheKey: `${s}` }, [p] = (0, r.transpose)(t2, [c], l), f = [e2[0].dims[0], e2[0].dims[1] / a, e2[0].dims[2] * o, e2[0].dims[3] * o];
return [t2.reshapeUnpacked(p, f)];
}, e.parseDepthToSpaceAttributes = (t2) => {
const e2 = t2.attributes.getInt("blocksize");
if (e2 < 1)
throw new Error(`blocksize must be >= 1, but got : ${e2} for DepthToSpace`);
const n2 = t2.attributes.getString("mode", "DCR");
if ("DCR" !== n2 && "CRD" !== n2)
throw new Error(`unrecognized mode: ${n2} for DepthToSpace`);
return { mode: n2, blocksize: e2 };
};
const i = (t2) => {
if (1 !== t2.length)
throw new Error(`DepthToSpace expect 1 inputs, but got ${t2.length}`);
if ("string" === t2[0].type || 4 !== t2[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: true }), e.createDotProductProgramInfoLoader = void 0;
const r = n(2517), i = n(5060), o = n(2039), a = n(2823), s = n(3248);
e.createDotProductProgramInfoLoader = (t2, e2, n2, u) => {
const c = ((t3, e3) => ({ name: "ConvDotProduct", inputNames: t3 ? ["Im2Col", "K", "B"] : ["Im2Col", "K"], inputTypes: t3 ? [o.TextureType.unpacked, o.TextureType.packedLastDimension, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.packedLastDimension], cacheKey: e3.activationCacheKey }))(e2.length > 2, u);
return Object.assign(Object.assign({}, c), { get: () => ((t3, e3, n3, u2, c2) => {
const l = n3[0].dims, p = n3[1].dims, f = [p[0], Math.ceil(l[1] * p[2] * p[3] / 4)], d = (0, s.calculateIm2ColDims)(l, p, u2), [h, g] = t3.calculateTextureWidthAndHeight(f, o.TextureType.packedLastDimension), b = r.ShapeUtil.computeStrides(d), [m, y] = t3.calculateTextureWidthAndHeight(d, o.TextureType.packedLastDimension), _ = u2.length, v = n3.length < 3 ? "0.0" : "_B(b)", w = Math.ceil(l[1] * p[2] * p[3] / 4), { activationFunction: x, applyActivation: T } = (0, a.getActivationSnippet)(c2), S = (0, i.getGlsl)(t3.session.backend.glContext.version), O = `
${x}
float process(int indices[${_}]) {
int b[1];
b[0] = indices[1];
int im2col[4];
im2col[0] = indices[0];
im2col[1] = indices[2];
im2col[2] = indices[3];
int im2colOffset = im2col[0] * ${b[0]} + im2col[1] * ${b[1]} + im2col[2] * ${b[2]};
int kernelOffset = indices[1] * ${f[1]};
float value = ${v};
for (int i = 0; i < ${w}; ++i) {
vec2 im2colCoords = offsetToCoords(im2colOffset, ${m}, ${y});
vec2 kernelCoords = offsetToCoords(kernelOffset, ${h}, ${g});
value += dot(${S.texture2D}(Im2Col, im2colCoords), ${S.texture2D}(K, kernelCoords));
++im2colOffset;
++kernelOffset;
}
${T}
return value;
}`;
return Object.assign(Object.assign({}, e3), { output: { dims: u2, type: n3[0].type, textureType: o.TextureType.unpacked }, shaderSource: O });
})(t2, c, e2, n2, u) });
};
}, 7992: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseFlattenAttributes = e.flatten = void 0;
const r = n(2517);
e.flatten = (t2, e2, n2) => {
i(e2, n2);
const o = r.ShapeUtil.flattenShape(e2[0].dims, n2);
return [t2.reshapeUnpacked(e2[0], o)];
}, e.parseFlattenAttributes = (t2) => t2.attributes.getInt("axis", 1);
const i = (t2, e2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Flatten requires 1 input.");
const n2 = t2[0].dims.length;
if (0 === n2)
throw new Error("scalar tensor is not supported.");
if (e2 < -n2 || e2 > n2)
throw new Error("Invalid axis");
if ("string" === t2[0].type)
throw new Error("string tensor is not supported.");
};
}, 2823: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseInternalActivationAttributes = e.getActivationSnippet = void 0;
const r = n(2517), i = n(4909);
e.getActivationSnippet = function(t2) {
let e2;
switch (t2.activation) {
case "Relu":
e2 = (0, i.glslRelu)();
break;
case "Sigmoid":
e2 = (0, i.glslSigmoid)();
break;
case "Clip":
e2 = (0, i.glslClip)(t2.clipMin, t2.clipMax);
break;
default:
return { activationFunction: "", applyActivation: "" };
}
const n2 = e2.name;
return { activationFunction: e2.body, applyActivation: `value = ${n2}_(value);` };
}, e.parseInternalActivationAttributes = (t2) => {
const e2 = t2.getString("activation", "");
if ("Clip" === e2) {
const [n2, i2] = t2.getFloats("activation_params", [r.MIN_CLIP, r.MAX_CLIP]);
return { activation: e2, clipMax: i2, clipMin: n2, activationCacheKey: `${e2}:${n2},${i2}` };
}
return { activation: e2, activationCacheKey: e2 };
};
}, 1253: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseGatherAttributes = e.gather = void 0;
const r = n(246), i = n(782), o = n(2517), a = n(2039);
e.gather = (t2, e2, n2) => (c(e2, n2.axis), [t2.run(u(t2, e2, n2), e2)]), e.parseGatherAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", 0) });
const s = { name: "Gather", inputNames: ["A", "B"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked] }, u = (t2, e2, n2) => {
const r2 = Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey });
return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => {
const i2 = n3[0].dims.slice(), s2 = n3[1].dims.slice(), u2 = new Array(i2.length + s2.length - 1);
r3 = o.ShapeUtil.normalizeAxis(r3, i2.length);
const c2 = [];
for (let t4 = 0; t4 < u2.length; t4++)
t4 < r3 ? (u2[t4] = i2[t4], c2.push(`inputIdx[${t4}] = outputIdx[${t4}];`)) : t4 < r3 + s2.length ? (u2[t4] = s2[t4 - r3], c2.push(`indexDataIdx[${t4 - r3}] = outputIdx[${t4}];`)) : (u2[t4] = i2[t4 - s2.length + 1], c2.push(`inputIdx[${t4 - s2.length + 1}] = outputIdx[${t4}];`));
const l = `
float process(int outputIdx[${u2.length || 1}]) {
int inputIdx[${i2.length}];
int indexDataIdx[${s2.length || 1}];
indexDataIdx[0] = 0;
${c2.join("\n ")}
int idx = int(_B(indexDataIdx));
inputIdx[${r3}] = idx < 0 ? idx + ${i2[r3]} : idx;
return _A(inputIdx);
}`;
return Object.assign(Object.assign({}, e3), { output: { dims: u2, type: n3[0].type, textureType: a.TextureType.unpacked }, shaderSource: l });
})(0, r2, e2, n2.axis) });
}, c = (t2, e2) => {
if (!t2 || 2 !== t2.length)
throw new Error("Gather requires 2 inputs.");
const n2 = t2[0].dims.length;
if (n2 < 1)
throw new Error("Invalid input shape.");
if (e2 < -n2 || e2 > n2 - 1)
throw new Error("Invalid axis.");
if (-1 === i.NUMBER_TYPES.indexOf(t2[0].type))
throw new Error("Invaid input type.");
if ("int32" !== t2[1].type && "int16" !== t2[1].type)
throw new Error("Invaid input type.");
};
}, 4776: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseGemmAttributesV11 = e.parseGemmAttributesV7 = e.gemm = void 0;
const r = n(246), i = n(2517), o = n(2039);
e.gemm = (t2, e2, n2) => (c(e2, n2), [t2.run(s(e2, n2), e2)]);
const a = (t2, e2) => {
const n2 = 0 !== t2.attributes.getInt("transA", 0), i2 = 0 !== t2.attributes.getInt("transB", 0), o2 = t2.attributes.getFloat("alpha", 1), a2 = t2.attributes.getFloat("beta", 1);
return (0, r.createAttributeWithCacheKey)({ transA: n2, transB: i2, alpha: o2, beta: a2, isOptionalC: e2 });
};
e.parseGemmAttributesV7 = (t2) => a(t2, false), e.parseGemmAttributesV11 = (t2) => a(t2, true);
const s = (t2, e2) => {
const n2 = { name: "Gemm", inputNames: 3 === t2.length ? ["A", "B", "C"] : ["A", "B"], inputTypes: 3 === t2.length ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], key: e2.cacheKey };
return Object.assign(Object.assign({}, n2), { get: () => u(n2, t2, e2) });
}, u = (t2, e2, n2) => {
const r2 = e2[0].dims.slice(), a2 = e2[1].dims.slice(), [s2, u2] = i.GemmUtil.getShapeOfGemmResult(r2, n2.transA, a2, n2.transB, 3 === e2.length ? e2[2].dims : void 0), c2 = [s2, u2];
if (!c2)
throw new Error("Can't use gemm on the given tensors");
let l = r2[r2.length - 1], p = "";
n2.transA && (l = r2[0]), n2.transA && n2.transB ? p = "value += _A_T(a) * _B_T(b);" : n2.transA && !n2.transB ? p = "value += _A_T(a) * _B(b);" : !n2.transA && n2.transB ? p = "value += _A(a) * _B_T(b);" : n2.transA || n2.transB || (p = "value += _A(a) * _B(b);");
const f = c2.length, d = `
float process(int indices[${f}]) {
int a[${f}];
int b[${f}];
${3 === e2.length ? `int c[${e2[2].dims.length}];` : ""}
copyVec(indices, a);
copyVec(indices, b);
${3 === e2.length ? "bcastIndices_C(indices, c);" : ""}
float value = 0.0;
for (int k=0; k<${l}; ++k) {
a[${f - 1}] = k;
b[${f - 2}] = k;
${p}
}
value = value * alpha;
${3 === e2.length ? "value += beta * _C(c);" : ""}
return value;
}`;
return Object.assign(Object.assign({}, t2), { output: { dims: c2, type: e2[0].type, textureType: o.TextureType.unpacked }, variables: [{ name: "alpha", type: "float", data: n2.alpha }, { name: "beta", type: "float", data: n2.beta }], shaderSource: d });
}, c = (t2, e2) => {
if (!t2)
throw new Error("Input is missing");
if (e2.isOptionalC && (t2.length < 2 || t2.length > 3))
throw new Error("Invaid input shape.");
if (!e2.isOptionalC && 3 !== t2.length)
throw new Error("Gemm requires 3 inputs");
if (3 === t2.length && 1 !== t2[2].dims.length && 2 !== t2[2].dims.length)
throw new Error("Invalid input shape of C");
if ("float32" !== t2[0].type && "float64" !== t2[0].type || "float32" !== t2[1].type && "float64" !== t2[1].type || 3 === t2.length && "float32" !== t2[2].type && "float64" !== t2[2].type)
throw new Error("Invalid input type.");
if (t2[0].type !== t2[1].type || 3 === t2.length && t2[0].type !== t2[2].type)
throw new Error("Input types are mismatched");
};
}, 8555: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.createPackedIm2ColProgramInfoLoader = void 0;
const r = n(5060), i = n(2039), o = n(2827);
e.createPackedIm2ColProgramInfoLoader = (t2, e2, n2, 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: () => ((t3, e3, n3, a2, s2, u2) => {
const c2 = n3.dims, l = a2.dims, p = s2.length, f = [l[1] * l[2] * l[3], s2[2] * s2[3]], d = l[2] * l[3], h = (0, o.unpackFromChannel)(), g = (0, r.getGlsl)(t3.session.backend.glContext.version);
let b = "";
for (let t4 = 0; t4 <= 1; t4++)
for (let e4 = 0; e4 <= 1; e4++)
b += `
blockIndex = rc.x + ${e4};
pos = rc.y + ${t4};
if(blockIndex < ${f[1]} && pos < ${f[0]}) {
offsetY = int(blockIndex / (${s2[p - 1]})) * ${u2.strides[0]} -
${u2.pads[0]};
d0 = offsetY + ${u2.dilations[0]} * (imod(pos, ${d}) / ${l[2]});
if(d0 < ${c2[2]} && d0 >= 0) {
offsetX = imod(blockIndex, ${s2[p - 1]}) * ${u2.strides[1]} -
${u2.pads[1]};
d1 = offsetX + ${u2.dilations[1]} * imod(imod(pos, ${d}), ${l[2]});
if(d1 < ${c2[3]} && d1 >= 0) {
ch = int(float(pos)/ ${d}.);
innerDims = vec2(d0, d1);
result[${2 * t4 + e4}] = getChannel(
getA(0, ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
`;
const m = `
${h}
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0.0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${b}
${g.output} = result;
}
`;
return Object.assign(Object.assign({}, e3), { output: { dims: f, type: n3.type, textureType: i.TextureType.packed }, shaderSource: m, hasMain: true });
})(t2, u, e2, n2, a, s) });
};
}, 3248: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.calculateIm2ColDims = e.createIm2ColProgramInfoLoader = void 0;
const r = n(2039);
e.createIm2ColProgramInfoLoader = (t2, n2, 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: () => ((t3, n3, i2, o2, a2, s2) => {
const u2 = i2.dims, c = o2.dims, l = a2.length, p = (0, e.calculateIm2ColDims)(u2, c, a2, 4), f = `
const int XC = ${u2[1]};
const int XH = ${u2[2]};
const int XW = ${u2[3]};
const int KH = ${s2.kernelShape[0]};
const int KW = ${s2.kernelShape[1]};
const int dilationH = ${s2.dilations[0]};
const int dilationW = ${s2.dilations[1]};
const int strideH = ${s2.strides[0]};
const int strideW = ${s2.strides[1]};
const int padH = ${s2.pads[0]};
const int padW = ${s2.pads[1]};
const int KHKW = KH*KW;
const int XCKHKW = XC * KHKW;
const int outputChannels = 4;
vec4 process(int indices[${l}]) {
int b = indices[0]; // batch size
int oh = indices[1] * strideH - padH; //output height
int ow = indices[2] * strideW - padW; //output width
int p = indices[3] * outputChannels; //patch
vec4 value = vec4(0.0);
for(int i=0; i < outputChannels; ++i) {
if(p < XCKHKW) {
int patchC = p / KHKW;
int patchH = (p - patchC*KHKW) / KW;
int patchW = (p - patchC*KHKW) - patchH * KW;
int xh2 = oh + patchH * dilationH;
int xw2 = ow + patchW * dilationW;
int x[${u2.length}];
x[0] = b;
x[1] = patchC;
x[2] = xh2;
x[3] = xw2;
if(xh2 >= 0 &&
xh2 < XH &&
xw2 >= 0 &&
xw2 < XW) {
value[i] = _X(x);
}
}
++p;
}
return value;
}
`;
return Object.assign(Object.assign({}, n3), { output: { dims: p, type: i2.type, textureType: r.TextureType.packedLastDimension }, shaderSource: f });
})(0, s, n2, i, o, a) });
}, e.calculateIm2ColDims = (t2, e2, n2, r2 = 4) => [n2[0], n2[2], n2[3], Math.ceil(t2[1] * e2[2] * e2[3] / r2)];
}, 6572: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseImageScalerAttributes = e.imageScaler = void 0;
const r = n(246), i = n(2039);
e.imageScaler = (t2, e2, n2) => (u(e2), [t2.run(a(t2, e2, n2), e2)]), e.parseImageScalerAttributes = (t2) => {
const e2 = t2.attributes.getFloat("scale"), n2 = t2.attributes.getFloats("bias");
return (0, r.createAttributeWithCacheKey)({ scale: e2, bias: n2 });
};
const o = { name: "ImageScaler", inputNames: ["X"], inputTypes: [i.TextureType.unpacked] }, a = (t2, e2, n2) => {
const r2 = Object.assign(Object.assign({}, o), { cacheHint: n2.cacheKey });
return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => {
const o2 = n3[0].dims.slice(), a2 = o2.length, u2 = `
${s(r3.bias.length)}
float process(int indices[${a2}]) {
return _X(indices) * scale + getBias(bias, indices[1]);
}`;
return Object.assign(Object.assign({}, e3), { output: { dims: o2, type: n3[0].type, textureType: i.TextureType.unpacked }, variables: [{ name: "bias", type: "float", arrayLength: r3.bias.length, data: r3.bias }, { name: "scale", type: "float", data: r3.scale }], shaderSource: u2 });
})(0, r2, e2, n2) });
}, s = (t2) => {
const e2 = [`float getBias(float bias[${t2}], int channel) {`];
for (let n2 = 0; n2 < t2; ++n2)
0 === n2 ? e2.push(` if (channel == ${n2}) { return bias[${n2}]; }`) : n2 === t2 - 1 ? e2.push(` else { return bias[${n2}]; }`) : e2.push(` else if (channel == ${n2}) { return bias[${n2}]; }`);
return e2.push(" }"), e2.join("\n");
}, u = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("ImageScaler requires 1 input.");
if (4 !== t2[0].dims.length)
throw new Error("Invalid input shape.");
if ("float32" !== t2[0].type && "float64" !== t2[0].type)
throw new Error("Invalid input type.");
};
}, 3346: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseInstanceNormalizationAttributes = e.instanceNormalization = void 0;
const r = n(5060), i = n(2039);
e.instanceNormalization = (t2, e2, n2) => {
c(e2);
const r2 = t2.run(a(e2[0]), e2);
return [t2.run(u(t2, e2[0], n2, r2.dims), [e2[0], r2, e2[1], e2[2]])];
}, e.parseInstanceNormalizationAttributes = (t2) => t2.attributes.getFloat("epsilon", 1e-5);
const o = { name: "InstanceNormalization_MeanAndVariance", inputNames: ["X"], inputTypes: [i.TextureType.unpacked] }, a = (t2) => Object.assign(Object.assign({}, o), { get: () => ((t3, e2) => {
const n2 = e2.dims.slice(), r2 = n2[1], o2 = n2[2] * n2[3], a2 = [n2[0], r2], s2 = `
vec4 process(int[2] indices) {
vec4 v = vec4(0.0);
int a[4];
a[0] = indices[0];
a[1] = indices[1];
float temp = 0.0;
for(int a2=0; a2<${n2[2]}; a2++) {
a[2] = a2;
for(int a3=0; a3<${n2[3]}; a3++) {
a[3] = a3;
float x = _X(a);
temp += x;
}
}
float mean = temp / float(${o2});
temp = 0.0;
for(int a2=0; a2<${n2[2]}; a2++) {
a[2] = a2;
for(int a3=0; a3<${n2[3]}; a3++) {
a[3] = a3;
float x = _X(a);
temp += (x - mean) * (x - mean);
}
}
v.r = mean;
v.g = temp / float(${o2});
return v;
}`;
return Object.assign(Object.assign({}, t3), { output: { dims: a2, type: e2.type, textureType: i.TextureType.packedLastDimension }, shaderSource: s2 });
})(o, t2) }), s = { name: "InstanceNormalization_ComputeOutput", inputNames: ["X", "MeanAndVariance", "Scale", "B"], inputTypes: [i.TextureType.unpacked, i.TextureType.packedLastDimension, i.TextureType.unpacked, i.TextureType.unpacked] }, u = (t2, e2, n2, o2) => {
const a2 = Object.assign(Object.assign({}, s), { cacheHint: `${n2}` });
return Object.assign(Object.assign({}, a2), { get: () => ((t3, e3, n3, o3, a3) => {
const s2 = (0, r.getGlsl)(t3.session.backend.glContext.version), [u2, c2] = t3.calculateTextureWidthAndHeight(a3, i.TextureType.packedLastDimension), [l, p] = [u2 / 4, c2], f = `
vec4 get_MeanAndVariance(int[2] mv) {
int offset = indicesToOffset_MeanAndVariance(mv);
vec2 coords = offsetToCoords(offset, ${l}, ${p});
return ${s2.texture2D}(MeanAndVariance, coords);
}
float process(int[4] indices) {
int mv[2];
mv[0] = indices[0];
mv[1] = indices[1];
vec4 mean_and_variance = get_MeanAndVariance(mv);
float mean = mean_and_variance.r;
float variance = mean_and_variance.g;
int sb[1];
sb[0] = indices[1];
float scale = _Scale(sb);
float b = _B(sb);
return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;
}`;
return Object.assign(Object.assign({}, e3), { output: { dims: n3.dims, type: n3.type, textureType: i.TextureType.unpacked }, variables: [{ name: "epsilon", type: "float", data: o3 }], shaderSource: f });
})(t2, a2, e2, n2, o2) });
}, c = (t2) => {
if (!t2 || 3 !== t2.length)
throw new Error("InstanceNormalization requires 3 inputs.");
const e2 = t2[0], n2 = t2[1], r2 = t2[2];
if (e2.dims.length < 3 || 1 !== n2.dims.length || 1 !== r2.dims.length)
throw new Error("Invalid input shape.");
if (n2.dims[0] !== e2.dims[1] || r2.dims[0] !== e2.dims[1])
throw new Error("Input shapes are mismatched.");
if ("float32" !== e2.type && "float64" !== e2.type || "float32" !== n2.type && "float64" !== n2.type || "float32" !== r2.type && "float64" !== r2.type)
throw new Error("Invalid input type.");
if (4 !== t2[0].dims.length)
throw new Error("Only support 4-D input shape.");
};
}, 708: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2, n2) => {
const c = (l = e2.length > 2, p = n2.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: () => ((t3, e3, n3, c2) => {
const l2 = n3.length > 2, p2 = l2 ? "value += getBiasForMatmul();" : "", f = n3[0].dims, d = n3[1].dims, h = r.BroadcastUtil.calcShape(f, d, true), g = !r.ShapeUtil.areEqual(n3[0].dims, n3[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)(t3.session.backend.glContext.version), w = (0, a.getCoordsDataType)(h.length), x = h.length, T = (0, a.getGlChannels)(), { activationFunction: S, applyActivation: O } = (0, s.getActivationSnippet)(c2), A = l2 ? `${(0, u.getBiasForMatmul)(w, T, n3[2].dims, h, true)}` : "", E = g ? `${function(t4, e4, n4, i2) {
let o2 = [], a2 = [];
const s2 = n4[0].dims, u2 = n4[1].dims, c3 = s2.length, l3 = u2.length, p3 = i2.length, f2 = p3 - c3, d2 = p3 - l3;
o2 = s2.map((t5, n5) => `coords.${e4[n5 + f2]}`), o2[c3 - 1] = "i*2", o2.join(", "), a2 = u2.map((t5, n5) => `coords.${e4[n5 + d2]}`), a2[l3 - 2] = "i*2", a2.join(", ");
const h2 = r.BroadcastUtil.getBroadcastDims(s2, i2), g2 = r.BroadcastUtil.getBroadcastDims(u2, i2), b2 = h2.map((t5) => `coords.${e4[t5 + f2]} = 0;`).join("\n"), m2 = g2.map((t5) => `coords.${e4[t5 + d2]} = 0;`).join("\n"), y2 = `int lastDim = coords.${e4[p3 - 1]};
coords.${e4[p3 - 1]} = coords.${e4[p3 - 2]};
coords.${e4[p3 - 2]} = lastDim;`;
return `
vec4 getAAtOutCoordsMatmul(int i) {
${t4} coords = getOutputCoords();
${y2}
${b2}
vec4 outputValue = getA(${o2});
return outputValue;
}
vec4 getBAtOutCoordsMatmul(int i) {
${t4} coords = getOutputCoords();
${y2}
${m2}
vec4 outputValue = getB(${a2});
return outputValue;
}`;
}(w, T, n3, h)}` : "", I = g ? "getAAtOutCoordsMatmul(i)" : `getA(${function(t4, e4) {
let n4 = "";
for (let r2 = 0; r2 < e4 - 2; r2++)
n4 += `rc.${t4[r2]}, `;
return n4 += `rc.${t4[e4 - 2]}, i*2`, n4;
}(T, y)})`, P = g ? "getBAtOutCoordsMatmul(i)" : `getB(${function(t4, e4) {
let n4 = "";
for (let r2 = 0; r2 < e4 - 2; r2++)
n4 += `rc.${t4[r2]}, `;
return n4 += `i*2, rc.${t4[e4 - 1]}`, n4;
}(T, _)})`, D = `
${E}
${A}
${S}
void main() {
${g ? "" : `${w} rc =
getOutputCoords(); int lastDim = rc.${T[x - 1]}; rc.${T[x - 1]} =
rc.${T[x - 2]}; rc.${T[x - 2]} = lastDim;
`}
vec4 value = vec4(0);
for (int i = 0; i < ${m}; i++) {
vec4 a = ${I};
vec4 b = ${P};
value += (a.rrbb * b.rgrg);
value += (a.ggaa * b.baba);
}
${p2}
${O}
${v.output} = value;
}`;
return Object.assign(Object.assign({}, e3), { output: { dims: h, type: n3[0].type, textureType: o.TextureType.packed }, shaderSource: D, hasMain: true });
})(t2, c, e2, n2) });
};
}, 5623: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2, e2) {
const n2 = (s2 = t2.length > 2, u2 = e2.activationCacheKey, { name: "MatMul", inputNames: s2 ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: s2 ? [i.TextureType.unpacked, i.TextureType.unpacked, i.TextureType.unpacked] : [i.TextureType.unpacked, i.TextureType.unpacked], cacheHint: u2 });
var s2, u2;
return Object.assign(Object.assign({}, n2), { get: () => function(t3, e3, n3) {
const s3 = e3[0].dims, u3 = e3[1].dims, c2 = r.BroadcastUtil.calcShape(s3, u3, true);
if (!c2)
throw new Error("Can't use matmul on the given tensors");
const p = (0, o.getCoordsDataType)(c2.length), f = (0, o.getGlChannels)(), { activationFunction: d, applyActivation: h } = (0, a.getActivationSnippet)(n3), g = e3.length > 2, b = g ? "value += getBiasForMatmul();" : "", m = g ? `${l(p, f, e3[2].dims, c2, false)}` : "", y = c2.length, _ = s3.length, v = u3.length, w = `
${d}
${m}
float process(int indices[${y}]) {
int a[${_}];
int b[${v}];
bcastMatmulIndices_A(indices, a);
bcastMatmulIndices_B(indices, b);
float value;
for (int k=0; k<${s3[s3.length - 1]}; ++k) {
a[${_ - 1}] = k;
b[${v - 2}] = k;
value += _A(a) * _B(b);
}
${b}
${h}
return value;
}`;
return Object.assign(Object.assign({}, t3), { output: { dims: c2, type: e3[0].type, textureType: i.TextureType.unpacked }, shaderSource: w });
}(n2, t2, e2) });
}
e.matMul = (t2, e2, n2) => (c(e2), t2.session.pack ? [t2.run((0, s.createPackedMatmulProgramInfoLoader)(t2, e2, n2), e2)] : [t2.run(u(e2, n2), e2)]), e.parseMatMulAttributes = (t2) => (0, a.parseInternalActivationAttributes)(t2.attributes), e.createMatmulProgramInfoLoader = u;
const c = (t2) => {
if (!t2 || 2 !== t2.length)
throw new Error("MatMul requires 2 inputs.");
if (t2[0].dims[t2[0].dims.length - 1] !== t2[1].dims[t2[1].dims.length - 2])
throw new Error("shared dimension does not match.");
if ("float32" !== t2[0].type && "float64" !== t2[0].type || "float32" !== t2[1].type && "float64" !== t2[1].type)
throw new Error("inputs should be float type");
if (t2[0].type !== t2[1].type)
throw new Error("inputs types should match");
};
function l(t2, e2, n2, i2, o2) {
let a2 = "";
const s2 = n2.length, u2 = i2.length, c2 = u2 - s2;
a2 = u2 < 2 && s2 > 0 ? "coords" : n2.map((t3, n3) => `coords.${e2[n3 + c2]}`).join(", ");
const l2 = r.BroadcastUtil.getBroadcastDims(n2, i2).map((t3) => `coords.${e2[t3 + c2]} = 0;`).join("\n");
let p = "vec4(outputValue.xx, outputValue.yy)";
return 1 === r.ShapeUtil.size(n2) && (p = "vec4(outputValue.x)"), o2 ? `
vec4 getBiasForMatmul() {
${t2} coords = getOutputCoords();
${l2}
vec4 outputValue = getBias(${a2});
return ${p};
}` : `
float getBiasForMatmul() {
${t2} coords = getOutputCoords();
${l2}
return getBias(coords.x);
}`;
}
e.getBiasForMatmul = l;
}, 2403: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2) => Object.assign(Object.assign({}, s), { get: () => ((t3, e3) => {
const n2 = (0, r.getGlsl)(t3.session.backend.glContext.version), u = e3.dims, c = u.length, l = e3.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 ? "" : `
int r = ${g[h - 2]};
int c = ${g[h - 1]};
int rp1 = ${g[h - 2]} + 1;
int cp1 = ${g[h - 1]} + 1;
bool rEdge = rp1 >= ${m};
bool cEdge = cp1 >= ${b};
`);
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(t4, e4, n3) {
if (0 === t4)
return "false";
if (1 === t4)
return `rc > ${e4[0]}`;
let r2 = "";
for (let i2 = t4 - 2; i2 < t4; i2++)
r2 += `${n3[i2]} >= ${e4[i2 - t4 + 2]}`, i2 < t4 - 1 && (r2 += "||");
return r2;
}(l, y, f), v = function(t4, e4) {
const n3 = t4.length;
if (0 === n3)
return "getA(), 0, 0, 0";
if (1 === n3)
return `getA(rc),
rc + 1 >= ${t4[0]} ? 0. : getA(rc + 1),
0, 0`;
let r2 = "";
if (n3 > 2)
for (let t5 = 0; t5 < n3 - 2; ++t5)
r2 += `${e4[t5]},`;
return `getA(${r2}r, c),
rEdge ? 0. : getA(${r2}rp1, c),
cEdge ? 0. : getA(${r2}r, cp1),
rEdge || cEdge ? 0. : getA(${r2}rp1, cp1)`;
}(u, f), w = `
void main() {
${p} rc = getOutputCoords();
if(${_}) {
${n2.output} = vec4(0);
} else {
${d}
${n2.output} = vec4(${v});
}
}
`;
return Object.assign(Object.assign({}, s), { hasMain: true, output: { dims: e3.dims, type: e3.type, textureType: i.TextureType.packed }, shaderSource: w });
})(t2, e2) });
}, 2827: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.unpackFromChannel = e.getChannels = e.getVecChannels = void 0;
const r = n(9390);
function i(t2, e2) {
return (0, r.getGlChannels)(e2).map((e3) => `${t2}.${e3}`);
}
e.getVecChannels = i, e.getChannels = function(t2, e2) {
return 1 === e2 ? [t2] : i(t2, e2);
}, 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: true }), 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 = (t2, e2, n2) => (l(e2), [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => c(t2, e2[0], n2) }), e2)]), e.parsePadAttributesV2 = (t2) => {
const e2 = t2.attributes.getString("mode", "constant"), n2 = t2.attributes.getFloat("value", 0), i2 = t2.attributes.getInts("pads");
return (0, r.createAttributeWithCacheKey)({ mode: e2, value: n2, pads: i2 });
}, e.padV11 = (t2, n2, r2) => {
p(n2);
const i2 = u(t2, n2, r2);
return (0, e.padV2)(t2, [n2[0]], i2);
}, e.parsePadAttributesV11 = (t2) => t2.attributes.getString("mode", "constant");
const u = (t2, e2, n2) => {
if (!t2.session.isInitializer(e2[1].dataId) || e2.length >= 3 && !t2.session.isInitializer(e2[2].dataId))
throw new Error("dynamic pad attributes are not allowed");
const i2 = Array.from(e2[1].integerData), o2 = e2.length >= 3 ? e2[2].floatData[0] : 0;
return (0, r.createAttributeWithCacheKey)({ mode: n2, pads: i2, value: o2 });
}, c = (t2, e2, n2) => {
const r2 = i.ShapeUtil.padShape(e2.dims.slice(), n2.pads), o2 = r2.length, s2 = `
${f(t2, e2, n2)}
float process(int[${o2}] indices) {
return padA(indices);
}`;
return { name: "Pad", inputNames: ["A"], inputTypes: [a.TextureType.unpacked], output: { dims: r2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: s2 };
}, l = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Pad requires 1 input");
if ("float32" !== t2[0].type && "float64" !== t2[0].type)
throw new Error("Invalid input type.");
}, p = (t2) => {
if (!t2 || 2 !== t2.length && 3 !== t2.length)
throw new Error("Pad requires 2 or 3 inputs");
if ("int32" !== t2[1].type)
throw new Error("Invalid input type.");
if (t2.length >= 3 && "string" === t2[2].type)
throw new Error("Invalid input type.");
}, f = (t2, e2, n2) => {
const r2 = (0, o.getGlsl)(t2.session.backend.glContext.version), [s2, u2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), c2 = i.ShapeUtil.computeStrides(e2.dims);
switch (n2.mode) {
case "constant":
return d(r2, e2.dims, c2, s2, u2, n2.pads, n2.value);
case "reflect":
return h(r2, e2.dims, c2, s2, u2, n2.pads);
case "edge":
return g(r2, e2.dims, c2, s2, u2, n2.pads);
default:
throw new Error("Invalid mode");
}
}, d = (t2, e2, n2, r2, i2, o2, a2) => {
const s2 = e2.length;
let u2 = "";
for (let t3 = s2 - 1; t3 >= 0; --t3)
u2 += `
k = m[${t3}] - ${o2[t3]};
if (k < 0) return constant;
if (k >= ${e2[t3]}) return constant;
offset += k * ${n2[t3]};
`;
return `
float padA(int m[${s2}]) {
const float constant = float(${a2});
int offset = 0;
int k = 0;
${u2}
vec2 coords = offsetToCoords(offset, ${r2}, ${i2});
float value = getColorAsFloat(${t2.texture2D}(A, coords));
return value;
}
`;
}, h = (t2, e2, n2, r2, i2, o2) => {
const a2 = e2.length;
let s2 = "";
for (let t3 = a2 - 1; t3 >= 0; --t3)
s2 += `
k = m[${t3}] - ${o2[t3]};
if (k < 0) { k = -k; }
{
const int _2n_1 = ${2 * (e2[t3] - 1)};
k = int( mod( float(k), float(_2n_1) ) ) ;
if(k >= ${e2[t3]}) { k = _2n_1 - k; }
}
offset += k * ${n2[t3]};
`;
return `
float padA(int m[${a2}]) {
int offset = 0;
int k = 0;
${s2}
vec2 coords = offsetToCoords(offset, ${r2}, ${i2});
float value = getColorAsFloat(${t2.texture2D}(A, coords));
return value;
}
`;
}, g = (t2, e2, n2, r2, i2, o2) => {
const a2 = e2.length;
let s2 = "";
for (let t3 = a2 - 1; t3 >= 0; --t3)
s2 += `
k = m[${t3}] - ${o2[t3]};
if (k < 0) k = 0;
if (k >= ${e2[t3]}) k = ${e2[t3] - 1};
offset += k * ${n2[t3]};
`;
return `
float padA(int m[${a2}]) {
int offset = 0;
int k = 0;
${s2}
vec2 coords = offsetToCoords(offset, ${r2}, ${i2});
float value = getColorAsFloat(${t2.texture2D}(A, coords));
return value;
}
`;
};
}, 2143: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2, n2) => {
p(e2);
const r2 = { name: "AveragePool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: n2.cacheKey };
return [t2.run(Object.assign(Object.assign({}, r2), { get: () => a(e2, r2, false, n2) }), e2)];
}, e.parseAveragePoolAttributes = (t2) => {
const e2 = t2.attributes.getString("auto_pad", "NOTSET"), n2 = t2.attributes.getInt("ceil_mode", 0), i2 = 0 !== t2.attributes.getInt("count_include_pad", 0), o2 = t2.attributes.getInts("kernel_shape"), a2 = t2.attributes.getInts("strides", []), s2 = t2.attributes.getInts("pads", []);
if (0 !== n2)
throw new Error("using ceil() in shape computation is not yet supported for AveragePool");
return (0, r.createAttributeWithCacheKey)({ autoPad: e2, ceilMode: n2, countIncludePad: i2, kernelShape: o2, strides: a2, pads: s2 });
};
const a = (t2, e2, n2, r2) => {
const [a2, s2] = u(t2, r2, n2), c2 = i.ShapeUtil.size(a2.kernelShape);
let l2 = "";
a2.countIncludePad ? l2 += `value /= float(${c2});` : l2 += `value /= float(${c2} - pad);`;
const p2 = `
${f(t2[0].dims, a2, "value += _X(x);", l2, "0.0")}
`;
return Object.assign(Object.assign({}, e2), { output: { dims: s2, type: t2[0].type, textureType: o.TextureType.unpacked }, shaderSource: p2 });
};
e.globalAveragePool = (t2, e2, n2) => {
p(e2);
const r2 = { name: "GlobalAveragePool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: `${n2.countIncludePad}` };
return [t2.run(Object.assign(Object.assign({}, r2), { get: () => a(e2, r2, true, n2) }), e2)];
}, e.parseGlobalAveragePoolAttributes = (t2) => {
const e2 = 0 !== t2.attributes.getInt("count_include_pad", 0);
return (0, r.createAttributeWithCacheKey)({ autoPad: "", ceilMode: 0, countIncludePad: e2, kernelShape: [], strides: [], pads: [] });
}, e.maxPool = (t2, e2, n2) => {
p(e2);
const r2 = { name: "MaxPool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: n2.cacheKey };
return [t2.run(Object.assign(Object.assign({}, r2), { get: () => s(e2, r2, false, n2) }), e2)];
}, e.parseMaxPoolAttributes = (t2) => {
const e2 = t2.attributes.getString("auto_pad", "NOTSET"), n2 = t2.attributes.getInt("ceil_mode", 0), i2 = t2.attributes.getInts("kernel_shape"), o2 = t2.attributes.getInts("strides", []), a2 = t2.attributes.getInts("pads", []), s2 = t2.attributes.getInt("storage_order", 0), u2 = t2.attributes.getInts("dilations", []);
if (0 !== s2)
throw new Error("column major storage order is not yet supported for MaxPool");
if (0 !== n2)
throw new Error("using ceil() in shape computation is not yet supported for MaxPool");
return (0, r.createAttributeWithCacheKey)({ autoPad: e2, ceilMode: n2, countIncludePad: false, kernelShape: i2, strides: o2, pads: a2, storageOrder: s2, dilations: u2 });
};
const s = (t2, e2, n2, r2) => {
const [i2, a2] = u(t2, r2, n2), s2 = `
${f(t2[0].dims, i2, "\n value = max(_X(x), value);\n ", "", "-1e5")}
`;
return Object.assign(Object.assign({}, e2), { output: { dims: a2, type: t2[0].type, textureType: o.TextureType.unpacked }, shaderSource: s2 });
}, u = (t2, e2, n2) => {
const r2 = t2[0].dims.slice(), o2 = Object.hasOwnProperty.call(e2, "dilations"), a2 = e2.kernelShape.slice(), s2 = e2.strides.slice(), u2 = o2 ? e2.dilations.slice() : [], c2 = e2.pads.slice();
i.PoolConvUtil.adjustPoolAttributes(n2, r2, a2, s2, u2, c2);
const l2 = i.PoolConvUtil.computePoolOutputShape(n2, r2, s2, u2, a2, c2, e2.autoPad), p2 = Object.assign({}, e2);
return o2 ? Object.assign(p2, { kernelShape: a2, strides: s2, pads: c2, dilations: u2, cacheKey: e2.cacheKey }) : Object.assign(p2, { kernelShape: a2, strides: s2, pads: c2, cacheKey: e2.cacheKey }), [p2, l2];
}, c = { autoPad: "", ceilMode: 0, countIncludePad: false, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [], cacheKey: "" }, l = { name: "GlobalMaxPool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked] };
e.globalMaxPool = (t2, e2) => (p(e2), [t2.run(Object.assign(Object.assign({}, l), { get: () => s(e2, l, true, c) }), e2)]);
const p = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Pool ops requires 1 input.");
if ("float32" !== t2[0].type && "float64" !== t2[0].type)
throw new Error("Invalid input type.");
}, f = (t2, e2, n2, r2, o2) => {
const a2 = t2.length;
if (e2.kernelShape.length <= 2) {
const i2 = e2.kernelShape[e2.kernelShape.length - 1], s2 = e2.strides[e2.strides.length - 1], u2 = e2.pads[e2.pads.length / 2 - 1], c2 = e2.pads[e2.pads.length - 1], l2 = t2[a2 - 1];
let p2 = "", f2 = "", d2 = "";
if (p2 = u2 + c2 !== 0 ? `
for (int i = 0; i < ${i2}; i++) {
x[${a2} - 1] = indices[${a2} - 1] * ${s2} - ${u2} + i;
if (x[${a2} - 1] < 0 || x[${a2} - 1] >= ${l2}) {
pad++;
continue;
}
${n2}
}` : `
for (int i = 0; i < ${i2}; i++) {
x[${a2} - 1] = indices[${a2} - 1] * ${s2} - ${u2} + i;
${n2}
}`, 2 === e2.kernelShape.length) {
const n3 = e2.kernelShape[e2.kernelShape.length - 2], r3 = e2.strides[e2.strides.length - 2], o3 = e2.pads[e2.pads.length / 2 - 2], s3 = e2.pads[e2.pads.length - 2], u3 = t2[a2 - 2];
f2 = o3 + s3 !== 0 ? `
for (int j = 0; j < ${n3}; j++) {
x[${a2} - 2] = indices[${a2} - 2] * ${r3} - ${o3} + j;
if (x[${a2} - 2] < 0 || x[${a2} - 2] >= ${u3}) {
pad+= ${i2};
continue;
}
` : `
for (int j = 0; j < ${n3}; j++) {
x[${a2} - 2] = indices[${a2} - 2] * ${r3} - ${o3} + j;
`, d2 = "\n }\n ";
}
return `
float process(int indices[${a2}]) {
int x[${a2}];
copyVec(indices, x);
float value = ${o2};
int pad = 0;
${f2}
${p2}
${d2}
${r2}
return value;
}
`;
}
{
const s2 = i.ShapeUtil.size(e2.kernelShape), u2 = i.ShapeUtil.computeStrides(e2.kernelShape), c2 = u2.length, l2 = e2.pads.length, p2 = h(c2), f2 = d(t2, "inputDims"), g = d(e2.pads, "pads"), b = d(u2, "kernelStrides"), m = d(e2.strides, "strides");
let y = "";
return y = e2.pads.reduce((t3, e3) => t3 + e3) ? `
if (x[j] >= inputDims[j] || x[j] < 0) {
pad++;
isPad = true;
break;
}
}
if (!isPad) {
${n2}
}` : `
}
${n2}
`, `
${p2}
float process(int indices[${a2}]) {
int x[${a2}];
copyVec(indices, x);
int offset[${c2}];
int pads[${l2}];
int inputDims[${a2}];
int kernelStrides[${c2}];
int strides[${c2}];
${g}
${f2}
${m}
${b}
float value = ${o2};
int pad = 0;
bool isPad = false;
for (int i = 0; i < ${s2}; i++) {
offsetToIndices(i, kernelStrides, offset);
isPad = false;
for (int j = ${a2} - ${c2}; j < ${a2}; j++) {
x[j] = indices[j] * strides[j - ${a2} + ${c2}]
+ offset[j - ${a2} + ${c2}] - pads[j - 2];
${y}
}
${r2}
return value;
}
`;
}
}, d = (t2, e2) => {
let n2 = "";
for (let r2 = 0; r2 < t2.length; r2++)
n2 += `
${e2}[${r2}] = ${t2[r2]};
`;
return n2;
}, h = (t2) => `
void offsetToIndices(int offset, int[${t2}] strides, out int[${t2}] indices) {
if (${t2} == 0) {
return;
}
for (int i = 0; i < ${t2} - 1; ++i) {
indices[i] = offset / strides[i];
offset -= indices[i] * strides[i];
}
indices[${t2} - 1] = offset;
}`;
}, 4939: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2, n2, r2, i2) => {
c(e2);
const o2 = { name: r2, inputNames: ["A"], inputTypes: [a.TextureType.unpacked] };
return [t2.run(Object.assign(Object.assign({}, o2), { cacheHint: n2.cacheKey, get: () => u(t2, e2, n2, r2, i2, o2) }), e2)];
};
e.parseReduceAttributes = (t2) => {
const e2 = t2.attributes.getInts("axes", []), n2 = 1 === t2.attributes.getInt("keepdims", 1);
return (0, r.createAttributeWithCacheKey)({ axes: e2, keepDims: n2 });
};
const u = (t2, e2, n2, r2, i2, s2) => {
const u2 = [], c2 = e2[0].dims.length || 1, l = [], p = o.ShapeUtil.normalizeAxes(n2.axes, e2[0].dims.length), f = i2(e2, p);
let d = f[1];
for (let t3 = 0; t3 < e2[0].dims.length; t3++)
p.indexOf(t3) >= 0 || 0 === p.length ? (n2.keepDims && u2.push(1), d = `
for(int j${t3} = 0; j${t3} < ${e2[0].dims[t3]}; j${t3}++) {
inputIdx[${t3}] = j${t3};
${d}
}`) : (l.push(`inputIdx[${t3}] = outputIdx[${u2.length}];`), u2.push(e2[0].dims[t3]));
const h = `
float process(int outputIdx[${u2.length || 1}]) {
float value; // final result
int inputIdx[${c2}]; // addressing input data
${l.join("\n")}
${f[0]} // init ops for reduce max/min
${d}
${f[2]} // final computation for reduce mean
return value;
}`;
return Object.assign(Object.assign({}, s2), { output: { dims: u2, type: e2[0].type, textureType: a.TextureType.unpacked }, shaderSource: h });
}, c = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Reduce op requires 1 input.");
if (-1 === i.NUMBER_TYPES.indexOf(t2[0].type))
throw new Error("Invalid input type.");
};
e.reduceSum = (t2, e2, n2) => s(t2, e2, n2, "ReduceSum", () => ["value = 0.0;", "value += _A(inputIdx);", ""]), e.reduceMean = (t2, e2, n2) => s(t2, e2, n2, "ReduceMean", (t3, e3) => {
let n3 = 1;
for (let r2 = 0; r2 < t3[0].dims.length; r2++)
(e3.indexOf(r2) >= 0 || 0 === e3.length) && (n3 *= t3[0].dims[r2]);
return ["value = 0.0;", "value += _A(inputIdx);", `value /= ${n3}.;`];
}), e.reduceMax = (t2, e2, n2) => s(t2, e2, n2, "ReduceMax", (t3, e3) => {
const n3 = [];
for (let r2 = 0; r2 < t3[0].dims.length; r2++)
(e3.indexOf(r2) >= 0 || 0 === e3.length) && n3.push(`inputIdx[${r2}] = 0;`);
return [`${n3.join("\n")}
value = _A(inputIdx);`, "value = max(value, _A(inputIdx));", ""];
}), e.reduceMin = (t2, e2, n2) => s(t2, e2, n2, "ReduceMin", (t3, e3) => {
const n3 = [];
for (let r2 = 0; r2 < t3[0].dims.length; r2++)
(e3.indexOf(r2) >= 0 || 0 === e3.length) && n3.push(`inputIdx[${r2}] = 0;`);
return [`${n3.join("\n")}
value = _A(inputIdx);`, "value = min(value, _A(inputIdx));", ""];
}), e.reduceProd = (t2, e2, n2) => s(t2, e2, n2, "ReduceProd", () => ["value = 1.0;", "value *= _A(inputIdx);", ""]), e.reduceLogSum = (t2, e2, n2) => s(t2, e2, n2, "ReduceLogSum", () => ["value = 0.0;", "value += _A(inputIdx);", "value = log(value);"]), e.reduceLogSumSquare = (t2, e2, n2) => s(t2, e2, n2, "ReduceLogSumSquare", () => ["float t; value = 0.0;", "t = _A(inputIdx); value += t * t;", ""]);
}, 7019: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.isReshapeCheap = e.processDims3D = e.createPackedReshape3DProgramInfoLoader = void 0;
const r = n(2517), i = n(5060), o = n(2039), a = n(2827);
e.createPackedReshape3DProgramInfoLoader = (t2, e2, n2) => {
const s = ((t3) => ({ name: "Reshape (packed)", inputTypes: [o.TextureType.packed], inputNames: ["A"], cacheHint: `${t3}` }))(n2);
return Object.assign(Object.assign({}, s), { get: () => ((t3, e3, n3, s2) => {
const u = e3.dims, c = s2;
let l = "";
for (let t4 = 0; t4 < 4; t4++) {
let e4 = "";
switch (t4) {
case 0:
e4 = "outputCoords = rc;";
break;
case 1:
e4 = "outputCoords = ivec3(rc.x, rc.y+1, rc.z);";
break;
case 2:
e4 = "outputCoords = ivec3(rc.x, rc.y, rc.z+1);";
break;
case 3:
e4 = "outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";
break;
default:
throw new Error();
}
l += `
${e4}
${t4 > 0 ? "if(outputCoords.y < rows && outputCoords.z < cols){" : ""}
int flattenedIndex = getFlattenedIndex(outputCoords);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);
vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${t4}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);
${t4 > 0 ? "}" : ""}
`;
}
const p = (0, i.getGlsl)(t3.session.backend.glContext.version), f = `
${function(t4) {
const e4 = r.ShapeUtil.computeStrides(t4), n4 = ["b", "r", "c"], i2 = "index";
return `
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${e4.map((t5, r2) => `int ${n4[r2]} = ${i2} / ${t5}; ${r2 === e4.length - 1 ? `int ${n4[r2 + 1]} = ${i2} - ${n4[r2]} * ${t5}` : `index -= ${n4[r2]} * ${t5}`};`).join("")}
return ivec3(b, r, c);
}
`;
}(u)}
${function(t4) {
const e4 = r.ShapeUtil.computeStrides(t4);
return `
int getFlattenedIndex(ivec3 coords) {
// reverse y, z order
return coords.x * ${e4[0]} + coords.z * ${e4[1]} + coords.y;
}
`;
}(c)}
${(0, a.unpackFromChannel)()}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.0);
ivec3 outputCoords;
int rows = ${c[2]};
int cols = ${c[1]};
${l}
${p.output} = result;
}
`;
return Object.assign(Object.assign({}, n3), { output: { dims: c, type: e3.type, textureType: o.TextureType.packed }, shaderSource: f, hasMain: true });
})(t2, e2, s, n2) });
}, e.processDims3D = function(t2) {
if (0 === t2.length)
return [1, 1, 1];
let e2 = 1;
for (let n2 = 0; n2 < t2.length - 2; ++n2)
e2 *= t2[n2];
return [e2, t2.length > 1 ? t2[t2.length - 2] : 1, t2[t2.length - 1]];
}, e.isReshapeCheap = function(t2, e2) {
let n2 = false;
return n2 = 0 === t2.length || 0 === e2.length || (t2.length < 2 || e2.length < 2 ? t2[t2.length - 1] === e2[e2.length - 1] : t2[t2.length - 1] === e2[e2.length - 1] && t2[t2.length - 2] === e2[e2.length - 2]), n2;
};
}, 718: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.reshape = void 0;
const r = n(2517);
e.reshape = (t2, e2) => {
const n2 = r.ShapeUtil.calculateReshapedDims(e2[0].dims, e2[1].integerData);
return t2.session.pack ? [t2.reshapePacked(e2[0], n2)] : [t2.reshapeUnpacked(e2[0], n2)];
};
}, 2268: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2, n2) => ((0, s.validateInputs)(e2, n2), [t2.run(Object.assign(Object.assign({}, u), { cacheHint: n2.cacheKey, get: () => c(t2, e2, n2) }), e2)]), e.parseResizeAttributesV10 = (t2) => (0, s.parseUpsampleAttributes)(t2, 10), e.parseResizeAttributesV11 = (t2) => (0, s.parseUpsampleAttributes)(t2, 11);
const c = (t2, e2, n2) => {
const s2 = (0, r.getGlsl)(t2.session.backend.glContext.version), [c2, p2] = l(e2, n2);
if (c2.every((t3) => 1 === t3) && "tf_crop_and_resize" !== n2.coordinateTransformMode)
return Object.assign(Object.assign({}, u), { output: { dims: p2, type: e2[0].type, textureType: i.TextureType.packed }, hasMain: true, shaderSource: `void main() {
vec4 v = ${s2.texture2D}(X, TexCoords);
${s2.output} = v;
}` });
const f2 = p2.length;
if (f2 < 2)
throw new Error(`output dimension should be at least 2, but got ${f2}`);
const d = p2[f2 - 2], h = p2[f2 - 1], g = e2[0].dims;
if (f2 !== g.length)
throw new Error(`output dimension should match input ${g.length}, but got ${f2}`);
const b = g[f2 - 2], m = g[f2 - 1], y = c2[f2 - 2], _ = c2[f2 - 1];
let v = "";
if ("linear" !== n2.mode)
throw new Error(`resize (packed) does not support mode: '${n2.mode}'`);
switch (n2.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 = `
vec4 getSourceFracIndex(ivec4 coords) {
vec4 fcoords = vec4(coords);
return vec4(
${h}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,
${d}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,
${h}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,
${d}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0
);
}
`;
break;
case "align_corners":
v = `
vec4 getSourceFracIndex(ivec4 coords) {
vec4 resized = vec4(${h}.0 - 1.0, ${d}.0 - 1.0, ${h}.0 - 1.0,
${d}.0 - 1.0);
vec4 original = vec4(${m}.0 - 1.0, ${b}.0 - 1.0, ${m}.0 - 1.0,
${b}.0 - 1.0);
vec4 new_scale = original / resized;
return vec4(coords) * new_scale;
}
`;
break;
default:
throw new Error(`resize (packed) does not support coordinateTransformMode: '${n2.coordinateTransformMode}'`);
}
const w = (0, o.getCoordsDataType)(f2), x = `
const vec2 inputWH = vec2(${b}.0, ${m}.0);
const vec4 scaleWHWH = vec4(float(${y}), float(${_}), float(${y}), float(${_}));
${(0, a.unpackFromChannel)()}
${v}
float getAValue(int x10, int r, int c, int d) {
return getChannel(getA(x10, r, c, d), vec2(c, d));
}
void main() {
${w} rc = getOutputCoords();
int batch = rc[0];
int depth = rc[1];
// retrieve the 4 coordinates that is used in the 4 packed output values.
ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);
// calculate the source index in fraction
vec4 sourceFrac = getSourceFracIndex(coords);
// get the lower and upper bound of the 4 values that will be packed into one texel.
ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));
ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));
ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));
ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));
bool hasNextRow = rc.w < ${d - 1};
bool hasNextCol = rc.z < ${h - 1};
// pack x00, x01, x10, x11's top-left corner into one vec4 structure
vec4 topLeft = vec4(
getAValue(batch, depth, x00.x, x00.y),
hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,
hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,
(hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);
// pack x00, x01, x10, x11's top-right corner into one vec4 structure
vec4 topRight = vec4(
getAValue(batch, depth, x00.x, x00.w),
hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,
hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,
(hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);
// pack x00, x01, x10, x11's bottom-left corner into one vec4 structure
vec4 bottomLeft = vec4(
getAValue(batch, depth, x00.z, x00.y),
hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,
hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,
(hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);
// pack x00, x01, x10, x11's bottom-right corner into one vec4 structure
vec4 bottomRight = vec4(
getAValue(batch, depth, x00.z, x00.w),
hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,
hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,
(hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);
// calculate the interpolation fraction on u and v direction
vec4 frac = vec4(sourceFrac) - floor(sourceFrac);
vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));
vec4 top = mix(topLeft, topRight, clampFrac.ywyw);
vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);
vec4 newValue = mix(top, bottom, clampFrac.xxzz);
${s2.output} = vec4(newValue);
}
`;
return Object.assign(Object.assign({}, u), { output: { dims: p2, type: e2[0].type, textureType: i.TextureType.packed }, hasMain: true, shaderSource: x });
}, l = (t2, e2) => {
const n2 = t2[0].dims;
let r2, i2 = e2.scales;
if (0 === i2.length) {
const o3 = t2[e2.scalesInputIdx];
if (o3 && 0 !== o3.size) {
if (t2[e2.sizesInputIdx])
throw new Error("Only one of scales or sizes must be provided as input.");
i2 = p(o3, e2.mode, e2.isResize);
} else {
const o4 = t2[e2.sizesInputIdx];
if (!o4 || 0 === o4.size)
throw new Error("Either scales or sizes MUST be provided as input.");
r2 = Array.from(o4.integerData), i2 = f(r2, n2, e2.mode, e2.isResize);
}
} else if (t2[e2.sizesInputIdx])
throw new Error("Only one of scales or sizes must be provided as input.");
const o2 = r2 || n2.map((t3, e3) => Math.floor(t3 * i2[e3]));
return [i2, o2];
}, p = (t2, e2, n2) => {
const r2 = Array.from(t2.floatData);
return (0, s.scalesValidation)(r2, e2, n2), r2;
}, f = (t2, e2, n2, r2) => {
const i2 = e2.length, o2 = new Array(i2);
for (let n3 = 0, r3 = i2; n3 < r3; n3++)
if (0 === e2[n3]) {
if (0 !== t2[n3])
throw new Error("Input dim is zero but required output dim is non-zero.");
o2[n3] = 1;
} else
o2[n3] = t2[n3] / e2[n3];
return (0, s.scalesValidation)(o2, n2, r2), o2;
};
}, 8117: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.shape = void 0;
const r = n(9162);
e.shape = (t2, e2) => (i(e2), [new r.Tensor([e2[0].dims.length], "int32", void 0, void 0, new Int32Array(e2[0].dims))]);
const i = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Shape requires 1 input.");
};
}, 2278: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2, n2) => (c(e2), [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => u(t2, e2[0], n2) }), e2)]), e.parseSliceAttributes = (t2) => {
const e2 = t2.attributes.getInts("starts"), n2 = t2.attributes.getInts("ends"), i2 = t2.attributes.getInts("axes", []);
return (0, r.createAttributeWithCacheKey)({ starts: e2, ends: n2, axes: i2 });
};
const u = (t2, e2, n2) => {
const r2 = 0 === n2.axes.length ? e2.dims.slice(0).map((t3, e3) => e3) : n2.axes, i2 = o.ShapeUtil.normalizeAxes(r2, e2.dims.length), u2 = n2.starts.map((t3, n3) => t3 > e2.dims[i2[n3]] - 1 ? e2.dims[i2[n3]] : o.ShapeUtil.normalizeAxis(t3, e2.dims[i2[n3]])), c2 = n2.ends.map((t3, n3) => t3 > e2.dims[i2[n3]] - 1 ? e2.dims[i2[n3]] : o.ShapeUtil.normalizeAxis(t3, e2.dims[i2[n3]])), l2 = e2.dims.slice(), p2 = [];
for (let t3 = 0; t3 < i2.length; t3++)
l2[i2[t3]] = c2[t3] - u2[t3], u2[t3] > 0 && p2.push(`outputIdx[${i2[t3]}] += ${u2[t3]};`);
const f = `
float process(int outputIdx[${l2.length}]) {
${p2.join("\n ")}
return _A(outputIdx);
}`;
return Object.assign(Object.assign({}, s), { output: { dims: l2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f });
}, c = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Slice requires 1 input.");
if (-1 === i.NUMBER_TYPES.indexOf(t2[0].type))
throw new Error("Invalid input type.");
};
e.sliceV10 = (t2, e2) => {
p(e2);
const n2 = l(t2, e2);
return [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => u(t2, e2[0], n2) }), [e2[0]])];
};
const l = (t2, e2) => {
if (!t2.session.isInitializer(e2[1].dataId) || !t2.session.isInitializer(e2[2].dataId) || e2.length >= 4 && !t2.session.isInitializer(e2[3].dataId) || e2.length >= 5 && !t2.session.isInitializer(e2[4].dataId))
throw new Error("dynamic slice attributes are not allowed");
if (e2.length >= 5 && e2[4].integerData.some((t3) => 1 !== t3))
throw new Error("currently non-1 steps is not supported for Slice");
const n2 = Array.from(e2[1].integerData), r2 = Array.from(e2[2].integerData), i2 = e2.length >= 4 ? Array.from(e2[3].integerData) : [];
return { starts: n2, ends: r2, axes: i2, cacheKey: `${i2};${n2};${r2}` };
}, p = (t2) => {
if (!t2 || t2.length < 3 || t2.length > 5)
throw new Error("Invalid input number.");
if ("int32" !== t2[1].type || 1 !== t2[1].dims.length)
throw new Error("Invalid input type.");
if ("int32" !== t2[2].type || 1 !== t2[2].dims.length)
throw new Error("Invalid input type.");
if (t2.length >= 4 && ("int32" !== t2[3].type || 1 !== t2[3].dims.length))
throw new Error("Invalid input type.");
if (t2.length >= 5 && ("int32" !== t2[4].type || 1 !== t2[4].dims.length))
throw new Error("Invalid input type.");
};
}, 5524: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2, n2) => {
g(e2);
const r2 = e2[0].dims.slice(), o2 = i.ShapeUtil.normalizeAxis(n2.axis, r2.length), a2 = i.ShapeUtil.sizeToDimension(r2, o2), s2 = i.ShapeUtil.sizeFromDimension(r2, o2);
return p(t2, e2, n2, a2, s2);
}, e.parseSoftmaxAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", 1) }), e.parseSoftmaxAttributesV13 = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", -1) }), e.softmaxV13 = (t2, e2, n2) => {
g(e2);
const o2 = e2[0].dims.slice(), a2 = i.ShapeUtil.normalizeAxis(n2.axis, o2.length), u2 = o2.length, c2 = a2 !== u2 - 1, l2 = [];
let f2, d2 = [], h2 = [];
c2 && (d2 = Array.from({ length: u2 }).map((t3, e3) => e3), d2[a2] = u2 - 1, d2[u2 - 1] = a2, d2.map((t3) => l2.push(o2[t3])), f2 = (0, r.createAttributeWithCacheKey)({ perm: d2 }), h2 = (0, s.transpose)(t2, e2, f2));
const b = c2 ? i.ShapeUtil.sizeToDimension(l2, u2 - 1) : i.ShapeUtil.sizeToDimension(o2, u2 - 1), m = c2 ? i.ShapeUtil.sizeFromDimension(l2, u2 - 1) : i.ShapeUtil.sizeFromDimension(o2, u2 - 1), y = p(t2, c2 ? h2 : e2, n2, b, m);
return c2 ? (0, s.transpose)(t2, y, f2) : y;
};
const p = (t2, e2, n2, r2, i2) => {
const o2 = f(t2, e2[0], r2, i2, [r2]), a2 = t2.run(Object.assign(Object.assign({}, u), { cacheHint: n2.cacheKey, get: () => o2 }), e2), s2 = d(t2, e2[0], r2, i2, o2.output.dims, [r2]), p2 = t2.run(Object.assign(Object.assign({}, c), { cacheHint: n2.cacheKey, get: () => s2 }), [e2[0], a2]), g2 = h(t2, e2[0], r2, i2, o2.output.dims, s2.output.dims);
return [t2.run(Object.assign(Object.assign({}, l), { cacheHint: n2.cacheKey, get: () => g2 }), [e2[0], a2, p2])];
}, f = (t2, e2, n2, r2, i2) => {
const [s2, c2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), l2 = i2.length;
if (n2 < 1 || r2 < 1)
throw new Error("Logical row count N and feature count D must be greater than or equal to 1");
if (1 !== i2.length)
throw new Error("Dimensionality of the output should be 1");
if (i2[0] !== n2)
throw new Error("Shape of the output should be equal to logical row count");
const p2 = (0, o.getGlsl)(t2.session.backend.glContext.version), f2 = `
float process(int[${l2}] indices) {
int logical_row_start_offset = indices[0] * ${r2};
float max = getColorAsFloat(${p2.texture2D}(A, offsetToCoords(logical_row_start_offset, ${s2},
${c2} )));
for(int i=1; i<${r2}; ++i)
{
float current = getColorAsFloat(${p2.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
${s2}, ${c2})));
if(current > max)
max = current;
}
return max;
}`;
return Object.assign(Object.assign({}, u), { output: { dims: i2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f2 });
}, d = (t2, e2, n2, r2, i2, s2) => {
const [u2, l2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), p2 = s2.length;
if (n2 < 1 || r2 < 1)
throw new Error("Logical row count N and feature count D must be greater than or equal to 1");
if (1 !== s2.length)
throw new Error("Dimensionality of the output should be 1");
if (s2[0] !== n2)
throw new Error("Shape of the output should be equal to logical row count");
if (1 !== i2.length)
throw new Error("Dimensionality of the intermediate results should be 1");
if (i2[0] !== n2)
throw new Error("Shape of the intermediate results should be equal to logical row count");
const f2 = `
float process(int[${p2}] indices) {
int logical_row_start_offset = indices[0] * ${r2};
float norm_factor = 0.0;
float max = _Max(indices);
for(int i=0; i<${r2}; ++i)
{
norm_factor += exp(getColorAsFloat(${(0, o.getGlsl)(t2.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i,
${u2}, ${l2}))) - max);
}
return norm_factor;
}`;
return Object.assign(Object.assign({}, c), { output: { dims: s2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f2 });
}, h = (t2, e2, n2, r2, i2, o2) => {
const [s2, u2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), c2 = e2.dims.length;
if (n2 < 1 || r2 < 1)
throw new Error("Logical row count N and feature count D must be greater than or equal to 1");
if (1 !== i2.length || 1 !== o2.length)
throw new Error("Dimensionality of the intermediate results should be 1");
if (i2[0] !== n2 || o2[0] !== n2)
throw new Error("Shape of the intermediate results should be equal to logical row count");
const p2 = `
float process(int[${c2}] indices) {
// get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)
int offset = coordsToOffset(TexCoords, ${s2}, ${u2});
//determine the logical row for this index
int logical_row_index[1];
logical_row_index[0] = offset / ${r2};
float norm_factor = _Norm(logical_row_index);
// avoid possible division by 0
// if norm_facor is 0, all elements are zero
// if so, return 0
if(norm_factor == 0.0)
return 0.0;
return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;
}`;
return Object.assign(Object.assign({}, l), { output: { dims: e2.dims, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: p2 });
}, g = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Softmax requires 1 input.");
if ("float32" !== t2[0].type && "float64" !== t2[0].type)
throw new Error("Invalid input type");
};
}, 5975: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2, n2) => {
c(e2);
const r2 = i.ShapeUtil.normalizeAxis(n2.axis, e2[0].dims.length), o2 = s(t2, e2, r2, n2), l = [];
for (let i2 = 0; i2 < o2; ++i2)
l.push(t2.run(Object.assign(Object.assign({}, a), { cacheHint: `${n2.cacheKey};${i2}`, get: () => u(t2, e2[0], n2, r2, i2) }), e2));
return l;
}, e.parseSplitAttributes = (t2) => {
const e2 = t2.attributes.getInt("axis", 0), n2 = t2.attributes.getInts("split", []), i2 = t2.outputs.length;
return (0, r.createAttributeWithCacheKey)({ axis: e2, split: n2, numOutputs: i2 });
};
const s = (t2, e2, n2, r2) => {
const [, o2] = i.SplitUtil.splitShape(e2[0].dims, n2, r2.split, r2.numOutputs);
return o2.length;
}, u = (t2, e2, n2, r2, s2) => {
const [u2, c2] = i.SplitUtil.splitShape(e2.dims, r2, n2.split, n2.numOutputs), l = c2[s2], p = u2[s2], f = `
float process(int indices[${p.length}]) {
indices[${r2}] += ${l};
return _A(indices);
}
`;
return Object.assign(Object.assign({}, a), { cacheHint: `${n2.cacheKey}:${s2}`, output: { dims: p, type: e2.type, textureType: o.TextureType.unpacked }, shaderSource: f });
}, c = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Split requires one input.");
if ("int8" !== t2[0].type && "uint8" !== t2[0].type && "int16" !== t2[0].type && "uint16" !== t2[0].type && "int32" !== t2[0].type && "uint32" !== t2[0].type && "float32" !== t2[0].type && "float64" !== t2[0].type && "bool" !== t2[0].type)
throw new Error("Invalid input type.");
};
}, 3933: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseSqueezeAttributes = e.squeezeV13 = e.squeeze = void 0;
const r = n(2517);
e.squeeze = (t2, e2, n2) => {
i(e2);
const o2 = r.ShapeUtil.squeezeShape(e2[0].dims, n2);
return [t2.reshapeUnpacked(e2[0], o2)];
}, e.squeezeV13 = (t2, n2) => (o(n2), (0, e.squeeze)(t2, [n2[0]], Array.from(n2[1].integerData))), e.parseSqueezeAttributes = (t2) => t2.attributes.getInts("axes");
const i = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Squeeze requires 1 input.");
if ("string" === t2[0].type)
throw new Error("invalid input tensor types.");
}, o = (t2) => {
if (!t2 || 2 !== t2.length)
throw new Error("Squeeze requires 2 inputs.");
if ("int32" !== t2[1].type)
throw new Error("Invalid input type.");
};
}, 6558: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.sum = void 0;
const r = n(5060), i = n(2039);
e.sum = (t2, e2) => {
a(e2);
const n2 = { name: "Sum", inputNames: e2.map((t3, e3) => `X${e3}`), inputTypes: new Array(e2.length).fill(i.TextureType.unpacked) };
return [t2.run(Object.assign(Object.assign({}, n2), { get: () => o(t2, e2, n2) }), e2)];
};
const o = (t2, e2, n2) => {
const o2 = (0, r.getGlsl)(t2.session.backend.glContext.version), a2 = e2[0].dims.slice(), s = `
void main() {
vec4 result = ${e2.map((t3, e3) => `${o2.texture2D}(X${e3},TexCoords)`).join(" + ")};
${o2.output} = result;
}
`;
return Object.assign(Object.assign({}, n2), { output: { dims: a2, type: e2[0].type, textureType: i.TextureType.unpacked }, hasMain: true, shaderSource: s });
}, a = (t2) => {
if (!t2 || 0 === t2.length)
throw new Error("Sum requires inputs.");
const e2 = t2[0].dims.length;
for (let n2 = 1; n2 < t2.length; n2++) {
if (e2 !== t2[n2].dims.length)
throw new Error("Input shapes are mismatched.");
for (let r2 = 0; r2 < e2; r2++)
if (t2[0].dims[r2] !== t2[n2].dims[r2])
throw new Error("Input shapes are not matched.");
}
if ("float32" !== t2[0].type && "float64" !== t2[0].type)
throw new Error("Invalid input type.");
for (let e3 = 1; e3 < t2.length; e3++)
if (t2[0].type !== t2[e3].type)
throw new Error("Input types are not matched.");
};
}, 5723: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.tile = void 0;
const r = n(782), i = n(2039);
e.tile = (t2, e2) => {
a(e2);
const n2 = { name: "Tile", inputNames: ["A"], inputTypes: [i.TextureType.unpacked] };
return [t2.run(Object.assign(Object.assign({}, n2), { get: () => o(t2, e2, n2) }), e2)];
};
const o = (t2, e2, n2) => {
const r2 = e2[0].dims.slice(), o2 = new Array(r2.length), a2 = [];
for (let t3 = 0; t3 < r2.length; t3++)
o2[t3] = r2[t3] * e2[1].numberData[t3], a2.push(`inputIdx[${t3}] = int(mod(float(outputIdx[${t3}]), ${r2[t3]}.));`);
const s = o2.length, u = `
float process(int outputIdx[${s}]) {
int inputIdx[${s}];
${a2.join("\n")}
return _A(inputIdx);
}
`;
return Object.assign(Object.assign({}, n2), { output: { dims: o2, type: e2[0].type, textureType: i.TextureType.unpacked }, shaderSource: u });
}, a = (t2) => {
if (!t2 || 2 !== t2.length)
throw new Error("Tile requires 2 input.");
if (1 !== t2[1].dims.length)
throw new Error("The second input shape must 1 dimension.");
if (t2[1].dims[0] !== t2[0].dims.length)
throw new Error("Invalid input shape.");
if (-1 === r.NUMBER_TYPES.indexOf(t2[0].type))
throw new Error("Invalid input type.");
if ("int32" !== t2[1].type && "int16" !== t2[1].type)
throw new Error("Invalid repeat type.");
};
}, 3738: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2, n2) => (p(e2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: n2.cacheKey, get: () => s(t2, e2[0], n2.perm) }), e2)]), e.parseTransposeAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ perm: t2.attributes.getInts("perm", []) });
const s = (t2, e2, n2) => {
const r2 = e2.dims;
n2 = u(r2, n2);
const i2 = c(r2, n2), s2 = r2.length, p2 = `
${l("perm", n2, s2)}
float process(int indices[${s2}]) {
int a[${s2}];
perm(a, indices);
return _A(a);
}`;
return Object.assign(Object.assign({}, a), { output: { dims: i2, type: e2.type, textureType: o.TextureType.unpacked }, shaderSource: p2 });
}, u = (t2, e2) => (e2 && e2.length !== t2.length && (e2 = [...t2.keys()].reverse()), e2), c = (t2, e2) => (e2 = u(t2, e2), i.ShapeUtil.sortBasedOnPerm(t2, e2)), l = (t2, e2, n2) => {
const r2 = [];
r2.push(`void ${t2}(out int a[${n2}], int src[${n2}]) {`);
for (let t3 = 0; t3 < n2; ++t3)
r2.push(` a[${e2[t3]}]=src[${t3}];`);
return r2.push(" }"), r2.join("\n");
}, p = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Transpose requires 1 input.");
if ("float32" !== t2[0].type && "float64" !== t2[0].type)
throw new Error("input should be float tensor");
};
}, 8710: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.encodeAsUint8 = void 0;
const r = n(5060), i = n(2039);
e.encodeAsUint8 = (t2, e2) => {
const n2 = e2.shape, o = (0, r.getGlsl)(t2.session.backend.glContext.version), a = `
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
bool isNaN(float val) {
return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;
}
highp vec4 encodeAsUint8(highp float v) {
if (isNaN(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
void main() {
float value = ${o.texture2D}(X,TexCoords).r;
${o.output} = encodeAsUint8(value);
}`, s = { name: "Uint8Encode", inputTypes: [i.TextureType.unpacked], inputNames: ["X"], output: { dims: n2, type: e2.tensor.type, textureType: i.TextureType.downloadUint8AsFloat }, shaderSource: a, hasMain: true };
return t2.executeProgram(s, [e2.tensor]);
};
}, 4909: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2) {
const e2 = "elu";
return { body: `
const float alpha = float(${t2});
float ${e2}_(float a) {
return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;
}
vec4 ${e2}_(vec4 v) {
return vec4(${e2}_(v.x), ${e2}_(v.y), ${e2}_(v.z), ${e2}_(v.w));
}
`, name: e2, type: o.FunctionType.ValueBased };
}
function g() {
return P("exp");
}
function b() {
return P("floor");
}
function m(t2, e2) {
const n2 = "clip";
return { body: `
const float min = float(${t2});
const float max = float(${e2});
float ${n2}_(float a) {
return clamp(a, min, max);
}
vec4 ${n2}_(vec4 v) {
return clamp(v, min, max);
}
`, name: n2, type: o.FunctionType.ValueBased };
}
function y() {
const t2 = "indentity";
return { body: `
float ${t2}_(float a) {
return a;
}
vec4 ${t2}_(vec4 v) {
return v;
}
`, name: t2, type: o.FunctionType.ValueBased };
}
function _(t2) {
const e2 = "leakyRelu";
return { body: `
const float alpha = float(${t2});
float ${e2}_(float a) {
return a < 0.0 ? a * alpha : a;
}
vec4 ${e2}_(vec4 v) {
return vec4(${e2}_(v.x), ${e2}_(v.y), ${e2}_(v.z), ${e2}_(v.w));
}
`, name: e2, type: o.FunctionType.ValueBased };
}
function v() {
return P("log");
}
function w() {
const t2 = "neg";
return { body: `
float ${t2}_(float a) {
return -a;
}
vec4 ${t2}_(vec4 v) {
return -v;
}
`, name: t2, type: o.FunctionType.ValueBased };
}
function x() {
const t2 = "not";
return { body: `
float ${t2}_(float a) {
return float( ! bool(a) );
}
bool ${t2}_(bool a) {
return !a;
}
vec4 ${t2}_(vec4 v) {
return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));
}
bvec4 ${t2}_(bvec4 v) {
return bvec4(!v.x, !v.y, !v.z, !v.w);
}
`, name: t2, type: o.FunctionType.ValueBased };
}
function T() {
return P("sin");
}
function S() {
const t2 = "relu";
return { body: `
float ${t2}_(float a) {
return max( a, 0.0 );
}
vec4 ${t2}_(vec4 v) {
return max( v, 0.0 );
}
`, name: t2, type: o.FunctionType.ValueBased };
}
function O() {
const t2 = "sigmoid";
return { body: `
float ${t2}_(float a) {
return 1.0 / (1.0 + exp(-a));
}
vec4 ${t2}_(vec4 v) {
return 1.0 / (1.0 + exp(-v));
}
`, name: t2, type: o.FunctionType.ValueBased };
}
function A() {
return P("sqrt");
}
function E() {
return P("tan");
}
function I() {
const t2 = "tanh";
return { body: `
float ${t2}_(float a) {
a = clamp(a, -10., 10.);
a = exp(2.*a);
return (a - 1.) / (a + 1.);
}
vec4 ${t2}_(vec4 v) {
v = clamp(v, -10., 10.);
v = exp(2.*v);
return (v - 1.) / (v + 1.);
}
`, name: t2, type: o.FunctionType.ValueBased };
}
function P(t2) {
return { body: `
float ${t2}_(float a) {
return ${t2}(a);
}
vec4 ${t2}_(vec4 v) {
return ${t2}(v);
}
`, name: t2, 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 = (t2, e2, n2, r2) => {
const i2 = t2.session.pack ? s.TextureType.packed : s.TextureType.unpacked, o2 = { name: n2.name, inputTypes: [i2], inputNames: ["A"], cacheHint: r2 };
return Object.assign(Object.assign({}, o2), { get: () => ((t3, e3, n3, r3) => {
const i3 = t3.session.pack ? s.TextureType.packed : s.TextureType.unpacked, o3 = (0, a.getGlsl)(t3.session.backend.glContext.version);
return Object.assign(Object.assign({}, e3), { output: { dims: n3.dims, type: n3.type, textureType: i3 }, shaderSource: `
${r3.body}
void main() {
vec4 v = ${o3.texture2D}(A, TexCoords);
v = ${r3.name}_(v);
${o3.output} = v;
}
`, hasMain: true });
})(t2, o2, e2, n2) });
};
e.abs = (t2, e2) => [t2.run(D(t2, e2[0], u()), e2)], e.acos = (t2, e2) => [t2.run(D(t2, e2[0], c()), e2)], e.asin = (t2, e2) => [t2.run(D(t2, e2[0], l()), e2)], e.atan = (t2, e2) => [t2.run(D(t2, e2[0], p()), e2)], e.clip = (t2, e2, n2) => [t2.run(D(t2, e2[0], m(n2.min, n2.max), n2.cacheKey), e2)], e.parseClipAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ min: t2.attributes.getFloat("min", i.MIN_CLIP), max: t2.attributes.getFloat("max", i.MAX_CLIP) }), e.clipV11 = (t2, n2) => {
const r2 = $(t2, n2);
return (0, e.clip)(t2, [n2[0]], r2);
};
const $ = (t2, e2) => {
if (e2.length >= 3 && (!t2.session.isInitializer(e2[1].dataId) || !t2.session.isInitializer(e2[2].dataId)))
throw new Error("dynamic clip attributes are not allowed");
const n2 = e2.length >= 3 ? e2[1].numberData[0] : i.MIN_CLIP, o2 = e2.length >= 3 ? e2[2].numberData[0] : i.MAX_CLIP;
return (0, r.createAttributeWithCacheKey)({ min: n2, max: o2 });
};
e.ceil = (t2, e2) => [t2.run(D(t2, e2[0], f()), e2)], e.cos = (t2, e2) => [t2.run(D(t2, e2[0], d()), e2)], e.elu = (t2, e2, n2) => [t2.run(D(t2, e2[0], h(n2.alpha), n2.cacheKey), e2)], e.parseEluAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ alpha: t2.attributes.getFloat("alpha", 1) }), e.exp = (t2, e2) => [t2.run(D(t2, e2[0], g()), e2)], e.floor = (t2, e2) => [t2.run(D(t2, e2[0], b()), e2)], e.identity = (t2, e2) => [t2.run(D(t2, e2[0], y()), e2)], e.leakyRelu = (t2, e2, n2) => [t2.run(D(t2, e2[0], _(n2.alpha), n2.cacheKey), e2)], e.parseLeakyReluAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ alpha: t2.attributes.getFloat("alpha", 0.01) }), e.log = (t2, e2) => [t2.run(D(t2, e2[0], v()), e2)], e.neg = (t2, e2) => [t2.run(D(t2, e2[0], w()), e2)], e.not = (t2, e2) => [t2.run(D(t2, e2[0], x()), e2)], e.relu = (t2, e2) => [t2.run(D(t2, e2[0], S()), e2)], e.sigmoid = (t2, e2) => [t2.run(D(t2, e2[0], O()), e2)], e.sin = (t2, e2) => [t2.run(D(t2, e2[0], T()), e2)], e.sqrt = (t2, e2) => [t2.run(D(t2, e2[0], A()), e2)], e.tan = (t2, e2) => [t2.run(D(t2, e2[0], E()), e2)], e.tanh = (t2, e2) => [t2.run(D(t2, e2[0], I()), e2)];
}, 5611: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2) => {
const n2 = e2.dims.length, u = (0, a.getChannels)("rc", n2), c = u.slice(-2), l = (0, o.getCoordsDataType)(n2), p = (0, a.unpackFromChannel)(), f = 0 === e2.dims.length ? "" : function(t3, e3) {
if (1 === t3)
return "rc";
let n3 = "";
for (let r2 = 0; r2 < t3; r2++)
n3 += e3[r2], r2 < t3 - 1 && (n3 += ",");
return n3;
}(n2, u), d = n2 <= 1 ? "rc" : `vec2(${c.join(",")})`, h = `
${p}
void main() {
${l} rc = getOutputCoords();
// Sample the texture with the coords to get the rgba channel value.
vec4 packedInput = getA(${f});
${(0, r.getGlsl)(t2.session.backend.glContext.version).output} = vec4(getChannel(packedInput, ${d}), 0, 0, 0);
}
`;
return Object.assign(Object.assign({}, s), { hasMain: true, output: { dims: e2.dims, type: e2.type, textureType: i.TextureType.unpacked }, shaderSource: h });
}, e.createUnpackProgramInfoLoader = (t2, n2) => Object.assign(Object.assign({}, s), { get: () => (0, e.createUnpackProgramInfo)(t2, n2) });
}, 8428: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.parseUnsqueezeAttributes = e.unsqueezeV13 = e.unsqueeze = void 0;
const r = n(2517);
e.unsqueeze = (t2, e2, n2) => {
i(e2);
const o2 = r.ShapeUtil.unsqueezeShape(e2[0].dims, n2);
return [t2.reshapeUnpacked(e2[0], o2)];
}, e.unsqueezeV13 = (t2, n2) => (o(n2), (0, e.unsqueeze)(t2, [n2[0]], Array.from(n2[1].integerData))), e.parseUnsqueezeAttributes = (t2) => t2.attributes.getInts("axes");
const i = (t2) => {
if (!t2 || 1 !== t2.length)
throw new Error("Unsqueeze requires 1 input.");
if ("string" === t2[0].type)
throw new Error("invalid input tensor types.");
}, o = (t2) => {
if (!t2 || 2 !== t2.length)
throw new Error("Unsqueeze requires 2 inputs.");
if ("int32" !== t2[1].type)
throw new Error("Invalid input type.");
};
}, 9793: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, n2, r2) => ((0, e.validateInputs)(n2, r2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: r2.cacheKey, get: () => s(t2, n2, r2) }), n2)]), e.parseUpsampleAttributesV7 = (t2) => (0, e.parseUpsampleAttributes)(t2, 7), e.parseUpsampleAttributesV9 = (t2) => (0, e.parseUpsampleAttributes)(t2, 9), e.parseUpsampleAttributes = (t2, n2) => {
const i2 = n2 >= 10, o2 = t2.attributes.getString("mode", "nearest");
if ("nearest" !== o2 && "linear" !== o2 && (n2 < 11 || "cubic" !== o2))
throw new Error(`unrecognized mode: ${o2}`);
let a2 = [];
n2 < 9 && (a2 = t2.attributes.getFloats("scales"), (0, e.scalesValidation)(a2, o2, i2));
const s2 = t2.attributes.getFloat("extrapolation_value", 0), u = n2 > 10 ? t2.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" === o2 && n2 >= 11 ? t2.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 = t2.attributes.getFloat("cubic_coeff_a", -0.75), d = 0 !== t2.attributes.getInt("exclude_outside", 0);
if (d && "cubic" !== o2)
throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");
const h = n2 < 11 || "nearest" === o2 && "asymmetric" === u && "floor" === p;
let g = 0, b = 0, m = 0;
return n2 > 10 ? t2.inputs.length > 2 ? (g = 1, b = 2, m = 3) : (b = 1, m = 2) : 9 === n2 && (b = 1), (0, r.createAttributeWithCacheKey)({ opset: n2, isResize: i2, mode: o2, scales: a2, extrapolationValue: s2, coordinateTransformMode: u, useExtrapolation: l, needRoiInput: c, nearestMode: p, cubicCoefficientA: f, excludeOutside: d, useNearest2xOptimization: h, roiInputIdx: g, scalesInputIdx: b, sizesInputIdx: m });
};
const s = (t2, e2, n2) => {
const r2 = (0, i.getGlsl)(t2.session.backend.glContext.version), [s2, u] = t2.calculateTextureWidthAndHeight(e2[0].dims, o.TextureType.unpacked), c = e2[0].dims.map((t3, e3) => Math.floor(t3 * n2.scales[e3])), [l, p] = t2.calculateTextureWidthAndHeight(c, o.TextureType.unpacked), f = c.length, d = new Array(f), h = new Array(f);
let g = `
int output_pitches[${f}];
int input_pitches[${f}];
`;
for (let t3 = f - 1; t3 >= 0; t3--)
d[t3] = t3 === f - 1 ? 1 : d[t3 + 1] * c[t3 + 1], h[t3] = t3 === f - 1 ? 1 : h[t3 + 1] * e2[0].dims[t3 + 1], g += `
output_pitches[${t3}] = ${d[t3]};
input_pitches[${t3}] = ${h[t3]};
`;
const b = `
float getInputFloat(int index) {
vec2 coords = offsetToCoords(index, ${s2}, ${u});
float value = getColorAsFloat(${r2.texture2D}(X, coords));
return value;
}
`, m = "nearest" === n2.mode ? `
${b}
float process(int indices[${f}]) {
int input_index = 0;
int output_index = coordsToOffset(TexCoords, ${l}, ${p});
${g}
int d, m;
for (int dim = 0; dim < ${f}; ++dim) {
d = output_index / output_pitches[dim];
m = output_index - d * output_pitches[dim];
output_index = m;
if (scales[dim] != 1 && d > 0) {
int d2 = d / scales[dim];
m = d - d2 * scales[dim];
d = d2;
}
input_index += input_pitches[dim] * d;
}
return getInputFloat(input_index);
}` : 4 === f ? `
${b}
float process(int indices[4]) {
int input_index = 0;
int output_index = coordsToOffset(TexCoords, ${l}, ${p});
${g}
int m;
int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;
index_of_dim0 = output_index / output_pitches[0];
m = output_index - index_of_dim0 * output_pitches[0];
index_of_dim1 = m / output_pitches[1];
m = m - index_of_dim1 * output_pitches[1];
index_of_dim2 = m / output_pitches[2];
m = m - index_of_dim2 * output_pitches[2];
index_of_dim3 = m;
int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;
index_of_input_dim2 = index_of_dim2 / scales[2];
y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];
index_of_input_dim3 = index_of_dim3 / scales[3];
x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];
input_index = index_of_dim0 * input_pitches[0] +
index_of_dim1 * input_pitches[1] +
index_of_input_dim2 * input_pitches[2] +
index_of_input_dim3;
float x00 = getInputFloat(input_index);
float x10, x01, x11;
bool end_of_dim2 = false;
if (index_of_input_dim2 == (${e2[0].dims[2]} - 1)) {
// It's the end in dimension 2
x01 = x00;
end_of_dim2 = true;
} else {
x01 = getInputFloat(input_index + input_pitches[2]);
}
if (index_of_input_dim3 == (input_pitches[2] - 1)) {
// It's the end in dimension 3
x10 = x00;
x11 = x01;
}
else {
x10 = getInputFloat(input_index + 1);
x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);
}
float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);
float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);
return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);
}` : `
${b}
float process(int indices[2]) {
int input_index = 0;
int output_index = coordsToOffset(TexCoords, ${l}, ${p});
${g}
int m;
int index_of_dim0, index_of_dim1;
index_of_dim0 = output_index / output_pitches[0];
m = output_index - index_of_dim0 * output_pitches[0];
index_of_dim1 = m;
int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;
index_of_input_dim0 = index_of_dim0 / scales[0];
y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];
index_of_input_dim1 = index_of_dim1 / scales[1];
x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];
input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;
float x00 = getInputFloat(input_index);
float x10, x01, x11;
bool end_of_dim0 = false;
if (index_of_input_dim0 == (${e2[0].dims[0]} - 1)) {
// It's the end in dimension 0
x01 = x00;
end_of_dim0 = true;
} else {
x01 = getInputFloat(input_index + input_pitches[0]);
}
if (index_of_input_dim1 == (input_pitches[0] - 1)) {
// It's the end in dimension 1
x10 = x00;
x11 = x01;
}
else {
x10 = getInputFloat(input_index + 1);
x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);
}
float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);
float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);
return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);
}`;
return Object.assign(Object.assign({}, a), { output: { dims: c, type: e2[0].type, textureType: o.TextureType.unpacked }, shaderSource: m, variables: [{ name: "scales", type: "int", arrayLength: n2.scales.length, data: n2.scales.map((t3) => Math.ceil(t3)) }] });
};
e.validateInputs = (t2, e2) => {
if (!t2 || e2.opset < 9 && 1 !== t2.length || e2.opset >= 9 && e2.opset < 11 && 2 !== t2.length || e2.opset >= 11 && t2.length < 2)
throw new Error("invalid inputs.");
if (e2.scales.length > 0 && t2[0].dims.length !== e2.scales.length)
throw new Error("Invalid input shape.");
if ("string" === t2[0].type)
throw new Error("Invalid input tensor types.");
}, e.scalesValidation = (t2, e2, n2) => {
if (n2) {
for (const e3 of t2)
if (e3 <= 0)
throw new Error("Scale value should be greater than 0.");
} else
for (const e3 of t2)
if (e3 < 1)
throw new Error("Scale value should be greater than or equal to 1.");
if (!("linear" !== e2 && "cubic" !== e2 || 2 === t2.length || 4 === t2.length && 1 === t2[0] && 1 === t2[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 ${n2 ? "Resize" : "Upsample"} opeartor.`);
};
}, 1958: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.ProgramManager = void 0;
const r = n(1670), i = n(6231), o = n(8879), a = n(5060);
e.ProgramManager = class {
constructor(t2, e2, n2) {
this.profiler = t2, this.glContext = e2, this.textureLayoutStrategy = n2, this.repo = /* @__PURE__ */ new Map(), this.attributesBound = false;
}
getArtifact(t2) {
return this.repo.get(t2);
}
setArtifact(t2, e2) {
this.repo.set(t2, e2);
}
run(t2, e2, n2) {
var r2;
this.profiler.event("op", `ProgramManager.run ${null !== (r2 = t2.programInfo.name) && void 0 !== r2 ? r2 : "unknown kernel"}`, () => {
var r3;
const o2 = this.glContext.gl, a2 = t2.program;
o2.useProgram(a2);
try {
this.bindOutput(n2), this.attributesBound || this.bindAttributes(t2.attribLocations), this.bindUniforms(t2.uniformLocations, null !== (r3 = t2.programInfo.variables) && void 0 !== r3 ? r3 : [], e2);
} catch (e3) {
throw i.Logger.error("ProgramManager", t2.programInfo.shaderSource), e3;
}
this.profiler.event("backend", "GlContext.draw()", () => {
this.glContext.draw();
});
}, this.glContext);
}
dispose() {
this.vertexShader && this.glContext.deleteShader(this.vertexShader), this.repo.forEach((t2) => this.glContext.deleteProgram(t2.program));
}
build(t2, e2, n2) {
return this.profiler.event("backend", "ProgramManager.build", () => {
const r2 = new o.GlslPreprocessor(this.glContext, t2, e2, n2), i2 = r2.preprocess(), a2 = this.compile(i2);
return { programInfo: t2, program: a2, uniformLocations: this.getUniformLocations(a2, r2.context.programInfo.inputNames, r2.context.programInfo.variables), attribLocations: this.getAttribLocations(a2) };
});
}
compile(t2) {
if (!this.vertexShader) {
i.Logger.verbose("ProrgramManager", "Compiling and caching Vertex shader for the first time");
const t3 = (0, a.getVertexShaderSource)(this.glContext.version);
this.vertexShader = this.glContext.compileShader(t3, this.glContext.gl.VERTEX_SHADER);
}
r.env.debug && i.Logger.verbose("ProrgramManager", `FragShader:
${t2}
`);
const e2 = this.glContext.compileShader(t2, this.glContext.gl.FRAGMENT_SHADER), n2 = this.glContext.createProgram(this.vertexShader, e2);
return this.glContext.deleteShader(e2), n2;
}
bindOutput(t2) {
const e2 = t2.width, n2 = t2.height;
i.Logger.verbose("ProrgramManager", `Binding output texture to Framebuffer: w/h=${e2}/${n2}, shape=${t2.shape}, type=${t2.tensor.type}`), this.glContext.attachFramebuffer(t2.texture, e2, n2);
}
bindAttributes(t2) {
const e2 = t2.position, n2 = t2.textureCoord;
this.glContext.setVertexAttributes(e2, n2), this.attributesBound = true;
}
bindUniforms(t2, e2, n2) {
var r2;
const i2 = this.glContext.gl;
let o2 = 0;
for (const { name: a2, type: s, location: u, arrayLength: c } of t2) {
const t3 = null === (r2 = e2.find((t4) => t4.name === a2)) || void 0 === r2 ? void 0 : r2.data;
if ("sampler2D" !== s && !t3)
throw new Error(`variable '${a2}' does not have data defined in program info`);
switch (s) {
case "sampler2D":
this.bindTexture(n2[o2], u, o2), o2++;
break;
case "float":
c ? i2.uniform1fv(u, t3) : i2.uniform1f(u, t3);
break;
case "int":
c ? i2.uniform1iv(u, t3) : i2.uniform1i(u, t3);
break;
default:
throw new Error(`Uniform not implemented: ${s}`);
}
}
}
bindTexture(t2, e2, n2) {
this.glContext.bindTextureToUniform(t2.texture, n2, e2);
}
getAttribLocations(t2) {
return { position: this.getAttribLocation(t2, "position"), textureCoord: this.getAttribLocation(t2, "textureCoord") };
}
getUniformLocations(t2, e2, n2) {
const r2 = [];
if (e2)
for (const n3 of e2)
r2.push({ name: n3, type: "sampler2D", location: this.getUniformLocation(t2, n3) });
if (n2)
for (const e3 of n2)
r2.push(Object.assign(Object.assign({}, e3), { location: this.getUniformLocation(t2, e3.name) }));
return r2;
}
getUniformLocation(t2, e2) {
const n2 = this.glContext.gl.getUniformLocation(t2, e2);
if (null === n2)
throw new Error(`Uniform ${e2} not found.`);
return n2;
}
getAttribLocation(t2, e2) {
return this.glContext.gl.getAttribLocation(t2, e2);
}
};
}, 6416: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2, e2) {
this.backend = t2, this.context = e2, this.layoutStrategy = new u.PreferLogicalStrategy(t2.glContext.maxTextureSize), this.programManager = new s.ProgramManager(this.context.profiler, t2.glContext, this.layoutStrategy), this.textureManager = new c.TextureManager(t2.glContext, this.layoutStrategy, this.context.profiler, { reuseTextures: "full" === t2.textureCacheMode }), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(), this.pack = t2.pack, this.pack2unpackMap = /* @__PURE__ */ new Map(), this.unpack2packMap = /* @__PURE__ */ new Map();
}
createInferenceHandler() {
return new o.WebGLInferenceHandler(this);
}
onGraphInitialized(t2) {
const e2 = t2.getValues().filter((t3) => -1 === t3.from && t3.tensor).map((t3) => t3.tensor.dataId);
this.initializers = new Set(e2);
}
isInitializer(t2) {
return !!this.initializers && this.initializers.has(t2);
}
addInitializer(t2) {
this.initializers.add(t2);
}
getTextureData(t2, e2) {
return e2 ? this.packedTextureDataCache.get(t2) : this.unpackedTextureDataCache.get(t2);
}
setTextureData(t2, e2, n2 = false) {
r.Logger.verbose("WebGLSessionHandler", "Storing Texture data in cache"), n2 ? this.packedTextureDataCache.set(t2, e2) : this.unpackedTextureDataCache.set(t2, e2);
}
dispose() {
this.programManager.dispose(), this.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach((t2) => this.textureManager.releaseTexture(t2, true)), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach((t2) => this.textureManager.releaseTexture(t2, true)), this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
}
resolve(t2, e2, n2) {
const r2 = (0, i.resolveOperator)(t2, e2, a.WEBGL_OP_RESOLVE_RULES);
return { impl: r2.opImpl, context: r2.opInit ? r2.opInit(t2, n2) : t2 };
}
};
}, 7769: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.Uint8DataEncoder = e.RGBAFloatDataEncoder = e.RedFloat32DataEncoder = void 0;
const r = n(6231);
e.RedFloat32DataEncoder = class {
constructor(t2, e2 = 1) {
if (1 === e2)
this.internalFormat = t2.R32F, this.format = t2.RED, this.textureType = t2.FLOAT, this.channelSize = e2;
else {
if (4 !== e2)
throw new Error(`Invalid number of channels: ${e2}`);
this.internalFormat = t2.RGBA32F, this.format = t2.RGBA, this.textureType = t2.FLOAT, this.channelSize = e2;
}
}
encode(t2, e2) {
let n2, i;
return t2.constructor !== Float32Array && (r.Logger.warning("Encoder", "data was not of type Float32; creating new Float32Array"), i = new Float32Array(t2)), e2 * this.channelSize > t2.length ? (r.Logger.warning("Encoder", "Source data too small. Allocating larger array"), i = t2, n2 = this.allocate(e2 * this.channelSize), i.forEach((t3, e3) => n2[e3] = t3)) : (i = t2, n2 = i), n2;
}
allocate(t2) {
return new Float32Array(4 * t2);
}
decode(t2, e2) {
return 1 === this.channelSize ? t2.filter((t3, e3) => e3 % 4 == 0).subarray(0, e2) : t2.subarray(0, e2);
}
}, e.RGBAFloatDataEncoder = class {
constructor(t2, e2 = 1, n2) {
if (1 !== e2 && 4 !== e2)
throw new Error(`Invalid number of channels: ${e2}`);
this.internalFormat = t2.RGBA, this.format = t2.RGBA, this.channelSize = e2, this.textureType = n2 || t2.FLOAT;
}
encode(t2, e2) {
let n2 = t2;
return 1 === this.channelSize && (r.Logger.verbose("Encoder", "Exploding into a larger array"), n2 = this.allocate(e2), t2.forEach((t3, e3) => n2[4 * e3] = t3)), n2;
}
allocate(t2) {
return new Float32Array(4 * t2);
}
decode(t2, e2) {
return 1 === this.channelSize ? t2.filter((t3, e3) => e3 % 4 == 0).subarray(0, e2) : t2.subarray(0, e2);
}
}, e.Uint8DataEncoder = class {
constructor(t2, e2 = 1) {
if (this.channelSize = 4, 1 === e2)
this.internalFormat = t2.ALPHA, this.format = t2.ALPHA, this.textureType = t2.UNSIGNED_BYTE, this.channelSize = e2;
else {
if (4 !== e2)
throw new Error(`Invalid number of channels: ${e2}`);
this.internalFormat = t2.RGBA, this.format = t2.RGBA, this.textureType = t2.UNSIGNED_BYTE, this.channelSize = e2;
}
}
encode(t2, e2) {
return new Uint8Array(t2.buffer, t2.byteOffset, t2.byteLength);
}
allocate(t2) {
return new Uint8Array(t2 * this.channelSize);
}
decode(t2, e2) {
if (t2 instanceof Uint8Array)
return t2.subarray(0, e2);
throw new Error(`Invalid array type: ${t2.constructor}`);
}
};
}, 7859: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2, e2) {
const n2 = [], r2 = [], i2 = null != e2 && Array.isArray(e2) && 0 === e2.length, o2 = null == e2 || i2 ? null : a(e2, t2).sort();
let s2 = 0;
for (let e3 = 0; e3 < t2.length; ++e3) {
if (null != o2) {
if (o2[s2] === e3 && 1 !== t2[e3])
throw new Error(`Can't squeeze axis ${e3} since its dim '${t2[e3]}' is not 1`);
(null == o2[s2] || o2[s2] > e3) && 1 === t2[e3] && (n2.push(t2[e3]), r2.push(e3)), o2[s2] <= e3 && s2++;
}
1 !== t2[e3] && (n2.push(t2[e3]), r2.push(e3));
}
return { newShape: n2, keptDims: r2 };
}
function a(t2, e2) {
const n2 = e2.length;
return t2 = null == t2 ? e2.map((t3, e3) => e3) : [].concat(t2), (0, i.assert)(t2.every((t3) => t3 >= -n2 && t3 < n2), () => `All values in axis param must be in range [-${n2}, ${n2}) but got axis ${t2}`), (0, i.assert)(t2.every(s), () => `All values in axis param must be integers but got axis ${t2}`), t2.map((t3) => t3 < 0 ? n2 + t3 : t3);
}
function s(t2) {
return t2 % 1 == 0;
}
function u(t2) {
if (0 === t2.length)
return 1;
let e2 = t2[0];
for (let n2 = 1; n2 < t2.length; n2++)
e2 *= t2[n2];
return e2;
}
function c(t2) {
const e2 = Math.ceil(Math.sqrt(t2));
return [e2, Math.ceil(t2 / e2)];
}
e.AlwaysKeepOriginalSizeStrategy = class {
constructor(t2) {
this.maxTextureSize = t2;
}
computeTextureWH(t2, e2) {
if (0 === t2.length)
return [1, 1];
const n2 = this.maxTextureSize;
if (e2 && void 0 !== e2.breakAxis) {
const i3 = e2.breakAxis >= t2.length ? 1 : t2.slice(e2.breakAxis).reduce((t3, e3) => t3 * e3), o3 = e2.breakAxis <= 0 ? 1 : t2.slice(0, e2.breakAxis).reduce((t3, e3) => t3 * e3);
if (!(i3 > n2 || o3 > n2))
return [i3, o3];
r.Logger.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${t2}, breakAxis:${e2.breakAxis}`);
}
const i2 = t2.reduce((t3, e3) => t3 * e3);
let o2 = Math.floor(Math.sqrt(i2));
for (; o2 < n2 && o2 < i2 && i2 % o2 != 0; o2++)
;
if (o2 >= n2 || i2 % o2 != 0)
throw new Error(`The given dimensions are outside this GPU's boundaries: ${t2}`);
return [o2, i2 / o2];
}
}, e.PreferLogicalStrategy = class {
constructor(t2) {
this.maxTextureSize = t2;
}
computeTextureWH(t2, e2) {
const n2 = this.computeTexture(t2, e2);
return e2 && e2.isPacked && (n2[0] /= 2, n2[1] /= 2), e2 && e2.reverseWH ? [n2[1], n2[0]] : n2;
}
computeTexture(t2, e2) {
const n2 = e2 && e2.isPacked;
if (0 === t2.length)
return n2 ? [2, 2] : [1, 1];
let i2 = this.maxTextureSize;
if (e2 && void 0 !== e2.breakAxis) {
const n3 = e2.breakAxis >= t2.length ? 1 : t2.slice(e2.breakAxis).reduce((t3, e3) => t3 * e3), o2 = e2.breakAxis <= 0 ? 1 : t2.slice(0, e2.breakAxis).reduce((t3, e3) => t3 * e3);
if (!(n3 > i2 || o2 > i2))
return [n3, o2];
r.Logger.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${t2}, breakAxis:${e2.breakAxis}`);
}
let a2 = t2.slice(0);
if (n2 && (i2 *= 2, a2 = a2.map((t3, e3) => e3 >= a2.length - 2 ? a2[e3] % 2 == 0 ? a2[e3] : a2[e3] + 1 : a2[e3]), 1 === a2.length && (a2 = [2, a2[0]])), 2 !== a2.length) {
const t3 = o(a2);
a2 = t3.newShape;
}
const s2 = u(a2);
return a2.length <= 1 && s2 <= i2 ? [1, s2] : 2 === a2.length && a2[0] <= i2 && a2[1] <= i2 ? a2 : 3 === a2.length && a2[0] * a2[1] <= i2 && a2[2] <= i2 ? [a2[0] * a2[1], a2[2]] : 3 === a2.length && a2[0] <= i2 && a2[1] * a2[2] <= i2 ? [a2[0], a2[1] * a2[2]] : 4 === a2.length && a2[0] * a2[1] * a2[2] <= i2 && a2[3] <= i2 ? [a2[0] * a2[1] * a2[2], a2[3]] : 4 === a2.length && a2[0] <= i2 && a2[1] * a2[2] * a2[3] <= i2 ? [a2[0], a2[1] * a2[2] * a2[3]] : n2 ? c(s2 / 4).map((t3) => 2 * t3) : c(s2);
}
}, e.squeezeShape = o, e.parseAxisParam = a, e.isInt = s, e.sizeFromShape = u, e.getRowsCols = function(t2) {
if (0 === t2.length)
throw Error("Cannot get rows and columns of an empty shape array.");
return [t2.length > 1 ? t2[t2.length - 2] : 1, t2[t2.length - 1]];
}, e.sizeToSquarishShape = c, e.getBatchDim = function(t2, e2 = 2) {
return u(t2.slice(0, t2.length - e2));
};
}, 4057: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.createTextureLayoutFromShape = e.calculateTextureWidthAndHeight = e.createTextureLayoutFromTextureType = void 0;
const r = n(2517), i = n(2039);
e.createTextureLayoutFromTextureType = (t2, n2, r2) => {
const o = r2 === i.TextureType.unpacked || r2 === i.TextureType.unpackedReversed ? 1 : 4, a = r2 === i.TextureType.packed, s = r2 === i.TextureType.unpackedReversed || r2 === i.TextureType.packed, u = r2 === i.TextureType.packedLastDimension ? n2.length - 1 : void 0, c = r2 === i.TextureType.packedLastDimension ? n2.map((t3, e2) => e2 === n2.length - 1 ? 4 * t3 : t3) : void 0;
return (0, e.createTextureLayoutFromShape)(t2, n2, o, c, { isPacked: a, reverseWH: s, breakAxis: u });
}, e.calculateTextureWidthAndHeight = (t2, n2, r2) => {
const i2 = (0, e.createTextureLayoutFromTextureType)(t2, n2, r2);
return [i2.width, i2.height];
}, e.createTextureLayoutFromShape = (t2, e2, n2 = 1, i2, o) => {
const a = !(!o || !o.isPacked), [s, u] = t2.computeTextureWH(a && i2 || e2, o), c = e2.length;
let l = e2.slice(0);
if (0 === c && (l = [1]), 1 === n2)
i2 = e2;
else if (a) {
if (4 !== n2)
throw new Error("a packed texture must be 4-channel");
i2 = e2, c > 0 && (l[c - 1] = Math.ceil(l[c - 1] / 2)), c > 1 && (l[c - 2] = Math.ceil(l[c - 2] / 2));
} else if (!i2)
throw new Error("Unpacked shape is needed when using channels > 1");
return { width: s, height: u, channels: n2, isPacked: a, shape: l, strides: r.ShapeUtil.computeStrides(l), unpackedShape: i2, reversedWH: o && o.reverseWH };
};
}, 5702: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.TextureManager = void 0;
const r = n(6231);
e.TextureManager = class {
constructor(t2, e2, n2, r2) {
this.glContext = t2, this.layoutStrategy = e2, this.profiler = n2, this.config = r2, this.pendingRead = /* @__PURE__ */ new Map(), r2.reuseTextures && (this.inUseTextures = /* @__PURE__ */ new Map(), this.idleTextures = /* @__PURE__ */ new Map(), this.textureLookup = /* @__PURE__ */ new Map());
}
createTextureFromLayout(t2, e2, n2, i) {
const o = this.toEncoderType(t2), a = this.glContext.getEncoder(o, e2.channels || 1, i);
if (e2.isPacked && 1 === i)
throw new Error("not implemented");
const s = e2.width, u = e2.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 e3 = this.idleTextures.get(c);
if (e3 && e3.length > 0) {
const r2 = e3.pop();
return l.push(r2), 1 === i && this.glContext.updateTexture(r2, s, u, a, this.toTextureData(t2, n2)), r2;
}
}
r.Logger.verbose("TextureManager", `Creating new texture of size ${e2.width}x${e2.height}`);
const p = this.glContext.allocateTexture(s, u, a, this.toTextureData(t2, n2));
return this.config.reuseTextures && (l.push(p), this.textureLookup.set(p, c)), p;
}
readTexture(t2, e2, n2) {
return n2 || (n2 = 1), this.profiler.event("backend", "TextureManager.readTexture", () => {
const r2 = t2.shape.reduce((t3, e3) => t3 * e3) * n2, i = this.glContext.readTexture(t2.texture, t2.width, t2.height, r2, this.toEncoderType(e2), n2);
return this.toTensorData(e2, i);
});
}
async readTextureAsync(t2, e2, n2) {
const r2 = t2.tensor.dataId;
if (n2 || (n2 = 1), this.pendingRead.has(r2)) {
const t3 = this.pendingRead.get(r2);
return new Promise((e3) => null == t3 ? void 0 : t3.push(e3));
}
return this.profiler.event("backend", "TextureManager.readTextureAsync", async () => {
this.pendingRead.set(r2, []);
const i = t2.shape.reduce((t3, e3) => t3 * e3) * n2;
await this.glContext.createAndWaitForFence();
const o = this.glContext.readTexture(t2.texture, t2.width, t2.height, i, this.toEncoderType(e2), n2), a = this.toTensorData(e2, o), s = this.pendingRead.get(r2);
return this.pendingRead.delete(r2), null == s || s.forEach((t3) => t3(a)), a;
});
}
readUint8TextureAsFloat(t2) {
return this.profiler.event("backend", "TextureManager.readUint8TextureAsFloat", () => {
const e2 = t2.shape.reduce((t3, e3) => t3 * e3), n2 = this.glContext.readTexture(t2.texture, t2.width, t2.height, 4 * e2, "byte", 4);
return new Float32Array(n2.buffer, n2.byteOffset, e2);
});
}
releaseTexture(t2, e2) {
let n2;
if (this.config.reuseTextures && (n2 = this.textureLookup.get(t2.texture), n2)) {
e2 && this.textureLookup.delete(n2);
const r2 = this.inUseTextures.get(n2);
if (r2) {
const e3 = r2.indexOf(t2.texture);
if (-1 !== e3) {
r2.splice(e3, 1);
let i = this.idleTextures.get(n2);
i || (i = [], this.idleTextures.set(n2, i)), i.push(t2.texture);
}
}
}
n2 && !e2 || (r.Logger.verbose("TextureManager", `Deleting texture of size ${t2.width}x${t2.height}`), this.glContext.deleteTexture(t2.texture));
}
toTensorData(t2, e2) {
switch (t2) {
case "int16":
return e2 instanceof Int16Array ? e2 : Int16Array.from(e2);
case "int32":
return e2 instanceof Int32Array ? e2 : Int32Array.from(e2);
case "int8":
return e2 instanceof Int8Array ? e2 : Int8Array.from(e2);
case "uint16":
return e2 instanceof Uint16Array ? e2 : Uint16Array.from(e2);
case "uint32":
return e2 instanceof Uint32Array ? e2 : Uint32Array.from(e2);
case "uint8":
case "bool":
return e2 instanceof Uint8Array ? e2 : Uint8Array.from(e2);
case "float32":
return e2 instanceof Float32Array ? e2 : Float32Array.from(e2);
case "float64":
return e2 instanceof Float64Array ? e2 : Float64Array.from(e2);
default:
throw new Error(`TensorData type ${t2} is not supported`);
}
}
toTextureData(t2, e2) {
if (e2)
return e2 instanceof Float32Array ? e2 : new Float32Array(e2);
}
toEncoderType(t2) {
return "float";
}
clearActiveTextures() {
this.glContext.clearActiveTextures();
}
};
}, 2039: (t, e) => {
"use strict";
var n;
Object.defineProperty(e, "__esModule", { value: true }), 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: true }), 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(t2) {
const e2 = t2.length;
return t2.slice(0, e2 - 1).concat(t2[e2 - 1] / 4);
}, e.repeatedTry = async function(t2, e2 = (t3) => 0, n2) {
return new Promise((r2, i) => {
let o = 0;
const a = () => {
if (t2())
return void r2();
o++;
const s = e2(o);
null != n2 && o >= n2 ? i() : setTimeout(a, s);
};
a();
});
}, e.generateShaderFuncNameFromInputSamplerName = function(t2) {
return (0, r.assert)(void 0 !== t2 && 0 !== t2.length, () => "empty string found for sampler name"), "get" + t2.charAt(0).toUpperCase() + t2.slice(1);
}, e.generateShaderFuncNameFromInputSamplerNameAtOutCoords = function(t2) {
return (0, r.assert)(void 0 !== t2 && 0 !== t2.length, () => "empty string found for sampler name"), "get" + t2.charAt(0).toUpperCase() + t2.slice(1) + "AtOutCoords";
}, e.squeezeInputShape = function(t2, e2) {
let n2 = JSON.parse(JSON.stringify(t2));
return n2 = e2, n2;
}, e.getSqueezedParams = function(t2, e2) {
return e2.map((e3) => t2[e3]).join(", ");
}, e.getCoordsDataType = function(t2) {
if (t2 <= 1)
return "int";
if (2 === t2)
return "ivec2";
if (3 === t2)
return "ivec3";
if (4 === t2)
return "ivec4";
if (5 === t2)
return "ivec5";
if (6 === t2)
return "ivec6";
throw Error(`GPU for rank ${t2} is not yet supported`);
}, e.getGlChannels = function(t2 = 6) {
return ["x", "y", "z", "w", "u", "v"].slice(0, t2);
};
}, 7305: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.createNewWebGLContext = e.createWebGLContext = void 0;
const r = n(6231), i = n(1713), o = {};
function a(t2) {
const e2 = 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 t3 = document.createElement("canvas");
return t3.width = 1, t3.height = 1, t3;
}();
let n2;
const o2 = { alpha: false, depth: false, antialias: false, stencil: false, preserveDrawingBuffer: false, premultipliedAlpha: false, failIfMajorPerformanceCaveat: false };
if ((!t2 || "webgl2" === t2) && (n2 = e2.getContext("webgl2", o2), n2))
try {
return new i.WebGLContext(n2, 2);
} catch (t3) {
r.Logger.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl2'. Error: ${t3}`);
}
if ((!t2 || "webgl" === t2) && (n2 = e2.getContext("webgl", o2) || e2.getContext("experimental-webgl", o2), n2))
try {
return new i.WebGLContext(n2, 1);
} catch (t3) {
r.Logger.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t3}`);
}
throw new Error("WebGL is not supported");
}
e.createWebGLContext = function t2(e2) {
let n2;
e2 && "webgl2" !== e2 || !("webgl2" in o) ? e2 && "webgl" !== e2 || !("webgl" in o) || (n2 = o.webgl) : n2 = o.webgl2, n2 = n2 || a(e2), e2 = e2 || 1 === n2.version ? "webgl" : "webgl2";
const r2 = n2.gl;
return o[e2] = n2, r2.isContextLost() ? (delete o[e2], t2(e2)) : (r2.disable(r2.DEPTH_TEST), r2.disable(r2.STENCIL_TEST), r2.disable(r2.BLEND), r2.disable(r2.DITHER), r2.disable(r2.POLYGON_OFFSET_FILL), r2.disable(r2.SAMPLE_COVERAGE), r2.enable(r2.SCISSOR_TEST), r2.enable(r2.CULL_FACE), r2.cullFace(r2.BACK), n2);
}, e.createNewWebGLContext = a;
}, 1713: function(t, e, n) {
"use strict";
var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) {
void 0 === r2 && (r2 = n2);
var i2 = Object.getOwnPropertyDescriptor(e2, n2);
i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() {
return e2[n2];
} }), Object.defineProperty(t2, r2, i2);
} : function(t2, e2, n2, r2) {
void 0 === r2 && (r2 = n2), t2[r2] = e2[n2];
}), i = this && this.__setModuleDefault || (Object.create ? function(t2, e2) {
Object.defineProperty(t2, "default", { enumerable: true, value: e2 });
} : function(t2, e2) {
t2.default = e2;
}), o = this && this.__importStar || function(t2) {
if (t2 && t2.__esModule)
return t2;
var e2 = {};
if (null != t2)
for (var n2 in t2)
"default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2);
return i(e2, t2), e2;
};
Object.defineProperty(e, "__esModule", { value: true }), e.WebGLContext = e.linearSearchLastTrue = void 0;
const a = n(1670), s = o(n(7769)), u = n(9390);
function c(t2) {
let e2 = 0;
for (; e2 < t2.length && t2[e2](); ++e2)
;
return e2 - 1;
}
e.linearSearchLastTrue = c, e.WebGLContext = class {
constructor(t2, e2) {
this.frameBufferBound = false, this.itemsToPoll = [], this.gl = t2, this.version = e2, this.getExtensions(), this.vertexbuffer = this.createVertexbuffer(), this.framebuffer = this.createFramebuffer(), this.queryVitalParameters();
}
allocateTexture(t2, e2, n2, r2) {
const i2 = this.gl, o2 = i2.createTexture();
i2.bindTexture(i2.TEXTURE_2D, o2), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_MIN_FILTER, i2.NEAREST), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_MAG_FILTER, i2.NEAREST), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_WRAP_S, i2.CLAMP_TO_EDGE), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_WRAP_T, i2.CLAMP_TO_EDGE);
const a2 = r2 ? n2.encode(r2, t2 * e2) : null;
return i2.texImage2D(i2.TEXTURE_2D, 0, n2.internalFormat, t2, e2, 0, n2.format, n2.textureType, a2), this.checkError(), o2;
}
updateTexture(t2, e2, n2, r2, i2) {
const o2 = this.gl;
o2.bindTexture(o2.TEXTURE_2D, t2);
const a2 = r2.encode(i2, e2 * n2);
o2.texSubImage2D(o2.TEXTURE_2D, 0, 0, 0, e2, n2, r2.format, r2.textureType, a2), this.checkError();
}
attachFramebuffer(t2, e2, n2) {
const r2 = this.gl;
r2.bindTexture(r2.TEXTURE_2D, t2), r2.bindFramebuffer(r2.FRAMEBUFFER, this.framebuffer), r2.framebufferTexture2D(r2.FRAMEBUFFER, r2.COLOR_ATTACHMENT0, r2.TEXTURE_2D, t2, 0), this.checkError(), r2.viewport(0, 0, e2, n2), r2.scissor(0, 0, e2, n2);
}
readTexture(t2, e2, n2, r2, i2, o2) {
const a2 = this.gl;
o2 || (o2 = 1), this.frameBufferBound || this.attachFramebuffer(t2, e2, n2);
const s2 = this.getEncoder(i2, o2), u2 = s2.allocate(e2 * n2);
return a2.bindTexture(a2.TEXTURE_2D, t2), a2.framebufferTexture2D(a2.FRAMEBUFFER, a2.COLOR_ATTACHMENT0, a2.TEXTURE_2D, t2, 0), a2.readPixels(0, 0, e2, n2, a2.RGBA, s2.textureType, u2), this.checkError(), s2.decode(u2, r2);
}
isFramebufferReady() {
return true;
}
getActiveTexture() {
const t2 = this.gl;
return "TEXTURE" + (t2.getParameter(this.gl.ACTIVE_TEXTURE) - t2.TEXTURE0);
}
getTextureBinding() {
return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D);
}
getFramebufferBinding() {
return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING);
}
setVertexAttributes(t2, e2) {
const n2 = this.gl;
n2.vertexAttribPointer(t2, 3, n2.FLOAT, false, 20, 0), n2.enableVertexAttribArray(t2), -1 !== e2 && (n2.vertexAttribPointer(e2, 2, n2.FLOAT, false, 20, 12), n2.enableVertexAttribArray(e2)), this.checkError();
}
createProgram(t2, e2) {
const n2 = this.gl, r2 = n2.createProgram();
return n2.attachShader(r2, t2), n2.attachShader(r2, e2), n2.linkProgram(r2), r2;
}
compileShader(t2, e2) {
const n2 = this.gl, r2 = n2.createShader(e2);
if (!r2)
throw new Error(`createShader() returned null with type ${e2}`);
if (n2.shaderSource(r2, t2), n2.compileShader(r2), false === n2.getShaderParameter(r2, n2.COMPILE_STATUS))
throw new Error(`Failed to compile shader: ${n2.getShaderInfoLog(r2)}
Shader source:
${t2}`);
return r2;
}
deleteShader(t2) {
this.gl.deleteShader(t2);
}
bindTextureToUniform(t2, e2, n2) {
const r2 = this.gl;
r2.activeTexture(r2.TEXTURE0 + e2), this.checkError(), r2.bindTexture(r2.TEXTURE_2D, t2), this.checkError(), r2.uniform1i(n2, e2), this.checkError();
}
draw() {
this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4), this.checkError();
}
checkError() {
if (a.env.debug) {
const t2 = this.gl, e2 = t2.getError();
let n2 = "";
switch (e2) {
case t2.NO_ERROR:
return;
case t2.INVALID_ENUM:
n2 = "INVALID_ENUM";
break;
case t2.INVALID_VALUE:
n2 = "INVALID_VALUE";
break;
case t2.INVALID_OPERATION:
n2 = "INVALID_OPERATION";
break;
case t2.INVALID_FRAMEBUFFER_OPERATION:
n2 = "INVALID_FRAMEBUFFER_OPERATION";
break;
case t2.OUT_OF_MEMORY:
n2 = "OUT_OF_MEMORY";
break;
case t2.CONTEXT_LOST_WEBGL:
n2 = "CONTEXT_LOST_WEBGL";
break;
default:
n2 = `Unknown WebGL Error: ${e2.toString(16)}`;
}
throw new Error(n2);
}
}
deleteTexture(t2) {
this.gl.deleteTexture(t2);
}
deleteProgram(t2) {
this.gl.deleteProgram(t2);
}
getEncoder(t2, e2, n2 = 0) {
if (2 === this.version)
return new s.RedFloat32DataEncoder(this.gl, e2);
switch (t2) {
case "float":
return 1 === n2 || this.isRenderFloat32Supported ? new s.RGBAFloatDataEncoder(this.gl, e2) : new s.RGBAFloatDataEncoder(this.gl, e2, this.textureHalfFloatExtension.HALF_FLOAT_OES);
case "int":
throw new Error("not implemented");
case "byte":
return new s.Uint8DataEncoder(this.gl, e2);
default:
throw new Error(`Invalid dataType: ${t2}`);
}
}
clearActiveTextures() {
const t2 = this.gl;
for (let e2 = 0; e2 < this.maxTextureImageUnits; ++e2)
t2.activeTexture(t2.TEXTURE0 + e2), t2.bindTexture(t2.TEXTURE_2D, null);
}
dispose() {
if (this.disposed)
return;
const t2 = this.gl;
t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteFramebuffer(this.framebuffer), t2.bindBuffer(t2.ARRAY_BUFFER, null), t2.deleteBuffer(this.vertexbuffer), t2.bindBuffer(t2.ELEMENT_ARRAY_BUFFER, null), t2.finish(), this.disposed = true;
}
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 t2 = this.gl, e2 = t2.createBuffer();
if (!e2)
throw new Error("createBuffer() returned null");
const n2 = this.createDefaultGeometry();
return t2.bindBuffer(t2.ARRAY_BUFFER, e2), t2.bufferData(t2.ARRAY_BUFFER, n2, t2.STATIC_DRAW), this.checkError(), e2;
}
createFramebuffer() {
const t2 = this.gl.createFramebuffer();
if (!t2)
throw new Error("createFramebuffer returned null");
return t2;
}
queryVitalParameters() {
const t2 = 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 = t2.getParameter(t2.MAX_TEXTURE_SIZE), this.maxTextureImageUnits = t2.getParameter(t2.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 t2 = this.gl, e2 = t2.createTexture();
t2.bindTexture(t2.TEXTURE_2D, e2);
const n2 = 2 === this.version ? t2.RGBA32F : t2.RGBA;
t2.texImage2D(t2.TEXTURE_2D, 0, n2, 1, 1, 0, t2.RGBA, t2.FLOAT, null);
const r2 = t2.createFramebuffer();
t2.bindFramebuffer(t2.FRAMEBUFFER, r2), t2.framebufferTexture2D(t2.FRAMEBUFFER, t2.COLOR_ATTACHMENT0, t2.TEXTURE_2D, e2, 0);
const i2 = t2.checkFramebufferStatus(t2.FRAMEBUFFER) === t2.FRAMEBUFFER_COMPLETE;
return t2.bindTexture(t2.TEXTURE_2D, null), t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteTexture(e2), t2.deleteFramebuffer(r2), i2;
}
checkRenderFloat32() {
if (2 === this.version) {
if (!this.colorBufferFloatExtension)
return false;
} else if (!this.textureFloatExtension)
return false;
return this.isFloatTextureAttachableToFrameBuffer;
}
checkFloat32Download() {
if (2 === this.version) {
if (!this.colorBufferFloatExtension)
return false;
} else {
if (!this.textureFloatExtension)
return false;
if (!this.gl.getExtension("WEBGL_color_buffer_float"))
return false;
}
return this.isFloatTextureAttachableToFrameBuffer;
}
checkFloat32Blend() {
const t2 = this.gl;
let e2, n2, r2, i2, o2;
try {
e2 = t2.createTexture(), n2 = t2.createFramebuffer(), t2.bindTexture(t2.TEXTURE_2D, e2);
const a2 = 2 === this.version ? t2.RGBA32F : t2.RGBA;
return t2.texImage2D(t2.TEXTURE_2D, 0, a2, 1, 1, 0, t2.RGBA, t2.FLOAT, null), t2.bindFramebuffer(t2.FRAMEBUFFER, n2), t2.framebufferTexture2D(t2.FRAMEBUFFER, t2.COLOR_ATTACHMENT0, t2.TEXTURE_2D, e2, 0), t2.enable(t2.BLEND), r2 = t2.createShader(t2.VERTEX_SHADER), !!r2 && (t2.shaderSource(r2, "void main(){}"), t2.compileShader(r2), i2 = t2.createShader(t2.FRAGMENT_SHADER), !!i2 && (t2.shaderSource(i2, "precision highp float;void main(){gl_FragColor=vec4(0.5);}"), t2.compileShader(i2), o2 = t2.createProgram(), !!o2 && (t2.attachShader(o2, r2), t2.attachShader(o2, i2), t2.linkProgram(o2), t2.useProgram(o2), t2.drawArrays(t2.POINTS, 0, 1), t2.getError() === t2.NO_ERROR)));
} finally {
t2.disable(t2.BLEND), o2 && t2.deleteProgram(o2), r2 && t2.deleteShader(r2), i2 && t2.deleteShader(i2), n2 && (t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteFramebuffer(n2)), e2 && (t2.bindTexture(t2.TEXTURE_2D, null), t2.deleteTexture(e2));
}
}
beginTimer() {
if (2 === this.version && this.disjointTimerQueryWebgl2Extension) {
const t2 = this.gl, e2 = this.disjointTimerQueryWebgl2Extension, n2 = t2.createQuery();
return t2.beginQuery(e2.TIME_ELAPSED_EXT, n2), n2;
}
throw new Error("WebGL1 profiling currently not supported.");
}
endTimer() {
if (2 !== this.version || !this.disjointTimerQueryWebgl2Extension)
throw new Error("WebGL1 profiling currently not supported");
{
const t2 = this.gl, e2 = this.disjointTimerQueryWebgl2Extension;
t2.endQuery(e2.TIME_ELAPSED_EXT);
}
}
isTimerResultAvailable(t2) {
let e2 = false, n2 = false;
if (2 !== this.version || !this.disjointTimerQueryWebgl2Extension)
throw new Error("WebGL1 profiling currently not supported");
{
const r2 = this.gl, i2 = this.disjointTimerQueryWebgl2Extension;
e2 = r2.getQueryParameter(t2, r2.QUERY_RESULT_AVAILABLE), n2 = r2.getParameter(i2.GPU_DISJOINT_EXT);
}
return e2 && !n2;
}
getTimerResult(t2) {
let e2 = 0;
if (2 !== this.version)
throw new Error("WebGL1 profiling currently not supported");
{
const n2 = this.gl;
e2 = n2.getQueryParameter(t2, n2.QUERY_RESULT), n2.deleteQuery(t2);
}
return e2 / 1e6;
}
async waitForQueryAndGetTime(t2) {
return await (0, u.repeatedTry)(() => this.isTimerResultAvailable(t2)), this.getTimerResult(t2);
}
async createAndWaitForFence() {
const t2 = this.createFence(this.gl);
return this.pollFence(t2);
}
createFence(t2) {
let e2;
const n2 = t2, r2 = n2.fenceSync(n2.SYNC_GPU_COMMANDS_COMPLETE, 0);
return t2.flush(), e2 = null === r2 ? () => true : () => {
const t3 = n2.clientWaitSync(r2, 0, 0);
return t3 === n2.ALREADY_SIGNALED || t3 === n2.CONDITION_SATISFIED;
}, { query: r2, isFencePassed: e2 };
}
async pollFence(t2) {
return new Promise((e2) => {
this.addItemToPoll(() => t2.isFencePassed(), () => e2());
});
}
pollItems() {
const t2 = c(this.itemsToPoll.map((t3) => t3.isDoneFn));
for (let e2 = 0; e2 <= t2; ++e2) {
const { resolveFn: t3 } = this.itemsToPoll[e2];
t3();
}
this.itemsToPoll = this.itemsToPoll.slice(t2 + 1);
}
async addItemToPoll(t2, e2) {
this.itemsToPoll.push({ isDoneFn: t2, resolveFn: e2 }), 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: true }), e.ExecutionPlan = void 0;
const r = n(6231);
class i {
constructor(t2, e2) {
this.op = t2, this.node = e2;
}
}
e.ExecutionPlan = class {
constructor(t2, e2, n2) {
this.graph = t2, this.profiler = n2, this.initialize(e2);
}
initialize(t2) {
this.profiler.event("session", "ExecutionPlan.initialize", () => {
const e2 = this.graph.getNodes();
if (e2.length !== t2.length)
throw new Error("The size of nodes and OPs do not match.");
this._ops = t2.map((t3, n2) => new i(t3, e2[n2])), this.reset(), this._starter = [], this._ops.forEach((t3, e3) => {
let n2 = true;
for (const e4 of t3.node.inputs)
if (!this._values[e4] && -1 === this.graph.getInputIndices().indexOf(e4)) {
n2 = false;
break;
}
n2 && this._starter.push(e3);
});
});
}
reset() {
this._values = this.graph.getValues().map((t2) => t2.tensor);
}
async execute(t2, e2) {
return this.profiler.event("session", "ExecutionPlan.execute", async () => {
this.reset();
const n2 = t2.createInferenceHandler(), i2 = this.graph.getInputIndices();
if (e2.length !== i2.length)
throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${e2.length} expected: ${i2.length}`);
e2.forEach((t3, e3) => {
const n3 = i2[e3];
this._values[n3] = t3;
});
const o = this._starter.slice(0), a = this.graph.getValues(), s = this.graph.getNodes();
let u = 0;
for (; u < o.length; ) {
const t3 = o[u++], e3 = this._ops[t3], i3 = e3.node.inputs.map((t4) => this._values[t4]);
if (-1 !== i3.indexOf(void 0))
throw new Error(`unresolved input detected: op: ${e3.node}`);
const c2 = i3;
r.Logger.verbose("ExecPlan", `Runing op:${e3.node.name} (${c2.map((t4, n3) => `'${e3.node.inputs[n3]}': ${t4.type}[${t4.dims.join(",")}]`).join(", ")})`);
const l = await this.profiler.event("node", e3.node.name, async () => e3.op.impl(n2, c2, e3.op.context));
if (l.length !== e3.node.outputs.length)
throw new Error("the size of output does not match model definition.");
l.forEach((t4, n3) => {
const r2 = e3.node.outputs[n3];
if (this._values[r2])
throw new Error(`output [${r2}] already has value: op:${e3.node.name}`);
this._values[r2] = t4;
});
const p = /* @__PURE__ */ new Set();
l.forEach((t4, n3) => {
const r2 = e3.node.outputs[n3];
for (const t5 of a[r2].to) {
const e4 = s[t5];
let n4 = true;
for (const t6 of e4.inputs)
if (!this._values[t6]) {
n4 = false;
break;
}
n4 && p.add(t5);
}
}), o.push(...p);
}
const c = [];
for (let t3 = 0; t3 < this.graph.getOutputIndices().length; t3++) {
const e3 = this.graph.getOutputIndices()[t3], n3 = this._values[e3];
if (void 0 === n3)
throw new Error(`required output [${e3}] does not have value`);
0 === e3 ? await n3.getData() : n3.data, c.push(n3);
}
return r.Logger.verbose("ExecPlan", "disposing of inferenceHandler"), n2.dispose(), c;
});
}
};
}, 7070: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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: (t2, e2) => new p(t2, e2) };
class c {
constructor(t2) {
this._from = void 0, this._to = [], this.tensor = void 0, this.type = void 0, t2 && (this.type = s.ProtoUtil.tensorValueTypeFromProto(t2.type.tensorType));
}
get from() {
return this._from;
}
get to() {
return this._to;
}
}
class l {
constructor(t2, e2) {
t2 instanceof r.onnx.NodeProto ? (this.name = t2.name, this.opType = t2.opType, this.attributes = new i.Attribute(t2.attribute)) : t2 instanceof u.Node && (this.name = null != e2 ? e2 : t2.name(), this.opType = t2.opType(), this.attributes = new i.Attribute(s.ProtoUtil.tensorAttributesFromORTFormat(t2))), this.inputs = [], this.outputs = [], this.executeNode = true;
}
}
class p {
constructor(t2, e2) {
if (!t2)
throw new TypeError("graph is empty");
this.buildGraph(t2), this.transformGraph(e2), 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(t2) {
if (t2 instanceof r.onnx.GraphProto)
this.buildGraphFromOnnxFormat(t2);
else {
if (!(t2 instanceof u.Graph))
throw new TypeError("Graph type is not supported.");
this.buildGraphFromOrtFormat(t2);
}
}
buildGraphFromOnnxFormat(t2) {
const e2 = /* @__PURE__ */ new Map();
this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = [];
const n2 = /* @__PURE__ */ new Map();
if (!t2.input)
throw new Error("missing information in graph: input");
const r2 = [];
for (const n3 of t2.input) {
if (e2.has(n3.name))
throw new Error(`duplicated input name: ${n3.name}`);
const t3 = this._allData.push(new c(n3)) - 1;
e2.set(n3.name, t3), r2.push(n3.name);
}
if (!t2.initializer)
throw new Error("missing information in graph: initializer");
for (const n3 of t2.initializer) {
let t3 = e2.get(n3.name);
if (void 0 === t3) {
const r3 = new c();
r3.type = { shape: { dims: s.ProtoUtil.tensorDimsFromProto(n3.dims) }, tensorType: s.ProtoUtil.tensorDataTypeFromProto(n3.dataType) }, t3 = this._allData.push(r3) - 1, e2.set(n3.name, t3);
}
this._allData[t3]._from = -1, this._allData[t3].tensor = a.Tensor.fromProto(n3);
}
for (let t3 = 0; t3 < this._allData.length; t3++)
this._allData[t3].tensor || (this._allInputIndices.push(t3), this._allInputNames.push(r2[t3]));
if (!t2.output)
throw new Error("missing information in graph: output");
for (const n3 of t2.output) {
if (e2.has(n3.name))
throw new Error(`duplicated output name: ${n3.name}`);
const t3 = this._allData.push(new c(n3)) - 1;
e2.set(n3.name, t3), this._allOutputIndices.push(t3), this._allOutputNames.push(n3.name);
}
if (!t2.node)
throw new Error("missing information in graph: node");
for (const e3 of t2.node) {
if (!e3.name)
for (let t4 = 0; ; t4++) {
const r3 = `unnamed_${e3.opType}_${t4}`;
if (!n2.has(r3)) {
e3.name = r3;
break;
}
}
if (n2.has(e3.name))
throw new Error(`duplicated node name: ${e3.name}`);
const t3 = this._nodes.push(new l(e3)) - 1;
n2.set(e3.name, t3);
}
for (let n3 = 0; n3 < this._nodes.length; n3++) {
const r3 = this._nodes[n3], i2 = t2.node[n3];
if (!i2.output)
throw new Error(`missing output for node: ${i2.name}`);
for (const t3 of i2.output) {
let o2 = e2.get(t3);
if (void 0 === o2 && (o2 = this._allData.push(new c()) - 1, e2.set(t3, o2)), r3.outputs.push(o2), void 0 !== this._allData[o2]._from)
throw new Error(`multiple nodes output to one data value: ${o2}`);
if (this._allData[o2]._from = n3, "Constant" === i2.opType) {
if (!i2.attribute || 1 !== i2.attribute.length || !i2.attribute[0].t)
throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");
if (!i2.output || 1 !== i2.output.length)
throw new Error("missing output or incorrect number of outputs for this Constant operator");
r3.outputs.pop(), r3.executeNode = false, this._allData[o2]._from = -1, this._allData[o2].tensor = a.Tensor.fromProto(i2.attribute[0].t);
}
}
}
for (let n3 = 0; n3 < this._nodes.length; n3++) {
const r3 = this._nodes[n3], i2 = t2.node[n3];
if (!i2.input)
throw new Error(`missing input for node: ${i2.name}`);
for (const t3 of i2.input) {
const o2 = e2.get(t3);
if (void 0 === o2) {
if ("" === t3 && 3 === i2.input.length && "Resize" === i2.opType)
continue;
throw new Error(`unrecognized input '${t3}' for node: ${i2.name}`);
}
r3.inputs.push(o2), this._allData[o2]._to.push(n3);
}
}
return true;
}
buildGraphFromOrtFormat(t2) {
var e2, n2, r2;
const i2 = /* @__PURE__ */ new Map();
this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = [];
const o2 = /* @__PURE__ */ new Map(), p2 = [];
for (let o3 = 0; o3 < t2.inputsLength(); o3++) {
const a2 = t2.inputs(o3);
if (i2.has(a2))
throw new Error(`duplicated input name: ${a2}`);
for (let o4 = 0; o4 < t2.nodeArgsLength(); o4++)
if ((null === (e2 = t2.nodeArgs(o4)) || void 0 === e2 ? void 0 : e2.name()) === a2) {
const e3 = new c();
if ((null === (r2 = null === (n2 = t2.nodeArgs(o4)) || void 0 === n2 ? void 0 : n2.type()) || void 0 === r2 ? void 0 : r2.valueType()) !== u.TypeInfoValue.tensor_type)
throw new Error("Unexpected value type for the nodeArg.");
const l2 = t2.nodeArgs(o4).type().value(new u.TensorTypeAndShape()), f = s.ProtoUtil.tensorDataTypeFromProto(l2.elemType()), d = l2.shape(), h = [];
for (let t3 = 0; t3 < d.dimLength(); t3++)
h.push(s.LongUtil.longToNumber(d.dim(t3).value().dimValue()));
e3.type = { shape: { dims: h }, tensorType: f };
const g = this._allData.push(e3) - 1;
i2.set(a2, g), p2.push(a2);
}
}
for (let e3 = 0; e3 < t2.initializersLength(); e3++) {
const n3 = t2.initializers(e3);
let r3 = i2.get(n3.name());
if (void 0 === r3) {
const t3 = new c(), e4 = s.ProtoUtil.tensorDimsFromORTFormat(n3), o3 = s.ProtoUtil.tensorDataTypeFromProto(n3.dataType());
t3.type = { shape: { dims: e4 }, tensorType: o3 }, r3 = this._allData.push(t3) - 1, i2.set(n3.name(), r3);
}
this._allData[r3]._from = -1, this._allData[r3].tensor = a.Tensor.fromOrtTensor(n3);
}
for (let t3 = 0; t3 < this._allData.length; t3++)
this._allData[t3].tensor || (this._allInputIndices.push(t3), this._allInputNames.push(p2[t3]));
for (let e3 = 0; e3 < t2.outputsLength(); e3++) {
const n3 = t2.outputs(e3);
if (i2.has(n3))
throw new Error(`duplicated output name: ${n3}`);
const r3 = this._allData.push(new c()) - 1;
i2.set(n3, r3), this._allOutputIndices.push(r3), this._allOutputNames.push(n3);
}
if (!t2.nodes)
throw new Error("missing information in graph: node");
for (let e3 = 0; e3 < t2.nodesLength(); e3++) {
const n3 = t2.nodes(e3);
let r3 = n3.name();
if (!r3)
for (let t3 = 0; r3 = `unnamed_${n3.opType()}_${t3}`, o2.has(r3); t3++)
;
if (o2.has(r3))
throw new Error(`duplicated node name: ${r3}`);
const i3 = this._nodes.push(new l(n3, r3)) - 1;
o2.set(r3, i3);
}
for (let e3 = 0; e3 < this._nodes.length; e3++) {
const n3 = this._nodes[e3], r3 = t2.nodes(e3);
if (null == r3)
throw new Error(`No node exists at index ${e3}`);
if (0 === (null == r3 ? void 0 : r3.outputsLength()))
throw new Error(`missing output for node: ${r3.name}`);
for (let t3 = 0; t3 < (null == r3 ? void 0 : r3.outputsLength()); t3++) {
const o3 = null == r3 ? void 0 : r3.outputs(t3);
let s2 = i2.get(o3);
if (void 0 === s2 && (s2 = this._allData.push(new c()) - 1, i2.set(o3, s2)), n3.outputs.push(s2), void 0 !== this._allData[s2]._from)
throw new Error(`multiple nodes output to one data value: ${s2}`);
if (this._allData[s2]._from = e3, "Constant" === r3.opType()) {
if (1 !== r3.attributesLength() || !r3.attributes(0).t())
throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");
if (1 !== r3.outputsLength())
throw new Error("missing output or incorrect number of outputs for this Constant operator");
n3.outputs.pop(), n3.executeNode = false, this._allData[s2]._from = -1, this._allData[s2].tensor = a.Tensor.fromOrtTensor(r3.attributes(0).t());
}
}
}
for (let e3 = 0; e3 < this._nodes.length; e3++) {
const n3 = this._nodes[e3], r3 = t2.nodes(e3);
if (0 === r3.inputsLength())
throw new Error(`missing input for node: ${r3.name}`);
for (let t3 = 0; t3 < r3.inputsLength(); t3++) {
const o3 = r3.inputs(t3), a2 = i2.get(o3);
if (void 0 === a2)
throw new Error(`unrecognized input '${o3}' for node: ${r3.name()}`);
n3.inputs.push(a2), this._allData[a2]._to.push(e3);
}
}
}
checkIsAcyclic() {
const t2 = /* @__PURE__ */ new Set();
this._allInputIndices.forEach((e3) => {
this._allData[e3]._to.forEach((e4) => {
t2.add(e4);
});
});
const e2 = Array.from(t2), n2 = new Array(this._nodes.length).fill("white");
for (; e2.length > 0; ) {
const t3 = e2.pop();
"gray" === n2[t3] ? n2[t3] = "black" : (e2.push(t3), n2[t3] = "gray", this._nodes[t3].outputs.forEach((r2) => {
const i2 = this._allData[r2];
if (void 0 !== i2.tensor)
throw new Error("node outputs should not be initialized");
if (i2._from !== t3)
throw new Error("from property of the Value object doesn't match index of Node being processed");
i2._to.forEach((t4) => {
if ("gray" === n2[t4])
throw new Error("model graph is cyclic");
"white" === n2[t4] && e2.push(t4);
});
}));
}
}
transformGraph(t2) {
this.removeAllIdentityNodes(), this.removeAllDropoutNodes(), this.fuseConvActivationNodes(), t2 && t2.transformGraph(this), this.finalizeGraph();
}
finalizeGraph() {
let t2 = 0;
for (let e2 = 0; e2 < this._nodes.length; e2++)
this._nodes[e2].executeNode ? t2 > 0 && (this._nodes[e2].inputs.forEach((n2) => {
const r2 = this._allData[n2]._to.indexOf(e2 + t2);
-1 !== r2 && (this._allData[n2]._to[r2] = e2);
}), this._nodes[e2].outputs.forEach((n2) => {
this._allData[n2]._from && this._allData[n2]._from === e2 + t2 && (this._allData[n2]._from = e2);
})) : (t2++, this._nodes[e2].outputs.forEach((t3) => {
this._allData[t3]._from = -2;
}), this._nodes.splice(e2, 1), e2--);
t2 = 0;
for (let e2 = 0; e2 < this._allData.length; e2++)
if (-2 !== this._allData[e2].from || -1 !== this._allOutputIndices.indexOf(e2 + t2)) {
if (t2 > 0) {
let n2 = -1;
void 0 !== this._allData[e2].from && -1 !== this._allData[e2].from ? (n2 = this._nodes[this._allData[e2].from].outputs.indexOf(e2 + t2), -1 !== n2 && (this._nodes[this._allData[e2].from].outputs[n2] = e2)) : (n2 = this._allInputIndices.indexOf(e2 + t2), -1 !== n2 && (this._allInputIndices[n2] = e2)), this._allData[e2].to.forEach((r2) => {
n2 = this._nodes[r2].inputs.indexOf(e2 + t2), -1 !== n2 && (this._nodes[r2].inputs[n2] = e2);
}), 0 === this._allData[e2].to.length && (n2 = this._allOutputIndices.indexOf(e2 + t2), -1 !== n2 && (this._allOutputIndices[n2] = e2));
}
} else
t2++, this._allData.splice(e2, 1), e2--;
}
deleteNode(t2) {
const e2 = this._nodes[t2];
if (e2.outputs.length > 1) {
for (let t3 = 1; t3 < e2.outputs.length; t3++)
if (this._allData[e2.outputs[t3]].to.length > 0)
throw new Error("Node deletion with more than one output connected to other nodes is not supported. ");
}
e2.executeNode = false;
const n2 = e2.inputs[0], r2 = e2.outputs[0], i2 = this._allData[r2].to, o2 = this._allData[n2].to.indexOf(t2);
if (-1 === o2)
throw new Error("The Value object doesn't have the current Node in it's 'to' property ");
this._allData[n2].to.splice(o2, 1), this._allData[r2]._to = [];
const a2 = this._allOutputIndices.indexOf(r2);
if (-1 !== a2 && (this._allOutputIndices[a2] = n2), i2 && i2.length > 0)
for (const t3 of i2) {
const e3 = this._nodes[t3].inputs.indexOf(r2);
if (-1 === e3)
throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");
this._nodes[t3].inputs[e3] = n2, this._allData[n2].to.push(t3);
}
}
removeAllDropoutNodes() {
let t2 = 0;
for (const e2 of this._nodes) {
if ("Dropout" === e2.opType) {
if (1 !== e2.inputs.length)
throw new Error("Dropout nodes should only contain one input. ");
if (1 !== e2.outputs.length && 2 !== e2.outputs.length)
throw new Error("Dropout nodes should contain either 1 or 2 output(s)");
if (2 === e2.outputs.length && 0 !== this._allData[e2.outputs[1]]._to.length)
throw new Error("Dropout nodes's second output should not be referenced by other nodes");
this.deleteNode(t2);
}
t2++;
}
}
removeAllIdentityNodes() {
let t2 = 0;
for (const e2 of this._nodes)
"Identity" === e2.opType && this.deleteNode(t2), t2++;
}
isActivation(t2) {
switch (t2.opType) {
case "Relu":
case "Sigmoid":
case "Clip":
return true;
default:
return false;
}
}
fuseConvActivationNodes() {
for (const t2 of this._nodes)
if ("Conv" === t2.opType) {
const e2 = this._allData[t2.outputs[0]]._to;
if (1 === e2.length && this.isActivation(this._nodes[e2[0]])) {
const n2 = this._nodes[e2[0]];
if ("Clip" === n2.opType)
if (1 === n2.inputs.length)
try {
t2.attributes.set("activation_params", "floats", [n2.attributes.getFloat("min"), n2.attributes.getFloat("max")]);
} catch (e3) {
t2.attributes.set("activation_params", "floats", [s.MIN_CLIP, s.MAX_CLIP]);
}
else {
if (!(n2.inputs.length >= 3 && void 0 !== this._allData[n2.inputs[1]].tensor && void 0 !== this._allData[n2.inputs[2]].tensor))
continue;
t2.attributes.set("activation_params", "floats", [this._allData[n2.inputs[1]].tensor.floatData[0], this._allData[n2.inputs[2]].tensor.floatData[0]]);
}
t2.attributes.set("activation", "string", n2.opType), this.deleteNode(e2[0]);
}
}
}
}
}, 6231: (t, e) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2, e2, n2) {
}
}(), console: new class {
log(t2, e2, n2) {
console.log(`${this.color(t2)} ${n2 ? "\x1B[35m" + n2 + "\x1B[0m " : ""}${e2}`);
}
color(t2) {
switch (t2) {
case "verbose":
return "\x1B[34;40mv\x1B[0m";
case "info":
return "\x1B[32mi\x1B[0m";
case "warning":
return "\x1B[30;43mw\x1B[0m";
case "error":
return "\x1B[31;40me\x1B[0m";
case "fatal":
return "\x1B[101mf\x1B[0m";
default:
throw new Error(`unsupported severity: ${t2}`);
}
}
}() }, i = { provider: "console", minimalSeverity: "warning", logDateTime: true, logSourceLocation: false };
let o = { "": i };
function a(t2, e2, n2, r2) {
if (void 0 === e2)
return i2 = t2, { verbose: a.verbose.bind(null, i2), info: a.info.bind(null, i2), warning: a.warning.bind(null, i2), error: a.error.bind(null, i2), fatal: a.fatal.bind(null, i2) };
if (void 0 === n2)
s(t2, e2);
else if ("number" == typeof n2 && void 0 === r2)
s(t2, e2);
else if ("string" == typeof n2 && void 0 === r2)
s(t2, n2, 0, e2);
else {
if ("string" != typeof n2 || "number" != typeof r2)
throw new TypeError("input is valid");
s(t2, n2, 0, e2);
}
var i2;
}
function s(t2, e2, i2, a2) {
const s2 = o[a2 || ""] || o[""];
n[t2] < n[s2.minimalSeverity] || (s2.logDateTime && (e2 = `${(/* @__PURE__ */ new Date()).toISOString()}|${e2}`), s2.logSourceLocation, r[s2.provider].log(t2, e2, a2));
}
!function(t2) {
function e2(t3) {
o = {}, n2("", t3 || {});
}
function n2(t3, n3) {
if ("*" === t3)
e2(n3);
else {
const e3 = o[t3] || i;
o[t3] = { provider: n3.provider || e3.provider, minimalSeverity: n3.minimalSeverity || e3.minimalSeverity, logDateTime: void 0 === n3.logDateTime ? e3.logDateTime : n3.logDateTime, logSourceLocation: void 0 === n3.logSourceLocation ? e3.logSourceLocation : n3.logSourceLocation };
}
}
t2.verbose = function(e3, n3) {
t2("verbose", e3, n3);
}, t2.info = function(e3, n3) {
t2("info", e3, n3);
}, t2.warning = function(e3, n3) {
t2("warning", e3, n3);
}, t2.error = function(e3, n3) {
t2("error", e3, n3);
}, t2.fatal = function(e3, n3) {
t2("fatal", e3, n3);
}, t2.reset = e2, t2.set = n2, t2.setWithEnv = function(t3) {
const e3 = {};
t3.logLevel && (e3.minimalSeverity = t3.logLevel), n2("", e3);
};
}(a || (a = {})), e.Logger = a;
class u {
constructor(t2, e2, n2, r2, i2, o2) {
this.category = t2, this.name = e2, this.startTime = n2, this.endCallback = r2, this.timer = i2, this.ctx = o2;
}
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(t2, e2, n2, r2) {
this.category = t2, this.name = e2, this.startTime = n2, this.endTime = r2;
}
}
e.Profiler = class {
static create(t2) {
return void 0 === t2 ? new this() : new this(t2.maxNumberEvents, t2.flushBatchSize, t2.flushIntervalInMilliseconds);
}
constructor(t2, e2, n2) {
this._started = false, this._flushPointer = 0, this._started = false, this._maxNumberEvents = void 0 === t2 ? 1e4 : t2, this._flushBatchSize = void 0 === e2 ? 10 : e2, this._flushIntervalInMilliseconds = void 0 === n2 ? 5e3 : n2;
}
start() {
this._started = true, this._timingEvents = [], this._flushTime = (0, e.now)(), this._flushPointer = 0;
}
stop() {
for (this._started = false; this._flushPointer < this._timingEvents.length; this._flushPointer++)
this.logOneEvent(this._timingEvents[this._flushPointer]);
}
event(t2, e2, n2, r2) {
const i2 = this._started ? this.begin(t2, e2, r2) : void 0;
let o2 = false;
const a2 = n2();
if (a2 && "function" == typeof a2.then)
return o2 = true, new Promise((t3, e3) => {
a2.then(async (e4) => {
i2 && await i2.end(), t3(e4);
}, async (t4) => {
i2 && await i2.end(), e3(t4);
});
});
if (!o2 && i2) {
const t3 = i2.end();
if (t3 && "function" == typeof t3.then)
return new Promise((e3, n3) => {
t3.then(() => {
e3(a2);
}, (t4) => {
n3(t4);
});
});
}
return a2;
}
begin(t2, n2, r2) {
if (!this._started)
throw new Error("profiler is not started yet");
if (void 0 === r2) {
const r3 = (0, e.now)();
return this.flush(r3), new u(t2, n2, r3, (t3) => this.endSync(t3));
}
{
const e2 = r2.beginTimer();
return new u(t2, n2, 0, async (t3) => this.end(t3), e2, r2);
}
}
async end(t2) {
const e2 = await t2.checkTimer();
this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new c(t2.category, t2.name, t2.startTime, e2)), this.flush(e2));
}
endSync(t2) {
const n2 = (0, e.now)();
this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new c(t2.category, t2.name, t2.startTime, n2)), this.flush(n2));
}
logOneEvent(t2) {
e.Logger.verbose(`Profiler.${t2.category}`, `${(t2.endTime - t2.startTime).toFixed(2)}ms on event '${t2.name}' at ${t2.endTime.toFixed(2)}`);
}
flush(t2) {
if (this._timingEvents.length - this._flushPointer >= this._flushBatchSize || t2 - this._flushTime >= this._flushIntervalInMilliseconds) {
for (const t3 = this._flushPointer; this._flushPointer < t3 + 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: true }), 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(t2, e2, n2) {
if (!n2)
try {
return void this.loadFromOnnxFormat(t2, e2);
} catch (t3) {
if (void 0 !== n2)
throw t3;
}
this.loadFromOrtFormat(t2, e2);
}
loadFromOnnxFormat(t2, e2) {
const n2 = i.onnx.ModelProto.decode(t2);
if (s.LongUtil.longToNumber(n2.irVersion) < 3)
throw new Error("only support ONNX model with IR_VERSION>=3");
this._opsets = n2.opsetImport.map((t3) => ({ domain: t3.domain, version: s.LongUtil.longToNumber(t3.version) })), this._graph = o.Graph.from(n2.graph, e2);
}
loadFromOrtFormat(t2, e2) {
const n2 = new r.flatbuffers.ByteBuffer(t2), i2 = u.InferenceSession.getRootAsInferenceSession(n2).model();
if (s.LongUtil.longToNumber(i2.irVersion()) < 3)
throw new Error("only support ONNX model with IR_VERSION>=3");
this._opsets = [];
for (let t3 = 0; t3 < i2.opsetImportLength(); t3++) {
const e3 = i2.opsetImport(t3);
this._opsets.push({ domain: null == e3 ? void 0 : e3.domain(), version: s.LongUtil.longToNumber(e3.version()) });
}
this._graph = o.Graph.from(i2.graph(), e2);
}
get graph() {
return this._graph;
}
get opsets() {
return this._opsets;
}
};
}, 782: (t, e) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2, e2) {
if (e2.endsWith("+")) {
const n2 = Number.parseInt(e2.substring(0, e2.length - 1), 10);
return !isNaN(n2) && n2 <= t2;
}
if (2 === e2.split("-").length) {
const n2 = e2.split("-"), r = Number.parseInt(n2[0], 10), i = Number.parseInt(n2[1], 10);
return !isNaN(r) && !isNaN(i) && r <= t2 && t2 <= i;
}
return Number.parseInt(e2, 10) === t2;
}
Object.defineProperty(e, "__esModule", { value: true }), e.resolveOperator = void 0, e.resolveOperator = function(t2, e2, r) {
for (const i of r) {
const r2 = i[0], o = i[1], a = i[2], s = i[3], u = i[4];
if (t2.opType === r2) {
for (const t3 of e2)
if ((t3.domain === o || "ai.onnx" === t3.domain && "" === o) && n(t3.version, a))
return { opImpl: s, opInit: u };
}
}
throw new TypeError(`cannot resolve operator '${t2.opType}' with opsets: ${e2.map((t3) => `${t3.domain || "ai.onnx"} v${t3.version}`).join(", ")}`);
};
}, 9395: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.onnxruntime = void 0;
const r = n(5686);
var i, o;
i = e.onnxruntime || (e.onnxruntime = {}), function(t2) {
let e2;
!function(t3) {
t3[t3.UNDEFINED = 0] = "UNDEFINED", t3[t3.FLOAT = 1] = "FLOAT", t3[t3.INT = 2] = "INT", t3[t3.STRING = 3] = "STRING", t3[t3.TENSOR = 4] = "TENSOR", t3[t3.GRAPH = 5] = "GRAPH", t3[t3.FLOATS = 6] = "FLOATS", t3[t3.INTS = 7] = "INTS", t3[t3.STRINGS = 8] = "STRINGS", t3[t3.TENSORS = 9] = "TENSORS", t3[t3.GRAPHS = 10] = "GRAPHS", t3[t3.SPARSE_TENSOR = 11] = "SPARSE_TENSOR", t3[t3.SPARSE_TENSORS = 12] = "SPARSE_TENSORS";
}(e2 = t2.AttributeType || (t2.AttributeType = {}));
}((o = i.experimental || (i.experimental = {})).fbs || (o.fbs = {})), function(t2) {
!function(t3) {
!function(t4) {
let e2;
!function(t5) {
t5[t5.UNKNOWN = 0] = "UNKNOWN", t5[t5.VALUE = 1] = "VALUE", t5[t5.PARAM = 2] = "PARAM";
}(e2 = t4.DimensionValueType || (t4.DimensionValueType = {}));
}(t3.fbs || (t3.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(t3) {
!function(t4) {
let e2;
!function(t5) {
t5[t5.UNDEFINED = 0] = "UNDEFINED", t5[t5.FLOAT = 1] = "FLOAT", t5[t5.UINT8 = 2] = "UINT8", t5[t5.INT8 = 3] = "INT8", t5[t5.UINT16 = 4] = "UINT16", t5[t5.INT16 = 5] = "INT16", t5[t5.INT32 = 6] = "INT32", t5[t5.INT64 = 7] = "INT64", t5[t5.STRING = 8] = "STRING", t5[t5.BOOL = 9] = "BOOL", t5[t5.FLOAT16 = 10] = "FLOAT16", t5[t5.DOUBLE = 11] = "DOUBLE", t5[t5.UINT32 = 12] = "UINT32", t5[t5.UINT64 = 13] = "UINT64", t5[t5.COMPLEX64 = 14] = "COMPLEX64", t5[t5.COMPLEX128 = 15] = "COMPLEX128", t5[t5.BFLOAT16 = 16] = "BFLOAT16";
}(e2 = t4.TensorDataType || (t4.TensorDataType = {}));
}(t3.fbs || (t3.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(t3) {
!function(t4) {
let e2;
!function(t5) {
t5[t5.Primitive = 0] = "Primitive", t5[t5.Fused = 1] = "Fused";
}(e2 = t4.NodeType || (t4.NodeType = {}));
}(t3.fbs || (t3.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(t3) {
!function(t4) {
let e2;
!function(t5) {
t5[t5.NONE = 0] = "NONE", t5[t5.tensor_type = 1] = "tensor_type", t5[t5.sequence_type = 2] = "sequence_type", t5[t5.map_type = 3] = "map_type";
}(e2 = t4.TypeInfoValue || (t4.TypeInfoValue = {}));
}(t3.fbs || (t3.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsShape(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsShape(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
dim(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 4);
return r2 ? (n3 || new t2.experimental.fbs.Dimension()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
dimLength() {
let t3 = this.bb.__offset(this.bb_pos, 4);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
static startShape(t3) {
t3.startObject(1);
}
static addDim(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static createDimVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startDimVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static endShape(t3) {
return t3.endObject();
}
static createShape(t3, e4) {
return n2.startShape(t3), n2.addDim(t3, e4), n2.endShape(t3);
}
}
e3.Shape = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsDimension(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsDimension(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
value(e4) {
let n3 = this.bb.__offset(this.bb_pos, 4);
return n3 ? (e4 || new t2.experimental.fbs.DimensionValue()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
denotation(t3) {
let e4 = this.bb.__offset(this.bb_pos, 6);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
static startDimension(t3) {
t3.startObject(2);
}
static addValue(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static addDenotation(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static endDimension(t3) {
return t3.endObject();
}
static createDimension(t3, e4, r2) {
return n2.startDimension(t3), n2.addValue(t3, e4), n2.addDenotation(t3, r2), n2.endDimension(t3);
}
}
e3.Dimension = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsDimensionValue(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsDimensionValue(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
dimType() {
let e4 = this.bb.__offset(this.bb_pos, 4);
return e4 ? this.bb.readInt8(this.bb_pos + e4) : t2.experimental.fbs.DimensionValueType.UNKNOWN;
}
dimValue() {
let t3 = this.bb.__offset(this.bb_pos, 6);
return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0);
}
dimParam(t3) {
let e4 = this.bb.__offset(this.bb_pos, 8);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
static startDimensionValue(t3) {
t3.startObject(3);
}
static addDimType(e4, n3) {
e4.addFieldInt8(0, n3, t2.experimental.fbs.DimensionValueType.UNKNOWN);
}
static addDimValue(t3, e4) {
t3.addFieldInt64(1, e4, t3.createLong(0, 0));
}
static addDimParam(t3, e4) {
t3.addFieldOffset(2, e4, 0);
}
static endDimensionValue(t3) {
return t3.endObject();
}
static createDimensionValue(t3, e4, r2, i2) {
return n2.startDimensionValue(t3), n2.addDimType(t3, e4), n2.addDimValue(t3, r2), n2.addDimParam(t3, i2), n2.endDimensionValue(t3);
}
}
e3.DimensionValue = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsTensorTypeAndShape(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsTensorTypeAndShape(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
elemType() {
let e4 = this.bb.__offset(this.bb_pos, 4);
return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED;
}
shape(e4) {
let n3 = this.bb.__offset(this.bb_pos, 6);
return n3 ? (e4 || new t2.experimental.fbs.Shape()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
static startTensorTypeAndShape(t3) {
t3.startObject(2);
}
static addElemType(e4, n3) {
e4.addFieldInt32(0, n3, t2.experimental.fbs.TensorDataType.UNDEFINED);
}
static addShape(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static endTensorTypeAndShape(t3) {
return t3.endObject();
}
static createTensorTypeAndShape(t3, e4, r2) {
return n2.startTensorTypeAndShape(t3), n2.addElemType(t3, e4), n2.addShape(t3, r2), n2.endTensorTypeAndShape(t3);
}
}
e3.TensorTypeAndShape = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsMapType(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsMapType(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
keyType() {
let e4 = this.bb.__offset(this.bb_pos, 4);
return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED;
}
valueType(e4) {
let n3 = this.bb.__offset(this.bb_pos, 6);
return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
static startMapType(t3) {
t3.startObject(2);
}
static addKeyType(e4, n3) {
e4.addFieldInt32(0, n3, t2.experimental.fbs.TensorDataType.UNDEFINED);
}
static addValueType(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static endMapType(t3) {
return t3.endObject();
}
static createMapType(t3, e4, r2) {
return n2.startMapType(t3), n2.addKeyType(t3, e4), n2.addValueType(t3, r2), n2.endMapType(t3);
}
}
e3.MapType = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsSequenceType(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsSequenceType(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
elemType(e4) {
let n3 = this.bb.__offset(this.bb_pos, 4);
return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
static startSequenceType(t3) {
t3.startObject(1);
}
static addElemType(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static endSequenceType(t3) {
return t3.endObject();
}
static createSequenceType(t3, e4) {
return n2.startSequenceType(t3), n2.addElemType(t3, e4), n2.endSequenceType(t3);
}
}
e3.SequenceType = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(t3) {
(t3.fbs || (t3.fbs = {})).EdgeEnd = class {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t4, e2) {
return this.bb_pos = t4, this.bb = e2, 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(t4, e2, n2, r2) {
return t4.prep(4, 12), t4.writeInt32(r2), t4.writeInt32(n2), t4.writeInt32(e2), t4.offset();
}
};
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsNodeEdge(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsNodeEdge(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
nodeIndex() {
let t3 = this.bb.__offset(this.bb_pos, 4);
return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0;
}
inputEdges(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 6);
return r2 ? (n3 || new t2.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + r2) + 12 * e4, this.bb) : null;
}
inputEdgesLength() {
let t3 = this.bb.__offset(this.bb_pos, 6);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
outputEdges(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 8);
return r2 ? (n3 || new t2.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + r2) + 12 * e4, this.bb) : null;
}
outputEdgesLength() {
let t3 = this.bb.__offset(this.bb_pos, 8);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
static startNodeEdge(t3) {
t3.startObject(3);
}
static addNodeIndex(t3, e4) {
t3.addFieldInt32(0, e4, 0);
}
static addInputEdges(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static startInputEdgesVector(t3, e4) {
t3.startVector(12, e4, 4);
}
static addOutputEdges(t3, e4) {
t3.addFieldOffset(2, e4, 0);
}
static startOutputEdgesVector(t3, e4) {
t3.startVector(12, e4, 4);
}
static endNodeEdge(t3) {
return t3.endObject();
}
static createNodeEdge(t3, e4, r2, i2) {
return n2.startNodeEdge(t3), n2.addNodeIndex(t3, e4), n2.addInputEdges(t3, r2), n2.addOutputEdges(t3, i2), n2.endNodeEdge(t3);
}
}
e3.NodeEdge = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsNode(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsNode(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
name(t3) {
let e4 = this.bb.__offset(this.bb_pos, 4);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
docString(t3) {
let e4 = this.bb.__offset(this.bb_pos, 6);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
domain(t3) {
let e4 = this.bb.__offset(this.bb_pos, 8);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
sinceVersion() {
let t3 = this.bb.__offset(this.bb_pos, 10);
return t3 ? this.bb.readInt32(this.bb_pos + t3) : 0;
}
index() {
let t3 = this.bb.__offset(this.bb_pos, 12);
return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0;
}
opType(t3) {
let e4 = this.bb.__offset(this.bb_pos, 14);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
type() {
let e4 = this.bb.__offset(this.bb_pos, 16);
return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.NodeType.Primitive;
}
executionProviderType(t3) {
let e4 = this.bb.__offset(this.bb_pos, 18);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
inputs(t3, e4) {
let n3 = this.bb.__offset(this.bb_pos, 20);
return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
}
inputsLength() {
let t3 = this.bb.__offset(this.bb_pos, 20);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
outputs(t3, e4) {
let n3 = this.bb.__offset(this.bb_pos, 22);
return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
}
outputsLength() {
let t3 = this.bb.__offset(this.bb_pos, 22);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
attributes(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 24);
return r2 ? (n3 || new t2.experimental.fbs.Attribute()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
attributesLength() {
let t3 = this.bb.__offset(this.bb_pos, 24);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
inputArgCounts(t3) {
let e4 = this.bb.__offset(this.bb_pos, 26);
return e4 ? this.bb.readInt32(this.bb.__vector(this.bb_pos + e4) + 4 * t3) : 0;
}
inputArgCountsLength() {
let t3 = this.bb.__offset(this.bb_pos, 26);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
inputArgCountsArray() {
let t3 = this.bb.__offset(this.bb_pos, 26);
return t3 ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null;
}
implicitInputs(t3, e4) {
let n3 = this.bb.__offset(this.bb_pos, 28);
return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
}
implicitInputsLength() {
let t3 = this.bb.__offset(this.bb_pos, 28);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
static startNode(t3) {
t3.startObject(13);
}
static addName(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static addDocString(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static addDomain(t3, e4) {
t3.addFieldOffset(2, e4, 0);
}
static addSinceVersion(t3, e4) {
t3.addFieldInt32(3, e4, 0);
}
static addIndex(t3, e4) {
t3.addFieldInt32(4, e4, 0);
}
static addOpType(t3, e4) {
t3.addFieldOffset(5, e4, 0);
}
static addType(e4, n3) {
e4.addFieldInt32(6, n3, t2.experimental.fbs.NodeType.Primitive);
}
static addExecutionProviderType(t3, e4) {
t3.addFieldOffset(7, e4, 0);
}
static addInputs(t3, e4) {
t3.addFieldOffset(8, e4, 0);
}
static createInputsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startInputsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addOutputs(t3, e4) {
t3.addFieldOffset(9, e4, 0);
}
static createOutputsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startOutputsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addAttributes(t3, e4) {
t3.addFieldOffset(10, e4, 0);
}
static createAttributesVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startAttributesVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addInputArgCounts(t3, e4) {
t3.addFieldOffset(11, e4, 0);
}
static createInputArgCountsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addInt32(e4[n3]);
return t3.endVector();
}
static startInputArgCountsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addImplicitInputs(t3, e4) {
t3.addFieldOffset(12, e4, 0);
}
static createImplicitInputsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startImplicitInputsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static endNode(t3) {
return t3.endObject();
}
static createNode(t3, e4, r2, i2, o2, a, s, u, c, l, p, f, d, h) {
return n2.startNode(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addDomain(t3, i2), n2.addSinceVersion(t3, o2), n2.addIndex(t3, a), n2.addOpType(t3, s), n2.addType(t3, u), n2.addExecutionProviderType(t3, c), n2.addInputs(t3, l), n2.addOutputs(t3, p), n2.addAttributes(t3, f), n2.addInputArgCounts(t3, d), n2.addImplicitInputs(t3, h), n2.endNode(t3);
}
}
e3.Node = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsValueInfo(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsValueInfo(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
name(t3) {
let e4 = this.bb.__offset(this.bb_pos, 4);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
docString(t3) {
let e4 = this.bb.__offset(this.bb_pos, 6);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
type(e4) {
let n3 = this.bb.__offset(this.bb_pos, 8);
return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
static startValueInfo(t3) {
t3.startObject(3);
}
static addName(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static addDocString(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static addType(t3, e4) {
t3.addFieldOffset(2, e4, 0);
}
static endValueInfo(t3) {
return t3.endObject();
}
static createValueInfo(t3, e4, r2, i2) {
return n2.startValueInfo(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addType(t3, i2), n2.endValueInfo(t3);
}
}
e3.ValueInfo = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsTypeInfo(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsTypeInfo(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
denotation(t3) {
let e4 = this.bb.__offset(this.bb_pos, 4);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
valueType() {
let e4 = this.bb.__offset(this.bb_pos, 6);
return e4 ? this.bb.readUint8(this.bb_pos + e4) : t2.experimental.fbs.TypeInfoValue.NONE;
}
value(t3) {
let e4 = this.bb.__offset(this.bb_pos, 8);
return e4 ? this.bb.__union(t3, this.bb_pos + e4) : null;
}
static startTypeInfo(t3) {
t3.startObject(3);
}
static addDenotation(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static addValueType(e4, n3) {
e4.addFieldInt8(1, n3, t2.experimental.fbs.TypeInfoValue.NONE);
}
static addValue(t3, e4) {
t3.addFieldOffset(2, e4, 0);
}
static endTypeInfo(t3) {
return t3.endObject();
}
static createTypeInfo(t3, e4, r2, i2) {
return n2.startTypeInfo(t3), n2.addDenotation(t3, e4), n2.addValueType(t3, r2), n2.addValue(t3, i2), n2.endTypeInfo(t3);
}
}
e3.TypeInfo = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(t3) {
!function(t4) {
class e2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t5, e3) {
return this.bb_pos = t5, this.bb = e3, this;
}
static getRootAsOperatorSetId(t5, n2) {
return (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5);
}
static getSizePrefixedRootAsOperatorSetId(t5, n2) {
return t5.setPosition(t5.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5);
}
domain(t5) {
let e3 = this.bb.__offset(this.bb_pos, 4);
return e3 ? this.bb.__string(this.bb_pos + e3, t5) : null;
}
version() {
let t5 = this.bb.__offset(this.bb_pos, 6);
return t5 ? this.bb.readInt64(this.bb_pos + t5) : this.bb.createLong(0, 0);
}
static startOperatorSetId(t5) {
t5.startObject(2);
}
static addDomain(t5, e3) {
t5.addFieldOffset(0, e3, 0);
}
static addVersion(t5, e3) {
t5.addFieldInt64(1, e3, t5.createLong(0, 0));
}
static endOperatorSetId(t5) {
return t5.endObject();
}
static createOperatorSetId(t5, n2, r2) {
return e2.startOperatorSetId(t5), e2.addDomain(t5, n2), e2.addVersion(t5, r2), e2.endOperatorSetId(t5);
}
}
t4.OperatorSetId = e2;
}(t3.fbs || (t3.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsTensor(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsTensor(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
name(t3) {
let e4 = this.bb.__offset(this.bb_pos, 4);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
docString(t3) {
let e4 = this.bb.__offset(this.bb_pos, 6);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
dims(t3) {
let e4 = this.bb.__offset(this.bb_pos, 8);
return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0);
}
dimsLength() {
let t3 = this.bb.__offset(this.bb_pos, 8);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
dataType() {
let e4 = this.bb.__offset(this.bb_pos, 10);
return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED;
}
rawData(t3) {
let e4 = this.bb.__offset(this.bb_pos, 12);
return e4 ? this.bb.readUint8(this.bb.__vector(this.bb_pos + e4) + t3) : 0;
}
rawDataLength() {
let t3 = this.bb.__offset(this.bb_pos, 12);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
rawDataArray() {
let t3 = this.bb.__offset(this.bb_pos, 12);
return t3 ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null;
}
stringData(t3, e4) {
let n3 = this.bb.__offset(this.bb_pos, 14);
return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
}
stringDataLength() {
let t3 = this.bb.__offset(this.bb_pos, 14);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
static startTensor(t3) {
t3.startObject(6);
}
static addName(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static addDocString(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static addDims(t3, e4) {
t3.addFieldOffset(2, e4, 0);
}
static createDimsVector(t3, e4) {
t3.startVector(8, e4.length, 8);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addInt64(e4[n3]);
return t3.endVector();
}
static startDimsVector(t3, e4) {
t3.startVector(8, e4, 8);
}
static addDataType(e4, n3) {
e4.addFieldInt32(3, n3, t2.experimental.fbs.TensorDataType.UNDEFINED);
}
static addRawData(t3, e4) {
t3.addFieldOffset(4, e4, 0);
}
static createRawDataVector(t3, e4) {
t3.startVector(1, e4.length, 1);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addInt8(e4[n3]);
return t3.endVector();
}
static startRawDataVector(t3, e4) {
t3.startVector(1, e4, 1);
}
static addStringData(t3, e4) {
t3.addFieldOffset(5, e4, 0);
}
static createStringDataVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startStringDataVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static endTensor(t3) {
return t3.endObject();
}
static createTensor(t3, e4, r2, i2, o2, a, s) {
return n2.startTensor(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addDims(t3, i2), n2.addDataType(t3, o2), n2.addRawData(t3, a), n2.addStringData(t3, s), n2.endTensor(t3);
}
}
e3.Tensor = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsSparseTensor(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsSparseTensor(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
values(e4) {
let n3 = this.bb.__offset(this.bb_pos, 4);
return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
indices(e4) {
let n3 = this.bb.__offset(this.bb_pos, 6);
return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
dims(t3) {
let e4 = this.bb.__offset(this.bb_pos, 8);
return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0);
}
dimsLength() {
let t3 = this.bb.__offset(this.bb_pos, 8);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
static startSparseTensor(t3) {
t3.startObject(3);
}
static addValues(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static addIndices(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static addDims(t3, e4) {
t3.addFieldOffset(2, e4, 0);
}
static createDimsVector(t3, e4) {
t3.startVector(8, e4.length, 8);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addInt64(e4[n3]);
return t3.endVector();
}
static startDimsVector(t3, e4) {
t3.startVector(8, e4, 8);
}
static endSparseTensor(t3) {
return t3.endObject();
}
static createSparseTensor(t3, e4, r2, i2) {
return n2.startSparseTensor(t3), n2.addValues(t3, e4), n2.addIndices(t3, r2), n2.addDims(t3, i2), n2.endSparseTensor(t3);
}
}
e3.SparseTensor = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsAttribute(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsAttribute(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
name(t3) {
let e4 = this.bb.__offset(this.bb_pos, 4);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
docString(t3) {
let e4 = this.bb.__offset(this.bb_pos, 6);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
type() {
let e4 = this.bb.__offset(this.bb_pos, 8);
return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.AttributeType.UNDEFINED;
}
f() {
let t3 = this.bb.__offset(this.bb_pos, 10);
return t3 ? this.bb.readFloat32(this.bb_pos + t3) : 0;
}
i() {
let t3 = this.bb.__offset(this.bb_pos, 12);
return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0);
}
s(t3) {
let e4 = this.bb.__offset(this.bb_pos, 14);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
t(e4) {
let n3 = this.bb.__offset(this.bb_pos, 16);
return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
g(e4) {
let n3 = this.bb.__offset(this.bb_pos, 18);
return n3 ? (e4 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
floats(t3) {
let e4 = this.bb.__offset(this.bb_pos, 20);
return e4 ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + e4) + 4 * t3) : 0;
}
floatsLength() {
let t3 = this.bb.__offset(this.bb_pos, 20);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
floatsArray() {
let t3 = this.bb.__offset(this.bb_pos, 20);
return t3 ? new Float32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null;
}
ints(t3) {
let e4 = this.bb.__offset(this.bb_pos, 22);
return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0);
}
intsLength() {
let t3 = this.bb.__offset(this.bb_pos, 22);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
strings(t3, e4) {
let n3 = this.bb.__offset(this.bb_pos, 24);
return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
}
stringsLength() {
let t3 = this.bb.__offset(this.bb_pos, 24);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
tensors(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 26);
return r2 ? (n3 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
tensorsLength() {
let t3 = this.bb.__offset(this.bb_pos, 26);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
graphs(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 28);
return r2 ? (n3 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
graphsLength() {
let t3 = this.bb.__offset(this.bb_pos, 28);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
static startAttribute(t3) {
t3.startObject(13);
}
static addName(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static addDocString(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static addType(e4, n3) {
e4.addFieldInt32(2, n3, t2.experimental.fbs.AttributeType.UNDEFINED);
}
static addF(t3, e4) {
t3.addFieldFloat32(3, e4, 0);
}
static addI(t3, e4) {
t3.addFieldInt64(4, e4, t3.createLong(0, 0));
}
static addS(t3, e4) {
t3.addFieldOffset(5, e4, 0);
}
static addT(t3, e4) {
t3.addFieldOffset(6, e4, 0);
}
static addG(t3, e4) {
t3.addFieldOffset(7, e4, 0);
}
static addFloats(t3, e4) {
t3.addFieldOffset(8, e4, 0);
}
static createFloatsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addFloat32(e4[n3]);
return t3.endVector();
}
static startFloatsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addInts(t3, e4) {
t3.addFieldOffset(9, e4, 0);
}
static createIntsVector(t3, e4) {
t3.startVector(8, e4.length, 8);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addInt64(e4[n3]);
return t3.endVector();
}
static startIntsVector(t3, e4) {
t3.startVector(8, e4, 8);
}
static addStrings(t3, e4) {
t3.addFieldOffset(10, e4, 0);
}
static createStringsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startStringsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addTensors(t3, e4) {
t3.addFieldOffset(11, e4, 0);
}
static createTensorsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startTensorsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addGraphs(t3, e4) {
t3.addFieldOffset(12, e4, 0);
}
static createGraphsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startGraphsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static endAttribute(t3) {
return t3.endObject();
}
static createAttribute(t3, e4, r2, i2, o2, a, s, u, c, l, p, f, d, h) {
return n2.startAttribute(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addType(t3, i2), n2.addF(t3, o2), n2.addI(t3, a), n2.addS(t3, s), n2.addT(t3, u), n2.addG(t3, c), n2.addFloats(t3, l), n2.addInts(t3, p), n2.addStrings(t3, f), n2.addTensors(t3, d), n2.addGraphs(t3, h), n2.endAttribute(t3);
}
}
e3.Attribute = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsGraph(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsGraph(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
initializers(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 4);
return r2 ? (n3 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
initializersLength() {
let t3 = this.bb.__offset(this.bb_pos, 4);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
nodeArgs(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 6);
return r2 ? (n3 || new t2.experimental.fbs.ValueInfo()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
nodeArgsLength() {
let t3 = this.bb.__offset(this.bb_pos, 6);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
nodes(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 8);
return r2 ? (n3 || new t2.experimental.fbs.Node()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
nodesLength() {
let t3 = this.bb.__offset(this.bb_pos, 8);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
maxNodeIndex() {
let t3 = this.bb.__offset(this.bb_pos, 10);
return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0;
}
nodeEdges(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 12);
return r2 ? (n3 || new t2.experimental.fbs.NodeEdge()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
nodeEdgesLength() {
let t3 = this.bb.__offset(this.bb_pos, 12);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
inputs(t3, e4) {
let n3 = this.bb.__offset(this.bb_pos, 14);
return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
}
inputsLength() {
let t3 = this.bb.__offset(this.bb_pos, 14);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
outputs(t3, e4) {
let n3 = this.bb.__offset(this.bb_pos, 16);
return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
}
outputsLength() {
let t3 = this.bb.__offset(this.bb_pos, 16);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
sparseInitializers(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 18);
return r2 ? (n3 || new t2.experimental.fbs.SparseTensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
sparseInitializersLength() {
let t3 = this.bb.__offset(this.bb_pos, 18);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
static startGraph(t3) {
t3.startObject(8);
}
static addInitializers(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static createInitializersVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startInitializersVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addNodeArgs(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static createNodeArgsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startNodeArgsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addNodes(t3, e4) {
t3.addFieldOffset(2, e4, 0);
}
static createNodesVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startNodesVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addMaxNodeIndex(t3, e4) {
t3.addFieldInt32(3, e4, 0);
}
static addNodeEdges(t3, e4) {
t3.addFieldOffset(4, e4, 0);
}
static createNodeEdgesVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startNodeEdgesVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addInputs(t3, e4) {
t3.addFieldOffset(5, e4, 0);
}
static createInputsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startInputsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addOutputs(t3, e4) {
t3.addFieldOffset(6, e4, 0);
}
static createOutputsVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startOutputsVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addSparseInitializers(t3, e4) {
t3.addFieldOffset(7, e4, 0);
}
static createSparseInitializersVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startSparseInitializersVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static endGraph(t3) {
return t3.endObject();
}
static createGraph(t3, e4, r2, i2, o2, a, s, u, c) {
return n2.startGraph(t3), n2.addInitializers(t3, e4), n2.addNodeArgs(t3, r2), n2.addNodes(t3, i2), n2.addMaxNodeIndex(t3, o2), n2.addNodeEdges(t3, a), n2.addInputs(t3, s), n2.addOutputs(t3, u), n2.addSparseInitializers(t3, c), n2.endGraph(t3);
}
}
e3.Graph = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsModel(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsModel(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
irVersion() {
let t3 = this.bb.__offset(this.bb_pos, 4);
return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0);
}
opsetImport(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 6);
return r2 ? (n3 || new t2.experimental.fbs.OperatorSetId()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
opsetImportLength() {
let t3 = this.bb.__offset(this.bb_pos, 6);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
producerName(t3) {
let e4 = this.bb.__offset(this.bb_pos, 8);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
producerVersion(t3) {
let e4 = this.bb.__offset(this.bb_pos, 10);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
domain(t3) {
let e4 = this.bb.__offset(this.bb_pos, 12);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
modelVersion() {
let t3 = this.bb.__offset(this.bb_pos, 14);
return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0);
}
docString(t3) {
let e4 = this.bb.__offset(this.bb_pos, 16);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
graph(e4) {
let n3 = this.bb.__offset(this.bb_pos, 18);
return n3 ? (e4 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
graphDocString(t3) {
let e4 = this.bb.__offset(this.bb_pos, 20);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
static startModel(t3) {
t3.startObject(9);
}
static addIrVersion(t3, e4) {
t3.addFieldInt64(0, e4, t3.createLong(0, 0));
}
static addOpsetImport(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static createOpsetImportVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startOpsetImportVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static addProducerName(t3, e4) {
t3.addFieldOffset(2, e4, 0);
}
static addProducerVersion(t3, e4) {
t3.addFieldOffset(3, e4, 0);
}
static addDomain(t3, e4) {
t3.addFieldOffset(4, e4, 0);
}
static addModelVersion(t3, e4) {
t3.addFieldInt64(5, e4, t3.createLong(0, 0));
}
static addDocString(t3, e4) {
t3.addFieldOffset(6, e4, 0);
}
static addGraph(t3, e4) {
t3.addFieldOffset(7, e4, 0);
}
static addGraphDocString(t3, e4) {
t3.addFieldOffset(8, e4, 0);
}
static endModel(t3) {
return t3.endObject();
}
static createModel(t3, e4, r2, i2, o2, a, s, u, c, l) {
return n2.startModel(t3), n2.addIrVersion(t3, e4), n2.addOpsetImport(t3, r2), n2.addProducerName(t3, i2), n2.addProducerVersion(t3, o2), n2.addDomain(t3, a), n2.addModelVersion(t3, s), n2.addDocString(t3, u), n2.addGraph(t3, c), n2.addGraphDocString(t3, l), n2.endModel(t3);
}
}
e3.Model = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(t3) {
!function(t4) {
class e2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t5, e3) {
return this.bb_pos = t5, this.bb = e3, this;
}
static getRootAsKernelCreateInfos(t5, n2) {
return (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5);
}
static getSizePrefixedRootAsKernelCreateInfos(t5, n2) {
return t5.setPosition(t5.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5);
}
nodeIndices(t5) {
let e3 = this.bb.__offset(this.bb_pos, 4);
return e3 ? this.bb.readUint32(this.bb.__vector(this.bb_pos + e3) + 4 * t5) : 0;
}
nodeIndicesLength() {
let t5 = this.bb.__offset(this.bb_pos, 4);
return t5 ? this.bb.__vector_len(this.bb_pos + t5) : 0;
}
nodeIndicesArray() {
let t5 = this.bb.__offset(this.bb_pos, 4);
return t5 ? new Uint32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t5), this.bb.__vector_len(this.bb_pos + t5)) : null;
}
kernelDefHashes(t5) {
let e3 = this.bb.__offset(this.bb_pos, 6);
return e3 ? this.bb.readUint64(this.bb.__vector(this.bb_pos + e3) + 8 * t5) : this.bb.createLong(0, 0);
}
kernelDefHashesLength() {
let t5 = this.bb.__offset(this.bb_pos, 6);
return t5 ? this.bb.__vector_len(this.bb_pos + t5) : 0;
}
static startKernelCreateInfos(t5) {
t5.startObject(2);
}
static addNodeIndices(t5, e3) {
t5.addFieldOffset(0, e3, 0);
}
static createNodeIndicesVector(t5, e3) {
t5.startVector(4, e3.length, 4);
for (let n2 = e3.length - 1; n2 >= 0; n2--)
t5.addInt32(e3[n2]);
return t5.endVector();
}
static startNodeIndicesVector(t5, e3) {
t5.startVector(4, e3, 4);
}
static addKernelDefHashes(t5, e3) {
t5.addFieldOffset(1, e3, 0);
}
static createKernelDefHashesVector(t5, e3) {
t5.startVector(8, e3.length, 8);
for (let n2 = e3.length - 1; n2 >= 0; n2--)
t5.addInt64(e3[n2]);
return t5.endVector();
}
static startKernelDefHashesVector(t5, e3) {
t5.startVector(8, e3, 8);
}
static endKernelCreateInfos(t5) {
return t5.endObject();
}
static createKernelCreateInfos(t5, n2, r2) {
return e2.startKernelCreateInfos(t5), e2.addNodeIndices(t5, n2), e2.addKernelDefHashes(t5, r2), e2.endKernelCreateInfos(t5);
}
}
t4.KernelCreateInfos = e2;
}(t3.fbs || (t3.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsSubGraphSessionState(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsSubGraphSessionState(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
graphId(t3) {
let e4 = this.bb.__offset(this.bb_pos, 4);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
sessionState(e4) {
let n3 = this.bb.__offset(this.bb_pos, 6);
return n3 ? (e4 || new t2.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
static startSubGraphSessionState(t3) {
t3.startObject(2);
}
static addGraphId(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static addSessionState(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static endSubGraphSessionState(t3) {
let e4 = t3.endObject();
return t3.requiredField(e4, 4), e4;
}
static createSubGraphSessionState(t3, e4, r2) {
return n2.startSubGraphSessionState(t3), n2.addGraphId(t3, e4), n2.addSessionState(t3, r2), n2.endSubGraphSessionState(t3);
}
}
e3.SubGraphSessionState = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsSessionState(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsSessionState(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
kernels(e4) {
let n3 = this.bb.__offset(this.bb_pos, 4);
return n3 ? (e4 || new t2.experimental.fbs.KernelCreateInfos()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
subGraphSessionStates(e4, n3) {
let r2 = this.bb.__offset(this.bb_pos, 6);
return r2 ? (n3 || new t2.experimental.fbs.SubGraphSessionState()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
}
subGraphSessionStatesLength() {
let t3 = this.bb.__offset(this.bb_pos, 6);
return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
}
static startSessionState(t3) {
t3.startObject(2);
}
static addKernels(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static addSubGraphSessionStates(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static createSubGraphSessionStatesVector(t3, e4) {
t3.startVector(4, e4.length, 4);
for (let n3 = e4.length - 1; n3 >= 0; n3--)
t3.addOffset(e4[n3]);
return t3.endVector();
}
static startSubGraphSessionStatesVector(t3, e4) {
t3.startVector(4, e4, 4);
}
static endSessionState(t3) {
return t3.endObject();
}
static createSessionState(t3, e4, r2) {
return n2.startSessionState(t3), n2.addKernels(t3, e4), n2.addSubGraphSessionStates(t3, r2), n2.endSessionState(t3);
}
}
e3.SessionState = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {})), function(t2) {
!function(e2) {
!function(e3) {
class n2 {
constructor() {
this.bb = null, this.bb_pos = 0;
}
__init(t3, e4) {
return this.bb_pos = t3, this.bb = e4, this;
}
static getRootAsInferenceSession(t3, e4) {
return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static getSizePrefixedRootAsInferenceSession(t3, e4) {
return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
}
static bufferHasIdentifier(t3) {
return t3.__has_identifier("ORTM");
}
ortVersion(t3) {
let e4 = this.bb.__offset(this.bb_pos, 4);
return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
}
model(e4) {
let n3 = this.bb.__offset(this.bb_pos, 6);
return n3 ? (e4 || new t2.experimental.fbs.Model()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
sessionState(e4) {
let n3 = this.bb.__offset(this.bb_pos, 8);
return n3 ? (e4 || new t2.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
}
static startInferenceSession(t3) {
t3.startObject(3);
}
static addOrtVersion(t3, e4) {
t3.addFieldOffset(0, e4, 0);
}
static addModel(t3, e4) {
t3.addFieldOffset(1, e4, 0);
}
static addSessionState(t3, e4) {
t3.addFieldOffset(2, e4, 0);
}
static endInferenceSession(t3) {
return t3.endObject();
}
static finishInferenceSessionBuffer(t3, e4) {
t3.finish(e4, "ORTM");
}
static finishSizePrefixedInferenceSessionBuffer(t3, e4) {
t3.finish(e4, "ORTM", true);
}
static createInferenceSession(t3, e4, r2, i2) {
return n2.startInferenceSession(t3), n2.addOrtVersion(t3, e4), n2.addModel(t3, r2), n2.addSessionState(t3, i2), n2.endInferenceSession(t3);
}
}
e3.InferenceSession = n2;
}(e2.fbs || (e2.fbs = {}));
}(t2.experimental || (t2.experimental = {}));
}(e.onnxruntime || (e.onnxruntime = {}));
}, 7448: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.OnnxjsSessionHandler = void 0;
const r = n(1670), i = n(9162);
e.OnnxjsSessionHandler = class {
constructor(t2) {
this.session = t2, this.inputNames = this.session.inputNames, this.outputNames = this.session.outputNames;
}
async dispose() {
}
async run(t2, e2, n2) {
const o = /* @__PURE__ */ new Map();
for (const e3 in t2)
if (Object.hasOwnProperty.call(t2, e3)) {
const n3 = t2[e3];
o.set(e3, new i.Tensor(n3.dims, n3.type, void 0, void 0, n3.data));
}
const a = await this.session.run(o), s = {};
return a.forEach((t3, e3) => {
s[e3] = new r.Tensor(t3.type, t3.data, t3.dims);
}), s;
}
startProfiling() {
this.session.startProfiling();
}
endProfiling() {
this.session.endProfiling();
}
};
}, 6919: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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(t2 = {}) {
this._initialized = false, this.backendHint = t2.backendHint, this.profiler = s.Profiler.create(t2.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(t2, e2, n2) {
await this.profiler.event("session", "Session.loadModel", async () => {
const a2 = await (0, o.resolveBackend)(this.backendHint);
if (this.sessionHandler = a2.createSessionHandler(this.context), this._model = new u.Model(), "string" == typeof t2) {
const e3 = t2.endsWith(".ort");
if ("undefined" == typeof fetch) {
const n3 = await (0, i.promisify)(r.readFile)(t2);
this.initialize(n3, e3);
} else {
const n3 = await fetch(t2), r2 = await n3.arrayBuffer();
this.initialize(new Uint8Array(r2), e3);
}
} else if (ArrayBuffer.isView(t2))
this.initialize(t2);
else {
const r2 = new Uint8Array(t2, e2 || 0, n2 || t2.byteLength);
this.initialize(r2);
}
});
}
initialize(t2, e2) {
if (this._initialized)
throw new Error("already initialized");
this.profiler.event("session", "Session.initialize", () => {
const n2 = this.sessionHandler.transformGraph ? this.sessionHandler : void 0;
this._model.load(t2, n2, e2), 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 = true;
}
async run(t2) {
if (!this._initialized)
throw new Error("session not initialized yet");
return this.profiler.event("session", "Session.run", async () => {
const e2 = this.normalizeAndValidateInputs(t2), n2 = await this._executionPlan.execute(this.sessionHandler, e2);
return this.createOutput(n2);
});
}
normalizeAndValidateInputs(t2) {
const e2 = this._model.graph.getInputNames();
if (Array.isArray(t2)) {
if (t2.length !== e2.length)
throw new Error(`incorrect input array length: expected ${e2.length} but got ${t2.length}`);
} else {
if (t2.size !== e2.length)
throw new Error(`incorrect input map size: expected ${e2.length} but got ${t2.size}`);
const n2 = new Array(t2.size);
let r2 = 0;
for (let i2 = 0; i2 < e2.length; ++i2) {
const o2 = t2.get(e2[i2]);
if (!o2)
throw new Error(`missing input tensor for: '${name}'`);
n2[r2++] = o2;
}
t2 = n2;
}
if (this.context.graphInputTypes && 0 !== this.context.graphInputTypes.length && this.context.graphInputDims && 0 !== this.context.graphInputDims.length)
this.validateInputTensorDims(this.context.graphInputDims, t2, false);
else {
const e3 = this._model.graph.getInputIndices(), n2 = this._model.graph.getValues(), r2 = new Array(e3.length);
for (let i2 = 0; i2 < e3.length; ++i2) {
const o2 = n2[e3[i2]];
r2[i2] = o2.type.shape.dims, this.context.graphInputTypes.push(o2.type.tensorType), this.context.graphInputDims.push(t2[i2].dims);
}
this.validateInputTensorDims(r2, t2, true);
}
return this.validateInputTensorTypes(this.context.graphInputTypes, t2), t2;
}
validateInputTensorTypes(t2, e2) {
for (let n2 = 0; n2 < e2.length; n2++) {
const r2 = t2[n2], i2 = e2[n2].type;
if (r2 !== i2)
throw new Error(`input tensor[${n2}] check failed: expected type '${r2}' but got ${i2}`);
}
}
validateInputTensorDims(t2, e2, n2) {
for (let r2 = 0; r2 < e2.length; r2++) {
const i2 = t2[r2], o2 = e2[r2].dims;
if (!this.compareTensorDims(i2, o2, n2))
throw new Error(`input tensor[${r2}] check failed: expected shape '[${i2.join(",")}]' but got [${o2.join(",")}]`);
}
}
compareTensorDims(t2, e2, n2) {
if (t2.length !== e2.length)
return false;
for (let r2 = 0; r2 < t2.length; ++r2)
if (t2[r2] !== e2[r2] && (!n2 || 0 !== t2[r2]))
return false;
return true;
}
createOutput(t2) {
const e2 = this._model.graph.getOutputNames();
if (t2.length !== e2.length)
throw new Error("expected number of outputs do not match number of generated outputs");
const n2 = /* @__PURE__ */ new Map();
for (let r2 = 0; r2 < e2.length; ++r2)
n2.set(e2[r2], t2[r2]);
return n2;
}
initializeOps(t2) {
const e2 = t2.getNodes();
this._ops = new Array(e2.length);
for (let n2 = 0; n2 < e2.length; n2++)
this._ops[n2] = this.sessionHandler.resolve(e2[n2], this._model.opsets, t2);
}
};
}, 9162: function(t, e, n) {
"use strict";
var r = this && this.__importDefault || function(t2) {
return t2 && t2.__esModule ? t2 : { default: t2 };
};
Object.defineProperty(e, "__esModule", { value: true }), 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 t2 = this.dataProvider(this.dataId);
if (t2.length !== this.size)
throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");
this.cache = t2;
}
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(t2) {
return this.data[u.ShapeUtil.indicesToOffset(t2, this.strides)];
}
set(t2, e2) {
this.data[u.ShapeUtil.indicesToOffset(t2, this.strides)] = e2;
}
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(t2, e2, n2, r2, o2, a2 = i.Guid.create()) {
this.dims = t2, this.type = e2, this.dataProvider = n2, this.asyncDataProvider = r2, this.cache = o2, this.dataId = a2, this.size = u.ShapeUtil.validateDimsAndCalcSize(t2);
const s2 = this.size, c2 = void 0 === n2 && void 0 === r2 && void 0 === o2;
if (void 0 !== o2 && o2.length !== s2)
throw new RangeError("Input dims doesn't match data length.");
if ("string" === e2) {
if (!(void 0 === o2 || Array.isArray(o2) && o2.every((t3) => "string" == typeof t3)))
throw new TypeError("cache should be a string array");
c2 && (this.cache = new Array(s2));
} else {
if (void 0 !== o2) {
const t3 = f(e2);
if (!(o2 instanceof t3))
throw new TypeError(`cache should be type ${t3.name}`);
}
if (c2) {
const t3 = new ArrayBuffer(s2 * function(t4) {
switch (t4) {
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 ${t4}`);
}
}(e2));
this.cache = function(t4, e3) {
return new (f(e3))(t4);
}(t3, e2);
}
}
}
static fromProto(t2) {
if (!t2)
throw new Error("cannot construct Value from an empty tensor");
const e2 = u.ProtoUtil.tensorDataTypeFromProto(t2.dataType), n2 = u.ProtoUtil.tensorDimsFromProto(t2.dims), r2 = new l(n2, e2);
if ("string" === e2)
t2.stringData.forEach((t3, e3) => {
r2.data[e3] = (0, u.decodeUtf8String)(t3);
});
else if (t2.rawData && "number" == typeof t2.rawData.byteLength && t2.rawData.byteLength > 0) {
const e3 = r2.data, n3 = new DataView(t2.rawData.buffer, t2.rawData.byteOffset, t2.rawData.byteLength), i2 = p(t2.dataType), o2 = t2.rawData.byteLength / i2;
if (t2.rawData.byteLength % i2 != 0)
throw new Error("invalid buffer length");
if (e3.length !== o2)
throw new Error("buffer length mismatch");
for (let r3 = 0; r3 < o2; r3++) {
const o3 = h(n3, t2.dataType, r3 * i2);
e3[r3] = o3;
}
} else {
let e3;
switch (t2.dataType) {
case a.onnx.TensorProto.DataType.FLOAT:
e3 = t2.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:
e3 = t2.int32Data;
break;
case a.onnx.TensorProto.DataType.INT64:
e3 = t2.int64Data;
break;
case a.onnx.TensorProto.DataType.DOUBLE:
e3 = t2.doubleData;
break;
case a.onnx.TensorProto.DataType.UINT32:
case a.onnx.TensorProto.DataType.UINT64:
e3 = t2.uint64Data;
break;
default:
throw new Error("unspecific error");
}
if (null == e3)
throw new Error("failed to populate data from a tensorproto value");
const n3 = r2.data;
if (n3.length !== e3.length)
throw new Error("array length mismatch");
for (let r3 = 0; r3 < e3.length; r3++) {
const i2 = e3[r3];
o.default.isLong(i2) ? n3[r3] = d(i2, t2.dataType) : n3[r3] = i2;
}
}
return r2;
}
static fromData(t2, e2, n2) {
return new l(e2, n2, void 0, void 0, t2);
}
static fromOrtTensor(t2) {
if (!t2)
throw new Error("cannot construct Value from an empty tensor");
const e2 = u.ProtoUtil.tensorDimsFromORTFormat(t2), n2 = u.ProtoUtil.tensorDataTypeFromProto(t2.dataType()), r2 = new l(e2, n2);
if ("string" === n2)
for (let e3 = 0; e3 < t2.stringDataLength(); e3++)
r2.data[e3] = t2.stringData(e3);
else if (t2.rawDataArray() && "number" == typeof t2.rawDataLength() && t2.rawDataLength() > 0) {
const e3 = r2.data, n3 = new DataView(t2.rawDataArray().buffer, t2.rawDataArray().byteOffset, t2.rawDataLength()), i2 = p(t2.dataType()), o2 = t2.rawDataLength() / i2;
if (t2.rawDataLength() % i2 != 0)
throw new Error("invalid buffer length");
if (e3.length !== o2)
throw new Error("buffer length mismatch");
for (let r3 = 0; r3 < o2; r3++) {
const o3 = h(n3, t2.dataType(), r3 * i2);
e3[r3] = o3;
}
}
return r2;
}
}
function p(t2) {
switch (t2) {
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[t2]}`);
}
}
function f(t2) {
switch (t2) {
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(t2, e2) {
if (e2 === a.onnx.TensorProto.DataType.INT64 || e2 === c.TensorDataType.INT64) {
if (t2.greaterThanOrEqual(2147483648) || t2.lessThan(-2147483648))
throw new TypeError("int64 is not supported");
} else {
if (e2 !== a.onnx.TensorProto.DataType.UINT32 && e2 !== c.TensorDataType.UINT32 && e2 !== a.onnx.TensorProto.DataType.UINT64 && e2 !== c.TensorDataType.UINT64)
throw new TypeError(`not a LONG type: ${a.onnx.TensorProto.DataType[e2]}`);
if (t2.greaterThanOrEqual(4294967296) || t2.lessThan(0))
throw new TypeError("uint64 is not supported");
}
return t2.toNumber();
}
function h(t2, e2, n2) {
switch (e2) {
case a.onnx.TensorProto.DataType.BOOL:
case a.onnx.TensorProto.DataType.UINT8:
return t2.getUint8(n2);
case a.onnx.TensorProto.DataType.INT8:
return t2.getInt8(n2);
case a.onnx.TensorProto.DataType.UINT16:
return t2.getUint16(n2, true);
case a.onnx.TensorProto.DataType.INT16:
return t2.getInt16(n2, true);
case a.onnx.TensorProto.DataType.FLOAT:
return t2.getFloat32(n2, true);
case a.onnx.TensorProto.DataType.INT32:
return t2.getInt32(n2, true);
case a.onnx.TensorProto.DataType.UINT32:
return t2.getUint32(n2, true);
case a.onnx.TensorProto.DataType.INT64:
return d(o.default.fromBits(t2.getUint32(n2, true), t2.getUint32(n2 + 4, true), false), e2);
case a.onnx.TensorProto.DataType.DOUBLE:
return t2.getFloat64(n2, true);
case a.onnx.TensorProto.DataType.UINT64:
return d(o.default.fromBits(t2.getUint32(n2, true), t2.getUint32(n2 + 4, true), true), e2);
default:
throw new Error(`cannot read from DataView for type ${a.onnx.TensorProto.DataType[e2]}`);
}
}
e.Tensor = l;
}, 2517: function(t, e, n) {
"use strict";
var r = this && this.__importDefault || function(t2) {
return t2 && t2.__esModule ? t2 : { default: t2 };
};
Object.defineProperty(e, "__esModule", { value: true }), 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(t2, ...e2) {
if (!t2 || t2.length !== e2.length)
return false;
for (let n2 = 0; n2 < t2.length; n2++)
if (!t2[n2].dims || t2[n2].dims.length !== e2[n2])
return false;
return true;
}, e.assert = function(t2, e2) {
if (!t2)
throw new Error("string" == typeof e2 ? e2 : e2());
}, e.ArrayUtil = class {
static arraysEqual(t2, e2) {
if (t2.length !== e2.length)
return false;
for (let n2 = 0; n2 < t2.length; n2++)
if (t2[n2] !== e2[n2])
return false;
return true;
}
};
class u {
static preprocessInputShapes(t2, e2) {
return [1 === t2.length ? [1, t2[0]] : t2, 1 === e2.length ? [e2[0], 1] : e2];
}
static postprocessOutputShape(t2, e2, n2) {
1 === e2 && t2.splice(t2.length - 2, 1), 1 === n2 && t2.pop();
}
static calcMatMulShape(t2, e2) {
return t2[1] !== e2[0] ? void 0 : [t2[0], e2[1]];
}
}
e.MatMulUtil = u;
class c {
static calcShape(t2, e2, n2 = false) {
const r2 = t2.length, i2 = e2.length;
if (0 === r2)
return e2;
if (0 === i2)
return t2;
const o2 = Math.max(t2.length, e2.length), a2 = new Array(o2);
if (n2) {
if (r2 < 2 || i2 < 2)
return;
const n3 = u.calcMatMulShape([t2[r2 - 2], t2[r2 - 1]], [e2[i2 - 2], e2[i2 - 1]]);
if (void 0 === n3)
return;
[a2[o2 - 2], a2[o2 - 1]] = n3;
}
for (let s2 = n2 ? 3 : 1; s2 <= o2; s2++) {
const n3 = r2 - s2 < 0 ? 1 : t2[r2 - s2], u2 = i2 - s2 < 0 ? 1 : e2[i2 - s2];
if (n3 !== u2 && n3 > 1 && u2 > 1)
return;
a2[o2 - s2] = Math.max(n3, u2);
}
return a2;
}
static index(t2, e2) {
const n2 = new Array(e2.length);
return c.fillIndex(t2, e2, n2), n2;
}
static fillIndex(t2, e2, n2) {
const r2 = t2.length - e2.length;
for (let i2 = 0; i2 < e2.length; i2++)
n2[i2] = t2[r2 + i2] % e2[i2];
}
static calc(t2, e2, n2, r2, i2) {
const o2 = c.calcShape(t2.dims, e2.dims);
if (o2) {
if (r2 && !f.areEqual(o2, t2.dims))
return;
const a2 = f.size(o2), u2 = r2 ? t2 : new s.Tensor(o2, i2 || t2.type);
if (0 === o2.length)
u2.set([], n2(t2.get([]), e2.get([])));
else {
const r3 = new Array(o2.length), i3 = new Array(t2.dims.length), s2 = new Array(e2.dims.length);
let l2, p2 = 0, f2 = 0, d2 = false, h2 = false;
0 === t2.dims.length && (p2 = t2.get([]), d2 = true), 0 === e2.dims.length && (f2 = e2.get([]), h2 = true);
for (let g2 = 0; g2 < a2; g2++) {
l2 = g2;
for (let t3 = o2.length - 1; t3 >= 0; t3--)
r3[t3] = l2 % o2[t3], l2 = Math.floor(l2 / o2[t3]);
d2 || (c.fillIndex(r3, t2.dims, i3), p2 = t2.get(i3)), h2 || (c.fillIndex(r3, e2.dims, s2), f2 = e2.get(s2)), u2.set(r3, n2(p2, f2));
}
}
return u2;
}
}
static isValidBroadcast(t2, e2) {
const n2 = t2.length, r2 = e2.length;
if (n2 > r2)
return false;
for (let i2 = 1; i2 <= n2; i2++)
if (1 !== t2[n2 - i2] && t2[n2 - i2] !== e2[r2 - i2])
return false;
return true;
}
static getBroadcastDims(t2, e2) {
const n2 = t2.length, r2 = [];
for (let i2 = 0; i2 < n2; i2++) {
const o2 = n2 - 1 - i2, a2 = t2[o2] || 1;
(e2[e2.length - 1 - i2] || 1) > 1 && 1 === a2 && r2.unshift(o2);
}
return r2;
}
}
e.BroadcastUtil = c, e.arrayCopyHelper = function(t2, e2, n2, r2, i2) {
if (r2 < 0 || r2 >= e2.length)
throw new Error("sourceIndex out of bounds");
if (n2 < 0 || n2 >= t2.length)
throw new Error("targetIndex out of bounds");
if (r2 + i2 > e2.length)
throw new Error("source indices to be copied are outside bounds");
if (n2 + i2 > t2.length)
throw new Error("target array is too small to hold result");
for (let o2 = 0; o2 < i2; o2++)
t2[n2 + o2] = e2[r2 + o2];
}, e.GemmUtil = class {
static getShapeOfGemmResult(t2, e2, n2, r2, i2) {
if (2 !== t2.length || 2 !== n2.length)
throw new Error("shape need to be of size 2");
let o2, a2, s2;
e2 ? (o2 = t2[1], a2 = t2[0]) : (o2 = t2[0], a2 = t2[1]);
let u2 = -1;
if (r2 ? (s2 = n2[0], u2 = 1) : (s2 = n2[1], u2 = 0), n2[u2] !== a2)
throw new Error("dimension mismatch");
if (o2 <= 0 || s2 <= 0 || a2 <= 0)
throw new Error("invalid shape specified");
if (i2 && !c.isValidBroadcast(i2, [o2, s2]))
throw new Error("gemm: invalid bias shape for broadcast");
return [o2, s2, a2];
}
};
class l {
static tensorDataTypeFromProto(t2) {
switch (t2) {
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[t2]}`);
}
}
static tensorDataTypeStringToEnum(t2) {
switch (t2) {
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: ${t2}`);
}
}
static tensorDimsFromProto(t2) {
return t2.map((t3) => o.default.isLong(t3) ? t3.toNumber() : t3);
}
static tensorValueTypeFromProto(t2) {
return { tensorType: l.tensorDataTypeFromProto(t2.elemType), shape: { dims: l.tensorDimsFromProto(t2.shape.dim.map((t3) => t3.dimValue)) } };
}
static tensorDimsFromORTFormat(t2) {
const e2 = [];
for (let n2 = 0; n2 < t2.dimsLength(); n2++)
e2.push(p.longToNumber(t2.dims(n2)));
return e2;
}
static tensorAttributesFromORTFormat(t2) {
const e2 = [];
for (let n2 = 0; n2 < t2.attributesLength(); n2++)
e2.push(t2.attributes(n2));
return e2;
}
}
e.ProtoUtil = l;
class p {
static longToNumber(t2, e2) {
return o.default.isLong(t2) ? t2.toNumber() : t2 instanceof i.flatbuffers.Long ? o.default.fromValue({ low: t2.low, high: t2.high, unsigned: null != e2 && e2 }).toNumber() : t2;
}
static isLong(t2) {
return o.default.isLong(t2) || t2 instanceof i.flatbuffers.Long;
}
}
e.LongUtil = p;
class f {
static size(t2) {
return f.getSizeFromDimensionRange(t2, 0, t2.length);
}
static sizeFromDimension(t2, e2) {
if (e2 < 0 || e2 > t2.length)
throw new Error(`invalid dimension of ${e2} for sizeFromDimension as Tensor has ${t2.length} dimensions.`);
return f.getSizeFromDimensionRange(t2, e2, t2.length);
}
static sizeToDimension(t2, e2) {
if (e2 < 0 || e2 > t2.length)
throw new Error(`invalid dimension of ${e2} for sizeToDimension as Tensor has ${t2.length} dimensions.`);
return f.getSizeFromDimensionRange(t2, 0, e2);
}
static getSizeFromDimensionRange(t2, e2, n2) {
let r2 = 1;
for (let i2 = e2; i2 < n2; i2++) {
if (t2[i2] <= 0)
throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");
r2 *= t2[i2];
}
return r2;
}
static computeStrides(t2) {
const e2 = t2.length;
if (0 === e2)
return [];
if (1 === e2)
return [1];
const n2 = new Array(e2);
n2[e2 - 1] = 1, n2[e2 - 2] = t2[e2 - 1];
for (let r2 = e2 - 3; r2 >= 0; --r2)
n2[r2] = n2[r2 + 1] * t2[r2 + 1];
return n2;
}
static transpose(t2) {
return t2.slice().reverse();
}
static indicesToOffset(t2, e2, n2) {
void 0 === n2 && (n2 = t2.length);
let r2 = 0;
for (let i2 = 0; i2 < n2; ++i2)
r2 += e2[i2] * t2[i2];
return r2;
}
static offsetToIndices(t2, e2) {
const n2 = e2.length;
if (0 === n2)
return [];
if (1 === n2)
return [t2 * e2[0]];
const r2 = new Array(e2.length);
for (let n3 = 0; n3 < r2.length - 1; ++n3)
r2[n3] = Math.floor(t2 / e2[n3]), t2 -= r2[n3] * e2[n3];
return r2[r2.length - 1] = t2, r2;
}
static normalizeAxis(t2, e2) {
if (t2 < -e2 && t2 >= e2)
throw new Error("unsupported axis for this operation.");
return t2 < 0 ? t2 + e2 : t2;
}
static normalizeAxes(t2, e2) {
return t2.map((t3) => this.normalizeAxis(t3, e2));
}
static incrementIndex(t2, e2, n2) {
if (0 === e2.length || 0 === t2.length)
throw new Error("Index incrementing unsupported for scalar Tensor");
if (void 0 === n2)
n2 = e2.length;
else if (n2 <= 0 || n2 > e2.length)
throw new Error("Incorrect axis to increment on");
for (let r2 = n2 - 1; r2 >= 0 && (t2[r2]++, !(t2[r2] < e2[r2])); --r2)
t2[r2] = 0;
}
static calculateReshapedDims(t2, e2) {
if (0 === e2.length) {
if (0 === t2.length || 1 === f.size(t2))
return [];
throw new Error("cannot reshape to a scalar Tensor");
}
const n2 = e2.length, r2 = new Array(n2);
let i2 = -1, o2 = 1;
for (let a3 = 0; a3 < n2; a3++) {
if (e2[a3] < -1)
throw new Error("a dimension in shape hints cannot be less than -1");
if (-1 === e2[a3]) {
if (-1 !== i2)
throw new Error("at most one dimension in shape hints can be -1");
i2 = a3;
} else {
if (0 === e2[a3]) {
if (a3 >= t2.length)
throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");
r2[a3] = t2[a3];
} else
r2[a3] = e2[a3];
o2 *= r2[a3];
}
}
const a2 = f.size(t2);
if (-1 !== i2) {
if (a2 % o2 != 0)
throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t2}] Output shape: [${e2}]`);
r2[i2] = a2 / o2;
} else if (o2 !== a2)
throw new Error("reshapedDims and originalDims don't have matching sizes");
return r2;
}
static sortBasedOnPerm(t2, e2) {
return e2 ? e2.map((e3) => t2[e3]) : t2.slice().reverse();
}
static padShape(t2, e2) {
const n2 = t2.length;
return t2.map((t3, r2) => t3 + e2[r2] + e2[r2 + n2]);
}
static areEqual(t2, e2) {
return t2.length === e2.length && t2.every((t3, n2) => t3 === e2[n2]);
}
static validateDimsAndCalcSize(t2) {
if (t2.length > 6)
throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");
let e2 = 1;
for (const n2 of t2) {
if (!Number.isInteger(n2))
throw new TypeError(`Invalid shape: ${n2} is not an integer`);
if (n2 < 0 || n2 > 2147483647)
throw new TypeError(`Invalid shape: length ${n2} is not allowed`);
e2 *= n2;
}
return e2;
}
static flattenShape(t2, e2) {
e2 < 0 && (e2 += t2.length);
const n2 = t2.reduce((t3, e3) => t3 * e3, 1), r2 = t2.slice(e2).reduce((t3, e3) => t3 * e3, 1);
return [n2 / r2, r2];
}
static squeezeShape(t2, e2) {
const n2 = new Array();
e2 = f.normalizeAxes(e2, t2.length);
for (let r2 = 0; r2 < t2.length; r2++) {
const i2 = e2.indexOf(r2) >= 0;
if (i2 && 1 !== t2[r2])
throw new Error("squeeze an axis of size different than 1");
(0 === e2.length && t2[r2] > 1 || e2.length > 0 && !i2) && n2.push(t2[r2]);
}
return n2;
}
static unsqueezeShape(t2, e2) {
const n2 = new Array(t2.length + e2.length);
n2.fill(0);
for (let t3 = 0; t3 < e2.length; t3++) {
const r3 = f.normalizeAxis(e2[t3], n2.length);
if (r3 >= n2.length)
throw new Error("'axes' has an out of range axis");
if (0 !== n2[r3])
throw new Error("'axes' has a duplicate axis");
n2[r3] = 1;
}
let r2 = 0;
for (let e3 = 0; e3 < n2.length; e3++)
0 === n2[e3] && (n2[e3] = t2[r2++]);
if (r2 !== t2.length)
throw new Error("the unsqueezed dimension could not be established");
return n2;
}
}
e.ShapeUtil = f, e.MathUtil = class {
static sqr(t2, e2, n2, r2, i2) {
if (r2 < 0 || r2 >= e2.length)
throw new Error("sourceIndex out of bounds");
if (n2 < 0 || n2 >= t2.length)
throw new Error("targetIndex out of bounds");
if (r2 + i2 > e2.length)
throw new Error("source indices to be copied are outside bounds");
if (n2 + i2 > t2.length)
throw new Error("target array is too small to hold result");
for (let o2 = 0; o2 < i2; o2++)
t2[n2 + o2] += Math.pow(e2[r2 + o2], 2);
}
static axpy(t2, e2, n2, r2, i2, o2) {
if (r2 < 0 || r2 >= e2.length)
throw new Error("sourceIndex out of bounds");
if (n2 < 0 || n2 >= t2.length)
throw new Error("targetIndex out of bounds");
if (r2 + i2 > e2.length)
throw new Error("source indices to be copied are outside bounds");
if (n2 + i2 > t2.length)
throw new Error("target array is too small to hold result");
for (let a2 = 0; a2 < i2; a2++)
t2[n2 + a2] += o2 * e2[r2 + a2];
}
static powx(t2, e2, n2, r2, i2, o2) {
if (r2 < 0 || r2 >= e2.length)
throw new Error("sourceIndex out of bounds");
if (n2 < 0 || n2 >= t2.length)
throw new Error("targetIndex out of bounds");
if (r2 + i2 > e2.length)
throw new Error("source indices to be copied are outside bounds");
if (n2 + i2 > t2.length)
throw new Error("target array is too small to hold result");
for (let a2 = 0; a2 < i2; a2++)
t2[n2 + a2] = Math.pow(e2[r2 + a2], o2);
}
static mul(t2, e2, n2, r2, i2) {
if (r2 < 0 || r2 >= e2.length)
throw new Error("sourceIndex out of bounds");
if (n2 < 0 || n2 >= t2.length)
throw new Error("targetIndex out of bounds");
if (r2 + i2 > e2.length)
throw new Error("source indices to be copied are outside bounds");
if (n2 + i2 > t2.length)
throw new Error("target array is too small to hold result");
for (let o2 = 0; o2 < i2; o2++)
t2[n2 + o2] = e2[r2 + o2] * t2[n2 + o2];
}
};
class d {
static splitShape(t2, e2, n2, r2) {
if (0 === n2.length) {
if (!r2)
throw new Error("need to know number of outputs when the 'split' attribute is not specified");
d.determineSplit(t2[e2], r2, n2);
}
const i2 = [], o2 = [0];
for (let r3 = 0; r3 < n2.length; ++r3) {
0 !== r3 && o2.push(o2[r3 - 1] + n2[r3 - 1]);
const a2 = t2.slice();
a2[e2] = n2[r3], i2.push(a2);
}
return [i2, o2];
}
static determineSplit(t2, e2, n2) {
if (t2 % e2 != 0)
throw new Error("cannot split tensor to equal sized parts");
for (let r2 = 0; r2 < e2; ++r2)
n2.push(t2 / e2);
}
}
e.SplitUtil = d;
class h {
static calcReduce(t2, e2, n2, r2, i2) {
const o2 = t2.dims.slice(0);
0 === e2.length && o2.forEach((t3, n3) => e2.push(n3));
const a2 = h.calcReduceShape(o2, e2, true), u2 = f.size(a2), l2 = new s.Tensor(a2, t2.type), p2 = f.computeStrides(a2), d2 = f.computeStrides(o2), g2 = new Array(o2.length);
for (let n3 = 0; n3 < u2; n3++) {
const a3 = f.offsetToIndices(n3, p2);
c.fillIndex(a3, o2, g2), l2.set(a3, h.calcReduceByAxis(t2.numberData, e2, o2, 0, f.indicesToOffset(g2, d2), r2, i2));
}
return n2 ? l2 : new s.Tensor(h.calcReduceShape(o2, e2, n2), l2.type, void 0, void 0, l2.data, l2.dataId);
}
static calcReduceByAxis(t2, e2, n2, r2, i2, o2, a2) {
let s2 = 0;
if (r2 >= e2.length)
return o2(t2[i2]);
const u2 = e2[r2], c2 = u2 >= n2.length ? 1 : f.size(n2.slice(u2 + 1));
for (let l2 = 0; l2 < n2[u2]; l2++)
s2 = 0 === l2 ? h.calcReduceByAxis(t2, e2, n2, r2 + 1, i2, o2, a2) : a2(s2, h.calcReduceByAxis(t2, e2, n2, r2 + 1, i2, o2, a2)), i2 += c2;
return s2;
}
static calcReduceShape(t2, e2, n2) {
const r2 = t2.slice();
for (let t3 = 0; t3 < e2.length; t3++)
r2[e2[t3]] = n2 ? 1 : 0;
return r2.filter((t3) => 0 !== t3);
}
}
e.ReduceUtil = h;
class g {
static adjustPoolAttributes(t2, e2, n2, r2, i2, o2) {
if (!t2 && n2.length !== e2.length - 2)
throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");
if (t2)
for (let t3 = 0; t3 < e2.length - 2; t3++)
t3 >= n2.length ? n2.push(e2[t3 + 2]) : n2[t3] = e2[t3 + 2];
for (let t3 = 0; t3 < n2.length; t3++)
if (t3 < r2.length) {
if (r2[t3] < 0)
throw new Error("strides should be greater than or equal to 1");
} else
r2.push(1);
for (let t3 = 0; t3 < n2.length; t3++)
if (t3 < i2.length) {
if (i2[t3] < 0)
throw new Error("dilations should be greater than or equal to 1");
} else
i2.push(1);
for (let t3 = 0; t3 < 2 * n2.length; t3++)
if (t3 < o2.length) {
if (o2[t3] < 0)
throw new Error("pad should be greater than or equal to 1");
} else
o2.push(0);
for (let t3 = 0; t3 < n2.length; t3++) {
if (n2[t3] <= 0)
throw new Error("kernel shapes need to be greater than 0");
if (o2[t3] >= n2[t3] || o2[t3 + n2.length] >= n2[t3])
throw new Error("pads should be smaller than kernel");
}
}
static adjustPadsBasedOnAutoPad(t2, e2, n2, r2, i2, o2) {
if (o2) {
if (i2.length !== 2 * (t2.length - 2))
throw new Error("length of pads should be twice the length of data dimensions");
if (e2.length !== t2.length - 2)
throw new Error("length of strides should be the length of data dimensions");
if (r2.length !== t2.length - 2)
throw new Error("length of kernel shapes should be the length of data dimensions");
for (let a2 = 0; a2 < t2.length - 2; a2++)
g.adjustPadAndReturnShape(t2[a2 + 2], e2[a2], n2[a2], r2[a2], i2, a2, a2 + t2.length - 2, o2);
}
}
static computePoolOutputShape(t2, e2, n2, r2, i2, o2, a2) {
if (e2.length <= 0)
throw new Error("input shape must be of size greater than 0");
const s2 = [e2[0], e2[1]];
return g.computeShapeHelper(t2, e2, s2, n2, r2, i2, o2, a2), s2;
}
static computeConvOutputShape(t2, e2, n2, r2, i2, o2, a2) {
if (t2.length <= 0 || e2.length <= 0)
throw new Error("invalid input tensor dims or invalid filter tensor dims");
const s2 = [t2[0], e2[0]];
return g.computeShapeHelper(false, t2, s2, n2, r2, i2, o2, a2), s2;
}
static computeShapeHelper(t2, e2, n2, r2, i2, o2, a2, s2) {
if (t2)
for (let t3 = 0; t3 < e2.length - 2; t3++)
n2.push(1);
else
for (let t3 = 0; t3 < e2.length - 2; t3++)
n2.push(g.adjustPadAndReturnShape(e2[t3 + 2], r2[t3], i2[t3], o2[t3], a2, t3, t3 + e2.length - 2, s2));
}
static adjustPadAndReturnShape(t2, e2, n2, r2, i2, o2, a2, s2) {
const u2 = n2 * (r2 - 1) + 1;
if (!s2 || "NOTSET" === s2)
return Math.floor((t2 + i2[o2] + i2[a2] - u2) / e2 + 1);
switch (s2) {
case "VALID":
return i2[o2] = 0, i2[a2] = 0, Math.floor((t2 - u2) / e2 + 1);
case "SAME_LOWER":
case "SAME_UPPER":
if (1 !== n2)
throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");
{
const n3 = ((t2 + e2 - 1) / e2 - 1) * e2 + r2 - t2;
return i2[o2] = "SAME_LOWER" === s2 ? Math.floor((n3 + 1) / 2) : Math.floor(n3 / 2), i2[a2] = n3 - i2[o2], Math.floor((t2 + n3 - r2) / e2 + 1);
}
default:
throw new Error("Unsupported AutoPad type");
}
}
}
e.PoolConvUtil = g, e.MIN_CLIP = -34028234663852886e22, e.MAX_CLIP = 34028234663852886e22, e.decodeUtf8String = function(t2) {
return new TextDecoder().decode(t2);
};
}, 7967: (t, e) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.iterateExtraOptions = void 0, e.iterateExtraOptions = (t2, n, r, i) => {
if ("object" == typeof t2 && null !== t2) {
if (r.has(t2))
throw new Error("Circular reference in options");
r.add(t2);
}
Object.entries(t2).forEach(([t3, o]) => {
const a = n ? n + t3 : t3;
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(t2, e2, n2, r2) {
void 0 === r2 && (r2 = n2);
var i2 = Object.getOwnPropertyDescriptor(e2, n2);
i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() {
return e2[n2];
} }), Object.defineProperty(t2, r2, i2);
} : function(t2, e2, n2, r2) {
void 0 === r2 && (r2 = n2), t2[r2] = e2[n2];
}), o = this && this.__setModuleDefault || (Object.create ? function(t2, e2) {
Object.defineProperty(t2, "default", { enumerable: true, value: e2 });
} : function(t2, e2) {
t2.default = e2;
}), a = this && this.__importStar || function(t2) {
if (t2 && t2.__esModule)
return t2;
var e2 = {};
if (null != t2)
for (var n2 in t2)
"default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && i(e2, t2, n2);
return o(e2, t2), e2;
};
Object.defineProperty(e, "__esModule", { value: true }), 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 = false, g = false, b = false;
const m = [], y = [], _ = [], v = [], w = [], x = [], T = () => {
if (h || !g || b || !p)
throw new Error("worker not ready");
}, S = (t2) => {
switch (t2.data.type) {
case "init-wasm":
h = false, t2.data.err ? (b = true, f[1](t2.data.err)) : (g = true, f[0]());
break;
case "init-ort":
t2.data.err ? d[1](t2.data.err) : d[0]();
break;
case "create_allocate":
t2.data.err ? m.shift()[1](t2.data.err) : m.shift()[0](t2.data.out);
break;
case "create_finalize":
t2.data.err ? y.shift()[1](t2.data.err) : y.shift()[0](t2.data.out);
break;
case "create":
t2.data.err ? _.shift()[1](t2.data.err) : _.shift()[0](t2.data.out);
break;
case "release":
t2.data.err ? v.shift()[1](t2.data.err) : v.shift()[0]();
break;
case "run":
t2.data.err ? w.shift()[1](t2.data.err) : w.shift()[0](t2.data.out);
break;
case "end-profiling":
t2.data.err ? x.shift()[1](t2.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 = true, void 0 === s.env.wasm.wasmPaths && O && 0 !== O.indexOf("blob:") && (s.env.wasm.wasmPaths = O.substr(0, +O.lastIndexOf("/") + 1)), new Promise((t2, e2) => {
null == p || p.terminate(), p = n(9710).Z(), p.onmessage = S, f = [t2, e2];
const r2 = { type: "init-wasm", in: s.env.wasm };
p.postMessage(r2);
});
}
return (0, c.initializeWebAssembly)(s.env.wasm);
}, e.initOrt = async (t2, e2) => {
if (l())
return T(), new Promise((n2, r2) => {
d = [n2, r2];
const i2 = { type: "init-ort", in: { numThreads: t2, loggingLevel: e2 } };
p.postMessage(i2);
});
u.initOrt(t2, e2);
}, e.createSessionAllocate = async (t2) => l() ? (T(), new Promise((e2, n2) => {
m.push([e2, n2]);
const r2 = { type: "create_allocate", in: { model: t2 } };
p.postMessage(r2, [t2.buffer]);
})) : u.createSessionAllocate(t2), e.createSessionFinalize = async (t2, e2) => l() ? (T(), new Promise((n2, r2) => {
y.push([n2, r2]);
const i2 = { type: "create_finalize", in: { modeldata: t2, options: e2 } };
p.postMessage(i2);
})) : u.createSessionFinalize(t2, e2), e.createSession = async (t2, e2) => l() ? (T(), new Promise((n2, r2) => {
_.push([n2, r2]);
const i2 = { type: "create", in: { model: t2, options: e2 } };
p.postMessage(i2, [t2.buffer]);
})) : u.createSession(t2, e2), e.releaseSession = async (t2) => {
if (l())
return T(), new Promise((e2, n2) => {
v.push([e2, n2]);
const r2 = { type: "release", in: t2 };
p.postMessage(r2);
});
u.releaseSession(t2);
}, e.run = async (t2, e2, n2, r2, i2) => l() ? (T(), new Promise((o2, a2) => {
w.push([o2, a2]);
const s2 = { type: "run", in: { sessionId: t2, inputIndices: e2, inputs: n2, outputIndices: r2, options: i2 } };
p.postMessage(s2, u.extractTransferableBuffers(n2));
})) : u.run(t2, e2, n2, r2, i2), e.endProfiling = async (t2) => {
if (l())
return T(), new Promise((e2, n2) => {
x.push([e2, n2]);
const r2 = { type: "end-profiling", in: t2 };
p.postMessage(r2);
});
u.endProfiling(t2);
};
}, 586: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.setRunOptions = void 0;
const r = n(7967), i = n(4983), o = n(6361);
e.setRunOptions = (t2) => {
const e2 = (0, o.getInstance)();
let n2 = 0;
const a = [], s = t2 || {};
try {
if (void 0 === (null == t2 ? void 0 : t2.logSeverityLevel))
s.logSeverityLevel = 2;
else if ("number" != typeof t2.logSeverityLevel || !Number.isInteger(t2.logSeverityLevel) || t2.logSeverityLevel < 0 || t2.logSeverityLevel > 4)
throw new Error(`log serverity level is not valid: ${t2.logSeverityLevel}`);
if (void 0 === (null == t2 ? void 0 : t2.logVerbosityLevel))
s.logVerbosityLevel = 0;
else if ("number" != typeof t2.logVerbosityLevel || !Number.isInteger(t2.logVerbosityLevel))
throw new Error(`log verbosity level is not valid: ${t2.logVerbosityLevel}`);
void 0 === (null == t2 ? void 0 : t2.terminate) && (s.terminate = false);
let o2 = 0;
if (void 0 !== (null == t2 ? void 0 : t2.tag) && (o2 = (0, i.allocWasmString)(t2.tag, a)), n2 = e2._OrtCreateRunOptions(s.logSeverityLevel, s.logVerbosityLevel, !!s.terminate, o2), 0 === n2)
throw new Error("Can't create run options");
return void 0 !== (null == t2 ? void 0 : t2.extra) && (0, r.iterateExtraOptions)(t2.extra, "", /* @__PURE__ */ new WeakSet(), (t3, r2) => {
const o3 = (0, i.allocWasmString)(t3, a), s2 = (0, i.allocWasmString)(r2, a);
if (0 !== e2._OrtAddRunConfigEntry(n2, o3, s2))
throw new Error(`Can't set a run config entry: ${t3} - ${r2}`);
}), [n2, a];
} catch (t3) {
throw 0 !== n2 && e2._OrtReleaseRunOptions(n2), a.forEach(e2._free), t3;
}
};
}, 2306: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.OnnxruntimeWebAssemblySessionHandler = void 0;
const r = n(2806), i = n(1670), o = n(2850), a = n(2157);
let s;
e.OnnxruntimeWebAssemblySessionHandler = class {
async createSessionAllocate(t2) {
const e2 = await fetch(t2), n2 = await e2.arrayBuffer();
return (0, a.createSessionAllocate)(new Uint8Array(n2));
}
async loadModel(t2, e2) {
if (s || (await (0, a.initOrt)(i.env.wasm.numThreads, ((t3) => {
switch (t3) {
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: ${t3}`);
}
})(i.env.logLevel)), s = true), "string" == typeof t2)
if ("undefined" == typeof fetch) {
const n2 = await (0, o.promisify)(r.readFile)(t2);
[this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSession)(n2, e2);
} else {
const n2 = await this.createSessionAllocate(t2);
[this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSessionFinalize)(n2, e2);
}
else
[this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSession)(t2, e2);
}
async dispose() {
return (0, a.releaseSession)(this.sessionId);
}
async run(t2, e2, n2) {
const r2 = [], o2 = [];
Object.entries(t2).forEach((t3) => {
const e3 = t3[0], n3 = t3[1], i2 = this.inputNames.indexOf(e3);
if (-1 === i2)
throw new Error(`invalid input '${e3}'`);
r2.push(n3), o2.push(i2);
});
const s2 = [];
Object.entries(e2).forEach((t3) => {
const e3 = t3[0], n3 = this.outputNames.indexOf(e3);
if (-1 === n3)
throw new Error(`invalid output '${e3}'`);
s2.push(n3);
});
const u = await (0, a.run)(this.sessionId, o2, r2.map((t3) => [t3.type, t3.dims, t3.data]), s2, n2), c = {};
for (let t3 = 0; t3 < u.length; t3++)
c[this.outputNames[s2[t3]]] = new i.Tensor(u[t3][0], u[t3][2], u[t3][1]);
return c;
}
startProfiling() {
}
endProfiling() {
(0, a.endProfiling)(this.sessionId);
}
};
}, 4919: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.setSessionOptions = void 0;
const r = n(7967), i = n(4983), o = n(6361);
e.setSessionOptions = (t2) => {
const e2 = (0, o.getInstance)();
let n2 = 0;
const a = [], s = t2 || {};
((t3) => {
t3.extra || (t3.extra = {}), t3.extra.session || (t3.extra.session = {});
const e3 = t3.extra.session;
e3.use_ort_model_bytes_directly || (e3.use_ort_model_bytes_directly = "1");
})(s);
try {
void 0 === (null == t2 ? void 0 : t2.graphOptimizationLevel) && (s.graphOptimizationLevel = "all");
const u = ((t3) => {
switch (t3) {
case "disabled":
return 0;
case "basic":
return 1;
case "extended":
return 2;
case "all":
return 99;
default:
throw new Error(`unsupported graph optimization level: ${t3}`);
}
})(s.graphOptimizationLevel);
void 0 === (null == t2 ? void 0 : t2.enableCpuMemArena) && (s.enableCpuMemArena = true), void 0 === (null == t2 ? void 0 : t2.enableMemPattern) && (s.enableMemPattern = true), void 0 === (null == t2 ? void 0 : t2.executionMode) && (s.executionMode = "sequential");
const c = ((t3) => {
switch (t3) {
case "sequential":
return 0;
case "parallel":
return 1;
default:
throw new Error(`unsupported execution mode: ${t3}`);
}
})(s.executionMode);
let l = 0;
if (void 0 !== (null == t2 ? void 0 : t2.logId) && (l = (0, i.allocWasmString)(t2.logId, a)), void 0 === (null == t2 ? void 0 : t2.logSeverityLevel))
s.logSeverityLevel = 2;
else if ("number" != typeof t2.logSeverityLevel || !Number.isInteger(t2.logSeverityLevel) || t2.logSeverityLevel < 0 || t2.logSeverityLevel > 4)
throw new Error(`log serverity level is not valid: ${t2.logSeverityLevel}`);
if (void 0 === (null == t2 ? void 0 : t2.logVerbosityLevel))
s.logVerbosityLevel = 0;
else if ("number" != typeof t2.logVerbosityLevel || !Number.isInteger(t2.logVerbosityLevel))
throw new Error(`log verbosity level is not valid: ${t2.logVerbosityLevel}`);
if (void 0 === (null == t2 ? void 0 : t2.enableProfiling) && (s.enableProfiling = false), n2 = e2._OrtCreateSessionOptions(u, !!s.enableCpuMemArena, !!s.enableMemPattern, c, !!s.enableProfiling, 0, l, s.logSeverityLevel, s.logVerbosityLevel), 0 === n2)
throw new Error("Can't create session options");
return (null == t2 ? void 0 : t2.executionProviders) && ((t3, e3, n3) => {
for (const r2 of e3) {
let e4 = "string" == typeof r2 ? r2 : r2.name;
switch (e4) {
case "xnnpack":
e4 = "XNNPACK";
break;
case "wasm":
case "cpu":
continue;
default:
throw new Error(`not supported EP: ${e4}`);
}
const a2 = (0, i.allocWasmString)(e4, n3);
if (0 !== (0, o.getInstance)()._OrtAppendExecutionProvider(t3, a2))
throw new Error(`Can't append execution provider: ${e4}`);
}
})(n2, t2.executionProviders, a), void 0 !== (null == t2 ? void 0 : t2.extra) && (0, r.iterateExtraOptions)(t2.extra, "", /* @__PURE__ */ new WeakSet(), (t3, r2) => {
const o2 = (0, i.allocWasmString)(t3, a), s2 = (0, i.allocWasmString)(r2, a);
if (0 !== e2._OrtAddSessionConfigEntry(n2, o2, s2))
throw new Error(`Can't set a session config entry: ${t3} - ${r2}`);
}), [n2, a];
} catch (t3) {
throw 0 !== n2 && e2._OrtReleaseSessionOptions(n2), a.forEach(e2._free), t3;
}
};
}, 4983: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), e.allocWasmString = void 0;
const r = n(6361);
e.allocWasmString = (t2, e2) => {
const n2 = (0, r.getInstance)(), i = n2.lengthBytesUTF8(t2) + 1, o = n2._malloc(i);
return n2.stringToUTF8(t2, o, i), e2.push(o), o;
};
}, 349: (t, e, n) => {
"use strict";
Object.defineProperty(e, "__esModule", { value: true }), 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 = (t2, e2) => {
const n2 = (0, a.getInstance)()._OrtInit(t2, e2);
if (0 !== n2)
throw new Error(`Can't initialize onnxruntime. error code = ${n2}`);
};
const s = /* @__PURE__ */ new Map();
e.createSessionAllocate = (t2) => {
const e2 = (0, a.getInstance)(), n2 = e2._malloc(t2.byteLength);
return e2.HEAPU8.set(t2, n2), [n2, t2.byteLength];
}, e.createSessionFinalize = (t2, e2) => {
const n2 = (0, a.getInstance)();
let r2 = 0, o2 = 0, u2 = [];
try {
if ([o2, u2] = (0, i.setSessionOptions)(e2), r2 = n2._OrtCreateSession(t2[0], t2[1], o2), 0 === r2)
throw new Error("Can't create a session");
} finally {
n2._free(t2[0]), n2._OrtReleaseSessionOptions(o2), u2.forEach(n2._free);
}
const c2 = n2._OrtGetInputCount(r2), l2 = n2._OrtGetOutputCount(r2), p = [], f = [], d = [], h = [];
for (let t3 = 0; t3 < c2; t3++) {
const e3 = n2._OrtGetInputName(r2, t3);
if (0 === e3)
throw new Error("Can't get an input name");
f.push(e3), p.push(n2.UTF8ToString(e3));
}
for (let t3 = 0; t3 < l2; t3++) {
const e3 = n2._OrtGetOutputName(r2, t3);
if (0 === e3)
throw new Error("Can't get an output name");
h.push(e3), d.push(n2.UTF8ToString(e3));
}
return s.set(r2, [r2, f, h]), [r2, p, d];
}, e.createSession = (t2, n2) => {
const r2 = (0, e.createSessionAllocate)(t2);
return (0, e.createSessionFinalize)(r2, n2);
}, e.releaseSession = (t2) => {
const e2 = (0, a.getInstance)(), n2 = s.get(t2);
if (!n2)
throw new Error("invalid session id");
const r2 = n2[0], i2 = n2[1], o2 = n2[2];
i2.forEach(e2._OrtFree), o2.forEach(e2._OrtFree), e2._OrtReleaseSession(r2), s.delete(t2);
};
const u = (t2) => {
switch (t2) {
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: ${t2}`);
}
}, c = (t2) => {
switch (t2) {
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: ${t2}`);
}
}, l = (t2) => {
switch (t2) {
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: ${t2}`);
}
};
e.run = (t2, e2, n2, i2, p) => {
const f = (0, a.getInstance)(), d = s.get(t2);
if (!d)
throw new Error("invalid session id");
const h = d[0], g = d[1], b = d[2], m = e2.length, y = i2.length;
let _ = 0, v = [];
const w = [], x = [];
try {
[_, v] = (0, r.setRunOptions)(p);
for (let t4 = 0; t4 < m; t4++) {
const e3 = n2[t4][0], r2 = n2[t4][1], i3 = n2[t4][2];
let a3, s3;
if (Array.isArray(i3)) {
s3 = 4 * i3.length, a3 = f._malloc(s3), x.push(a3);
let t5 = a3 / 4;
for (let e4 = 0; e4 < i3.length; e4++) {
if ("string" != typeof i3[e4])
throw new TypeError(`tensor data at index ${e4} is not a string`);
f.HEAPU32[t5++] = (0, o.allocWasmString)(i3[e4], x);
}
} else
s3 = i3.byteLength, a3 = f._malloc(s3), x.push(a3), f.HEAPU8.set(new Uint8Array(i3.buffer, i3.byteOffset, s3), a3);
const c2 = f.stackSave(), l2 = f.stackAlloc(4 * r2.length);
try {
let t5 = l2 / 4;
r2.forEach((e4) => f.HEAP32[t5++] = e4);
const n3 = f._OrtCreateTensor(u(e3), a3, s3, l2, r2.length);
if (0 === n3)
throw new Error("Can't create a tensor");
w.push(n3);
} finally {
f.stackRestore(c2);
}
}
const t3 = f.stackSave(), a2 = f.stackAlloc(4 * m), s2 = f.stackAlloc(4 * m), d2 = f.stackAlloc(4 * y), T = f.stackAlloc(4 * y);
try {
let n3 = a2 / 4, r2 = s2 / 4, o2 = d2 / 4, u2 = T / 4;
for (let t4 = 0; t4 < m; t4++)
f.HEAPU32[n3++] = w[t4], f.HEAPU32[r2++] = g[e2[t4]];
for (let t4 = 0; t4 < y; t4++)
f.HEAPU32[o2++] = 0, f.HEAPU32[u2++] = b[i2[t4]];
let p2 = f._OrtRun(h, s2, a2, m, T, y, d2, _);
const v2 = [];
if (0 === p2)
for (let t4 = 0; t4 < y; t4++) {
const e3 = f.HEAPU32[d2 / 4 + t4], n4 = f.stackSave(), r3 = f.stackAlloc(16);
let i3, o3 = 0;
try {
if (p2 = f._OrtGetTensorData(e3, r3, r3 + 4, r3 + 8, r3 + 12), 0 !== p2)
throw new Error(`Can't access output tensor data. error code = ${p2}`);
let t5 = r3 / 4;
const a3 = f.HEAPU32[t5++];
o3 = f.HEAPU32[t5++];
const s3 = f.HEAPU32[t5++], u3 = f.HEAPU32[t5++], d3 = [];
for (let t6 = 0; t6 < u3; t6++)
d3.push(f.HEAPU32[s3 / 4 + t6]);
f._OrtFree(s3);
const h2 = 0 === d3.length ? 1 : d3.reduce((t6, e4) => t6 * e4);
if (i3 = c(a3), "string" === i3) {
const t6 = [];
let e4 = o3 / 4;
for (let n5 = 0; n5 < h2; n5++) {
const r4 = f.HEAPU32[e4++], i4 = n5 === h2 - 1 ? void 0 : f.HEAPU32[e4] - r4;
t6.push(f.UTF8ToString(r4, i4));
}
v2.push([i3, d3, t6]);
} else {
const t6 = new (l(i3))(h2);
new Uint8Array(t6.buffer, t6.byteOffset, t6.byteLength).set(f.HEAPU8.subarray(o3, o3 + t6.byteLength)), v2.push([i3, d3, t6]);
}
} finally {
f.stackRestore(n4), "string" === i3 && o3 && f._free(o3), f._OrtReleaseTensor(e3);
}
}
if (0 === p2)
return v2;
throw new Error(`failed to call OrtRun(). error code = ${p2}.`);
} finally {
f.stackRestore(t3);
}
} finally {
w.forEach(f._OrtReleaseTensor), x.forEach(f._free), f._OrtReleaseRunOptions(_), v.forEach(f._free);
}
}, e.endProfiling = (t2) => {
const e2 = (0, a.getInstance)(), n2 = s.get(t2);
if (!n2)
throw new Error("invalid session id");
const r2 = n2[0], i2 = e2._OrtEndProfiling(r2);
if (0 === i2)
throw new Error("Can't get an profile file name");
e2._OrtFree(i2);
}, e.extractTransferableBuffers = (t2) => {
const e2 = [];
for (const n2 of t2) {
const t3 = n2[2];
!Array.isArray(t3) && t3.buffer && e2.push(t3.buffer);
}
return e2;
};
}, 6361: function(t, e, n) {
"use strict";
var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) {
void 0 === r2 && (r2 = n2);
var i2 = Object.getOwnPropertyDescriptor(e2, n2);
i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() {
return e2[n2];
} }), Object.defineProperty(t2, r2, i2);
} : function(t2, e2, n2, r2) {
void 0 === r2 && (r2 = n2), t2[r2] = e2[n2];
}), i = this && this.__setModuleDefault || (Object.create ? function(t2, e2) {
Object.defineProperty(t2, "default", { enumerable: true, value: e2 });
} : function(t2, e2) {
t2.default = e2;
}), o = this && this.__importStar || function(t2) {
if (t2 && t2.__esModule)
return t2;
var e2 = {};
if (null != t2)
for (var n2 in t2)
"default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2);
return i(e2, t2), e2;
}, a = this && this.__importDefault || function(t2) {
return t2 && t2.__esModule ? t2 : { default: t2 };
};
Object.defineProperty(e, "__esModule", { value: true }), e.dispose = e.getInstance = e.initializeWebAssembly = void 0;
const s = o(n(6449)), u = a(n(932)), c = n(3474);
let l, p = false, f = false, d = false;
const h = (t2, e2) => e2 ? t2 ? "ort-wasm-simd-threaded.wasm" : "ort-wasm-threaded.wasm" : t2 ? "ort-wasm-simd.wasm" : "ort-wasm.wasm";
e.initializeWebAssembly = async (t2) => {
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 = true;
const e2 = t2.initTimeout, r2 = t2.numThreads, i2 = t2.simd, o2 = r2 > 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 (t3) {
return false;
}
})(), a2 = i2 && (() => {
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 (t3) {
return false;
}
})(), g = "string" == typeof t2.wasmPaths ? t2.wasmPaths : void 0, b = h(false, o2), m = h(a2, o2), y = "object" == typeof t2.wasmPaths ? t2.wasmPaths[m] : void 0;
let _ = false;
const v = [];
if (e2 > 0 && v.push(new Promise((t3) => {
setTimeout(() => {
_ = true, t3();
}, e2);
})), v.push(new Promise((t3, e3) => {
const r3 = o2 ? c : u.default, i3 = { locateFile: (t4, e4) => o2 && t4.endsWith(".worker.js") && "undefined" != typeof Blob ? URL.createObjectURL(new Blob([n(4154)], { type: "text/javascript" })) : t4 === b ? null != y ? y : (null != g ? g : e4) + m : e4 + t4 };
if (o2)
if ("undefined" == typeof Blob)
i3.mainScriptUrlOrBlob = s.join("/", "ort-wasm-threaded.js");
else {
const t4 = `var ortWasmThreaded=(function(){var _scriptDir;return ${r3.toString()}})();`;
i3.mainScriptUrlOrBlob = new Blob([t4], { type: "text/javascript" });
}
r3(i3).then((e4) => {
f = false, p = true, l = e4, t3();
}, (t4) => {
f = false, d = true, e3(t4);
});
})), await Promise.race(v), _)
throw new Error(`WebAssembly backend initializing failed due to timeout: ${e2}ms`);
}, e.getInstance = () => {
if (p && l)
return l;
throw new Error("WebAssembly is not initialized yet.");
}, e.dispose = () => {
var t2;
!p || f || d || (f = true, null === (t2 = l.PThread) || void 0 === t2 || t2.terminateAllThreads(), l = void 0, f = false, p = false, d = true);
};
}, 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&&false,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&&false,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&&false;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(t2, e, n, r) {
var i = self || window;
try {
try {
var o;
try {
o = new i.Blob([t2]);
} catch (e2) {
(o = new (i.BlobBuilder || i.WebKitBlobBuilder || i.MozBlobBuilder || i.MSBlobBuilder)()).append(t2), 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 (r2) {
return new i[e]("data:application/javascript,".concat(encodeURIComponent(t2)), n);
}
} catch (t3) {
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&&false;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(t2, e2) {
this.low = 0 | t2, this.high = 0 | e2;
}, r.Long.create = function(t2, e2) {
return 0 == t2 && 0 == e2 ? r.Long.ZERO : new r.Long(t2, e2);
}, r.Long.prototype.toFloat64 = function() {
return (this.low >>> 0) + 4294967296 * this.high;
}, r.Long.prototype.equals = function(t2) {
return this.low == t2.low && this.high == t2.high;
}, r.Long.ZERO = new r.Long(0, 0), r.Builder = function(t2) {
if (t2)
e2 = t2;
else
var e2 = 1024;
this.bb = r.ByteBuffer.allocate(e2), this.space = e2, this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false;
}, 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 = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false;
}, r.Builder.prototype.forceDefaults = function(t2) {
this.force_defaults = t2;
}, 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(t2, e2) {
t2 > this.minalign && (this.minalign = t2);
for (var n2 = 1 + ~(this.bb.capacity() - this.space + e2) & t2 - 1; this.space < n2 + t2 + e2; ) {
var i = this.bb.capacity();
this.bb = r.Builder.growByteBuffer(this.bb), this.space += this.bb.capacity() - i;
}
this.pad(n2);
}, r.Builder.prototype.pad = function(t2) {
for (var e2 = 0; e2 < t2; e2++)
this.bb.writeInt8(--this.space, 0);
}, r.Builder.prototype.writeInt8 = function(t2) {
this.bb.writeInt8(this.space -= 1, t2);
}, r.Builder.prototype.writeInt16 = function(t2) {
this.bb.writeInt16(this.space -= 2, t2);
}, r.Builder.prototype.writeInt32 = function(t2) {
this.bb.writeInt32(this.space -= 4, t2);
}, r.Builder.prototype.writeInt64 = function(t2) {
this.bb.writeInt64(this.space -= 8, t2);
}, r.Builder.prototype.writeFloat32 = function(t2) {
this.bb.writeFloat32(this.space -= 4, t2);
}, r.Builder.prototype.writeFloat64 = function(t2) {
this.bb.writeFloat64(this.space -= 8, t2);
}, r.Builder.prototype.addInt8 = function(t2) {
this.prep(1, 0), this.writeInt8(t2);
}, r.Builder.prototype.addInt16 = function(t2) {
this.prep(2, 0), this.writeInt16(t2);
}, r.Builder.prototype.addInt32 = function(t2) {
this.prep(4, 0), this.writeInt32(t2);
}, r.Builder.prototype.addInt64 = function(t2) {
this.prep(8, 0), this.writeInt64(t2);
}, r.Builder.prototype.addFloat32 = function(t2) {
this.prep(4, 0), this.writeFloat32(t2);
}, r.Builder.prototype.addFloat64 = function(t2) {
this.prep(8, 0), this.writeFloat64(t2);
}, r.Builder.prototype.addFieldInt8 = function(t2, e2, n2) {
(this.force_defaults || e2 != n2) && (this.addInt8(e2), this.slot(t2));
}, r.Builder.prototype.addFieldInt16 = function(t2, e2, n2) {
(this.force_defaults || e2 != n2) && (this.addInt16(e2), this.slot(t2));
}, r.Builder.prototype.addFieldInt32 = function(t2, e2, n2) {
(this.force_defaults || e2 != n2) && (this.addInt32(e2), this.slot(t2));
}, r.Builder.prototype.addFieldInt64 = function(t2, e2, n2) {
!this.force_defaults && e2.equals(n2) || (this.addInt64(e2), this.slot(t2));
}, r.Builder.prototype.addFieldFloat32 = function(t2, e2, n2) {
(this.force_defaults || e2 != n2) && (this.addFloat32(e2), this.slot(t2));
}, r.Builder.prototype.addFieldFloat64 = function(t2, e2, n2) {
(this.force_defaults || e2 != n2) && (this.addFloat64(e2), this.slot(t2));
}, r.Builder.prototype.addFieldOffset = function(t2, e2, n2) {
(this.force_defaults || e2 != n2) && (this.addOffset(e2), this.slot(t2));
}, r.Builder.prototype.addFieldStruct = function(t2, e2, n2) {
e2 != n2 && (this.nested(e2), this.slot(t2));
}, r.Builder.prototype.nested = function(t2) {
if (t2 != 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(t2) {
this.vtable[t2] = this.offset();
}, r.Builder.prototype.offset = function() {
return this.bb.capacity() - this.space;
}, r.Builder.growByteBuffer = function(t2) {
var e2 = t2.capacity();
if (3221225472 & e2)
throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
var n2 = e2 << 1, i = r.ByteBuffer.allocate(n2);
return i.setPosition(n2 - e2), i.bytes().set(t2.bytes(), n2 - e2), i;
}, r.Builder.prototype.addOffset = function(t2) {
this.prep(r.SIZEOF_INT, 0), this.writeInt32(this.offset() - t2 + r.SIZEOF_INT);
}, r.Builder.prototype.startObject = function(t2) {
this.notNested(), null == this.vtable && (this.vtable = []), this.vtable_in_use = t2;
for (var e2 = 0; e2 < t2; e2++)
this.vtable[e2] = 0;
this.isNested = true, 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 t2 = this.offset(), e2 = this.vtable_in_use - 1; e2 >= 0 && 0 == this.vtable[e2]; e2--)
;
for (var n2 = e2 + 1; e2 >= 0; e2--)
this.addInt16(0 != this.vtable[e2] ? t2 - this.vtable[e2] : 0);
this.addInt16(t2 - this.object_start);
var i = (n2 + 2) * r.SIZEOF_SHORT;
this.addInt16(i);
var o = 0, a = this.space;
t:
for (e2 = 0; e2 < this.vtables.length; e2++) {
var s = this.bb.capacity() - this.vtables[e2];
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[e2];
break;
}
}
return o ? (this.space = this.bb.capacity() - t2, this.bb.writeInt32(this.space, o - t2)) : (this.vtables.push(this.offset()), this.bb.writeInt32(this.bb.capacity() - t2, this.offset() - t2)), this.isNested = false, t2;
}, r.Builder.prototype.finish = function(t2, e2, n2) {
var i = n2 ? r.SIZE_PREFIX_LENGTH : 0;
if (e2) {
var o = e2;
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(t2), i && this.addInt32(this.bb.capacity() - this.space), this.bb.setPosition(this.space);
}, r.Builder.prototype.finishSizePrefixed = function(t2, e2) {
this.finish(t2, e2, true);
}, r.Builder.prototype.requiredField = function(t2, e2) {
var n2 = this.bb.capacity() - t2, r2 = n2 - this.bb.readInt32(n2);
if (0 == this.bb.readInt16(r2 + e2))
throw new Error("FlatBuffers: field " + e2 + " must be set");
}, r.Builder.prototype.startVector = function(t2, e2, n2) {
this.notNested(), this.vector_num_elems = e2, this.prep(r.SIZEOF_INT, t2 * e2), this.prep(n2, t2 * e2);
}, r.Builder.prototype.endVector = function() {
return this.writeInt32(this.vector_num_elems), this.offset();
}, r.Builder.prototype.createString = function(t2) {
if (t2 instanceof Uint8Array)
var e2 = t2;
else {
e2 = [];
for (var n2 = 0; n2 < t2.length; ) {
var r2, i = t2.charCodeAt(n2++);
(r2 = i < 55296 || i >= 56320 ? i : (i << 10) + t2.charCodeAt(n2++) + -56613888) < 128 ? e2.push(r2) : (r2 < 2048 ? e2.push(r2 >> 6 & 31 | 192) : (r2 < 65536 ? e2.push(r2 >> 12 & 15 | 224) : e2.push(r2 >> 18 & 7 | 240, r2 >> 12 & 63 | 128), e2.push(r2 >> 6 & 63 | 128)), e2.push(63 & r2 | 128));
}
}
this.addInt8(0), this.startVector(1, e2.length, 1), this.bb.setPosition(this.space -= e2.length), n2 = 0;
for (var o = this.space, a = this.bb.bytes(); n2 < e2.length; n2++)
a[o++] = e2[n2];
return this.endVector();
}, r.Builder.prototype.createLong = function(t2, e2) {
return r.Long.create(t2, e2);
}, r.ByteBuffer = function(t2) {
this.bytes_ = t2, this.position_ = 0;
}, r.ByteBuffer.allocate = function(t2) {
return new r.ByteBuffer(new Uint8Array(t2));
}, 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(t2) {
this.position_ = t2;
}, r.ByteBuffer.prototype.capacity = function() {
return this.bytes_.length;
}, r.ByteBuffer.prototype.readInt8 = function(t2) {
return this.readUint8(t2) << 24 >> 24;
}, r.ByteBuffer.prototype.readUint8 = function(t2) {
return this.bytes_[t2];
}, r.ByteBuffer.prototype.readInt16 = function(t2) {
return this.readUint16(t2) << 16 >> 16;
}, r.ByteBuffer.prototype.readUint16 = function(t2) {
return this.bytes_[t2] | this.bytes_[t2 + 1] << 8;
}, r.ByteBuffer.prototype.readInt32 = function(t2) {
return this.bytes_[t2] | this.bytes_[t2 + 1] << 8 | this.bytes_[t2 + 2] << 16 | this.bytes_[t2 + 3] << 24;
}, r.ByteBuffer.prototype.readUint32 = function(t2) {
return this.readInt32(t2) >>> 0;
}, r.ByteBuffer.prototype.readInt64 = function(t2) {
return new r.Long(this.readInt32(t2), this.readInt32(t2 + 4));
}, r.ByteBuffer.prototype.readUint64 = function(t2) {
return new r.Long(this.readUint32(t2), this.readUint32(t2 + 4));
}, r.ByteBuffer.prototype.readFloat32 = function(t2) {
return r.int32[0] = this.readInt32(t2), r.float32[0];
}, r.ByteBuffer.prototype.readFloat64 = function(t2) {
return r.int32[r.isLittleEndian ? 0 : 1] = this.readInt32(t2), r.int32[r.isLittleEndian ? 1 : 0] = this.readInt32(t2 + 4), r.float64[0];
}, r.ByteBuffer.prototype.writeInt8 = function(t2, e2) {
this.bytes_[t2] = e2;
}, r.ByteBuffer.prototype.writeUint8 = function(t2, e2) {
this.bytes_[t2] = e2;
}, r.ByteBuffer.prototype.writeInt16 = function(t2, e2) {
this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8;
}, r.ByteBuffer.prototype.writeUint16 = function(t2, e2) {
this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8;
}, r.ByteBuffer.prototype.writeInt32 = function(t2, e2) {
this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8, this.bytes_[t2 + 2] = e2 >> 16, this.bytes_[t2 + 3] = e2 >> 24;
}, r.ByteBuffer.prototype.writeUint32 = function(t2, e2) {
this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8, this.bytes_[t2 + 2] = e2 >> 16, this.bytes_[t2 + 3] = e2 >> 24;
}, r.ByteBuffer.prototype.writeInt64 = function(t2, e2) {
this.writeInt32(t2, e2.low), this.writeInt32(t2 + 4, e2.high);
}, r.ByteBuffer.prototype.writeUint64 = function(t2, e2) {
this.writeUint32(t2, e2.low), this.writeUint32(t2 + 4, e2.high);
}, r.ByteBuffer.prototype.writeFloat32 = function(t2, e2) {
r.float32[0] = e2, this.writeInt32(t2, r.int32[0]);
}, r.ByteBuffer.prototype.writeFloat64 = function(t2, e2) {
r.float64[0] = e2, this.writeInt32(t2, r.int32[r.isLittleEndian ? 0 : 1]), this.writeInt32(t2 + 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 t2 = "", e2 = 0; e2 < r.FILE_IDENTIFIER_LENGTH; e2++)
t2 += String.fromCharCode(this.readInt8(this.position_ + r.SIZEOF_INT + e2));
return t2;
}, r.ByteBuffer.prototype.__offset = function(t2, e2) {
var n2 = t2 - this.readInt32(t2);
return e2 < this.readInt16(n2) ? this.readInt16(n2 + e2) : 0;
}, r.ByteBuffer.prototype.__union = function(t2, e2) {
return t2.bb_pos = e2 + this.readInt32(e2), t2.bb = this, t2;
}, r.ByteBuffer.prototype.__string = function(t2, e2) {
t2 += this.readInt32(t2);
var n2 = this.readInt32(t2), i = "", o = 0;
if (t2 += r.SIZEOF_INT, e2 === r.Encoding.UTF8_BYTES)
return this.bytes_.subarray(t2, t2 + n2);
for (; o < n2; ) {
var a, s = this.readUint8(t2 + o++);
if (s < 192)
a = s;
else {
var u = this.readUint8(t2 + o++);
if (s < 224)
a = (31 & s) << 6 | 63 & u;
else {
var c = this.readUint8(t2 + o++);
a = s < 240 ? (15 & s) << 12 | (63 & u) << 6 | 63 & c : (7 & s) << 18 | (63 & u) << 12 | (63 & c) << 6 | 63 & this.readUint8(t2 + 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(t2) {
return t2 + this.readInt32(t2);
}, r.ByteBuffer.prototype.__vector = function(t2) {
return t2 + this.readInt32(t2) + r.SIZEOF_INT;
}, r.ByteBuffer.prototype.__vector_len = function(t2) {
return this.readInt32(t2 + this.readInt32(t2));
}, r.ByteBuffer.prototype.__has_identifier = function(t2) {
if (t2.length != r.FILE_IDENTIFIER_LENGTH)
throw new Error("FlatBuffers: file identifier must be length " + r.FILE_IDENTIFIER_LENGTH);
for (var e2 = 0; e2 < r.FILE_IDENTIFIER_LENGTH; e2++)
if (t2.charCodeAt(e2) != this.readInt8(this.position_ + r.SIZEOF_INT + e2))
return false;
return true;
}, r.ByteBuffer.prototype.createLong = function(t2, e2) {
return r.Long.create(t2, e2);
};
} }, __webpack_module_cache__ = {};
function __webpack_require__(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, __webpack_require__), n.exports;
}
__webpack_require__.n = (t) => {
var e = t && t.__esModule ? () => t.default : () => t;
return __webpack_require__.d(e, { a: e }), e;
}, __webpack_require__.d = (t, e) => {
for (var n in e)
__webpack_require__.o(e, n) && !__webpack_require__.o(t, n) && Object.defineProperty(t, n, { enumerable: true, get: e[n] });
}, __webpack_require__.g = function() {
if ("object" == typeof globalThis)
return globalThis;
try {
return this || new Function("return this")();
} catch (t) {
if ("object" == typeof window)
return window;
}
}(), __webpack_require__.o = (t, e) => Object.prototype.hasOwnProperty.call(t, e), __webpack_require__.r = (t) => {
"undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: true });
};
var __webpack_exports__ = __webpack_require__(6018);
return __webpack_exports__;
})());
}
});
// node_modules/@xenova/transformers/src/backends/onnx.js
var ONNX_NODE, ONNX_WEB, ONNX, executionProviders;
var init_onnx = __esm({
"node_modules/@xenova/transformers/src/backends/onnx.js"() {
ONNX_NODE = __toESM(require_onnxruntime_node(), 1);
ONNX_WEB = __toESM(require_ort_web_min(), 1);
executionProviders = [
// 'webgpu',
"wasm"
];
if (typeof process !== "undefined" && false) {
ONNX = ONNX_NODE.default ?? ONNX_NODE;
executionProviders.unshift("cpu");
} else {
ONNX = ONNX_WEB.default ?? ONNX_WEB;
const isIOS = typeof navigator !== "undefined" && /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);
if (isIOS) {
ONNX.env.wasm.simd = false;
}
}
}
});
// node_modules/@xenova/transformers/src/env.js
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
var import_fs, import_path, import_url, onnx_env, VERSION, WEB_CACHE_AVAILABLE, FS_AVAILABLE, PATH_AVAILABLE, RUNNING_LOCALLY, __dirname, DEFAULT_CACHE_DIR, DEFAULT_LOCAL_MODEL_PATH, localModelPath, env;
var init_env = __esm({
"node_modules/@xenova/transformers/src/env.js"() {
import_fs = __toESM(require("fs"), 1);
import_path = __toESM(require("path"), 1);
import_url = __toESM(require("url"), 1);
init_onnx();
({ env: onnx_env } = ONNX);
VERSION = "2.17.2";
WEB_CACHE_AVAILABLE = typeof self !== "undefined" && "caches" in self;
FS_AVAILABLE = !isEmpty(import_fs.default);
PATH_AVAILABLE = !isEmpty(import_path.default);
RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE;
__dirname = RUNNING_LOCALLY ? import_path.default.dirname(import_path.default.dirname(import_url.default.fileURLToPath("file:///obsidian-bundle.js"))) : "./";
DEFAULT_CACHE_DIR = RUNNING_LOCALLY ? import_path.default.join(__dirname, "/.cache/") : null;
DEFAULT_LOCAL_MODEL_PATH = "/models/";
localModelPath = RUNNING_LOCALLY ? import_path.default.join(__dirname, DEFAULT_LOCAL_MODEL_PATH) : DEFAULT_LOCAL_MODEL_PATH;
if (onnx_env?.wasm) {
onnx_env.wasm.wasmPaths = RUNNING_LOCALLY ? import_path.default.join(__dirname, "/dist/") : `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;
}
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,
useFS: FS_AVAILABLE,
/////////////////// Cache settings ///////////////////
useBrowserCache: WEB_CACHE_AVAILABLE,
useFSCache: FS_AVAILABLE,
cacheDir: DEFAULT_CACHE_DIR,
useCustomCache: false,
customCache: null
//////////////////////////////////////////////////////
};
}
});
// node_modules/@xenova/transformers/src/utils/hub.js
function isValidUrl(string, protocols = null, validHosts = null) {
let url2;
try {
url2 = new URL(string);
} catch (_) {
return false;
}
if (protocols && !protocols.includes(url2.protocol)) {
return false;
}
if (validHosts && !validHosts.includes(url2.hostname)) {
return false;
}
return true;
}
async function getFile(urlOrPath) {
if (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.version;
const headers = new Headers();
headers.set("User-Agent", `transformers.js/${version}; is_ci/${IS_CI};`);
const isHFURL = isValidUrl(urlOrPath, ["http:", "https:"], ["huggingface.co", "hf.co"]);
if (isHFURL) {
const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;
if (token) {
headers.set("Authorization", `Bearer ${token}`);
}
}
return fetch(urlOrPath, { headers });
} else {
return fetch(urlOrPath);
}
}
function handleError(status, remoteURL, fatal) {
if (!fatal) {
return null;
}
const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`;
throw Error(`${message}: "${remoteURL}".`);
}
async function tryCache(cache, ...names) {
for (let name2 of names) {
try {
let result = await cache.match(name2);
if (result)
return result;
} catch (e) {
continue;
}
}
return void 0;
}
async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) {
if (!env.allowLocalModels) {
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.allowRemoteModels) {
throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.");
}
}
dispatchCallback(options.progress_callback, {
status: "initiate",
name: path_or_repo_id,
file: filename
});
let cache;
if (!cache && env.useBrowserCache) {
if (typeof caches === "undefined") {
throw Error("Browser cache is not available in this environment.");
}
try {
cache = await caches.open("transformers-cache");
} catch (e) {
console.warn("An error occurred while opening the browser cache:", e);
}
}
if (!cache && env.useFSCache) {
cache = new FileCache(options.cache_dir ?? env.cacheDir);
}
if (!cache && env.useCustomCache) {
if (!env.customCache) {
throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");
}
if (!env.customCache.match || !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.customCache;
}
const revision = options.revision ?? "main";
let requestURL = pathJoin(path_or_repo_id, filename);
let localPath = pathJoin(env.localModelPath, requestURL);
let remoteURL = pathJoin(
env.remoteHost,
env.remotePathTemplate.replaceAll("{model}", path_or_repo_id).replaceAll("{revision}", encodeURIComponent(revision)),
filename
);
let fsCacheKey = revision === "main" ? requestURL : pathJoin(path_or_repo_id, revision, filename);
let cacheKey;
let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL;
let toCacheResponse = false;
let response;
if (cache) {
response = await tryCache(cache, localPath, proposedCacheKey);
}
const cacheHit = response !== void 0;
if (response === void 0) {
if (env.allowLocalModels) {
const isURL = isValidUrl(requestURL, ["http:", "https:"]);
if (!isURL) {
try {
response = await getFile(localPath);
cacheKey = localPath;
} catch (e) {
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.allowRemoteModels) {
throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.`);
}
}
if (response === void 0 || response.status === 404) {
if (options.local_files_only || !env.allowRemoteModels) {
if (fatal) {
throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`);
} else {
return null;
}
}
response = await getFile(remoteURL);
if (response.status !== 200) {
return handleError(response.status, remoteURL, fatal);
}
cacheKey = proposedCacheKey;
}
toCacheResponse = cache && typeof Response !== "undefined" && response instanceof Response && response.status === 200;
}
dispatchCallback(options.progress_callback, {
status: "download",
name: path_or_repo_id,
file: filename
});
const progressInfo = {
status: "progress",
name: path_or_repo_id,
file: filename
};
let buffer;
if (!options.progress_callback) {
buffer = new Uint8Array(await response.arrayBuffer());
} else if (cacheHit && typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)) {
buffer = new Uint8Array(await response.arrayBuffer());
dispatchCallback(options.progress_callback, {
...progressInfo,
progress: 100,
loaded: buffer.length,
total: buffer.length
});
} else {
buffer = await readResponse(response, (data) => {
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) === void 0
) {
await cache.put(cacheKey, new Response(buffer, {
headers: response.headers
})).catch((err) => {
console.warn(`Unable to add response to browser cache: ${err}.`);
});
}
dispatchCallback(options.progress_callback, {
status: "done",
name: path_or_repo_id,
file: filename
});
return buffer;
}
async function getModelJSON(modelPath, fileName, fatal = true, options = {}) {
let buffer = await getModelFile(modelPath, fileName, fatal, options);
if (buffer === null) {
return {};
}
let decoder = new TextDecoder("utf-8");
let jsonData = decoder.decode(buffer);
return JSON.parse(jsonData);
}
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;
let newBuffer = new Uint8Array(total);
newBuffer.set(buffer);
buffer = newBuffer;
}
buffer.set(value, loaded);
loaded = newLoaded;
const progress = loaded / total * 100;
progress_callback({
progress,
loaded,
total
});
return read();
}
await read();
return buffer;
}
function pathJoin(...parts) {
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("/");
}
var import_fs2, import_path2, FileResponse, ERROR_MAPPING, FileCache;
var init_hub = __esm({
"node_modules/@xenova/transformers/src/utils/hub.js"() {
import_fs2 = __toESM(require("fs"), 1);
import_path2 = __toESM(require("path"), 1);
init_env();
init_core();
FileResponse = class _FileResponse {
/**
* Creates a new `FileResponse` object.
* @param {string|URL} filePath
*/
constructor(filePath) {
/**
* Mapping from file extensions to MIME types.
*/
__publicField(this, "_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"
});
this.filePath = filePath;
this.headers = new Headers();
this.exists = import_fs2.default.existsSync(filePath);
if (this.exists) {
this.status = 200;
this.statusText = "OK";
let stats = import_fs2.default.statSync(filePath);
this.headers.set("content-length", stats.size.toString());
this.updateContentType();
let self2 = this;
this.body = new ReadableStream({
start(controller) {
self2.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() {
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 import_fs2.default.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 import_fs2.default.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 import_fs2.default.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());
}
};
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"
};
FileCache = class {
/**
* Instantiate a `FileCache` object.
* @param {string} path
*/
constructor(path3) {
this.path = path3;
}
/**
* Checks whether the given request is in the cache.
* @param {string} request
* @returns {Promise<FileResponse | undefined>}
*/
async match(request2) {
let filePath = import_path2.default.join(this.path, request2);
let file = new FileResponse(filePath);
if (file.exists) {
return file;
} else {
return void 0;
}
}
/**
* Adds the given response to the cache.
* @param {string} request
* @param {Response|FileResponse} response
* @returns {Promise<void>}
*/
async put(request2, response) {
const buffer = Buffer.from(await response.arrayBuffer());
let outputPath = import_path2.default.join(this.path, request2);
try {
await import_fs2.default.promises.mkdir(import_path2.default.dirname(outputPath), { recursive: true });
await import_fs2.default.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>>;
};
}
});
// node_modules/@xenova/transformers/src/utils/maths.js
function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = "bilinear", align_corners = false) {
const x_scale = out_width / in_width;
const y_scale = out_height / in_height;
const out_img = new input.constructor(out_height * out_width * in_channels);
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) {
const outOffset = i * out_width + j;
const x = (j + 0.5) / x_scale - 0.5;
const y = (i + 0.5) / y_scale - 0.5;
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);
const s = x - x1;
const t = y - y1;
const w1 = (1 - s) * (1 - t);
const w2 = s * (1 - t);
const w3 = (1 - s) * t;
const w4 = s * t;
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) {
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;
}
function permute_data(array, dims, axes) {
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];
}
const invStride = axes.map((_, i) => stride[axes.indexOf(i)]);
const permutedData = new array.constructor(array.length);
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];
}
function softmax(arr) {
const maxVal = max(arr)[0];
const exps = arr.map((x) => Math.exp(x - maxVal));
const sumExps = exps.reduce((acc, val) => acc + val, 0);
const softmaxArr = exps.map((x) => x / sumExps);
return (
/** @type {T} */
softmaxArr
);
}
function log_softmax(arr) {
const softmaxArr = softmax(arr);
const logSoftmaxArr = softmaxArr.map((x) => Math.log(x));
return (
/** @type {T} */
logSoftmaxArr
);
}
function dot(arr1, arr2) {
let result = 0;
for (let i = 0; i < arr1.length; ++i) {
result += arr1[i] * arr2[i];
}
return result;
}
function getTopItems(items, top_k = 0) {
items = Array.from(items).map((x, i) => [i, x]).sort((a, b) => b[1] - a[1]);
if (top_k !== null && top_k > 0) {
items = items.slice(0, top_k);
}
return items;
}
function cos_sim(arr1, arr2) {
const dotProduct = dot(arr1, arr2);
const magnitudeA = magnitude(arr1);
const magnitudeB = magnitude(arr2);
const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB);
return cosineSimilarity;
}
function magnitude(arr) {
return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0));
}
function min(arr) {
if (arr.length === 0)
throw Error("Array must not be empty");
let min2 = arr[0];
let indexOfMin = 0;
for (let i = 1; i < arr.length; ++i) {
if (arr[i] < min2) {
min2 = arr[i];
indexOfMin = i;
}
}
return [min2, indexOfMin];
}
function max(arr) {
if (arr.length === 0)
throw Error("Array must not be empty");
let max2 = arr[0];
let indexOfMax = 0;
for (let i = 1; i < arr.length; ++i) {
if (arr[i] > max2) {
max2 = arr[i];
indexOfMax = i;
}
}
return [Number(max2), indexOfMax];
}
function isPowerOfTwo(number) {
return number > 0 && (number & number - 1) === 0;
}
function medianFilter(data, windowSize) {
if (windowSize % 2 === 0 || windowSize <= 0) {
throw new Error("Window size must be a positive odd number");
}
const outputArray = new data.constructor(data.length);
const buffer = new data.constructor(windowSize);
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;
}
function round(num, decimals) {
const pow = Math.pow(10, decimals);
return Math.round(num * pow) / pow;
}
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;
}
var P2FFT, NP2FFT, FFT;
var init_maths = __esm({
"node_modules/@xenova/transformers/src/utils/maths.js"() {
P2FFT = class {
/**
* @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;
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);
}
let power = 0;
for (let t = 1; this.size > t; t <<= 1)
++power;
this._width = power % 2 === 0 ? power - 1 : power;
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) {
const size = this._csize;
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 {
for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
const off = bitrev[t];
this._singleTransform4(data, out, outOff, off, step, inv);
}
}
const table = this.table;
for (step >>= 2; step >= 2; step >>= 2) {
len = size / step << 1;
const quarterLen = len >>> 2;
for (outOff = 0; outOff < size; outOff += len) {
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;
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;
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);
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) {
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) {
const step2 = step * 2;
const step3 = step * 3;
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];
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);
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) {
const size = this._csize;
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 {
for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
const off = bitrev[t];
this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv);
}
}
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;
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;
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 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;
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);
out[A] = T0r + T2r;
out[A + 1] = T0i + T2i;
out[B] = T1r + T3i;
out[B + 1] = T1i - T3r;
if (i === 0) {
out[C] = T0r - T2r;
out[C + 1] = T0i - T2i;
continue;
}
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;
}
}
}
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) {
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) {
const step2 = step * 2;
const step3 = step * 3;
const Ar = data[off];
const Br = data[off + step];
const Cr = data[off + step2];
const Dr = data[off + step3];
const T0r = Ar + Cr;
const T1r = Ar - Cr;
const T2r = Br + Dr;
const T3r = inv * (Br - Dr);
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 {
/**
* Constructs a new NP2FFT object.
* @param {number} fft_length The length of the FFT
*/
constructor(fft_length) {
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;
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);
const theta = -2 * Math.PI / fft_length;
const baseR = Math.cos(theta);
const baseI = Math.sin(theta);
for (let i = 0; i < b >> 1; ++i) {
const e = (i + 1 - fft_length) ** 2 / 2;
const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e;
const result_arg = e * Math.atan2(baseI, baseR);
const i2 = 2 * i;
chirp[i2] = result_mod * Math.cos(result_arg);
chirp[i2 + 1] = result_mod * Math.sin(result_arg);
ichirp[i2] = chirp[i2];
ichirp[i2 + 1] = -chirp[i2 + 1];
}
this._slicedChirpBuffer = chirp.subarray(a, b);
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) {
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 {
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);
}
};
FFT = class {
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);
}
};
}
});
// node_modules/@xenova/transformers/src/utils/tensor.js
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})`);
}
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];
}
function permute(tensor, axes) {
const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes);
return new Tensor(tensor.type, permutedData, shape);
}
function interpolate(input, [out_height, out_width], mode = "bilinear", align_corners = false) {
const in_channels = input.dims.at(-3) ?? 1;
const in_height = input.dims.at(-2);
const in_width = input.dims.at(-1);
let output = 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]);
}
function mean_pooling(last_hidden_state, attention_mask) {
let shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];
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;
for (let j = 0; j < seqLength; ++j) {
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
);
}
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, mean2] = std_mean(input, 1, 0, true);
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] - mean2.data[i]) / (std.data[i] + eps);
}
}
return new Tensor(input.type, returnedData, input.dims);
}
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;
}
function calc_unsqueeze_dims(dims, dim) {
dim = safeIndex(dim, dims.length + 1);
dims = dims.slice();
dims.splice(dim, 0, 1);
return dims;
}
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) {
index = (index % size + size) % size;
}
return index;
}
function cat(tensors, dim = 0) {
dim = safeIndex(dim, tensors[0].dims.length);
const resultDims = tensors[0].dims.slice();
resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);
const resultSize = resultDims.reduce((a, b) => a * b, 1);
const result = new tensors[0].data.constructor(resultSize);
const resultType = tensors[0].type;
if (dim === 0) {
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];
for (let i = 0; i < tensor.data.length; ++i) {
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);
}
result[resultIndex] = tensor.data[i];
}
currentDim += tensor.dims[dim];
}
}
return new Tensor(resultType, result, resultDims);
}
function stack(tensors, dim = 0) {
return cat(tensors.map((t) => t.unsqueeze(dim)), dim);
}
function std_mean(input, dim = null, correction = 1, keepdim = false) {
if (dim === null) {
const sum = input.data.reduce((a, b) => a + b, 0);
const mean2 = sum / input.data.length;
const std = Math.sqrt(input.data.reduce((a, b) => a + (b - mean2) ** 2, 0) / (input.data.length - correction));
const meanTensor2 = new Tensor(input.type, [mean2], [
/* scalar */
]);
const stdTensor2 = new Tensor(input.type, [std], [
/* scalar */
]);
return [stdTensor2, meanTensor2];
}
dim = safeIndex(dim, input.dims.length);
const meanTensor = mean(input, dim, keepdim);
const resultDims = input.dims.slice();
resultDims[dim] = 1;
const result = new input.data.constructor(input.data.length / input.dims[dim]);
for (let i = 0; i < input.data.length; ++i) {
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);
}
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];
}
function mean(input, dim = null, keepdim = false) {
if (dim === null) {
let val = input.data.reduce((a, b) => a + b, 0);
return new Tensor(input.type, [val / input.data.length], [
/* scalar */
]);
}
dim = safeIndex(dim, input.dims.length);
const resultDims = input.dims.slice();
resultDims[dim] = 1;
const result = new input.data.constructor(input.data.length / input.dims[dim]);
for (let i = 0; i < input.data.length; ++i) {
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);
}
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);
}
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
);
cost[0].data[0] = 0;
for (let j2 = 1; j2 < input_length + 1; ++j2) {
for (let i2 = 1; i2 < output_length + 1; ++i2) {
const c0 = cost[i2 - 1][j2 - 1].item();
const c1 = cost[i2 - 1][j2].item();
const c2 = cost[i2][j2 - 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[i2].data[j2] = matrix[i2 - 1][j2 - 1].item() + c;
trace[i2].data[j2] = t;
}
}
let i = output_length;
let j = input_length;
trace.data.fill(2, 0, outputShape[1]);
for (let i2 = 0; i2 < outputShape[0]; ++i2) {
trace[i2].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;
}
function ones(size) {
const numElements = size.reduce((a, b) => a * b, 1);
return new Tensor(
"int64",
new BigInt64Array(numElements).fill(1n),
size
);
}
function ones_like(tensor) {
return ones(tensor.dims);
}
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";
const cls = signed ? Int8Array : Uint8Array;
const inputData = tensor.data;
const outputData = new cls(inputData.length / 8);
for (let i = 0; i < inputData.length; ++i) {
const bit = inputData[i] > 0 ? 1 : 0;
const arrayIndex = Math.floor(i / 8);
const bitPosition = i % 8;
outputData[arrayIndex] |= bit << 7 - bitPosition;
if (signed && bitPosition === 0) {
outputData[arrayIndex] -= 128;
}
}
;
return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]);
}
var DataTypeMap, ONNXTensor, Tensor;
var init_tensor = __esm({
"node_modules/@xenova/transformers/src/utils/tensor.js"() {
init_onnx();
init_maths();
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
});
ONNXTensor = ONNX.Tensor;
Tensor = class _Tensor {
/**
* Create a new Tensor or copy an existing Tensor.
* @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
*/
constructor(...args) {
/** @type {number[]} Dimensions of the tensor. */
__publicField(this, "dims");
/** @type {DataType} Type of the tensor. */
__publicField(this, "type");
/** @type {DataArray} The data stored in the tensor. */
__publicField(this, "data");
/** @type {number} The number of elements in the tensor. */
__publicField(this, "size");
if (args[0] instanceof ONNXTensor) {
Object.assign(this, args[0]);
} else {
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)) {
return obj._getitem(index);
}
}
return obj[key];
},
set: (obj, key, value) => {
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) {
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;
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) {
let newTensorDims = [];
let newOffsets = [];
for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {
let slice2 = slices[sliceIndex];
if (slice2 === null || slice2 === void 0) {
newOffsets.push([0, this.dims[sliceIndex]]);
newTensorDims.push(this.dims[sliceIndex]);
} else if (typeof slice2 === "number") {
slice2 = safeIndex(slice2, this.dims[sliceIndex], sliceIndex);
newOffsets.push([slice2, slice2 + 1]);
} else if (Array.isArray(slice2) && slice2.length === 2) {
if (slice2[0] > slice2[1]) {
throw new Error(`Invalid slice: ${slice2}`);
}
let offsets = [
Math.max(slice2[0], 0),
Math.min(slice2[1], this.dims[sliceIndex])
];
newOffsets.push(offsets);
newTensorDims.push(offsets[1] - offsets[0]);
} else {
throw new Error(`Invalid slice: ${slice2}`);
}
}
let newDims = newOffsets.map(([start, end]) => end - start);
let newBufferSize = newDims.reduce((a, b) => a * b);
let data = new this.data.constructor(newBufferSize);
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") {
p = 2;
} else if (typeof p === "string") {
throw Error(`Unsupported norm: ${p}`);
}
if (dim === null) {
let val = this.data.reduce((a, b) => a + b ** p, 0) ** (1 / p);
return new _Tensor(this.type, [val], []);
}
dim = safeIndex(dim, this.dims.length);
const resultDims = this.dims.slice();
resultDims[dim] = 1;
const result = new this.data.constructor(this.data.length / this.dims[dim]);
for (let i = 0; i < this.data.length; ++i) {
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);
}
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, dim = 1) {
dim = safeIndex(dim, this.dims.length);
const norm = this.norm(p, dim, true);
for (let i = 0; i < this.data.length; ++i) {
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);
}
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, 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) {
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) {
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) {
const productOther = dims.reduce((product2, curr, index) => {
return index !== inferredIndex ? product2 * curr : product2;
}, 1);
dims[inferredIndex] = this.data.length / productOther;
}
return new _Tensor(this.type, this.data, dims);
}
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_(min2, max2) {
for (let i = 0; i < this.data.length; ++i) {
this.data[i] = Math.min(Math.max(this.data[i], min2), max2);
}
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(min2, max2) {
return this.clone().clamp_(min2, max2);
}
/**
* 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 (this.type === type)
return this;
if (!DataTypeMap.hasOwnProperty(type)) {
throw new Error(`Unsupported type: ${type}`);
}
return new _Tensor(type, DataTypeMap[type].from(this.data), this.dims);
}
};
}
});
// node_modules/@xenova/transformers/src/utils/data-structures.js
var PriorityQueue, CharTrie, CharTrieNode, TokenLattice, TokenLatticeNode;
var init_data_structures = __esm({
"node_modules/@xenova/transformers/src/utils/data-structures.js"() {
PriorityQueue = class {
/**
* 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;
}
}
};
CharTrie = class {
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 === void 0) {
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 !== void 0; ++i) {
const ch = text[i];
prefix += ch;
node = node.children.get(ch);
if (node !== void 0 && node.isLeaf) {
yield prefix;
}
}
}
};
CharTrieNode = 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, /* @__PURE__ */ new Map());
}
};
TokenLattice = class {
/**
* 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);
const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 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;
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);
}
};
TokenLatticeNode = 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;
}
/**
* 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;
}
};
}
});
// node_modules/@huggingface/jinja/dist/index.js
function isWord(char) {
return /\w/.test(char);
}
function isInteger(char) {
return /[0-9]/.test(char);
}
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;
}
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;
}
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 ?? (start = 0)) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length);
stop = (stop ?? (stop = array.length)) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length);
} else {
start = (start ?? (start = array.length - 1)) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1);
stop = (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());
}
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}`);
}
}
var TOKEN_TYPES, KEYWORDS, Token, ORDERED_MAPPING_TABLE, ESCAPE_CHARACTERS, Statement, Program, If, For, SetStatement, Expression, MemberExpression, CallExpression, Identifier, Literal, NumericLiteral, StringLiteral, BooleanLiteral, ArrayLiteral, TupleLiteral, ObjectLiteral, BinaryExpression, FilterExpression, TestExpression, UnaryExpression, SliceExpression, KeywordArgumentExpression, RuntimeValue, NumericValue, StringValue, BooleanValue, ObjectValue, ArrayValue, TupleValue, FunctionValue, NullValue, UndefinedValue, Environment, Interpreter, Template;
var init_dist = __esm({
"node_modules/@huggingface/jinja/dist/index.js"() {
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"
});
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
});
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;
}
};
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]
];
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
]);
Statement = class {
constructor() {
__publicField(this, "type", "Statement");
}
};
Program = class extends Statement {
constructor(body) {
super();
__publicField(this, "type", "Program");
this.body = body;
}
};
If = class extends Statement {
constructor(test, body, alternate) {
super();
__publicField(this, "type", "If");
this.test = test;
this.body = body;
this.alternate = alternate;
}
};
For = class extends Statement {
constructor(loopvar, iterable, body) {
super();
__publicField(this, "type", "For");
this.loopvar = loopvar;
this.iterable = iterable;
this.body = body;
}
};
SetStatement = class extends Statement {
constructor(assignee, value) {
super();
__publicField(this, "type", "Set");
this.assignee = assignee;
this.value = value;
}
};
Expression = class extends Statement {
constructor() {
super(...arguments);
__publicField(this, "type", "Expression");
}
};
MemberExpression = class extends Expression {
constructor(object, property, computed) {
super();
__publicField(this, "type", "MemberExpression");
this.object = object;
this.property = property;
this.computed = computed;
}
};
CallExpression = class extends Expression {
constructor(callee, args) {
super();
__publicField(this, "type", "CallExpression");
this.callee = callee;
this.args = args;
}
};
Identifier = class extends Expression {
/**
* @param {string} value The name of the identifier
*/
constructor(value) {
super();
__publicField(this, "type", "Identifier");
this.value = value;
}
};
Literal = class extends Expression {
constructor(value) {
super();
__publicField(this, "type", "Literal");
this.value = value;
}
};
NumericLiteral = class extends Literal {
constructor() {
super(...arguments);
__publicField(this, "type", "NumericLiteral");
}
};
StringLiteral = class extends Literal {
constructor() {
super(...arguments);
__publicField(this, "type", "StringLiteral");
}
};
BooleanLiteral = class extends Literal {
constructor() {
super(...arguments);
__publicField(this, "type", "BooleanLiteral");
}
};
ArrayLiteral = class extends Literal {
constructor() {
super(...arguments);
__publicField(this, "type", "ArrayLiteral");
}
};
TupleLiteral = class extends Literal {
constructor() {
super(...arguments);
__publicField(this, "type", "TupleLiteral");
}
};
ObjectLiteral = class extends Literal {
constructor() {
super(...arguments);
__publicField(this, "type", "ObjectLiteral");
}
};
BinaryExpression = class extends Expression {
constructor(operator, left, right) {
super();
__publicField(this, "type", "BinaryExpression");
this.operator = operator;
this.left = left;
this.right = right;
}
};
FilterExpression = class extends Expression {
constructor(operand, filter) {
super();
__publicField(this, "type", "FilterExpression");
this.operand = operand;
this.filter = filter;
}
};
TestExpression = class extends Expression {
constructor(operand, negate, test) {
super();
__publicField(this, "type", "TestExpression");
this.operand = operand;
this.negate = negate;
this.test = test;
}
};
UnaryExpression = class extends Expression {
constructor(operator, argument) {
super();
__publicField(this, "type", "UnaryExpression");
this.operator = operator;
this.argument = argument;
}
};
SliceExpression = class extends Expression {
constructor(start = void 0, stop = void 0, step = void 0) {
super();
__publicField(this, "type", "SliceExpression");
this.start = start;
this.stop = stop;
this.step = step;
}
};
KeywordArgumentExpression = class extends Expression {
constructor(key, value) {
super();
__publicField(this, "type", "KeywordArgumentExpression");
this.key = key;
this.value = value;
}
};
RuntimeValue = class {
/**
* Creates a new RuntimeValue.
*/
constructor(value = void 0) {
__publicField(this, "type", "RuntimeValue");
__publicField(this, "value");
/**
* A collection of built-in functions for this type.
*/
__publicField(this, "builtins", /* @__PURE__ */ new Map());
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);
}
};
NumericValue = class extends RuntimeValue {
constructor() {
super(...arguments);
__publicField(this, "type", "NumericValue");
}
};
StringValue = class extends RuntimeValue {
constructor() {
super(...arguments);
__publicField(this, "type", "StringValue");
__publicField(this, "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)]
]));
}
};
BooleanValue = class extends RuntimeValue {
constructor() {
super(...arguments);
__publicField(this, "type", "BooleanValue");
}
};
ObjectValue = class extends RuntimeValue {
constructor() {
super(...arguments);
__publicField(this, "type", "ObjectValue");
__publicField(this, "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]))
);
})
]
]));
}
/**
* 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);
}
};
ArrayValue = class extends RuntimeValue {
constructor() {
super(...arguments);
__publicField(this, "type", "ArrayValue");
__publicField(this, "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);
}
};
TupleValue = class extends ArrayValue {
constructor() {
super(...arguments);
__publicField(this, "type", "TupleValue");
}
};
FunctionValue = class extends RuntimeValue {
constructor() {
super(...arguments);
__publicField(this, "type", "FunctionValue");
}
};
NullValue = class extends RuntimeValue {
constructor() {
super(...arguments);
__publicField(this, "type", "NullValue");
}
};
UndefinedValue = class extends RuntimeValue {
constructor() {
super(...arguments);
__publicField(this, "type", "UndefinedValue");
}
};
Environment = class {
constructor(parent) {
/**
* The variables declared in this environment.
*/
__publicField(this, "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.
*/
__publicField(this, "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]
]));
this.parent = parent;
}
/**
* Set the value of a variable in the current environment.
*/
set(name2, value) {
return this.declareVariable(name2, convertToRuntimeValues(value));
}
declareVariable(name2, value) {
if (this.variables.has(name2)) {
throw new SyntaxError(`Variable already declared: ${name2}`);
}
this.variables.set(name2, 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(name2, value) {
this.variables.set(name2, 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(name2) {
if (this.variables.has(name2)) {
return this;
}
if (this.parent) {
return this.parent.resolve(name2);
}
throw new Error(`Unknown variable: ${name2}`);
}
lookupVariable(name2) {
try {
return this.resolve(name2).variables.get(name2) ?? new UndefinedValue();
} catch {
return new UndefinedValue();
}
}
};
Interpreter = class {
constructor(env3) {
__publicField(this, "global");
this.global = env3 ?? 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}`);
}
}
};
Template = class {
/**
* @param {string} template The template string
*/
constructor(template) {
__publicField(this, "parsed");
const tokens = tokenize(template, {
lstrip_blocks: true,
trim_blocks: true
});
this.parsed = parse(tokens);
}
render(items) {
const env3 = new Environment();
env3.set("false", false);
env3.set("true", true);
env3.set("raise_exception", (args) => {
throw new Error(args);
});
env3.set("range", range);
for (const [key, value] of Object.entries(items)) {
env3.set(key, value);
}
const interpreter = new Interpreter(env3);
const result = interpreter.run(this.parsed);
return result.value;
}
};
}
});
// node_modules/@xenova/transformers/src/tokenizers.js
async function loadTokenizer(pretrained_model_name_or_path, options) {
const info = await Promise.all([
getModelJSON(pretrained_model_name_or_path, "tokenizer.json", true, options),
getModelJSON(pretrained_model_name_or_path, "tokenizer_config.json", true, options)
]);
if (options.legacy !== null) {
info[1].legacy = options.legacy;
}
return info;
}
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;
}
function createPattern(pattern, invert = true) {
if (pattern.Regex !== void 0) {
let regex = pattern.Regex.replace(/\\([#&~])/g, "$1");
for (const [key, value] of PROBLEMATIC_REGEX_MAP) {
regex = regex.replaceAll(key, value);
}
return new RegExp(regex, "gu");
} else if (pattern.String !== void 0) {
const escaped = escapeRegExp(pattern.String);
return new RegExp(invert ? escaped : `(${escaped})`, "gu");
} else {
console.warn("Unknown pattern type:", pattern);
return null;
}
}
function objectToMap(obj) {
return new Map(Object.entries(obj));
}
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}.`);
}
}
function clean_up_tokenization(text) {
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");
}
function remove_accents(text) {
return text.replace(/[\u0300-\u036f]/g, "");
}
function lowercase_and_remove_accent(text) {
return remove_accents(text.toLowerCase());
}
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;
}
function whitespace_split(text) {
return text.match(/\S+/g) || [];
}
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" ? mergeArrays(item[key], padData) : mergeArrays(padData, item[key]);
}
}
function truncateHelper(item, length) {
for (const key of Object.keys(item)) {
item[key].length = length;
}
}
function _build_translation_inputs(self2, raw_inputs, tokenizer_options, generate_kwargs) {
if (!("language_codes" in self2) || !Array.isArray(self2.language_codes)) {
throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");
}
if (!("languageRegex" in self2) || !(self2.languageRegex instanceof RegExp)) {
throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");
}
if (!("lang_to_token" in self2) || typeof self2.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;
if (!self2.language_codes.includes(tgt_lang_token)) {
throw new Error(`Target language code "${tgt_lang_token}" is not valid. Must be one of: {${self2.language_codes.join(", ")}}`);
}
if (src_lang_token !== void 0) {
if (!self2.language_codes.includes(src_lang_token)) {
throw new Error(`Source language code "${src_lang_token}" is not valid. Must be one of: {${self2.language_codes.join(", ")}}`);
}
for (const item of self2.post_processor.config.single) {
if ("SpecialToken" in item && self2.languageRegex.test(item.SpecialToken.id)) {
item.SpecialToken.id = self2.lang_to_token(src_lang_token);
break;
}
}
}
generate_kwargs.forced_bos_token_id = self2.model.convert_tokens_to_ids([self2.lang_to_token(tgt_lang_token)])[0];
return self2._call(raw_inputs, tokenizer_options);
}
var PUNCTUATION_REGEX, PROBLEMATIC_REGEX_MAP, AddedToken, TokenizerModel, WordPieceTokenizer, Unigram, BYTES_TO_UNICODE, UNICODE_TO_BYTES, BPE, LegacyTokenizerModel, Normalizer, Replace, NFC, NFKC, NFKD, StripNormalizer, StripAccents, Lowercase, Prepend, NormalizerSequence, BertNormalizer, PreTokenizer, BertPreTokenizer, ByteLevelPreTokenizer, SplitPreTokenizer, PunctuationPreTokenizer, DigitsPreTokenizer, PostProcessor, BertProcessing, RobertaProcessing, TemplateProcessing, ByteLevelPostProcessor, PostProcessorSequence, Decoder, ReplaceDecoder, ByteFallback, FuseDecoder, StripDecoder, WordPieceDecoder, ByteLevelDecoder, CTCDecoder, DecoderSequence, BPEDecoder, VitsDecoder, MetaspacePreTokenizer, MetaspaceDecoder, Precompiled, PreTokenizerSequence, WhitespacePreTokenizer, WhitespaceSplit, ReplacePreTokenizer, SPECIAL_TOKEN_ATTRIBUTES, PreTrainedTokenizer, BertTokenizer, AlbertTokenizer, MobileBertTokenizer, SqueezeBertTokenizer, DebertaTokenizer, DebertaV2Tokenizer, HerbertTokenizer, ConvBertTokenizer, RoFormerTokenizer, DistilBertTokenizer, CamembertTokenizer, XLMTokenizer, ElectraTokenizer, T5Tokenizer, GPT2Tokenizer, BartTokenizer, MBartTokenizer, MBart50Tokenizer, RobertaTokenizer, BloomTokenizer, SPIECE_UNDERLINE, LlamaTokenizer, CodeLlamaTokenizer, XLMRobertaTokenizer, MPNetTokenizer, FalconTokenizer, GPTNeoXTokenizer, EsmTokenizer, Qwen2Tokenizer, GemmaTokenizer, Grok1Tokenizer, NllbTokenizer, M2M100Tokenizer, WHISPER_LANGUAGES, WHISPER_LANGUAGE_MAPPING, WHISPER_TO_LANGUAGE_CODE_MAPPING, WhisperTokenizer, CodeGenTokenizer, CLIPTokenizer, SiglipTokenizer, MarianTokenizer, Wav2Vec2CTCTokenizer, BlenderbotTokenizer, BlenderbotSmallTokenizer, SpeechT5Tokenizer, NougatTokenizer, VitsTokenizer, CohereTokenizer, AutoTokenizer;
var init_tokenizers = __esm({
"node_modules/@xenova/transformers/src/tokenizers.js"() {
init_core();
init_hub();
init_maths();
init_tensor();
init_data_structures();
init_dist();
PUNCTUATION_REGEX = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E";
PROBLEMATIC_REGEX_MAP = /* @__PURE__ */ 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]))"]
]);
AddedToken = class {
/**
* 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;
}
};
TokenizerModel = class extends Callable {
/**
* Creates a new instance of TokenizerModel.
* @param {Object} config The configuration object for the TokenizerModel.
*/
constructor(config) {
super();
this.config = config;
this.vocab = [];
this.tokens_to_ids = /* @__PURE__ */ new Map();
this.unk_token_id = void 0;
this.unk_token = void 0;
this.end_of_word_suffix = void 0;
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":
return new Unigram(config, ...args);
case "BPE":
return new BPE(config);
default:
if (config.vocab) {
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) {
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);
}
};
WordPieceTokenizer = class 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);
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.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;
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;
}
};
Unigram = class 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 = " ";
this.bosTokenId = this.tokens_to_ids.get(this.bosToken);
this.eosToken = moreConfig.eos_token;
this.eosTokenId = this.tokens_to_ids.get(this.eosToken);
this.unkToken = this.vocab[this.unk_token_id];
this.minScore = min(this.scores)[0];
this.unkScore = this.minScore - 10;
this.scores[this.unk_token_id] = this.unkScore;
this.trie = new CharTrie();
this.trie.extend(this.vocab);
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 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;
}
};
BYTES_TO_UNICODE = (() => {
const bs = [
...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)),
...Array.from({ length: "\xAC".charCodeAt(0) - "\xA1".charCodeAt(0) + 1 }, (_, i) => i + "\xA1".charCodeAt(0)),
...Array.from({ length: "\xFF".charCodeAt(0) - "\xAE".charCodeAt(0) + 1 }, (_, i) => i + "\xAE".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((n2) => String.fromCharCode(n2));
return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));
})();
UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE);
BPE = class 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 = " ";
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;
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;
this.cache = /* @__PURE__ */ 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 !== void 0) {
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) {
const queue = new PriorityQueue((a, b) => a.score < b.score);
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()) {
const node = queue.pop();
if (node.deleted || !node.next || node.next.deleted)
continue;
node.deleted = true;
node.next.deleted = true;
if (node.prev) {
const newPreviousNode = { ...node.prev };
node.prev.deleted = true;
node.prev = newPreviousNode;
if (newPreviousNode.prev) {
newPreviousNode.prev.next = newPreviousNode;
} else {
startingNode = newPreviousNode;
}
}
const merged = {
token: node.token + node.next.token,
bias: node.bias,
prev: node.prev,
next: node.next.next
};
if (merged.prev) {
merged.prev.next = merged;
this._add_node(queue, merged.prev);
} else {
startingNode = merged;
}
if (merged.next) {
merged.next.prev = merged;
this._add_node(queue, merged);
}
}
for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) {
result.push(currentNode.token);
}
} else {
result = word;
}
if (this.continuing_subword_suffix) {
for (let i = 0; i < result.length - 1; ++i) {
result[i] += this.continuing_subword_suffix;
}
}
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) {
const rank = this.bpe_ranks.get(node.token + this.BPE_SPLIT_TOKEN + node.next.token);
if (rank !== void 0) {
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;
}
};
LegacyTokenizerModel = class 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);
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;
}
};
Normalizer = class extends 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 = class 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);
}
};
NFC = class 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 = class 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 = class 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;
}
};
StripNormalizer = class 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) {
text = text.trim();
} else {
if (this.config.strip_left) {
text = text.trimStart();
}
if (this.config.strip_right) {
text = text.trimEnd();
}
}
return text;
}
};
StripAccents = class 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;
}
};
Lowercase = class 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;
}
};
Prepend = class 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;
}
};
NormalizerSequence = class 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);
}
};
BertNormalizer = class 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) {
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 >= 19968 && cp <= 40959 || cp >= 13312 && cp <= 19903 || cp >= 131072 && cp <= 173791 || cp >= 173824 && cp <= 177983 || cp >= 177984 && cp <= 178207 || cp >= 178208 && cp <= 183983 || cp >= 63744 && cp <= 64255 || cp >= 194560 && cp <= 195103;
}
/**
* 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 " ":
case "\n":
case "\r":
return false;
default:
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 === 65533 || this._is_control(char)) {
continue;
}
if (/^\s$/.test(char)) {
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;
}
};
PreTokenizer = class extends 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);
}
};
BertPreTokenizer = class 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();
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) || [];
}
};
ByteLevelPreTokenizer = class extends PreTokenizer {
/**
* Creates a new instance of the `ByteLevelPreTokenizer` class.
* @param {Object} config The configuration object.
*/
constructor(config) {
super();
this.config = config;
this.add_prefix_space = this.config.add_prefix_space;
this.trim_offsets = this.config.trim_offsets;
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) {
if (this.add_prefix_space && !text.startsWith(" ")) {
text = " " + text;
}
const tokens = this.use_regex ? text.match(this.pattern) || [] : [text];
return tokens.map(
(token) => Array.from(this.text_encoder.encode(token), (byte) => this.byte_encoder[byte]).join("")
);
}
};
SplitPreTokenizer = class 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;
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);
}
}
};
PunctuationPreTokenizer = class 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) || [];
}
};
DigitsPreTokenizer = class 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;
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) || [];
}
};
PostProcessor = class extends 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);
}
};
BertProcessing = class 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);
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 = mergeArrays([this.cls], tokens, [this.sep]);
}
let token_type_ids = new Array(tokens.length).fill(0);
if (tokens_pair !== null) {
const middle = add_special_tokens && this instanceof RobertaProcessing ? [this.sep] : [];
const after = add_special_tokens ? [this.sep] : [];
tokens = mergeArrays(tokens, middle, tokens_pair, after);
token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));
}
return { tokens, token_type_ids };
}
};
RobertaProcessing = class extends BertProcessing {
};
TemplateProcessing = class 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 = mergeArrays(processedTokens, tokens);
types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id));
} else if (item.Sequence.id === "B") {
processedTokens = mergeArrays(processedTokens, tokens_pair);
types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));
}
}
}
return { tokens: processedTokens, token_type_ids: types };
}
};
ByteLevelPostProcessor = class 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 = mergeArrays(tokens, tokens_pair);
}
return { tokens };
}
};
PostProcessorSequence = class 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) {
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 };
}
};
Decoder = class extends Callable {
/**
* Creates an instance of `Decoder`.
*
* @param {Object} config The configuration object.
*/
constructor(config) {
super();
this.config = config;
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.");
}
};
ReplaceDecoder = class 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));
}
};
ByteFallback = class 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;
}
};
FuseDecoder = class extends Decoder {
/** @type {Decoder['decode_chain']} */
decode_chain(tokens) {
return [tokens.join("")];
}
};
StripDecoder = class 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);
});
}
};
WordPieceDecoder = class 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)) {
token = token.replace(this.config.prefix, "");
} else {
token = " " + token;
}
}
if (this.cleanup) {
token = clean_up_tokenization(token);
}
return token;
});
}
};
ByteLevelDecoder = class 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) {
const sub_texts = [];
let current_sub_text = [];
for (const token of tokens) {
if (this.added_tokens.find((x) => x.content === token) !== void 0) {
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));
}
return sub_texts;
}
};
CTCDecoder = class 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 "";
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]);
}
}
const filtered_tokens = grouped_tokens.filter((token) => token !== this.pad_token);
let text = filtered_tokens.join("");
if (this.cleanup) {
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)];
}
};
DecoderSequence = class 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) {
return this.decoders.reduce((toks, decoder) => {
return decoder.decode_chain(toks);
}, tokens);
}
};
BPEDecoder = class 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 ? "" : " ");
});
}
};
VitsDecoder = class 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];
}
};
MetaspacePreTokenizer = class 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 = void 0
} = {}) {
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) && (this.prepend_scheme === "always" || this.prepend_scheme === "first" && section_index === 0)
) {
normalized = this.strRep + normalized;
}
return [normalized];
}
};
MetaspaceDecoder = class 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;
}
};
Precompiled = class 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) {
text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, "");
text = text.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm, " ");
if (text.includes("\uFF5E")) {
const parts = text.split("\uFF5E");
text = parts.map((part) => part.normalize("NFKC")).join("\uFF5E");
} else {
text = text.normalize("NFKC");
}
return text;
}
};
PreTokenizerSequence = class 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) {
return this.tokenizers.reduce((preTokenizedText, tokenizer) => {
return tokenizer.pre_tokenize(preTokenizedText, options);
}, [text]);
}
};
WhitespacePreTokenizer = class 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) || [];
}
};
WhitespaceSplit = class 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);
}
};
ReplacePreTokenizer = class 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)];
}
};
SPECIAL_TOKEN_ATTRIBUTES = [
"bos_token",
"eos_token",
"unk_token",
"sep_token",
"pad_token",
"cls_token",
"mask_token"
// additional_special_tokens (TODO)
];
PreTrainedTokenizer = class extends Callable {
/**
* 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();
__publicField(this, "return_token_type_ids", false);
__publicField(this, "_default_chat_template", `{% for message in messages %}{{'<|im_start|>' + message['role'] + '
' + message['content'] + '<|im_end|>' + '
'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
' }}{% endif %}`);
this._tokenizer_config = tokenizerConfig;
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);
this.special_tokens = [];
this.all_special_ids = [];
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);
}
}
this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? [];
this.special_tokens.push(...this.additional_special_tokens);
this.special_tokens = [...new Set(this.special_tokens)];
if (this.decoder) {
this.decoder.added_tokens = this.added_tokens;
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*" : ""}(${escapeRegExp(x.content)})${x.rstrip ? "\\s*" : ""}`).join("|")
) : null;
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;
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;
this.padding_side = "right";
this.legacy = false;
this.chat_template = tokenizerConfig.chat_template ?? null;
if (Array.isArray(this.chat_template)) {
const chat_template = /* @__PURE__ */ Object.create(null);
for (const { name: name2, template } of this.chat_template) {
if (typeof name2 !== "string" || typeof template !== "string") {
throw new Error('Chat template must be a list of objects with "name" and "template" properties');
}
chat_template[name2] = template;
}
this.chat_template = chat_template;
}
this._compiled_template_cache = /* @__PURE__ */ 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
});
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(text, {
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);
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 === void 0) {
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).");
}
encodedTokens = [this._encode_plus(text, text_pair, { add_special_tokens, return_token_type_ids })];
}
if (max_length === null) {
if (padding === "max_length") {
max_length = this.model_max_length;
} else {
max_length = 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.`);
}
}
max_length = Math.min(max_length, this.model_max_length);
if (padding || 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) {
if (truncation) {
truncateHelper(encodedTokens[i], max_length);
}
} else {
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)) {
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."
);
}
}
const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];
for (const key of Object.keys(encodedTokens[0])) {
result[key] = new 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 (!isBatched) {
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;
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 !== void 0) {
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 (x.length === 0) {
return [];
}
const sectionTokens = this.pre_tokenizer !== null ? this.pre_tokenizer(x, {
section_index
}) : [x];
const tokens2 = this.model(sectionTokens);
return tokens2;
}
}).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
} = {}) {
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: 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 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 Tensor) {
token_ids = prepareTensorForDecode(token_ids);
}
if (!Array.isArray(token_ids) || token_ids.length === 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));
}
let decoded = this.decoder ? this.decoder(tokens) : tokens.join(" ");
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;
}
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: tokenize2 = true,
padding = false,
truncation = false,
max_length = null,
return_tensor = true,
tokenizer_kwargs = {},
...kwargs
} = {}) {
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;
if (chat_template !== null && Object.hasOwn(template_dict, chat_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 {
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}`);
}
let compiledTemplate = this._compiled_template_cache.get(chat_template);
if (compiledTemplate === void 0) {
compiledTemplate = new Template(chat_template);
this._compiled_template_cache.set(chat_template, compiledTemplate);
}
const special_tokens_map = /* @__PURE__ */ 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,
...special_tokens_map,
...kwargs
});
if (tokenize2) {
return this._call(rendered, {
add_special_tokens: false,
padding,
truncation,
max_length,
return_tensor,
...tokenizer_kwargs
}).input_ids;
}
return rendered;
}
};
BertTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "return_token_type_ids", true);
}
};
AlbertTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "return_token_type_ids", true);
}
};
MobileBertTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "return_token_type_ids", true);
}
};
SqueezeBertTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "return_token_type_ids", true);
}
};
DebertaTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "return_token_type_ids", true);
}
};
DebertaV2Tokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "return_token_type_ids", true);
}
};
HerbertTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "return_token_type_ids", true);
}
};
ConvBertTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "return_token_type_ids", true);
}
};
RoFormerTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "return_token_type_ids", true);
}
};
DistilBertTokenizer = class extends PreTrainedTokenizer {
};
CamembertTokenizer = class extends PreTrainedTokenizer {
};
XLMTokenizer = class extends PreTrainedTokenizer {
constructor(tokenizerJSON, tokenizerConfig) {
super(tokenizerJSON, tokenizerConfig);
__publicField(this, "return_token_type_ids", true);
console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.');
}
};
ElectraTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "return_token_type_ids", true);
}
};
T5Tokenizer = class extends PreTrainedTokenizer {
};
GPT2Tokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "_default_chat_template", `{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}`);
}
};
BartTokenizer = class extends PreTrainedTokenizer {
};
MBartTokenizer = class 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;
}
/**
* 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);
}
};
MBart50Tokenizer = class extends MBartTokenizer {
};
RobertaTokenizer = class extends PreTrainedTokenizer {
};
BloomTokenizer = class extends GPT2Tokenizer {
// NOTE: `GPT2Tokenizer` to get the correct chat template
constructor(tokenizerJSON, tokenizerConfig) {
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);
}
};
SPIECE_UNDERLINE = "\u2581";
LlamaTokenizer = class extends PreTrainedTokenizer {
constructor(tokenizerJSON, tokenizerConfig) {
super(tokenizerJSON, tokenizerConfig);
__publicField(this, "_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>>
' + system_message + '
<</SYS>>
' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<<SYS>>
' + content.strip() + '
<</SYS>>
' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`);
__publicField(this, "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\nIf 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.");
this.use_default_system_prompt = tokenizerConfig.use_default_system_prompt ?? false;
this.legacy = tokenizerConfig.legacy ?? true;
if (!this.legacy) {
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("'", "\\'"));
}
};
CodeLlamaTokenizer = class extends LlamaTokenizer {
};
XLMRobertaTokenizer = class extends PreTrainedTokenizer {
};
MPNetTokenizer = class extends PreTrainedTokenizer {
};
FalconTokenizer = class extends PreTrainedTokenizer {
};
GPTNeoXTokenizer = class extends PreTrainedTokenizer {
};
EsmTokenizer = class extends PreTrainedTokenizer {
};
Qwen2Tokenizer = class extends PreTrainedTokenizer {
};
GemmaTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "_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 %}");
}
};
Grok1Tokenizer = class extends PreTrainedTokenizer {
};
NllbTokenizer = class 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;
}
/**
* 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);
}
};
M2M100Tokenizer = class 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);
}
};
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"]
];
WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES);
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 = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "_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
} = {}) {
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": "" };
}
const chunks = [];
let chunk = new_chunk();
let time_offset = 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) {
const token_ids = output.tokens;
const token_timestamps = returnWordTimestamps ? output.token_timestamps : null;
let last_timestamp = null;
let first_timestamp = timestamp_begin;
if ("stride" in output) {
const [chunk_len, stride_left, stride_right] = output.stride;
time_offset -= stride_left;
right_stride_start = chunk_len - stride_right;
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) {
if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) {
break;
}
last_timestamp = token;
}
}
}
}
let current_tokens = [];
let current_token_timestamps = [];
for (let i = 0; i < token_ids.length; ++i) {
const token = token_ids[i];
if (all_special_ids.has(token)) {
const text = this.decode([token]);
const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2));
if (language !== void 0) {
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);
previous_tokens = [];
current_tokens = [];
chunk = new_chunk();
}
last_language = chunk.language = language;
} else {
}
} else if (token >= timestamp_begin) {
const time = (token - timestamp_begin) * time_precision + time_offset;
const rounded_time = round(time, 2);
if (last_timestamp !== null && token >= last_timestamp) {
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 {
if (rounded_time === chunk.timestamp[0]) {
} else {
chunk.timestamp[1] = rounded_time;
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);
previous_tokens = [];
current_tokens = [];
previous_token_timestamps = [];
current_token_timestamps = [];
chunk = new_chunk();
}
}
} else {
current_tokens.push(token);
if (returnWordTimestamps) {
let start_time = round(token_timestamps[i] + time_offset, 2);
let end_time;
if (i + 1 < token_timestamps.length) {
end_time = round(token_timestamps[i + 1] + time_offset, 2);
} else {
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;
}
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)) {
chunk = new_chunk();
previous_tokens = [];
current_tokens = [];
previous_token_timestamps = [];
current_token_timestamps = [];
}
}
if (previous_tokens.length > 0) {
if (force_full_sequences && return_timestamps) {
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."
);
}
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);
}
let optional = /* @__PURE__ */ Object.create(null);
const full_text = chunks.map((chunk2) => chunk2.text).join("");
if (return_timestamps || return_language) {
for (let i = 0; i < chunks.length; ++i) {
const chunk2 = chunks[i];
if (!return_timestamps) {
delete chunk2["timestamp"];
}
if (!return_language) {
delete chunk2["language"];
}
}
if (returnWordTimestamps) {
const new_chunks = [];
for (const chunk2 of chunks) {
for (const word of chunk2.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) {
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 max2 = 0;
let maxIndices = [leftLength, leftLength, 0, 0];
const rightLength = rightSequence.length;
for (let j = 1; j < leftLength + rightLength; ++j) {
const eps = j / 1e4;
const leftStart2 = Math.max(0, leftLength - j);
const leftStop2 = Math.min(leftLength, leftLength + rightLength - j);
const left = leftSequence.slice(leftStart2, leftStop2);
const rightStart2 = Math.max(0, j - leftLength);
const rightStop2 = Math.min(rightLength, j);
const right = rightSequence.slice(rightStart2, rightStop2);
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 > max2) {
max2 = matching;
maxIndices = [leftStart2, leftStop2, rightStart2, rightStop2];
}
}
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 = `"'\u201C\xA1\xBF([{-`, append_punctuations = `"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`) {
language = language ?? "english";
let words, word_tokens, token_indices;
if (["chinese", "japanese", "thai", "lao", "myanmar"].includes(language)) {
[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;
if (decode_args && decode_args.decode_with_timestamps) {
if (token_ids instanceof Tensor) {
token_ids = prepareTensorForDecode(token_ids);
}
text = this.decodeWithTimestamps(token_ids, decode_args);
} else {
text = super.decode(token_ids, decode_args);
}
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;
let outputs = [[]];
for (const token of token_ids) {
if (token >= timestamp_begin) {
const timestamp = 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];
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);
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] = mergeArrays(newTokens[i], newTokens[j]);
newIndices[j] = mergeArrays(newIndices[i], newIndices[j]);
newWords[i] = "";
newTokens[i] = [];
newIndices[i] = [];
} else {
j = i;
}
--i;
}
i = 0;
j = 1;
while (j < newWords.length) {
if (!newWords[i].endsWith(" ") && appended.includes(newWords[j])) {
newWords[i] += newWords[j];
newTokens[i] = mergeArrays(newTokens[i], newTokens[j]);
newIndices[i] = 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
} = {}) {
const forced_decoder_ids = [];
if (language) {
language = language.toLowerCase();
let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language);
if (language_code === void 0) {
if (WHISPER_LANGUAGE_MAPPING.has(language)) {
language_code = language;
} else {
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 === void 0) {
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 {
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 === void 0) {
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 {
forced_decoder_ids.push(null);
}
if (no_timestamps) {
const no_timestamps_id = this.model.tokens_to_ids.get(`<|notimestamps|>`);
if (no_timestamps_id === void 0) {
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);
}
};
CodeGenTokenizer = class extends PreTrainedTokenizer {
};
CLIPTokenizer = class extends PreTrainedTokenizer {
};
SiglipTokenizer = class extends PreTrainedTokenizer {
};
MarianTokenizer = class 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;
const [matchInfo, ...remainder] = text.trim().split(this.languageRegex);
if (remainder.length === 0) {
return super._encode_text(matchInfo);
} else if (remainder.length === 2) {
const [language, text2] = 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 mergeArrays([language], super._encode_text(text2));
}
}
};
Wav2Vec2CTCTokenizer = class extends PreTrainedTokenizer {
};
BlenderbotTokenizer = class extends PreTrainedTokenizer {
constructor() {
super(...arguments);
__publicField(this, "_default_chat_template", `{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}`);
}
};
BlenderbotSmallTokenizer = class extends BlenderbotTokenizer {
};
SpeechT5Tokenizer = class extends PreTrainedTokenizer {
};
NougatTokenizer = class extends PreTrainedTokenizer {
};
VitsTokenizer = class extends PreTrainedTokenizer {
constructor(tokenizerJSON, tokenizerConfig) {
super(tokenizerJSON, tokenizerConfig);
this.decoder = new VitsDecoder({});
}
};
CohereTokenizer = class extends PreTrainedTokenizer {
};
AutoTokenizer = class {
/**
* 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
});
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);
}
};
__publicField(AutoTokenizer, "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
});
}
});
// node_modules/@xenova/transformers/src/configs.js
async function loadConfig(pretrained_model_name_or_path, options) {
let info = await getModelJSON(pretrained_model_name_or_path, "config.json", true, options);
return info;
}
var PretrainedConfig, AutoConfig;
var init_configs = __esm({
"node_modules/@xenova/transformers/src/configs.js"() {
init_hub();
PretrainedConfig = class {
// 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);
}
};
AutoConfig = class {
/** @type {PretrainedConfig.from_pretrained} */
static async from_pretrained(...args) {
return PretrainedConfig.from_pretrained(...args);
}
};
}
});
// node_modules/@xenova/transformers/src/utils/generation.js
var LogitsProcessorList, LogitsProcessor, ForceTokensLogitsProcessor, ForcedBOSTokenLogitsProcessor, ForcedEOSTokenLogitsProcessor, SuppressTokensAtBeginLogitsProcessor, WhisperTimeStampLogitsProcessor, NoRepeatNGramLogitsProcessor, RepetitionPenaltyLogitsProcessor, MinLengthLogitsProcessor, MinNewTokensLengthLogitsProcessor, NoBadWordsLogitsProcessor, GenerationConfig, Sampler, GreedySampler, MultinomialSampler, BeamSearchSampler;
var init_generation = __esm({
"node_modules/@xenova/transformers/src/utils/generation.js"() {
init_tensor();
init_core();
init_maths();
LogitsProcessorList = class extends 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) {
for (let logits of batchedLogits) {
this.processors.forEach(
(func) => func(input_ids, logits)
);
}
}
[Symbol.iterator]() {
return this.processors.values();
}
};
LogitsProcessor = class extends 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");
}
};
ForceTokensLogitsProcessor = class 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 (exists(map)) {
logits.data.fill(-Infinity);
logits.data[map] = 0;
}
return logits;
}
};
ForcedBOSTokenLogitsProcessor = class 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;
}
};
ForcedEOSTokenLogitsProcessor = class 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) {
}
};
SuppressTokensAtBeginLogitsProcessor = class 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;
}
};
WhisperTimeStampLogitsProcessor = class 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
);
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;
}
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) {
logitsData.subarray(this.timestamp_begin).fill(-Infinity);
} else {
logitsData.subarray(0, this.eos_token_id).fill(-Infinity);
}
}
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);
}
const logprobs = 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 = 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;
}
};
NoRepeatNGramLogitsProcessor = class 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;
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);
}
const generatedNgram = /* @__PURE__ */ 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 bannedTokens;
} else {
const generatedNgrams = this.getNgrams(prevInputIds);
const bannedTokens2 = this.getGeneratedNgrams(generatedNgrams, prevInputIds);
return bannedTokens2;
}
}
/**
* 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;
}
};
RepetitionPenaltyLogitsProcessor = class 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) {
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;
}
};
MinLengthLogitsProcessor = class 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;
}
};
MinNewTokensLengthLogitsProcessor = class 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;
}
};
NoBadWordsLogitsProcessor = class 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) {
let mark = true;
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)) {
mark = false;
break;
}
}
if (mark) {
logits.data[bad_word_ids.at(-1)] = -Infinity;
}
}
return logits;
}
};
GenerationConfig = /** @type {any} */
class {
/**
* Create a new GenerationConfig object.
* @param {GenerationConfigType} kwargs
*/
constructor(kwargs = {}) {
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;
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;
this.temperature = kwargs.temperature ?? 1;
this.top_k = kwargs.top_k ?? 50;
this.top_p = kwargs.top_p ?? 1;
this.typical_p = kwargs.typical_p ?? 1;
this.epsilon_cutoff = kwargs.epsilon_cutoff ?? 0;
this.eta_cutoff = kwargs.eta_cutoff ?? 0;
this.diversity_penalty = kwargs.diversity_penalty ?? 0;
this.repetition_penalty = kwargs.repetition_penalty ?? 1;
this.encoder_repetition_penalty = kwargs.encoder_repetition_penalty ?? 1;
this.length_penalty = kwargs.length_penalty ?? 1;
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;
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;
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;
this.encoder_no_repeat_ngram_size = kwargs.encoder_no_repeat_ngram_size ?? 0;
this.decoder_start_token_id = kwargs.decoder_start_token_id ?? null;
this.generation_kwargs = kwargs.generation_kwargs ?? {};
}
};
Sampler = class extends 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) {
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);
}
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) {
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;
}
/**
* 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) {
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);
}
}
};
GreedySampler = class 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) {
let logs = this.getLogits(logits, index);
let argmax = max(logs)[1];
return [
[argmax, 0]
];
}
};
MultinomialSampler = class extends Sampler {
/**
* Sample from the logits.
* @param {Tensor} logits
* @param {number} index
* @returns {Array}
*/
sample(logits, index = -1) {
let k = logits.dims.at(-1);
if (this.generation_config.top_k > 0) {
k = Math.min(this.generation_config.top_k, k);
}
const logs = this.getLogits(logits, index);
const topLogits = getTopItems(logs, k);
const probabilities = 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
];
});
}
};
BeamSearchSampler = class extends Sampler {
/**
* Sample from the logits.
* @param {Tensor} logits
* @param {number} index
* @returns {Array}
*/
sample(logits, index = -1) {
let k = logits.dims.at(-1);
if (this.generation_config.top_k > 0) {
k = Math.min(this.generation_config.top_k, k);
}
const logs = this.getLogits(logits, index);
const topLogits = getTopItems(logs, k);
const probabilities = 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
];
});
}
};
}
});
// node_modules/@xenova/transformers/src/models.js
async function constructSession(pretrained_model_name_or_path, fileName, options) {
let modelFileName = `onnx/${fileName}${options.quantized ? "_quantized" : ""}.onnx`;
let buffer = await getModelFile(pretrained_model_name_or_path, modelFileName, true, options);
try {
return await InferenceSession.create(buffer, {
executionProviders
});
} catch (err) {
if (executionProviders.length === 1 && 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"]
});
}
}
function validateInputs(session, inputs) {
const checkedInputs = /* @__PURE__ */ Object.create(null);
const missingInputs = [];
for (const inputName of session.inputNames) {
const tensor = inputs[inputName];
if (!(tensor instanceof Tensor)) {
missingInputs.push(inputName);
continue;
}
checkedInputs[inputName] = env2.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) {
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;
}
async function sessionRun(session, inputs) {
const checkedInputs = validateInputs(session, inputs);
try {
let output = await session.run(checkedInputs);
output = replaceTensors(output);
return output;
} catch (e) {
console.error(`An error occurred during model execution: "${e}".`);
console.error("Inputs given to model:", checkedInputs);
throw e;
}
}
function replaceTensors(obj) {
for (let prop in obj) {
if (obj[prop] instanceof ONNXTensor2) {
obj[prop] = new Tensor(obj[prop]);
} else if (typeof obj[prop] === "object") {
replaceTensors(obj[prop]);
}
}
return obj;
}
function toI64Tensor(items) {
if (items instanceof Tensor) {
return items;
}
if (items.length === 0) {
throw Error("items must be non-empty");
}
if (Array.isArray(items[0])) {
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 Tensor(
"int64",
BigInt64Array.from(items.flat().map((x) => BigInt(x))),
[items.length, items[0].length]
);
} else {
return new Tensor(
"int64",
BigInt64Array.from(items.map((x) => BigInt(x))),
[1, items.length]
);
}
}
function prepareAttentionMask(self2, tokens) {
let pad_token_id = self2.config.pad_token_id ?? null;
let eos_token_id = self2.config.eos_token_id ?? null;
if (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 Tensor("int64", data, tokens.dims);
} else {
return ones_like(tokens);
}
}
function preparePositionIds(session, feeds, use_cache_branch) {
if (!session.inputNames.includes("position_ids"))
return;
const data = new BigInt64Array(feeds.attention_mask.data.length);
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 {
data[index] = sum;
sum += feeds.attention_mask.data[index];
}
}
}
feeds.position_ids = new Tensor("int64", data, feeds.attention_mask.dims);
if (use_cache_branch) {
feeds.position_ids = feeds.position_ids.slice(null, -1).unsqueeze_(-1);
}
}
function boolTensor(value) {
return new Tensor("bool", [value], [1]);
}
async function seq2seqForward(self2, model_inputs) {
let { encoder_outputs, past_key_values } = model_inputs;
if (!encoder_outputs) {
encoder_outputs = (await encoderForward(self2, 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 (self2.decoder_merged_session.inputNames.includes("use_cache_branch")) {
decoderFeeds.use_cache_branch = boolTensor(use_cache_branch);
}
if (self2.decoder_merged_session.inputNames.includes("encoder_attention_mask")) {
decoderFeeds.encoder_attention_mask = model_inputs.attention_mask;
}
preparePositionIds(self2.decoder_merged_session, decoderFeeds, use_cache_branch);
self2.addPastKeyValues(decoderFeeds, past_key_values);
const decoderResults = await sessionRun(self2.decoder_merged_session, decoderFeeds);
let logits = decoderResults.logits;
past_key_values = self2.getPastKeyValues(decoderResults, past_key_values);
const attns = self2.getAttentions(decoderResults);
return new Seq2SeqLMOutput({ logits, past_key_values, encoder_outputs, ...attns });
}
function seq2seqStartBeams(self2, inputTokenIds, generation_config, numOutputTokens) {
let beams = [];
let beamId = 0;
const requires_attention_mask = self2.requires_attention_mask ?? true;
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;
if (decoder_input_ids instanceof 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) {
tokens.dims = [1, ...tokens.dims];
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(self2, tokens);
}
beams.push(start);
}
return beams;
}
async function seq2seqRunBeam(self2, beam) {
const input_name = self2.main_input_name;
let decoder_input_ids = beam.output_token_ids;
if (beam.prev_model_outputs) {
decoder_input_ids = decoder_input_ids.slice(-1);
}
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;
}
let output = await self2.forward(model_inputs);
beam.prev_model_outputs = output;
beam.encoder_outputs = output.encoder_outputs;
return output;
}
function seq2seqUpdatebeam(beam, newTokenId) {
beam.output_token_ids = [...beam.output_token_ids, newTokenId];
}
async function encoderForward(self2, model_inputs) {
const encoderFeeds = /* @__PURE__ */ Object.create(null);
for (const key of self2.session.inputNames) {
encoderFeeds[key] = model_inputs[key];
}
if (self2.session.inputNames.includes("token_type_ids") && !encoderFeeds.token_type_ids) {
encoderFeeds.token_type_ids = new Tensor(
"int64",
new BigInt64Array(encoderFeeds.input_ids.data.length),
encoderFeeds.input_ids.dims
);
}
return await sessionRun(self2.session, encoderFeeds);
}
async function decoderForward(self2, model_inputs) {
let { input_ids, past_key_values, attention_mask } = model_inputs;
let decoderFeeds = {
input_ids,
attention_mask: attention_mask ?? prepareAttentionMask(self2, input_ids)
};
const use_cache_branch = !!past_key_values;
if (self2.session.inputNames.includes("use_cache_branch")) {
decoderFeeds.use_cache_branch = boolTensor(use_cache_branch);
}
preparePositionIds(self2.session, decoderFeeds, use_cache_branch);
self2.addPastKeyValues(decoderFeeds, past_key_values);
let decoderResults = await sessionRun(self2.session, decoderFeeds);
let logits = decoderResults.logits;
past_key_values = self2.getPastKeyValues(decoderResults, past_key_values);
return { logits, past_key_values };
}
function decoderStartBeams(self2, 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);
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(self2, tokens);
}
let start = {
input: tokens,
model_input_ids: tokens,
attention_mask: attn_mask,
prev_model_outputs: null,
output_token_ids,
num_output_tokens: numOutputTokens,
done: false,
score: 0,
id: beamId++
// assign unique id to beams
};
beams.push(start);
}
return beams;
}
async function decoderRunBeam(self2, beam) {
let attnMaskData = new BigInt64Array(beam.output_token_ids.length).fill(1n);
let model_inputs = {
input_ids: beam.model_input_ids,
attention_mask: new Tensor(
"int64",
attnMaskData,
[1, attnMaskData.length]
),
past_key_values: beam.prev_model_outputs?.past_key_values
};
let output = await self2.forward(model_inputs);
beam.prev_model_outputs = output;
return output;
}
function decoderUpdatebeam(beam, newTokenId) {
beam.output_token_ids = [...beam.output_token_ids, newTokenId];
beam.model_input_ids = new Tensor("int64", [BigInt(newTokenId)], [1, 1]);
}
var InferenceSession, ONNXTensor2, env2, MODEL_TYPES, MODEL_TYPE_MAPPING, MODEL_NAME_TO_CLASS_MAPPING, MODEL_CLASS_TO_NAME_MAPPING, PreTrainedModel, ModelOutput, BaseModelOutput, BertPreTrainedModel, BertModel, BertForMaskedLM, BertForSequenceClassification, BertForTokenClassification, BertForQuestionAnswering, NomicBertPreTrainedModel, NomicBertModel, RoFormerPreTrainedModel, RoFormerModel, RoFormerForMaskedLM, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerForQuestionAnswering, ConvBertPreTrainedModel, ConvBertModel, ConvBertForMaskedLM, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertForQuestionAnswering, ElectraPreTrainedModel, ElectraModel, ElectraForMaskedLM, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraForQuestionAnswering, CamembertPreTrainedModel, CamembertModel, CamembertForMaskedLM, CamembertForSequenceClassification, CamembertForTokenClassification, CamembertForQuestionAnswering, DebertaPreTrainedModel, DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, DebertaV2PreTrainedModel, DebertaV2Model, DebertaV2ForMaskedLM, DebertaV2ForSequenceClassification, DebertaV2ForTokenClassification, DebertaV2ForQuestionAnswering, DistilBertPreTrainedModel, DistilBertModel, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertForQuestionAnswering, DistilBertForMaskedLM, EsmPreTrainedModel, EsmModel, EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, MobileBertPreTrainedModel, MobileBertModel, MobileBertForMaskedLM, MobileBertForSequenceClassification, MobileBertForQuestionAnswering, MPNetPreTrainedModel, MPNetModel, MPNetForMaskedLM, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetForQuestionAnswering, SqueezeBertPreTrainedModel, SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForSequenceClassification, SqueezeBertForQuestionAnswering, AlbertPreTrainedModel, AlbertModel, AlbertForSequenceClassification, AlbertForQuestionAnswering, AlbertForMaskedLM, T5PreTrainedModel, T5Model, T5ForConditionalGeneration, LongT5PreTrainedModel, LongT5Model, LongT5ForConditionalGeneration, MT5PreTrainedModel, MT5Model, MT5ForConditionalGeneration, BartPretrainedModel, BartModel, BartForConditionalGeneration, BartForSequenceClassification, MBartPreTrainedModel, MBartModel, MBartForConditionalGeneration, MBartForSequenceClassification, MBartForCausalLM, BlenderbotPreTrainedModel, BlenderbotModel, BlenderbotForConditionalGeneration, BlenderbotSmallPreTrainedModel, BlenderbotSmallModel, BlenderbotSmallForConditionalGeneration, RobertaPreTrainedModel, RobertaModel, RobertaForMaskedLM, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaForQuestionAnswering, XLMPreTrainedModel, XLMModel, XLMWithLMHeadModel, XLMForSequenceClassification, XLMForTokenClassification, XLMForQuestionAnswering, XLMRobertaPreTrainedModel, XLMRobertaModel, XLMRobertaForMaskedLM, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaForQuestionAnswering, ASTPreTrainedModel, ASTModel, ASTForAudioClassification, WhisperPreTrainedModel, WhisperModel, WhisperForConditionalGeneration, VisionEncoderDecoderModel, CLIPPreTrainedModel, CLIPModel, CLIPTextModelWithProjection, CLIPVisionModelWithProjection, SiglipPreTrainedModel, SiglipModel, SiglipTextModel, SiglipVisionModel, ChineseCLIPPreTrainedModel, ChineseCLIPModel, CLIPSegPreTrainedModel, CLIPSegModel, CLIPSegForImageSegmentation, GPT2PreTrainedModel, GPT2Model, GPT2LMHeadModel, GPTNeoPreTrainedModel, GPTNeoModel, GPTNeoForCausalLM, GPTNeoXPreTrainedModel, GPTNeoXModel, GPTNeoXForCausalLM, GPTJPreTrainedModel, GPTJModel, GPTJForCausalLM, GPTBigCodePreTrainedModel, GPTBigCodeModel, GPTBigCodeForCausalLM, CodeGenPreTrainedModel, CodeGenModel, CodeGenForCausalLM, LlamaPreTrainedModel, LlamaModel, LlamaForCausalLM, Qwen2PreTrainedModel, Qwen2Model, Qwen2ForCausalLM, PhiPreTrainedModel, PhiModel, PhiForCausalLM, BloomPreTrainedModel, BloomModel, BloomForCausalLM, MptPreTrainedModel, MptModel, MptForCausalLM, OPTPreTrainedModel, OPTModel, OPTForCausalLM, ViTPreTrainedModel, ViTModel, ViTForImageClassification, FastViTPreTrainedModel, FastViTModel, FastViTForImageClassification, VitMattePreTrainedModel, VitMatteForImageMatting, MobileViTPreTrainedModel, MobileViTModel, MobileViTForImageClassification, MobileViTV2PreTrainedModel, MobileViTV2Model, MobileViTV2ForImageClassification, OwlViTPreTrainedModel, OwlViTModel, OwlViTForObjectDetection, Owlv2PreTrainedModel, Owlv2Model, Owlv2ForObjectDetection, BeitPreTrainedModel, BeitModel, BeitForImageClassification, DetrPreTrainedModel, DetrModel, DetrForObjectDetection, DetrForSegmentation, DetrObjectDetectionOutput, DetrSegmentationOutput, TableTransformerPreTrainedModel, TableTransformerModel, TableTransformerForObjectDetection, TableTransformerObjectDetectionOutput, DeiTPreTrainedModel, DeiTModel, DeiTForImageClassification, ResNetPreTrainedModel, ResNetModel, ResNetForImageClassification, SwinPreTrainedModel, SwinModel, SwinForImageClassification, Swin2SRPreTrainedModel, Swin2SRModel, Swin2SRForImageSuperResolution, DPTPreTrainedModel, DPTModel, DPTForDepthEstimation, DepthAnythingPreTrainedModel, DepthAnythingForDepthEstimation, GLPNPreTrainedModel, GLPNModel, GLPNForDepthEstimation, DonutSwinPreTrainedModel, DonutSwinModel, ConvNextPreTrainedModel, ConvNextModel, ConvNextForImageClassification, ConvNextV2PreTrainedModel, ConvNextV2Model, ConvNextV2ForImageClassification, Dinov2PreTrainedModel, Dinov2Model, Dinov2ForImageClassification, YolosPreTrainedModel, YolosModel, YolosForObjectDetection, YolosObjectDetectionOutput, SamPreTrainedModel, SamModel, SamImageSegmentationOutput, MarianPreTrainedModel, MarianModel, MarianMTModel, M2M100PreTrainedModel, M2M100Model, M2M100ForConditionalGeneration, Wav2Vec2PreTrainedModel, Wav2Vec2Model, Wav2Vec2ForCTC, Wav2Vec2ForSequenceClassification, Wav2Vec2ForAudioFrameClassification, UniSpeechPreTrainedModel, UniSpeechModel, UniSpeechForCTC, UniSpeechForSequenceClassification, UniSpeechSatPreTrainedModel, UniSpeechSatModel, UniSpeechSatForCTC, UniSpeechSatForSequenceClassification, UniSpeechSatForAudioFrameClassification, Wav2Vec2BertPreTrainedModel, Wav2Vec2BertModel, Wav2Vec2BertForCTC, Wav2Vec2BertForSequenceClassification, HubertPreTrainedModel, HubertModel, HubertForCTC, HubertForSequenceClassification, WavLMPreTrainedModel, WavLMModel, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMForAudioFrameClassification, SpeechT5PreTrainedModel, SpeechT5Model, SpeechT5ForSpeechToText, SpeechT5ForTextToSpeech, SpeechT5HifiGan, TrOCRPreTrainedModel, TrOCRForCausalLM, MistralPreTrainedModel, MistralModel, MistralForCausalLM, Starcoder2PreTrainedModel, Starcoder2Model, Starcoder2ForCausalLM, FalconPreTrainedModel, FalconModel, FalconForCausalLM, ClapPreTrainedModel, ClapModel, ClapTextModelWithProjection, ClapAudioModelWithProjection, VitsPreTrainedModel, VitsModel, SegformerPreTrainedModel, SegformerModel, SegformerForImageClassification, SegformerForSemanticSegmentation, StableLmPreTrainedModel, StableLmModel, StableLmForCausalLM, EfficientNetPreTrainedModel, EfficientNetModel, EfficientNetForImageClassification, PretrainedMixin, MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_WITH_LM_HEAD_MAPPING_NAMES, MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_FOR_CTC_MAPPING_NAMES, MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_CLASS_TYPE_MAPPING, CUSTOM_MAPPING, AutoModel, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelForSeq2SeqLM, AutoModelForSpeechSeq2Seq, AutoModelForTextToSpectrogram, AutoModelForTextToWaveform, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForVision2Seq, AutoModelForImageClassification, AutoModelForImageSegmentation, AutoModelForSemanticSegmentation, AutoModelForObjectDetection, AutoModelForZeroShotObjectDetection, AutoModelForMaskGeneration, AutoModelForCTC, AutoModelForAudioClassification, AutoModelForXVector, AutoModelForAudioFrameClassification, AutoModelForDocumentQuestionAnswering, AutoModelForImageMatting, AutoModelForImageToImage, AutoModelForDepthEstimation, AutoModelForImageFeatureExtraction, Seq2SeqLMOutput, SequenceClassifierOutput, XVectorOutput, TokenClassifierOutput, MaskedLMOutput, QuestionAnsweringModelOutput, CausalLMOutput, CausalLMOutputWithPast, ImageMattingOutput, VitsModelOutput;
var init_models = __esm({
"node_modules/@xenova/transformers/src/models.js"() {
init_configs();
init_core();
init_hub();
init_generation();
init_tensor();
init_onnx();
init_transformers();
({ InferenceSession, Tensor: ONNXTensor2, env: env2 } = ONNX);
MODEL_TYPES = {
EncoderOnly: 0,
EncoderDecoder: 1,
Seq2Seq: 2,
Vision2Seq: 3,
DecoderOnly: 4,
MaskGeneration: 5
};
MODEL_TYPE_MAPPING = /* @__PURE__ */ new Map();
MODEL_NAME_TO_CLASS_MAPPING = /* @__PURE__ */ new Map();
MODEL_CLASS_TO_NAME_MAPPING = /* @__PURE__ */ new Map();
PreTrainedModel = class extends Callable {
/**
* 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();
__publicField(this, "main_input_name", "input_ids");
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 {
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];
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([
AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
constructSession(pretrained_model_name_or_path, options.model_file_name ?? "decoder_model_merged", options),
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([
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),
getModelJSON(pretrained_model_name_or_path, "generation_config.json", false, options)
]);
} else if (modelType === MODEL_TYPES.MaskGeneration) {
info = await Promise.all([
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([
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 {
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([
AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
constructSession(pretrained_model_name_or_path, options.model_file_name ?? "model", options)
]);
}
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, logits_processor = null) {
const processors = new LogitsProcessorList();
if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1) {
processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty));
}
if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) {
processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size));
}
if (generation_config.bad_words_ids !== null) {
processors.push(new 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 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 MinNewTokensLengthLogitsProcessor(
input_ids_seq_length,
generation_config.min_new_tokens,
generation_config.eos_token_id
));
}
if (generation_config.forced_bos_token_id !== null) {
processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id));
}
if (generation_config.forced_eos_token_id !== null) {
processors.push(new ForcedEOSTokenLogitsProcessor(
generation_config.max_length,
generation_config.forced_eos_token_id
));
}
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) {
begin_index += generation_config.forced_decoder_ids[generation_config.forced_decoder_ids.length - 1][0];
}
processors.push(new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index));
}
if (generation_config.forced_decoder_ids !== null) {
processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids));
}
if (logits_processor !== null) {
processors.extend(logits_processor);
}
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) {
let gen_config = new GenerationConfig(this.config);
if ("generation_config" in this) {
Object.assign(gen_config, this.generation_config);
}
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_VISION_2_SEQ_MAPPING_NAMES.get(modelType);
if (possibleInfo) {
errorMessage += ` Please use the following class instead: '${possibleInfo[0]}'`;
}
throw Error(errorMessage);
}
if (!(inputs instanceof Tensor) && !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;
if (this.config.is_encoder_decoder) {
input_ids_seq_length = 0;
} else {
input_ids_seq_length = inputs instanceof Tensor ? inputs.dims.at(-1) : inputs.length;
if (input_ids_seq_length === 0) {
throw Error("Must supply a non-empty array of input token ids.");
}
}
generation_config = this._get_generation_config(generation_config);
logits_processor = logits_processor ?? new LogitsProcessorList();
logits_processor = this._get_logits_processor(
generation_config,
input_ids_seq_length,
logits_processor
);
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];
}
let numOutputTokens = 1;
const maxOutputTokens = numOutputTokens + (generation_config.max_new_tokens ?? Infinity);
const useMaxLength = Number.isInteger(generation_config.max_length) && (generation_config.max_new_tokens ?? null) === null;
let sampler = Sampler.getSampler(generation_config);
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) {
newest_beams.push(beam);
continue;
}
if (useMaxLength && beam.output_token_ids.length >= generation_config.max_length) {
beam.done = true;
newest_beams.push(beam);
continue;
}
let output = await this.runBeam(beam);
if (generation_config.output_attentions) {
this.addAttentionsToBeam(beam, output);
}
if (generation_config.output_scores) {
}
let logits = output.logits.slice(null, -1, null);
logits_processor(beam.output_token_ids, logits);
let sampledTokens = sampler(logits);
for (let [newTokenId, logProb] of sampledTokens) {
let newBeam = { ...beam };
this.updateBeam(newBeam, newTokenId);
newBeam.score += logProb;
if (eos_token_ids && eos_token_ids.includes(newTokenId)) {
newBeam.done = true;
}
newest_beams.push(newBeam);
}
}
++numOutputTokens;
newest_beams = this.groupBeams(newest_beams).map(
(group) => group.sort((a, b) => b.score - a.score).slice(0, generation_config.num_beams)
// remove outside beam width
);
beams = newest_beams.flat();
if (generation_config.callback_function) {
generation_config.callback_function(beams);
}
}
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();
const sequences = getFlattened("output_token_ids");
if (generation_config.return_dict_in_generate) {
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) {
const groups = /* @__PURE__ */ Object.create(null);
for (const obj of beams) {
if (groups[obj.id] === void 0) {
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 = /* @__PURE__ */ Object.create(null);
for (const name2 in decoderResults) {
if (name2.startsWith("present")) {
let newName = name2.replace("present", "past_key_values");
if (pastKeyValues && name2.includes("encoder")) {
pkvs[newName] = pastKeyValues[newName];
} else {
pkvs[newName] = decoderResults[name2];
}
}
}
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 = /* @__PURE__ */ Object.create(null);
for (const attnName of ["cross_attentions", "decoder_attentions"]) {
const result = [];
for (const name2 in decoderResults) {
if (name2.startsWith(attnName)) {
const index = name2.split(".").pop();
result[index] = decoderResults[name2];
}
}
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 {
const batch_size = 1;
if (this.config.is_encoder_decoder && (this.add_encoder_pkv ?? true)) {
let encoder_dims = [batch_size, this.num_encoder_heads, 0, this.encoder_dim_kv];
let decoder_dims = [batch_size, this.num_decoder_heads, 0, this.decoder_dim_kv];
for (let i = 0; i < this.num_decoder_layers; ++i) {
decoderFeeds[`past_key_values.${i}.encoder.key`] = new Tensor("float32", [], encoder_dims);
decoderFeeds[`past_key_values.${i}.encoder.value`] = new Tensor("float32", [], encoder_dims);
decoderFeeds[`past_key_values.${i}.decoder.key`] = new Tensor("float32", [], decoder_dims);
decoderFeeds[`past_key_values.${i}.decoder.value`] = new Tensor("float32", [], decoder_dims);
}
} else if (this.config.model_type === "falcon") {
let dims = [batch_size * this.num_heads, 0, this.dim_kv];
for (let i = 0; i < this.num_layers; ++i) {
decoderFeeds[`past_key_values.${i}.key`] = new Tensor("float32", [], dims);
decoderFeeds[`past_key_values.${i}.value`] = new Tensor("float32", [], dims);
}
} else if (this.config.multi_query) {
let dims = [batch_size * this.num_heads, 0, 2 * this.dim_kv];
for (let i = 0; i < this.num_layers; ++i) {
decoderFeeds[`past_key_values.${i}.key_value`] = new Tensor("float32", [], dims);
}
} else if (this.config.model_type === "bloom") {
let keyDims = [batch_size * this.num_heads, this.dim_kv, 0];
let valueDims = [batch_size * this.num_heads, 0, this.dim_kv];
for (let i = 0; i < this.num_layers; ++i) {
decoderFeeds[`past_key_values.${i}.key`] = new Tensor("float32", [], keyDims);
decoderFeeds[`past_key_values.${i}.value`] = new Tensor("float32", [], valueDims);
}
} else {
let dims = [batch_size, this.num_heads, 0, this.dim_kv];
for (let i = 0; i < this.num_layers; ++i) {
decoderFeeds[`past_key_values.${i}.key`] = new Tensor("float32", [], dims);
decoderFeeds[`past_key_values.${i}.value`] = new 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);
}
};
ModelOutput = class {
};
BaseModelOutput = class 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;
}
};
BertPreTrainedModel = class extends PreTrainedModel {
};
BertModel = class extends BertPreTrainedModel {
};
BertForMaskedLM = class 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 = class 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 = class 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 = class 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));
}
};
NomicBertPreTrainedModel = class extends PreTrainedModel {
};
NomicBertModel = class extends NomicBertPreTrainedModel {
};
RoFormerPreTrainedModel = class extends PreTrainedModel {
};
RoFormerModel = class extends RoFormerPreTrainedModel {
};
RoFormerForMaskedLM = class 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));
}
};
RoFormerForSequenceClassification = class 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));
}
};
RoFormerForTokenClassification = class 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));
}
};
RoFormerForQuestionAnswering = class 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));
}
};
ConvBertPreTrainedModel = class extends PreTrainedModel {
};
ConvBertModel = class extends ConvBertPreTrainedModel {
};
ConvBertForMaskedLM = class 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));
}
};
ConvBertForSequenceClassification = class 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));
}
};
ConvBertForTokenClassification = class 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));
}
};
ConvBertForQuestionAnswering = class 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));
}
};
ElectraPreTrainedModel = class extends PreTrainedModel {
};
ElectraModel = class extends ElectraPreTrainedModel {
};
ElectraForMaskedLM = class 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));
}
};
ElectraForSequenceClassification = class 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));
}
};
ElectraForTokenClassification = class 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));
}
};
ElectraForQuestionAnswering = class 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));
}
};
CamembertPreTrainedModel = class extends PreTrainedModel {
};
CamembertModel = class extends CamembertPreTrainedModel {
};
CamembertForMaskedLM = class 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));
}
};
CamembertForSequenceClassification = class 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));
}
};
CamembertForTokenClassification = class 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));
}
};
CamembertForQuestionAnswering = class 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));
}
};
DebertaPreTrainedModel = class extends PreTrainedModel {
};
DebertaModel = class extends DebertaPreTrainedModel {
};
DebertaForMaskedLM = class 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));
}
};
DebertaForSequenceClassification = class 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));
}
};
DebertaForTokenClassification = class 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));
}
};
DebertaForQuestionAnswering = class 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));
}
};
DebertaV2PreTrainedModel = class extends PreTrainedModel {
};
DebertaV2Model = class extends DebertaV2PreTrainedModel {
};
DebertaV2ForMaskedLM = class 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));
}
};
DebertaV2ForSequenceClassification = class 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));
}
};
DebertaV2ForTokenClassification = class 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));
}
};
DebertaV2ForQuestionAnswering = class 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));
}
};
DistilBertPreTrainedModel = class extends PreTrainedModel {
};
DistilBertModel = class extends DistilBertPreTrainedModel {
};
DistilBertForSequenceClassification = class 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 = class 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 = class 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 = class 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));
}
};
EsmPreTrainedModel = class extends PreTrainedModel {
};
EsmModel = class extends EsmPreTrainedModel {
};
EsmForMaskedLM = class 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));
}
};
EsmForSequenceClassification = class 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));
}
};
EsmForTokenClassification = class 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));
}
};
MobileBertPreTrainedModel = class extends PreTrainedModel {
};
MobileBertModel = class extends MobileBertPreTrainedModel {
};
MobileBertForMaskedLM = class 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));
}
};
MobileBertForSequenceClassification = class 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));
}
};
MobileBertForQuestionAnswering = class 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));
}
};
MPNetPreTrainedModel = class extends PreTrainedModel {
};
MPNetModel = class extends MPNetPreTrainedModel {
};
MPNetForMaskedLM = class 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 = class 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 = class 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 = class 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));
}
};
SqueezeBertPreTrainedModel = class extends PreTrainedModel {
};
SqueezeBertModel = class extends SqueezeBertPreTrainedModel {
};
SqueezeBertForMaskedLM = class 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));
}
};
SqueezeBertForSequenceClassification = class 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));
}
};
SqueezeBertForQuestionAnswering = class 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));
}
};
AlbertPreTrainedModel = class extends PreTrainedModel {
};
AlbertModel = class extends AlbertPreTrainedModel {
};
AlbertForSequenceClassification = class 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));
}
};
AlbertForQuestionAnswering = class 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));
}
};
AlbertForMaskedLM = class 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));
}
};
T5PreTrainedModel = class extends PreTrainedModel {
};
T5Model = class extends T5PreTrainedModel {
};
T5ForConditionalGeneration = class 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;
}
};
LongT5PreTrainedModel = class extends PreTrainedModel {
};
LongT5Model = class extends LongT5PreTrainedModel {
};
LongT5ForConditionalGeneration = class 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;
}
};
MT5PreTrainedModel = class extends PreTrainedModel {
};
MT5Model = class extends MT5PreTrainedModel {
};
MT5ForConditionalGeneration = class 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;
}
};
BartPretrainedModel = class extends PreTrainedModel {
};
BartModel = class extends BartPretrainedModel {
};
BartForConditionalGeneration = class 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;
}
};
BartForSequenceClassification = class 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));
}
};
MBartPreTrainedModel = class extends PreTrainedModel {
};
MBartModel = class extends MBartPreTrainedModel {
};
MBartForConditionalGeneration = class 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;
}
};
MBartForSequenceClassification = class 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));
}
};
MBartForCausalLM = class 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;
}
};
BlenderbotPreTrainedModel = class extends PreTrainedModel {
};
BlenderbotModel = class extends BlenderbotPreTrainedModel {
};
BlenderbotForConditionalGeneration = class 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;
}
};
BlenderbotSmallPreTrainedModel = class extends PreTrainedModel {
};
BlenderbotSmallModel = class extends BlenderbotSmallPreTrainedModel {
};
BlenderbotSmallForConditionalGeneration = class 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;
}
};
RobertaPreTrainedModel = class extends PreTrainedModel {
};
RobertaModel = class extends RobertaPreTrainedModel {
};
RobertaForMaskedLM = class 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 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 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 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));
}
};
XLMPreTrainedModel = class extends PreTrainedModel {
};
XLMModel = class extends XLMPreTrainedModel {
};
XLMWithLMHeadModel = class 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));
}
};
XLMForSequenceClassification = class 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));
}
};
XLMForTokenClassification = class 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));
}
};
XLMForQuestionAnswering = class 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));
}
};
XLMRobertaPreTrainedModel = class extends PreTrainedModel {
};
XLMRobertaModel = class extends XLMRobertaPreTrainedModel {
};
XLMRobertaForMaskedLM = class 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 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 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 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));
}
};
ASTPreTrainedModel = class extends PreTrainedModel {
};
ASTModel = class extends ASTPreTrainedModel {
};
ASTForAudioClassification = class extends ASTPreTrainedModel {
};
WhisperPreTrainedModel = class extends PreTrainedModel {
};
WhisperModel = class extends WhisperPreTrainedModel {
};
WhisperForConditionalGeneration = class extends WhisperPreTrainedModel {
/**
* 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);
__publicField(this, "requires_attention_mask", false);
__publicField(this, "main_input_name", "input_features");
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) {
generation_config = this._get_generation_config(generation_config);
generation_config.return_timestamps ?? (generation_config.return_timestamps = false);
if (generation_config.return_timestamps) {
logits_processor = [new 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 === void 0) {
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) => {
let cross_attentions = Array.from(
{ length: this.config.decoder_layers },
(_, i) => cat(batch.map((x) => x[i]), 2)
);
let weights = 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] = std_mean(weights, -2, 0, true);
let smoothedWeights = weights.clone();
for (let a = 0; a < smoothedWeights.dims[0]; ++a) {
let aTensor = smoothedWeights[a];
for (let b = 0; b < aTensor.dims[0]; ++b) {
let bTensor = aTensor[b];
const stdTensor = std[a][b][0];
const meanTensor = calculatedMean[a][b][0];
for (let c = 0; c < bTensor.dims[0]; ++c) {
let cTensor = bTensor[c];
for (let d = 0; d < cTensor.data.length; ++d) {
cTensor.data[d] = (cTensor.data[d] - meanTensor.data[d]) / stdTensor.data[d];
}
cTensor.data.set(medianFilter(cTensor.data, median_filter_width));
}
}
}
const matrix = mean(smoothedWeights, 1);
return matrix;
});
const timestampsShape = [generate_outputs.sequences.length, generate_outputs.sequences[0].length];
const timestamps = new Tensor(
"float32",
new Float32Array(timestampsShape[0] * timestampsShape[1]),
timestampsShape
);
for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) {
const matrix = batchedMatrices[batch_idx].neg().squeeze_(0);
let [text_indices, time_indices] = dynamicTimeWarping(matrix);
let diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]);
let jumps = mergeArrays([1], diffs).map((x) => !!x);
let jump_times = [];
for (let i = 0; i < jumps.length; ++i) {
if (jumps[i]) {
jump_times.push(time_indices[i] * time_precision);
}
}
timestamps[batch_idx].data.set(jump_times, 1);
}
return timestamps;
}
};
VisionEncoderDecoderModel = class extends PreTrainedModel {
/**
* 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);
__publicField(this, "main_input_name", "pixel_values");
this.decoder_merged_session = decoder_merged_session;
this.generation_config = generation_config;
const encoderConfig = this.config.encoder;
const decoderConfig = this.config.decoder;
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.`);
}
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}"`);
}
const decoderModelClass = decoderModel[1];
const decoder = new decoderModelClass(decoderConfig, decoder_merged_session, generation_config);
this.add_encoder_pkv = "num_decoder_layers" in decoder;
if (this.add_encoder_pkv) {
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 {
this.num_layers = decoder.num_layers;
this.num_heads = decoder.num_heads;
this.dim_kv = decoder.dim_kv;
}
}
};
CLIPPreTrainedModel = class extends PreTrainedModel {
};
CLIPModel = class extends CLIPPreTrainedModel {
};
CLIPTextModelWithProjection = class extends CLIPPreTrainedModel {
/** @type {PreTrainedModel.from_pretrained} */
static async from_pretrained(pretrained_model_name_or_path, options = {}) {
options.model_file_name ?? (options.model_file_name = "text_model");
return super.from_pretrained(pretrained_model_name_or_path, options);
}
};
CLIPVisionModelWithProjection = class extends CLIPPreTrainedModel {
/** @type {PreTrainedModel.from_pretrained} */
static async from_pretrained(pretrained_model_name_or_path, options = {}) {
options.model_file_name ?? (options.model_file_name = "vision_model");
return super.from_pretrained(pretrained_model_name_or_path, options);
}
};
SiglipPreTrainedModel = class extends PreTrainedModel {
};
SiglipModel = class extends SiglipPreTrainedModel {
};
SiglipTextModel = class extends SiglipPreTrainedModel {
/** @type {PreTrainedModel.from_pretrained} */
static async from_pretrained(pretrained_model_name_or_path, options = {}) {
options.model_file_name ?? (options.model_file_name = "text_model");
return super.from_pretrained(pretrained_model_name_or_path, options);
}
};
SiglipVisionModel = class extends CLIPPreTrainedModel {
/** @type {PreTrainedModel.from_pretrained} */
static async from_pretrained(pretrained_model_name_or_path, options = {}) {
options.model_file_name ?? (options.model_file_name = "vision_model");
return super.from_pretrained(pretrained_model_name_or_path, options);
}
};
ChineseCLIPPreTrainedModel = class extends PreTrainedModel {
};
ChineseCLIPModel = class extends ChineseCLIPPreTrainedModel {
};
CLIPSegPreTrainedModel = class extends PreTrainedModel {
};
CLIPSegModel = class extends CLIPSegPreTrainedModel {
};
CLIPSegForImageSegmentation = class extends CLIPSegPreTrainedModel {
};
GPT2PreTrainedModel = class 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;
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;
}
};
GPT2Model = class extends GPT2PreTrainedModel {
};
GPT2LMHeadModel = class extends GPT2PreTrainedModel {
};
GPTNeoPreTrainedModel = class 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;
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;
}
};
GPTNeoModel = class extends GPTNeoPreTrainedModel {
};
GPTNeoForCausalLM = class extends GPTNeoPreTrainedModel {
};
GPTNeoXPreTrainedModel = class 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;
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;
}
};
GPTNeoXModel = class extends GPTNeoXPreTrainedModel {
};
GPTNeoXForCausalLM = class extends GPTNeoXPreTrainedModel {
};
GPTJPreTrainedModel = class 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;
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;
}
};
GPTJModel = class extends GPTJPreTrainedModel {
};
GPTJForCausalLM = class extends GPTJPreTrainedModel {
};
GPTBigCodePreTrainedModel = class 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;
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;
}
};
GPTBigCodeModel = class extends GPTBigCodePreTrainedModel {
};
GPTBigCodeForCausalLM = class extends GPTBigCodePreTrainedModel {
};
CodeGenPreTrainedModel = class 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;
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 = class extends CodeGenPreTrainedModel {
};
CodeGenForCausalLM = class extends CodeGenPreTrainedModel {
};
LlamaPreTrainedModel = class 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;
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;
}
};
LlamaModel = class extends LlamaPreTrainedModel {
};
LlamaForCausalLM = class extends LlamaPreTrainedModel {
};
Qwen2PreTrainedModel = class 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;
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;
}
};
Qwen2Model = class extends Qwen2PreTrainedModel {
};
Qwen2ForCausalLM = class extends Qwen2PreTrainedModel {
};
PhiPreTrainedModel = class 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;
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;
}
};
PhiModel = class extends PhiPreTrainedModel {
};
PhiForCausalLM = class extends PhiPreTrainedModel {
};
BloomPreTrainedModel = class 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;
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;
}
};
BloomModel = class extends BloomPreTrainedModel {
};
BloomForCausalLM = class extends BloomPreTrainedModel {
};
MptPreTrainedModel = class 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;
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;
}
};
MptModel = class extends MptPreTrainedModel {
};
MptForCausalLM = class extends MptPreTrainedModel {
};
OPTPreTrainedModel = class 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;
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;
}
};
OPTModel = class extends OPTPreTrainedModel {
};
OPTForCausalLM = class extends OPTPreTrainedModel {
};
ViTPreTrainedModel = class extends PreTrainedModel {
};
ViTModel = class extends ViTPreTrainedModel {
};
ViTForImageClassification = class extends ViTPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
FastViTPreTrainedModel = class extends PreTrainedModel {
};
FastViTModel = class extends FastViTPreTrainedModel {
};
FastViTForImageClassification = class extends FastViTPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
VitMattePreTrainedModel = class extends PreTrainedModel {
};
VitMatteForImageMatting = class extends VitMattePreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new ImageMattingOutput(await super._call(model_inputs));
}
};
MobileViTPreTrainedModel = class extends PreTrainedModel {
};
MobileViTModel = class extends MobileViTPreTrainedModel {
};
MobileViTForImageClassification = class extends MobileViTPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
MobileViTV2PreTrainedModel = class extends PreTrainedModel {
};
MobileViTV2Model = class extends MobileViTV2PreTrainedModel {
};
MobileViTV2ForImageClassification = class extends MobileViTV2PreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
OwlViTPreTrainedModel = class extends PreTrainedModel {
};
OwlViTModel = class extends OwlViTPreTrainedModel {
};
OwlViTForObjectDetection = class extends OwlViTPreTrainedModel {
};
Owlv2PreTrainedModel = class extends PreTrainedModel {
};
Owlv2Model = class extends Owlv2PreTrainedModel {
};
Owlv2ForObjectDetection = class extends Owlv2PreTrainedModel {
};
BeitPreTrainedModel = class extends PreTrainedModel {
};
BeitModel = class extends BeitPreTrainedModel {
};
BeitForImageClassification = class extends BeitPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
DetrPreTrainedModel = class extends PreTrainedModel {
};
DetrModel = class extends DetrPreTrainedModel {
};
DetrForObjectDetection = class extends DetrPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new DetrObjectDetectionOutput(await super._call(model_inputs));
}
};
DetrForSegmentation = class 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));
}
};
DetrObjectDetectionOutput = class 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;
}
};
DetrSegmentationOutput = class 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;
}
};
TableTransformerPreTrainedModel = class extends PreTrainedModel {
};
TableTransformerModel = class extends TableTransformerPreTrainedModel {
};
TableTransformerForObjectDetection = class extends TableTransformerPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new TableTransformerObjectDetectionOutput(await super._call(model_inputs));
}
};
TableTransformerObjectDetectionOutput = class extends DetrObjectDetectionOutput {
};
DeiTPreTrainedModel = class extends PreTrainedModel {
};
DeiTModel = class extends DeiTPreTrainedModel {
};
DeiTForImageClassification = class extends DeiTPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
ResNetPreTrainedModel = class extends PreTrainedModel {
};
ResNetModel = class extends ResNetPreTrainedModel {
};
ResNetForImageClassification = class extends ResNetPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
SwinPreTrainedModel = class extends PreTrainedModel {
};
SwinModel = class extends SwinPreTrainedModel {
};
SwinForImageClassification = class extends SwinPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
Swin2SRPreTrainedModel = class extends PreTrainedModel {
};
Swin2SRModel = class extends Swin2SRPreTrainedModel {
};
Swin2SRForImageSuperResolution = class extends Swin2SRPreTrainedModel {
};
DPTPreTrainedModel = class extends PreTrainedModel {
};
DPTModel = class extends DPTPreTrainedModel {
};
DPTForDepthEstimation = class extends DPTPreTrainedModel {
};
DepthAnythingPreTrainedModel = class extends PreTrainedModel {
};
DepthAnythingForDepthEstimation = class extends DepthAnythingPreTrainedModel {
};
GLPNPreTrainedModel = class extends PreTrainedModel {
};
GLPNModel = class extends GLPNPreTrainedModel {
};
GLPNForDepthEstimation = class extends GLPNPreTrainedModel {
};
DonutSwinPreTrainedModel = class extends PreTrainedModel {
};
DonutSwinModel = class extends DonutSwinPreTrainedModel {
};
ConvNextPreTrainedModel = class extends PreTrainedModel {
};
ConvNextModel = class extends ConvNextPreTrainedModel {
};
ConvNextForImageClassification = class extends ConvNextPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
ConvNextV2PreTrainedModel = class extends PreTrainedModel {
};
ConvNextV2Model = class extends ConvNextV2PreTrainedModel {
};
ConvNextV2ForImageClassification = class extends ConvNextV2PreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
Dinov2PreTrainedModel = class extends PreTrainedModel {
};
Dinov2Model = class extends Dinov2PreTrainedModel {
};
Dinov2ForImageClassification = class extends Dinov2PreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
YolosPreTrainedModel = class extends PreTrainedModel {
};
YolosModel = class extends YolosPreTrainedModel {
};
YolosForObjectDetection = class extends YolosPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new YolosObjectDetectionOutput(await super._call(model_inputs));
}
};
YolosObjectDetectionOutput = class 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;
}
};
SamPreTrainedModel = class extends PreTrainedModel {
};
SamModel = class 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 }) {
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) {
model_inputs = {
...model_inputs,
...await this.get_image_embeddings(model_inputs)
};
}
if (!model_inputs.input_labels) {
const shape = model_inputs.input_points.dims.slice(0, -1);
const numElements = shape.reduce((a, b) => a * b, 1);
model_inputs.input_labels = new Tensor(
"int64",
new BigInt64Array(numElements).fill(1n),
shape
);
}
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));
}
};
SamImageSegmentationOutput = class 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;
}
};
MarianPreTrainedModel = class extends PreTrainedModel {
};
MarianModel = class extends MarianPreTrainedModel {
};
MarianMTModel = class 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;
}
};
M2M100PreTrainedModel = class extends PreTrainedModel {
};
M2M100Model = class extends M2M100PreTrainedModel {
};
M2M100ForConditionalGeneration = class 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;
}
};
Wav2Vec2PreTrainedModel = class extends PreTrainedModel {
};
Wav2Vec2Model = class extends Wav2Vec2PreTrainedModel {
};
Wav2Vec2ForCTC = class 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));
}
};
Wav2Vec2ForSequenceClassification = class 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));
}
};
Wav2Vec2ForAudioFrameClassification = class 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));
}
};
UniSpeechPreTrainedModel = class extends PreTrainedModel {
};
UniSpeechModel = class extends UniSpeechPreTrainedModel {
};
UniSpeechForCTC = class 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));
}
};
UniSpeechForSequenceClassification = class 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));
}
};
UniSpeechSatPreTrainedModel = class extends PreTrainedModel {
};
UniSpeechSatModel = class extends UniSpeechSatPreTrainedModel {
};
UniSpeechSatForCTC = class 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));
}
};
UniSpeechSatForSequenceClassification = class 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));
}
};
UniSpeechSatForAudioFrameClassification = class 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));
}
};
Wav2Vec2BertPreTrainedModel = class extends PreTrainedModel {
};
Wav2Vec2BertModel = class extends Wav2Vec2BertPreTrainedModel {
};
Wav2Vec2BertForCTC = class 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));
}
};
Wav2Vec2BertForSequenceClassification = class 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));
}
};
HubertPreTrainedModel = class extends PreTrainedModel {
};
HubertModel = class extends Wav2Vec2PreTrainedModel {
};
HubertForCTC = class 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));
}
};
HubertForSequenceClassification = class 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));
}
};
WavLMPreTrainedModel = class extends PreTrainedModel {
};
WavLMModel = class extends WavLMPreTrainedModel {
};
WavLMForCTC = class 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));
}
};
WavLMForSequenceClassification = class 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));
}
};
WavLMForXVector = class 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));
}
};
WavLMForAudioFrameClassification = class 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));
}
};
SpeechT5PreTrainedModel = class extends PreTrainedModel {
};
SpeechT5Model = class extends SpeechT5PreTrainedModel {
};
SpeechT5ForSpeechToText = class extends SpeechT5PreTrainedModel {
};
SpeechT5ForTextToSpeech = class 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,
maxlenratio = 20,
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 Tensor(
"float32",
new Float32Array(num_mel_bins),
[1, 1, num_mel_bins]
);
}
let decoderFeeds = {
use_cache_branch,
output_sequence,
encoder_attention_mask,
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 spectrogram2 = cat(spectrogramParts);
const { waveform } = await sessionRun(vocoder.session, { spectrogram: spectrogram2 });
return {
spectrogram: spectrogram2,
waveform
// cross_attentions: null, // TODO add
};
}
};
SpeechT5HifiGan = class extends PreTrainedModel {
constructor() {
super(...arguments);
__publicField(this, "main_input_name", "spectrogram");
}
};
TrOCRPreTrainedModel = class 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;
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;
}
};
TrOCRForCausalLM = class extends TrOCRPreTrainedModel {
};
MistralPreTrainedModel = class 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;
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;
}
};
MistralModel = class extends MistralPreTrainedModel {
};
MistralForCausalLM = class extends MistralPreTrainedModel {
};
Starcoder2PreTrainedModel = class 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;
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;
}
};
Starcoder2Model = class extends Starcoder2PreTrainedModel {
};
Starcoder2ForCausalLM = class extends Starcoder2PreTrainedModel {
};
FalconPreTrainedModel = class 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;
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;
}
};
FalconModel = class extends FalconPreTrainedModel {
};
FalconForCausalLM = class extends FalconPreTrainedModel {
};
ClapPreTrainedModel = class extends PreTrainedModel {
};
ClapModel = class extends ClapPreTrainedModel {
};
ClapTextModelWithProjection = class extends ClapPreTrainedModel {
/** @type {PreTrainedModel.from_pretrained} */
static async from_pretrained(pretrained_model_name_or_path, options = {}) {
options.model_file_name ?? (options.model_file_name = "text_model");
return super.from_pretrained(pretrained_model_name_or_path, options);
}
};
ClapAudioModelWithProjection = class extends ClapPreTrainedModel {
/** @type {PreTrainedModel.from_pretrained} */
static async from_pretrained(pretrained_model_name_or_path, options = {}) {
options.model_file_name ?? (options.model_file_name = "audio_model");
return super.from_pretrained(pretrained_model_name_or_path, options);
}
};
VitsPreTrainedModel = class extends PreTrainedModel {
};
VitsModel = class 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));
}
};
SegformerPreTrainedModel = class extends PreTrainedModel {
};
SegformerModel = class extends SegformerPreTrainedModel {
};
SegformerForImageClassification = class extends SegformerPreTrainedModel {
};
SegformerForSemanticSegmentation = class extends SegformerPreTrainedModel {
};
StableLmPreTrainedModel = class 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;
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;
}
};
StableLmModel = class extends StableLmPreTrainedModel {
};
StableLmForCausalLM = class extends StableLmPreTrainedModel {
};
EfficientNetPreTrainedModel = class extends PreTrainedModel {
};
EfficientNetModel = class extends EfficientNetPreTrainedModel {
};
EfficientNetForImageClassification = class extends EfficientNetPreTrainedModel {
/**
* @param {any} model_inputs
*/
async _call(model_inputs) {
return new SequenceClassifierOutput(await super._call(model_inputs));
}
};
PretrainedMixin = class {
/** @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 AutoConfig.from_pretrained(pretrained_model_name_or_path, options);
if (!options.config) {
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;
}
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}`);
}
}
};
/**
* Mapping from model type to model class.
* @type {Map<string, Object>[]}
*/
__publicField(PretrainedMixin, "MODEL_CLASS_MAPPINGS", null);
/**
* Whether to attempt to instantiate the base class (`PretrainedModel`) if
* the model type is not found in the mapping.
*/
__publicField(PretrainedMixin, "BASE_IF_FAIL", false);
MODEL_MAPPING_NAMES_ENCODER_ONLY = /* @__PURE__ */ 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]]
]);
MODEL_MAPPING_NAMES_ENCODER_DECODER = /* @__PURE__ */ 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]]
]);
MODEL_MAPPING_NAMES_DECODER_ONLY = /* @__PURE__ */ 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]]
]);
MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([
["speecht5", ["SpeechT5ForSpeechToText", SpeechT5ForSpeechToText]],
["whisper", ["WhisperForConditionalGeneration", WhisperForConditionalGeneration]]
]);
MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = /* @__PURE__ */ new Map([
["speecht5", ["SpeechT5ForTextToSpeech", SpeechT5ForTextToSpeech]]
]);
MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = /* @__PURE__ */ new Map([
["vits", ["VitsModel", VitsModel]]
]);
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ 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]]
]);
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ 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]]
]);
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = /* @__PURE__ */ 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]]
]);
MODEL_WITH_LM_HEAD_MAPPING_NAMES = /* @__PURE__ */ 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]]
]);
MODEL_FOR_MASKED_LM_MAPPING_NAMES = /* @__PURE__ */ 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]]
]);
MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ 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]]
]);
MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([
["vision-encoder-decoder", ["VisionEncoderDecoderModel", VisionEncoderDecoderModel]]
]);
MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([
["vision-encoder-decoder", ["VisionEncoderDecoderModel", VisionEncoderDecoderModel]]
]);
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ 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]]
]);
MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([
["detr", ["DetrForObjectDetection", DetrForObjectDetection]],
["table-transformer", ["TableTransformerForObjectDetection", TableTransformerForObjectDetection]],
["yolos", ["YolosForObjectDetection", YolosForObjectDetection]]
]);
MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([
["owlvit", ["OwlViTForObjectDetection", OwlViTForObjectDetection]],
["owlv2", ["Owlv2ForObjectDetection", Owlv2ForObjectDetection]]
]);
MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
["detr", ["DetrForSegmentation", DetrForSegmentation]],
["clipseg", ["CLIPSegForImageSegmentation", CLIPSegForImageSegmentation]]
]);
MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
["segformer", ["SegformerForSemanticSegmentation", SegformerForSemanticSegmentation]]
]);
MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
["sam", ["SamModel", SamModel]]
]);
MODEL_FOR_CTC_MAPPING_NAMES = /* @__PURE__ */ new Map([
["wav2vec2", ["Wav2Vec2ForCTC", Wav2Vec2ForCTC]],
["wav2vec2-bert", ["Wav2Vec2BertForCTC", Wav2Vec2BertForCTC]],
["unispeech", ["UniSpeechForCTC", UniSpeechForCTC]],
["unispeech-sat", ["UniSpeechSatForCTC", UniSpeechSatForCTC]],
["wavlm", ["WavLMForCTC", WavLMForCTC]],
["hubert", ["HubertForCTC", HubertForCTC]]
]);
MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ 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]]
]);
MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = /* @__PURE__ */ new Map([
["wavlm", ["WavLMForXVector", WavLMForXVector]]
]);
MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
["unispeech-sat", ["UniSpeechSatForAudioFrameClassification", UniSpeechSatForAudioFrameClassification]],
["wavlm", ["WavLMForAudioFrameClassification", WavLMForAudioFrameClassification]],
["wav2vec2", ["Wav2Vec2ForAudioFrameClassification", Wav2Vec2ForAudioFrameClassification]]
]);
MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = /* @__PURE__ */ new Map([
["vitmatte", ["VitMatteForImageMatting", VitMatteForImageMatting]]
]);
MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = /* @__PURE__ */ new Map([
["swin2sr", ["Swin2SRForImageSuperResolution", Swin2SRForImageSuperResolution]]
]);
MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
["dpt", ["DPTForDepthEstimation", DPTForDepthEstimation]],
["depth_anything", ["DepthAnythingForDepthEstimation", DepthAnythingForDepthEstimation]],
["glpn", ["GLPNForDepthEstimation", GLPNForDepthEstimation]]
]);
MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = /* @__PURE__ */ new Map([
["clip", ["CLIPVisionModelWithProjection", CLIPVisionModelWithProjection]],
["siglip", ["SiglipVisionModel", SiglipVisionModel]]
]);
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) {
for (const [name2, model] of mappings.values()) {
MODEL_TYPE_MAPPING.set(name2, type);
MODEL_CLASS_TO_NAME_MAPPING.set(model, name2);
MODEL_NAME_TO_CLASS_MAPPING.set(name2, model);
}
}
CUSTOM_MAPPING = [
["CLIPTextModelWithProjection", CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly],
["SiglipTextModel", SiglipTextModel, MODEL_TYPES.EncoderOnly],
["ClapTextModelWithProjection", ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly],
["ClapAudioModelWithProjection", ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly]
];
for (const [name2, model, type] of CUSTOM_MAPPING) {
MODEL_TYPE_MAPPING.set(name2, type);
MODEL_CLASS_TO_NAME_MAPPING.set(model, name2);
MODEL_NAME_TO_CLASS_MAPPING.set(name2, model);
}
AutoModel = class extends PretrainedMixin {
};
/** @type {Map<string, Object>[]} */
// @ts-ignore
__publicField(AutoModel, "MODEL_CLASS_MAPPINGS", MODEL_CLASS_TYPE_MAPPING.map((x) => x[0]));
__publicField(AutoModel, "BASE_IF_FAIL", true);
AutoModelForSequenceClassification = class extends PretrainedMixin {
};
__publicField(AutoModelForSequenceClassification, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]);
AutoModelForTokenClassification = class extends PretrainedMixin {
};
__publicField(AutoModelForTokenClassification, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]);
AutoModelForSeq2SeqLM = class extends PretrainedMixin {
};
__publicField(AutoModelForSeq2SeqLM, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]);
AutoModelForSpeechSeq2Seq = class extends PretrainedMixin {
};
__publicField(AutoModelForSpeechSeq2Seq, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]);
AutoModelForTextToSpectrogram = class extends PretrainedMixin {
};
__publicField(AutoModelForTextToSpectrogram, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]);
AutoModelForTextToWaveform = class extends PretrainedMixin {
};
__publicField(AutoModelForTextToWaveform, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]);
AutoModelForCausalLM = class extends PretrainedMixin {
};
__publicField(AutoModelForCausalLM, "MODEL_CLASS_MAPPINGS", [MODEL_WITH_LM_HEAD_MAPPING_NAMES]);
AutoModelForMaskedLM = class extends PretrainedMixin {
};
__publicField(AutoModelForMaskedLM, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_MASKED_LM_MAPPING_NAMES]);
AutoModelForQuestionAnswering = class extends PretrainedMixin {
};
__publicField(AutoModelForQuestionAnswering, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]);
AutoModelForVision2Seq = class extends PretrainedMixin {
};
__publicField(AutoModelForVision2Seq, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]);
AutoModelForImageClassification = class extends PretrainedMixin {
};
__publicField(AutoModelForImageClassification, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]);
AutoModelForImageSegmentation = class extends PretrainedMixin {
};
__publicField(AutoModelForImageSegmentation, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]);
AutoModelForSemanticSegmentation = class extends PretrainedMixin {
};
__publicField(AutoModelForSemanticSegmentation, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]);
AutoModelForObjectDetection = class extends PretrainedMixin {
};
__publicField(AutoModelForObjectDetection, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]);
AutoModelForZeroShotObjectDetection = class extends PretrainedMixin {
};
__publicField(AutoModelForZeroShotObjectDetection, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]);
AutoModelForMaskGeneration = class extends PretrainedMixin {
};
__publicField(AutoModelForMaskGeneration, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]);
AutoModelForCTC = class extends PretrainedMixin {
};
__publicField(AutoModelForCTC, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_CTC_MAPPING_NAMES]);
AutoModelForAudioClassification = class extends PretrainedMixin {
};
__publicField(AutoModelForAudioClassification, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]);
AutoModelForXVector = class extends PretrainedMixin {
};
__publicField(AutoModelForXVector, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]);
AutoModelForAudioFrameClassification = class extends PretrainedMixin {
};
__publicField(AutoModelForAudioFrameClassification, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]);
AutoModelForDocumentQuestionAnswering = class extends PretrainedMixin {
};
__publicField(AutoModelForDocumentQuestionAnswering, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]);
AutoModelForImageMatting = class extends PretrainedMixin {
};
__publicField(AutoModelForImageMatting, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]);
AutoModelForImageToImage = class extends PretrainedMixin {
};
__publicField(AutoModelForImageToImage, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]);
AutoModelForDepthEstimation = class extends PretrainedMixin {
};
__publicField(AutoModelForDepthEstimation, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]);
AutoModelForImageFeatureExtraction = class extends PretrainedMixin {
};
__publicField(AutoModelForImageFeatureExtraction, "MODEL_CLASS_MAPPINGS", [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]);
Seq2SeqLMOutput = class 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;
}
};
SequenceClassifierOutput = class 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;
}
};
XVectorOutput = class 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;
}
};
TokenClassifierOutput = class extends ModelOutput {
/**
* @param {Object} output The output of the model.
* @param {Tensor} output.logits Classification scores (before SoftMax).
*/
constructor({ logits }) {
super();
this.logits = logits;
}
};
MaskedLMOutput = class 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;
}
};
QuestionAnsweringModelOutput = class 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;
}
};
CausalLMOutput = class 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;
}
};
CausalLMOutputWithPast = class 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;
}
};
ImageMattingOutput = class 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;
}
};
VitsModelOutput = class 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: spectrogram2 }) {
super();
this.waveform = waveform;
this.spectrogram = spectrogram2;
}
};
}
});
// stub:sharp
var require_sharp = __commonJS({
"stub:sharp"(exports2, module2) {
module2.exports = {};
}
});
// node_modules/@xenova/transformers/src/utils/image.js
var import_sharp, BROWSER_ENV, WEBWORKER_ENV, createCanvasFunction, ImageDataClass, loadImageFunction, RESAMPLING_MAPPING, CONTENT_TYPE_MAP, RawImage;
var init_image = __esm({
"node_modules/@xenova/transformers/src/utils/image.js"() {
init_hub();
init_env();
init_tensor();
import_sharp = __toESM(require_sharp(), 1);
BROWSER_ENV = typeof self !== "undefined";
WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === "DedicatedWorkerGlobalScope";
if (BROWSER_ENV) {
createCanvasFunction = (width, 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 (import_sharp.default) {
loadImageFunction = async (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 !== void 0 && rawChannels !== info.channels) {
newImage.convert(rawChannels);
}
return newImage;
};
} else {
throw new Error("Unable to load image processing library.");
}
RESAMPLING_MAPPING = {
0: "nearest",
1: "lanczos",
2: "bilinear",
3: "bicubic",
4: "box",
5: "hamming"
};
CONTENT_TYPE_MAP = /* @__PURE__ */ new Map([
["png", "image/png"],
["jpg", "image/jpeg"],
["jpeg", "image/jpeg"],
["gif", "image/gif"]
]);
RawImage = 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(url2) {
let response = await getFile(url2);
if (response.status !== 200) {
throw new Error(`Unable to read image from "${url2}" (${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) {
let img = await loadImageFunction(blob);
const ctx = createCanvasFunction(img.width, img.height).getContext("2d");
ctx.drawImage(img, 0, 0);
return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4);
} else {
let img = (0, import_sharp.default)(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") {
} 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:
case 4:
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.587 * green + 0.114 * 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:
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:
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:
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:
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
} = {}) {
let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample;
if (BROWSER_ENV) {
let numChannels = this.channels;
let canvas = this.toCanvas();
const ctx = createCanvasFunction(width, height).getContext("2d");
ctx.drawImage(canvas, 0, 0, width, height);
let resizedImage = new _RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4);
return resizedImage.convert(numChannels);
} else {
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":
img = img.affine([width / this.width, 0, 0, height / this.height], {
interpolator: resampleMethod
});
break;
case "lanczos":
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) {
return this;
}
if (BROWSER_ENV) {
let numChannels = this.channels;
let canvas = this.toCanvas();
let newWidth = this.width + left + right;
let newHeight = this.height + top + bottom;
const ctx = createCanvasFunction(newWidth, newHeight).getContext("2d");
ctx.drawImage(
canvas,
0,
0,
this.width,
this.height,
left,
top,
newWidth,
newHeight
);
let paddedImage = new _RawImage(
ctx.getImageData(0, 0, newWidth, newHeight).data,
newWidth,
newHeight,
4
);
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]) {
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);
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) {
const numChannels = this.channels;
const canvas = this.toCanvas();
const ctx = createCanvasFunction(crop_width, crop_height).getContext("2d");
ctx.drawImage(
canvas,
x_min,
y_min,
crop_width,
crop_height,
0,
0,
crop_width,
crop_height
);
const resizedImage = new _RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);
return resizedImage.convert(numChannels);
} else {
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 (this.width === crop_width && this.height === crop_height) {
return this;
}
let width_offset = (this.width - crop_width) / 2;
let height_offset = (this.height - crop_height) / 2;
if (BROWSER_ENV) {
let numChannels = this.channels;
let canvas = this.toCanvas();
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;
}
ctx.drawImage(
canvas,
sourceX,
sourceY,
crop_width,
crop_height,
destX,
destY,
crop_width,
crop_height
);
let resizedImage = new _RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);
return resizedImage.convert(numChannels);
} else {
let img = this.toSharp();
if (width_offset >= 0 && height_offset >= 0) {
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) {
let top = Math.floor(-height_offset);
let left = Math.floor(-width_offset);
img = img.extend({
top,
left,
// Ensures the resulting image has the desired dimensions
right: crop_width - this.width - left,
bottom: crop_height - this.height - top
});
} else {
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(
"uint8",
new Uint8Array(this.data),
[this.height, this.width, this.channels]
);
if (channel_format === "HWC") {
} else if (channel_format === "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.");
}
let cloned = this.clone().rgba();
let clonedCanvas = createCanvasFunction(cloned.width, cloned.height);
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;
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(path3) {
if (BROWSER_ENV) {
if (WEBWORKER_ENV) {
throw new Error("Unable to save an image from a Web Worker.");
}
const extension = path3.split(".").pop().toLowerCase();
const mime = CONTENT_TYPE_MAP.get(extension) ?? "image/png";
const blob = await this.toBlob(mime);
const dataURL = URL.createObjectURL(blob);
const downloadLink = document.createElement("a");
downloadLink.href = dataURL;
downloadLink.download = path3;
downloadLink.click();
downloadLink.remove();
} else if (!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(path3);
}
}
toSharp() {
if (BROWSER_ENV) {
throw new Error("toSharp() is only supported in server-side environments.");
}
return (0, import_sharp.default)(this.data, {
raw: {
width: this.width,
height: this.height,
channels: this.channels
}
});
}
};
}
});
// node_modules/@xenova/transformers/src/utils/audio.js
async function read_audio(url2, sampling_rate) {
if (typeof AudioContext === "undefined") {
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 getFile(url2)).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);
let audio;
if (decoded.numberOfChannels === 2) {
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 {
audio = decoded.getChannelData(0);
}
return audio;
}
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;
}
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));
}
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));
}
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) {
const slope = slopes[j];
for (let i = 0; i < numFreqs; ++i) {
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;
}
function linspace(start, end, num) {
const step = (end - start) / (num - 1);
return Float64Array.from({ length: num }, (_, i) => start + step * i);
}
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;
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") {
for (let i = 0; i < num_mel_filters; ++i) {
const filter = mel_filters[i];
const enorm = 2 / (filter_freqs[i + 2] - filter_freqs[i]);
for (let j = 0; j < num_frequency_bins; ++j) {
filter[j] *= enorm;
}
}
}
return mel_filters;
}
function padReflect(array, left, right) {
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[calculateReflectOffset(i, w)];
}
for (let i = 1; i <= right; ++i) {
padded[w + left + i] = array[calculateReflectOffset(w - i, w)];
}
return padded;
}
function _db_conversion_helper(spectrogram2, 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 < spectrogram2.length; ++i) {
spectrogram2[i] = factor * Math.log10(Math.max(min_value, spectrogram2[i]) - logReference);
}
if (db_range !== null) {
if (db_range <= 0) {
throw new Error("db_range must be greater than zero");
}
const maxValue = max(spectrogram2)[0] - db_range;
for (let i = 0; i < spectrogram2.length; ++i) {
spectrogram2[i] = Math.max(spectrogram2[i], maxValue);
}
}
return spectrogram2;
}
function amplitude_to_db(spectrogram2, reference = 1, min_value = 1e-5, db_range = null) {
return _db_conversion_helper(spectrogram2, 20, reference, min_value, db_range);
}
function power_to_db(spectrogram2, reference = 1, min_value = 1e-10, db_range = null) {
return _db_conversion_helper(spectrogram2, 10, reference, min_value, db_range);
}
function spectrogram(waveform, window2, frame_length, hop_length, {
fft_length = null,
power = 1,
center = true,
pad_mode = "reflect",
onesided = true,
preemphasis = null,
mel_filters = null,
mel_floor = 1e-10,
log_mel = null,
reference = 1,
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 = window2.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);
}
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 (max_num_frames !== null) {
if (max_num_frames > num_frames) {
if (do_pad) {
d1Max = max_num_frames;
}
} else {
d1Max = d1 = max_num_frames;
}
}
const fft = new 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) {
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 mean2 = sum / frame_length;
for (let j = 0; j < frame_length; ++j) {
inputBuffer[j] -= mean2;
}
}
if (preemphasis !== null) {
for (let j = frame_length - 1; j >= 1; --j) {
inputBuffer[j] -= preemphasis * inputBuffer[j - 1];
}
inputBuffer[0] *= 1 - preemphasis;
}
for (let j = 0; j < window2.length; ++j) {
inputBuffer[j] *= window2[j];
}
fft.realTransform(outputBuffer, inputBuffer);
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) {
const pow = 2 / power;
for (let i = 0; i < magnitudes.length; ++i) {
const magnitude2 = magnitudes[i];
for (let j = 0; j < magnitude2.length; ++j) {
magnitude2[j] **= pow;
}
}
}
const num_mel_filters = mel_filters.length;
const mel_spec = new Float32Array(num_mel_filters * d1Max);
const dims = transpose ? [d1Max, num_mel_filters] : [num_mel_filters, d1Max];
for (let i = 0; i < num_mel_filters; ++i) {
const filter = mel_filters[i];
for (let j = 0; j < d1; ++j) {
const magnitude2 = magnitudes[j];
let sum = 0;
for (let k = 0; k < num_frequency_bins; ++k) {
sum += filter[k] * magnitude2[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) {
amplitude_to_db(mel_spec, reference, min_value, db_range);
} else if (power === 2) {
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 };
}
function window_function(window_length, name2, {
periodic = true,
frame_length = null,
center = true
} = {}) {
const length = periodic ? window_length + 1 : window_length;
let window2;
switch (name2) {
case "boxcar":
window2 = new Float64Array(length).fill(1);
break;
case "hann":
case "hann_window":
window2 = hanning(length);
break;
case "povey":
window2 = hanning(length).map((x) => Math.pow(x, 0.85));
break;
default:
throw new Error(`Unknown window type ${name2}.`);
}
if (periodic) {
window2 = window2.subarray(0, window_length);
}
if (frame_length === null) {
return window2;
}
if (window_length > frame_length) {
throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`);
}
return window2;
}
var HERTZ_TO_MEL_MAPPING, MEL_TO_HERTZ_MAPPING;
var init_audio = __esm({
"node_modules/@xenova/transformers/src/utils/audio.js"() {
init_hub();
init_maths();
init_core();
HERTZ_TO_MEL_MAPPING = {
"htk": (freq) => 2595 * Math.log10(1 + freq / 700),
"kaldi": (freq) => 1127 * Math.log(1 + freq / 700),
"slaney": (freq, min_log_hertz = 1e3, min_log_mel = 15, logstep = 27 / Math.log(6.4)) => freq >= min_log_hertz ? min_log_mel + Math.log(freq / min_log_hertz) * logstep : 3 * freq / 200
};
MEL_TO_HERTZ_MAPPING = {
"htk": (mels) => 700 * (10 ** (mels / 2595) - 1),
"kaldi": (mels) => 700 * (Math.exp(mels / 1127) - 1),
"slaney": (mels, min_log_hertz = 1e3, min_log_mel = 15, logstep = Math.log(6.4) / 27) => mels >= min_log_mel ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel)) : 200 * mels / 3
};
}
});
// node_modules/@xenova/transformers/src/processors.js
function center_to_corners_format([centerX, centerY, width, height]) {
return [
centerX - width / 2,
centerY - height / 2,
centerX + width / 2,
centerY + height / 2
];
}
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) {
probs = logit.sigmoid().data;
for (let k = 0; k < probs.length; ++k) {
if (probs[k] > threshold) {
indices.push(k);
}
}
} else {
let maxIndex = max(logit.data)[1];
if (maxIndex === num_classes - 1) {
continue;
}
indices.push(maxIndex);
probs = softmax(logit.data);
}
for (const index of indices) {
let box = bbox[j].data;
box = center_to_corners_format(box);
if (target_size !== null) {
box = box.map((x, i2) => x * target_size[(i2 + 1) % 2]);
}
info.boxes.push(box);
info.classes.push(index);
info.scores.push(probs[index]);
}
}
toReturn.push(info);
}
return toReturn;
}
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.`
);
}
}
function constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) {
const a = val / multiple;
let x = bankers_round(a) * multiple;
if (maxVal !== null && x > maxVal) {
x = Math.floor(a) * multiple;
}
if (x < minVal) {
x = Math.ceil(a) * multiple;
}
return x;
}
function enforce_size_divisibility([width, height], divisor) {
return [
Math.max(Math.floor(width / divisor), 1) * divisor,
Math.max(Math.floor(height / divisor), 1) * divisor
];
}
var FeatureExtractor, ImageFeatureExtractor, SegformerFeatureExtractor, DPTFeatureExtractor, DPTImageProcessor, BitImageProcessor, GLPNFeatureExtractor, CLIPFeatureExtractor, ChineseCLIPFeatureExtractor, SiglipImageProcessor, ConvNextFeatureExtractor, ConvNextImageProcessor, ViTFeatureExtractor, ViTImageProcessor, EfficientNetImageProcessor, MobileViTFeatureExtractor, MobileViTImageProcessor, OwlViTFeatureExtractor, Owlv2ImageProcessor, DeiTFeatureExtractor, BeitFeatureExtractor, DonutFeatureExtractor, NougatImageProcessor, DetrFeatureExtractor, YolosFeatureExtractor, SamImageProcessor, Swin2SRImageProcessor, VitMatteImageProcessor, WhisperFeatureExtractor, Wav2Vec2FeatureExtractor, SeamlessM4TFeatureExtractor, ASTFeatureExtractor, ClapFeatureExtractor, SpeechT5FeatureExtractor, Processor, SamProcessor, WhisperProcessor, Wav2Vec2ProcessorWithLM, SpeechT5Processor, OwlViTProcessor, AutoProcessor;
var init_processors = __esm({
"node_modules/@xenova/transformers/src/processors.js"() {
init_core();
init_hub();
init_maths();
init_tensor();
init_image();
init_audio();
FeatureExtractor = class extends Callable {
/**
* Constructs a new FeatureExtractor instance.
*
* @param {Object} config The configuration for the feature extractor.
*/
constructor(config) {
super();
this.config = config;
}
};
ImageFeatureExtractor = class 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;
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 !== void 0 && this.size.height !== void 0) {
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;
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 = min(gray_image.data)[0];
const maxValue = 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) {
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;
}
if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {
const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels);
if (Array.isArray(constant_values)) {
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];
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`.");
}
const h1 = imageHeight - 1;
const w1 = imageWidth - 1;
for (let i = 0; i < paddedImageHeight; ++i) {
const a = i * paddedImageWidth;
const b = calculateReflectOffset(i, h1) * imageWidth;
for (let j = 0; j < paddedImageWidth; ++j) {
if (i < imageHeight && j < imageWidth)
continue;
const c = (a + j) * imageChannels;
const d = (b + calculateReflectOffset(j, w1)) * imageChannels;
for (let k = 0; k < imageChannels; ++k) {
paddedPixelData[c + k] = pixelData[d + k];
}
}
}
}
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) {
const [srcWidth, srcHeight] = image.size;
let shortest_edge;
let longest_edge;
if (this.do_thumbnail) {
const { height, width } = size;
shortest_edge = Math.min(height, width);
} else if (Number.isInteger(size)) {
shortest_edge = size;
longest_edge = this.config.max_size ?? shortest_edge;
} else if (size !== void 0) {
shortest_edge = size.shortest_edge;
longest_edge = size.longest_edge;
}
if (shortest_edge !== void 0 || longest_edge !== void 0) {
const shortResizeFactor = shortest_edge === void 0 ? 1 : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);
const newWidth = srcWidth * shortResizeFactor;
const newHeight = srcHeight * shortResizeFactor;
const longResizeFactor = longest_edge === void 0 ? 1 : Math.min(longest_edge / newWidth, longest_edge / newHeight);
let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2)));
let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2)));
if (this.size_divisibility !== void 0) {
[finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility);
}
return [finalWidth, finalHeight];
} else if (size !== void 0 && size.width !== void 0 && size.height !== void 0) {
let newWidth = size.width;
let newHeight = size.height;
if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) {
let scale_height = newHeight / srcHeight;
let scale_width = newWidth / srcWidth;
if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) {
scale_height = scale_width;
} else {
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 !== void 0) {
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) {
image = await this.crop_margin(image);
}
const [srcWidth, srcHeight] = image.size;
if (do_convert_rgb ?? this.do_convert_rgb) {
image = image.rgb();
} else if (do_convert_grayscale) {
image = image.grayscale();
}
if (this.do_resize) {
image = await this.resize(image);
}
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);
}
const reshaped_input_size = [image.height, image.width];
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];
}
}
}
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;
} 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.");
}
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 Tensor("float32", pixelData, imgDims).permute(2, 0, 1);
return {
original_size: [srcHeight, srcWidth],
reshaped_input_size,
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];
}
const imageData = await Promise.all(images.map((x) => this.preprocess(x)));
const pixel_values = stack(imageData.map((x) => x.pixel_values), 0);
return {
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)
};
}
};
SegformerFeatureExtractor = class 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];
if (target_size !== null) {
data = interpolate(data, target_size, "bilinear", false);
}
const [height, width] = target_size ?? data.dims.slice(-2);
const segmentation = new Tensor(
"int32",
new Int32Array(height * width),
[height, width]
);
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;
}
}
}
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;
}
const labels = hasLabel.filter((x) => x !== void 0);
toReturn.push({ segmentation, labels });
}
return toReturn;
}
};
DPTFeatureExtractor = class extends ImageFeatureExtractor {
};
DPTImageProcessor = class extends DPTFeatureExtractor {
};
BitImageProcessor = class extends ImageFeatureExtractor {
};
GLPNFeatureExtractor = class extends ImageFeatureExtractor {
};
CLIPFeatureExtractor = class extends ImageFeatureExtractor {
};
ChineseCLIPFeatureExtractor = class extends ImageFeatureExtractor {
};
SiglipImageProcessor = class extends ImageFeatureExtractor {
};
ConvNextFeatureExtractor = class extends ImageFeatureExtractor {
constructor(config) {
super(config);
this.crop_pct = this.config.crop_pct ?? 224 / 256;
}
async resize(image) {
const shortest_edge = this.size?.shortest_edge;
if (shortest_edge === void 0) {
throw new Error(`Size dictionary must contain 'shortest_edge' key.`);
}
if (shortest_edge < 384) {
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
});
image = await image.center_crop(shortest_edge, shortest_edge);
} else {
image = await image.resize(shortest_edge, shortest_edge, {
resample: this.resample
});
}
return image;
}
};
ConvNextImageProcessor = class extends ConvNextFeatureExtractor {
};
ViTFeatureExtractor = class extends ImageFeatureExtractor {
};
ViTImageProcessor = class extends ImageFeatureExtractor {
};
EfficientNetImageProcessor = class 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);
}
}
};
MobileViTFeatureExtractor = class extends ImageFeatureExtractor {
};
MobileViTImageProcessor = class extends MobileViTFeatureExtractor {
};
OwlViTFeatureExtractor = class extends ImageFeatureExtractor {
/** @type {post_process_object_detection} */
post_process_object_detection(...args) {
return post_process_object_detection(...args);
}
};
Owlv2ImageProcessor = class extends OwlViTFeatureExtractor {
};
DeiTFeatureExtractor = class extends ImageFeatureExtractor {
};
BeitFeatureExtractor = class extends ImageFeatureExtractor {
};
DonutFeatureExtractor = class 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,
...options
});
}
};
NougatImageProcessor = class extends DonutFeatureExtractor {
};
DetrFeatureExtractor = class 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);
const maskSize = [result.pixel_values.dims[0], 64, 64];
const pixel_mask = new 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 = max(cls.data)[1];
if (pred_label === num_labels) {
continue;
}
let scores = 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) {
let mask_k = [];
let mask_k_area = 0;
let original_area = 0;
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;
if (mask_exists) {
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 Tensor(
"int32",
new Int32Array(height * width),
[height, width]
);
let segments = [];
if (target_size !== null) {
for (let i = 0; i < mask_probs.length; ++i) {
mask_probs[i] = interpolate(mask_probs[i], target_size, "bilinear", false);
}
}
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;
for (let k = 0; k < pred_labels.length; ++k) {
let pred_class = pred_labels[k];
let [mask_exists, mask_k] = this.check_segment_validity(
mask_labels,
mask_probs,
k,
mask_threshold,
overlap_mask_area_threshold
);
if (!mask_exists) {
continue;
}
++current_segment_id;
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]
});
}
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 = /* @__PURE__ */ new Set();
}
const class_queries_logits = outputs.logits;
const masks_queries_logits = outputs.pred_masks;
const mask_probs = masks_queries_logits.sigmoid();
let [batch_size, num_queries, num_labels] = class_queries_logits.dims;
num_labels -= 1;
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) {
let [height, width] = target_size ?? mask_logits.dims.slice(-2);
let segmentation2 = new Tensor(
"int32",
new Int32Array(height * width).fill(-1),
[height, width]
);
toReturn.push({
segmentation: segmentation2,
segments_info: []
});
continue;
}
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,
segments_info: segments
});
}
return toReturn;
}
post_process_instance_segmentation() {
throw Error("Not implemented yet");
}
};
YolosFeatureExtractor = class extends ImageFeatureExtractor {
/** @type {post_process_object_detection} */
post_process_object_detection(...args) {
return post_process_object_detection(...args);
}
};
SamImageProcessor = class 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) {
input_points = structuredClone(input_points);
let shape = calculateDimensions(input_points);
if (shape.length === 3) {
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`.");
}
for (let i = 0; i < input_points.length; ++i) {
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) {
for (let k = 0; k < input_points[i][j].length; ++k) {
for (let w = 0; w < input_points[i][j][k].length; ++w) {
input_points[i][j][k][w] *= resizeFactors[w];
}
}
}
}
return new 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 = calculateDimensions(input_labels);
if (shape.length === 2) {
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 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) {
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,
binarize = true,
pad_size = null
} = {}) {
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];
const interpolated_masks = [];
for (let j = 0; j < mask.dims[0]; ++j) {
const m = mask[j];
let interpolated_mask = interpolate(m, target_image_size, "bilinear", false);
interpolated_mask = interpolated_mask.slice(null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]);
interpolated_mask = interpolate(interpolated_mask, original_size, "bilinear", false);
if (binarize) {
const binarizedMaskData = new Uint8Array(interpolated_mask.data.length);
for (let i2 = 0; i2 < interpolated_mask.data.length; ++i2) {
if (interpolated_mask.data[i2] > mask_threshold) {
binarizedMaskData[i2] = 1;
}
}
interpolated_mask = new Tensor(
"bool",
binarizedMaskData,
interpolated_mask.dims
);
}
interpolated_masks.push(interpolated_mask);
}
output_masks.push(stack(interpolated_masks));
}
return output_masks;
}
};
Swin2SRImageProcessor = class extends ImageFeatureExtractor {
pad_image(pixelData, imgDims, padSize, options = {}) {
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
});
}
};
VitMatteImageProcessor = class 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
})));
const pixel_values = stack(imageData.map(
// Concatenate images and trimaps
(x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0)
), 0);
return {
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)
};
}
};
WhisperFeatureExtractor = class extends FeatureExtractor {
constructor(config) {
var _a;
super(config);
(_a = this.config).mel_filters ?? (_a.mel_filters = mel_filter_bank(
Math.floor(1 + this.config.n_fft / 2),
// num_frequency_bins
this.config.feature_size,
// num_mel_filters
0,
// min_frequency
8e3,
// max_frequency
this.config.sampling_rate,
// sampling_rate
"slaney",
// norm
"slaney"
// mel_scale
));
this.window = 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 } = spectrogram(
waveform,
this.window,
// window
this.config.n_fft,
// frame_length
this.config.hop_length,
// hop_length
{
power: 2,
mel_filters: this.config.mel_filters,
log_mel: "log10",
// Custom
max_num_frames: this.config.nb_max_frames
// 3000
}
);
const maxValue = max(data)[0];
for (let i = 0; i < data.length; ++i) {
data[i] = (Math.max(data[i], maxValue - 8) + 4) / 4;
}
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 {
waveform = new Float32Array(this.config.n_samples);
waveform.set(audio);
}
const { data, dims } = this._extract_fbank_features(waveform);
return {
input_features: new Tensor(
"float32",
data,
[1, ...dims]
)
};
}
};
Wav2Vec2FeatureExtractor = class extends FeatureExtractor {
/**
* @param {Float32Array} input_values
* @returns {Float32Array}
*/
_zero_mean_unit_var_norm(input_values) {
const sum = input_values.reduce((a, b) => a + b, 0);
const mean2 = sum / input_values.length;
const variance = input_values.reduce((a, b) => a + (b - mean2) ** 2, 0) / input_values.length;
return input_values.map((x) => (x - mean2) / 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;
if (this.config.do_normalize) {
input_values = this._zero_mean_unit_var_norm(input_values);
}
const shape = [1, input_values.length];
return {
input_values: new Tensor("float32", input_values, shape),
attention_mask: new Tensor("int64", new BigInt64Array(input_values.length).fill(1n), shape)
};
}
};
SeamlessM4TFeatureExtractor = class extends FeatureExtractor {
constructor(config) {
super(config);
const sampling_rate = this.config.sampling_rate;
const mel_filters = 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
);
for (let i = 0; i < mel_filters.length; ++i) {
mel_filters[i].push(0);
}
this.mel_filters = mel_filters;
this.window = 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) {
waveform = waveform.map((x) => x * 32768);
return spectrogram(
waveform,
this.window,
// window
400,
// frame_length
160,
// hop_length
{
fft_length: 512,
power: 2,
center: false,
preemphasis: 0.97,
mel_filters: this.mel_filters,
log_mel: "log",
mel_floor: 1192092955078125e-22,
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 mean2 = sum / num_features;
let variance = 0;
for (let j = 0; j < num_features; ++j) {
variance += (features.data[j * feature_size + i] - mean2) ** 2;
}
variance /= num_features - 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] - mean2) / std;
}
}
}
let padded_attention_mask;
if (padding) {
const [num_frames2, num_channels2] = features.dims;
const pad_size = num_frames2 % pad_to_multiple_of;
if (pad_size > 0) {
const padded_data = new Float32Array(num_channels2 * (num_frames2 + pad_size));
padded_data.set(features.data);
padded_data.fill(this.config.padding_value, features.data.length);
const numPaddedFrames = num_frames2 + pad_size;
features = {
data: padded_data,
dims: [numPaddedFrames, num_channels2]
};
if (return_attention_mask) {
padded_attention_mask = new Tensor(
"int64",
new BigInt64Array(numPaddedFrames),
[1, numPaddedFrames]
);
padded_attention_mask.data.fill(1n, 0, num_frames2);
}
}
}
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 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 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;
}
};
ASTFeatureExtractor = class extends FeatureExtractor {
constructor(config) {
super(config);
const sampling_rate = this.config.sampling_rate;
const mel_filters = 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
);
for (let i = 0; i < mel_filters.length; ++i) {
mel_filters[i].push(0);
}
this.mel_filters = mel_filters;
this.window = 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) {
return spectrogram(
waveform,
this.window,
// window
400,
// frame_length
160,
// hop_length
{
fft_length: 512,
power: 2,
center: false,
preemphasis: 0.97,
mel_filters: this.mel_filters,
log_mel: "log",
mel_floor: 1192092955078125e-22,
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) {
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 Tensor(
"float32",
features.data,
[1, ...features.dims]
)
};
}
};
ClapFeatureExtractor = class extends FeatureExtractor {
constructor(config) {
super(config);
this.mel_filters = 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 = 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 = 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) {
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];
} else {
throw new Error(`Truncation strategy "${truncation}" not implemented`);
}
} else {
if (diff < 0) {
let padded = new Float64Array(max_length);
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];
}
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) {
return spectrogram(
waveform,
this.window,
// window
this.config.fft_window_size,
// frame_length
this.config.hop_length,
// hop_length
{
power: 2,
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");
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 Tensor(
"float32",
padded_inputs.data,
[1, ...padded_inputs.dims]
)
};
}
};
SpeechT5FeatureExtractor = class extends FeatureExtractor {
};
Processor = class extends 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;
}
/**
* 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);
}
};
SamProcessor = class 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) {
return this.feature_extractor.post_process_masks(...args);
}
/**
* @borrows SamImageProcessor#reshape_input_points as reshape_input_points
*/
reshape_input_points(...args) {
return this.feature_extractor.reshape_input_points(...args);
}
};
WhisperProcessor = class 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);
}
};
Wav2Vec2ProcessorWithLM = class 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);
}
};
SpeechT5Processor = class 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);
}
};
OwlViTProcessor = class extends Processor {
};
AutoProcessor = class {
/**
* 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 getModelJSON(pretrained_model_name_or_path, "preprocessor_config.json", true, {
progress_callback,
config,
cache_dir,
local_files_only,
revision
});
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 !== void 0) {
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}`);
}
}
let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor;
let feature_extractor = new feature_extractor_class(preprocessorConfig);
return new processor_class(feature_extractor);
}
};
__publicField(AutoProcessor, "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
});
__publicField(AutoProcessor, "PROCESSOR_CLASS_MAPPING", {
WhisperProcessor,
Wav2Vec2ProcessorWithLM,
SamProcessor,
SpeechT5Processor,
OwlViTProcessor
});
}
});
// node_modules/@xenova/transformers/src/pipelines.js
async function prepareImages(images) {
if (!Array.isArray(images)) {
images = [images];
}
return await Promise.all(images.map((x) => RawImage.read(x)));
}
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 read_audio(x, sampling_rate);
} else if (x instanceof Float64Array) {
return new Float32Array(x);
}
return x;
}));
}
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 };
}
function isChat(x) {
return Array.isArray(x) && x.every((x2) => "role" in x2 && "content" in x2);
}
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
} = {}) {
task = TASK_ALIASES[task] ?? task;
const pipelineInfo = SUPPORTED_TASKS[task.split("_", 1)[0]];
if (!pipelineInfo) {
throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`);
}
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 = /* @__PURE__ */ new Map([
["tokenizer", pipelineInfo.tokenizer],
["model", pipelineInfo.model],
["processor", pipelineInfo.processor]
]);
const results = await loadItems(classes, model, pretrainedOptions);
results.task = task;
dispatchCallback(progress_callback, {
"status": "ready",
"task": task,
"model": model
});
const pipelineClass = pipelineInfo.pipeline;
return new pipelineClass(results);
}
async function loadItems(mapping, model, pretrainedOptions) {
const result = /* @__PURE__ */ Object.create(null);
const promises = [];
for (let [name2, cls] of mapping.entries()) {
if (!cls)
continue;
let promise;
if (Array.isArray(cls)) {
promise = new Promise(async (resolve, reject) => {
let e;
for (let c of cls) {
if (c === null) {
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[name2] = promise;
promises.push(promise);
}
await Promise.all(promises);
for (let [name2, promise] of Object.entries(result)) {
result[name2] = await promise;
}
return result;
}
var Pipeline, TextClassificationPipeline, TokenClassificationPipeline, QuestionAnsweringPipeline, FillMaskPipeline, Text2TextGenerationPipeline, SummarizationPipeline, TranslationPipeline, TextGenerationPipeline, ZeroShotClassificationPipeline, FeatureExtractionPipeline, ImageFeatureExtractionPipeline, AudioClassificationPipeline, ZeroShotAudioClassificationPipeline, AutomaticSpeechRecognitionPipeline, ImageToTextPipeline, ImageClassificationPipeline, ImageSegmentationPipeline, ZeroShotImageClassificationPipeline, ObjectDetectionPipeline, ZeroShotObjectDetectionPipeline, DocumentQuestionAnsweringPipeline, TextToAudioPipeline, ImageToImagePipeline, DepthEstimationPipeline, SUPPORTED_TASKS, TASK_ALIASES;
var init_pipelines = __esm({
"node_modules/@xenova/transformers/src/pipelines.js"() {
init_tokenizers();
init_models();
init_processors();
init_core();
init_maths();
init_audio();
init_tensor();
init_image();
Pipeline = class extends 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();
}
};
TextClassificationPipeline = class 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
} = {}) {
const model_inputs = this.tokenizer(texts, {
padding: true,
truncation: true
});
const outputs = await this.model(model_inputs);
const function_to_apply = this.model.config.problem_type === "multi_label_classification" ? (batch) => batch.sigmoid().data : (batch) => softmax(batch.data);
const id2label = this.model.config.id2label;
const toReturn = [];
for (const batch of outputs.logits) {
const output = function_to_apply(batch);
const scores = 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]
);
}
};
TokenClassificationPipeline = class 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);
const model_inputs = this.tokenizer(isBatched ? texts : [texts], {
padding: true,
truncation: true
});
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];
const tokens = [];
for (let j = 0; j < batch.dims[0]; ++j) {
const tokenData = batch[j];
const topScoreIndex = max(tokenData.data)[1];
const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`;
if (ignore_labels.includes(entity)) {
continue;
}
const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true });
if (word === "") {
continue;
}
const scores = softmax(tokenData.data);
tokens.push({
entity,
score: scores[topScoreIndex],
index: j,
word,
// TODO: null for now, but will add
start: null,
end: null
});
}
toReturn.push(tokens);
}
return isBatched ? toReturn : toReturn[0];
}
};
QuestionAnsweringPipeline = class 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
} = {}) {
const inputs = this.tokenizer(question, {
text_pair: context,
padding: true,
truncation: true
});
const output = await this.model(inputs);
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(softmax(output.start_logits[j].data)).map((x, i) => [x, i]).filter((x) => x[1] > sepIndex);
const e1 = Array.from(softmax(output.end_logits[j].data)).map((x, i) => [x, i]).filter((x) => x[1] > sepIndex);
const options = 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
});
toReturn.push({
answer,
score
});
}
}
return topk === 1 ? toReturn[0] : toReturn;
}
};
FillMaskPipeline = class 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
} = {}) {
const model_inputs = this.tokenizer(texts, {
padding: true,
truncation: true
});
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 = getTopItems(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];
}
};
Text2TextGenerationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */
Pipeline {
/**
* Create a new Text2TextGenerationPipeline.
* @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
*/
constructor(options) {
super(options);
/** @type {'generated_text'} */
__publicField(this, "_key", "generated_text");
}
/** @type {Text2TextGenerationPipelineCallback} */
async _call(texts, generate_kwargs = {}) {
if (!Array.isArray(texts)) {
texts = [texts];
}
if (this.model.config.prefix) {
texts = texts.map((x) => this.model.config.prefix + x);
}
const task_specific_params = this.model.config.task_specific_params;
if (task_specific_params && task_specific_params[this.task]) {
if (task_specific_params[this.task].prefix) {
texts = texts.map((x) => task_specific_params[this.task].prefix + x);
}
}
const tokenizer = this.tokenizer;
const tokenizer_options = {
padding: true,
truncation: true
};
let input_ids;
if (this instanceof TranslationPipeline && "_build_translation_inputs" in tokenizer) {
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 }));
}
};
SummarizationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */
/** @type {any} */
Text2TextGenerationPipeline {
/**
* Create a new SummarizationPipeline.
* @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
*/
constructor(options) {
super(options);
/** @type {'summary_text'} */
__publicField(this, "_key", "summary_text");
}
};
TranslationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */
/** @type {any} */
Text2TextGenerationPipeline {
/**
* Create a new TranslationPipeline.
* @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
*/
constructor(options) {
super(options);
/** @type {'translation_text'} */
__publicField(this, "_key", "translation_text");
}
};
TextGenerationPipeline = class 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;
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;
inputs = /** @type {string[]} */
/** @type {Chat[]} */
texts.map(
(x) => this.tokenizer.apply_chat_template(x, {
tokenize: false,
add_generation_prompt: true
})
);
}
const add_special_tokens = generate_kwargs.add_special_tokens ?? false;
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);
}
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) {
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;
}
};
ZeroShotClassificationPipeline = class 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);
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 === void 0) {
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 === void 0) {
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];
}
const hypotheses = candidate_labels.map(
(x) => hypothesis_template.replace("{}", x)
);
const softmaxEach = multi_label || candidate_labels.length === 1;
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]);
}
}
const scores = softmaxEach ? entails_logits.map((x) => softmax(x)[1]) : softmax(entails_logits);
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];
}
};
FeatureExtractionPipeline = class 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"
)
} = {}) {
const model_inputs = this.tokenizer(texts, {
padding: true,
truncation: true
});
const outputs = await this.model(model_inputs);
let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings;
if (pooling === "none") {
} else if (pooling === "mean") {
result = 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 = quantize_embeddings(result, precision);
}
return result;
}
};
ImageFeatureExtractionPipeline = class 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 });
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;
}
};
AudioClassificationPipeline = class 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 = getTopItems(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]
);
}
};
ZeroShotAudioClassificationPipeline = class 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
];
}
const texts = candidate_labels.map(
(x) => hypothesis_template.replace("{}", x)
);
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);
const output = await this.model({ ...text_inputs, ...audio_inputs });
const probs = softmax(output.logits_per_audio.data);
toReturn.push([...probs].map((x, i) => ({
score: x,
label: candidate_labels[i]
})));
}
return single ? toReturn[0] : toReturn;
}
};
AutomaticSpeechRecognitionPipeline = class 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 = {}) {
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(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 = pop(kwargs, "language", null);
const task = 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.");
}
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) {
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`.");
}
const window2 = sampling_rate * chunk_length_s;
const stride = sampling_rate * stride_length_s;
const jump = window2 - 2 * stride;
let offset = 0;
while (offset < aud.length) {
const subarr = aud.subarray(offset, offset + window2);
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
}];
}
for (const chunk of chunks) {
kwargs.num_frames = Math.floor(chunk.stride[0] / hop_length);
const data = await this.model.generate(chunk.input_features, kwargs);
if (return_timestamps === "word") {
chunk.tokens = data.sequences[0];
chunk.token_timestamps = data.token_timestamps.tolist()[0].map(
(x) => round(x, 2)
);
} else {
chunk.tokens = data[0];
}
chunk.stride = chunk.stride.map((x) => x / sampling_rate);
if (chunk_callback !== null) {
chunk_callback(chunk);
}
}
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;
}
};
ImageToTextPipeline = class 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];
}
};
ImageClassificationPipeline = class 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 = getTopItems(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]
);
}
};
ImageSegmentationPipeline = class 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;
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 RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1);
annotation.push({
score: segment.score,
label: id2label[segment.label_id],
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 RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1);
annotation.push({
score: null,
label: id2label[label],
mask
});
}
} else {
throw Error(`Subtask ${subtask} not supported.`);
}
return annotation;
}
};
ZeroShotImageClassificationPipeline = class 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);
const texts = candidate_labels.map(
(x) => hypothesis_template.replace("{}", x)
);
const text_inputs = this.tokenizer(texts, {
padding: this.model.config.model_type === "siglip" ? "max_length" : true,
truncation: true
});
const { pixel_values } = await this.processor(preparedImages);
const output = await this.model({ ...text_inputs, pixel_values });
const function_to_apply = this.model.config.model_type === "siglip" ? (batch) => batch.sigmoid().data : (batch) => softmax(batch.data);
const toReturn = [];
for (const batch of output.logits_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);
toReturn.push(result);
}
return isBatched ? toReturn : toReturn[0];
}
};
ObjectDetectionPipeline = class 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 });
const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes);
const id2label = this.model.config.id2label;
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];
}
};
ZeroShotObjectDetectionPipeline = class 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);
const text_inputs = this.tokenizer(candidate_labels, {
padding: true,
truncation: true
});
const model_inputs = await this.processor(preparedImages);
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);
const output = await this.model({ ...text_inputs, pixel_values });
const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0];
let result = processed.boxes.map((box, i2) => ({
score: processed.scores[i2],
label: candidate_labels[processed.classes[i2]],
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];
}
};
DocumentQuestionAnsweringPipeline = class 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 = {}) {
const preparedImage = (await prepareImages(image))[0];
const { pixel_values } = await this.processor(preparedImage);
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;
const output = await this.model.generate(
pixel_values,
{
...generate_kwargs,
decoder_input_ids,
max_length: this.model.config.decoder.max_position_embeddings
}
);
const decoded = this.tokenizer.batch_decode(output)[0];
const match = decoded.match(/<s_answer>(.*?)<\/s_answer>/);
let answer = null;
if (match && match.length >= 2) {
answer = match[1].trim();
}
return [{ answer }];
}
};
TextToAudioPipeline = class extends /** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */
Pipeline {
/**
* Create a new TextToAudioPipeline.
* @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
*/
constructor(options) {
super(options);
__publicField(this, "DEFAULT_VOCODER_ID", "Xenova/speecht5_hifigan");
this.vocoder = options.vocoder ?? null;
}
/** @type {TextToAudioPipelineCallback} */
async _call(text_inputs, {
speaker_embeddings = null
} = {}) {
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) {
const inputs = this.tokenizer(text_inputs, {
padding: true,
truncation: true
});
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 }) {
if (!this.vocoder) {
console.log("No vocoder specified, using default HifiGan vocoder.");
this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { quantized: false });
}
if (typeof speaker_embeddings === "string" || speaker_embeddings instanceof URL) {
speaker_embeddings = new Float32Array(
await (await fetch(speaker_embeddings)).arrayBuffer()
);
}
if (speaker_embeddings instanceof Float32Array) {
speaker_embeddings = new Tensor(
"float32",
speaker_embeddings,
[1, speaker_embeddings.length]
);
} else if (!(speaker_embeddings instanceof Tensor)) {
throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");
}
const { input_ids } = this.tokenizer(text_inputs, {
padding: true,
truncation: true
});
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
};
}
};
ImageToImagePipeline = class 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);
const toReturn = [];
for (const batch of outputs.reconstruction) {
const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to("uint8");
toReturn.push(RawImage.fromTensor(output));
}
return toReturn.length > 1 ? toReturn : toReturn[0];
}
};
DepthEstimationPipeline = class 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 = interpolate(predicted_depth[i], preparedImages[i].size.reverse(), "bilinear", false);
const formatted = prediction.mul_(255 / max(prediction.data)[0]).to("uint8");
toReturn.push({
predicted_depth: predicted_depth[i],
depth: RawImage.fromTensor(formatted)
});
}
return toReturn.length > 1 ? toReturn : toReturn[0];
}
};
SUPPORTED_TASKS = Object.freeze({
"text-classification": {
"tokenizer": AutoTokenizer,
"pipeline": TextClassificationPipeline,
"model": 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": AutoTokenizer,
"pipeline": TokenClassificationPipeline,
"model": 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": AutoTokenizer,
"pipeline": QuestionAnsweringPipeline,
"model": AutoModelForQuestionAnswering,
"default": {
// TODO: replace with original
// "model": "distilbert-base-cased-distilled-squad",
"model": "Xenova/distilbert-base-cased-distilled-squad"
},
"type": "text"
},
"fill-mask": {
"tokenizer": AutoTokenizer,
"pipeline": FillMaskPipeline,
"model": AutoModelForMaskedLM,
"default": {
// TODO: replace with original
// "model": "bert-base-uncased",
"model": "Xenova/bert-base-uncased"
},
"type": "text"
},
"summarization": {
"tokenizer": AutoTokenizer,
"pipeline": SummarizationPipeline,
"model": AutoModelForSeq2SeqLM,
"default": {
// TODO: replace with original
// "model": "sshleifer/distilbart-cnn-6-6",
"model": "Xenova/distilbart-cnn-6-6"
},
"type": "text"
},
"translation": {
"tokenizer": AutoTokenizer,
"pipeline": TranslationPipeline,
"model": AutoModelForSeq2SeqLM,
"default": {
// TODO: replace with original
// "model": "t5-small",
"model": "Xenova/t5-small"
},
"type": "text"
},
"text2text-generation": {
"tokenizer": AutoTokenizer,
"pipeline": Text2TextGenerationPipeline,
"model": AutoModelForSeq2SeqLM,
"default": {
// TODO: replace with original
// "model": "google/flan-t5-small",
"model": "Xenova/flan-t5-small"
},
"type": "text"
},
"text-generation": {
"tokenizer": AutoTokenizer,
"pipeline": TextGenerationPipeline,
"model": AutoModelForCausalLM,
"default": {
// TODO: replace with original
// "model": "gpt2",
"model": "Xenova/gpt2"
},
"type": "text"
},
"zero-shot-classification": {
"tokenizer": AutoTokenizer,
"pipeline": ZeroShotClassificationPipeline,
"model": 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": AutoModelForAudioClassification,
"processor": 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": AutoTokenizer,
"pipeline": ZeroShotAudioClassificationPipeline,
"model": AutoModel,
"processor": AutoProcessor,
"default": {
// TODO: replace with original
// "model": "laion/clap-htsat-fused",
"model": "Xenova/clap-htsat-unfused"
},
"type": "multimodal"
},
"automatic-speech-recognition": {
"tokenizer": AutoTokenizer,
"pipeline": AutomaticSpeechRecognitionPipeline,
"model": [AutoModelForSpeechSeq2Seq, AutoModelForCTC],
"processor": AutoProcessor,
"default": {
// TODO: replace with original
// "model": "openai/whisper-tiny.en",
"model": "Xenova/whisper-tiny.en"
},
"type": "multimodal"
},
"text-to-audio": {
"tokenizer": AutoTokenizer,
"pipeline": TextToAudioPipeline,
"model": [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram],
"processor": [
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": AutoTokenizer,
"pipeline": ImageToTextPipeline,
"model": AutoModelForVision2Seq,
"processor": 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": AutoModelForImageClassification,
"processor": 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": [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation],
"processor": 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": AutoTokenizer,
"pipeline": ZeroShotImageClassificationPipeline,
"model": AutoModel,
"processor": 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": AutoModelForObjectDetection,
"processor": AutoProcessor,
"default": {
// TODO: replace with original
// "model": "facebook/detr-resnet-50",
"model": "Xenova/detr-resnet-50"
},
"type": "multimodal"
},
"zero-shot-object-detection": {
"tokenizer": AutoTokenizer,
"pipeline": ZeroShotObjectDetectionPipeline,
"model": AutoModelForZeroShotObjectDetection,
"processor": AutoProcessor,
"default": {
// TODO: replace with original
// "model": "google/owlvit-base-patch32",
"model": "Xenova/owlvit-base-patch32"
},
"type": "multimodal"
},
"document-question-answering": {
"tokenizer": AutoTokenizer,
"pipeline": DocumentQuestionAnsweringPipeline,
"model": AutoModelForDocumentQuestionAnswering,
"processor": 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": AutoModelForImageToImage,
"processor": 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": AutoModelForDepthEstimation,
"processor": 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": AutoTokenizer,
"pipeline": FeatureExtractionPipeline,
"model": 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": AutoProcessor,
"pipeline": ImageFeatureExtractionPipeline,
"model": [AutoModelForImageFeatureExtraction, AutoModel],
"default": {
// TODO: replace with original
// "model": "google/vit-base-patch16-224",
"model": "Xenova/vit-base-patch16-224-in21k"
},
"type": "image"
}
});
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"
});
}
});
// node_modules/@xenova/transformers/src/transformers.js
var transformers_exports = {};
__export(transformers_exports, {
ASTFeatureExtractor: () => ASTFeatureExtractor,
ASTForAudioClassification: () => ASTForAudioClassification,
ASTModel: () => ASTModel,
ASTPreTrainedModel: () => ASTPreTrainedModel,
AlbertForMaskedLM: () => AlbertForMaskedLM,
AlbertForQuestionAnswering: () => AlbertForQuestionAnswering,
AlbertForSequenceClassification: () => AlbertForSequenceClassification,
AlbertModel: () => AlbertModel,
AlbertPreTrainedModel: () => AlbertPreTrainedModel,
AlbertTokenizer: () => AlbertTokenizer,
AudioClassificationPipeline: () => AudioClassificationPipeline,
AutoConfig: () => AutoConfig,
AutoModel: () => AutoModel,
AutoModelForAudioClassification: () => AutoModelForAudioClassification,
AutoModelForAudioFrameClassification: () => AutoModelForAudioFrameClassification,
AutoModelForCTC: () => AutoModelForCTC,
AutoModelForCausalLM: () => AutoModelForCausalLM,
AutoModelForDepthEstimation: () => AutoModelForDepthEstimation,
AutoModelForDocumentQuestionAnswering: () => AutoModelForDocumentQuestionAnswering,
AutoModelForImageClassification: () => AutoModelForImageClassification,
AutoModelForImageFeatureExtraction: () => AutoModelForImageFeatureExtraction,
AutoModelForImageMatting: () => AutoModelForImageMatting,
AutoModelForImageSegmentation: () => AutoModelForImageSegmentation,
AutoModelForImageToImage: () => AutoModelForImageToImage,
AutoModelForMaskGeneration: () => AutoModelForMaskGeneration,
AutoModelForMaskedLM: () => AutoModelForMaskedLM,
AutoModelForObjectDetection: () => AutoModelForObjectDetection,
AutoModelForQuestionAnswering: () => AutoModelForQuestionAnswering,
AutoModelForSemanticSegmentation: () => AutoModelForSemanticSegmentation,
AutoModelForSeq2SeqLM: () => AutoModelForSeq2SeqLM,
AutoModelForSequenceClassification: () => AutoModelForSequenceClassification,
AutoModelForSpeechSeq2Seq: () => AutoModelForSpeechSeq2Seq,
AutoModelForTextToSpectrogram: () => AutoModelForTextToSpectrogram,
AutoModelForTextToWaveform: () => AutoModelForTextToWaveform,
AutoModelForTokenClassification: () => AutoModelForTokenClassification,
AutoModelForVision2Seq: () => AutoModelForVision2Seq,
AutoModelForXVector: () => AutoModelForXVector,
AutoModelForZeroShotObjectDetection: () => AutoModelForZeroShotObjectDetection,
AutoProcessor: () => AutoProcessor,
AutoTokenizer: () => AutoTokenizer,
AutomaticSpeechRecognitionPipeline: () => AutomaticSpeechRecognitionPipeline,
BartForConditionalGeneration: () => BartForConditionalGeneration,
BartForSequenceClassification: () => BartForSequenceClassification,
BartModel: () => BartModel,
BartPretrainedModel: () => BartPretrainedModel,
BartTokenizer: () => BartTokenizer,
BaseModelOutput: () => BaseModelOutput,
BeitFeatureExtractor: () => BeitFeatureExtractor,
BeitForImageClassification: () => BeitForImageClassification,
BeitModel: () => BeitModel,
BeitPreTrainedModel: () => BeitPreTrainedModel,
BertForMaskedLM: () => BertForMaskedLM,
BertForQuestionAnswering: () => BertForQuestionAnswering,
BertForSequenceClassification: () => BertForSequenceClassification,
BertForTokenClassification: () => BertForTokenClassification,
BertModel: () => BertModel,
BertPreTrainedModel: () => BertPreTrainedModel,
BertTokenizer: () => BertTokenizer,
BitImageProcessor: () => BitImageProcessor,
BlenderbotForConditionalGeneration: () => BlenderbotForConditionalGeneration,
BlenderbotModel: () => BlenderbotModel,
BlenderbotPreTrainedModel: () => BlenderbotPreTrainedModel,
BlenderbotSmallForConditionalGeneration: () => BlenderbotSmallForConditionalGeneration,
BlenderbotSmallModel: () => BlenderbotSmallModel,
BlenderbotSmallPreTrainedModel: () => BlenderbotSmallPreTrainedModel,
BlenderbotSmallTokenizer: () => BlenderbotSmallTokenizer,
BlenderbotTokenizer: () => BlenderbotTokenizer,
BloomForCausalLM: () => BloomForCausalLM,
BloomModel: () => BloomModel,
BloomPreTrainedModel: () => BloomPreTrainedModel,
BloomTokenizer: () => BloomTokenizer,
CLIPFeatureExtractor: () => CLIPFeatureExtractor,
CLIPModel: () => CLIPModel,
CLIPPreTrainedModel: () => CLIPPreTrainedModel,
CLIPSegForImageSegmentation: () => CLIPSegForImageSegmentation,
CLIPSegModel: () => CLIPSegModel,
CLIPSegPreTrainedModel: () => CLIPSegPreTrainedModel,
CLIPTextModelWithProjection: () => CLIPTextModelWithProjection,
CLIPTokenizer: () => CLIPTokenizer,
CLIPVisionModelWithProjection: () => CLIPVisionModelWithProjection,
CamembertForMaskedLM: () => CamembertForMaskedLM,
CamembertForQuestionAnswering: () => CamembertForQuestionAnswering,
CamembertForSequenceClassification: () => CamembertForSequenceClassification,
CamembertForTokenClassification: () => CamembertForTokenClassification,
CamembertModel: () => CamembertModel,
CamembertPreTrainedModel: () => CamembertPreTrainedModel,
CamembertTokenizer: () => CamembertTokenizer,
CausalLMOutput: () => CausalLMOutput,
CausalLMOutputWithPast: () => CausalLMOutputWithPast,
ChineseCLIPFeatureExtractor: () => ChineseCLIPFeatureExtractor,
ChineseCLIPModel: () => ChineseCLIPModel,
ChineseCLIPPreTrainedModel: () => ChineseCLIPPreTrainedModel,
ClapAudioModelWithProjection: () => ClapAudioModelWithProjection,
ClapFeatureExtractor: () => ClapFeatureExtractor,
ClapModel: () => ClapModel,
ClapPreTrainedModel: () => ClapPreTrainedModel,
ClapTextModelWithProjection: () => ClapTextModelWithProjection,
CodeGenForCausalLM: () => CodeGenForCausalLM,
CodeGenModel: () => CodeGenModel,
CodeGenPreTrainedModel: () => CodeGenPreTrainedModel,
CodeGenTokenizer: () => CodeGenTokenizer,
CodeLlamaTokenizer: () => CodeLlamaTokenizer,
CohereTokenizer: () => CohereTokenizer,
ConvBertForMaskedLM: () => ConvBertForMaskedLM,
ConvBertForQuestionAnswering: () => ConvBertForQuestionAnswering,
ConvBertForSequenceClassification: () => ConvBertForSequenceClassification,
ConvBertForTokenClassification: () => ConvBertForTokenClassification,
ConvBertModel: () => ConvBertModel,
ConvBertPreTrainedModel: () => ConvBertPreTrainedModel,
ConvBertTokenizer: () => ConvBertTokenizer,
ConvNextFeatureExtractor: () => ConvNextFeatureExtractor,
ConvNextForImageClassification: () => ConvNextForImageClassification,
ConvNextImageProcessor: () => ConvNextImageProcessor,
ConvNextModel: () => ConvNextModel,
ConvNextPreTrainedModel: () => ConvNextPreTrainedModel,
ConvNextV2ForImageClassification: () => ConvNextV2ForImageClassification,
ConvNextV2Model: () => ConvNextV2Model,
ConvNextV2PreTrainedModel: () => ConvNextV2PreTrainedModel,
DPTFeatureExtractor: () => DPTFeatureExtractor,
DPTForDepthEstimation: () => DPTForDepthEstimation,
DPTImageProcessor: () => DPTImageProcessor,
DPTModel: () => DPTModel,
DPTPreTrainedModel: () => DPTPreTrainedModel,
DebertaForMaskedLM: () => DebertaForMaskedLM,
DebertaForQuestionAnswering: () => DebertaForQuestionAnswering,
DebertaForSequenceClassification: () => DebertaForSequenceClassification,
DebertaForTokenClassification: () => DebertaForTokenClassification,
DebertaModel: () => DebertaModel,
DebertaPreTrainedModel: () => DebertaPreTrainedModel,
DebertaTokenizer: () => DebertaTokenizer,
DebertaV2ForMaskedLM: () => DebertaV2ForMaskedLM,
DebertaV2ForQuestionAnswering: () => DebertaV2ForQuestionAnswering,
DebertaV2ForSequenceClassification: () => DebertaV2ForSequenceClassification,
DebertaV2ForTokenClassification: () => DebertaV2ForTokenClassification,
DebertaV2Model: () => DebertaV2Model,
DebertaV2PreTrainedModel: () => DebertaV2PreTrainedModel,
DebertaV2Tokenizer: () => DebertaV2Tokenizer,
DeiTFeatureExtractor: () => DeiTFeatureExtractor,
DeiTForImageClassification: () => DeiTForImageClassification,
DeiTModel: () => DeiTModel,
DeiTPreTrainedModel: () => DeiTPreTrainedModel,
DepthAnythingForDepthEstimation: () => DepthAnythingForDepthEstimation,
DepthAnythingPreTrainedModel: () => DepthAnythingPreTrainedModel,
DepthEstimationPipeline: () => DepthEstimationPipeline,
DetrFeatureExtractor: () => DetrFeatureExtractor,
DetrForObjectDetection: () => DetrForObjectDetection,
DetrForSegmentation: () => DetrForSegmentation,
DetrModel: () => DetrModel,
DetrObjectDetectionOutput: () => DetrObjectDetectionOutput,
DetrPreTrainedModel: () => DetrPreTrainedModel,
DetrSegmentationOutput: () => DetrSegmentationOutput,
Dinov2ForImageClassification: () => Dinov2ForImageClassification,
Dinov2Model: () => Dinov2Model,
Dinov2PreTrainedModel: () => Dinov2PreTrainedModel,
DistilBertForMaskedLM: () => DistilBertForMaskedLM,
DistilBertForQuestionAnswering: () => DistilBertForQuestionAnswering,
DistilBertForSequenceClassification: () => DistilBertForSequenceClassification,
DistilBertForTokenClassification: () => DistilBertForTokenClassification,
DistilBertModel: () => DistilBertModel,
DistilBertPreTrainedModel: () => DistilBertPreTrainedModel,
DistilBertTokenizer: () => DistilBertTokenizer,
DocumentQuestionAnsweringPipeline: () => DocumentQuestionAnsweringPipeline,
DonutFeatureExtractor: () => DonutFeatureExtractor,
DonutSwinModel: () => DonutSwinModel,
DonutSwinPreTrainedModel: () => DonutSwinPreTrainedModel,
EfficientNetForImageClassification: () => EfficientNetForImageClassification,
EfficientNetImageProcessor: () => EfficientNetImageProcessor,
EfficientNetModel: () => EfficientNetModel,
EfficientNetPreTrainedModel: () => EfficientNetPreTrainedModel,
ElectraForMaskedLM: () => ElectraForMaskedLM,
ElectraForQuestionAnswering: () => ElectraForQuestionAnswering,
ElectraForSequenceClassification: () => ElectraForSequenceClassification,
ElectraForTokenClassification: () => ElectraForTokenClassification,
ElectraModel: () => ElectraModel,
ElectraPreTrainedModel: () => ElectraPreTrainedModel,
ElectraTokenizer: () => ElectraTokenizer,
EsmForMaskedLM: () => EsmForMaskedLM,
EsmForSequenceClassification: () => EsmForSequenceClassification,
EsmForTokenClassification: () => EsmForTokenClassification,
EsmModel: () => EsmModel,
EsmPreTrainedModel: () => EsmPreTrainedModel,
EsmTokenizer: () => EsmTokenizer,
FFT: () => FFT,
FalconForCausalLM: () => FalconForCausalLM,
FalconModel: () => FalconModel,
FalconPreTrainedModel: () => FalconPreTrainedModel,
FalconTokenizer: () => FalconTokenizer,
FastViTForImageClassification: () => FastViTForImageClassification,
FastViTModel: () => FastViTModel,
FastViTPreTrainedModel: () => FastViTPreTrainedModel,
FeatureExtractionPipeline: () => FeatureExtractionPipeline,
FeatureExtractor: () => FeatureExtractor,
FillMaskPipeline: () => FillMaskPipeline,
GLPNFeatureExtractor: () => GLPNFeatureExtractor,
GLPNForDepthEstimation: () => GLPNForDepthEstimation,
GLPNModel: () => GLPNModel,
GLPNPreTrainedModel: () => GLPNPreTrainedModel,
GPT2LMHeadModel: () => GPT2LMHeadModel,
GPT2Model: () => GPT2Model,
GPT2PreTrainedModel: () => GPT2PreTrainedModel,
GPT2Tokenizer: () => GPT2Tokenizer,
GPTBigCodeForCausalLM: () => GPTBigCodeForCausalLM,
GPTBigCodeModel: () => GPTBigCodeModel,
GPTBigCodePreTrainedModel: () => GPTBigCodePreTrainedModel,
GPTJForCausalLM: () => GPTJForCausalLM,
GPTJModel: () => GPTJModel,
GPTJPreTrainedModel: () => GPTJPreTrainedModel,
GPTNeoForCausalLM: () => GPTNeoForCausalLM,
GPTNeoModel: () => GPTNeoModel,
GPTNeoPreTrainedModel: () => GPTNeoPreTrainedModel,
GPTNeoXForCausalLM: () => GPTNeoXForCausalLM,
GPTNeoXModel: () => GPTNeoXModel,
GPTNeoXPreTrainedModel: () => GPTNeoXPreTrainedModel,
GPTNeoXTokenizer: () => GPTNeoXTokenizer,
GemmaTokenizer: () => GemmaTokenizer,
Grok1Tokenizer: () => Grok1Tokenizer,
HerbertTokenizer: () => HerbertTokenizer,
HubertForCTC: () => HubertForCTC,
HubertForSequenceClassification: () => HubertForSequenceClassification,
HubertModel: () => HubertModel,
HubertPreTrainedModel: () => HubertPreTrainedModel,
ImageClassificationPipeline: () => ImageClassificationPipeline,
ImageFeatureExtractionPipeline: () => ImageFeatureExtractionPipeline,
ImageFeatureExtractor: () => ImageFeatureExtractor,
ImageMattingOutput: () => ImageMattingOutput,
ImageSegmentationPipeline: () => ImageSegmentationPipeline,
ImageToImagePipeline: () => ImageToImagePipeline,
ImageToTextPipeline: () => ImageToTextPipeline,
LlamaForCausalLM: () => LlamaForCausalLM,
LlamaModel: () => LlamaModel,
LlamaPreTrainedModel: () => LlamaPreTrainedModel,
LlamaTokenizer: () => LlamaTokenizer,
LongT5ForConditionalGeneration: () => LongT5ForConditionalGeneration,
LongT5Model: () => LongT5Model,
LongT5PreTrainedModel: () => LongT5PreTrainedModel,
M2M100ForConditionalGeneration: () => M2M100ForConditionalGeneration,
M2M100Model: () => M2M100Model,
M2M100PreTrainedModel: () => M2M100PreTrainedModel,
M2M100Tokenizer: () => M2M100Tokenizer,
MBart50Tokenizer: () => MBart50Tokenizer,
MBartForCausalLM: () => MBartForCausalLM,
MBartForConditionalGeneration: () => MBartForConditionalGeneration,
MBartForSequenceClassification: () => MBartForSequenceClassification,
MBartModel: () => MBartModel,
MBartPreTrainedModel: () => MBartPreTrainedModel,
MBartTokenizer: () => MBartTokenizer,
MPNetForMaskedLM: () => MPNetForMaskedLM,
MPNetForQuestionAnswering: () => MPNetForQuestionAnswering,
MPNetForSequenceClassification: () => MPNetForSequenceClassification,
MPNetForTokenClassification: () => MPNetForTokenClassification,
MPNetModel: () => MPNetModel,
MPNetPreTrainedModel: () => MPNetPreTrainedModel,
MPNetTokenizer: () => MPNetTokenizer,
MT5ForConditionalGeneration: () => MT5ForConditionalGeneration,
MT5Model: () => MT5Model,
MT5PreTrainedModel: () => MT5PreTrainedModel,
MarianMTModel: () => MarianMTModel,
MarianModel: () => MarianModel,
MarianPreTrainedModel: () => MarianPreTrainedModel,
MarianTokenizer: () => MarianTokenizer,
MaskedLMOutput: () => MaskedLMOutput,
MistralForCausalLM: () => MistralForCausalLM,
MistralModel: () => MistralModel,
MistralPreTrainedModel: () => MistralPreTrainedModel,
MobileBertForMaskedLM: () => MobileBertForMaskedLM,
MobileBertForQuestionAnswering: () => MobileBertForQuestionAnswering,
MobileBertForSequenceClassification: () => MobileBertForSequenceClassification,
MobileBertModel: () => MobileBertModel,
MobileBertPreTrainedModel: () => MobileBertPreTrainedModel,
MobileBertTokenizer: () => MobileBertTokenizer,
MobileViTFeatureExtractor: () => MobileViTFeatureExtractor,
MobileViTForImageClassification: () => MobileViTForImageClassification,
MobileViTImageProcessor: () => MobileViTImageProcessor,
MobileViTModel: () => MobileViTModel,
MobileViTPreTrainedModel: () => MobileViTPreTrainedModel,
MobileViTV2ForImageClassification: () => MobileViTV2ForImageClassification,
MobileViTV2Model: () => MobileViTV2Model,
MobileViTV2PreTrainedModel: () => MobileViTV2PreTrainedModel,
ModelOutput: () => ModelOutput,
MptForCausalLM: () => MptForCausalLM,
MptModel: () => MptModel,
MptPreTrainedModel: () => MptPreTrainedModel,
NllbTokenizer: () => NllbTokenizer,
NomicBertModel: () => NomicBertModel,
NomicBertPreTrainedModel: () => NomicBertPreTrainedModel,
NougatImageProcessor: () => NougatImageProcessor,
NougatTokenizer: () => NougatTokenizer,
OPTForCausalLM: () => OPTForCausalLM,
OPTModel: () => OPTModel,
OPTPreTrainedModel: () => OPTPreTrainedModel,
ObjectDetectionPipeline: () => ObjectDetectionPipeline,
OwlViTFeatureExtractor: () => OwlViTFeatureExtractor,
OwlViTForObjectDetection: () => OwlViTForObjectDetection,
OwlViTModel: () => OwlViTModel,
OwlViTPreTrainedModel: () => OwlViTPreTrainedModel,
OwlViTProcessor: () => OwlViTProcessor,
Owlv2ForObjectDetection: () => Owlv2ForObjectDetection,
Owlv2ImageProcessor: () => Owlv2ImageProcessor,
Owlv2Model: () => Owlv2Model,
Owlv2PreTrainedModel: () => Owlv2PreTrainedModel,
PhiForCausalLM: () => PhiForCausalLM,
PhiModel: () => PhiModel,
PhiPreTrainedModel: () => PhiPreTrainedModel,
Pipeline: () => Pipeline,
PreTrainedModel: () => PreTrainedModel,
PreTrainedTokenizer: () => PreTrainedTokenizer,
PretrainedConfig: () => PretrainedConfig,
PretrainedMixin: () => PretrainedMixin,
Processor: () => Processor,
QuestionAnsweringModelOutput: () => QuestionAnsweringModelOutput,
QuestionAnsweringPipeline: () => QuestionAnsweringPipeline,
Qwen2ForCausalLM: () => Qwen2ForCausalLM,
Qwen2Model: () => Qwen2Model,
Qwen2PreTrainedModel: () => Qwen2PreTrainedModel,
Qwen2Tokenizer: () => Qwen2Tokenizer,
RawImage: () => RawImage,
ResNetForImageClassification: () => ResNetForImageClassification,
ResNetModel: () => ResNetModel,
ResNetPreTrainedModel: () => ResNetPreTrainedModel,
RoFormerForMaskedLM: () => RoFormerForMaskedLM,
RoFormerForQuestionAnswering: () => RoFormerForQuestionAnswering,
RoFormerForSequenceClassification: () => RoFormerForSequenceClassification,
RoFormerForTokenClassification: () => RoFormerForTokenClassification,
RoFormerModel: () => RoFormerModel,
RoFormerPreTrainedModel: () => RoFormerPreTrainedModel,
RoFormerTokenizer: () => RoFormerTokenizer,
RobertaForMaskedLM: () => RobertaForMaskedLM,
RobertaForQuestionAnswering: () => RobertaForQuestionAnswering,
RobertaForSequenceClassification: () => RobertaForSequenceClassification,
RobertaForTokenClassification: () => RobertaForTokenClassification,
RobertaModel: () => RobertaModel,
RobertaPreTrainedModel: () => RobertaPreTrainedModel,
RobertaTokenizer: () => RobertaTokenizer,
SamImageProcessor: () => SamImageProcessor,
SamImageSegmentationOutput: () => SamImageSegmentationOutput,
SamModel: () => SamModel,
SamPreTrainedModel: () => SamPreTrainedModel,
SamProcessor: () => SamProcessor,
SeamlessM4TFeatureExtractor: () => SeamlessM4TFeatureExtractor,
SegformerFeatureExtractor: () => SegformerFeatureExtractor,
SegformerForImageClassification: () => SegformerForImageClassification,
SegformerForSemanticSegmentation: () => SegformerForSemanticSegmentation,
SegformerModel: () => SegformerModel,
SegformerPreTrainedModel: () => SegformerPreTrainedModel,
Seq2SeqLMOutput: () => Seq2SeqLMOutput,
SequenceClassifierOutput: () => SequenceClassifierOutput,
SiglipImageProcessor: () => SiglipImageProcessor,
SiglipModel: () => SiglipModel,
SiglipPreTrainedModel: () => SiglipPreTrainedModel,
SiglipTextModel: () => SiglipTextModel,
SiglipTokenizer: () => SiglipTokenizer,
SiglipVisionModel: () => SiglipVisionModel,
SpeechT5FeatureExtractor: () => SpeechT5FeatureExtractor,
SpeechT5ForSpeechToText: () => SpeechT5ForSpeechToText,
SpeechT5ForTextToSpeech: () => SpeechT5ForTextToSpeech,
SpeechT5HifiGan: () => SpeechT5HifiGan,
SpeechT5Model: () => SpeechT5Model,
SpeechT5PreTrainedModel: () => SpeechT5PreTrainedModel,
SpeechT5Processor: () => SpeechT5Processor,
SpeechT5Tokenizer: () => SpeechT5Tokenizer,
SqueezeBertForMaskedLM: () => SqueezeBertForMaskedLM,
SqueezeBertForQuestionAnswering: () => SqueezeBertForQuestionAnswering,
SqueezeBertForSequenceClassification: () => SqueezeBertForSequenceClassification,
SqueezeBertModel: () => SqueezeBertModel,
SqueezeBertPreTrainedModel: () => SqueezeBertPreTrainedModel,
SqueezeBertTokenizer: () => SqueezeBertTokenizer,
StableLmForCausalLM: () => StableLmForCausalLM,
StableLmModel: () => StableLmModel,
StableLmPreTrainedModel: () => StableLmPreTrainedModel,
Starcoder2ForCausalLM: () => Starcoder2ForCausalLM,
Starcoder2Model: () => Starcoder2Model,
Starcoder2PreTrainedModel: () => Starcoder2PreTrainedModel,
SummarizationPipeline: () => SummarizationPipeline,
Swin2SRForImageSuperResolution: () => Swin2SRForImageSuperResolution,
Swin2SRImageProcessor: () => Swin2SRImageProcessor,
Swin2SRModel: () => Swin2SRModel,
Swin2SRPreTrainedModel: () => Swin2SRPreTrainedModel,
SwinForImageClassification: () => SwinForImageClassification,
SwinModel: () => SwinModel,
SwinPreTrainedModel: () => SwinPreTrainedModel,
T5ForConditionalGeneration: () => T5ForConditionalGeneration,
T5Model: () => T5Model,
T5PreTrainedModel: () => T5PreTrainedModel,
T5Tokenizer: () => T5Tokenizer,
TableTransformerForObjectDetection: () => TableTransformerForObjectDetection,
TableTransformerModel: () => TableTransformerModel,
TableTransformerObjectDetectionOutput: () => TableTransformerObjectDetectionOutput,
TableTransformerPreTrainedModel: () => TableTransformerPreTrainedModel,
Tensor: () => Tensor,
Text2TextGenerationPipeline: () => Text2TextGenerationPipeline,
TextClassificationPipeline: () => TextClassificationPipeline,
TextGenerationPipeline: () => TextGenerationPipeline,
TextToAudioPipeline: () => TextToAudioPipeline,
TokenClassificationPipeline: () => TokenClassificationPipeline,
TokenClassifierOutput: () => TokenClassifierOutput,
TokenizerModel: () => TokenizerModel,
TrOCRForCausalLM: () => TrOCRForCausalLM,
TrOCRPreTrainedModel: () => TrOCRPreTrainedModel,
TranslationPipeline: () => TranslationPipeline,
UniSpeechForCTC: () => UniSpeechForCTC,
UniSpeechForSequenceClassification: () => UniSpeechForSequenceClassification,
UniSpeechModel: () => UniSpeechModel,
UniSpeechPreTrainedModel: () => UniSpeechPreTrainedModel,
UniSpeechSatForAudioFrameClassification: () => UniSpeechSatForAudioFrameClassification,
UniSpeechSatForCTC: () => UniSpeechSatForCTC,
UniSpeechSatForSequenceClassification: () => UniSpeechSatForSequenceClassification,
UniSpeechSatModel: () => UniSpeechSatModel,
UniSpeechSatPreTrainedModel: () => UniSpeechSatPreTrainedModel,
ViTFeatureExtractor: () => ViTFeatureExtractor,
ViTForImageClassification: () => ViTForImageClassification,
ViTImageProcessor: () => ViTImageProcessor,
ViTModel: () => ViTModel,
ViTPreTrainedModel: () => ViTPreTrainedModel,
VisionEncoderDecoderModel: () => VisionEncoderDecoderModel,
VitMatteForImageMatting: () => VitMatteForImageMatting,
VitMatteImageProcessor: () => VitMatteImageProcessor,
VitMattePreTrainedModel: () => VitMattePreTrainedModel,
VitsModel: () => VitsModel,
VitsModelOutput: () => VitsModelOutput,
VitsPreTrainedModel: () => VitsPreTrainedModel,
VitsTokenizer: () => VitsTokenizer,
Wav2Vec2BertForCTC: () => Wav2Vec2BertForCTC,
Wav2Vec2BertForSequenceClassification: () => Wav2Vec2BertForSequenceClassification,
Wav2Vec2BertModel: () => Wav2Vec2BertModel,
Wav2Vec2BertPreTrainedModel: () => Wav2Vec2BertPreTrainedModel,
Wav2Vec2CTCTokenizer: () => Wav2Vec2CTCTokenizer,
Wav2Vec2FeatureExtractor: () => Wav2Vec2FeatureExtractor,
Wav2Vec2ForAudioFrameClassification: () => Wav2Vec2ForAudioFrameClassification,
Wav2Vec2ForCTC: () => Wav2Vec2ForCTC,
Wav2Vec2ForSequenceClassification: () => Wav2Vec2ForSequenceClassification,
Wav2Vec2Model: () => Wav2Vec2Model,
Wav2Vec2PreTrainedModel: () => Wav2Vec2PreTrainedModel,
Wav2Vec2ProcessorWithLM: () => Wav2Vec2ProcessorWithLM,
WavLMForAudioFrameClassification: () => WavLMForAudioFrameClassification,
WavLMForCTC: () => WavLMForCTC,
WavLMForSequenceClassification: () => WavLMForSequenceClassification,
WavLMForXVector: () => WavLMForXVector,
WavLMModel: () => WavLMModel,
WavLMPreTrainedModel: () => WavLMPreTrainedModel,
WhisperFeatureExtractor: () => WhisperFeatureExtractor,
WhisperForConditionalGeneration: () => WhisperForConditionalGeneration,
WhisperModel: () => WhisperModel,
WhisperPreTrainedModel: () => WhisperPreTrainedModel,
WhisperProcessor: () => WhisperProcessor,
WhisperTokenizer: () => WhisperTokenizer,
XLMForQuestionAnswering: () => XLMForQuestionAnswering,
XLMForSequenceClassification: () => XLMForSequenceClassification,
XLMForTokenClassification: () => XLMForTokenClassification,
XLMModel: () => XLMModel,
XLMPreTrainedModel: () => XLMPreTrainedModel,
XLMRobertaForMaskedLM: () => XLMRobertaForMaskedLM,
XLMRobertaForQuestionAnswering: () => XLMRobertaForQuestionAnswering,
XLMRobertaForSequenceClassification: () => XLMRobertaForSequenceClassification,
XLMRobertaForTokenClassification: () => XLMRobertaForTokenClassification,
XLMRobertaModel: () => XLMRobertaModel,
XLMRobertaPreTrainedModel: () => XLMRobertaPreTrainedModel,
XLMRobertaTokenizer: () => XLMRobertaTokenizer,
XLMTokenizer: () => XLMTokenizer,
XLMWithLMHeadModel: () => XLMWithLMHeadModel,
XVectorOutput: () => XVectorOutput,
YolosFeatureExtractor: () => YolosFeatureExtractor,
YolosForObjectDetection: () => YolosForObjectDetection,
YolosModel: () => YolosModel,
YolosObjectDetectionOutput: () => YolosObjectDetectionOutput,
YolosPreTrainedModel: () => YolosPreTrainedModel,
ZeroShotAudioClassificationPipeline: () => ZeroShotAudioClassificationPipeline,
ZeroShotClassificationPipeline: () => ZeroShotClassificationPipeline,
ZeroShotImageClassificationPipeline: () => ZeroShotImageClassificationPipeline,
ZeroShotObjectDetectionPipeline: () => ZeroShotObjectDetectionPipeline,
bankers_round: () => bankers_round,
cat: () => cat,
cos_sim: () => cos_sim,
dot: () => dot,
dynamicTimeWarping: () => dynamicTimeWarping,
env: () => env,
getTopItems: () => getTopItems,
hanning: () => hanning,
interpolate: () => interpolate,
interpolate_data: () => interpolate_data,
layer_norm: () => layer_norm,
log_softmax: () => log_softmax,
magnitude: () => magnitude,
max: () => max,
mean: () => mean,
mean_pooling: () => mean_pooling,
medianFilter: () => medianFilter,
mel_filter_bank: () => mel_filter_bank,
min: () => min,
ones: () => ones,
ones_like: () => ones_like,
permute: () => permute,
permute_data: () => permute_data,
pipeline: () => pipeline,
quantize_embeddings: () => quantize_embeddings,
read_audio: () => read_audio,
round: () => round,
softmax: () => softmax,
spectrogram: () => spectrogram,
stack: () => stack,
std_mean: () => std_mean,
window_function: () => window_function
});
var init_transformers = __esm({
"node_modules/@xenova/transformers/src/transformers.js"() {
init_pipelines();
init_env();
init_models();
init_tokenizers();
init_processors();
init_configs();
init_audio();
init_image();
init_tensor();
init_maths();
}
});
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => MemexChatPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian5 = require("obsidian");
// src/ChatView.ts
var import_obsidian = require("obsidian");
var VIEW_TYPE_MEMEX_CHAT = "memex-chat-view";
var ChatView = class extends import_obsidian.ItemView {
constructor(leaf, plugin) {
super(leaf);
this.threads = [];
this.activeThreadId = null;
this.pendingContext = [];
this.explicitContext = [];
this.isLoading = false;
// Mention autocomplete state
this.mentionSelectedIdx = 0;
this.mentionMatches = [];
// Active prompt extension buttons (file paths)
this.activeExtensions = /* @__PURE__ */ new Set();
// ─── Sidebar History ──────────────────────────────────────────────────────
this.historyExpanded = false;
this.historyThreads = [];
this.plugin = plugin;
this.renderComponent = new import_obsidian.Component();
}
getViewType() {
return VIEW_TYPE_MEMEX_CHAT;
}
getDisplayText() {
return "Memex Chat";
}
getIcon() {
return "message-circle";
}
async onOpen() {
this.renderComponent.load();
this.loadThreads();
this.buildUI();
if (!this.activeThreadId && this.threads.length === 0) {
this.newThread();
} else if (!this.activeThreadId && this.threads.length > 0) {
this.switchThread(this.threads[0].id);
}
}
async onClose() {
this.renderComponent.unload();
this.saveThreads();
}
// ─── UI Construction ─────────────────────────────────────────────────────
buildUI() {
const root = this.containerEl.children[1];
root.empty();
root.addClass("vc-root");
const header = root.createDiv("vc-header");
header.createEl("span", { text: "Memex Chat", cls: "vc-header-title" });
const modeBtns = header.createDiv("vc-header-modes");
for (const pb of this.plugin.settings.promptButtons) {
const modeBtn = modeBtns.createEl("button", { text: pb.label, cls: "vc-mode-btn" });
modeBtn.onclick = () => {
if (this.activeExtensions.has(pb.filePath)) {
this.activeExtensions.delete(pb.filePath);
modeBtn.removeClass("vc-mode-btn--active");
} else {
this.activeExtensions.add(pb.filePath);
modeBtn.addClass("vc-mode-btn--active");
}
this.updateModeHint();
};
}
const headerActions = header.createDiv("vc-header-actions");
const newThreadBtn = headerActions.createEl("button", { cls: "vc-icon-btn", title: "Neuer Thread" });
newThreadBtn.innerHTML = `<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none"><path d="M12 5v14M5 12h14" stroke-width="2" stroke-linecap="round"/></svg>`;
newThreadBtn.onclick = () => this.newThread();
const rebuildBtn = headerActions.createEl("button", { cls: "vc-icon-btn", title: "Index neu aufbauen" });
rebuildBtn.innerHTML = `<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none"><path d="M4 4v5h5M20 20v-5h-5" stroke-width="2" stroke-linecap="round"/><path d="M4.07 9a8 8 0 0 1 14.72-1.65M19.93 15a8 8 0 0 1-14.72 1.65" stroke-width="2" stroke-linecap="round"/></svg>`;
rebuildBtn.onclick = async () => {
rebuildBtn.disabled = true;
this.setStatus("Indiziere Vault\u2026");
await this.plugin.rebuildIndex();
const ready = this.plugin.activeSearch.isIndexed();
this.setStatus(ready ? "\u2713 Index bereit" : "");
setTimeout(() => this.setStatus(""), 2e3);
rebuildBtn.disabled = false;
};
const main = root.createDiv("vc-main");
const sidebar = main.createDiv("vc-sidebar");
sidebar.createEl("div", { text: "Threads", cls: "vc-sidebar-title" });
this.threadListEl = sidebar.createDiv("vc-thread-list");
const chatArea = main.createDiv("vc-chat-area");
this.statusEl = chatArea.createDiv("vc-status");
this.messagesEl = chatArea.createDiv("vc-messages");
this.contextPreviewEl = chatArea.createDiv("vc-context-preview");
this.contextPreviewEl.style.display = "none";
const inputArea = chatArea.createDiv("vc-input-area");
this.modeHintEl = inputArea.createDiv("vc-mode-hint");
this.modeHintEl.style.display = "none";
const inputWrapper = inputArea.createDiv("vc-input-wrapper");
this.mentionDropdownEl = root.createDiv("vc-mention-dropdown");
this.mentionDropdownEl.style.display = "none";
this.inputEl = inputWrapper.createEl("textarea", {
cls: "vc-input",
attr: { placeholder: "Frage stellen\u2026 (@ f\xFCr Notiz)" }
});
this.inputEl.rows = 3;
const inputActions = inputArea.createDiv("vc-input-actions");
const contextBtn = inputActions.createEl("button", { cls: "vc-ctx-btn", title: "Kontext manuell ausw\xE4hlen" });
contextBtn.innerHTML = `<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" stroke-width="2"/><path d="M14 2v6h6M8 13h8M8 17h5" stroke-width="2" stroke-linecap="round"/></svg> Kontext`;
contextBtn.onclick = () => this.openContextPicker();
this.sendBtn = inputActions.createEl("button", { cls: "vc-send-btn" });
this.sendBtn.setText("Senden");
this.sendBtn.onclick = () => this.handleSend();
this.registerDomEvent(this.inputEl, "keydown", (e) => {
if (this.mentionDropdownEl.style.display !== "none") {
if (e.key === "ArrowDown") {
e.preventDefault();
this.moveMentionSelection(1);
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
this.moveMentionSelection(-1);
return;
}
if (e.key === "Enter" || e.key === "Tab") {
e.preventDefault();
this.confirmMentionSelection();
return;
}
if (e.key === "Escape") {
e.preventDefault();
this.hideMentionDropdown();
return;
}
}
if (e.key === "Enter") {
const isCmdEnter = e.metaKey || e.ctrlKey;
const sendOnEnter = this.plugin.settings.sendOnEnter;
if (isCmdEnter || sendOnEnter && !e.shiftKey) {
e.preventDefault();
e.stopPropagation();
this.handleSend();
}
}
});
this.registerDomEvent(this.inputEl, "input", () => this.handleInputChange());
this.renderThreadList();
}
// ─── Thread Management ────────────────────────────────────────────────────
newThread() {
const thread = {
id: Date.now().toString(),
title: "Neuer Chat",
messages: [],
created: Date.now(),
updated: Date.now()
};
this.threads.unshift(thread);
this.switchThread(thread.id);
this.saveThreads();
}
switchThread(id) {
this.saveThreads();
this.activeThreadId = id;
this.renderThreadList();
this.renderMessages();
this.clearContextPreview();
}
get activeThread() {
return this.threads.find((t) => t.id === this.activeThreadId);
}
deleteThread(id) {
this.threads = this.threads.filter((t) => t.id !== id);
if (this.activeThreadId === id) {
if (this.threads.length > 0)
this.switchThread(this.threads[0].id);
else
this.newThread();
}
this.saveThreads();
this.renderThreadList();
}
// ─── Send & Context ──────────────────────────────────────────────────────
async handleSend() {
const query = this.inputEl.value.trim();
if (!query || this.isLoading)
return;
if (!this.plugin.settings.apiKey) {
this.setStatus("\u26A0 Bitte API Key in den Einstellungen eingeben");
return;
}
const mentions = [];
const seenPaths = /* @__PURE__ */ new Set();
for (const file of this.app.vault.getMarkdownFiles()) {
if (query.includes(`@${file.basename}`) && !seenPaths.has(file.path)) {
mentions.push(file);
seenPaths.add(file.path);
}
}
if (this.activeExtensions.size === 0) {
if (this.plugin.settings.autoRetrieveContext && this.plugin.settings.showContextPreview) {
if (this.pendingContext.length === 0 && this.explicitContext.length === 0) {
await this.fetchAndShowContext(query, mentions);
return;
}
}
} else {
this.pendingContext = [];
this.explicitContext = [];
}
const dateFiles = [];
for (const pb of this.plugin.settings.promptButtons) {
if (pb.searchMode === "date" && this.activeExtensions.has(pb.filePath)) {
const { start, end, label } = this.parseDateRange(query);
const found = this.findFilesByDate(start, end, pb.searchFolders ?? []);
dateFiles.push(...found);
this.setStatus(`${found.length} Texte aus ${label} gefunden`);
}
}
await this.sendMessage(query, [...mentions, ...dateFiles]);
}
async fetchAndShowContext(query, mentions) {
this.setStatus("Suche relevante Notizen\u2026");
this.isLoading = true;
try {
const engine = this.plugin.activeSearch;
if (!engine.isIndexed()) {
this.setStatus(this.plugin.settings.useEmbeddings ? "Lade Embedding-Modell\u2026" : "Indiziere Vault\u2026");
this.attachEmbedProgress();
await engine.buildIndex();
this.detachEmbedProgress();
}
this.pendingContext = await engine.search(query, this.plugin.settings.maxContextNotes);
this.explicitContext = mentions;
this.renderContextPreview();
this.setStatus("Kontext bereit \u2014 Senden best\xE4tigen oder anpassen");
} catch (e) {
this.detachEmbedProgress();
this.setStatus("Fehler bei Kontextsuche: " + e.message);
}
this.isLoading = false;
}
/** Wire up EmbedSearch progress callbacks to the status bar */
attachEmbedProgress() {
const es = this.plugin.embedSearch;
if (!es)
return;
es.onModelStatus = (s) => this.setStatus(s);
es.onProgress = (done, total, speed) => {
const speedStr = speed > 0 ? ` \u2022 ${speed.toFixed(1)} N/s` : "";
const eta = speed > 0 && done < total ? ` \u2022 ~${Math.ceil((total - done) / speed)}s` : "";
this.setStatus(`Embedding ${done}/${total}${speedStr}${eta}`);
};
}
detachEmbedProgress() {
const es = this.plugin.embedSearch;
if (!es)
return;
es.onModelStatus = void 0;
es.onProgress = void 0;
}
async sendMessage(query, additionalFiles = []) {
this.isLoading = true;
this.sendBtn.disabled = true;
const thread = this.activeThread;
if (!thread)
return;
const contextFiles = [
...this.explicitContext,
...this.pendingContext.map((r) => r.file),
...additionalFiles
].filter((f, i, arr) => arr.findIndex((x) => x.path === f.path) === i);
const contextNotes = contextFiles.map((f) => f.path);
let contextText = "";
if (contextFiles.length > 0) {
this.setStatus(`Lade ${contextFiles.length} Notizen\u2026`);
const contents = await Promise.all(
contextFiles.map(async (f) => {
const content = await this.plugin.search.getContent(f, this.plugin.settings.maxCharsPerNote);
return `=== [[${f.basename}]] ===
${content}`;
})
);
contextText = "\n\n---\nKontext aus dem Vault:\n\n" + contents.join("\n\n");
}
const userMsg = {
role: "user",
content: query,
timestamp: Date.now(),
contextNotes
};
thread.messages.push(userMsg);
thread.updated = Date.now();
if (thread.messages.length === 1) {
thread.title = query.slice(0, 50) + (query.length > 50 ? "\u2026" : "");
}
this.inputEl.value = "";
this.pendingContext = [];
this.explicitContext = [];
this.clearContextPreview();
this.modeHintEl.style.display = "none";
this.renderMessages();
this.renderThreadList();
const assistantMsg = {
role: "assistant",
content: "",
timestamp: Date.now(),
isStreaming: true
};
thread.messages.push(assistantMsg);
this.renderMessages();
const claudeMessages = thread.messages.slice(0, -1).slice(-10).map((m) => ({
role: m.role,
content: m.content
}));
claudeMessages.push({
role: "user",
content: query + contextText
});
this.setStatus("Claude denkt\u2026");
let systemPrompt = this.plugin.settings.systemPrompt;
const ctxPath = this.plugin.settings.systemContextFile;
if (ctxPath) {
const ctxFile = this.app.metadataCache.getFirstLinkpathDest(ctxPath, "") ?? this.app.vault.getAbstractFileByPath(ctxPath + ".md") ?? this.app.vault.getAbstractFileByPath(ctxPath);
if (ctxFile instanceof import_obsidian.TFile) {
systemPrompt += "\n\n---\n" + await this.app.vault.cachedRead(ctxFile);
}
}
for (const filePath of this.activeExtensions) {
const file = this.app.metadataCache.getFirstLinkpathDest(filePath, "") ?? this.app.vault.getAbstractFileByPath(filePath + ".md") ?? this.app.vault.getAbstractFileByPath(filePath);
if (file instanceof import_obsidian.TFile) {
const ext = await this.app.vault.cachedRead(file);
systemPrompt += "\n\n---\n" + ext;
}
}
try {
const stream = this.plugin.claude.streamChat(claudeMessages, {
apiKey: this.plugin.settings.apiKey,
model: this.plugin.settings.model,
maxTokens: this.plugin.settings.maxTokens,
systemPrompt
});
for await (const chunk of stream) {
if (chunk.type === "text" && chunk.text) {
assistantMsg.content += chunk.text;
this.updateLastMessage(assistantMsg.content);
} else if (chunk.type === "error") {
assistantMsg.content = `\u274C Fehler: ${chunk.error}`;
this.updateLastMessage(assistantMsg.content);
break;
}
}
assistantMsg.isStreaming = false;
assistantMsg.contextNotes = contextNotes;
this.setStatus("");
this.renderMessages();
this.saveThreads();
if (this.plugin.settings.saveThreadsToVault) {
await this.saveThreadToVault(thread);
}
} catch (e) {
assistantMsg.content = `\u274C Fehler: ${e.message}`;
assistantMsg.isStreaming = false;
this.renderMessages();
this.setStatus("");
}
this.isLoading = false;
this.sendBtn.disabled = false;
this.scrollToBottom();
}
// ─── Context Preview ──────────────────────────────────────────────────────
renderContextPreview() {
this.contextPreviewEl.empty();
this.contextPreviewEl.style.display = "block";
const header = this.contextPreviewEl.createDiv("vc-ctx-header");
header.createEl("span", { text: `\u{1F4CE} Kontext (${this.pendingContext.length} Notizen)`, cls: "vc-ctx-title" });
const actions = header.createDiv("vc-ctx-actions");
const confirmBtn = actions.createEl("button", { cls: "vc-send-btn vc-send-btn--sm", text: "\u2713 Senden" });
confirmBtn.onclick = () => this.sendMessage(this.inputEl.value.trim());
const clearBtn = actions.createEl("button", { cls: "vc-ctx-btn", text: "\u2717 Ohne Kontext" });
clearBtn.onclick = () => {
this.pendingContext = [];
this.explicitContext = [];
this.clearContextPreview();
this.sendMessage(this.inputEl.value.trim());
};
const list = this.contextPreviewEl.createDiv("vc-ctx-list");
for (const result of this.pendingContext) {
const item = list.createDiv("vc-ctx-item");
const score = Math.round(result.score * 100);
const itemHeader = item.createDiv("vc-ctx-item-header");
const titleEl = itemHeader.createEl("span", { text: result.title, cls: "vc-ctx-item-title" });
titleEl.onclick = () => this.app.workspace.openLinkText(result.file.path, "", "tab");
itemHeader.createEl("span", { text: `${score}%`, cls: "vc-ctx-score" });
const removeBtn = itemHeader.createEl("button", { cls: "vc-icon-btn vc-ctx-remove", title: "Entfernen" });
removeBtn.innerHTML = `\u2715`;
removeBtn.onclick = () => {
this.pendingContext = this.pendingContext.filter((r) => r.file.path !== result.file.path);
this.renderContextPreview();
};
const excerpt = item.createDiv("vc-ctx-excerpt");
excerpt.setText(result.excerpt.slice(0, 120) + "\u2026");
}
}
clearContextPreview() {
this.contextPreviewEl.style.display = "none";
this.contextPreviewEl.empty();
this.pendingContext = [];
this.explicitContext = [];
this.setStatus("");
}
updateModeHint() {
const hints = [];
for (const pb of this.plugin.settings.promptButtons) {
if (this.activeExtensions.has(pb.filePath) && pb.helpText) {
hints.push(pb.helpText);
}
}
if (hints.length > 0) {
this.modeHintEl.empty();
for (const hint of hints) {
const div = this.modeHintEl.createDiv("vc-mode-hint-text");
div.textContent = hint;
}
this.modeHintEl.style.display = "block";
this.inputEl.placeholder = "";
} else {
this.modeHintEl.style.display = "none";
this.inputEl.placeholder = "Frage stellen\u2026 (@ f\xFCr Notiz)";
}
}
async openContextPicker() {
const lastUserMsg = [...this.activeThread?.messages ?? []].reverse().find((m) => m.role === "user")?.content ?? "";
const query = this.inputEl.value.trim() || lastUserMsg;
this.setStatus("Suche Notizen\u2026");
try {
const engine = this.plugin.activeSearch;
if (!engine.isIndexed()) {
this.attachEmbedProgress();
await engine.buildIndex();
this.detachEmbedProgress();
}
const results = await engine.search(query, this.plugin.settings.maxContextNotes);
this.pendingContext = results;
this.renderContextPreview();
this.setStatus("");
} catch (e) {
this.detachEmbedProgress();
this.setStatus("Fehler: " + e.message);
}
}
// ─── Rendering ────────────────────────────────────────────────────────────
renderThreadList() {
this.threadListEl.empty();
for (const thread of this.threads) {
const item = this.threadListEl.createDiv("vc-thread-item" + (thread.id === this.activeThreadId ? " vc-thread-item--active" : ""));
const titleEl = item.createEl("span", { text: thread.title, cls: "vc-thread-title" });
titleEl.onclick = () => this.switchThread(thread.id);
titleEl.ondblclick = (e) => {
e.stopPropagation();
this.startRenameThread(thread, titleEl);
};
const del = item.createEl("button", { cls: "vc-icon-btn vc-thread-del", title: "L\xF6schen" });
del.innerHTML = "\u2715";
del.onclick = (e) => {
e.stopPropagation();
this.deleteThread(thread.id);
};
}
this.renderHistorySection();
}
startRenameThread(thread, titleEl) {
const input = document.createElement("input");
input.className = "vc-thread-rename";
input.value = thread.title;
titleEl.replaceWith(input);
input.select();
const finish = () => {
const newTitle = input.value.trim() || thread.title;
thread.title = newTitle;
this.saveThreads();
this.renderThreadList();
};
input.addEventListener("blur", finish);
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
input.blur();
}
if (e.key === "Escape") {
input.value = thread.title;
input.blur();
}
});
input.focus();
}
renderMessages() {
this.messagesEl.empty();
const thread = this.activeThread;
if (!thread || thread.messages.length === 0) {
const empty = this.messagesEl.createDiv("vc-empty");
empty.createEl("div", { text: "\u{1F4AC}", cls: "vc-empty-icon" });
empty.createEl("div", { text: "Stell eine Frage \u2014 ich suche passende Notizen aus deinem Vault.", cls: "vc-empty-text" });
empty.createEl("div", { text: "Tipp: Nutze @Notizname um eine Notiz direkt einzubinden.", cls: "vc-empty-hint" });
return;
}
for (const msg of thread.messages) {
this.renderMessage(msg);
}
this.scrollToBottom();
}
renderMessage(msg) {
const msgEl = this.messagesEl.createDiv(`vc-msg vc-msg--${msg.role}`);
const bubble = msgEl.createDiv("vc-bubble");
if (msg.role === "user") {
bubble.setText(msg.content);
} else {
const mdEl = bubble.createDiv("vc-md");
if (msg.isStreaming) {
mdEl.setText(msg.content);
mdEl.createEl("span", { cls: "vc-cursor", text: "\u2588" });
} else {
import_obsidian.MarkdownRenderer.render(this.app, msg.content, mdEl, "", this.renderComponent);
mdEl.querySelectorAll("a.internal-link").forEach((a) => {
const href = a.getAttribute("href") ?? a.textContent ?? "";
const exists2 = !!this.app.metadataCache.getFirstLinkpathDest(href, "");
if (!exists2) {
a.classList.add("is-unresolved");
const similar = this.plugin.search.findSimilarByName(href, 2, 0.45);
if (similar.length > 0) {
const hint = a.parentElement.createEl("span", { cls: "vc-link-hint" });
hint.createEl("span", { text: " \u2192 \xC4hnliche Notiz: ", cls: "vc-link-hint-label" });
similar.forEach((r, i) => {
if (i > 0)
hint.appendText(", ");
const link = hint.createEl("a", { text: r.title, cls: "internal-link vc-link-hint-target" });
link.addEventListener("click", (e) => {
e.preventDefault();
this.app.workspace.openLinkText(r.file.path, "", false);
});
});
a.insertAdjacentElement("afterend", hint);
}
}
a.addEventListener("click", (e) => {
e.preventDefault();
this.app.workspace.openLinkText(href, "", "tab");
});
});
}
}
if (!msg.isStreaming && msg.contextNotes && msg.contextNotes.length > 0) {
const sources = msgEl.createDiv("vc-sources");
sources.createEl("span", { text: "Quellen: ", cls: "vc-sources-label" });
for (const notePath of msg.contextNotes) {
const file = this.app.vault.getAbstractFileByPath(notePath);
const name2 = file instanceof import_obsidian.TFile ? file.basename : notePath.split("/").pop() ?? notePath;
const link = sources.createEl("span", { text: `[[${name2}]]`, cls: "vc-source-link" });
link.onclick = () => this.app.workspace.openLinkText(notePath, "", "tab");
}
}
if (!msg.isStreaming && msg.role === "assistant") {
const actions = msgEl.createDiv("vc-msg-actions");
const copyBtn = actions.createEl("button", { cls: "vc-msg-action-btn", title: "Antwort kopieren" });
copyBtn.innerHTML = `<svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" fill="none"><rect x="9" y="9" width="13" height="13" rx="2" stroke-width="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" stroke-width="2"/></svg> Kopieren`;
copyBtn.onclick = async () => {
await navigator.clipboard.writeText(msg.content);
copyBtn.textContent = "\u2713 Kopiert";
setTimeout(() => {
copyBtn.innerHTML = `<svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" fill="none"><rect x="9" y="9" width="13" height="13" rx="2" stroke-width="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" stroke-width="2"/></svg> Kopieren`;
}, 2e3);
};
const saveBtn = actions.createEl("button", { cls: "vc-msg-action-btn", title: "Als neue Notiz speichern" });
saveBtn.innerHTML = `<svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" fill="none"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" stroke-width="2"/><polyline points="17 21 17 13 7 13 7 21" stroke-width="2"/><polyline points="7 3 7 8 15 8" stroke-width="2"/></svg> Als Notiz`;
saveBtn.onclick = async () => {
await this.saveResponseAsNote(msg.content);
};
}
}
async saveResponseAsNote(content) {
const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
const firstLine = content.split("\n").find((l) => l.trim()) ?? "Claude Antwort";
const title = firstLine.replace(/^#+\s*/, "").replace(/[\\/:*?"<>|]/g, " ").slice(0, 60).trim();
const noteContent = `---
created: ${date}
tags: [chat, claude]
---
${content}`;
try {
const folder = this.app.fileManager.getNewFileParent("");
const folderPath = folder.path === "/" ? "" : folder.path + "/";
const fileName = `${folderPath}${date} ${title}.md`;
const existing = this.app.vault.getAbstractFileByPath(fileName);
const file = existing instanceof import_obsidian.TFile ? await this.app.vault.modify(existing, noteContent).then(() => existing) : await this.app.vault.create(fileName, noteContent);
this.app.workspace.openLinkText(file.path, "", "tab");
} catch (e) {
this.setStatus("\u26A0 Fehler beim Speichern: " + e.message);
}
}
updateLastMessage(content) {
const messages = this.messagesEl.querySelectorAll(".vc-msg--assistant");
const last = messages[messages.length - 1];
if (!last)
return;
const mdEl = last.querySelector(".vc-md");
if (mdEl) {
mdEl.textContent = content;
const cursor = mdEl.querySelector(".vc-cursor");
if (!cursor)
mdEl.createEl("span", { cls: "vc-cursor", text: "\u2588" });
}
this.scrollToBottom();
}
scrollToBottom() {
this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
}
setStatus(text) {
this.statusEl.setText(text);
this.statusEl.style.display = text ? "block" : "none";
}
/** Pre-fill the input textarea (used from plugin commands) */
setInputValue(value) {
this.inputEl.value = value;
}
/** Add files as explicit context (used from plugin commands) */
setExplicitContext(files) {
this.explicitContext = files;
}
handleInputChange() {
this.inputEl.style.height = "auto";
this.inputEl.style.height = Math.min(this.inputEl.scrollHeight, 200) + "px";
const cursor = this.inputEl.selectionStart ?? 0;
const textBefore = this.inputEl.value.slice(0, cursor);
const match = textBefore.match(/@([^@\n[\]]{2,})$/);
if (match) {
this.updateMentionDropdown(match[1]);
} else {
this.hideMentionDropdown();
}
}
updateMentionDropdown(query) {
const lower = query.toLowerCase();
this.mentionMatches = this.app.vault.getMarkdownFiles().map((f) => f.basename).filter((name2) => name2.toLowerCase().includes(lower)).slice(0, 8);
if (this.mentionMatches.length === 0) {
this.hideMentionDropdown();
return;
}
this.mentionSelectedIdx = 0;
this.renderMentionDropdown();
const rect = this.inputEl.getBoundingClientRect();
const el = this.mentionDropdownEl;
el.style.position = "fixed";
el.style.left = rect.left + "px";
el.style.width = rect.width + "px";
el.style.top = "auto";
el.style.bottom = window.innerHeight - rect.top + 4 + "px";
el.style.display = "block";
}
renderMentionDropdown() {
this.mentionDropdownEl.empty();
this.mentionMatches.forEach((name2, i) => {
const item = this.mentionDropdownEl.createDiv(
i === this.mentionSelectedIdx ? "vc-mention-item vc-mention-item--active" : "vc-mention-item"
);
item.setText(name2);
item.addEventListener("mousedown", (e) => {
e.preventDefault();
this.insertMention(name2);
});
});
}
moveMentionSelection(dir) {
this.mentionSelectedIdx = (this.mentionSelectedIdx + dir + this.mentionMatches.length) % this.mentionMatches.length;
this.renderMentionDropdown();
}
confirmMentionSelection() {
const name2 = this.mentionMatches[this.mentionSelectedIdx];
if (name2)
this.insertMention(name2);
}
insertMention(basename) {
const cursor = this.inputEl.selectionStart ?? 0;
const text = this.inputEl.value;
const textBefore = text.slice(0, cursor);
const match = textBefore.match(/@([^@\n]{2,})$/);
if (!match)
return;
const start = cursor - match[0].length;
const replacement = `@${basename}`;
this.inputEl.value = text.slice(0, start) + replacement + text.slice(cursor);
const newCursor = start + replacement.length;
this.inputEl.setSelectionRange(newCursor, newCursor);
this.hideMentionDropdown();
}
hideMentionDropdown() {
this.mentionDropdownEl.style.display = "none";
this.mentionDropdownEl.empty();
this.mentionMatches = [];
this.mentionSelectedIdx = 0;
}
// ─── Date-based context search ────────────────────────────────────────────
parseDateRange(query) {
const now = /* @__PURE__ */ new Date();
const lower = query.toLowerCase();
if (/letzt[eaem]n?\s+monat|vorig[eaem]n?\s+monat/.test(lower)) {
const start2 = new Date(now.getFullYear(), now.getMonth() - 1, 1);
const end2 = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59);
return { start: start2, end: end2, label: start2.toLocaleDateString("de-DE", { month: "long", year: "numeric" }) };
}
const MONTHS = {
januar: 0,
februar: 1,
"m\xE4rz": 2,
april: 3,
mai: 4,
juni: 5,
juli: 6,
august: 7,
september: 8,
oktober: 9,
november: 10,
dezember: 11
};
for (const [name2, idx] of Object.entries(MONTHS)) {
if (lower.includes(name2)) {
const yearMatch = lower.match(/\b(20\d{2})\b/);
const year = yearMatch ? parseInt(yearMatch[1]) : now.getFullYear();
const start2 = new Date(year, idx, 1);
const end2 = new Date(year, idx + 1, 0, 23, 59, 59);
return { start: start2, end: end2, label: start2.toLocaleDateString("de-DE", { month: "long", year: "numeric" }) };
}
}
const start = new Date(now.getFullYear(), now.getMonth(), 1);
const end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);
return { start, end, label: start.toLocaleDateString("de-DE", { month: "long", year: "numeric" }) };
}
getFileDate(file) {
const m = file.basename.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (m)
return new Date(+m[1], +m[2] - 1, +m[3]);
const fm = this.app.metadataCache.getFileCache(file)?.frontmatter;
if (fm) {
const raw = fm["created"] ?? fm["date"] ?? fm["datum"];
if (raw) {
const d = new Date(raw);
if (!isNaN(d.getTime()))
return d;
}
}
return new Date(file.stat.ctime);
}
findFilesByDate(start, end, folders) {
const s = start.getTime();
const e = end.getTime();
return this.app.vault.getMarkdownFiles().filter((file) => {
if (folders.length > 0 && !folders.some((f) => file.path.startsWith(f.endsWith("/") ? f : f + "/")))
return false;
const t = this.getFileDate(file).getTime();
return t >= s && t <= e;
});
}
// ─── Persistence ─────────────────────────────────────────────────────────
loadThreads() {
this.threads = this.plugin.data.threads ?? [];
}
saveThreads() {
this.plugin.data.threads = this.threads;
this.plugin.saveData(this.plugin.data);
}
async saveThreadToVault(thread) {
try {
const folder = this.plugin.settings.threadsFolder;
await this.app.vault.createFolder(folder).catch(() => {
});
const d = new Date(thread.created);
const ts = d.getFullYear().toString() + String(d.getMonth() + 1).padStart(2, "0") + String(d.getDate()).padStart(2, "0") + String(d.getHours()).padStart(2, "0") + String(d.getMinutes()).padStart(2, "0") + String(d.getSeconds()).padStart(2, "0");
const date = d.toISOString().slice(0, 10);
const safeName = thread.title.replace(/[\\/:*?"<>|]/g, " ").slice(0, 60);
const fileName = `${folder}/${ts} ${safeName}.md`;
let content = `---
created: ${date}
id: ${thread.id}
tags: [chat]
---
# ${thread.title}
`;
for (const msg of thread.messages) {
const role = msg.role === "user" ? "**Du**" : "**Claude**";
content += `${role}: ${msg.content}
`;
if (msg.contextNotes && msg.contextNotes.length > 0) {
const names = msg.contextNotes.map((p) => `[[${p.split("/").pop()?.replace(".md", "") ?? p}]]`);
content += `> Kontext: ${names.join(", ")}
`;
}
}
const existing = this.app.vault.getAbstractFileByPath(fileName);
if (existing instanceof import_obsidian.TFile) {
await this.app.vault.modify(existing, content);
} else {
await this.app.vault.create(fileName, content);
}
} catch {
}
}
/** Parse a vault chat file back into a Thread object */
async parseThreadFromVault(file) {
try {
const raw = await this.app.vault.cachedRead(file);
let id;
const fmMatch = raw.match(/^---\n([\s\S]*?)\n---/);
if (fmMatch) {
const idMatch = fmMatch[1].match(/^id:\s*(.+)$/m);
if (idMatch)
id = idMatch[1].trim();
}
const titleMatch = raw.match(/^# (.+)$/m);
const title = titleMatch ? titleMatch[1].trim() : file.basename;
const messages = [];
const body = fmMatch ? raw.slice(fmMatch[0].length) : raw;
const lines = body.split("\n");
let currentRole = null;
let currentContent = [];
const flush = () => {
if (currentRole && currentContent.length > 0) {
messages.push({
role: currentRole,
content: currentContent.join("\n").trim(),
timestamp: file.stat.ctime
});
}
currentContent = [];
currentRole = null;
};
for (const line of lines) {
if (line.startsWith("**Du**: ")) {
flush();
currentRole = "user";
currentContent.push(line.slice("**Du**: ".length));
} else if (line.startsWith("**Claude**: ")) {
flush();
currentRole = "assistant";
currentContent.push(line.slice("**Claude**: ".length));
} else if (currentRole) {
if (line.startsWith("> Kontext:"))
continue;
currentContent.push(line);
}
}
flush();
return {
id: id ?? file.stat.ctime.toString(),
title,
messages,
created: file.stat.ctime,
updated: file.stat.mtime
};
} catch {
return null;
}
}
/** Load saved vault files not already in this.threads */
async loadHistoryFromVault() {
const folder = this.plugin.settings.threadsFolder;
const loadedIds = new Set(this.threads.map((t) => t.id));
const results = [];
const files = this.app.vault.getMarkdownFiles().filter((f) => f.path.startsWith(folder + "/")).sort((a, b) => b.stat.mtime - a.stat.mtime);
for (const file of files) {
const thread = await this.parseThreadFromVault(file);
if (thread && !loadedIds.has(thread.id)) {
results.push(thread);
loadedIds.add(thread.id);
}
}
return results;
}
async renderHistorySection() {
const existing = this.threadListEl.parentElement?.querySelector(".vc-history-section");
if (existing)
existing.remove();
if (!this.plugin.settings.saveThreadsToVault)
return;
const sidebar = this.threadListEl.parentElement;
const section = sidebar.createDiv("vc-history-section");
const toggle = section.createDiv("vc-history-toggle");
toggle.createEl("span", { text: this.historyExpanded ? "\u25BE" : "\u25B8", cls: "vc-history-arrow" });
toggle.createEl("span", { text: "Verlauf", cls: "vc-history-label" });
const listEl = section.createDiv("vc-history-list");
listEl.style.display = this.historyExpanded ? "block" : "none";
toggle.onclick = async () => {
this.historyExpanded = !this.historyExpanded;
toggle.empty();
toggle.createEl("span", { text: this.historyExpanded ? "\u25BE" : "\u25B8", cls: "vc-history-arrow" });
toggle.createEl("span", { text: "Verlauf", cls: "vc-history-label" });
listEl.style.display = this.historyExpanded ? "block" : "none";
if (this.historyExpanded && this.historyThreads.length === 0) {
listEl.setText("Lade\u2026");
this.historyThreads = await this.loadHistoryFromVault();
this.renderHistoryList(listEl);
}
};
if (this.historyExpanded) {
if (this.historyThreads.length === 0) {
this.historyThreads = await this.loadHistoryFromVault();
}
this.renderHistoryList(listEl);
}
}
renderHistoryList(listEl) {
listEl.empty();
if (this.historyThreads.length === 0) {
listEl.createEl("div", { text: "Keine gespeicherten Chats", cls: "vc-history-empty" });
return;
}
for (const thread of this.historyThreads) {
const item = listEl.createDiv("vc-history-item");
item.createEl("span", { text: thread.title, cls: "vc-thread-title" });
item.onclick = () => {
this.threads.unshift(thread);
this.historyThreads = this.historyThreads.filter((t) => t.id !== thread.id);
this.switchThread(thread.id);
this.renderHistoryList(listEl);
};
}
}
};
// src/VaultSearch.ts
var VaultSearch = class {
// tokens from priority properties count 5x
constructor(app) {
this.docVectors = /* @__PURE__ */ new Map();
// path -> term -> tfidf
this.idf = /* @__PURE__ */ new Map();
this.docContents = /* @__PURE__ */ new Map();
this.indexed = false;
this.indexing = false;
/** Frontmatter properties whose values are boosted during indexing */
this.priorityProperties = ["collection", "related", "up", "tags"];
this.propertyBoost = 5;
this.app = app;
}
/** Tokenize text: lowercase, split on non-word chars, keep umlauts */
tokenize(text) {
return text.toLowerCase().replace(/[^\wäöüßÄÖÜ\s]/g, " ").split(/\s+/).filter((t) => t.length > 2);
}
/** Strip YAML frontmatter and Obsidian-specific markup */
cleanContent(raw) {
let content = raw;
if (content.startsWith("---")) {
const end = content.indexOf("\n---", 3);
if (end > 0)
content = content.slice(end + 4);
}
content = content.replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g, (_, target, alias) => alias || target);
content = content.replace(/!\[.*?\]\(.*?\)/g, "");
content = content.replace(/\[([^\]]+)\]\(.*?\)/g, "$1");
content = content.replace(/>\s*\[!\w+\][+-]?\s*/g, "");
content = content.replace(/^#{1,6}\s+/gm, "");
return content;
}
/** Build or rebuild the TF-IDF index */
async buildIndex() {
if (this.indexing)
return;
this.indexing = true;
this.indexed = false;
this.docVectors.clear();
this.idf.clear();
this.docContents.clear();
try {
const files = this.app.vault.getMarkdownFiles();
const total = files.length;
const df = /* @__PURE__ */ new Map();
const tfs = /* @__PURE__ */ new Map();
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (this.onProgress && i % 100 === 0)
this.onProgress(i, total);
try {
const raw = await this.app.vault.cachedRead(file);
const clean = this.cleanContent(raw);
this.docContents.set(file.path, clean);
const tokens = this.tokenize(clean + " " + file.basename);
const tf = /* @__PURE__ */ new Map();
for (const t of tokens) {
tf.set(t, (tf.get(t) ?? 0) + 1);
}
const fm = this.app.metadataCache.getFileCache(file)?.frontmatter ?? {};
for (const prop of this.priorityProperties) {
const val = fm[prop];
if (!val)
continue;
const text = Array.isArray(val) ? val.join(" ") : String(val);
for (const t of this.tokenize(text)) {
tf.set(t, (tf.get(t) ?? 0) + this.propertyBoost);
}
}
const maxTf = Math.max(...tf.values(), 1);
const normalizedTf = /* @__PURE__ */ new Map();
for (const [t, count] of tf) {
normalizedTf.set(t, count / maxTf);
}
tfs.set(file.path, normalizedTf);
for (const t of tf.keys()) {
df.set(t, (df.get(t) ?? 0) + 1);
}
} catch {
}
}
const N = files.length;
for (const [term, docCount] of df) {
this.idf.set(term, Math.log(N / docCount + 1));
}
for (const [path3, tf] of tfs) {
const vec = /* @__PURE__ */ new Map();
let norm = 0;
for (const [term, tfVal] of tf) {
const idfVal = this.idf.get(term) ?? 0;
const tfidf = tfVal * idfVal;
vec.set(term, tfidf);
norm += tfidf * tfidf;
}
norm = Math.sqrt(norm);
if (norm > 0) {
for (const [term, val] of vec) {
vec.set(term, val / norm);
}
}
this.docVectors.set(path3, vec);
}
this.indexed = true;
if (this.onProgress)
this.onProgress(total, total);
} finally {
this.indexing = false;
}
}
isIndexed() {
return this.indexed;
}
/** Find notes with similar names (no index required). Uses substring + word-overlap scoring. */
findSimilarByName(query, topK = 2, minScore = 0.45) {
const normalize = (s) => s.toLowerCase().replace(/[^\wäöüß\s]/gi, " ").trim();
const words = (s) => new Set(s.split(/\s+/).filter((w) => w.length > 1));
const q = normalize(query);
const qWords = words(q);
const scored = [];
for (const file of this.app.vault.getMarkdownFiles()) {
const name2 = normalize(file.basename);
const nameWords = words(name2);
let score = 0;
if (name2.includes(q) || q.includes(name2))
score = 0.9;
const intersection = [...qWords].filter((w) => nameWords.has(w)).length;
const union = (/* @__PURE__ */ new Set([...qWords, ...nameWords])).size;
if (union > 0)
score = Math.max(score, intersection / union);
if (score >= minScore)
scored.push([file, score]);
}
scored.sort((a, b) => b[1] - a[1]);
return scored.slice(0, topK).map(([file, score]) => ({
file,
score,
excerpt: "",
title: file.basename
}));
}
/** Search for the top-K most similar notes to the query */
async search(query, topK = 8) {
if (!this.indexed)
await this.buildIndex();
const tokens = this.tokenize(query);
const qtf = /* @__PURE__ */ new Map();
for (const t of tokens)
qtf.set(t, (qtf.get(t) ?? 0) + 1);
const qMax = Math.max(...qtf.values(), 1);
const qvec = /* @__PURE__ */ new Map();
let qnorm = 0;
for (const [t, count] of qtf) {
const tfidf = count / qMax * (this.idf.get(t) ?? 0);
qvec.set(t, tfidf);
qnorm += tfidf * tfidf;
}
qnorm = Math.sqrt(qnorm);
if (qnorm > 0)
for (const [t, v] of qvec)
qvec.set(t, v / qnorm);
const scores = [];
for (const [path3, vec] of this.docVectors) {
let score = 0;
for (const [t, qv] of qvec) {
const dv = vec.get(t) ?? 0;
score += qv * dv;
}
if (score > 0.01)
scores.push([path3, score]);
}
scores.sort((a, b) => b[1] - a[1]);
const top = scores.slice(0, topK);
const files = this.app.vault.getMarkdownFiles();
const fileMap = new Map(files.map((f) => [f.path, f]));
return top.map(([path3, score]) => {
const file = fileMap.get(path3);
if (!file)
return null;
const content = this.docContents.get(path3) ?? "";
const excerpt = this.buildExcerpt(content, query, 300);
return { file, score, excerpt, title: file.basename };
}).filter(Boolean);
}
/** Get note content for context injection */
async getContent(file, maxChars = 3e3) {
try {
const raw = await this.app.vault.cachedRead(file);
return this.cleanContent(raw).slice(0, maxChars);
} catch {
return "";
}
}
buildExcerpt(content, query, maxLen) {
const queryWords = query.toLowerCase().split(/\s+/);
const lower = content.toLowerCase();
let bestPos = 0;
let bestScore = 0;
for (let i = 0; i < content.length - maxLen; i += 50) {
const window2 = lower.slice(i, i + maxLen);
const score = queryWords.filter((w) => window2.includes(w)).length;
if (score > bestScore) {
bestScore = score;
bestPos = i;
}
}
let excerpt = content.slice(bestPos, bestPos + maxLen).trim();
if (bestPos > 0)
excerpt = "\u2026" + excerpt;
if (bestPos + maxLen < content.length)
excerpt += "\u2026";
return excerpt;
}
};
// src/EmbedSearch.ts
var import_fs3 = require("fs");
var import_path3 = require("path");
var EMBEDDING_MODELS = [
{ id: "TaylorAI/bge-micro-v2", name: "BGE Micro v2 (schnell, 384-dim, empfohlen)" },
{ id: "Xenova/all-MiniLM-L6-v2", name: "MiniLM L6 v2 (384-dim)" },
{ id: "Xenova/multilingual-e5-small", name: "Multilingual E5 Small (mehrsprachig, DE/EN)" },
{ id: "Xenova/paraphrase-multilingual-MiniLM-L12-v2", name: "Multilingual MiniLM L12 (mehrsprachig)" }
];
var EmbedSearch = class {
constructor(app, modelId) {
this.excludeFolders = [];
// vault folder prefixes to skip
this.contextProperties = [];
// frontmatter keys whose links get a score boost
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.pipe = null;
this.cache = /* @__PURE__ */ new Map();
// vaultPath → entry
this.vecs = /* @__PURE__ */ new Map();
this.indexed = false;
this.indexing = false;
// ─── Incremental re-embed on file change ─────────────────────────────────
this.reembedTimers = /* @__PURE__ */ new Map();
this.app = app;
this.modelId = modelId;
}
isIndexed() {
return this.indexed;
}
// ─── Paths ───────────────────────────────────────────────────────────────
get vaultRoot() {
return this.app.vault.adapter.basePath;
}
get baseDir() {
return (0, import_path3.join)(this.vaultRoot, ".memex-chat");
}
get modelsDir() {
return (0, import_path3.join)(this.baseDir, "models");
}
get embedDir() {
return (0, import_path3.join)(this.baseDir, "embeddings");
}
get manifestPath() {
return (0, import_path3.join)(this.embedDir, ".manifest.json");
}
/** Disk path for the embedding of a vault-relative note path (e.g. "folder/note.md") */
noteEmbedPath(vaultPath) {
return (0, import_path3.join)(this.embedDir, vaultPath.replace(/\.md$/, ".ajson"));
}
// ─── Pipeline ────────────────────────────────────────────────────────────
async loadPipeline() {
if (this.pipe)
return;
const { pipeline: pipeline2, env: env3 } = (init_transformers(), __toCommonJS(transformers_exports));
env3.backends.onnx.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.14.0/dist/";
env3.backends.onnx.wasm.proxy = false;
env3.backends.onnx.wasm.numThreads = 1;
env3.allowLocalModels = false;
env3.allowRemoteModels = true;
env3.useBrowserCache = false;
env3.useFSCache = true;
env3.cacheDir = this.modelsDir;
const progress_callback = (p) => {
if (!this.onModelStatus)
return;
if (p.status === "initiate") {
this.onModelStatus(`Lade Modell: ${p.name ?? p.file ?? ""}\u2026`);
} else if (p.status === "download") {
const pct = p.progress != null ? ` ${Math.round(p.progress)}%` : "";
const mb = p.total ? ` (${(p.total / 1e6).toFixed(1)} MB)` : "";
this.onModelStatus(`Download${pct}${mb}: ${p.file ?? ""}`);
} else if (p.status === "ready") {
this.onModelStatus("Modell bereit");
}
};
this.pipe = await pipeline2("feature-extraction", this.modelId, {
quantized: true,
progress_callback
});
}
async embed(text) {
await this.loadPipeline();
const result = await this.pipe(text.slice(0, 512), { pooling: "mean", normalize: true });
return Array.from(result.data);
}
/** embed() with a hard timeout; rejects with "embed timeout" if exceeded. */
embedWithTimeout(text, ms = 13e3) {
return Promise.race([
this.embed(text),
new Promise(
(_, reject) => setTimeout(() => reject(new Error("embed timeout")), ms)
)
]);
}
cosine(a, b) {
let dot2 = 0;
for (let i = 0; i < a.length; i++)
dot2 += a[i] * b[i];
return dot2;
}
// ─── Index ────────────────────────────────────────────────────────────────
async buildIndex() {
if (this.indexing)
return;
this.indexing = true;
this.indexed = false;
this.vecs.clear();
const changed = [];
let pipelineError = null;
try {
await import_fs3.promises.mkdir(this.modelsDir, { recursive: true });
await import_fs3.promises.mkdir(this.embedDir, { recursive: true });
} catch (e) {
console.error("[Memex] Verzeichnisse konnten nicht angelegt werden:", e);
}
try {
await this.loadCache();
const allFiles = this.app.vault.getMarkdownFiles();
const files = this.excludeFolders.length ? allFiles.filter((f) => !this.excludeFolders.some((ex) => f.path.startsWith(ex + "/"))) : allFiles;
const total = files.length;
let done = 0;
let windowStart = Date.now();
let windowEmbedded = 0;
let speed = 0;
for (const file of files) {
const mtime = file.stat.mtime;
const cached = this.cache.get(file.path);
if (cached && cached.mtime === mtime) {
this.vecs.set(file.path, { vec: cached.vec, file });
} else {
try {
await new Promise((r) => setTimeout(r, 0));
const raw = await this.app.vault.cachedRead(file);
const text = this.preprocess(raw).slice(0, 800) + " " + file.basename;
const vec = await this.embedWithTimeout(text, this.pipe ? 13e3 : 12e4);
this.cache.set(file.path, { mtime, vec });
this.vecs.set(file.path, { vec, file });
changed.push(file.path);
windowEmbedded++;
if (changed.length % 100 === 0)
await this.flushBatch(changed.slice(-100));
} catch (e) {
if (!this.pipe && !pipelineError) {
pipelineError = e;
console.error("[Memex] Pipeline-Ladefehler:", e);
break;
}
console.warn("[Memex] Datei \xFCbersprungen:", file.path, e);
}
}
done++;
if (this.onProgress && done % 5 === 0) {
const elapsed = (Date.now() - windowStart) / 1e3;
if (elapsed > 0 && windowEmbedded > 0) {
speed = windowEmbedded / elapsed;
if (windowEmbedded >= 25) {
windowStart = Date.now();
windowEmbedded = 0;
}
}
this.onProgress(done, total, speed);
}
}
if (pipelineError)
throw pipelineError;
const allPaths = new Set(files.map((f) => f.path));
const remainder = changed.length % 100;
await this.saveCache(remainder > 0 ? changed.slice(-remainder) : [], allPaths);
this.indexed = true;
if (this.onProgress)
this.onProgress(total, total, speed);
} catch (e) {
console.error("[Memex] buildIndex Fehler:", e);
} finally {
this.indexing = false;
}
}
/**
* Debounced re-embed for a single file (called on vault modify events).
* Waits 2 s after the last write before embedding.
*/
reembedFile(file) {
if (!this.indexed || this.indexing)
return;
const existing = this.reembedTimers.get(file.path);
if (existing)
clearTimeout(existing);
const timer = setTimeout(async () => {
this.reembedTimers.delete(file.path);
try {
const raw = await this.app.vault.cachedRead(file);
const text = this.preprocess(raw).slice(0, 800) + " " + file.basename;
const vec = await this.embedWithTimeout(text);
const mtime = file.stat.mtime;
this.cache.set(file.path, { mtime, vec });
this.vecs.set(file.path, { vec, file });
await this.saveCache([file.path], new Set(this.vecs.keys()));
} catch (e) {
console.warn("[Memex] Re-embed fehlgeschlagen:", file.path, e);
}
}, 2e3);
this.reembedTimers.set(file.path, timer);
}
/** Find notes similar to a given file using its cached vector (no re-embedding). */
async searchSimilarToFile(file, topK = 10) {
if (!this.indexed)
return [];
let qvec = this.vecs.get(file.path)?.vec;
if (!qvec) {
try {
const raw = await this.app.vault.cachedRead(file);
const text = this.preprocess(raw).slice(0, 800) + " " + file.basename;
qvec = await this.embedWithTimeout(text);
} catch {
return [];
}
}
const linkedPaths = /* @__PURE__ */ new Set();
if (this.contextProperties.length > 0) {
const meta = this.app.metadataCache.getFileCache(file);
const links = meta?.frontmatterLinks ?? [];
for (const link of links) {
if (this.contextProperties.includes(link.key.split(".")[0])) {
const resolved = this.app.metadataCache.getFirstLinkpathDest(link.link, file.path);
if (resolved)
linkedPaths.add(resolved.path);
}
}
}
const fileMeta = this.app.metadataCache.getFileCache(file);
const fileTags = new Set(
(fileMeta?.tags ?? []).map((t) => t.tag.toLowerCase())
);
const scores = [];
for (const [path3, { vec }] of this.vecs) {
if (path3 === file.path)
continue;
let s = this.cosine(qvec, vec);
if (s < 0.15)
continue;
if (linkedPaths.has(path3)) {
s = Math.min(1, s + 0.15);
}
if (fileTags.size > 0) {
const otherMeta = this.app.metadataCache.getFileCache(this.vecs.get(path3).file);
const otherTags = (otherMeta?.tags ?? []).map((t) => t.tag.toLowerCase());
let sharedTags = 0;
for (const tag of otherTags) {
if (fileTags.has(tag))
sharedTags++;
if (sharedTags >= 3)
break;
}
if (sharedTags > 0)
s = Math.min(1, s + sharedTags * 0.05);
}
scores.push([path3, s]);
}
scores.sort((a, b) => b[1] - a[1]);
return scores.slice(0, topK).map(([path3, score]) => {
const { file: f } = this.vecs.get(path3);
return { file: f, score, excerpt: "", title: f.basename, linked: linkedPaths.has(path3) };
});
}
async search(query, topK = 8) {
if (!this.indexed)
await this.buildIndex();
const qvec = await this.embed(query);
const scores = [];
for (const [path3, { vec }] of this.vecs) {
const s = this.cosine(qvec, vec);
if (s > 0.2)
scores.push([path3, s]);
}
scores.sort((a, b) => b[1] - a[1]);
return scores.slice(0, topK).map(([path3, score]) => {
const { file } = this.vecs.get(path3);
return { file, score, excerpt: "", title: file.basename };
});
}
// ─── Cache I/O ───────────────────────────────────────────────────────────
/**
* Load all existing .ajson files from embedDir into this.cache.
* If the manifest model doesn't match, skip loading (full rebuild).
*/
async loadCache() {
this.cache.clear();
try {
const manifestRaw = await import_fs3.promises.readFile(this.manifestPath, "utf8");
const manifest = JSON.parse(manifestRaw);
if (manifest.model !== this.modelId)
return;
} catch {
return;
}
await this.loadCacheDir(this.embedDir);
}
async loadCacheDir(dir) {
let entries;
try {
entries = await import_fs3.promises.readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (entry.name.startsWith("."))
continue;
const fullPath = (0, import_path3.join)(dir, entry.name);
if (entry.isDirectory()) {
await this.loadCacheDir(fullPath);
} else if (entry.name.endsWith(".ajson")) {
try {
const raw = await import_fs3.promises.readFile(fullPath, "utf8");
const { mtime, vec } = JSON.parse(raw);
const rel = (0, import_path3.relative)(this.embedDir, fullPath).replace(/\.ajson$/, ".md");
const vaultPath = rel.split("\\").join("/");
this.cache.set(vaultPath, { mtime, vec });
} catch {
}
}
}
}
/** Write .ajson files for a batch of vault paths (no pruning). Called incrementally. */
async flushBatch(vaultPaths) {
try {
const manifest = { model: this.modelId, version: 1 };
await import_fs3.promises.writeFile(this.manifestPath, JSON.stringify(manifest), "utf8");
for (const vaultPath of vaultPaths) {
const entry = this.cache.get(vaultPath);
if (!entry)
continue;
const filePath = this.noteEmbedPath(vaultPath);
await import_fs3.promises.mkdir((0, import_path3.dirname)(filePath), { recursive: true });
await import_fs3.promises.writeFile(filePath, JSON.stringify({ mtime: entry.mtime, vec: entry.vec }), "utf8");
}
} catch (e) {
console.error("[Memex] flushBatch Fehler:", e);
}
}
/**
* Final save: flush any remaining changed notes, then prune stale .ajson files.
*/
async saveCache(changed, allVaultPaths) {
if (changed.length > 0)
await this.flushBatch(changed);
await this.pruneStale(this.embedDir, allVaultPaths);
}
async pruneStale(dir, allVaultPaths) {
let entries;
try {
entries = await import_fs3.promises.readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (entry.name.startsWith("."))
continue;
const fullPath = (0, import_path3.join)(dir, entry.name);
if (entry.isDirectory()) {
await this.pruneStale(fullPath, allVaultPaths);
} else if (entry.name.endsWith(".ajson")) {
const rel = (0, import_path3.relative)(this.embedDir, fullPath).replace(/\.ajson$/, ".md");
const vaultPath = rel.split("\\").join("/");
if (!allVaultPaths.has(vaultPath)) {
await import_fs3.promises.unlink(fullPath).catch(() => {
});
}
}
}
}
// ─── Text preprocessing ──────────────────────────────────────────────────
preprocess(raw) {
let c = raw;
if (c.startsWith("---")) {
const end = c.indexOf("\n---", 3);
if (end > 0)
c = c.slice(end + 4);
}
c = c.replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g, (_, t, a) => a || t);
c = c.replace(/!\[.*?\]\(.*?\)/g, "");
c = c.replace(/\[([^\]]+)\]\(.*?\)/g, "$1");
c = c.replace(/^#{1,6}\s+/gm, "");
return c;
}
};
// src/HybridSearch.ts
var RRF_K = 60;
var HybridSearch = class {
constructor(tfidf, embed) {
this.tfidf = tfidf;
this.embed = embed;
}
isIndexed() {
return this.embed.isIndexed();
}
async search(query, topK = 8) {
const fetchK = topK * 3;
const [tfidfResults, embedResults] = await Promise.all([
this.tfidf.search(query, fetchK),
this.embed.search(query, fetchK)
]);
const tfidfRank = /* @__PURE__ */ new Map();
tfidfResults.forEach((r, i) => tfidfRank.set(r.file.path, i));
const embedRank = /* @__PURE__ */ new Map();
embedResults.forEach((r, i) => embedRank.set(r.file.path, i));
const tfidfMap = new Map(tfidfResults.map((r) => [r.file.path, r]));
const embedMap = new Map(embedResults.map((r) => [r.file.path, r]));
const allPaths = /* @__PURE__ */ new Set([
...tfidfResults.map((r) => r.file.path),
...embedResults.map((r) => r.file.path)
]);
const scored = [];
for (const path3 of allPaths) {
const tr = tfidfRank.has(path3) ? 1 / (RRF_K + tfidfRank.get(path3) + 1) : 0;
const er = embedRank.has(path3) ? 1 / (RRF_K + embedRank.get(path3) + 1) : 0;
scored.push([path3, tr + er]);
}
scored.sort((a, b) => b[1] - a[1]);
return scored.slice(0, topK).map(([path3, score]) => {
const t = tfidfMap.get(path3);
const e = embedMap.get(path3);
const base = t ?? e;
return {
file: base.file,
score,
excerpt: t?.excerpt ?? "",
title: base.title,
linked: t?.linked ?? e?.linked
};
});
}
};
// src/ClaudeClient.ts
var import_obsidian2 = require("obsidian");
var https = __toESM(require("https"));
var ClaudeClient = class {
constructor() {
this.baseUrl = "https://api.anthropic.com/v1/messages";
}
headers(apiKey) {
return {
"content-type": "application/json",
"x-api-key": apiKey,
"anthropic-version": "2023-06-01"
};
}
/**
* Stream a chat completion via Node.js https + SSE, yielding text chunks as they arrive.
* Uses the Node.js https module (available in Obsidian's Electron renderer via Node integration)
* to bypass Electron's CORS/CSP restrictions that block fetch and XHR to external APIs.
*/
async *streamChat(messages, options) {
const queue = [];
let done = false;
let wakeup = null;
const push = (c) => {
queue.push(c);
wakeup?.();
wakeup = null;
};
const finish = () => {
done = true;
wakeup?.();
wakeup = null;
};
const body = JSON.stringify({
model: options.model,
max_tokens: options.maxTokens ?? 8192,
system: options.systemPrompt,
messages,
stream: true
});
const req = https.request(
{
hostname: "api.anthropic.com",
path: "/v1/messages",
method: "POST",
headers: {
...this.headers(options.apiKey),
"content-length": Buffer.byteLength(body).toString()
}
},
(res) => {
if ((res.statusCode ?? 0) >= 400) {
let errBody = "";
res.on("data", (d) => errBody += d.toString());
res.on("end", () => {
push({ type: "error", error: `API Error ${res.statusCode}: ${errBody}` });
finish();
});
return;
}
let buf = "";
res.on("data", (chunk) => {
buf += chunk.toString();
const lines = buf.split("\n");
buf = lines.pop() ?? "";
for (const line of lines) {
if (!line.startsWith("data: "))
continue;
const data = line.slice(6).trim();
if (data === "[DONE]")
return;
try {
const ev = JSON.parse(data);
if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta") {
push({ type: "text", text: ev.delta.text });
}
} catch {
}
}
});
res.on("end", () => {
finish();
});
res.on("error", (e) => {
push({ type: "error", error: e.message });
finish();
});
}
);
req.on("error", (e) => {
push({ type: "error", error: e.message });
finish();
});
req.write(body);
req.end();
while (true) {
while (queue.length)
yield queue.shift();
if (done)
break;
await new Promise((r) => {
wakeup = r;
});
}
while (queue.length)
yield queue.shift();
yield { type: "done" };
}
/** Non-streaming convenience wrapper */
async chat(messages, options) {
const response = await (0, import_obsidian2.requestUrl)({
url: this.baseUrl,
method: "POST",
headers: this.headers(options.apiKey),
body: JSON.stringify({
model: options.model,
max_tokens: options.maxTokens ?? 8192,
system: options.systemPrompt,
messages
}),
throw: false
});
if (response.status >= 400) {
throw new Error(`API Error ${response.status}: ${response.text}`);
}
return response.json.content?.[0]?.text ?? "";
}
/**
* Fetch Claude models from the Anthropic Models API.
* Returns the 2 newest versions of each family (opus, sonnet, haiku), in that order.
*/
async fetchModels(apiKey) {
const response = await (0, import_obsidian2.requestUrl)({
url: "https://api.anthropic.com/v1/models",
method: "GET",
headers: this.headers(apiKey),
throw: false
});
if (response.status >= 400) {
throw new Error(`API Error ${response.status}: ${response.text}`);
}
const data = response.json.data ?? [];
if (data.length === 0) {
throw new Error("No models returned");
}
const sorted = data.sort((a, b) => b.created - a.created);
const families = ["opus", "sonnet", "haiku"];
return families.flatMap(
(family) => sorted.filter((m) => m.id.includes(family)).slice(0, 2).map((m) => ({ id: m.id, name: m.id }))
);
}
};
// src/SettingsTab.ts
var import_obsidian3 = require("obsidian");
var DEFAULT_SETTINGS = {
apiKey: "",
model: "claude-opus-4-6",
maxTokens: 8192,
maxContextNotes: 6,
maxCharsPerNote: 2500,
systemPrompt: `Du bist ein hilfreicher Assistent mit Zugriff auf die pers\xF6nliche Wissensdatenbank des Nutzers (Obsidian Vault).
Wenn du Fragen beantwortest:
- Nutze die bereitgestellten Notizen als prim\xE4re Wissensquelle
- Verweise auf relevante Notizen mit [[doppelten eckigen Klammern]]
- Antworte auf Deutsch, wenn die Frage auf Deutsch gestellt wird
- Wenn der Kontext unzureichend ist, sage das ehrlich und gib an, was noch fehlen k\xF6nnte
- Verkn\xFCpfe Konzepte aus verschiedenen Notizen kreativ miteinander`,
autoRetrieveContext: true,
showContextPreview: true,
saveThreadsToVault: true,
threadsFolder: "Calendar/Chat",
sendOnEnter: false,
contextProperties: ["collection", "related", "up", "tags"],
systemContextFile: "",
useEmbeddings: false,
embeddingModel: "TaylorAI/bge-micro-v2",
embedExcludeFolders: [],
promptButtons: [
{
label: "Draft Check",
filePath: "Schreibdenken/ferals/Code/Prompts/COHERENCE CHECK",
helpText: "\u{1F4DD} DRAFT \u2014 Fr\xFChphase: Kernbotschaft, Koh\xE4renz, grobe Struktur\n\u2702\uFE0F PRE-PUBLISH \u2014 Fast fertig: Feinschliff, Sprache, Logik\n\u{1F50D} DIAGNOSTIC \u2014 Gezielte Analyse: ein spezifisches Problem benennen\n\nGib die Phase an und f\xFCge deinen Text mit @[[Notiz]] ein."
},
{
label: "Monthly Check",
filePath: "Schreibdenken/ferals/Code/Prompts/MONTHLY COHERENCE AUDIT",
searchMode: "date",
searchFolders: ["Schreibdenken/ferals/Content/Artikel"]
}
]
};
var MODELS = [
{ id: "claude-opus-4-6", name: "Claude Opus 4.6 (St\xE4rkste)" },
{ id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6 (Empfohlen)" },
{ id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5 (Schnell)" }
];
var MemexChatSettingsTab = class extends import_obsidian3.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
const allFolders = this.app.vault.getAllFolders().map((f) => f.path).filter((p) => p !== "/").sort();
const attachFolderDropdown = (wrap, input, getExcluded, onPick) => {
const dropdown = wrap.createDiv("vc-folder-dropdown");
dropdown.style.display = "none";
const refresh = () => {
const q = input.value.toLowerCase();
const excluded = getExcluded();
const matches = allFolders.filter((f) => f.toLowerCase().includes(q) && !excluded.includes(f)).slice(0, 12);
dropdown.empty();
if (!matches.length) {
dropdown.style.display = "none";
return;
}
for (const f of matches) {
const item = dropdown.createDiv("vc-folder-item");
item.textContent = f;
item.addEventListener("mousedown", (e) => {
e.preventDefault();
onPick(f);
});
}
dropdown.style.display = "block";
};
input.addEventListener("input", refresh);
input.addEventListener("focus", refresh);
input.addEventListener("blur", () => setTimeout(() => {
dropdown.style.display = "none";
}, 150));
input.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
dropdown.style.display = "none";
input.blur();
}
});
};
containerEl.createEl("h2", { text: "Memex Chat Einstellungen" });
containerEl.createEl("p", {
text: `Memex Chat v${this.plugin.manifest.version}`,
cls: "setting-item-description"
});
containerEl.createEl("h3", { text: "Claude API" });
new import_obsidian3.Setting(containerEl).setName("API Key").setDesc("Dein Anthropic API Key (sk-ant-...)").addText(
(text) => text.setPlaceholder("sk-ant-api03-...").setValue(this.plugin.settings.apiKey).onChange(async (value) => {
this.plugin.settings.apiKey = value.trim();
await this.plugin.saveSettings();
})
);
let modelDrop;
let refreshBtn;
new import_obsidian3.Setting(containerEl).setName("Modell").setDesc("Welches Claude-Modell verwenden? (Aktualisieren zeigt Roh-IDs)").addDropdown((drop) => {
modelDrop = drop;
for (const m of MODELS)
drop.addOption(m.id, m.name);
drop.setValue(this.plugin.settings.model).onChange(async (value) => {
this.plugin.settings.model = value;
await this.plugin.saveSettings();
});
}).addButton((btn) => {
refreshBtn = btn;
btn.setButtonText("Aktualisieren").onClick(async () => {
const prev = modelDrop.getValue();
refreshBtn.setDisabled(true);
refreshBtn.setButtonText("...");
try {
const models = await this.plugin.claude.fetchModels(this.plugin.settings.apiKey);
modelDrop.selectEl.empty();
for (const m of models)
modelDrop.addOption(m.id, m.name);
modelDrop.setValue(prev);
this.plugin.settings.model = modelDrop.getValue();
await this.plugin.saveSettings();
} catch (err) {
new import_obsidian3.Notice("Modelle konnten nicht geladen werden: " + err.message);
} finally {
refreshBtn.setDisabled(false);
refreshBtn.setButtonText("Aktualisieren");
}
});
});
new import_obsidian3.Setting(containerEl).setName("Max. Antwort-Tokens").setDesc("Maximale L\xE4nge der Claude-Antwort. F\xFCr lange Analysen (z.B. Monthly Check) h\xF6her einstellen. (1024\u201316000)").addSlider(
(slider) => slider.setLimits(1024, 16e3, 512).setValue(this.plugin.settings.maxTokens).setDynamicTooltip().onChange(async (value) => {
this.plugin.settings.maxTokens = value;
await this.plugin.saveSettings();
})
);
new import_obsidian3.Setting(containerEl).setName("Senden mit Enter").setDesc("Ein: Enter sendet. Aus: Cmd+Enter sendet (Enter = neue Zeile)").addToggle(
(toggle) => toggle.setValue(this.plugin.settings.sendOnEnter).onChange(async (value) => {
this.plugin.settings.sendOnEnter = value;
await this.plugin.saveSettings();
})
);
containerEl.createEl("h3", { text: "Semantische Suche (Embeddings)" });
containerEl.createEl("p", {
text: "Ersetzt TF-IDF durch ein lokales KI-Modell (Transformers.js). Das Modell wird beim ersten Einsatz von HuggingFace heruntergeladen und dann lokal gecacht. WASM-Laufzeit wird einmalig vom CDN geladen.",
cls: "setting-item-description"
});
new import_obsidian3.Setting(containerEl).setName("Semantische Suche aktivieren").setDesc("Nutzt lokale Embeddings f\xFCr kontextbasierte \xC4hnlichkeitssuche statt TF-IDF").addToggle(
(toggle) => toggle.setValue(this.plugin.settings.useEmbeddings).onChange(async (value) => {
this.plugin.settings.useEmbeddings = value;
await this.plugin.saveSettings();
await this.plugin.initEmbedSearch();
})
);
new import_obsidian3.Setting(containerEl).setName("Embedding-Modell").setDesc("Welches Modell f\xFCr die semantische Suche verwenden? Kleiner = schneller, gr\xF6\xDFer = besser.").addDropdown((drop) => {
for (const m of EMBEDDING_MODELS)
drop.addOption(m.id, m.name);
drop.setValue(this.plugin.settings.embeddingModel).onChange(async (value) => {
this.plugin.settings.embeddingModel = value;
await this.plugin.saveSettings();
await this.plugin.initEmbedSearch();
});
});
const exclSetting = new import_obsidian3.Setting(containerEl).setName("Ordner ausschlie\xDFen").setDesc("Diese Ordner werden beim Embedding \xFCbersprungen. Nach \xC4nderung Index neu aufbauen.");
exclSetting.settingEl.style.flexWrap = "wrap";
exclSetting.settingEl.style.alignItems = "flex-start";
const exclTagContainer = exclSetting.controlEl.createDiv("vc-prop-tags");
const renderExclTags = () => {
exclTagContainer.empty();
for (const folder of this.plugin.settings.embedExcludeFolders) {
const tag = exclTagContainer.createEl("span", { cls: "vc-prop-tag" });
tag.createEl("span", { text: folder });
const x = tag.createEl("button", { cls: "vc-prop-tag-remove", text: "\xD7" });
x.onclick = async () => {
this.plugin.settings.embedExcludeFolders = this.plugin.settings.embedExcludeFolders.filter((f) => f !== folder);
await this.plugin.saveSettings();
renderExclTags();
};
}
};
renderExclTags();
const exclWrap = exclSetting.controlEl.createDiv("vc-folder-search-wrap");
const exclInput = exclWrap.createEl("input", {
cls: "vc-prop-input",
attr: { type: "text", placeholder: "Ordner suchen\u2026" }
});
const addExclFolder = async (folder) => {
folder = folder.trim().replace(/\/$/, "");
if (!folder || this.plugin.settings.embedExcludeFolders.includes(folder))
return;
this.plugin.settings.embedExcludeFolders = [...this.plugin.settings.embedExcludeFolders, folder];
await this.plugin.saveSettings();
exclInput.value = "";
renderExclTags();
};
attachFolderDropdown(
exclWrap,
exclInput,
() => this.plugin.settings.embedExcludeFolders,
(f) => addExclFolder(f)
);
exclInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
addExclFolder(exclInput.value);
}
});
containerEl.createEl("h3", { text: "Kontext-Einstellungen" });
new import_obsidian3.Setting(containerEl).setName("Max. Kontext-Notizen").setDesc("Wie viele Notizen werden automatisch als Kontext hinzugef\xFCgt? (1\u201315)").addSlider(
(slider) => slider.setLimits(1, 15, 1).setValue(this.plugin.settings.maxContextNotes).setDynamicTooltip().onChange(async (value) => {
this.plugin.settings.maxContextNotes = value;
await this.plugin.saveSettings();
})
);
new import_obsidian3.Setting(containerEl).setName("Max. Zeichen pro Notiz").setDesc("Wie viele Zeichen einer Notiz in den Kontext einbezogen werden (1000\u20138000)").addSlider(
(slider) => slider.setLimits(1e3, 8e3, 500).setValue(this.plugin.settings.maxCharsPerNote).setDynamicTooltip().onChange(async (value) => {
this.plugin.settings.maxCharsPerNote = value;
await this.plugin.saveSettings();
})
);
new import_obsidian3.Setting(containerEl).setName("Automatischer Kontext-Abruf").setDesc("Beim Senden automatisch relevante Notizen suchen und einbinden").addToggle(
(toggle) => toggle.setValue(this.plugin.settings.autoRetrieveContext).onChange(async (value) => {
this.plugin.settings.autoRetrieveContext = value;
await this.plugin.saveSettings();
})
);
new import_obsidian3.Setting(containerEl).setName("Kontext-Vorschau anzeigen").setDesc("Vor dem Senden zeigen, welche Notizen als Kontext verwendet werden").addToggle(
(toggle) => toggle.setValue(this.plugin.settings.showContextPreview).onChange(async (value) => {
this.plugin.settings.showContextPreview = value;
await this.plugin.saveSettings();
})
);
containerEl.createEl("h3", { text: "Priorit\xE4ts-Properties" });
containerEl.createEl("p", {
text: "Frontmatter-Properties, deren Werte bei der Kontextsuche st\xE4rker gewichtet werden (z.B. related, collection, up, tags). Nach \xC4nderung den Index neu aufbauen.",
cls: "setting-item-description"
});
const propSetting = new import_obsidian3.Setting(containerEl).setName("Properties");
propSetting.settingEl.style.flexWrap = "wrap";
propSetting.settingEl.style.alignItems = "flex-start";
const tagContainer = propSetting.controlEl.createDiv("vc-prop-tags");
const renderTags = () => {
tagContainer.empty();
for (const prop of this.plugin.settings.contextProperties) {
const tag = tagContainer.createEl("span", { cls: "vc-prop-tag" });
tag.createEl("span", { text: prop });
const removeBtn = tag.createEl("button", { cls: "vc-prop-tag-remove", text: "\xD7" });
removeBtn.onclick = async () => {
this.plugin.settings.contextProperties = this.plugin.settings.contextProperties.filter(
(p) => p !== prop
);
await this.plugin.saveSettings();
renderTags();
};
}
};
renderTags();
const addRow = propSetting.controlEl.createDiv("vc-prop-add-row");
const addInput = addRow.createEl("input", {
cls: "vc-prop-input",
attr: { type: "text", placeholder: "Property hinzuf\xFCgen\u2026" }
});
const addBtn = addRow.createEl("button", { cls: "vc-prop-add-btn", text: "+" });
const doAdd = async () => {
const val = addInput.value.trim().toLowerCase();
if (!val || this.plugin.settings.contextProperties.includes(val))
return;
this.plugin.settings.contextProperties = [...this.plugin.settings.contextProperties, val];
await this.plugin.saveSettings();
addInput.value = "";
renderTags();
};
addBtn.onclick = doAdd;
addInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
doAdd();
}
});
containerEl.createEl("h3", { text: "Prompt-Buttons" });
containerEl.createEl("p", {
text: "Buttons in der Chat-Leiste, die den System-Prompt um den Inhalt einer Vault-Notiz erweitern.",
cls: "setting-item-description"
});
const btnListEl = containerEl.createDiv("vc-pbtn-list");
const renderBtnList = () => {
btnListEl.empty();
for (const [idx, pb] of this.plugin.settings.promptButtons.entries()) {
const card = btnListEl.createDiv("vc-pbtn-card");
const row1 = card.createDiv("vc-pbtn-row");
const labelInput = row1.createEl("input", {
cls: "vc-pbtn-input",
attr: { type: "text", placeholder: "Label", value: pb.label }
});
labelInput.addEventListener("change", async () => {
this.plugin.settings.promptButtons[idx].label = labelInput.value.trim();
await this.plugin.saveSettings();
});
const pathInput = row1.createEl("input", {
cls: "vc-pbtn-input vc-pbtn-path",
attr: { type: "text", placeholder: "Pfad im Vault (ohne .md)", value: pb.filePath }
});
pathInput.addEventListener("change", async () => {
this.plugin.settings.promptButtons[idx].filePath = pathInput.value.trim();
await this.plugin.saveSettings();
});
const removeBtn = row1.createEl("button", { cls: "vc-prop-tag-remove", text: "\xD7" });
removeBtn.style.fontSize = "16px";
removeBtn.onclick = async () => {
this.plugin.settings.promptButtons.splice(idx, 1);
await this.plugin.saveSettings();
renderBtnList();
};
const row2 = card.createDiv("vc-pbtn-row2");
const toggleWrap = row2.createEl("label", { cls: "vc-pbtn-toggle-wrap" });
const checkbox = toggleWrap.createEl("input", { attr: { type: "checkbox" } });
checkbox.checked = pb.searchMode === "date";
toggleWrap.appendText(" Datumsbasierte Suche");
const folderSection = row2.createDiv("vc-pbtn-folders");
folderSection.style.display = pb.searchMode === "date" ? "flex" : "none";
const renderFolders = () => {
folderSection.empty();
folderSection.createEl("span", { text: "Ordner: ", cls: "vc-pbtn-folder-label" });
for (const folder of pb.searchFolders ?? []) {
const chip = folderSection.createEl("span", { cls: "vc-prop-tag" });
chip.createEl("span", { text: folder });
const x = chip.createEl("button", { cls: "vc-prop-tag-remove", text: "\xD7" });
x.onclick = async () => {
pb.searchFolders = (pb.searchFolders ?? []).filter((f) => f !== folder);
await this.plugin.saveSettings();
renderFolders();
};
}
const folderWrap = folderSection.createDiv("vc-folder-search-wrap");
folderWrap.style.width = "200px";
const folderInput = folderWrap.createEl("input", {
cls: "vc-pbtn-input",
attr: { type: "text", placeholder: "Ordner suchen\u2026" }
});
const doAddFolder = async (val) => {
val = val.trim().replace(/\/$/, "");
if (!val || (pb.searchFolders ?? []).includes(val))
return;
pb.searchFolders = [...pb.searchFolders ?? [], val];
await this.plugin.saveSettings();
renderFolders();
};
attachFolderDropdown(folderWrap, folderInput, () => pb.searchFolders ?? [], (f) => doAddFolder(f));
folderInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
doAddFolder(folderInput.value);
}
});
};
renderFolders();
checkbox.addEventListener("change", async () => {
pb.searchMode = checkbox.checked ? "date" : void 0;
if (!checkbox.checked)
pb.searchFolders = [];
folderSection.style.display = checkbox.checked ? "flex" : "none";
await this.plugin.saveSettings();
});
const helpLabel = card.createEl("label", { cls: "vc-pbtn-folder-label", text: "Hilfetext (optional, erscheint im Chat wenn Button aktiv):" });
const helpTextArea = card.createEl("textarea", {
cls: "vc-pbtn-help-textarea",
attr: { placeholder: "z.B. DRAFT \u2014 Fr\xFChphase\u2026\nPRE-PUBLISH \u2014 Fast fertig\u2026" }
});
helpTextArea.value = pb.helpText ?? "";
const updateHelpRows = () => {
const lines = helpTextArea.value.split("\n").length;
helpTextArea.rows = helpTextArea.value.trim() ? Math.max(2, lines) : 1;
};
updateHelpRows();
helpTextArea.addEventListener("input", updateHelpRows);
helpTextArea.addEventListener("change", async () => {
pb.helpText = helpTextArea.value.trim() || void 0;
await this.plugin.saveSettings();
});
}
const addRow2 = btnListEl.createDiv("vc-pbtn-add-row");
const newLabel = addRow2.createEl("input", {
cls: "vc-pbtn-input",
attr: { type: "text", placeholder: "Label (z.B. Draft Check)" }
});
const newPath = addRow2.createEl("input", {
cls: "vc-pbtn-input vc-pbtn-path",
attr: { type: "text", placeholder: "Pfad/zur/Prompt-Notiz" }
});
const addBtn2 = addRow2.createEl("button", { cls: "vc-prop-add-btn", text: "+" });
addBtn2.onclick = async () => {
const label = newLabel.value.trim();
const filePath = newPath.value.trim();
if (!label || !filePath)
return;
this.plugin.settings.promptButtons.push({ label, filePath });
await this.plugin.saveSettings();
renderBtnList();
};
};
renderBtnList();
containerEl.createEl("h3", { text: "Thread-History" });
new import_obsidian3.Setting(containerEl).setName("Threads im Vault speichern").setDesc("Chat-Threads als Markdown-Notizen im Vault ablegen").addToggle(
(toggle) => toggle.setValue(this.plugin.settings.saveThreadsToVault).onChange(async (value) => {
this.plugin.settings.saveThreadsToVault = value;
await this.plugin.saveSettings();
})
);
const threadsFolderSetting = new import_obsidian3.Setting(containerEl).setName("Threads-Ordner").setDesc("Pfad im Vault, wo Chat-Threads gespeichert werden");
const tfWrap = threadsFolderSetting.controlEl.createDiv("vc-folder-search-wrap");
const tfInput = tfWrap.createEl("input", {
cls: "vc-prop-input",
attr: { type: "text", placeholder: "Calendar/Chat" }
});
tfInput.value = this.plugin.settings.threadsFolder;
tfInput.addEventListener("input", async () => {
this.plugin.settings.threadsFolder = tfInput.value;
await this.plugin.saveSettings();
});
attachFolderDropdown(tfWrap, tfInput, () => [], async (f) => {
tfInput.value = f;
this.plugin.settings.threadsFolder = f;
await this.plugin.saveSettings();
});
containerEl.createEl("h3", { text: "System Prompt" });
new import_obsidian3.Setting(containerEl).setName("System Prompt").setDesc("Instruktionen f\xFCr Claude (wie soll er sich verhalten?)").addTextArea((textarea) => {
textarea.setValue(this.plugin.settings.systemPrompt).onChange(async (value) => {
this.plugin.settings.systemPrompt = value;
await this.plugin.saveSettings();
});
textarea.inputEl.rows = 8;
textarea.inputEl.style.width = "100%";
textarea.inputEl.style.fontFamily = "monospace";
textarea.inputEl.style.fontSize = "12px";
});
new import_obsidian3.Setting(containerEl).setName("System Context (Datei)").setDesc("Optionale Vault-Notiz, deren Inhalt an den System Prompt angeh\xE4ngt wird (Pfad ohne .md)").addText(
(text) => text.setPlaceholder("z.B. Prompts/Mein System Context").setValue(this.plugin.settings.systemContextFile).onChange(async (value) => {
this.plugin.settings.systemContextFile = value.trim();
await this.plugin.saveSettings();
})
);
containerEl.createEl("h3", { text: "Aktionen" });
new import_obsidian3.Setting(containerEl).setName("Index neu aufbauen").setDesc("Vault-Index neu aufbauen (TF-IDF oder Embedding-Index, je nach Einstellung)").addButton(
(btn) => btn.setButtonText("Index neu aufbauen").setCta().onClick(async () => {
btn.setButtonText("Indiziere\u2026");
btn.setDisabled(true);
await this.plugin.rebuildIndex();
btn.setButtonText("\u2713 Fertig!");
setTimeout(() => {
btn.setButtonText("Index neu aufbauen");
btn.setDisabled(false);
}, 2e3);
})
);
}
};
// src/RelatedNotesView.ts
var import_obsidian4 = require("obsidian");
var VIEW_TYPE_RELATED = "memex-related-notes";
var RelatedNotesView = class extends import_obsidian4.ItemView {
constructor(leaf, plugin) {
super(leaf);
this.refreshTimer = null;
this.plugin = plugin;
}
getViewType() {
return VIEW_TYPE_RELATED;
}
getDisplayText() {
return "Verwandte Notizen";
}
getIcon() {
return "sparkles";
}
async onOpen() {
this.registerEvent(this.app.workspace.on("active-leaf-change", () => this.scheduleRefresh()));
this.registerEvent(this.app.workspace.on("file-open", () => this.scheduleRefresh()));
this.render([]);
this.scheduleRefresh();
}
scheduleRefresh(delay = 400) {
if (this.refreshTimer)
clearTimeout(this.refreshTimer);
this.refreshTimer = setTimeout(() => this.refresh(), delay);
}
/** Called by the plugin when the embedding index finishes building. */
onIndexReady() {
this.scheduleRefresh(0);
}
async refresh() {
const file = this.app.workspace.getActiveFile();
if (!file || file.extension !== "md")
return;
const es = this.plugin.embedSearch;
if (!es || !es.isIndexed()) {
this.renderStatus("Embedding-Index wird aufgebaut\u2026");
return;
}
this.renderStatus("Suche verwandte Notizen\u2026");
const results = await es.searchSimilarToFile(file);
this.render(results, file.basename);
}
renderStatus(msg) {
this.contentEl.empty();
this.contentEl.createDiv({ cls: "vc-related-status", text: msg });
}
render(results, forNote) {
this.contentEl.empty();
const header = this.contentEl.createDiv("vc-related-header");
header.createDiv({ cls: "vc-related-title", text: "Verwandte Notizen" });
if (forNote)
header.createDiv({ cls: "vc-related-subtitle", text: forNote });
if (!results.length) {
this.contentEl.createDiv({ cls: "vc-related-status", text: forNote ? "Keine Treffer." : "" });
return;
}
const list = this.contentEl.createDiv("vc-related-list");
for (const r of results) {
const item = list.createDiv("vc-related-item");
const info = item.createDiv("vc-related-info");
const nameRow = info.createDiv("vc-related-name-row");
nameRow.createSpan({ cls: "vc-related-name", text: r.title });
if (r.linked)
nameRow.createSpan({ cls: "vc-related-linked", text: "verkn\xFCpft" });
const folder = r.file.parent?.path;
if (folder && folder !== "/") {
info.createDiv({ cls: "vc-related-folder", text: folder });
}
const scoreWrap = item.createDiv("vc-related-score-wrap");
const pct = Math.round(r.score * 100);
const bar = scoreWrap.createDiv("vc-related-bar");
bar.createDiv({ cls: "vc-related-bar-fill" }).style.width = `${pct}%`;
scoreWrap.createDiv({ cls: "vc-related-pct", text: `${pct}%` });
item.addEventListener("click", () => {
this.app.workspace.openLinkText(r.file.path, r.file.path, false);
});
}
}
};
// src/main.ts
var MemexChatPlugin = class extends import_obsidian5.Plugin {
constructor() {
super(...arguments);
this.embedSearch = null;
this.hybridSearch = null;
}
/** Returns the active search engine: HybridSearch when embeddings are ready, else VaultSearch */
get activeSearch() {
return this.hybridSearch ?? this.search;
}
async onload() {
const loaded = await this.loadData();
const mergedSettings = { ...DEFAULT_SETTINGS, ...loaded?.settings ?? {} };
if (loaded?.settings?.promptButtons) {
mergedSettings.promptButtons = loaded.settings.promptButtons.map((saved, i) => ({
...DEFAULT_SETTINGS.promptButtons[i] ?? {},
...saved
}));
}
this.data = {
settings: mergedSettings,
threads: loaded?.threads ?? []
};
this.settings = this.data.settings;
this.search = new VaultSearch(this.app);
this.claude = new ClaudeClient();
this.registerView(VIEW_TYPE_MEMEX_CHAT, (leaf) => new ChatView(leaf, this));
this.registerView(VIEW_TYPE_RELATED, (leaf) => new RelatedNotesView(leaf, this));
this.addRibbonIcon("message-circle", "Memex Chat \xF6ffnen", () => {
this.activateView();
});
this.addRibbonIcon("sparkles", "Verwandte Notizen", () => {
this.activateRelatedView();
});
this.addCommand({
id: "open-memex-chat",
name: "Memex Chat \xF6ffnen",
callback: () => this.activateView()
});
this.addCommand({
id: "memex-related-notes",
name: "Verwandte Notizen anzeigen",
callback: () => this.activateRelatedView()
});
this.addCommand({
id: "memex-chat-rebuild-index",
name: "Memex Chat: Index neu aufbauen",
callback: () => this.rebuildIndex()
});
this.addCommand({
id: "memex-chat-active-note",
name: "Memex Chat: Aktive Notiz als Kontext",
callback: () => {
const file = this.app.workspace.getActiveFile();
if (file) {
this.activateView().then(() => {
const leaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_MEMEX_CHAT)[0];
if (leaf) {
const view = leaf.view;
view.newThread();
view.setInputValue(`Erkl\xE4re und verkn\xFCpfe [[${file.basename}]] mit anderen Konzepten im Vault.`);
view.setExplicitContext([file]);
}
});
}
}
});
this.addSettingTab(new MemexChatSettingsTab(this.app, this));
this.registerEvent(
this.app.vault.on("modify", (file) => {
if (this.embedSearch && file instanceof import_obsidian5.TFile && file.extension === "md")
this.embedSearch.reembedFile(file);
})
);
this.app.workspace.onLayoutReady(() => {
if (!this.search.isIndexed()) {
this.search.priorityProperties = this.settings.contextProperties;
this.search.buildIndex().catch(console.error);
}
if (this.settings.useEmbeddings) {
this.initEmbedSearch().catch(console.error);
}
});
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_MEMEX_CHAT);
}
async activateView() {
const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_MEMEX_CHAT);
if (existing.length > 0) {
this.app.workspace.revealLeaf(existing[0]);
return;
}
const leaf = this.app.workspace.getLeaf("tab");
if (!leaf)
return;
await leaf.setViewState({ type: VIEW_TYPE_MEMEX_CHAT, active: true });
this.app.workspace.revealLeaf(leaf);
}
async activateRelatedView() {
const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_RELATED);
if (existing.length > 0) {
this.app.workspace.revealLeaf(existing[0]);
return;
}
const leaf = this.app.workspace.getRightLeaf(false);
if (!leaf)
return;
await leaf.setViewState({ type: VIEW_TYPE_RELATED, active: true });
this.app.workspace.revealLeaf(leaf);
}
notifyRelatedView() {
this.app.workspace.getLeavesOfType(VIEW_TYPE_RELATED).forEach((l) => {
if (l.view instanceof RelatedNotesView)
l.view.onIndexReady();
});
}
/** Create or recreate the EmbedSearch instance (called when settings change) */
async initEmbedSearch() {
if (!this.settings.useEmbeddings) {
this.embedSearch = null;
this.hybridSearch = null;
return;
}
this.embedSearch = new EmbedSearch(this.app, this.settings.embeddingModel);
this.embedSearch.excludeFolders = this.settings.embedExcludeFolders ?? [];
this.embedSearch.contextProperties = this.settings.contextProperties ?? [];
const modelShort = this.settings.embeddingModel.split("/").pop() ?? this.settings.embeddingModel;
const notice = new import_obsidian5.Notice(`Memex [${modelShort}]: Embedding wird vorbereitet\u2026`, 0);
this.embedSearch.onModelStatus = (status) => {
notice.setMessage(`Memex [${modelShort}]: ${status}`);
};
this.embedSearch.onProgress = (done, total, speed) => {
const speedStr = speed > 0 ? ` \u2022 ${speed.toFixed(1)} N/s` : "";
const remaining = speed > 0 && done < total ? (total - done) / speed : 0;
const eta = remaining > 0 ? ` \u2022 ~${remaining < 60 ? Math.ceil(remaining) + "s" : Math.ceil(remaining / 60) + "min"}` : "";
notice.setMessage(`Memex [${modelShort}]: ${done}/${total}${speedStr}${eta}`);
};
this.waitForSyncIdle(notice).then(() => this.embedSearch?.buildIndex()).then(() => {
if (this.embedSearch)
this.hybridSearch = new HybridSearch(this.search, this.embedSearch);
notice.setMessage(`\u2713 Memex [${modelShort}]: ${this.app.vault.getMarkdownFiles().length} Notizen eingebettet`);
setTimeout(() => notice.hide(), 4e3);
this.notifyRelatedView();
}).catch((e) => {
notice.setMessage(`\u2717 Memex Embedding: ${e.message}`);
setTimeout(() => notice.hide(), 6e3);
console.error(e);
}).finally(() => {
if (this.embedSearch) {
this.embedSearch.onProgress = void 0;
this.embedSearch.onModelStatus = void 0;
}
});
}
async rebuildIndex() {
const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_MEMEX_CHAT);
const view = leaves[0]?.view;
if (this.settings.useEmbeddings && this.embedSearch) {
this.hybridSearch = null;
this.embedSearch.onModelStatus = (status) => {
if (view)
view.setStatus(status);
};
this.embedSearch.onProgress = (done, total, speed) => {
if (view) {
const speedStr = speed > 0 ? ` \u2022 ${speed.toFixed(1)} N/s` : "";
const eta = speed > 0 && done < total ? ` \u2022 noch ~${Math.ceil((total - done) / speed)}s` : "";
view.setStatus(`Embedding ${done}/${total}${speedStr}${eta}`);
}
};
await this.embedSearch.buildIndex();
this.hybridSearch = new HybridSearch(this.search, this.embedSearch);
this.embedSearch.onProgress = void 0;
this.embedSearch.onModelStatus = void 0;
} else {
this.search.priorityProperties = this.settings.contextProperties;
this.search.onProgress = (done, total) => {
if (view && done % 200 === 0) {
view.setStatus(`Indiziere\u2026 ${done}/${total}`);
}
};
await this.search.buildIndex();
this.search.onProgress = void 0;
}
if (view) {
view.setStatus(`\u2713 ${this.app.vault.getMarkdownFiles().length} Notizen indiziert`);
setTimeout(() => view.setStatus(""), 3e3);
}
}
/**
* Waits until Obsidian Sync is idle.
* Strategy: watch for vault changes; if activity stops for 15 s, sync is done.
* If no activity within the first 5 s, sync isn't running — return immediately.
* Falls back after 5 minutes regardless.
*/
async waitForSyncIdle(notice) {
const syncPlugin = this.app.internalPlugins?.plugins?.["sync"]?.instance;
if (!syncPlugin)
return;
const PROBE_MS = 5e3;
const QUIET_MS = 15e3;
const MAX_MS = 5 * 6e4;
let lastChange = 0;
let activitySeen = false;
const tick = () => {
lastChange = Date.now();
activitySeen = true;
};
this.app.vault.on("create", tick);
this.app.vault.on("modify", tick);
this.app.vault.on("delete", tick);
try {
notice.setMessage("Memex: Pr\xFCfe Sync-Status\u2026");
await new Promise((r) => setTimeout(r, PROBE_MS));
if (!activitySeen)
return;
notice.setMessage("Memex: Warte auf Obsidian Sync\u2026");
const deadline = Date.now() + MAX_MS;
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 2e3));
if (Date.now() - lastChange >= QUIET_MS)
return;
}
} finally {
this.app.vault.off("create", tick);
this.app.vault.off("modify", tick);
this.app.vault.off("delete", tick);
}
}
async saveSettings() {
this.data.settings = this.settings;
await this.saveData(this.data);
}
};
/*! Bundled license information:
onnxruntime-common/dist/ort-common.node.js:
(*!
* ONNX Runtime Common v1.14.0
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*)
onnxruntime-web/dist/ort-web.min.js:
(*!
* ONNX Runtime Web v1.14.0
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*)
*/