diff --git "a/assets/worker-8c8208dc.js" "b/assets/worker-8c8208dc.js" new file mode 100644--- /dev/null +++ "b/assets/worker-8c8208dc.js" @@ -0,0 +1,1790 @@ +var fn=Object.defineProperty;var gn=(nt,_,n)=>_ in nt?fn(nt,_,{enumerable:!0,configurable:!0,writable:!0,value:n}):nt[_]=n;var le=(nt,_,n)=>(gn(nt,typeof _!="symbol"?_+"":_,n),n);(function(){var nt;"use strict";function _mergeNamespaces(_,n){return n.forEach(function(o){o&&typeof o!="string"&&!Array.isArray(o)&&Object.keys(o).forEach(function(u){if(u!=="default"&&!(u in _)){var l=Object.getOwnPropertyDescriptor(o,u);Object.defineProperty(_,u,l.get?l:{enumerable:!0,get:function(){return o[u]}})}})}),Object.freeze(_)}function dispatchCallback(_,n){_!==null&&_(n)}function reverseDictionary(_){return Object.fromEntries(Object.entries(_).map(([n,o])=>[o,n]))}function escapeRegExp(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Callable=class{constructor(){let _=function(...n){return _._call(...n)};return Object.setPrototypeOf(_,new.target.prototype)}_call(..._){throw Error("Must implement _call method in subclass")}};function isString(_){return typeof _=="string"||_ instanceof String}function isTypedArray(_){var n,o,u;return((u=(o=(n=_==null?void 0:_.prototype)==null?void 0:n.__proto__)==null?void 0:o.constructor)==null?void 0:u.name)==="TypedArray"}function isIntegralNumber(_){return Number.isInteger(_)||typeof _=="bigint"}function exists(_){return _!=null}function calculateDimensions(_){const n=[];let o=_;for(;Array.isArray(o);)n.push(o.length),o=o[0];return n}function pop(_,n,o=void 0){const u=_[n];if(u!==void 0)return delete _[n],u;if(o===void 0)throw Error(`Key ${n} does not exist in object.`);return o}function mergeArrays(..._){return Array.prototype.concat.apply([],_)}function product(..._){return _.reduce((n,o)=>n.flatMap(u=>o.map(l=>[u,l])))}var sharp={},ONNX_NODE=Object.freeze({__proto__:null,default:sharp});function getDefaultExportFromCjs(_){return _&&_.__esModule&&Object.prototype.hasOwnProperty.call(_,"default")?_.default:_}function getAugmentedNamespace(_){if(_.__esModule)return _;var n=_.default;if(typeof n=="function"){var o=function u(){if(this instanceof u){var l=[null];l.push.apply(l,arguments);var d=Function.bind.apply(n,l);return new d}return n.apply(this,arguments)};o.prototype=n.prototype}else o={};return Object.defineProperty(o,"__esModule",{value:!0}),Object.keys(_).forEach(function(u){var l=Object.getOwnPropertyDescriptor(_,u);Object.defineProperty(o,u,l.get?l:{enumerable:!0,get:function(){return _[u]}})}),o}var ortWeb_min$1={exports:{}};const backends={},backendsSortedByPriority=[],registerBackend=(_,n,o)=>{if(n&&typeof n.init=="function"&&typeof n.createSessionHandler=="function"){const u=backends[_];if(u===void 0)backends[_]={backend:n,priority:o};else{if(u.priority>o)return;if(u.priority===o&&u.backend!==n)throw new Error(`cannot register backend "${_}" using priority ${o}`)}if(o>=0){const l=backendsSortedByPriority.indexOf(_);l!==-1&&backendsSortedByPriority.splice(l,1);for(let d=0;d{const n=_.length===0?backendsSortedByPriority:_,o=[];for(const u of n){const l=backends[u];if(l){if(l.initialized)return l.backend;if(l.aborted)continue;const d=!!l.initPromise;try{return d||(l.initPromise=l.backend.init()),await l.initPromise,l.initialized=!0,l.backend}catch(s){d||o.push({name:u,err:s}),l.aborted=!0}finally{delete l.initPromise}}}throw new Error(`no available backend found. ERR: ${o.map(u=>`[${u.name}] ${u.err}`).join(", ")}`)};class EnvImpl{constructor(){this.wasm={},this.webgl={},this.logLevelInternal="warning"}set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);this.logLevelInternal=n}}get logLevel(){return this.logLevelInternal}}const env$1=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=_=>{let n=1;for(let o=0;o<_.length;o++){const u=_[o];if(typeof u!="number"||!Number.isSafeInteger(u))throw new TypeError(`dims[${o}] must be an integer, got: ${u}`);if(u<0)throw new RangeError(`dims[${o}] must be a non-negative integer, got: ${u}`);n*=u}return n};let Tensor$2=class ut{constructor(n,o,u){let l,d,s;if(typeof n=="string")if(l=n,s=u,n==="string"){if(!Array.isArray(o))throw new TypeError("A string tensor's data must be a string array.");d=o}else{const f=NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(n);if(f===void 0)throw new TypeError(`Unsupported tensor type: ${n}.`);if(Array.isArray(o))d=f.from(o);else if(o instanceof f)d=o;else throw new TypeError(`A ${l} tensor's data must be type of ${f}`)}else if(s=o,Array.isArray(n)){if(n.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const f=typeof n[0];if(f==="string")l="string",d=n;else if(f==="boolean")l="bool",d=Uint8Array.from(n);else throw new TypeError(`Invalid element type of data array: ${f}.`)}else{const f=NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(n.constructor);if(f===void 0)throw new TypeError(`Unsupported type for tensor data: ${n.constructor}.`);l=f,d=n}if(s===void 0)s=[d.length];else if(!Array.isArray(s))throw new TypeError("A tensor's dims must be a number array");const p=calculateSize(s);if(p!==d.length)throw new Error(`Tensor's size(${p}) does not match data length(${d.length}).`);this.dims=s,this.type=l,this.data=d,this.size=p}static bufferToTensor(n,o){if(n===void 0)throw new Error("Image buffer must be defined");if(o.height===void 0||o.width===void 0)throw new Error("Image height and width must be defined");const{height:u,width:l}=o,d=o.norm;let s,p;d===void 0||d.mean===void 0?s=255:s=d.mean,d===void 0||d.bias===void 0?p=0:p=d.bias;const f=o.bitmapFormat!==void 0?o.bitmapFormat:"RGBA",c=o.tensorFormat!==void 0&&o.tensorFormat!==void 0?o.tensorFormat:"RGB",a=u*l,t=c==="RGBA"?new Float32Array(a*4):new Float32Array(a*3);let e=4,r=0,i=1,h=2,g=3,m=0,b=a,y=a*2,w=-1;f==="RGB"&&(e=3,r=0,i=1,h=2,g=-1),c==="RGBA"?w=a*3:c==="RBG"?(m=0,y=a,b=a*2):c==="BGR"&&(y=0,b=a,m=a*2);for(let S=0;S{const t=document.createElement("canvas"),e=t.getContext("2d");if(!n||!e)return a();const r=new Image;r.crossOrigin="Anonymous",r.src=n,r.onload=()=>{t.width=r.width,t.height=r.height,e.drawImage(r,0,0,t.width,t.height);const i=e.getImageData(0,0,t.width,t.height);if(o!==void 0){if(o.height!==void 0&&o.height!==t.height)throw new Error("Image input config height doesn't match ImageBitmap height");if(f.height=t.height,o.width!==void 0&&o.width!==t.width)throw new Error("Image input config width doesn't match ImageBitmap width");f.width=t.width}else f.height=t.height,f.width=t.width;c(ut.bufferToTensor(i.data,f))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(p!==void 0)return ut.bufferToTensor(p,f);throw new Error("Input data provided is not supported - aborted tensor creation")}toImageData(n){var o,u;const l=document.createElement("canvas").getContext("2d");let d;if(l!=null){const s=this.dims[3],p=this.dims[2],f=this.dims[1],c=n!==void 0&&n.format!==void 0?n.format:"RGB",a=n!==void 0&&((o=n.norm)===null||o===void 0?void 0:o.mean)!==void 0?n.norm.mean:255,t=n!==void 0&&((u=n.norm)===null||u===void 0?void 0:u.bias)!==void 0?n.norm.bias:0,e=p*s;if(n!==void 0){if(n.height!==void 0&&n.height!==p)throw new Error("Image output config height doesn't match tensor height");if(n.width!==void 0&&n.width!==s)throw new Error("Image output config width doesn't match tensor width");if(n.format!==void 0&&f===4&&n.format!=="RGBA"||f===3&&n.format!=="RGB"&&n.format!=="BGR")throw new Error("Tensor format doesn't match input tensor dims")}const r=4;let i=0,h=1,g=2,m=3,b=0,y=e,w=e*2,T=-1;c==="RGBA"?(b=0,y=e,w=e*2,T=e*3):c==="RGB"?(b=0,y=e,w=e*2):c==="RBG"&&(b=0,w=e,y=e*2),d=l.createImageData(s,p);for(let S=0;S"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(s)for(const c of this.outputNames)l[c]=null;const p=await this.handler.run(n,l,d),f={};for(const c in p)Object.hasOwnProperty.call(p,c)&&(f[c]=new Tensor$1(p[c].type,p[c].data,p[c].dims));return f}static async create(n,o,u,l){let d,s={};if(typeof n=="string"){if(d=n,typeof o=="object"&&o!==null)s=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(n instanceof Uint8Array){if(d=n,typeof o=="object"&&o!==null)s=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer){const t=n;let e=0,r=n.byteLength;if(typeof o=="object"&&o!==null)s=o;else if(typeof o=="number"){if(e=o,!Number.isSafeInteger(e))throw new RangeError("'byteOffset' must be an integer.");if(e<0||e>=t.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${t.byteLength}).`);if(r=n.byteLength-e,typeof u=="number"){if(r=u,!Number.isSafeInteger(r))throw new RangeError("'byteLength' must be an integer.");if(r<=0||e+r>t.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${t.byteLength-e}].`);if(typeof l=="object"&&l!==null)s=l;else if(typeof l<"u")throw new TypeError("'options' must be an object.")}else if(typeof u<"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(t,e,r)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const f=(s.executionProviders||[]).map(t=>typeof t=="string"?t:t.name),a=await(await resolveBackend(f)).createSessionHandler(d,s);return new dn(a)}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$1,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(_,n){module.exports=n(require$$0)})(self,__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(_,n,o)=>{var u,l=(u=(u=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(d){function s(){return X.buffer!=ee&&Pe(X.buffer),ue}function p(){return X.buffer!=ee&&Pe(X.buffer),Ae}function f(){return X.buffer!=ee&&Pe(X.buffer),ve}function c(){return X.buffer!=ee&&Pe(X.buffer),oe}function a(){return X.buffer!=ee&&Pe(X.buffer),we}var t,e,r;d=d||{},t||(t=d!==void 0?d:{}),t.ready=new Promise(function(x,P){e=x,r=P});var i,h,g,m,b,y,w=Object.assign({},t),T="./this.program",S=(x,P)=>{throw P},A=typeof window=="object",O=typeof importScripts=="function",v=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",M=t.ENVIRONMENT_IS_PTHREAD||!1,F="";function R(x){return t.locateFile?t.locateFile(x,F):F+x}if(v){let x;F=O?o(908).dirname(F)+"/":"//",y=()=>{b||(m=o(1384),b=o(908))},i=function(P,k){return y(),P=b.normalize(P),m.readFileSync(P,k?void 0:"utf8")},g=P=>((P=i(P,!0)).buffer||(P=new Uint8Array(P)),P),h=(P,k,C)=>{y(),P=b.normalize(P),m.readFile(P,function(B,V){B?C(B):k(V.buffer)})},1{if(qe())throw process.exitCode=P,k;k instanceof Je||j("exiting due to exception: "+k),process.exit(P)},t.inspect=function(){return"[Emscripten Module object]"};try{x=o(9925)}catch(P){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),P}o.g.Worker=x.Worker}else(A||O)&&(O?F=self.location.href:typeof document<"u"&&document.currentScript&&(F=document.currentScript.src),u&&(F=u),F=F.indexOf("blob:")!==0?F.substr(0,F.replace(/[?#].*/,"").lastIndexOf("/")+1):"",v||(i=x=>{var P=new XMLHttpRequest;return P.open("GET",x,!1),P.send(null),P.responseText},O&&(g=x=>{var P=new XMLHttpRequest;return P.open("GET",x,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),h=(x,P,k)=>{var C=new XMLHttpRequest;C.open("GET",x,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?P(C.response):k()},C.onerror=k,C.send(null)}));v&&typeof performance>"u"&&(o.g.performance=o(6953).performance);var $=console.log.bind(console),N=console.warn.bind(console);v&&(y(),$=x=>m.writeSync(1,x+` +`),N=x=>m.writeSync(2,x+` +`));var G,D=t.print||$,j=t.printErr||N;Object.assign(t,w),w=null,t.thisProgram&&(T=t.thisProgram),t.quit&&(S=t.quit),t.wasmBinary&&(G=t.wasmBinary);var Q=t.noExitRuntime||!1;typeof WebAssembly!="object"&&ge("no native wasm support detected");var X,Z,ee,ue,Ae,ve,oe,we,be=!1,ke=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Le(x,P,k){var C=(P>>>=0)+k;for(k=P;x[k]&&!(k>=C);)++k;if(16(B=(240&B)==224?(15&B)<<12|V<<6|K:(7&B)<<18|V<<12|K<<6|63&x[P++])?C+=String.fromCharCode(B):(B-=65536,C+=String.fromCharCode(55296|B>>10,56320|1023&B))}}else C+=String.fromCharCode(B)}return C}function xe(x,P){return(x>>>=0)?Le(p(),x,P):""}function Fe(x,P,k,C){if(!(0>>=0;C=k+C-1;for(var V=0;V=K&&(K=65536+((1023&K)<<10)|1023&x.charCodeAt(++V)),127>=K){if(k>=C)break;P[k++>>>0]=K}else{if(2047>=K){if(k+1>=C)break;P[k++>>>0]=192|K>>6}else{if(65535>=K){if(k+2>=C)break;P[k++>>>0]=224|K>>12}else{if(k+3>=C)break;P[k++>>>0]=240|K>>18,P[k++>>>0]=128|K>>12&63}P[k++>>>0]=128|K>>6&63}P[k++>>>0]=128|63&K}}return P[k>>>0]=0,k-B}function Ce(x){for(var P=0,k=0;k=C?P++:2047>=C?P+=2:55296<=C&&57343>=C?(P+=4,++k):P+=3}return P}function Pe(x){ee=x,t.HEAP8=ue=new Int8Array(x),t.HEAP16=new Int16Array(x),t.HEAP32=ve=new Int32Array(x),t.HEAPU8=Ae=new Uint8Array(x),t.HEAPU16=new Uint16Array(x),t.HEAPU32=oe=new Uint32Array(x),t.HEAPF32=new Float32Array(x),t.HEAPF64=we=new Float64Array(x)}M&&(ee=t.buffer);var Oe=t.INITIAL_MEMORY||16777216;if(M)X=t.wasmMemory,ee=t.buffer;else if(t.wasmMemory)X=t.wasmMemory;else if(!((X=new WebAssembly.Memory({initial:Oe/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw j("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"),v&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");X&&(ee=X.buffer),Oe=ee.byteLength,Pe(ee);var Be,Ge=[],Ve=[],Xe=[],Qe=[];function qe(){return Q||!1}function Ue(){var x=t.preRun.shift();Ge.unshift(x)}var Me,je=0,Ye=null;function ge(x){throw M?postMessage({cmd:"onAbort",arg:x}):t.onAbort&&t.onAbort(x),j(x="Aborted("+x+")"),be=!0,x=new WebAssembly.RuntimeError(x+". Build with -sASSERTIONS for more info."),r(x),x}function pt(){return Me.startsWith("data:application/octet-stream;base64,")}function lt(){var x=Me;try{if(x==Me&&G)return new Uint8Array(G);if(g)return g(x);throw"both async and sync fetching of the wasm failed"}catch(P){ge(P)}}Me="ort-wasm-threaded.wasm",pt()||(Me=R(Me));var Et={};function Je(x){this.name="ExitStatus",this.message="Program terminated with exit("+x+")",this.status=x}function ct(x){(x=re.Vb[x])||ge(),re.mc(x)}function dt(x){var P=re.Cc();if(!P)return 6;re.ac.push(P),re.Vb[x.Ub]=P,P.Ub=x.Ub;var k={cmd:"run",start_routine:x.Ic,arg:x.zc,pthread_ptr:x.Ub};return P.$b=()=>{k.time=performance.now(),P.postMessage(k,x.Nc)},P.loaded&&(P.$b(),delete P.$b),0}function Re(x){if(M)return J(1,1,x);qe()||(re.oc(),t.onExit&&t.onExit(x),be=!0),S(x,new Je(x))}function it(x,P){if(!P&&M)throw kt(x),"unwind";qe()||M||(Wt(),rt(Xe),qt(0),Nt[1].length&&Lt(1,10),Nt[2].length&&Lt(2,10),re.oc()),Re(x)}var re={Yb:[],ac:[],qc:[],Vb:{},fc:function(){M&&re.Ec()},Pc:function(){},Ec:function(){re.receiveObjectTransfer=re.Gc,re.threadInitTLS=re.pc,re.setExitStatus=re.nc,Q=!1},nc:function(){},oc:function(){for(var x of Object.values(re.Vb))re.mc(x);for(x of re.Yb)x.terminate();re.Yb=[]},mc:function(x){var P=x.Ub;delete re.Vb[P],re.Yb.push(x),re.ac.splice(re.ac.indexOf(x),1),x.Ub=0,Rt(P)},Gc:function(){},pc:function(){re.qc.forEach(x=>x())},Fc:function(x,P){x.onmessage=k=>{var C=(k=k.data).cmd;if(x.Ub&&(re.Bc=x.Ub),k.targetThread&&k.targetThread!=Dt()){var B=re.Vb[k.Qc];B?B.postMessage(k,k.transferList):j('Internal error! Worker sent a message "'+C+'" to target pthread '+k.targetThread+", but that thread no longer exists!")}else C==="processProxyingQueue"?L(k.queue):C==="spawnThread"?dt(k):C==="cleanupThread"?ct(k.thread):C==="killThread"?(k=k.thread,C=re.Vb[k],delete re.Vb[k],C.terminate(),Rt(k),re.ac.splice(re.ac.indexOf(C),1),C.Ub=0):C==="cancelThread"?re.Vb[k.thread].postMessage({cmd:"cancel"}):C==="loaded"?(x.loaded=!0,P&&P(x),x.$b&&(x.$b(),delete x.$b)):C==="print"?D("Thread "+k.threadId+": "+k.text):C==="printErr"?j("Thread "+k.threadId+": "+k.text):C==="alert"?alert("Thread "+k.threadId+": "+k.text):k.target==="setimmediate"?x.postMessage(k):C==="onAbort"?t.onAbort&&t.onAbort(k.arg):C&&j("worker sent an unknown command "+C);re.Bc=void 0},x.onerror=k=>{throw j("worker sent an error! "+k.filename+":"+k.lineno+": "+k.message),k},v&&(x.on("message",function(k){x.onmessage({data:k})}),x.on("error",function(k){x.onerror(k)}),x.on("detachedExit",function(){})),x.postMessage({cmd:"load",urlOrBlob:t.mainScriptUrlOrBlob||u,wasmMemory:X,wasmModule:Z})},yc:function(){var x=R("ort-wasm-threaded.worker.js");re.Yb.push(new Worker(x))},Cc:function(){return re.Yb.length==0&&(re.yc(),re.Fc(re.Yb[0])),re.Yb.pop()}};function rt(x){for(;0>2>>>0];x=f()[x+48>>2>>>0],Qt(P,P-x),de(P)};var Ze=[];function Te(x){var P=Ze[x];return P||(x>=Ze.length&&(Ze.length=x+1),Ze[x]=P=Be.get(x)),P}t.invokeEntryPoint=function(x,P){x=Te(x)(P),qe()?re.nc(x):Kt(x)};var ot,ft,st=[],ae=0,ie=0;function se(x){this.Zb=x,this.Sb=x-24,this.xc=function(P){c()[this.Sb+4>>2>>>0]=P},this.bc=function(){return c()[this.Sb+4>>2>>>0]},this.wc=function(P){c()[this.Sb+8>>2>>>0]=P},this.Dc=function(){return c()[this.Sb+8>>2>>>0]},this.rc=function(){f()[this.Sb>>2>>>0]=0},this.hc=function(P){P=P?1:0,s()[this.Sb+12>>0>>>0]=P},this.uc=function(){return s()[this.Sb+12>>0>>>0]!=0},this.ic=function(P){P=P?1:0,s()[this.Sb+13>>0>>>0]=P},this.kc=function(){return s()[this.Sb+13>>0>>>0]!=0},this.fc=function(P,k){this.cc(0),this.xc(P),this.wc(k),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(f(),this.Sb>>2,1)},this.Hc=function(){return Atomics.sub(f(),this.Sb>>2,1)===1},this.cc=function(P){c()[this.Sb+16>>2>>>0]=P},this.tc=function(){return c()[this.Sb+16>>2>>>0]},this.vc=function(){if(Jt(this.bc()))return c()[this.Zb>>2>>>0];var P=this.tc();return P!==0?P:this.Zb}}function gt(x){return Vt(new se(x).Sb)}function at(x,P,k,C){return M?J(3,1,x,P,k,C):mt(x,P,k,C)}function mt(x,P,k,C){if(typeof SharedArrayBuffer>"u")return j("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var B=[];return M&&B.length===0?at(x,P,k,C):(x={Ic:k,Ub:x,zc:C,Nc:B},M?(x.Oc="spawnThread",postMessage(x,B),0):dt(x))}function _t(x,P,k){return M?J(4,1,x,P,k):0}function bt(x,P){if(M)return J(5,1,x,P)}function yt(x,P){if(M)return J(6,1,x,P)}function wt(x,P,k){if(M)return J(7,1,x,P,k)}function Tt(x,P,k){return M?J(8,1,x,P,k):0}function vt(x,P){if(M)return J(9,1,x,P)}function xt(x,P,k){if(M)return J(10,1,x,P,k)}function St(x,P,k,C){if(M)return J(11,1,x,P,k,C)}function At(x,P,k,C){if(M)return J(12,1,x,P,k,C)}function Ot(x,P,k,C){if(M)return J(13,1,x,P,k,C)}function Pt(x){if(M)return J(14,1,x)}function E(x,P){if(M)return J(15,1,x,P)}function I(x,P,k){if(M)return J(16,1,x,P,k)}function L(x){Atomics.store(f(),x>>2,1),Dt()&&Yt(x),Atomics.compareExchange(f(),x>>2,1,0)}function z(x){return c()[x>>>2]+4294967296*f()[x+4>>>2]}function U(x,P,k,C,B,V){return M?J(17,1,x,P,k,C,B,V):-52}function H(x,P,k,C,B,V){if(M)return J(18,1,x,P,k,C,B,V)}function Y(x){var P=Ce(x)+1,k=$t(P);return k&&Fe(x,s(),k,P),k}function te(x,P,k){function C(me){return(me=me.toTimeString().match(/\(([A-Za-z ]+)\)$/))?me[1]:"GMT"}if(M)return J(19,1,x,P,k);var B=new Date().getFullYear(),V=new Date(B,0,1),K=new Date(B,6,1);B=V.getTimezoneOffset();var ne=K.getTimezoneOffset(),fe=Math.max(B,ne);f()[x>>2>>>0]=60*fe,f()[P>>2>>>0]=+(B!=ne),x=C(V),P=C(K),x=Y(x),P=Y(P),ne>2>>>0]=x,c()[k+4>>2>>>0]=P):(c()[k>>2>>>0]=P,c()[k+4>>2>>>0]=x)}function J(x,P){var k=arguments.length-2,C=arguments;return Mt(()=>{for(var B=jt(8*k),V=B>>3,K=0;K>>0]=ne}return Xt(x,k,B,P)})}t.executeNotifiedProxyingQueue=L,ft=v?()=>{var x=process.hrtime();return 1e3*x[0]+x[1]/1e6}:M?()=>performance.now()-t.__performance_now_clock_drift:()=>performance.now();var ce,Se=[],$e={};function Ne(){if(!ce){var x,P={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",_:T||"./this.program"};for(x in $e)$e[x]===void 0?delete P[x]:P[x]=$e[x];var k=[];for(x in P)k.push(x+"="+P[x]);ce=k}return ce}function q(x,P){if(M)return J(20,1,x,P);var k=0;return Ne().forEach(function(C,B){var V=P+k;for(B=c()[x+4*B>>2>>>0]=V,V=0;V>0>>>0]=C.charCodeAt(V);s()[B>>0>>>0]=0,k+=C.length+1}),0}function _e(x,P){if(M)return J(21,1,x,P);var k=Ne();c()[x>>2>>>0]=k.length;var C=0;return k.forEach(function(B){C+=B.length+1}),c()[P>>2>>>0]=C,0}function Ee(x){return M?J(22,1,x):52}function We(x,P,k,C){return M?J(23,1,x,P,k,C):52}function et(x,P,k,C,B){return M?J(24,1,x,P,k,C,B):70}var Nt=[null,[],[]];function Lt(x,P){var k=Nt[x];P===0||P===10?((x===1?D:j)(Le(k,0)),k.length=0):k.push(P)}function zt(x,P,k,C){if(M)return J(25,1,x,P,k,C);for(var B=0,V=0;V>2>>>0],ne=c()[P+4>>2>>>0];P+=8;for(var fe=0;fe>>0]);B+=ne}return c()[C>>2>>>0]=B,0}var ze=0;function It(x){return x%4==0&&(x%100!=0||x%400==0)}var Bt=[31,29,31,30,31,30,31,31,30,31,30,31],Ut=[31,28,31,30,31,30,31,31,30,31,30,31];function Gt(x,P,k,C){function B(W,ye,Ie){for(W=typeof W=="number"?W.toString():W||"";W.lengthht?-1:0tt-W.getDate())){W.setDate(W.getDate()+ye);break}ye-=tt-W.getDate()+1,W.setDate(1),11>Ie?W.setMonth(Ie+1):(W.setMonth(0),W.setFullYear(W.getFullYear()+1))}return Ie=new Date(W.getFullYear()+1,0,4),ye=ne(new Date(W.getFullYear(),0,4)),Ie=ne(Ie),0>=K(ye,W)?0>=K(Ie,W)?W.getFullYear()+1:W.getFullYear():W.getFullYear()-1}var me=f()[C+40>>2>>>0];for(var De in C={Lc:f()[C>>2>>>0],Kc:f()[C+4>>2>>>0],dc:f()[C+8>>2>>>0],jc:f()[C+12>>2>>>0],ec:f()[C+16>>2>>>0],Xb:f()[C+20>>2>>>0],Tb:f()[C+24>>2>>>0],Wb:f()[C+28>>2>>>0],Rc:f()[C+32>>2>>>0],Jc:f()[C+36>>2>>>0],Mc:me?xe(me):""},k=xe(k),me={"%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"})k=k.replace(new RegExp(De,"g"),me[De]);var Ke="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),He="January February March April May June July August September October November December".split(" ");for(De in me={"%a":function(W){return Ke[W.Tb].substring(0,3)},"%A":function(W){return Ke[W.Tb]},"%b":function(W){return He[W.ec].substring(0,3)},"%B":function(W){return He[W.ec]},"%C":function(W){return V((W.Xb+1900)/100|0,2)},"%d":function(W){return V(W.jc,2)},"%e":function(W){return B(W.jc,2," ")},"%g":function(W){return fe(W).toString().substring(2)},"%G":function(W){return fe(W)},"%H":function(W){return V(W.dc,2)},"%I":function(W){return(W=W.dc)==0?W=12:12W.dc?"AM":"PM"},"%S":function(W){return V(W.Lc,2)},"%t":function(){return" "},"%u":function(W){return W.Tb||7},"%U":function(W){return V(Math.floor((W.Wb+7-W.Tb)/7),2)},"%V":function(W){var ye=Math.floor((W.Wb+7-(W.Tb+6)%7)/7);if(2>=(W.Tb+371-W.Wb-2)%7&&ye++,ye)ye==53&&((Ie=(W.Tb+371-W.Wb)%7)==4||Ie==3&&It(W.Xb)||(ye=1));else{ye=52;var Ie=(W.Tb+7-W.Wb-1)%7;(Ie==4||Ie==5&&It(W.Xb%400-1))&&ye++}return V(ye,2)},"%w":function(W){return W.Tb},"%W":function(W){return V(Math.floor((W.Wb+7-(W.Tb+6)%7)/7),2)},"%y":function(W){return(W.Xb+1900).toString().substring(2)},"%Y":function(W){return W.Xb+1900},"%z":function(W){var ye=0<=(W=W.Jc);return W=Math.abs(W)/60,(ye?"+":"-")+("0000"+(W/60*100+W%60)).slice(-4)},"%Z":function(W){return W.Mc},"%%":function(){return"%"}},k=k.replace(/%%/g,"\0\0"),me)k.includes(De)&&(k=k.replace(new RegExp(De,"g"),me[De](C)));return De=function(W){var ye=Array(Ce(W)+1);return Fe(W,ye,0,ye.length),ye}(k=k.replace(/\0\0/g,"%")),De.length>P?0:(function(W,ye){s().set(W,ye>>>0)}(De,x),De.length-1)}re.fc();var hn=[null,Re,kt,at,_t,bt,yt,wt,Tt,vt,xt,St,At,Ot,Pt,E,I,U,H,te,q,_e,Ee,We,et,zt],pn={b:function(x){return $t(x+24)+24},n:function(x){return(x=new se(x)).uc()||(x.hc(!0),ae--),x.ic(!1),st.push(x),x.sc(),x.vc()},ma:function(x){throw j("Unexpected exception thrown, this is not properly supported - aborting"),be=!0,x},x:function(){pe(0);var x=st.pop();if(x.Hc()&&!x.kc()){var P=x.Dc();P&&Te(P)(x.Zb),gt(x.Zb)}ie=0},e:function(){var x=ie;if(!x)return ze=0;var P=new se(x);P.cc(x);var k=P.bc();if(!k)return ze=0,x;for(var C=Array.prototype.slice.call(arguments),B=0;BL(C));else if(M)postMessage({targetThread:x,cmd:"processProxyingQueue",queue:C});else{if(!(x=re.Vb[x]))return;x.postMessage({cmd:"processProxyingQueue",queue:C})}return 1},Ea:function(){return-1},Pa:function(x,P){x=new Date(1e3*z(x)),f()[P>>2>>>0]=x.getUTCSeconds(),f()[P+4>>2>>>0]=x.getUTCMinutes(),f()[P+8>>2>>>0]=x.getUTCHours(),f()[P+12>>2>>>0]=x.getUTCDate(),f()[P+16>>2>>>0]=x.getUTCMonth(),f()[P+20>>2>>>0]=x.getUTCFullYear()-1900,f()[P+24>>2>>>0]=x.getUTCDay(),x=(x.getTime()-Date.UTC(x.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,f()[P+28>>2>>>0]=x},Qa:function(x,P){x=new Date(1e3*z(x)),f()[P>>2>>>0]=x.getSeconds(),f()[P+4>>2>>>0]=x.getMinutes(),f()[P+8>>2>>>0]=x.getHours(),f()[P+12>>2>>>0]=x.getDate(),f()[P+16>>2>>>0]=x.getMonth(),f()[P+20>>2>>>0]=x.getFullYear()-1900,f()[P+24>>2>>>0]=x.getDay();var k=new Date(x.getFullYear(),0,1),C=(x.getTime()-k.getTime())/864e5|0;f()[P+28>>2>>>0]=C,f()[P+36>>2>>>0]=-60*x.getTimezoneOffset(),C=new Date(x.getFullYear(),6,1).getTimezoneOffset(),x=0|(C!=(k=k.getTimezoneOffset())&&x.getTimezoneOffset()==Math.min(k,C)),f()[P+32>>2>>>0]=x},Ra:function(x){var P=new Date(f()[x+20>>2>>>0]+1900,f()[x+16>>2>>>0],f()[x+12>>2>>>0],f()[x+8>>2>>>0],f()[x+4>>2>>>0],f()[x>>2>>>0],0),k=f()[x+32>>2>>>0],C=P.getTimezoneOffset(),B=new Date(P.getFullYear(),0,1),V=new Date(P.getFullYear(),6,1).getTimezoneOffset(),K=B.getTimezoneOffset(),ne=Math.min(K,V);return 0>k?f()[x+32>>2>>>0]=+(V!=K&&ne==C):0>2>>>0]=P.getDay(),k=(P.getTime()-B.getTime())/864e5|0,f()[x+28>>2>>>0]=k,f()[x>>2>>>0]=P.getSeconds(),f()[x+4>>2>>>0]=P.getMinutes(),f()[x+8>>2>>>0]=P.getHours(),f()[x+12>>2>>>0]=P.getDate(),f()[x+16>>2>>>0]=P.getMonth(),P.getTime()/1e3|0},Aa:U,Ba:H,Sa:function x(P,k,C){x.Ac||(x.Ac=!0,te(P,k,C))},y:function(){ge("")},U:function(){if(!v&&!O){var x="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";ot||(ot={}),ot[x]||(ot[x]=1,v&&(x="warning: "+x),j(x))}},ra:function(){return 4294901760},B:ft,Ia:function(x,P,k){p().copyWithin(x>>>0,P>>>0,P+k>>>0)},F:function(){return v?o(3993).cpus().length:navigator.hardwareConcurrency},Da:function(x,P,k){Se.length=P,k>>=3;for(var C=0;C>>0];return(0>x?Et[-x-1]:hn[x]).apply(null,Se)},qa:function(x){var P=p().length;if((x>>>=0)<=P||4294901760=k;k*=2){var C=P*(1+.2/k);C=Math.min(C,x+100663296);var B=Math;C=Math.max(x,C),B=B.min.call(B,4294901760,C+(65536-C%65536)%65536);e:{try{X.grow(B-ee.byteLength+65535>>>16),Pe(X.buffer);var V=1;break e}catch{}V=void 0}if(V)return!0}return!1},Na:function(){throw"unwind"},Ga:q,Ha:_e,J:it,I:Ee,S:We,ga:et,R:zt,d:function(){return ze},na:function x(P,k){x.lc||(x.lc=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var B=new Uint8Array(1);return()=>(crypto.getRandomValues(B),B[0])}if(v)try{var V=o(Object(function(){var K=new Error("Cannot find module 'crypto'");throw K.code="MODULE_NOT_FOUND",K}()));return()=>V.randomBytes(1)[0]}catch{}return()=>ge("randomDevice")}());for(var C=0;C>0>>>0]=x.lc();return 0},ia:function(x,P,k){var C=he();try{return Te(x)(P,k)}catch(B){if(de(C),B!==B+0)throw B;pe(1,0)}},ja:function(x,P,k){var C=he();try{return Te(x)(P,k)}catch(B){if(de(C),B!==B+0)throw B;pe(1,0)}},K:function(x){var P=he();try{return Te(x)()}catch(k){if(de(P),k!==k+0)throw k;pe(1,0)}},f:function(x,P){var k=he();try{return Te(x)(P)}catch(C){if(de(k),C!==C+0)throw C;pe(1,0)}},P:function(x,P,k){var C=he();try{return Te(x)(P,k)}catch(B){if(de(C),B!==B+0)throw B;pe(1,0)}},Q:function(x,P,k){var C=he();try{return Te(x)(P,k)}catch(B){if(de(C),B!==B+0)throw B;pe(1,0)}},k:function(x,P,k){var C=he();try{return Te(x)(P,k)}catch(B){if(de(C),B!==B+0)throw B;pe(1,0)}},p:function(x,P,k,C){var B=he();try{return Te(x)(P,k,C)}catch(V){if(de(B),V!==V+0)throw V;pe(1,0)}},q:function(x,P,k,C,B){var V=he();try{return Te(x)(P,k,C,B)}catch(K){if(de(V),K!==K+0)throw K;pe(1,0)}},N:function(x,P,k,C,B,V){var K=he();try{return Te(x)(P,k,C,B,V)}catch(ne){if(de(K),ne!==ne+0)throw ne;pe(1,0)}},s:function(x,P,k,C,B,V){var K=he();try{return Te(x)(P,k,C,B,V)}catch(ne){if(de(K),ne!==ne+0)throw ne;pe(1,0)}},w:function(x,P,k,C,B,V,K){var ne=he();try{return Te(x)(P,k,C,B,V,K)}catch(fe){if(de(ne),fe!==fe+0)throw fe;pe(1,0)}},L:function(x,P,k,C,B,V,K,ne){var fe=he();try{return Te(x)(P,k,C,B,V,K,ne)}catch(me){if(de(fe),me!==me+0)throw me;pe(1,0)}},E:function(x,P,k,C,B,V,K,ne,fe,me,De,Ke){var He=he();try{return Te(x)(P,k,C,B,V,K,ne,fe,me,De,Ke)}catch(W){if(de(He),W!==W+0)throw W;pe(1,0)}},aa:function(x,P,k,C,B,V,K,ne){var fe=he();try{return un(x,P,k,C,B,V,K,ne)}catch(me){if(de(fe),me!==me+0)throw me;pe(1,0)}},_:function(x,P,k,C,B,V,K){var ne=he();try{return en(x,P,k,C,B,V,K)}catch(fe){if(de(ne),fe!==fe+0)throw fe;pe(1,0)}},Z:function(x,P,k,C,B){var V=he();try{return ln(x,P,k,C,B)}catch(K){if(de(V),K!==K+0)throw K;pe(1,0)}},ca:function(x,P,k,C){var B=he();try{return sn(x,P,k,C)}catch(V){if(de(B),V!==V+0)throw V;pe(1,0)}},$:function(x){var P=he();try{return Zt(x)}catch(k){if(de(P),k!==k+0)throw k;pe(1,0)}},ba:function(x,P){var k=he();try{return an(x,P)}catch(C){if(de(k),C!==C+0)throw C;pe(1,0)}},Y:function(x,P,k){var C=he();try{return tn(x,P,k)}catch(B){if(de(C),B!==B+0)throw B;pe(1,0)}},g:function(x){var P=he();try{Te(x)()}catch(k){if(de(P),k!==k+0)throw k;pe(1,0)}},r:function(x,P){var k=he();try{Te(x)(P)}catch(C){if(de(k),C!==C+0)throw C;pe(1,0)}},i:function(x,P,k){var C=he();try{Te(x)(P,k)}catch(B){if(de(C),B!==B+0)throw B;pe(1,0)}},ha:function(x,P,k,C){var B=he();try{Te(x)(P,k,C)}catch(V){if(de(B),V!==V+0)throw V;pe(1,0)}},m:function(x,P,k,C){var B=he();try{Te(x)(P,k,C)}catch(V){if(de(B),V!==V+0)throw V;pe(1,0)}},v:function(x,P,k,C,B){var V=he();try{Te(x)(P,k,C,B)}catch(K){if(de(V),K!==K+0)throw K;pe(1,0)}},u:function(x,P,k,C,B,V){var K=he();try{Te(x)(P,k,C,B,V)}catch(ne){if(de(K),ne!==ne+0)throw ne;pe(1,0)}},O:function(x,P,k,C,B,V,K){var ne=he();try{Te(x)(P,k,C,B,V,K)}catch(fe){if(de(ne),fe!==fe+0)throw fe;pe(1,0)}},A:function(x,P,k,C,B,V,K,ne){var fe=he();try{Te(x)(P,k,C,B,V,K,ne)}catch(me){if(de(fe),me!==me+0)throw me;pe(1,0)}},ka:function(x,P,k,C,B,V,K,ne,fe){var me=he();try{Te(x)(P,k,C,B,V,K,ne,fe)}catch(De){if(de(me),De!==De+0)throw De;pe(1,0)}},C:function(x,P,k,C,B,V,K,ne,fe,me,De){var Ke=he();try{Te(x)(P,k,C,B,V,K,ne,fe,me,De)}catch(He){if(de(Ke),He!==He+0)throw He;pe(1,0)}},D:function(x,P,k,C,B,V,K,ne,fe,me,De,Ke,He,W,ye,Ie){var tt=he();try{Te(x)(P,k,C,B,V,K,ne,fe,me,De,Ke,He,W,ye,Ie)}catch(ht){if(de(tt),ht!==ht+0)throw ht;pe(1,0)}},fa:function(x,P,k,C,B,V,K,ne){var fe=he();try{nn(x,P,k,C,B,V,K,ne)}catch(me){if(de(fe),me!==me+0)throw me;pe(1,0)}},da:function(x,P,k,C,B,V,K,ne,fe,me,De,Ke){var He=he();try{on(x,P,k,C,B,V,K,ne,fe,me,De,Ke)}catch(W){if(de(He),W!==W+0)throw W;pe(1,0)}},ea:function(x,P,k,C,B,V){var K=he();try{rn(x,P,k,C,B,V)}catch(ne){if(de(K),ne!==ne+0)throw ne;pe(1,0)}},o:function(x){return x},a:X||t.wasmMemory,G:function(x){ze=x},la:Gt,z:function(x,P,k,C){return Gt(x,P,k,C)}};(function(){function x(B,V){t.asm=B.exports,re.qc.push(t.asm.sb),Be=t.asm.ub,Ve.unshift(t.asm.Va),Z=V,M||(je--,t.monitorRunDependencies&&t.monitorRunDependencies(je),je==0&&Ye&&(B=Ye,Ye=null,B()))}function P(B){x(B.instance,B.module)}function k(B){return function(){if(!G&&(A||O)){if(typeof fetch=="function"&&!Me.startsWith("file://"))return fetch(Me,{credentials:"same-origin"}).then(function(V){if(!V.ok)throw"failed to load wasm binary file at '"+Me+"'";return V.arrayBuffer()}).catch(function(){return lt()});if(h)return new Promise(function(V,K){h(Me,function(ne){V(new Uint8Array(ne))},K)})}return Promise.resolve().then(function(){return lt()})}().then(function(V){return WebAssembly.instantiate(V,C)}).then(function(V){return V}).then(B,function(V){j("failed to asynchronously prepare wasm: "+V),ge(V)})}var C={a:pn};if(M||(je++,t.monitorRunDependencies&&t.monitorRunDependencies(je)),t.instantiateWasm)try{return t.instantiateWasm(C,x)}catch(B){return j("Module.instantiateWasm callback failed with error: "+B),!1}(G||typeof WebAssembly.instantiateStreaming!="function"||pt()||Me.startsWith("file://")||v||typeof fetch!="function"?k(P):fetch(Me,{credentials:"same-origin"}).then(function(B){return WebAssembly.instantiateStreaming(B,C).then(P,function(V){return j("wasm streaming compile failed: "+V),j("falling back to ArrayBuffer instantiation"),k(P)})})).catch(r)})(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.Va).apply(null,arguments)},t._OrtInit=function(){return(t._OrtInit=t.asm.Wa).apply(null,arguments)},t._OrtCreateSessionOptions=function(){return(t._OrtCreateSessionOptions=t.asm.Xa).apply(null,arguments)},t._OrtAppendExecutionProvider=function(){return(t._OrtAppendExecutionProvider=t.asm.Ya).apply(null,arguments)},t._OrtAddSessionConfigEntry=function(){return(t._OrtAddSessionConfigEntry=t.asm.Za).apply(null,arguments)},t._OrtReleaseSessionOptions=function(){return(t._OrtReleaseSessionOptions=t.asm._a).apply(null,arguments)},t._OrtCreateSession=function(){return(t._OrtCreateSession=t.asm.$a).apply(null,arguments)},t._OrtReleaseSession=function(){return(t._OrtReleaseSession=t.asm.ab).apply(null,arguments)},t._OrtGetInputCount=function(){return(t._OrtGetInputCount=t.asm.bb).apply(null,arguments)},t._OrtGetOutputCount=function(){return(t._OrtGetOutputCount=t.asm.cb).apply(null,arguments)},t._OrtGetInputName=function(){return(t._OrtGetInputName=t.asm.db).apply(null,arguments)},t._OrtGetOutputName=function(){return(t._OrtGetOutputName=t.asm.eb).apply(null,arguments)},t._OrtFree=function(){return(t._OrtFree=t.asm.fb).apply(null,arguments)},t._OrtCreateTensor=function(){return(t._OrtCreateTensor=t.asm.gb).apply(null,arguments)},t._OrtGetTensorData=function(){return(t._OrtGetTensorData=t.asm.hb).apply(null,arguments)},t._OrtReleaseTensor=function(){return(t._OrtReleaseTensor=t.asm.ib).apply(null,arguments)},t._OrtCreateRunOptions=function(){return(t._OrtCreateRunOptions=t.asm.jb).apply(null,arguments)},t._OrtAddRunConfigEntry=function(){return(t._OrtAddRunConfigEntry=t.asm.kb).apply(null,arguments)},t._OrtReleaseRunOptions=function(){return(t._OrtReleaseRunOptions=t.asm.lb).apply(null,arguments)},t._OrtRun=function(){return(t._OrtRun=t.asm.mb).apply(null,arguments)},t._OrtEndProfiling=function(){return(t._OrtEndProfiling=t.asm.nb).apply(null,arguments)};var Dt=t._pthread_self=function(){return(Dt=t._pthread_self=t.asm.ob).apply(null,arguments)},$t=t._malloc=function(){return($t=t._malloc=t.asm.pb).apply(null,arguments)},Vt=t._free=function(){return(Vt=t._free=t.asm.qb).apply(null,arguments)},qt=t._fflush=function(){return(qt=t._fflush=t.asm.rb).apply(null,arguments)};t.__emscripten_tls_init=function(){return(t.__emscripten_tls_init=t.asm.sb).apply(null,arguments)};var Wt=t.___funcs_on_exit=function(){return(Wt=t.___funcs_on_exit=t.asm.tb).apply(null,arguments)},Ht=t.__emscripten_thread_init=function(){return(Ht=t.__emscripten_thread_init=t.asm.vb).apply(null,arguments)};t.__emscripten_thread_crashed=function(){return(t.__emscripten_thread_crashed=t.asm.wb).apply(null,arguments)};var Ct,Xt=t._emscripten_run_in_main_runtime_thread_js=function(){return(Xt=t._emscripten_run_in_main_runtime_thread_js=t.asm.xb).apply(null,arguments)},Yt=t.__emscripten_proxy_execute_task_queue=function(){return(Yt=t.__emscripten_proxy_execute_task_queue=t.asm.yb).apply(null,arguments)},Rt=t.__emscripten_thread_free_data=function(){return(Rt=t.__emscripten_thread_free_data=t.asm.zb).apply(null,arguments)},Kt=t.__emscripten_thread_exit=function(){return(Kt=t.__emscripten_thread_exit=t.asm.Ab).apply(null,arguments)},pe=t._setThrew=function(){return(pe=t._setThrew=t.asm.Bb).apply(null,arguments)},Qt=t._emscripten_stack_set_limits=function(){return(Qt=t._emscripten_stack_set_limits=t.asm.Cb).apply(null,arguments)},he=t.stackSave=function(){return(he=t.stackSave=t.asm.Db).apply(null,arguments)},de=t.stackRestore=function(){return(de=t.stackRestore=t.asm.Eb).apply(null,arguments)},jt=t.stackAlloc=function(){return(jt=t.stackAlloc=t.asm.Fb).apply(null,arguments)},Ft=t.___cxa_can_catch=function(){return(Ft=t.___cxa_can_catch=t.asm.Gb).apply(null,arguments)},Jt=t.___cxa_is_pointer_type=function(){return(Jt=t.___cxa_is_pointer_type=t.asm.Hb).apply(null,arguments)},Zt=t.dynCall_j=function(){return(Zt=t.dynCall_j=t.asm.Ib).apply(null,arguments)},en=t.dynCall_iiiiij=function(){return(en=t.dynCall_iiiiij=t.asm.Jb).apply(null,arguments)},tn=t.dynCall_jii=function(){return(tn=t.dynCall_jii=t.asm.Kb).apply(null,arguments)},nn=t.dynCall_viiiiij=function(){return(nn=t.dynCall_viiiiij=t.asm.Lb).apply(null,arguments)},rn=t.dynCall_vjji=function(){return(rn=t.dynCall_vjji=t.asm.Mb).apply(null,arguments)},on=t.dynCall_viiijjjii=function(){return(on=t.dynCall_viiijjjii=t.asm.Nb).apply(null,arguments)},sn=t.dynCall_iij=function(){return(sn=t.dynCall_iij=t.asm.Ob).apply(null,arguments)},an=t.dynCall_ji=function(){return(an=t.dynCall_ji=t.asm.Pb).apply(null,arguments)},un=t.dynCall_iiiiiij=function(){return(un=t.dynCall_iiiiiij=t.asm.Qb).apply(null,arguments)},ln=t.dynCall_iiij=function(){return(ln=t.dynCall_iiij=t.asm.Rb).apply(null,arguments)};function cn(){function x(){if(!Ct&&(Ct=!0,t.calledRun=!0,!be)&&(M||rt(Ve),e(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),!M)){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;){var P=t.postRun.shift();Qe.unshift(P)}rt(Qe)}}if(!(0{var u,l=(u=(u=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(d){var s,p,f;d=d||{},s||(s=d!==void 0?d:{}),s.ready=new Promise(function(E,I){p=E,f=I});var c,a,t,e,r,i,h=Object.assign({},s),g="./this.program",m=(E,I)=>{throw I},b=typeof window=="object",y=typeof importScripts=="function",w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",T="";w?(T=y?o(908).dirname(T)+"/":"//",i=()=>{r||(e=o(1384),r=o(908))},c=function(E,I){return i(),E=r.normalize(E),e.readFileSync(E,I?void 0:"utf8")},t=E=>((E=c(E,!0)).buffer||(E=new Uint8Array(E)),E),a=(E,I,L)=>{i(),E=r.normalize(E),e.readFile(E,function(z,U){z?L(z):I(U.buffer)})},1{if(v||0{var I=new XMLHttpRequest;return I.open("GET",E,!1),I.send(null),I.responseText},y&&(t=E=>{var I=new XMLHttpRequest;return I.open("GET",E,!1),I.responseType="arraybuffer",I.send(null),new Uint8Array(I.response)}),a=(E,I,L)=>{var z=new XMLHttpRequest;z.open("GET",E,!0),z.responseType="arraybuffer",z.onload=()=>{z.status==200||z.status==0&&z.response?I(z.response):L()},z.onerror=L,z.send(null)});var S,A=s.print||console.log.bind(console),O=s.printErr||console.warn.bind(console);Object.assign(s,h),h=null,s.thisProgram&&(g=s.thisProgram),s.quit&&(m=s.quit),s.wasmBinary&&(S=s.wasmBinary);var v=s.noExitRuntime||!1;typeof WebAssembly!="object"&&Pe("no native wasm support detected");var M,F,R,$,N,G,D=!1,j=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Q(E,I,L){var z=(I>>>=0)+L;for(L=I;E[L]&&!(L>=z);)++L;if(16(U=(240&U)==224?(15&U)<<12|H<<6|Y:(7&U)<<18|H<<12|Y<<6|63&E[I++])?z+=String.fromCharCode(U):(U-=65536,z+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else z+=String.fromCharCode(U)}return z}function X(E,I){return(E>>>=0)?Q($,E,I):""}function Z(E,I,L,z){if(!(0>>=0;z=L+z-1;for(var H=0;H=Y&&(Y=65536+((1023&Y)<<10)|1023&E.charCodeAt(++H)),127>=Y){if(L>=z)break;I[L++>>>0]=Y}else{if(2047>=Y){if(L+1>=z)break;I[L++>>>0]=192|Y>>6}else{if(65535>=Y){if(L+2>=z)break;I[L++>>>0]=224|Y>>12}else{if(L+3>=z)break;I[L++>>>0]=240|Y>>18,I[L++>>>0]=128|Y>>12&63}I[L++>>>0]=128|Y>>6&63}I[L++>>>0]=128|63&Y}}return I[L>>>0]=0,L-U}function ee(E){for(var I=0,L=0;L=z?I++:2047>=z?I+=2:55296<=z&&57343>=z?(I+=4,++L):I+=3}return I}function ue(){var E=M.buffer;F=E,s.HEAP8=R=new Int8Array(E),s.HEAP16=new Int16Array(E),s.HEAP32=N=new Int32Array(E),s.HEAPU8=$=new Uint8Array(E),s.HEAPU16=new Uint16Array(E),s.HEAPU32=G=new Uint32Array(E),s.HEAPF32=new Float32Array(E),s.HEAPF64=new Float64Array(E)}var Ae,ve=[],oe=[],we=[],be=[],ke=0;function Le(){var E=s.preRun.shift();ve.unshift(E)}var xe,Fe=0,Ce=null;function Pe(E){throw s.onAbort&&s.onAbort(E),O(E="Aborted("+E+")"),D=!0,E=new WebAssembly.RuntimeError(E+". Build with -sASSERTIONS for more info."),f(E),E}function Oe(){return xe.startsWith("data:application/octet-stream;base64,")}if(xe="ort-wasm.wasm",!Oe()){var Be=xe;xe=s.locateFile?s.locateFile(Be,T):T+Be}function Ge(){var E=xe;try{if(E==xe&&S)return new Uint8Array(S);if(t)return t(E);throw"both async and sync fetching of the wasm failed"}catch(I){Pe(I)}}function Ve(E){this.name="ExitStatus",this.message="Program terminated with exit("+E+")",this.status=E}function Xe(E){for(;0>2>>>0]=I},this.Eb=function(){return G[this.zb+4>>2>>>0]},this.Sb=function(I){G[this.zb+8>>2>>>0]=I},this.Wb=function(){return G[this.zb+8>>2>>>0]},this.Tb=function(){N[this.zb>>2>>>0]=0},this.Ib=function(I){R[this.zb+12>>0>>>0]=I?1:0},this.Pb=function(){return R[this.zb+12>>0>>>0]!=0},this.Jb=function(I){R[this.zb+13>>0>>>0]=I?1:0},this.Lb=function(){return R[this.zb+13>>0>>>0]!=0},this.Rb=function(I,L){this.Fb(0),this.Ub(I),this.Sb(L),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){N[this.zb>>2>>>0]+=1},this.Xb=function(){var I=N[this.zb>>2>>>0];return N[this.zb>>2>>>0]=I-1,I===1},this.Fb=function(I){G[this.zb+16>>2>>>0]=I},this.Ob=function(){return G[this.zb+16>>2>>>0]},this.Qb=function(){if(mt(this.Eb()))return G[this.Db>>2>>>0];var I=this.Ob();return I!==0?I:this.Db}}function je(E){return ot(new Me(E).zb)}var Ye=[];function ge(E){var I=Ye[E];return I||(E>=Ye.length&&(Ye.length=E+1),Ye[E]=I=Ae.get(E)),I}function pt(E){var I=ee(E)+1,L=Te(I);return L&&Z(E,R,L,I),L}var lt={};function Et(){if(!Je){var E,I={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(E in lt)lt[E]===void 0?delete I[E]:I[E]=lt[E];var L=[];for(E in I)L.push(E+"="+I[E]);Je=L}return Je}var Je,ct=[null,[],[]];function dt(E,I){var L=ct[E];I===0||I===10?((E===1?A:O)(Q(L,0)),L.length=0):L.push(I)}var Re=0;function it(E){return E%4==0&&(E%100!=0||E%400==0)}var re=[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(E,I,L,z){function U(q,_e,Ee){for(q=typeof q=="number"?q.toString():q||"";q.length<_e;)q=Ee[0]+q;return q}function H(q,_e){return U(q,_e,"0")}function Y(q,_e){function Ee(et){return 0>et?-1:0We-q.getDate())){q.setDate(q.getDate()+_e);break}_e-=We-q.getDate()+1,q.setDate(1),11>Ee?q.setMonth(Ee+1):(q.setMonth(0),q.setFullYear(q.getFullYear()+1))}return Ee=new Date(q.getFullYear()+1,0,4),_e=te(new Date(q.getFullYear(),0,4)),Ee=te(Ee),0>=Y(_e,q)?0>=Y(Ee,q)?q.getFullYear()+1:q.getFullYear():q.getFullYear()-1}var ce=N[z+40>>2>>>0];for(var Se in z={$b:N[z>>2>>>0],Zb:N[z+4>>2>>>0],Gb:N[z+8>>2>>>0],Kb:N[z+12>>2>>>0],Hb:N[z+16>>2>>>0],Cb:N[z+20>>2>>>0],Ab:N[z+24>>2>>>0],Bb:N[z+28>>2>>>0],bc:N[z+32>>2>>>0],Yb:N[z+36>>2>>>0],ac:ce?X(ce):""},L=X(L),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"})L=L.replace(new RegExp(Se,"g"),ce[Se]);var $e="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ne="January February March April May June July August September October November December".split(" ");for(Se in ce={"%a":function(q){return $e[q.Ab].substring(0,3)},"%A":function(q){return $e[q.Ab]},"%b":function(q){return Ne[q.Hb].substring(0,3)},"%B":function(q){return Ne[q.Hb]},"%C":function(q){return H((q.Cb+1900)/100|0,2)},"%d":function(q){return H(q.Kb,2)},"%e":function(q){return U(q.Kb,2," ")},"%g":function(q){return J(q).toString().substring(2)},"%G":function(q){return J(q)},"%H":function(q){return H(q.Gb,2)},"%I":function(q){return(q=q.Gb)==0?q=12:12q.Gb?"AM":"PM"},"%S":function(q){return H(q.$b,2)},"%t":function(){return" "},"%u":function(q){return q.Ab||7},"%U":function(q){return H(Math.floor((q.Bb+7-q.Ab)/7),2)},"%V":function(q){var _e=Math.floor((q.Bb+7-(q.Ab+6)%7)/7);if(2>=(q.Ab+371-q.Bb-2)%7&&_e++,_e)_e==53&&((Ee=(q.Ab+371-q.Bb)%7)==4||Ee==3&&it(q.Cb)||(_e=1));else{_e=52;var Ee=(q.Ab+7-q.Bb-1)%7;(Ee==4||Ee==5&&it(q.Cb%400-1))&&_e++}return H(_e,2)},"%w":function(q){return q.Ab},"%W":function(q){return H(Math.floor((q.Bb+7-(q.Ab+6)%7)/7),2)},"%y":function(q){return(q.Cb+1900).toString().substring(2)},"%Y":function(q){return q.Cb+1900},"%z":function(q){var _e=0<=(q=q.Yb);return q=Math.abs(q)/60,(_e?"+":"-")+("0000"+(q/60*100+q%60)).slice(-4)},"%Z":function(q){return q.ac},"%%":function(){return"%"}},L=L.replace(/%%/g,"\0\0"),ce)L.includes(Se)&&(L=L.replace(new RegExp(Se,"g"),ce[Se](z)));return Se=function(q){var _e=Array(ee(q)+1);return Z(q,_e,0,_e.length),_e}(L=L.replace(/\0\0/g,"%")),Se.length>I?0:(R.set(Se,E>>>0),Se.length-1)}var kt={a:function(E){return Te(E+24)+24},m:function(E){return(E=new Me(E)).Pb()||(E.Ib(!0),qe--),E.Jb(!1),Qe.push(E),E.Nb(),E.Qb()},ia:function(E){throw O("Unexpected exception thrown, this is not properly supported - aborting"),D=!0,E},w:function(){ae(0);var E=Qe.pop();if(E.Xb()&&!E.Lb()){var I=E.Wb();I&&ge(I)(E.Db),je(E.Db)}Ue=0},d:function(){var E=Ue;if(!E)return Re=0;var I=new Me(E);I.Fb(E);var L=I.Eb();if(!L)return Re=0,E;for(var z=Array.prototype.slice.call(arguments),U=0;U>>2]+4294967296*N[E+4>>>2])),N[I>>2>>>0]=E.getUTCSeconds(),N[I+4>>2>>>0]=E.getUTCMinutes(),N[I+8>>2>>>0]=E.getUTCHours(),N[I+12>>2>>>0]=E.getUTCDate(),N[I+16>>2>>>0]=E.getUTCMonth(),N[I+20>>2>>>0]=E.getUTCFullYear()-1900,N[I+24>>2>>>0]=E.getUTCDay(),N[I+28>>2>>>0]=(E.getTime()-Date.UTC(E.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(E,I){E=new Date(1e3*(G[E>>>2]+4294967296*N[E+4>>>2])),N[I>>2>>>0]=E.getSeconds(),N[I+4>>2>>>0]=E.getMinutes(),N[I+8>>2>>>0]=E.getHours(),N[I+12>>2>>>0]=E.getDate(),N[I+16>>2>>>0]=E.getMonth(),N[I+20>>2>>>0]=E.getFullYear()-1900,N[I+24>>2>>>0]=E.getDay();var L=new Date(E.getFullYear(),0,1);N[I+28>>2>>>0]=(E.getTime()-L.getTime())/864e5|0,N[I+36>>2>>>0]=-60*E.getTimezoneOffset();var z=new Date(E.getFullYear(),6,1).getTimezoneOffset();L=L.getTimezoneOffset(),N[I+32>>2>>>0]=0|(z!=L&&E.getTimezoneOffset()==Math.min(L,z))},Fa:function(E){var I=new Date(N[E+20>>2>>>0]+1900,N[E+16>>2>>>0],N[E+12>>2>>>0],N[E+8>>2>>>0],N[E+4>>2>>>0],N[E>>2>>>0],0),L=N[E+32>>2>>>0],z=I.getTimezoneOffset(),U=new Date(I.getFullYear(),0,1),H=new Date(I.getFullYear(),6,1).getTimezoneOffset(),Y=U.getTimezoneOffset(),te=Math.min(Y,H);return 0>L?N[E+32>>2>>>0]=+(H!=Y&&te==z):0>2>>>0]=I.getDay(),N[E+28>>2>>>0]=(I.getTime()-U.getTime())/864e5|0,N[E>>2>>>0]=I.getSeconds(),N[E+4>>2>>>0]=I.getMinutes(),N[E+8>>2>>>0]=I.getHours(),N[E+12>>2>>>0]=I.getDate(),N[E+16>>2>>>0]=I.getMonth(),I.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function E(I,L,z){E.Vb||(E.Vb=!0,function(U,H,Y){function te(Ne){return(Ne=Ne.toTimeString().match(/\(([A-Za-z ]+)\)$/))?Ne[1]:"GMT"}var J=new Date().getFullYear(),ce=new Date(J,0,1),Se=new Date(J,6,1);J=ce.getTimezoneOffset();var $e=Se.getTimezoneOffset();N[U>>2>>>0]=60*Math.max(J,$e),N[H>>2>>>0]=+(J!=$e),U=te(ce),H=te(Se),U=pt(U),H=pt(H),$e>2>>>0]=U,G[Y+4>>2>>>0]=H):(G[Y>>2>>>0]=H,G[Y+4>>2>>>0]=U)}(I,L,z))},B:function(){Pe("")},ma:function(){return 4294901760},I:w?()=>{var E=process.hrtime();return 1e3*E[0]+E[1]/1e6}:()=>performance.now(),xa:function(E,I,L){$.copyWithin(E>>>0,I>>>0,I+L>>>0)},G:function(E){var I=$.length;if(4294901760<(E>>>=0))return!1;for(var L=1;4>=L;L*=2){var z=I*(1+.2/L);z=Math.min(z,E+100663296);var U=Math;z=Math.max(E,z),U=U.min.call(U,4294901760,z+(65536-z%65536)%65536);e:{try{M.grow(U-F.byteLength+65535>>>16),ue();var H=1;break e}catch{}H=void 0}if(H)return!0}return!1},va:function(E,I){var L=0;return Et().forEach(function(z,U){var H=I+L;for(U=G[E+4*U>>2>>>0]=H,H=0;H>0>>>0]=z.charCodeAt(H);R[U>>0>>>0]=0,L+=z.length+1}),0},wa:function(E,I){var L=Et();G[E>>2>>>0]=L.length;var z=0;return L.forEach(function(U){z+=U.length+1}),G[I>>2>>>0]=z,0},ba:function(E){v||0>2>>>0],te=G[I+4>>2>>>0];I+=8;for(var J=0;J>>0]);U+=te}return G[z>>2>>>0]=U,0},c:function(){return Re},ja:function E(I,L){E.Mb||(E.Mb=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var U=new Uint8Array(1);return()=>(crypto.getRandomValues(U),U[0])}if(w)try{var H=o(Object(function(){var Y=new Error("Cannot find module 'crypto'");throw Y.code="MODULE_NOT_FOUND",Y}()));return()=>H.randomBytes(1)[0]}catch{}return()=>Pe("randomDevice")}());for(var z=0;z>0>>>0]=E.Mb();return 0},ea:function(E,I,L){var z=ie();try{return ge(E)(I,L)}catch(U){if(se(z),U!==U+0)throw U;ae(1,0)}},fa:function(E,I,L){var z=ie();try{return ge(E)(I,L)}catch(U){if(se(z),U!==U+0)throw U;ae(1,0)}},J:function(E){var I=ie();try{return ge(E)()}catch(L){if(se(I),L!==L+0)throw L;ae(1,0)}},e:function(E,I){var L=ie();try{return ge(E)(I)}catch(z){if(se(L),z!==z+0)throw z;ae(1,0)}},N:function(E,I,L){var z=ie();try{return ge(E)(I,L)}catch(U){if(se(z),U!==U+0)throw U;ae(1,0)}},O:function(E,I,L){var z=ie();try{return ge(E)(I,L)}catch(U){if(se(z),U!==U+0)throw U;ae(1,0)}},j:function(E,I,L){var z=ie();try{return ge(E)(I,L)}catch(U){if(se(z),U!==U+0)throw U;ae(1,0)}},o:function(E,I,L,z){var U=ie();try{return ge(E)(I,L,z)}catch(H){if(se(U),H!==H+0)throw H;ae(1,0)}},p:function(E,I,L,z,U){var H=ie();try{return ge(E)(I,L,z,U)}catch(Y){if(se(H),Y!==Y+0)throw Y;ae(1,0)}},M:function(E,I,L,z,U,H){var Y=ie();try{return ge(E)(I,L,z,U,H)}catch(te){if(se(Y),te!==te+0)throw te;ae(1,0)}},r:function(E,I,L,z,U,H){var Y=ie();try{return ge(E)(I,L,z,U,H)}catch(te){if(se(Y),te!==te+0)throw te;ae(1,0)}},v:function(E,I,L,z,U,H,Y){var te=ie();try{return ge(E)(I,L,z,U,H,Y)}catch(J){if(se(te),J!==J+0)throw J;ae(1,0)}},K:function(E,I,L,z,U,H,Y,te){var J=ie();try{return ge(E)(I,L,z,U,H,Y,te)}catch(ce){if(se(J),ce!==ce+0)throw ce;ae(1,0)}},D:function(E,I,L,z,U,H,Y,te,J,ce,Se,$e){var Ne=ie();try{return ge(E)(I,L,z,U,H,Y,te,J,ce,Se,$e)}catch(q){if(se(Ne),q!==q+0)throw q;ae(1,0)}},X:function(E,I,L,z,U,H,Y,te){var J=ie();try{return At(E,I,L,z,U,H,Y,te)}catch(ce){if(se(J),ce!==ce+0)throw ce;ae(1,0)}},V:function(E,I,L,z,U,H,Y){var te=ie();try{return bt(E,I,L,z,U,H,Y)}catch(J){if(se(te),J!==J+0)throw J;ae(1,0)}},U:function(E,I,L,z,U){var H=ie();try{return Ot(E,I,L,z,U)}catch(Y){if(se(H),Y!==Y+0)throw Y;ae(1,0)}},Z:function(E,I,L,z){var U=ie();try{return xt(E,I,L,z)}catch(H){if(se(U),H!==H+0)throw H;ae(1,0)}},W:function(E){var I=ie();try{return _t(E)}catch(L){if(se(I),L!==L+0)throw L;ae(1,0)}},Y:function(E,I){var L=ie();try{return St(E,I)}catch(z){if(se(L),z!==z+0)throw z;ae(1,0)}},T:function(E,I,L){var z=ie();try{return yt(E,I,L)}catch(U){if(se(z),U!==U+0)throw U;ae(1,0)}},f:function(E){var I=ie();try{ge(E)()}catch(L){if(se(I),L!==L+0)throw L;ae(1,0)}},q:function(E,I){var L=ie();try{ge(E)(I)}catch(z){if(se(L),z!==z+0)throw z;ae(1,0)}},h:function(E,I,L){var z=ie();try{ge(E)(I,L)}catch(U){if(se(z),U!==U+0)throw U;ae(1,0)}},da:function(E,I,L,z){var U=ie();try{ge(E)(I,L,z)}catch(H){if(se(U),H!==H+0)throw H;ae(1,0)}},l:function(E,I,L,z){var U=ie();try{ge(E)(I,L,z)}catch(H){if(se(U),H!==H+0)throw H;ae(1,0)}},t:function(E,I,L,z,U){var H=ie();try{ge(E)(I,L,z,U)}catch(Y){if(se(H),Y!==Y+0)throw Y;ae(1,0)}},u:function(E,I,L,z,U,H){var Y=ie();try{ge(E)(I,L,z,U,H)}catch(te){if(se(Y),te!==te+0)throw te;ae(1,0)}},x:function(E,I,L,z,U,H,Y){var te=ie();try{ge(E)(I,L,z,U,H,Y)}catch(J){if(se(te),J!==J+0)throw J;ae(1,0)}},z:function(E,I,L,z,U,H,Y,te){var J=ie();try{ge(E)(I,L,z,U,H,Y,te)}catch(ce){if(se(J),ce!==ce+0)throw ce;ae(1,0)}},ga:function(E,I,L,z,U,H,Y,te,J){var ce=ie();try{ge(E)(I,L,z,U,H,Y,te,J)}catch(Se){if(se(ce),Se!==Se+0)throw Se;ae(1,0)}},A:function(E,I,L,z,U,H,Y,te,J,ce,Se){var $e=ie();try{ge(E)(I,L,z,U,H,Y,te,J,ce,Se)}catch(Ne){if(se($e),Ne!==Ne+0)throw Ne;ae(1,0)}},C:function(E,I,L,z,U,H,Y,te,J,ce,Se,$e,Ne,q,_e,Ee){var We=ie();try{ge(E)(I,L,z,U,H,Y,te,J,ce,Se,$e,Ne,q,_e,Ee)}catch(et){if(se(We),et!==et+0)throw et;ae(1,0)}},aa:function(E,I,L,z,U,H,Y,te){var J=ie();try{wt(E,I,L,z,U,H,Y,te)}catch(ce){if(se(J),ce!==ce+0)throw ce;ae(1,0)}},_:function(E,I,L,z,U,H,Y,te,J,ce,Se,$e){var Ne=ie();try{vt(E,I,L,z,U,H,Y,te,J,ce,Se,$e)}catch(q){if(se(Ne),q!==q+0)throw q;ae(1,0)}},$:function(E,I,L,z,U,H){var Y=ie();try{Tt(E,I,L,z,U,H)}catch(te){if(se(Y),te!==te+0)throw te;ae(1,0)}},n:function(E){return E},F:function(E){Re=E},ha:Mt,y:function(E,I,L,z){return Mt(E,I,L,z)}};(function(){function E(U){s.asm=U.exports,M=s.asm.Ka,ue(),Ae=s.asm.ib,oe.unshift(s.asm.La),Fe--,s.monitorRunDependencies&&s.monitorRunDependencies(Fe),Fe==0&&Ce&&(U=Ce,Ce=null,U())}function I(U){E(U.instance)}function L(U){return function(){if(!S&&(b||y)){if(typeof fetch=="function"&&!xe.startsWith("file://"))return fetch(xe,{credentials:"same-origin"}).then(function(H){if(!H.ok)throw"failed to load wasm binary file at '"+xe+"'";return H.arrayBuffer()}).catch(function(){return Ge()});if(a)return new Promise(function(H,Y){a(xe,function(te){H(new Uint8Array(te))},Y)})}return Promise.resolve().then(function(){return Ge()})}().then(function(H){return WebAssembly.instantiate(H,z)}).then(function(H){return H}).then(U,function(H){O("failed to asynchronously prepare wasm: "+H),Pe(H)})}var z={a:kt};if(Fe++,s.monitorRunDependencies&&s.monitorRunDependencies(Fe),s.instantiateWasm)try{return s.instantiateWasm(z,E)}catch(U){return O("Module.instantiateWasm callback failed with error: "+U),!1}(S||typeof WebAssembly.instantiateStreaming!="function"||Oe()||xe.startsWith("file://")||w||typeof fetch!="function"?L(I):fetch(xe,{credentials:"same-origin"}).then(function(U){return WebAssembly.instantiateStreaming(U,z).then(I,function(H){return O("wasm streaming compile failed: "+H),O("falling back to ArrayBuffer instantiation"),L(I)})})).catch(f)})(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm.La).apply(null,arguments)},s._OrtInit=function(){return(s._OrtInit=s.asm.Ma).apply(null,arguments)},s._OrtCreateSessionOptions=function(){return(s._OrtCreateSessionOptions=s.asm.Na).apply(null,arguments)},s._OrtAppendExecutionProvider=function(){return(s._OrtAppendExecutionProvider=s.asm.Oa).apply(null,arguments)},s._OrtAddSessionConfigEntry=function(){return(s._OrtAddSessionConfigEntry=s.asm.Pa).apply(null,arguments)},s._OrtReleaseSessionOptions=function(){return(s._OrtReleaseSessionOptions=s.asm.Qa).apply(null,arguments)},s._OrtCreateSession=function(){return(s._OrtCreateSession=s.asm.Ra).apply(null,arguments)},s._OrtReleaseSession=function(){return(s._OrtReleaseSession=s.asm.Sa).apply(null,arguments)},s._OrtGetInputCount=function(){return(s._OrtGetInputCount=s.asm.Ta).apply(null,arguments)},s._OrtGetOutputCount=function(){return(s._OrtGetOutputCount=s.asm.Ua).apply(null,arguments)},s._OrtGetInputName=function(){return(s._OrtGetInputName=s.asm.Va).apply(null,arguments)},s._OrtGetOutputName=function(){return(s._OrtGetOutputName=s.asm.Wa).apply(null,arguments)},s._OrtFree=function(){return(s._OrtFree=s.asm.Xa).apply(null,arguments)},s._OrtCreateTensor=function(){return(s._OrtCreateTensor=s.asm.Ya).apply(null,arguments)},s._OrtGetTensorData=function(){return(s._OrtGetTensorData=s.asm.Za).apply(null,arguments)},s._OrtReleaseTensor=function(){return(s._OrtReleaseTensor=s.asm._a).apply(null,arguments)},s._OrtCreateRunOptions=function(){return(s._OrtCreateRunOptions=s.asm.$a).apply(null,arguments)},s._OrtAddRunConfigEntry=function(){return(s._OrtAddRunConfigEntry=s.asm.ab).apply(null,arguments)},s._OrtReleaseRunOptions=function(){return(s._OrtReleaseRunOptions=s.asm.bb).apply(null,arguments)},s._OrtRun=function(){return(s._OrtRun=s.asm.cb).apply(null,arguments)},s._OrtEndProfiling=function(){return(s._OrtEndProfiling=s.asm.db).apply(null,arguments)};var Ze,Te=s._malloc=function(){return(Te=s._malloc=s.asm.eb).apply(null,arguments)},ot=s._free=function(){return(ot=s._free=s.asm.fb).apply(null,arguments)},ft=s._fflush=function(){return(ft=s._fflush=s.asm.gb).apply(null,arguments)},st=s.___funcs_on_exit=function(){return(st=s.___funcs_on_exit=s.asm.hb).apply(null,arguments)},ae=s._setThrew=function(){return(ae=s._setThrew=s.asm.jb).apply(null,arguments)},ie=s.stackSave=function(){return(ie=s.stackSave=s.asm.kb).apply(null,arguments)},se=s.stackRestore=function(){return(se=s.stackRestore=s.asm.lb).apply(null,arguments)},gt=s.stackAlloc=function(){return(gt=s.stackAlloc=s.asm.mb).apply(null,arguments)},at=s.___cxa_can_catch=function(){return(at=s.___cxa_can_catch=s.asm.nb).apply(null,arguments)},mt=s.___cxa_is_pointer_type=function(){return(mt=s.___cxa_is_pointer_type=s.asm.ob).apply(null,arguments)},_t=s.dynCall_j=function(){return(_t=s.dynCall_j=s.asm.pb).apply(null,arguments)},bt=s.dynCall_iiiiij=function(){return(bt=s.dynCall_iiiiij=s.asm.qb).apply(null,arguments)},yt=s.dynCall_jii=function(){return(yt=s.dynCall_jii=s.asm.rb).apply(null,arguments)},wt=s.dynCall_viiiiij=function(){return(wt=s.dynCall_viiiiij=s.asm.sb).apply(null,arguments)},Tt=s.dynCall_vjji=function(){return(Tt=s.dynCall_vjji=s.asm.tb).apply(null,arguments)},vt=s.dynCall_viiijjjii=function(){return(vt=s.dynCall_viiijjjii=s.asm.ub).apply(null,arguments)},xt=s.dynCall_iij=function(){return(xt=s.dynCall_iij=s.asm.vb).apply(null,arguments)},St=s.dynCall_ji=function(){return(St=s.dynCall_ji=s.asm.wb).apply(null,arguments)},At=s.dynCall_iiiiiij=function(){return(At=s.dynCall_iiiiiij=s.asm.xb).apply(null,arguments)},Ot=s.dynCall_iiij=function(){return(Ot=s.dynCall_iiij=s.asm.yb).apply(null,arguments)};function Pt(){function E(){if(!Ze&&(Ze=!0,s.calledRun=!0,!D)){if(Xe(oe),p(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;){var I=s.postRun.shift();be.unshift(I)}Xe(be)}}if(!(0{_.exports=function(n,o){for(var u=new Array(arguments.length-1),l=0,d=2,s=!0;d{var o=n;o.length=function(p){var f=p.length;if(!f)return 0;for(var c=0;--f%4>1&&p.charAt(f)==="=";)++c;return Math.ceil(3*p.length)/4-c};for(var u=new Array(64),l=new Array(123),d=0;d<64;)l[u[d]=d<26?d+65:d<52?d+71:d<62?d-4:d-59|43]=d++;o.encode=function(p,f,c){for(var a,t=null,e=[],r=0,i=0;f>2],a=(3&h)<<4,i=1;break;case 1:e[r++]=u[a|h>>4],a=(15&h)<<2,i=2;break;case 2:e[r++]=u[a|h>>6],e[r++]=u[63&h],i=0}r>8191&&((t||(t=[])).push(String.fromCharCode.apply(String,e)),r=0)}return i&&(e[r++]=u[a],e[r++]=61,i===1&&(e[r++]=61)),t?(r&&t.push(String.fromCharCode.apply(String,e.slice(0,r))),t.join("")):String.fromCharCode.apply(String,e.slice(0,r))};var s="invalid encoding";o.decode=function(p,f,c){for(var a,t=c,e=0,r=0;r1)break;if((i=l[i])===void 0)throw Error(s);switch(e){case 0:a=i,e=1;break;case 1:f[c++]=a<<2|(48&i)>>4,a=i,e=2;break;case 2:f[c++]=(15&a)<<4|(60&i)>>2,a=i,e=3;break;case 3:f[c++]=(3&a)<<6|i,e=0}}if(e===1)throw Error(s);return c-t},o.test=function(p){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(p)}},9211:_=>{function n(){this._listeners={}}_.exports=n,n.prototype.on=function(o,u,l){return(this._listeners[o]||(this._listeners[o]=[])).push({fn:u,ctx:l||this}),this},n.prototype.off=function(o,u){if(o===void 0)this._listeners={};else if(u===void 0)this._listeners[o]=[];else for(var l=this._listeners[o],d=0;d{function n(s){return typeof Float32Array<"u"?function(){var p=new Float32Array([-0]),f=new Uint8Array(p.buffer),c=f[3]===128;function a(i,h,g){p[0]=i,h[g]=f[0],h[g+1]=f[1],h[g+2]=f[2],h[g+3]=f[3]}function t(i,h,g){p[0]=i,h[g]=f[3],h[g+1]=f[2],h[g+2]=f[1],h[g+3]=f[0]}function e(i,h){return f[0]=i[h],f[1]=i[h+1],f[2]=i[h+2],f[3]=i[h+3],p[0]}function r(i,h){return f[3]=i[h],f[2]=i[h+1],f[1]=i[h+2],f[0]=i[h+3],p[0]}s.writeFloatLE=c?a:t,s.writeFloatBE=c?t:a,s.readFloatLE=c?e:r,s.readFloatBE=c?r:e}():function(){function p(c,a,t,e){var r=a<0?1:0;if(r&&(a=-a),a===0)c(1/a>0?0:2147483648,t,e);else if(isNaN(a))c(2143289344,t,e);else if(a>34028234663852886e22)c((r<<31|2139095040)>>>0,t,e);else if(a<11754943508222875e-54)c((r<<31|Math.round(a/1401298464324817e-60))>>>0,t,e);else{var i=Math.floor(Math.log(a)/Math.LN2);c((r<<31|i+127<<23|8388607&Math.round(a*Math.pow(2,-i)*8388608))>>>0,t,e)}}function f(c,a,t){var e=c(a,t),r=2*(e>>31)+1,i=e>>>23&255,h=8388607&e;return i===255?h?NaN:r*(1/0):i===0?1401298464324817e-60*r*h:r*Math.pow(2,i-150)*(h+8388608)}s.writeFloatLE=p.bind(null,o),s.writeFloatBE=p.bind(null,u),s.readFloatLE=f.bind(null,l),s.readFloatBE=f.bind(null,d)}(),typeof Float64Array<"u"?function(){var p=new Float64Array([-0]),f=new Uint8Array(p.buffer),c=f[7]===128;function a(i,h,g){p[0]=i,h[g]=f[0],h[g+1]=f[1],h[g+2]=f[2],h[g+3]=f[3],h[g+4]=f[4],h[g+5]=f[5],h[g+6]=f[6],h[g+7]=f[7]}function t(i,h,g){p[0]=i,h[g]=f[7],h[g+1]=f[6],h[g+2]=f[5],h[g+3]=f[4],h[g+4]=f[3],h[g+5]=f[2],h[g+6]=f[1],h[g+7]=f[0]}function e(i,h){return f[0]=i[h],f[1]=i[h+1],f[2]=i[h+2],f[3]=i[h+3],f[4]=i[h+4],f[5]=i[h+5],f[6]=i[h+6],f[7]=i[h+7],p[0]}function r(i,h){return f[7]=i[h],f[6]=i[h+1],f[5]=i[h+2],f[4]=i[h+3],f[3]=i[h+4],f[2]=i[h+5],f[1]=i[h+6],f[0]=i[h+7],p[0]}s.writeDoubleLE=c?a:t,s.writeDoubleBE=c?t:a,s.readDoubleLE=c?e:r,s.readDoubleBE=c?r:e}():function(){function p(c,a,t,e,r,i){var h=e<0?1:0;if(h&&(e=-e),e===0)c(0,r,i+a),c(1/e>0?0:2147483648,r,i+t);else if(isNaN(e))c(0,r,i+a),c(2146959360,r,i+t);else if(e>17976931348623157e292)c(0,r,i+a),c((h<<31|2146435072)>>>0,r,i+t);else{var g;if(e<22250738585072014e-324)c((g=e/5e-324)>>>0,r,i+a),c((h<<31|g/4294967296)>>>0,r,i+t);else{var m=Math.floor(Math.log(e)/Math.LN2);m===1024&&(m=1023),c(4503599627370496*(g=e*Math.pow(2,-m))>>>0,r,i+a),c((h<<31|m+1023<<20|1048576*g&1048575)>>>0,r,i+t)}}}function f(c,a,t,e,r){var i=c(e,r+a),h=c(e,r+t),g=2*(h>>31)+1,m=h>>>20&2047,b=4294967296*(1048575&h)+i;return m===2047?b?NaN:g*(1/0):m===0?5e-324*g*b:g*Math.pow(2,m-1075)*(b+4503599627370496)}s.writeDoubleLE=p.bind(null,o,0,4),s.writeDoubleBE=p.bind(null,u,4,0),s.readDoubleLE=f.bind(null,l,0,4),s.readDoubleBE=f.bind(null,d,4,0)}(),s}function o(s,p,f){p[f]=255&s,p[f+1]=s>>>8&255,p[f+2]=s>>>16&255,p[f+3]=s>>>24}function u(s,p,f){p[f]=s>>>24,p[f+1]=s>>>16&255,p[f+2]=s>>>8&255,p[f+3]=255&s}function l(s,p){return(s[p]|s[p+1]<<8|s[p+2]<<16|s[p+3]<<24)>>>0}function d(s,p){return(s[p]<<24|s[p+1]<<16|s[p+2]<<8|s[p+3])>>>0}_.exports=n(n)},7199:module=>{function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(_){}return null}module.exports=inquire},6662:_=>{_.exports=function(n,o,u){var l=u||8192,d=l>>>1,s=null,p=l;return function(f){if(f<1||f>d)return n(f);p+f>l&&(s=n(l),p=0);var c=o.call(s,p,p+=f);return 7&p&&(p=1+(7|p)),c}}},4997:(_,n)=>{var o=n;o.length=function(u){for(var l=0,d=0,s=0;s191&&s<224?f[c++]=(31&s)<<6|63&u[l++]:s>239&&s<365?(s=((7&s)<<18|(63&u[l++])<<12|(63&u[l++])<<6|63&u[l++])-65536,f[c++]=55296+(s>>10),f[c++]=56320+(1023&s)):f[c++]=(15&s)<<12|(63&u[l++])<<6|63&u[l++],c>8191&&((p||(p=[])).push(String.fromCharCode.apply(String,f)),c=0);return p?(c&&p.push(String.fromCharCode.apply(String,f.slice(0,c))),p.join("")):String.fromCharCode.apply(String,f.slice(0,c))},o.write=function(u,l,d){for(var s,p,f=d,c=0;c>6|192,l[d++]=63&s|128):(64512&s)==55296&&(64512&(p=u.charCodeAt(c+1)))==56320?(s=65536+((1023&s)<<10)+(1023&p),++c,l[d++]=s>>18|240,l[d++]=s>>12&63|128,l[d++]=s>>6&63|128,l[d++]=63&s|128):(l[d++]=s>>12|224,l[d++]=s>>6&63|128,l[d++]=63&s|128);return d-f}},3442:(_,n)=>{n.__esModule=!0;var o=function(){function u(l){if(!l)throw new TypeError("Invalid argument; `value` has no value.");this.value=u.EMPTY,l&&u.isGuid(l)&&(this.value=l)}return u.isGuid=function(l){var d=l.toString();return l&&(l instanceof u||u.validator.test(d))},u.create=function(){return new u([u.gen(2),u.gen(1),u.gen(1),u.gen(1),u.gen(3)].join("-"))},u.createEmpty=function(){return new u("emptyguid")},u.parse=function(l){return new u(l)},u.raw=function(){return[u.gen(2),u.gen(1),u.gen(1),u.gen(1),u.gen(3)].join("-")},u.gen=function(l){for(var d="",s=0;s{_.exports=o;var n=null;try{n=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(v,M,F){this.low=0|v,this.high=0|M,this.unsigned=!!F}function u(v){return(v&&v.__isLong__)===!0}o.prototype.__isLong__,Object.defineProperty(o.prototype,"__isLong__",{value:!0}),o.isLong=u;var l={},d={};function s(v,M){var F,R,$;return M?($=0<=(v>>>=0)&&v<256)&&(R=d[v])?R:(F=f(v,(0|v)<0?-1:0,!0),$&&(d[v]=F),F):($=-128<=(v|=0)&&v<128)&&(R=l[v])?R:(F=f(v,v<0?-1:0,!1),$&&(l[v]=F),F)}function p(v,M){if(isNaN(v))return M?m:g;if(M){if(v<0)return m;if(v>=r)return S}else{if(v<=-i)return A;if(v+1>=i)return T}return v<0?p(-v,M).neg():f(v%e|0,v/e|0,M)}function f(v,M,F){return new o(v,M,F)}o.fromInt=s,o.fromNumber=p,o.fromBits=f;var c=Math.pow;function a(v,M,F){if(v.length===0)throw Error("empty string");if(v==="NaN"||v==="Infinity"||v==="+Infinity"||v==="-Infinity")return g;if(typeof M=="number"?(F=M,M=!1):M=!!M,(F=F||10)<2||360)throw Error("interior hyphen");if(R===0)return a(v.substring(1),M,F).neg();for(var $=p(c(F,8)),N=g,G=0;G>>0:this.low},O.toNumber=function(){return this.unsigned?(this.high>>>0)*e+(this.low>>>0):this.high*e+(this.low>>>0)},O.toString=function(v){if((v=v||10)<2||36>>0).toString(v);if((N=D).isZero())return j+G;for(;j.length<6;)j="0"+j;G=""+j+G}},O.getHighBits=function(){return this.high},O.getHighBitsUnsigned=function(){return this.high>>>0},O.getLowBits=function(){return this.low},O.getLowBitsUnsigned=function(){return this.low>>>0},O.getNumBitsAbs=function(){if(this.isNegative())return this.eq(A)?64:this.neg().getNumBitsAbs();for(var v=this.high!=0?this.high:this.low,M=31;M>0&&!(v&1<=0},O.isOdd=function(){return(1&this.low)==1},O.isEven=function(){return(1&this.low)==0},O.equals=function(v){return u(v)||(v=t(v)),(this.unsigned===v.unsigned||this.high>>>31!=1||v.high>>>31!=1)&&this.high===v.high&&this.low===v.low},O.eq=O.equals,O.notEquals=function(v){return!this.eq(v)},O.neq=O.notEquals,O.ne=O.notEquals,O.lessThan=function(v){return this.comp(v)<0},O.lt=O.lessThan,O.lessThanOrEqual=function(v){return this.comp(v)<=0},O.lte=O.lessThanOrEqual,O.le=O.lessThanOrEqual,O.greaterThan=function(v){return this.comp(v)>0},O.gt=O.greaterThan,O.greaterThanOrEqual=function(v){return this.comp(v)>=0},O.gte=O.greaterThanOrEqual,O.ge=O.greaterThanOrEqual,O.compare=function(v){if(u(v)||(v=t(v)),this.eq(v))return 0;var M=this.isNegative(),F=v.isNegative();return M&&!F?-1:!M&&F?1:this.unsigned?v.high>>>0>this.high>>>0||v.high===this.high&&v.low>>>0>this.low>>>0?-1:1:this.sub(v).isNegative()?-1:1},O.comp=O.compare,O.negate=function(){return!this.unsigned&&this.eq(A)?A:this.not().add(b)},O.neg=O.negate,O.add=function(v){u(v)||(v=t(v));var M=this.high>>>16,F=65535&this.high,R=this.low>>>16,$=65535&this.low,N=v.high>>>16,G=65535&v.high,D=v.low>>>16,j=0,Q=0,X=0,Z=0;return X+=(Z+=$+(65535&v.low))>>>16,Q+=(X+=R+D)>>>16,j+=(Q+=F+G)>>>16,j+=M+N,f((X&=65535)<<16|(Z&=65535),(j&=65535)<<16|(Q&=65535),this.unsigned)},O.subtract=function(v){return u(v)||(v=t(v)),this.add(v.neg())},O.sub=O.subtract,O.multiply=function(v){if(this.isZero())return g;if(u(v)||(v=t(v)),n)return f(n.mul(this.low,this.high,v.low,v.high),n.get_high(),this.unsigned);if(v.isZero())return g;if(this.eq(A))return v.isOdd()?A:g;if(v.eq(A))return this.isOdd()?A:g;if(this.isNegative())return v.isNegative()?this.neg().mul(v.neg()):this.neg().mul(v).neg();if(v.isNegative())return this.mul(v.neg()).neg();if(this.lt(h)&&v.lt(h))return p(this.toNumber()*v.toNumber(),this.unsigned);var M=this.high>>>16,F=65535&this.high,R=this.low>>>16,$=65535&this.low,N=v.high>>>16,G=65535&v.high,D=v.low>>>16,j=65535&v.low,Q=0,X=0,Z=0,ee=0;return Z+=(ee+=$*j)>>>16,X+=(Z+=R*j)>>>16,Z&=65535,X+=(Z+=$*D)>>>16,Q+=(X+=F*j)>>>16,X&=65535,Q+=(X+=R*D)>>>16,X&=65535,Q+=(X+=$*G)>>>16,Q+=M*j+F*D+R*G+$*N,f((Z&=65535)<<16|(ee&=65535),(Q&=65535)<<16|(X&=65535),this.unsigned)},O.mul=O.multiply,O.divide=function(v){if(u(v)||(v=t(v)),v.isZero())throw Error("division by zero");var M,F,R;if(n)return this.unsigned||this.high!==-2147483648||v.low!==-1||v.high!==-1?f((this.unsigned?n.div_u:n.div_s)(this.low,this.high,v.low,v.high),n.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?m:g;if(this.unsigned){if(v.unsigned||(v=v.toUnsigned()),v.gt(this))return m;if(v.gt(this.shru(1)))return y;R=m}else{if(this.eq(A))return v.eq(b)||v.eq(w)?A:v.eq(A)?b:(M=this.shr(1).div(v).shl(1)).eq(g)?v.isNegative()?b:w:(F=this.sub(v.mul(M)),R=M.add(F.div(v)));if(v.eq(A))return this.unsigned?m:g;if(this.isNegative())return v.isNegative()?this.neg().div(v.neg()):this.neg().div(v).neg();if(v.isNegative())return this.div(v.neg()).neg();R=g}for(F=this;F.gte(v);){M=Math.max(1,Math.floor(F.toNumber()/v.toNumber()));for(var $=Math.ceil(Math.log(M)/Math.LN2),N=$<=48?1:c(2,$-48),G=p(M),D=G.mul(v);D.isNegative()||D.gt(F);)D=(G=p(M-=N,this.unsigned)).mul(v);G.isZero()&&(G=b),R=R.add(G),F=F.sub(D)}return R},O.div=O.divide,O.modulo=function(v){return u(v)||(v=t(v)),n?f((this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,v.low,v.high),n.get_high(),this.unsigned):this.sub(this.div(v).mul(v))},O.mod=O.modulo,O.rem=O.modulo,O.not=function(){return f(~this.low,~this.high,this.unsigned)},O.and=function(v){return u(v)||(v=t(v)),f(this.low&v.low,this.high&v.high,this.unsigned)},O.or=function(v){return u(v)||(v=t(v)),f(this.low|v.low,this.high|v.high,this.unsigned)},O.xor=function(v){return u(v)||(v=t(v)),f(this.low^v.low,this.high^v.high,this.unsigned)},O.shiftLeft=function(v){return u(v)&&(v=v.toInt()),(v&=63)==0?this:v<32?f(this.low<>>32-v,this.unsigned):f(0,this.low<>>v|this.high<<32-v,this.high>>v,this.unsigned):f(this.high>>v-32,this.high>=0?0:-1,this.unsigned)},O.shr=O.shiftRight,O.shiftRightUnsigned=function(v){if(u(v)&&(v=v.toInt()),(v&=63)==0)return this;var M=this.high;return v<32?f(this.low>>>v|M<<32-v,M>>>v,this.unsigned):f(v===32?M:M>>>v-32,0,this.unsigned)},O.shru=O.shiftRightUnsigned,O.shr_u=O.shiftRightUnsigned,O.toSigned=function(){return this.unsigned?f(this.low,this.high,!1):this},O.toUnsigned=function(){return this.unsigned?this:f(this.low,this.high,!0)},O.toBytes=function(v){return v?this.toBytesLE():this.toBytesBE()},O.toBytesLE=function(){var v=this.high,M=this.low;return[255&M,M>>>8&255,M>>>16&255,M>>>24,255&v,v>>>8&255,v>>>16&255,v>>>24]},O.toBytesBE=function(){var v=this.high,M=this.low;return[v>>>24,v>>>16&255,v>>>8&255,255&v,M>>>24,M>>>16&255,M>>>8&255,255&M]},o.fromBytes=function(v,M,F){return F?o.fromBytesLE(v,M):o.fromBytesBE(v,M)},o.fromBytesLE=function(v,M){return new o(v[0]|v[1]<<8|v[2]<<16|v[3]<<24,v[4]|v[5]<<8|v[6]<<16|v[7]<<24,M)},o.fromBytesBE=function(v,M){return new o(v[4]<<24|v[5]<<16|v[6]<<8|v[7],v[0]<<24|v[1]<<16|v[2]<<8|v[3],M)}},1446:(_,n,o)=>{var u,l,d,s=o(2100),p=s.Reader,f=s.Writer,c=s.util,a=s.roots.default||(s.roots.default={});a.onnx=((d={}).Version=(u={},(l=Object.create(u))[u[0]="_START_VERSION"]=0,l[u[1]="IR_VERSION_2017_10_10"]=1,l[u[2]="IR_VERSION_2017_10_30"]=2,l[u[3]="IR_VERSION_2017_11_3"]=3,l[u[4]="IR_VERSION_2019_1_22"]=4,l[u[5]="IR_VERSION"]=5,l),d.AttributeProto=function(){function t(e){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],e)for(var r=Object.keys(e),i=0;i>>3){case 1:h.name=e.string();break;case 21:h.refAttrName=e.string();break;case 13:h.docString=e.string();break;case 20:h.type=e.int32();break;case 2:h.f=e.float();break;case 3:h.i=e.int64();break;case 4:h.s=e.bytes();break;case 5:h.t=a.onnx.TensorProto.decode(e,e.uint32());break;case 6:h.g=a.onnx.GraphProto.decode(e,e.uint32());break;case 7:if(h.floats&&h.floats.length||(h.floats=[]),(7&g)==2)for(var m=e.uint32()+e.pos;e.pos>>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=a.onnx.TensorProto.fromObject(e.t)}if(e.g!=null){if(typeof e.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");r.g=a.onnx.GraphProto.fromObject(e.g)}if(e.floats){if(!Array.isArray(e.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");r.floats=[];for(var i=0;i>>0,e.ints[i].high>>>0).toNumber())}if(e.strings){if(!Array.isArray(e.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(r.strings=[],i=0;i>>0,e.i.high>>>0).toNumber():e.i),e.s!=null&&e.hasOwnProperty("s")&&(i.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")&&(i.t=a.onnx.TensorProto.toObject(e.t,r)),e.g!=null&&e.hasOwnProperty("g")&&(i.g=a.onnx.GraphProto.toObject(e.g,r)),e.floats&&e.floats.length){i.floats=[];for(var g=0;g>>0,e.ints[g].high>>>0).toNumber():e.ints[g];if(e.strings&&e.strings.length)for(i.strings=[],g=0;g>>3){case 1:h.name=e.string();break;case 2:h.type=a.onnx.TypeProto.decode(e,e.uint32());break;case 3:h.docString=e.string();break;default:e.skipType(7&g)}}return h},t.decodeDelimited=function(e){return e instanceof p||(e=new p(e)),this.decode(e,e.uint32())},t.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=a.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},t.fromObject=function(e){if(e instanceof a.onnx.ValueInfoProto)return e;var r=new a.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=a.onnx.TypeProto.fromObject(e.type)}return e.docString!=null&&(r.docString=String(e.docString)),r},t.toObject=function(e,r){r||(r={});var i={};return r.defaults&&(i.name="",i.type=null,i.docString=""),e.name!=null&&e.hasOwnProperty("name")&&(i.name=e.name),e.type!=null&&e.hasOwnProperty("type")&&(i.type=a.onnx.TypeProto.toObject(e.type,r)),e.docString!=null&&e.hasOwnProperty("docString")&&(i.docString=e.docString),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),d.NodeProto=function(){function t(e){if(this.input=[],this.output=[],this.attribute=[],e)for(var r=Object.keys(e),i=0;i>>3){case 1:h.input&&h.input.length||(h.input=[]),h.input.push(e.string());break;case 2:h.output&&h.output.length||(h.output=[]),h.output.push(e.string());break;case 3:h.name=e.string();break;case 4:h.opType=e.string();break;case 7:h.domain=e.string();break;case 5:h.attribute&&h.attribute.length||(h.attribute=[]),h.attribute.push(a.onnx.AttributeProto.decode(e,e.uint32()));break;case 6:h.docString=e.string();break;default:e.skipType(7&g)}}return h},t.decodeDelimited=function(e){return e instanceof p||(e=new p(e)),this.decode(e,e.uint32())},t.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:h.irVersion=e.int64();break;case 8:h.opsetImport&&h.opsetImport.length||(h.opsetImport=[]),h.opsetImport.push(a.onnx.OperatorSetIdProto.decode(e,e.uint32()));break;case 2:h.producerName=e.string();break;case 3:h.producerVersion=e.string();break;case 4:h.domain=e.string();break;case 5:h.modelVersion=e.int64();break;case 6:h.docString=e.string();break;case 7:h.graph=a.onnx.GraphProto.decode(e,e.uint32());break;case 14:h.metadataProps&&h.metadataProps.length||(h.metadataProps=[]),h.metadataProps.push(a.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return h},t.decodeDelimited=function(e){return e instanceof p||(e=new p(e)),this.decode(e,e.uint32())},t.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 i=0;i>>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=a.onnx.GraphProto.fromObject(e.graph)}if(e.metadataProps){if(!Array.isArray(e.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(r.metadataProps=[],i=0;i>>0,e.irVersion.high>>>0).toNumber():e.irVersion),e.producerName!=null&&e.hasOwnProperty("producerName")&&(i.producerName=e.producerName),e.producerVersion!=null&&e.hasOwnProperty("producerVersion")&&(i.producerVersion=e.producerVersion),e.domain!=null&&e.hasOwnProperty("domain")&&(i.domain=e.domain),e.modelVersion!=null&&e.hasOwnProperty("modelVersion")&&(typeof e.modelVersion=="number"?i.modelVersion=r.longs===String?String(e.modelVersion):e.modelVersion:i.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")&&(i.docString=e.docString),e.graph!=null&&e.hasOwnProperty("graph")&&(i.graph=a.onnx.GraphProto.toObject(e.graph,r)),e.opsetImport&&e.opsetImport.length){i.opsetImport=[];for(var g=0;g>>3){case 1:h.key=e.string();break;case 2:h.value=e.string();break;default:e.skipType(7&g)}}return h},t.decodeDelimited=function(e){return e instanceof p||(e=new p(e)),this.decode(e,e.uint32())},t.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},t.fromObject=function(e){if(e instanceof a.onnx.StringStringEntryProto)return e;var r=new a.onnx.StringStringEntryProto;return e.key!=null&&(r.key=String(e.key)),e.value!=null&&(r.value=String(e.value)),r},t.toObject=function(e,r){r||(r={});var i={};return r.defaults&&(i.key="",i.value=""),e.key!=null&&e.hasOwnProperty("key")&&(i.key=e.key),e.value!=null&&e.hasOwnProperty("value")&&(i.value=e.value),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),d.TensorAnnotation=function(){function t(e){if(this.quantParameterTensorNames=[],e)for(var r=Object.keys(e),i=0;i>>3){case 1:h.tensorName=e.string();break;case 2:h.quantParameterTensorNames&&h.quantParameterTensorNames.length||(h.quantParameterTensorNames=[]),h.quantParameterTensorNames.push(a.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return h},t.decodeDelimited=function(e){return e instanceof p||(e=new p(e)),this.decode(e,e.uint32())},t.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:h.node&&h.node.length||(h.node=[]),h.node.push(a.onnx.NodeProto.decode(e,e.uint32()));break;case 2:h.name=e.string();break;case 5:h.initializer&&h.initializer.length||(h.initializer=[]),h.initializer.push(a.onnx.TensorProto.decode(e,e.uint32()));break;case 10:h.docString=e.string();break;case 11:h.input&&h.input.length||(h.input=[]),h.input.push(a.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 12:h.output&&h.output.length||(h.output=[]),h.output.push(a.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 13:h.valueInfo&&h.valueInfo.length||(h.valueInfo=[]),h.valueInfo.push(a.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 14:h.quantizationAnnotation&&h.quantizationAnnotation.length||(h.quantizationAnnotation=[]),h.quantizationAnnotation.push(a.onnx.TensorAnnotation.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return h},t.decodeDelimited=function(e){return e instanceof p||(e=new p(e)),this.decode(e,e.uint32())},t.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(h.dims&&h.dims.length||(h.dims=[]),(7&g)==2)for(var m=e.uint32()+e.pos;e.pos>>0,e.dims[i].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=a.onnx.TensorProto.Segment.fromObject(e.segment)}if(e.floatData){if(!Array.isArray(e.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(r.floatData=[],i=0;i>>0,e.int64Data[i].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=[],i=0;i>>0,e.uint64Data[i].high>>>0).toNumber(!0))}return r},t.toObject=function(e,r){r||(r={});var i={};if((r.arrays||r.defaults)&&(i.dims=[],i.floatData=[],i.int32Data=[],i.stringData=[],i.int64Data=[],i.doubleData=[],i.uint64Data=[],i.externalData=[]),r.defaults&&(i.dataType=0,i.segment=null,i.name="",r.bytes===String?i.rawData="":(i.rawData=[],r.bytes!==Array&&(i.rawData=c.newBuffer(i.rawData))),i.docString="",i.dataLocation=r.enums===String?"DEFAULT":0),e.dims&&e.dims.length){i.dims=[];for(var h=0;h>>0,e.dims[h].high>>>0).toNumber():e.dims[h]}if(e.dataType!=null&&e.hasOwnProperty("dataType")&&(i.dataType=e.dataType),e.segment!=null&&e.hasOwnProperty("segment")&&(i.segment=a.onnx.TensorProto.Segment.toObject(e.segment,r)),e.floatData&&e.floatData.length)for(i.floatData=[],h=0;h>>0,e.int64Data[h].high>>>0).toNumber():e.int64Data[h];if(e.name!=null&&e.hasOwnProperty("name")&&(i.name=e.name),e.rawData!=null&&e.hasOwnProperty("rawData")&&(i.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(i.doubleData=[],h=0;h>>0,e.uint64Data[h].high>>>0).toNumber(!0):e.uint64Data[h];if(e.docString!=null&&e.hasOwnProperty("docString")&&(i.docString=e.docString),e.externalData&&e.externalData.length)for(i.externalData=[],h=0;h>>3){case 1:g.begin=r.int64();break;case 2:g.end=r.int64();break;default:r.skipType(7&m)}}return g},e.decodeDelimited=function(r){return r instanceof p||(r=new p(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 a.onnx.TensorProto.Segment)return r;var i=new a.onnx.TensorProto.Segment;return r.begin!=null&&(c.Long?(i.begin=c.Long.fromValue(r.begin)).unsigned=!1:typeof r.begin=="string"?i.begin=parseInt(r.begin,10):typeof r.begin=="number"?i.begin=r.begin:typeof r.begin=="object"&&(i.begin=new c.LongBits(r.begin.low>>>0,r.begin.high>>>0).toNumber())),r.end!=null&&(c.Long?(i.end=c.Long.fromValue(r.end)).unsigned=!1:typeof r.end=="string"?i.end=parseInt(r.end,10):typeof r.end=="number"?i.end=r.end:typeof r.end=="object"&&(i.end=new c.LongBits(r.end.low>>>0,r.end.high>>>0).toNumber())),i},e.toObject=function(r,i){i||(i={});var h={};if(i.defaults){if(c.Long){var g=new c.Long(0,0,!1);h.begin=i.longs===String?g.toString():i.longs===Number?g.toNumber():g}else h.begin=i.longs===String?"0":0;c.Long?(g=new c.Long(0,0,!1),h.end=i.longs===String?g.toString():i.longs===Number?g.toNumber():g):h.end=i.longs===String?"0":0}return r.begin!=null&&r.hasOwnProperty("begin")&&(typeof r.begin=="number"?h.begin=i.longs===String?String(r.begin):r.begin:h.begin=i.longs===String?c.Long.prototype.toString.call(r.begin):i.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"?h.end=i.longs===String?String(r.end):r.end:h.end=i.longs===String?c.Long.prototype.toString.call(r.end):i.longs===Number?new c.LongBits(r.end.low>>>0,r.end.high>>>0).toNumber():r.end),h},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),t.DataLocation=function(){var e={},r=Object.create(e);return r[e[0]="DEFAULT"]=0,r[e[1]="EXTERNAL"]=1,r}(),t}(),d.TensorShapeProto=function(){function t(e){if(this.dim=[],e)for(var r=Object.keys(e),i=0;i>>3==1?(h.dim&&h.dim.length||(h.dim=[]),h.dim.push(a.onnx.TensorShapeProto.Dimension.decode(e,e.uint32()))):e.skipType(7&g)}return h},t.decodeDelimited=function(e){return e instanceof p||(e=new p(e)),this.decode(e,e.uint32())},t.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:m.dimValue=i.int64();break;case 2:m.dimParam=i.string();break;case 3:m.denotation=i.string();break;default:i.skipType(7&b)}}return m},e.decodeDelimited=function(i){return i instanceof p||(i=new p(i)),this.decode(i,i.uint32())},e.verify=function(i){if(typeof i!="object"||i===null)return"object expected";var h={};if(i.dimValue!=null&&i.hasOwnProperty("dimValue")&&(h.value=1,!(c.isInteger(i.dimValue)||i.dimValue&&c.isInteger(i.dimValue.low)&&c.isInteger(i.dimValue.high))))return"dimValue: integer|Long expected";if(i.dimParam!=null&&i.hasOwnProperty("dimParam")){if(h.value===1)return"value: multiple values";if(h.value=1,!c.isString(i.dimParam))return"dimParam: string expected"}return i.denotation!=null&&i.hasOwnProperty("denotation")&&!c.isString(i.denotation)?"denotation: string expected":null},e.fromObject=function(i){if(i instanceof a.onnx.TensorShapeProto.Dimension)return i;var h=new a.onnx.TensorShapeProto.Dimension;return i.dimValue!=null&&(c.Long?(h.dimValue=c.Long.fromValue(i.dimValue)).unsigned=!1:typeof i.dimValue=="string"?h.dimValue=parseInt(i.dimValue,10):typeof i.dimValue=="number"?h.dimValue=i.dimValue:typeof i.dimValue=="object"&&(h.dimValue=new c.LongBits(i.dimValue.low>>>0,i.dimValue.high>>>0).toNumber())),i.dimParam!=null&&(h.dimParam=String(i.dimParam)),i.denotation!=null&&(h.denotation=String(i.denotation)),h},e.toObject=function(i,h){h||(h={});var g={};return h.defaults&&(g.denotation=""),i.dimValue!=null&&i.hasOwnProperty("dimValue")&&(typeof i.dimValue=="number"?g.dimValue=h.longs===String?String(i.dimValue):i.dimValue:g.dimValue=h.longs===String?c.Long.prototype.toString.call(i.dimValue):h.longs===Number?new c.LongBits(i.dimValue.low>>>0,i.dimValue.high>>>0).toNumber():i.dimValue,h.oneofs&&(g.value="dimValue")),i.dimParam!=null&&i.hasOwnProperty("dimParam")&&(g.dimParam=i.dimParam,h.oneofs&&(g.value="dimParam")),i.denotation!=null&&i.hasOwnProperty("denotation")&&(g.denotation=i.denotation),g},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),t}(),d.TypeProto=function(){function t(r){if(r)for(var i=Object.keys(r),h=0;h>>3){case 1:g.tensorType=a.onnx.TypeProto.Tensor.decode(r,r.uint32());break;case 6:g.denotation=r.string();break;default:r.skipType(7&m)}}return g},t.decodeDelimited=function(r){return r instanceof p||(r=new p(r)),this.decode(r,r.uint32())},t.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.tensorType!=null&&r.hasOwnProperty("tensorType")){var i=a.onnx.TypeProto.Tensor.verify(r.tensorType);if(i)return"tensorType."+i}return r.denotation!=null&&r.hasOwnProperty("denotation")&&!c.isString(r.denotation)?"denotation: string expected":null},t.fromObject=function(r){if(r instanceof a.onnx.TypeProto)return r;var i=new a.onnx.TypeProto;if(r.tensorType!=null){if(typeof r.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");i.tensorType=a.onnx.TypeProto.Tensor.fromObject(r.tensorType)}return r.denotation!=null&&(i.denotation=String(r.denotation)),i},t.toObject=function(r,i){i||(i={});var h={};return i.defaults&&(h.denotation=""),r.tensorType!=null&&r.hasOwnProperty("tensorType")&&(h.tensorType=a.onnx.TypeProto.Tensor.toObject(r.tensorType,i),i.oneofs&&(h.value="tensorType")),r.denotation!=null&&r.hasOwnProperty("denotation")&&(h.denotation=r.denotation),h},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t.Tensor=function(){function r(i){if(i)for(var h=Object.keys(i),g=0;g>>3){case 1:m.elemType=i.int32();break;case 2:m.shape=a.onnx.TensorShapeProto.decode(i,i.uint32());break;default:i.skipType(7&b)}}return m},r.decodeDelimited=function(i){return i instanceof p||(i=new p(i)),this.decode(i,i.uint32())},r.verify=function(i){if(typeof i!="object"||i===null)return"object expected";if(i.elemType!=null&&i.hasOwnProperty("elemType")&&!c.isInteger(i.elemType))return"elemType: integer expected";if(i.shape!=null&&i.hasOwnProperty("shape")){var h=a.onnx.TensorShapeProto.verify(i.shape);if(h)return"shape."+h}return null},r.fromObject=function(i){if(i instanceof a.onnx.TypeProto.Tensor)return i;var h=new a.onnx.TypeProto.Tensor;if(i.elemType!=null&&(h.elemType=0|i.elemType),i.shape!=null){if(typeof i.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");h.shape=a.onnx.TensorShapeProto.fromObject(i.shape)}return h},r.toObject=function(i,h){h||(h={});var g={};return h.defaults&&(g.elemType=0,g.shape=null),i.elemType!=null&&i.hasOwnProperty("elemType")&&(g.elemType=i.elemType),i.shape!=null&&i.hasOwnProperty("shape")&&(g.shape=a.onnx.TensorShapeProto.toObject(i.shape,h)),g},r.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},r}(),t}(),d.OperatorSetIdProto=function(){function t(e){if(e)for(var r=Object.keys(e),i=0;i>>3){case 1:h.domain=e.string();break;case 2:h.version=e.int64();break;default:e.skipType(7&g)}}return h},t.decodeDelimited=function(e){return e instanceof p||(e=new p(e)),this.decode(e,e.uint32())},t.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},t.fromObject=function(e){if(e instanceof a.onnx.OperatorSetIdProto)return e;var r=new a.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},t.toObject=function(e,r){r||(r={});var i={};if(r.defaults)if(i.domain="",c.Long){var h=new c.Long(0,0,!1);i.version=r.longs===String?h.toString():r.longs===Number?h.toNumber():h}else i.version=r.longs===String?"0":0;return e.domain!=null&&e.hasOwnProperty("domain")&&(i.domain=e.domain),e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?i.version=r.longs===String?String(e.version):e.version:i.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),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),d),_.exports=a},2100:(_,n,o)=>{_.exports=o(9482)},9482:(_,n,o)=>{var u=n;function l(){u.util._configure(),u.Writer._configure(u.BufferWriter),u.Reader._configure(u.BufferReader)}u.build="minimal",u.Writer=o(1173),u.BufferWriter=o(3155),u.Reader=o(1408),u.BufferReader=o(593),u.util=o(9693),u.rpc=o(5994),u.roots=o(5054),u.configure=l,l()},1408:(_,n,o)=>{_.exports=f;var u,l=o(9693),d=l.LongBits,s=l.utf8;function p(h,g){return RangeError("index out of range: "+h.pos+" + "+(g||1)+" > "+h.len)}function f(h){this.buf=h,this.pos=0,this.len=h.length}var c,a=typeof Uint8Array<"u"?function(h){if(h instanceof Uint8Array||Array.isArray(h))return new f(h);throw Error("illegal buffer")}:function(h){if(Array.isArray(h))return new f(h);throw Error("illegal buffer")},t=function(){return l.Buffer?function(h){return(f.create=function(g){return l.Buffer.isBuffer(g)?new u(g):a(g)})(h)}:a};function e(){var h=new d(0,0),g=0;if(!(this.len-this.pos>4)){for(;g<3;++g){if(this.pos>=this.len)throw p(this);if(h.lo=(h.lo|(127&this.buf[this.pos])<<7*g)>>>0,this.buf[this.pos++]<128)return h}return h.lo=(h.lo|(127&this.buf[this.pos++])<<7*g)>>>0,h}for(;g<4;++g)if(h.lo=(h.lo|(127&this.buf[this.pos])<<7*g)>>>0,this.buf[this.pos++]<128)return h;if(h.lo=(h.lo|(127&this.buf[this.pos])<<28)>>>0,h.hi=(h.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return h;if(g=0,this.len-this.pos>4){for(;g<5;++g)if(h.hi=(h.hi|(127&this.buf[this.pos])<<7*g+3)>>>0,this.buf[this.pos++]<128)return h}else for(;g<5;++g){if(this.pos>=this.len)throw p(this);if(h.hi=(h.hi|(127&this.buf[this.pos])<<7*g+3)>>>0,this.buf[this.pos++]<128)return h}throw Error("invalid varint encoding")}function r(h,g){return(h[g-4]|h[g-3]<<8|h[g-2]<<16|h[g-1]<<24)>>>0}function i(){if(this.pos+8>this.len)throw p(this,8);return new d(r(this.buf,this.pos+=4),r(this.buf,this.pos+=4))}f.create=t(),f.prototype._slice=l.Array.prototype.subarray||l.Array.prototype.slice,f.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,p(this,10);return c}),f.prototype.int32=function(){return 0|this.uint32()},f.prototype.sint32=function(){var h=this.uint32();return h>>>1^-(1&h)|0},f.prototype.bool=function(){return this.uint32()!==0},f.prototype.fixed32=function(){if(this.pos+4>this.len)throw p(this,4);return r(this.buf,this.pos+=4)},f.prototype.sfixed32=function(){if(this.pos+4>this.len)throw p(this,4);return 0|r(this.buf,this.pos+=4)},f.prototype.float=function(){if(this.pos+4>this.len)throw p(this,4);var h=l.float.readFloatLE(this.buf,this.pos);return this.pos+=4,h},f.prototype.double=function(){if(this.pos+8>this.len)throw p(this,4);var h=l.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,h},f.prototype.bytes=function(){var h=this.uint32(),g=this.pos,m=this.pos+h;if(m>this.len)throw p(this,h);return this.pos+=h,Array.isArray(this.buf)?this.buf.slice(g,m):g===m?new this.buf.constructor(0):this._slice.call(this.buf,g,m)},f.prototype.string=function(){var h=this.bytes();return s.read(h,0,h.length)},f.prototype.skip=function(h){if(typeof h=="number"){if(this.pos+h>this.len)throw p(this,h);this.pos+=h}else do if(this.pos>=this.len)throw p(this);while(128&this.buf[this.pos++]);return this},f.prototype.skipType=function(h){switch(h){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(h=7&this.uint32())!=4;)this.skipType(h);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+h+" at offset "+this.pos)}return this},f._configure=function(h){u=h,f.create=t(),u._configure();var g=l.Long?"toLong":"toNumber";l.merge(f.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 i.call(this)[g](!0)},sfixed64:function(){return i.call(this)[g](!1)}})}},593:(_,n,o)=>{_.exports=d;var u=o(1408);(d.prototype=Object.create(u.prototype)).constructor=d;var l=o(9693);function d(s){u.call(this,s)}d._configure=function(){l.Buffer&&(d.prototype._slice=l.Buffer.prototype.slice)},d.prototype.string=function(){var s=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+s,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+s,this.len))},d._configure()},5054:_=>{_.exports={}},5994:(_,n,o)=>{n.Service=o(7948)},7948:(_,n,o)=>{_.exports=l;var u=o(9693);function l(d,s,p){if(typeof d!="function")throw TypeError("rpcImpl must be a function");u.EventEmitter.call(this),this.rpcImpl=d,this.requestDelimited=!!s,this.responseDelimited=!!p}(l.prototype=Object.create(u.EventEmitter.prototype)).constructor=l,l.prototype.rpcCall=function d(s,p,f,c,a){if(!c)throw TypeError("request must be specified");var t=this;if(!a)return u.asPromise(d,t,s,p,f,c);if(t.rpcImpl)try{return t.rpcImpl(s,p[t.requestDelimited?"encodeDelimited":"encode"](c).finish(),function(e,r){if(e)return t.emit("error",e,s),a(e);if(r!==null){if(!(r instanceof f))try{r=f[t.responseDelimited?"decodeDelimited":"decode"](r)}catch(i){return t.emit("error",i,s),a(i)}return t.emit("data",r,s),a(null,r)}t.end(!0)})}catch(e){return t.emit("error",e,s),void setTimeout(function(){a(e)},0)}else setTimeout(function(){a(Error("already ended"))},0)},l.prototype.end=function(d){return this.rpcImpl&&(d||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(_,n,o)=>{_.exports=l;var u=o(9693);function l(f,c){this.lo=f>>>0,this.hi=c>>>0}var d=l.zero=new l(0,0);d.toNumber=function(){return 0},d.zzEncode=d.zzDecode=function(){return this},d.length=function(){return 1};var s=l.zeroHash="\0\0\0\0\0\0\0\0";l.fromNumber=function(f){if(f===0)return d;var c=f<0;c&&(f=-f);var a=f>>>0,t=(f-a)/4294967296>>>0;return c&&(t=~t>>>0,a=~a>>>0,++a>4294967295&&(a=0,++t>4294967295&&(t=0))),new l(a,t)},l.from=function(f){if(typeof f=="number")return l.fromNumber(f);if(u.isString(f)){if(!u.Long)return l.fromNumber(parseInt(f,10));f=u.Long.fromString(f)}return f.low||f.high?new l(f.low>>>0,f.high>>>0):d},l.prototype.toNumber=function(f){if(!f&&this.hi>>>31){var c=1+~this.lo>>>0,a=~this.hi>>>0;return c||(a=a+1>>>0),-(c+4294967296*a)}return this.lo+4294967296*this.hi},l.prototype.toLong=function(f){return u.Long?new u.Long(0|this.lo,0|this.hi,!!f):{low:0|this.lo,high:0|this.hi,unsigned:!!f}};var p=String.prototype.charCodeAt;l.fromHash=function(f){return f===s?d:new l((p.call(f,0)|p.call(f,1)<<8|p.call(f,2)<<16|p.call(f,3)<<24)>>>0,(p.call(f,4)|p.call(f,5)<<8|p.call(f,6)<<16|p.call(f,7)<<24)>>>0)},l.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)},l.prototype.zzEncode=function(){var f=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^f)>>>0,this.lo=(this.lo<<1^f)>>>0,this},l.prototype.zzDecode=function(){var f=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^f)>>>0,this.hi=(this.hi>>>1^f)>>>0,this},l.prototype.length=function(){var f=this.lo,c=(this.lo>>>28|this.hi<<4)>>>0,a=this.hi>>>24;return a===0?c===0?f<16384?f<128?1:2:f<2097152?3:4:c<16384?c<128?5:6:c<2097152?7:8:a<128?9:10}},9693:function(_,n,o){var u=n;function l(s,p,f){for(var c=Object.keys(p),a=0;a0)},u.Buffer=function(){try{var s=u.inquire("buffer").Buffer;return s.prototype.utf8Write?s:null}catch{return null}}(),u._Buffer_from=null,u._Buffer_allocUnsafe=null,u.newBuffer=function(s){return typeof s=="number"?u.Buffer?u._Buffer_allocUnsafe(s):new u.Array(s):u.Buffer?u._Buffer_from(s):typeof Uint8Array>"u"?s:new Uint8Array(s)},u.Array=typeof Uint8Array<"u"?Uint8Array:Array,u.Long=u.global.dcodeIO&&u.global.dcodeIO.Long||u.global.Long||u.inquire("long"),u.key2Re=/^true|false|0|1$/,u.key32Re=/^-?(?:0|[1-9][0-9]*)$/,u.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,u.longToHash=function(s){return s?u.LongBits.from(s).toHash():u.LongBits.zeroHash},u.longFromHash=function(s,p){var f=u.LongBits.fromHash(s);return u.Long?u.Long.fromBits(f.lo,f.hi,p):f.toNumber(!!p)},u.merge=l,u.lcFirst=function(s){return s.charAt(0).toLowerCase()+s.substring(1)},u.newError=d,u.ProtocolError=d("ProtocolError"),u.oneOfGetter=function(s){for(var p={},f=0;f-1;--a)if(p[c[a]]===1&&this[c[a]]!==void 0&&this[c[a]]!==null)return c[a]}},u.oneOfSetter=function(s){return function(p){for(var f=0;f{_.exports=t;var u,l=o(9693),d=l.LongBits,s=l.base64,p=l.utf8;function f(b,y,w){this.fn=b,this.len=y,this.next=void 0,this.val=w}function c(){}function a(b){this.head=b.head,this.tail=b.tail,this.len=b.len,this.next=b.states}function t(){this.len=0,this.head=new f(c,0,0),this.tail=this.head,this.states=null}var e=function(){return l.Buffer?function(){return(t.create=function(){return new u})()}:function(){return new t}};function r(b,y,w){y[w]=255&b}function i(b,y){this.len=b,this.next=void 0,this.val=y}function h(b,y,w){for(;b.hi;)y[w++]=127&b.lo|128,b.lo=(b.lo>>>7|b.hi<<25)>>>0,b.hi>>>=7;for(;b.lo>127;)y[w++]=127&b.lo|128,b.lo=b.lo>>>7;y[w++]=b.lo}function g(b,y,w){y[w]=255&b,y[w+1]=b>>>8&255,y[w+2]=b>>>16&255,y[w+3]=b>>>24}t.create=e(),t.alloc=function(b){return new l.Array(b)},l.Array!==Array&&(t.alloc=l.pool(t.alloc,l.Array.prototype.subarray)),t.prototype._push=function(b,y,w){return this.tail=this.tail.next=new f(b,y,w),this.len+=y,this},i.prototype=Object.create(f.prototype),i.prototype.fn=function(b,y,w){for(;b>127;)y[w++]=127&b|128,b>>>=7;y[w]=b},t.prototype.uint32=function(b){return this.len+=(this.tail=this.tail.next=new i((b>>>=0)<128?1:b<16384?2:b<2097152?3:b<268435456?4:5,b)).len,this},t.prototype.int32=function(b){return b<0?this._push(h,10,d.fromNumber(b)):this.uint32(b)},t.prototype.sint32=function(b){return this.uint32((b<<1^b>>31)>>>0)},t.prototype.uint64=function(b){var y=d.from(b);return this._push(h,y.length(),y)},t.prototype.int64=t.prototype.uint64,t.prototype.sint64=function(b){var y=d.from(b).zzEncode();return this._push(h,y.length(),y)},t.prototype.bool=function(b){return this._push(r,1,b?1:0)},t.prototype.fixed32=function(b){return this._push(g,4,b>>>0)},t.prototype.sfixed32=t.prototype.fixed32,t.prototype.fixed64=function(b){var y=d.from(b);return this._push(g,4,y.lo)._push(g,4,y.hi)},t.prototype.sfixed64=t.prototype.fixed64,t.prototype.float=function(b){return this._push(l.float.writeFloatLE,4,b)},t.prototype.double=function(b){return this._push(l.float.writeDoubleLE,8,b)};var m=l.Array.prototype.set?function(b,y,w){y.set(b,w)}:function(b,y,w){for(var T=0;T>>0;if(!y)return this._push(r,1,0);if(l.isString(b)){var w=t.alloc(y=s.length(b));s.decode(b,w,0),b=w}return this.uint32(y)._push(m,y,b)},t.prototype.string=function(b){var y=p.length(b);return y?this.uint32(y)._push(p.write,y,b):this._push(r,1,0)},t.prototype.fork=function(){return this.states=new a(this),this.head=this.tail=new f(c,0,0),this.len=0,this},t.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 f(c,0,0),this.len=0),this},t.prototype.ldelim=function(){var b=this.head,y=this.tail,w=this.len;return this.reset().uint32(w),w&&(this.tail.next=b.next,this.tail=y,this.len+=w),this},t.prototype.finish=function(){for(var b=this.head.next,y=this.constructor.alloc(this.len),w=0;b;)b.fn(b.val,y,w),w+=b.len,b=b.next;return y},t._configure=function(b){u=b,t.create=e(),u._configure()}},3155:(_,n,o)=>{_.exports=d;var u=o(1173);(d.prototype=Object.create(u.prototype)).constructor=d;var l=o(9693);function d(){u.call(this)}function s(p,f,c){p.length<40?l.utf8.write(p,f,c):f.utf8Write?f.utf8Write(p,c):f.write(p,c)}d._configure=function(){d.alloc=l._Buffer_allocUnsafe,d.writeBytesBuffer=l.Buffer&&l.Buffer.prototype instanceof Uint8Array&&l.Buffer.prototype.set.name==="set"?function(p,f,c){f.set(p,c)}:function(p,f,c){if(p.copy)p.copy(f,c,0,p.length);else for(var a=0;a>>0;return this.uint32(f),f&&this._push(d.writeBytesBuffer,f,p),this},d.prototype.string=function(p){var f=l.Buffer.byteLength(p);return this.uint32(f),f&&this._push(s,f,p),this},d._configure()},7714:(_,n,o)=>{n.R=void 0;const u=o(6919),l=o(7448);n.R=new class{async init(){}async createSessionHandler(d,s){const p=new u.Session(s);return await p.loadModel(d),new l.OnnxjsSessionHandler(p)}}},4200:(_,n,o)=>{n.c8=n.rX=void 0;const u=o(1670),l=o(5381),d=o(2157),s=o(2306);n.rX=()=>{if((typeof u.env.wasm.initTimeout!="number"||u.env.wasm.initTimeout<0)&&(u.env.wasm.initTimeout=0),typeof u.env.wasm.simd!="boolean"&&(u.env.wasm.simd=!0),typeof u.env.wasm.proxy!="boolean"&&(u.env.wasm.proxy=!1),typeof u.env.wasm.numThreads!="number"||!Number.isInteger(u.env.wasm.numThreads)||u.env.wasm.numThreads<=0){const p=typeof navigator>"u"?(0,l.cpus)().length:navigator.hardwareConcurrency;u.env.wasm.numThreads=Math.min(4,Math.ceil((p||1)/2))}},n.c8=new class{async init(){(0,n.rX)(),await(0,d.initWasm)()}async createSessionHandler(p,f){const c=new s.OnnxruntimeWebAssemblySessionHandler;return await c.loadModel(p,f),Promise.resolve(c)}}},6018:function(_,n,o){var u=this&&this.__createBinding||(Object.create?function(s,p,f,c){c===void 0&&(c=f);var a=Object.getOwnPropertyDescriptor(p,f);a&&!("get"in a?!p.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return p[f]}}),Object.defineProperty(s,c,a)}:function(s,p,f,c){c===void 0&&(c=f),s[c]=p[f]}),l=this&&this.__exportStar||function(s,p){for(var f in s)f==="default"||Object.prototype.hasOwnProperty.call(p,f)||u(p,s,f)};Object.defineProperty(n,"__esModule",{value:!0}),l(o(1670),n);const d=o(1670);{const s=o(7714).R;(0,d.registerBackend)("webgl",s,-10)}{const s=o(4200).c8;(0,d.registerBackend)("cpu",s,10),(0,d.registerBackend)("wasm",s,10),(0,d.registerBackend)("xnnpack",s,9)}},246:(_,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createAttributeWithCacheKey=void 0;class o{constructor(l){Object.assign(this,l)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map(l=>`${this[l]}`).join(";")),this._cacheKey}}n.createAttributeWithCacheKey=u=>new o(u)},7778:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Attribute=void 0;const u=o(1446),l=o(9395),d=o(9162),s=o(2517);var p=l.onnxruntime.experimental.fbs;class f{constructor(a){if(this._attributes=new Map,a!=null){for(const t of a)t instanceof u.onnx.AttributeProto?this._attributes.set(t.name,[f.getValue(t),f.getType(t)]):t instanceof p.Attribute&&this._attributes.set(t.name(),[f.getValue(t),f.getType(t)]);if(this._attributes.sized.Tensor.fromProto(r));if(a instanceof p.Attribute)return e.map(r=>d.Tensor.fromOrtTensor(r))}if(t===u.onnx.AttributeProto.AttributeType.STRING&&a instanceof u.onnx.AttributeProto){const r=e;return(0,s.decodeUtf8String)(r)}return t===u.onnx.AttributeProto.AttributeType.STRINGS&&a instanceof u.onnx.AttributeProto?e.map(s.decodeUtf8String):e}static getValueNoCheck(a){return a instanceof u.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(a):this.getValueNoCheckFromOrtFormat(a)}static getValueNoCheckFromOnnxFormat(a){switch(a.type){case u.onnx.AttributeProto.AttributeType.FLOAT:return a.f;case u.onnx.AttributeProto.AttributeType.INT:return a.i;case u.onnx.AttributeProto.AttributeType.STRING:return a.s;case u.onnx.AttributeProto.AttributeType.TENSOR:return a.t;case u.onnx.AttributeProto.AttributeType.GRAPH:return a.g;case u.onnx.AttributeProto.AttributeType.FLOATS:return a.floats;case u.onnx.AttributeProto.AttributeType.INTS:return a.ints;case u.onnx.AttributeProto.AttributeType.STRINGS:return a.strings;case u.onnx.AttributeProto.AttributeType.TENSORS:return a.tensors;case u.onnx.AttributeProto.AttributeType.GRAPHS:return a.graphs;default:throw new Error(`unsupported attribute type: ${u.onnx.AttributeProto.AttributeType[a.type]}`)}}static getValueNoCheckFromOrtFormat(a){switch(a.type()){case p.AttributeType.FLOAT:return a.f();case p.AttributeType.INT:return a.i();case p.AttributeType.STRING:return a.s();case p.AttributeType.TENSOR:return a.t();case p.AttributeType.GRAPH:return a.g();case p.AttributeType.FLOATS:return a.floatsArray();case p.AttributeType.INTS:{const t=[];for(let e=0;e{Object.defineProperty(n,"__esModule",{value:!0}),n.resolveBackend=n.backend=void 0;const u=o(5038),l=new Map;async function d(s){const p=n.backend;if(p[s]!==void 0&&function(f){const c=f;return"initialize"in c&&typeof c.initialize=="function"&&"createSessionHandler"in c&&typeof c.createSessionHandler=="function"&&"dispose"in c&&typeof c.dispose=="function"}(p[s])){const f=p[s];let c=f.initialize();if(typeof c=="object"&&"then"in c&&(c=await c),c)return l.set(s,f),f}}n.backend={webgl:new u.WebGLBackend},n.resolveBackend=async function s(p){if(!p)return s(["webgl"]);{const f=typeof p=="string"?[p]:p;for(const c of f){const a=l.get(c);if(a)return a;const t=await d(c);if(t)return t}}throw new Error("no available backend to use")}},5038:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLBackend=void 0;const u=o(1670),l=o(6231),d=o(6416),s=o(7305);n.WebGLBackend=class{get contextId(){return u.env.webgl.contextId}set contextId(p){u.env.webgl.contextId=p}get matmulMaxBatchSize(){return u.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(p){u.env.webgl.matmulMaxBatchSize=p}get textureCacheMode(){return u.env.webgl.textureCacheMode}set textureCacheMode(p){u.env.webgl.textureCacheMode=p}get pack(){return u.env.webgl.pack}set pack(p){u.env.webgl.pack=p}get async(){return u.env.webgl.async}set async(p){u.env.webgl.async=p}initialize(){try{return this.glContext=(0,s.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),l.Logger.setWithEnv(u.env),l.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(p){return l.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${p}`),!1}}createSessionHandler(p){return new d.WebGLSessionHandler(this,p)}dispose(){this.glContext.dispose()}}},5107:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CoordsGlslLib=void 0;const u=o(2517),l=o(8520),d=o(5060),s=o(7859),p=o(9390);class f extends l.GlslLib{constructor(a){super(a)}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 l.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 l.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 a=this.context.outputTextureLayout;return a.isPacked?this.getPackedOutputSamplingSnippet(a):this.getUnpackedOutputSamplingSnippet(a)}getPackedOutputSamplingSnippet(a){const t=a.unpackedShape,e=[a.width,a.height],r={},i="getOutputCoords";switch(t.length){case 0:r[i]=this.getOutputScalarCoords();break;case 1:r[i]=this.getOutputPacked1DCoords(t,e);break;case 2:r[i]=this.getOutputPacked2DCoords(t,e);break;case 3:r[i]=this.getOutputPacked3DCoords(t,e);break;default:r[i]=this.getOutputPackedNDCoords(t,e)}const h=` + void setOutput(vec4 val) { + ${(0,d.getGlsl)(this.context.glContext.version).output} = val; + } + `;return r.floatTextureSetRGBA=new l.GlslLibRoutine(h),r}getUnpackedOutputSamplingSnippet(a){const t=a.unpackedShape,e=[a.width,a.height],r={},i="getOutputCoords";switch(t.length){case 0:r[i]=this.getOutputScalarCoords();break;case 1:r[i]=this.getOutputUnpacked1DCoords(t,e);break;case 2:r[i]=this.getOutputUnpacked2DCoords(t,e);break;case 3:r[i]=this.getOutputUnpacked3DCoords(t,e);break;case 4:r[i]=this.getOutputUnpacked4DCoords(t,e);break;case 5:r[i]=this.getOutputUnpacked5DCoords(t,e);break;case 6:r[i]=this.getOutputUnpacked6DCoords(t,e);break;default:throw new Error(`Unsupported output dimensionality: ${t.length}`)}const h=` + void setOutput(float val) { + ${(0,d.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0); + } + `;return r.floatTextureSetR=new l.GlslLibRoutine(h),r}getOutputScalarCoords(){return new l.GlslLibRoutine(` + int getOutputCoords() { + return 0; + } + `)}getOutputPacked1DCoords(a,t){const e=t;let r="";return e[0]===1?(r=` + int getOutputCoords() { + return 2 * int(TexCoords.y * ${e[1]}.0); + } + `,new l.GlslLibRoutine(r)):e[1]===1?(r=` + int getOutputCoords() { + return 2 * int(TexCoords.x * ${e[0]}.0); + } + `,new l.GlslLibRoutine(r)):(r=` + int getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${e[0]}, ${e[1]})); + return 2 * (resTexRC.y * ${e[0]} + resTexRC.x); + } + `,new l.GlslLibRoutine(r))}getOutputPacked2DCoords(a,t){let e="";if(u.ArrayUtil.arraysEqual(a,t))return e=` + ivec2 getOutputCoords() { + return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); + } + `,new l.GlslLibRoutine(e);const r=t,i=Math.ceil(a[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, ${i}) * 2; + int c = 2 * (index / ${i}); + + return ivec2(r, c); + } + `,new l.GlslLibRoutine(e)}getOutputPacked3DCoords(a,t){const e=[t[0],t[1]],r=Math.ceil(a[2]/2),i=r*Math.ceil(a[1]/2),h=` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.y * ${e[0]} + resTexRC.x; + + int b = index / ${i}; + index -= b * ${i}; + + // 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 l.GlslLibRoutine(h)}getOutputPackedNDCoords(a,t){const e=[t[0],t[1]],r=Math.ceil(a[a.length-1]/2),i=r*Math.ceil(a[a.length-2]/2);let h=i,g="",m="b, r, c";for(let y=2;y=0;--m)i[m]=i[m+1]*a[m+1];const h=["r","c","d"],g=i.map((m,b)=>`int ${h[b]} = index / ${m}; ${b===i.length-1?`int ${h[b+1]} = index - ${h[b]} * ${m}`:`index -= ${h[b]} * ${m}`};`).join("");return e=` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${t[0]}, ${t[1]})); + int index = resTexRC.y * ${t[0]} + resTexRC.x; + ${g} + return ivec3(r, c, d); + } + `,new l.GlslLibRoutine(e)}getOutputUnpacked4DCoords(a,t){let e="";const r=a.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=a[r-1];for(let m=r-3;m>=0;--m)i[m]=i[m+1]*a[m+1];const h=["r","c","d","d2"],g=i.map((m,b)=>`int ${h[b]} = index / ${m}; ${b===i.length-1?`int ${h[b+1]} = index - ${h[b]} * ${m}`:`index -= ${h[b]} * ${m}`};`).join("");return e=` + ivec4 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${t[0]}, ${t[1]})); + int index = resTexRC.y * ${t[0]} + resTexRC.x; + ${g} + return ivec4(r, c, d, d2); + } + `,new l.GlslLibRoutine(e)}getOutputUnpacked5DCoords(a,t){let e="";const r=a.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=a[r-1];for(let m=r-3;m>=0;--m)i[m]=i[m+1]*a[m+1];const h=["r","c","d","d2","d3"],g=i.map((m,b)=>`int ${h[b]} = index / ${m}; ${b===i.length-1?`int ${h[b+1]} = index - ${h[b]} * ${m}`:`index -= ${h[b]} * ${m}`};`).join("");return e=` + ivec5 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${t[0]}, ${t[1]})); + int index = resTexRC.y * ${t[0]} + resTexRC.x; + ${g} + return ivec5(r, c, d, d2, d3); + } + `,new l.GlslLibRoutine(e)}getOutputUnpacked6DCoords(a,t){let e="";const r=a.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=a[r-1];for(let m=r-3;m>=0;--m)i[m]=i[m+1]*a[m+1];const h=["r","c","d","d2","d3","d4"],g=i.map((m,b)=>`int ${h[b]} = index / ${m}; ${b===i.length-1?`int ${h[b+1]} = index - ${h[b]} * ${m}`:`index -= ${h[b]} * ${m}`};`).join("");return e=` + ivec6 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${t[0]}, ${t[1]})); + int index = resTexRC.y * ${t[0]} + resTexRC.x; + ${g} + return ivec6(r, c, d, d2, d3, d4); + } + `,new l.GlslLibRoutine(e)}getCommonUtilFuncs(){const a={};let t="uvFromFlat";a[t]=new l.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); + } + `),t="packedUVfrom1D",a[t]=new l.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); + } + `),t="packedUVfrom2D",a[t]=new l.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); + } + `),t="packedUVfrom3D",a[t]=new l.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); + } + `),t="sampleTexture";const e=(0,d.getGlsl)(this.context.glContext.version);return a[t]=new l.GlslLibRoutine(` + float sampleTexture(sampler2D textureSampler, vec2 uv) { + return ${e.texture2D}(textureSampler, uv).r; + }`),a}getInputsSamplingSnippets(){const a={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((e,r)=>{const i=this.context.inputTextureLayouts[r],h=(0,p.generateShaderFuncNameFromInputSamplerName)(e);i.isPacked?a[h]=this.getPackedSamplerFromInput(h,e,i):a[h]=this.getUnpackedSamplerFromInput(h,e,i);const g=(0,p.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(e);i.unpackedShape.length<=t.unpackedShape.length&&(i.isPacked?a[g]=this.getPackedSamplerAtOutputCoords(g,i,t,e):a[g]=this.getUnpackedSamplerAtOutputCoords(g,i,t,e))}),a}getPackedSamplerAtOutputCoords(a,t,e,r){const i=t.unpackedShape,h=e.unpackedShape,g=r,m=(0,p.generateShaderFuncNameFromInputSamplerName)(g),b=i.length,y=h.length,w=u.BroadcastUtil.getBroadcastDims(i,h),T=(0,p.getCoordsDataType)(y),S=y-b;let A;const O=(0,p.getGlChannels)();A=b===0?"":y<2&&w.length>=1?"coords = 0;":w.map(N=>`coords.${O[N+S]} = 0;`).join(` +`);let v="";v=y<2&&b>0?"coords":i.map((N,G)=>`coords.${O[G+S]}`).join(", ");let M="return outputValue;";const F=u.ShapeUtil.size(i)===1,R=u.ShapeUtil.size(h)===1;if(b!==1||F||R){if(F&&!R)M=y===1?` + return vec4(outputValue.x, outputValue.x, 0., 0.); + `:` + return vec4(outputValue.x); + `;else if(w.length){const N=b-2,G=b-1;w.indexOf(N)>-1&&w.indexOf(G)>-1?M="return vec4(outputValue.x);":w.indexOf(N)>-1?M="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":w.indexOf(G)>-1&&(M="return vec4(outputValue.xx, outputValue.zz);")}}else M=` + return vec4(outputValue.xy, outputValue.xy); + `;const $=` + vec4 ${a}() { + ${T} coords = getOutputCoords(); + + int lastDim = coords.${O[y-1]}; + coords.${O[y-1]} = coords.${O[y-2]}; + coords.${O[y-2]} = lastDim; + + ${A} + vec4 outputValue = ${m}(${v}); + ${M} + } + `;return new l.GlslLibRoutine($,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(a,t,e,r){const i=[e.width,e.height],h=[t.width,t.height],g=t.unpackedShape.length,m=e.unpackedShape.length,b=t.unpackedShape,y=e.unpackedShape,w=(0,p.generateShaderFuncNameFromInputSamplerName)(r);if(g===m&&u.ArrayUtil.arraysEqual(h,i)){const R=` + float ${a}() { + return sampleTexture(${r}, TexCoords); + } + `;return new l.GlslLibRoutine(R,["coordinates.sampleTexture"])}const T=(0,p.getCoordsDataType)(m),S=u.BroadcastUtil.getBroadcastDims(b,y),A=m-g;let O;const v=(0,p.getGlChannels)();O=g===0?"":m<2&&S.length>=1?"coords = 0;":S.map(R=>`coords.${v[R+A]} = 0;`).join(` +`);let M="";M=m<2&&g>0?"coords":t.unpackedShape.map((R,$)=>`coords.${v[$+A]}`).join(", ");const F=` + float ${a}() { + ${T} coords = getOutputCoords(); + ${O} + return ${w}(${M}); + } + `;return new l.GlslLibRoutine(F,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(a,t,e){switch(e.unpackedShape.length){case 0:return this.getPackedSamplerScalar(a,t);case 1:return this.getPackedSampler1D(a,t,e);case 2:return this.getPackedSampler2D(a,t,e);case 3:return this.getPackedSampler3D(a,t,e);default:return this.getPackedSamplerND(a,t,e)}}getUnpackedSamplerFromInput(a,t,e){const r=e.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(a,t,e);case 1:return this.getUnpackedSampler1D(a,t,e);case 2:return this.getUnpackedSampler2D(a,t,e);case 3:return this.getUnpackedSampler3D(a,t,e);case 4:return this.getUnpackedSampler4D(a,t,e);case 5:return this.getUnpackedSampler5D(a,t,e);case 6:return this.getUnpackedSampler6D(a,t,e);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(a,t){const e=` + vec4 ${a}() { + return ${(0,d.getGlsl)(this.context.glContext.version).texture2D}(${t}, halfCR); + } + `;return new l.GlslLibRoutine(e)}getPackedSampler1D(a,t,e){const r=[e.width,e.height],i=[r[1],r[0]],h=(0,d.getGlsl)(this.context.glContext.version),g=`vec4 ${a}(int index) { + vec2 uv = packedUVfrom1D( + ${i[0]}, ${i[1]}, index); + return ${h.texture2D}(${t}, uv); + }`;return new l.GlslLibRoutine(g,["coordinates.packedUVfrom1D"])}getPackedSampler2D(a,t,e){const r=e.unpackedShape,i=[e.width,e.height],h=(0,d.getGlsl)(this.context.glContext.version),g=i[0],m=i[1];if(i!=null&&u.ArrayUtil.arraysEqual(r,i)){const T=`vec4 ${a}(int row, int col) { + vec2 uv = (vec2(col, row) + halfCR) / vec2(${m}.0, ${g}.0); + return ${h.texture2D}(${t}, uv); + }`;return new l.GlslLibRoutine(T)}const b=i,y=Math.ceil(r[1]/2),w=`vec4 ${a}(int row, int col) { + vec2 uv = packedUVfrom2D(${b[1]}, ${b[0]}, ${y}, row, col); + return ${h.texture2D}(${t}, uv); + }`;return new l.GlslLibRoutine(w,["coordinates.packedUVfrom2D"])}getPackedSampler3D(a,t,e){const r=e.unpackedShape,i=[e.width,e.height],h=[i[0],i[1]],g=(0,d.getGlsl)(this.context.glContext.version);if(r[0]===1){const T=r.slice(1),S=[1,2],A=(0,p.squeezeInputShape)(r,T),O=["b","row","col"],v=JSON.parse(JSON.stringify(e));v.unpackedShape=A;const M=this.getPackedSamplerFromInput(a,t,v),F=`${M.routineBody} + vec4 ${a}(int b, int row, int col) { + return ${a}(${(0,p.getSqueezedParams)(O,S)}); + } `;return new l.GlslLibRoutine(F,M.dependencies)}const m=h[0],b=h[1],y=Math.ceil(r[2]/2),w=`vec4 ${a}(int b, int row, int col) { + vec2 uv = packedUVfrom3D( + ${b}, ${m}, ${y*Math.ceil(r[1]/2)}, ${y}, b, row, col); + return ${g.texture2D}(${t}, uv);}`;return new l.GlslLibRoutine(w,["coordinates.packedUVfrom3D"])}getPackedSamplerND(a,t,e){const r=e.unpackedShape,i=r.length,h=[e.width,e.height],g=(0,d.getGlsl)(this.context.glContext.version),m=[h[0],h[1]],b=m[1],y=m[0],w=Math.ceil(r[i-1]/2);let T=w*Math.ceil(r[i-2]/2),S="int b, int row, int col",A=`b * ${T} + (row / 2) * ${w} + (col / 2)`;for(let v=2;v{const r=this.context.inputTextureLayouts[e],i=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let h=`_${t}`;a[h]=new l.GlslLibRoutine(this.getValueFromSingle(t,i,r.width,r.height,!1),[`shapeUtils.indicesToOffset${h}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),h+="_T",a[h]=new l.GlslLibRoutine(this.getValueFromSingle(t,i,r.width,r.height,!0),[`shapeUtils.indicesToOffset${h}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])}),a}getValueFromSingle(a,t,e,r,i){let h=`_${a}`;return i&&(h+="_T"),` + float ${h}(int m[${t}]) { + int offset = indicesToOffset${h}(m); + vec2 coords = offsetToCoords(offset, ${e}, ${r}); + float value = getColorAsFloat(${(0,d.getGlsl)(this.context.glContext.version).texture2D}(${a}, coords)); + return value; + } + `}getPackedValueFrom(a,t,e,r,i){let h=`_${a}_Pack`;return i&&(h+="_T"),` + vec4 ${h}(int m[${t}]) { + int offset = indicesToOffset_${a}(m); + vec2 coords = offsetToCoords(offset, ${e}, ${r}); + return ${(0,d.getGlsl)(this.context.glContext.version).texture2D}(${a}, coords); + } + `}}n.CoordsGlslLib=f},8520:(_,n)=>{var o;Object.defineProperty(n,"__esModule",{value:!0}),n.TopologicalSortGlslRoutines=n.GlslLibRoutineNode=n.GlslLibRoutine=n.GlslLib=n.GlslContext=n.FunctionType=void 0,(o=n.FunctionType||(n.FunctionType={}))[o.ValueBased=0]="ValueBased",o[o.Positional=1]="Positional",n.GlslContext=class{constructor(u,l,d,s){this.glContext=u,this.programInfo=l,this.inputTextureLayouts=d,this.outputTextureLayout=s}},n.GlslLib=class{constructor(u){this.context=u}},n.GlslLibRoutine=class{constructor(u,l){this.routineBody=u,this.dependencies=l}},n.GlslLibRoutineNode=class{constructor(u,l,d){this.name=u,this.dependencies=d||[],l&&(this.routineBody=l)}addDependency(u){u&&this.dependencies.push(u)}},n.TopologicalSortGlslRoutines=class{static returnOrderedNodes(u){if(!u||u.length===0)return[];if(u.length===1)return u;const l=new Set,d=new Set,s=new Array;return this.createOrderedNodes(u,l,d,s),s}static createOrderedNodes(u,l,d,s){for(let p=0;p0)for(let f=0;f{Object.defineProperty(n,"__esModule",{value:!0}),n.EncodingGlslLib=void 0;const u=o(8520);class l extends u.GlslLib{constructor(s){super(s)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new u.GlslLibRoutine(`highp vec4 encode(highp float f) { + return vec4(f, 0.0, 0.0, 0.0); + } + `)}}decodeFloat32(){return{decode:new u.GlslLibRoutine(`highp float decode(highp vec4 rgba) { + return rgba.r; + } + `)}}encodeUint8(){const s=l.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new u.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))); + ${s} + rgba = rgba / 255.0; // values need to be normalized to [0,1] + return rgba; + } + `)}}decodeUint8(){const s=l.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new u.GlslLibRoutine(` + highp float decode(highp vec4 rgba) { + rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] + ${s} + 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 s=new ArrayBuffer(4),p=new Uint32Array(s),f=new Uint8Array(s);if(p[0]=3735928559,f[0]===239)return!0;if(f[0]===222)return!1;throw new Error("unknown endianness")}}n.EncodingGlslLib=l},9894:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.FragColorGlslLib=void 0;const u=o(8520),l=o(5060);class d extends u.GlslLib{constructor(p){super(p)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const p=(0,l.getGlsl)(this.context.glContext.version);return{setFragColor:new u.GlslLibRoutine(` + void setFragColor(float value) { + ${p.output} = encode(value); + } + `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new u.GlslLibRoutine(` + float getColorAsFloat(vec4 color) { + return decode(color); + } + `,["encoding.decode"])}}}n.FragColorGlslLib=d},2848:(_,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.replaceInlines=void 0;const o=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;n.replaceInlines=function(u){const l={};let d;for(;(d=o.exec(u))!==null;){const s=d[3].split(",").map(p=>{const f=p.trim().split(" ");return f&&f.length===2?{type:f[0],name:f[1]}:null}).filter(p=>p!==null);l[d[2]]={params:s,body:d[4]}}for(const s in l){const p="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",s),f=new RegExp(p,"gm");for(;(d=f.exec(u))!==null;){const c=d[1],a=d[2],t=d[3].split(","),e=c?`${c} ${a};`:"";let r=l[s].body,i="";l[s].params.forEach((g,m)=>{g&&(i+=`${g.type} ${g.name} = ${t[m]}; +`)}),r=`${i} + ${r}`,r=r.replace("return",`${a} = `);const h=` + ${e} + { + ${r} + } + `;u=u.replace(d[0],h)}}return u.replace(o,"")}},8879:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.GlslPreprocessor=void 0;const u=o(8520),l=o(2848),d=o(5483),s=o(5060);n.GlslPreprocessor=class{constructor(p,f,c,a){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new u.GlslContext(p,f,c,a),Object.keys(d.glslRegistry).forEach(e=>{const r=new d.glslRegistry[e](this.context);this.libs[e]=r});const t=this.glslLibRoutineDependencyGraph;for(const e in this.libs){const r=this.libs[e].getFunctions();for(const i in r){const h=e+"."+i;let g;t[h]?(g=t[h],g.routineBody=r[i].routineBody):(g=new u.GlslLibRoutineNode(h,r[i].routineBody),t[h]=g);const m=r[i].dependencies;if(m)for(let b=0;b{const a=c.split(".")[1];p.indexOf(a)!==-1&&f.push(this.glslLibRoutineDependencyGraph[c])}),u.TopologicalSortGlslRoutines.returnOrderedNodes(f)}getUniforms(p,f){const c=[];if(p)for(const a of p)c.push(`uniform sampler2D ${a};`);if(f)for(const a of f)c.push(`uniform ${a.type} ${a.name}${a.arrayLength?`[${a.arrayLength}]`:""};`);return c.join(` +`)}}},5483:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.glslRegistry=void 0;const u=o(5107),l=o(7341),d=o(9894),s=o(2655),p=o(3891);n.glslRegistry={encoding:l.EncodingGlslLib,fragcolor:d.FragColorGlslLib,vec:p.VecGlslLib,shapeUtils:s.ShapeUtilsGlslLib,coordinates:u.CoordsGlslLib}},2655:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ShapeUtilsGlslLib=void 0;const u=o(8520);class l extends u.GlslLib{constructor(s){super(s)}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 s=this.context.outputTextureLayout.shape.length,p={};return this.context.programInfo.inputNames.forEach((f,c)=>{const a=this.context.inputTextureLayouts[c].unpackedShape;if(a.length<=s){const t=a.length,e=s-t,r=`bcastIndices_${f}`;let i="";for(let g=0;g{const a=this.context.inputTextureLayouts[c].shape;if(!(a.length<2||a.length>s)){const t=a.length,e=s-t,r=`bcastMatmulIndices_${f}`;let i="";for(let g=0;g{const c=this.context.inputTextureLayouts[f].shape,a=this.context.inputTextureLayouts[f].strides,t=c.length;let e=`indicesToOffset_${p}`;s[e]=new u.GlslLibRoutine(l.indexToOffsetSingle(e,t,a)),e=`indicesToOffset_${p}_T`,s[e]=new u.GlslLibRoutine(l.indexToOffsetSingle(e,t,a.slice().reverse()))}),s}static indexToOffsetSingle(s,p,f){let c="";for(let a=p-1;a>=0;--a)c+=` + offset += indices[${a}] * ${f[a]}; + `;return` + int ${s}(int indices[${p}]) { + int offset = 0; + ${c} + return offset; + } + `}offsetToIndices(){const s={};return this.context.programInfo.inputNames.forEach((p,f)=>{const c=this.context.inputTextureLayouts[f].shape,a=this.context.inputTextureLayouts[f].strides,t=c.length;let e=`offsetToIndices_${p}`;s[e]=new u.GlslLibRoutine(l.offsetToIndicesSingle(e,t,a)),e=`offsetToIndices_${p}_T`,s[e]=new u.GlslLibRoutine(l.offsetToIndicesSingle(e,t,a.slice().reverse()))}),s}static offsetToIndicesSingle(s,p,f){const c=[];for(let a=0;a{const c=this.context.inputTextureLayouts[f].shape,a=c.length,t=`incrementIndices_${p}`;let e="";for(let i=0;i= 0; --i) { + if(i > axis) continue; + indices[i] += 1; + if(indices[i] < shape[i]) { + break; + } + indices[i] = 0; + } + } + `;s[t]=new u.GlslLibRoutine(r)}),s}}n.ShapeUtilsGlslLib=l},5060:(_,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultFragShaderMain=n.getFragShaderPreamble=n.getVertexShaderSource=n.getGlsl=void 0;const o={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},u={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function l(d){return d===1?o:u}n.getGlsl=l,n.getVertexShaderSource=function(d){const s=l(d);return`${s.version} + precision highp float; + ${s.attribute} vec3 position; + ${s.attribute} vec2 textureCoord; + + ${s.varyingVertex} vec2 TexCoords; + + void main() + { + gl_Position = vec4(position, 1.0); + TexCoords = textureCoord; + }`},n.getFragShaderPreamble=function(d){const s=l(d);return`${s.version} + precision highp float; + precision highp int; + precision highp sampler2D; + ${s.varyingFrag} vec2 TexCoords; + ${s.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); + } + + `},n.getDefaultFragShaderMain=function(d,s){return` + void main() { + int indices[${s}]; + toVec(TexCoords, indices); + vec4 result = vec4(process(indices)); + ${l(d).output} = result; + } + `}},3891:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.VecGlslLib=void 0;const u=o(8520);class l extends u.GlslLib{constructor(s){super(s)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const s=this.context.outputTextureLayout.shape.length,p={add:"+=",sub:"-=",mul:"*=",div:"/="},f={};for(const c in p){const a=`${c}Vec`;let t="";for(let r=0;r{Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLInferenceHandler=void 0;const u=o(6231),l=o(9162),d=o(2517),s=o(2403),p=o(7019),f=o(8710),c=o(5611),a=o(4057),t=o(2039);n.WebGLInferenceHandler=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,r){return(0,a.calculateTextureWidthAndHeight)(this.session.layoutStrategy,e,r)}executeProgram(e,r){if(r.length{const S=T.map(O=>`${O.unpackedShape.join(",")};${O.width}x${O.height}`).join("_");let A=w.name;return w.cacheHint&&(A+="["+w.cacheHint+"]"),A+=":"+S,A})(e,i);let g=this.session.programManager.getArtifact(h);const m=g?g.programInfo:typeof e.get=="function"?e.get():e,b=(0,a.createTextureLayoutFromTextureType)(this.session.layoutStrategy,m.output.dims,m.output.textureType),y=this.createTextureData(b,m.output.type);return g||(g=this.session.programManager.build(m,i,y),this.session.programManager.setArtifact(h,g)),this.runProgram(g,i,y),y}run(e,r){return this.executeProgram(e,r).tensor}runProgram(e,r,i){for(let h=0;hthis.readTexture(m),async b=>this.readTextureAsync(m),void 0,g),texture:i});return this.setTextureData(m.tensor.dataId,m,e.isPacked),m}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,i=!1){this.session.isInitializer(e)?this.session.setTextureData(e,r,i):(i?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,f.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,f.encodeAsUint8)(this,e))}pack(e){return this.executeProgram((0,s.createPackProgramInfoLoader)(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram((0,c.createUnpackProgramInfoLoader)(this,e.tensor),[e.tensor])}}},1640:function(_,n,o){var u=this&&this.__createBinding||(Object.create?function(X,Z,ee,ue){ue===void 0&&(ue=ee);var Ae=Object.getOwnPropertyDescriptor(Z,ee);Ae&&!("get"in Ae?!Z.__esModule:Ae.writable||Ae.configurable)||(Ae={enumerable:!0,get:function(){return Z[ee]}}),Object.defineProperty(X,ue,Ae)}:function(X,Z,ee,ue){ue===void 0&&(ue=ee),X[ue]=Z[ee]}),l=this&&this.__setModuleDefault||(Object.create?function(X,Z){Object.defineProperty(X,"default",{enumerable:!0,value:Z})}:function(X,Z){X.default=Z}),d=this&&this.__importStar||function(X){if(X&&X.__esModule)return X;var Z={};if(X!=null)for(var ee in X)ee!=="default"&&Object.prototype.hasOwnProperty.call(X,ee)&&u(Z,X,ee);return l(Z,X),Z};Object.defineProperty(n,"__esModule",{value:!0}),n.WEBGL_OP_RESOLVE_RULES=void 0;const s=o(2898),p=d(o(7839)),f=o(4196),c=o(2069),a=o(8138),t=o(9663),e=o(5193),r=o(7992),i=o(1253),h=o(4776),g=o(6572),m=o(3346),b=o(5623),y=o(2870),w=o(2143),T=o(4939),S=o(718),A=o(2268),O=o(8117),v=o(2278),M=o(5524),F=o(5975),R=o(3933),$=o(6558),N=o(5723),G=o(3738),D=d(o(4909)),j=o(8428),Q=o(9793);n.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",D.abs],["Acos","","7+",D.acos],["Add","","7+",p.add],["And","","7+",p.and],["Asin","","7+",D.asin],["Atan","","7+",D.atan],["AveragePool","","7+",w.averagePool,w.parseAveragePoolAttributes],["BatchNormalization","","7+",s.batchNormalization,s.parseBatchNormalizationAttributes],["Cast","","6+",f.cast,f.parseCastAttributes],["Ceil","","6+",D.ceil],["Clip","","6-10",D.clip,D.parseClipAttributes],["Clip","","11+",D.clipV11],["Concat","","4+",c.concat,c.parseConcatAttributes],["Conv","","1+",a.conv,a.parseConvAttributes],["ConvTranspose","","1+",t.convTranspose,t.parseConvTransposeAttributes],["Cos","","7+",D.cos],["Div","","7+",p.div],["Dropout","","7+",D.identity],["DepthToSpace","","1+",e.depthToSpace,e.parseDepthToSpaceAttributes],["Equal","","7+",p.equal],["Elu","","6+",D.elu,D.parseEluAttributes],["Exp","","6+",D.exp],["Flatten","","1+",r.flatten,r.parseFlattenAttributes],["Floor","","6+",D.floor],["FusedConv","com.microsoft","1+",a.conv,a.parseConvAttributes],["Gather","","1+",i.gather,i.parseGatherAttributes],["Gemm","","7-10",h.gemm,h.parseGemmAttributesV7],["Gemm","","11+",h.gemm,h.parseGemmAttributesV11],["GlobalAveragePool","","1+",w.globalAveragePool,w.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",w.globalMaxPool],["Greater","","7+",p.greater],["Identity","","1+",D.identity],["ImageScaler","","1+",g.imageScaler,g.parseImageScalerAttributes],["InstanceNormalization","","6+",m.instanceNormalization,m.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",D.leakyRelu,D.parseLeakyReluAttributes],["Less","","7+",p.less],["Log","","6+",D.log],["MatMul","","1+",b.matMul,b.parseMatMulAttributes],["MaxPool","","1+",w.maxPool,w.parseMaxPoolAttributes],["Mul","","7+",p.mul],["Neg","","6+",D.neg],["Not","","1+",D.not],["Or","","7+",p.or],["Pad","","2-10",y.padV2,y.parsePadAttributesV2],["Pad","","11+",y.padV11,y.parsePadAttributesV11],["Pow","","7+",p.pow],["PRelu","","7+",p.pRelu],["ReduceLogSum","","1+",T.reduceLogSum,T.parseReduceAttributes],["ReduceMax","","1+",T.reduceMax,T.parseReduceAttributes],["ReduceMean","","1+",T.reduceMean,T.parseReduceAttributes],["ReduceMin","","1+",T.reduceMin,T.parseReduceAttributes],["ReduceProd","","1+",T.reduceProd,T.parseReduceAttributes],["ReduceSum","","1-12",T.reduceSum,T.parseReduceAttributes],["ReduceSumSquare","","1+",T.reduceLogSumSquare,T.parseReduceAttributes],["Relu","","6+",D.relu],["Reshape","","5+",S.reshape],["Resize","","10",A.resize,A.parseResizeAttributesV10],["Resize","","11+",A.resize,A.parseResizeAttributesV11],["Shape","","1+",O.shape],["Sigmoid","","6+",D.sigmoid],["Sin","","7+",D.sin],["Slice","","10+",v.sliceV10],["Slice","","1-9",v.slice,v.parseSliceAttributes],["Softmax","","1-12",M.softmax,M.parseSoftmaxAttributes],["Softmax","","13+",M.softmaxV13,M.parseSoftmaxAttributesV13],["Split","","2-12",F.split,F.parseSplitAttributes],["Sqrt","","6+",D.sqrt],["Squeeze","","1-12",R.squeeze,R.parseSqueezeAttributes],["Squeeze","","13+",R.squeezeV13],["Sub","","7+",p.sub],["Sum","","6+",$.sum],["Tan","","7+",D.tan],["Tanh","","6+",D.tanh],["Tile","","6+",N.tile],["Transpose","","1+",G.transpose,G.parseTransposeAttributes],["Upsample","","7-8",Q.upsample,Q.parseUpsampleAttributesV7],["Upsample","","9",Q.upsample,Q.parseUpsampleAttributesV9],["Unsqueeze","","1-12",j.unsqueeze,j.parseUnsqueezeAttributes],["Unsqueeze","","13+",j.unsqueezeV13],["Xor","","7+",p.xor]]},2898:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseBatchNormalizationAttributes=n.batchNormalization=void 0;const u=o(246),l=o(5060),d=o(2039),s={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked]};n.batchNormalization=(c,a,t)=>(f(a),[c.run(Object.assign(Object.assign({},s),{cacheHint:t.cacheKey,get:()=>p(c,a,t)}),a)]),n.parseBatchNormalizationAttributes=c=>{const a=c.attributes.getFloat("epsilon",1e-5),t=c.attributes.getFloat("momentum",.9),e=c.attributes.getInt("spatial",1);return(0,u.createAttributeWithCacheKey)({epsilon:a,momentum:t,spatial:e})};const p=(c,a,t)=>{const e=(0,l.getGlsl)(c.session.backend.glContext.version),r=a[0].dims.length,[i,h]=c.calculateTextureWidthAndHeight(a[1].dims,d.TextureType.unpacked),g=` + float process(int[${r}] indices) { + vec2 position = offsetToCoords(indices[1], ${i}, ${h}); + 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(${t.epsilon})) ) + b; + }`;return Object.assign(Object.assign({},s),{output:{dims:a[0].dims,type:a[0].type,textureType:d.TextureType.unpacked},shaderSource:g})},f=c=>{if(!c||c.length!==5)throw new Error("BatchNormalization requires 5 inputs.");const a=c[0],t=c[1],e=c[2],r=c[3],i=c[4];if(a.dims.length<3||t.dims.length!==1||e.dims.length!==1||r.dims.length!==1||i.dims.length!==1)throw new Error("invalid input shape.");if(t.dims[0]!==a.dims[1]||e.dims[0]!==a.dims[1]||r.dims[0]!==a.dims[1]||i.dims[0]!==a.dims[1])throw new Error("invalid input shape.");if(a.type!=="float32"&&a.type!=="float64"||t.type!=="float32"&&t.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||r.type!=="float32"&&r.type!=="float64"||i.type!=="float32"&&i.type!=="float64")throw new Error("invalid input tensor types.")}},7839:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.xor=n.sub=n.pRelu=n.pow=n.or=n.mul=n.less=n.greater=n.equal=n.div=n.and=n.add=n.glslPRelu=n.glslPow=n.glslXor=n.glslOr=n.glslAnd=n.glslLess=n.glslGreater=n.glslEqual=n.glslSub=n.glslMul=n.glslDiv=n.glslAdd=void 0;const u=o(2517),l=o(8520),d=o(5060),s=o(2039);function p(){const T="add_";return{body:` + float ${T}(float a, float b) { + return a + b; + } + vec4 ${T}(vec4 v1, vec4 v2) { + return v1 + v2; + } + `,name:T,type:l.FunctionType.ValueBased}}function f(){const T="div_";return{body:` + float ${T}(float a, float b) { + return a / b; + } + vec4 ${T}(vec4 v1, vec4 v2) { + return v1 / v2; + } + `,name:T,type:l.FunctionType.ValueBased}}function c(){const T="mul_";return{body:` + float ${T}(float a, float b) { + return a * b; + } + vec4 ${T}(vec4 v1, vec4 v2) { + return v1 * v2; + } + `,name:T,type:l.FunctionType.ValueBased}}function a(){const T="sub_";return{body:` + float ${T}(float a, float b) { + return a - b; + } + vec4 ${T}(vec4 v1, vec4 v2) { + return v1 - v2; + } + `,name:T,type:l.FunctionType.ValueBased}}function t(){const T="equal_";return{body:` + float ${T}(float a, float b) { + return float(a == b); + } + vec4 ${T}(vec4 v1, vec4 v2) { + return vec4(equal(v1, v2)); + } + `,name:T,type:l.FunctionType.ValueBased}}function e(){const T="greater_";return{body:` + float ${T}(float a, float b) { + return float(a > b); + } + vec4 ${T}(vec4 v1, vec4 v2) { + return vec4( v1.r > v2.r , + v1.g > v2.g, + v1.b > v2.b, + v1.a > v2.a ); + } + `,name:T,type:l.FunctionType.ValueBased}}function r(){const T="less_";return{body:` + float ${T}(float a, float b) { + return float(a < b); + } + vec4 ${T}(vec4 v1, vec4 v2) { + return vec4( v1.r < v2.r , + v1.g < v2.g, + v1.b < v2.b, + v1.a < v2.a ); + } + `,name:T,type:l.FunctionType.ValueBased}}function i(){const T="and_";return{body:` + float ${T}(float a, float b) { + return float( bool(a) && bool(b) ); + } + vec4 ${T}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r && b2.r , + b1.g && b2.g, + b1.b && b2.b, + b1.a && b2.a ); + } + `,name:T,type:l.FunctionType.ValueBased}}function h(){const T="or_";return{body:` + float ${T}(float a, float b) { + return float( bool(a) || bool(b) ); + } + vec4 ${T}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r || b2.r , + b1.g || b2.g, + b1.b || b2.b, + b1.a || b2.a ); + } + `,name:T,type:l.FunctionType.ValueBased}}function g(){const T="xor_";return{body:` + float ${T}(float a, float b) { + return float( bool(a) ^^ bool(b) ); + } + vec4 ${T}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r ^^ b2.r , + b1.g ^^ b2.g, + b1.b ^^ b2.b, + b1.a ^^ b2.a ); + } + `,name:T,type:l.FunctionType.ValueBased}}function m(){return function(T){const S=`${T}_`;return{body:` + float ${S}(float a, float b) { + return ${T}(a, b); + } + vec4 ${S}(vec4 v1, vec4 v2) { + return ${T}(v1, v2); + } + `,name:S,type:l.FunctionType.ValueBased}}("pow")}function b(){const T="prelu_";return{body:` + float ${T}(float a, float b) { + return a < 0.0 ? a * b: a; + } + vec4 ${T}(vec4 v1, vec4 v2) { + return vec4( + v1.r < 0.0 ? v1.r * v2.r: v1.r, + v1.g < 0.0 ? v1.g * v2.g: v1.g, + v1.b < 0.0 ? v1.b * v2.b: v1.b, + v1.a < 0.0 ? v1.a * v2.a: v1.a + ); + } + `,name:T,type:l.FunctionType.ValueBased}}n.glslAdd=p,n.glslDiv=f,n.glslMul=c,n.glslSub=a,n.glslEqual=t,n.glslGreater=e,n.glslLess=r,n.glslAnd=i,n.glslOr=h,n.glslXor=g,n.glslPow=m,n.glslPRelu=b;const y=(T,S,A,O=S[0].type,v)=>{const M=T.session.pack?s.TextureType.packed:s.TextureType.unpacked;return{name:A.name,inputNames:["A","B"],inputTypes:[M,M],cacheHint:v,get:()=>w(T,S,A,O)}},w=(T,S,A,O=S[0].type)=>{const v=T.session.pack?s.TextureType.packed:s.TextureType.unpacked,M=!u.ShapeUtil.areEqual(S[0].dims,S[1].dims);let F=S[0].dims;const R=T.session.pack;if(M){const G=u.BroadcastUtil.calcShape(S[0].dims,S[1].dims,!1);if(!G)throw new Error("Can't perform binary op on the given tensors");F=G;const D=F.length,j=S[0].dims.length!==0?S[0].dims.length:1,Q=S[1].dims.length!==0?S[1].dims.length:1,X=S[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",Z=S[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",ee=(0,d.getGlsl)(T.session.backend.glContext.version),ue=R?` + ${A.body} + void main() { + vec4 a = getAAtOutCoords(); + vec4 b = getBAtOutCoords(); + vec4 result = ${A.name}(a, b); + ${ee.output} = result; + }`:` + ${A.body} + float process(int indices[${D}]) { + int aindices[${j}]; + int bindices[${Q}]; + ${X} + ${Z} + return ${A.name}(_A(aindices), _B(bindices)); + }`;return{name:A.name,inputNames:["A","B"],inputTypes:[v,v],output:{dims:F,type:O,textureType:v},shaderSource:ue,hasMain:R}}const $=(0,d.getGlsl)(T.session.backend.glContext.version),N=` + ${A.body} + void main() { + vec4 v1 = ${$.texture2D}(A, TexCoords); + vec4 v2 = ${$.texture2D}(B, TexCoords); + vec4 result = ${A.name}(v1, v2); + ${$.output} = result; + } + `;return{name:A.name,inputNames:["A","B"],inputTypes:[v,v],output:{dims:S[0].dims,type:O,textureType:v},shaderSource:N,hasMain:!0}};n.add=(T,S)=>[T.run(y(T,S,p()),S)],n.and=(T,S)=>[T.run(y(T,S,i(),"bool"),S)],n.div=(T,S)=>[T.run(y(T,S,f()),S)],n.equal=(T,S)=>[T.run(y(T,S,t(),"bool"),S)],n.greater=(T,S)=>[T.run(y(T,S,e(),"bool"),S)],n.less=(T,S)=>[T.run(y(T,S,r(),"bool"),S)],n.mul=(T,S)=>[T.run(y(T,S,c()),S)],n.or=(T,S)=>[T.run(y(T,S,h(),"bool"),S)],n.pow=(T,S)=>[T.run(y(T,S,m()),S)],n.pRelu=(T,S)=>[T.run(y(T,S,b()),S)],n.sub=(T,S)=>[T.run(y(T,S,a()),S)],n.xor=(T,S)=>[T.run(y(T,S,g(),"bool"),S)]},4196:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseCastAttributes=n.cast=void 0;const u=o(2517);n.cast=(d,s,p)=>(l(s),[d.cast(s[0],p)]),n.parseCastAttributes=d=>u.ProtoUtil.tensorDataTypeFromProto(d.attributes.getInt("to"));const l=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:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackedConcatProgramInfoLoader=void 0;const u=o(5060),l=o(2039),d=o(9390),s=o(2827);n.createPackedConcatProgramInfoLoader=(f,c,a)=>{const t=(e=c.length,r=a.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:e},(i,h)=>`X${h}`),inputTypes:Array(e).fill(l.TextureType.packed),cacheHint:r});var e,r;return Object.assign(Object.assign({},t),{get:()=>((i,h,g,m)=>{const b=g[0].dims.slice();if(m>=b.length||m<-1*b.length)throw new Error("axis specified for concat doesn't match input dimensionality");m<0&&(m=b.length+m);const y=b.slice(0);for(let X=1;XX.dims),v=(0,d.getGlChannels)(w),M=new Array(O.length-1);M[0]=O[0][m];for(let X=1;X= ${M[X-1]}) { + return getChannel( + getX${X}(${p(v,F,Z)}), + vec2(${p(R,F,Z)})); + }`}const G=M.length,D=M[M.length-1];N+=` + return getChannel( + getX${G}(${p(v,F,D)}), + vec2(${p(R,F,D)}));`;const j=(0,u.getGlsl)(i.session.backend.glContext.version),Q=` + ${A} + float getValue(${v.map(X=>"int "+X)}) { + ${N} + } + + void main() { + ${S} coords = getOutputCoords(); + int lastDim = coords.${v[w-1]}; + coords.${v[w-1]} = coords.${v[w-2]}; + coords.${v[w-2]} = lastDim; + + vec4 result = vec4(getValue(${T}), 0., 0., 0.); + + ${T[w-1]} = ${T[w-1]} + 1; + if (${T[w-1]} < ${y[w-1]}) { + result.g = getValue(${T}); + } + + ${T[w-2]} = ${T[w-2]} + 1; + if (${T[w-2]} < ${y[w-2]}) { + result.a = getValue(${T}); + } + + ${T[w-1]} = ${T[w-1]} - 1; + if (${T[w-2]} < ${y[w-2]} && + ${T[w-1]} < ${y[w-1]}) { + result.b = getValue(${T}); + } + ${j.output} = result; + } + `;return Object.assign(Object.assign({},h),{output:{dims:y,type:g[0].type,textureType:l.TextureType.packed},shaderSource:Q,hasMain:!0})})(f,t,c,a.axis)})};const p=(f,c,a)=>{const t=f.indexOf(c);return f.map((e,r)=>r===t?`${e} - ${a}`:e).join()}},2069:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseConcatAttributes=n.concat=void 0;const u=o(246),l=o(2039),d=o(1163);n.concat=(e,r,i)=>(t(r),e.session.pack&&r[0].dims.length>1?[e.run((0,d.createPackedConcatProgramInfoLoader)(e,r,i),r)]:[e.run(s(e,r,i),r)]);const s=(e,r,i)=>{const h=(g=r.length,m=i.cacheKey,{name:"Concat",inputNames:Array.from({length:g},(b,y)=>`X${y}`),inputTypes:Array(g).fill(l.TextureType.unpacked),cacheHint:m});var g,m;return Object.assign(Object.assign({},h),{get:()=>((b,y,w,T)=>{const S=w[0].dims.slice();if(T>=S.length||T<-1*S.length)throw new Error("axis specified for concat doesn't match input dimensionality");T<0&&(T=S.length+T);const A=S.slice(0);for(let $=1;$`int getTextureWhereDataResides(int index) { + ${e.map((r,i)=>`if(index<${r}) {return ${i};} +`).join("")} + }`,f=e=>p(e),c=(e,r)=>{const i=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${r}]) {`];for(let h=0;h{const r=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let i=0;i(0,u.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis")});const t=e=>{if(!e||e.length<1)throw new Error("too few inputs");const r=e[0].type,i=e[0].dims.length;if(r==="string")throw new Error("string tensor is not supported yet");for(const h of e){if(h.type!==r)throw new Error("input tensors should be one type");if(h.dims.length!==i)throw new Error("input tensors should have the same shape")}}},4770:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createUnpackedGroupedConvProgramInfoLoader=void 0;const u=o(6231),l=o(5060),d=o(2039),s=o(8138),p=o(2823);n.createUnpackedGroupedConvProgramInfoLoader=(f,c,a)=>{const t=(e=c.length>2,r=a.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({},t),{get:()=>((i,h,g,m)=>{const b=h.length>2?"value += getBias(output_channel);":"",y=h[0].dims.slice(),w=h[1].dims.slice(),T=w[0]/m.group;u.Logger.verbose("GroupedConv",`autpPad:${m.autoPad}, dilations:${m.dilations}, group:${m.group}, kernelShape:${m.kernelShape}, pads:${m.pads}, strides:${m.strides}`);const S=(0,s.calculateOutputShape)(y,w,m.dilations,m.pads,m.strides),A=(0,l.getGlsl)(i.session.backend.glContext.version),{activationFunction:O,applyActivation:v}=(0,p.getActivationSnippet)(m),M=` + const ivec2 strides = ivec2(${m.strides[0]}, ${m.strides[1]}); + const ivec2 pads = ivec2(${m.pads[0]}, ${m.pads[1]}); + ${O} + 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 / ${T}; + + float value = 0.0; + for (int wInChannel = 0; wInChannel < ${w[1]}; wInChannel++) { + int input_channel = group_id * ${w[1]} + wInChannel; + for (int wHeight = 0; wHeight < ${w[2]}; wHeight++) { + int xHeight = xRCCorner.x + wHeight * ${m.dilations[0]}; + + if (xHeight < 0 || xHeight >= ${y[2]}) { + continue; + } + + for (int wWidth = 0; wWidth < ${w[3]}; wWidth++) { + int xWidth = xRCCorner.y + wWidth * ${m.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} + ${v} + ${A.output} = vec4(value, .0, .0, .0); + } +`;return Object.assign(Object.assign({},g),{output:{dims:S,type:h[0].type,textureType:d.TextureType.unpacked},shaderSource:M,hasMain:!0})})(f,c,t,a)})}},1386:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.conv2DPacked=n.conv2DPackedPointwise=void 0;const u=o(8138),l=o(8555),d=o(708);n.conv2DPackedPointwise=(s,p,f)=>{const c=p[0].dims,a=p[1].dims,t=(0,u.calculateOutputShape)(c,a,f.dilations,f.pads,f.strides),e=s.reshapePacked(p[0],[c[1],c[2]*c[3]]),r=s.reshapePacked(p[1],[a[0],a[1]]),i=p.length>2?[r,e,p[2]]:[r,e],h=s.run((0,d.createPackedMatmulProgramInfoLoader)(s,i,f),i);return s.reshapePacked(h,t)},n.conv2DPacked=(s,p,f)=>{const c=p[0].dims,a=p[1].dims,t=(0,u.calculateOutputShape)(c,a,f.dilations,f.pads,f.strides),e=s.run((0,l.createPackedIm2ColProgramInfoLoader)(s,p[0],p[1],t,f),[p[0]]),r=s.reshapePacked(p[1],[a[0],a[1]*a[2]*a[3]]),i=p.length===3?[r,e,p[2]]:[r,e],h=s.run((0,d.createPackedMatmulProgramInfoLoader)(s,i,f),i);return s.reshapePacked(h,t)}},9663:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseConvTransposeAttributes=n.convTranspose=void 0;const u=o(246),l=o(5060),d=o(2039),s=o(2823),p=(r,i,h,g,m,b)=>(r-1)*i+h+(g-1)*m+1-b,f=(r,i,h,g,m)=>{const b=Math.floor(r/2);i==="SAME_UPPER"?(h[g]=b,h[m]=r-b):i==="SAME_LOWER"&&(h[g]=r-b,h[m]=b)};n.convTranspose=(r,i,h)=>(e(i,h),c(r,i,h));const c=(r,i,h)=>{const g=t(h,i);return[a(r,i,g)]},a=(r,i,h)=>r.run(((g,m,b)=>{const y=(w=m.length>2,T=b.cacheKey,{name:"ConvTranspose",inputNames:w?["X","W","B"]:["X","W"],inputTypes:w?[d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked]:[d.TextureType.unpacked,d.TextureType.unpacked],cacheHint:T});var w,T;return Object.assign(Object.assign({},y),{get:()=>((S,A,O,v)=>{const M=A.length>2?"getB(output_channel)":"0.0",F=A[0].dims,R=A[1].dims,$=R[1],N=R[0]/v.group,G=[A[0].dims[0],A[1].dims[1]*v.group,...v.outputShape],D=(0,l.getGlsl)(S.session.backend.glContext.version),{activationFunction:j,applyActivation:Q}=(0,s.getActivationSnippet)(v),X=` + const ivec2 strides = ivec2(${v.strides[0]}, ${v.strides[1]}); + const ivec2 pads = ivec2(${v.pads[0]}, ${v.pads[1]}); + ${j} + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int output_channel = coords.y; + + ivec2 loc = coords.zw + pads; + + int group_id = output_channel / ${$}; + int wOutChannel = output_channel - group_id * ${$}; + + float value = ${M}; + for (int inChannelOffset = 0; inChannelOffset < ${N}; inChannelOffset++) { + int input_channel = group_id * ${N} + inChannelOffset; + for (int wWOff = 0; wWOff < ${R[2]}; wWOff++) { + for (int wHOff = 0; wHOff < ${R[3]}; wHOff++) { + ivec2 wOff = ivec2(wWOff * ${v.dilations[0]}, wHOff * ${v.dilations[1]}); + ivec2 wLoc = loc - wOff; + ivec2 wLocIn = wLoc / strides; + if ( + wLocIn * strides == wLoc && + wLocIn.x >= 0 && wLocIn.x < ${F[2]} && + wLocIn.y >= 0 && wLocIn.y < ${F[3]} + ) { + float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); + float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); + value += xVal * wVal; + } + } + } + } + ${Q} + ${D.output} = vec4(value, .0, .0, .0); + } +`;return Object.assign(Object.assign({},O),{output:{dims:G,type:A[0].type,textureType:d.TextureType.unpacked},shaderSource:X,hasMain:!0})})(g,m,y,b)})})(r,i,h),i),t=(r,i)=>{const h=r.kernelShape.slice();if(r.kernelShape.length===0)for(let y=2;y{const F=y.length-2,R=M.length===0;for(let $=0;${const i=r.attributes,h=(0,s.parseInternalActivationAttributes)(i),g=i.getString("auto_pad","NOTSET"),m=i.getInts("dilations",[1,1]),b=i.getInt("group",1),y=i.getInts("kernel_shape",[]),w=i.getInts("output_padding",[0,0]),T=i.getInts("output_shape",[]),S=i.getInts("pads",[0,0,0,0]),A=i.getInts("strides",[1,1]);return(0,u.createAttributeWithCacheKey)(Object.assign({autoPad:g,dilations:m,group:b,kernelShape:y,outputPadding:w,outputShape:T,pads:S,strides:A},h))};const e=(r,i)=>{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 h=r[1].dims[1]*i.group;if(r.length===3&&(r[2].dims.length!==1||r[2].dims[0]!==h))throw new Error("invalid bias");const g=r[0].dims.length-2;if(i.dilations.length!==g)throw new Error(`dilations should be ${g}D`);if(i.strides.length!==g)throw new Error(`strides should be ${g}D`);if(i.pads.length!==2*g)throw new Error(`pads should be ${2*g}D`);if(i.outputPadding.length!==g)throw new Error(`output_padding should be ${g}D`);if(i.kernelShape.length!==0&&i.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape");if(i.outputShape.length!==0&&i.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:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseConvAttributes=n.conv=n.calculateOutputShape=void 0;const u=o(246),l=o(2517),d=o(4770),s=o(1386),p=o(9828),f=o(2823),c=o(3248),a=o(5623);n.calculateOutputShape=(g,m,b,y,w)=>{const T=g[0],S=g.slice(2),A=S.length,O=m[0],v=m.slice(2).map((F,R)=>F+(F-1)*(b[R]-1)),M=S.map((F,R)=>F+y[R]+y[R+A]).map((F,R)=>Math.floor((F-v[R]+w[R])/w[R]));return[T,O].concat(...M)},n.conv=(g,m,b)=>(h(m,b),t(g,m,b));const t=(g,m,b)=>{const y=i(b,m),w=g.session.pack,T=y.kernelShape[0]===1&&y.kernelShape[1]===1;return y.group>1?[g.run((0,d.createUnpackedGroupedConvProgramInfoLoader)(g,m,y),m)]:T&&w?[e(g,m,y)]:w&&m[0].dims.length===4&&m[0].dims[0]===1&&!T?[(0,s.conv2DPacked)(g,m,y)]:[r(g,m,y)]},e=(g,m,b)=>{const y=m[0].dims,w=m[1].dims,T=(0,n.calculateOutputShape)(y,w,b.dilations,b.pads,b.strides),S=g.reshapeUnpacked(m[0],[y[1],y[2]*y[3]]),A=g.reshapeUnpacked(m[1],[w[0],w[1]]),O=m.length>2?[A,S,m[2]]:[A,S],v=g.run((0,a.createMatmulProgramInfoLoader)(O,b),O);return g.reshapeUnpacked(v,T)},r=(g,m,b)=>{const y=m[0].dims,w=m[1].dims,T=(0,n.calculateOutputShape)(y,w,b.dilations,b.pads,b.strides),S=g.run((0,c.createIm2ColProgramInfoLoader)(g,m[0],m[1],T,b),[m[0]]),A=m.length===3?[S,m[1],m[2]]:[S,m[1]];return g.run((0,p.createDotProductProgramInfoLoader)(g,m,T,b),A)},i=(g,m)=>{const b=g.kernelShape.slice();if(g.kernelShape.length===0)for(let T=2;T{const m=g.attributes,b=(0,f.parseInternalActivationAttributes)(m),y=m.getString("auto_pad","NOTSET"),w=m.getInts("dilations",[1,1]),T=m.getInt("group",1),S=m.getInts("kernel_shape",[]),A=m.getInts("pads",[0,0,0,0]),O=m.getInts("strides",[1,1]);return(0,u.createAttributeWithCacheKey)(Object.assign({autoPad:y,dilations:w,group:T,kernelShape:S,pads:A,strides:O},b))};const h=(g,m)=>{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]*m.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(m.dilations.length!==b)throw new Error(`dilations should be ${b}D`);if(m.strides.length!==b)throw new Error(`strides should be ${b}D`);if(m.pads.length!==2*b)throw new Error(`pads should be ${2*b}D`);if(m.kernelShape.length!==0&&m.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:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseDepthToSpaceAttributes=n.depthToSpace=void 0;const u=o(3738);n.depthToSpace=(d,s,p)=>{l(s);const f=p.blocksize,c=f*f,a=p.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],t=p.mode==="DCR"?[s[0].dims[0],f,f,s[0].dims[1]/c,s[0].dims[2],s[0].dims[3]]:[s[0].dims[0],s[0].dims[1]/c,f,f,s[0].dims[2],s[0].dims[3]],e=d.reshapeUnpacked(s[0],t),r={perm:a,cacheKey:`${a}`},[i]=(0,u.transpose)(d,[e],r),h=[s[0].dims[0],s[0].dims[1]/c,s[0].dims[2]*f,s[0].dims[3]*f];return[d.reshapeUnpacked(i,h)]},n.parseDepthToSpaceAttributes=d=>{const s=d.attributes.getInt("blocksize");if(s<1)throw new Error(`blocksize must be >= 1, but got : ${s} for DepthToSpace`);const p=d.attributes.getString("mode","DCR");if(p!=="DCR"&&p!=="CRD")throw new Error(`unrecognized mode: ${p} for DepthToSpace`);return{mode:p,blocksize:s}};const l=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:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createDotProductProgramInfoLoader=void 0;const u=o(2517),l=o(5060),d=o(2039),s=o(2823),p=o(3248);n.createDotProductProgramInfoLoader=(f,c,a,t)=>{const e=((r,i)=>({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:i.activationCacheKey}))(c.length>2,t);return Object.assign(Object.assign({},e),{get:()=>((r,i,h,g,m)=>{const b=h[0].dims,y=h[1].dims,w=[y[0],Math.ceil(b[1]*y[2]*y[3]/4)],T=(0,p.calculateIm2ColDims)(b,y,g),[S,A]=r.calculateTextureWidthAndHeight(w,d.TextureType.packedLastDimension),O=u.ShapeUtil.computeStrides(T),[v,M]=r.calculateTextureWidthAndHeight(T,d.TextureType.packedLastDimension),F=g.length,R=h.length<3?"0.0":"_B(b)",$=Math.ceil(b[1]*y[2]*y[3]/4),{activationFunction:N,applyActivation:G}=(0,s.getActivationSnippet)(m),D=(0,l.getGlsl)(r.session.backend.glContext.version),j=` +${N} +float process(int indices[${F}]) { + 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] * ${O[0]} + im2col[1] * ${O[1]} + im2col[2] * ${O[2]}; + int kernelOffset = indices[1] * ${w[1]}; + float value = ${R}; + for (int i = 0; i < ${$}; ++i) { + vec2 im2colCoords = offsetToCoords(im2colOffset, ${v}, ${M}); + vec2 kernelCoords = offsetToCoords(kernelOffset, ${S}, ${A}); + value += dot(${D.texture2D}(Im2Col, im2colCoords), ${D.texture2D}(K, kernelCoords)); + ++im2colOffset; + ++kernelOffset; + } + ${G} + return value; +}`;return Object.assign(Object.assign({},i),{output:{dims:g,type:h[0].type,textureType:d.TextureType.unpacked},shaderSource:j})})(f,e,c,a,t)})}},7992:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseFlattenAttributes=n.flatten=void 0;const u=o(2517);n.flatten=(d,s,p)=>{l(s,p);const f=u.ShapeUtil.flattenShape(s[0].dims,p);return[d.reshapeUnpacked(s[0],f)]},n.parseFlattenAttributes=d=>d.attributes.getInt("axis",1);const l=(d,s)=>{if(!d||d.length!==1)throw new Error("Flatten requires 1 input.");const p=d[0].dims.length;if(p===0)throw new Error("scalar tensor is not supported.");if(s<-p||s>p)throw new Error("Invalid axis");if(d[0].type==="string")throw new Error("string tensor is not supported.")}},2823:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseInternalActivationAttributes=n.getActivationSnippet=void 0;const u=o(2517),l=o(4909);n.getActivationSnippet=function(d){let s;switch(d.activation){case"Relu":s=(0,l.glslRelu)();break;case"Sigmoid":s=(0,l.glslSigmoid)();break;case"Clip":s=(0,l.glslClip)(d.clipMin,d.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const p=s.name;return{activationFunction:s.body,applyActivation:`value = ${p}_(value);`}},n.parseInternalActivationAttributes=d=>{const s=d.getString("activation","");if(s==="Clip"){const[p,f]=d.getFloats("activation_params",[u.MIN_CLIP,u.MAX_CLIP]);return{activation:s,clipMax:f,clipMin:p,activationCacheKey:`${s}:${p},${f}`}}return{activation:s,activationCacheKey:s}}},1253:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseGatherAttributes=n.gather=void 0;const u=o(246),l=o(782),d=o(2517),s=o(2039);n.gather=(a,t,e)=>(c(t,e.axis),[a.run(f(a,t,e),t)]),n.parseGatherAttributes=a=>(0,u.createAttributeWithCacheKey)({axis:a.attributes.getInt("axis",0)});const p={name:"Gather",inputNames:["A","B"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},f=(a,t,e)=>{const r=Object.assign(Object.assign({},p),{cacheHint:e.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((i,h,g,m)=>{const b=g[0].dims.slice(),y=g[1].dims.slice(),w=new Array(b.length+y.length-1);m=d.ShapeUtil.normalizeAxis(m,b.length);const T=[];for(let A=0;A{if(!a||a.length!==2)throw new Error("Gather requires 2 inputs.");const e=a[0].dims.length;if(e<1)throw new Error("Invalid input shape.");if(t<-e||t>e-1)throw new Error("Invalid axis.");if(l.NUMBER_TYPES.indexOf(a[0].type)===-1)throw new Error("Invaid input type.");if(a[1].type!=="int32"&&a[1].type!=="int16")throw new Error("Invaid input type.")}},4776:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseGemmAttributesV11=n.parseGemmAttributesV7=n.gemm=void 0;const u=o(246),l=o(2517),d=o(2039);n.gemm=(a,t,e)=>(c(t,e),[a.run(p(t,e),t)]);const s=(a,t)=>{const e=a.attributes.getInt("transA",0)!==0,r=a.attributes.getInt("transB",0)!==0,i=a.attributes.getFloat("alpha",1),h=a.attributes.getFloat("beta",1);return(0,u.createAttributeWithCacheKey)({transA:e,transB:r,alpha:i,beta:h,isOptionalC:t})};n.parseGemmAttributesV7=a=>s(a,!1),n.parseGemmAttributesV11=a=>s(a,!0);const p=(a,t)=>{const e={name:"Gemm",inputNames:a.length===3?["A","B","C"]:["A","B"],inputTypes:a.length===3?[d.TextureType.unpacked,d.TextureType.unpacked,d.TextureType.unpacked]:[d.TextureType.unpacked,d.TextureType.unpacked],key:t.cacheKey};return Object.assign(Object.assign({},e),{get:()=>f(e,a,t)})},f=(a,t,e)=>{const r=t[0].dims.slice(),i=t[1].dims.slice(),[h,g]=l.GemmUtil.getShapeOfGemmResult(r,e.transA,i,e.transB,t.length===3?t[2].dims:void 0),m=[h,g];if(!m)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 w=m.length,T=` + float process(int indices[${w}]) { + int a[${w}]; + int b[${w}]; + ${t.length===3?`int c[${t[2].dims.length}];`:""} + + copyVec(indices, a); + copyVec(indices, b); + ${t.length===3?"bcastIndices_C(indices, c);":""} + + float value = 0.0; + for (int k=0; k<${b}; ++k) { + a[${w-1}] = k; + b[${w-2}] = k; + ${y} + } + + value = value * alpha; + ${t.length===3?"value += beta * _C(c);":""} + return value; + }`;return Object.assign(Object.assign({},a),{output:{dims:m,type:t[0].type,textureType:d.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:e.alpha},{name:"beta",type:"float",data:e.beta}],shaderSource:T})},c=(a,t)=>{if(!a)throw new Error("Input is missing");if(t.isOptionalC&&(a.length<2||a.length>3))throw new Error("Invaid input shape.");if(!t.isOptionalC&&a.length!==3)throw new Error("Gemm requires 3 inputs");if(a.length===3&&a[2].dims.length!==1&&a[2].dims.length!==2)throw new Error("Invalid input shape of C");if(a[0].type!=="float32"&&a[0].type!=="float64"||a[1].type!=="float32"&&a[1].type!=="float64"||a.length===3&&a[2].type!=="float32"&&a[2].type!=="float64")throw new Error("Invalid input type.");if(a[0].type!==a[1].type||a.length===3&&a[0].type!==a[2].type)throw new Error("Input types are mismatched")}},8555:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackedIm2ColProgramInfoLoader=void 0;const u=o(5060),l=o(2039),d=o(2827);n.createPackedIm2ColProgramInfoLoader=(s,p,f,c,a)=>{const t=(e=a.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[l.TextureType.packed],cacheHint:e});var e;return Object.assign(Object.assign({},t),{get:()=>((r,i,h,g,m,b)=>{const y=h.dims,w=g.dims,T=m.length,S=[w[1]*w[2]*w[3],m[2]*m[3]],A=w[2]*w[3],O=(0,d.unpackFromChannel)(),v=(0,u.getGlsl)(r.session.backend.glContext.version);let M="";for(let R=0;R<=1;R++)for(let $=0;$<=1;$++)M+=` + blockIndex = rc.x + ${$}; + pos = rc.y + ${R}; + + if(blockIndex < ${S[1]} && pos < ${S[0]}) { + offsetY = int(blockIndex / (${m[T-1]})) * ${b.strides[0]} - + ${b.pads[0]}; + d0 = offsetY + ${b.dilations[0]} * (imod(pos, ${A}) / ${w[2]}); + + if(d0 < ${y[2]} && d0 >= 0) { + offsetX = imod(blockIndex, ${m[T-1]}) * ${b.strides[1]} - + ${b.pads[1]}; + d1 = offsetX + ${b.dilations[1]} * imod(imod(pos, ${A}), ${w[2]}); + + if(d1 < ${y[3]} && d1 >= 0) { + + ch = int(float(pos)/ ${A}.); + innerDims = vec2(d0, d1); + result[${2*R+$}] = getChannel( + getA(0, ch, int(innerDims.x), + int(innerDims.y)), innerDims); + } + } + } + + `;const F=` + ${O} + + void main() { + ivec2 rc = getOutputCoords(); + vec4 result = vec4(0.0); + int blockIndex, pos, offsetY, d0, offsetX, d1, ch; + vec2 innerDims; + ${M} + ${v.output} = result; + } + `;return Object.assign(Object.assign({},i),{output:{dims:S,type:h.type,textureType:l.TextureType.packed},shaderSource:F,hasMain:!0})})(s,t,p,f,c,a)})}},3248:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.calculateIm2ColDims=n.createIm2ColProgramInfoLoader=void 0;const u=o(2039);n.createIm2ColProgramInfoLoader=(l,d,s,p,f)=>{const c=(a=f.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[u.TextureType.unpacked],cacheHint:a});var a;return Object.assign(Object.assign({},c),{get:()=>((t,e,r,i,h,g)=>{const m=r.dims,b=i.dims,y=h.length,w=(0,n.calculateIm2ColDims)(m,b,h,4),T=` + const int XC = ${m[1]}; + const int XH = ${m[2]}; + const int XW = ${m[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[${m.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:w,type:r.type,textureType:u.TextureType.packedLastDimension},shaderSource:T})})(0,c,d,s,p,f)})},n.calculateIm2ColDims=(l,d,s,p=4)=>[s[0],s[2],s[3],Math.ceil(l[1]*d[2]*d[3]/p)]},6572:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseImageScalerAttributes=n.imageScaler=void 0;const u=o(246),l=o(2039);n.imageScaler=(c,a,t)=>(f(a),[c.run(s(c,a,t),a)]),n.parseImageScalerAttributes=c=>{const a=c.attributes.getFloat("scale"),t=c.attributes.getFloats("bias");return(0,u.createAttributeWithCacheKey)({scale:a,bias:t})};const d={name:"ImageScaler",inputNames:["X"],inputTypes:[l.TextureType.unpacked]},s=(c,a,t)=>{const e=Object.assign(Object.assign({},d),{cacheHint:t.cacheKey});return Object.assign(Object.assign({},e),{get:()=>((r,i,h,g)=>{const m=h[0].dims.slice(),b=m.length,y=` + ${p(g.bias.length)} + float process(int indices[${b}]) { + return _X(indices) * scale + getBias(bias, indices[1]); + }`;return Object.assign(Object.assign({},i),{output:{dims:m,type:h[0].type,textureType:l.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,a,t)})},p=c=>{const a=[`float getBias(float bias[${c}], int channel) {`];for(let t=0;t{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:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseInstanceNormalizationAttributes=n.instanceNormalization=void 0;const u=o(5060),l=o(2039);n.instanceNormalization=(a,t,e)=>{c(t);const r=a.run(s(t[0]),t);return[a.run(f(a,t[0],e,r.dims),[t[0],r,t[1],t[2]])]},n.parseInstanceNormalizationAttributes=a=>a.attributes.getFloat("epsilon",1e-5);const d={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[l.TextureType.unpacked]},s=a=>Object.assign(Object.assign({},d),{get:()=>((t,e)=>{const r=e.dims.slice(),i=r[1],h=r[2]*r[3],g=[r[0],i],m=` + 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(${h}); + 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(${h}); + + return v; + }`;return Object.assign(Object.assign({},t),{output:{dims:g,type:e.type,textureType:l.TextureType.packedLastDimension},shaderSource:m})})(d,a)}),p={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[l.TextureType.unpacked,l.TextureType.packedLastDimension,l.TextureType.unpacked,l.TextureType.unpacked]},f=(a,t,e,r)=>{const i=Object.assign(Object.assign({},p),{cacheHint:`${e}`});return Object.assign(Object.assign({},i),{get:()=>((h,g,m,b,y)=>{const w=(0,u.getGlsl)(h.session.backend.glContext.version),[T,S]=h.calculateTextureWidthAndHeight(y,l.TextureType.packedLastDimension),[A,O]=[T/4,S],v=` + vec4 get_MeanAndVariance(int[2] mv) { + int offset = indicesToOffset_MeanAndVariance(mv); + vec2 coords = offsetToCoords(offset, ${A}, ${O}); + return ${w.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:m.dims,type:m.type,textureType:l.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:b}],shaderSource:v})})(a,i,t,e,r)})},c=a=>{if(!a||a.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");const t=a[0],e=a[1],r=a[2];if(t.dims.length<3||e.dims.length!==1||r.dims.length!==1)throw new Error("Invalid input shape.");if(e.dims[0]!==t.dims[1]||r.dims[0]!==t.dims[1])throw new Error("Input shapes are mismatched.");if(t.type!=="float32"&&t.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||r.type!=="float32"&&r.type!=="float64")throw new Error("Invalid input type.");if(a[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}},708:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackedMatmulProgramInfoLoader=void 0;const u=o(2517),l=o(5060),d=o(2039),s=o(9390),p=o(2823),f=o(5623);n.createPackedMatmulProgramInfoLoader=(c,a,t)=>{const e=(r=a.length>2,i=t.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:i});var r,i;return Object.assign(Object.assign({},e),{get:()=>((h,g,m,b)=>{const y=m.length>2,w=y?"value += getBiasForMatmul();":"",T=m[0].dims,S=m[1].dims,A=u.BroadcastUtil.calcShape(T,S,!0),O=!u.ShapeUtil.areEqual(m[0].dims,m[1].dims);if(!A)throw new Error("Can't use matmul on the given tensors");const v=T[T.length-1],M=Math.ceil(v/2),F=T.length,R=S.length,$=(0,l.getGlsl)(h.session.backend.glContext.version),N=(0,s.getCoordsDataType)(A.length),G=A.length,D=(0,s.getGlChannels)(),{activationFunction:j,applyActivation:Q}=(0,p.getActivationSnippet)(b),X=y?`${(0,f.getBiasForMatmul)(N,D,m[2].dims,A,!0)}`:"",Z=O?`${function(ve,oe,we,be){let ke=[],Le=[];const xe=we[0].dims,Fe=we[1].dims,Ce=xe.length,Pe=Fe.length,Oe=be.length,Be=Oe-Ce,Ge=Oe-Pe;ke=xe.map((Me,je)=>`coords.${oe[je+Be]}`),ke[Ce-1]="i*2",ke.join(", "),Le=Fe.map((Me,je)=>`coords.${oe[je+Ge]}`),Le[Pe-2]="i*2",Le.join(", ");const Ve=u.BroadcastUtil.getBroadcastDims(xe,be),Xe=u.BroadcastUtil.getBroadcastDims(Fe,be),Qe=Ve.map(Me=>`coords.${oe[Me+Be]} = 0;`).join(` +`),qe=Xe.map(Me=>`coords.${oe[Me+Ge]} = 0;`).join(` +`),Ue=`int lastDim = coords.${oe[Oe-1]}; + coords.${oe[Oe-1]} = coords.${oe[Oe-2]}; + coords.${oe[Oe-2]} = lastDim;`;return` +vec4 getAAtOutCoordsMatmul(int i) { + ${ve} coords = getOutputCoords(); + ${Ue} + ${Qe} + vec4 outputValue = getA(${ke}); + return outputValue; +} + +vec4 getBAtOutCoordsMatmul(int i) { + ${ve} coords = getOutputCoords(); + ${Ue} + ${qe} + vec4 outputValue = getB(${Le}); + return outputValue; +}`}(N,D,m,A)}`:"",ee=O?"getAAtOutCoordsMatmul(i)":`getA(${function(ve,oe){let we="";for(let be=0;be{Object.defineProperty(n,"__esModule",{value:!0}),n.getBiasForMatmul=n.createMatmulProgramInfoLoader=n.parseMatMulAttributes=n.matMul=void 0;const u=o(2517),l=o(2039),d=o(9390),s=o(2823),p=o(708);function f(t,e){const r=(i=t.length>2,h=e.activationCacheKey,{name:"MatMul",inputNames:i?["A","B","Bias"]:["A","B"],inputTypes:i?[l.TextureType.unpacked,l.TextureType.unpacked,l.TextureType.unpacked]:[l.TextureType.unpacked,l.TextureType.unpacked],cacheHint:h});var i,h;return Object.assign(Object.assign({},r),{get:()=>function(g,m,b){const y=m[0].dims,w=m[1].dims,T=u.BroadcastUtil.calcShape(y,w,!0);if(!T)throw new Error("Can't use matmul on the given tensors");const S=(0,d.getCoordsDataType)(T.length),A=(0,d.getGlChannels)(),{activationFunction:O,applyActivation:v}=(0,s.getActivationSnippet)(b),M=m.length>2,F=M?"value += getBiasForMatmul();":"",R=M?`${a(S,A,m[2].dims,T,!1)}`:"",$=T.length,N=y.length,G=w.length,D=` + ${O} + ${R} + float process(int indices[${$}]) { + int a[${N}]; + int b[${G}]; + bcastMatmulIndices_A(indices, a); + bcastMatmulIndices_B(indices, b); + + float value; + for (int k=0; k<${y[y.length-1]}; ++k) { + a[${N-1}] = k; + b[${G-2}] = k; + value += _A(a) * _B(b); + } + ${F} + ${v} + return value; + }`;return Object.assign(Object.assign({},g),{output:{dims:T,type:m[0].type,textureType:l.TextureType.unpacked},shaderSource:D})}(r,t,e)})}n.matMul=(t,e,r)=>(c(e),t.session.pack?[t.run((0,p.createPackedMatmulProgramInfoLoader)(t,e,r),e)]:[t.run(f(e,r),e)]),n.parseMatMulAttributes=t=>(0,s.parseInternalActivationAttributes)(t.attributes),n.createMatmulProgramInfoLoader=f;const c=t=>{if(!t||t.length!==2)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.");if(t[0].type!=="float32"&&t[0].type!=="float64"||t[1].type!=="float32"&&t[1].type!=="float64")throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")};function a(t,e,r,i,h){let g="";const m=r.length,b=i.length,y=b-m;g=b<2&&m>0?"coords":r.map((S,A)=>`coords.${e[A+y]}`).join(", ");const w=u.BroadcastUtil.getBroadcastDims(r,i).map(S=>`coords.${e[S+y]} = 0;`).join(` +`);let T="vec4(outputValue.xx, outputValue.yy)";return u.ShapeUtil.size(r)===1&&(T="vec4(outputValue.x)"),h?` +vec4 getBiasForMatmul() { + ${t} coords = getOutputCoords(); + ${w} + vec4 outputValue = getBias(${g}); + return ${T}; +}`:` +float getBiasForMatmul() { + ${t} coords = getOutputCoords(); + ${w} + return getBias(coords.x); +}`}n.getBiasForMatmul=a},2403:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackProgramInfoLoader=void 0;const u=o(5060),l=o(2039),d=o(9390),s=o(2827),p={name:"pack",inputNames:["A"],inputTypes:[l.TextureType.unpackedReversed]};n.createPackProgramInfoLoader=(f,c)=>Object.assign(Object.assign({},p),{get:()=>((a,t)=>{const e=(0,u.getGlsl)(a.session.backend.glContext.version),r=t.dims,i=r.length,h=t.dims.length,g=(0,d.getCoordsDataType)(h),m=(0,s.getChannels)("rc",h),b=(y=h,w=m,T=r[r.length-2],S=r[r.length-1],y===0||y===1?"":` + int r = ${w[y-2]}; + int c = ${w[y-1]}; + int rp1 = ${w[y-2]} + 1; + int cp1 = ${w[y-1]} + 1; + bool rEdge = rp1 >= ${S}; + bool cEdge = cp1 >= ${T}; + `);var y,w,T,S;let A;A=i===0?[1,1]:i===1?[r[0],1]:[r[h-1],r[h-2]];const O=function(F,R,$){if(F===0)return"false";if(F===1)return`rc > ${R[0]}`;let N="";for(let G=F-2;G= ${R[G-F+2]}`,G= ${F[0]} ? 0. : getA(rc + 1), + 0, 0`;let N="";if($>2)for(let G=0;G<$-2;++G)N+=`${R[G]},`;return`getA(${N}r, c), + rEdge ? 0. : getA(${N}rp1, c), + cEdge ? 0. : getA(${N}r, cp1), + rEdge || cEdge ? 0. : getA(${N}rp1, cp1)`}(r,m),M=` + void main() { + ${g} rc = getOutputCoords(); + + if(${O}) { + ${e.output} = vec4(0); + } else { + ${b} + + ${e.output} = vec4(${v}); + } + } + `;return Object.assign(Object.assign({},p),{hasMain:!0,output:{dims:t.dims,type:t.type,textureType:l.TextureType.packed},shaderSource:M})})(f,c)})},2827:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.unpackFromChannel=n.getChannels=n.getVecChannels=void 0;const u=o(9390);function l(d,s){return(0,u.getGlChannels)(s).map(p=>`${d}.${p}`)}n.getVecChannels=l,n.getChannels=function(d,s){return s===1?[d]:l(d,s)},n.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:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parsePadAttributesV11=n.padV11=n.parsePadAttributesV2=n.padV2=void 0;const u=o(246),l=o(2517),d=o(5060),s=o(2039),p={name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};n.padV2=(g,m,b)=>(a(m),[g.run(Object.assign(Object.assign({},p),{cacheHint:b.cacheKey,get:()=>c(g,m[0],b)}),m)]),n.parsePadAttributesV2=g=>{const m=g.attributes.getString("mode","constant"),b=g.attributes.getFloat("value",0),y=g.attributes.getInts("pads");return(0,u.createAttributeWithCacheKey)({mode:m,value:b,pads:y})},n.padV11=(g,m,b)=>{t(m);const y=f(g,m,b);return(0,n.padV2)(g,[m[0]],y)},n.parsePadAttributesV11=g=>g.attributes.getString("mode","constant");const f=(g,m,b)=>{if(!g.session.isInitializer(m[1].dataId)||m.length>=3&&!g.session.isInitializer(m[2].dataId))throw new Error("dynamic pad attributes are not allowed");const y=Array.from(m[1].integerData),w=m.length>=3?m[2].floatData[0]:0;return(0,u.createAttributeWithCacheKey)({mode:b,pads:y,value:w})},c=(g,m,b)=>{const y=l.ShapeUtil.padShape(m.dims.slice(),b.pads),w=y.length,T=` + ${e(g,m,b)} + float process(int[${w}] indices) { + return padA(indices); + }`;return{name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked],output:{dims:y,type:m.type,textureType:s.TextureType.unpacked},shaderSource:T}},a=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.")},t=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,m,b)=>{const y=(0,d.getGlsl)(g.session.backend.glContext.version),[w,T]=g.calculateTextureWidthAndHeight(m.dims,s.TextureType.unpacked),S=l.ShapeUtil.computeStrides(m.dims);switch(b.mode){case"constant":return r(y,m.dims,S,w,T,b.pads,b.value);case"reflect":return i(y,m.dims,S,w,T,b.pads);case"edge":return h(y,m.dims,S,w,T,b.pads);default:throw new Error("Invalid mode")}},r=(g,m,b,y,w,T,S)=>{const A=m.length;let O="";for(let v=A-1;v>=0;--v)O+=` + k = m[${v}] - ${T[v]}; + if (k < 0) return constant; + if (k >= ${m[v]}) return constant; + offset += k * ${b[v]}; + `;return` + float padA(int m[${A}]) { + const float constant = float(${S}); + int offset = 0; + int k = 0; + ${O} + vec2 coords = offsetToCoords(offset, ${y}, ${w}); + float value = getColorAsFloat(${g.texture2D}(A, coords)); + return value; + } + `},i=(g,m,b,y,w,T)=>{const S=m.length;let A="";for(let O=S-1;O>=0;--O)A+=` + k = m[${O}] - ${T[O]}; + if (k < 0) { k = -k; } + { + const int _2n_1 = ${2*(m[O]-1)}; + k = int( mod( float(k), float(_2n_1) ) ) ; + if(k >= ${m[O]}) { k = _2n_1 - k; } + } + offset += k * ${b[O]}; + `;return` + float padA(int m[${S}]) { + int offset = 0; + int k = 0; + ${A} + vec2 coords = offsetToCoords(offset, ${y}, ${w}); + float value = getColorAsFloat(${g.texture2D}(A, coords)); + return value; + } + `},h=(g,m,b,y,w,T)=>{const S=m.length;let A="";for(let O=S-1;O>=0;--O)A+=` + k = m[${O}] - ${T[O]}; + if (k < 0) k = 0; + if (k >= ${m[O]}) k = ${m[O]-1}; + offset += k * ${b[O]}; + `;return` + float padA(int m[${S}]) { + int offset = 0; + int k = 0; + ${A} + vec2 coords = offsetToCoords(offset, ${y}, ${w}); + float value = getColorAsFloat(${g.texture2D}(A, coords)); + return value; + } + `}},2143:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.globalMaxPool=n.parseMaxPoolAttributes=n.maxPool=n.parseGlobalAveragePoolAttributes=n.globalAveragePool=n.parseAveragePoolAttributes=n.averagePool=void 0;const u=o(246),l=o(2517),d=o(2039);n.averagePool=(h,g,m)=>{t(g);const b={name:"AveragePool",inputNames:["X"],inputTypes:[d.TextureType.unpacked],cacheHint:m.cacheKey};return[h.run(Object.assign(Object.assign({},b),{get:()=>s(g,b,!1,m)}),g)]},n.parseAveragePoolAttributes=h=>{const g=h.attributes.getString("auto_pad","NOTSET"),m=h.attributes.getInt("ceil_mode",0),b=h.attributes.getInt("count_include_pad",0)!==0,y=h.attributes.getInts("kernel_shape"),w=h.attributes.getInts("strides",[]),T=h.attributes.getInts("pads",[]);if(m!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,u.createAttributeWithCacheKey)({autoPad:g,ceilMode:m,countIncludePad:b,kernelShape:y,strides:w,pads:T})};const s=(h,g,m,b)=>{const[y,w]=f(h,b,m),T=l.ShapeUtil.size(y.kernelShape);let S="";y.countIncludePad?S+=`value /= float(${T});`:S+=`value /= float(${T} - pad);`;const A=` + ${e(h[0].dims,y,"value += _X(x);",S,"0.0")} + `;return Object.assign(Object.assign({},g),{output:{dims:w,type:h[0].type,textureType:d.TextureType.unpacked},shaderSource:A})};n.globalAveragePool=(h,g,m)=>{t(g);const b={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[d.TextureType.unpacked],cacheHint:`${m.countIncludePad}`};return[h.run(Object.assign(Object.assign({},b),{get:()=>s(g,b,!0,m)}),g)]},n.parseGlobalAveragePoolAttributes=h=>{const g=h.attributes.getInt("count_include_pad",0)!==0;return(0,u.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:g,kernelShape:[],strides:[],pads:[]})},n.maxPool=(h,g,m)=>{t(g);const b={name:"MaxPool",inputNames:["X"],inputTypes:[d.TextureType.unpacked],cacheHint:m.cacheKey};return[h.run(Object.assign(Object.assign({},b),{get:()=>p(g,b,!1,m)}),g)]},n.parseMaxPoolAttributes=h=>{const g=h.attributes.getString("auto_pad","NOTSET"),m=h.attributes.getInt("ceil_mode",0),b=h.attributes.getInts("kernel_shape"),y=h.attributes.getInts("strides",[]),w=h.attributes.getInts("pads",[]),T=h.attributes.getInt("storage_order",0),S=h.attributes.getInts("dilations",[]);if(T!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(m!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,u.createAttributeWithCacheKey)({autoPad:g,ceilMode:m,countIncludePad:!1,kernelShape:b,strides:y,pads:w,storageOrder:T,dilations:S})};const p=(h,g,m,b)=>{const[y,w]=f(h,b,m),T=` + ${e(h[0].dims,y,` + value = max(_X(x), value); + `,"","-1e5")} + `;return Object.assign(Object.assign({},g),{output:{dims:w,type:h[0].type,textureType:d.TextureType.unpacked},shaderSource:T})},f=(h,g,m)=>{const b=h[0].dims.slice(),y=Object.hasOwnProperty.call(g,"dilations"),w=g.kernelShape.slice(),T=g.strides.slice(),S=y?g.dilations.slice():[],A=g.pads.slice();l.PoolConvUtil.adjustPoolAttributes(m,b,w,T,S,A);const O=l.PoolConvUtil.computePoolOutputShape(m,b,T,S,w,A,g.autoPad),v=Object.assign({},g);return y?Object.assign(v,{kernelShape:w,strides:T,pads:A,dilations:S,cacheKey:g.cacheKey}):Object.assign(v,{kernelShape:w,strides:T,pads:A,cacheKey:g.cacheKey}),[v,O]},c={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},a={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[d.TextureType.unpacked]};n.globalMaxPool=(h,g)=>(t(g),[h.run(Object.assign(Object.assign({},a),{get:()=>p(g,a,!0,c)}),g)]);const t=h=>{if(!h||h.length!==1)throw new Error("Pool ops requires 1 input.");if(h[0].type!=="float32"&&h[0].type!=="float64")throw new Error("Invalid input type.")},e=(h,g,m,b,y)=>{const w=h.length;if(g.kernelShape.length<=2){const T=g.kernelShape[g.kernelShape.length-1],S=g.strides[g.strides.length-1],A=g.pads[g.pads.length/2-1],O=g.pads[g.pads.length-1],v=h[w-1];let M="",F="",R="";if(M=A+O!==0?` + for (int i = 0; i < ${T}; i++) { + x[${w} - 1] = indices[${w} - 1] * ${S} - ${A} + i; + if (x[${w} - 1] < 0 || x[${w} - 1] >= ${v}) { + pad++; + continue; + } + ${m} + }`:` + for (int i = 0; i < ${T}; i++) { + x[${w} - 1] = indices[${w} - 1] * ${S} - ${A} + i; + ${m} + }`,g.kernelShape.length===2){const $=g.kernelShape[g.kernelShape.length-2],N=g.strides[g.strides.length-2],G=g.pads[g.pads.length/2-2],D=g.pads[g.pads.length-2],j=h[w-2];F=G+D!==0?` + for (int j = 0; j < ${$}; j++) { + x[${w} - 2] = indices[${w} - 2] * ${N} - ${G} + j; + if (x[${w} - 2] < 0 || x[${w} - 2] >= ${j}) { + pad+= ${T}; + continue; + } + `:` + for (int j = 0; j < ${$}; j++) { + x[${w} - 2] = indices[${w} - 2] * ${N} - ${G} + j; + `,R=` + } + `}return` + float process(int indices[${w}]) { + int x[${w}]; + copyVec(indices, x); + + float value = ${y}; + int pad = 0; + ${F} + ${M} + ${R} + ${b} + return value; + } + `}{const T=l.ShapeUtil.size(g.kernelShape),S=l.ShapeUtil.computeStrides(g.kernelShape),A=S.length,O=g.pads.length,v=i(A),M=r(h,"inputDims"),F=r(g.pads,"pads"),R=r(S,"kernelStrides"),$=r(g.strides,"strides");let N="";return N=g.pads.reduce((G,D)=>G+D)?` + if (x[j] >= inputDims[j] || x[j] < 0) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + ${m} + }`:` + } + ${m} + `,` + ${v} + float process(int indices[${w}]) { + int x[${w}]; + copyVec(indices, x); + int offset[${A}]; + int pads[${O}]; + int inputDims[${w}]; + int kernelStrides[${A}]; + int strides[${A}]; + ${F} + ${M} + ${$} + ${R} + + float value = ${y}; + int pad = 0; + bool isPad = false; + for (int i = 0; i < ${T}; i++) { + offsetToIndices(i, kernelStrides, offset); + isPad = false; + for (int j = ${w} - ${A}; j < ${w}; j++) { + x[j] = indices[j] * strides[j - ${w} + ${A}] + + offset[j - ${w} + ${A}] - pads[j - 2]; + ${N} + } + ${b} + + return value; + } + `}},r=(h,g)=>{let m="";for(let b=0;b` + void offsetToIndices(int offset, int[${h}] strides, out int[${h}] indices) { + if (${h} == 0) { + return; + } + for (int i = 0; i < ${h} - 1; ++i) { + indices[i] = offset / strides[i]; + offset -= indices[i] * strides[i]; + } + indices[${h} - 1] = offset; + }`},4939:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.reduceLogSumSquare=n.reduceLogSum=n.reduceProd=n.reduceMin=n.reduceMax=n.reduceMean=n.reduceSum=n.parseReduceAttributes=void 0;const u=o(246),l=o(782),d=o(2517),s=o(2039),p=(a,t,e,r,i)=>{c(t);const h={name:r,inputNames:["A"],inputTypes:[s.TextureType.unpacked]};return[a.run(Object.assign(Object.assign({},h),{cacheHint:e.cacheKey,get:()=>f(a,t,e,r,i,h)}),t)]};n.parseReduceAttributes=a=>{const t=a.attributes.getInts("axes",[]),e=a.attributes.getInt("keepdims",1)===1;return(0,u.createAttributeWithCacheKey)({axes:t,keepDims:e})};const f=(a,t,e,r,i,h)=>{const g=[],m=t[0].dims.length||1,b=[],y=d.ShapeUtil.normalizeAxes(e.axes,t[0].dims.length),w=i(t,y);let T=w[1];for(let A=0;A=0||y.length===0?(e.keepDims&&g.push(1),T=` + for(int j${A} = 0; j${A} < ${t[0].dims[A]}; j${A}++) { + inputIdx[${A}] = j${A}; + ${T} + }`):(b.push(`inputIdx[${A}] = outputIdx[${g.length}];`),g.push(t[0].dims[A]));const S=` + float process(int outputIdx[${g.length||1}]) { + float value; // final result + int inputIdx[${m}]; // addressing input data + ${b.join(` +`)} + ${w[0]} // init ops for reduce max/min + ${T} + ${w[2]} // final computation for reduce mean + return value; + }`;return Object.assign(Object.assign({},h),{output:{dims:g,type:t[0].type,textureType:s.TextureType.unpacked},shaderSource:S})},c=a=>{if(!a||a.length!==1)throw new Error("Reduce op requires 1 input.");if(l.NUMBER_TYPES.indexOf(a[0].type)===-1)throw new Error("Invalid input type.")};n.reduceSum=(a,t,e)=>p(a,t,e,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),n.reduceMean=(a,t,e)=>p(a,t,e,"ReduceMean",(r,i)=>{let h=1;for(let g=0;g=0||i.length===0)&&(h*=r[0].dims[g]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${h}.;`]}),n.reduceMax=(a,t,e)=>p(a,t,e,"ReduceMax",(r,i)=>{const h=[];for(let g=0;g=0||i.length===0)&&h.push(`inputIdx[${g}] = 0;`);return[`${h.join(` +`)} +value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),n.reduceMin=(a,t,e)=>p(a,t,e,"ReduceMin",(r,i)=>{const h=[];for(let g=0;g=0||i.length===0)&&h.push(`inputIdx[${g}] = 0;`);return[`${h.join(` +`)} +value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),n.reduceProd=(a,t,e)=>p(a,t,e,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),n.reduceLogSum=(a,t,e)=>p(a,t,e,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),n.reduceLogSumSquare=(a,t,e)=>p(a,t,e,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])},7019:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.isReshapeCheap=n.processDims3D=n.createPackedReshape3DProgramInfoLoader=void 0;const u=o(2517),l=o(5060),d=o(2039),s=o(2827);n.createPackedReshape3DProgramInfoLoader=(p,f,c)=>{const a=(t=>({name:"Reshape (packed)",inputTypes:[d.TextureType.packed],inputNames:["A"],cacheHint:`${t}`}))(c);return Object.assign(Object.assign({},a),{get:()=>((t,e,r,i)=>{const h=e.dims,g=i;let m="";for(let w=0;w<4;w++){let T="";switch(w){case 0:T="outputCoords = rc;";break;case 1:T="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:T="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:T="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}m+=` + ${T} + ${w>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[${w}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); + + ${w>0?"}":""} + `}const b=(0,l.getGlsl)(t.session.backend.glContext.version),y=` + ${function(w){const T=u.ShapeUtil.computeStrides(w),S=["b","r","c"],A="index";return` + ivec3 inputCoordsFromReshapedOutCoords(int index) { + ${T.map((O,v)=>`int ${S[v]} = ${A} / ${O}; ${v===T.length-1?`int ${S[v+1]} = ${A} - ${S[v]} * ${O}`:`index -= ${S[v]} * ${O}`};`).join("")} + return ivec3(b, r, c); + } + `}(h)} + ${function(w){const T=u.ShapeUtil.computeStrides(w);return` + int getFlattenedIndex(ivec3 coords) { + // reverse y, z order + return coords.x * ${T[0]} + coords.z * ${T[1]} + coords.y; + } +`}(g)} + ${(0,s.unpackFromChannel)()} + + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0.0); + + ivec3 outputCoords; + int rows = ${g[2]}; + int cols = ${g[1]}; + + ${m} + ${b.output} = result; + } + `;return Object.assign(Object.assign({},r),{output:{dims:g,type:e.type,textureType:d.TextureType.packed},shaderSource:y,hasMain:!0})})(p,f,a,c)})},n.processDims3D=function(p){if(p.length===0)return[1,1,1];let f=1;for(let c=0;c1?p[p.length-2]:1,p[p.length-1]]},n.isReshapeCheap=function(p,f){let c=!1;return c=p.length===0||f.length===0||(p.length<2||f.length<2?p[p.length-1]===f[f.length-1]:p[p.length-1]===f[f.length-1]&&p[p.length-2]===f[f.length-2]),c}},718:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.reshape=void 0;const u=o(2517);n.reshape=(l,d)=>{const s=u.ShapeUtil.calculateReshapedDims(d[0].dims,d[1].integerData);return l.session.pack?[l.reshapePacked(d[0],s)]:[l.reshapeUnpacked(d[0],s)]}},2268:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseResizeAttributesV11=n.parseResizeAttributesV10=n.resize=void 0;const u=o(5060),l=o(2039),d=o(9390),s=o(2827),p=o(9793),f={name:"Resize",inputNames:["A"],inputTypes:[l.TextureType.packed]};n.resize=(r,i,h)=>((0,p.validateInputs)(i,h),[r.run(Object.assign(Object.assign({},f),{cacheHint:h.cacheKey,get:()=>c(r,i,h)}),i)]),n.parseResizeAttributesV10=r=>(0,p.parseUpsampleAttributes)(r,10),n.parseResizeAttributesV11=r=>(0,p.parseUpsampleAttributes)(r,11);const c=(r,i,h)=>{const g=(0,u.getGlsl)(r.session.backend.glContext.version),[m,b]=a(i,h);if(m.every(N=>N===1)&&h.coordinateTransformMode!=="tf_crop_and_resize")return Object.assign(Object.assign({},f),{output:{dims:b,type:i[0].type,textureType:l.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 w=b[y-2],T=b[y-1],S=i[0].dims;if(y!==S.length)throw new Error(`output dimension should match input ${S.length}, but got ${y}`);const A=S[y-2],O=S[y-1],v=m[y-2],M=m[y-1];let F="";if(h.mode!=="linear")throw new Error(`resize (packed) does not support mode: '${h.mode}'`);switch(h.coordinateTransformMode){case"asymmetric":F=` + vec4 getSourceFracIndex(ivec4 coords) { + return vec4(coords) / scaleWHWH; + } + `;break;case"half_pixel":F=` + vec4 getSourceFracIndex(ivec4 coords) { + return (vec4(coords) + 0.5) / scaleWHWH - 0.5; + } + `;break;case"pytorch_half_pixel":F=` + vec4 getSourceFracIndex(ivec4 coords) { + vec4 fcoords = vec4(coords); + return vec4( + ${T}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, + ${w}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, + ${T}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, + ${w}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 + ); + } + `;break;case"align_corners":F=` + vec4 getSourceFracIndex(ivec4 coords) { + vec4 resized = vec4(${T}.0 - 1.0, ${w}.0 - 1.0, ${T}.0 - 1.0, + ${w}.0 - 1.0); + vec4 original = vec4(${O}.0 - 1.0, ${A}.0 - 1.0, ${O}.0 - 1.0, + ${A}.0 - 1.0); + vec4 new_scale = original / resized; + return vec4(coords) * new_scale; + } + `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${h.coordinateTransformMode}'`)}const R=(0,d.getCoordsDataType)(y),$=` + const vec2 inputWH = vec2(${A}.0, ${O}.0); + const vec4 scaleWHWH = vec4(float(${v}), float(${M}), float(${v}), float(${M})); + ${(0,s.unpackFromChannel)()} + ${F} + float getAValue(int x10, int r, int c, int d) { + return getChannel(getA(x10, r, c, d), vec2(c, d)); + } + void main() { + ${R} 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 < ${w-1}; + bool hasNextCol = rc.z < ${T-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({},f),{output:{dims:b,type:i[0].type,textureType:l.TextureType.packed},hasMain:!0,shaderSource:$})},a=(r,i)=>{const h=r[0].dims;let g,m=i.scales;if(m.length===0){const y=r[i.scalesInputIdx];if(y&&y.size!==0){if(r[i.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");m=t(y,i.mode,i.isResize)}else{const w=r[i.sizesInputIdx];if(!w||w.size===0)throw new Error("Either scales or sizes MUST be provided as input.");g=Array.from(w.integerData),m=e(g,h,i.mode,i.isResize)}}else if(r[i.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const b=g||h.map((y,w)=>Math.floor(y*m[w]));return[m,b]},t=(r,i,h)=>{const g=Array.from(r.floatData);return(0,p.scalesValidation)(g,i,h),g},e=(r,i,h,g)=>{const m=i.length,b=new Array(m);for(let y=0,w=m;y{Object.defineProperty(n,"__esModule",{value:!0}),n.shape=void 0;const u=o(9162);n.shape=(d,s)=>(l(s),[new u.Tensor([s[0].dims.length],"int32",void 0,void 0,new Int32Array(s[0].dims))]);const l=d=>{if(!d||d.length!==1)throw new Error("Shape requires 1 input.")}},2278:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.sliceV10=n.parseSliceAttributes=n.slice=void 0;const u=o(246),l=o(782),d=o(2517),s=o(2039),p={name:"Slice",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};n.slice=(e,r,i)=>(c(r),[e.run(Object.assign(Object.assign({},p),{cacheHint:i.cacheKey,get:()=>f(e,r[0],i)}),r)]),n.parseSliceAttributes=e=>{const r=e.attributes.getInts("starts"),i=e.attributes.getInts("ends"),h=e.attributes.getInts("axes",[]);return(0,u.createAttributeWithCacheKey)({starts:r,ends:i,axes:h})};const f=(e,r,i)=>{const h=i.axes.length===0?r.dims.slice(0).map((S,A)=>A):i.axes,g=d.ShapeUtil.normalizeAxes(h,r.dims.length),m=i.starts.map((S,A)=>S>r.dims[g[A]]-1?r.dims[g[A]]:d.ShapeUtil.normalizeAxis(S,r.dims[g[A]])),b=i.ends.map((S,A)=>S>r.dims[g[A]]-1?r.dims[g[A]]:d.ShapeUtil.normalizeAxis(S,r.dims[g[A]])),y=r.dims.slice(),w=[];for(let S=0;S0&&w.push(`outputIdx[${g[S]}] += ${m[S]};`);const T=` + float process(int outputIdx[${y.length}]) { + ${w.join(` + `)} + return _A(outputIdx); + }`;return Object.assign(Object.assign({},p),{output:{dims:y,type:r.type,textureType:s.TextureType.unpacked},shaderSource:T})},c=e=>{if(!e||e.length!==1)throw new Error("Slice requires 1 input.");if(l.NUMBER_TYPES.indexOf(e[0].type)===-1)throw new Error("Invalid input type.")};n.sliceV10=(e,r)=>{t(r);const i=a(e,r);return[e.run(Object.assign(Object.assign({},p),{cacheHint:i.cacheKey,get:()=>f(e,r[0],i)}),[r[0]])]};const a=(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(m=>m!==1))throw new Error("currently non-1 steps is not supported for Slice");const i=Array.from(r[1].integerData),h=Array.from(r[2].integerData),g=r.length>=4?Array.from(r[3].integerData):[];return{starts:i,ends:h,axes:g,cacheKey:`${g};${i};${h}`}},t=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:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.softmaxV13=n.parseSoftmaxAttributesV13=n.parseSoftmaxAttributes=n.softmax=void 0;const u=o(246),l=o(2517),d=o(5060),s=o(2039),p=o(3738),f={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[s.TextureType.unpacked]},c={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},a={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked,s.TextureType.unpacked]};n.softmax=(g,m,b)=>{h(m);const y=m[0].dims.slice(),w=l.ShapeUtil.normalizeAxis(b.axis,y.length),T=l.ShapeUtil.sizeToDimension(y,w),S=l.ShapeUtil.sizeFromDimension(y,w);return t(g,m,b,T,S)},n.parseSoftmaxAttributes=g=>(0,u.createAttributeWithCacheKey)({axis:g.attributes.getInt("axis",1)}),n.parseSoftmaxAttributesV13=g=>(0,u.createAttributeWithCacheKey)({axis:g.attributes.getInt("axis",-1)}),n.softmaxV13=(g,m,b)=>{h(m);const y=m[0].dims.slice(),w=l.ShapeUtil.normalizeAxis(b.axis,y.length),T=y.length,S=w!==T-1,A=[];let O,v=[],M=[];S&&(v=Array.from({length:T}).map((N,G)=>G),v[w]=T-1,v[T-1]=w,v.map(N=>A.push(y[N])),O=(0,u.createAttributeWithCacheKey)({perm:v}),M=(0,p.transpose)(g,m,O));const F=S?l.ShapeUtil.sizeToDimension(A,T-1):l.ShapeUtil.sizeToDimension(y,T-1),R=S?l.ShapeUtil.sizeFromDimension(A,T-1):l.ShapeUtil.sizeFromDimension(y,T-1),$=t(g,S?M:m,b,F,R);return S?(0,p.transpose)(g,$,O):$};const t=(g,m,b,y,w)=>{const T=e(g,m[0],y,w,[y]),S=g.run(Object.assign(Object.assign({},f),{cacheHint:b.cacheKey,get:()=>T}),m),A=r(g,m[0],y,w,T.output.dims,[y]),O=g.run(Object.assign(Object.assign({},c),{cacheHint:b.cacheKey,get:()=>A}),[m[0],S]),v=i(g,m[0],y,w,T.output.dims,A.output.dims);return[g.run(Object.assign(Object.assign({},a),{cacheHint:b.cacheKey,get:()=>v}),[m[0],S,O])]},e=(g,m,b,y,w)=>{const[T,S]=g.calculateTextureWidthAndHeight(m.dims,s.TextureType.unpacked),A=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");const O=(0,d.getGlsl)(g.session.backend.glContext.version),v=` + float process(int[${A}] indices) { + int logical_row_start_offset = indices[0] * ${y}; + + float max = getColorAsFloat(${O.texture2D}(A, offsetToCoords(logical_row_start_offset, ${T}, + ${S} ))); + for(int i=1; i<${y}; ++i) + { + float current = getColorAsFloat(${O.texture2D}(A, offsetToCoords(logical_row_start_offset + i, + ${T}, ${S}))); + if(current > max) + max = current; + } + + return max; + }`;return Object.assign(Object.assign({},f),{output:{dims:w,type:m.type,textureType:s.TextureType.unpacked},shaderSource:v})},r=(g,m,b,y,w,T)=>{const[S,A]=g.calculateTextureWidthAndHeight(m.dims,s.TextureType.unpacked),O=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");if(w.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(w[0]!==b)throw new Error("Shape of the intermediate results should be equal to logical row count");const v=` + float process(int[${O}] 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, + ${S}, ${A}))) - max); + } + + return norm_factor; + }`;return Object.assign(Object.assign({},c),{output:{dims:T,type:m.type,textureType:s.TextureType.unpacked},shaderSource:v})},i=(g,m,b,y,w,T)=>{const[S,A]=g.calculateTextureWidthAndHeight(m.dims,s.TextureType.unpacked),O=m.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(w.length!==1||T.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(w[0]!==b||T[0]!==b)throw new Error("Shape of the intermediate results should be equal to logical row count");const v=` + float process(int[${O}] indices) { + + // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) + int offset = coordsToOffset(TexCoords, ${S}, ${A}); + + //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({},a),{output:{dims:m.dims,type:m.type,textureType:s.TextureType.unpacked},shaderSource:v})},h=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:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseSplitAttributes=n.split=void 0;const u=o(246),l=o(2517),d=o(2039),s={name:"Split",inputNames:["A"],inputTypes:[d.TextureType.unpacked]};n.split=(a,t,e)=>{c(t);const r=l.ShapeUtil.normalizeAxis(e.axis,t[0].dims.length),i=p(a,t,r,e),h=[];for(let g=0;gf(a,t[0],e,r,g)}),t));return h},n.parseSplitAttributes=a=>{const t=a.attributes.getInt("axis",0),e=a.attributes.getInts("split",[]),r=a.outputs.length;return(0,u.createAttributeWithCacheKey)({axis:t,split:e,numOutputs:r})};const p=(a,t,e,r)=>{const[,i]=l.SplitUtil.splitShape(t[0].dims,e,r.split,r.numOutputs);return i.length},f=(a,t,e,r,i)=>{const[h,g]=l.SplitUtil.splitShape(t.dims,r,e.split,e.numOutputs),m=g[i],b=h[i],y=` + float process(int indices[${b.length}]) { + indices[${r}] += ${m}; + return _A(indices); + } + `;return Object.assign(Object.assign({},s),{cacheHint:`${e.cacheKey}:${i}`,output:{dims:b,type:t.type,textureType:d.TextureType.unpacked},shaderSource:y})},c=a=>{if(!a||a.length!==1)throw new Error("Split requires one input.");if(a[0].type!=="int8"&&a[0].type!=="uint8"&&a[0].type!=="int16"&&a[0].type!=="uint16"&&a[0].type!=="int32"&&a[0].type!=="uint32"&&a[0].type!=="float32"&&a[0].type!=="float64"&&a[0].type!=="bool")throw new Error("Invalid input type.")}},3933:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseSqueezeAttributes=n.squeezeV13=n.squeeze=void 0;const u=o(2517);n.squeeze=(s,p,f)=>{l(p);const c=u.ShapeUtil.squeezeShape(p[0].dims,f);return[s.reshapeUnpacked(p[0],c)]},n.squeezeV13=(s,p)=>(d(p),(0,n.squeeze)(s,[p[0]],Array.from(p[1].integerData))),n.parseSqueezeAttributes=s=>s.attributes.getInts("axes");const l=s=>{if(!s||s.length!==1)throw new Error("Squeeze requires 1 input.");if(s[0].type==="string")throw new Error("invalid input tensor types.")},d=s=>{if(!s||s.length!==2)throw new Error("Squeeze requires 2 inputs.");if(s[1].type!=="int32")throw new Error("Invalid input type.")}},6558:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.sum=void 0;const u=o(5060),l=o(2039);n.sum=(p,f)=>{s(f);const c={name:"Sum",inputNames:f.map((a,t)=>`X${t}`),inputTypes:new Array(f.length).fill(l.TextureType.unpacked)};return[p.run(Object.assign(Object.assign({},c),{get:()=>d(p,f,c)}),f)]};const d=(p,f,c)=>{const a=(0,u.getGlsl)(p.session.backend.glContext.version),t=f[0].dims.slice(),e=` + void main() { + vec4 result = ${f.map((r,i)=>`${a.texture2D}(X${i},TexCoords)`).join(" + ")}; + ${a.output} = result; + } + `;return Object.assign(Object.assign({},c),{output:{dims:t,type:f[0].type,textureType:l.TextureType.unpacked},hasMain:!0,shaderSource:e})},s=p=>{if(!p||p.length===0)throw new Error("Sum requires inputs.");const f=p[0].dims.length;for(let c=1;c{Object.defineProperty(n,"__esModule",{value:!0}),n.tile=void 0;const u=o(782),l=o(2039);n.tile=(p,f)=>{s(f);const c={name:"Tile",inputNames:["A"],inputTypes:[l.TextureType.unpacked]};return[p.run(Object.assign(Object.assign({},c),{get:()=>d(p,f,c)}),f)]};const d=(p,f,c)=>{const a=f[0].dims.slice(),t=new Array(a.length),e=[];for(let h=0;h{if(!p||p.length!==2)throw new Error("Tile requires 2 input.");if(p[1].dims.length!==1)throw new Error("The second input shape must 1 dimension.");if(p[1].dims[0]!==p[0].dims.length)throw new Error("Invalid input shape.");if(u.NUMBER_TYPES.indexOf(p[0].type)===-1)throw new Error("Invalid input type.");if(p[1].type!=="int32"&&p[1].type!=="int16")throw new Error("Invalid repeat type.")}},3738:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseTransposeAttributes=n.transpose=void 0;const u=o(246),l=o(2517),d=o(2039),s={name:"Transpose",inputNames:["A"],inputTypes:[d.TextureType.unpacked]};n.transpose=(e,r,i)=>(t(r),[e.run(Object.assign(Object.assign({},s),{cacheHint:i.cacheKey,get:()=>p(e,r[0],i.perm)}),r)]),n.parseTransposeAttributes=e=>(0,u.createAttributeWithCacheKey)({perm:e.attributes.getInts("perm",[])});const p=(e,r,i)=>{const h=r.dims;i=f(h,i);const g=c(h,i),m=h.length,b=` + ${a("perm",i,m)} + float process(int indices[${m}]) { + int a[${m}]; + perm(a, indices); + return _A(a); + }`;return Object.assign(Object.assign({},s),{output:{dims:g,type:r.type,textureType:d.TextureType.unpacked},shaderSource:b})},f=(e,r)=>(r&&r.length!==e.length&&(r=[...e.keys()].reverse()),r),c=(e,r)=>(r=f(e,r),l.ShapeUtil.sortBasedOnPerm(e,r)),a=(e,r,i)=>{const h=[];h.push(`void ${e}(out int a[${i}], int src[${i}]) {`);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:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.encodeAsUint8=void 0;const u=o(5060),l=o(2039);n.encodeAsUint8=(d,s)=>{const p=s.shape,f=(0,u.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 = ${f.texture2D}(X,TexCoords).r; + ${f.output} = encodeAsUint8(value); + }`,a={name:"Uint8Encode",inputTypes:[l.TextureType.unpacked],inputNames:["X"],output:{dims:p,type:s.tensor.type,textureType:l.TextureType.downloadUint8AsFloat},shaderSource:c,hasMain:!0};return d.executeProgram(a,[s.tensor])}},4909:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.tanh=n.tan=n.sqrt=n.sin=n.sigmoid=n.relu=n.not=n.neg=n.log=n.parseLeakyReluAttributes=n.leakyRelu=n.identity=n.floor=n.exp=n.parseEluAttributes=n.elu=n.cos=n.ceil=n.clipV11=n.parseClipAttributes=n.clip=n.atan=n.asin=n.acos=n.abs=n.glslTanh=n.glslTan=n.glslSqrt=n.glslSigmoid=n.glslRelu=n.glslSin=n.glslNot=n.glslNeg=n.glslLog=n.glslLeakyRelu=n.glslIdentity=n.glslClip=n.glslFloor=n.glslExp=n.glslElu=n.glslCos=n.glslCeil=n.glslAtan=n.glslAsin=n.glslAcos=n.glslAbs=void 0;const u=o(246),l=o(2517),d=o(8520),s=o(5060),p=o(2039);function f(){return $("abs")}function c(){return $("acos")}function a(){return $("asin")}function t(){return $("atan")}function e(){return $("ceil")}function r(){return $("cos")}function i(D){const j="elu";return{body:` + const float alpha = float(${D}); + + float ${j}_(float a) { + return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; + } + vec4 ${j}_(vec4 v) { + return vec4(${j}_(v.x), ${j}_(v.y), ${j}_(v.z), ${j}_(v.w)); + } + `,name:j,type:d.FunctionType.ValueBased}}function h(){return $("exp")}function g(){return $("floor")}function m(D,j){const Q="clip";return{body:` + const float min = float(${D}); + const float max = float(${j}); + + float ${Q}_(float a) { + return clamp(a, min, max); + } + vec4 ${Q}_(vec4 v) { + return clamp(v, min, max); + } + `,name:Q,type:d.FunctionType.ValueBased}}function b(){const D="indentity";return{body:` + float ${D}_(float a) { + return a; + } + vec4 ${D}_(vec4 v) { + return v; + } + `,name:D,type:d.FunctionType.ValueBased}}function y(D){const j="leakyRelu";return{body:` + const float alpha = float(${D}); + + float ${j}_(float a) { + return a < 0.0 ? a * alpha : a; + } + vec4 ${j}_(vec4 v) { + return vec4(${j}_(v.x), ${j}_(v.y), ${j}_(v.z), ${j}_(v.w)); + } + `,name:j,type:d.FunctionType.ValueBased}}function w(){return $("log")}function T(){const D="neg";return{body:` + float ${D}_(float a) { + return -a; + } + vec4 ${D}_(vec4 v) { + return -v; + } + `,name:D,type:d.FunctionType.ValueBased}}function S(){const D="not";return{body:` + float ${D}_(float a) { + return float( ! bool(a) ); + } + bool ${D}_(bool a) { + return !a; + } + vec4 ${D}_(vec4 v) { + return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); + } + bvec4 ${D}_(bvec4 v) { + return bvec4(!v.x, !v.y, !v.z, !v.w); + } + `,name:D,type:d.FunctionType.ValueBased}}function A(){return $("sin")}function O(){const D="relu";return{body:` + float ${D}_(float a) { + return max( a, 0.0 ); + } + vec4 ${D}_(vec4 v) { + return max( v, 0.0 ); + } + `,name:D,type:d.FunctionType.ValueBased}}function v(){const D="sigmoid";return{body:` + float ${D}_(float a) { + return 1.0 / (1.0 + exp(-a)); + } + vec4 ${D}_(vec4 v) { + return 1.0 / (1.0 + exp(-v)); + } + `,name:D,type:d.FunctionType.ValueBased}}function M(){return $("sqrt")}function F(){return $("tan")}function R(){const D="tanh";return{body:` + float ${D}_(float a) { + a = clamp(a, -10., 10.); + a = exp(2.*a); + return (a - 1.) / (a + 1.); + } + vec4 ${D}_(vec4 v) { + v = clamp(v, -10., 10.); + v = exp(2.*v); + return (v - 1.) / (v + 1.); + } + `,name:D,type:d.FunctionType.ValueBased}}function $(D){return{body:` + float ${D}_(float a) { + return ${D}(a); + } + vec4 ${D}_(vec4 v) { + return ${D}(v); + } + `,name:D,type:d.FunctionType.ValueBased}}n.glslAbs=f,n.glslAcos=c,n.glslAsin=a,n.glslAtan=t,n.glslCeil=e,n.glslCos=r,n.glslElu=i,n.glslExp=h,n.glslFloor=g,n.glslClip=m,n.glslIdentity=b,n.glslLeakyRelu=y,n.glslLog=w,n.glslNeg=T,n.glslNot=S,n.glslSin=A,n.glslRelu=O,n.glslSigmoid=v,n.glslSqrt=M,n.glslTan=F,n.glslTanh=R;const N=(D,j,Q,X)=>{const Z=D.session.pack?p.TextureType.packed:p.TextureType.unpacked,ee={name:Q.name,inputTypes:[Z],inputNames:["A"],cacheHint:X};return Object.assign(Object.assign({},ee),{get:()=>((ue,Ae,ve,oe)=>{const we=ue.session.pack?p.TextureType.packed:p.TextureType.unpacked,be=(0,s.getGlsl)(ue.session.backend.glContext.version);return Object.assign(Object.assign({},Ae),{output:{dims:ve.dims,type:ve.type,textureType:we},shaderSource:` + ${oe.body} + void main() { + vec4 v = ${be.texture2D}(A, TexCoords); + v = ${oe.name}_(v); + ${be.output} = v; + } + `,hasMain:!0})})(D,ee,j,Q)})};n.abs=(D,j)=>[D.run(N(D,j[0],f()),j)],n.acos=(D,j)=>[D.run(N(D,j[0],c()),j)],n.asin=(D,j)=>[D.run(N(D,j[0],a()),j)],n.atan=(D,j)=>[D.run(N(D,j[0],t()),j)],n.clip=(D,j,Q)=>[D.run(N(D,j[0],m(Q.min,Q.max),Q.cacheKey),j)],n.parseClipAttributes=D=>(0,u.createAttributeWithCacheKey)({min:D.attributes.getFloat("min",l.MIN_CLIP),max:D.attributes.getFloat("max",l.MAX_CLIP)}),n.clipV11=(D,j)=>{const Q=G(D,j);return(0,n.clip)(D,[j[0]],Q)};const G=(D,j)=>{if(j.length>=3&&(!D.session.isInitializer(j[1].dataId)||!D.session.isInitializer(j[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const Q=j.length>=3?j[1].numberData[0]:l.MIN_CLIP,X=j.length>=3?j[2].numberData[0]:l.MAX_CLIP;return(0,u.createAttributeWithCacheKey)({min:Q,max:X})};n.ceil=(D,j)=>[D.run(N(D,j[0],e()),j)],n.cos=(D,j)=>[D.run(N(D,j[0],r()),j)],n.elu=(D,j,Q)=>[D.run(N(D,j[0],i(Q.alpha),Q.cacheKey),j)],n.parseEluAttributes=D=>(0,u.createAttributeWithCacheKey)({alpha:D.attributes.getFloat("alpha",1)}),n.exp=(D,j)=>[D.run(N(D,j[0],h()),j)],n.floor=(D,j)=>[D.run(N(D,j[0],g()),j)],n.identity=(D,j)=>[D.run(N(D,j[0],b()),j)],n.leakyRelu=(D,j,Q)=>[D.run(N(D,j[0],y(Q.alpha),Q.cacheKey),j)],n.parseLeakyReluAttributes=D=>(0,u.createAttributeWithCacheKey)({alpha:D.attributes.getFloat("alpha",.01)}),n.log=(D,j)=>[D.run(N(D,j[0],w()),j)],n.neg=(D,j)=>[D.run(N(D,j[0],T()),j)],n.not=(D,j)=>[D.run(N(D,j[0],S()),j)],n.relu=(D,j)=>[D.run(N(D,j[0],O()),j)],n.sigmoid=(D,j)=>[D.run(N(D,j[0],v()),j)],n.sin=(D,j)=>[D.run(N(D,j[0],A()),j)],n.sqrt=(D,j)=>[D.run(N(D,j[0],M()),j)],n.tan=(D,j)=>[D.run(N(D,j[0],F()),j)],n.tanh=(D,j)=>[D.run(N(D,j[0],R()),j)]},5611:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createUnpackProgramInfoLoader=n.createUnpackProgramInfo=void 0;const u=o(5060),l=o(2039),d=o(9390),s=o(2827),p={name:"unpack",inputNames:["A"],inputTypes:[l.TextureType.packed]};n.createUnpackProgramInfo=(f,c)=>{const a=c.dims.length,t=(0,s.getChannels)("rc",a),e=t.slice(-2),r=(0,d.getCoordsDataType)(a),i=(0,s.unpackFromChannel)(),h=c.dims.length===0?"":function(b,y){if(b===1)return"rc";let w="";for(let T=0;TObject.assign(Object.assign({},p),{get:()=>(0,n.createUnpackProgramInfo)(f,c)})},8428:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseUnsqueezeAttributes=n.unsqueezeV13=n.unsqueeze=void 0;const u=o(2517);n.unsqueeze=(s,p,f)=>{l(p);const c=u.ShapeUtil.unsqueezeShape(p[0].dims,f);return[s.reshapeUnpacked(p[0],c)]},n.unsqueezeV13=(s,p)=>(d(p),(0,n.unsqueeze)(s,[p[0]],Array.from(p[1].integerData))),n.parseUnsqueezeAttributes=s=>s.attributes.getInts("axes");const l=s=>{if(!s||s.length!==1)throw new Error("Unsqueeze requires 1 input.");if(s[0].type==="string")throw new Error("invalid input tensor types.")},d=s=>{if(!s||s.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(s[1].type!=="int32")throw new Error("Invalid input type.")}},9793:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.scalesValidation=n.validateInputs=n.parseUpsampleAttributes=n.parseUpsampleAttributesV9=n.parseUpsampleAttributesV7=n.upsample=void 0;const u=o(246),l=o(5060),d=o(2039),s={name:"Upsample",inputNames:["X"],inputTypes:[d.TextureType.unpacked]};n.upsample=(f,c,a)=>((0,n.validateInputs)(c,a),[f.run(Object.assign(Object.assign({},s),{cacheHint:a.cacheKey,get:()=>p(f,c,a)}),c)]),n.parseUpsampleAttributesV7=f=>(0,n.parseUpsampleAttributes)(f,7),n.parseUpsampleAttributesV9=f=>(0,n.parseUpsampleAttributes)(f,9),n.parseUpsampleAttributes=(f,c)=>{const a=c>=10,t=f.attributes.getString("mode","nearest");if(t!=="nearest"&&t!=="linear"&&(c<11||t!=="cubic"))throw new Error(`unrecognized mode: ${t}`);let e=[];c<9&&(e=f.attributes.getFloats("scales"),(0,n.scalesValidation)(e,t,a));const r=f.attributes.getFloat("extrapolation_value",0),i=c>10?f.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(i)===-1)throw new Error(`coordinate_transform_mode '${i}' is not supported`);const h=i==="tf_crop_and_resize",g=h,m=t==="nearest"&&c>=11?f.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(m)===-1)throw new Error(`nearest_mode '${m}' is not supported`);const b=f.attributes.getFloat("cubic_coeff_a",-.75),y=f.attributes.getInt("exclude_outside",0)!==0;if(y&&t!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const w=c<11||t==="nearest"&&i==="asymmetric"&&m==="floor";let T=0,S=0,A=0;return c>10?f.inputs.length>2?(T=1,S=2,A=3):(S=1,A=2):c===9&&(S=1),(0,u.createAttributeWithCacheKey)({opset:c,isResize:a,mode:t,scales:e,extrapolationValue:r,coordinateTransformMode:i,useExtrapolation:g,needRoiInput:h,nearestMode:m,cubicCoefficientA:b,excludeOutside:y,useNearest2xOptimization:w,roiInputIdx:T,scalesInputIdx:S,sizesInputIdx:A})};const p=(f,c,a)=>{const t=(0,l.getGlsl)(f.session.backend.glContext.version),[e,r]=f.calculateTextureWidthAndHeight(c[0].dims,d.TextureType.unpacked),i=c[0].dims.map((A,O)=>Math.floor(A*a.scales[O])),[h,g]=f.calculateTextureWidthAndHeight(i,d.TextureType.unpacked),m=i.length,b=new Array(m),y=new Array(m);let w=` + int output_pitches[${m}]; + int input_pitches[${m}]; + `;for(let A=m-1;A>=0;A--)b[A]=A===m-1?1:b[A+1]*i[A+1],y[A]=A===m-1?1:y[A+1]*c[0].dims[A+1],w+=` + output_pitches[${A}] = ${b[A]}; + input_pitches[${A}] = ${y[A]}; + `;const T=` + float getInputFloat(int index) { + vec2 coords = offsetToCoords(index, ${e}, ${r}); + float value = getColorAsFloat(${t.texture2D}(X, coords)); + return value; + } + `,S=a.mode==="nearest"?` + ${T} + float process(int indices[${m}]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${h}, ${g}); + + ${w} + + int d, m; + for (int dim = 0; dim < ${m}; ++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); + }`:m===4?` + ${T} + float process(int indices[4]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${h}, ${g}); + + ${w} + + 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]); + }`:` + ${T} + float process(int indices[2]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${h}, ${g}); + + ${w} + + 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({},s),{output:{dims:i,type:c[0].type,textureType:d.TextureType.unpacked},shaderSource:S,variables:[{name:"scales",type:"int",arrayLength:a.scales.length,data:a.scales.map(A=>Math.ceil(A))}]})};n.validateInputs=(f,c)=>{if(!f||c.opset<9&&f.length!==1||c.opset>=9&&c.opset<11&&f.length!==2||c.opset>=11&&f.length<2)throw new Error("invalid inputs.");if(c.scales.length>0&&f[0].dims.length!==c.scales.length)throw new Error("Invalid input shape.");if(f[0].type==="string")throw new Error("Invalid input tensor types.")},n.scalesValidation=(f,c,a)=>{if(a){for(const t of f)if(t<=0)throw new Error("Scale value should be greater than 0.")}else for(const t of f)if(t<1)throw new Error("Scale value should be greater than or equal to 1.");if(!(c!=="linear"&&c!=="cubic"||f.length===2||f.length===4&&f[0]===1&&f[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 ${a?"Resize":"Upsample"} opeartor.`)}},1958:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ProgramManager=void 0;const u=o(1670),l=o(6231),d=o(8879),s=o(5060);n.ProgramManager=class{constructor(p,f,c){this.profiler=p,this.glContext=f,this.textureLayoutStrategy=c,this.repo=new Map,this.attributesBound=!1}getArtifact(p){return this.repo.get(p)}setArtifact(p,f){this.repo.set(p,f)}run(p,f,c){var a;this.profiler.event("op",`ProgramManager.run ${(a=p.programInfo.name)!==null&&a!==void 0?a:"unknown kernel"}`,()=>{var t;const e=this.glContext.gl,r=p.program;e.useProgram(r);try{this.bindOutput(c),this.attributesBound||this.bindAttributes(p.attribLocations),this.bindUniforms(p.uniformLocations,(t=p.programInfo.variables)!==null&&t!==void 0?t:[],f)}catch(i){throw l.Logger.error("ProgramManager",p.programInfo.shaderSource),i}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach(p=>this.glContext.deleteProgram(p.program))}build(p,f,c){return this.profiler.event("backend","ProgramManager.build",()=>{const a=new d.GlslPreprocessor(this.glContext,p,f,c),t=a.preprocess(),e=this.compile(t);return{programInfo:p,program:e,uniformLocations:this.getUniformLocations(e,a.context.programInfo.inputNames,a.context.programInfo.variables),attribLocations:this.getAttribLocations(e)}})}compile(p){if(!this.vertexShader){l.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const a=(0,s.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(a,this.glContext.gl.VERTEX_SHADER)}u.env.debug&&l.Logger.verbose("ProrgramManager",`FragShader: +${p} +`);const f=this.glContext.compileShader(p,this.glContext.gl.FRAGMENT_SHADER),c=this.glContext.createProgram(this.vertexShader,f);return this.glContext.deleteShader(f),c}bindOutput(p){const f=p.width,c=p.height;l.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${f}/${c}, shape=${p.shape}, type=${p.tensor.type}`),this.glContext.attachFramebuffer(p.texture,f,c)}bindAttributes(p){const f=p.position,c=p.textureCoord;this.glContext.setVertexAttributes(f,c),this.attributesBound=!0}bindUniforms(p,f,c){var a;const t=this.glContext.gl;let e=0;for(const{name:r,type:i,location:h,arrayLength:g}of p){const m=(a=f.find(b=>b.name===r))===null||a===void 0?void 0:a.data;if(i!=="sampler2D"&&!m)throw new Error(`variable '${r}' does not have data defined in program info`);switch(i){case"sampler2D":this.bindTexture(c[e],h,e),e++;break;case"float":g?t.uniform1fv(h,m):t.uniform1f(h,m);break;case"int":g?t.uniform1iv(h,m):t.uniform1i(h,m);break;default:throw new Error(`Uniform not implemented: ${i}`)}}}bindTexture(p,f,c){this.glContext.bindTextureToUniform(p.texture,c,f)}getAttribLocations(p){return{position:this.getAttribLocation(p,"position"),textureCoord:this.getAttribLocation(p,"textureCoord")}}getUniformLocations(p,f,c){const a=[];if(f)for(const t of f)a.push({name:t,type:"sampler2D",location:this.getUniformLocation(p,t)});if(c)for(const t of c)a.push(Object.assign(Object.assign({},t),{location:this.getUniformLocation(p,t.name)}));return a}getUniformLocation(p,f){const c=this.glContext.gl.getUniformLocation(p,f);if(c===null)throw new Error(`Uniform ${f} not found.`);return c}getAttribLocation(p,f){return this.glContext.gl.getAttribLocation(p,f)}}},6416:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLSessionHandler=void 0;const u=o(6231),l=o(1047),d=o(8316),s=o(1640),p=o(1958),f=o(7859),c=o(5702);n.WebGLSessionHandler=class{constructor(a,t){this.backend=a,this.context=t,this.layoutStrategy=new f.PreferLogicalStrategy(a.glContext.maxTextureSize),this.programManager=new p.ProgramManager(this.context.profiler,a.glContext,this.layoutStrategy),this.textureManager=new c.TextureManager(a.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:a.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=a.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new d.WebGLInferenceHandler(this)}onGraphInitialized(a){const t=a.getValues().filter(e=>e.from===-1&&e.tensor).map(e=>e.tensor.dataId);this.initializers=new Set(t)}isInitializer(a){return!!this.initializers&&this.initializers.has(a)}addInitializer(a){this.initializers.add(a)}getTextureData(a,t){return t?this.packedTextureDataCache.get(a):this.unpackedTextureDataCache.get(a)}setTextureData(a,t,e=!1){u.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),e?this.packedTextureDataCache.set(a,t):this.unpackedTextureDataCache.set(a,t)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(a=>this.textureManager.releaseTexture(a,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(a=>this.textureManager.releaseTexture(a,!0)),this.unpackedTextureDataCache=new Map}resolve(a,t,e){const r=(0,l.resolveOperator)(a,t,s.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(a,e):a}}}},7769:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Uint8DataEncoder=n.RGBAFloatDataEncoder=n.RedFloat32DataEncoder=void 0;const u=o(6231);n.RedFloat32DataEncoder=class{constructor(l,d=1){if(d===1)this.internalFormat=l.R32F,this.format=l.RED,this.textureType=l.FLOAT,this.channelSize=d;else{if(d!==4)throw new Error(`Invalid number of channels: ${d}`);this.internalFormat=l.RGBA32F,this.format=l.RGBA,this.textureType=l.FLOAT,this.channelSize=d}}encode(l,d){let s,p;return l.constructor!==Float32Array&&(u.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),p=new Float32Array(l)),d*this.channelSize>l.length?(u.Logger.warning("Encoder","Source data too small. Allocating larger array"),p=l,s=this.allocate(d*this.channelSize),p.forEach((f,c)=>s[c]=f)):(p=l,s=p),s}allocate(l){return new Float32Array(4*l)}decode(l,d){return this.channelSize===1?l.filter((s,p)=>p%4==0).subarray(0,d):l.subarray(0,d)}},n.RGBAFloatDataEncoder=class{constructor(l,d=1,s){if(d!==1&&d!==4)throw new Error(`Invalid number of channels: ${d}`);this.internalFormat=l.RGBA,this.format=l.RGBA,this.channelSize=d,this.textureType=s||l.FLOAT}encode(l,d){let s=l;return this.channelSize===1&&(u.Logger.verbose("Encoder","Exploding into a larger array"),s=this.allocate(d),l.forEach((p,f)=>s[4*f]=p)),s}allocate(l){return new Float32Array(4*l)}decode(l,d){return this.channelSize===1?l.filter((s,p)=>p%4==0).subarray(0,d):l.subarray(0,d)}},n.Uint8DataEncoder=class{constructor(l,d=1){if(this.channelSize=4,d===1)this.internalFormat=l.ALPHA,this.format=l.ALPHA,this.textureType=l.UNSIGNED_BYTE,this.channelSize=d;else{if(d!==4)throw new Error(`Invalid number of channels: ${d}`);this.internalFormat=l.RGBA,this.format=l.RGBA,this.textureType=l.UNSIGNED_BYTE,this.channelSize=d}}encode(l,d){return new Uint8Array(l.buffer,l.byteOffset,l.byteLength)}allocate(l){return new Uint8Array(l*this.channelSize)}decode(l,d){if(l instanceof Uint8Array)return l.subarray(0,d);throw new Error(`Invalid array type: ${l.constructor}`)}}},7859:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getBatchDim=n.sizeToSquarishShape=n.getRowsCols=n.sizeFromShape=n.isInt=n.parseAxisParam=n.squeezeShape=n.PreferLogicalStrategy=n.AlwaysKeepOriginalSizeStrategy=void 0;const u=o(6231),l=o(2517);function d(a,t){const e=[],r=[],i=t!=null&&Array.isArray(t)&&t.length===0,h=t==null||i?null:s(t,a).sort();let g=0;for(let m=0;mm)&&a[m]===1&&(e.push(a[m]),r.push(m)),h[g]<=m&&g++}a[m]!==1&&(e.push(a[m]),r.push(m))}return{newShape:e,keptDims:r}}function s(a,t){const e=t.length;return a=a==null?t.map((r,i)=>i):[].concat(a),(0,l.assert)(a.every(r=>r>=-e&&r`All values in axis param must be in range [-${e}, ${e}) but got axis ${a}`),(0,l.assert)(a.every(p),()=>`All values in axis param must be integers but got axis ${a}`),a.map(r=>r<0?e+r:r)}function p(a){return a%1==0}function f(a){if(a.length===0)return 1;let t=a[0];for(let e=1;e=a.length?1:a.slice(t.breakAxis).reduce((m,b)=>m*b),g=t.breakAxis<=0?1:a.slice(0,t.breakAxis).reduce((m,b)=>m*b);if(!(h>e||g>e))return[h,g];u.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${a}, breakAxis:${t.breakAxis}`)}const r=a.reduce((h,g)=>h*g);let i=Math.floor(Math.sqrt(r));for(;i=e||r%i!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${a}`);return[i,r/i]}},n.PreferLogicalStrategy=class{constructor(a){this.maxTextureSize=a}computeTextureWH(a,t){const e=this.computeTexture(a,t);return t&&t.isPacked&&(e[0]/=2,e[1]/=2),t&&t.reverseWH?[e[1],e[0]]:e}computeTexture(a,t){const e=t&&t.isPacked;if(a.length===0)return e?[2,2]:[1,1];let r=this.maxTextureSize;if(t&&t.breakAxis!==void 0){const g=t.breakAxis>=a.length?1:a.slice(t.breakAxis).reduce((b,y)=>b*y),m=t.breakAxis<=0?1:a.slice(0,t.breakAxis).reduce((b,y)=>b*y);if(!(g>r||m>r))return[g,m];u.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${a}, breakAxis:${t.breakAxis}`)}let i=a.slice(0);e&&(r*=2,i=i.map((g,m)=>m>=i.length-2?i[m]%2==0?i[m]:i[m]+1:i[m]),i.length===1&&(i=[2,i[0]])),i.length!==2&&(i=d(i).newShape);const h=f(i);return i.length<=1&&h<=r?[1,h]:i.length===2&&i[0]<=r&&i[1]<=r?i:i.length===3&&i[0]*i[1]<=r&&i[2]<=r?[i[0]*i[1],i[2]]:i.length===3&&i[0]<=r&&i[1]*i[2]<=r?[i[0],i[1]*i[2]]:i.length===4&&i[0]*i[1]*i[2]<=r&&i[3]<=r?[i[0]*i[1]*i[2],i[3]]:i.length===4&&i[0]<=r&&i[1]*i[2]*i[3]<=r?[i[0],i[1]*i[2]*i[3]]:e?c(h/4).map(g=>2*g):c(h)}},n.squeezeShape=d,n.parseAxisParam=s,n.isInt=p,n.sizeFromShape=f,n.getRowsCols=function(a){if(a.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[a.length>1?a[a.length-2]:1,a[a.length-1]]},n.sizeToSquarishShape=c,n.getBatchDim=function(a,t=2){return f(a.slice(0,a.length-t))}},4057:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createTextureLayoutFromShape=n.calculateTextureWidthAndHeight=n.createTextureLayoutFromTextureType=void 0;const u=o(2517),l=o(2039);n.createTextureLayoutFromTextureType=(d,s,p)=>{const f=p===l.TextureType.unpacked||p===l.TextureType.unpackedReversed?1:4,c=p===l.TextureType.packed,a=p===l.TextureType.unpackedReversed||p===l.TextureType.packed,t=p===l.TextureType.packedLastDimension?s.length-1:void 0,e=p===l.TextureType.packedLastDimension?s.map((r,i)=>i===s.length-1?4*r:r):void 0;return(0,n.createTextureLayoutFromShape)(d,s,f,e,{isPacked:c,reverseWH:a,breakAxis:t})},n.calculateTextureWidthAndHeight=(d,s,p)=>{const f=(0,n.createTextureLayoutFromTextureType)(d,s,p);return[f.width,f.height]},n.createTextureLayoutFromShape=(d,s,p=1,f,c)=>{const a=!(!c||!c.isPacked),[t,e]=d.computeTextureWH(a&&f||s,c),r=s.length;let i=s.slice(0);if(r===0&&(i=[1]),p===1)f=s;else if(a){if(p!==4)throw new Error("a packed texture must be 4-channel");f=s,r>0&&(i[r-1]=Math.ceil(i[r-1]/2)),r>1&&(i[r-2]=Math.ceil(i[r-2]/2))}else if(!f)throw new Error("Unpacked shape is needed when using channels > 1");return{width:t,height:e,channels:p,isPacked:a,shape:i,strides:u.ShapeUtil.computeStrides(i),unpackedShape:f,reversedWH:c&&c.reverseWH}}},5702:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.TextureManager=void 0;const u=o(6231);n.TextureManager=class{constructor(l,d,s,p){this.glContext=l,this.layoutStrategy=d,this.profiler=s,this.config=p,this.pendingRead=new Map,p.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(l,d,s,p){const f=this.toEncoderType(l),c=this.glContext.getEncoder(f,d.channels||1,p);if(d.isPacked&&p===1)throw new Error("not implemented");const a=d.width,t=d.height;let e,r;if(this.config.reuseTextures){e=`${a}x${t}_${c.format}_${c.internalFormat}_${c.textureType}`,r=this.inUseTextures.get(e),r||(r=[],this.inUseTextures.set(e,r));const h=this.idleTextures.get(e);if(h&&h.length>0){const g=h.pop();return r.push(g),p===1&&this.glContext.updateTexture(g,a,t,c,this.toTextureData(l,s)),g}}u.Logger.verbose("TextureManager",`Creating new texture of size ${d.width}x${d.height}`);const i=this.glContext.allocateTexture(a,t,c,this.toTextureData(l,s));return this.config.reuseTextures&&(r.push(i),this.textureLookup.set(i,e)),i}readTexture(l,d,s){return s||(s=1),this.profiler.event("backend","TextureManager.readTexture",()=>{const p=l.shape.reduce((c,a)=>c*a)*s,f=this.glContext.readTexture(l.texture,l.width,l.height,p,this.toEncoderType(d),s);return this.toTensorData(d,f)})}async readTextureAsync(l,d,s){const p=l.tensor.dataId;if(s||(s=1),this.pendingRead.has(p)){const f=this.pendingRead.get(p);return new Promise(c=>f==null?void 0:f.push(c))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(p,[]);const f=l.shape.reduce((e,r)=>e*r)*s;await this.glContext.createAndWaitForFence();const c=this.glContext.readTexture(l.texture,l.width,l.height,f,this.toEncoderType(d),s),a=this.toTensorData(d,c),t=this.pendingRead.get(p);return this.pendingRead.delete(p),t==null||t.forEach(e=>e(a)),a})}readUint8TextureAsFloat(l){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{const d=l.shape.reduce((p,f)=>p*f),s=this.glContext.readTexture(l.texture,l.width,l.height,4*d,"byte",4);return new Float32Array(s.buffer,s.byteOffset,d)})}releaseTexture(l,d){let s;if(this.config.reuseTextures&&(s=this.textureLookup.get(l.texture),s)){d&&this.textureLookup.delete(s);const p=this.inUseTextures.get(s);if(p){const f=p.indexOf(l.texture);if(f!==-1){p.splice(f,1);let c=this.idleTextures.get(s);c||(c=[],this.idleTextures.set(s,c)),c.push(l.texture)}}}s&&!d||(u.Logger.verbose("TextureManager",`Deleting texture of size ${l.width}x${l.height}`),this.glContext.deleteTexture(l.texture))}toTensorData(l,d){switch(l){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 ${l} is not supported`)}}toTextureData(l,d){if(d)return d instanceof Float32Array?d:new Float32Array(d)}toEncoderType(l){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},2039:(_,n)=>{var o;Object.defineProperty(n,"__esModule",{value:!0}),n.TextureType=void 0,(o=n.TextureType||(n.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:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getGlChannels=n.getCoordsDataType=n.getSqueezedParams=n.squeezeInputShape=n.generateShaderFuncNameFromInputSamplerNameAtOutCoords=n.generateShaderFuncNameFromInputSamplerName=n.repeatedTry=n.getPackedShape=void 0;const u=o(2517);n.getPackedShape=function(l){const d=l.length;return l.slice(0,d-1).concat(l[d-1]/4)},n.repeatedTry=async function(l,d=p=>0,s){return new Promise((p,f)=>{let c=0;const a=()=>{if(l())return void p();c++;const t=d(c);s!=null&&c>=s?f():setTimeout(a,t)};a()})},n.generateShaderFuncNameFromInputSamplerName=function(l){return(0,u.assert)(l!==void 0&&l.length!==0,()=>"empty string found for sampler name"),"get"+l.charAt(0).toUpperCase()+l.slice(1)},n.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(l){return(0,u.assert)(l!==void 0&&l.length!==0,()=>"empty string found for sampler name"),"get"+l.charAt(0).toUpperCase()+l.slice(1)+"AtOutCoords"},n.squeezeInputShape=function(l,d){let s=JSON.parse(JSON.stringify(l));return s=d,s},n.getSqueezedParams=function(l,d){return d.map(s=>l[s]).join(", ")},n.getCoordsDataType=function(l){if(l<=1)return"int";if(l===2)return"ivec2";if(l===3)return"ivec3";if(l===4)return"ivec4";if(l===5)return"ivec5";if(l===6)return"ivec6";throw Error(`GPU for rank ${l} is not yet supported`)},n.getGlChannels=function(l=6){return["x","y","z","w","u","v"].slice(0,l)}},7305:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createNewWebGLContext=n.createWebGLContext=void 0;const u=o(6231),l=o(1713),d={};function s(p){const f=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 t=document.createElement("canvas");return t.width=1,t.height=1,t}();let c;const a={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!p||p==="webgl2")&&(c=f.getContext("webgl2",a),c))try{return new l.WebGLContext(c,2)}catch(t){u.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${t}`)}if((!p||p==="webgl")&&(c=f.getContext("webgl",a)||f.getContext("experimental-webgl",a),c))try{return new l.WebGLContext(c,1)}catch(t){u.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t}`)}throw new Error("WebGL is not supported")}n.createWebGLContext=function p(f){let c;f&&f!=="webgl2"||!("webgl2"in d)?f&&f!=="webgl"||!("webgl"in d)||(c=d.webgl):c=d.webgl2,c=c||s(f),f=f||c.version===1?"webgl":"webgl2";const a=c.gl;return d[f]=c,a.isContextLost()?(delete d[f],p(f)):(a.disable(a.DEPTH_TEST),a.disable(a.STENCIL_TEST),a.disable(a.BLEND),a.disable(a.DITHER),a.disable(a.POLYGON_OFFSET_FILL),a.disable(a.SAMPLE_COVERAGE),a.enable(a.SCISSOR_TEST),a.enable(a.CULL_FACE),a.cullFace(a.BACK),c)},n.createNewWebGLContext=s},1713:function(_,n,o){var u=this&&this.__createBinding||(Object.create?function(a,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(a,r,i)}:function(a,t,e,r){r===void 0&&(r=e),a[r]=t[e]}),l=this&&this.__setModuleDefault||(Object.create?function(a,t){Object.defineProperty(a,"default",{enumerable:!0,value:t})}:function(a,t){a.default=t}),d=this&&this.__importStar||function(a){if(a&&a.__esModule)return a;var t={};if(a!=null)for(var e in a)e!=="default"&&Object.prototype.hasOwnProperty.call(a,e)&&u(t,a,e);return l(t,a),t};Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLContext=n.linearSearchLastTrue=void 0;const s=o(1670),p=d(o(7769)),f=o(9390);function c(a){let t=0;for(;tthis.isTimerResultAvailable(a)),this.getTimerResult(a)}async createAndWaitForFence(){const a=this.createFence(this.gl);return this.pollFence(a)}createFence(a){let t;const e=a,r=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return a.flush(),t=r===null?()=>!0:()=>{const i=e.clientWaitSync(r,0,0);return i===e.ALREADY_SIGNALED||i===e.CONDITION_SATISFIED},{query:r,isFencePassed:t}}async pollFence(a){return new Promise(t=>{this.addItemToPoll(()=>a.isFencePassed(),()=>t())})}pollItems(){const a=c(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=a;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(a+1)}async addItemToPoll(a,t){this.itemsToPoll.push({isDoneFn:a,resolveFn:t}),this.itemsToPoll.length>1||await(0,f.repeatedTry)(()=>(this.pollItems(),this.itemsToPoll.length===0))}}},1036:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ExecutionPlan=void 0;const u=o(6231);class l{constructor(s,p){this.op=s,this.node=p}}n.ExecutionPlan=class{constructor(d,s,p){this.graph=d,this.profiler=p,this.initialize(s)}initialize(d){this.profiler.event("session","ExecutionPlan.initialize",()=>{const s=this.graph.getNodes();if(s.length!==d.length)throw new Error("The size of nodes and OPs do not match.");this._ops=d.map((p,f)=>new l(p,s[f])),this.reset(),this._starter=[],this._ops.forEach((p,f)=>{let c=!0;for(const a of p.node.inputs)if(!this._values[a]&&this.graph.getInputIndices().indexOf(a)===-1){c=!1;break}c&&this._starter.push(f)})})}reset(){this._values=this.graph.getValues().map(d=>d.tensor)}async execute(d,s){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();const p=d.createInferenceHandler(),f=this.graph.getInputIndices();if(s.length!==f.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${s.length} expected: ${f.length}`);s.forEach((i,h)=>{const g=f[h];this._values[g]=i});const c=this._starter.slice(0),a=this.graph.getValues(),t=this.graph.getNodes();let e=0;for(;ethis._values[w]);if(g.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${h.node}`);const m=g;u.Logger.verbose("ExecPlan",`Runing op:${h.node.name} (${m.map((w,T)=>`'${h.node.inputs[T]}': ${w.type}[${w.dims.join(",")}]`).join(", ")})`);const b=await this.profiler.event("node",h.node.name,async()=>h.op.impl(p,m,h.op.context));if(b.length!==h.node.outputs.length)throw new Error("the size of output does not match model definition.");b.forEach((w,T)=>{const S=h.node.outputs[T];if(this._values[S])throw new Error(`output [${S}] already has value: op:${h.node.name}`);this._values[S]=w});const y=new Set;b.forEach((w,T)=>{const S=h.node.outputs[T];for(const A of a[S].to){const O=t[A];let v=!0;for(const M of O.inputs)if(!this._values[M]){v=!1;break}v&&y.add(A)}}),c.push(...y)}const r=[];for(let i=0;i{Object.defineProperty(n,"__esModule",{value:!0}),n.Graph=void 0;const u=o(1446),l=o(7778),d=o(9395),s=o(9162),p=o(2517);var f=d.onnxruntime.experimental.fbs;n.Graph={from:(e,r)=>new t(e,r)};class c{constructor(r){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,r&&(this.type=p.ProtoUtil.tensorValueTypeFromProto(r.type.tensorType))}get from(){return this._from}get to(){return this._to}}class a{constructor(r,i){r instanceof u.onnx.NodeProto?(this.name=r.name,this.opType=r.opType,this.attributes=new l.Attribute(r.attribute)):r instanceof f.Node&&(this.name=i??r.name(),this.opType=r.opType(),this.attributes=new l.Attribute(p.ProtoUtil.tensorAttributesFromORTFormat(r))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class t{constructor(r,i){if(!r)throw new TypeError("graph is empty");this.buildGraph(r),this.transformGraph(i),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 u.onnx.GraphProto)this.buildGraphFromOnnxFormat(r);else{if(!(r instanceof f.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(r)}}buildGraphFromOnnxFormat(r){const i=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const h=new Map;if(!r.input)throw new Error("missing information in graph: input");const g=[];for(const m of r.input){if(i.has(m.name))throw new Error(`duplicated input name: ${m.name}`);const b=this._allData.push(new c(m))-1;i.set(m.name,b),g.push(m.name)}if(!r.initializer)throw new Error("missing information in graph: initializer");for(const m of r.initializer){let b=i.get(m.name);if(b===void 0){const y=new c;y.type={shape:{dims:p.ProtoUtil.tensorDimsFromProto(m.dims)},tensorType:p.ProtoUtil.tensorDataTypeFromProto(m.dataType)},b=this._allData.push(y)-1,i.set(m.name,b)}this._allData[b]._from=-1,this._allData[b].tensor=s.Tensor.fromProto(m)}for(let m=0;m{this._allData[g]._to.forEach(m=>{r.add(m)})});const i=Array.from(r),h=new Array(this._nodes.length).fill("white");for(;i.length>0;){const g=i.pop();h[g]==="gray"?h[g]="black":(i.push(g),h[g]="gray",this._nodes[g].outputs.forEach(m=>{const b=this._allData[m];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(h[y]==="gray")throw new Error("model graph is cyclic");h[y]==="white"&&i.push(y)})}))}}transformGraph(r){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),r&&r.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let r=0;for(let i=0;i0&&(this._nodes[i].inputs.forEach(h=>{const g=this._allData[h]._to.indexOf(i+r);g!==-1&&(this._allData[h]._to[g]=i)}),this._nodes[i].outputs.forEach(h=>{this._allData[h]._from&&this._allData[h]._from===i+r&&(this._allData[h]._from=i)})):(r++,this._nodes[i].outputs.forEach(h=>{this._allData[h]._from=-2}),this._nodes.splice(i,1),i--);r=0;for(let i=0;i0){let h=-1;this._allData[i].from!==void 0&&this._allData[i].from!==-1?(h=this._nodes[this._allData[i].from].outputs.indexOf(i+r),h!==-1&&(this._nodes[this._allData[i].from].outputs[h]=i)):(h=this._allInputIndices.indexOf(i+r),h!==-1&&(this._allInputIndices[h]=i)),this._allData[i].to.forEach(g=>{h=this._nodes[g].inputs.indexOf(i+r),h!==-1&&(this._nodes[g].inputs[h]=i)}),this._allData[i].to.length===0&&(h=this._allOutputIndices.indexOf(i+r),h!==-1&&(this._allOutputIndices[h]=i))}}else r++,this._allData.splice(i,1),i--}deleteNode(r){const i=this._nodes[r];if(i.outputs.length>1){for(let w=1;w0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}i.executeNode=!1;const h=i.inputs[0],g=i.outputs[0],m=this._allData[g].to,b=this._allData[h].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[h].to.splice(b,1),this._allData[g]._to=[];const y=this._allOutputIndices.indexOf(g);if(y!==-1&&(this._allOutputIndices[y]=h),m&&m.length>0)for(const w of m){const T=this._nodes[w].inputs.indexOf(g);if(T===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[w].inputs[T]=h,this._allData[h].to.push(w)}}removeAllDropoutNodes(){let r=0;for(const i of this._nodes){if(i.opType==="Dropout"){if(i.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(i.outputs.length!==1&&i.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(i.outputs.length===2&&this._allData[i.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 i of this._nodes)i.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 i=this._allData[r.outputs[0]]._to;if(i.length===1&&this.isActivation(this._nodes[i[0]])){const h=this._nodes[i[0]];if(h.opType==="Clip")if(h.inputs.length===1)try{r.attributes.set("activation_params","floats",[h.attributes.getFloat("min"),h.attributes.getFloat("max")])}catch{r.attributes.set("activation_params","floats",[p.MIN_CLIP,p.MAX_CLIP])}else{if(!(h.inputs.length>=3&&this._allData[h.inputs[1]].tensor!==void 0&&this._allData[h.inputs[2]].tensor!==void 0))continue;r.attributes.set("activation_params","floats",[this._allData[h.inputs[1]].tensor.floatData[0],this._allData[h.inputs[2]].tensor.floatData[0]])}r.attributes.set("activation","string",h.opType),this.deleteNode(i[0])}}}}},6231:(_,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.now=n.Profiler=n.Logger=void 0;const o={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},u={none:new class{log(a,t,e){}},console:new class{log(a,t,e){console.log(`${this.color(a)} ${e?"\x1B[35m"+e+"\x1B[0m ":""}${t}`)}color(a){switch(a){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: ${a}`)}}}},l={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let d={"":l};function s(a,t,e,r){if(t===void 0)return i=a,{verbose:s.verbose.bind(null,i),info:s.info.bind(null,i),warning:s.warning.bind(null,i),error:s.error.bind(null,i),fatal:s.fatal.bind(null,i)};if(e===void 0)p(a,t);else if(typeof e=="number"&&r===void 0)p(a,t);else if(typeof e=="string"&&r===void 0)p(a,e,0,t);else{if(typeof e!="string"||typeof r!="number")throw new TypeError("input is valid");p(a,e,0,t)}var i}function p(a,t,e,r){const i=d[r||""]||d[""];o[a]{g.then(async y=>{i&&await i.end(),m(y)},async y=>{i&&await i.end(),b(y)})});if(!h&&i){const m=i.end();if(m&&typeof m.then=="function")return new Promise((b,y)=>{m.then(()=>{b(g)},w=>{y(w)})})}return g}begin(a,t,e){if(!this._started)throw new Error("profiler is not started yet");if(e===void 0){const r=(0,n.now)();return this.flush(r),new f(a,t,r,i=>this.endSync(i))}{const r=e.beginTimer();return new f(a,t,0,async i=>this.end(i),r,e)}}async end(a){const t=await a.checkTimer();this._timingEvents.length=this._flushBatchSize||a-this._flushTime>=this._flushIntervalInMilliseconds){for(const t=this._flushPointer;this._flushPointerperformance.now():Date.now},2644:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Model=void 0;const u=o(5686),l=o(1446),d=o(7070),s=o(9395),p=o(2517);var f=s.onnxruntime.experimental.fbs;n.Model=class{constructor(){}load(c,a,t){if(!t)try{return void this.loadFromOnnxFormat(c,a)}catch(e){if(t!==void 0)throw e}this.loadFromOrtFormat(c,a)}loadFromOnnxFormat(c,a){const t=l.onnx.ModelProto.decode(c);if(p.LongUtil.longToNumber(t.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=t.opsetImport.map(e=>({domain:e.domain,version:p.LongUtil.longToNumber(e.version)})),this._graph=d.Graph.from(t.graph,a)}loadFromOrtFormat(c,a){const t=new u.flatbuffers.ByteBuffer(c),e=f.InferenceSession.getRootAsInferenceSession(t).model();if(p.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(n,"__esModule",{value:!0}),n.FLOAT_TYPES=n.INT_TYPES=n.NUMBER_TYPES=void 0,n.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],n.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],n.FLOAT_TYPES=["float32","float64"]},1047:(_,n)=>{function o(u,l){if(l.endsWith("+")){const d=Number.parseInt(l.substring(0,l.length-1),10);return!isNaN(d)&&d<=u}if(l.split("-").length===2){const d=l.split("-"),s=Number.parseInt(d[0],10),p=Number.parseInt(d[1],10);return!isNaN(s)&&!isNaN(p)&&s<=u&&u<=p}return Number.parseInt(l,10)===u}Object.defineProperty(n,"__esModule",{value:!0}),n.resolveOperator=void 0,n.resolveOperator=function(u,l,d){for(const s of d){const p=s[0],f=s[1],c=s[2],a=s[3],t=s[4];if(u.opType===p){for(const e of l)if((e.domain===f||e.domain==="ai.onnx"&&f==="")&&o(e.version,c))return{opImpl:a,opInit:t}}}throw new TypeError(`cannot resolve operator '${u.opType}' with opsets: ${l.map(s=>`${s.domain||"ai.onnx"} v${s.version}`).join(", ")}`)}},9395:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.onnxruntime=void 0;const u=o(5686);var l,d;l=n.onnxruntime||(n.onnxruntime={}),function(s){(function(p){p[p.UNDEFINED=0]="UNDEFINED",p[p.FLOAT=1]="FLOAT",p[p.INT=2]="INT",p[p.STRING=3]="STRING",p[p.TENSOR=4]="TENSOR",p[p.GRAPH=5]="GRAPH",p[p.FLOATS=6]="FLOATS",p[p.INTS=7]="INTS",p[p.STRINGS=8]="STRINGS",p[p.TENSORS=9]="TENSORS",p[p.GRAPHS=10]="GRAPHS",p[p.SPARSE_TENSOR=11]="SPARSE_TENSOR",p[p.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(s.AttributeType||(s.AttributeType={}))}((d=l.experimental||(l.experimental={})).fbs||(d.fbs={})),function(s){(function(p){(function(f){(function(c){c[c.UNKNOWN=0]="UNKNOWN",c[c.VALUE=1]="VALUE",c[c.PARAM=2]="PARAM"})(f.DimensionValueType||(f.DimensionValueType={}))})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){(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"})(f.TensorDataType||(f.TensorDataType={}))})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){(function(c){c[c.Primitive=0]="Primitive",c[c.Fused=1]="Fused"})(f.NodeType||(f.NodeType={}))})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){(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"})(f.TypeInfoValue||(f.TypeInfoValue={}))})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsShape(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsShape(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}dim(t,e){let r=this.bb.__offset(this.bb_pos,4);return r?(e||new s.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}dimLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}static startShape(t){t.startObject(1)}static addDim(t,e){t.addFieldOffset(0,e,0)}static createDimVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startDimVector(t,e){t.startVector(4,e,4)}static endShape(t){return t.endObject()}static createShape(t,e){return c.startShape(t),c.addDim(t,e),c.endShape(t)}}f.Shape=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimension(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimension(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}value(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new s.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}denotation(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimension(t){t.startObject(2)}static addValue(t,e){t.addFieldOffset(0,e,0)}static addDenotation(t,e){t.addFieldOffset(1,e,0)}static endDimension(t){return t.endObject()}static createDimension(t,e,r){return c.startDimension(t),c.addValue(t,e),c.addDenotation(t,r),c.endDimension(t)}}f.Dimension=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimensionValue(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimensionValue(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}dimType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt8(this.bb_pos+t):s.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}dimParam(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimensionValue(t){t.startObject(3)}static addDimType(t,e){t.addFieldInt8(0,e,s.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static addDimParam(t,e){t.addFieldOffset(2,e,0)}static endDimensionValue(t){return t.endObject()}static createDimensionValue(t,e,r,i){return c.startDimensionValue(t),c.addDimType(t,e),c.addDimValue(t,r),c.addDimParam(t,i),c.endDimensionValue(t)}}f.DimensionValue=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensorTypeAndShape(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensorTypeAndShape(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}elemType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):s.experimental.fbs.TensorDataType.UNDEFINED}shape(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new s.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startTensorTypeAndShape(t){t.startObject(2)}static addElemType(t,e){t.addFieldInt32(0,e,s.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(t,e){t.addFieldOffset(1,e,0)}static endTensorTypeAndShape(t){return t.endObject()}static createTensorTypeAndShape(t,e,r){return c.startTensorTypeAndShape(t),c.addElemType(t,e),c.addShape(t,r),c.endTensorTypeAndShape(t)}}f.TensorTypeAndShape=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMapType(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMapType(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}keyType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):s.experimental.fbs.TensorDataType.UNDEFINED}valueType(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new s.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startMapType(t){t.startObject(2)}static addKeyType(t,e){t.addFieldInt32(0,e,s.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(t,e){t.addFieldOffset(1,e,0)}static endMapType(t){return t.endObject()}static createMapType(t,e,r){return c.startMapType(t),c.addKeyType(t,e),c.addValueType(t,r),c.endMapType(t)}}f.MapType=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSequenceType(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSequenceType(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}elemType(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new s.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSequenceType(t){t.startObject(1)}static addElemType(t,e){t.addFieldOffset(0,e,0)}static endSequenceType(t){return t.endObject()}static createSequenceType(t,e){return c.startSequenceType(t),c.addElemType(t,e),c.endSequenceType(t)}}f.SequenceType=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(p.fbs||(p.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(f,c){return this.bb_pos=f,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(f,c,a,t){return f.prep(4,12),f.writeInt32(t),f.writeInt32(a),f.writeInt32(c),f.offset()}}})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNodeEdge(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNodeEdge(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}nodeIndex(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb_pos+t):0}inputEdges(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new s.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}inputEdgesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}outputEdges(t,e){let r=this.bb.__offset(this.bb_pos,8);return r?(e||new s.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}outputEdgesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNodeEdge(t){t.startObject(3)}static addNodeIndex(t,e){t.addFieldInt32(0,e,0)}static addInputEdges(t,e){t.addFieldOffset(1,e,0)}static startInputEdgesVector(t,e){t.startVector(12,e,4)}static addOutputEdges(t,e){t.addFieldOffset(2,e,0)}static startOutputEdgesVector(t,e){t.startVector(12,e,4)}static endNodeEdge(t){return t.endObject()}static createNodeEdge(t,e,r,i){return c.startNodeEdge(t),c.addNodeIndex(t,e),c.addInputEdges(t,r),c.addOutputEdges(t,i),c.endNodeEdge(t)}}f.NodeEdge=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNode(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNode(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}sinceVersion(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):0}index(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint32(this.bb_pos+t):0}opType(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.readInt32(this.bb_pos+t):s.experimental.fbs.NodeType.Primitive}executionProviderType(t){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__string(this.bb_pos+e,t):null}inputs(t,e){let r=this.bb.__offset(this.bb_pos,20);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let r=this.bb.__offset(this.bb_pos,22);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}attributes(t,e){let r=this.bb.__offset(this.bb_pos,24);return r?(e||new s.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}attributesLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCounts(t){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.readInt32(this.bb.__vector(this.bb_pos+e)+4*t):0}inputArgCountsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCountsArray(){let t=this.bb.__offset(this.bb_pos,26);return t?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}implicitInputs(t,e){let r=this.bb.__offset(this.bb_pos,28);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}implicitInputsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNode(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDomain(t,e){t.addFieldOffset(2,e,0)}static addSinceVersion(t,e){t.addFieldInt32(3,e,0)}static addIndex(t,e){t.addFieldInt32(4,e,0)}static addOpType(t,e){t.addFieldOffset(5,e,0)}static addType(t,e){t.addFieldInt32(6,e,s.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(t,e){t.addFieldOffset(7,e,0)}static addInputs(t,e){t.addFieldOffset(8,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(9,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addAttributes(t,e){t.addFieldOffset(10,e,0)}static createAttributesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startAttributesVector(t,e){t.startVector(4,e,4)}static addInputArgCounts(t,e){t.addFieldOffset(11,e,0)}static createInputArgCountsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addInt32(e[r]);return t.endVector()}static startInputArgCountsVector(t,e){t.startVector(4,e,4)}static addImplicitInputs(t,e){t.addFieldOffset(12,e,0)}static createImplicitInputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startImplicitInputsVector(t,e){t.startVector(4,e,4)}static endNode(t){return t.endObject()}static createNode(t,e,r,i,h,g,m,b,y,w,T,S,A,O){return c.startNode(t),c.addName(t,e),c.addDocString(t,r),c.addDomain(t,i),c.addSinceVersion(t,h),c.addIndex(t,g),c.addOpType(t,m),c.addType(t,b),c.addExecutionProviderType(t,y),c.addInputs(t,w),c.addOutputs(t,T),c.addAttributes(t,S),c.addInputArgCounts(t,A),c.addImplicitInputs(t,O),c.endNode(t)}}f.Node=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsValueInfo(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsValueInfo(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(t){let e=this.bb.__offset(this.bb_pos,8);return e?(t||new s.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startValueInfo(t){t.startObject(3)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldOffset(2,e,0)}static endValueInfo(t){return t.endObject()}static createValueInfo(t,e,r,i){return c.startValueInfo(t),c.addName(t,e),c.addDocString(t,r),c.addType(t,i),c.endValueInfo(t)}}f.ValueInfo=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTypeInfo(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTypeInfo(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}denotation(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}valueType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):s.experimental.fbs.TypeInfoValue.NONE}value(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}static startTypeInfo(t){t.startObject(3)}static addDenotation(t,e){t.addFieldOffset(0,e,0)}static addValueType(t,e){t.addFieldInt8(1,e,s.experimental.fbs.TypeInfoValue.NONE)}static addValue(t,e){t.addFieldOffset(2,e,0)}static endTypeInfo(t){return t.endObject()}static createTypeInfo(t,e,r,i){return c.startTypeInfo(t),c.addDenotation(t,e),c.addValueType(t,r),c.addValue(t,i),c.endTypeInfo(t)}}f.TypeInfo=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsOperatorSetId(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsOperatorSetId(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}domain(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}version(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}static startOperatorSetId(t){t.startObject(2)}static addDomain(t,e){t.addFieldOffset(0,e,0)}static addVersion(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static endOperatorSetId(t){return t.endObject()}static createOperatorSetId(t,e,r){return c.startOperatorSetId(t),c.addDomain(t,e),c.addVersion(t,r),c.endOperatorSetId(t)}}f.OperatorSetId=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensor(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensor(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}dataType(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):s.experimental.fbs.TensorDataType.UNDEFINED}rawData(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}rawDataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}rawDataArray(){let t=this.bb.__offset(this.bb_pos,12);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}stringData(t,e){let r=this.bb.__offset(this.bb_pos,14);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}stringDataLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}static startTensor(t){t.startObject(6)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static addDataType(t,e){t.addFieldInt32(3,e,s.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(t,e){t.addFieldOffset(4,e,0)}static createRawDataVector(t,e){t.startVector(1,e.length,1);for(let r=e.length-1;r>=0;r--)t.addInt8(e[r]);return t.endVector()}static startRawDataVector(t,e){t.startVector(1,e,1)}static addStringData(t,e){t.addFieldOffset(5,e,0)}static createStringDataVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startStringDataVector(t,e){t.startVector(4,e,4)}static endTensor(t){return t.endObject()}static createTensor(t,e,r,i,h,g,m){return c.startTensor(t),c.addName(t,e),c.addDocString(t,r),c.addDims(t,i),c.addDataType(t,h),c.addRawData(t,g),c.addStringData(t,m),c.endTensor(t)}}f.Tensor=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSparseTensor(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSparseTensor(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}values(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new s.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}indices(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new s.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSparseTensor(t){t.startObject(3)}static addValues(t,e){t.addFieldOffset(0,e,0)}static addIndices(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static endSparseTensor(t){return t.endObject()}static createSparseTensor(t,e,r,i){return c.startSparseTensor(t),c.addValues(t,e),c.addIndices(t,r),c.addDims(t,i),c.endSparseTensor(t)}}f.SparseTensor=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsAttribute(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsAttribute(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt32(this.bb_pos+t):s.experimental.fbs.AttributeType.UNDEFINED}f(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readFloat32(this.bb_pos+t):0}i(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}s(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}t(t){let e=this.bb.__offset(this.bb_pos,16);return e?(t||new s.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}g(t){let e=this.bb.__offset(this.bb_pos,18);return e?(t||new s.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}floats(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.readFloat32(this.bb.__vector(this.bb_pos+e)+4*t):0}floatsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}floatsArray(){let t=this.bb.__offset(this.bb_pos,20);return t?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}ints(t){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}intsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}strings(t,e){let r=this.bb.__offset(this.bb_pos,24);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}stringsLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}tensors(t,e){let r=this.bb.__offset(this.bb_pos,26);return r?(e||new s.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}tensorsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}graphs(t,e){let r=this.bb.__offset(this.bb_pos,28);return r?(e||new s.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}graphsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startAttribute(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldInt32(2,e,s.experimental.fbs.AttributeType.UNDEFINED)}static addF(t,e){t.addFieldFloat32(3,e,0)}static addI(t,e){t.addFieldInt64(4,e,t.createLong(0,0))}static addS(t,e){t.addFieldOffset(5,e,0)}static addT(t,e){t.addFieldOffset(6,e,0)}static addG(t,e){t.addFieldOffset(7,e,0)}static addFloats(t,e){t.addFieldOffset(8,e,0)}static createFloatsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addFloat32(e[r]);return t.endVector()}static startFloatsVector(t,e){t.startVector(4,e,4)}static addInts(t,e){t.addFieldOffset(9,e,0)}static createIntsVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startIntsVector(t,e){t.startVector(8,e,8)}static addStrings(t,e){t.addFieldOffset(10,e,0)}static createStringsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startStringsVector(t,e){t.startVector(4,e,4)}static addTensors(t,e){t.addFieldOffset(11,e,0)}static createTensorsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startTensorsVector(t,e){t.startVector(4,e,4)}static addGraphs(t,e){t.addFieldOffset(12,e,0)}static createGraphsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startGraphsVector(t,e){t.startVector(4,e,4)}static endAttribute(t){return t.endObject()}static createAttribute(t,e,r,i,h,g,m,b,y,w,T,S,A,O){return c.startAttribute(t),c.addName(t,e),c.addDocString(t,r),c.addType(t,i),c.addF(t,h),c.addI(t,g),c.addS(t,m),c.addT(t,b),c.addG(t,y),c.addFloats(t,w),c.addInts(t,T),c.addStrings(t,S),c.addTensors(t,A),c.addGraphs(t,O),c.endAttribute(t)}}f.Attribute=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsGraph(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsGraph(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}initializers(t,e){let r=this.bb.__offset(this.bb_pos,4);return r?(e||new s.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}initializersLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeArgs(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new s.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeArgsLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}nodes(t,e){let r=this.bb.__offset(this.bb_pos,8);return r?(e||new s.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}maxNodeIndex(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readUint32(this.bb_pos+t):0}nodeEdges(t,e){let r=this.bb.__offset(this.bb_pos,12);return r?(e||new s.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeEdgesLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}inputs(t,e){let r=this.bb.__offset(this.bb_pos,14);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let r=this.bb.__offset(this.bb_pos,16);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__vector_len(this.bb_pos+t):0}sparseInitializers(t,e){let r=this.bb.__offset(this.bb_pos,18);return r?(e||new s.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}sparseInitializersLength(){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__vector_len(this.bb_pos+t):0}static startGraph(t){t.startObject(8)}static addInitializers(t,e){t.addFieldOffset(0,e,0)}static createInitializersVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startInitializersVector(t,e){t.startVector(4,e,4)}static addNodeArgs(t,e){t.addFieldOffset(1,e,0)}static createNodeArgsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startNodeArgsVector(t,e){t.startVector(4,e,4)}static addNodes(t,e){t.addFieldOffset(2,e,0)}static createNodesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startNodesVector(t,e){t.startVector(4,e,4)}static addMaxNodeIndex(t,e){t.addFieldInt32(3,e,0)}static addNodeEdges(t,e){t.addFieldOffset(4,e,0)}static createNodeEdgesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startNodeEdgesVector(t,e){t.startVector(4,e,4)}static addInputs(t,e){t.addFieldOffset(5,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(6,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addSparseInitializers(t,e){t.addFieldOffset(7,e,0)}static createSparseInitializersVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startSparseInitializersVector(t,e){t.startVector(4,e,4)}static endGraph(t){return t.endObject()}static createGraph(t,e,r,i,h,g,m,b,y){return c.startGraph(t),c.addInitializers(t,e),c.addNodeArgs(t,r),c.addNodes(t,i),c.addMaxNodeIndex(t,h),c.addNodeEdges(t,g),c.addInputs(t,m),c.addOutputs(t,b),c.addSparseInitializers(t,y),c.endGraph(t)}}f.Graph=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsModel(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsModel(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}irVersion(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}opsetImport(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new s.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}opsetImportLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}producerName(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}producerVersion(t){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,t):null}modelVersion(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}docString(t){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__string(this.bb_pos+e,t):null}graph(t){let e=this.bb.__offset(this.bb_pos,18);return e?(t||new s.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}graphDocString(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__string(this.bb_pos+e,t):null}static startModel(t){t.startObject(9)}static addIrVersion(t,e){t.addFieldInt64(0,e,t.createLong(0,0))}static addOpsetImport(t,e){t.addFieldOffset(1,e,0)}static createOpsetImportVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startOpsetImportVector(t,e){t.startVector(4,e,4)}static addProducerName(t,e){t.addFieldOffset(2,e,0)}static addProducerVersion(t,e){t.addFieldOffset(3,e,0)}static addDomain(t,e){t.addFieldOffset(4,e,0)}static addModelVersion(t,e){t.addFieldInt64(5,e,t.createLong(0,0))}static addDocString(t,e){t.addFieldOffset(6,e,0)}static addGraph(t,e){t.addFieldOffset(7,e,0)}static addGraphDocString(t,e){t.addFieldOffset(8,e,0)}static endModel(t){return t.endObject()}static createModel(t,e,r,i,h,g,m,b,y,w){return c.startModel(t),c.addIrVersion(t,e),c.addOpsetImport(t,r),c.addProducerName(t,i),c.addProducerVersion(t,h),c.addDomain(t,g),c.addModelVersion(t,m),c.addDocString(t,b),c.addGraph(t,y),c.addGraphDocString(t,w),c.endModel(t)}}f.Model=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsKernelCreateInfos(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKernelCreateInfos(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}nodeIndices(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb.__vector(this.bb_pos+e)+4*t):0}nodeIndicesLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeIndicesArray(){let t=this.bb.__offset(this.bb_pos,4);return t?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}kernelDefHashes(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}kernelDefHashesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startKernelCreateInfos(t){t.startObject(2)}static addNodeIndices(t,e){t.addFieldOffset(0,e,0)}static createNodeIndicesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addInt32(e[r]);return t.endVector()}static startNodeIndicesVector(t,e){t.startVector(4,e,4)}static addKernelDefHashes(t,e){t.addFieldOffset(1,e,0)}static createKernelDefHashesVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startKernelDefHashesVector(t,e){t.startVector(8,e,8)}static endKernelCreateInfos(t){return t.endObject()}static createKernelCreateInfos(t,e,r){return c.startKernelCreateInfos(t),c.addNodeIndices(t,e),c.addKernelDefHashes(t,r),c.endKernelCreateInfos(t)}}f.KernelCreateInfos=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSubGraphSessionState(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSubGraphSessionState(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}graphId(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}sessionState(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new s.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSubGraphSessionState(t){t.startObject(2)}static addGraphId(t,e){t.addFieldOffset(0,e,0)}static addSessionState(t,e){t.addFieldOffset(1,e,0)}static endSubGraphSessionState(t){let e=t.endObject();return t.requiredField(e,4),e}static createSubGraphSessionState(t,e,r){return c.startSubGraphSessionState(t),c.addGraphId(t,e),c.addSessionState(t,r),c.endSubGraphSessionState(t)}}f.SubGraphSessionState=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSessionState(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSessionState(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}kernels(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new s.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}subGraphSessionStates(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new s.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}subGraphSessionStatesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSessionState(t){t.startObject(2)}static addKernels(t,e){t.addFieldOffset(0,e,0)}static addSubGraphSessionStates(t,e){t.addFieldOffset(1,e,0)}static createSubGraphSessionStatesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startSubGraphSessionStatesVector(t,e){t.startVector(4,e,4)}static endSessionState(t){return t.endObject()}static createSessionState(t,e,r){return c.startSessionState(t),c.addKernels(t,e),c.addSubGraphSessionStates(t,r),c.endSessionState(t)}}f.SessionState=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(p){(function(f){class c{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsInferenceSession(t,e){return(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInferenceSession(t,e){return t.setPosition(t.position()+u.flatbuffers.SIZE_PREFIX_LENGTH),(e||new c).__init(t.readInt32(t.position())+t.position(),t)}static bufferHasIdentifier(t){return t.__has_identifier("ORTM")}ortVersion(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}model(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new s.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}sessionState(t){let e=this.bb.__offset(this.bb_pos,8);return e?(t||new s.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startInferenceSession(t){t.startObject(3)}static addOrtVersion(t,e){t.addFieldOffset(0,e,0)}static addModel(t,e){t.addFieldOffset(1,e,0)}static addSessionState(t,e){t.addFieldOffset(2,e,0)}static endInferenceSession(t){return t.endObject()}static finishInferenceSessionBuffer(t,e){t.finish(e,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(t,e){t.finish(e,"ORTM",!0)}static createInferenceSession(t,e,r,i){return c.startInferenceSession(t),c.addOrtVersion(t,e),c.addModel(t,r),c.addSessionState(t,i),c.endInferenceSession(t)}}f.InferenceSession=c})(p.fbs||(p.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={}))},7448:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OnnxjsSessionHandler=void 0;const u=o(1670),l=o(9162);n.OnnxjsSessionHandler=class{constructor(d){this.session=d,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(d,s,p){const f=new Map;for(const t in d)if(Object.hasOwnProperty.call(d,t)){const e=d[t];f.set(t,new l.Tensor(e.dims,e.type,void 0,void 0,e.data))}const c=await this.session.run(f),a={};return c.forEach((t,e)=>{a[e]=new u.Tensor(t.type,t.data,t.dims)}),a}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Session=void 0;const u=o(7067),l=o(1296),d=o(7091),s=o(1036),p=o(6231),f=o(2644);n.Session=class{constructor(c={}){this._initialized=!1,this.backendHint=c.backendHint,this.profiler=p.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,a,t){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 f.Model,typeof c=="string"){const r=c.endsWith(".ort");if(typeof fetch>"u"){const i=await(0,l.promisify)(u.readFile)(c);this.initialize(i,r)}else{const i=await fetch(c),h=await i.arrayBuffer();this.initialize(new Uint8Array(h),r)}}else if(ArrayBuffer.isView(c))this.initialize(c);else{const r=new Uint8Array(c,a||0,t||c.byteLength);this.initialize(r)}})}initialize(c,a){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{const t=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(c,t,a),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new s.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 a=this.normalizeAndValidateInputs(c),t=await this._executionPlan.execute(this.sessionHandler,a);return this.createOutput(t)})}normalizeAndValidateInputs(c){const a=this._model.graph.getInputNames();if(Array.isArray(c)){if(c.length!==a.length)throw new Error(`incorrect input array length: expected ${a.length} but got ${c.length}`)}else{if(c.size!==a.length)throw new Error(`incorrect input map size: expected ${a.length} but got ${c.size}`);const t=new Array(c.size);let e=0;for(let r=0;rtypeof O=="string")))throw new TypeError("cache should be a string array");A&&(this.cache=new Array(S))}else{if(w!==void 0){const O=e(m);if(!(w instanceof O))throw new TypeError(`cache should be type ${O.name}`)}if(A){const O=new ArrayBuffer(S*function(v){switch(v){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 ${v}`)}}(m));this.cache=function(v,M){return new(e(M))(v)}(O,m)}}}static fromProto(g){if(!g)throw new Error("cannot construct Value from an empty tensor");const m=f.ProtoUtil.tensorDataTypeFromProto(g.dataType),b=f.ProtoUtil.tensorDimsFromProto(g.dims),y=new a(b,m);if(m==="string")g.stringData.forEach((w,T)=>{y.data[T]=(0,f.decodeUtf8String)(w)});else if(g.rawData&&typeof g.rawData.byteLength=="number"&&g.rawData.byteLength>0){const w=y.data,T=new DataView(g.rawData.buffer,g.rawData.byteOffset,g.rawData.byteLength),S=t(g.dataType),A=g.rawData.byteLength/S;if(g.rawData.byteLength%S!=0)throw new Error("invalid buffer length");if(w.length!==A)throw new Error("buffer length mismatch");for(let O=0;O0){const w=y.data,T=new DataView(g.rawDataArray().buffer,g.rawDataArray().byteOffset,g.rawDataLength()),S=t(g.dataType()),A=g.rawDataLength()/S;if(g.rawDataLength()%S!=0)throw new Error("invalid buffer length");if(w.length!==A)throw new Error("buffer length mismatch");for(let O=0;O1&&M>1)return;A[S-O]=Math.max(v,M)}return A}static index(m,b){const y=new Array(b.length);return c.fillIndex(m,b,y),y}static fillIndex(m,b,y){const w=m.length-b.length;for(let T=0;T=0;Q--)v[Q]=R%S[Q],R=Math.floor(R/S[Q]);G||(c.fillIndex(v,m.dims,M),$=m.get(M)),D||(c.fillIndex(v,b.dims,F),N=b.get(F)),O.set(v,y($,N))}}return O}}static isValidBroadcast(m,b){const y=m.length,w=b.length;if(y>w)return!1;for(let T=1;T<=y;T++)if(m[y-T]!==1&&m[y-T]!==b[w-T])return!1;return!0}static getBroadcastDims(m,b){const y=m.length,w=[];for(let T=0;T1&&A===1&&w.unshift(S)}return w}}n.BroadcastUtil=c,n.arrayCopyHelper=function(g,m,b,y,w){if(y<0||y>=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let T=0;Td.default.isLong(b)?b.toNumber():b)}static tensorValueTypeFromProto(m){return{tensorType:a.tensorDataTypeFromProto(m.elemType),shape:{dims:a.tensorDimsFromProto(m.shape.dim.map(b=>b.dimValue))}}}static tensorDimsFromORTFormat(m){const b=[];for(let y=0;ym.length)throw new Error(`invalid dimension of ${b} for sizeFromDimension as Tensor has ${m.length} dimensions.`);return e.getSizeFromDimensionRange(m,b,m.length)}static sizeToDimension(m,b){if(b<0||b>m.length)throw new Error(`invalid dimension of ${b} for sizeToDimension as Tensor has ${m.length} dimensions.`);return e.getSizeFromDimensionRange(m,0,b)}static getSizeFromDimensionRange(m,b,y){let w=1;for(let T=b;T=0;--w)y[w]=y[w+1]*m[w+1];return y}static transpose(m){return m.slice().reverse()}static indicesToOffset(m,b,y){y===void 0&&(y=m.length);let w=0;for(let T=0;T=b)throw new Error("unsupported axis for this operation.");return m<0?m+b:m}static normalizeAxes(m,b){return m.map(y=>this.normalizeAxis(y,b))}static incrementIndex(m,b,y){if(b.length===0||m.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 w=y-1;w>=0&&(m[w]++,!(m[w]=m.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");w[O]=m[O]}else w[O]=b[O];S*=w[O]}}const A=e.size(m);if(T!==-1){if(A%S!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${m}] Output shape: [${b}]`);w[T]=A/S}else if(S!==A)throw new Error("reshapedDims and originalDims don't have matching sizes");return w}static sortBasedOnPerm(m,b){return b?b.map(y=>m[y]):m.slice().reverse()}static padShape(m,b){const y=m.length;return m.map((w,T)=>w+b[T]+b[T+y])}static areEqual(m,b){return m.length===b.length&&m.every((y,w)=>y===b[w])}static validateDimsAndCalcSize(m){if(m.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let b=1;for(const y of m){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(m,b){b<0&&(b+=m.length);const y=m.reduce((T,S)=>T*S,1),w=m.slice(b).reduce((T,S)=>T*S,1);return[y/w,w]}static squeezeShape(m,b){const y=new Array;b=e.normalizeAxes(b,m.length);for(let w=0;w=0;if(T&&m[w]!==1)throw new Error("squeeze an axis of size different than 1");(b.length===0&&m[w]>1||b.length>0&&!T)&&y.push(m[w])}return y}static unsqueezeShape(m,b){const y=new Array(m.length+b.length);y.fill(0);for(let T=0;T=y.length)throw new Error("'axes' has an out of range axis");if(y[S]!==0)throw new Error("'axes' has a duplicate axis");y[S]=1}let w=0;for(let T=0;T=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let T=0;T=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let S=0;S=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let S=0;S=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let T=0;Tb.push(N));const A=i.calcReduceShape(S,b,!0),O=e.size(A),v=new p.Tensor(A,m.type),M=e.computeStrides(A),F=e.computeStrides(S),R=new Array(S.length);for(let $=0;$=b.length)return S(m[T]);const v=b[w],M=v>=y.length?1:e.size(y.slice(v+1));for(let F=0;FT!==0)}}n.ReduceUtil=i;class h{static adjustPoolAttributes(m,b,y,w,T,S){if(!m&&y.length!==b.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(m)for(let A=0;A=y.length?y.push(b[A+2]):y[A]=b[A+2];for(let A=0;A=y[A]||S[A+y.length]>=y[A])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(m,b,y,w,T,S){if(S){if(T.length!==2*(m.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(b.length!==m.length-2)throw new Error("length of strides should be the length of data dimensions");if(w.length!==m.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let A=0;A{Object.defineProperty(n,"__esModule",{value:!0}),n.iterateExtraOptions=void 0,n.iterateExtraOptions=(o,u,l,d)=>{if(typeof o=="object"&&o!==null){if(l.has(o))throw new Error("Circular reference in options");l.add(o)}Object.entries(o).forEach(([s,p])=>{const f=u?u+s:s;if(typeof p=="object")(0,n.iterateExtraOptions)(p,f+".",l,d);else if(typeof p=="string"||typeof p=="number")d(f,p.toString());else{if(typeof p!="boolean")throw new Error("Can't handle extra config type: "+typeof p);d(f,p?"1":"0")}})}},2157:function(_,n,o){var u,l=this&&this.__createBinding||(Object.create?function(M,F,R,$){$===void 0&&($=R);var N=Object.getOwnPropertyDescriptor(F,R);N&&!("get"in N?!F.__esModule:N.writable||N.configurable)||(N={enumerable:!0,get:function(){return F[R]}}),Object.defineProperty(M,$,N)}:function(M,F,R,$){$===void 0&&($=R),M[$]=F[R]}),d=this&&this.__setModuleDefault||(Object.create?function(M,F){Object.defineProperty(M,"default",{enumerable:!0,value:F})}:function(M,F){M.default=F}),s=this&&this.__importStar||function(M){if(M&&M.__esModule)return M;var F={};if(M!=null)for(var R in M)R!=="default"&&Object.prototype.hasOwnProperty.call(M,R)&&l(F,M,R);return d(F,M),F};Object.defineProperty(n,"__esModule",{value:!0}),n.endProfiling=n.run=n.releaseSession=n.createSession=n.createSessionFinalize=n.createSessionAllocate=n.initOrt=n.initWasm=void 0;const p=o(1670),f=s(o(349)),c=o(6361),a=()=>!!p.env.wasm.proxy&&typeof document<"u";let t,e,r,i=!1,h=!1,g=!1;const m=[],b=[],y=[],w=[],T=[],S=[],A=()=>{if(i||!h||g||!t)throw new Error("worker not ready")},O=M=>{switch(M.data.type){case"init-wasm":i=!1,M.data.err?(g=!0,e[1](M.data.err)):(h=!0,e[0]());break;case"init-ort":M.data.err?r[1](M.data.err):r[0]();break;case"create_allocate":M.data.err?m.shift()[1](M.data.err):m.shift()[0](M.data.out);break;case"create_finalize":M.data.err?b.shift()[1](M.data.err):b.shift()[0](M.data.out);break;case"create":M.data.err?y.shift()[1](M.data.err):y.shift()[0](M.data.out);break;case"release":M.data.err?w.shift()[1](M.data.err):w.shift()[0]();break;case"run":M.data.err?T.shift()[1](M.data.err):T.shift()[0](M.data.out);break;case"end-profiling":M.data.err?S.shift()[1](M.data.err):S.shift()[0]()}},v=typeof document<"u"?(u=document==null?void 0:document.currentScript)===null||u===void 0?void 0:u.src:void 0;n.initWasm=async()=>{if(a()){if(h)return;if(i)throw new Error("multiple calls to 'initWasm()' detected.");if(g)throw new Error("previous call to 'initWasm()' failed.");return i=!0,p.env.wasm.wasmPaths===void 0&&v&&v.indexOf("blob:")!==0&&(p.env.wasm.wasmPaths=v.substr(0,+v.lastIndexOf("/")+1)),new Promise((M,F)=>{t==null||t.terminate(),t=o(9710).Z(),t.onmessage=O,e=[M,F];const R={type:"init-wasm",in:p.env.wasm};t.postMessage(R)})}return(0,c.initializeWebAssembly)(p.env.wasm)},n.initOrt=async(M,F)=>{if(a())return A(),new Promise((R,$)=>{r=[R,$];const N={type:"init-ort",in:{numThreads:M,loggingLevel:F}};t.postMessage(N)});f.initOrt(M,F)},n.createSessionAllocate=async M=>a()?(A(),new Promise((F,R)=>{m.push([F,R]);const $={type:"create_allocate",in:{model:M}};t.postMessage($,[M.buffer])})):f.createSessionAllocate(M),n.createSessionFinalize=async(M,F)=>a()?(A(),new Promise((R,$)=>{b.push([R,$]);const N={type:"create_finalize",in:{modeldata:M,options:F}};t.postMessage(N)})):f.createSessionFinalize(M,F),n.createSession=async(M,F)=>a()?(A(),new Promise((R,$)=>{y.push([R,$]);const N={type:"create",in:{model:M,options:F}};t.postMessage(N,[M.buffer])})):f.createSession(M,F),n.releaseSession=async M=>{if(a())return A(),new Promise((F,R)=>{w.push([F,R]);const $={type:"release",in:M};t.postMessage($)});f.releaseSession(M)},n.run=async(M,F,R,$,N)=>a()?(A(),new Promise((G,D)=>{T.push([G,D]);const j={type:"run",in:{sessionId:M,inputIndices:F,inputs:R,outputIndices:$,options:N}};t.postMessage(j,f.extractTransferableBuffers(R))})):f.run(M,F,R,$,N),n.endProfiling=async M=>{if(a())return A(),new Promise((F,R)=>{S.push([F,R]);const $={type:"end-profiling",in:M};t.postMessage($)});f.endProfiling(M)}},586:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.setRunOptions=void 0;const u=o(7967),l=o(4983),d=o(6361);n.setRunOptions=s=>{const p=(0,d.getInstance)();let f=0;const c=[],a=s||{};try{if((s==null?void 0:s.logSeverityLevel)===void 0)a.logSeverityLevel=2;else if(typeof s.logSeverityLevel!="number"||!Number.isInteger(s.logSeverityLevel)||s.logSeverityLevel<0||s.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${s.logSeverityLevel}`);if((s==null?void 0:s.logVerbosityLevel)===void 0)a.logVerbosityLevel=0;else if(typeof s.logVerbosityLevel!="number"||!Number.isInteger(s.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${s.logVerbosityLevel}`);(s==null?void 0:s.terminate)===void 0&&(a.terminate=!1);let t=0;if((s==null?void 0:s.tag)!==void 0&&(t=(0,l.allocWasmString)(s.tag,c)),f=p._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,t),f===0)throw new Error("Can't create run options");return(s==null?void 0:s.extra)!==void 0&&(0,u.iterateExtraOptions)(s.extra,"",new WeakSet,(e,r)=>{const i=(0,l.allocWasmString)(e,c),h=(0,l.allocWasmString)(r,c);if(p._OrtAddRunConfigEntry(f,i,h)!==0)throw new Error(`Can't set a run config entry: ${e} - ${r}`)}),[f,c]}catch(t){throw f!==0&&p._OrtReleaseRunOptions(f),c.forEach(p._free),t}}},2306:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OnnxruntimeWebAssemblySessionHandler=void 0;const u=o(2806),l=o(1670),d=o(2850),s=o(2157);let p;n.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(f){const c=await fetch(f),a=await c.arrayBuffer();return(0,s.createSessionAllocate)(new Uint8Array(a))}async loadModel(f,c){if(p||(await(0,s.initOrt)(l.env.wasm.numThreads,(a=>{switch(a){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: ${a}`)}})(l.env.logLevel)),p=!0),typeof f=="string")if(typeof fetch>"u"){const a=await(0,d.promisify)(u.readFile)(f);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(a,c)}else{const a=await this.createSessionAllocate(f);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSessionFinalize)(a,c)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(f,c)}async dispose(){return(0,s.releaseSession)(this.sessionId)}async run(f,c,a){const t=[],e=[];Object.entries(f).forEach(g=>{const m=g[0],b=g[1],y=this.inputNames.indexOf(m);if(y===-1)throw new Error(`invalid input '${m}'`);t.push(b),e.push(y)});const r=[];Object.entries(c).forEach(g=>{const m=g[0],b=this.outputNames.indexOf(m);if(b===-1)throw new Error(`invalid output '${m}'`);r.push(b)});const i=await(0,s.run)(this.sessionId,e,t.map(g=>[g.type,g.dims,g.data]),r,a),h={};for(let g=0;g{Object.defineProperty(n,"__esModule",{value:!0}),n.setSessionOptions=void 0;const u=o(7967),l=o(4983),d=o(6361);n.setSessionOptions=s=>{const p=(0,d.getInstance)();let f=0;const c=[],a=s||{};(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")})(a);try{(s==null?void 0:s.graphOptimizationLevel)===void 0&&(a.graphOptimizationLevel="all");const t=(i=>{switch(i){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${i}`)}})(a.graphOptimizationLevel);(s==null?void 0:s.enableCpuMemArena)===void 0&&(a.enableCpuMemArena=!0),(s==null?void 0:s.enableMemPattern)===void 0&&(a.enableMemPattern=!0),(s==null?void 0:s.executionMode)===void 0&&(a.executionMode="sequential");const e=(i=>{switch(i){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${i}`)}})(a.executionMode);let r=0;if((s==null?void 0:s.logId)!==void 0&&(r=(0,l.allocWasmString)(s.logId,c)),(s==null?void 0:s.logSeverityLevel)===void 0)a.logSeverityLevel=2;else if(typeof s.logSeverityLevel!="number"||!Number.isInteger(s.logSeverityLevel)||s.logSeverityLevel<0||s.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${s.logSeverityLevel}`);if((s==null?void 0:s.logVerbosityLevel)===void 0)a.logVerbosityLevel=0;else if(typeof s.logVerbosityLevel!="number"||!Number.isInteger(s.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${s.logVerbosityLevel}`);if((s==null?void 0:s.enableProfiling)===void 0&&(a.enableProfiling=!1),f=p._OrtCreateSessionOptions(t,!!a.enableCpuMemArena,!!a.enableMemPattern,e,!!a.enableProfiling,0,r,a.logSeverityLevel,a.logVerbosityLevel),f===0)throw new Error("Can't create session options");return s!=null&&s.executionProviders&&((i,h,g)=>{for(const m of h){let b=typeof m=="string"?m:m.name;switch(b){case"xnnpack":b="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${b}`)}const y=(0,l.allocWasmString)(b,g);if((0,d.getInstance)()._OrtAppendExecutionProvider(i,y)!==0)throw new Error(`Can't append execution provider: ${b}`)}})(f,s.executionProviders,c),(s==null?void 0:s.extra)!==void 0&&(0,u.iterateExtraOptions)(s.extra,"",new WeakSet,(i,h)=>{const g=(0,l.allocWasmString)(i,c),m=(0,l.allocWasmString)(h,c);if(p._OrtAddSessionConfigEntry(f,g,m)!==0)throw new Error(`Can't set a session config entry: ${i} - ${h}`)}),[f,c]}catch(t){throw f!==0&&p._OrtReleaseSessionOptions(f),c.forEach(p._free),t}}},4983:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.allocWasmString=void 0;const u=o(6361);n.allocWasmString=(l,d)=>{const s=(0,u.getInstance)(),p=s.lengthBytesUTF8(l)+1,f=s._malloc(p);return s.stringToUTF8(l,f,p),d.push(f),f}},349:(_,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.extractTransferableBuffers=n.endProfiling=n.run=n.releaseSession=n.createSession=n.createSessionFinalize=n.createSessionAllocate=n.initOrt=void 0;const u=o(586),l=o(4919),d=o(4983),s=o(6361);n.initOrt=(t,e)=>{const r=(0,s.getInstance)()._OrtInit(t,e);if(r!==0)throw new Error(`Can't initialize onnxruntime. error code = ${r}`)};const p=new Map;n.createSessionAllocate=t=>{const e=(0,s.getInstance)(),r=e._malloc(t.byteLength);return e.HEAPU8.set(t,r),[r,t.byteLength]},n.createSessionFinalize=(t,e)=>{const r=(0,s.getInstance)();let i=0,h=0,g=[];try{if([h,g]=(0,l.setSessionOptions)(e),i=r._OrtCreateSession(t[0],t[1],h),i===0)throw new Error("Can't create a session")}finally{r._free(t[0]),r._OrtReleaseSessionOptions(h),g.forEach(r._free)}const m=r._OrtGetInputCount(i),b=r._OrtGetOutputCount(i),y=[],w=[],T=[],S=[];for(let A=0;A{const r=(0,n.createSessionAllocate)(t);return(0,n.createSessionFinalize)(r,e)},n.releaseSession=t=>{const e=(0,s.getInstance)(),r=p.get(t);if(!r)throw new Error("invalid session id");const i=r[0],h=r[1],g=r[2];h.forEach(e._OrtFree),g.forEach(e._OrtFree),e._OrtReleaseSession(i),p.delete(t)};const f=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},c=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},a=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}`)}};n.run=(t,e,r,i,h)=>{const g=(0,s.getInstance)(),m=p.get(t);if(!m)throw new Error("invalid session id");const b=m[0],y=m[1],w=m[2],T=e.length,S=i.length;let A=0,O=[];const v=[],M=[];try{[A,O]=(0,u.setRunOptions)(h);for(let D=0;Dg.HEAP32[ve++]=we);const oe=g._OrtCreateTensor(f(j),Z,ee,Ae,Q.length);if(oe===0)throw new Error("Can't create a tensor");v.push(oe)}finally{g.stackRestore(ue)}}const F=g.stackSave(),R=g.stackAlloc(4*T),$=g.stackAlloc(4*T),N=g.stackAlloc(4*S),G=g.stackAlloc(4*S);try{let D=R/4,j=$/4,Q=N/4,X=G/4;for(let ue=0;ueOe*Be);if(we=c(Le),we==="string"){const Oe=[];let Be=be/4;for(let Ge=0;Ge{const e=(0,s.getInstance)(),r=p.get(t);if(!r)throw new Error("invalid session id");const i=r[0],h=e._OrtEndProfiling(i);if(h===0)throw new Error("Can't get an profile file name");e._OrtFree(h)},n.extractTransferableBuffers=t=>{const e=[];for(const r of t){const i=r[2];!Array.isArray(i)&&i.buffer&&e.push(i.buffer)}return e}},6361:function(_,n,o){var u=this&&this.__createBinding||(Object.create?function(h,g,m,b){b===void 0&&(b=m);var y=Object.getOwnPropertyDescriptor(g,m);y&&!("get"in y?!g.__esModule:y.writable||y.configurable)||(y={enumerable:!0,get:function(){return g[m]}}),Object.defineProperty(h,b,y)}:function(h,g,m,b){b===void 0&&(b=m),h[b]=g[m]}),l=this&&this.__setModuleDefault||(Object.create?function(h,g){Object.defineProperty(h,"default",{enumerable:!0,value:g})}:function(h,g){h.default=g}),d=this&&this.__importStar||function(h){if(h&&h.__esModule)return h;var g={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&u(g,h,m);return l(g,h),g},s=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(n,"__esModule",{value:!0}),n.dispose=n.getInstance=n.initializeWebAssembly=void 0;const p=d(o(6449)),f=s(o(932)),c=o(3474);let a,t=!1,e=!1,r=!1;const i=(h,g)=>g?h?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":h?"ort-wasm-simd.wasm":"ort-wasm.wasm";n.initializeWebAssembly=async h=>{if(t)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=h.initTimeout,m=h.numThreads,b=h.simd,y=m>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}})(),w=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}})(),T=typeof h.wasmPaths=="string"?h.wasmPaths:void 0,S=i(!1,y),A=i(w,y),O=typeof h.wasmPaths=="object"?h.wasmPaths[A]:void 0;let v=!1;const M=[];if(g>0&&M.push(new Promise(F=>{setTimeout(()=>{v=!0,F()},g)})),M.push(new Promise((F,R)=>{const $=y?c:f.default,N={locateFile:(G,D)=>y&&G.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([o(4154)],{type:"text/javascript"})):G===S?O??(T??D)+A:D+G};if(y)if(typeof Blob>"u")N.mainScriptUrlOrBlob=p.join("/","ort-wasm-threaded.js");else{const G=`var ortWasmThreaded=(function(){var _scriptDir;return ${$.toString()}})();`;N.mainScriptUrlOrBlob=new Blob([G],{type:"text/javascript"})}$(N).then(G=>{e=!1,t=!0,a=G,F()},G=>{e=!1,r=!0,R(G)})})),await Promise.race(M),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${g}ms`)},n.getInstance=()=>{if(t&&a)return a;throw new Error("WebAssembly is not initialized yet.")},n.dispose=()=>{var h;!t||e||r||(e=!0,(h=a.PThread)===null||h===void 0||h.terminateAllThreads(),a=void 0,e=!1,t=!1,r=!0)}},9710:(_,n,o)=>{o.d(n,{Z:()=>d});var u=o(477),l=o.n(u);function d(){return l()('/*!\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:_=>{_.exports=function(n,o,u,l){var d=self||window;try{try{var s;try{s=new d.Blob([n])}catch{(s=new(d.BlobBuilder||d.WebKitBlobBuilder||d.MozBlobBuilder||d.MSBlobBuilder)).append(n),s=s.getBlob()}var p=d.URL||d.webkitURL,f=p.createObjectURL(s),c=new d[o](f,u);return p.revokeObjectURL(f),c}catch{return new d[o]("data:application/javascript,".concat(encodeURIComponent(n)),u)}}catch{if(!l)throw Error("Inline worker is not supported");return new d[o](l,u)}}},4154:_=>{_.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:_=>{_.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(_,n,o)=>{o.r(n),o.d(n,{flatbuffers:()=>u});var u={};u.Offset,u.Table,u.SIZEOF_SHORT=2,u.SIZEOF_INT=4,u.FILE_IDENTIFIER_LENGTH=4,u.SIZE_PREFIX_LENGTH=4,u.Encoding={UTF8_BYTES:1,UTF16_STRING:2},u.int32=new Int32Array(2),u.float32=new Float32Array(u.int32.buffer),u.float64=new Float64Array(u.int32.buffer),u.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,u.Long=function(l,d){this.low=0|l,this.high=0|d},u.Long.create=function(l,d){return l==0&&d==0?u.Long.ZERO:new u.Long(l,d)},u.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},u.Long.prototype.equals=function(l){return this.low==l.low&&this.high==l.high},u.Long.ZERO=new u.Long(0,0),u.Builder=function(l){if(l)d=l;else var d=1024;this.bb=u.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},u.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},u.Builder.prototype.forceDefaults=function(l){this.force_defaults=l},u.Builder.prototype.dataBuffer=function(){return this.bb},u.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},u.Builder.prototype.prep=function(l,d){l>this.minalign&&(this.minalign=l);for(var s=1+~(this.bb.capacity()-this.space+d)&l-1;this.space=0&&this.vtable[d]==0;d--);for(var s=d+1;d>=0;d--)this.addInt16(this.vtable[d]!=0?l-this.vtable[d]:0);this.addInt16(l-this.object_start);var p=(s+2)*u.SIZEOF_SHORT;this.addInt16(p);var f=0,c=this.space;e:for(d=0;d=0;c--)this.writeInt8(f.charCodeAt(c))}this.prep(this.minalign,u.SIZEOF_INT+p),this.addOffset(l),p&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},u.Builder.prototype.finishSizePrefixed=function(l,d){this.finish(l,d,!0)},u.Builder.prototype.requiredField=function(l,d){var s=this.bb.capacity()-l,p=s-this.bb.readInt32(s);if(this.bb.readInt16(p+d)==0)throw new Error("FlatBuffers: field "+d+" must be set")},u.Builder.prototype.startVector=function(l,d,s){this.notNested(),this.vector_num_elems=d,this.prep(u.SIZEOF_INT,l*d),this.prep(s,l*d)},u.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},u.Builder.prototype.createString=function(l){if(l instanceof Uint8Array)var d=l;else{d=[];for(var s=0;s=56320?f:(f<<10)+l.charCodeAt(s++)+-56613888)<128?d.push(p):(p<2048?d.push(p>>6&31|192):(p<65536?d.push(p>>12&15|224):d.push(p>>18&7|240,p>>12&63|128),d.push(p>>6&63|128)),d.push(63&p|128))}}this.addInt8(0),this.startVector(1,d.length,1),this.bb.setPosition(this.space-=d.length),s=0;for(var c=this.space,a=this.bb.bytes();s>24},u.ByteBuffer.prototype.readUint8=function(l){return this.bytes_[l]},u.ByteBuffer.prototype.readInt16=function(l){return this.readUint16(l)<<16>>16},u.ByteBuffer.prototype.readUint16=function(l){return this.bytes_[l]|this.bytes_[l+1]<<8},u.ByteBuffer.prototype.readInt32=function(l){return this.bytes_[l]|this.bytes_[l+1]<<8|this.bytes_[l+2]<<16|this.bytes_[l+3]<<24},u.ByteBuffer.prototype.readUint32=function(l){return this.readInt32(l)>>>0},u.ByteBuffer.prototype.readInt64=function(l){return new u.Long(this.readInt32(l),this.readInt32(l+4))},u.ByteBuffer.prototype.readUint64=function(l){return new u.Long(this.readUint32(l),this.readUint32(l+4))},u.ByteBuffer.prototype.readFloat32=function(l){return u.int32[0]=this.readInt32(l),u.float32[0]},u.ByteBuffer.prototype.readFloat64=function(l){return u.int32[u.isLittleEndian?0:1]=this.readInt32(l),u.int32[u.isLittleEndian?1:0]=this.readInt32(l+4),u.float64[0]},u.ByteBuffer.prototype.writeInt8=function(l,d){this.bytes_[l]=d},u.ByteBuffer.prototype.writeUint8=function(l,d){this.bytes_[l]=d},u.ByteBuffer.prototype.writeInt16=function(l,d){this.bytes_[l]=d,this.bytes_[l+1]=d>>8},u.ByteBuffer.prototype.writeUint16=function(l,d){this.bytes_[l]=d,this.bytes_[l+1]=d>>8},u.ByteBuffer.prototype.writeInt32=function(l,d){this.bytes_[l]=d,this.bytes_[l+1]=d>>8,this.bytes_[l+2]=d>>16,this.bytes_[l+3]=d>>24},u.ByteBuffer.prototype.writeUint32=function(l,d){this.bytes_[l]=d,this.bytes_[l+1]=d>>8,this.bytes_[l+2]=d>>16,this.bytes_[l+3]=d>>24},u.ByteBuffer.prototype.writeInt64=function(l,d){this.writeInt32(l,d.low),this.writeInt32(l+4,d.high)},u.ByteBuffer.prototype.writeUint64=function(l,d){this.writeUint32(l,d.low),this.writeUint32(l+4,d.high)},u.ByteBuffer.prototype.writeFloat32=function(l,d){u.float32[0]=d,this.writeInt32(l,u.int32[0])},u.ByteBuffer.prototype.writeFloat64=function(l,d){u.float64[0]=d,this.writeInt32(l,u.int32[u.isLittleEndian?0:1]),this.writeInt32(l+4,u.int32[u.isLittleEndian?1:0])},u.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10),56320+(1023&c)))}return p},u.ByteBuffer.prototype.__indirect=function(l){return l+this.readInt32(l)},u.ByteBuffer.prototype.__vector=function(l){return l+this.readInt32(l)+u.SIZEOF_INT},u.ByteBuffer.prototype.__vector_len=function(l){return this.readInt32(l+this.readInt32(l))},u.ByteBuffer.prototype.__has_identifier=function(l){if(l.length!=u.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+u.FILE_IDENTIFIER_LENGTH);for(var d=0;d{var n=_&&_.__esModule?()=>_.default:()=>_;return __webpack_require__.d(n,{a:n}),n},__webpack_require__.d=(_,n)=>{for(var o in n)__webpack_require__.o(n,o)&&!__webpack_require__.o(_,o)&&Object.defineProperty(_,o,{enumerable:!0,get:n[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=(_,n)=>Object.prototype.hasOwnProperty.call(_,n),__webpack_require__.r=_=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(_,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(_,"__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.7.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={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(_){return Object.keys(_).length===0}globalThis.ReadableStream||(globalThis.ReadableStream=sharp.ReadableStream);class FileResponse{constructor(n){le(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=n,this.headers=new Headers,this.exists=sharp.existsSync(n),this.exists){this.status=200,this.statusText="OK";let o=sharp.statSync(n);this.headers.set("content-length",o.size.toString()),this.updateContentType();let u=this;this.body=new ReadableStream({start(l){u.arrayBuffer().then(d=>{l.enqueue(new Uint8Array(d)),l.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const n=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[n]??"application/octet-stream")}clone(){let n=new FileResponse(this.filePath);return n.exists=this.exists,n.status=this.status,n.statusText=this.statusText,n.headers=new Headers(this.headers),n}async arrayBuffer(){return(await sharp.promises.readFile(this.filePath)).buffer}async blob(){const n=await sharp.promises.readFile(this.filePath);return new Blob([n],{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(_,n=null){let o;try{o=new URL(_)}catch{return!1}return n&&!n.includes(o.hostname)?!1:o.protocol==="http:"||o.protocol==="https:"}async function getFile(_){var n,o,u;if(env.useFS&&!isValidHttpUrl(_))return new FileResponse(_);if(typeof process<"u"&&((n=process==null?void 0:process.release)==null?void 0:n.name)==="node"){const l=!!((o=process.env)!=null&&o.TESTING_REMOTELY),d=env.version,s=new Headers;if(s.set("User-Agent",`transformers.js/${d}; is_ci/${l};`),isValidHttpUrl(_,["huggingface.co","hf.co"])){const f=(u=process.env)==null?void 0:u.HF_ACCESS_TOKEN;f&&s.set("Authorization",`Bearer ${f}`)}return fetch(_,{headers:s})}else return fetch(_)}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(_,n,o){if(!o)return null;const u=ERROR_MAPPING[_]??`Error (${_}) occurred while trying to load file`;throw Error(`${u}: "${n}".`)}class FileCache{constructor(n){this.path=n}async match(n){let o=sharp.join(this.path,n),u=new FileResponse(o);if(u.exists)return u}async put(n,o){const u=Buffer.from(await o.arrayBuffer());let l=sharp.join(this.path,n);try{await sharp.promises.mkdir(sharp.dirname(l),{recursive:!0}),await sharp.promises.writeFile(l,u)}catch(d){console.warn("An error occurred while writing the file to cache:",d)}}}async function tryCache(_,...n){for(let o of n)try{let u=await _.match(o);if(u)return u}catch{continue}}async function getModelFile(_,n,o=!0,u={}){if(!env.allowLocalModels&&u.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(u.progress_callback,{status:"initiate",name:_,file:n});let l;if(!l&&env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{l=await caches.open("transformers-cache")}catch(h){console.warn("An error occurred while opening the browser cache:",h)}}if(!l&&env.useFSCache&&(l=new FileCache(u.cache_dir??env.cacheDir)),!l&&env.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const d=u.revision??"main";let s=pathJoin(_,n),p=pathJoin(env.localModelPath,s),f=pathJoin(env.remoteHost,env.remotePathTemplate.replaceAll("{model}",_).replaceAll("{revision}",d),n),c=d==="main"?s:pathJoin(_,d,n),a,t=l instanceof FileCache?c:f,e=!1,r;if(l&&(r=await tryCache(l,p,t)),r===void 0){if(env.allowLocalModels)if(isValidHttpUrl(s)){if(u.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${s}.`)}else try{r=await getFile(p),a=p}catch(g){console.warn(`Unable to load from local path "${p}": "${g}"`)}if(r===void 0||r.status===404){if(u.local_files_only||!env.allowRemoteModels){if(o)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${p}".`);return null}if(r=await getFile(f),r.status!==200)return handleError(r.status,f,o);a=t}e=l&&typeof Response<"u"&&r instanceof Response&&r.status===200}dispatchCallback(u.progress_callback,{status:"download",name:_,file:n});const i=await readResponse(r,h=>{dispatchCallback(u.progress_callback,{status:"progress",...h,name:_,file:n})});return e&&a&&await l.match(a)===void 0&&await l.put(a,new Response(i,{headers:r.headers})).catch(h=>{console.warn(`Unable to add response to browser cache: ${h}.`)}),dispatchCallback(u.progress_callback,{status:"done",name:_,file:n}),i}async function getModelJSON(_,n,o=!0,u={}){let l=await getModelFile(_,n,o,u);if(l===null)return{};let s=new TextDecoder("utf-8").decode(l);return JSON.parse(s)}async function readResponse(_,n){const o=_.headers.get("Content-Length");o===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let u=parseInt(o??"0"),l=new Uint8Array(u),d=0;const s=_.body.getReader();async function p(){const{done:f,value:c}=await s.read();if(f)return;let a=d+c.length;if(a>u){u=a;let e=new Uint8Array(u);e.set(l),l=e}l.set(c,d),d=a;const t=d/u*100;return n({progress:t,loaded:d,total:u}),p()}return await p(),l}function pathJoin(..._){return _=_.map((n,o)=>(o&&(n=n.replace(new RegExp("^/"),"")),o!==_.length-1&&(n=n.replace(new RegExp("/$"),"")),n)),_.join("/")}function interpolate_data(_,[n,o,u],[l,d],s="bilinear",p=!1){const f=d/u,c=l/o,a=new _.constructor(l*d*n),t=o*u,e=l*d;for(let r=0;r=0;--p)l[p]=f,u[p]=n[o[p]],f*=u[p];const d=o.map((p,f)=>l[o.indexOf(f)]),s=new _.constructor(_.length);for(let p=0;p<_.length;++p){let f=0;for(let c=n.length-1,a=p;c>=0;--c)f+=a%n[c]*d[c],a=Math.floor(a/n[c]);s[f]=_[p]}return[s,u]}function softmax(_){const n=max(_)[0],o=_.map(d=>Math.exp(d-n)),u=o.reduce((d,s)=>d+s,0);return o.map(d=>d/u)}function log_softmax(_){return softmax(_).map(u=>Math.log(u))}function getTopItems(_,n=0){return _=Array.from(_).map((o,u)=>[u,o]).sort((o,u)=>u[1]-o[1]),n>0&&(_=_.slice(0,n)),_}function min(_){if(_.length===0)throw Error("Array must not be empty");let n=_[0],o=0;for(let u=1;u<_.length;++u)_[u]n&&(n=_[u],o=u);return[n,o]}function rfftfreq(_,n=1){if(!Number.isInteger(_))throw new TypeError(`n should be an integer, but ${_} given.`);const o=1/(_*n),u=Math.floor(_/2)+1,l=new Array(u);for(let d=0;du;u<<=1)++o;this._width=o%2===0?o-1:o,this._bitrev=new Int32Array(1<>>l&3)<>>1);for(let l=0;l>>1]=n[l];return u}toComplexArray(n,o){const u=o||this.createComplexArray();for(let l=0;l>>1],u[l+1]=0;return u}completeSpectrum(n){const o=this._csize,u=o>>>1;for(let l=2;l>=2;s>=2;s>>=2){p=l/s<<1;let t=p>>>2;for(f=0;f>>1,s>>>1)}else for(f=0,c=0;f>>1,s>>>1,u)}for(s>>=2;s>=2;s>>=2){p=l/s<<1;const t=p>>>1,e=t>>>1,r=e>>>1;for(f=0;f=_.length&&(f=2*(_.length-1)-f),u[s++]=_[f]}u.sort(),o[d]=u[l]}return o}function round(_,n){const o=Math.pow(10,n);return Math.round(_*o)/o}const ONNXTensor$1=ONNX.Tensor;class Tensor extends ONNXTensor$1{constructor(...n){return n[0]instanceof ONNX.Tensor?super(n[0].type,n[0].data,n[0].dims):super(...n),new Proxy(this,{get:(o,u)=>{if(typeof u=="string"){let l=Number(u);if(Number.isInteger(l))return o._getitem(l)}return o[u]},set:(o,u,l)=>o[u]=l})}*[Symbol.iterator](){const[n,...o]=this.dims;if(o.length>0){const u=o.reduce((l,d)=>l*d);for(let l=0;l0){const l=u.reduce((d,s)=>d*s);return this._subarray(n,l,u)}else return new Tensor(this.type,[this.data[n]],u)}indexOf(n){for(let o=0;oc[1])throw new Error(`Invalid slice: ${c}`);let a=[Math.max(c[0],0),Math.min(c[1],this.dims[f])];u.push(a),o.push(a[1]-a[0])}else throw new Error(`Invalid slice: ${c}`)}let l=u.map(([f,c])=>c-f),d=l.reduce((f,c)=>f*c),s=new this.data.constructor(d);const p=this.stride();for(let f=0;f=0;--a){const e=l[a];c+=(t%e+u[a][0])*p[a],t=Math.floor(t/e)}s[f]=this.data[c]}return new Tensor(this.type,s,o)}transpose(...n){return transpose(this,n)}sum(n=null,o=!1){return this.norm(1,n,o)}norm(n="fro",o=null,u=!1){if(n==="fro")n=2;else if(typeof n=="string")throw Error(`Unsupported norm: ${n}`);if(o===null){let s=this.data.reduce((p,f)=>p+f**n,0)**(1/n);return new Tensor(this.type,[s],[])}o=safeIndex(o,this.dims.length);const l=this.dims.slice();l[o]=1;const d=new this.data.constructor(this.data.length/this.dims[o]);for(let s=0;s=0;--f){const t=this.dims[f];if(f!==o){const e=c%t;p+=e*a,a*=l[f]}c=Math.floor(c/t)}d[p]+=this.data[s]**n}if(n!==1)for(let s=0;s=0;--s){const c=this.dims[s];if(s!==o){const a=p%c;d+=a*f,f*=this.dims[s]}p=Math.floor(p/c)}this.data[l]/=u.data[d]}return this}normalize(n=2,o=1){return this.clone().normalize_(n,o)}stride(){return dimsToStride(this.dims)}squeeze(n=null){return new Tensor(this.type,this.data,calc_squeeze_dims(this.dims,n))}squeeze_(n=null){return this.dims=calc_squeeze_dims(this.dims,n),this}unsqueeze(n=null){return new Tensor(this.type,this.data,calc_unsqueeze_dims(this.dims,n))}unsqueeze_(n=null){return this.dims=calc_unsqueeze_dims(this.dims,n),this}flatten_(n=0,o=-1){o=(o+this.dims.length)%this.dims.length;let u=this.dims.slice(0,n),l=this.dims.slice(n,o+1),d=this.dims.slice(o+1);return this.dims=[...u,l.reduce((s,p)=>s*p,1),...d],this}flatten(n=0,o=-1){return this.clone().flatten_(n,o)}view(...n){let o=-1;for(let u=0;us!==o?l*d:l,1);n[o]=this.data.length/u}return new Tensor(this.type,this.data,n)}neg_(){for(let n=0;nd*s);if(o!==u)throw Error(`cannot reshape array of size ${o} into shape (${n})`);let l=_;for(let d=n.length-1;d>=0;d--)l=l.reduce((s,p)=>{let f=s[s.length-1];return f.lengtho!==1):typeof n=="number"?_[n]===1&&_.splice(n,1):Array.isArray(n)&&(_=_.filter((o,u)=>o!==1||!n.includes(u))),_}function calc_unsqueeze_dims(_,n){return n=safeIndex(n,_.length+1),_=_.slice(),_.splice(n,0,1),_}function safeIndex(_,n,o=null){if(_<-n||_>=n)throw new Error(`IndexError: index ${_} is out of bounds for dimension${o===null?"":" "+o} with size ${n}`);return _<0&&(_=(_%n+n)%n),_}function cat(_,n=0){n=safeIndex(n,_[0].dims.length);const o=_[0].dims.slice();o[n]=_.reduce((s,p)=>s+p.dims[n],0);const u=o.reduce((s,p)=>s*p,1),l=new _[0].data.constructor(u),d=_[0].type;if(n===0){let s=0;for(let p of _)l.set(p.data,s),s+=p.data.length}else{let s=0;for(let p=0;p<_.length;++p){let f=_[p];for(let c=0;c=0;--t){const i=f.dims[t];let h=e%i;t===n&&(h+=s),a+=h*r,r*=o[t],e=Math.floor(e/i)}l[a]=f.data[c]}s+=f.dims[n]}}return new Tensor(d,l,o)}function stack(_,n=0){return cat(_.map(o=>o.unsqueeze(n)),n)}function std_mean(_,n=null,o=1,u=!1){if(n===null){const c=_.data.reduce((r,i)=>r+i,0)/_.data.length,a=Math.sqrt(_.data.reduce((r,i)=>r+(i-c)**2,0)/(_.data.length-o)),t=new Tensor(_.type,[c],[]);return[new Tensor(_.type,[a],[]),t]}n=safeIndex(n,_.dims.length);const l=mean(_,n,u),d=_.dims.slice();d[n]=1;const s=new _.data.constructor(_.data.length/_.dims[n]);for(let f=0;f<_.data.length;++f){let c=0;for(let a=_.dims.length-1,t=f,e=1;a>=0;--a){const r=_.dims[a];if(a!==n){const i=t%r;c+=i*e,e*=d[a]}t=Math.floor(t/r)}s[c]+=(_.data[f]-l.data[c])**2}for(let f=0;fs+p,0);return new Tensor(_.type,[d/_.data.length],[])}n=safeIndex(n,_.dims.length);const u=_.dims.slice();u[n]=1;const l=new _.data.constructor(_.data.length/_.dims[n]);for(let d=0;d<_.data.length;++d){let s=0;for(let p=_.dims.length-1,f=d,c=1;p>=0;--p){const a=_.dims[p];if(p!==n){const t=f%a;s+=t*c,c*=u[p]}f=Math.floor(f/a)}l[s]+=_.data[d]}if(_.dims[n]!==1)for(let d=0;d0||p>0;)switch(f.push(s-1),c.push(p-1),d[s][p].item()){case 0:--s,--p;break;case 1:--s;break;case 2:--p;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${s}, ${p}]. Please file a bug report.`)}return f.reverse(),c.reverse(),[f,c]}function dimsToStride(_){const n=new Array(_.length);for(let o=_.length-1,u=1;o>=0;--o)n[o]=u,u*=_[o];return n}function ones(_){const n=_.reduce((o,u)=>o*u,1);return new Tensor("int64",new BigInt64Array(n).fill(1n),_)}function ones_like(_){return ones(_.dims)}class PriorityQueue{constructor(n=(o,u)=>o>u){this._heap=[],this._comparator=n}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...n){return this.extend(n)}extend(n){for(const o of n)this._heap.push(o),this._siftUp();return this.size}pop(){const n=this.peek(),o=this.size-1;return o>0&&this._swap(0,o),this._heap.pop(),this._siftDown(),n}replace(n){const o=this.peek();return this._heap[0]=n,this._siftDown(),o}_parent(n){return(n+1>>>1)-1}_left(n){return(n<<1)+1}_right(n){return n+1<<1}_greater(n,o){return this._comparator(this._heap[n],this._heap[o])}_swap(n,o){const u=this._heap[n];this._heap[n]=this._heap[o],this._heap[o]=u}_siftUp(){let n=this.size-1;for(;n>0&&this._greater(n,this._parent(n));)this._swap(n,this._parent(n)),n=this._parent(n)}_siftDown(){let n=0;for(;this._left(n)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const l=new TokenLatticeNode(this.bosTokenId,0,0,0,0),d=new TokenLatticeNode(this.eosTokenId,1,this.len,0,0);this.nodes.push(l.clone()),this.nodes.push(d.clone()),this.beginNodes[this.len].push(d),this.endNodes[0].push(l)}insert(n,o,u,l){const d=this.nodes.length,s=new TokenLatticeNode(l,d,n,o,u);this.beginNodes[n].push(s),this.endNodes[n+o].push(s),this.nodes.push(s)}viterbi(){const n=this.len;let o=0;for(;o<=n;){if(this.beginNodes[o].length==0)return[];for(let p of this.beginNodes[o]){p.prev=null;let f=0,c=null;for(let a of this.endNodes[o]){const t=a.backtraceScore+p.score;(c===null||t>f)&&(c=a.clone(),f=t)}if(c!==null)p.prev=c,p.backtraceScore=f;else return[]}++o}const u=[],d=this.beginNodes[n][0].prev;if(d===null)return[];let s=d.clone();for(;s.prev!==null;)u.push(s.clone()),s=s.clone().prev.clone();return u.reverse(),u}piece(n){return this.sentence.slice(n.pos,n.pos+n.length)}tokens(){return this.viterbi().map(o=>this.piece(o))}tokenIds(){return this.viterbi().map(o=>o.tokenId)}}class TokenLatticeNode{constructor(n,o,u,l,d){this.tokenId=n,this.nodeId=o,this.pos=u,this.length=l,this.score=d,this.prev=null,this.backtraceScore=0}clone(){const n=new TokenLatticeNode(this.tokenId,this.nodeId,this.pos,this.length,this.score);return n.prev=this.prev,n.backtraceScore=this.backtraceScore,n}}async function loadTokenizer(_,n){return await Promise.all([getModelJSON(_,"tokenizer.json",!0,n),getModelJSON(_,"tokenizer_config.json",!0,n)])}function createPattern(_,n=!0){return _.Regex!==void 0?new RegExp(n?_.Regex:`(${_.Regex})`,"gu"):_.String!==void 0?_.String:(console.warn("Unknown pattern type:",_),null)}function objectToMap(_){return new Map(Object.entries(_))}function clean_up_tokenization(_){return _.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n\'t/g,"n't").replace(/ \'m/g,"'m").replace(/ \'s/g,"'s").replace(/ \'ve/g,"'ve").replace(/ \'re/g,"'re")}function remove_accents(_){return _.replace(/[\u0300-\u036f]/g,"")}function lowercase_and_remove_accent(_){return remove_accents(_.toLowerCase())}function fuse(_,n){let o=[],u=0;for(;u<_.length;){if(o.push(_[u]),_[u]!==n){++u;continue}for(;u<_.length&&_[u]===n;)++u}return o}function whitespace_split(_){return _.match(/\S+/g)||[]}const PUNCTUATION_REGEX="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E";class TokenizerModel extends Callable{constructor(n){super(),this.config=n,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}static fromConfig(n,...o){switch(n.type){case"WordPiece":return new WordPieceTokenizer(n);case"Unigram":return new Unigram(n,...o);case"BPE":return new BPE(n);default:if(n.vocab)return new LegacyTokenizerModel(n,...o);throw new Error(`Unknown TokenizerModel type: ${n.type}`)}}_call(n){return this.encode(n)}encode(n){throw Error("encode should be implemented in subclass.")}convert_tokens_to_ids(n){let o=n.map(u=>this.tokens_to_ids.get(u)??this.unk_token_id);return this.fuse_unk&&(o=fuse(o,this.unk_token_id)),o}convert_ids_to_tokens(n){return n.map(o=>this.vocab[o]??this.unk_token)}}class WordPieceTokenizer extends TokenizerModel{constructor(n){super(n),this.tokens_to_ids=objectToMap(n.vocab),this.unk_token_id=this.tokens_to_ids.get(n.unk_token),this.unk_token=n.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[o,u]of this.tokens_to_ids)this.vocab[u]=o}encode(n){let o=[];for(let u of n){let l=[...u],d=!1,s=0,p=[];for(;s0&&(a=this.config.continuing_subword_prefix+a),this.tokens_to_ids.has(a)){c=a;break}--f}if(c===null){d=!0;break}p.push(c),s=f}d?o.push(this.unk_token):o.push(...p)}return o}}class Unigram extends TokenizerModel{constructor(n,o){super(n);const u=n.vocab.length;this.vocab=new Array(u),this.scores=new Array(u);for(let l=0;l[l,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(n){const o=n.sentence,u=o.length;let l=0;for(;l{const _=[...Array.from({length:"~".charCodeAt(0)-"!".charCodeAt(0)+1},(l,d)=>d+"!".charCodeAt(0)),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},(l,d)=>d+"¡".charCodeAt(0)),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},(l,d)=>d+"®".charCodeAt(0))];let n=_.slice(),o=0;for(let l=0;l<256;++l)_.includes(l)||(_.push(l),n.push(256+o),o+=1);let u=n.map(l=>String.fromCharCode(l));return Object.fromEntries(_.map((l,d)=>[l,u[d]]))})(),UNICODE_TO_BYTES=reverseDictionary(BYTES_TO_UNICODE);class BPE extends TokenizerModel{constructor(n){super(n),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=objectToMap(n.vocab),this.unk_token_id=this.tokens_to_ids.get(n.unk_token),this.unk_token=n.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[o,u]of this.tokens_to_ids)this.vocab[u]=o;this.bpe_ranks=new Map(n.merges.map((o,u)=>[o,u])),this.merges=n.merges.map(o=>o.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=n.end_of_word_suffix,this.continuing_subword_suffix=n.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(n){if(n.length===0)return[];const o=this.cache.get(n);if(o!==void 0)return o;const u=Array.from(n);this.end_of_word_suffix&&(u[u.length-1]+=this.end_of_word_suffix);let l=[];if(u.length>1){const d=new PriorityQueue((f,c)=>f.score`<0x${s.toString(16).toUpperCase().padStart(2,"0")}>`)):o.push(this.unk_token)}return o}}class LegacyTokenizerModel extends TokenizerModel{constructor(n,o){super(n),this.tokens_to_ids=objectToMap(o.target_lang?n.vocab[o.target_lang]:n.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[u,l]of this.tokens_to_ids)this.vocab[l]=u}encode(n){return n}}class Normalizer extends Callable{constructor(n){super(),this.config=n}static fromConfig(n){if(n===null)return null;switch(n.type){case"BertNormalizer":return new BertNormalizer(n);case"Precompiled":return new Precompiled(n);case"Sequence":return new NormalizerSequence(n);case"Replace":return new Replace(n);case"NFC":return new NFC(n);case"NFKD":return new NFKD(n);case"Strip":return new StripNormalizer(n);case"StripAccents":return new StripAccents(n);case"Lowercase":return new Lowercase(n);case"Prepend":return new Prepend(n);default:throw new Error(`Unknown Normalizer type: ${n.type}`)}}normalize(n){throw Error("normalize should be implemented in subclass.")}_call(n){return this.normalize(n)}}class Replace extends Normalizer{normalize(n){let o=createPattern(this.config.pattern);return o===null||(n=n.replaceAll(o,this.config.content)),n}}class NFC extends Normalizer{normalize(n){return n=n.normalize("NFC"),n}}class NFKD extends Normalizer{normalize(n){return n=n.normalize("NFKD"),n}}class StripNormalizer extends Normalizer{normalize(n){return this.config.strip_left&&this.config.strip_right?n=n.trim():(this.config.strip_left&&(n=n.trimStart()),this.config.strip_right&&(n=n.trimEnd())),n}}class StripAccents extends Normalizer{normalize(n){return n=remove_accents(n),n}}class Lowercase extends Normalizer{normalize(n){return n=n.toLowerCase(),n}}class Prepend extends Normalizer{normalize(n){return n=this.config.prepend+n,n}}class NormalizerSequence extends Normalizer{constructor(n){super(n),this.normalizers=n.normalizers.map(o=>Normalizer.fromConfig(o))}normalize(n){return this.normalizers.reduce((o,u)=>u.normalize(o),n)}}class BertNormalizer extends Normalizer{_tokenize_chinese_chars(n){let o=[];for(let u=0;u=19968&&n<=40959||n>=13312&&n<=19903||n>=131072&&n<=173791||n>=173824&&n<=177983||n>=177984&&n<=178207||n>=178208&&n<=183983||n>=63744&&n<=64255||n>=194560&&n<=195103}stripAccents(n){return n.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}normalize(n){return this.config.handle_chinese_chars&&(n=this._tokenize_chinese_chars(n)),this.config.lowercase?(n=n.toLowerCase(),this.config.strip_accents!==!1&&(n=this.stripAccents(n))):this.config.strip_accents&&(n=this.stripAccents(n)),n}}class PreTokenizer extends Callable{static fromConfig(n){if(n===null)return null;switch(n.type){case"BertPreTokenizer":return new BertPreTokenizer(n);case"Sequence":return new PreTokenizerSequence(n);case"WhitespaceSplit":return new WhitespaceSplit(n);case"Metaspace":return new MetaspacePreTokenizer(n);case"ByteLevel":return new ByteLevelPreTokenizer(n);case"Split":return new SplitPreTokenizer(n);case"Punctuation":return new PunctuationPreTokenizer(n);case"Digits":return new DigitsPreTokenizer(n);case"Replace":return new ReplacePreTokenizer(n);default:throw new Error(`Unknown PreTokenizer type: ${n.type}`)}}pre_tokenize_text(n){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(n){let o=[];return Array.isArray(n)?o=n.map(u=>this.pre_tokenize_text(u)):o=this.pre_tokenize_text(n),o.flat()}_call(n){return this.pre_tokenize(n)}}class BertPreTokenizer extends PreTokenizer{constructor(n){super(),this.pattern=new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`,"gu")}pre_tokenize_text(n){return n.trim().match(this.pattern)||[]}}class ByteLevelPreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n,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=/'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(n){return this.add_prefix_space&&!n.startsWith(" ")&&(n=" "+n),(this.use_regex?n.match(this.pattern)||[]:[n]).map(u=>Array.from(this.text_encoder.encode(u),l=>this.byte_encoder[l]).join(""))}}class SplitPreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n,this.pattern=createPattern(this.config.pattern,this.config.invert)}pre_tokenize_text(n){return this.pattern===null?[]:this.config.invert?n.match(this.pattern)||[]:n.split(this.pattern).filter(o=>o)}}class PunctuationPreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n,this.pattern=new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`,"gu")}pre_tokenize_text(n){return n.match(this.pattern)||[]}}class DigitsPreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n;const o=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(o,"gu")}pre_tokenize_text(n){return n.match(this.pattern)||[]}}class PostProcessor extends Callable{constructor(n){super(),this.config=n}static fromConfig(n){if(n===null)return null;switch(n.type){case"TemplateProcessing":return new TemplateProcessing(n);case"ByteLevel":return new ByteLevelPostProcessor(n);case"RobertaProcessing":return new RobertaProcessing(n);case"BertProcessing":return new BertProcessing(n);default:throw new Error(`Unknown PostProcessor type: ${n.type}`)}}post_process(n,...o){throw Error("post_process should be implemented in subclass.")}_call(n,...o){return this.post_process(n,...o)}}class BertProcessing extends PostProcessor{constructor(n){super(n),this.cls=n.cls[0],this.sep=n.sep[0]}post_process(n,o=null){return n=mergeArrays([this.cls],n,[this.sep]),o!==null&&(n=mergeArrays(n,[this.sep],o,[this.sep])),n}}class RobertaProcessing extends BertProcessing{}class TemplateProcessing extends PostProcessor{constructor(n){super(n),this.single=n.single,this.pair=n.pair}post_process(n,o=null){let u=o===null?this.single:this.pair,l=[];for(let d of u)"SpecialToken"in d?l.push(d.SpecialToken.id):"Sequence"in d&&(d.Sequence.id==="A"?l=mergeArrays(l,n):d.Sequence.id==="B"&&(l=mergeArrays(l,o)));return l}}class ByteLevelPostProcessor extends PostProcessor{post_process(n){return n}}class Decoder extends Callable{constructor(n){super(),this.config=n,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=n.trim_offsets}static fromConfig(n){switch(n.type){case"WordPiece":return new WordPieceDecoder(n);case"Metaspace":return new MetaspaceDecoder(n);case"ByteLevel":return new ByteLevelDecoder(n);case"Replace":return new ReplaceDecoder(n);case"ByteFallback":return new ByteFallback(n);case"Fuse":return new FuseDecoder(n);case"Strip":return new StripDecoder(n);case"Sequence":return new DecoderSequence(n);case"CTC":return new CTCDecoder(n);case"BPEDecoder":return new BPEDecoder(n);default:throw new Error(`Unknown Decoder type: ${n.type}`)}}_call(n){return this.decode(n)}decode(n){return this.decode_chain(n).join("")}decode_chain(n){throw Error("`decode_chain` should be implemented in subclass.")}}class ReplaceDecoder extends Decoder{decode_chain(n){let o=createPattern(this.config.pattern);return o===null?n:n.map(u=>u.replaceAll(o,this.config.content))}}class ByteFallback extends Decoder{constructor(n){super(n),this.text_decoder=new TextDecoder}decode_chain(n){let o=[],u=[];for(let l of n){let d=null;if(l.length===6&&l.startsWith("<0x")&&l.endsWith(">")){let s=parseInt(l.slice(3,5),16);isNaN(s)||(d=s)}if(d!==null)u.push(d);else{if(u.length>0){let s=this.text_decoder.decode(Uint8Array.from(u));o.push(s),u=[]}o.push(l)}}if(u.length>0){let l=this.text_decoder.decode(Uint8Array.from(u));o.push(l),u=[]}return o}}class FuseDecoder extends Decoder{decode_chain(n){return[n.join("")]}}class StripDecoder extends Decoder{constructor(n){super(n),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(n){return n.map(o=>{let u=0;for(let d=0;d(u!==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(n){super(n),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(n){let o=n.join(""),u=new Uint8Array([...o].map(d=>this.byte_decoder[d]));return this.text_decoder.decode(u)}decode_chain(n){let o=[],u=[];for(let l of n)this.added_tokens.includes(l)?(u.length>0&&(o.push(this.convert_tokens_to_string(u)),u=[]),o.push(l)):u.push(l);return u.length>0&&o.push(this.convert_tokens_to_string(u)),o}}class CTCDecoder extends Decoder{constructor(n){super(n),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(n){if(n.length===0)return"";let o=[n[0]];for(let d=1;dd!==this.pad_token).join("");return this.cleanup&&(l=clean_up_tokenization(l).replaceAll(this.word_delimiter_token," ").trim()),l}decode_chain(n){return[this.convert_tokens_to_string(n)]}}class DecoderSequence extends Decoder{constructor(n){super(n),this.decoders=n.decoders.map(o=>Decoder.fromConfig(o))}decode_chain(n){return this.decoders.reduce((o,u)=>u.decode_chain(o),n)}}class BPEDecoder extends Decoder{constructor(n){super(n),this.suffix=this.config.suffix}decode_chain(n){return n.map((o,u)=>o.replaceAll(this.suffix,u===n.length-1?"":" "))}}class MetaspacePreTokenizer extends PreTokenizer{constructor(n){super(),this.addPrefixSpace=n.add_prefix_space,this.replacement=n.replacement,this.strRep=n.str_rep||this.replacement}pre_tokenize(n){typeof n=="string"&&(n=n.trimStart().split(/\s+/));const o=[];for(let u of n){let l=u.replaceAll(" ",this.strRep);this.addPrefixSpace&&!l.startsWith(this.replacement)&&(l=this.strRep+l),o.push(l)}return o}}class MetaspaceDecoder extends Decoder{constructor(n){super(n),this.addPrefixSpace=n.add_prefix_space,this.replacement=n.replacement}decode_chain(n){let o=[];for(let u=0;uu.normalize("NFKC")).join("~"):n=n.normalize("NFKC"),n}}class PreTokenizerSequence extends PreTokenizer{constructor(n){super(),this.tokenizers=n.pretokenizers.map(o=>PreTokenizer.fromConfig(o))}pre_tokenize_text(n){return typeof n=="string"&&(n=[n]),this.tokenizers.reduce((o,u)=>u.pre_tokenize(o),n)}}class WhitespaceSplit extends PreTokenizer{constructor(n){super()}pre_tokenize_text(n){return whitespace_split(n)}}class ReplacePreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n,this.pattern=createPattern(this.config.pattern),this.content=this.config.content}pre_tokenize_text(n){return this.pattern===null?[n]:[n.replaceAll(this.pattern,this.config.content)]}}class PreTrainedTokenizer extends Callable{constructor(n,o){super(),this.normalizer=Normalizer.fromConfig(n.normalizer),this.pre_tokenizer=PreTokenizer.fromConfig(n.pre_tokenizer),this.model=TokenizerModel.fromConfig(n.model,o),this.post_processor=PostProcessor.fromConfig(n.post_processor),this.decoder=Decoder.fromConfig(n.decoder),this.decoder.end_of_word_suffix=this.model.end_of_word_suffix,this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(let u of n.added_tokens){let l=u.id,d=u.content;this.added_tokens.push(d),this.model.tokens_to_ids.set(d,l),this.model.vocab[l]=d,u.special&&(this.special_tokens.push(d),this.all_special_ids.push(l))}this.special_tokens.push(...o.additional_special_tokens??[]),this.special_tokens=[...new Set(this.special_tokens)],this.decoder.added_tokens=this.added_tokens,this.added_tokens_regex=this.added_tokens.length>0?new RegExp("("+this.added_tokens.map(escapeRegExp).join("|")+")"):null,this.mask_token=this.getToken(o,"mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken(o,"pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken(o,"sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.model_max_length=o.model_max_length,this.remove_space=o.remove_space,this.clean_up_tokenization_spaces=o.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=o.do_lowercase_and_remove_accent??!1,this.padding_side="right"}getToken(n,...o){for(let u of o){let l=n[u];if(l)if(typeof l=="object"){if(l.__type==="AddedToken")return l.content;throw Error(`Unknown token: ${l}`)}else return l}return null}static async from_pretrained(n,{progress_callback:o=null,config:u=null,cache_dir:l=null,local_files_only:d=!1,revision:s="main"}={}){let p=await loadTokenizer(n,{progress_callback:o,config:u,cache_dir:l,local_files_only:d,revision:s});return new this(...p)}prepare_model_inputs(n){return n}_call(n,{text_pair:o=null,add_special_tokens:u=!0,padding:l=!1,truncation:d=null,max_length:s=null,return_tensor:p=!0}={}){let f;if(Array.isArray(n)){if(n.length===0)throw Error("text array must be non-empty");if(o!==null){if(Array.isArray(o)){if(n.length!==o.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");f=n.map((e,r)=>this.encode(e,o[r],{add_special_tokens:u}))}else f=n.map(e=>this.encode(e,null,{add_special_tokens:u}))}else{if(n===null)throw Error("text may not be null");if(Array.isArray(o))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");f=[this.encode(n,o,{add_special_tokens:u})]}let c=max(f.map(e=>e.length))[0];s===null&&(s=c),s=Math.min(s,this.model_max_length);let a=[];if(l||d)for(let e=0;es)d&&(f[e]=f[e].slice(0,s)),a.push(new Array(f[e].length).fill(1));else if(l){let r=s-f[e].length;this.padding_side==="right"?(a.push(new Array(f[e].length).fill(1).concat(new Array(r).fill(0))),f[e].push(...new Array(r).fill(this.pad_token_id))):(a.push(new Array(r).fill(0).concat(new Array(f[e].length).fill(1))),f[e].unshift(...new Array(r).fill(this.pad_token_id)))}else a.push(new Array(f[e].length).fill(1));else a=f.map(e=>new Array(e.length).fill(1));if(p){if(!(l&&d)&&f.some(r=>r.length!==f[0].length))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.");let e=[f.length,f[0].length];f=new Tensor("int64",BigInt64Array.from(f.flat().map(BigInt)),e),a=new Tensor("int64",BigInt64Array.from(a.flat().map(BigInt)),e)}else Array.isArray(n)||(f=f[0],a=a[0]);let t={input_ids:f,attention_mask:a};return t=this.prepare_model_inputs(t),t}_encode_text(n){return n===null?null:(this.added_tokens_regex?n.split(this.added_tokens_regex).filter(l=>l):[n]).map(l=>{if(this.added_tokens.includes(l))return l;{this.remove_space===!0&&(l=l.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(l=lowercase_and_remove_accent(l)),this.normalizer!==null&&(l=this.normalizer(l));let d=this.pre_tokenizer!==null?this.pre_tokenizer(l):[l];return this.model(d)}}).flat()}encode(n,o=null,{add_special_tokens:u=!0}={}){let l=this._encode_text(n),d=this._encode_text(o),s=this.post_processor!==null&&u?this.post_processor(l,d):mergeArrays(l??[],d??[]);return this.model.convert_tokens_to_ids(s)}batch_decode(n,o={}){return n.map(u=>this.decode(u,o))}decode(n,o={}){if(!Array.isArray(n)||n.length===0||!isIntegralNumber(n[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(n,o)}decode_single(n,{skip_special_tokens:o=!1,clean_up_tokenization_spaces:u=null}){let l=this.model.convert_ids_to_tokens(n);o&&(l=l.filter(s=>!this.special_tokens.includes(s)));let d=this.decoder(l);return this.decoder.end_of_word_suffix&&(d=d.replaceAll(this.decoder.end_of_word_suffix," "),o&&(d=d.trim())),(u??this.clean_up_tokenization_spaces)&&(d=clean_up_tokenization(d)),d}}function add_token_types(_){if(_.input_ids instanceof Tensor)_.token_type_ids=new Tensor("int64",new BigInt64Array(_.input_ids.data.length),_.input_ids.dims);else if(Array.isArray(_.input_ids))Array.isArray(_.input_ids[0])?_.token_type_ids=_.input_ids.map(n=>new Array(n.length).fill(0)):_.token_type_ids=new Array(_.input_ids.length).fill(0);else throw new Error("Input ids must be a Tensor or an Array");return _}class BertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class AlbertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class MobileBertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class SqueezeBertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class DebertaTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class DebertaV2Tokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class HerbertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class DistilBertTokenizer extends PreTrainedTokenizer{}class CamembertTokenizer extends PreTrainedTokenizer{}class XLMTokenizer extends PreTrainedTokenizer{constructor(n,o){super(n,o),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}prepare_model_inputs(n){return add_token_types(n)}}class T5Tokenizer extends PreTrainedTokenizer{}class GPT2Tokenizer extends PreTrainedTokenizer{}class BartTokenizer extends PreTrainedTokenizer{}class MBartTokenizer extends PreTrainedTokenizer{constructor(n,o){super(n,o),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(u=>this.languageRegex.test(u)),this.lang_to_token=u=>u}_build_translation_inputs(n,o,u){return _build_translation_inputs(this,n,o,u)}}class MBart50Tokenizer extends MBartTokenizer{}class RobertaTokenizer extends PreTrainedTokenizer{}class BloomTokenizer extends PreTrainedTokenizer{constructor(n,o){var d,s;const u=".,!?…。,、।۔،",l=(s=(d=n.pre_tokenizer)==null?void 0:d.pretokenizers[0])==null?void 0:s.pattern;l&&l.Regex===` ?[^(\\s|[${u}])]+`&&(l.Regex=` ?[^\\s${u}]+`),super(n,o)}}class LlamaTokenizer extends PreTrainedTokenizer{}class CodeLlamaTokenizer extends PreTrainedTokenizer{}class XLMRobertaTokenizer extends PreTrainedTokenizer{}class MPNetTokenizer extends PreTrainedTokenizer{}class FalconTokenizer extends PreTrainedTokenizer{}class GPTNeoXTokenizer extends PreTrainedTokenizer{}function _build_translation_inputs(_,n,o,u){if(!("language_codes"in _)||!Array.isArray(_.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in _)||!(_.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in _)||typeof _.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const l=u.src_lang,d=u.tgt_lang;if(!_.language_codes.includes(d))throw new Error(`Target language code "${d}" is not valid. Must be one of: {${_.language_codes.join(", ")}}`);if(l!==void 0){if(!_.language_codes.includes(l))throw new Error(`Source language code "${l}" is not valid. Must be one of: {${_.language_codes.join(", ")}}`);for(let s of _.post_processor.config.single)if("SpecialToken"in s&&_.languageRegex.test(s.SpecialToken.id)){s.SpecialToken.id=_.lang_to_token(l);break}}return u.forced_bos_token_id=_.model.convert_tokens_to_ids([_.lang_to_token(d)])[0],_._call(n,o)}class NllbTokenizer extends PreTrainedTokenizer{constructor(n,o){super(n,o),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(u=>this.languageRegex.test(u)),this.lang_to_token=u=>u}_build_translation_inputs(n,o,u){return _build_translation_inputs(this,n,o,u)}}class M2M100Tokenizer extends PreTrainedTokenizer{constructor(n,o){super(n,o),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(u=>this.languageRegex.test(u)).map(u=>u.slice(2,-2)),this.lang_to_token=u=>`__${u}__`}_build_translation_inputs(n,o,u){return _build_translation_inputs(this,n,o,u)}}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(([_,n])=>[n,_]),["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{_decode_asr(n,{return_timestamps:o=!1,return_language:u=!1,time_precision:l=null,force_full_sequences:d=!0}={}){if(l===null)throw Error("Must specify time_precision");let s=null;const p=o==="word";function f(){return{language:s,timestamp:[null,null],text:""}}const c=[];let a=f(),t=0;const e=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1;let r=[],i=[],h=!1,g=null;const m=new Set(this.all_special_ids);for(let w of n){const T=w.tokens,S=p?w.token_timestamps:null;let A=null,O=e;if("stride"in w){const[F,R,$]=w.stride;if(t-=R,g=F-$,R&&(O=R/l+e),$)for(let N=T.length-1;N>=0;--N){const G=T[N];if(G>=e){if(A!==null&&(G-e)*l=e){const $=(R-e)*l+t,N=round($,2);if(A!==null&&R>=A)h=!0;else if(h||r.length>0&&R0?(r.push(v),p&&i.push(M)):r.every(F=>F.length===0)&&(a=f(),r=[],v=[],i=[],M=[])}if(r.length>0){if(d&&o)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,T]=this.findLongestCommonSequence(r,i),S=this.decode(w);a.text=S,p&&(a.words=this.collateWordTimestamps(w,T,s)),c.push(a)}let b=Object.create(null);const y=c.map(w=>w.text).join("");if(o||u){for(let w=0;w0;let p=s?[]:null,f=s?o[0]:null;for(let c=1;cN===F[G]).length,$=R/w+T;R>1&&$>t&&(t=$,e=[S,A,v,M])}const[i,h,g,m]=e,b=Math.floor((h+i)/2),y=Math.floor((m+g)/2);d.push(...u.slice(0,b)),u=a.slice(y),l=u.length,s&&(p.push(...f.slice(0,b)),f=o[c].slice(y))}return d.push(...u),s?(p.push(...f),[d,p]):[d,[]]}collateWordTimestamps(n,o,u){let[l,d,s]=this.combineTokensIntoWords(n,u),p=[];for(let f=0;f=l){let p=(s-l)*u;p=round(p,2),d.push(`<|${p}|>`),d.push([])}else d[d.length-1].push(s);return d=d.map(s=>typeof s=="string"?s:super.decode(s,o)),d.join("")}splitTokensOnUnicode(n){const o=this.decode(n,{decode_with_timestamps:!0}),u="�";let l=[],d=[],s=[],p=[],f=[],c=0;for(let a=0;a=this.model.tokens_to_ids.get("<|endoftext|>"),i=a.startsWith(" "),h=a.trim(),g=f.test(h);if(r||i||g||d.length===0)d.push(a),s.push(t),p.push(e);else{const m=d.length-1;d[m]+=a,s[m].push(...t),p[m].push(...e)}}return[d,s,p]}mergePunctuations(n,o,u,l,d){let s=structuredClone(n),p=structuredClone(o),f=structuredClone(u),c=s.length-2,a=s.length-1;for(;c>=0;)s[c].startsWith(" ")&&l.includes(s[c].trim())?(s[a]=s[c]+s[a],p[a]=mergeArrays(p[c],p[a]),f[a]=mergeArrays(f[c],f[a]),s[c]="",p[c]=[],f[c]=[]):a=c,--c;for(c=0,a=1;at),p.filter(t=>t.length>0),f.filter(t=>t.length>0)]}get_decoder_prompt_ids({language:n=null,task:o=null,no_timestamps:u=!0}={}){let l=[];if(n){n=n.toLowerCase();let d=WHISPER_TO_LANGUAGE_CODE_MAPPING.get(n);if(d===void 0)if(WHISPER_LANGUAGE_MAPPING.has(n))d=n;else{const f=n.length===2?WHISPER_LANGUAGE_MAPPING.keys():WHISPER_LANGUAGE_MAPPING.values();throw new Error(`Language "${n}" is not supported. Must be one of: ${JSON.stringify(f)}`)}let s=this.model.tokens_to_ids.get(`<|${d}|>`);if(s===void 0)throw new Error(`Unable to find language "${d}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);l.push(s)}else l.push(null);if(o){if(o=o.toLowerCase(),o!=="transcribe"&&o!=="translate")throw new Error(`Task "${o}" is not supported. Must be one of: ["transcribe", "translate"]`);let d=this.model.tokens_to_ids.get(`<|${o}|>`);if(d===void 0)throw new Error(`Unable to find task "${o}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);l.push(d)}else l.push(null);if(u){let d=this.model.tokens_to_ids.get("<|notimestamps|>");if(d===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.');l.push(d)}return l.map((d,s)=>[s+1,d]).filter(d=>d[1]!==null)}}class CodeGenTokenizer extends PreTrainedTokenizer{}class CLIPTokenizer extends PreTrainedTokenizer{}class MarianTokenizer extends PreTrainedTokenizer{constructor(n,o){super(n,o),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(u=>this.languageRegex.test(u)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(n){if(n===null)return null;let[o,...u]=n.trim().split(this.languageRegex);if(u.length===0)return super._encode_text(o);if(u.length===2){let[l,d]=u;return this.supported_language_codes.includes(l)||console.warn(`Unsupported language code "${l}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),mergeArrays([l],super._encode_text(d))}}}class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer{}class BlenderbotTokenizer extends PreTrainedTokenizer{}class BlenderbotSmallTokenizer extends PreTrainedTokenizer{}class SpeechT5Tokenizer extends PreTrainedTokenizer{}class AutoTokenizer{static async from_pretrained(n,{quantized:o=!0,progress_callback:u=null,config:l=null,cache_dir:d=null,local_files_only:s=!1,revision:p="main"}={}){let[f,c]=await loadTokenizer(n,{quantized:o,progress_callback:u,config:l,cache_dir:d,local_files_only:s,revision:p}),a=c.tokenizer_class.replace(/Fast$/,""),t=this.TOKENIZER_CLASS_MAPPING[a];return t||(console.warn(`Unknown tokenizer class "${a}", attempting to construct from base class.`),t=PreTrainedTokenizer),new t(f,c)}}le(AutoTokenizer,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer,DistilBertTokenizer,CamembertTokenizer,DebertaTokenizer,DebertaV2Tokenizer,BertTokenizer,HerbertTokenizer,XLMTokenizer,MobileBertTokenizer,SqueezeBertTokenizer,AlbertTokenizer,GPT2Tokenizer,BartTokenizer,MBartTokenizer,MBart50Tokenizer,RobertaTokenizer,WhisperTokenizer,CodeGenTokenizer,CLIPTokenizer,MarianTokenizer,BloomTokenizer,NllbTokenizer,M2M100Tokenizer,LlamaTokenizer,CodeLlamaTokenizer,XLMRobertaTokenizer,MPNetTokenizer,FalconTokenizer,GPTNeoXTokenizer,Wav2Vec2CTCTokenizer,BlenderbotTokenizer,BlenderbotSmallTokenizer,SpeechT5Tokenizer,PreTrainedTokenizer});async function loadConfig(_,n){return await getModelJSON(_,"config.json",!0,n)}class PretrainedConfig{constructor(n){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,n)}static async from_pretrained(n,{progress_callback:o=null,config:u=null,cache_dir:l=null,local_files_only:d=!1,revision:s="main"}={}){let p=u??await loadConfig(n,{progress_callback:o,config:u,cache_dir:l,local_files_only:d,revision:s});return new this(p)}}class AutoConfig{static async from_pretrained(...n){return PretrainedConfig.from_pretrained(...n)}}class LogitsProcessorList extends Callable{constructor(){super(),this.processors=[]}push(n){this.processors.push(n)}extend(n){this.processors.push(...n)}_call(n,o){for(let u of o)this.processors.forEach(l=>l(n,u))}[Symbol.iterator](){return this.processors.values()}}class LogitsProcessor extends Callable{_call(n,o){throw Error("`_call` should be implemented in a subclass")}}class ForceTokensLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.force_token_map=Object.fromEntries(n??[])}_call(n,o){let u=this.force_token_map[n.length];return exists(u)&&(o.data.fill(-1/0),o.data[u]=0),o}}class ForcedBOSTokenLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.bos_token_id=n}_call(n,o){return n.length===1&&(o.data.fill(-1/0),o.data[this.bos_token_id]=0),o}}class ForcedEOSTokenLogitsProcessor extends LogitsProcessor{constructor(n,o){super(),this.max_length=n,this.forced_eos_token_id=o}_call(n,o){}}class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor{constructor(n,o){super(),this.begin_suppress_tokens=n,this.begin_index=o}_call(n,o){if(n.length===this.begin_index)for(let u of this.begin_suppress_tokens)o.data[u]=-1/0;return o}}class WhisperTimeStampLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.eos_token_id=n.eos_token_id,this.no_timestamps_token_id=n.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=(n.forced_decoder_ids||[]).length+2,n.forced_decoder_ids.slice(-1)[0][1]===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=n.max_initial_timestamp_index}_call(n,o){if(o.data[this.no_timestamps_token_id]=-1/0,n.length===this.begin_index-1)return o.data.fill(-1/0),o.data[this.timestamp_begin]=0,o;const u=n.slice(this.begin_index),l=u.length>=1&&u[u.length-1]>=this.timestamp_begin,d=u.length<2||u[u.length-2]>=this.timestamp_begin;if(l&&(d?o.data.subarray(this.timestamp_begin).fill(-1/0):o.data.subarray(0,this.eos_token_id).fill(-1/0)),n.length===this.begin_index&&this.max_initial_timestamp_index!==null){const c=this.timestamp_begin+this.max_initial_timestamp_index;o.data.subarray(c+1).fill(-1/0)}const s=log_softmax(o.data),p=Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce((c,a)=>c+a)),f=max(s.subarray(0,this.timestamp_begin))[0];return p>f&&o.data.subarray(0,this.timestamp_begin).fill(-1/0),o}}class NoRepeatNGramLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.no_repeat_ngram_size=n}getNgrams(n){const o=n.length,u=[];for(let d=0;d0&&(l=l.map(d=>d/this.generation_config.temperature)),l}randomSelect(n){let o=n.reduce((l,d)=>l+d,0),u=Math.random()*o;for(let l=0;l1)return new BeamSearchSampler(n);if(n.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${n.num_return_sequences}.`);return new GreedySampler(n)}}class GreedySampler extends Sampler{sample(n,o=-1){let u=this.getLogits(n,o);return[[max(u)[1],0]]}}class MultinomialSampler extends Sampler{sample(n,o=-1){let u=n.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const l=this.getLogits(n,o),d=getTopItems(l,u),s=softmax(d.map(p=>p[1]));return Array.from({length:this.generation_config.num_beams},()=>{const p=this.randomSelect(s);return[d[p][0],Math.log(s[p])]})}}class BeamSearchSampler extends Sampler{sample(n,o=-1){let u=n.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const l=this.getLogits(n,o),d=getTopItems(l,u),s=softmax(d.map(p=>p[1]));return Array.from({length:this.generation_config.num_beams},(p,f)=>[d[f][0],Math.log(s[f])])}}const{InferenceSession,Tensor:ONNXTensor}=ONNX,MODEL_TYPES={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4},MODEL_TYPE_MAPPING=new Map,MODEL_NAME_TO_CLASS_MAPPING=new Map,MODEL_CLASS_TO_NAME_MAPPING=new Map;async function constructSession(_,n,o){let u=`onnx/${n}${o.quantized?"_quantized":""}.onnx`,l=await getModelFile(_,u,!0,o);try{return await InferenceSession.create(l,{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(l,{executionProviders:["wasm"]})}}async function validateInputs(_,n){const o={},u=[];for(let s of _.inputNames)n[s]===void 0?u.push(s):o[s]=n[s];if(u.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${u.join(", ")}.`);const l=Object.keys(n).length,d=_.inputNames.length;if(l>d){let s=Object.keys(n).filter(p=>!_.inputNames.includes(p));console.warn(`WARNING: Too many inputs were provided (${l} > ${d}). The following inputs will be ignored: "${s.join(", ")}".`)}return o}async function sessionRun(_,n){const o=await validateInputs(_,n);try{let u=await _.run(o);return u=replaceTensors(u),u}catch(u){throw console.error(`An error occurred during model execution: "${u}".`),console.error("Inputs given to model:",o),u}}function replaceTensors(_){for(let n in _)_[n]instanceof ONNXTensor?_[n]=new Tensor(_[n]):typeof _[n]=="object"&&replaceTensors(_[n]);return _}function toI64Tensor(_){if(_ instanceof Tensor)return _;if(_.length===0)throw Error("items must be non-empty");if(Array.isArray(_[0])){if(_.some(n=>n.length!==_[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(_.flat().map(n=>BigInt(n))),[_.length,_[0].length])}else return new Tensor("int64",BigInt64Array.from(_.map(n=>BigInt(n))),[1,_.length])}function prepareAttentionMask(_,n){let o=_.config.pad_token_id??null,u=_.config.eos_token_id??null;isIntegralNumber(u)&&(u=[u]);let l=n.indexOf(o)!==-1,d=u===null||!u.includes(o);if(l&&d){let s=BigInt64Array.from(n.data.map(p=>p!=o));return new Tensor("int64",s,n.dims)}else return ones_like(n)}function boolTensor(_){return new Tensor("bool",[_],[1])}async function seq2seqForward(_,n){let{encoder_outputs:o,past_key_values:u}=n;o||(o=(await encoderForward(_,n)).last_hidden_state);let l={input_ids:n.decoder_input_ids,encoder_hidden_states:o,use_cache_branch:boolTensor(!!u)};_.decoder_merged_session.inputNames.includes("encoder_attention_mask")&&(l.encoder_attention_mask=n.attention_mask),_.addPastKeyValues(l,u);const d=await sessionRun(_.decoder_merged_session,l);let s=d.logits;u=_.getPastKeyValues(d,u);const p=_.getAttentions(d);return new Seq2SeqLMOutput({logits:s,past_key_values:u,encoder_outputs:o,...p})}function seq2seqStartBeams(_,n,o,u){let l=[],d=0;const s=_.requires_attention_mask??!0;let p=o.decoder_input_ids??o.decoder_start_token_id??o.bos_token_id??o.eos_token_id;p instanceof Tensor?p=p.tolist().flat():Array.isArray(p)||(p=[p]);for(let f of n){f.dims=[1,...f.dims];let c={inputs:f,encoder_outputs:null,prev_model_outputs:null,output_token_ids:p,done:!1,score:0,id:d++};s&&(c.attention_mask=prepareAttentionMask(_,f)),l.push(c)}return l}async function seq2seqRunBeam(_,n){var s;const o=_.main_input_name;let u=n.output_token_ids;n.prev_model_outputs&&(u=u.slice(-1));let l={[o]:n.inputs,decoder_input_ids:toI64Tensor(u),encoder_outputs:n.encoder_outputs,past_key_values:(s=n.prev_model_outputs)==null?void 0:s.past_key_values};n.attention_mask&&(l.attention_mask=n.attention_mask);let d=await _.forward(l);return n.prev_model_outputs=d,n.encoder_outputs=d.encoder_outputs,d}function seq2seqUpdatebeam(_,n){_.output_token_ids=[..._.output_token_ids,n]}async function encoderForward(_,n){let o={};for(let u of _.session.inputNames)o[u]=n[u];return await sessionRun(_.session,o)}async function decoderForward(_,n){let{input_ids:o,past_key_values:u,attention_mask:l}=n,d={input_ids:o,attention_mask:l??prepareAttentionMask(_,o),use_cache_branch:boolTensor(!!u)};_.addPastKeyValues(d,u);let s=await sessionRun(_.session,d),p=s.logits;return u=_.getPastKeyValues(s,u),{logits:p,past_key_values:u}}function decoderStartBeams(_,n,o,u,l){let d=[],s=0;for(let p of n){let f=p.tolist().map(Number);p.dims=[1,...p.dims];let c;l?(c=l[s],c.dims=[1,...c.dims]):c=prepareAttentionMask(_,p);let a={input:p,model_input_ids:p,attention_mask:c,prev_model_outputs:null,output_token_ids:f,num_output_tokens:u,done:!1,score:0,id:s++};d.push(a)}return d}async function decoderRunBeam(_,n){var d;let o=new BigInt64Array(n.output_token_ids.length).fill(1n),u={input_ids:n.model_input_ids,attention_mask:new Tensor("int64",o,[1,o.length]),past_key_values:(d=n.prev_model_outputs)==null?void 0:d.past_key_values},l=await _.forward(u);return n.prev_model_outputs=l,l}function decoderUpdatebeam(_,n){_.output_token_ids=[..._.output_token_ids,n],_.model_input_ids=new Tensor("int64",[BigInt(n)],[1,1])}class PreTrainedModel extends Callable{constructor(o,u){super();le(this,"main_input_name","input_ids");this.config=o,this.session=u;const l=MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor),d=MODEL_TYPE_MAPPING.get(l);this.can_generate=!1,this._runBeam=null,this._getStartBeams=null,this._updateBeam=null,this._forward=null,d===MODEL_TYPES.DecoderOnly?(this.can_generate=!0,this._runBeam=decoderRunBeam,this._getStartBeams=decoderStartBeams,this._updateBeam=decoderUpdatebeam,this._forward=decoderForward):d===MODEL_TYPES.Seq2Seq||d===MODEL_TYPES.Vision2Seq?(this.can_generate=!0,this._runBeam=seq2seqRunBeam,this._getStartBeams=seq2seqStartBeams,this._updateBeam=seq2seqUpdatebeam,this._forward=seq2seqForward):d===MODEL_TYPES.EncoderDecoder?this._forward=encoderForward:this._forward=encoderForward}async dispose(){let o=[];for(let u of Object.keys(this)){let l=this[u];l instanceof InferenceSession&&o.push(l.handler.dispose())}return await Promise.all(o)}static async from_pretrained(o,{quantized:u=!0,progress_callback:l=null,config:d=null,cache_dir:s=null,local_files_only:p=!1,revision:f="main",model_file_name:c=null}={}){let a={quantized:u,progress_callback:l,config:d,cache_dir:s,local_files_only:p,revision:f,model_file_name:c};const t=MODEL_CLASS_TO_NAME_MAPPING.get(this),e=MODEL_TYPE_MAPPING.get(t);let r;return e===MODEL_TYPES.DecoderOnly?r=await Promise.all([AutoConfig.from_pretrained(o,a),constructSession(o,a.model_file_name??"decoder_model_merged",a),getModelJSON(o,"generation_config.json",!1,a)]):e===MODEL_TYPES.Seq2Seq||e===MODEL_TYPES.Vision2Seq?r=await Promise.all([AutoConfig.from_pretrained(o,a),constructSession(o,"encoder_model",a),constructSession(o,"decoder_model_merged",a),getModelJSON(o,"generation_config.json",!1,a)]):e===MODEL_TYPES.EncoderDecoder?r=await Promise.all([AutoConfig.from_pretrained(o,a),constructSession(o,"encoder_model",a),constructSession(o,"decoder_model_merged",a)]):(e!==MODEL_TYPES.EncoderOnly&&console.warn(`Model type for '${t}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),r=await Promise.all([AutoConfig.from_pretrained(o,a),constructSession(o,a.model_file_name??"model",a)])),new this(...r)}async _call(o){return await this.forward(o)}async forward(o){return await this._forward(this,o)}_get_logits_processor(o,u,l=null){const d=new LogitsProcessorList;if(o.repetition_penalty!==null&&o.repetition_penalty!==1&&d.push(new RepetitionPenaltyLogitsProcessor(o.repetition_penalty)),o.no_repeat_ngram_size!==null&&o.no_repeat_ngram_size>0&&d.push(new NoRepeatNGramLogitsProcessor(o.no_repeat_ngram_size)),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(u,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 s=u>1||o.forced_bos_token_id===null?u:u+1;o.forced_decoder_ids!==null&&(s+=o.forced_decoder_ids[o.forced_decoder_ids.length-1][0]),d.push(new SuppressTokensAtBeginLogitsProcessor(o.begin_suppress_tokens,s))}return o.forced_decoder_ids!==null&&d.push(new ForceTokensLogitsProcessor(o.forced_decoder_ids)),l!==null&&d.extend(l),d}_get_generation_config(o){let u=new GenerationConfig(this.config);return"generation_config"in this&&Object.assign(u,this.generation_config),o!==null&&Object.assign(u,o),u}async generate(o,u=null,l=null,{inputs_attention_mask:d=null}={}){if(!this.can_generate){let m=`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&&(m+=` Please use the following class instead: '${y[0]}'`),Error(m)}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 s;if(this.config.is_encoder_decoder)s=0;else if(s=o instanceof Tensor?o.dims.at(-1):o.length,s===0)throw Error("Must supply a non-empty array of input token ids.");u=this._get_generation_config(u),l=l??new LogitsProcessorList,l=this._get_logits_processor(u,s,l);let p=u.eos_token_id;p!==null&&!Array.isArray(p)&&(p=[p]);let f=1;const c=f+(u.max_new_tokens??1/0),a=Number.isInteger(u.max_length)&&(u.max_new_tokens??null)===null;let t=Sampler.getSampler(u),e=this.getStartBeams(o,u,f,d);for(;e.some(g=>!g.done)&&f=u.max_length){m.done=!0,g.push(m);continue}let b=await this.runBeam(m);u.output_attentions&&this.addAttentionsToBeam(m,b),u.output_scores;let y=b.logits.slice(null,-1,null);l(m.output_token_ids,y);let w=t(y);for(let[T,S]of w){let A={...m};this.updateBeam(A,T),A.score+=S,p&&p.includes(T)&&(A.done=!0),g.push(A)}}++f,g=this.groupBeams(g).map(m=>m.sort((b,y)=>y.score-b.score).slice(0,u.num_beams)),e=g.flat(),u.callback_function&&u.callback_function(e)}const r=this.groupBeams(e),i=g=>r.map(m=>u.num_return_sequences>1?m.slice(0,u.num_return_sequences).map(b=>b[g]):[m[0][g]]).flat(),h=i("output_token_ids");if(u.return_dict_in_generate){const g=i("decoder_attentions"),m=i("cross_attentions");return{sequences:h,decoder_attentions:g,cross_attentions:m}}else return h}addAttentionsToBeam(o,u){if(this.config.is_encoder_decoder){if(!u.cross_attentions||u.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(u.cross_attentions)}if(!u.decoder_attentions||u.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(u.decoder_attentions)}groupBeams(o){const u=Object.create(null);for(const l of o)u[l.id]===void 0?u[l.id]=[l]:u[l.id].push(l);return Object.values(u)}getPastKeyValues(o,u){const l=Object.create(null);for(const d in o)if(d.startsWith("present")){let s=d.replace("present","past_key_values");u&&d.includes("encoder")?l[s]=u[s]:l[s]=o[d]}return l}getAttentions(o){const u=Object.create(null);for(const l of["cross_attentions","decoder_attentions"]){const d=[];for(const s in o)if(s.startsWith(l)){const p=s.split(".").pop();d[p]=o[s]}u[l]=d}return u}addPastKeyValues(o,u){if(u)Object.assign(o,u);else if(this.config.is_encoder_decoder&&(this.add_encoder_pkv??!0)){let l=[1,this.num_encoder_heads,0,this.encoder_dim_kv],d=[1,this.num_decoder_heads,0,this.decoder_dim_kv];for(let s=0;s{let t=Array.from({length:this.config.decoder_layers},(m,b)=>cat(a.map(y=>y[b]),2)),e=stack(u.map(([m,b])=>l?t[m].slice(null,b,null,[0,l]):t[m].slice(null,b)));e=e.transpose(1,0,2,3);let[r,i]=std_mean(e,-2,0,!0),h=e.clone();for(let m=0;me[b+1]-e[b]),h=mergeArrays([1],i).map(m=>!!m),g=[];for(let m=0;m=e&&(Array.from(A.data).filter(v=>v>=u).length>0||m>=t))break}const b=cat(i),{waveform:y}=await sessionRun(s.session,{spectrogram:b});return{spectrogram:b,waveform:y}}}class SpeechT5HifiGan extends PreTrainedModel{constructor(){super(...arguments);le(this,"main_input_name","spectrogram")}}class PretrainedMixin{static async from_pretrained(n,{quantized:o=!0,progress_callback:u=null,config:l=null,cache_dir:d=null,local_files_only:s=!1,revision:p="main",model_file_name:f=null}={}){let c={quantized:o,progress_callback:u,config:l,cache_dir:d,local_files_only:s,revision:p,model_file_name:f};if(l=await AutoConfig.from_pretrained(n,c),c.config||(c.config=l),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let a of this.MODEL_CLASS_MAPPINGS){const t=a.get(l.model_type);if(t)return await t[1].from_pretrained(n,c)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${l.model_type}", attempting to construct from base class.`),await PreTrainedModel.from_pretrained(n,c);throw Error(`Unsupported model type: ${l.model_type}`)}}le(PretrainedMixin,"MODEL_CLASS_MAPPINGS",null),le(PretrainedMixin,"BASE_IF_FAIL",!1);const MODEL_MAPPING_NAMES_ENCODER_ONLY=new Map([["bert",["BertModel",BertModel]],["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]],["clip",["CLIPModel",CLIPModel]],["mobilebert",["MobileBertModel",MobileBertModel]],["squeezebert",["SqueezeBertModel",SqueezeBertModel]],["wav2vec2",["Wav2Vec2Model",Wav2Vec2Model]],["wavlm",["WavLMModel",WavLMModel]],["detr",["DetrModel",DetrModel]],["vit",["ViTModel",ViTModel]],["mobilevit",["MobileViTModel",MobileViTModel]],["beit",["BeitModel",BeitModel]],["deit",["DeiTModel",DeiTModel]],["resnet",["ResNetModel",ResNetModel]],["swin",["SwinModel",SwinModel]],["donut-swin",["DonutSwinModel",DonutSwinModel]],["yolos",["YolosModel",YolosModel]],["hifigan",["SpeechT5HifiGan",SpeechT5HifiGan]],["sam",["SamModel",SamModel]]]),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]],["mpt",["MptModel",MptModel]],["opt",["OPTModel",OPTModel]]]),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_SEQUENCE_CLASSIFICATION_MAPPING_NAMES=new Map([["bert",["BertForSequenceClassification",BertForSequenceClassification]],["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]],["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]],["mpt",["MptForCausalLM",MptForCausalLM]],["opt",["OPTForCausalLM",OPTForCausalLM]],["mbart",["MBartForCausalLM",MBartForCausalLM]]]),MODEL_FOR_MASKED_LM_MAPPING_NAMES=new Map([["bert",["BertForMaskedLM",BertForMaskedLM]],["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]],["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]],["resnet",["ResNetForImageClassification",ResNetForImageClassification]],["swin",["SwinForImageClassification",SwinForImageClassification]]]),MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES=new Map([["detr",["DetrForObjectDetection",DetrForObjectDetection]],["yolos",["YolosForObjectDetection",YolosForObjectDetection]]]),MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES=new Map([["detr",["DetrForSegmentation",DetrForSegmentation]]]),MODEL_FOR_MASK_GENERATION_MAPPING_NAMES=new Map([["sam",["SamModel",SamModel]]]),MODEL_FOR_CTC_MAPPING_NAMES=new Map([["wav2vec2",["Wav2Vec2ForCTC",Wav2Vec2ForCTC]],["wavlm",["WavLMForCTC",WavLMForCTC]]]),MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Wav2Vec2ForSequenceClassification]],["wavlm",["WavLMForSequenceClassification",WavLMForSequenceClassification]]]),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_OBJECT_DETECTION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_MASK_GENERATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[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]];for(const[_,n]of MODEL_CLASS_TYPE_MAPPING)for(const[o,u]of _.values())MODEL_TYPE_MAPPING.set(o,n),MODEL_CLASS_TO_NAME_MAPPING.set(u,o),MODEL_NAME_TO_CLASS_MAPPING.set(o,u);const CUSTOM_MAPPING=[["CLIPTextModelWithProjection",CLIPTextModelWithProjection,MODEL_TYPES.EncoderOnly],["CLIPVisionModelWithProjection",CLIPVisionModelWithProjection,MODEL_TYPES.EncoderOnly]];for(const[_,n,o]of CUSTOM_MAPPING)MODEL_TYPE_MAPPING.set(_,o),MODEL_CLASS_TO_NAME_MAPPING.set(n,_),MODEL_NAME_TO_CLASS_MAPPING.set(_,n);class AutoModel extends PretrainedMixin{}le(AutoModel,"MODEL_CLASS_MAPPINGS",[MODEL_MAPPING_NAMES_ENCODER_ONLY,MODEL_MAPPING_NAMES_ENCODER_DECODER,MODEL_MAPPING_NAMES_DECODER_ONLY]),le(AutoModel,"BASE_IF_FAIL",!0);class AutoModelForSequenceClassification extends PretrainedMixin{}le(AutoModelForSequenceClassification,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]);class AutoModelForTokenClassification extends PretrainedMixin{}le(AutoModelForTokenClassification,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]);class AutoModelForSeq2SeqLM extends PretrainedMixin{}le(AutoModelForSeq2SeqLM,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]);class AutoModelForSpeechSeq2Seq extends PretrainedMixin{}le(AutoModelForSpeechSeq2Seq,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]);class AutoModelForTextToSpectrogram extends PretrainedMixin{}le(AutoModelForTextToSpectrogram,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]);class AutoModelForCausalLM extends PretrainedMixin{}le(AutoModelForCausalLM,"MODEL_CLASS_MAPPINGS",[MODEL_WITH_LM_HEAD_MAPPING_NAMES]);class AutoModelForMaskedLM extends PretrainedMixin{}le(AutoModelForMaskedLM,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_MASKED_LM_MAPPING_NAMES]);class AutoModelForQuestionAnswering extends PretrainedMixin{}le(AutoModelForQuestionAnswering,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]);class AutoModelForVision2Seq extends PretrainedMixin{}le(AutoModelForVision2Seq,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]);class AutoModelForImageClassification extends PretrainedMixin{}le(AutoModelForImageClassification,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]);class AutoModelForImageSegmentation extends PretrainedMixin{}le(AutoModelForImageSegmentation,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]);class AutoModelForObjectDetection extends PretrainedMixin{}le(AutoModelForObjectDetection,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]);class AutoModelForCTC extends PretrainedMixin{}le(AutoModelForCTC,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_CTC_MAPPING_NAMES]);class AutoModelForAudioClassification extends PretrainedMixin{}le(AutoModelForAudioClassification,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]);class AutoModelForDocumentQuestionAnswering extends PretrainedMixin{}le(AutoModelForDocumentQuestionAnswering,"MODEL_CLASS_MAPPINGS",[MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]);class Seq2SeqLMOutput extends ModelOutput{constructor({logits:n,past_key_values:o,encoder_outputs:u,decoder_attentions:l=null,cross_attentions:d=null}){super(),this.logits=n,this.past_key_values=o,this.encoder_outputs=u,this.decoder_attentions=l,this.cross_attentions=d}}class SequenceClassifierOutput extends ModelOutput{constructor({logits:n}){super(),this.logits=n}}class TokenClassifierOutput extends ModelOutput{constructor({logits:n}){super(),this.logits=n}}class MaskedLMOutput extends ModelOutput{constructor({logits:n}){super(),this.logits=n}}class QuestionAnsweringModelOutput extends ModelOutput{constructor({start_logits:n,end_logits:o}){super(),this.start_logits=n,this.end_logits=o}}class CausalLMOutput extends ModelOutput{constructor({logits:n}){super(),this.logits=n}}const BROWSER_ENV=typeof self<"u";let createCanvasFunction,ImageDataClass,loadImageFunction;if(BROWSER_ENV)createCanvasFunction=(_,n)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(_,n)},loadImageFunction=self.createImageBitmap,ImageDataClass=self.ImageData;else if(sharp)loadImageFunction=async _=>{const o=(await _.metadata()).channels;let{data:u,info:l}=await _.raw().toBuffer({resolveWithObject:!0});const d=new RawImage(new Uint8ClampedArray(u),l.width,l.height,l.channels);return o!==void 0&&o!==l.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"};class RawImage{constructor(n,o,u,l){le(this,"_CONTENT_TYPE_MAP",{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"});this.data=n,this.width=o,this.height=u,this.channels=l}static async read(n){if(n instanceof RawImage)return n;if(isString(n)||n instanceof URL)return await this.fromURL(n);throw new Error(`Unsupported input type: ${typeof n}`)}static async fromURL(n){let o=await getFile(n);if(o.status!==200)throw new Error(`Unable to read image from "${n}" (${o.status} ${o.statusText})`);let u=await o.blob();return this.fromBlob(u)}static async fromBlob(n){if(BROWSER_ENV){let o=await loadImageFunction(n);const u=createCanvasFunction(o.width,o.height).getContext("2d");return u.drawImage(o,0,0),new this(u.getImageData(0,0,o.width,o.height).data,o.width,o.height,4)}else{let o=sharp(await n.arrayBuffer());return await loadImageFunction(o)}}grayscale(){if(this.channels===1)return this;let n=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let o=0,u=0;o=0?f=u:a=-u,l>=0?c=l:t=-l,p.drawImage(s,f,c,n,o,a,t,n,o),new RawImage(p.getImageData(0,0,n,o).data,n,o,4).convert(d)}else{let d=this.toSharp();if(u>=0&&l>=0)d=d.extract({left:Math.floor(u),top:Math.floor(l),width:n,height:o});else if(u<=0&&l<=0){let s=Math.floor(-l),p=Math.floor(-u);d=d.extend({top:s,left:p,right:n-this.width-p,bottom:o-this.height-s})}else{let s=[0,0],p=0;l<0?(s[0]=Math.floor(-l),s[1]=o-this.height-s[0]):p=Math.floor(l);let f=[0,0],c=0;u<0?(f[0]=Math.floor(-u),f[1]=n-this.width-f[0]):c=Math.floor(u),d=d.extend({top:s[0],bottom:s[1],left:f[0],right:f[1]}).extract({left:c,top:p,width:n,height:o})}return await loadImageFunction(d)}}toCanvas(){if(!BROWSER_ENV)throw new Error("toCanvas() is only supported in browser environments.");let n=this.clone().rgba(),o=createCanvasFunction(n.width,n.height),u=new ImageDataClass(n.data,n.width,n.height);return o.getContext("2d").putImageData(u,0,0),o}_update(n,o,u,l=null){return this.data=n,this.width=o,this.height=u,l!==null&&(this.channels=l),this}clone(){return new RawImage(this.data.slice(),this.width,this.height,this.channels)}convert(n){if(this.channels===n)return this;switch(n){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}save(n){if(BROWSER_ENV){const o=n.split(".").pop().toLowerCase(),u=this._CONTENT_TYPE_MAP[o]??"image/png",d=this.toCanvas().toDataURL(u),s=document.createElement("a");s.href=d,s.download=n,s.click(),s.remove()}else if(env.useFS)this.toSharp().toFile(n);else 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(_,n){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(_)).arrayBuffer(),u=new AudioContext({sampleRate:n});typeof n>"u"&&console.warn(`No sampling rate provided, using default of ${u.sampleRate}Hz.`);const l=await u.decodeAudioData(o);let d;if(l.numberOfChannels===2){const s=Math.sqrt(2);let p=l.getChannelData(0),f=l.getChannelData(1);d=new Float32Array(p.length);for(let c=0;c=i?e[b]=r*Math.exp(h*(y-i)):e[b]=a+t*y,g[b]=d.map(w=>e[b]-w)}const m=e.slice(1).map((b,y)=>1/(b-e[y]));for(let b=0;bn){let y=r[i].data;y=center_to_corners_format(y),a!==null&&(y=y.map((w,T)=>w*a[(T+1)%2])),t.boxes.push(y),t.classes.push(g),t.scores.push(b)}}f.push(t)}return f}class FeatureExtractor extends Callable{constructor(n){super(),this.config=n}}class ImageFeatureExtractor extends FeatureExtractor{constructor(n){super(n),this.image_mean=this.config.image_mean,this.image_std=this.config.image_std,this.resample=this.config.resample??2,this.do_rescale=this.config.do_rescale??!0,this.rescale_factor=this.config.rescale_factor??1/255,this.do_normalize=this.config.do_normalize,this.do_resize=this.config.do_resize,this.do_thumbnail=this.config.do_thumbnail,this.size=this.config.size,this.do_center_crop=this.config.do_center_crop,this.crop_size=this.config.crop_size,this.do_convert_rgb=this.config.do_convert_rgb??!0,this.pad_size=this.config.pad_size,this.do_pad=this.config.do_pad,this.do_pad&&!this.pad_size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size)}async thumbnail(n,o,u=2){const l=n.height,d=n.width,s=o.height,p=o.width;let f=Math.min(l,s),c=Math.min(d,p);return f===l&&c===d?n:(l>d?c=Math.floor(d*f/l):d>l&&(f=Math.floor(l*c/d)),await n.resize(c,f,{resample:u}))}async preprocess(n){this.do_convert_rgb&&(n=n.rgb());const o=n.width,u=n.height;if(this.do_resize){let c,a;if(this.do_thumbnail){const{height:t,width:e}=this.size;c=Math.min(t,e)}else Number.isInteger(this.size)?(c=this.size,a=this.config.max_size??c):(c=this.size.shortest_edge,a=this.size.longest_edge);if(c!==void 0||a!==void 0){const t=c===void 0?1:Math.max(c/o,c/u),e=o*t,r=u*t,i=a===void 0?1:Math.min(a/e,a/r),h=Math.floor(Number((e*i).toFixed(2))),g=Math.floor(Number((r*i).toFixed(2)));n=await n.resize(h,g,{resample:this.resample})}else if(this.size.width!==void 0&&this.size.height!==void 0)n=await n.resize(this.size.width,this.size.height,{resample:this.resample});else throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(this.size)}`)}if(this.do_thumbnail&&(n=await this.thumbnail(n,this.size,this.resample)),this.do_center_crop){let c,a;Number.isInteger(this.crop_size)?(c=this.crop_size,a=this.crop_size):(c=this.crop_size.width,a=this.crop_size.height),n=await n.center_crop(c,a)}let l=[n.height,n.width];if(this.do_pad&&this.pad_size){let c=0,a=this.pad_size.width-n.width,t=0,e=this.pad_size.height-n.height;n=await n.pad([c,a,t,e])}const d=Float32Array.from(n.data);if(this.do_rescale)for(let c=0;cthis.preprocess(d)));return u.forEach(d=>d.pixel_values.dims=[1,...d.pixel_values.dims]),{pixel_values:cat(u.map(d=>d.pixel_values)),original_sizes:u.map(d=>d.original_size),reshaped_input_sizes:u.map(d=>d.reshaped_input_size)}}}class ConvNextFeatureExtractor extends ImageFeatureExtractor{}class ViTFeatureExtractor extends ImageFeatureExtractor{}class MobileViTFeatureExtractor extends ImageFeatureExtractor{}class DeiTFeatureExtractor extends ImageFeatureExtractor{}class BeitFeatureExtractor extends ImageFeatureExtractor{}class DonutFeatureExtractor extends ImageFeatureExtractor{}class DetrFeatureExtractor extends ImageFeatureExtractor{async _call(n){const o=await super._call(n),u=[o.pixel_values.dims[0],64,64],l=new Tensor("int64",new BigInt64Array(u.reduce((d,s)=>d*s)).fill(1n),u);return{...o,pixel_mask:l}}post_process_object_detection(...n){return post_process_object_detection(...n)}remove_low_and_no_objects(n,o,u,l){let d=[],s=[],p=[];for(let f=0;fu&&(d.push(a),s.push(r),p.push(t))}return[d,s,p]}check_segment_validity(n,o,u,l=.5,d=.8){let s=[],p=0,f=0;for(let a=0;a=l&&++f;let c=p>0&&f>0;return c&&(c=p/f>d),[c,s]}compute_segments(n,o,u,l,d,s=null,p=null){let[f,c]=p??n[0].dims,a=new Tensor("int32",new Int32Array(f*c),[f,c]),t=[];if(p!==null)for(let h=0;hr[m]&&(e[m]=h,r[m]=n[h].data[m])}let i=0;for(let h=0;hBigInt(Math.round(f)))),s);return{pixel_values:u,original_sizes:l,reshaped_input_sizes:d,input_points:p}}post_process_masks(n,o,u,{mask_threshold:l=0,binarize:d=!0,pad_size:s=null}={}){let p=[];s=s??this.pad_size;let f=[s.height,s.width];for(let c=0;cb>l),m.dims)),m.dims=[1,...m.dims],r.push(m)}let i=cat(r);p.push(i)}return p}}class WhisperFeatureExtractor extends FeatureExtractor{constructor(n){var o;super(n),(o=this.config).mel_filters??(o.mel_filters=getMelFilters(this.config.sampling_rate,this.config.n_fft,this.config.feature_size))}calcOffset(n,o){return Math.abs((n+o)%(2*o)-o)}padReflect(n,o,u){const l=new Float32Array(n.length+o+u),d=n.length-1;for(let s=0;s>1;++T){const S=(T+1-u)**2/2,A=Math.sqrt(m**2+b**2)**S,O=S*Math.atan2(b,m);let v=2*T;c[v]=A*Math.cos(O),c[v+1]=A*Math.sin(O),a[v]=c[v],a[v+1]=-c[v+1]}const y=c.subarray(l,d),w=new FFT(s>>1);w.transform(r,a);for(let T=0;T>1,F=S[M]*o[M];t[O]=F*y[O],t[v]=F*y[v]}w.transform(i,t);for(let O=0;Ol?s-l:0,c=s>1,c=new Float32Array(p*f);for(let m=0;mthis.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`.");let o=n.slice(0,this.config.n_samples),u=this._extract_fbank_features(o);return{input_features:new Tensor("float32",u.data,[1,...u.dims])}}}class Wav2Vec2FeatureExtractor extends FeatureExtractor{_zero_mean_unit_var_norm(n){const u=n.reduce((d,s)=>d+s,0)/n.length,l=n.reduce((d,s)=>d+(s-u)**2,0)/n.length;return n.map(d=>(d-u)/Math.sqrt(l+1e-7))}async _call(n){var l;if(!(n instanceof Float32Array||n instanceof Float64Array))throw new Error(`Wav2Vec2FeatureExtractor expects input to be a Float32Array or a Float64Array, but got ${((l=n==null?void 0:n.constructor)==null?void 0:l.name)??typeof n} 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.`);n instanceof Float64Array&&(n=new Float32Array(n));let o=n;this.config.do_normalize&&(o=this._zero_mean_unit_var_norm(o));const u=[1,o.length];return{input_values:new Tensor("float32",o,u),attention_mask:new Tensor("int64",new BigInt64Array(o.length).fill(1n),u)}}}class SpeechT5FeatureExtractor extends FeatureExtractor{}class Processor extends Callable{constructor(n){super(),this.feature_extractor=n}async _call(n,...o){return await this.feature_extractor(n)}}class SamProcessor extends Processor{async _call(n,o){return await this.feature_extractor(n,o)}post_process_masks(...n){return this.feature_extractor.post_process_masks(...n)}}class WhisperProcessor extends Processor{async _call(n){return await this.feature_extractor(n)}}class Wav2Vec2ProcessorWithLM extends Processor{async _call(n){return await this.feature_extractor(n)}}class SpeechT5Processor extends Processor{async _call(n){return await this.feature_extractor(n)}}class AutoProcessor{static async from_pretrained(n,{progress_callback:o=null,config:u=null,cache_dir:l=null,local_files_only:d=!1,revision:s="main"}={}){let p=u??await getModelJSON(n,"preprocessor_config.json",!0,{progress_callback:o,config:u,cache_dir:l,local_files_only:d,revision:s}),f=p.feature_extractor_type??p.image_processor_type,c=this.FEATURE_EXTRACTOR_CLASS_MAPPING[f];if(!c)if(p.size!==void 0)console.warn(`Feature extractor type "${f}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),c=ImageFeatureExtractor;else throw new Error(`Unknown Feature Extractor type: ${f}`);let a=this.PROCESSOR_CLASS_MAPPING[p.processor_class]??Processor,t=new c(p);return new a(t)}}le(AutoProcessor,"FEATURE_EXTRACTOR_CLASS_MAPPING",{WhisperFeatureExtractor,ViTFeatureExtractor,MobileViTFeatureExtractor,ConvNextFeatureExtractor,BeitFeatureExtractor,DeiTFeatureExtractor,DetrFeatureExtractor,YolosFeatureExtractor,DonutFeatureExtractor,SamImageProcessor,Wav2Vec2FeatureExtractor,SpeechT5FeatureExtractor}),le(AutoProcessor,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor,Wav2Vec2ProcessorWithLM,SamProcessor,SpeechT5Processor});async function prepareImages(_){return Array.isArray(_)||(_=[_]),_=await Promise.all(_.map(n=>RawImage.read(n))),_}class Pipeline extends Callable{constructor({task:n,model:o,tokenizer:u=null,processor:l=null}){super(),this.task=n,this.model=o,this.tokenizer=u,this.processor=l}async dispose(){await this.model.dispose()}async _call(n,...o){let u=this.tokenizer(n,{padding:!0,truncation:!0}),l=await this.model(u);return[u,l]}}class TextClassificationPipeline extends Pipeline{async _call(n,{topk:o=1}={}){let u=this.model.config.problem_type==="multi_label_classification"?f=>f.sigmoid().data:f=>softmax(f.data),[l,d]=await super._call(n),s=this.model.config.id2label,p=[];for(let f of d.logits){let c=u(f),t=getTopItems(c,o).map(function(e){return{label:s[e[0]],score:e[1]}});o===1?p.push(...t):p.push(t)}return Array.isArray(n)||o===1?p:p[0]}}class TokenClassificationPipeline extends Pipeline{async _call(n,{ignore_labels:o=["O"]}={}){let u=Array.isArray(n);u||(n=[n]);let l=this.tokenizer,[d,s]=await super._call(n),p=s.logits,f=this.model.config.id2label,c=[];for(let a=0;a[r,i]).filter(r=>r[1]>c),t=Array.from(softmax(d.end_logits[p].data)).map((r,i)=>[r,i]).filter(r=>r[1]>c),e=product(a,t).filter(r=>r[0][1]<=r[1][1]).map(r=>[r[0][1],r[1][1],r[0][0]*r[1][0]]).sort((r,i)=>i[2]-r[2]);for(let r=0;r{let i=[...f];return i[c]=r[0],{score:r[1],token:r[0],token_str:d.model.vocab[r[0]],sequence:d.decode(i,{skip_special_tokens:!0})}}))}return Array.isArray(n)?s:s[0]}}class Text2TextGenerationPipeline extends Pipeline{constructor(){super(...arguments);le(this,"_key",null)}async _call(o,u={}){Array.isArray(o)||(o=[o]),this.model.config.prefix&&(o=o.map(c=>this.model.config.prefix+c));let l=this.model.config.task_specific_params;l&&l[this.task]&&l[this.task].prefix&&(o=o.map(c=>l[this.task].prefix+c));let d={padding:!0,truncation:!0},s;this instanceof TranslationPipeline&&"_build_translation_inputs"in this.tokenizer?s=this.tokenizer._build_translation_inputs(o,d,u).input_ids:s=this.tokenizer(o,d).input_ids;let p=await this.model.generate(s,u),f=this.tokenizer.batch_decode(p,{skip_special_tokens:!0});return this._key!==null&&(f=f.map(c=>this._key===null?c:{[this._key]:c})),f}}class SummarizationPipeline extends Text2TextGenerationPipeline{constructor(){super(...arguments);le(this,"_key","summary_text")}}class TranslationPipeline extends Text2TextGenerationPipeline{constructor(){super(...arguments);le(this,"_key","translation_text")}}class TextGenerationPipeline extends Pipeline{async _call(n,o={}){let u=typeof n=="string"||n instanceof String;u&&(n=[n]),this.tokenizer.padding_side="left";let l=this.tokenizer(n,{padding:!0,truncation:!0}),d=l.input_ids,s=l.attention_mask,p=await this.model.generate(d,o,null,{inputs_attention_mask:s});const f=this.tokenizer.batch_decode(p,{skip_special_tokens:!0}),c=Array.from({length:n.length},a=>[]);for(let a=0;a[o.toLowerCase(),u])),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(n,o,{hypothesis_template:u="This example is {}.",multi_label:l=!1}={}){let d=Array.isArray(n);d||(n=[n]),Array.isArray(o)||(o=[o]);let s=o.map(c=>u.replace("{}",c)),p=l||o.length===1,f=[];for(let c of n){let a=[];for(let r of s){let i=this.tokenizer(c,{text_pair:r,padding:!0,truncation:!0}),h=await this.model(i);p?a.push([h.logits.data[this.contradiction_id],h.logits.data[this.entailment_id]]):a.push(h.logits.data[this.entailment_id])}let t;p?t=a.map(r=>softmax(r)[1]):t=softmax(a);let e=t.map((r,i)=>[r,i]).sort((r,i)=>i[0]-r[0]);f.push({sequence:c,labels:e.map(r=>o[r[1]]),scores:e.map(r=>r[0])})}return d?f:f[0]}}class FeatureExtractionPipeline extends Pipeline{async _call(n,{pooling:o="none",normalize:u=!1}={}){let[l,d]=await super._call(n),s=d.last_hidden_state??d.logits;if(o!=="none")if(o==="mean")s=mean_pooling(s,l.attention_mask);else throw Error(`Pooling method '${o}' not supported.`);return u&&(s=s.normalize(2,-1)),s}}class AudioClassificationPipeline extends Pipeline{constructor(n){super(n)}async _preprocess(n,o){return isString(n)&&(n=await read_audio(n,o)),n}async _call(n,{topk:o=5}={}){let u=!Array.isArray(n);u&&(n=[n]);const l=this.model.config.id2label,d=this.processor.feature_extractor.config.sampling_rate;let s=[];for(let p of n){p=await this._preprocess(p,d);const f=await this.processor(p),a=(await this.model(f)).logits[0];let e=getTopItems(softmax(a.data),o).map(function(r){return{label:l[r[0]],score:r[1]}});o===1?s.push(...e):s.push(e)}return!u||o===1?s:s[0]}}class AutomaticSpeechRecognitionPipeline extends Pipeline{constructor(n){super(n)}async _preprocess(n,o){return isString(n)&&(n=await read_audio(n,o)),n}async _call(n,o={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(n,o);case"wav2vec2":return this._call_wav2vec2(n,o);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(n,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".');let u=!Array.isArray(n);u&&(n=[n]);const l=this.processor.feature_extractor.config.sampling_rate;let d=[];for(let s of n){s=await this._preprocess(s,l);const p=await this.processor(s),c=(await this.model(p)).logits[0],a=[];for(let e of c)a.push(max(e.data)[1]);const t=this.tokenizer.decode(a);d.push({text:t})}return u?d[0]:d}async _call_whisper(n,o={}){let u=o.return_timestamps??!1,l=o.chunk_length_s??0,d=o.stride_length_s??null,s=o.chunk_callback??null,p=o.force_full_sequences??!1;u==="word"&&(o.return_token_timestamps=!0);let f=pop(o,"language",null),c=pop(o,"task",null);if(f||c||u){if(o.forced_decoder_ids)throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.");let h=this.tokenizer.get_decoder_prompt_ids({language:f,task:c,no_timestamps:!u});h.length>0&&(o.forced_decoder_ids=h)}let a=!Array.isArray(n);a&&(n=[n]);const t=this.processor.feature_extractor.config.sampling_rate,e=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,r=this.processor.feature_extractor.config.hop_length;let i=[];for(let h of n){h=await this._preprocess(h,t);let g=[];if(l>0){if(d===null)d=l/6;else if(l<=d)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const y=t*l,w=t*d,T=y-2*w;let S=0;for(;S=h.length;g.push({stride:[A.length,v?0:w,M?0:w],input_features:O.input_features,is_last:M}),S+=T}}else g=[{stride:[h.length,0,0],input_features:(await this.processor(h)).input_features,is_last:!0}];for(let y of g){o.num_frames=Math.floor(y.stride[0]/r);let w=await this.model.generate(y.input_features,o);u==="word"?(y.tokens=w.sequences[0],y.token_timestamps=w.token_timestamps.tolist()[0].map(T=>round(T,2))):y.tokens=w[0],y.stride=y.stride.map(T=>T/t),s!==null&&s(y)}let[m,b]=this.tokenizer._decode_asr(g,{time_precision:e,return_timestamps:u,force_full_sequences:p});i.push({text:m,...b})}return a?i[0]:i}}class ImageToTextPipeline extends Pipeline{constructor(n){super(n)}async _call(n,o={}){let u=Array.isArray(n);n=await prepareImages(n);let{pixel_values:l}=await this.processor(n),d=[];for(let s of l){s.dims=[1,...s.dims];let p=await this.model.generate(s,o),f=this.tokenizer.batch_decode(p,{skip_special_tokens:!0}).map(c=>({generated_text:c.trim()}));d.push(f)}return u?d:d[0]}}class ImageClassificationPipeline extends Pipeline{constructor(n){super(n)}async _call(n,{topk:o=1}={}){let u=Array.isArray(n);n=await prepareImages(n);let{pixel_values:l}=await this.processor(n),d=await this.model({pixel_values:l}),s=this.model.config.id2label,p=[];for(let f of d.logits){let a=getTopItems(softmax(f.data),o).map(function(t){return{label:s[t[0]],score:t[1]}});o===1?p.push(...a):p.push(a)}return u||o===1?p:p[0]}}class ImageSegmentationPipeline extends Pipeline{constructor(n){super(n),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(n,{threshold:o=.5,mask_threshold:u=.5,overlap_mask_area_threshold:l=.8,label_ids_to_fuse:d=null,target_sizes:s=null,subtask:p=null}={}){if(Array.isArray(n)&&n.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");n=await prepareImages(n);let c=n.map(h=>[h.height,h.width]),{pixel_values:a,pixel_mask:t}=await this.processor(n),e=await this.model({pixel_values:a,pixel_mask:t}),r=null;if(p!==null)r=this.subtasks_mapping[p];else for(let[h,g]of Object.entries(this.subtasks_mapping))if(g in this.processor.feature_extractor){r=this.processor.feature_extractor[g].bind(this.processor.feature_extractor),p=h;break}let i=[];if(p==="panoptic"||p==="instance"){let h=r(e,o,u,l,d,s??c)[0],g=h.segmentation,m=this.model.config.id2label;for(let b of h.segments_info){let y=new Uint8ClampedArray(g.data.length);for(let T=0;Tu.replace("{}",a)),s=this.tokenizer(d,{padding:!0,truncation:!0}),{pixel_values:p}=await this.processor(n),f=await this.model({...s,pixel_values:p}),c=[];for(let a of f.logits_per_image){let t=softmax(a.data);c.push([...t].map((e,r)=>({score:e,label:o[r]})))}return l?c:c[0]}}class ObjectDetectionPipeline extends Pipeline{constructor(n){super(n)}async _call(n,{threshold:o=.9,percentage:u=!1}={}){let l=Array.isArray(n);if(l&&n.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");n=await prepareImages(n);let d=u?null:n.map(e=>[e.height,e.width]),{pixel_values:s,pixel_mask:p}=await this.processor(n),f=await this.model({pixel_values:s,pixel_mask:p}),c=this.processor.feature_extractor.post_process_object_detection(f,o,d),a=this.model.config.id2label;const t=c.map(e=>e.boxes.map((r,i)=>({score:e.scores[i],label:a[e.classes[i]],box:this._get_bounding_box(r,!u)})));return l?t:t[0]}_get_bounding_box(n,o){o&&(n=n.map(p=>p|0));const[u,l,d,s]=n;return{xmin:u,ymin:l,xmax:d,ymax:s}}}class DocumentQuestionAnsweringPipeline extends Pipeline{constructor(n){super(n)}async _call(n,o,u={}){n=(await prepareImages(n))[0];const{pixel_values:l}=await this.processor(n),d=`${o}`,s=this.tokenizer(d,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,p=await this.model.generate(l,{...u,decoder_input_ids:s,max_length:this.model.config.decoder.max_position_embeddings}),c=this.tokenizer.batch_decode(p)[0].match(/(.*?)<\/s_answer>/);let a=null;return c&&c.length>=2&&(a=c[1].trim()),[{answer:a}]}}class TextToAudioPipeline extends Pipeline{constructor(o){super(o);le(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=o.vocoder??null}async _call(o,{speaker_embeddings:u=null}={}){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 u=="string"||u instanceof URL)&&(u=new Float32Array(await(await fetch(u)).arrayBuffer())),u instanceof Float32Array)u=new Tensor("float32",u,[1,u.length]);else if(!(u instanceof Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:l}=this.tokenizer(o,{padding:!0,truncation:!0}),{waveform:d}=await this.model.generate_speech(l,u,{vocoder:this.vocoder}),s=this.processor.feature_extractor.config.sampling_rate;return{audio:d.data,sampling_rate:s}}}const SUPPORTED_TASKS={"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"},"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:[AutoModelForTextToSpectrogram],processor:AutoProcessor,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,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"},"document-question-answering":{tokenizer:AutoTokenizer,pipeline:DocumentQuestionAnsweringPipeline,model:AutoModelForDocumentQuestionAnswering,processor:AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"feature-extraction":{tokenizer:AutoTokenizer,pipeline:FeatureExtractionPipeline,model:AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"}},TASK_ALIASES={"sentiment-analysis":"text-classification",ner:"token-classification",vqa:"visual-question-answering",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"};async function pipeline(_,n=null,{quantized:o=!0,progress_callback:u=null,config:l=null,cache_dir:d=null,local_files_only:s=!1,revision:p="main"}={}){_=TASK_ALIASES[_]??_;let f=SUPPORTED_TASKS[_.split("_",1)[0]];if(!f)throw Error(`Unsupported pipeline: ${_}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`);n||(n=f.default.model,console.log(`No model specified. Using default model: "${n}".`));let c={quantized:o,progress_callback:u,config:l,cache_dir:d,local_files_only:s,revision:p};const a=new Map([["tokenizer",f.tokenizer],["model",f.model],["processor",f.processor]]);let t=await loadItems(a,n,c);t.task=_,dispatchCallback(u,{status:"ready",task:_,model:n});let e=f.pipeline;return new e(t)}async function loadItems(_,n,o){const u=Object.create(null),l=[];for(let[d,s]of _.entries()){if(!s)continue;let p;Array.isArray(s)?p=new Promise(async(f,c)=>{let a;for(let t of s)try{f(await t.from_pretrained(n,o));return}catch(e){a=e}c(a)}):p=s.from_pretrained(n,o),u[d]=p,l.push(p)}await Promise.all(l);for(let[d,s]of Object.entries(u))u[d]=await s;return u}env.allowLocalModels=!1;class PipelineFactory{constructor(n,o,u){this.tokenizer=n,this.model=o,this.quantized=u}static async getInstance(n=null){return this.instance===null&&(this.instance=pipeline(this.task,this.model,{quantized:this.quantized,progress_callback:n,revision:this.model.includes("/whisper-medium")?"no_attentions":"main"})),this.instance}}le(PipelineFactory,"task",null),le(PipelineFactory,"model",null),le(PipelineFactory,"quantized",null),le(PipelineFactory,"instance",null),self.addEventListener("message",async _=>{const n=_.data;let o=await transcribe(n.audio,n.model,n.multilingual,n.quantized,n.subtask,n.language);o!==null&&self.postMessage({status:"complete",task:"automatic-speech-recognition",data:o})});class AutomaticSpeechRecognitionPipelineFactory extends PipelineFactory{}le(AutomaticSpeechRecognitionPipelineFactory,"task","automatic-speech-recognition"),le(AutomaticSpeechRecognitionPipelineFactory,"model",null),le(AutomaticSpeechRecognitionPipelineFactory,"quantized",null);const transcribe=async(_,n,o,u,l,d)=>{const s=n.startsWith("distil-whisper/");let p=n;!s&&!o&&(p+=".en");const f=AutomaticSpeechRecognitionPipelineFactory;(f.model!==p||f.quantized!==u)&&(f.model=p,f.quantized=u,f.instance!==null&&((await f.getInstance()).dispose(),f.instance=null));let c=await f.getInstance(h=>{self.postMessage(h)});const a=c.processor.feature_extractor.config.chunk_length/c.model.config.max_source_positions;let t=[{tokens:[],finalised:!1}];function e(h){let g=t[t.length-1];Object.assign(g,h),g.finalised=!0,h.is_last||t.push({tokens:[],finalised:!1})}function r(h){let g=t[t.length-1];g.tokens=[...h[0].output_token_ids];let m=c.tokenizer._decode_asr(t,{time_precision:a,return_timestamps:!0,force_full_sequences:!1});self.postMessage({status:"update",task:"automatic-speech-recognition",data:m})}return await c(_,{top_k:0,do_sample:!1,chunk_length_s:s?20:30,stride_length_s:s?3:5,language:d,task:l,return_timestamps:!0,force_full_sequences:!1,callback_function:r,chunk_callback:e}).catch(h=>(self.postMessage({status:"error",task:"automatic-speech-recognition",data:h}),null))}})();