diff --git "a/index-17_Va4sS.js" "b/index-17_Va4sS.js" deleted file mode 100644--- "a/index-17_Va4sS.js" +++ /dev/null @@ -1,27471 +0,0 @@ -(function () { - const e = document.createElement('link').relList; - if (e && e.supports && e.supports('modulepreload')) return; - for (const u of document.querySelectorAll('link[rel="modulepreload"]')) i(u); - new MutationObserver((u) => { - for (const n of u) - if (n.type === 'childList') - for (const s of n.addedNodes) s.tagName === 'LINK' && s.rel === 'modulepreload' && i(s); - }).observe(document, { childList: !0, subtree: !0 }); - function o(u) { - const n = {}; - return ( - u.integrity && (n.integrity = u.integrity), - u.referrerPolicy && (n.referrerPolicy = u.referrerPolicy), - u.crossOrigin === 'use-credentials' - ? (n.credentials = 'include') - : u.crossOrigin === 'anonymous' - ? (n.credentials = 'omit') - : (n.credentials = 'same-origin'), - n - ); - } - function i(u) { - if (u.ep) return; - u.ep = !0; - const n = o(u); - fetch(u.href, n); - } -})(); -function dispatchCallback(t, e) { - t && t(e); -} -function reverseDictionary(t) { - return Object.fromEntries(Object.entries(t).map(([e, o]) => [o, e])); -} -const Callable = class { - constructor() { - let t = function (...e) { - return t._call(...e); - }; - return Object.setPrototypeOf(t, new.target.prototype); - } - _call(...t) { - throw Error('Must implement _call method in subclass'); - } -}; -function isTypedArray(t) { - return t?.prototype?.__proto__?.constructor?.name === 'TypedArray'; -} -function isIntegralNumber(t) { - return Number.isInteger(t) || typeof t == 'bigint'; -} -function exists(t) { - return t != null; -} -function calculateDimensions(t) { - const e = []; - let o = t; - for (; Array.isArray(o); ) e.push(o.length), (o = o[0]); - return e; -} -function mergeArrays(...t) { - return Array.prototype.concat.apply([], t); -} -function calculateReflectOffset(t, e) { - return Math.abs(((t + e) % (2 * e)) - e); -} -const sharp = {}, - ONNX_NODE = Object.freeze( - Object.defineProperty({ __proto__: null, default: sharp }, Symbol.toStringTag, { value: 'Module' }) - ), - VERSION = '3.0.0-alpha.0', - BROWSER_ENV$1 = typeof self < 'u', - WEB_CACHE_AVAILABLE = BROWSER_ENV$1 && 'caches' in self, - FS_AVAILABLE = !isEmpty(sharp), - PATH_AVAILABLE = !isEmpty(sharp), - RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE, - __dirname$1 = RUNNING_LOCALLY ? sharp.dirname(sharp.dirname(sharp.fileURLToPath(import.meta.url))) : './', - DEFAULT_CACHE_DIR = RUNNING_LOCALLY ? sharp.join(__dirname$1, '/.cache/') : null, - DEFAULT_LOCAL_MODEL_PATH = '/models/', - localModelPath = RUNNING_LOCALLY ? sharp.join(__dirname$1, DEFAULT_LOCAL_MODEL_PATH) : DEFAULT_LOCAL_MODEL_PATH, - env = { - backends: { onnx: {}, tfjs: {} }, - experimental: { useWebGPU: !1 }, - __dirname: __dirname$1, - version: VERSION, - allowRemoteModels: !0, - remoteHost: 'https://huggingface.co./', - remotePathTemplate: '{model}/resolve/{revision}/', - allowLocalModels: !BROWSER_ENV$1, - localModelPath, - useFS: FS_AVAILABLE, - useBrowserCache: WEB_CACHE_AVAILABLE, - useFSCache: FS_AVAILABLE, - cacheDir: DEFAULT_CACHE_DIR, - useCustomCache: !1, - customCache: null, - }; -function isEmpty(t) { - return Object.keys(t).length === 0; -} -var define_process_env_default = {}; -class FileResponse { - _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', - }; - constructor(e) { - if (((this.filePath = e), (this.headers = new Headers()), (this.exists = sharp.existsSync(e)), this.exists)) { - (this.status = 200), (this.statusText = 'OK'); - let o = sharp.statSync(e); - this.headers.set('content-length', o.size.toString()), this.updateContentType(); - let i = this; - this.body = new ReadableStream({ - start(u) { - i.arrayBuffer().then((n) => { - u.enqueue(new Uint8Array(n)), u.close(); - }); - }, - }); - } else (this.status = 404), (this.statusText = 'Not Found'), (this.body = null); - } - updateContentType() { - const e = this.filePath.toString().split('.').pop().toLowerCase(); - this.headers.set('content-type', this._CONTENT_TYPE_MAP[e] ?? 'application/octet-stream'); - } - clone() { - let e = new FileResponse(this.filePath); - return ( - (e.exists = this.exists), - (e.status = this.status), - (e.statusText = this.statusText), - (e.headers = new Headers(this.headers)), - e - ); - } - async arrayBuffer() { - return (await sharp.promises.readFile(this.filePath)).buffer; - } - async blob() { - const e = await sharp.promises.readFile(this.filePath); - return new Blob([e], { type: this.headers.get('content-type') }); - } - async text() { - return await sharp.promises.readFile(this.filePath, 'utf8'); - } - async json() { - return JSON.parse(await this.text()); - } -} -function isValidHttpUrl(t, e = null) { - let o; - try { - o = new URL(t); - } catch { - return !1; - } - return e && !e.includes(o.hostname) ? !1 : o.protocol === 'http:' || o.protocol === 'https:'; -} -async function getFile(t) { - if (env.useFS && !isValidHttpUrl(t)) return new FileResponse(t); - if (typeof process < 'u' && process?.release?.name === 'node') { - const e = !!define_process_env_default?.TESTING_REMOTELY, - o = env.version, - i = new Headers(); - if ( - (i.set('User-Agent', `transformers.js/${o}; is_ci/${e};`), isValidHttpUrl(t, ['huggingface.co', 'hf.co'])) - ) { - const n = define_process_env_default?.HF_TOKEN ?? define_process_env_default?.HF_ACCESS_TOKEN; - n && i.set('Authorization', `Bearer ${n}`); - } - return fetch(t, { headers: i }); - } else return fetch(t); -} -const ERROR_MAPPING = { - 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', - 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', -}; -function handleError(t, e, o) { - if (!o) return null; - const i = ERROR_MAPPING[t] ?? `Error (${t}) occurred while trying to load file`; - throw Error(`${i}: "${e}".`); -} -class FileCache { - constructor(e) { - this.path = e; - } - async match(e) { - let o = sharp.join(this.path, e), - i = new FileResponse(o); - if (i.exists) return i; - } - async put(e, o) { - const i = Buffer.from(await o.arrayBuffer()); - let u = sharp.join(this.path, e); - try { - await sharp.promises.mkdir(sharp.dirname(u), { recursive: !0 }), await sharp.promises.writeFile(u, i); - } catch (n) { - console.warn('An error occurred while writing the file to cache:', n); - } - } -} -async function tryCache(t, ...e) { - for (let o of e) - try { - let i = await t.match(o); - if (i) return i; - } catch { - continue; - } -} -async function getModelFile(t, e, o = !0, i = {}) { - if (!env.allowLocalModels && i.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`).' - ); - dispatchCallback(i.progress_callback, { status: 'initiate', name: t, file: e }); - let u; - if (!u && env.useBrowserCache) { - if (typeof caches > 'u') throw Error('Browser cache is not available in this environment.'); - try { - u = await caches.open('transformers-cache'); - } catch (S) { - console.warn('An error occurred while opening the browser cache:', S); - } - } - if ((!u && env.useFSCache && (u = new FileCache(i.cache_dir ?? env.cacheDir)), !u && env.useCustomCache)) - throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.'); - const n = i.revision ?? 'main'; - let s = pathJoin(t, e), - d = pathJoin(env.localModelPath, s), - f = pathJoin( - env.remoteHost, - env.remotePathTemplate.replaceAll('{model}', t).replaceAll('{revision}', encodeURIComponent(n)), - e - ), - r = n === 'main' ? s : pathJoin(t, n, e), - a, - l = u instanceof FileCache ? r : f, - p = !1, - m; - u && (m = await tryCache(u, d, l)); - const y = m !== void 0; - if (m === void 0) { - if (env.allowLocalModels) - if (isValidHttpUrl(s)) { - if (i.local_files_only) - throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${s}.`); - } else - try { - (m = await getFile(d)), (a = d); - } catch (E) { - console.warn(`Unable to load from local path "${d}": "${E}"`); - } - if (m === void 0 || m.status === 404) { - if (i.local_files_only || !env.allowRemoteModels) { - if (o) - throw Error( - `\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${d}".` - ); - return null; - } - if (((m = await getFile(f)), m.status !== 200)) return handleError(m.status, f, o); - a = l; - } - p = u && typeof Response < 'u' && m instanceof Response && m.status === 200; - } - dispatchCallback(i.progress_callback, { status: 'download', name: t, file: e }); - const T = { status: 'progress', name: t, file: e }; - let v; - return ( - i.progress_callback - ? y && typeof navigator < 'u' && /firefox/i.test(navigator.userAgent) - ? ((v = new Uint8Array(await m.arrayBuffer())), - dispatchCallback(i.progress_callback, { ...T, progress: 100, loaded: v.length, total: v.length })) - : (v = await readResponse(m, (S) => { - dispatchCallback(i.progress_callback, { ...T, ...S }); - })) - : (v = new Uint8Array(await m.arrayBuffer())), - p && - a && - (await u.match(a)) === void 0 && - (await u.put(a, new Response(v, { headers: m.headers })).catch((S) => { - console.warn(`Unable to add response to browser cache: ${S}.`); - })), - dispatchCallback(i.progress_callback, { status: 'done', name: t, file: e }), - v - ); -} -async function getModelJSON(t, e, o = !0, i = {}) { - let u = await getModelFile(t, e, o, i); - if (u === null) return {}; - let s = new TextDecoder('utf-8').decode(u); - return JSON.parse(s); -} -async function readResponse(t, e) { - const o = t.headers.get('Content-Length'); - o === null && - console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.'); - let i = parseInt(o ?? '0'), - u = new Uint8Array(i), - n = 0; - const s = t.body.getReader(); - async function d() { - const { done: f, value: r } = await s.read(); - if (f) return; - let a = n + r.length; - if (a > i) { - i = a; - let p = new Uint8Array(i); - p.set(u), (u = p); - } - u.set(r, n), (n = a); - const l = (n / i) * 100; - return e({ progress: l, loaded: n, total: i }), d(); - } - return await d(), u; -} -function pathJoin(...t) { - return ( - (t = t.map( - (e, o) => ( - o && (e = e.replace(new RegExp('^/'), '')), - o !== t.length - 1 && (e = e.replace(new RegExp('/$'), '')), - e - ) - )), - t.join('/') - ); -} -function interpolate_data(t, [e, o, i], [u, n], s = 'bilinear', d = !1) { - const f = n / i, - r = u / o, - a = new t.constructor(u * n * e), - l = o * i, - p = u * n; - for (let m = 0; m < u; ++m) - for (let y = 0; y < n; ++y) { - const T = m * n + y, - v = (y + 0.5) / f - 0.5, - S = (m + 0.5) / r - 0.5; - let E = Math.floor(v), - A = Math.floor(S); - const F = Math.min(E + 1, i - 1), - B = Math.min(A + 1, o - 1); - (E = Math.max(E, 0)), (A = Math.max(A, 0)); - const J = v - E, - Q = S - A, - re = (1 - J) * (1 - Q), - V = J * (1 - Q), - de = (1 - J) * Q, - ke = J * Q, - Ne = A * i, - Me = B * i, - Y = Ne + E, - _e = Ne + F, - he = Me + E, - ue = Me + F; - for (let pe = 0; pe < e; ++pe) { - const X = pe * l; - a[pe * p + T] = re * t[X + Y] + V * t[X + _e] + de * t[X + he] + ke * t[X + ue]; - } - } - return a; -} -function transpose_data(t, e, o) { - const i = new Array(o.length), - u = new Array(o.length); - for (let d = o.length - 1, f = 1; d >= 0; --d) (u[d] = f), (i[d] = e[o[d]]), (f *= i[d]); - const n = o.map((d, f) => u[o.indexOf(f)]), - s = new t.constructor(t.length); - for (let d = 0; d < t.length; ++d) { - let f = 0; - for (let r = e.length - 1, a = d; r >= 0; --r) (f += (a % e[r]) * n[r]), (a = Math.floor(a / e[r])); - s[f] = t[d]; - } - return [s, i]; -} -function softmax(t) { - const e = max(t)[0], - o = t.map((n) => Math.exp(n - e)), - i = o.reduce((n, s) => n + s, 0); - return o.map((n) => n / i); -} -function log_softmax(t) { - return softmax(t).map((i) => Math.log(i)); -} -function getTopItems(t, e = 0) { - return ( - (t = Array.from(t) - .map((o, i) => [i, o]) - .sort((o, i) => i[1] - o[1])), - e !== null && e > 0 && (t = t.slice(0, e)), - t - ); -} -function min(t) { - if (t.length === 0) throw Error('Array must not be empty'); - let e = t[0], - o = 0; - for (let i = 1; i < t.length; ++i) t[i] < e && ((e = t[i]), (o = i)); - return [e, o]; -} -function max(t) { - if (t.length === 0) throw Error('Array must not be empty'); - let e = t[0], - o = 0; - for (let i = 1; i < t.length; ++i) t[i] > e && ((e = t[i]), (o = i)); - return [Number(e), o]; -} -function isPowerOfTwo(t) { - return t > 0 && (t & (t - 1)) === 0; -} -class P2FFT { - constructor(e) { - if (((this.size = e | 0), this.size <= 1 || !isPowerOfTwo(this.size))) - throw new Error('FFT size must be a power of two larger than 1'); - (this._csize = e << 1), (this.table = new Float64Array(this.size * 2)); - for (let i = 0; i < this.table.length; i += 2) { - const u = (Math.PI * i) / this.size; - (this.table[i] = Math.cos(u)), (this.table[i + 1] = -Math.sin(u)); - } - let o = 0; - for (let i = 1; this.size > i; i <<= 1) ++o; - (this._width = o % 2 === 0 ? o - 1 : o), (this._bitrev = new Int32Array(1 << this._width)); - for (let i = 0; i < this._bitrev.length; ++i) { - this._bitrev[i] = 0; - for (let u = 0; u < this._width; u += 2) { - const n = this._width - u - 2; - this._bitrev[i] |= ((i >>> u) & 3) << n; - } - } - } - createComplexArray() { - return new Float64Array(this._csize); - } - fromComplexArray(e, o) { - const i = o || new Array(e.length >>> 1); - for (let u = 0; u < e.length; u += 2) i[u >>> 1] = e[u]; - return i; - } - toComplexArray(e, o) { - const i = o || this.createComplexArray(); - for (let u = 0; u < i.length; u += 2) (i[u] = e[u >>> 1]), (i[u + 1] = 0); - return i; - } - completeSpectrum(e) { - const o = this._csize, - i = o >>> 1; - for (let u = 2; u < i; u += 2) (e[o - u] = e[u]), (e[o - u + 1] = -e[u + 1]); - } - transform(e, o) { - if (e === o) throw new Error('Input and output buffers must be different'); - this._transform4(e, o, 1); - } - realTransform(e, o) { - if (e === o) throw new Error('Input and output buffers must be different'); - this._realTransform4(e, o, 1); - } - inverseTransform(e, o) { - if (e === o) throw new Error('Input and output buffers must be different'); - this._transform4(e, o, -1); - for (let i = 0; i < e.length; ++i) e[i] /= this.size; - } - _transform4(e, o, i) { - const u = this._csize; - let s = 1 << this._width, - d = (u / s) << 1, - f, - r; - const a = this._bitrev; - if (d === 4) - for (f = 0, r = 0; f < u; f += d, ++r) { - const l = a[r]; - this._singleTransform2(o, e, f, l, s); - } - else - for (f = 0, r = 0; f < u; f += d, ++r) { - const l = a[r]; - this._singleTransform4(o, e, f, l, s, i); - } - for (s >>= 2; s >= 2; s >>= 2) { - d = (u / s) << 1; - const l = d >>> 2; - for (f = 0; f < u; f += d) { - const p = f + l - 1; - for (let m = f, y = 0; m < p; m += 2, y += s) { - const T = m, - v = T + l, - S = v + l, - E = S + l, - A = e[T], - F = e[T + 1], - B = e[v], - J = e[v + 1], - Q = e[S], - re = e[S + 1], - V = e[E], - de = e[E + 1], - ke = this.table[y], - Ne = i * this.table[y + 1], - Me = B * ke - J * Ne, - Y = B * Ne + J * ke, - _e = this.table[2 * y], - he = i * this.table[2 * y + 1], - ue = Q * _e - re * he, - pe = Q * he + re * _e, - X = this.table[3 * y], - ve = i * this.table[3 * y + 1], - we = V * X - de * ve, - rt = V * ve + de * X, - ot = A + ue, - qe = F + pe, - He = A - ue, - Qe = F - pe, - Be = Me + we, - Ce = Y + rt, - Se = i * (Me - we), - je = i * (Y - rt); - (e[T] = ot + Be), - (e[T + 1] = qe + Ce), - (e[v] = He + je), - (e[v + 1] = Qe - Se), - (e[S] = ot - Be), - (e[S + 1] = qe - Ce), - (e[E] = He - je), - (e[E + 1] = Qe + Se); - } - } - } - } - _singleTransform2(e, o, i, u, n) { - const s = e[u], - d = e[u + 1], - f = e[u + n], - r = e[u + n + 1]; - (o[i] = s + f), (o[i + 1] = d + r), (o[i + 2] = s - f), (o[i + 3] = d - r); - } - _singleTransform4(e, o, i, u, n, s) { - const d = n * 2, - f = n * 3, - r = e[u], - a = e[u + 1], - l = e[u + n], - p = e[u + n + 1], - m = e[u + d], - y = e[u + d + 1], - T = e[u + f], - v = e[u + f + 1], - S = r + m, - E = a + y, - A = r - m, - F = a - y, - B = l + T, - J = p + v, - Q = s * (l - T), - re = s * (p - v); - (o[i] = S + B), - (o[i + 1] = E + J), - (o[i + 2] = A + re), - (o[i + 3] = F - Q), - (o[i + 4] = S - B), - (o[i + 5] = E - J), - (o[i + 6] = A - re), - (o[i + 7] = F + Q); - } - _realTransform4(e, o, i) { - const u = this._csize; - let s = 1 << this._width, - d = (u / s) << 1, - f, - r; - const a = this._bitrev; - if (d === 4) - for (f = 0, r = 0; f < u; f += d, ++r) { - const l = a[r]; - this._singleRealTransform2(o, e, f, l >>> 1, s >>> 1); - } - else - for (f = 0, r = 0; f < u; f += d, ++r) { - const l = a[r]; - this._singleRealTransform4(o, e, f, l >>> 1, s >>> 1, i); - } - for (s >>= 2; s >= 2; s >>= 2) { - d = (u / s) << 1; - const l = d >>> 2; - for (f = 0; f < u; f += d) { - const p = f + l - 1; - for (let m = f, y = 0; m < p; m += 2, y += s) { - const T = m, - v = T + l, - S = v + l, - E = S + l, - A = e[T], - F = e[T + 1], - B = e[v], - J = e[v + 1], - Q = e[S], - re = e[S + 1], - V = e[E], - de = e[E + 1], - ke = this.table[y], - Ne = i * this.table[y + 1], - Me = B * ke - J * Ne, - Y = B * Ne + J * ke, - _e = this.table[2 * y], - he = i * this.table[2 * y + 1], - ue = Q * _e - re * he, - pe = Q * he + re * _e, - X = this.table[3 * y], - ve = i * this.table[3 * y + 1], - we = V * X - de * ve, - rt = V * ve + de * X, - ot = A + ue, - qe = F + pe, - He = A - ue, - Qe = F - pe, - Be = Me + we, - Ce = Y + rt, - Se = i * (Me - we), - je = i * (Y - rt); - (e[T] = ot + Be), - (e[T + 1] = qe + Ce), - (e[v] = He + je), - (e[v + 1] = Qe - Se), - (e[S] = ot - Be), - (e[S + 1] = qe - Ce), - (e[E] = He - je), - (e[E + 1] = Qe + Se); - } - } - } - } - _singleRealTransform2(e, o, i, u, n) { - const s = e[u], - d = e[u + n]; - (o[i] = s + d), (o[i + 1] = 0), (o[i + 2] = s - d), (o[i + 3] = 0); - } - _singleRealTransform4(e, o, i, u, n, s) { - const d = n * 2, - f = n * 3, - r = e[u], - a = e[u + n], - l = e[u + d], - p = e[u + f], - m = r + l, - y = r - l, - T = a + p, - v = s * (a - p); - (o[i] = m + T), - (o[i + 1] = 0), - (o[i + 2] = y), - (o[i + 3] = -v), - (o[i + 4] = m - T), - (o[i + 5] = 0), - (o[i + 6] = y), - (o[i + 7] = v); - } -} -class NP2FFT { - constructor(e) { - const o = 2 * (e - 1), - i = 2 * (2 * e - 1), - u = 2 ** Math.ceil(Math.log2(i)); - (this.bufferSize = u), (this._a = o); - const n = new Float64Array(i), - s = new Float64Array(u); - (this._chirpBuffer = new Float64Array(u)), - (this._buffer1 = new Float64Array(u)), - (this._buffer2 = new Float64Array(u)), - (this._outBuffer1 = new Float64Array(u)), - (this._outBuffer2 = new Float64Array(u)); - const d = (-2 * Math.PI) / e, - f = Math.cos(d), - r = Math.sin(d); - for (let a = 0; a < i >> 1; ++a) { - const l = (a + 1 - e) ** 2 / 2, - p = Math.sqrt(f ** 2 + r ** 2) ** l, - m = l * Math.atan2(r, f), - y = 2 * a; - (n[y] = p * Math.cos(m)), (n[y + 1] = p * Math.sin(m)), (s[y] = n[y]), (s[y + 1] = -n[y + 1]); - } - (this._slicedChirpBuffer = n.subarray(o, i)), - (this._f = new P2FFT(u >> 1)), - this._f.transform(this._chirpBuffer, s); - } - _transform(e, o, i) { - const u = this._buffer1, - n = this._buffer2, - s = this._outBuffer1, - d = this._outBuffer2, - f = this._chirpBuffer, - r = this._slicedChirpBuffer, - a = this._a; - if (i) - for (let l = 0; l < r.length; l += 2) { - const p = l + 1, - m = l >> 1, - y = o[m]; - (u[l] = y * r[l]), (u[p] = y * r[p]); - } - else - for (let l = 0; l < r.length; l += 2) { - const p = l + 1; - (u[l] = o[l] * r[l] - o[p] * r[p]), (u[p] = o[l] * r[p] + o[p] * r[l]); - } - this._f.transform(s, u); - for (let l = 0; l < f.length; l += 2) { - const p = l + 1; - (n[l] = s[l] * f[l] - s[p] * f[p]), (n[p] = s[l] * f[p] + s[p] * f[l]); - } - this._f.inverseTransform(d, n); - for (let l = 0; l < d.length; l += 2) { - const p = d[l + a], - m = d[l + a + 1], - y = r[l], - T = r[l + 1]; - (e[l] = p * y - m * T), (e[l + 1] = p * T + m * y); - } - } - transform(e, o) { - this._transform(e, o, !1); - } - realTransform(e, o) { - this._transform(e, o, !0); - } -} -class FFT { - constructor(e) { - (this.fft_length = e), - (this.isPowerOfTwo = isPowerOfTwo(e)), - this.isPowerOfTwo - ? ((this.fft = new P2FFT(e)), (this.outputBufferSize = 2 * e)) - : ((this.fft = new NP2FFT(e)), (this.outputBufferSize = this.fft.bufferSize)); - } - realTransform(e, o) { - this.fft.realTransform(e, o); - } - transform(e, o) { - this.fft.transform(e, o); - } -} -function medianFilter(t, e) { - if (e % 2 === 0 || e <= 0) throw new Error('Window size must be a positive odd number'); - const o = new t.constructor(t.length), - i = new t.constructor(e), - u = Math.floor(e / 2); - for (let n = 0; n < t.length; ++n) { - let s = 0; - for (let d = -u; d <= u; ++d) { - let f = n + d; - f < 0 ? (f = Math.abs(f)) : f >= t.length && (f = 2 * (t.length - 1) - f), (i[s++] = t[f]); - } - i.sort(), (o[n] = i[u]); - } - return o; -} -const scriptRel = 'modulepreload', - assetsURL = function (t) { - return '/' + t; - }, - seen = {}, - __vitePreload = function (e, o, i) { - let u = Promise.resolve(); - if (o && o.length > 0) { - const n = document.getElementsByTagName('link'); - u = Promise.all( - o.map((s) => { - if (((s = assetsURL(s)), s in seen)) return; - seen[s] = !0; - const d = s.endsWith('.css'), - f = d ? '[rel="stylesheet"]' : ''; - if (!!i) - for (let l = n.length - 1; l >= 0; l--) { - const p = n[l]; - if (p.href === s && (!d || p.rel === 'stylesheet')) return; - } - else if (document.querySelector(`link[href="${s}"]${f}`)) return; - const a = document.createElement('link'); - if ( - ((a.rel = d ? 'stylesheet' : scriptRel), - d || ((a.as = 'script'), (a.crossOrigin = '')), - (a.href = s), - document.head.appendChild(a), - d) - ) - return new Promise((l, p) => { - a.addEventListener('load', l), - a.addEventListener('error', () => p(new Error(`Unable to preload CSS for ${s}`))); - }); - }) - ); - } - return u - .then(() => e()) - .catch((n) => { - const s = new Event('vite:preloadError', { cancelable: !0 }); - if (((s.payload = n), window.dispatchEvent(s), !s.defaultPrevented)) throw n; - }); - }; -/*! - * ONNX Runtime Web v1.17.1 - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ var vd = Object.create, - En = Object.defineProperty, - wd = Object.getOwnPropertyDescriptor, - _d = Object.getOwnPropertyNames, - Od = Object.getPrototypeOf, - Id = Object.prototype.hasOwnProperty, - L = (t, e) => () => (t && (e = t((t = 0))), e), - me = (t, e) => () => (e || t((e = { exports: {} }).exports, e), e.exports), - Pr = (t, e) => { - for (var o in e) En(t, o, { get: e[o], enumerable: !0 }); - }, - Ha = (t, e, o, i) => { - if ((e && typeof e == 'object') || typeof e == 'function') - for (let u of _d(e)) - !Id.call(t, u) && u !== o && En(t, u, { get: () => e[u], enumerable: !(i = wd(e, u)) || i.enumerable }); - return t; - }, - Er = (t, e, o) => ( - (o = t != null ? vd(Od(t)) : {}), - Ha(e || !t || !t.__esModule ? En(o, 'default', { value: t, enumerable: !0 }) : o, t) - ), - rr = (t) => Ha(En({}, '__esModule', { value: !0 }), t), - Dn, - nr, - or, - Ln, - Fn = L(() => { - (Dn = new Map()), - (nr = []), - (or = (t, e, o) => { - if (e && typeof e.init == 'function' && typeof e.createInferenceSessionHandler == 'function') { - let i = Dn.get(t); - if (i === void 0) Dn.set(t, { backend: e, priority: o }); - else { - if (i.priority > o) return; - if (i.priority === o && i.backend !== e) - throw new Error(`cannot register backend "${t}" using priority ${o}`); - } - if (o >= 0) { - let u = nr.indexOf(t); - u !== -1 && nr.splice(u, 1); - for (let n = 0; n < nr.length; n++) - if (Dn.get(nr[n]).priority <= o) { - nr.splice(n, 0, t); - return; - } - nr.push(t); - } - return; - } - throw new TypeError('not a valid backend'); - }), - (Ln = async (t) => { - let e = t.length === 0 ? nr : t, - o = []; - for (let i of e) { - let u = Dn.get(i); - if (u) { - if (u.initialized) return u.backend; - if (u.aborted) continue; - let n = !!u.initPromise; - try { - return ( - n || (u.initPromise = u.backend.init(i)), - await u.initPromise, - (u.initialized = !0), - u.backend - ); - } catch (s) { - n || o.push({ name: i, err: s }), (u.aborted = !0); - } finally { - delete u.initPromise; - } - } - } - throw new Error(`no available backend found. ERR: ${o.map((i) => `[${i.name}] ${i.err}`).join(', ')}`); - }); - }), - qa = L(() => { - Fn(); - }), - ja, - Ya = L(() => { - ja = '1.17.1'; - }), - Xa, - ir, - Ho = L(() => { - Ya(), - (Xa = 'warning'), - (ir = { - wasm: {}, - webgl: {}, - webgpu: {}, - versions: { common: ja }, - set logLevel(t) { - if (t !== void 0) { - if (typeof t != 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(t) === -1) - throw new Error(`Unsupported logging level: ${t}`); - Xa = t; - } - }, - get logLevel() { - return Xa; - }, - }), - Object.defineProperty(ir, 'logLevel', { enumerable: !0 }); - }), - Z, - Ka = L(() => { - Ho(), (Z = ir); - }), - Ja, - Za, - Qa = L(() => { - (Ja = (t, e) => { - let o = typeof document < 'u' ? document.createElement('canvas') : new OffscreenCanvas(1, 1); - (o.width = t.dims[3]), (o.height = t.dims[2]); - let i = o.getContext('2d'); - if (i != null) { - let u, n; - e?.tensorLayout !== void 0 && e.tensorLayout === 'NHWC' - ? ((u = t.dims[2]), (n = t.dims[3])) - : ((u = t.dims[3]), (n = t.dims[2])); - let s = e?.format !== void 0 ? e.format : 'RGB', - d = e?.norm, - f, - r; - d === void 0 || d.mean === void 0 - ? (f = [255, 255, 255, 255]) - : typeof d.mean == 'number' - ? (f = [d.mean, d.mean, d.mean, d.mean]) - : ((f = [d.mean[0], d.mean[1], d.mean[2], 0]), d.mean[3] !== void 0 && (f[3] = d.mean[3])), - d === void 0 || d.bias === void 0 - ? (r = [0, 0, 0, 0]) - : typeof d.bias == 'number' - ? (r = [d.bias, d.bias, d.bias, d.bias]) - : ((r = [d.bias[0], d.bias[1], d.bias[2], 0]), d.bias[3] !== void 0 && (r[3] = d.bias[3])); - let a = n * u, - l = 0, - p = a, - m = a * 2, - y = -1; - s === 'RGBA' - ? ((l = 0), (p = a), (m = a * 2), (y = a * 3)) - : s === 'RGB' - ? ((l = 0), (p = a), (m = a * 2)) - : s === 'RBG' && ((l = 0), (m = a), (p = a * 2)); - for (let T = 0; T < n; T++) - for (let v = 0; v < u; v++) { - let S = (t.data[l++] - r[0]) * f[0], - E = (t.data[p++] - r[1]) * f[1], - A = (t.data[m++] - r[2]) * f[2], - F = y === -1 ? 255 : (t.data[y++] - r[3]) * f[3]; - (i.fillStyle = 'rgba(' + S + ',' + E + ',' + A + ',' + F + ')'), i.fillRect(v, T, 1, 1); - } - if ('toDataURL' in o) return o.toDataURL(); - throw new Error('toDataURL is not supported'); - } else throw new Error('Can not access image data'); - }), - (Za = (t, e) => { - let o = - typeof document < 'u' - ? document.createElement('canvas').getContext('2d') - : new OffscreenCanvas(1, 1).getContext('2d'), - i; - if (o != null) { - let u, n, s; - e?.tensorLayout !== void 0 && e.tensorLayout === 'NHWC' - ? ((u = t.dims[2]), (n = t.dims[1]), (s = t.dims[3])) - : ((u = t.dims[3]), (n = t.dims[2]), (s = t.dims[1])); - let d = e !== void 0 && e.format !== void 0 ? e.format : 'RGB', - f = e?.norm, - r, - a; - f === void 0 || f.mean === void 0 - ? (r = [255, 255, 255, 255]) - : typeof f.mean == 'number' - ? (r = [f.mean, f.mean, f.mean, f.mean]) - : ((r = [f.mean[0], f.mean[1], f.mean[2], 255]), f.mean[3] !== void 0 && (r[3] = f.mean[3])), - f === void 0 || f.bias === void 0 - ? (a = [0, 0, 0, 0]) - : typeof f.bias == 'number' - ? (a = [f.bias, f.bias, f.bias, f.bias]) - : ((a = [f.bias[0], f.bias[1], f.bias[2], 0]), f.bias[3] !== void 0 && (a[3] = f.bias[3])); - let l = n * u; - if ( - e !== void 0 && - ((e.format !== void 0 && s === 4 && e.format !== 'RGBA') || - (s === 3 && e.format !== 'RGB' && e.format !== 'BGR')) - ) - throw new Error("Tensor format doesn't match input tensor dims"); - let p = 4, - m = 0, - y = 1, - T = 2, - v = 3, - S = 0, - E = l, - A = l * 2, - F = -1; - d === 'RGBA' - ? ((S = 0), (E = l), (A = l * 2), (F = l * 3)) - : d === 'RGB' - ? ((S = 0), (E = l), (A = l * 2)) - : d === 'RBG' && ((S = 0), (A = l), (E = l * 2)), - (i = o.createImageData(u, n)); - for (let B = 0; B < n * u; m += p, y += p, T += p, v += p, B++) - (i.data[m] = (t.data[S++] - a[0]) * r[0]), - (i.data[y] = (t.data[E++] - a[1]) * r[1]), - (i.data[T] = (t.data[A++] - a[2]) * r[2]), - (i.data[v] = F === -1 ? 255 : (t.data[F++] - a[3]) * r[3]); - } else throw new Error('Can not access image data'); - return i; - }); - }), - qo, - es, - ts, - rs, - ns, - os = L(() => { - $n(), - (qo = (t, e) => { - if (t === void 0) throw new Error('Image buffer must be defined'); - if (e.height === void 0 || e.width === void 0) - throw new Error('Image height and width must be defined'); - if (e.tensorLayout === 'NHWC') throw new Error('NHWC Tensor layout is not supported yet'); - let { height: o, width: i } = e, - u = e.norm ?? { mean: 255, bias: 0 }, - n, - s; - typeof u.mean == 'number' - ? (n = [u.mean, u.mean, u.mean, u.mean]) - : (n = [u.mean[0], u.mean[1], u.mean[2], u.mean[3] ?? 255]), - typeof u.bias == 'number' - ? (s = [u.bias, u.bias, u.bias, u.bias]) - : (s = [u.bias[0], u.bias[1], u.bias[2], u.bias[3] ?? 0]); - let d = e.format !== void 0 ? e.format : 'RGBA', - f = e.tensorFormat !== void 0 && e.tensorFormat !== void 0 ? e.tensorFormat : 'RGB', - r = o * i, - a = f === 'RGBA' ? new Float32Array(r * 4) : new Float32Array(r * 3), - l = 4, - p = 0, - m = 1, - y = 2, - T = 3, - v = 0, - S = r, - E = r * 2, - A = -1; - d === 'RGB' && ((l = 3), (p = 0), (m = 1), (y = 2), (T = -1)), - f === 'RGBA' - ? (A = r * 3) - : f === 'RBG' - ? ((v = 0), (E = r), (S = r * 2)) - : f === 'BGR' && ((E = 0), (S = r), (v = r * 2)); - for (let F = 0; F < r; F++, p += l, y += l, m += l, T += l) - (a[v++] = (t[p] + s[0]) / n[0]), - (a[S++] = (t[m] + s[1]) / n[1]), - (a[E++] = (t[y] + s[2]) / n[2]), - A !== -1 && T !== -1 && (a[A++] = (t[T] + s[3]) / n[3]); - return f === 'RGBA' ? new Ye('float32', a, [1, 4, o, i]) : new Ye('float32', a, [1, 3, o, i]); - }), - (es = async (t, e) => { - let o = typeof HTMLImageElement < 'u' && t instanceof HTMLImageElement, - i = typeof ImageData < 'u' && t instanceof ImageData, - u = typeof ImageBitmap < 'u' && t instanceof ImageBitmap, - n = typeof t == 'string', - s, - d = e ?? {}, - f = () => { - if (typeof document < 'u') return document.createElement('canvas'); - if (typeof OffscreenCanvas < 'u') return new OffscreenCanvas(1, 1); - throw new Error('Canvas is not supported'); - }, - r = (a) => - a instanceof HTMLCanvasElement || a instanceof OffscreenCanvas ? a.getContext('2d') : null; - if (o) { - let a = f(); - (a.width = t.width), (a.height = t.height); - let l = r(a); - if (l != null) { - let p = t.height, - m = t.width; - if ( - (e !== void 0 && - e.resizedHeight !== void 0 && - e.resizedWidth !== void 0 && - ((p = e.resizedHeight), (m = e.resizedWidth)), - e !== void 0) - ) { - if (((d = e), e.tensorFormat !== void 0)) - throw new Error('Image input config format must be RGBA for HTMLImageElement'); - (d.tensorFormat = 'RGBA'), (d.height = p), (d.width = m); - } else (d.tensorFormat = 'RGBA'), (d.height = p), (d.width = m); - l.drawImage(t, 0, 0), (s = l.getImageData(0, 0, m, p).data); - } else throw new Error('Can not access image data'); - } else if (i) { - let a, l; - if ( - (e !== void 0 && e.resizedWidth !== void 0 && e.resizedHeight !== void 0 - ? ((a = e.resizedHeight), (l = e.resizedWidth)) - : ((a = t.height), (l = t.width)), - e !== void 0 && (d = e), - (d.format = 'RGBA'), - (d.height = a), - (d.width = l), - e !== void 0) - ) { - let p = f(); - (p.width = l), (p.height = a); - let m = r(p); - if (m != null) m.putImageData(t, 0, 0), (s = m.getImageData(0, 0, l, a).data); - else throw new Error('Can not access image data'); - } else s = t.data; - } else if (u) { - if (e === void 0) throw new Error('Please provide image config with format for Imagebitmap'); - let a = f(); - (a.width = t.width), (a.height = t.height); - let l = r(a); - if (l != null) { - let p = t.height, - m = t.width; - return ( - l.drawImage(t, 0, 0, m, p), - (s = l.getImageData(0, 0, m, p).data), - (d.height = p), - (d.width = m), - qo(s, d) - ); - } else throw new Error('Can not access image data'); - } else { - if (n) - return new Promise((a, l) => { - let p = f(), - m = r(p); - if (!t || !m) return l(); - let y = new Image(); - (y.crossOrigin = 'Anonymous'), - (y.src = t), - (y.onload = () => { - (p.width = y.width), (p.height = y.height), m.drawImage(y, 0, 0, p.width, p.height); - let T = m.getImageData(0, 0, p.width, p.height); - (d.height = p.height), (d.width = p.width), a(qo(T.data, d)); - }); - }); - throw new Error('Input data provided is not supported - aborted tensor creation'); - } - if (s !== void 0) return qo(s, d); - throw new Error('Input data provided is not supported - aborted tensor creation'); - }), - (ts = (t, e) => { - let { width: o, height: i, download: u, dispose: n } = e, - s = [1, i, o, 4]; - return new Ye({ location: 'texture', type: 'float32', texture: t, dims: s, download: u, dispose: n }); - }), - (rs = (t, e) => { - let { dataType: o, dims: i, download: u, dispose: n } = e; - return new Ye({ - location: 'gpu-buffer', - type: o ?? 'float32', - gpuBuffer: t, - dims: i, - download: u, - dispose: n, - }); - }), - (ns = (t, e, o) => new Ye({ location: 'cpu-pinned', type: t, data: e, dims: o ?? [e.length] })); - }), - Qr, - Cn, - is, - as, - ss = L(() => { - (Qr = new Map([ - ['float32', Float32Array], - ['uint8', Uint8Array], - ['int8', Int8Array], - ['uint16', Uint16Array], - ['float16', Uint16Array], - ['int16', Int16Array], - ['int32', Int32Array], - ['bool', Uint8Array], - ['float64', Float64Array], - ['uint32', Uint32Array], - ])), - (Cn = new Map([ - [Float32Array, 'float32'], - [Uint8Array, 'uint8'], - [Int8Array, 'int8'], - [Uint16Array, 'uint16'], - [Int16Array, 'int16'], - [Int32Array, 'int32'], - [Float64Array, 'float64'], - [Uint32Array, 'uint32'], - ])), - (is = !1), - (as = () => { - if (!is) { - is = !0; - let t = typeof BigInt64Array < 'u' && typeof BigInt64Array.from == 'function', - e = typeof BigUint64Array < 'u' && typeof BigUint64Array.from == 'function'; - t && (Qr.set('int64', BigInt64Array), Cn.set(BigInt64Array, 'int64')), - e && (Qr.set('uint64', BigUint64Array), Cn.set(BigUint64Array, 'uint64')); - } - }); - }), - us, - ls, - fs = L(() => { - $n(), - (us = (t) => { - let e = 1; - for (let o = 0; o < t.length; o++) { - let i = t[o]; - if (typeof i != 'number' || !Number.isSafeInteger(i)) - throw new TypeError(`dims[${o}] must be an integer, got: ${i}`); - if (i < 0) throw new RangeError(`dims[${o}] must be a non-negative integer, got: ${i}`); - e *= i; - } - return e; - }), - (ls = (t, e) => { - switch (t.location) { - case 'cpu': - return new Ye(t.type, t.data, e); - case 'cpu-pinned': - return new Ye({ location: 'cpu-pinned', data: t.data, type: t.type, dims: e }); - case 'texture': - return new Ye({ location: 'texture', texture: t.texture, type: t.type, dims: e }); - case 'gpu-buffer': - return new Ye({ location: 'gpu-buffer', gpuBuffer: t.gpuBuffer, type: t.type, dims: e }); - default: - throw new Error(`tensorReshape: tensor location ${t.location} is not supported`); - } - }); - }), - Ye, - $n = L(() => { - Qa(), - os(), - ss(), - fs(), - (Ye = class { - constructor(t, e, o) { - as(); - let i, u; - if (typeof t == 'object' && 'location' in t) - switch (((this.dataLocation = t.location), (i = t.type), (u = t.dims), t.location)) { - case 'cpu-pinned': { - let s = Qr.get(i); - if (!s) - throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`); - if (!(t.data instanceof s)) throw new TypeError(`buffer should be of type ${s.name}`); - this.cpuData = t.data; - break; - } - case 'texture': { - if (i !== 'float32') - throw new TypeError(`unsupported type "${i}" to create tensor from texture`); - (this.gpuTextureData = t.texture), - (this.downloader = t.download), - (this.disposer = t.dispose); - break; - } - case 'gpu-buffer': { - if ( - i !== 'float32' && - i !== 'float16' && - i !== 'int32' && - i !== 'int64' && - i !== 'uint32' && - i !== 'bool' - ) - throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`); - (this.gpuBufferData = t.gpuBuffer), - (this.downloader = t.download), - (this.disposer = t.dispose); - break; - } - default: - throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); - } - else { - let s, d; - if (typeof t == 'string') - if (((i = t), (d = o), t === 'string')) { - if (!Array.isArray(e)) - throw new TypeError("A string tensor's data must be a string array."); - s = e; - } else { - let f = Qr.get(t); - if (f === void 0) throw new TypeError(`Unsupported tensor type: ${t}.`); - if (Array.isArray(e)) { - if (t === 'float16') - throw new TypeError( - 'Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.' - ); - t === 'uint64' || t === 'int64' ? (s = f.from(e, BigInt)) : (s = f.from(e)); - } else if (e instanceof f) s = e; - else throw new TypeError(`A ${i} tensor's data must be type of ${f}`); - } - else if (((d = e), Array.isArray(t))) { - if (t.length === 0) - throw new TypeError('Tensor type cannot be inferred from an empty array.'); - let f = typeof t[0]; - if (f === 'string') (i = 'string'), (s = t); - else if (f === 'boolean') (i = 'bool'), (s = Uint8Array.from(t)); - else throw new TypeError(`Invalid element type of data array: ${f}.`); - } else { - let f = Cn.get(t.constructor); - if (f === void 0) - throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`); - (i = f), (s = t); - } - if (d === void 0) d = [s.length]; - else if (!Array.isArray(d)) throw new TypeError("A tensor's dims must be a number array"); - (u = d), (this.cpuData = s), (this.dataLocation = 'cpu'); - } - let n = us(u); - if (this.cpuData && n !== this.cpuData.length) - throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`); - (this.type = i), (this.dims = u), (this.size = n); - } - static async fromImage(t, e) { - return es(t, e); - } - static fromTexture(t, e) { - return ts(t, e); - } - static fromGpuBuffer(t, e) { - return rs(t, e); - } - static fromPinnedBuffer(t, e, o) { - return ns(t, e, o); - } - toDataURL(t) { - return Ja(this, t); - } - toImageData(t) { - return Za(this, t); - } - get data() { - if ((this.ensureValid(), !this.cpuData)) - throw new Error( - 'The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.' - ); - return this.cpuData; - } - get location() { - return this.dataLocation; - } - get texture() { - if ((this.ensureValid(), !this.gpuTextureData)) - throw new Error('The data is not stored as a WebGL texture.'); - return this.gpuTextureData; - } - get gpuBuffer() { - if ((this.ensureValid(), !this.gpuBufferData)) - throw new Error('The data is not stored as a WebGPU buffer.'); - return this.gpuBufferData; - } - async getData(t) { - switch ((this.ensureValid(), this.dataLocation)) { - case 'cpu': - case 'cpu-pinned': - return this.data; - case 'texture': - case 'gpu-buffer': { - if (!this.downloader) - throw new Error('The current tensor is not created with a specified data downloader.'); - if (this.isDownloading) throw new Error('The current tensor is being downloaded.'); - try { - this.isDownloading = !0; - let e = await this.downloader(); - return ( - (this.downloader = void 0), - (this.dataLocation = 'cpu'), - (this.cpuData = e), - t && this.disposer && (this.disposer(), (this.disposer = void 0)), - e - ); - } finally { - this.isDownloading = !1; - } - } - default: - throw new Error(`cannot get data from location: ${this.dataLocation}`); - } - } - dispose() { - if (this.isDownloading) throw new Error('The current tensor is being downloaded.'); - this.disposer && (this.disposer(), (this.disposer = void 0)), - (this.cpuData = void 0), - (this.gpuTextureData = void 0), - (this.gpuBufferData = void 0), - (this.downloader = void 0), - (this.isDownloading = void 0), - (this.dataLocation = 'none'); - } - ensureValid() { - if (this.dataLocation === 'none') throw new Error('The tensor is disposed.'); - } - reshape(t) { - if ((this.ensureValid(), this.downloader || this.disposer)) - throw new Error('Cannot reshape a tensor that owns GPU resource.'); - return ls(this, t); - } - }); - }), - Re, - kn = L(() => { - $n(), (Re = Ye); - }), - cs, - ps, - ar, - sr, - jo = L(() => { - Ho(), - (cs = (t, e) => { - ir.wasm.trace && console.timeStamp(`${t}::ORT::${e}`); - }), - (ps = (t, e) => { - let o = new Error().stack?.split(/\r\n|\r|\n/g) || [], - i = !1; - for (let u = 0; u < o.length; u++) { - if (i && !o[u].includes('TRACE_FUNC')) { - let n = `FUNC_${t}::${o[u].trim().split(' ')[1]}`; - e && (n += `::${e}`), cs('CPU', n); - return; - } - o[u].includes('TRACE_FUNC') && (i = !0); - } - }), - (ar = (t) => { - ir.wasm.trace && ps('BEGIN', t); - }), - (sr = (t) => { - ir.wasm.trace && ps('END', t); - }); - }), - Bn, - ds = L(() => { - Fn(), - kn(), - jo(), - (Bn = class Rs { - constructor(e) { - this.handler = e; - } - async run(e, o, i) { - ar(); - let u = {}, - n = {}; - if (typeof e != 'object' || e === null || e instanceof Re || Array.isArray(e)) - throw new TypeError( - "'feeds' must be an object that use input names as keys and OnnxValue as corresponding values." - ); - let s = !0; - if (typeof o == 'object') { - if (o === null) throw new TypeError('Unexpected argument[1]: cannot be null.'); - if (o instanceof Re) throw new TypeError("'fetches' cannot be a Tensor"); - if (Array.isArray(o)) { - if (o.length === 0) throw new TypeError("'fetches' cannot be an empty array."); - s = !1; - for (let r of o) { - if (typeof r != 'string') - throw new TypeError("'fetches' must be a string array or an object."); - if (this.outputNames.indexOf(r) === -1) - throw new RangeError(`'fetches' contains invalid output name: ${r}.`); - u[r] = null; - } - if (typeof i == 'object' && i !== null) n = i; - else if (typeof i < 'u') throw new TypeError("'options' must be an object."); - } else { - let r = !1, - a = Object.getOwnPropertyNames(o); - for (let l of this.outputNames) - if (a.indexOf(l) !== -1) { - let p = o[l]; - (p === null || p instanceof Re) && ((r = !0), (s = !1), (u[l] = p)); - } - if (r) { - if (typeof i == 'object' && i !== null) n = i; - else if (typeof i < 'u') throw new TypeError("'options' must be an object."); - } else n = o; - } - } else if (typeof o < 'u') - throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); - for (let r of this.inputNames) - if (typeof e[r] > 'u') throw new Error(`input '${r}' is missing in 'feeds'.`); - if (s) for (let r of this.outputNames) u[r] = null; - let d = await this.handler.run(e, u, n), - f = {}; - for (let r in d) - if (Object.hasOwnProperty.call(d, r)) { - let a = d[r]; - a instanceof Re ? (f[r] = a) : (f[r] = new Re(a.type, a.data, a.dims)); - } - return sr(), f; - } - async release() { - return this.handler.dispose(); - } - static async create(e, o, i, u) { - ar(); - let n, - s = {}; - if (typeof e == 'string') { - if (((n = e), typeof o == 'object' && o !== null)) s = o; - else if (typeof o < 'u') throw new TypeError("'options' must be an object."); - } else if (e instanceof Uint8Array) { - if (((n = e), typeof o == 'object' && o !== null)) s = o; - else if (typeof o < 'u') throw new TypeError("'options' must be an object."); - } else if ( - e instanceof ArrayBuffer || - (typeof SharedArrayBuffer < 'u' && e instanceof SharedArrayBuffer) - ) { - let r = e, - a = 0, - l = e.byteLength; - if (typeof o == 'object' && o !== null) s = o; - else if (typeof o == 'number') { - if (((a = o), !Number.isSafeInteger(a))) - throw new RangeError("'byteOffset' must be an integer."); - if (a < 0 || a >= r.byteLength) - throw new RangeError(`'byteOffset' is out of range [0, ${r.byteLength}).`); - if (((l = e.byteLength - a), typeof i == 'number')) { - if (((l = i), !Number.isSafeInteger(l))) - throw new RangeError("'byteLength' must be an integer."); - if (l <= 0 || a + l > r.byteLength) - throw new RangeError(`'byteLength' is out of range (0, ${r.byteLength - a}].`); - if (typeof u == 'object' && u !== null) s = u; - else if (typeof u < 'u') throw new TypeError("'options' must be an object."); - } else if (typeof i < 'u') throw new TypeError("'byteLength' must be a number."); - } else if (typeof o < 'u') throw new TypeError("'options' must be an object."); - n = new Uint8Array(r, a, l); - } else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); - let d = (s.executionProviders || []).map((r) => (typeof r == 'string' ? r : r.name)), - f = await (await Ln(d)).createInferenceSessionHandler(n, s); - return sr(), new Rs(f); - } - startProfiling() { - this.handler.startProfiling(); - } - endProfiling() { - this.handler.endProfiling(); - } - get inputNames() { - return this.handler.inputNames; - } - get outputNames() { - return this.handler.outputNames; - } - }); - }), - Sd, - hs = L(() => { - ds(), (Sd = Bn); - }), - ms = L(() => {}), - Ad, - Nn, - bs = L(() => { - Fn(), - kn(), - (Ad = - "Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files."), - (Nn = class Bs { - constructor(e, o, i) { - (this.handler = e), (this.hasOptimizerModel = o), (this.hasEvalModel = i); - } - get trainingInputNames() { - return this.handler.inputNames; - } - get trainingOutputNames() { - return this.handler.outputNames; - } - get evalInputNames() { - if (this.hasEvalModel) return this.handler.evalInputNames; - throw new Error('This training session has no evalModel loaded.'); - } - get evalOutputNames() { - if (this.hasEvalModel) return this.handler.evalOutputNames; - throw new Error('This training session has no evalModel loaded.'); - } - static async create(e, o) { - let i = e.evalModel || '', - u = e.optimizerModel || '', - n = o || {}, - s = (n.executionProviders || []).map((f) => (typeof f == 'string' ? f : f.name)), - d = await Ln(s); - if (d.createTrainingSessionHandler) { - let f = await d.createTrainingSessionHandler(e.checkpointState, e.trainModel, i, u, n); - return new Bs(f, !!e.optimizerModel, !!e.evalModel); - } else throw new Error(Ad); - } - typeNarrowingForRunStep(e, o, i, u, n) { - let s = {}, - d = {}; - if (typeof i != 'object' || i === null || i instanceof Re || Array.isArray(i)) - throw new TypeError( - "'feeds' must be an object that use input names as keys and OnnxValue as corresponding values." - ); - let f = !0; - if (typeof u == 'object') { - if (u === null) throw new TypeError('Unexpected argument[1]: cannot be null.'); - if (u instanceof Re) throw new TypeError("'fetches' cannot be a Tensor"); - if (Array.isArray(u)) { - if (u.length === 0) throw new TypeError("'fetches' cannot be an empty array."); - f = !1; - for (let r of u) { - if (typeof r != 'string') - throw new TypeError("'fetches' must be a string array or an object."); - if (o.indexOf(r) === -1) - throw new RangeError(`'fetches' contains invalid output name: ${r}.`); - s[r] = null; - } - if (typeof n == 'object' && n !== null) d = n; - else if (typeof n < 'u') throw new TypeError("'options' must be an object."); - } else { - let r = !1, - a = Object.getOwnPropertyNames(u); - for (let l of o) - if (a.indexOf(l) !== -1) { - let p = u[l]; - (p === null || p instanceof Re) && ((r = !0), (f = !1), (s[l] = p)); - } - if (r) { - if (typeof n == 'object' && n !== null) d = n; - else if (typeof n < 'u') throw new TypeError("'options' must be an object."); - } else d = u; - } - } else if (typeof u < 'u') - throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); - for (let r of e) if (typeof i[r] > 'u') throw new Error(`input '${r}' is missing in 'feeds'.`); - if (f) for (let r of o) s[r] = null; - return [s, d]; - } - convertHandlerReturnTypeToMapOfTensors(e) { - let o = {}; - for (let i in e) - if (Object.hasOwnProperty.call(e, i)) { - let u = e[i]; - u instanceof Re ? (o[i] = u) : (o[i] = new Re(u.type, u.data, u.dims)); - } - return o; - } - async lazyResetGrad() { - await this.handler.lazyResetGrad(); - } - async runTrainStep(e, o, i) { - let [u, n] = this.typeNarrowingForRunStep( - this.trainingInputNames, - this.trainingOutputNames, - e, - o, - i - ), - s = await this.handler.runTrainStep(e, u, n); - return this.convertHandlerReturnTypeToMapOfTensors(s); - } - async runOptimizerStep(e) { - if (this.hasOptimizerModel) await this.handler.runOptimizerStep(e || {}); - else throw new Error('This TrainingSession has no OptimizerModel loaded.'); - } - async runEvalStep(e, o, i) { - if (this.hasEvalModel) { - let [u, n] = this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, e, o, i), - s = await this.handler.runEvalStep(e, u, n); - return this.convertHandlerReturnTypeToMapOfTensors(s); - } else throw new Error('This TrainingSession has no EvalModel loaded.'); - } - async getParametersSize(e = !0) { - return this.handler.getParametersSize(e); - } - async loadParametersBuffer(e, o = !0) { - let i = await this.getParametersSize(o); - if (e.length !== 4 * i) - throw new Error( - 'Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.' - ); - return this.handler.loadParametersBuffer(e, o); - } - async getContiguousParameters(e = !0) { - return this.handler.getContiguousParameters(e); - } - async release() { - return this.handler.dispose(); - } - }); - }), - Pd, - gs = L(() => { - bs(), (Pd = Nn); - }), - Yo = {}; -Pr(Yo, { - InferenceSession: () => Sd, - TRACE: () => cs, - TRACE_FUNC_BEGIN: () => ar, - TRACE_FUNC_END: () => sr, - Tensor: () => Re, - TrainingSession: () => Pd, - env: () => Z, - registerBackend: () => or, -}); -var vt = L(() => { - qa(), Ka(), hs(), kn(), jo(), ms(), gs(); -}); -function jt(t, e, o, i) { - if (e === void 0) return Dd(t); - if (o === void 0) Rn(t, e); - else if (typeof o == 'number' && i === void 0) Rn(t, e); - else if (typeof o == 'string' && i === void 0) Rn(t, o, 1, e); - else if (typeof o == 'string' && typeof i == 'number') Rn(t, o, i, e); - else throw new TypeError('input is valid'); -} -function Dd(t) { - return { - verbose: jt.verbose.bind(null, t), - info: jt.info.bind(null, t), - warning: jt.warning.bind(null, t), - error: jt.error.bind(null, t), - fatal: jt.fatal.bind(null, t), - }; -} -function Rn(t, e, o, i) { - let u = en[i || ''] || en['']; - Ts[t] < Ts[u.minimalSeverity] || - (u.logDateTime && (e = `${new Date().toISOString()}|${e}`), u.logSourceLocation, Ed[u.provider].log(t, e, i)); -} -var Xo, - Ko, - Ts, - Ed, - xs, - en, - ce, - Gn, - Un, - zn, - Mn, - ut = L(() => { - (Xo = class { - log(t, e, o) {} - }), - (Ko = class { - log(t, e, o) { - console.log(`${this.color(t)} ${o ? '\x1B[35m' + o + '\x1B[0m ' : ''}${e}`); - } - color(t) { - switch (t) { - 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: ${t}`); - } - } - }), - (Ts = { verbose: 1e3, info: 2e3, warning: 4e3, error: 5e3, fatal: 6e3 }), - (Ed = { none: new Xo(), console: new Ko() }), - (xs = { provider: 'console', minimalSeverity: 'warning', logDateTime: !0, logSourceLocation: !1 }), - (en = { '': xs }), - ((t) => { - function e(r, a) { - t('verbose', r, a); - } - t.verbose = e; - function o(r, a) { - t('info', r, a); - } - t.info = o; - function i(r, a) { - t('warning', r, a); - } - t.warning = i; - function u(r, a) { - t('error', r, a); - } - t.error = u; - function n(r, a) { - t('fatal', r, a); - } - t.fatal = n; - function s(r) { - (en = {}), d('', r || {}); - } - t.reset = s; - function d(r, a) { - if (r === '*') s(a); - else { - let l = en[r] || xs; - en[r] = { - provider: a.provider || l.provider, - minimalSeverity: a.minimalSeverity || l.minimalSeverity, - logDateTime: a.logDateTime === void 0 ? l.logDateTime : a.logDateTime, - logSourceLocation: - a.logSourceLocation === void 0 ? l.logSourceLocation : a.logSourceLocation, - }; - } - } - t.set = d; - function f(r) { - let a = {}; - r.logLevel && (a.minimalSeverity = r.logLevel), d('', a); - } - t.setWithEnv = f; - })((jt ||= {})), - (ce = jt), - (Gn = class { - constructor(t, e, o, i, u, n) { - (this.category = t), - (this.name = e), - (this.startTime = o), - (this.endCallback = i), - (this.timer = u), - (this.ctx = n); - } - async end() { - return this.endCallback(this); - } - async checkTimer() { - if (this.ctx === void 0 || this.timer === void 0) throw new Error('No webgl timer found'); - return this.ctx.endTimer(), this.ctx.waitForQueryAndGetTime(this.timer); - } - }), - (Un = class { - constructor(t, e, o, i) { - (this.category = t), (this.name = e), (this.startTime = o), (this.endTime = i); - } - }), - (zn = class { - constructor(t, e, o) { - (this._started = !1), - (this._flushPointer = 0), - (this._started = !1), - (this._maxNumberEvents = t === void 0 ? 1e4 : t), - (this._flushBatchSize = e === void 0 ? 10 : e), - (this._flushIntervalInMilliseconds = o === void 0 ? 5e3 : o); - } - static create(t) { - return t === void 0 - ? new this() - : new this(t.maxNumberEvents, t.flushBatchSize, t.flushIntervalInMilliseconds); - } - start() { - (this._started = !0), (this._timingEvents = []), (this._flushTime = Mn()), (this._flushPointer = 0); - } - stop() { - for (this._started = !1; this._flushPointer < this._timingEvents.length; this._flushPointer++) - this.logOneEvent(this._timingEvents[this._flushPointer]); - } - event(t, e, o, i) { - let u = this._started ? this.begin(t, e, i) : void 0, - n = !1, - s = o(); - if (s && typeof s.then == 'function') - return ( - (n = !0), - new Promise((d, f) => { - s.then( - async (r) => { - u && (await u.end()), d(r); - }, - async (r) => { - u && (await u.end()), f(r); - } - ); - }) - ); - if (!n && u) { - let d = u.end(); - if (d && typeof d.then == 'function') - return new Promise((f, r) => { - d.then( - () => { - f(s); - }, - (a) => { - r(a); - } - ); - }); - } - return s; - } - begin(t, e, o) { - if (!this._started) throw new Error('profiler is not started yet'); - if (o === void 0) { - let i = Mn(); - return this.flush(i), new Gn(t, e, i, (u) => this.endSync(u)); - } else { - let i = o.beginTimer(); - return new Gn(t, e, 0, async (u) => this.end(u), i, o); - } - } - async end(t) { - let e = await t.checkTimer(); - this._timingEvents.length < this._maxNumberEvents && - (this._timingEvents.push(new Un(t.category, t.name, t.startTime, e)), this.flush(e)); - } - endSync(t) { - let e = Mn(); - this._timingEvents.length < this._maxNumberEvents && - (this._timingEvents.push(new Un(t.category, t.name, t.startTime, e)), this.flush(e)); - } - logOneEvent(t) { - ce.verbose( - `Profiler.${t.category}`, - `${(t.endTime - t.startTime).toFixed(2)}ms on event '${t.name}' at ${t.endTime.toFixed(2)}` - ); - } - flush(t) { - if ( - this._timingEvents.length - this._flushPointer >= this._flushBatchSize || - t - this._flushTime >= this._flushIntervalInMilliseconds - ) { - for ( - let e = this._flushPointer; - this._flushPointer < e + this._flushBatchSize && - this._flushPointer < this._timingEvents.length; - this._flushPointer++ - ) - this.logOneEvent(this._timingEvents[this._flushPointer]); - this._flushTime = Mn(); - } - } - get started() { - return this._started; - } - }), - (Mn = typeof performance < 'u' && performance.now ? () => performance.now() : Date.now); - }); -function vs(t, e, o) { - for (let i of o) { - let u = i[0], - n = i[1], - s = i[2], - d = i[3], - f = i[4]; - if (t.opType === u) { - for (let r of e) - if ((r.domain === n || (r.domain === 'ai.onnx' && n === '')) && Ld(r.version, s)) - return { opImpl: d, opInit: f }; - } - } - throw new TypeError( - `cannot resolve operator '${t.opType}' with opsets: ${e - .map((i) => `${i.domain || 'ai.onnx'} v${i.version}`) - .join(', ')}` - ); -} -function Ld(t, e) { - if (e.endsWith('+')) { - let o = Number.parseInt(e.substring(0, e.length - 1), 10); - return !isNaN(o) && o <= t; - } else if (e.split('-').length === 2) { - let o = e.split('-'), - i = Number.parseInt(o[0], 10), - u = Number.parseInt(o[1], 10); - return !isNaN(i) && !isNaN(u) && i <= t && t <= u; - } else return Number.parseInt(e, 10) === t; -} -var ws = L(() => {}), - _s = me((t) => { - t.__esModule = !0; - var e = (function () { - function o(i) { - if (!i) throw new TypeError('Invalid argument; `value` has no value.'); - (this.value = o.EMPTY), i && o.isGuid(i) && (this.value = i); - } - return ( - (o.isGuid = function (i) { - var u = i.toString(); - return i && (i instanceof o || o.validator.test(u)); - }), - (o.create = function () { - return new o([o.gen(2), o.gen(1), o.gen(1), o.gen(1), o.gen(3)].join('-')); - }), - (o.createEmpty = function () { - return new o('emptyguid'); - }), - (o.parse = function (i) { - return new o(i); - }), - (o.raw = function () { - return [o.gen(2), o.gen(1), o.gen(1), o.gen(1), o.gen(3)].join('-'); - }), - (o.gen = function (i) { - for (var u = '', n = 0; n < i; n++) - u += (((1 + Math.random()) * 65536) | 0).toString(16).substring(1); - return u; - }), - (o.prototype.equals = function (i) { - return o.isGuid(i) && this.value === i.toString(); - }), - (o.prototype.isEmpty = function () { - return this.value === o.EMPTY; - }), - (o.prototype.toString = function () { - return this.value; - }), - (o.prototype.toJSON = function () { - return { value: this.value }; - }), - (o.validator = new RegExp('^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$', 'i')), - (o.EMPTY = '00000000-0000-0000-0000-000000000000'), - o - ); - })(); - t.Guid = e; - }); -function be(t, e, o) { - (this.low = t | 0), (this.high = e | 0), (this.unsigned = !!o); -} -function We(t) { - return (t && t.__isLong__) === !0; -} -function Os(t) { - var e = Math.clz32(t & -t); - return t ? 31 - e : e; -} -function ur(t, e) { - var o, i, u; - return e - ? ((t >>>= 0), (u = 0 <= t && t < 256) && ((i = Ss[t]), i) ? i : ((o = le(t, 0, !0)), u && (Ss[t] = o), o)) - : ((t |= 0), - (u = -128 <= t && t < 128) && ((i = Is[t]), i) ? i : ((o = le(t, t < 0 ? -1 : 0, !1)), u && (Is[t] = o), o)); -} -function ft(t, e) { - if (isNaN(t)) return e ? Ut : wt; - if (e) { - if (t < 0) return Ut; - if (t >= Ds) return $s; - } else { - if (t <= -Ps) return tt; - if (t + 1 >= Ps) return Fs; - } - return t < 0 ? ft(-t, e).neg() : le(t % Lr | 0, (t / Lr) | 0, e); -} -function le(t, e, o) { - return new be(t, e, o); -} -function Qo(t, e, o) { - if (t.length === 0) throw Error('empty string'); - if ( - (typeof e == 'number' ? ((o = e), (e = !1)) : (e = !!e), - t === 'NaN' || t === 'Infinity' || t === '+Infinity' || t === '-Infinity') - ) - return e ? Ut : wt; - if (((o = o || 10), o < 2 || 36 < o)) throw RangeError('radix'); - var i; - if ((i = t.indexOf('-')) > 0) throw Error('interior hyphen'); - if (i === 0) return Qo(t.substring(1), e, o).neg(); - for (var u = ft(Vn(o, 8)), n = wt, s = 0; s < t.length; s += 8) { - var d = Math.min(8, t.length - s), - f = parseInt(t.substring(s, s + d), o); - if (d < 8) { - var r = ft(Vn(o, d)); - n = n.mul(r).add(ft(f)); - } else (n = n.mul(u)), (n = n.add(ft(f))); - } - return (n.unsigned = e), n; -} -function _t(t, e) { - return typeof t == 'number' - ? ft(t, e) - : typeof t == 'string' - ? Qo(t, e) - : le(t.low, t.high, typeof e == 'boolean' ? e : t.unsigned); -} -var lt, - Is, - Ss, - Vn, - As, - $d, - Lr, - Ds, - Ps, - Es, - wt, - Ut, - Dr, - Ls, - Zo, - Fs, - $s, - tt, - $, - zt, - ei = L(() => { - lt = null; - try { - lt = 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 {} - be.prototype.__isLong__, - Object.defineProperty(be.prototype, '__isLong__', { value: !0 }), - (be.isLong = We), - (Is = {}), - (Ss = {}), - (be.fromInt = ur), - (be.fromNumber = ft), - (be.fromBits = le), - (Vn = Math.pow), - (be.fromString = Qo), - (be.fromValue = _t), - (As = 65536), - ($d = 1 << 24), - (Lr = As * As), - (Ds = Lr * Lr), - (Ps = Ds / 2), - (Es = ur($d)), - (wt = ur(0)), - (be.ZERO = wt), - (Ut = ur(0, !0)), - (be.UZERO = Ut), - (Dr = ur(1)), - (be.ONE = Dr), - (Ls = ur(1, !0)), - (be.UONE = Ls), - (Zo = ur(-1)), - (be.NEG_ONE = Zo), - (Fs = le(-1, 2147483647, !1)), - (be.MAX_VALUE = Fs), - ($s = le(-1, -1, !0)), - (be.MAX_UNSIGNED_VALUE = $s), - (tt = le(0, -2147483648, !1)), - (be.MIN_VALUE = tt), - ($ = be.prototype), - ($.toInt = function () { - return this.unsigned ? this.low >>> 0 : this.low; - }), - ($.toNumber = function () { - return this.unsigned ? (this.high >>> 0) * Lr + (this.low >>> 0) : this.high * Lr + (this.low >>> 0); - }), - ($.toString = function (t) { - if (((t = t || 10), t < 2 || 36 < t)) throw RangeError('radix'); - if (this.isZero()) return '0'; - if (this.isNegative()) - if (this.eq(tt)) { - var e = ft(t), - o = this.div(e), - i = o.mul(e).sub(this); - return o.toString(t) + i.toInt().toString(t); - } else return '-' + this.neg().toString(t); - for (var u = ft(Vn(t, 6), this.unsigned), n = this, s = ''; ; ) { - var d = n.div(u), - f = n.sub(d.mul(u)).toInt() >>> 0, - r = f.toString(t); - if (((n = d), n.isZero())) return r + s; - for (; r.length < 6; ) r = '0' + r; - s = '' + r + s; - } - }), - ($.getHighBits = function () { - return this.high; - }), - ($.getHighBitsUnsigned = function () { - return this.high >>> 0; - }), - ($.getLowBits = function () { - return this.low; - }), - ($.getLowBitsUnsigned = function () { - return this.low >>> 0; - }), - ($.getNumBitsAbs = function () { - if (this.isNegative()) return this.eq(tt) ? 64 : this.neg().getNumBitsAbs(); - for (var t = this.high != 0 ? this.high : this.low, e = 31; e > 0 && !(t & (1 << e)); e--); - return this.high != 0 ? e + 33 : e + 1; - }), - ($.isZero = function () { - return this.high === 0 && this.low === 0; - }), - ($.eqz = $.isZero), - ($.isNegative = function () { - return !this.unsigned && this.high < 0; - }), - ($.isPositive = function () { - return this.unsigned || this.high >= 0; - }), - ($.isOdd = function () { - return (this.low & 1) === 1; - }), - ($.isEven = function () { - return (this.low & 1) === 0; - }), - ($.equals = function (t) { - return ( - We(t) || (t = _t(t)), - this.unsigned !== t.unsigned && this.high >>> 31 === 1 && t.high >>> 31 === 1 - ? !1 - : this.high === t.high && this.low === t.low - ); - }), - ($.eq = $.equals), - ($.notEquals = function (t) { - return !this.eq(t); - }), - ($.neq = $.notEquals), - ($.ne = $.notEquals), - ($.lessThan = function (t) { - return this.comp(t) < 0; - }), - ($.lt = $.lessThan), - ($.lessThanOrEqual = function (t) { - return this.comp(t) <= 0; - }), - ($.lte = $.lessThanOrEqual), - ($.le = $.lessThanOrEqual), - ($.greaterThan = function (t) { - return this.comp(t) > 0; - }), - ($.gt = $.greaterThan), - ($.greaterThanOrEqual = function (t) { - return this.comp(t) >= 0; - }), - ($.gte = $.greaterThanOrEqual), - ($.ge = $.greaterThanOrEqual), - ($.compare = function (t) { - if ((We(t) || (t = _t(t)), this.eq(t))) return 0; - var e = this.isNegative(), - o = t.isNegative(); - return e && !o - ? -1 - : !e && o - ? 1 - : this.unsigned - ? t.high >>> 0 > this.high >>> 0 || (t.high === this.high && t.low >>> 0 > this.low >>> 0) - ? -1 - : 1 - : this.sub(t).isNegative() - ? -1 - : 1; - }), - ($.comp = $.compare), - ($.negate = function () { - return !this.unsigned && this.eq(tt) ? tt : this.not().add(Dr); - }), - ($.neg = $.negate), - ($.add = function (t) { - We(t) || (t = _t(t)); - var e = this.high >>> 16, - o = this.high & 65535, - i = this.low >>> 16, - u = this.low & 65535, - n = t.high >>> 16, - s = t.high & 65535, - d = t.low >>> 16, - f = t.low & 65535, - r = 0, - a = 0, - l = 0, - p = 0; - return ( - (p += u + f), - (l += p >>> 16), - (p &= 65535), - (l += i + d), - (a += l >>> 16), - (l &= 65535), - (a += o + s), - (r += a >>> 16), - (a &= 65535), - (r += e + n), - (r &= 65535), - le((l << 16) | p, (r << 16) | a, this.unsigned) - ); - }), - ($.subtract = function (t) { - return We(t) || (t = _t(t)), this.add(t.neg()); - }), - ($.sub = $.subtract), - ($.multiply = function (t) { - if (this.isZero()) return this; - if ((We(t) || (t = _t(t)), lt)) { - var e = lt.mul(this.low, this.high, t.low, t.high); - return le(e, lt.get_high(), this.unsigned); - } - if (t.isZero()) return this.unsigned ? Ut : wt; - if (this.eq(tt)) return t.isOdd() ? tt : wt; - if (t.eq(tt)) return this.isOdd() ? tt : wt; - if (this.isNegative()) return t.isNegative() ? this.neg().mul(t.neg()) : this.neg().mul(t).neg(); - if (t.isNegative()) return this.mul(t.neg()).neg(); - if (this.lt(Es) && t.lt(Es)) return ft(this.toNumber() * t.toNumber(), this.unsigned); - var o = this.high >>> 16, - i = this.high & 65535, - u = this.low >>> 16, - n = this.low & 65535, - s = t.high >>> 16, - d = t.high & 65535, - f = t.low >>> 16, - r = t.low & 65535, - a = 0, - l = 0, - p = 0, - m = 0; - return ( - (m += n * r), - (p += m >>> 16), - (m &= 65535), - (p += u * r), - (l += p >>> 16), - (p &= 65535), - (p += n * f), - (l += p >>> 16), - (p &= 65535), - (l += i * r), - (a += l >>> 16), - (l &= 65535), - (l += u * f), - (a += l >>> 16), - (l &= 65535), - (l += n * d), - (a += l >>> 16), - (l &= 65535), - (a += o * r + i * f + u * d + n * s), - (a &= 65535), - le((p << 16) | m, (a << 16) | l, this.unsigned) - ); - }), - ($.mul = $.multiply), - ($.divide = function (t) { - if ((We(t) || (t = _t(t)), t.isZero())) throw Error('division by zero'); - if (lt) { - if (!this.unsigned && this.high === -2147483648 && t.low === -1 && t.high === -1) return this; - var e = (this.unsigned ? lt.div_u : lt.div_s)(this.low, this.high, t.low, t.high); - return le(e, lt.get_high(), this.unsigned); - } - if (this.isZero()) return this.unsigned ? Ut : wt; - var o, i, u; - if (this.unsigned) { - if ((t.unsigned || (t = t.toUnsigned()), t.gt(this))) return Ut; - if (t.gt(this.shru(1))) return Ls; - u = Ut; - } else { - if (this.eq(tt)) { - if (t.eq(Dr) || t.eq(Zo)) return tt; - if (t.eq(tt)) return Dr; - var n = this.shr(1); - return ( - (o = n.div(t).shl(1)), - o.eq(wt) ? (t.isNegative() ? Dr : Zo) : ((i = this.sub(t.mul(o))), (u = o.add(i.div(t))), u) - ); - } else if (t.eq(tt)) return this.unsigned ? Ut : wt; - if (this.isNegative()) return t.isNegative() ? this.neg().div(t.neg()) : this.neg().div(t).neg(); - if (t.isNegative()) return this.div(t.neg()).neg(); - u = wt; - } - for (i = this; i.gte(t); ) { - o = Math.max(1, Math.floor(i.toNumber() / t.toNumber())); - for ( - var s = Math.ceil(Math.log(o) / Math.LN2), - d = s <= 48 ? 1 : Vn(2, s - 48), - f = ft(o), - r = f.mul(t); - r.isNegative() || r.gt(i); - - ) - (o -= d), (f = ft(o, this.unsigned)), (r = f.mul(t)); - f.isZero() && (f = Dr), (u = u.add(f)), (i = i.sub(r)); - } - return u; - }), - ($.div = $.divide), - ($.modulo = function (t) { - if ((We(t) || (t = _t(t)), lt)) { - var e = (this.unsigned ? lt.rem_u : lt.rem_s)(this.low, this.high, t.low, t.high); - return le(e, lt.get_high(), this.unsigned); - } - return this.sub(this.div(t).mul(t)); - }), - ($.mod = $.modulo), - ($.rem = $.modulo), - ($.not = function () { - return le(~this.low, ~this.high, this.unsigned); - }), - ($.countLeadingZeros = function () { - return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; - }), - ($.clz = $.countLeadingZeros), - ($.countTrailingZeros = function () { - return this.low ? Os(this.low) : Os(this.high) + 32; - }), - ($.ctz = $.countTrailingZeros), - ($.and = function (t) { - return We(t) || (t = _t(t)), le(this.low & t.low, this.high & t.high, this.unsigned); - }), - ($.or = function (t) { - return We(t) || (t = _t(t)), le(this.low | t.low, this.high | t.high, this.unsigned); - }), - ($.xor = function (t) { - return We(t) || (t = _t(t)), le(this.low ^ t.low, this.high ^ t.high, this.unsigned); - }), - ($.shiftLeft = function (t) { - return ( - We(t) && (t = t.toInt()), - (t &= 63) === 0 - ? this - : t < 32 - ? le(this.low << t, (this.high << t) | (this.low >>> (32 - t)), this.unsigned) - : le(0, this.low << (t - 32), this.unsigned) - ); - }), - ($.shl = $.shiftLeft), - ($.shiftRight = function (t) { - return ( - We(t) && (t = t.toInt()), - (t &= 63) === 0 - ? this - : t < 32 - ? le((this.low >>> t) | (this.high << (32 - t)), this.high >> t, this.unsigned) - : le(this.high >> (t - 32), this.high >= 0 ? 0 : -1, this.unsigned) - ); - }), - ($.shr = $.shiftRight), - ($.shiftRightUnsigned = function (t) { - return ( - We(t) && (t = t.toInt()), - (t &= 63) === 0 - ? this - : t < 32 - ? le((this.low >>> t) | (this.high << (32 - t)), this.high >>> t, this.unsigned) - : t === 32 - ? le(this.high, 0, this.unsigned) - : le(this.high >>> (t - 32), 0, this.unsigned) - ); - }), - ($.shru = $.shiftRightUnsigned), - ($.shr_u = $.shiftRightUnsigned), - ($.rotateLeft = function (t) { - var e; - return ( - We(t) && (t = t.toInt()), - (t &= 63) === 0 - ? this - : t === 32 - ? le(this.high, this.low, this.unsigned) - : t < 32 - ? ((e = 32 - t), - le((this.low << t) | (this.high >>> e), (this.high << t) | (this.low >>> e), this.unsigned)) - : ((t -= 32), - (e = 32 - t), - le((this.high << t) | (this.low >>> e), (this.low << t) | (this.high >>> e), this.unsigned)) - ); - }), - ($.rotl = $.rotateLeft), - ($.rotateRight = function (t) { - var e; - return ( - We(t) && (t = t.toInt()), - (t &= 63) === 0 - ? this - : t === 32 - ? le(this.high, this.low, this.unsigned) - : t < 32 - ? ((e = 32 - t), - le((this.high << e) | (this.low >>> t), (this.low << e) | (this.high >>> t), this.unsigned)) - : ((t -= 32), - (e = 32 - t), - le((this.low << e) | (this.high >>> t), (this.high << e) | (this.low >>> t), this.unsigned)) - ); - }), - ($.rotr = $.rotateRight), - ($.toSigned = function () { - return this.unsigned ? le(this.low, this.high, !1) : this; - }), - ($.toUnsigned = function () { - return this.unsigned ? this : le(this.low, this.high, !0); - }), - ($.toBytes = function (t) { - return t ? this.toBytesLE() : this.toBytesBE(); - }), - ($.toBytesLE = function () { - var t = this.high, - e = this.low; - return [ - e & 255, - (e >>> 8) & 255, - (e >>> 16) & 255, - e >>> 24, - t & 255, - (t >>> 8) & 255, - (t >>> 16) & 255, - t >>> 24, - ]; - }), - ($.toBytesBE = function () { - var t = this.high, - e = this.low; - return [ - t >>> 24, - (t >>> 16) & 255, - (t >>> 8) & 255, - t & 255, - e >>> 24, - (e >>> 16) & 255, - (e >>> 8) & 255, - e & 255, - ]; - }), - (be.fromBytes = function (t, e, o) { - return o ? be.fromBytesLE(t, e) : be.fromBytesBE(t, e); - }), - (be.fromBytesLE = function (t, e) { - return new be( - t[0] | (t[1] << 8) | (t[2] << 16) | (t[3] << 24), - t[4] | (t[5] << 8) | (t[6] << 16) | (t[7] << 24), - e - ); - }), - (be.fromBytesBE = function (t, e) { - return new be( - (t[4] << 24) | (t[5] << 16) | (t[6] << 8) | t[7], - (t[0] << 24) | (t[1] << 16) | (t[2] << 8) | t[3], - e - ); - }), - (zt = be); - }), - _, - Wn = L(() => { - (_ = {}), - _.Offset, - _.Table, - (_.SIZEOF_SHORT = 2), - (_.SIZEOF_INT = 4), - (_.FILE_IDENTIFIER_LENGTH = 4), - (_.SIZE_PREFIX_LENGTH = 4), - (_.Encoding = { UTF8_BYTES: 1, UTF16_STRING: 2 }), - (_.int32 = new Int32Array(2)), - (_.float32 = new Float32Array(_.int32.buffer)), - (_.float64 = new Float64Array(_.int32.buffer)), - (_.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1), - (_.Long = function (t, e) { - (this.low = t | 0), (this.high = e | 0); - }), - (_.Long.create = function (t, e) { - return t == 0 && e == 0 ? _.Long.ZERO : new _.Long(t, e); - }), - (_.Long.prototype.toFloat64 = function () { - return (this.low >>> 0) + this.high * 4294967296; - }), - (_.Long.prototype.equals = function (t) { - return this.low == t.low && this.high == t.high; - }), - (_.Long.ZERO = new _.Long(0, 0)), - (_.Builder = function (t) { - if (t) var e = t; - else var e = 1024; - (this.bb = _.ByteBuffer.allocate(e)), - (this.space = e), - (this.minalign = 1), - (this.vtable = null), - (this.vtable_in_use = 0), - (this.isNested = !1), - (this.object_start = 0), - (this.vtables = []), - (this.vector_num_elems = 0), - (this.force_defaults = !1); - }), - (_.Builder.prototype.clear = function () { - this.bb.clear(), - (this.space = this.bb.capacity()), - (this.minalign = 1), - (this.vtable = null), - (this.vtable_in_use = 0), - (this.isNested = !1), - (this.object_start = 0), - (this.vtables = []), - (this.vector_num_elems = 0), - (this.force_defaults = !1); - }), - (_.Builder.prototype.forceDefaults = function (t) { - this.force_defaults = t; - }), - (_.Builder.prototype.dataBuffer = function () { - return this.bb; - }), - (_.Builder.prototype.asUint8Array = function () { - return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset()); - }), - (_.Builder.prototype.prep = function (t, e) { - t > this.minalign && (this.minalign = t); - for (var o = (~(this.bb.capacity() - this.space + e) + 1) & (t - 1); this.space < o + t + e; ) { - var i = this.bb.capacity(); - (this.bb = _.Builder.growByteBuffer(this.bb)), (this.space += this.bb.capacity() - i); - } - this.pad(o); - }), - (_.Builder.prototype.pad = function (t) { - for (var e = 0; e < t; e++) this.bb.writeInt8(--this.space, 0); - }), - (_.Builder.prototype.writeInt8 = function (t) { - this.bb.writeInt8((this.space -= 1), t); - }), - (_.Builder.prototype.writeInt16 = function (t) { - this.bb.writeInt16((this.space -= 2), t); - }), - (_.Builder.prototype.writeInt32 = function (t) { - this.bb.writeInt32((this.space -= 4), t); - }), - (_.Builder.prototype.writeInt64 = function (t) { - this.bb.writeInt64((this.space -= 8), t); - }), - (_.Builder.prototype.writeFloat32 = function (t) { - this.bb.writeFloat32((this.space -= 4), t); - }), - (_.Builder.prototype.writeFloat64 = function (t) { - this.bb.writeFloat64((this.space -= 8), t); - }), - (_.Builder.prototype.addInt8 = function (t) { - this.prep(1, 0), this.writeInt8(t); - }), - (_.Builder.prototype.addInt16 = function (t) { - this.prep(2, 0), this.writeInt16(t); - }), - (_.Builder.prototype.addInt32 = function (t) { - this.prep(4, 0), this.writeInt32(t); - }), - (_.Builder.prototype.addInt64 = function (t) { - this.prep(8, 0), this.writeInt64(t); - }), - (_.Builder.prototype.addFloat32 = function (t) { - this.prep(4, 0), this.writeFloat32(t); - }), - (_.Builder.prototype.addFloat64 = function (t) { - this.prep(8, 0), this.writeFloat64(t); - }), - (_.Builder.prototype.addFieldInt8 = function (t, e, o) { - (this.force_defaults || e != o) && (this.addInt8(e), this.slot(t)); - }), - (_.Builder.prototype.addFieldInt16 = function (t, e, o) { - (this.force_defaults || e != o) && (this.addInt16(e), this.slot(t)); - }), - (_.Builder.prototype.addFieldInt32 = function (t, e, o) { - (this.force_defaults || e != o) && (this.addInt32(e), this.slot(t)); - }), - (_.Builder.prototype.addFieldInt64 = function (t, e, o) { - (this.force_defaults || !e.equals(o)) && (this.addInt64(e), this.slot(t)); - }), - (_.Builder.prototype.addFieldFloat32 = function (t, e, o) { - (this.force_defaults || e != o) && (this.addFloat32(e), this.slot(t)); - }), - (_.Builder.prototype.addFieldFloat64 = function (t, e, o) { - (this.force_defaults || e != o) && (this.addFloat64(e), this.slot(t)); - }), - (_.Builder.prototype.addFieldOffset = function (t, e, o) { - (this.force_defaults || e != o) && (this.addOffset(e), this.slot(t)); - }), - (_.Builder.prototype.addFieldStruct = function (t, e, o) { - e != o && (this.nested(e), this.slot(t)); - }), - (_.Builder.prototype.nested = function (t) { - if (t != this.offset()) throw new Error('FlatBuffers: struct must be serialized inline.'); - }), - (_.Builder.prototype.notNested = function () { - if (this.isNested) throw new Error('FlatBuffers: object serialization must not be nested.'); - }), - (_.Builder.prototype.slot = function (t) { - this.vtable[t] = this.offset(); - }), - (_.Builder.prototype.offset = function () { - return this.bb.capacity() - this.space; - }), - (_.Builder.growByteBuffer = function (t) { - var e = t.capacity(); - if (e & 3221225472) throw new Error('FlatBuffers: cannot grow buffer beyond 2 gigabytes.'); - var o = e << 1, - i = _.ByteBuffer.allocate(o); - return i.setPosition(o - e), i.bytes().set(t.bytes(), o - e), i; - }), - (_.Builder.prototype.addOffset = function (t) { - this.prep(_.SIZEOF_INT, 0), this.writeInt32(this.offset() - t + _.SIZEOF_INT); - }), - (_.Builder.prototype.startObject = function (t) { - this.notNested(), this.vtable == null && (this.vtable = []), (this.vtable_in_use = t); - for (var e = 0; e < t; e++) this.vtable[e] = 0; - (this.isNested = !0), (this.object_start = this.offset()); - }), - (_.Builder.prototype.endObject = function () { - if (this.vtable == null || !this.isNested) - throw new Error('FlatBuffers: endObject called without startObject'); - this.addInt32(0); - for (var t = this.offset(), e = this.vtable_in_use - 1; e >= 0 && this.vtable[e] == 0; e--); - for (var o = e + 1; e >= 0; e--) this.addInt16(this.vtable[e] != 0 ? t - this.vtable[e] : 0); - var i = 2; - this.addInt16(t - this.object_start); - var u = (o + i) * _.SIZEOF_SHORT; - this.addInt16(u); - var n = 0, - s = this.space; - e: for (e = 0; e < this.vtables.length; e++) { - var d = this.bb.capacity() - this.vtables[e]; - if (u == this.bb.readInt16(d)) { - for (var f = _.SIZEOF_SHORT; f < u; f += _.SIZEOF_SHORT) - if (this.bb.readInt16(s + f) != this.bb.readInt16(d + f)) continue e; - n = this.vtables[e]; - break; - } - } - return ( - n - ? ((this.space = this.bb.capacity() - t), this.bb.writeInt32(this.space, n - t)) - : (this.vtables.push(this.offset()), - this.bb.writeInt32(this.bb.capacity() - t, this.offset() - t)), - (this.isNested = !1), - t - ); - }), - (_.Builder.prototype.finish = function (t, e, o) { - var i = o ? _.SIZE_PREFIX_LENGTH : 0; - if (e) { - var u = e; - if ( - (this.prep(this.minalign, _.SIZEOF_INT + _.FILE_IDENTIFIER_LENGTH + i), - u.length != _.FILE_IDENTIFIER_LENGTH) - ) - throw new Error('FlatBuffers: file identifier must be length ' + _.FILE_IDENTIFIER_LENGTH); - for (var n = _.FILE_IDENTIFIER_LENGTH - 1; n >= 0; n--) this.writeInt8(u.charCodeAt(n)); - } - this.prep(this.minalign, _.SIZEOF_INT + i), - this.addOffset(t), - i && this.addInt32(this.bb.capacity() - this.space), - this.bb.setPosition(this.space); - }), - (_.Builder.prototype.finishSizePrefixed = function (t, e) { - this.finish(t, e, !0); - }), - (_.Builder.prototype.requiredField = function (t, e) { - var o = this.bb.capacity() - t, - i = o - this.bb.readInt32(o), - u = this.bb.readInt16(i + e) != 0; - if (!u) throw new Error('FlatBuffers: field ' + e + ' must be set'); - }), - (_.Builder.prototype.startVector = function (t, e, o) { - this.notNested(), (this.vector_num_elems = e), this.prep(_.SIZEOF_INT, t * e), this.prep(o, t * e); - }), - (_.Builder.prototype.endVector = function () { - return this.writeInt32(this.vector_num_elems), this.offset(); - }), - (_.Builder.prototype.createString = function (t) { - if (t instanceof Uint8Array) var e = t; - else - for (var e = [], o = 0; o < t.length; ) { - var i, - u = t.charCodeAt(o++); - if (u < 55296 || u >= 56320) i = u; - else { - var n = t.charCodeAt(o++); - i = (u << 10) + n + -56613888; - } - i < 128 - ? e.push(i) - : (i < 2048 - ? e.push(((i >> 6) & 31) | 192) - : (i < 65536 - ? e.push(((i >> 12) & 15) | 224) - : e.push(((i >> 18) & 7) | 240, ((i >> 12) & 63) | 128), - e.push(((i >> 6) & 63) | 128)), - e.push((i & 63) | 128)); - } - this.addInt8(0), this.startVector(1, e.length, 1), this.bb.setPosition((this.space -= e.length)); - for (var o = 0, s = this.space, d = this.bb.bytes(); o < e.length; o++) d[s++] = e[o]; - return this.endVector(); - }), - (_.Builder.prototype.createLong = function (t, e) { - return _.Long.create(t, e); - }), - (_.ByteBuffer = function (t) { - (this.bytes_ = t), (this.position_ = 0); - }), - (_.ByteBuffer.allocate = function (t) { - return new _.ByteBuffer(new Uint8Array(t)); - }), - (_.ByteBuffer.prototype.clear = function () { - this.position_ = 0; - }), - (_.ByteBuffer.prototype.bytes = function () { - return this.bytes_; - }), - (_.ByteBuffer.prototype.position = function () { - return this.position_; - }), - (_.ByteBuffer.prototype.setPosition = function (t) { - this.position_ = t; - }), - (_.ByteBuffer.prototype.capacity = function () { - return this.bytes_.length; - }), - (_.ByteBuffer.prototype.readInt8 = function (t) { - return (this.readUint8(t) << 24) >> 24; - }), - (_.ByteBuffer.prototype.readUint8 = function (t) { - return this.bytes_[t]; - }), - (_.ByteBuffer.prototype.readInt16 = function (t) { - return (this.readUint16(t) << 16) >> 16; - }), - (_.ByteBuffer.prototype.readUint16 = function (t) { - return this.bytes_[t] | (this.bytes_[t + 1] << 8); - }), - (_.ByteBuffer.prototype.readInt32 = function (t) { - return ( - this.bytes_[t] | (this.bytes_[t + 1] << 8) | (this.bytes_[t + 2] << 16) | (this.bytes_[t + 3] << 24) - ); - }), - (_.ByteBuffer.prototype.readUint32 = function (t) { - return this.readInt32(t) >>> 0; - }), - (_.ByteBuffer.prototype.readInt64 = function (t) { - return new _.Long(this.readInt32(t), this.readInt32(t + 4)); - }), - (_.ByteBuffer.prototype.readUint64 = function (t) { - return new _.Long(this.readUint32(t), this.readUint32(t + 4)); - }), - (_.ByteBuffer.prototype.readFloat32 = function (t) { - return (_.int32[0] = this.readInt32(t)), _.float32[0]; - }), - (_.ByteBuffer.prototype.readFloat64 = function (t) { - return ( - (_.int32[_.isLittleEndian ? 0 : 1] = this.readInt32(t)), - (_.int32[_.isLittleEndian ? 1 : 0] = this.readInt32(t + 4)), - _.float64[0] - ); - }), - (_.ByteBuffer.prototype.writeInt8 = function (t, e) { - this.bytes_[t] = e; - }), - (_.ByteBuffer.prototype.writeUint8 = function (t, e) { - this.bytes_[t] = e; - }), - (_.ByteBuffer.prototype.writeInt16 = function (t, e) { - (this.bytes_[t] = e), (this.bytes_[t + 1] = e >> 8); - }), - (_.ByteBuffer.prototype.writeUint16 = function (t, e) { - (this.bytes_[t] = e), (this.bytes_[t + 1] = e >> 8); - }), - (_.ByteBuffer.prototype.writeInt32 = function (t, e) { - (this.bytes_[t] = e), - (this.bytes_[t + 1] = e >> 8), - (this.bytes_[t + 2] = e >> 16), - (this.bytes_[t + 3] = e >> 24); - }), - (_.ByteBuffer.prototype.writeUint32 = function (t, e) { - (this.bytes_[t] = e), - (this.bytes_[t + 1] = e >> 8), - (this.bytes_[t + 2] = e >> 16), - (this.bytes_[t + 3] = e >> 24); - }), - (_.ByteBuffer.prototype.writeInt64 = function (t, e) { - this.writeInt32(t, e.low), this.writeInt32(t + 4, e.high); - }), - (_.ByteBuffer.prototype.writeUint64 = function (t, e) { - this.writeUint32(t, e.low), this.writeUint32(t + 4, e.high); - }), - (_.ByteBuffer.prototype.writeFloat32 = function (t, e) { - (_.float32[0] = e), this.writeInt32(t, _.int32[0]); - }), - (_.ByteBuffer.prototype.writeFloat64 = function (t, e) { - (_.float64[0] = e), - this.writeInt32(t, _.int32[_.isLittleEndian ? 0 : 1]), - this.writeInt32(t + 4, _.int32[_.isLittleEndian ? 1 : 0]); - }), - (_.ByteBuffer.prototype.getBufferIdentifier = function () { - if (this.bytes_.length < this.position_ + _.SIZEOF_INT + _.FILE_IDENTIFIER_LENGTH) - throw new Error('FlatBuffers: ByteBuffer is too short to contain an identifier.'); - for (var t = '', e = 0; e < _.FILE_IDENTIFIER_LENGTH; e++) - t += String.fromCharCode(this.readInt8(this.position_ + _.SIZEOF_INT + e)); - return t; - }), - (_.ByteBuffer.prototype.__offset = function (t, e) { - var o = t - this.readInt32(t); - return e < this.readInt16(o) ? this.readInt16(o + e) : 0; - }), - (_.ByteBuffer.prototype.__union = function (t, e) { - return (t.bb_pos = e + this.readInt32(e)), (t.bb = this), t; - }), - (_.ByteBuffer.prototype.__string = function (t, e) { - t += this.readInt32(t); - var o = this.readInt32(t), - i = '', - u = 0; - if (((t += _.SIZEOF_INT), e === _.Encoding.UTF8_BYTES)) return this.bytes_.subarray(t, t + o); - for (; u < o; ) { - var n, - s = this.readUint8(t + u++); - if (s < 192) n = s; - else { - var d = this.readUint8(t + u++); - if (s < 224) n = ((s & 31) << 6) | (d & 63); - else { - var f = this.readUint8(t + u++); - if (s < 240) n = ((s & 15) << 12) | ((d & 63) << 6) | (f & 63); - else { - var r = this.readUint8(t + u++); - n = ((s & 7) << 18) | ((d & 63) << 12) | ((f & 63) << 6) | (r & 63); - } - } - } - n < 65536 - ? (i += String.fromCharCode(n)) - : ((n -= 65536), (i += String.fromCharCode((n >> 10) + 55296, (n & 1023) + 56320))); - } - return i; - }), - (_.ByteBuffer.prototype.__indirect = function (t) { - return t + this.readInt32(t); - }), - (_.ByteBuffer.prototype.__vector = function (t) { - return t + this.readInt32(t) + _.SIZEOF_INT; - }), - (_.ByteBuffer.prototype.__vector_len = function (t) { - return this.readInt32(t + this.readInt32(t)); - }), - (_.ByteBuffer.prototype.__has_identifier = function (t) { - if (t.length != _.FILE_IDENTIFIER_LENGTH) - throw new Error('FlatBuffers: file identifier must be length ' + _.FILE_IDENTIFIER_LENGTH); - for (var e = 0; e < _.FILE_IDENTIFIER_LENGTH; e++) - if (t.charCodeAt(e) != this.readInt8(this.position_ + _.SIZEOF_INT + e)) return !1; - return !0; - }), - (_.ByteBuffer.prototype.createLong = function (t, e) { - return _.Long.create(t, e); - }); - }), - W, - tn = L(() => { - Wn(), - ((t) => { - ((e) => { - ((o) => { - ((i) => ( - (i[(i.UNDEFINED = 0)] = 'UNDEFINED'), - (i[(i.FLOAT = 1)] = 'FLOAT'), - (i[(i.INT = 2)] = 'INT'), - (i[(i.STRING = 3)] = 'STRING'), - (i[(i.TENSOR = 4)] = 'TENSOR'), - (i[(i.GRAPH = 5)] = 'GRAPH'), - (i[(i.FLOATS = 6)] = 'FLOATS'), - (i[(i.INTS = 7)] = 'INTS'), - (i[(i.STRINGS = 8)] = 'STRINGS'), - (i[(i.TENSORS = 9)] = 'TENSORS'), - (i[(i.GRAPHS = 10)] = 'GRAPHS'), - (i[(i.SPARSE_TENSOR = 11)] = 'SPARSE_TENSOR'), - (i[(i.SPARSE_TENSORS = 12)] = 'SPARSE_TENSORS') - ))((o.AttributeType ||= {})); - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - ((i) => ( - (i[(i.UNKNOWN = 0)] = 'UNKNOWN'), (i[(i.VALUE = 1)] = 'VALUE'), (i[(i.PARAM = 2)] = 'PARAM') - ))((o.DimensionValueType ||= {})); - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - ((i) => ( - (i[(i.UNDEFINED = 0)] = 'UNDEFINED'), - (i[(i.FLOAT = 1)] = 'FLOAT'), - (i[(i.UINT8 = 2)] = 'UINT8'), - (i[(i.INT8 = 3)] = 'INT8'), - (i[(i.UINT16 = 4)] = 'UINT16'), - (i[(i.INT16 = 5)] = 'INT16'), - (i[(i.INT32 = 6)] = 'INT32'), - (i[(i.INT64 = 7)] = 'INT64'), - (i[(i.STRING = 8)] = 'STRING'), - (i[(i.BOOL = 9)] = 'BOOL'), - (i[(i.FLOAT16 = 10)] = 'FLOAT16'), - (i[(i.DOUBLE = 11)] = 'DOUBLE'), - (i[(i.UINT32 = 12)] = 'UINT32'), - (i[(i.UINT64 = 13)] = 'UINT64'), - (i[(i.COMPLEX64 = 14)] = 'COMPLEX64'), - (i[(i.COMPLEX128 = 15)] = 'COMPLEX128'), - (i[(i.BFLOAT16 = 16)] = 'BFLOAT16'), - (i[(i.FLOAT8E4M3FN = 17)] = 'FLOAT8E4M3FN'), - (i[(i.FLOAT8E4M3FNUZ = 18)] = 'FLOAT8E4M3FNUZ'), - (i[(i.FLOAT8E5M2 = 19)] = 'FLOAT8E5M2'), - (i[(i.FLOAT8E5M2FNUZ = 20)] = 'FLOAT8E5M2FNUZ') - ))((o.TensorDataType ||= {})); - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - ((i) => ((i[(i.Primitive = 0)] = 'Primitive'), (i[(i.Fused = 1)] = 'Fused')))( - (o.NodeType ||= {}) - ); - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - ((i) => ( - (i[(i.NONE = 0)] = 'NONE'), - (i[(i.tensor_type = 1)] = 'tensor_type'), - (i[(i.sequence_type = 2)] = 'sequence_type'), - (i[(i.map_type = 3)] = 'map_type') - ))((o.TypeInfoValue ||= {})); - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsShape(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsShape(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - dim(n, s) { - let d = this.bb.__offset(this.bb_pos, 4); - return d - ? (s || new t.experimental.fbs.Dimension()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - dimLength() { - let n = this.bb.__offset(this.bb_pos, 4); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - static startShape(n) { - n.startObject(1); - } - static addDim(n, s) { - n.addFieldOffset(0, s, 0); - } - static createDimVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startDimVector(n, s) { - n.startVector(4, s, 4); - } - static endShape(n) { - return n.endObject(); - } - static createShape(n, s) { - return i.startShape(n), i.addDim(n, s), i.endShape(n); - } - } - o.Shape = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsDimension(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsDimension(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - value(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s - ? (n || new t.experimental.fbs.DimensionValue()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - denotation(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - static startDimension(n) { - n.startObject(2); - } - static addValue(n, s) { - n.addFieldOffset(0, s, 0); - } - static addDenotation(n, s) { - n.addFieldOffset(1, s, 0); - } - static endDimension(n) { - return n.endObject(); - } - static createDimension(n, s, d) { - return i.startDimension(n), i.addValue(n, s), i.addDenotation(n, d), i.endDimension(n); - } - } - o.Dimension = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsDimensionValue(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsDimensionValue(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - dimType() { - let n = this.bb.__offset(this.bb_pos, 4); - return n ? this.bb.readInt8(this.bb_pos + n) : 0; - } - dimValue() { - let n = this.bb.__offset(this.bb_pos, 6); - return n ? this.bb.readInt64(this.bb_pos + n) : this.bb.createLong(0, 0); - } - dimParam(n) { - let s = this.bb.__offset(this.bb_pos, 8); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - static startDimensionValue(n) { - n.startObject(3); - } - static addDimType(n, s) { - n.addFieldInt8(0, s, 0); - } - static addDimValue(n, s) { - n.addFieldInt64(1, s, n.createLong(0, 0)); - } - static addDimParam(n, s) { - n.addFieldOffset(2, s, 0); - } - static endDimensionValue(n) { - return n.endObject(); - } - static createDimensionValue(n, s, d, f) { - return ( - i.startDimensionValue(n), - i.addDimType(n, s), - i.addDimValue(n, d), - i.addDimParam(n, f), - i.endDimensionValue(n) - ); - } - } - o.DimensionValue = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsTensorTypeAndShape(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsTensorTypeAndShape(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - elemType() { - let n = this.bb.__offset(this.bb_pos, 4); - return n ? this.bb.readInt32(this.bb_pos + n) : 0; - } - shape(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s - ? (n || new t.experimental.fbs.Shape()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - static startTensorTypeAndShape(n) { - n.startObject(2); - } - static addElemType(n, s) { - n.addFieldInt32(0, s, 0); - } - static addShape(n, s) { - n.addFieldOffset(1, s, 0); - } - static endTensorTypeAndShape(n) { - return n.endObject(); - } - static createTensorTypeAndShape(n, s, d) { - return ( - i.startTensorTypeAndShape(n), - i.addElemType(n, s), - i.addShape(n, d), - i.endTensorTypeAndShape(n) - ); - } - } - o.TensorTypeAndShape = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsMapType(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsMapType(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - keyType() { - let n = this.bb.__offset(this.bb_pos, 4); - return n ? this.bb.readInt32(this.bb_pos + n) : 0; - } - valueType(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s - ? (n || new t.experimental.fbs.TypeInfo()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - static startMapType(n) { - n.startObject(2); - } - static addKeyType(n, s) { - n.addFieldInt32(0, s, 0); - } - static addValueType(n, s) { - n.addFieldOffset(1, s, 0); - } - static endMapType(n) { - return n.endObject(); - } - static createMapType(n, s, d) { - return i.startMapType(n), i.addKeyType(n, s), i.addValueType(n, d), i.endMapType(n); - } - } - o.MapType = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsSequenceType(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsSequenceType(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - elemType(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s - ? (n || new t.experimental.fbs.TypeInfo()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - static startSequenceType(n) { - n.startObject(1); - } - static addElemType(n, s) { - n.addFieldOffset(0, s, 0); - } - static endSequenceType(n) { - return n.endObject(); - } - static createSequenceType(n, s) { - return i.startSequenceType(n), i.addElemType(n, s), i.endSequenceType(n); - } - } - o.SequenceType = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), 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(n, s, d, f) { - return n.prep(4, 12), n.writeInt32(f), n.writeInt32(d), n.writeInt32(s), n.offset(); - } - } - o.EdgeEnd = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsNodeEdge(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsNodeEdge(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - nodeIndex() { - let n = this.bb.__offset(this.bb_pos, 4); - return n ? this.bb.readUint32(this.bb_pos + n) : 0; - } - inputEdges(n, s) { - let d = this.bb.__offset(this.bb_pos, 6); - return d - ? (s || new t.experimental.fbs.EdgeEnd()).__init( - this.bb.__vector(this.bb_pos + d) + n * 12, - this.bb - ) - : null; - } - inputEdgesLength() { - let n = this.bb.__offset(this.bb_pos, 6); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - outputEdges(n, s) { - let d = this.bb.__offset(this.bb_pos, 8); - return d - ? (s || new t.experimental.fbs.EdgeEnd()).__init( - this.bb.__vector(this.bb_pos + d) + n * 12, - this.bb - ) - : null; - } - outputEdgesLength() { - let n = this.bb.__offset(this.bb_pos, 8); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - static startNodeEdge(n) { - n.startObject(3); - } - static addNodeIndex(n, s) { - n.addFieldInt32(0, s, 0); - } - static addInputEdges(n, s) { - n.addFieldOffset(1, s, 0); - } - static startInputEdgesVector(n, s) { - n.startVector(12, s, 4); - } - static addOutputEdges(n, s) { - n.addFieldOffset(2, s, 0); - } - static startOutputEdgesVector(n, s) { - n.startVector(12, s, 4); - } - static endNodeEdge(n) { - return n.endObject(); - } - static createNodeEdge(n, s, d, f) { - return ( - i.startNodeEdge(n), - i.addNodeIndex(n, s), - i.addInputEdges(n, d), - i.addOutputEdges(n, f), - i.endNodeEdge(n) - ); - } - } - o.NodeEdge = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsNode(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsNode(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - name(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - docString(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - domain(n) { - let s = this.bb.__offset(this.bb_pos, 8); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - sinceVersion() { - let n = this.bb.__offset(this.bb_pos, 10); - return n ? this.bb.readInt32(this.bb_pos + n) : 0; - } - index() { - let n = this.bb.__offset(this.bb_pos, 12); - return n ? this.bb.readUint32(this.bb_pos + n) : 0; - } - opType(n) { - let s = this.bb.__offset(this.bb_pos, 14); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - type() { - let n = this.bb.__offset(this.bb_pos, 16); - return n ? this.bb.readInt32(this.bb_pos + n) : 0; - } - executionProviderType(n) { - let s = this.bb.__offset(this.bb_pos, 18); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - inputs(n, s) { - let d = this.bb.__offset(this.bb_pos, 20); - return d ? this.bb.__string(this.bb.__vector(this.bb_pos + d) + n * 4, s) : null; - } - inputsLength() { - let n = this.bb.__offset(this.bb_pos, 20); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - outputs(n, s) { - let d = this.bb.__offset(this.bb_pos, 22); - return d ? this.bb.__string(this.bb.__vector(this.bb_pos + d) + n * 4, s) : null; - } - outputsLength() { - let n = this.bb.__offset(this.bb_pos, 22); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - attributes(n, s) { - let d = this.bb.__offset(this.bb_pos, 24); - return d - ? (s || new t.experimental.fbs.Attribute()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - attributesLength() { - let n = this.bb.__offset(this.bb_pos, 24); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - inputArgCounts(n) { - let s = this.bb.__offset(this.bb_pos, 26); - return s ? this.bb.readInt32(this.bb.__vector(this.bb_pos + s) + n * 4) : 0; - } - inputArgCountsLength() { - let n = this.bb.__offset(this.bb_pos, 26); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - inputArgCountsArray() { - let n = this.bb.__offset(this.bb_pos, 26); - return n - ? new Int32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + n), - this.bb.__vector_len(this.bb_pos + n) - ) - : null; - } - implicitInputs(n, s) { - let d = this.bb.__offset(this.bb_pos, 28); - return d ? this.bb.__string(this.bb.__vector(this.bb_pos + d) + n * 4, s) : null; - } - implicitInputsLength() { - let n = this.bb.__offset(this.bb_pos, 28); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - static startNode(n) { - n.startObject(13); - } - static addName(n, s) { - n.addFieldOffset(0, s, 0); - } - static addDocString(n, s) { - n.addFieldOffset(1, s, 0); - } - static addDomain(n, s) { - n.addFieldOffset(2, s, 0); - } - static addSinceVersion(n, s) { - n.addFieldInt32(3, s, 0); - } - static addIndex(n, s) { - n.addFieldInt32(4, s, 0); - } - static addOpType(n, s) { - n.addFieldOffset(5, s, 0); - } - static addType(n, s) { - n.addFieldInt32(6, s, 0); - } - static addExecutionProviderType(n, s) { - n.addFieldOffset(7, s, 0); - } - static addInputs(n, s) { - n.addFieldOffset(8, s, 0); - } - static createInputsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startInputsVector(n, s) { - n.startVector(4, s, 4); - } - static addOutputs(n, s) { - n.addFieldOffset(9, s, 0); - } - static createOutputsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startOutputsVector(n, s) { - n.startVector(4, s, 4); - } - static addAttributes(n, s) { - n.addFieldOffset(10, s, 0); - } - static createAttributesVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startAttributesVector(n, s) { - n.startVector(4, s, 4); - } - static addInputArgCounts(n, s) { - n.addFieldOffset(11, s, 0); - } - static createInputArgCountsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addInt32(s[d]); - return n.endVector(); - } - static startInputArgCountsVector(n, s) { - n.startVector(4, s, 4); - } - static addImplicitInputs(n, s) { - n.addFieldOffset(12, s, 0); - } - static createImplicitInputsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startImplicitInputsVector(n, s) { - n.startVector(4, s, 4); - } - static endNode(n) { - return n.endObject(); - } - static createNode(n, s, d, f, r, a, l, p, m, y, T, v, S, E) { - return ( - i.startNode(n), - i.addName(n, s), - i.addDocString(n, d), - i.addDomain(n, f), - i.addSinceVersion(n, r), - i.addIndex(n, a), - i.addOpType(n, l), - i.addType(n, p), - i.addExecutionProviderType(n, m), - i.addInputs(n, y), - i.addOutputs(n, T), - i.addAttributes(n, v), - i.addInputArgCounts(n, S), - i.addImplicitInputs(n, E), - i.endNode(n) - ); - } - } - o.Node = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsValueInfo(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsValueInfo(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - name(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - docString(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - type(n) { - let s = this.bb.__offset(this.bb_pos, 8); - return s - ? (n || new t.experimental.fbs.TypeInfo()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - static startValueInfo(n) { - n.startObject(3); - } - static addName(n, s) { - n.addFieldOffset(0, s, 0); - } - static addDocString(n, s) { - n.addFieldOffset(1, s, 0); - } - static addType(n, s) { - n.addFieldOffset(2, s, 0); - } - static endValueInfo(n) { - return n.endObject(); - } - static createValueInfo(n, s, d, f) { - return ( - i.startValueInfo(n), - i.addName(n, s), - i.addDocString(n, d), - i.addType(n, f), - i.endValueInfo(n) - ); - } - } - o.ValueInfo = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsTypeInfo(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsTypeInfo(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - denotation(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - valueType() { - let n = this.bb.__offset(this.bb_pos, 6); - return n ? this.bb.readUint8(this.bb_pos + n) : 0; - } - value(n) { - let s = this.bb.__offset(this.bb_pos, 8); - return s ? this.bb.__union(n, this.bb_pos + s) : null; - } - static startTypeInfo(n) { - n.startObject(3); - } - static addDenotation(n, s) { - n.addFieldOffset(0, s, 0); - } - static addValueType(n, s) { - n.addFieldInt8(1, s, 0); - } - static addValue(n, s) { - n.addFieldOffset(2, s, 0); - } - static endTypeInfo(n) { - return n.endObject(); - } - static createTypeInfo(n, s, d, f) { - return ( - i.startTypeInfo(n), - i.addDenotation(n, s), - i.addValueType(n, d), - i.addValue(n, f), - i.endTypeInfo(n) - ); - } - } - o.TypeInfo = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsOperatorSetId(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsOperatorSetId(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - domain(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - version() { - let n = this.bb.__offset(this.bb_pos, 6); - return n ? this.bb.readInt64(this.bb_pos + n) : this.bb.createLong(0, 0); - } - static startOperatorSetId(n) { - n.startObject(2); - } - static addDomain(n, s) { - n.addFieldOffset(0, s, 0); - } - static addVersion(n, s) { - n.addFieldInt64(1, s, n.createLong(0, 0)); - } - static endOperatorSetId(n) { - return n.endObject(); - } - static createOperatorSetId(n, s, d) { - return ( - i.startOperatorSetId(n), - i.addDomain(n, s), - i.addVersion(n, d), - i.endOperatorSetId(n) - ); - } - } - o.OperatorSetId = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsTensor(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsTensor(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - name(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - docString(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - dims(n) { - let s = this.bb.__offset(this.bb_pos, 8); - return s - ? this.bb.readInt64(this.bb.__vector(this.bb_pos + s) + n * 8) - : this.bb.createLong(0, 0); - } - dimsLength() { - let n = this.bb.__offset(this.bb_pos, 8); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - dataType() { - let n = this.bb.__offset(this.bb_pos, 10); - return n ? this.bb.readInt32(this.bb_pos + n) : 0; - } - rawData(n) { - let s = this.bb.__offset(this.bb_pos, 12); - return s ? this.bb.readUint8(this.bb.__vector(this.bb_pos + s) + n) : 0; - } - rawDataLength() { - let n = this.bb.__offset(this.bb_pos, 12); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - rawDataArray() { - let n = this.bb.__offset(this.bb_pos, 12); - return n - ? new Uint8Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + n), - this.bb.__vector_len(this.bb_pos + n) - ) - : null; - } - stringData(n, s) { - let d = this.bb.__offset(this.bb_pos, 14); - return d ? this.bb.__string(this.bb.__vector(this.bb_pos + d) + n * 4, s) : null; - } - stringDataLength() { - let n = this.bb.__offset(this.bb_pos, 14); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - static startTensor(n) { - n.startObject(6); - } - static addName(n, s) { - n.addFieldOffset(0, s, 0); - } - static addDocString(n, s) { - n.addFieldOffset(1, s, 0); - } - static addDims(n, s) { - n.addFieldOffset(2, s, 0); - } - static createDimsVector(n, s) { - n.startVector(8, s.length, 8); - for (let d = s.length - 1; d >= 0; d--) n.addInt64(s[d]); - return n.endVector(); - } - static startDimsVector(n, s) { - n.startVector(8, s, 8); - } - static addDataType(n, s) { - n.addFieldInt32(3, s, 0); - } - static addRawData(n, s) { - n.addFieldOffset(4, s, 0); - } - static createRawDataVector(n, s) { - n.startVector(1, s.length, 1); - for (let d = s.length - 1; d >= 0; d--) n.addInt8(s[d]); - return n.endVector(); - } - static startRawDataVector(n, s) { - n.startVector(1, s, 1); - } - static addStringData(n, s) { - n.addFieldOffset(5, s, 0); - } - static createStringDataVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startStringDataVector(n, s) { - n.startVector(4, s, 4); - } - static endTensor(n) { - return n.endObject(); - } - static createTensor(n, s, d, f, r, a, l) { - return ( - i.startTensor(n), - i.addName(n, s), - i.addDocString(n, d), - i.addDims(n, f), - i.addDataType(n, r), - i.addRawData(n, a), - i.addStringData(n, l), - i.endTensor(n) - ); - } - } - o.Tensor = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsSparseTensor(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsSparseTensor(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - values(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s - ? (n || new t.experimental.fbs.Tensor()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - indices(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s - ? (n || new t.experimental.fbs.Tensor()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - dims(n) { - let s = this.bb.__offset(this.bb_pos, 8); - return s - ? this.bb.readInt64(this.bb.__vector(this.bb_pos + s) + n * 8) - : this.bb.createLong(0, 0); - } - dimsLength() { - let n = this.bb.__offset(this.bb_pos, 8); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - static startSparseTensor(n) { - n.startObject(3); - } - static addValues(n, s) { - n.addFieldOffset(0, s, 0); - } - static addIndices(n, s) { - n.addFieldOffset(1, s, 0); - } - static addDims(n, s) { - n.addFieldOffset(2, s, 0); - } - static createDimsVector(n, s) { - n.startVector(8, s.length, 8); - for (let d = s.length - 1; d >= 0; d--) n.addInt64(s[d]); - return n.endVector(); - } - static startDimsVector(n, s) { - n.startVector(8, s, 8); - } - static endSparseTensor(n) { - return n.endObject(); - } - static createSparseTensor(n, s, d, f) { - return ( - i.startSparseTensor(n), - i.addValues(n, s), - i.addIndices(n, d), - i.addDims(n, f), - i.endSparseTensor(n) - ); - } - } - o.SparseTensor = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsAttribute(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsAttribute(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - name(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - docString(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - type() { - let n = this.bb.__offset(this.bb_pos, 8); - return n ? this.bb.readInt32(this.bb_pos + n) : 0; - } - f() { - let n = this.bb.__offset(this.bb_pos, 10); - return n ? this.bb.readFloat32(this.bb_pos + n) : 0; - } - i() { - let n = this.bb.__offset(this.bb_pos, 12); - return n ? this.bb.readInt64(this.bb_pos + n) : this.bb.createLong(0, 0); - } - s(n) { - let s = this.bb.__offset(this.bb_pos, 14); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - t(n) { - let s = this.bb.__offset(this.bb_pos, 16); - return s - ? (n || new t.experimental.fbs.Tensor()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - g(n) { - let s = this.bb.__offset(this.bb_pos, 18); - return s - ? (n || new t.experimental.fbs.Graph()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - floats(n) { - let s = this.bb.__offset(this.bb_pos, 20); - return s ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + s) + n * 4) : 0; - } - floatsLength() { - let n = this.bb.__offset(this.bb_pos, 20); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - floatsArray() { - let n = this.bb.__offset(this.bb_pos, 20); - return n - ? new Float32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + n), - this.bb.__vector_len(this.bb_pos + n) - ) - : null; - } - ints(n) { - let s = this.bb.__offset(this.bb_pos, 22); - return s - ? this.bb.readInt64(this.bb.__vector(this.bb_pos + s) + n * 8) - : this.bb.createLong(0, 0); - } - intsLength() { - let n = this.bb.__offset(this.bb_pos, 22); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - strings(n, s) { - let d = this.bb.__offset(this.bb_pos, 24); - return d ? this.bb.__string(this.bb.__vector(this.bb_pos + d) + n * 4, s) : null; - } - stringsLength() { - let n = this.bb.__offset(this.bb_pos, 24); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - tensors(n, s) { - let d = this.bb.__offset(this.bb_pos, 26); - return d - ? (s || new t.experimental.fbs.Tensor()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - tensorsLength() { - let n = this.bb.__offset(this.bb_pos, 26); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - graphs(n, s) { - let d = this.bb.__offset(this.bb_pos, 28); - return d - ? (s || new t.experimental.fbs.Graph()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - graphsLength() { - let n = this.bb.__offset(this.bb_pos, 28); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - static startAttribute(n) { - n.startObject(13); - } - static addName(n, s) { - n.addFieldOffset(0, s, 0); - } - static addDocString(n, s) { - n.addFieldOffset(1, s, 0); - } - static addType(n, s) { - n.addFieldInt32(2, s, 0); - } - static addF(n, s) { - n.addFieldFloat32(3, s, 0); - } - static addI(n, s) { - n.addFieldInt64(4, s, n.createLong(0, 0)); - } - static addS(n, s) { - n.addFieldOffset(5, s, 0); - } - static addT(n, s) { - n.addFieldOffset(6, s, 0); - } - static addG(n, s) { - n.addFieldOffset(7, s, 0); - } - static addFloats(n, s) { - n.addFieldOffset(8, s, 0); - } - static createFloatsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addFloat32(s[d]); - return n.endVector(); - } - static startFloatsVector(n, s) { - n.startVector(4, s, 4); - } - static addInts(n, s) { - n.addFieldOffset(9, s, 0); - } - static createIntsVector(n, s) { - n.startVector(8, s.length, 8); - for (let d = s.length - 1; d >= 0; d--) n.addInt64(s[d]); - return n.endVector(); - } - static startIntsVector(n, s) { - n.startVector(8, s, 8); - } - static addStrings(n, s) { - n.addFieldOffset(10, s, 0); - } - static createStringsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startStringsVector(n, s) { - n.startVector(4, s, 4); - } - static addTensors(n, s) { - n.addFieldOffset(11, s, 0); - } - static createTensorsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startTensorsVector(n, s) { - n.startVector(4, s, 4); - } - static addGraphs(n, s) { - n.addFieldOffset(12, s, 0); - } - static createGraphsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startGraphsVector(n, s) { - n.startVector(4, s, 4); - } - static endAttribute(n) { - return n.endObject(); - } - static createAttribute(n, s, d, f, r, a, l, p, m, y, T, v, S, E) { - return ( - i.startAttribute(n), - i.addName(n, s), - i.addDocString(n, d), - i.addType(n, f), - i.addF(n, r), - i.addI(n, a), - i.addS(n, l), - i.addT(n, p), - i.addG(n, m), - i.addFloats(n, y), - i.addInts(n, T), - i.addStrings(n, v), - i.addTensors(n, S), - i.addGraphs(n, E), - i.endAttribute(n) - ); - } - } - o.Attribute = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsGraph(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsGraph(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - initializers(n, s) { - let d = this.bb.__offset(this.bb_pos, 4); - return d - ? (s || new t.experimental.fbs.Tensor()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - initializersLength() { - let n = this.bb.__offset(this.bb_pos, 4); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - nodeArgs(n, s) { - let d = this.bb.__offset(this.bb_pos, 6); - return d - ? (s || new t.experimental.fbs.ValueInfo()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - nodeArgsLength() { - let n = this.bb.__offset(this.bb_pos, 6); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - nodes(n, s) { - let d = this.bb.__offset(this.bb_pos, 8); - return d - ? (s || new t.experimental.fbs.Node()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - nodesLength() { - let n = this.bb.__offset(this.bb_pos, 8); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - maxNodeIndex() { - let n = this.bb.__offset(this.bb_pos, 10); - return n ? this.bb.readUint32(this.bb_pos + n) : 0; - } - nodeEdges(n, s) { - let d = this.bb.__offset(this.bb_pos, 12); - return d - ? (s || new t.experimental.fbs.NodeEdge()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - nodeEdgesLength() { - let n = this.bb.__offset(this.bb_pos, 12); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - inputs(n, s) { - let d = this.bb.__offset(this.bb_pos, 14); - return d ? this.bb.__string(this.bb.__vector(this.bb_pos + d) + n * 4, s) : null; - } - inputsLength() { - let n = this.bb.__offset(this.bb_pos, 14); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - outputs(n, s) { - let d = this.bb.__offset(this.bb_pos, 16); - return d ? this.bb.__string(this.bb.__vector(this.bb_pos + d) + n * 4, s) : null; - } - outputsLength() { - let n = this.bb.__offset(this.bb_pos, 16); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - sparseInitializers(n, s) { - let d = this.bb.__offset(this.bb_pos, 18); - return d - ? (s || new t.experimental.fbs.SparseTensor()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - sparseInitializersLength() { - let n = this.bb.__offset(this.bb_pos, 18); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - static startGraph(n) { - n.startObject(8); - } - static addInitializers(n, s) { - n.addFieldOffset(0, s, 0); - } - static createInitializersVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startInitializersVector(n, s) { - n.startVector(4, s, 4); - } - static addNodeArgs(n, s) { - n.addFieldOffset(1, s, 0); - } - static createNodeArgsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startNodeArgsVector(n, s) { - n.startVector(4, s, 4); - } - static addNodes(n, s) { - n.addFieldOffset(2, s, 0); - } - static createNodesVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startNodesVector(n, s) { - n.startVector(4, s, 4); - } - static addMaxNodeIndex(n, s) { - n.addFieldInt32(3, s, 0); - } - static addNodeEdges(n, s) { - n.addFieldOffset(4, s, 0); - } - static createNodeEdgesVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startNodeEdgesVector(n, s) { - n.startVector(4, s, 4); - } - static addInputs(n, s) { - n.addFieldOffset(5, s, 0); - } - static createInputsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startInputsVector(n, s) { - n.startVector(4, s, 4); - } - static addOutputs(n, s) { - n.addFieldOffset(6, s, 0); - } - static createOutputsVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startOutputsVector(n, s) { - n.startVector(4, s, 4); - } - static addSparseInitializers(n, s) { - n.addFieldOffset(7, s, 0); - } - static createSparseInitializersVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startSparseInitializersVector(n, s) { - n.startVector(4, s, 4); - } - static endGraph(n) { - return n.endObject(); - } - static createGraph(n, s, d, f, r, a, l, p, m) { - return ( - i.startGraph(n), - i.addInitializers(n, s), - i.addNodeArgs(n, d), - i.addNodes(n, f), - i.addMaxNodeIndex(n, r), - i.addNodeEdges(n, a), - i.addInputs(n, l), - i.addOutputs(n, p), - i.addSparseInitializers(n, m), - i.endGraph(n) - ); - } - } - o.Graph = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsModel(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsModel(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - irVersion() { - let n = this.bb.__offset(this.bb_pos, 4); - return n ? this.bb.readInt64(this.bb_pos + n) : this.bb.createLong(0, 0); - } - opsetImport(n, s) { - let d = this.bb.__offset(this.bb_pos, 6); - return d - ? (s || new t.experimental.fbs.OperatorSetId()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - opsetImportLength() { - let n = this.bb.__offset(this.bb_pos, 6); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - producerName(n) { - let s = this.bb.__offset(this.bb_pos, 8); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - producerVersion(n) { - let s = this.bb.__offset(this.bb_pos, 10); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - domain(n) { - let s = this.bb.__offset(this.bb_pos, 12); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - modelVersion() { - let n = this.bb.__offset(this.bb_pos, 14); - return n ? this.bb.readInt64(this.bb_pos + n) : this.bb.createLong(0, 0); - } - docString(n) { - let s = this.bb.__offset(this.bb_pos, 16); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - graph(n) { - let s = this.bb.__offset(this.bb_pos, 18); - return s - ? (n || new t.experimental.fbs.Graph()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - graphDocString(n) { - let s = this.bb.__offset(this.bb_pos, 20); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - static startModel(n) { - n.startObject(9); - } - static addIrVersion(n, s) { - n.addFieldInt64(0, s, n.createLong(0, 0)); - } - static addOpsetImport(n, s) { - n.addFieldOffset(1, s, 0); - } - static createOpsetImportVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startOpsetImportVector(n, s) { - n.startVector(4, s, 4); - } - static addProducerName(n, s) { - n.addFieldOffset(2, s, 0); - } - static addProducerVersion(n, s) { - n.addFieldOffset(3, s, 0); - } - static addDomain(n, s) { - n.addFieldOffset(4, s, 0); - } - static addModelVersion(n, s) { - n.addFieldInt64(5, s, n.createLong(0, 0)); - } - static addDocString(n, s) { - n.addFieldOffset(6, s, 0); - } - static addGraph(n, s) { - n.addFieldOffset(7, s, 0); - } - static addGraphDocString(n, s) { - n.addFieldOffset(8, s, 0); - } - static endModel(n) { - return n.endObject(); - } - static createModel(n, s, d, f, r, a, l, p, m, y) { - return ( - i.startModel(n), - i.addIrVersion(n, s), - i.addOpsetImport(n, d), - i.addProducerName(n, f), - i.addProducerVersion(n, r), - i.addDomain(n, a), - i.addModelVersion(n, l), - i.addDocString(n, p), - i.addGraph(n, m), - i.addGraphDocString(n, y), - i.endModel(n) - ); - } - } - o.Model = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsKernelCreateInfos(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsKernelCreateInfos(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - nodeIndices(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s ? this.bb.readUint32(this.bb.__vector(this.bb_pos + s) + n * 4) : 0; - } - nodeIndicesLength() { - let n = this.bb.__offset(this.bb_pos, 4); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - nodeIndicesArray() { - let n = this.bb.__offset(this.bb_pos, 4); - return n - ? new Uint32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + n), - this.bb.__vector_len(this.bb_pos + n) - ) - : null; - } - kernelDefHashes(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s - ? this.bb.readUint64(this.bb.__vector(this.bb_pos + s) + n * 8) - : this.bb.createLong(0, 0); - } - kernelDefHashesLength() { - let n = this.bb.__offset(this.bb_pos, 6); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - static startKernelCreateInfos(n) { - n.startObject(2); - } - static addNodeIndices(n, s) { - n.addFieldOffset(0, s, 0); - } - static createNodeIndicesVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addInt32(s[d]); - return n.endVector(); - } - static startNodeIndicesVector(n, s) { - n.startVector(4, s, 4); - } - static addKernelDefHashes(n, s) { - n.addFieldOffset(1, s, 0); - } - static createKernelDefHashesVector(n, s) { - n.startVector(8, s.length, 8); - for (let d = s.length - 1; d >= 0; d--) n.addInt64(s[d]); - return n.endVector(); - } - static startKernelDefHashesVector(n, s) { - n.startVector(8, s, 8); - } - static endKernelCreateInfos(n) { - return n.endObject(); - } - static createKernelCreateInfos(n, s, d) { - return ( - i.startKernelCreateInfos(n), - i.addNodeIndices(n, s), - i.addKernelDefHashes(n, d), - i.endKernelCreateInfos(n) - ); - } - } - o.KernelCreateInfos = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsSubGraphSessionState(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsSubGraphSessionState(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - graphId(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - sessionState(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s - ? (n || new t.experimental.fbs.SessionState()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - static startSubGraphSessionState(n) { - n.startObject(2); - } - static addGraphId(n, s) { - n.addFieldOffset(0, s, 0); - } - static addSessionState(n, s) { - n.addFieldOffset(1, s, 0); - } - static endSubGraphSessionState(n) { - let s = n.endObject(); - return n.requiredField(s, 4), s; - } - static createSubGraphSessionState(n, s, d) { - return ( - i.startSubGraphSessionState(n), - i.addGraphId(n, s), - i.addSessionState(n, d), - i.endSubGraphSessionState(n) - ); - } - } - o.SubGraphSessionState = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsSessionState(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsSessionState(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - kernels(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s - ? (n || new t.experimental.fbs.KernelCreateInfos()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - subGraphSessionStates(n, s) { - let d = this.bb.__offset(this.bb_pos, 6); - return d - ? (s || new t.experimental.fbs.SubGraphSessionState()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + d) + n * 4), - this.bb - ) - : null; - } - subGraphSessionStatesLength() { - let n = this.bb.__offset(this.bb_pos, 6); - return n ? this.bb.__vector_len(this.bb_pos + n) : 0; - } - static startSessionState(n) { - n.startObject(2); - } - static addKernels(n, s) { - n.addFieldOffset(0, s, 0); - } - static addSubGraphSessionStates(n, s) { - n.addFieldOffset(1, s, 0); - } - static createSubGraphSessionStatesVector(n, s) { - n.startVector(4, s.length, 4); - for (let d = s.length - 1; d >= 0; d--) n.addOffset(s[d]); - return n.endVector(); - } - static startSubGraphSessionStatesVector(n, s) { - n.startVector(4, s, 4); - } - static endSessionState(n) { - return n.endObject(); - } - static createSessionState(n, s, d) { - return ( - i.startSessionState(n), - i.addKernels(n, s), - i.addSubGraphSessionStates(n, d), - i.endSessionState(n) - ); - } - } - o.SessionState = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})), - ((t) => { - ((e) => { - ((o) => { - class i { - constructor() { - (this.bb = null), (this.bb_pos = 0); - } - __init(n, s) { - return (this.bb_pos = n), (this.bb = s), this; - } - static getRootAsInferenceSession(n, s) { - return (s || new i()).__init(n.readInt32(n.position()) + n.position(), n); - } - static getSizePrefixedRootAsInferenceSession(n, s) { - return ( - n.setPosition(n.position() + _.SIZE_PREFIX_LENGTH), - (s || new i()).__init(n.readInt32(n.position()) + n.position(), n) - ); - } - static bufferHasIdentifier(n) { - return n.__has_identifier('ORTM'); - } - ortVersion(n) { - let s = this.bb.__offset(this.bb_pos, 4); - return s ? this.bb.__string(this.bb_pos + s, n) : null; - } - model(n) { - let s = this.bb.__offset(this.bb_pos, 6); - return s - ? (n || new t.experimental.fbs.Model()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - sessionState(n) { - let s = this.bb.__offset(this.bb_pos, 8); - return s - ? (n || new t.experimental.fbs.SessionState()).__init( - this.bb.__indirect(this.bb_pos + s), - this.bb - ) - : null; - } - static startInferenceSession(n) { - n.startObject(3); - } - static addOrtVersion(n, s) { - n.addFieldOffset(0, s, 0); - } - static addModel(n, s) { - n.addFieldOffset(1, s, 0); - } - static addSessionState(n, s) { - n.addFieldOffset(2, s, 0); - } - static endInferenceSession(n) { - return n.endObject(); - } - static finishInferenceSessionBuffer(n, s) { - n.finish(s, 'ORTM'); - } - static finishSizePrefixedInferenceSessionBuffer(n, s) { - n.finish(s, 'ORTM', !0); - } - static createInferenceSession(n, s, d, f) { - return ( - i.startInferenceSession(n), - i.addOrtVersion(n, s), - i.addModel(n, d), - i.addSessionState(n, f), - i.endInferenceSession(n) - ); - } - } - o.InferenceSession = i; - })((e.fbs ||= {})); - })((t.experimental ||= {})); - })((W ||= {})); - }), - ks = me((t, e) => { - e.exports = o; - function o(i, u) { - for (var n = new Array(arguments.length - 1), s = 0, d = 2, f = !0; d < arguments.length; ) - n[s++] = arguments[d++]; - return new Promise(function (r, a) { - n[s] = function (l) { - if (f) - if (((f = !1), l)) a(l); - else { - for (var p = new Array(arguments.length - 1), m = 0; m < p.length; ) p[m++] = arguments[m]; - r.apply(null, p); - } - }; - try { - i.apply(u || null, n); - } catch (l) { - f && ((f = !1), a(l)); - } - }); - } - }), - Ms = me((t) => { - var e = t; - e.length = function (s) { - var d = s.length; - if (!d) return 0; - for (var f = 0; --d % 4 > 1 && s.charAt(d) === '='; ) ++f; - return Math.ceil(s.length * 3) / 4 - f; - }; - var o = new Array(64), - i = new Array(123); - for (u = 0; u < 64; ) i[(o[u] = u < 26 ? u + 65 : u < 52 ? u + 71 : u < 62 ? u - 4 : (u - 59) | 43)] = u++; - var u; - e.encode = function (s, d, f) { - for (var r = null, a = [], l = 0, p = 0, m; d < f; ) { - var y = s[d++]; - switch (p) { - case 0: - (a[l++] = o[y >> 2]), (m = (y & 3) << 4), (p = 1); - break; - case 1: - (a[l++] = o[m | (y >> 4)]), (m = (y & 15) << 2), (p = 2); - break; - case 2: - (a[l++] = o[m | (y >> 6)]), (a[l++] = o[y & 63]), (p = 0); - break; - } - l > 8191 && ((r || (r = [])).push(String.fromCharCode.apply(String, a)), (l = 0)); - } - return ( - p && ((a[l++] = o[m]), (a[l++] = 61), p === 1 && (a[l++] = 61)), - r - ? (l && r.push(String.fromCharCode.apply(String, a.slice(0, l))), r.join('')) - : String.fromCharCode.apply(String, a.slice(0, l)) - ); - }; - var n = 'invalid encoding'; - (e.decode = function (s, d, f) { - for (var r = f, a = 0, l, p = 0; p < s.length; ) { - var m = s.charCodeAt(p++); - if (m === 61 && a > 1) break; - if ((m = i[m]) === void 0) throw Error(n); - switch (a) { - case 0: - (l = m), (a = 1); - break; - case 1: - (d[f++] = (l << 2) | ((m & 48) >> 4)), (l = m), (a = 2); - break; - case 2: - (d[f++] = ((l & 15) << 4) | ((m & 60) >> 2)), (l = m), (a = 3); - break; - case 3: - (d[f++] = ((l & 3) << 6) | m), (a = 0); - break; - } - } - if (a === 1) throw Error(n); - return f - r; - }), - (e.test = function (s) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s); - }); - }), - Us = me((t, e) => { - e.exports = o; - function o() { - this._listeners = {}; - } - (o.prototype.on = function (i, u, n) { - return (this._listeners[i] || (this._listeners[i] = [])).push({ fn: u, ctx: n || this }), this; - }), - (o.prototype.off = function (i, u) { - if (i === void 0) this._listeners = {}; - else if (u === void 0) this._listeners[i] = []; - else for (var n = this._listeners[i], s = 0; s < n.length; ) n[s].fn === u ? n.splice(s, 1) : ++s; - return this; - }), - (o.prototype.emit = function (i) { - var u = this._listeners[i]; - if (u) { - for (var n = [], s = 1; s < arguments.length; ) n.push(arguments[s++]); - for (s = 0; s < u.length; ) u[s].fn.apply(u[s++].ctx, n); - } - return this; - }); - }), - Ys = me((t, e) => { - e.exports = o(o); - function o(d) { - return ( - typeof Float32Array < 'u' - ? (function () { - var f = new Float32Array([-0]), - r = new Uint8Array(f.buffer), - a = r[3] === 128; - function l(T, v, S) { - (f[0] = T), (v[S] = r[0]), (v[S + 1] = r[1]), (v[S + 2] = r[2]), (v[S + 3] = r[3]); - } - function p(T, v, S) { - (f[0] = T), (v[S] = r[3]), (v[S + 1] = r[2]), (v[S + 2] = r[1]), (v[S + 3] = r[0]); - } - (d.writeFloatLE = a ? l : p), (d.writeFloatBE = a ? p : l); - function m(T, v) { - return (r[0] = T[v]), (r[1] = T[v + 1]), (r[2] = T[v + 2]), (r[3] = T[v + 3]), f[0]; - } - function y(T, v) { - return (r[3] = T[v]), (r[2] = T[v + 1]), (r[1] = T[v + 2]), (r[0] = T[v + 3]), f[0]; - } - (d.readFloatLE = a ? m : y), (d.readFloatBE = a ? y : m); - })() - : (function () { - function f(a, l, p, m) { - var y = l < 0 ? 1 : 0; - if ((y && (l = -l), l === 0)) a(1 / l > 0 ? 0 : 2147483648, p, m); - else if (isNaN(l)) a(2143289344, p, m); - else if (l > 34028234663852886e22) a(((y << 31) | 2139095040) >>> 0, p, m); - else if (l < 11754943508222875e-54) - a(((y << 31) | Math.round(l / 1401298464324817e-60)) >>> 0, p, m); - else { - var T = Math.floor(Math.log(l) / Math.LN2), - v = Math.round(l * Math.pow(2, -T) * 8388608) & 8388607; - a(((y << 31) | ((T + 127) << 23) | v) >>> 0, p, m); - } - } - (d.writeFloatLE = f.bind(null, i)), (d.writeFloatBE = f.bind(null, u)); - function r(a, l, p) { - var m = a(l, p), - y = (m >> 31) * 2 + 1, - T = (m >>> 23) & 255, - v = m & 8388607; - return T === 255 - ? v - ? NaN - : y * (1 / 0) - : T === 0 - ? y * 1401298464324817e-60 * v - : y * Math.pow(2, T - 150) * (v + 8388608); - } - (d.readFloatLE = r.bind(null, n)), (d.readFloatBE = r.bind(null, s)); - })(), - typeof Float64Array < 'u' - ? (function () { - var f = new Float64Array([-0]), - r = new Uint8Array(f.buffer), - a = r[7] === 128; - function l(T, v, S) { - (f[0] = T), - (v[S] = r[0]), - (v[S + 1] = r[1]), - (v[S + 2] = r[2]), - (v[S + 3] = r[3]), - (v[S + 4] = r[4]), - (v[S + 5] = r[5]), - (v[S + 6] = r[6]), - (v[S + 7] = r[7]); - } - function p(T, v, S) { - (f[0] = T), - (v[S] = r[7]), - (v[S + 1] = r[6]), - (v[S + 2] = r[5]), - (v[S + 3] = r[4]), - (v[S + 4] = r[3]), - (v[S + 5] = r[2]), - (v[S + 6] = r[1]), - (v[S + 7] = r[0]); - } - (d.writeDoubleLE = a ? l : p), (d.writeDoubleBE = a ? p : l); - function m(T, v) { - return ( - (r[0] = T[v]), - (r[1] = T[v + 1]), - (r[2] = T[v + 2]), - (r[3] = T[v + 3]), - (r[4] = T[v + 4]), - (r[5] = T[v + 5]), - (r[6] = T[v + 6]), - (r[7] = T[v + 7]), - f[0] - ); - } - function y(T, v) { - return ( - (r[7] = T[v]), - (r[6] = T[v + 1]), - (r[5] = T[v + 2]), - (r[4] = T[v + 3]), - (r[3] = T[v + 4]), - (r[2] = T[v + 5]), - (r[1] = T[v + 6]), - (r[0] = T[v + 7]), - f[0] - ); - } - (d.readDoubleLE = a ? m : y), (d.readDoubleBE = a ? y : m); - })() - : (function () { - function f(a, l, p, m, y, T) { - var v = m < 0 ? 1 : 0; - if ((v && (m = -m), m === 0)) a(0, y, T + l), a(1 / m > 0 ? 0 : 2147483648, y, T + p); - else if (isNaN(m)) a(0, y, T + l), a(2146959360, y, T + p); - else if (m > 17976931348623157e292) - a(0, y, T + l), a(((v << 31) | 2146435072) >>> 0, y, T + p); - else { - var S; - if (m < 22250738585072014e-324) - (S = m / 5e-324), - a(S >>> 0, y, T + l), - a(((v << 31) | (S / 4294967296)) >>> 0, y, T + p); - else { - var E = Math.floor(Math.log(m) / Math.LN2); - E === 1024 && (E = 1023), - (S = m * Math.pow(2, -E)), - a((S * 4503599627370496) >>> 0, y, T + l), - a( - ((v << 31) | ((E + 1023) << 20) | ((S * 1048576) & 1048575)) >>> 0, - y, - T + p - ); - } - } - } - (d.writeDoubleLE = f.bind(null, i, 0, 4)), (d.writeDoubleBE = f.bind(null, u, 4, 0)); - function r(a, l, p, m, y) { - var T = a(m, y + l), - v = a(m, y + p), - S = (v >> 31) * 2 + 1, - E = (v >>> 20) & 2047, - A = 4294967296 * (v & 1048575) + T; - return E === 2047 - ? A - ? NaN - : S * (1 / 0) - : E === 0 - ? S * 5e-324 * A - : S * Math.pow(2, E - 1075) * (A + 4503599627370496); - } - (d.readDoubleLE = r.bind(null, n, 0, 4)), (d.readDoubleBE = r.bind(null, s, 4, 0)); - })(), - d - ); - } - function i(d, f, r) { - (f[r] = d & 255), (f[r + 1] = (d >>> 8) & 255), (f[r + 2] = (d >>> 16) & 255), (f[r + 3] = d >>> 24); - } - function u(d, f, r) { - (f[r] = d >>> 24), (f[r + 1] = (d >>> 16) & 255), (f[r + 2] = (d >>> 8) & 255), (f[r + 3] = d & 255); - } - function n(d, f) { - return (d[f] | (d[f + 1] << 8) | (d[f + 2] << 16) | (d[f + 3] << 24)) >>> 0; - } - function s(d, f) { - return ((d[f] << 24) | (d[f + 1] << 16) | (d[f + 2] << 8) | d[f + 3]) >>> 0; - } - }), - Xs = me((exports, module) => { - module.exports = inquire; - 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; - } - }), - Js = me((t) => { - var e = t; - (e.length = function (o) { - for (var i = 0, u = 0, n = 0; n < o.length; ++n) - (u = o.charCodeAt(n)), - u < 128 - ? (i += 1) - : u < 2048 - ? (i += 2) - : (u & 64512) === 55296 && (o.charCodeAt(n + 1) & 64512) === 56320 - ? (++n, (i += 4)) - : (i += 3); - return i; - }), - (e.read = function (o, i, u) { - var n = u - i; - if (n < 1) return ''; - for (var s = null, d = [], f = 0, r; i < u; ) - (r = o[i++]), - r < 128 - ? (d[f++] = r) - : r > 191 && r < 224 - ? (d[f++] = ((r & 31) << 6) | (o[i++] & 63)) - : r > 239 && r < 365 - ? ((r = - (((r & 7) << 18) | ((o[i++] & 63) << 12) | ((o[i++] & 63) << 6) | (o[i++] & 63)) - - 65536), - (d[f++] = 55296 + (r >> 10)), - (d[f++] = 56320 + (r & 1023))) - : (d[f++] = ((r & 15) << 12) | ((o[i++] & 63) << 6) | (o[i++] & 63)), - f > 8191 && ((s || (s = [])).push(String.fromCharCode.apply(String, d)), (f = 0)); - return s - ? (f && s.push(String.fromCharCode.apply(String, d.slice(0, f))), s.join('')) - : String.fromCharCode.apply(String, d.slice(0, f)); - }), - (e.write = function (o, i, u) { - for (var n = u, s, d, f = 0; f < o.length; ++f) - (s = o.charCodeAt(f)), - s < 128 - ? (i[u++] = s) - : s < 2048 - ? ((i[u++] = (s >> 6) | 192), (i[u++] = (s & 63) | 128)) - : (s & 64512) === 55296 && ((d = o.charCodeAt(f + 1)) & 64512) === 56320 - ? ((s = 65536 + ((s & 1023) << 10) + (d & 1023)), - ++f, - (i[u++] = (s >> 18) | 240), - (i[u++] = ((s >> 12) & 63) | 128), - (i[u++] = ((s >> 6) & 63) | 128), - (i[u++] = (s & 63) | 128)) - : ((i[u++] = (s >> 12) | 224), (i[u++] = ((s >> 6) & 63) | 128), (i[u++] = (s & 63) | 128)); - return u - n; - }); - }), - Qs = me((t, e) => { - e.exports = o; - function o(i, u, n) { - var s = n || 8192, - d = s >>> 1, - f = null, - r = s; - return function (a) { - if (a < 1 || a > d) return i(a); - r + a > s && ((f = i(s)), (r = 0)); - var l = u.call(f, r, (r += a)); - return r & 7 && (r = (r | 7) + 1), l; - }; - } - }), - tu = me((t, e) => { - e.exports = i; - var o = Xt(); - function i(d, f) { - (this.lo = d >>> 0), (this.hi = f >>> 0); - } - var u = (i.zero = new i(0, 0)); - (u.toNumber = function () { - return 0; - }), - (u.zzEncode = u.zzDecode = - function () { - return this; - }), - (u.length = function () { - return 1; - }); - var n = (i.zeroHash = '\0\0\0\0\0\0\0\0'); - (i.fromNumber = function (d) { - if (d === 0) return u; - var f = d < 0; - f && (d = -d); - var r = d >>> 0, - a = ((d - r) / 4294967296) >>> 0; - return ( - f && ((a = ~a >>> 0), (r = ~r >>> 0), ++r > 4294967295 && ((r = 0), ++a > 4294967295 && (a = 0))), - new i(r, a) - ); - }), - (i.from = function (d) { - if (typeof d == 'number') return i.fromNumber(d); - if (o.isString(d)) - if (o.Long) d = o.Long.fromString(d); - else return i.fromNumber(parseInt(d, 10)); - return d.low || d.high ? new i(d.low >>> 0, d.high >>> 0) : u; - }), - (i.prototype.toNumber = function (d) { - if (!d && this.hi >>> 31) { - var f = (~this.lo + 1) >>> 0, - r = ~this.hi >>> 0; - return f || (r = (r + 1) >>> 0), -(f + r * 4294967296); - } - return this.lo + this.hi * 4294967296; - }), - (i.prototype.toLong = function (d) { - return o.Long - ? new o.Long(this.lo | 0, this.hi | 0, !!d) - : { low: this.lo | 0, high: this.hi | 0, unsigned: !!d }; - }); - var s = String.prototype.charCodeAt; - (i.fromHash = function (d) { - return d === n - ? u - : new i( - (s.call(d, 0) | (s.call(d, 1) << 8) | (s.call(d, 2) << 16) | (s.call(d, 3) << 24)) >>> 0, - (s.call(d, 4) | (s.call(d, 5) << 8) | (s.call(d, 6) << 16) | (s.call(d, 7) << 24)) >>> 0 - ); - }), - (i.prototype.toHash = function () { - return String.fromCharCode( - this.lo & 255, - (this.lo >>> 8) & 255, - (this.lo >>> 16) & 255, - this.lo >>> 24, - this.hi & 255, - (this.hi >>> 8) & 255, - (this.hi >>> 16) & 255, - this.hi >>> 24 - ); - }), - (i.prototype.zzEncode = function () { - var d = this.hi >> 31; - return ( - (this.hi = (((this.hi << 1) | (this.lo >>> 31)) ^ d) >>> 0), - (this.lo = ((this.lo << 1) ^ d) >>> 0), - this - ); - }), - (i.prototype.zzDecode = function () { - var d = -(this.lo & 1); - return ( - (this.lo = (((this.lo >>> 1) | (this.hi << 31)) ^ d) >>> 0), - (this.hi = ((this.hi >>> 1) ^ d) >>> 0), - this - ); - }), - (i.prototype.length = function () { - var d = this.lo, - f = ((this.lo >>> 28) | (this.hi << 4)) >>> 0, - r = this.hi >>> 24; - return r === 0 - ? f === 0 - ? d < 16384 - ? d < 128 - ? 1 - : 2 - : d < 2097152 - ? 3 - : 4 - : f < 16384 - ? f < 128 - ? 5 - : 6 - : f < 2097152 - ? 7 - : 8 - : r < 128 - ? 9 - : 10; - }); - }), - Xt = me((t) => { - var e = t; - (e.asPromise = ks()), - (e.base64 = Ms()), - (e.EventEmitter = Us()), - (e.float = Ys()), - (e.inquire = Xs()), - (e.utf8 = Js()), - (e.pool = Qs()), - (e.LongBits = tu()), - (e.isNode = !!( - typeof global < 'u' && - global && - global.process && - global.process.versions && - global.process.versions.node - )), - (e.global = (e.isNode && global) || (typeof window < 'u' && window) || (typeof self < 'u' && self) || t), - (e.emptyArray = Object.freeze ? Object.freeze([]) : []), - (e.emptyObject = Object.freeze ? Object.freeze({}) : {}), - (e.isInteger = - Number.isInteger || - function (u) { - return typeof u == 'number' && isFinite(u) && Math.floor(u) === u; - }), - (e.isString = function (u) { - return typeof u == 'string' || u instanceof String; - }), - (e.isObject = function (u) { - return u && typeof u == 'object'; - }), - (e.isset = e.isSet = - function (u, n) { - var s = u[n]; - return s != null && u.hasOwnProperty(n) - ? typeof s != 'object' || (Array.isArray(s) ? s.length : Object.keys(s).length) > 0 - : !1; - }), - (e.Buffer = (function () { - try { - var u = e.inquire('buffer').Buffer; - return u.prototype.utf8Write ? u : null; - } catch { - return null; - } - })()), - (e._Buffer_from = null), - (e._Buffer_allocUnsafe = null), - (e.newBuffer = function (u) { - return typeof u == 'number' - ? e.Buffer - ? e._Buffer_allocUnsafe(u) - : new e.Array(u) - : e.Buffer - ? e._Buffer_from(u) - : typeof Uint8Array > 'u' - ? u - : new Uint8Array(u); - }), - (e.Array = typeof Uint8Array < 'u' ? Uint8Array : Array), - (e.Long = (e.global.dcodeIO && e.global.dcodeIO.Long) || e.global.Long || e.inquire('long')), - (e.key2Re = /^true|false|0|1$/), - (e.key32Re = /^-?(?:0|[1-9][0-9]*)$/), - (e.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/), - (e.longToHash = function (u) { - return u ? e.LongBits.from(u).toHash() : e.LongBits.zeroHash; - }), - (e.longFromHash = function (u, n) { - var s = e.LongBits.fromHash(u); - return e.Long ? e.Long.fromBits(s.lo, s.hi, n) : s.toNumber(!!n); - }); - function o(u, n, s) { - for (var d = Object.keys(n), f = 0; f < d.length; ++f) (u[d[f]] === void 0 || !s) && (u[d[f]] = n[d[f]]); - return u; - } - (e.merge = o), - (e.lcFirst = function (u) { - return u.charAt(0).toLowerCase() + u.substring(1); - }); - function i(u) { - function n(s, d) { - if (!(this instanceof n)) return new n(s, d); - Object.defineProperty(this, 'message', { - get: function () { - return s; - }, - }), - Error.captureStackTrace - ? Error.captureStackTrace(this, n) - : Object.defineProperty(this, 'stack', { value: new Error().stack || '' }), - d && o(this, d); - } - return ( - (n.prototype = Object.create(Error.prototype, { - constructor: { value: n, writable: !0, enumerable: !1, configurable: !0 }, - name: { - get: function () { - return u; - }, - set: void 0, - enumerable: !1, - configurable: !0, - }, - toString: { - value: function () { - return this.name + ': ' + this.message; - }, - writable: !0, - enumerable: !1, - configurable: !0, - }, - })), - n - ); - } - (e.newError = i), - (e.ProtocolError = i('ProtocolError')), - (e.oneOfGetter = function (u) { - for (var n = {}, s = 0; s < u.length; ++s) n[u[s]] = 1; - return function () { - for (var d = Object.keys(this), f = d.length - 1; f > -1; --f) - if (n[d[f]] === 1 && this[d[f]] !== void 0 && this[d[f]] !== null) return d[f]; - }; - }), - (e.oneOfSetter = function (u) { - return function (n) { - for (var s = 0; s < u.length; ++s) u[s] !== n && delete this[u[s]]; - }; - }), - (e.toJSONOptions = { longs: String, enums: String, bytes: String, json: !0 }), - (e._configure = function () { - var u = e.Buffer; - if (!u) { - e._Buffer_from = e._Buffer_allocUnsafe = null; - return; - } - (e._Buffer_from = - (u.from !== Uint8Array.from && u.from) || - function (n, s) { - return new u(n, s); - }), - (e._Buffer_allocUnsafe = - u.allocUnsafe || - function (n) { - return new u(n); - }); - }); - }), - li = me((t, e) => { - e.exports = a; - var o = Xt(), - i, - u = o.LongBits, - n = o.base64, - s = o.utf8; - function d(E, A, F) { - (this.fn = E), (this.len = A), (this.next = void 0), (this.val = F); - } - function f() {} - function r(E) { - (this.head = E.head), (this.tail = E.tail), (this.len = E.len), (this.next = E.states); - } - function a() { - (this.len = 0), (this.head = new d(f, 0, 0)), (this.tail = this.head), (this.states = null); - } - var l = function () { - return o.Buffer - ? function () { - return (a.create = function () { - return new i(); - })(); - } - : function () { - return new a(); - }; - }; - (a.create = l()), - (a.alloc = function (E) { - return new o.Array(E); - }), - o.Array !== Array && (a.alloc = o.pool(a.alloc, o.Array.prototype.subarray)), - (a.prototype._push = function (E, A, F) { - return (this.tail = this.tail.next = new d(E, A, F)), (this.len += A), this; - }); - function p(E, A, F) { - A[F] = E & 255; - } - function m(E, A, F) { - for (; E > 127; ) (A[F++] = (E & 127) | 128), (E >>>= 7); - A[F] = E; - } - function y(E, A) { - (this.len = E), (this.next = void 0), (this.val = A); - } - (y.prototype = Object.create(d.prototype)), - (y.prototype.fn = m), - (a.prototype.uint32 = function (E) { - return ( - (this.len += (this.tail = this.tail.next = - new y( - (E = E >>> 0) < 128 ? 1 : E < 16384 ? 2 : E < 2097152 ? 3 : E < 268435456 ? 4 : 5, - E - )).len), - this - ); - }), - (a.prototype.int32 = function (E) { - return E < 0 ? this._push(T, 10, u.fromNumber(E)) : this.uint32(E); - }), - (a.prototype.sint32 = function (E) { - return this.uint32(((E << 1) ^ (E >> 31)) >>> 0); - }); - function T(E, A, F) { - for (; E.hi; ) (A[F++] = (E.lo & 127) | 128), (E.lo = ((E.lo >>> 7) | (E.hi << 25)) >>> 0), (E.hi >>>= 7); - for (; E.lo > 127; ) (A[F++] = (E.lo & 127) | 128), (E.lo = E.lo >>> 7); - A[F++] = E.lo; - } - (a.prototype.uint64 = function (E) { - var A = u.from(E); - return this._push(T, A.length(), A); - }), - (a.prototype.int64 = a.prototype.uint64), - (a.prototype.sint64 = function (E) { - var A = u.from(E).zzEncode(); - return this._push(T, A.length(), A); - }), - (a.prototype.bool = function (E) { - return this._push(p, 1, E ? 1 : 0); - }); - function v(E, A, F) { - (A[F] = E & 255), (A[F + 1] = (E >>> 8) & 255), (A[F + 2] = (E >>> 16) & 255), (A[F + 3] = E >>> 24); - } - (a.prototype.fixed32 = function (E) { - return this._push(v, 4, E >>> 0); - }), - (a.prototype.sfixed32 = a.prototype.fixed32), - (a.prototype.fixed64 = function (E) { - var A = u.from(E); - return this._push(v, 4, A.lo)._push(v, 4, A.hi); - }), - (a.prototype.sfixed64 = a.prototype.fixed64), - (a.prototype.float = function (E) { - return this._push(o.float.writeFloatLE, 4, E); - }), - (a.prototype.double = function (E) { - return this._push(o.float.writeDoubleLE, 8, E); - }); - var S = o.Array.prototype.set - ? function (E, A, F) { - A.set(E, F); - } - : function (E, A, F) { - for (var B = 0; B < E.length; ++B) A[F + B] = E[B]; - }; - (a.prototype.bytes = function (E) { - var A = E.length >>> 0; - if (!A) return this._push(p, 1, 0); - if (o.isString(E)) { - var F = a.alloc((A = n.length(E))); - n.decode(E, F, 0), (E = F); - } - return this.uint32(A)._push(S, A, E); - }), - (a.prototype.string = function (E) { - var A = s.length(E); - return A ? this.uint32(A)._push(s.write, A, E) : this._push(p, 1, 0); - }), - (a.prototype.fork = function () { - return (this.states = new r(this)), (this.head = this.tail = new d(f, 0, 0)), (this.len = 0), this; - }), - (a.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 d(f, 0, 0)), (this.len = 0)), - this - ); - }), - (a.prototype.ldelim = function () { - var E = this.head, - A = this.tail, - F = this.len; - return this.reset().uint32(F), F && ((this.tail.next = E.next), (this.tail = A), (this.len += F)), this; - }), - (a.prototype.finish = function () { - for (var E = this.head.next, A = this.constructor.alloc(this.len), F = 0; E; ) - E.fn(E.val, A, F), (F += E.len), (E = E.next); - return A; - }), - (a._configure = function (E) { - (i = E), (a.create = l()), i._configure(); - }); - }), - fu = me((t, e) => { - e.exports = u; - var o = li(); - (u.prototype = Object.create(o.prototype)).constructor = u; - var i = Xt(); - function u() { - o.call(this); - } - (u._configure = function () { - (u.alloc = i._Buffer_allocUnsafe), - (u.writeBytesBuffer = - i.Buffer && i.Buffer.prototype instanceof Uint8Array && i.Buffer.prototype.set.name === 'set' - ? function (s, d, f) { - d.set(s, f); - } - : function (s, d, f) { - if (s.copy) s.copy(d, f, 0, s.length); - else for (var r = 0; r < s.length; ) d[f++] = s[r++]; - }); - }), - (u.prototype.bytes = function (s) { - i.isString(s) && (s = i._Buffer_from(s, 'base64')); - var d = s.length >>> 0; - return this.uint32(d), d && this._push(u.writeBytesBuffer, d, s), this; - }); - function n(s, d, f) { - s.length < 40 ? i.utf8.write(s, d, f) : d.utf8Write ? d.utf8Write(s, f) : d.write(s, f); - } - (u.prototype.string = function (s) { - var d = i.Buffer.byteLength(s); - return this.uint32(d), d && this._push(n, d, s), this; - }), - u._configure(); - }), - pi = me((t, e) => { - e.exports = d; - var o = Xt(), - i, - u = o.LongBits, - n = o.utf8; - function s(m, y) { - return RangeError('index out of range: ' + m.pos + ' + ' + (y || 1) + ' > ' + m.len); - } - function d(m) { - (this.buf = m), (this.pos = 0), (this.len = m.length); - } - var f = - typeof Uint8Array < 'u' - ? function (m) { - if (m instanceof Uint8Array || Array.isArray(m)) return new d(m); - throw Error('illegal buffer'); - } - : function (m) { - if (Array.isArray(m)) return new d(m); - throw Error('illegal buffer'); - }, - r = function () { - return o.Buffer - ? function (m) { - return (d.create = function (y) { - return o.Buffer.isBuffer(y) ? new i(y) : f(y); - })(m); - } - : f; - }; - (d.create = r()), - (d.prototype._slice = o.Array.prototype.subarray || o.Array.prototype.slice), - (d.prototype.uint32 = (function () { - var m = 4294967295; - return function () { - if ( - ((m = (this.buf[this.pos] & 127) >>> 0), - this.buf[this.pos++] < 128 || - ((m = (m | ((this.buf[this.pos] & 127) << 7)) >>> 0), this.buf[this.pos++] < 128) || - ((m = (m | ((this.buf[this.pos] & 127) << 14)) >>> 0), this.buf[this.pos++] < 128) || - ((m = (m | ((this.buf[this.pos] & 127) << 21)) >>> 0), this.buf[this.pos++] < 128) || - ((m = (m | ((this.buf[this.pos] & 15) << 28)) >>> 0), this.buf[this.pos++] < 128)) - ) - return m; - if ((this.pos += 5) > this.len) throw ((this.pos = this.len), s(this, 10)); - return m; - }; - })()), - (d.prototype.int32 = function () { - return this.uint32() | 0; - }), - (d.prototype.sint32 = function () { - var m = this.uint32(); - return ((m >>> 1) ^ -(m & 1)) | 0; - }); - function a() { - var m = new u(0, 0), - y = 0; - if (this.len - this.pos > 4) { - for (; y < 4; ++y) - if (((m.lo = (m.lo | ((this.buf[this.pos] & 127) << (y * 7))) >>> 0), this.buf[this.pos++] < 128)) - return m; - if ( - ((m.lo = (m.lo | ((this.buf[this.pos] & 127) << 28)) >>> 0), - (m.hi = (m.hi | ((this.buf[this.pos] & 127) >> 4)) >>> 0), - this.buf[this.pos++] < 128) - ) - return m; - y = 0; - } else { - for (; y < 3; ++y) { - if (this.pos >= this.len) throw s(this); - if (((m.lo = (m.lo | ((this.buf[this.pos] & 127) << (y * 7))) >>> 0), this.buf[this.pos++] < 128)) - return m; - } - return (m.lo = (m.lo | ((this.buf[this.pos++] & 127) << (y * 7))) >>> 0), m; - } - if (this.len - this.pos > 4) { - for (; y < 5; ++y) - if ( - ((m.hi = (m.hi | ((this.buf[this.pos] & 127) << (y * 7 + 3))) >>> 0), - this.buf[this.pos++] < 128) - ) - return m; - } else - for (; y < 5; ++y) { - if (this.pos >= this.len) throw s(this); - if ( - ((m.hi = (m.hi | ((this.buf[this.pos] & 127) << (y * 7 + 3))) >>> 0), - this.buf[this.pos++] < 128) - ) - return m; - } - throw Error('invalid varint encoding'); - } - d.prototype.bool = function () { - return this.uint32() !== 0; - }; - function l(m, y) { - return (m[y - 4] | (m[y - 3] << 8) | (m[y - 2] << 16) | (m[y - 1] << 24)) >>> 0; - } - (d.prototype.fixed32 = function () { - if (this.pos + 4 > this.len) throw s(this, 4); - return l(this.buf, (this.pos += 4)); - }), - (d.prototype.sfixed32 = function () { - if (this.pos + 4 > this.len) throw s(this, 4); - return l(this.buf, (this.pos += 4)) | 0; - }); - function p() { - if (this.pos + 8 > this.len) throw s(this, 8); - return new u(l(this.buf, (this.pos += 4)), l(this.buf, (this.pos += 4))); - } - (d.prototype.float = function () { - if (this.pos + 4 > this.len) throw s(this, 4); - var m = o.float.readFloatLE(this.buf, this.pos); - return (this.pos += 4), m; - }), - (d.prototype.double = function () { - if (this.pos + 8 > this.len) throw s(this, 4); - var m = o.float.readDoubleLE(this.buf, this.pos); - return (this.pos += 8), m; - }), - (d.prototype.bytes = function () { - var m = this.uint32(), - y = this.pos, - T = this.pos + m; - if (T > this.len) throw s(this, m); - return ( - (this.pos += m), - Array.isArray(this.buf) - ? this.buf.slice(y, T) - : y === T - ? new this.buf.constructor(0) - : this._slice.call(this.buf, y, T) - ); - }), - (d.prototype.string = function () { - var m = this.bytes(); - return n.read(m, 0, m.length); - }), - (d.prototype.skip = function (m) { - if (typeof m == 'number') { - if (this.pos + m > this.len) throw s(this, m); - this.pos += m; - } else - do if (this.pos >= this.len) throw s(this); - while (this.buf[this.pos++] & 128); - return this; - }), - (d.prototype.skipType = function (m) { - switch (m) { - case 0: - this.skip(); - break; - case 1: - this.skip(8); - break; - case 2: - this.skip(this.uint32()); - break; - case 3: - for (; (m = this.uint32() & 7) !== 4; ) this.skipType(m); - break; - case 5: - this.skip(4); - break; - default: - throw Error('invalid wire type ' + m + ' at offset ' + this.pos); - } - return this; - }), - (d._configure = function (m) { - (i = m), (d.create = r()), i._configure(); - var y = o.Long ? 'toLong' : 'toNumber'; - o.merge(d.prototype, { - int64: function () { - return a.call(this)[y](!1); - }, - uint64: function () { - return a.call(this)[y](!0); - }, - sint64: function () { - return a.call(this).zzDecode()[y](!1); - }, - fixed64: function () { - return p.call(this)[y](!0); - }, - sfixed64: function () { - return p.call(this)[y](!1); - }, - }); - }); - }), - Tu = me((t, e) => { - e.exports = u; - var o = pi(); - (u.prototype = Object.create(o.prototype)).constructor = u; - var i = Xt(); - function u(n) { - o.call(this, n); - } - (u._configure = function () { - i.Buffer && (u.prototype._slice = i.Buffer.prototype.slice); - }), - (u.prototype.string = function () { - var n = this.uint32(); - return this.buf.utf8Slice - ? this.buf.utf8Slice(this.pos, (this.pos = Math.min(this.pos + n, this.len))) - : this.buf.toString('utf-8', this.pos, (this.pos = Math.min(this.pos + n, this.len))); - }), - u._configure(); - }), - vu = me((t, e) => { - e.exports = i; - var o = Xt(); - (i.prototype = Object.create(o.EventEmitter.prototype)).constructor = i; - function i(u, n, s) { - if (typeof u != 'function') throw TypeError('rpcImpl must be a function'); - o.EventEmitter.call(this), - (this.rpcImpl = u), - (this.requestDelimited = !!n), - (this.responseDelimited = !!s); - } - (i.prototype.rpcCall = function u(n, s, d, f, r) { - if (!f) throw TypeError('request must be specified'); - var a = this; - if (!r) return o.asPromise(u, a, n, s, d, f); - if (!a.rpcImpl) { - setTimeout(function () { - r(Error('already ended')); - }, 0); - return; - } - try { - return a.rpcImpl(n, s[a.requestDelimited ? 'encodeDelimited' : 'encode'](f).finish(), function (l, p) { - if (l) return a.emit('error', l, n), r(l); - if (p === null) { - a.end(!0); - return; - } - if (!(p instanceof d)) - try { - p = d[a.responseDelimited ? 'decodeDelimited' : 'decode'](p); - } catch (m) { - return a.emit('error', m, n), r(m); - } - return a.emit('data', p, n), r(null, p); - }); - } catch (l) { - a.emit('error', l, n), - setTimeout(function () { - r(l); - }, 0); - return; - } - }), - (i.prototype.end = function (u) { - return ( - this.rpcImpl && - (u || this.rpcImpl(null, null, null), (this.rpcImpl = null), this.emit('end').off()), - this - ); - }); - }), - _u = me((t) => { - var e = t; - e.Service = vu(); - }), - Iu = me((t, e) => { - e.exports = {}; - }), - Pu = me((t) => { - var e = t; - (e.build = 'minimal'), - (e.Writer = li()), - (e.BufferWriter = fu()), - (e.Reader = pi()), - (e.BufferReader = Tu()), - (e.util = Xt()), - (e.rpc = _u()), - (e.roots = Iu()), - (e.configure = o); - function o() { - e.util._configure(), e.Writer._configure(e.BufferWriter), e.Reader._configure(e.BufferReader); - } - o(); - }), - Du = me((t, e) => { - e.exports = Pu(); - }), - $r = me((t, e) => { - var o = Du(), - i = o.Reader, - u = o.Writer, - n = o.util, - s = o.roots.default || (o.roots.default = {}); - (s.onnx = (function () { - var d = {}; - return ( - (d.Version = (function () { - var f = {}, - r = Object.create(f); - return ( - (r[(f[0] = '_START_VERSION')] = 0), - (r[(f[1] = 'IR_VERSION_2017_10_10')] = 1), - (r[(f[2] = 'IR_VERSION_2017_10_30')] = 2), - (r[(f[3] = 'IR_VERSION_2017_11_3')] = 3), - (r[(f[4] = 'IR_VERSION_2019_1_22')] = 4), - (r[(f[5] = 'IR_VERSION_2019_3_18')] = 5), - (r[(f[6] = 'IR_VERSION_2019_9_19')] = 6), - (r[(f[7] = 'IR_VERSION_2020_5_8')] = 7), - (r[(f[8] = 'IR_VERSION_2021_7_30')] = 8), - (r[(f[9] = 'IR_VERSION')] = 9), - r - ); - })()), - (d.AttributeProto = (function () { - function f(r) { - if ( - ((this.floats = []), - (this.ints = []), - (this.strings = []), - (this.tensors = []), - (this.graphs = []), - (this.sparseTensors = []), - (this.typeProtos = []), - r) - ) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.name = ''), - (f.prototype.refAttrName = ''), - (f.prototype.docString = ''), - (f.prototype.type = 0), - (f.prototype.f = 0), - (f.prototype.i = n.Long ? n.Long.fromBits(0, 0, !1) : 0), - (f.prototype.s = n.newBuffer([])), - (f.prototype.t = null), - (f.prototype.g = null), - (f.prototype.sparseTensor = null), - (f.prototype.tp = null), - (f.prototype.floats = n.emptyArray), - (f.prototype.ints = n.emptyArray), - (f.prototype.strings = n.emptyArray), - (f.prototype.tensors = n.emptyArray), - (f.prototype.graphs = n.emptyArray), - (f.prototype.sparseTensors = n.emptyArray), - (f.prototype.typeProtos = n.emptyArray), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - if ( - (a || (a = u.create()), - r.name != null && Object.hasOwnProperty.call(r, 'name') && a.uint32(10).string(r.name), - r.f != null && Object.hasOwnProperty.call(r, 'f') && a.uint32(21).float(r.f), - r.i != null && Object.hasOwnProperty.call(r, 'i') && a.uint32(24).int64(r.i), - r.s != null && Object.hasOwnProperty.call(r, 's') && a.uint32(34).bytes(r.s), - r.t != null && - Object.hasOwnProperty.call(r, 't') && - s.onnx.TensorProto.encode(r.t, a.uint32(42).fork()).ldelim(), - r.g != null && - Object.hasOwnProperty.call(r, 'g') && - s.onnx.GraphProto.encode(r.g, a.uint32(50).fork()).ldelim(), - r.floats != null && r.floats.length) - ) { - a.uint32(58).fork(); - for (var l = 0; l < r.floats.length; ++l) a.float(r.floats[l]); - a.ldelim(); - } - if (r.ints != null && r.ints.length) { - a.uint32(66).fork(); - for (var l = 0; l < r.ints.length; ++l) a.int64(r.ints[l]); - a.ldelim(); - } - if (r.strings != null && r.strings.length) - for (var l = 0; l < r.strings.length; ++l) a.uint32(74).bytes(r.strings[l]); - if (r.tensors != null && r.tensors.length) - for (var l = 0; l < r.tensors.length; ++l) - s.onnx.TensorProto.encode(r.tensors[l], a.uint32(82).fork()).ldelim(); - if (r.graphs != null && r.graphs.length) - for (var l = 0; l < r.graphs.length; ++l) - s.onnx.GraphProto.encode(r.graphs[l], a.uint32(90).fork()).ldelim(); - if ( - (r.docString != null && - Object.hasOwnProperty.call(r, 'docString') && - a.uint32(106).string(r.docString), - r.tp != null && - Object.hasOwnProperty.call(r, 'tp') && - s.onnx.TypeProto.encode(r.tp, a.uint32(114).fork()).ldelim(), - r.typeProtos != null && r.typeProtos.length) - ) - for (var l = 0; l < r.typeProtos.length; ++l) - s.onnx.TypeProto.encode(r.typeProtos[l], a.uint32(122).fork()).ldelim(); - if ( - (r.type != null && Object.hasOwnProperty.call(r, 'type') && a.uint32(160).int32(r.type), - r.refAttrName != null && - Object.hasOwnProperty.call(r, 'refAttrName') && - a.uint32(170).string(r.refAttrName), - r.sparseTensor != null && - Object.hasOwnProperty.call(r, 'sparseTensor') && - s.onnx.SparseTensorProto.encode(r.sparseTensor, a.uint32(178).fork()).ldelim(), - r.sparseTensors != null && r.sparseTensors.length) - ) - for (var l = 0; l < r.sparseTensors.length; ++l) - s.onnx.SparseTensorProto.encode(r.sparseTensors[l], a.uint32(186).fork()).ldelim(); - return a; - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for ( - var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.AttributeProto(); - r.pos < l; - - ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - p.name = r.string(); - break; - } - case 21: { - p.refAttrName = r.string(); - break; - } - case 13: { - p.docString = r.string(); - break; - } - case 20: { - p.type = r.int32(); - break; - } - case 2: { - p.f = r.float(); - break; - } - case 3: { - p.i = r.int64(); - break; - } - case 4: { - p.s = r.bytes(); - break; - } - case 5: { - p.t = s.onnx.TensorProto.decode(r, r.uint32()); - break; - } - case 6: { - p.g = s.onnx.GraphProto.decode(r, r.uint32()); - break; - } - case 22: { - p.sparseTensor = s.onnx.SparseTensorProto.decode(r, r.uint32()); - break; - } - case 14: { - p.tp = s.onnx.TypeProto.decode(r, r.uint32()); - break; - } - case 7: { - if (((p.floats && p.floats.length) || (p.floats = []), (m & 7) === 2)) - for (var y = r.uint32() + r.pos; r.pos < y; ) p.floats.push(r.float()); - else p.floats.push(r.float()); - break; - } - case 8: { - if (((p.ints && p.ints.length) || (p.ints = []), (m & 7) === 2)) - for (var y = r.uint32() + r.pos; r.pos < y; ) p.ints.push(r.int64()); - else p.ints.push(r.int64()); - break; - } - case 9: { - (p.strings && p.strings.length) || (p.strings = []), p.strings.push(r.bytes()); - break; - } - case 10: { - (p.tensors && p.tensors.length) || (p.tensors = []), - p.tensors.push(s.onnx.TensorProto.decode(r, r.uint32())); - break; - } - case 11: { - (p.graphs && p.graphs.length) || (p.graphs = []), - p.graphs.push(s.onnx.GraphProto.decode(r, r.uint32())); - break; - } - case 23: { - (p.sparseTensors && p.sparseTensors.length) || (p.sparseTensors = []), - p.sparseTensors.push(s.onnx.SparseTensorProto.decode(r, r.uint32())); - break; - } - case 15: { - (p.typeProtos && p.typeProtos.length) || (p.typeProtos = []), - p.typeProtos.push(s.onnx.TypeProto.decode(r, r.uint32())); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if (r.name != null && r.hasOwnProperty('name') && !n.isString(r.name)) - return 'name: string expected'; - if (r.refAttrName != null && r.hasOwnProperty('refAttrName') && !n.isString(r.refAttrName)) - return 'refAttrName: string expected'; - if (r.docString != null && r.hasOwnProperty('docString') && !n.isString(r.docString)) - return 'docString: string expected'; - if (r.type != null && r.hasOwnProperty('type')) - switch (r.type) { - default: - return 'type: enum value expected'; - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 11: - case 13: - case 6: - case 7: - case 8: - case 9: - case 10: - case 12: - case 14: - break; - } - if (r.f != null && r.hasOwnProperty('f') && typeof r.f != 'number') - return 'f: number expected'; - if ( - r.i != null && - r.hasOwnProperty('i') && - !n.isInteger(r.i) && - !(r.i && n.isInteger(r.i.low) && n.isInteger(r.i.high)) - ) - return 'i: integer|Long expected'; - if ( - r.s != null && - r.hasOwnProperty('s') && - !((r.s && typeof r.s.length == 'number') || n.isString(r.s)) - ) - return 's: buffer expected'; - if (r.t != null && r.hasOwnProperty('t')) { - var a = s.onnx.TensorProto.verify(r.t); - if (a) return 't.' + a; - } - if (r.g != null && r.hasOwnProperty('g')) { - var a = s.onnx.GraphProto.verify(r.g); - if (a) return 'g.' + a; - } - if (r.sparseTensor != null && r.hasOwnProperty('sparseTensor')) { - var a = s.onnx.SparseTensorProto.verify(r.sparseTensor); - if (a) return 'sparseTensor.' + a; - } - if (r.tp != null && r.hasOwnProperty('tp')) { - var a = s.onnx.TypeProto.verify(r.tp); - if (a) return 'tp.' + a; - } - if (r.floats != null && r.hasOwnProperty('floats')) { - if (!Array.isArray(r.floats)) return 'floats: array expected'; - for (var l = 0; l < r.floats.length; ++l) - if (typeof r.floats[l] != 'number') return 'floats: number[] expected'; - } - if (r.ints != null && r.hasOwnProperty('ints')) { - if (!Array.isArray(r.ints)) return 'ints: array expected'; - for (var l = 0; l < r.ints.length; ++l) - if ( - !n.isInteger(r.ints[l]) && - !(r.ints[l] && n.isInteger(r.ints[l].low) && n.isInteger(r.ints[l].high)) - ) - return 'ints: integer|Long[] expected'; - } - if (r.strings != null && r.hasOwnProperty('strings')) { - if (!Array.isArray(r.strings)) return 'strings: array expected'; - for (var l = 0; l < r.strings.length; ++l) - if ( - !( - (r.strings[l] && typeof r.strings[l].length == 'number') || - n.isString(r.strings[l]) - ) - ) - return 'strings: buffer[] expected'; - } - if (r.tensors != null && r.hasOwnProperty('tensors')) { - if (!Array.isArray(r.tensors)) return 'tensors: array expected'; - for (var l = 0; l < r.tensors.length; ++l) { - var a = s.onnx.TensorProto.verify(r.tensors[l]); - if (a) return 'tensors.' + a; - } - } - if (r.graphs != null && r.hasOwnProperty('graphs')) { - if (!Array.isArray(r.graphs)) return 'graphs: array expected'; - for (var l = 0; l < r.graphs.length; ++l) { - var a = s.onnx.GraphProto.verify(r.graphs[l]); - if (a) return 'graphs.' + a; - } - } - if (r.sparseTensors != null && r.hasOwnProperty('sparseTensors')) { - if (!Array.isArray(r.sparseTensors)) return 'sparseTensors: array expected'; - for (var l = 0; l < r.sparseTensors.length; ++l) { - var a = s.onnx.SparseTensorProto.verify(r.sparseTensors[l]); - if (a) return 'sparseTensors.' + a; - } - } - if (r.typeProtos != null && r.hasOwnProperty('typeProtos')) { - if (!Array.isArray(r.typeProtos)) return 'typeProtos: array expected'; - for (var l = 0; l < r.typeProtos.length; ++l) { - var a = s.onnx.TypeProto.verify(r.typeProtos[l]); - if (a) return 'typeProtos.' + a; - } - } - return null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.AttributeProto) return r; - var a = new s.onnx.AttributeProto(); - switch ( - (r.name != null && (a.name = String(r.name)), - r.refAttrName != null && (a.refAttrName = String(r.refAttrName)), - r.docString != null && (a.docString = String(r.docString)), - r.type) - ) { - default: - if (typeof r.type == 'number') { - a.type = r.type; - break; - } - break; - case 'UNDEFINED': - case 0: - a.type = 0; - break; - case 'FLOAT': - case 1: - a.type = 1; - break; - case 'INT': - case 2: - a.type = 2; - break; - case 'STRING': - case 3: - a.type = 3; - break; - case 'TENSOR': - case 4: - a.type = 4; - break; - case 'GRAPH': - case 5: - a.type = 5; - break; - case 'SPARSE_TENSOR': - case 11: - a.type = 11; - break; - case 'TYPE_PROTO': - case 13: - a.type = 13; - break; - case 'FLOATS': - case 6: - a.type = 6; - break; - case 'INTS': - case 7: - a.type = 7; - break; - case 'STRINGS': - case 8: - a.type = 8; - break; - case 'TENSORS': - case 9: - a.type = 9; - break; - case 'GRAPHS': - case 10: - a.type = 10; - break; - case 'SPARSE_TENSORS': - case 12: - a.type = 12; - break; - case 'TYPE_PROTOS': - case 14: - a.type = 14; - break; - } - if ( - (r.f != null && (a.f = Number(r.f)), - r.i != null && - (n.Long - ? ((a.i = n.Long.fromValue(r.i)).unsigned = !1) - : typeof r.i == 'string' - ? (a.i = parseInt(r.i, 10)) - : typeof r.i == 'number' - ? (a.i = r.i) - : typeof r.i == 'object' && - (a.i = new n.LongBits(r.i.low >>> 0, r.i.high >>> 0).toNumber())), - r.s != null && - (typeof r.s == 'string' - ? n.base64.decode(r.s, (a.s = n.newBuffer(n.base64.length(r.s))), 0) - : r.s.length >= 0 && (a.s = r.s)), - r.t != null) - ) { - if (typeof r.t != 'object') throw TypeError('.onnx.AttributeProto.t: object expected'); - a.t = s.onnx.TensorProto.fromObject(r.t); - } - if (r.g != null) { - if (typeof r.g != 'object') throw TypeError('.onnx.AttributeProto.g: object expected'); - a.g = s.onnx.GraphProto.fromObject(r.g); - } - if (r.sparseTensor != null) { - if (typeof r.sparseTensor != 'object') - throw TypeError('.onnx.AttributeProto.sparseTensor: object expected'); - a.sparseTensor = s.onnx.SparseTensorProto.fromObject(r.sparseTensor); - } - if (r.tp != null) { - if (typeof r.tp != 'object') - throw TypeError('.onnx.AttributeProto.tp: object expected'); - a.tp = s.onnx.TypeProto.fromObject(r.tp); - } - if (r.floats) { - if (!Array.isArray(r.floats)) - throw TypeError('.onnx.AttributeProto.floats: array expected'); - a.floats = []; - for (var l = 0; l < r.floats.length; ++l) a.floats[l] = Number(r.floats[l]); - } - if (r.ints) { - if (!Array.isArray(r.ints)) - throw TypeError('.onnx.AttributeProto.ints: array expected'); - a.ints = []; - for (var l = 0; l < r.ints.length; ++l) - n.Long - ? ((a.ints[l] = n.Long.fromValue(r.ints[l])).unsigned = !1) - : typeof r.ints[l] == 'string' - ? (a.ints[l] = parseInt(r.ints[l], 10)) - : typeof r.ints[l] == 'number' - ? (a.ints[l] = r.ints[l]) - : typeof r.ints[l] == 'object' && - (a.ints[l] = new n.LongBits( - r.ints[l].low >>> 0, - r.ints[l].high >>> 0 - ).toNumber()); - } - if (r.strings) { - if (!Array.isArray(r.strings)) - throw TypeError('.onnx.AttributeProto.strings: array expected'); - a.strings = []; - for (var l = 0; l < r.strings.length; ++l) - typeof r.strings[l] == 'string' - ? n.base64.decode( - r.strings[l], - (a.strings[l] = n.newBuffer(n.base64.length(r.strings[l]))), - 0 - ) - : r.strings[l].length >= 0 && (a.strings[l] = r.strings[l]); - } - if (r.tensors) { - if (!Array.isArray(r.tensors)) - throw TypeError('.onnx.AttributeProto.tensors: array expected'); - a.tensors = []; - for (var l = 0; l < r.tensors.length; ++l) { - if (typeof r.tensors[l] != 'object') - throw TypeError('.onnx.AttributeProto.tensors: object expected'); - a.tensors[l] = s.onnx.TensorProto.fromObject(r.tensors[l]); - } - } - if (r.graphs) { - if (!Array.isArray(r.graphs)) - throw TypeError('.onnx.AttributeProto.graphs: array expected'); - a.graphs = []; - for (var l = 0; l < r.graphs.length; ++l) { - if (typeof r.graphs[l] != 'object') - throw TypeError('.onnx.AttributeProto.graphs: object expected'); - a.graphs[l] = s.onnx.GraphProto.fromObject(r.graphs[l]); - } - } - if (r.sparseTensors) { - if (!Array.isArray(r.sparseTensors)) - throw TypeError('.onnx.AttributeProto.sparseTensors: array expected'); - a.sparseTensors = []; - for (var l = 0; l < r.sparseTensors.length; ++l) { - if (typeof r.sparseTensors[l] != 'object') - throw TypeError('.onnx.AttributeProto.sparseTensors: object expected'); - a.sparseTensors[l] = s.onnx.SparseTensorProto.fromObject(r.sparseTensors[l]); - } - } - if (r.typeProtos) { - if (!Array.isArray(r.typeProtos)) - throw TypeError('.onnx.AttributeProto.typeProtos: array expected'); - a.typeProtos = []; - for (var l = 0; l < r.typeProtos.length; ++l) { - if (typeof r.typeProtos[l] != 'object') - throw TypeError('.onnx.AttributeProto.typeProtos: object expected'); - a.typeProtos[l] = s.onnx.TypeProto.fromObject(r.typeProtos[l]); - } - } - return a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if ( - ((a.arrays || a.defaults) && - ((l.floats = []), - (l.ints = []), - (l.strings = []), - (l.tensors = []), - (l.graphs = []), - (l.typeProtos = []), - (l.sparseTensors = [])), - a.defaults) - ) { - if (((l.name = ''), (l.f = 0), n.Long)) { - var p = new n.Long(0, 0, !1); - l.i = a.longs === String ? p.toString() : a.longs === Number ? p.toNumber() : p; - } else l.i = a.longs === String ? '0' : 0; - a.bytes === String - ? (l.s = '') - : ((l.s = []), a.bytes !== Array && (l.s = n.newBuffer(l.s))), - (l.t = null), - (l.g = null), - (l.docString = ''), - (l.tp = null), - (l.type = a.enums === String ? 'UNDEFINED' : 0), - (l.refAttrName = ''), - (l.sparseTensor = null); - } - if ( - (r.name != null && r.hasOwnProperty('name') && (l.name = r.name), - r.f != null && - r.hasOwnProperty('f') && - (l.f = a.json && !isFinite(r.f) ? String(r.f) : r.f), - r.i != null && - r.hasOwnProperty('i') && - (typeof r.i == 'number' - ? (l.i = a.longs === String ? String(r.i) : r.i) - : (l.i = - a.longs === String - ? n.Long.prototype.toString.call(r.i) - : a.longs === Number - ? new n.LongBits(r.i.low >>> 0, r.i.high >>> 0).toNumber() - : r.i)), - r.s != null && - r.hasOwnProperty('s') && - (l.s = - a.bytes === String - ? n.base64.encode(r.s, 0, r.s.length) - : a.bytes === Array - ? Array.prototype.slice.call(r.s) - : r.s), - r.t != null && r.hasOwnProperty('t') && (l.t = s.onnx.TensorProto.toObject(r.t, a)), - r.g != null && r.hasOwnProperty('g') && (l.g = s.onnx.GraphProto.toObject(r.g, a)), - r.floats && r.floats.length) - ) { - l.floats = []; - for (var m = 0; m < r.floats.length; ++m) - l.floats[m] = a.json && !isFinite(r.floats[m]) ? String(r.floats[m]) : r.floats[m]; - } - if (r.ints && r.ints.length) { - l.ints = []; - for (var m = 0; m < r.ints.length; ++m) - typeof r.ints[m] == 'number' - ? (l.ints[m] = a.longs === String ? String(r.ints[m]) : r.ints[m]) - : (l.ints[m] = - a.longs === String - ? n.Long.prototype.toString.call(r.ints[m]) - : a.longs === Number - ? new n.LongBits(r.ints[m].low >>> 0, r.ints[m].high >>> 0).toNumber() - : r.ints[m]); - } - if (r.strings && r.strings.length) { - l.strings = []; - for (var m = 0; m < r.strings.length; ++m) - l.strings[m] = - a.bytes === String - ? n.base64.encode(r.strings[m], 0, r.strings[m].length) - : a.bytes === Array - ? Array.prototype.slice.call(r.strings[m]) - : r.strings[m]; - } - if (r.tensors && r.tensors.length) { - l.tensors = []; - for (var m = 0; m < r.tensors.length; ++m) - l.tensors[m] = s.onnx.TensorProto.toObject(r.tensors[m], a); - } - if (r.graphs && r.graphs.length) { - l.graphs = []; - for (var m = 0; m < r.graphs.length; ++m) - l.graphs[m] = s.onnx.GraphProto.toObject(r.graphs[m], a); - } - if ( - (r.docString != null && r.hasOwnProperty('docString') && (l.docString = r.docString), - r.tp != null && r.hasOwnProperty('tp') && (l.tp = s.onnx.TypeProto.toObject(r.tp, a)), - r.typeProtos && r.typeProtos.length) - ) { - l.typeProtos = []; - for (var m = 0; m < r.typeProtos.length; ++m) - l.typeProtos[m] = s.onnx.TypeProto.toObject(r.typeProtos[m], a); - } - if ( - (r.type != null && - r.hasOwnProperty('type') && - (l.type = - a.enums === String - ? s.onnx.AttributeProto.AttributeType[r.type] === void 0 - ? r.type - : s.onnx.AttributeProto.AttributeType[r.type] - : r.type), - r.refAttrName != null && - r.hasOwnProperty('refAttrName') && - (l.refAttrName = r.refAttrName), - r.sparseTensor != null && - r.hasOwnProperty('sparseTensor') && - (l.sparseTensor = s.onnx.SparseTensorProto.toObject(r.sparseTensor, a)), - r.sparseTensors && r.sparseTensors.length) - ) { - l.sparseTensors = []; - for (var m = 0; m < r.sparseTensors.length; ++m) - l.sparseTensors[m] = s.onnx.SparseTensorProto.toObject(r.sparseTensors[m], a); - } - return l; - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.AttributeProto'; - }), - (f.AttributeType = (function () { - var r = {}, - a = Object.create(r); - return ( - (a[(r[0] = 'UNDEFINED')] = 0), - (a[(r[1] = 'FLOAT')] = 1), - (a[(r[2] = 'INT')] = 2), - (a[(r[3] = 'STRING')] = 3), - (a[(r[4] = 'TENSOR')] = 4), - (a[(r[5] = 'GRAPH')] = 5), - (a[(r[11] = 'SPARSE_TENSOR')] = 11), - (a[(r[13] = 'TYPE_PROTO')] = 13), - (a[(r[6] = 'FLOATS')] = 6), - (a[(r[7] = 'INTS')] = 7), - (a[(r[8] = 'STRINGS')] = 8), - (a[(r[9] = 'TENSORS')] = 9), - (a[(r[10] = 'GRAPHS')] = 10), - (a[(r[12] = 'SPARSE_TENSORS')] = 12), - (a[(r[14] = 'TYPE_PROTOS')] = 14), - a - ); - })()), - f - ); - })()), - (d.ValueInfoProto = (function () { - function f(r) { - if (r) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.name = ''), - (f.prototype.type = null), - (f.prototype.docString = ''), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - return ( - a || (a = u.create()), - r.name != null && Object.hasOwnProperty.call(r, 'name') && a.uint32(10).string(r.name), - r.type != null && - Object.hasOwnProperty.call(r, 'type') && - s.onnx.TypeProto.encode(r.type, a.uint32(18).fork()).ldelim(), - r.docString != null && - Object.hasOwnProperty.call(r, 'docString') && - a.uint32(26).string(r.docString), - a - ); - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for ( - var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.ValueInfoProto(); - r.pos < l; - - ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - p.name = r.string(); - break; - } - case 2: { - p.type = s.onnx.TypeProto.decode(r, r.uint32()); - break; - } - case 3: { - p.docString = r.string(); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if (r.name != null && r.hasOwnProperty('name') && !n.isString(r.name)) - return 'name: string expected'; - if (r.type != null && r.hasOwnProperty('type')) { - var a = s.onnx.TypeProto.verify(r.type); - if (a) return 'type.' + a; - } - return r.docString != null && r.hasOwnProperty('docString') && !n.isString(r.docString) - ? 'docString: string expected' - : null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.ValueInfoProto) return r; - var a = new s.onnx.ValueInfoProto(); - if ((r.name != null && (a.name = String(r.name)), r.type != null)) { - if (typeof r.type != 'object') - throw TypeError('.onnx.ValueInfoProto.type: object expected'); - a.type = s.onnx.TypeProto.fromObject(r.type); - } - return r.docString != null && (a.docString = String(r.docString)), a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - return ( - a.defaults && ((l.name = ''), (l.type = null), (l.docString = '')), - r.name != null && r.hasOwnProperty('name') && (l.name = r.name), - r.type != null && - r.hasOwnProperty('type') && - (l.type = s.onnx.TypeProto.toObject(r.type, a)), - r.docString != null && r.hasOwnProperty('docString') && (l.docString = r.docString), - l - ); - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.ValueInfoProto'; - }), - f - ); - })()), - (d.NodeProto = (function () { - function f(r) { - if (((this.input = []), (this.output = []), (this.attribute = []), r)) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.input = n.emptyArray), - (f.prototype.output = n.emptyArray), - (f.prototype.name = ''), - (f.prototype.opType = ''), - (f.prototype.domain = ''), - (f.prototype.attribute = n.emptyArray), - (f.prototype.docString = ''), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - if ((a || (a = u.create()), r.input != null && r.input.length)) - for (var l = 0; l < r.input.length; ++l) a.uint32(10).string(r.input[l]); - if (r.output != null && r.output.length) - for (var l = 0; l < r.output.length; ++l) a.uint32(18).string(r.output[l]); - if ( - (r.name != null && Object.hasOwnProperty.call(r, 'name') && a.uint32(26).string(r.name), - r.opType != null && - Object.hasOwnProperty.call(r, 'opType') && - a.uint32(34).string(r.opType), - r.attribute != null && r.attribute.length) - ) - for (var l = 0; l < r.attribute.length; ++l) - s.onnx.AttributeProto.encode(r.attribute[l], a.uint32(42).fork()).ldelim(); - return ( - r.docString != null && - Object.hasOwnProperty.call(r, 'docString') && - a.uint32(50).string(r.docString), - r.domain != null && - Object.hasOwnProperty.call(r, 'domain') && - a.uint32(58).string(r.domain), - a - ); - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for (var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.NodeProto(); r.pos < l; ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - (p.input && p.input.length) || (p.input = []), p.input.push(r.string()); - break; - } - case 2: { - (p.output && p.output.length) || (p.output = []), p.output.push(r.string()); - break; - } - case 3: { - p.name = r.string(); - break; - } - case 4: { - p.opType = r.string(); - break; - } - case 7: { - p.domain = r.string(); - break; - } - case 5: { - (p.attribute && p.attribute.length) || (p.attribute = []), - p.attribute.push(s.onnx.AttributeProto.decode(r, r.uint32())); - break; - } - case 6: { - p.docString = r.string(); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if (r.input != null && r.hasOwnProperty('input')) { - if (!Array.isArray(r.input)) return 'input: array expected'; - for (var a = 0; a < r.input.length; ++a) - if (!n.isString(r.input[a])) return 'input: string[] expected'; - } - if (r.output != null && r.hasOwnProperty('output')) { - if (!Array.isArray(r.output)) return 'output: array expected'; - for (var a = 0; a < r.output.length; ++a) - if (!n.isString(r.output[a])) return 'output: string[] expected'; - } - if (r.name != null && r.hasOwnProperty('name') && !n.isString(r.name)) - return 'name: string expected'; - if (r.opType != null && r.hasOwnProperty('opType') && !n.isString(r.opType)) - return 'opType: string expected'; - if (r.domain != null && r.hasOwnProperty('domain') && !n.isString(r.domain)) - return 'domain: string expected'; - if (r.attribute != null && r.hasOwnProperty('attribute')) { - if (!Array.isArray(r.attribute)) return 'attribute: array expected'; - for (var a = 0; a < r.attribute.length; ++a) { - var l = s.onnx.AttributeProto.verify(r.attribute[a]); - if (l) return 'attribute.' + l; - } - } - return r.docString != null && r.hasOwnProperty('docString') && !n.isString(r.docString) - ? 'docString: string expected' - : null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.NodeProto) return r; - var a = new s.onnx.NodeProto(); - if (r.input) { - if (!Array.isArray(r.input)) throw TypeError('.onnx.NodeProto.input: array expected'); - a.input = []; - for (var l = 0; l < r.input.length; ++l) a.input[l] = String(r.input[l]); - } - if (r.output) { - if (!Array.isArray(r.output)) throw TypeError('.onnx.NodeProto.output: array expected'); - a.output = []; - for (var l = 0; l < r.output.length; ++l) a.output[l] = String(r.output[l]); - } - if ( - (r.name != null && (a.name = String(r.name)), - r.opType != null && (a.opType = String(r.opType)), - r.domain != null && (a.domain = String(r.domain)), - r.attribute) - ) { - if (!Array.isArray(r.attribute)) - throw TypeError('.onnx.NodeProto.attribute: array expected'); - a.attribute = []; - for (var l = 0; l < r.attribute.length; ++l) { - if (typeof r.attribute[l] != 'object') - throw TypeError('.onnx.NodeProto.attribute: object expected'); - a.attribute[l] = s.onnx.AttributeProto.fromObject(r.attribute[l]); - } - } - return r.docString != null && (a.docString = String(r.docString)), a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if ( - ((a.arrays || a.defaults) && ((l.input = []), (l.output = []), (l.attribute = [])), - a.defaults && ((l.name = ''), (l.opType = ''), (l.docString = ''), (l.domain = '')), - r.input && r.input.length) - ) { - l.input = []; - for (var p = 0; p < r.input.length; ++p) l.input[p] = r.input[p]; - } - if (r.output && r.output.length) { - l.output = []; - for (var p = 0; p < r.output.length; ++p) l.output[p] = r.output[p]; - } - if ( - (r.name != null && r.hasOwnProperty('name') && (l.name = r.name), - r.opType != null && r.hasOwnProperty('opType') && (l.opType = r.opType), - r.attribute && r.attribute.length) - ) { - l.attribute = []; - for (var p = 0; p < r.attribute.length; ++p) - l.attribute[p] = s.onnx.AttributeProto.toObject(r.attribute[p], a); - } - return ( - r.docString != null && r.hasOwnProperty('docString') && (l.docString = r.docString), - r.domain != null && r.hasOwnProperty('domain') && (l.domain = r.domain), - l - ); - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.NodeProto'; - }), - f - ); - })()), - (d.TrainingInfoProto = (function () { - function f(r) { - if (((this.initializationBinding = []), (this.updateBinding = []), r)) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.initialization = null), - (f.prototype.algorithm = null), - (f.prototype.initializationBinding = n.emptyArray), - (f.prototype.updateBinding = n.emptyArray), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - if ( - (a || (a = u.create()), - r.initialization != null && - Object.hasOwnProperty.call(r, 'initialization') && - s.onnx.GraphProto.encode(r.initialization, a.uint32(10).fork()).ldelim(), - r.algorithm != null && - Object.hasOwnProperty.call(r, 'algorithm') && - s.onnx.GraphProto.encode(r.algorithm, a.uint32(18).fork()).ldelim(), - r.initializationBinding != null && r.initializationBinding.length) - ) - for (var l = 0; l < r.initializationBinding.length; ++l) - s.onnx.StringStringEntryProto.encode( - r.initializationBinding[l], - a.uint32(26).fork() - ).ldelim(); - if (r.updateBinding != null && r.updateBinding.length) - for (var l = 0; l < r.updateBinding.length; ++l) - s.onnx.StringStringEntryProto.encode( - r.updateBinding[l], - a.uint32(34).fork() - ).ldelim(); - return a; - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for ( - var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.TrainingInfoProto(); - r.pos < l; - - ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - p.initialization = s.onnx.GraphProto.decode(r, r.uint32()); - break; - } - case 2: { - p.algorithm = s.onnx.GraphProto.decode(r, r.uint32()); - break; - } - case 3: { - (p.initializationBinding && p.initializationBinding.length) || - (p.initializationBinding = []), - p.initializationBinding.push( - s.onnx.StringStringEntryProto.decode(r, r.uint32()) - ); - break; - } - case 4: { - (p.updateBinding && p.updateBinding.length) || (p.updateBinding = []), - p.updateBinding.push(s.onnx.StringStringEntryProto.decode(r, r.uint32())); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if (r.initialization != null && r.hasOwnProperty('initialization')) { - var a = s.onnx.GraphProto.verify(r.initialization); - if (a) return 'initialization.' + a; - } - if (r.algorithm != null && r.hasOwnProperty('algorithm')) { - var a = s.onnx.GraphProto.verify(r.algorithm); - if (a) return 'algorithm.' + a; - } - if (r.initializationBinding != null && r.hasOwnProperty('initializationBinding')) { - if (!Array.isArray(r.initializationBinding)) - return 'initializationBinding: array expected'; - for (var l = 0; l < r.initializationBinding.length; ++l) { - var a = s.onnx.StringStringEntryProto.verify(r.initializationBinding[l]); - if (a) return 'initializationBinding.' + a; - } - } - if (r.updateBinding != null && r.hasOwnProperty('updateBinding')) { - if (!Array.isArray(r.updateBinding)) return 'updateBinding: array expected'; - for (var l = 0; l < r.updateBinding.length; ++l) { - var a = s.onnx.StringStringEntryProto.verify(r.updateBinding[l]); - if (a) return 'updateBinding.' + a; - } - } - return null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.TrainingInfoProto) return r; - var a = new s.onnx.TrainingInfoProto(); - if (r.initialization != null) { - if (typeof r.initialization != 'object') - throw TypeError('.onnx.TrainingInfoProto.initialization: object expected'); - a.initialization = s.onnx.GraphProto.fromObject(r.initialization); - } - if (r.algorithm != null) { - if (typeof r.algorithm != 'object') - throw TypeError('.onnx.TrainingInfoProto.algorithm: object expected'); - a.algorithm = s.onnx.GraphProto.fromObject(r.algorithm); - } - if (r.initializationBinding) { - if (!Array.isArray(r.initializationBinding)) - throw TypeError('.onnx.TrainingInfoProto.initializationBinding: array expected'); - a.initializationBinding = []; - for (var l = 0; l < r.initializationBinding.length; ++l) { - if (typeof r.initializationBinding[l] != 'object') - throw TypeError( - '.onnx.TrainingInfoProto.initializationBinding: object expected' - ); - a.initializationBinding[l] = s.onnx.StringStringEntryProto.fromObject( - r.initializationBinding[l] - ); - } - } - if (r.updateBinding) { - if (!Array.isArray(r.updateBinding)) - throw TypeError('.onnx.TrainingInfoProto.updateBinding: array expected'); - a.updateBinding = []; - for (var l = 0; l < r.updateBinding.length; ++l) { - if (typeof r.updateBinding[l] != 'object') - throw TypeError('.onnx.TrainingInfoProto.updateBinding: object expected'); - a.updateBinding[l] = s.onnx.StringStringEntryProto.fromObject(r.updateBinding[l]); - } - } - return a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if ( - ((a.arrays || a.defaults) && ((l.initializationBinding = []), (l.updateBinding = [])), - a.defaults && ((l.initialization = null), (l.algorithm = null)), - r.initialization != null && - r.hasOwnProperty('initialization') && - (l.initialization = s.onnx.GraphProto.toObject(r.initialization, a)), - r.algorithm != null && - r.hasOwnProperty('algorithm') && - (l.algorithm = s.onnx.GraphProto.toObject(r.algorithm, a)), - r.initializationBinding && r.initializationBinding.length) - ) { - l.initializationBinding = []; - for (var p = 0; p < r.initializationBinding.length; ++p) - l.initializationBinding[p] = s.onnx.StringStringEntryProto.toObject( - r.initializationBinding[p], - a - ); - } - if (r.updateBinding && r.updateBinding.length) { - l.updateBinding = []; - for (var p = 0; p < r.updateBinding.length; ++p) - l.updateBinding[p] = s.onnx.StringStringEntryProto.toObject(r.updateBinding[p], a); - } - return l; - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.TrainingInfoProto'; - }), - f - ); - })()), - (d.ModelProto = (function () { - function f(r) { - if ( - ((this.opsetImport = []), - (this.metadataProps = []), - (this.trainingInfo = []), - (this.functions = []), - r) - ) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.irVersion = n.Long ? n.Long.fromBits(0, 0, !1) : 0), - (f.prototype.opsetImport = n.emptyArray), - (f.prototype.producerName = ''), - (f.prototype.producerVersion = ''), - (f.prototype.domain = ''), - (f.prototype.modelVersion = n.Long ? n.Long.fromBits(0, 0, !1) : 0), - (f.prototype.docString = ''), - (f.prototype.graph = null), - (f.prototype.metadataProps = n.emptyArray), - (f.prototype.trainingInfo = n.emptyArray), - (f.prototype.functions = n.emptyArray), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - if ( - (a || (a = u.create()), - r.irVersion != null && - Object.hasOwnProperty.call(r, 'irVersion') && - a.uint32(8).int64(r.irVersion), - r.producerName != null && - Object.hasOwnProperty.call(r, 'producerName') && - a.uint32(18).string(r.producerName), - r.producerVersion != null && - Object.hasOwnProperty.call(r, 'producerVersion') && - a.uint32(26).string(r.producerVersion), - r.domain != null && - Object.hasOwnProperty.call(r, 'domain') && - a.uint32(34).string(r.domain), - r.modelVersion != null && - Object.hasOwnProperty.call(r, 'modelVersion') && - a.uint32(40).int64(r.modelVersion), - r.docString != null && - Object.hasOwnProperty.call(r, 'docString') && - a.uint32(50).string(r.docString), - r.graph != null && - Object.hasOwnProperty.call(r, 'graph') && - s.onnx.GraphProto.encode(r.graph, a.uint32(58).fork()).ldelim(), - r.opsetImport != null && r.opsetImport.length) - ) - for (var l = 0; l < r.opsetImport.length; ++l) - s.onnx.OperatorSetIdProto.encode(r.opsetImport[l], a.uint32(66).fork()).ldelim(); - if (r.metadataProps != null && r.metadataProps.length) - for (var l = 0; l < r.metadataProps.length; ++l) - s.onnx.StringStringEntryProto.encode( - r.metadataProps[l], - a.uint32(114).fork() - ).ldelim(); - if (r.trainingInfo != null && r.trainingInfo.length) - for (var l = 0; l < r.trainingInfo.length; ++l) - s.onnx.TrainingInfoProto.encode(r.trainingInfo[l], a.uint32(162).fork()).ldelim(); - if (r.functions != null && r.functions.length) - for (var l = 0; l < r.functions.length; ++l) - s.onnx.FunctionProto.encode(r.functions[l], a.uint32(202).fork()).ldelim(); - return a; - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for (var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.ModelProto(); r.pos < l; ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - p.irVersion = r.int64(); - break; - } - case 8: { - (p.opsetImport && p.opsetImport.length) || (p.opsetImport = []), - p.opsetImport.push(s.onnx.OperatorSetIdProto.decode(r, r.uint32())); - break; - } - case 2: { - p.producerName = r.string(); - break; - } - case 3: { - p.producerVersion = r.string(); - break; - } - case 4: { - p.domain = r.string(); - break; - } - case 5: { - p.modelVersion = r.int64(); - break; - } - case 6: { - p.docString = r.string(); - break; - } - case 7: { - p.graph = s.onnx.GraphProto.decode(r, r.uint32()); - break; - } - case 14: { - (p.metadataProps && p.metadataProps.length) || (p.metadataProps = []), - p.metadataProps.push(s.onnx.StringStringEntryProto.decode(r, r.uint32())); - break; - } - case 20: { - (p.trainingInfo && p.trainingInfo.length) || (p.trainingInfo = []), - p.trainingInfo.push(s.onnx.TrainingInfoProto.decode(r, r.uint32())); - break; - } - case 25: { - (p.functions && p.functions.length) || (p.functions = []), - p.functions.push(s.onnx.FunctionProto.decode(r, r.uint32())); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if ( - r.irVersion != null && - r.hasOwnProperty('irVersion') && - !n.isInteger(r.irVersion) && - !(r.irVersion && n.isInteger(r.irVersion.low) && n.isInteger(r.irVersion.high)) - ) - return 'irVersion: integer|Long expected'; - if (r.opsetImport != null && r.hasOwnProperty('opsetImport')) { - if (!Array.isArray(r.opsetImport)) return 'opsetImport: array expected'; - for (var a = 0; a < r.opsetImport.length; ++a) { - var l = s.onnx.OperatorSetIdProto.verify(r.opsetImport[a]); - if (l) return 'opsetImport.' + l; - } - } - if ( - r.producerName != null && - r.hasOwnProperty('producerName') && - !n.isString(r.producerName) - ) - return 'producerName: string expected'; - if ( - r.producerVersion != null && - r.hasOwnProperty('producerVersion') && - !n.isString(r.producerVersion) - ) - return 'producerVersion: string expected'; - if (r.domain != null && r.hasOwnProperty('domain') && !n.isString(r.domain)) - return 'domain: string expected'; - if ( - r.modelVersion != null && - r.hasOwnProperty('modelVersion') && - !n.isInteger(r.modelVersion) && - !(r.modelVersion && n.isInteger(r.modelVersion.low) && n.isInteger(r.modelVersion.high)) - ) - return 'modelVersion: integer|Long expected'; - if (r.docString != null && r.hasOwnProperty('docString') && !n.isString(r.docString)) - return 'docString: string expected'; - if (r.graph != null && r.hasOwnProperty('graph')) { - var l = s.onnx.GraphProto.verify(r.graph); - if (l) return 'graph.' + l; - } - if (r.metadataProps != null && r.hasOwnProperty('metadataProps')) { - if (!Array.isArray(r.metadataProps)) return 'metadataProps: array expected'; - for (var a = 0; a < r.metadataProps.length; ++a) { - var l = s.onnx.StringStringEntryProto.verify(r.metadataProps[a]); - if (l) return 'metadataProps.' + l; - } - } - if (r.trainingInfo != null && r.hasOwnProperty('trainingInfo')) { - if (!Array.isArray(r.trainingInfo)) return 'trainingInfo: array expected'; - for (var a = 0; a < r.trainingInfo.length; ++a) { - var l = s.onnx.TrainingInfoProto.verify(r.trainingInfo[a]); - if (l) return 'trainingInfo.' + l; - } - } - if (r.functions != null && r.hasOwnProperty('functions')) { - if (!Array.isArray(r.functions)) return 'functions: array expected'; - for (var a = 0; a < r.functions.length; ++a) { - var l = s.onnx.FunctionProto.verify(r.functions[a]); - if (l) return 'functions.' + l; - } - } - return null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.ModelProto) return r; - var a = new s.onnx.ModelProto(); - if ( - (r.irVersion != null && - (n.Long - ? ((a.irVersion = n.Long.fromValue(r.irVersion)).unsigned = !1) - : typeof r.irVersion == 'string' - ? (a.irVersion = parseInt(r.irVersion, 10)) - : typeof r.irVersion == 'number' - ? (a.irVersion = r.irVersion) - : typeof r.irVersion == 'object' && - (a.irVersion = new n.LongBits( - r.irVersion.low >>> 0, - r.irVersion.high >>> 0 - ).toNumber())), - r.opsetImport) - ) { - if (!Array.isArray(r.opsetImport)) - throw TypeError('.onnx.ModelProto.opsetImport: array expected'); - a.opsetImport = []; - for (var l = 0; l < r.opsetImport.length; ++l) { - if (typeof r.opsetImport[l] != 'object') - throw TypeError('.onnx.ModelProto.opsetImport: object expected'); - a.opsetImport[l] = s.onnx.OperatorSetIdProto.fromObject(r.opsetImport[l]); - } - } - if ( - (r.producerName != null && (a.producerName = String(r.producerName)), - r.producerVersion != null && (a.producerVersion = String(r.producerVersion)), - r.domain != null && (a.domain = String(r.domain)), - r.modelVersion != null && - (n.Long - ? ((a.modelVersion = n.Long.fromValue(r.modelVersion)).unsigned = !1) - : typeof r.modelVersion == 'string' - ? (a.modelVersion = parseInt(r.modelVersion, 10)) - : typeof r.modelVersion == 'number' - ? (a.modelVersion = r.modelVersion) - : typeof r.modelVersion == 'object' && - (a.modelVersion = new n.LongBits( - r.modelVersion.low >>> 0, - r.modelVersion.high >>> 0 - ).toNumber())), - r.docString != null && (a.docString = String(r.docString)), - r.graph != null) - ) { - if (typeof r.graph != 'object') - throw TypeError('.onnx.ModelProto.graph: object expected'); - a.graph = s.onnx.GraphProto.fromObject(r.graph); - } - if (r.metadataProps) { - if (!Array.isArray(r.metadataProps)) - throw TypeError('.onnx.ModelProto.metadataProps: array expected'); - a.metadataProps = []; - for (var l = 0; l < r.metadataProps.length; ++l) { - if (typeof r.metadataProps[l] != 'object') - throw TypeError('.onnx.ModelProto.metadataProps: object expected'); - a.metadataProps[l] = s.onnx.StringStringEntryProto.fromObject(r.metadataProps[l]); - } - } - if (r.trainingInfo) { - if (!Array.isArray(r.trainingInfo)) - throw TypeError('.onnx.ModelProto.trainingInfo: array expected'); - a.trainingInfo = []; - for (var l = 0; l < r.trainingInfo.length; ++l) { - if (typeof r.trainingInfo[l] != 'object') - throw TypeError('.onnx.ModelProto.trainingInfo: object expected'); - a.trainingInfo[l] = s.onnx.TrainingInfoProto.fromObject(r.trainingInfo[l]); - } - } - if (r.functions) { - if (!Array.isArray(r.functions)) - throw TypeError('.onnx.ModelProto.functions: array expected'); - a.functions = []; - for (var l = 0; l < r.functions.length; ++l) { - if (typeof r.functions[l] != 'object') - throw TypeError('.onnx.ModelProto.functions: object expected'); - a.functions[l] = s.onnx.FunctionProto.fromObject(r.functions[l]); - } - } - return a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if ( - ((a.arrays || a.defaults) && - ((l.opsetImport = []), - (l.metadataProps = []), - (l.trainingInfo = []), - (l.functions = [])), - a.defaults) - ) { - if (n.Long) { - var p = new n.Long(0, 0, !1); - l.irVersion = - a.longs === String ? p.toString() : a.longs === Number ? p.toNumber() : p; - } else l.irVersion = a.longs === String ? '0' : 0; - if (((l.producerName = ''), (l.producerVersion = ''), (l.domain = ''), n.Long)) { - var p = new n.Long(0, 0, !1); - l.modelVersion = - a.longs === String ? p.toString() : a.longs === Number ? p.toNumber() : p; - } else l.modelVersion = a.longs === String ? '0' : 0; - (l.docString = ''), (l.graph = null); - } - if ( - (r.irVersion != null && - r.hasOwnProperty('irVersion') && - (typeof r.irVersion == 'number' - ? (l.irVersion = a.longs === String ? String(r.irVersion) : r.irVersion) - : (l.irVersion = - a.longs === String - ? n.Long.prototype.toString.call(r.irVersion) - : a.longs === Number - ? new n.LongBits( - r.irVersion.low >>> 0, - r.irVersion.high >>> 0 - ).toNumber() - : r.irVersion)), - r.producerName != null && - r.hasOwnProperty('producerName') && - (l.producerName = r.producerName), - r.producerVersion != null && - r.hasOwnProperty('producerVersion') && - (l.producerVersion = r.producerVersion), - r.domain != null && r.hasOwnProperty('domain') && (l.domain = r.domain), - r.modelVersion != null && - r.hasOwnProperty('modelVersion') && - (typeof r.modelVersion == 'number' - ? (l.modelVersion = - a.longs === String ? String(r.modelVersion) : r.modelVersion) - : (l.modelVersion = - a.longs === String - ? n.Long.prototype.toString.call(r.modelVersion) - : a.longs === Number - ? new n.LongBits( - r.modelVersion.low >>> 0, - r.modelVersion.high >>> 0 - ).toNumber() - : r.modelVersion)), - r.docString != null && r.hasOwnProperty('docString') && (l.docString = r.docString), - r.graph != null && - r.hasOwnProperty('graph') && - (l.graph = s.onnx.GraphProto.toObject(r.graph, a)), - r.opsetImport && r.opsetImport.length) - ) { - l.opsetImport = []; - for (var m = 0; m < r.opsetImport.length; ++m) - l.opsetImport[m] = s.onnx.OperatorSetIdProto.toObject(r.opsetImport[m], a); - } - if (r.metadataProps && r.metadataProps.length) { - l.metadataProps = []; - for (var m = 0; m < r.metadataProps.length; ++m) - l.metadataProps[m] = s.onnx.StringStringEntryProto.toObject(r.metadataProps[m], a); - } - if (r.trainingInfo && r.trainingInfo.length) { - l.trainingInfo = []; - for (var m = 0; m < r.trainingInfo.length; ++m) - l.trainingInfo[m] = s.onnx.TrainingInfoProto.toObject(r.trainingInfo[m], a); - } - if (r.functions && r.functions.length) { - l.functions = []; - for (var m = 0; m < r.functions.length; ++m) - l.functions[m] = s.onnx.FunctionProto.toObject(r.functions[m], a); - } - return l; - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.ModelProto'; - }), - f - ); - })()), - (d.StringStringEntryProto = (function () { - function f(r) { - if (r) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.key = ''), - (f.prototype.value = ''), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - return ( - a || (a = u.create()), - r.key != null && Object.hasOwnProperty.call(r, 'key') && a.uint32(10).string(r.key), - r.value != null && - Object.hasOwnProperty.call(r, 'value') && - a.uint32(18).string(r.value), - a - ); - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for ( - var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.StringStringEntryProto(); - r.pos < l; - - ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - p.key = r.string(); - break; - } - case 2: { - p.value = r.string(); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - return typeof r != 'object' || r === null - ? 'object expected' - : r.key != null && r.hasOwnProperty('key') && !n.isString(r.key) - ? 'key: string expected' - : r.value != null && r.hasOwnProperty('value') && !n.isString(r.value) - ? 'value: string expected' - : null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.StringStringEntryProto) return r; - var a = new s.onnx.StringStringEntryProto(); - return ( - r.key != null && (a.key = String(r.key)), - r.value != null && (a.value = String(r.value)), - a - ); - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - return ( - a.defaults && ((l.key = ''), (l.value = '')), - r.key != null && r.hasOwnProperty('key') && (l.key = r.key), - r.value != null && r.hasOwnProperty('value') && (l.value = r.value), - l - ); - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.StringStringEntryProto'; - }), - f - ); - })()), - (d.TensorAnnotation = (function () { - function f(r) { - if (((this.quantParameterTensorNames = []), r)) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.tensorName = ''), - (f.prototype.quantParameterTensorNames = n.emptyArray), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - if ( - (a || (a = u.create()), - r.tensorName != null && - Object.hasOwnProperty.call(r, 'tensorName') && - a.uint32(10).string(r.tensorName), - r.quantParameterTensorNames != null && r.quantParameterTensorNames.length) - ) - for (var l = 0; l < r.quantParameterTensorNames.length; ++l) - s.onnx.StringStringEntryProto.encode( - r.quantParameterTensorNames[l], - a.uint32(18).fork() - ).ldelim(); - return a; - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for ( - var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.TensorAnnotation(); - r.pos < l; - - ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - p.tensorName = r.string(); - break; - } - case 2: { - (p.quantParameterTensorNames && p.quantParameterTensorNames.length) || - (p.quantParameterTensorNames = []), - p.quantParameterTensorNames.push( - s.onnx.StringStringEntryProto.decode(r, r.uint32()) - ); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if (r.tensorName != null && r.hasOwnProperty('tensorName') && !n.isString(r.tensorName)) - return 'tensorName: string expected'; - if (r.quantParameterTensorNames != null && r.hasOwnProperty('quantParameterTensorNames')) { - if (!Array.isArray(r.quantParameterTensorNames)) - return 'quantParameterTensorNames: array expected'; - for (var a = 0; a < r.quantParameterTensorNames.length; ++a) { - var l = s.onnx.StringStringEntryProto.verify(r.quantParameterTensorNames[a]); - if (l) return 'quantParameterTensorNames.' + l; - } - } - return null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.TensorAnnotation) return r; - var a = new s.onnx.TensorAnnotation(); - if ( - (r.tensorName != null && (a.tensorName = String(r.tensorName)), - r.quantParameterTensorNames) - ) { - if (!Array.isArray(r.quantParameterTensorNames)) - throw TypeError('.onnx.TensorAnnotation.quantParameterTensorNames: array expected'); - a.quantParameterTensorNames = []; - for (var l = 0; l < r.quantParameterTensorNames.length; ++l) { - if (typeof r.quantParameterTensorNames[l] != 'object') - throw TypeError( - '.onnx.TensorAnnotation.quantParameterTensorNames: object expected' - ); - a.quantParameterTensorNames[l] = s.onnx.StringStringEntryProto.fromObject( - r.quantParameterTensorNames[l] - ); - } - } - return a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if ( - ((a.arrays || a.defaults) && (l.quantParameterTensorNames = []), - a.defaults && (l.tensorName = ''), - r.tensorName != null && r.hasOwnProperty('tensorName') && (l.tensorName = r.tensorName), - r.quantParameterTensorNames && r.quantParameterTensorNames.length) - ) { - l.quantParameterTensorNames = []; - for (var p = 0; p < r.quantParameterTensorNames.length; ++p) - l.quantParameterTensorNames[p] = s.onnx.StringStringEntryProto.toObject( - r.quantParameterTensorNames[p], - a - ); - } - return l; - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.TensorAnnotation'; - }), - f - ); - })()), - (d.GraphProto = (function () { - function f(r) { - if ( - ((this.node = []), - (this.initializer = []), - (this.sparseInitializer = []), - (this.input = []), - (this.output = []), - (this.valueInfo = []), - (this.quantizationAnnotation = []), - r) - ) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.node = n.emptyArray), - (f.prototype.name = ''), - (f.prototype.initializer = n.emptyArray), - (f.prototype.sparseInitializer = n.emptyArray), - (f.prototype.docString = ''), - (f.prototype.input = n.emptyArray), - (f.prototype.output = n.emptyArray), - (f.prototype.valueInfo = n.emptyArray), - (f.prototype.quantizationAnnotation = n.emptyArray), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - if ((a || (a = u.create()), r.node != null && r.node.length)) - for (var l = 0; l < r.node.length; ++l) - s.onnx.NodeProto.encode(r.node[l], a.uint32(10).fork()).ldelim(); - if ( - (r.name != null && Object.hasOwnProperty.call(r, 'name') && a.uint32(18).string(r.name), - r.initializer != null && r.initializer.length) - ) - for (var l = 0; l < r.initializer.length; ++l) - s.onnx.TensorProto.encode(r.initializer[l], a.uint32(42).fork()).ldelim(); - if ( - (r.docString != null && - Object.hasOwnProperty.call(r, 'docString') && - a.uint32(82).string(r.docString), - r.input != null && r.input.length) - ) - for (var l = 0; l < r.input.length; ++l) - s.onnx.ValueInfoProto.encode(r.input[l], a.uint32(90).fork()).ldelim(); - if (r.output != null && r.output.length) - for (var l = 0; l < r.output.length; ++l) - s.onnx.ValueInfoProto.encode(r.output[l], a.uint32(98).fork()).ldelim(); - if (r.valueInfo != null && r.valueInfo.length) - for (var l = 0; l < r.valueInfo.length; ++l) - s.onnx.ValueInfoProto.encode(r.valueInfo[l], a.uint32(106).fork()).ldelim(); - if (r.quantizationAnnotation != null && r.quantizationAnnotation.length) - for (var l = 0; l < r.quantizationAnnotation.length; ++l) - s.onnx.TensorAnnotation.encode( - r.quantizationAnnotation[l], - a.uint32(114).fork() - ).ldelim(); - if (r.sparseInitializer != null && r.sparseInitializer.length) - for (var l = 0; l < r.sparseInitializer.length; ++l) - s.onnx.SparseTensorProto.encode( - r.sparseInitializer[l], - a.uint32(122).fork() - ).ldelim(); - return a; - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for (var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.GraphProto(); r.pos < l; ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - (p.node && p.node.length) || (p.node = []), - p.node.push(s.onnx.NodeProto.decode(r, r.uint32())); - break; - } - case 2: { - p.name = r.string(); - break; - } - case 5: { - (p.initializer && p.initializer.length) || (p.initializer = []), - p.initializer.push(s.onnx.TensorProto.decode(r, r.uint32())); - break; - } - case 15: { - (p.sparseInitializer && p.sparseInitializer.length) || - (p.sparseInitializer = []), - p.sparseInitializer.push(s.onnx.SparseTensorProto.decode(r, r.uint32())); - break; - } - case 10: { - p.docString = r.string(); - break; - } - case 11: { - (p.input && p.input.length) || (p.input = []), - p.input.push(s.onnx.ValueInfoProto.decode(r, r.uint32())); - break; - } - case 12: { - (p.output && p.output.length) || (p.output = []), - p.output.push(s.onnx.ValueInfoProto.decode(r, r.uint32())); - break; - } - case 13: { - (p.valueInfo && p.valueInfo.length) || (p.valueInfo = []), - p.valueInfo.push(s.onnx.ValueInfoProto.decode(r, r.uint32())); - break; - } - case 14: { - (p.quantizationAnnotation && p.quantizationAnnotation.length) || - (p.quantizationAnnotation = []), - p.quantizationAnnotation.push( - s.onnx.TensorAnnotation.decode(r, r.uint32()) - ); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if (r.node != null && r.hasOwnProperty('node')) { - if (!Array.isArray(r.node)) return 'node: array expected'; - for (var a = 0; a < r.node.length; ++a) { - var l = s.onnx.NodeProto.verify(r.node[a]); - if (l) return 'node.' + l; - } - } - if (r.name != null && r.hasOwnProperty('name') && !n.isString(r.name)) - return 'name: string expected'; - if (r.initializer != null && r.hasOwnProperty('initializer')) { - if (!Array.isArray(r.initializer)) return 'initializer: array expected'; - for (var a = 0; a < r.initializer.length; ++a) { - var l = s.onnx.TensorProto.verify(r.initializer[a]); - if (l) return 'initializer.' + l; - } - } - if (r.sparseInitializer != null && r.hasOwnProperty('sparseInitializer')) { - if (!Array.isArray(r.sparseInitializer)) return 'sparseInitializer: array expected'; - for (var a = 0; a < r.sparseInitializer.length; ++a) { - var l = s.onnx.SparseTensorProto.verify(r.sparseInitializer[a]); - if (l) return 'sparseInitializer.' + l; - } - } - if (r.docString != null && r.hasOwnProperty('docString') && !n.isString(r.docString)) - return 'docString: string expected'; - if (r.input != null && r.hasOwnProperty('input')) { - if (!Array.isArray(r.input)) return 'input: array expected'; - for (var a = 0; a < r.input.length; ++a) { - var l = s.onnx.ValueInfoProto.verify(r.input[a]); - if (l) return 'input.' + l; - } - } - if (r.output != null && r.hasOwnProperty('output')) { - if (!Array.isArray(r.output)) return 'output: array expected'; - for (var a = 0; a < r.output.length; ++a) { - var l = s.onnx.ValueInfoProto.verify(r.output[a]); - if (l) return 'output.' + l; - } - } - if (r.valueInfo != null && r.hasOwnProperty('valueInfo')) { - if (!Array.isArray(r.valueInfo)) return 'valueInfo: array expected'; - for (var a = 0; a < r.valueInfo.length; ++a) { - var l = s.onnx.ValueInfoProto.verify(r.valueInfo[a]); - if (l) return 'valueInfo.' + l; - } - } - if (r.quantizationAnnotation != null && r.hasOwnProperty('quantizationAnnotation')) { - if (!Array.isArray(r.quantizationAnnotation)) - return 'quantizationAnnotation: array expected'; - for (var a = 0; a < r.quantizationAnnotation.length; ++a) { - var l = s.onnx.TensorAnnotation.verify(r.quantizationAnnotation[a]); - if (l) return 'quantizationAnnotation.' + l; - } - } - return null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.GraphProto) return r; - var a = new s.onnx.GraphProto(); - if (r.node) { - if (!Array.isArray(r.node)) throw TypeError('.onnx.GraphProto.node: array expected'); - a.node = []; - for (var l = 0; l < r.node.length; ++l) { - if (typeof r.node[l] != 'object') - throw TypeError('.onnx.GraphProto.node: object expected'); - a.node[l] = s.onnx.NodeProto.fromObject(r.node[l]); - } - } - if ((r.name != null && (a.name = String(r.name)), r.initializer)) { - if (!Array.isArray(r.initializer)) - throw TypeError('.onnx.GraphProto.initializer: array expected'); - a.initializer = []; - for (var l = 0; l < r.initializer.length; ++l) { - if (typeof r.initializer[l] != 'object') - throw TypeError('.onnx.GraphProto.initializer: object expected'); - a.initializer[l] = s.onnx.TensorProto.fromObject(r.initializer[l]); - } - } - if (r.sparseInitializer) { - if (!Array.isArray(r.sparseInitializer)) - throw TypeError('.onnx.GraphProto.sparseInitializer: array expected'); - a.sparseInitializer = []; - for (var l = 0; l < r.sparseInitializer.length; ++l) { - if (typeof r.sparseInitializer[l] != 'object') - throw TypeError('.onnx.GraphProto.sparseInitializer: object expected'); - a.sparseInitializer[l] = s.onnx.SparseTensorProto.fromObject( - r.sparseInitializer[l] - ); - } - } - if ((r.docString != null && (a.docString = String(r.docString)), r.input)) { - if (!Array.isArray(r.input)) throw TypeError('.onnx.GraphProto.input: array expected'); - a.input = []; - for (var l = 0; l < r.input.length; ++l) { - if (typeof r.input[l] != 'object') - throw TypeError('.onnx.GraphProto.input: object expected'); - a.input[l] = s.onnx.ValueInfoProto.fromObject(r.input[l]); - } - } - if (r.output) { - if (!Array.isArray(r.output)) - throw TypeError('.onnx.GraphProto.output: array expected'); - a.output = []; - for (var l = 0; l < r.output.length; ++l) { - if (typeof r.output[l] != 'object') - throw TypeError('.onnx.GraphProto.output: object expected'); - a.output[l] = s.onnx.ValueInfoProto.fromObject(r.output[l]); - } - } - if (r.valueInfo) { - if (!Array.isArray(r.valueInfo)) - throw TypeError('.onnx.GraphProto.valueInfo: array expected'); - a.valueInfo = []; - for (var l = 0; l < r.valueInfo.length; ++l) { - if (typeof r.valueInfo[l] != 'object') - throw TypeError('.onnx.GraphProto.valueInfo: object expected'); - a.valueInfo[l] = s.onnx.ValueInfoProto.fromObject(r.valueInfo[l]); - } - } - if (r.quantizationAnnotation) { - if (!Array.isArray(r.quantizationAnnotation)) - throw TypeError('.onnx.GraphProto.quantizationAnnotation: array expected'); - a.quantizationAnnotation = []; - for (var l = 0; l < r.quantizationAnnotation.length; ++l) { - if (typeof r.quantizationAnnotation[l] != 'object') - throw TypeError('.onnx.GraphProto.quantizationAnnotation: object expected'); - a.quantizationAnnotation[l] = s.onnx.TensorAnnotation.fromObject( - r.quantizationAnnotation[l] - ); - } - } - return a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if ( - ((a.arrays || a.defaults) && - ((l.node = []), - (l.initializer = []), - (l.input = []), - (l.output = []), - (l.valueInfo = []), - (l.quantizationAnnotation = []), - (l.sparseInitializer = [])), - a.defaults && ((l.name = ''), (l.docString = '')), - r.node && r.node.length) - ) { - l.node = []; - for (var p = 0; p < r.node.length; ++p) - l.node[p] = s.onnx.NodeProto.toObject(r.node[p], a); - } - if ( - (r.name != null && r.hasOwnProperty('name') && (l.name = r.name), - r.initializer && r.initializer.length) - ) { - l.initializer = []; - for (var p = 0; p < r.initializer.length; ++p) - l.initializer[p] = s.onnx.TensorProto.toObject(r.initializer[p], a); - } - if ( - (r.docString != null && r.hasOwnProperty('docString') && (l.docString = r.docString), - r.input && r.input.length) - ) { - l.input = []; - for (var p = 0; p < r.input.length; ++p) - l.input[p] = s.onnx.ValueInfoProto.toObject(r.input[p], a); - } - if (r.output && r.output.length) { - l.output = []; - for (var p = 0; p < r.output.length; ++p) - l.output[p] = s.onnx.ValueInfoProto.toObject(r.output[p], a); - } - if (r.valueInfo && r.valueInfo.length) { - l.valueInfo = []; - for (var p = 0; p < r.valueInfo.length; ++p) - l.valueInfo[p] = s.onnx.ValueInfoProto.toObject(r.valueInfo[p], a); - } - if (r.quantizationAnnotation && r.quantizationAnnotation.length) { - l.quantizationAnnotation = []; - for (var p = 0; p < r.quantizationAnnotation.length; ++p) - l.quantizationAnnotation[p] = s.onnx.TensorAnnotation.toObject( - r.quantizationAnnotation[p], - a - ); - } - if (r.sparseInitializer && r.sparseInitializer.length) { - l.sparseInitializer = []; - for (var p = 0; p < r.sparseInitializer.length; ++p) - l.sparseInitializer[p] = s.onnx.SparseTensorProto.toObject( - r.sparseInitializer[p], - a - ); - } - return l; - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.GraphProto'; - }), - f - ); - })()), - (d.TensorProto = (function () { - function f(r) { - if ( - ((this.dims = []), - (this.floatData = []), - (this.int32Data = []), - (this.stringData = []), - (this.int64Data = []), - (this.externalData = []), - (this.doubleData = []), - (this.uint64Data = []), - r) - ) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.dims = n.emptyArray), - (f.prototype.dataType = 0), - (f.prototype.segment = null), - (f.prototype.floatData = n.emptyArray), - (f.prototype.int32Data = n.emptyArray), - (f.prototype.stringData = n.emptyArray), - (f.prototype.int64Data = n.emptyArray), - (f.prototype.name = ''), - (f.prototype.docString = ''), - (f.prototype.rawData = n.newBuffer([])), - (f.prototype.externalData = n.emptyArray), - (f.prototype.dataLocation = 0), - (f.prototype.doubleData = n.emptyArray), - (f.prototype.uint64Data = n.emptyArray), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - if ((a || (a = u.create()), r.dims != null && r.dims.length)) { - a.uint32(10).fork(); - for (var l = 0; l < r.dims.length; ++l) a.int64(r.dims[l]); - a.ldelim(); - } - if ( - (r.dataType != null && - Object.hasOwnProperty.call(r, 'dataType') && - a.uint32(16).int32(r.dataType), - r.segment != null && - Object.hasOwnProperty.call(r, 'segment') && - s.onnx.TensorProto.Segment.encode(r.segment, a.uint32(26).fork()).ldelim(), - r.floatData != null && r.floatData.length) - ) { - a.uint32(34).fork(); - for (var l = 0; l < r.floatData.length; ++l) a.float(r.floatData[l]); - a.ldelim(); - } - if (r.int32Data != null && r.int32Data.length) { - a.uint32(42).fork(); - for (var l = 0; l < r.int32Data.length; ++l) a.int32(r.int32Data[l]); - a.ldelim(); - } - if (r.stringData != null && r.stringData.length) - for (var l = 0; l < r.stringData.length; ++l) a.uint32(50).bytes(r.stringData[l]); - if (r.int64Data != null && r.int64Data.length) { - a.uint32(58).fork(); - for (var l = 0; l < r.int64Data.length; ++l) a.int64(r.int64Data[l]); - a.ldelim(); - } - if ( - (r.name != null && Object.hasOwnProperty.call(r, 'name') && a.uint32(66).string(r.name), - r.rawData != null && - Object.hasOwnProperty.call(r, 'rawData') && - a.uint32(74).bytes(r.rawData), - r.doubleData != null && r.doubleData.length) - ) { - a.uint32(82).fork(); - for (var l = 0; l < r.doubleData.length; ++l) a.double(r.doubleData[l]); - a.ldelim(); - } - if (r.uint64Data != null && r.uint64Data.length) { - a.uint32(90).fork(); - for (var l = 0; l < r.uint64Data.length; ++l) a.uint64(r.uint64Data[l]); - a.ldelim(); - } - if ( - (r.docString != null && - Object.hasOwnProperty.call(r, 'docString') && - a.uint32(98).string(r.docString), - r.externalData != null && r.externalData.length) - ) - for (var l = 0; l < r.externalData.length; ++l) - s.onnx.StringStringEntryProto.encode( - r.externalData[l], - a.uint32(106).fork() - ).ldelim(); - return ( - r.dataLocation != null && - Object.hasOwnProperty.call(r, 'dataLocation') && - a.uint32(112).int32(r.dataLocation), - a - ); - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for (var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.TensorProto(); r.pos < l; ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - if (((p.dims && p.dims.length) || (p.dims = []), (m & 7) === 2)) - for (var y = r.uint32() + r.pos; r.pos < y; ) p.dims.push(r.int64()); - else p.dims.push(r.int64()); - break; - } - case 2: { - p.dataType = r.int32(); - break; - } - case 3: { - p.segment = s.onnx.TensorProto.Segment.decode(r, r.uint32()); - break; - } - case 4: { - if (((p.floatData && p.floatData.length) || (p.floatData = []), (m & 7) === 2)) - for (var y = r.uint32() + r.pos; r.pos < y; ) p.floatData.push(r.float()); - else p.floatData.push(r.float()); - break; - } - case 5: { - if (((p.int32Data && p.int32Data.length) || (p.int32Data = []), (m & 7) === 2)) - for (var y = r.uint32() + r.pos; r.pos < y; ) p.int32Data.push(r.int32()); - else p.int32Data.push(r.int32()); - break; - } - case 6: { - (p.stringData && p.stringData.length) || (p.stringData = []), - p.stringData.push(r.bytes()); - break; - } - case 7: { - if (((p.int64Data && p.int64Data.length) || (p.int64Data = []), (m & 7) === 2)) - for (var y = r.uint32() + r.pos; r.pos < y; ) p.int64Data.push(r.int64()); - else p.int64Data.push(r.int64()); - break; - } - case 8: { - p.name = r.string(); - break; - } - case 12: { - p.docString = r.string(); - break; - } - case 9: { - p.rawData = r.bytes(); - break; - } - case 13: { - (p.externalData && p.externalData.length) || (p.externalData = []), - p.externalData.push(s.onnx.StringStringEntryProto.decode(r, r.uint32())); - break; - } - case 14: { - p.dataLocation = r.int32(); - break; - } - case 10: { - if ( - ((p.doubleData && p.doubleData.length) || (p.doubleData = []), - (m & 7) === 2) - ) - for (var y = r.uint32() + r.pos; r.pos < y; ) p.doubleData.push(r.double()); - else p.doubleData.push(r.double()); - break; - } - case 11: { - if ( - ((p.uint64Data && p.uint64Data.length) || (p.uint64Data = []), - (m & 7) === 2) - ) - for (var y = r.uint32() + r.pos; r.pos < y; ) p.uint64Data.push(r.uint64()); - else p.uint64Data.push(r.uint64()); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if (r.dims != null && r.hasOwnProperty('dims')) { - if (!Array.isArray(r.dims)) return 'dims: array expected'; - for (var a = 0; a < r.dims.length; ++a) - if ( - !n.isInteger(r.dims[a]) && - !(r.dims[a] && n.isInteger(r.dims[a].low) && n.isInteger(r.dims[a].high)) - ) - return 'dims: integer|Long[] expected'; - } - if (r.dataType != null && r.hasOwnProperty('dataType') && !n.isInteger(r.dataType)) - return 'dataType: integer expected'; - if (r.segment != null && r.hasOwnProperty('segment')) { - var l = s.onnx.TensorProto.Segment.verify(r.segment); - if (l) return 'segment.' + l; - } - if (r.floatData != null && r.hasOwnProperty('floatData')) { - if (!Array.isArray(r.floatData)) return 'floatData: array expected'; - for (var a = 0; a < r.floatData.length; ++a) - if (typeof r.floatData[a] != 'number') return 'floatData: number[] expected'; - } - if (r.int32Data != null && r.hasOwnProperty('int32Data')) { - if (!Array.isArray(r.int32Data)) return 'int32Data: array expected'; - for (var a = 0; a < r.int32Data.length; ++a) - if (!n.isInteger(r.int32Data[a])) return 'int32Data: integer[] expected'; - } - if (r.stringData != null && r.hasOwnProperty('stringData')) { - if (!Array.isArray(r.stringData)) return 'stringData: array expected'; - for (var a = 0; a < r.stringData.length; ++a) - if ( - !( - (r.stringData[a] && typeof r.stringData[a].length == 'number') || - n.isString(r.stringData[a]) - ) - ) - return 'stringData: buffer[] expected'; - } - if (r.int64Data != null && r.hasOwnProperty('int64Data')) { - if (!Array.isArray(r.int64Data)) return 'int64Data: array expected'; - for (var a = 0; a < r.int64Data.length; ++a) - if ( - !n.isInteger(r.int64Data[a]) && - !( - r.int64Data[a] && - n.isInteger(r.int64Data[a].low) && - n.isInteger(r.int64Data[a].high) - ) - ) - return 'int64Data: integer|Long[] expected'; - } - if (r.name != null && r.hasOwnProperty('name') && !n.isString(r.name)) - return 'name: string expected'; - if (r.docString != null && r.hasOwnProperty('docString') && !n.isString(r.docString)) - return 'docString: string expected'; - if ( - r.rawData != null && - r.hasOwnProperty('rawData') && - !((r.rawData && typeof r.rawData.length == 'number') || n.isString(r.rawData)) - ) - return 'rawData: buffer expected'; - if (r.externalData != null && r.hasOwnProperty('externalData')) { - if (!Array.isArray(r.externalData)) return 'externalData: array expected'; - for (var a = 0; a < r.externalData.length; ++a) { - var l = s.onnx.StringStringEntryProto.verify(r.externalData[a]); - if (l) return 'externalData.' + l; - } - } - if (r.dataLocation != null && r.hasOwnProperty('dataLocation')) - switch (r.dataLocation) { - default: - return 'dataLocation: enum value expected'; - case 0: - case 1: - break; - } - if (r.doubleData != null && r.hasOwnProperty('doubleData')) { - if (!Array.isArray(r.doubleData)) return 'doubleData: array expected'; - for (var a = 0; a < r.doubleData.length; ++a) - if (typeof r.doubleData[a] != 'number') return 'doubleData: number[] expected'; - } - if (r.uint64Data != null && r.hasOwnProperty('uint64Data')) { - if (!Array.isArray(r.uint64Data)) return 'uint64Data: array expected'; - for (var a = 0; a < r.uint64Data.length; ++a) - if ( - !n.isInteger(r.uint64Data[a]) && - !( - r.uint64Data[a] && - n.isInteger(r.uint64Data[a].low) && - n.isInteger(r.uint64Data[a].high) - ) - ) - return 'uint64Data: integer|Long[] expected'; - } - return null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.TensorProto) return r; - var a = new s.onnx.TensorProto(); - if (r.dims) { - if (!Array.isArray(r.dims)) throw TypeError('.onnx.TensorProto.dims: array expected'); - a.dims = []; - for (var l = 0; l < r.dims.length; ++l) - n.Long - ? ((a.dims[l] = n.Long.fromValue(r.dims[l])).unsigned = !1) - : typeof r.dims[l] == 'string' - ? (a.dims[l] = parseInt(r.dims[l], 10)) - : typeof r.dims[l] == 'number' - ? (a.dims[l] = r.dims[l]) - : typeof r.dims[l] == 'object' && - (a.dims[l] = new n.LongBits( - r.dims[l].low >>> 0, - r.dims[l].high >>> 0 - ).toNumber()); - } - if ((r.dataType != null && (a.dataType = r.dataType | 0), r.segment != null)) { - if (typeof r.segment != 'object') - throw TypeError('.onnx.TensorProto.segment: object expected'); - a.segment = s.onnx.TensorProto.Segment.fromObject(r.segment); - } - if (r.floatData) { - if (!Array.isArray(r.floatData)) - throw TypeError('.onnx.TensorProto.floatData: array expected'); - a.floatData = []; - for (var l = 0; l < r.floatData.length; ++l) a.floatData[l] = Number(r.floatData[l]); - } - if (r.int32Data) { - if (!Array.isArray(r.int32Data)) - throw TypeError('.onnx.TensorProto.int32Data: array expected'); - a.int32Data = []; - for (var l = 0; l < r.int32Data.length; ++l) a.int32Data[l] = r.int32Data[l] | 0; - } - if (r.stringData) { - if (!Array.isArray(r.stringData)) - throw TypeError('.onnx.TensorProto.stringData: array expected'); - a.stringData = []; - for (var l = 0; l < r.stringData.length; ++l) - typeof r.stringData[l] == 'string' - ? n.base64.decode( - r.stringData[l], - (a.stringData[l] = n.newBuffer(n.base64.length(r.stringData[l]))), - 0 - ) - : r.stringData[l].length >= 0 && (a.stringData[l] = r.stringData[l]); - } - if (r.int64Data) { - if (!Array.isArray(r.int64Data)) - throw TypeError('.onnx.TensorProto.int64Data: array expected'); - a.int64Data = []; - for (var l = 0; l < r.int64Data.length; ++l) - n.Long - ? ((a.int64Data[l] = n.Long.fromValue(r.int64Data[l])).unsigned = !1) - : typeof r.int64Data[l] == 'string' - ? (a.int64Data[l] = parseInt(r.int64Data[l], 10)) - : typeof r.int64Data[l] == 'number' - ? (a.int64Data[l] = r.int64Data[l]) - : typeof r.int64Data[l] == 'object' && - (a.int64Data[l] = new n.LongBits( - r.int64Data[l].low >>> 0, - r.int64Data[l].high >>> 0 - ).toNumber()); - } - if ( - (r.name != null && (a.name = String(r.name)), - r.docString != null && (a.docString = String(r.docString)), - r.rawData != null && - (typeof r.rawData == 'string' - ? n.base64.decode( - r.rawData, - (a.rawData = n.newBuffer(n.base64.length(r.rawData))), - 0 - ) - : r.rawData.length >= 0 && (a.rawData = r.rawData)), - r.externalData) - ) { - if (!Array.isArray(r.externalData)) - throw TypeError('.onnx.TensorProto.externalData: array expected'); - a.externalData = []; - for (var l = 0; l < r.externalData.length; ++l) { - if (typeof r.externalData[l] != 'object') - throw TypeError('.onnx.TensorProto.externalData: object expected'); - a.externalData[l] = s.onnx.StringStringEntryProto.fromObject(r.externalData[l]); - } - } - switch (r.dataLocation) { - default: - if (typeof r.dataLocation == 'number') { - a.dataLocation = r.dataLocation; - break; - } - break; - case 'DEFAULT': - case 0: - a.dataLocation = 0; - break; - case 'EXTERNAL': - case 1: - a.dataLocation = 1; - break; - } - if (r.doubleData) { - if (!Array.isArray(r.doubleData)) - throw TypeError('.onnx.TensorProto.doubleData: array expected'); - a.doubleData = []; - for (var l = 0; l < r.doubleData.length; ++l) a.doubleData[l] = Number(r.doubleData[l]); - } - if (r.uint64Data) { - if (!Array.isArray(r.uint64Data)) - throw TypeError('.onnx.TensorProto.uint64Data: array expected'); - a.uint64Data = []; - for (var l = 0; l < r.uint64Data.length; ++l) - n.Long - ? ((a.uint64Data[l] = n.Long.fromValue(r.uint64Data[l])).unsigned = !0) - : typeof r.uint64Data[l] == 'string' - ? (a.uint64Data[l] = parseInt(r.uint64Data[l], 10)) - : typeof r.uint64Data[l] == 'number' - ? (a.uint64Data[l] = r.uint64Data[l]) - : typeof r.uint64Data[l] == 'object' && - (a.uint64Data[l] = new n.LongBits( - r.uint64Data[l].low >>> 0, - r.uint64Data[l].high >>> 0 - ).toNumber(!0)); - } - return a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if ( - ((a.arrays || a.defaults) && - ((l.dims = []), - (l.floatData = []), - (l.int32Data = []), - (l.stringData = []), - (l.int64Data = []), - (l.doubleData = []), - (l.uint64Data = []), - (l.externalData = [])), - a.defaults && - ((l.dataType = 0), - (l.segment = null), - (l.name = ''), - a.bytes === String - ? (l.rawData = '') - : ((l.rawData = []), a.bytes !== Array && (l.rawData = n.newBuffer(l.rawData))), - (l.docString = ''), - (l.dataLocation = a.enums === String ? 'DEFAULT' : 0)), - r.dims && r.dims.length) - ) { - l.dims = []; - for (var p = 0; p < r.dims.length; ++p) - typeof r.dims[p] == 'number' - ? (l.dims[p] = a.longs === String ? String(r.dims[p]) : r.dims[p]) - : (l.dims[p] = - a.longs === String - ? n.Long.prototype.toString.call(r.dims[p]) - : a.longs === Number - ? new n.LongBits(r.dims[p].low >>> 0, r.dims[p].high >>> 0).toNumber() - : r.dims[p]); - } - if ( - (r.dataType != null && r.hasOwnProperty('dataType') && (l.dataType = r.dataType), - r.segment != null && - r.hasOwnProperty('segment') && - (l.segment = s.onnx.TensorProto.Segment.toObject(r.segment, a)), - r.floatData && r.floatData.length) - ) { - l.floatData = []; - for (var p = 0; p < r.floatData.length; ++p) - l.floatData[p] = - a.json && !isFinite(r.floatData[p]) ? String(r.floatData[p]) : r.floatData[p]; - } - if (r.int32Data && r.int32Data.length) { - l.int32Data = []; - for (var p = 0; p < r.int32Data.length; ++p) l.int32Data[p] = r.int32Data[p]; - } - if (r.stringData && r.stringData.length) { - l.stringData = []; - for (var p = 0; p < r.stringData.length; ++p) - l.stringData[p] = - a.bytes === String - ? n.base64.encode(r.stringData[p], 0, r.stringData[p].length) - : a.bytes === Array - ? Array.prototype.slice.call(r.stringData[p]) - : r.stringData[p]; - } - if (r.int64Data && r.int64Data.length) { - l.int64Data = []; - for (var p = 0; p < r.int64Data.length; ++p) - typeof r.int64Data[p] == 'number' - ? (l.int64Data[p] = - a.longs === String ? String(r.int64Data[p]) : r.int64Data[p]) - : (l.int64Data[p] = - a.longs === String - ? n.Long.prototype.toString.call(r.int64Data[p]) - : a.longs === Number - ? new n.LongBits( - r.int64Data[p].low >>> 0, - r.int64Data[p].high >>> 0 - ).toNumber() - : r.int64Data[p]); - } - if ( - (r.name != null && r.hasOwnProperty('name') && (l.name = r.name), - r.rawData != null && - r.hasOwnProperty('rawData') && - (l.rawData = - a.bytes === String - ? n.base64.encode(r.rawData, 0, r.rawData.length) - : a.bytes === Array - ? Array.prototype.slice.call(r.rawData) - : r.rawData), - r.doubleData && r.doubleData.length) - ) { - l.doubleData = []; - for (var p = 0; p < r.doubleData.length; ++p) - l.doubleData[p] = - a.json && !isFinite(r.doubleData[p]) - ? String(r.doubleData[p]) - : r.doubleData[p]; - } - if (r.uint64Data && r.uint64Data.length) { - l.uint64Data = []; - for (var p = 0; p < r.uint64Data.length; ++p) - typeof r.uint64Data[p] == 'number' - ? (l.uint64Data[p] = - a.longs === String ? String(r.uint64Data[p]) : r.uint64Data[p]) - : (l.uint64Data[p] = - a.longs === String - ? n.Long.prototype.toString.call(r.uint64Data[p]) - : a.longs === Number - ? new n.LongBits( - r.uint64Data[p].low >>> 0, - r.uint64Data[p].high >>> 0 - ).toNumber(!0) - : r.uint64Data[p]); - } - if ( - (r.docString != null && r.hasOwnProperty('docString') && (l.docString = r.docString), - r.externalData && r.externalData.length) - ) { - l.externalData = []; - for (var p = 0; p < r.externalData.length; ++p) - l.externalData[p] = s.onnx.StringStringEntryProto.toObject(r.externalData[p], a); - } - return ( - r.dataLocation != null && - r.hasOwnProperty('dataLocation') && - (l.dataLocation = - a.enums === String - ? s.onnx.TensorProto.DataLocation[r.dataLocation] === void 0 - ? r.dataLocation - : s.onnx.TensorProto.DataLocation[r.dataLocation] - : r.dataLocation), - l - ); - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.TensorProto'; - }), - (f.DataType = (function () { - var r = {}, - a = Object.create(r); - return ( - (a[(r[0] = 'UNDEFINED')] = 0), - (a[(r[1] = 'FLOAT')] = 1), - (a[(r[2] = 'UINT8')] = 2), - (a[(r[3] = 'INT8')] = 3), - (a[(r[4] = 'UINT16')] = 4), - (a[(r[5] = 'INT16')] = 5), - (a[(r[6] = 'INT32')] = 6), - (a[(r[7] = 'INT64')] = 7), - (a[(r[8] = 'STRING')] = 8), - (a[(r[9] = 'BOOL')] = 9), - (a[(r[10] = 'FLOAT16')] = 10), - (a[(r[11] = 'DOUBLE')] = 11), - (a[(r[12] = 'UINT32')] = 12), - (a[(r[13] = 'UINT64')] = 13), - (a[(r[14] = 'COMPLEX64')] = 14), - (a[(r[15] = 'COMPLEX128')] = 15), - (a[(r[16] = 'BFLOAT16')] = 16), - (a[(r[17] = 'FLOAT8E4M3FN')] = 17), - (a[(r[18] = 'FLOAT8E4M3FNUZ')] = 18), - (a[(r[19] = 'FLOAT8E5M2')] = 19), - (a[(r[20] = 'FLOAT8E5M2FNUZ')] = 20), - a - ); - })()), - (f.Segment = (function () { - function r(a) { - if (a) - for (var l = Object.keys(a), p = 0; p < l.length; ++p) - a[l[p]] != null && (this[l[p]] = a[l[p]]); - } - return ( - (r.prototype.begin = n.Long ? n.Long.fromBits(0, 0, !1) : 0), - (r.prototype.end = n.Long ? n.Long.fromBits(0, 0, !1) : 0), - (r.create = function (a) { - return new r(a); - }), - (r.encode = function (a, l) { - return ( - l || (l = u.create()), - a.begin != null && - Object.hasOwnProperty.call(a, 'begin') && - l.uint32(8).int64(a.begin), - a.end != null && - Object.hasOwnProperty.call(a, 'end') && - l.uint32(16).int64(a.end), - l - ); - }), - (r.encodeDelimited = function (a, l) { - return this.encode(a, l).ldelim(); - }), - (r.decode = function (a, l) { - a instanceof i || (a = i.create(a)); - for ( - var p = l === void 0 ? a.len : a.pos + l, m = new s.onnx.TensorProto.Segment(); - a.pos < p; - - ) { - var y = a.uint32(); - switch (y >>> 3) { - case 1: { - m.begin = a.int64(); - break; - } - case 2: { - m.end = a.int64(); - break; - } - default: - a.skipType(y & 7); - break; - } - } - return m; - }), - (r.decodeDelimited = function (a) { - return a instanceof i || (a = new i(a)), this.decode(a, a.uint32()); - }), - (r.verify = function (a) { - return typeof a != 'object' || a === null - ? 'object expected' - : a.begin != null && - a.hasOwnProperty('begin') && - !n.isInteger(a.begin) && - !(a.begin && n.isInteger(a.begin.low) && n.isInteger(a.begin.high)) - ? 'begin: integer|Long expected' - : a.end != null && - a.hasOwnProperty('end') && - !n.isInteger(a.end) && - !(a.end && n.isInteger(a.end.low) && n.isInteger(a.end.high)) - ? 'end: integer|Long expected' - : null; - }), - (r.fromObject = function (a) { - if (a instanceof s.onnx.TensorProto.Segment) return a; - var l = new s.onnx.TensorProto.Segment(); - return ( - a.begin != null && - (n.Long - ? ((l.begin = n.Long.fromValue(a.begin)).unsigned = !1) - : typeof a.begin == 'string' - ? (l.begin = parseInt(a.begin, 10)) - : typeof a.begin == 'number' - ? (l.begin = a.begin) - : typeof a.begin == 'object' && - (l.begin = new n.LongBits( - a.begin.low >>> 0, - a.begin.high >>> 0 - ).toNumber())), - a.end != null && - (n.Long - ? ((l.end = n.Long.fromValue(a.end)).unsigned = !1) - : typeof a.end == 'string' - ? (l.end = parseInt(a.end, 10)) - : typeof a.end == 'number' - ? (l.end = a.end) - : typeof a.end == 'object' && - (l.end = new n.LongBits( - a.end.low >>> 0, - a.end.high >>> 0 - ).toNumber())), - l - ); - }), - (r.toObject = function (a, l) { - l || (l = {}); - var p = {}; - if (l.defaults) { - if (n.Long) { - var m = new n.Long(0, 0, !1); - p.begin = - l.longs === String - ? m.toString() - : l.longs === Number - ? m.toNumber() - : m; - } else p.begin = l.longs === String ? '0' : 0; - if (n.Long) { - var m = new n.Long(0, 0, !1); - p.end = - l.longs === String - ? m.toString() - : l.longs === Number - ? m.toNumber() - : m; - } else p.end = l.longs === String ? '0' : 0; - } - return ( - a.begin != null && - a.hasOwnProperty('begin') && - (typeof a.begin == 'number' - ? (p.begin = l.longs === String ? String(a.begin) : a.begin) - : (p.begin = - l.longs === String - ? n.Long.prototype.toString.call(a.begin) - : l.longs === Number - ? new n.LongBits( - a.begin.low >>> 0, - a.begin.high >>> 0 - ).toNumber() - : a.begin)), - a.end != null && - a.hasOwnProperty('end') && - (typeof a.end == 'number' - ? (p.end = l.longs === String ? String(a.end) : a.end) - : (p.end = - l.longs === String - ? n.Long.prototype.toString.call(a.end) - : l.longs === Number - ? new n.LongBits(a.end.low >>> 0, a.end.high >>> 0).toNumber() - : a.end)), - p - ); - }), - (r.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (r.getTypeUrl = function (a) { - return a === void 0 && (a = 'type.googleapis.com'), a + '/onnx.TensorProto.Segment'; - }), - r - ); - })()), - (f.DataLocation = (function () { - var r = {}, - a = Object.create(r); - return (a[(r[0] = 'DEFAULT')] = 0), (a[(r[1] = 'EXTERNAL')] = 1), a; - })()), - f - ); - })()), - (d.SparseTensorProto = (function () { - function f(r) { - if (((this.dims = []), r)) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.values = null), - (f.prototype.indices = null), - (f.prototype.dims = n.emptyArray), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - if ( - (a || (a = u.create()), - r.values != null && - Object.hasOwnProperty.call(r, 'values') && - s.onnx.TensorProto.encode(r.values, a.uint32(10).fork()).ldelim(), - r.indices != null && - Object.hasOwnProperty.call(r, 'indices') && - s.onnx.TensorProto.encode(r.indices, a.uint32(18).fork()).ldelim(), - r.dims != null && r.dims.length) - ) { - a.uint32(26).fork(); - for (var l = 0; l < r.dims.length; ++l) a.int64(r.dims[l]); - a.ldelim(); - } - return a; - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for ( - var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.SparseTensorProto(); - r.pos < l; - - ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - p.values = s.onnx.TensorProto.decode(r, r.uint32()); - break; - } - case 2: { - p.indices = s.onnx.TensorProto.decode(r, r.uint32()); - break; - } - case 3: { - if (((p.dims && p.dims.length) || (p.dims = []), (m & 7) === 2)) - for (var y = r.uint32() + r.pos; r.pos < y; ) p.dims.push(r.int64()); - else p.dims.push(r.int64()); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if (r.values != null && r.hasOwnProperty('values')) { - var a = s.onnx.TensorProto.verify(r.values); - if (a) return 'values.' + a; - } - if (r.indices != null && r.hasOwnProperty('indices')) { - var a = s.onnx.TensorProto.verify(r.indices); - if (a) return 'indices.' + a; - } - if (r.dims != null && r.hasOwnProperty('dims')) { - if (!Array.isArray(r.dims)) return 'dims: array expected'; - for (var l = 0; l < r.dims.length; ++l) - if ( - !n.isInteger(r.dims[l]) && - !(r.dims[l] && n.isInteger(r.dims[l].low) && n.isInteger(r.dims[l].high)) - ) - return 'dims: integer|Long[] expected'; - } - return null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.SparseTensorProto) return r; - var a = new s.onnx.SparseTensorProto(); - if (r.values != null) { - if (typeof r.values != 'object') - throw TypeError('.onnx.SparseTensorProto.values: object expected'); - a.values = s.onnx.TensorProto.fromObject(r.values); - } - if (r.indices != null) { - if (typeof r.indices != 'object') - throw TypeError('.onnx.SparseTensorProto.indices: object expected'); - a.indices = s.onnx.TensorProto.fromObject(r.indices); - } - if (r.dims) { - if (!Array.isArray(r.dims)) - throw TypeError('.onnx.SparseTensorProto.dims: array expected'); - a.dims = []; - for (var l = 0; l < r.dims.length; ++l) - n.Long - ? ((a.dims[l] = n.Long.fromValue(r.dims[l])).unsigned = !1) - : typeof r.dims[l] == 'string' - ? (a.dims[l] = parseInt(r.dims[l], 10)) - : typeof r.dims[l] == 'number' - ? (a.dims[l] = r.dims[l]) - : typeof r.dims[l] == 'object' && - (a.dims[l] = new n.LongBits( - r.dims[l].low >>> 0, - r.dims[l].high >>> 0 - ).toNumber()); - } - return a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if ( - ((a.arrays || a.defaults) && (l.dims = []), - a.defaults && ((l.values = null), (l.indices = null)), - r.values != null && - r.hasOwnProperty('values') && - (l.values = s.onnx.TensorProto.toObject(r.values, a)), - r.indices != null && - r.hasOwnProperty('indices') && - (l.indices = s.onnx.TensorProto.toObject(r.indices, a)), - r.dims && r.dims.length) - ) { - l.dims = []; - for (var p = 0; p < r.dims.length; ++p) - typeof r.dims[p] == 'number' - ? (l.dims[p] = a.longs === String ? String(r.dims[p]) : r.dims[p]) - : (l.dims[p] = - a.longs === String - ? n.Long.prototype.toString.call(r.dims[p]) - : a.longs === Number - ? new n.LongBits(r.dims[p].low >>> 0, r.dims[p].high >>> 0).toNumber() - : r.dims[p]); - } - return l; - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.SparseTensorProto'; - }), - f - ); - })()), - (d.TensorShapeProto = (function () { - function f(r) { - if (((this.dim = []), r)) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.dim = n.emptyArray), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - if ((a || (a = u.create()), r.dim != null && r.dim.length)) - for (var l = 0; l < r.dim.length; ++l) - s.onnx.TensorShapeProto.Dimension.encode(r.dim[l], a.uint32(10).fork()).ldelim(); - return a; - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for ( - var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.TensorShapeProto(); - r.pos < l; - - ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - (p.dim && p.dim.length) || (p.dim = []), - p.dim.push(s.onnx.TensorShapeProto.Dimension.decode(r, r.uint32())); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if (r.dim != null && r.hasOwnProperty('dim')) { - if (!Array.isArray(r.dim)) return 'dim: array expected'; - for (var a = 0; a < r.dim.length; ++a) { - var l = s.onnx.TensorShapeProto.Dimension.verify(r.dim[a]); - if (l) return 'dim.' + l; - } - } - return null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.TensorShapeProto) return r; - var a = new s.onnx.TensorShapeProto(); - if (r.dim) { - if (!Array.isArray(r.dim)) - throw TypeError('.onnx.TensorShapeProto.dim: array expected'); - a.dim = []; - for (var l = 0; l < r.dim.length; ++l) { - if (typeof r.dim[l] != 'object') - throw TypeError('.onnx.TensorShapeProto.dim: object expected'); - a.dim[l] = s.onnx.TensorShapeProto.Dimension.fromObject(r.dim[l]); - } - } - return a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if (((a.arrays || a.defaults) && (l.dim = []), r.dim && r.dim.length)) { - l.dim = []; - for (var p = 0; p < r.dim.length; ++p) - l.dim[p] = s.onnx.TensorShapeProto.Dimension.toObject(r.dim[p], a); - } - return l; - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.TensorShapeProto'; - }), - (f.Dimension = (function () { - function r(l) { - if (l) - for (var p = Object.keys(l), m = 0; m < p.length; ++m) - l[p[m]] != null && (this[p[m]] = l[p[m]]); - } - (r.prototype.dimValue = null), (r.prototype.dimParam = null), (r.prototype.denotation = ''); - var a; - return ( - Object.defineProperty(r.prototype, 'value', { - get: n.oneOfGetter((a = ['dimValue', 'dimParam'])), - set: n.oneOfSetter(a), - }), - (r.create = function (l) { - return new r(l); - }), - (r.encode = function (l, p) { - return ( - p || (p = u.create()), - l.dimValue != null && - Object.hasOwnProperty.call(l, 'dimValue') && - p.uint32(8).int64(l.dimValue), - l.dimParam != null && - Object.hasOwnProperty.call(l, 'dimParam') && - p.uint32(18).string(l.dimParam), - l.denotation != null && - Object.hasOwnProperty.call(l, 'denotation') && - p.uint32(26).string(l.denotation), - p - ); - }), - (r.encodeDelimited = function (l, p) { - return this.encode(l, p).ldelim(); - }), - (r.decode = function (l, p) { - l instanceof i || (l = i.create(l)); - for ( - var m = p === void 0 ? l.len : l.pos + p, - y = new s.onnx.TensorShapeProto.Dimension(); - l.pos < m; - - ) { - var T = l.uint32(); - switch (T >>> 3) { - case 1: { - y.dimValue = l.int64(); - break; - } - case 2: { - y.dimParam = l.string(); - break; - } - case 3: { - y.denotation = l.string(); - break; - } - default: - l.skipType(T & 7); - break; - } - } - return y; - }), - (r.decodeDelimited = function (l) { - return l instanceof i || (l = new i(l)), this.decode(l, l.uint32()); - }), - (r.verify = function (l) { - if (typeof l != 'object' || l === null) return 'object expected'; - var p = {}; - if ( - l.dimValue != null && - l.hasOwnProperty('dimValue') && - ((p.value = 1), - !n.isInteger(l.dimValue) && - !( - l.dimValue && - n.isInteger(l.dimValue.low) && - n.isInteger(l.dimValue.high) - )) - ) - return 'dimValue: integer|Long expected'; - if (l.dimParam != null && l.hasOwnProperty('dimParam')) { - if (p.value === 1) return 'value: multiple values'; - if (((p.value = 1), !n.isString(l.dimParam))) - return 'dimParam: string expected'; - } - return l.denotation != null && - l.hasOwnProperty('denotation') && - !n.isString(l.denotation) - ? 'denotation: string expected' - : null; - }), - (r.fromObject = function (l) { - if (l instanceof s.onnx.TensorShapeProto.Dimension) return l; - var p = new s.onnx.TensorShapeProto.Dimension(); - return ( - l.dimValue != null && - (n.Long - ? ((p.dimValue = n.Long.fromValue(l.dimValue)).unsigned = !1) - : typeof l.dimValue == 'string' - ? (p.dimValue = parseInt(l.dimValue, 10)) - : typeof l.dimValue == 'number' - ? (p.dimValue = l.dimValue) - : typeof l.dimValue == 'object' && - (p.dimValue = new n.LongBits( - l.dimValue.low >>> 0, - l.dimValue.high >>> 0 - ).toNumber())), - l.dimParam != null && (p.dimParam = String(l.dimParam)), - l.denotation != null && (p.denotation = String(l.denotation)), - p - ); - }), - (r.toObject = function (l, p) { - p || (p = {}); - var m = {}; - return ( - p.defaults && (m.denotation = ''), - l.dimValue != null && - l.hasOwnProperty('dimValue') && - (typeof l.dimValue == 'number' - ? (m.dimValue = p.longs === String ? String(l.dimValue) : l.dimValue) - : (m.dimValue = - p.longs === String - ? n.Long.prototype.toString.call(l.dimValue) - : p.longs === Number - ? new n.LongBits( - l.dimValue.low >>> 0, - l.dimValue.high >>> 0 - ).toNumber() - : l.dimValue), - p.oneofs && (m.value = 'dimValue')), - l.dimParam != null && - l.hasOwnProperty('dimParam') && - ((m.dimParam = l.dimParam), p.oneofs && (m.value = 'dimParam')), - l.denotation != null && - l.hasOwnProperty('denotation') && - (m.denotation = l.denotation), - m - ); - }), - (r.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (r.getTypeUrl = function (l) { - return ( - l === void 0 && (l = 'type.googleapis.com'), - l + '/onnx.TensorShapeProto.Dimension' - ); - }), - r - ); - })()), - f - ); - })()), - (d.TypeProto = (function () { - function f(a) { - if (a) - for (var l = Object.keys(a), p = 0; p < l.length; ++p) - a[l[p]] != null && (this[l[p]] = a[l[p]]); - } - (f.prototype.tensorType = null), - (f.prototype.sequenceType = null), - (f.prototype.mapType = null), - (f.prototype.optionalType = null), - (f.prototype.sparseTensorType = null), - (f.prototype.denotation = ''); - var r; - return ( - Object.defineProperty(f.prototype, 'value', { - get: n.oneOfGetter( - (r = ['tensorType', 'sequenceType', 'mapType', 'optionalType', 'sparseTensorType']) - ), - set: n.oneOfSetter(r), - }), - (f.create = function (a) { - return new f(a); - }), - (f.encode = function (a, l) { - return ( - l || (l = u.create()), - a.tensorType != null && - Object.hasOwnProperty.call(a, 'tensorType') && - s.onnx.TypeProto.Tensor.encode(a.tensorType, l.uint32(10).fork()).ldelim(), - a.sequenceType != null && - Object.hasOwnProperty.call(a, 'sequenceType') && - s.onnx.TypeProto.Sequence.encode(a.sequenceType, l.uint32(34).fork()).ldelim(), - a.mapType != null && - Object.hasOwnProperty.call(a, 'mapType') && - s.onnx.TypeProto.Map.encode(a.mapType, l.uint32(42).fork()).ldelim(), - a.denotation != null && - Object.hasOwnProperty.call(a, 'denotation') && - l.uint32(50).string(a.denotation), - a.sparseTensorType != null && - Object.hasOwnProperty.call(a, 'sparseTensorType') && - s.onnx.TypeProto.SparseTensor.encode( - a.sparseTensorType, - l.uint32(66).fork() - ).ldelim(), - a.optionalType != null && - Object.hasOwnProperty.call(a, 'optionalType') && - s.onnx.TypeProto.Optional.encode(a.optionalType, l.uint32(74).fork()).ldelim(), - l - ); - }), - (f.encodeDelimited = function (a, l) { - return this.encode(a, l).ldelim(); - }), - (f.decode = function (a, l) { - a instanceof i || (a = i.create(a)); - for (var p = l === void 0 ? a.len : a.pos + l, m = new s.onnx.TypeProto(); a.pos < p; ) { - var y = a.uint32(); - switch (y >>> 3) { - case 1: { - m.tensorType = s.onnx.TypeProto.Tensor.decode(a, a.uint32()); - break; - } - case 4: { - m.sequenceType = s.onnx.TypeProto.Sequence.decode(a, a.uint32()); - break; - } - case 5: { - m.mapType = s.onnx.TypeProto.Map.decode(a, a.uint32()); - break; - } - case 9: { - m.optionalType = s.onnx.TypeProto.Optional.decode(a, a.uint32()); - break; - } - case 8: { - m.sparseTensorType = s.onnx.TypeProto.SparseTensor.decode(a, a.uint32()); - break; - } - case 6: { - m.denotation = a.string(); - break; - } - default: - a.skipType(y & 7); - break; - } - } - return m; - }), - (f.decodeDelimited = function (a) { - return a instanceof i || (a = new i(a)), this.decode(a, a.uint32()); - }), - (f.verify = function (a) { - if (typeof a != 'object' || a === null) return 'object expected'; - var l = {}; - if (a.tensorType != null && a.hasOwnProperty('tensorType')) { - l.value = 1; - { - var p = s.onnx.TypeProto.Tensor.verify(a.tensorType); - if (p) return 'tensorType.' + p; - } - } - if (a.sequenceType != null && a.hasOwnProperty('sequenceType')) { - if (l.value === 1) return 'value: multiple values'; - l.value = 1; - { - var p = s.onnx.TypeProto.Sequence.verify(a.sequenceType); - if (p) return 'sequenceType.' + p; - } - } - if (a.mapType != null && a.hasOwnProperty('mapType')) { - if (l.value === 1) return 'value: multiple values'; - l.value = 1; - { - var p = s.onnx.TypeProto.Map.verify(a.mapType); - if (p) return 'mapType.' + p; - } - } - if (a.optionalType != null && a.hasOwnProperty('optionalType')) { - if (l.value === 1) return 'value: multiple values'; - l.value = 1; - { - var p = s.onnx.TypeProto.Optional.verify(a.optionalType); - if (p) return 'optionalType.' + p; - } - } - if (a.sparseTensorType != null && a.hasOwnProperty('sparseTensorType')) { - if (l.value === 1) return 'value: multiple values'; - l.value = 1; - { - var p = s.onnx.TypeProto.SparseTensor.verify(a.sparseTensorType); - if (p) return 'sparseTensorType.' + p; - } - } - return a.denotation != null && a.hasOwnProperty('denotation') && !n.isString(a.denotation) - ? 'denotation: string expected' - : null; - }), - (f.fromObject = function (a) { - if (a instanceof s.onnx.TypeProto) return a; - var l = new s.onnx.TypeProto(); - if (a.tensorType != null) { - if (typeof a.tensorType != 'object') - throw TypeError('.onnx.TypeProto.tensorType: object expected'); - l.tensorType = s.onnx.TypeProto.Tensor.fromObject(a.tensorType); - } - if (a.sequenceType != null) { - if (typeof a.sequenceType != 'object') - throw TypeError('.onnx.TypeProto.sequenceType: object expected'); - l.sequenceType = s.onnx.TypeProto.Sequence.fromObject(a.sequenceType); - } - if (a.mapType != null) { - if (typeof a.mapType != 'object') - throw TypeError('.onnx.TypeProto.mapType: object expected'); - l.mapType = s.onnx.TypeProto.Map.fromObject(a.mapType); - } - if (a.optionalType != null) { - if (typeof a.optionalType != 'object') - throw TypeError('.onnx.TypeProto.optionalType: object expected'); - l.optionalType = s.onnx.TypeProto.Optional.fromObject(a.optionalType); - } - if (a.sparseTensorType != null) { - if (typeof a.sparseTensorType != 'object') - throw TypeError('.onnx.TypeProto.sparseTensorType: object expected'); - l.sparseTensorType = s.onnx.TypeProto.SparseTensor.fromObject(a.sparseTensorType); - } - return a.denotation != null && (l.denotation = String(a.denotation)), l; - }), - (f.toObject = function (a, l) { - l || (l = {}); - var p = {}; - return ( - l.defaults && (p.denotation = ''), - a.tensorType != null && - a.hasOwnProperty('tensorType') && - ((p.tensorType = s.onnx.TypeProto.Tensor.toObject(a.tensorType, l)), - l.oneofs && (p.value = 'tensorType')), - a.sequenceType != null && - a.hasOwnProperty('sequenceType') && - ((p.sequenceType = s.onnx.TypeProto.Sequence.toObject(a.sequenceType, l)), - l.oneofs && (p.value = 'sequenceType')), - a.mapType != null && - a.hasOwnProperty('mapType') && - ((p.mapType = s.onnx.TypeProto.Map.toObject(a.mapType, l)), - l.oneofs && (p.value = 'mapType')), - a.denotation != null && a.hasOwnProperty('denotation') && (p.denotation = a.denotation), - a.sparseTensorType != null && - a.hasOwnProperty('sparseTensorType') && - ((p.sparseTensorType = s.onnx.TypeProto.SparseTensor.toObject( - a.sparseTensorType, - l - )), - l.oneofs && (p.value = 'sparseTensorType')), - a.optionalType != null && - a.hasOwnProperty('optionalType') && - ((p.optionalType = s.onnx.TypeProto.Optional.toObject(a.optionalType, l)), - l.oneofs && (p.value = 'optionalType')), - p - ); - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (a) { - return a === void 0 && (a = 'type.googleapis.com'), a + '/onnx.TypeProto'; - }), - (f.Tensor = (function () { - function a(l) { - if (l) - for (var p = Object.keys(l), m = 0; m < p.length; ++m) - l[p[m]] != null && (this[p[m]] = l[p[m]]); - } - return ( - (a.prototype.elemType = 0), - (a.prototype.shape = null), - (a.create = function (l) { - return new a(l); - }), - (a.encode = function (l, p) { - return ( - p || (p = u.create()), - l.elemType != null && - Object.hasOwnProperty.call(l, 'elemType') && - p.uint32(8).int32(l.elemType), - l.shape != null && - Object.hasOwnProperty.call(l, 'shape') && - s.onnx.TensorShapeProto.encode(l.shape, p.uint32(18).fork()).ldelim(), - p - ); - }), - (a.encodeDelimited = function (l, p) { - return this.encode(l, p).ldelim(); - }), - (a.decode = function (l, p) { - l instanceof i || (l = i.create(l)); - for ( - var m = p === void 0 ? l.len : l.pos + p, y = new s.onnx.TypeProto.Tensor(); - l.pos < m; - - ) { - var T = l.uint32(); - switch (T >>> 3) { - case 1: { - y.elemType = l.int32(); - break; - } - case 2: { - y.shape = s.onnx.TensorShapeProto.decode(l, l.uint32()); - break; - } - default: - l.skipType(T & 7); - break; - } - } - return y; - }), - (a.decodeDelimited = function (l) { - return l instanceof i || (l = new i(l)), this.decode(l, l.uint32()); - }), - (a.verify = function (l) { - if (typeof l != 'object' || l === null) return 'object expected'; - if (l.elemType != null && l.hasOwnProperty('elemType') && !n.isInteger(l.elemType)) - return 'elemType: integer expected'; - if (l.shape != null && l.hasOwnProperty('shape')) { - var p = s.onnx.TensorShapeProto.verify(l.shape); - if (p) return 'shape.' + p; - } - return null; - }), - (a.fromObject = function (l) { - if (l instanceof s.onnx.TypeProto.Tensor) return l; - var p = new s.onnx.TypeProto.Tensor(); - if ((l.elemType != null && (p.elemType = l.elemType | 0), l.shape != null)) { - if (typeof l.shape != 'object') - throw TypeError('.onnx.TypeProto.Tensor.shape: object expected'); - p.shape = s.onnx.TensorShapeProto.fromObject(l.shape); - } - return p; - }), - (a.toObject = function (l, p) { - p || (p = {}); - var m = {}; - return ( - p.defaults && ((m.elemType = 0), (m.shape = null)), - l.elemType != null && l.hasOwnProperty('elemType') && (m.elemType = l.elemType), - l.shape != null && - l.hasOwnProperty('shape') && - (m.shape = s.onnx.TensorShapeProto.toObject(l.shape, p)), - m - ); - }), - (a.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (a.getTypeUrl = function (l) { - return l === void 0 && (l = 'type.googleapis.com'), l + '/onnx.TypeProto.Tensor'; - }), - a - ); - })()), - (f.Sequence = (function () { - function a(l) { - if (l) - for (var p = Object.keys(l), m = 0; m < p.length; ++m) - l[p[m]] != null && (this[p[m]] = l[p[m]]); - } - return ( - (a.prototype.elemType = null), - (a.create = function (l) { - return new a(l); - }), - (a.encode = function (l, p) { - return ( - p || (p = u.create()), - l.elemType != null && - Object.hasOwnProperty.call(l, 'elemType') && - s.onnx.TypeProto.encode(l.elemType, p.uint32(10).fork()).ldelim(), - p - ); - }), - (a.encodeDelimited = function (l, p) { - return this.encode(l, p).ldelim(); - }), - (a.decode = function (l, p) { - l instanceof i || (l = i.create(l)); - for ( - var m = p === void 0 ? l.len : l.pos + p, y = new s.onnx.TypeProto.Sequence(); - l.pos < m; - - ) { - var T = l.uint32(); - switch (T >>> 3) { - case 1: { - y.elemType = s.onnx.TypeProto.decode(l, l.uint32()); - break; - } - default: - l.skipType(T & 7); - break; - } - } - return y; - }), - (a.decodeDelimited = function (l) { - return l instanceof i || (l = new i(l)), this.decode(l, l.uint32()); - }), - (a.verify = function (l) { - if (typeof l != 'object' || l === null) return 'object expected'; - if (l.elemType != null && l.hasOwnProperty('elemType')) { - var p = s.onnx.TypeProto.verify(l.elemType); - if (p) return 'elemType.' + p; - } - return null; - }), - (a.fromObject = function (l) { - if (l instanceof s.onnx.TypeProto.Sequence) return l; - var p = new s.onnx.TypeProto.Sequence(); - if (l.elemType != null) { - if (typeof l.elemType != 'object') - throw TypeError('.onnx.TypeProto.Sequence.elemType: object expected'); - p.elemType = s.onnx.TypeProto.fromObject(l.elemType); - } - return p; - }), - (a.toObject = function (l, p) { - p || (p = {}); - var m = {}; - return ( - p.defaults && (m.elemType = null), - l.elemType != null && - l.hasOwnProperty('elemType') && - (m.elemType = s.onnx.TypeProto.toObject(l.elemType, p)), - m - ); - }), - (a.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (a.getTypeUrl = function (l) { - return l === void 0 && (l = 'type.googleapis.com'), l + '/onnx.TypeProto.Sequence'; - }), - a - ); - })()), - (f.Map = (function () { - function a(l) { - if (l) - for (var p = Object.keys(l), m = 0; m < p.length; ++m) - l[p[m]] != null && (this[p[m]] = l[p[m]]); - } - return ( - (a.prototype.keyType = 0), - (a.prototype.valueType = null), - (a.create = function (l) { - return new a(l); - }), - (a.encode = function (l, p) { - return ( - p || (p = u.create()), - l.keyType != null && - Object.hasOwnProperty.call(l, 'keyType') && - p.uint32(8).int32(l.keyType), - l.valueType != null && - Object.hasOwnProperty.call(l, 'valueType') && - s.onnx.TypeProto.encode(l.valueType, p.uint32(18).fork()).ldelim(), - p - ); - }), - (a.encodeDelimited = function (l, p) { - return this.encode(l, p).ldelim(); - }), - (a.decode = function (l, p) { - l instanceof i || (l = i.create(l)); - for ( - var m = p === void 0 ? l.len : l.pos + p, y = new s.onnx.TypeProto.Map(); - l.pos < m; - - ) { - var T = l.uint32(); - switch (T >>> 3) { - case 1: { - y.keyType = l.int32(); - break; - } - case 2: { - y.valueType = s.onnx.TypeProto.decode(l, l.uint32()); - break; - } - default: - l.skipType(T & 7); - break; - } - } - return y; - }), - (a.decodeDelimited = function (l) { - return l instanceof i || (l = new i(l)), this.decode(l, l.uint32()); - }), - (a.verify = function (l) { - if (typeof l != 'object' || l === null) return 'object expected'; - if (l.keyType != null && l.hasOwnProperty('keyType') && !n.isInteger(l.keyType)) - return 'keyType: integer expected'; - if (l.valueType != null && l.hasOwnProperty('valueType')) { - var p = s.onnx.TypeProto.verify(l.valueType); - if (p) return 'valueType.' + p; - } - return null; - }), - (a.fromObject = function (l) { - if (l instanceof s.onnx.TypeProto.Map) return l; - var p = new s.onnx.TypeProto.Map(); - if ((l.keyType != null && (p.keyType = l.keyType | 0), l.valueType != null)) { - if (typeof l.valueType != 'object') - throw TypeError('.onnx.TypeProto.Map.valueType: object expected'); - p.valueType = s.onnx.TypeProto.fromObject(l.valueType); - } - return p; - }), - (a.toObject = function (l, p) { - p || (p = {}); - var m = {}; - return ( - p.defaults && ((m.keyType = 0), (m.valueType = null)), - l.keyType != null && l.hasOwnProperty('keyType') && (m.keyType = l.keyType), - l.valueType != null && - l.hasOwnProperty('valueType') && - (m.valueType = s.onnx.TypeProto.toObject(l.valueType, p)), - m - ); - }), - (a.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (a.getTypeUrl = function (l) { - return l === void 0 && (l = 'type.googleapis.com'), l + '/onnx.TypeProto.Map'; - }), - a - ); - })()), - (f.Optional = (function () { - function a(l) { - if (l) - for (var p = Object.keys(l), m = 0; m < p.length; ++m) - l[p[m]] != null && (this[p[m]] = l[p[m]]); - } - return ( - (a.prototype.elemType = null), - (a.create = function (l) { - return new a(l); - }), - (a.encode = function (l, p) { - return ( - p || (p = u.create()), - l.elemType != null && - Object.hasOwnProperty.call(l, 'elemType') && - s.onnx.TypeProto.encode(l.elemType, p.uint32(10).fork()).ldelim(), - p - ); - }), - (a.encodeDelimited = function (l, p) { - return this.encode(l, p).ldelim(); - }), - (a.decode = function (l, p) { - l instanceof i || (l = i.create(l)); - for ( - var m = p === void 0 ? l.len : l.pos + p, y = new s.onnx.TypeProto.Optional(); - l.pos < m; - - ) { - var T = l.uint32(); - switch (T >>> 3) { - case 1: { - y.elemType = s.onnx.TypeProto.decode(l, l.uint32()); - break; - } - default: - l.skipType(T & 7); - break; - } - } - return y; - }), - (a.decodeDelimited = function (l) { - return l instanceof i || (l = new i(l)), this.decode(l, l.uint32()); - }), - (a.verify = function (l) { - if (typeof l != 'object' || l === null) return 'object expected'; - if (l.elemType != null && l.hasOwnProperty('elemType')) { - var p = s.onnx.TypeProto.verify(l.elemType); - if (p) return 'elemType.' + p; - } - return null; - }), - (a.fromObject = function (l) { - if (l instanceof s.onnx.TypeProto.Optional) return l; - var p = new s.onnx.TypeProto.Optional(); - if (l.elemType != null) { - if (typeof l.elemType != 'object') - throw TypeError('.onnx.TypeProto.Optional.elemType: object expected'); - p.elemType = s.onnx.TypeProto.fromObject(l.elemType); - } - return p; - }), - (a.toObject = function (l, p) { - p || (p = {}); - var m = {}; - return ( - p.defaults && (m.elemType = null), - l.elemType != null && - l.hasOwnProperty('elemType') && - (m.elemType = s.onnx.TypeProto.toObject(l.elemType, p)), - m - ); - }), - (a.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (a.getTypeUrl = function (l) { - return l === void 0 && (l = 'type.googleapis.com'), l + '/onnx.TypeProto.Optional'; - }), - a - ); - })()), - (f.SparseTensor = (function () { - function a(l) { - if (l) - for (var p = Object.keys(l), m = 0; m < p.length; ++m) - l[p[m]] != null && (this[p[m]] = l[p[m]]); - } - return ( - (a.prototype.elemType = 0), - (a.prototype.shape = null), - (a.create = function (l) { - return new a(l); - }), - (a.encode = function (l, p) { - return ( - p || (p = u.create()), - l.elemType != null && - Object.hasOwnProperty.call(l, 'elemType') && - p.uint32(8).int32(l.elemType), - l.shape != null && - Object.hasOwnProperty.call(l, 'shape') && - s.onnx.TensorShapeProto.encode(l.shape, p.uint32(18).fork()).ldelim(), - p - ); - }), - (a.encodeDelimited = function (l, p) { - return this.encode(l, p).ldelim(); - }), - (a.decode = function (l, p) { - l instanceof i || (l = i.create(l)); - for ( - var m = p === void 0 ? l.len : l.pos + p, - y = new s.onnx.TypeProto.SparseTensor(); - l.pos < m; - - ) { - var T = l.uint32(); - switch (T >>> 3) { - case 1: { - y.elemType = l.int32(); - break; - } - case 2: { - y.shape = s.onnx.TensorShapeProto.decode(l, l.uint32()); - break; - } - default: - l.skipType(T & 7); - break; - } - } - return y; - }), - (a.decodeDelimited = function (l) { - return l instanceof i || (l = new i(l)), this.decode(l, l.uint32()); - }), - (a.verify = function (l) { - if (typeof l != 'object' || l === null) return 'object expected'; - if (l.elemType != null && l.hasOwnProperty('elemType') && !n.isInteger(l.elemType)) - return 'elemType: integer expected'; - if (l.shape != null && l.hasOwnProperty('shape')) { - var p = s.onnx.TensorShapeProto.verify(l.shape); - if (p) return 'shape.' + p; - } - return null; - }), - (a.fromObject = function (l) { - if (l instanceof s.onnx.TypeProto.SparseTensor) return l; - var p = new s.onnx.TypeProto.SparseTensor(); - if ((l.elemType != null && (p.elemType = l.elemType | 0), l.shape != null)) { - if (typeof l.shape != 'object') - throw TypeError('.onnx.TypeProto.SparseTensor.shape: object expected'); - p.shape = s.onnx.TensorShapeProto.fromObject(l.shape); - } - return p; - }), - (a.toObject = function (l, p) { - p || (p = {}); - var m = {}; - return ( - p.defaults && ((m.elemType = 0), (m.shape = null)), - l.elemType != null && l.hasOwnProperty('elemType') && (m.elemType = l.elemType), - l.shape != null && - l.hasOwnProperty('shape') && - (m.shape = s.onnx.TensorShapeProto.toObject(l.shape, p)), - m - ); - }), - (a.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (a.getTypeUrl = function (l) { - return ( - l === void 0 && (l = 'type.googleapis.com'), l + '/onnx.TypeProto.SparseTensor' - ); - }), - a - ); - })()), - f - ); - })()), - (d.OperatorSetIdProto = (function () { - function f(r) { - if (r) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.domain = ''), - (f.prototype.version = n.Long ? n.Long.fromBits(0, 0, !1) : 0), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - return ( - a || (a = u.create()), - r.domain != null && - Object.hasOwnProperty.call(r, 'domain') && - a.uint32(10).string(r.domain), - r.version != null && - Object.hasOwnProperty.call(r, 'version') && - a.uint32(16).int64(r.version), - a - ); - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for ( - var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.OperatorSetIdProto(); - r.pos < l; - - ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - p.domain = r.string(); - break; - } - case 2: { - p.version = r.int64(); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - return typeof r != 'object' || r === null - ? 'object expected' - : r.domain != null && r.hasOwnProperty('domain') && !n.isString(r.domain) - ? 'domain: string expected' - : r.version != null && - r.hasOwnProperty('version') && - !n.isInteger(r.version) && - !(r.version && n.isInteger(r.version.low) && n.isInteger(r.version.high)) - ? 'version: integer|Long expected' - : null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.OperatorSetIdProto) return r; - var a = new s.onnx.OperatorSetIdProto(); - return ( - r.domain != null && (a.domain = String(r.domain)), - r.version != null && - (n.Long - ? ((a.version = n.Long.fromValue(r.version)).unsigned = !1) - : typeof r.version == 'string' - ? (a.version = parseInt(r.version, 10)) - : typeof r.version == 'number' - ? (a.version = r.version) - : typeof r.version == 'object' && - (a.version = new n.LongBits( - r.version.low >>> 0, - r.version.high >>> 0 - ).toNumber())), - a - ); - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if (a.defaults) - if (((l.domain = ''), n.Long)) { - var p = new n.Long(0, 0, !1); - l.version = - a.longs === String ? p.toString() : a.longs === Number ? p.toNumber() : p; - } else l.version = a.longs === String ? '0' : 0; - return ( - r.domain != null && r.hasOwnProperty('domain') && (l.domain = r.domain), - r.version != null && - r.hasOwnProperty('version') && - (typeof r.version == 'number' - ? (l.version = a.longs === String ? String(r.version) : r.version) - : (l.version = - a.longs === String - ? n.Long.prototype.toString.call(r.version) - : a.longs === Number - ? new n.LongBits(r.version.low >>> 0, r.version.high >>> 0).toNumber() - : r.version)), - l - ); - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.OperatorSetIdProto'; - }), - f - ); - })()), - (d.OperatorStatus = (function () { - var f = {}, - r = Object.create(f); - return (r[(f[0] = 'EXPERIMENTAL')] = 0), (r[(f[1] = 'STABLE')] = 1), r; - })()), - (d.FunctionProto = (function () { - function f(r) { - if ( - ((this.input = []), - (this.output = []), - (this.attribute = []), - (this.attributeProto = []), - (this.node = []), - (this.opsetImport = []), - r) - ) - for (var a = Object.keys(r), l = 0; l < a.length; ++l) - r[a[l]] != null && (this[a[l]] = r[a[l]]); - } - return ( - (f.prototype.name = ''), - (f.prototype.input = n.emptyArray), - (f.prototype.output = n.emptyArray), - (f.prototype.attribute = n.emptyArray), - (f.prototype.attributeProto = n.emptyArray), - (f.prototype.node = n.emptyArray), - (f.prototype.docString = ''), - (f.prototype.opsetImport = n.emptyArray), - (f.prototype.domain = ''), - (f.create = function (r) { - return new f(r); - }), - (f.encode = function (r, a) { - if ( - (a || (a = u.create()), - r.name != null && Object.hasOwnProperty.call(r, 'name') && a.uint32(10).string(r.name), - r.input != null && r.input.length) - ) - for (var l = 0; l < r.input.length; ++l) a.uint32(34).string(r.input[l]); - if (r.output != null && r.output.length) - for (var l = 0; l < r.output.length; ++l) a.uint32(42).string(r.output[l]); - if (r.attribute != null && r.attribute.length) - for (var l = 0; l < r.attribute.length; ++l) a.uint32(50).string(r.attribute[l]); - if (r.node != null && r.node.length) - for (var l = 0; l < r.node.length; ++l) - s.onnx.NodeProto.encode(r.node[l], a.uint32(58).fork()).ldelim(); - if ( - (r.docString != null && - Object.hasOwnProperty.call(r, 'docString') && - a.uint32(66).string(r.docString), - r.opsetImport != null && r.opsetImport.length) - ) - for (var l = 0; l < r.opsetImport.length; ++l) - s.onnx.OperatorSetIdProto.encode(r.opsetImport[l], a.uint32(74).fork()).ldelim(); - if ( - (r.domain != null && - Object.hasOwnProperty.call(r, 'domain') && - a.uint32(82).string(r.domain), - r.attributeProto != null && r.attributeProto.length) - ) - for (var l = 0; l < r.attributeProto.length; ++l) - s.onnx.AttributeProto.encode(r.attributeProto[l], a.uint32(90).fork()).ldelim(); - return a; - }), - (f.encodeDelimited = function (r, a) { - return this.encode(r, a).ldelim(); - }), - (f.decode = function (r, a) { - r instanceof i || (r = i.create(r)); - for ( - var l = a === void 0 ? r.len : r.pos + a, p = new s.onnx.FunctionProto(); - r.pos < l; - - ) { - var m = r.uint32(); - switch (m >>> 3) { - case 1: { - p.name = r.string(); - break; - } - case 4: { - (p.input && p.input.length) || (p.input = []), p.input.push(r.string()); - break; - } - case 5: { - (p.output && p.output.length) || (p.output = []), p.output.push(r.string()); - break; - } - case 6: { - (p.attribute && p.attribute.length) || (p.attribute = []), - p.attribute.push(r.string()); - break; - } - case 11: { - (p.attributeProto && p.attributeProto.length) || (p.attributeProto = []), - p.attributeProto.push(s.onnx.AttributeProto.decode(r, r.uint32())); - break; - } - case 7: { - (p.node && p.node.length) || (p.node = []), - p.node.push(s.onnx.NodeProto.decode(r, r.uint32())); - break; - } - case 8: { - p.docString = r.string(); - break; - } - case 9: { - (p.opsetImport && p.opsetImport.length) || (p.opsetImport = []), - p.opsetImport.push(s.onnx.OperatorSetIdProto.decode(r, r.uint32())); - break; - } - case 10: { - p.domain = r.string(); - break; - } - default: - r.skipType(m & 7); - break; - } - } - return p; - }), - (f.decodeDelimited = function (r) { - return r instanceof i || (r = new i(r)), this.decode(r, r.uint32()); - }), - (f.verify = function (r) { - if (typeof r != 'object' || r === null) return 'object expected'; - if (r.name != null && r.hasOwnProperty('name') && !n.isString(r.name)) - return 'name: string expected'; - if (r.input != null && r.hasOwnProperty('input')) { - if (!Array.isArray(r.input)) return 'input: array expected'; - for (var a = 0; a < r.input.length; ++a) - if (!n.isString(r.input[a])) return 'input: string[] expected'; - } - if (r.output != null && r.hasOwnProperty('output')) { - if (!Array.isArray(r.output)) return 'output: array expected'; - for (var a = 0; a < r.output.length; ++a) - if (!n.isString(r.output[a])) return 'output: string[] expected'; - } - if (r.attribute != null && r.hasOwnProperty('attribute')) { - if (!Array.isArray(r.attribute)) return 'attribute: array expected'; - for (var a = 0; a < r.attribute.length; ++a) - if (!n.isString(r.attribute[a])) return 'attribute: string[] expected'; - } - if (r.attributeProto != null && r.hasOwnProperty('attributeProto')) { - if (!Array.isArray(r.attributeProto)) return 'attributeProto: array expected'; - for (var a = 0; a < r.attributeProto.length; ++a) { - var l = s.onnx.AttributeProto.verify(r.attributeProto[a]); - if (l) return 'attributeProto.' + l; - } - } - if (r.node != null && r.hasOwnProperty('node')) { - if (!Array.isArray(r.node)) return 'node: array expected'; - for (var a = 0; a < r.node.length; ++a) { - var l = s.onnx.NodeProto.verify(r.node[a]); - if (l) return 'node.' + l; - } - } - if (r.docString != null && r.hasOwnProperty('docString') && !n.isString(r.docString)) - return 'docString: string expected'; - if (r.opsetImport != null && r.hasOwnProperty('opsetImport')) { - if (!Array.isArray(r.opsetImport)) return 'opsetImport: array expected'; - for (var a = 0; a < r.opsetImport.length; ++a) { - var l = s.onnx.OperatorSetIdProto.verify(r.opsetImport[a]); - if (l) return 'opsetImport.' + l; - } - } - return r.domain != null && r.hasOwnProperty('domain') && !n.isString(r.domain) - ? 'domain: string expected' - : null; - }), - (f.fromObject = function (r) { - if (r instanceof s.onnx.FunctionProto) return r; - var a = new s.onnx.FunctionProto(); - if ((r.name != null && (a.name = String(r.name)), r.input)) { - if (!Array.isArray(r.input)) - throw TypeError('.onnx.FunctionProto.input: array expected'); - a.input = []; - for (var l = 0; l < r.input.length; ++l) a.input[l] = String(r.input[l]); - } - if (r.output) { - if (!Array.isArray(r.output)) - throw TypeError('.onnx.FunctionProto.output: array expected'); - a.output = []; - for (var l = 0; l < r.output.length; ++l) a.output[l] = String(r.output[l]); - } - if (r.attribute) { - if (!Array.isArray(r.attribute)) - throw TypeError('.onnx.FunctionProto.attribute: array expected'); - a.attribute = []; - for (var l = 0; l < r.attribute.length; ++l) a.attribute[l] = String(r.attribute[l]); - } - if (r.attributeProto) { - if (!Array.isArray(r.attributeProto)) - throw TypeError('.onnx.FunctionProto.attributeProto: array expected'); - a.attributeProto = []; - for (var l = 0; l < r.attributeProto.length; ++l) { - if (typeof r.attributeProto[l] != 'object') - throw TypeError('.onnx.FunctionProto.attributeProto: object expected'); - a.attributeProto[l] = s.onnx.AttributeProto.fromObject(r.attributeProto[l]); - } - } - if (r.node) { - if (!Array.isArray(r.node)) throw TypeError('.onnx.FunctionProto.node: array expected'); - a.node = []; - for (var l = 0; l < r.node.length; ++l) { - if (typeof r.node[l] != 'object') - throw TypeError('.onnx.FunctionProto.node: object expected'); - a.node[l] = s.onnx.NodeProto.fromObject(r.node[l]); - } - } - if ((r.docString != null && (a.docString = String(r.docString)), r.opsetImport)) { - if (!Array.isArray(r.opsetImport)) - throw TypeError('.onnx.FunctionProto.opsetImport: array expected'); - a.opsetImport = []; - for (var l = 0; l < r.opsetImport.length; ++l) { - if (typeof r.opsetImport[l] != 'object') - throw TypeError('.onnx.FunctionProto.opsetImport: object expected'); - a.opsetImport[l] = s.onnx.OperatorSetIdProto.fromObject(r.opsetImport[l]); - } - } - return r.domain != null && (a.domain = String(r.domain)), a; - }), - (f.toObject = function (r, a) { - a || (a = {}); - var l = {}; - if ( - ((a.arrays || a.defaults) && - ((l.input = []), - (l.output = []), - (l.attribute = []), - (l.node = []), - (l.opsetImport = []), - (l.attributeProto = [])), - a.defaults && ((l.name = ''), (l.docString = ''), (l.domain = '')), - r.name != null && r.hasOwnProperty('name') && (l.name = r.name), - r.input && r.input.length) - ) { - l.input = []; - for (var p = 0; p < r.input.length; ++p) l.input[p] = r.input[p]; - } - if (r.output && r.output.length) { - l.output = []; - for (var p = 0; p < r.output.length; ++p) l.output[p] = r.output[p]; - } - if (r.attribute && r.attribute.length) { - l.attribute = []; - for (var p = 0; p < r.attribute.length; ++p) l.attribute[p] = r.attribute[p]; - } - if (r.node && r.node.length) { - l.node = []; - for (var p = 0; p < r.node.length; ++p) - l.node[p] = s.onnx.NodeProto.toObject(r.node[p], a); - } - if ( - (r.docString != null && r.hasOwnProperty('docString') && (l.docString = r.docString), - r.opsetImport && r.opsetImport.length) - ) { - l.opsetImport = []; - for (var p = 0; p < r.opsetImport.length; ++p) - l.opsetImport[p] = s.onnx.OperatorSetIdProto.toObject(r.opsetImport[p], a); - } - if ( - (r.domain != null && r.hasOwnProperty('domain') && (l.domain = r.domain), - r.attributeProto && r.attributeProto.length) - ) { - l.attributeProto = []; - for (var p = 0; p < r.attributeProto.length; ++p) - l.attributeProto[p] = s.onnx.AttributeProto.toObject(r.attributeProto[p], a); - } - return l; - }), - (f.prototype.toJSON = function () { - return this.constructor.toObject(this, o.util.toJSONOptions); - }), - (f.getTypeUrl = function (r) { - return r === void 0 && (r = 'type.googleapis.com'), r + '/onnx.FunctionProto'; - }), - f - ); - })()), - d - ); - })()), - (e.exports = s); - }); -function Cr(t, e) { - if (!t) throw new Error(typeof e == 'string' ? e : e()); -} -function sn(t) { - return new TextDecoder().decode(t); -} -var ye, - cr, - hi, - Xe, - Xn, - Ve, - nt, - U, - an, - pr, - dr, - hr, - fe = L(() => { - Wn(), - ei(), - (ye = Er($r())), - mr(), - (cr = class { - static arraysEqual(t, e) { - if (t.length !== e.length) return !1; - for (let o = 0; o < t.length; o++) if (t[o] !== e[o]) return !1; - return !0; - } - }), - (hi = class { - static preprocessInputShapes(t, e) { - let o = t.length === 1 ? [1, t[0]] : t, - i = e.length === 1 ? [e[0], 1] : e; - return [o, i]; - } - static postprocessOutputShape(t, e, o) { - e === 1 && t.splice(t.length - 2, 1), o === 1 && t.pop(); - } - static calcMatMulShape(t, e) { - return t[1] !== e[0] ? void 0 : [t[0], e[1]]; - } - }), - (Xe = class fr { - static calcShape(e, o, i = !1) { - let u = e.length, - n = o.length; - if (u === 0) return o; - if (n === 0) return e; - let s = Math.max(e.length, o.length), - d = new Array(s); - if (i) { - if (u < 2 || n < 2) return; - let f = hi.calcMatMulShape([e[u - 2], e[u - 1]], [o[n - 2], o[n - 1]]); - if (f === void 0) return; - [d[s - 2], d[s - 1]] = f; - } - for (let f = i ? 3 : 1; f <= s; f++) { - let r = u - f < 0 ? 1 : e[u - f], - a = n - f < 0 ? 1 : o[n - f]; - if (r !== a && r > 1 && a > 1) return; - d[s - f] = Math.max(r, a); - } - return d; - } - static index(e, o) { - let i = new Array(o.length); - return fr.fillIndex(e, o, i), i; - } - static fillIndex(e, o, i) { - let u = e.length - o.length; - for (let n = 0; n < o.length; n++) i[n] = e[u + n] % o[n]; - } - static calc(e, o, i, u, n) { - let s = fr.calcShape(e.dims, o.dims); - if (s) { - if (u && !U.areEqual(s, e.dims)) return; - let d = U.size(s), - f = u ? e : new Fe(s, n || e.type); - if (s.length === 0) f.set([], i(e.get([]), o.get([]))); - else { - let r = new Array(s.length), - a = new Array(e.dims.length), - l = new Array(o.dims.length), - p = 0, - m = 0, - y = !1, - T = !1; - e.dims.length === 0 && ((p = e.get([])), (y = !0)), - o.dims.length === 0 && ((m = o.get([])), (T = !0)); - let v; - for (let S = 0; S < d; S++) { - v = S; - for (let E = s.length - 1; E >= 0; E--) (r[E] = v % s[E]), (v = Math.floor(v / s[E])); - y || (fr.fillIndex(r, e.dims, a), (p = e.get(a))), - T || (fr.fillIndex(r, o.dims, l), (m = o.get(l))), - f.set(r, i(p, m)); - } - } - return f; - } - } - static isValidBroadcast(e, o) { - let i = e.length, - u = o.length; - if (i > u) return !1; - for (let n = 1; n <= i; n++) if (e[i - n] !== 1 && e[i - n] !== o[u - n]) return !1; - return !0; - } - static getBroadcastDims(e, o) { - let i = e.length, - u = []; - for (let n = 0; n < i; n++) { - let s = i - 1 - n, - d = e[s] || 1; - (o[o.length - 1 - n] || 1) > 1 && d === 1 && u.unshift(s); - } - return u; - } - }), - (Xn = class { - static getShapeOfGemmResult(t, e, o, i, u) { - if (t.length !== 2 || o.length !== 2) throw new Error('shape need to be of size 2'); - let n, s, d; - e ? ((n = t[1]), (s = t[0])) : ((n = t[0]), (s = t[1])); - let f = -1; - if ((i ? ((d = o[0]), (f = 1)) : ((d = o[1]), (f = 0)), o[f] !== s)) - throw new Error('dimension mismatch'); - if (n <= 0 || d <= 0 || s <= 0) throw new Error('invalid shape specified'); - if (u && !Xe.isValidBroadcast(u, [n, d])) throw new Error('gemm: invalid bias shape for broadcast'); - return [n, d, s]; - } - }), - (Ve = class Sn { - static tensorDataTypeFromProto(e) { - switch (e) { - case ye.onnx.TensorProto.DataType.INT8: - return 'int8'; - case ye.onnx.TensorProto.DataType.UINT8: - return 'uint8'; - case ye.onnx.TensorProto.DataType.BOOL: - return 'bool'; - case ye.onnx.TensorProto.DataType.INT16: - return 'int16'; - case ye.onnx.TensorProto.DataType.UINT16: - return 'uint16'; - case ye.onnx.TensorProto.DataType.INT32: - return 'int32'; - case ye.onnx.TensorProto.DataType.UINT32: - return 'uint32'; - case ye.onnx.TensorProto.DataType.FLOAT: - return 'float32'; - case ye.onnx.TensorProto.DataType.DOUBLE: - return 'float64'; - case ye.onnx.TensorProto.DataType.STRING: - return 'string'; - case ye.onnx.TensorProto.DataType.INT64: - return 'int32'; - case ye.onnx.TensorProto.DataType.UINT64: - return 'uint32'; - default: - throw new Error(`unsupported data type: ${ye.onnx.TensorProto.DataType[e]}`); - } - } - static tensorDataTypeStringToEnum(e) { - switch (e) { - case 'int8': - return ye.onnx.TensorProto.DataType.INT8; - case 'uint8': - return ye.onnx.TensorProto.DataType.UINT8; - case 'bool': - return ye.onnx.TensorProto.DataType.BOOL; - case 'int16': - return ye.onnx.TensorProto.DataType.INT16; - case 'uint16': - return ye.onnx.TensorProto.DataType.UINT16; - case 'int32': - return ye.onnx.TensorProto.DataType.INT32; - case 'uint32': - return ye.onnx.TensorProto.DataType.UINT32; - case 'float32': - return ye.onnx.TensorProto.DataType.FLOAT; - case 'float64': - return ye.onnx.TensorProto.DataType.DOUBLE; - case 'string': - return ye.onnx.TensorProto.DataType.STRING; - case 'int64': - return ye.onnx.TensorProto.DataType.INT64; - case 'uint64': - return ye.onnx.TensorProto.DataType.UINT64; - default: - throw new Error(`unsupported data type: ${e}`); - } - } - static tensorDimsFromProto(e) { - return e.map((o) => (zt.isLong(o) ? o.toNumber() : o)); - } - static tensorValueTypeFromProto(e) { - return { - tensorType: Sn.tensorDataTypeFromProto(e.elemType), - shape: { dims: Sn.tensorDimsFromProto(e.shape.dim.map((o) => o.dimValue)) }, - }; - } - static tensorDimsFromORTFormat(e) { - let o = []; - for (let i = 0; i < e.dimsLength(); i++) o.push(nt.longToNumber(e.dims(i))); - return o; - } - static tensorAttributesFromORTFormat(e) { - let o = []; - for (let i = 0; i < e.attributesLength(); i++) o.push(e.attributes(i)); - return o; - } - }), - (nt = class { - static longToNumber(t, e) { - return zt.isLong(t) - ? t.toNumber() - : t instanceof _.Long - ? zt.fromValue({ low: t.low, high: t.high, unsigned: e ?? !1 }).toNumber() - : t; - } - static isLong(t) { - return zt.isLong(t) || t instanceof _.Long; - } - }), - (U = class Pt { - static size(e) { - return Pt.getSizeFromDimensionRange(e, 0, e.length); - } - static sizeFromDimension(e, o) { - if (o < 0 || o > e.length) - throw new Error( - `invalid dimension of ${o} for sizeFromDimension as Tensor has ${e.length} dimensions.` - ); - return Pt.getSizeFromDimensionRange(e, o, e.length); - } - static sizeToDimension(e, o) { - if (o < 0 || o > e.length) - throw new Error( - `invalid dimension of ${o} for sizeToDimension as Tensor has ${e.length} dimensions.` - ); - return Pt.getSizeFromDimensionRange(e, 0, o); - } - static getSizeFromDimensionRange(e, o, i) { - let u = 1; - for (let n = o; n < i; n++) { - if (e[n] <= 0) - throw new Error( - 'cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.' - ); - u *= e[n]; - } - return u; - } - static computeStrides(e) { - let o = e.length; - if (o === 0) return []; - if (o === 1) return [1]; - let i = new Array(o); - (i[o - 1] = 1), (i[o - 2] = e[o - 1]); - for (let u = o - 3; u >= 0; --u) i[u] = i[u + 1] * e[u + 1]; - return i; - } - static transpose(e) { - return e.slice().reverse(); - } - static indicesToOffset(e, o, i) { - i === void 0 && (i = e.length); - let u = 0; - for (let n = 0; n < i; ++n) u += o[n] * e[n]; - return u; - } - static offsetToIndices(e, o) { - let i = o.length; - if (i === 0) return []; - if (i === 1) return [e * o[0]]; - let u = new Array(o.length); - for (let n = 0; n < u.length - 1; ++n) (u[n] = Math.floor(e / o[n])), (e -= u[n] * o[n]); - return (u[u.length - 1] = e), u; - } - static normalizeAxis(e, o) { - if (e < -o && e >= o) throw new Error('unsupported axis for this operation.'); - return e < 0 ? e + o : e; - } - static normalizeAxes(e, o) { - return e.map((i) => this.normalizeAxis(i, o)); - } - static incrementIndex(e, o, i) { - if (o.length === 0 || e.length === 0) - throw new Error('Index incrementing unsupported for scalar Tensor'); - if (i === void 0) i = o.length; - else if (i <= 0 || i > o.length) throw new Error('Incorrect axis to increment on'); - for (let u = i - 1; u >= 0 && (e[u]++, !(e[u] < o[u])); --u) e[u] = 0; - } - static calculateReshapedDims(e, o) { - if (o.length === 0) { - if (e.length === 0 || Pt.size(e) === 1) return []; - throw new Error('cannot reshape to a scalar Tensor'); - } - let i = o.length, - u = new Array(i), - n = -1, - s = 1; - for (let f = 0; f < i; f++) { - if (o[f] < -1) throw new Error('a dimension in shape hints cannot be less than -1'); - if (o[f] === -1) { - if (n !== -1) throw new Error('at most one dimension in shape hints can be -1'); - n = f; - } else { - if (o[f] === 0) { - if (f >= e.length) - throw new Error( - 'the dimension with value zero exceeds the dimension size of the input tensor' - ); - u[f] = e[f]; - } else u[f] = o[f]; - s *= u[f]; - } - } - let d = Pt.size(e); - if (n !== -1) { - if (d % s !== 0) - throw new Error( - `the input tensor cannot be reshaped to the requested shape. Input shape: [${e}] Output shape: [${o}]` - ); - u[n] = d / s; - } else if (s !== d) throw new Error("reshapedDims and originalDims don't have matching sizes"); - return u; - } - static sortBasedOnPerm(e, o) { - return o ? o.map((i) => e[i]) : e.slice().reverse(); - } - static padShape(e, o) { - let i = e.length; - return e.map((u, n) => u + o[n] + o[n + i]); - } - static areEqual(e, o) { - return e.length !== o.length ? !1 : e.every((i, u) => i === o[u]); - } - static validateDimsAndCalcSize(e) { - if (e.length > 6) throw new TypeError('Only rank 0 to 6 is supported for tensor shape.'); - let o = 1; - for (let i of e) { - if (!Number.isInteger(i)) throw new TypeError(`Invalid shape: ${i} is not an integer`); - if (i < 0 || i > 2147483647) throw new TypeError(`Invalid shape: length ${i} is not allowed`); - o *= i; - } - return o; - } - static flattenShape(e, o) { - o < 0 && (o += e.length); - let i = e.reduce((n, s) => n * s, 1), - u = e.slice(o).reduce((n, s) => n * s, 1); - return [i / u, u]; - } - static squeezeShape(e, o) { - let i = new Array(); - o = Pt.normalizeAxes(o, e.length); - for (let u = 0; u < e.length; u++) { - let n = o.indexOf(u) >= 0; - if (n && e[u] !== 1) throw new Error('squeeze an axis of size different than 1'); - ((o.length === 0 && e[u] > 1) || (o.length > 0 && !n)) && i.push(e[u]); - } - return i; - } - static unsqueezeShape(e, o) { - let i = new Array(e.length + o.length); - i.fill(0); - for (let n = 0; n < o.length; n++) { - let s = Pt.normalizeAxis(o[n], i.length); - if (s >= i.length) throw new Error("'axes' has an out of range axis"); - if (i[s] !== 0) throw new Error("'axes' has a duplicate axis"); - i[s] = 1; - } - let u = 0; - for (let n = 0; n < i.length; n++) i[n] === 0 && (i[n] = e[u++]); - if (u !== e.length) throw new Error('the unsqueezed dimension could not be established'); - return i; - } - }), - (an = class js { - static splitShape(e, o, i, u) { - if (i.length === 0) { - if (!u) - throw new Error( - "need to know number of outputs when the 'split' attribute is not specified" - ); - js.determineSplit(e[o], u, i); - } - let n = [], - s = [0]; - for (let d = 0; d < i.length; ++d) { - d !== 0 && s.push(s[d - 1] + i[d - 1]); - let f = e.slice(); - (f[o] = i[d]), n.push(f); - } - return [n, s]; - } - static determineSplit(e, o, i) { - if (e % o !== 0) throw new Error('cannot split tensor to equal sized parts'); - for (let u = 0; u < o; ++u) i.push(e / o); - } - }), - (pr = class _r { - static adjustPoolAttributes(e, o, i, u, n, s) { - if (!e && i.length !== o.length - 2) - throw new Error( - 'length of specified kernel shapes should be 2 less than length of input dimensions' - ); - if (e) for (let d = 0; d < o.length - 2; d++) d >= i.length ? i.push(o[d + 2]) : (i[d] = o[d + 2]); - for (let d = 0; d < i.length; d++) - if (d < u.length) { - if (u[d] < 0) throw new Error('strides should be greater than or equal to 1'); - } else u.push(1); - for (let d = 0; d < i.length; d++) - if (d < n.length) { - if (n[d] < 0) throw new Error('dilations should be greater than or equal to 1'); - } else n.push(1); - for (let d = 0; d < i.length * 2; d++) - if (d < s.length) { - if (s[d] < 0) throw new Error('pad should be greater than or equal to 1'); - } else s.push(0); - for (let d = 0; d < i.length; d++) { - if (i[d] <= 0) throw new Error('kernel shapes need to be greater than 0'); - if (s[d] >= i[d] || s[d + i.length] >= i[d]) - throw new Error('pads should be smaller than kernel'); - } - } - static adjustPadsBasedOnAutoPad(e, o, i, u, n, s) { - if (s) { - if (n.length !== 2 * (e.length - 2)) - throw new Error('length of pads should be twice the length of data dimensions'); - if (o.length !== e.length - 2) - throw new Error('length of strides should be the length of data dimensions'); - if (u.length !== e.length - 2) - throw new Error('length of kernel shapes should be the length of data dimensions'); - for (let d = 0; d < e.length - 2; d++) - _r.adjustPadAndReturnShape(e[d + 2], o[d], i[d], u[d], n, d, d + e.length - 2, s); - } - } - static computePoolOutputShape(e, o, i, u, n, s, d) { - if (o.length <= 0) throw new Error('input shape must be of size greater than 0'); - let f = [o[0], o[1]]; - return _r.computeShapeHelper(e, o, f, i, u, n, s, d), f; - } - static computeConvOutputShape(e, o, i, u, n, s, d) { - if (e.length <= 0 || o.length <= 0) - throw new Error('invalid input tensor dims or invalid filter tensor dims'); - let f = [e[0], o[0]]; - return _r.computeShapeHelper(!1, e, f, i, u, n, s, d), f; - } - static computeShapeHelper(e, o, i, u, n, s, d, f) { - if (e) for (let r = 0; r < o.length - 2; r++) i.push(1); - else - for (let r = 0; r < o.length - 2; r++) - i.push(_r.adjustPadAndReturnShape(o[r + 2], u[r], n[r], s[r], d, r, r + o.length - 2, f)); - } - static adjustPadAndReturnShape(e, o, i, u, n, s, d, f) { - let r = i * (u - 1) + 1; - if (f && f !== 'NOTSET') - switch (f) { - case 'VALID': - return (n[s] = 0), (n[d] = 0), Math.floor((e - r) / o + 1); - case 'SAME_LOWER': - case 'SAME_UPPER': - if (i !== 1) throw new Error('Dilation not supported for SAME_UPPER or SAME_LOWER'); - { - let a = ((e + o - 1) / o - 1) * o + u - e; - return ( - (n[s] = Math.floor(f === 'SAME_LOWER' ? (a + 1) / 2 : a / 2)), - (n[d] = a - n[s]), - Math.floor((e + a - u) / o + 1) - ); - } - default: - throw new Error('Unsupported AutoPad type'); - } - else return Math.floor((e + n[s] + n[d] - r) / o + 1); - } - }), - (dr = -34028234663852886e22), - (hr = 34028234663852886e22); - }); -function Vd(t) { - switch (t) { - case 'bool': - case 'int8': - case 'uint8': - return 1; - case 'int16': - case 'uint16': - return 2; - case 'int32': - case 'uint32': - case 'float32': - return 4; - case 'float64': - return 8; - default: - throw new Error(`cannot calculate sizeof() on type ${t}`); - } -} -function Fu(t) { - switch (t) { - case te.onnx.TensorProto.DataType.UINT8: - case te.onnx.TensorProto.DataType.INT8: - case te.onnx.TensorProto.DataType.BOOL: - return 1; - case te.onnx.TensorProto.DataType.UINT16: - case te.onnx.TensorProto.DataType.INT16: - return 2; - case te.onnx.TensorProto.DataType.FLOAT: - case te.onnx.TensorProto.DataType.INT32: - case te.onnx.TensorProto.DataType.UINT32: - return 4; - case te.onnx.TensorProto.DataType.INT64: - case te.onnx.TensorProto.DataType.DOUBLE: - case te.onnx.TensorProto.DataType.UINT64: - return 8; - default: - throw new Error(`cannot calculate sizeof() on type ${te.onnx.TensorProto.DataType[t]}`); - } -} -function Wd(t, e) { - return new (ku(e))(t); -} -function ku(t) { - switch (t) { - case 'bool': - case 'uint8': - return Uint8Array; - case 'int8': - return Int8Array; - case 'int16': - return Int16Array; - case 'uint16': - return Uint16Array; - case 'int32': - return Int32Array; - case 'uint32': - return Uint32Array; - case 'int64': - return BigInt64Array; - case 'float32': - return Float32Array; - case 'float64': - return Float64Array; - default: - throw new Error('unspecified error'); - } -} -function bi(t, e) { - if (e === te.onnx.TensorProto.DataType.INT64 || e === mi.TensorDataType.INT64) { - if (t.greaterThanOrEqual(2147483648) || t.lessThan(-2147483648)) throw new TypeError('int64 is not supported'); - } else if ( - e === te.onnx.TensorProto.DataType.UINT32 || - e === mi.TensorDataType.UINT32 || - e === te.onnx.TensorProto.DataType.UINT64 || - e === mi.TensorDataType.UINT64 - ) { - if (t.greaterThanOrEqual(4294967296) || t.lessThan(0)) throw new TypeError('uint64 is not supported'); - } else throw new TypeError(`not a LONG type: ${te.onnx.TensorProto.DataType[e]}`); - return t.toNumber(); -} -function $u(t, e, o) { - switch (e) { - case te.onnx.TensorProto.DataType.BOOL: - case te.onnx.TensorProto.DataType.UINT8: - return t.getUint8(o); - case te.onnx.TensorProto.DataType.INT8: - return t.getInt8(o); - case te.onnx.TensorProto.DataType.UINT16: - return t.getUint16(o, !0); - case te.onnx.TensorProto.DataType.INT16: - return t.getInt16(o, !0); - case te.onnx.TensorProto.DataType.FLOAT: - return t.getFloat32(o, !0); - case te.onnx.TensorProto.DataType.INT32: - return t.getInt32(o, !0); - case te.onnx.TensorProto.DataType.UINT32: - return t.getUint32(o, !0); - case te.onnx.TensorProto.DataType.INT64: - return bi(zt.fromBits(t.getUint32(o, !0), t.getUint32(o + 4, !0), !1), e); - case te.onnx.TensorProto.DataType.DOUBLE: - return t.getFloat64(o, !0); - case te.onnx.TensorProto.DataType.UINT64: - return bi(zt.fromBits(t.getUint32(o, !0), t.getUint32(o + 4, !0), !0), e); - default: - throw new Error(`cannot read from DataView for type ${te.onnx.TensorProto.DataType[e]}`); - } -} -var Cu, - te, - mi, - Fe, - mr = L(() => { - (Cu = Er(_s())), - ei(), - tn(), - (te = Er($r())), - fe(), - (mi = W.experimental.fbs), - (Fe = class Kr { - constructor(e, o, i, u, n, s = Cu.Guid.create()) { - (this.dims = e), - (this.type = o), - (this.dataProvider = i), - (this.asyncDataProvider = u), - (this.cache = n), - (this.dataId = s), - (this.size = U.validateDimsAndCalcSize(e)); - let d = this.size, - f = i === void 0 && u === void 0 && n === void 0; - if (n !== void 0 && n.length !== d) throw new RangeError("Input dims doesn't match data length."); - if (o === 'string') { - if (n !== void 0 && (!Array.isArray(n) || !n.every((r) => typeof r == 'string'))) - throw new TypeError('cache should be a string array'); - f && (this.cache = new Array(d)); - } else { - if (n !== void 0) { - let r = ku(o); - if (!(n instanceof r)) throw new TypeError(`cache should be type ${r.name}`); - } - if (f) { - let r = new ArrayBuffer(d * Vd(o)); - this.cache = Wd(r, o); - } - } - } - get data() { - if (this.cache === void 0) { - let e = this.dataProvider(this.dataId); - if (e.length !== this.size) - throw new Error( - 'Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.' - ); - this.cache = e; - } - return this.cache; - } - get stringData() { - if (this.type !== 'string') 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 (this.type !== 'string') return this.data; - throw new TypeError('type cannot be non-number (string)'); - } - get(e) { - return this.data[U.indicesToOffset(e, this.strides)]; - } - set(e, o) { - this.data[U.indicesToOffset(e, this.strides)] = o; - } - async getData() { - return ( - this.cache === void 0 && (this.cache = await this.asyncDataProvider(this.dataId)), this.cache - ); - } - get strides() { - return this._strides || (this._strides = U.computeStrides(this.dims)), this._strides; - } - static fromProto(e) { - if (!e) throw new Error('cannot construct Value from an empty tensor'); - let o = Ve.tensorDataTypeFromProto(e.dataType), - i = Ve.tensorDimsFromProto(e.dims), - u = new Kr(i, o); - if (o === 'string') - e.stringData.forEach((n, s) => { - u.data[s] = sn(n); - }); - else if (e.rawData && typeof e.rawData.byteLength == 'number' && e.rawData.byteLength > 0) { - let n = u.data, - s = new DataView(e.rawData.buffer, e.rawData.byteOffset, e.rawData.byteLength), - d = Fu(e.dataType), - f = e.rawData.byteLength / d; - if (e.rawData.byteLength % d !== 0) throw new Error('invalid buffer length'); - if (n.length !== f) throw new Error('buffer length mismatch'); - for (let r = 0; r < f; r++) { - let a = $u(s, e.dataType, r * d); - n[r] = a; - } - } else { - let n; - switch (e.dataType) { - case te.onnx.TensorProto.DataType.FLOAT: - n = e.floatData; - break; - case te.onnx.TensorProto.DataType.INT32: - case te.onnx.TensorProto.DataType.INT16: - case te.onnx.TensorProto.DataType.UINT16: - case te.onnx.TensorProto.DataType.INT8: - case te.onnx.TensorProto.DataType.UINT8: - case te.onnx.TensorProto.DataType.BOOL: - n = e.int32Data; - break; - case te.onnx.TensorProto.DataType.INT64: - n = e.int64Data; - break; - case te.onnx.TensorProto.DataType.DOUBLE: - n = e.doubleData; - break; - case te.onnx.TensorProto.DataType.UINT32: - case te.onnx.TensorProto.DataType.UINT64: - n = e.uint64Data; - break; - default: - throw new Error('unspecific error'); - } - if (n == null) throw new Error('failed to populate data from a tensorproto value'); - let s = u.data; - if (s.length !== n.length) throw new Error('array length mismatch'); - for (let d = 0; d < n.length; d++) { - let f = n[d]; - zt.isLong(f) ? (s[d] = bi(f, e.dataType)) : (s[d] = f); - } - } - return u; - } - static fromData(e, o, i) { - return new Kr(o, i, void 0, void 0, e); - } - static fromOrtTensor(e) { - if (!e) throw new Error('cannot construct Value from an empty tensor'); - let o = Ve.tensorDimsFromORTFormat(e), - i = Ve.tensorDataTypeFromProto(e.dataType()), - u = new Kr(o, i); - if (i === 'string') for (let n = 0; n < e.stringDataLength(); n++) u.data[n] = e.stringData(n); - else if (e.rawDataArray() && typeof e.rawDataLength() == 'number' && e.rawDataLength() > 0) { - let n = u.data, - s = new DataView(e.rawDataArray().buffer, e.rawDataArray().byteOffset, e.rawDataLength()), - d = Fu(e.dataType()), - f = e.rawDataLength() / d; - if (e.rawDataLength() % d !== 0) throw new Error('invalid buffer length'); - if (n.length !== f) throw new Error('buffer length mismatch'); - for (let r = 0; r < f; r++) { - let a = $u(s, e.dataType(), r * d); - n[r] = a; - } - } - return u; - } - }); - }); -function q(t) { - return t === 1 ? Hd : qd; -} -function Bu(t) { - let e = q(t); - return `${e.version} - precision highp float; - ${e.attribute} vec3 position; - ${e.attribute} vec2 textureCoord; - - ${e.varyingVertex} vec2 TexCoords; - - void main() - { - gl_Position = vec4(position, 1.0); - TexCoords = textureCoord; - }`; -} -function Nu(t) { - let e = q(t); - return `${e.version} - precision highp float; - precision highp int; - precision highp sampler2D; - ${e.varyingFrag} vec2 TexCoords; - ${e.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); - } - - `; -} -function Ru(t, e) { - let o = q(t); - return ` - void main() { - int indices[${e}]; - toVec(TexCoords, indices); - vec4 result = vec4(process(indices)); - ${o.output} = result; - } - `; -} -var Hd, - qd, - xe = L(() => { - (Hd = { - version: '', - attribute: 'attribute', - varyingVertex: 'varying', - varyingFrag: 'varying', - texture2D: 'texture2D', - output: 'gl_FragColor', - outputDeclaration: '', - }), - (qd = { - version: '#version 300 es', - attribute: 'in', - varyingVertex: 'out', - varyingFrag: 'in', - texture2D: 'texture', - output: 'outputColor', - outputDeclaration: 'out vec4 outputColor;', - }); - }), - ae = L(() => {}); -async function gi(t, e = (i) => 0, o) { - return new Promise((i, u) => { - let n = 0, - s = () => { - if (t()) { - i(); - return; - } - n++; - let d = e(n); - if (o != null && n >= o) { - u(); - return; - } - setTimeout(s, d); - }; - s(); - }); -} -function Kn(t) { - return ( - Cr(typeof t < 'u' && t.length !== 0, () => 'empty string found for sampler name'), - 'get' + t.charAt(0).toUpperCase() + t.slice(1) - ); -} -function Mu(t) { - return ( - Cr(typeof t < 'u' && t.length !== 0, () => 'empty string found for sampler name'), - 'get' + t.charAt(0).toUpperCase() + t.slice(1) + 'AtOutCoords' - ); -} -function kr(t, e) { - let o = JSON.parse(JSON.stringify(t)); - return (o = e), o; -} -function Br(t, e) { - return e.map((o) => t[o]).join(', '); -} -function Ke(t) { - if (t <= 1) return 'int'; - if (t === 2) return 'ivec2'; - if (t === 3) return 'ivec3'; - if (t === 4) return 'ivec4'; - if (t === 5) return 'ivec5'; - if (t === 6) return 'ivec6'; - throw Error(`GPU for rank ${t} is not yet supported`); -} -function St(t = 6) { - return ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, t); -} -var Ft = L(() => { - fe(); -}); -function jd(t, e) { - return St(e).map((o) => `${t}.${o}`); -} -function Nr(t, e) { - return e === 1 ? [t] : jd(t, e); -} -function $t() { - return ` - float getChannel(vec4 frag, int dim) { - int modCoord = imod(dim, 2); - return modCoord == 0 ? frag.r : frag.g; - } - - float getChannel(vec4 frag, vec2 innerDims) { - vec2 modCoord = mod(innerDims, 2.); - return modCoord.x == 0. ? - (modCoord.y == 0. ? frag.r : frag.g) : - (modCoord.y == 0. ? frag.b : frag.a); - } - `; -} -var br = L(() => { - Ft(); -}); -function Xd(t, e, o) { - if (t === 0) return 'false'; - if (t === 1) return `rc > ${e[0]}`; - let i = ''; - for (let u = t - 2; u < t; u++) (i += `${o[u]} >= ${e[u - t + 2]}`), u < t - 1 && (i += '||'); - return i; -} -function Kd(t, e) { - let o = t.length; - if (o === 0) return 'getA(), 0, 0, 0'; - if (o === 1) - return `getA(rc), - rc + 1 >= ${t[0]} ? 0. : getA(rc + 1), - 0, 0`; - let i = 'r, c', - u = 'r, cp1', - n = 'rp1, c', - s = 'rp1, cp1', - d = ''; - if (o > 2) for (let f = 0; f < o - 2; ++f) d = d + `${e[f]},`; - return `getA(${d}${i}), - rEdge ? 0. : getA(${d}${n}), - cEdge ? 0. : getA(${d}${u}), - rEdge || cEdge ? 0. : getA(${d}${s})`; -} -function Jd(t, e, o, i) { - return t === 0 || t === 1 - ? '' - : ` - int r = ${e[t - 2]}; - int c = ${e[t - 1]}; - int rp1 = ${e[t - 2]} + 1; - int cp1 = ${e[t - 1]} + 1; - bool rEdge = rp1 >= ${i}; - bool cEdge = cp1 >= ${o}; - `; -} -var Gu, - Yd, - Uu, - zu = L(() => { - xe(), - ae(), - Ft(), - br(), - (Gu = { name: 'pack', inputNames: ['A'], inputTypes: [1] }), - (Yd = (t, e) => { - let o = q(t.session.backend.glContext.version), - i = e.dims, - u = i.length, - n = e.dims.length, - s = Ke(n), - d = Nr('rc', n), - f = Jd(n, d, i[i.length - 2], i[i.length - 1]), - r; - u === 0 ? (r = [1, 1]) : u === 1 ? (r = [i[0], 1]) : (r = [i[n - 1], i[n - 2]]); - let a = Xd(n, r, d), - l = Kd(i, d), - p = ` - void main() { - ${s} rc = getOutputCoords(); - - if(${a}) { - ${o.output} = vec4(0); - } else { - ${f} - - ${o.output} = vec4(${l}); - } - } - `; - return { ...Gu, hasMain: !0, output: { dims: e.dims, type: e.type, textureType: 2 }, shaderSource: p }; - }), - (Uu = (t, e) => ({ ...Gu, get: () => Yd(t, e) })); - }); -function yi(t) { - if (t.length === 0) return [1, 1, 1]; - let e = 1; - for (let o = 0; o < t.length - 2; ++o) e *= t[o]; - return [e, t.length > 1 ? t[t.length - 2] : 1, t[t.length - 1]]; -} -function Wu(t, e) { - let o = !1; - return ( - t.length === 0 || e.length === 0 - ? (o = !0) - : t.length < 2 || e.length < 2 - ? (o = t[t.length - 1] === e[e.length - 1]) - : (o = t[t.length - 1] === e[e.length - 1] && t[t.length - 2] === e[e.length - 2]), - o - ); -} -function eh(t) { - let e = U.computeStrides(t), - o = ['b', 'r', 'c'], - i = 'index'; - return ` - ivec3 inputCoordsFromReshapedOutCoords(int index) { - ${e - .map((u, n) => { - let s = `int ${o[n]} = ${i} / ${u}`, - d = n === e.length - 1 ? `int ${o[n + 1]} = ${i} - ${o[n]} * ${u}` : `index -= ${o[n]} * ${u}`; - return `${s}; ${d};`; - }) - .join('')} - return ivec3(b, r, c); - } - `; -} -function th(t) { - let e = U.computeStrides(t); - return ` - int getFlattenedIndex(ivec3 coords) { - // reverse y, z order - return coords.x * ${e[0]} + coords.z * ${e[1]} + coords.y; - } -`; -} -var Zd, - Qd, - Vu, - Hu = L(() => { - fe(), - xe(), - ae(), - br(), - (Zd = (t) => ({ name: 'Reshape (packed)', inputTypes: [2], inputNames: ['A'], cacheHint: `${t}` })), - (Qd = (t, e, o, i) => { - let u = e.dims, - n = i, - s = ''; - for (let r = 0; r < 4; r++) { - let a = ''; - switch (r) { - case 0: - a = 'outputCoords = rc;'; - break; - case 1: - a = 'outputCoords = ivec3(rc.x, rc.y+1, rc.z);'; - break; - case 2: - a = 'outputCoords = ivec3(rc.x, rc.y, rc.z+1);'; - break; - case 3: - a = 'outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);'; - break; - default: - throw new Error(); - } - s += ` - ${a} - ${r > 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[${r}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); - - ${r > 0 ? '}' : ''} - `; - } - let d = q(t.session.backend.glContext.version), - f = ` - ${eh(u)} - ${th(n)} - ${$t()} - - void main() { - ivec3 rc = getOutputCoords(); - - vec4 result = vec4(0.0); - - ivec3 outputCoords; - int rows = ${n[2]}; - int cols = ${n[1]}; - - ${s} - ${d.output} = result; - } - `; - return { ...o, output: { dims: n, type: e.type, textureType: 2 }, shaderSource: f, hasMain: !0 }; - }), - (Vu = (t, e, o) => { - let i = Zd(o); - return { ...i, get: () => Qd(t, e, i, o) }; - }); - }), - Ti, - qu = L(() => { - xe(), - ae(), - (Ti = (t, e) => { - let o = e.shape, - i = q(t.session.backend.glContext.version), - u = ` - 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 = ${i.texture2D}(X,TexCoords).r; - ${i.output} = encodeAsUint8(value); - }`, - n = { - name: 'Uint8Encode', - inputTypes: [0], - inputNames: ['X'], - output: { dims: o, type: e.tensor.type, textureType: 3 }, - shaderSource: u, - hasMain: !0, - }; - return t.executeProgram(n, [e.tensor]); - }); - }); -function nh(t, e) { - if (t === 1) return 'rc'; - let o = ''; - for (let i = 0; i < t; i++) (o += e[i]), i < t - 1 && (o += ','); - return o; -} -var ju, - rh, - Yu, - Xu = L(() => { - xe(), - ae(), - Ft(), - br(), - (ju = { name: 'unpack', inputNames: ['A'], inputTypes: [2] }), - (rh = (t, e) => { - let o = e.dims.length, - i = Nr('rc', o), - u = i.slice(-2), - n = Ke(o), - s = $t(), - d = e.dims.length === 0 ? '' : nh(o, i), - f = o <= 1 ? 'rc' : `vec2(${u.join(',')})`, - r = q(t.session.backend.glContext.version), - a = ` - ${s} - void main() { - ${n} rc = getOutputCoords(); - - // Sample the texture with the coords to get the rgba channel value. - vec4 packedInput = getA(${d}); - - ${r.output} = vec4(getChannel(packedInput, ${f}), 0, 0, 0); - } - `; - return { ...ju, hasMain: !0, output: { dims: e.dims, type: e.type, textureType: 0 }, shaderSource: a }; - }), - (Yu = (t, e) => ({ ...ju, get: () => rh(t, e) })); - }), - Jn, - un, - Zn, - ln = L(() => { - ut(), - (Jn = class { - constructor(t, e = 1) { - if (e === 1) - (this.internalFormat = t.R32F), - (this.format = t.RED), - (this.textureType = t.FLOAT), - (this.channelSize = e); - else if (e === 4) - (this.internalFormat = t.RGBA32F), - (this.format = t.RGBA), - (this.textureType = t.FLOAT), - (this.channelSize = e); - else throw new Error(`Invalid number of channels: ${e}`); - } - encode(t, e) { - let o, i; - return ( - t.constructor !== Float32Array && - (ce.warning('Encoder', 'data was not of type Float32; creating new Float32Array'), - (i = new Float32Array(t))), - e * this.channelSize > t.length - ? (ce.warning('Encoder', 'Source data too small. Allocating larger array'), - (i = t), - (o = this.allocate(e * this.channelSize)), - i.forEach((u, n) => (o[n] = u))) - : ((i = t), (o = i)), - o - ); - } - allocate(t) { - return new Float32Array(t * 4); - } - decode(t, e) { - return this.channelSize === 1 ? t.filter((o, i) => i % 4 === 0).subarray(0, e) : t.subarray(0, e); - } - }), - (un = class { - constructor(t, e = 1, o) { - if (e !== 1 && e !== 4) throw new Error(`Invalid number of channels: ${e}`); - (this.internalFormat = t.RGBA), - (this.format = t.RGBA), - (this.channelSize = e), - (this.textureType = o || t.FLOAT); - } - encode(t, e) { - let o = t; - return ( - this.channelSize === 1 && - (ce.verbose('Encoder', 'Exploding into a larger array'), - (o = this.allocate(e)), - t.forEach((i, u) => (o[u * 4] = i))), - o - ); - } - allocate(t) { - return new Float32Array(t * 4); - } - decode(t, e) { - return this.channelSize === 1 ? t.filter((o, i) => i % 4 === 0).subarray(0, e) : t.subarray(0, e); - } - }), - (Zn = class { - constructor(t, e = 1) { - if (((this.channelSize = 4), e === 1)) - (this.internalFormat = t.ALPHA), - (this.format = t.ALPHA), - (this.textureType = t.UNSIGNED_BYTE), - (this.channelSize = e); - else if (e === 4) - (this.internalFormat = t.RGBA), - (this.format = t.RGBA), - (this.textureType = t.UNSIGNED_BYTE), - (this.channelSize = e); - else throw new Error(`Invalid number of channels: ${e}`); - } - encode(t, e) { - return new Uint8Array(t.buffer, t.byteOffset, t.byteLength); - } - allocate(t) { - return new Uint8Array(t * this.channelSize); - } - decode(t, e) { - if (t instanceof Uint8Array) return t.subarray(0, e); - throw new Error(`Invalid array type: ${t.constructor}`); - } - }); - }), - fn, - Ku, - xi, - Ju = L(() => { - fe(), - ae(), - (fn = (t, e, o) => { - let i = o === 0 || o === 1 ? 1 : 4, - u = o === 2, - n = o === 1 || o === 2, - s = o === 4 ? e.length - 1 : void 0, - d = o === 4 ? e.map((f, r) => (r === e.length - 1 ? f * 4 : f)) : void 0; - return xi(t, e, i, d, { isPacked: u, reverseWH: n, breakAxis: s }); - }), - (Ku = (t, e, o) => { - let i = fn(t, e, o); - return [i.width, i.height]; - }), - (xi = (t, e, o = 1, i, u) => { - let n = !!(u && u.isPacked), - [s, d] = t.computeTextureWH((n && i) || e, u), - f = e.length, - r = e.slice(0); - if ((f === 0 && (r = [1]), o === 1)) i = e; - else if (n) { - if (o !== 4) throw new Error('a packed texture must be 4-channel'); - (i = e), - f > 0 && (r[f - 1] = Math.ceil(r[f - 1] / 2)), - f > 1 && (r[f - 2] = Math.ceil(r[f - 2] / 2)); - } else if (!i) throw new Error('Unpacked shape is needed when using channels > 1'); - return { - width: s, - height: d, - channels: o, - isPacked: n, - shape: r, - strides: U.computeStrides(r), - unpackedShape: i, - reversedWH: u && u.reverseWH, - }; - }); - }), - ih, - Qn, - Qu = L(() => { - ut(), - mr(), - fe(), - zu(), - Hu(), - qu(), - Xu(), - ln(), - Ju(), - ae(), - (ih = (t, e) => { - let o = e.map((u) => `${u.unpackedShape.join(',')};${u.width}x${u.height}`).join('_'), - i = t.name; - return t.cacheHint && (i += '[' + t.cacheHint + ']'), (i += ':' + o), i; - }), - (Qn = class { - constructor(t) { - (this.session = t), - (this.packedTextureDataCache = new Map()), - (this.unpackedTextureDataCache = new Map()); - } - calculateTextureWidthAndHeight(t, e) { - return Ku(this.session.layoutStrategy, t, e); - } - executeProgram(t, e) { - if (e.length < t.inputNames.length) - throw new Error(`Input size mustn't be less than ${t.inputNames.length}.`); - if (t.inputNames.length !== t.inputTypes.length) - throw new Error('input names size does not match input types'); - let o = []; - for (let f = 0; f < t.inputNames.length; ++f) - o[f] = this.getOrCreateTextureData(e[f], t.inputTypes[f]); - let i = ih(t, o), - u = this.session.programManager.getArtifact(i), - n = u ? u.programInfo : typeof t.get == 'function' ? t.get() : t, - s = fn(this.session.layoutStrategy, n.output.dims, n.output.textureType), - d = this.createTextureData(s, n.output.type); - return ( - u || - ((u = this.session.programManager.build(n, o, d)), - this.session.programManager.setArtifact(i, u)), - this.runProgram(u, o, d), - d - ); - } - run(t, e) { - return this.executeProgram(t, e).tensor; - } - runProgram(t, e, o) { - for (let i = 0; i < e.length; ++i) - if (!!e[i].isPacked != (t.programInfo.inputTypes[i] === 2)) - throw new Error(`input[${i}] property packed inconsistent`); - if (!!o.isPacked != (t.programInfo.output.textureType === 2)) - throw new Error('output property packed inconsistent'); - this.session.programManager.run(t, e, o); - } - getOrCreateTextureData(t, e) { - let o = this.getTextureData(t.dataId, e === 2); - if (!o && ((o = this.getTextureData(t.dataId, e !== 2)), o)) - return e === 2 ? this.pack(o) : this.unpack(o); - if (!o) { - let i = fn(this.session.layoutStrategy, t.dims, e); - if (e === 4) { - let u = t.dims; - if (u.length === 4) { - let n = [u[0], Math.ceil((u[1] * u[2] * u[3]) / 4)], - s = fn(this.session.layoutStrategy, n, e), - d = t.numberData; - if ((u[1] * u[2] * u[3]) % 4 !== 0) { - let f = u[0], - r = u[1] * u[2] * u[3], - a = Math.ceil((r * 1) / 4) * 4, - l = f * a; - d = new Float32Array(l); - for (let p = 0; p < f; ++p) { - let m = p * r, - y = p * a + (p % 1) * r; - d.set(t.numberData.subarray(m, m + r), y); - } - } - return this.createTextureData(s, t.type, d, t, 1); - } - } - if (e === 2) { - let u = xi(this.session.layoutStrategy, t.dims, 1, [], { reverseWH: !0 }), - n = this.createTextureData(u, t.type, t.numberData, t, 1); - o = this.pack(n); - } else o = this.createTextureData(i, t.type, t.numberData, t, 1); - } - return o; - } - createTextureDataFromLayoutBindTensor(t, e, o, i) { - return this.createTextureData(t, e, o, i, 1); - } - createTextureData(t, e, o, i, u) { - ce.verbose('InferenceHandler', `Creating TextureData: layout:[${JSON.stringify(t)}]`); - let n = this.session.textureManager.createTextureFromLayout(e, t, o, u); - return this.createTextureDataFromTexture(t, e, n, i); - } - reshapeUnpacked(t, e) { - let o = this.getOrCreateTextureData(t, 0), - i = { - channels: o.channels, - height: o.height, - width: o.width, - shape: e.length !== 0 ? e : [1], - strides: U.computeStrides(e), - unpackedShape: e, - }; - return this.createTextureDataFromTexture(i, t.type, o.texture).tensor; - } - reshapePacked(t, e) { - let o = this.getOrCreateTextureData(t, 2); - if (Wu(t.dims, e)) { - let d = { - channels: o.channels, - height: o.height, - width: o.width, - shape: e.length !== 0 ? e : [1], - strides: U.computeStrides(e), - unpackedShape: e, - isPacked: !0, - }; - return this.createTextureDataFromTexture(d, t.type, o.texture).tensor; - } - let i = yi(t.dims), - u = yi(e), - n = this.reshapePacked(t, i), - s = this.run(Vu(this, n, u), [n]); - return this.reshapePacked(s, e); - } - cast(t, e) { - let o = this.getOrCreateTextureData(t, 0); - return this.createTextureDataFromTexture(o, e, o.texture).tensor; - } - createTextureDataFromTexture(t, e, o, i, u) { - let n = { - ...t, - tensor: - i || - new Fe( - t.unpackedShape, - e, - (s) => this.readTexture(n), - async (s) => this.readTextureAsync(n), - void 0, - u - ), - texture: o, - }; - return this.setTextureData(n.tensor.dataId, n, t.isPacked), n; - } - getTextureData(t, e = !1) { - return this.session.isInitializer(t) - ? this.session.getTextureData(t, e) - : e - ? this.packedTextureDataCache.get(t) - : this.unpackedTextureDataCache.get(t); - } - setTextureData(t, e, o = !1) { - this.session.isInitializer(t) - ? this.session.setTextureData(t, e, o) - : (o ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(t, e); - } - isTextureLayoutCached(t, e = !1) { - return !!this.getTextureData(t.dataId, e); - } - dispose() { - this.session.textureManager.clearActiveTextures(), - this.packedTextureDataCache.forEach((t) => this.session.textureManager.releaseTexture(t)), - (this.packedTextureDataCache = new Map()), - this.unpackedTextureDataCache.forEach((t) => this.session.textureManager.releaseTexture(t)), - (this.unpackedTextureDataCache = new Map()); - } - readTexture(t) { - return t.isPacked - ? this.readTexture(this.unpack(t)) - : this.session.backend.glContext.isFloat32DownloadSupported - ? this.session.textureManager.readTexture(t, t.tensor.type, t.channels) - : this.session.textureManager.readUint8TextureAsFloat(Ti(this, t)); - } - async readTextureAsync(t) { - return t.isPacked - ? this.readTextureAsync(this.unpack(t)) - : this.session.backend.glContext.isFloat32DownloadSupported - ? this.session.textureManager.readTextureAsync(t, t.tensor.type, t.channels) - : this.session.textureManager.readUint8TextureAsFloat(Ti(this, t)); - } - pack(t) { - return this.executeProgram(Uu(this, t.tensor), [t.tensor]); - } - unpack(t) { - return this.executeProgram(Yu(this, t.tensor), [t.tensor]); - } - }); - }), - vi, - ee, - Ge = L(() => { - (vi = class { - constructor(t) { - Object.assign(this, t); - } - get cacheKey() { - return ( - this.key || - (this.key = Object.getOwnPropertyNames(this) - .sort() - .map((t) => `${this[t]}`) - .join(';')), - this.key - ); - } - }), - (ee = (t) => new vi(t)); - }), - el, - tl, - rl, - ah, - sh, - nl = L(() => { - Ge(), - xe(), - ae(), - (el = { - name: 'BatchNormalization', - inputNames: ['A', 'Scale', 'B', 'Mean', 'Variance'], - inputTypes: [0, 0, 0, 0, 0], - }), - (tl = (t, e, o) => (sh(e), [t.run({ ...el, cacheHint: o.cacheKey, get: () => ah(t, e, o) }, e)])), - (rl = (t) => { - let e = t.attributes.getFloat('epsilon', 1e-5), - o = t.attributes.getFloat('momentum', 0.9), - i = t.attributes.getInt('spatial', 1); - return ee({ epsilon: e, momentum: o, spatial: i }); - }), - (ah = (t, e, o) => { - let i = q(t.session.backend.glContext.version), - u = e[0].dims.length, - [n, s] = t.calculateTextureWidthAndHeight(e[1].dims, 0), - d = ` - float process(int[${u}] indices) { - vec2 position = offsetToCoords(indices[1], ${n}, ${s}); - float scale = getColorAsFloat(${i.texture2D}(Scale, position)); - float mean = getColorAsFloat(${i.texture2D}(Mean, position)); - float variance = getColorAsFloat(${i.texture2D}(Variance, position)); - float b = getColorAsFloat(${i.texture2D}(B, position)); - - return scale * ( (_A(indices) - mean) / sqrt(variance + float(${o.epsilon})) ) + b; - }`; - return { ...el, output: { dims: e[0].dims, type: e[0].type, textureType: 0 }, shaderSource: d }; - }), - (sh = (t) => { - if (!t || t.length !== 5) throw new Error('BatchNormalization requires 5 inputs.'); - let e = t[0], - o = t[1], - i = t[2], - u = t[3], - n = t[4]; - if ( - e.dims.length < 3 || - o.dims.length !== 1 || - i.dims.length !== 1 || - u.dims.length !== 1 || - n.dims.length !== 1 - ) - throw new Error('invalid input shape.'); - if ( - o.dims[0] !== e.dims[1] || - i.dims[0] !== e.dims[1] || - u.dims[0] !== e.dims[1] || - n.dims[0] !== e.dims[1] - ) - throw new Error('invalid input shape.'); - if ( - (e.type !== 'float32' && e.type !== 'float64') || - (o.type !== 'float32' && o.type !== 'float64') || - (i.type !== 'float32' && i.type !== 'float64') || - (u.type !== 'float32' && u.type !== 'float64') || - (n.type !== 'float32' && n.type !== 'float64') - ) - throw new Error('invalid input tensor types.'); - }); - }), - eo, - pt, - R, - cn, - to, - Vt = L(() => { - (eo = class { - constructor(t, e, o, i) { - (this.glContext = t), - (this.programInfo = e), - (this.inputTextureLayouts = o), - (this.outputTextureLayout = i); - } - }), - (pt = class { - constructor(t) { - this.context = t; - } - }), - (R = class { - constructor(t, e) { - (this.routineBody = t), (this.dependencies = e); - } - }), - (cn = class { - constructor(t, e, o) { - (this.name = t), - o ? (this.dependencies = o) : (this.dependencies = []), - e && (this.routineBody = e); - } - addDependency(t) { - t && this.dependencies.push(t); - } - }), - (to = class { - static returnOrderedNodes(t) { - if (!t || t.length === 0) return []; - if (t.length === 1) return t; - let e = new Set(), - o = new Set(), - i = new Array(); - return this.createOrderedNodes(t, e, o, i), i; - } - static createOrderedNodes(t, e, o, i) { - for (let u = 0; u < t.length; ++u) this.dfsTraverse(t[u], e, o, i); - } - static dfsTraverse(t, e, o, i) { - if (!t || o.has(t.name)) return; - if (e.has(t.name)) - throw new Error( - "Cyclic dependency detected. Can't topologically sort routines needed for shader." - ); - e.add(t.name); - let u = t.dependencies; - if (u && u.length > 0) for (let n = 0; n < u.length; ++n) this.dfsTraverse(u[n], e, o, i); - i.push(t), o.add(t.name), e.delete(t.name); - } - }); - }); -function lh() { - let t = 'add_'; - return { - body: ` - float ${t}(float a, float b) { - return a + b; - } - vec4 ${t}(vec4 v1, vec4 v2) { - return v1 + v2; - } - `, - name: t, - type: 0, - }; -} -function fh() { - let t = 'div_'; - return { - body: ` - float ${t}(float a, float b) { - return a / b; - } - vec4 ${t}(vec4 v1, vec4 v2) { - return v1 / v2; - } - `, - name: t, - type: 0, - }; -} -function ch() { - let t = 'mul_'; - return { - body: ` - float ${t}(float a, float b) { - return a * b; - } - vec4 ${t}(vec4 v1, vec4 v2) { - return v1 * v2; - } - `, - name: t, - type: 0, - }; -} -function ph() { - let t = 'sub_'; - return { - body: ` - float ${t}(float a, float b) { - return a - b; - } - vec4 ${t}(vec4 v1, vec4 v2) { - return v1 - v2; - } - `, - name: t, - type: 0, - }; -} -function dh() { - let t = 'equal_'; - return { - body: ` - float ${t}(float a, float b) { - return float(a == b); - } - vec4 ${t}(vec4 v1, vec4 v2) { - return vec4(equal(v1, v2)); - } - `, - name: t, - type: 0, - }; -} -function hh() { - let t = 'greater_'; - return { - body: ` - float ${t}(float a, float b) { - return float(a > b); - } - vec4 ${t}(vec4 v1, vec4 v2) { - return vec4( v1.r > v2.r , - v1.g > v2.g, - v1.b > v2.b, - v1.a > v2.a ); - } - `, - name: t, - type: 0, - }; -} -function mh() { - let t = 'less_'; - return { - body: ` - float ${t}(float a, float b) { - return float(a < b); - } - vec4 ${t}(vec4 v1, vec4 v2) { - return vec4( v1.r < v2.r , - v1.g < v2.g, - v1.b < v2.b, - v1.a < v2.a ); - } - `, - name: t, - type: 0, - }; -} -function bh() { - let t = 'and_'; - return { - body: ` - float ${t}(float a, float b) { - return float( bool(a) && bool(b) ); - } - vec4 ${t}(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: t, - type: 0, - }; -} -function gh() { - let t = 'or_'; - return { - body: ` - float ${t}(float a, float b) { - return float( bool(a) || bool(b) ); - } - vec4 ${t}(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: t, - type: 0, - }; -} -function yh() { - let t = 'xor_'; - return { - body: ` - float ${t}(float a, float b) { - return float( bool(a) ^^ bool(b) ); - } - vec4 ${t}(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: t, - type: 0, - }; -} -function Th() { - return vh('pow'); -} -function xh() { - let t = 'prelu_'; - return { - body: ` - float ${t}(float a, float b) { - return a < 0.0 ? a * b: a; - } - vec4 ${t}(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: t, - type: 0, - }; -} -function vh(t) { - let e = `${t}_`; - return { - body: ` - float ${e}(float a, float b) { - return ${t}(a, b); - } - vec4 ${e}(vec4 v1, vec4 v2) { - return ${t}(v1, v2); - } - `, - name: e, - type: 0, - }; -} -var dt, - wh, - ol, - il, - al, - sl, - ul, - ll, - fl, - cl, - pl, - dl, - hl, - ml, - bl = L(() => { - fe(), - Vt(), - xe(), - ae(), - (dt = (t, e, o, i = e[0].type, u) => { - let n = t.session.pack ? 2 : 0; - return { - name: o.name, - inputNames: ['A', 'B'], - inputTypes: [n, n], - cacheHint: u, - get: () => wh(t, e, o, i), - }; - }), - (wh = (t, e, o, i = e[0].type) => { - let u = t.session.pack ? 2 : 0, - n = !U.areEqual(e[0].dims, e[1].dims), - s = e[0].dims, - d = t.session.pack; - if (n) { - let a = Xe.calcShape(e[0].dims, e[1].dims, !1); - if (!a) throw new Error("Can't perform binary op on the given tensors"); - s = a; - let l = s.length, - p = e[0].dims.length !== 0 ? e[0].dims.length : 1, - m = e[1].dims.length !== 0 ? e[1].dims.length : 1, - y = e[0].dims.length !== 0 ? 'bcastIndices_A(indices, aindices);' : 'aindices[0] = 0;', - T = e[1].dims.length !== 0 ? 'bcastIndices_B(indices, bindices);' : 'bindices[0] = 0;', - v = q(t.session.backend.glContext.version), - S = d - ? ` - ${o.body} - void main() { - vec4 a = getAAtOutCoords(); - vec4 b = getBAtOutCoords(); - vec4 result = ${o.name}(a, b); - ${v.output} = result; - }` - : ` - ${o.body} - float process(int indices[${l}]) { - int aindices[${p}]; - int bindices[${m}]; - ${y} - ${T} - return ${o.name}(_A(aindices), _B(bindices)); - }`; - return { - name: o.name, - inputNames: ['A', 'B'], - inputTypes: [u, u], - output: { dims: s, type: i, textureType: u }, - shaderSource: S, - hasMain: d, - }; - } - let f = q(t.session.backend.glContext.version), - r = ` - ${o.body} - void main() { - vec4 v1 = ${f.texture2D}(A, TexCoords); - vec4 v2 = ${f.texture2D}(B, TexCoords); - vec4 result = ${o.name}(v1, v2); - ${f.output} = result; - } - `; - return { - name: o.name, - inputNames: ['A', 'B'], - inputTypes: [u, u], - output: { dims: e[0].dims, type: i, textureType: u }, - shaderSource: r, - hasMain: !0, - }; - }), - (ol = (t, e) => [t.run(dt(t, e, lh()), e)]), - (il = (t, e) => [t.run(dt(t, e, bh(), 'bool'), e)]), - (al = (t, e) => [t.run(dt(t, e, fh()), e)]), - (sl = (t, e) => [t.run(dt(t, e, dh(), 'bool'), e)]), - (ul = (t, e) => [t.run(dt(t, e, hh(), 'bool'), e)]), - (ll = (t, e) => [t.run(dt(t, e, mh(), 'bool'), e)]), - (fl = (t, e) => [t.run(dt(t, e, ch()), e)]), - (cl = (t, e) => [t.run(dt(t, e, gh(), 'bool'), e)]), - (pl = (t, e) => [t.run(dt(t, e, Th()), e)]), - (dl = (t, e) => [t.run(dt(t, e, xh()), e)]), - (hl = (t, e) => [t.run(dt(t, e, ph()), e)]), - (ml = (t, e) => [t.run(dt(t, e, yh(), 'bool'), e)]); - }), - gl, - yl, - Oh, - Tl = L(() => { - fe(), - (gl = (t, e, o) => (Oh(e), [t.cast(e[0], o)])), - (yl = (t) => Ve.tensorDataTypeFromProto(t.attributes.getInt('to'))), - (Oh = (t) => { - if (!t || t.length !== 1) throw new Error('Cast requires 1 input.'); - if (t[0].type === 'string') throw new Error('Invalid input type.'); - }); - }), - Ih, - Sh, - xl, - ro, - vl = L(() => { - xe(), - ae(), - Ft(), - br(), - (Ih = (t, e) => ({ - name: 'Concat (packed)', - inputNames: Array.from({ length: t }, (o, i) => `X${i}`), - inputTypes: Array(t).fill(2), - cacheHint: e, - })), - (Sh = (t, e, o, i) => { - let u = o[0].dims.slice(); - if (i >= u.length || i < -1 * u.length) - throw new Error("axis specified for concat doesn't match input dimensionality"); - i < 0 && (i = u.length + i); - let n = u.slice(0); - for (let B = 1; B < o.length; B++) { - let J = o[B].dims.slice(); - for (let Q = 0; Q < u.length; Q++) - if (Q === i) n[i] += J[Q]; - else if (u[Q] !== J[Q]) throw new Error('non concat dimensions must match'); - } - let s = n.length, - d = Nr('coords', s), - f = Ke(s), - r = $t(), - a = o.map((B) => B.dims), - l = St(s), - p = new Array(a.length - 1); - p[0] = a[0][i]; - for (let B = 1; B < p.length; B++) p[B] = p[B - 1] + a[B][i]; - let m = l[i], - y = l.slice(-2), - T = l.join(), - v = `if (${m} < ${p[0]}) { - return getChannel( - getX0(${T}), vec2(${y.join()})); - }`; - for (let B = 1; B < p.length; B++) { - let J = p[B - 1]; - v += ` - if (${m} < ${p[B]} && ${m} >= ${p[B - 1]}) { - return getChannel( - getX${B}(${ro(l, m, J)}), - vec2(${ro(y, m, J)})); - }`; - } - let S = p.length, - E = p[p.length - 1]; - v += ` - return getChannel( - getX${S}(${ro(l, m, E)}), - vec2(${ro(y, m, E)}));`; - let A = q(t.session.backend.glContext.version), - F = ` - ${r} - float getValue(${l.map((B) => 'int ' + B)}) { - ${v} - } - - void main() { - ${f} coords = getOutputCoords(); - int lastDim = coords.${l[s - 1]}; - coords.${l[s - 1]} = coords.${l[s - 2]}; - coords.${l[s - 2]} = lastDim; - - vec4 result = vec4(getValue(${d}), 0., 0., 0.); - - ${d[s - 1]} = ${d[s - 1]} + 1; - if (${d[s - 1]} < ${n[s - 1]}) { - result.g = getValue(${d}); - } - - ${d[s - 2]} = ${d[s - 2]} + 1; - if (${d[s - 2]} < ${n[s - 2]}) { - result.a = getValue(${d}); - } - - ${d[s - 1]} = ${d[s - 1]} - 1; - if (${d[s - 2]} < ${n[s - 2]} && - ${d[s - 1]} < ${n[s - 1]}) { - result.b = getValue(${d}); - } - ${A.output} = result; - } - `; - return { ...e, output: { dims: n, type: o[0].type, textureType: 2 }, shaderSource: F, hasMain: !0 }; - }), - (xl = (t, e, o) => { - let i = Ih(e.length, o.cacheKey); - return { ...i, get: () => Sh(t, i, e, o.axis) }; - }), - (ro = (t, e, o) => { - let i = t.indexOf(e); - return t.map((u, n) => (n === i ? `${u} - ${o}` : u)).join(); - }); - }), - wl, - Ah, - Ph, - Eh, - _l, - Dh, - Lh, - Fh, - Ol, - $h, - Il = L(() => { - Ge(), - ae(), - vl(), - (wl = (t, e, o) => ( - $h(e), t.session.pack && e[0].dims.length > 1 ? [t.run(xl(t, e, o), e)] : [t.run(Eh(t, e, o), e)] - )), - (Ah = (t, e) => ({ - name: 'Concat', - inputNames: Array.from({ length: t }, (o, i) => `X${i}`), - inputTypes: Array(t).fill(0), - cacheHint: e, - })), - (Ph = (t, e, o, i) => { - let u = o[0].dims.slice(); - if (i >= u.length || i < -1 * u.length) - throw new Error("axis specified for concat doesn't match input dimensionality"); - i < 0 && (i = u.length + i); - let n = u.slice(0); - for (let m = 1; m < o.length; m++) { - let y = o[m].dims.slice(); - for (let T = 0; T < u.length; T++) - if (T === i) n[i] += y[T]; - else if (u[T] !== y[T]) throw new Error('non concat dimensions must match'); - } - let s = n.length, - d = new Array(o.length), - f = 0; - for (let m = 0; m < d.length; ++m) (f += o[m].dims[i]), (d[m] = f); - let r = ''; - o.length < 5 ? (r = _l(d)) : (r = Dh(d)); - let a = Lh(o.length, s), - l = Fh(d), - p = ` - ${a} - ${l} - ${r} - float process(int indices[${s}]) { - int textureIndex = getTextureWhereDataResides (indices[${i}]); - - if(textureIndex != 0) { - indices[${i}] = indices[${i}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1))); - } - - return fetchDataFromCorrectTexture(textureIndex, indices); - }`; - return { ...e, output: { dims: n, type: o[0].type, textureType: 0 }, shaderSource: p }; - }), - (Eh = (t, e, o) => { - let i = Ah(e.length, o.cacheKey); - return { ...i, get: () => Ph(t, i, e, o.axis) }; - }), - (_l = (t) => `int getTextureWhereDataResides(int index) { - ${t - .map( - (e, o) => `if(index<${e}) {return ${o};} -` - ) - .join('')} - }`), - (Dh = (t) => _l(t)), - (Lh = (t, e) => { - let o = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e}]) {`]; - for (let i = 0; i < t; ++i) - i === 0 - ? o.push(` if (textureIndex == ${i}) { return _X${i}(indices); }`) - : i === t - 1 - ? o.push(` else { return _X${i}(indices); }`) - : o.push(` else if (textureIndex == ${i}) { return _X${i}(indices); }`); - return ( - o.push(' }'), - o.join(` -`) - ); - }), - (Fh = (t) => { - let e = ['int getSizeInConcatAxisValueFromIndex(int index) {']; - for (let o = 0; o < t.length; ++o) - o === 0 - ? e.push(` if (index == ${o}) { return ${t[o]}; }`) - : o === t.length - 1 - ? e.push(` else { return ${t[o]}; }`) - : e.push(` else if (index == ${o}) { return ${t[o]}; }`); - return ( - e.push(' }'), - e.join(` -`) - ); - }), - (Ol = (t) => ee({ axis: t.attributes.getInt('axis') })), - ($h = (t) => { - if (!t || t.length < 1) throw new Error('too few inputs'); - let e = t[0].type, - o = t[0].dims.length; - if (e === 'string') throw new Error('string tensor is not supported yet'); - for (let i of t) { - if (i.type !== e) throw new Error('input tensors should be one type'); - if (i.dims.length !== o) throw new Error('input tensors should have the same shape'); - } - }); - }); -function Ch() { - return ht('abs'); -} -function kh() { - return ht('acos'); -} -function Bh() { - return ht('asin'); -} -function Nh() { - return ht('atan'); -} -function Rh() { - return ht('ceil'); -} -function Mh() { - return ht('cos'); -} -function Gh(t) { - let e = 'elu'; - return { - body: ` - const float alpha = float(${t}); - - float ${e}_(float a) { - return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; - } - vec4 ${e}_(vec4 v) { - return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); - } - `, - name: e, - type: 0, - }; -} -function Uh() { - return ht('exp'); -} -function zh() { - return ht('floor'); -} -function wi(t, e) { - let o = 'clip'; - return { - body: ` - const float min = float(${t}); - const float max = float(${e}); - - float ${o}_(float a) { - return clamp(a, min, max); - } - vec4 ${o}_(vec4 v) { - return clamp(v, min, max); - } - `, - name: o, - type: 0, - }; -} -function Vh() { - let t = 'indentity'; - return { - body: ` - float ${t}_(float a) { - return a; - } - vec4 ${t}_(vec4 v) { - return v; - } - `, - name: t, - type: 0, - }; -} -function Wh(t) { - let e = 'leakyRelu'; - return { - body: ` - const float alpha = float(${t}); - - float ${e}_(float a) { - return a < 0.0 ? a * alpha : a; - } - vec4 ${e}_(vec4 v) { - return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); - } - `, - name: e, - type: 0, - }; -} -function Hh() { - return ht('log'); -} -function qh() { - let t = 'neg'; - return { - body: ` - float ${t}_(float a) { - return -a; - } - vec4 ${t}_(vec4 v) { - return -v; - } - `, - name: t, - type: 0, - }; -} -function jh() { - let t = 'not'; - return { - body: ` - float ${t}_(float a) { - return float( ! bool(a) ); - } - bool ${t}_(bool a) { - return !a; - } - vec4 ${t}_(vec4 v) { - return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); - } - bvec4 ${t}_(bvec4 v) { - return bvec4(!v.x, !v.y, !v.z, !v.w); - } - `, - name: t, - type: 0, - }; -} -function Yh() { - return ht('sin'); -} -function _i() { - let t = 'relu'; - return { - body: ` - float ${t}_(float a) { - return max( a, 0.0 ); - } - vec4 ${t}_(vec4 v) { - return max( v, 0.0 ); - } - `, - name: t, - type: 0, - }; -} -function Oi() { - let t = 'sigmoid'; - return { - body: ` - float ${t}_(float a) { - return 1.0 / (1.0 + exp(-a)); - } - vec4 ${t}_(vec4 v) { - return 1.0 / (1.0 + exp(-v)); - } - `, - name: t, - type: 0, - }; -} -function Xh() { - return ht('sqrt'); -} -function Kh() { - return ht('tan'); -} -function Jh() { - let t = 'tanh'; - return { - body: ` - float ${t}_(float a) { - a = clamp(a, -10., 10.); - a = exp(2.*a); - return (a - 1.) / (a + 1.); - } - vec4 ${t}_(vec4 v) { - v = clamp(v, -10., 10.); - v = exp(2.*v); - return (v - 1.) / (v + 1.); - } - `, - name: t, - type: 0, - }; -} -function ht(t) { - return { - body: ` - float ${t}_(float a) { - return ${t}(a); - } - vec4 ${t}_(vec4 v) { - return ${t}(v); - } - `, - name: t, - type: 0, - }; -} -var Zh, - Pe, - Sl, - Al, - Pl, - El, - Ii, - Dl, - Ll, - Qh, - Fl, - $l, - Cl, - kl, - Bl, - Nl, - Si, - Rl, - Ml, - Gl, - Ul, - zl, - Vl, - Wl, - Hl, - ql, - jl, - Yl, - Ai = L(() => { - Ge(), - fe(), - Vt(), - xe(), - ae(), - (Zh = (t, e, o, i) => { - let u = t.session.pack ? 2 : 0, - n = q(t.session.backend.glContext.version); - return { - ...e, - output: { dims: o.dims, type: o.type, textureType: u }, - shaderSource: ` - ${i.body} - void main() { - vec4 v = ${n.texture2D}(A, TexCoords); - v = ${i.name}_(v); - ${n.output} = v; - } - `, - hasMain: !0, - }; - }), - (Pe = (t, e, o, i) => { - let u = t.session.pack ? 2 : 0, - n = { name: o.name, inputTypes: [u], inputNames: ['A'], cacheHint: i }; - return { ...n, get: () => Zh(t, n, e, o) }; - }), - (Sl = (t, e) => [t.run(Pe(t, e[0], Ch()), e)]), - (Al = (t, e) => [t.run(Pe(t, e[0], kh()), e)]), - (Pl = (t, e) => [t.run(Pe(t, e[0], Bh()), e)]), - (El = (t, e) => [t.run(Pe(t, e[0], Nh()), e)]), - (Ii = (t, e, o) => [t.run(Pe(t, e[0], wi(o.min, o.max), o.cacheKey), e)]), - (Dl = (t) => ee({ min: t.attributes.getFloat('min', dr), max: t.attributes.getFloat('max', hr) })), - (Ll = (t, e) => { - let o = Qh(t, e); - return Ii(t, [e[0]], o); - }), - (Qh = (t, e) => { - if (e.length >= 3 && (!t.session.isInitializer(e[1].dataId) || !t.session.isInitializer(e[2].dataId))) - throw new Error('dynamic clip attributes are not allowed'); - let o = e.length >= 3 ? e[1].numberData[0] : dr, - i = e.length >= 3 ? e[2].numberData[0] : hr; - return ee({ min: o, max: i }); - }), - (Fl = (t, e) => [t.run(Pe(t, e[0], Rh()), e)]), - ($l = (t, e) => [t.run(Pe(t, e[0], Mh()), e)]), - (Cl = (t, e, o) => [t.run(Pe(t, e[0], Gh(o.alpha), o.cacheKey), e)]), - (kl = (t) => ee({ alpha: t.attributes.getFloat('alpha', 1) })), - (Bl = (t, e) => [t.run(Pe(t, e[0], Uh()), e)]), - (Nl = (t, e) => [t.run(Pe(t, e[0], zh()), e)]), - (Si = (t, e) => [t.run(Pe(t, e[0], Vh()), e)]), - (Rl = (t, e, o) => [t.run(Pe(t, e[0], Wh(o.alpha), o.cacheKey), e)]), - (Ml = (t) => ee({ alpha: t.attributes.getFloat('alpha', 0.01) })), - (Gl = (t, e) => [t.run(Pe(t, e[0], Hh()), e)]), - (Ul = (t, e) => [t.run(Pe(t, e[0], qh()), e)]), - (zl = (t, e) => [t.run(Pe(t, e[0], jh()), e)]), - (Vl = (t, e) => [t.run(Pe(t, e[0], _i()), e)]), - (Wl = (t, e) => [t.run(Pe(t, e[0], Oi()), e)]), - (Hl = (t, e) => [t.run(Pe(t, e[0], Yh()), e)]), - (ql = (t, e) => [t.run(Pe(t, e[0], Xh()), e)]), - (jl = (t, e) => [t.run(Pe(t, e[0], Kh()), e)]), - (Yl = (t, e) => [t.run(Pe(t, e[0], Jh()), e)]); - }); -function Ct(t) { - let e; - switch (t.activation) { - case 'Relu': - e = _i(); - break; - case 'Sigmoid': - e = Oi(); - break; - case 'Clip': - e = wi(t.clipMin, t.clipMax); - break; - default: - return { activationFunction: '', applyActivation: '' }; - } - let o = e.name, - i = e.body, - u = `value = ${o}_(value);`; - return { activationFunction: i, applyActivation: u }; -} -var Rr, - gr = L(() => { - fe(), - Ai(), - (Rr = (t) => { - let e = t.getString('activation', ''); - if (e === 'Clip') { - let [o, i] = t.getFloats('activation_params', [dr, hr]); - return { activation: e, clipMax: i, clipMin: o, activationCacheKey: `${e}:${o},${i}` }; - } - return { activation: e, activationCacheKey: e }; - }); - }), - tm, - rm, - Xl, - Kl = L(() => { - ut(), - xe(), - ae(), - no(), - gr(), - (tm = (t, e) => ({ - name: 'GroupedConv', - inputNames: t ? ['X', 'W', 'Bias'] : ['X', 'W'], - inputTypes: t ? [0, 0, 0] : [0, 0], - cacheHint: e, - })), - (rm = (t, e, o, i) => { - let u = e.length > 2 ? 'value += getBias(output_channel);' : '', - n = e[0].dims.slice(), - s = e[1].dims.slice(), - d = s[0] / i.group; - ce.verbose( - 'GroupedConv', - `autpPad:${i.autoPad}, dilations:${i.dilations}, group:${i.group}, kernelShape:${i.kernelShape}, pads:${i.pads}, strides:${i.strides}` - ); - let f = Mr(n, s, i.dilations, i.pads, i.strides), - r = q(t.session.backend.glContext.version), - { activationFunction: a, applyActivation: l } = Ct(i), - p = ` - const ivec2 strides = ivec2(${i.strides[0]}, ${i.strides[1]}); - const ivec2 pads = ivec2(${i.pads[0]}, ${i.pads[1]}); - ${a} - 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 / ${d}; - - float value = 0.0; - for (int wInChannel = 0; wInChannel < ${s[1]}; wInChannel++) { - int input_channel = group_id * ${s[1]} + wInChannel; - for (int wHeight = 0; wHeight < ${s[2]}; wHeight++) { - int xHeight = xRCCorner.x + wHeight * ${i.dilations[0]}; - - if (xHeight < 0 || xHeight >= ${n[2]}) { - continue; - } - - for (int wWidth = 0; wWidth < ${s[3]}; wWidth++) { - int xWidth = xRCCorner.y + wWidth * ${i.dilations[1]}; - if (xWidth < 0 || xWidth >= ${n[3]}) { - continue; - } - - float xVal = getX(batch, input_channel, xWidth, xHeight); - float wVal = getW(output_channel, wInChannel, wWidth, wHeight); - value += xVal*wVal; - } - } - } - ${u} - ${l} - ${r.output} = vec4(value, .0, .0, .0); - } -`; - return { ...o, output: { dims: f, type: e[0].type, textureType: 0 }, shaderSource: p, hasMain: !0 }; - }), - (Xl = (t, e, o) => { - let i = tm(e.length > 2, o.cacheKey); - return { ...i, get: () => rm(t, e, i, o) }; - }); - }), - nm, - om, - Jl, - Zl = L(() => { - xe(), - ae(), - br(), - (nm = (t) => ({ name: 'Im2Col (packed)', inputNames: ['A'], inputTypes: [2], cacheHint: t })), - (om = (t, e, o, i, u, n) => { - let s = o.dims, - d = i.dims, - f = 2, - r = 3, - a = u.length, - l = [d[1] * d[2] * d[3], u[2] * u[3]], - p = d[2] * d[3], - m = $t(), - y = q(t.session.backend.glContext.version), - T = ''; - for (let S = 0; S <= 1; S++) - for (let E = 0; E <= 1; E++) - T += ` - blockIndex = rc.x + ${E}; - pos = rc.y + ${S}; - - if(blockIndex < ${l[1]} && pos < ${l[0]}) { - offsetY = int(blockIndex / (${u[a - 1]})) * ${n.strides[0]} - - ${n.pads[0]}; - d0 = offsetY + ${n.dilations[0]} * (imod(pos, ${p}) / ${d[2]}); - - if(d0 < ${s[f]} && d0 >= 0) { - offsetX = imod(blockIndex, ${u[a - 1]}) * ${n.strides[1]} - - ${n.pads[1]}; - d1 = offsetX + ${n.dilations[1]} * imod(imod(pos, ${p}), ${d[2]}); - - if(d1 < ${s[r]} && d1 >= 0) { - - ch = int(float(pos)/ ${p}.); - innerDims = vec2(d0, d1); - result[${S * 2 + E}] = getChannel( - getA(0, ch, int(innerDims.x), - int(innerDims.y)), innerDims); - } - } - } - - `; - let v = ` - ${m} - - void main() { - ivec2 rc = getOutputCoords(); - vec4 result = vec4(0.0); - int blockIndex, pos, offsetY, d0, offsetX, d1, ch; - vec2 innerDims; - ${T} - ${y.output} = result; - } - `; - return { ...e, output: { dims: l, type: o.type, textureType: 2 }, shaderSource: v, hasMain: !0 }; - }), - (Jl = (t, e, o, i, u) => { - let n = nm(u.cacheKey); - return { ...n, get: () => om(t, n, e, o, i, u) }; - }); - }); -function am(t, e, o) { - let i = e[0].dims, - u = e[1].dims, - n = Xe.calcShape(i, u, !0); - if (!n) throw new Error("Can't use matmul on the given tensors"); - let s = Ke(n.length), - d = St(), - { activationFunction: f, applyActivation: r } = Ct(o), - a = e.length > 2, - l = a ? 'value += getBiasForMatmul();' : '', - p = a ? `${Ei(s, d, e[2].dims, n, !1)}` : '', - m = n.length, - y = i.length, - T = u.length, - v = i[i.length - 1], - S = ` - ${f} - ${p} - float process(int indices[${m}]) { - int a[${y}]; - int b[${T}]; - bcastMatmulIndices_A(indices, a); - bcastMatmulIndices_B(indices, b); - - float value; - for (int k=0; k<${v}; ++k) { - a[${y - 1}] = k; - b[${T - 2}] = k; - value += _A(a) * _B(b); - } - ${l} - ${r} - return value; - }`; - return { ...t, output: { dims: n, type: e[0].type, textureType: 0 }, shaderSource: S }; -} -function Pi(t, e) { - let o = im(t.length > 2, e.activationCacheKey); - return { ...o, get: () => am(o, t, e) }; -} -function Ei(t, e, o, i, u) { - let n = '', - s = o.length, - d = i.length, - f = d - s; - d < 2 && s > 0 ? (n = 'coords') : (n = o.map((p, m) => `coords.${e[m + f]}`).join(', ')); - let r = Xe.getBroadcastDims(o, i).map((p) => `coords.${e[p + f]} = 0;`).join(` -`), - a = U.size(o) === 1, - l = 'vec4(outputValue.xx, outputValue.yy)'; - return ( - a && (l = 'vec4(outputValue.x)'), - u - ? ` -vec4 getBiasForMatmul() { - ${t} coords = getOutputCoords(); - ${r} - vec4 outputValue = getBias(${n}); - return ${l}; -}` - : ` -float getBiasForMatmul() { - ${t} coords = getOutputCoords(); - ${r} - return getBias(coords.x); -}` - ); -} -var Ql, - ef, - im, - sm, - oo = L(() => { - fe(), - ae(), - Ft(), - gr(), - Di(), - (Ql = (t, e, o) => (sm(e), t.session.pack ? [t.run(io(t, e, o), e)] : [t.run(Pi(e, o), e)])), - (ef = (t) => Rr(t.attributes)), - (im = (t, e) => ({ - name: 'MatMul', - inputNames: t ? ['A', 'B', 'Bias'] : ['A', 'B'], - inputTypes: t ? [0, 0, 0] : [0, 0], - cacheHint: e, - })), - (sm = (t) => { - if (!t || t.length !== 2) throw new Error('MatMul requires 2 inputs.'); - if (t[0].dims[t[0].dims.length - 1] !== t[1].dims[t[1].dims.length - 2]) - throw new Error('shared dimension does not match.'); - if ( - (t[0].type !== 'float32' && t[0].type !== 'float64') || - (t[1].type !== 'float32' && t[1].type !== 'float64') - ) - throw new Error('inputs should be float type'); - if (t[0].type !== t[1].type) throw new Error('inputs types should match'); - }); - }); -function fm(t, e, o, i) { - let u = [], - n = [], - s = o[0].dims, - d = o[1].dims, - f = s.length, - r = d.length, - a = i.length, - l = a - f, - p = a - r; - (u = s.map((E, A) => `coords.${e[A + l]}`)), - (u[f - 1] = 'i*2'), - u.join(', '), - (n = d.map((E, A) => `coords.${e[A + p]}`)), - (n[r - 2] = 'i*2'), - n.join(', '); - let m = Xe.getBroadcastDims(s, i), - y = Xe.getBroadcastDims(d, i), - T = m.map((E) => `coords.${e[E + l]} = 0;`).join(` -`), - v = y.map((E) => `coords.${e[E + p]} = 0;`).join(` -`), - S = `int lastDim = coords.${e[a - 1]}; - coords.${e[a - 1]} = coords.${e[a - 2]}; - coords.${e[a - 2]} = lastDim;`; - return ` -vec4 getAAtOutCoordsMatmul(int i) { - ${t} coords = getOutputCoords(); - ${S} - ${T} - vec4 outputValue = getA(${u}); - return outputValue; -} - -vec4 getBAtOutCoordsMatmul(int i) { - ${t} coords = getOutputCoords(); - ${S} - ${v} - vec4 outputValue = getB(${n}); - return outputValue; -}`; -} -function cm(t, e) { - let o = ''; - for (let i = 0; i < e - 2; i++) o += `rc.${t[i]}, `; - return (o += `rc.${t[e - 2]}, i*2`), o; -} -function pm(t, e) { - let o = ''; - for (let i = 0; i < e - 2; i++) o += `rc.${t[i]}, `; - return (o += `i*2, rc.${t[e - 1]}`), o; -} -var um, - lm, - io, - Di = L(() => { - fe(), - xe(), - ae(), - Ft(), - gr(), - oo(), - (um = (t, e) => ({ - name: 'MatMul (packed)', - inputNames: t ? ['A', 'B', 'Bias'] : ['A', 'B'], - inputTypes: t ? [2, 2, 2] : [2, 2], - cacheHint: e, - })), - (lm = (t, e, o, i) => { - let u = o.length > 2, - n = u ? 'value += getBiasForMatmul();' : '', - s = o[0].dims, - d = o[1].dims, - f = Xe.calcShape(s, d, !0), - r = !U.areEqual(o[0].dims, o[1].dims); - if (!f) throw new Error("Can't use matmul on the given tensors"); - let a = s[s.length - 1], - l = Math.ceil(a / 2), - p = s.length, - m = d.length, - y = q(t.session.backend.glContext.version), - T = Ke(f.length), - v = f.length, - S = St(), - { activationFunction: E, applyActivation: A } = Ct(i), - F = u ? `${Ei(T, S, o[2].dims, f, !0)}` : '', - B = r ? `${fm(T, S, o, f)}` : '', - J = r ? 'getAAtOutCoordsMatmul(i)' : `getA(${cm(S, p)})`, - Q = r ? 'getBAtOutCoordsMatmul(i)' : `getB(${pm(S, m)})`, - re = r - ? '' - : `${T} rc = - getOutputCoords(); int lastDim = rc.${S[v - 1]}; rc.${S[v - 1]} = - rc.${S[v - 2]}; rc.${S[v - 2]} = lastDim; - `, - V = ` - ${B} - ${F} - ${E} - void main() { - ${re} - - vec4 value = vec4(0); - for (int i = 0; i < ${l}; i++) { - vec4 a = ${J}; - vec4 b = ${Q}; - - value += (a.rrbb * b.rgrg); - value += (a.ggaa * b.baba); - } - ${n} - ${A} - ${y.output} = value; - }`; - return { ...e, output: { dims: f, type: o[0].type, textureType: 2 }, shaderSource: V, hasMain: !0 }; - }), - (io = (t, e, o) => { - let i = um(e.length > 2, o.activationCacheKey); - return { ...i, get: () => lm(t, i, e, o) }; - }); - }), - tf, - rf = L(() => { - no(), - Zl(), - Di(), - (tf = (t, e, o) => { - let i = e[0].dims, - u = e[1].dims, - n = Mr(i, u, o.dilations, o.pads, o.strides), - s = t.run(Jl(t, e[0], e[1], n, o), [e[0]]), - d = t.reshapePacked(e[1], [u[0], u[1] * u[2] * u[3]]), - f = e.length === 3 ? [d, s, e[2]] : [d, s], - r = t.run(io(t, f, o), f); - return t.reshapePacked(r, n); - }); - }), - dm, - hm, - nf, - Li, - Fi = L(() => { - ae(), - (dm = (t) => ({ name: 'Im2Col', inputNames: ['X'], inputTypes: [0], cacheHint: t })), - (hm = (t, e, o, i, u, n) => { - let s = o.dims, - d = i.dims, - f = u.length, - r = Li(s, d, u, 4), - a = ` - const int XC = ${s[1]}; - const int XH = ${s[2]}; - const int XW = ${s[3]}; - const int KH = ${n.kernelShape[0]}; - const int KW = ${n.kernelShape[1]}; - const int dilationH = ${n.dilations[0]}; - const int dilationW = ${n.dilations[1]}; - const int strideH = ${n.strides[0]}; - const int strideW = ${n.strides[1]}; - const int padH = ${n.pads[0]}; - const int padW = ${n.pads[1]}; - const int KHKW = KH*KW; - const int XCKHKW = XC * KHKW; - const int outputChannels = 4; - vec4 process(int indices[${f}]) { - 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[${s.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 { ...e, output: { dims: r, type: o.type, textureType: 4 }, shaderSource: a }; - }), - (nf = (t, e, o, i, u) => { - let n = dm(u.cacheKey); - return { ...n, get: () => hm(t, n, e, o, i, u) }; - }), - (Li = (t, e, o, i = 4) => [o[0], o[2], o[3], Math.ceil((t[1] * e[2] * e[3]) / i)]); - }), - mm, - bm, - of, - af = L(() => { - fe(), - xe(), - ae(), - gr(), - Fi(), - (mm = (t, e) => ({ - name: 'ConvDotProduct', - inputNames: t ? ['Im2Col', 'K', 'B'] : ['Im2Col', 'K'], - inputTypes: t ? [0, 4, 0] : [0, 4], - cacheKey: e.activationCacheKey, - })), - (bm = (t, e, o, i, u) => { - let n = o[0].dims, - s = o[1].dims, - d = [s[0], Math.ceil((n[1] * s[2] * s[3]) / 4)], - f = Li(n, s, i), - [r, a] = t.calculateTextureWidthAndHeight(d, 4), - l = U.computeStrides(f), - [p, m] = t.calculateTextureWidthAndHeight(f, 4), - y = i.length, - T = o.length < 3 ? '0.0' : '_B(b)', - v = Math.ceil((n[1] * s[2] * s[3]) / 4), - { activationFunction: S, applyActivation: E } = Ct(u), - A = q(t.session.backend.glContext.version), - F = ` -${S} -float process(int indices[${y}]) { - 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] * ${l[0]} + im2col[1] * ${l[1]} + im2col[2] * ${l[2]}; - int kernelOffset = indices[1] * ${d[1]}; - float value = ${T}; - for (int i = 0; i < ${v}; ++i) { - vec2 im2colCoords = offsetToCoords(im2colOffset, ${p}, ${m}); - vec2 kernelCoords = offsetToCoords(kernelOffset, ${r}, ${a}); - value += dot(${A.texture2D}(Im2Col, im2colCoords), ${A.texture2D}(K, kernelCoords)); - ++im2colOffset; - ++kernelOffset; - } - ${E} - return value; -}`; - return { ...e, output: { dims: i, type: o[0].type, textureType: 0 }, shaderSource: F }; - }), - (of = (t, e, o, i) => { - let u = mm(e.length > 2, i); - return { ...u, get: () => bm(t, u, e, o, i) }; - }); - }), - Mr, - $i, - gm, - ym, - Tm, - xm, - Ci, - vm, - no = L(() => { - Ge(), - fe(), - Kl(), - rf(), - af(), - gr(), - Fi(), - oo(), - (Mr = (t, e, o, i, u) => { - let n = t[0], - s = t.slice(2), - d = s.length, - f = e[0], - r = e.slice(2).map((l, p) => l + (l - 1) * (o[p] - 1)), - a = s.map((l, p) => l + i[p] + i[p + d]).map((l, p) => Math.floor((l - r[p] + u[p]) / u[p])); - return [n, f].concat(...a); - }), - ($i = (t, e, o) => (vm(e, o), gm(t, e, o))), - (gm = (t, e, o) => { - let i = xm(o, e), - u = t.session.pack, - n = i.kernelShape[0] === 1 && i.kernelShape[1] === 1; - return i.group > 1 - ? [t.run(Xl(t, e, i), e)] - : n && u - ? [ym(t, e, i)] - : u && e[0].dims.length === 4 && e[0].dims[0] === 1 && !n - ? [tf(t, e, i)] - : [Tm(t, e, i)]; - }), - (ym = (t, e, o) => { - let i = e[0].dims, - u = e[1].dims, - n = Mr(i, u, o.dilations, o.pads, o.strides), - s = t.reshapeUnpacked(e[0], [i[1], i[2] * i[3]]), - d = t.reshapeUnpacked(e[1], [u[0], u[1]]), - f = e.length > 2 ? [d, s, e[2]] : [d, s], - r = t.run(Pi(f, o), f); - return t.reshapeUnpacked(r, n); - }), - (Tm = (t, e, o) => { - let i = e[0].dims, - u = e[1].dims, - n = Mr(i, u, o.dilations, o.pads, o.strides), - s = t.run(nf(t, e[0], e[1], n, o), [e[0]]), - d = e.length === 3 ? [s, e[1], e[2]] : [s, e[1]]; - return t.run(of(t, e, n, o), d); - }), - (xm = (t, e) => { - let o = t.kernelShape.slice(); - if (t.kernelShape.length === 0) for (let n = 2; n < e[1].dims.length; ++n) o.push(e[1].dims[n]); - let i = t.pads.slice(); - pr.adjustPadsBasedOnAutoPad(e[0].dims, t.strides, t.dilations, o, i, t.autoPad); - let u = Object.assign({}, t); - return Object.assign(u, { kernelShape: o, pads: i, cacheKey: t.cacheKey }), u; - }), - (Ci = (t) => { - let e = t.attributes, - o = Rr(e), - i = e.getString('auto_pad', 'NOTSET'), - u = e.getInts('dilations', [1, 1]), - n = e.getInt('group', 1), - s = e.getInts('kernel_shape', []), - d = e.getInts('pads', [0, 0, 0, 0]), - f = e.getInts('strides', [1, 1]); - return ee({ autoPad: i, dilations: u, group: n, kernelShape: s, pads: d, strides: f, ...o }); - }), - (vm = (t, e) => { - if (!t || (t.length !== 2 && t.length !== 3)) throw new Error('Conv requires 2 or 3 inputs'); - if (t[0].dims.length !== 4 || t[1].dims.length !== 4) - throw new Error('currently only support 2-dimensional conv'); - let o = t[0].dims[1], - i = t[1].dims[1] * e.group; - if (o !== i) throw new Error('FILTER_IN_CHANNEL should be equal to DATA_CHANNEL'); - if (t.length === 3 && (t[2].dims.length !== 1 || t[1].dims[0] !== t[2].dims[0])) - throw new Error('invalid bias'); - let u = t[0].dims.length - 2; - if (e.dilations.length !== u) throw new Error(`dilations should be ${u}D`); - if (e.strides.length !== u) throw new Error(`strides should be ${u}D`); - if (e.pads.length !== u * 2) throw new Error(`pads should be ${u * 2}D`); - if (e.kernelShape.length !== 0 && e.kernelShape.length !== t[1].dims.length - 2) - throw new Error('invalid kernel shape'); - if (t[0].type !== 'float32' || t[1].type !== 'float32') - throw new Error('Conv input(X,W) should be float tensor'); - if (t.length === 3 && t[2].type !== 'float32') - throw new Error('Conv input(bias) should be float tensor'); - }); - }), - wm, - _m, - Om, - sf, - Im, - Sm, - Am, - Pm, - Em, - Dm, - uf, - Lm, - lf = L(() => { - Ge(), - xe(), - ae(), - gr(), - (wm = (t, e, o, i, u, n) => (t - 1) * e + o + (i - 1) * u + 1 - n), - (_m = (t, e, o, i, u) => { - let n = Math.floor(t / 2); - e === 'SAME_UPPER' ? ((o[i] = n), (o[u] = t - n)) : e === 'SAME_LOWER' && ((o[i] = t - n), (o[u] = n)); - }), - (Om = (t, e, o, i, u, n, s, d) => { - let f = t.length - 2, - r = d.length === 0; - for (let a = 0; a < f; ++a) { - let l = r ? t[a + 2] * n[a] : d[a], - p = wm(t[a + 2], n[a], u[a], e[a], o[a], l); - _m(p, i, u, a, a + f), - r && d.push(n[a] * (t[a + 2] - 1) + s[a] + (e[a] - 1) * o[a] + 1 - u[a] - u[a + f]); - } - }), - (sf = (t, e, o) => (Lm(e, o), Im(t, e, o))), - (Im = (t, e, o) => { - let i = Dm(o, e); - return [Em(t, e, i)]; - }), - (Sm = (t, e) => ({ - name: 'ConvTranspose', - inputNames: t ? ['X', 'W', 'B'] : ['X', 'W'], - inputTypes: t ? [0, 0, 0] : [0, 0], - cacheHint: e, - })), - (Am = (t, e, o, i) => { - let u = e.length > 2 ? 'getB(output_channel)' : '0.0', - n = e[0].dims, - s = e[1].dims, - d = s[1], - f = s[0] / i.group, - r = [e[0].dims[0], e[1].dims[1] * i.group, ...i.outputShape], - a = q(t.session.backend.glContext.version), - { activationFunction: l, applyActivation: p } = Ct(i), - m = ` - const ivec2 strides = ivec2(${i.strides[0]}, ${i.strides[1]}); - const ivec2 pads = ivec2(${i.pads[0]}, ${i.pads[1]}); - ${l} - void main() { - ivec4 coords = getOutputCoords(); - int batch = coords.x; - int output_channel = coords.y; - - ivec2 loc = coords.zw + pads; - - int group_id = output_channel / ${d}; - int wOutChannel = output_channel - group_id * ${d}; - - float value = ${u}; - for (int inChannelOffset = 0; inChannelOffset < ${f}; inChannelOffset++) { - int input_channel = group_id * ${f} + inChannelOffset; - for (int wWOff = 0; wWOff < ${s[2]}; wWOff++) { - for (int wHOff = 0; wHOff < ${s[3]}; wHOff++) { - ivec2 wOff = ivec2(wWOff * ${i.dilations[0]}, wHOff * ${i.dilations[1]}); - ivec2 wLoc = loc - wOff; - ivec2 wLocIn = wLoc / strides; - if ( - wLocIn * strides == wLoc && - wLocIn.x >= 0 && wLocIn.x < ${n[2]} && - wLocIn.y >= 0 && wLocIn.y < ${n[3]} - ) { - float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); - float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); - value += xVal * wVal; - } - } - } - } - ${p} - ${a.output} = vec4(value, .0, .0, .0); - } -`; - return { ...o, output: { dims: r, type: e[0].type, textureType: 0 }, shaderSource: m, hasMain: !0 }; - }), - (Pm = (t, e, o) => { - let i = Sm(e.length > 2, o.cacheKey); - return { ...i, get: () => Am(t, e, i, o) }; - }), - (Em = (t, e, o) => t.run(Pm(t, e, o), e)), - (Dm = (t, e) => { - let o = t.kernelShape.slice(); - if (t.kernelShape.length === 0) for (let d = 2; d < e[1].dims.length; ++d) o.push(e[1].dims[d]); - let i = t.pads.slice(), - u = t.outputShape.slice(), - n = e[0].dims; - Om(n, o, t.dilations, t.autoPad, i, t.strides, t.outputPadding, u); - let s = Object.assign({}, t); - return Object.assign(s, { kernelShape: o, pads: i, outputShape: u, cacheKey: t.cacheKey }), s; - }), - (uf = (t) => { - let e = t.attributes, - o = Rr(e), - i = e.getString('auto_pad', 'NOTSET'), - u = e.getInts('dilations', [1, 1]), - n = e.getInt('group', 1), - s = e.getInts('kernel_shape', []), - d = e.getInts('output_padding', [0, 0]), - f = e.getInts('output_shape', []), - r = e.getInts('pads', [0, 0, 0, 0]), - a = e.getInts('strides', [1, 1]); - return ee({ - autoPad: i, - dilations: u, - group: n, - kernelShape: s, - outputPadding: d, - outputShape: f, - pads: r, - strides: a, - ...o, - }); - }), - (Lm = (t, e) => { - if (!t || (t.length !== 2 && t.length !== 3)) throw new Error('Conv requires 2 or 3 inputs'); - if (t[0].dims.length !== 4 || t[1].dims.length !== 4) - throw new Error('currently only support 2-dimensional conv'); - let o = t[0].dims[1], - i = t[1].dims[0]; - if (o !== i) throw new Error('FILTER_IN_CHANNEL should be equal to DATA_CHANNEL'); - let u = t[1].dims[1] * e.group; - if (t.length === 3 && (t[2].dims.length !== 1 || t[2].dims[0] !== u)) throw new Error('invalid bias'); - let n = t[0].dims.length - 2; - if (e.dilations.length !== n) throw new Error(`dilations should be ${n}D`); - if (e.strides.length !== n) throw new Error(`strides should be ${n}D`); - if (e.pads.length !== n * 2) throw new Error(`pads should be ${n * 2}D`); - if (e.outputPadding.length !== n) throw new Error(`output_padding should be ${n}D`); - if (e.kernelShape.length !== 0 && e.kernelShape.length !== t[1].dims.length - 2) - throw new Error('invalid kernel shape'); - if (e.outputShape.length !== 0 && e.outputShape.length !== t[0].dims.length - 2) - throw new Error('invalid output shape'); - if (t[0].type !== 'float32' || t[1].type !== 'float32') - throw new Error('ConvTranspose input(X,W) should be float tensor'); - if (t.length === 3 && t[2].type !== 'float32') - throw new Error('ConvTranspose input(bias) should be float tensor'); - }); - }), - ff, - yr, - cf, - Fm, - pf, - $m, - Cm, - km, - ao = L(() => { - Ge(), - fe(), - ae(), - (ff = { name: 'Transpose', inputNames: ['A'], inputTypes: [0] }), - (yr = (t, e, o) => (km(e), [t.run({ ...ff, cacheHint: o.cacheKey, get: () => Fm(t, e[0], o.perm) }, e)])), - (cf = (t) => ee({ perm: t.attributes.getInts('perm', []) })), - (Fm = (t, e, o) => { - let i = e.dims; - o = pf(i, o); - let u = $m(i, o), - n = i.length, - s = ` - ${Cm('perm', o, n)} - float process(int indices[${n}]) { - int a[${n}]; - perm(a, indices); - return _A(a); - }`; - return { ...ff, output: { dims: u, type: e.type, textureType: 0 }, shaderSource: s }; - }), - (pf = (t, e) => (e && e.length !== t.length && (e = [...t.keys()].reverse()), e)), - ($m = (t, e) => ((e = pf(t, e)), U.sortBasedOnPerm(t, e))), - (Cm = (t, e, o) => { - let i = []; - i.push(`void ${t}(out int a[${o}], int src[${o}]) {`); - for (let u = 0; u < o; ++u) i.push(` a[${e[u]}]=src[${u}];`); - return ( - i.push(' }'), - i.join(` -`) - ); - }), - (km = (t) => { - if (!t || t.length !== 1) throw new Error('Transpose requires 1 input.'); - if (t[0].type !== 'float32' && t[0].type !== 'float64') throw new Error('input should be float tensor'); - }); - }), - df, - hf, - Bm, - mf = L(() => { - ao(), - (df = (t, e, o) => { - Bm(e); - let i = o.blocksize, - u = i * i, - n = o.mode === 'DCR' ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3], - s = - o.mode === 'DCR' - ? [e[0].dims[0], i, i, e[0].dims[1] / u, e[0].dims[2], e[0].dims[3]] - : [e[0].dims[0], e[0].dims[1] / u, i, i, e[0].dims[2], e[0].dims[3]], - d = t.reshapeUnpacked(e[0], s), - f = { perm: n, cacheKey: `${n}` }, - [r] = yr(t, [d], f), - a = [e[0].dims[0], e[0].dims[1] / u, e[0].dims[2] * i, e[0].dims[3] * i]; - return [t.reshapeUnpacked(r, a)]; - }), - (hf = (t) => { - let e = t.attributes.getInt('blocksize'); - if (e < 1) throw new Error(`blocksize must be >= 1, but got : ${e} for DepthToSpace`); - let o = t.attributes.getString('mode', 'DCR'); - if (o !== 'DCR' && o !== 'CRD') throw new Error(`unrecognized mode: ${o} for DepthToSpace`); - return { mode: o, blocksize: e }; - }), - (Bm = (t) => { - if (t.length !== 1) throw new Error(`DepthToSpace expect 1 inputs, but got ${t.length}`); - if (t[0].type === 'string' || t[0].dims.length !== 4) - throw new TypeError('DepthToSpace input should be a 4-D numeric tensor'); - }); - }), - bf, - gf, - Nm, - yf = L(() => { - fe(), - (bf = (t, e, o) => { - Nm(e, o); - let i = U.flattenShape(e[0].dims, o); - return [t.reshapeUnpacked(e[0], i)]; - }), - (gf = (t) => t.attributes.getInt('axis', 1)), - (Nm = (t, e) => { - if (!t || t.length !== 1) throw new Error('Flatten requires 1 input.'); - let o = t[0].dims.length; - if (o === 0) throw new Error('scalar tensor is not supported.'); - if (e < -o || e > o) throw new Error('Invalid axis'); - if (t[0].type === 'string') throw new Error('string tensor is not supported.'); - }); - }), - Jt, - pn = L(() => { - Jt = ['float32', 'float64', 'int32', 'int16', 'int8', 'uint16', 'uint32', 'uint8']; - }), - Tf, - xf, - Rm, - Mm, - Gm, - Um, - vf = L(() => { - Ge(), - pn(), - fe(), - ae(), - (Tf = (t, e, o) => (Um(e, o.axis), [t.run(Gm(t, e, o), e)])), - (xf = (t) => ee({ axis: t.attributes.getInt('axis', 0) })), - (Rm = { name: 'Gather', inputNames: ['A', 'B'], inputTypes: [0, 0] }), - (Mm = (t, e, o, i) => { - let u = o[0].dims.slice(), - n = o[1].dims.slice(), - s = new Array(u.length + n.length - 1); - i = U.normalizeAxis(i, u.length); - let d = []; - for (let p = 0; p < s.length; p++) - p < i - ? ((s[p] = u[p]), d.push(`inputIdx[${p}] = outputIdx[${p}];`)) - : p < i + n.length - ? ((s[p] = n[p - i]), d.push(`indexDataIdx[${p - i}] = outputIdx[${p}];`)) - : ((s[p] = u[p - n.length + 1]), d.push(`inputIdx[${p - n.length + 1}] = outputIdx[${p}];`)); - let f = s.length || 1, - r = u.length, - a = n.length || 1, - l = ` - float process(int outputIdx[${f}]) { - int inputIdx[${r}]; - int indexDataIdx[${a}]; - indexDataIdx[0] = 0; - ${d.join(` - `)} - int idx = int(_B(indexDataIdx)); - inputIdx[${i}] = idx < 0 ? idx + ${u[i]} : idx; - return _A(inputIdx); - }`; - return { ...e, output: { dims: s, type: o[0].type, textureType: 0 }, shaderSource: l }; - }), - (Gm = (t, e, o) => { - let i = { ...Rm, cacheHint: o.cacheKey }; - return { ...i, get: () => Mm(t, i, e, o.axis) }; - }), - (Um = (t, e) => { - if (!t || t.length !== 2) throw new Error('Gather requires 2 inputs.'); - let o = t[0].dims.length; - if (o < 1) throw new Error('Invalid input shape.'); - if (e < -o || e > o - 1) throw new Error('Invalid axis.'); - if (Jt.indexOf(t[0].type) === -1) throw new Error('Invaid input type.'); - if (t[1].type !== 'int32' && t[1].type !== 'int16') throw new Error('Invaid input type.'); - }); - }), - ki, - wf, - _f, - Of, - zm, - Vm, - Wm, - If = L(() => { - Ge(), - fe(), - ae(), - (ki = (t, e, o) => (Wm(e, o), [t.run(zm(e, o), e)])), - (wf = (t, e) => { - let o = t.attributes.getInt('transA', 0) !== 0, - i = t.attributes.getInt('transB', 0) !== 0, - u = t.attributes.getFloat('alpha', 1), - n = t.attributes.getFloat('beta', 1); - return ee({ transA: o, transB: i, alpha: u, beta: n, isOptionalC: e }); - }), - (_f = (t) => wf(t, !1)), - (Of = (t) => wf(t, !0)), - (zm = (t, e) => { - let o = { - name: 'Gemm', - inputNames: t.length === 3 ? ['A', 'B', 'C'] : ['A', 'B'], - inputTypes: t.length === 3 ? [0, 0, 0] : [0, 0], - key: e.cacheKey, - }; - return { ...o, get: () => Vm(o, t, e) }; - }), - (Vm = (t, e, o) => { - let i = e[0].dims.slice(), - u = e[1].dims.slice(), - [n, s] = Xn.getShapeOfGemmResult(i, o.transA, u, o.transB, e.length === 3 ? e[2].dims : void 0), - d = [n, s]; - if (!d) throw new Error("Can't use gemm on the given tensors"); - let f = i[i.length - 1], - r = ''; - o.transA && (f = i[0]), - o.transA && o.transB - ? (r = 'value += _A_T(a) * _B_T(b);') - : o.transA && !o.transB - ? (r = 'value += _A_T(a) * _B(b);') - : !o.transA && o.transB - ? (r = 'value += _A(a) * _B_T(b);') - : !o.transA && !o.transB && (r = 'value += _A(a) * _B(b);'); - let a = d.length, - l = e.length === 3 ? `int c[${e[2].dims.length}];` : '', - p = e.length === 3 ? 'bcastIndices_C(indices, c);' : '', - m = e.length === 3 ? 'value += beta * _C(c);' : '', - y = ` - float process(int indices[${a}]) { - int a[${a}]; - int b[${a}]; - ${l} - - copyVec(indices, a); - copyVec(indices, b); - ${p} - - float value = 0.0; - for (int k=0; k<${f}; ++k) { - a[${a - 1}] = k; - b[${a - 2}] = k; - ${r} - } - - value = value * alpha; - ${m} - return value; - }`; - return { - ...t, - output: { dims: d, type: e[0].type, textureType: 0 }, - variables: [ - { name: 'alpha', type: 'float', data: o.alpha }, - { name: 'beta', type: 'float', data: o.beta }, - ], - shaderSource: y, - }; - }), - (Wm = (t, e) => { - if (!t) throw new Error('Input is missing'); - if (e.isOptionalC && (t.length < 2 || t.length > 3)) throw new Error('Invaid input shape.'); - if (!e.isOptionalC && t.length !== 3) throw new Error('Gemm requires 3 inputs'); - if (t.length === 3 && t[2].dims.length !== 1 && t[2].dims.length !== 2) - throw new Error('Invalid input shape of C'); - if ( - (t[0].type !== 'float32' && t[0].type !== 'float64') || - (t[1].type !== 'float32' && t[1].type !== 'float64') || - (t.length === 3 && t[2].type !== 'float32' && t[2].type !== 'float64') - ) - throw new Error('Invalid input type.'); - if (t[0].type !== t[1].type || (t.length === 3 && t[0].type !== t[2].type)) - throw new Error('Input types are mismatched'); - }); - }), - Sf, - Af, - Hm, - qm, - jm, - Ym, - Xm, - Pf = L(() => { - Ge(), - ae(), - (Sf = (t, e, o) => (Xm(e), [t.run(jm(t, e, o), e)])), - (Af = (t) => { - let e = t.attributes.getFloat('scale'), - o = t.attributes.getFloats('bias'); - return ee({ scale: e, bias: o }); - }), - (Hm = { name: 'ImageScaler', inputNames: ['X'], inputTypes: [0] }), - (qm = (t, e, o, i) => { - let u = o[0].dims.slice(), - n = u.length, - s = ` - ${Ym(i.bias.length)} - float process(int indices[${n}]) { - return _X(indices) * scale + getBias(bias, indices[1]); - }`; - return { - ...e, - output: { dims: u, type: o[0].type, textureType: 0 }, - variables: [ - { name: 'bias', type: 'float', arrayLength: i.bias.length, data: i.bias }, - { name: 'scale', type: 'float', data: i.scale }, - ], - shaderSource: s, - }; - }), - (jm = (t, e, o) => { - let i = { ...Hm, cacheHint: o.cacheKey }; - return { ...i, get: () => qm(t, i, e, o) }; - }), - (Ym = (t) => { - let e = [`float getBias(float bias[${t}], int channel) {`]; - for (let o = 0; o < t; ++o) - o === 0 - ? e.push(` if (channel == ${o}) { return bias[${o}]; }`) - : o === t - 1 - ? e.push(` else { return bias[${o}]; }`) - : e.push(` else if (channel == ${o}) { return bias[${o}]; }`); - return ( - e.push(' }'), - e.join(` -`) - ); - }), - (Xm = (t) => { - if (!t || t.length !== 1) throw new Error('ImageScaler requires 1 input.'); - if (t[0].dims.length !== 4) throw new Error('Invalid input shape.'); - if (t[0].type !== 'float32' && t[0].type !== 'float64') throw new Error('Invalid input type.'); - }); - }), - Df, - Lf, - Ef, - Km, - Jm, - Zm, - Qm, - eb, - tb, - Ff = L(() => { - xe(), - ae(), - (Df = (t, e, o) => { - tb(e); - let i = t.run(Jm(e[0]), e); - return [t.run(eb(t, e[0], o, i.dims), [e[0], i, e[1], e[2]])]; - }), - (Lf = (t) => t.attributes.getFloat('epsilon', 1e-5)), - (Ef = { name: 'InstanceNormalization_MeanAndVariance', inputNames: ['X'], inputTypes: [0] }), - (Km = (t, e) => { - let o = e.dims.slice(), - i = o[1], - u = o[2] * o[3], - n = [o[0], i], - s = ` - 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<${o[2]}; a2++) { - a[2] = a2; - for(int a3=0; a3<${o[3]}; a3++) { - a[3] = a3; - float x = _X(a); - temp += x; - } - } - float mean = temp / float(${u}); - temp = 0.0; - for(int a2=0; a2<${o[2]}; a2++) { - a[2] = a2; - for(int a3=0; a3<${o[3]}; a3++) { - a[3] = a3; - float x = _X(a); - temp += (x - mean) * (x - mean); - } - } - v.r = mean; - v.g = temp / float(${u}); - - return v; - }`; - return { ...t, output: { dims: n, type: e.type, textureType: 4 }, shaderSource: s }; - }), - (Jm = (t) => ({ ...Ef, get: () => Km(Ef, t) })), - (Zm = { - name: 'InstanceNormalization_ComputeOutput', - inputNames: ['X', 'MeanAndVariance', 'Scale', 'B'], - inputTypes: [0, 4, 0, 0], - }), - (Qm = (t, e, o, i, u) => { - let n = q(t.session.backend.glContext.version), - [s, d] = t.calculateTextureWidthAndHeight(u, 4), - [f, r] = [s / 4, d], - a = ` - vec4 get_MeanAndVariance(int[2] mv) { - int offset = indicesToOffset_MeanAndVariance(mv); - vec2 coords = offsetToCoords(offset, ${f}, ${r}); - return ${n.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 { - ...e, - output: { dims: o.dims, type: o.type, textureType: 0 }, - variables: [{ name: 'epsilon', type: 'float', data: i }], - shaderSource: a, - }; - }), - (eb = (t, e, o, i) => { - let u = { ...Zm, cacheHint: `${o}` }; - return { ...u, get: () => Qm(t, u, e, o, i) }; - }), - (tb = (t) => { - if (!t || t.length !== 3) throw new Error('InstanceNormalization requires 3 inputs.'); - let e = t[0], - o = t[1], - i = t[2]; - if (e.dims.length < 3 || o.dims.length !== 1 || i.dims.length !== 1) - throw new Error('Invalid input shape.'); - if (o.dims[0] !== e.dims[1] || i.dims[0] !== e.dims[1]) throw new Error('Input shapes are mismatched.'); - if ( - (e.type !== 'float32' && e.type !== 'float64') || - (o.type !== 'float32' && o.type !== 'float64') || - (i.type !== 'float32' && i.type !== 'float64') - ) - throw new Error('Invalid input type.'); - if (t[0].dims.length !== 4) throw new Error('Only support 4-D input shape.'); - }); - }); -function rb(t, e) { - let o = t[0].dims[1], - i = t[0].dims.length, - u = -Math.floor((e.size - 1) / 2), - n = Math.ceil((e.size - 1) / 2), - s = `float(${e.alpha}) / float(${e.size})`, - d = `float(${e.bias})`, - f = `float(${e.beta})`, - r = ` - float process(int indices[${i}]) { - int c = indices[1]; - float x = _X(indices); - float square_sum = 0.0; - - for (int i = ${u}; i <= ${n}; i++) { - int idx = c + i; - if (c >= 0 && c < ${o}) { - indices[1] = idx; - float j = _X(indices); - square_sum += j * j; - } - } - return x / pow(${d} + ${s} * square_sum, ${f}); - }`; - return { - ...kf, - cacheHint: e.cacheKey, - output: { dims: t[0].dims, type: t[0].type, textureType: 0 }, - shaderSource: r, - }; -} -function nb(t, e) { - return { ...kf, cacheHint: e.cacheKey, get: () => rb(t, e) }; -} -var $f, - Cf, - kf, - ob, - Bf = L(() => { - Ge(), - ae(), - ($f = (t, e, o) => (ob(e), [t.run(nb(e, o), e)])), - (Cf = (t) => { - let e = t.attributes.getFloat('alpha', 1e-4), - o = t.attributes.getFloat('beta', 0.75), - i = t.attributes.getFloat('bias', 1), - u = t.attributes.getInt('size'); - return ee({ alpha: e, beta: o, bias: i, size: u }); - }), - (kf = { name: 'LRN', inputNames: ['X'], inputTypes: [0] }), - (ob = (t) => { - if (!t || t.length !== 1) throw new Error('LRN requires 1 input.'); - if (t[0].dims.length !== 4) throw new Error('currently only support LRN for input with "NCHW" format'); - if (t[0].type !== 'float32') throw new Error('input should be float type'); - }); - }), - ib, - Bi, - Nf, - Rf, - Mf, - ab, - sb, - ub, - lb, - fb, - cb, - pb, - db, - Gf = L(() => { - Ge(), - fe(), - xe(), - ae(), - (ib = { name: 'Pad', inputNames: ['A'], inputTypes: [0] }), - (Bi = (t, e, o) => (ub(e), [t.run({ ...ib, cacheHint: o.cacheKey, get: () => sb(t, e[0], o) }, e)])), - (Nf = (t) => { - let e = t.attributes.getString('mode', 'constant'), - o = t.attributes.getFloat('value', 0), - i = t.attributes.getInts('pads'); - return ee({ mode: e, value: o, pads: i }); - }), - (Rf = (t, e, o) => { - lb(e); - let i = ab(t, e, o); - return Bi(t, [e[0]], i); - }), - (Mf = (t) => t.attributes.getString('mode', 'constant')), - (ab = (t, e, o) => { - if (!t.session.isInitializer(e[1].dataId) || (e.length >= 3 && !t.session.isInitializer(e[2].dataId))) - throw new Error('dynamic pad attributes are not allowed'); - let i = Array.from(e[1].integerData), - u = e.length >= 3 ? e[2].floatData[0] : 0; - return ee({ mode: o, pads: i, value: u }); - }), - (sb = (t, e, o) => { - let i = U.padShape(e.dims.slice(), o.pads), - u = i.length, - n = ` - ${fb(t, e, o)} - float process(int[${u}] indices) { - return padA(indices); - }`; - return { - name: 'Pad', - inputNames: ['A'], - inputTypes: [0], - output: { dims: i, type: e.type, textureType: 0 }, - shaderSource: n, - }; - }), - (ub = (t) => { - if (!t || t.length !== 1) throw new Error('Pad requires 1 input'); - if (t[0].type !== 'float32' && t[0].type !== 'float64') throw new Error('Invalid input type.'); - }), - (lb = (t) => { - if (!t || (t.length !== 2 && t.length !== 3)) throw new Error('Pad requires 2 or 3 inputs'); - if (t[1].type !== 'int32') throw new Error('Invalid input type.'); - if (t.length >= 3 && t[2].type === 'string') throw new Error('Invalid input type.'); - }), - (fb = (t, e, o) => { - let i = q(t.session.backend.glContext.version), - [u, n] = t.calculateTextureWidthAndHeight(e.dims, 0), - s = U.computeStrides(e.dims); - switch (o.mode) { - case 'constant': - return cb(i, e.dims, s, u, n, o.pads, o.value); - case 'reflect': - return pb(i, e.dims, s, u, n, o.pads); - case 'edge': - return db(i, e.dims, s, u, n, o.pads); - default: - throw new Error('Invalid mode'); - } - }), - (cb = (t, e, o, i, u, n, s) => { - let d = e.length, - f = ''; - for (let r = d - 1; r >= 0; --r) - f += ` - k = m[${r}] - ${n[r]}; - if (k < 0) return constant; - if (k >= ${e[r]}) return constant; - offset += k * ${o[r]}; - `; - return ` - float padA(int m[${d}]) { - const float constant = float(${s}); - int offset = 0; - int k = 0; - ${f} - vec2 coords = offsetToCoords(offset, ${i}, ${u}); - float value = getColorAsFloat(${t.texture2D}(A, coords)); - return value; - } - `; - }), - (pb = (t, e, o, i, u, n) => { - let s = e.length, - d = ''; - for (let f = s - 1; f >= 0; --f) - d += ` - k = m[${f}] - ${n[f]}; - if (k < 0) { k = -k; } - { - const int _2n_1 = ${2 * (e[f] - 1)}; - k = int( mod( float(k), float(_2n_1) ) ) ; - if(k >= ${e[f]}) { k = _2n_1 - k; } - } - offset += k * ${o[f]}; - `; - return ` - float padA(int m[${s}]) { - int offset = 0; - int k = 0; - ${d} - vec2 coords = offsetToCoords(offset, ${i}, ${u}); - float value = getColorAsFloat(${t.texture2D}(A, coords)); - return value; - } - `; - }), - (db = (t, e, o, i, u, n) => { - let s = e.length, - d = ''; - for (let f = s - 1; f >= 0; --f) - d += ` - k = m[${f}] - ${n[f]}; - if (k < 0) k = 0; - if (k >= ${e[f]}) k = ${e[f] - 1}; - offset += k * ${o[f]}; - `; - return ` - float padA(int m[${s}]) { - int offset = 0; - int k = 0; - ${d} - vec2 coords = offsetToCoords(offset, ${i}, ${u}); - float value = getColorAsFloat(${t.texture2D}(A, coords)); - return value; - } - `; - }); - }), - zf, - Vf, - Wf, - Hf, - qf, - jf, - Yf, - Xf, - Kf, - hb, - Uf, - Jf, - uo, - Zf, - so, - mb, - Qf = L(() => { - Ge(), - fe(), - ae(), - (zf = (t, e, o) => { - uo(e); - let i = { name: 'AveragePool', inputNames: ['X'], inputTypes: [0], cacheHint: o.cacheKey }; - return [t.run({ ...i, get: () => Wf(e, i, !1, o) }, e)]; - }), - (Vf = (t) => { - let e = t.attributes.getString('auto_pad', 'NOTSET'), - o = t.attributes.getInt('ceil_mode', 0), - i = t.attributes.getInt('count_include_pad', 0) !== 0, - u = t.attributes.getInts('kernel_shape'), - n = t.attributes.getInts('strides', []), - s = t.attributes.getInts('pads', []); - if (o !== 0) throw new Error('using ceil() in shape computation is not yet supported for AveragePool'); - return ee({ autoPad: e, ceilMode: o, countIncludePad: i, kernelShape: u, strides: n, pads: s }); - }), - (Wf = (t, e, o, i) => { - let [u, n] = Kf(t, i, o), - s = U.size(u.kernelShape), - d = 'value += _X(x);', - f = ''; - u.countIncludePad ? (f += `value /= float(${s});`) : (f += `value /= float(${s} - pad);`); - let r = ` - ${Zf(t[0].dims, u, d, f, '0.0')} - `; - return { ...e, output: { dims: n, type: t[0].type, textureType: 0 }, shaderSource: r }; - }), - (Hf = (t, e, o) => { - uo(e); - let i = { - name: 'GlobalAveragePool', - inputNames: ['X'], - inputTypes: [0], - cacheHint: `${o.countIncludePad}`, - }; - return [t.run({ ...i, get: () => Wf(e, i, !0, o) }, e)]; - }), - (qf = (t) => { - let e = t.attributes.getInt('count_include_pad', 0) !== 0; - return ee({ autoPad: '', ceilMode: 0, countIncludePad: e, kernelShape: [], strides: [], pads: [] }); - }), - (jf = (t, e, o) => { - uo(e); - let i = { name: 'MaxPool', inputNames: ['X'], inputTypes: [0], cacheHint: o.cacheKey }; - return [t.run({ ...i, get: () => Xf(e, i, !1, o) }, e)]; - }), - (Yf = (t) => { - let e = t.attributes.getString('auto_pad', 'NOTSET'), - o = t.attributes.getInt('ceil_mode', 0), - i = t.attributes.getInts('kernel_shape'), - u = t.attributes.getInts('strides', []), - n = t.attributes.getInts('pads', []), - s = t.attributes.getInt('storage_order', 0), - d = t.attributes.getInts('dilations', []); - if (s !== 0) throw new Error('column major storage order is not yet supported for MaxPool'); - if (o !== 0) throw new Error('using ceil() in shape computation is not yet supported for MaxPool'); - return ee({ - autoPad: e, - ceilMode: o, - countIncludePad: !1, - kernelShape: i, - strides: u, - pads: n, - storageOrder: s, - dilations: d, - }); - }), - (Xf = (t, e, o, i) => { - let [u, n] = Kf(t, i, o), - s = ` - value = max(_X(x), value); - `, - d = '', - f = ` - ${Zf(t[0].dims, u, s, d, '-1e5')} - `; - return { ...e, output: { dims: n, type: t[0].type, textureType: 0 }, shaderSource: f }; - }), - (Kf = (t, e, o) => { - let i = t[0].dims.slice(), - u = Object.hasOwnProperty.call(e, 'dilations'), - n = e.kernelShape.slice(), - s = e.strides.slice(), - d = u ? e.dilations.slice() : [], - f = e.pads.slice(); - pr.adjustPoolAttributes(o, i, n, s, d, f); - let r = pr.computePoolOutputShape(o, i, s, d, n, f, e.autoPad), - a = Object.assign({}, e); - return ( - u - ? Object.assign(a, { kernelShape: n, strides: s, pads: f, dilations: d, cacheKey: e.cacheKey }) - : Object.assign(a, { kernelShape: n, strides: s, pads: f, cacheKey: e.cacheKey }), - [a, r] - ); - }), - (hb = { - autoPad: '', - ceilMode: 0, - countIncludePad: !1, - kernelShape: [], - strides: [], - pads: [], - storageOrder: 0, - dilations: [], - cacheKey: '', - }), - (Uf = { name: 'GlobalMaxPool', inputNames: ['X'], inputTypes: [0] }), - (Jf = (t, e) => (uo(e), [t.run({ ...Uf, get: () => Xf(e, Uf, !0, hb) }, e)])), - (uo = (t) => { - if (!t || t.length !== 1) throw new Error('Pool ops requires 1 input.'); - if (t[0].type !== 'float32' && t[0].type !== 'float64') throw new Error('Invalid input type.'); - }), - (Zf = (t, e, o, i, u) => { - let n = t.length; - if (e.kernelShape.length <= 2) { - let s = e.kernelShape[e.kernelShape.length - 1], - d = e.strides[e.strides.length - 1], - f = e.pads[e.pads.length / 2 - 1], - r = e.pads[e.pads.length - 1], - a = t[n - 1], - l = '', - p = '', - m = ''; - if ( - (f + r !== 0 - ? (l = ` - for (int i = 0; i < ${s}; i++) { - x[${n} - 1] = indices[${n} - 1] * ${d} - ${f} + i; - if (x[${n} - 1] < 0 || x[${n} - 1] >= ${a}) { - pad++; - continue; - } - ${o} - }`) - : (l = ` - for (int i = 0; i < ${s}; i++) { - x[${n} - 1] = indices[${n} - 1] * ${d} - ${f} + i; - ${o} - }`), - e.kernelShape.length === 2) - ) { - let y = e.kernelShape[e.kernelShape.length - 2], - T = e.strides[e.strides.length - 2], - v = e.pads[e.pads.length / 2 - 2], - S = e.pads[e.pads.length - 2], - E = t[n - 2]; - v + S !== 0 - ? (p = ` - for (int j = 0; j < ${y}; j++) { - x[${n} - 2] = indices[${n} - 2] * ${T} - ${v} + j; - if (x[${n} - 2] < 0 || x[${n} - 2] >= ${E}) { - pad+= ${s}; - continue; - } - `) - : (p = ` - for (int j = 0; j < ${y}; j++) { - x[${n} - 2] = indices[${n} - 2] * ${T} - ${v} + j; - `), - (m = ` - } - `); - } - return ` - float process(int indices[${n}]) { - int x[${n}]; - copyVec(indices, x); - - float value = ${u}; - int pad = 0; - ${p} - ${l} - ${m} - ${i} - return value; - } - `; - } else { - let s = U.size(e.kernelShape), - d = U.computeStrides(e.kernelShape), - f = d.length, - r = e.pads.length, - a = mb(f), - l = so(t, 'inputDims'), - p = so(e.pads, 'pads'), - m = so(d, 'kernelStrides'), - y = so(e.strides, 'strides'), - T = e.pads.reduce((S, E) => S + E), - v = ''; - return ( - T - ? (v = ` - if (x[j] >= inputDims[j] || x[j] < 0) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - ${o} - }`) - : (v = ` - } - ${o} - `), - ` - ${a} - float process(int indices[${n}]) { - int x[${n}]; - copyVec(indices, x); - int offset[${f}]; - int pads[${r}]; - int inputDims[${n}]; - int kernelStrides[${f}]; - int strides[${f}]; - ${p} - ${l} - ${y} - ${m} - - float value = ${u}; - int pad = 0; - bool isPad = false; - for (int i = 0; i < ${s}; i++) { - offsetToIndices(i, kernelStrides, offset); - isPad = false; - for (int j = ${n} - ${f}; j < ${n}; j++) { - x[j] = indices[j] * strides[j - ${n} + ${f}] - + offset[j - ${n} + ${f}] - pads[j - 2]; - ${v} - } - ${i} - - return value; - } - ` - ); - } - }), - (so = (t, e) => { - let o = ''; - for (let i = 0; i < t.length; i++) - o += ` - ${e}[${i}] = ${t[i]}; - `; - return o; - }), - (mb = (t) => ` - void offsetToIndices(int offset, int[${t}] strides, out int[${t}] indices) { - if (${t} == 0) { - return; - } - for (int i = 0; i < ${t} - 1; ++i) { - indices[i] = offset / strides[i]; - offset -= indices[i] * strides[i]; - } - indices[${t} - 1] = offset; - }`); - }), - Tr, - Zt, - bb, - gb, - ec, - tc, - rc, - nc, - oc, - ic, - ac, - sc = L(() => { - Ge(), - pn(), - fe(), - ae(), - (Tr = (t, e, o, i, u) => { - gb(e); - let n = { name: i, inputNames: ['A'], inputTypes: [0] }; - return [t.run({ ...n, cacheHint: o.cacheKey, get: () => bb(t, e, o, i, u, n) }, e)]; - }), - (Zt = (t) => { - let e = t.attributes.getInts('axes', []), - o = t.attributes.getInt('keepdims', 1) === 1; - return ee({ axes: e, keepDims: o }); - }), - (bb = (t, e, o, i, u, n) => { - let s = [], - d = e[0].dims.length || 1, - f = [], - r = U.normalizeAxes(o.axes, e[0].dims.length), - a = u(e, r), - l = a[1]; - for (let m = 0; m < e[0].dims.length; m++) - r.indexOf(m) >= 0 || r.length === 0 - ? (o.keepDims && s.push(1), - (l = ` - for(int j${m} = 0; j${m} < ${e[0].dims[m]}; j${m}++) { - inputIdx[${m}] = j${m}; - ${l} - }`)) - : (f.push(`inputIdx[${m}] = outputIdx[${s.length}];`), s.push(e[0].dims[m])); - let p = ` - float process(int outputIdx[${s.length || 1}]) { - float value; // final result - int inputIdx[${d}]; // addressing input data - ${f.join(` -`)} - ${a[0]} // init ops for reduce max/min - ${l} - ${a[2]} // final computation for reduce mean - return value; - }`; - return { ...n, output: { dims: s, type: e[0].type, textureType: 0 }, shaderSource: p }; - }), - (gb = (t) => { - if (!t || t.length !== 1) throw new Error('Reduce op requires 1 input.'); - if (Jt.indexOf(t[0].type) === -1) throw new Error('Invalid input type.'); - }), - (ec = (t, e, o) => Tr(t, e, o, 'ReduceSum', () => ['value = 0.0;', 'value += _A(inputIdx);', ''])), - (tc = (t, e, o) => - Tr(t, e, o, 'ReduceMean', (i, u) => { - let n = 1; - for (let s = 0; s < i[0].dims.length; s++) - (u.indexOf(s) >= 0 || u.length === 0) && (n *= i[0].dims[s]); - return ['value = 0.0;', 'value += _A(inputIdx);', `value /= ${n}.;`]; - })), - (rc = (t, e, o) => - Tr(t, e, o, 'ReduceMax', (i, u) => { - let n = []; - for (let s = 0; s < i[0].dims.length; s++) - (u.indexOf(s) >= 0 || u.length === 0) && n.push(`inputIdx[${s}] = 0;`); - return [ - `${n.join(` -`)} -value = _A(inputIdx);`, - 'value = max(value, _A(inputIdx));', - '', - ]; - })), - (nc = (t, e, o) => - Tr(t, e, o, 'ReduceMin', (i, u) => { - let n = []; - for (let s = 0; s < i[0].dims.length; s++) - (u.indexOf(s) >= 0 || u.length === 0) && n.push(`inputIdx[${s}] = 0;`); - return [ - `${n.join(` -`)} -value = _A(inputIdx);`, - 'value = min(value, _A(inputIdx));', - '', - ]; - })), - (oc = (t, e, o) => Tr(t, e, o, 'ReduceProd', () => ['value = 1.0;', 'value *= _A(inputIdx);', ''])), - (ic = (t, e, o) => - Tr(t, e, o, 'ReduceLogSum', () => ['value = 0.0;', 'value += _A(inputIdx);', 'value = log(value);'])), - (ac = (t, e, o) => - Tr(t, e, o, 'ReduceLogSumSquare', () => [ - 'float t; value = 0.0;', - 't = _A(inputIdx); value += t * t;', - '', - ])); - }), - uc, - lc = L(() => { - fe(), - (uc = (t, e) => { - let o = U.calculateReshapedDims(e[0].dims, e[1].integerData); - return t.session.pack ? [t.reshapePacked(e[0], o)] : [t.reshapeUnpacked(e[0], o)]; - }); - }), - fc, - Ni, - cc, - pc, - dn, - yb, - Ri, - lo, - Mi = L(() => { - Ge(), - xe(), - ae(), - (fc = { name: 'Upsample', inputNames: ['X'], inputTypes: [0] }), - (Ni = (t, e, o) => (Ri(e, o), [t.run({ ...fc, cacheHint: o.cacheKey, get: () => yb(t, e, o) }, e)])), - (cc = (t) => dn(t, 7)), - (pc = (t) => dn(t, 9)), - (dn = (t, e) => { - let o = e >= 10, - i = t.attributes.getString('mode', 'nearest'); - if (i !== 'nearest' && i !== 'linear' && (e < 11 || i !== 'cubic')) - throw new Error(`unrecognized mode: ${i}`); - let u = []; - e < 9 && ((u = t.attributes.getFloats('scales')), lo(u, i, o)); - let n = t.attributes.getFloat('extrapolation_value', 0), - s = e > 10 ? t.attributes.getString('coordinate_transformation_mode', 'half_pixel') : 'asymmetric'; - if ( - [ - 'asymmetric', - 'pytorch_half_pixel', - 'tf_half_pixel_for_nn', - 'align_corners', - 'tf_crop_and_resize', - 'half_pixel', - ].indexOf(s) === -1 - ) - throw new Error(`coordinate_transform_mode '${s}' is not supported`); - let d = s === 'tf_crop_and_resize', - f = d, - r = i === 'nearest' && e >= 11 ? t.attributes.getString('nearest_mode', 'round_prefer_floor') : ''; - if (['round_prefer_floor', 'round_prefer_ceil', 'floor', 'ceil', ''].indexOf(r) === -1) - throw new Error(`nearest_mode '${r}' is not supported`); - let a = t.attributes.getFloat('cubic_coeff_a', -0.75), - l = t.attributes.getInt('exclude_outside', 0) !== 0; - if (l && i !== 'cubic') throw new Error('exclude_outside can be set to 1 only when mode is CUBIC.'); - let p = e < 11 ? !0 : i === 'nearest' && s === 'asymmetric' && r === 'floor', - m = 0, - y = 0, - T = 0; - return ( - e > 10 - ? t.inputs.length > 2 - ? ((m = 1), (y = 2), (T = 3)) - : ((y = 1), (T = 2)) - : e === 9 && (y = 1), - ee({ - opset: e, - isResize: o, - mode: i, - scales: u, - extrapolationValue: n, - coordinateTransformMode: s, - useExtrapolation: f, - needRoiInput: d, - nearestMode: r, - cubicCoefficientA: a, - excludeOutside: l, - useNearest2xOptimization: p, - roiInputIdx: m, - scalesInputIdx: y, - sizesInputIdx: T, - }) - ); - }), - (yb = (t, e, o) => { - let i = q(t.session.backend.glContext.version), - [u, n] = t.calculateTextureWidthAndHeight(e[0].dims, 0), - s = e[0].dims.map((T, v) => Math.floor(T * o.scales[v])), - [d, f] = t.calculateTextureWidthAndHeight(s, 0), - r = s.length, - a = new Array(r), - l = new Array(r), - p = ` - int output_pitches[${r}]; - int input_pitches[${r}]; - `; - for (let T = r - 1; T >= 0; T--) - (a[T] = T === r - 1 ? 1 : a[T + 1] * s[T + 1]), - (l[T] = T === r - 1 ? 1 : l[T + 1] * e[0].dims[T + 1]), - (p += ` - output_pitches[${T}] = ${a[T]}; - input_pitches[${T}] = ${l[T]}; - `); - let m = ` - float getInputFloat(int index) { - vec2 coords = offsetToCoords(index, ${u}, ${n}); - float value = getColorAsFloat(${i.texture2D}(X, coords)); - return value; - } - `, - y = - o.mode === 'nearest' - ? ` - ${m} - float process(int indices[${r}]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${d}, ${f}); - - ${p} - - int d, m; - for (int dim = 0; dim < ${r}; ++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); - }` - : r === 4 - ? ` - ${m} - float process(int indices[4]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${d}, ${f}); - - ${p} - - 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 == (${e[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]); - }` - : ` - ${m} - float process(int indices[2]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${d}, ${f}); - - ${p} - - 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 == (${e[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 { - ...fc, - output: { dims: s, type: e[0].type, textureType: 0 }, - shaderSource: y, - variables: [ - { - name: 'scales', - type: 'int', - arrayLength: o.scales.length, - data: o.scales.map((T) => Math.ceil(T)), - }, - ], - }; - }), - (Ri = (t, e) => { - if ( - !t || - (e.opset < 9 && t.length !== 1) || - (e.opset >= 9 && e.opset < 11 && t.length !== 2) || - (e.opset >= 11 && t.length < 2) - ) - throw new Error('invalid inputs.'); - if (e.scales.length > 0 && t[0].dims.length !== e.scales.length) - throw new Error('Invalid input shape.'); - if (t[0].type === 'string') throw new Error('Invalid input tensor types.'); - }), - (lo = (t, e, o) => { - if (o) { - for (let i of t) if (i <= 0) throw new Error('Scale value should be greater than 0.'); - } else for (let i of t) if (i < 1) throw new Error('Scale value should be greater than or equal to 1.'); - if ((e === 'linear' || e === 'cubic') && t.length !== 2 && (t.length !== 4 || t[0] !== 1 || t[1] !== 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 ${ - o ? 'Resize' : 'Upsample' - } opeartor.` - ); - }); - }), - Gi, - Ui, - dc, - hc, - Tb, - xb, - vb, - wb, - mc = L(() => { - xe(), - ae(), - Ft(), - br(), - Mi(), - (Gi = { name: 'Resize', inputNames: ['A'], inputTypes: [2] }), - (Ui = (t, e, o) => (Ri(e, o), [t.run({ ...Gi, cacheHint: o.cacheKey, get: () => Tb(t, e, o) }, e)])), - (dc = (t) => dn(t, 10)), - (hc = (t) => dn(t, 11)), - (Tb = (t, e, o) => { - let i = q(t.session.backend.glContext.version), - [u, n] = xb(e, o); - if (u.every((E) => E === 1) && o.coordinateTransformMode !== 'tf_crop_and_resize') - return { - ...Gi, - output: { dims: n, type: e[0].type, textureType: 2 }, - hasMain: !0, - shaderSource: `void main() { - vec4 v = ${i.texture2D}(X, TexCoords); - ${i.output} = v; - }`, - }; - let s = n.length; - if (s < 2) throw new Error(`output dimension should be at least 2, but got ${s}`); - let d = n[s - 2], - f = n[s - 1], - r = e[0].dims; - if (s !== r.length) throw new Error(`output dimension should match input ${r.length}, but got ${s}`); - let a = r[s - 2], - l = r[s - 1], - p = u[s - 2], - m = u[s - 1], - y = ''; - if (o.mode !== 'linear') throw new Error(`resize (packed) does not support mode: '${o.mode}'`); - switch (o.coordinateTransformMode) { - case 'asymmetric': - y = ` - vec4 getSourceFracIndex(ivec4 coords) { - return vec4(coords) / scaleWHWH; - } - `; - break; - case 'half_pixel': - y = ` - vec4 getSourceFracIndex(ivec4 coords) { - return (vec4(coords) + 0.5) / scaleWHWH - 0.5; - } - `; - break; - case 'pytorch_half_pixel': - y = ` - vec4 getSourceFracIndex(ivec4 coords) { - vec4 fcoords = vec4(coords); - return vec4( - ${f}.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, - ${f}.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': - y = ` - vec4 getSourceFracIndex(ivec4 coords) { - vec4 resized = vec4(${f}.0 - 1.0, ${d}.0 - 1.0, ${f}.0 - 1.0, - ${d}.0 - 1.0); - vec4 original = vec4(${l}.0 - 1.0, ${a}.0 - 1.0, ${l}.0 - 1.0, - ${a}.0 - 1.0); - vec4 new_scale = original / resized; - return vec4(coords) * new_scale; - } - `; - break; - default: - throw new Error( - `resize (packed) does not support coordinateTransformMode: '${o.coordinateTransformMode}'` - ); - } - let T = Ke(s), - v = $t(), - S = ` - const vec2 inputWH = vec2(${a}.0, ${l}.0); - const vec4 scaleWHWH = vec4(float(${p}), float(${m}), float(${p}), float(${m})); - ${v} - ${y} - float getAValue(int x10, int r, int c, int d) { - return getChannel(getA(x10, r, c, d), vec2(c, d)); - } - void main() { - ${T} 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 < ${f - 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); - - ${i.output} = vec4(newValue); - } - `; - return { ...Gi, output: { dims: n, type: e[0].type, textureType: 2 }, hasMain: !0, shaderSource: S }; - }), - (xb = (t, e) => { - let o = t[0].dims, - i = e.scales, - u; - if (i.length === 0) { - let s = t[e.scalesInputIdx]; - if (s && s.size !== 0) { - if (t[e.sizesInputIdx]) - throw new Error('Only one of scales or sizes must be provided as input.'); - i = vb(s, e.mode, e.isResize); - } else { - let d = t[e.sizesInputIdx]; - if (!d || d.size === 0) throw new Error('Either scales or sizes MUST be provided as input.'); - (u = Array.from(d.integerData)), (i = wb(u, o, e.mode, e.isResize)); - } - } else if (t[e.sizesInputIdx]) - throw new Error('Only one of scales or sizes must be provided as input.'); - let n = u || o.map((s, d) => Math.floor(s * i[d])); - return [i, n]; - }), - (vb = (t, e, o) => { - let i = Array.from(t.floatData); - return lo(i, e, o), i; - }), - (wb = (t, e, o, i) => { - let u = e.length, - n = new Array(u); - for (let s = 0, d = u; s < d; s++) - if (e[s] === 0) { - if (t[s] !== 0) throw new Error('Input dim is zero but required output dim is non-zero.'); - n[s] = 1; - } else n[s] = t[s] / e[s]; - return lo(n, o, i), n; - }); - }), - bc, - _b, - gc = L(() => { - mr(), - (bc = (t, e) => (_b(e), [new Fe([e[0].dims.length], 'int32', void 0, void 0, new Int32Array(e[0].dims))])), - (_b = (t) => { - if (!t || t.length !== 1) throw new Error('Shape requires 1 input.'); - }); - }), - zi, - yc, - Tc, - xc, - Ob, - vc, - Ib, - Sb, - wc = L(() => { - Ge(), - pn(), - fe(), - ae(), - (zi = { name: 'Slice', inputNames: ['A'], inputTypes: [0] }), - (yc = (t, e, o) => (Ob(e), [t.run({ ...zi, cacheHint: o.cacheKey, get: () => xc(t, e[0], o) }, e)])), - (Tc = (t) => { - let e = t.attributes.getInts('starts'), - o = t.attributes.getInts('ends'), - i = t.attributes.getInts('axes', []); - return ee({ starts: e, ends: o, axes: i }); - }), - (xc = (t, e, o) => { - let i = o.axes.length === 0 ? e.dims.slice(0).map((a, l) => l) : o.axes, - u = U.normalizeAxes(i, e.dims.length), - n = o.starts.map((a, l) => - a > e.dims[u[l]] - 1 ? e.dims[u[l]] : U.normalizeAxis(a, e.dims[u[l]]) - ), - s = o.ends.map((a, l) => (a > e.dims[u[l]] - 1 ? e.dims[u[l]] : U.normalizeAxis(a, e.dims[u[l]]))), - d = e.dims.slice(), - f = []; - for (let a = 0; a < u.length; a++) - (d[u[a]] = s[a] - n[a]), n[a] > 0 && f.push(`outputIdx[${u[a]}] += ${n[a]};`); - let r = ` - float process(int outputIdx[${d.length}]) { - ${f.join(` - `)} - return _A(outputIdx); - }`; - return { ...zi, output: { dims: d, type: e.type, textureType: 0 }, shaderSource: r }; - }), - (Ob = (t) => { - if (!t || t.length !== 1) throw new Error('Slice requires 1 input.'); - if (Jt.indexOf(t[0].type) === -1) throw new Error('Invalid input type.'); - }), - (vc = (t, e) => { - Sb(e); - let o = Ib(t, e); - return [t.run({ ...zi, cacheHint: o.cacheKey, get: () => xc(t, e[0], o) }, [e[0]])]; - }), - (Ib = (t, e) => { - if ( - !t.session.isInitializer(e[1].dataId) || - !t.session.isInitializer(e[2].dataId) || - (e.length >= 4 && !t.session.isInitializer(e[3].dataId)) || - (e.length >= 5 && !t.session.isInitializer(e[4].dataId)) - ) - throw new Error('dynamic slice attributes are not allowed'); - if (e.length >= 5 && e[4].integerData.some((s) => s !== 1)) - throw new Error('currently non-1 steps is not supported for Slice'); - let o = Array.from(e[1].integerData), - i = Array.from(e[2].integerData), - u = e.length >= 4 ? Array.from(e[3].integerData) : [], - n = `${u};${o};${i}`; - return { starts: o, ends: i, axes: u, cacheKey: n }; - }), - (Sb = (t) => { - if (!t || t.length < 3 || t.length > 5) throw new Error('Invalid input number.'); - if (t[1].type !== 'int32' || t[1].dims.length !== 1) throw new Error('Invalid input type.'); - if (t[2].type !== 'int32' || t[2].dims.length !== 1) throw new Error('Invalid input type.'); - if (t.length >= 4 && (t[3].type !== 'int32' || t[3].dims.length !== 1)) - throw new Error('Invalid input type.'); - if (t.length >= 5 && (t[4].type !== 'int32' || t[4].dims.length !== 1)) - throw new Error('Invalid input type.'); - }); - }), - _c, - Oc, - Ic, - Sc, - Ac, - Pc, - Ec, - Dc, - Ab, - Pb, - Eb, - Lc, - Fc = L(() => { - Ge(), - fe(), - xe(), - ae(), - ao(), - (_c = { name: 'SoftmaxComputeMax', inputNames: ['A'], inputTypes: [0] }), - (Oc = { name: 'SoftmaxComputeScale', inputNames: ['A', 'Max'], inputTypes: [0, 0] }), - (Ic = { name: 'SoftMax', inputNames: ['A', 'Max', 'Norm'], inputTypes: [0, 0, 0] }), - (Sc = (t, e, o) => { - Lc(e); - let i = e[0].dims.slice(), - u = U.normalizeAxis(o.axis, i.length), - n = U.sizeToDimension(i, u), - s = U.sizeFromDimension(i, u); - return Dc(t, e, o, n, s); - }), - (Ac = (t) => ee({ axis: t.attributes.getInt('axis', 1) })), - (Pc = (t) => ee({ axis: t.attributes.getInt('axis', -1) })), - (Ec = (t, e, o) => { - Lc(e); - let i = e[0].dims.slice(), - u = U.normalizeAxis(o.axis, i.length), - n = i.length, - s = u !== n - 1, - d = [], - f = [], - r = [], - a; - s && - ((f = Array.from({ length: n }).map((y, T) => T)), - (f[u] = n - 1), - (f[n - 1] = u), - f.map((y) => d.push(i[y])), - (a = ee({ perm: f })), - (r = yr(t, e, a))); - let l = s ? U.sizeToDimension(d, n - 1) : U.sizeToDimension(i, n - 1), - p = s ? U.sizeFromDimension(d, n - 1) : U.sizeFromDimension(i, n - 1), - m = Dc(t, s ? r : e, o, l, p); - return s ? yr(t, m, a) : m; - }), - (Dc = (t, e, o, i, u) => { - let n = Ab(t, e[0], i, u, [i]), - s = t.run({ ..._c, cacheHint: o.cacheKey, get: () => n }, e), - d = Pb(t, e[0], i, u, n.output.dims, [i]), - f = t.run({ ...Oc, cacheHint: o.cacheKey, get: () => d }, [e[0], s]), - r = Eb(t, e[0], i, u, n.output.dims, d.output.dims); - return [t.run({ ...Ic, cacheHint: o.cacheKey, get: () => r }, [e[0], s, f])]; - }), - (Ab = (t, e, o, i, u) => { - let [n, s] = t.calculateTextureWidthAndHeight(e.dims, 0), - d = u.length; - if (o < 1 || i < 1) - throw new Error('Logical row count N and feature count D must be greater than or equal to 1'); - if (u.length !== 1) throw new Error('Dimensionality of the output should be 1'); - if (u[0] !== o) throw new Error('Shape of the output should be equal to logical row count'); - let f = q(t.session.backend.glContext.version), - r = ` - float process(int[${d}] indices) { - int logical_row_start_offset = indices[0] * ${i}; - - float max = getColorAsFloat(${f.texture2D}(A, offsetToCoords(logical_row_start_offset, ${n}, - ${s} ))); - for(int i=1; i<${i}; ++i) - { - float current = getColorAsFloat(${f.texture2D}(A, offsetToCoords(logical_row_start_offset + i, - ${n}, ${s}))); - if(current > max) - max = current; - } - - return max; - }`; - return { ..._c, output: { dims: u, type: e.type, textureType: 0 }, shaderSource: r }; - }), - (Pb = (t, e, o, i, u, n) => { - let [s, d] = t.calculateTextureWidthAndHeight(e.dims, 0), - f = n.length; - if (o < 1 || i < 1) - throw new Error('Logical row count N and feature count D must be greater than or equal to 1'); - if (n.length !== 1) throw new Error('Dimensionality of the output should be 1'); - if (n[0] !== o) throw new Error('Shape of the output should be equal to logical row count'); - if (u.length !== 1) throw new Error('Dimensionality of the intermediate results should be 1'); - if (u[0] !== o) - throw new Error('Shape of the intermediate results should be equal to logical row count'); - let r = q(t.session.backend.glContext.version), - a = ` - float process(int[${f}] indices) { - int logical_row_start_offset = indices[0] * ${i}; - - float norm_factor = 0.0; - float max = _Max(indices); - for(int i=0; i<${i}; ++i) - { - norm_factor += exp(getColorAsFloat(${r.texture2D}(A, offsetToCoords(logical_row_start_offset + i, - ${s}, ${d}))) - max); - } - - return norm_factor; - }`; - return { ...Oc, output: { dims: n, type: e.type, textureType: 0 }, shaderSource: a }; - }), - (Eb = (t, e, o, i, u, n) => { - let [s, d] = t.calculateTextureWidthAndHeight(e.dims, 0), - f = e.dims.length; - if (o < 1 || i < 1) - throw new Error('Logical row count N and feature count D must be greater than or equal to 1'); - if (u.length !== 1 || n.length !== 1) - throw new Error('Dimensionality of the intermediate results should be 1'); - if (u[0] !== o || n[0] !== o) - throw new Error('Shape of the intermediate results should be equal to logical row count'); - let r = ` - float process(int[${f}] indices) { - - // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) - int offset = coordsToOffset(TexCoords, ${s}, ${d}); - - //determine the logical row for this index - int logical_row_index[1]; - logical_row_index[0] = offset / ${i}; - - 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 { ...Ic, output: { dims: e.dims, type: e.type, textureType: 0 }, shaderSource: r }; - }), - (Lc = (t) => { - if (!t || t.length !== 1) throw new Error('Softmax requires 1 input.'); - if (t[0].type !== 'float32' && t[0].type !== 'float64') throw new Error('Invalid input type'); - }); - }), - $c, - Cc, - kc, - Db, - Lb, - Fb, - Bc = L(() => { - Ge(), - fe(), - ae(), - ($c = { name: 'Split', inputNames: ['A'], inputTypes: [0] }), - (Cc = (t, e, o) => { - Fb(e); - let i = U.normalizeAxis(o.axis, e[0].dims.length), - u = Db(t, e, i, o), - n = []; - for (let s = 0; s < u; ++s) - n.push(t.run({ ...$c, cacheHint: `${o.cacheKey};${s}`, get: () => Lb(t, e[0], o, i, s) }, e)); - return n; - }), - (kc = (t) => { - let e = t.attributes.getInt('axis', 0), - o = t.attributes.getInts('split', []), - i = t.outputs.length; - return ee({ axis: e, split: o, numOutputs: i }); - }), - (Db = (t, e, o, i) => { - let [, u] = an.splitShape(e[0].dims, o, i.split, i.numOutputs); - return u.length; - }), - (Lb = (t, e, o, i, u) => { - let [n, s] = an.splitShape(e.dims, i, o.split, o.numOutputs), - d = s[u], - f = n[u], - r = ` - float process(int indices[${f.length}]) { - indices[${i}] += ${d}; - return _A(indices); - } - `; - return { - ...$c, - cacheHint: `${o.cacheKey}:${u}`, - output: { dims: f, type: e.type, textureType: 0 }, - shaderSource: r, - }; - }), - (Fb = (t) => { - if (!t || t.length !== 1) throw new Error('Split requires one input.'); - if ( - t[0].type !== 'int8' && - t[0].type !== 'uint8' && - t[0].type !== 'int16' && - t[0].type !== 'uint16' && - t[0].type !== 'int32' && - t[0].type !== 'uint32' && - t[0].type !== 'float32' && - t[0].type !== 'float64' && - t[0].type !== 'bool' - ) - throw new Error('Invalid input type.'); - }); - }), - Vi, - Nc, - Rc, - $b, - Cb, - Mc = L(() => { - fe(), - (Vi = (t, e, o) => { - $b(e); - let i = U.squeezeShape(e[0].dims, o); - return [t.reshapeUnpacked(e[0], i)]; - }), - (Nc = (t, e) => (Cb(e), Vi(t, [e[0]], Array.from(e[1].integerData)))), - (Rc = (t) => t.attributes.getInts('axes')), - ($b = (t) => { - if (!t || t.length !== 1) throw new Error('Squeeze requires 1 input.'); - if (t[0].type === 'string') throw new Error('invalid input tensor types.'); - }), - (Cb = (t) => { - if (!t || t.length !== 2) throw new Error('Squeeze requires 2 inputs.'); - if (t[1].type !== 'int32') throw new Error('Invalid input type.'); - }); - }), - Gc, - kb, - Bb, - Uc = L(() => { - xe(), - ae(), - (Gc = (t, e) => { - Bb(e); - let o = { name: 'Sum', inputNames: e.map((i, u) => `X${u}`), inputTypes: new Array(e.length).fill(0) }; - return [t.run({ ...o, get: () => kb(t, e, o) }, e)]; - }), - (kb = (t, e, o) => { - let i = q(t.session.backend.glContext.version), - u = e[0].dims.slice(), - n = ` - void main() { - vec4 result = ${e.map((s, d) => `${i.texture2D}(X${d},TexCoords)`).join(' + ')}; - ${i.output} = result; - } - `; - return { ...o, output: { dims: u, type: e[0].type, textureType: 0 }, hasMain: !0, shaderSource: n }; - }), - (Bb = (t) => { - if (!t || t.length === 0) throw new Error('Sum requires inputs.'); - let e = t[0].dims.length; - for (let o = 1; o < t.length; o++) { - if (e !== t[o].dims.length) throw new Error('Input shapes are mismatched.'); - for (let i = 0; i < e; i++) - if (t[0].dims[i] !== t[o].dims[i]) throw new Error('Input shapes are not matched.'); - } - if (t[0].type !== 'float32' && t[0].type !== 'float64') throw new Error('Invalid input type.'); - for (let o = 1; o < t.length; o++) - if (t[0].type !== t[o].type) throw new Error('Input types are not matched.'); - }); - }), - zc, - Nb, - Rb, - Vc = L(() => { - pn(), - ae(), - (zc = (t, e) => { - Rb(e); - let o = { name: 'Tile', inputNames: ['A'], inputTypes: [0] }; - return [t.run({ ...o, get: () => Nb(t, e, o) }, e)]; - }), - (Nb = (t, e, o) => { - let i = e[0].dims.slice(), - u = new Array(i.length), - n = []; - for (let f = 0; f < i.length; f++) - (u[f] = i[f] * e[1].numberData[f]), - n.push(`inputIdx[${f}] = int(mod(float(outputIdx[${f}]), ${i[f]}.));`); - let s = u.length, - d = ` - float process(int outputIdx[${s}]) { - int inputIdx[${s}]; - ${n.join(` -`)} - return _A(inputIdx); - } - `; - return { ...o, output: { dims: u, type: e[0].type, textureType: 0 }, shaderSource: d }; - }), - (Rb = (t) => { - if (!t || t.length !== 2) throw new Error('Tile requires 2 input.'); - if (t[1].dims.length !== 1) throw new Error('The second input shape must 1 dimension.'); - if (t[1].dims[0] !== t[0].dims.length) throw new Error('Invalid input shape.'); - if (Jt.indexOf(t[0].type) === -1) throw new Error('Invalid input type.'); - if (t[1].type !== 'int32' && t[1].type !== 'int16') throw new Error('Invalid repeat type.'); - }); - }), - Wi, - Wc, - Hc, - Mb, - Gb, - qc = L(() => { - fe(), - (Wi = (t, e, o) => { - Mb(e); - let i = U.unsqueezeShape(e[0].dims, o); - return [t.reshapeUnpacked(e[0], i)]; - }), - (Wc = (t, e) => (Gb(e), Wi(t, [e[0]], Array.from(e[1].integerData)))), - (Hc = (t) => t.attributes.getInts('axes')), - (Mb = (t) => { - if (!t || t.length !== 1) throw new Error('Unsqueeze requires 1 input.'); - if (t[0].type === 'string') throw new Error('invalid input tensor types.'); - }), - (Gb = (t) => { - if (!t || t.length !== 2) throw new Error('Unsqueeze requires 2 inputs.'); - if (t[1].type !== 'int32') throw new Error('Invalid input type.'); - }); - }), - jc, - Yc = L(() => { - nl(), - bl(), - Tl(), - Il(), - no(), - lf(), - mf(), - yf(), - vf(), - If(), - Pf(), - Ff(), - Bf(), - oo(), - Gf(), - Qf(), - sc(), - lc(), - mc(), - gc(), - wc(), - Fc(), - Bc(), - Mc(), - Uc(), - Vc(), - ao(), - Ai(), - qc(), - Mi(), - (jc = [ - ['Abs', '', '6+', Sl], - ['Acos', '', '7+', Al], - ['Add', '', '7+', ol], - ['And', '', '7+', il], - ['Asin', '', '7+', Pl], - ['Atan', '', '7+', El], - ['AveragePool', '', '7+', zf, Vf], - ['BatchNormalization', '', '7+', tl, rl], - ['Cast', '', '6+', gl, yl], - ['Ceil', '', '6+', Fl], - ['Clip', '', '6-10', Ii, Dl], - ['Clip', '', '11+', Ll], - ['Concat', '', '4+', wl, Ol], - ['Conv', '', '1+', $i, Ci], - ['ConvTranspose', '', '1+', sf, uf], - ['Cos', '', '7+', $l], - ['Div', '', '7+', al], - ['Dropout', '', '7+', Si], - ['DepthToSpace', '', '1+', df, hf], - ['Equal', '', '7+', sl], - ['Elu', '', '6+', Cl, kl], - ['Exp', '', '6+', Bl], - ['Flatten', '', '1+', bf, gf], - ['Floor', '', '6+', Nl], - ['FusedConv', 'com.microsoft', '1+', $i, Ci], - ['Gather', '', '1+', Tf, xf], - ['Gemm', '', '7-10', ki, _f], - ['Gemm', '', '11+', ki, Of], - ['GlobalAveragePool', '', '1+', Hf, qf], - ['GlobalMaxPool', '', '1+', Jf], - ['Greater', '', '7+', ul], - ['Identity', '', '1+', Si], - ['ImageScaler', '', '1+', Sf, Af], - ['InstanceNormalization', '', '6+', Df, Lf], - ['LeakyRelu', '', '6+', Rl, Ml], - ['Less', '', '7+', ll], - ['LRN', '', '1+', $f, Cf], - ['Log', '', '6+', Gl], - ['MatMul', '', '1+', Ql, ef], - ['MaxPool', '', '1+', jf, Yf], - ['Mul', '', '7+', fl], - ['Neg', '', '6+', Ul], - ['Not', '', '1+', zl], - ['Or', '', '7+', cl], - ['Pad', '', '2-10', Bi, Nf], - ['Pad', '', '11+', Rf, Mf], - ['Pow', '', '7+', pl], - ['PRelu', '', '7+', dl], - ['ReduceLogSum', '', '1+', ic, Zt], - ['ReduceMax', '', '1+', rc, Zt], - ['ReduceMean', '', '1+', tc, Zt], - ['ReduceMin', '', '1+', nc, Zt], - ['ReduceProd', '', '1+', oc, Zt], - ['ReduceSum', '', '1-12', ec, Zt], - ['ReduceSumSquare', '', '1+', ac, Zt], - ['Relu', '', '6+', Vl], - ['Reshape', '', '5+', uc], - ['Resize', '', '10', Ui, dc], - ['Resize', '', '11+', Ui, hc], - ['Shape', '', '1+', bc], - ['Sigmoid', '', '6+', Wl], - ['Sin', '', '7+', Hl], - ['Slice', '', '10+', vc], - ['Slice', '', '1-9', yc, Tc], - ['Softmax', '', '1-12', Sc, Ac], - ['Softmax', '', '13+', Ec, Pc], - ['Split', '', '2-12', Cc, kc], - ['Sqrt', '', '6+', ql], - ['Squeeze', '', '1-12', Vi, Rc], - ['Squeeze', '', '13+', Nc], - ['Sub', '', '7+', hl], - ['Sum', '', '6+', Gc], - ['Tan', '', '7+', jl], - ['Tanh', '', '6+', Yl], - ['Tile', '', '6+', zc], - ['Transpose', '', '1+', yr, cf], - ['Upsample', '', '7-8', Ni, cc], - ['Upsample', '', '9', Ni, pc], - ['Unsqueeze', '', '1-12', Wi, Hc], - ['Unsqueeze', '', '13+', Wc], - ['Xor', '', '7+', ml], - ]); - }); -function Kc(t) { - let e = {}, - o; - for (; (o = Xc.exec(t)) !== null; ) { - let i = o[3] - .split(',') - .map((u) => { - let n = u.trim().split(' '); - return n && n.length === 2 ? { type: n[0], name: n[1] } : null; - }) - .filter((u) => u !== null); - e[o[2]] = { params: i, body: o[4] }; - } - for (let i in e) { - let u = Ub.replace('__FUNC__', i), - n = new RegExp(u, 'gm'); - for (; (o = n.exec(t)) !== null; ) { - let s = o[1], - d = o[2], - f = o[3].split(','), - r = s ? `${s} ${d};` : '', - a = e[i].body, - l = ''; - e[i].params.forEach((m, y) => { - m && - (l += `${m.type} ${m.name} = ${f[y]}; -`); - }), - (a = `${l} - ${a}`), - (a = a.replace('return', `${d} = `)); - let p = ` - ${r} - { - ${a} - } - `; - t = t.replace(o[0], p); - } - } - return (t = t.replace(Xc, '')), t; -} -var Xc, - Ub, - Jc = L(() => { - (Xc = /@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm), - (Ub = '(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;'); - }); -function Gr(t, e) { - let o = [], - i = [], - u = e != null && Array.isArray(e) && e.length === 0, - n = e == null || u ? null : zb(e, t).sort(), - s = 0; - for (let d = 0; d < t.length; ++d) { - if (n != null) { - if (n[s] === d && t[d] !== 1) throw new Error(`Can't squeeze axis ${d} since its dim '${t[d]}' is not 1`); - (n[s] == null || n[s] > d) && t[d] === 1 && (o.push(t[d]), i.push(d)), n[s] <= d && s++; - } - t[d] !== 1 && (o.push(t[d]), i.push(d)); - } - return { newShape: o, keptDims: i }; -} -function zb(t, e) { - let o = e.length; - return ( - (t = t == null ? e.map((i, u) => u) : [].concat(t)), - Cr( - t.every((i) => i >= -o && i < o), - () => `All values in axis param must be in range [-${o}, ${o}) but got axis ${t}` - ), - Cr(t.every(Vb), () => `All values in axis param must be integers but got axis ${t}`), - t.map((i) => (i < 0 ? o + i : i)) - ); -} -function Vb(t) { - return t % 1 === 0; -} -function Wb(t) { - if (t.length === 0) return 1; - let e = t[0]; - for (let o = 1; o < t.length; o++) e *= t[o]; - return e; -} -function Zc(t) { - let e = Math.ceil(Math.sqrt(t)); - return [e, Math.ceil(t / e)]; -} -var fo, - Hi = L(() => { - ut(), - fe(), - (fo = class { - constructor(t) { - this.maxTextureSize = t; - } - computeTextureWH(t, e) { - let o = this.computeTexture(t, e); - return e && e.isPacked && ((o[0] /= 2), (o[1] /= 2)), e && e.reverseWH ? [o[1], o[0]] : o; - } - computeTexture(t, e) { - let o = e && e.isPacked; - if (t.length === 0) return o ? [2, 2] : [1, 1]; - let i = this.maxTextureSize; - if (e && e.breakAxis !== void 0) { - let s = e.breakAxis >= t.length ? 1 : t.slice(e.breakAxis).reduce((f, r) => f * r), - d = e.breakAxis <= 0 ? 1 : t.slice(0, e.breakAxis).reduce((f, r) => f * r); - if (s > i || d > i) - ce.verbose( - 'TextureLayout', - `Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}` - ); - else return [s, d]; - } - let u = t.slice(0); - o && - ((i = i * 2), - (u = u.map((s, d) => (d >= u.length - 2 ? (u[d] % 2 === 0 ? u[d] : u[d] + 1) : u[d]))), - u.length === 1 && (u = [2, u[0]])), - u.length !== 2 && (u = Gr(u).newShape); - let n = Wb(u); - return u.length <= 1 && n <= i - ? [1, n] - : u.length === 2 && u[0] <= i && u[1] <= i - ? u - : u.length === 3 && u[0] * u[1] <= i && u[2] <= i - ? [u[0] * u[1], u[2]] - : u.length === 3 && u[0] <= i && u[1] * u[2] <= i - ? [u[0], u[1] * u[2]] - : u.length === 4 && u[0] * u[1] * u[2] <= i && u[3] <= i - ? [u[0] * u[1] * u[2], u[3]] - : u.length === 4 && u[0] <= i && u[1] * u[2] * u[3] <= i - ? [u[0], u[1] * u[2] * u[3]] - : o - ? Zc(n / 4).map((s) => s * 2) - : Zc(n); - } - }); - }), - co, - Qc = L(() => { - fe(), - Vt(), - xe(), - Hi(), - Ft(), - (co = class extends pt { - constructor(t) { - super(t); - } - getFunctions() { - return { - ...this.offsetToCoords(), - ...this.coordsToOffset(), - ...this.toVec(), - ...this.valueFrom(), - ...this.getCommonUtilFuncs(), - ...this.getInputsSamplingSnippets(), - ...this.getOutputSamplingSnippet(), - }; - } - getCustomTypes() { - return {}; - } - offsetToCoords() { - let t = 'offsetToCoords'; - return { - offsetToCoords: new R(` - vec2 ${t}(int offset, int width, int height) { - int t = offset / width; - int s = offset - t*width; - vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height); - return coords; - } - `), - }; - } - coordsToOffset() { - let t = 'coordsToOffset'; - return { - coordsToOffset: new R(` - int ${t}(vec2 coords, int width, int height) { - float s = coords.s * float(width); - float t = coords.t * float(height); - int offset = int(t) * width + int(s); - return offset; - } - `), - }; - } - getOutputSamplingSnippet() { - let t = this.context.outputTextureLayout; - return t.isPacked - ? this.getPackedOutputSamplingSnippet(t) - : this.getUnpackedOutputSamplingSnippet(t); - } - getPackedOutputSamplingSnippet(t) { - let e = t.unpackedShape, - o = [t.width, t.height], - i = {}, - u = 'getOutputCoords'; - switch (e.length) { - case 0: - i[u] = this.getOutputScalarCoords(); - break; - case 1: - i[u] = this.getOutputPacked1DCoords(e, o); - break; - case 2: - i[u] = this.getOutputPacked2DCoords(e, o); - break; - case 3: - i[u] = this.getOutputPacked3DCoords(e, o); - break; - default: - i[u] = this.getOutputPackedNDCoords(e, o); - } - let n = ` - void setOutput(vec4 val) { - ${q(this.context.glContext.version).output} = val; - } - `, - s = 'floatTextureSetRGBA'; - return (i[s] = new R(n)), i; - } - getUnpackedOutputSamplingSnippet(t) { - let e = t.unpackedShape, - o = [t.width, t.height], - i = {}, - u = 'getOutputCoords'; - switch (e.length) { - case 0: - i[u] = this.getOutputScalarCoords(); - break; - case 1: - i[u] = this.getOutputUnpacked1DCoords(e, o); - break; - case 2: - i[u] = this.getOutputUnpacked2DCoords(e, o); - break; - case 3: - i[u] = this.getOutputUnpacked3DCoords(e, o); - break; - case 4: - i[u] = this.getOutputUnpacked4DCoords(e, o); - break; - case 5: - i[u] = this.getOutputUnpacked5DCoords(e, o); - break; - case 6: - i[u] = this.getOutputUnpacked6DCoords(e, o); - break; - default: - throw new Error(`Unsupported output dimensionality: ${e.length}`); - } - let n = ` - void setOutput(float val) { - ${q(this.context.glContext.version).output} = vec4(val, 0, 0, 0); - } - `, - s = 'floatTextureSetR'; - return (i[s] = new R(n)), i; - } - getOutputScalarCoords() { - return new R(` - int getOutputCoords() { - return 0; - } - `); - } - getOutputPacked1DCoords(t, e) { - let o = e, - i = ''; - return o[0] === 1 - ? ((i = ` - int getOutputCoords() { - return 2 * int(TexCoords.y * ${o[1]}.0); - } - `), - new R(i)) - : o[1] === 1 - ? ((i = ` - int getOutputCoords() { - return 2 * int(TexCoords.x * ${o[0]}.0); - } - `), - new R(i)) - : ((i = ` - int getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${o[0]}, ${o[1]})); - return 2 * (resTexRC.y * ${o[0]} + resTexRC.x); - } - `), - new R(i)); - } - getOutputPacked2DCoords(t, e) { - let o = ''; - if (cr.arraysEqual(t, e)) - return ( - (o = ` - ivec2 getOutputCoords() { - return 2 * ivec2(TexCoords.xy * vec2(${e[0]}, ${e[1]})); - } - `), - new R(o) - ); - let i = e, - u = Math.ceil(t[1] / 2); - return ( - (o = ` - ivec2 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${i[0]}, ${i[1]})); - - int index = resTexRC.y * ${i[0]} + resTexRC.x; - - // reverse r and c order for packed texture - int r = imod(index, ${u}) * 2; - int c = 2 * (index / ${u}); - - return ivec2(r, c); - } - `), - new R(o) - ); - } - getOutputPacked3DCoords(t, e) { - let o = [e[0], e[1]], - i = Math.ceil(t[2] / 2), - u = i * Math.ceil(t[1] / 2), - n = ` - ivec3 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${o[0]}, ${o[1]})); - int index = resTexRC.y * ${o[0]} + resTexRC.x; - - int b = index / ${u}; - index -= b * ${u}; - - // reverse r and c order for packed texture - int r = imod(index, ${i}) * 2; - int c = 2 * (index / ${i}); - - return ivec3(b, r, c); - } - `; - return new R(n); - } - getOutputPackedNDCoords(t, e) { - let o = [e[0], e[1]], - i = Math.ceil(t[t.length - 1] / 2), - u = i * Math.ceil(t[t.length - 2] / 2), - n = u, - s = '', - d = 'b, r, c'; - for (let r = 2; r < t.length - 1; r++) - (n *= t[t.length - r - 1]), - (s = - ` - int b${r} = index / ${n}; - index -= b${r} * ${n}; - ` + s), - (d = `b${r}, ` + d); - let f = ` - ivec${t.length} getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${o[0]}, ${o[1]})); - int index = resTexRC.y * ${o[0]} + resTexRC.x; - - ${s} - - int b = index / ${u}; - index -= b * ${u}; - - // reverse r and c order for packed texture - int r = imod(index, ${i}) * 2; - int c = 2 * (index / ${i}); - - return ivec${t.length}(${d}); - } - `; - return new R(f); - } - getOutputUnpacked1DCoords(t, e) { - let o = ` - int getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e[0]}, ${e[1]})); - return resTexRC.y * ${e[0]} + resTexRC.x; - } - `; - return new R(o); - } - getOutputUnpacked2DCoords(t, e) { - let o = ` - ivec2 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e[0]}, ${e[1]})); - int index = resTexRC.y * ${e[0]} + resTexRC.x; - int r = index / ${t[1]}; - int c = index - r * ${t[1]}; - return ivec2(r, c); - } - `; - return new R(o); - } - getOutputUnpacked3DCoords(t, e) { - let o = '', - i = t.length, - u = null; - i < 2 && (u = []), (u = new Array(i - 1)), (u[i - 2] = t[i - 1]); - for (let d = i - 3; d >= 0; --d) u[d] = u[d + 1] * t[d + 1]; - let n = ['r', 'c', 'd'], - s = u - .map((d, f) => { - let r = `int ${n[f]} = index / ${d}`, - a = - f === u.length - 1 - ? `int ${n[f + 1]} = index - ${n[f]} * ${d}` - : `index -= ${n[f]} * ${d}`; - return `${r}; ${a};`; - }) - .join(''); - return ( - (o = ` - ivec3 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e[0]}, ${e[1]})); - int index = resTexRC.y * ${e[0]} + resTexRC.x; - ${s} - return ivec3(r, c, d); - } - `), - new R(o) - ); - } - getOutputUnpacked4DCoords(t, e) { - let o = '', - i = t.length, - u = null; - i < 2 && (u = []), (u = new Array(i - 1)), (u[i - 2] = t[i - 1]); - for (let d = i - 3; d >= 0; --d) u[d] = u[d + 1] * t[d + 1]; - let n = ['r', 'c', 'd', 'd2'], - s = u - .map((d, f) => { - let r = `int ${n[f]} = index / ${d}`, - a = - f === u.length - 1 - ? `int ${n[f + 1]} = index - ${n[f]} * ${d}` - : `index -= ${n[f]} * ${d}`; - return `${r}; ${a};`; - }) - .join(''); - return ( - (o = ` - ivec4 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e[0]}, ${e[1]})); - int index = resTexRC.y * ${e[0]} + resTexRC.x; - ${s} - return ivec4(r, c, d, d2); - } - `), - new R(o) - ); - } - getOutputUnpacked5DCoords(t, e) { - let o = '', - i = t.length, - u = null; - i < 2 && (u = []), (u = new Array(i - 1)), (u[i - 2] = t[i - 1]); - for (let d = i - 3; d >= 0; --d) u[d] = u[d + 1] * t[d + 1]; - let n = ['r', 'c', 'd', 'd2', 'd3'], - s = u - .map((d, f) => { - let r = `int ${n[f]} = index / ${d}`, - a = - f === u.length - 1 - ? `int ${n[f + 1]} = index - ${n[f]} * ${d}` - : `index -= ${n[f]} * ${d}`; - return `${r}; ${a};`; - }) - .join(''); - return ( - (o = ` - ivec5 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e[0]}, ${e[1]})); - int index = resTexRC.y * ${e[0]} + resTexRC.x; - ${s} - return ivec5(r, c, d, d2, d3); - } - `), - new R(o) - ); - } - getOutputUnpacked6DCoords(t, e) { - let o = '', - i = t.length, - u = null; - i < 2 && (u = []), (u = new Array(i - 1)), (u[i - 2] = t[i - 1]); - for (let d = i - 3; d >= 0; --d) u[d] = u[d + 1] * t[d + 1]; - let n = ['r', 'c', 'd', 'd2', 'd3', 'd4'], - s = u - .map((d, f) => { - let r = `int ${n[f]} = index / ${d}`, - a = - f === u.length - 1 - ? `int ${n[f + 1]} = index - ${n[f]} * ${d}` - : `index -= ${n[f]} * ${d}`; - return `${r}; ${a};`; - }) - .join(''); - return ( - (o = ` - ivec6 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e[0]}, ${e[1]})); - int index = resTexRC.y * ${e[0]} + resTexRC.x; - ${s} - return ivec6(r, c, d, d2, d3, d4); - } - `), - new R(o) - ); - } - getCommonUtilFuncs() { - let t = {}, - e = 'uvFromFlat'; - (t[e] = new R(` - vec2 uvFromFlat(int texNumR, int texNumC, int index) { - int texC = index / texNumR; - int texR = index - texC * texNumR; - // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to - // v. - return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC); - } - `)), - (e = 'packedUVfrom1D'), - (t[e] = new R(` - vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { - int texelIndex = index / 2; - int texR = texelIndex / texNumC; - int texC = texelIndex - texR * texNumC; - return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); - } - `)), - (e = 'packedUVfrom2D'), - (t[e] = new R(` - vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) { - int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); - int texR = texelIndex / texNumC; - int texC = texelIndex - texR * texNumC; - return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); - } - `)), - (e = 'packedUVfrom3D'), - (t[e] = new R(` - vec2 packedUVfrom3D(int texNumR, int texNumC, - int texelsInBatch, int texelsInLogicalRow, int b, - int row, int col) { - int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); - int texR = index / texNumC; - int texC = index - texR * texNumC; - return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); - } - `)), - (e = 'sampleTexture'); - let o = q(this.context.glContext.version); - return ( - (t[e] = new R(` - float sampleTexture(sampler2D textureSampler, vec2 uv) { - return ${o.texture2D}(textureSampler, uv).r; - }`)), - t - ); - } - getInputsSamplingSnippets() { - let t = {}, - e = this.context.outputTextureLayout; - return ( - this.context.programInfo.inputNames.forEach((o, i) => { - let u = this.context.inputTextureLayouts[i], - n = Kn(o); - u.isPacked - ? (t[n] = this.getPackedSamplerFromInput(n, o, u)) - : (t[n] = this.getUnpackedSamplerFromInput(n, o, u)); - let s = Mu(o); - u.unpackedShape.length <= e.unpackedShape.length && - (u.isPacked - ? (t[s] = this.getPackedSamplerAtOutputCoords(s, u, e, o)) - : (t[s] = this.getUnpackedSamplerAtOutputCoords(s, u, e, o))); - }), - t - ); - } - getPackedSamplerAtOutputCoords(t, e, o, i) { - let u = e.unpackedShape, - n = o.unpackedShape, - s = Kn(i), - d = u.length, - f = n.length, - r = Xe.getBroadcastDims(u, n), - a = Ke(f), - l = f - d, - p, - m = St(); - d === 0 - ? (p = '') - : f < 2 && r.length >= 1 - ? (p = 'coords = 0;') - : (p = r.map((F) => `coords.${m[F + l]} = 0;`).join(` -`)); - let y = ''; - f < 2 && d > 0 ? (y = 'coords') : (y = u.map((F, B) => `coords.${m[B + l]}`).join(', ')); - let T = 'return outputValue;', - v = U.size(u) === 1, - S = U.size(n) === 1; - if (d === 1 && !v && !S) - T = ` - return vec4(outputValue.xy, outputValue.xy); - `; - else if (v && !S) - f === 1 - ? (T = ` - return vec4(outputValue.x, outputValue.x, 0., 0.); - `) - : (T = ` - return vec4(outputValue.x); - `); - else if (r.length) { - let F = d - 2, - B = d - 1; - r.indexOf(F) > -1 && r.indexOf(B) > -1 - ? (T = 'return vec4(outputValue.x);') - : r.indexOf(F) > -1 - ? (T = 'return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);') - : r.indexOf(B) > -1 && (T = 'return vec4(outputValue.xx, outputValue.zz);'); - } - let E = ` - int lastDim = coords.${m[f - 1]}; - coords.${m[f - 1]} = coords.${m[f - 2]}; - coords.${m[f - 2]} = lastDim; - `, - A = ` - vec4 ${t}() { - ${a} coords = getOutputCoords(); - ${E} - ${p} - vec4 outputValue = ${s}(${y}); - ${T} - } - `; - return new R(A, ['coordinates.getOutputCoords']); - } - getUnpackedSamplerAtOutputCoords(t, e, o, i) { - let u = [o.width, o.height], - n = [e.width, e.height], - s = e.unpackedShape.length, - d = o.unpackedShape.length, - f = e.unpackedShape, - r = o.unpackedShape, - a = Kn(i); - if (s === d && cr.arraysEqual(n, u)) { - let E = ` - float ${t}() { - return sampleTexture(${i}, TexCoords); - } - `; - return new R(E, ['coordinates.sampleTexture']); - } - let l = Ke(d), - p = Xe.getBroadcastDims(f, r), - m = d - s, - y, - T = St(); - s === 0 - ? (y = '') - : d < 2 && p.length >= 1 - ? (y = 'coords = 0;') - : (y = p.map((E) => `coords.${T[E + m]} = 0;`).join(` -`)); - let v = ''; - d < 2 && s > 0 - ? (v = 'coords') - : (v = e.unpackedShape.map((E, A) => `coords.${T[A + m]}`).join(', ')); - let S = ` - float ${t}() { - ${l} coords = getOutputCoords(); - ${y} - return ${a}(${v}); - } - `; - return new R(S, ['coordinates.getOutputCoords']); - } - getPackedSamplerFromInput(t, e, o) { - switch (o.unpackedShape.length) { - case 0: - return this.getPackedSamplerScalar(t, e); - case 1: - return this.getPackedSampler1D(t, e, o); - case 2: - return this.getPackedSampler2D(t, e, o); - case 3: - return this.getPackedSampler3D(t, e, o); - default: - return this.getPackedSamplerND(t, e, o); - } - } - getUnpackedSamplerFromInput(t, e, o) { - let i = o.unpackedShape; - switch (i.length) { - case 0: - return this.getUnpackedSamplerScalar(t, e, o); - case 1: - return this.getUnpackedSampler1D(t, e, o); - case 2: - return this.getUnpackedSampler2D(t, e, o); - case 3: - return this.getUnpackedSampler3D(t, e, o); - case 4: - return this.getUnpackedSampler4D(t, e, o); - case 5: - return this.getUnpackedSampler5D(t, e, o); - case 6: - return this.getUnpackedSampler6D(t, e, o); - default: - throw new Error(`Unsupported dimension ${i.length}-D`); - } - } - getPackedSamplerScalar(t, e) { - let o = q(this.context.glContext.version), - i = ` - vec4 ${t}() { - return ${o.texture2D}(${e}, halfCR); - } - `; - return new R(i); - } - getPackedSampler1D(t, e, o) { - let i = [o.width, o.height], - u = [i[1], i[0]], - n = q(this.context.glContext.version), - s = `vec4 ${t}(int index) { - vec2 uv = packedUVfrom1D( - ${u[0]}, ${u[1]}, index); - return ${n.texture2D}(${e}, uv); - }`; - return new R(s, ['coordinates.packedUVfrom1D']); - } - getPackedSampler2D(t, e, o) { - let i = o.unpackedShape, - u = [o.width, o.height], - n = q(this.context.glContext.version), - s = u[0], - d = u[1]; - if (u != null && cr.arraysEqual(i, u)) { - let l = `vec4 ${t}(int row, int col) { - vec2 uv = (vec2(col, row) + halfCR) / vec2(${d}.0, ${s}.0); - return ${n.texture2D}(${e}, uv); - }`; - return new R(l); - } - let f = u, - r = Math.ceil(i[1] / 2), - a = `vec4 ${t}(int row, int col) { - vec2 uv = packedUVfrom2D(${f[1]}, ${f[0]}, ${r}, row, col); - return ${n.texture2D}(${e}, uv); - }`; - return new R(a, ['coordinates.packedUVfrom2D']); - } - getPackedSampler3D(t, e, o) { - let i = o.unpackedShape, - u = [o.width, o.height], - n = [u[0], u[1]], - s = q(this.context.glContext.version); - if (i[0] === 1) { - let p = i.slice(1), - m = [1, 2], - y = kr(i, p), - T = ['b', 'row', 'col'], - v = JSON.parse(JSON.stringify(o)); - v.unpackedShape = y; - let S = this.getPackedSamplerFromInput(t, e, v), - E = `${S.routineBody} - vec4 ${t}(int b, int row, int col) { - return ${t}(${Br(T, m)}); - } `; - return new R(E, S.dependencies); - } - let d = n[0], - f = n[1], - r = Math.ceil(i[2] / 2), - a = r * Math.ceil(i[1] / 2), - l = `vec4 ${t}(int b, int row, int col) { - vec2 uv = packedUVfrom3D( - ${f}, ${d}, ${a}, ${r}, b, row, col); - return ${s.texture2D}(${e}, uv);}`; - return new R(l, ['coordinates.packedUVfrom3D']); - } - getPackedSamplerND(t, e, o) { - let i = o.unpackedShape, - u = i.length, - n = [o.width, o.height], - s = q(this.context.glContext.version), - d = [n[0], n[1]], - f = d[1], - r = d[0], - a = Math.ceil(i[u - 1] / 2), - l = a * Math.ceil(i[u - 2] / 2), - p = 'int b, int row, int col', - m = `b * ${l} + (row / 2) * ${a} + (col / 2)`; - for (let T = 2; T < u - 1; T++) - (p = `int b${T}, ` + p), (l *= i[u - T - 1]), (m = `b${T} * ${l} + ` + m); - let y = `vec4 ${t}(${p}) { - int index = ${m}; - int texR = index / ${r}; - int texC = index - texR * ${r}; - vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}, ${f}); - return ${s.texture2D}(${e}, uv); - }`; - return new R(y); - } - getUnpackedSamplerScalar(t, e, o) { - let [i, u] = [o.width, o.height]; - if (i === 1 && u === 1) { - let s = ` - float ${t}() { - return sampleTexture(${e}, halfCR); - } - `; - return new R(s, ['coordinates.sampleTexture']); - } - let n = ` - float ${t}() { - int offset_${e} = coordsToOffset(TexCoords, ${i}, ${u}); - vec2 uv = uvFromFlat(${i}, ${u}, offset_${e}); - return sampleTexture(${e}, uv); - } - `; - return new R(n, [ - 'coordinates.uvFromFlat', - 'coordinates.sampleTexture', - 'coordinates.coordsToOffset', - ]); - } - getUnpackedSampler1D(t, e, o) { - let i = o.width, - u = o.height; - if (u === 1 && i === 1) { - let s = ` - float ${t}(int index) { - return sampleTexture(${e}, halfCR); - } - `; - return new R(s, ['coordinates.sampleTexture']); - } - if (u === 1) { - let s = ` - float ${t}(int index) { - vec2 uv = vec2((float(index) + 0.5) / ${i}.0, 0.5); - return sampleTexture(${e}, uv); - } - `; - return new R(s, ['coordinates.sampleTexture']); - } - if (i === 1) { - let s = ` - float ${t}(int index) { - vec2 uv = vec2(0.5, (float(index) + 0.5) / ${u}.0); - return sampleTexture(${e}, uv); - } - `; - return new R(s, ['coordinates.sampleTexture']); - } - let n = ` - float ${t}(int index) { - vec2 uv = uvFromFlat(${i}, ${u}, index); - return sampleTexture(${e}, uv); - } - `; - return new R(n, ['coordinates.uvFromFlat', 'coordinates.sampleTexture']); - } - getUnpackedSampler2D(t, e, o) { - let i = o.unpackedShape, - u = [o.height, o.width]; - if (u != null && cr.arraysEqual(i, u)) { - let l = u[1], - p = u[0], - m = ` - float ${t}(int row, int col) { - vec2 uv = (vec2(row, col) + halfCR) / vec2(${l}.0, ${p}.0); - return sampleTexture(${e}, uv); - } - `; - return new R(m, ['coordinates.sampleTexture']); - } - let { newShape: n, keptDims: s } = Gr(i), - d = n; - if (d.length < i.length) { - let l = kr(i, d), - p = JSON.parse(JSON.stringify(o)); - p.unpackedShape = l; - let m = ['col', 'row'], - y = ` - ${this.getUnpackedSamplerFromInput(t, e, p).routineBody} - float ${t}(int row, int col) { - return ${t}(${Br(m, s)}); - } - `; - return new R(y, ['coordinates.sampleTexture']); - } - let f = u[1], - r = u[0]; - if (r === 1) { - let l = ` - float ${t}(int row, int col) { - int offset_${e} = coordsToOffset(TexCoords, ${f}, ${r}); - float index = dot(vec3(row, col, offset_${e}), vec3(${i[1]}, 1, 1)); - vec2 uv = vec2(0.5, (index + 0.5) / ${f}.0); - return sampleTexture(${e}, uv); - } - `; - return new R(l, ['coordinates.sampleTexture', 'coordinates.coordsToOffset']); - } - if (f === 1) { - let l = ` - float ${t}(int row, int col) { - int offset_${e} = coordsToOffset(TexCoords, ${f}, ${r}); - float index = dot(vec3(row, col, offset_${e}), vec3(${i[1]}, 1, 1)); - vec2 uv = vec2((index + 0.5) / ${r}.0, 0.5); - return sampleTexture(${e}, uv); - } - `; - return new R(l, ['coordinates.sampleTexture', 'coordinates.coordsToOffset']); - } - let a = ` - float ${t}(int row, int col) { - int index = col * ${i[1]} + row; - vec2 uv = uvFromFlat(${f}, ${r}, index); - return sampleTexture(${e}, uv); - } - `; - return new R(a, [ - 'coordinates.uvFromFlat', - 'coordinates.sampleTexture', - 'coordinates.coordsToOffset', - ]); - } - getUnpackedSampler3D(t, e, o) { - let i = o.unpackedShape, - u = i[1] * i[2], - n = i[2], - { newShape: s, keptDims: d } = Gr(i), - f = s; - if (f.length < i.length) { - let p = kr(i, f), - m = ['batch', 'col', 'row'], - y = JSON.parse(JSON.stringify(o)); - y.unpackedShape = p; - let T = this.getUnpackedSamplerFromInput(t, e, y), - v = d.reverse(), - S = ` - ${T.routineBody} - float ${t}(int batch, int row, int col) { - return ${t}(${Br(m, v)}); - } - `; - return new R(S, T.dependencies); - } - let r = o.width, - a = o.height, - l = ` - float ${t}(int depth, int row, int col) { - // Explicitly use integer operations as dot() only works on floats. - int index = depth * ${u} + col * ${n} + row; - vec2 uv = uvFromFlat(${r}, ${a}, index); - return sampleTexture(${e}, uv); - } - `; - return new R(l, [ - 'coordinates.uvFromFlat', - 'coordinates.sampleTexture', - 'coordinates.coordsToOffset', - ]); - } - getUnpackedSampler4D(t, e, o) { - let i = o.unpackedShape, - u = i[3], - n = i[2] * u, - s = i[1] * n, - d = o.width, - f = o.height, - r = ` - float ${t}(int row, int col, int depth, int depth2) { - int index = row * ${s} + col * ${n} + - depth2 * ${u} + depth; - vec2 uv = uvFromFlat(${d}, ${f}, index); - return sampleTexture(${e}, uv); - } - `; - return new R(r, ['coordinates.uvFromFlat', 'coordinates.sampleTexture']); - } - getUnpackedSampler5D(t, e, o) { - let i = o.unpackedShape, - u = i[4], - n = i[3] * u, - s = i[2] * n, - d = i[1] * s, - { newShape: f, keptDims: r } = Gr(i); - if (f.length < i.length) { - let m = kr(i, f), - y = ['row', 'col', 'depth', 'depth2', 'depth3'], - T = JSON.parse(JSON.stringify(o)); - T.unpackedShape = m; - let v = ` - ${this.getUnpackedSamplerFromInput(t, e, T).routineBody} - float ${t}(int row, int col, int depth, int depth2, int depth3) { - return ${t}(${Br(y, r)}); - } - `; - return new R(v, ['coordinates.sampleTexture', 'coordinates.uvFromFlat']); - } - let a = o.width, - l = o.height, - p = ` - float ${t}(int row, int col, int depth, int depth2, int depth3) { - int index = row * ${d} + col * ${s} + depth * ${n} + - depth3 * ${u} + depth2; - vec2 uv = uvFromFlat(${a}, ${l}, index); - return sampleTexture(${e}, uv); - } - `; - return new R(p, ['coordinates.sampleTexture', 'coordinates.uvFromFlat']); - } - getUnpackedSampler6D(t, e, o) { - let i = o.unpackedShape, - u = i[5], - n = i[4] * u, - s = i[3] * n, - d = i[2] * s, - f = i[1] * d, - { newShape: r, keptDims: a } = Gr(i); - if (r.length < i.length) { - let y = kr(i, r), - T = ['row', 'col', 'depth', 'depth2', 'depth3', 'depth4'], - v = JSON.parse(JSON.stringify(o)); - v.unpackedShape = y; - let S = ` - ${this.getUnpackedSamplerFromInput(t, e, v).routineBody} - float ${t}(int row, int col, int depth, - int depth2, int depth3, int depth4) { - return ${t}(${Br(T, a)}); - } - `; - return new R(S, ['coordinates.sampleTexture', 'coordinates.uvFromFlat']); - } - let l = o.width, - p = o.height, - m = ` - float ${t}(int row, int col, int depth, - int depth2, int depth3, int depth4) { - int index = row * ${f} + col * ${d} + depth * ${s} + - depth2 * ${n} + depth3 * ${u} + depth4; - vec2 uv = uvFromFlat(${l}, ${p}, index); - return sampleTexture(${e}, uv); - } - `; - return new R(m, [ - 'coordinates.uvFromFlat', - 'coordinates.sampleTexture', - 'coordinates.coordsToOffset', - ]); - } - toVec() { - let t = this.context.outputTextureLayout, - e = t.shape.length, - o = t.strides, - i = t.width, - u = t.height, - n = []; - for (let d = 0; d < e - 1; ++d) - n.push(` - c[${d}] = offset / ${o[d]};`), - n.push(` - offset -= c[${d}] * ${o[d]};`); - n.push(` - c[${e - 1}] = offset;`); - let s = ` - void toVec(vec2 texCoords, out int c[${e}]) { - int offset = coordsToOffset(texCoords, ${i}, ${u}); - ${n.join('')} - } - void toVec(int offset, out int c[${e}]) { - ${n.join('')} - } - `; - return { toVec: new R(s, ['coordinates.coordsToOffset']) }; - } - valueFrom() { - let t = {}; - return ( - this.context.programInfo.inputNames.forEach((e, o) => { - let i = this.context.inputTextureLayouts[o], - u = (i.unpackedShape.length > 0 ? i.unpackedShape : i.shape).length, - n = `_${e}`; - (t[n] = new R(this.getValueFromSingle(e, u, i.width, i.height, !1), [ - `shapeUtils.indicesToOffset${n}`, - 'coordinates.offsetToCoords', - 'fragcolor.getColorAsFloat', - ])), - (n = n + '_T'), - (t[n] = new R(this.getValueFromSingle(e, u, i.width, i.height, !0), [ - `shapeUtils.indicesToOffset${n}`, - 'coordinates.offsetToCoords', - 'fragcolor.getColorAsFloat', - ])); - }), - t - ); - } - getValueFromSingle(t, e, o, i, u) { - let n = `_${t}`; - u && (n = n + '_T'); - let s = q(this.context.glContext.version); - return ` - float ${n}(int m[${e}]) { - int offset = indicesToOffset${n}(m); - vec2 coords = offsetToCoords(offset, ${o}, ${i}); - float value = getColorAsFloat(${s.texture2D}(${t}, coords)); - return value; - } - `; - } - getPackedValueFrom(t, e, o, i, u) { - let n = `_${t}_Pack`; - u && (n = n + '_T'); - let s = q(this.context.glContext.version); - return ` - vec4 ${n}(int m[${e}]) { - int offset = indicesToOffset_${t}(m); - vec2 coords = offsetToCoords(offset, ${o}, ${i}); - return ${s.texture2D}(${t}, coords); - } - `; - } - }); - }), - po, - ep = L(() => { - Vt(), - (po = class Pn extends pt { - constructor(e) { - super(e); - } - getFunctions() { - return { ...this.encodeFloat32(), ...this.decodeFloat32() }; - } - getCustomTypes() { - return {}; - } - encodeFloat32() { - return { - encode: new R(`highp vec4 encode(highp float f) { - return vec4(f, 0.0, 0.0, 0.0); - } - `), - }; - } - decodeFloat32() { - return { - decode: new R(`highp float decode(highp vec4 rgba) { - return rgba.r; - } - `), - }; - } - encodeUint8() { - let e = Pn.isLittleEndian() ? 'rgba.rgba=rgba.abgr;' : ''; - return { - encode: new R(` - 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))); - ${e} - rgba = rgba / 255.0; // values need to be normalized to [0,1] - return rgba; - } - `), - }; - } - decodeUint8() { - let e = Pn.isLittleEndian() ? 'rgba.rgba=rgba.abgr;' : ''; - return { - decode: new R(` - highp float decode(highp vec4 rgba) { - rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] - ${e} - 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() { - let e = new ArrayBuffer(4), - o = new Uint32Array(e), - i = new Uint8Array(e); - if (((o[0] = 3735928559), i[0] === 239)) return !0; - if (i[0] === 222) return !1; - throw new Error('unknown endianness'); - } - }); - }), - ho, - tp = L(() => { - Vt(), - xe(), - (ho = class extends pt { - constructor(t) { - super(t); - } - getFunctions() { - return { ...this.setFragColor(), ...this.getColorAsFloat() }; - } - getCustomTypes() { - return {}; - } - setFragColor() { - let t = q(this.context.glContext.version); - return { - setFragColor: new R( - ` - void setFragColor(float value) { - ${t.output} = encode(value); - } - `, - ['encoding.encode'] - ), - }; - } - getColorAsFloat() { - return { - getColorAsFloat: new R( - ` - float getColorAsFloat(vec4 color) { - return decode(color); - } - `, - ['encoding.decode'] - ), - }; - } - }); - }), - mo, - rp = L(() => { - Vt(), - (mo = class wr extends pt { - constructor(e) { - super(e); - } - getFunctions() { - return { - ...this.bcastIndex(), - ...this.bcastMatmulIndex(), - ...this.offsetToIndices(), - ...this.indicesToOffset(), - ...this.incrementIndices(), - }; - } - getCustomTypes() { - return {}; - } - bcastIndex() { - let e = this.context.outputTextureLayout.shape.length, - o = {}; - return ( - this.context.programInfo.inputNames.forEach((i, u) => { - let n = this.context.inputTextureLayouts[u].unpackedShape; - if (n.length <= e) { - let s = n.length, - d = e - s, - f = `bcastIndices_${i}`, - r = ''; - for (let l = 0; l < s; ++l) - r += ` - realIndices[${l}] = int( mod(float(bcastedIndices[${d + l}]), ${n[l]}.0) ); - `; - let a = ` - void ${f} (int bcastedIndices[${e}], out int realIndices[${s}]) { - ${r} - } - `; - o[f] = new R(a); - } - }), - o - ); - } - bcastMatmulIndex() { - let e = this.context.outputTextureLayout.shape.length, - o = {}; - return ( - this.context.programInfo.inputNames.forEach((i, u) => { - let n = this.context.inputTextureLayouts[u].shape; - if (!(n.length < 2 || n.length > e)) { - let s = n.length, - d = e - s, - f = `bcastMatmulIndices_${i}`, - r = ''; - for (let l = 0; l < s - 2; ++l) - r += ` - realIndices[${l}] = int( mod(float(bcastedIndices[${d + l}]), ${n[l]}.0) ); - `; - let a = ` - void ${f}(int bcastedIndices[${e}], out int realIndices[${s}]) { - ${r} - realIndices[${s - 1}] = bcastedIndices[${e - 1}]; - realIndices[${s - 2}] = bcastedIndices[${e - 2}]; - } - `; - o[f] = new R(a); - } - }), - o - ); - } - indicesToOffset() { - let e = {}; - return ( - this.context.programInfo.inputNames.forEach((o, i) => { - let u = this.context.inputTextureLayouts[i].shape, - n = this.context.inputTextureLayouts[i].strides, - s = u.length, - d = `indicesToOffset_${o}`; - (e[d] = new R(wr.indexToOffsetSingle(d, s, n))), - (d = `indicesToOffset_${o}_T`), - (e[d] = new R(wr.indexToOffsetSingle(d, s, n.slice().reverse()))); - }), - e - ); - } - static indexToOffsetSingle(e, o, i) { - let u = ''; - for (let n = o - 1; n >= 0; --n) - u += ` - offset += indices[${n}] * ${i[n]}; - `; - return ` - int ${e}(int indices[${o}]) { - int offset = 0; - ${u} - return offset; - } - `; - } - offsetToIndices() { - let e = {}; - return ( - this.context.programInfo.inputNames.forEach((o, i) => { - let u = this.context.inputTextureLayouts[i].shape, - n = this.context.inputTextureLayouts[i].strides, - s = u.length, - d = `offsetToIndices_${o}`; - (e[d] = new R(wr.offsetToIndicesSingle(d, s, n))), - (d = `offsetToIndices_${o}_T`), - (e[d] = new R(wr.offsetToIndicesSingle(d, s, n.slice().reverse()))); - }), - e - ); - } - static offsetToIndicesSingle(e, o, i) { - let u = []; - for (let n = 0; n < o - 1; ++n) - u.push(` - indices[${n}] = offset / ${i[n]};`), - u.push(` - offset -= indices[${n}] * ${i[n]};`); - return ( - u.push(` - indices[${o - 1}] = offset;`), - ` - void ${e}(int offset, out int indices[${o}]) { - ${u.join('')} - } - ` - ); - } - incrementIndices() { - let e = {}; - return ( - this.context.programInfo.inputNames.forEach((o, i) => { - let u = this.context.inputTextureLayouts[i].shape, - n = u.length, - s = `incrementIndices_${o}`, - d = ''; - for (let r = 0; r < n; ++r) - d += ` - shape[${r}] = ${u[r]};`; - let f = ` - void ${s}(int axis, out int indices[${n}]) { - int shape[${n}]; - ${d}; - for(int i = ${n} -1 ; i >= 0; --i) { - if(i > axis) continue; - indices[i] += 1; - if(indices[i] < shape[i]) { - break; - } - indices[i] = 0; - } - } - `; - e[s] = new R(f); - }), - e - ); - } - }); - }), - bo, - np = L(() => { - Vt(), - (bo = class extends pt { - constructor(t) { - super(t); - } - getCustomTypes() { - return {}; - } - getFunctions() { - return { - ...this.binaryVecFunctions(), - ...this.copyVec(), - ...this.setVecItem(), - ...this.getVecItem(), - }; - } - binaryVecFunctions() { - let t = this.context.outputTextureLayout.shape.length, - e = { add: '+=', sub: '-=', mul: '*=', div: '/=' }, - o = {}; - for (let i in e) { - let u = `${i}Vec`, - n = ''; - for (let d = 0; d < t; ++d) - n += ` - dest[${d}] ${e[i]} src[${d}]; - `; - let s = ` - void ${u}(int src[${t}], out int dest[${t}]) { - ${n} - } - `; - o[u] = new R(s); - } - return o; - } - copyVec() { - let t = this.context.outputTextureLayout.shape.length, - e = ''; - for (let i = 0; i < t; ++i) - e += ` - dest[${i}] = src[${i}]; - `; - let o = ` - void copyVec(int src[${t}], out int dest[${t}]) { - ${e} - } - `; - return { copyVec: new R(o) }; - } - setVecItem() { - let t = this.context.outputTextureLayout.shape.length, - e = ` - if(index < 0) - index =${t} + index; - if (index == 0) - m[0] = value; - `; - for (let i = 1; i < t - 1; ++i) - e += ` - else if (index == ${i}) - m[${i}] = value; - `; - e += ` - else - m[${t - 1}] = value; - `; - let o = ` - void setVecItem(out int m[${t}], int index, int value) { - ${e} - } - `; - return { setVecItem: new R(o) }; - } - getVecItem() { - let t = this.context.outputTextureLayout.shape.length, - e = ` - if(index < 0) - index = ${t} + index; - if (index == 0) - return m[0]; - `; - for (let i = 1; i < t - 1; ++i) - e += ` - else if (index == ${i}) - return m[${i}]; - `; - e += ` - else - return m[${t - 1}]; - `; - let o = ` - int getVecItem(int m[${t}], int index) { - ${e} - } - `; - return { getVecItem: new R(o) }; - } - }); - }), - qi, - op = L(() => { - Qc(), ep(), tp(), rp(), np(), (qi = { encoding: po, fragcolor: ho, vec: bo, shapeUtils: mo, coordinates: co }); - }), - go, - ip = L(() => { - Vt(), - Jc(), - op(), - xe(), - (go = class { - constructor(t, e, o, i) { - (this.libs = {}), - (this.glslLibRoutineDependencyGraph = {}), - (this.context = new eo(t, e, o, i)), - Object.keys(qi).forEach((n) => { - let s = new qi[n](this.context); - this.libs[n] = s; - }); - let u = this.glslLibRoutineDependencyGraph; - for (let n in this.libs) { - let s = this.libs[n].getFunctions(); - for (let d in s) { - let f = n + '.' + d, - r; - u[f] - ? ((r = u[f]), (r.routineBody = s[d].routineBody)) - : ((r = new cn(f, s[d].routineBody)), (u[f] = r)); - let a = s[d].dependencies; - if (a) - for (let l = 0; l < a.length; ++l) - if (u[a[l]]) r.addDependency(u[a[l]]); - else { - let p = new cn(a[l]); - (u[a[l]] = p), r.addDependency(p); - } - } - } - } - preprocess() { - let t = this.context.programInfo, - e = t.shaderSource; - return ( - this.context.programInfo.hasMain || - (e = `${e} - ${Ru(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`), - (e = Kc(e)), - `${Nu(this.context.glContext.version)} - ${this.getUniforms(t.inputNames, t.variables)} - ${this.getImports(e)} - ${e}` - ); - } - getImports(t) { - let e = this.selectGlslLibRoutinesToBeIncluded(t); - if (e.length === 0) return ''; - let o = ''; - for (let i = 0; i < e.length; ++i) - if (e[i].routineBody) - o += - e[i].routineBody + - ` -`; - else throw new Error(`Missing body for the Glsl Library routine: ${e[i].name}`); - return o; - } - selectGlslLibRoutinesToBeIncluded(t) { - let e = []; - return ( - Object.keys(this.glslLibRoutineDependencyGraph).forEach((o) => { - let i = o.split('.')[1]; - t.indexOf(i) !== -1 && e.push(this.glslLibRoutineDependencyGraph[o]); - }), - to.returnOrderedNodes(e) - ); - } - getUniforms(t, e) { - let o = []; - if (t) for (let i of t) o.push(`uniform sampler2D ${i};`); - if (e) - for (let i of e) - o.push(`uniform ${i.type} ${i.name}${i.arrayLength ? `[${i.arrayLength}]` : ''};`); - return o.join(` -`); - } - }); - }), - yo, - ap = L(() => { - vt(), - ut(), - ip(), - xe(), - (yo = class { - constructor(t, e, o) { - (this.profiler = t), - (this.glContext = e), - (this.textureLayoutStrategy = o), - (this.repo = new Map()), - (this.attributesBound = !1); - } - getArtifact(t) { - return this.repo.get(t); - } - setArtifact(t, e) { - this.repo.set(t, e); - } - run(t, e, o) { - this.profiler.event( - 'op', - `ProgramManager.run ${t.programInfo.name ?? 'unknown kernel'}`, - () => { - let i = this.glContext.gl, - u = t.program; - i.useProgram(u); - try { - this.bindOutput(o), - this.attributesBound || this.bindAttributes(t.attribLocations), - this.bindUniforms(t.uniformLocations, t.programInfo.variables ?? [], e); - } catch (n) { - throw (ce.error('ProgramManager', t.programInfo.shaderSource), n); - } - this.profiler.event('backend', 'GlContext.draw()', () => { - this.glContext.draw(); - }); - }, - this.glContext - ); - } - dispose() { - this.vertexShader && this.glContext.deleteShader(this.vertexShader), - this.repo.forEach((t) => this.glContext.deleteProgram(t.program)); - } - build(t, e, o) { - return this.profiler.event('backend', 'ProgramManager.build', () => { - let i = new go(this.glContext, t, e, o), - u = i.preprocess(), - n = this.compile(u); - return { - programInfo: t, - program: n, - uniformLocations: this.getUniformLocations( - n, - i.context.programInfo.inputNames, - i.context.programInfo.variables - ), - attribLocations: this.getAttribLocations(n), - }; - }); - } - compile(t) { - if (!this.vertexShader) { - ce.verbose('ProrgramManager', 'Compiling and caching Vertex shader for the first time'); - let i = Bu(this.glContext.version); - this.vertexShader = this.glContext.compileShader(i, this.glContext.gl.VERTEX_SHADER); - } - Z.debug && - ce.verbose( - 'ProrgramManager', - `FragShader: -${t} -` - ); - let e = this.glContext.compileShader(t, this.glContext.gl.FRAGMENT_SHADER), - o = this.glContext.createProgram(this.vertexShader, e); - return this.glContext.deleteShader(e), o; - } - bindOutput(t) { - let e = t.width, - o = t.height; - ce.verbose( - 'ProrgramManager', - `Binding output texture to Framebuffer: w/h=${e}/${o}, shape=${t.shape}, type=${t.tensor.type}` - ), - this.glContext.attachFramebuffer(t.texture, e, o); - } - bindAttributes(t) { - let e = t.position, - o = t.textureCoord; - this.glContext.setVertexAttributes(e, o), (this.attributesBound = !0); - } - bindUniforms(t, e, o) { - let i = this.glContext.gl, - u = 0; - for (let { name: n, type: s, location: d, arrayLength: f } of t) { - let r = e.find((a) => a.name === n)?.data; - if (s !== 'sampler2D' && !r) - throw new Error(`variable '${n}' does not have data defined in program info`); - switch (s) { - case 'sampler2D': - this.bindTexture(o[u], d, u), u++; - break; - case 'float': - f ? i.uniform1fv(d, r) : i.uniform1f(d, r); - break; - case 'int': - f ? i.uniform1iv(d, r) : i.uniform1i(d, r); - break; - default: - throw new Error(`Uniform not implemented: ${s}`); - } - } - } - bindTexture(t, e, o) { - this.glContext.bindTextureToUniform(t.texture, o, e); - } - getAttribLocations(t) { - return { - position: this.getAttribLocation(t, 'position'), - textureCoord: this.getAttribLocation(t, 'textureCoord'), - }; - } - getUniformLocations(t, e, o) { - let i = []; - if (e) - for (let u of e) - i.push({ name: u, type: 'sampler2D', location: this.getUniformLocation(t, u) }); - if (o) for (let u of o) i.push({ ...u, location: this.getUniformLocation(t, u.name) }); - return i; - } - getUniformLocation(t, e) { - let o = this.glContext.gl.getUniformLocation(t, e); - if (o === null) throw new Error(`Uniform ${e} not found.`); - return o; - } - getAttribLocation(t, e) { - return this.glContext.gl.getAttribLocation(t, e); - } - }); - }), - To, - sp = L(() => { - ut(), - ln(), - (To = class { - constructor(t, e, o, i) { - (this.glContext = t), - (this.layoutStrategy = e), - (this.profiler = o), - (this.config = i), - (this.pendingRead = new Map()), - i.reuseTextures && - ((this.inUseTextures = new Map()), - (this.idleTextures = new Map()), - (this.textureLookup = new Map())); - } - createTextureFromLayout(t, e, o, i) { - let u = this.toEncoderType(t), - n = this.glContext.getEncoder(u, e.channels || 1, i); - if (e.isPacked && i === 1) throw new Error('not implemented'); - let s = e.width, - d = e.height, - f, - r; - if (this.config.reuseTextures) { - (f = `${s}x${d}_${n.format}_${n.internalFormat}_${n.textureType}`), - (r = this.inUseTextures.get(f)), - r || ((r = []), this.inUseTextures.set(f, r)); - let l = this.idleTextures.get(f); - if (l && l.length > 0) { - let p = l.pop(); - return ( - r.push(p), - i === 1 && this.glContext.updateTexture(p, s, d, n, this.toTextureData(t, o)), - p - ); - } - } - ce.verbose('TextureManager', `Creating new texture of size ${e.width}x${e.height}`); - let a = this.glContext.allocateTexture(s, d, n, this.toTextureData(t, o)); - return this.config.reuseTextures && (r.push(a), this.textureLookup.set(a, f)), a; - } - readTexture(t, e, o) { - return ( - o || (o = 1), - this.profiler.event('backend', 'TextureManager.readTexture', () => { - let i = t.shape.reduce((n, s) => n * s) * o, - u = this.glContext.readTexture( - t.texture, - t.width, - t.height, - i, - this.toEncoderType(e), - o - ); - return this.toTensorData(e, u); - }) - ); - } - async readTextureAsync(t, e, o) { - let i = t.tensor.dataId; - if ((o || (o = 1), this.pendingRead.has(i))) { - let u = this.pendingRead.get(i); - return new Promise((n) => u?.push(n)); - } - return this.profiler.event('backend', 'TextureManager.readTextureAsync', async () => { - this.pendingRead.set(i, []); - let u = t.shape.reduce((f, r) => f * r) * o; - await this.glContext.createAndWaitForFence(); - let n = this.glContext.readTexture(t.texture, t.width, t.height, u, this.toEncoderType(e), o), - s = this.toTensorData(e, n), - d = this.pendingRead.get(i); - return this.pendingRead.delete(i), d?.forEach((f) => f(s)), s; - }); - } - readUint8TextureAsFloat(t) { - return this.profiler.event('backend', 'TextureManager.readUint8TextureAsFloat', () => { - let e = t.shape.reduce((i, u) => i * u), - o = this.glContext.readTexture(t.texture, t.width, t.height, e * 4, 'byte', 4); - return new Float32Array(o.buffer, o.byteOffset, e); - }); - } - releaseTexture(t, e) { - let o; - if (this.config.reuseTextures && ((o = this.textureLookup.get(t.texture)), o)) { - e && this.textureLookup.delete(o); - let i = this.inUseTextures.get(o); - if (i) { - let u = i.indexOf(t.texture); - if (u !== -1) { - i.splice(u, 1); - let n = this.idleTextures.get(o); - n || ((n = []), this.idleTextures.set(o, n)), n.push(t.texture); - } - } - } - (!o || e) && - (ce.verbose('TextureManager', `Deleting texture of size ${t.width}x${t.height}`), - this.glContext.deleteTexture(t.texture)); - } - toTensorData(t, e) { - switch (t) { - case 'int16': - return e instanceof Int16Array ? e : Int16Array.from(e); - case 'int32': - return e instanceof Int32Array ? e : Int32Array.from(e); - case 'int8': - return e instanceof Int8Array ? e : Int8Array.from(e); - case 'uint16': - return e instanceof Uint16Array ? e : Uint16Array.from(e); - case 'uint32': - return e instanceof Uint32Array ? e : Uint32Array.from(e); - case 'uint8': - case 'bool': - return e instanceof Uint8Array ? e : Uint8Array.from(e); - case 'float32': - return e instanceof Float32Array ? e : Float32Array.from(e); - case 'float64': - return e instanceof Float64Array ? e : Float64Array.from(e); - default: - throw new Error(`TensorData type ${t} is not supported`); - } - } - toTextureData(t, e) { - if (e) return e instanceof Float32Array ? e : new Float32Array(e); - } - toEncoderType(t) { - return 'float'; - } - clearActiveTextures() { - this.glContext.clearActiveTextures(); - } - }); - }), - xo, - up = L(() => { - ut(), - ws(), - Qu(), - Yc(), - ap(), - Hi(), - sp(), - (xo = class { - constructor(t, e) { - (this.backend = t), - (this.context = e), - (this.layoutStrategy = new fo(t.glContext.maxTextureSize)), - (this.programManager = new yo(this.context.profiler, t.glContext, this.layoutStrategy)), - (this.textureManager = new To(t.glContext, this.layoutStrategy, this.context.profiler, { - reuseTextures: t.textureCacheMode === 'full', - })), - (this.packedTextureDataCache = new Map()), - (this.unpackedTextureDataCache = new Map()), - (this.pack = t.pack), - (this.pack2unpackMap = new Map()), - (this.unpack2packMap = new Map()); - } - createInferenceHandler() { - return new Qn(this); - } - onGraphInitialized(t) { - let e = t - .getValues() - .filter((o) => o.from === -1 && o.tensor) - .map((o) => o.tensor.dataId); - this.initializers = new Set(e); - } - isInitializer(t) { - return this.initializers ? this.initializers.has(t) : !1; - } - addInitializer(t) { - this.initializers.add(t); - } - getTextureData(t, e) { - return e ? this.packedTextureDataCache.get(t) : this.unpackedTextureDataCache.get(t); - } - setTextureData(t, e, o = !1) { - ce.verbose('WebGLSessionHandler', 'Storing Texture data in cache'), - o ? this.packedTextureDataCache.set(t, e) : this.unpackedTextureDataCache.set(t, e); - } - dispose() { - this.programManager.dispose(), - this.textureManager.clearActiveTextures(), - this.packedTextureDataCache.forEach((t) => this.textureManager.releaseTexture(t, !0)), - (this.packedTextureDataCache = new Map()), - this.unpackedTextureDataCache.forEach((t) => this.textureManager.releaseTexture(t, !0)), - (this.unpackedTextureDataCache = new Map()); - } - resolve(t, e, o) { - let i = vs(t, e, jc); - return { impl: i.opImpl, context: i.opInit ? i.opInit(t, o) : t }; - } - }); - }); -function Hb(t) { - let e = 0; - for (; e < t.length && t[e](); ++e); - return e - 1; -} -var hn, - lp = L(() => { - vt(), - ln(), - ln(), - Ft(), - (hn = class { - constructor(t, e) { - (this.frameBufferBound = !1), - (this.itemsToPoll = []), - (this.gl = t), - (this.version = e), - this.getExtensions(), - (this.vertexbuffer = this.createVertexbuffer()), - (this.framebuffer = this.createFramebuffer()), - this.queryVitalParameters(); - } - allocateTexture(t, e, o, i) { - let u = this.gl, - n = u.createTexture(); - u.bindTexture(u.TEXTURE_2D, n), - u.texParameteri(u.TEXTURE_2D, u.TEXTURE_MIN_FILTER, u.NEAREST), - u.texParameteri(u.TEXTURE_2D, u.TEXTURE_MAG_FILTER, u.NEAREST), - u.texParameteri(u.TEXTURE_2D, u.TEXTURE_WRAP_S, u.CLAMP_TO_EDGE), - u.texParameteri(u.TEXTURE_2D, u.TEXTURE_WRAP_T, u.CLAMP_TO_EDGE); - let s = i ? o.encode(i, t * e) : null; - return ( - u.texImage2D(u.TEXTURE_2D, 0, o.internalFormat, t, e, 0, o.format, o.textureType, s), - this.checkError(), - n - ); - } - updateTexture(t, e, o, i, u) { - let n = this.gl; - n.bindTexture(n.TEXTURE_2D, t); - let s = i.encode(u, e * o); - n.texSubImage2D(n.TEXTURE_2D, 0, 0, 0, e, o, i.format, i.textureType, s), this.checkError(); - } - attachFramebuffer(t, e, o) { - let i = this.gl; - i.bindTexture(i.TEXTURE_2D, t), - i.bindFramebuffer(i.FRAMEBUFFER, this.framebuffer), - i.framebufferTexture2D(i.FRAMEBUFFER, i.COLOR_ATTACHMENT0, i.TEXTURE_2D, t, 0), - this.checkError(), - i.viewport(0, 0, e, o), - i.scissor(0, 0, e, o); - } - readTexture(t, e, o, i, u, n) { - let s = this.gl; - n || (n = 1), this.frameBufferBound || this.attachFramebuffer(t, e, o); - let d = this.getEncoder(u, n), - f = d.allocate(e * o); - return ( - s.bindTexture(s.TEXTURE_2D, t), - s.framebufferTexture2D(s.FRAMEBUFFER, s.COLOR_ATTACHMENT0, s.TEXTURE_2D, t, 0), - s.readPixels(0, 0, e, o, s.RGBA, d.textureType, f), - this.checkError(), - d.decode(f, i) - ); - } - isFramebufferReady() { - return !0; - } - getActiveTexture() { - let t = this.gl; - return `TEXTURE${t.getParameter(this.gl.ACTIVE_TEXTURE) - t.TEXTURE0}`; - } - getTextureBinding() { - return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D); - } - getFramebufferBinding() { - return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING); - } - setVertexAttributes(t, e) { - let o = this.gl; - o.vertexAttribPointer(t, 3, o.FLOAT, !1, 20, 0), - o.enableVertexAttribArray(t), - e !== -1 && (o.vertexAttribPointer(e, 2, o.FLOAT, !1, 20, 12), o.enableVertexAttribArray(e)), - this.checkError(); - } - createProgram(t, e) { - let o = this.gl, - i = o.createProgram(); - return o.attachShader(i, t), o.attachShader(i, e), o.linkProgram(i), i; - } - compileShader(t, e) { - let o = this.gl, - i = o.createShader(e); - if (!i) throw new Error(`createShader() returned null with type ${e}`); - if ((o.shaderSource(i, t), o.compileShader(i), o.getShaderParameter(i, o.COMPILE_STATUS) === !1)) - throw new Error(`Failed to compile shader: ${o.getShaderInfoLog(i)} -Shader source: -${t}`); - return i; - } - deleteShader(t) { - this.gl.deleteShader(t); - } - bindTextureToUniform(t, e, o) { - let i = this.gl; - i.activeTexture(i.TEXTURE0 + e), - this.checkError(), - i.bindTexture(i.TEXTURE_2D, t), - this.checkError(), - i.uniform1i(o, e), - this.checkError(); - } - draw() { - this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4), this.checkError(); - } - checkError() { - if (Z.debug) { - let t = this.gl, - e = t.getError(), - o = ''; - switch (e) { - case t.NO_ERROR: - return; - case t.INVALID_ENUM: - o = 'INVALID_ENUM'; - break; - case t.INVALID_VALUE: - o = 'INVALID_VALUE'; - break; - case t.INVALID_OPERATION: - o = 'INVALID_OPERATION'; - break; - case t.INVALID_FRAMEBUFFER_OPERATION: - o = 'INVALID_FRAMEBUFFER_OPERATION'; - break; - case t.OUT_OF_MEMORY: - o = 'OUT_OF_MEMORY'; - break; - case t.CONTEXT_LOST_WEBGL: - o = 'CONTEXT_LOST_WEBGL'; - break; - default: - o = `Unknown WebGL Error: ${e.toString(16)}`; - } - throw new Error(o); - } - } - deleteTexture(t) { - this.gl.deleteTexture(t); - } - deleteProgram(t) { - this.gl.deleteProgram(t); - } - getEncoder(t, e, o = 0) { - if (this.version === 2) return new Jn(this.gl, e); - switch (t) { - case 'float': - return o === 1 || this.isRenderFloat32Supported - ? new un(this.gl, e) - : new un(this.gl, e, this.textureHalfFloatExtension.HALF_FLOAT_OES); - case 'int': - throw new Error('not implemented'); - case 'byte': - return new Zn(this.gl, e); - default: - throw new Error(`Invalid dataType: ${t}`); - } - } - clearActiveTextures() { - let t = this.gl; - for (let e = 0; e < this.maxTextureImageUnits; ++e) - t.activeTexture(t.TEXTURE0 + e), t.bindTexture(t.TEXTURE_2D, null); - } - dispose() { - if (this.disposed) return; - let t = this.gl; - t.bindFramebuffer(t.FRAMEBUFFER, null), - t.deleteFramebuffer(this.framebuffer), - t.bindBuffer(t.ARRAY_BUFFER, null), - t.deleteBuffer(this.vertexbuffer), - t.bindBuffer(t.ELEMENT_ARRAY_BUFFER, null), - t.finish(), - (this.disposed = !0); - } - createDefaultGeometry() { - return new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]); - } - createVertexbuffer() { - let t = this.gl, - e = t.createBuffer(); - if (!e) throw new Error('createBuffer() returned null'); - let o = this.createDefaultGeometry(); - return ( - t.bindBuffer(t.ARRAY_BUFFER, e), - t.bufferData(t.ARRAY_BUFFER, o, t.STATIC_DRAW), - this.checkError(), - e - ); - } - createFramebuffer() { - let t = this.gl.createFramebuffer(); - if (!t) throw new Error('createFramebuffer returned null'); - return t; - } - queryVitalParameters() { - let t = this.gl; - if ( - ((this.isFloatTextureAttachableToFrameBuffer = this.checkFloatTextureAttachableToFrameBuffer()), - (this.isRenderFloat32Supported = this.checkRenderFloat32()), - (this.isFloat32DownloadSupported = this.checkFloat32Download()), - this.version === 1 && !this.textureHalfFloatExtension && !this.isRenderFloat32Supported) - ) - throw new Error('both float32 and float16 TextureType are not supported'); - (this.isBlendSupported = !this.isRenderFloat32Supported || this.checkFloat32Blend()), - (this.maxTextureSize = t.getParameter(t.MAX_TEXTURE_SIZE)), - (this.maxTextureImageUnits = t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)), - this.version; - } - getExtensions() { - this.version === 2 - ? ((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() { - let t = this.gl, - e = t.createTexture(); - t.bindTexture(t.TEXTURE_2D, e); - let o = this.version === 2 ? t.RGBA32F : t.RGBA; - t.texImage2D(t.TEXTURE_2D, 0, o, 1, 1, 0, t.RGBA, t.FLOAT, null); - let i = t.createFramebuffer(); - t.bindFramebuffer(t.FRAMEBUFFER, i), - t.framebufferTexture2D(t.FRAMEBUFFER, t.COLOR_ATTACHMENT0, t.TEXTURE_2D, e, 0); - let u = t.checkFramebufferStatus(t.FRAMEBUFFER) === t.FRAMEBUFFER_COMPLETE; - return ( - t.bindTexture(t.TEXTURE_2D, null), - t.bindFramebuffer(t.FRAMEBUFFER, null), - t.deleteTexture(e), - t.deleteFramebuffer(i), - u - ); - } - checkRenderFloat32() { - if (this.version === 2) { - if (!this.colorBufferFloatExtension) return !1; - } else if (!this.textureFloatExtension) return !1; - return this.isFloatTextureAttachableToFrameBuffer; - } - checkFloat32Download() { - if (this.version === 2) { - if (!this.colorBufferFloatExtension) return !1; - } else if (!this.textureFloatExtension || !this.gl.getExtension('WEBGL_color_buffer_float')) - return !1; - return this.isFloatTextureAttachableToFrameBuffer; - } - checkFloat32Blend() { - let t = this.gl, - e, - o, - i, - u, - n; - try { - (e = t.createTexture()), (o = t.createFramebuffer()), t.bindTexture(t.TEXTURE_2D, e); - let s = this.version === 2 ? t.RGBA32F : t.RGBA; - return ( - t.texImage2D(t.TEXTURE_2D, 0, s, 1, 1, 0, t.RGBA, t.FLOAT, null), - t.bindFramebuffer(t.FRAMEBUFFER, o), - t.framebufferTexture2D(t.FRAMEBUFFER, t.COLOR_ATTACHMENT0, t.TEXTURE_2D, e, 0), - t.enable(t.BLEND), - (i = t.createShader(t.VERTEX_SHADER)), - !i || - (t.shaderSource(i, 'void main(){}'), - t.compileShader(i), - (u = t.createShader(t.FRAGMENT_SHADER)), - !u) || - (t.shaderSource(u, 'precision highp float;void main(){gl_FragColor=vec4(0.5);}'), - t.compileShader(u), - (n = t.createProgram()), - !n) - ? !1 - : (t.attachShader(n, i), - t.attachShader(n, u), - t.linkProgram(n), - t.useProgram(n), - t.drawArrays(t.POINTS, 0, 1), - t.getError() === t.NO_ERROR) - ); - } finally { - t.disable(t.BLEND), - n && t.deleteProgram(n), - i && t.deleteShader(i), - u && t.deleteShader(u), - o && (t.bindFramebuffer(t.FRAMEBUFFER, null), t.deleteFramebuffer(o)), - e && (t.bindTexture(t.TEXTURE_2D, null), t.deleteTexture(e)); - } - } - beginTimer() { - if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { - let t = this.gl, - e = this.disjointTimerQueryWebgl2Extension, - o = t.createQuery(); - return t.beginQuery(e.TIME_ELAPSED_EXT, o), o; - } else throw new Error('WebGL1 profiling currently not supported.'); - } - endTimer() { - if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { - let t = this.gl, - e = this.disjointTimerQueryWebgl2Extension; - t.endQuery(e.TIME_ELAPSED_EXT); - return; - } else throw new Error('WebGL1 profiling currently not supported'); - } - isTimerResultAvailable(t) { - let e = !1, - o = !1; - if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { - let i = this.gl, - u = this.disjointTimerQueryWebgl2Extension; - (e = i.getQueryParameter(t, i.QUERY_RESULT_AVAILABLE)), - (o = i.getParameter(u.GPU_DISJOINT_EXT)); - } else throw new Error('WebGL1 profiling currently not supported'); - return e && !o; - } - getTimerResult(t) { - let e = 0; - if (this.version === 2) { - let o = this.gl; - (e = o.getQueryParameter(t, o.QUERY_RESULT)), o.deleteQuery(t); - } else throw new Error('WebGL1 profiling currently not supported'); - return e / 1e6; - } - async waitForQueryAndGetTime(t) { - return await gi(() => this.isTimerResultAvailable(t)), this.getTimerResult(t); - } - async createAndWaitForFence() { - let t = this.createFence(this.gl); - return this.pollFence(t); - } - createFence(t) { - let e, - o = t, - i = o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE, 0); - return ( - t.flush(), - i === null - ? (e = () => !0) - : (e = () => { - let u = o.clientWaitSync(i, 0, 0); - return u === o.ALREADY_SIGNALED || u === o.CONDITION_SATISFIED; - }), - { query: i, isFencePassed: e } - ); - } - async pollFence(t) { - return new Promise((e) => { - this.addItemToPoll( - () => t.isFencePassed(), - () => e() - ); - }); - } - pollItems() { - let t = Hb(this.itemsToPoll.map((e) => e.isDoneFn)); - for (let e = 0; e <= t; ++e) { - let { resolveFn: o } = this.itemsToPoll[e]; - o(); - } - this.itemsToPoll = this.itemsToPoll.slice(t + 1); - } - async addItemToPoll(t, e) { - this.itemsToPoll.push({ isDoneFn: t, resolveFn: e }), - !(this.itemsToPoll.length > 1) && - (await gi(() => (this.pollItems(), this.itemsToPoll.length === 0))); - } - }); - }); -function ji(t) { - let e; - if ( - ((!t || t === 'webgl2') && 'webgl2' in Ur - ? (e = Ur.webgl2) - : (!t || t === 'webgl') && 'webgl' in Ur && (e = Ur.webgl), - !e) - ) - try { - let i = jb(); - e = fp(i, t); - } catch { - let i = qb(); - e = fp(i, t); - } - t = t || e.version === 1 ? 'webgl' : 'webgl2'; - let o = e.gl; - return ( - (Ur[t] = e), - o.isContextLost() - ? (delete Ur[t], ji(t)) - : (o.disable(o.DEPTH_TEST), - o.disable(o.STENCIL_TEST), - o.disable(o.BLEND), - o.disable(o.DITHER), - o.disable(o.POLYGON_OFFSET_FILL), - o.disable(o.SAMPLE_COVERAGE), - o.enable(o.SCISSOR_TEST), - o.enable(o.CULL_FACE), - o.cullFace(o.BACK), - e) - ); -} -function fp(t, e) { - let o = { - alpha: !1, - depth: !1, - antialias: !1, - stencil: !1, - preserveDrawingBuffer: !1, - premultipliedAlpha: !1, - failIfMajorPerformanceCaveat: !1, - }, - i, - u = o; - if ((!e || e === 'webgl2') && ((i = t.getContext('webgl2', u)), i)) - try { - return new hn(i, 2); - } catch (n) { - ce.warning('GlContextFactory', `failed to create WebGLContext using contextId 'webgl2'. Error: ${n}`); - } - if ((!e || e === 'webgl') && ((i = t.getContext('webgl', u) || t.getContext('experimental-webgl', u)), i)) - try { - return new hn(i, 1); - } catch (n) { - ce.warning( - 'GlContextFactory', - `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${n}` - ); - } - throw new Error('WebGL is not supported'); -} -function qb() { - if (typeof document > 'u') throw new TypeError('failed to create canvas: document is not supported'); - let t = document.createElement('canvas'); - return (t.width = 1), (t.height = 1), t; -} -function jb() { - if (typeof OffscreenCanvas > 'u') - throw new TypeError('failed to create offscreen canvas: OffscreenCanvas is not supported'); - return new OffscreenCanvas(1, 1); -} -var Ur, - cp = L(() => { - ut(), lp(), (Ur = {}); - }), - vo, - pp = L(() => { - vt(), - ut(), - up(), - cp(), - (vo = class { - get contextId() { - return Z.webgl.contextId; - } - set contextId(t) { - Z.webgl.contextId = t; - } - get matmulMaxBatchSize() { - return Z.webgl.matmulMaxBatchSize; - } - set matmulMaxBatchSize(t) { - Z.webgl.matmulMaxBatchSize = t; - } - get textureCacheMode() { - return Z.webgl.textureCacheMode; - } - set textureCacheMode(t) { - Z.webgl.textureCacheMode = t; - } - get pack() { - return Z.webgl.pack; - } - set pack(t) { - Z.webgl.pack = t; - } - get async() { - return Z.webgl.async; - } - set async(t) { - Z.webgl.async = t; - } - initialize() { - try { - return ( - (this.glContext = ji(this.contextId)), - typeof this.matmulMaxBatchSize != 'number' && (this.matmulMaxBatchSize = 16), - typeof this.textureCacheMode != 'string' && (this.textureCacheMode = 'full'), - typeof this.pack != 'boolean' && (this.pack = !1), - typeof this.async != 'boolean' && (this.async = !1), - ce.setWithEnv(Z), - Z.webgl.context || Object.defineProperty(Z.webgl, 'context', { value: this.glContext.gl }), - ce.verbose( - 'WebGLBackend', - `Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${ - this.matmulMaxBatchSize - }; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${ - this.async - }.` - ), - !0 - ); - } catch (t) { - return ce.warning('WebGLBackend', `Unable to initialize WebGLBackend. ${t}`), !1; - } - } - createSessionHandler(t) { - return new xo(this, t); - } - dispose() { - this.glContext.dispose(); - } - }); - }); -async function Yi(t) { - if (t) { - let e = typeof t == 'string' ? [t] : t; - for (let o of e) { - let i = dp.get(o); - if (i) return i; - let u = await Xb(o); - if (u) return u; - } - } else return Yi(['webgl']); - throw new Error('no available backend to use'); -} -async function Xb(t) { - let e = Yb; - if (typeof e[t] < 'u' && Kb(e[t])) { - let o = e[t], - i = o.initialize(); - if ((typeof i == 'object' && 'then' in i && (i = await i), i)) return dp.set(t, o), o; - } -} -function Kb(t) { - let e = t; - return ( - 'initialize' in e && - typeof e.initialize == 'function' && - 'createSessionHandler' in e && - typeof e.createSessionHandler == 'function' && - 'dispose' in e && - typeof e.dispose == 'function' - ); -} -var dp, - Yb, - hp = L(() => { - pp(), (dp = new Map()), (Yb = { webgl: new vo() }); - }), - Xi, - wo, - mp = L(() => { - ut(), - (Xi = class { - constructor(t, e) { - (this.op = t), (this.node = e); - } - }), - (wo = class { - constructor(t, e, o) { - (this.graph = t), (this.profiler = o), this.initialize(e); - } - initialize(t) { - this.profiler.event('session', 'ExecutionPlan.initialize', () => { - let e = this.graph.getNodes(); - if (e.length !== t.length) throw new Error('The size of nodes and OPs do not match.'); - (this._ops = t.map((o, i) => new Xi(o, e[i]))), - this.reset(), - (this._starter = []), - this._ops.forEach((o, i) => { - let u = !0; - for (let n of o.node.inputs) - if (!this._values[n] && this.graph.getInputIndices().indexOf(n) === -1) { - u = !1; - break; - } - u && this._starter.push(i); - }); - }); - } - reset() { - this._values = this.graph.getValues().map((t) => t.tensor); - } - async execute(t, e) { - return this.profiler.event('session', 'ExecutionPlan.execute', async () => { - this.reset(); - let o = t.createInferenceHandler(), - i = this.graph.getInputIndices(); - if (e.length !== i.length) - throw new Error( - `number of input tensors don't match the number of inputs to the model: actual: ${e.length} expected: ${i.length}` - ); - e.forEach((r, a) => { - let l = i[a]; - this._values[l] = r; - }); - let u = this._starter.slice(0), - n = this.graph.getValues(), - s = this.graph.getNodes(), - d = 0; - for (; d < u.length; ) { - let r = u[d++], - a = this._ops[r], - l = a.node.inputs.map((T) => this._values[T]); - if (l.indexOf(void 0) !== -1) throw new Error(`unresolved input detected: op: ${a.node}`); - let p = l; - ce.verbose( - 'ExecPlan', - `Runing op:${a.node.name} (${p - .map((T, v) => `'${a.node.inputs[v]}': ${T.type}[${T.dims.join(',')}]`) - .join(', ')})` - ); - let m = await this.profiler.event('node', a.node.name, async () => - a.op.impl(o, p, a.op.context) - ); - if (m.length !== a.node.outputs.length) - throw new Error('the size of output does not match model definition.'); - m.forEach((T, v) => { - let S = a.node.outputs[v]; - if (this._values[S]) - throw new Error(`output [${S}] already has value: op:${a.node.name}`); - this._values[S] = T; - }); - let y = new Set(); - m.forEach((T, v) => { - let S = a.node.outputs[v]; - for (let E of n[S].to) { - let A = s[E], - F = !0; - for (let B of A.inputs) - if (!this._values[B]) { - F = !1; - break; - } - F && y.add(E); - } - }), - u.push(...y); - } - let f = []; - for (let r = 0; r < this.graph.getOutputIndices().length; r++) { - let a = this.graph.getOutputIndices()[r], - l = this._values[a]; - if (l === void 0) throw new Error(`required output [${a}] does not have value`); - a === 0 ? await l.getData() : l.data, f.push(l); - } - return ce.verbose('ExecPlan', 'disposing of inferenceHandler'), o.dispose(), f; - }); - } - }); - }), - oe, - mt, - mn, - bp = L(() => { - tn(), - (oe = Er($r())), - mr(), - fe(), - (mt = W.experimental.fbs), - (mn = class vr { - constructor(e) { - if (((this._attributes = new Map()), e != null)) { - for (let o of e) - o instanceof oe.onnx.AttributeProto - ? this._attributes.set(o.name, [vr.getValue(o), vr.getType(o)]) - : o instanceof mt.Attribute && - this._attributes.set(o.name(), [vr.getValue(o), vr.getType(o)]); - if (this._attributes.size < e.length) throw new Error('duplicated attribute names'); - } - } - set(e, o, i) { - this._attributes.set(e, [i, o]); - } - delete(e) { - this._attributes.delete(e); - } - getFloat(e, o) { - return this.get(e, 'float', o); - } - getInt(e, o) { - return this.get(e, 'int', o); - } - getString(e, o) { - return this.get(e, 'string', o); - } - getTensor(e, o) { - return this.get(e, 'tensor', o); - } - getFloats(e, o) { - return this.get(e, 'floats', o); - } - getInts(e, o) { - return this.get(e, 'ints', o); - } - getStrings(e, o) { - return this.get(e, 'strings', o); - } - getTensors(e, o) { - return this.get(e, 'tensors', o); - } - get(e, o, i) { - let u = this._attributes.get(e); - if (u === void 0) { - if (i !== void 0) return i; - throw new Error(`required attribute not found: ${e}`); - } - if (u[1] !== o) throw new Error(`type mismatch: expected ${o} but got ${u[1]}`); - return u[0]; - } - static getType(e) { - let o = e instanceof oe.onnx.AttributeProto ? e.type : e.type(); - switch (o) { - case oe.onnx.AttributeProto.AttributeType.FLOAT: - return 'float'; - case oe.onnx.AttributeProto.AttributeType.INT: - return 'int'; - case oe.onnx.AttributeProto.AttributeType.STRING: - return 'string'; - case oe.onnx.AttributeProto.AttributeType.TENSOR: - return 'tensor'; - case oe.onnx.AttributeProto.AttributeType.FLOATS: - return 'floats'; - case oe.onnx.AttributeProto.AttributeType.INTS: - return 'ints'; - case oe.onnx.AttributeProto.AttributeType.STRINGS: - return 'strings'; - case oe.onnx.AttributeProto.AttributeType.TENSORS: - return 'tensors'; - default: - throw new Error( - `attribute type is not supported yet: ${oe.onnx.AttributeProto.AttributeType[o]}` - ); - } - } - static getValue(e) { - let o = e instanceof oe.onnx.AttributeProto ? e.type : e.type(); - if ( - o === oe.onnx.AttributeProto.AttributeType.GRAPH || - o === oe.onnx.AttributeProto.AttributeType.GRAPHS - ) - throw new Error('graph attribute is not supported yet'); - let i = this.getValueNoCheck(e); - if (o === oe.onnx.AttributeProto.AttributeType.INT && nt.isLong(i)) return nt.longToNumber(i); - if (o === oe.onnx.AttributeProto.AttributeType.INTS) { - let u = i, - n = new Array(u.length); - for (let s = 0; s < u.length; s++) { - let d = u[s]; - n[s] = nt.longToNumber(d); - } - return n; - } - if (o === oe.onnx.AttributeProto.AttributeType.TENSOR) - return e instanceof oe.onnx.AttributeProto ? Fe.fromProto(i) : Fe.fromOrtTensor(i); - if (o === oe.onnx.AttributeProto.AttributeType.TENSORS) { - if (e instanceof oe.onnx.AttributeProto) return i.map((u) => Fe.fromProto(u)); - if (e instanceof mt.Attribute) return i.map((u) => Fe.fromOrtTensor(u)); - } - return o === oe.onnx.AttributeProto.AttributeType.STRING && e instanceof oe.onnx.AttributeProto - ? sn(i) - : o === oe.onnx.AttributeProto.AttributeType.STRINGS && e instanceof oe.onnx.AttributeProto - ? i.map(sn) - : i; - } - static getValueNoCheck(e) { - return e instanceof oe.onnx.AttributeProto - ? this.getValueNoCheckFromOnnxFormat(e) - : this.getValueNoCheckFromOrtFormat(e); - } - static getValueNoCheckFromOnnxFormat(e) { - switch (e.type) { - case oe.onnx.AttributeProto.AttributeType.FLOAT: - return e.f; - case oe.onnx.AttributeProto.AttributeType.INT: - return e.i; - case oe.onnx.AttributeProto.AttributeType.STRING: - return e.s; - case oe.onnx.AttributeProto.AttributeType.TENSOR: - return e.t; - case oe.onnx.AttributeProto.AttributeType.GRAPH: - return e.g; - case oe.onnx.AttributeProto.AttributeType.FLOATS: - return e.floats; - case oe.onnx.AttributeProto.AttributeType.INTS: - return e.ints; - case oe.onnx.AttributeProto.AttributeType.STRINGS: - return e.strings; - case oe.onnx.AttributeProto.AttributeType.TENSORS: - return e.tensors; - case oe.onnx.AttributeProto.AttributeType.GRAPHS: - return e.graphs; - default: - throw new Error( - `unsupported attribute type: ${oe.onnx.AttributeProto.AttributeType[e.type]}` - ); - } - } - static getValueNoCheckFromOrtFormat(e) { - switch (e.type()) { - case mt.AttributeType.FLOAT: - return e.f(); - case mt.AttributeType.INT: - return e.i(); - case mt.AttributeType.STRING: - return e.s(); - case mt.AttributeType.TENSOR: - return e.t(); - case mt.AttributeType.GRAPH: - return e.g(); - case mt.AttributeType.FLOATS: - return e.floatsArray(); - case mt.AttributeType.INTS: { - let o = []; - for (let i = 0; i < e.intsLength(); i++) o.push(e.ints(i)); - return o; - } - case mt.AttributeType.STRINGS: { - let o = []; - for (let i = 0; i < e.stringsLength(); i++) o.push(e.strings(i)); - return o; - } - case mt.AttributeType.TENSORS: { - let o = []; - for (let i = 0; i < e.tensorsLength(); i++) o.push(e.tensors(i)); - return o; - } - default: - throw new Error(`unsupported attribute type: ${mt.AttributeType[e.type()]}`); - } - } - }); - }), - Ji, - _o, - Zi, - kt, - Oo, - Ki, - gp = L(() => { - bp(), - tn(), - (Ji = Er($r())), - mr(), - fe(), - (_o = W.experimental.fbs), - (Zi = { from: (t, e) => new Ki(t, e) }), - (kt = class { - constructor(t) { - (this._from = void 0), - (this._to = []), - (this.tensor = void 0), - (this.type = void 0), - t && (this.type = Ve.tensorValueTypeFromProto(t.type.tensorType)); - } - get from() { - return this._from; - } - get to() { - return this._to; - } - }), - (Oo = class { - constructor(t, e) { - t instanceof Ji.onnx.NodeProto - ? ((this.name = t.name), (this.opType = t.opType), (this.attributes = new mn(t.attribute))) - : t instanceof _o.Node && - ((this.name = e ?? t.name()), - (this.opType = t.opType()), - (this.attributes = new mn(Ve.tensorAttributesFromORTFormat(t)))), - (this.inputs = []), - (this.outputs = []), - (this.executeNode = !0); - } - }), - (Ki = class { - constructor(t, e) { - if (!t) throw new TypeError('graph is empty'); - this.buildGraph(t), this.transformGraph(e), this.checkIsAcyclic(); - } - getInputIndices() { - return this._allInputIndices; - } - getInputNames() { - return this._allInputNames; - } - getOutputIndices() { - return this._allOutputIndices; - } - getOutputNames() { - return this._allOutputNames; - } - getValues() { - return this._allData; - } - getNodes() { - return this._nodes; - } - buildGraph(t) { - if (t instanceof Ji.onnx.GraphProto) this.buildGraphFromOnnxFormat(t); - else if (t instanceof _o.Graph) this.buildGraphFromOrtFormat(t); - else throw new TypeError('Graph type is not supported.'); - } - buildGraphFromOnnxFormat(t) { - let e = new Map(); - (this._allData = []), - (this._allInputIndices = []), - (this._allInputNames = []), - (this._allOutputIndices = []), - (this._allOutputNames = []), - (this._nodes = []); - let o = new Map(); - if (!t.input) throw new Error('missing information in graph: input'); - let i = []; - for (let u of t.input) { - if (e.has(u.name)) throw new Error(`duplicated input name: ${u.name}`); - let n = this._allData.push(new kt(u)) - 1; - e.set(u.name, n), i.push(u.name); - } - if (!t.initializer) throw new Error('missing information in graph: initializer'); - for (let u of t.initializer) { - let n = e.get(u.name); - if (n === void 0) { - let s = new kt(); - (s.type = { - shape: { dims: Ve.tensorDimsFromProto(u.dims) }, - tensorType: Ve.tensorDataTypeFromProto(u.dataType), - }), - (n = this._allData.push(s) - 1), - e.set(u.name, n); - } - (this._allData[n]._from = -1), (this._allData[n].tensor = Fe.fromProto(u)); - } - for (let u = 0; u < this._allData.length; u++) - this._allData[u].tensor || (this._allInputIndices.push(u), this._allInputNames.push(i[u])); - if (!t.output) throw new Error('missing information in graph: output'); - for (let u of t.output) { - if (e.has(u.name)) throw new Error(`duplicated output name: ${u.name}`); - let n = this._allData.push(new kt(u)) - 1; - e.set(u.name, n), this._allOutputIndices.push(n), this._allOutputNames.push(u.name); - } - if (!t.node) throw new Error('missing information in graph: node'); - for (let u of t.node) { - if (!u.name) - for (let s = 0; ; s++) { - let d = `unnamed_${u.opType}_${s}`; - if (!o.has(d)) { - u.name = d; - break; - } - } - if (o.has(u.name)) throw new Error(`duplicated node name: ${u.name}`); - let n = this._nodes.push(new Oo(u)) - 1; - o.set(u.name, n); - } - for (let u = 0; u < this._nodes.length; u++) { - let n = this._nodes[u], - s = t.node[u]; - if (!s.output) throw new Error(`missing output for node: ${s.name}`); - for (let d of s.output) { - let f = e.get(d); - if ( - (typeof f > 'u' && ((f = this._allData.push(new kt()) - 1), e.set(d, f)), - n.outputs.push(f), - this._allData[f]._from !== void 0) - ) - throw new Error(`multiple nodes output to one data value: ${f}`); - if (((this._allData[f]._from = u), s.opType === 'Constant')) { - if (!s.attribute || s.attribute.length !== 1 || !s.attribute[0].t) - throw new Error( - 'missing attributes or missing tensor value in attributes for this Constant operator' - ); - if (!s.output || s.output.length !== 1) - throw new Error( - 'missing output or incorrect number of outputs for this Constant operator' - ); - n.outputs.pop(), - (n.executeNode = !1), - (this._allData[f]._from = -1), - (this._allData[f].tensor = Fe.fromProto(s.attribute[0].t)); - } - } - } - for (let u = 0; u < this._nodes.length; u++) { - let n = this._nodes[u], - s = t.node[u]; - if (!s.input) throw new Error(`missing input for node: ${s.name}`); - for (let d of s.input) { - let f = e.get(d); - if (typeof f > 'u') { - if (d === '' && (s.input.length === 3 || s.input.length === 4) && s.opType === 'Resize') - continue; - throw new Error(`unrecognized input '${d}' for node: ${s.name}`); - } - n.inputs.push(f), this._allData[f]._to.push(u); - } - } - return !0; - } - buildGraphFromOrtFormat(t) { - let e = new Map(); - (this._allData = []), - (this._allInputIndices = []), - (this._allInputNames = []), - (this._allOutputIndices = []), - (this._allOutputNames = []), - (this._nodes = []); - let o = new Map(), - i = []; - for (let u = 0; u < t.inputsLength(); u++) { - let n = t.inputs(u); - if (e.has(n)) throw new Error(`duplicated input name: ${n}`); - for (let s = 0; s < t.nodeArgsLength(); s++) - if (t.nodeArgs(s)?.name() === n) { - let d = new kt(); - if (t.nodeArgs(s)?.type()?.valueType() !== _o.TypeInfoValue.tensor_type) - throw new Error('Unexpected value type for the nodeArg.'); - let f = t.nodeArgs(s).type().value(new _o.TensorTypeAndShape()), - r = Ve.tensorDataTypeFromProto(f.elemType()), - a = f.shape(), - l = []; - for (let m = 0; m < a.dimLength(); m++) - l.push(nt.longToNumber(a.dim(m).value().dimValue())); - d.type = { shape: { dims: l }, tensorType: r }; - let p = this._allData.push(d) - 1; - e.set(n, p), i.push(n); - } - } - for (let u = 0; u < t.initializersLength(); u++) { - let n = t.initializers(u), - s = e.get(n.name()); - if (s === void 0) { - let d = new kt(), - f = Ve.tensorDimsFromORTFormat(n), - r = Ve.tensorDataTypeFromProto(n.dataType()); - (d.type = { shape: { dims: f }, tensorType: r }), - (s = this._allData.push(d) - 1), - e.set(n.name(), s); - } - (this._allData[s]._from = -1), (this._allData[s].tensor = Fe.fromOrtTensor(n)); - } - for (let u = 0; u < this._allData.length; u++) - this._allData[u].tensor || (this._allInputIndices.push(u), this._allInputNames.push(i[u])); - for (let u = 0; u < t.outputsLength(); u++) { - let n = t.outputs(u); - if (e.has(n)) throw new Error(`duplicated output name: ${n}`); - let s = this._allData.push(new kt()) - 1; - e.set(n, s), this._allOutputIndices.push(s), this._allOutputNames.push(n); - } - if (!t.nodes) throw new Error('missing information in graph: node'); - for (let u = 0; u < t.nodesLength(); u++) { - let n = t.nodes(u), - s = n.name(); - if (!s) for (let f = 0; (s = `unnamed_${n.opType()}_${f}`), !!o.has(s); f++); - if (o.has(s)) throw new Error(`duplicated node name: ${s}`); - let d = this._nodes.push(new Oo(n, s)) - 1; - o.set(s, d); - } - for (let u = 0; u < this._nodes.length; u++) { - let n = this._nodes[u], - s = t.nodes(u); - if (s == null) throw new Error(`No node exists at index ${u}`); - if (s?.outputsLength() === 0) throw new Error(`missing output for node: ${s.name}`); - for (let d = 0; d < s?.outputsLength(); d++) { - let f = s?.outputs(d), - r = e.get(f); - if ( - (typeof r > 'u' && ((r = this._allData.push(new kt()) - 1), e.set(f, r)), - n.outputs.push(r), - this._allData[r]._from !== void 0) - ) - throw new Error(`multiple nodes output to one data value: ${r}`); - if (((this._allData[r]._from = u), s.opType() === 'Constant')) { - if (s.attributesLength() !== 1 || !s.attributes(0).t()) - throw new Error( - 'missing attributes or missing tensor value in attributes for this Constant operator' - ); - if (s.outputsLength() !== 1) - throw new Error( - 'missing output or incorrect number of outputs for this Constant operator' - ); - n.outputs.pop(), - (n.executeNode = !1), - (this._allData[r]._from = -1), - (this._allData[r].tensor = Fe.fromOrtTensor(s.attributes(0).t())); - } - } - } - for (let u = 0; u < this._nodes.length; u++) { - let n = this._nodes[u], - s = t.nodes(u); - if (s.inputsLength() === 0) throw new Error(`missing input for node: ${s.name}`); - for (let d = 0; d < s.inputsLength(); d++) { - let f = s.inputs(d), - r = e.get(f); - if (typeof r > 'u') throw new Error(`unrecognized input '${f}' for node: ${s.name()}`); - n.inputs.push(r), this._allData[r]._to.push(u); - } - } - } - checkIsAcyclic() { - let t = new Set(); - this._allInputIndices.forEach((i) => { - this._allData[i]._to.forEach((u) => { - t.add(u); - }); - }); - let e = Array.from(t), - o = new Array(this._nodes.length).fill('white'); - for (; e.length > 0; ) { - let i = e.pop(); - o[i] === 'gray' - ? (o[i] = 'black') - : (e.push(i), - (o[i] = 'gray'), - this._nodes[i].outputs.forEach((u) => { - let n = this._allData[u]; - if (typeof n.tensor < 'u') throw new Error('node outputs should not be initialized'); - if (n._from !== i) - throw new Error( - "from property of the Value object doesn't match index of Node being processed" - ); - n._to.forEach((s) => { - if (o[s] === 'gray') throw new Error('model graph is cyclic'); - o[s] === 'white' && e.push(s); - }); - })); - } - } - transformGraph(t) { - this.removeAllIdentityNodes(), - this.removeAllDropoutNodes(), - this.fuseConvActivationNodes(), - t && t.transformGraph(this), - this.finalizeGraph(); - } - finalizeGraph() { - let t = 0, - e = new Array(this._nodes.length, 0), - o = 0; - for (let i = 0; i < this._nodes.length; i++) - (e[i] = o), - this._nodes[i].executeNode - ? (o !== i && (this._nodes[o] = this._nodes[i]), o++) - : this._nodes[i].outputs.forEach((u) => { - this._allData[u]._from = -2; - }); - this._nodes.splice(o, this._nodes.length - o); - for (let i = 0; i < this._allData.length; i++) { - let u = this._allData[i]; - u._from !== void 0 && u._from !== -1 && u._from !== -2 && (u._from = e[u._from]); - for (let n = 0; n < u._to.length; n++) - if (u._to[n] >= 0) u._to[n] = e[u._to[n]]; - else throw new Error('Trying to update a removed node'); - } - t = 0; - for (let i = 0; i < this._allData.length; i++) { - if (this._allData[i].from === -2 && this._allOutputIndices.indexOf(i + t) === -1) { - t++, this._allData.splice(i, 1), i--; - continue; - } - if (t > 0) { - let u = -1; - this._allData[i].from !== void 0 && this._allData[i].from !== -1 - ? ((u = this._nodes[this._allData[i].from].outputs.indexOf(i + t)), - u !== -1 && (this._nodes[this._allData[i].from].outputs[u] = i)) - : ((u = this._allInputIndices.indexOf(i + t)), - u !== -1 && (this._allInputIndices[u] = i)), - this._allData[i].to.forEach((n) => { - (u = this._nodes[n].inputs.indexOf(i + t)), - u !== -1 && (this._nodes[n].inputs[u] = i); - }), - this._allData[i].to.length === 0 && - ((u = this._allOutputIndices.indexOf(i + t)), - u !== -1 && (this._allOutputIndices[u] = i)); - } - } - } - deleteNode(t) { - let e = this._nodes[t]; - if (e.outputs.length > 1) { - for (let s = 1; s < e.outputs.length; s++) - if (this._allData[e.outputs[s]].to.length > 0) - throw new Error( - 'Node deletion with more than one output connected to other nodes is not supported. ' - ); - } - e.executeNode = !1; - let o = e.inputs[0], - i = e.outputs[0], - u = this._allData[i].to; - for (let s = 0; s < e.inputs.length; s++) { - let d = this._allData[e.inputs[s]].to.indexOf(t); - if (d === -1) - throw new Error("The Value object doesn't have the current Node in it's 'to' property "); - this._allData[e.inputs[s]].to.splice(d, 1); - } - this._allData[i]._to = []; - let n = this._allOutputIndices.indexOf(i); - if ((n !== -1 && (this._allOutputIndices[n] = o), u && u.length > 0)) - for (let s of u) { - let d = this._nodes[s].inputs.indexOf(i); - if (d === -1) - throw new Error( - "The Node object doesn't have the output Value in it's 'inputs' property " - ); - (this._nodes[s].inputs[d] = o), this._allData[o].to.push(s); - } - } - removeAllDropoutNodes() { - let t = 0; - for (let e of this._nodes) { - if (e.opType === 'Dropout') { - if (e.inputs.length !== 1) throw new Error('Dropout nodes should only contain one input. '); - if (e.outputs.length !== 1 && e.outputs.length !== 2) - throw new Error('Dropout nodes should contain either 1 or 2 output(s)'); - if (e.outputs.length === 2 && this._allData[e.outputs[1]]._to.length !== 0) - throw new Error( - "Dropout nodes's second output should not be referenced by other nodes" - ); - this.deleteNode(t); - } - t++; - } - } - removeAllIdentityNodes() { - let t = 0; - for (let e of this._nodes) e.opType === 'Identity' && this.deleteNode(t), t++; - } - isActivation(t) { - switch (t.opType) { - case 'Relu': - case 'Sigmoid': - case 'Clip': - return !0; - default: - return !1; - } - } - fuseConvActivationNodes() { - for (let t of this._nodes) - if (t.opType === 'Conv') { - let e = this._allData[t.outputs[0]]._to; - if (e.length === 1 && this.isActivation(this._nodes[e[0]])) { - let o = this._nodes[e[0]]; - if (o.opType === 'Clip') - if (o.inputs.length === 1) - try { - t.attributes.set('activation_params', 'floats', [ - o.attributes.getFloat('min'), - o.attributes.getFloat('max'), - ]); - } catch { - t.attributes.set('activation_params', 'floats', [dr, hr]); - } - else if ( - o.inputs.length >= 3 && - this._allData[o.inputs[1]].tensor !== void 0 && - this._allData[o.inputs[2]].tensor !== void 0 - ) - t.attributes.set('activation_params', 'floats', [ - this._allData[o.inputs[1]].tensor.floatData[0], - this._allData[o.inputs[2]].tensor.floatData[0], - ]); - else continue; - t.attributes.set('activation', 'string', o.opType), this.deleteNode(e[0]); - } - } - } - }); - }), - yp, - Jb, - Io, - Tp = L(() => { - Wn(), - gp(), - tn(), - (yp = Er($r())), - fe(), - (Jb = W.experimental.fbs), - (Io = class { - constructor() {} - load(t, e, o) { - if (!o) - try { - this.loadFromOnnxFormat(t, e); - return; - } catch (i) { - if (o !== void 0) throw i; - } - this.loadFromOrtFormat(t, e); - } - loadFromOnnxFormat(t, e) { - let o = yp.onnx.ModelProto.decode(t); - if (nt.longToNumber(o.irVersion) < 3) throw new Error('only support ONNX model with IR_VERSION>=3'); - (this._opsets = o.opsetImport.map((i) => ({ - domain: i.domain, - version: nt.longToNumber(i.version), - }))), - (this._graph = Zi.from(o.graph, e)); - } - loadFromOrtFormat(t, e) { - let o = new _.ByteBuffer(t), - i = Jb.InferenceSession.getRootAsInferenceSession(o).model(); - if (nt.longToNumber(i.irVersion()) < 3) - throw new Error('only support ONNX model with IR_VERSION>=3'); - this._opsets = []; - for (let u = 0; u < i.opsetImportLength(); u++) { - let n = i.opsetImport(u); - this._opsets.push({ domain: n?.domain(), version: nt.longToNumber(n.version()) }); - } - this._graph = Zi.from(i.graph(), e); - } - get graph() { - return this._graph; - } - get opsets() { - return this._opsets; - } - }); - }), - So, - xp = L(() => { - hp(), - mp(), - ut(), - Tp(), - (So = class { - constructor(t = {}) { - (this._initialized = !1), - (this.backendHint = t.backendHint), - (this.profiler = zn.create(t.profiler)), - (this.context = { profiler: this.profiler, graphInputTypes: [], graphInputDims: [] }); - } - get inputNames() { - return this._model.graph.getInputNames(); - } - get outputNames() { - return this._model.graph.getOutputNames(); - } - startProfiling() { - this.profiler.start(); - } - endProfiling() { - this.profiler.stop(); - } - async loadModel(t, e, o) { - await this.profiler.event('session', 'Session.loadModel', async () => { - let i = await Yi(this.backendHint); - if ( - ((this.sessionHandler = i.createSessionHandler(this.context)), - (this._model = new Io()), - typeof t == 'string') - ) { - let u = t.endsWith('.ort'); - if (typeof process < 'u' && process.versions && process.versions.node) { - let n = await (void 0)(t); - this.initialize(n, u); - } else { - let n = await (await fetch(t)).arrayBuffer(); - this.initialize(new Uint8Array(n), u); - } - } else if (ArrayBuffer.isView(t)) this.initialize(t); - else { - let u = new Uint8Array(t, e || 0, o || t.byteLength); - this.initialize(u); - } - }); - } - initialize(t, e) { - if (this._initialized) throw new Error('already initialized'); - this.profiler.event('session', 'Session.initialize', () => { - let o = this.sessionHandler.transformGraph ? this.sessionHandler : void 0; - this._model.load(t, o, e), - this.sessionHandler.onGraphInitialized && - this.sessionHandler.onGraphInitialized(this._model.graph), - this.initializeOps(this._model.graph), - (this._executionPlan = new wo(this._model.graph, this._ops, this.profiler)); - }), - (this._initialized = !0); - } - async run(t) { - if (!this._initialized) throw new Error('session not initialized yet'); - return this.profiler.event('session', 'Session.run', async () => { - let e = this.normalizeAndValidateInputs(t), - o = await this._executionPlan.execute(this.sessionHandler, e); - return this.createOutput(o); - }); - } - normalizeAndValidateInputs(t) { - let e = this._model.graph.getInputNames(); - if (Array.isArray(t)) { - if (t.length !== e.length) - throw new Error(`incorrect input array length: expected ${e.length} but got ${t.length}`); - } else { - if (t.size !== e.length) - throw new Error(`incorrect input map size: expected ${e.length} but got ${t.size}`); - let o = new Array(t.size), - i = 0; - for (let u = 0; u < e.length; ++u) { - let n = t.get(e[u]); - if (!n) throw new Error(`missing input tensor for: '${name}'`); - o[i++] = n; - } - t = o; - } - if ( - !this.context.graphInputTypes || - this.context.graphInputTypes.length === 0 || - !this.context.graphInputDims || - this.context.graphInputDims.length === 0 - ) { - let o = this._model.graph.getInputIndices(), - i = this._model.graph.getValues(), - u = new Array(o.length); - for (let n = 0; n < o.length; ++n) { - let s = i[o[n]]; - (u[n] = s.type.shape.dims), - this.context.graphInputTypes.push(s.type.tensorType), - this.context.graphInputDims.push(t[n].dims); - } - this.validateInputTensorDims(u, t, !0); - } else this.validateInputTensorDims(this.context.graphInputDims, t, !1); - return this.validateInputTensorTypes(this.context.graphInputTypes, t), t; - } - validateInputTensorTypes(t, e) { - for (let o = 0; o < e.length; o++) { - let i = t[o], - u = e[o].type; - if (i !== u) - throw new Error(`input tensor[${o}] check failed: expected type '${i}' but got ${u}`); - } - } - validateInputTensorDims(t, e, o) { - for (let i = 0; i < e.length; i++) { - let u = t[i], - n = e[i].dims; - if (!this.compareTensorDims(u, n, o)) - throw new Error( - `input tensor[${i}] check failed: expected shape '[${u.join(',')}]' but got [${n.join( - ',' - )}]` - ); - } - } - compareTensorDims(t, e, o) { - if (t.length !== e.length) return !1; - for (let i = 0; i < t.length; ++i) if (t[i] !== e[i] && (!o || t[i] !== 0)) return !1; - return !0; - } - createOutput(t) { - let e = this._model.graph.getOutputNames(); - if (t.length !== e.length) - throw new Error('expected number of outputs do not match number of generated outputs'); - let o = new Map(); - for (let i = 0; i < e.length; ++i) o.set(e[i], t[i]); - return o; - } - initializeOps(t) { - let e = t.getNodes(); - this._ops = new Array(e.length); - for (let o = 0; o < e.length; o++) - this._ops[o] = this.sessionHandler.resolve(e[o], this._model.opsets, t); - } - }); - }), - Ao, - vp = L(() => { - vt(), - mr(), - (Ao = class { - constructor(t) { - (this.session = t), - (this.inputNames = this.session.inputNames), - (this.outputNames = this.session.outputNames); - } - async dispose() {} - async run(t, e, o) { - let i = new Map(); - for (let s in t) - if (Object.hasOwnProperty.call(t, s)) { - let d = t[s]; - i.set(s, new Fe(d.dims, d.type, void 0, void 0, d.data)); - } - let u = await this.session.run(i), - n = {}; - return ( - u.forEach((s, d) => { - n[d] = new Re(s.type, s.data, s.dims); - }), - n - ); - } - startProfiling() { - this.session.startProfiling(); - } - endProfiling() { - this.session.endProfiling(); - } - }); - }), - wp = {}; -Pr(wp, { onnxjsBackend: () => Qb }); -var Qi, - Qb, - _p = L(() => { - xp(), - vp(), - (Qi = class { - async init() {} - async createInferenceSessionHandler(t, e) { - let o = new So(e); - return typeof t == 'string' ? await o.loadModel(t) : await o.loadModel(t), new Ao(o); - } - }), - (Qb = new Qi()); - }), - ea = {}; -Pr(ea, { createReadStream: () => Op, readFile: () => eg, readFileSync: () => tg }); -var eg, - tg, - Op, - ta = L(() => { - (eg = void 0), (tg = void 0), (Op = void 0); - }), - ra = {}; -Pr(ra, { join: () => rg }); -var rg, - na = L(() => { - rg = void 0; - }), - Ap = me((t, e) => { - var o = (() => { - var i = typeof document < 'u' && document.currentScript ? document.currentScript.src : void 0; - return ( - typeof __filename < 'u' && (i = i || __filename), - function (u = {}) { - var n = u, - s, - d; - n.ready = new Promise((O, M) => { - (s = O), (d = M); - }); - var f = Object.assign({}, n), - r = './this.program', - a = typeof window == 'object', - l = typeof importScripts == 'function', - p = - typeof process == 'object' && - typeof process.versions == 'object' && - typeof process.versions.node == 'string', - m = '', - y, - T, - v; - if (p) { - var S = (ta(), rr(ea)), - E = (na(), rr(ra)); - (m = l ? E.dirname(m) + '/' : __dirname + '/'), - (y = (O, M) => ( - (O = ve(O) ? new URL(O) : E.normalize(O)), S.readFileSync(O, M ? void 0 : 'utf8') - )), - (v = (O) => ((O = y(O, !0)), O.buffer || (O = new Uint8Array(O)), O)), - (T = (O, M, I, k = !0) => { - (O = ve(O) ? new URL(O) : E.normalize(O)), - S.readFile(O, k ? void 0 : 'utf8', (G, ne) => { - G ? I(G) : M(k ? ne.buffer : ne); - }); - }), - !n.thisProgram && 1 < process.argv.length && (r = process.argv[1].replace(/\\/g, '/')), - process.argv.slice(2), - (n.inspect = () => '[Emscripten Module object]'); - } else - (a || l) && - (l - ? (m = self.location.href) - : typeof document < 'u' && document.currentScript && (m = document.currentScript.src), - i && (m = i), - m.indexOf('blob:') !== 0 - ? (m = m.substr(0, m.replace(/[?#].*/, '').lastIndexOf('/') + 1)) - : (m = ''), - (y = (O) => { - var M = new XMLHttpRequest(); - return M.open('GET', O, !1), M.send(null), M.responseText; - }), - l && - (v = (O) => { - var M = new XMLHttpRequest(); - return ( - M.open('GET', O, !1), - (M.responseType = 'arraybuffer'), - M.send(null), - new Uint8Array(M.response) - ); - }), - (T = (O, M, I) => { - var k = new XMLHttpRequest(); - k.open('GET', O, !0), - (k.responseType = 'arraybuffer'), - (k.onload = () => { - k.status == 200 || (k.status == 0 && k.response) ? M(k.response) : I(); - }), - (k.onerror = I), - k.send(null); - })); - var A = console.log.bind(console), - F = console.error.bind(console); - Object.assign(n, f), - (f = null), - typeof WebAssembly != 'object' && pe('no native wasm support detected'); - var B, - J = !1, - Q, - re, - V, - de, - ke; - function Ne() { - var O = B.buffer; - (n.HEAP8 = Q = new Int8Array(O)), - (n.HEAP16 = new Int16Array(O)), - (n.HEAPU8 = re = new Uint8Array(O)), - (n.HEAPU16 = new Uint16Array(O)), - (n.HEAP32 = V = new Int32Array(O)), - (n.HEAPU32 = de = new Uint32Array(O)), - (n.HEAPF32 = new Float32Array(O)), - (n.HEAPF64 = ke = new Float64Array(O)); - } - var Me = [], - Y = [], - _e = [], - he = 0, - ue = null; - function pe(O) { - throw ( - ((O = 'Aborted(' + O + ')'), - F(O), - (J = !0), - (O = new WebAssembly.RuntimeError(O + '. Build with -sASSERTIONS for more info.')), - d(O), - O) - ); - } - var X = (O) => O.startsWith('data:application/octet-stream;base64,'), - ve = (O) => O.startsWith('file://'), - we; - if (((we = 'ort-wasm.wasm'), !X(we))) { - var rt = we; - we = n.locateFile ? n.locateFile(rt, m) : m + rt; - } - function ot(O) { - if (v) return v(O); - throw 'both async and sync fetching of the wasm failed'; - } - function qe(O) { - if (a || l) { - if (typeof fetch == 'function' && !ve(O)) - return fetch(O, { credentials: 'same-origin' }) - .then((M) => { - if (!M.ok) throw "failed to load wasm binary file at '" + O + "'"; - return M.arrayBuffer(); - }) - .catch(() => ot(O)); - if (T) - return new Promise((M, I) => { - T(O, (k) => M(new Uint8Array(k)), I); - }); - } - return Promise.resolve().then(() => ot(O)); - } - function He(O, M, I) { - return qe(O) - .then((k) => WebAssembly.instantiate(k, M)) - .then((k) => k) - .then(I, (k) => { - F(`failed to asynchronously prepare wasm: ${k}`), pe(k); - }); - } - function Qe(O, M) { - var I = we; - return typeof WebAssembly.instantiateStreaming != 'function' || - X(I) || - ve(I) || - p || - typeof fetch != 'function' - ? He(I, O, M) - : fetch(I, { credentials: 'same-origin' }).then((k) => - WebAssembly.instantiateStreaming(k, O).then(M, function (G) { - return ( - F(`wasm streaming compile failed: ${G}`), - F('falling back to ArrayBuffer instantiation'), - He(I, O, M) - ); - }) - ); - } - var Be, - Ce = { - 919888: (O, M, I, k) => { - if (typeof n > 'u' || !n.za) return 1; - if ( - ((O = Mt(O >>> 0)), - O.startsWith('./') && (O = O.substring(2)), - (O = n.za.get(O)), - !O) - ) - return 2; - if (((M >>>= 0), (I >>>= 0), M + I > O.byteLength)) return 3; - try { - return re.set(O.subarray(M, M + I), (k >>> 0) >>> 0), 0; - } catch { - return 4; - } - }, - }; - function Se(O) { - (this.xa = O - 24), - (this.Ha = function (M) { - de[((this.xa + 4) >>> 2) >>> 0] = M; - }), - (this.Ga = function (M) { - de[((this.xa + 8) >>> 2) >>> 0] = M; - }), - (this.Aa = function (M, I) { - this.Fa(), this.Ha(M), this.Ga(I); - }), - (this.Fa = function () { - de[((this.xa + 16) >>> 2) >>> 0] = 0; - }); - } - var je = 0, - Tt = typeof TextDecoder < 'u' ? new TextDecoder('utf8') : void 0, - xt = (O, M, I) => { - M >>>= 0; - var k = M + I; - for (I = M; O[I] && !(I >= k); ) ++I; - if (16 < I - M && O.buffer && Tt) return Tt.decode(O.subarray(M, I)); - for (k = ''; M < I; ) { - var G = O[M++]; - if (G & 128) { - var ne = O[M++] & 63; - if ((G & 224) == 192) k += String.fromCharCode(((G & 31) << 6) | ne); - else { - var ge = O[M++] & 63; - (G = - (G & 240) == 224 - ? ((G & 15) << 12) | (ne << 6) | ge - : ((G & 7) << 18) | (ne << 12) | (ge << 6) | (O[M++] & 63)), - 65536 > G - ? (k += String.fromCharCode(G)) - : ((G -= 65536), - (k += String.fromCharCode(55296 | (G >> 10), 56320 | (G & 1023)))); - } - } else k += String.fromCharCode(G); - } - return k; - }, - Mt = (O, M) => ((O >>>= 0) ? xt(re, O, M) : ''), - Ot = (O) => { - for (var M = 0, I = 0; I < O.length; ++I) { - var k = O.charCodeAt(I); - 127 >= k - ? M++ - : 2047 >= k - ? (M += 2) - : 55296 <= k && 57343 >= k - ? ((M += 4), ++I) - : (M += 3); - } - return M; - }, - gt = (O, M, I, k) => { - if (((I >>>= 0), !(0 < k))) return 0; - var G = I; - k = I + k - 1; - for (var ne = 0; ne < O.length; ++ne) { - var ge = O.charCodeAt(ne); - if (55296 <= ge && 57343 >= ge) { - var Ue = O.charCodeAt(++ne); - ge = (65536 + ((ge & 1023) << 10)) | (Ue & 1023); - } - if (127 >= ge) { - if (I >= k) break; - M[I++ >>> 0] = ge; - } else { - if (2047 >= ge) { - if (I + 1 >= k) break; - M[I++ >>> 0] = 192 | (ge >> 6); - } else { - if (65535 >= ge) { - if (I + 2 >= k) break; - M[I++ >>> 0] = 224 | (ge >> 12); - } else { - if (I + 3 >= k) break; - (M[I++ >>> 0] = 240 | (ge >> 18)), (M[I++ >>> 0] = 128 | ((ge >> 12) & 63)); - } - M[I++ >>> 0] = 128 | ((ge >> 6) & 63); - } - M[I++ >>> 0] = 128 | (ge & 63); - } - } - return (M[I >>> 0] = 0), I - G; - }, - yt = (O) => O % 4 === 0 && (O % 100 !== 0 || O % 400 === 0), - Or = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], - Ht = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], - Sr = (O) => { - var M = Ot(O) + 1, - I = Gt(M); - return I && gt(O, re, I, M), I; - }, - st = [], - Bt = {}, - At = () => { - if (!It) { - var O = { - USER: 'web_user', - LOGNAME: 'web_user', - PATH: '/', - PWD: '/', - HOME: '/home/web_user', - LANG: - ( - (typeof navigator == 'object' && - navigator.languages && - navigator.languages[0]) || - 'C' - ).replace('-', '_') + '.UTF-8', - _: r || './this.program', - }, - M; - for (M in Bt) Bt[M] === void 0 ? delete O[M] : (O[M] = Bt[M]); - var I = []; - for (M in O) I.push(`${M}=${O[M]}`); - It = I; - } - return It; - }, - It, - Ar = [null, [], []], - Et = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], - Yt = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - function Ir(O) { - var M = Array(Ot(O) + 1); - return gt(O, M, 0, M.length), M; - } - function Dt(O, M, I, k) { - function G(C, Te, Ie) { - for (C = typeof C == 'number' ? C.toString() : C || ''; C.length < Te; ) C = Ie[0] + C; - return C; - } - function ne(C, Te) { - return G(C, Te, '0'); - } - function ge(C, Te) { - function Ie(lr) { - return 0 > lr ? -1 : 0 < lr ? 1 : 0; - } - var at; - return ( - (at = Ie(C.getFullYear() - Te.getFullYear())) === 0 && - (at = Ie(C.getMonth() - Te.getMonth())) === 0 && - (at = Ie(C.getDate() - Te.getDate())), - at - ); - } - function Ue(C) { - switch (C.getDay()) { - case 0: - return new Date(C.getFullYear() - 1, 11, 29); - case 1: - return C; - case 2: - return new Date(C.getFullYear(), 0, 3); - case 3: - return new Date(C.getFullYear(), 0, 2); - case 4: - return new Date(C.getFullYear(), 0, 1); - case 5: - return new Date(C.getFullYear() - 1, 11, 31); - case 6: - return new Date(C.getFullYear() - 1, 11, 30); - } - } - function et(C) { - var Te = C.ta; - for (C = new Date(new Date(C.ua + 1900, 0, 1).getTime()); 0 < Te; ) { - var Ie = C.getMonth(), - at = (yt(C.getFullYear()) ? Et : Yt)[Ie]; - if (Te > at - C.getDate()) - (Te -= at - C.getDate() + 1), - C.setDate(1), - 11 > Ie - ? C.setMonth(Ie + 1) - : (C.setMonth(0), C.setFullYear(C.getFullYear() + 1)); - else { - C.setDate(C.getDate() + Te); - break; - } - } - return ( - (Ie = new Date(C.getFullYear() + 1, 0, 4)), - (Te = Ue(new Date(C.getFullYear(), 0, 4))), - (Ie = Ue(Ie)), - 0 >= ge(Te, C) - ? 0 >= ge(Ie, C) - ? C.getFullYear() + 1 - : C.getFullYear() - : C.getFullYear() - 1 - ); - } - (O >>>= 0), (M >>>= 0), (I >>>= 0), (k >>>= 0); - var Ze = de[((k + 40) >>> 2) >>> 0]; - (k = { - Da: V[(k >>> 2) >>> 0], - Ca: V[((k + 4) >>> 2) >>> 0], - va: V[((k + 8) >>> 2) >>> 0], - ya: V[((k + 12) >>> 2) >>> 0], - wa: V[((k + 16) >>> 2) >>> 0], - ua: V[((k + 20) >>> 2) >>> 0], - oa: V[((k + 24) >>> 2) >>> 0], - ta: V[((k + 28) >>> 2) >>> 0], - Ia: V[((k + 32) >>> 2) >>> 0], - Ba: V[((k + 36) >>> 2) >>> 0], - Ea: Ze ? Mt(Ze) : '', - }), - (I = Mt(I)), - (Ze = { - '%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', - }); - for (var Je in Ze) I = I.replace(new RegExp(Je, 'g'), Ze[Je]); - var er = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'.split(' '), - tr = - 'January February March April May June July August September October November December'.split( - ' ' - ); - (Ze = { - '%a': (C) => er[C.oa].substring(0, 3), - '%A': (C) => er[C.oa], - '%b': (C) => tr[C.wa].substring(0, 3), - '%B': (C) => tr[C.wa], - '%C': (C) => ne(((C.ua + 1900) / 100) | 0, 2), - '%d': (C) => ne(C.ya, 2), - '%e': (C) => G(C.ya, 2, ' '), - '%g': (C) => et(C).toString().substring(2), - '%G': (C) => et(C), - '%H': (C) => ne(C.va, 2), - '%I': (C) => ((C = C.va), C == 0 ? (C = 12) : 12 < C && (C -= 12), ne(C, 2)), - '%j': (C) => { - for (var Te = 0, Ie = 0; Ie <= C.wa - 1; Te += (yt(C.ua + 1900) ? Et : Yt)[Ie++]); - return ne(C.ya + Te, 3); - }, - '%m': (C) => ne(C.wa + 1, 2), - '%M': (C) => ne(C.Ca, 2), - '%n': () => ` -`, - '%p': (C) => (0 <= C.va && 12 > C.va ? 'AM' : 'PM'), - '%S': (C) => ne(C.Da, 2), - '%t': () => ' ', - '%u': (C) => C.oa || 7, - '%U': (C) => ne(Math.floor((C.ta + 7 - C.oa) / 7), 2), - '%V': (C) => { - var Te = Math.floor((C.ta + 7 - ((C.oa + 6) % 7)) / 7); - if ((2 >= (C.oa + 371 - C.ta - 2) % 7 && Te++, Te)) - Te == 53 && - ((Ie = (C.oa + 371 - C.ta) % 7), Ie == 4 || (Ie == 3 && yt(C.ua)) || (Te = 1)); - else { - Te = 52; - var Ie = (C.oa + 7 - C.ta - 1) % 7; - (Ie == 4 || (Ie == 5 && yt((C.ua % 400) - 1))) && Te++; - } - return ne(Te, 2); - }, - '%w': (C) => C.oa, - '%W': (C) => ne(Math.floor((C.ta + 7 - ((C.oa + 6) % 7)) / 7), 2), - '%y': (C) => (C.ua + 1900).toString().substring(2), - '%Y': (C) => C.ua + 1900, - '%z': (C) => { - C = C.Ba; - var Te = 0 <= C; - return ( - (C = Math.abs(C) / 60), - (Te ? '+' : '-') + ('0000' + ((C / 60) * 100 + (C % 60))).slice(-4) - ); - }, - '%Z': (C) => C.Ea, - '%%': () => '%', - }), - (I = I.replace(/%%/g, '\0\0')); - for (Je in Ze) I.includes(Je) && (I = I.replace(new RegExp(Je, 'g'), Ze[Je](k))); - return ( - (I = I.replace(/\0\0/g, '%')), - (Je = Ir(I)), - Je.length > M ? 0 : (Q.set(Je, O >>> 0), Je.length - 1) - ); - } - var Zr = { - a: function (O, M, I) { - throw ((O >>>= 0), new Se(O).Aa(M >>> 0, I >>> 0), (je = O), je); - }, - e: function () { - return 0; - }, - H: function () {}, - x: function () {}, - z: function () {}, - J: function () { - return 0; - }, - F: function () {}, - A: function () {}, - E: function () {}, - g: function () {}, - y: function () {}, - v: function () {}, - G: function () {}, - w: function () {}, - k: () => 1, - n: function (O, M, I) { - (O = (M + 2097152) >>> 0 < 4194305 - !!O ? (O >>> 0) + 4294967296 * M : NaN), - (I >>>= 0), - (O = new Date(1e3 * O)), - (V[(I >>> 2) >>> 0] = O.getUTCSeconds()), - (V[((I + 4) >>> 2) >>> 0] = O.getUTCMinutes()), - (V[((I + 8) >>> 2) >>> 0] = O.getUTCHours()), - (V[((I + 12) >>> 2) >>> 0] = O.getUTCDate()), - (V[((I + 16) >>> 2) >>> 0] = O.getUTCMonth()), - (V[((I + 20) >>> 2) >>> 0] = O.getUTCFullYear() - 1900), - (V[((I + 24) >>> 2) >>> 0] = O.getUTCDay()), - (V[((I + 28) >>> 2) >>> 0] = - ((O.getTime() - Date.UTC(O.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5) | 0); - }, - o: function (O, M, I) { - (O = (M + 2097152) >>> 0 < 4194305 - !!O ? (O >>> 0) + 4294967296 * M : NaN), - (I >>>= 0), - (O = new Date(1e3 * O)), - (V[(I >>> 2) >>> 0] = O.getSeconds()), - (V[((I + 4) >>> 2) >>> 0] = O.getMinutes()), - (V[((I + 8) >>> 2) >>> 0] = O.getHours()), - (V[((I + 12) >>> 2) >>> 0] = O.getDate()), - (V[((I + 16) >>> 2) >>> 0] = O.getMonth()), - (V[((I + 20) >>> 2) >>> 0] = O.getFullYear() - 1900), - (V[((I + 24) >>> 2) >>> 0] = O.getDay()), - (V[((I + 28) >>> 2) >>> 0] = - ((yt(O.getFullYear()) ? Or : Ht)[O.getMonth()] + O.getDate() - 1) | 0), - (V[((I + 36) >>> 2) >>> 0] = -(60 * O.getTimezoneOffset())), - (M = new Date(O.getFullYear(), 6, 1).getTimezoneOffset()); - var k = new Date(O.getFullYear(), 0, 1).getTimezoneOffset(); - V[((I + 32) >>> 2) >>> 0] = (M != k && O.getTimezoneOffset() == Math.min(k, M)) | 0; - }, - p: function (O) { - O >>>= 0; - var M = new Date( - V[((O + 20) >>> 2) >>> 0] + 1900, - V[((O + 16) >>> 2) >>> 0], - V[((O + 12) >>> 2) >>> 0], - V[((O + 8) >>> 2) >>> 0], - V[((O + 4) >>> 2) >>> 0], - V[(O >>> 2) >>> 0], - 0 - ), - I = V[((O + 32) >>> 2) >>> 0], - k = M.getTimezoneOffset(), - G = new Date(M.getFullYear(), 6, 1).getTimezoneOffset(), - ne = new Date(M.getFullYear(), 0, 1).getTimezoneOffset(), - ge = Math.min(ne, G); - return ( - 0 > I - ? (V[((O + 32) >>> 2) >>> 0] = +(G != ne && ge == k)) - : 0 < I != (ge == k) && - ((G = Math.max(ne, G)), - M.setTime(M.getTime() + 6e4 * ((0 < I ? ge : G) - k))), - (V[((O + 24) >>> 2) >>> 0] = M.getDay()), - (V[((O + 28) >>> 2) >>> 0] = - ((yt(M.getFullYear()) ? Or : Ht)[M.getMonth()] + M.getDate() - 1) | 0), - (V[(O >>> 2) >>> 0] = M.getSeconds()), - (V[((O + 4) >>> 2) >>> 0] = M.getMinutes()), - (V[((O + 8) >>> 2) >>> 0] = M.getHours()), - (V[((O + 12) >>> 2) >>> 0] = M.getDate()), - (V[((O + 16) >>> 2) >>> 0] = M.getMonth()), - (V[((O + 20) >>> 2) >>> 0] = M.getYear()), - (O = M.getTime()), - isNaN(O) ? ((V[(Kt() >>> 2) >>> 0] = 61), (O = -1)) : (O /= 1e3), - Fr( - ((Be = O), - 1 <= +Math.abs(Be) - ? 0 < Be - ? +Math.floor(Be / 4294967296) >>> 0 - : ~~+Math.ceil((Be - +(~~Be >>> 0)) / 4294967296) >>> 0 - : 0) - ), - O >>> 0 - ); - }, - l: function () { - return -52; - }, - m: function () {}, - t: function (O, M, I) { - function k(et) { - return (et = et.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? et[1] : 'GMT'; - } - I >>>= 0; - var G = new Date().getFullYear(), - ne = new Date(G, 0, 1), - ge = new Date(G, 6, 1); - G = ne.getTimezoneOffset(); - var Ue = ge.getTimezoneOffset(); - (de[((O >>> 0) >>> 2) >>> 0] = 60 * Math.max(G, Ue)), - (V[((M >>> 0) >>> 2) >>> 0] = +(G != Ue)), - (O = k(ne)), - (M = k(ge)), - (O = Sr(O)), - (M = Sr(M)), - Ue < G - ? ((de[(I >>> 2) >>> 0] = O), (de[((I + 4) >>> 2) >>> 0] = M)) - : ((de[(I >>> 2) >>> 0] = M), (de[((I + 4) >>> 2) >>> 0] = O)); - }, - d: () => { - pe(''); - }, - B: function (O, M, I) { - (O >>>= 0), (M >>>= 0), (I >>>= 0), (st.length = 0); - for (var k; (k = re[M++ >>> 0]); ) { - var G = k != 105; - (G &= k != 112), - (I += G && I % 8 ? 4 : 0), - st.push( - k == 112 - ? de[(I >>> 2) >>> 0] - : k == 105 - ? V[(I >>> 2) >>> 0] - : ke[(I >>> 3) >>> 0] - ), - (I += G ? 8 : 4); - } - return Ce[O].apply(null, st); - }, - h: () => Date.now(), - u: function () { - return 4294901760; - }, - b: () => performance.now(), - I: function (O, M, I) { - return (M >>>= 0), re.copyWithin((O >>> 0) >>> 0, M >>> 0, (M + (I >>> 0)) >>> 0); - }, - s: function (O) { - O >>>= 0; - var M = re.length; - if (4294901760 < O) return !1; - for (var I = 1; 4 >= I; I *= 2) { - var k = M * (1 + 0.2 / I); - k = Math.min(k, O + 100663296); - var G = Math; - k = Math.max(O, k); - e: { - G = - (G.min.call(G, 4294901760, k + ((65536 - (k % 65536)) % 65536)) - - B.buffer.byteLength + - 65535) / - 65536; - try { - B.grow(G), Ne(); - var ne = 1; - break e; - } catch {} - ne = void 0; - } - if (ne) return !0; - } - return !1; - }, - C: function (O, M) { - (O >>>= 0), (M >>>= 0); - var I = 0; - return ( - At().forEach((k, G) => { - var ne = M + I; - for (G = de[((O + 4 * G) >>> 2) >>> 0] = ne, ne = 0; ne < k.length; ++ne) - Q[(G++ >>> 0) >>> 0] = k.charCodeAt(ne); - (Q[(G >>> 0) >>> 0] = 0), (I += k.length + 1); - }), - 0 - ); - }, - D: function (O, M) { - (O >>>= 0), (M >>>= 0); - var I = At(); - de[(O >>> 2) >>> 0] = I.length; - var k = 0; - return I.forEach((G) => (k += G.length + 1)), (de[(M >>> 2) >>> 0] = k), 0; - }, - f: () => 52, - j: function () { - return 52; - }, - q: function () { - return 70; - }, - i: function (O, M, I, k) { - (M >>>= 0), (I >>>= 0), (k >>>= 0); - for (var G = 0, ne = 0; ne < I; ne++) { - var ge = de[(M >>> 2) >>> 0], - Ue = de[((M + 4) >>> 2) >>> 0]; - M += 8; - for (var et = 0; et < Ue; et++) { - var Ze = re[(ge + et) >>> 0], - Je = Ar[O]; - Ze === 0 || Ze === 10 - ? ((O === 1 ? A : F)(xt(Je, 0)), (Je.length = 0)) - : Je.push(Ze); - } - G += Ue; - } - return (de[(k >>> 2) >>> 0] = G), 0; - }, - r: Dt, - c: function (O, M, I, k) { - return Dt(O >>> 0, M >>> 0, I >>> 0, k >>> 0); - }, - }, - H = (function () { - function O(I) { - return ( - (H = I.exports), - (H = Wt()), - (B = H.K), - Ne(), - Y.unshift(H.L), - he--, - he == 0 && ue && ((I = ue), (ue = null), I()), - H - ); - } - var M = { a: Zr }; - if ((he++, n.instantiateWasm)) - try { - return n.instantiateWasm(M, O); - } catch (I) { - F(`Module.instantiateWasm callback failed with error: ${I}`), d(I); - } - return ( - Qe(M, function (I) { - O(I.instance); - }).catch(d), - {} - ); - })(); - (n._OrtInit = (O, M) => (n._OrtInit = H.M)(O, M)), - (n._OrtGetLastError = (O, M) => (n._OrtGetLastError = H.N)(O, M)), - (n._OrtCreateSessionOptions = (O, M, I, k, G, ne, ge, Ue, et, Ze) => - (n._OrtCreateSessionOptions = H.O)(O, M, I, k, G, ne, ge, Ue, et, Ze)), - (n._OrtAppendExecutionProvider = (O, M) => (n._OrtAppendExecutionProvider = H.P)(O, M)), - (n._OrtAddFreeDimensionOverride = (O, M, I) => (n._OrtAddFreeDimensionOverride = H.Q)(O, M, I)), - (n._OrtAddSessionConfigEntry = (O, M, I) => (n._OrtAddSessionConfigEntry = H.R)(O, M, I)), - (n._OrtReleaseSessionOptions = (O) => (n._OrtReleaseSessionOptions = H.S)(O)), - (n._OrtCreateSession = (O, M, I) => (n._OrtCreateSession = H.T)(O, M, I)), - (n._OrtReleaseSession = (O) => (n._OrtReleaseSession = H.U)(O)), - (n._OrtGetInputOutputCount = (O, M, I) => (n._OrtGetInputOutputCount = H.V)(O, M, I)), - (n._OrtGetInputName = (O, M) => (n._OrtGetInputName = H.W)(O, M)), - (n._OrtGetOutputName = (O, M) => (n._OrtGetOutputName = H.X)(O, M)), - (n._OrtFree = (O) => (n._OrtFree = H.Y)(O)), - (n._OrtCreateTensor = (O, M, I, k, G, ne) => (n._OrtCreateTensor = H.Z)(O, M, I, k, G, ne)), - (n._OrtGetTensorData = (O, M, I, k, G) => (n._OrtGetTensorData = H._)(O, M, I, k, G)), - (n._OrtReleaseTensor = (O) => (n._OrtReleaseTensor = H.$)(O)), - (n._OrtCreateRunOptions = (O, M, I, k) => (n._OrtCreateRunOptions = H.aa)(O, M, I, k)), - (n._OrtAddRunConfigEntry = (O, M, I) => (n._OrtAddRunConfigEntry = H.ba)(O, M, I)), - (n._OrtReleaseRunOptions = (O) => (n._OrtReleaseRunOptions = H.ca)(O)), - (n._OrtCreateBinding = (O) => (n._OrtCreateBinding = H.da)(O)), - (n._OrtBindInput = (O, M, I) => (n._OrtBindInput = H.ea)(O, M, I)), - (n._OrtBindOutput = (O, M, I, k) => (n._OrtBindOutput = H.fa)(O, M, I, k)), - (n._OrtClearBoundOutputs = (O) => (n._OrtClearBoundOutputs = H.ga)(O)), - (n._OrtReleaseBinding = (O) => (n._OrtReleaseBinding = H.ha)(O)), - (n._OrtRunWithBinding = (O, M, I, k, G) => (n._OrtRunWithBinding = H.ia)(O, M, I, k, G)), - (n._OrtRun = (O, M, I, k, G, ne, ge, Ue) => (n._OrtRun = H.ja)(O, M, I, k, G, ne, ge, Ue)), - (n._OrtEndProfiling = (O) => (n._OrtEndProfiling = H.ka)(O)); - var Kt = () => (Kt = H.la)(), - Gt = (n._malloc = (O) => (Gt = n._malloc = H.ma)(O)); - n._free = (O) => (n._free = H.na)(O); - var Fr = (O) => (Fr = H.pa)(O), - Qt = () => (Qt = H.qa)(), - jr = (O) => (jr = H.ra)(O), - se = (O) => (se = H.sa)(O); - function Wt() { - var O = H; - O = Object.assign({}, O); - var M = (k) => () => k() >>> 0, - I = (k) => (G) => k(G) >>> 0; - return (O.la = M(O.la)), (O.ma = I(O.ma)), (O.qa = M(O.qa)), (O.sa = I(O.sa)), O; - } - (n.stackAlloc = se), - (n.stackSave = Qt), - (n.stackRestore = jr), - (n.UTF8ToString = Mt), - (n.stringToUTF8 = (O, M, I) => gt(O, re, M, I)), - (n.lengthBytesUTF8 = Ot); - var Nt; - ue = function O() { - Nt || Lt(), Nt || (ue = O); - }; - function Lt() { - if (!(0 < he)) { - if (n.preRun) - for (typeof n.preRun == 'function' && (n.preRun = [n.preRun]); n.preRun.length; ) { - var O = n.preRun.shift(); - Me.unshift(O); - } - for (; 0 < Me.length; ) Me.shift()(n); - if (!(0 < he || Nt || ((Nt = !0), (n.calledRun = !0), J))) { - for (; 0 < Y.length; ) Y.shift()(n); - for (s(n); 0 < _e.length; ) _e.shift()(n); - } - } - } - return Lt(), u.ready; - } - ); - })(); - typeof t == 'object' && typeof e == 'object' - ? (e.exports = o) - : typeof define == 'function' && define.amd && define([], () => o); - }), - Pp = me(() => {}), - Ep = me(() => {}), - Dp = {}; -Pr(Dp, { cpus: () => ng }); -var ng, - Lp = L(() => { - ng = void 0; - }), - Cp = me((t, e) => { - var o = (() => { - var i = typeof document < 'u' && document.currentScript ? document.currentScript.src : void 0; - return ( - typeof __filename < 'u' && (i = i || __filename), - function (u = {}) { - function n() { - return _e.buffer != X.buffer && qe(), X; - } - function s() { - return _e.buffer != X.buffer && qe(), ve; - } - function d() { - return _e.buffer != X.buffer && qe(), we; - } - function f() { - return _e.buffer != X.buffer && qe(), rt; - } - function r() { - return _e.buffer != X.buffer && qe(), ot; - } - var a = u, - l, - p; - a.ready = new Promise((g, x) => { - (l = g), (p = x); - }); - var m = Object.assign({}, a), - y = './this.program', - T = (g, x) => { - throw x; - }, - v = typeof window == 'object', - S = typeof importScripts == 'function', - E = - typeof process == 'object' && - typeof process.versions == 'object' && - typeof process.versions.node == 'string', - A = a.ENVIRONMENT_IS_PTHREAD || !1, - F = ''; - function B(g) { - return a.locateFile ? a.locateFile(g, F) : F + g; - } - var J, Q, re; - if (E) { - var V = (ta(), rr(ea)), - de = (na(), rr(ra)); - (F = S ? de.dirname(F) + '/' : __dirname + '/'), - (J = (x, P) => ( - (x = Ot(x) ? new URL(x) : de.normalize(x)), V.readFileSync(x, P ? void 0 : 'utf8') - )), - (re = (x) => ((x = J(x, !0)), x.buffer || (x = new Uint8Array(x)), x)), - (Q = (x, P, D, j = !0) => { - (x = Ot(x) ? new URL(x) : de.normalize(x)), - V.readFile(x, j ? void 0 : 'utf8', (z, K) => { - z ? D(z) : P(j ? K.buffer : K); - }); - }), - !a.thisProgram && 1 < process.argv.length && (y = process.argv[1].replace(/\\/g, '/')), - process.argv.slice(2), - (T = (x, P) => { - throw ((process.exitCode = x), P); - }), - (a.inspect = () => '[Emscripten Module object]'); - let g; - try { - g = Pp(); - } catch (x) { - throw ( - (console.error( - 'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?' - ), - x) - ); - } - global.Worker = g.Worker; - } else - (v || S) && - (S - ? (F = self.location.href) - : typeof document < 'u' && document.currentScript && (F = document.currentScript.src), - typeof i < 'u' && i && (F = i), - F.indexOf('blob:') !== 0 - ? (F = F.substr(0, F.replace(/[?#].*/, '').lastIndexOf('/') + 1)) - : (F = ''), - E || - ((J = (g) => { - var x = new XMLHttpRequest(); - return x.open('GET', g, !1), x.send(null), x.responseText; - }), - S && - (re = (g) => { - var x = new XMLHttpRequest(); - return ( - x.open('GET', g, !1), - (x.responseType = 'arraybuffer'), - x.send(null), - new Uint8Array(x.response) - ); - }), - (Q = (g, x, P) => { - var D = new XMLHttpRequest(); - D.open('GET', g, !0), - (D.responseType = 'arraybuffer'), - (D.onload = () => { - D.status == 200 || (D.status == 0 && D.response) ? x(D.response) : P(); - }), - (D.onerror = P), - D.send(null); - }))); - E && typeof performance > 'u' && (global.performance = Ep().performance); - var ke = console.log.bind(console), - Ne = console.error.bind(console); - E && - ((ke = (...g) => - V.writeSync( - 1, - g.join(' ') + - ` -` - )), - (Ne = (...g) => - V.writeSync( - 2, - g.join(' ') + - ` -` - ))); - var Me = ke, - Y = Ne; - Object.assign(a, m), - (m = null), - typeof WebAssembly != 'object' && xt('no native wasm support detected'); - var _e, - he, - ue = !1, - pe, - X, - ve, - we, - rt, - ot; - function qe() { - var g = _e.buffer; - (a.HEAP8 = X = new Int8Array(g)), - (a.HEAP16 = new Int16Array(g)), - (a.HEAPU8 = ve = new Uint8Array(g)), - (a.HEAPU16 = new Uint16Array(g)), - (a.HEAP32 = we = new Int32Array(g)), - (a.HEAPU32 = rt = new Uint32Array(g)), - (a.HEAPF32 = new Float32Array(g)), - (a.HEAPF64 = ot = new Float64Array(g)); - } - var He = 16777216; - if (A) _e = a.wasmMemory; - else if (a.wasmMemory) _e = a.wasmMemory; - else if ( - ((_e = new WebAssembly.Memory({ initial: He / 65536, maximum: 65536, shared: !0 })), - !(_e.buffer instanceof SharedArrayBuffer)) - ) - throw ( - (Y( - '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' - ), - E && - Y( - '(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)' - ), - Error('bad memory')) - ); - qe(), (He = _e.buffer.byteLength); - var Qe = [], - Be = [], - Ce = [], - Se = 0, - je = null; - function Tt() { - if ((Se--, Se == 0 && je)) { - var g = je; - (je = null), g(); - } - } - function xt(g) { - throw ( - ((g = 'Aborted(' + g + ')'), - Y(g), - (ue = !0), - (pe = 1), - (g = new WebAssembly.RuntimeError(g + '. Build with -sASSERTIONS for more info.')), - p(g), - g) - ); - } - var Mt = (g) => g.startsWith('data:application/octet-stream;base64,'), - Ot = (g) => g.startsWith('file://'), - gt; - (gt = 'ort-wasm-threaded.wasm'), Mt(gt) || (gt = B(gt)); - function yt(g) { - if (re) return re(g); - throw 'both async and sync fetching of the wasm failed'; - } - function Or(g) { - if (v || S) { - if (typeof fetch == 'function' && !Ot(g)) - return fetch(g, { credentials: 'same-origin' }) - .then((x) => { - if (!x.ok) throw "failed to load wasm binary file at '" + g + "'"; - return x.arrayBuffer(); - }) - .catch(() => yt(g)); - if (Q) - return new Promise((x, P) => { - Q(g, (D) => x(new Uint8Array(D)), P); - }); - } - return Promise.resolve().then(() => yt(g)); - } - function Ht(g, x, P) { - return Or(g) - .then((D) => WebAssembly.instantiate(D, x)) - .then((D) => D) - .then(P, (D) => { - Y(`failed to asynchronously prepare wasm: ${D}`), xt(D); - }); - } - function Sr(g, x) { - var P = gt; - return typeof WebAssembly.instantiateStreaming != 'function' || - Mt(P) || - Ot(P) || - E || - typeof fetch != 'function' - ? Ht(P, g, x) - : fetch(P, { credentials: 'same-origin' }).then((D) => - WebAssembly.instantiateStreaming(D, g).then(x, function (j) { - return ( - Y(`wasm streaming compile failed: ${j}`), - Y('falling back to ArrayBuffer instantiation'), - Ht(P, g, x) - ); - }) - ); - } - var st, - Bt = { - 921276: (g, x, P, D) => { - if (typeof a > 'u' || !a.cb) return 1; - if ( - ((g = Dt(g >>> 0)), - g.startsWith('./') && (g = g.substring(2)), - (g = a.cb.get(g)), - !g) - ) - return 2; - if (((x >>>= 0), (P >>>= 0), (D >>>= 0), x + P > g.byteLength)) return 3; - try { - return s().set(g.subarray(x, x + P), D >>> 0), 0; - } catch { - return 4; - } - }, - }; - function At(g) { - (this.name = 'ExitStatus'), - (this.message = `Program terminated with exit(${g})`), - (this.status = g); - } - var It = (g) => { - g.terminate(), (g.onmessage = () => {}); - }, - Ar = (g) => { - se.Pa.length == 0 && (Qt(), se.Ya(se.Pa[0])); - var x = se.Pa.pop(); - if (!x) return 6; - se.Qa.push(x), (se.Ma[g.Oa] = x), (x.Oa = g.Oa); - var P = { cmd: 'run', start_routine: g.kb, arg: g.hb, pthread_ptr: g.Oa }; - return E && x.unref(), x.postMessage(P, g.qb), 0; - }, - Et = 0, - Yt = typeof TextDecoder < 'u' ? new TextDecoder('utf8') : void 0, - Ir = (g, x, P) => { - x >>>= 0; - var D = x + P; - for (P = x; g[P] && !(P >= D); ) ++P; - if (16 < P - x && g.buffer && Yt) - return Yt.decode( - g.buffer instanceof SharedArrayBuffer ? g.slice(x, P) : g.subarray(x, P) - ); - for (D = ''; x < P; ) { - var j = g[x++]; - if (j & 128) { - var z = g[x++] & 63; - if ((j & 224) == 192) D += String.fromCharCode(((j & 31) << 6) | z); - else { - var K = g[x++] & 63; - (j = - (j & 240) == 224 - ? ((j & 15) << 12) | (z << 6) | K - : ((j & 7) << 18) | (z << 12) | (K << 6) | (g[x++] & 63)), - 65536 > j - ? (D += String.fromCharCode(j)) - : ((j -= 65536), - (D += String.fromCharCode(55296 | (j >> 10), 56320 | (j & 1023)))); - } - } else D += String.fromCharCode(j); - } - return D; - }, - Dt = (g, x) => ((g >>>= 0) ? Ir(s(), g, x) : ''), - Zr = (g) => { - var x = xn(); - return (g = g()), Yr(x), g; - }; - function H(g, x) { - var P = arguments.length - 2, - D = arguments; - return Zr(() => { - for (var j = On(8 * P), z = j >>> 3, K = 0; K < P; K++) { - var $e = D[2 + K]; - r()[(z + K) >>> 0] = $e; - } - return si(g, P, j, x); - }); - } - function Kt(g) { - if (A) return H(0, 1, g); - (pe = g), 0 < Et || (se.lb(), a.onExit?.(g), (ue = !0)), T(g, new At(g)); - } - var Gt = (g) => { - if (((pe = g), A)) throw (Nt(g), 'unwind'); - Kt(g); - }; - function Fr() { - for (var g = a.numThreads; g--; ) Qt(); - Qe.unshift(() => { - Se++, jr(() => Tt()); - }); - } - function Qt() { - var g = B('ort-wasm-threaded.worker.js'); - (g = new Worker(g)), se.Pa.push(g); - } - function jr(g) { - A ? g() : Promise.all(se.Pa.map(se.Ya)).then(g); - } - var se = { - Pa: [], - Qa: [], - bb: [], - Ma: {}, - Wa() { - A - ? ((se.receiveObjectTransfer = se.jb), - (se.threadInitTLS = se.ab), - (se.setExitStatus = se.$a)) - : Fr(); - }, - $a: (g) => (pe = g), - tb: ['$terminateWorker'], - lb: () => { - for (var g of se.Qa) It(g); - for (g of se.Pa) It(g); - (se.Pa = []), (se.Qa = []), (se.Ma = []); - }, - Za: (g) => { - var x = g.Oa; - delete se.Ma[x], se.Pa.push(g), se.Qa.splice(se.Qa.indexOf(g), 1), (g.Oa = 0), wn(x); - }, - jb() {}, - ab() { - se.bb.forEach((g) => g()); - }, - Ya: (g) => - new Promise((x) => { - (g.onmessage = (z) => { - z = z.data; - var K = z.cmd; - if (z.targetThread && z.targetThread != Hr()) { - var $e = se.Ma[z.targetThread]; - $e - ? $e.postMessage(z, z.transferList) - : Y( - `Internal error! Worker sent a message "${K}" to target pthread ${z.targetThread}, but that thread no longer exists!` - ); - } else - K === 'checkMailbox' - ? qr() - : K === 'spawnThread' - ? Ar(z) - : K === 'cleanupThread' - ? se.Za(se.Ma[z.thread]) - : K === 'killThread' - ? ((z = z.thread), - (K = se.Ma[z]), - delete se.Ma[z], - It(K), - wn(z), - se.Qa.splice(se.Qa.indexOf(K), 1), - (K.Oa = 0)) - : K === 'cancelThread' - ? se.Ma[z.thread].postMessage({ cmd: 'cancel' }) - : K === 'loaded' - ? ((g.loaded = !0), E && !g.Oa && g.unref(), x(g)) - : K === 'alert' - ? alert(`Thread ${z.threadId}: ${z.text}`) - : z.target === 'setimmediate' - ? g.postMessage(z) - : K === 'callHandler' - ? a[z.handler](...z.args) - : K && Y(`worker sent an unknown command ${K}`); - }), - (g.onerror = (z) => { - throw (Y(`worker sent an error! ${z.filename}:${z.lineno}: ${z.message}`), z); - }), - E && - (g.on('message', (z) => g.onmessage({ data: z })), - g.on('error', (z) => g.onerror(z))); - var P = [], - D = ['onExit'], - j; - for (j of D) a.hasOwnProperty(j) && P.push(j); - g.postMessage({ - cmd: 'load', - handlers: P, - urlOrBlob: a.mainScriptUrlOrBlob || i, - wasmMemory: _e, - wasmModule: he, - }); - }), - }; - a.PThread = se; - var Wt = (g) => { - for (; 0 < g.length; ) g.shift()(a); - }; - a.establishStackSpace = () => { - var g = Hr(), - x = f()[((g + 52) >>> 2) >>> 0]; - (g = f()[((g + 56) >>> 2) >>> 0]), ci(x, x - g), Yr(x); - }; - function Nt(g) { - if (A) return H(1, 0, g); - Gt(g); - } - var Lt = [], - O; - a.invokeEntryPoint = (g, x) => { - var P = Lt[g]; - P || (g >= Lt.length && (Lt.length = g + 1), (Lt[g] = P = O.get(g))), - (g = P(x)), - 0 < Et ? se.$a(g) : vn(g); - }; - function M(g) { - (this.Va = g - 24), - (this.gb = function (x) { - f()[((this.Va + 4) >>> 2) >>> 0] = x; - }), - (this.fb = function (x) { - f()[((this.Va + 8) >>> 2) >>> 0] = x; - }), - (this.Wa = function (x, P) { - this.eb(), this.gb(x), this.fb(P); - }), - (this.eb = function () { - f()[((this.Va + 16) >>> 2) >>> 0] = 0; - }); - } - var I = 0; - function k(g, x, P, D) { - return A ? H(2, 1, g, x, P, D) : G(g, x, P, D); - } - function G(g, x, P, D) { - if (((g >>>= 0), (x >>>= 0), (P >>>= 0), (D >>>= 0), typeof SharedArrayBuffer > 'u')) - return ( - Y( - 'Current environment does not support SharedArrayBuffer, pthreads are not available!' - ), - 6 - ); - var j = []; - return A && j.length === 0 - ? k(g, x, P, D) - : ((g = { kb: P, Oa: g, hb: D, qb: j }), - A ? ((g.sb = 'spawnThread'), postMessage(g, j), 0) : Ar(g)); - } - function ne(g, x, P) { - return A ? H(3, 1, g, x, P) : 0; - } - function ge(g, x) { - if (A) return H(4, 1, g, x); - } - var Ue = (g) => { - for (var x = 0, P = 0; P < g.length; ++P) { - var D = g.charCodeAt(P); - 127 >= D - ? x++ - : 2047 >= D - ? (x += 2) - : 55296 <= D && 57343 >= D - ? ((x += 4), ++P) - : (x += 3); - } - return x; - }, - et = (g, x, P, D) => { - if (((P >>>= 0), !(0 < D))) return 0; - var j = P; - D = P + D - 1; - for (var z = 0; z < g.length; ++z) { - var K = g.charCodeAt(z); - if (55296 <= K && 57343 >= K) { - var $e = g.charCodeAt(++z); - K = (65536 + ((K & 1023) << 10)) | ($e & 1023); - } - if (127 >= K) { - if (P >= D) break; - x[P++ >>> 0] = K; - } else { - if (2047 >= K) { - if (P + 1 >= D) break; - x[P++ >>> 0] = 192 | (K >> 6); - } else { - if (65535 >= K) { - if (P + 2 >= D) break; - x[P++ >>> 0] = 224 | (K >> 12); - } else { - if (P + 3 >= D) break; - (x[P++ >>> 0] = 240 | (K >> 18)), (x[P++ >>> 0] = 128 | ((K >> 12) & 63)); - } - x[P++ >>> 0] = 128 | ((K >> 6) & 63); - } - x[P++ >>> 0] = 128 | (K & 63); - } - } - return (x[P >>> 0] = 0), P - j; - }, - Ze = (g, x, P) => et(g, s(), x, P); - function Je(g, x) { - if (A) return H(5, 1, g, x); - } - function er(g, x, P) { - if (A) return H(6, 1, g, x, P); - } - function tr(g, x, P) { - return A ? H(7, 1, g, x, P) : 0; - } - function C(g, x) { - if (A) return H(8, 1, g, x); - } - function Te(g, x, P) { - if (A) return H(9, 1, g, x, P); - } - function Ie(g, x, P, D) { - if (A) return H(10, 1, g, x, P, D); - } - function at(g, x, P, D) { - if (A) return H(11, 1, g, x, P, D); - } - function lr(g, x, P, D) { - if (A) return H(12, 1, g, x, P, D); - } - function An(g) { - if (A) return H(13, 1, g); - } - function In(g, x) { - if (A) return H(14, 1, g, x); - } - function jn(g, x, P) { - if (A) return H(15, 1, g, x, P); - } - function Jr(g) { - (g >>>= 0), - typeof Atomics.rb == 'function' && - (Atomics.rb(d(), g >>> 2, g).value.then(qr), - (g += 128), - Atomics.store(d(), g >>> 2, 1)); - } - a.__emscripten_thread_mailbox_await = Jr; - var qr = () => { - var g = Hr(); - if (g && (Jr(g), (g = ai), !ue)) - try { - if ((g(), !(0 < Et))) - try { - A ? vn(pe) : Gt(pe); - } catch (x) { - x instanceof At || x == 'unwind' || T(1, x); - } - } catch (x) { - x instanceof At || x == 'unwind' || T(1, x); - } - }; - a.checkMailbox = qr; - var rn = [], - qt = (g) => g % 4 === 0 && (g % 100 !== 0 || g % 400 === 0), - qn = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], - Hn = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; - function Yn(g, x, P, D, j, z, K, $e) { - return A ? H(16, 1, g, x, P, D, j, z, K, $e) : -52; - } - function Mo(g, x, P, D, j, z, K) { - if (A) return H(17, 1, g, x, P, D, j, z, K); - } - var No = (g) => { - var x = Ue(g) + 1, - P = oi(x); - return P && Ze(g, P, x), P; - }, - nn = [], - on = {}, - Ro = () => { - if (!_n) { - var g = { - USER: 'web_user', - LOGNAME: 'web_user', - PATH: '/', - PWD: '/', - HOME: '/home/web_user', - LANG: - ( - (typeof navigator == 'object' && - navigator.languages && - navigator.languages[0]) || - 'C' - ).replace('-', '_') + '.UTF-8', - _: y || './this.program', - }, - x; - for (x in on) on[x] === void 0 ? delete g[x] : (g[x] = on[x]); - var P = []; - for (x in g) P.push(`${x}=${g[x]}`); - _n = P; - } - return _n; - }, - _n; - function Bo(g, x) { - if (A) return H(18, 1, g, x); - (g >>>= 0), (x >>>= 0); - var P = 0; - return ( - Ro().forEach((D, j) => { - var z = x + P; - for (j = f()[((g + 4 * j) >>> 2) >>> 0] = z, z = 0; z < D.length; ++z) - n()[(j++ >>> 0) >>> 0] = D.charCodeAt(z); - (n()[(j >>> 0) >>> 0] = 0), (P += D.length + 1); - }), - 0 - ); - } - function Uo(g, x) { - if (A) return H(19, 1, g, x); - (g >>>= 0), (x >>>= 0); - var P = Ro(); - f()[(g >>> 2) >>> 0] = P.length; - var D = 0; - return P.forEach((j) => (D += j.length + 1)), (f()[(x >>> 2) >>> 0] = D), 0; - } - function zo(g) { - return A ? H(20, 1, g) : 52; - } - function Vo(g, x, P, D) { - return A ? H(21, 1, g, x, P, D) : 52; - } - function Go(g, x, P, D, j) { - return A ? H(22, 1, g, x, P, D, j) : 70; - } - var zs = [null, [], []]; - function Wo(g, x, P, D) { - if (A) return H(23, 1, g, x, P, D); - (x >>>= 0), (P >>>= 0), (D >>>= 0); - for (var j = 0, z = 0; z < P; z++) { - var K = f()[(x >>> 2) >>> 0], - $e = f()[((x + 4) >>> 2) >>> 0]; - x += 8; - for (var ct = 0; ct < $e; ct++) { - var ze = s()[(K + ct) >>> 0], - it = zs[g]; - ze === 0 || ze === 10 ? ((g === 1 ? Me : Y)(Ir(it, 0)), (it.length = 0)) : it.push(ze); - } - j += $e; - } - return (f()[(D >>> 2) >>> 0] = j), 0; - } - var Jo = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], - ti = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - function Vs(g) { - var x = Array(Ue(g) + 1); - return et(g, x, 0, x.length), x; - } - var Gs = (g, x) => { - n().set(g, x >>> 0); - }; - function ri(g, x, P, D) { - function j(N, Ae, Le) { - for (N = typeof N == 'number' ? N.toString() : N || ''; N.length < Ae; ) N = Le[0] + N; - return N; - } - function z(N, Ae) { - return j(N, Ae, '0'); - } - function K(N, Ae) { - function Le(Ns) { - return 0 > Ns ? -1 : 0 < Ns ? 1 : 0; - } - var Rt; - return ( - (Rt = Le(N.getFullYear() - Ae.getFullYear())) === 0 && - (Rt = Le(N.getMonth() - Ae.getMonth())) === 0 && - (Rt = Le(N.getDate() - Ae.getDate())), - Rt - ); - } - function $e(N) { - switch (N.getDay()) { - case 0: - return new Date(N.getFullYear() - 1, 11, 29); - case 1: - return N; - case 2: - return new Date(N.getFullYear(), 0, 3); - case 3: - return new Date(N.getFullYear(), 0, 2); - case 4: - return new Date(N.getFullYear(), 0, 1); - case 5: - return new Date(N.getFullYear() - 1, 11, 31); - case 6: - return new Date(N.getFullYear() - 1, 11, 30); - } - } - function ct(N) { - var Ae = N.Ra; - for (N = new Date(new Date(N.Sa + 1900, 0, 1).getTime()); 0 < Ae; ) { - var Le = N.getMonth(), - Rt = (qt(N.getFullYear()) ? Jo : ti)[Le]; - if (Ae > Rt - N.getDate()) - (Ae -= Rt - N.getDate() + 1), - N.setDate(1), - 11 > Le - ? N.setMonth(Le + 1) - : (N.setMonth(0), N.setFullYear(N.getFullYear() + 1)); - else { - N.setDate(N.getDate() + Ae); - break; - } - } - return ( - (Le = new Date(N.getFullYear() + 1, 0, 4)), - (Ae = $e(new Date(N.getFullYear(), 0, 4))), - (Le = $e(Le)), - 0 >= K(Ae, N) - ? 0 >= K(Le, N) - ? N.getFullYear() + 1 - : N.getFullYear() - : N.getFullYear() - 1 - ); - } - (g >>>= 0), (x >>>= 0), (P >>>= 0), (D >>>= 0); - var ze = f()[((D + 40) >>> 2) >>> 0]; - (D = { - ob: d()[(D >>> 2) >>> 0], - nb: d()[((D + 4) >>> 2) >>> 0], - Ta: d()[((D + 8) >>> 2) >>> 0], - Xa: d()[((D + 12) >>> 2) >>> 0], - Ua: d()[((D + 16) >>> 2) >>> 0], - Sa: d()[((D + 20) >>> 2) >>> 0], - Na: d()[((D + 24) >>> 2) >>> 0], - Ra: d()[((D + 28) >>> 2) >>> 0], - ub: d()[((D + 32) >>> 2) >>> 0], - mb: d()[((D + 36) >>> 2) >>> 0], - pb: ze ? Dt(ze) : '', - }), - (P = Dt(P)), - (ze = { - '%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', - }); - for (var it in ze) P = P.replace(new RegExp(it, 'g'), ze[it]); - var fi = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'.split(' '), - Cs = - 'January February March April May June July August September October November December'.split( - ' ' - ); - (ze = { - '%a': (N) => fi[N.Na].substring(0, 3), - '%A': (N) => fi[N.Na], - '%b': (N) => Cs[N.Ua].substring(0, 3), - '%B': (N) => Cs[N.Ua], - '%C': (N) => z(((N.Sa + 1900) / 100) | 0, 2), - '%d': (N) => z(N.Xa, 2), - '%e': (N) => j(N.Xa, 2, ' '), - '%g': (N) => ct(N).toString().substring(2), - '%G': (N) => ct(N), - '%H': (N) => z(N.Ta, 2), - '%I': (N) => ((N = N.Ta), N == 0 ? (N = 12) : 12 < N && (N -= 12), z(N, 2)), - '%j': (N) => { - for (var Ae = 0, Le = 0; Le <= N.Ua - 1; Ae += (qt(N.Sa + 1900) ? Jo : ti)[Le++]); - return z(N.Xa + Ae, 3); - }, - '%m': (N) => z(N.Ua + 1, 2), - '%M': (N) => z(N.nb, 2), - '%n': () => ` -`, - '%p': (N) => (0 <= N.Ta && 12 > N.Ta ? 'AM' : 'PM'), - '%S': (N) => z(N.ob, 2), - '%t': () => ' ', - '%u': (N) => N.Na || 7, - '%U': (N) => z(Math.floor((N.Ra + 7 - N.Na) / 7), 2), - '%V': (N) => { - var Ae = Math.floor((N.Ra + 7 - ((N.Na + 6) % 7)) / 7); - if ((2 >= (N.Na + 371 - N.Ra - 2) % 7 && Ae++, Ae)) - Ae == 53 && - ((Le = (N.Na + 371 - N.Ra) % 7), Le == 4 || (Le == 3 && qt(N.Sa)) || (Ae = 1)); - else { - Ae = 52; - var Le = (N.Na + 7 - N.Ra - 1) % 7; - (Le == 4 || (Le == 5 && qt((N.Sa % 400) - 1))) && Ae++; - } - return z(Ae, 2); - }, - '%w': (N) => N.Na, - '%W': (N) => z(Math.floor((N.Ra + 7 - ((N.Na + 6) % 7)) / 7), 2), - '%y': (N) => (N.Sa + 1900).toString().substring(2), - '%Y': (N) => N.Sa + 1900, - '%z': (N) => { - N = N.mb; - var Ae = 0 <= N; - return ( - (N = Math.abs(N) / 60), - (Ae ? '+' : '-') + ('0000' + ((N / 60) * 100 + (N % 60))).slice(-4) - ); - }, - '%Z': (N) => N.pb, - '%%': () => '%', - }), - (P = P.replace(/%%/g, '\0\0')); - for (it in ze) P.includes(it) && (P = P.replace(new RegExp(it, 'g'), ze[it](D))); - return ( - (P = P.replace(/\0\0/g, '%')), (it = Vs(P)), it.length > x ? 0 : (Gs(it, g), it.length - 1) - ); - } - se.Wa(); - var Ws = [ - Kt, - Nt, - k, - ne, - ge, - Je, - er, - tr, - C, - Te, - Ie, - at, - lr, - An, - In, - jn, - Yn, - Mo, - Bo, - Uo, - zo, - Vo, - Go, - Wo, - ], - qs = { - b: function (g, x, P) { - throw ((g >>>= 0), new M(g).Wa(x >>> 0, P >>> 0), (I = g), I); - }, - L: function (g) { - ii(g >>> 0, !S, 1, !v, 131072, !1), se.ab(); - }, - j: function (g) { - (g >>>= 0), A ? postMessage({ cmd: 'cleanupThread', thread: g }) : se.Za(se.Ma[g]); - }, - H: G, - h: ne, - S: ge, - D: Je, - F: er, - T: tr, - Q: C, - J: Te, - P: Ie, - n: at, - E: lr, - B: An, - R: In, - C: jn, - p: () => 1, - z: function (g, x) { - (g >>>= 0), - g == x >>> 0 - ? setTimeout(() => qr()) - : A - ? postMessage({ targetThread: g, cmd: 'checkMailbox' }) - : (g = se.Ma[g]) && g.postMessage({ cmd: 'checkMailbox' }); - }, - I: function (g, x, P, D) { - (x >>>= 0), (rn.length = P), (D = (D >>> 0) >>> 3); - for (var j = 0; j < P; j++) rn[j] = r()[(D + j) >>> 0]; - return ( - (g = 0 > g ? Bt[-g - 1] : Ws[g]), - (se.ib = x), - (x = g.apply(null, rn)), - (se.ib = 0), - x - ); - }, - K: Jr, - o: function (g) { - E && se.Ma[g >>> 0].ref(); - }, - s: function (g, x, P) { - (g = (x + 2097152) >>> 0 < 4194305 - !!g ? (g >>> 0) + 4294967296 * x : NaN), - (P >>>= 0), - (g = new Date(1e3 * g)), - (d()[(P >>> 2) >>> 0] = g.getUTCSeconds()), - (d()[((P + 4) >>> 2) >>> 0] = g.getUTCMinutes()), - (d()[((P + 8) >>> 2) >>> 0] = g.getUTCHours()), - (d()[((P + 12) >>> 2) >>> 0] = g.getUTCDate()), - (d()[((P + 16) >>> 2) >>> 0] = g.getUTCMonth()), - (d()[((P + 20) >>> 2) >>> 0] = g.getUTCFullYear() - 1900), - (d()[((P + 24) >>> 2) >>> 0] = g.getUTCDay()), - (g = ((g.getTime() - Date.UTC(g.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5) | 0), - (d()[((P + 28) >>> 2) >>> 0] = g); - }, - t: function (g, x, P) { - (g = (x + 2097152) >>> 0 < 4194305 - !!g ? (g >>> 0) + 4294967296 * x : NaN), - (P >>>= 0), - (g = new Date(1e3 * g)), - (d()[(P >>> 2) >>> 0] = g.getSeconds()), - (d()[((P + 4) >>> 2) >>> 0] = g.getMinutes()), - (d()[((P + 8) >>> 2) >>> 0] = g.getHours()), - (d()[((P + 12) >>> 2) >>> 0] = g.getDate()), - (d()[((P + 16) >>> 2) >>> 0] = g.getMonth()), - (d()[((P + 20) >>> 2) >>> 0] = g.getFullYear() - 1900), - (d()[((P + 24) >>> 2) >>> 0] = g.getDay()), - (x = ((qt(g.getFullYear()) ? qn : Hn)[g.getMonth()] + g.getDate() - 1) | 0), - (d()[((P + 28) >>> 2) >>> 0] = x), - (d()[((P + 36) >>> 2) >>> 0] = -(60 * g.getTimezoneOffset())), - (x = new Date(g.getFullYear(), 6, 1).getTimezoneOffset()); - var D = new Date(g.getFullYear(), 0, 1).getTimezoneOffset(); - (g = (x != D && g.getTimezoneOffset() == Math.min(D, x)) | 0), - (d()[((P + 32) >>> 2) >>> 0] = g); - }, - u: function (g) { - g >>>= 0; - var x = new Date( - d()[((g + 20) >>> 2) >>> 0] + 1900, - d()[((g + 16) >>> 2) >>> 0], - d()[((g + 12) >>> 2) >>> 0], - d()[((g + 8) >>> 2) >>> 0], - d()[((g + 4) >>> 2) >>> 0], - d()[(g >>> 2) >>> 0], - 0 - ), - P = d()[((g + 32) >>> 2) >>> 0], - D = x.getTimezoneOffset(), - j = new Date(x.getFullYear(), 6, 1).getTimezoneOffset(), - z = new Date(x.getFullYear(), 0, 1).getTimezoneOffset(), - K = Math.min(z, j); - return ( - 0 > P - ? (d()[((g + 32) >>> 2) >>> 0] = +(j != z && K == D)) - : 0 < P != (K == D) && - ((j = Math.max(z, j)), x.setTime(x.getTime() + 6e4 * ((0 < P ? K : j) - D))), - (d()[((g + 24) >>> 2) >>> 0] = x.getDay()), - (P = ((qt(x.getFullYear()) ? qn : Hn)[x.getMonth()] + x.getDate() - 1) | 0), - (d()[((g + 28) >>> 2) >>> 0] = P), - (d()[(g >>> 2) >>> 0] = x.getSeconds()), - (d()[((g + 4) >>> 2) >>> 0] = x.getMinutes()), - (d()[((g + 8) >>> 2) >>> 0] = x.getHours()), - (d()[((g + 12) >>> 2) >>> 0] = x.getDate()), - (d()[((g + 16) >>> 2) >>> 0] = x.getMonth()), - (d()[((g + 20) >>> 2) >>> 0] = x.getYear()), - (g = x.getTime()), - isNaN(g) ? ((d()[(ni() >>> 2) >>> 0] = 61), (g = -1)) : (g /= 1e3), - ui( - ((st = g), - 1 <= +Math.abs(st) - ? 0 < st - ? +Math.floor(st / 4294967296) >>> 0 - : ~~+Math.ceil((st - +(~~st >>> 0)) / 4294967296) >>> 0 - : 0) - ), - g >>> 0 - ); - }, - q: Yn, - r: Mo, - y: function (g, x, P) { - function D(ze) { - return (ze = ze.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? ze[1] : 'GMT'; - } - (g >>>= 0), (x >>>= 0), (P >>>= 0); - var j = new Date().getFullYear(), - z = new Date(j, 0, 1), - K = new Date(j, 6, 1); - j = z.getTimezoneOffset(); - var $e = K.getTimezoneOffset(), - ct = Math.max(j, $e); - (f()[(g >>> 2) >>> 0] = 60 * ct), - (d()[(x >>> 2) >>> 0] = +(j != $e)), - (g = D(z)), - (x = D(K)), - (g = No(g)), - (x = No(x)), - $e < j - ? ((f()[(P >>> 2) >>> 0] = g), (f()[((P + 4) >>> 2) >>> 0] = x)) - : ((f()[(P >>> 2) >>> 0] = x), (f()[((P + 4) >>> 2) >>> 0] = g)); - }, - c: () => { - xt(''); - }, - O: function (g, x, P) { - (g >>>= 0), (x >>>= 0), (P >>>= 0), (nn.length = 0); - for (var D; (D = s()[x++ >>> 0]); ) { - var j = D != 105; - (j &= D != 112), - (P += j && P % 8 ? 4 : 0), - nn.push( - D == 112 - ? f()[(P >>> 2) >>> 0] - : D == 105 - ? d()[(P >>> 2) >>> 0] - : r()[(P >>> 3) >>> 0] - ), - (P += j ? 8 : 4); - } - return Bt[g].apply(null, nn); - }, - k: () => {}, - i: () => Date.now(), - U: () => { - throw ((Et += 1), 'unwind'); - }, - A: function () { - return 4294901760; - }, - e: () => performance.timeOrigin + performance.now(), - f: () => (E ? (Lp(), rr(Dp)).cpus().length : navigator.hardwareConcurrency), - x: function (g) { - g >>>= 0; - var x = s().length; - if (g <= x || 4294901760 < g) return !1; - for (var P = 1; 4 >= P; P *= 2) { - var D = x * (1 + 0.2 / P); - D = Math.min(D, g + 100663296); - var j = Math; - D = Math.max(g, D); - e: { - j = - (j.min.call(j, 4294901760, D + ((65536 - (D % 65536)) % 65536)) - - _e.buffer.byteLength + - 65535) / - 65536; - try { - _e.grow(j), qe(); - var z = 1; - break e; - } catch {} - z = void 0; - } - if (z) return !0; - } - return !1; - }, - M: Bo, - N: Uo, - G: Gt, - g: zo, - m: Vo, - v: Go, - l: Wo, - a: _e || a.wasmMemory, - w: ri, - d: function (g, x, P, D) { - return ri(g >>> 0, x >>> 0, P >>> 0, D >>> 0); - }, - }, - ie = (function () { - function g(P, D) { - return ( - (ie = P.exports), - (ie = Hs()), - se.bb.push(ie.za), - (O = ie.Aa), - Be.unshift(ie.V), - (he = D), - Tt(), - ie - ); - } - var x = { a: qs }; - if ((Se++, a.instantiateWasm)) - try { - return a.instantiateWasm(x, g); - } catch (P) { - Y(`Module.instantiateWasm callback failed with error: ${P}`), p(P); - } - return ( - Sr(x, function (P) { - g(P.instance, P.module); - }).catch(p), - {} - ); - })(); - (a._OrtInit = (g, x) => (a._OrtInit = ie.W)(g, x)), - (a._OrtGetLastError = (g, x) => (a._OrtGetLastError = ie.X)(g, x)), - (a._OrtCreateSessionOptions = (g, x, P, D, j, z, K, $e, ct, ze) => - (a._OrtCreateSessionOptions = ie.Y)(g, x, P, D, j, z, K, $e, ct, ze)), - (a._OrtAppendExecutionProvider = (g, x) => (a._OrtAppendExecutionProvider = ie.Z)(g, x)), - (a._OrtAddFreeDimensionOverride = (g, x, P) => - (a._OrtAddFreeDimensionOverride = ie._)(g, x, P)), - (a._OrtAddSessionConfigEntry = (g, x, P) => (a._OrtAddSessionConfigEntry = ie.$)(g, x, P)), - (a._OrtReleaseSessionOptions = (g) => (a._OrtReleaseSessionOptions = ie.aa)(g)), - (a._OrtCreateSession = (g, x, P) => (a._OrtCreateSession = ie.ba)(g, x, P)), - (a._OrtReleaseSession = (g) => (a._OrtReleaseSession = ie.ca)(g)), - (a._OrtGetInputOutputCount = (g, x, P) => (a._OrtGetInputOutputCount = ie.da)(g, x, P)), - (a._OrtGetInputName = (g, x) => (a._OrtGetInputName = ie.ea)(g, x)), - (a._OrtGetOutputName = (g, x) => (a._OrtGetOutputName = ie.fa)(g, x)), - (a._OrtFree = (g) => (a._OrtFree = ie.ga)(g)), - (a._OrtCreateTensor = (g, x, P, D, j, z) => (a._OrtCreateTensor = ie.ha)(g, x, P, D, j, z)), - (a._OrtGetTensorData = (g, x, P, D, j) => (a._OrtGetTensorData = ie.ia)(g, x, P, D, j)), - (a._OrtReleaseTensor = (g) => (a._OrtReleaseTensor = ie.ja)(g)), - (a._OrtCreateRunOptions = (g, x, P, D) => (a._OrtCreateRunOptions = ie.ka)(g, x, P, D)), - (a._OrtAddRunConfigEntry = (g, x, P) => (a._OrtAddRunConfigEntry = ie.la)(g, x, P)), - (a._OrtReleaseRunOptions = (g) => (a._OrtReleaseRunOptions = ie.ma)(g)), - (a._OrtCreateBinding = (g) => (a._OrtCreateBinding = ie.na)(g)), - (a._OrtBindInput = (g, x, P) => (a._OrtBindInput = ie.oa)(g, x, P)), - (a._OrtBindOutput = (g, x, P, D) => (a._OrtBindOutput = ie.pa)(g, x, P, D)), - (a._OrtClearBoundOutputs = (g) => (a._OrtClearBoundOutputs = ie.qa)(g)), - (a._OrtReleaseBinding = (g) => (a._OrtReleaseBinding = ie.ra)(g)), - (a._OrtRunWithBinding = (g, x, P, D, j) => (a._OrtRunWithBinding = ie.sa)(g, x, P, D, j)), - (a._OrtRun = (g, x, P, D, j, z, K, $e) => (a._OrtRun = ie.ta)(g, x, P, D, j, z, K, $e)), - (a._OrtEndProfiling = (g) => (a._OrtEndProfiling = ie.ua)(g)); - var ni = () => (ni = ie.va)(), - Hr = (a._pthread_self = () => (Hr = a._pthread_self = ie.wa)()), - oi = (a._malloc = (g) => (oi = a._malloc = ie.xa)(g)); - (a._free = (g) => (a._free = ie.ya)(g)), - (a.__emscripten_tls_init = () => (a.__emscripten_tls_init = ie.za)()); - var ii = (a.__emscripten_thread_init = (g, x, P, D, j, z) => - (ii = a.__emscripten_thread_init = ie.Ba)(g, x, P, D, j, z)); - a.__emscripten_thread_crashed = () => (a.__emscripten_thread_crashed = ie.Ca)(); - var si = (g, x, P, D) => (si = ie.Da)(g, x, P, D), - wn = (g) => (wn = ie.Ea)(g), - vn = (a.__emscripten_thread_exit = (g) => (vn = a.__emscripten_thread_exit = ie.Fa)(g)), - ai = () => (ai = ie.Ga)(), - ui = (g) => (ui = ie.Ha)(g), - ci = (g, x) => (ci = ie.Ia)(g, x), - xn = () => (xn = ie.Ja)(), - Yr = (g) => (Yr = ie.Ka)(g), - On = (g) => (On = ie.La)(g); - function Hs() { - var g = ie; - g = Object.assign({}, g); - var x = (D) => () => D() >>> 0, - P = (D) => (j) => D(j) >>> 0; - return ( - (g.va = x(g.va)), - (g.wa = x(g.wa)), - (g.xa = P(g.xa)), - (g.emscripten_main_runtime_thread_id = x(g.emscripten_main_runtime_thread_id)), - (g.Ja = x(g.Ja)), - (g.La = P(g.La)), - g - ); - } - (a.wasmMemory = _e), - (a.stackAlloc = On), - (a.stackSave = xn), - (a.stackRestore = Yr), - (a.keepRuntimeAlive = () => 0 < Et), - (a.UTF8ToString = Dt), - (a.stringToUTF8 = Ze), - (a.lengthBytesUTF8 = Ue), - (a.ExitStatus = At), - (a.PThread = se); - var Xr; - je = function g() { - Xr || di(), Xr || (je = g); - }; - function di() { - if (!(0 < Se)) - if (A) l(a), A || Wt(Be), startWorker(a); - else { - if (a.preRun) - for (typeof a.preRun == 'function' && (a.preRun = [a.preRun]); a.preRun.length; ) - Qe.unshift(a.preRun.shift()); - Wt(Qe), - 0 < Se || - Xr || - ((Xr = !0), (a.calledRun = !0), ue || (A || Wt(Be), l(a), A || Wt(Ce))); - } - } - return di(), u.ready; - } - ); - })(); - typeof t == 'object' && typeof e == 'object' - ? (e.exports = o) - : typeof define == 'function' && define.amd && define([], () => o); - }), - kp = me((t, e) => { - e.exports = - '"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\n'; - }), - Np, - ig, - aa, - sa, - Po, - Bp, - ag, - sg, - ug, - Rp, - Ee, - zr = L(() => { - (Np = Ap()), - (ig = Cp()), - (sa = !1), - (Po = !1), - (Bp = !1), - (ag = (t) => { - if (t === 1) return !1; - if (typeof SharedArrayBuffer > 'u') - return ( - typeof self < 'u' && - !self.crossOriginIsolated && - console.warn( - 'env.wasm.numThreads is set to ' + - t + - ', but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.' - ), - !1 - ); - typeof process < 'u' && - process.versions && - process.versions.node && - console.warn( - 'env.wasm.numThreads is set to ' + - t + - ', however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.' - ); - try { - return ( - typeof MessageChannel < 'u' && 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 { - return !1; - } - }), - (sg = () => { - 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 { - return !1; - } - }), - (ug = (t, e) => - t - ? e - ? 'ort-wasm-simd-threaded.wasm' - : 'ort-wasm-simd.wasm' - : e - ? 'ort-wasm-threaded.wasm' - : 'ort-wasm.wasm'), - (Rp = async (t) => { - if (sa) return Promise.resolve(); - if (Po) throw new Error("multiple calls to 'initializeWebAssembly()' detected."); - if (Bp) throw new Error("previous call to 'initializeWebAssembly()' failed."); - Po = !0; - let e = t.initTimeout, - o = t.numThreads, - i = t.simd, - u = ag(o), - n = i && sg(), - s = t.wasmPaths, - d = typeof s == 'string' ? s : void 0, - f = ug(n, u), - r = typeof s == 'object' ? s[f] : void 0, - a = !1, - l = []; - if ( - (e > 0 && - l.push( - new Promise((p) => { - setTimeout(() => { - (a = !0), p(); - }, e); - }) - ), - l.push( - new Promise((p, m) => { - let y = u ? ig : Np, - T = { - locateFile: (v, S) => - u && v.endsWith('.worker.js') && typeof Blob < 'u' - ? URL.createObjectURL(new Blob([kp()], { type: 'text/javascript' })) - : v.endsWith('.wasm') - ? r || (d ?? S) + f - : S + v, - }; - if (u) - if (((T.numThreads = o), typeof Blob > 'u')) - T.mainScriptUrlOrBlob = (void 0)(__dirname, 'ort-wasm-threaded.js'); - else { - let v = `var ortWasmThreaded=${y.toString()};`; - T.mainScriptUrlOrBlob = new Blob([v], { type: 'text/javascript' }); - } - y(T).then( - (v) => { - (Po = !1), (sa = !0), (aa = v), p(); - }, - (v) => { - (Po = !1), (Bp = !0), m(v); - } - ); - }) - ), - await Promise.race(l), - a) - ) - throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`); - }), - (Ee = () => { - if (sa && aa) return aa; - throw new Error('WebAssembly is not initialized yet.'); - }); - }), - De, - bn, - Oe, - Eo = L(() => { - zr(), - (De = (t, e) => { - let o = Ee(), - i = o.lengthBytesUTF8(t) + 1, - u = o._malloc(i); - return o.stringToUTF8(t, u, i), e.push(u), u; - }), - (bn = (t, e, o, i) => { - if (typeof t == 'object' && t !== null) { - if (o.has(t)) throw new Error('Circular reference in options'); - o.add(t); - } - Object.entries(t).forEach(([u, n]) => { - let s = e ? e + u : u; - if (typeof n == 'object') bn(n, s + '.', o, i); - else if (typeof n == 'string' || typeof n == 'number') i(s, n.toString()); - else if (typeof n == 'boolean') i(s, n ? '1' : '0'); - else throw new Error(`Can't handle extra config type: ${typeof n}`); - }); - }), - (Oe = (t) => { - let e = Ee(), - o = e.stackSave(); - try { - let i = e.stackAlloc(8); - e._OrtGetLastError(i, i + 4); - let u = e.HEAP32[i / 4], - n = e.HEAPU32[i / 4 + 1], - s = n ? e.UTF8ToString(n) : ''; - throw new Error(`${t} ERROR_CODE: ${u}, ERROR_MESSAGE: ${s}`); - } finally { - e.stackRestore(o); - } - }); - }), - Mp, - Gp = L(() => { - zr(), - Eo(), - (Mp = (t) => { - let e = Ee(), - o = 0, - i = [], - u = t || {}; - try { - if (t?.logSeverityLevel === void 0) u.logSeverityLevel = 2; - else if ( - typeof t.logSeverityLevel != 'number' || - !Number.isInteger(t.logSeverityLevel) || - t.logSeverityLevel < 0 || - t.logSeverityLevel > 4 - ) - throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`); - if (t?.logVerbosityLevel === void 0) u.logVerbosityLevel = 0; - else if (typeof t.logVerbosityLevel != 'number' || !Number.isInteger(t.logVerbosityLevel)) - throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`); - t?.terminate === void 0 && (u.terminate = !1); - let n = 0; - return ( - t?.tag !== void 0 && (n = De(t.tag, i)), - (o = e._OrtCreateRunOptions(u.logSeverityLevel, u.logVerbosityLevel, !!u.terminate, n)), - o === 0 && Oe("Can't create run options."), - t?.extra !== void 0 && - bn(t.extra, '', new WeakSet(), (s, d) => { - let f = De(s, i), - r = De(d, i); - e._OrtAddRunConfigEntry(o, f, r) !== 0 && - Oe(`Can't set a run config entry: ${s} - ${d}.`); - }), - [o, i] - ); - } catch (n) { - throw (o !== 0 && e._OrtReleaseRunOptions(o), i.forEach((s) => e._free(s)), n); - } - }); - }), - lg, - fg, - cg, - pg, - Up, - zp = L(() => { - zr(), - Eo(), - (lg = (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}`); - } - }), - (fg = (t) => { - switch (t) { - case 'sequential': - return 0; - case 'parallel': - return 1; - default: - throw new Error(`unsupported execution mode: ${t}`); - } - }), - (cg = (t) => { - t.extra || (t.extra = {}), t.extra.session || (t.extra.session = {}); - let e = t.extra.session; - e.use_ort_model_bytes_directly || (e.use_ort_model_bytes_directly = '1'), - t.executionProviders && - t.executionProviders.some((o) => (typeof o == 'string' ? o : o.name) === 'webgpu') && - (t.enableMemPattern = !1); - }), - (pg = (t, e, o) => { - for (let i of e) { - let u = typeof i == 'string' ? i : i.name; - switch (u) { - case 'webnn': - if (((u = 'WEBNN'), typeof i != 'string')) { - let s = i; - if (s?.deviceType) { - let d = De('deviceType', o), - f = De(s.deviceType, o); - Ee()._OrtAddSessionConfigEntry(t, d, f) !== 0 && - Oe(`Can't set a session config entry: 'deviceType' - ${s.deviceType}.`); - } - if (s?.numThreads) { - let d = s.numThreads; - (typeof d != 'number' || !Number.isInteger(d) || d < 0) && (d = 0); - let f = De('numThreads', o), - r = De(d.toString(), o); - Ee()._OrtAddSessionConfigEntry(t, f, r) !== 0 && - Oe(`Can't set a session config entry: 'numThreads' - ${s.numThreads}.`); - } - if (s?.powerPreference) { - let d = De('powerPreference', o), - f = De(s.powerPreference, o); - Ee()._OrtAddSessionConfigEntry(t, d, f) !== 0 && - Oe( - `Can't set a session config entry: 'powerPreference' - ${s.powerPreference}.` - ); - } - } - break; - case 'webgpu': - if (((u = 'JS'), typeof i != 'string')) { - let s = i; - if (s?.preferredLayout) { - if (s.preferredLayout !== 'NCHW' && s.preferredLayout !== 'NHWC') - throw new Error( - `preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}` - ); - let d = De('preferredLayout', o), - f = De(s.preferredLayout, o); - Ee()._OrtAddSessionConfigEntry(t, d, f) !== 0 && - Oe( - `Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.` - ); - } - } - break; - case 'wasm': - case 'cpu': - continue; - default: - throw new Error(`not supported execution provider: ${u}`); - } - let n = De(u, o); - Ee()._OrtAppendExecutionProvider(t, n) !== 0 && Oe(`Can't append execution provider: ${u}.`); - } - }), - (Up = (t) => { - let e = Ee(), - o = 0, - i = [], - u = t || {}; - cg(u); - try { - let n = lg(u.graphOptimizationLevel ?? 'all'), - s = fg(u.executionMode ?? 'sequential'), - d = typeof u.logId == 'string' ? De(u.logId, i) : 0, - f = u.logSeverityLevel ?? 2; - if (!Number.isInteger(f) || f < 0 || f > 4) - throw new Error(`log serverity level is not valid: ${f}`); - let r = u.logVerbosityLevel ?? 0; - if (!Number.isInteger(r) || r < 0 || r > 4) - throw new Error(`log verbosity level is not valid: ${r}`); - let a = typeof u.optimizedModelFilePath == 'string' ? De(u.optimizedModelFilePath, i) : 0; - if ( - ((o = e._OrtCreateSessionOptions( - n, - !!u.enableCpuMemArena, - !!u.enableMemPattern, - s, - !!u.enableProfiling, - 0, - d, - f, - r, - a - )), - o === 0 && Oe("Can't create session options."), - u.executionProviders && pg(o, u.executionProviders, i), - u.freeDimensionOverrides) - ) - for (let [l, p] of Object.entries(u.freeDimensionOverrides)) { - if (typeof l != 'string') - throw new Error(`free dimension override name must be a string: ${l}`); - if (typeof p != 'number' || !Number.isInteger(p) || p < 0) - throw new Error(`free dimension override value must be a non-negative integer: ${p}`); - let m = De(l, i); - e._OrtAddFreeDimensionOverride(o, m, p) !== 0 && - Oe(`Can't set a free dimension override: ${l} - ${p}.`); - } - return ( - u.extra !== void 0 && - bn(u.extra, '', new WeakSet(), (l, p) => { - let m = De(l, i), - y = De(p, i); - e._OrtAddSessionConfigEntry(o, m, y) !== 0 && - Oe(`Can't set a session config entry: ${l} - ${p}.`); - }), - [o, i] - ); - } catch (n) { - throw (o !== 0 && e._OrtReleaseSessionOptions(o), i.forEach((s) => e._free(s)), n); - } - }); - }), - ua, - Vp, - la, - Wp, - Hp, - Do, - qp, - fa = L(() => { - (ua = (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 'float16': - return 10; - 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}`); - } - }), - (Vp = (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 10: - return 'float16'; - 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}`); - } - }), - (la = (t) => [void 0, 4, 1, 1, 2, 2, 4, 8, void 0, 1, 2, 8, 4, 8, void 0, void 0, void 0][t]), - (Wp = (t) => { - switch (t) { - case 'float16': - return Uint16Array; - case 'float32': - return Float32Array; - case 'uint8': - return Uint8Array; - case 'int8': - return Int8Array; - case 'uint16': - return Uint16Array; - case 'int16': - return Int16Array; - case 'int32': - return Int32Array; - case 'bool': - return Uint8Array; - case 'float64': - return Float64Array; - case 'uint32': - return Uint32Array; - case 'int64': - return BigInt64Array; - case 'uint64': - return BigUint64Array; - default: - throw new Error(`unsupported type: ${t}`); - } - }), - (Hp = (t) => { - switch (t) { - case 'verbose': - return 0; - case 'info': - return 1; - case 'warning': - return 2; - case 'error': - return 3; - case 'fatal': - return 4; - default: - throw new Error(`unsupported logging level: ${t}`); - } - }), - (Do = (t) => - t === 'float32' || t === 'int32' || t === 'int64' || t === 'bool' || t === 'float16' || t === 'uint32'), - (qp = (t) => { - switch (t) { - case 'none': - return 0; - case 'cpu': - return 1; - case 'cpu-pinned': - return 2; - case 'texture': - return 3; - case 'gpu-buffer': - return 4; - default: - throw new Error(`unsupported data location: ${t}`); - } - }); - }), - gn, - ca = L(() => { - gn = async (t) => { - if (typeof t == 'string') - if (typeof process < 'u' && process.versions && process.versions.node) - try { - return new Uint8Array(await (void 0)(t)); - } catch (e) { - if (e.code === 'ERR_FS_FILE_TOO_LARGE') { - let o = (void 0)(t), - i = []; - for await (let u of o) i.push(u); - return new Uint8Array(Buffer.concat(i)); - } - throw e; - } - else { - let e = await fetch(t); - if (!e.ok) throw new Error(`failed to load external data file: ${t}`); - let o = e.headers.get('Content-Length'), - i = o ? parseInt(o, 10) : 0; - if (i < 1073741824) return new Uint8Array(await e.arrayBuffer()); - { - if (!e.body) throw new Error(`failed to load external data file: ${t}, no response body.`); - let u = e.body.getReader(), - n; - try { - n = new ArrayBuffer(i); - } catch (d) { - if (d instanceof RangeError) { - let f = Math.ceil(i / 65536); - n = new WebAssembly.Memory({ initial: f, maximum: f }).buffer; - } else throw d; - } - let s = 0; - for (;;) { - let { done: d, value: f } = await u.read(); - if (d) break; - let r = f.byteLength; - new Uint8Array(n, s, r).set(f), (s += r); - } - return new Uint8Array(n, 0, i); - } - } - else - return t instanceof Blob - ? new Uint8Array(await t.arrayBuffer()) - : t instanceof Uint8Array - ? t - : new Uint8Array(t); - }; - }), - dg, - Yp, - Xp, - yn, - hg, - pa, - Kp, - Jp, - jp, - Zp, - Qp, - ed, - td = L(() => { - Gp(), - zp(), - fa(), - zr(), - Eo(), - ca(), - (dg = (t, e) => { - Ee()._OrtInit(t, e) !== 0 && Oe("Can't initialize onnxruntime."); - }), - (Yp = async (t) => { - dg(t.wasm.numThreads, Hp(t.logLevel)); - }), - (Xp = async (t, e) => {}), - (yn = new Map()), - (hg = (t) => { - let e = Ee(), - o = e.stackSave(); - try { - let i = e.stackAlloc(8); - return ( - e._OrtGetInputOutputCount(t, i, i + 4) !== 0 && Oe("Can't get session input/output count."), - [e.HEAP32[i / 4], e.HEAP32[i / 4 + 1]] - ); - } finally { - e.stackRestore(o); - } - }), - (pa = (t) => { - let e = Ee(), - o = e._malloc(t.byteLength); - if (o === 0) - throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`); - return e.HEAPU8.set(t, o), [o, t.byteLength]; - }), - (Kp = async (t, e) => { - let o, - i, - u = Ee(); - Array.isArray(t) - ? ([o, i] = t) - : t.buffer === u.HEAPU8.buffer - ? ([o, i] = [t.byteOffset, t.byteLength]) - : ([o, i] = pa(t)); - let n = 0, - s = 0, - d = [], - f = [], - r = []; - try { - if ((([s, d] = Up(e)), e?.externalData && u.mountExternalData)) { - let v = []; - for (let S of e.externalData) { - let E = typeof S == 'string' ? S : S.path; - v.push( - gn(typeof S == 'string' ? S : S.data).then((A) => { - u.mountExternalData(E, A); - }) - ); - } - await Promise.all(v); - } - (n = u._OrtCreateSession(o, i, s)), n === 0 && Oe("Can't create a session."); - let [a, l] = hg(n), - p = [], - m = [], - y = []; - for (let v = 0; v < a; v++) { - let S = u._OrtGetInputName(n, v); - S === 0 && Oe("Can't get an input name."), f.push(S), p.push(u.UTF8ToString(S)); - } - for (let v = 0; v < l; v++) { - let S = u._OrtGetOutputName(n, v); - S === 0 && Oe("Can't get an output name."), r.push(S); - let E = u.UTF8ToString(S); - m.push(E); - } - return yn.set(n, [n, f, r, null]), [n, p, m]; - } catch (a) { - throw ( - (f.forEach((l) => u._OrtFree(l)), - r.forEach((l) => u._OrtFree(l)), - n !== 0 && u._OrtReleaseSession(n), - a) - ); - } finally { - u._free(o), - s !== 0 && u._OrtReleaseSessionOptions(s), - d.forEach((a) => u._free(a)), - u.unmountExternalData?.(); - } - }), - (Jp = (t) => { - let e = Ee(), - o = yn.get(t); - if (!o) throw new Error(`cannot release session. invalid session id: ${t}`); - let [i, u, n, s] = o; - s && e._OrtReleaseBinding(s.handle), - e.jsepUnregisterBuffers?.(t), - u.forEach((d) => e._OrtFree(d)), - n.forEach((d) => e._OrtFree(d)), - e._OrtReleaseSession(i), - yn.delete(t); - }), - (jp = (t, e, o, i, u) => { - if (!t) { - e.push(0); - return; - } - let n = Ee(), - s = t[0], - d = t[1], - f = t[3], - r, - a; - if (s === 'string' && f === 'gpu-buffer') throw new Error('String tensor is not supported on GPU.'); - if (f === 'gpu-buffer') { - let m = t[2].gpuBuffer, - y = la(ua(s)); - (a = d.reduce((T, v) => T * v, 1) * y), (r = n.jsepRegisterBuffer(i, u, m, a)); - } else { - let m = t[2]; - if (Array.isArray(m)) { - (a = 4 * m.length), (r = n._malloc(a)), o.push(r); - let y = r / 4; - for (let T = 0; T < m.length; T++) { - if (typeof m[T] != 'string') - throw new TypeError(`tensor data at index ${T} is not a string`); - n.HEAPU32[y++] = De(m[T], o); - } - } else - (a = m.byteLength), - (r = n._malloc(a)), - o.push(r), - n.HEAPU8.set(new Uint8Array(m.buffer, m.byteOffset, a), r); - } - let l = n.stackSave(), - p = n.stackAlloc(4 * d.length); - try { - let m = p / 4; - d.forEach((T) => (n.HEAP32[m++] = T)); - let y = n._OrtCreateTensor(ua(s), r, a, p, d.length, qp(f)); - y === 0 && Oe(`Can't create tensor for input/output. session=${i}, index=${u}.`), e.push(y); - } finally { - n.stackRestore(l); - } - }), - (Zp = async (t, e, o, i, u, n) => { - let s = Ee(), - d = yn.get(t); - if (!d) throw new Error(`cannot run inference. invalid session id: ${t}`); - let [f, r, a, l] = d, - p = e.length, - m = i.length, - y = 0, - T = [], - v = [], - S = [], - E = [], - A = s.stackSave(), - F = s.stackAlloc(p * 4), - B = s.stackAlloc(p * 4), - J = s.stackAlloc(m * 4), - Q = s.stackAlloc(m * 4); - try { - [y, T] = Mp(n); - for (let Y = 0; Y < p; Y++) jp(o[Y], v, E, t, e[Y]); - for (let Y = 0; Y < m; Y++) jp(u[Y], S, E, t, p + i[Y]); - let re = F / 4, - V = B / 4, - de = J / 4, - ke = Q / 4; - for (let Y = 0; Y < p; Y++) (s.HEAPU32[re++] = v[Y]), (s.HEAPU32[V++] = r[e[Y]]); - for (let Y = 0; Y < m; Y++) (s.HEAPU32[de++] = S[Y]), (s.HEAPU32[ke++] = a[i[Y]]); - let Ne; - (Ne = await s._OrtRun(f, B, F, p, Q, m, J, y)), Ne !== 0 && Oe('failed to call OrtRun().'); - let Me = []; - for (let Y = 0; Y < m; Y++) { - let _e = s.HEAPU32[J / 4 + Y]; - if (_e === S[Y]) { - Me.push(u[Y]); - continue; - } - let he = s.stackSave(), - ue = s.stackAlloc(4 * 4), - pe = !1, - X, - ve = 0; - try { - s._OrtGetTensorData(_e, ue, ue + 4, ue + 8, ue + 12) !== 0 && - Oe(`Can't access output tensor data on index ${Y}.`); - let we = ue / 4, - rt = s.HEAPU32[we++]; - ve = s.HEAPU32[we++]; - let ot = s.HEAPU32[we++], - qe = s.HEAPU32[we++], - He = []; - for (let Ce = 0; Ce < qe; Ce++) He.push(s.HEAPU32[ot / 4 + Ce]); - s._OrtFree(ot); - let Qe = He.reduce((Ce, Se) => Ce * Se, 1); - X = Vp(rt); - let Be = l?.outputPreferredLocations[i[Y]]; - if (X === 'string') { - if (Be === 'gpu-buffer') throw new Error('String tensor is not supported on GPU.'); - let Ce = [], - Se = ve / 4; - for (let je = 0; je < Qe; je++) { - let Tt = s.HEAPU32[Se++], - xt = je === Qe - 1 ? void 0 : s.HEAPU32[Se] - Tt; - Ce.push(s.UTF8ToString(Tt, xt)); - } - Me.push([X, He, Ce, 'cpu']); - } else if (Be === 'gpu-buffer' && Qe > 0) { - let Ce = s.jsepGetBuffer(ve), - Se = la(rt); - if (Se === void 0 || !Do(X)) throw new Error(`Unsupported data type: ${X}`); - (pe = !0), - Me.push([ - X, - He, - { - gpuBuffer: Ce, - download: s.jsepCreateDownloader(Ce, Qe * Se, X), - dispose: () => { - s._OrtReleaseTensor(_e); - }, - }, - 'gpu-buffer', - ]); - } else { - let Ce = Wp(X), - Se = new Ce(Qe); - new Uint8Array(Se.buffer, Se.byteOffset, Se.byteLength).set( - s.HEAPU8.subarray(ve, ve + Se.byteLength) - ), - Me.push([X, He, Se, 'cpu']); - } - } finally { - s.stackRestore(he), X === 'string' && ve && s._free(ve), pe || s._OrtReleaseTensor(_e); - } - } - return l && s._OrtClearBoundOutputs(l.handle), Me; - } finally { - s.stackRestore(A), - v.forEach((re) => s._OrtReleaseTensor(re)), - S.forEach((re) => s._OrtReleaseTensor(re)), - E.forEach((re) => s._free(re)), - y !== 0 && s._OrtReleaseRunOptions(y), - T.forEach((re) => s._free(re)); - } - }), - (Qp = (t) => { - let e = Ee(), - o = yn.get(t); - if (!o) throw new Error('invalid session id'); - let i = o[0], - u = e._OrtEndProfiling(i); - u === 0 && Oe("Can't get an profile file name."), e._OrtFree(u); - }), - (ed = (t) => { - let e = []; - for (let o of t) { - let i = o[2]; - !Array.isArray(i) && 'buffer' in i && e.push(i.buffer); - } - return e; - }); - }), - rd = me((t, e) => { - e.exports = - '/*!\n * ONNX Runtime Web v1.17.1\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var Et=Object.defineProperty;var Jr=Object.getOwnPropertyDescriptor;var Xr=Object.getOwnPropertyNames;var Qr=Object.prototype.hasOwnProperty;var St=(u,d)=>()=>(u&&(d=u(u=0)),d);var et=(u,d)=>()=>(d||u((d={exports:{}}).exports,d),d.exports),Tt=(u,d)=>{for(var a in d)Et(u,a,{get:d[a],enumerable:!0})},Zr=(u,d,a,h)=>{if(d&&typeof d=="object"||typeof d=="function")for(let l of Xr(d))!Qr.call(u,l)&&l!==a&&Et(u,l,{get:()=>d[l],enumerable:!(h=Jr(d,l))||h.enumerable});return u};var tt=u=>Zr(Et({},"__esModule",{value:!0}),u);var At={};Tt(At,{createReadStream:()=>dr,readFile:()=>Kr,readFileSync:()=>en});var Kr,en,dr,Mt=St(()=>{Kr=void 0,en=void 0,dr=void 0});var Ct={};Tt(Ct,{join:()=>tn});var tn,Dt=St(()=>{tn=void 0});var gr=et((mr,xt)=>{"use strict";var pr=(()=>{var u=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(u=u||__filename),function(d={}){var a=d,h,l;a.ready=new Promise((r,o)=>{h=r,l=o});var w=Object.assign({},a),g="./this.program",i=typeof window=="object",A=typeof importScripts=="function",D=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",I="",B,F,U;if(D){var k=(Mt(),tt(At)),L=(Dt(),tt(Ct));I=A?L.dirname(I)+"/":__dirname+"/",B=(r,o)=>(r=ye(r)?new URL(r):L.normalize(r),k.readFileSync(r,o?void 0:"utf8")),U=r=>(r=B(r,!0),r.buffer||(r=new Uint8Array(r)),r),F=(r,o,s,m=!0)=>{r=ye(r)?new URL(r):L.normalize(r),k.readFile(r,m?void 0:"utf8",(O,S)=>{O?s(O):o(m?S.buffer:S)})},!a.thisProgram&&1"[Emscripten Module object]"}else(i||A)&&(A?I=self.location.href:typeof document<"u"&&document.currentScript&&(I=document.currentScript.src),u&&(I=u),I.indexOf("blob:")!==0?I=I.substr(0,I.replace(/[?#].*/,"").lastIndexOf("/")+1):I="",B=r=>{var o=new XMLHttpRequest;return o.open("GET",r,!1),o.send(null),o.responseText},A&&(U=r=>{var o=new XMLHttpRequest;return o.open("GET",r,!1),o.responseType="arraybuffer",o.send(null),new Uint8Array(o.response)}),F=(r,o,s)=>{var m=new XMLHttpRequest;m.open("GET",r,!0),m.responseType="arraybuffer",m.onload=()=>{m.status==200||m.status==0&&m.response?o(m.response):s()},m.onerror=s,m.send(null)});var _=console.log.bind(console),x=console.error.bind(console);Object.assign(a,w),w=null,typeof WebAssembly!="object"&&de("no native wasm support detected");var N,he=!1,ie,ae,E,Y,ue;function Re(){var r=N.buffer;a.HEAP8=ie=new Int8Array(r),a.HEAP16=new Int16Array(r),a.HEAPU8=ae=new Uint8Array(r),a.HEAPU16=new Uint16Array(r),a.HEAP32=E=new Int32Array(r),a.HEAPU32=Y=new Uint32Array(r),a.HEAPF32=new Float32Array(r),a.HEAPF64=ue=new Float64Array(r)}var Ie=[],ee=[],j=[],ce=0,P=null,te=null;function de(r){throw r="Aborted("+r+")",x(r),he=!0,r=new WebAssembly.RuntimeError(r+". Build with -sASSERTIONS for more info."),l(r),r}var ge=r=>r.startsWith("data:application/octet-stream;base64,"),ye=r=>r.startsWith("file://"),J;if(J="ort-wasm.wasm",!ge(J)){var fe=J;J=a.locateFile?a.locateFile(fe,I):I+fe}function we(r){if(U)return U(r);throw"both async and sync fetching of the wasm failed"}function Ae(r){if(i||A){if(typeof fetch=="function"&&!ye(r))return fetch(r,{credentials:"same-origin"}).then(o=>{if(!o.ok)throw"failed to load wasm binary file at \'"+r+"\'";return o.arrayBuffer()}).catch(()=>we(r));if(F)return new Promise((o,s)=>{F(r,m=>o(new Uint8Array(m)),s)})}return Promise.resolve().then(()=>we(r))}function Me(r,o,s){return Ae(r).then(m=>WebAssembly.instantiate(m,o)).then(m=>m).then(s,m=>{x(`failed to asynchronously prepare wasm: ${m}`),de(m)})}function Fe(r,o){var s=J;return typeof WebAssembly.instantiateStreaming!="function"||ge(s)||ye(s)||D||typeof fetch!="function"?Me(s,r,o):fetch(s,{credentials:"same-origin"}).then(m=>WebAssembly.instantiateStreaming(m,r).then(o,function(O){return x(`wasm streaming compile failed: ${O}`),x("falling back to ArrayBuffer instantiation"),Me(s,r,o)}))}var Ee,pe={919888:(r,o,s,m)=>{if(typeof a>"u"||!a.za)return 1;if(r=be(r>>>0),r.startsWith("./")&&(r=r.substring(2)),r=a.za.get(r),!r)return 2;if(o>>>=0,s>>>=0,o+s>r.byteLength)return 3;try{return ae.set(r.subarray(o,o+s),m>>>0>>>0),0}catch{return 4}}};function Oe(r){this.xa=r-24,this.Ha=function(o){Y[this.xa+4>>>2>>>0]=o},this.Ga=function(o){Y[this.xa+8>>>2>>>0]=o},this.Aa=function(o,s){this.Fa(),this.Ha(o),this.Ga(s)},this.Fa=function(){Y[this.xa+16>>>2>>>0]=0}}var ve=0,re=0,Z=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ce=(r,o,s)=>{o>>>=0;var m=o+s;for(s=o;r[s]&&!(s>=m);)++s;if(16O?m+=String.fromCharCode(O):(O-=65536,m+=String.fromCharCode(55296|O>>10,56320|O&1023))}}else m+=String.fromCharCode(O)}return m},be=(r,o)=>(r>>>=0)?Ce(ae,r,o):"",_e=r=>{for(var o=0,s=0;s=m?o++:2047>=m?o+=2:55296<=m&&57343>=m?(o+=4,++s):o+=3}return o},ke=(r,o,s,m)=>{if(s>>>=0,!(0=R){var K=r.charCodeAt(++S);R=65536+((R&1023)<<10)|K&1023}if(127>=R){if(s>=m)break;o[s++>>>0]=R}else{if(2047>=R){if(s+1>=m)break;o[s++>>>0]=192|R>>6}else{if(65535>=R){if(s+2>=m)break;o[s++>>>0]=224|R>>12}else{if(s+3>=m)break;o[s++>>>0]=240|R>>18,o[s++>>>0]=128|R>>12&63}o[s++>>>0]=128|R>>6&63}o[s++>>>0]=128|R&63}}return o[s>>>0]=0,s-O},Ue=r=>r%4===0&&(r%100!==0||r%400===0),ze=[0,31,60,91,121,152,182,213,244,274,305,335],at=[0,31,59,90,120,151,181,212,243,273,304,334],De=r=>{var o=_e(r)+1,s=st(o);return s&&ke(r,ae,s,o),s},Ne=[],Pe={},He=()=>{if(!$e){var r={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:g||"./this.program"},o;for(o in Pe)Pe[o]===void 0?delete r[o]:r[o]=Pe[o];var s=[];for(o in r)s.push(`${o}=${r[o]}`);$e=s}return $e},$e,Le=[null,[],[]],qe=[31,29,31,30,31,30,31,31,30,31,30,31],Ve=[31,28,31,30,31,30,31,31,30,31,30,31];function Ge(r){var o=Array(_e(r)+1);return ke(r,o,0,o.length),o}function ot(r,o,s,m){function O(c,W,G){for(c=typeof c=="number"?c.toString():c||"";c.lengthKe?-1:0Se-c.getDate())W-=Se-c.getDate()+1,c.setDate(1),11>G?c.setMonth(G+1):(c.setMonth(0),c.setFullYear(c.getFullYear()+1));else{c.setDate(c.getDate()+W);break}}return G=new Date(c.getFullYear()+1,0,4),W=K(new Date(c.getFullYear(),0,4)),G=K(G),0>=R(W,c)?0>=R(G,c)?c.getFullYear()+1:c.getFullYear():c.getFullYear()-1}r>>>=0,o>>>=0,s>>>=0,m>>>=0;var oe=Y[m+40>>>2>>>0];m={Da:E[m>>>2>>>0],Ca:E[m+4>>>2>>>0],va:E[m+8>>>2>>>0],ya:E[m+12>>>2>>>0],wa:E[m+16>>>2>>>0],ua:E[m+20>>>2>>>0],oa:E[m+24>>>2>>>0],ta:E[m+28>>>2>>>0],Ia:E[m+32>>>2>>>0],Ba:E[m+36>>>2>>>0],Ea:oe?be(oe):""},s=be(s),oe={"%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"};for(var se in oe)s=s.replace(new RegExp(se,"g"),oe[se]);var Qe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ze="January February March April May June July August September October November December".split(" ");oe={"%a":c=>Qe[c.oa].substring(0,3),"%A":c=>Qe[c.oa],"%b":c=>Ze[c.wa].substring(0,3),"%B":c=>Ze[c.wa],"%C":c=>S((c.ua+1900)/100|0,2),"%d":c=>S(c.ya,2),"%e":c=>O(c.ya,2," "),"%g":c=>le(c).toString().substring(2),"%G":c=>le(c),"%H":c=>S(c.va,2),"%I":c=>(c=c.va,c==0?c=12:12{for(var W=0,G=0;G<=c.wa-1;W+=(Ue(c.ua+1900)?qe:Ve)[G++]);return S(c.ya+W,3)},"%m":c=>S(c.wa+1,2),"%M":c=>S(c.Ca,2),"%n":()=>`\n`,"%p":c=>0<=c.va&&12>c.va?"AM":"PM","%S":c=>S(c.Da,2),"%t":()=>" ","%u":c=>c.oa||7,"%U":c=>S(Math.floor((c.ta+7-c.oa)/7),2),"%V":c=>{var W=Math.floor((c.ta+7-(c.oa+6)%7)/7);if(2>=(c.oa+371-c.ta-2)%7&&W++,W)W==53&&(G=(c.oa+371-c.ta)%7,G==4||G==3&&Ue(c.ua)||(W=1));else{W=52;var G=(c.oa+7-c.ta-1)%7;(G==4||G==5&&Ue(c.ua%400-1))&&W++}return S(W,2)},"%w":c=>c.oa,"%W":c=>S(Math.floor((c.ta+7-(c.oa+6)%7)/7),2),"%y":c=>(c.ua+1900).toString().substring(2),"%Y":c=>c.ua+1900,"%z":c=>{c=c.Ba;var W=0<=c;return c=Math.abs(c)/60,(W?"+":"-")+("0000"+(c/60*100+c%60)).slice(-4)},"%Z":c=>c.Ea,"%%":()=>"%"},s=s.replace(/%%/g,"\\0\\0");for(se in oe)s.includes(se)&&(s=s.replace(new RegExp(se,"g"),oe[se](m)));return s=s.replace(/\\0\\0/g,"%"),se=Ge(s),se.length>o?0:(ie.set(se,r>>>0),se.length-1)}var $={a:function(r,o,s){throw r>>>=0,new Oe(r).Aa(o>>>0,s>>>0),ve=r,re++,ve},e:function(){return 0},H:function(){},x:function(){},z:function(){},J:function(){return 0},F:function(){},A:function(){},E:function(){},g:function(){},y:function(){},v:function(){},G:function(){},w:function(){},k:()=>1,n:function(r,o,s){r=o+2097152>>>0<4194305-!!r?(r>>>0)+4294967296*o:NaN,s>>>=0,r=new Date(1e3*r),E[s>>>2>>>0]=r.getUTCSeconds(),E[s+4>>>2>>>0]=r.getUTCMinutes(),E[s+8>>>2>>>0]=r.getUTCHours(),E[s+12>>>2>>>0]=r.getUTCDate(),E[s+16>>>2>>>0]=r.getUTCMonth(),E[s+20>>>2>>>0]=r.getUTCFullYear()-1900,E[s+24>>>2>>>0]=r.getUTCDay(),E[s+28>>>2>>>0]=(r.getTime()-Date.UTC(r.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},o:function(r,o,s){r=o+2097152>>>0<4194305-!!r?(r>>>0)+4294967296*o:NaN,s>>>=0,r=new Date(1e3*r),E[s>>>2>>>0]=r.getSeconds(),E[s+4>>>2>>>0]=r.getMinutes(),E[s+8>>>2>>>0]=r.getHours(),E[s+12>>>2>>>0]=r.getDate(),E[s+16>>>2>>>0]=r.getMonth(),E[s+20>>>2>>>0]=r.getFullYear()-1900,E[s+24>>>2>>>0]=r.getDay(),E[s+28>>>2>>>0]=(Ue(r.getFullYear())?ze:at)[r.getMonth()]+r.getDate()-1|0,E[s+36>>>2>>>0]=-(60*r.getTimezoneOffset()),o=new Date(r.getFullYear(),6,1).getTimezoneOffset();var m=new Date(r.getFullYear(),0,1).getTimezoneOffset();E[s+32>>>2>>>0]=(o!=m&&r.getTimezoneOffset()==Math.min(m,o))|0},p:function(r){r>>>=0;var o=new Date(E[r+20>>>2>>>0]+1900,E[r+16>>>2>>>0],E[r+12>>>2>>>0],E[r+8>>>2>>>0],E[r+4>>>2>>>0],E[r>>>2>>>0],0),s=E[r+32>>>2>>>0],m=o.getTimezoneOffset(),O=new Date(o.getFullYear(),6,1).getTimezoneOffset(),S=new Date(o.getFullYear(),0,1).getTimezoneOffset(),R=Math.min(S,O);return 0>s?E[r+32>>>2>>>0]=+(O!=S&&R==m):0>>2>>>0]=o.getDay(),E[r+28>>>2>>>0]=(Ue(o.getFullYear())?ze:at)[o.getMonth()]+o.getDate()-1|0,E[r>>>2>>>0]=o.getSeconds(),E[r+4>>>2>>>0]=o.getMinutes(),E[r+8>>>2>>>0]=o.getHours(),E[r+12>>>2>>>0]=o.getDate(),E[r+16>>>2>>>0]=o.getMonth(),E[r+20>>>2>>>0]=o.getYear(),r=o.getTime(),isNaN(r)?(E[Ye()>>>2>>>0]=61,r=-1):r/=1e3,Je((Ee=r,1<=+Math.abs(Ee)?0>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)),r>>>0},l:function(){return-52},m:function(){},t:function(r,o,s){function m(le){return(le=le.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?le[1]:"GMT"}s>>>=0;var O=new Date().getFullYear(),S=new Date(O,0,1),R=new Date(O,6,1);O=S.getTimezoneOffset();var K=R.getTimezoneOffset();Y[r>>>0>>>2>>>0]=60*Math.max(O,K),E[o>>>0>>>2>>>0]=+(O!=K),r=m(S),o=m(R),r=De(r),o=De(o),K>>2>>>0]=r,Y[s+4>>>2>>>0]=o):(Y[s>>>2>>>0]=o,Y[s+4>>>2>>>0]=r)},d:()=>{de("")},B:function(r,o,s){r>>>=0,o>>>=0,s>>>=0,Ne.length=0;for(var m;m=ae[o++>>>0];){var O=m!=105;O&=m!=112,s+=O&&s%8?4:0,Ne.push(m==112?Y[s>>>2>>>0]:m==105?E[s>>>2>>>0]:ue[s>>>3>>>0]),s+=O?8:4}return pe[r].apply(null,Ne)},h:()=>Date.now(),u:function(){return 4294901760},b:()=>performance.now(),I:function(r,o,s){return o>>>=0,ae.copyWithin(r>>>0>>>0,o>>>0,o+(s>>>0)>>>0)},s:function(r){r>>>=0;var o=ae.length;if(4294901760=s;s*=2){var m=o*(1+.2/s);m=Math.min(m,r+100663296);var O=Math;m=Math.max(r,m);e:{O=(O.min.call(O,4294901760,m+(65536-m%65536)%65536)-N.buffer.byteLength+65535)/65536;try{N.grow(O),Re();var S=1;break e}catch{}S=void 0}if(S)return!0}return!1},C:function(r,o){r>>>=0,o>>>=0;var s=0;return He().forEach((m,O)=>{var S=o+s;for(O=Y[r+4*O>>>2>>>0]=S,S=0;S>>0>>>0]=m.charCodeAt(S);ie[O>>>0>>>0]=0,s+=m.length+1}),0},D:function(r,o){r>>>=0,o>>>=0;var s=He();Y[r>>>2>>>0]=s.length;var m=0;return s.forEach(O=>m+=O.length+1),Y[o>>>2>>>0]=m,0},f:()=>52,j:function(){return 52},q:function(){return 70},i:function(r,o,s,m){o>>>=0,s>>>=0,m>>>=0;for(var O=0,S=0;S>>2>>>0],K=Y[o+4>>>2>>>0];o+=8;for(var le=0;le>>0],se=Le[r];oe===0||oe===10?((r===1?_:x)(Ce(se,0)),se.length=0):se.push(oe)}O+=K}return Y[m>>>2>>>0]=O,0},r:ot,c:function(r,o,s,m){return ot(r>>>0,o>>>0,s>>>0,m>>>0)}},C=function(){function r(s){return C=s.exports,C=ut(),N=C.K,Re(),ee.unshift(C.L),ce--,ce==0&&(P!==null&&(clearInterval(P),P=null),te&&(s=te,te=null,s())),C}var o={a:$};if(ce++,a.instantiateWasm)try{return a.instantiateWasm(o,r)}catch(s){x(`Module.instantiateWasm callback failed with error: ${s}`),l(s)}return Fe(o,function(s){r(s.instance)}).catch(l),{}}();a._OrtInit=(r,o)=>(a._OrtInit=C.M)(r,o),a._OrtGetLastError=(r,o)=>(a._OrtGetLastError=C.N)(r,o),a._OrtCreateSessionOptions=(r,o,s,m,O,S,R,K,le,oe)=>(a._OrtCreateSessionOptions=C.O)(r,o,s,m,O,S,R,K,le,oe),a._OrtAppendExecutionProvider=(r,o)=>(a._OrtAppendExecutionProvider=C.P)(r,o),a._OrtAddFreeDimensionOverride=(r,o,s)=>(a._OrtAddFreeDimensionOverride=C.Q)(r,o,s),a._OrtAddSessionConfigEntry=(r,o,s)=>(a._OrtAddSessionConfigEntry=C.R)(r,o,s),a._OrtReleaseSessionOptions=r=>(a._OrtReleaseSessionOptions=C.S)(r),a._OrtCreateSession=(r,o,s)=>(a._OrtCreateSession=C.T)(r,o,s),a._OrtReleaseSession=r=>(a._OrtReleaseSession=C.U)(r),a._OrtGetInputOutputCount=(r,o,s)=>(a._OrtGetInputOutputCount=C.V)(r,o,s),a._OrtGetInputName=(r,o)=>(a._OrtGetInputName=C.W)(r,o),a._OrtGetOutputName=(r,o)=>(a._OrtGetOutputName=C.X)(r,o),a._OrtFree=r=>(a._OrtFree=C.Y)(r),a._OrtCreateTensor=(r,o,s,m,O,S)=>(a._OrtCreateTensor=C.Z)(r,o,s,m,O,S),a._OrtGetTensorData=(r,o,s,m,O)=>(a._OrtGetTensorData=C._)(r,o,s,m,O),a._OrtReleaseTensor=r=>(a._OrtReleaseTensor=C.$)(r),a._OrtCreateRunOptions=(r,o,s,m)=>(a._OrtCreateRunOptions=C.aa)(r,o,s,m),a._OrtAddRunConfigEntry=(r,o,s)=>(a._OrtAddRunConfigEntry=C.ba)(r,o,s),a._OrtReleaseRunOptions=r=>(a._OrtReleaseRunOptions=C.ca)(r),a._OrtCreateBinding=r=>(a._OrtCreateBinding=C.da)(r),a._OrtBindInput=(r,o,s)=>(a._OrtBindInput=C.ea)(r,o,s),a._OrtBindOutput=(r,o,s,m)=>(a._OrtBindOutput=C.fa)(r,o,s,m),a._OrtClearBoundOutputs=r=>(a._OrtClearBoundOutputs=C.ga)(r),a._OrtReleaseBinding=r=>(a._OrtReleaseBinding=C.ha)(r),a._OrtRunWithBinding=(r,o,s,m,O)=>(a._OrtRunWithBinding=C.ia)(r,o,s,m,O),a._OrtRun=(r,o,s,m,O,S,R,K)=>(a._OrtRun=C.ja)(r,o,s,m,O,S,R,K),a._OrtEndProfiling=r=>(a._OrtEndProfiling=C.ka)(r);var Ye=()=>(Ye=C.la)(),st=a._malloc=r=>(st=a._malloc=C.ma)(r);a._free=r=>(a._free=C.na)(r);var Je=r=>(Je=C.pa)(r),it=()=>(it=C.qa)(),M=r=>(M=C.ra)(r),Be=r=>(Be=C.sa)(r);function ut(){var r=C;r=Object.assign({},r);var o=m=>()=>m()>>>0,s=m=>O=>m(O)>>>0;return r.la=o(r.la),r.ma=s(r.ma),r.qa=o(r.qa),r.sa=s(r.sa),r}a.stackAlloc=Be,a.stackSave=it,a.stackRestore=M,a.UTF8ToString=be,a.stringToUTF8=(r,o,s)=>ke(r,ae,o,s),a.lengthBytesUTF8=_e;var xe;te=function r(){xe||Xe(),xe||(te=r)};function Xe(){if(!(0pr)});var hr=et(()=>{});var yr=et(()=>{});var br={};Tt(br,{cpus:()=>rn});var rn,wr=St(()=>{rn=void 0});var _r=et((vr,Ft)=>{"use strict";var Or=(()=>{var u=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(u=u||__filename),function(d={}){function a(){return j.buffer!=de.buffer&&we(),de}function h(){return j.buffer!=de.buffer&&we(),ge}function l(){return j.buffer!=de.buffer&&we(),ye}function w(){return j.buffer!=de.buffer&&we(),J}function g(){return j.buffer!=de.buffer&&we(),fe}var i=d,A,D;i.ready=new Promise((e,t)=>{A=e,D=t});var I=Object.assign({},i),B="./this.program",F=(e,t)=>{throw t},U=typeof window=="object",k=typeof importScripts=="function",L=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",_=i.ENVIRONMENT_IS_PTHREAD||!1,x="";function N(e){return i.locateFile?i.locateFile(e,x):x+e}var he,ie,ae;if(L){var E=(Mt(),tt(At)),Y=(Dt(),tt(Ct));x=k?Y.dirname(x)+"/":__dirname+"/",he=(t,n)=>(t=be(t)?new URL(t):Y.normalize(t),E.readFileSync(t,n?void 0:"utf8")),ae=t=>(t=he(t,!0),t.buffer||(t=new Uint8Array(t)),t),ie=(t,n,f,y=!0)=>{t=be(t)?new URL(t):Y.normalize(t),E.readFile(t,y?void 0:"utf8",(b,v)=>{b?f(b):n(y?v.buffer:v)})},!i.thisProgram&&1{throw process.exitCode=t,n},i.inspect=()=>"[Emscripten Module object]";let e;try{e=hr()}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}global.Worker=e.Worker}else(U||k)&&(k?x=self.location.href:typeof document<"u"&&document.currentScript&&(x=document.currentScript.src),typeof u<"u"&&u&&(x=u),x.indexOf("blob:")!==0?x=x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1):x="",L||(he=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},k&&(ae=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),ie=(e,t,n)=>{var f=new XMLHttpRequest;f.open("GET",e,!0),f.responseType="arraybuffer",f.onload=()=>{f.status==200||f.status==0&&f.response?t(f.response):n()},f.onerror=n,f.send(null)}));L&&typeof performance>"u"&&(global.performance=yr().performance);var ue=console.log.bind(console),Re=console.error.bind(console);L&&(ue=(...e)=>E.writeSync(1,e.join(" ")+`\n`),Re=(...e)=>E.writeSync(2,e.join(" ")+`\n`));var Ie=ue,ee=Re;Object.assign(i,I),I=null,typeof WebAssembly!="object"&&Z("no native wasm support detected");var j,ce,P=!1,te,de,ge,ye,J,fe;function we(){var e=j.buffer;i.HEAP8=de=new Int8Array(e),i.HEAP16=new Int16Array(e),i.HEAPU8=ge=new Uint8Array(e),i.HEAPU16=new Uint16Array(e),i.HEAP32=ye=new Int32Array(e),i.HEAPU32=J=new Uint32Array(e),i.HEAPF32=new Float32Array(e),i.HEAPF64=fe=new Float64Array(e)}var Ae=16777216;if(_)j=i.wasmMemory;else if(i.wasmMemory)j=i.wasmMemory;else if(j=new WebAssembly.Memory({initial:Ae/65536,maximum:65536,shared:!0}),!(j.buffer instanceof SharedArrayBuffer))throw ee("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"),L&&ee("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");we(),Ae=j.buffer.byteLength;var Me=[],Fe=[],Ee=[],pe=0,Oe=null,ve=null;function re(){if(pe--,pe==0&&(Oe!==null&&(clearInterval(Oe),Oe=null),ve)){var e=ve;ve=null,e()}}function Z(e){throw e="Aborted("+e+")",ee(e),P=!0,te=1,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),D(e),e}var Ce=e=>e.startsWith("data:application/octet-stream;base64,"),be=e=>e.startsWith("file://"),_e;_e="ort-wasm-threaded.wasm",Ce(_e)||(_e=N(_e));function ke(e){if(ae)return ae(e);throw"both async and sync fetching of the wasm failed"}function Ue(e){if(U||k){if(typeof fetch=="function"&&!be(e))return fetch(e,{credentials:"same-origin"}).then(t=>{if(!t.ok)throw"failed to load wasm binary file at \'"+e+"\'";return t.arrayBuffer()}).catch(()=>ke(e));if(ie)return new Promise((t,n)=>{ie(e,f=>t(new Uint8Array(f)),n)})}return Promise.resolve().then(()=>ke(e))}function ze(e,t,n){return Ue(e).then(f=>WebAssembly.instantiate(f,t)).then(f=>f).then(n,f=>{ee(`failed to asynchronously prepare wasm: ${f}`),Z(f)})}function at(e,t){var n=_e;return typeof WebAssembly.instantiateStreaming!="function"||Ce(n)||be(n)||L||typeof fetch!="function"?ze(n,e,t):fetch(n,{credentials:"same-origin"}).then(f=>WebAssembly.instantiateStreaming(f,e).then(t,function(y){return ee(`wasm streaming compile failed: ${y}`),ee("falling back to ArrayBuffer instantiation"),ze(n,e,t)}))}var De,Ne={921276:(e,t,n,f)=>{if(typeof i>"u"||!i.cb)return 1;if(e=Ge(e>>>0),e.startsWith("./")&&(e=e.substring(2)),e=i.cb.get(e),!e)return 2;if(t>>>=0,n>>>=0,f>>>=0,t+n>e.byteLength)return 3;try{return h().set(e.subarray(t,t+n),f>>>0),0}catch{return 4}}};function Pe(e){this.name="ExitStatus",this.message=`Program terminated with exit(${e})`,this.status=e}var He=e=>{e.terminate(),e.onmessage=()=>{}},$e=e=>{M.Pa.length==0&&(Je(),M.Ya(M.Pa[0]));var t=M.Pa.pop();if(!t)return 6;M.Qa.push(t),M.Ma[e.Oa]=t,t.Oa=e.Oa;var n={cmd:"run",start_routine:e.kb,arg:e.hb,pthread_ptr:e.Oa};return L&&t.unref(),t.postMessage(n,e.qb),0},Le=0,qe=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ve=(e,t,n)=>{t>>>=0;var f=t+n;for(n=t;e[n]&&!(n>=f);)++n;if(16y?f+=String.fromCharCode(y):(y-=65536,f+=String.fromCharCode(55296|y>>10,56320|y&1023))}}else f+=String.fromCharCode(y)}return f},Ge=(e,t)=>(e>>>=0)?Ve(h(),e,t):"",ot=e=>{var t=vt();return e=e(),ct(t),e};function $(e,t){var n=arguments.length-2,f=arguments;return ot(()=>{for(var y=_t(8*n),b=y>>>3,v=0;v>>0]=z}return ar(e,n,y,t)})}function C(e){if(_)return $(0,1,e);te=e,0{if(te=e,_)throw ut(e),"unwind";C(e)};function st(){for(var e=i.numThreads;e--;)Je();Me.unshift(()=>{pe++,it(()=>re())})}function Je(){var e=N("ort-wasm-threaded.worker.js");e=new Worker(e),M.Pa.push(e)}function it(e){_?e():Promise.all(M.Pa.map(M.Ya)).then(e)}var M={Pa:[],Qa:[],bb:[],Ma:{},Wa(){_?(M.receiveObjectTransfer=M.jb,M.threadInitTLS=M.ab,M.setExitStatus=M.$a):st()},$a:e=>te=e,tb:["$terminateWorker"],lb:()=>{for(var e of M.Qa)He(e);for(e of M.Pa)He(e);M.Pa=[],M.Qa=[],M.Ma=[]},Za:e=>{var t=e.Oa;delete M.Ma[t],M.Pa.push(e),M.Qa.splice(M.Qa.indexOf(e),1),e.Oa=0,wt(t)},jb(){},ab(){M.bb.forEach(e=>e())},Ya:e=>new Promise(t=>{e.onmessage=b=>{b=b.data;var v=b.cmd;if(b.targetThread&&b.targetThread!=lt()){var z=M.Ma[b.targetThread];z?z.postMessage(b,b.transferList):ee(`Internal error! Worker sent a message "${v}" to target pthread ${b.targetThread}, but that thread no longer exists!`)}else v==="checkMailbox"?ft():v==="spawnThread"?$e(b):v==="cleanupThread"?M.Za(M.Ma[b.thread]):v==="killThread"?(b=b.thread,v=M.Ma[b],delete M.Ma[b],He(v),wt(b),M.Qa.splice(M.Qa.indexOf(v),1),v.Oa=0):v==="cancelThread"?M.Ma[b.thread].postMessage({cmd:"cancel"}):v==="loaded"?(e.loaded=!0,L&&!e.Oa&&e.unref(),t(e)):v==="alert"?alert(`Thread ${b.threadId}: ${b.text}`):b.target==="setimmediate"?e.postMessage(b):v==="callHandler"?i[b.handler](...b.args):v&&ee(`worker sent an unknown command ${v}`)},e.onerror=b=>{throw ee(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b},L&&(e.on("message",b=>e.onmessage({data:b})),e.on("error",b=>e.onerror(b)));var n=[],f=["onExit"],y;for(y of f)i.hasOwnProperty(y)&&n.push(y);e.postMessage({cmd:"load",handlers:n,urlOrBlob:i.mainScriptUrlOrBlob||u,wasmMemory:j,wasmModule:ce})})};i.PThread=M;var Be=e=>{for(;0{var e=lt(),t=w()[e+52>>>2>>>0];e=w()[e+56>>>2>>>0],ir(t,t-e),ct(t)};function ut(e){if(_)return $(1,0,e);Ye(e)}var xe=[],Xe;i.invokeEntryPoint=(e,t)=>{var n=xe[e];n||(e>=xe.length&&(xe.length=e+1),xe[e]=n=Xe.get(e)),e=n(t),0>>2>>>0]=t},this.fb=function(t){w()[this.Va+8>>>2>>>0]=t},this.Wa=function(t,n){this.eb(),this.gb(t),this.fb(n)},this.eb=function(){w()[this.Va+16>>>2>>>0]=0}}var o=0,s=0;function m(e,t,n,f){return _?$(2,1,e,t,n,f):O(e,t,n,f)}function O(e,t,n,f){if(e>>>=0,t>>>=0,n>>>=0,f>>>=0,typeof SharedArrayBuffer>"u")return ee("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var y=[];return _&&y.length===0?m(e,t,n,f):(e={kb:n,Oa:e,hb:f,qb:y},_?(e.sb="spawnThread",postMessage(e,y),0):$e(e))}function S(e,t,n){return _?$(3,1,e,t,n):0}function R(e,t){if(_)return $(4,1,e,t)}var K=e=>{for(var t=0,n=0;n=f?t++:2047>=f?t+=2:55296<=f&&57343>=f?(t+=4,++n):t+=3}return t},le=(e,t,n,f)=>{if(n>>>=0,!(0=v){var z=e.charCodeAt(++b);v=65536+((v&1023)<<10)|z&1023}if(127>=v){if(n>=f)break;t[n++>>>0]=v}else{if(2047>=v){if(n+1>=f)break;t[n++>>>0]=192|v>>6}else{if(65535>=v){if(n+2>=f)break;t[n++>>>0]=224|v>>12}else{if(n+3>=f)break;t[n++>>>0]=240|v>>18,t[n++>>>0]=128|v>>12&63}t[n++>>>0]=128|v>>6&63}t[n++>>>0]=128|v&63}}return t[n>>>0]=0,n-y},oe=(e,t,n)=>le(e,h(),t,n);function se(e,t){if(_)return $(5,1,e,t)}function Qe(e,t,n){if(_)return $(6,1,e,t,n)}function Ze(e,t,n){return _?$(7,1,e,t,n):0}function c(e,t){if(_)return $(8,1,e,t)}function W(e,t,n){if(_)return $(9,1,e,t,n)}function G(e,t,n,f){if(_)return $(10,1,e,t,n,f)}function Se(e,t,n,f){if(_)return $(11,1,e,t,n,f)}function Ke(e,t,n,f){if(_)return $(12,1,e,t,n,f)}function Bt(e){if(_)return $(13,1,e)}function Wt(e,t){if(_)return $(14,1,e,t)}function kt(e,t,n){if(_)return $(15,1,e,t,n)}function mt(e){e>>>=0,typeof Atomics.rb=="function"&&(Atomics.rb(l(),e>>>2,e).value.then(ft),e+=128,Atomics.store(l(),e>>>2,1))}i.__emscripten_thread_mailbox_await=mt;var ft=()=>{var e=lt();if(e&&(mt(e),e=or,!P))try{if(e(),!(0e%4===0&&(e%100!==0||e%400===0),Nt=[0,31,60,91,121,152,182,213,244,274,305,335],Ht=[0,31,59,90,120,151,181,212,243,273,304,334];function $t(e,t,n,f,y,b,v,z){return _?$(16,1,e,t,n,f,y,b,v,z):-52}function Gt(e,t,n,f,y,b,v){if(_)return $(17,1,e,t,n,f,y,b,v)}var Yt=e=>{var t=K(e)+1,n=rr(t);return n&&oe(e,n,t),n},ht=[],yt={},jt=()=>{if(!bt){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:B||"./this.program"},t;for(t in yt)yt[t]===void 0?delete e[t]:e[t]=yt[t];var n=[];for(t in e)n.push(`${t}=${e[t]}`);bt=n}return bt},bt;function zt(e,t){if(_)return $(18,1,e,t);e>>>=0,t>>>=0;var n=0;return jt().forEach((f,y)=>{var b=t+n;for(y=w()[e+4*y>>>2>>>0]=b,b=0;b>>0>>>0]=f.charCodeAt(b);a()[y>>>0>>>0]=0,n+=f.length+1}),0}function qt(e,t){if(_)return $(19,1,e,t);e>>>=0,t>>>=0;var n=jt();w()[e>>>2>>>0]=n.length;var f=0;return n.forEach(y=>f+=y.length+1),w()[t>>>2>>>0]=f,0}function Vt(e){return _?$(20,1,e):52}function Jt(e,t,n,f){return _?$(21,1,e,t,n,f):52}function Xt(e,t,n,f,y){return _?$(22,1,e,t,n,f,y):70}var Gr=[null,[],[]];function Qt(e,t,n,f){if(_)return $(23,1,e,t,n,f);t>>>=0,n>>>=0,f>>>=0;for(var y=0,b=0;b>>2>>>0],z=w()[t+4>>>2>>>0];t+=8;for(var Te=0;Te>>0],me=Gr[e];ne===0||ne===10?((e===1?Ie:ee)(Ve(me,0)),me.length=0):me.push(ne)}y+=z}return w()[f>>>2>>>0]=y,0}var Zt=[31,29,31,30,31,30,31,31,30,31,30,31],Kt=[31,28,31,30,31,30,31,31,30,31,30,31];function Yr(e){var t=Array(K(e)+1);return le(e,t,0,t.length),t}var jr=(e,t)=>{a().set(e,t>>>0)};function er(e,t,n,f){function y(p,H,q){for(p=typeof p=="number"?p.toString():p||"";p.lengthcr?-1:0We-p.getDate())H-=We-p.getDate()+1,p.setDate(1),11>q?p.setMonth(q+1):(p.setMonth(0),p.setFullYear(p.getFullYear()+1));else{p.setDate(p.getDate()+H);break}}return q=new Date(p.getFullYear()+1,0,4),H=z(new Date(p.getFullYear(),0,4)),q=z(q),0>=v(H,p)?0>=v(q,p)?p.getFullYear()+1:p.getFullYear():p.getFullYear()-1}e>>>=0,t>>>=0,n>>>=0,f>>>=0;var ne=w()[f+40>>>2>>>0];f={ob:l()[f>>>2>>>0],nb:l()[f+4>>>2>>>0],Ta:l()[f+8>>>2>>>0],Xa:l()[f+12>>>2>>>0],Ua:l()[f+16>>>2>>>0],Sa:l()[f+20>>>2>>>0],Na:l()[f+24>>>2>>>0],Ra:l()[f+28>>>2>>>0],ub:l()[f+32>>>2>>>0],mb:l()[f+36>>>2>>>0],pb:ne?Ge(ne):""},n=Ge(n),ne={"%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"};for(var me in ne)n=n.replace(new RegExp(me,"g"),ne[me]);var fr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),lr="January February March April May June July August September October November December".split(" ");ne={"%a":p=>fr[p.Na].substring(0,3),"%A":p=>fr[p.Na],"%b":p=>lr[p.Ua].substring(0,3),"%B":p=>lr[p.Ua],"%C":p=>b((p.Sa+1900)/100|0,2),"%d":p=>b(p.Xa,2),"%e":p=>y(p.Xa,2," "),"%g":p=>Te(p).toString().substring(2),"%G":p=>Te(p),"%H":p=>b(p.Ta,2),"%I":p=>(p=p.Ta,p==0?p=12:12{for(var H=0,q=0;q<=p.Ua-1;H+=(je(p.Sa+1900)?Zt:Kt)[q++]);return b(p.Xa+H,3)},"%m":p=>b(p.Ua+1,2),"%M":p=>b(p.nb,2),"%n":()=>`\n`,"%p":p=>0<=p.Ta&&12>p.Ta?"AM":"PM","%S":p=>b(p.ob,2),"%t":()=>" ","%u":p=>p.Na||7,"%U":p=>b(Math.floor((p.Ra+7-p.Na)/7),2),"%V":p=>{var H=Math.floor((p.Ra+7-(p.Na+6)%7)/7);if(2>=(p.Na+371-p.Ra-2)%7&&H++,H)H==53&&(q=(p.Na+371-p.Ra)%7,q==4||q==3&&je(p.Sa)||(H=1));else{H=52;var q=(p.Na+7-p.Ra-1)%7;(q==4||q==5&&je(p.Sa%400-1))&&H++}return b(H,2)},"%w":p=>p.Na,"%W":p=>b(Math.floor((p.Ra+7-(p.Na+6)%7)/7),2),"%y":p=>(p.Sa+1900).toString().substring(2),"%Y":p=>p.Sa+1900,"%z":p=>{p=p.mb;var H=0<=p;return p=Math.abs(p)/60,(H?"+":"-")+("0000"+(p/60*100+p%60)).slice(-4)},"%Z":p=>p.pb,"%%":()=>"%"},n=n.replace(/%%/g,"\\0\\0");for(me in ne)n.includes(me)&&(n=n.replace(new RegExp(me,"g"),ne[me](f)));return n=n.replace(/\\0\\0/g,"%"),me=Yr(n),me.length>t?0:(jr(me,e),me.length-1)}M.Wa();var zr=[C,ut,m,S,R,se,Qe,Ze,c,W,G,Se,Ke,Bt,Wt,kt,$t,Gt,zt,qt,Vt,Jt,Xt,Qt],qr={b:function(e,t,n){throw e>>>=0,new r(e).Wa(t>>>0,n>>>0),o=e,s++,o},L:function(e){nr(e>>>0,!k,1,!U,131072,!1),M.ab()},j:function(e){e>>>=0,_?postMessage({cmd:"cleanupThread",thread:e}):M.Za(M.Ma[e])},H:O,h:S,S:R,D:se,F:Qe,T:Ze,Q:c,J:W,P:G,n:Se,E:Ke,B:Bt,R:Wt,C:kt,p:()=>1,z:function(e,t){e>>>=0,e==t>>>0?setTimeout(()=>ft()):_?postMessage({targetThread:e,cmd:"checkMailbox"}):(e=M.Ma[e])&&e.postMessage({cmd:"checkMailbox"})},I:function(e,t,n,f){t>>>=0,gt.length=n,f=f>>>0>>>3;for(var y=0;y>>0];return e=0>e?Ne[-e-1]:zr[e],M.ib=t,t=e.apply(null,gt),M.ib=0,t},K:mt,o:function(e){L&&M.Ma[e>>>0].ref()},s:function(e,t,n){e=t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN,n>>>=0,e=new Date(1e3*e),l()[n>>>2>>>0]=e.getUTCSeconds(),l()[n+4>>>2>>>0]=e.getUTCMinutes(),l()[n+8>>>2>>>0]=e.getUTCHours(),l()[n+12>>>2>>>0]=e.getUTCDate(),l()[n+16>>>2>>>0]=e.getUTCMonth(),l()[n+20>>>2>>>0]=e.getUTCFullYear()-1900,l()[n+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,l()[n+28>>>2>>>0]=e},t:function(e,t,n){e=t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN,n>>>=0,e=new Date(1e3*e),l()[n>>>2>>>0]=e.getSeconds(),l()[n+4>>>2>>>0]=e.getMinutes(),l()[n+8>>>2>>>0]=e.getHours(),l()[n+12>>>2>>>0]=e.getDate(),l()[n+16>>>2>>>0]=e.getMonth(),l()[n+20>>>2>>>0]=e.getFullYear()-1900,l()[n+24>>>2>>>0]=e.getDay(),t=(je(e.getFullYear())?Nt:Ht)[e.getMonth()]+e.getDate()-1|0,l()[n+28>>>2>>>0]=t,l()[n+36>>>2>>>0]=-(60*e.getTimezoneOffset()),t=new Date(e.getFullYear(),6,1).getTimezoneOffset();var f=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=(t!=f&&e.getTimezoneOffset()==Math.min(f,t))|0,l()[n+32>>>2>>>0]=e},u:function(e){e>>>=0;var t=new Date(l()[e+20>>>2>>>0]+1900,l()[e+16>>>2>>>0],l()[e+12>>>2>>>0],l()[e+8>>>2>>>0],l()[e+4>>>2>>>0],l()[e>>>2>>>0],0),n=l()[e+32>>>2>>>0],f=t.getTimezoneOffset(),y=new Date(t.getFullYear(),6,1).getTimezoneOffset(),b=new Date(t.getFullYear(),0,1).getTimezoneOffset(),v=Math.min(b,y);return 0>n?l()[e+32>>>2>>>0]=+(y!=b&&v==f):0>>2>>>0]=t.getDay(),n=(je(t.getFullYear())?Nt:Ht)[t.getMonth()]+t.getDate()-1|0,l()[e+28>>>2>>>0]=n,l()[e>>>2>>>0]=t.getSeconds(),l()[e+4>>>2>>>0]=t.getMinutes(),l()[e+8>>>2>>>0]=t.getHours(),l()[e+12>>>2>>>0]=t.getDate(),l()[e+16>>>2>>>0]=t.getMonth(),l()[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),isNaN(e)?(l()[tr()>>>2>>>0]=61,e=-1):e/=1e3,sr((De=e,1<=+Math.abs(De)?0>>0:~~+Math.ceil((De-+(~~De>>>0))/4294967296)>>>0:0)),e>>>0},q:$t,r:Gt,y:function(e,t,n){function f(ne){return(ne=ne.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?ne[1]:"GMT"}e>>>=0,t>>>=0,n>>>=0;var y=new Date().getFullYear(),b=new Date(y,0,1),v=new Date(y,6,1);y=b.getTimezoneOffset();var z=v.getTimezoneOffset(),Te=Math.max(y,z);w()[e>>>2>>>0]=60*Te,l()[t>>>2>>>0]=+(y!=z),e=f(b),t=f(v),e=Yt(e),t=Yt(t),z>>2>>>0]=e,w()[n+4>>>2>>>0]=t):(w()[n>>>2>>>0]=t,w()[n+4>>>2>>>0]=e)},c:()=>{Z("")},O:function(e,t,n){e>>>=0,t>>>=0,n>>>=0,ht.length=0;for(var f;f=h()[t++>>>0];){var y=f!=105;y&=f!=112,n+=y&&n%8?4:0,ht.push(f==112?w()[n>>>2>>>0]:f==105?l()[n>>>2>>>0]:g()[n>>>3>>>0]),n+=y?8:4}return Ne[e].apply(null,ht)},k:()=>{},i:()=>Date.now(),U:()=>{throw Le+=1,"unwind"},A:function(){return 4294901760},e:()=>performance.timeOrigin+performance.now(),f:()=>L?(wr(),tt(br)).cpus().length:navigator.hardwareConcurrency,x:function(e){e>>>=0;var t=h().length;if(e<=t||4294901760=n;n*=2){var f=t*(1+.2/n);f=Math.min(f,e+100663296);var y=Math;f=Math.max(e,f);e:{y=(y.min.call(y,4294901760,f+(65536-f%65536)%65536)-j.buffer.byteLength+65535)/65536;try{j.grow(y),we();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1},M:zt,N:qt,G:Ye,g:Vt,m:Jt,v:Xt,l:Qt,a:j||i.wasmMemory,w:er,d:function(e,t,n,f){return er(e>>>0,t>>>0,n>>>0,f>>>0)}},T=function(){function e(n,f){return T=n.exports,T=Vr(),M.bb.push(T.za),Xe=T.Aa,Fe.unshift(T.V),ce=f,re(),T}var t={a:qr};if(pe++,i.instantiateWasm)try{return i.instantiateWasm(t,e)}catch(n){ee(`Module.instantiateWasm callback failed with error: ${n}`),D(n)}return at(t,function(n){e(n.instance,n.module)}).catch(D),{}}();i._OrtInit=(e,t)=>(i._OrtInit=T.W)(e,t),i._OrtGetLastError=(e,t)=>(i._OrtGetLastError=T.X)(e,t),i._OrtCreateSessionOptions=(e,t,n,f,y,b,v,z,Te,ne)=>(i._OrtCreateSessionOptions=T.Y)(e,t,n,f,y,b,v,z,Te,ne),i._OrtAppendExecutionProvider=(e,t)=>(i._OrtAppendExecutionProvider=T.Z)(e,t),i._OrtAddFreeDimensionOverride=(e,t,n)=>(i._OrtAddFreeDimensionOverride=T._)(e,t,n),i._OrtAddSessionConfigEntry=(e,t,n)=>(i._OrtAddSessionConfigEntry=T.$)(e,t,n),i._OrtReleaseSessionOptions=e=>(i._OrtReleaseSessionOptions=T.aa)(e),i._OrtCreateSession=(e,t,n)=>(i._OrtCreateSession=T.ba)(e,t,n),i._OrtReleaseSession=e=>(i._OrtReleaseSession=T.ca)(e),i._OrtGetInputOutputCount=(e,t,n)=>(i._OrtGetInputOutputCount=T.da)(e,t,n),i._OrtGetInputName=(e,t)=>(i._OrtGetInputName=T.ea)(e,t),i._OrtGetOutputName=(e,t)=>(i._OrtGetOutputName=T.fa)(e,t),i._OrtFree=e=>(i._OrtFree=T.ga)(e),i._OrtCreateTensor=(e,t,n,f,y,b)=>(i._OrtCreateTensor=T.ha)(e,t,n,f,y,b),i._OrtGetTensorData=(e,t,n,f,y)=>(i._OrtGetTensorData=T.ia)(e,t,n,f,y),i._OrtReleaseTensor=e=>(i._OrtReleaseTensor=T.ja)(e),i._OrtCreateRunOptions=(e,t,n,f)=>(i._OrtCreateRunOptions=T.ka)(e,t,n,f),i._OrtAddRunConfigEntry=(e,t,n)=>(i._OrtAddRunConfigEntry=T.la)(e,t,n),i._OrtReleaseRunOptions=e=>(i._OrtReleaseRunOptions=T.ma)(e),i._OrtCreateBinding=e=>(i._OrtCreateBinding=T.na)(e),i._OrtBindInput=(e,t,n)=>(i._OrtBindInput=T.oa)(e,t,n),i._OrtBindOutput=(e,t,n,f)=>(i._OrtBindOutput=T.pa)(e,t,n,f),i._OrtClearBoundOutputs=e=>(i._OrtClearBoundOutputs=T.qa)(e),i._OrtReleaseBinding=e=>(i._OrtReleaseBinding=T.ra)(e),i._OrtRunWithBinding=(e,t,n,f,y)=>(i._OrtRunWithBinding=T.sa)(e,t,n,f,y),i._OrtRun=(e,t,n,f,y,b,v,z)=>(i._OrtRun=T.ta)(e,t,n,f,y,b,v,z),i._OrtEndProfiling=e=>(i._OrtEndProfiling=T.ua)(e);var tr=()=>(tr=T.va)(),lt=i._pthread_self=()=>(lt=i._pthread_self=T.wa)(),rr=i._malloc=e=>(rr=i._malloc=T.xa)(e);i._free=e=>(i._free=T.ya)(e),i.__emscripten_tls_init=()=>(i.__emscripten_tls_init=T.za)();var nr=i.__emscripten_thread_init=(e,t,n,f,y,b)=>(nr=i.__emscripten_thread_init=T.Ba)(e,t,n,f,y,b);i.__emscripten_thread_crashed=()=>(i.__emscripten_thread_crashed=T.Ca)();var ar=(e,t,n,f)=>(ar=T.Da)(e,t,n,f),wt=e=>(wt=T.Ea)(e),Ot=i.__emscripten_thread_exit=e=>(Ot=i.__emscripten_thread_exit=T.Fa)(e),or=()=>(or=T.Ga)(),sr=e=>(sr=T.Ha)(e),ir=(e,t)=>(ir=T.Ia)(e,t),vt=()=>(vt=T.Ja)(),ct=e=>(ct=T.Ka)(e),_t=e=>(_t=T.La)(e);function Vr(){var e=T;e=Object.assign({},e);var t=f=>()=>f()>>>0,n=f=>y=>f(y)>>>0;return e.va=t(e.va),e.wa=t(e.wa),e.xa=n(e.xa),e.emscripten_main_runtime_thread_id=t(e.emscripten_main_runtime_thread_id),e.Ja=t(e.Ja),e.La=n(e.La),e}i.wasmMemory=j,i.stackAlloc=_t,i.stackSave=vt,i.stackRestore=ct,i.keepRuntimeAlive=()=>0Or)});var Er=et((On,nn)=>{nn.exports=\'"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\\n\'});var Tr;Tr=gr();var an=_r(),Ut,Pt=!1,pt=!1,Sr=!1,on=u=>{if(u===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+u+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+u+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&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{return!1}},sn=()=>{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{return!1}},un=(u,d)=>u?d?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":d?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Ar=async u=>{if(Pt)return Promise.resolve();if(pt)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Sr)throw new Error("previous call to \'initializeWebAssembly()\' failed.");pt=!0;let d=u.initTimeout,a=u.numThreads,h=u.simd,l=on(a),w=h&&sn(),g=u.wasmPaths,i=typeof g=="string"?g:void 0,A=un(w,l),D=typeof g=="object"?g[A]:void 0,I=!1,B=[];if(d>0&&B.push(new Promise(F=>{setTimeout(()=>{I=!0,F()},d)})),B.push(new Promise((F,U)=>{let k=l?an:Tr,L={locateFile:(_,x)=>l&&_.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([Er()],{type:"text/javascript"})):_.endsWith(".wasm")?D||(i??x)+A:x+_};if(l)if(L.numThreads=a,typeof Blob>"u")L.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let _=`var ortWasmThreaded=${k.toString()};`;L.mainScriptUrlOrBlob=new Blob([_],{type:"text/javascript"})}k(L).then(_=>{pt=!1,Pt=!0,Ut=_,F()},_=>{pt=!1,Sr=!0,U(_)})})),await Promise.race(B),I)throw new Error(`WebAssembly backend initializing failed due to timeout: ${d}ms`)},X=()=>{if(Pt&&Ut)return Ut;throw new Error("WebAssembly is not initialized yet.")};var Q=(u,d)=>{let a=X(),h=a.lengthBytesUTF8(u)+1,l=a._malloc(h);return a.stringToUTF8(u,l,h),d.push(l),l},rt=(u,d,a,h)=>{if(typeof u=="object"&&u!==null){if(a.has(u))throw new Error("Circular reference in options");a.add(u)}Object.entries(u).forEach(([l,w])=>{let g=d?d+l:l;if(typeof w=="object")rt(w,g+".",a,h);else if(typeof w=="string"||typeof w=="number")h(g,w.toString());else if(typeof w=="boolean")h(g,w?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof w}`)})},V=u=>{let d=X(),a=d.stackSave();try{let h=d.stackAlloc(8);d._OrtGetLastError(h,h+4);let l=d.HEAP32[h/4],w=d.HEAPU32[h/4+1],g=w?d.UTF8ToString(w):"";throw new Error(`${u} ERROR_CODE: ${l}, ERROR_MESSAGE: ${g}`)}finally{d.stackRestore(a)}};var Mr=u=>{let d=X(),a=0,h=[],l=u||{};try{if(u?.logSeverityLevel===void 0)l.logSeverityLevel=2;else if(typeof u.logSeverityLevel!="number"||!Number.isInteger(u.logSeverityLevel)||u.logSeverityLevel<0||u.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${u.logSeverityLevel}`);if(u?.logVerbosityLevel===void 0)l.logVerbosityLevel=0;else if(typeof u.logVerbosityLevel!="number"||!Number.isInteger(u.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${u.logVerbosityLevel}`);u?.terminate===void 0&&(l.terminate=!1);let w=0;return u?.tag!==void 0&&(w=Q(u.tag,h)),a=d._OrtCreateRunOptions(l.logSeverityLevel,l.logVerbosityLevel,!!l.terminate,w),a===0&&V("Can\'t create run options."),u?.extra!==void 0&&rt(u.extra,"",new WeakSet,(g,i)=>{let A=Q(g,h),D=Q(i,h);d._OrtAddRunConfigEntry(a,A,D)!==0&&V(`Can\'t set a run config entry: ${g} - ${i}.`)}),[a,h]}catch(w){throw a!==0&&d._OrtReleaseRunOptions(a),h.forEach(g=>d._free(g)),w}};var fn=u=>{switch(u){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${u}`)}},ln=u=>{switch(u){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${u}`)}},cn=u=>{u.extra||(u.extra={}),u.extra.session||(u.extra.session={});let d=u.extra.session;d.use_ort_model_bytes_directly||(d.use_ort_model_bytes_directly="1"),u.executionProviders&&u.executionProviders.some(a=>(typeof a=="string"?a:a.name)==="webgpu")&&(u.enableMemPattern=!1)},dn=(u,d,a)=>{for(let h of d){let l=typeof h=="string"?h:h.name;switch(l){case"webnn":if(l="WEBNN",typeof h!="string"){let g=h;if(g?.deviceType){let i=Q("deviceType",a),A=Q(g.deviceType,a);X()._OrtAddSessionConfigEntry(u,i,A)!==0&&V(`Can\'t set a session config entry: \'deviceType\' - ${g.deviceType}.`)}if(g?.numThreads){let i=g.numThreads;(typeof i!="number"||!Number.isInteger(i)||i<0)&&(i=0);let A=Q("numThreads",a),D=Q(i.toString(),a);X()._OrtAddSessionConfigEntry(u,A,D)!==0&&V(`Can\'t set a session config entry: \'numThreads\' - ${g.numThreads}.`)}if(g?.powerPreference){let i=Q("powerPreference",a),A=Q(g.powerPreference,a);X()._OrtAddSessionConfigEntry(u,i,A)!==0&&V(`Can\'t set a session config entry: \'powerPreference\' - ${g.powerPreference}.`)}}break;case"webgpu":if(l="JS",typeof h!="string"){let g=h;if(g?.preferredLayout){if(g.preferredLayout!=="NCHW"&&g.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${g.preferredLayout}`);let i=Q("preferredLayout",a),A=Q(g.preferredLayout,a);X()._OrtAddSessionConfigEntry(u,i,A)!==0&&V(`Can\'t set a session config entry: \'preferredLayout\' - ${g.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let w=Q(l,a);X()._OrtAppendExecutionProvider(u,w)!==0&&V(`Can\'t append execution provider: ${l}.`)}},Cr=u=>{let d=X(),a=0,h=[],l=u||{};cn(l);try{let w=fn(l.graphOptimizationLevel??"all"),g=ln(l.executionMode??"sequential"),i=typeof l.logId=="string"?Q(l.logId,h):0,A=l.logSeverityLevel??2;if(!Number.isInteger(A)||A<0||A>4)throw new Error(`log serverity level is not valid: ${A}`);let D=l.logVerbosityLevel??0;if(!Number.isInteger(D)||D<0||D>4)throw new Error(`log verbosity level is not valid: ${D}`);let I=typeof l.optimizedModelFilePath=="string"?Q(l.optimizedModelFilePath,h):0;if(a=d._OrtCreateSessionOptions(w,!!l.enableCpuMemArena,!!l.enableMemPattern,g,!!l.enableProfiling,0,i,A,D,I),a===0&&V("Can\'t create session options."),l.executionProviders&&dn(a,l.executionProviders,h),l.freeDimensionOverrides)for(let[B,F]of Object.entries(l.freeDimensionOverrides)){if(typeof B!="string")throw new Error(`free dimension override name must be a string: ${B}`);if(typeof F!="number"||!Number.isInteger(F)||F<0)throw new Error(`free dimension override value must be a non-negative integer: ${F}`);let U=Q(B,h);d._OrtAddFreeDimensionOverride(a,U,F)!==0&&V(`Can\'t set a free dimension override: ${B} - ${F}.`)}return l.extra!==void 0&&rt(l.extra,"",new WeakSet,(B,F)=>{let U=Q(B,h),k=Q(F,h);d._OrtAddSessionConfigEntry(a,U,k)!==0&&V(`Can\'t set a session config entry: ${B} - ${F}.`)}),[a,h]}catch(w){throw a!==0&&d._OrtReleaseSessionOptions(a),h.forEach(g=>d._free(g)),w}};var Rt=u=>{switch(u){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"float16":return 10;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: ${u}`)}},Dr=u=>{switch(u){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 10:return"float16";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: ${u}`)}},It=u=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][u],xr=u=>{switch(u){case"float16":return Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${u}`)}},Fr=u=>{switch(u){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: ${u}`)}},Ur=u=>u==="float32"||u==="int32"||u==="int64"||u==="bool"||u==="float16"||u==="uint32",Pr=u=>{switch(u){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${u}`)}};var Rr=async u=>{if(typeof u=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(u))}catch(d){if(d.code==="ERR_FS_FILE_TOO_LARGE"){let a=(void 0)(u),h=[];for await(let l of a)h.push(l);return new Uint8Array(Buffer.concat(h))}throw d}else{let d=await fetch(u);if(!d.ok)throw new Error(`failed to load external data file: ${u}`);let a=d.headers.get("Content-Length"),h=a?parseInt(a,10):0;if(h<1073741824)return new Uint8Array(await d.arrayBuffer());{if(!d.body)throw new Error(`failed to load external data file: ${u}, no response body.`);let l=d.body.getReader(),w;try{w=new ArrayBuffer(h)}catch(i){if(i instanceof RangeError){let A=Math.ceil(h/65536);w=new WebAssembly.Memory({initial:A,maximum:A}).buffer}else throw i}let g=0;for(;;){let{done:i,value:A}=await l.read();if(i)break;let D=A.byteLength;new Uint8Array(w,g,D).set(A),g+=D}return new Uint8Array(w,0,h)}}else return u instanceof Blob?new Uint8Array(await u.arrayBuffer()):u instanceof Uint8Array?u:new Uint8Array(u)};var pn=(u,d)=>{X()._OrtInit(u,d)!==0&&V("Can\'t initialize onnxruntime.")},Lr=async u=>{pn(u.wasm.numThreads,Fr(u.logLevel))},Br=async(u,d)=>{},nt=new Map,mn=u=>{let d=X(),a=d.stackSave();try{let h=d.stackAlloc(8);return d._OrtGetInputOutputCount(u,h,h+4)!==0&&V("Can\'t get session input/output count."),[d.HEAP32[h/4],d.HEAP32[h/4+1]]}finally{d.stackRestore(a)}},Lt=u=>{let d=X(),a=d._malloc(u.byteLength);if(a===0)throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${u.byteLength}.`);return d.HEAPU8.set(u,a),[a,u.byteLength]},Wr=async(u,d)=>{let a,h,l=X();Array.isArray(u)?[a,h]=u:u.buffer===l.HEAPU8.buffer?[a,h]=[u.byteOffset,u.byteLength]:[a,h]=Lt(u);let w=0,g=0,i=0,A=[],D=[],I=[];try{if([g,A]=Cr(d),d?.externalData&&l.mountExternalData){let x=[];for(let N of d.externalData){let he=typeof N=="string"?N:N.path;x.push(Rr(typeof N=="string"?N:N.data).then(ie=>{l.mountExternalData(he,ie)}))}await Promise.all(x)}w=l._OrtCreateSession(a,h,g),w===0&&V("Can\'t create a session.");let[B,F]=mn(w),U=[],k=[],L=[];for(let x=0;xl._OrtFree(F)),I.forEach(F=>l._OrtFree(F)),i!==0&&l._OrtReleaseBinding(i),w!==0&&l._OrtReleaseSession(w),B}finally{l._free(a),g!==0&&l._OrtReleaseSessionOptions(g),A.forEach(B=>l._free(B)),l.unmountExternalData?.()}},kr=u=>{let d=X(),a=nt.get(u);if(!a)throw new Error(`cannot release session. invalid session id: ${u}`);let[h,l,w,g]=a;g&&d._OrtReleaseBinding(g.handle),d.jsepUnregisterBuffers?.(u),l.forEach(i=>d._OrtFree(i)),w.forEach(i=>d._OrtFree(i)),d._OrtReleaseSession(h),nt.delete(u)},Ir=(u,d,a,h,l)=>{if(!u){d.push(0);return}let w=X(),g=u[0],i=u[1],A=u[3],D,I;if(g==="string"&&A==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(A==="gpu-buffer"){let U=u[2].gpuBuffer,k=It(Rt(g));I=i.reduce((L,_)=>L*_,1)*k,D=w.jsepRegisterBuffer(h,l,U,I)}else{let U=u[2];if(Array.isArray(U)){I=4*U.length,D=w._malloc(I),a.push(D);let k=D/4;for(let L=0;Lw.HEAP32[U++]=L);let k=w._OrtCreateTensor(Rt(g),D,I,F,i.length,Pr(A));k===0&&V(`Can\'t create tensor for input/output. session=${h}, index=${l}.`),d.push(k)}finally{w.stackRestore(B)}},Nr=async(u,d,a,h,l,w)=>{let g=X(),i=nt.get(u);if(!i)throw new Error(`cannot run inference. invalid session id: ${u}`);let[A,D,I,B]=i,F=d.length,U=h.length,k=0,L=[],_=[],x=[],N=[],he=g.stackSave(),ie=g.stackAlloc(F*4),ae=g.stackAlloc(F*4),E=g.stackAlloc(U*4),Y=g.stackAlloc(U*4);try{[k,L]=Mr(w);for(let P=0;Pre*Z,1);J=Dr(Me);let ve=B?.outputPreferredLocations[h[P]];if(J==="string"){if(ve==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let re=[],Z=fe/4;for(let Ce=0;Ce0){let re=g.jsepGetBuffer(fe),Z=It(Me);if(Z===void 0||!Ur(J))throw new Error(`Unsupported data type: ${J}`);ye=!0,ce.push([J,pe,{gpuBuffer:re,download:g.jsepCreateDownloader(re,Oe*Z,J),dispose:()=>{g._OrtReleaseTensor(te)}},"gpu-buffer"])}else{let re=xr(J),Z=new re(Oe);new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength).set(g.HEAPU8.subarray(fe,fe+Z.byteLength)),ce.push([J,pe,Z,"cpu"])}}finally{g.stackRestore(de),J==="string"&&fe&&g._free(fe),ye||g._OrtReleaseTensor(te)}}return B&&g._OrtClearBoundOutputs(B.handle),ce}finally{g.stackRestore(he),_.forEach(ue=>g._OrtReleaseTensor(ue)),x.forEach(ue=>g._OrtReleaseTensor(ue)),N.forEach(ue=>g._free(ue)),k!==0&&g._OrtReleaseRunOptions(k),L.forEach(ue=>g._free(ue))}},Hr=u=>{let d=X(),a=nt.get(u);if(!a)throw new Error("invalid session id");let h=a[0],l=d._OrtEndProfiling(h);l===0&&V("Can\'t get an profile file name."),d._OrtFree(l)},$r=u=>{let d=[];for(let a of u){let h=a[2];!Array.isArray(h)&&"buffer"in h&&d.push(h.buffer)}return d};self.onmessage=u=>{let{type:d,in:a}=u.data;try{switch(d){case"init-wasm":Ar(a.wasm).then(()=>{Lr(a).then(()=>{postMessage({type:d})},h=>{postMessage({type:d,err:h})})},h=>{postMessage({type:d,err:h})});break;case"init-ep":{let{epName:h,env:l}=a;Br(l,h).then(()=>{postMessage({type:d})},w=>{postMessage({type:d,err:w})});break}case"copy-from":{let{buffer:h}=a,l=Lt(h);postMessage({type:d,out:l});break}case"create":{let{model:h,options:l}=a;Wr(h,l).then(w=>{postMessage({type:d,out:w})},w=>{postMessage({type:d,err:w})});break}case"release":kr(a),postMessage({type:d});break;case"run":{let{sessionId:h,inputIndices:l,inputs:w,outputIndices:g,options:i}=a;Nr(h,l,w,g,new Array(g.length).fill(null),i).then(A=>{A.some(D=>D[3]!=="cpu")?postMessage({type:d,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:d,out:A},$r(A))},A=>{postMessage({type:d,err:A})});break}case"end-profiling":Hr(a),postMessage({type:d});break;default:}}catch(h){postMessage({type:d,err:h})}};})();\n'; - }), - xr, - bt, - Tn, - Fo, - $o, - da, - ha, - Vr, - Wr, - gg, - Lo, - nd, - od, - id, - ad, - sd, - ud, - ld, - ma = L(() => { - vt(), - td(), - zr(), - (xr = () => !!Z.wasm.proxy && typeof document < 'u'), - (Tn = !1), - (Fo = !1), - ($o = !1), - (ha = new Map()), - (Vr = (t, e) => { - let o = ha.get(t); - o ? o.push(e) : ha.set(t, [e]); - }), - (Wr = () => { - if (Tn || !Fo || $o || !bt) throw new Error('worker not ready'); - }), - (gg = (t) => { - switch (t.data.type) { - case 'init-wasm': - (Tn = !1), t.data.err ? (($o = !0), da[1](t.data.err)) : ((Fo = !0), da[0]()); - break; - case 'init-ep': - case 'copy-from': - case 'create': - case 'release': - case 'run': - case 'end-profiling': { - let e = ha.get(t.data.type); - t.data.err ? e.shift()[1](t.data.err) : e.shift()[0](t.data.out); - break; - } - } - }), - (Lo = typeof document < 'u' ? document?.currentScript?.src : void 0), - (nd = async () => { - if (!Fo) { - if (Tn) throw new Error("multiple calls to 'initWasm()' detected."); - if ($o) throw new Error("previous call to 'initWasm()' failed."); - if (((Tn = !0), xr())) - return ( - Z.wasm.wasmPaths === void 0 && - Lo && - Lo.indexOf('blob:') !== 0 && - (Z.wasm.wasmPaths = Lo.substr(0, +Lo.lastIndexOf('/') + 1)), - new Promise((t, e) => { - bt?.terminate(); - let o = URL.createObjectURL(new Blob([rd()], { type: 'text/javascript' })); - (bt = new Worker(o, { name: 'ort-wasm-proxy-worker' })), - (bt.onerror = (u) => e(u)), - (bt.onmessage = gg), - URL.revokeObjectURL(o), - (da = [t, e]); - let i = { type: 'init-wasm', in: Z }; - bt.postMessage(i); - }) - ); - try { - await Rp(Z.wasm), await Yp(Z), (Fo = !0); - } catch (t) { - throw (($o = !0), t); - } finally { - Tn = !1; - } - } - }), - (od = async (t) => { - if (xr()) - return ( - Wr(), - new Promise((e, o) => { - Vr('init-ep', [e, o]); - let i = { type: 'init-ep', in: { epName: t, env: Z } }; - bt.postMessage(i); - }) - ); - await Xp(Z, t); - }), - (id = async (t) => - xr() - ? (Wr(), - new Promise((e, o) => { - Vr('copy-from', [e, o]); - let i = { type: 'copy-from', in: { buffer: t } }; - bt.postMessage(i, [t.buffer]); - })) - : pa(t)), - (ad = async (t, e) => { - if (xr()) { - if (e?.preferredOutputLocation) - throw new Error('session option "preferredOutputLocation" is not supported for proxy.'); - return ( - Wr(), - new Promise((o, i) => { - Vr('create', [o, i]); - let u = { type: 'create', in: { model: t, options: e } }, - n = []; - t instanceof Uint8Array && n.push(t.buffer), bt.postMessage(u, n); - }) - ); - } else return Kp(t, e); - }), - (sd = async (t) => { - if (xr()) - return ( - Wr(), - new Promise((e, o) => { - Vr('release', [e, o]); - let i = { type: 'release', in: t }; - bt.postMessage(i); - }) - ); - Jp(t); - }), - (ud = async (t, e, o, i, u, n) => { - if (xr()) { - if (o.some((s) => s[3] !== 'cpu')) - throw new Error('input tensor on GPU is not supported for proxy.'); - if (u.some((s) => s)) throw new Error('pre-allocated output tensor is not supported for proxy.'); - return ( - Wr(), - new Promise((s, d) => { - Vr('run', [s, d]); - let f = o, - r = { - type: 'run', - in: { sessionId: t, inputIndices: e, inputs: f, outputIndices: i, options: n }, - }; - bt.postMessage(r, ed(f)); - }) - ); - } else return Zp(t, e, o, i, u, n); - }), - (ld = async (t) => { - if (xr()) - return ( - Wr(), - new Promise((e, o) => { - Vr('end-profiling', [e, o]); - let i = { type: 'end-profiling', in: t }; - bt.postMessage(i); - }) - ); - Qp(t); - }); - }), - fd, - yg, - Co, - cd = L(() => { - vt(), - ma(), - fa(), - ca(), - (fd = (t, e) => { - switch (t.location) { - case 'cpu': - return [t.type, t.dims, t.data, 'cpu']; - case 'gpu-buffer': - return [t.type, t.dims, { gpuBuffer: t.gpuBuffer }, 'gpu-buffer']; - default: - throw new Error(`invalid data location: ${t.location} for ${e()}`); - } - }), - (yg = (t) => { - switch (t[3]) { - case 'cpu': - return new Re(t[0], t[2], t[1]); - case 'gpu-buffer': { - let e = t[0]; - if (!Do(e)) throw new Error(`not supported data type: ${e} for deserializing GPU tensor`); - let { gpuBuffer: o, download: i, dispose: u } = t[2]; - return Re.fromGpuBuffer(o, { dataType: e, dims: t[1], download: i, dispose: u }); - } - default: - throw new Error(`invalid data location: ${t[3]}`); - } - }), - (Co = class { - async fetchModelAndCopyToWasmMemory(t) { - return id(await gn(t)); - } - async loadModel(t, e) { - ar(); - let o; - typeof t == 'string' - ? typeof process < 'u' && process.versions && process.versions.node - ? (o = await gn(t)) - : (o = await this.fetchModelAndCopyToWasmMemory(t)) - : (o = t), - ([this.sessionId, this.inputNames, this.outputNames] = await ad(o, e)), - sr(); - } - async dispose() { - return sd(this.sessionId); - } - async run(t, e, o) { - ar(); - let i = [], - u = []; - Object.entries(t).forEach((l) => { - let p = l[0], - m = l[1], - y = this.inputNames.indexOf(p); - if (y === -1) throw new Error(`invalid input '${p}'`); - i.push(m), u.push(y); - }); - let n = [], - s = []; - Object.entries(e).forEach((l) => { - let p = l[0], - m = l[1], - y = this.outputNames.indexOf(p); - if (y === -1) throw new Error(`invalid output '${p}'`); - n.push(m), s.push(y); - }); - let d = i.map((l, p) => fd(l, () => `input "${this.inputNames[u[p]]}"`)), - f = n.map((l, p) => (l ? fd(l, () => `output "${this.outputNames[s[p]]}"`) : null)), - r = await ud(this.sessionId, u, d, s, f, o), - a = {}; - for (let l = 0; l < r.length; l++) a[this.outputNames[s[l]]] = n[l] ?? yg(r[l]); - return sr(), a; - } - startProfiling() {} - endProfiling() { - ld(this.sessionId); - } - }); - }), - Tg, - ko, - pd = L(() => { - vt(), - ma(), - cd(), - (Tg = () => { - if ( - ((typeof Z.wasm.initTimeout != 'number' || Z.wasm.initTimeout < 0) && (Z.wasm.initTimeout = 0), - typeof Z.wasm.simd != 'boolean' && (Z.wasm.simd = !0), - typeof Z.wasm.proxy != 'boolean' && (Z.wasm.proxy = !1), - typeof Z.wasm.trace != 'boolean' && (Z.wasm.trace = !1), - typeof Z.wasm.numThreads != 'number' || - !Number.isInteger(Z.wasm.numThreads) || - Z.wasm.numThreads <= 0) - ) { - ((typeof self < 'u' && !self.crossOriginIsolated) || - (typeof process < 'u' && process.versions && process.versions.node)) && - (Z.wasm.numThreads = 1); - let t = typeof navigator > 'u' ? (void 0)().length : navigator.hardwareConcurrency; - Z.wasm.numThreads = Math.min(4, Math.ceil((t || 1) / 2)); - } - }), - (ko = class { - async init(t) { - Tg(), await nd(), await od(t); - } - async createInferenceSessionHandler(t, e) { - let o = new Co(); - return await o.loadModel(t, e), Promise.resolve(o); - } - }); - }), - dd = {}; -Pr(dd, { wasmBackend: () => xg }); -var xg, - hd = L(() => { - pd(), (xg = new ko()); - }); -vt(); -vt(); -vt(); -var ys = '1.17.1', - zO = Yo; -{ - let t = (_p(), rr(wp)).onnxjsBackend; - or('webgl', t, -10); -} -{ - let t = (hd(), rr(dd)).wasmBackend; - or('cpu', t, 10), or('wasm', t, 10), or('webnn', t, 9); -} -Object.defineProperty(Z.versions, 'web', { value: ys, enumerable: !0 }); -/*! Bundled license information: - -long/index.js: - (** - * @license - * Copyright 2009 The Closure Library Authors - * Copyright 2020 Daniel Wirtz / The long.js Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - *) -*/ const ONNX_WEB = Object.freeze( - Object.defineProperty( - { - __proto__: null, - get InferenceSession() { - return Sd; - }, - get TRACE() { - return cs; - }, - get TRACE_FUNC_BEGIN() { - return ar; - }, - get TRACE_FUNC_END() { - return sr; - }, - get Tensor() { - return Re; - }, - get TrainingSession() { - return Pd; - }, - default: zO, - get env() { - return Z; - }, - get registerBackend() { - return or; - }, - }, - Symbol.toStringTag, - { value: 'Module' } - ) - ), - tensorToDataURL = (t, e) => { - const o = typeof document < 'u' ? document.createElement('canvas') : new OffscreenCanvas(1, 1); - (o.width = t.dims[3]), (o.height = t.dims[2]); - const i = o.getContext('2d'); - if (i != null) { - let u, n; - e?.tensorLayout !== void 0 && e.tensorLayout === 'NHWC' - ? ((u = t.dims[2]), (n = t.dims[3])) - : ((u = t.dims[3]), (n = t.dims[2])); - const s = e?.format !== void 0 ? e.format : 'RGB', - d = e?.norm; - let f, r; - d === void 0 || d.mean === void 0 - ? (f = [255, 255, 255, 255]) - : typeof d.mean == 'number' - ? (f = [d.mean, d.mean, d.mean, d.mean]) - : ((f = [d.mean[0], d.mean[1], d.mean[2], 0]), d.mean[3] !== void 0 && (f[3] = d.mean[3])), - d === void 0 || d.bias === void 0 - ? (r = [0, 0, 0, 0]) - : typeof d.bias == 'number' - ? (r = [d.bias, d.bias, d.bias, d.bias]) - : ((r = [d.bias[0], d.bias[1], d.bias[2], 0]), d.bias[3] !== void 0 && (r[3] = d.bias[3])); - const a = n * u; - let l = 0, - p = a, - m = a * 2, - y = -1; - s === 'RGBA' - ? ((l = 0), (p = a), (m = a * 2), (y = a * 3)) - : s === 'RGB' - ? ((l = 0), (p = a), (m = a * 2)) - : s === 'RBG' && ((l = 0), (m = a), (p = a * 2)); - for (let T = 0; T < n; T++) - for (let v = 0; v < u; v++) { - const S = (t.data[l++] - r[0]) * f[0], - E = (t.data[p++] - r[1]) * f[1], - A = (t.data[m++] - r[2]) * f[2], - F = y === -1 ? 255 : (t.data[y++] - r[3]) * f[3]; - (i.fillStyle = 'rgba(' + S + ',' + E + ',' + A + ',' + F + ')'), i.fillRect(v, T, 1, 1); - } - if ('toDataURL' in o) return o.toDataURL(); - throw new Error('toDataURL is not supported'); - } else throw new Error('Can not access image data'); - }, - tensorToImageData = (t, e) => { - const o = - typeof document < 'u' - ? document.createElement('canvas').getContext('2d') - : new OffscreenCanvas(1, 1).getContext('2d'); - let i; - if (o != null) { - let u, n, s; - e?.tensorLayout !== void 0 && e.tensorLayout === 'NHWC' - ? ((u = t.dims[2]), (n = t.dims[1]), (s = t.dims[3])) - : ((u = t.dims[3]), (n = t.dims[2]), (s = t.dims[1])); - const d = e !== void 0 && e.format !== void 0 ? e.format : 'RGB', - f = e?.norm; - let r, a; - f === void 0 || f.mean === void 0 - ? (r = [255, 255, 255, 255]) - : typeof f.mean == 'number' - ? (r = [f.mean, f.mean, f.mean, f.mean]) - : ((r = [f.mean[0], f.mean[1], f.mean[2], 255]), f.mean[3] !== void 0 && (r[3] = f.mean[3])), - f === void 0 || f.bias === void 0 - ? (a = [0, 0, 0, 0]) - : typeof f.bias == 'number' - ? (a = [f.bias, f.bias, f.bias, f.bias]) - : ((a = [f.bias[0], f.bias[1], f.bias[2], 0]), f.bias[3] !== void 0 && (a[3] = f.bias[3])); - const l = n * u; - if ( - e !== void 0 && - ((e.format !== void 0 && s === 4 && e.format !== 'RGBA') || - (s === 3 && e.format !== 'RGB' && e.format !== 'BGR')) - ) - throw new Error("Tensor format doesn't match input tensor dims"); - const p = 4; - let m = 0, - y = 1, - T = 2, - v = 3, - S = 0, - E = l, - A = l * 2, - F = -1; - d === 'RGBA' - ? ((S = 0), (E = l), (A = l * 2), (F = l * 3)) - : d === 'RGB' - ? ((S = 0), (E = l), (A = l * 2)) - : d === 'RBG' && ((S = 0), (A = l), (E = l * 2)), - (i = o.createImageData(u, n)); - for (let B = 0; B < n * u; m += p, y += p, T += p, v += p, B++) - (i.data[m] = (t.data[S++] - a[0]) * r[0]), - (i.data[y] = (t.data[E++] - a[1]) * r[1]), - (i.data[T] = (t.data[A++] - a[2]) * r[2]), - (i.data[v] = F === -1 ? 255 : (t.data[F++] - a[3]) * r[3]); - } else throw new Error('Can not access image data'); - return i; - }, - bufferToTensor = (t, e) => { - if (t === void 0) throw new Error('Image buffer must be defined'); - if (e.height === void 0 || e.width === void 0) throw new Error('Image height and width must be defined'); - if (e.tensorLayout === 'NHWC') throw new Error('NHWC Tensor layout is not supported yet'); - const { height: o, width: i } = e, - u = e.norm ?? { mean: 255, bias: 0 }; - let n, s; - typeof u.mean == 'number' - ? (n = [u.mean, u.mean, u.mean, u.mean]) - : (n = [u.mean[0], u.mean[1], u.mean[2], u.mean[3] ?? 255]), - typeof u.bias == 'number' - ? (s = [u.bias, u.bias, u.bias, u.bias]) - : (s = [u.bias[0], u.bias[1], u.bias[2], u.bias[3] ?? 0]); - const d = e.format !== void 0 ? e.format : 'RGBA', - f = e.tensorFormat !== void 0 && e.tensorFormat !== void 0 ? e.tensorFormat : 'RGB', - r = o * i, - a = f === 'RGBA' ? new Float32Array(r * 4) : new Float32Array(r * 3); - let l = 4, - p = 0, - m = 1, - y = 2, - T = 3, - v = 0, - S = r, - E = r * 2, - A = -1; - d === 'RGB' && ((l = 3), (p = 0), (m = 1), (y = 2), (T = -1)), - f === 'RGBA' - ? (A = r * 3) - : f === 'RBG' - ? ((v = 0), (E = r), (S = r * 2)) - : f === 'BGR' && ((E = 0), (S = r), (v = r * 2)); - for (let B = 0; B < r; B++, p += l, y += l, m += l, T += l) - (a[v++] = (t[p] + s[0]) / n[0]), - (a[S++] = (t[m] + s[1]) / n[1]), - (a[E++] = (t[y] + s[2]) / n[2]), - A !== -1 && T !== -1 && (a[A++] = (t[T] + s[3]) / n[3]); - return f === 'RGBA' ? new Tensor$2('float32', a, [1, 4, o, i]) : new Tensor$2('float32', a, [1, 3, o, i]); - }, - tensorFromImage = async (t, e) => { - const o = typeof HTMLImageElement < 'u' && t instanceof HTMLImageElement, - i = typeof ImageData < 'u' && t instanceof ImageData, - u = typeof ImageBitmap < 'u' && t instanceof ImageBitmap, - n = typeof t == 'string'; - let s, - d = e ?? {}; - const f = () => { - if (typeof document < 'u') return document.createElement('canvas'); - if (typeof OffscreenCanvas < 'u') return new OffscreenCanvas(1, 1); - throw new Error('Canvas is not supported'); - }, - r = (a) => (a instanceof HTMLCanvasElement || a instanceof OffscreenCanvas ? a.getContext('2d') : null); - if (o) { - const a = f(); - (a.width = t.width), (a.height = t.height); - const l = r(a); - if (l != null) { - let p = t.height, - m = t.width; - if ( - (e !== void 0 && - e.resizedHeight !== void 0 && - e.resizedWidth !== void 0 && - ((p = e.resizedHeight), (m = e.resizedWidth)), - e !== void 0) - ) { - if (((d = e), e.tensorFormat !== void 0)) - throw new Error('Image input config format must be RGBA for HTMLImageElement'); - (d.tensorFormat = 'RGBA'), (d.height = p), (d.width = m); - } else (d.tensorFormat = 'RGBA'), (d.height = p), (d.width = m); - l.drawImage(t, 0, 0), (s = l.getImageData(0, 0, m, p).data); - } else throw new Error('Can not access image data'); - } else if (i) { - let a, l; - if ( - (e !== void 0 && e.resizedWidth !== void 0 && e.resizedHeight !== void 0 - ? ((a = e.resizedHeight), (l = e.resizedWidth)) - : ((a = t.height), (l = t.width)), - e !== void 0 && (d = e), - (d.format = 'RGBA'), - (d.height = a), - (d.width = l), - e !== void 0) - ) { - const p = f(); - (p.width = l), (p.height = a); - const m = r(p); - if (m != null) m.putImageData(t, 0, 0), (s = m.getImageData(0, 0, l, a).data); - else throw new Error('Can not access image data'); - } else s = t.data; - } else if (u) { - if (e === void 0) throw new Error('Please provide image config with format for Imagebitmap'); - const a = f(); - (a.width = t.width), (a.height = t.height); - const l = r(a); - if (l != null) { - const p = t.height, - m = t.width; - return ( - l.drawImage(t, 0, 0, m, p), - (s = l.getImageData(0, 0, m, p).data), - (d.height = p), - (d.width = m), - bufferToTensor(s, d) - ); - } else throw new Error('Can not access image data'); - } else { - if (n) - return new Promise((a, l) => { - const p = f(), - m = r(p); - if (!t || !m) return l(); - const y = new Image(); - (y.crossOrigin = 'Anonymous'), - (y.src = t), - (y.onload = () => { - (p.width = y.width), (p.height = y.height), m.drawImage(y, 0, 0, p.width, p.height); - const T = m.getImageData(0, 0, p.width, p.height); - (d.height = p.height), (d.width = p.width), a(bufferToTensor(T.data, d)); - }); - }); - throw new Error('Input data provided is not supported - aborted tensor creation'); - } - if (s !== void 0) return bufferToTensor(s, d); - throw new Error('Input data provided is not supported - aborted tensor creation'); - }, - tensorFromTexture = (t, e) => { - const { width: o, height: i, download: u, dispose: n } = e, - s = [1, i, o, 4]; - return new Tensor$2({ location: 'texture', type: 'float32', texture: t, dims: s, download: u, dispose: n }); - }, - tensorFromGpuBuffer = (t, e) => { - const { dataType: o, dims: i, download: u, dispose: n } = e; - return new Tensor$2({ - location: 'gpu-buffer', - type: o ?? 'float32', - gpuBuffer: t, - dims: i, - download: u, - dispose: n, - }); - }, - tensorFromPinnedBuffer = (t, e, o) => - new Tensor$2({ location: 'cpu-pinned', type: t, data: e, dims: o ?? [e.length] }), - NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([ - ['float32', Float32Array], - ['uint8', Uint8Array], - ['int8', Int8Array], - ['uint16', Uint16Array], - ['float16', Uint16Array], - ['int16', Int16Array], - ['int32', Int32Array], - ['bool', Uint8Array], - ['float64', Float64Array], - ['uint32', Uint32Array], - ]), - NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map([ - [Float32Array, 'float32'], - [Uint8Array, 'uint8'], - [Int8Array, 'int8'], - [Uint16Array, 'uint16'], - [Int16Array, 'int16'], - [Int32Array, 'int32'], - [Float64Array, 'float64'], - [Uint32Array, 'uint32'], - ]); -let isBigIntChecked = !1; -const checkBigInt = () => { - if (!isBigIntChecked) { - isBigIntChecked = !0; - const t = typeof BigInt64Array < 'u' && typeof BigInt64Array.from == 'function', - e = typeof BigUint64Array < 'u' && typeof BigUint64Array.from == 'function'; - t && - (NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array), - NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64')), - e && - (NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array), - NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64')); - } - }, - calculateSize = (t) => { - let e = 1; - for (let o = 0; o < t.length; o++) { - const i = t[o]; - if (typeof i != 'number' || !Number.isSafeInteger(i)) - throw new TypeError(`dims[${o}] must be an integer, got: ${i}`); - if (i < 0) throw new RangeError(`dims[${o}] must be a non-negative integer, got: ${i}`); - e *= i; - } - return e; - }, - tensorReshape = (t, e) => { - switch (t.location) { - case 'cpu': - return new Tensor$2(t.type, t.data, e); - case 'cpu-pinned': - return new Tensor$2({ location: 'cpu-pinned', data: t.data, type: t.type, dims: e }); - case 'texture': - return new Tensor$2({ location: 'texture', texture: t.texture, type: t.type, dims: e }); - case 'gpu-buffer': - return new Tensor$2({ location: 'gpu-buffer', gpuBuffer: t.gpuBuffer, type: t.type, dims: e }); - default: - throw new Error(`tensorReshape: tensor location ${t.location} is not supported`); - } - }; -let Tensor$2 = class { - constructor(e, o, i) { - checkBigInt(); - let u, n; - if (typeof e == 'object' && 'location' in e) - switch (((this.dataLocation = e.location), (u = e.type), (n = e.dims), e.location)) { - case 'cpu-pinned': { - const d = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(u); - if (!d) throw new TypeError(`unsupported type "${u}" to create tensor from pinned buffer`); - if (!(e.data instanceof d)) throw new TypeError(`buffer should be of type ${d.name}`); - this.cpuData = e.data; - break; - } - case 'texture': { - if (u !== 'float32') throw new TypeError(`unsupported type "${u}" to create tensor from texture`); - (this.gpuTextureData = e.texture), (this.downloader = e.download), (this.disposer = e.dispose); - break; - } - case 'gpu-buffer': { - if ( - u !== 'float32' && - u !== 'float16' && - u !== 'int32' && - u !== 'int64' && - u !== 'uint32' && - u !== 'bool' - ) - throw new TypeError(`unsupported type "${u}" to create tensor from gpu buffer`); - (this.gpuBufferData = e.gpuBuffer), (this.downloader = e.download), (this.disposer = e.dispose); - break; - } - default: - throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); - } - else { - let d, f; - if (typeof e == 'string') - if (((u = e), (f = i), e === 'string')) { - if (!Array.isArray(o)) throw new TypeError("A string tensor's data must be a string array."); - d = o; - } else { - const r = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(e); - if (r === void 0) throw new TypeError(`Unsupported tensor type: ${e}.`); - if (Array.isArray(o)) { - if (e === 'float16') - throw new TypeError( - 'Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.' - ); - e === 'uint64' || e === 'int64' ? (d = r.from(o, BigInt)) : (d = r.from(o)); - } else if (o instanceof r) d = o; - else throw new TypeError(`A ${u} tensor's data must be type of ${r}`); - } - else if (((f = o), Array.isArray(e))) { - if (e.length === 0) throw new TypeError('Tensor type cannot be inferred from an empty array.'); - const r = typeof e[0]; - if (r === 'string') (u = 'string'), (d = e); - else if (r === 'boolean') (u = 'bool'), (d = Uint8Array.from(e)); - else throw new TypeError(`Invalid element type of data array: ${r}.`); - } else { - const r = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(e.constructor); - if (r === void 0) throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`); - (u = r), (d = e); - } - if (f === void 0) f = [d.length]; - else if (!Array.isArray(f)) throw new TypeError("A tensor's dims must be a number array"); - (n = f), (this.cpuData = d), (this.dataLocation = 'cpu'); - } - const s = calculateSize(n); - if (this.cpuData && s !== this.cpuData.length) - throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`); - (this.type = u), (this.dims = n), (this.size = s); - } - static async fromImage(e, o) { - return tensorFromImage(e, o); - } - static fromTexture(e, o) { - return tensorFromTexture(e, o); - } - static fromGpuBuffer(e, o) { - return tensorFromGpuBuffer(e, o); - } - static fromPinnedBuffer(e, o, i) { - return tensorFromPinnedBuffer(e, o, i); - } - toDataURL(e) { - return tensorToDataURL(this, e); - } - toImageData(e) { - return tensorToImageData(this, e); - } - get data() { - if ((this.ensureValid(), !this.cpuData)) - throw new Error( - 'The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.' - ); - return this.cpuData; - } - get location() { - return this.dataLocation; - } - get texture() { - if ((this.ensureValid(), !this.gpuTextureData)) throw new Error('The data is not stored as a WebGL texture.'); - return this.gpuTextureData; - } - get gpuBuffer() { - if ((this.ensureValid(), !this.gpuBufferData)) throw new Error('The data is not stored as a WebGPU buffer.'); - return this.gpuBufferData; - } - async getData(e) { - switch ((this.ensureValid(), this.dataLocation)) { - case 'cpu': - case 'cpu-pinned': - return this.data; - case 'texture': - case 'gpu-buffer': { - if (!this.downloader) - throw new Error('The current tensor is not created with a specified data downloader.'); - if (this.isDownloading) throw new Error('The current tensor is being downloaded.'); - try { - this.isDownloading = !0; - const o = await this.downloader(); - return ( - (this.downloader = void 0), - (this.dataLocation = 'cpu'), - (this.cpuData = o), - e && this.disposer && (this.disposer(), (this.disposer = void 0)), - o - ); - } finally { - this.isDownloading = !1; - } - } - default: - throw new Error(`cannot get data from location: ${this.dataLocation}`); - } - } - dispose() { - if (this.isDownloading) throw new Error('The current tensor is being downloaded.'); - this.disposer && (this.disposer(), (this.disposer = void 0)), - (this.cpuData = void 0), - (this.gpuTextureData = void 0), - (this.gpuBufferData = void 0), - (this.downloader = void 0), - (this.isDownloading = void 0), - (this.dataLocation = 'none'); - } - ensureValid() { - if (this.dataLocation === 'none') throw new Error('The tensor is disposed.'); - } - reshape(e) { - if ((this.ensureValid(), this.downloader || this.disposer)) - throw new Error('Cannot reshape a tensor that owns GPU resource.'); - return tensorReshape(this, e); - } -}; -const Tensor$1 = Tensor$2; -let ONNX; -const WEBGPU_AVAILABLE = typeof navigator < 'u' && 'gpu' in navigator, - USE_ONNXRUNTIME_NODE = typeof process < 'u' && process?.release?.name === 'node', - ONNX_MODULES = new Map(); -USE_ONNXRUNTIME_NODE - ? ((ONNX = sharp ?? ONNX_NODE), ONNX_MODULES.set('node', ONNX)) - : ((ONNX = zO ?? ONNX_WEB), ONNX_MODULES.set('web', ONNX)); -async function createInferenceSession(t, e) { - let o, i; - if (USE_ONNXRUNTIME_NODE) { - const s = ONNX_MODULES.get('node'); - (i = s.InferenceSession), (o = ['cpu']), Object.assign(s.env, env.backends.onnx); - } else if (WEBGPU_AVAILABLE && env.experimental.useWebGPU) { - let s = ONNX_MODULES.get('webgpu'); - s === void 0 && - ((s = await __vitePreload(() => import('./ort.webgpu.min-7V0I_OOb.js'), __vite__mapDeps([]))), - ONNX_MODULES.set('webgpu', s)), - (i = s.InferenceSession), - (o = ['webgpu', 'wasm']), - Object.assign(s.env, env.backends.onnx); - } else { - const s = ONNX_MODULES.get('web'); - (i = s.InferenceSession), (o = ['wasm']), Object.assign(s.env, env.backends.onnx); - } - const u = { executionProviders: o, ...e }; - return await i.create(t, u); -} -function isONNXTensor(t) { - for (const e of ONNX_MODULES.values()) if (t instanceof e.Tensor) return !0; - return !1; -} -const ONNX_ENV = ONNX?.env; -ONNX_ENV && - ONNX_ENV.wasm && - ((ONNX_ENV.wasm.wasmPaths = RUNNING_LOCALLY - ? sharp.join(env.__dirname, '/dist/') - : `https://cdn.jsdelivr.net/npm/@xenova/transformers@${env.version}/dist/`), - typeof navigator < 'u' && - /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent) && - (ONNX_ENV.wasm.simd = !1), - (ONNX_ENV.wasm.proxy = !0)); -function isONNXProxy() { - return ONNX_ENV.wasm.proxy; -} -env.backends.onnx = ONNX_ENV; -const DataTypeMap = Object.freeze({ - float32: Float32Array, - float16: Uint16Array, - float64: Float64Array, - string: Array, - int8: Int8Array, - uint8: Uint8Array, - int16: Int16Array, - uint16: Uint16Array, - int32: Int32Array, - uint32: Uint32Array, - int64: BigInt64Array, - uint64: BigUint64Array, - bool: Uint8Array, -}); -class Tensor { - get dims() { - return this.ort_tensor.dims; - } - set dims(e) { - this.ort_tensor.dims = e; - } - get type() { - return this.ort_tensor.type; - } - get data() { - return this.ort_tensor.data; - } - get size() { - return this.ort_tensor.size; - } - ort_tensor; - constructor(...e) { - return ( - isONNXTensor(e[0]) ? (this.ort_tensor = e[0]) : (this.ort_tensor = new Tensor$1(e[0], e[1], e[2])), - new Proxy(this, { - get: (o, i) => { - if (typeof i == 'string') { - let u = Number(i); - if (Number.isInteger(u)) return o._getitem(u); - } - return o[i]; - }, - set: (o, i, u) => (o[i] = u), - }) - ); - } - dispose() { - this.ort_tensor.dispose(); - } - *[Symbol.iterator]() { - const [e, ...o] = this.dims; - if (o.length > 0) { - const i = o.reduce((u, n) => u * n); - for (let u = 0; u < e; ++u) yield this._subarray(u, i, o); - } else yield* this.data; - } - _getitem(e) { - const [o, ...i] = this.dims; - if (((e = safeIndex(e, o)), i.length > 0)) { - const u = i.reduce((n, s) => n * s); - return this._subarray(e, u, i); - } else return new Tensor(this.type, [this.data[e]], i); - } - indexOf(e) { - for (let o = 0; o < this.data.length; ++o) if (this.data[o] == e) return o; - return -1; - } - _subarray(e, o, i) { - const u = e * o, - n = (e + 1) * o, - s = 'subarray' in this.data ? this.data.subarray(u, n) : this.data.slice(u, n); - return new Tensor(this.type, s, i); - } - 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]; - } - tolist() { - return reshape(this.data, this.dims); - } - sigmoid() { - return this.clone().sigmoid_(); - } - sigmoid_() { - for (let e = 0; e < this.data.length; ++e) this.data[e] = 1 / (1 + Math.exp(-this.data[e])); - return this; - } - mul(e) { - return this.clone().mul_(e); - } - mul_(e) { - for (let o = 0; o < this.data.length; ++o) this.data[o] *= e; - return this; - } - add(e) { - return this.clone().add_(e); - } - add_(e) { - for (let o = 0; o < this.data.length; ++o) this.data[o] += e; - return this; - } - clone() { - return new Tensor(this.type, this.data.slice(), this.dims.slice()); - } - slice(...e) { - let o = [], - i = []; - for (let f = 0; f < this.dims.length; ++f) { - let r = e[f]; - if (r == null) i.push([0, this.dims[f]]), o.push(this.dims[f]); - else if (typeof r == 'number') (r = safeIndex(r, this.dims[f], f)), i.push([r, r + 1]); - else if (Array.isArray(r) && r.length === 2) { - if (r[0] > r[1]) throw new Error(`Invalid slice: ${r}`); - let a = [Math.max(r[0], 0), Math.min(r[1], this.dims[f])]; - i.push(a), o.push(a[1] - a[0]); - } else throw new Error(`Invalid slice: ${r}`); - } - let u = i.map(([f, r]) => r - f), - n = u.reduce((f, r) => f * r), - s = new this.data.constructor(n); - const d = this.stride(); - for (let f = 0; f < n; ++f) { - let r = 0; - for (let a = u.length - 1, l = f; a >= 0; --a) { - const p = u[a]; - (r += ((l % p) + i[a][0]) * d[a]), (l = Math.floor(l / p)); - } - s[f] = this.data[r]; - } - return new Tensor(this.type, s, o); - } - transpose(...e) { - return transpose(this, e); - } - sum(e = null, o = !1) { - return this.norm(1, e, o); - } - norm(e = 'fro', o = null, i = !1) { - if (e === 'fro') e = 2; - else if (typeof e == 'string') throw Error(`Unsupported norm: ${e}`); - if (o === null) { - let s = this.data.reduce((d, f) => d + f ** e, 0) ** (1 / e); - return new Tensor(this.type, [s], []); - } - o = safeIndex(o, this.dims.length); - const u = this.dims.slice(); - u[o] = 1; - const n = new this.data.constructor(this.data.length / this.dims[o]); - for (let s = 0; s < this.data.length; ++s) { - let d = 0; - for (let f = this.dims.length - 1, r = s, a = 1; f >= 0; --f) { - const l = this.dims[f]; - if (f !== o) { - const p = r % l; - (d += p * a), (a *= u[f]); - } - r = Math.floor(r / l); - } - n[d] += this.data[s] ** e; - } - if (e !== 1) for (let s = 0; s < n.length; ++s) n[s] = n[s] ** (1 / e); - return i || u.splice(o, 1), new Tensor(this.type, n, u); - } - normalize_(e = 2, o = 1) { - o = safeIndex(o, this.dims.length); - const i = this.norm(e, o, !0); - for (let u = 0; u < this.data.length; ++u) { - let n = 0; - for (let s = this.dims.length - 1, d = u, f = 1; s >= 0; --s) { - const r = this.dims[s]; - if (s !== o) { - const a = d % r; - (n += a * f), (f *= this.dims[s]); - } - d = Math.floor(d / r); - } - this.data[u] /= i.data[n]; - } - return this; - } - normalize(e = 2, o = 1) { - return this.clone().normalize_(e, o); - } - stride() { - return dimsToStride(this.dims); - } - squeeze(e = null) { - return new Tensor(this.type, this.data, calc_squeeze_dims(this.dims, e)); - } - squeeze_(e = null) { - return (this.dims = calc_squeeze_dims(this.dims, e)), this; - } - unsqueeze(e = null) { - return new Tensor(this.type, this.data, calc_unsqueeze_dims(this.dims, e)); - } - unsqueeze_(e = null) { - return (this.dims = calc_unsqueeze_dims(this.dims, e)), this; - } - flatten_(e = 0, o = -1) { - o = (o + this.dims.length) % this.dims.length; - let i = this.dims.slice(0, e), - u = this.dims.slice(e, o + 1), - n = this.dims.slice(o + 1); - return (this.dims = [...i, u.reduce((s, d) => s * d, 1), ...n]), this; - } - flatten(e = 0, o = -1) { - return this.clone().flatten_(e, o); - } - view(...e) { - let o = -1; - for (let i = 0; i < e.length; ++i) - if (e[i] === -1) { - if (o !== -1) throw new Error('Only one dimension can be inferred'); - o = i; - } - if (o !== -1) { - const i = e.reduce((u, n, s) => (s !== o ? u * n : u), 1); - e[o] = this.data.length / i; - } - return new Tensor(this.type, this.data, e); - } - neg_() { - for (let e = 0; e < this.data.length; ++e) this.data[e] = -this.data[e]; - return this; - } - neg() { - return this.clone().neg_(); - } - clamp_(e, o) { - for (let i = 0; i < this.data.length; ++i) this.data[i] = Math.min(Math.max(this.data[i], e), o); - return this; - } - clamp(e, o) { - return this.clone().clamp_(e, o); - } - round_() { - for (let e = 0; e < this.data.length; ++e) this.data[e] = Math.round(this.data[e]); - return this; - } - round() { - return this.clone().round_(); - } - to(e) { - if (this.type === e) return this; - if (!DataTypeMap.hasOwnProperty(e)) throw new Error(`Unsupported type: ${e}`); - return new Tensor(e, DataTypeMap[e].from(this.data), this.dims); - } -} -function reshape(t, e) { - const o = t.length, - i = e.reduce((n, s) => n * s); - if (o !== i) throw Error(`cannot reshape array of size ${o} into shape (${e})`); - let u = t; - for (let n = e.length - 1; n >= 0; n--) - u = u.reduce( - (s, d) => { - let f = s[s.length - 1]; - return f.length < e[n] ? f.push(d) : s.push([d]), s; - }, - [[]] - ); - return u[0]; -} -function transpose(t, e) { - const [o, i] = transpose_data(t.data, t.dims, e); - return new Tensor(t.type, o, i); -} -function interpolate(t, [e, o], i = 'bilinear', u = !1) { - const n = t.dims.at(-3) ?? 1, - s = t.dims.at(-2), - d = t.dims.at(-1); - let f = interpolate_data(t.data, [n, s, d], [e, o], i, u); - return new Tensor(t.type, f, [n, e, o]); -} -function calc_squeeze_dims(t, e) { - return ( - (t = t.slice()), - e === null - ? (t = t.filter((o) => o !== 1)) - : typeof e == 'number' - ? t[e] === 1 && t.splice(e, 1) - : Array.isArray(e) && (t = t.filter((o, i) => o !== 1 || !e.includes(i))), - t - ); -} -function calc_unsqueeze_dims(t, e) { - return (e = safeIndex(e, t.length + 1)), (t = t.slice()), t.splice(e, 0, 1), t; -} -function safeIndex(t, e, o = null) { - if (t < -e || t >= e) - throw new Error( - `IndexError: index ${t} is out of bounds for dimension${o === null ? '' : ' ' + o} with size ${e}` - ); - return t < 0 && (t = ((t % e) + e) % e), t; -} -function cat(t, e = 0) { - e = safeIndex(e, t[0].dims.length); - const o = t[0].dims.slice(); - o[e] = t.reduce((s, d) => s + d.dims[e], 0); - const i = o.reduce((s, d) => s * d, 1), - u = new t[0].data.constructor(i), - n = t[0].type; - if (e === 0) { - let s = 0; - for (let d of t) u.set(d.data, s), (s += d.data.length); - } else { - let s = 0; - for (let d = 0; d < t.length; ++d) { - let f = t[d]; - for (let r = 0; r < f.data.length; ++r) { - let a = 0; - for (let l = f.dims.length - 1, p = r, m = 1; l >= 0; --l) { - const y = f.dims[l]; - let T = p % y; - l === e && (T += s), (a += T * m), (m *= o[l]), (p = Math.floor(p / y)); - } - u[a] = f.data[r]; - } - s += f.dims[e]; - } - } - return new Tensor(n, u, o); -} -function stack(t, e = 0) { - return cat( - t.map((o) => o.unsqueeze(e)), - e - ); -} -function std_mean(t, e = null, o = 1, i = !1) { - if (e === null) { - const r = t.data.reduce((m, y) => m + y, 0) / t.data.length, - a = Math.sqrt(t.data.reduce((m, y) => m + (y - r) ** 2, 0) / (t.data.length - o)), - l = new Tensor(t.type, [r], []); - return [new Tensor(t.type, [a], []), l]; - } - e = safeIndex(e, t.dims.length); - const u = mean(t, e, i), - n = t.dims.slice(); - n[e] = 1; - const s = new t.data.constructor(t.data.length / t.dims[e]); - for (let f = 0; f < t.data.length; ++f) { - let r = 0; - for (let a = t.dims.length - 1, l = f, p = 1; a >= 0; --a) { - const m = t.dims[a]; - if (a !== e) { - const y = l % m; - (r += y * p), (p *= n[a]); - } - l = Math.floor(l / m); - } - s[r] += (t.data[f] - u.data[r]) ** 2; - } - for (let f = 0; f < s.length; ++f) s[f] = Math.sqrt(s[f] / (t.dims[e] - o)); - return i || n.splice(e, 1), [new Tensor(t.type, s, n), u]; -} -function mean(t, e = null, o = !1) { - if (e === null) { - let n = t.data.reduce((s, d) => s + d, 0); - return new Tensor(t.type, [n / t.data.length], []); - } - e = safeIndex(e, t.dims.length); - const i = t.dims.slice(); - i[e] = 1; - const u = new t.data.constructor(t.data.length / t.dims[e]); - for (let n = 0; n < t.data.length; ++n) { - let s = 0; - for (let d = t.dims.length - 1, f = n, r = 1; d >= 0; --d) { - const a = t.dims[d]; - if (d !== e) { - const l = f % a; - (s += l * r), (r *= i[d]); - } - f = Math.floor(f / a); - } - u[s] += t.data[n]; - } - if (t.dims[e] !== 1) for (let n = 0; n < u.length; ++n) u[n] = u[n] / t.dims[e]; - return o || i.splice(e, 1), new Tensor(t.type, u, i); -} -function dynamicTimeWarping(t) { - const [e, o] = t.dims, - i = [e + 1, o + 1], - u = new Tensor('float32', new Float32Array(i[0] * i[1]).fill(1 / 0), i), - n = new Tensor('float32', new Float32Array(i[0] * i[1]).fill(-1), i); - u[0].data[0] = 0; - for (let a = 1; a < o + 1; ++a) - for (let l = 1; l < e + 1; ++l) { - const p = u[l - 1][a - 1].item(), - m = u[l - 1][a].item(), - y = u[l][a - 1].item(); - let T, v; - p < m && p < y ? ((T = p), (v = 0)) : m < p && m < y ? ((T = m), (v = 1)) : ((T = y), (v = 2)), - (u[l].data[a] = t[l - 1][a - 1].item() + T), - (n[l].data[a] = v); - } - let s = e, - d = o; - n.data.fill(2, 0, i[1]); - for (let a = 0; a < i[0]; ++a) n[a].data[0] = 1; - let f = [], - r = []; - for (; s > 0 || d > 0; ) - switch ((f.push(s - 1), r.push(d - 1), n[s][d].item())) { - case 0: - --s, --d; - break; - case 1: - --s; - break; - case 2: - --d; - break; - default: - throw new Error( - `Internal error in dynamic time warping. Unexpected trace[${s}, ${d}]. Please file a bug report.` - ); - } - return f.reverse(), r.reverse(), [f, r]; -} -function dimsToStride(t) { - const e = new Array(t.length); - for (let o = t.length - 1, i = 1; o >= 0; --o) (e[o] = i), (i *= t[o]); - return e; -} -function ones(t) { - const e = t.reduce((o, i) => o * i, 1); - return new Tensor('int64', new BigInt64Array(e).fill(1n), t); -} -function ones_like(t) { - return ones(t.dims); -} -var TOKEN_TYPES = Object.freeze({ - Text: 'Text', - NumericLiteral: 'NumericLiteral', - BooleanLiteral: 'BooleanLiteral', - StringLiteral: 'StringLiteral', - Identifier: 'Identifier', - 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', - 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', -}); -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, - true: TOKEN_TYPES.BooleanLiteral, - false: TOKEN_TYPES.BooleanLiteral, -}); -TOKEN_TYPES.OpenStatement, - TOKEN_TYPES.CloseStatement, - TOKEN_TYPES.OpenExpression, - TOKEN_TYPES.CloseExpression, - 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, - TOKEN_TYPES.ComparisonBinaryOperator, - TOKEN_TYPES.ComparisonBinaryOperator, - TOKEN_TYPES.ComparisonBinaryOperator, - TOKEN_TYPES.ComparisonBinaryOperator, - TOKEN_TYPES.ComparisonBinaryOperator, - TOKEN_TYPES.ComparisonBinaryOperator, - TOKEN_TYPES.AdditiveBinaryOperator, - TOKEN_TYPES.AdditiveBinaryOperator, - TOKEN_TYPES.MultiplicativeBinaryOperator, - TOKEN_TYPES.MultiplicativeBinaryOperator, - TOKEN_TYPES.MultiplicativeBinaryOperator, - TOKEN_TYPES.Equals; -const BYTES_TO_UNICODE = (() => { - const t = [ - ...Array.from({ length: 94 }, (u, n) => n + 33), - ...Array.from({ length: 12 }, (u, n) => n + 161), - ...Array.from({ length: 82 }, (u, n) => n + 174), - ], - e = t.slice(); - let o = 0; - for (let u = 0; u < 256; ++u) t.includes(u) || (t.push(u), e.push(256 + o), (o += 1)); - const i = e.map((u) => String.fromCharCode(u)); - return Object.fromEntries(t.map((u, n) => [u, i[n]])); -})(); -reverseDictionary(BYTES_TO_UNICODE); -const WHISPER_LANGUAGES = [ - ['en', 'english'], - ['zh', 'chinese'], - ['de', 'german'], - ['es', 'spanish'], - ['ru', 'russian'], - ['ko', 'korean'], - ['fr', 'french'], - ['ja', 'japanese'], - ['pt', 'portuguese'], - ['tr', 'turkish'], - ['pl', 'polish'], - ['ca', 'catalan'], - ['nl', 'dutch'], - ['ar', 'arabic'], - ['sv', 'swedish'], - ['it', 'italian'], - ['id', 'indonesian'], - ['hi', 'hindi'], - ['fi', 'finnish'], - ['vi', 'vietnamese'], - ['he', 'hebrew'], - ['uk', 'ukrainian'], - ['el', 'greek'], - ['ms', 'malay'], - ['cs', 'czech'], - ['ro', 'romanian'], - ['da', 'danish'], - ['hu', 'hungarian'], - ['ta', 'tamil'], - ['no', 'norwegian'], - ['th', 'thai'], - ['ur', 'urdu'], - ['hr', 'croatian'], - ['bg', 'bulgarian'], - ['lt', 'lithuanian'], - ['la', 'latin'], - ['mi', 'maori'], - ['ml', 'malayalam'], - ['cy', 'welsh'], - ['sk', 'slovak'], - ['te', 'telugu'], - ['fa', 'persian'], - ['lv', 'latvian'], - ['bn', 'bengali'], - ['sr', 'serbian'], - ['az', 'azerbaijani'], - ['sl', 'slovenian'], - ['kn', 'kannada'], - ['et', 'estonian'], - ['mk', 'macedonian'], - ['br', 'breton'], - ['eu', 'basque'], - ['is', 'icelandic'], - ['hy', 'armenian'], - ['ne', 'nepali'], - ['mn', 'mongolian'], - ['bs', 'bosnian'], - ['kk', 'kazakh'], - ['sq', 'albanian'], - ['sw', 'swahili'], - ['gl', 'galician'], - ['mr', 'marathi'], - ['pa', 'punjabi'], - ['si', 'sinhala'], - ['km', 'khmer'], - ['sn', 'shona'], - ['yo', 'yoruba'], - ['so', 'somali'], - ['af', 'afrikaans'], - ['oc', 'occitan'], - ['ka', 'georgian'], - ['be', 'belarusian'], - ['tg', 'tajik'], - ['sd', 'sindhi'], - ['gu', 'gujarati'], - ['am', 'amharic'], - ['yi', 'yiddish'], - ['lo', 'lao'], - ['uz', 'uzbek'], - ['fo', 'faroese'], - ['ht', 'haitian creole'], - ['ps', 'pashto'], - ['tk', 'turkmen'], - ['nn', 'nynorsk'], - ['mt', 'maltese'], - ['sa', 'sanskrit'], - ['lb', 'luxembourgish'], - ['my', 'myanmar'], - ['bo', 'tibetan'], - ['tl', 'tagalog'], - ['mg', 'malagasy'], - ['as', 'assamese'], - ['tt', 'tatar'], - ['haw', 'hawaiian'], - ['ln', 'lingala'], - ['ha', 'hausa'], - ['ba', 'bashkir'], - ['jw', 'javanese'], - ['su', 'sundanese'], -]; -new Map(WHISPER_LANGUAGES); -async function loadConfig(t, e) { - return await getModelJSON(t, 'config.json', !0, e); -} -class PretrainedConfig { - constructor(e) { - (this.model_type = null), (this.is_encoder_decoder = !1), Object.assign(this, e); - } - static async from_pretrained( - e, - { - progress_callback: o = null, - config: i = null, - cache_dir: u = null, - local_files_only: n = !1, - revision: s = 'main', - } = {} - ) { - let d = - i ?? - (await loadConfig(e, { progress_callback: o, config: i, cache_dir: u, local_files_only: n, revision: s })); - return new this(d); - } -} -class AutoConfig { - static async from_pretrained(...e) { - return PretrainedConfig.from_pretrained(...e); - } -} -class LogitsProcessorList extends Callable { - constructor() { - super(), (this.processors = []); - } - push(e) { - this.processors.push(e); - } - extend(e) { - this.processors.push(...e); - } - _call(e, o) { - for (let i of o) this.processors.forEach((u) => u(e, i)); - } - [Symbol.iterator]() { - return this.processors.values(); - } -} -class LogitsProcessor extends Callable { - _call(e, o) { - throw Error('`_call` should be implemented in a subclass'); - } -} -class ForceTokensLogitsProcessor extends LogitsProcessor { - constructor(e) { - super(), (this.force_token_map = Object.fromEntries(e ?? [])); - } - _call(e, o) { - let i = this.force_token_map[e.length]; - return exists(i) && (o.data.fill(-1 / 0), (o.data[i] = 0)), o; - } -} -class ForcedBOSTokenLogitsProcessor extends LogitsProcessor { - constructor(e) { - super(), (this.bos_token_id = e); - } - _call(e, o) { - return e.length === 1 && (o.data.fill(-1 / 0), (o.data[this.bos_token_id] = 0)), o; - } -} -class ForcedEOSTokenLogitsProcessor extends LogitsProcessor { - constructor(e, o) { - super(), (this.max_length = e), (this.forced_eos_token_id = o); - } - _call(e, o) {} -} -class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor { - constructor(e, o) { - super(), (this.begin_suppress_tokens = e), (this.begin_index = o); - } - _call(e, o) { - if (e.length === this.begin_index) for (let i of this.begin_suppress_tokens) o.data[i] = -1 / 0; - return o; - } -} -class WhisperTimeStampLogitsProcessor extends LogitsProcessor { - constructor(e) { - super(), - (this.eos_token_id = e.eos_token_id), - (this.no_timestamps_token_id = e.no_timestamps_token_id), - (this.timestamp_begin = this.no_timestamps_token_id + 1), - (this.begin_index = (e.forced_decoder_ids || []).length + 2), - e.forced_decoder_ids.slice(-1)[0][1] === this.no_timestamps_token_id && (this.begin_index -= 1), - (this.max_initial_timestamp_index = e.max_initial_timestamp_index); - } - _call(e, o) { - const i = o.data; - if (((i[this.no_timestamps_token_id] = -1 / 0), e.length === this.begin_index - 1)) - return i.fill(-1 / 0), (i[this.timestamp_begin] = 0), o; - const u = e.slice(this.begin_index), - n = u.length >= 1 && u[u.length - 1] >= this.timestamp_begin, - s = u.length < 2 || u[u.length - 2] >= this.timestamp_begin; - if ( - (n && (s ? i.subarray(this.timestamp_begin).fill(-1 / 0) : i.subarray(0, this.eos_token_id).fill(-1 / 0)), - e.length === this.begin_index && this.max_initial_timestamp_index !== null) - ) { - const a = this.timestamp_begin + this.max_initial_timestamp_index; - i.subarray(a + 1).fill(-1 / 0); - } - const d = log_softmax(i), - f = Math.log( - d - .subarray(this.timestamp_begin) - .map(Math.exp) - .reduce((a, l) => a + l) - ), - r = max(d.subarray(0, this.timestamp_begin))[0]; - return f > r && i.subarray(0, this.timestamp_begin).fill(-1 / 0), o; - } -} -class NoRepeatNGramLogitsProcessor extends LogitsProcessor { - constructor(e) { - super(), (this.no_repeat_ngram_size = e); - } - getNgrams(e) { - const o = e.length, - i = []; - for (let n = 0; n < o + 1 - this.no_repeat_ngram_size; ++n) { - const s = []; - for (let d = 0; d < this.no_repeat_ngram_size; ++d) s.push(e[n + d]); - i.push(s); - } - const u = new Map(); - for (const n of i) { - const s = n.slice(0, n.length - 1), - d = JSON.stringify(s), - f = u.get(d) ?? []; - f.push(n[n.length - 1]), u.set(d, f); - } - return u; - } - getGeneratedNgrams(e, o) { - const i = o.slice(o.length + 1 - this.no_repeat_ngram_size, o.length); - return e.get(JSON.stringify(i)) ?? []; - } - calcBannedNgramTokens(e) { - const o = []; - if (e.length + 1 < this.no_repeat_ngram_size) return o; - { - const i = this.getNgrams(e); - return this.getGeneratedNgrams(i, e); - } - } - _call(e, o) { - const i = this.calcBannedNgramTokens(e); - for (const u of i) o.data[u] = -1 / 0; - return o; - } -} -class RepetitionPenaltyLogitsProcessor extends LogitsProcessor { - constructor(e) { - super(), (this.penalty = e); - } - _call(e, o) { - for (const i of e) o.data[i] < 0 ? (o.data[i] *= this.penalty) : (o.data[i] /= this.penalty); - return o; - } -} -class MinLengthLogitsProcessor extends LogitsProcessor { - constructor(e, o) { - super(), (this.min_length = e), (this.eos_token_id = Array.isArray(o) ? o : [o]); - } - _call(e, o) { - if (e.length < this.min_length) for (const i of this.eos_token_id) o.data[i] = -1 / 0; - return o; - } -} -class MinNewTokensLengthLogitsProcessor extends LogitsProcessor { - constructor(e, o, i) { - super(), - (this.prompt_length_to_skip = e), - (this.min_new_tokens = o), - (this.eos_token_id = Array.isArray(i) ? i : [i]); - } - _call(e, o) { - if (e.length - this.prompt_length_to_skip < this.min_new_tokens) - for (const u of this.eos_token_id) o.data[u] = -1 / 0; - return o; - } -} -class NoBadWordsLogitsProcessor extends LogitsProcessor { - constructor(e, o) { - super(), (this.bad_words_ids = e), (this.eos_token_id = Array.isArray(o) ? o : [o]); - } - _call(e, o) { - for (const i of this.bad_words_ids) { - let u = !0; - for (let n = 1; n <= i.length - 1 && i.length < e.length; ++n) - if (i.at(-n - 1) !== e.at(-n)) { - u = !1; - break; - } - u && (o.data[i.at(-1)] = -1 / 0); - } - return o; - } -} -const GenerationConfig = class { - constructor(t = {}) { - (this.max_length = t.max_length ?? 20), - (this.max_new_tokens = t.max_new_tokens ?? null), - (this.min_length = t.min_length ?? 0), - (this.min_new_tokens = t.min_new_tokens ?? null), - (this.early_stopping = t.early_stopping ?? !1), - (this.max_time = t.max_time ?? null), - (this.do_sample = t.do_sample ?? !1), - (this.num_beams = t.num_beams ?? 1), - (this.num_beam_groups = t.num_beam_groups ?? 1), - (this.penalty_alpha = t.penalty_alpha ?? null), - (this.use_cache = t.use_cache ?? !0), - (this.temperature = t.temperature ?? 1), - (this.top_k = t.top_k ?? 50), - (this.top_p = t.top_p ?? 1), - (this.typical_p = t.typical_p ?? 1), - (this.epsilon_cutoff = t.epsilon_cutoff ?? 0), - (this.eta_cutoff = t.eta_cutoff ?? 0), - (this.diversity_penalty = t.diversity_penalty ?? 0), - (this.repetition_penalty = t.repetition_penalty ?? 1), - (this.encoder_repetition_penalty = t.encoder_repetition_penalty ?? 1), - (this.length_penalty = t.length_penalty ?? 1), - (this.no_repeat_ngram_size = t.no_repeat_ngram_size ?? 0), - (this.bad_words_ids = t.bad_words_ids ?? null), - (this.force_words_ids = t.force_words_ids ?? null), - (this.renormalize_logits = t.renormalize_logits ?? !1), - (this.constraints = t.constraints ?? null), - (this.forced_bos_token_id = t.forced_bos_token_id ?? null), - (this.forced_eos_token_id = t.forced_eos_token_id ?? null), - (this.remove_invalid_values = t.remove_invalid_values ?? !1), - (this.exponential_decay_length_penalty = t.exponential_decay_length_penalty ?? null), - (this.suppress_tokens = t.suppress_tokens ?? null), - (this.begin_suppress_tokens = t.begin_suppress_tokens ?? null), - (this.forced_decoder_ids = t.forced_decoder_ids ?? null), - (this.num_return_sequences = t.num_return_sequences ?? 1), - (this.output_attentions = t.output_attentions ?? !1), - (this.output_hidden_states = t.output_hidden_states ?? !1), - (this.output_scores = t.output_scores ?? !1), - (this.return_dict_in_generate = t.return_dict_in_generate ?? !1), - (this.pad_token_id = t.pad_token_id ?? null), - (this.bos_token_id = t.bos_token_id ?? null), - (this.eos_token_id = t.eos_token_id ?? null), - (this.encoder_no_repeat_ngram_size = t.encoder_no_repeat_ngram_size ?? 0), - (this.decoder_start_token_id = t.decoder_start_token_id ?? null), - (this.generation_kwargs = t.generation_kwargs ?? {}); - } -}; -class Sampler extends Callable { - constructor(e) { - super(), (this.generation_config = e); - } - _call(e, o = -1) { - return this.sample(e, o); - } - sample(e, o) { - throw Error('sample should be implemented in subclasses.'); - } - getLogits(e, o) { - let i = e.dims.at(-1), - u = e.data; - if (o === -1) u = u.slice(-i); - else { - let n = o * i; - u = u.slice(n, n + i); - } - return this.generation_config.temperature > 0 && (u = u.map((n) => n / this.generation_config.temperature)), u; - } - randomSelect(e) { - let o = e.reduce((u, n) => u + n, 0), - i = Math.random() * o; - for (let u = 0; u < e.length; ++u) if (((i -= e[u]), i <= 0)) return u; - return 0; - } - static getSampler(e) { - if (e.do_sample) return new MultinomialSampler(e); - if (e.num_beams > 1) return new BeamSearchSampler(e); - if (e.num_return_sequences > 1) - throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`); - return new GreedySampler(e); - } -} -class GreedySampler extends Sampler { - sample(e, o = -1) { - let i = this.getLogits(e, o); - return [[max(i)[1], 0]]; - } -} -class MultinomialSampler extends Sampler { - sample(e, o = -1) { - let i = e.dims.at(-1); - this.generation_config.top_k > 0 && (i = Math.min(this.generation_config.top_k, i)); - const u = this.getLogits(e, o), - n = getTopItems(u, i), - s = softmax(n.map((d) => d[1])); - return Array.from({ length: this.generation_config.num_beams }, () => { - const d = this.randomSelect(s); - return [n[d][0], Math.log(s[d])]; - }); - } -} -class BeamSearchSampler extends Sampler { - sample(e, o = -1) { - let i = e.dims.at(-1); - this.generation_config.top_k > 0 && (i = Math.min(this.generation_config.top_k, i)); - const u = this.getLogits(e, o), - n = getTopItems(u, i), - s = softmax(n.map((d) => d[1])); - return Array.from({ length: this.generation_config.num_beams }, (d, f) => [n[f][0], Math.log(s[f])]); - } -} -const MODEL_TYPES = { EncoderOnly: 0, EncoderDecoder: 1, Seq2Seq: 2, Vision2Seq: 3, DecoderOnly: 4, MaskGeneration: 5 }, - MODEL_TYPE_MAPPING = new Map(), - MODEL_NAME_TO_CLASS_MAPPING = new Map(), - MODEL_CLASS_TO_NAME_MAPPING = new Map(); -async function constructSession(t, e, o) { - const i = `onnx/${e}${o.quantized ? '_quantized' : ''}.onnx`, - u = await getModelFile(t, i, !0, o), - n = o.session_options ?? {}; - if (n.externalData !== void 0) - for (let s = 0; s < n.externalData.length; s++) { - const d = n.externalData[s]; - if (typeof d.data == 'string') { - const f = await getModelFile(t, d.data, !0, o); - d.data = f; - } - } - return await createInferenceSession(u, n); -} -function validateInputs(t, e) { - const o = Object.create(null), - i = []; - for (const s of t.inputNames) { - const d = e[s]; - if (!(d instanceof Tensor)) { - i.push(s); - continue; - } - o[s] = isONNXProxy() ? d.clone() : d; - } - if (i.length > 0) - throw new Error(`An error occurred during model execution: "Missing the following inputs: ${i.join(', ')}.`); - const u = Object.keys(e).length, - n = t.inputNames.length; - if (u > n) { - let s = Object.keys(e).filter((d) => !t.inputNames.includes(d)); - console.warn( - `WARNING: Too many inputs were provided (${u} > ${n}). The following inputs will be ignored: "${s.join( - ', ' - )}".` - ); - } - return o; -} -async function sessionRun(t, e) { - const o = validateInputs(t, e); - try { - const i = Object.fromEntries(Object.entries(o).map(([n, s]) => [n, s.ort_tensor])); - let u = await t.run(i); - u = replaceTensors(u); - for (const [n, s] of Object.entries(o)) n.startsWith('past_key_values') && s.dispose(); - return u; - } catch (i) { - throw ( - (console.error(`An error occurred during model execution: "${i}".`), - console.error('Inputs given to model:', o), - i) - ); - } -} -function replaceTensors(t) { - for (let e in t) isONNXTensor(t[e]) ? (t[e] = new Tensor(t[e])) : typeof t[e] == 'object' && replaceTensors(t[e]); - return t; -} -function toI64Tensor(t) { - if (t instanceof Tensor) return t; - if (t.length === 0) throw Error('items must be non-empty'); - if (Array.isArray(t[0])) { - if (t.some((e) => e.length !== t[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(t.flat().map((e) => BigInt(e))), [t.length, t[0].length]); - } else return new Tensor('int64', BigInt64Array.from(t.map((e) => BigInt(e))), [1, t.length]); -} -function prepareAttentionMask(t, e) { - let o = t.config.pad_token_id ?? null, - i = t.config.eos_token_id ?? null; - isIntegralNumber(i) && (i = [i]); - let u = e.indexOf(o) !== -1, - n = i === null || !i.includes(o); - if (u && n) { - let s = BigInt64Array.from(e.data.map((d) => d != o)); - return new Tensor('int64', s, e.dims); - } else return ones_like(e); -} -function preparePositionIds(t, e, o) { - if (!t.inputNames.includes('position_ids')) return; - const i = new BigInt64Array(e.attention_mask.data.length); - for (let u = 0; u < e.attention_mask.dims[0]; ++u) { - let n = u * e.attention_mask.dims[1], - s = BigInt(0); - for (let d = 0; d < e.attention_mask.dims[1]; ++d) { - const f = n + d; - e.attention_mask.data[f] === 0n ? (i[f] = BigInt(1)) : ((i[f] = s), (s += e.attention_mask.data[f])); - } - } - (e.position_ids = new Tensor('int64', i, e.attention_mask.dims)), - o && (e.position_ids = e.position_ids.slice(null, -1).unsqueeze_(-1)); -} -function boolTensor(t) { - return new Tensor('bool', [t], [1]); -} -async function seq2seqForward(t, e) { - let { encoder_outputs: o, past_key_values: i } = e; - o || (o = (await encoderForward(t, e)).last_hidden_state); - let u = { input_ids: e.decoder_input_ids, encoder_hidden_states: o }; - const n = !!i; - t.decoder_merged_session.inputNames.includes('use_cache_branch') && (u.use_cache_branch = boolTensor(n)), - t.decoder_merged_session.inputNames.includes('encoder_attention_mask') && - (u.encoder_attention_mask = e.attention_mask), - preparePositionIds(t.decoder_merged_session, u, n), - t.addPastKeyValues(u, i); - const s = await sessionRun(t.decoder_merged_session, u); - let d = s.logits; - i = t.getPastKeyValues(s, i); - const f = t.getAttentions(s); - return new Seq2SeqLMOutput({ logits: d, past_key_values: i, encoder_outputs: o, ...f }); -} -function seq2seqStartBeams(t, e, o, i) { - let u = [], - n = 0; - const s = t.requires_attention_mask ?? !0; - let d = o.decoder_input_ids ?? o.decoder_start_token_id ?? o.bos_token_id ?? o.eos_token_id; - d instanceof Tensor ? (d = d.tolist().flat()) : Array.isArray(d) || (d = [d]); - for (let f of e) { - f.dims = [1, ...f.dims]; - let r = { - inputs: f, - encoder_outputs: null, - prev_model_outputs: null, - output_token_ids: d, - done: !1, - score: 0, - id: n++, - }; - s && (r.attention_mask = prepareAttentionMask(t, f)), u.push(r); - } - return u; -} -async function seq2seqRunBeam(t, e) { - const o = t.main_input_name; - let i = e.output_token_ids; - e.prev_model_outputs && (i = i.slice(-1)); - let u = { - [o]: e.inputs, - decoder_input_ids: toI64Tensor(i), - encoder_outputs: e.encoder_outputs, - past_key_values: e.prev_model_outputs?.past_key_values, - }; - e.attention_mask && (u.attention_mask = e.attention_mask); - let n = await t.forward(u); - return (e.prev_model_outputs = n), (e.encoder_outputs = n.encoder_outputs), n; -} -function seq2seqUpdatebeam(t, e) { - t.output_token_ids = [...t.output_token_ids, e]; -} -async function encoderForward(t, e) { - const o = Object.create(null); - for (const i of t.session.inputNames) o[i] = e[i]; - return ( - t.session.inputNames.includes('token_type_ids') && - !o.token_type_ids && - (o.token_type_ids = new Tensor('int64', new BigInt64Array(o.input_ids.data.length), o.input_ids.dims)), - await sessionRun(t.session, o) - ); -} -async function decoderForward(t, e) { - let { input_ids: o, past_key_values: i, attention_mask: u } = e, - n = { input_ids: o, attention_mask: u ?? prepareAttentionMask(t, o) }; - const s = !!i; - t.session.inputNames.includes('use_cache_branch') && (n.use_cache_branch = boolTensor(s)), - preparePositionIds(t.session, n, s), - t.addPastKeyValues(n, i); - let d = await sessionRun(t.session, n), - f = d.logits; - return (i = t.getPastKeyValues(d, i)), { logits: f, past_key_values: i }; -} -function decoderStartBeams(t, e, o, i, u) { - let n = [], - s = 0; - for (let d of e) { - let f = d.tolist().map(Number); - d.dims = [1, ...d.dims]; - let r; - u ? ((r = u[s]), (r.dims = [1, ...r.dims])) : (r = prepareAttentionMask(t, d)); - let a = { - input: d, - model_input_ids: d, - attention_mask: r, - prev_model_outputs: null, - output_token_ids: f, - num_output_tokens: i, - done: !1, - score: 0, - id: s++, - }; - n.push(a); - } - return n; -} -async function decoderRunBeam(t, e) { - let o = new BigInt64Array(e.output_token_ids.length).fill(1n), - i = { - input_ids: e.model_input_ids, - attention_mask: new Tensor('int64', o, [1, o.length]), - past_key_values: e.prev_model_outputs?.past_key_values, - }, - u = await t.forward(i); - return (e.prev_model_outputs = u), u; -} -function decoderUpdatebeam(t, e) { - (t.output_token_ids = [...t.output_token_ids, e]), (t.model_input_ids = new Tensor('int64', [BigInt(e)], [1, 1])); -} -class PreTrainedModel extends Callable { - main_input_name = 'input_ids'; - constructor(e, o) { - super(), (this.config = e), (this.session = o); - const i = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor), - u = MODEL_TYPE_MAPPING.get(i); - (this.can_generate = !1), - (this._runBeam = null), - (this._getStartBeams = null), - (this._updateBeam = null), - (this._forward = null), - u === MODEL_TYPES.DecoderOnly - ? ((this.can_generate = !0), - (this._runBeam = decoderRunBeam), - (this._getStartBeams = decoderStartBeams), - (this._updateBeam = decoderUpdatebeam), - (this._forward = decoderForward)) - : u === MODEL_TYPES.Seq2Seq || u === MODEL_TYPES.Vision2Seq - ? ((this.can_generate = !0), - (this._runBeam = seq2seqRunBeam), - (this._getStartBeams = seq2seqStartBeams), - (this._updateBeam = seq2seqUpdatebeam), - (this._forward = seq2seqForward)) - : u === MODEL_TYPES.EncoderDecoder - ? (this._forward = encoderForward) - : (this._forward = encoderForward); - } - async dispose() { - const e = []; - for (let o of Object.keys(this)) { - let i = this[o]; - i?.handler?.dispose !== void 0 && e.push(i.handler.dispose()); - } - return await Promise.all(e); - } - static async from_pretrained( - e, - { - quantized: o = !0, - progress_callback: i = null, - config: u = null, - cache_dir: n = null, - local_files_only: s = !1, - revision: d = 'main', - model_file_name: f = null, - session_options: r = {}, - } = {} - ) { - let a = { - quantized: o, - progress_callback: i, - config: u, - cache_dir: n, - local_files_only: s, - revision: d, - model_file_name: f, - session_options: r, - }; - const l = MODEL_CLASS_TO_NAME_MAPPING.get(this), - p = MODEL_TYPE_MAPPING.get(l); - let m; - return ( - p === MODEL_TYPES.DecoderOnly - ? (m = await Promise.all([ - AutoConfig.from_pretrained(e, a), - constructSession(e, a.model_file_name ?? 'decoder_model_merged', a), - getModelJSON(e, 'generation_config.json', !1, a), - ])) - : p === MODEL_TYPES.Seq2Seq || p === MODEL_TYPES.Vision2Seq - ? (m = await Promise.all([ - AutoConfig.from_pretrained(e, a), - constructSession(e, 'encoder_model', a), - constructSession(e, 'decoder_model_merged', a), - getModelJSON(e, 'generation_config.json', !1, a), - ])) - : p === MODEL_TYPES.MaskGeneration - ? (m = await Promise.all([ - AutoConfig.from_pretrained(e, a), - constructSession(e, 'vision_encoder', a), - constructSession(e, 'prompt_encoder_mask_decoder', a), - ])) - : p === MODEL_TYPES.EncoderDecoder - ? (m = await Promise.all([ - AutoConfig.from_pretrained(e, a), - constructSession(e, 'encoder_model', a), - constructSession(e, 'decoder_model_merged', a), - ])) - : (p !== MODEL_TYPES.EncoderOnly && - console.warn( - `Model type for '${ - l ?? u?.model_type - }' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.` - ), - (m = await Promise.all([ - AutoConfig.from_pretrained(e, a), - constructSession(e, a.model_file_name ?? 'model', a), - ]))), - new this(...m) - ); - } - async _call(e) { - return await this.forward(e); - } - async forward(e) { - return await this._forward(this, e); - } - _get_logits_processor(e, o, i = null) { - const u = new LogitsProcessorList(); - if ( - (e.repetition_penalty !== null && - e.repetition_penalty !== 1 && - u.push(new RepetitionPenaltyLogitsProcessor(e.repetition_penalty)), - e.no_repeat_ngram_size !== null && - e.no_repeat_ngram_size > 0 && - u.push(new NoRepeatNGramLogitsProcessor(e.no_repeat_ngram_size)), - e.bad_words_ids !== null && u.push(new NoBadWordsLogitsProcessor(e.bad_words_ids, e.eos_token_id)), - e.min_length !== null && - e.eos_token_id !== null && - e.min_length > 0 && - u.push(new MinLengthLogitsProcessor(e.min_length, e.eos_token_id)), - e.min_new_tokens !== null && - e.eos_token_id !== null && - e.min_new_tokens > 0 && - u.push(new MinNewTokensLengthLogitsProcessor(o, e.min_new_tokens, e.eos_token_id)), - e.forced_bos_token_id !== null && u.push(new ForcedBOSTokenLogitsProcessor(e.forced_bos_token_id)), - e.forced_eos_token_id !== null && - u.push(new ForcedEOSTokenLogitsProcessor(e.max_length, e.forced_eos_token_id)), - e.begin_suppress_tokens !== null) - ) { - let n = o > 1 || e.forced_bos_token_id === null ? o : o + 1; - e.forced_decoder_ids !== null && (n += e.forced_decoder_ids[e.forced_decoder_ids.length - 1][0]), - u.push(new SuppressTokensAtBeginLogitsProcessor(e.begin_suppress_tokens, n)); - } - return ( - e.forced_decoder_ids !== null && u.push(new ForceTokensLogitsProcessor(e.forced_decoder_ids)), - i !== null && u.extend(i), - u - ); - } - _get_generation_config(e) { - let o = new GenerationConfig(this.config); - return ( - 'generation_config' in this && Object.assign(o, this.generation_config), - e !== null && Object.assign(o, e), - o - ); - } - async generate(e, o = null, i = null, { inputs_attention_mask: u = null } = {}) { - if (!this.can_generate) { - let v = `The current model class (${MODEL_CLASS_TO_NAME_MAPPING.get( - this.constructor - )}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`; - const S = this.config.model_type, - E = - MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(S) ?? - MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(S) ?? - MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(S) ?? - MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(S); - throw (E && (v += ` Please use the following class instead: '${E[0]}'`), Error(v)); - } - if (!(e instanceof Tensor) && !isTypedArray(e) && !Array.isArray(e)) - throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${e.constructor.name}".`); - let n; - if (this.config.is_encoder_decoder) n = 0; - else if (((n = e instanceof Tensor ? e.dims.at(-1) : e.length), n === 0)) - throw Error('Must supply a non-empty array of input token ids.'); - (o = this._get_generation_config(o)), - (i = i ?? new LogitsProcessorList()), - (i = this._get_logits_processor(o, n, i)); - let s = o.eos_token_id; - s !== null && !Array.isArray(s) && (s = [s]); - let d = 1; - const f = d + (o.max_new_tokens ?? 1 / 0), - r = Number.isInteger(o.max_length) && (o.max_new_tokens ?? null) === null; - let a = Sampler.getSampler(o), - l = this.getStartBeams(e, o, d, u); - for (; l.some((T) => !T.done) && d < f; ) { - let T = []; - for (let v of l) { - if (v.done) { - T.push(v); - continue; - } - if (r && v.output_token_ids.length >= o.max_length) { - (v.done = !0), T.push(v); - continue; - } - let S = await this.runBeam(v); - o.output_attentions && this.addAttentionsToBeam(v, S), o.output_scores; - let E = S.logits.slice(null, -1, null); - i(v.output_token_ids, E); - let A = a(E); - for (let [F, B] of A) { - let J = { ...v }; - this.updateBeam(J, F), (J.score += B), s && s.includes(F) && (J.done = !0), T.push(J); - } - } - ++d, - (T = this.groupBeams(T).map((v) => v.sort((S, E) => E.score - S.score).slice(0, o.num_beams))), - (l = T.flat()), - o.callback_function && o.callback_function(l); - } - const p = this.groupBeams(l), - m = (T) => - p - .map((v) => - o.num_return_sequences > 1 ? v.slice(0, o.num_return_sequences).map((S) => S[T]) : [v[0][T]] - ) - .flat(), - y = m('output_token_ids'); - if (o.return_dict_in_generate) { - const T = m('decoder_attentions'), - v = m('cross_attentions'); - return { sequences: y, decoder_attentions: T, cross_attentions: v }; - } else return y; - } - addAttentionsToBeam(e, o) { - if (this.config.is_encoder_decoder) { - if (!o.cross_attentions || o.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`.' - ); - e.cross_attentions || (e.cross_attentions = []), e.cross_attentions.push(o.cross_attentions); - } - if (!o.decoder_attentions || o.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`.' - ); - e.decoder_attentions || (e.decoder_attentions = []), e.decoder_attentions.push(o.decoder_attentions); - } - groupBeams(e) { - const o = Object.create(null); - for (const i of e) o[i.id] === void 0 ? (o[i.id] = [i]) : o[i.id].push(i); - return Object.values(o); - } - getPastKeyValues(e, o) { - const i = Object.create(null); - for (const u in e) - if (u.startsWith('present')) { - let n = u.replace('present', 'past_key_values'); - o && u.includes('encoder') ? (i[n] = o[n]) : (i[n] = e[u]); - } - return i; - } - getAttentions(e) { - const o = Object.create(null); - for (const i of ['cross_attentions', 'decoder_attentions']) { - const u = []; - for (const n in e) - if (n.startsWith(i)) { - const s = n.split('.').pop(); - u[s] = e[n]; - } - o[i] = u; - } - return o; - } - addPastKeyValues(e, o) { - if (o) Object.assign(e, o); - else { - const u = this.config.precision || 'float32', - n = u === 'float16' ? new Uint16Array() : []; - if (this.config.is_encoder_decoder && (this.add_encoder_pkv ?? !0)) { - let s = [1, this.num_encoder_heads, 0, this.encoder_dim_kv], - d = [1, this.num_decoder_heads, 0, this.decoder_dim_kv]; - for (let f = 0; f < this.num_decoder_layers; ++f) - (e[`past_key_values.${f}.encoder.key`] = new Tensor(u, n, s)), - (e[`past_key_values.${f}.encoder.value`] = new Tensor(u, n, s)), - (e[`past_key_values.${f}.decoder.key`] = new Tensor(u, n, d)), - (e[`past_key_values.${f}.decoder.value`] = new Tensor(u, n, d)); - } else if (this.config.model_type === 'falcon') { - let s = [1 * this.num_heads, 0, this.dim_kv]; - for (let d = 0; d < this.num_layers; ++d) - (e[`past_key_values.${d}.key`] = new Tensor(u, n, s)), - (e[`past_key_values.${d}.value`] = new Tensor(u, n, s)); - } else if (this.config.multi_query) { - let s = [1 * this.num_heads, 0, 2 * this.dim_kv]; - for (let d = 0; d < this.num_layers; ++d) e[`past_key_values.${d}.key_value`] = new Tensor(u, n, s); - } else if (this.config.model_type === 'bloom') { - let s = [1 * this.num_heads, this.dim_kv, 0], - d = [1 * this.num_heads, 0, this.dim_kv]; - for (let f = 0; f < this.num_layers; ++f) - (e[`past_key_values.${f}.key`] = new Tensor(u, n, s)), - (e[`past_key_values.${f}.value`] = new Tensor(u, n, d)); - } else { - let s = [1, this.num_heads, 0, this.dim_kv]; - for (let d = 0; d < this.num_layers; ++d) - (e[`past_key_values.${d}.key`] = new Tensor(u, n, s)), - (e[`past_key_values.${d}.value`] = new Tensor(u, n, s)); - } - } - } - getStartBeams(e, o, i, u) { - return this._getStartBeams(this, e, o, i, u); - } - async runBeam(e) { - return await this._runBeam(this, e); - } - updateBeam(e, o) { - return this._updateBeam(e, o); - } -} -class ModelOutput {} -class BertPreTrainedModel extends PreTrainedModel {} -class BertModel extends BertPreTrainedModel {} -class BertForMaskedLM extends BertPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class BertForSequenceClassification extends BertPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class BertForTokenClassification extends BertPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class BertForQuestionAnswering extends BertPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class NomicBertPreTrainedModel extends PreTrainedModel {} -class NomicBertModel extends NomicBertPreTrainedModel {} -class RoFormerPreTrainedModel extends PreTrainedModel {} -class RoFormerModel extends RoFormerPreTrainedModel {} -class RoFormerForMaskedLM extends RoFormerPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class RoFormerForSequenceClassification extends RoFormerPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class RoFormerForTokenClassification extends RoFormerPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class ConvBertPreTrainedModel extends PreTrainedModel {} -class ConvBertModel extends ConvBertPreTrainedModel {} -class ConvBertForMaskedLM extends ConvBertPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class ConvBertForSequenceClassification extends ConvBertPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class ConvBertForTokenClassification extends ConvBertPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class ElectraPreTrainedModel extends PreTrainedModel {} -class ElectraModel extends ElectraPreTrainedModel {} -class ElectraForMaskedLM extends ElectraPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class ElectraForSequenceClassification extends ElectraPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class ElectraForTokenClassification extends ElectraPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class ElectraForQuestionAnswering extends ElectraPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class CamembertPreTrainedModel extends PreTrainedModel {} -class CamembertModel extends CamembertPreTrainedModel {} -class CamembertForMaskedLM extends CamembertPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class CamembertForSequenceClassification extends CamembertPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class CamembertForTokenClassification extends CamembertPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class CamembertForQuestionAnswering extends CamembertPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class DebertaPreTrainedModel extends PreTrainedModel {} -class DebertaModel extends DebertaPreTrainedModel {} -class DebertaForMaskedLM extends DebertaPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class DebertaForSequenceClassification extends DebertaPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class DebertaForTokenClassification extends DebertaPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class DebertaForQuestionAnswering extends DebertaPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class DebertaV2PreTrainedModel extends PreTrainedModel {} -class DebertaV2Model extends DebertaV2PreTrainedModel {} -class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class DistilBertPreTrainedModel extends PreTrainedModel {} -class DistilBertModel extends DistilBertPreTrainedModel {} -class DistilBertForSequenceClassification extends DistilBertPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class DistilBertForTokenClassification extends DistilBertPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class DistilBertForMaskedLM extends DistilBertPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class EsmPreTrainedModel extends PreTrainedModel {} -class EsmModel extends EsmPreTrainedModel {} -class EsmForMaskedLM extends EsmPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class EsmForSequenceClassification extends EsmPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class EsmForTokenClassification extends EsmPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class MobileBertPreTrainedModel extends PreTrainedModel {} -class MobileBertModel extends MobileBertPreTrainedModel {} -class MobileBertForMaskedLM extends MobileBertPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class MobileBertForSequenceClassification extends MobileBertPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class MPNetPreTrainedModel extends PreTrainedModel {} -class MPNetModel extends MPNetPreTrainedModel {} -class MPNetForMaskedLM extends MPNetPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class MPNetForSequenceClassification extends MPNetPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class MPNetForTokenClassification extends MPNetPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class MPNetForQuestionAnswering extends MPNetPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class SqueezeBertPreTrainedModel extends PreTrainedModel {} -class SqueezeBertModel extends SqueezeBertPreTrainedModel {} -class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class AlbertPreTrainedModel extends PreTrainedModel {} -class AlbertModel extends AlbertPreTrainedModel {} -class AlbertForSequenceClassification extends AlbertPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class AlbertForQuestionAnswering extends AlbertPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class AlbertForMaskedLM extends AlbertPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class T5PreTrainedModel extends PreTrainedModel {} -class T5Model extends T5PreTrainedModel {} -class T5ForConditionalGeneration extends T5PreTrainedModel { - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } -} -class LongT5PreTrainedModel extends PreTrainedModel {} -class LongT5Model extends LongT5PreTrainedModel {} -class LongT5ForConditionalGeneration extends LongT5PreTrainedModel { - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } -} -class MT5PreTrainedModel extends PreTrainedModel {} -class MT5Model extends MT5PreTrainedModel {} -class MT5ForConditionalGeneration extends MT5PreTrainedModel { - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } -} -class BartPretrainedModel extends PreTrainedModel {} -class BartModel extends BartPretrainedModel {} -class BartForConditionalGeneration extends BartPretrainedModel { - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } -} -class BartForSequenceClassification extends BartPretrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class MBartPreTrainedModel extends PreTrainedModel {} -class MBartModel extends MBartPreTrainedModel {} -class MBartForConditionalGeneration extends MBartPreTrainedModel { - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } -} -class MBartForSequenceClassification extends MBartPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class MBartForCausalLM extends MBartPreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (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); - } -} -class BlenderbotPreTrainedModel extends PreTrainedModel {} -class BlenderbotModel extends BlenderbotPreTrainedModel {} -class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel { - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } -} -class BlenderbotSmallPreTrainedModel extends PreTrainedModel {} -class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel {} -class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel { - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } -} -class RobertaPreTrainedModel extends PreTrainedModel {} -class RobertaModel extends RobertaPreTrainedModel {} -class RobertaForMaskedLM extends RobertaPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class RobertaForSequenceClassification extends RobertaPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class RobertaForTokenClassification extends RobertaPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class RobertaForQuestionAnswering extends RobertaPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class XLMPreTrainedModel extends PreTrainedModel {} -class XLMModel extends XLMPreTrainedModel {} -class XLMWithLMHeadModel extends XLMPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class XLMForSequenceClassification extends XLMPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class XLMForTokenClassification extends XLMPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class XLMForQuestionAnswering extends XLMPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class XLMRobertaPreTrainedModel extends PreTrainedModel {} -class XLMRobertaModel extends XLMRobertaPreTrainedModel {} -class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel { - async _call(e) { - return new MaskedLMOutput(await super._call(e)); - } -} -class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel { - async _call(e) { - return new QuestionAnsweringModelOutput(await super._call(e)); - } -} -class ASTPreTrainedModel extends PreTrainedModel {} -class ASTModel extends ASTPreTrainedModel {} -class ASTForAudioClassification extends ASTPreTrainedModel {} -class WhisperPreTrainedModel extends PreTrainedModel {} -class WhisperModel extends WhisperPreTrainedModel {} -class WhisperForConditionalGeneration extends WhisperPreTrainedModel { - requires_attention_mask = !1; - main_input_name = 'input_features'; - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } - async generate(e, o = null, i = null) { - if ( - ((o = this._get_generation_config(o)), - (o.return_timestamps ??= !1), - o.return_timestamps && (i = [new WhisperTimeStampLogitsProcessor(o)]), - o.return_token_timestamps && - ((o.output_attentions = !0), - (o.return_dict_in_generate = !0), - o.task === 'translate' && - console.warn("Token-level timestamps may not be reliable for task 'translate'."), - !o.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 u = await super.generate(e, o, i); - return ( - o.return_token_timestamps && - o.alignment_heads && - (u.token_timestamps = this._extract_token_timestamps(u, o.alignment_heads, o.num_frames)), - u - ); - } - _extract_token_timestamps(e, o, i = null, u = 0.02) { - if (!e.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 n = this.config.median_filter_width; - n === void 0 && (console.warn('Model config has no `median_filter_width`, using default value of 7.'), (n = 7)); - const s = e.cross_attentions.map((r) => { - let a = Array.from({ length: this.config.decoder_layers }, (v, S) => - cat( - r.map((E) => E[S]), - 2 - ) - ), - l = stack(o.map(([v, S]) => (i ? a[v].slice(null, S, null, [0, i]) : a[v].slice(null, S)))); - l = l.transpose(1, 0, 2, 3); - let [p, m] = std_mean(l, -2, 0, !0), - y = l.clone(); - for (let v = 0; v < y.dims[0]; ++v) { - let S = y[v]; - for (let E = 0; E < S.dims[0]; ++E) { - let A = S[E]; - const F = p[v][E][0], - B = m[v][E][0]; - for (let J = 0; J < A.dims[0]; ++J) { - let Q = A[J]; - for (let re = 0; re < Q.data.length; ++re) - Q.data[re] = (Q.data[re] - B.data[re]) / F.data[re]; - Q.data.set(medianFilter(Q.data, n)); - } - } - } - return mean(y, 1); - }), - d = [e.sequences.length, e.sequences[0].length], - f = new Tensor('float32', new Float32Array(d[0] * d[1]), d); - for (let r = 0; r < d[0]; ++r) { - const a = s[r].neg().squeeze_(0); - let [l, p] = dynamicTimeWarping(a), - m = Array.from({ length: l.length - 1 }, (v, S) => l[S + 1] - l[S]), - y = mergeArrays([1], m).map((v) => !!v), - T = []; - for (let v = 0; v < y.length; ++v) y[v] && T.push(p[v] * u); - f[r].data.set(T, 1); - } - return f; - } -} -class VisionEncoderDecoderModel extends PreTrainedModel { - main_input_name = 'pixel_values'; - constructor(e, o, i, u) { - super(e, o), (this.decoder_merged_session = i), (this.generation_config = u); - const n = this.config.encoder, - s = this.config.decoder, - d = n.model_type; - (MODEL_MAPPING_NAMES_ENCODER_ONLY.get(d) ?? MODEL_MAPPING_NAMES_ENCODER_DECODER.get(d)) || - console.warn( - `Model type for encoder '${d}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.` - ); - const r = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(s.model_type); - if (!r) - throw new Error( - `Unable to construct \`VisionEncoderDecoder\` due to unsupported decoder: "${this.config.decoder.model_type}"` - ); - const a = r[1], - l = new a(s, i, u); - (this.add_encoder_pkv = 'num_decoder_layers' in l), - this.add_encoder_pkv - ? ((this.num_decoder_layers = l.num_decoder_layers), - (this.num_decoder_heads = l.num_decoder_heads), - (this.decoder_dim_kv = l.decoder_dim_kv), - (this.num_encoder_layers = l.num_encoder_layers), - (this.num_encoder_heads = l.num_encoder_heads), - (this.encoder_dim_kv = l.encoder_dim_kv)) - : ((this.num_layers = l.num_layers), (this.num_heads = l.num_heads), (this.dim_kv = l.dim_kv)); - } -} -class CLIPPreTrainedModel extends PreTrainedModel {} -class CLIPModel extends CLIPPreTrainedModel {} -class CLIPTextModelWithProjection extends CLIPPreTrainedModel { - static async from_pretrained(e, o = {}) { - return (o.model_file_name ??= 'text_model'), super.from_pretrained(e, o); - } -} -class CLIPVisionModelWithProjection extends CLIPPreTrainedModel { - static async from_pretrained(e, o = {}) { - return (o.model_file_name ??= 'vision_model'), super.from_pretrained(e, o); - } -} -class SiglipPreTrainedModel extends PreTrainedModel {} -class SiglipModel extends SiglipPreTrainedModel {} -class SiglipTextModel extends SiglipPreTrainedModel { - static async from_pretrained(e, o = {}) { - return (o.model_file_name ??= 'text_model'), super.from_pretrained(e, o); - } -} -class SiglipVisionModel extends CLIPPreTrainedModel { - static async from_pretrained(e, o = {}) { - return (o.model_file_name ??= 'vision_model'), super.from_pretrained(e, o); - } -} -class ChineseCLIPPreTrainedModel extends PreTrainedModel {} -class ChineseCLIPModel extends ChineseCLIPPreTrainedModel {} -class CLIPSegPreTrainedModel extends PreTrainedModel {} -class CLIPSegModel extends CLIPSegPreTrainedModel {} -class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel {} -class GPT2PreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.n_head), - (this.num_layers = this.config.n_layer), - (this.dim_kv = this.config.n_embd / this.num_heads); - } -} -class GPT2Model extends GPT2PreTrainedModel {} -class GPT2LMHeadModel extends GPT2PreTrainedModel {} -class GPTNeoPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.num_heads), - (this.num_layers = this.config.num_layers), - (this.dim_kv = this.config.hidden_size / this.num_heads); - } -} -class GPTNeoModel extends GPTNeoPreTrainedModel {} -class GPTNeoForCausalLM extends GPTNeoPreTrainedModel {} -class GPTNeoXPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.num_attention_heads), - (this.num_layers = this.config.num_hidden_layers), - (this.dim_kv = this.config.hidden_size / this.num_heads); - } -} -class GPTNeoXModel extends GPTNeoXPreTrainedModel {} -class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel {} -class GPTJPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.n_head), - (this.num_layers = this.config.n_layer), - (this.dim_kv = this.config.n_embd / this.num_heads); - } -} -class GPTJModel extends GPTJPreTrainedModel {} -class GPTJForCausalLM extends GPTJPreTrainedModel {} -class GPTBigCodePreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.n_head), - (this.num_layers = this.config.n_layer), - (this.dim_kv = this.config.n_embd / this.num_heads); - } -} -class GPTBigCodeModel extends GPTBigCodePreTrainedModel {} -class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel {} -class CodeGenPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.n_head), - (this.num_layers = this.config.n_layer), - (this.dim_kv = this.config.n_embd / this.num_heads); - } -} -class CodeGenModel extends CodeGenPreTrainedModel {} -class CodeGenForCausalLM extends CodeGenPreTrainedModel {} -class LlamaPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (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); - } -} -class LlamaModel extends LlamaPreTrainedModel {} -class LlamaForCausalLM extends LlamaPreTrainedModel {} -class Qwen2PreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (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); - } -} -class Qwen2Model extends Qwen2PreTrainedModel {} -class Qwen2ForCausalLM extends Qwen2PreTrainedModel {} -class PhiPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.num_attention_heads), - (this.num_layers = this.config.num_hidden_layers), - (this.dim_kv = this.config.hidden_size / this.num_heads); - } -} -class PhiModel extends PhiPreTrainedModel {} -class PhiForCausalLM extends PhiPreTrainedModel {} -class BloomPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (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); - } -} -class BloomModel extends BloomPreTrainedModel {} -class BloomForCausalLM extends BloomPreTrainedModel {} -class MptPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (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); - } -} -class MptModel extends MptPreTrainedModel {} -class MptForCausalLM extends MptPreTrainedModel {} -class OPTPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.num_attention_heads), - (this.num_layers = this.config.num_hidden_layers), - (this.dim_kv = this.config.hidden_size / this.num_heads); - } -} -class OPTModel extends OPTPreTrainedModel {} -class OPTForCausalLM extends OPTPreTrainedModel {} -class ViTPreTrainedModel extends PreTrainedModel {} -class ViTModel extends ViTPreTrainedModel {} -class ViTForImageClassification extends ViTPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class VitMattePreTrainedModel extends PreTrainedModel {} -class VitMatteForImageMatting extends VitMattePreTrainedModel { - async _call(e) { - return new ImageMattingOutput(await super._call(e)); - } -} -class MobileViTPreTrainedModel extends PreTrainedModel {} -class MobileViTModel extends MobileViTPreTrainedModel {} -class MobileViTForImageClassification extends MobileViTPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class OwlViTPreTrainedModel extends PreTrainedModel {} -class OwlViTModel extends OwlViTPreTrainedModel {} -class OwlViTForObjectDetection extends OwlViTPreTrainedModel {} -class Owlv2PreTrainedModel extends PreTrainedModel {} -class Owlv2Model extends Owlv2PreTrainedModel {} -class Owlv2ForObjectDetection extends Owlv2PreTrainedModel {} -class BeitPreTrainedModel extends PreTrainedModel {} -class BeitModel extends BeitPreTrainedModel {} -class BeitForImageClassification extends BeitPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class DetrPreTrainedModel extends PreTrainedModel {} -class DetrModel extends DetrPreTrainedModel {} -class DetrForObjectDetection extends DetrPreTrainedModel { - async _call(e) { - return new DetrObjectDetectionOutput(await super._call(e)); - } -} -class DetrForSegmentation extends DetrPreTrainedModel { - async _call(e) { - return new DetrSegmentationOutput(await super._call(e)); - } -} -class DetrObjectDetectionOutput extends ModelOutput { - constructor({ logits: e, pred_boxes: o }) { - super(), (this.logits = e), (this.pred_boxes = o); - } -} -class DetrSegmentationOutput extends ModelOutput { - constructor({ logits: e, pred_boxes: o, pred_masks: i }) { - super(), (this.logits = e), (this.pred_boxes = o), (this.pred_masks = i); - } -} -class TableTransformerPreTrainedModel extends PreTrainedModel {} -class TableTransformerModel extends TableTransformerPreTrainedModel {} -class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel { - async _call(e) { - return new TableTransformerObjectDetectionOutput(await super._call(e)); - } -} -class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput {} -class DeiTPreTrainedModel extends PreTrainedModel {} -class DeiTModel extends DeiTPreTrainedModel {} -class DeiTForImageClassification extends DeiTPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class ResNetPreTrainedModel extends PreTrainedModel {} -class ResNetModel extends ResNetPreTrainedModel {} -class ResNetForImageClassification extends ResNetPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class SwinPreTrainedModel extends PreTrainedModel {} -class SwinModel extends SwinPreTrainedModel {} -class SwinForImageClassification extends SwinPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class Swin2SRPreTrainedModel extends PreTrainedModel {} -class Swin2SRModel extends Swin2SRPreTrainedModel {} -class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel {} -class DPTPreTrainedModel extends PreTrainedModel {} -class DPTModel extends DPTPreTrainedModel {} -class DPTForDepthEstimation extends DPTPreTrainedModel {} -class DepthAnythingPreTrainedModel extends PreTrainedModel {} -class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel {} -class GLPNPreTrainedModel extends PreTrainedModel {} -class GLPNModel extends GLPNPreTrainedModel {} -class GLPNForDepthEstimation extends GLPNPreTrainedModel {} -class DonutSwinPreTrainedModel extends PreTrainedModel {} -class DonutSwinModel extends DonutSwinPreTrainedModel {} -class ConvNextPreTrainedModel extends PreTrainedModel {} -class ConvNextModel extends ConvNextPreTrainedModel {} -class ConvNextForImageClassification extends ConvNextPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class ConvNextV2PreTrainedModel extends PreTrainedModel {} -class ConvNextV2Model extends ConvNextV2PreTrainedModel {} -class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class Dinov2PreTrainedModel extends PreTrainedModel {} -class Dinov2Model extends Dinov2PreTrainedModel {} -class Dinov2ForImageClassification extends Dinov2PreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class YolosPreTrainedModel extends PreTrainedModel {} -class YolosModel extends YolosPreTrainedModel {} -class YolosForObjectDetection extends YolosPreTrainedModel { - async _call(e) { - return new YolosObjectDetectionOutput(await super._call(e)); - } -} -class YolosObjectDetectionOutput extends ModelOutput { - constructor({ logits: e, pred_boxes: o }) { - super(), (this.logits = e), (this.pred_boxes = o); - } -} -class SamPreTrainedModel extends PreTrainedModel {} -class SamModel extends SamPreTrainedModel { - constructor(e, o, i) { - super(e, o), (this.prompt_encoder_mask_decoder = i); - } - async get_image_embeddings({ pixel_values: e }) { - return await encoderForward(this, { pixel_values: e }); - } - async forward(e) { - if ( - ((!e.image_embeddings || !e.image_positional_embeddings) && - (e = { ...e, ...(await this.get_image_embeddings(e)) }), - !e.input_labels) - ) { - const o = e.input_points.dims.slice(0, -1), - i = o.reduce((u, n) => u * n, 1); - e.input_labels = new Tensor('int64', new BigInt64Array(i).fill(1n), o); - } - return await sessionRun(this.prompt_encoder_mask_decoder, { - input_points: e.input_points, - input_labels: e.input_labels, - image_embeddings: e.image_embeddings, - image_positional_embeddings: e.image_positional_embeddings, - }); - } - async _call(e) { - return new SamImageSegmentationOutput(await super._call(e)); - } -} -class SamImageSegmentationOutput extends ModelOutput { - constructor({ iou_scores: e, pred_masks: o }) { - super(), (this.iou_scores = e), (this.pred_masks = o); - } -} -class MarianPreTrainedModel extends PreTrainedModel {} -class MarianModel extends MarianPreTrainedModel {} -class MarianMTModel extends MarianPreTrainedModel { - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } -} -class M2M100PreTrainedModel extends PreTrainedModel {} -class M2M100Model extends M2M100PreTrainedModel {} -class M2M100ForConditionalGeneration extends M2M100PreTrainedModel { - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } -} -class Wav2Vec2PreTrainedModel extends PreTrainedModel {} -class Wav2Vec2Model extends Wav2Vec2PreTrainedModel {} -class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel { - async _call(e) { - return new CausalLMOutput(await super._call(e)); - } -} -class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class UniSpeechPreTrainedModel extends PreTrainedModel {} -class UniSpeechModel extends UniSpeechPreTrainedModel {} -class UniSpeechForCTC extends UniSpeechPreTrainedModel { - async _call(e) { - return new CausalLMOutput(await super._call(e)); - } -} -class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class UniSpeechSatPreTrainedModel extends PreTrainedModel {} -class UniSpeechSatModel extends UniSpeechSatPreTrainedModel {} -class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel { - async _call(e) { - return new CausalLMOutput(await super._call(e)); - } -} -class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class Wav2Vec2BertPreTrainedModel extends PreTrainedModel {} -class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel {} -class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel { - async _call(e) { - return new CausalLMOutput(await super._call(e)); - } -} -class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class HubertModel extends Wav2Vec2PreTrainedModel {} -class HubertForCTC extends Wav2Vec2PreTrainedModel { - async _call(e) { - return new CausalLMOutput(await super._call(e)); - } -} -class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class WavLMPreTrainedModel extends PreTrainedModel {} -class WavLMModel extends WavLMPreTrainedModel {} -class WavLMForCTC extends WavLMPreTrainedModel { - async _call(e) { - return new CausalLMOutput(await super._call(e)); - } -} -class WavLMForSequenceClassification extends WavLMPreTrainedModel { - async _call(e) { - return new SequenceClassifierOutput(await super._call(e)); - } -} -class WavLMForXVector extends WavLMPreTrainedModel { - async _call(e) { - return new XVectorOutput(await super._call(e)); - } -} -class WavLMForAudioFrameClassification extends WavLMPreTrainedModel { - async _call(e) { - return new TokenClassifierOutput(await super._call(e)); - } -} -class SpeechT5PreTrainedModel extends PreTrainedModel {} -class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel {} -class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel { - constructor(e, o, i, u) { - super(e, o), - (this.decoder_merged_session = i), - (this.generation_config = u), - (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); - } - async generate_speech( - e, - o, - { threshold: i = 0.5, minlenratio: u = 0, maxlenratio: n = 20, vocoder: s = null } = {} - ) { - const d = { input_ids: e }, - { encoder_outputs: f, encoder_attention_mask: r } = await encoderForward(this, d), - a = f.dims[1] / this.config.reduction_factor, - l = Math.floor(a * n), - p = Math.floor(a * u), - m = this.config.num_mel_bins; - let y = [], - T = null, - v = null, - S = 0; - for (;;) { - ++S; - const F = boolTensor(!!v); - let B; - v ? (B = v.output_sequence_out) : (B = new Tensor('float32', new Float32Array(m), [1, 1, m])); - let J = { - use_cache_branch: F, - output_sequence: B, - encoder_attention_mask: r, - speaker_embeddings: o, - encoder_hidden_states: f, - }; - this.addPastKeyValues(J, T), - (v = await sessionRun(this.decoder_merged_session, J)), - (T = this.getPastKeyValues(v, T)); - const { prob: Q, spectrum: re } = v; - if ((y.push(re), S >= p && (Array.from(Q.data).filter((V) => V >= i).length > 0 || S >= l))) break; - } - const E = cat(y), - { waveform: A } = await sessionRun(s.session, { spectrogram: E }); - return { spectrogram: E, waveform: A }; - } -} -class SpeechT5HifiGan extends PreTrainedModel { - main_input_name = 'spectrogram'; -} -class TrOCRPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (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); - } -} -class TrOCRForCausalLM extends TrOCRPreTrainedModel {} -class MistralPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.num_key_value_heads), - (this.num_layers = this.config.num_hidden_layers), - (this.dim_kv = this.config.hidden_size / this.config.num_attention_heads); - } -} -class MistralModel extends MistralPreTrainedModel {} -class MistralForCausalLM extends MistralPreTrainedModel {} -class Starcoder2PreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.num_key_value_heads), - (this.num_layers = this.config.num_hidden_layers), - (this.dim_kv = this.config.hidden_size / this.config.num_attention_heads); - } -} -class Starcoder2Model extends Starcoder2PreTrainedModel {} -class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel {} -class FalconPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.num_attention_heads), - (this.num_layers = this.config.num_hidden_layers), - (this.dim_kv = this.config.hidden_size / this.config.num_attention_heads); - } -} -class FalconModel extends FalconPreTrainedModel {} -class FalconForCausalLM extends FalconPreTrainedModel {} -class ClapPreTrainedModel extends PreTrainedModel {} -class ClapModel extends ClapPreTrainedModel {} -class ClapTextModelWithProjection extends ClapPreTrainedModel { - static async from_pretrained(e, o = {}) { - return (o.model_file_name ??= 'text_model'), super.from_pretrained(e, o); - } -} -class ClapAudioModelWithProjection extends ClapPreTrainedModel { - static async from_pretrained(e, o = {}) { - return (o.model_file_name ??= 'audio_model'), super.from_pretrained(e, o); - } -} -class VitsPreTrainedModel extends PreTrainedModel {} -class VitsModel extends VitsPreTrainedModel { - async _call(e) { - return new VitsModelOutput(await super._call(e)); - } -} -class SegformerPreTrainedModel extends PreTrainedModel {} -class SegformerForImageClassification extends SegformerPreTrainedModel {} -class SegformerForSemanticSegmentation extends SegformerPreTrainedModel {} -class StableLmPreTrainedModel extends PreTrainedModel { - constructor(e, o, i) { - super(e, o), - (this.generation_config = i), - (this.config.pad_token_id = this.config.eos_token_id), - (this.num_heads = this.config.num_attention_heads), - (this.num_layers = this.config.num_hidden_layers), - (this.dim_kv = this.config.hidden_size / this.num_heads); - } -} -class StableLmForCausalLM extends StableLmPreTrainedModel {} -class PretrainedMixin { - static MODEL_CLASS_MAPPINGS = null; - static BASE_IF_FAIL = !1; - static async from_pretrained( - e, - { - quantized: o = !0, - progress_callback: i = null, - config: u = null, - cache_dir: n = null, - local_files_only: s = !1, - revision: d = 'main', - model_file_name: f = null, - session_options: r = {}, - } = {} - ) { - let a = { - quantized: o, - progress_callback: i, - config: u, - cache_dir: n, - local_files_only: s, - revision: d, - model_file_name: f, - session_options: r, - }; - if (((u = await AutoConfig.from_pretrained(e, a)), a.config || (a.config = u), !this.MODEL_CLASS_MAPPINGS)) - throw new Error('`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: ' + this.name); - for (let l of this.MODEL_CLASS_MAPPINGS) { - const p = l.get(u.model_type); - if (p) return await p[1].from_pretrained(e, a); - } - if (this.BASE_IF_FAIL) - return ( - console.warn(`Unknown model class "${u.model_type}", attempting to construct from base class.`), - await PreTrainedModel.from_pretrained(e, a) - ); - throw Error(`Unsupported model type: ${u.model_type}`); - } -} -const MODEL_MAPPING_NAMES_ENCODER_ONLY = new Map([ - ['bert', ['BertModel', BertModel]], - ['nomic_bert', ['NomicBertModel', NomicBertModel]], - ['roformer', ['RoFormerModel', RoFormerModel]], - ['electra', ['ElectraModel', ElectraModel]], - ['esm', ['EsmModel', EsmModel]], - ['convbert', ['ConvBertModel', ConvBertModel]], - ['camembert', ['CamembertModel', CamembertModel]], - ['deberta', ['DebertaModel', DebertaModel]], - ['deberta-v2', ['DebertaV2Model', DebertaV2Model]], - ['mpnet', ['MPNetModel', MPNetModel]], - ['albert', ['AlbertModel', AlbertModel]], - ['distilbert', ['DistilBertModel', DistilBertModel]], - ['roberta', ['RobertaModel', RobertaModel]], - ['xlm', ['XLMModel', XLMModel]], - ['xlm-roberta', ['XLMRobertaModel', XLMRobertaModel]], - ['clap', ['ClapModel', ClapModel]], - ['clip', ['CLIPModel', CLIPModel]], - ['clipseg', ['CLIPSegModel', CLIPSegModel]], - ['chinese_clip', ['ChineseCLIPModel', ChineseCLIPModel]], - ['siglip', ['SiglipModel', SiglipModel]], - ['mobilebert', ['MobileBertModel', MobileBertModel]], - ['squeezebert', ['SqueezeBertModel', SqueezeBertModel]], - ['wav2vec2', ['Wav2Vec2Model', Wav2Vec2Model]], - ['wav2vec2-bert', ['Wav2Vec2BertModel', Wav2Vec2BertModel]], - ['unispeech', ['UniSpeechModel', UniSpeechModel]], - ['unispeech-sat', ['UniSpeechSatModel', UniSpeechSatModel]], - ['hubert', ['HubertModel', HubertModel]], - ['wavlm', ['WavLMModel', WavLMModel]], - ['audio-spectrogram-transformer', ['ASTModel', ASTModel]], - ['vits', ['VitsModel', VitsModel]], - ['detr', ['DetrModel', DetrModel]], - ['table-transformer', ['TableTransformerModel', TableTransformerModel]], - ['vit', ['ViTModel', ViTModel]], - ['mobilevit', ['MobileViTModel', MobileViTModel]], - ['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]], - ]), - MODEL_MAPPING_NAMES_ENCODER_DECODER = new Map([ - ['t5', ['T5Model', T5Model]], - ['longt5', ['LongT5Model', LongT5Model]], - ['mt5', ['MT5Model', MT5Model]], - ['bart', ['BartModel', BartModel]], - ['mbart', ['MBartModel', MBartModel]], - ['marian', ['MarianModel', MarianModel]], - ['whisper', ['WhisperModel', WhisperModel]], - ['m2m_100', ['M2M100Model', M2M100Model]], - ['blenderbot', ['BlenderbotModel', BlenderbotModel]], - ['blenderbot-small', ['BlenderbotSmallModel', BlenderbotSmallModel]], - ]), - MODEL_MAPPING_NAMES_DECODER_ONLY = new Map([ - ['bloom', ['BloomModel', BloomModel]], - ['gpt2', ['GPT2Model', GPT2Model]], - ['gptj', ['GPTJModel', GPTJModel]], - ['gpt_bigcode', ['GPTBigCodeModel', GPTBigCodeModel]], - ['gpt_neo', ['GPTNeoModel', GPTNeoModel]], - ['gpt_neox', ['GPTNeoXModel', GPTNeoXModel]], - ['codegen', ['CodeGenModel', CodeGenModel]], - ['llama', ['LlamaModel', LlamaModel]], - ['qwen2', ['Qwen2Model', Qwen2Model]], - ['phi', ['PhiModel', PhiModel]], - ['mpt', ['MptModel', MptModel]], - ['opt', ['OPTModel', OPTModel]], - ['mistral', ['MistralModel', MistralModel]], - ['starcoder2', ['Starcoder2Model', Starcoder2Model]], - ['falcon', ['FalconModel', FalconModel]], - ]), - MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = new Map([ - ['speecht5', ['SpeechT5ForSpeechToText', SpeechT5ForSpeechToText]], - ['whisper', ['WhisperForConditionalGeneration', WhisperForConditionalGeneration]], - ]), - MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = new Map([ - ['speecht5', ['SpeechT5ForTextToSpeech', SpeechT5ForTextToSpeech]], - ]), - MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = new Map([['vits', ['VitsModel', VitsModel]]]), - MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = new Map([ - ['bert', ['BertForSequenceClassification', BertForSequenceClassification]], - ['roformer', ['RoFormerForSequenceClassification', RoFormerForSequenceClassification]], - ['electra', ['ElectraForSequenceClassification', ElectraForSequenceClassification]], - ['esm', ['EsmForSequenceClassification', EsmForSequenceClassification]], - ['convbert', ['ConvBertForSequenceClassification', ConvBertForSequenceClassification]], - ['camembert', ['CamembertForSequenceClassification', CamembertForSequenceClassification]], - ['deberta', ['DebertaForSequenceClassification', DebertaForSequenceClassification]], - ['deberta-v2', ['DebertaV2ForSequenceClassification', DebertaV2ForSequenceClassification]], - ['mpnet', ['MPNetForSequenceClassification', MPNetForSequenceClassification]], - ['albert', ['AlbertForSequenceClassification', AlbertForSequenceClassification]], - ['distilbert', ['DistilBertForSequenceClassification', DistilBertForSequenceClassification]], - ['roberta', ['RobertaForSequenceClassification', RobertaForSequenceClassification]], - ['xlm', ['XLMForSequenceClassification', XLMForSequenceClassification]], - ['xlm-roberta', ['XLMRobertaForSequenceClassification', XLMRobertaForSequenceClassification]], - ['bart', ['BartForSequenceClassification', BartForSequenceClassification]], - ['mbart', ['MBartForSequenceClassification', MBartForSequenceClassification]], - ['mobilebert', ['MobileBertForSequenceClassification', MobileBertForSequenceClassification]], - ['squeezebert', ['SqueezeBertForSequenceClassification', SqueezeBertForSequenceClassification]], - ]), - MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = new Map([ - ['bert', ['BertForTokenClassification', BertForTokenClassification]], - ['roformer', ['RoFormerForTokenClassification', RoFormerForTokenClassification]], - ['electra', ['ElectraForTokenClassification', ElectraForTokenClassification]], - ['esm', ['EsmForTokenClassification', EsmForTokenClassification]], - ['convbert', ['ConvBertForTokenClassification', ConvBertForTokenClassification]], - ['camembert', ['CamembertForTokenClassification', CamembertForTokenClassification]], - ['deberta', ['DebertaForTokenClassification', DebertaForTokenClassification]], - ['deberta-v2', ['DebertaV2ForTokenClassification', DebertaV2ForTokenClassification]], - ['mpnet', ['MPNetForTokenClassification', MPNetForTokenClassification]], - ['distilbert', ['DistilBertForTokenClassification', DistilBertForTokenClassification]], - ['roberta', ['RobertaForTokenClassification', RobertaForTokenClassification]], - ['xlm', ['XLMForTokenClassification', XLMForTokenClassification]], - ['xlm-roberta', ['XLMRobertaForTokenClassification', XLMRobertaForTokenClassification]], - ]), - MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = new Map([ - ['t5', ['T5ForConditionalGeneration', T5ForConditionalGeneration]], - ['longt5', ['LongT5ForConditionalGeneration', LongT5ForConditionalGeneration]], - ['mt5', ['MT5ForConditionalGeneration', MT5ForConditionalGeneration]], - ['bart', ['BartForConditionalGeneration', BartForConditionalGeneration]], - ['mbart', ['MBartForConditionalGeneration', MBartForConditionalGeneration]], - ['marian', ['MarianMTModel', MarianMTModel]], - ['m2m_100', ['M2M100ForConditionalGeneration', M2M100ForConditionalGeneration]], - ['blenderbot', ['BlenderbotForConditionalGeneration', BlenderbotForConditionalGeneration]], - ['blenderbot-small', ['BlenderbotSmallForConditionalGeneration', BlenderbotSmallForConditionalGeneration]], - ]), - MODEL_WITH_LM_HEAD_MAPPING_NAMES = new Map([ - ['bloom', ['BloomForCausalLM', BloomForCausalLM]], - ['gpt2', ['GPT2LMHeadModel', GPT2LMHeadModel]], - ['gptj', ['GPTJForCausalLM', GPTJForCausalLM]], - ['gpt_bigcode', ['GPTBigCodeForCausalLM', GPTBigCodeForCausalLM]], - ['gpt_neo', ['GPTNeoForCausalLM', GPTNeoForCausalLM]], - ['gpt_neox', ['GPTNeoXForCausalLM', GPTNeoXForCausalLM]], - ['codegen', ['CodeGenForCausalLM', CodeGenForCausalLM]], - ['llama', ['LlamaForCausalLM', LlamaForCausalLM]], - ['qwen2', ['Qwen2ForCausalLM', Qwen2ForCausalLM]], - ['phi', ['PhiForCausalLM', PhiForCausalLM]], - ['mpt', ['MptForCausalLM', MptForCausalLM]], - ['opt', ['OPTForCausalLM', OPTForCausalLM]], - ['mbart', ['MBartForCausalLM', MBartForCausalLM]], - ['mistral', ['MistralForCausalLM', MistralForCausalLM]], - ['starcoder2', ['Starcoder2ForCausalLM', Starcoder2ForCausalLM]], - ['falcon', ['FalconForCausalLM', FalconForCausalLM]], - ['trocr', ['TrOCRForCausalLM', TrOCRForCausalLM]], - ['stablelm', ['StableLmForCausalLM', StableLmForCausalLM]], - ]), - MODEL_FOR_MASKED_LM_MAPPING_NAMES = new Map([ - ['bert', ['BertForMaskedLM', BertForMaskedLM]], - ['roformer', ['RoFormerForMaskedLM', RoFormerForMaskedLM]], - ['electra', ['ElectraForMaskedLM', ElectraForMaskedLM]], - ['esm', ['EsmForMaskedLM', EsmForMaskedLM]], - ['convbert', ['ConvBertForMaskedLM', ConvBertForMaskedLM]], - ['camembert', ['CamembertForMaskedLM', CamembertForMaskedLM]], - ['deberta', ['DebertaForMaskedLM', DebertaForMaskedLM]], - ['deberta-v2', ['DebertaV2ForMaskedLM', DebertaV2ForMaskedLM]], - ['mpnet', ['MPNetForMaskedLM', MPNetForMaskedLM]], - ['albert', ['AlbertForMaskedLM', AlbertForMaskedLM]], - ['distilbert', ['DistilBertForMaskedLM', DistilBertForMaskedLM]], - ['roberta', ['RobertaForMaskedLM', RobertaForMaskedLM]], - ['xlm', ['XLMWithLMHeadModel', XLMWithLMHeadModel]], - ['xlm-roberta', ['XLMRobertaForMaskedLM', XLMRobertaForMaskedLM]], - ['mobilebert', ['MobileBertForMaskedLM', MobileBertForMaskedLM]], - ['squeezebert', ['SqueezeBertForMaskedLM', SqueezeBertForMaskedLM]], - ]), - MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = new Map([ - ['bert', ['BertForQuestionAnswering', BertForQuestionAnswering]], - ['roformer', ['RoFormerForQuestionAnswering', RoFormerForQuestionAnswering]], - ['electra', ['ElectraForQuestionAnswering', ElectraForQuestionAnswering]], - ['convbert', ['ConvBertForQuestionAnswering', ConvBertForQuestionAnswering]], - ['camembert', ['CamembertForQuestionAnswering', CamembertForQuestionAnswering]], - ['deberta', ['DebertaForQuestionAnswering', DebertaForQuestionAnswering]], - ['deberta-v2', ['DebertaV2ForQuestionAnswering', DebertaV2ForQuestionAnswering]], - ['mpnet', ['MPNetForQuestionAnswering', MPNetForQuestionAnswering]], - ['albert', ['AlbertForQuestionAnswering', AlbertForQuestionAnswering]], - ['distilbert', ['DistilBertForQuestionAnswering', DistilBertForQuestionAnswering]], - ['roberta', ['RobertaForQuestionAnswering', RobertaForQuestionAnswering]], - ['xlm', ['XLMForQuestionAnswering', XLMForQuestionAnswering]], - ['xlm-roberta', ['XLMRobertaForQuestionAnswering', XLMRobertaForQuestionAnswering]], - ['mobilebert', ['MobileBertForQuestionAnswering', MobileBertForQuestionAnswering]], - ['squeezebert', ['SqueezeBertForQuestionAnswering', SqueezeBertForQuestionAnswering]], - ]), - MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = new Map([ - ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]], - ]), - MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = new Map([ - ['vit', ['ViTForImageClassification', ViTForImageClassification]], - ['mobilevit', ['MobileViTForImageClassification', MobileViTForImageClassification]], - ['beit', ['BeitForImageClassification', BeitForImageClassification]], - ['deit', ['DeiTForImageClassification', DeiTForImageClassification]], - ['convnext', ['ConvNextForImageClassification', ConvNextForImageClassification]], - ['convnextv2', ['ConvNextV2ForImageClassification', ConvNextV2ForImageClassification]], - ['dinov2', ['Dinov2ForImageClassification', Dinov2ForImageClassification]], - ['resnet', ['ResNetForImageClassification', ResNetForImageClassification]], - ['swin', ['SwinForImageClassification', SwinForImageClassification]], - ['segformer', ['SegformerForImageClassification', SegformerForImageClassification]], - ]), - MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = new Map([ - ['detr', ['DetrForObjectDetection', DetrForObjectDetection]], - ['table-transformer', ['TableTransformerForObjectDetection', TableTransformerForObjectDetection]], - ['yolos', ['YolosForObjectDetection', YolosForObjectDetection]], - ]), - MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = new Map([ - ['owlvit', ['OwlViTForObjectDetection', OwlViTForObjectDetection]], - ['owlv2', ['Owlv2ForObjectDetection', Owlv2ForObjectDetection]], - ]), - MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = new Map([ - ['detr', ['DetrForSegmentation', DetrForSegmentation]], - ['clipseg', ['CLIPSegForImageSegmentation', CLIPSegForImageSegmentation]], - ]), - MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = new Map([ - ['segformer', ['SegformerForSemanticSegmentation', SegformerForSemanticSegmentation]], - ]), - MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = new Map([['sam', ['SamModel', SamModel]]]), - MODEL_FOR_CTC_MAPPING_NAMES = new Map([ - ['wav2vec2', ['Wav2Vec2ForCTC', Wav2Vec2ForCTC]], - ['wav2vec2-bert', ['Wav2Vec2BertForCTC', Wav2Vec2BertForCTC]], - ['unispeech', ['UniSpeechForCTC', UniSpeechForCTC]], - ['unispeech-sat', ['UniSpeechSatForCTC', UniSpeechSatForCTC]], - ['wavlm', ['WavLMForCTC', WavLMForCTC]], - ['hubert', ['HubertForCTC', HubertForCTC]], - ]), - MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = new Map([ - ['wav2vec2', ['Wav2Vec2ForSequenceClassification', Wav2Vec2ForSequenceClassification]], - ['wav2vec2-bert', ['Wav2Vec2BertForSequenceClassification', Wav2Vec2BertForSequenceClassification]], - ['unispeech', ['UniSpeechForSequenceClassification', UniSpeechForSequenceClassification]], - ['unispeech-sat', ['UniSpeechSatForSequenceClassification', UniSpeechSatForSequenceClassification]], - ['wavlm', ['WavLMForSequenceClassification', WavLMForSequenceClassification]], - ['hubert', ['HubertForSequenceClassification', HubertForSequenceClassification]], - ['audio-spectrogram-transformer', ['ASTForAudioClassification', ASTForAudioClassification]], - ]), - MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = new Map([['wavlm', ['WavLMForXVector', WavLMForXVector]]]), - MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = new Map([ - ['unispeech-sat', ['UniSpeechSatForAudioFrameClassification', UniSpeechSatForAudioFrameClassification]], - ['wavlm', ['WavLMForAudioFrameClassification', WavLMForAudioFrameClassification]], - ['wav2vec2', ['Wav2Vec2ForAudioFrameClassification', Wav2Vec2ForAudioFrameClassification]], - ]), - MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = new Map([ - ['vitmatte', ['VitMatteForImageMatting', VitMatteForImageMatting]], - ]), - MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = new Map([ - ['swin2sr', ['Swin2SRForImageSuperResolution', Swin2SRForImageSuperResolution]], - ]), - MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = new Map([ - ['dpt', ['DPTForDepthEstimation', DPTForDepthEstimation]], - ['depth_anything', ['DepthAnythingForDepthEstimation', DepthAnythingForDepthEstimation]], - ['glpn', ['GLPNForDepthEstimation', GLPNForDepthEstimation]], - ]), - 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], - ]; -for (const [t, e] of MODEL_CLASS_TYPE_MAPPING) - for (const [o, i] of t.values()) - MODEL_TYPE_MAPPING.set(o, e), MODEL_CLASS_TO_NAME_MAPPING.set(i, o), MODEL_NAME_TO_CLASS_MAPPING.set(o, i); -const CUSTOM_MAPPING = [ - ['CLIPTextModelWithProjection', CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly], - ['CLIPVisionModelWithProjection', CLIPVisionModelWithProjection, MODEL_TYPES.EncoderOnly], - ['SiglipTextModel', SiglipTextModel, MODEL_TYPES.EncoderOnly], - ['SiglipVisionModel', SiglipVisionModel, MODEL_TYPES.EncoderOnly], - ['ClapTextModelWithProjection', ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly], - ['ClapAudioModelWithProjection', ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly], -]; -for (const [t, e, o] of CUSTOM_MAPPING) - MODEL_TYPE_MAPPING.set(t, o), MODEL_CLASS_TO_NAME_MAPPING.set(e, t), MODEL_NAME_TO_CLASS_MAPPING.set(t, e); -class AutoModel extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map((e) => e[0]); - static BASE_IF_FAIL = !0; -} -class Seq2SeqLMOutput extends ModelOutput { - constructor({ - logits: e, - past_key_values: o, - encoder_outputs: i, - decoder_attentions: u = null, - cross_attentions: n = null, - }) { - super(), - (this.logits = e), - (this.past_key_values = o), - (this.encoder_outputs = i), - (this.decoder_attentions = u), - (this.cross_attentions = n); - } -} -class SequenceClassifierOutput extends ModelOutput { - constructor({ logits: e }) { - super(), (this.logits = e); - } -} -class XVectorOutput extends ModelOutput { - constructor({ logits: e, embeddings: o }) { - super(), (this.logits = e), (this.embeddings = o); - } -} -class TokenClassifierOutput extends ModelOutput { - constructor({ logits: e }) { - super(), (this.logits = e); - } -} -class MaskedLMOutput extends ModelOutput { - constructor({ logits: e }) { - super(), (this.logits = e); - } -} -class QuestionAnsweringModelOutput extends ModelOutput { - constructor({ start_logits: e, end_logits: o }) { - super(), (this.start_logits = e), (this.end_logits = o); - } -} -class CausalLMOutput extends ModelOutput { - constructor({ logits: e }) { - super(), (this.logits = e); - } -} -class ImageMattingOutput extends ModelOutput { - constructor({ alphas: e }) { - super(), (this.alphas = e); - } -} -class VitsModelOutput extends ModelOutput { - constructor({ waveform: e, spectrogram: o }) { - super(), (this.waveform = e), (this.spectrogram = o); - } -} -const BROWSER_ENV = typeof self < 'u', - WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope'; -let createCanvasFunction, ImageDataClass, loadImageFunction; -if (BROWSER_ENV) - (createCanvasFunction = (t, e) => { - if (!self.OffscreenCanvas) throw new Error('OffscreenCanvas not supported by this browser.'); - return new self.OffscreenCanvas(t, e); - }), - (loadImageFunction = self.createImageBitmap), - (ImageDataClass = self.ImageData); -else if (sharp) - loadImageFunction = async (t) => { - const o = (await t.metadata()).channels, - { data: i, info: u } = await t.raw().toBuffer({ resolveWithObject: !0 }), - n = new RawImage(new Uint8ClampedArray(i), u.width, u.height, u.channels); - return o !== void 0 && o !== u.channels && n.convert(o), n; - }; -else throw new Error('Unable to load image processing library.'); -const RESAMPLING_MAPPING = { 0: 'nearest', 1: 'lanczos', 2: 'bilinear', 3: 'bicubic', 4: 'box', 5: 'hamming' }, - CONTENT_TYPE_MAP = new Map([ - ['png', 'image/png'], - ['jpg', 'image/jpeg'], - ['jpeg', 'image/jpeg'], - ['gif', 'image/gif'], - ]); -class RawImage { - constructor(e, o, i, u) { - (this.data = e), (this.width = o), (this.height = i), (this.channels = u); - } - get size() { - return [this.width, this.height]; - } - static async read(e) { - if (e instanceof RawImage) return e; - if (typeof e == 'string' || e instanceof URL) return await this.fromURL(e); - throw new Error(`Unsupported input type: ${typeof e}`); - } - static async fromURL(e) { - const o = await getFile(e); - if (o.status !== 200) throw new Error(`Unable to read image from "${e}" (${o.status} ${o.statusText})`); - const i = await o.blob(); - return this.fromBlob(i); - } - static async fromBlob(e) { - if (BROWSER_ENV) { - const o = await loadImageFunction(e), - i = createCanvasFunction(o.width, o.height).getContext('2d'); - return i.drawImage(o, 0, 0), new this(i.getImageData(0, 0, o.width, o.height).data, o.width, o.height, 4); - } else { - const o = sharp(await e.arrayBuffer()); - return await loadImageFunction(o); - } - } - static fromTensor(e, o = 'CHW') { - if (e.dims.length !== 3) - throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`); - if (o === 'CHW') e = e.transpose(1, 2, 0); - else if (o !== 'HWC') throw new Error(`Unsupported channel format: ${o}`); - if (!(e.data instanceof Uint8ClampedArray || e.data instanceof Uint8Array)) - throw new Error(`Unsupported tensor type: ${e.type}`); - switch (e.dims[2]) { - case 1: - case 2: - case 3: - case 4: - return new RawImage(e.data, e.dims[1], e.dims[0], e.dims[2]); - default: - throw new Error(`Unsupported number of channels: ${e.dims[2]}`); - } - } - grayscale() { - if (this.channels === 1) return this; - const e = new Uint8ClampedArray(this.width * this.height * 1); - switch (this.channels) { - case 3: - case 4: - for (let o = 0, i = 0; o < this.data.length; o += this.channels) { - const u = this.data[o], - n = this.data[o + 1], - s = this.data[o + 2]; - e[i++] = Math.round(0.2989 * u + 0.587 * n + 0.114 * s); - } - break; - default: - throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); - } - return this._update(e, this.width, this.height, 1); - } - rgb() { - if (this.channels === 3) return this; - const e = new Uint8ClampedArray(this.width * this.height * 3); - switch (this.channels) { - case 1: - for (let o = 0, i = 0; o < this.data.length; ++o) - (e[i++] = this.data[o]), (e[i++] = this.data[o]), (e[i++] = this.data[o]); - break; - case 4: - for (let o = 0, i = 0; o < this.data.length; o += 4) - (e[i++] = this.data[o]), (e[i++] = this.data[o + 1]), (e[i++] = this.data[o + 2]); - break; - default: - throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); - } - return this._update(e, this.width, this.height, 3); - } - rgba() { - if (this.channels === 4) return this; - const e = new Uint8ClampedArray(this.width * this.height * 4); - switch (this.channels) { - case 1: - for (let o = 0, i = 0; o < this.data.length; ++o) - (e[i++] = this.data[o]), (e[i++] = this.data[o]), (e[i++] = this.data[o]), (e[i++] = 255); - break; - case 3: - for (let o = 0, i = 0; o < this.data.length; o += 3) - (e[i++] = this.data[o]), (e[i++] = this.data[o + 1]), (e[i++] = this.data[o + 2]), (e[i++] = 255); - break; - default: - throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); - } - return this._update(e, this.width, this.height, 4); - } - async resize(e, o, { resample: i = 2 } = {}) { - let u = RESAMPLING_MAPPING[i] ?? i; - if (BROWSER_ENV) { - const n = this.channels, - s = this.toCanvas(), - d = createCanvasFunction(e, o).getContext('2d'); - return d.drawImage(s, 0, 0, e, o), new RawImage(d.getImageData(0, 0, e, o).data, e, o, 4).convert(n); - } else { - let n = this.toSharp(); - switch (u) { - case 'box': - case 'hamming': - (u === 'box' || u === 'hamming') && - (console.warn(`Resampling method ${u} is not yet supported. Using bilinear instead.`), - (u = 'bilinear')); - case 'nearest': - case 'bilinear': - case 'bicubic': - n = n.affine([e / this.width, 0, 0, o / this.height], { interpolator: u }); - break; - case 'lanczos': - n = n.resize({ width: e, height: o, fit: 'fill', kernel: 'lanczos3' }); - break; - default: - throw new Error(`Resampling method ${u} is not supported.`); - } - return await loadImageFunction(n); - } - } - async pad([e, o, i, u]) { - if ( - ((e = Math.max(e, 0)), - (o = Math.max(o, 0)), - (i = Math.max(i, 0)), - (u = Math.max(u, 0)), - e === 0 && o === 0 && i === 0 && u === 0) - ) - return this; - if (BROWSER_ENV) { - const n = this.channels, - s = this.toCanvas(), - d = this.width + e + o, - f = this.height + i + u, - r = createCanvasFunction(d, f).getContext('2d'); - return ( - r.drawImage(s, 0, 0, this.width, this.height, e, i, d, f), - new RawImage(r.getImageData(0, 0, d, f).data, d, f, 4).convert(n) - ); - } else { - const n = this.toSharp().extend({ left: e, right: o, top: i, bottom: u }); - return await loadImageFunction(n); - } - } - async crop([e, o, i, u]) { - if ( - ((e = Math.max(e, 0)), - (o = Math.max(o, 0)), - (i = Math.min(i, this.width - 1)), - (u = Math.min(u, this.height - 1)), - e === 0 && o === 0 && i === this.width - 1 && u === this.height - 1) - ) - return this; - const n = i - e + 1, - s = u - o + 1; - if (BROWSER_ENV) { - const d = this.channels, - f = this.toCanvas(), - r = createCanvasFunction(n, s).getContext('2d'); - return ( - r.drawImage(f, e, o, n, s, 0, 0, n, s), - new RawImage(r.getImageData(0, 0, n, s).data, n, s, 4).convert(d) - ); - } else { - const d = this.toSharp().extract({ left: e, top: o, width: n, height: s }); - return await loadImageFunction(d); - } - } - async center_crop(e, o) { - if (this.width === e && this.height === o) return this; - const i = (this.width - e) / 2, - u = (this.height - o) / 2; - if (BROWSER_ENV) { - const n = this.channels, - s = this.toCanvas(), - d = createCanvasFunction(e, o).getContext('2d'); - let f = 0, - r = 0, - a = 0, - l = 0; - return ( - i >= 0 ? (f = i) : (a = -i), - u >= 0 ? (r = u) : (l = -u), - d.drawImage(s, f, r, e, o, a, l, e, o), - new RawImage(d.getImageData(0, 0, e, o).data, e, o, 4).convert(n) - ); - } else { - let n = this.toSharp(); - if (i >= 0 && u >= 0) n = n.extract({ left: Math.floor(i), top: Math.floor(u), width: e, height: o }); - else if (i <= 0 && u <= 0) { - const s = Math.floor(-u), - d = Math.floor(-i); - n = n.extend({ top: s, left: d, right: e - this.width - d, bottom: o - this.height - s }); - } else { - let s = [0, 0], - d = 0; - u < 0 ? ((s[0] = Math.floor(-u)), (s[1] = o - this.height - s[0])) : (d = Math.floor(u)); - let f = [0, 0], - r = 0; - i < 0 ? ((f[0] = Math.floor(-i)), (f[1] = e - this.width - f[0])) : (r = Math.floor(i)), - (n = n - .extend({ top: s[0], bottom: s[1], left: f[0], right: f[1] }) - .extract({ left: r, top: d, width: e, height: o })); - } - return await loadImageFunction(n); - } - } - async toBlob(e = 'image/png', o = 1) { - if (!BROWSER_ENV) throw new Error('toBlob() is only supported in browser environments.'); - return await this.toCanvas().convertToBlob({ type: e, quality: o }); - } - toCanvas() { - if (!BROWSER_ENV) throw new Error('toCanvas() is only supported in browser environments.'); - const e = this.clone().rgba(), - o = createCanvasFunction(e.width, e.height), - i = new ImageDataClass(e.data, e.width, e.height); - return o.getContext('2d').putImageData(i, 0, 0), o; - } - _update(e, o, i, u = null) { - return (this.data = e), (this.width = o), (this.height = i), u !== null && (this.channels = u), this; - } - clone() { - return new RawImage(this.data.slice(), this.width, this.height, this.channels); - } - convert(e) { - if (this.channels === e) return this; - switch (e) { - 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; - } - async save(e) { - if (BROWSER_ENV) { - if (WEBWORKER_ENV) throw new Error('Unable to save an image from a Web Worker.'); - const o = e.split('.').pop().toLowerCase(), - i = CONTENT_TYPE_MAP.get(o) ?? 'image/png', - u = await this.toBlob(i), - n = URL.createObjectURL(u), - s = document.createElement('a'); - (s.href = n), (s.download = e), s.click(), s.remove(); - } else { - if (env.useFS) return await this.toSharp().toFile(e); - throw new Error('Unable to save the image because filesystem is disabled in this environment.'); - } - } - toSharp() { - if (BROWSER_ENV) throw new Error('toSharp() is only supported in server-side environments.'); - return sharp(this.data, { raw: { width: this.width, height: this.height, channels: this.channels } }); - } -} -function hanning(t) { - if (t < 1) return new Float64Array(); - if (t === 1) return new Float64Array([1]); - const e = t - 1, - o = Math.PI / e, - i = new Float64Array(t); - for (let u = 0; u < t; ++u) { - const n = 2 * u - e; - i[u] = 0.5 + 0.5 * Math.cos(o * n); - } - return i; -} -const HERTZ_TO_MEL_MAPPING = { - htk: (t) => 2595 * Math.log10(1 + t / 700), - kaldi: (t) => 1127 * Math.log(1 + t / 700), - slaney: (t, e = 1e3, o = 15, i = 27 / Math.log(6.4)) => (t >= e ? o + Math.log(t / e) * i : (3 * t) / 200), -}; -function hertz_to_mel(t, e = 'htk') { - const o = HERTZ_TO_MEL_MAPPING[e]; - if (!o) throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); - return typeof t == 'number' ? o(t) : t.map((i) => o(i)); -} -const MEL_TO_HERTZ_MAPPING = { - htk: (t) => 700 * (10 ** (t / 2595) - 1), - kaldi: (t) => 700 * (Math.exp(t / 1127) - 1), - slaney: (t, e = 1e3, o = 15, i = Math.log(6.4) / 27) => (t >= o ? e * Math.exp(i * (t - o)) : (200 * t) / 3), -}; -function mel_to_hertz(t, e = 'htk') { - const o = MEL_TO_HERTZ_MAPPING[e]; - if (!o) throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); - return typeof t == 'number' ? o(t) : t.map((i) => o(i)); -} -function _create_triangular_filter_bank(t, e) { - const o = Float64Array.from({ length: e.length - 1 }, (s, d) => e[d + 1] - e[d]), - i = Array.from({ length: t.length }, () => new Array(e.length)); - for (let s = 0; s < t.length; ++s) { - const d = i[s]; - for (let f = 0; f < e.length; ++f) d[f] = e[f] - t[s]; - } - const u = e.length - 2, - n = Array.from({ length: u }, () => new Array(t.length)); - for (let s = 0; s < t.length; ++s) { - const d = i[s]; - for (let f = 0; f < u; ++f) { - const r = -d[f] / o[f], - a = d[f + 2] / o[f + 1]; - n[f][s] = Math.max(0, Math.min(r, a)); - } - } - return n; -} -function linspace(t, e, o) { - const i = (e - t) / (o - 1); - return Float64Array.from({ length: o }, (u, n) => t + i * n); -} -function mel_filter_bank(t, e, o, i, u, n = null, s = 'htk', d = !1) { - if (n !== null && n !== 'slaney') throw new Error('norm must be one of null or "slaney"'); - const f = hertz_to_mel(o, s), - r = hertz_to_mel(i, s), - a = linspace(f, r, e + 2); - let l = mel_to_hertz(a, s), - p; - if (d) { - const y = u / (t * 2); - (p = hertz_to_mel( - Float64Array.from({ length: t }, (T, v) => v * y), - s - )), - (l = a); - } else p = linspace(0, Math.floor(u / 2), t); - const m = _create_triangular_filter_bank(p, l); - if (n !== null && n === 'slaney') - for (let y = 0; y < e; ++y) { - const T = m[y], - v = 2 / (l[y + 2] - l[y]); - for (let S = 0; S < t; ++S) T[S] *= v; - } - return m; -} -function padReflect(t, e, o) { - const i = new t.constructor(t.length + e + o), - u = t.length - 1; - for (let n = 0; n < t.length; ++n) i[e + n] = t[n]; - for (let n = 1; n <= e; ++n) i[e - n] = t[calculateReflectOffset(n, u)]; - for (let n = 1; n <= o; ++n) i[u + e + n] = t[calculateReflectOffset(u - n, u)]; - return i; -} -function _db_conversion_helper(t, e, o, i, u) { - if (o <= 0) throw new Error('reference must be greater than zero'); - if (i <= 0) throw new Error('min_value must be greater than zero'); - o = Math.max(i, o); - const n = Math.log10(o); - for (let s = 0; s < t.length; ++s) t[s] = e * Math.log10(Math.max(i, t[s]) - n); - if (u !== null) { - if (u <= 0) throw new Error('db_range must be greater than zero'); - const s = max(t)[0] - u; - for (let d = 0; d < t.length; ++d) t[d] = Math.max(t[d], s); - } - return t; -} -function amplitude_to_db(t, e = 1, o = 1e-5, i = null) { - return _db_conversion_helper(t, 20, e, o, i); -} -function power_to_db(t, e = 1, o = 1e-10, i = null) { - return _db_conversion_helper(t, 10, e, o, i); -} -function spectrogram( - t, - e, - o, - i, - { - fft_length: u = null, - power: n = 1, - center: s = !0, - pad_mode: d = 'reflect', - onesided: f = !0, - preemphasis: r = null, - mel_filters: a = null, - mel_floor: l = 1e-10, - log_mel: p = null, - reference: m = 1, - min_value: y = 1e-10, - db_range: T = null, - remove_dc_offset: v = null, - max_num_frames: S = null, - do_pad: E = !0, - transpose: A = !1, - } = {} -) { - const F = e.length; - if ((u === null && (u = o), o > u)) throw Error(`frame_length (${o}) may not be larger than fft_length (${u})`); - if (F !== o) throw new Error(`Length of the window (${F}) must equal frame_length (${o})`); - if (i <= 0) throw new Error('hop_length must be greater than zero'); - if (s) { - if (d !== 'reflect') throw new Error(`pad_mode="${d}" not implemented yet.`); - const he = Math.floor((u - 1) / 2) + 1; - t = padReflect(t, he, he); - } - const B = Math.floor(1 + Math.floor((t.length - o) / i)), - J = f ? Math.floor(u / 2) + 1 : u; - let Q = B, - re = B; - S !== null && (S > B ? E && (re = S) : (re = Q = S)); - const V = new FFT(u), - de = new Float64Array(u), - ke = new Float64Array(V.outputBufferSize), - Ne = new Array(Q); - for (let he = 0; he < Q; ++he) { - const ue = he * i; - for (let X = 0; X < o; ++X) de[X] = t[ue + X]; - if (v) { - let X = 0; - for (let we = 0; we < o; ++we) X += de[we]; - const ve = X / o; - for (let we = 0; we < o; ++we) de[we] -= ve; - } - if (r !== null) { - for (let X = o - 1; X >= 1; --X) de[X] -= r * de[X - 1]; - de[0] *= 1 - r; - } - for (let X = 0; X < e.length; ++X) de[X] *= e[X]; - V.realTransform(ke, de); - const pe = new Array(J); - for (let X = 0; X < pe.length; ++X) { - const ve = X << 1; - pe[X] = ke[ve] ** 2 + ke[ve + 1] ** 2; - } - Ne[he] = pe; - } - if (n !== null && n !== 2) { - const he = 2 / n; - for (let ue = 0; ue < Ne.length; ++ue) { - const pe = Ne[ue]; - for (let X = 0; X < pe.length; ++X) pe[X] **= he; - } - } - const Me = a.length, - Y = new Float32Array(Me * re), - _e = A ? [re, Me] : [Me, re]; - for (let he = 0; he < Me; ++he) { - const ue = a[he]; - for (let pe = 0; pe < Q; ++pe) { - const X = Ne[pe]; - let ve = 0; - for (let we = 0; we < J; ++we) ve += ue[we] * X[we]; - Y[A ? pe * Me + he : he * Q + pe] = Math.max(l, ve); - } - } - if (n !== null && p !== null) { - const he = Math.min(Y.length, Q * Me); - switch (p) { - case 'log': - for (let ue = 0; ue < he; ++ue) Y[ue] = Math.log(Y[ue]); - break; - case 'log10': - for (let ue = 0; ue < he; ++ue) Y[ue] = Math.log10(Y[ue]); - break; - case 'dB': - if (n === 1) amplitude_to_db(Y, m, y, T); - else if (n === 2) power_to_db(Y, m, y, T); - else throw new Error(`Cannot use log_mel option '${p}' with power ${n}`); - break; - default: - throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${p}'`); - } - } - return { data: Y, dims: _e }; -} -function window_function(t, e, { periodic: o = !0, frame_length: i = null, center: u = !0 } = {}) { - const n = o ? t + 1 : t; - let s; - switch (e) { - case 'boxcar': - s = new Float64Array(n).fill(1); - break; - case 'hann': - case 'hann_window': - s = hanning(n); - break; - case 'povey': - s = hanning(n).map((d) => Math.pow(d, 0.85)); - break; - default: - throw new Error(`Unknown window type ${e}.`); - } - if ((o && (s = s.subarray(0, t)), i === null)) return s; - if (t > i) throw new Error(`Length of the window (${t}) may not be larger than frame_length (${i})`); - return s; -} -function center_to_corners_format([t, e, o, i]) { - return [t - o / 2, e - i / 2, t + o / 2, e + i / 2]; -} -function post_process_object_detection(t, e = 0.5, o = null, i = !1) { - const u = t.logits, - n = t.pred_boxes, - [s, d, f] = u.dims; - if (o !== null && o.length !== s) - throw Error('Make sure that you pass in as many target sizes as the batch dimension of the logits'); - let r = []; - for (let a = 0; a < s; ++a) { - let l = o !== null ? o[a] : null, - p = { boxes: [], classes: [], scores: [] }, - m = u[a], - y = n[a]; - for (let T = 0; T < d; ++T) { - let v = m[T], - S = [], - E; - if (i) { - E = v.sigmoid().data; - for (let A = 0; A < E.length; ++A) E[A] > e && S.push(A); - } else { - let A = max(v.data)[1]; - if (A === f - 1) continue; - S.push(A), (E = softmax(v.data)); - } - for (const A of S) { - let F = y[T].data; - (F = center_to_corners_format(F)), - l !== null && (F = F.map((B, J) => B * l[(J + 1) % 2])), - p.boxes.push(F), - p.classes.push(A), - p.scores.push(E[A]); - } - } - r.push(p); - } - return r; -} -function validate_audio_inputs(t, e) { - if (!(t instanceof Float32Array || t instanceof Float64Array)) - throw new Error( - `${e} expects input to be a Float32Array or a Float64Array, but got ${ - t?.constructor?.name ?? typeof t - } 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(t, e, o = 0, i = null) { - let u = Math.round(t / e) * e; - return i !== null && u > i && (u = Math.floor(t / e) * e), u < o && (u = Math.ceil(t / e) * e), u; -} -function enforce_size_divisibility([t, e], o) { - return [Math.floor(t / o) * o, Math.floor(e / o) * o]; -} -class FeatureExtractor extends Callable { - constructor(e) { - super(), (this.config = e); - } -} -class ImageFeatureExtractor extends FeatureExtractor { - constructor(e) { - super(e), - (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 ?? !0), - (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 ?? !0), - (this.do_crop_margin = this.config.do_crop_margin), - (this.pad_size = this.config.pad_size), - (this.do_pad = this.config.do_pad), - this.do_pad && - !this.pad_size && - this.size && - this.size.width !== void 0 && - this.size.height !== void 0 && - (this.pad_size = this.size); - } - async thumbnail(e, o, i = 2) { - const u = e.height, - n = e.width, - s = o.height, - d = o.width; - let f = Math.min(u, s), - r = Math.min(n, d); - return f === u && r === n - ? e - : (u > n ? (r = Math.floor((n * f) / u)) : n > u && (f = Math.floor((u * r) / n)), - await e.resize(r, f, { resample: i })); - } - async crop_margin(e, o = 200) { - const i = e.clone().grayscale(), - u = min(i.data)[0], - s = max(i.data)[0] - u; - if (s === 0) return e; - const d = o / 255; - let f = i.width, - r = i.height, - a = 0, - l = 0; - for (let p = 0; p < i.height; ++p) { - const m = p * i.width; - for (let y = 0; y < i.width; ++y) - (i.data[m + y] - u) / s < d && - ((f = Math.min(f, y)), (r = Math.min(r, p)), (a = Math.max(a, y)), (l = Math.max(l, p))); - } - return (e = await e.crop([f, r, a, l])), e; - } - pad_image(e, o, i, { mode: u = 'constant', center: n = !1, constant_values: s = 0 } = {}) { - const [d, f, r] = o; - let a, l; - if ((typeof i == 'number' ? ((a = i), (l = i)) : ((a = i.width), (l = i.height)), a !== d || l !== f)) { - const p = new Float32Array(a * l * r); - if (Array.isArray(s)) for (let T = 0; T < p.length; ++T) p[T] = s[T % r]; - else s !== 0 && p.fill(s); - const [m, y] = n ? [Math.floor((a - d) / 2), Math.floor((l - f) / 2)] : [0, 0]; - for (let T = 0; T < f; ++T) { - const v = (T + y) * a, - S = T * d; - for (let E = 0; E < d; ++E) { - const A = (v + E + m) * r, - F = (S + E) * r; - for (let B = 0; B < r; ++B) p[A + B] = e[F + B]; - } - } - if (u === 'symmetric') { - if (n) throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.'); - const T = f - 1, - v = d - 1; - for (let S = 0; S < l; ++S) { - const E = S * a, - A = calculateReflectOffset(S, T) * d; - for (let F = 0; F < a; ++F) { - if (S < f && F < d) continue; - const B = (E + F) * r, - J = (A + calculateReflectOffset(F, v)) * r; - for (let Q = 0; Q < r; ++Q) p[B + Q] = e[J + Q]; - } - } - } - (e = p), (o = [l, a, r]); - } - return [e, o]; - } - rescale(e) { - for (let o = 0; o < e.length; ++o) e[o] = this.rescale_factor * e[o]; - } - get_resize_output_image_size(e, o) { - const [i, u] = e.size; - let n, s; - if (this.do_thumbnail) { - const { height: d, width: f } = o; - n = Math.min(d, f); - } else - Number.isInteger(o) - ? ((n = o), (s = this.config.max_size ?? n)) - : o !== void 0 && ((n = o.shortest_edge), (s = o.longest_edge)); - if (n !== void 0 || s !== void 0) { - const d = n === void 0 ? 1 : Math.max(n / i, n / u), - f = i * d, - r = u * d, - a = s === void 0 ? 1 : Math.min(s / f, s / r); - let l = Math.floor(Number((f * a).toFixed(2))), - p = Math.floor(Number((r * a).toFixed(2))); - return ( - this.size_divisibility !== void 0 && - ([l, p] = enforce_size_divisibility([l, p], this.size_divisibility)), - [l, p] - ); - } else if (o !== void 0 && o.width !== void 0 && o.height !== void 0) { - let d = o.width, - f = o.height; - if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) { - let r = o.height / u, - a = o.width / i; - Math.abs(1 - a) < Math.abs(1 - r) ? (r = a) : (a = r), - (f = constraint_to_multiple_of(r * u, this.config.ensure_multiple_of)), - (d = constraint_to_multiple_of(a * i, this.config.ensure_multiple_of)); - } - return [d, f]; - } else { - if (this.size_divisibility !== void 0) return enforce_size_divisibility([i, u], this.size_divisibility); - throw new Error( - `Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(o)}` - ); - } - } - async resize(e) { - const [o, i] = this.get_resize_output_image_size(e, this.size); - return await e.resize(o, i, { resample: this.resample }); - } - async preprocess( - e, - { do_normalize: o = null, do_pad: i = null, do_convert_rgb: u = null, do_convert_grayscale: n = null } = {} - ) { - this.do_crop_margin && (e = await this.crop_margin(e)); - const [s, d] = e.size; - if ( - (u ?? this.do_convert_rgb ? (e = e.rgb()) : n && (e = e.grayscale()), - this.do_resize && (e = await this.resize(e)), - this.do_thumbnail && (e = await this.thumbnail(e, this.size, this.resample)), - this.do_center_crop) - ) { - let m, y; - Number.isInteger(this.crop_size) - ? ((m = this.crop_size), (y = this.crop_size)) - : ((m = this.crop_size.width), (y = this.crop_size.height)), - (e = await e.center_crop(m, y)); - } - const f = [e.height, e.width]; - let r = Float32Array.from(e.data), - a = [e.height, e.width, e.channels]; - if ((this.do_rescale && this.rescale(r), o ?? this.do_normalize)) { - let m = this.image_mean; - Array.isArray(this.image_mean) || (m = new Array(e.channels).fill(m)); - let y = this.image_std; - if ( - (Array.isArray(this.image_std) || (y = new Array(e.channels).fill(m)), - m.length !== e.channels || y.length !== e.channels) - ) - throw new Error( - `When set to arrays, the length of \`image_mean\` (${m.length}) and \`image_std\` (${y.length}) must match the number of channels in the image (${e.channels}).` - ); - for (let T = 0; T < r.length; T += e.channels) - for (let v = 0; v < e.channels; ++v) r[T + v] = (r[T + v] - this.image_mean[v]) / this.image_std[v]; - } - if (this.do_pad && this.pad_size) { - const m = new Float32Array(this.pad_size.width * this.pad_size.height * e.channels); - for (let y = 0; y < e.height; ++y) { - const T = y * this.pad_size.width, - v = y * e.width; - for (let S = 0; S < e.width; ++S) { - const E = (T + S) * e.channels, - A = (v + S) * e.channels; - for (let F = 0; F < e.channels; ++F) m[E + F] = r[A + F]; - } - } - (r = m), (a = [this.pad_size.height, this.pad_size.width, e.channels]); - } - const l = new Tensor('float32', r, a), - p = transpose(l, [2, 0, 1]); - return { original_size: [d, s], reshaped_input_size: f, pixel_values: p }; - } - async _call(e, ...o) { - Array.isArray(e) || (e = [e]); - const i = await Promise.all(e.map((n) => this.preprocess(n))); - return { - pixel_values: stack( - i.map((n) => n.pixel_values), - 0 - ), - original_sizes: i.map((n) => n.original_size), - reshaped_input_sizes: i.map((n) => n.reshaped_input_size), - }; - } -} -class SegformerFeatureExtractor extends ImageFeatureExtractor { - post_process_semantic_segmentation(e, o = null) { - const i = e.logits, - u = i.dims[0]; - if (o !== null && o.length !== u) - throw Error('Make sure that you pass in as many target sizes as the batch dimension of the logits'); - const n = []; - for (let s = 0; s < u; ++s) { - const d = o !== null ? o[s] : null; - let f = i[s]; - d !== null && (f = interpolate(f, d, 'bilinear', !1)); - const [r, a] = d ?? f.dims.slice(-2), - l = new Tensor('int32', new Int32Array(r * a), [r, a]), - p = f[0].data; - for (let v = 1; v < f.dims[0]; ++v) { - const S = f[v].data; - for (let E = 0; E < S.length; ++E) S[E] > p[E] && ((p[E] = S[E]), (l.data[E] = v)); - } - const m = new Array(f.dims[0]), - y = l.data; - for (let v = 0; v < y.length; ++v) { - const S = y[v]; - m[S] = S; - } - const T = m.filter((v) => v !== void 0); - n.push({ segmentation: l, labels: T }); - } - return n; - } -} -class DPTImageProcessor extends ImageFeatureExtractor {} -class BitImageProcessor extends ImageFeatureExtractor {} -class DPTFeatureExtractor extends ImageFeatureExtractor {} -class GLPNFeatureExtractor extends ImageFeatureExtractor {} -class CLIPFeatureExtractor extends ImageFeatureExtractor {} -class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor {} -class SiglipImageProcessor extends ImageFeatureExtractor {} -class ConvNextFeatureExtractor extends ImageFeatureExtractor { - constructor(e) { - super(e), (this.crop_pct = this.config.crop_pct ?? 224 / 256); - } - async resize(e) { - const o = this.size?.shortest_edge; - if (o === void 0) throw new Error("Size dictionary must contain 'shortest_edge' key."); - if (o < 384) { - const i = Math.floor(o / this.crop_pct), - [u, n] = this.get_resize_output_image_size(e, { shortest_edge: i }); - (e = await e.resize(u, n, { resample: this.resample })), (e = await e.center_crop(o, o)); - } else e = await e.resize(o, o, { resample: this.resample }); - return e; - } -} -class ConvNextImageProcessor extends ConvNextFeatureExtractor {} -class ViTFeatureExtractor extends ImageFeatureExtractor {} -class ViTImageProcessor extends ImageFeatureExtractor {} -class MobileViTFeatureExtractor extends ImageFeatureExtractor {} -class OwlViTFeatureExtractor extends ImageFeatureExtractor { - post_process_object_detection(...e) { - return post_process_object_detection(...e); - } -} -class Owlv2ImageProcessor extends OwlViTFeatureExtractor {} -class DeiTFeatureExtractor extends ImageFeatureExtractor {} -class BeitFeatureExtractor extends ImageFeatureExtractor {} -class DonutFeatureExtractor extends ImageFeatureExtractor { - pad_image(e, o, i, u = {}) { - const [n, s, d] = o; - let f = this.image_mean; - Array.isArray(this.image_mean) || (f = new Array(d).fill(f)); - let r = this.image_std; - Array.isArray(r) || (r = new Array(d).fill(f)); - const a = f.map((l, p) => -l / this.image_std[p]); - return super.pad_image(e, o, i, { center: !0, constant_values: a, ...u }); - } -} -class NougatImageProcessor extends DonutFeatureExtractor {} -class DetrFeatureExtractor extends ImageFeatureExtractor { - async _call(e) { - const o = await super._call(e), - i = [o.pixel_values.dims[0], 64, 64], - u = new Tensor('int64', new BigInt64Array(i.reduce((n, s) => n * s)).fill(1n), i); - return { ...o, pixel_mask: u }; - } - post_process_object_detection(...e) { - return post_process_object_detection(...e); - } - remove_low_and_no_objects(e, o, i, u) { - let n = [], - s = [], - d = []; - for (let f = 0; f < e.dims[0]; ++f) { - let r = e[f], - a = o[f], - l = max(r.data)[1]; - if (l === u) continue; - let m = softmax(r.data)[l]; - m > i && (n.push(a), s.push(m), d.push(l)); - } - return [n, s, d]; - } - check_segment_validity(e, o, i, u = 0.5, n = 0.8) { - let s = [], - d = 0, - f = 0; - for (let a = 0; a < e.length; ++a) e[a] === i && (s.push(a), ++d), o[i].data[a] >= u && ++f; - let r = d > 0 && f > 0; - return r && (r = d / f > n), [r, s]; - } - compute_segments(e, o, i, u, n, s = null, d = null) { - let [f, r] = d ?? e[0].dims, - a = new Tensor('int32', new Int32Array(f * r), [f, r]), - l = []; - if (d !== null) for (let T = 0; T < e.length; ++T) e[T] = interpolate(e[T], d, 'bilinear', !1); - let p = new Int32Array(e[0].data.length), - m = new Float32Array(e[0].data.length); - for (let T = 0; T < e.length; ++T) { - let v = o[T]; - for (let S = 0; S < e[T].data.length; ++S) - (e[T].data[S] *= v), e[T].data[S] > m[S] && ((p[S] = T), (m[S] = e[T].data[S])); - } - let y = 0; - for (let T = 0; T < i.length; ++T) { - let v = i[T], - [S, E] = this.check_segment_validity(p, e, T, u, n); - if (S) { - ++y; - for (let A of E) a.data[A] = y; - l.push({ id: y, label_id: v, score: o[T] }); - } - } - return [a, l]; - } - post_process_panoptic_segmentation(e, o = 0.5, i = 0.5, u = 0.8, n = null, s = null) { - n === null && (console.warn('`label_ids_to_fuse` unset. No instance will be fused.'), (n = new Set())); - const d = e.logits, - r = e.pred_masks.sigmoid(); - let [a, l, p] = d.dims; - if (((p -= 1), s !== null && s.length !== a)) - throw Error('Make sure that you pass in as many target sizes as the batch dimension of the logits'); - let m = []; - for (let y = 0; y < a; ++y) { - let T = s !== null ? s[y] : null, - v = d[y], - S = r[y], - [E, A, F] = this.remove_low_and_no_objects(v, S, o, p); - if (F.length === 0) { - let [Q, re] = T ?? S.dims.slice(-2), - V = new Tensor('int32', new Int32Array(Q * re).fill(-1), [Q, re]); - m.push({ segmentation: V, segments_info: [] }); - continue; - } - let [B, J] = this.compute_segments(E, A, F, i, u, n, T); - m.push({ segmentation: B, segments_info: J }); - } - return m; - } - post_process_instance_segmentation() { - throw Error('Not implemented yet'); - } -} -class YolosFeatureExtractor extends ImageFeatureExtractor { - post_process_object_detection(...e) { - return post_process_object_detection(...e); - } -} -class SamImageProcessor extends ImageFeatureExtractor { - reshape_input_points(e, o, i) { - e = structuredClone(e); - let u = calculateDimensions(e); - if (u.length === 3) (u = [1, ...u]), (e = [e]); - else if (u.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 n = 0; n < e.length; ++n) { - let s = o[n], - d = i[n], - f = [d[0] / s[0], d[1] / s[1]]; - for (let r = 0; r < e[n].length; ++r) - for (let a = 0; a < e[n][r].length; ++a) - for (let l = 0; l < e[n][r][a].length; ++l) e[n][r][a][l] *= f[l]; - } - return new Tensor('float32', Float32Array.from(e.flat(1 / 0)), u); - } - add_input_labels(e, o) { - let i = calculateDimensions(e); - if (i.length === 2) (i = [1, ...i]), (e = [e]); - else if (i.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 (i.some((u, n) => u !== o.dims[n])) - throw Error(`The first ${i.length} dimensions of 'input_points' and 'input_labels' must be the same.`); - return new Tensor('int64', e.flat(1 / 0).map(BigInt), i); - } - async _call(e, o = null, i = null) { - const u = await super._call(e); - if ((o && (u.input_points = this.reshape_input_points(o, u.original_sizes, u.reshaped_input_sizes)), i)) { - if (!u.input_points) throw Error('`input_points` must be provided if `input_labels` are provided.'); - u.input_labels = this.add_input_labels(i, u.input_points); - } - return u; - } - post_process_masks(e, o, i, { mask_threshold: u = 0, binarize: n = !0, pad_size: s = null } = {}) { - const d = []; - s = s ?? this.pad_size; - const f = [s.height, s.width]; - for (let r = 0; r < o.length; ++r) { - const a = o[r], - l = i[r], - p = e[r], - m = []; - for (let y = 0; y < p.dims[0]; ++y) { - const T = p[y]; - let v = interpolate(T, f, 'bilinear', !1); - if (((v = v.slice(null, [0, l[0]], [0, l[1]])), (v = interpolate(v, a, 'bilinear', !1)), n)) { - const S = new Uint8Array(v.data.length); - for (let E = 0; E < v.data.length; ++E) v.data[E] > u && (S[E] = 1); - v = new Tensor('bool', S, v.dims); - } - m.push(v); - } - d.push(stack(m)); - } - return d; - } - generate_crop_boxes( - e, - o, - { - crop_n_layers: i = 0, - overlap_ratio: u = 512 / 1500, - points_per_crop: n = 32, - crop_n_points_downscale_factor: s = 1, - } = {} - ) {} -} -class Swin2SRImageProcessor extends ImageFeatureExtractor { - pad_image(e, o, i, u = {}) { - const [n, s, d] = o; - return super.pad_image( - e, - o, - { width: n + ((i - (n % i)) % i), height: s + ((i - (s % i)) % i) }, - { mode: 'symmetric', center: !1, constant_values: -1, ...u } - ); - } -} -class VitMatteImageProcessor extends ImageFeatureExtractor { - async _call(e, o) { - Array.isArray(e) || (e = [e]), Array.isArray(o) || (o = [o]); - const i = await Promise.all(e.map((s) => this.preprocess(s))), - u = await Promise.all( - o.map((s) => this.preprocess(s, { do_normalize: !1, do_convert_rgb: !1, do_convert_grayscale: !0 })) - ); - return { - pixel_values: stack( - i.map((s, d) => cat([s.pixel_values, u[d].pixel_values], 0)), - 0 - ), - original_sizes: i.map((s) => s.original_size), - reshaped_input_sizes: i.map((s) => s.reshaped_input_size), - }; - } -} -class WhisperFeatureExtractor extends FeatureExtractor { - constructor(e) { - super(e), - (this.config.mel_filters ??= mel_filter_bank( - Math.floor(1 + this.config.n_fft / 2), - this.config.feature_size, - 0, - 8e3, - this.config.sampling_rate, - 'slaney', - 'slaney' - )), - (this.window = window_function(this.config.n_fft, 'hann')); - } - _extract_fbank_features(e) { - const { data: o, dims: i } = spectrogram(e, this.window, this.config.n_fft, this.config.hop_length, { - power: 2, - mel_filters: this.config.mel_filters, - log_mel: 'log10', - max_num_frames: this.config.nb_max_frames, - }), - u = max(o)[0]; - for (let n = 0; n < o.length; ++n) o[n] = (Math.max(o[n], u - 8) + 4) / 4; - return { data: o, dims: i }; - } - async _call(e) { - validate_audio_inputs(e, 'WhisperFeatureExtractor'); - let o; - e.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`.' - ), - (o = e.slice(0, this.config.n_samples))) - : ((o = new Float32Array(this.config.n_samples)), o.set(e)); - const { data: i, dims: u } = this._extract_fbank_features(o); - return { input_features: new Tensor('float32', i, [1, ...u]) }; - } -} -class Wav2Vec2FeatureExtractor extends FeatureExtractor { - _zero_mean_unit_var_norm(e) { - const i = e.reduce((n, s) => n + s, 0) / e.length, - u = e.reduce((n, s) => n + (s - i) ** 2, 0) / e.length; - return e.map((n) => (n - i) / Math.sqrt(u + 1e-7)); - } - async _call(e) { - validate_audio_inputs(e, 'Wav2Vec2FeatureExtractor'), e instanceof Float64Array && (e = new Float32Array(e)); - let o = e; - this.config.do_normalize && (o = this._zero_mean_unit_var_norm(o)); - const i = [1, o.length]; - return { - input_values: new Tensor('float32', o, i), - attention_mask: new Tensor('int64', new BigInt64Array(o.length).fill(1n), i), - }; - } -} -class SeamlessM4TFeatureExtractor extends FeatureExtractor { - constructor(e) { - super(e); - const o = this.config.sampling_rate, - i = mel_filter_bank(256, this.config.num_mel_bins, 20, Math.floor(o / 2), o, null, 'kaldi', !0); - for (let u = 0; u < i.length; ++u) i[u].push(0); - (this.mel_filters = i), (this.window = window_function(400, 'povey', { periodic: !1 })); - } - _extract_fbank_features(e, o) { - return ( - (e = e.map((i) => i * 32768)), - spectrogram(e, this.window, 400, 160, { - fft_length: 512, - power: 2, - center: !1, - preemphasis: 0.97, - mel_filters: this.mel_filters, - log_mel: 'log', - mel_floor: 1192092955078125e-22, - remove_dc_offset: !0, - max_num_frames: o, - transpose: !0, - }) - ); - } - async _call( - e, - { - padding: o = !0, - pad_to_multiple_of: i = 2, - do_normalize_per_mel_bins: u = !0, - return_attention_mask: n = !0, - } = {} - ) { - validate_audio_inputs(e, 'SeamlessM4TFeatureExtractor'); - let s = this._extract_fbank_features(e, this.config.max_length); - if (u) { - const [y, T] = s.dims; - for (let v = 0; v < T; ++v) { - let S = 0; - for (let B = 0; B < y; ++B) S += s.data[B * T + v]; - const E = S / y; - let A = 0; - for (let B = 0; B < y; ++B) A += (s.data[B * T + v] - E) ** 2; - A /= y - 1; - const F = Math.sqrt(A + 1e-7); - for (let B = 0; B < y; ++B) { - const J = B * T + v; - s.data[J] = (s.data[J] - E) / F; - } - } - } - let d; - if (o) { - const [y, T] = s.dims, - v = y % i; - if (v > 0) { - const S = new Float32Array(T * (y + v)); - S.set(s.data), S.fill(this.config.padding_value, s.data.length); - const E = y + v; - (s = { data: S, dims: [E, T] }), - n && ((d = new Tensor('int64', new BigInt64Array(E), [1, E])), d.data.fill(1n, 0, y)); - } - } - const [f, r] = s.dims, - a = this.config.stride; - if (f % a !== 0) throw new Error(`The number of frames (${f}) must be a multiple of the stride (${a}).`); - const p = new Tensor('float32', s.data, s.dims).view(1, Math.floor(f / a), r * a), - m = { input_features: p }; - if (n) { - const y = p.dims[1], - T = new Tensor('int64', new BigInt64Array(y), [1, y]); - if (d) for (let v = 1, S = 0; v < f; v += a, ++S) T.data[S] = d.data[v]; - else T.data.fill(1n); - m.attention_mask = T; - } - return m; - } -} -class ASTFeatureExtractor extends FeatureExtractor { - constructor(e) { - super(e); - const o = this.config.sampling_rate, - i = mel_filter_bank(256, this.config.num_mel_bins, 20, Math.floor(o / 2), o, null, 'kaldi', !0); - for (let u = 0; u < i.length; ++u) i[u].push(0); - (this.mel_filters = i), - (this.window = window_function(400, 'hann', { periodic: !1 })), - (this.mean = this.config.mean), - (this.std = this.config.std); - } - _extract_fbank_features(e, o) { - return spectrogram(e, this.window, 400, 160, { - fft_length: 512, - power: 2, - center: !1, - preemphasis: 0.97, - mel_filters: this.mel_filters, - log_mel: 'log', - mel_floor: 1192092955078125e-22, - remove_dc_offset: !0, - max_num_frames: o, - transpose: !0, - }); - } - async _call(e) { - validate_audio_inputs(e, 'ASTFeatureExtractor'); - const o = this._extract_fbank_features(e, this.config.max_length); - if (this.config.do_normalize) { - const i = this.std * 2; - for (let u = 0; u < o.data.length; ++u) o.data[u] = (o.data[u] - this.mean) / i; - } - return { input_values: new Tensor('float32', o.data, [1, ...o.dims]) }; - } -} -class ClapFeatureExtractor extends FeatureExtractor { - constructor(e) { - super(e), - (this.mel_filters = mel_filter_bank( - this.config.nb_frequency_bins, - this.config.feature_size, - this.config.frequency_min, - this.config.frequency_max, - this.config.sampling_rate, - null, - 'htk' - )), - (this.mel_filters_slaney = mel_filter_bank( - this.config.nb_frequency_bins, - this.config.feature_size, - this.config.frequency_min, - this.config.frequency_max, - this.config.sampling_rate, - 'slaney', - 'slaney' - )), - (this.window = window_function(this.config.fft_window_size, 'hann')); - } - _get_input_mel(e, o, i, u) { - let n, - s = !1; - const d = e.length - o; - if (d > 0) - if (i === 'rand_trunc') { - s = !0; - const f = Math.floor(Math.random() * (d + 1)); - (e = e.subarray(f, f + o)), - (n = this._extract_fbank_features(e, this.mel_filters_slaney, this.config.nb_max_samples)), - (n.dims = [1, ...n.dims]); - } else throw new Error(`Truncation strategy "${i}" not implemented`); - else { - if (d < 0) { - let f = new Float64Array(o); - if ((f.set(e), u === 'repeat')) - for (let r = e.length; r < o; r += e.length) f.set(e.subarray(0, Math.min(e.length, o - r)), r); - else if (u === 'repeatpad') for (let r = e.length; r < -d; r += e.length) f.set(e, r); - e = f; - } - if (i === 'fusion') throw new Error(`Truncation strategy "${i}" not implemented`); - (n = this._extract_fbank_features(e, this.mel_filters_slaney, this.config.nb_max_samples)), - (n.dims = [1, ...n.dims]); - } - return { ...n, longer: s }; - } - _extract_fbank_features(e, o, i = null) { - return spectrogram(e, this.window, this.config.fft_window_size, this.config.hop_length, { - power: 2, - mel_filters: o, - log_mel: 'dB', - max_num_frames: i, - do_pad: !1, - transpose: !0, - }); - } - async _call(e, { max_length: o = null } = {}) { - validate_audio_inputs(e, 'ClapFeatureExtractor'); - const i = this._get_input_mel(e, o ?? this.config.nb_max_samples, this.config.truncation, this.config.padding); - return { input_features: new Tensor('float32', i.data, [1, ...i.dims]) }; - } -} -class SpeechT5FeatureExtractor extends FeatureExtractor {} -class Processor extends Callable { - constructor(e) { - super(), (this.feature_extractor = e); - } - async _call(e, ...o) { - return await this.feature_extractor(e, ...o); - } -} -class SamProcessor extends Processor { - async _call(...e) { - return await this.feature_extractor(...e); - } - post_process_masks(...e) { - return this.feature_extractor.post_process_masks(...e); - } - reshape_input_points(...e) { - return this.feature_extractor.reshape_input_points(...e); - } -} -class WhisperProcessor extends Processor { - async _call(e) { - return await this.feature_extractor(e); - } -} -class Wav2Vec2ProcessorWithLM extends Processor { - async _call(e) { - return await this.feature_extractor(e); - } -} -class SpeechT5Processor extends Processor { - async _call(e) { - return await this.feature_extractor(e); - } -} -class OwlViTProcessor extends Processor {} -class AutoProcessor { - static FEATURE_EXTRACTOR_CLASS_MAPPING = { - ImageFeatureExtractor, - WhisperFeatureExtractor, - ViTFeatureExtractor, - MobileViTFeatureExtractor, - OwlViTFeatureExtractor, - Owlv2ImageProcessor, - CLIPFeatureExtractor, - ChineseCLIPFeatureExtractor, - SiglipImageProcessor, - ConvNextFeatureExtractor, - ConvNextImageProcessor, - SegformerFeatureExtractor, - BitImageProcessor, - DPTImageProcessor, - DPTFeatureExtractor, - GLPNFeatureExtractor, - BeitFeatureExtractor, - DeiTFeatureExtractor, - DetrFeatureExtractor, - YolosFeatureExtractor, - DonutFeatureExtractor, - NougatImageProcessor, - ViTImageProcessor, - VitMatteImageProcessor, - SamImageProcessor, - Swin2SRImageProcessor, - Wav2Vec2FeatureExtractor, - SeamlessM4TFeatureExtractor, - SpeechT5FeatureExtractor, - ASTFeatureExtractor, - ClapFeatureExtractor, - }; - static PROCESSOR_CLASS_MAPPING = { - WhisperProcessor, - Wav2Vec2ProcessorWithLM, - SamProcessor, - SpeechT5Processor, - OwlViTProcessor, - }; - static async from_pretrained( - e, - { - progress_callback: o = null, - config: i = null, - cache_dir: u = null, - local_files_only: n = !1, - revision: s = 'main', - } = {} - ) { - let d = - i ?? - (await getModelJSON(e, 'preprocessor_config.json', !0, { - progress_callback: o, - config: i, - cache_dir: u, - local_files_only: n, - revision: s, - })), - f = d.feature_extractor_type ?? d.image_processor_type, - r = this.FEATURE_EXTRACTOR_CLASS_MAPPING[f]; - if (!r) - if (d.size !== void 0) - console.warn( - `Feature extractor type "${f}" not found, assuming ImageFeatureExtractor due to size parameter in config.` - ), - (r = ImageFeatureExtractor); - else throw new Error(`Unknown Feature Extractor type: ${f}`); - let a = this.PROCESSOR_CLASS_MAPPING[d.processor_class] ?? Processor, - l = new r(d); - return new a(l); - } -} -if (!navigator.gpu) { - const t = 'WebGPU is not supported by this browser.'; - throw (alert(t), Error(t)); -} -env.backends.onnx.wasm.proxy = !0; -env.backends.onnx.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.1/dist/'; -env.backends.onnx.wasm.numThreads = 1; -env.experimental.useWebGPU = !0; -const EXAMPLE_URL = - 'https://images.pexels.com/photos/5965592/pexels-photo-5965592.jpeg?auto=compress&cs=tinysrgb&w=1024', - status = document.getElementById('status'), - fileUpload = document.getElementById('upload'), - imageContainer = document.getElementById('container'), - example = document.getElementById('example'); -status.textContent = 'AI 모델 로딩중...'; -let model; -try { - model = await AutoModel.from_pretrained('briaai/RMBG-1.4', { config: { model_type: 'custom' }, quantized: !1 }); -} catch (t) { - throw ((status.textContent = t.message), alert(t.message), t); -} -const processor = await AutoProcessor.from_pretrained('briaai/RMBG-1.4', { - config: { - do_normalize: !0, - do_pad: !1, - do_rescale: !0, - do_resize: !0, - image_mean: [0.5, 0.5, 0.5], - feature_extractor_type: 'ImageFeatureExtractor', - image_std: [1, 1, 1], - resample: 2, - rescale_factor: 0.00392156862745098, - size: { width: 1024, height: 1024 }, - }, -}); -status.textContent = 'AI 모델 설치중...'; -const [b, c, h, w] = [1, 3, 1024, 1024], - dummyData = new Float32Array(b * c * h * w); -await model({ input: new Tensor('float32', dummyData, [b, c, h, w]) }); -status.textContent = '준비 완료!'; -example.addEventListener('click', (t) => { - t.preventDefault(), predict(EXAMPLE_URL); -}); -fileUpload.addEventListener('change', function (t) { - const e = t.target.files[0]; - if (!e) return; - const o = new FileReader(); - (o.onload = (i) => predict(i.target.result)), o.readAsDataURL(e); -}); -async function predict(t) { - const e = await RawImage.fromURL(t); - (imageContainer.innerHTML = ''), (imageContainer.style.backgroundImage = `url(${t})`); - const o = e.width / e.height, - [i, u] = o > 720 / 480 ? [720, 720 / o] : [480 * o, 480]; - (imageContainer.style.width = `${i}px`), - (imageContainer.style.height = `${u}px`), - (status.textContent = 'Analysing...'); - const { pixel_values: n } = await processor(e), - s = performance.now(), - { output: d } = await model({ input: n }), - f = performance.now(), - r = await RawImage.fromTensor(d[0].mul(255).to('uint8')).resize(e.width, e.height), - a = document.createElement('canvas'); - (a.width = e.width), (a.height = e.height); - const l = a.getContext('2d'); - l.drawImage(e.toCanvas(), 0, 0); - const p = l.getImageData(0, 0, e.width, e.height); - for (let m = 0; m < r.data.length; ++m) p.data[4 * m + 3] = r.data[m]; - l.putImageData(p, 0, 0), - imageContainer.append(a), - imageContainer.style.removeProperty('background-image'), - (imageContainer.style.background = - 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAGUExURb+/v////5nD/3QAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAUSURBVBjTYwABQSCglEENMxgYGAAynwRB8BEAgQAAAABJRU5ErkJggg==")'), - (status.textContent = `Done! (Inference took ${Math.round(f - s)}ms)`); -} -function __vite__mapDeps(indexes) { - if (!__vite__mapDeps.viteFileDeps) { - __vite__mapDeps.viteFileDeps = []; - } - return indexes.map((i) => __vite__mapDeps.viteFileDeps[i]); -}