diff --git "a/assets/index-DsJJsoL4.js" "b/assets/index-DsJJsoL4.js" new file mode 100644--- /dev/null +++ "b/assets/index-DsJJsoL4.js" @@ -0,0 +1,1832 @@ +function __vite__mapDeps(indexes) { + if (!__vite__mapDeps.viteFileDeps) { + __vite__mapDeps.viteFileDeps = [] + } + return indexes.map((i) => __vite__mapDeps.viteFileDeps[i]) +} +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))i(u);new MutationObserver(u=>{for(const n of u)if(n.type==="childList")for(const s of n.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&i(s)}).observe(document,{childList:!0,subtree:!0});function o(u){const n={};return u.integrity&&(n.integrity=u.integrity),u.referrerPolicy&&(n.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?n.credentials="include":u.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function i(u){if(u.ep)return;u.ep=!0;const n=o(u);fetch(u.href,n)}})();function dispatchCallback(t,e){t&&t(e)}function reverseDictionary(t){return Object.fromEntries(Object.entries(t).map(([e,o])=>[o,e]))}const Callable=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function isTypedArray(t){return t?.prototype?.__proto__?.constructor?.name==="TypedArray"}function isIntegralNumber(t){return Number.isInteger(t)||typeof t=="bigint"}function exists(t){return t!=null}function calculateDimensions(t){const e=[];let o=t;for(;Array.isArray(o);)e.push(o.length),o=o[0];return e}function mergeArrays(...t){return Array.prototype.concat.apply([],t)}function calculateReflectOffset(t,e){return Math.abs((t+e)%(2*e)-e)}const sharp={},ONNX_NODE=Object.freeze(Object.defineProperty({__proto__:null,default:sharp},Symbol.toStringTag,{value:"Module"})),VERSION="3.0.0-alpha.0",BROWSER_ENV$1=typeof self<"u",WEB_CACHE_AVAILABLE=BROWSER_ENV$1&&"caches"in self,FS_AVAILABLE=!isEmpty(sharp),PATH_AVAILABLE=!isEmpty(sharp),RUNNING_LOCALLY=FS_AVAILABLE&&PATH_AVAILABLE,__dirname$1=RUNNING_LOCALLY?sharp.dirname(sharp.dirname(sharp.fileURLToPath(import.meta.url))):"./",DEFAULT_CACHE_DIR=RUNNING_LOCALLY?sharp.join(__dirname$1,"/.cache/"):null,DEFAULT_LOCAL_MODEL_PATH="/models/",localModelPath=RUNNING_LOCALLY?sharp.join(__dirname$1,DEFAULT_LOCAL_MODEL_PATH):DEFAULT_LOCAL_MODEL_PATH,env={backends:{onnx:{},tfjs:{}},experimental:{useWebGPU:!1},__dirname:__dirname$1,version:VERSION,allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!BROWSER_ENV$1,localModelPath,useFS:FS_AVAILABLE,useBrowserCache:WEB_CACHE_AVAILABLE,useFSCache:FS_AVAILABLE,cacheDir:DEFAULT_CACHE_DIR,useCustomCache:!1,customCache:null};function isEmpty(t){return Object.keys(t).length===0}var define_process_env_default={};class FileResponse{_CONTENT_TYPE_MAP={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=sharp.existsSync(e),this.exists){this.status=200,this.statusText="OK";let o=sharp.statSync(e);this.headers.set("content-length",o.size.toString()),this.updateContentType();let i=this;this.body=new ReadableStream({start(u){i.arrayBuffer().then(n=>{u.enqueue(new Uint8Array(n)),u.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new FileResponse(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await sharp.promises.readFile(this.filePath)).buffer}async blob(){const e=await sharp.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await sharp.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function isValidHttpUrl(t,e=null){let o;try{o=new URL(t)}catch{return!1}return e&&!e.includes(o.hostname)?!1:o.protocol==="http:"||o.protocol==="https:"}async function getFile(t){if(env.useFS&&!isValidHttpUrl(t))return new FileResponse(t);if(typeof process<"u"&&process?.release?.name==="node"){const e=!!define_process_env_default?.TESTING_REMOTELY,o=env.version,i=new Headers;if(i.set("User-Agent",`transformers.js/${o}; is_ci/${e};`),isValidHttpUrl(t,["huggingface.co","hf.co"])){const n=define_process_env_default?.HF_TOKEN??define_process_env_default?.HF_ACCESS_TOKEN;n&&i.set("Authorization",`Bearer ${n}`)}return fetch(t,{headers:i})}else return fetch(t)}const ERROR_MAPPING={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function handleError(t,e,o){if(!o)return null;const i=ERROR_MAPPING[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${i}: "${e}".`)}class FileCache{constructor(e){this.path=e}async match(e){let o=sharp.join(this.path,e),i=new FileResponse(o);if(i.exists)return i}async put(e,o){const i=Buffer.from(await o.arrayBuffer());let u=sharp.join(this.path,e);try{await sharp.promises.mkdir(sharp.dirname(u),{recursive:!0}),await sharp.promises.writeFile(u,i)}catch(n){console.warn("An error occurred while writing the file to cache:",n)}}}async function tryCache(t,...e){for(let o of e)try{let i=await t.match(o);if(i)return i}catch{continue}}async function getModelFile(t,e,o=!0,i={}){if(!env.allowLocalModels&&i.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");dispatchCallback(i.progress_callback,{status:"initiate",name:t,file:e});let u;if(!u&&env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{u=await caches.open("transformers-cache")}catch(v){console.warn("An error occurred while opening the browser cache:",v)}}if(!u&&env.useFSCache&&(u=new FileCache(i.cache_dir??env.cacheDir)),!u&&env.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const n=i.revision??"main";let s=pathJoin(t,e),c=pathJoin(env.localModelPath,s),d=pathJoin(env.remoteHost,env.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),r=n==="main"?s:pathJoin(t,n,e),a,l=u instanceof FileCache?r:d,h=!1,f;u&&(f=await tryCache(u,c,l));const m=f!==void 0;if(f===void 0){if(env.allowLocalModels)if(isValidHttpUrl(s)){if(i.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${s}.`)}else try{f=await getFile(c),a=c}catch(T){console.warn(`Unable to load from local path "${c}": "${T}"`)}if(f===void 0||f.status===404){if(i.local_files_only||!env.allowRemoteModels){if(o)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${c}".`);return null}if(f=await getFile(d),f.status!==200)return handleError(f.status,d,o);a=l}h=u&&typeof Response<"u"&&f instanceof Response&&f.status===200}dispatchCallback(i.progress_callback,{status:"download",name:t,file:e});const g={status:"progress",name:t,file:e};let b;return i.progress_callback?m&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(b=new Uint8Array(await f.arrayBuffer()),dispatchCallback(i.progress_callback,{...g,progress:100,loaded:b.length,total:b.length})):b=await readResponse(f,v=>{dispatchCallback(i.progress_callback,{...g,...v})}):b=new Uint8Array(await f.arrayBuffer()),h&&a&&await u.match(a)===void 0&&await u.put(a,new Response(b,{headers:f.headers})).catch(v=>{console.warn(`Unable to add response to browser cache: ${v}.`)}),dispatchCallback(i.progress_callback,{status:"done",name:t,file:e}),b}async function getModelJSON(t,e,o=!0,i={}){let u=await getModelFile(t,e,o,i);if(u===null)return{};let s=new TextDecoder("utf-8").decode(u);return JSON.parse(s)}async function readResponse(t,e){const o=t.headers.get("Content-Length");o===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let i=parseInt(o??"0"),u=new Uint8Array(i),n=0;const s=t.body.getReader();async function c(){const{done:d,value:r}=await s.read();if(d)return;let a=n+r.length;if(a>i){i=a;let h=new Uint8Array(i);h.set(u),u=h}u.set(r,n),n=a;const l=n/i*100;return e({progress:l,loaded:n,total:i}),c()}return await c(),u}function pathJoin(...t){return t=t.map((e,o)=>(o&&(e=e.replace(new RegExp("^/"),"")),o!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function interpolate_data(t,[e,o,i],[u,n],s="bilinear",c=!1){const d=n/i,r=u/o,a=new t.constructor(u*n*e),l=o*i,h=u*n;for(let f=0;f=0;--c)u[c]=d,i[c]=e[o[c]],d*=i[c];const n=o.map((c,d)=>u[o.indexOf(d)]),s=new t.constructor(t.length);for(let c=0;c=0;--r)d+=a%e[r]*n[r],a=Math.floor(a/e[r]);s[d]=t[c]}return[s,i]}function softmax(t){const e=max(t)[0],o=t.map(n=>Math.exp(n-e)),i=o.reduce((n,s)=>n+s,0);return o.map(n=>n/i)}function log_softmax(t){return softmax(t).map(i=>Math.log(i))}function getTopItems(t,e=0){return t=Array.from(t).map((o,i)=>[i,o]).sort((o,i)=>i[1]-o[1]),e!==null&&e>0&&(t=t.slice(0,e)),t}function min(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],o=0;for(let i=1;ie&&(e=t[i],o=i);return[Number(e),o]}function isPowerOfTwo(t){return t>0&&(t&t-1)===0}class P2FFT{constructor(e){if(this.size=e|0,this.size<=1||!isPowerOfTwo(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let i=0;ii;i<<=1)++o;this._width=o%2===0?o-1:o,this._bitrev=new Int32Array(1<>>u&3)<>>1);for(let u=0;u>>1]=e[u];return i}toComplexArray(e,o){const i=o||this.createComplexArray();for(let u=0;u>>1],i[u+1]=0;return i}completeSpectrum(e){const o=this._csize,i=o>>>1;for(let u=2;u>=2;s>=2;s>>=2){c=u/s<<1;const l=c>>>2;for(d=0;d>>1,s>>>1)}else for(d=0,r=0;d>>1,s>>>1,i)}for(s>>=2;s>=2;s>>=2){c=u/s<<1;const l=c>>>2;for(d=0;d>1;++a){const l=(a+1-e)**2/2,h=Math.sqrt(d**2+r**2)**l,f=l*Math.atan2(r,d),m=2*a;n[m]=h*Math.cos(f),n[m+1]=h*Math.sin(f),s[m]=n[m],s[m+1]=-n[m+1]}this._slicedChirpBuffer=n.subarray(o,i),this._f=new P2FFT(u>>1),this._f.transform(this._chirpBuffer,s)}_transform(e,o,i){const u=this._buffer1,n=this._buffer2,s=this._outBuffer1,c=this._outBuffer2,d=this._chirpBuffer,r=this._slicedChirpBuffer,a=this._a;if(i)for(let l=0;l>1,m=o[f];u[l]=m*r[l],u[h]=m*r[h]}else for(let l=0;l=t.length&&(d=2*(t.length-1)-d),i[s++]=t[d]}i.sort(),o[n]=i[u]}return o}const scriptRel="modulepreload",assetsURL=function(t){return"/"+t},seen={},__vitePreload=function(e,o,i){let u=Promise.resolve();if(o&&o.length>0){const n=document.getElementsByTagName("link");u=Promise.all(o.map(s=>{if(s=assetsURL(s),s in seen)return;seen[s]=!0;const c=s.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(!!i)for(let l=n.length-1;l>=0;l--){const h=n[l];if(h.href===s&&(!c||h.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${s}"]${d}`))return;const a=document.createElement("link");if(a.rel=c?"stylesheet":scriptRel,c||(a.as="script",a.crossOrigin=""),a.href=s,document.head.appendChild(a),c)return new Promise((l,h)=>{a.addEventListener("load",l),a.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${s}`)))})}))}return u.then(()=>e()).catch(n=>{const s=new Event("vite:preloadError",{cancelable:!0});if(s.payload=n,window.dispatchEvent(s),!s.defaultPrevented)throw n})};/*! + * ONNX Runtime Web v1.17.1 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var vd=Object.create,En=Object.defineProperty,wd=Object.getOwnPropertyDescriptor,_d=Object.getOwnPropertyNames,Od=Object.getPrototypeOf,Id=Object.prototype.hasOwnProperty,L=(t,e)=>()=>(t&&(e=t(t=0)),e),me=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Pr=(t,e)=>{for(var o in e)En(t,o,{get:e[o],enumerable:!0})},Ha=(t,e,o,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let u of _d(e))!Id.call(t,u)&&u!==o&&En(t,u,{get:()=>e[u],enumerable:!(i=wd(e,u))||i.enumerable});return t},Er=(t,e,o)=>(o=t!=null?vd(Od(t)):{},Ha(e||!t||!t.__esModule?En(o,"default",{value:t,enumerable:!0}):o,t)),rr=t=>Ha(En({},"__esModule",{value:!0}),t),Dn,nr,or,Ln,Fn=L(()=>{Dn=new Map,nr=[],or=(t,e,o)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let i=Dn.get(t);if(i===void 0)Dn.set(t,{backend:e,priority:o});else{if(i.priority>o)return;if(i.priority===o&&i.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${o}`)}if(o>=0){let u=nr.indexOf(t);u!==-1&&nr.splice(u,1);for(let n=0;n{let e=t.length===0?nr:t,o=[];for(let i of e){let u=Dn.get(i);if(u){if(u.initialized)return u.backend;if(u.aborted)continue;let n=!!u.initPromise;try{return n||(u.initPromise=u.backend.init(i)),await u.initPromise,u.initialized=!0,u.backend}catch(s){n||o.push({name:i,err:s}),u.aborted=!0}finally{delete u.initPromise}}}throw new Error(`no available backend found. ERR: ${o.map(i=>`[${i.name}] ${i.err}`).join(", ")}`)}}),qa=L(()=>{Fn()}),ja,Ya=L(()=>{ja="1.17.1"}),Xa,ir,Ho=L(()=>{Ya(),Xa="warning",ir={wasm:{},webgl:{},webgpu:{},versions:{common:ja},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Xa=t}},get logLevel(){return Xa}},Object.defineProperty(ir,"logLevel",{enumerable:!0})}),Z,Ka=L(()=>{Ho(),Z=ir}),Ja,Za,Qa=L(()=>{Ja=(t,e)=>{let o=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);o.width=t.dims[3],o.height=t.dims[2];let i=o.getContext("2d");if(i!=null){let u,n;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(u=t.dims[2],n=t.dims[3]):(u=t.dims[3],n=t.dims[2]);let s=e?.format!==void 0?e.format:"RGB",c=e?.norm,d,r;c===void 0||c.mean===void 0?d=[255,255,255,255]:typeof c.mean=="number"?d=[c.mean,c.mean,c.mean,c.mean]:(d=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(d[3]=c.mean[3])),c===void 0||c.bias===void 0?r=[0,0,0,0]:typeof c.bias=="number"?r=[c.bias,c.bias,c.bias,c.bias]:(r=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(r[3]=c.bias[3]));let a=n*u,l=0,h=a,f=a*2,m=-1;s==="RGBA"?(l=0,h=a,f=a*2,m=a*3):s==="RGB"?(l=0,h=a,f=a*2):s==="RBG"&&(l=0,f=a,h=a*2);for(let g=0;g{let o=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(o!=null){let u,n,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(u=t.dims[2],n=t.dims[1],s=t.dims[3]):(u=t.dims[3],n=t.dims[2],s=t.dims[1]);let c=e!==void 0&&e.format!==void 0?e.format:"RGB",d=e?.norm,r,a;d===void 0||d.mean===void 0?r=[255,255,255,255]:typeof d.mean=="number"?r=[d.mean,d.mean,d.mean,d.mean]:(r=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(r[3]=d.mean[3])),d===void 0||d.bias===void 0?a=[0,0,0,0]:typeof d.bias=="number"?a=[d.bias,d.bias,d.bias,d.bias]:(a=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(a[3]=d.bias[3]));let l=n*u;if(e!==void 0&&(e.format!==void 0&&s===4&&e.format!=="RGBA"||s===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,f=0,m=1,g=2,b=3,v=0,T=l,E=l*2,M=-1;c==="RGBA"?(v=0,T=l,E=l*2,M=l*3):c==="RGB"?(v=0,T=l,E=l*2):c==="RBG"&&(v=0,E=l,T=l*2),i=o.createImageData(u,n);for(let F=0;F{$n(),qo=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:o,width:i}=e,u=e.norm??{mean:255,bias:0},n,s;typeof u.mean=="number"?n=[u.mean,u.mean,u.mean,u.mean]:n=[u.mean[0],u.mean[1],u.mean[2],u.mean[3]??255],typeof u.bias=="number"?s=[u.bias,u.bias,u.bias,u.bias]:s=[u.bias[0],u.bias[1],u.bias[2],u.bias[3]??0];let c=e.format!==void 0?e.format:"RGBA",d=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",r=o*i,a=d==="RGBA"?new Float32Array(r*4):new Float32Array(r*3),l=4,h=0,f=1,m=2,g=3,b=0,v=r,T=r*2,E=-1;c==="RGB"&&(l=3,h=0,f=1,m=2,g=-1),d==="RGBA"?E=r*3:d==="RBG"?(b=0,T=r,v=r*2):d==="BGR"&&(T=0,v=r,b=r*2);for(let M=0;M{let o=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,i=typeof ImageData<"u"&&t instanceof ImageData,u=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,n=typeof t=="string",s,c=e??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},r=a=>a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas?a.getContext("2d"):null;if(o){let a=d();a.width=t.width,a.height=t.height;let l=r(a);if(l!=null){let h=t.height,f=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(h=e.resizedHeight,f=e.resizedWidth),e!==void 0){if(c=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=h,c.width=f}else c.tensorFormat="RGBA",c.height=h,c.width=f;l.drawImage(t,0,0),s=l.getImageData(0,0,f,h).data}else throw new Error("Can not access image data")}else if(i){let a,l;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(a=e.resizedHeight,l=e.resizedWidth):(a=t.height,l=t.width),e!==void 0&&(c=e),c.format="RGBA",c.height=a,c.width=l,e!==void 0){let h=d();h.width=l,h.height=a;let f=r(h);if(f!=null)f.putImageData(t,0,0),s=f.getImageData(0,0,l,a).data;else throw new Error("Can not access image data")}else s=t.data}else if(u){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let a=d();a.width=t.width,a.height=t.height;let l=r(a);if(l!=null){let h=t.height,f=t.width;return l.drawImage(t,0,0,f,h),s=l.getImageData(0,0,f,h).data,c.height=h,c.width=f,qo(s,c)}else throw new Error("Can not access image data")}else{if(n)return new Promise((a,l)=>{let h=d(),f=r(h);if(!t||!f)return l();let m=new Image;m.crossOrigin="Anonymous",m.src=t,m.onload=()=>{h.width=m.width,h.height=m.height,f.drawImage(m,0,0,h.width,h.height);let g=f.getImageData(0,0,h.width,h.height);c.height=h.height,c.width=h.width,a(qo(g.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return qo(s,c);throw new Error("Input data provided is not supported - aborted tensor creation")},ts=(t,e)=>{let{width:o,height:i,download:u,dispose:n}=e,s=[1,i,o,4];return new Ye({location:"texture",type:"float32",texture:t,dims:s,download:u,dispose:n})},rs=(t,e)=>{let{dataType:o,dims:i,download:u,dispose:n}=e;return new Ye({location:"gpu-buffer",type:o??"float32",gpuBuffer:t,dims:i,download:u,dispose:n})},ns=(t,e,o)=>new Ye({location:"cpu-pinned",type:t,data:e,dims:o??[e.length]})}),Qr,Cn,is,as,ss=L(()=>{Qr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Cn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),is=!1,as=()=>{if(!is){is=!0;let t=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",e=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";t&&(Qr.set("int64",BigInt64Array),Cn.set(BigInt64Array,"int64")),e&&(Qr.set("uint64",BigUint64Array),Cn.set(BigUint64Array,"uint64"))}}}),us,ls,fs=L(()=>{$n(),us=t=>{let e=1;for(let o=0;o{switch(t.location){case"cpu":return new Ye(t.type,t.data,e);case"cpu-pinned":return new Ye({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Ye({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Ye({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Ye,$n=L(()=>{Qa(),os(),ss(),fs(),Ye=class{constructor(t,e,o){as();let i,u;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,i=t.type,u=t.dims,t.location){case"cpu-pinned":{let s=Qr.get(i);if(!s)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(t.data instanceof s))throw new TypeError(`buffer should be of type ${s.name}`);this.cpuData=t.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="bool")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let s,c;if(typeof t=="string")if(i=t,c=o,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");s=e}else{let d=Qr.get(t);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16")throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");t==="uint64"||t==="int64"?s=d.from(e,BigInt):s=d.from(e)}else if(e instanceof d)s=e;else throw new TypeError(`A ${i} tensor's data must be type of ${d}`)}else if(c=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof t[0];if(d==="string")i="string",s=t;else if(d==="boolean")i="bool",s=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else{let d=Cn.get(t.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);i=d,s=t}if(c===void 0)c=[s.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");u=c,this.cpuData=s,this.dataLocation="cpu"}let n=us(u);if(this.cpuData&&n!==this.cpuData.length)throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=u,this.size=n}static async fromImage(t,e){return es(t,e)}static fromTexture(t,e){return ts(t,e)}static fromGpuBuffer(t,e){return rs(t,e)}static fromPinnedBuffer(t,e,o){return ns(t,e,o)}toDataURL(t){return Ja(this,t)}toImageData(t){return Za(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return ls(this,t)}}}),Re,kn=L(()=>{$n(),Re=Ye}),cs,ps,ar,sr,jo=L(()=>{Ho(),cs=(t,e)=>{ir.wasm.trace&&console.timeStamp(`${t}::ORT::${e}`)},ps=(t,e)=>{let o=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let u=0;u{ir.wasm.trace&&ps("BEGIN",t)},sr=t=>{ir.wasm.trace&&ps("END",t)}}),Bn,ds=L(()=>{Fn(),kn(),jo(),Bn=class di{constructor(e){this.handler=e}async run(e,o,i){ar();let u={},n={};if(typeof e!="object"||e===null||e instanceof Re||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof o=="object"){if(o===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(o instanceof Re)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(o)){if(o.length===0)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let r of o){if(typeof r!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(r)===-1)throw new RangeError(`'fetches' contains invalid output name: ${r}.`);u[r]=null}if(typeof i=="object"&&i!==null)n=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let r=!1,a=Object.getOwnPropertyNames(o);for(let l of this.outputNames)if(a.indexOf(l)!==-1){let h=o[l];(h===null||h instanceof Re)&&(r=!0,s=!1,u[l]=h)}if(r){if(typeof i=="object"&&i!==null)n=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else n=o}}else if(typeof o<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let r of this.inputNames)if(typeof e[r]>"u")throw new Error(`input '${r}' is missing in 'feeds'.`);if(s)for(let r of this.outputNames)u[r]=null;let c=await this.handler.run(e,u,n),d={};for(let r in c)if(Object.hasOwnProperty.call(c,r)){let a=c[r];a instanceof Re?d[r]=a:d[r]=new Re(a.type,a.data,a.dims)}return sr(),d}async release(){return this.handler.dispose()}static async create(e,o,i,u){ar();let n,s={};if(typeof e=="string"){if(n=e,typeof o=="object"&&o!==null)s=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(n=e,typeof o=="object"&&o!==null)s=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let r=e,a=0,l=e.byteLength;if(typeof o=="object"&&o!==null)s=o;else if(typeof o=="number"){if(a=o,!Number.isSafeInteger(a))throw new RangeError("'byteOffset' must be an integer.");if(a<0||a>=r.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${r.byteLength}).`);if(l=e.byteLength-a,typeof i=="number"){if(l=i,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||a+l>r.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${r.byteLength-a}].`);if(typeof u=="object"&&u!==null)s=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof o<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(r,a,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let c=(s.executionProviders||[]).map(r=>typeof r=="string"?r:r.name),d=await(await Ln(c)).createInferenceSessionHandler(n,s);return sr(),new di(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),Sd,hs=L(()=>{ds(),Sd=Bn}),ms=L(()=>{}),Ad,Nn,bs=L(()=>{Fn(),kn(),Ad="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Nn=class fi{constructor(e,o,i){this.handler=e,this.hasOptimizerModel=o,this.hasEvalModel=i}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(e,o){let i=e.evalModel||"",u=e.optimizerModel||"",n=o||{},s=(n.executionProviders||[]).map(d=>typeof d=="string"?d:d.name),c=await Ln(s);if(c.createTrainingSessionHandler){let d=await c.createTrainingSessionHandler(e.checkpointState,e.trainModel,i,u,n);return new fi(d,!!e.optimizerModel,!!e.evalModel)}else throw new Error(Ad)}typeNarrowingForRunStep(e,o,i,u,n){let s={},c={};if(typeof i!="object"||i===null||i instanceof Re||Array.isArray(i))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof u=="object"){if(u===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(u instanceof Re)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(u)){if(u.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let r of u){if(typeof r!="string")throw new TypeError("'fetches' must be a string array or an object.");if(o.indexOf(r)===-1)throw new RangeError(`'fetches' contains invalid output name: ${r}.`);s[r]=null}if(typeof n=="object"&&n!==null)c=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let r=!1,a=Object.getOwnPropertyNames(u);for(let l of o)if(a.indexOf(l)!==-1){let h=u[l];(h===null||h instanceof Re)&&(r=!0,d=!1,s[l]=h)}if(r){if(typeof n=="object"&&n!==null)c=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else c=u}}else if(typeof u<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let r of e)if(typeof i[r]>"u")throw new Error(`input '${r}' is missing in 'feeds'.`);if(d)for(let r of o)s[r]=null;return[s,c]}convertHandlerReturnTypeToMapOfTensors(e){let o={};for(let i in e)if(Object.hasOwnProperty.call(e,i)){let u=e[i];u instanceof Re?o[i]=u:o[i]=new Re(u.type,u.data,u.dims)}return o}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,o,i){let[u,n]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,o,i),s=await this.handler.runTrainStep(e,u,n);return this.convertHandlerReturnTypeToMapOfTensors(s)}async runOptimizerStep(e){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(e||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(e,o,i){if(this.hasEvalModel){let[u,n]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,o,i),s=await this.handler.runEvalStep(e,u,n);return this.convertHandlerReturnTypeToMapOfTensors(s)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(e=!0){return this.handler.getParametersSize(e)}async loadParametersBuffer(e,o=!0){let i=await this.getParametersSize(o);if(e.length!==4*i)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,o)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}}),Pd,gs=L(()=>{bs(),Pd=Nn}),Yo={};Pr(Yo,{InferenceSession:()=>Sd,TRACE:()=>cs,TRACE_FUNC_BEGIN:()=>ar,TRACE_FUNC_END:()=>sr,Tensor:()=>Re,TrainingSession:()=>Pd,env:()=>Z,registerBackend:()=>or});var vt=L(()=>{qa(),Ka(),hs(),kn(),jo(),ms(),gs()});function jt(t,e,o,i){if(e===void 0)return Dd(t);if(o===void 0)Rn(t,e);else if(typeof o=="number"&&i===void 0)Rn(t,e);else if(typeof o=="string"&&i===void 0)Rn(t,o,1,e);else if(typeof o=="string"&&typeof i=="number")Rn(t,o,i,e);else throw new TypeError("input is valid")}function Dd(t){return{verbose:jt.verbose.bind(null,t),info:jt.info.bind(null,t),warning:jt.warning.bind(null,t),error:jt.error.bind(null,t),fatal:jt.fatal.bind(null,t)}}function Rn(t,e,o,i){let u=en[i||""]||en[""];Ts[t]{Xo=class{log(t,e,o){}},Ko=class{log(t,e,o){console.log(`${this.color(t)} ${o?"\x1B[35m"+o+"\x1B[0m ":""}${e}`)}color(t){switch(t){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${t}`)}}},Ts={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},Ed={none:new Xo,console:new Ko},xs={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1},en={"":xs},(t=>{function e(r,a){t("verbose",r,a)}t.verbose=e;function o(r,a){t("info",r,a)}t.info=o;function i(r,a){t("warning",r,a)}t.warning=i;function u(r,a){t("error",r,a)}t.error=u;function n(r,a){t("fatal",r,a)}t.fatal=n;function s(r){en={},c("",r||{})}t.reset=s;function c(r,a){if(r==="*")s(a);else{let l=en[r]||xs;en[r]={provider:a.provider||l.provider,minimalSeverity:a.minimalSeverity||l.minimalSeverity,logDateTime:a.logDateTime===void 0?l.logDateTime:a.logDateTime,logSourceLocation:a.logSourceLocation===void 0?l.logSourceLocation:a.logSourceLocation}}}t.set=c;function d(r){let a={};r.logLevel&&(a.minimalSeverity=r.logLevel),c("",a)}t.setWithEnv=d})(jt||={}),ce=jt,Gn=class{constructor(t,e,o,i,u,n){this.category=t,this.name=e,this.startTime=o,this.endCallback=i,this.timer=u,this.ctx=n}async end(){return this.endCallback(this)}async checkTimer(){if(this.ctx===void 0||this.timer===void 0)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}},Un=class{constructor(t,e,o,i){this.category=t,this.name=e,this.startTime=o,this.endTime=i}},zn=class{constructor(t,e,o){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=t===void 0?1e4:t,this._flushBatchSize=e===void 0?10:e,this._flushIntervalInMilliseconds=o===void 0?5e3:o}static create(t){return t===void 0?new this:new this(t.maxNumberEvents,t.flushBatchSize,t.flushIntervalInMilliseconds)}start(){this._started=!0,this._timingEvents=[],this._flushTime=Mn(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer{s.then(async r=>{u&&await u.end(),c(r)},async r=>{u&&await u.end(),d(r)})});if(!n&&u){let c=u.end();if(c&&typeof c.then=="function")return new Promise((d,r)=>{c.then(()=>{d(s)},a=>{r(a)})})}return s}begin(t,e,o){if(!this._started)throw new Error("profiler is not started yet");if(o===void 0){let i=Mn();return this.flush(i),new Gn(t,e,i,u=>this.endSync(u))}else{let i=o.beginTimer();return new Gn(t,e,0,async u=>this.end(u),i,o)}}async end(t){let e=await t.checkTimer();this._timingEvents.length=this._flushBatchSize||t-this._flushTime>=this._flushIntervalInMilliseconds){for(let e=this._flushPointer;this._flushPointerperformance.now():Date.now});function vs(t,e,o){for(let i of o){let u=i[0],n=i[1],s=i[2],c=i[3],d=i[4];if(t.opType===u){for(let r of e)if((r.domain===n||r.domain==="ai.onnx"&&n==="")&&Ld(r.version,s))return{opImpl:c,opInit:d}}}throw new TypeError(`cannot resolve operator '${t.opType}' with opsets: ${e.map(i=>`${i.domain||"ai.onnx"} v${i.version}`).join(", ")}`)}function Ld(t,e){if(e.endsWith("+")){let o=Number.parseInt(e.substring(0,e.length-1),10);return!isNaN(o)&&o<=t}else if(e.split("-").length===2){let o=e.split("-"),i=Number.parseInt(o[0],10),u=Number.parseInt(o[1],10);return!isNaN(i)&&!isNaN(u)&&i<=t&&t<=u}else return Number.parseInt(e,10)===t}var ws=L(()=>{}),_s=me(t=>{t.__esModule=!0;var e=function(){function o(i){if(!i)throw new TypeError("Invalid argument; `value` has no value.");this.value=o.EMPTY,i&&o.isGuid(i)&&(this.value=i)}return o.isGuid=function(i){var u=i.toString();return i&&(i instanceof o||o.validator.test(u))},o.create=function(){return new o([o.gen(2),o.gen(1),o.gen(1),o.gen(1),o.gen(3)].join("-"))},o.createEmpty=function(){return new o("emptyguid")},o.parse=function(i){return new o(i)},o.raw=function(){return[o.gen(2),o.gen(1),o.gen(1),o.gen(1),o.gen(3)].join("-")},o.gen=function(i){for(var u="",n=0;n>>=0,(u=0<=t&&t<256)&&(i=Ss[t],i)?i:(o=le(t,0,!0),u&&(Ss[t]=o),o)):(t|=0,(u=-128<=t&&t<128)&&(i=Is[t],i)?i:(o=le(t,t<0?-1:0,!1),u&&(Is[t]=o),o))}function ft(t,e){if(isNaN(t))return e?Ut:wt;if(e){if(t<0)return Ut;if(t>=Ds)return $s}else{if(t<=-Ps)return tt;if(t+1>=Ps)return Fs}return t<0?ft(-t,e).neg():le(t%Lr|0,t/Lr|0,e)}function le(t,e,o){return new be(t,e,o)}function Qo(t,e,o){if(t.length===0)throw Error("empty string");if(typeof e=="number"?(o=e,e=!1):e=!!e,t==="NaN"||t==="Infinity"||t==="+Infinity"||t==="-Infinity")return e?Ut:wt;if(o=o||10,o<2||360)throw Error("interior hyphen");if(i===0)return Qo(t.substring(1),e,o).neg();for(var u=ft(Vn(o,8)),n=wt,s=0;s{lt=null;try{lt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}be.prototype.__isLong__,Object.defineProperty(be.prototype,"__isLong__",{value:!0}),be.isLong=We,Is={},Ss={},be.fromInt=ur,be.fromNumber=ft,be.fromBits=le,Vn=Math.pow,be.fromString=Qo,be.fromValue=_t,As=65536,$d=1<<24,Lr=As*As,Ds=Lr*Lr,Ps=Ds/2,Es=ur($d),wt=ur(0),be.ZERO=wt,Ut=ur(0,!0),be.UZERO=Ut,Dr=ur(1),be.ONE=Dr,Ls=ur(1,!0),be.UONE=Ls,Zo=ur(-1),be.NEG_ONE=Zo,Fs=le(-1,2147483647,!1),be.MAX_VALUE=Fs,$s=le(-1,-1,!0),be.MAX_UNSIGNED_VALUE=$s,tt=le(0,-2147483648,!1),be.MIN_VALUE=tt,$=be.prototype,$.toInt=function(){return this.unsigned?this.low>>>0:this.low},$.toNumber=function(){return this.unsigned?(this.high>>>0)*Lr+(this.low>>>0):this.high*Lr+(this.low>>>0)},$.toString=function(t){if(t=t||10,t<2||36>>0,r=d.toString(t);if(n=c,n.isZero())return r+s;for(;r.length<6;)r="0"+r;s=""+r+s}},$.getHighBits=function(){return this.high},$.getHighBitsUnsigned=function(){return this.high>>>0},$.getLowBits=function(){return this.low},$.getLowBitsUnsigned=function(){return this.low>>>0},$.getNumBitsAbs=function(){if(this.isNegative())return this.eq(tt)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<=0},$.isOdd=function(){return(this.low&1)===1},$.isEven=function(){return(this.low&1)===0},$.equals=function(t){return We(t)||(t=_t(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low},$.eq=$.equals,$.notEquals=function(t){return!this.eq(t)},$.neq=$.notEquals,$.ne=$.notEquals,$.lessThan=function(t){return this.comp(t)<0},$.lt=$.lessThan,$.lessThanOrEqual=function(t){return this.comp(t)<=0},$.lte=$.lessThanOrEqual,$.le=$.lessThanOrEqual,$.greaterThan=function(t){return this.comp(t)>0},$.gt=$.greaterThan,$.greaterThanOrEqual=function(t){return this.comp(t)>=0},$.gte=$.greaterThanOrEqual,$.ge=$.greaterThanOrEqual,$.compare=function(t){if(We(t)||(t=_t(t)),this.eq(t))return 0;var e=this.isNegative(),o=t.isNegative();return e&&!o?-1:!e&&o?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},$.comp=$.compare,$.negate=function(){return!this.unsigned&&this.eq(tt)?tt:this.not().add(Dr)},$.neg=$.negate,$.add=function(t){We(t)||(t=_t(t));var e=this.high>>>16,o=this.high&65535,i=this.low>>>16,u=this.low&65535,n=t.high>>>16,s=t.high&65535,c=t.low>>>16,d=t.low&65535,r=0,a=0,l=0,h=0;return h+=u+d,l+=h>>>16,h&=65535,l+=i+c,a+=l>>>16,l&=65535,a+=o+s,r+=a>>>16,a&=65535,r+=e+n,r&=65535,le(l<<16|h,r<<16|a,this.unsigned)},$.subtract=function(t){return We(t)||(t=_t(t)),this.add(t.neg())},$.sub=$.subtract,$.multiply=function(t){if(this.isZero())return this;if(We(t)||(t=_t(t)),lt){var e=lt.mul(this.low,this.high,t.low,t.high);return le(e,lt.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Ut:wt;if(this.eq(tt))return t.isOdd()?tt:wt;if(t.eq(tt))return this.isOdd()?tt:wt;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Es)&&t.lt(Es))return ft(this.toNumber()*t.toNumber(),this.unsigned);var o=this.high>>>16,i=this.high&65535,u=this.low>>>16,n=this.low&65535,s=t.high>>>16,c=t.high&65535,d=t.low>>>16,r=t.low&65535,a=0,l=0,h=0,f=0;return f+=n*r,h+=f>>>16,f&=65535,h+=u*r,l+=h>>>16,h&=65535,h+=n*d,l+=h>>>16,h&=65535,l+=i*r,a+=l>>>16,l&=65535,l+=u*d,a+=l>>>16,l&=65535,l+=n*c,a+=l>>>16,l&=65535,a+=o*r+i*d+u*c+n*s,a&=65535,le(h<<16|f,a<<16|l,this.unsigned)},$.mul=$.multiply,$.divide=function(t){if(We(t)||(t=_t(t)),t.isZero())throw Error("division by zero");if(lt){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?lt.div_u:lt.div_s)(this.low,this.high,t.low,t.high);return le(e,lt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Ut:wt;var o,i,u;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Ut;if(t.gt(this.shru(1)))return Ls;u=Ut}else{if(this.eq(tt)){if(t.eq(Dr)||t.eq(Zo))return tt;if(t.eq(tt))return Dr;var n=this.shr(1);return o=n.div(t).shl(1),o.eq(wt)?t.isNegative()?Dr:Zo:(i=this.sub(t.mul(o)),u=o.add(i.div(t)),u)}else if(t.eq(tt))return this.unsigned?Ut:wt;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();u=wt}for(i=this;i.gte(t);){o=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var s=Math.ceil(Math.log(o)/Math.LN2),c=s<=48?1:Vn(2,s-48),d=ft(o),r=d.mul(t);r.isNegative()||r.gt(i);)o-=c,d=ft(o,this.unsigned),r=d.mul(t);d.isZero()&&(d=Dr),u=u.add(d),i=i.sub(r)}return u},$.div=$.divide,$.modulo=function(t){if(We(t)||(t=_t(t)),lt){var e=(this.unsigned?lt.rem_u:lt.rem_s)(this.low,this.high,t.low,t.high);return le(e,lt.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},$.mod=$.modulo,$.rem=$.modulo,$.not=function(){return le(~this.low,~this.high,this.unsigned)},$.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},$.clz=$.countLeadingZeros,$.countTrailingZeros=function(){return this.low?Os(this.low):Os(this.high)+32},$.ctz=$.countTrailingZeros,$.and=function(t){return We(t)||(t=_t(t)),le(this.low&t.low,this.high&t.high,this.unsigned)},$.or=function(t){return We(t)||(t=_t(t)),le(this.low|t.low,this.high|t.high,this.unsigned)},$.xor=function(t){return We(t)||(t=_t(t)),le(this.low^t.low,this.high^t.high,this.unsigned)},$.shiftLeft=function(t){return We(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?le(this.low<>>32-t,this.unsigned):le(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):le(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},$.shr=$.shiftRight,$.shiftRightUnsigned=function(t){return We(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?le(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?le(this.high,0,this.unsigned):le(this.high>>>t-32,0,this.unsigned)},$.shru=$.shiftRightUnsigned,$.shr_u=$.shiftRightUnsigned,$.rotateLeft=function(t){var e;return We(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?le(this.high,this.low,this.unsigned):t<32?(e=32-t,le(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,le(this.high<>>e,this.low<>>e,this.unsigned))},$.rotl=$.rotateLeft,$.rotateRight=function(t){var e;return We(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?le(this.high,this.low,this.unsigned):t<32?(e=32-t,le(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,le(this.low<>>t,this.high<>>t,this.unsigned))},$.rotr=$.rotateRight,$.toSigned=function(){return this.unsigned?le(this.low,this.high,!1):this},$.toUnsigned=function(){return this.unsigned?this:le(this.low,this.high,!0)},$.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},$.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]},$.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]},be.fromBytes=function(t,e,o){return o?be.fromBytesLE(t,e):be.fromBytesBE(t,e)},be.fromBytesLE=function(t,e){return new be(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},be.fromBytesBE=function(t,e){return new be(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)},zt=be}),_,Wn=L(()=>{_={},_.Offset,_.Table,_.SIZEOF_SHORT=2,_.SIZEOF_INT=4,_.FILE_IDENTIFIER_LENGTH=4,_.SIZE_PREFIX_LENGTH=4,_.Encoding={UTF8_BYTES:1,UTF16_STRING:2},_.int32=new Int32Array(2),_.float32=new Float32Array(_.int32.buffer),_.float64=new Float64Array(_.int32.buffer),_.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,_.Long=function(t,e){this.low=t|0,this.high=e|0},_.Long.create=function(t,e){return t==0&&e==0?_.Long.ZERO:new _.Long(t,e)},_.Long.prototype.toFloat64=function(){return(this.low>>>0)+this.high*4294967296},_.Long.prototype.equals=function(t){return this.low==t.low&&this.high==t.high},_.Long.ZERO=new _.Long(0,0),_.Builder=function(t){if(t)var e=t;else var e=1024;this.bb=_.ByteBuffer.allocate(e),this.space=e,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},_.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},_.Builder.prototype.forceDefaults=function(t){this.force_defaults=t},_.Builder.prototype.dataBuffer=function(){return this.bb},_.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},_.Builder.prototype.prep=function(t,e){t>this.minalign&&(this.minalign=t);for(var o=~(this.bb.capacity()-this.space+e)+1&t-1;this.space=0&&this.vtable[e]==0;e--);for(var o=e+1;e>=0;e--)this.addInt16(this.vtable[e]!=0?t-this.vtable[e]:0);var i=2;this.addInt16(t-this.object_start);var u=(o+i)*_.SIZEOF_SHORT;this.addInt16(u);var n=0,s=this.space;e:for(e=0;e=0;n--)this.writeInt8(u.charCodeAt(n))}this.prep(this.minalign,_.SIZEOF_INT+i),this.addOffset(t),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},_.Builder.prototype.finishSizePrefixed=function(t,e){this.finish(t,e,!0)},_.Builder.prototype.requiredField=function(t,e){var o=this.bb.capacity()-t,i=o-this.bb.readInt32(o),u=this.bb.readInt16(i+e)!=0;if(!u)throw new Error("FlatBuffers: field "+e+" must be set")},_.Builder.prototype.startVector=function(t,e,o){this.notNested(),this.vector_num_elems=e,this.prep(_.SIZEOF_INT,t*e),this.prep(o,t*e)},_.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},_.Builder.prototype.createString=function(t){if(t instanceof Uint8Array)var e=t;else for(var e=[],o=0;o=56320)i=u;else{var n=t.charCodeAt(o++);i=(u<<10)+n+-56613888}i<128?e.push(i):(i<2048?e.push(i>>6&31|192):(i<65536?e.push(i>>12&15|224):e.push(i>>18&7|240,i>>12&63|128),e.push(i>>6&63|128)),e.push(i&63|128))}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length);for(var o=0,s=this.space,c=this.bb.bytes();o>24},_.ByteBuffer.prototype.readUint8=function(t){return this.bytes_[t]},_.ByteBuffer.prototype.readInt16=function(t){return this.readUint16(t)<<16>>16},_.ByteBuffer.prototype.readUint16=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8},_.ByteBuffer.prototype.readInt32=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24},_.ByteBuffer.prototype.readUint32=function(t){return this.readInt32(t)>>>0},_.ByteBuffer.prototype.readInt64=function(t){return new _.Long(this.readInt32(t),this.readInt32(t+4))},_.ByteBuffer.prototype.readUint64=function(t){return new _.Long(this.readUint32(t),this.readUint32(t+4))},_.ByteBuffer.prototype.readFloat32=function(t){return _.int32[0]=this.readInt32(t),_.float32[0]},_.ByteBuffer.prototype.readFloat64=function(t){return _.int32[_.isLittleEndian?0:1]=this.readInt32(t),_.int32[_.isLittleEndian?1:0]=this.readInt32(t+4),_.float64[0]},_.ByteBuffer.prototype.writeInt8=function(t,e){this.bytes_[t]=e},_.ByteBuffer.prototype.writeUint8=function(t,e){this.bytes_[t]=e},_.ByteBuffer.prototype.writeInt16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},_.ByteBuffer.prototype.writeUint16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},_.ByteBuffer.prototype.writeInt32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},_.ByteBuffer.prototype.writeUint32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},_.ByteBuffer.prototype.writeInt64=function(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)},_.ByteBuffer.prototype.writeUint64=function(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)},_.ByteBuffer.prototype.writeFloat32=function(t,e){_.float32[0]=e,this.writeInt32(t,_.int32[0])},_.ByteBuffer.prototype.writeFloat64=function(t,e){_.float64[0]=e,this.writeInt32(t,_.int32[_.isLittleEndian?0:1]),this.writeInt32(t+4,_.int32[_.isLittleEndian?1:0])},_.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10)+55296,(n&1023)+56320))}return i},_.ByteBuffer.prototype.__indirect=function(t){return t+this.readInt32(t)},_.ByteBuffer.prototype.__vector=function(t){return t+this.readInt32(t)+_.SIZEOF_INT},_.ByteBuffer.prototype.__vector_len=function(t){return this.readInt32(t+this.readInt32(t))},_.ByteBuffer.prototype.__has_identifier=function(t){if(t.length!=_.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+_.FILE_IDENTIFIER_LENGTH);for(var e=0;e<_.FILE_IDENTIFIER_LENGTH;e++)if(t.charCodeAt(e)!=this.readInt8(this.position_+_.SIZEOF_INT+e))return!1;return!0},_.ByteBuffer.prototype.createLong=function(t,e){return _.Long.create(t,e)}}),W,tn=L(()=>{Wn(),(t=>{(e=>{(o=>{(i=>(i[i.UNDEFINED=0]="UNDEFINED",i[i.FLOAT=1]="FLOAT",i[i.INT=2]="INT",i[i.STRING=3]="STRING",i[i.TENSOR=4]="TENSOR",i[i.GRAPH=5]="GRAPH",i[i.FLOATS=6]="FLOATS",i[i.INTS=7]="INTS",i[i.STRINGS=8]="STRINGS",i[i.TENSORS=9]="TENSORS",i[i.GRAPHS=10]="GRAPHS",i[i.SPARSE_TENSOR=11]="SPARSE_TENSOR",i[i.SPARSE_TENSORS=12]="SPARSE_TENSORS"))(o.AttributeType||={})})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{(i=>(i[i.UNKNOWN=0]="UNKNOWN",i[i.VALUE=1]="VALUE",i[i.PARAM=2]="PARAM"))(o.DimensionValueType||={})})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{(i=>(i[i.UNDEFINED=0]="UNDEFINED",i[i.FLOAT=1]="FLOAT",i[i.UINT8=2]="UINT8",i[i.INT8=3]="INT8",i[i.UINT16=4]="UINT16",i[i.INT16=5]="INT16",i[i.INT32=6]="INT32",i[i.INT64=7]="INT64",i[i.STRING=8]="STRING",i[i.BOOL=9]="BOOL",i[i.FLOAT16=10]="FLOAT16",i[i.DOUBLE=11]="DOUBLE",i[i.UINT32=12]="UINT32",i[i.UINT64=13]="UINT64",i[i.COMPLEX64=14]="COMPLEX64",i[i.COMPLEX128=15]="COMPLEX128",i[i.BFLOAT16=16]="BFLOAT16",i[i.FLOAT8E4M3FN=17]="FLOAT8E4M3FN",i[i.FLOAT8E4M3FNUZ=18]="FLOAT8E4M3FNUZ",i[i.FLOAT8E5M2=19]="FLOAT8E5M2",i[i.FLOAT8E5M2FNUZ=20]="FLOAT8E5M2FNUZ"))(o.TensorDataType||={})})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{(i=>(i[i.Primitive=0]="Primitive",i[i.Fused=1]="Fused"))(o.NodeType||={})})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{(i=>(i[i.NONE=0]="NONE",i[i.tensor_type=1]="tensor_type",i[i.sequence_type=2]="sequence_type",i[i.map_type=3]="map_type"))(o.TypeInfoValue||={})})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsShape(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsShape(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}dim(n,s){let c=this.bb.__offset(this.bb_pos,4);return c?(s||new t.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}dimLength(){let n=this.bb.__offset(this.bb_pos,4);return n?this.bb.__vector_len(this.bb_pos+n):0}static startShape(n){n.startObject(1)}static addDim(n,s){n.addFieldOffset(0,s,0)}static createDimVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startDimVector(n,s){n.startVector(4,s,4)}static endShape(n){return n.endObject()}static createShape(n,s){return i.startShape(n),i.addDim(n,s),i.endShape(n)}}o.Shape=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsDimension(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsDimension(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}value(n){let s=this.bb.__offset(this.bb_pos,4);return s?(n||new t.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}denotation(n){let s=this.bb.__offset(this.bb_pos,6);return s?this.bb.__string(this.bb_pos+s,n):null}static startDimension(n){n.startObject(2)}static addValue(n,s){n.addFieldOffset(0,s,0)}static addDenotation(n,s){n.addFieldOffset(1,s,0)}static endDimension(n){return n.endObject()}static createDimension(n,s,c){return i.startDimension(n),i.addValue(n,s),i.addDenotation(n,c),i.endDimension(n)}}o.Dimension=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsDimensionValue(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsDimensionValue(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}dimType(){let n=this.bb.__offset(this.bb_pos,4);return n?this.bb.readInt8(this.bb_pos+n):0}dimValue(){let n=this.bb.__offset(this.bb_pos,6);return n?this.bb.readInt64(this.bb_pos+n):this.bb.createLong(0,0)}dimParam(n){let s=this.bb.__offset(this.bb_pos,8);return s?this.bb.__string(this.bb_pos+s,n):null}static startDimensionValue(n){n.startObject(3)}static addDimType(n,s){n.addFieldInt8(0,s,0)}static addDimValue(n,s){n.addFieldInt64(1,s,n.createLong(0,0))}static addDimParam(n,s){n.addFieldOffset(2,s,0)}static endDimensionValue(n){return n.endObject()}static createDimensionValue(n,s,c,d){return i.startDimensionValue(n),i.addDimType(n,s),i.addDimValue(n,c),i.addDimParam(n,d),i.endDimensionValue(n)}}o.DimensionValue=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsTensorTypeAndShape(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsTensorTypeAndShape(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}elemType(){let n=this.bb.__offset(this.bb_pos,4);return n?this.bb.readInt32(this.bb_pos+n):0}shape(n){let s=this.bb.__offset(this.bb_pos,6);return s?(n||new t.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}static startTensorTypeAndShape(n){n.startObject(2)}static addElemType(n,s){n.addFieldInt32(0,s,0)}static addShape(n,s){n.addFieldOffset(1,s,0)}static endTensorTypeAndShape(n){return n.endObject()}static createTensorTypeAndShape(n,s,c){return i.startTensorTypeAndShape(n),i.addElemType(n,s),i.addShape(n,c),i.endTensorTypeAndShape(n)}}o.TensorTypeAndShape=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsMapType(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsMapType(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}keyType(){let n=this.bb.__offset(this.bb_pos,4);return n?this.bb.readInt32(this.bb_pos+n):0}valueType(n){let s=this.bb.__offset(this.bb_pos,6);return s?(n||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}static startMapType(n){n.startObject(2)}static addKeyType(n,s){n.addFieldInt32(0,s,0)}static addValueType(n,s){n.addFieldOffset(1,s,0)}static endMapType(n){return n.endObject()}static createMapType(n,s,c){return i.startMapType(n),i.addKeyType(n,s),i.addValueType(n,c),i.endMapType(n)}}o.MapType=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsSequenceType(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsSequenceType(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}elemType(n){let s=this.bb.__offset(this.bb_pos,4);return s?(n||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}static startSequenceType(n){n.startObject(1)}static addElemType(n,s){n.addFieldOffset(0,s,0)}static endSequenceType(n){return n.endObject()}static createSequenceType(n,s){return i.startSequenceType(n),i.addElemType(n,s),i.endSequenceType(n)}}o.SequenceType=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(n,s,c,d){return n.prep(4,12),n.writeInt32(d),n.writeInt32(c),n.writeInt32(s),n.offset()}}o.EdgeEnd=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsNodeEdge(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsNodeEdge(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}nodeIndex(){let n=this.bb.__offset(this.bb_pos,4);return n?this.bb.readUint32(this.bb_pos+n):0}inputEdges(n,s){let c=this.bb.__offset(this.bb_pos,6);return c?(s||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+c)+n*12,this.bb):null}inputEdgesLength(){let n=this.bb.__offset(this.bb_pos,6);return n?this.bb.__vector_len(this.bb_pos+n):0}outputEdges(n,s){let c=this.bb.__offset(this.bb_pos,8);return c?(s||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+c)+n*12,this.bb):null}outputEdgesLength(){let n=this.bb.__offset(this.bb_pos,8);return n?this.bb.__vector_len(this.bb_pos+n):0}static startNodeEdge(n){n.startObject(3)}static addNodeIndex(n,s){n.addFieldInt32(0,s,0)}static addInputEdges(n,s){n.addFieldOffset(1,s,0)}static startInputEdgesVector(n,s){n.startVector(12,s,4)}static addOutputEdges(n,s){n.addFieldOffset(2,s,0)}static startOutputEdgesVector(n,s){n.startVector(12,s,4)}static endNodeEdge(n){return n.endObject()}static createNodeEdge(n,s,c,d){return i.startNodeEdge(n),i.addNodeIndex(n,s),i.addInputEdges(n,c),i.addOutputEdges(n,d),i.endNodeEdge(n)}}o.NodeEdge=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsNode(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsNode(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}name(n){let s=this.bb.__offset(this.bb_pos,4);return s?this.bb.__string(this.bb_pos+s,n):null}docString(n){let s=this.bb.__offset(this.bb_pos,6);return s?this.bb.__string(this.bb_pos+s,n):null}domain(n){let s=this.bb.__offset(this.bb_pos,8);return s?this.bb.__string(this.bb_pos+s,n):null}sinceVersion(){let n=this.bb.__offset(this.bb_pos,10);return n?this.bb.readInt32(this.bb_pos+n):0}index(){let n=this.bb.__offset(this.bb_pos,12);return n?this.bb.readUint32(this.bb_pos+n):0}opType(n){let s=this.bb.__offset(this.bb_pos,14);return s?this.bb.__string(this.bb_pos+s,n):null}type(){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.readInt32(this.bb_pos+n):0}executionProviderType(n){let s=this.bb.__offset(this.bb_pos,18);return s?this.bb.__string(this.bb_pos+s,n):null}inputs(n,s){let c=this.bb.__offset(this.bb_pos,20);return c?this.bb.__string(this.bb.__vector(this.bb_pos+c)+n*4,s):null}inputsLength(){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__vector_len(this.bb_pos+n):0}outputs(n,s){let c=this.bb.__offset(this.bb_pos,22);return c?this.bb.__string(this.bb.__vector(this.bb_pos+c)+n*4,s):null}outputsLength(){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__vector_len(this.bb_pos+n):0}attributes(n,s){let c=this.bb.__offset(this.bb_pos,24);return c?(s||new t.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}attributesLength(){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__vector_len(this.bb_pos+n):0}inputArgCounts(n){let s=this.bb.__offset(this.bb_pos,26);return s?this.bb.readInt32(this.bb.__vector(this.bb_pos+s)+n*4):0}inputArgCountsLength(){let n=this.bb.__offset(this.bb_pos,26);return n?this.bb.__vector_len(this.bb_pos+n):0}inputArgCountsArray(){let n=this.bb.__offset(this.bb_pos,26);return n?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+n),this.bb.__vector_len(this.bb_pos+n)):null}implicitInputs(n,s){let c=this.bb.__offset(this.bb_pos,28);return c?this.bb.__string(this.bb.__vector(this.bb_pos+c)+n*4,s):null}implicitInputsLength(){let n=this.bb.__offset(this.bb_pos,28);return n?this.bb.__vector_len(this.bb_pos+n):0}static startNode(n){n.startObject(13)}static addName(n,s){n.addFieldOffset(0,s,0)}static addDocString(n,s){n.addFieldOffset(1,s,0)}static addDomain(n,s){n.addFieldOffset(2,s,0)}static addSinceVersion(n,s){n.addFieldInt32(3,s,0)}static addIndex(n,s){n.addFieldInt32(4,s,0)}static addOpType(n,s){n.addFieldOffset(5,s,0)}static addType(n,s){n.addFieldInt32(6,s,0)}static addExecutionProviderType(n,s){n.addFieldOffset(7,s,0)}static addInputs(n,s){n.addFieldOffset(8,s,0)}static createInputsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startInputsVector(n,s){n.startVector(4,s,4)}static addOutputs(n,s){n.addFieldOffset(9,s,0)}static createOutputsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startOutputsVector(n,s){n.startVector(4,s,4)}static addAttributes(n,s){n.addFieldOffset(10,s,0)}static createAttributesVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startAttributesVector(n,s){n.startVector(4,s,4)}static addInputArgCounts(n,s){n.addFieldOffset(11,s,0)}static createInputArgCountsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addInt32(s[c]);return n.endVector()}static startInputArgCountsVector(n,s){n.startVector(4,s,4)}static addImplicitInputs(n,s){n.addFieldOffset(12,s,0)}static createImplicitInputsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startImplicitInputsVector(n,s){n.startVector(4,s,4)}static endNode(n){return n.endObject()}static createNode(n,s,c,d,r,a,l,h,f,m,g,b,v,T){return i.startNode(n),i.addName(n,s),i.addDocString(n,c),i.addDomain(n,d),i.addSinceVersion(n,r),i.addIndex(n,a),i.addOpType(n,l),i.addType(n,h),i.addExecutionProviderType(n,f),i.addInputs(n,m),i.addOutputs(n,g),i.addAttributes(n,b),i.addInputArgCounts(n,v),i.addImplicitInputs(n,T),i.endNode(n)}}o.Node=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsValueInfo(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsValueInfo(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}name(n){let s=this.bb.__offset(this.bb_pos,4);return s?this.bb.__string(this.bb_pos+s,n):null}docString(n){let s=this.bb.__offset(this.bb_pos,6);return s?this.bb.__string(this.bb_pos+s,n):null}type(n){let s=this.bb.__offset(this.bb_pos,8);return s?(n||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}static startValueInfo(n){n.startObject(3)}static addName(n,s){n.addFieldOffset(0,s,0)}static addDocString(n,s){n.addFieldOffset(1,s,0)}static addType(n,s){n.addFieldOffset(2,s,0)}static endValueInfo(n){return n.endObject()}static createValueInfo(n,s,c,d){return i.startValueInfo(n),i.addName(n,s),i.addDocString(n,c),i.addType(n,d),i.endValueInfo(n)}}o.ValueInfo=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsTypeInfo(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsTypeInfo(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}denotation(n){let s=this.bb.__offset(this.bb_pos,4);return s?this.bb.__string(this.bb_pos+s,n):null}valueType(){let n=this.bb.__offset(this.bb_pos,6);return n?this.bb.readUint8(this.bb_pos+n):0}value(n){let s=this.bb.__offset(this.bb_pos,8);return s?this.bb.__union(n,this.bb_pos+s):null}static startTypeInfo(n){n.startObject(3)}static addDenotation(n,s){n.addFieldOffset(0,s,0)}static addValueType(n,s){n.addFieldInt8(1,s,0)}static addValue(n,s){n.addFieldOffset(2,s,0)}static endTypeInfo(n){return n.endObject()}static createTypeInfo(n,s,c,d){return i.startTypeInfo(n),i.addDenotation(n,s),i.addValueType(n,c),i.addValue(n,d),i.endTypeInfo(n)}}o.TypeInfo=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsOperatorSetId(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsOperatorSetId(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}domain(n){let s=this.bb.__offset(this.bb_pos,4);return s?this.bb.__string(this.bb_pos+s,n):null}version(){let n=this.bb.__offset(this.bb_pos,6);return n?this.bb.readInt64(this.bb_pos+n):this.bb.createLong(0,0)}static startOperatorSetId(n){n.startObject(2)}static addDomain(n,s){n.addFieldOffset(0,s,0)}static addVersion(n,s){n.addFieldInt64(1,s,n.createLong(0,0))}static endOperatorSetId(n){return n.endObject()}static createOperatorSetId(n,s,c){return i.startOperatorSetId(n),i.addDomain(n,s),i.addVersion(n,c),i.endOperatorSetId(n)}}o.OperatorSetId=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsTensor(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsTensor(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}name(n){let s=this.bb.__offset(this.bb_pos,4);return s?this.bb.__string(this.bb_pos+s,n):null}docString(n){let s=this.bb.__offset(this.bb_pos,6);return s?this.bb.__string(this.bb_pos+s,n):null}dims(n){let s=this.bb.__offset(this.bb_pos,8);return s?this.bb.readInt64(this.bb.__vector(this.bb_pos+s)+n*8):this.bb.createLong(0,0)}dimsLength(){let n=this.bb.__offset(this.bb_pos,8);return n?this.bb.__vector_len(this.bb_pos+n):0}dataType(){let n=this.bb.__offset(this.bb_pos,10);return n?this.bb.readInt32(this.bb_pos+n):0}rawData(n){let s=this.bb.__offset(this.bb_pos,12);return s?this.bb.readUint8(this.bb.__vector(this.bb_pos+s)+n):0}rawDataLength(){let n=this.bb.__offset(this.bb_pos,12);return n?this.bb.__vector_len(this.bb_pos+n):0}rawDataArray(){let n=this.bb.__offset(this.bb_pos,12);return n?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+n),this.bb.__vector_len(this.bb_pos+n)):null}stringData(n,s){let c=this.bb.__offset(this.bb_pos,14);return c?this.bb.__string(this.bb.__vector(this.bb_pos+c)+n*4,s):null}stringDataLength(){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__vector_len(this.bb_pos+n):0}static startTensor(n){n.startObject(6)}static addName(n,s){n.addFieldOffset(0,s,0)}static addDocString(n,s){n.addFieldOffset(1,s,0)}static addDims(n,s){n.addFieldOffset(2,s,0)}static createDimsVector(n,s){n.startVector(8,s.length,8);for(let c=s.length-1;c>=0;c--)n.addInt64(s[c]);return n.endVector()}static startDimsVector(n,s){n.startVector(8,s,8)}static addDataType(n,s){n.addFieldInt32(3,s,0)}static addRawData(n,s){n.addFieldOffset(4,s,0)}static createRawDataVector(n,s){n.startVector(1,s.length,1);for(let c=s.length-1;c>=0;c--)n.addInt8(s[c]);return n.endVector()}static startRawDataVector(n,s){n.startVector(1,s,1)}static addStringData(n,s){n.addFieldOffset(5,s,0)}static createStringDataVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startStringDataVector(n,s){n.startVector(4,s,4)}static endTensor(n){return n.endObject()}static createTensor(n,s,c,d,r,a,l){return i.startTensor(n),i.addName(n,s),i.addDocString(n,c),i.addDims(n,d),i.addDataType(n,r),i.addRawData(n,a),i.addStringData(n,l),i.endTensor(n)}}o.Tensor=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsSparseTensor(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsSparseTensor(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}values(n){let s=this.bb.__offset(this.bb_pos,4);return s?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}indices(n){let s=this.bb.__offset(this.bb_pos,6);return s?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}dims(n){let s=this.bb.__offset(this.bb_pos,8);return s?this.bb.readInt64(this.bb.__vector(this.bb_pos+s)+n*8):this.bb.createLong(0,0)}dimsLength(){let n=this.bb.__offset(this.bb_pos,8);return n?this.bb.__vector_len(this.bb_pos+n):0}static startSparseTensor(n){n.startObject(3)}static addValues(n,s){n.addFieldOffset(0,s,0)}static addIndices(n,s){n.addFieldOffset(1,s,0)}static addDims(n,s){n.addFieldOffset(2,s,0)}static createDimsVector(n,s){n.startVector(8,s.length,8);for(let c=s.length-1;c>=0;c--)n.addInt64(s[c]);return n.endVector()}static startDimsVector(n,s){n.startVector(8,s,8)}static endSparseTensor(n){return n.endObject()}static createSparseTensor(n,s,c,d){return i.startSparseTensor(n),i.addValues(n,s),i.addIndices(n,c),i.addDims(n,d),i.endSparseTensor(n)}}o.SparseTensor=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsAttribute(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsAttribute(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}name(n){let s=this.bb.__offset(this.bb_pos,4);return s?this.bb.__string(this.bb_pos+s,n):null}docString(n){let s=this.bb.__offset(this.bb_pos,6);return s?this.bb.__string(this.bb_pos+s,n):null}type(){let n=this.bb.__offset(this.bb_pos,8);return n?this.bb.readInt32(this.bb_pos+n):0}f(){let n=this.bb.__offset(this.bb_pos,10);return n?this.bb.readFloat32(this.bb_pos+n):0}i(){let n=this.bb.__offset(this.bb_pos,12);return n?this.bb.readInt64(this.bb_pos+n):this.bb.createLong(0,0)}s(n){let s=this.bb.__offset(this.bb_pos,14);return s?this.bb.__string(this.bb_pos+s,n):null}t(n){let s=this.bb.__offset(this.bb_pos,16);return s?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}g(n){let s=this.bb.__offset(this.bb_pos,18);return s?(n||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}floats(n){let s=this.bb.__offset(this.bb_pos,20);return s?this.bb.readFloat32(this.bb.__vector(this.bb_pos+s)+n*4):0}floatsLength(){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__vector_len(this.bb_pos+n):0}floatsArray(){let n=this.bb.__offset(this.bb_pos,20);return n?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+n),this.bb.__vector_len(this.bb_pos+n)):null}ints(n){let s=this.bb.__offset(this.bb_pos,22);return s?this.bb.readInt64(this.bb.__vector(this.bb_pos+s)+n*8):this.bb.createLong(0,0)}intsLength(){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__vector_len(this.bb_pos+n):0}strings(n,s){let c=this.bb.__offset(this.bb_pos,24);return c?this.bb.__string(this.bb.__vector(this.bb_pos+c)+n*4,s):null}stringsLength(){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__vector_len(this.bb_pos+n):0}tensors(n,s){let c=this.bb.__offset(this.bb_pos,26);return c?(s||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}tensorsLength(){let n=this.bb.__offset(this.bb_pos,26);return n?this.bb.__vector_len(this.bb_pos+n):0}graphs(n,s){let c=this.bb.__offset(this.bb_pos,28);return c?(s||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}graphsLength(){let n=this.bb.__offset(this.bb_pos,28);return n?this.bb.__vector_len(this.bb_pos+n):0}static startAttribute(n){n.startObject(13)}static addName(n,s){n.addFieldOffset(0,s,0)}static addDocString(n,s){n.addFieldOffset(1,s,0)}static addType(n,s){n.addFieldInt32(2,s,0)}static addF(n,s){n.addFieldFloat32(3,s,0)}static addI(n,s){n.addFieldInt64(4,s,n.createLong(0,0))}static addS(n,s){n.addFieldOffset(5,s,0)}static addT(n,s){n.addFieldOffset(6,s,0)}static addG(n,s){n.addFieldOffset(7,s,0)}static addFloats(n,s){n.addFieldOffset(8,s,0)}static createFloatsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addFloat32(s[c]);return n.endVector()}static startFloatsVector(n,s){n.startVector(4,s,4)}static addInts(n,s){n.addFieldOffset(9,s,0)}static createIntsVector(n,s){n.startVector(8,s.length,8);for(let c=s.length-1;c>=0;c--)n.addInt64(s[c]);return n.endVector()}static startIntsVector(n,s){n.startVector(8,s,8)}static addStrings(n,s){n.addFieldOffset(10,s,0)}static createStringsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startStringsVector(n,s){n.startVector(4,s,4)}static addTensors(n,s){n.addFieldOffset(11,s,0)}static createTensorsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startTensorsVector(n,s){n.startVector(4,s,4)}static addGraphs(n,s){n.addFieldOffset(12,s,0)}static createGraphsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startGraphsVector(n,s){n.startVector(4,s,4)}static endAttribute(n){return n.endObject()}static createAttribute(n,s,c,d,r,a,l,h,f,m,g,b,v,T){return i.startAttribute(n),i.addName(n,s),i.addDocString(n,c),i.addType(n,d),i.addF(n,r),i.addI(n,a),i.addS(n,l),i.addT(n,h),i.addG(n,f),i.addFloats(n,m),i.addInts(n,g),i.addStrings(n,b),i.addTensors(n,v),i.addGraphs(n,T),i.endAttribute(n)}}o.Attribute=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsGraph(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsGraph(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}initializers(n,s){let c=this.bb.__offset(this.bb_pos,4);return c?(s||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}initializersLength(){let n=this.bb.__offset(this.bb_pos,4);return n?this.bb.__vector_len(this.bb_pos+n):0}nodeArgs(n,s){let c=this.bb.__offset(this.bb_pos,6);return c?(s||new t.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}nodeArgsLength(){let n=this.bb.__offset(this.bb_pos,6);return n?this.bb.__vector_len(this.bb_pos+n):0}nodes(n,s){let c=this.bb.__offset(this.bb_pos,8);return c?(s||new t.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}nodesLength(){let n=this.bb.__offset(this.bb_pos,8);return n?this.bb.__vector_len(this.bb_pos+n):0}maxNodeIndex(){let n=this.bb.__offset(this.bb_pos,10);return n?this.bb.readUint32(this.bb_pos+n):0}nodeEdges(n,s){let c=this.bb.__offset(this.bb_pos,12);return c?(s||new t.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}nodeEdgesLength(){let n=this.bb.__offset(this.bb_pos,12);return n?this.bb.__vector_len(this.bb_pos+n):0}inputs(n,s){let c=this.bb.__offset(this.bb_pos,14);return c?this.bb.__string(this.bb.__vector(this.bb_pos+c)+n*4,s):null}inputsLength(){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__vector_len(this.bb_pos+n):0}outputs(n,s){let c=this.bb.__offset(this.bb_pos,16);return c?this.bb.__string(this.bb.__vector(this.bb_pos+c)+n*4,s):null}outputsLength(){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.__vector_len(this.bb_pos+n):0}sparseInitializers(n,s){let c=this.bb.__offset(this.bb_pos,18);return c?(s||new t.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}sparseInitializersLength(){let n=this.bb.__offset(this.bb_pos,18);return n?this.bb.__vector_len(this.bb_pos+n):0}static startGraph(n){n.startObject(8)}static addInitializers(n,s){n.addFieldOffset(0,s,0)}static createInitializersVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startInitializersVector(n,s){n.startVector(4,s,4)}static addNodeArgs(n,s){n.addFieldOffset(1,s,0)}static createNodeArgsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startNodeArgsVector(n,s){n.startVector(4,s,4)}static addNodes(n,s){n.addFieldOffset(2,s,0)}static createNodesVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startNodesVector(n,s){n.startVector(4,s,4)}static addMaxNodeIndex(n,s){n.addFieldInt32(3,s,0)}static addNodeEdges(n,s){n.addFieldOffset(4,s,0)}static createNodeEdgesVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startNodeEdgesVector(n,s){n.startVector(4,s,4)}static addInputs(n,s){n.addFieldOffset(5,s,0)}static createInputsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startInputsVector(n,s){n.startVector(4,s,4)}static addOutputs(n,s){n.addFieldOffset(6,s,0)}static createOutputsVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startOutputsVector(n,s){n.startVector(4,s,4)}static addSparseInitializers(n,s){n.addFieldOffset(7,s,0)}static createSparseInitializersVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startSparseInitializersVector(n,s){n.startVector(4,s,4)}static endGraph(n){return n.endObject()}static createGraph(n,s,c,d,r,a,l,h,f){return i.startGraph(n),i.addInitializers(n,s),i.addNodeArgs(n,c),i.addNodes(n,d),i.addMaxNodeIndex(n,r),i.addNodeEdges(n,a),i.addInputs(n,l),i.addOutputs(n,h),i.addSparseInitializers(n,f),i.endGraph(n)}}o.Graph=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsModel(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsModel(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}irVersion(){let n=this.bb.__offset(this.bb_pos,4);return n?this.bb.readInt64(this.bb_pos+n):this.bb.createLong(0,0)}opsetImport(n,s){let c=this.bb.__offset(this.bb_pos,6);return c?(s||new t.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}opsetImportLength(){let n=this.bb.__offset(this.bb_pos,6);return n?this.bb.__vector_len(this.bb_pos+n):0}producerName(n){let s=this.bb.__offset(this.bb_pos,8);return s?this.bb.__string(this.bb_pos+s,n):null}producerVersion(n){let s=this.bb.__offset(this.bb_pos,10);return s?this.bb.__string(this.bb_pos+s,n):null}domain(n){let s=this.bb.__offset(this.bb_pos,12);return s?this.bb.__string(this.bb_pos+s,n):null}modelVersion(){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.readInt64(this.bb_pos+n):this.bb.createLong(0,0)}docString(n){let s=this.bb.__offset(this.bb_pos,16);return s?this.bb.__string(this.bb_pos+s,n):null}graph(n){let s=this.bb.__offset(this.bb_pos,18);return s?(n||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}graphDocString(n){let s=this.bb.__offset(this.bb_pos,20);return s?this.bb.__string(this.bb_pos+s,n):null}static startModel(n){n.startObject(9)}static addIrVersion(n,s){n.addFieldInt64(0,s,n.createLong(0,0))}static addOpsetImport(n,s){n.addFieldOffset(1,s,0)}static createOpsetImportVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startOpsetImportVector(n,s){n.startVector(4,s,4)}static addProducerName(n,s){n.addFieldOffset(2,s,0)}static addProducerVersion(n,s){n.addFieldOffset(3,s,0)}static addDomain(n,s){n.addFieldOffset(4,s,0)}static addModelVersion(n,s){n.addFieldInt64(5,s,n.createLong(0,0))}static addDocString(n,s){n.addFieldOffset(6,s,0)}static addGraph(n,s){n.addFieldOffset(7,s,0)}static addGraphDocString(n,s){n.addFieldOffset(8,s,0)}static endModel(n){return n.endObject()}static createModel(n,s,c,d,r,a,l,h,f,m){return i.startModel(n),i.addIrVersion(n,s),i.addOpsetImport(n,c),i.addProducerName(n,d),i.addProducerVersion(n,r),i.addDomain(n,a),i.addModelVersion(n,l),i.addDocString(n,h),i.addGraph(n,f),i.addGraphDocString(n,m),i.endModel(n)}}o.Model=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsKernelCreateInfos(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsKernelCreateInfos(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}nodeIndices(n){let s=this.bb.__offset(this.bb_pos,4);return s?this.bb.readUint32(this.bb.__vector(this.bb_pos+s)+n*4):0}nodeIndicesLength(){let n=this.bb.__offset(this.bb_pos,4);return n?this.bb.__vector_len(this.bb_pos+n):0}nodeIndicesArray(){let n=this.bb.__offset(this.bb_pos,4);return n?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+n),this.bb.__vector_len(this.bb_pos+n)):null}kernelDefHashes(n){let s=this.bb.__offset(this.bb_pos,6);return s?this.bb.readUint64(this.bb.__vector(this.bb_pos+s)+n*8):this.bb.createLong(0,0)}kernelDefHashesLength(){let n=this.bb.__offset(this.bb_pos,6);return n?this.bb.__vector_len(this.bb_pos+n):0}static startKernelCreateInfos(n){n.startObject(2)}static addNodeIndices(n,s){n.addFieldOffset(0,s,0)}static createNodeIndicesVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addInt32(s[c]);return n.endVector()}static startNodeIndicesVector(n,s){n.startVector(4,s,4)}static addKernelDefHashes(n,s){n.addFieldOffset(1,s,0)}static createKernelDefHashesVector(n,s){n.startVector(8,s.length,8);for(let c=s.length-1;c>=0;c--)n.addInt64(s[c]);return n.endVector()}static startKernelDefHashesVector(n,s){n.startVector(8,s,8)}static endKernelCreateInfos(n){return n.endObject()}static createKernelCreateInfos(n,s,c){return i.startKernelCreateInfos(n),i.addNodeIndices(n,s),i.addKernelDefHashes(n,c),i.endKernelCreateInfos(n)}}o.KernelCreateInfos=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsSubGraphSessionState(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsSubGraphSessionState(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}graphId(n){let s=this.bb.__offset(this.bb_pos,4);return s?this.bb.__string(this.bb_pos+s,n):null}sessionState(n){let s=this.bb.__offset(this.bb_pos,6);return s?(n||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}static startSubGraphSessionState(n){n.startObject(2)}static addGraphId(n,s){n.addFieldOffset(0,s,0)}static addSessionState(n,s){n.addFieldOffset(1,s,0)}static endSubGraphSessionState(n){let s=n.endObject();return n.requiredField(s,4),s}static createSubGraphSessionState(n,s,c){return i.startSubGraphSessionState(n),i.addGraphId(n,s),i.addSessionState(n,c),i.endSubGraphSessionState(n)}}o.SubGraphSessionState=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsSessionState(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsSessionState(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}kernels(n){let s=this.bb.__offset(this.bb_pos,4);return s?(n||new t.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}subGraphSessionStates(n,s){let c=this.bb.__offset(this.bb_pos,6);return c?(s||new t.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+c)+n*4),this.bb):null}subGraphSessionStatesLength(){let n=this.bb.__offset(this.bb_pos,6);return n?this.bb.__vector_len(this.bb_pos+n):0}static startSessionState(n){n.startObject(2)}static addKernels(n,s){n.addFieldOffset(0,s,0)}static addSubGraphSessionStates(n,s){n.addFieldOffset(1,s,0)}static createSubGraphSessionStatesVector(n,s){n.startVector(4,s.length,4);for(let c=s.length-1;c>=0;c--)n.addOffset(s[c]);return n.endVector()}static startSubGraphSessionStatesVector(n,s){n.startVector(4,s,4)}static endSessionState(n){return n.endObject()}static createSessionState(n,s,c){return i.startSessionState(n),i.addKernels(n,s),i.addSubGraphSessionStates(n,c),i.endSessionState(n)}}o.SessionState=i})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(o=>{class i{constructor(){this.bb=null,this.bb_pos=0}__init(n,s){return this.bb_pos=n,this.bb=s,this}static getRootAsInferenceSession(n,s){return(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static getSizePrefixedRootAsInferenceSession(n,s){return n.setPosition(n.position()+_.SIZE_PREFIX_LENGTH),(s||new i).__init(n.readInt32(n.position())+n.position(),n)}static bufferHasIdentifier(n){return n.__has_identifier("ORTM")}ortVersion(n){let s=this.bb.__offset(this.bb_pos,4);return s?this.bb.__string(this.bb_pos+s,n):null}model(n){let s=this.bb.__offset(this.bb_pos,6);return s?(n||new t.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}sessionState(n){let s=this.bb.__offset(this.bb_pos,8);return s?(n||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+s),this.bb):null}static startInferenceSession(n){n.startObject(3)}static addOrtVersion(n,s){n.addFieldOffset(0,s,0)}static addModel(n,s){n.addFieldOffset(1,s,0)}static addSessionState(n,s){n.addFieldOffset(2,s,0)}static endInferenceSession(n){return n.endObject()}static finishInferenceSessionBuffer(n,s){n.finish(s,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(n,s){n.finish(s,"ORTM",!0)}static createInferenceSession(n,s,c,d){return i.startInferenceSession(n),i.addOrtVersion(n,s),i.addModel(n,c),i.addSessionState(n,d),i.endInferenceSession(n)}}o.InferenceSession=i})(e.fbs||={})})(t.experimental||={})})(W||={})}),ks=me((t,e)=>{e.exports=o;function o(i,u){for(var n=new Array(arguments.length-1),s=0,c=2,d=!0;c{var e=t;e.length=function(s){var c=s.length;if(!c)return 0;for(var d=0;--c%4>1&&s.charAt(c)==="=";)++d;return Math.ceil(s.length*3)/4-d};var o=new Array(64),i=new Array(123);for(u=0;u<64;)i[o[u]=u<26?u+65:u<52?u+71:u<62?u-4:u-59|43]=u++;var u;e.encode=function(s,c,d){for(var r=null,a=[],l=0,h=0,f;c>2],f=(m&3)<<4,h=1;break;case 1:a[l++]=o[f|m>>4],f=(m&15)<<2,h=2;break;case 2:a[l++]=o[f|m>>6],a[l++]=o[m&63],h=0;break}l>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,a)),l=0)}return h&&(a[l++]=o[f],a[l++]=61,h===1&&(a[l++]=61)),r?(l&&r.push(String.fromCharCode.apply(String,a.slice(0,l))),r.join("")):String.fromCharCode.apply(String,a.slice(0,l))};var n="invalid encoding";e.decode=function(s,c,d){for(var r=d,a=0,l,h=0;h1)break;if((f=i[f])===void 0)throw Error(n);switch(a){case 0:l=f,a=1;break;case 1:c[d++]=l<<2|(f&48)>>4,l=f,a=2;break;case 2:c[d++]=(l&15)<<4|(f&60)>>2,l=f,a=3;break;case 3:c[d++]=(l&3)<<6|f,a=0;break}}if(a===1)throw Error(n);return d-r},e.test=function(s){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s)}}),Us=me((t,e)=>{e.exports=o;function o(){this._listeners={}}o.prototype.on=function(i,u,n){return(this._listeners[i]||(this._listeners[i]=[])).push({fn:u,ctx:n||this}),this},o.prototype.off=function(i,u){if(i===void 0)this._listeners={};else if(u===void 0)this._listeners[i]=[];else for(var n=this._listeners[i],s=0;s{e.exports=o(o);function o(c){return typeof Float32Array<"u"?function(){var d=new Float32Array([-0]),r=new Uint8Array(d.buffer),a=r[3]===128;function l(g,b,v){d[0]=g,b[v]=r[0],b[v+1]=r[1],b[v+2]=r[2],b[v+3]=r[3]}function h(g,b,v){d[0]=g,b[v]=r[3],b[v+1]=r[2],b[v+2]=r[1],b[v+3]=r[0]}c.writeFloatLE=a?l:h,c.writeFloatBE=a?h:l;function f(g,b){return r[0]=g[b],r[1]=g[b+1],r[2]=g[b+2],r[3]=g[b+3],d[0]}function m(g,b){return r[3]=g[b],r[2]=g[b+1],r[1]=g[b+2],r[0]=g[b+3],d[0]}c.readFloatLE=a?f:m,c.readFloatBE=a?m:f}():function(){function d(a,l,h,f){var m=l<0?1:0;if(m&&(l=-l),l===0)a(1/l>0?0:2147483648,h,f);else if(isNaN(l))a(2143289344,h,f);else if(l>34028234663852886e22)a((m<<31|2139095040)>>>0,h,f);else if(l<11754943508222875e-54)a((m<<31|Math.round(l/1401298464324817e-60))>>>0,h,f);else{var g=Math.floor(Math.log(l)/Math.LN2),b=Math.round(l*Math.pow(2,-g)*8388608)&8388607;a((m<<31|g+127<<23|b)>>>0,h,f)}}c.writeFloatLE=d.bind(null,i),c.writeFloatBE=d.bind(null,u);function r(a,l,h){var f=a(l,h),m=(f>>31)*2+1,g=f>>>23&255,b=f&8388607;return g===255?b?NaN:m*(1/0):g===0?m*1401298464324817e-60*b:m*Math.pow(2,g-150)*(b+8388608)}c.readFloatLE=r.bind(null,n),c.readFloatBE=r.bind(null,s)}(),typeof Float64Array<"u"?function(){var d=new Float64Array([-0]),r=new Uint8Array(d.buffer),a=r[7]===128;function l(g,b,v){d[0]=g,b[v]=r[0],b[v+1]=r[1],b[v+2]=r[2],b[v+3]=r[3],b[v+4]=r[4],b[v+5]=r[5],b[v+6]=r[6],b[v+7]=r[7]}function h(g,b,v){d[0]=g,b[v]=r[7],b[v+1]=r[6],b[v+2]=r[5],b[v+3]=r[4],b[v+4]=r[3],b[v+5]=r[2],b[v+6]=r[1],b[v+7]=r[0]}c.writeDoubleLE=a?l:h,c.writeDoubleBE=a?h:l;function f(g,b){return r[0]=g[b],r[1]=g[b+1],r[2]=g[b+2],r[3]=g[b+3],r[4]=g[b+4],r[5]=g[b+5],r[6]=g[b+6],r[7]=g[b+7],d[0]}function m(g,b){return r[7]=g[b],r[6]=g[b+1],r[5]=g[b+2],r[4]=g[b+3],r[3]=g[b+4],r[2]=g[b+5],r[1]=g[b+6],r[0]=g[b+7],d[0]}c.readDoubleLE=a?f:m,c.readDoubleBE=a?m:f}():function(){function d(a,l,h,f,m,g){var b=f<0?1:0;if(b&&(f=-f),f===0)a(0,m,g+l),a(1/f>0?0:2147483648,m,g+h);else if(isNaN(f))a(0,m,g+l),a(2146959360,m,g+h);else if(f>17976931348623157e292)a(0,m,g+l),a((b<<31|2146435072)>>>0,m,g+h);else{var v;if(f<22250738585072014e-324)v=f/5e-324,a(v>>>0,m,g+l),a((b<<31|v/4294967296)>>>0,m,g+h);else{var T=Math.floor(Math.log(f)/Math.LN2);T===1024&&(T=1023),v=f*Math.pow(2,-T),a(v*4503599627370496>>>0,m,g+l),a((b<<31|T+1023<<20|v*1048576&1048575)>>>0,m,g+h)}}}c.writeDoubleLE=d.bind(null,i,0,4),c.writeDoubleBE=d.bind(null,u,4,0);function r(a,l,h,f,m){var g=a(f,m+l),b=a(f,m+h),v=(b>>31)*2+1,T=b>>>20&2047,E=4294967296*(b&1048575)+g;return T===2047?E?NaN:v*(1/0):T===0?v*5e-324*E:v*Math.pow(2,T-1075)*(E+4503599627370496)}c.readDoubleLE=r.bind(null,n,0,4),c.readDoubleBE=r.bind(null,s,4,0)}(),c}function i(c,d,r){d[r]=c&255,d[r+1]=c>>>8&255,d[r+2]=c>>>16&255,d[r+3]=c>>>24}function u(c,d,r){d[r]=c>>>24,d[r+1]=c>>>16&255,d[r+2]=c>>>8&255,d[r+3]=c&255}function n(c,d){return(c[d]|c[d+1]<<8|c[d+2]<<16|c[d+3]<<24)>>>0}function s(c,d){return(c[d]<<24|c[d+1]<<16|c[d+2]<<8|c[d+3])>>>0}}),Xs=me((exports,module)=>{module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}}),Js=me(t=>{var e=t;e.length=function(o){for(var i=0,u=0,n=0;n191&&r<224?c[d++]=(r&31)<<6|o[i++]&63:r>239&&r<365?(r=((r&7)<<18|(o[i++]&63)<<12|(o[i++]&63)<<6|o[i++]&63)-65536,c[d++]=55296+(r>>10),c[d++]=56320+(r&1023)):c[d++]=(r&15)<<12|(o[i++]&63)<<6|o[i++]&63,d>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,c)),d=0);return s?(d&&s.push(String.fromCharCode.apply(String,c.slice(0,d))),s.join("")):String.fromCharCode.apply(String,c.slice(0,d))},e.write=function(o,i,u){for(var n=u,s,c,d=0;d>6|192,i[u++]=s&63|128):(s&64512)===55296&&((c=o.charCodeAt(d+1))&64512)===56320?(s=65536+((s&1023)<<10)+(c&1023),++d,i[u++]=s>>18|240,i[u++]=s>>12&63|128,i[u++]=s>>6&63|128,i[u++]=s&63|128):(i[u++]=s>>12|224,i[u++]=s>>6&63|128,i[u++]=s&63|128);return u-n}}),Qs=me((t,e)=>{e.exports=o;function o(i,u,n){var s=n||8192,c=s>>>1,d=null,r=s;return function(a){if(a<1||a>c)return i(a);r+a>s&&(d=i(s),r=0);var l=u.call(d,r,r+=a);return r&7&&(r=(r|7)+1),l}}}),tu=me((t,e)=>{e.exports=i;var o=Xt();function i(c,d){this.lo=c>>>0,this.hi=d>>>0}var u=i.zero=new i(0,0);u.toNumber=function(){return 0},u.zzEncode=u.zzDecode=function(){return this},u.length=function(){return 1};var n=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(c){if(c===0)return u;var d=c<0;d&&(c=-c);var r=c>>>0,a=(c-r)/4294967296>>>0;return d&&(a=~a>>>0,r=~r>>>0,++r>4294967295&&(r=0,++a>4294967295&&(a=0))),new i(r,a)},i.from=function(c){if(typeof c=="number")return i.fromNumber(c);if(o.isString(c))if(o.Long)c=o.Long.fromString(c);else return i.fromNumber(parseInt(c,10));return c.low||c.high?new i(c.low>>>0,c.high>>>0):u},i.prototype.toNumber=function(c){if(!c&&this.hi>>>31){var d=~this.lo+1>>>0,r=~this.hi>>>0;return d||(r=r+1>>>0),-(d+r*4294967296)}return this.lo+this.hi*4294967296},i.prototype.toLong=function(c){return o.Long?new o.Long(this.lo|0,this.hi|0,!!c):{low:this.lo|0,high:this.hi|0,unsigned:!!c}};var s=String.prototype.charCodeAt;i.fromHash=function(c){return c===n?u:new i((s.call(c,0)|s.call(c,1)<<8|s.call(c,2)<<16|s.call(c,3)<<24)>>>0,(s.call(c,4)|s.call(c,5)<<8|s.call(c,6)<<16|s.call(c,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var c=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^c)>>>0,this.lo=(this.lo<<1^c)>>>0,this},i.prototype.zzDecode=function(){var c=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^c)>>>0,this.hi=(this.hi>>>1^c)>>>0,this},i.prototype.length=function(){var c=this.lo,d=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?d===0?c<16384?c<128?1:2:c<2097152?3:4:d<16384?d<128?5:6:d<2097152?7:8:r<128?9:10}}),Xt=me(t=>{var e=t;e.asPromise=ks(),e.base64=Ms(),e.EventEmitter=Us(),e.float=Ys(),e.inquire=Xs(),e.utf8=Js(),e.pool=Qs(),e.LongBits=tu(),e.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node),e.global=e.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||t,e.emptyArray=Object.freeze?Object.freeze([]):[],e.emptyObject=Object.freeze?Object.freeze({}):{},e.isInteger=Number.isInteger||function(u){return typeof u=="number"&&isFinite(u)&&Math.floor(u)===u},e.isString=function(u){return typeof u=="string"||u instanceof String},e.isObject=function(u){return u&&typeof u=="object"},e.isset=e.isSet=function(u,n){var s=u[n];return s!=null&&u.hasOwnProperty(n)?typeof s!="object"||(Array.isArray(s)?s.length:Object.keys(s).length)>0:!1},e.Buffer=function(){try{var u=e.inquire("buffer").Buffer;return u.prototype.utf8Write?u:null}catch{return null}}(),e._Buffer_from=null,e._Buffer_allocUnsafe=null,e.newBuffer=function(u){return typeof u=="number"?e.Buffer?e._Buffer_allocUnsafe(u):new e.Array(u):e.Buffer?e._Buffer_from(u):typeof Uint8Array>"u"?u:new Uint8Array(u)},e.Array=typeof Uint8Array<"u"?Uint8Array:Array,e.Long=e.global.dcodeIO&&e.global.dcodeIO.Long||e.global.Long||e.inquire("long"),e.key2Re=/^true|false|0|1$/,e.key32Re=/^-?(?:0|[1-9][0-9]*)$/,e.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,e.longToHash=function(u){return u?e.LongBits.from(u).toHash():e.LongBits.zeroHash},e.longFromHash=function(u,n){var s=e.LongBits.fromHash(u);return e.Long?e.Long.fromBits(s.lo,s.hi,n):s.toNumber(!!n)};function o(u,n,s){for(var c=Object.keys(n),d=0;d-1;--d)if(n[c[d]]===1&&this[c[d]]!==void 0&&this[c[d]]!==null)return c[d]}},e.oneOfSetter=function(u){return function(n){for(var s=0;s{e.exports=a;var o=Xt(),i,u=o.LongBits,n=o.base64,s=o.utf8;function c(T,E,M){this.fn=T,this.len=E,this.next=void 0,this.val=M}function d(){}function r(T){this.head=T.head,this.tail=T.tail,this.len=T.len,this.next=T.states}function a(){this.len=0,this.head=new c(d,0,0),this.tail=this.head,this.states=null}var l=function(){return o.Buffer?function(){return(a.create=function(){return new i})()}:function(){return new a}};a.create=l(),a.alloc=function(T){return new o.Array(T)},o.Array!==Array&&(a.alloc=o.pool(a.alloc,o.Array.prototype.subarray)),a.prototype._push=function(T,E,M){return this.tail=this.tail.next=new c(T,E,M),this.len+=E,this};function h(T,E,M){E[M]=T&255}function f(T,E,M){for(;T>127;)E[M++]=T&127|128,T>>>=7;E[M]=T}function m(T,E){this.len=T,this.next=void 0,this.val=E}m.prototype=Object.create(c.prototype),m.prototype.fn=f,a.prototype.uint32=function(T){return this.len+=(this.tail=this.tail.next=new m((T=T>>>0)<128?1:T<16384?2:T<2097152?3:T<268435456?4:5,T)).len,this},a.prototype.int32=function(T){return T<0?this._push(g,10,u.fromNumber(T)):this.uint32(T)},a.prototype.sint32=function(T){return this.uint32((T<<1^T>>31)>>>0)};function g(T,E,M){for(;T.hi;)E[M++]=T.lo&127|128,T.lo=(T.lo>>>7|T.hi<<25)>>>0,T.hi>>>=7;for(;T.lo>127;)E[M++]=T.lo&127|128,T.lo=T.lo>>>7;E[M++]=T.lo}a.prototype.uint64=function(T){var E=u.from(T);return this._push(g,E.length(),E)},a.prototype.int64=a.prototype.uint64,a.prototype.sint64=function(T){var E=u.from(T).zzEncode();return this._push(g,E.length(),E)},a.prototype.bool=function(T){return this._push(h,1,T?1:0)};function b(T,E,M){E[M]=T&255,E[M+1]=T>>>8&255,E[M+2]=T>>>16&255,E[M+3]=T>>>24}a.prototype.fixed32=function(T){return this._push(b,4,T>>>0)},a.prototype.sfixed32=a.prototype.fixed32,a.prototype.fixed64=function(T){var E=u.from(T);return this._push(b,4,E.lo)._push(b,4,E.hi)},a.prototype.sfixed64=a.prototype.fixed64,a.prototype.float=function(T){return this._push(o.float.writeFloatLE,4,T)},a.prototype.double=function(T){return this._push(o.float.writeDoubleLE,8,T)};var v=o.Array.prototype.set?function(T,E,M){E.set(T,M)}:function(T,E,M){for(var F=0;F>>0;if(!E)return this._push(h,1,0);if(o.isString(T)){var M=a.alloc(E=n.length(T));n.decode(T,M,0),T=M}return this.uint32(E)._push(v,E,T)},a.prototype.string=function(T){var E=s.length(T);return E?this.uint32(E)._push(s.write,E,T):this._push(h,1,0)},a.prototype.fork=function(){return this.states=new r(this),this.head=this.tail=new c(d,0,0),this.len=0,this},a.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(d,0,0),this.len=0),this},a.prototype.ldelim=function(){var T=this.head,E=this.tail,M=this.len;return this.reset().uint32(M),M&&(this.tail.next=T.next,this.tail=E,this.len+=M),this},a.prototype.finish=function(){for(var T=this.head.next,E=this.constructor.alloc(this.len),M=0;T;)T.fn(T.val,E,M),M+=T.len,T=T.next;return E},a._configure=function(T){i=T,a.create=l(),i._configure()}}),fu=me((t,e)=>{e.exports=u;var o=li();(u.prototype=Object.create(o.prototype)).constructor=u;var i=Xt();function u(){o.call(this)}u._configure=function(){u.alloc=i._Buffer_allocUnsafe,u.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&i.Buffer.prototype.set.name==="set"?function(s,c,d){c.set(s,d)}:function(s,c,d){if(s.copy)s.copy(c,d,0,s.length);else for(var r=0;r>>0;return this.uint32(c),c&&this._push(u.writeBytesBuffer,c,s),this};function n(s,c,d){s.length<40?i.utf8.write(s,c,d):c.utf8Write?c.utf8Write(s,d):c.write(s,d)}u.prototype.string=function(s){var c=i.Buffer.byteLength(s);return this.uint32(c),c&&this._push(n,c,s),this},u._configure()}),pi=me((t,e)=>{e.exports=c;var o=Xt(),i,u=o.LongBits,n=o.utf8;function s(f,m){return RangeError("index out of range: "+f.pos+" + "+(m||1)+" > "+f.len)}function c(f){this.buf=f,this.pos=0,this.len=f.length}var d=typeof Uint8Array<"u"?function(f){if(f instanceof Uint8Array||Array.isArray(f))return new c(f);throw Error("illegal buffer")}:function(f){if(Array.isArray(f))return new c(f);throw Error("illegal buffer")},r=function(){return o.Buffer?function(f){return(c.create=function(m){return o.Buffer.isBuffer(m)?new i(m):d(m)})(f)}:d};c.create=r(),c.prototype._slice=o.Array.prototype.subarray||o.Array.prototype.slice,c.prototype.uint32=function(){var f=4294967295;return function(){if(f=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(f=(f|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(f=(f|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(f=(f|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(f=(f|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return f;if((this.pos+=5)>this.len)throw this.pos=this.len,s(this,10);return f}}(),c.prototype.int32=function(){return this.uint32()|0},c.prototype.sint32=function(){var f=this.uint32();return f>>>1^-(f&1)|0};function a(){var f=new u(0,0),m=0;if(this.len-this.pos>4){for(;m<4;++m)if(f.lo=(f.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return f;if(f.lo=(f.lo|(this.buf[this.pos]&127)<<28)>>>0,f.hi=(f.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return f;m=0}else{for(;m<3;++m){if(this.pos>=this.len)throw s(this);if(f.lo=(f.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return f}return f.lo=(f.lo|(this.buf[this.pos++]&127)<>>0,f}if(this.len-this.pos>4){for(;m<5;++m)if(f.hi=(f.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return f}else for(;m<5;++m){if(this.pos>=this.len)throw s(this);if(f.hi=(f.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return f}throw Error("invalid varint encoding")}c.prototype.bool=function(){return this.uint32()!==0};function l(f,m){return(f[m-4]|f[m-3]<<8|f[m-2]<<16|f[m-1]<<24)>>>0}c.prototype.fixed32=function(){if(this.pos+4>this.len)throw s(this,4);return l(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw s(this,4);return l(this.buf,this.pos+=4)|0};function h(){if(this.pos+8>this.len)throw s(this,8);return new u(l(this.buf,this.pos+=4),l(this.buf,this.pos+=4))}c.prototype.float=function(){if(this.pos+4>this.len)throw s(this,4);var f=o.float.readFloatLE(this.buf,this.pos);return this.pos+=4,f},c.prototype.double=function(){if(this.pos+8>this.len)throw s(this,4);var f=o.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,f},c.prototype.bytes=function(){var f=this.uint32(),m=this.pos,g=this.pos+f;if(g>this.len)throw s(this,f);return this.pos+=f,Array.isArray(this.buf)?this.buf.slice(m,g):m===g?new this.buf.constructor(0):this._slice.call(this.buf,m,g)},c.prototype.string=function(){var f=this.bytes();return n.read(f,0,f.length)},c.prototype.skip=function(f){if(typeof f=="number"){if(this.pos+f>this.len)throw s(this,f);this.pos+=f}else do if(this.pos>=this.len)throw s(this);while(this.buf[this.pos++]&128);return this},c.prototype.skipType=function(f){switch(f){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(f=this.uint32()&7)!==4;)this.skipType(f);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+f+" at offset "+this.pos)}return this},c._configure=function(f){i=f,c.create=r(),i._configure();var m=o.Long?"toLong":"toNumber";o.merge(c.prototype,{int64:function(){return a.call(this)[m](!1)},uint64:function(){return a.call(this)[m](!0)},sint64:function(){return a.call(this).zzDecode()[m](!1)},fixed64:function(){return h.call(this)[m](!0)},sfixed64:function(){return h.call(this)[m](!1)}})}}),Tu=me((t,e)=>{e.exports=u;var o=pi();(u.prototype=Object.create(o.prototype)).constructor=u;var i=Xt();function u(n){o.call(this,n)}u._configure=function(){i.Buffer&&(u.prototype._slice=i.Buffer.prototype.slice)},u.prototype.string=function(){var n=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+n,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+n,this.len))},u._configure()}),vu=me((t,e)=>{e.exports=i;var o=Xt();(i.prototype=Object.create(o.EventEmitter.prototype)).constructor=i;function i(u,n,s){if(typeof u!="function")throw TypeError("rpcImpl must be a function");o.EventEmitter.call(this),this.rpcImpl=u,this.requestDelimited=!!n,this.responseDelimited=!!s}i.prototype.rpcCall=function u(n,s,c,d,r){if(!d)throw TypeError("request must be specified");var a=this;if(!r)return o.asPromise(u,a,n,s,c,d);if(!a.rpcImpl){setTimeout(function(){r(Error("already ended"))},0);return}try{return a.rpcImpl(n,s[a.requestDelimited?"encodeDelimited":"encode"](d).finish(),function(l,h){if(l)return a.emit("error",l,n),r(l);if(h===null){a.end(!0);return}if(!(h instanceof c))try{h=c[a.responseDelimited?"decodeDelimited":"decode"](h)}catch(f){return a.emit("error",f,n),r(f)}return a.emit("data",h,n),r(null,h)})}catch(l){a.emit("error",l,n),setTimeout(function(){r(l)},0);return}},i.prototype.end=function(u){return this.rpcImpl&&(u||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}}),_u=me(t=>{var e=t;e.Service=vu()}),Iu=me((t,e)=>{e.exports={}}),Pu=me(t=>{var e=t;e.build="minimal",e.Writer=li(),e.BufferWriter=fu(),e.Reader=pi(),e.BufferReader=Tu(),e.util=Xt(),e.rpc=_u(),e.roots=Iu(),e.configure=o;function o(){e.util._configure(),e.Writer._configure(e.BufferWriter),e.Reader._configure(e.BufferReader)}o()}),Du=me((t,e)=>{e.exports=Pu()}),$r=me((t,e)=>{var o=Du(),i=o.Reader,u=o.Writer,n=o.util,s=o.roots.default||(o.roots.default={});s.onnx=function(){var c={};return c.Version=function(){var d={},r=Object.create(d);return r[d[0]="_START_VERSION"]=0,r[d[1]="IR_VERSION_2017_10_10"]=1,r[d[2]="IR_VERSION_2017_10_30"]=2,r[d[3]="IR_VERSION_2017_11_3"]=3,r[d[4]="IR_VERSION_2019_1_22"]=4,r[d[5]="IR_VERSION_2019_3_18"]=5,r[d[6]="IR_VERSION_2019_9_19"]=6,r[d[7]="IR_VERSION_2020_5_8"]=7,r[d[8]="IR_VERSION_2021_7_30"]=8,r[d[9]="IR_VERSION"]=9,r}(),c.AttributeProto=function(){function d(r){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],this.sparseTensors=[],this.typeProtos=[],r)for(var a=Object.keys(r),l=0;l>>3){case 1:{h.name=r.string();break}case 21:{h.refAttrName=r.string();break}case 13:{h.docString=r.string();break}case 20:{h.type=r.int32();break}case 2:{h.f=r.float();break}case 3:{h.i=r.int64();break}case 4:{h.s=r.bytes();break}case 5:{h.t=s.onnx.TensorProto.decode(r,r.uint32());break}case 6:{h.g=s.onnx.GraphProto.decode(r,r.uint32());break}case 22:{h.sparseTensor=s.onnx.SparseTensorProto.decode(r,r.uint32());break}case 14:{h.tp=s.onnx.TypeProto.decode(r,r.uint32());break}case 7:{if(h.floats&&h.floats.length||(h.floats=[]),(f&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.i.high>>>0).toNumber())),r.s!=null&&(typeof r.s=="string"?n.base64.decode(r.s,a.s=n.newBuffer(n.base64.length(r.s)),0):r.s.length>=0&&(a.s=r.s)),r.t!=null){if(typeof r.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");a.t=s.onnx.TensorProto.fromObject(r.t)}if(r.g!=null){if(typeof r.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");a.g=s.onnx.GraphProto.fromObject(r.g)}if(r.sparseTensor!=null){if(typeof r.sparseTensor!="object")throw TypeError(".onnx.AttributeProto.sparseTensor: object expected");a.sparseTensor=s.onnx.SparseTensorProto.fromObject(r.sparseTensor)}if(r.tp!=null){if(typeof r.tp!="object")throw TypeError(".onnx.AttributeProto.tp: object expected");a.tp=s.onnx.TypeProto.fromObject(r.tp)}if(r.floats){if(!Array.isArray(r.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");a.floats=[];for(var l=0;l>>0,r.ints[l].high>>>0).toNumber())}if(r.strings){if(!Array.isArray(r.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");a.strings=[];for(var l=0;l=0&&(a.strings[l]=r.strings[l])}if(r.tensors){if(!Array.isArray(r.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");a.tensors=[];for(var l=0;l>>0,r.i.high>>>0).toNumber():r.i),r.s!=null&&r.hasOwnProperty("s")&&(l.s=a.bytes===String?n.base64.encode(r.s,0,r.s.length):a.bytes===Array?Array.prototype.slice.call(r.s):r.s),r.t!=null&&r.hasOwnProperty("t")&&(l.t=s.onnx.TensorProto.toObject(r.t,a)),r.g!=null&&r.hasOwnProperty("g")&&(l.g=s.onnx.GraphProto.toObject(r.g,a)),r.floats&&r.floats.length){l.floats=[];for(var f=0;f>>0,r.ints[f].high>>>0).toNumber():r.ints[f]}if(r.strings&&r.strings.length){l.strings=[];for(var f=0;f>>3){case 1:{h.name=r.string();break}case 2:{h.type=s.onnx.TypeProto.decode(r,r.uint32());break}case 3:{h.docString=r.string();break}default:r.skipType(f&7);break}}return h},d.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},d.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.name!=null&&r.hasOwnProperty("name")&&!n.isString(r.name))return"name: string expected";if(r.type!=null&&r.hasOwnProperty("type")){var a=s.onnx.TypeProto.verify(r.type);if(a)return"type."+a}return r.docString!=null&&r.hasOwnProperty("docString")&&!n.isString(r.docString)?"docString: string expected":null},d.fromObject=function(r){if(r instanceof s.onnx.ValueInfoProto)return r;var a=new s.onnx.ValueInfoProto;if(r.name!=null&&(a.name=String(r.name)),r.type!=null){if(typeof r.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");a.type=s.onnx.TypeProto.fromObject(r.type)}return r.docString!=null&&(a.docString=String(r.docString)),a},d.toObject=function(r,a){a||(a={});var l={};return a.defaults&&(l.name="",l.type=null,l.docString=""),r.name!=null&&r.hasOwnProperty("name")&&(l.name=r.name),r.type!=null&&r.hasOwnProperty("type")&&(l.type=s.onnx.TypeProto.toObject(r.type,a)),r.docString!=null&&r.hasOwnProperty("docString")&&(l.docString=r.docString),l},d.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},d.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.ValueInfoProto"},d}(),c.NodeProto=function(){function d(r){if(this.input=[],this.output=[],this.attribute=[],r)for(var a=Object.keys(r),l=0;l>>3){case 1:{h.input&&h.input.length||(h.input=[]),h.input.push(r.string());break}case 2:{h.output&&h.output.length||(h.output=[]),h.output.push(r.string());break}case 3:{h.name=r.string();break}case 4:{h.opType=r.string();break}case 7:{h.domain=r.string();break}case 5:{h.attribute&&h.attribute.length||(h.attribute=[]),h.attribute.push(s.onnx.AttributeProto.decode(r,r.uint32()));break}case 6:{h.docString=r.string();break}default:r.skipType(f&7);break}}return h},d.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},d.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.input!=null&&r.hasOwnProperty("input")){if(!Array.isArray(r.input))return"input: array expected";for(var a=0;a>>3){case 1:{h.initialization=s.onnx.GraphProto.decode(r,r.uint32());break}case 2:{h.algorithm=s.onnx.GraphProto.decode(r,r.uint32());break}case 3:{h.initializationBinding&&h.initializationBinding.length||(h.initializationBinding=[]),h.initializationBinding.push(s.onnx.StringStringEntryProto.decode(r,r.uint32()));break}case 4:{h.updateBinding&&h.updateBinding.length||(h.updateBinding=[]),h.updateBinding.push(s.onnx.StringStringEntryProto.decode(r,r.uint32()));break}default:r.skipType(f&7);break}}return h},d.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},d.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.initialization!=null&&r.hasOwnProperty("initialization")){var a=s.onnx.GraphProto.verify(r.initialization);if(a)return"initialization."+a}if(r.algorithm!=null&&r.hasOwnProperty("algorithm")){var a=s.onnx.GraphProto.verify(r.algorithm);if(a)return"algorithm."+a}if(r.initializationBinding!=null&&r.hasOwnProperty("initializationBinding")){if(!Array.isArray(r.initializationBinding))return"initializationBinding: array expected";for(var l=0;l>>3){case 1:{h.irVersion=r.int64();break}case 8:{h.opsetImport&&h.opsetImport.length||(h.opsetImport=[]),h.opsetImport.push(s.onnx.OperatorSetIdProto.decode(r,r.uint32()));break}case 2:{h.producerName=r.string();break}case 3:{h.producerVersion=r.string();break}case 4:{h.domain=r.string();break}case 5:{h.modelVersion=r.int64();break}case 6:{h.docString=r.string();break}case 7:{h.graph=s.onnx.GraphProto.decode(r,r.uint32());break}case 14:{h.metadataProps&&h.metadataProps.length||(h.metadataProps=[]),h.metadataProps.push(s.onnx.StringStringEntryProto.decode(r,r.uint32()));break}case 20:{h.trainingInfo&&h.trainingInfo.length||(h.trainingInfo=[]),h.trainingInfo.push(s.onnx.TrainingInfoProto.decode(r,r.uint32()));break}case 25:{h.functions&&h.functions.length||(h.functions=[]),h.functions.push(s.onnx.FunctionProto.decode(r,r.uint32()));break}default:r.skipType(f&7);break}}return h},d.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},d.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.irVersion!=null&&r.hasOwnProperty("irVersion")&&!n.isInteger(r.irVersion)&&!(r.irVersion&&n.isInteger(r.irVersion.low)&&n.isInteger(r.irVersion.high)))return"irVersion: integer|Long expected";if(r.opsetImport!=null&&r.hasOwnProperty("opsetImport")){if(!Array.isArray(r.opsetImport))return"opsetImport: array expected";for(var a=0;a>>0,r.irVersion.high>>>0).toNumber())),r.opsetImport){if(!Array.isArray(r.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");a.opsetImport=[];for(var l=0;l>>0,r.modelVersion.high>>>0).toNumber())),r.docString!=null&&(a.docString=String(r.docString)),r.graph!=null){if(typeof r.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");a.graph=s.onnx.GraphProto.fromObject(r.graph)}if(r.metadataProps){if(!Array.isArray(r.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");a.metadataProps=[];for(var l=0;l>>0,r.irVersion.high>>>0).toNumber():r.irVersion),r.producerName!=null&&r.hasOwnProperty("producerName")&&(l.producerName=r.producerName),r.producerVersion!=null&&r.hasOwnProperty("producerVersion")&&(l.producerVersion=r.producerVersion),r.domain!=null&&r.hasOwnProperty("domain")&&(l.domain=r.domain),r.modelVersion!=null&&r.hasOwnProperty("modelVersion")&&(typeof r.modelVersion=="number"?l.modelVersion=a.longs===String?String(r.modelVersion):r.modelVersion:l.modelVersion=a.longs===String?n.Long.prototype.toString.call(r.modelVersion):a.longs===Number?new n.LongBits(r.modelVersion.low>>>0,r.modelVersion.high>>>0).toNumber():r.modelVersion),r.docString!=null&&r.hasOwnProperty("docString")&&(l.docString=r.docString),r.graph!=null&&r.hasOwnProperty("graph")&&(l.graph=s.onnx.GraphProto.toObject(r.graph,a)),r.opsetImport&&r.opsetImport.length){l.opsetImport=[];for(var f=0;f>>3){case 1:{h.key=r.string();break}case 2:{h.value=r.string();break}default:r.skipType(f&7);break}}return h},d.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},d.verify=function(r){return typeof r!="object"||r===null?"object expected":r.key!=null&&r.hasOwnProperty("key")&&!n.isString(r.key)?"key: string expected":r.value!=null&&r.hasOwnProperty("value")&&!n.isString(r.value)?"value: string expected":null},d.fromObject=function(r){if(r instanceof s.onnx.StringStringEntryProto)return r;var a=new s.onnx.StringStringEntryProto;return r.key!=null&&(a.key=String(r.key)),r.value!=null&&(a.value=String(r.value)),a},d.toObject=function(r,a){a||(a={});var l={};return a.defaults&&(l.key="",l.value=""),r.key!=null&&r.hasOwnProperty("key")&&(l.key=r.key),r.value!=null&&r.hasOwnProperty("value")&&(l.value=r.value),l},d.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},d.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.StringStringEntryProto"},d}(),c.TensorAnnotation=function(){function d(r){if(this.quantParameterTensorNames=[],r)for(var a=Object.keys(r),l=0;l>>3){case 1:{h.tensorName=r.string();break}case 2:{h.quantParameterTensorNames&&h.quantParameterTensorNames.length||(h.quantParameterTensorNames=[]),h.quantParameterTensorNames.push(s.onnx.StringStringEntryProto.decode(r,r.uint32()));break}default:r.skipType(f&7);break}}return h},d.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},d.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.tensorName!=null&&r.hasOwnProperty("tensorName")&&!n.isString(r.tensorName))return"tensorName: string expected";if(r.quantParameterTensorNames!=null&&r.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(r.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var a=0;a>>3){case 1:{h.node&&h.node.length||(h.node=[]),h.node.push(s.onnx.NodeProto.decode(r,r.uint32()));break}case 2:{h.name=r.string();break}case 5:{h.initializer&&h.initializer.length||(h.initializer=[]),h.initializer.push(s.onnx.TensorProto.decode(r,r.uint32()));break}case 15:{h.sparseInitializer&&h.sparseInitializer.length||(h.sparseInitializer=[]),h.sparseInitializer.push(s.onnx.SparseTensorProto.decode(r,r.uint32()));break}case 10:{h.docString=r.string();break}case 11:{h.input&&h.input.length||(h.input=[]),h.input.push(s.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 12:{h.output&&h.output.length||(h.output=[]),h.output.push(s.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 13:{h.valueInfo&&h.valueInfo.length||(h.valueInfo=[]),h.valueInfo.push(s.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 14:{h.quantizationAnnotation&&h.quantizationAnnotation.length||(h.quantizationAnnotation=[]),h.quantizationAnnotation.push(s.onnx.TensorAnnotation.decode(r,r.uint32()));break}default:r.skipType(f&7);break}}return h},d.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},d.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.node!=null&&r.hasOwnProperty("node")){if(!Array.isArray(r.node))return"node: array expected";for(var a=0;a>>3){case 1:{if(h.dims&&h.dims.length||(h.dims=[]),(f&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.dims[l].high>>>0).toNumber())}if(r.dataType!=null&&(a.dataType=r.dataType|0),r.segment!=null){if(typeof r.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");a.segment=s.onnx.TensorProto.Segment.fromObject(r.segment)}if(r.floatData){if(!Array.isArray(r.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");a.floatData=[];for(var l=0;l=0&&(a.stringData[l]=r.stringData[l])}if(r.int64Data){if(!Array.isArray(r.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");a.int64Data=[];for(var l=0;l>>0,r.int64Data[l].high>>>0).toNumber())}if(r.name!=null&&(a.name=String(r.name)),r.docString!=null&&(a.docString=String(r.docString)),r.rawData!=null&&(typeof r.rawData=="string"?n.base64.decode(r.rawData,a.rawData=n.newBuffer(n.base64.length(r.rawData)),0):r.rawData.length>=0&&(a.rawData=r.rawData)),r.externalData){if(!Array.isArray(r.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");a.externalData=[];for(var l=0;l>>0,r.uint64Data[l].high>>>0).toNumber(!0))}return a},d.toObject=function(r,a){a||(a={});var l={};if((a.arrays||a.defaults)&&(l.dims=[],l.floatData=[],l.int32Data=[],l.stringData=[],l.int64Data=[],l.doubleData=[],l.uint64Data=[],l.externalData=[]),a.defaults&&(l.dataType=0,l.segment=null,l.name="",a.bytes===String?l.rawData="":(l.rawData=[],a.bytes!==Array&&(l.rawData=n.newBuffer(l.rawData))),l.docString="",l.dataLocation=a.enums===String?"DEFAULT":0),r.dims&&r.dims.length){l.dims=[];for(var h=0;h>>0,r.dims[h].high>>>0).toNumber():r.dims[h]}if(r.dataType!=null&&r.hasOwnProperty("dataType")&&(l.dataType=r.dataType),r.segment!=null&&r.hasOwnProperty("segment")&&(l.segment=s.onnx.TensorProto.Segment.toObject(r.segment,a)),r.floatData&&r.floatData.length){l.floatData=[];for(var h=0;h>>0,r.int64Data[h].high>>>0).toNumber():r.int64Data[h]}if(r.name!=null&&r.hasOwnProperty("name")&&(l.name=r.name),r.rawData!=null&&r.hasOwnProperty("rawData")&&(l.rawData=a.bytes===String?n.base64.encode(r.rawData,0,r.rawData.length):a.bytes===Array?Array.prototype.slice.call(r.rawData):r.rawData),r.doubleData&&r.doubleData.length){l.doubleData=[];for(var h=0;h>>0,r.uint64Data[h].high>>>0).toNumber(!0):r.uint64Data[h]}if(r.docString!=null&&r.hasOwnProperty("docString")&&(l.docString=r.docString),r.externalData&&r.externalData.length){l.externalData=[];for(var h=0;h>>3){case 1:{f.begin=a.int64();break}case 2:{f.end=a.int64();break}default:a.skipType(m&7);break}}return f},r.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},r.verify=function(a){return typeof a!="object"||a===null?"object expected":a.begin!=null&&a.hasOwnProperty("begin")&&!n.isInteger(a.begin)&&!(a.begin&&n.isInteger(a.begin.low)&&n.isInteger(a.begin.high))?"begin: integer|Long expected":a.end!=null&&a.hasOwnProperty("end")&&!n.isInteger(a.end)&&!(a.end&&n.isInteger(a.end.low)&&n.isInteger(a.end.high))?"end: integer|Long expected":null},r.fromObject=function(a){if(a instanceof s.onnx.TensorProto.Segment)return a;var l=new s.onnx.TensorProto.Segment;return a.begin!=null&&(n.Long?(l.begin=n.Long.fromValue(a.begin)).unsigned=!1:typeof a.begin=="string"?l.begin=parseInt(a.begin,10):typeof a.begin=="number"?l.begin=a.begin:typeof a.begin=="object"&&(l.begin=new n.LongBits(a.begin.low>>>0,a.begin.high>>>0).toNumber())),a.end!=null&&(n.Long?(l.end=n.Long.fromValue(a.end)).unsigned=!1:typeof a.end=="string"?l.end=parseInt(a.end,10):typeof a.end=="number"?l.end=a.end:typeof a.end=="object"&&(l.end=new n.LongBits(a.end.low>>>0,a.end.high>>>0).toNumber())),l},r.toObject=function(a,l){l||(l={});var h={};if(l.defaults){if(n.Long){var f=new n.Long(0,0,!1);h.begin=l.longs===String?f.toString():l.longs===Number?f.toNumber():f}else h.begin=l.longs===String?"0":0;if(n.Long){var f=new n.Long(0,0,!1);h.end=l.longs===String?f.toString():l.longs===Number?f.toNumber():f}else h.end=l.longs===String?"0":0}return a.begin!=null&&a.hasOwnProperty("begin")&&(typeof a.begin=="number"?h.begin=l.longs===String?String(a.begin):a.begin:h.begin=l.longs===String?n.Long.prototype.toString.call(a.begin):l.longs===Number?new n.LongBits(a.begin.low>>>0,a.begin.high>>>0).toNumber():a.begin),a.end!=null&&a.hasOwnProperty("end")&&(typeof a.end=="number"?h.end=l.longs===String?String(a.end):a.end:h.end=l.longs===String?n.Long.prototype.toString.call(a.end):l.longs===Number?new n.LongBits(a.end.low>>>0,a.end.high>>>0).toNumber():a.end),h},r.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},r.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TensorProto.Segment"},r}(),d.DataLocation=function(){var r={},a=Object.create(r);return a[r[0]="DEFAULT"]=0,a[r[1]="EXTERNAL"]=1,a}(),d}(),c.SparseTensorProto=function(){function d(r){if(this.dims=[],r)for(var a=Object.keys(r),l=0;l>>3){case 1:{h.values=s.onnx.TensorProto.decode(r,r.uint32());break}case 2:{h.indices=s.onnx.TensorProto.decode(r,r.uint32());break}case 3:{if(h.dims&&h.dims.length||(h.dims=[]),(f&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.dims[l].high>>>0).toNumber())}return a},d.toObject=function(r,a){a||(a={});var l={};if((a.arrays||a.defaults)&&(l.dims=[]),a.defaults&&(l.values=null,l.indices=null),r.values!=null&&r.hasOwnProperty("values")&&(l.values=s.onnx.TensorProto.toObject(r.values,a)),r.indices!=null&&r.hasOwnProperty("indices")&&(l.indices=s.onnx.TensorProto.toObject(r.indices,a)),r.dims&&r.dims.length){l.dims=[];for(var h=0;h>>0,r.dims[h].high>>>0).toNumber():r.dims[h]}return l},d.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},d.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.SparseTensorProto"},d}(),c.TensorShapeProto=function(){function d(r){if(this.dim=[],r)for(var a=Object.keys(r),l=0;l>>3){case 1:{h.dim&&h.dim.length||(h.dim=[]),h.dim.push(s.onnx.TensorShapeProto.Dimension.decode(r,r.uint32()));break}default:r.skipType(f&7);break}}return h},d.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},d.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.dim!=null&&r.hasOwnProperty("dim")){if(!Array.isArray(r.dim))return"dim: array expected";for(var a=0;a>>3){case 1:{m.dimValue=l.int64();break}case 2:{m.dimParam=l.string();break}case 3:{m.denotation=l.string();break}default:l.skipType(g&7);break}}return m},r.decodeDelimited=function(l){return l instanceof i||(l=new i(l)),this.decode(l,l.uint32())},r.verify=function(l){if(typeof l!="object"||l===null)return"object expected";var h={};if(l.dimValue!=null&&l.hasOwnProperty("dimValue")&&(h.value=1,!n.isInteger(l.dimValue)&&!(l.dimValue&&n.isInteger(l.dimValue.low)&&n.isInteger(l.dimValue.high))))return"dimValue: integer|Long expected";if(l.dimParam!=null&&l.hasOwnProperty("dimParam")){if(h.value===1)return"value: multiple values";if(h.value=1,!n.isString(l.dimParam))return"dimParam: string expected"}return l.denotation!=null&&l.hasOwnProperty("denotation")&&!n.isString(l.denotation)?"denotation: string expected":null},r.fromObject=function(l){if(l instanceof s.onnx.TensorShapeProto.Dimension)return l;var h=new s.onnx.TensorShapeProto.Dimension;return l.dimValue!=null&&(n.Long?(h.dimValue=n.Long.fromValue(l.dimValue)).unsigned=!1:typeof l.dimValue=="string"?h.dimValue=parseInt(l.dimValue,10):typeof l.dimValue=="number"?h.dimValue=l.dimValue:typeof l.dimValue=="object"&&(h.dimValue=new n.LongBits(l.dimValue.low>>>0,l.dimValue.high>>>0).toNumber())),l.dimParam!=null&&(h.dimParam=String(l.dimParam)),l.denotation!=null&&(h.denotation=String(l.denotation)),h},r.toObject=function(l,h){h||(h={});var f={};return h.defaults&&(f.denotation=""),l.dimValue!=null&&l.hasOwnProperty("dimValue")&&(typeof l.dimValue=="number"?f.dimValue=h.longs===String?String(l.dimValue):l.dimValue:f.dimValue=h.longs===String?n.Long.prototype.toString.call(l.dimValue):h.longs===Number?new n.LongBits(l.dimValue.low>>>0,l.dimValue.high>>>0).toNumber():l.dimValue,h.oneofs&&(f.value="dimValue")),l.dimParam!=null&&l.hasOwnProperty("dimParam")&&(f.dimParam=l.dimParam,h.oneofs&&(f.value="dimParam")),l.denotation!=null&&l.hasOwnProperty("denotation")&&(f.denotation=l.denotation),f},r.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},r.getTypeUrl=function(l){return l===void 0&&(l="type.googleapis.com"),l+"/onnx.TensorShapeProto.Dimension"},r}(),d}(),c.TypeProto=function(){function d(a){if(a)for(var l=Object.keys(a),h=0;h>>3){case 1:{f.tensorType=s.onnx.TypeProto.Tensor.decode(a,a.uint32());break}case 4:{f.sequenceType=s.onnx.TypeProto.Sequence.decode(a,a.uint32());break}case 5:{f.mapType=s.onnx.TypeProto.Map.decode(a,a.uint32());break}case 9:{f.optionalType=s.onnx.TypeProto.Optional.decode(a,a.uint32());break}case 8:{f.sparseTensorType=s.onnx.TypeProto.SparseTensor.decode(a,a.uint32());break}case 6:{f.denotation=a.string();break}default:a.skipType(m&7);break}}return f},d.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},d.verify=function(a){if(typeof a!="object"||a===null)return"object expected";var l={};if(a.tensorType!=null&&a.hasOwnProperty("tensorType")){l.value=1;{var h=s.onnx.TypeProto.Tensor.verify(a.tensorType);if(h)return"tensorType."+h}}if(a.sequenceType!=null&&a.hasOwnProperty("sequenceType")){if(l.value===1)return"value: multiple values";l.value=1;{var h=s.onnx.TypeProto.Sequence.verify(a.sequenceType);if(h)return"sequenceType."+h}}if(a.mapType!=null&&a.hasOwnProperty("mapType")){if(l.value===1)return"value: multiple values";l.value=1;{var h=s.onnx.TypeProto.Map.verify(a.mapType);if(h)return"mapType."+h}}if(a.optionalType!=null&&a.hasOwnProperty("optionalType")){if(l.value===1)return"value: multiple values";l.value=1;{var h=s.onnx.TypeProto.Optional.verify(a.optionalType);if(h)return"optionalType."+h}}if(a.sparseTensorType!=null&&a.hasOwnProperty("sparseTensorType")){if(l.value===1)return"value: multiple values";l.value=1;{var h=s.onnx.TypeProto.SparseTensor.verify(a.sparseTensorType);if(h)return"sparseTensorType."+h}}return a.denotation!=null&&a.hasOwnProperty("denotation")&&!n.isString(a.denotation)?"denotation: string expected":null},d.fromObject=function(a){if(a instanceof s.onnx.TypeProto)return a;var l=new s.onnx.TypeProto;if(a.tensorType!=null){if(typeof a.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");l.tensorType=s.onnx.TypeProto.Tensor.fromObject(a.tensorType)}if(a.sequenceType!=null){if(typeof a.sequenceType!="object")throw TypeError(".onnx.TypeProto.sequenceType: object expected");l.sequenceType=s.onnx.TypeProto.Sequence.fromObject(a.sequenceType)}if(a.mapType!=null){if(typeof a.mapType!="object")throw TypeError(".onnx.TypeProto.mapType: object expected");l.mapType=s.onnx.TypeProto.Map.fromObject(a.mapType)}if(a.optionalType!=null){if(typeof a.optionalType!="object")throw TypeError(".onnx.TypeProto.optionalType: object expected");l.optionalType=s.onnx.TypeProto.Optional.fromObject(a.optionalType)}if(a.sparseTensorType!=null){if(typeof a.sparseTensorType!="object")throw TypeError(".onnx.TypeProto.sparseTensorType: object expected");l.sparseTensorType=s.onnx.TypeProto.SparseTensor.fromObject(a.sparseTensorType)}return a.denotation!=null&&(l.denotation=String(a.denotation)),l},d.toObject=function(a,l){l||(l={});var h={};return l.defaults&&(h.denotation=""),a.tensorType!=null&&a.hasOwnProperty("tensorType")&&(h.tensorType=s.onnx.TypeProto.Tensor.toObject(a.tensorType,l),l.oneofs&&(h.value="tensorType")),a.sequenceType!=null&&a.hasOwnProperty("sequenceType")&&(h.sequenceType=s.onnx.TypeProto.Sequence.toObject(a.sequenceType,l),l.oneofs&&(h.value="sequenceType")),a.mapType!=null&&a.hasOwnProperty("mapType")&&(h.mapType=s.onnx.TypeProto.Map.toObject(a.mapType,l),l.oneofs&&(h.value="mapType")),a.denotation!=null&&a.hasOwnProperty("denotation")&&(h.denotation=a.denotation),a.sparseTensorType!=null&&a.hasOwnProperty("sparseTensorType")&&(h.sparseTensorType=s.onnx.TypeProto.SparseTensor.toObject(a.sparseTensorType,l),l.oneofs&&(h.value="sparseTensorType")),a.optionalType!=null&&a.hasOwnProperty("optionalType")&&(h.optionalType=s.onnx.TypeProto.Optional.toObject(a.optionalType,l),l.oneofs&&(h.value="optionalType")),h},d.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},d.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto"},d.Tensor=function(){function a(l){if(l)for(var h=Object.keys(l),f=0;f>>3){case 1:{m.elemType=l.int32();break}case 2:{m.shape=s.onnx.TensorShapeProto.decode(l,l.uint32());break}default:l.skipType(g&7);break}}return m},a.decodeDelimited=function(l){return l instanceof i||(l=new i(l)),this.decode(l,l.uint32())},a.verify=function(l){if(typeof l!="object"||l===null)return"object expected";if(l.elemType!=null&&l.hasOwnProperty("elemType")&&!n.isInteger(l.elemType))return"elemType: integer expected";if(l.shape!=null&&l.hasOwnProperty("shape")){var h=s.onnx.TensorShapeProto.verify(l.shape);if(h)return"shape."+h}return null},a.fromObject=function(l){if(l instanceof s.onnx.TypeProto.Tensor)return l;var h=new s.onnx.TypeProto.Tensor;if(l.elemType!=null&&(h.elemType=l.elemType|0),l.shape!=null){if(typeof l.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");h.shape=s.onnx.TensorShapeProto.fromObject(l.shape)}return h},a.toObject=function(l,h){h||(h={});var f={};return h.defaults&&(f.elemType=0,f.shape=null),l.elemType!=null&&l.hasOwnProperty("elemType")&&(f.elemType=l.elemType),l.shape!=null&&l.hasOwnProperty("shape")&&(f.shape=s.onnx.TensorShapeProto.toObject(l.shape,h)),f},a.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},a.getTypeUrl=function(l){return l===void 0&&(l="type.googleapis.com"),l+"/onnx.TypeProto.Tensor"},a}(),d.Sequence=function(){function a(l){if(l)for(var h=Object.keys(l),f=0;f>>3){case 1:{m.elemType=s.onnx.TypeProto.decode(l,l.uint32());break}default:l.skipType(g&7);break}}return m},a.decodeDelimited=function(l){return l instanceof i||(l=new i(l)),this.decode(l,l.uint32())},a.verify=function(l){if(typeof l!="object"||l===null)return"object expected";if(l.elemType!=null&&l.hasOwnProperty("elemType")){var h=s.onnx.TypeProto.verify(l.elemType);if(h)return"elemType."+h}return null},a.fromObject=function(l){if(l instanceof s.onnx.TypeProto.Sequence)return l;var h=new s.onnx.TypeProto.Sequence;if(l.elemType!=null){if(typeof l.elemType!="object")throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected");h.elemType=s.onnx.TypeProto.fromObject(l.elemType)}return h},a.toObject=function(l,h){h||(h={});var f={};return h.defaults&&(f.elemType=null),l.elemType!=null&&l.hasOwnProperty("elemType")&&(f.elemType=s.onnx.TypeProto.toObject(l.elemType,h)),f},a.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},a.getTypeUrl=function(l){return l===void 0&&(l="type.googleapis.com"),l+"/onnx.TypeProto.Sequence"},a}(),d.Map=function(){function a(l){if(l)for(var h=Object.keys(l),f=0;f>>3){case 1:{m.keyType=l.int32();break}case 2:{m.valueType=s.onnx.TypeProto.decode(l,l.uint32());break}default:l.skipType(g&7);break}}return m},a.decodeDelimited=function(l){return l instanceof i||(l=new i(l)),this.decode(l,l.uint32())},a.verify=function(l){if(typeof l!="object"||l===null)return"object expected";if(l.keyType!=null&&l.hasOwnProperty("keyType")&&!n.isInteger(l.keyType))return"keyType: integer expected";if(l.valueType!=null&&l.hasOwnProperty("valueType")){var h=s.onnx.TypeProto.verify(l.valueType);if(h)return"valueType."+h}return null},a.fromObject=function(l){if(l instanceof s.onnx.TypeProto.Map)return l;var h=new s.onnx.TypeProto.Map;if(l.keyType!=null&&(h.keyType=l.keyType|0),l.valueType!=null){if(typeof l.valueType!="object")throw TypeError(".onnx.TypeProto.Map.valueType: object expected");h.valueType=s.onnx.TypeProto.fromObject(l.valueType)}return h},a.toObject=function(l,h){h||(h={});var f={};return h.defaults&&(f.keyType=0,f.valueType=null),l.keyType!=null&&l.hasOwnProperty("keyType")&&(f.keyType=l.keyType),l.valueType!=null&&l.hasOwnProperty("valueType")&&(f.valueType=s.onnx.TypeProto.toObject(l.valueType,h)),f},a.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},a.getTypeUrl=function(l){return l===void 0&&(l="type.googleapis.com"),l+"/onnx.TypeProto.Map"},a}(),d.Optional=function(){function a(l){if(l)for(var h=Object.keys(l),f=0;f>>3){case 1:{m.elemType=s.onnx.TypeProto.decode(l,l.uint32());break}default:l.skipType(g&7);break}}return m},a.decodeDelimited=function(l){return l instanceof i||(l=new i(l)),this.decode(l,l.uint32())},a.verify=function(l){if(typeof l!="object"||l===null)return"object expected";if(l.elemType!=null&&l.hasOwnProperty("elemType")){var h=s.onnx.TypeProto.verify(l.elemType);if(h)return"elemType."+h}return null},a.fromObject=function(l){if(l instanceof s.onnx.TypeProto.Optional)return l;var h=new s.onnx.TypeProto.Optional;if(l.elemType!=null){if(typeof l.elemType!="object")throw TypeError(".onnx.TypeProto.Optional.elemType: object expected");h.elemType=s.onnx.TypeProto.fromObject(l.elemType)}return h},a.toObject=function(l,h){h||(h={});var f={};return h.defaults&&(f.elemType=null),l.elemType!=null&&l.hasOwnProperty("elemType")&&(f.elemType=s.onnx.TypeProto.toObject(l.elemType,h)),f},a.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},a.getTypeUrl=function(l){return l===void 0&&(l="type.googleapis.com"),l+"/onnx.TypeProto.Optional"},a}(),d.SparseTensor=function(){function a(l){if(l)for(var h=Object.keys(l),f=0;f>>3){case 1:{m.elemType=l.int32();break}case 2:{m.shape=s.onnx.TensorShapeProto.decode(l,l.uint32());break}default:l.skipType(g&7);break}}return m},a.decodeDelimited=function(l){return l instanceof i||(l=new i(l)),this.decode(l,l.uint32())},a.verify=function(l){if(typeof l!="object"||l===null)return"object expected";if(l.elemType!=null&&l.hasOwnProperty("elemType")&&!n.isInteger(l.elemType))return"elemType: integer expected";if(l.shape!=null&&l.hasOwnProperty("shape")){var h=s.onnx.TensorShapeProto.verify(l.shape);if(h)return"shape."+h}return null},a.fromObject=function(l){if(l instanceof s.onnx.TypeProto.SparseTensor)return l;var h=new s.onnx.TypeProto.SparseTensor;if(l.elemType!=null&&(h.elemType=l.elemType|0),l.shape!=null){if(typeof l.shape!="object")throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected");h.shape=s.onnx.TensorShapeProto.fromObject(l.shape)}return h},a.toObject=function(l,h){h||(h={});var f={};return h.defaults&&(f.elemType=0,f.shape=null),l.elemType!=null&&l.hasOwnProperty("elemType")&&(f.elemType=l.elemType),l.shape!=null&&l.hasOwnProperty("shape")&&(f.shape=s.onnx.TensorShapeProto.toObject(l.shape,h)),f},a.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},a.getTypeUrl=function(l){return l===void 0&&(l="type.googleapis.com"),l+"/onnx.TypeProto.SparseTensor"},a}(),d}(),c.OperatorSetIdProto=function(){function d(r){if(r)for(var a=Object.keys(r),l=0;l>>3){case 1:{h.domain=r.string();break}case 2:{h.version=r.int64();break}default:r.skipType(f&7);break}}return h},d.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},d.verify=function(r){return typeof r!="object"||r===null?"object expected":r.domain!=null&&r.hasOwnProperty("domain")&&!n.isString(r.domain)?"domain: string expected":r.version!=null&&r.hasOwnProperty("version")&&!n.isInteger(r.version)&&!(r.version&&n.isInteger(r.version.low)&&n.isInteger(r.version.high))?"version: integer|Long expected":null},d.fromObject=function(r){if(r instanceof s.onnx.OperatorSetIdProto)return r;var a=new s.onnx.OperatorSetIdProto;return r.domain!=null&&(a.domain=String(r.domain)),r.version!=null&&(n.Long?(a.version=n.Long.fromValue(r.version)).unsigned=!1:typeof r.version=="string"?a.version=parseInt(r.version,10):typeof r.version=="number"?a.version=r.version:typeof r.version=="object"&&(a.version=new n.LongBits(r.version.low>>>0,r.version.high>>>0).toNumber())),a},d.toObject=function(r,a){a||(a={});var l={};if(a.defaults)if(l.domain="",n.Long){var h=new n.Long(0,0,!1);l.version=a.longs===String?h.toString():a.longs===Number?h.toNumber():h}else l.version=a.longs===String?"0":0;return r.domain!=null&&r.hasOwnProperty("domain")&&(l.domain=r.domain),r.version!=null&&r.hasOwnProperty("version")&&(typeof r.version=="number"?l.version=a.longs===String?String(r.version):r.version:l.version=a.longs===String?n.Long.prototype.toString.call(r.version):a.longs===Number?new n.LongBits(r.version.low>>>0,r.version.high>>>0).toNumber():r.version),l},d.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},d.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.OperatorSetIdProto"},d}(),c.OperatorStatus=function(){var d={},r=Object.create(d);return r[d[0]="EXPERIMENTAL"]=0,r[d[1]="STABLE"]=1,r}(),c.FunctionProto=function(){function d(r){if(this.input=[],this.output=[],this.attribute=[],this.attributeProto=[],this.node=[],this.opsetImport=[],r)for(var a=Object.keys(r),l=0;l>>3){case 1:{h.name=r.string();break}case 4:{h.input&&h.input.length||(h.input=[]),h.input.push(r.string());break}case 5:{h.output&&h.output.length||(h.output=[]),h.output.push(r.string());break}case 6:{h.attribute&&h.attribute.length||(h.attribute=[]),h.attribute.push(r.string());break}case 11:{h.attributeProto&&h.attributeProto.length||(h.attributeProto=[]),h.attributeProto.push(s.onnx.AttributeProto.decode(r,r.uint32()));break}case 7:{h.node&&h.node.length||(h.node=[]),h.node.push(s.onnx.NodeProto.decode(r,r.uint32()));break}case 8:{h.docString=r.string();break}case 9:{h.opsetImport&&h.opsetImport.length||(h.opsetImport=[]),h.opsetImport.push(s.onnx.OperatorSetIdProto.decode(r,r.uint32()));break}case 10:{h.domain=r.string();break}default:r.skipType(f&7);break}}return h},d.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},d.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.name!=null&&r.hasOwnProperty("name")&&!n.isString(r.name))return"name: string expected";if(r.input!=null&&r.hasOwnProperty("input")){if(!Array.isArray(r.input))return"input: array expected";for(var a=0;a{Wn(),ei(),ye=Er($r()),mr(),cr=class{static arraysEqual(t,e){if(t.length!==e.length)return!1;for(let o=0;o1&&a>1)return;c[s-d]=Math.max(r,a)}return c}static index(e,o){let i=new Array(o.length);return Qt.fillIndex(e,o,i),i}static fillIndex(e,o,i){let u=e.length-o.length;for(let n=0;n=0;T--)r[T]=b%s[T],b=Math.floor(b/s[T]);m||(Qt.fillIndex(r,e.dims,a),h=e.get(a)),g||(Qt.fillIndex(r,o.dims,l),f=o.get(l)),d.set(r,i(h,f))}}return d}}static isValidBroadcast(e,o){let i=e.length,u=o.length;if(i>u)return!1;for(let n=1;n<=i;n++)if(e[i-n]!==1&&e[i-n]!==o[u-n])return!1;return!0}static getBroadcastDims(e,o){let i=e.length,u=[];for(let n=0;n1&&c===1&&u.unshift(s)}return u}},Xn=class{static getShapeOfGemmResult(t,e,o,i,u){if(t.length!==2||o.length!==2)throw new Error("shape need to be of size 2");let n,s,c;e?(n=t[1],s=t[0]):(n=t[0],s=t[1]);let d=-1;if(i?(c=o[0],d=1):(c=o[1],d=0),o[d]!==s)throw new Error("dimension mismatch");if(n<=0||c<=0||s<=0)throw new Error("invalid shape specified");if(u&&!Xe.isValidBroadcast(u,[n,c]))throw new Error("gemm: invalid bias shape for broadcast");return[n,c,s]}},Ve=class wn{static tensorDataTypeFromProto(e){switch(e){case ye.onnx.TensorProto.DataType.INT8:return"int8";case ye.onnx.TensorProto.DataType.UINT8:return"uint8";case ye.onnx.TensorProto.DataType.BOOL:return"bool";case ye.onnx.TensorProto.DataType.INT16:return"int16";case ye.onnx.TensorProto.DataType.UINT16:return"uint16";case ye.onnx.TensorProto.DataType.INT32:return"int32";case ye.onnx.TensorProto.DataType.UINT32:return"uint32";case ye.onnx.TensorProto.DataType.FLOAT:return"float32";case ye.onnx.TensorProto.DataType.DOUBLE:return"float64";case ye.onnx.TensorProto.DataType.STRING:return"string";case ye.onnx.TensorProto.DataType.INT64:return"int32";case ye.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${ye.onnx.TensorProto.DataType[e]}`)}}static tensorDataTypeStringToEnum(e){switch(e){case"int8":return ye.onnx.TensorProto.DataType.INT8;case"uint8":return ye.onnx.TensorProto.DataType.UINT8;case"bool":return ye.onnx.TensorProto.DataType.BOOL;case"int16":return ye.onnx.TensorProto.DataType.INT16;case"uint16":return ye.onnx.TensorProto.DataType.UINT16;case"int32":return ye.onnx.TensorProto.DataType.INT32;case"uint32":return ye.onnx.TensorProto.DataType.UINT32;case"float32":return ye.onnx.TensorProto.DataType.FLOAT;case"float64":return ye.onnx.TensorProto.DataType.DOUBLE;case"string":return ye.onnx.TensorProto.DataType.STRING;case"int64":return ye.onnx.TensorProto.DataType.INT64;case"uint64":return ye.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${e}`)}}static tensorDimsFromProto(e){return e.map(o=>zt.isLong(o)?o.toNumber():o)}static tensorValueTypeFromProto(e){return{tensorType:wn.tensorDataTypeFromProto(e.elemType),shape:{dims:wn.tensorDimsFromProto(e.shape.dim.map(o=>o.dimValue))}}}static tensorDimsFromORTFormat(e){let o=[];for(let i=0;ie.length)throw new Error(`invalid dimension of ${o} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return Tt.getSizeFromDimensionRange(e,o,e.length)}static sizeToDimension(e,o){if(o<0||o>e.length)throw new Error(`invalid dimension of ${o} for sizeToDimension as Tensor has ${e.length} dimensions.`);return Tt.getSizeFromDimensionRange(e,0,o)}static getSizeFromDimensionRange(e,o,i){let u=1;for(let n=o;n=0;--u)i[u]=i[u+1]*e[u+1];return i}static transpose(e){return e.slice().reverse()}static indicesToOffset(e,o,i){i===void 0&&(i=e.length);let u=0;for(let n=0;n=o)throw new Error("unsupported axis for this operation.");return e<0?e+o:e}static normalizeAxes(e,o){return e.map(i=>this.normalizeAxis(i,o))}static incrementIndex(e,o,i){if(o.length===0||e.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(i===void 0)i=o.length;else if(i<=0||i>o.length)throw new Error("Incorrect axis to increment on");for(let u=i-1;u>=0&&(e[u]++,!(e[u]=e.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");u[d]=e[d]}else u[d]=o[d];s*=u[d]}}let c=Tt.size(e);if(n!==-1){if(c%s!==0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${e}] Output shape: [${o}]`);u[n]=c/s}else if(s!==c)throw new Error("reshapedDims and originalDims don't have matching sizes");return u}static sortBasedOnPerm(e,o){return o?o.map(i=>e[i]):e.slice().reverse()}static padShape(e,o){let i=e.length;return e.map((u,n)=>u+o[n]+o[n+i])}static areEqual(e,o){return e.length!==o.length?!1:e.every((i,u)=>i===o[u])}static validateDimsAndCalcSize(e){if(e.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let o=1;for(let i of e){if(!Number.isInteger(i))throw new TypeError(`Invalid shape: ${i} is not an integer`);if(i<0||i>2147483647)throw new TypeError(`Invalid shape: length ${i} is not allowed`);o*=i}return o}static flattenShape(e,o){o<0&&(o+=e.length);let i=e.reduce((n,s)=>n*s,1),u=e.slice(o).reduce((n,s)=>n*s,1);return[i/u,u]}static squeezeShape(e,o){let i=new Array;o=Tt.normalizeAxes(o,e.length);for(let u=0;u=0;if(n&&e[u]!==1)throw new Error("squeeze an axis of size different than 1");(o.length===0&&e[u]>1||o.length>0&&!n)&&i.push(e[u])}return i}static unsqueezeShape(e,o){let i=new Array(e.length+o.length);i.fill(0);for(let n=0;n=i.length)throw new Error("'axes' has an out of range axis");if(i[s]!==0)throw new Error("'axes' has a duplicate axis");i[s]=1}let u=0;for(let n=0;n=i.length?i.push(o[c+2]):i[c]=o[c+2];for(let c=0;c=i[c]||s[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,o,i,u,n,s){if(s){if(n.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(o.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let c=0;c{Cu=Er(_s()),ei(),tn(),te=Er($r()),fe(),mi=W.experimental.fbs,Fe=class qr{constructor(e,o,i,u,n,s=Cu.Guid.create()){this.dims=e,this.type=o,this.dataProvider=i,this.asyncDataProvider=u,this.cache=n,this.dataId=s,this.size=U.validateDimsAndCalcSize(e);let c=this.size,d=i===void 0&&u===void 0&&n===void 0;if(n!==void 0&&n.length!==c)throw new RangeError("Input dims doesn't match data length.");if(o==="string"){if(n!==void 0&&(!Array.isArray(n)||!n.every(r=>typeof r=="string")))throw new TypeError("cache should be a string array");d&&(this.cache=new Array(c))}else{if(n!==void 0){let r=ku(o);if(!(n instanceof r))throw new TypeError(`cache should be type ${r.name}`)}if(d){let r=new ArrayBuffer(c*Vd(o));this.cache=Wd(r,o)}}}get data(){if(this.cache===void 0){let e=this.dataProvider(this.dataId);if(e.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=e}return this.cache}get stringData(){if(this.type!=="string")throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if(this.type!=="string")return this.data;throw new TypeError("type cannot be non-number (string)")}get(e){return this.data[U.indicesToOffset(e,this.strides)]}set(e,o){this.data[U.indicesToOffset(e,this.strides)]=o}async getData(){return this.cache===void 0&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=U.computeStrides(this.dims)),this._strides}static fromProto(e){if(!e)throw new Error("cannot construct Value from an empty tensor");let o=Ve.tensorDataTypeFromProto(e.dataType),i=Ve.tensorDimsFromProto(e.dims),u=new qr(i,o);if(o==="string")e.stringData.forEach((n,s)=>{u.data[s]=sn(n)});else if(e.rawData&&typeof e.rawData.byteLength=="number"&&e.rawData.byteLength>0){let n=u.data,s=new DataView(e.rawData.buffer,e.rawData.byteOffset,e.rawData.byteLength),c=Fu(e.dataType),d=e.rawData.byteLength/c;if(e.rawData.byteLength%c!==0)throw new Error("invalid buffer length");if(n.length!==d)throw new Error("buffer length mismatch");for(let r=0;r0){let n=u.data,s=new DataView(e.rawDataArray().buffer,e.rawDataArray().byteOffset,e.rawDataLength()),c=Fu(e.dataType()),d=e.rawDataLength()/c;if(e.rawDataLength()%c!==0)throw new Error("invalid buffer length");if(n.length!==d)throw new Error("buffer length mismatch");for(let r=0;r{Hd={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},qd={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"}}),ae=L(()=>{});async function gi(t,e=i=>0,o){return new Promise((i,u)=>{let n=0,s=()=>{if(t()){i();return}n++;let c=e(n);if(o!=null&&n>=o){u();return}setTimeout(s,c)};s()})}function Kn(t){return Cr(typeof t<"u"&&t.length!==0,()=>"empty string found for sampler name"),"get"+t.charAt(0).toUpperCase()+t.slice(1)}function Mu(t){return Cr(typeof t<"u"&&t.length!==0,()=>"empty string found for sampler name"),"get"+t.charAt(0).toUpperCase()+t.slice(1)+"AtOutCoords"}function kr(t,e){let o=JSON.parse(JSON.stringify(t));return o=e,o}function Br(t,e){return e.map(o=>t[o]).join(", ")}function Ke(t){if(t<=1)return"int";if(t===2)return"ivec2";if(t===3)return"ivec3";if(t===4)return"ivec4";if(t===5)return"ivec5";if(t===6)return"ivec6";throw Error(`GPU for rank ${t} is not yet supported`)}function St(t=6){return["x","y","z","w","u","v"].slice(0,t)}var Ft=L(()=>{fe()});function jd(t,e){return St(e).map(o=>`${t}.${o}`)}function Nr(t,e){return e===1?[t]:jd(t,e)}function $t(){return` + float getChannel(vec4 frag, int dim) { + int modCoord = imod(dim, 2); + return modCoord == 0 ? frag.r : frag.g; + } + + float getChannel(vec4 frag, vec2 innerDims) { + vec2 modCoord = mod(innerDims, 2.); + return modCoord.x == 0. ? + (modCoord.y == 0. ? frag.r : frag.g) : + (modCoord.y == 0. ? frag.b : frag.a); + } + `}var br=L(()=>{Ft()});function Xd(t,e,o){if(t===0)return"false";if(t===1)return`rc > ${e[0]}`;let i="";for(let u=t-2;u= ${e[u-t+2]}`,u= ${t[0]} ? 0. : getA(rc + 1), + 0, 0`;let i="r, c",u="r, cp1",n="rp1, c",s="rp1, cp1",c="";if(o>2)for(let d=0;d= ${i}; + bool cEdge = cp1 >= ${o}; + `}var Gu,Yd,Uu,zu=L(()=>{xe(),ae(),Ft(),br(),Gu={name:"pack",inputNames:["A"],inputTypes:[1]},Yd=(t,e)=>{let o=q(t.session.backend.glContext.version),i=e.dims,u=i.length,n=e.dims.length,s=Ke(n),c=Nr("rc",n),d=Jd(n,c,i[i.length-2],i[i.length-1]),r;u===0?r=[1,1]:u===1?r=[i[0],1]:r=[i[n-1],i[n-2]];let a=Xd(n,r,c),l=Kd(i,c),h=` + void main() { + ${s} rc = getOutputCoords(); + + if(${a}) { + ${o.output} = vec4(0); + } else { + ${d} + + ${o.output} = vec4(${l}); + } + } + `;return{...Gu,hasMain:!0,output:{dims:e.dims,type:e.type,textureType:2},shaderSource:h}},Uu=(t,e)=>({...Gu,get:()=>Yd(t,e)})});function yi(t){if(t.length===0)return[1,1,1];let e=1;for(let o=0;o1?t[t.length-2]:1,t[t.length-1]]}function Wu(t,e){let o=!1;return t.length===0||e.length===0?o=!0:t.length<2||e.length<2?o=t[t.length-1]===e[e.length-1]:o=t[t.length-1]===e[e.length-1]&&t[t.length-2]===e[e.length-2],o}function eh(t){let e=U.computeStrides(t),o=["b","r","c"],i="index";return` + ivec3 inputCoordsFromReshapedOutCoords(int index) { + ${e.map((u,n)=>{let s=`int ${o[n]} = ${i} / ${u}`,c=n===e.length-1?`int ${o[n+1]} = ${i} - ${o[n]} * ${u}`:`index -= ${o[n]} * ${u}`;return`${s}; ${c};`}).join("")} + return ivec3(b, r, c); + } + `}function th(t){let e=U.computeStrides(t);return` + int getFlattenedIndex(ivec3 coords) { + // reverse y, z order + return coords.x * ${e[0]} + coords.z * ${e[1]} + coords.y; + } +`}var Zd,Qd,Vu,Hu=L(()=>{fe(),xe(),ae(),br(),Zd=t=>({name:"Reshape (packed)",inputTypes:[2],inputNames:["A"],cacheHint:`${t}`}),Qd=(t,e,o,i)=>{let u=e.dims,n=i,s="";for(let r=0;r<4;r++){let a="";switch(r){case 0:a="outputCoords = rc;";break;case 1:a="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:a="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:a="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}s+=` + ${a} + ${r>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""} + int flattenedIndex = getFlattenedIndex(outputCoords); + + ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex); + vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z)); + + result[${r}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); + + ${r>0?"}":""} + `}let c=q(t.session.backend.glContext.version),d=` + ${eh(u)} + ${th(n)} + ${$t()} + + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0.0); + + ivec3 outputCoords; + int rows = ${n[2]}; + int cols = ${n[1]}; + + ${s} + ${c.output} = result; + } + `;return{...o,output:{dims:n,type:e.type,textureType:2},shaderSource:d,hasMain:!0}},Vu=(t,e,o)=>{let i=Zd(o);return{...i,get:()=>Qd(t,e,i,o)}}}),Ti,qu=L(()=>{xe(),ae(),Ti=(t,e)=>{let o=e.shape,i=q(t.session.backend.glContext.version),u=` + const float FLOAT_MAX = 1.70141184e38; + const float FLOAT_MIN = 1.17549435e-38; + + bool isNaN(float val) { + return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true; + } + + highp vec4 encodeAsUint8(highp float v) { + if (isNaN(v)) { + return vec4(255, 255, 255, 255); + } + + highp float av = abs(v); + + if(av < FLOAT_MIN) { + return vec4(0.0, 0.0, 0.0, 0.0); + } else if(v > FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; + } else if(v < -FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; + } + + highp vec4 c = vec4(0,0,0,0); + + highp float e = floor(log2(av)); + highp float m = exp2(fract(log2(av))) - 1.0; + + c[2] = floor(128.0 * m); + m -= c[2] / 128.0; + c[1] = floor(32768.0 * m); + m -= c[1] / 32768.0; + c[0] = floor(8388608.0 * m); + + highp float ebias = e + 127.0; + c[3] = floor(ebias / 2.0); + ebias -= c[3] * 2.0; + c[2] += floor(ebias) * 128.0; + + c[3] += 128.0 * step(0.0, -v); + + return c / 255.0; + } + + void main() { + float value = ${i.texture2D}(X,TexCoords).r; + ${i.output} = encodeAsUint8(value); + }`,n={name:"Uint8Encode",inputTypes:[0],inputNames:["X"],output:{dims:o,type:e.tensor.type,textureType:3},shaderSource:u,hasMain:!0};return t.executeProgram(n,[e.tensor])}});function nh(t,e){if(t===1)return"rc";let o="";for(let i=0;i{xe(),ae(),Ft(),br(),ju={name:"unpack",inputNames:["A"],inputTypes:[2]},rh=(t,e)=>{let o=e.dims.length,i=Nr("rc",o),u=i.slice(-2),n=Ke(o),s=$t(),c=e.dims.length===0?"":nh(o,i),d=o<=1?"rc":`vec2(${u.join(",")})`,r=q(t.session.backend.glContext.version),a=` + ${s} + void main() { + ${n} rc = getOutputCoords(); + + // Sample the texture with the coords to get the rgba channel value. + vec4 packedInput = getA(${c}); + + ${r.output} = vec4(getChannel(packedInput, ${d}), 0, 0, 0); + } + `;return{...ju,hasMain:!0,output:{dims:e.dims,type:e.type,textureType:0},shaderSource:a}},Yu=(t,e)=>({...ju,get:()=>rh(t,e)})}),Jn,un,Zn,ln=L(()=>{ut(),Jn=class{constructor(t,e=1){if(e===1)this.internalFormat=t.R32F,this.format=t.RED,this.textureType=t.FLOAT,this.channelSize=e;else if(e===4)this.internalFormat=t.RGBA32F,this.format=t.RGBA,this.textureType=t.FLOAT,this.channelSize=e;else throw new Error(`Invalid number of channels: ${e}`)}encode(t,e){let o,i;return t.constructor!==Float32Array&&(ce.warning("Encoder","data was not of type Float32; creating new Float32Array"),i=new Float32Array(t)),e*this.channelSize>t.length?(ce.warning("Encoder","Source data too small. Allocating larger array"),i=t,o=this.allocate(e*this.channelSize),i.forEach((u,n)=>o[n]=u)):(i=t,o=i),o}allocate(t){return new Float32Array(t*4)}decode(t,e){return this.channelSize===1?t.filter((o,i)=>i%4===0).subarray(0,e):t.subarray(0,e)}},un=class{constructor(t,e=1,o){if(e!==1&&e!==4)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA,this.format=t.RGBA,this.channelSize=e,this.textureType=o||t.FLOAT}encode(t,e){let o=t;return this.channelSize===1&&(ce.verbose("Encoder","Exploding into a larger array"),o=this.allocate(e),t.forEach((i,u)=>o[u*4]=i)),o}allocate(t){return new Float32Array(t*4)}decode(t,e){return this.channelSize===1?t.filter((o,i)=>i%4===0).subarray(0,e):t.subarray(0,e)}},Zn=class{constructor(t,e=1){if(this.channelSize=4,e===1)this.internalFormat=t.ALPHA,this.format=t.ALPHA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e;else if(e===4)this.internalFormat=t.RGBA,this.format=t.RGBA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e;else throw new Error(`Invalid number of channels: ${e}`)}encode(t,e){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}allocate(t){return new Uint8Array(t*this.channelSize)}decode(t,e){if(t instanceof Uint8Array)return t.subarray(0,e);throw new Error(`Invalid array type: ${t.constructor}`)}}}),fn,Ku,xi,Ju=L(()=>{fe(),ae(),fn=(t,e,o)=>{let i=o===0||o===1?1:4,u=o===2,n=o===1||o===2,s=o===4?e.length-1:void 0,c=o===4?e.map((d,r)=>r===e.length-1?d*4:d):void 0;return xi(t,e,i,c,{isPacked:u,reverseWH:n,breakAxis:s})},Ku=(t,e,o)=>{let i=fn(t,e,o);return[i.width,i.height]},xi=(t,e,o=1,i,u)=>{let n=!!(u&&u.isPacked),[s,c]=t.computeTextureWH(n&&i||e,u),d=e.length,r=e.slice(0);if(d===0&&(r=[1]),o===1)i=e;else if(n){if(o!==4)throw new Error("a packed texture must be 4-channel");i=e,d>0&&(r[d-1]=Math.ceil(r[d-1]/2)),d>1&&(r[d-2]=Math.ceil(r[d-2]/2))}else if(!i)throw new Error("Unpacked shape is needed when using channels > 1");return{width:s,height:c,channels:o,isPacked:n,shape:r,strides:U.computeStrides(r),unpackedShape:i,reversedWH:u&&u.reverseWH}}}),ih,Qn,Qu=L(()=>{ut(),mr(),fe(),zu(),Hu(),qu(),Xu(),ln(),Ju(),ae(),ih=(t,e)=>{let o=e.map(u=>`${u.unpackedShape.join(",")};${u.width}x${u.height}`).join("_"),i=t.name;return t.cacheHint&&(i+="["+t.cacheHint+"]"),i+=":"+o,i},Qn=class{constructor(t){this.session=t,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(t,e){return Ku(this.session.layoutStrategy,t,e)}executeProgram(t,e){if(e.lengththis.readTexture(n),async s=>this.readTextureAsync(n),void 0,u),texture:o};return this.setTextureData(n.tensor.dataId,n,t.isPacked),n}getTextureData(t,e=!1){return this.session.isInitializer(t)?this.session.getTextureData(t,e):e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,o=!1){this.session.isInitializer(t)?this.session.setTextureData(t,e,o):(o?this.packedTextureDataCache:this.unpackedTextureDataCache).set(t,e)}isTextureLayoutCached(t,e=!1){return!!this.getTextureData(t.dataId,e)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(t=>this.session.textureManager.releaseTexture(t)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(t=>this.session.textureManager.releaseTexture(t)),this.unpackedTextureDataCache=new Map}readTexture(t){return t.isPacked?this.readTexture(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat(Ti(this,t))}async readTextureAsync(t){return t.isPacked?this.readTextureAsync(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat(Ti(this,t))}pack(t){return this.executeProgram(Uu(this,t.tensor),[t.tensor])}unpack(t){return this.executeProgram(Yu(this,t.tensor),[t.tensor])}}}),vi,ee,Ge=L(()=>{vi=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},ee=t=>new vi(t)}),el,tl,rl,ah,sh,nl=L(()=>{Ge(),xe(),ae(),el={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[0,0,0,0,0]},tl=(t,e,o)=>(sh(e),[t.run({...el,cacheHint:o.cacheKey,get:()=>ah(t,e,o)},e)]),rl=t=>{let e=t.attributes.getFloat("epsilon",1e-5),o=t.attributes.getFloat("momentum",.9),i=t.attributes.getInt("spatial",1);return ee({epsilon:e,momentum:o,spatial:i})},ah=(t,e,o)=>{let i=q(t.session.backend.glContext.version),u=e[0].dims.length,[n,s]=t.calculateTextureWidthAndHeight(e[1].dims,0),c=` + float process(int[${u}] indices) { + vec2 position = offsetToCoords(indices[1], ${n}, ${s}); + float scale = getColorAsFloat(${i.texture2D}(Scale, position)); + float mean = getColorAsFloat(${i.texture2D}(Mean, position)); + float variance = getColorAsFloat(${i.texture2D}(Variance, position)); + float b = getColorAsFloat(${i.texture2D}(B, position)); + + return scale * ( (_A(indices) - mean) / sqrt(variance + float(${o.epsilon})) ) + b; + }`;return{...el,output:{dims:e[0].dims,type:e[0].type,textureType:0},shaderSource:c}},sh=t=>{if(!t||t.length!==5)throw new Error("BatchNormalization requires 5 inputs.");let e=t[0],o=t[1],i=t[2],u=t[3],n=t[4];if(e.dims.length<3||o.dims.length!==1||i.dims.length!==1||u.dims.length!==1||n.dims.length!==1)throw new Error("invalid input shape.");if(o.dims[0]!==e.dims[1]||i.dims[0]!==e.dims[1]||u.dims[0]!==e.dims[1]||n.dims[0]!==e.dims[1])throw new Error("invalid input shape.");if(e.type!=="float32"&&e.type!=="float64"||o.type!=="float32"&&o.type!=="float64"||i.type!=="float32"&&i.type!=="float64"||u.type!=="float32"&&u.type!=="float64"||n.type!=="float32"&&n.type!=="float64")throw new Error("invalid input tensor types.")}}),eo,pt,R,cn,to,Vt=L(()=>{eo=class{constructor(t,e,o,i){this.glContext=t,this.programInfo=e,this.inputTextureLayouts=o,this.outputTextureLayout=i}},pt=class{constructor(t){this.context=t}},R=class{constructor(t,e){this.routineBody=t,this.dependencies=e}},cn=class{constructor(t,e,o){this.name=t,o?this.dependencies=o:this.dependencies=[],e&&(this.routineBody=e)}addDependency(t){t&&this.dependencies.push(t)}},to=class{static returnOrderedNodes(t){if(!t||t.length===0)return[];if(t.length===1)return t;let e=new Set,o=new Set,i=new Array;return this.createOrderedNodes(t,e,o,i),i}static createOrderedNodes(t,e,o,i){for(let u=0;u0)for(let n=0;n b); + } + vec4 ${t}(vec4 v1, vec4 v2) { + return vec4( v1.r > v2.r , + v1.g > v2.g, + v1.b > v2.b, + v1.a > v2.a ); + } + `,name:t,type:0}}function mh(){let t="less_";return{body:` + float ${t}(float a, float b) { + return float(a < b); + } + vec4 ${t}(vec4 v1, vec4 v2) { + return vec4( v1.r < v2.r , + v1.g < v2.g, + v1.b < v2.b, + v1.a < v2.a ); + } + `,name:t,type:0}}function bh(){let t="and_";return{body:` + float ${t}(float a, float b) { + return float( bool(a) && bool(b) ); + } + vec4 ${t}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r && b2.r , + b1.g && b2.g, + b1.b && b2.b, + b1.a && b2.a ); + } + `,name:t,type:0}}function gh(){let t="or_";return{body:` + float ${t}(float a, float b) { + return float( bool(a) || bool(b) ); + } + vec4 ${t}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r || b2.r , + b1.g || b2.g, + b1.b || b2.b, + b1.a || b2.a ); + } + `,name:t,type:0}}function yh(){let t="xor_";return{body:` + float ${t}(float a, float b) { + return float( bool(a) ^^ bool(b) ); + } + vec4 ${t}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r ^^ b2.r , + b1.g ^^ b2.g, + b1.b ^^ b2.b, + b1.a ^^ b2.a ); + } + `,name:t,type:0}}function Th(){return vh("pow")}function xh(){let t="prelu_";return{body:` + float ${t}(float a, float b) { + return a < 0.0 ? a * b: a; + } + vec4 ${t}(vec4 v1, vec4 v2) { + return vec4( + v1.r < 0.0 ? v1.r * v2.r: v1.r, + v1.g < 0.0 ? v1.g * v2.g: v1.g, + v1.b < 0.0 ? v1.b * v2.b: v1.b, + v1.a < 0.0 ? v1.a * v2.a: v1.a + ); + } + `,name:t,type:0}}function vh(t){let e=`${t}_`;return{body:` + float ${e}(float a, float b) { + return ${t}(a, b); + } + vec4 ${e}(vec4 v1, vec4 v2) { + return ${t}(v1, v2); + } + `,name:e,type:0}}var dt,wh,ol,il,al,sl,ul,ll,fl,cl,pl,dl,hl,ml,bl=L(()=>{fe(),Vt(),xe(),ae(),dt=(t,e,o,i=e[0].type,u)=>{let n=t.session.pack?2:0;return{name:o.name,inputNames:["A","B"],inputTypes:[n,n],cacheHint:u,get:()=>wh(t,e,o,i)}},wh=(t,e,o,i=e[0].type)=>{let u=t.session.pack?2:0,n=!U.areEqual(e[0].dims,e[1].dims),s=e[0].dims,c=t.session.pack;if(n){let a=Xe.calcShape(e[0].dims,e[1].dims,!1);if(!a)throw new Error("Can't perform binary op on the given tensors");s=a;let l=s.length,h=e[0].dims.length!==0?e[0].dims.length:1,f=e[1].dims.length!==0?e[1].dims.length:1,m=e[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",g=e[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",b=q(t.session.backend.glContext.version),v=c?` + ${o.body} + void main() { + vec4 a = getAAtOutCoords(); + vec4 b = getBAtOutCoords(); + vec4 result = ${o.name}(a, b); + ${b.output} = result; + }`:` + ${o.body} + float process(int indices[${l}]) { + int aindices[${h}]; + int bindices[${f}]; + ${m} + ${g} + return ${o.name}(_A(aindices), _B(bindices)); + }`;return{name:o.name,inputNames:["A","B"],inputTypes:[u,u],output:{dims:s,type:i,textureType:u},shaderSource:v,hasMain:c}}let d=q(t.session.backend.glContext.version),r=` + ${o.body} + void main() { + vec4 v1 = ${d.texture2D}(A, TexCoords); + vec4 v2 = ${d.texture2D}(B, TexCoords); + vec4 result = ${o.name}(v1, v2); + ${d.output} = result; + } + `;return{name:o.name,inputNames:["A","B"],inputTypes:[u,u],output:{dims:e[0].dims,type:i,textureType:u},shaderSource:r,hasMain:!0}},ol=(t,e)=>[t.run(dt(t,e,lh()),e)],il=(t,e)=>[t.run(dt(t,e,bh(),"bool"),e)],al=(t,e)=>[t.run(dt(t,e,fh()),e)],sl=(t,e)=>[t.run(dt(t,e,dh(),"bool"),e)],ul=(t,e)=>[t.run(dt(t,e,hh(),"bool"),e)],ll=(t,e)=>[t.run(dt(t,e,mh(),"bool"),e)],fl=(t,e)=>[t.run(dt(t,e,ch()),e)],cl=(t,e)=>[t.run(dt(t,e,gh(),"bool"),e)],pl=(t,e)=>[t.run(dt(t,e,Th()),e)],dl=(t,e)=>[t.run(dt(t,e,xh()),e)],hl=(t,e)=>[t.run(dt(t,e,ph()),e)],ml=(t,e)=>[t.run(dt(t,e,yh(),"bool"),e)]}),gl,yl,Oh,Tl=L(()=>{fe(),gl=(t,e,o)=>(Oh(e),[t.cast(e[0],o)]),yl=t=>Ve.tensorDataTypeFromProto(t.attributes.getInt("to")),Oh=t=>{if(!t||t.length!==1)throw new Error("Cast requires 1 input.");if(t[0].type==="string")throw new Error("Invalid input type.")}}),Ih,Sh,xl,ro,vl=L(()=>{xe(),ae(),Ft(),br(),Ih=(t,e)=>({name:"Concat (packed)",inputNames:Array.from({length:t},(o,i)=>`X${i}`),inputTypes:Array(t).fill(2),cacheHint:e}),Sh=(t,e,o,i)=>{let u=o[0].dims.slice();if(i>=u.length||i<-1*u.length)throw new Error("axis specified for concat doesn't match input dimensionality");i<0&&(i=u.length+i);let n=u.slice(0);for(let F=1;FF.dims),l=St(s),h=new Array(a.length-1);h[0]=a[0][i];for(let F=1;F= ${h[F-1]}) { + return getChannel( + getX${F}(${ro(l,f,Y)}), + vec2(${ro(m,f,Y)})); + }`}let v=h.length,T=h[h.length-1];b+=` + return getChannel( + getX${v}(${ro(l,f,T)}), + vec2(${ro(m,f,T)}));`;let E=q(t.session.backend.glContext.version),M=` + ${r} + float getValue(${l.map(F=>"int "+F)}) { + ${b} + } + + void main() { + ${d} coords = getOutputCoords(); + int lastDim = coords.${l[s-1]}; + coords.${l[s-1]} = coords.${l[s-2]}; + coords.${l[s-2]} = lastDim; + + vec4 result = vec4(getValue(${c}), 0., 0., 0.); + + ${c[s-1]} = ${c[s-1]} + 1; + if (${c[s-1]} < ${n[s-1]}) { + result.g = getValue(${c}); + } + + ${c[s-2]} = ${c[s-2]} + 1; + if (${c[s-2]} < ${n[s-2]}) { + result.a = getValue(${c}); + } + + ${c[s-1]} = ${c[s-1]} - 1; + if (${c[s-2]} < ${n[s-2]} && + ${c[s-1]} < ${n[s-1]}) { + result.b = getValue(${c}); + } + ${E.output} = result; + } + `;return{...e,output:{dims:n,type:o[0].type,textureType:2},shaderSource:M,hasMain:!0}},xl=(t,e,o)=>{let i=Ih(e.length,o.cacheKey);return{...i,get:()=>Sh(t,i,e,o.axis)}},ro=(t,e,o)=>{let i=t.indexOf(e);return t.map((u,n)=>n===i?`${u} - ${o}`:u).join()}}),wl,Ah,Ph,Eh,_l,Dh,Lh,Fh,Ol,$h,Il=L(()=>{Ge(),ae(),vl(),wl=(t,e,o)=>($h(e),t.session.pack&&e[0].dims.length>1?[t.run(xl(t,e,o),e)]:[t.run(Eh(t,e,o),e)]),Ah=(t,e)=>({name:"Concat",inputNames:Array.from({length:t},(o,i)=>`X${i}`),inputTypes:Array(t).fill(0),cacheHint:e}),Ph=(t,e,o,i)=>{let u=o[0].dims.slice();if(i>=u.length||i<-1*u.length)throw new Error("axis specified for concat doesn't match input dimensionality");i<0&&(i=u.length+i);let n=u.slice(0);for(let f=1;f{let i=Ah(e.length,o.cacheKey);return{...i,get:()=>Ph(t,i,e,o.axis)}},_l=t=>`int getTextureWhereDataResides(int index) { + ${t.map((e,o)=>`if(index<${e}) {return ${o};} +`).join("")} + }`,Dh=t=>_l(t),Lh=(t,e)=>{let o=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e}]) {`];for(let i=0;i{let e=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let o=0;oee({axis:t.attributes.getInt("axis")}),$h=t=>{if(!t||t.length<1)throw new Error("too few inputs");let e=t[0].type,o=t[0].dims.length;if(e==="string")throw new Error("string tensor is not supported yet");for(let i of t){if(i.type!==e)throw new Error("input tensors should be one type");if(i.dims.length!==o)throw new Error("input tensors should have the same shape")}}});function Ch(){return ht("abs")}function kh(){return ht("acos")}function Bh(){return ht("asin")}function Nh(){return ht("atan")}function Rh(){return ht("ceil")}function Mh(){return ht("cos")}function Gh(t){let e="elu";return{body:` + const float alpha = float(${t}); + + float ${e}_(float a) { + return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; + } + vec4 ${e}_(vec4 v) { + return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); + } + `,name:e,type:0}}function Uh(){return ht("exp")}function zh(){return ht("floor")}function wi(t,e){let o="clip";return{body:` + const float min = float(${t}); + const float max = float(${e}); + + float ${o}_(float a) { + return clamp(a, min, max); + } + vec4 ${o}_(vec4 v) { + return clamp(v, min, max); + } + `,name:o,type:0}}function Vh(){let t="indentity";return{body:` + float ${t}_(float a) { + return a; + } + vec4 ${t}_(vec4 v) { + return v; + } + `,name:t,type:0}}function Wh(t){let e="leakyRelu";return{body:` + const float alpha = float(${t}); + + float ${e}_(float a) { + return a < 0.0 ? a * alpha : a; + } + vec4 ${e}_(vec4 v) { + return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); + } + `,name:e,type:0}}function Hh(){return ht("log")}function qh(){let t="neg";return{body:` + float ${t}_(float a) { + return -a; + } + vec4 ${t}_(vec4 v) { + return -v; + } + `,name:t,type:0}}function jh(){let t="not";return{body:` + float ${t}_(float a) { + return float( ! bool(a) ); + } + bool ${t}_(bool a) { + return !a; + } + vec4 ${t}_(vec4 v) { + return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); + } + bvec4 ${t}_(bvec4 v) { + return bvec4(!v.x, !v.y, !v.z, !v.w); + } + `,name:t,type:0}}function Yh(){return ht("sin")}function _i(){let t="relu";return{body:` + float ${t}_(float a) { + return max( a, 0.0 ); + } + vec4 ${t}_(vec4 v) { + return max( v, 0.0 ); + } + `,name:t,type:0}}function Oi(){let t="sigmoid";return{body:` + float ${t}_(float a) { + return 1.0 / (1.0 + exp(-a)); + } + vec4 ${t}_(vec4 v) { + return 1.0 / (1.0 + exp(-v)); + } + `,name:t,type:0}}function Xh(){return ht("sqrt")}function Kh(){return ht("tan")}function Jh(){let t="tanh";return{body:` + float ${t}_(float a) { + a = clamp(a, -10., 10.); + a = exp(2.*a); + return (a - 1.) / (a + 1.); + } + vec4 ${t}_(vec4 v) { + v = clamp(v, -10., 10.); + v = exp(2.*v); + return (v - 1.) / (v + 1.); + } + `,name:t,type:0}}function ht(t){return{body:` + float ${t}_(float a) { + return ${t}(a); + } + vec4 ${t}_(vec4 v) { + return ${t}(v); + } + `,name:t,type:0}}var Zh,Pe,Sl,Al,Pl,El,Ii,Dl,Ll,Qh,Fl,$l,Cl,kl,Bl,Nl,Si,Rl,Ml,Gl,Ul,zl,Vl,Wl,Hl,ql,jl,Yl,Ai=L(()=>{Ge(),fe(),Vt(),xe(),ae(),Zh=(t,e,o,i)=>{let u=t.session.pack?2:0,n=q(t.session.backend.glContext.version);return{...e,output:{dims:o.dims,type:o.type,textureType:u},shaderSource:` + ${i.body} + void main() { + vec4 v = ${n.texture2D}(A, TexCoords); + v = ${i.name}_(v); + ${n.output} = v; + } + `,hasMain:!0}},Pe=(t,e,o,i)=>{let u=t.session.pack?2:0,n={name:o.name,inputTypes:[u],inputNames:["A"],cacheHint:i};return{...n,get:()=>Zh(t,n,e,o)}},Sl=(t,e)=>[t.run(Pe(t,e[0],Ch()),e)],Al=(t,e)=>[t.run(Pe(t,e[0],kh()),e)],Pl=(t,e)=>[t.run(Pe(t,e[0],Bh()),e)],El=(t,e)=>[t.run(Pe(t,e[0],Nh()),e)],Ii=(t,e,o)=>[t.run(Pe(t,e[0],wi(o.min,o.max),o.cacheKey),e)],Dl=t=>ee({min:t.attributes.getFloat("min",dr),max:t.attributes.getFloat("max",hr)}),Ll=(t,e)=>{let o=Qh(t,e);return Ii(t,[e[0]],o)},Qh=(t,e)=>{if(e.length>=3&&(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)))throw new Error("dynamic clip attributes are not allowed");let o=e.length>=3?e[1].numberData[0]:dr,i=e.length>=3?e[2].numberData[0]:hr;return ee({min:o,max:i})},Fl=(t,e)=>[t.run(Pe(t,e[0],Rh()),e)],$l=(t,e)=>[t.run(Pe(t,e[0],Mh()),e)],Cl=(t,e,o)=>[t.run(Pe(t,e[0],Gh(o.alpha),o.cacheKey),e)],kl=t=>ee({alpha:t.attributes.getFloat("alpha",1)}),Bl=(t,e)=>[t.run(Pe(t,e[0],Uh()),e)],Nl=(t,e)=>[t.run(Pe(t,e[0],zh()),e)],Si=(t,e)=>[t.run(Pe(t,e[0],Vh()),e)],Rl=(t,e,o)=>[t.run(Pe(t,e[0],Wh(o.alpha),o.cacheKey),e)],Ml=t=>ee({alpha:t.attributes.getFloat("alpha",.01)}),Gl=(t,e)=>[t.run(Pe(t,e[0],Hh()),e)],Ul=(t,e)=>[t.run(Pe(t,e[0],qh()),e)],zl=(t,e)=>[t.run(Pe(t,e[0],jh()),e)],Vl=(t,e)=>[t.run(Pe(t,e[0],_i()),e)],Wl=(t,e)=>[t.run(Pe(t,e[0],Oi()),e)],Hl=(t,e)=>[t.run(Pe(t,e[0],Yh()),e)],ql=(t,e)=>[t.run(Pe(t,e[0],Xh()),e)],jl=(t,e)=>[t.run(Pe(t,e[0],Kh()),e)],Yl=(t,e)=>[t.run(Pe(t,e[0],Jh()),e)]});function Ct(t){let e;switch(t.activation){case"Relu":e=_i();break;case"Sigmoid":e=Oi();break;case"Clip":e=wi(t.clipMin,t.clipMax);break;default:return{activationFunction:"",applyActivation:""}}let o=e.name,i=e.body,u=`value = ${o}_(value);`;return{activationFunction:i,applyActivation:u}}var Rr,gr=L(()=>{fe(),Ai(),Rr=t=>{let e=t.getString("activation","");if(e==="Clip"){let[o,i]=t.getFloats("activation_params",[dr,hr]);return{activation:e,clipMax:i,clipMin:o,activationCacheKey:`${e}:${o},${i}`}}return{activation:e,activationCacheKey:e}}}),tm,rm,Xl,Kl=L(()=>{ut(),xe(),ae(),no(),gr(),tm=(t,e)=>({name:"GroupedConv",inputNames:t?["X","W","Bias"]:["X","W"],inputTypes:t?[0,0,0]:[0,0],cacheHint:e}),rm=(t,e,o,i)=>{let u=e.length>2?"value += getBias(output_channel);":"",n=e[0].dims.slice(),s=e[1].dims.slice(),c=s[0]/i.group;ce.verbose("GroupedConv",`autpPad:${i.autoPad}, dilations:${i.dilations}, group:${i.group}, kernelShape:${i.kernelShape}, pads:${i.pads}, strides:${i.strides}`);let d=Mr(n,s,i.dilations,i.pads,i.strides),r=q(t.session.backend.glContext.version),{activationFunction:a,applyActivation:l}=Ct(i),h=` + const ivec2 strides = ivec2(${i.strides[0]}, ${i.strides[1]}); + const ivec2 pads = ivec2(${i.pads[0]}, ${i.pads[1]}); + ${a} + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int output_channel = coords.y; + ivec2 xRCCorner = coords.zw * strides - pads; + int group_id = output_channel / ${c}; + + float value = 0.0; + for (int wInChannel = 0; wInChannel < ${s[1]}; wInChannel++) { + int input_channel = group_id * ${s[1]} + wInChannel; + for (int wHeight = 0; wHeight < ${s[2]}; wHeight++) { + int xHeight = xRCCorner.x + wHeight * ${i.dilations[0]}; + + if (xHeight < 0 || xHeight >= ${n[2]}) { + continue; + } + + for (int wWidth = 0; wWidth < ${s[3]}; wWidth++) { + int xWidth = xRCCorner.y + wWidth * ${i.dilations[1]}; + if (xWidth < 0 || xWidth >= ${n[3]}) { + continue; + } + + float xVal = getX(batch, input_channel, xWidth, xHeight); + float wVal = getW(output_channel, wInChannel, wWidth, wHeight); + value += xVal*wVal; + } + } + } + ${u} + ${l} + ${r.output} = vec4(value, .0, .0, .0); + } +`;return{...o,output:{dims:d,type:e[0].type,textureType:0},shaderSource:h,hasMain:!0}},Xl=(t,e,o)=>{let i=tm(e.length>2,o.cacheKey);return{...i,get:()=>rm(t,e,i,o)}}}),nm,om,Jl,Zl=L(()=>{xe(),ae(),br(),nm=t=>({name:"Im2Col (packed)",inputNames:["A"],inputTypes:[2],cacheHint:t}),om=(t,e,o,i,u,n)=>{let s=o.dims,c=i.dims,d=2,r=3,a=u.length,l=[c[1]*c[2]*c[3],u[2]*u[3]],h=c[2]*c[3],f=$t(),m=q(t.session.backend.glContext.version),g="";for(let v=0;v<=1;v++)for(let T=0;T<=1;T++)g+=` + blockIndex = rc.x + ${T}; + pos = rc.y + ${v}; + + if(blockIndex < ${l[1]} && pos < ${l[0]}) { + offsetY = int(blockIndex / (${u[a-1]})) * ${n.strides[0]} - + ${n.pads[0]}; + d0 = offsetY + ${n.dilations[0]} * (imod(pos, ${h}) / ${c[2]}); + + if(d0 < ${s[d]} && d0 >= 0) { + offsetX = imod(blockIndex, ${u[a-1]}) * ${n.strides[1]} - + ${n.pads[1]}; + d1 = offsetX + ${n.dilations[1]} * imod(imod(pos, ${h}), ${c[2]}); + + if(d1 < ${s[r]} && d1 >= 0) { + + ch = int(float(pos)/ ${h}.); + innerDims = vec2(d0, d1); + result[${v*2+T}] = getChannel( + getA(0, ch, int(innerDims.x), + int(innerDims.y)), innerDims); + } + } + } + + `;let b=` + ${f} + + void main() { + ivec2 rc = getOutputCoords(); + vec4 result = vec4(0.0); + int blockIndex, pos, offsetY, d0, offsetX, d1, ch; + vec2 innerDims; + ${g} + ${m.output} = result; + } + `;return{...e,output:{dims:l,type:o.type,textureType:2},shaderSource:b,hasMain:!0}},Jl=(t,e,o,i,u)=>{let n=nm(u.cacheKey);return{...n,get:()=>om(t,n,e,o,i,u)}}});function am(t,e,o){let i=e[0].dims,u=e[1].dims,n=Xe.calcShape(i,u,!0);if(!n)throw new Error("Can't use matmul on the given tensors");let s=Ke(n.length),c=St(),{activationFunction:d,applyActivation:r}=Ct(o),a=e.length>2,l=a?"value += getBiasForMatmul();":"",h=a?`${Ei(s,c,e[2].dims,n,!1)}`:"",f=n.length,m=i.length,g=u.length,b=i[i.length-1],v=` + ${d} + ${h} + float process(int indices[${f}]) { + int a[${m}]; + int b[${g}]; + bcastMatmulIndices_A(indices, a); + bcastMatmulIndices_B(indices, b); + + float value; + for (int k=0; k<${b}; ++k) { + a[${m-1}] = k; + b[${g-2}] = k; + value += _A(a) * _B(b); + } + ${l} + ${r} + return value; + }`;return{...t,output:{dims:n,type:e[0].type,textureType:0},shaderSource:v}}function Pi(t,e){let o=im(t.length>2,e.activationCacheKey);return{...o,get:()=>am(o,t,e)}}function Ei(t,e,o,i,u){let n="",s=o.length,c=i.length,d=c-s;c<2&&s>0?n="coords":n=o.map((h,f)=>`coords.${e[f+d]}`).join(", ");let r=Xe.getBroadcastDims(o,i).map(h=>`coords.${e[h+d]} = 0;`).join(` +`),a=U.size(o)===1,l="vec4(outputValue.xx, outputValue.yy)";return a&&(l="vec4(outputValue.x)"),u?` +vec4 getBiasForMatmul() { + ${t} coords = getOutputCoords(); + ${r} + vec4 outputValue = getBias(${n}); + return ${l}; +}`:` +float getBiasForMatmul() { + ${t} coords = getOutputCoords(); + ${r} + return getBias(coords.x); +}`}var Ql,ef,im,sm,oo=L(()=>{fe(),ae(),Ft(),gr(),Di(),Ql=(t,e,o)=>(sm(e),t.session.pack?[t.run(io(t,e,o),e)]:[t.run(Pi(e,o),e)]),ef=t=>Rr(t.attributes),im=(t,e)=>({name:"MatMul",inputNames:t?["A","B","Bias"]:["A","B"],inputTypes:t?[0,0,0]:[0,0],cacheHint:e}),sm=t=>{if(!t||t.length!==2)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.");if(t[0].type!=="float32"&&t[0].type!=="float64"||t[1].type!=="float32"&&t[1].type!=="float64")throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")}});function fm(t,e,o,i){let u=[],n=[],s=o[0].dims,c=o[1].dims,d=s.length,r=c.length,a=i.length,l=a-d,h=a-r;u=s.map((T,E)=>`coords.${e[E+l]}`),u[d-1]="i*2",u.join(", "),n=c.map((T,E)=>`coords.${e[E+h]}`),n[r-2]="i*2",n.join(", ");let f=Xe.getBroadcastDims(s,i),m=Xe.getBroadcastDims(c,i),g=f.map(T=>`coords.${e[T+l]} = 0;`).join(` +`),b=m.map(T=>`coords.${e[T+h]} = 0;`).join(` +`),v=`int lastDim = coords.${e[a-1]}; + coords.${e[a-1]} = coords.${e[a-2]}; + coords.${e[a-2]} = lastDim;`;return` +vec4 getAAtOutCoordsMatmul(int i) { + ${t} coords = getOutputCoords(); + ${v} + ${g} + vec4 outputValue = getA(${u}); + return outputValue; +} + +vec4 getBAtOutCoordsMatmul(int i) { + ${t} coords = getOutputCoords(); + ${v} + ${b} + vec4 outputValue = getB(${n}); + return outputValue; +}`}function cm(t,e){let o="";for(let i=0;i{fe(),xe(),ae(),Ft(),gr(),oo(),um=(t,e)=>({name:"MatMul (packed)",inputNames:t?["A","B","Bias"]:["A","B"],inputTypes:t?[2,2,2]:[2,2],cacheHint:e}),lm=(t,e,o,i)=>{let u=o.length>2,n=u?"value += getBiasForMatmul();":"",s=o[0].dims,c=o[1].dims,d=Xe.calcShape(s,c,!0),r=!U.areEqual(o[0].dims,o[1].dims);if(!d)throw new Error("Can't use matmul on the given tensors");let a=s[s.length-1],l=Math.ceil(a/2),h=s.length,f=c.length,m=q(t.session.backend.glContext.version),g=Ke(d.length),b=d.length,v=St(),{activationFunction:T,applyActivation:E}=Ct(i),M=u?`${Ei(g,v,o[2].dims,d,!0)}`:"",F=r?`${fm(g,v,o,d)}`:"",Y=r?"getAAtOutCoordsMatmul(i)":`getA(${cm(v,h)})`,H=r?"getBAtOutCoordsMatmul(i)":`getB(${pm(v,f)})`,X=r?"":`${g} rc = + getOutputCoords(); int lastDim = rc.${v[b-1]}; rc.${v[b-1]} = + rc.${v[b-2]}; rc.${v[b-2]} = lastDim; + `,k=` + ${F} + ${M} + ${T} + void main() { + ${X} + + vec4 value = vec4(0); + for (int i = 0; i < ${l}; i++) { + vec4 a = ${Y}; + vec4 b = ${H}; + + value += (a.rrbb * b.rgrg); + value += (a.ggaa * b.baba); + } + ${n} + ${E} + ${m.output} = value; + }`;return{...e,output:{dims:d,type:o[0].type,textureType:2},shaderSource:k,hasMain:!0}},io=(t,e,o)=>{let i=um(e.length>2,o.activationCacheKey);return{...i,get:()=>lm(t,i,e,o)}}}),tf,rf=L(()=>{no(),Zl(),Di(),tf=(t,e,o)=>{let i=e[0].dims,u=e[1].dims,n=Mr(i,u,o.dilations,o.pads,o.strides),s=t.run(Jl(t,e[0],e[1],n,o),[e[0]]),c=t.reshapePacked(e[1],[u[0],u[1]*u[2]*u[3]]),d=e.length===3?[c,s,e[2]]:[c,s],r=t.run(io(t,d,o),d);return t.reshapePacked(r,n)}}),dm,hm,nf,Li,Fi=L(()=>{ae(),dm=t=>({name:"Im2Col",inputNames:["X"],inputTypes:[0],cacheHint:t}),hm=(t,e,o,i,u,n)=>{let s=o.dims,c=i.dims,d=u.length,r=Li(s,c,u,4),a=` + const int XC = ${s[1]}; + const int XH = ${s[2]}; + const int XW = ${s[3]}; + const int KH = ${n.kernelShape[0]}; + const int KW = ${n.kernelShape[1]}; + const int dilationH = ${n.dilations[0]}; + const int dilationW = ${n.dilations[1]}; + const int strideH = ${n.strides[0]}; + const int strideW = ${n.strides[1]}; + const int padH = ${n.pads[0]}; + const int padW = ${n.pads[1]}; + const int KHKW = KH*KW; + const int XCKHKW = XC * KHKW; + const int outputChannels = 4; + vec4 process(int indices[${d}]) { + int b = indices[0]; // batch size + int oh = indices[1] * strideH - padH; //output height + int ow = indices[2] * strideW - padW; //output width + int p = indices[3] * outputChannels; //patch + vec4 value = vec4(0.0); + for(int i=0; i < outputChannels; ++i) { + if(p < XCKHKW) { + int patchC = p / KHKW; + int patchH = (p - patchC*KHKW) / KW; + int patchW = (p - patchC*KHKW) - patchH * KW; + int xh2 = oh + patchH * dilationH; + int xw2 = ow + patchW * dilationW; + int x[${s.length}]; + x[0] = b; + x[1] = patchC; + x[2] = xh2; + x[3] = xw2; + if(xh2 >= 0 && + xh2 < XH && + xw2 >= 0 && + xw2 < XW) { + value[i] = _X(x); + } + } + ++p; + } + return value; + } + `;return{...e,output:{dims:r,type:o.type,textureType:4},shaderSource:a}},nf=(t,e,o,i,u)=>{let n=dm(u.cacheKey);return{...n,get:()=>hm(t,n,e,o,i,u)}},Li=(t,e,o,i=4)=>[o[0],o[2],o[3],Math.ceil(t[1]*e[2]*e[3]/i)]}),mm,bm,of,af=L(()=>{fe(),xe(),ae(),gr(),Fi(),mm=(t,e)=>({name:"ConvDotProduct",inputNames:t?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:t?[0,4,0]:[0,4],cacheKey:e.activationCacheKey}),bm=(t,e,o,i,u)=>{let n=o[0].dims,s=o[1].dims,c=[s[0],Math.ceil(n[1]*s[2]*s[3]/4)],d=Li(n,s,i),[r,a]=t.calculateTextureWidthAndHeight(c,4),l=U.computeStrides(d),[h,f]=t.calculateTextureWidthAndHeight(d,4),m=i.length,g=o.length<3?"0.0":"_B(b)",b=Math.ceil(n[1]*s[2]*s[3]/4),{activationFunction:v,applyActivation:T}=Ct(u),E=q(t.session.backend.glContext.version),M=` +${v} +float process(int indices[${m}]) { + int b[1]; + b[0] = indices[1]; + int im2col[4]; + im2col[0] = indices[0]; + im2col[1] = indices[2]; + im2col[2] = indices[3]; + int im2colOffset = im2col[0] * ${l[0]} + im2col[1] * ${l[1]} + im2col[2] * ${l[2]}; + int kernelOffset = indices[1] * ${c[1]}; + float value = ${g}; + for (int i = 0; i < ${b}; ++i) { + vec2 im2colCoords = offsetToCoords(im2colOffset, ${h}, ${f}); + vec2 kernelCoords = offsetToCoords(kernelOffset, ${r}, ${a}); + value += dot(${E.texture2D}(Im2Col, im2colCoords), ${E.texture2D}(K, kernelCoords)); + ++im2colOffset; + ++kernelOffset; + } + ${T} + return value; +}`;return{...e,output:{dims:i,type:o[0].type,textureType:0},shaderSource:M}},of=(t,e,o,i)=>{let u=mm(e.length>2,i);return{...u,get:()=>bm(t,u,e,o,i)}}}),Mr,$i,gm,ym,Tm,xm,Ci,vm,no=L(()=>{Ge(),fe(),Kl(),rf(),af(),gr(),Fi(),oo(),Mr=(t,e,o,i,u)=>{let n=t[0],s=t.slice(2),c=s.length,d=e[0],r=e.slice(2).map((l,h)=>l+(l-1)*(o[h]-1)),a=s.map((l,h)=>l+i[h]+i[h+c]).map((l,h)=>Math.floor((l-r[h]+u[h])/u[h]));return[n,d].concat(...a)},$i=(t,e,o)=>(vm(e,o),gm(t,e,o)),gm=(t,e,o)=>{let i=xm(o,e),u=t.session.pack,n=i.kernelShape[0]===1&&i.kernelShape[1]===1;return i.group>1?[t.run(Xl(t,e,i),e)]:n&&u?[ym(t,e,i)]:u&&e[0].dims.length===4&&e[0].dims[0]===1&&!n?[tf(t,e,i)]:[Tm(t,e,i)]},ym=(t,e,o)=>{let i=e[0].dims,u=e[1].dims,n=Mr(i,u,o.dilations,o.pads,o.strides),s=t.reshapeUnpacked(e[0],[i[1],i[2]*i[3]]),c=t.reshapeUnpacked(e[1],[u[0],u[1]]),d=e.length>2?[c,s,e[2]]:[c,s],r=t.run(Pi(d,o),d);return t.reshapeUnpacked(r,n)},Tm=(t,e,o)=>{let i=e[0].dims,u=e[1].dims,n=Mr(i,u,o.dilations,o.pads,o.strides),s=t.run(nf(t,e[0],e[1],n,o),[e[0]]),c=e.length===3?[s,e[1],e[2]]:[s,e[1]];return t.run(of(t,e,n,o),c)},xm=(t,e)=>{let o=t.kernelShape.slice();if(t.kernelShape.length===0)for(let n=2;n{let e=t.attributes,o=Rr(e),i=e.getString("auto_pad","NOTSET"),u=e.getInts("dilations",[1,1]),n=e.getInt("group",1),s=e.getInts("kernel_shape",[]),c=e.getInts("pads",[0,0,0,0]),d=e.getInts("strides",[1,1]);return ee({autoPad:i,dilations:u,group:n,kernelShape:s,pads:c,strides:d,...o})},vm=(t,e)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length!==4||t[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");let o=t[0].dims[1],i=t[1].dims[1]*e.group;if(o!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(t.length===3&&(t[2].dims.length!==1||t[1].dims[0]!==t[2].dims[0]))throw new Error("invalid bias");let u=t[0].dims.length-2;if(e.dilations.length!==u)throw new Error(`dilations should be ${u}D`);if(e.strides.length!==u)throw new Error(`strides should be ${u}D`);if(e.pads.length!==u*2)throw new Error(`pads should be ${u*2}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if(t[0].type!=="float32"||t[1].type!=="float32")throw new Error("Conv input(X,W) should be float tensor");if(t.length===3&&t[2].type!=="float32")throw new Error("Conv input(bias) should be float tensor")}}),wm,_m,Om,sf,Im,Sm,Am,Pm,Em,Dm,uf,Lm,lf=L(()=>{Ge(),xe(),ae(),gr(),wm=(t,e,o,i,u,n)=>(t-1)*e+o+(i-1)*u+1-n,_m=(t,e,o,i,u)=>{let n=Math.floor(t/2);e==="SAME_UPPER"?(o[i]=n,o[u]=t-n):e==="SAME_LOWER"&&(o[i]=t-n,o[u]=n)},Om=(t,e,o,i,u,n,s,c)=>{let d=t.length-2,r=c.length===0;for(let a=0;a(Lm(e,o),Im(t,e,o)),Im=(t,e,o)=>{let i=Dm(o,e);return[Em(t,e,i)]},Sm=(t,e)=>({name:"ConvTranspose",inputNames:t?["X","W","B"]:["X","W"],inputTypes:t?[0,0,0]:[0,0],cacheHint:e}),Am=(t,e,o,i)=>{let u=e.length>2?"getB(output_channel)":"0.0",n=e[0].dims,s=e[1].dims,c=s[1],d=s[0]/i.group,r=[e[0].dims[0],e[1].dims[1]*i.group,...i.outputShape],a=q(t.session.backend.glContext.version),{activationFunction:l,applyActivation:h}=Ct(i),f=` + const ivec2 strides = ivec2(${i.strides[0]}, ${i.strides[1]}); + const ivec2 pads = ivec2(${i.pads[0]}, ${i.pads[1]}); + ${l} + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int output_channel = coords.y; + + ivec2 loc = coords.zw + pads; + + int group_id = output_channel / ${c}; + int wOutChannel = output_channel - group_id * ${c}; + + float value = ${u}; + for (int inChannelOffset = 0; inChannelOffset < ${d}; inChannelOffset++) { + int input_channel = group_id * ${d} + inChannelOffset; + for (int wWOff = 0; wWOff < ${s[2]}; wWOff++) { + for (int wHOff = 0; wHOff < ${s[3]}; wHOff++) { + ivec2 wOff = ivec2(wWOff * ${i.dilations[0]}, wHOff * ${i.dilations[1]}); + ivec2 wLoc = loc - wOff; + ivec2 wLocIn = wLoc / strides; + if ( + wLocIn * strides == wLoc && + wLocIn.x >= 0 && wLocIn.x < ${n[2]} && + wLocIn.y >= 0 && wLocIn.y < ${n[3]} + ) { + float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); + float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); + value += xVal * wVal; + } + } + } + } + ${h} + ${a.output} = vec4(value, .0, .0, .0); + } +`;return{...o,output:{dims:r,type:e[0].type,textureType:0},shaderSource:f,hasMain:!0}},Pm=(t,e,o)=>{let i=Sm(e.length>2,o.cacheKey);return{...i,get:()=>Am(t,e,i,o)}},Em=(t,e,o)=>t.run(Pm(t,e,o),e),Dm=(t,e)=>{let o=t.kernelShape.slice();if(t.kernelShape.length===0)for(let c=2;c{let e=t.attributes,o=Rr(e),i=e.getString("auto_pad","NOTSET"),u=e.getInts("dilations",[1,1]),n=e.getInt("group",1),s=e.getInts("kernel_shape",[]),c=e.getInts("output_padding",[0,0]),d=e.getInts("output_shape",[]),r=e.getInts("pads",[0,0,0,0]),a=e.getInts("strides",[1,1]);return ee({autoPad:i,dilations:u,group:n,kernelShape:s,outputPadding:c,outputShape:d,pads:r,strides:a,...o})},Lm=(t,e)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length!==4||t[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");let o=t[0].dims[1],i=t[1].dims[0];if(o!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let u=t[1].dims[1]*e.group;if(t.length===3&&(t[2].dims.length!==1||t[2].dims[0]!==u))throw new Error("invalid bias");let n=t[0].dims.length-2;if(e.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(e.strides.length!==n)throw new Error(`strides should be ${n}D`);if(e.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(e.outputPadding.length!==n)throw new Error(`output_padding should be ${n}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if(e.outputShape.length!==0&&e.outputShape.length!==t[0].dims.length-2)throw new Error("invalid output shape");if(t[0].type!=="float32"||t[1].type!=="float32")throw new Error("ConvTranspose input(X,W) should be float tensor");if(t.length===3&&t[2].type!=="float32")throw new Error("ConvTranspose input(bias) should be float tensor")}}),ff,yr,cf,Fm,pf,$m,Cm,km,ao=L(()=>{Ge(),fe(),ae(),ff={name:"Transpose",inputNames:["A"],inputTypes:[0]},yr=(t,e,o)=>(km(e),[t.run({...ff,cacheHint:o.cacheKey,get:()=>Fm(t,e[0],o.perm)},e)]),cf=t=>ee({perm:t.attributes.getInts("perm",[])}),Fm=(t,e,o)=>{let i=e.dims;o=pf(i,o);let u=$m(i,o),n=i.length,s=` + ${Cm("perm",o,n)} + float process(int indices[${n}]) { + int a[${n}]; + perm(a, indices); + return _A(a); + }`;return{...ff,output:{dims:u,type:e.type,textureType:0},shaderSource:s}},pf=(t,e)=>(e&&e.length!==t.length&&(e=[...t.keys()].reverse()),e),$m=(t,e)=>(e=pf(t,e),U.sortBasedOnPerm(t,e)),Cm=(t,e,o)=>{let i=[];i.push(`void ${t}(out int a[${o}], int src[${o}]) {`);for(let u=0;u{if(!t||t.length!==1)throw new Error("Transpose requires 1 input.");if(t[0].type!=="float32"&&t[0].type!=="float64")throw new Error("input should be float tensor")}}),df,hf,Bm,mf=L(()=>{ao(),df=(t,e,o)=>{Bm(e);let i=o.blocksize,u=i*i,n=o.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],s=o.mode==="DCR"?[e[0].dims[0],i,i,e[0].dims[1]/u,e[0].dims[2],e[0].dims[3]]:[e[0].dims[0],e[0].dims[1]/u,i,i,e[0].dims[2],e[0].dims[3]],c=t.reshapeUnpacked(e[0],s),d={perm:n,cacheKey:`${n}`},[r]=yr(t,[c],d),a=[e[0].dims[0],e[0].dims[1]/u,e[0].dims[2]*i,e[0].dims[3]*i];return[t.reshapeUnpacked(r,a)]},hf=t=>{let e=t.attributes.getInt("blocksize");if(e<1)throw new Error(`blocksize must be >= 1, but got : ${e} for DepthToSpace`);let o=t.attributes.getString("mode","DCR");if(o!=="DCR"&&o!=="CRD")throw new Error(`unrecognized mode: ${o} for DepthToSpace`);return{mode:o,blocksize:e}},Bm=t=>{if(t.length!==1)throw new Error(`DepthToSpace expect 1 inputs, but got ${t.length}`);if(t[0].type==="string"||t[0].dims.length!==4)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}}),bf,gf,Nm,yf=L(()=>{fe(),bf=(t,e,o)=>{Nm(e,o);let i=U.flattenShape(e[0].dims,o);return[t.reshapeUnpacked(e[0],i)]},gf=t=>t.attributes.getInt("axis",1),Nm=(t,e)=>{if(!t||t.length!==1)throw new Error("Flatten requires 1 input.");let o=t[0].dims.length;if(o===0)throw new Error("scalar tensor is not supported.");if(e<-o||e>o)throw new Error("Invalid axis");if(t[0].type==="string")throw new Error("string tensor is not supported.")}}),Jt,pn=L(()=>{Jt=["float32","float64","int32","int16","int8","uint16","uint32","uint8"]}),Tf,xf,Rm,Mm,Gm,Um,vf=L(()=>{Ge(),pn(),fe(),ae(),Tf=(t,e,o)=>(Um(e,o.axis),[t.run(Gm(t,e,o),e)]),xf=t=>ee({axis:t.attributes.getInt("axis",0)}),Rm={name:"Gather",inputNames:["A","B"],inputTypes:[0,0]},Mm=(t,e,o,i)=>{let u=o[0].dims.slice(),n=o[1].dims.slice(),s=new Array(u.length+n.length-1);i=U.normalizeAxis(i,u.length);let c=[];for(let h=0;h{let i={...Rm,cacheHint:o.cacheKey};return{...i,get:()=>Mm(t,i,e,o.axis)}},Um=(t,e)=>{if(!t||t.length!==2)throw new Error("Gather requires 2 inputs.");let o=t[0].dims.length;if(o<1)throw new Error("Invalid input shape.");if(e<-o||e>o-1)throw new Error("Invalid axis.");if(Jt.indexOf(t[0].type)===-1)throw new Error("Invaid input type.");if(t[1].type!=="int32"&&t[1].type!=="int16")throw new Error("Invaid input type.")}}),ki,wf,_f,Of,zm,Vm,Wm,If=L(()=>{Ge(),fe(),ae(),ki=(t,e,o)=>(Wm(e,o),[t.run(zm(e,o),e)]),wf=(t,e)=>{let o=t.attributes.getInt("transA",0)!==0,i=t.attributes.getInt("transB",0)!==0,u=t.attributes.getFloat("alpha",1),n=t.attributes.getFloat("beta",1);return ee({transA:o,transB:i,alpha:u,beta:n,isOptionalC:e})},_f=t=>wf(t,!1),Of=t=>wf(t,!0),zm=(t,e)=>{let o={name:"Gemm",inputNames:t.length===3?["A","B","C"]:["A","B"],inputTypes:t.length===3?[0,0,0]:[0,0],key:e.cacheKey};return{...o,get:()=>Vm(o,t,e)}},Vm=(t,e,o)=>{let i=e[0].dims.slice(),u=e[1].dims.slice(),[n,s]=Xn.getShapeOfGemmResult(i,o.transA,u,o.transB,e.length===3?e[2].dims:void 0),c=[n,s];if(!c)throw new Error("Can't use gemm on the given tensors");let d=i[i.length-1],r="";o.transA&&(d=i[0]),o.transA&&o.transB?r="value += _A_T(a) * _B_T(b);":o.transA&&!o.transB?r="value += _A_T(a) * _B(b);":!o.transA&&o.transB?r="value += _A(a) * _B_T(b);":!o.transA&&!o.transB&&(r="value += _A(a) * _B(b);");let a=c.length,l=e.length===3?`int c[${e[2].dims.length}];`:"",h=e.length===3?"bcastIndices_C(indices, c);":"",f=e.length===3?"value += beta * _C(c);":"",m=` + float process(int indices[${a}]) { + int a[${a}]; + int b[${a}]; + ${l} + + copyVec(indices, a); + copyVec(indices, b); + ${h} + + float value = 0.0; + for (int k=0; k<${d}; ++k) { + a[${a-1}] = k; + b[${a-2}] = k; + ${r} + } + + value = value * alpha; + ${f} + return value; + }`;return{...t,output:{dims:c,type:e[0].type,textureType:0},variables:[{name:"alpha",type:"float",data:o.alpha},{name:"beta",type:"float",data:o.beta}],shaderSource:m}},Wm=(t,e)=>{if(!t)throw new Error("Input is missing");if(e.isOptionalC&&(t.length<2||t.length>3))throw new Error("Invaid input shape.");if(!e.isOptionalC&&t.length!==3)throw new Error("Gemm requires 3 inputs");if(t.length===3&&t[2].dims.length!==1&&t[2].dims.length!==2)throw new Error("Invalid input shape of C");if(t[0].type!=="float32"&&t[0].type!=="float64"||t[1].type!=="float32"&&t[1].type!=="float64"||t.length===3&&t[2].type!=="float32"&&t[2].type!=="float64")throw new Error("Invalid input type.");if(t[0].type!==t[1].type||t.length===3&&t[0].type!==t[2].type)throw new Error("Input types are mismatched")}}),Sf,Af,Hm,qm,jm,Ym,Xm,Pf=L(()=>{Ge(),ae(),Sf=(t,e,o)=>(Xm(e),[t.run(jm(t,e,o),e)]),Af=t=>{let e=t.attributes.getFloat("scale"),o=t.attributes.getFloats("bias");return ee({scale:e,bias:o})},Hm={name:"ImageScaler",inputNames:["X"],inputTypes:[0]},qm=(t,e,o,i)=>{let u=o[0].dims.slice(),n=u.length,s=` + ${Ym(i.bias.length)} + float process(int indices[${n}]) { + return _X(indices) * scale + getBias(bias, indices[1]); + }`;return{...e,output:{dims:u,type:o[0].type,textureType:0},variables:[{name:"bias",type:"float",arrayLength:i.bias.length,data:i.bias},{name:"scale",type:"float",data:i.scale}],shaderSource:s}},jm=(t,e,o)=>{let i={...Hm,cacheHint:o.cacheKey};return{...i,get:()=>qm(t,i,e,o)}},Ym=t=>{let e=[`float getBias(float bias[${t}], int channel) {`];for(let o=0;o{if(!t||t.length!==1)throw new Error("ImageScaler requires 1 input.");if(t[0].dims.length!==4)throw new Error("Invalid input shape.");if(t[0].type!=="float32"&&t[0].type!=="float64")throw new Error("Invalid input type.")}}),Df,Lf,Ef,Km,Jm,Zm,Qm,eb,tb,Ff=L(()=>{xe(),ae(),Df=(t,e,o)=>{tb(e);let i=t.run(Jm(e[0]),e);return[t.run(eb(t,e[0],o,i.dims),[e[0],i,e[1],e[2]])]},Lf=t=>t.attributes.getFloat("epsilon",1e-5),Ef={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[0]},Km=(t,e)=>{let o=e.dims.slice(),i=o[1],u=o[2]*o[3],n=[o[0],i],s=` + vec4 process(int[2] indices) { + vec4 v = vec4(0.0); + int a[4]; + a[0] = indices[0]; + a[1] = indices[1]; + float temp = 0.0; + for(int a2=0; a2<${o[2]}; a2++) { + a[2] = a2; + for(int a3=0; a3<${o[3]}; a3++) { + a[3] = a3; + float x = _X(a); + temp += x; + } + } + float mean = temp / float(${u}); + temp = 0.0; + for(int a2=0; a2<${o[2]}; a2++) { + a[2] = a2; + for(int a3=0; a3<${o[3]}; a3++) { + a[3] = a3; + float x = _X(a); + temp += (x - mean) * (x - mean); + } + } + v.r = mean; + v.g = temp / float(${u}); + + return v; + }`;return{...t,output:{dims:n,type:e.type,textureType:4},shaderSource:s}},Jm=t=>({...Ef,get:()=>Km(Ef,t)}),Zm={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[0,4,0,0]},Qm=(t,e,o,i,u)=>{let n=q(t.session.backend.glContext.version),[s,c]=t.calculateTextureWidthAndHeight(u,4),[d,r]=[s/4,c],a=` + vec4 get_MeanAndVariance(int[2] mv) { + int offset = indicesToOffset_MeanAndVariance(mv); + vec2 coords = offsetToCoords(offset, ${d}, ${r}); + return ${n.texture2D}(MeanAndVariance, coords); + } + + float process(int[4] indices) { + int mv[2]; + mv[0] = indices[0]; + mv[1] = indices[1]; + vec4 mean_and_variance = get_MeanAndVariance(mv); + float mean = mean_and_variance.r; + float variance = mean_and_variance.g; + + int sb[1]; + sb[0] = indices[1]; + float scale = _Scale(sb); + float b = _B(sb); + + return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; + }`;return{...e,output:{dims:o.dims,type:o.type,textureType:0},variables:[{name:"epsilon",type:"float",data:i}],shaderSource:a}},eb=(t,e,o,i)=>{let u={...Zm,cacheHint:`${o}`};return{...u,get:()=>Qm(t,u,e,o,i)}},tb=t=>{if(!t||t.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");let e=t[0],o=t[1],i=t[2];if(e.dims.length<3||o.dims.length!==1||i.dims.length!==1)throw new Error("Invalid input shape.");if(o.dims[0]!==e.dims[1]||i.dims[0]!==e.dims[1])throw new Error("Input shapes are mismatched.");if(e.type!=="float32"&&e.type!=="float64"||o.type!=="float32"&&o.type!=="float64"||i.type!=="float32"&&i.type!=="float64")throw new Error("Invalid input type.");if(t[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}});function rb(t,e){let o=t[0].dims[1],i=t[0].dims.length,u=-Math.floor((e.size-1)/2),n=Math.ceil((e.size-1)/2),s=`float(${e.alpha}) / float(${e.size})`,c=`float(${e.bias})`,d=`float(${e.beta})`,r=` + float process(int indices[${i}]) { + int c = indices[1]; + float x = _X(indices); + float square_sum = 0.0; + + for (int i = ${u}; i <= ${n}; i++) { + int idx = c + i; + if (c >= 0 && c < ${o}) { + indices[1] = idx; + float j = _X(indices); + square_sum += j * j; + } + } + return x / pow(${c} + ${s} * square_sum, ${d}); + }`;return{...kf,cacheHint:e.cacheKey,output:{dims:t[0].dims,type:t[0].type,textureType:0},shaderSource:r}}function nb(t,e){return{...kf,cacheHint:e.cacheKey,get:()=>rb(t,e)}}var $f,Cf,kf,ob,Bf=L(()=>{Ge(),ae(),$f=(t,e,o)=>(ob(e),[t.run(nb(e,o),e)]),Cf=t=>{let e=t.attributes.getFloat("alpha",1e-4),o=t.attributes.getFloat("beta",.75),i=t.attributes.getFloat("bias",1),u=t.attributes.getInt("size");return ee({alpha:e,beta:o,bias:i,size:u})},kf={name:"LRN",inputNames:["X"],inputTypes:[0]},ob=t=>{if(!t||t.length!==1)throw new Error("LRN requires 1 input.");if(t[0].dims.length!==4)throw new Error('currently only support LRN for input with "NCHW" format');if(t[0].type!=="float32")throw new Error("input should be float type")}}),ib,Bi,Nf,Rf,Mf,ab,sb,ub,lb,fb,cb,pb,db,Gf=L(()=>{Ge(),fe(),xe(),ae(),ib={name:"Pad",inputNames:["A"],inputTypes:[0]},Bi=(t,e,o)=>(ub(e),[t.run({...ib,cacheHint:o.cacheKey,get:()=>sb(t,e[0],o)},e)]),Nf=t=>{let e=t.attributes.getString("mode","constant"),o=t.attributes.getFloat("value",0),i=t.attributes.getInts("pads");return ee({mode:e,value:o,pads:i})},Rf=(t,e,o)=>{lb(e);let i=ab(t,e,o);return Bi(t,[e[0]],i)},Mf=t=>t.attributes.getString("mode","constant"),ab=(t,e,o)=>{if(!t.session.isInitializer(e[1].dataId)||e.length>=3&&!t.session.isInitializer(e[2].dataId))throw new Error("dynamic pad attributes are not allowed");let i=Array.from(e[1].integerData),u=e.length>=3?e[2].floatData[0]:0;return ee({mode:o,pads:i,value:u})},sb=(t,e,o)=>{let i=U.padShape(e.dims.slice(),o.pads),u=i.length,n=` + ${fb(t,e,o)} + float process(int[${u}] indices) { + return padA(indices); + }`;return{name:"Pad",inputNames:["A"],inputTypes:[0],output:{dims:i,type:e.type,textureType:0},shaderSource:n}},ub=t=>{if(!t||t.length!==1)throw new Error("Pad requires 1 input");if(t[0].type!=="float32"&&t[0].type!=="float64")throw new Error("Invalid input type.")},lb=t=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Pad requires 2 or 3 inputs");if(t[1].type!=="int32")throw new Error("Invalid input type.");if(t.length>=3&&t[2].type==="string")throw new Error("Invalid input type.")},fb=(t,e,o)=>{let i=q(t.session.backend.glContext.version),[u,n]=t.calculateTextureWidthAndHeight(e.dims,0),s=U.computeStrides(e.dims);switch(o.mode){case"constant":return cb(i,e.dims,s,u,n,o.pads,o.value);case"reflect":return pb(i,e.dims,s,u,n,o.pads);case"edge":return db(i,e.dims,s,u,n,o.pads);default:throw new Error("Invalid mode")}},cb=(t,e,o,i,u,n,s)=>{let c=e.length,d="";for(let r=c-1;r>=0;--r)d+=` + k = m[${r}] - ${n[r]}; + if (k < 0) return constant; + if (k >= ${e[r]}) return constant; + offset += k * ${o[r]}; + `;return` + float padA(int m[${c}]) { + const float constant = float(${s}); + int offset = 0; + int k = 0; + ${d} + vec2 coords = offsetToCoords(offset, ${i}, ${u}); + float value = getColorAsFloat(${t.texture2D}(A, coords)); + return value; + } + `},pb=(t,e,o,i,u,n)=>{let s=e.length,c="";for(let d=s-1;d>=0;--d)c+=` + k = m[${d}] - ${n[d]}; + if (k < 0) { k = -k; } + { + const int _2n_1 = ${2*(e[d]-1)}; + k = int( mod( float(k), float(_2n_1) ) ) ; + if(k >= ${e[d]}) { k = _2n_1 - k; } + } + offset += k * ${o[d]}; + `;return` + float padA(int m[${s}]) { + int offset = 0; + int k = 0; + ${c} + vec2 coords = offsetToCoords(offset, ${i}, ${u}); + float value = getColorAsFloat(${t.texture2D}(A, coords)); + return value; + } + `},db=(t,e,o,i,u,n)=>{let s=e.length,c="";for(let d=s-1;d>=0;--d)c+=` + k = m[${d}] - ${n[d]}; + if (k < 0) k = 0; + if (k >= ${e[d]}) k = ${e[d]-1}; + offset += k * ${o[d]}; + `;return` + float padA(int m[${s}]) { + int offset = 0; + int k = 0; + ${c} + vec2 coords = offsetToCoords(offset, ${i}, ${u}); + float value = getColorAsFloat(${t.texture2D}(A, coords)); + return value; + } + `}}),zf,Vf,Wf,Hf,qf,jf,Yf,Xf,Kf,hb,Uf,Jf,uo,Zf,so,mb,Qf=L(()=>{Ge(),fe(),ae(),zf=(t,e,o)=>{uo(e);let i={name:"AveragePool",inputNames:["X"],inputTypes:[0],cacheHint:o.cacheKey};return[t.run({...i,get:()=>Wf(e,i,!1,o)},e)]},Vf=t=>{let e=t.attributes.getString("auto_pad","NOTSET"),o=t.attributes.getInt("ceil_mode",0),i=t.attributes.getInt("count_include_pad",0)!==0,u=t.attributes.getInts("kernel_shape"),n=t.attributes.getInts("strides",[]),s=t.attributes.getInts("pads",[]);if(o!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return ee({autoPad:e,ceilMode:o,countIncludePad:i,kernelShape:u,strides:n,pads:s})},Wf=(t,e,o,i)=>{let[u,n]=Kf(t,i,o),s=U.size(u.kernelShape),c="value += _X(x);",d="";u.countIncludePad?d+=`value /= float(${s});`:d+=`value /= float(${s} - pad);`;let r=` + ${Zf(t[0].dims,u,c,d,"0.0")} + `;return{...e,output:{dims:n,type:t[0].type,textureType:0},shaderSource:r}},Hf=(t,e,o)=>{uo(e);let i={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[0],cacheHint:`${o.countIncludePad}`};return[t.run({...i,get:()=>Wf(e,i,!0,o)},e)]},qf=t=>{let e=t.attributes.getInt("count_include_pad",0)!==0;return ee({autoPad:"",ceilMode:0,countIncludePad:e,kernelShape:[],strides:[],pads:[]})},jf=(t,e,o)=>{uo(e);let i={name:"MaxPool",inputNames:["X"],inputTypes:[0],cacheHint:o.cacheKey};return[t.run({...i,get:()=>Xf(e,i,!1,o)},e)]},Yf=t=>{let e=t.attributes.getString("auto_pad","NOTSET"),o=t.attributes.getInt("ceil_mode",0),i=t.attributes.getInts("kernel_shape"),u=t.attributes.getInts("strides",[]),n=t.attributes.getInts("pads",[]),s=t.attributes.getInt("storage_order",0),c=t.attributes.getInts("dilations",[]);if(s!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(o!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return ee({autoPad:e,ceilMode:o,countIncludePad:!1,kernelShape:i,strides:u,pads:n,storageOrder:s,dilations:c})},Xf=(t,e,o,i)=>{let[u,n]=Kf(t,i,o),s=` + value = max(_X(x), value); + `,c="",d=` + ${Zf(t[0].dims,u,s,c,"-1e5")} + `;return{...e,output:{dims:n,type:t[0].type,textureType:0},shaderSource:d}},Kf=(t,e,o)=>{let i=t[0].dims.slice(),u=Object.hasOwnProperty.call(e,"dilations"),n=e.kernelShape.slice(),s=e.strides.slice(),c=u?e.dilations.slice():[],d=e.pads.slice();pr.adjustPoolAttributes(o,i,n,s,c,d);let r=pr.computePoolOutputShape(o,i,s,c,n,d,e.autoPad),a=Object.assign({},e);return u?Object.assign(a,{kernelShape:n,strides:s,pads:d,dilations:c,cacheKey:e.cacheKey}):Object.assign(a,{kernelShape:n,strides:s,pads:d,cacheKey:e.cacheKey}),[a,r]},hb={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},Uf={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[0]},Jf=(t,e)=>(uo(e),[t.run({...Uf,get:()=>Xf(e,Uf,!0,hb)},e)]),uo=t=>{if(!t||t.length!==1)throw new Error("Pool ops requires 1 input.");if(t[0].type!=="float32"&&t[0].type!=="float64")throw new Error("Invalid input type.")},Zf=(t,e,o,i,u)=>{let n=t.length;if(e.kernelShape.length<=2){let s=e.kernelShape[e.kernelShape.length-1],c=e.strides[e.strides.length-1],d=e.pads[e.pads.length/2-1],r=e.pads[e.pads.length-1],a=t[n-1],l="",h="",f="";if(d+r!==0?l=` + for (int i = 0; i < ${s}; i++) { + x[${n} - 1] = indices[${n} - 1] * ${c} - ${d} + i; + if (x[${n} - 1] < 0 || x[${n} - 1] >= ${a}) { + pad++; + continue; + } + ${o} + }`:l=` + for (int i = 0; i < ${s}; i++) { + x[${n} - 1] = indices[${n} - 1] * ${c} - ${d} + i; + ${o} + }`,e.kernelShape.length===2){let m=e.kernelShape[e.kernelShape.length-2],g=e.strides[e.strides.length-2],b=e.pads[e.pads.length/2-2],v=e.pads[e.pads.length-2],T=t[n-2];b+v!==0?h=` + for (int j = 0; j < ${m}; j++) { + x[${n} - 2] = indices[${n} - 2] * ${g} - ${b} + j; + if (x[${n} - 2] < 0 || x[${n} - 2] >= ${T}) { + pad+= ${s}; + continue; + } + `:h=` + for (int j = 0; j < ${m}; j++) { + x[${n} - 2] = indices[${n} - 2] * ${g} - ${b} + j; + `,f=` + } + `}return` + float process(int indices[${n}]) { + int x[${n}]; + copyVec(indices, x); + + float value = ${u}; + int pad = 0; + ${h} + ${l} + ${f} + ${i} + return value; + } + `}else{let s=U.size(e.kernelShape),c=U.computeStrides(e.kernelShape),d=c.length,r=e.pads.length,a=mb(d),l=so(t,"inputDims"),h=so(e.pads,"pads"),f=so(c,"kernelStrides"),m=so(e.strides,"strides"),g=e.pads.reduce((v,T)=>v+T),b="";return g?b=` + if (x[j] >= inputDims[j] || x[j] < 0) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + ${o} + }`:b=` + } + ${o} + `,` + ${a} + float process(int indices[${n}]) { + int x[${n}]; + copyVec(indices, x); + int offset[${d}]; + int pads[${r}]; + int inputDims[${n}]; + int kernelStrides[${d}]; + int strides[${d}]; + ${h} + ${l} + ${m} + ${f} + + float value = ${u}; + int pad = 0; + bool isPad = false; + for (int i = 0; i < ${s}; i++) { + offsetToIndices(i, kernelStrides, offset); + isPad = false; + for (int j = ${n} - ${d}; j < ${n}; j++) { + x[j] = indices[j] * strides[j - ${n} + ${d}] + + offset[j - ${n} + ${d}] - pads[j - 2]; + ${b} + } + ${i} + + return value; + } + `}},so=(t,e)=>{let o="";for(let i=0;i` + void offsetToIndices(int offset, int[${t}] strides, out int[${t}] indices) { + if (${t} == 0) { + return; + } + for (int i = 0; i < ${t} - 1; ++i) { + indices[i] = offset / strides[i]; + offset -= indices[i] * strides[i]; + } + indices[${t} - 1] = offset; + }`}),Tr,Zt,bb,gb,ec,tc,rc,nc,oc,ic,ac,sc=L(()=>{Ge(),pn(),fe(),ae(),Tr=(t,e,o,i,u)=>{gb(e);let n={name:i,inputNames:["A"],inputTypes:[0]};return[t.run({...n,cacheHint:o.cacheKey,get:()=>bb(t,e,o,i,u,n)},e)]},Zt=t=>{let e=t.attributes.getInts("axes",[]),o=t.attributes.getInt("keepdims",1)===1;return ee({axes:e,keepDims:o})},bb=(t,e,o,i,u,n)=>{let s=[],c=e[0].dims.length||1,d=[],r=U.normalizeAxes(o.axes,e[0].dims.length),a=u(e,r),l=a[1];for(let f=0;f=0||r.length===0?(o.keepDims&&s.push(1),l=` + for(int j${f} = 0; j${f} < ${e[0].dims[f]}; j${f}++) { + inputIdx[${f}] = j${f}; + ${l} + }`):(d.push(`inputIdx[${f}] = outputIdx[${s.length}];`),s.push(e[0].dims[f]));let h=` + float process(int outputIdx[${s.length||1}]) { + float value; // final result + int inputIdx[${c}]; // addressing input data + ${d.join(` +`)} + ${a[0]} // init ops for reduce max/min + ${l} + ${a[2]} // final computation for reduce mean + return value; + }`;return{...n,output:{dims:s,type:e[0].type,textureType:0},shaderSource:h}},gb=t=>{if(!t||t.length!==1)throw new Error("Reduce op requires 1 input.");if(Jt.indexOf(t[0].type)===-1)throw new Error("Invalid input type.")},ec=(t,e,o)=>Tr(t,e,o,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),tc=(t,e,o)=>Tr(t,e,o,"ReduceMean",(i,u)=>{let n=1;for(let s=0;s=0||u.length===0)&&(n*=i[0].dims[s]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${n}.;`]}),rc=(t,e,o)=>Tr(t,e,o,"ReduceMax",(i,u)=>{let n=[];for(let s=0;s=0||u.length===0)&&n.push(`inputIdx[${s}] = 0;`);return[`${n.join(` +`)} +value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),nc=(t,e,o)=>Tr(t,e,o,"ReduceMin",(i,u)=>{let n=[];for(let s=0;s=0||u.length===0)&&n.push(`inputIdx[${s}] = 0;`);return[`${n.join(` +`)} +value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),oc=(t,e,o)=>Tr(t,e,o,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),ic=(t,e,o)=>Tr(t,e,o,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),ac=(t,e,o)=>Tr(t,e,o,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])}),uc,lc=L(()=>{fe(),uc=(t,e)=>{let o=U.calculateReshapedDims(e[0].dims,e[1].integerData);return t.session.pack?[t.reshapePacked(e[0],o)]:[t.reshapeUnpacked(e[0],o)]}}),fc,Ni,cc,pc,dn,yb,Ri,lo,Mi=L(()=>{Ge(),xe(),ae(),fc={name:"Upsample",inputNames:["X"],inputTypes:[0]},Ni=(t,e,o)=>(Ri(e,o),[t.run({...fc,cacheHint:o.cacheKey,get:()=>yb(t,e,o)},e)]),cc=t=>dn(t,7),pc=t=>dn(t,9),dn=(t,e)=>{let o=e>=10,i=t.attributes.getString("mode","nearest");if(i!=="nearest"&&i!=="linear"&&(e<11||i!=="cubic"))throw new Error(`unrecognized mode: ${i}`);let u=[];e<9&&(u=t.attributes.getFloats("scales"),lo(u,i,o));let n=t.attributes.getFloat("extrapolation_value",0),s=e>10?t.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(s)===-1)throw new Error(`coordinate_transform_mode '${s}' is not supported`);let c=s==="tf_crop_and_resize",d=c,r=i==="nearest"&&e>=11?t.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(r)===-1)throw new Error(`nearest_mode '${r}' is not supported`);let a=t.attributes.getFloat("cubic_coeff_a",-.75),l=t.attributes.getInt("exclude_outside",0)!==0;if(l&&i!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");let h=e<11?!0:i==="nearest"&&s==="asymmetric"&&r==="floor",f=0,m=0,g=0;return e>10?t.inputs.length>2?(f=1,m=2,g=3):(m=1,g=2):e===9&&(m=1),ee({opset:e,isResize:o,mode:i,scales:u,extrapolationValue:n,coordinateTransformMode:s,useExtrapolation:d,needRoiInput:c,nearestMode:r,cubicCoefficientA:a,excludeOutside:l,useNearest2xOptimization:h,roiInputIdx:f,scalesInputIdx:m,sizesInputIdx:g})},yb=(t,e,o)=>{let i=q(t.session.backend.glContext.version),[u,n]=t.calculateTextureWidthAndHeight(e[0].dims,0),s=e[0].dims.map((g,b)=>Math.floor(g*o.scales[b])),[c,d]=t.calculateTextureWidthAndHeight(s,0),r=s.length,a=new Array(r),l=new Array(r),h=` + int output_pitches[${r}]; + int input_pitches[${r}]; + `;for(let g=r-1;g>=0;g--)a[g]=g===r-1?1:a[g+1]*s[g+1],l[g]=g===r-1?1:l[g+1]*e[0].dims[g+1],h+=` + output_pitches[${g}] = ${a[g]}; + input_pitches[${g}] = ${l[g]}; + `;let f=` + float getInputFloat(int index) { + vec2 coords = offsetToCoords(index, ${u}, ${n}); + float value = getColorAsFloat(${i.texture2D}(X, coords)); + return value; + } + `,m=o.mode==="nearest"?` + ${f} + float process(int indices[${r}]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${c}, ${d}); + + ${h} + + int d, m; + for (int dim = 0; dim < ${r}; ++dim) { + d = output_index / output_pitches[dim]; + m = output_index - d * output_pitches[dim]; + output_index = m; + + if (scales[dim] != 1 && d > 0) { + int d2 = d / scales[dim]; + m = d - d2 * scales[dim]; + d = d2; + } + input_index += input_pitches[dim] * d; + } + + return getInputFloat(input_index); + }`:r===4?` + ${f} + float process(int indices[4]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${c}, ${d}); + + ${h} + + int m; + int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3; + index_of_dim0 = output_index / output_pitches[0]; + m = output_index - index_of_dim0 * output_pitches[0]; + index_of_dim1 = m / output_pitches[1]; + m = m - index_of_dim1 * output_pitches[1]; + index_of_dim2 = m / output_pitches[2]; + m = m - index_of_dim2 * output_pitches[2]; + index_of_dim3 = m; + + int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset; + index_of_input_dim2 = index_of_dim2 / scales[2]; + y_offset = index_of_dim2 - index_of_input_dim2 * scales[2]; + index_of_input_dim3 = index_of_dim3 / scales[3]; + x_offset = index_of_dim3 - index_of_input_dim3 * scales[3]; + + input_index = index_of_dim0 * input_pitches[0] + + index_of_dim1 * input_pitches[1] + + index_of_input_dim2 * input_pitches[2] + + index_of_input_dim3; + + float x00 = getInputFloat(input_index); + float x10, x01, x11; + + bool end_of_dim2 = false; + if (index_of_input_dim2 == (${e[0].dims[2]} - 1)) { + // It's the end in dimension 2 + x01 = x00; + end_of_dim2 = true; + } else { + x01 = getInputFloat(input_index + input_pitches[2]); + } + + if (index_of_input_dim3 == (input_pitches[2] - 1)) { + // It's the end in dimension 3 + x10 = x00; + x11 = x01; + } + else { + x10 = getInputFloat(input_index + 1); + x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1); + } + + float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]); + float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]); + return y0 + float(x_offset) * (y1 - y0) / float(scales[3]); + }`:` + ${f} + float process(int indices[2]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${c}, ${d}); + + ${h} + + int m; + int index_of_dim0, index_of_dim1; + index_of_dim0 = output_index / output_pitches[0]; + m = output_index - index_of_dim0 * output_pitches[0]; + index_of_dim1 = m; + + int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset; + index_of_input_dim0 = index_of_dim0 / scales[0]; + y_offset = index_of_dim0 - index_of_input_dim0 * scales[0]; + index_of_input_dim1 = index_of_dim1 / scales[1]; + x_offset = index_of_dim1 - index_of_input_dim1 * scales[1]; + + input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1; + + float x00 = getInputFloat(input_index); + float x10, x01, x11; + + bool end_of_dim0 = false; + if (index_of_input_dim0 == (${e[0].dims[0]} - 1)) { + // It's the end in dimension 0 + x01 = x00; + end_of_dim0 = true; + } else { + x01 = getInputFloat(input_index + input_pitches[0]); + } + + if (index_of_input_dim1 == (input_pitches[0] - 1)) { + // It's the end in dimension 1 + x10 = x00; + x11 = x01; + } + else { + x10 = getInputFloat(input_index + 1); + x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1); + } + + float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); + float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); + return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); + }`;return{...fc,output:{dims:s,type:e[0].type,textureType:0},shaderSource:m,variables:[{name:"scales",type:"int",arrayLength:o.scales.length,data:o.scales.map(g=>Math.ceil(g))}]}},Ri=(t,e)=>{if(!t||e.opset<9&&t.length!==1||e.opset>=9&&e.opset<11&&t.length!==2||e.opset>=11&&t.length<2)throw new Error("invalid inputs.");if(e.scales.length>0&&t[0].dims.length!==e.scales.length)throw new Error("Invalid input shape.");if(t[0].type==="string")throw new Error("Invalid input tensor types.")},lo=(t,e,o)=>{if(o){for(let i of t)if(i<=0)throw new Error("Scale value should be greater than 0.")}else for(let i of t)if(i<1)throw new Error("Scale value should be greater than or equal to 1.");if((e==="linear"||e==="cubic")&&t.length!==2&&(t.length!==4||t[0]!==1||t[1]!==1))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${o?"Resize":"Upsample"} opeartor.`)}}),Gi,Ui,dc,hc,Tb,xb,vb,wb,mc=L(()=>{xe(),ae(),Ft(),br(),Mi(),Gi={name:"Resize",inputNames:["A"],inputTypes:[2]},Ui=(t,e,o)=>(Ri(e,o),[t.run({...Gi,cacheHint:o.cacheKey,get:()=>Tb(t,e,o)},e)]),dc=t=>dn(t,10),hc=t=>dn(t,11),Tb=(t,e,o)=>{let i=q(t.session.backend.glContext.version),[u,n]=xb(e,o);if(u.every(T=>T===1)&&o.coordinateTransformMode!=="tf_crop_and_resize")return{...Gi,output:{dims:n,type:e[0].type,textureType:2},hasMain:!0,shaderSource:`void main() { + vec4 v = ${i.texture2D}(X, TexCoords); + ${i.output} = v; + }`};let s=n.length;if(s<2)throw new Error(`output dimension should be at least 2, but got ${s}`);let c=n[s-2],d=n[s-1],r=e[0].dims;if(s!==r.length)throw new Error(`output dimension should match input ${r.length}, but got ${s}`);let a=r[s-2],l=r[s-1],h=u[s-2],f=u[s-1],m="";if(o.mode!=="linear")throw new Error(`resize (packed) does not support mode: '${o.mode}'`);switch(o.coordinateTransformMode){case"asymmetric":m=` + vec4 getSourceFracIndex(ivec4 coords) { + return vec4(coords) / scaleWHWH; + } + `;break;case"half_pixel":m=` + vec4 getSourceFracIndex(ivec4 coords) { + return (vec4(coords) + 0.5) / scaleWHWH - 0.5; + } + `;break;case"pytorch_half_pixel":m=` + vec4 getSourceFracIndex(ivec4 coords) { + vec4 fcoords = vec4(coords); + return vec4( + ${d}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, + ${c}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, + ${d}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, + ${c}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 + ); + } + `;break;case"align_corners":m=` + vec4 getSourceFracIndex(ivec4 coords) { + vec4 resized = vec4(${d}.0 - 1.0, ${c}.0 - 1.0, ${d}.0 - 1.0, + ${c}.0 - 1.0); + vec4 original = vec4(${l}.0 - 1.0, ${a}.0 - 1.0, ${l}.0 - 1.0, + ${a}.0 - 1.0); + vec4 new_scale = original / resized; + return vec4(coords) * new_scale; + } + `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${o.coordinateTransformMode}'`)}let g=Ke(s),b=$t(),v=` + const vec2 inputWH = vec2(${a}.0, ${l}.0); + const vec4 scaleWHWH = vec4(float(${h}), float(${f}), float(${h}), float(${f})); + ${b} + ${m} + float getAValue(int x10, int r, int c, int d) { + return getChannel(getA(x10, r, c, d), vec2(c, d)); + } + void main() { + ${g} 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 < ${c-1}; + bool hasNextCol = rc.z < ${d-1}; + + // pack x00, x01, x10, x11's top-left corner into one vec4 structure + vec4 topLeft = vec4( + getAValue(batch, depth, x00.x, x00.y), + hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0); + + // pack x00, x01, x10, x11's top-right corner into one vec4 structure + vec4 topRight = vec4( + getAValue(batch, depth, x00.x, x00.w), + hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0); + + // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure + vec4 bottomLeft = vec4( + getAValue(batch, depth, x00.z, x00.y), + hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0); + + // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure + vec4 bottomRight = vec4( + getAValue(batch, depth, x00.z, x00.w), + hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0); + + // calculate the interpolation fraction on u and v direction + vec4 frac = vec4(sourceFrac) - floor(sourceFrac); + vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0)); + + vec4 top = mix(topLeft, topRight, clampFrac.ywyw); + vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw); + vec4 newValue = mix(top, bottom, clampFrac.xxzz); + + ${i.output} = vec4(newValue); + } + `;return{...Gi,output:{dims:n,type:e[0].type,textureType:2},hasMain:!0,shaderSource:v}},xb=(t,e)=>{let o=t[0].dims,i=e.scales,u;if(i.length===0){let s=t[e.scalesInputIdx];if(s&&s.size!==0){if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");i=vb(s,e.mode,e.isResize)}else{let c=t[e.sizesInputIdx];if(!c||c.size===0)throw new Error("Either scales or sizes MUST be provided as input.");u=Array.from(c.integerData),i=wb(u,o,e.mode,e.isResize)}}else if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");let n=u||o.map((s,c)=>Math.floor(s*i[c]));return[i,n]},vb=(t,e,o)=>{let i=Array.from(t.floatData);return lo(i,e,o),i},wb=(t,e,o,i)=>{let u=e.length,n=new Array(u);for(let s=0,c=u;s{mr(),bc=(t,e)=>(_b(e),[new Fe([e[0].dims.length],"int32",void 0,void 0,new Int32Array(e[0].dims))]),_b=t=>{if(!t||t.length!==1)throw new Error("Shape requires 1 input.")}}),zi,yc,Tc,xc,Ob,vc,Ib,Sb,wc=L(()=>{Ge(),pn(),fe(),ae(),zi={name:"Slice",inputNames:["A"],inputTypes:[0]},yc=(t,e,o)=>(Ob(e),[t.run({...zi,cacheHint:o.cacheKey,get:()=>xc(t,e[0],o)},e)]),Tc=t=>{let e=t.attributes.getInts("starts"),o=t.attributes.getInts("ends"),i=t.attributes.getInts("axes",[]);return ee({starts:e,ends:o,axes:i})},xc=(t,e,o)=>{let i=o.axes.length===0?e.dims.slice(0).map((a,l)=>l):o.axes,u=U.normalizeAxes(i,e.dims.length),n=o.starts.map((a,l)=>a>e.dims[u[l]]-1?e.dims[u[l]]:U.normalizeAxis(a,e.dims[u[l]])),s=o.ends.map((a,l)=>a>e.dims[u[l]]-1?e.dims[u[l]]:U.normalizeAxis(a,e.dims[u[l]])),c=e.dims.slice(),d=[];for(let a=0;a0&&d.push(`outputIdx[${u[a]}] += ${n[a]};`);let r=` + float process(int outputIdx[${c.length}]) { + ${d.join(` + `)} + return _A(outputIdx); + }`;return{...zi,output:{dims:c,type:e.type,textureType:0},shaderSource:r}},Ob=t=>{if(!t||t.length!==1)throw new Error("Slice requires 1 input.");if(Jt.indexOf(t[0].type)===-1)throw new Error("Invalid input type.")},vc=(t,e)=>{Sb(e);let o=Ib(t,e);return[t.run({...zi,cacheHint:o.cacheKey,get:()=>xc(t,e[0],o)},[e[0]])]},Ib=(t,e)=>{if(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)||e.length>=4&&!t.session.isInitializer(e[3].dataId)||e.length>=5&&!t.session.isInitializer(e[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(e.length>=5&&e[4].integerData.some(s=>s!==1))throw new Error("currently non-1 steps is not supported for Slice");let o=Array.from(e[1].integerData),i=Array.from(e[2].integerData),u=e.length>=4?Array.from(e[3].integerData):[],n=`${u};${o};${i}`;return{starts:o,ends:i,axes:u,cacheKey:n}},Sb=t=>{if(!t||t.length<3||t.length>5)throw new Error("Invalid input number.");if(t[1].type!=="int32"||t[1].dims.length!==1)throw new Error("Invalid input type.");if(t[2].type!=="int32"||t[2].dims.length!==1)throw new Error("Invalid input type.");if(t.length>=4&&(t[3].type!=="int32"||t[3].dims.length!==1))throw new Error("Invalid input type.");if(t.length>=5&&(t[4].type!=="int32"||t[4].dims.length!==1))throw new Error("Invalid input type.")}}),_c,Oc,Ic,Sc,Ac,Pc,Ec,Dc,Ab,Pb,Eb,Lc,Fc=L(()=>{Ge(),fe(),xe(),ae(),ao(),_c={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[0]},Oc={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[0,0]},Ic={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[0,0,0]},Sc=(t,e,o)=>{Lc(e);let i=e[0].dims.slice(),u=U.normalizeAxis(o.axis,i.length),n=U.sizeToDimension(i,u),s=U.sizeFromDimension(i,u);return Dc(t,e,o,n,s)},Ac=t=>ee({axis:t.attributes.getInt("axis",1)}),Pc=t=>ee({axis:t.attributes.getInt("axis",-1)}),Ec=(t,e,o)=>{Lc(e);let i=e[0].dims.slice(),u=U.normalizeAxis(o.axis,i.length),n=i.length,s=u!==n-1,c=[],d=[],r=[],a;s&&(d=Array.from({length:n}).map((m,g)=>g),d[u]=n-1,d[n-1]=u,d.map(m=>c.push(i[m])),a=ee({perm:d}),r=yr(t,e,a));let l=s?U.sizeToDimension(c,n-1):U.sizeToDimension(i,n-1),h=s?U.sizeFromDimension(c,n-1):U.sizeFromDimension(i,n-1),f=Dc(t,s?r:e,o,l,h);return s?yr(t,f,a):f},Dc=(t,e,o,i,u)=>{let n=Ab(t,e[0],i,u,[i]),s=t.run({..._c,cacheHint:o.cacheKey,get:()=>n},e),c=Pb(t,e[0],i,u,n.output.dims,[i]),d=t.run({...Oc,cacheHint:o.cacheKey,get:()=>c},[e[0],s]),r=Eb(t,e[0],i,u,n.output.dims,c.output.dims);return[t.run({...Ic,cacheHint:o.cacheKey,get:()=>r},[e[0],s,d])]},Ab=(t,e,o,i,u)=>{let[n,s]=t.calculateTextureWidthAndHeight(e.dims,0),c=u.length;if(o<1||i<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(u.length!==1)throw new Error("Dimensionality of the output should be 1");if(u[0]!==o)throw new Error("Shape of the output should be equal to logical row count");let d=q(t.session.backend.glContext.version),r=` + float process(int[${c}] indices) { + int logical_row_start_offset = indices[0] * ${i}; + + float max = getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset, ${n}, + ${s} ))); + for(int i=1; i<${i}; ++i) + { + float current = getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset + i, + ${n}, ${s}))); + if(current > max) + max = current; + } + + return max; + }`;return{..._c,output:{dims:u,type:e.type,textureType:0},shaderSource:r}},Pb=(t,e,o,i,u,n)=>{let[s,c]=t.calculateTextureWidthAndHeight(e.dims,0),d=n.length;if(o<1||i<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(n.length!==1)throw new Error("Dimensionality of the output should be 1");if(n[0]!==o)throw new Error("Shape of the output should be equal to logical row count");if(u.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(u[0]!==o)throw new Error("Shape of the intermediate results should be equal to logical row count");let r=q(t.session.backend.glContext.version),a=` + float process(int[${d}] indices) { + int logical_row_start_offset = indices[0] * ${i}; + + float norm_factor = 0.0; + float max = _Max(indices); + for(int i=0; i<${i}; ++i) + { + norm_factor += exp(getColorAsFloat(${r.texture2D}(A, offsetToCoords(logical_row_start_offset + i, + ${s}, ${c}))) - max); + } + + return norm_factor; + }`;return{...Oc,output:{dims:n,type:e.type,textureType:0},shaderSource:a}},Eb=(t,e,o,i,u,n)=>{let[s,c]=t.calculateTextureWidthAndHeight(e.dims,0),d=e.dims.length;if(o<1||i<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(u.length!==1||n.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(u[0]!==o||n[0]!==o)throw new Error("Shape of the intermediate results should be equal to logical row count");let r=` + float process(int[${d}] indices) { + + // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) + int offset = coordsToOffset(TexCoords, ${s}, ${c}); + + //determine the logical row for this index + int logical_row_index[1]; + logical_row_index[0] = offset / ${i}; + + float norm_factor = _Norm(logical_row_index); + + // avoid possible division by 0 + // if norm_facor is 0, all elements are zero + // if so, return 0 + if(norm_factor == 0.0) + return 0.0; + + return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; + }`;return{...Ic,output:{dims:e.dims,type:e.type,textureType:0},shaderSource:r}},Lc=t=>{if(!t||t.length!==1)throw new Error("Softmax requires 1 input.");if(t[0].type!=="float32"&&t[0].type!=="float64")throw new Error("Invalid input type")}}),$c,Cc,kc,Db,Lb,Fb,Bc=L(()=>{Ge(),fe(),ae(),$c={name:"Split",inputNames:["A"],inputTypes:[0]},Cc=(t,e,o)=>{Fb(e);let i=U.normalizeAxis(o.axis,e[0].dims.length),u=Db(t,e,i,o),n=[];for(let s=0;sLb(t,e[0],o,i,s)},e));return n},kc=t=>{let e=t.attributes.getInt("axis",0),o=t.attributes.getInts("split",[]),i=t.outputs.length;return ee({axis:e,split:o,numOutputs:i})},Db=(t,e,o,i)=>{let[,u]=an.splitShape(e[0].dims,o,i.split,i.numOutputs);return u.length},Lb=(t,e,o,i,u)=>{let[n,s]=an.splitShape(e.dims,i,o.split,o.numOutputs),c=s[u],d=n[u],r=` + float process(int indices[${d.length}]) { + indices[${i}] += ${c}; + return _A(indices); + } + `;return{...$c,cacheHint:`${o.cacheKey}:${u}`,output:{dims:d,type:e.type,textureType:0},shaderSource:r}},Fb=t=>{if(!t||t.length!==1)throw new Error("Split requires one input.");if(t[0].type!=="int8"&&t[0].type!=="uint8"&&t[0].type!=="int16"&&t[0].type!=="uint16"&&t[0].type!=="int32"&&t[0].type!=="uint32"&&t[0].type!=="float32"&&t[0].type!=="float64"&&t[0].type!=="bool")throw new Error("Invalid input type.")}}),Vi,Nc,Rc,$b,Cb,Mc=L(()=>{fe(),Vi=(t,e,o)=>{$b(e);let i=U.squeezeShape(e[0].dims,o);return[t.reshapeUnpacked(e[0],i)]},Nc=(t,e)=>(Cb(e),Vi(t,[e[0]],Array.from(e[1].integerData))),Rc=t=>t.attributes.getInts("axes"),$b=t=>{if(!t||t.length!==1)throw new Error("Squeeze requires 1 input.");if(t[0].type==="string")throw new Error("invalid input tensor types.")},Cb=t=>{if(!t||t.length!==2)throw new Error("Squeeze requires 2 inputs.");if(t[1].type!=="int32")throw new Error("Invalid input type.")}}),Gc,kb,Bb,Uc=L(()=>{xe(),ae(),Gc=(t,e)=>{Bb(e);let o={name:"Sum",inputNames:e.map((i,u)=>`X${u}`),inputTypes:new Array(e.length).fill(0)};return[t.run({...o,get:()=>kb(t,e,o)},e)]},kb=(t,e,o)=>{let i=q(t.session.backend.glContext.version),u=e[0].dims.slice(),n=` + void main() { + vec4 result = ${e.map((s,c)=>`${i.texture2D}(X${c},TexCoords)`).join(" + ")}; + ${i.output} = result; + } + `;return{...o,output:{dims:u,type:e[0].type,textureType:0},hasMain:!0,shaderSource:n}},Bb=t=>{if(!t||t.length===0)throw new Error("Sum requires inputs.");let e=t[0].dims.length;for(let o=1;o{pn(),ae(),zc=(t,e)=>{Rb(e);let o={name:"Tile",inputNames:["A"],inputTypes:[0]};return[t.run({...o,get:()=>Nb(t,e,o)},e)]},Nb=(t,e,o)=>{let i=e[0].dims.slice(),u=new Array(i.length),n=[];for(let d=0;d{if(!t||t.length!==2)throw new Error("Tile requires 2 input.");if(t[1].dims.length!==1)throw new Error("The second input shape must 1 dimension.");if(t[1].dims[0]!==t[0].dims.length)throw new Error("Invalid input shape.");if(Jt.indexOf(t[0].type)===-1)throw new Error("Invalid input type.");if(t[1].type!=="int32"&&t[1].type!=="int16")throw new Error("Invalid repeat type.")}}),Wi,Wc,Hc,Mb,Gb,qc=L(()=>{fe(),Wi=(t,e,o)=>{Mb(e);let i=U.unsqueezeShape(e[0].dims,o);return[t.reshapeUnpacked(e[0],i)]},Wc=(t,e)=>(Gb(e),Wi(t,[e[0]],Array.from(e[1].integerData))),Hc=t=>t.attributes.getInts("axes"),Mb=t=>{if(!t||t.length!==1)throw new Error("Unsqueeze requires 1 input.");if(t[0].type==="string")throw new Error("invalid input tensor types.")},Gb=t=>{if(!t||t.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(t[1].type!=="int32")throw new Error("Invalid input type.")}}),jc,Yc=L(()=>{nl(),bl(),Tl(),Il(),no(),lf(),mf(),yf(),vf(),If(),Pf(),Ff(),Bf(),oo(),Gf(),Qf(),sc(),lc(),mc(),gc(),wc(),Fc(),Bc(),Mc(),Uc(),Vc(),ao(),Ai(),qc(),Mi(),jc=[["Abs","","6+",Sl],["Acos","","7+",Al],["Add","","7+",ol],["And","","7+",il],["Asin","","7+",Pl],["Atan","","7+",El],["AveragePool","","7+",zf,Vf],["BatchNormalization","","7+",tl,rl],["Cast","","6+",gl,yl],["Ceil","","6+",Fl],["Clip","","6-10",Ii,Dl],["Clip","","11+",Ll],["Concat","","4+",wl,Ol],["Conv","","1+",$i,Ci],["ConvTranspose","","1+",sf,uf],["Cos","","7+",$l],["Div","","7+",al],["Dropout","","7+",Si],["DepthToSpace","","1+",df,hf],["Equal","","7+",sl],["Elu","","6+",Cl,kl],["Exp","","6+",Bl],["Flatten","","1+",bf,gf],["Floor","","6+",Nl],["FusedConv","com.microsoft","1+",$i,Ci],["Gather","","1+",Tf,xf],["Gemm","","7-10",ki,_f],["Gemm","","11+",ki,Of],["GlobalAveragePool","","1+",Hf,qf],["GlobalMaxPool","","1+",Jf],["Greater","","7+",ul],["Identity","","1+",Si],["ImageScaler","","1+",Sf,Af],["InstanceNormalization","","6+",Df,Lf],["LeakyRelu","","6+",Rl,Ml],["Less","","7+",ll],["LRN","","1+",$f,Cf],["Log","","6+",Gl],["MatMul","","1+",Ql,ef],["MaxPool","","1+",jf,Yf],["Mul","","7+",fl],["Neg","","6+",Ul],["Not","","1+",zl],["Or","","7+",cl],["Pad","","2-10",Bi,Nf],["Pad","","11+",Rf,Mf],["Pow","","7+",pl],["PRelu","","7+",dl],["ReduceLogSum","","1+",ic,Zt],["ReduceMax","","1+",rc,Zt],["ReduceMean","","1+",tc,Zt],["ReduceMin","","1+",nc,Zt],["ReduceProd","","1+",oc,Zt],["ReduceSum","","1-12",ec,Zt],["ReduceSumSquare","","1+",ac,Zt],["Relu","","6+",Vl],["Reshape","","5+",uc],["Resize","","10",Ui,dc],["Resize","","11+",Ui,hc],["Shape","","1+",bc],["Sigmoid","","6+",Wl],["Sin","","7+",Hl],["Slice","","10+",vc],["Slice","","1-9",yc,Tc],["Softmax","","1-12",Sc,Ac],["Softmax","","13+",Ec,Pc],["Split","","2-12",Cc,kc],["Sqrt","","6+",ql],["Squeeze","","1-12",Vi,Rc],["Squeeze","","13+",Nc],["Sub","","7+",hl],["Sum","","6+",Gc],["Tan","","7+",jl],["Tanh","","6+",Yl],["Tile","","6+",zc],["Transpose","","1+",yr,cf],["Upsample","","7-8",Ni,cc],["Upsample","","9",Ni,pc],["Unsqueeze","","1-12",Wi,Hc],["Unsqueeze","","13+",Wc],["Xor","","7+",ml]]});function Kc(t){let e={},o;for(;(o=Xc.exec(t))!==null;){let i=o[3].split(",").map(u=>{let n=u.trim().split(" ");return n&&n.length===2?{type:n[0],name:n[1]}:null}).filter(u=>u!==null);e[o[2]]={params:i,body:o[4]}}for(let i in e){let u=Ub.replace("__FUNC__",i),n=new RegExp(u,"gm");for(;(o=n.exec(t))!==null;){let s=o[1],c=o[2],d=o[3].split(","),r=s?`${s} ${c};`:"",a=e[i].body,l="";e[i].params.forEach((f,m)=>{f&&(l+=`${f.type} ${f.name} = ${d[m]}; +`)}),a=`${l} + ${a}`,a=a.replace("return",`${c} = `);let h=` + ${r} + { + ${a} + } + `;t=t.replace(o[0],h)}}return t=t.replace(Xc,""),t}var Xc,Ub,Jc=L(()=>{Xc=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm,Ub="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;"});function Gr(t,e){let o=[],i=[],u=e!=null&&Array.isArray(e)&&e.length===0,n=e==null||u?null:zb(e,t).sort(),s=0;for(let c=0;cc)&&t[c]===1&&(o.push(t[c]),i.push(c)),n[s]<=c&&s++}t[c]!==1&&(o.push(t[c]),i.push(c))}return{newShape:o,keptDims:i}}function zb(t,e){let o=e.length;return t=t==null?e.map((i,u)=>u):[].concat(t),Cr(t.every(i=>i>=-o&&i`All values in axis param must be in range [-${o}, ${o}) but got axis ${t}`),Cr(t.every(Vb),()=>`All values in axis param must be integers but got axis ${t}`),t.map(i=>i<0?o+i:i)}function Vb(t){return t%1===0}function Wb(t){if(t.length===0)return 1;let e=t[0];for(let o=1;o{ut(),fe(),fo=class{constructor(t){this.maxTextureSize=t}computeTextureWH(t,e){let o=this.computeTexture(t,e);return e&&e.isPacked&&(o[0]/=2,o[1]/=2),e&&e.reverseWH?[o[1],o[0]]:o}computeTexture(t,e){let o=e&&e.isPacked;if(t.length===0)return o?[2,2]:[1,1];let i=this.maxTextureSize;if(e&&e.breakAxis!==void 0){let s=e.breakAxis>=t.length?1:t.slice(e.breakAxis).reduce((d,r)=>d*r),c=e.breakAxis<=0?1:t.slice(0,e.breakAxis).reduce((d,r)=>d*r);if(s>i||c>i)ce.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}`);else return[s,c]}let u=t.slice(0);o&&(i=i*2,u=u.map((s,c)=>c>=u.length-2?u[c]%2===0?u[c]:u[c]+1:u[c]),u.length===1&&(u=[2,u[0]])),u.length!==2&&(u=Gr(u).newShape);let n=Wb(u);return u.length<=1&&n<=i?[1,n]:u.length===2&&u[0]<=i&&u[1]<=i?u:u.length===3&&u[0]*u[1]<=i&&u[2]<=i?[u[0]*u[1],u[2]]:u.length===3&&u[0]<=i&&u[1]*u[2]<=i?[u[0],u[1]*u[2]]:u.length===4&&u[0]*u[1]*u[2]<=i&&u[3]<=i?[u[0]*u[1]*u[2],u[3]]:u.length===4&&u[0]<=i&&u[1]*u[2]*u[3]<=i?[u[0],u[1]*u[2]*u[3]]:o?Zc(n/4).map(s=>s*2):Zc(n)}}}),co,Qc=L(()=>{fe(),Vt(),xe(),Hi(),Ft(),co=class extends pt{constructor(t){super(t)}getFunctions(){return{...this.offsetToCoords(),...this.coordsToOffset(),...this.toVec(),...this.valueFrom(),...this.getCommonUtilFuncs(),...this.getInputsSamplingSnippets(),...this.getOutputSamplingSnippet()}}getCustomTypes(){return{}}offsetToCoords(){let t="offsetToCoords";return{offsetToCoords:new R(` + vec2 ${t}(int offset, int width, int height) { + int t = offset / width; + int s = offset - t*width; + vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height); + return coords; + } + `)}}coordsToOffset(){let t="coordsToOffset";return{coordsToOffset:new R(` + int ${t}(vec2 coords, int width, int height) { + float s = coords.s * float(width); + float t = coords.t * float(height); + int offset = int(t) * width + int(s); + return offset; + } + `)}}getOutputSamplingSnippet(){let t=this.context.outputTextureLayout;return t.isPacked?this.getPackedOutputSamplingSnippet(t):this.getUnpackedOutputSamplingSnippet(t)}getPackedOutputSamplingSnippet(t){let e=t.unpackedShape,o=[t.width,t.height],i={},u="getOutputCoords";switch(e.length){case 0:i[u]=this.getOutputScalarCoords();break;case 1:i[u]=this.getOutputPacked1DCoords(e,o);break;case 2:i[u]=this.getOutputPacked2DCoords(e,o);break;case 3:i[u]=this.getOutputPacked3DCoords(e,o);break;default:i[u]=this.getOutputPackedNDCoords(e,o)}let n=` + void setOutput(vec4 val) { + ${q(this.context.glContext.version).output} = val; + } + `,s="floatTextureSetRGBA";return i[s]=new R(n),i}getUnpackedOutputSamplingSnippet(t){let e=t.unpackedShape,o=[t.width,t.height],i={},u="getOutputCoords";switch(e.length){case 0:i[u]=this.getOutputScalarCoords();break;case 1:i[u]=this.getOutputUnpacked1DCoords(e,o);break;case 2:i[u]=this.getOutputUnpacked2DCoords(e,o);break;case 3:i[u]=this.getOutputUnpacked3DCoords(e,o);break;case 4:i[u]=this.getOutputUnpacked4DCoords(e,o);break;case 5:i[u]=this.getOutputUnpacked5DCoords(e,o);break;case 6:i[u]=this.getOutputUnpacked6DCoords(e,o);break;default:throw new Error(`Unsupported output dimensionality: ${e.length}`)}let n=` + void setOutput(float val) { + ${q(this.context.glContext.version).output} = vec4(val, 0, 0, 0); + } + `,s="floatTextureSetR";return i[s]=new R(n),i}getOutputScalarCoords(){return new R(` + int getOutputCoords() { + return 0; + } + `)}getOutputPacked1DCoords(t,e){let o=e,i="";return o[0]===1?(i=` + int getOutputCoords() { + return 2 * int(TexCoords.y * ${o[1]}.0); + } + `,new R(i)):o[1]===1?(i=` + int getOutputCoords() { + return 2 * int(TexCoords.x * ${o[0]}.0); + } + `,new R(i)):(i=` + int getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${o[0]}, ${o[1]})); + return 2 * (resTexRC.y * ${o[0]} + resTexRC.x); + } + `,new R(i))}getOutputPacked2DCoords(t,e){let o="";if(cr.arraysEqual(t,e))return o=` + ivec2 getOutputCoords() { + return 2 * ivec2(TexCoords.xy * vec2(${e[0]}, ${e[1]})); + } + `,new R(o);let i=e,u=Math.ceil(t[1]/2);return o=` + ivec2 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${i[0]}, ${i[1]})); + + int index = resTexRC.y * ${i[0]} + resTexRC.x; + + // reverse r and c order for packed texture + int r = imod(index, ${u}) * 2; + int c = 2 * (index / ${u}); + + return ivec2(r, c); + } + `,new R(o)}getOutputPacked3DCoords(t,e){let o=[e[0],e[1]],i=Math.ceil(t[2]/2),u=i*Math.ceil(t[1]/2),n=` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${o[0]}, ${o[1]})); + int index = resTexRC.y * ${o[0]} + resTexRC.x; + + int b = index / ${u}; + index -= b * ${u}; + + // reverse r and c order for packed texture + int r = imod(index, ${i}) * 2; + int c = 2 * (index / ${i}); + + return ivec3(b, r, c); + } + `;return new R(n)}getOutputPackedNDCoords(t,e){let o=[e[0],e[1]],i=Math.ceil(t[t.length-1]/2),u=i*Math.ceil(t[t.length-2]/2),n=u,s="",c="b, r, c";for(let r=2;r=0;--c)u[c]=u[c+1]*t[c+1];let n=["r","c","d"],s=u.map((c,d)=>{let r=`int ${n[d]} = index / ${c}`,a=d===u.length-1?`int ${n[d+1]} = index - ${n[d]} * ${c}`:`index -= ${n[d]} * ${c}`;return`${r}; ${a};`}).join("");return o=` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.y * ${e[0]} + resTexRC.x; + ${s} + return ivec3(r, c, d); + } + `,new R(o)}getOutputUnpacked4DCoords(t,e){let o="",i=t.length,u=null;i<2&&(u=[]),u=new Array(i-1),u[i-2]=t[i-1];for(let c=i-3;c>=0;--c)u[c]=u[c+1]*t[c+1];let n=["r","c","d","d2"],s=u.map((c,d)=>{let r=`int ${n[d]} = index / ${c}`,a=d===u.length-1?`int ${n[d+1]} = index - ${n[d]} * ${c}`:`index -= ${n[d]} * ${c}`;return`${r}; ${a};`}).join("");return o=` + ivec4 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.y * ${e[0]} + resTexRC.x; + ${s} + return ivec4(r, c, d, d2); + } + `,new R(o)}getOutputUnpacked5DCoords(t,e){let o="",i=t.length,u=null;i<2&&(u=[]),u=new Array(i-1),u[i-2]=t[i-1];for(let c=i-3;c>=0;--c)u[c]=u[c+1]*t[c+1];let n=["r","c","d","d2","d3"],s=u.map((c,d)=>{let r=`int ${n[d]} = index / ${c}`,a=d===u.length-1?`int ${n[d+1]} = index - ${n[d]} * ${c}`:`index -= ${n[d]} * ${c}`;return`${r}; ${a};`}).join("");return o=` + ivec5 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.y * ${e[0]} + resTexRC.x; + ${s} + return ivec5(r, c, d, d2, d3); + } + `,new R(o)}getOutputUnpacked6DCoords(t,e){let o="",i=t.length,u=null;i<2&&(u=[]),u=new Array(i-1),u[i-2]=t[i-1];for(let c=i-3;c>=0;--c)u[c]=u[c+1]*t[c+1];let n=["r","c","d","d2","d3","d4"],s=u.map((c,d)=>{let r=`int ${n[d]} = index / ${c}`,a=d===u.length-1?`int ${n[d+1]} = index - ${n[d]} * ${c}`:`index -= ${n[d]} * ${c}`;return`${r}; ${a};`}).join("");return o=` + ivec6 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.y * ${e[0]} + resTexRC.x; + ${s} + return ivec6(r, c, d, d2, d3, d4); + } + `,new R(o)}getCommonUtilFuncs(){let t={},e="uvFromFlat";t[e]=new R(` + vec2 uvFromFlat(int texNumR, int texNumC, int index) { + int texC = index / texNumR; + int texR = index - texC * texNumR; + // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to + // v. + return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC); + } + `),e="packedUVfrom1D",t[e]=new R(` + vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { + int texelIndex = index / 2; + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); + } + `),e="packedUVfrom2D",t[e]=new R(` + vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) { + int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); + } + `),e="packedUVfrom3D",t[e]=new R(` + vec2 packedUVfrom3D(int texNumR, int texNumC, + int texelsInBatch, int texelsInLogicalRow, int b, + int row, int col) { + int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); + } + `),e="sampleTexture";let o=q(this.context.glContext.version);return t[e]=new R(` + float sampleTexture(sampler2D textureSampler, vec2 uv) { + return ${o.texture2D}(textureSampler, uv).r; + }`),t}getInputsSamplingSnippets(){let t={},e=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((o,i)=>{let u=this.context.inputTextureLayouts[i],n=Kn(o);u.isPacked?t[n]=this.getPackedSamplerFromInput(n,o,u):t[n]=this.getUnpackedSamplerFromInput(n,o,u);let s=Mu(o);u.unpackedShape.length<=e.unpackedShape.length&&(u.isPacked?t[s]=this.getPackedSamplerAtOutputCoords(s,u,e,o):t[s]=this.getUnpackedSamplerAtOutputCoords(s,u,e,o))}),t}getPackedSamplerAtOutputCoords(t,e,o,i){let u=e.unpackedShape,n=o.unpackedShape,s=Kn(i),c=u.length,d=n.length,r=Xe.getBroadcastDims(u,n),a=Ke(d),l=d-c,h,f=St();c===0?h="":d<2&&r.length>=1?h="coords = 0;":h=r.map(M=>`coords.${f[M+l]} = 0;`).join(` +`);let m="";d<2&&c>0?m="coords":m=u.map((M,F)=>`coords.${f[F+l]}`).join(", ");let g="return outputValue;",b=U.size(u)===1,v=U.size(n)===1;if(c===1&&!b&&!v)g=` + return vec4(outputValue.xy, outputValue.xy); + `;else if(b&&!v)d===1?g=` + return vec4(outputValue.x, outputValue.x, 0., 0.); + `:g=` + return vec4(outputValue.x); + `;else if(r.length){let M=c-2,F=c-1;r.indexOf(M)>-1&&r.indexOf(F)>-1?g="return vec4(outputValue.x);":r.indexOf(M)>-1?g="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":r.indexOf(F)>-1&&(g="return vec4(outputValue.xx, outputValue.zz);")}let T=` + int lastDim = coords.${f[d-1]}; + coords.${f[d-1]} = coords.${f[d-2]}; + coords.${f[d-2]} = lastDim; + `,E=` + vec4 ${t}() { + ${a} coords = getOutputCoords(); + ${T} + ${h} + vec4 outputValue = ${s}(${m}); + ${g} + } + `;return new R(E,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(t,e,o,i){let u=[o.width,o.height],n=[e.width,e.height],s=e.unpackedShape.length,c=o.unpackedShape.length,d=e.unpackedShape,r=o.unpackedShape,a=Kn(i);if(s===c&&cr.arraysEqual(n,u)){let T=` + float ${t}() { + return sampleTexture(${i}, TexCoords); + } + `;return new R(T,["coordinates.sampleTexture"])}let l=Ke(c),h=Xe.getBroadcastDims(d,r),f=c-s,m,g=St();s===0?m="":c<2&&h.length>=1?m="coords = 0;":m=h.map(T=>`coords.${g[T+f]} = 0;`).join(` +`);let b="";c<2&&s>0?b="coords":b=e.unpackedShape.map((T,E)=>`coords.${g[E+f]}`).join(", ");let v=` + float ${t}() { + ${l} coords = getOutputCoords(); + ${m} + return ${a}(${b}); + } + `;return new R(v,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(t,e,o){switch(o.unpackedShape.length){case 0:return this.getPackedSamplerScalar(t,e);case 1:return this.getPackedSampler1D(t,e,o);case 2:return this.getPackedSampler2D(t,e,o);case 3:return this.getPackedSampler3D(t,e,o);default:return this.getPackedSamplerND(t,e,o)}}getUnpackedSamplerFromInput(t,e,o){let i=o.unpackedShape;switch(i.length){case 0:return this.getUnpackedSamplerScalar(t,e,o);case 1:return this.getUnpackedSampler1D(t,e,o);case 2:return this.getUnpackedSampler2D(t,e,o);case 3:return this.getUnpackedSampler3D(t,e,o);case 4:return this.getUnpackedSampler4D(t,e,o);case 5:return this.getUnpackedSampler5D(t,e,o);case 6:return this.getUnpackedSampler6D(t,e,o);default:throw new Error(`Unsupported dimension ${i.length}-D`)}}getPackedSamplerScalar(t,e){let o=q(this.context.glContext.version),i=` + vec4 ${t}() { + return ${o.texture2D}(${e}, halfCR); + } + `;return new R(i)}getPackedSampler1D(t,e,o){let i=[o.width,o.height],u=[i[1],i[0]],n=q(this.context.glContext.version),s=`vec4 ${t}(int index) { + vec2 uv = packedUVfrom1D( + ${u[0]}, ${u[1]}, index); + return ${n.texture2D}(${e}, uv); + }`;return new R(s,["coordinates.packedUVfrom1D"])}getPackedSampler2D(t,e,o){let i=o.unpackedShape,u=[o.width,o.height],n=q(this.context.glContext.version),s=u[0],c=u[1];if(u!=null&&cr.arraysEqual(i,u)){let l=`vec4 ${t}(int row, int col) { + vec2 uv = (vec2(col, row) + halfCR) / vec2(${c}.0, ${s}.0); + return ${n.texture2D}(${e}, uv); + }`;return new R(l)}let d=u,r=Math.ceil(i[1]/2),a=`vec4 ${t}(int row, int col) { + vec2 uv = packedUVfrom2D(${d[1]}, ${d[0]}, ${r}, row, col); + return ${n.texture2D}(${e}, uv); + }`;return new R(a,["coordinates.packedUVfrom2D"])}getPackedSampler3D(t,e,o){let i=o.unpackedShape,u=[o.width,o.height],n=[u[0],u[1]],s=q(this.context.glContext.version);if(i[0]===1){let h=i.slice(1),f=[1,2],m=kr(i,h),g=["b","row","col"],b=JSON.parse(JSON.stringify(o));b.unpackedShape=m;let v=this.getPackedSamplerFromInput(t,e,b),T=`${v.routineBody} + vec4 ${t}(int b, int row, int col) { + return ${t}(${Br(g,f)}); + } `;return new R(T,v.dependencies)}let c=n[0],d=n[1],r=Math.ceil(i[2]/2),a=r*Math.ceil(i[1]/2),l=`vec4 ${t}(int b, int row, int col) { + vec2 uv = packedUVfrom3D( + ${d}, ${c}, ${a}, ${r}, b, row, col); + return ${s.texture2D}(${e}, uv);}`;return new R(l,["coordinates.packedUVfrom3D"])}getPackedSamplerND(t,e,o){let i=o.unpackedShape,u=i.length,n=[o.width,o.height],s=q(this.context.glContext.version),c=[n[0],n[1]],d=c[1],r=c[0],a=Math.ceil(i[u-1]/2),l=a*Math.ceil(i[u-2]/2),h="int b, int row, int col",f=`b * ${l} + (row / 2) * ${a} + (col / 2)`;for(let g=2;g{let i=this.context.inputTextureLayouts[o],u=(i.unpackedShape.length>0?i.unpackedShape:i.shape).length,n=`_${e}`;t[n]=new R(this.getValueFromSingle(e,u,i.width,i.height,!1),[`shapeUtils.indicesToOffset${n}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),n=n+"_T",t[n]=new R(this.getValueFromSingle(e,u,i.width,i.height,!0),[`shapeUtils.indicesToOffset${n}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])}),t}getValueFromSingle(t,e,o,i,u){let n=`_${t}`;u&&(n=n+"_T");let s=q(this.context.glContext.version);return` + float ${n}(int m[${e}]) { + int offset = indicesToOffset${n}(m); + vec2 coords = offsetToCoords(offset, ${o}, ${i}); + float value = getColorAsFloat(${s.texture2D}(${t}, coords)); + return value; + } + `}getPackedValueFrom(t,e,o,i,u){let n=`_${t}_Pack`;u&&(n=n+"_T");let s=q(this.context.glContext.version);return` + vec4 ${n}(int m[${e}]) { + int offset = indicesToOffset_${t}(m); + vec2 coords = offsetToCoords(offset, ${o}, ${i}); + return ${s.texture2D}(${t}, coords); + } + `}}}),po,ep=L(()=>{Vt(),po=class vn extends pt{constructor(e){super(e)}getFunctions(){return{...this.encodeFloat32(),...this.decodeFloat32()}}getCustomTypes(){return{}}encodeFloat32(){return{encode:new R(`highp vec4 encode(highp float f) { + return vec4(f, 0.0, 0.0, 0.0); + } + `)}}decodeFloat32(){return{decode:new R(`highp float decode(highp vec4 rgba) { + return rgba.r; + } + `)}}encodeUint8(){let e=vn.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new R(` + highp vec4 encode(highp float f) { + highp float F = abs(f); + highp float Sign = step(0.0,-f); + highp float Exponent = floor(log2(F)); + highp float Mantissa = (exp2(- Exponent) * F); + Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa)); + highp vec4 rgba; + rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0)); + rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0); + rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0))); + rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0))); + ${e} + rgba = rgba / 255.0; // values need to be normalized to [0,1] + return rgba; + } + `)}}decodeUint8(){let e=vn.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new R(` + highp float decode(highp vec4 rgba) { + rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] + ${e} + highp float Sign = 1.0 - step(128.0,rgba[0])*2.0; + highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; + highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000); + highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); + return Result; + } + `)}}static isLittleEndian(){let e=new ArrayBuffer(4),o=new Uint32Array(e),i=new Uint8Array(e);if(o[0]=3735928559,i[0]===239)return!0;if(i[0]===222)return!1;throw new Error("unknown endianness")}}}),ho,tp=L(()=>{Vt(),xe(),ho=class extends pt{constructor(t){super(t)}getFunctions(){return{...this.setFragColor(),...this.getColorAsFloat()}}getCustomTypes(){return{}}setFragColor(){let t=q(this.context.glContext.version);return{setFragColor:new R(` + void setFragColor(float value) { + ${t.output} = encode(value); + } + `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new R(` + float getColorAsFloat(vec4 color) { + return decode(color); + } + `,["encoding.decode"])}}}}),mo,rp=L(()=>{Vt(),mo=class tr extends pt{constructor(e){super(e)}getFunctions(){return{...this.bcastIndex(),...this.bcastMatmulIndex(),...this.offsetToIndices(),...this.indicesToOffset(),...this.incrementIndices()}}getCustomTypes(){return{}}bcastIndex(){let e=this.context.outputTextureLayout.shape.length,o={};return this.context.programInfo.inputNames.forEach((i,u)=>{let n=this.context.inputTextureLayouts[u].unpackedShape;if(n.length<=e){let s=n.length,c=e-s,d=`bcastIndices_${i}`,r="";for(let l=0;l{let n=this.context.inputTextureLayouts[u].shape;if(!(n.length<2||n.length>e)){let s=n.length,c=e-s,d=`bcastMatmulIndices_${i}`,r="";for(let l=0;l{let u=this.context.inputTextureLayouts[i].shape,n=this.context.inputTextureLayouts[i].strides,s=u.length,c=`indicesToOffset_${o}`;e[c]=new R(tr.indexToOffsetSingle(c,s,n)),c=`indicesToOffset_${o}_T`,e[c]=new R(tr.indexToOffsetSingle(c,s,n.slice().reverse()))}),e}static indexToOffsetSingle(e,o,i){let u="";for(let n=o-1;n>=0;--n)u+=` + offset += indices[${n}] * ${i[n]}; + `;return` + int ${e}(int indices[${o}]) { + int offset = 0; + ${u} + return offset; + } + `}offsetToIndices(){let e={};return this.context.programInfo.inputNames.forEach((o,i)=>{let u=this.context.inputTextureLayouts[i].shape,n=this.context.inputTextureLayouts[i].strides,s=u.length,c=`offsetToIndices_${o}`;e[c]=new R(tr.offsetToIndicesSingle(c,s,n)),c=`offsetToIndices_${o}_T`,e[c]=new R(tr.offsetToIndicesSingle(c,s,n.slice().reverse()))}),e}static offsetToIndicesSingle(e,o,i){let u=[];for(let n=0;n{let u=this.context.inputTextureLayouts[i].shape,n=u.length,s=`incrementIndices_${o}`,c="";for(let r=0;r= 0; --i) { + if(i > axis) continue; + indices[i] += 1; + if(indices[i] < shape[i]) { + break; + } + indices[i] = 0; + } + } + `;e[s]=new R(d)}),e}}}),bo,np=L(()=>{Vt(),bo=class extends pt{constructor(t){super(t)}getCustomTypes(){return{}}getFunctions(){return{...this.binaryVecFunctions(),...this.copyVec(),...this.setVecItem(),...this.getVecItem()}}binaryVecFunctions(){let t=this.context.outputTextureLayout.shape.length,e={add:"+=",sub:"-=",mul:"*=",div:"/="},o={};for(let i in e){let u=`${i}Vec`,n="";for(let c=0;c{Qc(),ep(),tp(),rp(),np(),qi={encoding:po,fragcolor:ho,vec:bo,shapeUtils:mo,coordinates:co}}),go,ip=L(()=>{Vt(),Jc(),op(),xe(),go=class{constructor(t,e,o,i){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new eo(t,e,o,i),Object.keys(qi).forEach(n=>{let s=new qi[n](this.context);this.libs[n]=s});let u=this.glslLibRoutineDependencyGraph;for(let n in this.libs){let s=this.libs[n].getFunctions();for(let c in s){let d=n+"."+c,r;u[d]?(r=u[d],r.routineBody=s[c].routineBody):(r=new cn(d,s[c].routineBody),u[d]=r);let a=s[c].dependencies;if(a)for(let l=0;l{let i=o.split(".")[1];t.indexOf(i)!==-1&&e.push(this.glslLibRoutineDependencyGraph[o])}),to.returnOrderedNodes(e)}getUniforms(t,e){let o=[];if(t)for(let i of t)o.push(`uniform sampler2D ${i};`);if(e)for(let i of e)o.push(`uniform ${i.type} ${i.name}${i.arrayLength?`[${i.arrayLength}]`:""};`);return o.join(` +`)}}}),yo,ap=L(()=>{vt(),ut(),ip(),xe(),yo=class{constructor(t,e,o){this.profiler=t,this.glContext=e,this.textureLayoutStrategy=o,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,e){this.repo.set(t,e)}run(t,e,o){this.profiler.event("op",`ProgramManager.run ${t.programInfo.name??"unknown kernel"}`,()=>{let i=this.glContext.gl,u=t.program;i.useProgram(u);try{this.bindOutput(o),this.attributesBound||this.bindAttributes(t.attribLocations),this.bindUniforms(t.uniformLocations,t.programInfo.variables??[],e)}catch(n){throw ce.error("ProgramManager",t.programInfo.shaderSource),n}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach(t=>this.glContext.deleteProgram(t.program))}build(t,e,o){return this.profiler.event("backend","ProgramManager.build",()=>{let i=new go(this.glContext,t,e,o),u=i.preprocess(),n=this.compile(u);return{programInfo:t,program:n,uniformLocations:this.getUniformLocations(n,i.context.programInfo.inputNames,i.context.programInfo.variables),attribLocations:this.getAttribLocations(n)}})}compile(t){if(!this.vertexShader){ce.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");let i=Bu(this.glContext.version);this.vertexShader=this.glContext.compileShader(i,this.glContext.gl.VERTEX_SHADER)}Z.debug&&ce.verbose("ProrgramManager",`FragShader: +${t} +`);let e=this.glContext.compileShader(t,this.glContext.gl.FRAGMENT_SHADER),o=this.glContext.createProgram(this.vertexShader,e);return this.glContext.deleteShader(e),o}bindOutput(t){let e=t.width,o=t.height;ce.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${e}/${o}, shape=${t.shape}, type=${t.tensor.type}`),this.glContext.attachFramebuffer(t.texture,e,o)}bindAttributes(t){let e=t.position,o=t.textureCoord;this.glContext.setVertexAttributes(e,o),this.attributesBound=!0}bindUniforms(t,e,o){let i=this.glContext.gl,u=0;for(let{name:n,type:s,location:c,arrayLength:d}of t){let r=e.find(a=>a.name===n)?.data;if(s!=="sampler2D"&&!r)throw new Error(`variable '${n}' does not have data defined in program info`);switch(s){case"sampler2D":this.bindTexture(o[u],c,u),u++;break;case"float":d?i.uniform1fv(c,r):i.uniform1f(c,r);break;case"int":d?i.uniform1iv(c,r):i.uniform1i(c,r);break;default:throw new Error(`Uniform not implemented: ${s}`)}}}bindTexture(t,e,o){this.glContext.bindTextureToUniform(t.texture,o,e)}getAttribLocations(t){return{position:this.getAttribLocation(t,"position"),textureCoord:this.getAttribLocation(t,"textureCoord")}}getUniformLocations(t,e,o){let i=[];if(e)for(let u of e)i.push({name:u,type:"sampler2D",location:this.getUniformLocation(t,u)});if(o)for(let u of o)i.push({...u,location:this.getUniformLocation(t,u.name)});return i}getUniformLocation(t,e){let o=this.glContext.gl.getUniformLocation(t,e);if(o===null)throw new Error(`Uniform ${e} not found.`);return o}getAttribLocation(t,e){return this.glContext.gl.getAttribLocation(t,e)}}}),To,sp=L(()=>{ut(),ln(),To=class{constructor(t,e,o,i){this.glContext=t,this.layoutStrategy=e,this.profiler=o,this.config=i,this.pendingRead=new Map,i.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(t,e,o,i){let u=this.toEncoderType(t),n=this.glContext.getEncoder(u,e.channels||1,i);if(e.isPacked&&i===1)throw new Error("not implemented");let s=e.width,c=e.height,d,r;if(this.config.reuseTextures){d=`${s}x${c}_${n.format}_${n.internalFormat}_${n.textureType}`,r=this.inUseTextures.get(d),r||(r=[],this.inUseTextures.set(d,r));let l=this.idleTextures.get(d);if(l&&l.length>0){let h=l.pop();return r.push(h),i===1&&this.glContext.updateTexture(h,s,c,n,this.toTextureData(t,o)),h}}ce.verbose("TextureManager",`Creating new texture of size ${e.width}x${e.height}`);let a=this.glContext.allocateTexture(s,c,n,this.toTextureData(t,o));return this.config.reuseTextures&&(r.push(a),this.textureLookup.set(a,d)),a}readTexture(t,e,o){return o||(o=1),this.profiler.event("backend","TextureManager.readTexture",()=>{let i=t.shape.reduce((n,s)=>n*s)*o,u=this.glContext.readTexture(t.texture,t.width,t.height,i,this.toEncoderType(e),o);return this.toTensorData(e,u)})}async readTextureAsync(t,e,o){let i=t.tensor.dataId;if(o||(o=1),this.pendingRead.has(i)){let u=this.pendingRead.get(i);return new Promise(n=>u?.push(n))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(i,[]);let u=t.shape.reduce((d,r)=>d*r)*o;await this.glContext.createAndWaitForFence();let n=this.glContext.readTexture(t.texture,t.width,t.height,u,this.toEncoderType(e),o),s=this.toTensorData(e,n),c=this.pendingRead.get(i);return this.pendingRead.delete(i),c?.forEach(d=>d(s)),s})}readUint8TextureAsFloat(t){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{let e=t.shape.reduce((i,u)=>i*u),o=this.glContext.readTexture(t.texture,t.width,t.height,e*4,"byte",4);return new Float32Array(o.buffer,o.byteOffset,e)})}releaseTexture(t,e){let o;if(this.config.reuseTextures&&(o=this.textureLookup.get(t.texture),o)){e&&this.textureLookup.delete(o);let i=this.inUseTextures.get(o);if(i){let u=i.indexOf(t.texture);if(u!==-1){i.splice(u,1);let n=this.idleTextures.get(o);n||(n=[],this.idleTextures.set(o,n)),n.push(t.texture)}}}(!o||e)&&(ce.verbose("TextureManager",`Deleting texture of size ${t.width}x${t.height}`),this.glContext.deleteTexture(t.texture))}toTensorData(t,e){switch(t){case"int16":return e instanceof Int16Array?e:Int16Array.from(e);case"int32":return e instanceof Int32Array?e:Int32Array.from(e);case"int8":return e instanceof Int8Array?e:Int8Array.from(e);case"uint16":return e instanceof Uint16Array?e:Uint16Array.from(e);case"uint32":return e instanceof Uint32Array?e:Uint32Array.from(e);case"uint8":case"bool":return e instanceof Uint8Array?e:Uint8Array.from(e);case"float32":return e instanceof Float32Array?e:Float32Array.from(e);case"float64":return e instanceof Float64Array?e:Float64Array.from(e);default:throw new Error(`TensorData type ${t} is not supported`)}}toTextureData(t,e){if(e)return e instanceof Float32Array?e:new Float32Array(e)}toEncoderType(t){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}}),xo,up=L(()=>{ut(),ws(),Qu(),Yc(),ap(),Hi(),sp(),xo=class{constructor(t,e){this.backend=t,this.context=e,this.layoutStrategy=new fo(t.glContext.maxTextureSize),this.programManager=new yo(this.context.profiler,t.glContext,this.layoutStrategy),this.textureManager=new To(t.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:t.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=t.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new Qn(this)}onGraphInitialized(t){let e=t.getValues().filter(o=>o.from===-1&&o.tensor).map(o=>o.tensor.dataId);this.initializers=new Set(e)}isInitializer(t){return this.initializers?this.initializers.has(t):!1}addInitializer(t){this.initializers.add(t)}getTextureData(t,e){return e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,o=!1){ce.verbose("WebGLSessionHandler","Storing Texture data in cache"),o?this.packedTextureDataCache.set(t,e):this.unpackedTextureDataCache.set(t,e)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(t=>this.textureManager.releaseTexture(t,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(t=>this.textureManager.releaseTexture(t,!0)),this.unpackedTextureDataCache=new Map}resolve(t,e,o){let i=vs(t,e,jc);return{impl:i.opImpl,context:i.opInit?i.opInit(t,o):t}}}});function Hb(t){let e=0;for(;e{vt(),ln(),ln(),Ft(),hn=class{constructor(t,e){this.frameBufferBound=!1,this.itemsToPoll=[],this.gl=t,this.version=e,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(t,e,o,i){let u=this.gl,n=u.createTexture();u.bindTexture(u.TEXTURE_2D,n),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MIN_FILTER,u.NEAREST),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MAG_FILTER,u.NEAREST),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE);let s=i?o.encode(i,t*e):null;return u.texImage2D(u.TEXTURE_2D,0,o.internalFormat,t,e,0,o.format,o.textureType,s),this.checkError(),n}updateTexture(t,e,o,i,u){let n=this.gl;n.bindTexture(n.TEXTURE_2D,t);let s=i.encode(u,e*o);n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,o,i.format,i.textureType,s),this.checkError()}attachFramebuffer(t,e,o){let i=this.gl;i.bindTexture(i.TEXTURE_2D,t),i.bindFramebuffer(i.FRAMEBUFFER,this.framebuffer),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,t,0),this.checkError(),i.viewport(0,0,e,o),i.scissor(0,0,e,o)}readTexture(t,e,o,i,u,n){let s=this.gl;n||(n=1),this.frameBufferBound||this.attachFramebuffer(t,e,o);let c=this.getEncoder(u,n),d=c.allocate(e*o);return s.bindTexture(s.TEXTURE_2D,t),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,t,0),s.readPixels(0,0,e,o,s.RGBA,c.textureType,d),this.checkError(),c.decode(d,i)}isFramebufferReady(){return!0}getActiveTexture(){let t=this.gl;return`TEXTURE${t.getParameter(this.gl.ACTIVE_TEXTURE)-t.TEXTURE0}`}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(t,e){let o=this.gl;o.vertexAttribPointer(t,3,o.FLOAT,!1,20,0),o.enableVertexAttribArray(t),e!==-1&&(o.vertexAttribPointer(e,2,o.FLOAT,!1,20,12),o.enableVertexAttribArray(e)),this.checkError()}createProgram(t,e){let o=this.gl,i=o.createProgram();return o.attachShader(i,t),o.attachShader(i,e),o.linkProgram(i),i}compileShader(t,e){let o=this.gl,i=o.createShader(e);if(!i)throw new Error(`createShader() returned null with type ${e}`);if(o.shaderSource(i,t),o.compileShader(i),o.getShaderParameter(i,o.COMPILE_STATUS)===!1)throw new Error(`Failed to compile shader: ${o.getShaderInfoLog(i)} +Shader source: +${t}`);return i}deleteShader(t){this.gl.deleteShader(t)}bindTextureToUniform(t,e,o){let i=this.gl;i.activeTexture(i.TEXTURE0+e),this.checkError(),i.bindTexture(i.TEXTURE_2D,t),this.checkError(),i.uniform1i(o,e),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(Z.debug){let t=this.gl,e=t.getError(),o="";switch(e){case t.NO_ERROR:return;case t.INVALID_ENUM:o="INVALID_ENUM";break;case t.INVALID_VALUE:o="INVALID_VALUE";break;case t.INVALID_OPERATION:o="INVALID_OPERATION";break;case t.INVALID_FRAMEBUFFER_OPERATION:o="INVALID_FRAMEBUFFER_OPERATION";break;case t.OUT_OF_MEMORY:o="OUT_OF_MEMORY";break;case t.CONTEXT_LOST_WEBGL:o="CONTEXT_LOST_WEBGL";break;default:o=`Unknown WebGL Error: ${e.toString(16)}`}throw new Error(o)}}deleteTexture(t){this.gl.deleteTexture(t)}deleteProgram(t){this.gl.deleteProgram(t)}getEncoder(t,e,o=0){if(this.version===2)return new Jn(this.gl,e);switch(t){case"float":return o===1||this.isRenderFloat32Supported?new un(this.gl,e):new un(this.gl,e,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new Zn(this.gl,e);default:throw new Error(`Invalid dataType: ${t}`)}}clearActiveTextures(){let t=this.gl;for(let e=0;ethis.isTimerResultAvailable(t)),this.getTimerResult(t)}async createAndWaitForFence(){let t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e,o=t,i=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),i===null?e=()=>!0:e=()=>{let u=o.clientWaitSync(i,0,0);return u===o.ALREADY_SIGNALED||u===o.CONDITION_SATISFIED},{query:i,isFencePassed:e}}async pollFence(t){return new Promise(e=>{this.addItemToPoll(()=>t.isFencePassed(),()=>e())})}pollItems(){let t=Hb(this.itemsToPoll.map(e=>e.isDoneFn));for(let e=0;e<=t;++e){let{resolveFn:o}=this.itemsToPoll[e];o()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}async addItemToPoll(t,e){this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),!(this.itemsToPoll.length>1)&&await gi(()=>(this.pollItems(),this.itemsToPoll.length===0))}}});function ji(t){let e;if((!t||t==="webgl2")&&"webgl2"in Ur?e=Ur.webgl2:(!t||t==="webgl")&&"webgl"in Ur&&(e=Ur.webgl),!e)try{let i=jb();e=fp(i,t)}catch{let i=qb();e=fp(i,t)}t=t||e.version===1?"webgl":"webgl2";let o=e.gl;return Ur[t]=e,o.isContextLost()?(delete Ur[t],ji(t)):(o.disable(o.DEPTH_TEST),o.disable(o.STENCIL_TEST),o.disable(o.BLEND),o.disable(o.DITHER),o.disable(o.POLYGON_OFFSET_FILL),o.disable(o.SAMPLE_COVERAGE),o.enable(o.SCISSOR_TEST),o.enable(o.CULL_FACE),o.cullFace(o.BACK),e)}function fp(t,e){let o={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1},i,u=o;if((!e||e==="webgl2")&&(i=t.getContext("webgl2",u),i))try{return new hn(i,2)}catch(n){ce.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${n}`)}if((!e||e==="webgl")&&(i=t.getContext("webgl",u)||t.getContext("experimental-webgl",u),i))try{return new hn(i,1)}catch(n){ce.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${n}`)}throw new Error("WebGL is not supported")}function qb(){if(typeof document>"u")throw new TypeError("failed to create canvas: document is not supported");let t=document.createElement("canvas");return t.width=1,t.height=1,t}function jb(){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}var Ur,cp=L(()=>{ut(),lp(),Ur={}}),vo,pp=L(()=>{vt(),ut(),up(),cp(),vo=class{get contextId(){return Z.webgl.contextId}set contextId(t){Z.webgl.contextId=t}get matmulMaxBatchSize(){return Z.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(t){Z.webgl.matmulMaxBatchSize=t}get textureCacheMode(){return Z.webgl.textureCacheMode}set textureCacheMode(t){Z.webgl.textureCacheMode=t}get pack(){return Z.webgl.pack}set pack(t){Z.webgl.pack=t}get async(){return Z.webgl.async}set async(t){Z.webgl.async=t}initialize(){try{return this.glContext=ji(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),ce.setWithEnv(Z),Z.webgl.context||Object.defineProperty(Z.webgl,"context",{value:this.glContext.gl}),ce.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(t){return ce.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${t}`),!1}}createSessionHandler(t){return new xo(this,t)}dispose(){this.glContext.dispose()}}});async function Yi(t){if(t){let e=typeof t=="string"?[t]:t;for(let o of e){let i=dp.get(o);if(i)return i;let u=await Xb(o);if(u)return u}}else return Yi(["webgl"]);throw new Error("no available backend to use")}async function Xb(t){let e=Yb;if(typeof e[t]<"u"&&Kb(e[t])){let o=e[t],i=o.initialize();if(typeof i=="object"&&"then"in i&&(i=await i),i)return dp.set(t,o),o}}function Kb(t){let e=t;return"initialize"in e&&typeof e.initialize=="function"&&"createSessionHandler"in e&&typeof e.createSessionHandler=="function"&&"dispose"in e&&typeof e.dispose=="function"}var dp,Yb,hp=L(()=>{pp(),dp=new Map,Yb={webgl:new vo}}),Xi,wo,mp=L(()=>{ut(),Xi=class{constructor(t,e){this.op=t,this.node=e}},wo=class{constructor(t,e,o){this.graph=t,this.profiler=o,this.initialize(e)}initialize(t){this.profiler.event("session","ExecutionPlan.initialize",()=>{let e=this.graph.getNodes();if(e.length!==t.length)throw new Error("The size of nodes and OPs do not match.");this._ops=t.map((o,i)=>new Xi(o,e[i])),this.reset(),this._starter=[],this._ops.forEach((o,i)=>{let u=!0;for(let n of o.node.inputs)if(!this._values[n]&&this.graph.getInputIndices().indexOf(n)===-1){u=!1;break}u&&this._starter.push(i)})})}reset(){this._values=this.graph.getValues().map(t=>t.tensor)}async execute(t,e){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();let o=t.createInferenceHandler(),i=this.graph.getInputIndices();if(e.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${e.length} expected: ${i.length}`);e.forEach((r,a)=>{let l=i[a];this._values[l]=r});let u=this._starter.slice(0),n=this.graph.getValues(),s=this.graph.getNodes(),c=0;for(;cthis._values[g]);if(l.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${a.node}`);let h=l;ce.verbose("ExecPlan",`Runing op:${a.node.name} (${h.map((g,b)=>`'${a.node.inputs[b]}': ${g.type}[${g.dims.join(",")}]`).join(", ")})`);let f=await this.profiler.event("node",a.node.name,async()=>a.op.impl(o,h,a.op.context));if(f.length!==a.node.outputs.length)throw new Error("the size of output does not match model definition.");f.forEach((g,b)=>{let v=a.node.outputs[b];if(this._values[v])throw new Error(`output [${v}] already has value: op:${a.node.name}`);this._values[v]=g});let m=new Set;f.forEach((g,b)=>{let v=a.node.outputs[b];for(let T of n[v].to){let E=s[T],M=!0;for(let F of E.inputs)if(!this._values[F]){M=!1;break}M&&m.add(T)}}),u.push(...m)}let d=[];for(let r=0;r{tn(),oe=Er($r()),mr(),fe(),mt=W.experimental.fbs,mn=class lr{constructor(e){if(this._attributes=new Map,e!=null){for(let o of e)o instanceof oe.onnx.AttributeProto?this._attributes.set(o.name,[lr.getValue(o),lr.getType(o)]):o instanceof mt.Attribute&&this._attributes.set(o.name(),[lr.getValue(o),lr.getType(o)]);if(this._attributes.sizeFe.fromProto(u));if(e instanceof mt.Attribute)return i.map(u=>Fe.fromOrtTensor(u))}return o===oe.onnx.AttributeProto.AttributeType.STRING&&e instanceof oe.onnx.AttributeProto?sn(i):o===oe.onnx.AttributeProto.AttributeType.STRINGS&&e instanceof oe.onnx.AttributeProto?i.map(sn):i}static getValueNoCheck(e){return e instanceof oe.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(e):this.getValueNoCheckFromOrtFormat(e)}static getValueNoCheckFromOnnxFormat(e){switch(e.type){case oe.onnx.AttributeProto.AttributeType.FLOAT:return e.f;case oe.onnx.AttributeProto.AttributeType.INT:return e.i;case oe.onnx.AttributeProto.AttributeType.STRING:return e.s;case oe.onnx.AttributeProto.AttributeType.TENSOR:return e.t;case oe.onnx.AttributeProto.AttributeType.GRAPH:return e.g;case oe.onnx.AttributeProto.AttributeType.FLOATS:return e.floats;case oe.onnx.AttributeProto.AttributeType.INTS:return e.ints;case oe.onnx.AttributeProto.AttributeType.STRINGS:return e.strings;case oe.onnx.AttributeProto.AttributeType.TENSORS:return e.tensors;case oe.onnx.AttributeProto.AttributeType.GRAPHS:return e.graphs;default:throw new Error(`unsupported attribute type: ${oe.onnx.AttributeProto.AttributeType[e.type]}`)}}static getValueNoCheckFromOrtFormat(e){switch(e.type()){case mt.AttributeType.FLOAT:return e.f();case mt.AttributeType.INT:return e.i();case mt.AttributeType.STRING:return e.s();case mt.AttributeType.TENSOR:return e.t();case mt.AttributeType.GRAPH:return e.g();case mt.AttributeType.FLOATS:return e.floatsArray();case mt.AttributeType.INTS:{let o=[];for(let i=0;i{bp(),tn(),Ji=Er($r()),mr(),fe(),_o=W.experimental.fbs,Zi={from:(t,e)=>new Ki(t,e)},kt=class{constructor(t){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,t&&(this.type=Ve.tensorValueTypeFromProto(t.type.tensorType))}get from(){return this._from}get to(){return this._to}},Oo=class{constructor(t,e){t instanceof Ji.onnx.NodeProto?(this.name=t.name,this.opType=t.opType,this.attributes=new mn(t.attribute)):t instanceof _o.Node&&(this.name=e??t.name(),this.opType=t.opType(),this.attributes=new mn(Ve.tensorAttributesFromORTFormat(t))),this.inputs=[],this.outputs=[],this.executeNode=!0}},Ki=class{constructor(t,e){if(!t)throw new TypeError("graph is empty");this.buildGraph(t),this.transformGraph(e),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(t){if(t instanceof Ji.onnx.GraphProto)this.buildGraphFromOnnxFormat(t);else if(t instanceof _o.Graph)this.buildGraphFromOrtFormat(t);else throw new TypeError("Graph type is not supported.")}buildGraphFromOnnxFormat(t){let e=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let o=new Map;if(!t.input)throw new Error("missing information in graph: input");let i=[];for(let u of t.input){if(e.has(u.name))throw new Error(`duplicated input name: ${u.name}`);let n=this._allData.push(new kt(u))-1;e.set(u.name,n),i.push(u.name)}if(!t.initializer)throw new Error("missing information in graph: initializer");for(let u of t.initializer){let n=e.get(u.name);if(n===void 0){let s=new kt;s.type={shape:{dims:Ve.tensorDimsFromProto(u.dims)},tensorType:Ve.tensorDataTypeFromProto(u.dataType)},n=this._allData.push(s)-1,e.set(u.name,n)}this._allData[n]._from=-1,this._allData[n].tensor=Fe.fromProto(u)}for(let u=0;u"u"&&(d=this._allData.push(new kt)-1,e.set(c,d)),n.outputs.push(d),this._allData[d]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${d}`);if(this._allData[d]._from=u,s.opType==="Constant"){if(!s.attribute||s.attribute.length!==1||!s.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!s.output||s.output.length!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");n.outputs.pop(),n.executeNode=!1,this._allData[d]._from=-1,this._allData[d].tensor=Fe.fromProto(s.attribute[0].t)}}}for(let u=0;u"u"){if(c===""&&(s.input.length===3||s.input.length===4)&&s.opType==="Resize")continue;throw new Error(`unrecognized input '${c}' for node: ${s.name}`)}n.inputs.push(d),this._allData[d]._to.push(u)}}return!0}buildGraphFromOrtFormat(t){let e=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let o=new Map,i=[];for(let u=0;u"u"&&(r=this._allData.push(new kt)-1,e.set(d,r)),n.outputs.push(r),this._allData[r]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${r}`);if(this._allData[r]._from=u,s.opType()==="Constant"){if(s.attributesLength()!==1||!s.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(s.outputsLength()!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");n.outputs.pop(),n.executeNode=!1,this._allData[r]._from=-1,this._allData[r].tensor=Fe.fromOrtTensor(s.attributes(0).t())}}}for(let u=0;u"u")throw new Error(`unrecognized input '${d}' for node: ${s.name()}`);n.inputs.push(r),this._allData[r]._to.push(u)}}}checkIsAcyclic(){let t=new Set;this._allInputIndices.forEach(i=>{this._allData[i]._to.forEach(u=>{t.add(u)})});let e=Array.from(t),o=new Array(this._nodes.length).fill("white");for(;e.length>0;){let i=e.pop();o[i]==="gray"?o[i]="black":(e.push(i),o[i]="gray",this._nodes[i].outputs.forEach(u=>{let n=this._allData[u];if(typeof n.tensor<"u")throw new Error("node outputs should not be initialized");if(n._from!==i)throw new Error("from property of the Value object doesn't match index of Node being processed");n._to.forEach(s=>{if(o[s]==="gray")throw new Error("model graph is cyclic");o[s]==="white"&&e.push(s)})}))}}transformGraph(t){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),t&&t.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let t=0,e=new Array(this._nodes.length,0),o=0;for(let i=0;i{this._allData[u]._from=-2});this._nodes.splice(o,this._nodes.length-o);for(let i=0;i=0)u._to[n]=e[u._to[n]];else throw new Error("Trying to update a removed node")}t=0;for(let i=0;i0){let u=-1;this._allData[i].from!==void 0&&this._allData[i].from!==-1?(u=this._nodes[this._allData[i].from].outputs.indexOf(i+t),u!==-1&&(this._nodes[this._allData[i].from].outputs[u]=i)):(u=this._allInputIndices.indexOf(i+t),u!==-1&&(this._allInputIndices[u]=i)),this._allData[i].to.forEach(n=>{u=this._nodes[n].inputs.indexOf(i+t),u!==-1&&(this._nodes[n].inputs[u]=i)}),this._allData[i].to.length===0&&(u=this._allOutputIndices.indexOf(i+t),u!==-1&&(this._allOutputIndices[u]=i))}}}deleteNode(t){let e=this._nodes[t];if(e.outputs.length>1){for(let s=1;s0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}e.executeNode=!1;let o=e.inputs[0],i=e.outputs[0],u=this._allData[i].to;for(let s=0;s0)for(let s of u){let c=this._nodes[s].inputs.indexOf(i);if(c===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[s].inputs[c]=o,this._allData[o].to.push(s)}}removeAllDropoutNodes(){let t=0;for(let e of this._nodes){if(e.opType==="Dropout"){if(e.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(e.outputs.length!==1&&e.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(e.outputs.length===2&&this._allData[e.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(t)}t++}}removeAllIdentityNodes(){let t=0;for(let e of this._nodes)e.opType==="Identity"&&this.deleteNode(t),t++}isActivation(t){switch(t.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(let t of this._nodes)if(t.opType==="Conv"){let e=this._allData[t.outputs[0]]._to;if(e.length===1&&this.isActivation(this._nodes[e[0]])){let o=this._nodes[e[0]];if(o.opType==="Clip")if(o.inputs.length===1)try{t.attributes.set("activation_params","floats",[o.attributes.getFloat("min"),o.attributes.getFloat("max")])}catch{t.attributes.set("activation_params","floats",[dr,hr])}else if(o.inputs.length>=3&&this._allData[o.inputs[1]].tensor!==void 0&&this._allData[o.inputs[2]].tensor!==void 0)t.attributes.set("activation_params","floats",[this._allData[o.inputs[1]].tensor.floatData[0],this._allData[o.inputs[2]].tensor.floatData[0]]);else continue;t.attributes.set("activation","string",o.opType),this.deleteNode(e[0])}}}}}),yp,Jb,Io,Tp=L(()=>{Wn(),gp(),tn(),yp=Er($r()),fe(),Jb=W.experimental.fbs,Io=class{constructor(){}load(t,e,o){if(!o)try{this.loadFromOnnxFormat(t,e);return}catch(i){if(o!==void 0)throw i}this.loadFromOrtFormat(t,e)}loadFromOnnxFormat(t,e){let o=yp.onnx.ModelProto.decode(t);if(nt.longToNumber(o.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=o.opsetImport.map(i=>({domain:i.domain,version:nt.longToNumber(i.version)})),this._graph=Zi.from(o.graph,e)}loadFromOrtFormat(t,e){let o=new _.ByteBuffer(t),i=Jb.InferenceSession.getRootAsInferenceSession(o).model();if(nt.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let u=0;u{hp(),mp(),ut(),Tp(),So=class{constructor(t={}){this._initialized=!1,this.backendHint=t.backendHint,this.profiler=zn.create(t.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(t,e,o){await this.profiler.event("session","Session.loadModel",async()=>{let i=await Yi(this.backendHint);if(this.sessionHandler=i.createSessionHandler(this.context),this._model=new Io,typeof t=="string"){let u=t.endsWith(".ort");if(typeof process<"u"&&process.versions&&process.versions.node){let n=await(void 0)(t);this.initialize(n,u)}else{let n=await(await fetch(t)).arrayBuffer();this.initialize(new Uint8Array(n),u)}}else if(ArrayBuffer.isView(t))this.initialize(t);else{let u=new Uint8Array(t,e||0,o||t.byteLength);this.initialize(u)}})}initialize(t,e){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{let o=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(t,o,e),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new wo(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(t){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{let e=this.normalizeAndValidateInputs(t),o=await this._executionPlan.execute(this.sessionHandler,e);return this.createOutput(o)})}normalizeAndValidateInputs(t){let e=this._model.graph.getInputNames();if(Array.isArray(t)){if(t.length!==e.length)throw new Error(`incorrect input array length: expected ${e.length} but got ${t.length}`)}else{if(t.size!==e.length)throw new Error(`incorrect input map size: expected ${e.length} but got ${t.size}`);let o=new Array(t.size),i=0;for(let u=0;u{vt(),mr(),Ao=class{constructor(t){this.session=t,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(t,e,o){let i=new Map;for(let s in t)if(Object.hasOwnProperty.call(t,s)){let c=t[s];i.set(s,new Fe(c.dims,c.type,void 0,void 0,c.data))}let u=await this.session.run(i),n={};return u.forEach((s,c)=>{n[c]=new Re(s.type,s.data,s.dims)}),n}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}}),wp={};Pr(wp,{onnxjsBackend:()=>Qb});var Qi,Qb,_p=L(()=>{xp(),vp(),Qi=class{async init(){}async createInferenceSessionHandler(t,e){let o=new So(e);return typeof t=="string"?await o.loadModel(t):await o.loadModel(t),new Ao(o)}},Qb=new Qi}),ea={};Pr(ea,{createReadStream:()=>Op,readFile:()=>eg,readFileSync:()=>tg});var eg,tg,Op,ta=L(()=>{eg=void 0,tg=void 0,Op=void 0}),ra={};Pr(ra,{join:()=>rg});var rg,na=L(()=>{rg=void 0}),Ap=me((t,e)=>{var o=(()=>{var i=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(i=i||__filename),function(u={}){var n=u,s,c;n.ready=new Promise((w,O)=>{s=w,c=O});var d=Object.assign({},n),r="./this.program",a=typeof window=="object",l=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",f="",m,g,b;if(h){var v=(ta(),rr(ea)),T=(na(),rr(ra));f=l?T.dirname(f)+"/":__dirname+"/",m=(w,O)=>(w=ge(w)?new URL(w):T.normalize(w),v.readFileSync(w,O?void 0:"utf8")),b=w=>(w=m(w,!0),w.buffer||(w=new Uint8Array(w)),w),g=(w,O,S,D=!0)=>{w=ge(w)?new URL(w):T.normalize(w),v.readFile(w,D?void 0:"utf8",(B,K)=>{B?S(B):O(D?K.buffer:K)})},!n.thisProgram&&1"[Emscripten Module object]"}else(a||l)&&(l?f=self.location.href:typeof document<"u"&&document.currentScript&&(f=document.currentScript.src),i&&(f=i),f.indexOf("blob:")!==0?f=f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):f="",m=w=>{var O=new XMLHttpRequest;return O.open("GET",w,!1),O.send(null),O.responseText},l&&(b=w=>{var O=new XMLHttpRequest;return O.open("GET",w,!1),O.responseType="arraybuffer",O.send(null),new Uint8Array(O.response)}),g=(w,O,S)=>{var D=new XMLHttpRequest;D.open("GET",w,!0),D.responseType="arraybuffer",D.onload=()=>{D.status==200||D.status==0&&D.response?O(D.response):S()},D.onerror=S,D.send(null)});var E=console.log.bind(console),M=console.error.bind(console);Object.assign(n,d),d=null,typeof WebAssembly!="object"&&se("no native wasm support detected");var F,Y=!1,H,X,k,ne,Ce;function Me(){var w=F.buffer;n.HEAP8=H=new Int8Array(w),n.HEAP16=new Int16Array(w),n.HEAPU8=X=new Uint8Array(w),n.HEAPU16=new Uint16Array(w),n.HEAP32=k=new Int32Array(w),n.HEAPU32=ne=new Uint32Array(w),n.HEAPF32=new Float32Array(w),n.HEAPF64=Ce=new Float64Array(w)}var we=[],z=[],de=[],ie=0,re=null;function se(w){throw w="Aborted("+w+")",M(w),Y=!0,w=new WebAssembly.RuntimeError(w+". Build with -sASSERTIONS for more info."),c(w),w}var V=w=>w.startsWith("data:application/octet-stream;base64,"),ge=w=>w.startsWith("file://"),he;if(he="ort-wasm.wasm",!V(he)){var Ze=he;he=n.locateFile?n.locateFile(Ze,f):f+Ze}function Qe(w){if(b)return b(w);throw"both async and sync fetching of the wasm failed"}function Be(w){if(a||l){if(typeof fetch=="function"&&!ge(w))return fetch(w,{credentials:"same-origin"}).then(O=>{if(!O.ok)throw"failed to load wasm binary file at '"+w+"'";return O.arrayBuffer()}).catch(()=>Qe(w));if(g)return new Promise((O,S)=>{g(w,D=>O(new Uint8Array(D)),S)})}return Promise.resolve().then(()=>Qe(w))}function je(w,O,S){return Be(w).then(D=>WebAssembly.instantiate(D,O)).then(D=>D).then(S,D=>{M(`failed to asynchronously prepare wasm: ${D}`),se(D)})}function Ue(w,O){var S=he;return typeof WebAssembly.instantiateStreaming!="function"||V(S)||ge(S)||h||typeof fetch!="function"?je(S,w,O):fetch(S,{credentials:"same-origin"}).then(D=>WebAssembly.instantiateStreaming(D,w).then(O,function(B){return M(`wasm streaming compile failed: ${B}`),M("falling back to ArrayBuffer instantiation"),je(S,w,O)}))}var Ne,Se={919888:(w,O,S,D)=>{if(typeof n>"u"||!n.za)return 1;if(w=xt(w>>>0),w.startsWith("./")&&(w=w.substring(2)),w=n.za.get(w),!w)return 2;if(O>>>=0,S>>>=0,O+S>w.byteLength)return 3;try{return X.set(w.subarray(O,O+S),D>>>0>>>0),0}catch{return 4}}};function _e(w){this.xa=w-24,this.Ha=function(O){ne[this.xa+4>>>2>>>0]=O},this.Ga=function(O){ne[this.xa+8>>>2>>>0]=O},this.Aa=function(O,S){this.Fa(),this.Ha(O),this.Ga(S)},this.Fa=function(){ne[this.xa+16>>>2>>>0]=0}}var Le=0,at=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,ct=(w,O,S)=>{O>>>=0;var D=O+S;for(S=O;w[S]&&!(S>=D);)++S;if(16B?D+=String.fromCharCode(B):(B-=65536,D+=String.fromCharCode(55296|B>>10,56320|B&1023))}}else D+=String.fromCharCode(B)}return D},xt=(w,O)=>(w>>>=0)?ct(X,w,O):"",gt=w=>{for(var O=0,S=0;S=D?O++:2047>=D?O+=2:55296<=D&&57343>=D?(O+=4,++S):O+=3}return O},it=(w,O,S,D)=>{if(S>>>=0,!(0=ue){var $e=w.charCodeAt(++K);ue=65536+((ue&1023)<<10)|$e&1023}if(127>=ue){if(S>=D)break;O[S++>>>0]=ue}else{if(2047>=ue){if(S+1>=D)break;O[S++>>>0]=192|ue>>6}else{if(65535>=ue){if(S+2>=D)break;O[S++>>>0]=224|ue>>12}else{if(S+3>=D)break;O[S++>>>0]=240|ue>>18,O[S++>>>0]=128|ue>>12&63}O[S++>>>0]=128|ue>>6&63}O[S++>>>0]=128|ue&63}}return O[S>>>0]=0,S-B},st=w=>w%4===0&&(w%100!==0||w%400===0),fr=[0,31,60,91,121,152,182,213,244,274,305,335],Bt=[0,31,59,90,120,151,181,212,243,273,304,334],_r=w=>{var O=gt(w)+1,S=Nt(O);return S&&it(w,X,S,O),S},et=[],Dt={},Ot=()=>{if(!Et){var w={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:r||"./this.program"},O;for(O in Dt)Dt[O]===void 0?delete w[O]:w[O]=Dt[O];var S=[];for(O in w)S.push(`${O}=${w[O]}`);Et=S}return Et},Et,wr=[null,[],[]],yt=[31,29,31,30,31,30,31,31,30,31,30,31],Gt=[31,28,31,30,31,30,31,31,30,31,30,31];function vr(w){var O=Array(gt(w)+1);return it(w,O,0,O.length),O}function Pt(w,O,S,D){function B(A,pe,ve){for(A=typeof A=="number"?A.toString():A||"";A.lengthKt?-1:0rt-A.getDate())pe-=rt-A.getDate()+1,A.setDate(1),11>ve?A.setMonth(ve+1):(A.setMonth(0),A.setFullYear(A.getFullYear()+1));else{A.setDate(A.getDate()+pe);break}}return ve=new Date(A.getFullYear()+1,0,4),pe=$e(new Date(A.getFullYear(),0,4)),ve=$e(ve),0>=ue(pe,A)?0>=ue(ve,A)?A.getFullYear()+1:A.getFullYear():A.getFullYear()-1}w>>>=0,O>>>=0,S>>>=0,D>>>=0;var ze=ne[D+40>>>2>>>0];D={Da:k[D>>>2>>>0],Ca:k[D+4>>>2>>>0],va:k[D+8>>>2>>>0],ya:k[D+12>>>2>>>0],wa:k[D+16>>>2>>>0],ua:k[D+20>>>2>>>0],oa:k[D+24>>>2>>>0],ta:k[D+28>>>2>>>0],Ia:k[D+32>>>2>>>0],Ba:k[D+36>>>2>>>0],Ea:ze?xt(ze):""},S=xt(S),ze={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var qe in ze)S=S.replace(new RegExp(qe,"g"),ze[qe]);var Ht="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Yt="January February March April May June July August September October November December".split(" ");ze={"%a":A=>Ht[A.oa].substring(0,3),"%A":A=>Ht[A.oa],"%b":A=>Yt[A.wa].substring(0,3),"%B":A=>Yt[A.wa],"%C":A=>K((A.ua+1900)/100|0,2),"%d":A=>K(A.ya,2),"%e":A=>B(A.ya,2," "),"%g":A=>He(A).toString().substring(2),"%G":A=>He(A),"%H":A=>K(A.va,2),"%I":A=>(A=A.va,A==0?A=12:12{for(var pe=0,ve=0;ve<=A.wa-1;pe+=(st(A.ua+1900)?yt:Gt)[ve++]);return K(A.ya+pe,3)},"%m":A=>K(A.wa+1,2),"%M":A=>K(A.Ca,2),"%n":()=>` +`,"%p":A=>0<=A.va&&12>A.va?"AM":"PM","%S":A=>K(A.Da,2),"%t":()=>" ","%u":A=>A.oa||7,"%U":A=>K(Math.floor((A.ta+7-A.oa)/7),2),"%V":A=>{var pe=Math.floor((A.ta+7-(A.oa+6)%7)/7);if(2>=(A.oa+371-A.ta-2)%7&&pe++,pe)pe==53&&(ve=(A.oa+371-A.ta)%7,ve==4||ve==3&&st(A.ua)||(pe=1));else{pe=52;var ve=(A.oa+7-A.ta-1)%7;(ve==4||ve==5&&st(A.ua%400-1))&&pe++}return K(pe,2)},"%w":A=>A.oa,"%W":A=>K(Math.floor((A.ta+7-(A.oa+6)%7)/7),2),"%y":A=>(A.ua+1900).toString().substring(2),"%Y":A=>A.ua+1900,"%z":A=>{A=A.Ba;var pe=0<=A;return A=Math.abs(A)/60,(pe?"+":"-")+("0000"+(A/60*100+A%60)).slice(-4)},"%Z":A=>A.Ea,"%%":()=>"%"},S=S.replace(/%%/g,"\0\0");for(qe in ze)S.includes(qe)&&(S=S.replace(new RegExp(qe,"g"),ze[qe](D)));return S=S.replace(/\0\0/g,"%"),qe=vr(S),qe.length>O?0:(H.set(qe,w>>>0),qe.length-1)}var Hr={a:function(w,O,S){throw w>>>=0,new _e(w).Aa(O>>>0,S>>>0),Le=w,Le},e:function(){return 0},H:function(){},x:function(){},z:function(){},J:function(){return 0},F:function(){},A:function(){},E:function(){},g:function(){},y:function(){},v:function(){},G:function(){},w:function(){},k:()=>1,n:function(w,O,S){w=O+2097152>>>0<4194305-!!w?(w>>>0)+4294967296*O:NaN,S>>>=0,w=new Date(1e3*w),k[S>>>2>>>0]=w.getUTCSeconds(),k[S+4>>>2>>>0]=w.getUTCMinutes(),k[S+8>>>2>>>0]=w.getUTCHours(),k[S+12>>>2>>>0]=w.getUTCDate(),k[S+16>>>2>>>0]=w.getUTCMonth(),k[S+20>>>2>>>0]=w.getUTCFullYear()-1900,k[S+24>>>2>>>0]=w.getUTCDay(),k[S+28>>>2>>>0]=(w.getTime()-Date.UTC(w.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},o:function(w,O,S){w=O+2097152>>>0<4194305-!!w?(w>>>0)+4294967296*O:NaN,S>>>=0,w=new Date(1e3*w),k[S>>>2>>>0]=w.getSeconds(),k[S+4>>>2>>>0]=w.getMinutes(),k[S+8>>>2>>>0]=w.getHours(),k[S+12>>>2>>>0]=w.getDate(),k[S+16>>>2>>>0]=w.getMonth(),k[S+20>>>2>>>0]=w.getFullYear()-1900,k[S+24>>>2>>>0]=w.getDay(),k[S+28>>>2>>>0]=(st(w.getFullYear())?fr:Bt)[w.getMonth()]+w.getDate()-1|0,k[S+36>>>2>>>0]=-(60*w.getTimezoneOffset()),O=new Date(w.getFullYear(),6,1).getTimezoneOffset();var D=new Date(w.getFullYear(),0,1).getTimezoneOffset();k[S+32>>>2>>>0]=(O!=D&&w.getTimezoneOffset()==Math.min(D,O))|0},p:function(w){w>>>=0;var O=new Date(k[w+20>>>2>>>0]+1900,k[w+16>>>2>>>0],k[w+12>>>2>>>0],k[w+8>>>2>>>0],k[w+4>>>2>>>0],k[w>>>2>>>0],0),S=k[w+32>>>2>>>0],D=O.getTimezoneOffset(),B=new Date(O.getFullYear(),6,1).getTimezoneOffset(),K=new Date(O.getFullYear(),0,1).getTimezoneOffset(),ue=Math.min(K,B);return 0>S?k[w+32>>>2>>>0]=+(B!=K&&ue==D):0>>2>>>0]=O.getDay(),k[w+28>>>2>>>0]=(st(O.getFullYear())?fr:Bt)[O.getMonth()]+O.getDate()-1|0,k[w>>>2>>>0]=O.getSeconds(),k[w+4>>>2>>>0]=O.getMinutes(),k[w+8>>>2>>>0]=O.getHours(),k[w+12>>>2>>>0]=O.getDate(),k[w+16>>>2>>>0]=O.getMonth(),k[w+20>>>2>>>0]=O.getYear(),w=O.getTime(),isNaN(w)?(k[Wt()>>>2>>>0]=61,w=-1):w/=1e3,Or((Ne=w,1<=+Math.abs(Ne)?0>>0:~~+Math.ceil((Ne-+(~~Ne>>>0))/4294967296)>>>0:0)),w>>>0},l:function(){return-52},m:function(){},t:function(w,O,S){function D(He){return(He=He.toTimeString().match(/\(([A-Za-z ]+)\)$/))?He[1]:"GMT"}S>>>=0;var B=new Date().getFullYear(),K=new Date(B,0,1),ue=new Date(B,6,1);B=K.getTimezoneOffset();var $e=ue.getTimezoneOffset();ne[w>>>0>>>2>>>0]=60*Math.max(B,$e),k[O>>>0>>>2>>>0]=+(B!=$e),w=D(K),O=D(ue),w=_r(w),O=_r(O),$e>>2>>>0]=w,ne[S+4>>>2>>>0]=O):(ne[S>>>2>>>0]=O,ne[S+4>>>2>>>0]=w)},d:()=>{se("")},B:function(w,O,S){w>>>=0,O>>>=0,S>>>=0,et.length=0;for(var D;D=X[O++>>>0];){var B=D!=105;B&=D!=112,S+=B&&S%8?4:0,et.push(D==112?ne[S>>>2>>>0]:D==105?k[S>>>2>>>0]:Ce[S>>>3>>>0]),S+=B?8:4}return Se[w].apply(null,et)},h:()=>Date.now(),u:function(){return 4294901760},b:()=>performance.now(),I:function(w,O,S){return O>>>=0,X.copyWithin(w>>>0>>>0,O>>>0,O+(S>>>0)>>>0)},s:function(w){w>>>=0;var O=X.length;if(4294901760=S;S*=2){var D=O*(1+.2/S);D=Math.min(D,w+100663296);var B=Math;D=Math.max(w,D);e:{B=(B.min.call(B,4294901760,D+(65536-D%65536)%65536)-F.buffer.byteLength+65535)/65536;try{F.grow(B),Me();var K=1;break e}catch{}K=void 0}if(K)return!0}return!1},C:function(w,O){w>>>=0,O>>>=0;var S=0;return Ot().forEach((D,B)=>{var K=O+S;for(B=ne[w+4*B>>>2>>>0]=K,K=0;K>>0>>>0]=D.charCodeAt(K);H[B>>>0>>>0]=0,S+=D.length+1}),0},D:function(w,O){w>>>=0,O>>>=0;var S=Ot();ne[w>>>2>>>0]=S.length;var D=0;return S.forEach(B=>D+=B.length+1),ne[O>>>2>>>0]=D,0},f:()=>52,j:function(){return 52},q:function(){return 70},i:function(w,O,S,D){O>>>=0,S>>>=0,D>>>=0;for(var B=0,K=0;K>>2>>>0],$e=ne[O+4>>>2>>>0];O+=8;for(var He=0;He<$e;He++){var ze=X[ue+He>>>0],qe=wr[w];ze===0||ze===10?((w===1?E:M)(ct(qe,0)),qe.length=0):qe.push(ze)}B+=$e}return ne[D>>>2>>>0]=B,0},r:Pt,c:function(w,O,S,D){return Pt(w>>>0,O>>>0,S>>>0,D>>>0)}},j=function(){function w(S){return j=S.exports,j=Lt(),F=j.K,Me(),z.unshift(j.L),ie--,ie==0&&re&&(S=re,re=null,S()),j}var O={a:Hr};if(ie++,n.instantiateWasm)try{return n.instantiateWasm(O,w)}catch(S){M(`Module.instantiateWasm callback failed with error: ${S}`),c(S)}return Ue(O,function(S){w(S.instance)}).catch(c),{}}();n._OrtInit=(w,O)=>(n._OrtInit=j.M)(w,O),n._OrtGetLastError=(w,O)=>(n._OrtGetLastError=j.N)(w,O),n._OrtCreateSessionOptions=(w,O,S,D,B,K,ue,$e,He,ze)=>(n._OrtCreateSessionOptions=j.O)(w,O,S,D,B,K,ue,$e,He,ze),n._OrtAppendExecutionProvider=(w,O)=>(n._OrtAppendExecutionProvider=j.P)(w,O),n._OrtAddFreeDimensionOverride=(w,O,S)=>(n._OrtAddFreeDimensionOverride=j.Q)(w,O,S),n._OrtAddSessionConfigEntry=(w,O,S)=>(n._OrtAddSessionConfigEntry=j.R)(w,O,S),n._OrtReleaseSessionOptions=w=>(n._OrtReleaseSessionOptions=j.S)(w),n._OrtCreateSession=(w,O,S)=>(n._OrtCreateSession=j.T)(w,O,S),n._OrtReleaseSession=w=>(n._OrtReleaseSession=j.U)(w),n._OrtGetInputOutputCount=(w,O,S)=>(n._OrtGetInputOutputCount=j.V)(w,O,S),n._OrtGetInputName=(w,O)=>(n._OrtGetInputName=j.W)(w,O),n._OrtGetOutputName=(w,O)=>(n._OrtGetOutputName=j.X)(w,O),n._OrtFree=w=>(n._OrtFree=j.Y)(w),n._OrtCreateTensor=(w,O,S,D,B,K)=>(n._OrtCreateTensor=j.Z)(w,O,S,D,B,K),n._OrtGetTensorData=(w,O,S,D,B)=>(n._OrtGetTensorData=j._)(w,O,S,D,B),n._OrtReleaseTensor=w=>(n._OrtReleaseTensor=j.$)(w),n._OrtCreateRunOptions=(w,O,S,D)=>(n._OrtCreateRunOptions=j.aa)(w,O,S,D),n._OrtAddRunConfigEntry=(w,O,S)=>(n._OrtAddRunConfigEntry=j.ba)(w,O,S),n._OrtReleaseRunOptions=w=>(n._OrtReleaseRunOptions=j.ca)(w),n._OrtCreateBinding=w=>(n._OrtCreateBinding=j.da)(w),n._OrtBindInput=(w,O,S)=>(n._OrtBindInput=j.ea)(w,O,S),n._OrtBindOutput=(w,O,S,D)=>(n._OrtBindOutput=j.fa)(w,O,S,D),n._OrtClearBoundOutputs=w=>(n._OrtClearBoundOutputs=j.ga)(w),n._OrtReleaseBinding=w=>(n._OrtReleaseBinding=j.ha)(w),n._OrtRunWithBinding=(w,O,S,D,B)=>(n._OrtRunWithBinding=j.ia)(w,O,S,D,B),n._OrtRun=(w,O,S,D,B,K,ue,$e)=>(n._OrtRun=j.ja)(w,O,S,D,B,K,ue,$e),n._OrtEndProfiling=w=>(n._OrtEndProfiling=j.ka)(w);var Wt=()=>(Wt=j.la)(),Nt=n._malloc=w=>(Nt=n._malloc=j.ma)(w);n._free=w=>(n._free=j.na)(w);var Or=w=>(Or=j.pa)(w),qt=()=>(qt=j.qa)(),Sr=w=>(Sr=j.ra)(w),J=w=>(J=j.sa)(w);function Lt(){var w=j;w=Object.assign({},w);var O=D=>()=>D()>>>0,S=D=>B=>D(B)>>>0;return w.la=O(w.la),w.ma=S(w.ma),w.qa=O(w.qa),w.sa=S(w.sa),w}n.stackAlloc=J,n.stackSave=qt,n.stackRestore=Sr,n.UTF8ToString=xt,n.stringToUTF8=(w,O,S)=>it(w,X,O,S),n.lengthBytesUTF8=gt;var Mt;re=function w(){Mt||At(),Mt||(re=w)};function At(){if(!(0o)}),Pp=me(()=>{}),Ep=me(()=>{}),Dp={};Pr(Dp,{cpus:()=>ng});var ng,Lp=L(()=>{ng=void 0}),Cp=me((t,e)=>{var o=(()=>{var i=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(i=i||__filename),function(u={}){function n(){return de.buffer!=V.buffer&&Be(),V}function s(){return de.buffer!=V.buffer&&Be(),ge}function c(){return de.buffer!=V.buffer&&Be(),he}function d(){return de.buffer!=V.buffer&&Be(),Ze}function r(){return de.buffer!=V.buffer&&Be(),Qe}var a=u,l,h;a.ready=new Promise((p,y)=>{l=p,h=y});var f=Object.assign({},a),m="./this.program",g=(p,y)=>{throw y},b=typeof window=="object",v=typeof importScripts=="function",T=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",E=a.ENVIRONMENT_IS_PTHREAD||!1,M="";function F(p){return a.locateFile?a.locateFile(p,M):M+p}var Y,H,X;if(T){var k=(ta(),rr(ea)),ne=(na(),rr(ra));M=v?ne.dirname(M)+"/":__dirname+"/",Y=(y,x)=>(y=gt(y)?new URL(y):ne.normalize(y),k.readFileSync(y,x?void 0:"utf8")),X=y=>(y=Y(y,!0),y.buffer||(y=new Uint8Array(y)),y),H=(y,x,P,C=!0)=>{y=gt(y)?new URL(y):ne.normalize(y),k.readFile(y,C?void 0:"utf8",(N,G)=>{N?P(N):x(C?G.buffer:G)})},!a.thisProgram&&1{throw process.exitCode=y,x},a.inspect=()=>"[Emscripten Module object]";let p;try{p=Pp()}catch(y){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),y}global.Worker=p.Worker}else(b||v)&&(v?M=self.location.href:typeof document<"u"&&document.currentScript&&(M=document.currentScript.src),typeof i<"u"&&i&&(M=i),M.indexOf("blob:")!==0?M=M.substr(0,M.replace(/[?#].*/,"").lastIndexOf("/")+1):M="",T||(Y=p=>{var y=new XMLHttpRequest;return y.open("GET",p,!1),y.send(null),y.responseText},v&&(X=p=>{var y=new XMLHttpRequest;return y.open("GET",p,!1),y.responseType="arraybuffer",y.send(null),new Uint8Array(y.response)}),H=(p,y,x)=>{var P=new XMLHttpRequest;P.open("GET",p,!0),P.responseType="arraybuffer",P.onload=()=>{P.status==200||P.status==0&&P.response?y(P.response):x()},P.onerror=x,P.send(null)}));T&&typeof performance>"u"&&(global.performance=Ep().performance);var Ce=console.log.bind(console),Me=console.error.bind(console);T&&(Ce=(...p)=>k.writeSync(1,p.join(" ")+` +`),Me=(...p)=>k.writeSync(2,p.join(" ")+` +`));var we=Ce,z=Me;Object.assign(a,f),f=null,typeof WebAssembly!="object"&&ct("no native wasm support detected");var de,ie,re=!1,se,V,ge,he,Ze,Qe;function Be(){var p=de.buffer;a.HEAP8=V=new Int8Array(p),a.HEAP16=new Int16Array(p),a.HEAPU8=ge=new Uint8Array(p),a.HEAPU16=new Uint16Array(p),a.HEAP32=he=new Int32Array(p),a.HEAPU32=Ze=new Uint32Array(p),a.HEAPF32=new Float32Array(p),a.HEAPF64=Qe=new Float64Array(p)}var je=16777216;if(E)de=a.wasmMemory;else if(a.wasmMemory)de=a.wasmMemory;else if(de=new WebAssembly.Memory({initial:je/65536,maximum:65536,shared:!0}),!(de.buffer instanceof SharedArrayBuffer))throw z("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"),T&&z("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");Be(),je=de.buffer.byteLength;var Ue=[],Ne=[],Se=[],_e=0,Le=null;function at(){if(_e--,_e==0&&Le){var p=Le;Le=null,p()}}function ct(p){throw p="Aborted("+p+")",z(p),re=!0,se=1,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),h(p),p}var xt=p=>p.startsWith("data:application/octet-stream;base64,"),gt=p=>p.startsWith("file://"),it;it="ort-wasm-threaded.wasm",xt(it)||(it=F(it));function st(p){if(X)return X(p);throw"both async and sync fetching of the wasm failed"}function fr(p){if(b||v){if(typeof fetch=="function"&&!gt(p))return fetch(p,{credentials:"same-origin"}).then(y=>{if(!y.ok)throw"failed to load wasm binary file at '"+p+"'";return y.arrayBuffer()}).catch(()=>st(p));if(H)return new Promise((y,x)=>{H(p,P=>y(new Uint8Array(P)),x)})}return Promise.resolve().then(()=>st(p))}function Bt(p,y,x){return fr(p).then(P=>WebAssembly.instantiate(P,y)).then(P=>P).then(x,P=>{z(`failed to asynchronously prepare wasm: ${P}`),ct(P)})}function _r(p,y){var x=it;return typeof WebAssembly.instantiateStreaming!="function"||xt(x)||gt(x)||T||typeof fetch!="function"?Bt(x,p,y):fetch(x,{credentials:"same-origin"}).then(P=>WebAssembly.instantiateStreaming(P,p).then(y,function(C){return z(`wasm streaming compile failed: ${C}`),z("falling back to ArrayBuffer instantiation"),Bt(x,p,y)}))}var et,Dt={921276:(p,y,x,P)=>{if(typeof a>"u"||!a.cb)return 1;if(p=Pt(p>>>0),p.startsWith("./")&&(p=p.substring(2)),p=a.cb.get(p),!p)return 2;if(y>>>=0,x>>>=0,P>>>=0,y+x>p.byteLength)return 3;try{return s().set(p.subarray(y,y+x),P>>>0),0}catch{return 4}}};function Ot(p){this.name="ExitStatus",this.message=`Program terminated with exit(${p})`,this.status=p}var Et=p=>{p.terminate(),p.onmessage=()=>{}},wr=p=>{J.Pa.length==0&&(qt(),J.Ya(J.Pa[0]));var y=J.Pa.pop();if(!y)return 6;J.Qa.push(y),J.Ma[p.Oa]=y,y.Oa=p.Oa;var x={cmd:"run",start_routine:p.kb,arg:p.hb,pthread_ptr:p.Oa};return T&&y.unref(),y.postMessage(x,p.qb),0},yt=0,Gt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,vr=(p,y,x)=>{y>>>=0;var P=y+x;for(x=y;p[x]&&!(x>=P);)++x;if(16C?P+=String.fromCharCode(C):(C-=65536,P+=String.fromCharCode(55296|C>>10,56320|C&1023))}}else P+=String.fromCharCode(C)}return P},Pt=(p,y)=>(p>>>=0)?vr(s(),p,y):"",Hr=p=>{var y=on();return p=p(),Fr(y),p};function j(p,y){var x=arguments.length-2,P=arguments;return Hr(()=>{for(var C=_n(8*x),N=C>>>3,G=0;G>>0]=Ae}return ri(p,x,C,y)})}function Wt(p){if(E)return j(0,1,p);se=p,0{if(se=p,E)throw Mt(p),"unwind";Wt(p)};function Or(){for(var p=a.numThreads;p--;)qt();Ue.unshift(()=>{_e++,Sr(()=>at())})}function qt(){var p=F("ort-wasm-threaded.worker.js");p=new Worker(p),J.Pa.push(p)}function Sr(p){E?p():Promise.all(J.Pa.map(J.Ya)).then(p)}var J={Pa:[],Qa:[],bb:[],Ma:{},Wa(){E?(J.receiveObjectTransfer=J.jb,J.threadInitTLS=J.ab,J.setExitStatus=J.$a):Or()},$a:p=>se=p,tb:["$terminateWorker"],lb:()=>{for(var p of J.Qa)Et(p);for(p of J.Pa)Et(p);J.Pa=[],J.Qa=[],J.Ma=[]},Za:p=>{var y=p.Oa;delete J.Ma[y],J.Pa.push(p),J.Qa.splice(J.Qa.indexOf(p),1),p.Oa=0,rn(y)},jb(){},ab(){J.bb.forEach(p=>p())},Ya:p=>new Promise(y=>{p.onmessage=N=>{N=N.data;var G=N.cmd;if(N.targetThread&&N.targetThread!=Ir()){var Ae=J.Ma[N.targetThread];Ae?Ae.postMessage(N,N.transferList):z(`Internal error! Worker sent a message "${G}" to target pthread ${N.targetThread}, but that thread no longer exists!`)}else G==="checkMailbox"?Ar():G==="spawnThread"?wr(N):G==="cleanupThread"?J.Za(J.Ma[N.thread]):G==="killThread"?(N=N.thread,G=J.Ma[N],delete J.Ma[N],Et(G),rn(N),J.Qa.splice(J.Qa.indexOf(G),1),G.Oa=0):G==="cancelThread"?J.Ma[N.thread].postMessage({cmd:"cancel"}):G==="loaded"?(p.loaded=!0,T&&!p.Oa&&p.unref(),y(p)):G==="alert"?alert(`Thread ${N.threadId}: ${N.text}`):N.target==="setimmediate"?p.postMessage(N):G==="callHandler"?a[N.handler](...N.args):G&&z(`worker sent an unknown command ${G}`)},p.onerror=N=>{throw z(`worker sent an error! ${N.filename}:${N.lineno}: ${N.message}`),N},T&&(p.on("message",N=>p.onmessage({data:N})),p.on("error",N=>p.onerror(N)));var x=[],P=["onExit"],C;for(C of P)a.hasOwnProperty(C)&&x.push(C);p.postMessage({cmd:"load",handlers:x,urlOrBlob:a.mainScriptUrlOrBlob||i,wasmMemory:de,wasmModule:ie})})};a.PThread=J;var Lt=p=>{for(;0{var p=Ir(),y=d()[p+52>>>2>>>0];p=d()[p+56>>>2>>>0],ii(y,y-p),Fr(y)};function Mt(p){if(E)return j(1,0,p);Nt(p)}var At=[],w;a.invokeEntryPoint=(p,y)=>{var x=At[p];x||(p>=At.length&&(At.length=p+1),At[p]=x=w.get(p)),p=x(y),0>>2>>>0]=y},this.fb=function(y){d()[this.Va+8>>>2>>>0]=y},this.Wa=function(y,x){this.eb(),this.gb(y),this.fb(x)},this.eb=function(){d()[this.Va+16>>>2>>>0]=0}}var S=0;function D(p,y,x,P){return E?j(2,1,p,y,x,P):B(p,y,x,P)}function B(p,y,x,P){if(p>>>=0,y>>>=0,x>>>=0,P>>>=0,typeof SharedArrayBuffer>"u")return z("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var C=[];return E&&C.length===0?D(p,y,x,P):(p={kb:x,Oa:p,hb:P,qb:C},E?(p.sb="spawnThread",postMessage(p,C),0):wr(p))}function K(p,y,x){return E?j(3,1,p,y,x):0}function ue(p,y){if(E)return j(4,1,p,y)}var $e=p=>{for(var y=0,x=0;x=P?y++:2047>=P?y+=2:55296<=P&&57343>=P?(y+=4,++x):y+=3}return y},He=(p,y,x,P)=>{if(x>>>=0,!(0=G){var Ae=p.charCodeAt(++N);G=65536+((G&1023)<<10)|Ae&1023}if(127>=G){if(x>=P)break;y[x++>>>0]=G}else{if(2047>=G){if(x+1>=P)break;y[x++>>>0]=192|G>>6}else{if(65535>=G){if(x+2>=P)break;y[x++>>>0]=224|G>>12}else{if(x+3>=P)break;y[x++>>>0]=240|G>>18,y[x++>>>0]=128|G>>12&63}y[x++>>>0]=128|G>>6&63}y[x++>>>0]=128|G&63}}return y[x>>>0]=0,x-C},ze=(p,y,x)=>He(p,s(),y,x);function qe(p,y){if(E)return j(5,1,p,y)}function Ht(p,y,x){if(E)return j(6,1,p,y,x)}function Yt(p,y,x){return E?j(7,1,p,y,x):0}function A(p,y){if(E)return j(8,1,p,y)}function pe(p,y,x){if(E)return j(9,1,p,y,x)}function ve(p,y,x,P){if(E)return j(10,1,p,y,x,P)}function rt(p,y,x,P){if(E)return j(11,1,p,y,x,P)}function Kt(p,y,x,P){if(E)return j(12,1,p,y,x,P)}function xn(p){if(E)return j(13,1,p)}function On(p,y){if(E)return j(14,1,p,y)}function Sn(p,y,x){if(E)return j(15,1,p,y,x)}function Yr(p){p>>>=0,typeof Atomics.rb=="function"&&(Atomics.rb(c(),p>>>2,p).value.then(Ar),p+=128,Atomics.store(c(),p>>>2,1))}a.__emscripten_thread_mailbox_await=Yr;var Ar=()=>{var p=Ir();if(p&&(Yr(p),p=ni,!re))try{if(p(),!(0p%4===0&&(p%100!==0||p%400===0),Pn=[0,31,60,91,121,152,182,213,244,274,305,335],An=[0,31,59,90,120,151,181,212,243,273,304,334];function In(p,y,x,P,C,N,G,Ae){return E?j(16,1,p,y,x,P,C,N,G,Ae):-52}function jn(p,y,x,P,C,N,G){if(E)return j(17,1,p,y,x,P,C,N,G)}var qn=p=>{var y=$e(p)+1,x=Jo(y);return x&&ze(p,x,y),x},Kr=[],Zr={},Hn=()=>{if(!Jr){var 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",_:m||"./this.program"},y;for(y in Zr)Zr[y]===void 0?delete p[y]:p[y]=Zr[y];var x=[];for(y in p)x.push(`${y}=${p[y]}`);Jr=x}return Jr},Jr;function Yn(p,y){if(E)return j(18,1,p,y);p>>>=0,y>>>=0;var x=0;return Hn().forEach((P,C)=>{var N=y+x;for(C=d()[p+4*C>>>2>>>0]=N,N=0;N>>0>>>0]=P.charCodeAt(N);n()[C>>>0>>>0]=0,x+=P.length+1}),0}function Mo(p,y){if(E)return j(19,1,p,y);p>>>=0,y>>>=0;var x=Hn();d()[p>>>2>>>0]=x.length;var P=0;return x.forEach(C=>P+=C.length+1),d()[y>>>2>>>0]=P,0}function No(p){return E?j(20,1,p):52}function Ro(p,y,x,P){return E?j(21,1,p,y,x,P):52}function Bo(p,y,x,P,C){return E?j(22,1,p,y,x,P,C):70}var Ns=[null,[],[]];function Uo(p,y,x,P){if(E)return j(23,1,p,y,x,P);y>>>=0,x>>>=0,P>>>=0;for(var C=0,N=0;N>>2>>>0],Ae=d()[y+4>>>2>>>0];y+=8;for(var ot=0;ot>>0],Je=Ns[p];ke===0||ke===10?((p===1?we:z)(vr(Je,0)),Je.length=0):Je.push(ke)}C+=Ae}return d()[P>>>2>>>0]=C,0}var zo=[31,29,31,30,31,30,31,31,30,31,30,31],Vo=[31,28,31,30,31,30,31,31,30,31,30,31];function Rs(p){var y=Array($e(p)+1);return He(p,y,0,y.length),y}var Bs=(p,y)=>{n().set(p,y>>>0)};function Go(p,y,x,P){function C(I,Te,Ie){for(I=typeof I=="number"?I.toString():I||"";I.lengthci?-1:0It-I.getDate())Te-=It-I.getDate()+1,I.setDate(1),11>Ie?I.setMonth(Ie+1):(I.setMonth(0),I.setFullYear(I.getFullYear()+1));else{I.setDate(I.getDate()+Te);break}}return Ie=new Date(I.getFullYear()+1,0,4),Te=Ae(new Date(I.getFullYear(),0,4)),Ie=Ae(Ie),0>=G(Te,I)?0>=G(Ie,I)?I.getFullYear()+1:I.getFullYear():I.getFullYear()-1}p>>>=0,y>>>=0,x>>>=0,P>>>=0;var ke=d()[P+40>>>2>>>0];P={ob:c()[P>>>2>>>0],nb:c()[P+4>>>2>>>0],Ta:c()[P+8>>>2>>>0],Xa:c()[P+12>>>2>>>0],Ua:c()[P+16>>>2>>>0],Sa:c()[P+20>>>2>>>0],Na:c()[P+24>>>2>>>0],Ra:c()[P+28>>>2>>>0],ub:c()[P+32>>>2>>>0],mb:c()[P+36>>>2>>>0],pb:ke?Pt(ke):""},x=Pt(x),ke={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var Je in ke)x=x.replace(new RegExp(Je,"g"),ke[Je]);var ai="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),ui="January February March April May June July August September October November December".split(" ");ke={"%a":I=>ai[I.Na].substring(0,3),"%A":I=>ai[I.Na],"%b":I=>ui[I.Ua].substring(0,3),"%B":I=>ui[I.Ua],"%C":I=>N((I.Sa+1900)/100|0,2),"%d":I=>N(I.Xa,2),"%e":I=>C(I.Xa,2," "),"%g":I=>ot(I).toString().substring(2),"%G":I=>ot(I),"%H":I=>N(I.Ta,2),"%I":I=>(I=I.Ta,I==0?I=12:12{for(var Te=0,Ie=0;Ie<=I.Ua-1;Te+=(Rt(I.Sa+1900)?zo:Vo)[Ie++]);return N(I.Xa+Te,3)},"%m":I=>N(I.Ua+1,2),"%M":I=>N(I.nb,2),"%n":()=>` +`,"%p":I=>0<=I.Ta&&12>I.Ta?"AM":"PM","%S":I=>N(I.ob,2),"%t":()=>" ","%u":I=>I.Na||7,"%U":I=>N(Math.floor((I.Ra+7-I.Na)/7),2),"%V":I=>{var Te=Math.floor((I.Ra+7-(I.Na+6)%7)/7);if(2>=(I.Na+371-I.Ra-2)%7&&Te++,Te)Te==53&&(Ie=(I.Na+371-I.Ra)%7,Ie==4||Ie==3&&Rt(I.Sa)||(Te=1));else{Te=52;var Ie=(I.Na+7-I.Ra-1)%7;(Ie==4||Ie==5&&Rt(I.Sa%400-1))&&Te++}return N(Te,2)},"%w":I=>I.Na,"%W":I=>N(Math.floor((I.Ra+7-(I.Na+6)%7)/7),2),"%y":I=>(I.Sa+1900).toString().substring(2),"%Y":I=>I.Sa+1900,"%z":I=>{I=I.mb;var Te=0<=I;return I=Math.abs(I)/60,(Te?"+":"-")+("0000"+(I/60*100+I%60)).slice(-4)},"%Z":I=>I.pb,"%%":()=>"%"},x=x.replace(/%%/g,"\0\0");for(Je in ke)x.includes(Je)&&(x=x.replace(new RegExp(Je,"g"),ke[Je](P)));return x=x.replace(/\0\0/g,"%"),Je=Rs(x),Je.length>y?0:(Bs(Je,p),Je.length-1)}J.Wa();var js=[Wt,Mt,D,K,ue,qe,Ht,Yt,A,pe,ve,rt,Kt,xn,On,Sn,In,jn,Yn,Mo,No,Ro,Bo,Uo],zs={b:function(p,y,x){throw p>>>=0,new O(p).Wa(y>>>0,x>>>0),S=p,S},L:function(p){ti(p>>>0,!v,1,!b,131072,!1),J.ab()},j:function(p){p>>>=0,E?postMessage({cmd:"cleanupThread",thread:p}):J.Za(J.Ma[p])},H:B,h:K,S:ue,D:qe,F:Ht,T:Yt,Q:A,J:pe,P:ve,n:rt,E:Kt,B:xn,R:On,C:Sn,p:()=>1,z:function(p,y){p>>>=0,p==y>>>0?setTimeout(()=>Ar()):E?postMessage({targetThread:p,cmd:"checkMailbox"}):(p=J.Ma[p])&&p.postMessage({cmd:"checkMailbox"})},I:function(p,y,x,P){y>>>=0,Xr.length=x,P=P>>>0>>>3;for(var C=0;C>>0];return p=0>p?Dt[-p-1]:js[p],J.ib=y,y=p.apply(null,Xr),J.ib=0,y},K:Yr,o:function(p){T&&J.Ma[p>>>0].ref()},s:function(p,y,x){p=y+2097152>>>0<4194305-!!p?(p>>>0)+4294967296*y:NaN,x>>>=0,p=new Date(1e3*p),c()[x>>>2>>>0]=p.getUTCSeconds(),c()[x+4>>>2>>>0]=p.getUTCMinutes(),c()[x+8>>>2>>>0]=p.getUTCHours(),c()[x+12>>>2>>>0]=p.getUTCDate(),c()[x+16>>>2>>>0]=p.getUTCMonth(),c()[x+20>>>2>>>0]=p.getUTCFullYear()-1900,c()[x+24>>>2>>>0]=p.getUTCDay(),p=(p.getTime()-Date.UTC(p.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,c()[x+28>>>2>>>0]=p},t:function(p,y,x){p=y+2097152>>>0<4194305-!!p?(p>>>0)+4294967296*y:NaN,x>>>=0,p=new Date(1e3*p),c()[x>>>2>>>0]=p.getSeconds(),c()[x+4>>>2>>>0]=p.getMinutes(),c()[x+8>>>2>>>0]=p.getHours(),c()[x+12>>>2>>>0]=p.getDate(),c()[x+16>>>2>>>0]=p.getMonth(),c()[x+20>>>2>>>0]=p.getFullYear()-1900,c()[x+24>>>2>>>0]=p.getDay(),y=(Rt(p.getFullYear())?Pn:An)[p.getMonth()]+p.getDate()-1|0,c()[x+28>>>2>>>0]=y,c()[x+36>>>2>>>0]=-(60*p.getTimezoneOffset()),y=new Date(p.getFullYear(),6,1).getTimezoneOffset();var P=new Date(p.getFullYear(),0,1).getTimezoneOffset();p=(y!=P&&p.getTimezoneOffset()==Math.min(P,y))|0,c()[x+32>>>2>>>0]=p},u:function(p){p>>>=0;var y=new Date(c()[p+20>>>2>>>0]+1900,c()[p+16>>>2>>>0],c()[p+12>>>2>>>0],c()[p+8>>>2>>>0],c()[p+4>>>2>>>0],c()[p>>>2>>>0],0),x=c()[p+32>>>2>>>0],P=y.getTimezoneOffset(),C=new Date(y.getFullYear(),6,1).getTimezoneOffset(),N=new Date(y.getFullYear(),0,1).getTimezoneOffset(),G=Math.min(N,C);return 0>x?c()[p+32>>>2>>>0]=+(C!=N&&G==P):0>>2>>>0]=y.getDay(),x=(Rt(y.getFullYear())?Pn:An)[y.getMonth()]+y.getDate()-1|0,c()[p+28>>>2>>>0]=x,c()[p>>>2>>>0]=y.getSeconds(),c()[p+4>>>2>>>0]=y.getMinutes(),c()[p+8>>>2>>>0]=y.getHours(),c()[p+12>>>2>>>0]=y.getDate(),c()[p+16>>>2>>>0]=y.getMonth(),c()[p+20>>>2>>>0]=y.getYear(),p=y.getTime(),isNaN(p)?(c()[Wo()>>>2>>>0]=61,p=-1):p/=1e3,oi((et=p,1<=+Math.abs(et)?0>>0:~~+Math.ceil((et-+(~~et>>>0))/4294967296)>>>0:0)),p>>>0},q:In,r:jn,y:function(p,y,x){function P(ke){return(ke=ke.toTimeString().match(/\(([A-Za-z ]+)\)$/))?ke[1]:"GMT"}p>>>=0,y>>>=0,x>>>=0;var C=new Date().getFullYear(),N=new Date(C,0,1),G=new Date(C,6,1);C=N.getTimezoneOffset();var Ae=G.getTimezoneOffset(),ot=Math.max(C,Ae);d()[p>>>2>>>0]=60*ot,c()[y>>>2>>>0]=+(C!=Ae),p=P(N),y=P(G),p=qn(p),y=qn(y),Ae>>2>>>0]=p,d()[x+4>>>2>>>0]=y):(d()[x>>>2>>>0]=y,d()[x+4>>>2>>>0]=p)},c:()=>{ct("")},O:function(p,y,x){p>>>=0,y>>>=0,x>>>=0,Kr.length=0;for(var P;P=s()[y++>>>0];){var C=P!=105;C&=P!=112,x+=C&&x%8?4:0,Kr.push(P==112?d()[x>>>2>>>0]:P==105?c()[x>>>2>>>0]:r()[x>>>3>>>0]),x+=C?8:4}return Dt[p].apply(null,Kr)},k:()=>{},i:()=>Date.now(),U:()=>{throw yt+=1,"unwind"},A:function(){return 4294901760},e:()=>performance.timeOrigin+performance.now(),f:()=>T?(Lp(),rr(Dp)).cpus().length:navigator.hardwareConcurrency,x:function(p){p>>>=0;var y=s().length;if(p<=y||4294901760=x;x*=2){var P=y*(1+.2/x);P=Math.min(P,p+100663296);var C=Math;P=Math.max(p,P);e:{C=(C.min.call(C,4294901760,P+(65536-P%65536)%65536)-de.buffer.byteLength+65535)/65536;try{de.grow(C),Be();var N=1;break e}catch{}N=void 0}if(N)return!0}return!1},M:Yn,N:Mo,G:Nt,g:No,m:Ro,v:Bo,l:Uo,a:de||a.wasmMemory,w:Go,d:function(p,y,x,P){return Go(p>>>0,y>>>0,x>>>0,P>>>0)}},Q=function(){function p(x,P){return Q=x.exports,Q=Vs(),J.bb.push(Q.za),w=Q.Aa,Ne.unshift(Q.V),ie=P,at(),Q}var y={a:zs};if(_e++,a.instantiateWasm)try{return a.instantiateWasm(y,p)}catch(x){z(`Module.instantiateWasm callback failed with error: ${x}`),h(x)}return _r(y,function(x){p(x.instance,x.module)}).catch(h),{}}();a._OrtInit=(p,y)=>(a._OrtInit=Q.W)(p,y),a._OrtGetLastError=(p,y)=>(a._OrtGetLastError=Q.X)(p,y),a._OrtCreateSessionOptions=(p,y,x,P,C,N,G,Ae,ot,ke)=>(a._OrtCreateSessionOptions=Q.Y)(p,y,x,P,C,N,G,Ae,ot,ke),a._OrtAppendExecutionProvider=(p,y)=>(a._OrtAppendExecutionProvider=Q.Z)(p,y),a._OrtAddFreeDimensionOverride=(p,y,x)=>(a._OrtAddFreeDimensionOverride=Q._)(p,y,x),a._OrtAddSessionConfigEntry=(p,y,x)=>(a._OrtAddSessionConfigEntry=Q.$)(p,y,x),a._OrtReleaseSessionOptions=p=>(a._OrtReleaseSessionOptions=Q.aa)(p),a._OrtCreateSession=(p,y,x)=>(a._OrtCreateSession=Q.ba)(p,y,x),a._OrtReleaseSession=p=>(a._OrtReleaseSession=Q.ca)(p),a._OrtGetInputOutputCount=(p,y,x)=>(a._OrtGetInputOutputCount=Q.da)(p,y,x),a._OrtGetInputName=(p,y)=>(a._OrtGetInputName=Q.ea)(p,y),a._OrtGetOutputName=(p,y)=>(a._OrtGetOutputName=Q.fa)(p,y),a._OrtFree=p=>(a._OrtFree=Q.ga)(p),a._OrtCreateTensor=(p,y,x,P,C,N)=>(a._OrtCreateTensor=Q.ha)(p,y,x,P,C,N),a._OrtGetTensorData=(p,y,x,P,C)=>(a._OrtGetTensorData=Q.ia)(p,y,x,P,C),a._OrtReleaseTensor=p=>(a._OrtReleaseTensor=Q.ja)(p),a._OrtCreateRunOptions=(p,y,x,P)=>(a._OrtCreateRunOptions=Q.ka)(p,y,x,P),a._OrtAddRunConfigEntry=(p,y,x)=>(a._OrtAddRunConfigEntry=Q.la)(p,y,x),a._OrtReleaseRunOptions=p=>(a._OrtReleaseRunOptions=Q.ma)(p),a._OrtCreateBinding=p=>(a._OrtCreateBinding=Q.na)(p),a._OrtBindInput=(p,y,x)=>(a._OrtBindInput=Q.oa)(p,y,x),a._OrtBindOutput=(p,y,x,P)=>(a._OrtBindOutput=Q.pa)(p,y,x,P),a._OrtClearBoundOutputs=p=>(a._OrtClearBoundOutputs=Q.qa)(p),a._OrtReleaseBinding=p=>(a._OrtReleaseBinding=Q.ra)(p),a._OrtRunWithBinding=(p,y,x,P,C)=>(a._OrtRunWithBinding=Q.sa)(p,y,x,P,C),a._OrtRun=(p,y,x,P,C,N,G,Ae)=>(a._OrtRun=Q.ta)(p,y,x,P,C,N,G,Ae),a._OrtEndProfiling=p=>(a._OrtEndProfiling=Q.ua)(p);var Wo=()=>(Wo=Q.va)(),Ir=a._pthread_self=()=>(Ir=a._pthread_self=Q.wa)(),Jo=a._malloc=p=>(Jo=a._malloc=Q.xa)(p);a._free=p=>(a._free=Q.ya)(p),a.__emscripten_tls_init=()=>(a.__emscripten_tls_init=Q.za)();var ti=a.__emscripten_thread_init=(p,y,x,P,C,N)=>(ti=a.__emscripten_thread_init=Q.Ba)(p,y,x,P,C,N);a.__emscripten_thread_crashed=()=>(a.__emscripten_thread_crashed=Q.Ca)();var ri=(p,y,x,P)=>(ri=Q.Da)(p,y,x,P),rn=p=>(rn=Q.Ea)(p),nn=a.__emscripten_thread_exit=p=>(nn=a.__emscripten_thread_exit=Q.Fa)(p),ni=()=>(ni=Q.Ga)(),oi=p=>(oi=Q.Ha)(p),ii=(p,y)=>(ii=Q.Ia)(p,y),on=()=>(on=Q.Ja)(),Fr=p=>(Fr=Q.Ka)(p),_n=p=>(_n=Q.La)(p);function Vs(){var p=Q;p=Object.assign({},p);var y=P=>()=>P()>>>0,x=P=>C=>P(C)>>>0;return p.va=y(p.va),p.wa=y(p.wa),p.xa=x(p.xa),p.emscripten_main_runtime_thread_id=y(p.emscripten_main_runtime_thread_id),p.Ja=y(p.Ja),p.La=x(p.La),p}a.wasmMemory=de,a.stackAlloc=_n,a.stackSave=on,a.stackRestore=Fr,a.keepRuntimeAlive=()=>0o)}),kp=me((t,e)=>{e.exports='"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\n'}),Np,ig,aa,sa,Po,Bp,ag,sg,ug,Rp,Ee,zr=L(()=>{Np=Ap(),ig=Cp(),sa=!1,Po=!1,Bp=!1,ag=t=>{if(t===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+t+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},sg=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},ug=(t,e)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":e?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Rp=async t=>{if(sa)return Promise.resolve();if(Po)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Bp)throw new Error("previous call to 'initializeWebAssembly()' failed.");Po=!0;let e=t.initTimeout,o=t.numThreads,i=t.simd,u=ag(o),n=i&&sg(),s=t.wasmPaths,c=typeof s=="string"?s:void 0,d=ug(n,u),r=typeof s=="object"?s[d]:void 0,a=!1,l=[];if(e>0&&l.push(new Promise(h=>{setTimeout(()=>{a=!0,h()},e)})),l.push(new Promise((h,f)=>{let m=u?ig:Np,g={locateFile:(b,v)=>u&&b.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([kp()],{type:"text/javascript"})):b.endsWith(".wasm")?r||(c??v)+d:v+b};if(u)if(g.numThreads=o,typeof Blob>"u")g.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let b=`var ortWasmThreaded=${m.toString()};`;g.mainScriptUrlOrBlob=new Blob([b],{type:"text/javascript"})}m(g).then(b=>{Po=!1,sa=!0,aa=b,h()},b=>{Po=!1,Bp=!0,f(b)})})),await Promise.race(l),a)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Ee=()=>{if(sa&&aa)return aa;throw new Error("WebAssembly is not initialized yet.")}}),De,bn,Oe,Eo=L(()=>{zr(),De=(t,e)=>{let o=Ee(),i=o.lengthBytesUTF8(t)+1,u=o._malloc(i);return o.stringToUTF8(t,u,i),e.push(u),u},bn=(t,e,o,i)=>{if(typeof t=="object"&&t!==null){if(o.has(t))throw new Error("Circular reference in options");o.add(t)}Object.entries(t).forEach(([u,n])=>{let s=e?e+u:u;if(typeof n=="object")bn(n,s+".",o,i);else if(typeof n=="string"||typeof n=="number")i(s,n.toString());else if(typeof n=="boolean")i(s,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},Oe=t=>{let e=Ee(),o=e.stackSave();try{let i=e.stackAlloc(8);e._OrtGetLastError(i,i+4);let u=e.HEAP32[i/4],n=e.HEAPU32[i/4+1],s=n?e.UTF8ToString(n):"";throw new Error(`${t} ERROR_CODE: ${u}, ERROR_MESSAGE: ${s}`)}finally{e.stackRestore(o)}}}),Mp,Gp=L(()=>{zr(),Eo(),Mp=t=>{let e=Ee(),o=0,i=[],u=t||{};try{if(t?.logSeverityLevel===void 0)u.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)u.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(u.terminate=!1);let n=0;return t?.tag!==void 0&&(n=De(t.tag,i)),o=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,n),o===0&&Oe("Can't create run options."),t?.extra!==void 0&&bn(t.extra,"",new WeakSet,(s,c)=>{let d=De(s,i),r=De(c,i);e._OrtAddRunConfigEntry(o,d,r)!==0&&Oe(`Can't set a run config entry: ${s} - ${c}.`)}),[o,i]}catch(n){throw o!==0&&e._OrtReleaseRunOptions(o),i.forEach(s=>e._free(s)),n}}}),lg,fg,cg,pg,Up,zp=L(()=>{zr(),Eo(),lg=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},fg=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},cg=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(o=>(typeof o=="string"?o:o.name)==="webgpu")&&(t.enableMemPattern=!1)},pg=(t,e,o)=>{for(let i of e){let u=typeof i=="string"?i:i.name;switch(u){case"webnn":if(u="WEBNN",typeof i!="string"){let s=i;if(s?.deviceType){let c=De("deviceType",o),d=De(s.deviceType,o);Ee()._OrtAddSessionConfigEntry(t,c,d)!==0&&Oe(`Can't set a session config entry: 'deviceType' - ${s.deviceType}.`)}if(s?.numThreads){let c=s.numThreads;(typeof c!="number"||!Number.isInteger(c)||c<0)&&(c=0);let d=De("numThreads",o),r=De(c.toString(),o);Ee()._OrtAddSessionConfigEntry(t,d,r)!==0&&Oe(`Can't set a session config entry: 'numThreads' - ${s.numThreads}.`)}if(s?.powerPreference){let c=De("powerPreference",o),d=De(s.powerPreference,o);Ee()._OrtAddSessionConfigEntry(t,c,d)!==0&&Oe(`Can't set a session config entry: 'powerPreference' - ${s.powerPreference}.`)}}break;case"webgpu":if(u="JS",typeof i!="string"){let s=i;if(s?.preferredLayout){if(s.preferredLayout!=="NCHW"&&s.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`);let c=De("preferredLayout",o),d=De(s.preferredLayout,o);Ee()._OrtAddSessionConfigEntry(t,c,d)!==0&&Oe(`Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${u}`)}let n=De(u,o);Ee()._OrtAppendExecutionProvider(t,n)!==0&&Oe(`Can't append execution provider: ${u}.`)}},Up=t=>{let e=Ee(),o=0,i=[],u=t||{};cg(u);try{let n=lg(u.graphOptimizationLevel??"all"),s=fg(u.executionMode??"sequential"),c=typeof u.logId=="string"?De(u.logId,i):0,d=u.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let r=u.logVerbosityLevel??0;if(!Number.isInteger(r)||r<0||r>4)throw new Error(`log verbosity level is not valid: ${r}`);let a=typeof u.optimizedModelFilePath=="string"?De(u.optimizedModelFilePath,i):0;if(o=e._OrtCreateSessionOptions(n,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,c,d,r,a),o===0&&Oe("Can't create session options."),u.executionProviders&&pg(o,u.executionProviders,i),u.freeDimensionOverrides)for(let[l,h]of Object.entries(u.freeDimensionOverrides)){if(typeof l!="string")throw new Error(`free dimension override name must be a string: ${l}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let f=De(l,i);e._OrtAddFreeDimensionOverride(o,f,h)!==0&&Oe(`Can't set a free dimension override: ${l} - ${h}.`)}return u.extra!==void 0&&bn(u.extra,"",new WeakSet,(l,h)=>{let f=De(l,i),m=De(h,i);e._OrtAddSessionConfigEntry(o,f,m)!==0&&Oe(`Can't set a session config entry: ${l} - ${h}.`)}),[o,i]}catch(n){throw o!==0&&e._OrtReleaseSessionOptions(o),i.forEach(s=>e._free(s)),n}}}),ua,Vp,la,Wp,Hp,Do,qp,fa=L(()=>{ua=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},Vp=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},la=t=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][t],Wp=t=>{switch(t){case"float16":return Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Hp=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},Do=t=>t==="float32"||t==="int32"||t==="int64"||t==="bool"||t==="float16"||t==="uint32",qp=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${t}`)}}}),gn,ca=L(()=>{gn=async t=>{if(typeof t=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(t))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let o=(void 0)(t),i=[];for await(let u of o)i.push(u);return new Uint8Array(Buffer.concat(i))}throw e}else{let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let o=e.headers.get("Content-Length"),i=o?parseInt(o,10):0;if(i<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let u=e.body.getReader(),n;try{n=new ArrayBuffer(i)}catch(c){if(c instanceof RangeError){let d=Math.ceil(i/65536);n=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw c}let s=0;for(;;){let{done:c,value:d}=await u.read();if(c)break;let r=d.byteLength;new Uint8Array(n,s,r).set(d),s+=r}return new Uint8Array(n,0,i)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),dg,Yp,Xp,yn,hg,pa,Kp,Jp,jp,Zp,Qp,ed,td=L(()=>{Gp(),zp(),fa(),zr(),Eo(),ca(),dg=(t,e)=>{Ee()._OrtInit(t,e)!==0&&Oe("Can't initialize onnxruntime.")},Yp=async t=>{dg(t.wasm.numThreads,Hp(t.logLevel))},Xp=async(t,e)=>{},yn=new Map,hg=t=>{let e=Ee(),o=e.stackSave();try{let i=e.stackAlloc(8);return e._OrtGetInputOutputCount(t,i,i+4)!==0&&Oe("Can't get session input/output count."),[e.HEAP32[i/4],e.HEAP32[i/4+1]]}finally{e.stackRestore(o)}},pa=t=>{let e=Ee(),o=e._malloc(t.byteLength);if(o===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,o),[o,t.byteLength]},Kp=async(t,e)=>{let o,i,u=Ee();Array.isArray(t)?[o,i]=t:t.buffer===u.HEAPU8.buffer?[o,i]=[t.byteOffset,t.byteLength]:[o,i]=pa(t);let n=0,s=0,c=[],d=[],r=[];try{if([s,c]=Up(e),e?.externalData&&u.mountExternalData){let b=[];for(let v of e.externalData){let T=typeof v=="string"?v:v.path;b.push(gn(typeof v=="string"?v:v.data).then(E=>{u.mountExternalData(T,E)}))}await Promise.all(b)}n=u._OrtCreateSession(o,i,s),n===0&&Oe("Can't create a session.");let[a,l]=hg(n),h=[],f=[],m=[];for(let b=0;bu._OrtFree(l)),r.forEach(l=>u._OrtFree(l)),n!==0&&u._OrtReleaseSession(n),a}finally{u._free(o),s!==0&&u._OrtReleaseSessionOptions(s),c.forEach(a=>u._free(a)),u.unmountExternalData?.()}},Jp=t=>{let e=Ee(),o=yn.get(t);if(!o)throw new Error(`cannot release session. invalid session id: ${t}`);let[i,u,n,s]=o;s&&e._OrtReleaseBinding(s.handle),e.jsepUnregisterBuffers?.(t),u.forEach(c=>e._OrtFree(c)),n.forEach(c=>e._OrtFree(c)),e._OrtReleaseSession(i),yn.delete(t)},jp=(t,e,o,i,u)=>{if(!t){e.push(0);return}let n=Ee(),s=t[0],c=t[1],d=t[3],r,a;if(s==="string"&&d==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(d==="gpu-buffer"){let f=t[2].gpuBuffer,m=la(ua(s));a=c.reduce((g,b)=>g*b,1)*m,r=n.jsepRegisterBuffer(i,u,f,a)}else{let f=t[2];if(Array.isArray(f)){a=4*f.length,r=n._malloc(a),o.push(r);let m=r/4;for(let g=0;gn.HEAP32[f++]=g);let m=n._OrtCreateTensor(ua(s),r,a,h,c.length,qp(d));m===0&&Oe(`Can't create tensor for input/output. session=${i}, index=${u}.`),e.push(m)}finally{n.stackRestore(l)}},Zp=async(t,e,o,i,u,n)=>{let s=Ee(),c=yn.get(t);if(!c)throw new Error(`cannot run inference. invalid session id: ${t}`);let[d,r,a,l]=c,h=e.length,f=i.length,m=0,g=[],b=[],v=[],T=[],E=s.stackSave(),M=s.stackAlloc(h*4),F=s.stackAlloc(h*4),Y=s.stackAlloc(f*4),H=s.stackAlloc(f*4);try{[m,g]=Mp(n);for(let z=0;zSe*_e,1);V=Vp(Ze);let Ne=l?.outputPreferredLocations[i[z]];if(V==="string"){if(Ne==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Se=[],_e=ge/4;for(let Le=0;Le0){let Se=s.jsepGetBuffer(ge),_e=la(Ze);if(_e===void 0||!Do(V))throw new Error(`Unsupported data type: ${V}`);se=!0,we.push([V,je,{gpuBuffer:Se,download:s.jsepCreateDownloader(Se,Ue*_e,V),dispose:()=>{s._OrtReleaseTensor(de)}},"gpu-buffer"])}else{let Se=Wp(V),_e=new Se(Ue);new Uint8Array(_e.buffer,_e.byteOffset,_e.byteLength).set(s.HEAPU8.subarray(ge,ge+_e.byteLength)),we.push([V,je,_e,"cpu"])}}finally{s.stackRestore(ie),V==="string"&&ge&&s._free(ge),se||s._OrtReleaseTensor(de)}}return l&&s._OrtClearBoundOutputs(l.handle),we}finally{s.stackRestore(E),b.forEach(X=>s._OrtReleaseTensor(X)),v.forEach(X=>s._OrtReleaseTensor(X)),T.forEach(X=>s._free(X)),m!==0&&s._OrtReleaseRunOptions(m),g.forEach(X=>s._free(X))}},Qp=t=>{let e=Ee(),o=yn.get(t);if(!o)throw new Error("invalid session id");let i=o[0],u=e._OrtEndProfiling(i);u===0&&Oe("Can't get an profile file name."),e._OrtFree(u)},ed=t=>{let e=[];for(let o of t){let i=o[2];!Array.isArray(i)&&"buffer"in i&&e.push(i.buffer)}return e}}),rd=me((t,e)=>{e.exports='/*!\n * ONNX Runtime Web v1.17.1\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var Et=Object.defineProperty;var Jr=Object.getOwnPropertyDescriptor;var Xr=Object.getOwnPropertyNames;var Qr=Object.prototype.hasOwnProperty;var St=(u,d)=>()=>(u&&(d=u(u=0)),d);var et=(u,d)=>()=>(d||u((d={exports:{}}).exports,d),d.exports),Tt=(u,d)=>{for(var a in d)Et(u,a,{get:d[a],enumerable:!0})},Zr=(u,d,a,h)=>{if(d&&typeof d=="object"||typeof d=="function")for(let l of Xr(d))!Qr.call(u,l)&&l!==a&&Et(u,l,{get:()=>d[l],enumerable:!(h=Jr(d,l))||h.enumerable});return u};var tt=u=>Zr(Et({},"__esModule",{value:!0}),u);var At={};Tt(At,{createReadStream:()=>dr,readFile:()=>Kr,readFileSync:()=>en});var Kr,en,dr,Mt=St(()=>{Kr=void 0,en=void 0,dr=void 0});var Ct={};Tt(Ct,{join:()=>tn});var tn,Dt=St(()=>{tn=void 0});var gr=et((mr,xt)=>{"use strict";var pr=(()=>{var u=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(u=u||__filename),function(d={}){var a=d,h,l;a.ready=new Promise((r,o)=>{h=r,l=o});var w=Object.assign({},a),g="./this.program",i=typeof window=="object",A=typeof importScripts=="function",D=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",I="",B,F,U;if(D){var k=(Mt(),tt(At)),L=(Dt(),tt(Ct));I=A?L.dirname(I)+"/":__dirname+"/",B=(r,o)=>(r=ye(r)?new URL(r):L.normalize(r),k.readFileSync(r,o?void 0:"utf8")),U=r=>(r=B(r,!0),r.buffer||(r=new Uint8Array(r)),r),F=(r,o,s,m=!0)=>{r=ye(r)?new URL(r):L.normalize(r),k.readFile(r,m?void 0:"utf8",(O,S)=>{O?s(O):o(m?S.buffer:S)})},!a.thisProgram&&1"[Emscripten Module object]"}else(i||A)&&(A?I=self.location.href:typeof document<"u"&&document.currentScript&&(I=document.currentScript.src),u&&(I=u),I.indexOf("blob:")!==0?I=I.substr(0,I.replace(/[?#].*/,"").lastIndexOf("/")+1):I="",B=r=>{var o=new XMLHttpRequest;return o.open("GET",r,!1),o.send(null),o.responseText},A&&(U=r=>{var o=new XMLHttpRequest;return o.open("GET",r,!1),o.responseType="arraybuffer",o.send(null),new Uint8Array(o.response)}),F=(r,o,s)=>{var m=new XMLHttpRequest;m.open("GET",r,!0),m.responseType="arraybuffer",m.onload=()=>{m.status==200||m.status==0&&m.response?o(m.response):s()},m.onerror=s,m.send(null)});var _=console.log.bind(console),x=console.error.bind(console);Object.assign(a,w),w=null,typeof WebAssembly!="object"&&de("no native wasm support detected");var N,he=!1,ie,ae,E,Y,ue;function Re(){var r=N.buffer;a.HEAP8=ie=new Int8Array(r),a.HEAP16=new Int16Array(r),a.HEAPU8=ae=new Uint8Array(r),a.HEAPU16=new Uint16Array(r),a.HEAP32=E=new Int32Array(r),a.HEAPU32=Y=new Uint32Array(r),a.HEAPF32=new Float32Array(r),a.HEAPF64=ue=new Float64Array(r)}var Ie=[],ee=[],j=[],ce=0,P=null,te=null;function de(r){throw r="Aborted("+r+")",x(r),he=!0,r=new WebAssembly.RuntimeError(r+". Build with -sASSERTIONS for more info."),l(r),r}var ge=r=>r.startsWith("data:application/octet-stream;base64,"),ye=r=>r.startsWith("file://"),J;if(J="ort-wasm.wasm",!ge(J)){var fe=J;J=a.locateFile?a.locateFile(fe,I):I+fe}function we(r){if(U)return U(r);throw"both async and sync fetching of the wasm failed"}function Ae(r){if(i||A){if(typeof fetch=="function"&&!ye(r))return fetch(r,{credentials:"same-origin"}).then(o=>{if(!o.ok)throw"failed to load wasm binary file at \'"+r+"\'";return o.arrayBuffer()}).catch(()=>we(r));if(F)return new Promise((o,s)=>{F(r,m=>o(new Uint8Array(m)),s)})}return Promise.resolve().then(()=>we(r))}function Me(r,o,s){return Ae(r).then(m=>WebAssembly.instantiate(m,o)).then(m=>m).then(s,m=>{x(`failed to asynchronously prepare wasm: ${m}`),de(m)})}function Fe(r,o){var s=J;return typeof WebAssembly.instantiateStreaming!="function"||ge(s)||ye(s)||D||typeof fetch!="function"?Me(s,r,o):fetch(s,{credentials:"same-origin"}).then(m=>WebAssembly.instantiateStreaming(m,r).then(o,function(O){return x(`wasm streaming compile failed: ${O}`),x("falling back to ArrayBuffer instantiation"),Me(s,r,o)}))}var Ee,pe={919888:(r,o,s,m)=>{if(typeof a>"u"||!a.za)return 1;if(r=be(r>>>0),r.startsWith("./")&&(r=r.substring(2)),r=a.za.get(r),!r)return 2;if(o>>>=0,s>>>=0,o+s>r.byteLength)return 3;try{return ae.set(r.subarray(o,o+s),m>>>0>>>0),0}catch{return 4}}};function Oe(r){this.xa=r-24,this.Ha=function(o){Y[this.xa+4>>>2>>>0]=o},this.Ga=function(o){Y[this.xa+8>>>2>>>0]=o},this.Aa=function(o,s){this.Fa(),this.Ha(o),this.Ga(s)},this.Fa=function(){Y[this.xa+16>>>2>>>0]=0}}var ve=0,re=0,Z=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ce=(r,o,s)=>{o>>>=0;var m=o+s;for(s=o;r[s]&&!(s>=m);)++s;if(16O?m+=String.fromCharCode(O):(O-=65536,m+=String.fromCharCode(55296|O>>10,56320|O&1023))}}else m+=String.fromCharCode(O)}return m},be=(r,o)=>(r>>>=0)?Ce(ae,r,o):"",_e=r=>{for(var o=0,s=0;s=m?o++:2047>=m?o+=2:55296<=m&&57343>=m?(o+=4,++s):o+=3}return o},ke=(r,o,s,m)=>{if(s>>>=0,!(0=R){var K=r.charCodeAt(++S);R=65536+((R&1023)<<10)|K&1023}if(127>=R){if(s>=m)break;o[s++>>>0]=R}else{if(2047>=R){if(s+1>=m)break;o[s++>>>0]=192|R>>6}else{if(65535>=R){if(s+2>=m)break;o[s++>>>0]=224|R>>12}else{if(s+3>=m)break;o[s++>>>0]=240|R>>18,o[s++>>>0]=128|R>>12&63}o[s++>>>0]=128|R>>6&63}o[s++>>>0]=128|R&63}}return o[s>>>0]=0,s-O},Ue=r=>r%4===0&&(r%100!==0||r%400===0),ze=[0,31,60,91,121,152,182,213,244,274,305,335],at=[0,31,59,90,120,151,181,212,243,273,304,334],De=r=>{var o=_e(r)+1,s=st(o);return s&&ke(r,ae,s,o),s},Ne=[],Pe={},He=()=>{if(!$e){var r={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:g||"./this.program"},o;for(o in Pe)Pe[o]===void 0?delete r[o]:r[o]=Pe[o];var s=[];for(o in r)s.push(`${o}=${r[o]}`);$e=s}return $e},$e,Le=[null,[],[]],qe=[31,29,31,30,31,30,31,31,30,31,30,31],Ve=[31,28,31,30,31,30,31,31,30,31,30,31];function Ge(r){var o=Array(_e(r)+1);return ke(r,o,0,o.length),o}function ot(r,o,s,m){function O(c,W,G){for(c=typeof c=="number"?c.toString():c||"";c.lengthKe?-1:0Se-c.getDate())W-=Se-c.getDate()+1,c.setDate(1),11>G?c.setMonth(G+1):(c.setMonth(0),c.setFullYear(c.getFullYear()+1));else{c.setDate(c.getDate()+W);break}}return G=new Date(c.getFullYear()+1,0,4),W=K(new Date(c.getFullYear(),0,4)),G=K(G),0>=R(W,c)?0>=R(G,c)?c.getFullYear()+1:c.getFullYear():c.getFullYear()-1}r>>>=0,o>>>=0,s>>>=0,m>>>=0;var oe=Y[m+40>>>2>>>0];m={Da:E[m>>>2>>>0],Ca:E[m+4>>>2>>>0],va:E[m+8>>>2>>>0],ya:E[m+12>>>2>>>0],wa:E[m+16>>>2>>>0],ua:E[m+20>>>2>>>0],oa:E[m+24>>>2>>>0],ta:E[m+28>>>2>>>0],Ia:E[m+32>>>2>>>0],Ba:E[m+36>>>2>>>0],Ea:oe?be(oe):""},s=be(s),oe={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var se in oe)s=s.replace(new RegExp(se,"g"),oe[se]);var Qe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ze="January February March April May June July August September October November December".split(" ");oe={"%a":c=>Qe[c.oa].substring(0,3),"%A":c=>Qe[c.oa],"%b":c=>Ze[c.wa].substring(0,3),"%B":c=>Ze[c.wa],"%C":c=>S((c.ua+1900)/100|0,2),"%d":c=>S(c.ya,2),"%e":c=>O(c.ya,2," "),"%g":c=>le(c).toString().substring(2),"%G":c=>le(c),"%H":c=>S(c.va,2),"%I":c=>(c=c.va,c==0?c=12:12{for(var W=0,G=0;G<=c.wa-1;W+=(Ue(c.ua+1900)?qe:Ve)[G++]);return S(c.ya+W,3)},"%m":c=>S(c.wa+1,2),"%M":c=>S(c.Ca,2),"%n":()=>`\n`,"%p":c=>0<=c.va&&12>c.va?"AM":"PM","%S":c=>S(c.Da,2),"%t":()=>" ","%u":c=>c.oa||7,"%U":c=>S(Math.floor((c.ta+7-c.oa)/7),2),"%V":c=>{var W=Math.floor((c.ta+7-(c.oa+6)%7)/7);if(2>=(c.oa+371-c.ta-2)%7&&W++,W)W==53&&(G=(c.oa+371-c.ta)%7,G==4||G==3&&Ue(c.ua)||(W=1));else{W=52;var G=(c.oa+7-c.ta-1)%7;(G==4||G==5&&Ue(c.ua%400-1))&&W++}return S(W,2)},"%w":c=>c.oa,"%W":c=>S(Math.floor((c.ta+7-(c.oa+6)%7)/7),2),"%y":c=>(c.ua+1900).toString().substring(2),"%Y":c=>c.ua+1900,"%z":c=>{c=c.Ba;var W=0<=c;return c=Math.abs(c)/60,(W?"+":"-")+("0000"+(c/60*100+c%60)).slice(-4)},"%Z":c=>c.Ea,"%%":()=>"%"},s=s.replace(/%%/g,"\\0\\0");for(se in oe)s.includes(se)&&(s=s.replace(new RegExp(se,"g"),oe[se](m)));return s=s.replace(/\\0\\0/g,"%"),se=Ge(s),se.length>o?0:(ie.set(se,r>>>0),se.length-1)}var $={a:function(r,o,s){throw r>>>=0,new Oe(r).Aa(o>>>0,s>>>0),ve=r,re++,ve},e:function(){return 0},H:function(){},x:function(){},z:function(){},J:function(){return 0},F:function(){},A:function(){},E:function(){},g:function(){},y:function(){},v:function(){},G:function(){},w:function(){},k:()=>1,n:function(r,o,s){r=o+2097152>>>0<4194305-!!r?(r>>>0)+4294967296*o:NaN,s>>>=0,r=new Date(1e3*r),E[s>>>2>>>0]=r.getUTCSeconds(),E[s+4>>>2>>>0]=r.getUTCMinutes(),E[s+8>>>2>>>0]=r.getUTCHours(),E[s+12>>>2>>>0]=r.getUTCDate(),E[s+16>>>2>>>0]=r.getUTCMonth(),E[s+20>>>2>>>0]=r.getUTCFullYear()-1900,E[s+24>>>2>>>0]=r.getUTCDay(),E[s+28>>>2>>>0]=(r.getTime()-Date.UTC(r.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},o:function(r,o,s){r=o+2097152>>>0<4194305-!!r?(r>>>0)+4294967296*o:NaN,s>>>=0,r=new Date(1e3*r),E[s>>>2>>>0]=r.getSeconds(),E[s+4>>>2>>>0]=r.getMinutes(),E[s+8>>>2>>>0]=r.getHours(),E[s+12>>>2>>>0]=r.getDate(),E[s+16>>>2>>>0]=r.getMonth(),E[s+20>>>2>>>0]=r.getFullYear()-1900,E[s+24>>>2>>>0]=r.getDay(),E[s+28>>>2>>>0]=(Ue(r.getFullYear())?ze:at)[r.getMonth()]+r.getDate()-1|0,E[s+36>>>2>>>0]=-(60*r.getTimezoneOffset()),o=new Date(r.getFullYear(),6,1).getTimezoneOffset();var m=new Date(r.getFullYear(),0,1).getTimezoneOffset();E[s+32>>>2>>>0]=(o!=m&&r.getTimezoneOffset()==Math.min(m,o))|0},p:function(r){r>>>=0;var o=new Date(E[r+20>>>2>>>0]+1900,E[r+16>>>2>>>0],E[r+12>>>2>>>0],E[r+8>>>2>>>0],E[r+4>>>2>>>0],E[r>>>2>>>0],0),s=E[r+32>>>2>>>0],m=o.getTimezoneOffset(),O=new Date(o.getFullYear(),6,1).getTimezoneOffset(),S=new Date(o.getFullYear(),0,1).getTimezoneOffset(),R=Math.min(S,O);return 0>s?E[r+32>>>2>>>0]=+(O!=S&&R==m):0>>2>>>0]=o.getDay(),E[r+28>>>2>>>0]=(Ue(o.getFullYear())?ze:at)[o.getMonth()]+o.getDate()-1|0,E[r>>>2>>>0]=o.getSeconds(),E[r+4>>>2>>>0]=o.getMinutes(),E[r+8>>>2>>>0]=o.getHours(),E[r+12>>>2>>>0]=o.getDate(),E[r+16>>>2>>>0]=o.getMonth(),E[r+20>>>2>>>0]=o.getYear(),r=o.getTime(),isNaN(r)?(E[Ye()>>>2>>>0]=61,r=-1):r/=1e3,Je((Ee=r,1<=+Math.abs(Ee)?0>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)),r>>>0},l:function(){return-52},m:function(){},t:function(r,o,s){function m(le){return(le=le.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?le[1]:"GMT"}s>>>=0;var O=new Date().getFullYear(),S=new Date(O,0,1),R=new Date(O,6,1);O=S.getTimezoneOffset();var K=R.getTimezoneOffset();Y[r>>>0>>>2>>>0]=60*Math.max(O,K),E[o>>>0>>>2>>>0]=+(O!=K),r=m(S),o=m(R),r=De(r),o=De(o),K>>2>>>0]=r,Y[s+4>>>2>>>0]=o):(Y[s>>>2>>>0]=o,Y[s+4>>>2>>>0]=r)},d:()=>{de("")},B:function(r,o,s){r>>>=0,o>>>=0,s>>>=0,Ne.length=0;for(var m;m=ae[o++>>>0];){var O=m!=105;O&=m!=112,s+=O&&s%8?4:0,Ne.push(m==112?Y[s>>>2>>>0]:m==105?E[s>>>2>>>0]:ue[s>>>3>>>0]),s+=O?8:4}return pe[r].apply(null,Ne)},h:()=>Date.now(),u:function(){return 4294901760},b:()=>performance.now(),I:function(r,o,s){return o>>>=0,ae.copyWithin(r>>>0>>>0,o>>>0,o+(s>>>0)>>>0)},s:function(r){r>>>=0;var o=ae.length;if(4294901760=s;s*=2){var m=o*(1+.2/s);m=Math.min(m,r+100663296);var O=Math;m=Math.max(r,m);e:{O=(O.min.call(O,4294901760,m+(65536-m%65536)%65536)-N.buffer.byteLength+65535)/65536;try{N.grow(O),Re();var S=1;break e}catch{}S=void 0}if(S)return!0}return!1},C:function(r,o){r>>>=0,o>>>=0;var s=0;return He().forEach((m,O)=>{var S=o+s;for(O=Y[r+4*O>>>2>>>0]=S,S=0;S>>0>>>0]=m.charCodeAt(S);ie[O>>>0>>>0]=0,s+=m.length+1}),0},D:function(r,o){r>>>=0,o>>>=0;var s=He();Y[r>>>2>>>0]=s.length;var m=0;return s.forEach(O=>m+=O.length+1),Y[o>>>2>>>0]=m,0},f:()=>52,j:function(){return 52},q:function(){return 70},i:function(r,o,s,m){o>>>=0,s>>>=0,m>>>=0;for(var O=0,S=0;S>>2>>>0],K=Y[o+4>>>2>>>0];o+=8;for(var le=0;le>>0],se=Le[r];oe===0||oe===10?((r===1?_:x)(Ce(se,0)),se.length=0):se.push(oe)}O+=K}return Y[m>>>2>>>0]=O,0},r:ot,c:function(r,o,s,m){return ot(r>>>0,o>>>0,s>>>0,m>>>0)}},C=function(){function r(s){return C=s.exports,C=ut(),N=C.K,Re(),ee.unshift(C.L),ce--,ce==0&&(P!==null&&(clearInterval(P),P=null),te&&(s=te,te=null,s())),C}var o={a:$};if(ce++,a.instantiateWasm)try{return a.instantiateWasm(o,r)}catch(s){x(`Module.instantiateWasm callback failed with error: ${s}`),l(s)}return Fe(o,function(s){r(s.instance)}).catch(l),{}}();a._OrtInit=(r,o)=>(a._OrtInit=C.M)(r,o),a._OrtGetLastError=(r,o)=>(a._OrtGetLastError=C.N)(r,o),a._OrtCreateSessionOptions=(r,o,s,m,O,S,R,K,le,oe)=>(a._OrtCreateSessionOptions=C.O)(r,o,s,m,O,S,R,K,le,oe),a._OrtAppendExecutionProvider=(r,o)=>(a._OrtAppendExecutionProvider=C.P)(r,o),a._OrtAddFreeDimensionOverride=(r,o,s)=>(a._OrtAddFreeDimensionOverride=C.Q)(r,o,s),a._OrtAddSessionConfigEntry=(r,o,s)=>(a._OrtAddSessionConfigEntry=C.R)(r,o,s),a._OrtReleaseSessionOptions=r=>(a._OrtReleaseSessionOptions=C.S)(r),a._OrtCreateSession=(r,o,s)=>(a._OrtCreateSession=C.T)(r,o,s),a._OrtReleaseSession=r=>(a._OrtReleaseSession=C.U)(r),a._OrtGetInputOutputCount=(r,o,s)=>(a._OrtGetInputOutputCount=C.V)(r,o,s),a._OrtGetInputName=(r,o)=>(a._OrtGetInputName=C.W)(r,o),a._OrtGetOutputName=(r,o)=>(a._OrtGetOutputName=C.X)(r,o),a._OrtFree=r=>(a._OrtFree=C.Y)(r),a._OrtCreateTensor=(r,o,s,m,O,S)=>(a._OrtCreateTensor=C.Z)(r,o,s,m,O,S),a._OrtGetTensorData=(r,o,s,m,O)=>(a._OrtGetTensorData=C._)(r,o,s,m,O),a._OrtReleaseTensor=r=>(a._OrtReleaseTensor=C.$)(r),a._OrtCreateRunOptions=(r,o,s,m)=>(a._OrtCreateRunOptions=C.aa)(r,o,s,m),a._OrtAddRunConfigEntry=(r,o,s)=>(a._OrtAddRunConfigEntry=C.ba)(r,o,s),a._OrtReleaseRunOptions=r=>(a._OrtReleaseRunOptions=C.ca)(r),a._OrtCreateBinding=r=>(a._OrtCreateBinding=C.da)(r),a._OrtBindInput=(r,o,s)=>(a._OrtBindInput=C.ea)(r,o,s),a._OrtBindOutput=(r,o,s,m)=>(a._OrtBindOutput=C.fa)(r,o,s,m),a._OrtClearBoundOutputs=r=>(a._OrtClearBoundOutputs=C.ga)(r),a._OrtReleaseBinding=r=>(a._OrtReleaseBinding=C.ha)(r),a._OrtRunWithBinding=(r,o,s,m,O)=>(a._OrtRunWithBinding=C.ia)(r,o,s,m,O),a._OrtRun=(r,o,s,m,O,S,R,K)=>(a._OrtRun=C.ja)(r,o,s,m,O,S,R,K),a._OrtEndProfiling=r=>(a._OrtEndProfiling=C.ka)(r);var Ye=()=>(Ye=C.la)(),st=a._malloc=r=>(st=a._malloc=C.ma)(r);a._free=r=>(a._free=C.na)(r);var Je=r=>(Je=C.pa)(r),it=()=>(it=C.qa)(),M=r=>(M=C.ra)(r),Be=r=>(Be=C.sa)(r);function ut(){var r=C;r=Object.assign({},r);var o=m=>()=>m()>>>0,s=m=>O=>m(O)>>>0;return r.la=o(r.la),r.ma=s(r.ma),r.qa=o(r.qa),r.sa=s(r.sa),r}a.stackAlloc=Be,a.stackSave=it,a.stackRestore=M,a.UTF8ToString=be,a.stringToUTF8=(r,o,s)=>ke(r,ae,o,s),a.lengthBytesUTF8=_e;var xe;te=function r(){xe||Xe(),xe||(te=r)};function Xe(){if(!(0pr)});var hr=et(()=>{});var yr=et(()=>{});var br={};Tt(br,{cpus:()=>rn});var rn,wr=St(()=>{rn=void 0});var _r=et((vr,Ft)=>{"use strict";var Or=(()=>{var u=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(u=u||__filename),function(d={}){function a(){return j.buffer!=de.buffer&&we(),de}function h(){return j.buffer!=de.buffer&&we(),ge}function l(){return j.buffer!=de.buffer&&we(),ye}function w(){return j.buffer!=de.buffer&&we(),J}function g(){return j.buffer!=de.buffer&&we(),fe}var i=d,A,D;i.ready=new Promise((e,t)=>{A=e,D=t});var I=Object.assign({},i),B="./this.program",F=(e,t)=>{throw t},U=typeof window=="object",k=typeof importScripts=="function",L=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",_=i.ENVIRONMENT_IS_PTHREAD||!1,x="";function N(e){return i.locateFile?i.locateFile(e,x):x+e}var he,ie,ae;if(L){var E=(Mt(),tt(At)),Y=(Dt(),tt(Ct));x=k?Y.dirname(x)+"/":__dirname+"/",he=(t,n)=>(t=be(t)?new URL(t):Y.normalize(t),E.readFileSync(t,n?void 0:"utf8")),ae=t=>(t=he(t,!0),t.buffer||(t=new Uint8Array(t)),t),ie=(t,n,f,y=!0)=>{t=be(t)?new URL(t):Y.normalize(t),E.readFile(t,y?void 0:"utf8",(b,v)=>{b?f(b):n(y?v.buffer:v)})},!i.thisProgram&&1{throw process.exitCode=t,n},i.inspect=()=>"[Emscripten Module object]";let e;try{e=hr()}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}global.Worker=e.Worker}else(U||k)&&(k?x=self.location.href:typeof document<"u"&&document.currentScript&&(x=document.currentScript.src),typeof u<"u"&&u&&(x=u),x.indexOf("blob:")!==0?x=x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1):x="",L||(he=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},k&&(ae=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),ie=(e,t,n)=>{var f=new XMLHttpRequest;f.open("GET",e,!0),f.responseType="arraybuffer",f.onload=()=>{f.status==200||f.status==0&&f.response?t(f.response):n()},f.onerror=n,f.send(null)}));L&&typeof performance>"u"&&(global.performance=yr().performance);var ue=console.log.bind(console),Re=console.error.bind(console);L&&(ue=(...e)=>E.writeSync(1,e.join(" ")+`\n`),Re=(...e)=>E.writeSync(2,e.join(" ")+`\n`));var Ie=ue,ee=Re;Object.assign(i,I),I=null,typeof WebAssembly!="object"&&Z("no native wasm support detected");var j,ce,P=!1,te,de,ge,ye,J,fe;function we(){var e=j.buffer;i.HEAP8=de=new Int8Array(e),i.HEAP16=new Int16Array(e),i.HEAPU8=ge=new Uint8Array(e),i.HEAPU16=new Uint16Array(e),i.HEAP32=ye=new Int32Array(e),i.HEAPU32=J=new Uint32Array(e),i.HEAPF32=new Float32Array(e),i.HEAPF64=fe=new Float64Array(e)}var Ae=16777216;if(_)j=i.wasmMemory;else if(i.wasmMemory)j=i.wasmMemory;else if(j=new WebAssembly.Memory({initial:Ae/65536,maximum:65536,shared:!0}),!(j.buffer instanceof SharedArrayBuffer))throw ee("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),L&&ee("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");we(),Ae=j.buffer.byteLength;var Me=[],Fe=[],Ee=[],pe=0,Oe=null,ve=null;function re(){if(pe--,pe==0&&(Oe!==null&&(clearInterval(Oe),Oe=null),ve)){var e=ve;ve=null,e()}}function Z(e){throw e="Aborted("+e+")",ee(e),P=!0,te=1,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),D(e),e}var Ce=e=>e.startsWith("data:application/octet-stream;base64,"),be=e=>e.startsWith("file://"),_e;_e="ort-wasm-threaded.wasm",Ce(_e)||(_e=N(_e));function ke(e){if(ae)return ae(e);throw"both async and sync fetching of the wasm failed"}function Ue(e){if(U||k){if(typeof fetch=="function"&&!be(e))return fetch(e,{credentials:"same-origin"}).then(t=>{if(!t.ok)throw"failed to load wasm binary file at \'"+e+"\'";return t.arrayBuffer()}).catch(()=>ke(e));if(ie)return new Promise((t,n)=>{ie(e,f=>t(new Uint8Array(f)),n)})}return Promise.resolve().then(()=>ke(e))}function ze(e,t,n){return Ue(e).then(f=>WebAssembly.instantiate(f,t)).then(f=>f).then(n,f=>{ee(`failed to asynchronously prepare wasm: ${f}`),Z(f)})}function at(e,t){var n=_e;return typeof WebAssembly.instantiateStreaming!="function"||Ce(n)||be(n)||L||typeof fetch!="function"?ze(n,e,t):fetch(n,{credentials:"same-origin"}).then(f=>WebAssembly.instantiateStreaming(f,e).then(t,function(y){return ee(`wasm streaming compile failed: ${y}`),ee("falling back to ArrayBuffer instantiation"),ze(n,e,t)}))}var De,Ne={921276:(e,t,n,f)=>{if(typeof i>"u"||!i.cb)return 1;if(e=Ge(e>>>0),e.startsWith("./")&&(e=e.substring(2)),e=i.cb.get(e),!e)return 2;if(t>>>=0,n>>>=0,f>>>=0,t+n>e.byteLength)return 3;try{return h().set(e.subarray(t,t+n),f>>>0),0}catch{return 4}}};function Pe(e){this.name="ExitStatus",this.message=`Program terminated with exit(${e})`,this.status=e}var He=e=>{e.terminate(),e.onmessage=()=>{}},$e=e=>{M.Pa.length==0&&(Je(),M.Ya(M.Pa[0]));var t=M.Pa.pop();if(!t)return 6;M.Qa.push(t),M.Ma[e.Oa]=t,t.Oa=e.Oa;var n={cmd:"run",start_routine:e.kb,arg:e.hb,pthread_ptr:e.Oa};return L&&t.unref(),t.postMessage(n,e.qb),0},Le=0,qe=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ve=(e,t,n)=>{t>>>=0;var f=t+n;for(n=t;e[n]&&!(n>=f);)++n;if(16y?f+=String.fromCharCode(y):(y-=65536,f+=String.fromCharCode(55296|y>>10,56320|y&1023))}}else f+=String.fromCharCode(y)}return f},Ge=(e,t)=>(e>>>=0)?Ve(h(),e,t):"",ot=e=>{var t=vt();return e=e(),ct(t),e};function $(e,t){var n=arguments.length-2,f=arguments;return ot(()=>{for(var y=_t(8*n),b=y>>>3,v=0;v>>0]=z}return ar(e,n,y,t)})}function C(e){if(_)return $(0,1,e);te=e,0{if(te=e,_)throw ut(e),"unwind";C(e)};function st(){for(var e=i.numThreads;e--;)Je();Me.unshift(()=>{pe++,it(()=>re())})}function Je(){var e=N("ort-wasm-threaded.worker.js");e=new Worker(e),M.Pa.push(e)}function it(e){_?e():Promise.all(M.Pa.map(M.Ya)).then(e)}var M={Pa:[],Qa:[],bb:[],Ma:{},Wa(){_?(M.receiveObjectTransfer=M.jb,M.threadInitTLS=M.ab,M.setExitStatus=M.$a):st()},$a:e=>te=e,tb:["$terminateWorker"],lb:()=>{for(var e of M.Qa)He(e);for(e of M.Pa)He(e);M.Pa=[],M.Qa=[],M.Ma=[]},Za:e=>{var t=e.Oa;delete M.Ma[t],M.Pa.push(e),M.Qa.splice(M.Qa.indexOf(e),1),e.Oa=0,wt(t)},jb(){},ab(){M.bb.forEach(e=>e())},Ya:e=>new Promise(t=>{e.onmessage=b=>{b=b.data;var v=b.cmd;if(b.targetThread&&b.targetThread!=lt()){var z=M.Ma[b.targetThread];z?z.postMessage(b,b.transferList):ee(`Internal error! Worker sent a message "${v}" to target pthread ${b.targetThread}, but that thread no longer exists!`)}else v==="checkMailbox"?ft():v==="spawnThread"?$e(b):v==="cleanupThread"?M.Za(M.Ma[b.thread]):v==="killThread"?(b=b.thread,v=M.Ma[b],delete M.Ma[b],He(v),wt(b),M.Qa.splice(M.Qa.indexOf(v),1),v.Oa=0):v==="cancelThread"?M.Ma[b.thread].postMessage({cmd:"cancel"}):v==="loaded"?(e.loaded=!0,L&&!e.Oa&&e.unref(),t(e)):v==="alert"?alert(`Thread ${b.threadId}: ${b.text}`):b.target==="setimmediate"?e.postMessage(b):v==="callHandler"?i[b.handler](...b.args):v&&ee(`worker sent an unknown command ${v}`)},e.onerror=b=>{throw ee(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b},L&&(e.on("message",b=>e.onmessage({data:b})),e.on("error",b=>e.onerror(b)));var n=[],f=["onExit"],y;for(y of f)i.hasOwnProperty(y)&&n.push(y);e.postMessage({cmd:"load",handlers:n,urlOrBlob:i.mainScriptUrlOrBlob||u,wasmMemory:j,wasmModule:ce})})};i.PThread=M;var Be=e=>{for(;0{var e=lt(),t=w()[e+52>>>2>>>0];e=w()[e+56>>>2>>>0],ir(t,t-e),ct(t)};function ut(e){if(_)return $(1,0,e);Ye(e)}var xe=[],Xe;i.invokeEntryPoint=(e,t)=>{var n=xe[e];n||(e>=xe.length&&(xe.length=e+1),xe[e]=n=Xe.get(e)),e=n(t),0>>2>>>0]=t},this.fb=function(t){w()[this.Va+8>>>2>>>0]=t},this.Wa=function(t,n){this.eb(),this.gb(t),this.fb(n)},this.eb=function(){w()[this.Va+16>>>2>>>0]=0}}var o=0,s=0;function m(e,t,n,f){return _?$(2,1,e,t,n,f):O(e,t,n,f)}function O(e,t,n,f){if(e>>>=0,t>>>=0,n>>>=0,f>>>=0,typeof SharedArrayBuffer>"u")return ee("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var y=[];return _&&y.length===0?m(e,t,n,f):(e={kb:n,Oa:e,hb:f,qb:y},_?(e.sb="spawnThread",postMessage(e,y),0):$e(e))}function S(e,t,n){return _?$(3,1,e,t,n):0}function R(e,t){if(_)return $(4,1,e,t)}var K=e=>{for(var t=0,n=0;n=f?t++:2047>=f?t+=2:55296<=f&&57343>=f?(t+=4,++n):t+=3}return t},le=(e,t,n,f)=>{if(n>>>=0,!(0=v){var z=e.charCodeAt(++b);v=65536+((v&1023)<<10)|z&1023}if(127>=v){if(n>=f)break;t[n++>>>0]=v}else{if(2047>=v){if(n+1>=f)break;t[n++>>>0]=192|v>>6}else{if(65535>=v){if(n+2>=f)break;t[n++>>>0]=224|v>>12}else{if(n+3>=f)break;t[n++>>>0]=240|v>>18,t[n++>>>0]=128|v>>12&63}t[n++>>>0]=128|v>>6&63}t[n++>>>0]=128|v&63}}return t[n>>>0]=0,n-y},oe=(e,t,n)=>le(e,h(),t,n);function se(e,t){if(_)return $(5,1,e,t)}function Qe(e,t,n){if(_)return $(6,1,e,t,n)}function Ze(e,t,n){return _?$(7,1,e,t,n):0}function c(e,t){if(_)return $(8,1,e,t)}function W(e,t,n){if(_)return $(9,1,e,t,n)}function G(e,t,n,f){if(_)return $(10,1,e,t,n,f)}function Se(e,t,n,f){if(_)return $(11,1,e,t,n,f)}function Ke(e,t,n,f){if(_)return $(12,1,e,t,n,f)}function Bt(e){if(_)return $(13,1,e)}function Wt(e,t){if(_)return $(14,1,e,t)}function kt(e,t,n){if(_)return $(15,1,e,t,n)}function mt(e){e>>>=0,typeof Atomics.rb=="function"&&(Atomics.rb(l(),e>>>2,e).value.then(ft),e+=128,Atomics.store(l(),e>>>2,1))}i.__emscripten_thread_mailbox_await=mt;var ft=()=>{var e=lt();if(e&&(mt(e),e=or,!P))try{if(e(),!(0e%4===0&&(e%100!==0||e%400===0),Nt=[0,31,60,91,121,152,182,213,244,274,305,335],Ht=[0,31,59,90,120,151,181,212,243,273,304,334];function $t(e,t,n,f,y,b,v,z){return _?$(16,1,e,t,n,f,y,b,v,z):-52}function Gt(e,t,n,f,y,b,v){if(_)return $(17,1,e,t,n,f,y,b,v)}var Yt=e=>{var t=K(e)+1,n=rr(t);return n&&oe(e,n,t),n},ht=[],yt={},jt=()=>{if(!bt){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:B||"./this.program"},t;for(t in yt)yt[t]===void 0?delete e[t]:e[t]=yt[t];var n=[];for(t in e)n.push(`${t}=${e[t]}`);bt=n}return bt},bt;function zt(e,t){if(_)return $(18,1,e,t);e>>>=0,t>>>=0;var n=0;return jt().forEach((f,y)=>{var b=t+n;for(y=w()[e+4*y>>>2>>>0]=b,b=0;b>>0>>>0]=f.charCodeAt(b);a()[y>>>0>>>0]=0,n+=f.length+1}),0}function qt(e,t){if(_)return $(19,1,e,t);e>>>=0,t>>>=0;var n=jt();w()[e>>>2>>>0]=n.length;var f=0;return n.forEach(y=>f+=y.length+1),w()[t>>>2>>>0]=f,0}function Vt(e){return _?$(20,1,e):52}function Jt(e,t,n,f){return _?$(21,1,e,t,n,f):52}function Xt(e,t,n,f,y){return _?$(22,1,e,t,n,f,y):70}var Gr=[null,[],[]];function Qt(e,t,n,f){if(_)return $(23,1,e,t,n,f);t>>>=0,n>>>=0,f>>>=0;for(var y=0,b=0;b>>2>>>0],z=w()[t+4>>>2>>>0];t+=8;for(var Te=0;Te>>0],me=Gr[e];ne===0||ne===10?((e===1?Ie:ee)(Ve(me,0)),me.length=0):me.push(ne)}y+=z}return w()[f>>>2>>>0]=y,0}var Zt=[31,29,31,30,31,30,31,31,30,31,30,31],Kt=[31,28,31,30,31,30,31,31,30,31,30,31];function Yr(e){var t=Array(K(e)+1);return le(e,t,0,t.length),t}var jr=(e,t)=>{a().set(e,t>>>0)};function er(e,t,n,f){function y(p,H,q){for(p=typeof p=="number"?p.toString():p||"";p.lengthcr?-1:0We-p.getDate())H-=We-p.getDate()+1,p.setDate(1),11>q?p.setMonth(q+1):(p.setMonth(0),p.setFullYear(p.getFullYear()+1));else{p.setDate(p.getDate()+H);break}}return q=new Date(p.getFullYear()+1,0,4),H=z(new Date(p.getFullYear(),0,4)),q=z(q),0>=v(H,p)?0>=v(q,p)?p.getFullYear()+1:p.getFullYear():p.getFullYear()-1}e>>>=0,t>>>=0,n>>>=0,f>>>=0;var ne=w()[f+40>>>2>>>0];f={ob:l()[f>>>2>>>0],nb:l()[f+4>>>2>>>0],Ta:l()[f+8>>>2>>>0],Xa:l()[f+12>>>2>>>0],Ua:l()[f+16>>>2>>>0],Sa:l()[f+20>>>2>>>0],Na:l()[f+24>>>2>>>0],Ra:l()[f+28>>>2>>>0],ub:l()[f+32>>>2>>>0],mb:l()[f+36>>>2>>>0],pb:ne?Ge(ne):""},n=Ge(n),ne={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var me in ne)n=n.replace(new RegExp(me,"g"),ne[me]);var fr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),lr="January February March April May June July August September October November December".split(" ");ne={"%a":p=>fr[p.Na].substring(0,3),"%A":p=>fr[p.Na],"%b":p=>lr[p.Ua].substring(0,3),"%B":p=>lr[p.Ua],"%C":p=>b((p.Sa+1900)/100|0,2),"%d":p=>b(p.Xa,2),"%e":p=>y(p.Xa,2," "),"%g":p=>Te(p).toString().substring(2),"%G":p=>Te(p),"%H":p=>b(p.Ta,2),"%I":p=>(p=p.Ta,p==0?p=12:12{for(var H=0,q=0;q<=p.Ua-1;H+=(je(p.Sa+1900)?Zt:Kt)[q++]);return b(p.Xa+H,3)},"%m":p=>b(p.Ua+1,2),"%M":p=>b(p.nb,2),"%n":()=>`\n`,"%p":p=>0<=p.Ta&&12>p.Ta?"AM":"PM","%S":p=>b(p.ob,2),"%t":()=>" ","%u":p=>p.Na||7,"%U":p=>b(Math.floor((p.Ra+7-p.Na)/7),2),"%V":p=>{var H=Math.floor((p.Ra+7-(p.Na+6)%7)/7);if(2>=(p.Na+371-p.Ra-2)%7&&H++,H)H==53&&(q=(p.Na+371-p.Ra)%7,q==4||q==3&&je(p.Sa)||(H=1));else{H=52;var q=(p.Na+7-p.Ra-1)%7;(q==4||q==5&&je(p.Sa%400-1))&&H++}return b(H,2)},"%w":p=>p.Na,"%W":p=>b(Math.floor((p.Ra+7-(p.Na+6)%7)/7),2),"%y":p=>(p.Sa+1900).toString().substring(2),"%Y":p=>p.Sa+1900,"%z":p=>{p=p.mb;var H=0<=p;return p=Math.abs(p)/60,(H?"+":"-")+("0000"+(p/60*100+p%60)).slice(-4)},"%Z":p=>p.pb,"%%":()=>"%"},n=n.replace(/%%/g,"\\0\\0");for(me in ne)n.includes(me)&&(n=n.replace(new RegExp(me,"g"),ne[me](f)));return n=n.replace(/\\0\\0/g,"%"),me=Yr(n),me.length>t?0:(jr(me,e),me.length-1)}M.Wa();var zr=[C,ut,m,S,R,se,Qe,Ze,c,W,G,Se,Ke,Bt,Wt,kt,$t,Gt,zt,qt,Vt,Jt,Xt,Qt],qr={b:function(e,t,n){throw e>>>=0,new r(e).Wa(t>>>0,n>>>0),o=e,s++,o},L:function(e){nr(e>>>0,!k,1,!U,131072,!1),M.ab()},j:function(e){e>>>=0,_?postMessage({cmd:"cleanupThread",thread:e}):M.Za(M.Ma[e])},H:O,h:S,S:R,D:se,F:Qe,T:Ze,Q:c,J:W,P:G,n:Se,E:Ke,B:Bt,R:Wt,C:kt,p:()=>1,z:function(e,t){e>>>=0,e==t>>>0?setTimeout(()=>ft()):_?postMessage({targetThread:e,cmd:"checkMailbox"}):(e=M.Ma[e])&&e.postMessage({cmd:"checkMailbox"})},I:function(e,t,n,f){t>>>=0,gt.length=n,f=f>>>0>>>3;for(var y=0;y>>0];return e=0>e?Ne[-e-1]:zr[e],M.ib=t,t=e.apply(null,gt),M.ib=0,t},K:mt,o:function(e){L&&M.Ma[e>>>0].ref()},s:function(e,t,n){e=t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN,n>>>=0,e=new Date(1e3*e),l()[n>>>2>>>0]=e.getUTCSeconds(),l()[n+4>>>2>>>0]=e.getUTCMinutes(),l()[n+8>>>2>>>0]=e.getUTCHours(),l()[n+12>>>2>>>0]=e.getUTCDate(),l()[n+16>>>2>>>0]=e.getUTCMonth(),l()[n+20>>>2>>>0]=e.getUTCFullYear()-1900,l()[n+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,l()[n+28>>>2>>>0]=e},t:function(e,t,n){e=t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN,n>>>=0,e=new Date(1e3*e),l()[n>>>2>>>0]=e.getSeconds(),l()[n+4>>>2>>>0]=e.getMinutes(),l()[n+8>>>2>>>0]=e.getHours(),l()[n+12>>>2>>>0]=e.getDate(),l()[n+16>>>2>>>0]=e.getMonth(),l()[n+20>>>2>>>0]=e.getFullYear()-1900,l()[n+24>>>2>>>0]=e.getDay(),t=(je(e.getFullYear())?Nt:Ht)[e.getMonth()]+e.getDate()-1|0,l()[n+28>>>2>>>0]=t,l()[n+36>>>2>>>0]=-(60*e.getTimezoneOffset()),t=new Date(e.getFullYear(),6,1).getTimezoneOffset();var f=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=(t!=f&&e.getTimezoneOffset()==Math.min(f,t))|0,l()[n+32>>>2>>>0]=e},u:function(e){e>>>=0;var t=new Date(l()[e+20>>>2>>>0]+1900,l()[e+16>>>2>>>0],l()[e+12>>>2>>>0],l()[e+8>>>2>>>0],l()[e+4>>>2>>>0],l()[e>>>2>>>0],0),n=l()[e+32>>>2>>>0],f=t.getTimezoneOffset(),y=new Date(t.getFullYear(),6,1).getTimezoneOffset(),b=new Date(t.getFullYear(),0,1).getTimezoneOffset(),v=Math.min(b,y);return 0>n?l()[e+32>>>2>>>0]=+(y!=b&&v==f):0>>2>>>0]=t.getDay(),n=(je(t.getFullYear())?Nt:Ht)[t.getMonth()]+t.getDate()-1|0,l()[e+28>>>2>>>0]=n,l()[e>>>2>>>0]=t.getSeconds(),l()[e+4>>>2>>>0]=t.getMinutes(),l()[e+8>>>2>>>0]=t.getHours(),l()[e+12>>>2>>>0]=t.getDate(),l()[e+16>>>2>>>0]=t.getMonth(),l()[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),isNaN(e)?(l()[tr()>>>2>>>0]=61,e=-1):e/=1e3,sr((De=e,1<=+Math.abs(De)?0>>0:~~+Math.ceil((De-+(~~De>>>0))/4294967296)>>>0:0)),e>>>0},q:$t,r:Gt,y:function(e,t,n){function f(ne){return(ne=ne.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?ne[1]:"GMT"}e>>>=0,t>>>=0,n>>>=0;var y=new Date().getFullYear(),b=new Date(y,0,1),v=new Date(y,6,1);y=b.getTimezoneOffset();var z=v.getTimezoneOffset(),Te=Math.max(y,z);w()[e>>>2>>>0]=60*Te,l()[t>>>2>>>0]=+(y!=z),e=f(b),t=f(v),e=Yt(e),t=Yt(t),z>>2>>>0]=e,w()[n+4>>>2>>>0]=t):(w()[n>>>2>>>0]=t,w()[n+4>>>2>>>0]=e)},c:()=>{Z("")},O:function(e,t,n){e>>>=0,t>>>=0,n>>>=0,ht.length=0;for(var f;f=h()[t++>>>0];){var y=f!=105;y&=f!=112,n+=y&&n%8?4:0,ht.push(f==112?w()[n>>>2>>>0]:f==105?l()[n>>>2>>>0]:g()[n>>>3>>>0]),n+=y?8:4}return Ne[e].apply(null,ht)},k:()=>{},i:()=>Date.now(),U:()=>{throw Le+=1,"unwind"},A:function(){return 4294901760},e:()=>performance.timeOrigin+performance.now(),f:()=>L?(wr(),tt(br)).cpus().length:navigator.hardwareConcurrency,x:function(e){e>>>=0;var t=h().length;if(e<=t||4294901760=n;n*=2){var f=t*(1+.2/n);f=Math.min(f,e+100663296);var y=Math;f=Math.max(e,f);e:{y=(y.min.call(y,4294901760,f+(65536-f%65536)%65536)-j.buffer.byteLength+65535)/65536;try{j.grow(y),we();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1},M:zt,N:qt,G:Ye,g:Vt,m:Jt,v:Xt,l:Qt,a:j||i.wasmMemory,w:er,d:function(e,t,n,f){return er(e>>>0,t>>>0,n>>>0,f>>>0)}},T=function(){function e(n,f){return T=n.exports,T=Vr(),M.bb.push(T.za),Xe=T.Aa,Fe.unshift(T.V),ce=f,re(),T}var t={a:qr};if(pe++,i.instantiateWasm)try{return i.instantiateWasm(t,e)}catch(n){ee(`Module.instantiateWasm callback failed with error: ${n}`),D(n)}return at(t,function(n){e(n.instance,n.module)}).catch(D),{}}();i._OrtInit=(e,t)=>(i._OrtInit=T.W)(e,t),i._OrtGetLastError=(e,t)=>(i._OrtGetLastError=T.X)(e,t),i._OrtCreateSessionOptions=(e,t,n,f,y,b,v,z,Te,ne)=>(i._OrtCreateSessionOptions=T.Y)(e,t,n,f,y,b,v,z,Te,ne),i._OrtAppendExecutionProvider=(e,t)=>(i._OrtAppendExecutionProvider=T.Z)(e,t),i._OrtAddFreeDimensionOverride=(e,t,n)=>(i._OrtAddFreeDimensionOverride=T._)(e,t,n),i._OrtAddSessionConfigEntry=(e,t,n)=>(i._OrtAddSessionConfigEntry=T.$)(e,t,n),i._OrtReleaseSessionOptions=e=>(i._OrtReleaseSessionOptions=T.aa)(e),i._OrtCreateSession=(e,t,n)=>(i._OrtCreateSession=T.ba)(e,t,n),i._OrtReleaseSession=e=>(i._OrtReleaseSession=T.ca)(e),i._OrtGetInputOutputCount=(e,t,n)=>(i._OrtGetInputOutputCount=T.da)(e,t,n),i._OrtGetInputName=(e,t)=>(i._OrtGetInputName=T.ea)(e,t),i._OrtGetOutputName=(e,t)=>(i._OrtGetOutputName=T.fa)(e,t),i._OrtFree=e=>(i._OrtFree=T.ga)(e),i._OrtCreateTensor=(e,t,n,f,y,b)=>(i._OrtCreateTensor=T.ha)(e,t,n,f,y,b),i._OrtGetTensorData=(e,t,n,f,y)=>(i._OrtGetTensorData=T.ia)(e,t,n,f,y),i._OrtReleaseTensor=e=>(i._OrtReleaseTensor=T.ja)(e),i._OrtCreateRunOptions=(e,t,n,f)=>(i._OrtCreateRunOptions=T.ka)(e,t,n,f),i._OrtAddRunConfigEntry=(e,t,n)=>(i._OrtAddRunConfigEntry=T.la)(e,t,n),i._OrtReleaseRunOptions=e=>(i._OrtReleaseRunOptions=T.ma)(e),i._OrtCreateBinding=e=>(i._OrtCreateBinding=T.na)(e),i._OrtBindInput=(e,t,n)=>(i._OrtBindInput=T.oa)(e,t,n),i._OrtBindOutput=(e,t,n,f)=>(i._OrtBindOutput=T.pa)(e,t,n,f),i._OrtClearBoundOutputs=e=>(i._OrtClearBoundOutputs=T.qa)(e),i._OrtReleaseBinding=e=>(i._OrtReleaseBinding=T.ra)(e),i._OrtRunWithBinding=(e,t,n,f,y)=>(i._OrtRunWithBinding=T.sa)(e,t,n,f,y),i._OrtRun=(e,t,n,f,y,b,v,z)=>(i._OrtRun=T.ta)(e,t,n,f,y,b,v,z),i._OrtEndProfiling=e=>(i._OrtEndProfiling=T.ua)(e);var tr=()=>(tr=T.va)(),lt=i._pthread_self=()=>(lt=i._pthread_self=T.wa)(),rr=i._malloc=e=>(rr=i._malloc=T.xa)(e);i._free=e=>(i._free=T.ya)(e),i.__emscripten_tls_init=()=>(i.__emscripten_tls_init=T.za)();var nr=i.__emscripten_thread_init=(e,t,n,f,y,b)=>(nr=i.__emscripten_thread_init=T.Ba)(e,t,n,f,y,b);i.__emscripten_thread_crashed=()=>(i.__emscripten_thread_crashed=T.Ca)();var ar=(e,t,n,f)=>(ar=T.Da)(e,t,n,f),wt=e=>(wt=T.Ea)(e),Ot=i.__emscripten_thread_exit=e=>(Ot=i.__emscripten_thread_exit=T.Fa)(e),or=()=>(or=T.Ga)(),sr=e=>(sr=T.Ha)(e),ir=(e,t)=>(ir=T.Ia)(e,t),vt=()=>(vt=T.Ja)(),ct=e=>(ct=T.Ka)(e),_t=e=>(_t=T.La)(e);function Vr(){var e=T;e=Object.assign({},e);var t=f=>()=>f()>>>0,n=f=>y=>f(y)>>>0;return e.va=t(e.va),e.wa=t(e.wa),e.xa=n(e.xa),e.emscripten_main_runtime_thread_id=t(e.emscripten_main_runtime_thread_id),e.Ja=t(e.Ja),e.La=n(e.La),e}i.wasmMemory=j,i.stackAlloc=_t,i.stackSave=vt,i.stackRestore=ct,i.keepRuntimeAlive=()=>0Or)});var Er=et((On,nn)=>{nn.exports=\'"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\\n\'});var Tr;Tr=gr();var an=_r(),Ut,Pt=!1,pt=!1,Sr=!1,on=u=>{if(u===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+u+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+u+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},sn=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},un=(u,d)=>u?d?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":d?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Ar=async u=>{if(Pt)return Promise.resolve();if(pt)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Sr)throw new Error("previous call to \'initializeWebAssembly()\' failed.");pt=!0;let d=u.initTimeout,a=u.numThreads,h=u.simd,l=on(a),w=h&&sn(),g=u.wasmPaths,i=typeof g=="string"?g:void 0,A=un(w,l),D=typeof g=="object"?g[A]:void 0,I=!1,B=[];if(d>0&&B.push(new Promise(F=>{setTimeout(()=>{I=!0,F()},d)})),B.push(new Promise((F,U)=>{let k=l?an:Tr,L={locateFile:(_,x)=>l&&_.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([Er()],{type:"text/javascript"})):_.endsWith(".wasm")?D||(i??x)+A:x+_};if(l)if(L.numThreads=a,typeof Blob>"u")L.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let _=`var ortWasmThreaded=${k.toString()};`;L.mainScriptUrlOrBlob=new Blob([_],{type:"text/javascript"})}k(L).then(_=>{pt=!1,Pt=!0,Ut=_,F()},_=>{pt=!1,Sr=!0,U(_)})})),await Promise.race(B),I)throw new Error(`WebAssembly backend initializing failed due to timeout: ${d}ms`)},X=()=>{if(Pt&&Ut)return Ut;throw new Error("WebAssembly is not initialized yet.")};var Q=(u,d)=>{let a=X(),h=a.lengthBytesUTF8(u)+1,l=a._malloc(h);return a.stringToUTF8(u,l,h),d.push(l),l},rt=(u,d,a,h)=>{if(typeof u=="object"&&u!==null){if(a.has(u))throw new Error("Circular reference in options");a.add(u)}Object.entries(u).forEach(([l,w])=>{let g=d?d+l:l;if(typeof w=="object")rt(w,g+".",a,h);else if(typeof w=="string"||typeof w=="number")h(g,w.toString());else if(typeof w=="boolean")h(g,w?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof w}`)})},V=u=>{let d=X(),a=d.stackSave();try{let h=d.stackAlloc(8);d._OrtGetLastError(h,h+4);let l=d.HEAP32[h/4],w=d.HEAPU32[h/4+1],g=w?d.UTF8ToString(w):"";throw new Error(`${u} ERROR_CODE: ${l}, ERROR_MESSAGE: ${g}`)}finally{d.stackRestore(a)}};var Mr=u=>{let d=X(),a=0,h=[],l=u||{};try{if(u?.logSeverityLevel===void 0)l.logSeverityLevel=2;else if(typeof u.logSeverityLevel!="number"||!Number.isInteger(u.logSeverityLevel)||u.logSeverityLevel<0||u.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${u.logSeverityLevel}`);if(u?.logVerbosityLevel===void 0)l.logVerbosityLevel=0;else if(typeof u.logVerbosityLevel!="number"||!Number.isInteger(u.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${u.logVerbosityLevel}`);u?.terminate===void 0&&(l.terminate=!1);let w=0;return u?.tag!==void 0&&(w=Q(u.tag,h)),a=d._OrtCreateRunOptions(l.logSeverityLevel,l.logVerbosityLevel,!!l.terminate,w),a===0&&V("Can\'t create run options."),u?.extra!==void 0&&rt(u.extra,"",new WeakSet,(g,i)=>{let A=Q(g,h),D=Q(i,h);d._OrtAddRunConfigEntry(a,A,D)!==0&&V(`Can\'t set a run config entry: ${g} - ${i}.`)}),[a,h]}catch(w){throw a!==0&&d._OrtReleaseRunOptions(a),h.forEach(g=>d._free(g)),w}};var fn=u=>{switch(u){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${u}`)}},ln=u=>{switch(u){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${u}`)}},cn=u=>{u.extra||(u.extra={}),u.extra.session||(u.extra.session={});let d=u.extra.session;d.use_ort_model_bytes_directly||(d.use_ort_model_bytes_directly="1"),u.executionProviders&&u.executionProviders.some(a=>(typeof a=="string"?a:a.name)==="webgpu")&&(u.enableMemPattern=!1)},dn=(u,d,a)=>{for(let h of d){let l=typeof h=="string"?h:h.name;switch(l){case"webnn":if(l="WEBNN",typeof h!="string"){let g=h;if(g?.deviceType){let i=Q("deviceType",a),A=Q(g.deviceType,a);X()._OrtAddSessionConfigEntry(u,i,A)!==0&&V(`Can\'t set a session config entry: \'deviceType\' - ${g.deviceType}.`)}if(g?.numThreads){let i=g.numThreads;(typeof i!="number"||!Number.isInteger(i)||i<0)&&(i=0);let A=Q("numThreads",a),D=Q(i.toString(),a);X()._OrtAddSessionConfigEntry(u,A,D)!==0&&V(`Can\'t set a session config entry: \'numThreads\' - ${g.numThreads}.`)}if(g?.powerPreference){let i=Q("powerPreference",a),A=Q(g.powerPreference,a);X()._OrtAddSessionConfigEntry(u,i,A)!==0&&V(`Can\'t set a session config entry: \'powerPreference\' - ${g.powerPreference}.`)}}break;case"webgpu":if(l="JS",typeof h!="string"){let g=h;if(g?.preferredLayout){if(g.preferredLayout!=="NCHW"&&g.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${g.preferredLayout}`);let i=Q("preferredLayout",a),A=Q(g.preferredLayout,a);X()._OrtAddSessionConfigEntry(u,i,A)!==0&&V(`Can\'t set a session config entry: \'preferredLayout\' - ${g.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let w=Q(l,a);X()._OrtAppendExecutionProvider(u,w)!==0&&V(`Can\'t append execution provider: ${l}.`)}},Cr=u=>{let d=X(),a=0,h=[],l=u||{};cn(l);try{let w=fn(l.graphOptimizationLevel??"all"),g=ln(l.executionMode??"sequential"),i=typeof l.logId=="string"?Q(l.logId,h):0,A=l.logSeverityLevel??2;if(!Number.isInteger(A)||A<0||A>4)throw new Error(`log serverity level is not valid: ${A}`);let D=l.logVerbosityLevel??0;if(!Number.isInteger(D)||D<0||D>4)throw new Error(`log verbosity level is not valid: ${D}`);let I=typeof l.optimizedModelFilePath=="string"?Q(l.optimizedModelFilePath,h):0;if(a=d._OrtCreateSessionOptions(w,!!l.enableCpuMemArena,!!l.enableMemPattern,g,!!l.enableProfiling,0,i,A,D,I),a===0&&V("Can\'t create session options."),l.executionProviders&&dn(a,l.executionProviders,h),l.freeDimensionOverrides)for(let[B,F]of Object.entries(l.freeDimensionOverrides)){if(typeof B!="string")throw new Error(`free dimension override name must be a string: ${B}`);if(typeof F!="number"||!Number.isInteger(F)||F<0)throw new Error(`free dimension override value must be a non-negative integer: ${F}`);let U=Q(B,h);d._OrtAddFreeDimensionOverride(a,U,F)!==0&&V(`Can\'t set a free dimension override: ${B} - ${F}.`)}return l.extra!==void 0&&rt(l.extra,"",new WeakSet,(B,F)=>{let U=Q(B,h),k=Q(F,h);d._OrtAddSessionConfigEntry(a,U,k)!==0&&V(`Can\'t set a session config entry: ${B} - ${F}.`)}),[a,h]}catch(w){throw a!==0&&d._OrtReleaseSessionOptions(a),h.forEach(g=>d._free(g)),w}};var Rt=u=>{switch(u){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${u}`)}},Dr=u=>{switch(u){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${u}`)}},It=u=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][u],xr=u=>{switch(u){case"float16":return Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${u}`)}},Fr=u=>{switch(u){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${u}`)}},Ur=u=>u==="float32"||u==="int32"||u==="int64"||u==="bool"||u==="float16"||u==="uint32",Pr=u=>{switch(u){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${u}`)}};var Rr=async u=>{if(typeof u=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(u))}catch(d){if(d.code==="ERR_FS_FILE_TOO_LARGE"){let a=(void 0)(u),h=[];for await(let l of a)h.push(l);return new Uint8Array(Buffer.concat(h))}throw d}else{let d=await fetch(u);if(!d.ok)throw new Error(`failed to load external data file: ${u}`);let a=d.headers.get("Content-Length"),h=a?parseInt(a,10):0;if(h<1073741824)return new Uint8Array(await d.arrayBuffer());{if(!d.body)throw new Error(`failed to load external data file: ${u}, no response body.`);let l=d.body.getReader(),w;try{w=new ArrayBuffer(h)}catch(i){if(i instanceof RangeError){let A=Math.ceil(h/65536);w=new WebAssembly.Memory({initial:A,maximum:A}).buffer}else throw i}let g=0;for(;;){let{done:i,value:A}=await l.read();if(i)break;let D=A.byteLength;new Uint8Array(w,g,D).set(A),g+=D}return new Uint8Array(w,0,h)}}else return u instanceof Blob?new Uint8Array(await u.arrayBuffer()):u instanceof Uint8Array?u:new Uint8Array(u)};var pn=(u,d)=>{X()._OrtInit(u,d)!==0&&V("Can\'t initialize onnxruntime.")},Lr=async u=>{pn(u.wasm.numThreads,Fr(u.logLevel))},Br=async(u,d)=>{},nt=new Map,mn=u=>{let d=X(),a=d.stackSave();try{let h=d.stackAlloc(8);return d._OrtGetInputOutputCount(u,h,h+4)!==0&&V("Can\'t get session input/output count."),[d.HEAP32[h/4],d.HEAP32[h/4+1]]}finally{d.stackRestore(a)}},Lt=u=>{let d=X(),a=d._malloc(u.byteLength);if(a===0)throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${u.byteLength}.`);return d.HEAPU8.set(u,a),[a,u.byteLength]},Wr=async(u,d)=>{let a,h,l=X();Array.isArray(u)?[a,h]=u:u.buffer===l.HEAPU8.buffer?[a,h]=[u.byteOffset,u.byteLength]:[a,h]=Lt(u);let w=0,g=0,i=0,A=[],D=[],I=[];try{if([g,A]=Cr(d),d?.externalData&&l.mountExternalData){let x=[];for(let N of d.externalData){let he=typeof N=="string"?N:N.path;x.push(Rr(typeof N=="string"?N:N.data).then(ie=>{l.mountExternalData(he,ie)}))}await Promise.all(x)}w=l._OrtCreateSession(a,h,g),w===0&&V("Can\'t create a session.");let[B,F]=mn(w),U=[],k=[],L=[];for(let x=0;xl._OrtFree(F)),I.forEach(F=>l._OrtFree(F)),i!==0&&l._OrtReleaseBinding(i),w!==0&&l._OrtReleaseSession(w),B}finally{l._free(a),g!==0&&l._OrtReleaseSessionOptions(g),A.forEach(B=>l._free(B)),l.unmountExternalData?.()}},kr=u=>{let d=X(),a=nt.get(u);if(!a)throw new Error(`cannot release session. invalid session id: ${u}`);let[h,l,w,g]=a;g&&d._OrtReleaseBinding(g.handle),d.jsepUnregisterBuffers?.(u),l.forEach(i=>d._OrtFree(i)),w.forEach(i=>d._OrtFree(i)),d._OrtReleaseSession(h),nt.delete(u)},Ir=(u,d,a,h,l)=>{if(!u){d.push(0);return}let w=X(),g=u[0],i=u[1],A=u[3],D,I;if(g==="string"&&A==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(A==="gpu-buffer"){let U=u[2].gpuBuffer,k=It(Rt(g));I=i.reduce((L,_)=>L*_,1)*k,D=w.jsepRegisterBuffer(h,l,U,I)}else{let U=u[2];if(Array.isArray(U)){I=4*U.length,D=w._malloc(I),a.push(D);let k=D/4;for(let L=0;Lw.HEAP32[U++]=L);let k=w._OrtCreateTensor(Rt(g),D,I,F,i.length,Pr(A));k===0&&V(`Can\'t create tensor for input/output. session=${h}, index=${l}.`),d.push(k)}finally{w.stackRestore(B)}},Nr=async(u,d,a,h,l,w)=>{let g=X(),i=nt.get(u);if(!i)throw new Error(`cannot run inference. invalid session id: ${u}`);let[A,D,I,B]=i,F=d.length,U=h.length,k=0,L=[],_=[],x=[],N=[],he=g.stackSave(),ie=g.stackAlloc(F*4),ae=g.stackAlloc(F*4),E=g.stackAlloc(U*4),Y=g.stackAlloc(U*4);try{[k,L]=Mr(w);for(let P=0;Pre*Z,1);J=Dr(Me);let ve=B?.outputPreferredLocations[h[P]];if(J==="string"){if(ve==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let re=[],Z=fe/4;for(let Ce=0;Ce0){let re=g.jsepGetBuffer(fe),Z=It(Me);if(Z===void 0||!Ur(J))throw new Error(`Unsupported data type: ${J}`);ye=!0,ce.push([J,pe,{gpuBuffer:re,download:g.jsepCreateDownloader(re,Oe*Z,J),dispose:()=>{g._OrtReleaseTensor(te)}},"gpu-buffer"])}else{let re=xr(J),Z=new re(Oe);new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength).set(g.HEAPU8.subarray(fe,fe+Z.byteLength)),ce.push([J,pe,Z,"cpu"])}}finally{g.stackRestore(de),J==="string"&&fe&&g._free(fe),ye||g._OrtReleaseTensor(te)}}return B&&g._OrtClearBoundOutputs(B.handle),ce}finally{g.stackRestore(he),_.forEach(ue=>g._OrtReleaseTensor(ue)),x.forEach(ue=>g._OrtReleaseTensor(ue)),N.forEach(ue=>g._free(ue)),k!==0&&g._OrtReleaseRunOptions(k),L.forEach(ue=>g._free(ue))}},Hr=u=>{let d=X(),a=nt.get(u);if(!a)throw new Error("invalid session id");let h=a[0],l=d._OrtEndProfiling(h);l===0&&V("Can\'t get an profile file name."),d._OrtFree(l)},$r=u=>{let d=[];for(let a of u){let h=a[2];!Array.isArray(h)&&"buffer"in h&&d.push(h.buffer)}return d};self.onmessage=u=>{let{type:d,in:a}=u.data;try{switch(d){case"init-wasm":Ar(a.wasm).then(()=>{Lr(a).then(()=>{postMessage({type:d})},h=>{postMessage({type:d,err:h})})},h=>{postMessage({type:d,err:h})});break;case"init-ep":{let{epName:h,env:l}=a;Br(l,h).then(()=>{postMessage({type:d})},w=>{postMessage({type:d,err:w})});break}case"copy-from":{let{buffer:h}=a,l=Lt(h);postMessage({type:d,out:l});break}case"create":{let{model:h,options:l}=a;Wr(h,l).then(w=>{postMessage({type:d,out:w})},w=>{postMessage({type:d,err:w})});break}case"release":kr(a),postMessage({type:d});break;case"run":{let{sessionId:h,inputIndices:l,inputs:w,outputIndices:g,options:i}=a;Nr(h,l,w,g,new Array(g.length).fill(null),i).then(A=>{A.some(D=>D[3]!=="cpu")?postMessage({type:d,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:d,out:A},$r(A))},A=>{postMessage({type:d,err:A})});break}case"end-profiling":Hr(a),postMessage({type:d});break;default:}}catch(h){postMessage({type:d,err:h})}};})();\n'}),xr,bt,Tn,Fo,$o,da,ha,Vr,Wr,gg,Lo,nd,od,id,ad,sd,ud,ld,ma=L(()=>{vt(),td(),zr(),xr=()=>!!Z.wasm.proxy&&typeof document<"u",Tn=!1,Fo=!1,$o=!1,ha=new Map,Vr=(t,e)=>{let o=ha.get(t);o?o.push(e):ha.set(t,[e])},Wr=()=>{if(Tn||!Fo||$o||!bt)throw new Error("worker not ready")},gg=t=>{switch(t.data.type){case"init-wasm":Tn=!1,t.data.err?($o=!0,da[1](t.data.err)):(Fo=!0,da[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=ha.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}}},Lo=typeof document<"u"?document?.currentScript?.src:void 0,nd=async()=>{if(!Fo){if(Tn)throw new Error("multiple calls to 'initWasm()' detected.");if($o)throw new Error("previous call to 'initWasm()' failed.");if(Tn=!0,xr())return Z.wasm.wasmPaths===void 0&&Lo&&Lo.indexOf("blob:")!==0&&(Z.wasm.wasmPaths=Lo.substr(0,+Lo.lastIndexOf("/")+1)),new Promise((t,e)=>{bt?.terminate();let o=URL.createObjectURL(new Blob([rd()],{type:"text/javascript"}));bt=new Worker(o,{name:"ort-wasm-proxy-worker"}),bt.onerror=u=>e(u),bt.onmessage=gg,URL.revokeObjectURL(o),da=[t,e];let i={type:"init-wasm",in:Z};bt.postMessage(i)});try{await Rp(Z.wasm),await Yp(Z),Fo=!0}catch(t){throw $o=!0,t}finally{Tn=!1}}},od=async t=>{if(xr())return Wr(),new Promise((e,o)=>{Vr("init-ep",[e,o]);let i={type:"init-ep",in:{epName:t,env:Z}};bt.postMessage(i)});await Xp(Z,t)},id=async t=>xr()?(Wr(),new Promise((e,o)=>{Vr("copy-from",[e,o]);let i={type:"copy-from",in:{buffer:t}};bt.postMessage(i,[t.buffer])})):pa(t),ad=async(t,e)=>{if(xr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Wr(),new Promise((o,i)=>{Vr("create",[o,i]);let u={type:"create",in:{model:t,options:e}},n=[];t instanceof Uint8Array&&n.push(t.buffer),bt.postMessage(u,n)})}else return Kp(t,e)},sd=async t=>{if(xr())return Wr(),new Promise((e,o)=>{Vr("release",[e,o]);let i={type:"release",in:t};bt.postMessage(i)});Jp(t)},ud=async(t,e,o,i,u,n)=>{if(xr()){if(o.some(s=>s[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(u.some(s=>s))throw new Error("pre-allocated output tensor is not supported for proxy.");return Wr(),new Promise((s,c)=>{Vr("run",[s,c]);let d=o,r={type:"run",in:{sessionId:t,inputIndices:e,inputs:d,outputIndices:i,options:n}};bt.postMessage(r,ed(d))})}else return Zp(t,e,o,i,u,n)},ld=async t=>{if(xr())return Wr(),new Promise((e,o)=>{Vr("end-profiling",[e,o]);let i={type:"end-profiling",in:t};bt.postMessage(i)});Qp(t)}}),fd,yg,Co,cd=L(()=>{vt(),ma(),fa(),ca(),fd=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},yg=t=>{switch(t[3]){case"cpu":return new Re(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Do(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:o,download:i,dispose:u}=t[2];return Re.fromGpuBuffer(o,{dataType:e,dims:t[1],download:i,dispose:u})}default:throw new Error(`invalid data location: ${t[3]}`)}},Co=class{async fetchModelAndCopyToWasmMemory(t){return id(await gn(t))}async loadModel(t,e){ar();let o;typeof t=="string"?typeof process<"u"&&process.versions&&process.versions.node?o=await gn(t):o=await this.fetchModelAndCopyToWasmMemory(t):o=t,[this.sessionId,this.inputNames,this.outputNames]=await ad(o,e),sr()}async dispose(){return sd(this.sessionId)}async run(t,e,o){ar();let i=[],u=[];Object.entries(t).forEach(l=>{let h=l[0],f=l[1],m=this.inputNames.indexOf(h);if(m===-1)throw new Error(`invalid input '${h}'`);i.push(f),u.push(m)});let n=[],s=[];Object.entries(e).forEach(l=>{let h=l[0],f=l[1],m=this.outputNames.indexOf(h);if(m===-1)throw new Error(`invalid output '${h}'`);n.push(f),s.push(m)});let c=i.map((l,h)=>fd(l,()=>`input "${this.inputNames[u[h]]}"`)),d=n.map((l,h)=>l?fd(l,()=>`output "${this.outputNames[s[h]]}"`):null),r=await ud(this.sessionId,u,c,s,d,o),a={};for(let l=0;l{vt(),ma(),cd(),Tg=()=>{if((typeof Z.wasm.initTimeout!="number"||Z.wasm.initTimeout<0)&&(Z.wasm.initTimeout=0),typeof Z.wasm.simd!="boolean"&&(Z.wasm.simd=!0),typeof Z.wasm.proxy!="boolean"&&(Z.wasm.proxy=!1),typeof Z.wasm.trace!="boolean"&&(Z.wasm.trace=!1),typeof Z.wasm.numThreads!="number"||!Number.isInteger(Z.wasm.numThreads)||Z.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(Z.wasm.numThreads=1);let t=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;Z.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},ko=class{async init(t){Tg(),await nd(),await od(t)}async createInferenceSessionHandler(t,e){let o=new Co;return await o.loadModel(t,e),Promise.resolve(o)}}}),dd={};Pr(dd,{wasmBackend:()=>xg});var xg,hd=L(()=>{pd(),xg=new ko});vt();vt();vt();var ys="1.17.1",zO=Yo;{let t=(_p(),rr(wp)).onnxjsBackend;or("webgl",t,-10)}{let t=(hd(),rr(dd)).wasmBackend;or("cpu",t,10),or("wasm",t,10),or("webnn",t,9)}Object.defineProperty(Z.versions,"web",{value:ys,enumerable:!0});/*! Bundled license information: + +long/index.js: + (** + * @license + * Copyright 2009 The Closure Library Authors + * Copyright 2020 Daniel Wirtz / The long.js Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + *) +*/const ONNX_WEB=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return Sd},get TRACE(){return cs},get TRACE_FUNC_BEGIN(){return ar},get TRACE_FUNC_END(){return sr},get Tensor(){return Re},get TrainingSession(){return Pd},default:zO,get env(){return Z},get registerBackend(){return or}},Symbol.toStringTag,{value:"Module"})),tensorToDataURL=(t,e)=>{const o=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);o.width=t.dims[3],o.height=t.dims[2];const i=o.getContext("2d");if(i!=null){let u,n;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(u=t.dims[2],n=t.dims[3]):(u=t.dims[3],n=t.dims[2]);const s=e?.format!==void 0?e.format:"RGB",c=e?.norm;let d,r;c===void 0||c.mean===void 0?d=[255,255,255,255]:typeof c.mean=="number"?d=[c.mean,c.mean,c.mean,c.mean]:(d=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(d[3]=c.mean[3])),c===void 0||c.bias===void 0?r=[0,0,0,0]:typeof c.bias=="number"?r=[c.bias,c.bias,c.bias,c.bias]:(r=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(r[3]=c.bias[3]));const a=n*u;let l=0,h=a,f=a*2,m=-1;s==="RGBA"?(l=0,h=a,f=a*2,m=a*3):s==="RGB"?(l=0,h=a,f=a*2):s==="RBG"&&(l=0,f=a,h=a*2);for(let g=0;g{const o=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let i;if(o!=null){let u,n,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(u=t.dims[2],n=t.dims[1],s=t.dims[3]):(u=t.dims[3],n=t.dims[2],s=t.dims[1]);const c=e!==void 0&&e.format!==void 0?e.format:"RGB",d=e?.norm;let r,a;d===void 0||d.mean===void 0?r=[255,255,255,255]:typeof d.mean=="number"?r=[d.mean,d.mean,d.mean,d.mean]:(r=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(r[3]=d.mean[3])),d===void 0||d.bias===void 0?a=[0,0,0,0]:typeof d.bias=="number"?a=[d.bias,d.bias,d.bias,d.bias]:(a=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(a[3]=d.bias[3]));const l=n*u;if(e!==void 0&&(e.format!==void 0&&s===4&&e.format!=="RGBA"||s===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const h=4;let f=0,m=1,g=2,b=3,v=0,T=l,E=l*2,M=-1;c==="RGBA"?(v=0,T=l,E=l*2,M=l*3):c==="RGB"?(v=0,T=l,E=l*2):c==="RBG"&&(v=0,E=l,T=l*2),i=o.createImageData(u,n);for(let F=0;F{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:o,width:i}=e,u=e.norm??{mean:255,bias:0};let n,s;typeof u.mean=="number"?n=[u.mean,u.mean,u.mean,u.mean]:n=[u.mean[0],u.mean[1],u.mean[2],u.mean[3]??255],typeof u.bias=="number"?s=[u.bias,u.bias,u.bias,u.bias]:s=[u.bias[0],u.bias[1],u.bias[2],u.bias[3]??0];const c=e.format!==void 0?e.format:"RGBA",d=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",r=o*i,a=d==="RGBA"?new Float32Array(r*4):new Float32Array(r*3);let l=4,h=0,f=1,m=2,g=3,b=0,v=r,T=r*2,E=-1;c==="RGB"&&(l=3,h=0,f=1,m=2,g=-1),d==="RGBA"?E=r*3:d==="RBG"?(b=0,T=r,v=r*2):d==="BGR"&&(T=0,v=r,b=r*2);for(let F=0;F{const o=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,i=typeof ImageData<"u"&&t instanceof ImageData,u=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,n=typeof t=="string";let s,c=e??{};const d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},r=a=>a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas?a.getContext("2d"):null;if(o){const a=d();a.width=t.width,a.height=t.height;const l=r(a);if(l!=null){let h=t.height,f=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(h=e.resizedHeight,f=e.resizedWidth),e!==void 0){if(c=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=h,c.width=f}else c.tensorFormat="RGBA",c.height=h,c.width=f;l.drawImage(t,0,0),s=l.getImageData(0,0,f,h).data}else throw new Error("Can not access image data")}else if(i){let a,l;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(a=e.resizedHeight,l=e.resizedWidth):(a=t.height,l=t.width),e!==void 0&&(c=e),c.format="RGBA",c.height=a,c.width=l,e!==void 0){const h=d();h.width=l,h.height=a;const f=r(h);if(f!=null)f.putImageData(t,0,0),s=f.getImageData(0,0,l,a).data;else throw new Error("Can not access image data")}else s=t.data}else if(u){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");const a=d();a.width=t.width,a.height=t.height;const l=r(a);if(l!=null){const h=t.height,f=t.width;return l.drawImage(t,0,0,f,h),s=l.getImageData(0,0,f,h).data,c.height=h,c.width=f,bufferToTensor(s,c)}else throw new Error("Can not access image data")}else{if(n)return new Promise((a,l)=>{const h=d(),f=r(h);if(!t||!f)return l();const m=new Image;m.crossOrigin="Anonymous",m.src=t,m.onload=()=>{h.width=m.width,h.height=m.height,f.drawImage(m,0,0,h.width,h.height);const g=f.getImageData(0,0,h.width,h.height);c.height=h.height,c.width=h.width,a(bufferToTensor(g.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return bufferToTensor(s,c);throw new Error("Input data provided is not supported - aborted tensor creation")},tensorFromTexture=(t,e)=>{const{width:o,height:i,download:u,dispose:n}=e,s=[1,i,o,4];return new Tensor$2({location:"texture",type:"float32",texture:t,dims:s,download:u,dispose:n})},tensorFromGpuBuffer=(t,e)=>{const{dataType:o,dims:i,download:u,dispose:n}=e;return new Tensor$2({location:"gpu-buffer",type:o??"float32",gpuBuffer:t,dims:i,download:u,dispose:n})},tensorFromPinnedBuffer=(t,e,o)=>new Tensor$2({location:"cpu-pinned",type:t,data:e,dims:o??[e.length]}),NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let isBigIntChecked=!1;const checkBigInt=()=>{if(!isBigIntChecked){isBigIntChecked=!0;const t=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",e=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";t&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64",BigInt64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array,"int64")),e&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64",BigUint64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array,"uint64"))}},calculateSize=t=>{let e=1;for(let o=0;o{switch(t.location){case"cpu":return new Tensor$2(t.type,t.data,e);case"cpu-pinned":return new Tensor$2({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Tensor$2({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Tensor$2({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};let Tensor$2=class{constructor(e,o,i){checkBigInt();let u,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,u=e.type,n=e.dims,e.location){case"cpu-pinned":{const c=NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(u);if(!c)throw new TypeError(`unsupported type "${u}" to create tensor from pinned buffer`);if(!(e.data instanceof c))throw new TypeError(`buffer should be of type ${c.name}`);this.cpuData=e.data;break}case"texture":{if(u!=="float32")throw new TypeError(`unsupported type "${u}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(u!=="float32"&&u!=="float16"&&u!=="int32"&&u!=="int64"&&u!=="uint32"&&u!=="bool")throw new TypeError(`unsupported type "${u}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let c,d;if(typeof e=="string")if(u=e,d=i,e==="string"){if(!Array.isArray(o))throw new TypeError("A string tensor's data must be a string array.");c=o}else{const r=NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(e);if(r===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(o)){if(e==="float16")throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");e==="uint64"||e==="int64"?c=r.from(o,BigInt):c=r.from(o)}else if(o instanceof r)c=o;else throw new TypeError(`A ${u} tensor's data must be type of ${r}`)}else if(d=o,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const r=typeof e[0];if(r==="string")u="string",c=e;else if(r==="boolean")u="bool",c=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${r}.`)}else{const r=NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(e.constructor);if(r===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);u=r,c=e}if(d===void 0)d=[c.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");n=d,this.cpuData=c,this.dataLocation="cpu"}const s=calculateSize(n);if(this.cpuData&&s!==this.cpuData.length)throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=u,this.dims=n,this.size=s}static async fromImage(e,o){return tensorFromImage(e,o)}static fromTexture(e,o){return tensorFromTexture(e,o)}static fromGpuBuffer(e,o){return tensorFromGpuBuffer(e,o)}static fromPinnedBuffer(e,o,i){return tensorFromPinnedBuffer(e,o,i)}toDataURL(e){return tensorToDataURL(this,e)}toImageData(e){return tensorToImageData(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const o=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=o,e&&this.disposer&&(this.disposer(),this.disposer=void 0),o}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return tensorReshape(this,e)}};const Tensor$1=Tensor$2;let ONNX;const WEBGPU_AVAILABLE=typeof navigator<"u"&&"gpu"in navigator,USE_ONNXRUNTIME_NODE=typeof process<"u"&&process?.release?.name==="node",ONNX_MODULES=new Map;USE_ONNXRUNTIME_NODE?(ONNX=sharp??ONNX_NODE,ONNX_MODULES.set("node",ONNX)):(ONNX=zO??ONNX_WEB,ONNX_MODULES.set("web",ONNX));async function createInferenceSession(t,e){let o,i;if(USE_ONNXRUNTIME_NODE){const s=ONNX_MODULES.get("node");i=s.InferenceSession,o=["cpu"],Object.assign(s.env,env.backends.onnx)}else if(WEBGPU_AVAILABLE&&env.experimental.useWebGPU){let s=ONNX_MODULES.get("webgpu");s===void 0&&(s=await __vitePreload(()=>import("./ort.webgpu.min-BaaO-cT5.js"),__vite__mapDeps([])),ONNX_MODULES.set("webgpu",s)),i=s.InferenceSession,o=["webgpu","wasm"],Object.assign(s.env,env.backends.onnx)}else{const s=ONNX_MODULES.get("web");i=s.InferenceSession,o=["wasm"],Object.assign(s.env,env.backends.onnx)}const u={executionProviders:o,...e};return await i.create(t,u)}function isONNXTensor(t){for(const e of ONNX_MODULES.values())if(t instanceof e.Tensor)return!0;return!1}const ONNX_ENV=ONNX?.env;ONNX_ENV&&ONNX_ENV.wasm&&(ONNX_ENV.wasm.wasmPaths=RUNNING_LOCALLY?sharp.join(env.__dirname,"/dist/"):`https://cdn.jsdelivr.net/npm/@xenova/transformers@${env.version}/dist/`,typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(ONNX_ENV.wasm.simd=!1),ONNX_ENV.wasm.proxy=!0);function isONNXProxy(){return ONNX_ENV.wasm.proxy}env.backends.onnx=ONNX_ENV;const DataTypeMap=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class Tensor{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}ort_tensor;constructor(...e){return isONNXTensor(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new Tensor$1(e[0],e[1],e[2]),new Proxy(this,{get:(o,i)=>{if(typeof i=="string"){let u=Number(i);if(Number.isInteger(u))return o._getitem(u)}return o[i]},set:(o,i,u)=>o[i]=u})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...o]=this.dims;if(o.length>0){const i=o.reduce((u,n)=>u*n);for(let u=0;u0){const u=i.reduce((n,s)=>n*s);return this._subarray(e,u,i)}else return new Tensor(this.type,[this.data[e]],i)}indexOf(e){for(let o=0;or[1])throw new Error(`Invalid slice: ${r}`);let a=[Math.max(r[0],0),Math.min(r[1],this.dims[d])];i.push(a),o.push(a[1]-a[0])}else throw new Error(`Invalid slice: ${r}`)}let u=i.map(([d,r])=>r-d),n=u.reduce((d,r)=>d*r),s=new this.data.constructor(n);const c=this.stride();for(let d=0;d=0;--a){const h=u[a];r+=(l%h+i[a][0])*c[a],l=Math.floor(l/h)}s[d]=this.data[r]}return new Tensor(this.type,s,o)}transpose(...e){return transpose(this,e)}sum(e=null,o=!1){return this.norm(1,e,o)}norm(e="fro",o=null,i=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);if(o===null){let s=this.data.reduce((c,d)=>c+d**e,0)**(1/e);return new Tensor(this.type,[s],[])}o=safeIndex(o,this.dims.length);const u=this.dims.slice();u[o]=1;const n=new this.data.constructor(this.data.length/this.dims[o]);for(let s=0;s=0;--d){const l=this.dims[d];if(d!==o){const h=r%l;c+=h*a,a*=u[d]}r=Math.floor(r/l)}n[c]+=this.data[s]**e}if(e!==1)for(let s=0;s=0;--s){const r=this.dims[s];if(s!==o){const a=c%r;n+=a*d,d*=this.dims[s]}c=Math.floor(c/r)}this.data[u]/=i.data[n]}return this}normalize(e=2,o=1){return this.clone().normalize_(e,o)}stride(){return dimsToStride(this.dims)}squeeze(e=null){return new Tensor(this.type,this.data,calc_squeeze_dims(this.dims,e))}squeeze_(e=null){return this.dims=calc_squeeze_dims(this.dims,e),this}unsqueeze(e=null){return new Tensor(this.type,this.data,calc_unsqueeze_dims(this.dims,e))}unsqueeze_(e=null){return this.dims=calc_unsqueeze_dims(this.dims,e),this}flatten_(e=0,o=-1){o=(o+this.dims.length)%this.dims.length;let i=this.dims.slice(0,e),u=this.dims.slice(e,o+1),n=this.dims.slice(o+1);return this.dims=[...i,u.reduce((s,c)=>s*c,1),...n],this}flatten(e=0,o=-1){return this.clone().flatten_(e,o)}view(...e){let o=-1;for(let i=0;is!==o?u*n:u,1);e[o]=this.data.length/i}return new Tensor(this.type,this.data,e)}neg_(){for(let e=0;en*s);if(o!==i)throw Error(`cannot reshape array of size ${o} into shape (${e})`);let u=t;for(let n=e.length-1;n>=0;n--)u=u.reduce((s,c)=>{let d=s[s.length-1];return d.lengtho!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((o,i)=>o!==1||!e.includes(i))),t}function calc_unsqueeze_dims(t,e){return e=safeIndex(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function safeIndex(t,e,o=null){if(t<-e||t>=e)throw new Error(`IndexError: index ${t} is out of bounds for dimension${o===null?"":" "+o} with size ${e}`);return t<0&&(t=(t%e+e)%e),t}function cat(t,e=0){e=safeIndex(e,t[0].dims.length);const o=t[0].dims.slice();o[e]=t.reduce((s,c)=>s+c.dims[e],0);const i=o.reduce((s,c)=>s*c,1),u=new t[0].data.constructor(i),n=t[0].type;if(e===0){let s=0;for(let c of t)u.set(c.data,s),s+=c.data.length}else{let s=0;for(let c=0;c=0;--l){const m=d.dims[l];let g=h%m;l===e&&(g+=s),a+=g*f,f*=o[l],h=Math.floor(h/m)}u[a]=d.data[r]}s+=d.dims[e]}}return new Tensor(n,u,o)}function stack(t,e=0){return cat(t.map(o=>o.unsqueeze(e)),e)}function std_mean(t,e=null,o=1,i=!1){if(e===null){const r=t.data.reduce((f,m)=>f+m,0)/t.data.length,a=Math.sqrt(t.data.reduce((f,m)=>f+(m-r)**2,0)/(t.data.length-o)),l=new Tensor(t.type,[r],[]);return[new Tensor(t.type,[a],[]),l]}e=safeIndex(e,t.dims.length);const u=mean(t,e,i),n=t.dims.slice();n[e]=1;const s=new t.data.constructor(t.data.length/t.dims[e]);for(let d=0;d=0;--a){const f=t.dims[a];if(a!==e){const m=l%f;r+=m*h,h*=n[a]}l=Math.floor(l/f)}s[r]+=(t.data[d]-u.data[r])**2}for(let d=0;ds+c,0);return new Tensor(t.type,[n/t.data.length],[])}e=safeIndex(e,t.dims.length);const i=t.dims.slice();i[e]=1;const u=new t.data.constructor(t.data.length/t.dims[e]);for(let n=0;n=0;--c){const a=t.dims[c];if(c!==e){const l=d%a;s+=l*r,r*=i[c]}d=Math.floor(d/a)}u[s]+=t.data[n]}if(t.dims[e]!==1)for(let n=0;n0||c>0;)switch(d.push(s-1),r.push(c-1),n[s][c].item()){case 0:--s,--c;break;case 1:--s;break;case 2:--c;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${s}, ${c}]. Please file a bug report.`)}return d.reverse(),r.reverse(),[d,r]}function dimsToStride(t){const e=new Array(t.length);for(let o=t.length-1,i=1;o>=0;--o)e[o]=i,i*=t[o];return e}function ones(t){const e=t.reduce((o,i)=>o*i,1);return new Tensor("int64",new BigInt64Array(e).fill(1n),t)}function ones_like(t){return ones(t.dims)}var TOKEN_TYPES=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"});Object.freeze({set:TOKEN_TYPES.Set,for:TOKEN_TYPES.For,in:TOKEN_TYPES.In,is:TOKEN_TYPES.Is,if:TOKEN_TYPES.If,else:TOKEN_TYPES.Else,endif:TOKEN_TYPES.EndIf,elif:TOKEN_TYPES.ElseIf,endfor:TOKEN_TYPES.EndFor,and:TOKEN_TYPES.And,or:TOKEN_TYPES.Or,not:TOKEN_TYPES.Not,"not in":TOKEN_TYPES.NotIn,true:TOKEN_TYPES.BooleanLiteral,false:TOKEN_TYPES.BooleanLiteral});TOKEN_TYPES.OpenStatement,TOKEN_TYPES.CloseStatement,TOKEN_TYPES.OpenExpression,TOKEN_TYPES.CloseExpression,TOKEN_TYPES.OpenParen,TOKEN_TYPES.CloseParen,TOKEN_TYPES.OpenCurlyBracket,TOKEN_TYPES.CloseCurlyBracket,TOKEN_TYPES.OpenSquareBracket,TOKEN_TYPES.CloseSquareBracket,TOKEN_TYPES.Comma,TOKEN_TYPES.Dot,TOKEN_TYPES.Colon,TOKEN_TYPES.Pipe,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.AdditiveBinaryOperator,TOKEN_TYPES.AdditiveBinaryOperator,TOKEN_TYPES.MultiplicativeBinaryOperator,TOKEN_TYPES.MultiplicativeBinaryOperator,TOKEN_TYPES.MultiplicativeBinaryOperator,TOKEN_TYPES.Equals;const BYTES_TO_UNICODE=(()=>{const t=[...Array.from({length:94},(u,n)=>n+33),...Array.from({length:12},(u,n)=>n+161),...Array.from({length:82},(u,n)=>n+174)],e=t.slice();let o=0;for(let u=0;u<256;++u)t.includes(u)||(t.push(u),e.push(256+o),o+=1);const i=e.map(u=>String.fromCharCode(u));return Object.fromEntries(t.map((u,n)=>[u,i[n]]))})();reverseDictionary(BYTES_TO_UNICODE);const WHISPER_LANGUAGES=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]];new Map(WHISPER_LANGUAGES);async function loadConfig(t,e){return await getModelJSON(t,"config.json",!0,e)}class PretrainedConfig{constructor(e){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,e)}static async from_pretrained(e,{progress_callback:o=null,config:i=null,cache_dir:u=null,local_files_only:n=!1,revision:s="main"}={}){let c=i??await loadConfig(e,{progress_callback:o,config:i,cache_dir:u,local_files_only:n,revision:s});return new this(c)}}class AutoConfig{static async from_pretrained(...e){return PretrainedConfig.from_pretrained(...e)}}class LogitsProcessorList extends Callable{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,o){for(let i of o)this.processors.forEach(u=>u(e,i))}[Symbol.iterator](){return this.processors.values()}}class LogitsProcessor extends Callable{_call(e,o){throw Error("`_call` should be implemented in a subclass")}}class ForceTokensLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.force_token_map=Object.fromEntries(e??[])}_call(e,o){let i=this.force_token_map[e.length];return exists(i)&&(o.data.fill(-1/0),o.data[i]=0),o}}class ForcedBOSTokenLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.bos_token_id=e}_call(e,o){return e.length===1&&(o.data.fill(-1/0),o.data[this.bos_token_id]=0),o}}class ForcedEOSTokenLogitsProcessor extends LogitsProcessor{constructor(e,o){super(),this.max_length=e,this.forced_eos_token_id=o}_call(e,o){}}class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor{constructor(e,o){super(),this.begin_suppress_tokens=e,this.begin_index=o}_call(e,o){if(e.length===this.begin_index)for(let i of this.begin_suppress_tokens)o.data[i]=-1/0;return o}}class WhisperTimeStampLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.eos_token_id=e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=(e.forced_decoder_ids||[]).length+2,e.forced_decoder_ids.slice(-1)[0][1]===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,o){const i=o.data;if(i[this.no_timestamps_token_id]=-1/0,e.length===this.begin_index-1)return i.fill(-1/0),i[this.timestamp_begin]=0,o;const u=e.slice(this.begin_index),n=u.length>=1&&u[u.length-1]>=this.timestamp_begin,s=u.length<2||u[u.length-2]>=this.timestamp_begin;if(n&&(s?i.subarray(this.timestamp_begin).fill(-1/0):i.subarray(0,this.eos_token_id).fill(-1/0)),e.length===this.begin_index&&this.max_initial_timestamp_index!==null){const a=this.timestamp_begin+this.max_initial_timestamp_index;i.subarray(a+1).fill(-1/0)}const c=log_softmax(i),d=Math.log(c.subarray(this.timestamp_begin).map(Math.exp).reduce((a,l)=>a+l)),r=max(c.subarray(0,this.timestamp_begin))[0];return d>r&&i.subarray(0,this.timestamp_begin).fill(-1/0),o}}class NoRepeatNGramLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const o=e.length,i=[];for(let n=0;n0&&(u=u.map(n=>n/this.generation_config.temperature)),u}randomSelect(e){let o=e.reduce((u,n)=>u+n,0),i=Math.random()*o;for(let u=0;u1)return new BeamSearchSampler(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new GreedySampler(e)}}class GreedySampler extends Sampler{sample(e,o=-1){let i=this.getLogits(e,o);return[[max(i)[1],0]]}}class MultinomialSampler extends Sampler{sample(e,o=-1){let i=e.dims.at(-1);this.generation_config.top_k>0&&(i=Math.min(this.generation_config.top_k,i));const u=this.getLogits(e,o),n=getTopItems(u,i),s=softmax(n.map(c=>c[1]));return Array.from({length:this.generation_config.num_beams},()=>{const c=this.randomSelect(s);return[n[c][0],Math.log(s[c])]})}}class BeamSearchSampler extends Sampler{sample(e,o=-1){let i=e.dims.at(-1);this.generation_config.top_k>0&&(i=Math.min(this.generation_config.top_k,i));const u=this.getLogits(e,o),n=getTopItems(u,i),s=softmax(n.map(c=>c[1]));return Array.from({length:this.generation_config.num_beams},(c,d)=>[n[d][0],Math.log(s[d])])}}const MODEL_TYPES={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5},MODEL_TYPE_MAPPING=new Map,MODEL_NAME_TO_CLASS_MAPPING=new Map,MODEL_CLASS_TO_NAME_MAPPING=new Map;async function constructSession(t,e,o){const i=`onnx/${e}${o.quantized?"_quantized":""}.onnx`,u=await getModelFile(t,i,!0,o),n=o.session_options??{};if(n.externalData!==void 0)for(let s=0;s0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${i.join(", ")}.`);const u=Object.keys(e).length,n=t.inputNames.length;if(u>n){let s=Object.keys(e).filter(c=>!t.inputNames.includes(c));console.warn(`WARNING: Too many inputs were provided (${u} > ${n}). The following inputs will be ignored: "${s.join(", ")}".`)}return o}async function sessionRun(t,e){const o=validateInputs(t,e);try{const i=Object.fromEntries(Object.entries(o).map(([n,s])=>[n,s.ort_tensor]));let u=await t.run(i);u=replaceTensors(u);for(const[n,s]of Object.entries(o))n.startsWith("past_key_values")&&s.dispose();return u}catch(i){throw console.error(`An error occurred during model execution: "${i}".`),console.error("Inputs given to model:",o),i}}function replaceTensors(t){for(let e in t)isONNXTensor(t[e])?t[e]=new Tensor(t[e]):typeof t[e]=="object"&&replaceTensors(t[e]);return t}function toI64Tensor(t){if(t instanceof Tensor)return t;if(t.length===0)throw Error("items must be non-empty");if(Array.isArray(t[0])){if(t.some(e=>e.length!==t[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new Tensor("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new Tensor("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function prepareAttentionMask(t,e){let o=t.config.pad_token_id??null,i=t.config.eos_token_id??null;isIntegralNumber(i)&&(i=[i]);let u=e.indexOf(o)!==-1,n=i===null||!i.includes(o);if(u&&n){let s=BigInt64Array.from(e.data.map(c=>c!=o));return new Tensor("int64",s,e.dims)}else return ones_like(e)}function preparePositionIds(t,e,o){if(!t.inputNames.includes("position_ids"))return;const i=new BigInt64Array(e.attention_mask.data.length);for(let u=0;u0&&u.push(new NoRepeatNGramLogitsProcessor(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&u.push(new NoBadWordsLogitsProcessor(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&u.push(new MinLengthLogitsProcessor(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&u.push(new MinNewTokensLengthLogitsProcessor(o,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&u.push(new ForcedBOSTokenLogitsProcessor(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&u.push(new ForcedEOSTokenLogitsProcessor(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){let n=o>1||e.forced_bos_token_id===null?o:o+1;e.forced_decoder_ids!==null&&(n+=e.forced_decoder_ids[e.forced_decoder_ids.length-1][0]),u.push(new SuppressTokensAtBeginLogitsProcessor(e.begin_suppress_tokens,n))}return e.forced_decoder_ids!==null&&u.push(new ForceTokensLogitsProcessor(e.forced_decoder_ids)),i!==null&&u.extend(i),u}_get_generation_config(e){let o=new GenerationConfig(this.config);return"generation_config"in this&&Object.assign(o,this.generation_config),e!==null&&Object.assign(o,e),o}async generate(e,o=null,i=null,{inputs_attention_mask:u=null}={}){if(!this.can_generate){let b=`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 v=this.config.model_type,T=MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(v)??MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(v)??MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(v)??MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(v);throw T&&(b+=` Please use the following class instead: '${T[0]}'`),Error(b)}if(!(e instanceof Tensor)&&!isTypedArray(e)&&!Array.isArray(e))throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${e.constructor.name}".`);let n;if(this.config.is_encoder_decoder)n=0;else if(n=e instanceof Tensor?e.dims.at(-1):e.length,n===0)throw Error("Must supply a non-empty array of input token ids.");o=this._get_generation_config(o),i=i??new LogitsProcessorList,i=this._get_logits_processor(o,n,i);let s=o.eos_token_id;s!==null&&!Array.isArray(s)&&(s=[s]);let c=1;const d=c+(o.max_new_tokens??1/0),r=Number.isInteger(o.max_length)&&(o.max_new_tokens??null)===null;let a=Sampler.getSampler(o),l=this.getStartBeams(e,o,c,u);for(;l.some(g=>!g.done)&&c=o.max_length){b.done=!0,g.push(b);continue}let v=await this.runBeam(b);o.output_attentions&&this.addAttentionsToBeam(b,v),o.output_scores;let T=v.logits.slice(null,-1,null);i(b.output_token_ids,T);let E=a(T);for(let[M,F]of E){let Y={...b};this.updateBeam(Y,M),Y.score+=F,s&&s.includes(M)&&(Y.done=!0),g.push(Y)}}++c,g=this.groupBeams(g).map(b=>b.sort((v,T)=>T.score-v.score).slice(0,o.num_beams)),l=g.flat(),o.callback_function&&o.callback_function(l)}const h=this.groupBeams(l),f=g=>h.map(b=>o.num_return_sequences>1?b.slice(0,o.num_return_sequences).map(v=>v[g]):[b[0][g]]).flat(),m=f("output_token_ids");if(o.return_dict_in_generate){const g=f("decoder_attentions"),b=f("cross_attentions");return{sequences:m,decoder_attentions:g,cross_attentions:b}}else return m}addAttentionsToBeam(e,o){if(this.config.is_encoder_decoder){if(!o.cross_attentions||o.cross_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.cross_attentions||(e.cross_attentions=[]),e.cross_attentions.push(o.cross_attentions)}if(!o.decoder_attentions||o.decoder_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.decoder_attentions||(e.decoder_attentions=[]),e.decoder_attentions.push(o.decoder_attentions)}groupBeams(e){const o=Object.create(null);for(const i of e)o[i.id]===void 0?o[i.id]=[i]:o[i.id].push(i);return Object.values(o)}getPastKeyValues(e,o){const i=Object.create(null);for(const u in e)if(u.startsWith("present")){let n=u.replace("present","past_key_values");o&&u.includes("encoder")?i[n]=o[n]:i[n]=e[u]}return i}getAttentions(e){const o=Object.create(null);for(const i of["cross_attentions","decoder_attentions"]){const u=[];for(const n in e)if(n.startsWith(i)){const s=n.split(".").pop();u[s]=e[n]}o[i]=u}return o}addPastKeyValues(e,o){if(o)Object.assign(e,o);else{const u=this.config.precision||"float32",n=u==="float16"?new Uint16Array:[];if(this.config.is_encoder_decoder&&(this.add_encoder_pkv??!0)){let s=[1,this.num_encoder_heads,0,this.encoder_dim_kv],c=[1,this.num_decoder_heads,0,this.decoder_dim_kv];for(let d=0;d{let a=Array.from({length:this.config.decoder_layers},(b,v)=>cat(r.map(T=>T[v]),2)),l=stack(o.map(([b,v])=>i?a[b].slice(null,v,null,[0,i]):a[b].slice(null,v)));l=l.transpose(1,0,2,3);let[h,f]=std_mean(l,-2,0,!0),m=l.clone();for(let b=0;bl[v+1]-l[v]),m=mergeArrays([1],f).map(b=>!!b),g=[];for(let b=0;bu*n,1);e.input_labels=new Tensor("int64",new BigInt64Array(i).fill(1n),o)}return await sessionRun(this.prompt_encoder_mask_decoder,{input_points:e.input_points,input_labels:e.input_labels,image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings})}async _call(e){return new SamImageSegmentationOutput(await super._call(e))}}class SamImageSegmentationOutput extends ModelOutput{constructor({iou_scores:e,pred_masks:o}){super(),this.iou_scores=e,this.pred_masks=o}}class MarianPreTrainedModel extends PreTrainedModel{}class MarianModel extends MarianPreTrainedModel{}class MarianMTModel extends MarianPreTrainedModel{constructor(e,o,i,u){super(e,o),this.decoder_merged_session=i,this.generation_config=u,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class M2M100PreTrainedModel extends PreTrainedModel{}class M2M100Model extends M2M100PreTrainedModel{}class M2M100ForConditionalGeneration extends M2M100PreTrainedModel{constructor(e,o,i,u){super(e,o),this.decoder_merged_session=i,this.generation_config=u,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class Wav2Vec2PreTrainedModel extends PreTrainedModel{}class Wav2Vec2Model extends Wav2Vec2PreTrainedModel{}class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class UniSpeechPreTrainedModel extends PreTrainedModel{}class UniSpeechModel extends UniSpeechPreTrainedModel{}class UniSpeechForCTC extends UniSpeechPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class UniSpeechSatPreTrainedModel extends PreTrainedModel{}class UniSpeechSatModel extends UniSpeechSatPreTrainedModel{}class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class Wav2Vec2BertPreTrainedModel extends PreTrainedModel{}class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel{}class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class HubertModel extends Wav2Vec2PreTrainedModel{}class HubertForCTC extends Wav2Vec2PreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class WavLMPreTrainedModel extends PreTrainedModel{}class WavLMModel extends WavLMPreTrainedModel{}class WavLMForCTC extends WavLMPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class WavLMForSequenceClassification extends WavLMPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class WavLMForXVector extends WavLMPreTrainedModel{async _call(e){return new XVectorOutput(await super._call(e))}}class WavLMForAudioFrameClassification extends WavLMPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class SpeechT5PreTrainedModel extends PreTrainedModel{}class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel{}class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel{constructor(e,o,i,u){super(e,o),this.decoder_merged_session=i,this.generation_config=u,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.hidden_size/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.hidden_size/this.num_encoder_heads}async generate_speech(e,o,{threshold:i=.5,minlenratio:u=0,maxlenratio:n=20,vocoder:s=null}={}){const c={input_ids:e},{encoder_outputs:d,encoder_attention_mask:r}=await encoderForward(this,c),a=d.dims[1]/this.config.reduction_factor,l=Math.floor(a*n),h=Math.floor(a*u),f=this.config.num_mel_bins;let m=[],g=null,b=null,v=0;for(;;){++v;const M=boolTensor(!!b);let F;b?F=b.output_sequence_out:F=new Tensor("float32",new Float32Array(f),[1,1,f]);let Y={use_cache_branch:M,output_sequence:F,encoder_attention_mask:r,speaker_embeddings:o,encoder_hidden_states:d};this.addPastKeyValues(Y,g),b=await sessionRun(this.decoder_merged_session,Y),g=this.getPastKeyValues(b,g);const{prob:H,spectrum:X}=b;if(m.push(X),v>=h&&(Array.from(H.data).filter(k=>k>=i).length>0||v>=l))break}const T=cat(m),{waveform:E}=await sessionRun(s.session,{spectrogram:T});return{spectrogram:T,waveform:E}}}class SpeechT5HifiGan extends PreTrainedModel{main_input_name="spectrogram"}class TrOCRPreTrainedModel extends PreTrainedModel{constructor(e,o,i){super(e,o),this.generation_config=i,this.config.pad_token_id=this.config.eos_token_id,this.num_encoder_layers=this.num_decoder_layers=this.config.decoder_layers,this.num_encoder_heads=this.num_decoder_heads=this.config.decoder_attention_heads,this.encoder_dim_kv=this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads}}class TrOCRForCausalLM extends TrOCRPreTrainedModel{}class MistralPreTrainedModel extends PreTrainedModel{constructor(e,o,i){super(e,o),this.generation_config=i,this.config.pad_token_id=this.config.eos_token_id,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class MistralModel extends MistralPreTrainedModel{}class MistralForCausalLM extends MistralPreTrainedModel{}class Starcoder2PreTrainedModel extends PreTrainedModel{constructor(e,o,i){super(e,o),this.generation_config=i,this.config.pad_token_id=this.config.eos_token_id,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class Starcoder2Model extends Starcoder2PreTrainedModel{}class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel{}class FalconPreTrainedModel extends PreTrainedModel{constructor(e,o,i){super(e,o),this.generation_config=i,this.config.pad_token_id=this.config.eos_token_id,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class FalconModel extends FalconPreTrainedModel{}class FalconForCausalLM extends FalconPreTrainedModel{}class ClapPreTrainedModel extends PreTrainedModel{}class ClapModel extends ClapPreTrainedModel{}class ClapTextModelWithProjection extends ClapPreTrainedModel{static async from_pretrained(e,o={}){return o.model_file_name??="text_model",super.from_pretrained(e,o)}}class ClapAudioModelWithProjection extends ClapPreTrainedModel{static async from_pretrained(e,o={}){return o.model_file_name??="audio_model",super.from_pretrained(e,o)}}class VitsPreTrainedModel extends PreTrainedModel{}class VitsModel extends VitsPreTrainedModel{async _call(e){return new VitsModelOutput(await super._call(e))}}class SegformerPreTrainedModel extends PreTrainedModel{}class SegformerForImageClassification extends SegformerPreTrainedModel{}class SegformerForSemanticSegmentation extends SegformerPreTrainedModel{}class StableLmPreTrainedModel extends PreTrainedModel{constructor(e,o,i){super(e,o),this.generation_config=i,this.config.pad_token_id=this.config.eos_token_id,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.num_heads}}class StableLmForCausalLM extends StableLmPreTrainedModel{}class PretrainedMixin{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{quantized:o=!0,progress_callback:i=null,config:u=null,cache_dir:n=null,local_files_only:s=!1,revision:c="main",model_file_name:d=null,session_options:r={}}={}){let a={quantized:o,progress_callback:i,config:u,cache_dir:n,local_files_only:s,revision:c,model_file_name:d,session_options:r};if(u=await AutoConfig.from_pretrained(e,a),a.config||(a.config=u),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let l of this.MODEL_CLASS_MAPPINGS){const h=l.get(u.model_type);if(h)return await h[1].from_pretrained(e,a)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${u.model_type}", attempting to construct from base class.`),await PreTrainedModel.from_pretrained(e,a);throw Error(`Unsupported model type: ${u.model_type}`)}}const MODEL_MAPPING_NAMES_ENCODER_ONLY=new Map([["bert",["BertModel",BertModel]],["nomic_bert",["NomicBertModel",NomicBertModel]],["roformer",["RoFormerModel",RoFormerModel]],["electra",["ElectraModel",ElectraModel]],["esm",["EsmModel",EsmModel]],["convbert",["ConvBertModel",ConvBertModel]],["camembert",["CamembertModel",CamembertModel]],["deberta",["DebertaModel",DebertaModel]],["deberta-v2",["DebertaV2Model",DebertaV2Model]],["mpnet",["MPNetModel",MPNetModel]],["albert",["AlbertModel",AlbertModel]],["distilbert",["DistilBertModel",DistilBertModel]],["roberta",["RobertaModel",RobertaModel]],["xlm",["XLMModel",XLMModel]],["xlm-roberta",["XLMRobertaModel",XLMRobertaModel]],["clap",["ClapModel",ClapModel]],["clip",["CLIPModel",CLIPModel]],["clipseg",["CLIPSegModel",CLIPSegModel]],["chinese_clip",["ChineseCLIPModel",ChineseCLIPModel]],["siglip",["SiglipModel",SiglipModel]],["mobilebert",["MobileBertModel",MobileBertModel]],["squeezebert",["SqueezeBertModel",SqueezeBertModel]],["wav2vec2",["Wav2Vec2Model",Wav2Vec2Model]],["wav2vec2-bert",["Wav2Vec2BertModel",Wav2Vec2BertModel]],["unispeech",["UniSpeechModel",UniSpeechModel]],["unispeech-sat",["UniSpeechSatModel",UniSpeechSatModel]],["hubert",["HubertModel",HubertModel]],["wavlm",["WavLMModel",WavLMModel]],["audio-spectrogram-transformer",["ASTModel",ASTModel]],["vits",["VitsModel",VitsModel]],["detr",["DetrModel",DetrModel]],["table-transformer",["TableTransformerModel",TableTransformerModel]],["vit",["ViTModel",ViTModel]],["mobilevit",["MobileViTModel",MobileViTModel]],["owlvit",["OwlViTModel",OwlViTModel]],["owlv2",["Owlv2Model",Owlv2Model]],["beit",["BeitModel",BeitModel]],["deit",["DeiTModel",DeiTModel]],["convnext",["ConvNextModel",ConvNextModel]],["convnextv2",["ConvNextV2Model",ConvNextV2Model]],["dinov2",["Dinov2Model",Dinov2Model]],["resnet",["ResNetModel",ResNetModel]],["swin",["SwinModel",SwinModel]],["swin2sr",["Swin2SRModel",Swin2SRModel]],["donut-swin",["DonutSwinModel",DonutSwinModel]],["yolos",["YolosModel",YolosModel]],["dpt",["DPTModel",DPTModel]],["glpn",["GLPNModel",GLPNModel]],["hifigan",["SpeechT5HifiGan",SpeechT5HifiGan]]]),MODEL_MAPPING_NAMES_ENCODER_DECODER=new Map([["t5",["T5Model",T5Model]],["longt5",["LongT5Model",LongT5Model]],["mt5",["MT5Model",MT5Model]],["bart",["BartModel",BartModel]],["mbart",["MBartModel",MBartModel]],["marian",["MarianModel",MarianModel]],["whisper",["WhisperModel",WhisperModel]],["m2m_100",["M2M100Model",M2M100Model]],["blenderbot",["BlenderbotModel",BlenderbotModel]],["blenderbot-small",["BlenderbotSmallModel",BlenderbotSmallModel]]]),MODEL_MAPPING_NAMES_DECODER_ONLY=new Map([["bloom",["BloomModel",BloomModel]],["gpt2",["GPT2Model",GPT2Model]],["gptj",["GPTJModel",GPTJModel]],["gpt_bigcode",["GPTBigCodeModel",GPTBigCodeModel]],["gpt_neo",["GPTNeoModel",GPTNeoModel]],["gpt_neox",["GPTNeoXModel",GPTNeoXModel]],["codegen",["CodeGenModel",CodeGenModel]],["llama",["LlamaModel",LlamaModel]],["qwen2",["Qwen2Model",Qwen2Model]],["phi",["PhiModel",PhiModel]],["mpt",["MptModel",MptModel]],["opt",["OPTModel",OPTModel]],["mistral",["MistralModel",MistralModel]],["starcoder2",["Starcoder2Model",Starcoder2Model]],["falcon",["FalconModel",FalconModel]]]),MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES=new Map([["speecht5",["SpeechT5ForSpeechToText",SpeechT5ForSpeechToText]],["whisper",["WhisperForConditionalGeneration",WhisperForConditionalGeneration]]]),MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES=new Map([["speecht5",["SpeechT5ForTextToSpeech",SpeechT5ForTextToSpeech]]]),MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES=new Map([["vits",["VitsModel",VitsModel]]]),MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES=new Map([["bert",["BertForSequenceClassification",BertForSequenceClassification]],["roformer",["RoFormerForSequenceClassification",RoFormerForSequenceClassification]],["electra",["ElectraForSequenceClassification",ElectraForSequenceClassification]],["esm",["EsmForSequenceClassification",EsmForSequenceClassification]],["convbert",["ConvBertForSequenceClassification",ConvBertForSequenceClassification]],["camembert",["CamembertForSequenceClassification",CamembertForSequenceClassification]],["deberta",["DebertaForSequenceClassification",DebertaForSequenceClassification]],["deberta-v2",["DebertaV2ForSequenceClassification",DebertaV2ForSequenceClassification]],["mpnet",["MPNetForSequenceClassification",MPNetForSequenceClassification]],["albert",["AlbertForSequenceClassification",AlbertForSequenceClassification]],["distilbert",["DistilBertForSequenceClassification",DistilBertForSequenceClassification]],["roberta",["RobertaForSequenceClassification",RobertaForSequenceClassification]],["xlm",["XLMForSequenceClassification",XLMForSequenceClassification]],["xlm-roberta",["XLMRobertaForSequenceClassification",XLMRobertaForSequenceClassification]],["bart",["BartForSequenceClassification",BartForSequenceClassification]],["mbart",["MBartForSequenceClassification",MBartForSequenceClassification]],["mobilebert",["MobileBertForSequenceClassification",MobileBertForSequenceClassification]],["squeezebert",["SqueezeBertForSequenceClassification",SqueezeBertForSequenceClassification]]]),MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES=new Map([["bert",["BertForTokenClassification",BertForTokenClassification]],["roformer",["RoFormerForTokenClassification",RoFormerForTokenClassification]],["electra",["ElectraForTokenClassification",ElectraForTokenClassification]],["esm",["EsmForTokenClassification",EsmForTokenClassification]],["convbert",["ConvBertForTokenClassification",ConvBertForTokenClassification]],["camembert",["CamembertForTokenClassification",CamembertForTokenClassification]],["deberta",["DebertaForTokenClassification",DebertaForTokenClassification]],["deberta-v2",["DebertaV2ForTokenClassification",DebertaV2ForTokenClassification]],["mpnet",["MPNetForTokenClassification",MPNetForTokenClassification]],["distilbert",["DistilBertForTokenClassification",DistilBertForTokenClassification]],["roberta",["RobertaForTokenClassification",RobertaForTokenClassification]],["xlm",["XLMForTokenClassification",XLMForTokenClassification]],["xlm-roberta",["XLMRobertaForTokenClassification",XLMRobertaForTokenClassification]]]),MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES=new Map([["t5",["T5ForConditionalGeneration",T5ForConditionalGeneration]],["longt5",["LongT5ForConditionalGeneration",LongT5ForConditionalGeneration]],["mt5",["MT5ForConditionalGeneration",MT5ForConditionalGeneration]],["bart",["BartForConditionalGeneration",BartForConditionalGeneration]],["mbart",["MBartForConditionalGeneration",MBartForConditionalGeneration]],["marian",["MarianMTModel",MarianMTModel]],["m2m_100",["M2M100ForConditionalGeneration",M2M100ForConditionalGeneration]],["blenderbot",["BlenderbotForConditionalGeneration",BlenderbotForConditionalGeneration]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",BlenderbotSmallForConditionalGeneration]]]),MODEL_WITH_LM_HEAD_MAPPING_NAMES=new Map([["bloom",["BloomForCausalLM",BloomForCausalLM]],["gpt2",["GPT2LMHeadModel",GPT2LMHeadModel]],["gptj",["GPTJForCausalLM",GPTJForCausalLM]],["gpt_bigcode",["GPTBigCodeForCausalLM",GPTBigCodeForCausalLM]],["gpt_neo",["GPTNeoForCausalLM",GPTNeoForCausalLM]],["gpt_neox",["GPTNeoXForCausalLM",GPTNeoXForCausalLM]],["codegen",["CodeGenForCausalLM",CodeGenForCausalLM]],["llama",["LlamaForCausalLM",LlamaForCausalLM]],["qwen2",["Qwen2ForCausalLM",Qwen2ForCausalLM]],["phi",["PhiForCausalLM",PhiForCausalLM]],["mpt",["MptForCausalLM",MptForCausalLM]],["opt",["OPTForCausalLM",OPTForCausalLM]],["mbart",["MBartForCausalLM",MBartForCausalLM]],["mistral",["MistralForCausalLM",MistralForCausalLM]],["starcoder2",["Starcoder2ForCausalLM",Starcoder2ForCausalLM]],["falcon",["FalconForCausalLM",FalconForCausalLM]],["trocr",["TrOCRForCausalLM",TrOCRForCausalLM]],["stablelm",["StableLmForCausalLM",StableLmForCausalLM]]]),MODEL_FOR_MASKED_LM_MAPPING_NAMES=new Map([["bert",["BertForMaskedLM",BertForMaskedLM]],["roformer",["RoFormerForMaskedLM",RoFormerForMaskedLM]],["electra",["ElectraForMaskedLM",ElectraForMaskedLM]],["esm",["EsmForMaskedLM",EsmForMaskedLM]],["convbert",["ConvBertForMaskedLM",ConvBertForMaskedLM]],["camembert",["CamembertForMaskedLM",CamembertForMaskedLM]],["deberta",["DebertaForMaskedLM",DebertaForMaskedLM]],["deberta-v2",["DebertaV2ForMaskedLM",DebertaV2ForMaskedLM]],["mpnet",["MPNetForMaskedLM",MPNetForMaskedLM]],["albert",["AlbertForMaskedLM",AlbertForMaskedLM]],["distilbert",["DistilBertForMaskedLM",DistilBertForMaskedLM]],["roberta",["RobertaForMaskedLM",RobertaForMaskedLM]],["xlm",["XLMWithLMHeadModel",XLMWithLMHeadModel]],["xlm-roberta",["XLMRobertaForMaskedLM",XLMRobertaForMaskedLM]],["mobilebert",["MobileBertForMaskedLM",MobileBertForMaskedLM]],["squeezebert",["SqueezeBertForMaskedLM",SqueezeBertForMaskedLM]]]),MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES=new Map([["bert",["BertForQuestionAnswering",BertForQuestionAnswering]],["roformer",["RoFormerForQuestionAnswering",RoFormerForQuestionAnswering]],["electra",["ElectraForQuestionAnswering",ElectraForQuestionAnswering]],["convbert",["ConvBertForQuestionAnswering",ConvBertForQuestionAnswering]],["camembert",["CamembertForQuestionAnswering",CamembertForQuestionAnswering]],["deberta",["DebertaForQuestionAnswering",DebertaForQuestionAnswering]],["deberta-v2",["DebertaV2ForQuestionAnswering",DebertaV2ForQuestionAnswering]],["mpnet",["MPNetForQuestionAnswering",MPNetForQuestionAnswering]],["albert",["AlbertForQuestionAnswering",AlbertForQuestionAnswering]],["distilbert",["DistilBertForQuestionAnswering",DistilBertForQuestionAnswering]],["roberta",["RobertaForQuestionAnswering",RobertaForQuestionAnswering]],["xlm",["XLMForQuestionAnswering",XLMForQuestionAnswering]],["xlm-roberta",["XLMRobertaForQuestionAnswering",XLMRobertaForQuestionAnswering]],["mobilebert",["MobileBertForQuestionAnswering",MobileBertForQuestionAnswering]],["squeezebert",["SqueezeBertForQuestionAnswering",SqueezeBertForQuestionAnswering]]]),MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",VisionEncoderDecoderModel]]]),MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES=new Map([["vit",["ViTForImageClassification",ViTForImageClassification]],["mobilevit",["MobileViTForImageClassification",MobileViTForImageClassification]],["beit",["BeitForImageClassification",BeitForImageClassification]],["deit",["DeiTForImageClassification",DeiTForImageClassification]],["convnext",["ConvNextForImageClassification",ConvNextForImageClassification]],["convnextv2",["ConvNextV2ForImageClassification",ConvNextV2ForImageClassification]],["dinov2",["Dinov2ForImageClassification",Dinov2ForImageClassification]],["resnet",["ResNetForImageClassification",ResNetForImageClassification]],["swin",["SwinForImageClassification",SwinForImageClassification]],["segformer",["SegformerForImageClassification",SegformerForImageClassification]]]),MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES=new Map([["detr",["DetrForObjectDetection",DetrForObjectDetection]],["table-transformer",["TableTransformerForObjectDetection",TableTransformerForObjectDetection]],["yolos",["YolosForObjectDetection",YolosForObjectDetection]]]),MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES=new Map([["owlvit",["OwlViTForObjectDetection",OwlViTForObjectDetection]],["owlv2",["Owlv2ForObjectDetection",Owlv2ForObjectDetection]]]),MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES=new Map([["detr",["DetrForSegmentation",DetrForSegmentation]],["clipseg",["CLIPSegForImageSegmentation",CLIPSegForImageSegmentation]]]),MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES=new Map([["segformer",["SegformerForSemanticSegmentation",SegformerForSemanticSegmentation]]]),MODEL_FOR_MASK_GENERATION_MAPPING_NAMES=new Map([["sam",["SamModel",SamModel]]]),MODEL_FOR_CTC_MAPPING_NAMES=new Map([["wav2vec2",["Wav2Vec2ForCTC",Wav2Vec2ForCTC]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Wav2Vec2BertForCTC]],["unispeech",["UniSpeechForCTC",UniSpeechForCTC]],["unispeech-sat",["UniSpeechSatForCTC",UniSpeechSatForCTC]],["wavlm",["WavLMForCTC",WavLMForCTC]],["hubert",["HubertForCTC",HubertForCTC]]]),MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Wav2Vec2ForSequenceClassification]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Wav2Vec2BertForSequenceClassification]],["unispeech",["UniSpeechForSequenceClassification",UniSpeechForSequenceClassification]],["unispeech-sat",["UniSpeechSatForSequenceClassification",UniSpeechSatForSequenceClassification]],["wavlm",["WavLMForSequenceClassification",WavLMForSequenceClassification]],["hubert",["HubertForSequenceClassification",HubertForSequenceClassification]],["audio-spectrogram-transformer",["ASTForAudioClassification",ASTForAudioClassification]]]),MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES=new Map([["wavlm",["WavLMForXVector",WavLMForXVector]]]),MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",UniSpeechSatForAudioFrameClassification]],["wavlm",["WavLMForAudioFrameClassification",WavLMForAudioFrameClassification]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Wav2Vec2ForAudioFrameClassification]]]),MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES=new Map([["vitmatte",["VitMatteForImageMatting",VitMatteForImageMatting]]]),MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Swin2SRForImageSuperResolution]]]),MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES=new Map([["dpt",["DPTForDepthEstimation",DPTForDepthEstimation]],["depth_anything",["DepthAnythingForDepthEstimation",DepthAnythingForDepthEstimation]],["glpn",["GLPNForDepthEstimation",GLPNForDepthEstimation]]]),MODEL_CLASS_TYPE_MAPPING=[[MODEL_MAPPING_NAMES_ENCODER_ONLY,MODEL_TYPES.EncoderOnly],[MODEL_MAPPING_NAMES_ENCODER_DECODER,MODEL_TYPES.EncoderDecoder],[MODEL_MAPPING_NAMES_DECODER_ONLY,MODEL_TYPES.DecoderOnly],[MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,MODEL_TYPES.Seq2Seq],[MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES,MODEL_TYPES.Seq2Seq],[MODEL_WITH_LM_HEAD_MAPPING_NAMES,MODEL_TYPES.DecoderOnly],[MODEL_FOR_MASKED_LM_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,MODEL_TYPES.Vision2Seq],[MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_MASK_GENERATION_MAPPING_NAMES,MODEL_TYPES.MaskGeneration],[MODEL_FOR_CTC_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES,MODEL_TYPES.Seq2Seq],[MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly]];for(const[t,e]of MODEL_CLASS_TYPE_MAPPING)for(const[o,i]of t.values())MODEL_TYPE_MAPPING.set(o,e),MODEL_CLASS_TO_NAME_MAPPING.set(i,o),MODEL_NAME_TO_CLASS_MAPPING.set(o,i);const CUSTOM_MAPPING=[["CLIPTextModelWithProjection",CLIPTextModelWithProjection,MODEL_TYPES.EncoderOnly],["CLIPVisionModelWithProjection",CLIPVisionModelWithProjection,MODEL_TYPES.EncoderOnly],["SiglipTextModel",SiglipTextModel,MODEL_TYPES.EncoderOnly],["SiglipVisionModel",SiglipVisionModel,MODEL_TYPES.EncoderOnly],["ClapTextModelWithProjection",ClapTextModelWithProjection,MODEL_TYPES.EncoderOnly],["ClapAudioModelWithProjection",ClapAudioModelWithProjection,MODEL_TYPES.EncoderOnly]];for(const[t,e,o]of CUSTOM_MAPPING)MODEL_TYPE_MAPPING.set(t,o),MODEL_CLASS_TO_NAME_MAPPING.set(e,t),MODEL_NAME_TO_CLASS_MAPPING.set(t,e);class AutoModel extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=MODEL_CLASS_TYPE_MAPPING.map(e=>e[0]);static BASE_IF_FAIL=!0}class Seq2SeqLMOutput extends ModelOutput{constructor({logits:e,past_key_values:o,encoder_outputs:i,decoder_attentions:u=null,cross_attentions:n=null}){super(),this.logits=e,this.past_key_values=o,this.encoder_outputs=i,this.decoder_attentions=u,this.cross_attentions=n}}class SequenceClassifierOutput extends ModelOutput{constructor({logits:e}){super(),this.logits=e}}class XVectorOutput extends ModelOutput{constructor({logits:e,embeddings:o}){super(),this.logits=e,this.embeddings=o}}class TokenClassifierOutput extends ModelOutput{constructor({logits:e}){super(),this.logits=e}}class MaskedLMOutput extends ModelOutput{constructor({logits:e}){super(),this.logits=e}}class QuestionAnsweringModelOutput extends ModelOutput{constructor({start_logits:e,end_logits:o}){super(),this.start_logits=e,this.end_logits=o}}class CausalLMOutput extends ModelOutput{constructor({logits:e}){super(),this.logits=e}}class ImageMattingOutput extends ModelOutput{constructor({alphas:e}){super(),this.alphas=e}}class VitsModelOutput extends ModelOutput{constructor({waveform:e,spectrogram:o}){super(),this.waveform=e,this.spectrogram=o}}const BROWSER_ENV=typeof self<"u",WEBWORKER_ENV=BROWSER_ENV&&self.constructor.name==="DedicatedWorkerGlobalScope";let createCanvasFunction,ImageDataClass,loadImageFunction;if(BROWSER_ENV)createCanvasFunction=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},loadImageFunction=self.createImageBitmap,ImageDataClass=self.ImageData;else if(sharp)loadImageFunction=async t=>{const o=(await t.metadata()).channels,{data:i,info:u}=await t.raw().toBuffer({resolveWithObject:!0}),n=new RawImage(new Uint8ClampedArray(i),u.width,u.height,u.channels);return o!==void 0&&o!==u.channels&&n.convert(o),n};else throw new Error("Unable to load image processing library.");const RESAMPLING_MAPPING={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},CONTENT_TYPE_MAP=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class RawImage{constructor(e,o,i,u){this.data=e,this.width=o,this.height=i,this.channels=u}get size(){return[this.width,this.height]}static async read(e){if(e instanceof RawImage)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);throw new Error(`Unsupported input type: ${typeof e}`)}static async fromURL(e){const o=await getFile(e);if(o.status!==200)throw new Error(`Unable to read image from "${e}" (${o.status} ${o.statusText})`);const i=await o.blob();return this.fromBlob(i)}static async fromBlob(e){if(BROWSER_ENV){const o=await loadImageFunction(e),i=createCanvasFunction(o.width,o.height).getContext("2d");return i.drawImage(o,0,0),new this(i.getImageData(0,0,o.width,o.height).data,o.width,o.height,4)}else{const o=sharp(await e.arrayBuffer());return await loadImageFunction(o)}}static fromTensor(e,o="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(o==="CHW")e=e.transpose(1,2,0);else if(o!=="HWC")throw new Error(`Unsupported channel format: ${o}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new RawImage(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let o=0,i=0;o=0?d=i:a=-i,u>=0?r=u:l=-u,c.drawImage(s,d,r,e,o,a,l,e,o),new RawImage(c.getImageData(0,0,e,o).data,e,o,4).convert(n)}else{let n=this.toSharp();if(i>=0&&u>=0)n=n.extract({left:Math.floor(i),top:Math.floor(u),width:e,height:o});else if(i<=0&&u<=0){const s=Math.floor(-u),c=Math.floor(-i);n=n.extend({top:s,left:c,right:e-this.width-c,bottom:o-this.height-s})}else{let s=[0,0],c=0;u<0?(s[0]=Math.floor(-u),s[1]=o-this.height-s[0]):c=Math.floor(u);let d=[0,0],r=0;i<0?(d[0]=Math.floor(-i),d[1]=e-this.width-d[0]):r=Math.floor(i),n=n.extend({top:s[0],bottom:s[1],left:d[0],right:d[1]}).extract({left:r,top:c,width:e,height:o})}return await loadImageFunction(n)}}async toBlob(e="image/png",o=1){if(!BROWSER_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:o})}toCanvas(){if(!BROWSER_ENV)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),o=createCanvasFunction(e.width,e.height),i=new ImageDataClass(e.data,e.width,e.height);return o.getContext("2d").putImageData(i,0,0),o}_update(e,o,i,u=null){return this.data=e,this.width=o,this.height=i,u!==null&&(this.channels=u),this}clone(){return new RawImage(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(BROWSER_ENV){if(WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const o=e.split(".").pop().toLowerCase(),i=CONTENT_TYPE_MAP.get(o)??"image/png",u=await this.toBlob(i),n=URL.createObjectURL(u),s=document.createElement("a");s.href=n,s.download=e,s.click(),s.remove()}else{if(env.useFS)return await this.toSharp().toFile(e);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(BROWSER_ENV)throw new Error("toSharp() is only supported in server-side environments.");return sharp(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}function hanning(t){if(t<1)return new Float64Array;if(t===1)return new Float64Array([1]);const e=t-1,o=Math.PI/e,i=new Float64Array(t);for(let u=0;u2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,o=15,i=27/Math.log(6.4))=>t>=e?o+Math.log(t/e)*i:3*t/200};function hertz_to_mel(t,e="htk"){const o=HERTZ_TO_MEL_MAPPING[e];if(!o)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?o(t):t.map(i=>o(i))}const MEL_TO_HERTZ_MAPPING={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,o=15,i=Math.log(6.4)/27)=>t>=o?e*Math.exp(i*(t-o)):200*t/3};function mel_to_hertz(t,e="htk"){const o=MEL_TO_HERTZ_MAPPING[e];if(!o)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?o(t):t.map(i=>o(i))}function _create_triangular_filter_bank(t,e){const o=Float64Array.from({length:e.length-1},(s,c)=>e[c+1]-e[c]),i=Array.from({length:t.length},()=>new Array(e.length));for(let s=0;snew Array(t.length));for(let s=0;st+i*n)}function mel_filter_bank(t,e,o,i,u,n=null,s="htk",c=!1){if(n!==null&&n!=="slaney")throw new Error('norm must be one of null or "slaney"');const d=hertz_to_mel(o,s),r=hertz_to_mel(i,s),a=linspace(d,r,e+2);let l=mel_to_hertz(a,s),h;if(c){const m=u/(t*2);h=hertz_to_mel(Float64Array.from({length:t},(g,b)=>b*m),s),l=a}else h=linspace(0,Math.floor(u/2),t);const f=_create_triangular_filter_bank(h,l);if(n!==null&&n==="slaney")for(let m=0;mu)throw Error(`frame_length (${o}) may not be larger than fft_length (${u})`);if(M!==o)throw new Error(`Length of the window (${M}) must equal frame_length (${o})`);if(i<=0)throw new Error("hop_length must be greater than zero");if(s){if(c!=="reflect")throw new Error(`pad_mode="${c}" not implemented yet.`);const ie=Math.floor((u-1)/2)+1;t=padReflect(t,ie,ie)}const F=Math.floor(1+Math.floor((t.length-o)/i)),Y=d?Math.floor(u/2)+1:u;let H=F,X=F;v!==null&&(v>F?T&&(X=v):X=H=v);const k=new FFT(u),ne=new Float64Array(u),Ce=new Float64Array(k.outputBufferSize),Me=new Array(H);for(let ie=0;ie=1;--V)ne[V]-=r*ne[V-1];ne[0]*=1-r}for(let V=0;VMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(o&&(s=s.subarray(0,t)),i===null)return s;if(t>i)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${i})`);return s}function center_to_corners_format([t,e,o,i]){return[t-o/2,e-i/2,t+o/2,e+i/2]}function post_process_object_detection(t,e=.5,o=null,i=!1){const u=t.logits,n=t.pred_boxes,[s,c,d]=u.dims;if(o!==null&&o.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let r=[];for(let a=0;ae&&v.push(E)}else{let E=max(b.data)[1];if(E===d-1)continue;v.push(E),T=softmax(b.data)}for(const E of v){let M=m[g].data;M=center_to_corners_format(M),l!==null&&(M=M.map((F,Y)=>F*l[(Y+1)%2])),h.boxes.push(M),h.classes.push(E),h.scores.push(T[E])}}r.push(h)}return r}function validate_audio_inputs(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}function constraint_to_multiple_of(t,e,o=0,i=null){let u=Math.round(t/e)*e;return i!==null&&u>i&&(u=Math.floor(t/e)*e),un?r=Math.floor(n*d/u):n>u&&(d=Math.floor(u*r/n)),await e.resize(r,d,{resample:i}))}async crop_margin(e,o=200){const i=e.clone().grayscale(),u=min(i.data)[0],s=max(i.data)[0]-u;if(s===0)return e;const c=o/255;let d=i.width,r=i.height,a=0,l=0;for(let h=0;hthis.preprocess(n)));return{pixel_values:stack(i.map(n=>n.pixel_values),0),original_sizes:i.map(n=>n.original_size),reshaped_input_sizes:i.map(n=>n.reshaped_input_size)}}}class SegformerFeatureExtractor extends ImageFeatureExtractor{post_process_semantic_segmentation(e,o=null){const i=e.logits,u=i.dims[0];if(o!==null&&o.length!==u)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const n=[];for(let s=0;sh[T]&&(h[T]=v[T],l.data[T]=b)}const f=new Array(d.dims[0]),m=l.data;for(let b=0;bb!==void 0);n.push({segmentation:l,labels:g})}return n}}class DPTImageProcessor extends ImageFeatureExtractor{}class BitImageProcessor extends ImageFeatureExtractor{}class DPTFeatureExtractor extends ImageFeatureExtractor{}class GLPNFeatureExtractor extends ImageFeatureExtractor{}class CLIPFeatureExtractor extends ImageFeatureExtractor{}class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor{}class SiglipImageProcessor extends ImageFeatureExtractor{}class ConvNextFeatureExtractor extends ImageFeatureExtractor{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){const o=this.size?.shortest_edge;if(o===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(o<384){const i=Math.floor(o/this.crop_pct),[u,n]=this.get_resize_output_image_size(e,{shortest_edge:i});e=await e.resize(u,n,{resample:this.resample}),e=await e.center_crop(o,o)}else e=await e.resize(o,o,{resample:this.resample});return e}}class ConvNextImageProcessor extends ConvNextFeatureExtractor{}class ViTFeatureExtractor extends ImageFeatureExtractor{}class ViTImageProcessor extends ImageFeatureExtractor{}class MobileViTFeatureExtractor extends ImageFeatureExtractor{}class OwlViTFeatureExtractor extends ImageFeatureExtractor{post_process_object_detection(...e){return post_process_object_detection(...e)}}class Owlv2ImageProcessor extends OwlViTFeatureExtractor{}class DeiTFeatureExtractor extends ImageFeatureExtractor{}class BeitFeatureExtractor extends ImageFeatureExtractor{}class DonutFeatureExtractor extends ImageFeatureExtractor{pad_image(e,o,i,u={}){const[n,s,c]=o;let d=this.image_mean;Array.isArray(this.image_mean)||(d=new Array(c).fill(d));let r=this.image_std;Array.isArray(r)||(r=new Array(c).fill(d));const a=d.map((l,h)=>-l/this.image_std[h]);return super.pad_image(e,o,i,{center:!0,constant_values:a,...u})}}class NougatImageProcessor extends DonutFeatureExtractor{}class DetrFeatureExtractor extends ImageFeatureExtractor{async _call(e){const o=await super._call(e),i=[o.pixel_values.dims[0],64,64],u=new Tensor("int64",new BigInt64Array(i.reduce((n,s)=>n*s)).fill(1n),i);return{...o,pixel_mask:u}}post_process_object_detection(...e){return post_process_object_detection(...e)}remove_low_and_no_objects(e,o,i,u){let n=[],s=[],c=[];for(let d=0;di&&(n.push(a),s.push(f),c.push(l))}return[n,s,c]}check_segment_validity(e,o,i,u=.5,n=.8){let s=[],c=0,d=0;for(let a=0;a=u&&++d;let r=c>0&&d>0;return r&&(r=c/d>n),[r,s]}compute_segments(e,o,i,u,n,s=null,c=null){let[d,r]=c??e[0].dims,a=new Tensor("int32",new Int32Array(d*r),[d,r]),l=[];if(c!==null)for(let g=0;gf[v]&&(h[v]=g,f[v]=e[g].data[v])}let m=0;for(let g=0;gu!==o.dims[n]))throw Error(`The first ${i.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Tensor("int64",e.flat(1/0).map(BigInt),i)}async _call(e,o=null,i=null){const u=await super._call(e);if(o&&(u.input_points=this.reshape_input_points(o,u.original_sizes,u.reshaped_input_sizes)),i){if(!u.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");u.input_labels=this.add_input_labels(i,u.input_points)}return u}post_process_masks(e,o,i,{mask_threshold:u=0,binarize:n=!0,pad_size:s=null}={}){const c=[];s=s??this.pad_size;const d=[s.height,s.width];for(let r=0;ru&&(v[T]=1);b=new Tensor("bool",v,b.dims)}f.push(b)}c.push(stack(f))}return c}generate_crop_boxes(e,o,{crop_n_layers:i=0,overlap_ratio:u=512/1500,points_per_crop:n=32,crop_n_points_downscale_factor:s=1}={}){}}class Swin2SRImageProcessor extends ImageFeatureExtractor{pad_image(e,o,i,u={}){const[n,s,c]=o;return super.pad_image(e,o,{width:n+(i-n%i)%i,height:s+(i-s%i)%i},{mode:"symmetric",center:!1,constant_values:-1,...u})}}class VitMatteImageProcessor extends ImageFeatureExtractor{async _call(e,o){Array.isArray(e)||(e=[e]),Array.isArray(o)||(o=[o]);const i=await Promise.all(e.map(s=>this.preprocess(s))),u=await Promise.all(o.map(s=>this.preprocess(s,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:stack(i.map((s,c)=>cat([s.pixel_values,u[c].pixel_values],0)),0),original_sizes:i.map(s=>s.original_size),reshaped_input_sizes:i.map(s=>s.reshaped_input_size)}}}class WhisperFeatureExtractor extends FeatureExtractor{constructor(e){super(e),this.config.mel_filters??=mel_filter_bank(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=window_function(this.config.n_fft,"hann")}_extract_fbank_features(e){const{data:o,dims:i}=spectrogram(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),u=max(o)[0];for(let n=0;nthis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),o=e.slice(0,this.config.n_samples)):(o=new Float32Array(this.config.n_samples),o.set(e));const{data:i,dims:u}=this._extract_fbank_features(o);return{input_features:new Tensor("float32",i,[1,...u])}}}class Wav2Vec2FeatureExtractor extends FeatureExtractor{_zero_mean_unit_var_norm(e){const i=e.reduce((n,s)=>n+s,0)/e.length,u=e.reduce((n,s)=>n+(s-i)**2,0)/e.length;return e.map(n=>(n-i)/Math.sqrt(u+1e-7))}async _call(e){validate_audio_inputs(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let o=e;this.config.do_normalize&&(o=this._zero_mean_unit_var_norm(o));const i=[1,o.length];return{input_values:new Tensor("float32",o,i),attention_mask:new Tensor("int64",new BigInt64Array(o.length).fill(1n),i)}}}class SeamlessM4TFeatureExtractor extends FeatureExtractor{constructor(e){super(e);const o=this.config.sampling_rate,i=mel_filter_bank(256,this.config.num_mel_bins,20,Math.floor(o/2),o,null,"kaldi",!0);for(let u=0;ui*32768),spectrogram(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:o,transpose:!0})}async _call(e,{padding:o=!0,pad_to_multiple_of:i=2,do_normalize_per_mel_bins:u=!0,return_attention_mask:n=!0}={}){validate_audio_inputs(e,"SeamlessM4TFeatureExtractor");let s=this._extract_fbank_features(e,this.config.max_length);if(u){const[m,g]=s.dims;for(let b=0;b0){const v=new Float32Array(g*(m+b));v.set(s.data),v.fill(this.config.padding_value,s.data.length);const T=m+b;s={data:v,dims:[T,g]},n&&(c=new Tensor("int64",new BigInt64Array(T),[1,T]),c.data.fill(1n,0,m))}}const[d,r]=s.dims,a=this.config.stride;if(d%a!==0)throw new Error(`The number of frames (${d}) must be a multiple of the stride (${a}).`);const h=new Tensor("float32",s.data,s.dims).view(1,Math.floor(d/a),r*a),f={input_features:h};if(n){const m=h.dims[1],g=new Tensor("int64",new BigInt64Array(m),[1,m]);if(c)for(let b=1,v=0;b0)if(i==="rand_trunc"){s=!0;const d=Math.floor(Math.random()*(c+1));e=e.subarray(d,d+o),n=this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples),n.dims=[1,...n.dims]}else throw new Error(`Truncation strategy "${i}" not implemented`);else{if(c<0){let d=new Float64Array(o);if(d.set(e),u==="repeat")for(let r=e.length;r{size=Number(sizeSlider.value),processor.feature_extractor.size={shortest_edge:size},sizeLabel.textContent=size});sizeSlider.disabled=!1;status.textContent="Ready";let isProcessing=!1,previousTime;const context=canvas.getContext("2d",{willReadFrequently:!0}),outputContext=outputCanvas.getContext("2d",{willReadFrequently:!0});function updateCanvas(){const{width:t,height:e}=canvas;isProcessing||(isProcessing=!0,async function(){console.log("run"),context.drawImage(video,0,0,t,e);const o=context.getImageData(0,0,t,e),i=new RawImage(o.data,t,e,4),u=await processor(i),{output:n}=await model({input:u.pixel_values}),s=await RawImage.fromTensor(n[0].mul(255).to("uint8")).resize(t,e),c=o;for(let d=0;d{video.srcObject=t,video.play();const e=t.getVideoTracks()[0],{width:o,height:i}=e.getSettings();outputCanvas.width=canvas.width=o,outputCanvas.height=canvas.height=i;const u=o/i,[n,s]=u>720/405?[720,720/u]:[405*u,405];container.style.width=`${n}px`,container.style.height=`${s}px`,setTimeout(updateCanvas,10)}).catch(t=>{alert(t)});