var fn=Object.defineProperty;var mn=(nt,p,t)=>p in nt?fn(nt,p,{enumerable:!0,configurable:!0,writable:!0,value:t}):nt[p]=t;var K=(nt,p,t)=>(mn(nt,typeof p!="symbol"?p+"":p,t),t);(function(){"use strict";var nt;function _mergeNamespaces(p,t){return t.forEach(function(o){o&&typeof o!="string"&&!Array.isArray(o)&&Object.keys(o).forEach(function(i){if(i!=="default"&&!(i in p)){var u=Object.getOwnPropertyDescriptor(o,i);Object.defineProperty(p,i,u.get?u:{enumerable:!0,get:function(){return o[i]}})}})}),Object.freeze(p)}function dispatchCallback(p,t){p&&p(t)}function reverseDictionary(p){return Object.fromEntries(Object.entries(p).map(([t,o])=>[o,t]))}function escapeRegExp(p){return p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Callable=class{constructor(){let p=function(...t){return p._call(...t)};return Object.setPrototypeOf(p,new.target.prototype)}_call(...p){throw Error("Must implement _call method in subclass")}};function isTypedArray(p){var t,o,i;return((i=(o=(t=p==null?void 0:p.prototype)==null?void 0:t.__proto__)==null?void 0:o.constructor)==null?void 0:i.name)==="TypedArray"}function isIntegralNumber(p){return Number.isInteger(p)||typeof p=="bigint"}function exists(p){return p!=null}function calculateDimensions(p){const t=[];let o=p;for(;Array.isArray(o);)t.push(o.length),o=o[0];return t}function pop(p,t,o=void 0){const i=p[t];if(i!==void 0)return delete p[t],i;if(o===void 0)throw Error(`Key ${t} does not exist in object.`);return o}function mergeArrays(...p){return Array.prototype.concat.apply([],p)}function product(...p){return p.reduce((t,o)=>t.flatMap(i=>o.map(u=>[i,u])))}function calculateReflectOffset(p,t){return Math.abs((p+t)%(2*t)-t)}var sharp={},ONNX_NODE=Object.freeze({__proto__:null,default:sharp});function getDefaultExportFromCjs(p){return p&&p.__esModule&&Object.prototype.hasOwnProperty.call(p,"default")?p.default:p}function getAugmentedNamespace(p){if(p.__esModule)return p;var t=p.default;if(typeof t=="function"){var o=function i(){return this instanceof i?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};o.prototype=t.prototype}else o={};return Object.defineProperty(o,"__esModule",{value:!0}),Object.keys(p).forEach(function(i){var u=Object.getOwnPropertyDescriptor(p,i);Object.defineProperty(o,i,u.get?u:{enumerable:!0,get:function(){return p[i]}})}),o}var ortWeb_min$1={exports:{}};const backends={},backendsSortedByPriority=[],registerBackend=(p,t,o)=>{if(t&&typeof t.init=="function"&&typeof t.createSessionHandler=="function"){const i=backends[p];if(i===void 0)backends[p]={backend:t,priority:o};else{if(i.priority>o)return;if(i.priority===o&&i.backend!==t)throw new Error(`cannot register backend "${p}" using priority ${o}`)}if(o>=0){const u=backendsSortedByPriority.indexOf(p);u!==-1&&backendsSortedByPriority.splice(u,1);for(let d=0;d{const t=p.length===0?backendsSortedByPriority:p,o=[];for(const i of t){const u=backends[i];if(u){if(u.initialized)return u.backend;if(u.aborted)continue;const d=!!u.initPromise;try{return d||(u.initPromise=u.backend.init()),await u.initPromise,u.initialized=!0,u.backend}catch(a){d||o.push({name:i,err:a}),u.aborted=!0}finally{delete u.initPromise}}}throw new Error(`no available backend found. ERR: ${o.map(i=>`[${i.name}] ${i.err}`).join(", ")}`)};class EnvImpl{constructor(){this.wasm={},this.webgl={},this.logLevelInternal="warning"}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}`);this.logLevelInternal=t}}get logLevel(){return this.logLevelInternal}}const env$2=new EnvImpl,isBigInt64ArrayAvailable=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",isBigUint64ArrayAvailable=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function",NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);isBigInt64ArrayAvailable&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64",BigInt64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array,"int64")),isBigUint64ArrayAvailable&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64",BigUint64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array,"uint64"));const calculateSize=p=>{let t=1;for(let o=0;o{const n=document.createElement("canvas"),e=n.getContext("2d");if(!t||!e)return l();const r=new Image;r.crossOrigin="Anonymous",r.src=t,r.onload=()=>{n.width=r.width,n.height=r.height,e.drawImage(r,0,0,n.width,n.height);const s=e.getImageData(0,0,n.width,n.height);if(o!==void 0){if(o.height!==void 0&&o.height!==n.height)throw new Error("Image input config height doesn't match ImageBitmap height");if(m.height=n.height,o.width!==void 0&&o.width!==n.width)throw new Error("Image input config width doesn't match ImageBitmap width");m.width=n.width}else m.height=n.height,m.width=n.width;c(lt.bufferToTensor(s.data,m))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(h!==void 0)return lt.bufferToTensor(h,m);throw new Error("Input data provided is not supported - aborted tensor creation")}toImageData(t){var o,i;const u=document.createElement("canvas").getContext("2d");let d;if(u!=null){const a=this.dims[3],h=this.dims[2],m=this.dims[1],c=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t!==void 0&&((o=t.norm)===null||o===void 0?void 0:o.mean)!==void 0?t.norm.mean:255,n=t!==void 0&&((i=t.norm)===null||i===void 0?void 0:i.bias)!==void 0?t.norm.bias:0,e=h*a;if(t!==void 0){if(t.height!==void 0&&t.height!==h)throw new Error("Image output config height doesn't match tensor height");if(t.width!==void 0&&t.width!==a)throw new Error("Image output config width doesn't match tensor width");if(t.format!==void 0&&m===4&&t.format!=="RGBA"||m===3&&t.format!=="RGB"&&t.format!=="BGR")throw new Error("Tensor format doesn't match input tensor dims")}const r=4;let s=0,f=1,g=2,_=3,b=0,y=e,T=e*2,w=-1;c==="RGBA"?(b=0,y=e,T=e*2,w=e*3):c==="RGB"?(b=0,y=e,T=e*2):c==="RBG"&&(b=0,T=e,y=e*2),d=u.createImageData(a,h);for(let v=0;v"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(const c of this.outputNames)u[c]=null;const h=await this.handler.run(t,u,d),m={};for(const c in h)Object.hasOwnProperty.call(h,c)&&(m[c]=new Tensor$1(h[c].type,h[c].data,h[c].dims));return m}static async create(t,o,i,u){let d,a={};if(typeof t=="string"){if(d=t,typeof o=="object"&&o!==null)a=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(d=t,typeof o=="object"&&o!==null)a=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){const n=t;let e=0,r=t.byteLength;if(typeof o=="object"&&o!==null)a=o;else if(typeof o=="number"){if(e=o,!Number.isSafeInteger(e))throw new RangeError("'byteOffset' must be an integer.");if(e<0||e>=n.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${n.byteLength}).`);if(r=t.byteLength-e,typeof i=="number"){if(r=i,!Number.isSafeInteger(r))throw new RangeError("'byteLength' must be an integer.");if(r<=0||e+r>n.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${n.byteLength-e}].`);if(typeof u=="object"&&u!==null)a=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.");d=new Uint8Array(n,e,r)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const m=(a.executionProviders||[]).map(n=>typeof n=="string"?n:n.name),l=await(await resolveBackend(m)).createSessionHandler(d,a);return new dn(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const InferenceSession$1=InferenceSession$2;var lib=Object.freeze({__proto__:null,InferenceSession:InferenceSession$1,Tensor:Tensor$1,env:env$2,registerBackend}),require$$0=getAugmentedNamespace(lib);/*! * ONNX Runtime Web v1.14.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */(function(module,exports){(function(p,t){module.exports=t(require$$0)})(self,__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(p,t,o)=>{var i,u=(i=(i=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(d){function a(){return G.buffer!=J&&Me(G.buffer),ae}function h(){return G.buffer!=J&&Me(G.buffer),Ee}function m(){return G.buffer!=J&&Me(G.buffer),xe}function c(){return G.buffer!=J&&Me(G.buffer),le}function l(){return G.buffer!=J&&Me(G.buffer),we}var n,e,r;d=d||{},n||(n=d!==void 0?d:{}),n.ready=new Promise(function(S,A){e=S,r=A});var s,f,g,_,b,y,T=Object.assign({},n),w="./this.program",v=(S,A)=>{throw A},E=typeof window=="object",P=typeof importScripts=="function",x=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",O=n.ENVIRONMENT_IS_PTHREAD||!1,$="";function k(S){return n.locateFile?n.locateFile(S,$):$+S}if(x){let S;$=P?o(908).dirname($)+"/":"//",y=()=>{b||(_=o(1384),b=o(908))},s=function(A,I){return y(),A=b.normalize(A),_.readFileSync(A,I?void 0:"utf8")},g=A=>((A=s(A,!0)).buffer||(A=new Uint8Array(A)),A),f=(A,I,L)=>{y(),A=b.normalize(A),_.readFile(A,function(j,q){j?L(j):I(q.buffer)})},1{if(qe())throw process.exitCode=A,I;I instanceof Ze||B("exiting due to exception: "+I),process.exit(A)},n.inspect=function(){return"[Emscripten Module object]"};try{S=o(9925)}catch(A){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),A}o.g.Worker=S.Worker}else(E||P)&&(P?$=self.location.href:typeof document<"u"&&document.currentScript&&($=document.currentScript.src),i&&($=i),$=$.indexOf("blob:")!==0?$.substr(0,$.replace(/[?#].*/,"").lastIndexOf("/")+1):"",x||(s=S=>{var A=new XMLHttpRequest;return A.open("GET",S,!1),A.send(null),A.responseText},P&&(g=S=>{var A=new XMLHttpRequest;return A.open("GET",S,!1),A.responseType="arraybuffer",A.send(null),new Uint8Array(A.response)}),f=(S,A,I)=>{var L=new XMLHttpRequest;L.open("GET",S,!0),L.responseType="arraybuffer",L.onload=()=>{L.status==200||L.status==0&&L.response?A(L.response):I()},L.onerror=I,L.send(null)}));x&&typeof performance>"u"&&(o.g.performance=o(6953).performance);var N=console.log.bind(console),D=console.warn.bind(console);x&&(y(),N=S=>_.writeSync(1,S+` `),D=S=>_.writeSync(2,S+` `));var V,C=n.print||N,B=n.printErr||D;Object.assign(n,T),T=null,n.thisProgram&&(w=n.thisProgram),n.quit&&(v=n.quit),n.wasmBinary&&(V=n.wasmBinary);var X=n.noExitRuntime||!1;typeof WebAssembly!="object"&&me("no native wasm support detected");var G,ee,J,ae,Ee,xe,le,we,be=!1,ke=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Le(S,A,I){var L=(A>>>=0)+I;for(I=A;S[I]&&!(I>=L);)++I;if(16(j=(240&j)==224?(15&j)<<12|q<<6|Z:(7&j)<<18|q<<12|Z<<6|63&S[A++])?L+=String.fromCharCode(j):(j-=65536,L+=String.fromCharCode(55296|j>>10,56320|1023&j))}}else L+=String.fromCharCode(j)}return L}function ve(S,A){return(S>>>=0)?Le(h(),S,A):""}function $e(S,A,I,L){if(!(0>>=0;L=I+L-1;for(var q=0;q=Z&&(Z=65536+((1023&Z)<<10)|1023&S.charCodeAt(++q)),127>=Z){if(I>=L)break;A[I++>>>0]=Z}else{if(2047>=Z){if(I+1>=L)break;A[I++>>>0]=192|Z>>6}else{if(65535>=Z){if(I+2>=L)break;A[I++>>>0]=224|Z>>12}else{if(I+3>=L)break;A[I++>>>0]=240|Z>>18,A[I++>>>0]=128|Z>>12&63}A[I++>>>0]=128|Z>>6&63}A[I++>>>0]=128|63&Z}}return A[I>>>0]=0,I-j}function Fe(S){for(var A=0,I=0;I=L?A++:2047>=L?A+=2:55296<=L&&57343>=L?(A+=4,++I):A+=3}return A}function Me(S){J=S,n.HEAP8=ae=new Int8Array(S),n.HEAP16=new Int16Array(S),n.HEAP32=xe=new Int32Array(S),n.HEAPU8=Ee=new Uint8Array(S),n.HEAPU16=new Uint16Array(S),n.HEAPU32=le=new Uint32Array(S),n.HEAPF32=new Float32Array(S),n.HEAPF64=we=new Float64Array(S)}O&&(J=n.buffer);var Pe=n.INITIAL_MEMORY||16777216;if(O)G=n.wasmMemory,J=n.buffer;else if(n.wasmMemory)G=n.wasmMemory;else if(!((G=new WebAssembly.Memory({initial:Pe/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw B("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"),x&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");G&&(J=G.buffer),Pe=J.byteLength,Me(J);var je,Ue=[],Ge=[],Ye=[],Qe=[];function qe(){return X||!1}function Ve(){var S=n.preRun.shift();Ue.unshift(S)}var Oe,Be=0,Ke=null;function me(S){throw O?postMessage({cmd:"onAbort",arg:S}):n.onAbort&&n.onAbort(S),B(S="Aborted("+S+")"),be=!0,S=new WebAssembly.RuntimeError(S+". Build with -sASSERTIONS for more info."),r(S),S}function pt(){return Oe.startsWith("data:application/octet-stream;base64,")}function ut(){var S=Oe;try{if(S==Oe&&V)return new Uint8Array(V);if(g)return g(S);throw"both async and sync fetching of the wasm failed"}catch(A){me(A)}}Oe="ort-wasm-threaded.wasm",pt()||(Oe=k(Oe));var Ot={};function Ze(S){this.name="ExitStatus",this.message="Program terminated with exit("+S+")",this.status=S}function ct(S){(S=oe.Vb[S])||me(),oe.mc(S)}function dt(S){var A=oe.Cc();if(!A)return 6;oe.ac.push(A),oe.Vb[S.Ub]=A,A.Ub=S.Ub;var I={cmd:"run",start_routine:S.Ic,arg:S.zc,pthread_ptr:S.Ub};return A.$b=()=>{I.time=performance.now(),A.postMessage(I,S.Nc)},A.loaded&&(A.$b(),delete A.$b),0}function Re(S){if(O)return te(1,1,S);qe()||(oe.oc(),n.onExit&&n.onExit(S),be=!0),v(S,new Ze(S))}function ot(S,A){if(!A&&O)throw It(S),"unwind";qe()||O||(Wt(),rt(Ye),qt(0),Nt[1].length&&Lt(1,10),Nt[2].length&&Lt(2,10),oe.oc()),Re(S)}var oe={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&oe.Ec()},Pc:function(){},Ec:function(){oe.receiveObjectTransfer=oe.Gc,oe.threadInitTLS=oe.pc,oe.setExitStatus=oe.nc,X=!1},nc:function(){},oc:function(){for(var S of Object.values(oe.Vb))oe.mc(S);for(S of oe.Yb)S.terminate();oe.Yb=[]},mc:function(S){var A=S.Ub;delete oe.Vb[A],oe.Yb.push(S),oe.ac.splice(oe.ac.indexOf(S),1),S.Ub=0,Rt(A)},Gc:function(){},pc:function(){oe.qc.forEach(S=>S())},Fc:function(S,A){S.onmessage=I=>{var L=(I=I.data).cmd;if(S.Ub&&(oe.Bc=S.Ub),I.targetThread&&I.targetThread!=Ct()){var j=oe.Vb[I.Qc];j?j.postMessage(I,I.transferList):B('Internal error! Worker sent a message "'+L+'" to target pthread '+I.targetThread+", but that thread no longer exists!")}else L==="processProxyingQueue"?R(I.queue):L==="spawnThread"?dt(I):L==="cleanupThread"?ct(I.thread):L==="killThread"?(I=I.thread,L=oe.Vb[I],delete oe.Vb[I],L.terminate(),Rt(I),oe.ac.splice(oe.ac.indexOf(L),1),L.Ub=0):L==="cancelThread"?oe.Vb[I.thread].postMessage({cmd:"cancel"}):L==="loaded"?(S.loaded=!0,A&&A(S),S.$b&&(S.$b(),delete S.$b)):L==="print"?C("Thread "+I.threadId+": "+I.text):L==="printErr"?B("Thread "+I.threadId+": "+I.text):L==="alert"?alert("Thread "+I.threadId+": "+I.text):I.target==="setimmediate"?S.postMessage(I):L==="onAbort"?n.onAbort&&n.onAbort(I.arg):L&&B("worker sent an unknown command "+L);oe.Bc=void 0},S.onerror=I=>{throw B("worker sent an error! "+I.filename+":"+I.lineno+": "+I.message),I},x&&(S.on("message",function(I){S.onmessage({data:I})}),S.on("error",function(I){S.onerror(I)}),S.on("detachedExit",function(){})),S.postMessage({cmd:"load",urlOrBlob:n.mainScriptUrlOrBlob||i,wasmMemory:G,wasmModule:ee})},yc:function(){var S=k("ort-wasm-threaded.worker.js");oe.Yb.push(new Worker(S))},Cc:function(){return oe.Yb.length==0&&(oe.yc(),oe.Fc(oe.Yb[0])),oe.Yb.pop()}};function rt(S){for(;0>2>>>0];S=m()[S+48>>2>>>0],Qt(A,A-S),de(A)};var Je=[];function Te(S){var A=Je[S];return A||(S>=Je.length&&(Je.length=S+1),Je[S]=A=je.get(S)),A}n.invokeEntryPoint=function(S,A){S=Te(S)(A),qe()?oe.nc(S):Xt(S)};var it,ft,st=[],ue=0,ie=0;function se(S){this.Zb=S,this.Sb=S-24,this.xc=function(A){c()[this.Sb+4>>2>>>0]=A},this.bc=function(){return c()[this.Sb+4>>2>>>0]},this.wc=function(A){c()[this.Sb+8>>2>>>0]=A},this.Dc=function(){return c()[this.Sb+8>>2>>>0]},this.rc=function(){m()[this.Sb>>2>>>0]=0},this.hc=function(A){A=A?1:0,a()[this.Sb+12>>0>>>0]=A},this.uc=function(){return a()[this.Sb+12>>0>>>0]!=0},this.ic=function(A){A=A?1:0,a()[this.Sb+13>>0>>>0]=A},this.kc=function(){return a()[this.Sb+13>>0>>>0]!=0},this.fc=function(A,I){this.cc(0),this.xc(A),this.wc(I),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(m(),this.Sb>>2,1)},this.Hc=function(){return Atomics.sub(m(),this.Sb>>2,1)===1},this.cc=function(A){c()[this.Sb+16>>2>>>0]=A},this.tc=function(){return c()[this.Sb+16>>2>>>0]},this.vc=function(){if(Zt(this.bc()))return c()[this.Zb>>2>>>0];var A=this.tc();return A!==0?A:this.Zb}}function mt(S){return Gt(new se(S).Sb)}function at(S,A,I,L){return O?te(3,1,S,A,I,L):gt(S,A,I,L)}function gt(S,A,I,L){if(typeof SharedArrayBuffer>"u")return B("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var j=[];return O&&j.length===0?at(S,A,I,L):(S={Ic:I,Ub:S,zc:L,Nc:j},O?(S.Oc="spawnThread",postMessage(S,j),0):dt(S))}function _t(S,A,I){return O?te(4,1,S,A,I):0}function bt(S,A){if(O)return te(5,1,S,A)}function yt(S,A){if(O)return te(6,1,S,A)}function wt(S,A,I){if(O)return te(7,1,S,A,I)}function Tt(S,A,I){return O?te(8,1,S,A,I):0}function xt(S,A){if(O)return te(9,1,S,A)}function vt(S,A,I){if(O)return te(10,1,S,A,I)}function St(S,A,I,L){if(O)return te(11,1,S,A,I,L)}function Et(S,A,I,L){if(O)return te(12,1,S,A,I,L)}function Pt(S,A,I,L){if(O)return te(13,1,S,A,I,L)}function At(S){if(O)return te(14,1,S)}function M(S,A){if(O)return te(15,1,S,A)}function F(S,A,I){if(O)return te(16,1,S,A,I)}function R(S){Atomics.store(m(),S>>2,1),Ct()&&Kt(S),Atomics.compareExchange(m(),S>>2,1,0)}function z(S){return c()[S>>>2]+4294967296*m()[S+4>>>2]}function U(S,A,I,L,j,q){return O?te(17,1,S,A,I,L,j,q):-52}function Y(S,A,I,L,j,q){if(O)return te(18,1,S,A,I,L,j,q)}function Q(S){var A=Fe(S)+1,I=$t(A);return I&&$e(S,a(),I,A),I}function ne(S,A,I){function L(ge){return(ge=ge.toTimeString().match(/\(([A-Za-z ]+)\)$/))?ge[1]:"GMT"}if(O)return te(19,1,S,A,I);var j=new Date().getFullYear(),q=new Date(j,0,1),Z=new Date(j,6,1);j=q.getTimezoneOffset();var re=Z.getTimezoneOffset(),fe=Math.max(j,re);m()[S>>2>>>0]=60*fe,m()[A>>2>>>0]=+(j!=re),S=L(q),A=L(Z),S=Q(S),A=Q(A),re>2>>>0]=S,c()[I+4>>2>>>0]=A):(c()[I>>2>>>0]=A,c()[I+4>>2>>>0]=S)}function te(S,A){var I=arguments.length-2,L=arguments;return Mt(()=>{for(var j=Bt(8*I),q=j>>3,Z=0;Z>>0]=re}return Yt(S,I,j,A)})}n.executeNotifiedProxyingQueue=R,ft=x?()=>{var S=process.hrtime();return 1e3*S[0]+S[1]/1e6}:O?()=>performance.now()-n.__performance_now_clock_drift:()=>performance.now();var ce,Se=[],Ne={};function De(){if(!ce){var S,A={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",_:w||"./this.program"};for(S in Ne)Ne[S]===void 0?delete A[S]:A[S]=Ne[S];var I=[];for(S in A)I.push(S+"="+A[S]);ce=I}return ce}function W(S,A){if(O)return te(20,1,S,A);var I=0;return De().forEach(function(L,j){var q=A+I;for(j=c()[S+4*j>>2>>>0]=q,q=0;q>0>>>0]=L.charCodeAt(q);a()[j>>0>>>0]=0,I+=L.length+1}),0}function _e(S,A){if(O)return te(21,1,S,A);var I=De();c()[S>>2>>>0]=I.length;var L=0;return I.forEach(function(j){L+=j.length+1}),c()[A>>2>>>0]=L,0}function Ae(S){return O?te(22,1,S):52}function We(S,A,I,L){return O?te(23,1,S,A,I,L):52}function et(S,A,I,L,j){return O?te(24,1,S,A,I,L,j):70}var Nt=[null,[],[]];function Lt(S,A){var I=Nt[S];A===0||A===10?((S===1?C:B)(Le(I,0)),I.length=0):I.push(A)}function zt(S,A,I,L){if(O)return te(25,1,S,A,I,L);for(var j=0,q=0;q>2>>>0],re=c()[A+4>>2>>>0];A+=8;for(var fe=0;fe>>0]);j+=re}return c()[L>>2>>>0]=j,0}var ze=0;function kt(S){return S%4==0&&(S%100!=0||S%400==0)}var jt=[31,29,31,30,31,30,31,31,30,31,30,31],Vt=[31,28,31,30,31,30,31,31,30,31,30,31];function Ut(S,A,I,L){function j(H,ye,Ie){for(H=typeof H=="number"?H.toString():H||"";H.lengthht?-1:0tt-H.getDate())){H.setDate(H.getDate()+ye);break}ye-=tt-H.getDate()+1,H.setDate(1),11>Ie?H.setMonth(Ie+1):(H.setMonth(0),H.setFullYear(H.getFullYear()+1))}return Ie=new Date(H.getFullYear()+1,0,4),ye=re(new Date(H.getFullYear(),0,4)),Ie=re(Ie),0>=Z(ye,H)?0>=Z(Ie,H)?H.getFullYear()+1:H.getFullYear():H.getFullYear()-1}var ge=m()[L+40>>2>>>0];for(var Ce in L={Lc:m()[L>>2>>>0],Kc:m()[L+4>>2>>>0],dc:m()[L+8>>2>>>0],jc:m()[L+12>>2>>>0],ec:m()[L+16>>2>>>0],Xb:m()[L+20>>2>>>0],Tb:m()[L+24>>2>>>0],Wb:m()[L+28>>2>>>0],Rc:m()[L+32>>2>>>0],Jc:m()[L+36>>2>>>0],Mc:ge?ve(ge):""},I=ve(I),ge={"%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"})I=I.replace(new RegExp(Ce,"g"),ge[Ce]);var Xe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),He="January February March April May June July August September October November December".split(" ");for(Ce in ge={"%a":function(H){return Xe[H.Tb].substring(0,3)},"%A":function(H){return Xe[H.Tb]},"%b":function(H){return He[H.ec].substring(0,3)},"%B":function(H){return He[H.ec]},"%C":function(H){return q((H.Xb+1900)/100|0,2)},"%d":function(H){return q(H.jc,2)},"%e":function(H){return j(H.jc,2," ")},"%g":function(H){return fe(H).toString().substring(2)},"%G":function(H){return fe(H)},"%H":function(H){return q(H.dc,2)},"%I":function(H){return(H=H.dc)==0?H=12:12H.dc?"AM":"PM"},"%S":function(H){return q(H.Lc,2)},"%t":function(){return" "},"%u":function(H){return H.Tb||7},"%U":function(H){return q(Math.floor((H.Wb+7-H.Tb)/7),2)},"%V":function(H){var ye=Math.floor((H.Wb+7-(H.Tb+6)%7)/7);if(2>=(H.Tb+371-H.Wb-2)%7&&ye++,ye)ye==53&&((Ie=(H.Tb+371-H.Wb)%7)==4||Ie==3&&kt(H.Xb)||(ye=1));else{ye=52;var Ie=(H.Tb+7-H.Wb-1)%7;(Ie==4||Ie==5&&kt(H.Xb%400-1))&&ye++}return q(ye,2)},"%w":function(H){return H.Tb},"%W":function(H){return q(Math.floor((H.Wb+7-(H.Tb+6)%7)/7),2)},"%y":function(H){return(H.Xb+1900).toString().substring(2)},"%Y":function(H){return H.Xb+1900},"%z":function(H){var ye=0<=(H=H.Jc);return H=Math.abs(H)/60,(ye?"+":"-")+("0000"+(H/60*100+H%60)).slice(-4)},"%Z":function(H){return H.Mc},"%%":function(){return"%"}},I=I.replace(/%%/g,"\0\0"),ge)I.includes(Ce)&&(I=I.replace(new RegExp(Ce,"g"),ge[Ce](L)));return Ce=function(H){var ye=Array(Fe(H)+1);return $e(H,ye,0,ye.length),ye}(I=I.replace(/\0\0/g,"%")),Ce.length>A?0:(function(H,ye){a().set(H,ye>>>0)}(Ce,S),Ce.length-1)}oe.fc();var hn=[null,Re,It,at,_t,bt,yt,wt,Tt,xt,vt,St,Et,Pt,At,M,F,U,Y,ne,W,_e,Ae,We,et,zt],pn={b:function(S){return $t(S+24)+24},n:function(S){return(S=new se(S)).uc()||(S.hc(!0),ue--),S.ic(!1),st.push(S),S.sc(),S.vc()},ma:function(S){throw B("Unexpected exception thrown, this is not properly supported - aborting"),be=!0,S},x:function(){pe(0);var S=st.pop();if(S.Hc()&&!S.kc()){var A=S.Dc();A&&Te(A)(S.Zb),mt(S.Zb)}ie=0},e:function(){var S=ie;if(!S)return ze=0;var A=new se(S);A.cc(S);var I=A.bc();if(!I)return ze=0,S;for(var L=Array.prototype.slice.call(arguments),j=0;jR(L));else if(O)postMessage({targetThread:S,cmd:"processProxyingQueue",queue:L});else{if(!(S=oe.Vb[S]))return;S.postMessage({cmd:"processProxyingQueue",queue:L})}return 1},Ea:function(){return-1},Pa:function(S,A){S=new Date(1e3*z(S)),m()[A>>2>>>0]=S.getUTCSeconds(),m()[A+4>>2>>>0]=S.getUTCMinutes(),m()[A+8>>2>>>0]=S.getUTCHours(),m()[A+12>>2>>>0]=S.getUTCDate(),m()[A+16>>2>>>0]=S.getUTCMonth(),m()[A+20>>2>>>0]=S.getUTCFullYear()-1900,m()[A+24>>2>>>0]=S.getUTCDay(),S=(S.getTime()-Date.UTC(S.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,m()[A+28>>2>>>0]=S},Qa:function(S,A){S=new Date(1e3*z(S)),m()[A>>2>>>0]=S.getSeconds(),m()[A+4>>2>>>0]=S.getMinutes(),m()[A+8>>2>>>0]=S.getHours(),m()[A+12>>2>>>0]=S.getDate(),m()[A+16>>2>>>0]=S.getMonth(),m()[A+20>>2>>>0]=S.getFullYear()-1900,m()[A+24>>2>>>0]=S.getDay();var I=new Date(S.getFullYear(),0,1),L=(S.getTime()-I.getTime())/864e5|0;m()[A+28>>2>>>0]=L,m()[A+36>>2>>>0]=-60*S.getTimezoneOffset(),L=new Date(S.getFullYear(),6,1).getTimezoneOffset(),S=0|(L!=(I=I.getTimezoneOffset())&&S.getTimezoneOffset()==Math.min(I,L)),m()[A+32>>2>>>0]=S},Ra:function(S){var A=new Date(m()[S+20>>2>>>0]+1900,m()[S+16>>2>>>0],m()[S+12>>2>>>0],m()[S+8>>2>>>0],m()[S+4>>2>>>0],m()[S>>2>>>0],0),I=m()[S+32>>2>>>0],L=A.getTimezoneOffset(),j=new Date(A.getFullYear(),0,1),q=new Date(A.getFullYear(),6,1).getTimezoneOffset(),Z=j.getTimezoneOffset(),re=Math.min(Z,q);return 0>I?m()[S+32>>2>>>0]=+(q!=Z&&re==L):0>2>>>0]=A.getDay(),I=(A.getTime()-j.getTime())/864e5|0,m()[S+28>>2>>>0]=I,m()[S>>2>>>0]=A.getSeconds(),m()[S+4>>2>>>0]=A.getMinutes(),m()[S+8>>2>>>0]=A.getHours(),m()[S+12>>2>>>0]=A.getDate(),m()[S+16>>2>>>0]=A.getMonth(),A.getTime()/1e3|0},Aa:U,Ba:Y,Sa:function S(A,I,L){S.Ac||(S.Ac=!0,ne(A,I,L))},y:function(){me("")},U:function(){if(!x&&!P){var S="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";it||(it={}),it[S]||(it[S]=1,x&&(S="warning: "+S),B(S))}},ra:function(){return 4294901760},B:ft,Ia:function(S,A,I){h().copyWithin(S>>>0,A>>>0,A+I>>>0)},F:function(){return x?o(3993).cpus().length:navigator.hardwareConcurrency},Da:function(S,A,I){Se.length=A,I>>=3;for(var L=0;L>>0];return(0>S?Ot[-S-1]:hn[S]).apply(null,Se)},qa:function(S){var A=h().length;if((S>>>=0)<=A||4294901760=I;I*=2){var L=A*(1+.2/I);L=Math.min(L,S+100663296);var j=Math;L=Math.max(S,L),j=j.min.call(j,4294901760,L+(65536-L%65536)%65536);e:{try{G.grow(j-J.byteLength+65535>>>16),Me(G.buffer);var q=1;break e}catch{}q=void 0}if(q)return!0}return!1},Na:function(){throw"unwind"},Ga:W,Ha:_e,J:ot,I:Ae,S:We,ga:et,R:zt,d:function(){return ze},na:function S(A,I){S.lc||(S.lc=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var j=new Uint8Array(1);return()=>(crypto.getRandomValues(j),j[0])}if(x)try{var q=o(Object(function(){var Z=new Error("Cannot find module 'crypto'");throw Z.code="MODULE_NOT_FOUND",Z}()));return()=>q.randomBytes(1)[0]}catch{}return()=>me("randomDevice")}());for(var L=0;L>0>>>0]=S.lc();return 0},ia:function(S,A,I){var L=he();try{return Te(S)(A,I)}catch(j){if(de(L),j!==j+0)throw j;pe(1,0)}},ja:function(S,A,I){var L=he();try{return Te(S)(A,I)}catch(j){if(de(L),j!==j+0)throw j;pe(1,0)}},K:function(S){var A=he();try{return Te(S)()}catch(I){if(de(A),I!==I+0)throw I;pe(1,0)}},f:function(S,A){var I=he();try{return Te(S)(A)}catch(L){if(de(I),L!==L+0)throw L;pe(1,0)}},P:function(S,A,I){var L=he();try{return Te(S)(A,I)}catch(j){if(de(L),j!==j+0)throw j;pe(1,0)}},Q:function(S,A,I){var L=he();try{return Te(S)(A,I)}catch(j){if(de(L),j!==j+0)throw j;pe(1,0)}},k:function(S,A,I){var L=he();try{return Te(S)(A,I)}catch(j){if(de(L),j!==j+0)throw j;pe(1,0)}},p:function(S,A,I,L){var j=he();try{return Te(S)(A,I,L)}catch(q){if(de(j),q!==q+0)throw q;pe(1,0)}},q:function(S,A,I,L,j){var q=he();try{return Te(S)(A,I,L,j)}catch(Z){if(de(q),Z!==Z+0)throw Z;pe(1,0)}},N:function(S,A,I,L,j,q){var Z=he();try{return Te(S)(A,I,L,j,q)}catch(re){if(de(Z),re!==re+0)throw re;pe(1,0)}},s:function(S,A,I,L,j,q){var Z=he();try{return Te(S)(A,I,L,j,q)}catch(re){if(de(Z),re!==re+0)throw re;pe(1,0)}},w:function(S,A,I,L,j,q,Z){var re=he();try{return Te(S)(A,I,L,j,q,Z)}catch(fe){if(de(re),fe!==fe+0)throw fe;pe(1,0)}},L:function(S,A,I,L,j,q,Z,re){var fe=he();try{return Te(S)(A,I,L,j,q,Z,re)}catch(ge){if(de(fe),ge!==ge+0)throw ge;pe(1,0)}},E:function(S,A,I,L,j,q,Z,re,fe,ge,Ce,Xe){var He=he();try{return Te(S)(A,I,L,j,q,Z,re,fe,ge,Ce,Xe)}catch(H){if(de(He),H!==H+0)throw H;pe(1,0)}},aa:function(S,A,I,L,j,q,Z,re){var fe=he();try{return ln(S,A,I,L,j,q,Z,re)}catch(ge){if(de(fe),ge!==ge+0)throw ge;pe(1,0)}},_:function(S,A,I,L,j,q,Z){var re=he();try{return en(S,A,I,L,j,q,Z)}catch(fe){if(de(re),fe!==fe+0)throw fe;pe(1,0)}},Z:function(S,A,I,L,j){var q=he();try{return un(S,A,I,L,j)}catch(Z){if(de(q),Z!==Z+0)throw Z;pe(1,0)}},ca:function(S,A,I,L){var j=he();try{return sn(S,A,I,L)}catch(q){if(de(j),q!==q+0)throw q;pe(1,0)}},$:function(S){var A=he();try{return Jt(S)}catch(I){if(de(A),I!==I+0)throw I;pe(1,0)}},ba:function(S,A){var I=he();try{return an(S,A)}catch(L){if(de(I),L!==L+0)throw L;pe(1,0)}},Y:function(S,A,I){var L=he();try{return tn(S,A,I)}catch(j){if(de(L),j!==j+0)throw j;pe(1,0)}},g:function(S){var A=he();try{Te(S)()}catch(I){if(de(A),I!==I+0)throw I;pe(1,0)}},r:function(S,A){var I=he();try{Te(S)(A)}catch(L){if(de(I),L!==L+0)throw L;pe(1,0)}},i:function(S,A,I){var L=he();try{Te(S)(A,I)}catch(j){if(de(L),j!==j+0)throw j;pe(1,0)}},ha:function(S,A,I,L){var j=he();try{Te(S)(A,I,L)}catch(q){if(de(j),q!==q+0)throw q;pe(1,0)}},m:function(S,A,I,L){var j=he();try{Te(S)(A,I,L)}catch(q){if(de(j),q!==q+0)throw q;pe(1,0)}},v:function(S,A,I,L,j){var q=he();try{Te(S)(A,I,L,j)}catch(Z){if(de(q),Z!==Z+0)throw Z;pe(1,0)}},u:function(S,A,I,L,j,q){var Z=he();try{Te(S)(A,I,L,j,q)}catch(re){if(de(Z),re!==re+0)throw re;pe(1,0)}},O:function(S,A,I,L,j,q,Z){var re=he();try{Te(S)(A,I,L,j,q,Z)}catch(fe){if(de(re),fe!==fe+0)throw fe;pe(1,0)}},A:function(S,A,I,L,j,q,Z,re){var fe=he();try{Te(S)(A,I,L,j,q,Z,re)}catch(ge){if(de(fe),ge!==ge+0)throw ge;pe(1,0)}},ka:function(S,A,I,L,j,q,Z,re,fe){var ge=he();try{Te(S)(A,I,L,j,q,Z,re,fe)}catch(Ce){if(de(ge),Ce!==Ce+0)throw Ce;pe(1,0)}},C:function(S,A,I,L,j,q,Z,re,fe,ge,Ce){var Xe=he();try{Te(S)(A,I,L,j,q,Z,re,fe,ge,Ce)}catch(He){if(de(Xe),He!==He+0)throw He;pe(1,0)}},D:function(S,A,I,L,j,q,Z,re,fe,ge,Ce,Xe,He,H,ye,Ie){var tt=he();try{Te(S)(A,I,L,j,q,Z,re,fe,ge,Ce,Xe,He,H,ye,Ie)}catch(ht){if(de(tt),ht!==ht+0)throw ht;pe(1,0)}},fa:function(S,A,I,L,j,q,Z,re){var fe=he();try{nn(S,A,I,L,j,q,Z,re)}catch(ge){if(de(fe),ge!==ge+0)throw ge;pe(1,0)}},da:function(S,A,I,L,j,q,Z,re,fe,ge,Ce,Xe){var He=he();try{on(S,A,I,L,j,q,Z,re,fe,ge,Ce,Xe)}catch(H){if(de(He),H!==H+0)throw H;pe(1,0)}},ea:function(S,A,I,L,j,q){var Z=he();try{rn(S,A,I,L,j,q)}catch(re){if(de(Z),re!==re+0)throw re;pe(1,0)}},o:function(S){return S},a:G||n.wasmMemory,G:function(S){ze=S},la:Ut,z:function(S,A,I,L){return Ut(S,A,I,L)}};(function(){function S(j,q){n.asm=j.exports,oe.qc.push(n.asm.sb),je=n.asm.ub,Ge.unshift(n.asm.Va),ee=q,O||(Be--,n.monitorRunDependencies&&n.monitorRunDependencies(Be),Be==0&&Ke&&(j=Ke,Ke=null,j()))}function A(j){S(j.instance,j.module)}function I(j){return function(){if(!V&&(E||P)){if(typeof fetch=="function"&&!Oe.startsWith("file://"))return fetch(Oe,{credentials:"same-origin"}).then(function(q){if(!q.ok)throw"failed to load wasm binary file at '"+Oe+"'";return q.arrayBuffer()}).catch(function(){return ut()});if(f)return new Promise(function(q,Z){f(Oe,function(re){q(new Uint8Array(re))},Z)})}return Promise.resolve().then(function(){return ut()})}().then(function(q){return WebAssembly.instantiate(q,L)}).then(function(q){return q}).then(j,function(q){B("failed to asynchronously prepare wasm: "+q),me(q)})}var L={a:pn};if(O||(Be++,n.monitorRunDependencies&&n.monitorRunDependencies(Be)),n.instantiateWasm)try{return n.instantiateWasm(L,S)}catch(j){return B("Module.instantiateWasm callback failed with error: "+j),!1}(V||typeof WebAssembly.instantiateStreaming!="function"||pt()||Oe.startsWith("file://")||x||typeof fetch!="function"?I(A):fetch(Oe,{credentials:"same-origin"}).then(function(j){return WebAssembly.instantiateStreaming(j,L).then(A,function(q){return B("wasm streaming compile failed: "+q),B("falling back to ArrayBuffer instantiation"),I(A)})})).catch(r)})(),n.___wasm_call_ctors=function(){return(n.___wasm_call_ctors=n.asm.Va).apply(null,arguments)},n._OrtInit=function(){return(n._OrtInit=n.asm.Wa).apply(null,arguments)},n._OrtCreateSessionOptions=function(){return(n._OrtCreateSessionOptions=n.asm.Xa).apply(null,arguments)},n._OrtAppendExecutionProvider=function(){return(n._OrtAppendExecutionProvider=n.asm.Ya).apply(null,arguments)},n._OrtAddSessionConfigEntry=function(){return(n._OrtAddSessionConfigEntry=n.asm.Za).apply(null,arguments)},n._OrtReleaseSessionOptions=function(){return(n._OrtReleaseSessionOptions=n.asm._a).apply(null,arguments)},n._OrtCreateSession=function(){return(n._OrtCreateSession=n.asm.$a).apply(null,arguments)},n._OrtReleaseSession=function(){return(n._OrtReleaseSession=n.asm.ab).apply(null,arguments)},n._OrtGetInputCount=function(){return(n._OrtGetInputCount=n.asm.bb).apply(null,arguments)},n._OrtGetOutputCount=function(){return(n._OrtGetOutputCount=n.asm.cb).apply(null,arguments)},n._OrtGetInputName=function(){return(n._OrtGetInputName=n.asm.db).apply(null,arguments)},n._OrtGetOutputName=function(){return(n._OrtGetOutputName=n.asm.eb).apply(null,arguments)},n._OrtFree=function(){return(n._OrtFree=n.asm.fb).apply(null,arguments)},n._OrtCreateTensor=function(){return(n._OrtCreateTensor=n.asm.gb).apply(null,arguments)},n._OrtGetTensorData=function(){return(n._OrtGetTensorData=n.asm.hb).apply(null,arguments)},n._OrtReleaseTensor=function(){return(n._OrtReleaseTensor=n.asm.ib).apply(null,arguments)},n._OrtCreateRunOptions=function(){return(n._OrtCreateRunOptions=n.asm.jb).apply(null,arguments)},n._OrtAddRunConfigEntry=function(){return(n._OrtAddRunConfigEntry=n.asm.kb).apply(null,arguments)},n._OrtReleaseRunOptions=function(){return(n._OrtReleaseRunOptions=n.asm.lb).apply(null,arguments)},n._OrtRun=function(){return(n._OrtRun=n.asm.mb).apply(null,arguments)},n._OrtEndProfiling=function(){return(n._OrtEndProfiling=n.asm.nb).apply(null,arguments)};var Ct=n._pthread_self=function(){return(Ct=n._pthread_self=n.asm.ob).apply(null,arguments)},$t=n._malloc=function(){return($t=n._malloc=n.asm.pb).apply(null,arguments)},Gt=n._free=function(){return(Gt=n._free=n.asm.qb).apply(null,arguments)},qt=n._fflush=function(){return(qt=n._fflush=n.asm.rb).apply(null,arguments)};n.__emscripten_tls_init=function(){return(n.__emscripten_tls_init=n.asm.sb).apply(null,arguments)};var Wt=n.___funcs_on_exit=function(){return(Wt=n.___funcs_on_exit=n.asm.tb).apply(null,arguments)},Ht=n.__emscripten_thread_init=function(){return(Ht=n.__emscripten_thread_init=n.asm.vb).apply(null,arguments)};n.__emscripten_thread_crashed=function(){return(n.__emscripten_thread_crashed=n.asm.wb).apply(null,arguments)};var Dt,Yt=n._emscripten_run_in_main_runtime_thread_js=function(){return(Yt=n._emscripten_run_in_main_runtime_thread_js=n.asm.xb).apply(null,arguments)},Kt=n.__emscripten_proxy_execute_task_queue=function(){return(Kt=n.__emscripten_proxy_execute_task_queue=n.asm.yb).apply(null,arguments)},Rt=n.__emscripten_thread_free_data=function(){return(Rt=n.__emscripten_thread_free_data=n.asm.zb).apply(null,arguments)},Xt=n.__emscripten_thread_exit=function(){return(Xt=n.__emscripten_thread_exit=n.asm.Ab).apply(null,arguments)},pe=n._setThrew=function(){return(pe=n._setThrew=n.asm.Bb).apply(null,arguments)},Qt=n._emscripten_stack_set_limits=function(){return(Qt=n._emscripten_stack_set_limits=n.asm.Cb).apply(null,arguments)},he=n.stackSave=function(){return(he=n.stackSave=n.asm.Db).apply(null,arguments)},de=n.stackRestore=function(){return(de=n.stackRestore=n.asm.Eb).apply(null,arguments)},Bt=n.stackAlloc=function(){return(Bt=n.stackAlloc=n.asm.Fb).apply(null,arguments)},Ft=n.___cxa_can_catch=function(){return(Ft=n.___cxa_can_catch=n.asm.Gb).apply(null,arguments)},Zt=n.___cxa_is_pointer_type=function(){return(Zt=n.___cxa_is_pointer_type=n.asm.Hb).apply(null,arguments)},Jt=n.dynCall_j=function(){return(Jt=n.dynCall_j=n.asm.Ib).apply(null,arguments)},en=n.dynCall_iiiiij=function(){return(en=n.dynCall_iiiiij=n.asm.Jb).apply(null,arguments)},tn=n.dynCall_jii=function(){return(tn=n.dynCall_jii=n.asm.Kb).apply(null,arguments)},nn=n.dynCall_viiiiij=function(){return(nn=n.dynCall_viiiiij=n.asm.Lb).apply(null,arguments)},rn=n.dynCall_vjji=function(){return(rn=n.dynCall_vjji=n.asm.Mb).apply(null,arguments)},on=n.dynCall_viiijjjii=function(){return(on=n.dynCall_viiijjjii=n.asm.Nb).apply(null,arguments)},sn=n.dynCall_iij=function(){return(sn=n.dynCall_iij=n.asm.Ob).apply(null,arguments)},an=n.dynCall_ji=function(){return(an=n.dynCall_ji=n.asm.Pb).apply(null,arguments)},ln=n.dynCall_iiiiiij=function(){return(ln=n.dynCall_iiiiiij=n.asm.Qb).apply(null,arguments)},un=n.dynCall_iiij=function(){return(un=n.dynCall_iiij=n.asm.Rb).apply(null,arguments)};function cn(){function S(){if(!Dt&&(Dt=!0,n.calledRun=!0,!be)&&(O||rt(Ge),e(n),n.onRuntimeInitialized&&n.onRuntimeInitialized(),!O)){if(n.postRun)for(typeof n.postRun=="function"&&(n.postRun=[n.postRun]);n.postRun.length;){var A=n.postRun.shift();Qe.unshift(A)}rt(Qe)}}if(!(0{var i,u=(i=(i=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(d){var a,h,m;d=d||{},a||(a=d!==void 0?d:{}),a.ready=new Promise(function(M,F){h=M,m=F});var c,l,n,e,r,s,f=Object.assign({},a),g="./this.program",_=(M,F)=>{throw F},b=typeof window=="object",y=typeof importScripts=="function",T=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",w="";T?(w=y?o(908).dirname(w)+"/":"//",s=()=>{r||(e=o(1384),r=o(908))},c=function(M,F){return s(),M=r.normalize(M),e.readFileSync(M,F?void 0:"utf8")},n=M=>((M=c(M,!0)).buffer||(M=new Uint8Array(M)),M),l=(M,F,R)=>{s(),M=r.normalize(M),e.readFile(M,function(z,U){z?R(z):F(U.buffer)})},1{if(x||0{var F=new XMLHttpRequest;return F.open("GET",M,!1),F.send(null),F.responseText},y&&(n=M=>{var F=new XMLHttpRequest;return F.open("GET",M,!1),F.responseType="arraybuffer",F.send(null),new Uint8Array(F.response)}),l=(M,F,R)=>{var z=new XMLHttpRequest;z.open("GET",M,!0),z.responseType="arraybuffer",z.onload=()=>{z.status==200||z.status==0&&z.response?F(z.response):R()},z.onerror=R,z.send(null)});var v,E=a.print||console.log.bind(console),P=a.printErr||console.warn.bind(console);Object.assign(a,f),f=null,a.thisProgram&&(g=a.thisProgram),a.quit&&(_=a.quit),a.wasmBinary&&(v=a.wasmBinary);var x=a.noExitRuntime||!1;typeof WebAssembly!="object"&&Me("no native wasm support detected");var O,$,k,N,D,V,C=!1,B=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function X(M,F,R){var z=(F>>>=0)+R;for(R=F;M[R]&&!(R>=z);)++R;if(16(U=(240&U)==224?(15&U)<<12|Y<<6|Q:(7&U)<<18|Y<<12|Q<<6|63&M[F++])?z+=String.fromCharCode(U):(U-=65536,z+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else z+=String.fromCharCode(U)}return z}function G(M,F){return(M>>>=0)?X(N,M,F):""}function ee(M,F,R,z){if(!(0>>=0;z=R+z-1;for(var Y=0;Y=Q&&(Q=65536+((1023&Q)<<10)|1023&M.charCodeAt(++Y)),127>=Q){if(R>=z)break;F[R++>>>0]=Q}else{if(2047>=Q){if(R+1>=z)break;F[R++>>>0]=192|Q>>6}else{if(65535>=Q){if(R+2>=z)break;F[R++>>>0]=224|Q>>12}else{if(R+3>=z)break;F[R++>>>0]=240|Q>>18,F[R++>>>0]=128|Q>>12&63}F[R++>>>0]=128|Q>>6&63}F[R++>>>0]=128|63&Q}}return F[R>>>0]=0,R-U}function J(M){for(var F=0,R=0;R=z?F++:2047>=z?F+=2:55296<=z&&57343>=z?(F+=4,++R):F+=3}return F}function ae(){var M=O.buffer;$=M,a.HEAP8=k=new Int8Array(M),a.HEAP16=new Int16Array(M),a.HEAP32=D=new Int32Array(M),a.HEAPU8=N=new Uint8Array(M),a.HEAPU16=new Uint16Array(M),a.HEAPU32=V=new Uint32Array(M),a.HEAPF32=new Float32Array(M),a.HEAPF64=new Float64Array(M)}var Ee,xe=[],le=[],we=[],be=[],ke=0;function Le(){var M=a.preRun.shift();xe.unshift(M)}var ve,$e=0,Fe=null;function Me(M){throw a.onAbort&&a.onAbort(M),P(M="Aborted("+M+")"),C=!0,M=new WebAssembly.RuntimeError(M+". Build with -sASSERTIONS for more info."),m(M),M}function Pe(){return ve.startsWith("data:application/octet-stream;base64,")}if(ve="ort-wasm.wasm",!Pe()){var je=ve;ve=a.locateFile?a.locateFile(je,w):w+je}function Ue(){var M=ve;try{if(M==ve&&v)return new Uint8Array(v);if(n)return n(M);throw"both async and sync fetching of the wasm failed"}catch(F){Me(F)}}function Ge(M){this.name="ExitStatus",this.message="Program terminated with exit("+M+")",this.status=M}function Ye(M){for(;0>2>>>0]=F},this.Eb=function(){return V[this.zb+4>>2>>>0]},this.Sb=function(F){V[this.zb+8>>2>>>0]=F},this.Wb=function(){return V[this.zb+8>>2>>>0]},this.Tb=function(){D[this.zb>>2>>>0]=0},this.Ib=function(F){k[this.zb+12>>0>>>0]=F?1:0},this.Pb=function(){return k[this.zb+12>>0>>>0]!=0},this.Jb=function(F){k[this.zb+13>>0>>>0]=F?1:0},this.Lb=function(){return k[this.zb+13>>0>>>0]!=0},this.Rb=function(F,R){this.Fb(0),this.Ub(F),this.Sb(R),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){D[this.zb>>2>>>0]+=1},this.Xb=function(){var F=D[this.zb>>2>>>0];return D[this.zb>>2>>>0]=F-1,F===1},this.Fb=function(F){V[this.zb+16>>2>>>0]=F},this.Ob=function(){return V[this.zb+16>>2>>>0]},this.Qb=function(){if(gt(this.Eb()))return V[this.Db>>2>>>0];var F=this.Ob();return F!==0?F:this.Db}}function Be(M){return it(new Oe(M).zb)}var Ke=[];function me(M){var F=Ke[M];return F||(M>=Ke.length&&(Ke.length=M+1),Ke[M]=F=Ee.get(M)),F}function pt(M){var F=J(M)+1,R=Te(F);return R&&ee(M,k,R,F),R}var ut={};function Ot(){if(!Ze){var M,F={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"};for(M in ut)ut[M]===void 0?delete F[M]:F[M]=ut[M];var R=[];for(M in F)R.push(M+"="+F[M]);Ze=R}return Ze}var Ze,ct=[null,[],[]];function dt(M,F){var R=ct[M];F===0||F===10?((M===1?E:P)(X(R,0)),R.length=0):R.push(F)}var Re=0;function ot(M){return M%4==0&&(M%100!=0||M%400==0)}var oe=[31,29,31,30,31,30,31,31,30,31,30,31],rt=[31,28,31,30,31,30,31,31,30,31,30,31];function Mt(M,F,R,z){function U(W,_e,Ae){for(W=typeof W=="number"?W.toString():W||"";W.length<_e;)W=Ae[0]+W;return W}function Y(W,_e){return U(W,_e,"0")}function Q(W,_e){function Ae(et){return 0>et?-1:0We-W.getDate())){W.setDate(W.getDate()+_e);break}_e-=We-W.getDate()+1,W.setDate(1),11>Ae?W.setMonth(Ae+1):(W.setMonth(0),W.setFullYear(W.getFullYear()+1))}return Ae=new Date(W.getFullYear()+1,0,4),_e=ne(new Date(W.getFullYear(),0,4)),Ae=ne(Ae),0>=Q(_e,W)?0>=Q(Ae,W)?W.getFullYear()+1:W.getFullYear():W.getFullYear()-1}var ce=D[z+40>>2>>>0];for(var Se in z={$b:D[z>>2>>>0],Zb:D[z+4>>2>>>0],Gb:D[z+8>>2>>>0],Kb:D[z+12>>2>>>0],Hb:D[z+16>>2>>>0],Cb:D[z+20>>2>>>0],Ab:D[z+24>>2>>>0],Bb:D[z+28>>2>>>0],bc:D[z+32>>2>>>0],Yb:D[z+36>>2>>>0],ac:ce?G(ce):""},R=G(R),ce={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})R=R.replace(new RegExp(Se,"g"),ce[Se]);var Ne="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),De="January February March April May June July August September October November December".split(" ");for(Se in ce={"%a":function(W){return Ne[W.Ab].substring(0,3)},"%A":function(W){return Ne[W.Ab]},"%b":function(W){return De[W.Hb].substring(0,3)},"%B":function(W){return De[W.Hb]},"%C":function(W){return Y((W.Cb+1900)/100|0,2)},"%d":function(W){return Y(W.Kb,2)},"%e":function(W){return U(W.Kb,2," ")},"%g":function(W){return te(W).toString().substring(2)},"%G":function(W){return te(W)},"%H":function(W){return Y(W.Gb,2)},"%I":function(W){return(W=W.Gb)==0?W=12:12W.Gb?"AM":"PM"},"%S":function(W){return Y(W.$b,2)},"%t":function(){return" "},"%u":function(W){return W.Ab||7},"%U":function(W){return Y(Math.floor((W.Bb+7-W.Ab)/7),2)},"%V":function(W){var _e=Math.floor((W.Bb+7-(W.Ab+6)%7)/7);if(2>=(W.Ab+371-W.Bb-2)%7&&_e++,_e)_e==53&&((Ae=(W.Ab+371-W.Bb)%7)==4||Ae==3&&ot(W.Cb)||(_e=1));else{_e=52;var Ae=(W.Ab+7-W.Bb-1)%7;(Ae==4||Ae==5&&ot(W.Cb%400-1))&&_e++}return Y(_e,2)},"%w":function(W){return W.Ab},"%W":function(W){return Y(Math.floor((W.Bb+7-(W.Ab+6)%7)/7),2)},"%y":function(W){return(W.Cb+1900).toString().substring(2)},"%Y":function(W){return W.Cb+1900},"%z":function(W){var _e=0<=(W=W.Yb);return W=Math.abs(W)/60,(_e?"+":"-")+("0000"+(W/60*100+W%60)).slice(-4)},"%Z":function(W){return W.ac},"%%":function(){return"%"}},R=R.replace(/%%/g,"\0\0"),ce)R.includes(Se)&&(R=R.replace(new RegExp(Se,"g"),ce[Se](z)));return Se=function(W){var _e=Array(J(W)+1);return ee(W,_e,0,_e.length),_e}(R=R.replace(/\0\0/g,"%")),Se.length>F?0:(k.set(Se,M>>>0),Se.length-1)}var It={a:function(M){return Te(M+24)+24},m:function(M){return(M=new Oe(M)).Pb()||(M.Ib(!0),qe--),M.Jb(!1),Qe.push(M),M.Nb(),M.Qb()},ia:function(M){throw P("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,M},w:function(){ue(0);var M=Qe.pop();if(M.Xb()&&!M.Lb()){var F=M.Wb();F&&me(F)(M.Db),Be(M.Db)}Ve=0},d:function(){var M=Ve;if(!M)return Re=0;var F=new Oe(M);F.Fb(M);var R=F.Eb();if(!R)return Re=0,M;for(var z=Array.prototype.slice.call(arguments),U=0;U>>2]+4294967296*D[M+4>>>2])),D[F>>2>>>0]=M.getUTCSeconds(),D[F+4>>2>>>0]=M.getUTCMinutes(),D[F+8>>2>>>0]=M.getUTCHours(),D[F+12>>2>>>0]=M.getUTCDate(),D[F+16>>2>>>0]=M.getUTCMonth(),D[F+20>>2>>>0]=M.getUTCFullYear()-1900,D[F+24>>2>>>0]=M.getUTCDay(),D[F+28>>2>>>0]=(M.getTime()-Date.UTC(M.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(M,F){M=new Date(1e3*(V[M>>>2]+4294967296*D[M+4>>>2])),D[F>>2>>>0]=M.getSeconds(),D[F+4>>2>>>0]=M.getMinutes(),D[F+8>>2>>>0]=M.getHours(),D[F+12>>2>>>0]=M.getDate(),D[F+16>>2>>>0]=M.getMonth(),D[F+20>>2>>>0]=M.getFullYear()-1900,D[F+24>>2>>>0]=M.getDay();var R=new Date(M.getFullYear(),0,1);D[F+28>>2>>>0]=(M.getTime()-R.getTime())/864e5|0,D[F+36>>2>>>0]=-60*M.getTimezoneOffset();var z=new Date(M.getFullYear(),6,1).getTimezoneOffset();R=R.getTimezoneOffset(),D[F+32>>2>>>0]=0|(z!=R&&M.getTimezoneOffset()==Math.min(R,z))},Fa:function(M){var F=new Date(D[M+20>>2>>>0]+1900,D[M+16>>2>>>0],D[M+12>>2>>>0],D[M+8>>2>>>0],D[M+4>>2>>>0],D[M>>2>>>0],0),R=D[M+32>>2>>>0],z=F.getTimezoneOffset(),U=new Date(F.getFullYear(),0,1),Y=new Date(F.getFullYear(),6,1).getTimezoneOffset(),Q=U.getTimezoneOffset(),ne=Math.min(Q,Y);return 0>R?D[M+32>>2>>>0]=+(Y!=Q&&ne==z):0>2>>>0]=F.getDay(),D[M+28>>2>>>0]=(F.getTime()-U.getTime())/864e5|0,D[M>>2>>>0]=F.getSeconds(),D[M+4>>2>>>0]=F.getMinutes(),D[M+8>>2>>>0]=F.getHours(),D[M+12>>2>>>0]=F.getDate(),D[M+16>>2>>>0]=F.getMonth(),F.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function M(F,R,z){M.Vb||(M.Vb=!0,function(U,Y,Q){function ne(De){return(De=De.toTimeString().match(/\(([A-Za-z ]+)\)$/))?De[1]:"GMT"}var te=new Date().getFullYear(),ce=new Date(te,0,1),Se=new Date(te,6,1);te=ce.getTimezoneOffset();var Ne=Se.getTimezoneOffset();D[U>>2>>>0]=60*Math.max(te,Ne),D[Y>>2>>>0]=+(te!=Ne),U=ne(ce),Y=ne(Se),U=pt(U),Y=pt(Y),Ne>2>>>0]=U,V[Q+4>>2>>>0]=Y):(V[Q>>2>>>0]=Y,V[Q+4>>2>>>0]=U)}(F,R,z))},B:function(){Me("")},ma:function(){return 4294901760},I:T?()=>{var M=process.hrtime();return 1e3*M[0]+M[1]/1e6}:()=>performance.now(),xa:function(M,F,R){N.copyWithin(M>>>0,F>>>0,F+R>>>0)},G:function(M){var F=N.length;if(4294901760<(M>>>=0))return!1;for(var R=1;4>=R;R*=2){var z=F*(1+.2/R);z=Math.min(z,M+100663296);var U=Math;z=Math.max(M,z),U=U.min.call(U,4294901760,z+(65536-z%65536)%65536);e:{try{O.grow(U-$.byteLength+65535>>>16),ae();var Y=1;break e}catch{}Y=void 0}if(Y)return!0}return!1},va:function(M,F){var R=0;return Ot().forEach(function(z,U){var Y=F+R;for(U=V[M+4*U>>2>>>0]=Y,Y=0;Y>0>>>0]=z.charCodeAt(Y);k[U>>0>>>0]=0,R+=z.length+1}),0},wa:function(M,F){var R=Ot();V[M>>2>>>0]=R.length;var z=0;return R.forEach(function(U){z+=U.length+1}),V[F>>2>>>0]=z,0},ba:function(M){x||0>2>>>0],ne=V[F+4>>2>>>0];F+=8;for(var te=0;te>>0]);U+=ne}return V[z>>2>>>0]=U,0},c:function(){return Re},ja:function M(F,R){M.Mb||(M.Mb=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var U=new Uint8Array(1);return()=>(crypto.getRandomValues(U),U[0])}if(T)try{var Y=o(Object(function(){var Q=new Error("Cannot find module 'crypto'");throw Q.code="MODULE_NOT_FOUND",Q}()));return()=>Y.randomBytes(1)[0]}catch{}return()=>Me("randomDevice")}());for(var z=0;z>0>>>0]=M.Mb();return 0},ea:function(M,F,R){var z=ie();try{return me(M)(F,R)}catch(U){if(se(z),U!==U+0)throw U;ue(1,0)}},fa:function(M,F,R){var z=ie();try{return me(M)(F,R)}catch(U){if(se(z),U!==U+0)throw U;ue(1,0)}},J:function(M){var F=ie();try{return me(M)()}catch(R){if(se(F),R!==R+0)throw R;ue(1,0)}},e:function(M,F){var R=ie();try{return me(M)(F)}catch(z){if(se(R),z!==z+0)throw z;ue(1,0)}},N:function(M,F,R){var z=ie();try{return me(M)(F,R)}catch(U){if(se(z),U!==U+0)throw U;ue(1,0)}},O:function(M,F,R){var z=ie();try{return me(M)(F,R)}catch(U){if(se(z),U!==U+0)throw U;ue(1,0)}},j:function(M,F,R){var z=ie();try{return me(M)(F,R)}catch(U){if(se(z),U!==U+0)throw U;ue(1,0)}},o:function(M,F,R,z){var U=ie();try{return me(M)(F,R,z)}catch(Y){if(se(U),Y!==Y+0)throw Y;ue(1,0)}},p:function(M,F,R,z,U){var Y=ie();try{return me(M)(F,R,z,U)}catch(Q){if(se(Y),Q!==Q+0)throw Q;ue(1,0)}},M:function(M,F,R,z,U,Y){var Q=ie();try{return me(M)(F,R,z,U,Y)}catch(ne){if(se(Q),ne!==ne+0)throw ne;ue(1,0)}},r:function(M,F,R,z,U,Y){var Q=ie();try{return me(M)(F,R,z,U,Y)}catch(ne){if(se(Q),ne!==ne+0)throw ne;ue(1,0)}},v:function(M,F,R,z,U,Y,Q){var ne=ie();try{return me(M)(F,R,z,U,Y,Q)}catch(te){if(se(ne),te!==te+0)throw te;ue(1,0)}},K:function(M,F,R,z,U,Y,Q,ne){var te=ie();try{return me(M)(F,R,z,U,Y,Q,ne)}catch(ce){if(se(te),ce!==ce+0)throw ce;ue(1,0)}},D:function(M,F,R,z,U,Y,Q,ne,te,ce,Se,Ne){var De=ie();try{return me(M)(F,R,z,U,Y,Q,ne,te,ce,Se,Ne)}catch(W){if(se(De),W!==W+0)throw W;ue(1,0)}},X:function(M,F,R,z,U,Y,Q,ne){var te=ie();try{return Et(M,F,R,z,U,Y,Q,ne)}catch(ce){if(se(te),ce!==ce+0)throw ce;ue(1,0)}},V:function(M,F,R,z,U,Y,Q){var ne=ie();try{return bt(M,F,R,z,U,Y,Q)}catch(te){if(se(ne),te!==te+0)throw te;ue(1,0)}},U:function(M,F,R,z,U){var Y=ie();try{return Pt(M,F,R,z,U)}catch(Q){if(se(Y),Q!==Q+0)throw Q;ue(1,0)}},Z:function(M,F,R,z){var U=ie();try{return vt(M,F,R,z)}catch(Y){if(se(U),Y!==Y+0)throw Y;ue(1,0)}},W:function(M){var F=ie();try{return _t(M)}catch(R){if(se(F),R!==R+0)throw R;ue(1,0)}},Y:function(M,F){var R=ie();try{return St(M,F)}catch(z){if(se(R),z!==z+0)throw z;ue(1,0)}},T:function(M,F,R){var z=ie();try{return yt(M,F,R)}catch(U){if(se(z),U!==U+0)throw U;ue(1,0)}},f:function(M){var F=ie();try{me(M)()}catch(R){if(se(F),R!==R+0)throw R;ue(1,0)}},q:function(M,F){var R=ie();try{me(M)(F)}catch(z){if(se(R),z!==z+0)throw z;ue(1,0)}},h:function(M,F,R){var z=ie();try{me(M)(F,R)}catch(U){if(se(z),U!==U+0)throw U;ue(1,0)}},da:function(M,F,R,z){var U=ie();try{me(M)(F,R,z)}catch(Y){if(se(U),Y!==Y+0)throw Y;ue(1,0)}},l:function(M,F,R,z){var U=ie();try{me(M)(F,R,z)}catch(Y){if(se(U),Y!==Y+0)throw Y;ue(1,0)}},t:function(M,F,R,z,U){var Y=ie();try{me(M)(F,R,z,U)}catch(Q){if(se(Y),Q!==Q+0)throw Q;ue(1,0)}},u:function(M,F,R,z,U,Y){var Q=ie();try{me(M)(F,R,z,U,Y)}catch(ne){if(se(Q),ne!==ne+0)throw ne;ue(1,0)}},x:function(M,F,R,z,U,Y,Q){var ne=ie();try{me(M)(F,R,z,U,Y,Q)}catch(te){if(se(ne),te!==te+0)throw te;ue(1,0)}},z:function(M,F,R,z,U,Y,Q,ne){var te=ie();try{me(M)(F,R,z,U,Y,Q,ne)}catch(ce){if(se(te),ce!==ce+0)throw ce;ue(1,0)}},ga:function(M,F,R,z,U,Y,Q,ne,te){var ce=ie();try{me(M)(F,R,z,U,Y,Q,ne,te)}catch(Se){if(se(ce),Se!==Se+0)throw Se;ue(1,0)}},A:function(M,F,R,z,U,Y,Q,ne,te,ce,Se){var Ne=ie();try{me(M)(F,R,z,U,Y,Q,ne,te,ce,Se)}catch(De){if(se(Ne),De!==De+0)throw De;ue(1,0)}},C:function(M,F,R,z,U,Y,Q,ne,te,ce,Se,Ne,De,W,_e,Ae){var We=ie();try{me(M)(F,R,z,U,Y,Q,ne,te,ce,Se,Ne,De,W,_e,Ae)}catch(et){if(se(We),et!==et+0)throw et;ue(1,0)}},aa:function(M,F,R,z,U,Y,Q,ne){var te=ie();try{wt(M,F,R,z,U,Y,Q,ne)}catch(ce){if(se(te),ce!==ce+0)throw ce;ue(1,0)}},_:function(M,F,R,z,U,Y,Q,ne,te,ce,Se,Ne){var De=ie();try{xt(M,F,R,z,U,Y,Q,ne,te,ce,Se,Ne)}catch(W){if(se(De),W!==W+0)throw W;ue(1,0)}},$:function(M,F,R,z,U,Y){var Q=ie();try{Tt(M,F,R,z,U,Y)}catch(ne){if(se(Q),ne!==ne+0)throw ne;ue(1,0)}},n:function(M){return M},F:function(M){Re=M},ha:Mt,y:function(M,F,R,z){return Mt(M,F,R,z)}};(function(){function M(U){a.asm=U.exports,O=a.asm.Ka,ae(),Ee=a.asm.ib,le.unshift(a.asm.La),$e--,a.monitorRunDependencies&&a.monitorRunDependencies($e),$e==0&&Fe&&(U=Fe,Fe=null,U())}function F(U){M(U.instance)}function R(U){return function(){if(!v&&(b||y)){if(typeof fetch=="function"&&!ve.startsWith("file://"))return fetch(ve,{credentials:"same-origin"}).then(function(Y){if(!Y.ok)throw"failed to load wasm binary file at '"+ve+"'";return Y.arrayBuffer()}).catch(function(){return Ue()});if(l)return new Promise(function(Y,Q){l(ve,function(ne){Y(new Uint8Array(ne))},Q)})}return Promise.resolve().then(function(){return Ue()})}().then(function(Y){return WebAssembly.instantiate(Y,z)}).then(function(Y){return Y}).then(U,function(Y){P("failed to asynchronously prepare wasm: "+Y),Me(Y)})}var z={a:It};if($e++,a.monitorRunDependencies&&a.monitorRunDependencies($e),a.instantiateWasm)try{return a.instantiateWasm(z,M)}catch(U){return P("Module.instantiateWasm callback failed with error: "+U),!1}(v||typeof WebAssembly.instantiateStreaming!="function"||Pe()||ve.startsWith("file://")||T||typeof fetch!="function"?R(F):fetch(ve,{credentials:"same-origin"}).then(function(U){return WebAssembly.instantiateStreaming(U,z).then(F,function(Y){return P("wasm streaming compile failed: "+Y),P("falling back to ArrayBuffer instantiation"),R(F)})})).catch(m)})(),a.___wasm_call_ctors=function(){return(a.___wasm_call_ctors=a.asm.La).apply(null,arguments)},a._OrtInit=function(){return(a._OrtInit=a.asm.Ma).apply(null,arguments)},a._OrtCreateSessionOptions=function(){return(a._OrtCreateSessionOptions=a.asm.Na).apply(null,arguments)},a._OrtAppendExecutionProvider=function(){return(a._OrtAppendExecutionProvider=a.asm.Oa).apply(null,arguments)},a._OrtAddSessionConfigEntry=function(){return(a._OrtAddSessionConfigEntry=a.asm.Pa).apply(null,arguments)},a._OrtReleaseSessionOptions=function(){return(a._OrtReleaseSessionOptions=a.asm.Qa).apply(null,arguments)},a._OrtCreateSession=function(){return(a._OrtCreateSession=a.asm.Ra).apply(null,arguments)},a._OrtReleaseSession=function(){return(a._OrtReleaseSession=a.asm.Sa).apply(null,arguments)},a._OrtGetInputCount=function(){return(a._OrtGetInputCount=a.asm.Ta).apply(null,arguments)},a._OrtGetOutputCount=function(){return(a._OrtGetOutputCount=a.asm.Ua).apply(null,arguments)},a._OrtGetInputName=function(){return(a._OrtGetInputName=a.asm.Va).apply(null,arguments)},a._OrtGetOutputName=function(){return(a._OrtGetOutputName=a.asm.Wa).apply(null,arguments)},a._OrtFree=function(){return(a._OrtFree=a.asm.Xa).apply(null,arguments)},a._OrtCreateTensor=function(){return(a._OrtCreateTensor=a.asm.Ya).apply(null,arguments)},a._OrtGetTensorData=function(){return(a._OrtGetTensorData=a.asm.Za).apply(null,arguments)},a._OrtReleaseTensor=function(){return(a._OrtReleaseTensor=a.asm._a).apply(null,arguments)},a._OrtCreateRunOptions=function(){return(a._OrtCreateRunOptions=a.asm.$a).apply(null,arguments)},a._OrtAddRunConfigEntry=function(){return(a._OrtAddRunConfigEntry=a.asm.ab).apply(null,arguments)},a._OrtReleaseRunOptions=function(){return(a._OrtReleaseRunOptions=a.asm.bb).apply(null,arguments)},a._OrtRun=function(){return(a._OrtRun=a.asm.cb).apply(null,arguments)},a._OrtEndProfiling=function(){return(a._OrtEndProfiling=a.asm.db).apply(null,arguments)};var Je,Te=a._malloc=function(){return(Te=a._malloc=a.asm.eb).apply(null,arguments)},it=a._free=function(){return(it=a._free=a.asm.fb).apply(null,arguments)},ft=a._fflush=function(){return(ft=a._fflush=a.asm.gb).apply(null,arguments)},st=a.___funcs_on_exit=function(){return(st=a.___funcs_on_exit=a.asm.hb).apply(null,arguments)},ue=a._setThrew=function(){return(ue=a._setThrew=a.asm.jb).apply(null,arguments)},ie=a.stackSave=function(){return(ie=a.stackSave=a.asm.kb).apply(null,arguments)},se=a.stackRestore=function(){return(se=a.stackRestore=a.asm.lb).apply(null,arguments)},mt=a.stackAlloc=function(){return(mt=a.stackAlloc=a.asm.mb).apply(null,arguments)},at=a.___cxa_can_catch=function(){return(at=a.___cxa_can_catch=a.asm.nb).apply(null,arguments)},gt=a.___cxa_is_pointer_type=function(){return(gt=a.___cxa_is_pointer_type=a.asm.ob).apply(null,arguments)},_t=a.dynCall_j=function(){return(_t=a.dynCall_j=a.asm.pb).apply(null,arguments)},bt=a.dynCall_iiiiij=function(){return(bt=a.dynCall_iiiiij=a.asm.qb).apply(null,arguments)},yt=a.dynCall_jii=function(){return(yt=a.dynCall_jii=a.asm.rb).apply(null,arguments)},wt=a.dynCall_viiiiij=function(){return(wt=a.dynCall_viiiiij=a.asm.sb).apply(null,arguments)},Tt=a.dynCall_vjji=function(){return(Tt=a.dynCall_vjji=a.asm.tb).apply(null,arguments)},xt=a.dynCall_viiijjjii=function(){return(xt=a.dynCall_viiijjjii=a.asm.ub).apply(null,arguments)},vt=a.dynCall_iij=function(){return(vt=a.dynCall_iij=a.asm.vb).apply(null,arguments)},St=a.dynCall_ji=function(){return(St=a.dynCall_ji=a.asm.wb).apply(null,arguments)},Et=a.dynCall_iiiiiij=function(){return(Et=a.dynCall_iiiiiij=a.asm.xb).apply(null,arguments)},Pt=a.dynCall_iiij=function(){return(Pt=a.dynCall_iiij=a.asm.yb).apply(null,arguments)};function At(){function M(){if(!Je&&(Je=!0,a.calledRun=!0,!C)){if(Ye(le),h(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;){var F=a.postRun.shift();be.unshift(F)}Ye(be)}}if(!(0<$e)){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)Le();Ye(xe),0<$e||(a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),M()},1)):M())}}if(a.UTF8ToString=G,a.stringToUTF8=function(M,F,R){return ee(M,N,F,R)},a.lengthBytesUTF8=J,a.stackSave=ie,a.stackRestore=se,a.stackAlloc=mt,Fe=function M(){Je||At(),Je||(Fe=M)},a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);0{p.exports=function(t,o){for(var i=new Array(arguments.length-1),u=0,d=2,a=!0;d{var o=t;o.length=function(h){var m=h.length;if(!m)return 0;for(var c=0;--m%4>1&&h.charAt(m)==="=";)++c;return Math.ceil(3*h.length)/4-c};for(var i=new Array(64),u=new Array(123),d=0;d<64;)u[i[d]=d<26?d+65:d<52?d+71:d<62?d-4:d-59|43]=d++;o.encode=function(h,m,c){for(var l,n=null,e=[],r=0,s=0;m>2],l=(3&f)<<4,s=1;break;case 1:e[r++]=i[l|f>>4],l=(15&f)<<2,s=2;break;case 2:e[r++]=i[l|f>>6],e[r++]=i[63&f],s=0}r>8191&&((n||(n=[])).push(String.fromCharCode.apply(String,e)),r=0)}return s&&(e[r++]=i[l],e[r++]=61,s===1&&(e[r++]=61)),n?(r&&n.push(String.fromCharCode.apply(String,e.slice(0,r))),n.join("")):String.fromCharCode.apply(String,e.slice(0,r))};var a="invalid encoding";o.decode=function(h,m,c){for(var l,n=c,e=0,r=0;r1)break;if((s=u[s])===void 0)throw Error(a);switch(e){case 0:l=s,e=1;break;case 1:m[c++]=l<<2|(48&s)>>4,l=s,e=2;break;case 2:m[c++]=(15&l)<<4|(60&s)>>2,l=s,e=3;break;case 3:m[c++]=(3&l)<<6|s,e=0}}if(e===1)throw Error(a);return c-n},o.test=function(h){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(h)}},9211:p=>{function t(){this._listeners={}}p.exports=t,t.prototype.on=function(o,i,u){return(this._listeners[o]||(this._listeners[o]=[])).push({fn:i,ctx:u||this}),this},t.prototype.off=function(o,i){if(o===void 0)this._listeners={};else if(i===void 0)this._listeners[o]=[];else for(var u=this._listeners[o],d=0;d{function t(a){return typeof Float32Array<"u"?function(){var h=new Float32Array([-0]),m=new Uint8Array(h.buffer),c=m[3]===128;function l(s,f,g){h[0]=s,f[g]=m[0],f[g+1]=m[1],f[g+2]=m[2],f[g+3]=m[3]}function n(s,f,g){h[0]=s,f[g]=m[3],f[g+1]=m[2],f[g+2]=m[1],f[g+3]=m[0]}function e(s,f){return m[0]=s[f],m[1]=s[f+1],m[2]=s[f+2],m[3]=s[f+3],h[0]}function r(s,f){return m[3]=s[f],m[2]=s[f+1],m[1]=s[f+2],m[0]=s[f+3],h[0]}a.writeFloatLE=c?l:n,a.writeFloatBE=c?n:l,a.readFloatLE=c?e:r,a.readFloatBE=c?r:e}():function(){function h(c,l,n,e){var r=l<0?1:0;if(r&&(l=-l),l===0)c(1/l>0?0:2147483648,n,e);else if(isNaN(l))c(2143289344,n,e);else if(l>34028234663852886e22)c((r<<31|2139095040)>>>0,n,e);else if(l<11754943508222875e-54)c((r<<31|Math.round(l/1401298464324817e-60))>>>0,n,e);else{var s=Math.floor(Math.log(l)/Math.LN2);c((r<<31|s+127<<23|8388607&Math.round(l*Math.pow(2,-s)*8388608))>>>0,n,e)}}function m(c,l,n){var e=c(l,n),r=2*(e>>31)+1,s=e>>>23&255,f=8388607&e;return s===255?f?NaN:r*(1/0):s===0?1401298464324817e-60*r*f:r*Math.pow(2,s-150)*(f+8388608)}a.writeFloatLE=h.bind(null,o),a.writeFloatBE=h.bind(null,i),a.readFloatLE=m.bind(null,u),a.readFloatBE=m.bind(null,d)}(),typeof Float64Array<"u"?function(){var h=new Float64Array([-0]),m=new Uint8Array(h.buffer),c=m[7]===128;function l(s,f,g){h[0]=s,f[g]=m[0],f[g+1]=m[1],f[g+2]=m[2],f[g+3]=m[3],f[g+4]=m[4],f[g+5]=m[5],f[g+6]=m[6],f[g+7]=m[7]}function n(s,f,g){h[0]=s,f[g]=m[7],f[g+1]=m[6],f[g+2]=m[5],f[g+3]=m[4],f[g+4]=m[3],f[g+5]=m[2],f[g+6]=m[1],f[g+7]=m[0]}function e(s,f){return m[0]=s[f],m[1]=s[f+1],m[2]=s[f+2],m[3]=s[f+3],m[4]=s[f+4],m[5]=s[f+5],m[6]=s[f+6],m[7]=s[f+7],h[0]}function r(s,f){return m[7]=s[f],m[6]=s[f+1],m[5]=s[f+2],m[4]=s[f+3],m[3]=s[f+4],m[2]=s[f+5],m[1]=s[f+6],m[0]=s[f+7],h[0]}a.writeDoubleLE=c?l:n,a.writeDoubleBE=c?n:l,a.readDoubleLE=c?e:r,a.readDoubleBE=c?r:e}():function(){function h(c,l,n,e,r,s){var f=e<0?1:0;if(f&&(e=-e),e===0)c(0,r,s+l),c(1/e>0?0:2147483648,r,s+n);else if(isNaN(e))c(0,r,s+l),c(2146959360,r,s+n);else if(e>17976931348623157e292)c(0,r,s+l),c((f<<31|2146435072)>>>0,r,s+n);else{var g;if(e<22250738585072014e-324)c((g=e/5e-324)>>>0,r,s+l),c((f<<31|g/4294967296)>>>0,r,s+n);else{var _=Math.floor(Math.log(e)/Math.LN2);_===1024&&(_=1023),c(4503599627370496*(g=e*Math.pow(2,-_))>>>0,r,s+l),c((f<<31|_+1023<<20|1048576*g&1048575)>>>0,r,s+n)}}}function m(c,l,n,e,r){var s=c(e,r+l),f=c(e,r+n),g=2*(f>>31)+1,_=f>>>20&2047,b=4294967296*(1048575&f)+s;return _===2047?b?NaN:g*(1/0):_===0?5e-324*g*b:g*Math.pow(2,_-1075)*(b+4503599627370496)}a.writeDoubleLE=h.bind(null,o,0,4),a.writeDoubleBE=h.bind(null,i,4,0),a.readDoubleLE=m.bind(null,u,0,4),a.readDoubleBE=m.bind(null,d,4,0)}(),a}function o(a,h,m){h[m]=255&a,h[m+1]=a>>>8&255,h[m+2]=a>>>16&255,h[m+3]=a>>>24}function i(a,h,m){h[m]=a>>>24,h[m+1]=a>>>16&255,h[m+2]=a>>>8&255,h[m+3]=255&a}function u(a,h){return(a[h]|a[h+1]<<8|a[h+2]<<16|a[h+3]<<24)>>>0}function d(a,h){return(a[h]<<24|a[h+1]<<16|a[h+2]<<8|a[h+3])>>>0}p.exports=t(t)},7199:module=>{function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(p){}return null}module.exports=inquire},6662:p=>{p.exports=function(t,o,i){var u=i||8192,d=u>>>1,a=null,h=u;return function(m){if(m<1||m>d)return t(m);h+m>u&&(a=t(u),h=0);var c=o.call(a,h,h+=m);return 7&h&&(h=1+(7|h)),c}}},4997:(p,t)=>{var o=t;o.length=function(i){for(var u=0,d=0,a=0;a191&&a<224?m[c++]=(31&a)<<6|63&i[u++]:a>239&&a<365?(a=((7&a)<<18|(63&i[u++])<<12|(63&i[u++])<<6|63&i[u++])-65536,m[c++]=55296+(a>>10),m[c++]=56320+(1023&a)):m[c++]=(15&a)<<12|(63&i[u++])<<6|63&i[u++],c>8191&&((h||(h=[])).push(String.fromCharCode.apply(String,m)),c=0);return h?(c&&h.push(String.fromCharCode.apply(String,m.slice(0,c))),h.join("")):String.fromCharCode.apply(String,m.slice(0,c))},o.write=function(i,u,d){for(var a,h,m=d,c=0;c>6|192,u[d++]=63&a|128):(64512&a)==55296&&(64512&(h=i.charCodeAt(c+1)))==56320?(a=65536+((1023&a)<<10)+(1023&h),++c,u[d++]=a>>18|240,u[d++]=a>>12&63|128,u[d++]=a>>6&63|128,u[d++]=63&a|128):(u[d++]=a>>12|224,u[d++]=a>>6&63|128,u[d++]=63&a|128);return d-m}},3442:(p,t)=>{t.__esModule=!0;var o=function(){function i(u){if(!u)throw new TypeError("Invalid argument; `value` has no value.");this.value=i.EMPTY,u&&i.isGuid(u)&&(this.value=u)}return i.isGuid=function(u){var d=u.toString();return u&&(u instanceof i||i.validator.test(d))},i.create=function(){return new i([i.gen(2),i.gen(1),i.gen(1),i.gen(1),i.gen(3)].join("-"))},i.createEmpty=function(){return new i("emptyguid")},i.parse=function(u){return new i(u)},i.raw=function(){return[i.gen(2),i.gen(1),i.gen(1),i.gen(1),i.gen(3)].join("-")},i.gen=function(u){for(var d="",a=0;a{p.exports=o;var t=null;try{t=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{}function o(x,O,$){this.low=0|x,this.high=0|O,this.unsigned=!!$}function i(x){return(x&&x.__isLong__)===!0}o.prototype.__isLong__,Object.defineProperty(o.prototype,"__isLong__",{value:!0}),o.isLong=i;var u={},d={};function a(x,O){var $,k,N;return O?(N=0<=(x>>>=0)&&x<256)&&(k=d[x])?k:($=m(x,(0|x)<0?-1:0,!0),N&&(d[x]=$),$):(N=-128<=(x|=0)&&x<128)&&(k=u[x])?k:($=m(x,x<0?-1:0,!1),N&&(u[x]=$),$)}function h(x,O){if(isNaN(x))return O?_:g;if(O){if(x<0)return _;if(x>=r)return v}else{if(x<=-s)return E;if(x+1>=s)return w}return x<0?h(-x,O).neg():m(x%e|0,x/e|0,O)}function m(x,O,$){return new o(x,O,$)}o.fromInt=a,o.fromNumber=h,o.fromBits=m;var c=Math.pow;function l(x,O,$){if(x.length===0)throw Error("empty string");if(x==="NaN"||x==="Infinity"||x==="+Infinity"||x==="-Infinity")return g;if(typeof O=="number"?($=O,O=!1):O=!!O,($=$||10)<2||36<$)throw RangeError("radix");var k;if((k=x.indexOf("-"))>0)throw Error("interior hyphen");if(k===0)return l(x.substring(1),O,$).neg();for(var N=h(c($,8)),D=g,V=0;V>>0:this.low},P.toNumber=function(){return this.unsigned?(this.high>>>0)*e+(this.low>>>0):this.high*e+(this.low>>>0)},P.toString=function(x){if((x=x||10)<2||36>>0).toString(x);if((D=C).isZero())return B+V;for(;B.length<6;)B="0"+B;V=""+B+V}},P.getHighBits=function(){return this.high},P.getHighBitsUnsigned=function(){return this.high>>>0},P.getLowBits=function(){return this.low},P.getLowBitsUnsigned=function(){return this.low>>>0},P.getNumBitsAbs=function(){if(this.isNegative())return this.eq(E)?64:this.neg().getNumBitsAbs();for(var x=this.high!=0?this.high:this.low,O=31;O>0&&!(x&1<=0},P.isOdd=function(){return(1&this.low)==1},P.isEven=function(){return(1&this.low)==0},P.equals=function(x){return i(x)||(x=n(x)),(this.unsigned===x.unsigned||this.high>>>31!=1||x.high>>>31!=1)&&this.high===x.high&&this.low===x.low},P.eq=P.equals,P.notEquals=function(x){return!this.eq(x)},P.neq=P.notEquals,P.ne=P.notEquals,P.lessThan=function(x){return this.comp(x)<0},P.lt=P.lessThan,P.lessThanOrEqual=function(x){return this.comp(x)<=0},P.lte=P.lessThanOrEqual,P.le=P.lessThanOrEqual,P.greaterThan=function(x){return this.comp(x)>0},P.gt=P.greaterThan,P.greaterThanOrEqual=function(x){return this.comp(x)>=0},P.gte=P.greaterThanOrEqual,P.ge=P.greaterThanOrEqual,P.compare=function(x){if(i(x)||(x=n(x)),this.eq(x))return 0;var O=this.isNegative(),$=x.isNegative();return O&&!$?-1:!O&&$?1:this.unsigned?x.high>>>0>this.high>>>0||x.high===this.high&&x.low>>>0>this.low>>>0?-1:1:this.sub(x).isNegative()?-1:1},P.comp=P.compare,P.negate=function(){return!this.unsigned&&this.eq(E)?E:this.not().add(b)},P.neg=P.negate,P.add=function(x){i(x)||(x=n(x));var O=this.high>>>16,$=65535&this.high,k=this.low>>>16,N=65535&this.low,D=x.high>>>16,V=65535&x.high,C=x.low>>>16,B=0,X=0,G=0,ee=0;return G+=(ee+=N+(65535&x.low))>>>16,X+=(G+=k+C)>>>16,B+=(X+=$+V)>>>16,B+=O+D,m((G&=65535)<<16|(ee&=65535),(B&=65535)<<16|(X&=65535),this.unsigned)},P.subtract=function(x){return i(x)||(x=n(x)),this.add(x.neg())},P.sub=P.subtract,P.multiply=function(x){if(this.isZero())return g;if(i(x)||(x=n(x)),t)return m(t.mul(this.low,this.high,x.low,x.high),t.get_high(),this.unsigned);if(x.isZero())return g;if(this.eq(E))return x.isOdd()?E:g;if(x.eq(E))return this.isOdd()?E:g;if(this.isNegative())return x.isNegative()?this.neg().mul(x.neg()):this.neg().mul(x).neg();if(x.isNegative())return this.mul(x.neg()).neg();if(this.lt(f)&&x.lt(f))return h(this.toNumber()*x.toNumber(),this.unsigned);var O=this.high>>>16,$=65535&this.high,k=this.low>>>16,N=65535&this.low,D=x.high>>>16,V=65535&x.high,C=x.low>>>16,B=65535&x.low,X=0,G=0,ee=0,J=0;return ee+=(J+=N*B)>>>16,G+=(ee+=k*B)>>>16,ee&=65535,G+=(ee+=N*C)>>>16,X+=(G+=$*B)>>>16,G&=65535,X+=(G+=k*C)>>>16,G&=65535,X+=(G+=N*V)>>>16,X+=O*B+$*C+k*V+N*D,m((ee&=65535)<<16|(J&=65535),(X&=65535)<<16|(G&=65535),this.unsigned)},P.mul=P.multiply,P.divide=function(x){if(i(x)||(x=n(x)),x.isZero())throw Error("division by zero");var O,$,k;if(t)return this.unsigned||this.high!==-2147483648||x.low!==-1||x.high!==-1?m((this.unsigned?t.div_u:t.div_s)(this.low,this.high,x.low,x.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?_:g;if(this.unsigned){if(x.unsigned||(x=x.toUnsigned()),x.gt(this))return _;if(x.gt(this.shru(1)))return y;k=_}else{if(this.eq(E))return x.eq(b)||x.eq(T)?E:x.eq(E)?b:(O=this.shr(1).div(x).shl(1)).eq(g)?x.isNegative()?b:T:($=this.sub(x.mul(O)),k=O.add($.div(x)));if(x.eq(E))return this.unsigned?_:g;if(this.isNegative())return x.isNegative()?this.neg().div(x.neg()):this.neg().div(x).neg();if(x.isNegative())return this.div(x.neg()).neg();k=g}for($=this;$.gte(x);){O=Math.max(1,Math.floor($.toNumber()/x.toNumber()));for(var N=Math.ceil(Math.log(O)/Math.LN2),D=N<=48?1:c(2,N-48),V=h(O),C=V.mul(x);C.isNegative()||C.gt($);)C=(V=h(O-=D,this.unsigned)).mul(x);V.isZero()&&(V=b),k=k.add(V),$=$.sub(C)}return k},P.div=P.divide,P.modulo=function(x){return i(x)||(x=n(x)),t?m((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,x.low,x.high),t.get_high(),this.unsigned):this.sub(this.div(x).mul(x))},P.mod=P.modulo,P.rem=P.modulo,P.not=function(){return m(~this.low,~this.high,this.unsigned)},P.and=function(x){return i(x)||(x=n(x)),m(this.low&x.low,this.high&x.high,this.unsigned)},P.or=function(x){return i(x)||(x=n(x)),m(this.low|x.low,this.high|x.high,this.unsigned)},P.xor=function(x){return i(x)||(x=n(x)),m(this.low^x.low,this.high^x.high,this.unsigned)},P.shiftLeft=function(x){return i(x)&&(x=x.toInt()),(x&=63)==0?this:x<32?m(this.low<>>32-x,this.unsigned):m(0,this.low<>>x|this.high<<32-x,this.high>>x,this.unsigned):m(this.high>>x-32,this.high>=0?0:-1,this.unsigned)},P.shr=P.shiftRight,P.shiftRightUnsigned=function(x){if(i(x)&&(x=x.toInt()),(x&=63)==0)return this;var O=this.high;return x<32?m(this.low>>>x|O<<32-x,O>>>x,this.unsigned):m(x===32?O:O>>>x-32,0,this.unsigned)},P.shru=P.shiftRightUnsigned,P.shr_u=P.shiftRightUnsigned,P.toSigned=function(){return this.unsigned?m(this.low,this.high,!1):this},P.toUnsigned=function(){return this.unsigned?this:m(this.low,this.high,!0)},P.toBytes=function(x){return x?this.toBytesLE():this.toBytesBE()},P.toBytesLE=function(){var x=this.high,O=this.low;return[255&O,O>>>8&255,O>>>16&255,O>>>24,255&x,x>>>8&255,x>>>16&255,x>>>24]},P.toBytesBE=function(){var x=this.high,O=this.low;return[x>>>24,x>>>16&255,x>>>8&255,255&x,O>>>24,O>>>16&255,O>>>8&255,255&O]},o.fromBytes=function(x,O,$){return $?o.fromBytesLE(x,O):o.fromBytesBE(x,O)},o.fromBytesLE=function(x,O){return new o(x[0]|x[1]<<8|x[2]<<16|x[3]<<24,x[4]|x[5]<<8|x[6]<<16|x[7]<<24,O)},o.fromBytesBE=function(x,O){return new o(x[4]<<24|x[5]<<16|x[6]<<8|x[7],x[0]<<24|x[1]<<16|x[2]<<8|x[3],O)}},1446:(p,t,o)=>{var i,u,d,a=o(2100),h=a.Reader,m=a.Writer,c=a.util,l=a.roots.default||(a.roots.default={});l.onnx=((d={}).Version=(i={},(u=Object.create(i))[i[0]="_START_VERSION"]=0,u[i[1]="IR_VERSION_2017_10_10"]=1,u[i[2]="IR_VERSION_2017_10_30"]=2,u[i[3]="IR_VERSION_2017_11_3"]=3,u[i[4]="IR_VERSION_2019_1_22"]=4,u[i[5]="IR_VERSION"]=5,u),d.AttributeProto=function(){function n(e){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],e)for(var r=Object.keys(e),s=0;s>>3){case 1:f.name=e.string();break;case 21:f.refAttrName=e.string();break;case 13:f.docString=e.string();break;case 20:f.type=e.int32();break;case 2:f.f=e.float();break;case 3:f.i=e.int64();break;case 4:f.s=e.bytes();break;case 5:f.t=l.onnx.TensorProto.decode(e,e.uint32());break;case 6:f.g=l.onnx.GraphProto.decode(e,e.uint32());break;case 7:if(f.floats&&f.floats.length||(f.floats=[]),(7&g)==2)for(var _=e.uint32()+e.pos;e.pos<_;)f.floats.push(e.float());else f.floats.push(e.float());break;case 8:if(f.ints&&f.ints.length||(f.ints=[]),(7&g)==2)for(_=e.uint32()+e.pos;e.pos<_;)f.ints.push(e.int64());else f.ints.push(e.int64());break;case 9:f.strings&&f.strings.length||(f.strings=[]),f.strings.push(e.bytes());break;case 10:f.tensors&&f.tensors.length||(f.tensors=[]),f.tensors.push(l.onnx.TensorProto.decode(e,e.uint32()));break;case 11:f.graphs&&f.graphs.length||(f.graphs=[]),f.graphs.push(l.onnx.GraphProto.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return f},n.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.name!=null&&e.hasOwnProperty("name")&&!c.isString(e.name))return"name: string expected";if(e.refAttrName!=null&&e.hasOwnProperty("refAttrName")&&!c.isString(e.refAttrName))return"refAttrName: string expected";if(e.docString!=null&&e.hasOwnProperty("docString")&&!c.isString(e.docString))return"docString: string expected";if(e.type!=null&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:}if(e.f!=null&&e.hasOwnProperty("f")&&typeof e.f!="number")return"f: number expected";if(e.i!=null&&e.hasOwnProperty("i")&&!(c.isInteger(e.i)||e.i&&c.isInteger(e.i.low)&&c.isInteger(e.i.high)))return"i: integer|Long expected";if(e.s!=null&&e.hasOwnProperty("s")&&!(e.s&&typeof e.s.length=="number"||c.isString(e.s)))return"s: buffer expected";if(e.t!=null&&e.hasOwnProperty("t")&&(s=l.onnx.TensorProto.verify(e.t)))return"t."+s;if(e.g!=null&&e.hasOwnProperty("g")&&(s=l.onnx.GraphProto.verify(e.g)))return"g."+s;if(e.floats!=null&&e.hasOwnProperty("floats")){if(!Array.isArray(e.floats))return"floats: array expected";for(var r=0;r>>0,e.i.high>>>0).toNumber())),e.s!=null&&(typeof e.s=="string"?c.base64.decode(e.s,r.s=c.newBuffer(c.base64.length(e.s)),0):e.s.length&&(r.s=e.s)),e.t!=null){if(typeof e.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");r.t=l.onnx.TensorProto.fromObject(e.t)}if(e.g!=null){if(typeof e.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");r.g=l.onnx.GraphProto.fromObject(e.g)}if(e.floats){if(!Array.isArray(e.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");r.floats=[];for(var s=0;s>>0,e.ints[s].high>>>0).toNumber())}if(e.strings){if(!Array.isArray(e.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(r.strings=[],s=0;s>>0,e.i.high>>>0).toNumber():e.i),e.s!=null&&e.hasOwnProperty("s")&&(s.s=r.bytes===String?c.base64.encode(e.s,0,e.s.length):r.bytes===Array?Array.prototype.slice.call(e.s):e.s),e.t!=null&&e.hasOwnProperty("t")&&(s.t=l.onnx.TensorProto.toObject(e.t,r)),e.g!=null&&e.hasOwnProperty("g")&&(s.g=l.onnx.GraphProto.toObject(e.g,r)),e.floats&&e.floats.length){s.floats=[];for(var g=0;g>>0,e.ints[g].high>>>0).toNumber():e.ints[g];if(e.strings&&e.strings.length)for(s.strings=[],g=0;g>>3){case 1:f.name=e.string();break;case 2:f.type=l.onnx.TypeProto.decode(e,e.uint32());break;case 3:f.docString=e.string();break;default:e.skipType(7&g)}}return f},n.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.name!=null&&e.hasOwnProperty("name")&&!c.isString(e.name))return"name: string expected";if(e.type!=null&&e.hasOwnProperty("type")){var r=l.onnx.TypeProto.verify(e.type);if(r)return"type."+r}return e.docString!=null&&e.hasOwnProperty("docString")&&!c.isString(e.docString)?"docString: string expected":null},n.fromObject=function(e){if(e instanceof l.onnx.ValueInfoProto)return e;var r=new l.onnx.ValueInfoProto;if(e.name!=null&&(r.name=String(e.name)),e.type!=null){if(typeof e.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");r.type=l.onnx.TypeProto.fromObject(e.type)}return e.docString!=null&&(r.docString=String(e.docString)),r},n.toObject=function(e,r){r||(r={});var s={};return r.defaults&&(s.name="",s.type=null,s.docString=""),e.name!=null&&e.hasOwnProperty("name")&&(s.name=e.name),e.type!=null&&e.hasOwnProperty("type")&&(s.type=l.onnx.TypeProto.toObject(e.type,r)),e.docString!=null&&e.hasOwnProperty("docString")&&(s.docString=e.docString),s},n.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},n}(),d.NodeProto=function(){function n(e){if(this.input=[],this.output=[],this.attribute=[],e)for(var r=Object.keys(e),s=0;s>>3){case 1:f.input&&f.input.length||(f.input=[]),f.input.push(e.string());break;case 2:f.output&&f.output.length||(f.output=[]),f.output.push(e.string());break;case 3:f.name=e.string();break;case 4:f.opType=e.string();break;case 7:f.domain=e.string();break;case 5:f.attribute&&f.attribute.length||(f.attribute=[]),f.attribute.push(l.onnx.AttributeProto.decode(e,e.uint32()));break;case 6:f.docString=e.string();break;default:e.skipType(7&g)}}return f},n.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.input!=null&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(var r=0;r>>3){case 1:f.irVersion=e.int64();break;case 8:f.opsetImport&&f.opsetImport.length||(f.opsetImport=[]),f.opsetImport.push(l.onnx.OperatorSetIdProto.decode(e,e.uint32()));break;case 2:f.producerName=e.string();break;case 3:f.producerVersion=e.string();break;case 4:f.domain=e.string();break;case 5:f.modelVersion=e.int64();break;case 6:f.docString=e.string();break;case 7:f.graph=l.onnx.GraphProto.decode(e,e.uint32());break;case 14:f.metadataProps&&f.metadataProps.length||(f.metadataProps=[]),f.metadataProps.push(l.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return f},n.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.irVersion!=null&&e.hasOwnProperty("irVersion")&&!(c.isInteger(e.irVersion)||e.irVersion&&c.isInteger(e.irVersion.low)&&c.isInteger(e.irVersion.high)))return"irVersion: integer|Long expected";if(e.opsetImport!=null&&e.hasOwnProperty("opsetImport")){if(!Array.isArray(e.opsetImport))return"opsetImport: array expected";for(var r=0;r>>0,e.irVersion.high>>>0).toNumber())),e.opsetImport){if(!Array.isArray(e.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");r.opsetImport=[];for(var s=0;s>>0,e.modelVersion.high>>>0).toNumber())),e.docString!=null&&(r.docString=String(e.docString)),e.graph!=null){if(typeof e.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");r.graph=l.onnx.GraphProto.fromObject(e.graph)}if(e.metadataProps){if(!Array.isArray(e.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(r.metadataProps=[],s=0;s>>0,e.irVersion.high>>>0).toNumber():e.irVersion),e.producerName!=null&&e.hasOwnProperty("producerName")&&(s.producerName=e.producerName),e.producerVersion!=null&&e.hasOwnProperty("producerVersion")&&(s.producerVersion=e.producerVersion),e.domain!=null&&e.hasOwnProperty("domain")&&(s.domain=e.domain),e.modelVersion!=null&&e.hasOwnProperty("modelVersion")&&(typeof e.modelVersion=="number"?s.modelVersion=r.longs===String?String(e.modelVersion):e.modelVersion:s.modelVersion=r.longs===String?c.Long.prototype.toString.call(e.modelVersion):r.longs===Number?new c.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber():e.modelVersion),e.docString!=null&&e.hasOwnProperty("docString")&&(s.docString=e.docString),e.graph!=null&&e.hasOwnProperty("graph")&&(s.graph=l.onnx.GraphProto.toObject(e.graph,r)),e.opsetImport&&e.opsetImport.length){s.opsetImport=[];for(var g=0;g>>3){case 1:f.key=e.string();break;case 2:f.value=e.string();break;default:e.skipType(7&g)}}return f},n.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},n.verify=function(e){return typeof e!="object"||e===null?"object expected":e.key!=null&&e.hasOwnProperty("key")&&!c.isString(e.key)?"key: string expected":e.value!=null&&e.hasOwnProperty("value")&&!c.isString(e.value)?"value: string expected":null},n.fromObject=function(e){if(e instanceof l.onnx.StringStringEntryProto)return e;var r=new l.onnx.StringStringEntryProto;return e.key!=null&&(r.key=String(e.key)),e.value!=null&&(r.value=String(e.value)),r},n.toObject=function(e,r){r||(r={});var s={};return r.defaults&&(s.key="",s.value=""),e.key!=null&&e.hasOwnProperty("key")&&(s.key=e.key),e.value!=null&&e.hasOwnProperty("value")&&(s.value=e.value),s},n.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},n}(),d.TensorAnnotation=function(){function n(e){if(this.quantParameterTensorNames=[],e)for(var r=Object.keys(e),s=0;s>>3){case 1:f.tensorName=e.string();break;case 2:f.quantParameterTensorNames&&f.quantParameterTensorNames.length||(f.quantParameterTensorNames=[]),f.quantParameterTensorNames.push(l.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return f},n.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.tensorName!=null&&e.hasOwnProperty("tensorName")&&!c.isString(e.tensorName))return"tensorName: string expected";if(e.quantParameterTensorNames!=null&&e.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(e.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var r=0;r>>3){case 1:f.node&&f.node.length||(f.node=[]),f.node.push(l.onnx.NodeProto.decode(e,e.uint32()));break;case 2:f.name=e.string();break;case 5:f.initializer&&f.initializer.length||(f.initializer=[]),f.initializer.push(l.onnx.TensorProto.decode(e,e.uint32()));break;case 10:f.docString=e.string();break;case 11:f.input&&f.input.length||(f.input=[]),f.input.push(l.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 12:f.output&&f.output.length||(f.output=[]),f.output.push(l.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 13:f.valueInfo&&f.valueInfo.length||(f.valueInfo=[]),f.valueInfo.push(l.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 14:f.quantizationAnnotation&&f.quantizationAnnotation.length||(f.quantizationAnnotation=[]),f.quantizationAnnotation.push(l.onnx.TensorAnnotation.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return f},n.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.node!=null&&e.hasOwnProperty("node")){if(!Array.isArray(e.node))return"node: array expected";for(var r=0;r>>3){case 1:if(f.dims&&f.dims.length||(f.dims=[]),(7&g)==2)for(var _=e.uint32()+e.pos;e.pos<_;)f.dims.push(e.int64());else f.dims.push(e.int64());break;case 2:f.dataType=e.int32();break;case 3:f.segment=l.onnx.TensorProto.Segment.decode(e,e.uint32());break;case 4:if(f.floatData&&f.floatData.length||(f.floatData=[]),(7&g)==2)for(_=e.uint32()+e.pos;e.pos<_;)f.floatData.push(e.float());else f.floatData.push(e.float());break;case 5:if(f.int32Data&&f.int32Data.length||(f.int32Data=[]),(7&g)==2)for(_=e.uint32()+e.pos;e.pos<_;)f.int32Data.push(e.int32());else f.int32Data.push(e.int32());break;case 6:f.stringData&&f.stringData.length||(f.stringData=[]),f.stringData.push(e.bytes());break;case 7:if(f.int64Data&&f.int64Data.length||(f.int64Data=[]),(7&g)==2)for(_=e.uint32()+e.pos;e.pos<_;)f.int64Data.push(e.int64());else f.int64Data.push(e.int64());break;case 8:f.name=e.string();break;case 12:f.docString=e.string();break;case 9:f.rawData=e.bytes();break;case 13:f.externalData&&f.externalData.length||(f.externalData=[]),f.externalData.push(l.onnx.StringStringEntryProto.decode(e,e.uint32()));break;case 14:f.dataLocation=e.int32();break;case 10:if(f.doubleData&&f.doubleData.length||(f.doubleData=[]),(7&g)==2)for(_=e.uint32()+e.pos;e.pos<_;)f.doubleData.push(e.double());else f.doubleData.push(e.double());break;case 11:if(f.uint64Data&&f.uint64Data.length||(f.uint64Data=[]),(7&g)==2)for(_=e.uint32()+e.pos;e.pos<_;)f.uint64Data.push(e.uint64());else f.uint64Data.push(e.uint64());break;default:e.skipType(7&g)}}return f},n.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.dims!=null&&e.hasOwnProperty("dims")){if(!Array.isArray(e.dims))return"dims: array expected";for(var r=0;r>>0,e.dims[s].high>>>0).toNumber())}if(e.dataType!=null&&(r.dataType=0|e.dataType),e.segment!=null){if(typeof e.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");r.segment=l.onnx.TensorProto.Segment.fromObject(e.segment)}if(e.floatData){if(!Array.isArray(e.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(r.floatData=[],s=0;s>>0,e.int64Data[s].high>>>0).toNumber())}if(e.name!=null&&(r.name=String(e.name)),e.docString!=null&&(r.docString=String(e.docString)),e.rawData!=null&&(typeof e.rawData=="string"?c.base64.decode(e.rawData,r.rawData=c.newBuffer(c.base64.length(e.rawData)),0):e.rawData.length&&(r.rawData=e.rawData)),e.externalData){if(!Array.isArray(e.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(r.externalData=[],s=0;s>>0,e.uint64Data[s].high>>>0).toNumber(!0))}return r},n.toObject=function(e,r){r||(r={});var s={};if((r.arrays||r.defaults)&&(s.dims=[],s.floatData=[],s.int32Data=[],s.stringData=[],s.int64Data=[],s.doubleData=[],s.uint64Data=[],s.externalData=[]),r.defaults&&(s.dataType=0,s.segment=null,s.name="",r.bytes===String?s.rawData="":(s.rawData=[],r.bytes!==Array&&(s.rawData=c.newBuffer(s.rawData))),s.docString="",s.dataLocation=r.enums===String?"DEFAULT":0),e.dims&&e.dims.length){s.dims=[];for(var f=0;f>>0,e.dims[f].high>>>0).toNumber():e.dims[f]}if(e.dataType!=null&&e.hasOwnProperty("dataType")&&(s.dataType=e.dataType),e.segment!=null&&e.hasOwnProperty("segment")&&(s.segment=l.onnx.TensorProto.Segment.toObject(e.segment,r)),e.floatData&&e.floatData.length)for(s.floatData=[],f=0;f>>0,e.int64Data[f].high>>>0).toNumber():e.int64Data[f];if(e.name!=null&&e.hasOwnProperty("name")&&(s.name=e.name),e.rawData!=null&&e.hasOwnProperty("rawData")&&(s.rawData=r.bytes===String?c.base64.encode(e.rawData,0,e.rawData.length):r.bytes===Array?Array.prototype.slice.call(e.rawData):e.rawData),e.doubleData&&e.doubleData.length)for(s.doubleData=[],f=0;f>>0,e.uint64Data[f].high>>>0).toNumber(!0):e.uint64Data[f];if(e.docString!=null&&e.hasOwnProperty("docString")&&(s.docString=e.docString),e.externalData&&e.externalData.length)for(s.externalData=[],f=0;f>>3){case 1:g.begin=r.int64();break;case 2:g.end=r.int64();break;default:r.skipType(7&_)}}return g},e.decodeDelimited=function(r){return r instanceof h||(r=new h(r)),this.decode(r,r.uint32())},e.verify=function(r){return typeof r!="object"||r===null?"object expected":r.begin!=null&&r.hasOwnProperty("begin")&&!(c.isInteger(r.begin)||r.begin&&c.isInteger(r.begin.low)&&c.isInteger(r.begin.high))?"begin: integer|Long expected":r.end!=null&&r.hasOwnProperty("end")&&!(c.isInteger(r.end)||r.end&&c.isInteger(r.end.low)&&c.isInteger(r.end.high))?"end: integer|Long expected":null},e.fromObject=function(r){if(r instanceof l.onnx.TensorProto.Segment)return r;var s=new l.onnx.TensorProto.Segment;return r.begin!=null&&(c.Long?(s.begin=c.Long.fromValue(r.begin)).unsigned=!1:typeof r.begin=="string"?s.begin=parseInt(r.begin,10):typeof r.begin=="number"?s.begin=r.begin:typeof r.begin=="object"&&(s.begin=new c.LongBits(r.begin.low>>>0,r.begin.high>>>0).toNumber())),r.end!=null&&(c.Long?(s.end=c.Long.fromValue(r.end)).unsigned=!1:typeof r.end=="string"?s.end=parseInt(r.end,10):typeof r.end=="number"?s.end=r.end:typeof r.end=="object"&&(s.end=new c.LongBits(r.end.low>>>0,r.end.high>>>0).toNumber())),s},e.toObject=function(r,s){s||(s={});var f={};if(s.defaults){if(c.Long){var g=new c.Long(0,0,!1);f.begin=s.longs===String?g.toString():s.longs===Number?g.toNumber():g}else f.begin=s.longs===String?"0":0;c.Long?(g=new c.Long(0,0,!1),f.end=s.longs===String?g.toString():s.longs===Number?g.toNumber():g):f.end=s.longs===String?"0":0}return r.begin!=null&&r.hasOwnProperty("begin")&&(typeof r.begin=="number"?f.begin=s.longs===String?String(r.begin):r.begin:f.begin=s.longs===String?c.Long.prototype.toString.call(r.begin):s.longs===Number?new c.LongBits(r.begin.low>>>0,r.begin.high>>>0).toNumber():r.begin),r.end!=null&&r.hasOwnProperty("end")&&(typeof r.end=="number"?f.end=s.longs===String?String(r.end):r.end:f.end=s.longs===String?c.Long.prototype.toString.call(r.end):s.longs===Number?new c.LongBits(r.end.low>>>0,r.end.high>>>0).toNumber():r.end),f},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e}(),n.DataLocation=function(){var e={},r=Object.create(e);return r[e[0]="DEFAULT"]=0,r[e[1]="EXTERNAL"]=1,r}(),n}(),d.TensorShapeProto=function(){function n(e){if(this.dim=[],e)for(var r=Object.keys(e),s=0;s>>3==1?(f.dim&&f.dim.length||(f.dim=[]),f.dim.push(l.onnx.TensorShapeProto.Dimension.decode(e,e.uint32()))):e.skipType(7&g)}return f},n.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.dim!=null&&e.hasOwnProperty("dim")){if(!Array.isArray(e.dim))return"dim: array expected";for(var r=0;r>>3){case 1:_.dimValue=s.int64();break;case 2:_.dimParam=s.string();break;case 3:_.denotation=s.string();break;default:s.skipType(7&b)}}return _},e.decodeDelimited=function(s){return s instanceof h||(s=new h(s)),this.decode(s,s.uint32())},e.verify=function(s){if(typeof s!="object"||s===null)return"object expected";var f={};if(s.dimValue!=null&&s.hasOwnProperty("dimValue")&&(f.value=1,!(c.isInteger(s.dimValue)||s.dimValue&&c.isInteger(s.dimValue.low)&&c.isInteger(s.dimValue.high))))return"dimValue: integer|Long expected";if(s.dimParam!=null&&s.hasOwnProperty("dimParam")){if(f.value===1)return"value: multiple values";if(f.value=1,!c.isString(s.dimParam))return"dimParam: string expected"}return s.denotation!=null&&s.hasOwnProperty("denotation")&&!c.isString(s.denotation)?"denotation: string expected":null},e.fromObject=function(s){if(s instanceof l.onnx.TensorShapeProto.Dimension)return s;var f=new l.onnx.TensorShapeProto.Dimension;return s.dimValue!=null&&(c.Long?(f.dimValue=c.Long.fromValue(s.dimValue)).unsigned=!1:typeof s.dimValue=="string"?f.dimValue=parseInt(s.dimValue,10):typeof s.dimValue=="number"?f.dimValue=s.dimValue:typeof s.dimValue=="object"&&(f.dimValue=new c.LongBits(s.dimValue.low>>>0,s.dimValue.high>>>0).toNumber())),s.dimParam!=null&&(f.dimParam=String(s.dimParam)),s.denotation!=null&&(f.denotation=String(s.denotation)),f},e.toObject=function(s,f){f||(f={});var g={};return f.defaults&&(g.denotation=""),s.dimValue!=null&&s.hasOwnProperty("dimValue")&&(typeof s.dimValue=="number"?g.dimValue=f.longs===String?String(s.dimValue):s.dimValue:g.dimValue=f.longs===String?c.Long.prototype.toString.call(s.dimValue):f.longs===Number?new c.LongBits(s.dimValue.low>>>0,s.dimValue.high>>>0).toNumber():s.dimValue,f.oneofs&&(g.value="dimValue")),s.dimParam!=null&&s.hasOwnProperty("dimParam")&&(g.dimParam=s.dimParam,f.oneofs&&(g.value="dimParam")),s.denotation!=null&&s.hasOwnProperty("denotation")&&(g.denotation=s.denotation),g},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e}(),n}(),d.TypeProto=function(){function n(r){if(r)for(var s=Object.keys(r),f=0;f>>3){case 1:g.tensorType=l.onnx.TypeProto.Tensor.decode(r,r.uint32());break;case 6:g.denotation=r.string();break;default:r.skipType(7&_)}}return g},n.decodeDelimited=function(r){return r instanceof h||(r=new h(r)),this.decode(r,r.uint32())},n.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.tensorType!=null&&r.hasOwnProperty("tensorType")){var s=l.onnx.TypeProto.Tensor.verify(r.tensorType);if(s)return"tensorType."+s}return r.denotation!=null&&r.hasOwnProperty("denotation")&&!c.isString(r.denotation)?"denotation: string expected":null},n.fromObject=function(r){if(r instanceof l.onnx.TypeProto)return r;var s=new l.onnx.TypeProto;if(r.tensorType!=null){if(typeof r.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");s.tensorType=l.onnx.TypeProto.Tensor.fromObject(r.tensorType)}return r.denotation!=null&&(s.denotation=String(r.denotation)),s},n.toObject=function(r,s){s||(s={});var f={};return s.defaults&&(f.denotation=""),r.tensorType!=null&&r.hasOwnProperty("tensorType")&&(f.tensorType=l.onnx.TypeProto.Tensor.toObject(r.tensorType,s),s.oneofs&&(f.value="tensorType")),r.denotation!=null&&r.hasOwnProperty("denotation")&&(f.denotation=r.denotation),f},n.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},n.Tensor=function(){function r(s){if(s)for(var f=Object.keys(s),g=0;g>>3){case 1:_.elemType=s.int32();break;case 2:_.shape=l.onnx.TensorShapeProto.decode(s,s.uint32());break;default:s.skipType(7&b)}}return _},r.decodeDelimited=function(s){return s instanceof h||(s=new h(s)),this.decode(s,s.uint32())},r.verify=function(s){if(typeof s!="object"||s===null)return"object expected";if(s.elemType!=null&&s.hasOwnProperty("elemType")&&!c.isInteger(s.elemType))return"elemType: integer expected";if(s.shape!=null&&s.hasOwnProperty("shape")){var f=l.onnx.TensorShapeProto.verify(s.shape);if(f)return"shape."+f}return null},r.fromObject=function(s){if(s instanceof l.onnx.TypeProto.Tensor)return s;var f=new l.onnx.TypeProto.Tensor;if(s.elemType!=null&&(f.elemType=0|s.elemType),s.shape!=null){if(typeof s.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");f.shape=l.onnx.TensorShapeProto.fromObject(s.shape)}return f},r.toObject=function(s,f){f||(f={});var g={};return f.defaults&&(g.elemType=0,g.shape=null),s.elemType!=null&&s.hasOwnProperty("elemType")&&(g.elemType=s.elemType),s.shape!=null&&s.hasOwnProperty("shape")&&(g.shape=l.onnx.TensorShapeProto.toObject(s.shape,f)),g},r.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},r}(),n}(),d.OperatorSetIdProto=function(){function n(e){if(e)for(var r=Object.keys(e),s=0;s>>3){case 1:f.domain=e.string();break;case 2:f.version=e.int64();break;default:e.skipType(7&g)}}return f},n.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},n.verify=function(e){return typeof e!="object"||e===null?"object expected":e.domain!=null&&e.hasOwnProperty("domain")&&!c.isString(e.domain)?"domain: string expected":e.version!=null&&e.hasOwnProperty("version")&&!(c.isInteger(e.version)||e.version&&c.isInteger(e.version.low)&&c.isInteger(e.version.high))?"version: integer|Long expected":null},n.fromObject=function(e){if(e instanceof l.onnx.OperatorSetIdProto)return e;var r=new l.onnx.OperatorSetIdProto;return e.domain!=null&&(r.domain=String(e.domain)),e.version!=null&&(c.Long?(r.version=c.Long.fromValue(e.version)).unsigned=!1:typeof e.version=="string"?r.version=parseInt(e.version,10):typeof e.version=="number"?r.version=e.version:typeof e.version=="object"&&(r.version=new c.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber())),r},n.toObject=function(e,r){r||(r={});var s={};if(r.defaults)if(s.domain="",c.Long){var f=new c.Long(0,0,!1);s.version=r.longs===String?f.toString():r.longs===Number?f.toNumber():f}else s.version=r.longs===String?"0":0;return e.domain!=null&&e.hasOwnProperty("domain")&&(s.domain=e.domain),e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?s.version=r.longs===String?String(e.version):e.version:s.version=r.longs===String?c.Long.prototype.toString.call(e.version):r.longs===Number?new c.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber():e.version),s},n.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},n}(),d),p.exports=l},2100:(p,t,o)=>{p.exports=o(9482)},9482:(p,t,o)=>{var i=t;function u(){i.util._configure(),i.Writer._configure(i.BufferWriter),i.Reader._configure(i.BufferReader)}i.build="minimal",i.Writer=o(1173),i.BufferWriter=o(3155),i.Reader=o(1408),i.BufferReader=o(593),i.util=o(9693),i.rpc=o(5994),i.roots=o(5054),i.configure=u,u()},1408:(p,t,o)=>{p.exports=m;var i,u=o(9693),d=u.LongBits,a=u.utf8;function h(f,g){return RangeError("index out of range: "+f.pos+" + "+(g||1)+" > "+f.len)}function m(f){this.buf=f,this.pos=0,this.len=f.length}var c,l=typeof Uint8Array<"u"?function(f){if(f instanceof Uint8Array||Array.isArray(f))return new m(f);throw Error("illegal buffer")}:function(f){if(Array.isArray(f))return new m(f);throw Error("illegal buffer")},n=function(){return u.Buffer?function(f){return(m.create=function(g){return u.Buffer.isBuffer(g)?new i(g):l(g)})(f)}:l};function e(){var f=new d(0,0),g=0;if(!(this.len-this.pos>4)){for(;g<3;++g){if(this.pos>=this.len)throw h(this);if(f.lo=(f.lo|(127&this.buf[this.pos])<<7*g)>>>0,this.buf[this.pos++]<128)return f}return f.lo=(f.lo|(127&this.buf[this.pos++])<<7*g)>>>0,f}for(;g<4;++g)if(f.lo=(f.lo|(127&this.buf[this.pos])<<7*g)>>>0,this.buf[this.pos++]<128)return f;if(f.lo=(f.lo|(127&this.buf[this.pos])<<28)>>>0,f.hi=(f.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return f;if(g=0,this.len-this.pos>4){for(;g<5;++g)if(f.hi=(f.hi|(127&this.buf[this.pos])<<7*g+3)>>>0,this.buf[this.pos++]<128)return f}else for(;g<5;++g){if(this.pos>=this.len)throw h(this);if(f.hi=(f.hi|(127&this.buf[this.pos])<<7*g+3)>>>0,this.buf[this.pos++]<128)return f}throw Error("invalid varint encoding")}function r(f,g){return(f[g-4]|f[g-3]<<8|f[g-2]<<16|f[g-1]<<24)>>>0}function s(){if(this.pos+8>this.len)throw h(this,8);return new d(r(this.buf,this.pos+=4),r(this.buf,this.pos+=4))}m.create=n(),m.prototype._slice=u.Array.prototype.subarray||u.Array.prototype.slice,m.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)||(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)||(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)||(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128))return c;if((this.pos+=5)>this.len)throw this.pos=this.len,h(this,10);return c}),m.prototype.int32=function(){return 0|this.uint32()},m.prototype.sint32=function(){var f=this.uint32();return f>>>1^-(1&f)|0},m.prototype.bool=function(){return this.uint32()!==0},m.prototype.fixed32=function(){if(this.pos+4>this.len)throw h(this,4);return r(this.buf,this.pos+=4)},m.prototype.sfixed32=function(){if(this.pos+4>this.len)throw h(this,4);return 0|r(this.buf,this.pos+=4)},m.prototype.float=function(){if(this.pos+4>this.len)throw h(this,4);var f=u.float.readFloatLE(this.buf,this.pos);return this.pos+=4,f},m.prototype.double=function(){if(this.pos+8>this.len)throw h(this,4);var f=u.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,f},m.prototype.bytes=function(){var f=this.uint32(),g=this.pos,_=this.pos+f;if(_>this.len)throw h(this,f);return this.pos+=f,Array.isArray(this.buf)?this.buf.slice(g,_):g===_?new this.buf.constructor(0):this._slice.call(this.buf,g,_)},m.prototype.string=function(){var f=this.bytes();return a.read(f,0,f.length)},m.prototype.skip=function(f){if(typeof f=="number"){if(this.pos+f>this.len)throw h(this,f);this.pos+=f}else do if(this.pos>=this.len)throw h(this);while(128&this.buf[this.pos++]);return this},m.prototype.skipType=function(f){switch(f){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(f=7&this.uint32())!=4;)this.skipType(f);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+f+" at offset "+this.pos)}return this},m._configure=function(f){i=f,m.create=n(),i._configure();var g=u.Long?"toLong":"toNumber";u.merge(m.prototype,{int64:function(){return e.call(this)[g](!1)},uint64:function(){return e.call(this)[g](!0)},sint64:function(){return e.call(this).zzDecode()[g](!1)},fixed64:function(){return s.call(this)[g](!0)},sfixed64:function(){return s.call(this)[g](!1)}})}},593:(p,t,o)=>{p.exports=d;var i=o(1408);(d.prototype=Object.create(i.prototype)).constructor=d;var u=o(9693);function d(a){i.call(this,a)}d._configure=function(){u.Buffer&&(d.prototype._slice=u.Buffer.prototype.slice)},d.prototype.string=function(){var a=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+a,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+a,this.len))},d._configure()},5054:p=>{p.exports={}},5994:(p,t,o)=>{t.Service=o(7948)},7948:(p,t,o)=>{p.exports=u;var i=o(9693);function u(d,a,h){if(typeof d!="function")throw TypeError("rpcImpl must be a function");i.EventEmitter.call(this),this.rpcImpl=d,this.requestDelimited=!!a,this.responseDelimited=!!h}(u.prototype=Object.create(i.EventEmitter.prototype)).constructor=u,u.prototype.rpcCall=function d(a,h,m,c,l){if(!c)throw TypeError("request must be specified");var n=this;if(!l)return i.asPromise(d,n,a,h,m,c);if(n.rpcImpl)try{return n.rpcImpl(a,h[n.requestDelimited?"encodeDelimited":"encode"](c).finish(),function(e,r){if(e)return n.emit("error",e,a),l(e);if(r!==null){if(!(r instanceof m))try{r=m[n.responseDelimited?"decodeDelimited":"decode"](r)}catch(s){return n.emit("error",s,a),l(s)}return n.emit("data",r,a),l(null,r)}n.end(!0)})}catch(e){return n.emit("error",e,a),void setTimeout(function(){l(e)},0)}else setTimeout(function(){l(Error("already ended"))},0)},u.prototype.end=function(d){return this.rpcImpl&&(d||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(p,t,o)=>{p.exports=u;var i=o(9693);function u(m,c){this.lo=m>>>0,this.hi=c>>>0}var d=u.zero=new u(0,0);d.toNumber=function(){return 0},d.zzEncode=d.zzDecode=function(){return this},d.length=function(){return 1};var a=u.zeroHash="\0\0\0\0\0\0\0\0";u.fromNumber=function(m){if(m===0)return d;var c=m<0;c&&(m=-m);var l=m>>>0,n=(m-l)/4294967296>>>0;return c&&(n=~n>>>0,l=~l>>>0,++l>4294967295&&(l=0,++n>4294967295&&(n=0))),new u(l,n)},u.from=function(m){if(typeof m=="number")return u.fromNumber(m);if(i.isString(m)){if(!i.Long)return u.fromNumber(parseInt(m,10));m=i.Long.fromString(m)}return m.low||m.high?new u(m.low>>>0,m.high>>>0):d},u.prototype.toNumber=function(m){if(!m&&this.hi>>>31){var c=1+~this.lo>>>0,l=~this.hi>>>0;return c||(l=l+1>>>0),-(c+4294967296*l)}return this.lo+4294967296*this.hi},u.prototype.toLong=function(m){return i.Long?new i.Long(0|this.lo,0|this.hi,!!m):{low:0|this.lo,high:0|this.hi,unsigned:!!m}};var h=String.prototype.charCodeAt;u.fromHash=function(m){return m===a?d:new u((h.call(m,0)|h.call(m,1)<<8|h.call(m,2)<<16|h.call(m,3)<<24)>>>0,(h.call(m,4)|h.call(m,5)<<8|h.call(m,6)<<16|h.call(m,7)<<24)>>>0)},u.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},u.prototype.zzEncode=function(){var m=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^m)>>>0,this.lo=(this.lo<<1^m)>>>0,this},u.prototype.zzDecode=function(){var m=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^m)>>>0,this.hi=(this.hi>>>1^m)>>>0,this},u.prototype.length=function(){var m=this.lo,c=(this.lo>>>28|this.hi<<4)>>>0,l=this.hi>>>24;return l===0?c===0?m<16384?m<128?1:2:m<2097152?3:4:c<16384?c<128?5:6:c<2097152?7:8:l<128?9:10}},9693:function(p,t,o){var i=t;function u(a,h,m){for(var c=Object.keys(h),l=0;l0)},i.Buffer=function(){try{var a=i.inquire("buffer").Buffer;return a.prototype.utf8Write?a:null}catch{return null}}(),i._Buffer_from=null,i._Buffer_allocUnsafe=null,i.newBuffer=function(a){return typeof a=="number"?i.Buffer?i._Buffer_allocUnsafe(a):new i.Array(a):i.Buffer?i._Buffer_from(a):typeof Uint8Array>"u"?a:new Uint8Array(a)},i.Array=typeof Uint8Array<"u"?Uint8Array:Array,i.Long=i.global.dcodeIO&&i.global.dcodeIO.Long||i.global.Long||i.inquire("long"),i.key2Re=/^true|false|0|1$/,i.key32Re=/^-?(?:0|[1-9][0-9]*)$/,i.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,i.longToHash=function(a){return a?i.LongBits.from(a).toHash():i.LongBits.zeroHash},i.longFromHash=function(a,h){var m=i.LongBits.fromHash(a);return i.Long?i.Long.fromBits(m.lo,m.hi,h):m.toNumber(!!h)},i.merge=u,i.lcFirst=function(a){return a.charAt(0).toLowerCase()+a.substring(1)},i.newError=d,i.ProtocolError=d("ProtocolError"),i.oneOfGetter=function(a){for(var h={},m=0;m-1;--l)if(h[c[l]]===1&&this[c[l]]!==void 0&&this[c[l]]!==null)return c[l]}},i.oneOfSetter=function(a){return function(h){for(var m=0;m{p.exports=n;var i,u=o(9693),d=u.LongBits,a=u.base64,h=u.utf8;function m(b,y,T){this.fn=b,this.len=y,this.next=void 0,this.val=T}function c(){}function l(b){this.head=b.head,this.tail=b.tail,this.len=b.len,this.next=b.states}function n(){this.len=0,this.head=new m(c,0,0),this.tail=this.head,this.states=null}var e=function(){return u.Buffer?function(){return(n.create=function(){return new i})()}:function(){return new n}};function r(b,y,T){y[T]=255&b}function s(b,y){this.len=b,this.next=void 0,this.val=y}function f(b,y,T){for(;b.hi;)y[T++]=127&b.lo|128,b.lo=(b.lo>>>7|b.hi<<25)>>>0,b.hi>>>=7;for(;b.lo>127;)y[T++]=127&b.lo|128,b.lo=b.lo>>>7;y[T++]=b.lo}function g(b,y,T){y[T]=255&b,y[T+1]=b>>>8&255,y[T+2]=b>>>16&255,y[T+3]=b>>>24}n.create=e(),n.alloc=function(b){return new u.Array(b)},u.Array!==Array&&(n.alloc=u.pool(n.alloc,u.Array.prototype.subarray)),n.prototype._push=function(b,y,T){return this.tail=this.tail.next=new m(b,y,T),this.len+=y,this},s.prototype=Object.create(m.prototype),s.prototype.fn=function(b,y,T){for(;b>127;)y[T++]=127&b|128,b>>>=7;y[T]=b},n.prototype.uint32=function(b){return this.len+=(this.tail=this.tail.next=new s((b>>>=0)<128?1:b<16384?2:b<2097152?3:b<268435456?4:5,b)).len,this},n.prototype.int32=function(b){return b<0?this._push(f,10,d.fromNumber(b)):this.uint32(b)},n.prototype.sint32=function(b){return this.uint32((b<<1^b>>31)>>>0)},n.prototype.uint64=function(b){var y=d.from(b);return this._push(f,y.length(),y)},n.prototype.int64=n.prototype.uint64,n.prototype.sint64=function(b){var y=d.from(b).zzEncode();return this._push(f,y.length(),y)},n.prototype.bool=function(b){return this._push(r,1,b?1:0)},n.prototype.fixed32=function(b){return this._push(g,4,b>>>0)},n.prototype.sfixed32=n.prototype.fixed32,n.prototype.fixed64=function(b){var y=d.from(b);return this._push(g,4,y.lo)._push(g,4,y.hi)},n.prototype.sfixed64=n.prototype.fixed64,n.prototype.float=function(b){return this._push(u.float.writeFloatLE,4,b)},n.prototype.double=function(b){return this._push(u.float.writeDoubleLE,8,b)};var _=u.Array.prototype.set?function(b,y,T){y.set(b,T)}:function(b,y,T){for(var w=0;w>>0;if(!y)return this._push(r,1,0);if(u.isString(b)){var T=n.alloc(y=a.length(b));a.decode(b,T,0),b=T}return this.uint32(y)._push(_,y,b)},n.prototype.string=function(b){var y=h.length(b);return y?this.uint32(y)._push(h.write,y,b):this._push(r,1,0)},n.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new m(c,0,0),this.len=0,this},n.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 m(c,0,0),this.len=0),this},n.prototype.ldelim=function(){var b=this.head,y=this.tail,T=this.len;return this.reset().uint32(T),T&&(this.tail.next=b.next,this.tail=y,this.len+=T),this},n.prototype.finish=function(){for(var b=this.head.next,y=this.constructor.alloc(this.len),T=0;b;)b.fn(b.val,y,T),T+=b.len,b=b.next;return y},n._configure=function(b){i=b,n.create=e(),i._configure()}},3155:(p,t,o)=>{p.exports=d;var i=o(1173);(d.prototype=Object.create(i.prototype)).constructor=d;var u=o(9693);function d(){i.call(this)}function a(h,m,c){h.length<40?u.utf8.write(h,m,c):m.utf8Write?m.utf8Write(h,c):m.write(h,c)}d._configure=function(){d.alloc=u._Buffer_allocUnsafe,d.writeBytesBuffer=u.Buffer&&u.Buffer.prototype instanceof Uint8Array&&u.Buffer.prototype.set.name==="set"?function(h,m,c){m.set(h,c)}:function(h,m,c){if(h.copy)h.copy(m,c,0,h.length);else for(var l=0;l>>0;return this.uint32(m),m&&this._push(d.writeBytesBuffer,m,h),this},d.prototype.string=function(h){var m=u.Buffer.byteLength(h);return this.uint32(m),m&&this._push(a,m,h),this},d._configure()},7714:(p,t,o)=>{t.R=void 0;const i=o(6919),u=o(7448);t.R=new class{async init(){}async createSessionHandler(d,a){const h=new i.Session(a);return await h.loadModel(d),new u.OnnxjsSessionHandler(h)}}},4200:(p,t,o)=>{t.c8=t.rX=void 0;const i=o(1670),u=o(5381),d=o(2157),a=o(2306);t.rX=()=>{if((typeof i.env.wasm.initTimeout!="number"||i.env.wasm.initTimeout<0)&&(i.env.wasm.initTimeout=0),typeof i.env.wasm.simd!="boolean"&&(i.env.wasm.simd=!0),typeof i.env.wasm.proxy!="boolean"&&(i.env.wasm.proxy=!1),typeof i.env.wasm.numThreads!="number"||!Number.isInteger(i.env.wasm.numThreads)||i.env.wasm.numThreads<=0){const h=typeof navigator>"u"?(0,u.cpus)().length:navigator.hardwareConcurrency;i.env.wasm.numThreads=Math.min(4,Math.ceil((h||1)/2))}},t.c8=new class{async init(){(0,t.rX)(),await(0,d.initWasm)()}async createSessionHandler(h,m){const c=new a.OnnxruntimeWebAssemblySessionHandler;return await c.loadModel(h,m),Promise.resolve(c)}}},6018:function(p,t,o){var i=this&&this.__createBinding||(Object.create?function(a,h,m,c){c===void 0&&(c=m);var l=Object.getOwnPropertyDescriptor(h,m);l&&!("get"in l?!h.__esModule:l.writable||l.configurable)||(l={enumerable:!0,get:function(){return h[m]}}),Object.defineProperty(a,c,l)}:function(a,h,m,c){c===void 0&&(c=m),a[c]=h[m]}),u=this&&this.__exportStar||function(a,h){for(var m in a)m==="default"||Object.prototype.hasOwnProperty.call(h,m)||i(h,a,m)};Object.defineProperty(t,"__esModule",{value:!0}),u(o(1670),t);const d=o(1670);{const a=o(7714).R;(0,d.registerBackend)("webgl",a,-10)}{const a=o(4200).c8;(0,d.registerBackend)("cpu",a,10),(0,d.registerBackend)("wasm",a,10),(0,d.registerBackend)("xnnpack",a,9)}},246:(p,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createAttributeWithCacheKey=void 0;class o{constructor(u){Object.assign(this,u)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map(u=>`${this[u]}`).join(";")),this._cacheKey}}t.createAttributeWithCacheKey=i=>new o(i)},7778:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Attribute=void 0;const i=o(1446),u=o(9395),d=o(9162),a=o(2517);var h=u.onnxruntime.experimental.fbs;class m{constructor(l){if(this._attributes=new Map,l!=null){for(const n of l)n instanceof i.onnx.AttributeProto?this._attributes.set(n.name,[m.getValue(n),m.getType(n)]):n instanceof h.Attribute&&this._attributes.set(n.name(),[m.getValue(n),m.getType(n)]);if(this._attributes.sized.Tensor.fromProto(r));if(l instanceof h.Attribute)return e.map(r=>d.Tensor.fromOrtTensor(r))}if(n===i.onnx.AttributeProto.AttributeType.STRING&&l instanceof i.onnx.AttributeProto){const r=e;return(0,a.decodeUtf8String)(r)}return n===i.onnx.AttributeProto.AttributeType.STRINGS&&l instanceof i.onnx.AttributeProto?e.map(a.decodeUtf8String):e}static getValueNoCheck(l){return l instanceof i.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(l):this.getValueNoCheckFromOrtFormat(l)}static getValueNoCheckFromOnnxFormat(l){switch(l.type){case i.onnx.AttributeProto.AttributeType.FLOAT:return l.f;case i.onnx.AttributeProto.AttributeType.INT:return l.i;case i.onnx.AttributeProto.AttributeType.STRING:return l.s;case i.onnx.AttributeProto.AttributeType.TENSOR:return l.t;case i.onnx.AttributeProto.AttributeType.GRAPH:return l.g;case i.onnx.AttributeProto.AttributeType.FLOATS:return l.floats;case i.onnx.AttributeProto.AttributeType.INTS:return l.ints;case i.onnx.AttributeProto.AttributeType.STRINGS:return l.strings;case i.onnx.AttributeProto.AttributeType.TENSORS:return l.tensors;case i.onnx.AttributeProto.AttributeType.GRAPHS:return l.graphs;default:throw new Error(`unsupported attribute type: ${i.onnx.AttributeProto.AttributeType[l.type]}`)}}static getValueNoCheckFromOrtFormat(l){switch(l.type()){case h.AttributeType.FLOAT:return l.f();case h.AttributeType.INT:return l.i();case h.AttributeType.STRING:return l.s();case h.AttributeType.TENSOR:return l.t();case h.AttributeType.GRAPH:return l.g();case h.AttributeType.FLOATS:return l.floatsArray();case h.AttributeType.INTS:{const n=[];for(let e=0;e{Object.defineProperty(t,"__esModule",{value:!0}),t.resolveBackend=t.backend=void 0;const i=o(5038),u=new Map;async function d(a){const h=t.backend;if(h[a]!==void 0&&function(m){const c=m;return"initialize"in c&&typeof c.initialize=="function"&&"createSessionHandler"in c&&typeof c.createSessionHandler=="function"&&"dispose"in c&&typeof c.dispose=="function"}(h[a])){const m=h[a];let c=m.initialize();if(typeof c=="object"&&"then"in c&&(c=await c),c)return u.set(a,m),m}}t.backend={webgl:new i.WebGLBackend},t.resolveBackend=async function a(h){if(!h)return a(["webgl"]);{const m=typeof h=="string"?[h]:h;for(const c of m){const l=u.get(c);if(l)return l;const n=await d(c);if(n)return n}}throw new Error("no available backend to use")}},5038:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLBackend=void 0;const i=o(1670),u=o(6231),d=o(6416),a=o(7305);t.WebGLBackend=class{get contextId(){return i.env.webgl.contextId}set contextId(h){i.env.webgl.contextId=h}get matmulMaxBatchSize(){return i.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(h){i.env.webgl.matmulMaxBatchSize=h}get textureCacheMode(){return i.env.webgl.textureCacheMode}set textureCacheMode(h){i.env.webgl.textureCacheMode=h}get pack(){return i.env.webgl.pack}set pack(h){i.env.webgl.pack=h}get async(){return i.env.webgl.async}set async(h){i.env.webgl.async=h}initialize(){try{return this.glContext=(0,a.createWebGLContext)(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),u.Logger.setWithEnv(i.env),u.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(h){return u.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${h}`),!1}}createSessionHandler(h){return new d.WebGLSessionHandler(this,h)}dispose(){this.glContext.dispose()}}},5107:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoordsGlslLib=void 0;const i=o(2517),u=o(8520),d=o(5060),a=o(7859),h=o(9390);class m extends u.GlslLib{constructor(l){super(l)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new u.GlslLibRoutine(` vec2 offsetToCoords(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(){return{coordsToOffset:new u.GlslLibRoutine(` int coordsToOffset(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(){const l=this.context.outputTextureLayout;return l.isPacked?this.getPackedOutputSamplingSnippet(l):this.getUnpackedOutputSamplingSnippet(l)}getPackedOutputSamplingSnippet(l){const n=l.unpackedShape,e=[l.width,l.height],r={},s="getOutputCoords";switch(n.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputPacked1DCoords(n,e);break;case 2:r[s]=this.getOutputPacked2DCoords(n,e);break;case 3:r[s]=this.getOutputPacked3DCoords(n,e);break;default:r[s]=this.getOutputPackedNDCoords(n,e)}const f=` void setOutput(vec4 val) { ${(0,d.getGlsl)(this.context.glContext.version).output} = val; } `;return r.floatTextureSetRGBA=new u.GlslLibRoutine(f),r}getUnpackedOutputSamplingSnippet(l){const n=l.unpackedShape,e=[l.width,l.height],r={},s="getOutputCoords";switch(n.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputUnpacked1DCoords(n,e);break;case 2:r[s]=this.getOutputUnpacked2DCoords(n,e);break;case 3:r[s]=this.getOutputUnpacked3DCoords(n,e);break;case 4:r[s]=this.getOutputUnpacked4DCoords(n,e);break;case 5:r[s]=this.getOutputUnpacked5DCoords(n,e);break;case 6:r[s]=this.getOutputUnpacked6DCoords(n,e);break;default:throw new Error(`Unsupported output dimensionality: ${n.length}`)}const f=` void setOutput(float val) { ${(0,d.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0); } `;return r.floatTextureSetR=new u.GlslLibRoutine(f),r}getOutputScalarCoords(){return new u.GlslLibRoutine(` int getOutputCoords() { return 0; } `)}getOutputPacked1DCoords(l,n){const e=n;let r="";return e[0]===1?(r=` int getOutputCoords() { return 2 * int(TexCoords.y * ${e[1]}.0); } `,new u.GlslLibRoutine(r)):e[1]===1?(r=` int getOutputCoords() { return 2 * int(TexCoords.x * ${e[0]}.0); } `,new u.GlslLibRoutine(r)):(r=` int getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${e[0]}, ${e[1]})); return 2 * (resTexRC.y * ${e[0]} + resTexRC.x); } `,new u.GlslLibRoutine(r))}getOutputPacked2DCoords(l,n){let e="";if(i.ArrayUtil.arraysEqual(l,n))return e=` ivec2 getOutputCoords() { return 2 * ivec2(TexCoords.xy * vec2(${n[0]}, ${n[1]})); } `,new u.GlslLibRoutine(e);const r=n,s=Math.ceil(l[1]/2);return e=` ivec2 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${r[0]}, ${r[1]})); int index = resTexRC.y * ${r[0]} + resTexRC.x; // reverse r and c order for packed texture int r = imod(index, ${s}) * 2; int c = 2 * (index / ${s}); return ivec2(r, c); } `,new u.GlslLibRoutine(e)}getOutputPacked3DCoords(l,n){const e=[n[0],n[1]],r=Math.ceil(l[2]/2),s=r*Math.ceil(l[1]/2),f=` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${e[0]}, ${e[1]})); int index = resTexRC.y * ${e[0]} + resTexRC.x; int b = index / ${s}; index -= b * ${s}; // reverse r and c order for packed texture int r = imod(index, ${r}) * 2; int c = 2 * (index / ${r}); return ivec3(b, r, c); } `;return new u.GlslLibRoutine(f)}getOutputPackedNDCoords(l,n){const e=[n[0],n[1]],r=Math.ceil(l[l.length-1]/2),s=r*Math.ceil(l[l.length-2]/2);let f=s,g="",_="b, r, c";for(let y=2;y=0;--_)s[_]=s[_+1]*l[_+1];const f=["r","c","d"],g=s.map((_,b)=>`int ${f[b]} = index / ${_}; ${b===s.length-1?`int ${f[b+1]} = index - ${f[b]} * ${_}`:`index -= ${f[b]} * ${_}`};`).join("");return e=` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n[0]}, ${n[1]})); int index = resTexRC.y * ${n[0]} + resTexRC.x; ${g} return ivec3(r, c, d); } `,new u.GlslLibRoutine(e)}getOutputUnpacked4DCoords(l,n){let e="";const r=l.length;let s=null;r<2&&(s=[]),s=new Array(r-1),s[r-2]=l[r-1];for(let _=r-3;_>=0;--_)s[_]=s[_+1]*l[_+1];const f=["r","c","d","d2"],g=s.map((_,b)=>`int ${f[b]} = index / ${_}; ${b===s.length-1?`int ${f[b+1]} = index - ${f[b]} * ${_}`:`index -= ${f[b]} * ${_}`};`).join("");return e=` ivec4 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n[0]}, ${n[1]})); int index = resTexRC.y * ${n[0]} + resTexRC.x; ${g} return ivec4(r, c, d, d2); } `,new u.GlslLibRoutine(e)}getOutputUnpacked5DCoords(l,n){let e="";const r=l.length;let s=null;r<2&&(s=[]),s=new Array(r-1),s[r-2]=l[r-1];for(let _=r-3;_>=0;--_)s[_]=s[_+1]*l[_+1];const f=["r","c","d","d2","d3"],g=s.map((_,b)=>`int ${f[b]} = index / ${_}; ${b===s.length-1?`int ${f[b+1]} = index - ${f[b]} * ${_}`:`index -= ${f[b]} * ${_}`};`).join("");return e=` ivec5 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n[0]}, ${n[1]})); int index = resTexRC.y * ${n[0]} + resTexRC.x; ${g} return ivec5(r, c, d, d2, d3); } `,new u.GlslLibRoutine(e)}getOutputUnpacked6DCoords(l,n){let e="";const r=l.length;let s=null;r<2&&(s=[]),s=new Array(r-1),s[r-2]=l[r-1];for(let _=r-3;_>=0;--_)s[_]=s[_+1]*l[_+1];const f=["r","c","d","d2","d3","d4"],g=s.map((_,b)=>`int ${f[b]} = index / ${_}; ${b===s.length-1?`int ${f[b+1]} = index - ${f[b]} * ${_}`:`index -= ${f[b]} * ${_}`};`).join("");return e=` ivec6 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n[0]}, ${n[1]})); int index = resTexRC.y * ${n[0]} + resTexRC.x; ${g} return ivec6(r, c, d, d2, d3, d4); } `,new u.GlslLibRoutine(e)}getCommonUtilFuncs(){const l={};let n="uvFromFlat";l[n]=new u.GlslLibRoutine(` 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); } `),n="packedUVfrom1D",l[n]=new u.GlslLibRoutine(` 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); } `),n="packedUVfrom2D",l[n]=new u.GlslLibRoutine(` 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); } `),n="packedUVfrom3D",l[n]=new u.GlslLibRoutine(` 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); } `),n="sampleTexture";const e=(0,d.getGlsl)(this.context.glContext.version);return l[n]=new u.GlslLibRoutine(` float sampleTexture(sampler2D textureSampler, vec2 uv) { return ${e.texture2D}(textureSampler, uv).r; }`),l}getInputsSamplingSnippets(){const l={},n=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((e,r)=>{const s=this.context.inputTextureLayouts[r],f=(0,h.generateShaderFuncNameFromInputSamplerName)(e);s.isPacked?l[f]=this.getPackedSamplerFromInput(f,e,s):l[f]=this.getUnpackedSamplerFromInput(f,e,s);const g=(0,h.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(e);s.unpackedShape.length<=n.unpackedShape.length&&(s.isPacked?l[g]=this.getPackedSamplerAtOutputCoords(g,s,n,e):l[g]=this.getUnpackedSamplerAtOutputCoords(g,s,n,e))}),l}getPackedSamplerAtOutputCoords(l,n,e,r){const s=n.unpackedShape,f=e.unpackedShape,g=r,_=(0,h.generateShaderFuncNameFromInputSamplerName)(g),b=s.length,y=f.length,T=i.BroadcastUtil.getBroadcastDims(s,f),w=(0,h.getCoordsDataType)(y),v=y-b;let E;const P=(0,h.getGlChannels)();E=b===0?"":y<2&&T.length>=1?"coords = 0;":T.map(D=>`coords.${P[D+v]} = 0;`).join(` `);let x="";x=y<2&&b>0?"coords":s.map((D,V)=>`coords.${P[V+v]}`).join(", ");let O="return outputValue;";const $=i.ShapeUtil.size(s)===1,k=i.ShapeUtil.size(f)===1;if(b!==1||$||k){if($&&!k)O=y===1?` return vec4(outputValue.x, outputValue.x, 0., 0.); `:` return vec4(outputValue.x); `;else if(T.length){const D=b-2,V=b-1;T.indexOf(D)>-1&&T.indexOf(V)>-1?O="return vec4(outputValue.x);":T.indexOf(D)>-1?O="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":T.indexOf(V)>-1&&(O="return vec4(outputValue.xx, outputValue.zz);")}}else O=` return vec4(outputValue.xy, outputValue.xy); `;const N=` vec4 ${l}() { ${w} coords = getOutputCoords(); int lastDim = coords.${P[y-1]}; coords.${P[y-1]} = coords.${P[y-2]}; coords.${P[y-2]} = lastDim; ${E} vec4 outputValue = ${_}(${x}); ${O} } `;return new u.GlslLibRoutine(N,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(l,n,e,r){const s=[e.width,e.height],f=[n.width,n.height],g=n.unpackedShape.length,_=e.unpackedShape.length,b=n.unpackedShape,y=e.unpackedShape,T=(0,h.generateShaderFuncNameFromInputSamplerName)(r);if(g===_&&i.ArrayUtil.arraysEqual(f,s)){const k=` float ${l}() { return sampleTexture(${r}, TexCoords); } `;return new u.GlslLibRoutine(k,["coordinates.sampleTexture"])}const w=(0,h.getCoordsDataType)(_),v=i.BroadcastUtil.getBroadcastDims(b,y),E=_-g;let P;const x=(0,h.getGlChannels)();P=g===0?"":_<2&&v.length>=1?"coords = 0;":v.map(k=>`coords.${x[k+E]} = 0;`).join(` `);let O="";O=_<2&&g>0?"coords":n.unpackedShape.map((k,N)=>`coords.${x[N+E]}`).join(", ");const $=` float ${l}() { ${w} coords = getOutputCoords(); ${P} return ${T}(${O}); } `;return new u.GlslLibRoutine($,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(l,n,e){switch(e.unpackedShape.length){case 0:return this.getPackedSamplerScalar(l,n);case 1:return this.getPackedSampler1D(l,n,e);case 2:return this.getPackedSampler2D(l,n,e);case 3:return this.getPackedSampler3D(l,n,e);default:return this.getPackedSamplerND(l,n,e)}}getUnpackedSamplerFromInput(l,n,e){const r=e.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(l,n,e);case 1:return this.getUnpackedSampler1D(l,n,e);case 2:return this.getUnpackedSampler2D(l,n,e);case 3:return this.getUnpackedSampler3D(l,n,e);case 4:return this.getUnpackedSampler4D(l,n,e);case 5:return this.getUnpackedSampler5D(l,n,e);case 6:return this.getUnpackedSampler6D(l,n,e);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(l,n){const e=` vec4 ${l}() { return ${(0,d.getGlsl)(this.context.glContext.version).texture2D}(${n}, halfCR); } `;return new u.GlslLibRoutine(e)}getPackedSampler1D(l,n,e){const r=[e.width,e.height],s=[r[1],r[0]],f=(0,d.getGlsl)(this.context.glContext.version),g=`vec4 ${l}(int index) { vec2 uv = packedUVfrom1D( ${s[0]}, ${s[1]}, index); return ${f.texture2D}(${n}, uv); }`;return new u.GlslLibRoutine(g,["coordinates.packedUVfrom1D"])}getPackedSampler2D(l,n,e){const r=e.unpackedShape,s=[e.width,e.height],f=(0,d.getGlsl)(this.context.glContext.version),g=s[0],_=s[1];if(s!=null&&i.ArrayUtil.arraysEqual(r,s)){const w=`vec4 ${l}(int row, int col) { vec2 uv = (vec2(col, row) + halfCR) / vec2(${_}.0, ${g}.0); return ${f.texture2D}(${n}, uv); }`;return new u.GlslLibRoutine(w)}const b=s,y=Math.ceil(r[1]/2),T=`vec4 ${l}(int row, int col) { vec2 uv = packedUVfrom2D(${b[1]}, ${b[0]}, ${y}, row, col); return ${f.texture2D}(${n}, uv); }`;return new u.GlslLibRoutine(T,["coordinates.packedUVfrom2D"])}getPackedSampler3D(l,n,e){const r=e.unpackedShape,s=[e.width,e.height],f=[s[0],s[1]],g=(0,d.getGlsl)(this.context.glContext.version);if(r[0]===1){const w=r.slice(1),v=[1,2],E=(0,h.squeezeInputShape)(r,w),P=["b","row","col"],x=JSON.parse(JSON.stringify(e));x.unpackedShape=E;const O=this.getPackedSamplerFromInput(l,n,x),$=`${O.routineBody} vec4 ${l}(int b, int row, int col) { return ${l}(${(0,h.getSqueezedParams)(P,v)}); } `;return new u.GlslLibRoutine($,O.dependencies)}const _=f[0],b=f[1],y=Math.ceil(r[2]/2),T=`vec4 ${l}(int b, int row, int col) { vec2 uv = packedUVfrom3D( ${b}, ${_}, ${y*Math.ceil(r[1]/2)}, ${y}, b, row, col); return ${g.texture2D}(${n}, uv);}`;return new u.GlslLibRoutine(T,["coordinates.packedUVfrom3D"])}getPackedSamplerND(l,n,e){const r=e.unpackedShape,s=r.length,f=[e.width,e.height],g=(0,d.getGlsl)(this.context.glContext.version),_=[f[0],f[1]],b=_[1],y=_[0],T=Math.ceil(r[s-1]/2);let w=T*Math.ceil(r[s-2]/2),v="int b, int row, int col",E=`b * ${w} + (row / 2) * ${T} + (col / 2)`;for(let x=2;x{const r=this.context.inputTextureLayouts[e],s=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let f=`_${n}`;l[f]=new u.GlslLibRoutine(this.getValueFromSingle(n,s,r.width,r.height,!1),[`shapeUtils.indicesToOffset${f}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),f+="_T",l[f]=new u.GlslLibRoutine(this.getValueFromSingle(n,s,r.width,r.height,!0),[`shapeUtils.indicesToOffset${f}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])}),l}getValueFromSingle(l,n,e,r,s){let f=`_${l}`;return s&&(f+="_T"),` float ${f}(int m[${n}]) { int offset = indicesToOffset${f}(m); vec2 coords = offsetToCoords(offset, ${e}, ${r}); float value = getColorAsFloat(${(0,d.getGlsl)(this.context.glContext.version).texture2D}(${l}, coords)); return value; } `}getPackedValueFrom(l,n,e,r,s){let f=`_${l}_Pack`;return s&&(f+="_T"),` vec4 ${f}(int m[${n}]) { int offset = indicesToOffset_${l}(m); vec2 coords = offsetToCoords(offset, ${e}, ${r}); return ${(0,d.getGlsl)(this.context.glContext.version).texture2D}(${l}, coords); } `}}t.CoordsGlslLib=m},8520:(p,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.TopologicalSortGlslRoutines=t.GlslLibRoutineNode=t.GlslLibRoutine=t.GlslLib=t.GlslContext=t.FunctionType=void 0,(o=t.FunctionType||(t.FunctionType={}))[o.ValueBased=0]="ValueBased",o[o.Positional=1]="Positional",t.GlslContext=class{constructor(i,u,d,a){this.glContext=i,this.programInfo=u,this.inputTextureLayouts=d,this.outputTextureLayout=a}},t.GlslLib=class{constructor(i){this.context=i}},t.GlslLibRoutine=class{constructor(i,u){this.routineBody=i,this.dependencies=u}},t.GlslLibRoutineNode=class{constructor(i,u,d){this.name=i,this.dependencies=d||[],u&&(this.routineBody=u)}addDependency(i){i&&this.dependencies.push(i)}},t.TopologicalSortGlslRoutines=class{static returnOrderedNodes(i){if(!i||i.length===0)return[];if(i.length===1)return i;const u=new Set,d=new Set,a=new Array;return this.createOrderedNodes(i,u,d,a),a}static createOrderedNodes(i,u,d,a){for(let h=0;h0)for(let m=0;m{Object.defineProperty(t,"__esModule",{value:!0}),t.EncodingGlslLib=void 0;const i=o(8520);class u extends i.GlslLib{constructor(a){super(a)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new i.GlslLibRoutine(`highp vec4 encode(highp float f) { return vec4(f, 0.0, 0.0, 0.0); } `)}}decodeFloat32(){return{decode:new i.GlslLibRoutine(`highp float decode(highp vec4 rgba) { return rgba.r; } `)}}encodeUint8(){const a=u.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new i.GlslLibRoutine(` highp vec4 encode(highp float f) { highp float F = abs(f); highp float Sign = step(0.0,-f); highp float Exponent = floor(log2(F)); highp float Mantissa = (exp2(- Exponent) * F); Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa)); highp vec4 rgba; rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0)); rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0); rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0))); rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0))); ${a} rgba = rgba / 255.0; // values need to be normalized to [0,1] return rgba; } `)}}decodeUint8(){const a=u.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new i.GlslLibRoutine(` highp float decode(highp vec4 rgba) { rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] ${a} highp float Sign = 1.0 - step(128.0,rgba[0])*2.0; highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000); highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); return Result; } `)}}static isLittleEndian(){const a=new ArrayBuffer(4),h=new Uint32Array(a),m=new Uint8Array(a);if(h[0]=3735928559,m[0]===239)return!0;if(m[0]===222)return!1;throw new Error("unknown endianness")}}t.EncodingGlslLib=u},9894:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FragColorGlslLib=void 0;const i=o(8520),u=o(5060);class d extends i.GlslLib{constructor(h){super(h)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const h=(0,u.getGlsl)(this.context.glContext.version);return{setFragColor:new i.GlslLibRoutine(` void setFragColor(float value) { ${h.output} = encode(value); } `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new i.GlslLibRoutine(` float getColorAsFloat(vec4 color) { return decode(color); } `,["encoding.decode"])}}}t.FragColorGlslLib=d},2848:(p,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.replaceInlines=void 0;const o=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;t.replaceInlines=function(i){const u={};let d;for(;(d=o.exec(i))!==null;){const a=d[3].split(",").map(h=>{const m=h.trim().split(" ");return m&&m.length===2?{type:m[0],name:m[1]}:null}).filter(h=>h!==null);u[d[2]]={params:a,body:d[4]}}for(const a in u){const h="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",a),m=new RegExp(h,"gm");for(;(d=m.exec(i))!==null;){const c=d[1],l=d[2],n=d[3].split(","),e=c?`${c} ${l};`:"";let r=u[a].body,s="";u[a].params.forEach((g,_)=>{g&&(s+=`${g.type} ${g.name} = ${n[_]}; `)}),r=`${s} ${r}`,r=r.replace("return",`${l} = `);const f=` ${e} { ${r} } `;i=i.replace(d[0],f)}}return i.replace(o,"")}},8879:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GlslPreprocessor=void 0;const i=o(8520),u=o(2848),d=o(5483),a=o(5060);t.GlslPreprocessor=class{constructor(h,m,c,l){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new i.GlslContext(h,m,c,l),Object.keys(d.glslRegistry).forEach(e=>{const r=new d.glslRegistry[e](this.context);this.libs[e]=r});const n=this.glslLibRoutineDependencyGraph;for(const e in this.libs){const r=this.libs[e].getFunctions();for(const s in r){const f=e+"."+s;let g;n[f]?(g=n[f],g.routineBody=r[s].routineBody):(g=new i.GlslLibRoutineNode(f,r[s].routineBody),n[f]=g);const _=r[s].dependencies;if(_)for(let b=0;b<_.length;++b)if(n[_[b]])g.addDependency(n[_[b]]);else{const y=new i.GlslLibRoutineNode(_[b]);n[_[b]]=y,g.addDependency(y)}}}}preprocess(){const h=this.context.programInfo;let m=h.shaderSource;return this.context.programInfo.hasMain||(m=`${m} ${(0,a.getDefaultFragShaderMain)(this.context.glContext.version,this.context.outputTextureLayout.shape.length)}`),m=(0,u.replaceInlines)(m),`${(0,a.getFragShaderPreamble)(this.context.glContext.version)} ${this.getUniforms(h.inputNames,h.variables)} ${this.getImports(m)} ${m}`}getImports(h){const m=this.selectGlslLibRoutinesToBeIncluded(h);if(m.length===0)return"";let c="";for(let l=0;l{const l=c.split(".")[1];h.indexOf(l)!==-1&&m.push(this.glslLibRoutineDependencyGraph[c])}),i.TopologicalSortGlslRoutines.returnOrderedNodes(m)}getUniforms(h,m){const c=[];if(h)for(const l of h)c.push(`uniform sampler2D ${l};`);if(m)for(const l of m)c.push(`uniform ${l.type} ${l.name}${l.arrayLength?`[${l.arrayLength}]`:""};`);return c.join(` `)}}},5483:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.glslRegistry=void 0;const i=o(5107),u=o(7341),d=o(9894),a=o(2655),h=o(3891);t.glslRegistry={encoding:u.EncodingGlslLib,fragcolor:d.FragColorGlslLib,vec:h.VecGlslLib,shapeUtils:a.ShapeUtilsGlslLib,coordinates:i.CoordsGlslLib}},2655:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShapeUtilsGlslLib=void 0;const i=o(8520);class u extends i.GlslLib{constructor(a){super(a)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.bcastIndex()),this.bcastMatmulIndex()),this.offsetToIndices()),this.indicesToOffset()),this.incrementIndices())}getCustomTypes(){return{}}bcastIndex(){const a=this.context.outputTextureLayout.shape.length,h={};return this.context.programInfo.inputNames.forEach((m,c)=>{const l=this.context.inputTextureLayouts[c].unpackedShape;if(l.length<=a){const n=l.length,e=a-n,r=`bcastIndices_${m}`;let s="";for(let g=0;g{const l=this.context.inputTextureLayouts[c].shape;if(!(l.length<2||l.length>a)){const n=l.length,e=a-n,r=`bcastMatmulIndices_${m}`;let s="";for(let g=0;g{const c=this.context.inputTextureLayouts[m].shape,l=this.context.inputTextureLayouts[m].strides,n=c.length;let e=`indicesToOffset_${h}`;a[e]=new i.GlslLibRoutine(u.indexToOffsetSingle(e,n,l)),e=`indicesToOffset_${h}_T`,a[e]=new i.GlslLibRoutine(u.indexToOffsetSingle(e,n,l.slice().reverse()))}),a}static indexToOffsetSingle(a,h,m){let c="";for(let l=h-1;l>=0;--l)c+=` offset += indices[${l}] * ${m[l]}; `;return` int ${a}(int indices[${h}]) { int offset = 0; ${c} return offset; } `}offsetToIndices(){const a={};return this.context.programInfo.inputNames.forEach((h,m)=>{const c=this.context.inputTextureLayouts[m].shape,l=this.context.inputTextureLayouts[m].strides,n=c.length;let e=`offsetToIndices_${h}`;a[e]=new i.GlslLibRoutine(u.offsetToIndicesSingle(e,n,l)),e=`offsetToIndices_${h}_T`,a[e]=new i.GlslLibRoutine(u.offsetToIndicesSingle(e,n,l.slice().reverse()))}),a}static offsetToIndicesSingle(a,h,m){const c=[];for(let l=0;l{const c=this.context.inputTextureLayouts[m].shape,l=c.length,n=`incrementIndices_${h}`;let e="";for(let s=0;s= 0; --i) { if(i > axis) continue; indices[i] += 1; if(indices[i] < shape[i]) { break; } indices[i] = 0; } } `;a[n]=new i.GlslLibRoutine(r)}),a}}t.ShapeUtilsGlslLib=u},5060:(p,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getDefaultFragShaderMain=t.getFragShaderPreamble=t.getVertexShaderSource=t.getGlsl=void 0;const o={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},i={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function u(d){return d===1?o:i}t.getGlsl=u,t.getVertexShaderSource=function(d){const a=u(d);return`${a.version} precision highp float; ${a.attribute} vec3 position; ${a.attribute} vec2 textureCoord; ${a.varyingVertex} vec2 TexCoords; void main() { gl_Position = vec4(position, 1.0); TexCoords = textureCoord; }`},t.getFragShaderPreamble=function(d){const a=u(d);return`${a.version} precision highp float; precision highp int; precision highp sampler2D; ${a.varyingFrag} vec2 TexCoords; ${a.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); } `},t.getDefaultFragShaderMain=function(d,a){return` void main() { int indices[${a}]; toVec(TexCoords, indices); vec4 result = vec4(process(indices)); ${u(d).output} = result; } `}},3891:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.VecGlslLib=void 0;const i=o(8520);class u extends i.GlslLib{constructor(a){super(a)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const a=this.context.outputTextureLayout.shape.length,h={add:"+=",sub:"-=",mul:"*=",div:"/="},m={};for(const c in h){const l=`${c}Vec`;let n="";for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLInferenceHandler=void 0;const i=o(6231),u=o(9162),d=o(2517),a=o(2403),h=o(7019),m=o(8710),c=o(5611),l=o(4057),n=o(2039);t.WebGLInferenceHandler=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,r){return(0,l.calculateTextureWidthAndHeight)(this.session.layoutStrategy,e,r)}executeProgram(e,r){if(r.length{const v=w.map(P=>`${P.unpackedShape.join(",")};${P.width}x${P.height}`).join("_");let E=T.name;return T.cacheHint&&(E+="["+T.cacheHint+"]"),E+=":"+v,E})(e,s);let g=this.session.programManager.getArtifact(f);const _=g?g.programInfo:typeof e.get=="function"?e.get():e,b=(0,l.createTextureLayoutFromTextureType)(this.session.layoutStrategy,_.output.dims,_.output.textureType),y=this.createTextureData(b,_.output.type);return g||(g=this.session.programManager.build(_,s,y),this.session.programManager.setArtifact(f,g)),this.runProgram(g,s,y),y}run(e,r){return this.executeProgram(e,r).tensor}runProgram(e,r,s){for(let f=0;fthis.readTexture(_),async b=>this.readTextureAsync(_),void 0,g),texture:s});return this.setTextureData(_.tensor.dataId,_,e.isPacked),_}getTextureData(e,r=!1){return this.session.isInitializer(e)?this.session.getTextureData(e,r):r?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,r,s=!1){this.session.isInitializer(e)?this.session.setTextureData(e,r,s):(s?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,r)}isTextureLayoutCached(e,r=!1){return!!this.getTextureData(e.dataId,r)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,m.encodeAsUint8)(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,m.encodeAsUint8)(this,e))}pack(e){return this.executeProgram((0,a.createPackProgramInfoLoader)(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram((0,c.createUnpackProgramInfoLoader)(this,e.tensor),[e.tensor])}}},1640:function(p,t,o){var i=this&&this.__createBinding||(Object.create?function(G,ee,J,ae){ae===void 0&&(ae=J);var Ee=Object.getOwnPropertyDescriptor(ee,J);Ee&&!("get"in Ee?!ee.__esModule:Ee.writable||Ee.configurable)||(Ee={enumerable:!0,get:function(){return ee[J]}}),Object.defineProperty(G,ae,Ee)}:function(G,ee,J,ae){ae===void 0&&(ae=J),G[ae]=ee[J]}),u=this&&this.__setModuleDefault||(Object.create?function(G,ee){Object.defineProperty(G,"default",{enumerable:!0,value:ee})}:function(G,ee){G.default=ee}),d=this&&this.__importStar||function(G){if(G&&G.__esModule)return G;var ee={};if(G!=null)for(var J in G)J!=="default"&&Object.prototype.hasOwnProperty.call(G,J)&&i(ee,G,J);return u(ee,G),ee};Object.defineProperty(t,"__esModule",{value:!0}),t.WEBGL_OP_RESOLVE_RULES=void 0;const a=o(2898),h=d(o(7839)),m=o(4196),c=o(2069),l=o(8138),n=o(9663),e=o(5193),r=o(7992),s=o(1253),f=o(4776),g=o(6572),_=o(3346),b=o(5623),y=o(2870),T=o(2143),w=o(4939),v=o(718),E=o(2268),P=o(8117),x=o(2278),O=o(5524),$=o(5975),k=o(3933),N=o(6558),D=o(5723),V=o(3738),C=d(o(4909)),B=o(8428),X=o(9793);t.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",C.abs],["Acos","","7+",C.acos],["Add","","7+",h.add],["And","","7+",h.and],["Asin","","7+",C.asin],["Atan","","7+",C.atan],["AveragePool","","7+",T.averagePool,T.parseAveragePoolAttributes],["BatchNormalization","","7+",a.batchNormalization,a.parseBatchNormalizationAttributes],["Cast","","6+",m.cast,m.parseCastAttributes],["Ceil","","6+",C.ceil],["Clip","","6-10",C.clip,C.parseClipAttributes],["Clip","","11+",C.clipV11],["Concat","","4+",c.concat,c.parseConcatAttributes],["Conv","","1+",l.conv,l.parseConvAttributes],["ConvTranspose","","1+",n.convTranspose,n.parseConvTransposeAttributes],["Cos","","7+",C.cos],["Div","","7+",h.div],["Dropout","","7+",C.identity],["DepthToSpace","","1+",e.depthToSpace,e.parseDepthToSpaceAttributes],["Equal","","7+",h.equal],["Elu","","6+",C.elu,C.parseEluAttributes],["Exp","","6+",C.exp],["Flatten","","1+",r.flatten,r.parseFlattenAttributes],["Floor","","6+",C.floor],["FusedConv","com.microsoft","1+",l.conv,l.parseConvAttributes],["Gather","","1+",s.gather,s.parseGatherAttributes],["Gemm","","7-10",f.gemm,f.parseGemmAttributesV7],["Gemm","","11+",f.gemm,f.parseGemmAttributesV11],["GlobalAveragePool","","1+",T.globalAveragePool,T.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",T.globalMaxPool],["Greater","","7+",h.greater],["Identity","","1+",C.identity],["ImageScaler","","1+",g.imageScaler,g.parseImageScalerAttributes],["InstanceNormalization","","6+",_.instanceNormalization,_.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",C.leakyRelu,C.parseLeakyReluAttributes],["Less","","7+",h.less],["Log","","6+",C.log],["MatMul","","1+",b.matMul,b.parseMatMulAttributes],["MaxPool","","1+",T.maxPool,T.parseMaxPoolAttributes],["Mul","","7+",h.mul],["Neg","","6+",C.neg],["Not","","1+",C.not],["Or","","7+",h.or],["Pad","","2-10",y.padV2,y.parsePadAttributesV2],["Pad","","11+",y.padV11,y.parsePadAttributesV11],["Pow","","7+",h.pow],["PRelu","","7+",h.pRelu],["ReduceLogSum","","1+",w.reduceLogSum,w.parseReduceAttributes],["ReduceMax","","1+",w.reduceMax,w.parseReduceAttributes],["ReduceMean","","1+",w.reduceMean,w.parseReduceAttributes],["ReduceMin","","1+",w.reduceMin,w.parseReduceAttributes],["ReduceProd","","1+",w.reduceProd,w.parseReduceAttributes],["ReduceSum","","1-12",w.reduceSum,w.parseReduceAttributes],["ReduceSumSquare","","1+",w.reduceLogSumSquare,w.parseReduceAttributes],["Relu","","6+",C.relu],["Reshape","","5+",v.reshape],["Resize","","10",E.resize,E.parseResizeAttributesV10],["Resize","","11+",E.resize,E.parseResizeAttributesV11],["Shape","","1+",P.shape],["Sigmoid","","6+",C.sigmoid],["Sin","","7+",C.sin],["Slice","","10+",x.sliceV10],["Slice","","1-9",x.slice,x.parseSliceAttributes],["Softmax","","1-12",O.softmax,O.parseSoftmaxAttributes],["Softmax","","13+",O.softmaxV13,O.parseSoftmaxAttributesV13],["Split","","2-12",$.split,$.parseSplitAttributes],["Sqrt","","6+",C.sqrt],["Squeeze","","1-12",k.squeeze,k.parseSqueezeAttributes],["Squeeze","","13+",k.squeezeV13],["Sub","","7+",h.sub],["Sum","","6+",N.sum],["Tan","","7+",C.tan],["Tanh","","6+",C.tanh],["Tile","","6+",D.tile],["Transpose","","1+",V.transpose,V.parseTransposeAttributes],["Upsample","","7-8",X.upsample,X.parseUpsampleAttributesV7],["Upsample","","9",X.upsample,X.parseUpsampleAttributesV9],["Unsqueeze","","1-12",B.unsqueeze,B.parseUnsqueezeAttributes],["Unsqueeze","","13+",B.unsqueezeV13],["Xor","","7+",h.xor]]},2898:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseBatchNormalizationAttributes=t.batchNormalization=void 0;const i=o(246),u=o(5060),d=o(2039),a={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked]};t.batchNormalization=(c,l,n)=>(m(l),[c.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>h(c,l,n)}),l)]),t.parseBatchNormalizationAttributes=c=>{const l=c.attributes.getFloat("epsilon",1e-5),n=c.attributes.getFloat("momentum",.9),e=c.attributes.getInt("spatial",1);return(0,i.createAttributeWithCacheKey)({epsilon:l,momentum:n,spatial:e})};const h=(c,l,n)=>{const e=(0,u.getGlsl)(c.session.backend.glContext.version),r=l[0].dims.length,[s,f]=c.calculateTextureWidthAndHeight(l[1].dims,d.TextureType.unpacked),g=` float process(int[${r}] indices) { vec2 position = offsetToCoords(indices[1], ${s}, ${f}); float scale = getColorAsFloat(${e.texture2D}(Scale, position)); float mean = getColorAsFloat(${e.texture2D}(Mean, position)); float variance = getColorAsFloat(${e.texture2D}(Variance, position)); float b = getColorAsFloat(${e.texture2D}(B, position)); return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n.epsilon})) ) + b; }`;return Object.assign(Object.assign({},a),{output:{dims:l[0].dims,type:l[0].type,textureType:d.TextureType.unpacked},shaderSource:g})},m=c=>{if(!c||c.length!==5)throw new Error("BatchNormalization requires 5 inputs.");const l=c[0],n=c[1],e=c[2],r=c[3],s=c[4];if(l.dims.length<3||n.dims.length!==1||e.dims.length!==1||r.dims.length!==1||s.dims.length!==1)throw new Error("invalid input shape.");if(n.dims[0]!==l.dims[1]||e.dims[0]!==l.dims[1]||r.dims[0]!==l.dims[1]||s.dims[0]!==l.dims[1])throw new Error("invalid input shape.");if(l.type!=="float32"&&l.type!=="float64"||n.type!=="float32"&&n.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||r.type!=="float32"&&r.type!=="float64"||s.type!=="float32"&&s.type!=="float64")throw new Error("invalid input tensor types.")}},7839:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.xor=t.sub=t.pRelu=t.pow=t.or=t.mul=t.less=t.greater=t.equal=t.div=t.and=t.add=t.glslPRelu=t.glslPow=t.glslXor=t.glslOr=t.glslAnd=t.glslLess=t.glslGreater=t.glslEqual=t.glslSub=t.glslMul=t.glslDiv=t.glslAdd=void 0;const i=o(2517),u=o(8520),d=o(5060),a=o(2039);function h(){const w="add_";return{body:` float ${w}(float a, float b) { return a + b; } vec4 ${w}(vec4 v1, vec4 v2) { return v1 + v2; } `,name:w,type:u.FunctionType.ValueBased}}function m(){const w="div_";return{body:` float ${w}(float a, float b) { return a / b; } vec4 ${w}(vec4 v1, vec4 v2) { return v1 / v2; } `,name:w,type:u.FunctionType.ValueBased}}function c(){const w="mul_";return{body:` float ${w}(float a, float b) { return a * b; } vec4 ${w}(vec4 v1, vec4 v2) { return v1 * v2; } `,name:w,type:u.FunctionType.ValueBased}}function l(){const w="sub_";return{body:` float ${w}(float a, float b) { return a - b; } vec4 ${w}(vec4 v1, vec4 v2) { return v1 - v2; } `,name:w,type:u.FunctionType.ValueBased}}function n(){const w="equal_";return{body:` float ${w}(float a, float b) { return float(a == b); } vec4 ${w}(vec4 v1, vec4 v2) { return vec4(equal(v1, v2)); } `,name:w,type:u.FunctionType.ValueBased}}function e(){const w="greater_";return{body:` float ${w}(float a, float b) { return float(a > b); } vec4 ${w}(vec4 v1, vec4 v2) { return vec4( v1.r > v2.r , v1.g > v2.g, v1.b > v2.b, v1.a > v2.a ); } `,name:w,type:u.FunctionType.ValueBased}}function r(){const w="less_";return{body:` float ${w}(float a, float b) { return float(a < b); } vec4 ${w}(vec4 v1, vec4 v2) { return vec4( v1.r < v2.r , v1.g < v2.g, v1.b < v2.b, v1.a < v2.a ); } `,name:w,type:u.FunctionType.ValueBased}}function s(){const w="and_";return{body:` float ${w}(float a, float b) { return float( bool(a) && bool(b) ); } vec4 ${w}(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:w,type:u.FunctionType.ValueBased}}function f(){const w="or_";return{body:` float ${w}(float a, float b) { return float( bool(a) || bool(b) ); } vec4 ${w}(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:w,type:u.FunctionType.ValueBased}}function g(){const w="xor_";return{body:` float ${w}(float a, float b) { return float( bool(a) ^^ bool(b) ); } vec4 ${w}(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:w,type:u.FunctionType.ValueBased}}function _(){return function(w){const v=`${w}_`;return{body:` float ${v}(float a, float b) { return ${w}(a, b); } vec4 ${v}(vec4 v1, vec4 v2) { return ${w}(v1, v2); } `,name:v,type:u.FunctionType.ValueBased}}("pow")}function b(){const w="prelu_";return{body:` float ${w}(float a, float b) { return a < 0.0 ? a * b: a; } vec4 ${w}(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:w,type:u.FunctionType.ValueBased}}t.glslAdd=h,t.glslDiv=m,t.glslMul=c,t.glslSub=l,t.glslEqual=n,t.glslGreater=e,t.glslLess=r,t.glslAnd=s,t.glslOr=f,t.glslXor=g,t.glslPow=_,t.glslPRelu=b;const y=(w,v,E,P=v[0].type,x)=>{const O=w.session.pack?a.TextureType.packed:a.TextureType.unpacked;return{name:E.name,inputNames:["A","B"],inputTypes:[O,O],cacheHint:x,get:()=>T(w,v,E,P)}},T=(w,v,E,P=v[0].type)=>{const x=w.session.pack?a.TextureType.packed:a.TextureType.unpacked,O=!i.ShapeUtil.areEqual(v[0].dims,v[1].dims);let $=v[0].dims;const k=w.session.pack;if(O){const V=i.BroadcastUtil.calcShape(v[0].dims,v[1].dims,!1);if(!V)throw new Error("Can't perform binary op on the given tensors");$=V;const C=$.length,B=v[0].dims.length!==0?v[0].dims.length:1,X=v[1].dims.length!==0?v[1].dims.length:1,G=v[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",ee=v[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",J=(0,d.getGlsl)(w.session.backend.glContext.version),ae=k?` ${E.body} void main() { vec4 a = getAAtOutCoords(); vec4 b = getBAtOutCoords(); vec4 result = ${E.name}(a, b); ${J.output} = result; }`:` ${E.body} float process(int indices[${C}]) { int aindices[${B}]; int bindices[${X}]; ${G} ${ee} return ${E.name}(_A(aindices), _B(bindices)); }`;return{name:E.name,inputNames:["A","B"],inputTypes:[x,x],output:{dims:$,type:P,textureType:x},shaderSource:ae,hasMain:k}}const N=(0,d.getGlsl)(w.session.backend.glContext.version),D=` ${E.body} void main() { vec4 v1 = ${N.texture2D}(A, TexCoords); vec4 v2 = ${N.texture2D}(B, TexCoords); vec4 result = ${E.name}(v1, v2); ${N.output} = result; } `;return{name:E.name,inputNames:["A","B"],inputTypes:[x,x],output:{dims:v[0].dims,type:P,textureType:x},shaderSource:D,hasMain:!0}};t.add=(w,v)=>[w.run(y(w,v,h()),v)],t.and=(w,v)=>[w.run(y(w,v,s(),"bool"),v)],t.div=(w,v)=>[w.run(y(w,v,m()),v)],t.equal=(w,v)=>[w.run(y(w,v,n(),"bool"),v)],t.greater=(w,v)=>[w.run(y(w,v,e(),"bool"),v)],t.less=(w,v)=>[w.run(y(w,v,r(),"bool"),v)],t.mul=(w,v)=>[w.run(y(w,v,c()),v)],t.or=(w,v)=>[w.run(y(w,v,f(),"bool"),v)],t.pow=(w,v)=>[w.run(y(w,v,_()),v)],t.pRelu=(w,v)=>[w.run(y(w,v,b()),v)],t.sub=(w,v)=>[w.run(y(w,v,l()),v)],t.xor=(w,v)=>[w.run(y(w,v,g(),"bool"),v)]},4196:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseCastAttributes=t.cast=void 0;const i=o(2517);t.cast=(d,a,h)=>(u(a),[d.cast(a[0],h)]),t.parseCastAttributes=d=>i.ProtoUtil.tensorDataTypeFromProto(d.attributes.getInt("to"));const u=d=>{if(!d||d.length!==1)throw new Error("Cast requires 1 input.");if(d[0].type==="string")throw new Error("Invalid input type.")}},1163:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createPackedConcatProgramInfoLoader=void 0;const i=o(5060),u=o(2039),d=o(9390),a=o(2827);t.createPackedConcatProgramInfoLoader=(m,c,l)=>{const n=(e=c.length,r=l.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:e},(s,f)=>`X${f}`),inputTypes:Array(e).fill(u.TextureType.packed),cacheHint:r});var e,r;return Object.assign(Object.assign({},n),{get:()=>((s,f,g,_)=>{const b=g[0].dims.slice();if(_>=b.length||_<-1*b.length)throw new Error("axis specified for concat doesn't match input dimensionality");_<0&&(_=b.length+_);const y=b.slice(0);for(let G=1;GG.dims),x=(0,d.getGlChannels)(T),O=new Array(P.length-1);O[0]=P[0][_];for(let G=1;G= ${O[G-1]}) { return getChannel( getX${G}(${h(x,$,ee)}), vec2(${h(k,$,ee)})); }`}const V=O.length,C=O[O.length-1];D+=` return getChannel( getX${V}(${h(x,$,C)}), vec2(${h(k,$,C)}));`;const B=(0,i.getGlsl)(s.session.backend.glContext.version),X=` ${E} float getValue(${x.map(G=>"int "+G)}) { ${D} } void main() { ${v} coords = getOutputCoords(); int lastDim = coords.${x[T-1]}; coords.${x[T-1]} = coords.${x[T-2]}; coords.${x[T-2]} = lastDim; vec4 result = vec4(getValue(${w}), 0., 0., 0.); ${w[T-1]} = ${w[T-1]} + 1; if (${w[T-1]} < ${y[T-1]}) { result.g = getValue(${w}); } ${w[T-2]} = ${w[T-2]} + 1; if (${w[T-2]} < ${y[T-2]}) { result.a = getValue(${w}); } ${w[T-1]} = ${w[T-1]} - 1; if (${w[T-2]} < ${y[T-2]} && ${w[T-1]} < ${y[T-1]}) { result.b = getValue(${w}); } ${B.output} = result; } `;return Object.assign(Object.assign({},f),{output:{dims:y,type:g[0].type,textureType:u.TextureType.packed},shaderSource:X,hasMain:!0})})(m,n,c,l.axis)})};const h=(m,c,l)=>{const n=m.indexOf(c);return m.map((e,r)=>r===n?`${e} - ${l}`:e).join()}},2069:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseConcatAttributes=t.concat=void 0;const i=o(246),u=o(2039),d=o(1163);t.concat=(e,r,s)=>(n(r),e.session.pack&&r[0].dims.length>1?[e.run((0,d.createPackedConcatProgramInfoLoader)(e,r,s),r)]:[e.run(a(e,r,s),r)]);const a=(e,r,s)=>{const f=(g=r.length,_=s.cacheKey,{name:"Concat",inputNames:Array.from({length:g},(b,y)=>`X${y}`),inputTypes:Array(g).fill(u.TextureType.unpacked),cacheHint:_});var g,_;return Object.assign(Object.assign({},f),{get:()=>((b,y,T,w)=>{const v=T[0].dims.slice();if(w>=v.length||w<-1*v.length)throw new Error("axis specified for concat doesn't match input dimensionality");w<0&&(w=v.length+w);const E=v.slice(0);for(let N=1;N`int getTextureWhereDataResides(int index) { ${e.map((r,s)=>`if(index<${r}) {return ${s};} `).join("")} }`,m=e=>h(e),c=(e,r)=>{const s=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${r}]) {`];for(let f=0;f{const r=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let s=0;s(0,i.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis")});const n=e=>{if(!e||e.length<1)throw new Error("too few inputs");const r=e[0].type,s=e[0].dims.length;if(r==="string")throw new Error("string tensor is not supported yet");for(const f of e){if(f.type!==r)throw new Error("input tensors should be one type");if(f.dims.length!==s)throw new Error("input tensors should have the same shape")}}},4770:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createUnpackedGroupedConvProgramInfoLoader=void 0;const i=o(6231),u=o(5060),d=o(2039),a=o(8138),h=o(2823);t.createUnpackedGroupedConvProgramInfoLoader=(m,c,l)=>{const n=(e=c.length>2,r=l.cacheKey,{name:"GroupedConv",inputNames:e?["X","W","Bias"]:["X","W"],inputTypes:e?[d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked]:[d.TextureType.unpacked,d.TextureType.unpacked],cacheHint:r});var e,r;return Object.assign(Object.assign({},n),{get:()=>((s,f,g,_)=>{const b=f.length>2?"value += getBias(output_channel);":"",y=f[0].dims.slice(),T=f[1].dims.slice(),w=T[0]/_.group;i.Logger.verbose("GroupedConv",`autpPad:${_.autoPad}, dilations:${_.dilations}, group:${_.group}, kernelShape:${_.kernelShape}, pads:${_.pads}, strides:${_.strides}`);const v=(0,a.calculateOutputShape)(y,T,_.dilations,_.pads,_.strides),E=(0,u.getGlsl)(s.session.backend.glContext.version),{activationFunction:P,applyActivation:x}=(0,h.getActivationSnippet)(_),O=` const ivec2 strides = ivec2(${_.strides[0]}, ${_.strides[1]}); const ivec2 pads = ivec2(${_.pads[0]}, ${_.pads[1]}); ${P} 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 / ${w}; float value = 0.0; for (int wInChannel = 0; wInChannel < ${T[1]}; wInChannel++) { int input_channel = group_id * ${T[1]} + wInChannel; for (int wHeight = 0; wHeight < ${T[2]}; wHeight++) { int xHeight = xRCCorner.x + wHeight * ${_.dilations[0]}; if (xHeight < 0 || xHeight >= ${y[2]}) { continue; } for (int wWidth = 0; wWidth < ${T[3]}; wWidth++) { int xWidth = xRCCorner.y + wWidth * ${_.dilations[1]}; if (xWidth < 0 || xWidth >= ${y[3]}) { continue; } float xVal = getX(batch, input_channel, xWidth, xHeight); float wVal = getW(output_channel, wInChannel, wWidth, wHeight); value += xVal*wVal; } } } ${b} ${x} ${E.output} = vec4(value, .0, .0, .0); } `;return Object.assign(Object.assign({},g),{output:{dims:v,type:f[0].type,textureType:d.TextureType.unpacked},shaderSource:O,hasMain:!0})})(m,c,n,l)})}},1386:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.conv2DPacked=t.conv2DPackedPointwise=void 0;const i=o(8138),u=o(8555),d=o(708);t.conv2DPackedPointwise=(a,h,m)=>{const c=h[0].dims,l=h[1].dims,n=(0,i.calculateOutputShape)(c,l,m.dilations,m.pads,m.strides),e=a.reshapePacked(h[0],[c[1],c[2]*c[3]]),r=a.reshapePacked(h[1],[l[0],l[1]]),s=h.length>2?[r,e,h[2]]:[r,e],f=a.run((0,d.createPackedMatmulProgramInfoLoader)(a,s,m),s);return a.reshapePacked(f,n)},t.conv2DPacked=(a,h,m)=>{const c=h[0].dims,l=h[1].dims,n=(0,i.calculateOutputShape)(c,l,m.dilations,m.pads,m.strides),e=a.run((0,u.createPackedIm2ColProgramInfoLoader)(a,h[0],h[1],n,m),[h[0]]),r=a.reshapePacked(h[1],[l[0],l[1]*l[2]*l[3]]),s=h.length===3?[r,e,h[2]]:[r,e],f=a.run((0,d.createPackedMatmulProgramInfoLoader)(a,s,m),s);return a.reshapePacked(f,n)}},9663:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseConvTransposeAttributes=t.convTranspose=void 0;const i=o(246),u=o(5060),d=o(2039),a=o(2823),h=(r,s,f,g,_,b)=>(r-1)*s+f+(g-1)*_+1-b,m=(r,s,f,g,_)=>{const b=Math.floor(r/2);s==="SAME_UPPER"?(f[g]=b,f[_]=r-b):s==="SAME_LOWER"&&(f[g]=r-b,f[_]=b)};t.convTranspose=(r,s,f)=>(e(s,f),c(r,s,f));const c=(r,s,f)=>{const g=n(f,s);return[l(r,s,g)]},l=(r,s,f)=>r.run(((g,_,b)=>{const y=(T=_.length>2,w=b.cacheKey,{name:"ConvTranspose",inputNames:T?["X","W","B"]:["X","W"],inputTypes:T?[d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked]:[d.TextureType.unpacked,d.TextureType.unpacked],cacheHint:w});var T,w;return Object.assign(Object.assign({},y),{get:()=>((v,E,P,x)=>{const O=E.length>2?"getB(output_channel)":"0.0",$=E[0].dims,k=E[1].dims,N=k[1],D=k[0]/x.group,V=[E[0].dims[0],E[1].dims[1]*x.group,...x.outputShape],C=(0,u.getGlsl)(v.session.backend.glContext.version),{activationFunction:B,applyActivation:X}=(0,a.getActivationSnippet)(x),G=` const ivec2 strides = ivec2(${x.strides[0]}, ${x.strides[1]}); const ivec2 pads = ivec2(${x.pads[0]}, ${x.pads[1]}); ${B} void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; int output_channel = coords.y; ivec2 loc = coords.zw + pads; int group_id = output_channel / ${N}; int wOutChannel = output_channel - group_id * ${N}; float value = ${O}; for (int inChannelOffset = 0; inChannelOffset < ${D}; inChannelOffset++) { int input_channel = group_id * ${D} + inChannelOffset; for (int wWOff = 0; wWOff < ${k[2]}; wWOff++) { for (int wHOff = 0; wHOff < ${k[3]}; wHOff++) { ivec2 wOff = ivec2(wWOff * ${x.dilations[0]}, wHOff * ${x.dilations[1]}); ivec2 wLoc = loc - wOff; ivec2 wLocIn = wLoc / strides; if ( wLocIn * strides == wLoc && wLocIn.x >= 0 && wLocIn.x < ${$[2]} && wLocIn.y >= 0 && wLocIn.y < ${$[3]} ) { float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); value += xVal * wVal; } } } } ${X} ${C.output} = vec4(value, .0, .0, .0); } `;return Object.assign(Object.assign({},P),{output:{dims:V,type:E[0].type,textureType:d.TextureType.unpacked},shaderSource:G,hasMain:!0})})(g,_,y,b)})})(r,s,f),s),n=(r,s)=>{const f=r.kernelShape.slice();if(r.kernelShape.length===0)for(let y=2;y{const $=y.length-2,k=O.length===0;for(let N=0;N<$;++N){const D=k?y[N+2]*P[N]:O[N],V=h(y[N+2],P[N],E[N],T[N],w[N],D);m(V,v,E,N,N+$),k&&O.push(P[N]*(y[N+2]-1)+x[N]+(T[N]-1)*w[N]+1-E[N]-E[N+$])}})(s[0].dims,f,r.dilations,r.autoPad,g,r.strides,r.outputPadding,_);const b=Object.assign({},r);return Object.assign(b,{kernelShape:f,pads:g,outputShape:_,cacheKey:r.cacheKey}),b};t.parseConvTransposeAttributes=r=>{const s=r.attributes,f=(0,a.parseInternalActivationAttributes)(s),g=s.getString("auto_pad","NOTSET"),_=s.getInts("dilations",[1,1]),b=s.getInt("group",1),y=s.getInts("kernel_shape",[]),T=s.getInts("output_padding",[0,0]),w=s.getInts("output_shape",[]),v=s.getInts("pads",[0,0,0,0]),E=s.getInts("strides",[1,1]);return(0,i.createAttributeWithCacheKey)(Object.assign({autoPad:g,dilations:_,group:b,kernelShape:y,outputPadding:T,outputShape:w,pads:v,strides:E},f))};const e=(r,s)=>{if(!r||r.length!==2&&r.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(r[0].dims.length!==4||r[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");if(r[0].dims[1]!==r[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const f=r[1].dims[1]*s.group;if(r.length===3&&(r[2].dims.length!==1||r[2].dims[0]!==f))throw new Error("invalid bias");const g=r[0].dims.length-2;if(s.dilations.length!==g)throw new Error(`dilations should be ${g}D`);if(s.strides.length!==g)throw new Error(`strides should be ${g}D`);if(s.pads.length!==2*g)throw new Error(`pads should be ${2*g}D`);if(s.outputPadding.length!==g)throw new Error(`output_padding should be ${g}D`);if(s.kernelShape.length!==0&&s.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape");if(s.outputShape.length!==0&&s.outputShape.length!==r[0].dims.length-2)throw new Error("invalid output shape");if(r[0].type!=="float32"||r[1].type!=="float32")throw new Error("ConvTranspose input(X,W) should be float tensor");if(r.length===3&&r[2].type!=="float32")throw new Error("ConvTranspose input(bias) should be float tensor")}},8138:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseConvAttributes=t.conv=t.calculateOutputShape=void 0;const i=o(246),u=o(2517),d=o(4770),a=o(1386),h=o(9828),m=o(2823),c=o(3248),l=o(5623);t.calculateOutputShape=(g,_,b,y,T)=>{const w=g[0],v=g.slice(2),E=v.length,P=_[0],x=_.slice(2).map(($,k)=>$+($-1)*(b[k]-1)),O=v.map(($,k)=>$+y[k]+y[k+E]).map(($,k)=>Math.floor(($-x[k]+T[k])/T[k]));return[w,P].concat(...O)},t.conv=(g,_,b)=>(f(_,b),n(g,_,b));const n=(g,_,b)=>{const y=s(b,_),T=g.session.pack,w=y.kernelShape[0]===1&&y.kernelShape[1]===1;return y.group>1?[g.run((0,d.createUnpackedGroupedConvProgramInfoLoader)(g,_,y),_)]:w&&T?[e(g,_,y)]:T&&_[0].dims.length===4&&_[0].dims[0]===1&&!w?[(0,a.conv2DPacked)(g,_,y)]:[r(g,_,y)]},e=(g,_,b)=>{const y=_[0].dims,T=_[1].dims,w=(0,t.calculateOutputShape)(y,T,b.dilations,b.pads,b.strides),v=g.reshapeUnpacked(_[0],[y[1],y[2]*y[3]]),E=g.reshapeUnpacked(_[1],[T[0],T[1]]),P=_.length>2?[E,v,_[2]]:[E,v],x=g.run((0,l.createMatmulProgramInfoLoader)(P,b),P);return g.reshapeUnpacked(x,w)},r=(g,_,b)=>{const y=_[0].dims,T=_[1].dims,w=(0,t.calculateOutputShape)(y,T,b.dilations,b.pads,b.strides),v=g.run((0,c.createIm2ColProgramInfoLoader)(g,_[0],_[1],w,b),[_[0]]),E=_.length===3?[v,_[1],_[2]]:[v,_[1]];return g.run((0,h.createDotProductProgramInfoLoader)(g,_,w,b),E)},s=(g,_)=>{const b=g.kernelShape.slice();if(g.kernelShape.length===0)for(let w=2;w<_[1].dims.length;++w)b.push(_[1].dims[w]);const y=g.pads.slice();u.PoolConvUtil.adjustPadsBasedOnAutoPad(_[0].dims,g.strides,g.dilations,b,y,g.autoPad);const T=Object.assign({},g);return Object.assign(T,{kernelShape:b,pads:y,cacheKey:g.cacheKey}),T};t.parseConvAttributes=g=>{const _=g.attributes,b=(0,m.parseInternalActivationAttributes)(_),y=_.getString("auto_pad","NOTSET"),T=_.getInts("dilations",[1,1]),w=_.getInt("group",1),v=_.getInts("kernel_shape",[]),E=_.getInts("pads",[0,0,0,0]),P=_.getInts("strides",[1,1]);return(0,i.createAttributeWithCacheKey)(Object.assign({autoPad:y,dilations:T,group:w,kernelShape:v,pads:E,strides:P},b))};const f=(g,_)=>{if(!g||g.length!==2&&g.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(g[0].dims.length!==4||g[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");if(g[0].dims[1]!==g[1].dims[1]*_.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(g.length===3&&(g[2].dims.length!==1||g[1].dims[0]!==g[2].dims[0]))throw new Error("invalid bias");const b=g[0].dims.length-2;if(_.dilations.length!==b)throw new Error(`dilations should be ${b}D`);if(_.strides.length!==b)throw new Error(`strides should be ${b}D`);if(_.pads.length!==2*b)throw new Error(`pads should be ${2*b}D`);if(_.kernelShape.length!==0&&_.kernelShape.length!==g[1].dims.length-2)throw new Error("invalid kernel shape");if(g[0].type!=="float32"||g[1].type!=="float32")throw new Error("Conv input(X,W) should be float tensor");if(g.length===3&&g[2].type!=="float32")throw new Error("Conv input(bias) should be float tensor")}},5193:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDepthToSpaceAttributes=t.depthToSpace=void 0;const i=o(3738);t.depthToSpace=(d,a,h)=>{u(a);const m=h.blocksize,c=m*m,l=h.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],n=h.mode==="DCR"?[a[0].dims[0],m,m,a[0].dims[1]/c,a[0].dims[2],a[0].dims[3]]:[a[0].dims[0],a[0].dims[1]/c,m,m,a[0].dims[2],a[0].dims[3]],e=d.reshapeUnpacked(a[0],n),r={perm:l,cacheKey:`${l}`},[s]=(0,i.transpose)(d,[e],r),f=[a[0].dims[0],a[0].dims[1]/c,a[0].dims[2]*m,a[0].dims[3]*m];return[d.reshapeUnpacked(s,f)]},t.parseDepthToSpaceAttributes=d=>{const a=d.attributes.getInt("blocksize");if(a<1)throw new Error(`blocksize must be >= 1, but got : ${a} for DepthToSpace`);const h=d.attributes.getString("mode","DCR");if(h!=="DCR"&&h!=="CRD")throw new Error(`unrecognized mode: ${h} for DepthToSpace`);return{mode:h,blocksize:a}};const u=d=>{if(d.length!==1)throw new Error(`DepthToSpace expect 1 inputs, but got ${d.length}`);if(d[0].type==="string"||d[0].dims.length!==4)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},9828:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createDotProductProgramInfoLoader=void 0;const i=o(2517),u=o(5060),d=o(2039),a=o(2823),h=o(3248);t.createDotProductProgramInfoLoader=(m,c,l,n)=>{const e=((r,s)=>({name:"ConvDotProduct",inputNames:r?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:r?[d.TextureType.unpacked,d.TextureType.packedLastDimension,d.TextureType.unpacked]:[d.TextureType.unpacked,d.TextureType.packedLastDimension],cacheKey:s.activationCacheKey}))(c.length>2,n);return Object.assign(Object.assign({},e),{get:()=>((r,s,f,g,_)=>{const b=f[0].dims,y=f[1].dims,T=[y[0],Math.ceil(b[1]*y[2]*y[3]/4)],w=(0,h.calculateIm2ColDims)(b,y,g),[v,E]=r.calculateTextureWidthAndHeight(T,d.TextureType.packedLastDimension),P=i.ShapeUtil.computeStrides(w),[x,O]=r.calculateTextureWidthAndHeight(w,d.TextureType.packedLastDimension),$=g.length,k=f.length<3?"0.0":"_B(b)",N=Math.ceil(b[1]*y[2]*y[3]/4),{activationFunction:D,applyActivation:V}=(0,a.getActivationSnippet)(_),C=(0,u.getGlsl)(r.session.backend.glContext.version),B=` ${D} float process(int indices[${$}]) { int b[1]; b[0] = indices[1]; int im2col[4]; im2col[0] = indices[0]; im2col[1] = indices[2]; im2col[2] = indices[3]; int im2colOffset = im2col[0] * ${P[0]} + im2col[1] * ${P[1]} + im2col[2] * ${P[2]}; int kernelOffset = indices[1] * ${T[1]}; float value = ${k}; for (int i = 0; i < ${N}; ++i) { vec2 im2colCoords = offsetToCoords(im2colOffset, ${x}, ${O}); vec2 kernelCoords = offsetToCoords(kernelOffset, ${v}, ${E}); value += dot(${C.texture2D}(Im2Col, im2colCoords), ${C.texture2D}(K, kernelCoords)); ++im2colOffset; ++kernelOffset; } ${V} return value; }`;return Object.assign(Object.assign({},s),{output:{dims:g,type:f[0].type,textureType:d.TextureType.unpacked},shaderSource:B})})(m,e,c,l,n)})}},7992:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseFlattenAttributes=t.flatten=void 0;const i=o(2517);t.flatten=(d,a,h)=>{u(a,h);const m=i.ShapeUtil.flattenShape(a[0].dims,h);return[d.reshapeUnpacked(a[0],m)]},t.parseFlattenAttributes=d=>d.attributes.getInt("axis",1);const u=(d,a)=>{if(!d||d.length!==1)throw new Error("Flatten requires 1 input.");const h=d[0].dims.length;if(h===0)throw new Error("scalar tensor is not supported.");if(a<-h||a>h)throw new Error("Invalid axis");if(d[0].type==="string")throw new Error("string tensor is not supported.")}},2823:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseInternalActivationAttributes=t.getActivationSnippet=void 0;const i=o(2517),u=o(4909);t.getActivationSnippet=function(d){let a;switch(d.activation){case"Relu":a=(0,u.glslRelu)();break;case"Sigmoid":a=(0,u.glslSigmoid)();break;case"Clip":a=(0,u.glslClip)(d.clipMin,d.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const h=a.name;return{activationFunction:a.body,applyActivation:`value = ${h}_(value);`}},t.parseInternalActivationAttributes=d=>{const a=d.getString("activation","");if(a==="Clip"){const[h,m]=d.getFloats("activation_params",[i.MIN_CLIP,i.MAX_CLIP]);return{activation:a,clipMax:m,clipMin:h,activationCacheKey:`${a}:${h},${m}`}}return{activation:a,activationCacheKey:a}}},1253:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseGatherAttributes=t.gather=void 0;const i=o(246),u=o(782),d=o(2517),a=o(2039);t.gather=(l,n,e)=>(c(n,e.axis),[l.run(m(l,n,e),n)]),t.parseGatherAttributes=l=>(0,i.createAttributeWithCacheKey)({axis:l.attributes.getInt("axis",0)});const h={name:"Gather",inputNames:["A","B"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked]},m=(l,n,e)=>{const r=Object.assign(Object.assign({},h),{cacheHint:e.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((s,f,g,_)=>{const b=g[0].dims.slice(),y=g[1].dims.slice(),T=new Array(b.length+y.length-1);_=d.ShapeUtil.normalizeAxis(_,b.length);const w=[];for(let E=0;E{if(!l||l.length!==2)throw new Error("Gather requires 2 inputs.");const e=l[0].dims.length;if(e<1)throw new Error("Invalid input shape.");if(n<-e||n>e-1)throw new Error("Invalid axis.");if(u.NUMBER_TYPES.indexOf(l[0].type)===-1)throw new Error("Invaid input type.");if(l[1].type!=="int32"&&l[1].type!=="int16")throw new Error("Invaid input type.")}},4776:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseGemmAttributesV11=t.parseGemmAttributesV7=t.gemm=void 0;const i=o(246),u=o(2517),d=o(2039);t.gemm=(l,n,e)=>(c(n,e),[l.run(h(n,e),n)]);const a=(l,n)=>{const e=l.attributes.getInt("transA",0)!==0,r=l.attributes.getInt("transB",0)!==0,s=l.attributes.getFloat("alpha",1),f=l.attributes.getFloat("beta",1);return(0,i.createAttributeWithCacheKey)({transA:e,transB:r,alpha:s,beta:f,isOptionalC:n})};t.parseGemmAttributesV7=l=>a(l,!1),t.parseGemmAttributesV11=l=>a(l,!0);const h=(l,n)=>{const e={name:"Gemm",inputNames:l.length===3?["A","B","C"]:["A","B"],inputTypes:l.length===3?[d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked]:[d.TextureType.unpacked,d.TextureType.unpacked],key:n.cacheKey};return Object.assign(Object.assign({},e),{get:()=>m(e,l,n)})},m=(l,n,e)=>{const r=n[0].dims.slice(),s=n[1].dims.slice(),[f,g]=u.GemmUtil.getShapeOfGemmResult(r,e.transA,s,e.transB,n.length===3?n[2].dims:void 0),_=[f,g];if(!_)throw new Error("Can't use gemm on the given tensors");let b=r[r.length-1],y="";e.transA&&(b=r[0]),e.transA&&e.transB?y="value += _A_T(a) * _B_T(b);":e.transA&&!e.transB?y="value += _A_T(a) * _B(b);":!e.transA&&e.transB?y="value += _A(a) * _B_T(b);":e.transA||e.transB||(y="value += _A(a) * _B(b);");const T=_.length,w=` float process(int indices[${T}]) { int a[${T}]; int b[${T}]; ${n.length===3?`int c[${n[2].dims.length}];`:""} copyVec(indices, a); copyVec(indices, b); ${n.length===3?"bcastIndices_C(indices, c);":""} float value = 0.0; for (int k=0; k<${b}; ++k) { a[${T-1}] = k; b[${T-2}] = k; ${y} } value = value * alpha; ${n.length===3?"value += beta * _C(c);":""} return value; }`;return Object.assign(Object.assign({},l),{output:{dims:_,type:n[0].type,textureType:d.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:e.alpha},{name:"beta",type:"float",data:e.beta}],shaderSource:w})},c=(l,n)=>{if(!l)throw new Error("Input is missing");if(n.isOptionalC&&(l.length<2||l.length>3))throw new Error("Invaid input shape.");if(!n.isOptionalC&&l.length!==3)throw new Error("Gemm requires 3 inputs");if(l.length===3&&l[2].dims.length!==1&&l[2].dims.length!==2)throw new Error("Invalid input shape of C");if(l[0].type!=="float32"&&l[0].type!=="float64"||l[1].type!=="float32"&&l[1].type!=="float64"||l.length===3&&l[2].type!=="float32"&&l[2].type!=="float64")throw new Error("Invalid input type.");if(l[0].type!==l[1].type||l.length===3&&l[0].type!==l[2].type)throw new Error("Input types are mismatched")}},8555:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createPackedIm2ColProgramInfoLoader=void 0;const i=o(5060),u=o(2039),d=o(2827);t.createPackedIm2ColProgramInfoLoader=(a,h,m,c,l)=>{const n=(e=l.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[u.TextureType.packed],cacheHint:e});var e;return Object.assign(Object.assign({},n),{get:()=>((r,s,f,g,_,b)=>{const y=f.dims,T=g.dims,w=_.length,v=[T[1]*T[2]*T[3],_[2]*_[3]],E=T[2]*T[3],P=(0,d.unpackFromChannel)(),x=(0,i.getGlsl)(r.session.backend.glContext.version);let O="";for(let k=0;k<=1;k++)for(let N=0;N<=1;N++)O+=` blockIndex = rc.x + ${N}; pos = rc.y + ${k}; if(blockIndex < ${v[1]} && pos < ${v[0]}) { offsetY = int(blockIndex / (${_[w-1]})) * ${b.strides[0]} - ${b.pads[0]}; d0 = offsetY + ${b.dilations[0]} * (imod(pos, ${E}) / ${T[2]}); if(d0 < ${y[2]} && d0 >= 0) { offsetX = imod(blockIndex, ${_[w-1]}) * ${b.strides[1]} - ${b.pads[1]}; d1 = offsetX + ${b.dilations[1]} * imod(imod(pos, ${E}), ${T[2]}); if(d1 < ${y[3]} && d1 >= 0) { ch = int(float(pos)/ ${E}.); innerDims = vec2(d0, d1); result[${2*k+N}] = getChannel( getA(0, ch, int(innerDims.x), int(innerDims.y)), innerDims); } } } `;const $=` ${P} void main() { ivec2 rc = getOutputCoords(); vec4 result = vec4(0.0); int blockIndex, pos, offsetY, d0, offsetX, d1, ch; vec2 innerDims; ${O} ${x.output} = result; } `;return Object.assign(Object.assign({},s),{output:{dims:v,type:f.type,textureType:u.TextureType.packed},shaderSource:$,hasMain:!0})})(a,n,h,m,c,l)})}},3248:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.calculateIm2ColDims=t.createIm2ColProgramInfoLoader=void 0;const i=o(2039);t.createIm2ColProgramInfoLoader=(u,d,a,h,m)=>{const c=(l=m.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[i.TextureType.unpacked],cacheHint:l});var l;return Object.assign(Object.assign({},c),{get:()=>((n,e,r,s,f,g)=>{const _=r.dims,b=s.dims,y=f.length,T=(0,t.calculateIm2ColDims)(_,b,f,4),w=` const int XC = ${_[1]}; const int XH = ${_[2]}; const int XW = ${_[3]}; const int KH = ${g.kernelShape[0]}; const int KW = ${g.kernelShape[1]}; const int dilationH = ${g.dilations[0]}; const int dilationW = ${g.dilations[1]}; const int strideH = ${g.strides[0]}; const int strideW = ${g.strides[1]}; const int padH = ${g.pads[0]}; const int padW = ${g.pads[1]}; const int KHKW = KH*KW; const int XCKHKW = XC * KHKW; const int outputChannels = 4; vec4 process(int indices[${y}]) { 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[${_.length}]; x[0] = b; x[1] = patchC; x[2] = xh2; x[3] = xw2; if(xh2 >= 0 && xh2 < XH && xw2 >= 0 && xw2 < XW) { value[i] = _X(x); } } ++p; } return value; } `;return Object.assign(Object.assign({},e),{output:{dims:T,type:r.type,textureType:i.TextureType.packedLastDimension},shaderSource:w})})(0,c,d,a,h,m)})},t.calculateIm2ColDims=(u,d,a,h=4)=>[a[0],a[2],a[3],Math.ceil(u[1]*d[2]*d[3]/h)]},6572:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseImageScalerAttributes=t.imageScaler=void 0;const i=o(246),u=o(2039);t.imageScaler=(c,l,n)=>(m(l),[c.run(a(c,l,n),l)]),t.parseImageScalerAttributes=c=>{const l=c.attributes.getFloat("scale"),n=c.attributes.getFloats("bias");return(0,i.createAttributeWithCacheKey)({scale:l,bias:n})};const d={name:"ImageScaler",inputNames:["X"],inputTypes:[u.TextureType.unpacked]},a=(c,l,n)=>{const e=Object.assign(Object.assign({},d),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},e),{get:()=>((r,s,f,g)=>{const _=f[0].dims.slice(),b=_.length,y=` ${h(g.bias.length)} float process(int indices[${b}]) { return _X(indices) * scale + getBias(bias, indices[1]); }`;return Object.assign(Object.assign({},s),{output:{dims:_,type:f[0].type,textureType:u.TextureType.unpacked},variables:[{name:"bias",type:"float",arrayLength:g.bias.length,data:g.bias},{name:"scale",type:"float",data:g.scale}],shaderSource:y})})(0,e,l,n)})},h=c=>{const l=[`float getBias(float bias[${c}], int channel) {`];for(let n=0;n{if(!c||c.length!==1)throw new Error("ImageScaler requires 1 input.");if(c[0].dims.length!==4)throw new Error("Invalid input shape.");if(c[0].type!=="float32"&&c[0].type!=="float64")throw new Error("Invalid input type.")}},3346:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseInstanceNormalizationAttributes=t.instanceNormalization=void 0;const i=o(5060),u=o(2039);t.instanceNormalization=(l,n,e)=>{c(n);const r=l.run(a(n[0]),n);return[l.run(m(l,n[0],e,r.dims),[n[0],r,n[1],n[2]])]},t.parseInstanceNormalizationAttributes=l=>l.attributes.getFloat("epsilon",1e-5);const d={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[u.TextureType.unpacked]},a=l=>Object.assign(Object.assign({},d),{get:()=>((n,e)=>{const r=e.dims.slice(),s=r[1],f=r[2]*r[3],g=[r[0],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<${r[2]}; a2++) { a[2] = a2; for(int a3=0; a3<${r[3]}; a3++) { a[3] = a3; float x = _X(a); temp += x; } } float mean = temp / float(${f}); temp = 0.0; for(int a2=0; a2<${r[2]}; a2++) { a[2] = a2; for(int a3=0; a3<${r[3]}; a3++) { a[3] = a3; float x = _X(a); temp += (x - mean) * (x - mean); } } v.r = mean; v.g = temp / float(${f}); return v; }`;return Object.assign(Object.assign({},n),{output:{dims:g,type:e.type,textureType:u.TextureType.packedLastDimension},shaderSource:_})})(d,l)}),h={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[u.TextureType.unpacked,u.TextureType.packedLastDimension,u.TextureType.unpacked,u.TextureType.unpacked]},m=(l,n,e,r)=>{const s=Object.assign(Object.assign({},h),{cacheHint:`${e}`});return Object.assign(Object.assign({},s),{get:()=>((f,g,_,b,y)=>{const T=(0,i.getGlsl)(f.session.backend.glContext.version),[w,v]=f.calculateTextureWidthAndHeight(y,u.TextureType.packedLastDimension),[E,P]=[w/4,v],x=` vec4 get_MeanAndVariance(int[2] mv) { int offset = indicesToOffset_MeanAndVariance(mv); vec2 coords = offsetToCoords(offset, ${E}, ${P}); return ${T.texture2D}(MeanAndVariance, coords); } float process(int[4] indices) { int mv[2]; mv[0] = indices[0]; mv[1] = indices[1]; vec4 mean_and_variance = get_MeanAndVariance(mv); float mean = mean_and_variance.r; float variance = mean_and_variance.g; int sb[1]; sb[0] = indices[1]; float scale = _Scale(sb); float b = _B(sb); return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; }`;return Object.assign(Object.assign({},g),{output:{dims:_.dims,type:_.type,textureType:u.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:b}],shaderSource:x})})(l,s,n,e,r)})},c=l=>{if(!l||l.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");const n=l[0],e=l[1],r=l[2];if(n.dims.length<3||e.dims.length!==1||r.dims.length!==1)throw new Error("Invalid input shape.");if(e.dims[0]!==n.dims[1]||r.dims[0]!==n.dims[1])throw new Error("Input shapes are mismatched.");if(n.type!=="float32"&&n.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||r.type!=="float32"&&r.type!=="float64")throw new Error("Invalid input type.");if(l[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}},708:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createPackedMatmulProgramInfoLoader=void 0;const i=o(2517),u=o(5060),d=o(2039),a=o(9390),h=o(2823),m=o(5623);t.createPackedMatmulProgramInfoLoader=(c,l,n)=>{const e=(r=l.length>2,s=n.activationCacheKey,{name:"MatMul (packed)",inputNames:r?["A","B","Bias"]:["A","B"],inputTypes:r?[d.TextureType.packed,d.TextureType.packed,d.TextureType.packed]:[d.TextureType.packed,d.TextureType.packed],cacheHint:s});var r,s;return Object.assign(Object.assign({},e),{get:()=>((f,g,_,b)=>{const y=_.length>2,T=y?"value += getBiasForMatmul();":"",w=_[0].dims,v=_[1].dims,E=i.BroadcastUtil.calcShape(w,v,!0),P=!i.ShapeUtil.areEqual(_[0].dims,_[1].dims);if(!E)throw new Error("Can't use matmul on the given tensors");const x=w[w.length-1],O=Math.ceil(x/2),$=w.length,k=v.length,N=(0,u.getGlsl)(f.session.backend.glContext.version),D=(0,a.getCoordsDataType)(E.length),V=E.length,C=(0,a.getGlChannels)(),{activationFunction:B,applyActivation:X}=(0,h.getActivationSnippet)(b),G=y?`${(0,m.getBiasForMatmul)(D,C,_[2].dims,E,!0)}`:"",ee=P?`${function(xe,le,we,be){let ke=[],Le=[];const ve=we[0].dims,$e=we[1].dims,Fe=ve.length,Me=$e.length,Pe=be.length,je=Pe-Fe,Ue=Pe-Me;ke=ve.map((Oe,Be)=>`coords.${le[Be+je]}`),ke[Fe-1]="i*2",ke.join(", "),Le=$e.map((Oe,Be)=>`coords.${le[Be+Ue]}`),Le[Me-2]="i*2",Le.join(", ");const Ge=i.BroadcastUtil.getBroadcastDims(ve,be),Ye=i.BroadcastUtil.getBroadcastDims($e,be),Qe=Ge.map(Oe=>`coords.${le[Oe+je]} = 0;`).join(` `),qe=Ye.map(Oe=>`coords.${le[Oe+Ue]} = 0;`).join(` `),Ve=`int lastDim = coords.${le[Pe-1]}; coords.${le[Pe-1]} = coords.${le[Pe-2]}; coords.${le[Pe-2]} = lastDim;`;return` vec4 getAAtOutCoordsMatmul(int i) { ${xe} coords = getOutputCoords(); ${Ve} ${Qe} vec4 outputValue = getA(${ke}); return outputValue; } vec4 getBAtOutCoordsMatmul(int i) { ${xe} coords = getOutputCoords(); ${Ve} ${qe} vec4 outputValue = getB(${Le}); return outputValue; }`}(D,C,_,E)}`:"",J=P?"getAAtOutCoordsMatmul(i)":`getA(${function(xe,le){let we="";for(let be=0;be{Object.defineProperty(t,"__esModule",{value:!0}),t.getBiasForMatmul=t.createMatmulProgramInfoLoader=t.parseMatMulAttributes=t.matMul=void 0;const i=o(2517),u=o(2039),d=o(9390),a=o(2823),h=o(708);function m(n,e){const r=(s=n.length>2,f=e.activationCacheKey,{name:"MatMul",inputNames:s?["A","B","Bias"]:["A","B"],inputTypes:s?[u.TextureType.unpacked,u.TextureType.unpacked,u.TextureType.unpacked]:[u.TextureType.unpacked,u.TextureType.unpacked],cacheHint:f});var s,f;return Object.assign(Object.assign({},r),{get:()=>function(g,_,b){const y=_[0].dims,T=_[1].dims,w=i.BroadcastUtil.calcShape(y,T,!0);if(!w)throw new Error("Can't use matmul on the given tensors");const v=(0,d.getCoordsDataType)(w.length),E=(0,d.getGlChannels)(),{activationFunction:P,applyActivation:x}=(0,a.getActivationSnippet)(b),O=_.length>2,$=O?"value += getBiasForMatmul();":"",k=O?`${l(v,E,_[2].dims,w,!1)}`:"",N=w.length,D=y.length,V=T.length,C=` ${P} ${k} float process(int indices[${N}]) { int a[${D}]; int b[${V}]; bcastMatmulIndices_A(indices, a); bcastMatmulIndices_B(indices, b); float value; for (int k=0; k<${y[y.length-1]}; ++k) { a[${D-1}] = k; b[${V-2}] = k; value += _A(a) * _B(b); } ${$} ${x} return value; }`;return Object.assign(Object.assign({},g),{output:{dims:w,type:_[0].type,textureType:u.TextureType.unpacked},shaderSource:C})}(r,n,e)})}t.matMul=(n,e,r)=>(c(e),n.session.pack?[n.run((0,h.createPackedMatmulProgramInfoLoader)(n,e,r),e)]:[n.run(m(e,r),e)]),t.parseMatMulAttributes=n=>(0,a.parseInternalActivationAttributes)(n.attributes),t.createMatmulProgramInfoLoader=m;const c=n=>{if(!n||n.length!==2)throw new Error("MatMul requires 2 inputs.");if(n[0].dims[n[0].dims.length-1]!==n[1].dims[n[1].dims.length-2])throw new Error("shared dimension does not match.");if(n[0].type!=="float32"&&n[0].type!=="float64"||n[1].type!=="float32"&&n[1].type!=="float64")throw new Error("inputs should be float type");if(n[0].type!==n[1].type)throw new Error("inputs types should match")};function l(n,e,r,s,f){let g="";const _=r.length,b=s.length,y=b-_;g=b<2&&_>0?"coords":r.map((v,E)=>`coords.${e[E+y]}`).join(", ");const T=i.BroadcastUtil.getBroadcastDims(r,s).map(v=>`coords.${e[v+y]} = 0;`).join(` `);let w="vec4(outputValue.xx, outputValue.yy)";return i.ShapeUtil.size(r)===1&&(w="vec4(outputValue.x)"),f?` vec4 getBiasForMatmul() { ${n} coords = getOutputCoords(); ${T} vec4 outputValue = getBias(${g}); return ${w}; }`:` float getBiasForMatmul() { ${n} coords = getOutputCoords(); ${T} return getBias(coords.x); }`}t.getBiasForMatmul=l},2403:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createPackProgramInfoLoader=void 0;const i=o(5060),u=o(2039),d=o(9390),a=o(2827),h={name:"pack",inputNames:["A"],inputTypes:[u.TextureType.unpackedReversed]};t.createPackProgramInfoLoader=(m,c)=>Object.assign(Object.assign({},h),{get:()=>((l,n)=>{const e=(0,i.getGlsl)(l.session.backend.glContext.version),r=n.dims,s=r.length,f=n.dims.length,g=(0,d.getCoordsDataType)(f),_=(0,a.getChannels)("rc",f),b=(y=f,T=_,w=r[r.length-2],v=r[r.length-1],y===0||y===1?"":` int r = ${T[y-2]}; int c = ${T[y-1]}; int rp1 = ${T[y-2]} + 1; int cp1 = ${T[y-1]} + 1; bool rEdge = rp1 >= ${v}; bool cEdge = cp1 >= ${w}; `);var y,T,w,v;let E;E=s===0?[1,1]:s===1?[r[0],1]:[r[f-1],r[f-2]];const P=function($,k,N){if($===0)return"false";if($===1)return`rc > ${k[0]}`;let D="";for(let V=$-2;V<$;V++)D+=`${N[V]} >= ${k[V-$+2]}`,V<$-1&&(D+="||");return D}(f,E,_),x=function($,k){const N=$.length;if(N===0)return"getA(), 0, 0, 0";if(N===1)return`getA(rc), rc + 1 >= ${$[0]} ? 0. : getA(rc + 1), 0, 0`;let D="";if(N>2)for(let V=0;V{Object.defineProperty(t,"__esModule",{value:!0}),t.unpackFromChannel=t.getChannels=t.getVecChannels=void 0;const i=o(9390);function u(d,a){return(0,i.getGlChannels)(a).map(h=>`${d}.${h}`)}t.getVecChannels=u,t.getChannels=function(d,a){return a===1?[d]:u(d,a)},t.unpackFromChannel=function(){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); } `}},2870:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parsePadAttributesV11=t.padV11=t.parsePadAttributesV2=t.padV2=void 0;const i=o(246),u=o(2517),d=o(5060),a=o(2039),h={name:"Pad",inputNames:["A"],inputTypes:[a.TextureType.unpacked]};t.padV2=(g,_,b)=>(l(_),[g.run(Object.assign(Object.assign({},h),{cacheHint:b.cacheKey,get:()=>c(g,_[0],b)}),_)]),t.parsePadAttributesV2=g=>{const _=g.attributes.getString("mode","constant"),b=g.attributes.getFloat("value",0),y=g.attributes.getInts("pads");return(0,i.createAttributeWithCacheKey)({mode:_,value:b,pads:y})},t.padV11=(g,_,b)=>{n(_);const y=m(g,_,b);return(0,t.padV2)(g,[_[0]],y)},t.parsePadAttributesV11=g=>g.attributes.getString("mode","constant");const m=(g,_,b)=>{if(!g.session.isInitializer(_[1].dataId)||_.length>=3&&!g.session.isInitializer(_[2].dataId))throw new Error("dynamic pad attributes are not allowed");const y=Array.from(_[1].integerData),T=_.length>=3?_[2].floatData[0]:0;return(0,i.createAttributeWithCacheKey)({mode:b,pads:y,value:T})},c=(g,_,b)=>{const y=u.ShapeUtil.padShape(_.dims.slice(),b.pads),T=y.length,w=` ${e(g,_,b)} float process(int[${T}] indices) { return padA(indices); }`;return{name:"Pad",inputNames:["A"],inputTypes:[a.TextureType.unpacked],output:{dims:y,type:_.type,textureType:a.TextureType.unpacked},shaderSource:w}},l=g=>{if(!g||g.length!==1)throw new Error("Pad requires 1 input");if(g[0].type!=="float32"&&g[0].type!=="float64")throw new Error("Invalid input type.")},n=g=>{if(!g||g.length!==2&&g.length!==3)throw new Error("Pad requires 2 or 3 inputs");if(g[1].type!=="int32")throw new Error("Invalid input type.");if(g.length>=3&&g[2].type==="string")throw new Error("Invalid input type.")},e=(g,_,b)=>{const y=(0,d.getGlsl)(g.session.backend.glContext.version),[T,w]=g.calculateTextureWidthAndHeight(_.dims,a.TextureType.unpacked),v=u.ShapeUtil.computeStrides(_.dims);switch(b.mode){case"constant":return r(y,_.dims,v,T,w,b.pads,b.value);case"reflect":return s(y,_.dims,v,T,w,b.pads);case"edge":return f(y,_.dims,v,T,w,b.pads);default:throw new Error("Invalid mode")}},r=(g,_,b,y,T,w,v)=>{const E=_.length;let P="";for(let x=E-1;x>=0;--x)P+=` k = m[${x}] - ${w[x]}; if (k < 0) return constant; if (k >= ${_[x]}) return constant; offset += k * ${b[x]}; `;return` float padA(int m[${E}]) { const float constant = float(${v}); int offset = 0; int k = 0; ${P} vec2 coords = offsetToCoords(offset, ${y}, ${T}); float value = getColorAsFloat(${g.texture2D}(A, coords)); return value; } `},s=(g,_,b,y,T,w)=>{const v=_.length;let E="";for(let P=v-1;P>=0;--P)E+=` k = m[${P}] - ${w[P]}; if (k < 0) { k = -k; } { const int _2n_1 = ${2*(_[P]-1)}; k = int( mod( float(k), float(_2n_1) ) ) ; if(k >= ${_[P]}) { k = _2n_1 - k; } } offset += k * ${b[P]}; `;return` float padA(int m[${v}]) { int offset = 0; int k = 0; ${E} vec2 coords = offsetToCoords(offset, ${y}, ${T}); float value = getColorAsFloat(${g.texture2D}(A, coords)); return value; } `},f=(g,_,b,y,T,w)=>{const v=_.length;let E="";for(let P=v-1;P>=0;--P)E+=` k = m[${P}] - ${w[P]}; if (k < 0) k = 0; if (k >= ${_[P]}) k = ${_[P]-1}; offset += k * ${b[P]}; `;return` float padA(int m[${v}]) { int offset = 0; int k = 0; ${E} vec2 coords = offsetToCoords(offset, ${y}, ${T}); float value = getColorAsFloat(${g.texture2D}(A, coords)); return value; } `}},2143:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.globalMaxPool=t.parseMaxPoolAttributes=t.maxPool=t.parseGlobalAveragePoolAttributes=t.globalAveragePool=t.parseAveragePoolAttributes=t.averagePool=void 0;const i=o(246),u=o(2517),d=o(2039);t.averagePool=(f,g,_)=>{n(g);const b={name:"AveragePool",inputNames:["X"],inputTypes:[d.TextureType.unpacked],cacheHint:_.cacheKey};return[f.run(Object.assign(Object.assign({},b),{get:()=>a(g,b,!1,_)}),g)]},t.parseAveragePoolAttributes=f=>{const g=f.attributes.getString("auto_pad","NOTSET"),_=f.attributes.getInt("ceil_mode",0),b=f.attributes.getInt("count_include_pad",0)!==0,y=f.attributes.getInts("kernel_shape"),T=f.attributes.getInts("strides",[]),w=f.attributes.getInts("pads",[]);if(_!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,i.createAttributeWithCacheKey)({autoPad:g,ceilMode:_,countIncludePad:b,kernelShape:y,strides:T,pads:w})};const a=(f,g,_,b)=>{const[y,T]=m(f,b,_),w=u.ShapeUtil.size(y.kernelShape);let v="";y.countIncludePad?v+=`value /= float(${w});`:v+=`value /= float(${w} - pad);`;const E=` ${e(f[0].dims,y,"value += _X(x);",v,"0.0")} `;return Object.assign(Object.assign({},g),{output:{dims:T,type:f[0].type,textureType:d.TextureType.unpacked},shaderSource:E})};t.globalAveragePool=(f,g,_)=>{n(g);const b={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[d.TextureType.unpacked],cacheHint:`${_.countIncludePad}`};return[f.run(Object.assign(Object.assign({},b),{get:()=>a(g,b,!0,_)}),g)]},t.parseGlobalAveragePoolAttributes=f=>{const g=f.attributes.getInt("count_include_pad",0)!==0;return(0,i.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:g,kernelShape:[],strides:[],pads:[]})},t.maxPool=(f,g,_)=>{n(g);const b={name:"MaxPool",inputNames:["X"],inputTypes:[d.TextureType.unpacked],cacheHint:_.cacheKey};return[f.run(Object.assign(Object.assign({},b),{get:()=>h(g,b,!1,_)}),g)]},t.parseMaxPoolAttributes=f=>{const g=f.attributes.getString("auto_pad","NOTSET"),_=f.attributes.getInt("ceil_mode",0),b=f.attributes.getInts("kernel_shape"),y=f.attributes.getInts("strides",[]),T=f.attributes.getInts("pads",[]),w=f.attributes.getInt("storage_order",0),v=f.attributes.getInts("dilations",[]);if(w!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(_!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,i.createAttributeWithCacheKey)({autoPad:g,ceilMode:_,countIncludePad:!1,kernelShape:b,strides:y,pads:T,storageOrder:w,dilations:v})};const h=(f,g,_,b)=>{const[y,T]=m(f,b,_),w=` ${e(f[0].dims,y,` value = max(_X(x), value); `,"","-1e5")} `;return Object.assign(Object.assign({},g),{output:{dims:T,type:f[0].type,textureType:d.TextureType.unpacked},shaderSource:w})},m=(f,g,_)=>{const b=f[0].dims.slice(),y=Object.hasOwnProperty.call(g,"dilations"),T=g.kernelShape.slice(),w=g.strides.slice(),v=y?g.dilations.slice():[],E=g.pads.slice();u.PoolConvUtil.adjustPoolAttributes(_,b,T,w,v,E);const P=u.PoolConvUtil.computePoolOutputShape(_,b,w,v,T,E,g.autoPad),x=Object.assign({},g);return y?Object.assign(x,{kernelShape:T,strides:w,pads:E,dilations:v,cacheKey:g.cacheKey}):Object.assign(x,{kernelShape:T,strides:w,pads:E,cacheKey:g.cacheKey}),[x,P]},c={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},l={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[d.TextureType.unpacked]};t.globalMaxPool=(f,g)=>(n(g),[f.run(Object.assign(Object.assign({},l),{get:()=>h(g,l,!0,c)}),g)]);const n=f=>{if(!f||f.length!==1)throw new Error("Pool ops requires 1 input.");if(f[0].type!=="float32"&&f[0].type!=="float64")throw new Error("Invalid input type.")},e=(f,g,_,b,y)=>{const T=f.length;if(g.kernelShape.length<=2){const w=g.kernelShape[g.kernelShape.length-1],v=g.strides[g.strides.length-1],E=g.pads[g.pads.length/2-1],P=g.pads[g.pads.length-1],x=f[T-1];let O="",$="",k="";if(O=E+P!==0?` for (int i = 0; i < ${w}; i++) { x[${T} - 1] = indices[${T} - 1] * ${v} - ${E} + i; if (x[${T} - 1] < 0 || x[${T} - 1] >= ${x}) { pad++; continue; } ${_} }`:` for (int i = 0; i < ${w}; i++) { x[${T} - 1] = indices[${T} - 1] * ${v} - ${E} + i; ${_} }`,g.kernelShape.length===2){const N=g.kernelShape[g.kernelShape.length-2],D=g.strides[g.strides.length-2],V=g.pads[g.pads.length/2-2],C=g.pads[g.pads.length-2],B=f[T-2];$=V+C!==0?` for (int j = 0; j < ${N}; j++) { x[${T} - 2] = indices[${T} - 2] * ${D} - ${V} + j; if (x[${T} - 2] < 0 || x[${T} - 2] >= ${B}) { pad+= ${w}; continue; } `:` for (int j = 0; j < ${N}; j++) { x[${T} - 2] = indices[${T} - 2] * ${D} - ${V} + j; `,k=` } `}return` float process(int indices[${T}]) { int x[${T}]; copyVec(indices, x); float value = ${y}; int pad = 0; ${$} ${O} ${k} ${b} return value; } `}{const w=u.ShapeUtil.size(g.kernelShape),v=u.ShapeUtil.computeStrides(g.kernelShape),E=v.length,P=g.pads.length,x=s(E),O=r(f,"inputDims"),$=r(g.pads,"pads"),k=r(v,"kernelStrides"),N=r(g.strides,"strides");let D="";return D=g.pads.reduce((V,C)=>V+C)?` if (x[j] >= inputDims[j] || x[j] < 0) { pad++; isPad = true; break; } } if (!isPad) { ${_} }`:` } ${_} `,` ${x} float process(int indices[${T}]) { int x[${T}]; copyVec(indices, x); int offset[${E}]; int pads[${P}]; int inputDims[${T}]; int kernelStrides[${E}]; int strides[${E}]; ${$} ${O} ${N} ${k} float value = ${y}; int pad = 0; bool isPad = false; for (int i = 0; i < ${w}; i++) { offsetToIndices(i, kernelStrides, offset); isPad = false; for (int j = ${T} - ${E}; j < ${T}; j++) { x[j] = indices[j] * strides[j - ${T} + ${E}] + offset[j - ${T} + ${E}] - pads[j - 2]; ${D} } ${b} return value; } `}},r=(f,g)=>{let _="";for(let b=0;b` void offsetToIndices(int offset, int[${f}] strides, out int[${f}] indices) { if (${f} == 0) { return; } for (int i = 0; i < ${f} - 1; ++i) { indices[i] = offset / strides[i]; offset -= indices[i] * strides[i]; } indices[${f} - 1] = offset; }`},4939:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reduceLogSumSquare=t.reduceLogSum=t.reduceProd=t.reduceMin=t.reduceMax=t.reduceMean=t.reduceSum=t.parseReduceAttributes=void 0;const i=o(246),u=o(782),d=o(2517),a=o(2039),h=(l,n,e,r,s)=>{c(n);const f={name:r,inputNames:["A"],inputTypes:[a.TextureType.unpacked]};return[l.run(Object.assign(Object.assign({},f),{cacheHint:e.cacheKey,get:()=>m(l,n,e,r,s,f)}),n)]};t.parseReduceAttributes=l=>{const n=l.attributes.getInts("axes",[]),e=l.attributes.getInt("keepdims",1)===1;return(0,i.createAttributeWithCacheKey)({axes:n,keepDims:e})};const m=(l,n,e,r,s,f)=>{const g=[],_=n[0].dims.length||1,b=[],y=d.ShapeUtil.normalizeAxes(e.axes,n[0].dims.length),T=s(n,y);let w=T[1];for(let E=0;E=0||y.length===0?(e.keepDims&&g.push(1),w=` for(int j${E} = 0; j${E} < ${n[0].dims[E]}; j${E}++) { inputIdx[${E}] = j${E}; ${w} }`):(b.push(`inputIdx[${E}] = outputIdx[${g.length}];`),g.push(n[0].dims[E]));const v=` float process(int outputIdx[${g.length||1}]) { float value; // final result int inputIdx[${_}]; // addressing input data ${b.join(` `)} ${T[0]} // init ops for reduce max/min ${w} ${T[2]} // final computation for reduce mean return value; }`;return Object.assign(Object.assign({},f),{output:{dims:g,type:n[0].type,textureType:a.TextureType.unpacked},shaderSource:v})},c=l=>{if(!l||l.length!==1)throw new Error("Reduce op requires 1 input.");if(u.NUMBER_TYPES.indexOf(l[0].type)===-1)throw new Error("Invalid input type.")};t.reduceSum=(l,n,e)=>h(l,n,e,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),t.reduceMean=(l,n,e)=>h(l,n,e,"ReduceMean",(r,s)=>{let f=1;for(let g=0;g=0||s.length===0)&&(f*=r[0].dims[g]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${f}.;`]}),t.reduceMax=(l,n,e)=>h(l,n,e,"ReduceMax",(r,s)=>{const f=[];for(let g=0;g=0||s.length===0)&&f.push(`inputIdx[${g}] = 0;`);return[`${f.join(` `)} value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),t.reduceMin=(l,n,e)=>h(l,n,e,"ReduceMin",(r,s)=>{const f=[];for(let g=0;g=0||s.length===0)&&f.push(`inputIdx[${g}] = 0;`);return[`${f.join(` `)} value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),t.reduceProd=(l,n,e)=>h(l,n,e,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),t.reduceLogSum=(l,n,e)=>h(l,n,e,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),t.reduceLogSumSquare=(l,n,e)=>h(l,n,e,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])},7019:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isReshapeCheap=t.processDims3D=t.createPackedReshape3DProgramInfoLoader=void 0;const i=o(2517),u=o(5060),d=o(2039),a=o(2827);t.createPackedReshape3DProgramInfoLoader=(h,m,c)=>{const l=(n=>({name:"Reshape (packed)",inputTypes:[d.TextureType.packed],inputNames:["A"],cacheHint:`${n}`}))(c);return Object.assign(Object.assign({},l),{get:()=>((n,e,r,s)=>{const f=e.dims,g=s;let _="";for(let T=0;T<4;T++){let w="";switch(T){case 0:w="outputCoords = rc;";break;case 1:w="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:w="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:w="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}_+=` ${w} ${T>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[${T}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); ${T>0?"}":""} `}const b=(0,u.getGlsl)(n.session.backend.glContext.version),y=` ${function(T){const w=i.ShapeUtil.computeStrides(T),v=["b","r","c"],E="index";return` ivec3 inputCoordsFromReshapedOutCoords(int index) { ${w.map((P,x)=>`int ${v[x]} = ${E} / ${P}; ${x===w.length-1?`int ${v[x+1]} = ${E} - ${v[x]} * ${P}`:`index -= ${v[x]} * ${P}`};`).join("")} return ivec3(b, r, c); } `}(f)} ${function(T){const w=i.ShapeUtil.computeStrides(T);return` int getFlattenedIndex(ivec3 coords) { // reverse y, z order return coords.x * ${w[0]} + coords.z * ${w[1]} + coords.y; } `}(g)} ${(0,a.unpackFromChannel)()} void main() { ivec3 rc = getOutputCoords(); vec4 result = vec4(0.0); ivec3 outputCoords; int rows = ${g[2]}; int cols = ${g[1]}; ${_} ${b.output} = result; } `;return Object.assign(Object.assign({},r),{output:{dims:g,type:e.type,textureType:d.TextureType.packed},shaderSource:y,hasMain:!0})})(h,m,l,c)})},t.processDims3D=function(h){if(h.length===0)return[1,1,1];let m=1;for(let c=0;c1?h[h.length-2]:1,h[h.length-1]]},t.isReshapeCheap=function(h,m){let c=!1;return c=h.length===0||m.length===0||(h.length<2||m.length<2?h[h.length-1]===m[m.length-1]:h[h.length-1]===m[m.length-1]&&h[h.length-2]===m[m.length-2]),c}},718:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reshape=void 0;const i=o(2517);t.reshape=(u,d)=>{const a=i.ShapeUtil.calculateReshapedDims(d[0].dims,d[1].integerData);return u.session.pack?[u.reshapePacked(d[0],a)]:[u.reshapeUnpacked(d[0],a)]}},2268:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseResizeAttributesV11=t.parseResizeAttributesV10=t.resize=void 0;const i=o(5060),u=o(2039),d=o(9390),a=o(2827),h=o(9793),m={name:"Resize",inputNames:["A"],inputTypes:[u.TextureType.packed]};t.resize=(r,s,f)=>((0,h.validateInputs)(s,f),[r.run(Object.assign(Object.assign({},m),{cacheHint:f.cacheKey,get:()=>c(r,s,f)}),s)]),t.parseResizeAttributesV10=r=>(0,h.parseUpsampleAttributes)(r,10),t.parseResizeAttributesV11=r=>(0,h.parseUpsampleAttributes)(r,11);const c=(r,s,f)=>{const g=(0,i.getGlsl)(r.session.backend.glContext.version),[_,b]=l(s,f);if(_.every(D=>D===1)&&f.coordinateTransformMode!=="tf_crop_and_resize")return Object.assign(Object.assign({},m),{output:{dims:b,type:s[0].type,textureType:u.TextureType.packed},hasMain:!0,shaderSource:`void main() { vec4 v = ${g.texture2D}(X, TexCoords); ${g.output} = v; }`});const y=b.length;if(y<2)throw new Error(`output dimension should be at least 2, but got ${y}`);const T=b[y-2],w=b[y-1],v=s[0].dims;if(y!==v.length)throw new Error(`output dimension should match input ${v.length}, but got ${y}`);const E=v[y-2],P=v[y-1],x=_[y-2],O=_[y-1];let $="";if(f.mode!=="linear")throw new Error(`resize (packed) does not support mode: '${f.mode}'`);switch(f.coordinateTransformMode){case"asymmetric":$=` vec4 getSourceFracIndex(ivec4 coords) { return vec4(coords) / scaleWHWH; } `;break;case"half_pixel":$=` vec4 getSourceFracIndex(ivec4 coords) { return (vec4(coords) + 0.5) / scaleWHWH - 0.5; } `;break;case"pytorch_half_pixel":$=` vec4 getSourceFracIndex(ivec4 coords) { vec4 fcoords = vec4(coords); return vec4( ${w}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, ${T}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, ${w}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, ${T}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 ); } `;break;case"align_corners":$=` vec4 getSourceFracIndex(ivec4 coords) { vec4 resized = vec4(${w}.0 - 1.0, ${T}.0 - 1.0, ${w}.0 - 1.0, ${T}.0 - 1.0); vec4 original = vec4(${P}.0 - 1.0, ${E}.0 - 1.0, ${P}.0 - 1.0, ${E}.0 - 1.0); vec4 new_scale = original / resized; return vec4(coords) * new_scale; } `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${f.coordinateTransformMode}'`)}const k=(0,d.getCoordsDataType)(y),N=` const vec2 inputWH = vec2(${E}.0, ${P}.0); const vec4 scaleWHWH = vec4(float(${x}), float(${O}), float(${x}), float(${O})); ${(0,a.unpackFromChannel)()} ${$} float getAValue(int x10, int r, int c, int d) { return getChannel(getA(x10, r, c, d), vec2(c, d)); } void main() { ${k} 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 < ${T-1}; bool hasNextCol = rc.z < ${w-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); ${g.output} = vec4(newValue); } `;return Object.assign(Object.assign({},m),{output:{dims:b,type:s[0].type,textureType:u.TextureType.packed},hasMain:!0,shaderSource:N})},l=(r,s)=>{const f=r[0].dims;let g,_=s.scales;if(_.length===0){const y=r[s.scalesInputIdx];if(y&&y.size!==0){if(r[s.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");_=n(y,s.mode,s.isResize)}else{const T=r[s.sizesInputIdx];if(!T||T.size===0)throw new Error("Either scales or sizes MUST be provided as input.");g=Array.from(T.integerData),_=e(g,f,s.mode,s.isResize)}}else if(r[s.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const b=g||f.map((y,T)=>Math.floor(y*_[T]));return[_,b]},n=(r,s,f)=>{const g=Array.from(r.floatData);return(0,h.scalesValidation)(g,s,f),g},e=(r,s,f,g)=>{const _=s.length,b=new Array(_);for(let y=0,T=_;y{Object.defineProperty(t,"__esModule",{value:!0}),t.shape=void 0;const i=o(9162);t.shape=(d,a)=>(u(a),[new i.Tensor([a[0].dims.length],"int32",void 0,void 0,new Int32Array(a[0].dims))]);const u=d=>{if(!d||d.length!==1)throw new Error("Shape requires 1 input.")}},2278:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sliceV10=t.parseSliceAttributes=t.slice=void 0;const i=o(246),u=o(782),d=o(2517),a=o(2039),h={name:"Slice",inputNames:["A"],inputTypes:[a.TextureType.unpacked]};t.slice=(e,r,s)=>(c(r),[e.run(Object.assign(Object.assign({},h),{cacheHint:s.cacheKey,get:()=>m(e,r[0],s)}),r)]),t.parseSliceAttributes=e=>{const r=e.attributes.getInts("starts"),s=e.attributes.getInts("ends"),f=e.attributes.getInts("axes",[]);return(0,i.createAttributeWithCacheKey)({starts:r,ends:s,axes:f})};const m=(e,r,s)=>{const f=s.axes.length===0?r.dims.slice(0).map((v,E)=>E):s.axes,g=d.ShapeUtil.normalizeAxes(f,r.dims.length),_=s.starts.map((v,E)=>v>r.dims[g[E]]-1?r.dims[g[E]]:d.ShapeUtil.normalizeAxis(v,r.dims[g[E]])),b=s.ends.map((v,E)=>v>r.dims[g[E]]-1?r.dims[g[E]]:d.ShapeUtil.normalizeAxis(v,r.dims[g[E]])),y=r.dims.slice(),T=[];for(let v=0;v0&&T.push(`outputIdx[${g[v]}] += ${_[v]};`);const w=` float process(int outputIdx[${y.length}]) { ${T.join(` `)} return _A(outputIdx); }`;return Object.assign(Object.assign({},h),{output:{dims:y,type:r.type,textureType:a.TextureType.unpacked},shaderSource:w})},c=e=>{if(!e||e.length!==1)throw new Error("Slice requires 1 input.");if(u.NUMBER_TYPES.indexOf(e[0].type)===-1)throw new Error("Invalid input type.")};t.sliceV10=(e,r)=>{n(r);const s=l(e,r);return[e.run(Object.assign(Object.assign({},h),{cacheHint:s.cacheKey,get:()=>m(e,r[0],s)}),[r[0]])]};const l=(e,r)=>{if(!e.session.isInitializer(r[1].dataId)||!e.session.isInitializer(r[2].dataId)||r.length>=4&&!e.session.isInitializer(r[3].dataId)||r.length>=5&&!e.session.isInitializer(r[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(r.length>=5&&r[4].integerData.some(_=>_!==1))throw new Error("currently non-1 steps is not supported for Slice");const s=Array.from(r[1].integerData),f=Array.from(r[2].integerData),g=r.length>=4?Array.from(r[3].integerData):[];return{starts:s,ends:f,axes:g,cacheKey:`${g};${s};${f}`}},n=e=>{if(!e||e.length<3||e.length>5)throw new Error("Invalid input number.");if(e[1].type!=="int32"||e[1].dims.length!==1)throw new Error("Invalid input type.");if(e[2].type!=="int32"||e[2].dims.length!==1)throw new Error("Invalid input type.");if(e.length>=4&&(e[3].type!=="int32"||e[3].dims.length!==1))throw new Error("Invalid input type.");if(e.length>=5&&(e[4].type!=="int32"||e[4].dims.length!==1))throw new Error("Invalid input type.")}},5524:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.softmaxV13=t.parseSoftmaxAttributesV13=t.parseSoftmaxAttributes=t.softmax=void 0;const i=o(246),u=o(2517),d=o(5060),a=o(2039),h=o(3738),m={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[a.TextureType.unpacked]},c={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked]},l={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked,a.TextureType.unpacked]};t.softmax=(g,_,b)=>{f(_);const y=_[0].dims.slice(),T=u.ShapeUtil.normalizeAxis(b.axis,y.length),w=u.ShapeUtil.sizeToDimension(y,T),v=u.ShapeUtil.sizeFromDimension(y,T);return n(g,_,b,w,v)},t.parseSoftmaxAttributes=g=>(0,i.createAttributeWithCacheKey)({axis:g.attributes.getInt("axis",1)}),t.parseSoftmaxAttributesV13=g=>(0,i.createAttributeWithCacheKey)({axis:g.attributes.getInt("axis",-1)}),t.softmaxV13=(g,_,b)=>{f(_);const y=_[0].dims.slice(),T=u.ShapeUtil.normalizeAxis(b.axis,y.length),w=y.length,v=T!==w-1,E=[];let P,x=[],O=[];v&&(x=Array.from({length:w}).map((D,V)=>V),x[T]=w-1,x[w-1]=T,x.map(D=>E.push(y[D])),P=(0,i.createAttributeWithCacheKey)({perm:x}),O=(0,h.transpose)(g,_,P));const $=v?u.ShapeUtil.sizeToDimension(E,w-1):u.ShapeUtil.sizeToDimension(y,w-1),k=v?u.ShapeUtil.sizeFromDimension(E,w-1):u.ShapeUtil.sizeFromDimension(y,w-1),N=n(g,v?O:_,b,$,k);return v?(0,h.transpose)(g,N,P):N};const n=(g,_,b,y,T)=>{const w=e(g,_[0],y,T,[y]),v=g.run(Object.assign(Object.assign({},m),{cacheHint:b.cacheKey,get:()=>w}),_),E=r(g,_[0],y,T,w.output.dims,[y]),P=g.run(Object.assign(Object.assign({},c),{cacheHint:b.cacheKey,get:()=>E}),[_[0],v]),x=s(g,_[0],y,T,w.output.dims,E.output.dims);return[g.run(Object.assign(Object.assign({},l),{cacheHint:b.cacheKey,get:()=>x}),[_[0],v,P])]},e=(g,_,b,y,T)=>{const[w,v]=g.calculateTextureWidthAndHeight(_.dims,a.TextureType.unpacked),E=T.length;if(b<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(T.length!==1)throw new Error("Dimensionality of the output should be 1");if(T[0]!==b)throw new Error("Shape of the output should be equal to logical row count");const P=(0,d.getGlsl)(g.session.backend.glContext.version),x=` float process(int[${E}] indices) { int logical_row_start_offset = indices[0] * ${y}; float max = getColorAsFloat(${P.texture2D}(A, offsetToCoords(logical_row_start_offset, ${w}, ${v} ))); for(int i=1; i<${y}; ++i) { float current = getColorAsFloat(${P.texture2D}(A, offsetToCoords(logical_row_start_offset + i, ${w}, ${v}))); if(current > max) max = current; } return max; }`;return Object.assign(Object.assign({},m),{output:{dims:T,type:_.type,textureType:a.TextureType.unpacked},shaderSource:x})},r=(g,_,b,y,T,w)=>{const[v,E]=g.calculateTextureWidthAndHeight(_.dims,a.TextureType.unpacked),P=w.length;if(b<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(w.length!==1)throw new Error("Dimensionality of the output should be 1");if(w[0]!==b)throw new Error("Shape of the output should be equal to logical row count");if(T.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(T[0]!==b)throw new Error("Shape of the intermediate results should be equal to logical row count");const x=` float process(int[${P}] indices) { int logical_row_start_offset = indices[0] * ${y}; float norm_factor = 0.0; float max = _Max(indices); for(int i=0; i<${y}; ++i) { norm_factor += exp(getColorAsFloat(${(0,d.getGlsl)(g.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i, ${v}, ${E}))) - max); } return norm_factor; }`;return Object.assign(Object.assign({},c),{output:{dims:w,type:_.type,textureType:a.TextureType.unpacked},shaderSource:x})},s=(g,_,b,y,T,w)=>{const[v,E]=g.calculateTextureWidthAndHeight(_.dims,a.TextureType.unpacked),P=_.dims.length;if(b<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(T.length!==1||w.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(T[0]!==b||w[0]!==b)throw new Error("Shape of the intermediate results should be equal to logical row count");const x=` float process(int[${P}] indices) { // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) int offset = coordsToOffset(TexCoords, ${v}, ${E}); //determine the logical row for this index int logical_row_index[1]; logical_row_index[0] = offset / ${y}; float norm_factor = _Norm(logical_row_index); // avoid possible division by 0 // if norm_facor is 0, all elements are zero // if so, return 0 if(norm_factor == 0.0) return 0.0; return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; }`;return Object.assign(Object.assign({},l),{output:{dims:_.dims,type:_.type,textureType:a.TextureType.unpacked},shaderSource:x})},f=g=>{if(!g||g.length!==1)throw new Error("Softmax requires 1 input.");if(g[0].type!=="float32"&&g[0].type!=="float64")throw new Error("Invalid input type")}},5975:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseSplitAttributes=t.split=void 0;const i=o(246),u=o(2517),d=o(2039),a={name:"Split",inputNames:["A"],inputTypes:[d.TextureType.unpacked]};t.split=(l,n,e)=>{c(n);const r=u.ShapeUtil.normalizeAxis(e.axis,n[0].dims.length),s=h(l,n,r,e),f=[];for(let g=0;gm(l,n[0],e,r,g)}),n));return f},t.parseSplitAttributes=l=>{const n=l.attributes.getInt("axis",0),e=l.attributes.getInts("split",[]),r=l.outputs.length;return(0,i.createAttributeWithCacheKey)({axis:n,split:e,numOutputs:r})};const h=(l,n,e,r)=>{const[,s]=u.SplitUtil.splitShape(n[0].dims,e,r.split,r.numOutputs);return s.length},m=(l,n,e,r,s)=>{const[f,g]=u.SplitUtil.splitShape(n.dims,r,e.split,e.numOutputs),_=g[s],b=f[s],y=` float process(int indices[${b.length}]) { indices[${r}] += ${_}; return _A(indices); } `;return Object.assign(Object.assign({},a),{cacheHint:`${e.cacheKey}:${s}`,output:{dims:b,type:n.type,textureType:d.TextureType.unpacked},shaderSource:y})},c=l=>{if(!l||l.length!==1)throw new Error("Split requires one input.");if(l[0].type!=="int8"&&l[0].type!=="uint8"&&l[0].type!=="int16"&&l[0].type!=="uint16"&&l[0].type!=="int32"&&l[0].type!=="uint32"&&l[0].type!=="float32"&&l[0].type!=="float64"&&l[0].type!=="bool")throw new Error("Invalid input type.")}},3933:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseSqueezeAttributes=t.squeezeV13=t.squeeze=void 0;const i=o(2517);t.squeeze=(a,h,m)=>{u(h);const c=i.ShapeUtil.squeezeShape(h[0].dims,m);return[a.reshapeUnpacked(h[0],c)]},t.squeezeV13=(a,h)=>(d(h),(0,t.squeeze)(a,[h[0]],Array.from(h[1].integerData))),t.parseSqueezeAttributes=a=>a.attributes.getInts("axes");const u=a=>{if(!a||a.length!==1)throw new Error("Squeeze requires 1 input.");if(a[0].type==="string")throw new Error("invalid input tensor types.")},d=a=>{if(!a||a.length!==2)throw new Error("Squeeze requires 2 inputs.");if(a[1].type!=="int32")throw new Error("Invalid input type.")}},6558:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sum=void 0;const i=o(5060),u=o(2039);t.sum=(h,m)=>{a(m);const c={name:"Sum",inputNames:m.map((l,n)=>`X${n}`),inputTypes:new Array(m.length).fill(u.TextureType.unpacked)};return[h.run(Object.assign(Object.assign({},c),{get:()=>d(h,m,c)}),m)]};const d=(h,m,c)=>{const l=(0,i.getGlsl)(h.session.backend.glContext.version),n=m[0].dims.slice(),e=` void main() { vec4 result = ${m.map((r,s)=>`${l.texture2D}(X${s},TexCoords)`).join(" + ")}; ${l.output} = result; } `;return Object.assign(Object.assign({},c),{output:{dims:n,type:m[0].type,textureType:u.TextureType.unpacked},hasMain:!0,shaderSource:e})},a=h=>{if(!h||h.length===0)throw new Error("Sum requires inputs.");const m=h[0].dims.length;for(let c=1;c{Object.defineProperty(t,"__esModule",{value:!0}),t.tile=void 0;const i=o(782),u=o(2039);t.tile=(h,m)=>{a(m);const c={name:"Tile",inputNames:["A"],inputTypes:[u.TextureType.unpacked]};return[h.run(Object.assign(Object.assign({},c),{get:()=>d(h,m,c)}),m)]};const d=(h,m,c)=>{const l=m[0].dims.slice(),n=new Array(l.length),e=[];for(let f=0;f{if(!h||h.length!==2)throw new Error("Tile requires 2 input.");if(h[1].dims.length!==1)throw new Error("The second input shape must 1 dimension.");if(h[1].dims[0]!==h[0].dims.length)throw new Error("Invalid input shape.");if(i.NUMBER_TYPES.indexOf(h[0].type)===-1)throw new Error("Invalid input type.");if(h[1].type!=="int32"&&h[1].type!=="int16")throw new Error("Invalid repeat type.")}},3738:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseTransposeAttributes=t.transpose=void 0;const i=o(246),u=o(2517),d=o(2039),a={name:"Transpose",inputNames:["A"],inputTypes:[d.TextureType.unpacked]};t.transpose=(e,r,s)=>(n(r),[e.run(Object.assign(Object.assign({},a),{cacheHint:s.cacheKey,get:()=>h(e,r[0],s.perm)}),r)]),t.parseTransposeAttributes=e=>(0,i.createAttributeWithCacheKey)({perm:e.attributes.getInts("perm",[])});const h=(e,r,s)=>{const f=r.dims;s=m(f,s);const g=c(f,s),_=f.length,b=` ${l("perm",s,_)} float process(int indices[${_}]) { int a[${_}]; perm(a, indices); return _A(a); }`;return Object.assign(Object.assign({},a),{output:{dims:g,type:r.type,textureType:d.TextureType.unpacked},shaderSource:b})},m=(e,r)=>(r&&r.length!==e.length&&(r=[...e.keys()].reverse()),r),c=(e,r)=>(r=m(e,r),u.ShapeUtil.sortBasedOnPerm(e,r)),l=(e,r,s)=>{const f=[];f.push(`void ${e}(out int a[${s}], int src[${s}]) {`);for(let g=0;g{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("input should be float tensor")}},8710:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeAsUint8=void 0;const i=o(5060),u=o(2039);t.encodeAsUint8=(d,a)=>{const h=a.shape,m=(0,i.getGlsl)(d.session.backend.glContext.version),c=` 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 = ${m.texture2D}(X,TexCoords).r; ${m.output} = encodeAsUint8(value); }`,l={name:"Uint8Encode",inputTypes:[u.TextureType.unpacked],inputNames:["X"],output:{dims:h,type:a.tensor.type,textureType:u.TextureType.downloadUint8AsFloat},shaderSource:c,hasMain:!0};return d.executeProgram(l,[a.tensor])}},4909:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.tanh=t.tan=t.sqrt=t.sin=t.sigmoid=t.relu=t.not=t.neg=t.log=t.parseLeakyReluAttributes=t.leakyRelu=t.identity=t.floor=t.exp=t.parseEluAttributes=t.elu=t.cos=t.ceil=t.clipV11=t.parseClipAttributes=t.clip=t.atan=t.asin=t.acos=t.abs=t.glslTanh=t.glslTan=t.glslSqrt=t.glslSigmoid=t.glslRelu=t.glslSin=t.glslNot=t.glslNeg=t.glslLog=t.glslLeakyRelu=t.glslIdentity=t.glslClip=t.glslFloor=t.glslExp=t.glslElu=t.glslCos=t.glslCeil=t.glslAtan=t.glslAsin=t.glslAcos=t.glslAbs=void 0;const i=o(246),u=o(2517),d=o(8520),a=o(5060),h=o(2039);function m(){return N("abs")}function c(){return N("acos")}function l(){return N("asin")}function n(){return N("atan")}function e(){return N("ceil")}function r(){return N("cos")}function s(C){const B="elu";return{body:` const float alpha = float(${C}); float ${B}_(float a) { return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; } vec4 ${B}_(vec4 v) { return vec4(${B}_(v.x), ${B}_(v.y), ${B}_(v.z), ${B}_(v.w)); } `,name:B,type:d.FunctionType.ValueBased}}function f(){return N("exp")}function g(){return N("floor")}function _(C,B){const X="clip";return{body:` const float min = float(${C}); const float max = float(${B}); float ${X}_(float a) { return clamp(a, min, max); } vec4 ${X}_(vec4 v) { return clamp(v, min, max); } `,name:X,type:d.FunctionType.ValueBased}}function b(){const C="indentity";return{body:` float ${C}_(float a) { return a; } vec4 ${C}_(vec4 v) { return v; } `,name:C,type:d.FunctionType.ValueBased}}function y(C){const B="leakyRelu";return{body:` const float alpha = float(${C}); float ${B}_(float a) { return a < 0.0 ? a * alpha : a; } vec4 ${B}_(vec4 v) { return vec4(${B}_(v.x), ${B}_(v.y), ${B}_(v.z), ${B}_(v.w)); } `,name:B,type:d.FunctionType.ValueBased}}function T(){return N("log")}function w(){const C="neg";return{body:` float ${C}_(float a) { return -a; } vec4 ${C}_(vec4 v) { return -v; } `,name:C,type:d.FunctionType.ValueBased}}function v(){const C="not";return{body:` float ${C}_(float a) { return float( ! bool(a) ); } bool ${C}_(bool a) { return !a; } vec4 ${C}_(vec4 v) { return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); } bvec4 ${C}_(bvec4 v) { return bvec4(!v.x, !v.y, !v.z, !v.w); } `,name:C,type:d.FunctionType.ValueBased}}function E(){return N("sin")}function P(){const C="relu";return{body:` float ${C}_(float a) { return max( a, 0.0 ); } vec4 ${C}_(vec4 v) { return max( v, 0.0 ); } `,name:C,type:d.FunctionType.ValueBased}}function x(){const C="sigmoid";return{body:` float ${C}_(float a) { return 1.0 / (1.0 + exp(-a)); } vec4 ${C}_(vec4 v) { return 1.0 / (1.0 + exp(-v)); } `,name:C,type:d.FunctionType.ValueBased}}function O(){return N("sqrt")}function $(){return N("tan")}function k(){const C="tanh";return{body:` float ${C}_(float a) { a = clamp(a, -10., 10.); a = exp(2.*a); return (a - 1.) / (a + 1.); } vec4 ${C}_(vec4 v) { v = clamp(v, -10., 10.); v = exp(2.*v); return (v - 1.) / (v + 1.); } `,name:C,type:d.FunctionType.ValueBased}}function N(C){return{body:` float ${C}_(float a) { return ${C}(a); } vec4 ${C}_(vec4 v) { return ${C}(v); } `,name:C,type:d.FunctionType.ValueBased}}t.glslAbs=m,t.glslAcos=c,t.glslAsin=l,t.glslAtan=n,t.glslCeil=e,t.glslCos=r,t.glslElu=s,t.glslExp=f,t.glslFloor=g,t.glslClip=_,t.glslIdentity=b,t.glslLeakyRelu=y,t.glslLog=T,t.glslNeg=w,t.glslNot=v,t.glslSin=E,t.glslRelu=P,t.glslSigmoid=x,t.glslSqrt=O,t.glslTan=$,t.glslTanh=k;const D=(C,B,X,G)=>{const ee=C.session.pack?h.TextureType.packed:h.TextureType.unpacked,J={name:X.name,inputTypes:[ee],inputNames:["A"],cacheHint:G};return Object.assign(Object.assign({},J),{get:()=>((ae,Ee,xe,le)=>{const we=ae.session.pack?h.TextureType.packed:h.TextureType.unpacked,be=(0,a.getGlsl)(ae.session.backend.glContext.version);return Object.assign(Object.assign({},Ee),{output:{dims:xe.dims,type:xe.type,textureType:we},shaderSource:` ${le.body} void main() { vec4 v = ${be.texture2D}(A, TexCoords); v = ${le.name}_(v); ${be.output} = v; } `,hasMain:!0})})(C,J,B,X)})};t.abs=(C,B)=>[C.run(D(C,B[0],m()),B)],t.acos=(C,B)=>[C.run(D(C,B[0],c()),B)],t.asin=(C,B)=>[C.run(D(C,B[0],l()),B)],t.atan=(C,B)=>[C.run(D(C,B[0],n()),B)],t.clip=(C,B,X)=>[C.run(D(C,B[0],_(X.min,X.max),X.cacheKey),B)],t.parseClipAttributes=C=>(0,i.createAttributeWithCacheKey)({min:C.attributes.getFloat("min",u.MIN_CLIP),max:C.attributes.getFloat("max",u.MAX_CLIP)}),t.clipV11=(C,B)=>{const X=V(C,B);return(0,t.clip)(C,[B[0]],X)};const V=(C,B)=>{if(B.length>=3&&(!C.session.isInitializer(B[1].dataId)||!C.session.isInitializer(B[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const X=B.length>=3?B[1].numberData[0]:u.MIN_CLIP,G=B.length>=3?B[2].numberData[0]:u.MAX_CLIP;return(0,i.createAttributeWithCacheKey)({min:X,max:G})};t.ceil=(C,B)=>[C.run(D(C,B[0],e()),B)],t.cos=(C,B)=>[C.run(D(C,B[0],r()),B)],t.elu=(C,B,X)=>[C.run(D(C,B[0],s(X.alpha),X.cacheKey),B)],t.parseEluAttributes=C=>(0,i.createAttributeWithCacheKey)({alpha:C.attributes.getFloat("alpha",1)}),t.exp=(C,B)=>[C.run(D(C,B[0],f()),B)],t.floor=(C,B)=>[C.run(D(C,B[0],g()),B)],t.identity=(C,B)=>[C.run(D(C,B[0],b()),B)],t.leakyRelu=(C,B,X)=>[C.run(D(C,B[0],y(X.alpha),X.cacheKey),B)],t.parseLeakyReluAttributes=C=>(0,i.createAttributeWithCacheKey)({alpha:C.attributes.getFloat("alpha",.01)}),t.log=(C,B)=>[C.run(D(C,B[0],T()),B)],t.neg=(C,B)=>[C.run(D(C,B[0],w()),B)],t.not=(C,B)=>[C.run(D(C,B[0],v()),B)],t.relu=(C,B)=>[C.run(D(C,B[0],P()),B)],t.sigmoid=(C,B)=>[C.run(D(C,B[0],x()),B)],t.sin=(C,B)=>[C.run(D(C,B[0],E()),B)],t.sqrt=(C,B)=>[C.run(D(C,B[0],O()),B)],t.tan=(C,B)=>[C.run(D(C,B[0],$()),B)],t.tanh=(C,B)=>[C.run(D(C,B[0],k()),B)]},5611:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createUnpackProgramInfoLoader=t.createUnpackProgramInfo=void 0;const i=o(5060),u=o(2039),d=o(9390),a=o(2827),h={name:"unpack",inputNames:["A"],inputTypes:[u.TextureType.packed]};t.createUnpackProgramInfo=(m,c)=>{const l=c.dims.length,n=(0,a.getChannels)("rc",l),e=n.slice(-2),r=(0,d.getCoordsDataType)(l),s=(0,a.unpackFromChannel)(),f=c.dims.length===0?"":function(b,y){if(b===1)return"rc";let T="";for(let w=0;wObject.assign(Object.assign({},h),{get:()=>(0,t.createUnpackProgramInfo)(m,c)})},8428:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseUnsqueezeAttributes=t.unsqueezeV13=t.unsqueeze=void 0;const i=o(2517);t.unsqueeze=(a,h,m)=>{u(h);const c=i.ShapeUtil.unsqueezeShape(h[0].dims,m);return[a.reshapeUnpacked(h[0],c)]},t.unsqueezeV13=(a,h)=>(d(h),(0,t.unsqueeze)(a,[h[0]],Array.from(h[1].integerData))),t.parseUnsqueezeAttributes=a=>a.attributes.getInts("axes");const u=a=>{if(!a||a.length!==1)throw new Error("Unsqueeze requires 1 input.");if(a[0].type==="string")throw new Error("invalid input tensor types.")},d=a=>{if(!a||a.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(a[1].type!=="int32")throw new Error("Invalid input type.")}},9793:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.scalesValidation=t.validateInputs=t.parseUpsampleAttributes=t.parseUpsampleAttributesV9=t.parseUpsampleAttributesV7=t.upsample=void 0;const i=o(246),u=o(5060),d=o(2039),a={name:"Upsample",inputNames:["X"],inputTypes:[d.TextureType.unpacked]};t.upsample=(m,c,l)=>((0,t.validateInputs)(c,l),[m.run(Object.assign(Object.assign({},a),{cacheHint:l.cacheKey,get:()=>h(m,c,l)}),c)]),t.parseUpsampleAttributesV7=m=>(0,t.parseUpsampleAttributes)(m,7),t.parseUpsampleAttributesV9=m=>(0,t.parseUpsampleAttributes)(m,9),t.parseUpsampleAttributes=(m,c)=>{const l=c>=10,n=m.attributes.getString("mode","nearest");if(n!=="nearest"&&n!=="linear"&&(c<11||n!=="cubic"))throw new Error(`unrecognized mode: ${n}`);let e=[];c<9&&(e=m.attributes.getFloats("scales"),(0,t.scalesValidation)(e,n,l));const r=m.attributes.getFloat("extrapolation_value",0),s=c>10?m.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`);const f=s==="tf_crop_and_resize",g=f,_=n==="nearest"&&c>=11?m.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(_)===-1)throw new Error(`nearest_mode '${_}' is not supported`);const b=m.attributes.getFloat("cubic_coeff_a",-.75),y=m.attributes.getInt("exclude_outside",0)!==0;if(y&&n!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const T=c<11||n==="nearest"&&s==="asymmetric"&&_==="floor";let w=0,v=0,E=0;return c>10?m.inputs.length>2?(w=1,v=2,E=3):(v=1,E=2):c===9&&(v=1),(0,i.createAttributeWithCacheKey)({opset:c,isResize:l,mode:n,scales:e,extrapolationValue:r,coordinateTransformMode:s,useExtrapolation:g,needRoiInput:f,nearestMode:_,cubicCoefficientA:b,excludeOutside:y,useNearest2xOptimization:T,roiInputIdx:w,scalesInputIdx:v,sizesInputIdx:E})};const h=(m,c,l)=>{const n=(0,u.getGlsl)(m.session.backend.glContext.version),[e,r]=m.calculateTextureWidthAndHeight(c[0].dims,d.TextureType.unpacked),s=c[0].dims.map((E,P)=>Math.floor(E*l.scales[P])),[f,g]=m.calculateTextureWidthAndHeight(s,d.TextureType.unpacked),_=s.length,b=new Array(_),y=new Array(_);let T=` int output_pitches[${_}]; int input_pitches[${_}]; `;for(let E=_-1;E>=0;E--)b[E]=E===_-1?1:b[E+1]*s[E+1],y[E]=E===_-1?1:y[E+1]*c[0].dims[E+1],T+=` output_pitches[${E}] = ${b[E]}; input_pitches[${E}] = ${y[E]}; `;const w=` float getInputFloat(int index) { vec2 coords = offsetToCoords(index, ${e}, ${r}); float value = getColorAsFloat(${n.texture2D}(X, coords)); return value; } `,v=l.mode==="nearest"?` ${w} float process(int indices[${_}]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${f}, ${g}); ${T} int d, m; for (int dim = 0; dim < ${_}; ++dim) { d = output_index / output_pitches[dim]; m = output_index - d * output_pitches[dim]; output_index = m; if (scales[dim] != 1 && d > 0) { int d2 = d / scales[dim]; m = d - d2 * scales[dim]; d = d2; } input_index += input_pitches[dim] * d; } return getInputFloat(input_index); }`:_===4?` ${w} float process(int indices[4]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${f}, ${g}); ${T} 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 == (${c[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]); }`:` ${w} float process(int indices[2]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${f}, ${g}); ${T} 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 == (${c[0].dims[0]} - 1)) { // It's the end in dimension 0 x01 = x00; end_of_dim0 = true; } else { x01 = getInputFloat(input_index + input_pitches[0]); } if (index_of_input_dim1 == (input_pitches[0] - 1)) { // It's the end in dimension 1 x10 = x00; x11 = x01; } else { x10 = getInputFloat(input_index + 1); x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1); } float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); }`;return Object.assign(Object.assign({},a),{output:{dims:s,type:c[0].type,textureType:d.TextureType.unpacked},shaderSource:v,variables:[{name:"scales",type:"int",arrayLength:l.scales.length,data:l.scales.map(E=>Math.ceil(E))}]})};t.validateInputs=(m,c)=>{if(!m||c.opset<9&&m.length!==1||c.opset>=9&&c.opset<11&&m.length!==2||c.opset>=11&&m.length<2)throw new Error("invalid inputs.");if(c.scales.length>0&&m[0].dims.length!==c.scales.length)throw new Error("Invalid input shape.");if(m[0].type==="string")throw new Error("Invalid input tensor types.")},t.scalesValidation=(m,c,l)=>{if(l){for(const n of m)if(n<=0)throw new Error("Scale value should be greater than 0.")}else for(const n of m)if(n<1)throw new Error("Scale value should be greater than or equal to 1.");if(!(c!=="linear"&&c!=="cubic"||m.length===2||m.length===4&&m[0]===1&&m[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 ${l?"Resize":"Upsample"} opeartor.`)}},1958:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProgramManager=void 0;const i=o(1670),u=o(6231),d=o(8879),a=o(5060);t.ProgramManager=class{constructor(h,m,c){this.profiler=h,this.glContext=m,this.textureLayoutStrategy=c,this.repo=new Map,this.attributesBound=!1}getArtifact(h){return this.repo.get(h)}setArtifact(h,m){this.repo.set(h,m)}run(h,m,c){var l;this.profiler.event("op",`ProgramManager.run ${(l=h.programInfo.name)!==null&&l!==void 0?l:"unknown kernel"}`,()=>{var n;const e=this.glContext.gl,r=h.program;e.useProgram(r);try{this.bindOutput(c),this.attributesBound||this.bindAttributes(h.attribLocations),this.bindUniforms(h.uniformLocations,(n=h.programInfo.variables)!==null&&n!==void 0?n:[],m)}catch(s){throw u.Logger.error("ProgramManager",h.programInfo.shaderSource),s}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach(h=>this.glContext.deleteProgram(h.program))}build(h,m,c){return this.profiler.event("backend","ProgramManager.build",()=>{const l=new d.GlslPreprocessor(this.glContext,h,m,c),n=l.preprocess(),e=this.compile(n);return{programInfo:h,program:e,uniformLocations:this.getUniformLocations(e,l.context.programInfo.inputNames,l.context.programInfo.variables),attribLocations:this.getAttribLocations(e)}})}compile(h){if(!this.vertexShader){u.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const l=(0,a.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(l,this.glContext.gl.VERTEX_SHADER)}i.env.debug&&u.Logger.verbose("ProrgramManager",`FragShader: ${h} `);const m=this.glContext.compileShader(h,this.glContext.gl.FRAGMENT_SHADER),c=this.glContext.createProgram(this.vertexShader,m);return this.glContext.deleteShader(m),c}bindOutput(h){const m=h.width,c=h.height;u.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${m}/${c}, shape=${h.shape}, type=${h.tensor.type}`),this.glContext.attachFramebuffer(h.texture,m,c)}bindAttributes(h){const m=h.position,c=h.textureCoord;this.glContext.setVertexAttributes(m,c),this.attributesBound=!0}bindUniforms(h,m,c){var l;const n=this.glContext.gl;let e=0;for(const{name:r,type:s,location:f,arrayLength:g}of h){const _=(l=m.find(b=>b.name===r))===null||l===void 0?void 0:l.data;if(s!=="sampler2D"&&!_)throw new Error(`variable '${r}' does not have data defined in program info`);switch(s){case"sampler2D":this.bindTexture(c[e],f,e),e++;break;case"float":g?n.uniform1fv(f,_):n.uniform1f(f,_);break;case"int":g?n.uniform1iv(f,_):n.uniform1i(f,_);break;default:throw new Error(`Uniform not implemented: ${s}`)}}}bindTexture(h,m,c){this.glContext.bindTextureToUniform(h.texture,c,m)}getAttribLocations(h){return{position:this.getAttribLocation(h,"position"),textureCoord:this.getAttribLocation(h,"textureCoord")}}getUniformLocations(h,m,c){const l=[];if(m)for(const n of m)l.push({name:n,type:"sampler2D",location:this.getUniformLocation(h,n)});if(c)for(const n of c)l.push(Object.assign(Object.assign({},n),{location:this.getUniformLocation(h,n.name)}));return l}getUniformLocation(h,m){const c=this.glContext.gl.getUniformLocation(h,m);if(c===null)throw new Error(`Uniform ${m} not found.`);return c}getAttribLocation(h,m){return this.glContext.gl.getAttribLocation(h,m)}}},6416:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLSessionHandler=void 0;const i=o(6231),u=o(1047),d=o(8316),a=o(1640),h=o(1958),m=o(7859),c=o(5702);t.WebGLSessionHandler=class{constructor(l,n){this.backend=l,this.context=n,this.layoutStrategy=new m.PreferLogicalStrategy(l.glContext.maxTextureSize),this.programManager=new h.ProgramManager(this.context.profiler,l.glContext,this.layoutStrategy),this.textureManager=new c.TextureManager(l.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:l.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=l.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new d.WebGLInferenceHandler(this)}onGraphInitialized(l){const n=l.getValues().filter(e=>e.from===-1&&e.tensor).map(e=>e.tensor.dataId);this.initializers=new Set(n)}isInitializer(l){return!!this.initializers&&this.initializers.has(l)}addInitializer(l){this.initializers.add(l)}getTextureData(l,n){return n?this.packedTextureDataCache.get(l):this.unpackedTextureDataCache.get(l)}setTextureData(l,n,e=!1){i.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),e?this.packedTextureDataCache.set(l,n):this.unpackedTextureDataCache.set(l,n)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(l=>this.textureManager.releaseTexture(l,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(l=>this.textureManager.releaseTexture(l,!0)),this.unpackedTextureDataCache=new Map}resolve(l,n,e){const r=(0,u.resolveOperator)(l,n,a.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(l,e):l}}}},7769:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Uint8DataEncoder=t.RGBAFloatDataEncoder=t.RedFloat32DataEncoder=void 0;const i=o(6231);t.RedFloat32DataEncoder=class{constructor(u,d=1){if(d===1)this.internalFormat=u.R32F,this.format=u.RED,this.textureType=u.FLOAT,this.channelSize=d;else{if(d!==4)throw new Error(`Invalid number of channels: ${d}`);this.internalFormat=u.RGBA32F,this.format=u.RGBA,this.textureType=u.FLOAT,this.channelSize=d}}encode(u,d){let a,h;return u.constructor!==Float32Array&&(i.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),h=new Float32Array(u)),d*this.channelSize>u.length?(i.Logger.warning("Encoder","Source data too small. Allocating larger array"),h=u,a=this.allocate(d*this.channelSize),h.forEach((m,c)=>a[c]=m)):(h=u,a=h),a}allocate(u){return new Float32Array(4*u)}decode(u,d){return this.channelSize===1?u.filter((a,h)=>h%4==0).subarray(0,d):u.subarray(0,d)}},t.RGBAFloatDataEncoder=class{constructor(u,d=1,a){if(d!==1&&d!==4)throw new Error(`Invalid number of channels: ${d}`);this.internalFormat=u.RGBA,this.format=u.RGBA,this.channelSize=d,this.textureType=a||u.FLOAT}encode(u,d){let a=u;return this.channelSize===1&&(i.Logger.verbose("Encoder","Exploding into a larger array"),a=this.allocate(d),u.forEach((h,m)=>a[4*m]=h)),a}allocate(u){return new Float32Array(4*u)}decode(u,d){return this.channelSize===1?u.filter((a,h)=>h%4==0).subarray(0,d):u.subarray(0,d)}},t.Uint8DataEncoder=class{constructor(u,d=1){if(this.channelSize=4,d===1)this.internalFormat=u.ALPHA,this.format=u.ALPHA,this.textureType=u.UNSIGNED_BYTE,this.channelSize=d;else{if(d!==4)throw new Error(`Invalid number of channels: ${d}`);this.internalFormat=u.RGBA,this.format=u.RGBA,this.textureType=u.UNSIGNED_BYTE,this.channelSize=d}}encode(u,d){return new Uint8Array(u.buffer,u.byteOffset,u.byteLength)}allocate(u){return new Uint8Array(u*this.channelSize)}decode(u,d){if(u instanceof Uint8Array)return u.subarray(0,d);throw new Error(`Invalid array type: ${u.constructor}`)}}},7859:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getBatchDim=t.sizeToSquarishShape=t.getRowsCols=t.sizeFromShape=t.isInt=t.parseAxisParam=t.squeezeShape=t.PreferLogicalStrategy=t.AlwaysKeepOriginalSizeStrategy=void 0;const i=o(6231),u=o(2517);function d(l,n){const e=[],r=[],s=n!=null&&Array.isArray(n)&&n.length===0,f=n==null||s?null:a(n,l).sort();let g=0;for(let _=0;__)&&l[_]===1&&(e.push(l[_]),r.push(_)),f[g]<=_&&g++}l[_]!==1&&(e.push(l[_]),r.push(_))}return{newShape:e,keptDims:r}}function a(l,n){const e=n.length;return l=l==null?n.map((r,s)=>s):[].concat(l),(0,u.assert)(l.every(r=>r>=-e&&r`All values in axis param must be in range [-${e}, ${e}) but got axis ${l}`),(0,u.assert)(l.every(h),()=>`All values in axis param must be integers but got axis ${l}`),l.map(r=>r<0?e+r:r)}function h(l){return l%1==0}function m(l){if(l.length===0)return 1;let n=l[0];for(let e=1;e=l.length?1:l.slice(n.breakAxis).reduce((_,b)=>_*b),g=n.breakAxis<=0?1:l.slice(0,n.breakAxis).reduce((_,b)=>_*b);if(!(f>e||g>e))return[f,g];i.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${l}, breakAxis:${n.breakAxis}`)}const r=l.reduce((f,g)=>f*g);let s=Math.floor(Math.sqrt(r));for(;s=e||r%s!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${l}`);return[s,r/s]}},t.PreferLogicalStrategy=class{constructor(l){this.maxTextureSize=l}computeTextureWH(l,n){const e=this.computeTexture(l,n);return n&&n.isPacked&&(e[0]/=2,e[1]/=2),n&&n.reverseWH?[e[1],e[0]]:e}computeTexture(l,n){const e=n&&n.isPacked;if(l.length===0)return e?[2,2]:[1,1];let r=this.maxTextureSize;if(n&&n.breakAxis!==void 0){const g=n.breakAxis>=l.length?1:l.slice(n.breakAxis).reduce((b,y)=>b*y),_=n.breakAxis<=0?1:l.slice(0,n.breakAxis).reduce((b,y)=>b*y);if(!(g>r||_>r))return[g,_];i.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${l}, breakAxis:${n.breakAxis}`)}let s=l.slice(0);e&&(r*=2,s=s.map((g,_)=>_>=s.length-2?s[_]%2==0?s[_]:s[_]+1:s[_]),s.length===1&&(s=[2,s[0]])),s.length!==2&&(s=d(s).newShape);const f=m(s);return s.length<=1&&f<=r?[1,f]:s.length===2&&s[0]<=r&&s[1]<=r?s:s.length===3&&s[0]*s[1]<=r&&s[2]<=r?[s[0]*s[1],s[2]]:s.length===3&&s[0]<=r&&s[1]*s[2]<=r?[s[0],s[1]*s[2]]:s.length===4&&s[0]*s[1]*s[2]<=r&&s[3]<=r?[s[0]*s[1]*s[2],s[3]]:s.length===4&&s[0]<=r&&s[1]*s[2]*s[3]<=r?[s[0],s[1]*s[2]*s[3]]:e?c(f/4).map(g=>2*g):c(f)}},t.squeezeShape=d,t.parseAxisParam=a,t.isInt=h,t.sizeFromShape=m,t.getRowsCols=function(l){if(l.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[l.length>1?l[l.length-2]:1,l[l.length-1]]},t.sizeToSquarishShape=c,t.getBatchDim=function(l,n=2){return m(l.slice(0,l.length-n))}},4057:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createTextureLayoutFromShape=t.calculateTextureWidthAndHeight=t.createTextureLayoutFromTextureType=void 0;const i=o(2517),u=o(2039);t.createTextureLayoutFromTextureType=(d,a,h)=>{const m=h===u.TextureType.unpacked||h===u.TextureType.unpackedReversed?1:4,c=h===u.TextureType.packed,l=h===u.TextureType.unpackedReversed||h===u.TextureType.packed,n=h===u.TextureType.packedLastDimension?a.length-1:void 0,e=h===u.TextureType.packedLastDimension?a.map((r,s)=>s===a.length-1?4*r:r):void 0;return(0,t.createTextureLayoutFromShape)(d,a,m,e,{isPacked:c,reverseWH:l,breakAxis:n})},t.calculateTextureWidthAndHeight=(d,a,h)=>{const m=(0,t.createTextureLayoutFromTextureType)(d,a,h);return[m.width,m.height]},t.createTextureLayoutFromShape=(d,a,h=1,m,c)=>{const l=!(!c||!c.isPacked),[n,e]=d.computeTextureWH(l&&m||a,c),r=a.length;let s=a.slice(0);if(r===0&&(s=[1]),h===1)m=a;else if(l){if(h!==4)throw new Error("a packed texture must be 4-channel");m=a,r>0&&(s[r-1]=Math.ceil(s[r-1]/2)),r>1&&(s[r-2]=Math.ceil(s[r-2]/2))}else if(!m)throw new Error("Unpacked shape is needed when using channels > 1");return{width:n,height:e,channels:h,isPacked:l,shape:s,strides:i.ShapeUtil.computeStrides(s),unpackedShape:m,reversedWH:c&&c.reverseWH}}},5702:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TextureManager=void 0;const i=o(6231);t.TextureManager=class{constructor(u,d,a,h){this.glContext=u,this.layoutStrategy=d,this.profiler=a,this.config=h,this.pendingRead=new Map,h.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(u,d,a,h){const m=this.toEncoderType(u),c=this.glContext.getEncoder(m,d.channels||1,h);if(d.isPacked&&h===1)throw new Error("not implemented");const l=d.width,n=d.height;let e,r;if(this.config.reuseTextures){e=`${l}x${n}_${c.format}_${c.internalFormat}_${c.textureType}`,r=this.inUseTextures.get(e),r||(r=[],this.inUseTextures.set(e,r));const f=this.idleTextures.get(e);if(f&&f.length>0){const g=f.pop();return r.push(g),h===1&&this.glContext.updateTexture(g,l,n,c,this.toTextureData(u,a)),g}}i.Logger.verbose("TextureManager",`Creating new texture of size ${d.width}x${d.height}`);const s=this.glContext.allocateTexture(l,n,c,this.toTextureData(u,a));return this.config.reuseTextures&&(r.push(s),this.textureLookup.set(s,e)),s}readTexture(u,d,a){return a||(a=1),this.profiler.event("backend","TextureManager.readTexture",()=>{const h=u.shape.reduce((c,l)=>c*l)*a,m=this.glContext.readTexture(u.texture,u.width,u.height,h,this.toEncoderType(d),a);return this.toTensorData(d,m)})}async readTextureAsync(u,d,a){const h=u.tensor.dataId;if(a||(a=1),this.pendingRead.has(h)){const m=this.pendingRead.get(h);return new Promise(c=>m==null?void 0:m.push(c))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(h,[]);const m=u.shape.reduce((e,r)=>e*r)*a;await this.glContext.createAndWaitForFence();const c=this.glContext.readTexture(u.texture,u.width,u.height,m,this.toEncoderType(d),a),l=this.toTensorData(d,c),n=this.pendingRead.get(h);return this.pendingRead.delete(h),n==null||n.forEach(e=>e(l)),l})}readUint8TextureAsFloat(u){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{const d=u.shape.reduce((h,m)=>h*m),a=this.glContext.readTexture(u.texture,u.width,u.height,4*d,"byte",4);return new Float32Array(a.buffer,a.byteOffset,d)})}releaseTexture(u,d){let a;if(this.config.reuseTextures&&(a=this.textureLookup.get(u.texture),a)){d&&this.textureLookup.delete(a);const h=this.inUseTextures.get(a);if(h){const m=h.indexOf(u.texture);if(m!==-1){h.splice(m,1);let c=this.idleTextures.get(a);c||(c=[],this.idleTextures.set(a,c)),c.push(u.texture)}}}a&&!d||(i.Logger.verbose("TextureManager",`Deleting texture of size ${u.width}x${u.height}`),this.glContext.deleteTexture(u.texture))}toTensorData(u,d){switch(u){case"int16":return d instanceof Int16Array?d:Int16Array.from(d);case"int32":return d instanceof Int32Array?d:Int32Array.from(d);case"int8":return d instanceof Int8Array?d:Int8Array.from(d);case"uint16":return d instanceof Uint16Array?d:Uint16Array.from(d);case"uint32":return d instanceof Uint32Array?d:Uint32Array.from(d);case"uint8":case"bool":return d instanceof Uint8Array?d:Uint8Array.from(d);case"float32":return d instanceof Float32Array?d:Float32Array.from(d);case"float64":return d instanceof Float64Array?d:Float64Array.from(d);default:throw new Error(`TensorData type ${u} is not supported`)}}toTextureData(u,d){if(d)return d instanceof Float32Array?d:new Float32Array(d)}toEncoderType(u){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},2039:(p,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.TextureType=void 0,(o=t.TextureType||(t.TextureType={}))[o.unpacked=0]="unpacked",o[o.unpackedReversed=1]="unpackedReversed",o[o.packed=2]="packed",o[o.downloadUint8AsFloat=3]="downloadUint8AsFloat",o[o.packedLastDimension=4]="packedLastDimension"},9390:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getGlChannels=t.getCoordsDataType=t.getSqueezedParams=t.squeezeInputShape=t.generateShaderFuncNameFromInputSamplerNameAtOutCoords=t.generateShaderFuncNameFromInputSamplerName=t.repeatedTry=t.getPackedShape=void 0;const i=o(2517);t.getPackedShape=function(u){const d=u.length;return u.slice(0,d-1).concat(u[d-1]/4)},t.repeatedTry=async function(u,d=h=>0,a){return new Promise((h,m)=>{let c=0;const l=()=>{if(u())return void h();c++;const n=d(c);a!=null&&c>=a?m():setTimeout(l,n)};l()})},t.generateShaderFuncNameFromInputSamplerName=function(u){return(0,i.assert)(u!==void 0&&u.length!==0,()=>"empty string found for sampler name"),"get"+u.charAt(0).toUpperCase()+u.slice(1)},t.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(u){return(0,i.assert)(u!==void 0&&u.length!==0,()=>"empty string found for sampler name"),"get"+u.charAt(0).toUpperCase()+u.slice(1)+"AtOutCoords"},t.squeezeInputShape=function(u,d){let a=JSON.parse(JSON.stringify(u));return a=d,a},t.getSqueezedParams=function(u,d){return d.map(a=>u[a]).join(", ")},t.getCoordsDataType=function(u){if(u<=1)return"int";if(u===2)return"ivec2";if(u===3)return"ivec3";if(u===4)return"ivec4";if(u===5)return"ivec5";if(u===6)return"ivec6";throw Error(`GPU for rank ${u} is not yet supported`)},t.getGlChannels=function(u=6){return["x","y","z","w","u","v"].slice(0,u)}},7305:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createNewWebGLContext=t.createWebGLContext=void 0;const i=o(6231),u=o(1713),d={};function a(h){const m=function(){if(typeof document>"u"){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}const n=document.createElement("canvas");return n.width=1,n.height=1,n}();let c;const l={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!h||h==="webgl2")&&(c=m.getContext("webgl2",l),c))try{return new u.WebGLContext(c,2)}catch(n){i.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${n}`)}if((!h||h==="webgl")&&(c=m.getContext("webgl",l)||m.getContext("experimental-webgl",l),c))try{return new u.WebGLContext(c,1)}catch(n){i.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${n}`)}throw new Error("WebGL is not supported")}t.createWebGLContext=function h(m){let c;m&&m!=="webgl2"||!("webgl2"in d)?m&&m!=="webgl"||!("webgl"in d)||(c=d.webgl):c=d.webgl2,c=c||a(m),m=m||c.version===1?"webgl":"webgl2";const l=c.gl;return d[m]=c,l.isContextLost()?(delete d[m],h(m)):(l.disable(l.DEPTH_TEST),l.disable(l.STENCIL_TEST),l.disable(l.BLEND),l.disable(l.DITHER),l.disable(l.POLYGON_OFFSET_FILL),l.disable(l.SAMPLE_COVERAGE),l.enable(l.SCISSOR_TEST),l.enable(l.CULL_FACE),l.cullFace(l.BACK),c)},t.createNewWebGLContext=a},1713:function(p,t,o){var i=this&&this.__createBinding||(Object.create?function(l,n,e,r){r===void 0&&(r=e);var s=Object.getOwnPropertyDescriptor(n,e);s&&!("get"in s?!n.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return n[e]}}),Object.defineProperty(l,r,s)}:function(l,n,e,r){r===void 0&&(r=e),l[r]=n[e]}),u=this&&this.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),d=this&&this.__importStar||function(l){if(l&&l.__esModule)return l;var n={};if(l!=null)for(var e in l)e!=="default"&&Object.prototype.hasOwnProperty.call(l,e)&&i(n,l,e);return u(n,l),n};Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLContext=t.linearSearchLastTrue=void 0;const a=o(1670),h=d(o(7769)),m=o(9390);function c(l){let n=0;for(;nthis.isTimerResultAvailable(l)),this.getTimerResult(l)}async createAndWaitForFence(){const l=this.createFence(this.gl);return this.pollFence(l)}createFence(l){let n;const e=l,r=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return l.flush(),n=r===null?()=>!0:()=>{const s=e.clientWaitSync(r,0,0);return s===e.ALREADY_SIGNALED||s===e.CONDITION_SATISFIED},{query:r,isFencePassed:n}}async pollFence(l){return new Promise(n=>{this.addItemToPoll(()=>l.isFencePassed(),()=>n())})}pollItems(){const l=c(this.itemsToPoll.map(n=>n.isDoneFn));for(let n=0;n<=l;++n){const{resolveFn:e}=this.itemsToPoll[n];e()}this.itemsToPoll=this.itemsToPoll.slice(l+1)}async addItemToPoll(l,n){this.itemsToPoll.push({isDoneFn:l,resolveFn:n}),this.itemsToPoll.length>1||await(0,m.repeatedTry)(()=>(this.pollItems(),this.itemsToPoll.length===0))}}},1036:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExecutionPlan=void 0;const i=o(6231);class u{constructor(a,h){this.op=a,this.node=h}}t.ExecutionPlan=class{constructor(d,a,h){this.graph=d,this.profiler=h,this.initialize(a)}initialize(d){this.profiler.event("session","ExecutionPlan.initialize",()=>{const a=this.graph.getNodes();if(a.length!==d.length)throw new Error("The size of nodes and OPs do not match.");this._ops=d.map((h,m)=>new u(h,a[m])),this.reset(),this._starter=[],this._ops.forEach((h,m)=>{let c=!0;for(const l of h.node.inputs)if(!this._values[l]&&this.graph.getInputIndices().indexOf(l)===-1){c=!1;break}c&&this._starter.push(m)})})}reset(){this._values=this.graph.getValues().map(d=>d.tensor)}async execute(d,a){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();const h=d.createInferenceHandler(),m=this.graph.getInputIndices();if(a.length!==m.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${a.length} expected: ${m.length}`);a.forEach((s,f)=>{const g=m[f];this._values[g]=s});const c=this._starter.slice(0),l=this.graph.getValues(),n=this.graph.getNodes();let e=0;for(;ethis._values[T]);if(g.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${f.node}`);const _=g;i.Logger.verbose("ExecPlan",`Runing op:${f.node.name} (${_.map((T,w)=>`'${f.node.inputs[w]}': ${T.type}[${T.dims.join(",")}]`).join(", ")})`);const b=await this.profiler.event("node",f.node.name,async()=>f.op.impl(h,_,f.op.context));if(b.length!==f.node.outputs.length)throw new Error("the size of output does not match model definition.");b.forEach((T,w)=>{const v=f.node.outputs[w];if(this._values[v])throw new Error(`output [${v}] already has value: op:${f.node.name}`);this._values[v]=T});const y=new Set;b.forEach((T,w)=>{const v=f.node.outputs[w];for(const E of l[v].to){const P=n[E];let x=!0;for(const O of P.inputs)if(!this._values[O]){x=!1;break}x&&y.add(E)}}),c.push(...y)}const r=[];for(let s=0;s{Object.defineProperty(t,"__esModule",{value:!0}),t.Graph=void 0;const i=o(1446),u=o(7778),d=o(9395),a=o(9162),h=o(2517);var m=d.onnxruntime.experimental.fbs;t.Graph={from:(e,r)=>new n(e,r)};class c{constructor(r){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,r&&(this.type=h.ProtoUtil.tensorValueTypeFromProto(r.type.tensorType))}get from(){return this._from}get to(){return this._to}}class l{constructor(r,s){r instanceof i.onnx.NodeProto?(this.name=r.name,this.opType=r.opType,this.attributes=new u.Attribute(r.attribute)):r instanceof m.Node&&(this.name=s??r.name(),this.opType=r.opType(),this.attributes=new u.Attribute(h.ProtoUtil.tensorAttributesFromORTFormat(r))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class n{constructor(r,s){if(!r)throw new TypeError("graph is empty");this.buildGraph(r),this.transformGraph(s),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(r){if(r instanceof i.onnx.GraphProto)this.buildGraphFromOnnxFormat(r);else{if(!(r instanceof m.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(r)}}buildGraphFromOnnxFormat(r){const s=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const f=new Map;if(!r.input)throw new Error("missing information in graph: input");const g=[];for(const _ of r.input){if(s.has(_.name))throw new Error(`duplicated input name: ${_.name}`);const b=this._allData.push(new c(_))-1;s.set(_.name,b),g.push(_.name)}if(!r.initializer)throw new Error("missing information in graph: initializer");for(const _ of r.initializer){let b=s.get(_.name);if(b===void 0){const y=new c;y.type={shape:{dims:h.ProtoUtil.tensorDimsFromProto(_.dims)},tensorType:h.ProtoUtil.tensorDataTypeFromProto(_.dataType)},b=this._allData.push(y)-1,s.set(_.name,b)}this._allData[b]._from=-1,this._allData[b].tensor=a.Tensor.fromProto(_)}for(let _=0;_{this._allData[g]._to.forEach(_=>{r.add(_)})});const s=Array.from(r),f=new Array(this._nodes.length).fill("white");for(;s.length>0;){const g=s.pop();f[g]==="gray"?f[g]="black":(s.push(g),f[g]="gray",this._nodes[g].outputs.forEach(_=>{const b=this._allData[_];if(b.tensor!==void 0)throw new Error("node outputs should not be initialized");if(b._from!==g)throw new Error("from property of the Value object doesn't match index of Node being processed");b._to.forEach(y=>{if(f[y]==="gray")throw new Error("model graph is cyclic");f[y]==="white"&&s.push(y)})}))}}transformGraph(r){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),r&&r.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let r=0;for(let s=0;s0&&(this._nodes[s].inputs.forEach(f=>{const g=this._allData[f]._to.indexOf(s+r);g!==-1&&(this._allData[f]._to[g]=s)}),this._nodes[s].outputs.forEach(f=>{this._allData[f]._from&&this._allData[f]._from===s+r&&(this._allData[f]._from=s)})):(r++,this._nodes[s].outputs.forEach(f=>{this._allData[f]._from=-2}),this._nodes.splice(s,1),s--);r=0;for(let s=0;s0){let f=-1;this._allData[s].from!==void 0&&this._allData[s].from!==-1?(f=this._nodes[this._allData[s].from].outputs.indexOf(s+r),f!==-1&&(this._nodes[this._allData[s].from].outputs[f]=s)):(f=this._allInputIndices.indexOf(s+r),f!==-1&&(this._allInputIndices[f]=s)),this._allData[s].to.forEach(g=>{f=this._nodes[g].inputs.indexOf(s+r),f!==-1&&(this._nodes[g].inputs[f]=s)}),this._allData[s].to.length===0&&(f=this._allOutputIndices.indexOf(s+r),f!==-1&&(this._allOutputIndices[f]=s))}}else r++,this._allData.splice(s,1),s--}deleteNode(r){const s=this._nodes[r];if(s.outputs.length>1){for(let T=1;T0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}s.executeNode=!1;const f=s.inputs[0],g=s.outputs[0],_=this._allData[g].to,b=this._allData[f].to.indexOf(r);if(b===-1)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[f].to.splice(b,1),this._allData[g]._to=[];const y=this._allOutputIndices.indexOf(g);if(y!==-1&&(this._allOutputIndices[y]=f),_&&_.length>0)for(const T of _){const w=this._nodes[T].inputs.indexOf(g);if(w===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[T].inputs[w]=f,this._allData[f].to.push(T)}}removeAllDropoutNodes(){let r=0;for(const s of this._nodes){if(s.opType==="Dropout"){if(s.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(s.outputs.length!==1&&s.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(s.outputs.length===2&&this._allData[s.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(r)}r++}}removeAllIdentityNodes(){let r=0;for(const s of this._nodes)s.opType==="Identity"&&this.deleteNode(r),r++}isActivation(r){switch(r.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const r of this._nodes)if(r.opType==="Conv"){const s=this._allData[r.outputs[0]]._to;if(s.length===1&&this.isActivation(this._nodes[s[0]])){const f=this._nodes[s[0]];if(f.opType==="Clip")if(f.inputs.length===1)try{r.attributes.set("activation_params","floats",[f.attributes.getFloat("min"),f.attributes.getFloat("max")])}catch{r.attributes.set("activation_params","floats",[h.MIN_CLIP,h.MAX_CLIP])}else{if(!(f.inputs.length>=3&&this._allData[f.inputs[1]].tensor!==void 0&&this._allData[f.inputs[2]].tensor!==void 0))continue;r.attributes.set("activation_params","floats",[this._allData[f.inputs[1]].tensor.floatData[0],this._allData[f.inputs[2]].tensor.floatData[0]])}r.attributes.set("activation","string",f.opType),this.deleteNode(s[0])}}}}},6231:(p,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.now=t.Profiler=t.Logger=void 0;const o={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},i={none:new class{log(l,n,e){}},console:new class{log(l,n,e){console.log(`${this.color(l)} ${e?"\x1B[35m"+e+"\x1B[0m ":""}${n}`)}color(l){switch(l){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: ${l}`)}}}},u={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let d={"":u};function a(l,n,e,r){if(n===void 0)return s=l,{verbose:a.verbose.bind(null,s),info:a.info.bind(null,s),warning:a.warning.bind(null,s),error:a.error.bind(null,s),fatal:a.fatal.bind(null,s)};if(e===void 0)h(l,n);else if(typeof e=="number"&&r===void 0)h(l,n);else if(typeof e=="string"&&r===void 0)h(l,e,0,n);else{if(typeof e!="string"||typeof r!="number")throw new TypeError("input is valid");h(l,e,0,n)}var s}function h(l,n,e,r){const s=d[r||""]||d[""];o[l]{g.then(async y=>{s&&await s.end(),_(y)},async y=>{s&&await s.end(),b(y)})});if(!f&&s){const _=s.end();if(_&&typeof _.then=="function")return new Promise((b,y)=>{_.then(()=>{b(g)},T=>{y(T)})})}return g}begin(l,n,e){if(!this._started)throw new Error("profiler is not started yet");if(e===void 0){const r=(0,t.now)();return this.flush(r),new m(l,n,r,s=>this.endSync(s))}{const r=e.beginTimer();return new m(l,n,0,async s=>this.end(s),r,e)}}async end(l){const n=await l.checkTimer();this._timingEvents.length=this._flushBatchSize||l-this._flushTime>=this._flushIntervalInMilliseconds){for(const n=this._flushPointer;this._flushPointerperformance.now():Date.now},2644:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const i=o(5686),u=o(1446),d=o(7070),a=o(9395),h=o(2517);var m=a.onnxruntime.experimental.fbs;t.Model=class{constructor(){}load(c,l,n){if(!n)try{return void this.loadFromOnnxFormat(c,l)}catch(e){if(n!==void 0)throw e}this.loadFromOrtFormat(c,l)}loadFromOnnxFormat(c,l){const n=u.onnx.ModelProto.decode(c);if(h.LongUtil.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map(e=>({domain:e.domain,version:h.LongUtil.longToNumber(e.version)})),this._graph=d.Graph.from(n.graph,l)}loadFromOrtFormat(c,l){const n=new i.flatbuffers.ByteBuffer(c),e=m.InferenceSession.getRootAsInferenceSession(n).model();if(h.LongUtil.longToNumber(e.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.FLOAT_TYPES=t.INT_TYPES=t.NUMBER_TYPES=void 0,t.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],t.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],t.FLOAT_TYPES=["float32","float64"]},1047:(p,t)=>{function o(i,u){if(u.endsWith("+")){const d=Number.parseInt(u.substring(0,u.length-1),10);return!isNaN(d)&&d<=i}if(u.split("-").length===2){const d=u.split("-"),a=Number.parseInt(d[0],10),h=Number.parseInt(d[1],10);return!isNaN(a)&&!isNaN(h)&&a<=i&&i<=h}return Number.parseInt(u,10)===i}Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOperator=void 0,t.resolveOperator=function(i,u,d){for(const a of d){const h=a[0],m=a[1],c=a[2],l=a[3],n=a[4];if(i.opType===h){for(const e of u)if((e.domain===m||e.domain==="ai.onnx"&&m==="")&&o(e.version,c))return{opImpl:l,opInit:n}}}throw new TypeError(`cannot resolve operator '${i.opType}' with opsets: ${u.map(a=>`${a.domain||"ai.onnx"} v${a.version}`).join(", ")}`)}},9395:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onnxruntime=void 0;const i=o(5686);var u,d;u=t.onnxruntime||(t.onnxruntime={}),function(a){(function(h){h[h.UNDEFINED=0]="UNDEFINED",h[h.FLOAT=1]="FLOAT",h[h.INT=2]="INT",h[h.STRING=3]="STRING",h[h.TENSOR=4]="TENSOR",h[h.GRAPH=5]="GRAPH",h[h.FLOATS=6]="FLOATS",h[h.INTS=7]="INTS",h[h.STRINGS=8]="STRINGS",h[h.TENSORS=9]="TENSORS",h[h.GRAPHS=10]="GRAPHS",h[h.SPARSE_TENSOR=11]="SPARSE_TENSOR",h[h.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(a.AttributeType||(a.AttributeType={}))}((d=u.experimental||(u.experimental={})).fbs||(d.fbs={})),function(a){(function(h){(function(m){(function(c){c[c.UNKNOWN=0]="UNKNOWN",c[c.VALUE=1]="VALUE",c[c.PARAM=2]="PARAM"})(m.DimensionValueType||(m.DimensionValueType={}))})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){(function(c){c[c.UNDEFINED=0]="UNDEFINED",c[c.FLOAT=1]="FLOAT",c[c.UINT8=2]="UINT8",c[c.INT8=3]="INT8",c[c.UINT16=4]="UINT16",c[c.INT16=5]="INT16",c[c.INT32=6]="INT32",c[c.INT64=7]="INT64",c[c.STRING=8]="STRING",c[c.BOOL=9]="BOOL",c[c.FLOAT16=10]="FLOAT16",c[c.DOUBLE=11]="DOUBLE",c[c.UINT32=12]="UINT32",c[c.UINT64=13]="UINT64",c[c.COMPLEX64=14]="COMPLEX64",c[c.COMPLEX128=15]="COMPLEX128",c[c.BFLOAT16=16]="BFLOAT16"})(m.TensorDataType||(m.TensorDataType={}))})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){(function(c){c[c.Primitive=0]="Primitive",c[c.Fused=1]="Fused"})(m.NodeType||(m.NodeType={}))})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){(function(c){c[c.NONE=0]="NONE",c[c.tensor_type=1]="tensor_type",c[c.sequence_type=2]="sequence_type",c[c.map_type=3]="map_type"})(m.TypeInfoValue||(m.TypeInfoValue={}))})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsShape(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsShape(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}dim(n,e){let r=this.bb.__offset(this.bb_pos,4);return r?(e||new a.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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,e){n.addFieldOffset(0,e,0)}static createDimVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startDimVector(n,e){n.startVector(4,e,4)}static endShape(n){return n.endObject()}static createShape(n,e){return c.startShape(n),c.addDim(n,e),c.endShape(n)}}m.Shape=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsDimension(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsDimension(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}value(n){let e=this.bb.__offset(this.bb_pos,4);return e?(n||new a.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}denotation(n){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,n):null}static startDimension(n){n.startObject(2)}static addValue(n,e){n.addFieldOffset(0,e,0)}static addDenotation(n,e){n.addFieldOffset(1,e,0)}static endDimension(n){return n.endObject()}static createDimension(n,e,r){return c.startDimension(n),c.addValue(n,e),c.addDenotation(n,r),c.endDimension(n)}}m.Dimension=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsDimensionValue(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsDimensionValue(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__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):a.experimental.fbs.DimensionValueType.UNKNOWN}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 e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,n):null}static startDimensionValue(n){n.startObject(3)}static addDimType(n,e){n.addFieldInt8(0,e,a.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(n,e){n.addFieldInt64(1,e,n.createLong(0,0))}static addDimParam(n,e){n.addFieldOffset(2,e,0)}static endDimensionValue(n){return n.endObject()}static createDimensionValue(n,e,r,s){return c.startDimensionValue(n),c.addDimType(n,e),c.addDimValue(n,r),c.addDimParam(n,s),c.endDimensionValue(n)}}m.DimensionValue=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsTensorTypeAndShape(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsTensorTypeAndShape(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__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):a.experimental.fbs.TensorDataType.UNDEFINED}shape(n){let e=this.bb.__offset(this.bb_pos,6);return e?(n||new a.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startTensorTypeAndShape(n){n.startObject(2)}static addElemType(n,e){n.addFieldInt32(0,e,a.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(n,e){n.addFieldOffset(1,e,0)}static endTensorTypeAndShape(n){return n.endObject()}static createTensorTypeAndShape(n,e,r){return c.startTensorTypeAndShape(n),c.addElemType(n,e),c.addShape(n,r),c.endTensorTypeAndShape(n)}}m.TensorTypeAndShape=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsMapType(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsMapType(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__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):a.experimental.fbs.TensorDataType.UNDEFINED}valueType(n){let e=this.bb.__offset(this.bb_pos,6);return e?(n||new a.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startMapType(n){n.startObject(2)}static addKeyType(n,e){n.addFieldInt32(0,e,a.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(n,e){n.addFieldOffset(1,e,0)}static endMapType(n){return n.endObject()}static createMapType(n,e,r){return c.startMapType(n),c.addKeyType(n,e),c.addValueType(n,r),c.endMapType(n)}}m.MapType=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsSequenceType(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsSequenceType(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}elemType(n){let e=this.bb.__offset(this.bb_pos,4);return e?(n||new a.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSequenceType(n){n.startObject(1)}static addElemType(n,e){n.addFieldOffset(0,e,0)}static endSequenceType(n){return n.endObject()}static createSequenceType(n,e){return c.startSequenceType(n),c.addElemType(n,e),c.endSequenceType(n)}}m.SequenceType=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(h.fbs||(h.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(m,c){return this.bb_pos=m,this.bb=c,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(m,c,l,n){return m.prep(4,12),m.writeInt32(n),m.writeInt32(l),m.writeInt32(c),m.offset()}}})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsNodeEdge(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsNodeEdge(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__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,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new a.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*n,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,e){let r=this.bb.__offset(this.bb_pos,8);return r?(e||new a.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*n,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,e){n.addFieldInt32(0,e,0)}static addInputEdges(n,e){n.addFieldOffset(1,e,0)}static startInputEdgesVector(n,e){n.startVector(12,e,4)}static addOutputEdges(n,e){n.addFieldOffset(2,e,0)}static startOutputEdgesVector(n,e){n.startVector(12,e,4)}static endNodeEdge(n){return n.endObject()}static createNodeEdge(n,e,r,s){return c.startNodeEdge(n),c.addNodeIndex(n,e),c.addInputEdges(n,r),c.addOutputEdges(n,s),c.endNodeEdge(n)}}m.NodeEdge=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsNode(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsNode(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}name(n){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,n):null}docString(n){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,n):null}domain(n){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,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 e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,n):null}type(){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.readInt32(this.bb_pos+n):a.experimental.fbs.NodeType.Primitive}executionProviderType(n){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__string(this.bb_pos+e,n):null}inputs(n,e){let r=this.bb.__offset(this.bb_pos,20);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*n,e):null}inputsLength(){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__vector_len(this.bb_pos+n):0}outputs(n,e){let r=this.bb.__offset(this.bb_pos,22);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*n,e):null}outputsLength(){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__vector_len(this.bb_pos+n):0}attributes(n,e){let r=this.bb.__offset(this.bb_pos,24);return r?(e||new a.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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 e=this.bb.__offset(this.bb_pos,26);return e?this.bb.readInt32(this.bb.__vector(this.bb_pos+e)+4*n):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,e){let r=this.bb.__offset(this.bb_pos,28);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*n,e):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,e){n.addFieldOffset(0,e,0)}static addDocString(n,e){n.addFieldOffset(1,e,0)}static addDomain(n,e){n.addFieldOffset(2,e,0)}static addSinceVersion(n,e){n.addFieldInt32(3,e,0)}static addIndex(n,e){n.addFieldInt32(4,e,0)}static addOpType(n,e){n.addFieldOffset(5,e,0)}static addType(n,e){n.addFieldInt32(6,e,a.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(n,e){n.addFieldOffset(7,e,0)}static addInputs(n,e){n.addFieldOffset(8,e,0)}static createInputsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startInputsVector(n,e){n.startVector(4,e,4)}static addOutputs(n,e){n.addFieldOffset(9,e,0)}static createOutputsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startOutputsVector(n,e){n.startVector(4,e,4)}static addAttributes(n,e){n.addFieldOffset(10,e,0)}static createAttributesVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startAttributesVector(n,e){n.startVector(4,e,4)}static addInputArgCounts(n,e){n.addFieldOffset(11,e,0)}static createInputArgCountsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addInt32(e[r]);return n.endVector()}static startInputArgCountsVector(n,e){n.startVector(4,e,4)}static addImplicitInputs(n,e){n.addFieldOffset(12,e,0)}static createImplicitInputsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startImplicitInputsVector(n,e){n.startVector(4,e,4)}static endNode(n){return n.endObject()}static createNode(n,e,r,s,f,g,_,b,y,T,w,v,E,P){return c.startNode(n),c.addName(n,e),c.addDocString(n,r),c.addDomain(n,s),c.addSinceVersion(n,f),c.addIndex(n,g),c.addOpType(n,_),c.addType(n,b),c.addExecutionProviderType(n,y),c.addInputs(n,T),c.addOutputs(n,w),c.addAttributes(n,v),c.addInputArgCounts(n,E),c.addImplicitInputs(n,P),c.endNode(n)}}m.Node=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsValueInfo(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsValueInfo(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}name(n){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,n):null}docString(n){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,n):null}type(n){let e=this.bb.__offset(this.bb_pos,8);return e?(n||new a.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startValueInfo(n){n.startObject(3)}static addName(n,e){n.addFieldOffset(0,e,0)}static addDocString(n,e){n.addFieldOffset(1,e,0)}static addType(n,e){n.addFieldOffset(2,e,0)}static endValueInfo(n){return n.endObject()}static createValueInfo(n,e,r,s){return c.startValueInfo(n),c.addName(n,e),c.addDocString(n,r),c.addType(n,s),c.endValueInfo(n)}}m.ValueInfo=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsTypeInfo(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsTypeInfo(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}denotation(n){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,n):null}valueType(){let n=this.bb.__offset(this.bb_pos,6);return n?this.bb.readUint8(this.bb_pos+n):a.experimental.fbs.TypeInfoValue.NONE}value(n){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(n,this.bb_pos+e):null}static startTypeInfo(n){n.startObject(3)}static addDenotation(n,e){n.addFieldOffset(0,e,0)}static addValueType(n,e){n.addFieldInt8(1,e,a.experimental.fbs.TypeInfoValue.NONE)}static addValue(n,e){n.addFieldOffset(2,e,0)}static endTypeInfo(n){return n.endObject()}static createTypeInfo(n,e,r,s){return c.startTypeInfo(n),c.addDenotation(n,e),c.addValueType(n,r),c.addValue(n,s),c.endTypeInfo(n)}}m.TypeInfo=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsOperatorSetId(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsOperatorSetId(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}domain(n){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,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,e){n.addFieldOffset(0,e,0)}static addVersion(n,e){n.addFieldInt64(1,e,n.createLong(0,0))}static endOperatorSetId(n){return n.endObject()}static createOperatorSetId(n,e,r){return c.startOperatorSetId(n),c.addDomain(n,e),c.addVersion(n,r),c.endOperatorSetId(n)}}m.OperatorSetId=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsTensor(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsTensor(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}name(n){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,n):null}docString(n){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,n):null}dims(n){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*n):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):a.experimental.fbs.TensorDataType.UNDEFINED}rawData(n){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+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,e){let r=this.bb.__offset(this.bb_pos,14);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*n,e):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,e){n.addFieldOffset(0,e,0)}static addDocString(n,e){n.addFieldOffset(1,e,0)}static addDims(n,e){n.addFieldOffset(2,e,0)}static createDimsVector(n,e){n.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)n.addInt64(e[r]);return n.endVector()}static startDimsVector(n,e){n.startVector(8,e,8)}static addDataType(n,e){n.addFieldInt32(3,e,a.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(n,e){n.addFieldOffset(4,e,0)}static createRawDataVector(n,e){n.startVector(1,e.length,1);for(let r=e.length-1;r>=0;r--)n.addInt8(e[r]);return n.endVector()}static startRawDataVector(n,e){n.startVector(1,e,1)}static addStringData(n,e){n.addFieldOffset(5,e,0)}static createStringDataVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startStringDataVector(n,e){n.startVector(4,e,4)}static endTensor(n){return n.endObject()}static createTensor(n,e,r,s,f,g,_){return c.startTensor(n),c.addName(n,e),c.addDocString(n,r),c.addDims(n,s),c.addDataType(n,f),c.addRawData(n,g),c.addStringData(n,_),c.endTensor(n)}}m.Tensor=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsSparseTensor(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsSparseTensor(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}values(n){let e=this.bb.__offset(this.bb_pos,4);return e?(n||new a.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}indices(n){let e=this.bb.__offset(this.bb_pos,6);return e?(n||new a.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}dims(n){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*n):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,e){n.addFieldOffset(0,e,0)}static addIndices(n,e){n.addFieldOffset(1,e,0)}static addDims(n,e){n.addFieldOffset(2,e,0)}static createDimsVector(n,e){n.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)n.addInt64(e[r]);return n.endVector()}static startDimsVector(n,e){n.startVector(8,e,8)}static endSparseTensor(n){return n.endObject()}static createSparseTensor(n,e,r,s){return c.startSparseTensor(n),c.addValues(n,e),c.addIndices(n,r),c.addDims(n,s),c.endSparseTensor(n)}}m.SparseTensor=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsAttribute(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsAttribute(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}name(n){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,n):null}docString(n){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,n):null}type(){let n=this.bb.__offset(this.bb_pos,8);return n?this.bb.readInt32(this.bb_pos+n):a.experimental.fbs.AttributeType.UNDEFINED}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 e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,n):null}t(n){let e=this.bb.__offset(this.bb_pos,16);return e?(n||new a.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}g(n){let e=this.bb.__offset(this.bb_pos,18);return e?(n||new a.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}floats(n){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.readFloat32(this.bb.__vector(this.bb_pos+e)+4*n):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 e=this.bb.__offset(this.bb_pos,22);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*n):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,e){let r=this.bb.__offset(this.bb_pos,24);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*n,e):null}stringsLength(){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__vector_len(this.bb_pos+n):0}tensors(n,e){let r=this.bb.__offset(this.bb_pos,26);return r?(e||new a.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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,e){let r=this.bb.__offset(this.bb_pos,28);return r?(e||new a.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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,e){n.addFieldOffset(0,e,0)}static addDocString(n,e){n.addFieldOffset(1,e,0)}static addType(n,e){n.addFieldInt32(2,e,a.experimental.fbs.AttributeType.UNDEFINED)}static addF(n,e){n.addFieldFloat32(3,e,0)}static addI(n,e){n.addFieldInt64(4,e,n.createLong(0,0))}static addS(n,e){n.addFieldOffset(5,e,0)}static addT(n,e){n.addFieldOffset(6,e,0)}static addG(n,e){n.addFieldOffset(7,e,0)}static addFloats(n,e){n.addFieldOffset(8,e,0)}static createFloatsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addFloat32(e[r]);return n.endVector()}static startFloatsVector(n,e){n.startVector(4,e,4)}static addInts(n,e){n.addFieldOffset(9,e,0)}static createIntsVector(n,e){n.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)n.addInt64(e[r]);return n.endVector()}static startIntsVector(n,e){n.startVector(8,e,8)}static addStrings(n,e){n.addFieldOffset(10,e,0)}static createStringsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startStringsVector(n,e){n.startVector(4,e,4)}static addTensors(n,e){n.addFieldOffset(11,e,0)}static createTensorsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startTensorsVector(n,e){n.startVector(4,e,4)}static addGraphs(n,e){n.addFieldOffset(12,e,0)}static createGraphsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startGraphsVector(n,e){n.startVector(4,e,4)}static endAttribute(n){return n.endObject()}static createAttribute(n,e,r,s,f,g,_,b,y,T,w,v,E,P){return c.startAttribute(n),c.addName(n,e),c.addDocString(n,r),c.addType(n,s),c.addF(n,f),c.addI(n,g),c.addS(n,_),c.addT(n,b),c.addG(n,y),c.addFloats(n,T),c.addInts(n,w),c.addStrings(n,v),c.addTensors(n,E),c.addGraphs(n,P),c.endAttribute(n)}}m.Attribute=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsGraph(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsGraph(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}initializers(n,e){let r=this.bb.__offset(this.bb_pos,4);return r?(e||new a.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new a.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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,e){let r=this.bb.__offset(this.bb_pos,8);return r?(e||new a.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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,e){let r=this.bb.__offset(this.bb_pos,12);return r?(e||new a.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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,e){let r=this.bb.__offset(this.bb_pos,14);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*n,e):null}inputsLength(){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__vector_len(this.bb_pos+n):0}outputs(n,e){let r=this.bb.__offset(this.bb_pos,16);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*n,e):null}outputsLength(){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.__vector_len(this.bb_pos+n):0}sparseInitializers(n,e){let r=this.bb.__offset(this.bb_pos,18);return r?(e||new a.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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,e){n.addFieldOffset(0,e,0)}static createInitializersVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startInitializersVector(n,e){n.startVector(4,e,4)}static addNodeArgs(n,e){n.addFieldOffset(1,e,0)}static createNodeArgsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startNodeArgsVector(n,e){n.startVector(4,e,4)}static addNodes(n,e){n.addFieldOffset(2,e,0)}static createNodesVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startNodesVector(n,e){n.startVector(4,e,4)}static addMaxNodeIndex(n,e){n.addFieldInt32(3,e,0)}static addNodeEdges(n,e){n.addFieldOffset(4,e,0)}static createNodeEdgesVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startNodeEdgesVector(n,e){n.startVector(4,e,4)}static addInputs(n,e){n.addFieldOffset(5,e,0)}static createInputsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startInputsVector(n,e){n.startVector(4,e,4)}static addOutputs(n,e){n.addFieldOffset(6,e,0)}static createOutputsVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startOutputsVector(n,e){n.startVector(4,e,4)}static addSparseInitializers(n,e){n.addFieldOffset(7,e,0)}static createSparseInitializersVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startSparseInitializersVector(n,e){n.startVector(4,e,4)}static endGraph(n){return n.endObject()}static createGraph(n,e,r,s,f,g,_,b,y){return c.startGraph(n),c.addInitializers(n,e),c.addNodeArgs(n,r),c.addNodes(n,s),c.addMaxNodeIndex(n,f),c.addNodeEdges(n,g),c.addInputs(n,_),c.addOutputs(n,b),c.addSparseInitializers(n,y),c.endGraph(n)}}m.Graph=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsModel(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsModel(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__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,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new a.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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 e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,n):null}producerVersion(n){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,n):null}domain(n){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,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 e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__string(this.bb_pos+e,n):null}graph(n){let e=this.bb.__offset(this.bb_pos,18);return e?(n||new a.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}graphDocString(n){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__string(this.bb_pos+e,n):null}static startModel(n){n.startObject(9)}static addIrVersion(n,e){n.addFieldInt64(0,e,n.createLong(0,0))}static addOpsetImport(n,e){n.addFieldOffset(1,e,0)}static createOpsetImportVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startOpsetImportVector(n,e){n.startVector(4,e,4)}static addProducerName(n,e){n.addFieldOffset(2,e,0)}static addProducerVersion(n,e){n.addFieldOffset(3,e,0)}static addDomain(n,e){n.addFieldOffset(4,e,0)}static addModelVersion(n,e){n.addFieldInt64(5,e,n.createLong(0,0))}static addDocString(n,e){n.addFieldOffset(6,e,0)}static addGraph(n,e){n.addFieldOffset(7,e,0)}static addGraphDocString(n,e){n.addFieldOffset(8,e,0)}static endModel(n){return n.endObject()}static createModel(n,e,r,s,f,g,_,b,y,T){return c.startModel(n),c.addIrVersion(n,e),c.addOpsetImport(n,r),c.addProducerName(n,s),c.addProducerVersion(n,f),c.addDomain(n,g),c.addModelVersion(n,_),c.addDocString(n,b),c.addGraph(n,y),c.addGraphDocString(n,T),c.endModel(n)}}m.Model=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsKernelCreateInfos(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsKernelCreateInfos(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}nodeIndices(n){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb.__vector(this.bb_pos+e)+4*n):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 e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint64(this.bb.__vector(this.bb_pos+e)+8*n):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,e){n.addFieldOffset(0,e,0)}static createNodeIndicesVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addInt32(e[r]);return n.endVector()}static startNodeIndicesVector(n,e){n.startVector(4,e,4)}static addKernelDefHashes(n,e){n.addFieldOffset(1,e,0)}static createKernelDefHashesVector(n,e){n.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)n.addInt64(e[r]);return n.endVector()}static startKernelDefHashesVector(n,e){n.startVector(8,e,8)}static endKernelCreateInfos(n){return n.endObject()}static createKernelCreateInfos(n,e,r){return c.startKernelCreateInfos(n),c.addNodeIndices(n,e),c.addKernelDefHashes(n,r),c.endKernelCreateInfos(n)}}m.KernelCreateInfos=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsSubGraphSessionState(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsSubGraphSessionState(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}graphId(n){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,n):null}sessionState(n){let e=this.bb.__offset(this.bb_pos,6);return e?(n||new a.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSubGraphSessionState(n){n.startObject(2)}static addGraphId(n,e){n.addFieldOffset(0,e,0)}static addSessionState(n,e){n.addFieldOffset(1,e,0)}static endSubGraphSessionState(n){let e=n.endObject();return n.requiredField(e,4),e}static createSubGraphSessionState(n,e,r){return c.startSubGraphSessionState(n),c.addGraphId(n,e),c.addSessionState(n,r),c.endSubGraphSessionState(n)}}m.SubGraphSessionState=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsSessionState(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsSessionState(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}kernels(n){let e=this.bb.__offset(this.bb_pos,4);return e?(n||new a.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}subGraphSessionStates(n,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new a.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*n),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,e){n.addFieldOffset(0,e,0)}static addSubGraphSessionStates(n,e){n.addFieldOffset(1,e,0)}static createSubGraphSessionStatesVector(n,e){n.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)n.addOffset(e[r]);return n.endVector()}static startSubGraphSessionStatesVector(n,e){n.startVector(4,e,4)}static endSessionState(n){return n.endObject()}static createSessionState(n,e,r){return c.startSessionState(n),c.addKernels(n,e),c.addSubGraphSessionStates(n,r),c.endSessionState(n)}}m.SessionState=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(a){(function(h){(function(m){class c{constructor(){this.bb=null,this.bb_pos=0}__init(n,e){return this.bb_pos=n,this.bb=e,this}static getRootAsInferenceSession(n,e){return(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsInferenceSession(n,e){return n.setPosition(n.position()+i.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(n.readInt32(n.position())+n.position(),n)}static bufferHasIdentifier(n){return n.__has_identifier("ORTM")}ortVersion(n){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,n):null}model(n){let e=this.bb.__offset(this.bb_pos,6);return e?(n||new a.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}sessionState(n){let e=this.bb.__offset(this.bb_pos,8);return e?(n||new a.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startInferenceSession(n){n.startObject(3)}static addOrtVersion(n,e){n.addFieldOffset(0,e,0)}static addModel(n,e){n.addFieldOffset(1,e,0)}static addSessionState(n,e){n.addFieldOffset(2,e,0)}static endInferenceSession(n){return n.endObject()}static finishInferenceSessionBuffer(n,e){n.finish(e,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(n,e){n.finish(e,"ORTM",!0)}static createInferenceSession(n,e,r,s){return c.startInferenceSession(n),c.addOrtVersion(n,e),c.addModel(n,r),c.addSessionState(n,s),c.endInferenceSession(n)}}m.InferenceSession=c})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(t.onnxruntime||(t.onnxruntime={}))},7448:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OnnxjsSessionHandler=void 0;const i=o(1670),u=o(9162);t.OnnxjsSessionHandler=class{constructor(d){this.session=d,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(d,a,h){const m=new Map;for(const n in d)if(Object.hasOwnProperty.call(d,n)){const e=d[n];m.set(n,new u.Tensor(e.dims,e.type,void 0,void 0,e.data))}const c=await this.session.run(m),l={};return c.forEach((n,e)=>{l[e]=new i.Tensor(n.type,n.data,n.dims)}),l}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Session=void 0;const i=o(7067),u=o(1296),d=o(7091),a=o(1036),h=o(6231),m=o(2644);t.Session=class{constructor(c={}){this._initialized=!1,this.backendHint=c.backendHint,this.profiler=h.Profiler.create(c.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(c,l,n){await this.profiler.event("session","Session.loadModel",async()=>{const e=await(0,d.resolveBackend)(this.backendHint);if(this.sessionHandler=e.createSessionHandler(this.context),this._model=new m.Model,typeof c=="string"){const r=c.endsWith(".ort");if(typeof fetch>"u"){const s=await(0,u.promisify)(i.readFile)(c);this.initialize(s,r)}else{const s=await fetch(c),f=await s.arrayBuffer();this.initialize(new Uint8Array(f),r)}}else if(ArrayBuffer.isView(c))this.initialize(c);else{const r=new Uint8Array(c,l||0,n||c.byteLength);this.initialize(r)}})}initialize(c,l){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{const n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(c,n,l),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new a.ExecutionPlan(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(c){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{const l=this.normalizeAndValidateInputs(c),n=await this._executionPlan.execute(this.sessionHandler,l);return this.createOutput(n)})}normalizeAndValidateInputs(c){const l=this._model.graph.getInputNames();if(Array.isArray(c)){if(c.length!==l.length)throw new Error(`incorrect input array length: expected ${l.length} but got ${c.length}`)}else{if(c.size!==l.length)throw new Error(`incorrect input map size: expected ${l.length} but got ${c.size}`);const n=new Array(c.size);let e=0;for(let r=0;rtypeof P=="string")))throw new TypeError("cache should be a string array");E&&(this.cache=new Array(v))}else{if(T!==void 0){const P=e(_);if(!(T instanceof P))throw new TypeError(`cache should be type ${P.name}`)}if(E){const P=new ArrayBuffer(v*function(x){switch(x){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 ${x}`)}}(_));this.cache=function(x,O){return new(e(O))(x)}(P,_)}}}static fromProto(g){if(!g)throw new Error("cannot construct Value from an empty tensor");const _=m.ProtoUtil.tensorDataTypeFromProto(g.dataType),b=m.ProtoUtil.tensorDimsFromProto(g.dims),y=new l(b,_);if(_==="string")g.stringData.forEach((T,w)=>{y.data[w]=(0,m.decodeUtf8String)(T)});else if(g.rawData&&typeof g.rawData.byteLength=="number"&&g.rawData.byteLength>0){const T=y.data,w=new DataView(g.rawData.buffer,g.rawData.byteOffset,g.rawData.byteLength),v=n(g.dataType),E=g.rawData.byteLength/v;if(g.rawData.byteLength%v!=0)throw new Error("invalid buffer length");if(T.length!==E)throw new Error("buffer length mismatch");for(let P=0;P0){const T=y.data,w=new DataView(g.rawDataArray().buffer,g.rawDataArray().byteOffset,g.rawDataLength()),v=n(g.dataType()),E=g.rawDataLength()/v;if(g.rawDataLength()%v!=0)throw new Error("invalid buffer length");if(T.length!==E)throw new Error("buffer length mismatch");for(let P=0;P1&&O>1)return;E[v-P]=Math.max(x,O)}return E}static index(_,b){const y=new Array(b.length);return c.fillIndex(_,b,y),y}static fillIndex(_,b,y){const T=_.length-b.length;for(let w=0;w=0;X--)x[X]=k%v[X],k=Math.floor(k/v[X]);V||(c.fillIndex(x,_.dims,O),N=_.get(O)),C||(c.fillIndex(x,b.dims,$),D=b.get($)),P.set(x,y(N,D))}}return P}}static isValidBroadcast(_,b){const y=_.length,T=b.length;if(y>T)return!1;for(let w=1;w<=y;w++)if(_[y-w]!==1&&_[y-w]!==b[T-w])return!1;return!0}static getBroadcastDims(_,b){const y=_.length,T=[];for(let w=0;w1&&E===1&&T.unshift(v)}return T}}t.BroadcastUtil=c,t.arrayCopyHelper=function(g,_,b,y,T){if(y<0||y>=_.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+T>_.length)throw new Error("source indices to be copied are outside bounds");if(b+T>g.length)throw new Error("target array is too small to hold result");for(let w=0;wd.default.isLong(b)?b.toNumber():b)}static tensorValueTypeFromProto(_){return{tensorType:l.tensorDataTypeFromProto(_.elemType),shape:{dims:l.tensorDimsFromProto(_.shape.dim.map(b=>b.dimValue))}}}static tensorDimsFromORTFormat(_){const b=[];for(let y=0;y<_.dimsLength();y++)b.push(n.longToNumber(_.dims(y)));return b}static tensorAttributesFromORTFormat(_){const b=[];for(let y=0;y<_.attributesLength();y++)b.push(_.attributes(y));return b}}t.ProtoUtil=l;class n{static longToNumber(_,b){return d.default.isLong(_)?_.toNumber():_ instanceof u.flatbuffers.Long?d.default.fromValue({low:_.low,high:_.high,unsigned:b!=null&&b}).toNumber():_}static isLong(_){return d.default.isLong(_)||_ instanceof u.flatbuffers.Long}}t.LongUtil=n;class e{static size(_){return e.getSizeFromDimensionRange(_,0,_.length)}static sizeFromDimension(_,b){if(b<0||b>_.length)throw new Error(`invalid dimension of ${b} for sizeFromDimension as Tensor has ${_.length} dimensions.`);return e.getSizeFromDimensionRange(_,b,_.length)}static sizeToDimension(_,b){if(b<0||b>_.length)throw new Error(`invalid dimension of ${b} for sizeToDimension as Tensor has ${_.length} dimensions.`);return e.getSizeFromDimensionRange(_,0,b)}static getSizeFromDimensionRange(_,b,y){let T=1;for(let w=b;w=0;--T)y[T]=y[T+1]*_[T+1];return y}static transpose(_){return _.slice().reverse()}static indicesToOffset(_,b,y){y===void 0&&(y=_.length);let T=0;for(let w=0;w=b)throw new Error("unsupported axis for this operation.");return _<0?_+b:_}static normalizeAxes(_,b){return _.map(y=>this.normalizeAxis(y,b))}static incrementIndex(_,b,y){if(b.length===0||_.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(y===void 0)y=b.length;else if(y<=0||y>b.length)throw new Error("Incorrect axis to increment on");for(let T=y-1;T>=0&&(_[T]++,!(_[T]=_.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");T[P]=_[P]}else T[P]=b[P];v*=T[P]}}const E=e.size(_);if(w!==-1){if(E%v!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${_}] Output shape: [${b}]`);T[w]=E/v}else if(v!==E)throw new Error("reshapedDims and originalDims don't have matching sizes");return T}static sortBasedOnPerm(_,b){return b?b.map(y=>_[y]):_.slice().reverse()}static padShape(_,b){const y=_.length;return _.map((T,w)=>T+b[w]+b[w+y])}static areEqual(_,b){return _.length===b.length&&_.every((y,T)=>y===b[T])}static validateDimsAndCalcSize(_){if(_.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let b=1;for(const y of _){if(!Number.isInteger(y))throw new TypeError(`Invalid shape: ${y} is not an integer`);if(y<0||y>2147483647)throw new TypeError(`Invalid shape: length ${y} is not allowed`);b*=y}return b}static flattenShape(_,b){b<0&&(b+=_.length);const y=_.reduce((w,v)=>w*v,1),T=_.slice(b).reduce((w,v)=>w*v,1);return[y/T,T]}static squeezeShape(_,b){const y=new Array;b=e.normalizeAxes(b,_.length);for(let T=0;T<_.length;T++){const w=b.indexOf(T)>=0;if(w&&_[T]!==1)throw new Error("squeeze an axis of size different than 1");(b.length===0&&_[T]>1||b.length>0&&!w)&&y.push(_[T])}return y}static unsqueezeShape(_,b){const y=new Array(_.length+b.length);y.fill(0);for(let w=0;w=y.length)throw new Error("'axes' has an out of range axis");if(y[v]!==0)throw new Error("'axes' has a duplicate axis");y[v]=1}let T=0;for(let w=0;w=_.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+T>_.length)throw new Error("source indices to be copied are outside bounds");if(b+T>g.length)throw new Error("target array is too small to hold result");for(let w=0;w=_.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+T>_.length)throw new Error("source indices to be copied are outside bounds");if(b+T>g.length)throw new Error("target array is too small to hold result");for(let v=0;v=_.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+T>_.length)throw new Error("source indices to be copied are outside bounds");if(b+T>g.length)throw new Error("target array is too small to hold result");for(let v=0;v=_.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+T>_.length)throw new Error("source indices to be copied are outside bounds");if(b+T>g.length)throw new Error("target array is too small to hold result");for(let w=0;wb.push(D));const E=s.calcReduceShape(v,b,!0),P=e.size(E),x=new h.Tensor(E,_.type),O=e.computeStrides(E),$=e.computeStrides(v),k=new Array(v.length);for(let N=0;N=b.length)return v(_[w]);const x=b[T],O=x>=y.length?1:e.size(y.slice(x+1));for(let $=0;$w!==0)}}t.ReduceUtil=s;class f{static adjustPoolAttributes(_,b,y,T,w,v){if(!_&&y.length!==b.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(_)for(let E=0;E=y.length?y.push(b[E+2]):y[E]=b[E+2];for(let E=0;E=y[E]||v[E+y.length]>=y[E])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(_,b,y,T,w,v){if(v){if(w.length!==2*(_.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(b.length!==_.length-2)throw new Error("length of strides should be the length of data dimensions");if(T.length!==_.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let E=0;E<_.length-2;E++)f.adjustPadAndReturnShape(_[E+2],b[E],y[E],T[E],w,E,E+_.length-2,v)}}static computePoolOutputShape(_,b,y,T,w,v,E){if(b.length<=0)throw new Error("input shape must be of size greater than 0");const P=[b[0],b[1]];return f.computeShapeHelper(_,b,P,y,T,w,v,E),P}static computeConvOutputShape(_,b,y,T,w,v,E){if(_.length<=0||b.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");const P=[_[0],b[0]];return f.computeShapeHelper(!1,_,P,y,T,w,v,E),P}static computeShapeHelper(_,b,y,T,w,v,E,P){if(_)for(let x=0;x{Object.defineProperty(t,"__esModule",{value:!0}),t.iterateExtraOptions=void 0,t.iterateExtraOptions=(o,i,u,d)=>{if(typeof o=="object"&&o!==null){if(u.has(o))throw new Error("Circular reference in options");u.add(o)}Object.entries(o).forEach(([a,h])=>{const m=i?i+a:a;if(typeof h=="object")(0,t.iterateExtraOptions)(h,m+".",u,d);else if(typeof h=="string"||typeof h=="number")d(m,h.toString());else{if(typeof h!="boolean")throw new Error("Can't handle extra config type: "+typeof h);d(m,h?"1":"0")}})}},2157:function(p,t,o){var i,u=this&&this.__createBinding||(Object.create?function(O,$,k,N){N===void 0&&(N=k);var D=Object.getOwnPropertyDescriptor($,k);D&&!("get"in D?!$.__esModule:D.writable||D.configurable)||(D={enumerable:!0,get:function(){return $[k]}}),Object.defineProperty(O,N,D)}:function(O,$,k,N){N===void 0&&(N=k),O[N]=$[k]}),d=this&&this.__setModuleDefault||(Object.create?function(O,$){Object.defineProperty(O,"default",{enumerable:!0,value:$})}:function(O,$){O.default=$}),a=this&&this.__importStar||function(O){if(O&&O.__esModule)return O;var $={};if(O!=null)for(var k in O)k!=="default"&&Object.prototype.hasOwnProperty.call(O,k)&&u($,O,k);return d($,O),$};Object.defineProperty(t,"__esModule",{value:!0}),t.endProfiling=t.run=t.releaseSession=t.createSession=t.createSessionFinalize=t.createSessionAllocate=t.initOrt=t.initWasm=void 0;const h=o(1670),m=a(o(349)),c=o(6361),l=()=>!!h.env.wasm.proxy&&typeof document<"u";let n,e,r,s=!1,f=!1,g=!1;const _=[],b=[],y=[],T=[],w=[],v=[],E=()=>{if(s||!f||g||!n)throw new Error("worker not ready")},P=O=>{switch(O.data.type){case"init-wasm":s=!1,O.data.err?(g=!0,e[1](O.data.err)):(f=!0,e[0]());break;case"init-ort":O.data.err?r[1](O.data.err):r[0]();break;case"create_allocate":O.data.err?_.shift()[1](O.data.err):_.shift()[0](O.data.out);break;case"create_finalize":O.data.err?b.shift()[1](O.data.err):b.shift()[0](O.data.out);break;case"create":O.data.err?y.shift()[1](O.data.err):y.shift()[0](O.data.out);break;case"release":O.data.err?T.shift()[1](O.data.err):T.shift()[0]();break;case"run":O.data.err?w.shift()[1](O.data.err):w.shift()[0](O.data.out);break;case"end-profiling":O.data.err?v.shift()[1](O.data.err):v.shift()[0]()}},x=typeof document<"u"?(i=document==null?void 0:document.currentScript)===null||i===void 0?void 0:i.src:void 0;t.initWasm=async()=>{if(l()){if(f)return;if(s)throw new Error("multiple calls to 'initWasm()' detected.");if(g)throw new Error("previous call to 'initWasm()' failed.");return s=!0,h.env.wasm.wasmPaths===void 0&&x&&x.indexOf("blob:")!==0&&(h.env.wasm.wasmPaths=x.substr(0,+x.lastIndexOf("/")+1)),new Promise((O,$)=>{n==null||n.terminate(),n=o(9710).Z(),n.onmessage=P,e=[O,$];const k={type:"init-wasm",in:h.env.wasm};n.postMessage(k)})}return(0,c.initializeWebAssembly)(h.env.wasm)},t.initOrt=async(O,$)=>{if(l())return E(),new Promise((k,N)=>{r=[k,N];const D={type:"init-ort",in:{numThreads:O,loggingLevel:$}};n.postMessage(D)});m.initOrt(O,$)},t.createSessionAllocate=async O=>l()?(E(),new Promise(($,k)=>{_.push([$,k]);const N={type:"create_allocate",in:{model:O}};n.postMessage(N,[O.buffer])})):m.createSessionAllocate(O),t.createSessionFinalize=async(O,$)=>l()?(E(),new Promise((k,N)=>{b.push([k,N]);const D={type:"create_finalize",in:{modeldata:O,options:$}};n.postMessage(D)})):m.createSessionFinalize(O,$),t.createSession=async(O,$)=>l()?(E(),new Promise((k,N)=>{y.push([k,N]);const D={type:"create",in:{model:O,options:$}};n.postMessage(D,[O.buffer])})):m.createSession(O,$),t.releaseSession=async O=>{if(l())return E(),new Promise(($,k)=>{T.push([$,k]);const N={type:"release",in:O};n.postMessage(N)});m.releaseSession(O)},t.run=async(O,$,k,N,D)=>l()?(E(),new Promise((V,C)=>{w.push([V,C]);const B={type:"run",in:{sessionId:O,inputIndices:$,inputs:k,outputIndices:N,options:D}};n.postMessage(B,m.extractTransferableBuffers(k))})):m.run(O,$,k,N,D),t.endProfiling=async O=>{if(l())return E(),new Promise(($,k)=>{v.push([$,k]);const N={type:"end-profiling",in:O};n.postMessage(N)});m.endProfiling(O)}},586:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setRunOptions=void 0;const i=o(7967),u=o(4983),d=o(6361);t.setRunOptions=a=>{const h=(0,d.getInstance)();let m=0;const c=[],l=a||{};try{if((a==null?void 0:a.logSeverityLevel)===void 0)l.logSeverityLevel=2;else if(typeof a.logSeverityLevel!="number"||!Number.isInteger(a.logSeverityLevel)||a.logSeverityLevel<0||a.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${a.logSeverityLevel}`);if((a==null?void 0:a.logVerbosityLevel)===void 0)l.logVerbosityLevel=0;else if(typeof a.logVerbosityLevel!="number"||!Number.isInteger(a.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${a.logVerbosityLevel}`);(a==null?void 0:a.terminate)===void 0&&(l.terminate=!1);let n=0;if((a==null?void 0:a.tag)!==void 0&&(n=(0,u.allocWasmString)(a.tag,c)),m=h._OrtCreateRunOptions(l.logSeverityLevel,l.logVerbosityLevel,!!l.terminate,n),m===0)throw new Error("Can't create run options");return(a==null?void 0:a.extra)!==void 0&&(0,i.iterateExtraOptions)(a.extra,"",new WeakSet,(e,r)=>{const s=(0,u.allocWasmString)(e,c),f=(0,u.allocWasmString)(r,c);if(h._OrtAddRunConfigEntry(m,s,f)!==0)throw new Error(`Can't set a run config entry: ${e} - ${r}`)}),[m,c]}catch(n){throw m!==0&&h._OrtReleaseRunOptions(m),c.forEach(h._free),n}}},2306:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OnnxruntimeWebAssemblySessionHandler=void 0;const i=o(2806),u=o(1670),d=o(2850),a=o(2157);let h;t.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(m){const c=await fetch(m),l=await c.arrayBuffer();return(0,a.createSessionAllocate)(new Uint8Array(l))}async loadModel(m,c){if(h||(await(0,a.initOrt)(u.env.wasm.numThreads,(l=>{switch(l){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: ${l}`)}})(u.env.logLevel)),h=!0),typeof m=="string")if(typeof fetch>"u"){const l=await(0,d.promisify)(i.readFile)(m);[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSession)(l,c)}else{const l=await this.createSessionAllocate(m);[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSessionFinalize)(l,c)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSession)(m,c)}async dispose(){return(0,a.releaseSession)(this.sessionId)}async run(m,c,l){const n=[],e=[];Object.entries(m).forEach(g=>{const _=g[0],b=g[1],y=this.inputNames.indexOf(_);if(y===-1)throw new Error(`invalid input '${_}'`);n.push(b),e.push(y)});const r=[];Object.entries(c).forEach(g=>{const _=g[0],b=this.outputNames.indexOf(_);if(b===-1)throw new Error(`invalid output '${_}'`);r.push(b)});const s=await(0,a.run)(this.sessionId,e,n.map(g=>[g.type,g.dims,g.data]),r,l),f={};for(let g=0;g{Object.defineProperty(t,"__esModule",{value:!0}),t.setSessionOptions=void 0;const i=o(7967),u=o(4983),d=o(6361);t.setSessionOptions=a=>{const h=(0,d.getInstance)();let m=0;const c=[],l=a||{};(n=>{n.extra||(n.extra={}),n.extra.session||(n.extra.session={});const e=n.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(l);try{(a==null?void 0:a.graphOptimizationLevel)===void 0&&(l.graphOptimizationLevel="all");const n=(s=>{switch(s){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${s}`)}})(l.graphOptimizationLevel);(a==null?void 0:a.enableCpuMemArena)===void 0&&(l.enableCpuMemArena=!0),(a==null?void 0:a.enableMemPattern)===void 0&&(l.enableMemPattern=!0),(a==null?void 0:a.executionMode)===void 0&&(l.executionMode="sequential");const e=(s=>{switch(s){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${s}`)}})(l.executionMode);let r=0;if((a==null?void 0:a.logId)!==void 0&&(r=(0,u.allocWasmString)(a.logId,c)),(a==null?void 0:a.logSeverityLevel)===void 0)l.logSeverityLevel=2;else if(typeof a.logSeverityLevel!="number"||!Number.isInteger(a.logSeverityLevel)||a.logSeverityLevel<0||a.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${a.logSeverityLevel}`);if((a==null?void 0:a.logVerbosityLevel)===void 0)l.logVerbosityLevel=0;else if(typeof a.logVerbosityLevel!="number"||!Number.isInteger(a.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${a.logVerbosityLevel}`);if((a==null?void 0:a.enableProfiling)===void 0&&(l.enableProfiling=!1),m=h._OrtCreateSessionOptions(n,!!l.enableCpuMemArena,!!l.enableMemPattern,e,!!l.enableProfiling,0,r,l.logSeverityLevel,l.logVerbosityLevel),m===0)throw new Error("Can't create session options");return a!=null&&a.executionProviders&&((s,f,g)=>{for(const _ of f){let b=typeof _=="string"?_:_.name;switch(b){case"xnnpack":b="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${b}`)}const y=(0,u.allocWasmString)(b,g);if((0,d.getInstance)()._OrtAppendExecutionProvider(s,y)!==0)throw new Error(`Can't append execution provider: ${b}`)}})(m,a.executionProviders,c),(a==null?void 0:a.extra)!==void 0&&(0,i.iterateExtraOptions)(a.extra,"",new WeakSet,(s,f)=>{const g=(0,u.allocWasmString)(s,c),_=(0,u.allocWasmString)(f,c);if(h._OrtAddSessionConfigEntry(m,g,_)!==0)throw new Error(`Can't set a session config entry: ${s} - ${f}`)}),[m,c]}catch(n){throw m!==0&&h._OrtReleaseSessionOptions(m),c.forEach(h._free),n}}},4983:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.allocWasmString=void 0;const i=o(6361);t.allocWasmString=(u,d)=>{const a=(0,i.getInstance)(),h=a.lengthBytesUTF8(u)+1,m=a._malloc(h);return a.stringToUTF8(u,m,h),d.push(m),m}},349:(p,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractTransferableBuffers=t.endProfiling=t.run=t.releaseSession=t.createSession=t.createSessionFinalize=t.createSessionAllocate=t.initOrt=void 0;const i=o(586),u=o(4919),d=o(4983),a=o(6361);t.initOrt=(n,e)=>{const r=(0,a.getInstance)()._OrtInit(n,e);if(r!==0)throw new Error(`Can't initialize onnxruntime. error code = ${r}`)};const h=new Map;t.createSessionAllocate=n=>{const e=(0,a.getInstance)(),r=e._malloc(n.byteLength);return e.HEAPU8.set(n,r),[r,n.byteLength]},t.createSessionFinalize=(n,e)=>{const r=(0,a.getInstance)();let s=0,f=0,g=[];try{if([f,g]=(0,u.setSessionOptions)(e),s=r._OrtCreateSession(n[0],n[1],f),s===0)throw new Error("Can't create a session")}finally{r._free(n[0]),r._OrtReleaseSessionOptions(f),g.forEach(r._free)}const _=r._OrtGetInputCount(s),b=r._OrtGetOutputCount(s),y=[],T=[],w=[],v=[];for(let E=0;E<_;E++){const P=r._OrtGetInputName(s,E);if(P===0)throw new Error("Can't get an input name");T.push(P),y.push(r.UTF8ToString(P))}for(let E=0;E{const r=(0,t.createSessionAllocate)(n);return(0,t.createSessionFinalize)(r,e)},t.releaseSession=n=>{const e=(0,a.getInstance)(),r=h.get(n);if(!r)throw new Error("invalid session id");const s=r[0],f=r[1],g=r[2];f.forEach(e._OrtFree),g.forEach(e._OrtFree),e._OrtReleaseSession(s),h.delete(n)};const m=n=>{switch(n){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${n}`)}},c=n=>{switch(n){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${n}`)}},l=n=>{switch(n){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${n}`)}};t.run=(n,e,r,s,f)=>{const g=(0,a.getInstance)(),_=h.get(n);if(!_)throw new Error("invalid session id");const b=_[0],y=_[1],T=_[2],w=e.length,v=s.length;let E=0,P=[];const x=[],O=[];try{[E,P]=(0,i.setRunOptions)(f);for(let C=0;Cg.HEAP32[xe++]=we);const le=g._OrtCreateTensor(m(B),ee,J,Ee,X.length);if(le===0)throw new Error("Can't create a tensor");x.push(le)}finally{g.stackRestore(ae)}}const $=g.stackSave(),k=g.stackAlloc(4*w),N=g.stackAlloc(4*w),D=g.stackAlloc(4*v),V=g.stackAlloc(4*v);try{let C=k/4,B=N/4,X=D/4,G=V/4;for(let ae=0;aePe*je);if(we=c(Le),we==="string"){const Pe=[];let je=be/4;for(let Ue=0;Ue{const e=(0,a.getInstance)(),r=h.get(n);if(!r)throw new Error("invalid session id");const s=r[0],f=e._OrtEndProfiling(s);if(f===0)throw new Error("Can't get an profile file name");e._OrtFree(f)},t.extractTransferableBuffers=n=>{const e=[];for(const r of n){const s=r[2];!Array.isArray(s)&&s.buffer&&e.push(s.buffer)}return e}},6361:function(p,t,o){var i=this&&this.__createBinding||(Object.create?function(f,g,_,b){b===void 0&&(b=_);var y=Object.getOwnPropertyDescriptor(g,_);y&&!("get"in y?!g.__esModule:y.writable||y.configurable)||(y={enumerable:!0,get:function(){return g[_]}}),Object.defineProperty(f,b,y)}:function(f,g,_,b){b===void 0&&(b=_),f[b]=g[_]}),u=this&&this.__setModuleDefault||(Object.create?function(f,g){Object.defineProperty(f,"default",{enumerable:!0,value:g})}:function(f,g){f.default=g}),d=this&&this.__importStar||function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var _ in f)_!=="default"&&Object.prototype.hasOwnProperty.call(f,_)&&i(g,f,_);return u(g,f),g},a=this&&this.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.dispose=t.getInstance=t.initializeWebAssembly=void 0;const h=d(o(6449)),m=a(o(932)),c=o(3474);let l,n=!1,e=!1,r=!1;const s=(f,g)=>g?f?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":f?"ort-wasm-simd.wasm":"ort-wasm.wasm";t.initializeWebAssembly=async f=>{if(n)return Promise.resolve();if(e)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(r)throw new Error("previous call to 'initializeWebAssembly()' failed.");e=!0;const g=f.initTimeout,_=f.numThreads,b=f.simd,y=_>1&&(()=>{try{return typeof SharedArrayBuffer<"u"&&(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}})(),T=b&&(()=>{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}})(),w=typeof f.wasmPaths=="string"?f.wasmPaths:void 0,v=s(!1,y),E=s(T,y),P=typeof f.wasmPaths=="object"?f.wasmPaths[E]:void 0;let x=!1;const O=[];if(g>0&&O.push(new Promise($=>{setTimeout(()=>{x=!0,$()},g)})),O.push(new Promise(($,k)=>{const N=y?c:m.default,D={locateFile:(V,C)=>y&&V.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([o(4154)],{type:"text/javascript"})):V===v?P??(w??C)+E:C+V};if(y)if(typeof Blob>"u")D.mainScriptUrlOrBlob=h.join("/","ort-wasm-threaded.js");else{const V=`var ortWasmThreaded=(function(){var _scriptDir;return ${N.toString()}})();`;D.mainScriptUrlOrBlob=new Blob([V],{type:"text/javascript"})}N(D).then(V=>{e=!1,n=!0,l=V,$()},V=>{e=!1,r=!0,k(V)})})),await Promise.race(O),x)throw new Error(`WebAssembly backend initializing failed due to timeout: ${g}ms`)},t.getInstance=()=>{if(n&&l)return l;throw new Error("WebAssembly is not initialized yet.")},t.dispose=()=>{var f;!n||e||r||(e=!0,(f=l.PThread)===null||f===void 0||f.terminateAllThreads(),l=void 0,e=!1,n=!1,r=!0)}},9710:(p,t,o)=>{o.d(t,{Z:()=>d});var i=o(477),u=o.n(i);function d(){return u()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&>(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;azt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(_||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;tp.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;tt*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),o=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n',"Worker",void 0,void 0)}},477:p=>{p.exports=function(t,o,i,u){var d=self||window;try{try{var a;try{a=new d.Blob([t])}catch{(a=new(d.BlobBuilder||d.WebKitBlobBuilder||d.MozBlobBuilder||d.MSBlobBuilder)).append(t),a=a.getBlob()}var h=d.URL||d.webkitURL,m=h.createObjectURL(a),c=new d[o](m,i);return h.revokeObjectURL(m),c}catch{return new d[o]("data:application/javascript,".concat(encodeURIComponent(t)),i)}}catch{if(!u)throw Error("Inline worker is not supported");return new d[o](u,i)}}},4154:p=>{p.exports=`"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}}; `},1670:p=>{p.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(p,t,o)=>{o.r(t),o.d(t,{flatbuffers:()=>i});var i={};i.Offset,i.Table,i.SIZEOF_SHORT=2,i.SIZEOF_INT=4,i.FILE_IDENTIFIER_LENGTH=4,i.SIZE_PREFIX_LENGTH=4,i.Encoding={UTF8_BYTES:1,UTF16_STRING:2},i.int32=new Int32Array(2),i.float32=new Float32Array(i.int32.buffer),i.float64=new Float64Array(i.int32.buffer),i.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,i.Long=function(u,d){this.low=0|u,this.high=0|d},i.Long.create=function(u,d){return u==0&&d==0?i.Long.ZERO:new i.Long(u,d)},i.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},i.Long.prototype.equals=function(u){return this.low==u.low&&this.high==u.high},i.Long.ZERO=new i.Long(0,0),i.Builder=function(u){if(u)d=u;else var d=1024;this.bb=i.ByteBuffer.allocate(d),this.space=d,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},i.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},i.Builder.prototype.forceDefaults=function(u){this.force_defaults=u},i.Builder.prototype.dataBuffer=function(){return this.bb},i.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},i.Builder.prototype.prep=function(u,d){u>this.minalign&&(this.minalign=u);for(var a=1+~(this.bb.capacity()-this.space+d)&u-1;this.space=0&&this.vtable[d]==0;d--);for(var a=d+1;d>=0;d--)this.addInt16(this.vtable[d]!=0?u-this.vtable[d]:0);this.addInt16(u-this.object_start);var h=(a+2)*i.SIZEOF_SHORT;this.addInt16(h);var m=0,c=this.space;e:for(d=0;d=0;c--)this.writeInt8(m.charCodeAt(c))}this.prep(this.minalign,i.SIZEOF_INT+h),this.addOffset(u),h&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},i.Builder.prototype.finishSizePrefixed=function(u,d){this.finish(u,d,!0)},i.Builder.prototype.requiredField=function(u,d){var a=this.bb.capacity()-u,h=a-this.bb.readInt32(a);if(this.bb.readInt16(h+d)==0)throw new Error("FlatBuffers: field "+d+" must be set")},i.Builder.prototype.startVector=function(u,d,a){this.notNested(),this.vector_num_elems=d,this.prep(i.SIZEOF_INT,u*d),this.prep(a,u*d)},i.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},i.Builder.prototype.createString=function(u){if(u instanceof Uint8Array)var d=u;else{d=[];for(var a=0;a=56320?m:(m<<10)+u.charCodeAt(a++)+-56613888)<128?d.push(h):(h<2048?d.push(h>>6&31|192):(h<65536?d.push(h>>12&15|224):d.push(h>>18&7|240,h>>12&63|128),d.push(h>>6&63|128)),d.push(63&h|128))}}this.addInt8(0),this.startVector(1,d.length,1),this.bb.setPosition(this.space-=d.length),a=0;for(var c=this.space,l=this.bb.bytes();a>24},i.ByteBuffer.prototype.readUint8=function(u){return this.bytes_[u]},i.ByteBuffer.prototype.readInt16=function(u){return this.readUint16(u)<<16>>16},i.ByteBuffer.prototype.readUint16=function(u){return this.bytes_[u]|this.bytes_[u+1]<<8},i.ByteBuffer.prototype.readInt32=function(u){return this.bytes_[u]|this.bytes_[u+1]<<8|this.bytes_[u+2]<<16|this.bytes_[u+3]<<24},i.ByteBuffer.prototype.readUint32=function(u){return this.readInt32(u)>>>0},i.ByteBuffer.prototype.readInt64=function(u){return new i.Long(this.readInt32(u),this.readInt32(u+4))},i.ByteBuffer.prototype.readUint64=function(u){return new i.Long(this.readUint32(u),this.readUint32(u+4))},i.ByteBuffer.prototype.readFloat32=function(u){return i.int32[0]=this.readInt32(u),i.float32[0]},i.ByteBuffer.prototype.readFloat64=function(u){return i.int32[i.isLittleEndian?0:1]=this.readInt32(u),i.int32[i.isLittleEndian?1:0]=this.readInt32(u+4),i.float64[0]},i.ByteBuffer.prototype.writeInt8=function(u,d){this.bytes_[u]=d},i.ByteBuffer.prototype.writeUint8=function(u,d){this.bytes_[u]=d},i.ByteBuffer.prototype.writeInt16=function(u,d){this.bytes_[u]=d,this.bytes_[u+1]=d>>8},i.ByteBuffer.prototype.writeUint16=function(u,d){this.bytes_[u]=d,this.bytes_[u+1]=d>>8},i.ByteBuffer.prototype.writeInt32=function(u,d){this.bytes_[u]=d,this.bytes_[u+1]=d>>8,this.bytes_[u+2]=d>>16,this.bytes_[u+3]=d>>24},i.ByteBuffer.prototype.writeUint32=function(u,d){this.bytes_[u]=d,this.bytes_[u+1]=d>>8,this.bytes_[u+2]=d>>16,this.bytes_[u+3]=d>>24},i.ByteBuffer.prototype.writeInt64=function(u,d){this.writeInt32(u,d.low),this.writeInt32(u+4,d.high)},i.ByteBuffer.prototype.writeUint64=function(u,d){this.writeUint32(u,d.low),this.writeUint32(u+4,d.high)},i.ByteBuffer.prototype.writeFloat32=function(u,d){i.float32[0]=d,this.writeInt32(u,i.int32[0])},i.ByteBuffer.prototype.writeFloat64=function(u,d){i.float64[0]=d,this.writeInt32(u,i.int32[i.isLittleEndian?0:1]),this.writeInt32(u+4,i.int32[i.isLittleEndian?1:0])},i.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10),56320+(1023&c)))}return h},i.ByteBuffer.prototype.__indirect=function(u){return u+this.readInt32(u)},i.ByteBuffer.prototype.__vector=function(u){return u+this.readInt32(u)+i.SIZEOF_INT},i.ByteBuffer.prototype.__vector_len=function(u){return this.readInt32(u+this.readInt32(u))},i.ByteBuffer.prototype.__has_identifier=function(u){if(u.length!=i.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+i.FILE_IDENTIFIER_LENGTH);for(var d=0;d{var t=p&&p.__esModule?()=>p.default:()=>p;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(p,t)=>{for(var o in t)__webpack_require__.o(t,o)&&!__webpack_require__.o(p,o)&&Object.defineProperty(p,o,{enumerable:!0,get:t[o]})},__webpack_require__.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}}(),__webpack_require__.o=(p,t)=>Object.prototype.hasOwnProperty.call(p,t),__webpack_require__.r=p=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(p,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(p,"__esModule",{value:!0})};var __webpack_exports__=__webpack_require__(6018);return __webpack_exports__})())})(ortWeb_min$1);var ortWeb_minExports=ortWeb_min$1.exports,ortWeb_min=getDefaultExportFromCjs(ortWeb_minExports),ONNX_WEB=_mergeNamespaces({__proto__:null,default:ortWeb_min},[ortWeb_minExports]);let ONNX;const executionProviders=["wasm"];typeof process<"u"&&((nt=process==null?void 0:process.release)==null?void 0:nt.name)==="node"?(ONNX=sharp??ONNX_NODE,executionProviders.unshift("cpu")):(ONNX=ortWeb_min??ONNX_WEB,typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(ONNX.env.wasm.simd=!1));const{env:onnx_env}=ONNX,VERSION="2.15.0",WEB_CACHE_AVAILABLE=typeof self<"u"&&"caches"in self,FS_AVAILABLE=!isEmpty(sharp),PATH_AVAILABLE=!isEmpty(sharp),RUNNING_LOCALLY=FS_AVAILABLE&&PATH_AVAILABLE,__dirname=RUNNING_LOCALLY?sharp.dirname(sharp.dirname(sharp.fileURLToPath(self.location.href))):"./",DEFAULT_CACHE_DIR=RUNNING_LOCALLY?sharp.join(__dirname,"/.cache/"):null,DEFAULT_LOCAL_MODEL_PATH="/models/",localModelPath=RUNNING_LOCALLY?sharp.join(__dirname,DEFAULT_LOCAL_MODEL_PATH):DEFAULT_LOCAL_MODEL_PATH;onnx_env.wasm.wasmPaths=RUNNING_LOCALLY?sharp.join(__dirname,"/dist/"):`https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;const env$1={backends:{onnx:onnx_env,tfjs:{}},__dirname,version:VERSION,allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!0,localModelPath,useFS:FS_AVAILABLE,useBrowserCache:WEB_CACHE_AVAILABLE,useFSCache:FS_AVAILABLE,cacheDir:DEFAULT_CACHE_DIR,useCustomCache:!1,customCache:null};function isEmpty(p){return Object.keys(p).length===0}var define_process_env_default={};globalThis.ReadableStream||(globalThis.ReadableStream=sharp.ReadableStream);class FileResponse{constructor(t){K(this,"_CONTENT_TYPE_MAP",{txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"});if(this.filePath=t,this.headers=new Headers,this.exists=sharp.existsSync(t),this.exists){this.status=200,this.statusText="OK";let o=sharp.statSync(t);this.headers.set("content-length",o.size.toString()),this.updateContentType();let i=this;this.body=new ReadableStream({start(u){i.arrayBuffer().then(d=>{u.enqueue(new Uint8Array(d)),u.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[t]??"application/octet-stream")}clone(){let t=new FileResponse(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await sharp.promises.readFile(this.filePath)).buffer}async blob(){const t=await sharp.promises.readFile(this.filePath);return new Blob([t],{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(p,t=null){let o;try{o=new URL(p)}catch{return!1}return t&&!t.includes(o.hostname)?!1:o.protocol==="http:"||o.protocol==="https:"}async function getFile(p){var t;if(env$1.useFS&&!isValidHttpUrl(p))return new FileResponse(p);if(typeof process<"u"&&((t=process==null?void 0:process.release)==null?void 0:t.name)==="node"){const o=!!(define_process_env_default!=null&&define_process_env_default.TESTING_REMOTELY),i=env$1.version,u=new Headers;if(u.set("User-Agent",`transformers.js/${i}; is_ci/${o};`),isValidHttpUrl(p,["huggingface.co","hf.co"])){const a=(define_process_env_default==null?void 0:define_process_env_default.HF_TOKEN)??(define_process_env_default==null?void 0:define_process_env_default.HF_ACCESS_TOKEN);a&&u.set("Authorization",`Bearer ${a}`)}return fetch(p,{headers:u})}else return fetch(p)}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(p,t,o){if(!o)return null;const i=ERROR_MAPPING[p]??`Error (${p}) occurred while trying to load file`;throw Error(`${i}: "${t}".`)}class FileCache{constructor(t){this.path=t}async match(t){let o=sharp.join(this.path,t),i=new FileResponse(o);if(i.exists)return i}async put(t,o){const i=Buffer.from(await o.arrayBuffer());let u=sharp.join(this.path,t);try{await sharp.promises.mkdir(sharp.dirname(u),{recursive:!0}),await sharp.promises.writeFile(u,i)}catch(d){console.warn("An error occurred while writing the file to cache:",d)}}}async function tryCache(p,...t){for(let o of t)try{let i=await p.match(o);if(i)return i}catch{continue}}async function getModelFile(p,t,o=!0,i={}){if(!env$1.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:p,file:t});let u;if(!u&&env$1.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{u=await caches.open("transformers-cache")}catch(_){console.warn("An error occurred while opening the browser cache:",_)}}if(!u&&env$1.useFSCache&&(u=new FileCache(i.cache_dir??env$1.cacheDir)),!u&&env$1.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const d=i.revision??"main";let a=pathJoin(p,t),h=pathJoin(env$1.localModelPath,a),m=pathJoin(env$1.remoteHost,env$1.remotePathTemplate.replaceAll("{model}",p).replaceAll("{revision}",encodeURIComponent(d)),t),c=d==="main"?a:pathJoin(p,d,t),l,n=u instanceof FileCache?c:m,e=!1,r;u&&(r=await tryCache(u,h,n));const s=r!==void 0;if(r===void 0){if(env$1.allowLocalModels)if(isValidHttpUrl(a)){if(i.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`)}else try{r=await getFile(h),l=h}catch(b){console.warn(`Unable to load from local path "${h}": "${b}"`)}if(r===void 0||r.status===404){if(i.local_files_only||!env$1.allowRemoteModels){if(o)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${h}".`);return null}if(r=await getFile(m),r.status!==200)return handleError(r.status,m,o);l=n}e=u&&typeof Response<"u"&&r instanceof Response&&r.status===200}dispatchCallback(i.progress_callback,{status:"download",name:p,file:t});const f={status:"progress",name:p,file:t};let g;return i.progress_callback?s&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(g=new Uint8Array(await r.arrayBuffer()),dispatchCallback(i.progress_callback,{...f,progress:100,loaded:g.length,total:g.length})):g=await readResponse(r,_=>{dispatchCallback(i.progress_callback,{...f,..._})}):g=new Uint8Array(await r.arrayBuffer()),e&&l&&await u.match(l)===void 0&&await u.put(l,new Response(g,{headers:r.headers})).catch(_=>{console.warn(`Unable to add response to browser cache: ${_}.`)}),dispatchCallback(i.progress_callback,{status:"done",name:p,file:t}),g}async function getModelJSON(p,t,o=!0,i={}){let u=await getModelFile(p,t,o,i);if(u===null)return{};let a=new TextDecoder("utf-8").decode(u);return JSON.parse(a)}async function readResponse(p,t){const o=p.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),d=0;const a=p.body.getReader();async function h(){const{done:m,value:c}=await a.read();if(m)return;let l=d+c.length;if(l>i){i=l;let e=new Uint8Array(i);e.set(u),u=e}u.set(c,d),d=l;const n=d/i*100;return t({progress:n,loaded:d,total:i}),h()}return await h(),u}function pathJoin(...p){return p=p.map((t,o)=>(o&&(t=t.replace(new RegExp("^/"),"")),o!==p.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),p.join("/")}function interpolate_data(p,[t,o,i],[u,d],a="bilinear",h=!1){const m=d/i,c=u/o,l=new p.constructor(u*d*t),n=o*i,e=u*d;for(let r=0;r=0;--h)u[h]=m,i[h]=t[o[h]],m*=i[h];const d=o.map((h,m)=>u[o.indexOf(m)]),a=new p.constructor(p.length);for(let h=0;h=0;--c)m+=l%t[c]*d[c],l=Math.floor(l/t[c]);a[m]=p[h]}return[a,i]}function softmax(p){const t=max(p)[0],o=p.map(d=>Math.exp(d-t)),i=o.reduce((d,a)=>d+a,0);return o.map(d=>d/i)}function log_softmax(p){return softmax(p).map(i=>Math.log(i))}function getTopItems(p,t=0){return p=Array.from(p).map((o,i)=>[i,o]).sort((o,i)=>i[1]-o[1]),t!==null&&t>0&&(p=p.slice(0,t)),p}function min(p){if(p.length===0)throw Error("Array must not be empty");let t=p[0],o=0;for(let i=1;it&&(t=p[i],o=i);return[Number(t),o]}function isPowerOfTwo(p){return p>0&&(p&p-1)===0}class P2FFT{constructor(t){if(this.size=t|0,this.size<=1||!isPowerOfTwo(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=t<<1,this.table=new Float64Array(this.size*2);for(let i=0;ii;i<<=1)++o;this._width=o%2===0?o-1:o,this._bitrev=new Int32Array(1<>>u&3)<>>1);for(let u=0;u>>1]=t[u];return i}toComplexArray(t,o){const i=o||this.createComplexArray();for(let u=0;u>>1],i[u+1]=0;return i}completeSpectrum(t){const o=this._csize,i=o>>>1;for(let u=2;u>=2;a>=2;a>>=2){h=u/a<<1;const n=h>>>2;for(m=0;m>>1,a>>>1)}else for(m=0,c=0;m>>1,a>>>1,i)}for(a>>=2;a>=2;a>>=2){h=u/a<<1;const n=h>>>2;for(m=0;m>1;++l){const n=(l+1-t)**2/2,e=Math.sqrt(m**2+c**2)**n,r=n*Math.atan2(c,m),s=2*l;d[s]=e*Math.cos(r),d[s+1]=e*Math.sin(r),a[s]=d[s],a[s+1]=-d[s+1]}this._slicedChirpBuffer=d.subarray(o,i),this._f=new P2FFT(u>>1),this._f.transform(this._chirpBuffer,a)}_transform(t,o,i){const u=this._buffer1,d=this._buffer2,a=this._outBuffer1,h=this._outBuffer2,m=this._chirpBuffer,c=this._slicedChirpBuffer,l=this._a;if(i)for(let n=0;n>1,s=o[r];u[n]=s*c[n],u[e]=s*c[e]}else for(let n=0;n=p.length&&(m=2*(p.length-1)-m),i[a++]=p[m]}i.sort(),o[d]=i[u]}return o}function round(p,t){const o=Math.pow(10,t);return Math.round(p*o)/o}const DataTypeMap=Object.freeze({float32:Float32Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array}),ONNXTensor$1=ONNX.Tensor;class Tensor{constructor(...t){K(this,"dims");K(this,"type");K(this,"data");K(this,"size");return t[0]instanceof ONNXTensor$1?Object.assign(this,t[0]):Object.assign(this,new ONNXTensor$1(t[0],t[1],t[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})}*[Symbol.iterator](){const[t,...o]=this.dims;if(o.length>0){const i=o.reduce((u,d)=>u*d);for(let u=0;u0){const u=i.reduce((d,a)=>d*a);return this._subarray(t,u,i)}else return new Tensor(this.type,[this.data[t]],i)}indexOf(t){for(let o=0;oc[1])throw new Error(`Invalid slice: ${c}`);let l=[Math.max(c[0],0),Math.min(c[1],this.dims[m])];i.push(l),o.push(l[1]-l[0])}else throw new Error(`Invalid slice: ${c}`)}let u=i.map(([m,c])=>c-m),d=u.reduce((m,c)=>m*c),a=new this.data.constructor(d);const h=this.stride();for(let m=0;m=0;--l){const e=u[l];c+=(n%e+i[l][0])*h[l],n=Math.floor(n/e)}a[m]=this.data[c]}return new Tensor(this.type,a,o)}transpose(...t){return transpose(this,t)}sum(t=null,o=!1){return this.norm(1,t,o)}norm(t="fro",o=null,i=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);if(o===null){let a=this.data.reduce((h,m)=>h+m**t,0)**(1/t);return new Tensor(this.type,[a],[])}o=safeIndex(o,this.dims.length);const u=this.dims.slice();u[o]=1;const d=new this.data.constructor(this.data.length/this.dims[o]);for(let a=0;a=0;--m){const n=this.dims[m];if(m!==o){const e=c%n;h+=e*l,l*=u[m]}c=Math.floor(c/n)}d[h]+=this.data[a]**t}if(t!==1)for(let a=0;a=0;--a){const c=this.dims[a];if(a!==o){const l=h%c;d+=l*m,m*=this.dims[a]}h=Math.floor(h/c)}this.data[u]/=i.data[d]}return this}normalize(t=2,o=1){return this.clone().normalize_(t,o)}stride(){return dimsToStride(this.dims)}squeeze(t=null){return new Tensor(this.type,this.data,calc_squeeze_dims(this.dims,t))}squeeze_(t=null){return this.dims=calc_squeeze_dims(this.dims,t),this}unsqueeze(t=null){return new Tensor(this.type,this.data,calc_unsqueeze_dims(this.dims,t))}unsqueeze_(t=null){return this.dims=calc_unsqueeze_dims(this.dims,t),this}flatten_(t=0,o=-1){o=(o+this.dims.length)%this.dims.length;let i=this.dims.slice(0,t),u=this.dims.slice(t,o+1),d=this.dims.slice(o+1);return this.dims=[...i,u.reduce((a,h)=>a*h,1),...d],this}flatten(t=0,o=-1){return this.clone().flatten_(t,o)}view(...t){let o=-1;for(let i=0;ia!==o?u*d:u,1);t[o]=this.data.length/i}return new Tensor(this.type,this.data,t)}neg_(){for(let t=0;td*a);if(o!==i)throw Error(`cannot reshape array of size ${o} into shape (${t})`);let u=p;for(let d=t.length-1;d>=0;d--)u=u.reduce((a,h)=>{let m=a[a.length-1];return m.lengtho!==1):typeof t=="number"?p[t]===1&&p.splice(t,1):Array.isArray(t)&&(p=p.filter((o,i)=>o!==1||!t.includes(i))),p}function calc_unsqueeze_dims(p,t){return t=safeIndex(t,p.length+1),p=p.slice(),p.splice(t,0,1),p}function safeIndex(p,t,o=null){if(p<-t||p>=t)throw new Error(`IndexError: index ${p} is out of bounds for dimension${o===null?"":" "+o} with size ${t}`);return p<0&&(p=(p%t+t)%t),p}function cat(p,t=0){t=safeIndex(t,p[0].dims.length);const o=p[0].dims.slice();o[t]=p.reduce((a,h)=>a+h.dims[t],0);const i=o.reduce((a,h)=>a*h,1),u=new p[0].data.constructor(i),d=p[0].type;if(t===0){let a=0;for(let h of p)u.set(h.data,a),a+=h.data.length}else{let a=0;for(let h=0;h=0;--n){const s=m.dims[n];let f=e%s;n===t&&(f+=a),l+=f*r,r*=o[n],e=Math.floor(e/s)}u[l]=m.data[c]}a+=m.dims[t]}}return new Tensor(d,u,o)}function stack(p,t=0){return cat(p.map(o=>o.unsqueeze(t)),t)}function std_mean(p,t=null,o=1,i=!1){if(t===null){const c=p.data.reduce((r,s)=>r+s,0)/p.data.length,l=Math.sqrt(p.data.reduce((r,s)=>r+(s-c)**2,0)/(p.data.length-o)),n=new Tensor(p.type,[c],[]);return[new Tensor(p.type,[l],[]),n]}t=safeIndex(t,p.dims.length);const u=mean(p,t,i),d=p.dims.slice();d[t]=1;const a=new p.data.constructor(p.data.length/p.dims[t]);for(let m=0;m=0;--l){const r=p.dims[l];if(l!==t){const s=n%r;c+=s*e,e*=d[l]}n=Math.floor(n/r)}a[c]+=(p.data[m]-u.data[c])**2}for(let m=0;ma+h,0);return new Tensor(p.type,[d/p.data.length],[])}t=safeIndex(t,p.dims.length);const i=p.dims.slice();i[t]=1;const u=new p.data.constructor(p.data.length/p.dims[t]);for(let d=0;d=0;--h){const l=p.dims[h];if(h!==t){const n=m%l;a+=n*c,c*=i[h]}m=Math.floor(m/l)}u[a]+=p.data[d]}if(p.dims[t]!==1)for(let d=0;d0||h>0;)switch(m.push(a-1),c.push(h-1),d[a][h].item()){case 0:--a,--h;break;case 1:--a;break;case 2:--h;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${h}]. Please file a bug report.`)}return m.reverse(),c.reverse(),[m,c]}function dimsToStride(p){const t=new Array(p.length);for(let o=p.length-1,i=1;o>=0;--o)t[o]=i,i*=p[o];return t}function ones(p){const t=p.reduce((o,i)=>o*i,1);return new Tensor("int64",new BigInt64Array(t).fill(1n),p)}function ones_like(p){return ones(p.dims)}class PriorityQueue{constructor(t=(o,i)=>o>i){this._heap=[],this._comparator=t}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(const o of t)this._heap.push(o),this._siftUp();return this.size}pop(){const t=this.peek(),o=this.size-1;return o>0&&this._swap(0,o),this._heap.pop(),this._siftDown(),t}replace(t){const o=this.peek();return this._heap[0]=t,this._siftDown(),o}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,o){return this._comparator(this._heap[t],this._heap[o])}_swap(t,o){const i=this._heap[t];this._heap[t]=this._heap[o],this._heap[o]=i}_siftUp(){let t=this.size-1;for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_siftDown(){let t=0;for(;this._left(t)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const u=new TokenLatticeNode(this.bosTokenId,0,0,0,0),d=new TokenLatticeNode(this.eosTokenId,1,this.len,0,0);this.nodes.push(u.clone()),this.nodes.push(d.clone()),this.beginNodes[this.len].push(d),this.endNodes[0].push(u)}insert(t,o,i,u){const d=this.nodes.length,a=new TokenLatticeNode(u,d,t,o,i);this.beginNodes[t].push(a),this.endNodes[t+o].push(a),this.nodes.push(a)}viterbi(){const t=this.len;let o=0;for(;o<=t;){if(this.beginNodes[o].length==0)return[];for(let h of this.beginNodes[o]){h.prev=null;let m=0,c=null;for(let l of this.endNodes[o]){const n=l.backtraceScore+h.score;(c===null||n>m)&&(c=l.clone(),m=n)}if(c!==null)h.prev=c,h.backtraceScore=m;else return[]}++o}const i=[],d=this.beginNodes[t][0].prev;if(d===null)return[];let a=d.clone();for(;a.prev!==null;)i.push(a.clone()),a=a.clone().prev.clone();return i.reverse(),i}piece(t){return this.sentence.slice(t.pos,t.pos+t.length)}tokens(){return this.viterbi().map(o=>this.piece(o))}tokenIds(){return this.viterbi().map(o=>o.tokenId)}}class TokenLatticeNode{constructor(t,o,i,u,d){this.tokenId=t,this.nodeId=o,this.pos=i,this.length=u,this.score=d,this.prev=null,this.backtraceScore=0}clone(){const t=new TokenLatticeNode(this.tokenId,this.nodeId,this.pos,this.length,this.score);return t.prev=this.prev,t.backtraceScore=this.backtraceScore,t}}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",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",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),KEYWORDS=Object.freeze({set:TOKEN_TYPES.Set,for:TOKEN_TYPES.For,in:TOKEN_TYPES.In,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=class{constructor(p,t){this.value=p,this.type=t}};function isWord(p){return/\w/.test(p)}function isInteger(p){return/[0-9]/.test(p)}var ORDERED_MAPPING_TABLE=[["{%",TOKEN_TYPES.OpenStatement],["%}",TOKEN_TYPES.CloseStatement],["{{",TOKEN_TYPES.OpenExpression],["}}",TOKEN_TYPES.CloseExpression],["(",TOKEN_TYPES.OpenParen],[")",TOKEN_TYPES.CloseParen],["[",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]],ESCAPE_CHARACTERS=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function tokenize(p){var d,a,h;const t=[],o=p;let i=0;const u=m=>{let c="";for(;m(o[i]);){if(o[i]==="\\"){if(++i,i>=o.length)throw new SyntaxError("Unexpected end of input");const l=o[i++],n=ESCAPE_CHARACTERS.get(l);if(n===void 0)throw new SyntaxError(`Unexpected escaped character: ${l}`);c+=n;continue}if(c+=o[i++],i>=o.length)throw new SyntaxError("Unexpected end of input")}return c};e:for(;i0){t.push(new Token(l,TOKEN_TYPES.Text));continue}}u(l=>/\s/.test(l));const c=o[i];if(c==="-"||c==="+"){const l=(a=t.at(-1))==null?void 0:a.type;if(l===TOKEN_TYPES.Text||l===void 0)throw new SyntaxError(`Unexpected character: ${c}`);switch(l){case TOKEN_TYPES.Identifier:case TOKEN_TYPES.NumericLiteral:case TOKEN_TYPES.BooleanLiteral:case TOKEN_TYPES.StringLiteral:case TOKEN_TYPES.CloseParen:case TOKEN_TYPES.CloseSquareBracket:break;default:{++i;const n=u(isInteger);t.push(new Token(`${c}${n}`,n.length>0?TOKEN_TYPES.NumericLiteral:TOKEN_TYPES.UnaryOperator));continue}}}for(const[l,n]of ORDERED_MAPPING_TABLE)if(o.slice(i,i+l.length)===l){t.push(new Token(l,n)),i+=l.length;continue e}if(c==="'"){++i;const l=u(n=>n!=="'");t.push(new Token(l,TOKEN_TYPES.StringLiteral)),++i;continue}if(isInteger(c)){const l=u(isInteger);t.push(new Token(l,TOKEN_TYPES.NumericLiteral));continue}if(isWord(c)){const l=u(isWord),n=Object.hasOwn(KEYWORDS,l)?KEYWORDS[l]:TOKEN_TYPES.Identifier;n===TOKEN_TYPES.In&&((h=t.at(-1))==null?void 0:h.type)===TOKEN_TYPES.Not?(t.pop(),t.push(new Token("not in",TOKEN_TYPES.NotIn))):t.push(new Token(l,n));continue}throw new SyntaxError(`Unexpected character: ${c}`)}return t}var Statement=class{constructor(){K(this,"type","Statement")}},Program=class extends Statement{constructor(t){super();K(this,"type","Program");this.body=t}},If=class extends Statement{constructor(t,o,i){super();K(this,"type","If");this.test=t,this.body=o,this.alternate=i}},For=class extends Statement{constructor(t,o,i){super();K(this,"type","For");this.loopvar=t,this.iterable=o,this.body=i}},SetStatement=class extends Statement{constructor(t,o){super();K(this,"type","Set");this.assignee=t,this.value=o}},Expression=class extends Statement{constructor(){super(...arguments);K(this,"type","Expression")}},MemberExpression=class extends Expression{constructor(t,o,i){super();K(this,"type","MemberExpression");this.object=t,this.property=o,this.computed=i}},CallExpression=class extends Expression{constructor(t,o){super();K(this,"type","CallExpression");this.callee=t,this.args=o}},Identifier=class extends Expression{constructor(t){super();K(this,"type","Identifier");this.value=t}},Literal=class extends Expression{constructor(t){super();K(this,"type","Literal");this.value=t}},NumericLiteral=class extends Literal{constructor(){super(...arguments);K(this,"type","NumericLiteral")}},StringLiteral=class extends Literal{constructor(t){super(t);K(this,"type","StringLiteral")}},BooleanLiteral=class extends Literal{constructor(){super(...arguments);K(this,"type","BooleanLiteral")}},BinaryExpression=class extends Expression{constructor(t,o,i){super();K(this,"type","BinaryExpression");this.operator=t,this.left=o,this.right=i}},FilterExpression=class extends Expression{constructor(t,o){super();K(this,"type","FilterExpression");this.operand=t,this.filter=o}},UnaryExpression=class extends Expression{constructor(t,o){super();K(this,"type","UnaryExpression");this.operator=t,this.argument=o}},SliceExpression=class extends Expression{constructor(t=void 0,o=void 0,i=void 0){super();K(this,"type","SliceExpression");this.start=t,this.stop=o,this.step=i}};function parse(p){const t=new Program([]);let o=0;function i(k,N){const D=p[o++];if(!D||D.type!==k)throw new Error(`Parser Error: ${N}. ${D.type} !== ${k}.`);return D}function u(){switch(p[o].type){case TOKEN_TYPES.Text:return h();case TOKEN_TYPES.OpenStatement:return m();case TOKEN_TYPES.OpenExpression:return c();default:throw new SyntaxError(`Unexpected token type: ${p[o].type}`)}}function d(...k){return o+k.length<=p.length&&k.some((N,D)=>N!==p[o+D].type)}function a(...k){return o+k.length<=p.length&&k.every((N,D)=>N===p[o+D].type)}function h(){return new StringLiteral(i(TOKEN_TYPES.Text,"Expected text token").value)}function m(){i(TOKEN_TYPES.OpenStatement,"Expected opening statement token");let k;switch(p[o].type){case TOKEN_TYPES.Set:++o,k=l(),i(TOKEN_TYPES.CloseStatement,"Expected closing statement token");break;case TOKEN_TYPES.If:++o,k=n(),i(TOKEN_TYPES.OpenStatement,"Expected {% token"),i(TOKEN_TYPES.EndIf,"Expected endif token"),i(TOKEN_TYPES.CloseStatement,"Expected %} token");break;case TOKEN_TYPES.For:++o,k=e(),i(TOKEN_TYPES.OpenStatement,"Expected {% token"),i(TOKEN_TYPES.EndFor,"Expected endfor token"),i(TOKEN_TYPES.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${p[o].type}`)}return k}function c(){i(TOKEN_TYPES.OpenExpression,"Expected opening expression token");const k=r();return i(TOKEN_TYPES.CloseExpression,"Expected closing expression token"),k}function l(){const k=r();if(a(TOKEN_TYPES.Equals)){++o;const N=l();return new SetStatement(k,N)}return k}function n(){var V,C,B,X,G,ee,J,ae;const k=r();i(TOKEN_TYPES.CloseStatement,"Expected closing statement token");const N=[],D=[];for(;!(((V=p[o])==null?void 0:V.type)===TOKEN_TYPES.OpenStatement&&(((C=p[o+1])==null?void 0:C.type)===TOKEN_TYPES.ElseIf||((B=p[o+1])==null?void 0:B.type)===TOKEN_TYPES.Else||((X=p[o+1])==null?void 0:X.type)===TOKEN_TYPES.EndIf));)N.push(u());if(((G=p[o])==null?void 0:G.type)===TOKEN_TYPES.OpenStatement&&((ee=p[o+1])==null?void 0:ee.type)!==TOKEN_TYPES.EndIf)if(++o,a(TOKEN_TYPES.ElseIf))i(TOKEN_TYPES.ElseIf,"Expected elseif token"),D.push(n());else for(i(TOKEN_TYPES.Else,"Expected else token"),i(TOKEN_TYPES.CloseStatement,"Expected closing statement token");!(((J=p[o])==null?void 0:J.type)===TOKEN_TYPES.OpenStatement&&((ae=p[o+1])==null?void 0:ae.type)===TOKEN_TYPES.EndIf);)D.push(u());return new If(k,N,D)}function e(){const k=$();if(!(k instanceof Identifier))throw new SyntaxError("Expected identifier for the loop variable");i(TOKEN_TYPES.In,"Expected `in` keyword following loop variable");const N=r();i(TOKEN_TYPES.CloseStatement,"Expected closing statement token");const D=[];for(;d(TOKEN_TYPES.OpenStatement,TOKEN_TYPES.EndFor);)D.push(u());return new For(k,N,D)}function r(){return s()}function s(){let k=f();for(;a(TOKEN_TYPES.Or);){const N=p[o];++o;const D=f();k=new BinaryExpression(N,k,D)}return k}function f(){let k=g();for(;a(TOKEN_TYPES.And);){const N=p[o];++o;const D=g();k=new BinaryExpression(N,k,D)}return k}function g(){let k;for(;a(TOKEN_TYPES.Not);){const N=p[o];++o;const D=g();k=new UnaryExpression(N,D)}return k??_()}function _(){let k=b();for(;a(TOKEN_TYPES.ComparisonBinaryOperator)||a(TOKEN_TYPES.In)||a(TOKEN_TYPES.NotIn);){const N=p[o];++o;const D=b();k=new BinaryExpression(N,k,D)}return k}function b(){let k=x();for(;a(TOKEN_TYPES.AdditiveBinaryOperator);){const N=p[o];++o;const D=x();k=new BinaryExpression(N,k,D)}return k}function y(){const k=P();return a(TOKEN_TYPES.OpenParen)?T(k):k}function T(k){let N=new CallExpression(k,w());return a(TOKEN_TYPES.OpenParen)&&(N=T(N)),N}function w(){i(TOKEN_TYPES.OpenParen,"Expected opening parenthesis for arguments list");const k=a(TOKEN_TYPES.CloseParen)?[]:v();return i(TOKEN_TYPES.CloseParen,"Expected closing parenthesis for arguments list"),k}function v(){const k=[r()];for(;a(TOKEN_TYPES.Comma);)++o,k.push(r());return k}function E(){const k=[];let N=!1;for(;!a(TOKEN_TYPES.CloseSquareBracket);)a(TOKEN_TYPES.Colon)?(k.push(void 0),++o,N=!0):(k.push(r()),a(TOKEN_TYPES.Colon)&&(++o,N=!0));if(k.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){if(k.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new SliceExpression(...k)}return k[0]}function P(){let k=$();for(;a(TOKEN_TYPES.Dot)||a(TOKEN_TYPES.OpenSquareBracket);){const N=p[o];++o;let D;const V=N.type!==TOKEN_TYPES.Dot;if(V)D=E(),i(TOKEN_TYPES.CloseSquareBracket,"Expected closing square bracket");else if(D=$(),D.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");k=new MemberExpression(k,D,V)}return k}function x(){let k=O();for(;a(TOKEN_TYPES.MultiplicativeBinaryOperator);){const N=p[o];++o;const D=O();k=new BinaryExpression(N,k,D)}return k}function O(){let k=y();for(;a(TOKEN_TYPES.Pipe);){++o;const N=$();if(!(N instanceof Identifier))throw new SyntaxError("Expected identifier for the filter");k=new FilterExpression(k,N)}return k}function $(){const k=p[o];switch(k.type){case TOKEN_TYPES.NumericLiteral:return++o,new NumericLiteral(Number(k.value));case TOKEN_TYPES.StringLiteral:return++o,new StringLiteral(k.value);case TOKEN_TYPES.BooleanLiteral:return++o,new BooleanLiteral(k.value==="true");case TOKEN_TYPES.Identifier:return++o,new Identifier(k.value);case TOKEN_TYPES.OpenParen:{++o;const N=r();if(p[o].type!==TOKEN_TYPES.CloseParen)throw new SyntaxError("Expected closing parenthesis");return++o,N}default:throw new SyntaxError(`Unexpected token: ${k.type}`)}}for(;o=0?(t=(t??(t=0))<0?Math.max(p.length+t,0):Math.min(t,p.length),o=(o??(o=p.length))<0?Math.max(p.length+o,0):Math.min(o,p.length)):(t=(t??(t=p.length-1))<0?Math.max(p.length+t,-1):Math.min(t,p.length-1),o=(o??(o=-1))<-1?Math.max(p.length+o,-1):Math.min(o,p.length-1));const d=[];for(let a=t;u*anew StringValue(this.value.toUpperCase()))],["lower",new FunctionValue(()=>new StringValue(this.value.toLowerCase()))],["strip",new FunctionValue(()=>new StringValue(this.value.trim()))],["length",new NumericValue(this.value.length)]]))}},BooleanValue=class extends RuntimeValue{constructor(){super(...arguments);K(this,"type","BooleanValue")}},ObjectValue=class extends RuntimeValue{constructor(){super(...arguments);K(this,"type","ObjectValue")}__bool__(){return new BooleanValue(this.value.size>0)}},ArrayValue=class extends RuntimeValue{constructor(){super(...arguments);K(this,"type","ArrayValue");K(this,"builtins",new Map([["length",new NumericValue(this.value.length)]]))}__bool__(){return new BooleanValue(this.value.length>0)}},FunctionValue=class extends RuntimeValue{constructor(){super(...arguments);K(this,"type","FunctionValue")}},NullValue=class extends RuntimeValue{constructor(){super(...arguments);K(this,"type","NullValue")}},UndefinedValue=class extends RuntimeValue{constructor(){super(...arguments);K(this,"type","UndefinedValue")}},Environment=class{constructor(p){K(this,"variables",new Map);this.parent=p}set(p,t){return this.declareVariable(p,convertToRuntimeValues(t))}declareVariable(p,t){if(this.variables.has(p))throw new SyntaxError(`Variable already declared: ${p}`);return this.variables.set(p,t),t}setVariable(p,t){let o;try{o=this.resolve(p)}catch{}return(o??this).variables.set(p,t),t}resolve(p){if(this.variables.has(p))return this;if(this.parent)return this.parent.resolve(p);throw new Error(`Unknown variable: ${p}`)}lookupVariable(p){return this.resolve(p).variables.get(p)??new NullValue}},Interpreter=class{constructor(p){K(this,"global");this.global=p??new Environment}run(p){return this.evaluate(p,this.global)}evaluateBinaryExpression(p,t){const o=this.evaluate(p.left,t),i=this.evaluate(p.right,t);switch(p.operator.value){case"==":return new BooleanValue(o.value==i.value);case"!=":return new BooleanValue(o.value!=i.value);case"and":return o.__bool__().value?i:o;case"or":return o.__bool__().value?o:i}if(o instanceof UndefinedValue||i instanceof UndefinedValue)throw new Error("Cannot perform operation on undefined values");if(o instanceof NullValue||i instanceof NullValue)throw new Error("Cannot perform operation on null values");if(o instanceof NumericValue&&i instanceof NumericValue)switch(p.operator.value){case"+":return new NumericValue(o.value+i.value);case"-":return new NumericValue(o.value-i.value);case"*":return new NumericValue(o.value*i.value);case"/":return new NumericValue(o.value/i.value);case"%":return new NumericValue(o.value%i.value);case"<":return new BooleanValue(o.value":return new BooleanValue(o.value>i.value);case">=":return new BooleanValue(o.value>=i.value);case"<=":return new BooleanValue(o.value<=i.value)}else if(i instanceof ArrayValue){const u=i.value.find(d=>d.value===o.value)!==void 0;switch(p.operator.value){case"in":return new BooleanValue(u);case"not in":return new BooleanValue(!u)}}if(o instanceof StringValue||i instanceof StringValue)switch(p.operator.value){case"+":return new StringValue(o.value.toString()+i.value.toString())}if(o instanceof StringValue&&i instanceof StringValue)switch(p.operator.value){case"in":return new BooleanValue(i.value.includes(o.value));case"not in":return new BooleanValue(!i.value.includes(o.value))}throw new SyntaxError(`Unknown operator "${p.operator.value}" between ${o.type} and ${i.type}`)}evaluateFilterExpression(p,t){const o=this.evaluate(p.operand,t);if(o instanceof ArrayValue)switch(p.filter.value){case"first":return o.value[0];case"last":return o.value[o.value.length-1];case"length":return new NumericValue(o.value.length);case"reverse":return new ArrayValue(o.value.reverse());case"sort":return new ArrayValue(o.value.sort((i,u)=>{if(i.type!==u.type)throw new Error(`Cannot compare different types: ${i.type} and ${u.type}`);switch(i.type){case"NumericValue":return i.value-u.value;case"StringValue":return i.value.localeCompare(u.value);default:throw new Error(`Cannot compare type: ${i.type}`)}}));default:throw new Error(`Unknown filter: ${p.filter.value}`)}throw new Error(`Cannot apply filter to type: ${o.type}`)}evaluateUnaryExpression(p,t){const o=this.evaluate(p.argument,t);switch(p.operator.value){case"not":return new BooleanValue(!o.value);default:throw new SyntaxError(`Unknown operator: ${p.operator.value}`)}}evalProgram(p,t){return this.evaluateBlock(p.body,t)}evaluateBlock(p,t){let o="";for(const i of p){const u=this.evaluate(i,t);u.type!=="NullValue"&&(o+=u.value)}return o=o.replace(/^\n/,""),new StringValue(o)}evaluateIdentifier(p,t){return t.lookupVariable(p.value)}evaluateCallExpression(p,t){const o=p.args.map(u=>this.evaluate(u,t)),i=this.evaluate(p.callee,t);if(i.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(o,t)}evaluateSliceExpression(p,t,o){if(!(p instanceof ArrayValue||p instanceof StringValue))throw new Error("Slice object must be an array or string");const i=this.evaluate(t.start,o),u=this.evaluate(t.stop,o),d=this.evaluate(t.step,o);if(!(i instanceof NumericValue||i instanceof UndefinedValue))throw new Error("Slice start must be numeric or undefined");if(!(u instanceof NumericValue||u instanceof UndefinedValue))throw new Error("Slice stop must be numeric or undefined");if(!(d instanceof NumericValue||d instanceof UndefinedValue))throw new Error("Slice step must be numeric or undefined");return p instanceof ArrayValue?new ArrayValue(slice(p.value,i.value,u.value,d.value)):new StringValue(slice(Array.from(p.value),i.value,u.value,d.value).join(""))}evaluateMemberExpression(p,t){const o=this.evaluate(p.object,t);let i;if(p.computed){if(p.property.type==="SliceExpression")return this.evaluateSliceExpression(o,p.property,t);i=this.evaluate(p.property,t)}else i=new StringValue(p.property.value);let u;if(o instanceof ObjectValue){if(!(i instanceof StringValue))throw new Error(`Cannot access property with non-string: got ${i.type}`);u=o.value.get(i.value)??o.builtins.get(i.value)}else if(o instanceof ArrayValue||o instanceof StringValue)if(i instanceof NumericValue)u=o.value.at(i.value),o instanceof StringValue&&(u=new StringValue(o.value.at(i.value)));else if(i instanceof StringValue)u=o.builtins.get(i.value);else throw new Error(`Cannot access property with non-string/non-number: got ${i.type}`);else{if(!(i instanceof StringValue))throw new Error(`Cannot access property with non-string: got ${i.type}`);u=o.builtins.get(i.value)}if(!(u instanceof RuntimeValue))throw new Error(`${o.type} has no property '${i.value}'`);return u}evaluateSet(p,t){if(p.assignee.type!=="Identifier")throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(p.assignee)}`);const o=p.assignee.value;return t.setVariable(o,this.evaluate(p.value,t)),new NullValue}evaluateIf(p,t){const o=this.evaluate(p.test,t);return this.evaluateBlock(o.__bool__().value?p.body:p.alternate,t)}evaluateFor(p,t){const o=new Environment(t),i=this.evaluate(p.iterable,o);if(!(i instanceof ArrayValue))throw new Error(`Expected iterable type in for loop: got ${i.type}`);let u="";for(let d=0;d[h,m])))),o.setVariable(p.loopvar.value,i.value[d]);const a=this.evaluateBlock(p.body,o);u+=a.value}return new StringValue(u)}evaluate(p,t){if(p===void 0)return new UndefinedValue;switch(p.type){case"Program":return this.evalProgram(p,t);case"Set":return this.evaluateSet(p,t);case"If":return this.evaluateIf(p,t);case"For":return this.evaluateFor(p,t);case"NumericLiteral":return new NumericValue(Number(p.value));case"StringLiteral":return new StringValue(p.value);case"BooleanLiteral":return new BooleanValue(p.value);case"Identifier":return this.evaluateIdentifier(p,t);case"CallExpression":return this.evaluateCallExpression(p,t);case"MemberExpression":return this.evaluateMemberExpression(p,t);case"UnaryExpression":return this.evaluateUnaryExpression(p,t);case"BinaryExpression":return this.evaluateBinaryExpression(p,t);case"FilterExpression":return this.evaluateFilterExpression(p,t);default:throw new SyntaxError(`Unknown node type: ${p.type}`)}}};function convertToRuntimeValues(p){switch(typeof p){case"number":return new NumericValue(p);case"string":return new StringValue(p);case"boolean":return new BooleanValue(p);case"object":return p===null?new NullValue:Array.isArray(p)?new ArrayValue(p.map(convertToRuntimeValues)):new ObjectValue(new Map(Object.entries(p).map(([t,o])=>[t,convertToRuntimeValues(o)])));case"function":return new FunctionValue((t,o)=>{const i=p(...t.map(u=>u.value))??null;return convertToRuntimeValues(i)});default:throw new Error(`Cannot convert to runtime value: ${p}`)}}var Template=class{constructor(p){K(this,"parsed");p=p.replace(/%}\s+{%/g,"%}{%");const t=tokenize(p);this.parsed=parse(t)}render(p){const t=new Environment;t.set("false",!1),t.set("true",!0),t.set("raise_exception",u=>{throw new Error(u)});for(const[u,d]of Object.entries(p))t.set(u,d);return new Interpreter(t).run(this.parsed).value}};async function loadTokenizer(p,t){const o=await Promise.all([getModelJSON(p,"tokenizer.json",!0,t),getModelJSON(p,"tokenizer_config.json",!0,t)]);return t.legacy!==null&&(o[1].legacy=t.legacy),o}function regexSplit(p,t){const o=[];let i=0;for(const u of p.matchAll(t)){const d=u[0];i0&&o.push(d),i=u.index+d.length}return ithis.tokens_to_ids.get(o)??this.unk_token_id)}convert_ids_to_tokens(t){return t.map(o=>this.vocab[o]??this.unk_token)}}class WordPieceTokenizer extends TokenizerModel{constructor(t){super(t),this.tokens_to_ids=objectToMap(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[o,i]of this.tokens_to_ids)this.vocab[i]=o}encode(t){const o=[];for(const i of t){const u=[...i];if(u.length>this.max_input_chars_per_word){o.push(this.unk_token);continue}let d=!1,a=0;const h=[];for(;a0&&(l=this.config.continuing_subword_prefix+l),this.tokens_to_ids.has(l)){c=l;break}--m}if(c===null){d=!0;break}h.push(c),a=m}d?o.push(this.unk_token):o.push(...h)}return o}}class Unigram extends TokenizerModel{constructor(t,o){super(t);const i=t.vocab.length;this.vocab=new Array(i),this.scores=new Array(i);for(let u=0;u[u,d])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=o.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=min(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(t){const o=t.sentence,i=o.length;let u=0;for(;u{const p=[...Array.from({length:94},(u,d)=>d+33),...Array.from({length:12},(u,d)=>d+161),...Array.from({length:82},(u,d)=>d+174)],t=p.slice();let o=0;for(let u=0;u<256;++u)p.includes(u)||(p.push(u),t.push(256+o),o+=1);const i=t.map(u=>String.fromCharCode(u));return Object.fromEntries(p.map((u,d)=>[u,i[d]]))})(),UNICODE_TO_BYTES=reverseDictionary(BYTES_TO_UNICODE);class BPE extends TokenizerModel{constructor(t){super(t),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=objectToMap(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[o,i]of this.tokens_to_ids)this.vocab[i]=o;this.bpe_ranks=new Map(t.merges.map((o,i)=>[o,i])),this.merges=t.merges.map(o=>o.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.cache=new Map}bpe(t){if(t.length===0)return[];const o=this.cache.get(t);if(o!==void 0)return o;const i=Array.from(t);this.end_of_word_suffix&&(i[i.length-1]+=this.end_of_word_suffix);let u=[];if(i.length>1){const d=new PriorityQueue((m,c)=>m.score`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`)):o.push(this.unk_token)}return o}}class LegacyTokenizerModel extends TokenizerModel{constructor(t,o){super(t),this.tokens_to_ids=objectToMap(o.target_lang?t.vocab[o.target_lang]:t.vocab),this.bos_token=o.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=o.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=o.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=o.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[i,u]of this.tokens_to_ids)this.vocab[u]=i}encode(t){return t}}class Normalizer extends Callable{constructor(t){super(),this.config=t}static fromConfig(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new BertNormalizer(t);case"Precompiled":return new Precompiled(t);case"Sequence":return new NormalizerSequence(t);case"Replace":return new Replace(t);case"NFC":return new NFC(t);case"NFKC":return new NFKC(t);case"NFKD":return new NFKD(t);case"Strip":return new StripNormalizer(t);case"StripAccents":return new StripAccents(t);case"Lowercase":return new Lowercase(t);case"Prepend":return new Prepend(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}normalize(t){throw Error("normalize should be implemented in subclass.")}_call(t){return this.normalize(t)}}class Replace extends Normalizer{normalize(t){const o=createPattern(this.config.pattern);return o===null?t:t.replaceAll(o,this.config.content)}}class NFC extends Normalizer{normalize(t){return t=t.normalize("NFC"),t}}class NFKC extends Normalizer{normalize(t){return t=t.normalize("NFKC"),t}}class NFKD extends Normalizer{normalize(t){return t=t.normalize("NFKD"),t}}class StripNormalizer extends Normalizer{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}}class StripAccents extends Normalizer{normalize(t){return t=remove_accents(t),t}}class Lowercase extends Normalizer{normalize(t){return t=t.toLowerCase(),t}}class Prepend extends Normalizer{normalize(t){return t=this.config.prepend+t,t}}class NormalizerSequence extends Normalizer{constructor(t){super(t),this.normalizers=t.normalizers.map(o=>Normalizer.fromConfig(o))}normalize(t){return this.normalizers.reduce((o,i)=>i.normalize(o),t)}}class BertNormalizer extends Normalizer{_tokenize_chinese_chars(t){const o=[];for(let i=0;i=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103}stripAccents(t){return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}_is_control(t){switch(t){case" ":case` `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}_clean_text(t){const o=[];for(const i of t){const u=i.charCodeAt(0);u===0||u===65533||this._is_control(i)||(/^\s$/.test(i)?o.push(" "):o.push(i))}return o.join("")}normalize(t){return this.config.clean_text&&(t=this._clean_text(t)),this.config.handle_chinese_chars&&(t=this._tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.stripAccents(t))):this.config.strip_accents&&(t=this.stripAccents(t)),t}}class PreTokenizer extends Callable{static fromConfig(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new BertPreTokenizer(t);case"Sequence":return new PreTokenizerSequence(t);case"Whitespace":return new WhitespacePreTokenizer(t);case"WhitespaceSplit":return new WhitespaceSplit(t);case"Metaspace":return new MetaspacePreTokenizer(t);case"ByteLevel":return new ByteLevelPreTokenizer(t);case"Split":return new SplitPreTokenizer(t);case"Punctuation":return new PunctuationPreTokenizer(t);case"Digits":return new DigitsPreTokenizer(t);case"Replace":return new ReplacePreTokenizer(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}pre_tokenize_text(t,o){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(t,o){return(Array.isArray(t)?t.map(i=>this.pre_tokenize_text(i,o)):this.pre_tokenize_text(t,o)).flat()}_call(t,o){return this.pre_tokenize(t,o)}}class BertPreTokenizer extends PreTokenizer{constructor(t){super(),this.pattern=new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`,"gu")}pre_tokenize_text(t,o){return t.trim().match(this.pattern)||[]}}class ByteLevelPreTokenizer extends PreTokenizer{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=BYTES_TO_UNICODE,this.text_encoder=new TextEncoder}pre_tokenize_text(t,o){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(u=>Array.from(this.text_encoder.encode(u),d=>this.byte_encoder[d]).join(""))}}class SplitPreTokenizer extends PreTokenizer{constructor(t){super(),this.config=t,this.pattern=createPattern(this.config.pattern,this.config.invert)}pre_tokenize_text(t,o){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:regexSplit(t,this.pattern)}}class PunctuationPreTokenizer extends PreTokenizer{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`,"gu")}pre_tokenize_text(t,o){return t.match(this.pattern)||[]}}class DigitsPreTokenizer extends PreTokenizer{constructor(t){super(),this.config=t;const o=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(o,"gu")}pre_tokenize_text(t,o){return t.match(this.pattern)||[]}}class PostProcessor extends Callable{constructor(t){super(),this.config=t}static fromConfig(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new TemplateProcessing(t);case"ByteLevel":return new ByteLevelPostProcessor(t);case"RobertaProcessing":return new RobertaProcessing(t);case"BertProcessing":return new BertProcessing(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}post_process(t,...o){throw Error("post_process should be implemented in subclass.")}_call(t,...o){return this.post_process(t,...o)}}class BertProcessing extends PostProcessor{constructor(t){super(t),this.cls=t.cls[0],this.sep=t.sep[0]}post_process(t,o=null,{add_special_tokens:i=!0}={}){i&&(t=mergeArrays([this.cls],t,[this.sep]));let u=new Array(t.length).fill(0);if(o!==null){const d=i&&this instanceof RobertaProcessing?[this.sep]:[],a=i?[this.sep]:[];t=mergeArrays(t,d,o,a),u=mergeArrays(u,new Array(o.length+d.length+a.length).fill(1))}return{tokens:t,token_type_ids:u}}}class RobertaProcessing extends BertProcessing{}class TemplateProcessing extends PostProcessor{constructor(t){super(t),this.single=t.single,this.pair=t.pair}post_process(t,o=null,{add_special_tokens:i=!0}={}){const u=o===null?this.single:this.pair;let d=[],a=[];for(const h of u)"SpecialToken"in h?i&&(d.push(h.SpecialToken.id),a.push(h.SpecialToken.type_id)):"Sequence"in h&&(h.Sequence.id==="A"?(d=mergeArrays(d,t),a=mergeArrays(a,new Array(t.length).fill(h.Sequence.type_id))):h.Sequence.id==="B"&&(d=mergeArrays(d,o),a=mergeArrays(a,new Array(o.length).fill(h.Sequence.type_id))));return{tokens:d,token_type_ids:a}}}class ByteLevelPostProcessor extends PostProcessor{post_process(t,o=null){return o&&(t=mergeArrays(t,o)),{tokens:t}}}class Decoder extends Callable{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=t.trim_offsets}static fromConfig(t){if(t===null)return null;switch(t.type){case"WordPiece":return new WordPieceDecoder(t);case"Metaspace":return new MetaspaceDecoder(t);case"ByteLevel":return new ByteLevelDecoder(t);case"Replace":return new ReplaceDecoder(t);case"ByteFallback":return new ByteFallback(t);case"Fuse":return new FuseDecoder(t);case"Strip":return new StripDecoder(t);case"Sequence":return new DecoderSequence(t);case"CTC":return new CTCDecoder(t);case"BPEDecoder":return new BPEDecoder(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}decode_chain(t){throw Error("`decode_chain` should be implemented in subclass.")}}class ReplaceDecoder extends Decoder{decode_chain(t){const o=createPattern(this.config.pattern);return o===null?t:t.map(i=>i.replaceAll(o,this.config.content))}}class ByteFallback extends Decoder{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){const o=[];let i=[];for(const u of t){let d=null;if(u.length===6&&u.startsWith("<0x")&&u.endsWith(">")){const a=parseInt(u.slice(3,5),16);isNaN(a)||(d=a)}if(d!==null)i.push(d);else{if(i.length>0){const a=this.text_decoder.decode(Uint8Array.from(i));o.push(a),i=[]}o.push(u)}}if(i.length>0){const u=this.text_decoder.decode(Uint8Array.from(i));o.push(u),i=[]}return o}}class FuseDecoder extends Decoder{decode_chain(t){return[t.join("")]}}class StripDecoder extends Decoder{constructor(t){super(t),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(t){return t.map(o=>{let i=0;for(let d=0;d(i!==0&&(o.startsWith(this.config.prefix)?o=o.replace(this.config.prefix,""):o=" "+o),this.cleanup&&(o=clean_up_tokenization(o)),o))}}class ByteLevelDecoder extends Decoder{constructor(t){super(t),this.byte_decoder=UNICODE_TO_BYTES,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){const o=t.join(""),i=new Uint8Array([...o].map(d=>this.byte_decoder[d]));return this.text_decoder.decode(i)}decode_chain(t){const o=[];let i=[];for(const u of t)this.added_tokens.find(d=>d.content===u)!==void 0?(i.length>0&&(o.push(this.convert_tokens_to_string(i)),i=[]),o.push(u)):i.push(u);return i.length>0&&o.push(this.convert_tokens_to_string(i)),o}}class CTCDecoder extends Decoder{constructor(t){super(t),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";const o=[t[0]];for(let d=1;dd!==this.pad_token).join("");return this.cleanup&&(u=clean_up_tokenization(u).replaceAll(this.word_delimiter_token," ").trim()),u}decode_chain(t){return[this.convert_tokens_to_string(t)]}}class DecoderSequence extends Decoder{constructor(t){super(t),this.decoders=t.decoders.map(o=>Decoder.fromConfig(o))}decode_chain(t){return this.decoders.reduce((o,i)=>i.decode_chain(o),t)}}class BPEDecoder extends Decoder{constructor(t){super(t),this.suffix=this.config.suffix}decode_chain(t){return t.map((o,i)=>o.replaceAll(this.suffix,i===t.length-1?"":" "))}}class VitsDecoder extends Decoder{decode_chain(t){let o="";for(let i=1;ii.normalize("NFKC")).join("~"):t=t.normalize("NFKC"),t}}class PreTokenizerSequence extends PreTokenizer{constructor(t){super(),this.tokenizers=t.pretokenizers.map(o=>PreTokenizer.fromConfig(o))}pre_tokenize_text(t,o){return this.tokenizers.reduce((i,u)=>u.pre_tokenize(i,o),[t])}}class WhitespacePreTokenizer extends PreTokenizer{constructor(t){super()}pre_tokenize_text(t,o){return t.match(/\w+|[^\w\s]+/g)||[]}}class WhitespaceSplit extends PreTokenizer{constructor(t){super()}pre_tokenize_text(t,o){return whitespace_split(t)}}class ReplacePreTokenizer extends PreTokenizer{constructor(t){super(),this.config=t,this.pattern=createPattern(this.config.pattern),this.content=this.config.content}pre_tokenize_text(t,o){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content)]}}const SPECIAL_TOKEN_ATTRIBUTES=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function padHelper(p,t,o,i){for(const u of Object.keys(p)){const d=t-p[u].length,a=o(u),h=new Array(d).fill(a);p[u]=i==="right"?mergeArrays(p[u],h):mergeArrays(h,p[u])}}function truncateHelper(p,t){for(const o of Object.keys(p))p[o].length=t}class PreTrainedTokenizer extends Callable{constructor(o,i){super();K(this,"return_token_type_ids",!1);K(this,"_default_chat_template",`{% for message in messages %}{{'<|im_start|>' + message['role'] + ' ' + message['content'] + '<|im_end|>' + ' '}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant ' }}{% endif %}`);this._tokenizer_config=i,this.normalizer=Normalizer.fromConfig(o.normalizer),this.pre_tokenizer=PreTokenizer.fromConfig(o.pre_tokenizer),this.model=TokenizerModel.fromConfig(o.model,i),this.post_processor=PostProcessor.fromConfig(o.post_processor),this.decoder=Decoder.fromConfig(o.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const u of o.added_tokens){const d=new AddedToken(u);this.added_tokens.push(d),this.model.tokens_to_ids.set(d.content,d.id),this.model.vocab[d.id]=d.content,d.special&&(this.special_tokens.push(d.content),this.all_special_ids.push(d.id))}this.additional_special_tokens=i.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.map(u=>`${u.lstrip?"\\s*":""}(${escapeRegExp(u.content)})${u.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=i.model_max_length,this.remove_space=i.remove_space,this.clean_up_tokenization_spaces=i.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=i.do_lowercase_and_remove_accent??!1,this.padding_side="right",this.legacy=!1,this.chat_template=i.chat_template??null,this._compiled_template_cache=new Map}getToken(...o){for(const i of o){const u=this._tokenizer_config[i];if(u)if(typeof u=="object"){if(u.__type==="AddedToken")return u.content;throw Error(`Unknown token: ${u}`)}else return u}return null}static async from_pretrained(o,{progress_callback:i=null,config:u=null,cache_dir:d=null,local_files_only:a=!1,revision:h="main",legacy:m=null}={}){const c=await loadTokenizer(o,{progress_callback:i,config:u,cache_dir:d,local_files_only:a,revision:h,legacy:m});return new this(...c)}_call(o,{text_pair:i=null,add_special_tokens:u=!0,padding:d=!1,truncation:a=null,max_length:h=null,return_tensor:m=!0}={}){const c=Array.isArray(o);let l;if(c){if(o.length===0)throw Error("text array must be non-empty");if(i!==null){if(Array.isArray(i)){if(o.length!==i.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");l=o.map((e,r)=>this._encode_plus(e,i[r],{add_special_tokens:u}))}else l=o.map(e=>this._encode_plus(e,null,{add_special_tokens:u}))}else{if(o===null)throw Error("text may not be null");if(Array.isArray(i))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");l=[this._encode_plus(o,i,{add_special_tokens:u})]}if(h===null?d==="max_length"?h=this.model_max_length:h=max(l.map(e=>e.input_ids.length))[0]:a||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),h=Math.min(h,this.model_max_length),d||a)for(let e=0;eh?a&&truncateHelper(l[e],h):d&&padHelper(l[e],h,r=>r==="input_ids"?this.pad_token_id:0,this.padding_side));const n={};if(m){if(!(d&&a)&&l.some(r=>{var s;for(const f of Object.keys(r))if(r[f].length!==((s=l[0][f])==null?void 0:s.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const e=[l.length,l[0].input_ids.length];for(const r of Object.keys(l[0]))n[r]=new Tensor("int64",BigInt64Array.from(l.flatMap(s=>s[r]).map(BigInt)),e)}else{for(const e of Object.keys(l[0]))n[e]=l.map(r=>r[e]);if(!c)for(const e of Object.keys(n))n[e]=n[e][0]}return n}_encode_text(o){return o===null?null:(this.added_tokens_regex?o.split(this.added_tokens_regex).filter(d=>d):[o]).map((d,a)=>{if(this.added_tokens.find(m=>m.content===d)!==void 0)return d;{if(this.remove_space===!0&&(d=d.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(d=lowercase_and_remove_accent(d)),this.normalizer!==null&&(d=this.normalizer(d)),d.length===0)return[];const m=this.pre_tokenizer!==null?this.pre_tokenizer(d,{section_index:a}):[d];return this.model(m)}}).flat()}_encode_plus(o,i=null,{add_special_tokens:u=!0}={}){const d=this._encode_text(o),a=this._encode_text(i),h=this.post_processor?this.post_processor(d,a,{add_special_tokens:u}):{tokens:mergeArrays(d??[],a??[])},m=this.model.convert_tokens_to_ids(h.tokens),c={input_ids:m,attention_mask:new Array(m.length).fill(1)};return this.return_token_type_ids&&h.token_type_ids&&(c.token_type_ids=h.token_type_ids),c}encode(o,i=null,{add_special_tokens:u=!0}={}){const{input_ids:d}=this._encode_plus(o,i,{add_special_tokens:u});return d}batch_decode(o,i={}){return o instanceof Tensor&&(o=o.tolist()),o.map(u=>this.decode(u,i))}decode(o,i={}){if(o instanceof Tensor&&(o=prepareTensorForDecode(o)),!Array.isArray(o)||o.length===0||!isIntegralNumber(o[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(o,i)}decode_single(o,{skip_special_tokens:i=!1,clean_up_tokenization_spaces:u=null}){let d=this.model.convert_ids_to_tokens(o);i&&(d=d.filter(h=>!this.special_tokens.includes(h)));let a=this.decoder?this.decoder(d):d.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(a=a.replaceAll(this.decoder.end_of_word_suffix," "),i&&(a=a.trim())),(u??this.clean_up_tokenization_spaces)&&(a=clean_up_tokenization(a)),a}get default_chat_template(){return this._warned_about_chat_template||(console.warn("No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information."),this._warned_about_chat_template=!0),this._default_chat_template}apply_chat_template(o,{chat_template:i=null,add_generation_prompt:u=!1,tokenize:d=!0,padding:a=!1,truncation:h=!1,max_length:m=null,return_tensor:c=!0}={}){i??(i=this.chat_template??this.default_chat_template);let l=this._compiled_template_cache.get(i);l===void 0&&(l=new Template(i),this._compiled_template_cache.set(i,l));const n=Object.create(null);for(const r of SPECIAL_TOKEN_ATTRIBUTES){const s=this.getToken(r);s&&(n[r]=s)}const e=l.render({messages:o,add_generation_prompt:u,...n});return d?this._call(e,{add_special_tokens:!1,padding:a,truncation:h,max_length:m,return_tensor:c}).input_ids:e}}class BertTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"return_token_type_ids",!0)}}class AlbertTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"return_token_type_ids",!0)}}class MobileBertTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"return_token_type_ids",!0)}}class SqueezeBertTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"return_token_type_ids",!0)}}class DebertaTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"return_token_type_ids",!0)}}class DebertaV2Tokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"return_token_type_ids",!0)}}class HerbertTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"return_token_type_ids",!0)}}class ConvBertTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"return_token_type_ids",!0)}}class RoFormerTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"return_token_type_ids",!0)}}class DistilBertTokenizer extends PreTrainedTokenizer{}class CamembertTokenizer extends PreTrainedTokenizer{}class XLMTokenizer extends PreTrainedTokenizer{constructor(o,i){super(o,i);K(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class ElectraTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"return_token_type_ids",!0)}}class T5Tokenizer extends PreTrainedTokenizer{}class GPT2Tokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"_default_chat_template",'{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}')}}class BartTokenizer extends PreTrainedTokenizer{}class MBartTokenizer extends PreTrainedTokenizer{constructor(t,o){super(t,o),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(i=>this.languageRegex.test(i)),this.lang_to_token=i=>i}_build_translation_inputs(t,o,i){return _build_translation_inputs(this,t,o,i)}}class MBart50Tokenizer extends MBartTokenizer{}class RobertaTokenizer extends PreTrainedTokenizer{}class BloomTokenizer extends GPT2Tokenizer{constructor(t,o){var d,a;const i=".,!?…。,、।۔،",u=(a=(d=t.pre_tokenizer)==null?void 0:d.pretokenizers[0])==null?void 0:a.pattern;u&&u.Regex===` ?[^(\\s|[${i}])]+`&&(u.Regex=` ?[^\\s${i}]+`),super(t,o)}}const SPIECE_UNDERLINE="▁";class LlamaTokenizer extends PreTrainedTokenizer{constructor(o,i){super(o,i);K(this,"_default_chat_template",`{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<> ' + system_message + ' <> ' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<> ' + content.strip() + ' <> ' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`);K(this,"DEFAULT_SYSTEM_PROMPT",`You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.`);this.use_default_system_prompt=i.use_default_system_prompt??!1,this.legacy=i.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new MetaspacePreTokenizer({replacement:SPIECE_UNDERLINE,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(o){if(o===null)return null;if(this.legacy||o.length===0)return super._encode_text(o);let i=super._encode_text(SPIECE_UNDERLINE+o.replaceAll(SPIECE_UNDERLINE," "));return i.length>1&&i[0]===SPIECE_UNDERLINE&&this.special_tokens.includes(i[1])&&(i=i.slice(1)),i}get default_chat_template(){return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT",this.use_default_system_prompt?"true":"false").replaceAll("DEFAULT_SYSTEM_MESSAGE",this.DEFAULT_SYSTEM_PROMPT.replaceAll(` `,"\\n").replaceAll("'","\\'"))}}class CodeLlamaTokenizer extends LlamaTokenizer{}class XLMRobertaTokenizer extends PreTrainedTokenizer{}class MPNetTokenizer extends PreTrainedTokenizer{}class FalconTokenizer extends PreTrainedTokenizer{}class GPTNeoXTokenizer extends PreTrainedTokenizer{}class EsmTokenizer extends PreTrainedTokenizer{}class Qwen2Tokenizer extends PreTrainedTokenizer{}function _build_translation_inputs(p,t,o,i){if(!("language_codes"in p)||!Array.isArray(p.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in p)||!(p.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in p)||typeof p.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const u=i.src_lang,d=i.tgt_lang;if(!p.language_codes.includes(d))throw new Error(`Target language code "${d}" is not valid. Must be one of: {${p.language_codes.join(", ")}}`);if(u!==void 0){if(!p.language_codes.includes(u))throw new Error(`Source language code "${u}" is not valid. Must be one of: {${p.language_codes.join(", ")}}`);for(const a of p.post_processor.config.single)if("SpecialToken"in a&&p.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=p.lang_to_token(u);break}}return i.forced_bos_token_id=p.model.convert_tokens_to_ids([p.lang_to_token(d)])[0],p._call(t,o)}class NllbTokenizer extends PreTrainedTokenizer{constructor(t,o){super(t,o),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(i=>this.languageRegex.test(i)),this.lang_to_token=i=>i}_build_translation_inputs(t,o,i){return _build_translation_inputs(this,t,o,i)}}class M2M100Tokenizer extends PreTrainedTokenizer{constructor(t,o){super(t,o),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(i=>this.languageRegex.test(i)).map(i=>i.slice(2,-2)),this.lang_to_token=i=>`__${i}__`}_build_translation_inputs(t,o,i){return _build_translation_inputs(this,t,o,i)}}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"]],WHISPER_LANGUAGE_MAPPING=new Map(WHISPER_LANGUAGES),WHISPER_TO_LANGUAGE_CODE_MAPPING=new Map([...WHISPER_LANGUAGES.map(([p,t])=>[t,p]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);class WhisperTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"_default_chat_template",'{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}')}_decode_asr(o,{return_timestamps:i=!1,return_language:u=!1,time_precision:d=null,force_full_sequences:a=!0}={}){if(d===null)throw Error("Must specify time_precision");let h=null;const m=i==="word";function c(){return{language:h,timestamp:[null,null],text:""}}const l=[];let n=c(),e=0;const r=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1;let s=[],f=[],g=!1,_=null;const b=new Set(this.all_special_ids);for(const w of o){const v=w.tokens,E=m?w.token_timestamps:null;let P=null,x=r;if("stride"in w){const[k,N,D]=w.stride;if(e-=N,_=k-D,N&&(x=N/d+r),D)for(let V=v.length-1;V>=0;--V){const C=v[V];if(C>=r){if(P!==null&&(C-r)*d<_)break;P=C}}}let O=[],$=[];for(let k=0;k=r){const D=(N-r)*d+e,V=round(D,2);if(P!==null&&N>=P)g=!0;else if(g||s.length>0&&N0?(s.push(O),m&&f.push($)):s.every(k=>k.length===0)&&(n=c(),s=[],O=[],f=[],$=[])}if(s.length>0){if(a&&i)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[w,v]=this.findLongestCommonSequence(s,f),E=this.decode(w);n.text=E,m&&(n.words=this.collateWordTimestamps(w,v,h)),l.push(n)}let y=Object.create(null);const T=l.map(w=>w.text).join("");if(i||u){for(let w=0;w0;let m=h?[]:null,c=h?i[0]:null;for(let l=1;lV===k[C]).length,D=N/w+v;N>1&&D>e&&(e=D,r=[E,P,O,$])}const[f,g,_,b]=r,y=Math.floor((g+f)/2),T=Math.floor((b+_)/2);a.push(...u.slice(0,y)),u=n.slice(T),d=u.length,h&&(m.push(...c.slice(0,y)),c=i[l].slice(T))}return a.push(...u),h?(m.push(...c),[a,m]):[a,[]]}collateWordTimestamps(o,i,u){const[d,a,h]=this.combineTokensIntoWords(o,u),m=[];for(let c=0;c=d){const m=round((h-d)*u,2);a.push(`<|${m}|>`),a.push([])}else a[a.length-1].push(h);return a=a.map(h=>typeof h=="string"?h:super.decode(h,i)),a.join("")}splitTokensOnUnicode(o){const i=this.decode(o,{decode_with_timestamps:!0}),u="�",d=[],a=[],h=[];let m=[],c=[],l=0;for(let n=0;n=this.model.tokens_to_ids.get("<|endoftext|>"),f=n.startsWith(" "),g=n.trim(),_=c.test(g);if(s||f||_||a.length===0)a.push(n),h.push(e),m.push(r);else{const b=a.length-1;a[b]+=n,h[b].push(...e),m[b].push(...r)}}return[a,h,m]}mergePunctuations(o,i,u,d,a){const h=structuredClone(o),m=structuredClone(i),c=structuredClone(u);let l=h.length-2,n=h.length-1;for(;l>=0;)h[l].startsWith(" ")&&d.includes(h[l].trim())?(h[n]=h[l]+h[n],m[n]=mergeArrays(m[l],m[n]),c[n]=mergeArrays(c[l],c[n]),h[l]="",m[l]=[],c[l]=[]):n=l,--l;for(l=0,n=1;ne),m.filter(e=>e.length>0),c.filter(e=>e.length>0)]}get_decoder_prompt_ids({language:o=null,task:i=null,no_timestamps:u=!0}={}){const d=[];if(o){o=o.toLowerCase();let a=WHISPER_TO_LANGUAGE_CODE_MAPPING.get(o);if(a===void 0)if(WHISPER_LANGUAGE_MAPPING.has(o))a=o;else{const c=o.length===2?WHISPER_LANGUAGE_MAPPING.keys():WHISPER_LANGUAGE_MAPPING.values();throw new Error(`Language "${o}" is not supported. Must be one of: ${JSON.stringify(c)}`)}const h=this.model.tokens_to_ids.get(`<|${a}|>`);if(h===void 0)throw new Error(`Unable to find language "${a}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);d.push(h)}else d.push(null);if(i){if(i=i.toLowerCase(),i!=="transcribe"&&i!=="translate")throw new Error(`Task "${i}" is not supported. Must be one of: ["transcribe", "translate"]`);const a=this.model.tokens_to_ids.get(`<|${i}|>`);if(a===void 0)throw new Error(`Unable to find task "${i}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);d.push(a)}else d.push(null);if(u){const a=this.model.tokens_to_ids.get("<|notimestamps|>");if(a===void 0)throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.');d.push(a)}return d.map((a,h)=>[h+1,a]).filter(a=>a[1]!==null)}}class CodeGenTokenizer extends PreTrainedTokenizer{}class CLIPTokenizer extends PreTrainedTokenizer{}class SiglipTokenizer extends PreTrainedTokenizer{}class MarianTokenizer extends PreTrainedTokenizer{constructor(t,o){super(t,o),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(i=>this.languageRegex.test(i)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(t){if(t===null)return null;const[o,...i]=t.trim().split(this.languageRegex);if(i.length===0)return super._encode_text(o);if(i.length===2){const[u,d]=i;return this.supported_language_codes.includes(u)||console.warn(`Unsupported language code "${u}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),mergeArrays([u],super._encode_text(d))}}}class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer{}class BlenderbotTokenizer extends PreTrainedTokenizer{constructor(){super(...arguments);K(this,"_default_chat_template","{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}")}}class BlenderbotSmallTokenizer extends BlenderbotTokenizer{}class SpeechT5Tokenizer extends PreTrainedTokenizer{}class NougatTokenizer extends PreTrainedTokenizer{}class VitsTokenizer extends PreTrainedTokenizer{constructor(t,o){super(t,o),this.decoder=new VitsDecoder({})}}class AutoTokenizer{static async from_pretrained(t,{quantized:o=!0,progress_callback:i=null,config:u=null,cache_dir:d=null,local_files_only:a=!1,revision:h="main",legacy:m=null}={}){var r;const[c,l]=await loadTokenizer(t,{quantized:o,progress_callback:i,config:u,cache_dir:d,local_files_only:a,revision:h,legacy:m}),n=((r=l.tokenizer_class)==null?void 0:r.replace(/Fast$/,""))??"PreTrainedTokenizer";let e=this.TOKENIZER_CLASS_MAPPING[n];return e||(console.warn(`Unknown tokenizer class "${n}", attempting to construct from base class.`),e=PreTrainedTokenizer),new e(c,l)}}K(AutoTokenizer,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer,DistilBertTokenizer,CamembertTokenizer,DebertaTokenizer,DebertaV2Tokenizer,BertTokenizer,HerbertTokenizer,ConvBertTokenizer,RoFormerTokenizer,XLMTokenizer,ElectraTokenizer,MobileBertTokenizer,SqueezeBertTokenizer,AlbertTokenizer,GPT2Tokenizer,BartTokenizer,MBartTokenizer,MBart50Tokenizer,RobertaTokenizer,WhisperTokenizer,CodeGenTokenizer,CLIPTokenizer,SiglipTokenizer,MarianTokenizer,BloomTokenizer,NllbTokenizer,M2M100Tokenizer,LlamaTokenizer,CodeLlamaTokenizer,XLMRobertaTokenizer,MPNetTokenizer,FalconTokenizer,GPTNeoXTokenizer,EsmTokenizer,Wav2Vec2CTCTokenizer,BlenderbotTokenizer,BlenderbotSmallTokenizer,SpeechT5Tokenizer,NougatTokenizer,VitsTokenizer,Qwen2Tokenizer,PreTrainedTokenizer});async function loadConfig(p,t){return await getModelJSON(p,"config.json",!0,t)}class PretrainedConfig{constructor(t){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,t)}static async from_pretrained(t,{progress_callback:o=null,config:i=null,cache_dir:u=null,local_files_only:d=!1,revision:a="main"}={}){let h=i??await loadConfig(t,{progress_callback:o,config:i,cache_dir:u,local_files_only:d,revision:a});return new this(h)}}class AutoConfig{static async from_pretrained(...t){return PretrainedConfig.from_pretrained(...t)}}class LogitsProcessorList extends Callable{constructor(){super(),this.processors=[]}push(t){this.processors.push(t)}extend(t){this.processors.push(...t)}_call(t,o){for(let i of o)this.processors.forEach(u=>u(t,i))}[Symbol.iterator](){return this.processors.values()}}class LogitsProcessor extends Callable{_call(t,o){throw Error("`_call` should be implemented in a subclass")}}class ForceTokensLogitsProcessor extends LogitsProcessor{constructor(t){super(),this.force_token_map=Object.fromEntries(t??[])}_call(t,o){let i=this.force_token_map[t.length];return exists(i)&&(o.data.fill(-1/0),o.data[i]=0),o}}class ForcedBOSTokenLogitsProcessor extends LogitsProcessor{constructor(t){super(),this.bos_token_id=t}_call(t,o){return t.length===1&&(o.data.fill(-1/0),o.data[this.bos_token_id]=0),o}}class ForcedEOSTokenLogitsProcessor extends LogitsProcessor{constructor(t,o){super(),this.max_length=t,this.forced_eos_token_id=o}_call(t,o){}}class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor{constructor(t,o){super(),this.begin_suppress_tokens=t,this.begin_index=o}_call(t,o){if(t.length===this.begin_index)for(let i of this.begin_suppress_tokens)o.data[i]=-1/0;return o}}class WhisperTimeStampLogitsProcessor extends LogitsProcessor{constructor(t){super(),this.eos_token_id=t.eos_token_id,this.no_timestamps_token_id=t.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=(t.forced_decoder_ids||[]).length+2,t.forced_decoder_ids.slice(-1)[0][1]===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=t.max_initial_timestamp_index}_call(t,o){const i=o.data;if(i[this.no_timestamps_token_id]=-1/0,t.length===this.begin_index-1)return i.fill(-1/0),i[this.timestamp_begin]=0,o;const u=t.slice(this.begin_index),d=u.length>=1&&u[u.length-1]>=this.timestamp_begin,a=u.length<2||u[u.length-2]>=this.timestamp_begin;if(d&&(a?i.subarray(this.timestamp_begin).fill(-1/0):i.subarray(0,this.eos_token_id).fill(-1/0)),t.length===this.begin_index&&this.max_initial_timestamp_index!==null){const l=this.timestamp_begin+this.max_initial_timestamp_index;i.subarray(l+1).fill(-1/0)}const h=log_softmax(i),m=Math.log(h.subarray(this.timestamp_begin).map(Math.exp).reduce((l,n)=>l+n)),c=max(h.subarray(0,this.timestamp_begin))[0];return m>c&&i.subarray(0,this.timestamp_begin).fill(-1/0),o}}class NoRepeatNGramLogitsProcessor extends LogitsProcessor{constructor(t){super(),this.no_repeat_ngram_size=t}getNgrams(t){const o=t.length,i=[];for(let d=0;d0&&(u=u.map(d=>d/this.generation_config.temperature)),u}randomSelect(t){let o=t.reduce((u,d)=>u+d,0),i=Math.random()*o;for(let u=0;u1)return new BeamSearchSampler(t);if(t.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${t.num_return_sequences}.`);return new GreedySampler(t)}}class GreedySampler extends Sampler{sample(t,o=-1){let i=this.getLogits(t,o);return[[max(i)[1],0]]}}class MultinomialSampler extends Sampler{sample(t,o=-1){let i=t.dims.at(-1);this.generation_config.top_k>0&&(i=Math.min(this.generation_config.top_k,i));const u=this.getLogits(t,o),d=getTopItems(u,i),a=softmax(d.map(h=>h[1]));return Array.from({length:this.generation_config.num_beams},()=>{const h=this.randomSelect(a);return[d[h][0],Math.log(a[h])]})}}class BeamSearchSampler extends Sampler{sample(t,o=-1){let i=t.dims.at(-1);this.generation_config.top_k>0&&(i=Math.min(this.generation_config.top_k,i));const u=this.getLogits(t,o),d=getTopItems(u,i),a=softmax(d.map(h=>h[1]));return Array.from({length:this.generation_config.num_beams},(h,m)=>[d[m][0],Math.log(a[m])])}}const{InferenceSession,Tensor:ONNXTensor,env}=ONNX,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(p,t,o){let i=`onnx/${t}${o.quantized?"_quantized":""}.onnx`,u=await getModelFile(p,i,!0,o);try{return await InferenceSession.create(u,{executionProviders})}catch(d){if(executionProviders.length===1&&executionProviders[0]==="wasm")throw d;return console.warn(d),console.warn("Something went wrong during model construction (most likely a missing operation). Using `wasm` as a fallback. "),await InferenceSession.create(u,{executionProviders:["wasm"]})}}function validateInputs(p,t){const o=Object.create(null),i=[];for(const a of p.inputNames){const h=t[a];if(!(h instanceof Tensor)){i.push(a);continue}o[a]=env.wasm.proxy?h.clone():h}if(i.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${i.join(", ")}.`);const u=Object.keys(t).length,d=p.inputNames.length;if(u>d){let a=Object.keys(t).filter(h=>!p.inputNames.includes(h));console.warn(`WARNING: Too many inputs were provided (${u} > ${d}). The following inputs will be ignored: "${a.join(", ")}".`)}return o}async function sessionRun(p,t){const o=validateInputs(p,t);try{let i=await p.run(o);return i=replaceTensors(i),i}catch(i){throw console.error(`An error occurred during model execution: "${i}".`),console.error("Inputs given to model:",o),i}}function replaceTensors(p){for(let t in p)p[t]instanceof ONNXTensor?p[t]=new Tensor(p[t]):typeof p[t]=="object"&&replaceTensors(p[t]);return p}function toI64Tensor(p){if(p instanceof Tensor)return p;if(p.length===0)throw Error("items must be non-empty");if(Array.isArray(p[0])){if(p.some(t=>t.length!==p[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(p.flat().map(t=>BigInt(t))),[p.length,p[0].length])}else return new Tensor("int64",BigInt64Array.from(p.map(t=>BigInt(t))),[1,p.length])}function prepareAttentionMask(p,t){let o=p.config.pad_token_id??null,i=p.config.eos_token_id??null;isIntegralNumber(i)&&(i=[i]);let u=t.indexOf(o)!==-1,d=i===null||!i.includes(o);if(u&&d){let a=BigInt64Array.from(t.data.map(h=>h!=o));return new Tensor("int64",a,t.dims)}else return ones_like(t)}function preparePositionIds(p,t,o){if(!p.inputNames.includes("position_ids"))return;const i=new BigInt64Array(t.attention_mask.data.length);for(let u=0;u0&&d.push(new NoRepeatNGramLogitsProcessor(o.no_repeat_ngram_size)),o.bad_words_ids!==null&&d.push(new NoBadWordsLogitsProcessor(o.bad_words_ids,o.eos_token_id)),o.min_length!==null&&o.eos_token_id!==null&&o.min_length>0&&d.push(new MinLengthLogitsProcessor(o.min_length,o.eos_token_id)),o.min_new_tokens!==null&&o.eos_token_id!==null&&o.min_new_tokens>0&&d.push(new MinNewTokensLengthLogitsProcessor(i,o.min_new_tokens,o.eos_token_id)),o.forced_bos_token_id!==null&&d.push(new ForcedBOSTokenLogitsProcessor(o.forced_bos_token_id)),o.forced_eos_token_id!==null&&d.push(new ForcedEOSTokenLogitsProcessor(o.max_length,o.forced_eos_token_id)),o.begin_suppress_tokens!==null){let a=i>1||o.forced_bos_token_id===null?i:i+1;o.forced_decoder_ids!==null&&(a+=o.forced_decoder_ids[o.forced_decoder_ids.length-1][0]),d.push(new SuppressTokensAtBeginLogitsProcessor(o.begin_suppress_tokens,a))}return o.forced_decoder_ids!==null&&d.push(new ForceTokensLogitsProcessor(o.forced_decoder_ids)),u!==null&&d.extend(u),d}_get_generation_config(o){let i=new GenerationConfig(this.config);return"generation_config"in this&&Object.assign(i,this.generation_config),o!==null&&Object.assign(i,o),i}async generate(o,i=null,u=null,{inputs_attention_mask:d=null}={}){if(!this.can_generate){let _=`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 b=this.config.model_type,y=MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(b)??MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(b)??MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(b)??MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(b);throw y&&(_+=` Please use the following class instead: '${y[0]}'`),Error(_)}if(!(o instanceof Tensor)&&!isTypedArray(o)&&!Array.isArray(o))throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${o.constructor.name}".`);let a;if(this.config.is_encoder_decoder)a=0;else if(a=o instanceof Tensor?o.dims.at(-1):o.length,a===0)throw Error("Must supply a non-empty array of input token ids.");i=this._get_generation_config(i),u=u??new LogitsProcessorList,u=this._get_logits_processor(i,a,u);let h=i.eos_token_id;h!==null&&!Array.isArray(h)&&(h=[h]);let m=1;const c=m+(i.max_new_tokens??1/0),l=Number.isInteger(i.max_length)&&(i.max_new_tokens??null)===null;let n=Sampler.getSampler(i),e=this.getStartBeams(o,i,m,d);for(;e.some(g=>!g.done)&&m=i.max_length){_.done=!0,g.push(_);continue}let b=await this.runBeam(_);i.output_attentions&&this.addAttentionsToBeam(_,b),i.output_scores;let y=b.logits.slice(null,-1,null);u(_.output_token_ids,y);let T=n(y);for(let[w,v]of T){let E={..._};this.updateBeam(E,w),E.score+=v,h&&h.includes(w)&&(E.done=!0),g.push(E)}}++m,g=this.groupBeams(g).map(_=>_.sort((b,y)=>y.score-b.score).slice(0,i.num_beams)),e=g.flat(),i.callback_function&&i.callback_function(e)}const r=this.groupBeams(e),s=g=>r.map(_=>i.num_return_sequences>1?_.slice(0,i.num_return_sequences).map(b=>b[g]):[_[0][g]]).flat(),f=s("output_token_ids");if(i.return_dict_in_generate){const g=s("decoder_attentions"),_=s("cross_attentions");return{sequences:f,decoder_attentions:g,cross_attentions:_}}else return f}addAttentionsToBeam(o,i){if(this.config.is_encoder_decoder){if(!i.cross_attentions||i.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`.");o.cross_attentions||(o.cross_attentions=[]),o.cross_attentions.push(i.cross_attentions)}if(!i.decoder_attentions||i.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`.");o.decoder_attentions||(o.decoder_attentions=[]),o.decoder_attentions.push(i.decoder_attentions)}groupBeams(o){const i=Object.create(null);for(const u of o)i[u.id]===void 0?i[u.id]=[u]:i[u.id].push(u);return Object.values(i)}getPastKeyValues(o,i){const u=Object.create(null);for(const d in o)if(d.startsWith("present")){let a=d.replace("present","past_key_values");i&&d.includes("encoder")?u[a]=i[a]:u[a]=o[d]}return u}getAttentions(o){const i=Object.create(null);for(const u of["cross_attentions","decoder_attentions"]){const d=[];for(const a in o)if(a.startsWith(u)){const h=a.split(".").pop();d[h]=o[a]}i[u]=d}return i}addPastKeyValues(o,i){if(i)Object.assign(o,i);else if(this.config.is_encoder_decoder&&(this.add_encoder_pkv??!0)){let d=[1,this.num_encoder_heads,0,this.encoder_dim_kv],a=[1,this.num_decoder_heads,0,this.decoder_dim_kv];for(let h=0;h{let n=Array.from({length:this.config.decoder_layers},(_,b)=>cat(l.map(y=>y[b]),2)),e=stack(i.map(([_,b])=>u?n[_].slice(null,b,null,[0,u]):n[_].slice(null,b)));e=e.transpose(1,0,2,3);let[r,s]=std_mean(e,-2,0,!0),f=e.clone();for(let _=0;_e[b+1]-e[b]),f=mergeArrays([1],s).map(_=>!!_),g=[];for(let _=0;_u*d,1);t.input_labels=new Tensor("int64",new BigInt64Array(i).fill(1n),o)}return await sessionRun(this.prompt_encoder_mask_decoder,{input_points:t.input_points,input_labels:t.input_labels,image_embeddings:t.image_embeddings,image_positional_embeddings:t.image_positional_embeddings})}async _call(t){return new SamImageSegmentationOutput(await super._call(t))}}class SamImageSegmentationOutput extends ModelOutput{constructor({iou_scores:t,pred_masks:o}){super(),this.iou_scores=t,this.pred_masks=o}}class MarianPreTrainedModel extends PreTrainedModel{}class MarianModel extends MarianPreTrainedModel{}class MarianMTModel extends MarianPreTrainedModel{constructor(t,o,i,u){super(t,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(t,o,i,u){super(t,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(t){return new CausalLMOutput(await super._call(t))}}class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel{async _call(t){return new SequenceClassifierOutput(await super._call(t))}}class Wav2Vec2BertPreTrainedModel extends PreTrainedModel{}class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel{}class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel{async _call(t){return new CausalLMOutput(await super._call(t))}}class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel{async _call(t){return new SequenceClassifierOutput(await super._call(t))}}class HubertModel extends Wav2Vec2PreTrainedModel{}class HubertForCTC extends Wav2Vec2PreTrainedModel{async _call(t){return new CausalLMOutput(await super._call(t))}}class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel{async _call(t){return new SequenceClassifierOutput(await super._call(t))}}class WavLMPreTrainedModel extends PreTrainedModel{}class WavLMModel extends WavLMPreTrainedModel{}class WavLMForCTC extends WavLMPreTrainedModel{async _call(t){return new CausalLMOutput(await super._call(t))}}class WavLMForSequenceClassification extends WavLMPreTrainedModel{async _call(t){return new SequenceClassifierOutput(await super._call(t))}}class SpeechT5PreTrainedModel extends PreTrainedModel{}class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel{}class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel{constructor(t,o,i,u){super(t,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(t,o,{threshold:i=.5,minlenratio:u=0,maxlenratio:d=20,vocoder:a=null}={}){const h={input_ids:t},{encoder_outputs:m,encoder_attention_mask:c}=await encoderForward(this,h),l=m.dims[1]/this.config.reduction_factor,n=Math.floor(l*d),e=Math.floor(l*u),r=this.config.num_mel_bins;let s=[],f=null,g=null,_=0;for(;;){++_;const T=boolTensor(!!g);let w;g?w=g.output_sequence_out:w=new Tensor("float32",new Float32Array(r),[1,1,r]);let v={use_cache_branch:T,output_sequence:w,encoder_attention_mask:c,speaker_embeddings:o,encoder_hidden_states:m};this.addPastKeyValues(v,f),g=await sessionRun(this.decoder_merged_session,v),f=this.getPastKeyValues(g,f);const{prob:E,spectrum:P}=g;if(s.push(P),_>=e&&(Array.from(E.data).filter(x=>x>=i).length>0||_>=n))break}const b=cat(s),{waveform:y}=await sessionRun(a.session,{spectrogram:b});return{spectrogram:b,waveform:y}}}class SpeechT5HifiGan extends PreTrainedModel{constructor(){super(...arguments);K(this,"main_input_name","spectrogram")}}class TrOCRPreTrainedModel extends PreTrainedModel{constructor(t,o,i){super(t,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(t,o,i){super(t,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 FalconPreTrainedModel extends PreTrainedModel{constructor(t,o,i){super(t,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(t,o={}){return o.model_file_name??(o.model_file_name="text_model"),super.from_pretrained(t,o)}}class ClapAudioModelWithProjection extends ClapPreTrainedModel{static async from_pretrained(t,o={}){return o.model_file_name??(o.model_file_name="audio_model"),super.from_pretrained(t,o)}}class VitsPreTrainedModel extends PreTrainedModel{}class VitsModel extends VitsPreTrainedModel{async _call(t){return new VitsModelOutput(await super._call(t))}}class SegformerPreTrainedModel extends PreTrainedModel{}class SegformerForImageClassification extends SegformerPreTrainedModel{}class SegformerForSemanticSegmentation extends SegformerPreTrainedModel{}class PretrainedMixin{static async from_pretrained(t,{quantized:o=!0,progress_callback:i=null,config:u=null,cache_dir:d=null,local_files_only:a=!1,revision:h="main",model_file_name:m=null}={}){let c={quantized:o,progress_callback:i,config:u,cache_dir:d,local_files_only:a,revision:h,model_file_name:m};if(u=await AutoConfig.from_pretrained(t,c),c.config||(c.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 n=l.get(u.model_type);if(n)return await n[1].from_pretrained(t,c)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${u.model_type}", attempting to construct from base class.`),await PreTrainedModel.from_pretrained(t,c);throw Error(`Unsupported model type: ${u.model_type}`)}}K(PretrainedMixin,"MODEL_CLASS_MAPPINGS",null),K(PretrainedMixin,"BASE_IF_FAIL",!1);const MODEL_MAPPING_NAMES_ENCODER_ONLY=new Map([["bert",["BertModel",BertModel]],["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]],["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]],["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]],["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]],["falcon",["FalconForCausalLM",FalconForCausalLM]],["trocr",["TrOCRForCausalLM",TrOCRForCausalLM]]]),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_DOCUMENT_QUESTION_ANSWERING_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]]]),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]],["wavlm",["WavLMForCTC",WavLMForCTC]],["hubert",["HubertForCTC",HubertForCTC]]]),MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Wav2Vec2ForSequenceClassification]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Wav2Vec2BertForSequenceClassification]],["wavlm",["WavLMForSequenceClassification",WavLMForSequenceClassification]],["hubert",["HubertForSequenceClassification",HubertForSequenceClassification]],["audio-spectrogram-transformer",["ASTForAudioClassification",ASTForAudioClassification]]]),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]];for(const[p,t]of MODEL_CLASS_TYPE_MAPPING)for(const[o,i]of p.values())MODEL_TYPE_MAPPING.set(o,t),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[p,t,o]of CUSTOM_MAPPING)MODEL_TYPE_MAPPING.set(p,o),MODEL_CLASS_TO_NAME_MAPPING.set(t,p),MODEL_NAME_TO_CLASS_MAPPING.set(p,t);class AutoModel extends PretrainedMixin{}K(AutoModel,"MODEL_CLASS_MAPPINGS",MODEL_CLASS_TYPE_MAPPING.map(t=>t[0])),K(AutoModel,"BASE_IF_FAIL",!0);class AutoModelForSequenceClassification extends PretrainedMixin{}K(AutoModelForSequenceClassification,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]);class AutoModelForTokenClassification extends PretrainedMixin{}K(AutoModelForTokenClassification,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]);class AutoModelForSeq2SeqLM extends PretrainedMixin{}K(AutoModelForSeq2SeqLM,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]);class AutoModelForSpeechSeq2Seq extends PretrainedMixin{}K(AutoModelForSpeechSeq2Seq,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]);class AutoModelForTextToSpectrogram extends PretrainedMixin{}K(AutoModelForTextToSpectrogram,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]);class AutoModelForTextToWaveform extends PretrainedMixin{}K(AutoModelForTextToWaveform,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]);class AutoModelForCausalLM extends PretrainedMixin{}K(AutoModelForCausalLM,"MODEL_CLASS_MAPPINGS",[MODEL_WITH_LM_HEAD_MAPPING_NAMES]);class AutoModelForMaskedLM extends PretrainedMixin{}K(AutoModelForMaskedLM,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_MASKED_LM_MAPPING_NAMES]);class AutoModelForQuestionAnswering extends PretrainedMixin{}K(AutoModelForQuestionAnswering,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]);class AutoModelForVision2Seq extends PretrainedMixin{}K(AutoModelForVision2Seq,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]);class AutoModelForImageClassification extends PretrainedMixin{}K(AutoModelForImageClassification,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]);class AutoModelForImageSegmentation extends PretrainedMixin{}K(AutoModelForImageSegmentation,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]);class AutoModelForSemanticSegmentation extends PretrainedMixin{}K(AutoModelForSemanticSegmentation,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]);class AutoModelForObjectDetection extends PretrainedMixin{}K(AutoModelForObjectDetection,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]);class AutoModelForZeroShotObjectDetection extends PretrainedMixin{}K(AutoModelForZeroShotObjectDetection,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]);class AutoModelForCTC extends PretrainedMixin{}K(AutoModelForCTC,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_CTC_MAPPING_NAMES]);class AutoModelForAudioClassification extends PretrainedMixin{}K(AutoModelForAudioClassification,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]);class AutoModelForDocumentQuestionAnswering extends PretrainedMixin{}K(AutoModelForDocumentQuestionAnswering,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]);class AutoModelForImageToImage extends PretrainedMixin{}K(AutoModelForImageToImage,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]);class AutoModelForDepthEstimation extends PretrainedMixin{}K(AutoModelForDepthEstimation,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]);class Seq2SeqLMOutput extends ModelOutput{constructor({logits:t,past_key_values:o,encoder_outputs:i,decoder_attentions:u=null,cross_attentions:d=null}){super(),this.logits=t,this.past_key_values=o,this.encoder_outputs=i,this.decoder_attentions=u,this.cross_attentions=d}}class SequenceClassifierOutput extends ModelOutput{constructor({logits:t}){super(),this.logits=t}}class TokenClassifierOutput extends ModelOutput{constructor({logits:t}){super(),this.logits=t}}class MaskedLMOutput extends ModelOutput{constructor({logits:t}){super(),this.logits=t}}class QuestionAnsweringModelOutput extends ModelOutput{constructor({start_logits:t,end_logits:o}){super(),this.start_logits=t,this.end_logits=o}}class CausalLMOutput extends ModelOutput{constructor({logits:t}){super(),this.logits=t}}class ImageMattingOutput extends ModelOutput{constructor({alphas:t}){super(),this.alphas=t}}class VitsModelOutput extends ModelOutput{constructor({waveform:t,spectrogram:o}){super(),this.waveform=t,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=(p,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(p,t)},loadImageFunction=self.createImageBitmap,ImageDataClass=self.ImageData;else if(sharp)loadImageFunction=async p=>{const o=(await p.metadata()).channels;let{data:i,info:u}=await p.raw().toBuffer({resolveWithObject:!0});const d=new RawImage(new Uint8ClampedArray(i),u.width,u.height,u.channels);return o!==void 0&&o!==u.channels&&d.convert(o),d};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(t,o,i,u){this.data=t,this.width=o,this.height=i,this.channels=u}get size(){return[this.width,this.height]}static async read(t){if(t instanceof RawImage)return t;if(typeof t=="string"||t instanceof URL)return await this.fromURL(t);throw new Error(`Unsupported input type: ${typeof t}`)}static async fromURL(t){let o=await getFile(t);if(o.status!==200)throw new Error(`Unable to read image from "${t}" (${o.status} ${o.statusText})`);let i=await o.blob();return this.fromBlob(i)}static async fromBlob(t){if(BROWSER_ENV){let o=await loadImageFunction(t);const 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{let o=sharp(await t.arrayBuffer());return await loadImageFunction(o)}}static fromTensor(t,o="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(o==="CHW")t=t.transpose(1,2,0);else if(o!=="HWC")throw new Error(`Unsupported channel format: ${o}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new RawImage(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw new Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let o=0,i=0;o=0?m=i:l=-i,u>=0?c=u:n=-u,h.drawImage(a,m,c,t,o,l,n,t,o),new RawImage(h.getImageData(0,0,t,o).data,t,o,4).convert(d)}else{let d=this.toSharp();if(i>=0&&u>=0)d=d.extract({left:Math.floor(i),top:Math.floor(u),width:t,height:o});else if(i<=0&&u<=0){let a=Math.floor(-u),h=Math.floor(-i);d=d.extend({top:a,left:h,right:t-this.width-h,bottom:o-this.height-a})}else{let a=[0,0],h=0;u<0?(a[0]=Math.floor(-u),a[1]=o-this.height-a[0]):h=Math.floor(u);let m=[0,0],c=0;i<0?(m[0]=Math.floor(-i),m[1]=t-this.width-m[0]):c=Math.floor(i),d=d.extend({top:a[0],bottom:a[1],left:m[0],right:m[1]}).extract({left:c,top:h,width:t,height:o})}return await loadImageFunction(d)}}async toBlob(t="image/png",o=1){if(!BROWSER_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:o})}toCanvas(){if(!BROWSER_ENV)throw new Error("toCanvas() is only supported in browser environments.");let t=this.clone().rgba(),o=createCanvasFunction(t.width,t.height),i=new ImageDataClass(t.data,t.width,t.height);return o.getContext("2d").putImageData(i,0,0),o}_update(t,o,i,u=null){return this.data=t,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(t){if(this.channels===t)return this;switch(t){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(t){if(BROWSER_ENV){if(WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const o=t.split(".").pop().toLowerCase(),i=CONTENT_TYPE_MAP.get(o)??"image/png",u=await this.toBlob(i),d=URL.createObjectURL(u),a=document.createElement("a");a.href=d,a.download=t,a.click(),a.remove()}else{if(env$1.useFS)return await this.toSharp().toFile(t);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}})}}async function read_audio(p,t){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const o=await(await getFile(p)).arrayBuffer(),i=new AudioContext({sampleRate:t});typeof t>"u"&&console.warn(`No sampling rate provided, using default of ${i.sampleRate}Hz.`);const u=await i.decodeAudioData(o);let d;if(u.numberOfChannels===2){const a=Math.sqrt(2),h=u.getChannelData(0),m=u.getChannelData(1);d=new Float32Array(h.length);for(let c=0;c2595*Math.log10(1+p/700),kaldi:p=>1127*Math.log(1+p/700),slaney:(p,t=1e3,o=15,i=27/Math.log(6.4))=>p>=t?o+Math.log(p/t)*i:3*p/200};function hertz_to_mel(p,t="htk"){const o=HERTZ_TO_MEL_MAPPING[t];if(!o)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof p=="number"?o(p):p.map(i=>o(i))}const MEL_TO_HERTZ_MAPPING={htk:p=>700*(10**(p/2595)-1),kaldi:p=>700*(Math.exp(p/1127)-1),slaney:(p,t=1e3,o=15,i=Math.log(6.4)/27)=>p>=o?t*Math.exp(i*(p-o)):200*p/3};function mel_to_hertz(p,t="htk"){const o=MEL_TO_HERTZ_MAPPING[t];if(!o)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof p=="number"?o(p):p.map(i=>o(i))}function _create_triangular_filter_bank(p,t){const o=Float64Array.from({length:t.length-1},(a,h)=>t[h+1]-t[h]),i=Array.from({length:p.length},()=>new Array(t.length));for(let a=0;anew Array(p.length));for(let a=0;ap+i*d)}function mel_filter_bank(p,t,o,i,u,d=null,a="htk",h=!1){if(d!==null&&d!=="slaney")throw new Error('norm must be one of null or "slaney"');const m=hertz_to_mel(o,a),c=hertz_to_mel(i,a),l=linspace(m,c,t+2);let n=mel_to_hertz(l,a),e;if(h){const s=u/(p*2);e=hertz_to_mel(Float64Array.from({length:p},(f,g)=>g*s),a),n=l}else e=linspace(0,Math.floor(u/2),p);const r=_create_triangular_filter_bank(e,n);if(d!==null&&d==="slaney")for(let s=0;su)throw Error(`frame_length (${o}) may not be larger than fft_length (${u})`);if(T!==o)throw new Error(`Length of the window (${T}) must equal frame_length (${o})`);if(i<=0)throw new Error("hop_length must be greater than zero");if(a){if(h!=="reflect")throw new Error(`pad_mode="${h}" not implemented yet.`);const C=Math.floor((u-1)/2)+1;p=padReflect(p,C,C)}const w=Math.floor(1+Math.floor((p.length-o)/i)),v=m?Math.floor(u/2)+1:u;let E=w,P=w;_!==null&&(_>w?b&&(P=_):P=E=_);const x=new FFT(u),O=new Float64Array(u),$=new Float64Array(x.outputBufferSize),k=new Array(E);for(let C=0;C=1;--G)O[G]-=c*O[G-1];O[0]*=1-c}for(let G=0;GMath.pow(h,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(o&&(a=a.subarray(0,p)),i===null)return a;if(p>i)throw new Error(`Length of the window (${p}) may not be larger than frame_length (${i})`);return a}function center_to_corners_format([p,t,o,i]){return[p-o/2,t-i/2,p+o/2,t+i/2]}function post_process_object_detection(p,t=.5,o=null,i=!1){const u=p.logits,d=p.pred_boxes,[a,h,m]=u.dims;if(o!==null&&o.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let l=0;lt&&_.push(y)}else{let y=max(g.data)[1];if(y===m-1)continue;_.push(y),b=softmax(g.data)}for(const y of _){let T=s[f].data;T=center_to_corners_format(T),n!==null&&(T=T.map((w,v)=>w*n[(v+1)%2])),e.boxes.push(T),e.classes.push(y),e.scores.push(b[y])}}c.push(e)}return c}function validate_audio_inputs(p,t){var o;if(!(p instanceof Float32Array||p instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${((o=p==null?void 0:p.constructor)==null?void 0:o.name)??typeof p} 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(p,t,o=0,i=null){let u=Math.round(p/t)*t;return i!==null&&u>i&&(u=Math.floor(p/t)*t),ud?c=Math.floor(d*m/u):d>u&&(m=Math.floor(u*c/d)),await t.resize(c,m,{resample:i}))}async crop_margin(t,o=200){const i=t.clone().grayscale(),u=min(i.data)[0],a=max(i.data)[0]-u;if(a===0)return t;const h=o/255;let m=i.width,c=i.height,l=0,n=0;for(let e=0;ethis.preprocess(d)));return{pixel_values:stack(i.map(d=>d.pixel_values),0),original_sizes:i.map(d=>d.original_size),reshaped_input_sizes:i.map(d=>d.reshaped_input_size)}}}class SegformerFeatureExtractor extends ImageFeatureExtractor{post_process_semantic_segmentation(t,o=null){const i=t.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 d=[];for(let a=0;ae[b]&&(e[b]=_[b],n.data[b]=g)}const r=new Array(m.dims[0]),s=n.data;for(let g=0;gg!==void 0);d.push({segmentation:n,labels:f})}return d}}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(t){super(t),this.crop_pct=this.config.crop_pct??224/256}async resize(t){var i;const o=(i=this.size)==null?void 0:i.shortest_edge;if(o===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(o<384){const u=Math.floor(o/this.crop_pct),[d,a]=this.get_resize_output_image_size(t,{shortest_edge:u});t=await t.resize(d,a,{resample:this.resample}),t=await t.center_crop(o,o)}else t=await t.resize(o,o,{resample:this.resample});return t}}class ConvNextImageProcessor extends ConvNextFeatureExtractor{}class ViTFeatureExtractor extends ImageFeatureExtractor{}class ViTImageProcessor extends ImageFeatureExtractor{}class MobileViTFeatureExtractor extends ImageFeatureExtractor{}class OwlViTFeatureExtractor extends ImageFeatureExtractor{post_process_object_detection(...t){return post_process_object_detection(...t)}}class DeiTFeatureExtractor extends ImageFeatureExtractor{}class BeitFeatureExtractor extends ImageFeatureExtractor{}class DonutFeatureExtractor extends ImageFeatureExtractor{pad_image(t,o,i,u={}){const[d,a,h]=o;let m=this.image_mean;Array.isArray(this.image_mean)||(m=new Array(h).fill(m));let c=this.image_std;Array.isArray(c)||(c=new Array(h).fill(m));const l=m.map((n,e)=>-n/this.image_std[e]);return super.pad_image(t,o,i,{center:!0,constant_values:l,...u})}}class NougatImageProcessor extends DonutFeatureExtractor{}class DetrFeatureExtractor extends ImageFeatureExtractor{async _call(t){const o=await super._call(t),i=[o.pixel_values.dims[0],64,64],u=new Tensor("int64",new BigInt64Array(i.reduce((d,a)=>d*a)).fill(1n),i);return{...o,pixel_mask:u}}post_process_object_detection(...t){return post_process_object_detection(...t)}remove_low_and_no_objects(t,o,i,u){let d=[],a=[],h=[];for(let m=0;mi&&(d.push(l),a.push(r),h.push(n))}return[d,a,h]}check_segment_validity(t,o,i,u=.5,d=.8){let a=[],h=0,m=0;for(let l=0;l=u&&++m;let c=h>0&&m>0;return c&&(c=h/m>d),[c,a]}compute_segments(t,o,i,u,d,a=null,h=null){let[m,c]=h??t[0].dims,l=new Tensor("int32",new Int32Array(m*c),[m,c]),n=[];if(h!==null)for(let f=0;fr[_]&&(e[_]=f,r[_]=t[f].data[_])}let s=0;for(let f=0;fu!==o.dims[d]))throw Error(`The first ${i.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Tensor("int64",t.flat(1/0).map(BigInt),i)}async _call(t,o=null,i=null){const u=await super._call(t);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(t,o,i,{mask_threshold:u=0,binarize:d=!0,pad_size:a=null}={}){const h=[];a=a??this.pad_size;const m=[a.height,a.width];for(let c=0;cu&&(_[b]=1);g=new Tensor("bool",_,g.dims)}r.push(g)}h.push(stack(r))}return h}}class Swin2SRImageProcessor extends ImageFeatureExtractor{pad_image(t,o,i,u={}){const[d,a,h]=o;return super.pad_image(t,o,{width:d+(i-d%i)%i,height:a+(i-a%i)%i},{mode:"symmetric",center:!1,constant_values:-1,...u})}}class VitMatteImageProcessor extends ImageFeatureExtractor{async _call(t,o){Array.isArray(t)||(t=[t]),Array.isArray(o)||(o=[o]);const i=await Promise.all(t.map(a=>this.preprocess(a))),u=await Promise.all(o.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:stack(i.map((a,h)=>cat([a.pixel_values,u[h].pixel_values],0)),0),original_sizes:i.map(a=>a.original_size),reshaped_input_sizes:i.map(a=>a.reshaped_input_size)}}}class WhisperFeatureExtractor extends FeatureExtractor{constructor(t){var o;super(t),(o=this.config).mel_filters??(o.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(t){const{data:o,dims:i}=spectrogram(t,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 d=0;dthis.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=t.slice(0,this.config.n_samples)):(o=new Float32Array(this.config.n_samples),o.set(t));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(t){const i=t.reduce((d,a)=>d+a,0)/t.length,u=t.reduce((d,a)=>d+(a-i)**2,0)/t.length;return t.map(d=>(d-i)/Math.sqrt(u+1e-7))}async _call(t){validate_audio_inputs(t,"Wav2Vec2FeatureExtractor"),t instanceof Float64Array&&(t=new Float32Array(t));let o=t;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(t){super(t);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;ui*32768),spectrogram(t,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.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(t,{padding:o=!0,pad_to_multiple_of:i=2,do_normalize_per_mel_bins:u=!0,return_attention_mask:d=!0}={}){validate_audio_inputs(t,"SeamlessM4TFeatureExtractor");let a=this._extract_fbank_features(t,this.config.max_length);if(u){const[s,f]=a.dims;for(let g=0;g0){const _=new Float32Array(f*(s+g));_.set(a.data),_.fill(this.config.padding_value,a.data.length);const b=s+g;a={data:_,dims:[b,f]},d&&(h=new Tensor("int64",new BigInt64Array(b),[1,b]),h.data.fill(1n,0,s))}}const[m,c]=a.dims,l=this.config.stride;if(m%l!==0)throw new Error(`The number of frames (${m}) must be a multiple of the stride (${l}).`);const e=new Tensor("float32",a.data,a.dims).view(1,Math.floor(m/l),c*l),r={input_features:e};if(d){const s=e.dims[1],f=new Tensor("int64",new BigInt64Array(s),[1,s]);if(h)for(let g=1,_=0;g0)if(i==="rand_trunc"){a=!0;const m=Math.floor(Math.random()*(h+1));t=t.subarray(m,m+o),d=this._extract_fbank_features(t,this.mel_filters_slaney,this.config.nb_max_samples),d.dims=[1,...d.dims]}else throw new Error(`Truncation strategy "${i}" not implemented`);else{if(h<0){let m=new Float64Array(o);if(m.set(t),u==="repeat")for(let c=t.length;cRawImage.read(t)))}async function prepareAudios(p,t){return Array.isArray(p)||(p=[p]),await Promise.all(p.map(o=>typeof o=="string"||o instanceof URL?read_audio(o,t):o instanceof Float64Array?new Float32Array(o):o))}function get_bounding_box(p,t){t&&(p=p.map(a=>a|0));const[o,i,u,d]=p;return{xmin:o,ymin:i,xmax:u,ymax:d}}class Pipeline extends Callable{constructor({task:t,model:o,tokenizer:i=null,processor:u=null}){super(),this.task=t,this.model=o,this.tokenizer=i,this.processor=u}async dispose(){await this.model.dispose()}}class TextClassificationPipeline extends Pipeline{constructor(t){super(t)}async _call(t,{topk:o=1}={}){const i=this.tokenizer(t,{padding:!0,truncation:!0}),u=await this.model(i),d=this.model.config.problem_type==="multi_label_classification"?m=>m.sigmoid().data:m=>softmax(m.data),a=this.model.config.id2label,h=[];for(const m of u.logits){const c=d(m),n=getTopItems(c,o).map(e=>({label:a[e[0]],score:e[1]}));o===1?h.push(...n):h.push(n)}return Array.isArray(t)||o===1?h:h[0]}}class TokenClassificationPipeline extends Pipeline{constructor(t){super(t)}async _call(t,{ignore_labels:o=["O"]}={}){const i=Array.isArray(t),u=this.tokenizer(i?t:[t],{padding:!0,truncation:!0}),a=(await this.model(u)).logits,h=this.model.config.id2label,m=[];for(let c=0;c[r,s]).filter(r=>r[1]>c),n=Array.from(softmax(d.end_logits[h].data)).map((r,s)=>[r,s]).filter(r=>r[1]>c),e=product(l,n).filter(r=>r[0][1]<=r[1][1]).map(r=>[r[0][1],r[1][1],r[0][0]*r[1][0]]).sort((r,s)=>s[2]-r[2]);for(let r=0;r{const r=[...h];return r[m]=e[0],{score:e[1],token:e[0],token_str:this.tokenizer.model.vocab[e[0]],sequence:this.tokenizer.decode(r,{skip_special_tokens:!0})}}))}return Array.isArray(t)?d:d[0]}}class Text2TextGenerationPipeline extends Pipeline{constructor(o){super(o);K(this,"_key","generated_text")}async _call(o,i={}){Array.isArray(o)||(o=[o]),this.model.config.prefix&&(o=o.map(c=>this.model.config.prefix+c));const u=this.model.config.task_specific_params;u&&u[this.task]&&u[this.task].prefix&&(o=o.map(c=>u[this.task].prefix+c));const d=this.tokenizer,a={padding:!0,truncation:!0};let h;this instanceof TranslationPipeline&&"_build_translation_inputs"in d?h=d._build_translation_inputs(o,a,i).input_ids:h=d(o,a).input_ids;const m=await this.model.generate(h,i);return d.batch_decode(m,{skip_special_tokens:!0}).map(c=>({[this._key]:c}))}}class SummarizationPipeline extends Text2TextGenerationPipeline{constructor(o){super(o);K(this,"_key","summary_text")}}class TranslationPipeline extends Text2TextGenerationPipeline{constructor(o){super(o);K(this,"_key","translation_text")}}class TextGenerationPipeline extends Pipeline{constructor(t){super(t)}async _call(t,o={}){const i=Array.isArray(t);i||(t=[t]);const u=o.add_special_tokens??!1;this.tokenizer.padding_side="left";const{input_ids:d,attention_mask:a}=this.tokenizer(t,{add_special_tokens:u,padding:!0,truncation:!0}),h=await this.model.generate(d,o,null,{inputs_attention_mask:a}),m=this.tokenizer.batch_decode(h,{skip_special_tokens:!0}),c=Array.from({length:t.length},l=>[]);for(let l=0;l[o.toLowerCase(),i])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(t,o,{hypothesis_template:i="This example is {}.",multi_label:u=!1}={}){const d=Array.isArray(t);d||(t=[t]),Array.isArray(o)||(o=[o]);const a=o.map(c=>i.replace("{}",c)),h=u||o.length===1,m=[];for(const c of t){const l=[];for(const r of a){const s=this.tokenizer(c,{text_pair:r,padding:!0,truncation:!0}),f=await this.model(s);h?l.push([f.logits.data[this.contradiction_id],f.logits.data[this.entailment_id]]):l.push(f.logits.data[this.entailment_id])}const e=(h?l.map(r=>softmax(r)[1]):softmax(l)).map((r,s)=>[r,s]).sort((r,s)=>s[0]-r[0]);m.push({sequence:c,labels:e.map(r=>o[r[1]]),scores:e.map(r=>r[0])})}return d?m:m[0]}}class FeatureExtractionPipeline extends Pipeline{constructor(t){super(t)}async _call(t,{pooling:o="none",normalize:i=!1}={}){const u=this.tokenizer(t,{padding:!0,truncation:!0}),d=await this.model(u);let a=d.last_hidden_state??d.logits;if(o!=="none")if(o==="mean")a=mean_pooling(a,u.attention_mask);else if(o==="cls")a=a.slice(null,0);else throw Error(`Pooling method '${o}' not supported.`);return i&&(a=a.normalize(2,-1)),a}}class AudioClassificationPipeline extends Pipeline{constructor(t){super(t)}async _call(t,{topk:o=null}={}){const i=!Array.isArray(t),u=this.processor.feature_extractor.config.sampling_rate,d=await prepareAudios(t,u),a=this.model.config.id2label,h=[];for(const m of d){const c=await this.processor(m),n=(await this.model(c)).logits[0],r=getTopItems(softmax(n.data),o).map(s=>({label:a[s[0]],score:s[1]}));o===1?h.push(...r):h.push(r)}return!i||o===1?h:h[0]}}class ZeroShotAudioClassificationPipeline extends Pipeline{constructor(t){super(t)}async _call(t,o,{hypothesis_template:i="This is a sound of {}."}={}){const u=!Array.isArray(t);u&&(t=[t]);const d=o.map(l=>i.replace("{}",l)),a=this.tokenizer(d,{padding:!0,truncation:!0}),h=this.processor.feature_extractor.config.sampling_rate,m=await prepareAudios(t,h),c=[];for(const l of m){const n=await this.processor(l),e=await this.model({...a,...n}),r=softmax(e.logits_per_audio.data);c.push([...r].map((s,f)=>({score:s,label:o[f]})))}return u?c[0]:c}}class AutomaticSpeechRecognitionPipeline extends Pipeline{constructor(t){super(t)}async _call(t,o={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(t,o);case"wav2vec2":case"wav2vec2-bert":case"hubert":return this._call_wav2vec2(t,o);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(t,o={}){o.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),o.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const i=!Array.isArray(t);i&&(t=[t]);const u=this.processor.feature_extractor.config.sampling_rate,d=await prepareAudios(t,u),a=[];for(const h of d){const m=await this.processor(h),l=(await this.model(m)).logits[0],n=[];for(const r of l)n.push(max(r.data)[1]);const e=this.tokenizer.decode(n);a.push({text:e})}return i?a[0]:a}async _call_whisper(t,o={}){const i=o.return_timestamps??!1,u=o.chunk_length_s??0,d=o.chunk_callback??null,a=o.force_full_sequences??!1;let h=o.stride_length_s??null;i==="word"&&(o.return_token_timestamps=!0);const m=pop(o,"language",null),c=pop(o,"task",null);if(m||c||i){if(o.forced_decoder_ids)throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.");const g=this.tokenizer.get_decoder_prompt_ids({language:m,task:c,no_timestamps:!i});g.length>0&&(o.forced_decoder_ids=g)}const l=!Array.isArray(t);l&&(t=[t]);const n=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,e=this.processor.feature_extractor.config.hop_length,r=this.processor.feature_extractor.config.sampling_rate,s=await prepareAudios(t,r),f=[];for(const g of s){let _=[];if(u>0){if(h===null)h=u/6;else if(u<=h)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const T=r*u,w=r*h,v=T-2*w;let E=0;for(;E=g.length;_.push({stride:[P.length,O?0:w,$?0:w],input_features:x.input_features,is_last:$}),E+=v}}else _=[{stride:[g.length,0,0],input_features:(await this.processor(g)).input_features,is_last:!0}];for(const T of _){o.num_frames=Math.floor(T.stride[0]/e);const w=await this.model.generate(T.input_features,o);i==="word"?(T.tokens=w.sequences[0],T.token_timestamps=w.token_timestamps.tolist()[0].map(v=>round(v,2))):T.tokens=w[0],T.stride=T.stride.map(v=>v/r),d!==null&&d(T)}const[b,y]=this.tokenizer._decode_asr(_,{time_precision:n,return_timestamps:i,force_full_sequences:a});f.push({text:b,...y})}return l?f[0]:f}}class ImageToTextPipeline extends Pipeline{constructor(t){super(t)}async _call(t,o={}){const i=Array.isArray(t),u=await prepareImages(t),{pixel_values:d}=await this.processor(u),a=[];for(const h of d){h.dims=[1,...h.dims];const m=await this.model.generate(h,o),c=this.tokenizer.batch_decode(m,{skip_special_tokens:!0}).map(l=>({generated_text:l.trim()}));a.push(c)}return i?a:a[0]}}class ImageClassificationPipeline extends Pipeline{constructor(t){super(t)}async _call(t,{topk:o=1}={}){const i=Array.isArray(t),u=await prepareImages(t),{pixel_values:d}=await this.processor(u),a=await this.model({pixel_values:d}),h=this.model.config.id2label,m=[];for(const c of a.logits){const n=getTopItems(softmax(c.data),o).map(e=>({label:h[e[0]],score:e[1]}));o===1?m.push(...n):m.push(n)}return i||o===1?m:m[0]}}class ImageSegmentationPipeline extends Pipeline{constructor(t){super(t),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(t,{threshold:o=.5,mask_threshold:i=.5,overlap_mask_area_threshold:u=.8,label_ids_to_fuse:d=null,target_sizes:a=null,subtask:h=null}={}){if(Array.isArray(t)&&t.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const c=await prepareImages(t),l=c.map(_=>[_.height,_.width]),{pixel_values:n,pixel_mask:e}=await this.processor(c),r=await this.model({pixel_values:n,pixel_mask:e});let s=null;if(h!==null)s=this.subtasks_mapping[h];else for(let[_,b]of Object.entries(this.subtasks_mapping))if(b in this.processor.feature_extractor){s=this.processor.feature_extractor[b].bind(this.processor.feature_extractor),h=_;break}const f=this.model.config.id2label,g=[];if(h==="panoptic"||h==="instance"){const _=s(r,o,i,u,d,a??l)[0],b=_.segmentation;for(const y of _.segments_info){const T=new Uint8ClampedArray(b.data.length);for(let v=0;vi.replace("{}",e)),h=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:m}=await this.processor(d),c=await this.model({...h,pixel_values:m}),l=this.model.config.model_type==="siglip"?e=>e.sigmoid().data:e=>softmax(e.data),n=[];for(const e of c.logits_per_image){const s=[...l(e)].map((f,g)=>({score:f,label:o[g]}));s.sort((f,g)=>g.score-f.score),n.push(s)}return u?n:n[0]}}class ObjectDetectionPipeline extends Pipeline{constructor(t){super(t)}async _call(t,{threshold:o=.9,percentage:i=!1}={}){const u=Array.isArray(t);if(u&&t.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const d=await prepareImages(t),a=i?null:d.map(r=>[r.height,r.width]),{pixel_values:h,pixel_mask:m}=await this.processor(d),c=await this.model({pixel_values:h,pixel_mask:m}),l=this.processor.feature_extractor.post_process_object_detection(c,o,a),n=this.model.config.id2label,e=l.map(r=>r.boxes.map((s,f)=>({score:r.scores[f],label:n[r.classes[f]],box:get_bounding_box(s,!i)})));return u?e:e[0]}}class ZeroShotObjectDetectionPipeline extends Pipeline{constructor(t){super(t)}async _call(t,o,{threshold:i=.1,topk:u=null,percentage:d=!1}={}){const a=Array.isArray(t),h=await prepareImages(t),m=this.tokenizer(o,{padding:!0,truncation:!0}),c=await this.processor(h),l=[];for(let n=0;n({score:g.scores[y],label:o[g.classes[y]],box:get_bounding_box(b,!d)})).sort((b,y)=>y.score-b.score);u!==null&&(_=_.slice(0,u)),l.push(_)}return a?l:l[0]}}class DocumentQuestionAnsweringPipeline extends Pipeline{constructor(t){super(t)}async _call(t,o,i={}){const u=(await prepareImages(t))[0],{pixel_values:d}=await this.processor(u),a=`${o}`,h=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,m=await this.model.generate(d,{...i,decoder_input_ids:h,max_length:this.model.config.decoder.max_position_embeddings}),l=this.tokenizer.batch_decode(m)[0].match(/(.*?)<\/s_answer>/);let n=null;return l&&l.length>=2&&(n=l[1].trim()),[{answer:n}]}}class TextToAudioPipeline extends Pipeline{constructor(o){super(o);K(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=o.vocoder??null}async _call(o,{speaker_embeddings:i=null}={}){return this.processor?this._call_text_to_spectrogram(o,{speaker_embeddings:i}):this._call_text_to_waveform(o)}async _call_text_to_waveform(o){const i=this.tokenizer(o,{padding:!0,truncation:!0}),{waveform:u}=await this.model(i),d=this.model.config.sampling_rate;return{audio:u.data,sampling_rate:d}}async _call_text_to_spectrogram(o,{speaker_embeddings:i}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{quantized:!1})),(typeof i=="string"||i instanceof URL)&&(i=new Float32Array(await(await fetch(i)).arrayBuffer())),i instanceof Float32Array)i=new Tensor("float32",i,[1,i.length]);else if(!(i instanceof Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:u}=this.tokenizer(o,{padding:!0,truncation:!0}),{waveform:d}=await this.model.generate_speech(u,i,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return{audio:d.data,sampling_rate:a}}}class ImageToImagePipeline extends Pipeline{constructor(t){super(t)}async _call(t){const o=await prepareImages(t),i=await this.processor(o),u=await this.model(i),d=[];for(const a of u.reconstruction){const h=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");d.push(RawImage.fromTensor(h))}return d.length>1?d:d[0]}}class DepthEstimationPipeline extends Pipeline{constructor(t){super(t)}async _call(t){const o=await prepareImages(t),i=await this.processor(o),{predicted_depth:u}=await this.model(i),d=[];for(let a=0;a1?d:d[0]}}const SUPPORTED_TASKS=Object.freeze({"text-classification":{tokenizer:AutoTokenizer,pipeline:TextClassificationPipeline,model:AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:AutoTokenizer,pipeline:TokenClassificationPipeline,model:AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:AutoTokenizer,pipeline:QuestionAnsweringPipeline,model:AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:AutoTokenizer,pipeline:FillMaskPipeline,model:AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:AutoTokenizer,pipeline:SummarizationPipeline,model:AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:AutoTokenizer,pipeline:TranslationPipeline,model:AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:AutoTokenizer,pipeline:Text2TextGenerationPipeline,model:AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:AutoTokenizer,pipeline:TextGenerationPipeline,model:AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:AutoTokenizer,pipeline:ZeroShotClassificationPipeline,model:AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:AudioClassificationPipeline,model:AutoModelForAudioClassification,processor:AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:AutoTokenizer,pipeline:ZeroShotAudioClassificationPipeline,model:AutoModel,processor:AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:AutoTokenizer,pipeline:AutomaticSpeechRecognitionPipeline,model:[AutoModelForSpeechSeq2Seq,AutoModelForCTC],processor:AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:AutoTokenizer,pipeline:TextToAudioPipeline,model:[AutoModelForTextToWaveform,AutoModelForTextToSpectrogram],processor:[AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:AutoTokenizer,pipeline:ImageToTextPipeline,model:AutoModelForVision2Seq,processor:AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ImageClassificationPipeline,model:AutoModelForImageClassification,processor:AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ImageSegmentationPipeline,model:[AutoModelForImageSegmentation,AutoModelForSemanticSegmentation],processor:AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:AutoTokenizer,pipeline:ZeroShotImageClassificationPipeline,model:AutoModel,processor:AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ObjectDetectionPipeline,model:AutoModelForObjectDetection,processor:AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:AutoTokenizer,pipeline:ZeroShotObjectDetectionPipeline,model:AutoModelForZeroShotObjectDetection,processor:AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:AutoTokenizer,pipeline:DocumentQuestionAnsweringPipeline,model:AutoModelForDocumentQuestionAnswering,processor:AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ImageToImagePipeline,model:AutoModelForImageToImage,processor:AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:DepthEstimationPipeline,model:AutoModelForDepthEstimation,processor:AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:AutoTokenizer,pipeline:FeatureExtractionPipeline,model:AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"}}),TASK_ALIASES=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function pipeline(p,t=null,{quantized:o=!0,progress_callback:i=null,config:u=null,cache_dir:d=null,local_files_only:a=!1,revision:h="main"}={}){p=TASK_ALIASES[p]??p;const m=SUPPORTED_TASKS[p.split("_",1)[0]];if(!m)throw Error(`Unsupported pipeline: ${p}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`);t||(t=m.default.model,console.log(`No model specified. Using default model: "${t}".`));const c={quantized:o,progress_callback:i,config:u,cache_dir:d,local_files_only:a,revision:h},l=new Map([["tokenizer",m.tokenizer],["model",m.model],["processor",m.processor]]),n=await loadItems(l,t,c);n.task=p,dispatchCallback(i,{status:"ready",task:p,model:t});const e=m.pipeline;return new e(n)}async function loadItems(p,t,o){const i=Object.create(null),u=[];for(let[d,a]of p.entries()){if(!a)continue;let h;Array.isArray(a)?h=new Promise(async(m,c)=>{let l;for(let n of a){if(n===null){m(null);return}try{m(await n.from_pretrained(t,o));return}catch(e){l=e}}c(l)}):h=a.from_pretrained(t,o),i[d]=h,u.push(h)}await Promise.all(u);for(let[d,a]of Object.entries(i))i[d]=await a;return i}env$1.allowLocalModels=!1;class MyFeatureExtractionPipeline{static async getInstance(t=null){return this.instance===null&&(this.instance=pipeline(this.task,this.model,{quantized:!0,progress_callback:t})),this.instance}}K(MyFeatureExtractionPipeline,"task","feature-extraction"),K(MyFeatureExtractionPipeline,"model","nomic-ai/nomic-embed-text-v1.5"),K(MyFeatureExtractionPipeline,"instance",null);const SEARCH_PREFIX="search_query: ",DOCUMENT_PREFIX="search_document: ";self.addEventListener("message",async p=>{const t=await MyFeatureExtractionPipeline.getInstance(a=>{self.postMessage(a)}),{source:o,text:i}=p.data,u=[SEARCH_PREFIX+o,...i.trim().split(` `).map(a=>DOCUMENT_PREFIX+a)],d=await t(u,{pooling:"mean",normalize:!0});self.postMessage({status:"complete",embeddings:d.tolist()})})})();