@webex/ladon-ts 5.8.0 → 5.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Cisco Ladon-TS
3
3
  * Copyright (c) Cisco Systems, Inc. All rights reserved.
4
- * Build timestamp: July 1, 2025 at 12:11:01 AM UTC
4
+ * Build timestamp: July 2, 2025 at 09:45:43 PM UTC
5
5
  */
6
6
  (function(){"use strict";var _documentCurrentScript=typeof document<"u"?document.currentScript:null;self.document={baseURI:location.origin};const originalConsoleLog=console.log,originalConsoleWarn=console.warn,originalConsoleError=console.error;console.log=(...e)=>{postMessage({type:"log",message:e.join(" "),severity:"log"}),originalConsoleLog(...e)},console.warn=(...e)=>{postMessage({type:"log",message:e.join(" "),severity:"warn"}),originalConsoleWarn(...e)},console.error=(...e)=>{postMessage({type:"log",message:e.join(" "),severity:"error"}),originalConsoleError(...e)};/*!
7
7
  * ONNX Runtime Web v1.20.1
@@ -1803,7 +1803,7 @@ ${e}
1803
1803
  `);let n=this.glContext.compileShader(e,this.glContext.gl.FRAGMENT_SHADER),i=this.glContext.createProgram(this.vertexShader,n);return this.glContext.deleteShader(n),i}bindOutput(e){let n=e.width,i=e.height;tt.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${n}/${i}, shape=${e.shape}, type=${e.tensor.type}`),this.glContext.attachFramebuffer(e.texture,n,i)}bindAttributes(e){let n=e.position,i=e.textureCoord;this.glContext.setVertexAttributes(n,i),this.attributesBound=!0}bindUniforms(e,n,i){var o;let a=this.glContext.gl,p=0;for(let{name:s,type:d,location:c,arrayLength:r}of e){let u=(o=n.find(l=>l.name===s))==null?void 0:o.data;if(d!=="sampler2D"&&!u)throw new Error(`variable '${s}' does not have data defined in program info`);switch(d){case"sampler2D":this.bindTexture(i[p],c,p),p++;break;case"float":r?a.uniform1fv(c,u):a.uniform1f(c,u);break;case"int":r?a.uniform1iv(c,u):a.uniform1i(c,u);break;default:throw new Error(`Uniform not implemented: ${d}`)}}}bindTexture(e,n,i){this.glContext.bindTextureToUniform(e.texture,i,n)}getAttribLocations(e){return{position:this.getAttribLocation(e,"position"),textureCoord:this.getAttribLocation(e,"textureCoord")}}getUniformLocations(e,n,i){let a=[];if(n)for(let p of n)a.push({name:p,type:"sampler2D",location:this.getUniformLocation(e,p)});if(i)for(let p of i)a.push({...p,location:this.getUniformLocation(e,p.name)});return a}getUniformLocation(e,n){let i=this.glContext.gl.getUniformLocation(e,n);if(i===null)throw new Error(`Uniform ${n} not found.`);return i}getAttribLocation(e,n){return this.glContext.gl.getAttribLocation(e,n)}}}),Kn,xp=O(()=>{Ut(),Fr(),Kn=class{constructor(e,n,i,a){this.glContext=e,this.layoutStrategy=n,this.profiler=i,this.config=a,this.pendingRead=new Map,a.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(e,n,i,a){let p=this.toEncoderType(e),o=this.glContext.getEncoder(p,n.channels||1,a);if(n.isPacked&&a===1)throw new Error("not implemented");let s=n.width,d=n.height,c,r;if(this.config.reuseTextures){c=`${s}x${d}_${o.format}_${o.internalFormat}_${o.textureType}`,r=this.inUseTextures.get(c),r||(r=[],this.inUseTextures.set(c,r));let l=this.idleTextures.get(c);if(l&&l.length>0){let h=l.pop();return r.push(h),a===1&&this.glContext.updateTexture(h,s,d,o,this.toTextureData(e,i)),h}}tt.verbose("TextureManager",`Creating new texture of size ${n.width}x${n.height}`);let u=this.glContext.allocateTexture(s,d,o,this.toTextureData(e,i));return this.config.reuseTextures&&(r.push(u),this.textureLookup.set(u,c)),u}readTexture(e,n,i){return i||(i=1),this.profiler.event("backend","TextureManager.readTexture",()=>{let a=e.shape.reduce((o,s)=>o*s)*i,p=this.glContext.readTexture(e.texture,e.width,e.height,a,this.toEncoderType(n),i);return this.toTensorData(n,p)})}async readTextureAsync(e,n,i){let a=e.tensor.dataId;if(i||(i=1),this.pendingRead.has(a)){let p=this.pendingRead.get(a);return new Promise(o=>p==null?void 0:p.push(o))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(a,[]);let p=e.shape.reduce((c,r)=>c*r)*i;await this.glContext.createAndWaitForFence();let o=this.glContext.readTexture(e.texture,e.width,e.height,p,this.toEncoderType(n),i),s=this.toTensorData(n,o),d=this.pendingRead.get(a);return this.pendingRead.delete(a),d==null||d.forEach(c=>c(s)),s})}readUint8TextureAsFloat(e){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{let n=e.shape.reduce((a,p)=>a*p),i=this.glContext.readTexture(e.texture,e.width,e.height,n*4,"byte",4);return new Float32Array(i.buffer,i.byteOffset,n)})}releaseTexture(e,n){let i;if(this.config.reuseTextures&&(i=this.textureLookup.get(e.texture),i)){n&&this.textureLookup.delete(i);let a=this.inUseTextures.get(i);if(a){let p=a.indexOf(e.texture);if(p!==-1){a.splice(p,1);let o=this.idleTextures.get(i);o||(o=[],this.idleTextures.set(i,o)),o.push(e.texture)}}}(!i||n)&&(tt.verbose("TextureManager",`Deleting texture of size ${e.width}x${e.height}`),this.glContext.deleteTexture(e.texture))}toTensorData(e,n){switch(e){case"int16":return n instanceof Int16Array?n:Int16Array.from(n);case"int32":return n instanceof Int32Array?n:Int32Array.from(n);case"int8":return n instanceof Int8Array?n:Int8Array.from(n);case"uint16":return n instanceof Uint16Array?n:Uint16Array.from(n);case"uint32":return n instanceof Uint32Array?n:Uint32Array.from(n);case"uint8":case"bool":return n instanceof Uint8Array?n:Uint8Array.from(n);case"float32":return n instanceof Float32Array?n:Float32Array.from(n);case"float64":return n instanceof Float64Array?n:Float64Array.from(n);default:throw new Error(`TensorData type ${e} is not supported`)}}toTextureData(e,n){if(n)return n instanceof Float32Array?n:new Float32Array(n)}toEncoderType(e){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}}),Jn,Tp=O(()=>{Ut(),Bs(),cl(),ap(),yp(),Ni(),xp(),Jn=class{constructor(e,n){this.backend=e,this.context=n,this.layoutStrategy=new Un(e.glContext.maxTextureSize),this.programManager=new Xn(this.context.profiler,e.glContext,this.layoutStrategy),this.textureManager=new Kn(e.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:e.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=e.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new Dn(this)}onGraphInitialized(e){let n=e.getValues().filter(i=>i.from===-1&&i.tensor).map(i=>i.tensor.dataId);this.initializers=new Set(n)}isInitializer(e){return this.initializers?this.initializers.has(e):!1}addInitializer(e){this.initializers.add(e)}getTextureData(e,n){return n?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,n,i=!1){tt.verbose("WebGLSessionHandler","Storing Texture data in cache"),i?this.packedTextureDataCache.set(e,n):this.unpackedTextureDataCache.set(e,n)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.textureManager.releaseTexture(e,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.textureManager.releaseTexture(e,!0)),this.unpackedTextureDataCache=new Map}resolve(e,n,i){let a=ks(e,n,ip);return{impl:a.opImpl,context:a.opInit?a.opInit(e,i):e}}}});function bg(e){let n=0;for(;n<e.length&&e[n]();++n);return n-1}var Mr,wp=O(()=>{Yt(),Fr(),Fr(),pe(),Mr=class{constructor(e,n){this.frameBufferBound=!1,this.itemsToPoll=[],this.gl=e,this.version=n,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(e,n,i,a){let p=this.gl,o=p.createTexture();p.bindTexture(p.TEXTURE_2D,o),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE);let s=a?i.encode(a,e*n):null;return p.texImage2D(p.TEXTURE_2D,0,i.internalFormat,e,n,0,i.format,i.textureType,s),this.checkError(),o}updateTexture(e,n,i,a,p){let o=this.gl;o.bindTexture(o.TEXTURE_2D,e);let s=a.encode(p,n*i);o.texSubImage2D(o.TEXTURE_2D,0,0,0,n,i,a.format,a.textureType,s),this.checkError()}attachFramebuffer(e,n,i){let a=this.gl;a.bindTexture(a.TEXTURE_2D,e),a.bindFramebuffer(a.FRAMEBUFFER,this.framebuffer),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,e,0),this.checkError(),a.viewport(0,0,n,i),a.scissor(0,0,n,i)}readTexture(e,n,i,a,p,o){let s=this.gl;o||(o=1),this.frameBufferBound||this.attachFramebuffer(e,n,i);let d=this.getEncoder(p,o),c=d.allocate(n*i);return s.bindTexture(s.TEXTURE_2D,e),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,e,0),s.readPixels(0,0,n,i,s.RGBA,d.textureType,c),this.checkError(),d.decode(c,a)}isFramebufferReady(){return!0}getActiveTexture(){let e=this.gl;return`TEXTURE${e.getParameter(this.gl.ACTIVE_TEXTURE)-e.TEXTURE0}`}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(e,n){let i=this.gl;i.vertexAttribPointer(e,3,i.FLOAT,!1,20,0),i.enableVertexAttribArray(e),n!==-1&&(i.vertexAttribPointer(n,2,i.FLOAT,!1,20,12),i.enableVertexAttribArray(n)),this.checkError()}createProgram(e,n){let i=this.gl,a=i.createProgram();return i.attachShader(a,e),i.attachShader(a,n),i.linkProgram(a),a}compileShader(e,n){let i=this.gl,a=i.createShader(n);if(!a)throw new Error(`createShader() returned null with type ${n}`);if(i.shaderSource(a,e),i.compileShader(a),i.getShaderParameter(a,i.COMPILE_STATUS)===!1)throw new Error(`Failed to compile shader: ${i.getShaderInfoLog(a)}
1804
1804
  Shader source:
1805
1805
  ${e}`);return a}deleteShader(e){this.gl.deleteShader(e)}bindTextureToUniform(e,n,i){let a=this.gl;a.activeTexture(a.TEXTURE0+n),this.checkError(),a.bindTexture(a.TEXTURE_2D,e),this.checkError(),a.uniform1i(i,n),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(z.debug){let e=this.gl,n=e.getError(),i="";switch(n){case e.NO_ERROR:return;case e.INVALID_ENUM:i="INVALID_ENUM";break;case e.INVALID_VALUE:i="INVALID_VALUE";break;case e.INVALID_OPERATION:i="INVALID_OPERATION";break;case e.INVALID_FRAMEBUFFER_OPERATION:i="INVALID_FRAMEBUFFER_OPERATION";break;case e.OUT_OF_MEMORY:i="OUT_OF_MEMORY";break;case e.CONTEXT_LOST_WEBGL:i="CONTEXT_LOST_WEBGL";break;default:i=`Unknown WebGL Error: ${n.toString(16)}`}throw new Error(i)}}deleteTexture(e){this.gl.deleteTexture(e)}deleteProgram(e){this.gl.deleteProgram(e)}getEncoder(e,n,i=0){if(this.version===2)return new Pn(this.gl,n);switch(e){case"float":return i===1||this.isRenderFloat32Supported?new Br(this.gl,n):new Br(this.gl,n,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new En(this.gl,n);default:throw new Error(`Invalid dataType: ${e}`)}}clearActiveTextures(){let e=this.gl;for(let n=0;n<this.maxTextureImageUnits;++n)e.activeTexture(e.TEXTURE0+n),e.bindTexture(e.TEXTURE_2D,null)}dispose(){if(this.disposed)return;let e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(this.framebuffer),e.bindBuffer(e.ARRAY_BUFFER,null),e.deleteBuffer(this.vertexbuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.finish(),this.disposed=!0}createDefaultGeometry(){return new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0])}createVertexbuffer(){let e=this.gl,n=e.createBuffer();if(!n)throw new Error("createBuffer() returned null");let i=this.createDefaultGeometry();return e.bindBuffer(e.ARRAY_BUFFER,n),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW),this.checkError(),n}createFramebuffer(){let e=this.gl.createFramebuffer();if(!e)throw new Error("createFramebuffer returned null");return e}queryVitalParameters(){let e=this.gl;if(this.isFloatTextureAttachableToFrameBuffer=this.checkFloatTextureAttachableToFrameBuffer(),this.isRenderFloat32Supported=this.checkRenderFloat32(),this.isFloat32DownloadSupported=this.checkFloat32Download(),this.version===1&&!this.textureHalfFloatExtension&&!this.isRenderFloat32Supported)throw new Error("both float32 and float16 TextureType are not supported");this.isBlendSupported=!this.isRenderFloat32Supported||this.checkFloat32Blend(),this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.maxTextureImageUnits=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.version}getExtensions(){this.version===2?(this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float"),this.disjointTimerQueryWebgl2Extension=this.gl.getExtension("EXT_disjoint_timer_query_webgl2")):(this.textureFloatExtension=this.gl.getExtension("OES_texture_float"),this.textureHalfFloatExtension=this.gl.getExtension("OES_texture_half_float"))}checkFloatTextureAttachableToFrameBuffer(){let e=this.gl,n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let i=this.version===2?e.RGBA32F:e.RGBA;e.texImage2D(e.TEXTURE_2D,0,i,1,1,0,e.RGBA,e.FLOAT,null);let a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);let p=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(a),p}checkRenderFloat32(){if(this.version===2){if(!this.colorBufferFloatExtension)return!1}else if(!this.textureFloatExtension)return!1;return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Download(){if(this.version===2){if(!this.colorBufferFloatExtension)return!1}else if(!this.textureFloatExtension||!this.gl.getExtension("WEBGL_color_buffer_float"))return!1;return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Blend(){let e=this.gl,n,i,a,p,o;try{n=e.createTexture(),i=e.createFramebuffer(),e.bindTexture(e.TEXTURE_2D,n);let s=this.version===2?e.RGBA32F:e.RGBA;return e.texImage2D(e.TEXTURE_2D,0,s,1,1,0,e.RGBA,e.FLOAT,null),e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0),e.enable(e.BLEND),a=e.createShader(e.VERTEX_SHADER),!a||(e.shaderSource(a,"void main(){}"),e.compileShader(a),p=e.createShader(e.FRAGMENT_SHADER),!p)||(e.shaderSource(p,"precision highp float;void main(){gl_FragColor=vec4(0.5);}"),e.compileShader(p),o=e.createProgram(),!o)?!1:(e.attachShader(o,a),e.attachShader(o,p),e.linkProgram(o),e.useProgram(o),e.drawArrays(e.POINTS,0,1),e.getError()===e.NO_ERROR)}finally{e.disable(e.BLEND),o&&e.deleteProgram(o),a&&e.deleteShader(a),p&&e.deleteShader(p),i&&(e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(i)),n&&(e.bindTexture(e.TEXTURE_2D,null),e.deleteTexture(n))}}beginTimer(){if(this.version===2&&this.disjointTimerQueryWebgl2Extension){let e=this.gl,n=this.disjointTimerQueryWebgl2Extension,i=e.createQuery();return e.beginQuery(n.TIME_ELAPSED_EXT,i),i}else throw new Error("WebGL1 profiling currently not supported.")}endTimer(){if(this.version===2&&this.disjointTimerQueryWebgl2Extension){let e=this.gl,n=this.disjointTimerQueryWebgl2Extension;e.endQuery(n.TIME_ELAPSED_EXT);return}else throw new Error("WebGL1 profiling currently not supported")}isTimerResultAvailable(e){let n=!1,i=!1;if(this.version===2&&this.disjointTimerQueryWebgl2Extension){let a=this.gl,p=this.disjointTimerQueryWebgl2Extension;n=a.getQueryParameter(e,a.QUERY_RESULT_AVAILABLE),i=a.getParameter(p.GPU_DISJOINT_EXT)}else throw new Error("WebGL1 profiling currently not supported");return n&&!i}getTimerResult(e){let n=0;if(this.version===2){let i=this.gl;n=i.getQueryParameter(e,i.QUERY_RESULT),i.deleteQuery(e)}else throw new Error("WebGL1 profiling currently not supported");return n/1e6}async waitForQueryAndGetTime(e){return await li(()=>this.isTimerResultAvailable(e)),this.getTimerResult(e)}async createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let n,i=e,a=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),a===null?n=()=>!0:n=()=>{let p=i.clientWaitSync(a,0,0);return p===i.ALREADY_SIGNALED||p===i.CONDITION_SATISFIED},{query:a,isFencePassed:n}}async pollFence(e){return new Promise(n=>{this.addItemToPoll(()=>e.isFencePassed(),()=>n())})}pollItems(){let e=bg(this.itemsToPoll.map(n=>n.isDoneFn));for(let n=0;n<=e;++n){let{resolveFn:i}=this.itemsToPoll[n];i()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}async addItemToPoll(e,n){this.itemsToPoll.push({isDoneFn:e,resolveFn:n}),!(this.itemsToPoll.length>1)&&await li(()=>(this.pollItems(),this.itemsToPoll.length===0))}}});function Gi(e){let n;if((!e||e==="webgl2")&&"webgl2"in mr?n=mr.webgl2:(!e||e==="webgl")&&"webgl"in mr&&(n=mr.webgl),!n)try{let a=yg();n=vp(a,e)}catch{let a=gg();n=vp(a,e)}e=e||n.version===1?"webgl":"webgl2";let i=n.gl;return mr[e]=n,i.isContextLost()?(delete mr[e],Gi(e)):(i.disable(i.DEPTH_TEST),i.disable(i.STENCIL_TEST),i.disable(i.BLEND),i.disable(i.DITHER),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SAMPLE_COVERAGE),i.enable(i.SCISSOR_TEST),i.enable(i.CULL_FACE),i.cullFace(i.BACK),n)}function vp(e,n){let i={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1},a,p=i;if((!n||n==="webgl2")&&(a=e.getContext("webgl2",p),a))try{return new Mr(a,2)}catch(o){tt.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${o}`)}if((!n||n==="webgl")&&(a=e.getContext("webgl",p)||e.getContext("experimental-webgl",p),a))try{return new Mr(a,1)}catch(o){tt.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${o}`)}throw new Error("WebGL is not supported")}function gg(){if(typeof document>"u")throw new TypeError("failed to create canvas: document is not supported");let e=document.createElement("canvas");return e.width=1,e.height=1,e}function yg(){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}var mr,Ip=O(()=>{Ut(),wp(),mr={}}),Yn,_p=O(()=>{Yt(),Ut(),Tp(),Ip(),Yn=class{get contextId(){return z.webgl.contextId}set contextId(e){z.webgl.contextId=e}get matmulMaxBatchSize(){return z.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(e){z.webgl.matmulMaxBatchSize=e}get textureCacheMode(){return z.webgl.textureCacheMode}set textureCacheMode(e){z.webgl.textureCacheMode=e}get pack(){return z.webgl.pack}set pack(e){z.webgl.pack=e}get async(){return z.webgl.async}set async(e){z.webgl.async=e}initialize(){try{return this.glContext=Gi(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),tt.setWithEnv(z),z.webgl.context||Object.defineProperty(z.webgl,"context",{value:this.glContext.gl}),tt.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(e){return tt.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${e}`),!1}}createSessionHandler(e){return new Jn(this,e)}dispose(){this.glContext.dispose()}}});async function Mi(e){if(e){let n=typeof e=="string"?[e]:e;for(let i of n){let a=Op.get(i);if(a)return a;let p=await Tg(i);if(p)return p}}else return Mi(["webgl"]);throw new Error("no available backend to use")}async function Tg(e){let n=xg;if(typeof n[e]<"u"&&wg(n[e])){let i=n[e],a=i.initialize();if(typeof a=="object"&&"then"in a&&(a=await a),a)return Op.set(e,i),i}}function wg(e){let n=e;return"initialize"in n&&typeof n.initialize=="function"&&"createSessionHandler"in n&&typeof n.createSessionHandler=="function"&&"dispose"in n&&typeof n.dispose=="function"}var Op,xg,Sp=O(()=>{_p(),Op=new Map,xg={webgl:new Yn}}),Ui,Zn,Ap=O(()=>{Ut(),Ui=class{constructor(e,n){this.op=e,this.node=n}},Zn=class{constructor(e,n,i){this.graph=e,this.profiler=i,this.initialize(n)}initialize(e){this.profiler.event("session","ExecutionPlan.initialize",()=>{let n=this.graph.getNodes();if(n.length!==e.length)throw new Error("The size of nodes and OPs do not match.");this._ops=e.map((i,a)=>new Ui(i,n[a])),this.reset(),this._starter=[],this._ops.forEach((i,a)=>{let p=!0;for(let o of i.node.inputs)if(!this._values[o]&&this.graph.getInputIndices().indexOf(o)===-1){p=!1;break}p&&this._starter.push(a)})})}reset(){this._values=this.graph.getValues().map(e=>e.tensor)}async execute(e,n){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();let i=e.createInferenceHandler(),a=this.graph.getInputIndices();if(n.length!==a.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${n.length} expected: ${a.length}`);n.forEach((r,u)=>{let l=a[u];this._values[l]=r});let p=this._starter.slice(0),o=this.graph.getValues(),s=this.graph.getNodes(),d=0;for(;d<p.length;){let r=p[d++],u=this._ops[r],l=u.node.inputs.map(y=>this._values[y]);if(l.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${u.node}`);let h=l;tt.verbose("ExecPlan",`Running op:${u.node.name} (${h.map((y,_)=>`'${u.node.inputs[_]}': ${y.type}[${y.dims.join(",")}]`).join(", ")})`);let f=await this.profiler.event("node",u.node.name,async()=>u.op.impl(i,h,u.op.context));if(f.length!==u.node.outputs.length)throw new Error("the size of output does not match model definition.");f.forEach((y,_)=>{let I=u.node.outputs[_];if(this._values[I])throw new Error(`output [${I}] already has value: op:${u.node.name}`);this._values[I]=y});let m=new Set;f.forEach((y,_)=>{let I=u.node.outputs[_];for(let x of o[I].to){let P=s[x],N=!0;for(let R of P.inputs)if(!this._values[R]){N=!1;break}N&&m.add(x)}}),p.push(...m)}let c=[];for(let r=0;r<this.graph.getOutputIndices().length;r++){let u=this.graph.getOutputIndices()[r],l=this._values[u];if(l===void 0)throw new Error(`required output [${u}] does not have value`);u===0?await l.getData():l.data,c.push(l)}return tt.verbose("ExecPlan","disposing of inferenceHandler"),i.dispose(),c})}}}),q,Xt,Ur,Pp=O(()=>{Pr(),q=rr(sr()),We(),Y(),Xt=F.experimental.fbs,Ur=class Ie{constructor(n){if(this._attributes=new Map,n!=null){for(let i of n)i instanceof q.onnx.AttributeProto?this._attributes.set(i.name,[Ie.getValue(i),Ie.getType(i)]):i instanceof Xt.Attribute&&this._attributes.set(i.name(),[Ie.getValue(i),Ie.getType(i)]);if(this._attributes.size<n.length)throw new Error("duplicated attribute names")}}set(n,i,a){this._attributes.set(n,[a,i])}delete(n){this._attributes.delete(n)}getFloat(n,i){return this.get(n,"float",i)}getInt(n,i){return this.get(n,"int",i)}getString(n,i){return this.get(n,"string",i)}getTensor(n,i){return this.get(n,"tensor",i)}getFloats(n,i){return this.get(n,"floats",i)}getInts(n,i){return this.get(n,"ints",i)}getStrings(n,i){return this.get(n,"strings",i)}getTensors(n,i){return this.get(n,"tensors",i)}get(n,i,a){let p=this._attributes.get(n);if(p===void 0){if(a!==void 0)return a;throw new Error(`required attribute not found: ${n}`)}if(p[1]!==i)throw new Error(`type mismatch: expected ${i} but got ${p[1]}`);return p[0]}static getType(n){let i=n instanceof q.onnx.AttributeProto?n.type:n.type();switch(i){case q.onnx.AttributeProto.AttributeType.FLOAT:return"float";case q.onnx.AttributeProto.AttributeType.INT:return"int";case q.onnx.AttributeProto.AttributeType.STRING:return"string";case q.onnx.AttributeProto.AttributeType.TENSOR:return"tensor";case q.onnx.AttributeProto.AttributeType.FLOATS:return"floats";case q.onnx.AttributeProto.AttributeType.INTS:return"ints";case q.onnx.AttributeProto.AttributeType.STRINGS:return"strings";case q.onnx.AttributeProto.AttributeType.TENSORS:return"tensors";default:throw new Error(`attribute type is not supported yet: ${q.onnx.AttributeProto.AttributeType[i]}`)}}static getValue(n){let i=n instanceof q.onnx.AttributeProto?n.type:n.type();if(i===q.onnx.AttributeProto.AttributeType.GRAPH||i===q.onnx.AttributeProto.AttributeType.GRAPHS)throw new Error("graph attribute is not supported yet");let a=this.getValueNoCheck(n);if(i===q.onnx.AttributeProto.AttributeType.INT&&Rt.isLong(a))return Rt.longToNumber(a);if(i===q.onnx.AttributeProto.AttributeType.INTS){let p=a,o=new Array(p.length);for(let s=0;s<p.length;s++){let d=p[s];o[s]=Rt.longToNumber(d)}return o}if(i===q.onnx.AttributeProto.AttributeType.TENSOR)return n instanceof q.onnx.AttributeProto?bt.fromProto(a):bt.fromOrtTensor(a);if(i===q.onnx.AttributeProto.AttributeType.TENSORS){if(n instanceof q.onnx.AttributeProto)return a.map(p=>bt.fromProto(p));if(n instanceof Xt.Attribute)return a.map(p=>bt.fromOrtTensor(p))}return i===q.onnx.AttributeProto.AttributeType.STRING&&n instanceof q.onnx.AttributeProto?kr(a):i===q.onnx.AttributeProto.AttributeType.STRINGS&&n instanceof q.onnx.AttributeProto?a.map(kr):a}static getValueNoCheck(n){return n instanceof q.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(n):this.getValueNoCheckFromOrtFormat(n)}static getValueNoCheckFromOnnxFormat(n){switch(n.type){case q.onnx.AttributeProto.AttributeType.FLOAT:return n.f;case q.onnx.AttributeProto.AttributeType.INT:return n.i;case q.onnx.AttributeProto.AttributeType.STRING:return n.s;case q.onnx.AttributeProto.AttributeType.TENSOR:return n.t;case q.onnx.AttributeProto.AttributeType.GRAPH:return n.g;case q.onnx.AttributeProto.AttributeType.FLOATS:return n.floats;case q.onnx.AttributeProto.AttributeType.INTS:return n.ints;case q.onnx.AttributeProto.AttributeType.STRINGS:return n.strings;case q.onnx.AttributeProto.AttributeType.TENSORS:return n.tensors;case q.onnx.AttributeProto.AttributeType.GRAPHS:return n.graphs;default:throw new Error(`unsupported attribute type: ${q.onnx.AttributeProto.AttributeType[n.type]}`)}}static getValueNoCheckFromOrtFormat(n){switch(n.type()){case Xt.AttributeType.FLOAT:return n.f();case Xt.AttributeType.INT:return n.i();case Xt.AttributeType.STRING:return n.s();case Xt.AttributeType.TENSOR:return n.t();case Xt.AttributeType.GRAPH:return n.g();case Xt.AttributeType.FLOATS:return n.floatsArray();case Xt.AttributeType.INTS:{let i=[];for(let a=0;a<n.intsLength();a++)i.push(n.ints(a));return i}case Xt.AttributeType.STRINGS:{let i=[];for(let a=0;a<n.stringsLength();a++)i.push(n.strings(a));return i}case Xt.AttributeType.TENSORS:{let i=[];for(let a=0;a<n.tensorsLength();a++)i.push(n.tensors(a));return i}default:throw new Error(`unsupported attribute type: ${Xt.AttributeType[n.type()]}`)}}}}),zi,Qn,Wi,me,to,Vi,Ep=O(()=>{Pp(),Pr(),zi=rr(sr()),We(),Y(),Qn=F.experimental.fbs,Wi={from:(e,n)=>new Vi(e,n)},me=class{constructor(e){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,e&&(this.type=At.tensorValueTypeFromProto(e.type.tensorType))}get from(){return this._from}get to(){return this._to}},to=class{constructor(e,n){e instanceof zi.onnx.NodeProto?(this.name=e.name,this.opType=e.opType,this.attributes=new Ur(e.attribute)):e instanceof Qn.Node&&(this.name=n??e.name(),this.opType=e.opType(),this.attributes=new Ur(At.tensorAttributesFromORTFormat(e))),this.inputs=[],this.outputs=[],this.executeNode=!0}},Vi=class{constructor(e,n){if(!e)throw new TypeError("graph is empty");this.buildGraph(e),this.transformGraph(n),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(e){if(e instanceof zi.onnx.GraphProto)this.buildGraphFromOnnxFormat(e);else if(e instanceof Qn.Graph)this.buildGraphFromOrtFormat(e);else throw new TypeError("Graph type is not supported.")}buildGraphFromOnnxFormat(e){let n=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let i=new Map;if(!e.input)throw new Error("missing information in graph: input");let a=[];for(let p of e.input){if(n.has(p.name))throw new Error(`duplicated input name: ${p.name}`);let o=this._allData.push(new me(p))-1;n.set(p.name,o),a.push(p.name)}if(!e.initializer)throw new Error("missing information in graph: initializer");for(let p of e.initializer){let o=n.get(p.name);if(o===void 0){let s=new me;s.type={shape:{dims:At.tensorDimsFromProto(p.dims)},tensorType:At.tensorDataTypeFromProto(p.dataType)},o=this._allData.push(s)-1,n.set(p.name,o)}this._allData[o]._from=-1,this._allData[o].tensor=bt.fromProto(p)}for(let p=0;p<this._allData.length;p++)this._allData[p].tensor||(this._allInputIndices.push(p),this._allInputNames.push(a[p]));if(!e.output)throw new Error("missing information in graph: output");for(let p of e.output){if(n.has(p.name))throw new Error(`duplicated output name: ${p.name}`);let o=this._allData.push(new me(p))-1;n.set(p.name,o),this._allOutputIndices.push(o),this._allOutputNames.push(p.name)}if(!e.node)throw new Error("missing information in graph: node");for(let p of e.node){if(!p.name)for(let s=0;;s++){let d=`unnamed_${p.opType}_${s}`;if(!i.has(d)){p.name=d;break}}if(i.has(p.name))throw new Error(`duplicated node name: ${p.name}`);let o=this._nodes.push(new to(p))-1;i.set(p.name,o)}for(let p=0;p<this._nodes.length;p++){let o=this._nodes[p],s=e.node[p];if(!s.output)throw new Error(`missing output for node: ${s.name}`);for(let d of s.output){let c=n.get(d);if(typeof c>"u"&&(c=this._allData.push(new me)-1,n.set(d,c)),o.outputs.push(c),this._allData[c]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${c}`);if(this._allData[c]._from=p,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");o.outputs.pop(),o.executeNode=!1,this._allData[c]._from=-1,this._allData[c].tensor=bt.fromProto(s.attribute[0].t)}}}for(let p=0;p<this._nodes.length;p++){let o=this._nodes[p],s=e.node[p];if(!s.input)throw new Error(`missing input for node: ${s.name}`);for(let d of s.input){let c=n.get(d);if(typeof c>"u"){if(d===""&&(s.input.length===3||s.input.length===4)&&s.opType==="Resize")continue;throw new Error(`unrecognized input '${d}' for node: ${s.name}`)}o.inputs.push(c),this._allData[c]._to.push(p)}}return!0}buildGraphFromOrtFormat(e){var p,o,s;let n=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let i=new Map,a=[];for(let d=0;d<e.inputsLength();d++){let c=e.inputs(d);if(n.has(c))throw new Error(`duplicated input name: ${c}`);for(let r=0;r<e.nodeArgsLength();r++)if(((p=e.nodeArgs(r))==null?void 0:p.name())===c){let u=new me;if(((s=(o=e.nodeArgs(r))==null?void 0:o.type())==null?void 0:s.valueType())!==Qn.TypeInfoValue.tensor_type)throw new Error("Unexpected value type for the nodeArg.");let l=e.nodeArgs(r).type().value(new Qn.TensorTypeAndShape),h=At.tensorDataTypeFromProto(l.elemType()),f=l.shape(),m=[];for(let _=0;_<f.dimLength();_++)m.push(Rt.longToNumber(f.dim(_).value().dimValue()));u.type={shape:{dims:m},tensorType:h};let y=this._allData.push(u)-1;n.set(c,y),a.push(c)}}for(let d=0;d<e.initializersLength();d++){let c=e.initializers(d),r=n.get(c.name());if(r===void 0){let u=new me,l=At.tensorDimsFromORTFormat(c),h=At.tensorDataTypeFromProto(c.dataType());u.type={shape:{dims:l},tensorType:h},r=this._allData.push(u)-1,n.set(c.name(),r)}this._allData[r]._from=-1,this._allData[r].tensor=bt.fromOrtTensor(c)}for(let d=0;d<this._allData.length;d++)this._allData[d].tensor||(this._allInputIndices.push(d),this._allInputNames.push(a[d]));for(let d=0;d<e.outputsLength();d++){let c=e.outputs(d);if(n.has(c))throw new Error(`duplicated output name: ${c}`);let r=this._allData.push(new me)-1;n.set(c,r),this._allOutputIndices.push(r),this._allOutputNames.push(c)}if(!e.nodes)throw new Error("missing information in graph: node");for(let d=0;d<e.nodesLength();d++){let c=e.nodes(d),r=c.name();if(!r)for(let l=0;r=`unnamed_${c.opType()}_${l}`,!!i.has(r);l++);if(i.has(r))throw new Error(`duplicated node name: ${r}`);let u=this._nodes.push(new to(c,r))-1;i.set(r,u)}for(let d=0;d<this._nodes.length;d++){let c=this._nodes[d],r=e.nodes(d);if(r==null)throw new Error(`No node exists at index ${d}`);if((r==null?void 0:r.outputsLength())===0)throw new Error(`missing output for node: ${r.name}`);for(let u=0;u<(r==null?void 0:r.outputsLength());u++){let l=r==null?void 0:r.outputs(u),h=n.get(l);if(typeof h>"u"&&(h=this._allData.push(new me)-1,n.set(l,h)),c.outputs.push(h),this._allData[h]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${h}`);if(this._allData[h]._from=d,r.opType()==="Constant"){if(r.attributesLength()!==1||!r.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(r.outputsLength()!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");c.outputs.pop(),c.executeNode=!1,this._allData[h]._from=-1,this._allData[h].tensor=bt.fromOrtTensor(r.attributes(0).t())}}}for(let d=0;d<this._nodes.length;d++){let c=this._nodes[d],r=e.nodes(d);if(r.inputsLength()===0)throw new Error(`missing input for node: ${r.name}`);for(let u=0;u<r.inputsLength();u++){let l=r.inputs(u),h=n.get(l);if(typeof h>"u")throw new Error(`unrecognized input '${l}' for node: ${r.name()}`);c.inputs.push(h),this._allData[h]._to.push(d)}}}checkIsAcyclic(){let e=new Set;this._allInputIndices.forEach(a=>{this._allData[a]._to.forEach(p=>{e.add(p)})});let n=Array.from(e),i=new Array(this._nodes.length).fill("white");for(;n.length>0;){let a=n.pop();i[a]==="gray"?i[a]="black":(n.push(a),i[a]="gray",this._nodes[a].outputs.forEach(p=>{let o=this._allData[p];if(typeof o.tensor<"u")throw new Error("node outputs should not be initialized");if(o._from!==a)throw new Error("from property of the Value object doesn't match index of Node being processed");o._to.forEach(s=>{if(i[s]==="gray")throw new Error("model graph is cyclic");i[s]==="white"&&n.push(s)})}))}}transformGraph(e){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),e&&e.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let e=0,n=new Array(this._nodes.length,0),i=0;for(let a=0;a<this._nodes.length;a++)n[a]=i,this._nodes[a].executeNode?(i!==a&&(this._nodes[i]=this._nodes[a]),i++):this._nodes[a].outputs.forEach(p=>{this._allData[p]._from=-2});this._nodes.splice(i,this._nodes.length-i);for(let a=0;a<this._allData.length;a++){let p=this._allData[a];p._from!==void 0&&p._from!==-1&&p._from!==-2&&(p._from=n[p._from]);for(let o=0;o<p._to.length;o++)if(p._to[o]>=0)p._to[o]=n[p._to[o]];else throw new Error("Trying to update a removed node")}e=0;for(let a=0;a<this._allData.length;a++){if(this._allData[a].from===-2&&this._allOutputIndices.indexOf(a+e)===-1){e++,this._allData.splice(a,1),a--;continue}if(e>0){let p=-1;this._allData[a].from!==void 0&&this._allData[a].from!==-1?(p=this._nodes[this._allData[a].from].outputs.indexOf(a+e),p!==-1&&(this._nodes[this._allData[a].from].outputs[p]=a)):(p=this._allInputIndices.indexOf(a+e),p!==-1&&(this._allInputIndices[p]=a)),this._allData[a].to.forEach(o=>{p=this._nodes[o].inputs.indexOf(a+e),p!==-1&&(this._nodes[o].inputs[p]=a)}),this._allData[a].to.length===0&&(p=this._allOutputIndices.indexOf(a+e),p!==-1&&(this._allOutputIndices[p]=a))}}}deleteNode(e){let n=this._nodes[e];if(n.outputs.length>1){for(let s=1;s<n.outputs.length;s++)if(this._allData[n.outputs[s]].to.length>0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}n.executeNode=!1;let i=n.inputs[0],a=n.outputs[0],p=this._allData[a].to;for(let s=0;s<n.inputs.length;s++){let d=this._allData[n.inputs[s]].to.indexOf(e);if(d===-1)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[n.inputs[s]].to.splice(d,1)}this._allData[a]._to=[];let o=this._allOutputIndices.indexOf(a);if(o!==-1&&(this._allOutputIndices[o]=i),p&&p.length>0)for(let s of p){let d=this._nodes[s].inputs.indexOf(a);if(d===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[s].inputs[d]=i,this._allData[i].to.push(s)}}removeAllDropoutNodes(){let e=0;for(let n of this._nodes){if(n.opType==="Dropout"){if(n.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(n.outputs.length!==1&&n.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(n.outputs.length===2&&this._allData[n.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(e)}e++}}removeAllIdentityNodes(){let e=0;for(let n of this._nodes)n.opType==="Identity"&&this.deleteNode(e),e++}isActivation(e){switch(e.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(let e of this._nodes)if(e.opType==="Conv"){let n=this._allData[e.outputs[0]]._to;if(n.length===1&&this.isActivation(this._nodes[n[0]])){let i=this._nodes[n[0]];if(i.opType==="Clip")if(i.inputs.length===1)try{e.attributes.set("activation_params","floats",[i.attributes.getFloat("min"),i.attributes.getFloat("max")])}catch{e.attributes.set("activation_params","floats",[Ve,ze])}else if(i.inputs.length>=3&&this._allData[i.inputs[1]].tensor!==void 0&&this._allData[i.inputs[2]].tensor!==void 0)e.attributes.set("activation_params","floats",[this._allData[i.inputs[1]].tensor.floatData[0],this._allData[i.inputs[2]].tensor.floatData[0]]);else continue;e.attributes.set("activation","string",i.opType),this.deleteNode(n[0])}}}}}),Dp,vg,eo,Lp=O(()=>{wn(),Ep(),Pr(),Dp=rr(sr()),Y(),vg=F.experimental.fbs,eo=class{constructor(){}load(e,n,i){let a;if(!i)try{this.loadFromOnnxFormat(e,n);return}catch(p){if(i!==void 0)throw p;a=p}try{this.loadFromOrtFormat(e,n)}catch(p){throw i!==void 0?p:new Error(`Failed to load model as ONNX format: ${a}
1806
- as ORT format: ${p}`)}}loadFromOnnxFormat(e,n){let i=Dp.onnx.ModelProto.decode(e);if(Rt.longToNumber(i.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=i.opsetImport.map(a=>({domain:a.domain,version:Rt.longToNumber(a.version)})),this._graph=Wi.from(i.graph,n)}loadFromOrtFormat(e,n){let i=new w.ByteBuffer(e),a=vg.InferenceSession.getRootAsInferenceSession(i).model();if(Rt.longToNumber(a.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let p=0;p<a.opsetImportLength();p++){let o=a.opsetImport(p);this._opsets.push({domain:o==null?void 0:o.domain(),version:Rt.longToNumber(o.version())})}this._graph=Wi.from(a.graph(),n)}get graph(){return this._graph}get opsets(){return this._opsets}}}),ro,$p=O(()=>{Sp(),Ap(),Ut(),Lp(),ro=class{constructor(e={}){this._initialized=!1,this.backendHint=e.backendHint,this.profiler=xn.create(e.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(e,n,i){await this.profiler.event("session","Session.loadModel",async()=>{let a=await Mi(this.backendHint);if(this.sessionHandler=a.createSessionHandler(this.context),this._model=new eo,typeof e=="string"){let p=e.endsWith(".ort");{let o=await(await fetch(e)).arrayBuffer();this.initialize(new Uint8Array(o),p)}}else if(ArrayBuffer.isView(e))this.initialize(e);else{let p=new Uint8Array(e,n||0,i||e.byteLength);this.initialize(p)}})}initialize(e,n){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{let i=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(e,i,n),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new Zn(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(e){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{let n=this.normalizeAndValidateInputs(e),i=await this._executionPlan.execute(this.sessionHandler,n);return this.createOutput(i)})}normalizeAndValidateInputs(e){let n=this._model.graph.getInputNames();if(Array.isArray(e)){if(e.length!==n.length)throw new Error(`incorrect input array length: expected ${n.length} but got ${e.length}`)}else{if(e.size!==n.length)throw new Error(`incorrect input map size: expected ${n.length} but got ${e.size}`);let i=new Array(e.size),a=0;for(let p=0;p<n.length;++p){let o=e.get(n[p]);if(!o)throw new Error(`missing input tensor for: '${name}'`);i[a++]=o}e=i}if(!this.context.graphInputTypes||this.context.graphInputTypes.length===0||!this.context.graphInputDims||this.context.graphInputDims.length===0){let i=this._model.graph.getInputIndices(),a=this._model.graph.getValues(),p=new Array(i.length);for(let o=0;o<i.length;++o){let s=a[i[o]];p[o]=s.type.shape.dims,this.context.graphInputTypes.push(s.type.tensorType),this.context.graphInputDims.push(e[o].dims)}this.validateInputTensorDims(p,e,!0)}else this.validateInputTensorDims(this.context.graphInputDims,e,!1);return this.validateInputTensorTypes(this.context.graphInputTypes,e),e}validateInputTensorTypes(e,n){for(let i=0;i<n.length;i++){let a=e[i],p=n[i].type;if(a!==p)throw new Error(`input tensor[${i}] check failed: expected type '${a}' but got ${p}`)}}validateInputTensorDims(e,n,i){for(let a=0;a<n.length;a++){let p=e[a],o=n[a].dims;if(!this.compareTensorDims(p,o,i))throw new Error(`input tensor[${a}] check failed: expected shape '[${p.join(",")}]' but got [${o.join(",")}]`)}}compareTensorDims(e,n,i){if(e.length!==n.length)return!1;for(let a=0;a<e.length;++a)if(e[a]!==n[a]&&(!i||e[a]!==0))return!1;return!0}createOutput(e){let n=this._model.graph.getOutputNames();if(e.length!==n.length)throw new Error("expected number of outputs do not match number of generated outputs");let i=new Map;for(let a=0;a<n.length;++a)i.set(n[a],e[a]);return i}initializeOps(e){let n=e.getNodes();this._ops=new Array(n.length);for(let i=0;i<n.length;i++)this._ops[i]=this.sessionHandler.resolve(n[i],this._model.opsets,e)}}}),no,kp=O(()=>{Yt(),We(),no=class{constructor(e){this.session=e,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(e,n,i){let a=new Map;for(let s in e)if(Object.hasOwnProperty.call(e,s)){let d=e[s];a.set(s,new bt(d.dims,d.type,void 0,void 0,d.data))}let p=await this.session.run(a),o={};return p.forEach((s,d)=>{o[d]=new yt(s.type,s.data,s.dims)}),o}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}}),Bp={};Or(Bp,{onnxjsBackend:()=>Ig});var Hi,Ig,Fp=O(()=>{$p(),kp(),Hi=class{async init(){}async createInferenceSessionHandler(e,n){let i=new ro(n);return typeof e=="string"?await i.loadModel(e):await i.loadModel(e),new no(i)}},Ig=new Hi}),oo=O(()=>{}),Rp={};Or(Rp,{default:()=>_g});var Cp,Np,_g,Gp=O(()=>{var e;qi(),Ke(),Vr(),Cp="ort-wasm-proxy-worker",Np=((e=globalThis.self)==null?void 0:e.name)===Cp,Np&&(self.onmessage=n=>{let{type:i,in:a}=n.data;try{switch(i){case"init-wasm":io(a.wasm).then(()=>{ao(a).then(()=>{postMessage({type:i})},p=>{postMessage({type:i,err:p})})},p=>{postMessage({type:i,err:p})});break;case"init-ep":{let{epName:p,env:o}=a;so(o,p).then(()=>{postMessage({type:i})},s=>{postMessage({type:i,err:s})});break}case"copy-from":{let{buffer:p}=a,o=zr(p);postMessage({type:i,out:o});break}case"create":{let{model:p,options:o}=a;uo(p,o).then(s=>{postMessage({type:i,out:s})},s=>{postMessage({type:i,err:s})});break}case"release":lo(a),postMessage({type:i});break;case"run":{let{sessionId:p,inputIndices:o,inputs:s,outputIndices:d,options:c}=a;fo(p,o,s,d,new Array(d.length).fill(null),c).then(r=>{r.some(u=>u[3]!=="cpu")?postMessage({type:i,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:i,out:r},po([...s,...r]))},r=>{postMessage({type:i,err:r})});break}case"end-profiling":co(a),postMessage({type:i});break;default:}}catch(p){postMessage({type:i,err:p})}}),_g=Np?null:n=>new Worker(n??br,{type:"module",name:Cp})}),Up={};Or(Up,{default:()=>Og});var ji,Mp,Og,Vp=O(()=>{var e;Mp=(ji=_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("segmentation.js",document.baseURI).href,async function(n={}){function i(){return ft.buffer!=gt.buffer&&it(),gt}function a(){return ft.buffer!=gt.buffer&&it(),U}function p(){return ft.buffer!=gt.buffer&&it(),Mt}function o(){return ft.buffer!=gt.buffer&&it(),De}function s(){return ft.buffer!=gt.buffer&&it(),ae}var d,c,r=Object.assign({},n),u=new Promise((g,b)=>{d=g,c=b}),l=typeof window=="object",h=typeof importScripts=="function",f=h&&self.name=="em-pthread";r.mountExternalData=(g,b)=>{g.startsWith("./")&&(g=g.substring(2)),(r.Ua||(r.Ua=new Map)).set(g,b)},r.unmountExternalData=()=>{delete r.Ua};var m,y,_=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor,I=Object.assign({},r),x="./this.program",P=(g,b)=>{throw b},N="";(l||h)&&(h?N=self.location.href:typeof document<"u"&&document.currentScript&&(N=document.currentScript.src),ji&&(N=ji),N=N.startsWith("blob:")?"":N.substr(0,N.replace(/[?#].*/,"").lastIndexOf("/")+1),h&&(y=g=>{var b=new XMLHttpRequest;return b.open("GET",g,!1),b.responseType="arraybuffer",b.send(null),new Uint8Array(b.response)}),m=(g,b,v)=>{var S=new XMLHttpRequest;S.open("GET",g,!0),S.responseType="arraybuffer",S.onload=()=>{S.status==200||S.status==0&&S.response?b(S.response):v()},S.onerror=v,S.send(null)});var R,ct=console.log.bind(console),st=console.error.bind(console),Dt=ct,Z=st;if(Object.assign(r,I),I=null,f){let g=function(b){try{var v=b.data,S=v.cmd;if(S==="load"){let E=[];self.onmessage=$=>E.push($),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let $ of E)g($);self.onmessage=g};for(let $ of v.handlers)r[$]&&!r[$].proxy||(r[$]=(...L)=>{postMessage({Za:"callHandler",kb:$,args:L})},$=="print"&&(Dt=r[$]),$=="printErr"&&(Z=r[$]));ft=v.wasmMemory,it(),Ot(v.wasmModule)}else if(S==="run"){Jr(v.pthread_ptr,0,0,1,0,0),Ir(v.pthread_ptr),Ia(),_o(),Ae||(Ae=!0);try{Pa(v.start_routine,v.arg)}catch(E){if(E!="unwind")throw E}}else S==="cancel"?le()&&er(-1):v.target!=="setimmediate"&&(S==="checkMailbox"?Ae&&Ze():S&&(Z(`worker: received unknown command ${S}`),Z(v)))}catch(E){throw ga(),E}};var Ot,Ae=!1;Z=function(...b){b=b.join(" "),console.error(b)},self.alert=function(...b){postMessage({Za:"alert",text:b.join(" "),nb:le()})},r.instantiateWasm=(b,v)=>new Promise(S=>{Ot=E=>{E=new WebAssembly.Instance(E,nn()),v(E),S()}}),self.onunhandledrejection=b=>{throw b.reason||b},self.onmessage=g}r.wasmBinary&&(R=r.wasmBinary);var ft,$e,Nt,gt,U,Mt,De,vt,ae,nt=!1;function it(){var g=ft.buffer;r.HEAP8=gt=new Int8Array(g),r.HEAP16=new Int16Array(g),r.HEAPU8=U=new Uint8Array(g),r.HEAPU16=new Uint16Array(g),r.HEAP32=Mt=new Int32Array(g),r.HEAPU32=De=new Uint32Array(g),r.HEAPF32=new Float32Array(g),r.HEAPF64=ae=new Float64Array(g),r.HEAP64=vt=new BigInt64Array(g),r.HEAPU64=new BigUint64Array(g)}if(!f){if(!((ft=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof _))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"),Error("bad memory");it()}var ee=[],Wt=[],Le=[],re=0,_t=null;function Pt(){if(--re==0&&_t){var g=_t;_t=null,g()}}function Ft(g){throw Z(g="Aborted("+g+")"),nt=!0,Nt=1,g=new WebAssembly.RuntimeError(g+". Build with -sASSERTIONS for more info."),c(g),g}var et,at=g=>g.startsWith("data:application/octet-stream;base64,"),Lt=g=>g.startsWith("file://");function ue(g){if(g==et&&R)return new Uint8Array(R);if(y)return y(g);throw"both async and sync fetching of the wasm failed"}function Re(g,b,v){return function(S){if(!R&&(l||h)){if(typeof fetch=="function"&&!Lt(S))return fetch(S,{credentials:"same-origin"}).then(E=>{if(!E.ok)throw`failed to load wasm binary file at '${S}'`;return E.arrayBuffer()}).catch(()=>ue(S));if(m)return new Promise((E,$)=>{m(S,L=>E(new Uint8Array(L)),$)})}return Promise.resolve().then(()=>ue(S))}(g).then(S=>WebAssembly.instantiate(S,b)).then(v,S=>{Z(`failed to asynchronously prepare wasm: ${S}`),Ft(S)})}function nn(){return{a:{j:Ea,b:$a,E:Po,g:Do,V:ko,A:jo,C:Bo,W:zo,T:Xo,L:Ko,S:Yo,o:Jo,B:Zo,y:Qo,U:ti,z:ri,_:Da,Z:ka,P:Na,w:Fa,F:Ca,k:La,O:Ir,Y:Ra,I:ja,J:Ba,K:Ma,G:ea,H:ra,v:Va,q:za,l:Ua,p:Ga,e:Ha,X:qa,x:Wa,d:na,f:Xa,i:Ka,u:Ya,t:Ja,s:Za,Q:aa,R:sa,D:Er,h:la,n:ua,M:pa,m:da,a:ft,r:_r,N:fa,c:Ks}}}var on={837620:(g,b,v,S,E)=>{if(r===void 0||!r.Ua)return 1;if((g=fe(g>>>0)).startsWith("./")&&(g=g.substring(2)),!(g=r.Ua.get(g)))return 2;if(S>>>=0,(b>>>=0)+(v>>>=0)>g.byteLength)return 3;try{let $=g.subarray(b,b+v);switch(E){case 0:a().set($,S>>>0);break;case 1:r.mb(S,$);break;default:return 4}return 0}catch{return 4}},838303:()=>typeof wasmOffsetConverter<"u"};function Ea(){return typeof wasmOffsetConverter<"u"}function wr(g){this.name="ExitStatus",this.message=`Program terminated with exit(${g})`,this.status=g}var vr=g=>{g.terminate(),g.onmessage=()=>{}},vn=g=>{Jt.length==0&&(So(),Oo(Jt[0]));var b=Jt.pop();if(!b)return 6;oe.push(b),$t[g.Ra]=b,b.Ra=g.Ra;var v={cmd:"run",start_routine:g.cb,arg:g.ab,pthread_ptr:g.Ra};return b.postMessage(v,g.ib),0},ce=0,K=(g,b,...v)=>{for(var S=2*v.length,E=tn(),$=Qr(8*S),L=$>>>3,X=0;X<v.length;X++){var lt=v[X];typeof lt=="bigint"?(vt[L+2*X]=1n,vt[L+2*X+1]=lt):(vt[L+2*X]=0n,s()[L+2*X+1>>>0]=lt)}return g=ma(g,0,S,$,b),ar(E),g};function _r(g){if(f)return K(0,1,g);if(Nt=g,!(0<ce)){for(var b of oe)vr(b);for(b of Jt)vr(b);Jt=[],oe=[],$t=[],nt=!0}P(g,new wr(g))}function _n(g){if(f)return K(1,0,g);Er(g)}var Er=g=>{if(Nt=g,f)throw _n(g),"unwind";_r(g)},Jt=[],oe=[],On=[],$t={},In=g=>{var b=g.Ra;delete $t[b],Jt.push(g),oe.splice(oe.indexOf(g),1),g.Ra=0,Zr(b)};function _o(){On.forEach(g=>g())}var Oo=g=>new Promise(b=>{g.onmessage=E=>{var $=(E=E.data).cmd;if(E.targetThread&&E.targetThread!=le()){var L=$t[E.targetThread];L?L.postMessage(E,E.transferList):Z(`Internal error! Worker sent a message "${$}" to target pthread ${E.targetThread}, but that thread no longer exists!`)}else $==="checkMailbox"?Ze():$==="spawnThread"?vn(E):$==="cleanupThread"?In($t[E.thread]):$==="killThread"?(E=E.thread,$=$t[E],delete $t[E],vr($),Zr(E),oe.splice(oe.indexOf($),1),$.Ra=0):$==="cancelThread"?$t[E.thread].postMessage({cmd:"cancel"}):$==="loaded"?(g.loaded=!0,b(g)):$==="alert"?alert(`Thread ${E.threadId}: ${E.text}`):E.target==="setimmediate"?g.postMessage(E):$==="callHandler"?r[E.handler](...E.args):$&&Z(`worker sent an unknown command ${$}`)},g.onerror=E=>{throw Z(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var v,S=[];for(v of[])r.hasOwnProperty(v)&&S.push(v);g.postMessage({cmd:"load",handlers:S,wasmMemory:ft,wasmModule:$e})});function So(){var g=new Worker(new URL(_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("segmentation.js",document.baseURI).href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Jt.push(g)}var Eo,Ge=g=>{for(;0<g.length;)g.shift()(r)},Ia=()=>{var g=le(),b=o()[g+52>>>2>>>0];g=o()[g+56>>>2>>>0],ya(b,b-g),ar(b)},Ye=[],Pa=(g,b)=>{ce=0;var v=Ye[g];v||(g>=Ye.length&&(Ye.length=g+1),Ye[g]=v=Eo.get(g)),g=v(b),0<ce?Nt=g:er(g)};class Aa{constructor(b){this.Xa=b-24}}function $a(g,b,v){var S=new Aa(g>>>=0);throw b>>>=0,v>>>=0,o()[S.Xa+16>>>2>>>0]=0,o()[S.Xa+4>>>2>>>0]=b,o()[S.Xa+8>>>2>>>0]=v,g}function Io(g,b,v,S){return f?K(2,1,g,b,v,S):Po(g,b,v,S)}function Po(g,b,v,S){if(g>>>=0,b>>>=0,v>>>=0,S>>>=0,_===void 0)return Z("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var E=[];return f&&E.length===0?Io(g,b,v,S):(g={cb:v,Ra:g,ab:S,ib:E},f?(g.Za="spawnThread",postMessage(g,E),0):vn(g))}var Ao=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,$o=(g,b,v)=>{var S=(b>>>=0)+v;for(v=b;g[v]&&!(v>=S);)++v;if(16<v-b&&g.buffer&&Ao)return Ao.decode(g.buffer instanceof _?g.slice(b,v):g.subarray(b,v));for(S="";b<v;){var E=g[b++];if(128&E){var $=63&g[b++];if((224&E)==192)S+=String.fromCharCode((31&E)<<6|$);else{var L=63&g[b++];65536>(E=(240&E)==224?(15&E)<<12|$<<6|L:(7&E)<<18|$<<12|L<<6|63&g[b++])?S+=String.fromCharCode(E):(E-=65536,S+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else S+=String.fromCharCode(E)}return S},fe=(g,b)=>(g>>>=0)?$o(a(),g,b):"";function Do(g,b,v){return f?K(3,1,g,b,v):0}function ko(g,b){if(f)return K(4,1,g,b)}var Fo=g=>{for(var b=0,v=0;v<g.length;++v){var S=g.charCodeAt(v);127>=S?b++:2047>=S?b+=2:55296<=S&&57343>=S?(b+=4,++v):b+=3}return b},Lo=(g,b,v,S)=>{if(!(0<S))return 0;var E=v>>>=0;S=v+S-1;for(var $=0;$<g.length;++$){var L=g.charCodeAt($);if(55296<=L&&57343>=L&&(L=65536+((1023&L)<<10)|1023&g.charCodeAt(++$)),127>=L){if(v>=S)break;b[v++>>>0]=L}else{if(2047>=L){if(v+1>=S)break;b[v++>>>0]=192|L>>6}else{if(65535>=L){if(v+2>=S)break;b[v++>>>0]=224|L>>12}else{if(v+3>=S)break;b[v++>>>0]=240|L>>18,b[v++>>>0]=128|L>>12&63}b[v++>>>0]=128|L>>6&63}b[v++>>>0]=128|63&L}}return b[v>>>0]=0,v-E},ge=(g,b,v)=>Lo(g,a(),b,v);function jo(g,b){if(f)return K(5,1,g,b)}function Bo(g,b,v){if(f)return K(6,1,g,b,v)}function zo(g,b,v){return f?K(7,1,g,b,v):0}function Xo(g,b){if(f)return K(8,1,g,b)}function Ko(g,b,v){if(f)return K(9,1,g,b,v)}function Yo(g,b,v,S){if(f)return K(10,1,g,b,v,S)}function Jo(g,b,v,S){if(f)return K(11,1,g,b,v,S)}function Zo(g,b,v,S){if(f)return K(12,1,g,b,v,S)}function Qo(g){if(f)return K(13,1,g)}function ti(g,b){if(f)return K(14,1,g,b)}function ri(g,b,v){if(f)return K(15,1,g,b,v)}var Da=()=>{Ft("")},ka=()=>1;function Na(g){Jr(g>>>0,!h,1,!l,131072,!1),_o()}function Ir(g){g>>>=0,typeof Atomics.jb=="function"&&(Atomics.jb(p(),g>>>2,g).value.then(Ze),g+=128,Atomics.store(p(),g>>>2,1))}var Ze=()=>{var g=le();if(g&&(Ir(g),g=ba,!nt))try{if(g(),!(0<ce))try{f?er(Nt):Er(Nt)}catch(b){b instanceof wr||b=="unwind"||P(1,b)}}catch(b){b instanceof wr||b=="unwind"||P(1,b)}};function Fa(g,b){(g>>>=0)==b>>>0?setTimeout(Ze):f?postMessage({targetThread:g,cmd:"checkMailbox"}):(g=$t[g])&&g.postMessage({cmd:"checkMailbox"})}var Dr=[];function Ca(g,b,v,S,E){for(b>>>=0,S/=2,Dr.length=S,v=E>>>0>>>3,E=0;E<S;E++)Dr[E]=vt[v+2*E]?vt[v+2*E+1]:s()[v+2*E+1>>>0];return(b?on[b]:Js[g])(...Dr)}function La(g){g>>>=0,f?postMessage({cmd:"cleanupThread",thread:g}):In($t[g])}function Ra(g){}function ja(g,b){g=-9007199254740992>g||9007199254740992<g?NaN:Number(g),b>>>=0,g=new Date(1e3*g),p()[b>>>2>>>0]=g.getUTCSeconds(),p()[b+4>>>2>>>0]=g.getUTCMinutes(),p()[b+8>>>2>>>0]=g.getUTCHours(),p()[b+12>>>2>>>0]=g.getUTCDate(),p()[b+16>>>2>>>0]=g.getUTCMonth(),p()[b+20>>>2>>>0]=g.getUTCFullYear()-1900,p()[b+24>>>2>>>0]=g.getUTCDay(),g=(g.getTime()-Date.UTC(g.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,p()[b+28>>>2>>>0]=g}var se=g=>g%4==0&&(g%100!=0||g%400==0),ni=[0,31,60,91,121,152,182,213,244,274,305,335],ii=[0,31,59,90,120,151,181,212,243,273,304,334];function Ba(g,b){g=-9007199254740992>g||9007199254740992<g?NaN:Number(g),b>>>=0,g=new Date(1e3*g),p()[b>>>2>>>0]=g.getSeconds(),p()[b+4>>>2>>>0]=g.getMinutes(),p()[b+8>>>2>>>0]=g.getHours(),p()[b+12>>>2>>>0]=g.getDate(),p()[b+16>>>2>>>0]=g.getMonth(),p()[b+20>>>2>>>0]=g.getFullYear()-1900,p()[b+24>>>2>>>0]=g.getDay();var v=(se(g.getFullYear())?ni:ii)[g.getMonth()]+g.getDate()-1|0;p()[b+28>>>2>>>0]=v,p()[b+36>>>2>>>0]=-60*g.getTimezoneOffset(),v=new Date(g.getFullYear(),6,1).getTimezoneOffset();var S=new Date(g.getFullYear(),0,1).getTimezoneOffset();g=0|(v!=S&&g.getTimezoneOffset()==Math.min(S,v)),p()[b+32>>>2>>>0]=g}function Ma(g){g>>>=0;var b=new Date(p()[g+20>>>2>>>0]+1900,p()[g+16>>>2>>>0],p()[g+12>>>2>>>0],p()[g+8>>>2>>>0],p()[g+4>>>2>>>0],p()[g>>>2>>>0],0),v=p()[g+32>>>2>>>0],S=b.getTimezoneOffset(),E=new Date(b.getFullYear(),6,1).getTimezoneOffset(),$=new Date(b.getFullYear(),0,1).getTimezoneOffset(),L=Math.min($,E);return 0>v?p()[g+32>>>2>>>0]=+(E!=$&&L==S):0<v!=(L==S)&&(E=Math.max($,E),b.setTime(b.getTime()+6e4*((0<v?L:E)-S))),p()[g+24>>>2>>>0]=b.getDay(),v=(se(b.getFullYear())?ni:ii)[b.getMonth()]+b.getDate()-1|0,p()[g+28>>>2>>>0]=v,p()[g>>>2>>>0]=b.getSeconds(),p()[g+4>>>2>>>0]=b.getMinutes(),p()[g+8>>>2>>>0]=b.getHours(),p()[g+12>>>2>>>0]=b.getDate(),p()[g+16>>>2>>>0]=b.getMonth(),p()[g+20>>>2>>>0]=b.getYear(),g=b.getTime(),BigInt(isNaN(g)?-1:g/1e3)}function ea(g,b,v,S,E,$,L){return f?K(16,1,g,b,v,S,E,$,L):-52}function ra(g,b,v,S,E,$){if(f)return K(17,1,g,b,v,S,E,$)}function Va(g,b,v,S){g>>>=0,b>>>=0,v>>>=0,S>>>=0;var E=new Date().getFullYear(),$=new Date(E,0,1),L=new Date(E,6,1);E=$.getTimezoneOffset();var X=L.getTimezoneOffset(),lt=Math.max(E,X);o()[g>>>2>>>0]=60*lt,p()[b>>>2>>>0]=+(E!=X),$=(g=pt=>pt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])($),L=g(L),X<E?(ge($,v,17),ge(L,S,17)):(ge($,S,17),ge(L,v,17))}var Lr=[];function za(g,b,v){g>>>=0,b>>>=0,v>>>=0,Lr.length=0;for(var S;S=a()[b++>>>0];){var E=S!=105;v+=(E&=S!=112)&&v%8?4:0,Lr.push(S==112?o()[v>>>2>>>0]:S==106?vt[v>>>3]:S==105?p()[v>>>2>>>0]:s()[v>>>3>>>0]),v+=E?8:4}return on[g](...Lr)}var Ua=()=>{},Ga=()=>Date.now();function Ha(g,b){return Z(fe(g>>>0,b>>>0))}var na,qa=()=>{throw ce+=1,"unwind"};function Wa(){return 4294901760}na=()=>performance.timeOrigin+performance.now();var Xa=()=>navigator.hardwareConcurrency;function Ka(){return Ft("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Ya(g){g>>>=0;var b=a().length;if(g<=b||4294901760<g)return!1;for(var v=1;4>=v;v*=2){var S=b*(1+.2/v);S=Math.min(S,g+100663296);var E=Math;S=Math.max(g,S);t:{E=(E.min.call(E,4294901760,S+(65536-S%65536)%65536)-ft.buffer.byteLength+65535)/65536;try{ft.grow(E),it();var $=1;break t}catch{}$=void 0}if($)return!0}return!1}var Qe=()=>(Ft("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),be={},oa=g=>{g.forEach(b=>{Qe()})};function Ja(){var g=Error().stack.toString().split(`
1806
+ as ORT format: ${p}`)}}loadFromOnnxFormat(e,n){let i=Dp.onnx.ModelProto.decode(e);if(Rt.longToNumber(i.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=i.opsetImport.map(a=>({domain:a.domain,version:Rt.longToNumber(a.version)})),this._graph=Wi.from(i.graph,n)}loadFromOrtFormat(e,n){let i=new w.ByteBuffer(e),a=vg.InferenceSession.getRootAsInferenceSession(i).model();if(Rt.longToNumber(a.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let p=0;p<a.opsetImportLength();p++){let o=a.opsetImport(p);this._opsets.push({domain:o==null?void 0:o.domain(),version:Rt.longToNumber(o.version())})}this._graph=Wi.from(a.graph(),n)}get graph(){return this._graph}get opsets(){return this._opsets}}}),ro,$p=O(()=>{Sp(),Ap(),Ut(),Lp(),ro=class{constructor(e={}){this._initialized=!1,this.backendHint=e.backendHint,this.profiler=xn.create(e.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(e,n,i){await this.profiler.event("session","Session.loadModel",async()=>{let a=await Mi(this.backendHint);if(this.sessionHandler=a.createSessionHandler(this.context),this._model=new eo,typeof e=="string"){let p=e.endsWith(".ort");{let o=await(await fetch(e)).arrayBuffer();this.initialize(new Uint8Array(o),p)}}else if(ArrayBuffer.isView(e))this.initialize(e);else{let p=new Uint8Array(e,n||0,i||e.byteLength);this.initialize(p)}})}initialize(e,n){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{let i=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(e,i,n),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new Zn(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(e){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{let n=this.normalizeAndValidateInputs(e),i=await this._executionPlan.execute(this.sessionHandler,n);return this.createOutput(i)})}normalizeAndValidateInputs(e){let n=this._model.graph.getInputNames();if(Array.isArray(e)){if(e.length!==n.length)throw new Error(`incorrect input array length: expected ${n.length} but got ${e.length}`)}else{if(e.size!==n.length)throw new Error(`incorrect input map size: expected ${n.length} but got ${e.size}`);let i=new Array(e.size),a=0;for(let p=0;p<n.length;++p){let o=e.get(n[p]);if(!o)throw new Error(`missing input tensor for: '${name}'`);i[a++]=o}e=i}if(!this.context.graphInputTypes||this.context.graphInputTypes.length===0||!this.context.graphInputDims||this.context.graphInputDims.length===0){let i=this._model.graph.getInputIndices(),a=this._model.graph.getValues(),p=new Array(i.length);for(let o=0;o<i.length;++o){let s=a[i[o]];p[o]=s.type.shape.dims,this.context.graphInputTypes.push(s.type.tensorType),this.context.graphInputDims.push(e[o].dims)}this.validateInputTensorDims(p,e,!0)}else this.validateInputTensorDims(this.context.graphInputDims,e,!1);return this.validateInputTensorTypes(this.context.graphInputTypes,e),e}validateInputTensorTypes(e,n){for(let i=0;i<n.length;i++){let a=e[i],p=n[i].type;if(a!==p)throw new Error(`input tensor[${i}] check failed: expected type '${a}' but got ${p}`)}}validateInputTensorDims(e,n,i){for(let a=0;a<n.length;a++){let p=e[a],o=n[a].dims;if(!this.compareTensorDims(p,o,i))throw new Error(`input tensor[${a}] check failed: expected shape '[${p.join(",")}]' but got [${o.join(",")}]`)}}compareTensorDims(e,n,i){if(e.length!==n.length)return!1;for(let a=0;a<e.length;++a)if(e[a]!==n[a]&&(!i||e[a]!==0))return!1;return!0}createOutput(e){let n=this._model.graph.getOutputNames();if(e.length!==n.length)throw new Error("expected number of outputs do not match number of generated outputs");let i=new Map;for(let a=0;a<n.length;++a)i.set(n[a],e[a]);return i}initializeOps(e){let n=e.getNodes();this._ops=new Array(n.length);for(let i=0;i<n.length;i++)this._ops[i]=this.sessionHandler.resolve(n[i],this._model.opsets,e)}}}),no,kp=O(()=>{Yt(),We(),no=class{constructor(e){this.session=e,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(e,n,i){let a=new Map;for(let s in e)if(Object.hasOwnProperty.call(e,s)){let d=e[s];a.set(s,new bt(d.dims,d.type,void 0,void 0,d.data))}let p=await this.session.run(a),o={};return p.forEach((s,d)=>{o[d]=new yt(s.type,s.data,s.dims)}),o}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}}),Bp={};Or(Bp,{onnxjsBackend:()=>Ig});var Hi,Ig,Fp=O(()=>{$p(),kp(),Hi=class{async init(){}async createInferenceSessionHandler(e,n){let i=new ro(n);return typeof e=="string"?await i.loadModel(e):await i.loadModel(e),new no(i)}},Ig=new Hi}),oo=O(()=>{}),Rp={};Or(Rp,{default:()=>_g});var Cp,Np,_g,Gp=O(()=>{var e;qi(),Ke(),Vr(),Cp="ort-wasm-proxy-worker",Np=((e=globalThis.self)==null?void 0:e.name)===Cp,Np&&(self.onmessage=n=>{let{type:i,in:a}=n.data;try{switch(i){case"init-wasm":io(a.wasm).then(()=>{ao(a).then(()=>{postMessage({type:i})},p=>{postMessage({type:i,err:p})})},p=>{postMessage({type:i,err:p})});break;case"init-ep":{let{epName:p,env:o}=a;so(o,p).then(()=>{postMessage({type:i})},s=>{postMessage({type:i,err:s})});break}case"copy-from":{let{buffer:p}=a,o=zr(p);postMessage({type:i,out:o});break}case"create":{let{model:p,options:o}=a;uo(p,o).then(s=>{postMessage({type:i,out:s})},s=>{postMessage({type:i,err:s})});break}case"release":lo(a),postMessage({type:i});break;case"run":{let{sessionId:p,inputIndices:o,inputs:s,outputIndices:d,options:c}=a;fo(p,o,s,d,new Array(d.length).fill(null),c).then(r=>{r.some(u=>u[3]!=="cpu")?postMessage({type:i,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:i,out:r},po([...s,...r]))},r=>{postMessage({type:i,err:r})});break}case"end-profiling":co(a),postMessage({type:i});break;default:}}catch(p){postMessage({type:i,err:p})}}),_g=Np?null:n=>new Worker(n??br,{type:"module",name:Cp})}),Up={};Or(Up,{default:()=>Og});var ji,Mp,Og,Vp=O(()=>{var e;Mp=(ji=_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("segmentation.js",document.baseURI).href,async function(n={}){function i(){return ft.buffer!=gt.buffer&&it(),gt}function a(){return ft.buffer!=gt.buffer&&it(),U}function p(){return ft.buffer!=gt.buffer&&it(),Mt}function o(){return ft.buffer!=gt.buffer&&it(),De}function s(){return ft.buffer!=gt.buffer&&it(),ae}var d,c,r=Object.assign({},n),u=new Promise((g,b)=>{d=g,c=b}),l=typeof window=="object",h=typeof importScripts=="function",f=h&&self.name=="em-pthread";r.mountExternalData=(g,b)=>{g.startsWith("./")&&(g=g.substring(2)),(r.Ua||(r.Ua=new Map)).set(g,b)},r.unmountExternalData=()=>{delete r.Ua};var m,y,_=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor,I=Object.assign({},r),x="./this.program",P=(g,b)=>{throw b},N="";(l||h)&&(h?N=self.location.href:typeof document<"u"&&document.currentScript&&(N=document.currentScript.src),ji&&(N=ji),N=N.startsWith("blob:")?"":N.substr(0,N.replace(/[?#].*/,"").lastIndexOf("/")+1),h&&(y=g=>{var b=new XMLHttpRequest;return b.open("GET",g,!1),b.responseType="arraybuffer",b.send(null),new Uint8Array(b.response)}),m=(g,b,v)=>{var S=new XMLHttpRequest;S.open("GET",g,!0),S.responseType="arraybuffer",S.onload=()=>{S.status==200||S.status==0&&S.response?b(S.response):v()},S.onerror=v,S.send(null)});var R,ct=console.log.bind(console),st=console.error.bind(console),Dt=ct,Z=st;if(Object.assign(r,I),I=null,f){let g=function(b){try{var v=b.data,S=v.cmd;if(S==="load"){let E=[];self.onmessage=$=>E.push($),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let $ of E)g($);self.onmessage=g};for(let $ of v.handlers)r[$]&&!r[$].proxy||(r[$]=(...L)=>{postMessage({Za:"callHandler",kb:$,args:L})},$=="print"&&(Dt=r[$]),$=="printErr"&&(Z=r[$]));ft=v.wasmMemory,it(),Ot(v.wasmModule)}else if(S==="run"){Jr(v.pthread_ptr,0,0,1,0,0),Ir(v.pthread_ptr),Ia(),_o(),Ae||(Ae=!0);try{Pa(v.start_routine,v.arg)}catch(E){if(E!="unwind")throw E}}else S==="cancel"?le()&&er(-1):v.target!=="setimmediate"&&(S==="checkMailbox"?Ae&&Ze():S&&(Z(`worker: received unknown command ${S}`),Z(v)))}catch(E){throw ga(),E}};var Ot,Ae=!1;Z=function(...b){b=b.join(" "),console.error(b)},self.alert=function(...b){postMessage({Za:"alert",text:b.join(" "),nb:le()})},r.instantiateWasm=(b,v)=>new Promise(S=>{Ot=E=>{E=new WebAssembly.Instance(E,nn()),v(E),S()}}),self.onunhandledrejection=b=>{throw b.reason||b},self.onmessage=g}r.wasmBinary&&(R=r.wasmBinary);var ft,$e,Nt,gt,U,Mt,De,vt,ae,nt=!1;function it(){var g=ft.buffer;r.HEAP8=gt=new Int8Array(g),r.HEAP16=new Int16Array(g),r.HEAPU8=U=new Uint8Array(g),r.HEAPU16=new Uint16Array(g),r.HEAP32=Mt=new Int32Array(g),r.HEAPU32=De=new Uint32Array(g),r.HEAPF32=new Float32Array(g),r.HEAPF64=ae=new Float64Array(g),r.HEAP64=vt=new BigInt64Array(g),r.HEAPU64=new BigUint64Array(g)}if(!f){if(!((ft=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof _))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"),Error("bad memory");it()}var ee=[],Wt=[],Le=[],re=0,_t=null;function Pt(){if(--re==0&&_t){var g=_t;_t=null,g()}}function Ft(g){throw Z(g="Aborted("+g+")"),nt=!0,Nt=1,g=new WebAssembly.RuntimeError(g+". Build with -sASSERTIONS for more info."),c(g),g}var et,at=g=>g.startsWith("data:application/octet-stream;base64,"),Lt=g=>g.startsWith("file://");function ue(g){if(g==et&&R)return new Uint8Array(R);if(y)return y(g);throw"both async and sync fetching of the wasm failed"}function Re(g,b,v){return function(S){if(!R&&(l||h)){if(typeof fetch=="function"&&!Lt(S))return fetch(S,{credentials:"same-origin"}).then(E=>{if(!E.ok)throw`failed to load wasm binary file at '${S}'`;return E.arrayBuffer()}).catch(()=>ue(S));if(m)return new Promise((E,$)=>{m(S,L=>E(new Uint8Array(L)),$)})}return Promise.resolve().then(()=>ue(S))}(g).then(S=>WebAssembly.instantiate(S,b)).then(v,S=>{Z(`failed to asynchronously prepare wasm: ${S}`),Ft(S)})}function nn(){return{a:{j:Ea,b:$a,E:Po,g:Do,V:ko,A:jo,C:Bo,W:zo,T:Xo,L:Ko,S:Yo,o:Jo,B:Zo,y:Qo,U:ti,z:ri,_:Da,Z:ka,P:Na,w:Fa,F:Ca,k:La,O:Ir,Y:ja,I:Ra,J:Ba,K:Ma,G:ea,H:ra,v:Va,q:za,l:Ua,p:Ga,e:Ha,X:qa,x:Wa,d:na,f:Xa,i:Ka,u:Ya,t:Ja,s:Za,Q:aa,R:sa,D:Er,h:la,n:ua,M:pa,m:da,a:ft,r:_r,N:fa,c:Ks}}}var on={837620:(g,b,v,S,E)=>{if(r===void 0||!r.Ua)return 1;if((g=fe(g>>>0)).startsWith("./")&&(g=g.substring(2)),!(g=r.Ua.get(g)))return 2;if(S>>>=0,(b>>>=0)+(v>>>=0)>g.byteLength)return 3;try{let $=g.subarray(b,b+v);switch(E){case 0:a().set($,S>>>0);break;case 1:r.mb(S,$);break;default:return 4}return 0}catch{return 4}},838303:()=>typeof wasmOffsetConverter<"u"};function Ea(){return typeof wasmOffsetConverter<"u"}function wr(g){this.name="ExitStatus",this.message=`Program terminated with exit(${g})`,this.status=g}var vr=g=>{g.terminate(),g.onmessage=()=>{}},vn=g=>{Jt.length==0&&(So(),Oo(Jt[0]));var b=Jt.pop();if(!b)return 6;oe.push(b),$t[g.Ra]=b,b.Ra=g.Ra;var v={cmd:"run",start_routine:g.cb,arg:g.ab,pthread_ptr:g.Ra};return b.postMessage(v,g.ib),0},ce=0,K=(g,b,...v)=>{for(var S=2*v.length,E=tn(),$=Qr(8*S),L=$>>>3,X=0;X<v.length;X++){var lt=v[X];typeof lt=="bigint"?(vt[L+2*X]=1n,vt[L+2*X+1]=lt):(vt[L+2*X]=0n,s()[L+2*X+1>>>0]=lt)}return g=ma(g,0,S,$,b),ar(E),g};function _r(g){if(f)return K(0,1,g);if(Nt=g,!(0<ce)){for(var b of oe)vr(b);for(b of Jt)vr(b);Jt=[],oe=[],$t=[],nt=!0}P(g,new wr(g))}function _n(g){if(f)return K(1,0,g);Er(g)}var Er=g=>{if(Nt=g,f)throw _n(g),"unwind";_r(g)},Jt=[],oe=[],On=[],$t={},In=g=>{var b=g.Ra;delete $t[b],Jt.push(g),oe.splice(oe.indexOf(g),1),g.Ra=0,Zr(b)};function _o(){On.forEach(g=>g())}var Oo=g=>new Promise(b=>{g.onmessage=E=>{var $=(E=E.data).cmd;if(E.targetThread&&E.targetThread!=le()){var L=$t[E.targetThread];L?L.postMessage(E,E.transferList):Z(`Internal error! Worker sent a message "${$}" to target pthread ${E.targetThread}, but that thread no longer exists!`)}else $==="checkMailbox"?Ze():$==="spawnThread"?vn(E):$==="cleanupThread"?In($t[E.thread]):$==="killThread"?(E=E.thread,$=$t[E],delete $t[E],vr($),Zr(E),oe.splice(oe.indexOf($),1),$.Ra=0):$==="cancelThread"?$t[E.thread].postMessage({cmd:"cancel"}):$==="loaded"?(g.loaded=!0,b(g)):$==="alert"?alert(`Thread ${E.threadId}: ${E.text}`):E.target==="setimmediate"?g.postMessage(E):$==="callHandler"?r[E.handler](...E.args):$&&Z(`worker sent an unknown command ${$}`)},g.onerror=E=>{throw Z(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var v,S=[];for(v of[])r.hasOwnProperty(v)&&S.push(v);g.postMessage({cmd:"load",handlers:S,wasmMemory:ft,wasmModule:$e})});function So(){var g=new Worker(new URL(_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("segmentation.js",document.baseURI).href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Jt.push(g)}var Eo,Ge=g=>{for(;0<g.length;)g.shift()(r)},Ia=()=>{var g=le(),b=o()[g+52>>>2>>>0];g=o()[g+56>>>2>>>0],ya(b,b-g),ar(b)},Ye=[],Pa=(g,b)=>{ce=0;var v=Ye[g];v||(g>=Ye.length&&(Ye.length=g+1),Ye[g]=v=Eo.get(g)),g=v(b),0<ce?Nt=g:er(g)};class Aa{constructor(b){this.Xa=b-24}}function $a(g,b,v){var S=new Aa(g>>>=0);throw b>>>=0,v>>>=0,o()[S.Xa+16>>>2>>>0]=0,o()[S.Xa+4>>>2>>>0]=b,o()[S.Xa+8>>>2>>>0]=v,g}function Io(g,b,v,S){return f?K(2,1,g,b,v,S):Po(g,b,v,S)}function Po(g,b,v,S){if(g>>>=0,b>>>=0,v>>>=0,S>>>=0,_===void 0)return Z("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var E=[];return f&&E.length===0?Io(g,b,v,S):(g={cb:v,Ra:g,ab:S,ib:E},f?(g.Za="spawnThread",postMessage(g,E),0):vn(g))}var Ao=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,$o=(g,b,v)=>{var S=(b>>>=0)+v;for(v=b;g[v]&&!(v>=S);)++v;if(16<v-b&&g.buffer&&Ao)return Ao.decode(g.buffer instanceof _?g.slice(b,v):g.subarray(b,v));for(S="";b<v;){var E=g[b++];if(128&E){var $=63&g[b++];if((224&E)==192)S+=String.fromCharCode((31&E)<<6|$);else{var L=63&g[b++];65536>(E=(240&E)==224?(15&E)<<12|$<<6|L:(7&E)<<18|$<<12|L<<6|63&g[b++])?S+=String.fromCharCode(E):(E-=65536,S+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else S+=String.fromCharCode(E)}return S},fe=(g,b)=>(g>>>=0)?$o(a(),g,b):"";function Do(g,b,v){return f?K(3,1,g,b,v):0}function ko(g,b){if(f)return K(4,1,g,b)}var Fo=g=>{for(var b=0,v=0;v<g.length;++v){var S=g.charCodeAt(v);127>=S?b++:2047>=S?b+=2:55296<=S&&57343>=S?(b+=4,++v):b+=3}return b},Lo=(g,b,v,S)=>{if(!(0<S))return 0;var E=v>>>=0;S=v+S-1;for(var $=0;$<g.length;++$){var L=g.charCodeAt($);if(55296<=L&&57343>=L&&(L=65536+((1023&L)<<10)|1023&g.charCodeAt(++$)),127>=L){if(v>=S)break;b[v++>>>0]=L}else{if(2047>=L){if(v+1>=S)break;b[v++>>>0]=192|L>>6}else{if(65535>=L){if(v+2>=S)break;b[v++>>>0]=224|L>>12}else{if(v+3>=S)break;b[v++>>>0]=240|L>>18,b[v++>>>0]=128|L>>12&63}b[v++>>>0]=128|L>>6&63}b[v++>>>0]=128|63&L}}return b[v>>>0]=0,v-E},ge=(g,b,v)=>Lo(g,a(),b,v);function jo(g,b){if(f)return K(5,1,g,b)}function Bo(g,b,v){if(f)return K(6,1,g,b,v)}function zo(g,b,v){return f?K(7,1,g,b,v):0}function Xo(g,b){if(f)return K(8,1,g,b)}function Ko(g,b,v){if(f)return K(9,1,g,b,v)}function Yo(g,b,v,S){if(f)return K(10,1,g,b,v,S)}function Jo(g,b,v,S){if(f)return K(11,1,g,b,v,S)}function Zo(g,b,v,S){if(f)return K(12,1,g,b,v,S)}function Qo(g){if(f)return K(13,1,g)}function ti(g,b){if(f)return K(14,1,g,b)}function ri(g,b,v){if(f)return K(15,1,g,b,v)}var Da=()=>{Ft("")},ka=()=>1;function Na(g){Jr(g>>>0,!h,1,!l,131072,!1),_o()}function Ir(g){g>>>=0,typeof Atomics.jb=="function"&&(Atomics.jb(p(),g>>>2,g).value.then(Ze),g+=128,Atomics.store(p(),g>>>2,1))}var Ze=()=>{var g=le();if(g&&(Ir(g),g=ba,!nt))try{if(g(),!(0<ce))try{f?er(Nt):Er(Nt)}catch(b){b instanceof wr||b=="unwind"||P(1,b)}}catch(b){b instanceof wr||b=="unwind"||P(1,b)}};function Fa(g,b){(g>>>=0)==b>>>0?setTimeout(Ze):f?postMessage({targetThread:g,cmd:"checkMailbox"}):(g=$t[g])&&g.postMessage({cmd:"checkMailbox"})}var Dr=[];function Ca(g,b,v,S,E){for(b>>>=0,S/=2,Dr.length=S,v=E>>>0>>>3,E=0;E<S;E++)Dr[E]=vt[v+2*E]?vt[v+2*E+1]:s()[v+2*E+1>>>0];return(b?on[b]:Js[g])(...Dr)}function La(g){g>>>=0,f?postMessage({cmd:"cleanupThread",thread:g}):In($t[g])}function ja(g){}function Ra(g,b){g=-9007199254740992>g||9007199254740992<g?NaN:Number(g),b>>>=0,g=new Date(1e3*g),p()[b>>>2>>>0]=g.getUTCSeconds(),p()[b+4>>>2>>>0]=g.getUTCMinutes(),p()[b+8>>>2>>>0]=g.getUTCHours(),p()[b+12>>>2>>>0]=g.getUTCDate(),p()[b+16>>>2>>>0]=g.getUTCMonth(),p()[b+20>>>2>>>0]=g.getUTCFullYear()-1900,p()[b+24>>>2>>>0]=g.getUTCDay(),g=(g.getTime()-Date.UTC(g.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,p()[b+28>>>2>>>0]=g}var se=g=>g%4==0&&(g%100!=0||g%400==0),ni=[0,31,60,91,121,152,182,213,244,274,305,335],ii=[0,31,59,90,120,151,181,212,243,273,304,334];function Ba(g,b){g=-9007199254740992>g||9007199254740992<g?NaN:Number(g),b>>>=0,g=new Date(1e3*g),p()[b>>>2>>>0]=g.getSeconds(),p()[b+4>>>2>>>0]=g.getMinutes(),p()[b+8>>>2>>>0]=g.getHours(),p()[b+12>>>2>>>0]=g.getDate(),p()[b+16>>>2>>>0]=g.getMonth(),p()[b+20>>>2>>>0]=g.getFullYear()-1900,p()[b+24>>>2>>>0]=g.getDay();var v=(se(g.getFullYear())?ni:ii)[g.getMonth()]+g.getDate()-1|0;p()[b+28>>>2>>>0]=v,p()[b+36>>>2>>>0]=-60*g.getTimezoneOffset(),v=new Date(g.getFullYear(),6,1).getTimezoneOffset();var S=new Date(g.getFullYear(),0,1).getTimezoneOffset();g=0|(v!=S&&g.getTimezoneOffset()==Math.min(S,v)),p()[b+32>>>2>>>0]=g}function Ma(g){g>>>=0;var b=new Date(p()[g+20>>>2>>>0]+1900,p()[g+16>>>2>>>0],p()[g+12>>>2>>>0],p()[g+8>>>2>>>0],p()[g+4>>>2>>>0],p()[g>>>2>>>0],0),v=p()[g+32>>>2>>>0],S=b.getTimezoneOffset(),E=new Date(b.getFullYear(),6,1).getTimezoneOffset(),$=new Date(b.getFullYear(),0,1).getTimezoneOffset(),L=Math.min($,E);return 0>v?p()[g+32>>>2>>>0]=+(E!=$&&L==S):0<v!=(L==S)&&(E=Math.max($,E),b.setTime(b.getTime()+6e4*((0<v?L:E)-S))),p()[g+24>>>2>>>0]=b.getDay(),v=(se(b.getFullYear())?ni:ii)[b.getMonth()]+b.getDate()-1|0,p()[g+28>>>2>>>0]=v,p()[g>>>2>>>0]=b.getSeconds(),p()[g+4>>>2>>>0]=b.getMinutes(),p()[g+8>>>2>>>0]=b.getHours(),p()[g+12>>>2>>>0]=b.getDate(),p()[g+16>>>2>>>0]=b.getMonth(),p()[g+20>>>2>>>0]=b.getYear(),g=b.getTime(),BigInt(isNaN(g)?-1:g/1e3)}function ea(g,b,v,S,E,$,L){return f?K(16,1,g,b,v,S,E,$,L):-52}function ra(g,b,v,S,E,$){if(f)return K(17,1,g,b,v,S,E,$)}function Va(g,b,v,S){g>>>=0,b>>>=0,v>>>=0,S>>>=0;var E=new Date().getFullYear(),$=new Date(E,0,1),L=new Date(E,6,1);E=$.getTimezoneOffset();var X=L.getTimezoneOffset(),lt=Math.max(E,X);o()[g>>>2>>>0]=60*lt,p()[b>>>2>>>0]=+(E!=X),$=(g=pt=>pt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])($),L=g(L),X<E?(ge($,v,17),ge(L,S,17)):(ge($,S,17),ge(L,v,17))}var Lr=[];function za(g,b,v){g>>>=0,b>>>=0,v>>>=0,Lr.length=0;for(var S;S=a()[b++>>>0];){var E=S!=105;v+=(E&=S!=112)&&v%8?4:0,Lr.push(S==112?o()[v>>>2>>>0]:S==106?vt[v>>>3]:S==105?p()[v>>>2>>>0]:s()[v>>>3>>>0]),v+=E?8:4}return on[g](...Lr)}var Ua=()=>{},Ga=()=>Date.now();function Ha(g,b){return Z(fe(g>>>0,b>>>0))}var na,qa=()=>{throw ce+=1,"unwind"};function Wa(){return 4294901760}na=()=>performance.timeOrigin+performance.now();var Xa=()=>navigator.hardwareConcurrency;function Ka(){return Ft("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Ya(g){g>>>=0;var b=a().length;if(g<=b||4294901760<g)return!1;for(var v=1;4>=v;v*=2){var S=b*(1+.2/v);S=Math.min(S,g+100663296);var E=Math;S=Math.max(g,S);t:{E=(E.min.call(E,4294901760,S+(65536-S%65536)%65536)-ft.buffer.byteLength+65535)/65536;try{ft.grow(E),it();var $=1;break t}catch{}$=void 0}if($)return!0}return!1}var Qe=()=>(Ft("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),be={},oa=g=>{g.forEach(b=>{Qe()})};function Ja(){var g=Error().stack.toString().split(`
1807
1807
  `);return g[0]=="Error"&&g.shift(),oa(g),be.$a=Qe(),be.bb=g,be.$a}function Za(g,b,v){if(g>>>=0,b>>>=0,be.$a==g)var S=be.bb;else(S=Error().stack.toString().split(`
1808
1808
  `))[0]=="Error"&&S.shift(),oa(S);for(var E=3;S[E]&&Qe()!=g;)++E;for(g=0;g<v&&S[g+E];++g)p()[b+4*g>>>2>>>0]=Qe();return g}var Kr,Yr={},ia=()=>{if(!Kr){var g,b={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",_:x};for(g in Yr)Yr[g]===void 0?delete b[g]:b[g]=Yr[g];var v=[];for(g in b)v.push(`${g}=${b[g]}`);Kr=v}return Kr};function aa(g,b){if(f)return K(18,1,g,b);g>>>=0,b>>>=0;var v=0;return ia().forEach((S,E)=>{var $=b+v;for(E=o()[g+4*E>>>2>>>0]=$,$=0;$<S.length;++$)i()[E++>>>0]=S.charCodeAt($);i()[E>>>0]=0,v+=S.length+1}),0}function sa(g,b){if(f)return K(19,1,g,b);g>>>=0,b>>>=0;var v=ia();o()[g>>>2>>>0]=v.length;var S=0;return v.forEach(E=>S+=E.length+1),o()[b>>>2>>>0]=S,0}function la(g){return f?K(20,1,g):52}function ua(g,b,v,S){return f?K(21,1,g,b,v,S):52}function pa(g,b,v,S){return f?K(22,1,g,b,v,S):70}var qs=[null,[],[]];function da(g,b,v,S){if(f)return K(23,1,g,b,v,S);b>>>=0,v>>>=0,S>>>=0;for(var E=0,$=0;$<v;$++){var L=o()[b>>>2>>>0],X=o()[b+4>>>2>>>0];b+=8;for(var lt=0;lt<X;lt++){var pt=a()[L+lt>>>0],wt=qs[g];pt===0||pt===10?((g===1?Dt:Z)($o(wt,0)),wt.length=0):wt.push(pt)}E+=X}return o()[S>>>2>>>0]=E,0}var ca=[31,29,31,30,31,30,31,31,30,31,30,31],ha=[31,28,31,30,31,30,31,31,30,31,30,31],Xs=(g,b)=>{i().set(g,b>>>0)};function fa(g,b,v,S){function E(A,V,Q){for(A=typeof A=="number"?A.toString():A||"";A.length<V;)A=Q[0]+A;return A}function $(A,V){return E(A,V,"0")}function L(A,V){function Q(Ta){return 0>Ta?-1:0<Ta?1:0}var ie;return(ie=Q(A.getFullYear()-V.getFullYear()))===0&&(ie=Q(A.getMonth()-V.getMonth()))===0&&(ie=Q(A.getDate()-V.getDate())),ie}function X(A){switch(A.getDay()){case 0:return new Date(A.getFullYear()-1,11,29);case 1:return A;case 2:return new Date(A.getFullYear(),0,3);case 3:return new Date(A.getFullYear(),0,2);case 4:return new Date(A.getFullYear(),0,1);case 5:return new Date(A.getFullYear()-1,11,31);case 6:return new Date(A.getFullYear()-1,11,30)}}function lt(A){var V=A.Sa;for(A=new Date(new Date(A.Ta+1900,0,1).getTime());0<V;){var Q=A.getMonth(),ie=(se(A.getFullYear())?ca:ha)[Q];if(!(V>ie-A.getDate())){A.setDate(A.getDate()+V);break}V-=ie-A.getDate()+1,A.setDate(1),11>Q?A.setMonth(Q+1):(A.setMonth(0),A.setFullYear(A.getFullYear()+1))}return Q=new Date(A.getFullYear()+1,0,4),V=X(new Date(A.getFullYear(),0,4)),Q=X(Q),0>=L(V,A)?0>=L(Q,A)?A.getFullYear()+1:A.getFullYear():A.getFullYear()-1}g>>>=0,b>>>=0,v>>>=0,S>>>=0;var pt=o()[S+40>>>2>>>0];for(var wt in S={gb:p()[S>>>2>>>0],fb:p()[S+4>>>2>>>0],Va:p()[S+8>>>2>>>0],Ya:p()[S+12>>>2>>>0],Wa:p()[S+16>>>2>>>0],Ta:p()[S+20>>>2>>>0],Qa:p()[S+24>>>2>>>0],Sa:p()[S+28>>>2>>>0],ob:p()[S+32>>>2>>>0],eb:p()[S+36>>>2>>>0],hb:pt?fe(pt):""},v=fe(v),pt={"%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"})v=v.replace(new RegExp(wt,"g"),pt[wt]);var va="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),xa="January February March April May June July August September October November December".split(" ");for(wt in pt={"%a":A=>va[A.Qa].substring(0,3),"%A":A=>va[A.Qa],"%b":A=>xa[A.Wa].substring(0,3),"%B":A=>xa[A.Wa],"%C":A=>$((A.Ta+1900)/100|0,2),"%d":A=>$(A.Ya,2),"%e":A=>E(A.Ya,2," "),"%g":A=>lt(A).toString().substring(2),"%G":lt,"%H":A=>$(A.Va,2),"%I":A=>((A=A.Va)==0?A=12:12<A&&(A-=12),$(A,2)),"%j":A=>{for(var V=0,Q=0;Q<=A.Wa-1;V+=(se(A.Ta+1900)?ca:ha)[Q++]);return $(A.Ya+V,3)},"%m":A=>$(A.Wa+1,2),"%M":A=>$(A.fb,2),"%n":()=>`
1809
1809
  `,"%p":A=>0<=A.Va&&12>A.Va?"AM":"PM","%S":A=>$(A.gb,2),"%t":()=>" ","%u":A=>A.Qa||7,"%U":A=>$(Math.floor((A.Sa+7-A.Qa)/7),2),"%V":A=>{var V=Math.floor((A.Sa+7-(A.Qa+6)%7)/7);if(2>=(A.Qa+371-A.Sa-2)%7&&V++,V)V==53&&((Q=(A.Qa+371-A.Sa)%7)==4||Q==3&&se(A.Ta)||(V=1));else{V=52;var Q=(A.Qa+7-A.Sa-1)%7;(Q==4||Q==5&&se(A.Ta%400-1))&&V++}return $(V,2)},"%w":A=>A.Qa,"%W":A=>$(Math.floor((A.Sa+7-(A.Qa+6)%7)/7),2),"%y":A=>(A.Ta+1900).toString().substring(2),"%Y":A=>A.Ta+1900,"%z":A=>{var V=0<=(A=A.eb);return A=Math.abs(A)/60,(V?"+":"-")+("0000"+(A/60*100+A%60)).slice(-4)},"%Z":A=>A.hb,"%%":()=>"%"},v=v.replace(/%%/g,"\0\0"),pt)v.includes(wt)&&(v=v.replace(new RegExp(wt,"g"),pt[wt](S)));return wt=function(A){var V=Array(Fo(A)+1);return Lo(A,V,0,V.length),V}(v=v.replace(/\0\0/g,"%")),wt.length>b?0:(Xs(wt,g),wt.length-1)}function Ks(g,b,v,S){return fa(g>>>0,b>>>0,v>>>0,S>>>0)}f||function(){for(var g=r.numThreads-1;g--;)So();ee.unshift(()=>{re++,function(b){f?b():Promise.all(Jt.map(Oo)).then(b)}(()=>Pt())})}();var Js=[_r,_n,Io,Do,ko,jo,Bo,zo,Xo,Ko,Yo,Jo,Zo,Qo,ti,ri,ea,ra,aa,sa,la,ua,pa,da],M=function(){function g(v,S){return M=v.exports,M=function(){var E=M,$=X=>()=>X()>>>0,L=X=>lt=>X(lt)>>>0;return(E=Object.assign({},E)).Ba=$(E.Ba),E.Ca=L(E.Ca),E.emscripten_main_runtime_thread_id=$(E.emscripten_main_runtime_thread_id),E.Oa=L(E.Oa),E.Pa=$(E.Pa),E}(),On.push(M.Ea),Eo=M.Fa,Wt.unshift(M.$),$e=S,Pt(),M}var b=nn();if(re++,r.instantiateWasm)try{return r.instantiateWasm(b,g)}catch(v){Z(`Module.instantiateWasm callback failed with error: ${v}`),c(v)}return et||(et=r.locateFile?at("ort-wasm-simd-threaded.wasm")?"ort-wasm-simd-threaded.wasm":r.locateFile?r.locateFile("ort-wasm-simd-threaded.wasm",N):N+"ort-wasm-simd-threaded.wasm":""),function(v,S){var E=et;return R||typeof WebAssembly.instantiateStreaming!="function"||at(E)||Lt(E)||typeof fetch!="function"?Re(E,v,S):fetch(E,{credentials:"same-origin"}).then($=>WebAssembly.instantiateStreaming($,v).then(S,function(L){return Z(`wasm streaming compile failed: ${L}`),Z("falling back to ArrayBuffer instantiation"),Re(E,v,S)}))}(b,function(v){g(v.instance,v.module)}).catch(c),{}}();r._OrtInit=(g,b)=>(r._OrtInit=M.aa)(g,b),r._OrtGetLastError=(g,b)=>(r._OrtGetLastError=M.ba)(g,b),r._OrtCreateSessionOptions=(g,b,v,S,E,$,L,X,lt,pt)=>(r._OrtCreateSessionOptions=M.ca)(g,b,v,S,E,$,L,X,lt,pt),r._OrtAppendExecutionProvider=(g,b)=>(r._OrtAppendExecutionProvider=M.da)(g,b),r._OrtAddFreeDimensionOverride=(g,b,v)=>(r._OrtAddFreeDimensionOverride=M.ea)(g,b,v),r._OrtAddSessionConfigEntry=(g,b,v)=>(r._OrtAddSessionConfigEntry=M.fa)(g,b,v),r._OrtReleaseSessionOptions=g=>(r._OrtReleaseSessionOptions=M.ga)(g),r._OrtCreateSession=(g,b,v)=>(r._OrtCreateSession=M.ha)(g,b,v),r._OrtReleaseSession=g=>(r._OrtReleaseSession=M.ia)(g),r._OrtGetInputOutputCount=(g,b,v)=>(r._OrtGetInputOutputCount=M.ja)(g,b,v),r._OrtGetInputName=(g,b)=>(r._OrtGetInputName=M.ka)(g,b),r._OrtGetOutputName=(g,b)=>(r._OrtGetOutputName=M.la)(g,b),r._OrtFree=g=>(r._OrtFree=M.ma)(g),r._OrtCreateTensor=(g,b,v,S,E,$)=>(r._OrtCreateTensor=M.na)(g,b,v,S,E,$),r._OrtGetTensorData=(g,b,v,S,E)=>(r._OrtGetTensorData=M.oa)(g,b,v,S,E),r._OrtReleaseTensor=g=>(r._OrtReleaseTensor=M.pa)(g),r._OrtCreateRunOptions=(g,b,v,S)=>(r._OrtCreateRunOptions=M.qa)(g,b,v,S),r._OrtAddRunConfigEntry=(g,b,v)=>(r._OrtAddRunConfigEntry=M.ra)(g,b,v),r._OrtReleaseRunOptions=g=>(r._OrtReleaseRunOptions=M.sa)(g),r._OrtCreateBinding=g=>(r._OrtCreateBinding=M.ta)(g),r._OrtBindInput=(g,b,v)=>(r._OrtBindInput=M.ua)(g,b,v),r._OrtBindOutput=(g,b,v,S)=>(r._OrtBindOutput=M.va)(g,b,v,S),r._OrtClearBoundOutputs=g=>(r._OrtClearBoundOutputs=M.wa)(g),r._OrtReleaseBinding=g=>(r._OrtReleaseBinding=M.xa)(g),r._OrtRunWithBinding=(g,b,v,S,E)=>(r._OrtRunWithBinding=M.ya)(g,b,v,S,E),r._OrtRun=(g,b,v,S,E,$,L,X)=>(r._OrtRun=M.za)(g,b,v,S,E,$,L,X),r._OrtEndProfiling=g=>(r._OrtEndProfiling=M.Aa)(g);var le=()=>(le=M.Ba)();r._malloc=g=>(r._malloc=M.Ca)(g),r._free=g=>(r._free=M.Da)(g);var tr,Jr=(g,b,v,S,E,$)=>(Jr=M.Ga)(g,b,v,S,E,$),ga=()=>(ga=M.Ha)(),ma=(g,b,v,S,E)=>(ma=M.Ia)(g,b,v,S,E),Zr=g=>(Zr=M.Ja)(g),er=g=>(er=M.Ka)(g),ba=()=>(ba=M.La)(),ya=(g,b)=>(ya=M.Ma)(g,b),ar=g=>(ar=M.Na)(g),Qr=g=>(Qr=M.Oa)(g),tn=()=>(tn=M.Pa)();function wa(){0<re||(f?(d(r),f||Ge(Wt),startWorker(r)):(Ge(ee),0<re||tr||(tr=!0,r.calledRun=!0,nt||(f||Ge(Wt),d(r),f||Ge(Le)))))}return r.___start_em_js=838360,r.___stop_em_js=838421,r.stackSave=()=>tn(),r.stackRestore=g=>ar(g),r.stackAlloc=g=>Qr(g),r.UTF8ToString=fe,r.stringToUTF8=ge,r.lengthBytesUTF8=Fo,_t=function g(){tr||wa(),tr||(_t=g)},wa(),u}),Og=Mp,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&Mp()}),br,Sg,Ag,Pg,zp,Wp,Eg,Hp,Vr=O(()=>{var e,n;oo(),br=(_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("segmentation.js",document.baseURI).href)??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(n=self.location)==null?void 0:n.href:void 0),Sg=typeof location>"u"?void 0:location.origin,Ag=(i,a)=>{try{let p=a??br;return(p?new URL(i,p):new URL(i)).origin===Sg}catch{return!1}},Pg=async i=>{let a=await(await fetch(i,{credentials:"same-origin"})).blob();return URL.createObjectURL(a)},zp=(Gp(),sn(Rp)).default,Wp=async()=>{if(!br)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ag(br))return[void 0,zp()];let i=await Pg(br);return[i,zp(i)]},Eg=(Vp(),sn(Up)).default,Hp=async(i,a,p)=>[void 0,Eg]}),Xi,Ki,ho,qp,Dg,Lg,io,xt,Ke=O(()=>{Vr(),Ki=!1,ho=!1,qp=!1,Dg=()=>{if(typeof SharedArrayBuffer>"u")return!1;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}},Lg=()=>{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}},io=async e=>{if(Ki)return Promise.resolve();if(ho)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(qp)throw new Error("previous call to 'initializeWebAssembly()' failed.");ho=!0;let n=e.initTimeout,i=e.numThreads;if(!Lg())throw new Error("WebAssembly SIMD is not supported in the current environment.");let a=Dg();i>1&&!a&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+i+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=i=1);let p=e.wasmPaths,o=typeof p=="string"?p:void 0,s=p==null?void 0:p.mjs,d=(s==null?void 0:s.href)??s,c=p==null?void 0:p.wasm,r=(c==null?void 0:c.href)??c,u=e.wasmBinary,[l,h]=await Hp(d,o,i>1),f=!1,m=[];if(n>0&&m.push(new Promise(y=>{setTimeout(()=>{f=!0,y()},n)})),m.push(new Promise((y,_)=>{let I={numThreads:i};u?I.wasmBinary=u:(r||o)&&(I.locateFile=(x,P)=>r??(o??P)+x),h(I).then(x=>{ho=!1,Ki=!0,Xi=x,y(),l&&URL.revokeObjectURL(l)},x=>{ho=!1,qp=!0,_(x)})})),await Promise.race(m),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${n}ms`)},xt=()=>{if(Ki&&Xi)return Xi;throw new Error("WebAssembly is not initialized yet.")}}),Tt,Wr,ht,mo=O(()=>{Ke(),Tt=(e,n)=>{let i=xt(),a=i.lengthBytesUTF8(e)+1,p=i._malloc(a);return i.stringToUTF8(e,p,a),n.push(p),p},Wr=(e,n,i,a)=>{if(typeof e=="object"&&e!==null){if(i.has(e))throw new Error("Circular reference in options");i.add(e)}Object.entries(e).forEach(([p,o])=>{let s=n?n+p:p;if(typeof o=="object")Wr(o,s+".",i,a);else if(typeof o=="string"||typeof o=="number")a(s,o.toString());else if(typeof o=="boolean")a(s,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},ht=e=>{let n=xt(),i=n.stackSave();try{let a=n.stackAlloc(8);n._OrtGetLastError(a,a+4);let p=n.HEAP32[a/4],o=n.HEAPU32[a/4+1],s=o?n.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${p}, ERROR_MESSAGE: ${s}`)}finally{n.stackRestore(i)}}}),jp,Xp=O(()=>{Ke(),mo(),jp=e=>{let n=xt(),i=0,a=[],p=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)p.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)p.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(p.terminate=!1);let o=0;return(e==null?void 0:e.tag)!==void 0&&(o=Tt(e.tag,a)),i=n._OrtCreateRunOptions(p.logSeverityLevel,p.logVerbosityLevel,!!p.terminate,o),i===0&&ht("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Wr(e.extra,"",new WeakSet,(s,d)=>{let c=Tt(s,a),r=Tt(d,a);n._OrtAddRunConfigEntry(i,c,r)!==0&&ht(`Can't set a run config entry: ${s} - ${d}.`)}),[i,a]}catch(o){throw i!==0&&n._OrtReleaseRunOptions(i),a.forEach(s=>n._free(s)),o}}}),$g,kg,Bg,Fg,Kp,Jp=O(()=>{Ke(),mo(),$g=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},kg=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Bg=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let n=e.extra.session;n.use_ort_model_bytes_directly||(n.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(i=>(typeof i=="string"?i:i.name)==="webgpu")&&(e.enableMemPattern=!1)},Fg=(e,n,i)=>{for(let a of n){let p=typeof a=="string"?a:a.name;switch(p){case"webnn":if(p="WEBNN",typeof a!="string"){let s=a==null?void 0:a.deviceType;if(s){let d=Tt("deviceType",i),c=Tt(s,i);xt()._OrtAddSessionConfigEntry(e,d,c)!==0&&ht(`Can't set a session config entry: 'deviceType' - ${s}.`)}}break;case"webgpu":if(p="JS",typeof a!="string"){let s=a;if(s!=null&&s.preferredLayout){if(s.preferredLayout!=="NCHW"&&s.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`);let d=Tt("preferredLayout",i),c=Tt(s.preferredLayout,i);xt()._OrtAddSessionConfigEntry(e,d,c)!==0&&ht(`Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${p}`)}let o=Tt(p,i);xt()._OrtAppendExecutionProvider(e,o)!==0&&ht(`Can't append execution provider: ${p}.`)}},Kp=e=>{let n=xt(),i=0,a=[],p=e||{};Bg(p);try{let o=$g(p.graphOptimizationLevel??"all"),s=kg(p.executionMode??"sequential"),d=typeof p.logId=="string"?Tt(p.logId,a):0,c=p.logSeverityLevel??2;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log serverity level is not valid: ${c}`);let r=p.logVerbosityLevel??0;if(!Number.isInteger(r)||r<0||r>4)throw new Error(`log verbosity level is not valid: ${r}`);let u=typeof p.optimizedModelFilePath=="string"?Tt(p.optimizedModelFilePath,a):0;if(i=n._OrtCreateSessionOptions(o,!!p.enableCpuMemArena,!!p.enableMemPattern,s,!!p.enableProfiling,0,d,c,r,u),i===0&&ht("Can't create session options."),p.executionProviders&&Fg(i,p.executionProviders,a),p.enableGraphCapture!==void 0){if(typeof p.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${p.enableGraphCapture}`);let l=Tt("enableGraphCapture",a),h=Tt(p.enableGraphCapture.toString(),a);n._OrtAddSessionConfigEntry(i,l,h)!==0&&ht(`Can't set a session config entry: 'enableGraphCapture' - ${p.enableGraphCapture}.`)}if(p.freeDimensionOverrides)for(let[l,h]of Object.entries(p.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=Tt(l,a);n._OrtAddFreeDimensionOverride(i,f,h)!==0&&ht(`Can't set a free dimension override: ${l} - ${h}.`)}return p.extra!==void 0&&Wr(p.extra,"",new WeakSet,(l,h)=>{let f=Tt(l,a),m=Tt(h,a);n._OrtAddSessionConfigEntry(i,f,m)!==0&&ht(`Can't set a session config entry: ${l} - ${h}.`)}),[i,a]}catch(o){throw i!==0&&n._OrtReleaseSessionOptions(i),a.forEach(s=>n._free(s)),o}}}),Hr,Yp,qr,Zp,Qp,bo,go,td,Ji=O(()=>{Hr=e=>{switch(e){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;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Yp=e=>{switch(e){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";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},qr=(e,n)=>{let i=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],a=typeof n=="number"?n:n.reduce((p,o)=>p*o,1);return i>0?Math.ceil(a*i):void 0},Zp=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array: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: ${e}`)}},Qp=e=>{switch(e){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: ${e}`)}},bo=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",go=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool",td=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),jr,Yi=O(()=>{oo(),jr=async e=>{if(typeof e=="string"){let n=await fetch(e);if(!n.ok)throw new Error(`failed to load external data file: ${e}`);let i=n.headers.get("Content-Length"),a=i?parseInt(i,10):0;if(a<1073741824)return new Uint8Array(await n.arrayBuffer());{if(!n.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let p=n.body.getReader(),o;try{o=new ArrayBuffer(a)}catch(d){if(d instanceof RangeError){let c=Math.ceil(a/65536);o=new WebAssembly.Memory({initial:c,maximum:c}).buffer}else throw d}let s=0;for(;;){let{done:d,value:c}=await p.read();if(d)break;let r=c.byteLength;new Uint8Array(o,s,r).set(c),s+=r}return new Uint8Array(o,0,a)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Cg,ao,so,yr,Ng,zr,uo,lo,ed,fo,co,po,qi=O(()=>{Xp(),Jp(),Ji(),Ke(),mo(),Yi(),Cg=(e,n)=>{xt()._OrtInit(e,n)!==0&&ht("Can't initialize onnxruntime.")},ao=async e=>{Cg(e.wasm.numThreads,Qp(e.logLevel))},so=async(e,n)=>{},yr=new Map,Ng=e=>{let n=xt(),i=n.stackSave();try{let a=n.stackAlloc(8);return n._OrtGetInputOutputCount(e,a,a+4)!==0&&ht("Can't get session input/output count."),[n.HEAP32[a/4],n.HEAP32[a/4+1]]}finally{n.stackRestore(i)}},zr=e=>{let n=xt(),i=n._malloc(e.byteLength);if(i===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return n.HEAPU8.set(e,i),[i,e.byteLength]},uo=async(e,n)=>{var u;let i,a,p=xt();Array.isArray(e)?[i,a]=e:e.buffer===p.HEAPU8.buffer?[i,a]=[e.byteOffset,e.byteLength]:[i,a]=zr(e);let o=0,s=0,d=[],c=[],r=[];try{if([s,d]=Kp(n),(n==null?void 0:n.externalData)&&p.mountExternalData){let x=[];for(let P of n.externalData){let N=typeof P=="string"?P:P.path;x.push(jr(typeof P=="string"?P:P.data).then(R=>{p.mountExternalData(N,R)}))}await Promise.all(x)}for(let x of(n==null?void 0:n.executionProviders)??[])if((typeof x=="string"?x:x.name)==="webnn"){if(p.shouldTransferToMLTensor=!1,p.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof x!="string"){let P=x,N=P==null?void 0:P.context,R=P==null?void 0:P.gpuDevice,ct=P==null?void 0:P.deviceType,st=P==null?void 0:P.numThreads,Dt=P==null?void 0:P.powerPreference;N?p.currentContext=N:R?p.currentContext=await navigator.ml.createContext(R):p.currentContext=await navigator.ml.createContext({deviceType:ct,numThreads:st,powerPreference:Dt})}else p.currentContext=await navigator.ml.createContext();break}o=await p._OrtCreateSession(i,a,s),o===0&&ht("Can't create a session."),p.currentContext&&(p.jsepRegisterMLContext(o,p.currentContext),p.currentContext=void 0,p.shouldTransferToMLTensor=!0);let[l,h]=Ng(o),f=!!(n!=null&&n.enableGraphCapture),m=[],y=[],_=[];for(let x=0;x<l;x++){let P=p._OrtGetInputName(o,x);P===0&&ht("Can't get an input name."),c.push(P),m.push(p.UTF8ToString(P))}for(let x=0;x<h;x++){let P=p._OrtGetOutputName(o,x);P===0&&ht("Can't get an output name."),r.push(P);let N=p.UTF8ToString(P);y.push(N)}return yr.set(o,[o,c,r,null,f,!1]),[o,m,y]}catch(l){throw c.forEach(h=>p._OrtFree(h)),r.forEach(h=>p._OrtFree(h)),o!==0&&p._OrtReleaseSession(o),l}finally{p._free(i),s!==0&&p._OrtReleaseSessionOptions(s),d.forEach(l=>p._free(l)),(u=p.unmountExternalData)==null||u.call(p)}},lo=e=>{var c;let n=xt(),i=yr.get(e);if(!i)throw new Error(`cannot release session. invalid session id: ${e}`);let[a,p,o,s,d]=i;s&&(d&&n._OrtClearBoundOutputs(s.handle),n._OrtReleaseBinding(s.handle)),(c=n.jsepOnReleaseSession)==null||c.call(n,e),p.forEach(r=>n._OrtFree(r)),o.forEach(r=>n._OrtFree(r)),n._OrtReleaseSession(a),yr.delete(e)},ed=(e,n,i,a,p,o=!1)=>{if(!e){n.push(0);return}let s=xt(),d=e[0],c=e[1],r=e[3],u,l;if(d==="string"&&(r==="gpu-buffer"||r==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&r!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${p} when enableGraphCapture is true.`);if(r==="gpu-buffer"){let m=e[2].gpuBuffer;l=qr(Hr(d),c);let y=s.jsepRegisterBuffer;if(!y)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');u=y(a,p,m,l)}else if(r==="ml-tensor"){let m=e[2].mlTensor;l=qr(Hr(d),c);let y=s.jsepRegisterMLTensor;if(!y)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');u=y(m,Hr(d),c)}else{let m=e[2];if(Array.isArray(m)){l=4*m.length,u=s._malloc(l),i.push(u);let y=u/4;for(let _=0;_<m.length;_++){if(typeof m[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);s.HEAPU32[y++]=Tt(m[_],i)}}else l=m.byteLength,u=s._malloc(l),i.push(u),s.HEAPU8.set(new Uint8Array(m.buffer,m.byteOffset,l),u)}let h=s.stackSave(),f=s.stackAlloc(4*c.length);try{let m=f/4;c.forEach(_=>s.HEAP32[m++]=_);let y=s._OrtCreateTensor(Hr(d),u,l,f,c.length,td(r));y===0&&ht(`Can't create tensor for input/output. session=${a}, index=${p}.`),n.push(y)}finally{s.stackRestore(h)}},fo=async(e,n,i,a,p,o)=>{var Z;let s=xt(),d=yr.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=d[0],r=d[1],u=d[2],l=d[3],h=d[4];d[5];let f=n.length,m=a.length,y=0,_=[],I=[],x=[],P=[],N=s.stackSave(),R=s.stackAlloc(f*4),ct=s.stackAlloc(f*4),st=s.stackAlloc(m*4),Dt=s.stackAlloc(m*4);try{(Z=s.jsepOnRunStart)==null||Z.call(s,c),[y,_]=jp(o);for(let U=0;U<f;U++)ed(i[U],I,P,e,n[U],h);for(let U=0;U<m;U++)ed(p[U],x,P,e,f+a[U],h);let Ot=R/4,Ae=ct/4,ft=st/4,$e=Dt/4;for(let U=0;U<f;U++)s.HEAPU32[Ot++]=I[U],s.HEAPU32[Ae++]=r[n[U]];for(let U=0;U<m;U++)s.HEAPU32[ft++]=x[U],s.HEAPU32[$e++]=u[a[U]];let Nt;Nt=await s._OrtRun(c,ct,R,f,Dt,m,st,y),Nt!==0&&ht("failed to call OrtRun().");let gt=[];for(let U=0;U<m;U++){let Mt=s.HEAPU32[st/4+U];if(Mt===x[U]){gt.push(p[U]);continue}let De=s.stackSave(),vt=s.stackAlloc(4*4),ae=!1,nt,it=0;try{s._OrtGetTensorData(Mt,vt,vt+4,vt+8,vt+12)!==0&&ht(`Can't access output tensor data on index ${U}.`);let ee=vt/4,Wt=s.HEAPU32[ee++];it=s.HEAPU32[ee++];let Le=s.HEAPU32[ee++],re=s.HEAPU32[ee++],_t=[];for(let et=0;et<re;et++)_t.push(s.HEAPU32[Le/4+et]);s._OrtFree(Le);let Pt=_t.reduce((et,at)=>et*at,1);nt=Yp(Wt);let Ft=l==null?void 0:l.outputPreferredLocations[a[U]];if(nt==="string"){if(Ft==="gpu-buffer"||Ft==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let et=[],at=it/4;for(let Lt=0;Lt<Pt;Lt++){let ue=s.HEAPU32[at++],Re=Lt===Pt-1?void 0:s.HEAPU32[at]-ue;et.push(s.UTF8ToString(ue,Re))}gt.push([nt,_t,et,"cpu"])}else if(Ft==="gpu-buffer"&&Pt>0){let et=s.jsepGetBuffer;if(!et)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let at=et(it),Lt=qr(Wt,Pt);if(Lt===void 0||!bo(nt))throw new Error(`Unsupported data type: ${nt}`);ae=!0,gt.push([nt,_t,{gpuBuffer:at,download:s.jsepCreateDownloader(at,Lt,nt),dispose:()=>{s._OrtReleaseTensor(Mt)}},"gpu-buffer"])}else if(Ft==="ml-tensor"&&Pt>0){let et=s.jsepEnsureTensor;if(!et)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(qr(Wt,Pt)===void 0||!go(nt))throw new Error(`Unsupported data type: ${nt}`);let at=await et(it,Wt,_t,!1);ae=!0,gt.push([nt,_t,{mlTensor:at,download:s.jsepCreateMLTensorDownloader(it,nt),dispose:()=>{s.jsepReleaseTensorId(it),s._OrtReleaseTensor(Mt)}},"ml-tensor"])}else{let et=Zp(nt),at=new et(Pt);new Uint8Array(at.buffer,at.byteOffset,at.byteLength).set(s.HEAPU8.subarray(it,it+at.byteLength)),gt.push([nt,_t,at,"cpu"])}}finally{s.stackRestore(De),nt==="string"&&it&&s._free(it),ae||s._OrtReleaseTensor(Mt)}}return l&&!h&&(s._OrtClearBoundOutputs(l.handle),yr.set(e,[c,r,u,l,h,!1])),gt}finally{s.stackRestore(N),I.forEach(Ot=>s._OrtReleaseTensor(Ot)),x.forEach(Ot=>s._OrtReleaseTensor(Ot)),P.forEach(Ot=>s._free(Ot)),y!==0&&s._OrtReleaseRunOptions(y),_.forEach(Ot=>s._free(Ot))}},co=e=>{let n=xt(),i=yr.get(e);if(!i)throw new Error("invalid session id");let a=i[0],p=n._OrtEndProfiling(a);p===0&&ht("Can't get an profile file name."),n._OrtFree(p)},po=e=>{let n=[];for(let i of e){let a=i[2];!Array.isArray(a)&&"buffer"in a&&n.push(a.buffer)}return n}}),Je,Kt,Xr,xo,To,yo,Zi,Qi,xr,Tr,Gg,rd,nd,od,id,ad,sd,ud,ta=O(()=>{Yt(),qi(),Ke(),Vr(),Je=()=>!!z.wasm.proxy&&typeof document<"u",Xr=!1,xo=!1,To=!1,Qi=new Map,xr=(e,n)=>{let i=Qi.get(e);i?i.push(n):Qi.set(e,[n])},Tr=()=>{if(Xr||!xo||To||!Kt)throw new Error("worker not ready")},Gg=e=>{switch(e.data.type){case"init-wasm":Xr=!1,e.data.err?(To=!0,Zi[1](e.data.err)):(xo=!0,Zi[0]()),yo&&(URL.revokeObjectURL(yo),yo=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let n=Qi.get(e.data.type);e.data.err?n.shift()[1](e.data.err):n.shift()[0](e.data.out);break}}},rd=async()=>{if(!xo){if(Xr)throw new Error("multiple calls to 'initWasm()' detected.");if(To)throw new Error("previous call to 'initWasm()' failed.");if(Xr=!0,Je())return new Promise((e,n)=>{Kt==null||Kt.terminate(),Wp().then(([i,a])=>{try{Kt=a,Kt.onerror=o=>n(o),Kt.onmessage=Gg,Zi=[e,n];let p={type:"init-wasm",in:z};Kt.postMessage(p),yo=i}catch(p){n(p)}},n)});try{await io(z.wasm),await ao(z),xo=!0}catch(e){throw To=!0,e}finally{Xr=!1}}},nd=async e=>{if(Je())return Tr(),new Promise((n,i)=>{xr("init-ep",[n,i]);let a={type:"init-ep",in:{epName:e,env:z}};Kt.postMessage(a)});await so(z,e)},od=async e=>Je()?(Tr(),new Promise((n,i)=>{xr("copy-from",[n,i]);let a={type:"copy-from",in:{buffer:e}};Kt.postMessage(a,[e.buffer])})):zr(e),id=async(e,n)=>{if(Je()){if(n!=null&&n.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Tr(),new Promise((i,a)=>{xr("create",[i,a]);let p={type:"create",in:{model:e,options:{...n}}},o=[];e instanceof Uint8Array&&o.push(e.buffer),Kt.postMessage(p,o)})}else return uo(e,n)},ad=async e=>{if(Je())return Tr(),new Promise((n,i)=>{xr("release",[n,i]);let a={type:"release",in:e};Kt.postMessage(a)});lo(e)},sd=async(e,n,i,a,p,o)=>{if(Je()){if(i.some(s=>s[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(p.some(s=>s))throw new Error("pre-allocated output tensor is not supported for proxy.");return Tr(),new Promise((s,d)=>{xr("run",[s,d]);let c=i,r={type:"run",in:{sessionId:e,inputIndices:n,inputs:c,outputIndices:a,options:o}};Kt.postMessage(r,po(c))})}else return fo(e,n,i,a,p,o)},ud=async e=>{if(Je())return Tr(),new Promise((n,i)=>{xr("end-profiling",[n,i]);let a={type:"end-profiling",in:e};Kt.postMessage(a)});co(e)}}),ld,Mg,wo,fd=O(()=>{Yt(),ta(),Ji(),oo(),Yi(),ld=(e,n)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${n()}`)}},Mg=e=>{switch(e[3]){case"cpu":return new yt(e[0],e[2],e[1]);case"gpu-buffer":{let n=e[0];if(!bo(n))throw new Error(`not supported data type: ${n} for deserializing GPU tensor`);let{gpuBuffer:i,download:a,dispose:p}=e[2];return yt.fromGpuBuffer(i,{dataType:n,dims:e[1],download:a,dispose:p})}case"ml-tensor":{let n=e[0];if(!go(n))throw new Error(`not supported data type: ${n} for deserializing MLTensor tensor`);let{mlTensor:i,download:a,dispose:p}=e[2];return yt.fromMLTensor(i,{dataType:n,dims:e[1],download:a,dispose:p})}default:throw new Error(`invalid data location: ${e[3]}`)}},wo=class{async fetchModelAndCopyToWasmMemory(e){return od(await jr(e))}async loadModel(e,n){Fe();let i;typeof e=="string"?i=await this.fetchModelAndCopyToWasmMemory(e):i=e,[this.sessionId,this.inputNames,this.outputNames]=await id(i,n),Ce()}async dispose(){return ad(this.sessionId)}async run(e,n,i){Fe();let a=[],p=[];Object.entries(e).forEach(l=>{let h=l[0],f=l[1],m=this.inputNames.indexOf(h);if(m===-1)throw new Error(`invalid input '${h}'`);a.push(f),p.push(m)});let o=[],s=[];Object.entries(n).forEach(l=>{let h=l[0],f=l[1],m=this.outputNames.indexOf(h);if(m===-1)throw new Error(`invalid output '${h}'`);o.push(f),s.push(m)});let d=a.map((l,h)=>ld(l,()=>`input "${this.inputNames[p[h]]}"`)),c=o.map((l,h)=>l?ld(l,()=>`output "${this.outputNames[s[h]]}"`):null),r=await sd(this.sessionId,p,d,s,c,i),u={};for(let l=0;l<r.length;l++)u[this.outputNames[s[l]]]=o[l]??Mg(r[l]);return Ce(),u}startProfiling(){}endProfiling(){ud(this.sessionId)}}}),pd={};Or(pd,{OnnxruntimeWebAssemblyBackend:()=>vo,initializeFlags:()=>cd,wasmBackend:()=>Ug});var cd,vo,Ug,dd=O(()=>{Yt(),ta(),fd(),Vr(),cd=()=>{if((typeof z.wasm.initTimeout!="number"||z.wasm.initTimeout<0)&&(z.wasm.initTimeout=0),z.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),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)if(typeof self<"u"&&!self.crossOriginIsolated)z.wasm.numThreads=1;else{let e=typeof navigator>"u"?Co("node:os").cpus().length:navigator.hardwareConcurrency;z.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},vo=class{async init(e){cd(),await rd(),await nd(e)}async createInferenceSessionHandler(e,n){let i=new wo;return await i.loadModel(e,n),Promise.resolve(i)}},Ug=new vo});Yt(),Yt(),Yt();var Ds="1.20.1";{let e=(Fp(),sn(Bp)).onnxjsBackend;nr("webgl",e,-10)}{let e=(dd(),sn(pd)).wasmBackend;nr("cpu",e,10),nr("wasm",e,10)}Object.defineProperty(z.versions,"web",{value:Ds,enumerable:!0});/*! Bundled license information:
@@ -1828,5 +1828,5 @@ as ORT format: ${p}`)}}loadFromOnnxFormat(e,n){let i=Dp.onnx.ModelProto.decode(e
1828
1828
  *
1829
1829
  * SPDX-License-Identifier: Apache-2.0
1830
1830
  *)
1831
- */function C(e){if(e.startsWith("blob:"))return!0;try{return new URL(e),!0}catch{return!1}}const T=(e,n)=>!n||e.startsWith("http")?new URL(e).href:e?n.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):n;class t{constructor(){this.resolvedUriCache=new Map}async resolveUri(n,i){if(!i)throw new Error("Asset URI is undefined.");if(this.resolvedUriCache.has(i))return this.resolvedUriCache.get(i);let a;if(C(i)?a=i:i.match(/\.[a-z0-9]+$/i)?typeof n.assetUrlResolver=="function"&&(a=await n.assetUrlResolver(i,n)):a=T(i,n.baseUrl),!a)throw new Error(`Failed to resolve asset URI: ${i}`);return this.resolvedUriCache.set(i,a),a}}const d$1=new t;function stripQueryParams(e){try{const n=new URL(e);return n.search="",n.toString()}catch{return e}}async function loadAndCacheFile(e){const n=await caches.open("ladon-cache"),i=stripQueryParams(e),a=await n.match(i);if(a)return a.arrayBuffer();const p=await fetch(e);if(!p.ok)throw new Error(`Failed to fetch file: ${e}`);const o=p.headers.get("Content-Type")||"binary/octet-stream";if(!o.includes("application/wasm")&&!o.includes("binary/octet-stream"))throw new Error(`Unexpected MIME type: ${o} for ${i}`);const s=await p.arrayBuffer(),d=new Response(s,{headers:{"Content-Type":o,"Content-Length":s.byteLength.toString()}});return await n.put(i,d),s}const ONNX_WASM_FILENAME="ort-wasm-simd-threaded.wasm";class ModelManager{constructor(){this.modelSessions={}}async loadModel(n){const{mask:i,executionProviders:a}=n;z.wasm.numThreads=1;const p=await d$1.resolveUri(n,n.wasmUri);if(p)try{z.wasm.wasmBinary=await loadAndCacheFile(p+ONNX_WASM_FILENAME)}catch(d){console.warn("Failed to load or cache WASM file. Using WASM paths.",d),z.wasm.wasmPaths=p}const o=await d$1.resolveUri(n,i.modelUri);let s=this.modelSessions[o];if(!s){const c={executionProviders:a!=null&&a.length?a:["wasm"]};try{const r=await loadAndCacheFile(o);s=await Yd.create(r,c)}catch(r){console.warn("Failed to load or cache model file. Using model URL.",r),s=await Yd.create(o,c)}}return this.modelSessions[o]=s,await this.warmupModel(s,i.inputSize,i.modelRank),s}async warmupModel(n,i={width:1280,height:720},a=3,p="float32"){const o=i.height*i.width,s=new Float32Array(a*o).fill(0),d=new yt(p,s,[1,a,i.height,i.width]),c={[n.inputNames[0]]:d};if(a===3){const r=new Float32Array(o).fill(0),u=new yt(p,r,[1,1,i.height,i.width]);c[n.inputNames[1]]=u}await n.run(c)}getModelSession(n){return this.modelSessions[n]}async destroyModel(n){const i=this.modelSessions[n];i&&(await i.release(),delete this.modelSessions[n])}}const modelManager=new ModelManager;class LadonGenerator{constructor(n){this.config=n,this.lastMaskGenerationTime=0;const{height:i,width:a}=this.config.mask.outputSize;this.lastMask=new yt("float32",new Float32Array(i*a),[1,1,i,a]),this.lastResult={data:this.lastMask.data,facesAndLandmarks:{data:new Float32Array(0),dims:[]},gesture:new Float32Array(0),motion:0,timestamp:0,warm:!1}}isLoaded(){return!!this.maskModel}preprocess(n,i){const{modelRank:a,inputSize:p,outputSize:o}=this.config.mask,{height:s,width:d}=p,c=s*d;this.output??(this.output=new Float32Array(c*a));const r=n.length/4;for(let h=0;h<3;h++)for(let f=0;f<r;f++)this.output[f+h*c]=n[f*4+(2-h)];const u=o.width/d,l=o.height/s;for(let h=0;h<d;h++){const f=Math.floor(h*u);for(let m=0;m<s;m++){const y=Math.floor(m*l),_=f+y*o.width,I=h+m*d+3*c,x=Math.min(Math.max(i[_],0),255);this.output[I]=x}}return this.output}getTimeSinceLastGeneration(){return Date.now()-this.lastMaskGenerationTime}async getLadonOutput(n,i){var o,s,d,c;if(!this.maskModel)throw new Error("[ladon-ts] Mask model not loaded.");if(this.getTimeSinceLastGeneration()<this.config.mask.generationIntervalMs)return{data:this.lastMask.data,facesAndLandmarks:this.lastResult.facesAndLandmarks,gesture:this.lastResult.gesture,motion:this.lastResult.motion,warm:!1,timestamp:i};this.lastMaskGenerationTime=Date.now();const a=new yt("float32",this.preprocess(n,this.lastMask.data),[1,this.config.mask.modelRank,this.config.mask.inputSize.height,this.config.mask.inputSize.width]),p=await this.maskModel.run({input:a});return this.lastMask=p.segmentation,this.lastResult={data:this.lastMask.data??new Float32Array(0),facesAndLandmarks:{data:((o=p.faces_and_landmarks)==null?void 0:o.data)??new Float32Array(0),dims:((s=p.faces_and_landmarks)==null?void 0:s.dims)??[]},gesture:((d=p.gesture)==null?void 0:d.data)??new Float32Array(0),motion:((c=p.motion)==null?void 0:c.data[0])??0,timestamp:i,warm:!0},this.lastResult}async load(){if(this.modelUrl=await d$1.resolveUri(this.config,this.config.mask.modelUri),this.maskModel=modelManager.getModelSession(this.modelUrl),this.maskModel??(this.maskModel=await modelManager.loadModel(this.config)),!this.maskModel)throw new Error("Failed to load the ONNX model.")}async postRender(){}async destroy(){if(!this.modelUrl)throw new Error("[ladon-ts] Generator teardown failed. Model URL is not defined.");await modelManager.destroyModel(this.modelUrl),this.modelUrl=void 0,this.maskModel=void 0,this.output=void 0}}const MAX_QUEUE_SIZE=3,queue=[];let preloadPromise=null,generator,processing=!1;async function processQueue(){if(!processing){for(processing=!0;queue.length>0;){const{image:e,timestamp:n}=queue.shift();await handleGenerate(e,n)}setTimeout(()=>{processing=!1},0)}}self.addEventListener("message",async e=>{const{type:n,config:i,image:a,timestamp:p}=e.data;try{switch(n){case"preload":i&&(preloadPromise=handlePreload(i),await preloadPromise);break;case"init":i&&(preloadPromise&&await preloadPromise,await handleInit(i));break;case"generate":if(a){if(queue.length>=MAX_QUEUE_SIZE){const o=queue.shift();o&&postMessage({facesAndLandmarks:null,gesture:null,mask:null,motion:null,timestamp:o.timestamp,status:"dropped",warm:!1})}queue.push({image:a,timestamp:p}),processQueue()}break;case"destroy":await handleDestroy();break;default:console.warn(`[ladon-ts] Worker generator recieved unknown message: ${JSON.stringify(e.data)}`)}}catch(o){console.error(`[ladon-ts] Worker generator error handling message: ${o}`),postMessage({status:"error",error:o.message})}});async function handlePreload(e){await modelManager.loadModel(e),postMessage({status:"preloaded"})}async function handleInit(e){generator=new LadonGenerator(e),await generator.load(),postMessage({status:"initialized"})}async function handleGenerate(e,n){if(!generator||!generator.isLoaded()){console.warn("[ladon-ts] Generator is not initialized");return}if(!e){console.warn("[ladon-ts] No valid input provided for generation");return}const i=await generator.getLadonOutput(e,n);postMessage({facesAndLandmarks:i.facesAndLandmarks,gesture:i.gesture,mask:i.data,motion:i.motion,timestamp:i.timestamp,status:"generated",warm:i.warm})}async function handleDestroy(){generator?await generator.destroy():console.warn("[ladon-ts] No generator to destroy"),postMessage({status:"destroyed"})}})();
1831
+ */function C(e){if(e.startsWith("blob:"))return!0;try{return new URL(e),!0}catch{return!1}}const T=(e,n)=>!n||e.startsWith("http")?new URL(e).href:e?n.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):n;class t{constructor(){this.resolvedUriCache=new Map}async resolveUri(n,i){if(!i)throw new Error("Asset URI is undefined.");if(this.resolvedUriCache.has(i))return this.resolvedUriCache.get(i);let a;if(C(i)?a=i:i.match(/\.[a-z0-9]+$/i)?typeof n.assetUrlResolver=="function"&&(a=await n.assetUrlResolver(i,n)):a=T(i,n.baseUrl),!a)throw new Error(`Failed to resolve asset URI: ${i}`);return this.resolvedUriCache.set(i,a),a}}const d$1=new t;function stripQueryParams(e){try{const n=new URL(e);return n.search="",n.toString()}catch{return e}}async function loadAndCacheFile(e){const n=await caches.open("ladon-cache"),i=stripQueryParams(e),a=await n.match(i);if(a)return a.arrayBuffer();const p=await fetch(e);if(!p.ok)throw new Error(`Failed to fetch file: ${e}`);const o=p.headers.get("Content-Type")||"binary/octet-stream";if(!o.includes("application/wasm")&&!o.includes("binary/octet-stream"))throw new Error(`Unexpected MIME type: ${o} for ${i}`);const s=await p.arrayBuffer(),d=new Response(s,{headers:{"Content-Type":o,"Content-Length":s.byteLength.toString()}});return await n.put(i,d),s}const ONNX_WASM_FILENAME="ort-wasm-simd-threaded.wasm";class ModelManager{constructor(){this.modelSessions={}}async loadModel(n){const{mask:i,executionProviders:a}=n;z.wasm.numThreads=1;const p=await d$1.resolveUri(n,n.wasmUri);if(p)try{z.wasm.wasmBinary=await loadAndCacheFile(p+ONNX_WASM_FILENAME)}catch(d){console.warn("Failed to load or cache WASM file. Using WASM paths.",d),z.wasm.wasmPaths=p}const o=await d$1.resolveUri(n,i.modelUri);let s=this.modelSessions[o];if(!s){const c={executionProviders:a!=null&&a.length?a:["wasm"]};try{const r=await loadAndCacheFile(o);s=await Yd.create(r,c)}catch(r){console.warn("Failed to load or cache model file. Using model URL.",r),s=await Yd.create(o,c)}}return this.modelSessions[o]=s,await this.warmupModel(s,i.inputSize,i.modelRank),s}async warmupModel(n,i={width:1280,height:720},a=3,p="float32"){const o=i.height*i.width,s=new Float32Array(a*o).fill(0),d=new yt(p,s,[1,a,i.height,i.width]),c={[n.inputNames[0]]:d};if(a===3){const r=new Float32Array(o).fill(0),u=new yt(p,r,[1,1,i.height,i.width]);c[n.inputNames[1]]=u}await n.run(c)}getModelSession(n){return this.modelSessions[n]}async destroyModel(n){const i=this.modelSessions[n];i&&(await i.release(),delete this.modelSessions[n])}}const modelManager=new ModelManager;class LadonGenerator{constructor(n){this.config=n,this.lastMaskGenerationTime=0;const{height:i,width:a}=this.config.mask.outputSize;this.lastMask=new yt("float32",new Float32Array(i*a),[1,1,i,a]),this.lastResult={data:this.lastMask.data,facesAndLandmarks:{data:new Float32Array(0),dims:[]},gesture:new Float32Array(0),motion:0,timestamp:0,warm:!1}}isLoaded(){return!!this.maskModel}preprocess(n,i){const{modelRank:a,inputSize:p,outputSize:o}=this.config.mask,{height:s,width:d}=p,c=s*d;this.output??(this.output=new Float32Array(c*a));const r=n.length/4;for(let h=0;h<3;h++)for(let f=0;f<r;f++)this.output[f+h*c]=n[f*4+(2-h)];const u=o.width/d,l=o.height/s;for(let h=0;h<d;h++){const f=Math.floor(h*u);for(let m=0;m<s;m++){const y=Math.floor(m*l),_=f+y*o.width,I=h+m*d+3*c,x=Math.min(Math.max(i[_],0),255);this.output[I]=x}}return this.output}getTimeSinceLastGeneration(){return Date.now()-this.lastMaskGenerationTime}async getLadonOutput(n,i){var o,s,d,c;if(!this.maskModel)throw new Error("[ladon-ts] Mask model not loaded.");if(this.getTimeSinceLastGeneration()<this.config.mask.generationIntervalMs)return{data:this.lastMask.data,facesAndLandmarks:this.lastResult.facesAndLandmarks,gesture:this.lastResult.gesture,motion:this.lastResult.motion,warm:!1,timestamp:i};this.lastMaskGenerationTime=Date.now();const a=new yt("float32",this.preprocess(n,this.lastMask.data),[1,this.config.mask.modelRank,this.config.mask.inputSize.height,this.config.mask.inputSize.width]),p=await this.maskModel.run({input:a});return this.lastMask=p.segmentation,this.lastResult={data:this.lastMask.data??new Float32Array(0),facesAndLandmarks:{data:((o=p.faces_and_landmarks)==null?void 0:o.data)??new Float32Array(0),dims:((s=p.faces_and_landmarks)==null?void 0:s.dims)??[]},gesture:((d=p.gesture)==null?void 0:d.data)??new Float32Array(0),motion:((c=p.motion)==null?void 0:c.data[0])??0,timestamp:i,warm:!0},this.lastResult}async load(){if(this.modelUrl=await d$1.resolveUri(this.config,this.config.mask.modelUri),this.maskModel=modelManager.getModelSession(this.modelUrl),this.maskModel??(this.maskModel=await modelManager.loadModel(this.config)),!this.maskModel)throw new Error("Failed to load the ONNX model.")}async process(){}async destroy(){if(!this.modelUrl)throw new Error("[ladon-ts] Generator teardown failed. Model URL is not defined.");await modelManager.destroyModel(this.modelUrl),this.modelUrl=void 0,this.maskModel=void 0,this.output=void 0}}const MAX_QUEUE_SIZE=3,queue=[];let preloadPromise=null,generator,processing=!1;async function processQueue(){if(!processing){for(processing=!0;queue.length>0;){const{image:e,timestamp:n}=queue.shift();await handleGenerate(e,n)}setTimeout(()=>{processing=!1},0)}}self.addEventListener("message",async e=>{const{type:n,config:i,image:a,timestamp:p}=e.data;try{switch(n){case"preload":i&&(preloadPromise=handlePreload(i),await preloadPromise);break;case"init":i&&(preloadPromise&&await preloadPromise,await handleInit(i));break;case"generate":if(a){if(queue.length>=MAX_QUEUE_SIZE){const o=queue.shift();o&&postMessage({facesAndLandmarks:null,gesture:null,mask:null,motion:null,timestamp:o.timestamp,status:"dropped",warm:!1})}queue.push({image:a,timestamp:p}),processQueue()}break;case"destroy":await handleDestroy();break;default:console.warn(`[ladon-ts] Worker generator recieved unknown message: ${JSON.stringify(e.data)}`)}}catch(o){console.error(`[ladon-ts] Worker generator error handling message: ${o}`),postMessage({status:"error",error:o.message})}});async function handlePreload(e){await modelManager.loadModel(e),postMessage({status:"preloaded"})}async function handleInit(e){generator=new LadonGenerator(e),await generator.load(),postMessage({status:"initialized"})}async function handleGenerate(e,n){if(!generator||!generator.isLoaded()){console.warn("[ladon-ts] Generator is not initialized");return}if(!e){console.warn("[ladon-ts] No valid input provided for generation");return}const i=await generator.getLadonOutput(e,n);postMessage({facesAndLandmarks:i.facesAndLandmarks,gesture:i.gesture,mask:i.data,motion:i.motion,timestamp:i.timestamp,status:"generated",warm:i.warm})}async function handleDestroy(){generator?await generator.destroy():console.warn("[ladon-ts] No generator to destroy"),postMessage({status:"destroyed"})}})();
1832
1832
  //# sourceMappingURL=segmentation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"segmentation.js","sources":["../src/shim.ts","../src/console-overrides.ts","../../build/module/lib/util.js","../../build/module/lib/resource-loader.js","../src/util.ts","../src/model-manager.ts","../src/ladon-generator.ts","../src/segmentation.ts"],"sourcesContent":["/**\n * This file is used to provide a shim for the document object in a web worker.\n * The document object is not available in a web worker, so we need to provide a shim\n * to prevent errors when running the code in a web worker.\n * \n * See: https://github.com/vitejs/vite/issues/9879#issuecomment-1372112651\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(self.document as any) = {\n baseURI: location.origin\n};","/**\n * Override console methods to send logs to the main thread for display in the UI.\n */\n\nconst originalConsoleLog = console.log;\nconst originalConsoleWarn = console.warn;\nconst originalConsoleError = console.error;\n\nconsole.log = (...args) => {\n postMessage({ type: 'log', message: args.join(' '), severity: 'log' });\n originalConsoleLog(...args);\n};\n\nconsole.warn = (...args) => {\n postMessage({ type: 'log', message: args.join(' '), severity: 'warn' });\n originalConsoleWarn(...args);\n};\n\nconsole.error = (...args) => {\n postMessage({ type: 'log', message: args.join(' '), severity: 'error' });\n originalConsoleError(...args);\n};","var I = /* @__PURE__ */ ((o) => (o.Nearest = \"nearest\", o))(I || {});\nconst U = (o, n, u, r, e) => {\n const l = new Uint8ClampedArray(r * e * 4), p = n / r, y = u / e, s = n * 4;\n let a = 0;\n for (let t = 0; t < e; t++) {\n const f = Math.floor(t * y) * s;\n for (let c = 0; c < r; c++) {\n const m = f + Math.floor(c * p) * 4;\n l[a++] = o[m], l[a++] = o[m + 1], l[a++] = o[m + 2], l[a++] = o[m + 3];\n }\n }\n return l;\n};\nfunction A(o, n, u, r, e) {\n const l = new Uint8ClampedArray(r * e);\n if (n === r && u === e) {\n for (let s = 0; s < o.length; s++)\n l[s] = Math.min(Math.max(o[s], 0), 255);\n return l;\n }\n const p = (n - 1) / (r - 1), y = (u - 1) / (e - 1);\n for (let s = 0; s < e; s++)\n for (let a = 0; a < r; a++) {\n const t = p * a, f = y * s, c = Math.floor(t), m = Math.floor(f), S = Math.min(Math.ceil(t), n - 1), x = Math.min(Math.ceil(f), u - 1), w = t - c, i = f - m, M = o[m * n + c], h = o[m * n + S], k = o[x * n + c], P = o[x * n + S], E = M * (1 - w) * (1 - i) + h * w * (1 - i) + k * (1 - w) * i + P * w * i;\n l[s * r + a] = Math.min(Math.max(E, 0), 255);\n }\n return l;\n}\nfunction d(o, n, u, r, e) {\n const l = new Uint8ClampedArray(r * e), p = n / r, y = u / e, s = (t, f) => {\n if (t === 0) return 1;\n if (t < 0 && (t = -t), t < f) {\n const c = Math.PI * t;\n return f * Math.sin(c) * Math.sin(c / f) / (c * c);\n }\n return 0;\n }, a = 3;\n for (let t = 0; t < e; t++)\n for (let f = 0; f < r; f++) {\n const c = f * p, m = t * y, S = Math.floor(c), x = Math.floor(m);\n let w = 0, i = 0;\n for (let M = x - a + 1; M <= x + a; M++)\n for (let h = S - a + 1; h <= S + a; h++)\n if (h >= 0 && h < n && M >= 0 && M < u) {\n const k = o[M * n + h], P = s(c - h, a) * s(m - M, a);\n w += k * P, i += P;\n }\n l[t * r + f] = i !== 0 ? Math.round(w / i) : 0;\n }\n return l;\n}\nfunction L(o, n, u) {\n const r = o.createShader(n);\n if (!r)\n throw new Error(\"[ladon-ts] Error creating shader\");\n if (o.shaderSource(r, u), o.compileShader(r), !o.getShaderParameter(r, o.COMPILE_STATUS)) {\n const e = o.getShaderInfoLog(r) ?? \"unknown error compiling shader.\";\n throw new Error(\"[ladon-ts] \" + e);\n }\n return r;\n}\nfunction R(o, n, u) {\n const r = o.createProgram();\n if (!r)\n throw new Error(\"[ladon-ts] Error creating GPU program\");\n if (o.attachShader(r, n), o.attachShader(r, u), o.linkProgram(r), !o.getProgramParameter(r, o.LINK_STATUS)) {\n const e = o.getProgramInfoLog(r) ?? \"unknown error linking program.\";\n throw new Error(\"[ladon-ts] \" + e);\n }\n return r;\n}\nfunction C(o) {\n if (o.startsWith(\"blob:\"))\n return !0;\n try {\n return new URL(o), !0;\n } catch {\n return !1;\n }\n}\nconst T = (o, n) => !n || o.startsWith(\"http\") ? new URL(o).href : o ? n.replace(/\\/+$/, \"\") + \"/\" + o.replace(/^\\/+/, \"\") : n;\nexport {\n I as InterpolationMethod,\n A as bilinearUpsample,\n L as compileShader,\n C as isResolvedUri,\n d as lanczos3Upsample,\n R as linkProgram,\n U as resizeImage,\n T as toAbsoluteURI\n};\n//# sourceMappingURL=util.js.map\n","import { isResolvedUri as l, toAbsoluteURI as s } from \"./util.js\";\nclass t {\n constructor() {\n this.resolvedUriCache = /* @__PURE__ */ new Map();\n }\n /**\n * Resolves the full URL for a given asset. Non-file URIs are treated as paths and resolved\n * using the `toAbsoluteURI` method. If the assetUri is already resolved, or if it's found in\n * cache, it will be returned directly. If an assetUrlResolver function is provided in the\n * configuration, it will be used to resolve the URL if the assetUri is not fully qualified,\n * a blob URL, or in the cache.\n *\n * @param config - The preload configuration.\n * @param assetUri - The asset URI from the config.\n * @returns The resolved full URL.\n */\n async resolveUri(o, e) {\n if (!e)\n throw new Error(\"Asset URI is undefined.\");\n if (this.resolvedUriCache.has(e))\n return this.resolvedUriCache.get(e);\n let r;\n if (l(e) ? r = e : e.match(/\\.[a-z0-9]+$/i) ? typeof o.assetUrlResolver == \"function\" && (r = await o.assetUrlResolver(e, o)) : r = s(e, o.baseUrl), !r)\n throw new Error(`Failed to resolve asset URI: ${e}`);\n return this.resolvedUriCache.set(e, r), r;\n }\n}\nconst d = new t();\nexport {\n t as ResourceLoader,\n d as resourceLoader\n};\n//# sourceMappingURL=resource-loader.js.map\n","export { isResolvedUri, toAbsoluteURI } from '@webex/ladon-ts';\n\n/**\n * Helper to strip query params.\n *\n * @param url - The URL to strip query params from.\n * @returns The URL without query params.\n */\nfunction stripQueryParams(url: string): string {\n try {\n const u = new URL(url);\n u.search = '';\n return u.toString();\n } catch {\n return url;\n }\n}\n\n/**\n * Fetches a JavaScript module from the given URL, caches it in the 'ladon-cache' \n * Cache API if the URL is HTTP(S), and returns a Blob URL for use with APIs.\n * \n * @param url - The URL of the JavaScript module to fetch.\n * @returns A promise that resolves to a Blob URL for the fetched module.\n */\nexport async function loadAndCacheFile(fileUrl: string): Promise<ArrayBufferLike | Uint8Array> {\n const cache = await caches.open('ladon-cache');\n\n // Normalize the URL by stripping query parameters\n const normalizedUrl = stripQueryParams(fileUrl);\n\n // Try to get the file from cache using its full URL\n const cachedResponse = await cache.match(normalizedUrl);\n if (cachedResponse) {\n return cachedResponse.arrayBuffer();\n }\n\n // If not in cache, fetch and cache the file\n const response = await fetch(fileUrl);\n\n // Ensure the response is valid\n if (!response.ok) {\n throw new Error(`Failed to fetch file: ${fileUrl}`);\n }\n\n const contentType = response.headers.get('Content-Type') || 'binary/octet-stream';\n\n // Validate expected MIME types\n if (!contentType.includes('application/wasm') && !contentType.includes('binary/octet-stream')) {\n throw new Error(`Unexpected MIME type: ${contentType} for ${normalizedUrl}`);\n }\n\n const fileBinary = await response.arrayBuffer();\n\n // Cache the response with proper headers\n const cachedResponseWithHeaders = new Response(fileBinary, {\n headers: {\n 'Content-Type': contentType,\n 'Content-Length': fileBinary.byteLength.toString(),\n },\n });\n\n // Store the response in the cache using the full URL as the key\n await cache.put(normalizedUrl, cachedResponseWithHeaders);\n\n return fileBinary;\n}\n","import * as ort from 'onnxruntime-web';\nimport { PreloadConfig, ResolutionConfig, resourceLoader } from '@webex/ladon-ts';\n\nimport { loadAndCacheFile } from './util';\n\n// There is only a single WASM file for all WebAssembly binaries now.\nconst ONNX_WASM_FILENAME = 'ort-wasm-simd-threaded.wasm';\n\n/**\n * Resource manager used to load resources for the segmentation worker.\n */\nexport class ModelManager {\n private modelSessions: Record<string, ort.InferenceSession> = {};\n\n /**\n * Load the model using the provided configuration. This gets called by the worker when using\n * the worker generator.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the model is preloaded.\n */\n public async loadModel(config: PreloadConfig) {\n const { mask, executionProviders: providers } = config;\n\n // Lock to a single thread to avoid performance issues.\n ort.env.wasm.numThreads = 1;\n\n // Get the resolved paths for the WASM binary.\n const wasmPaths = await resourceLoader.resolveUri(config, config.wasmUri);\n\n if (wasmPaths) {\n try {\n ort.env.wasm.wasmBinary = await loadAndCacheFile(wasmPaths + ONNX_WASM_FILENAME);\n } catch (error) {\n console.warn('Failed to load or cache WASM file. Using WASM paths.', error);\n ort.env.wasm.wasmPaths = wasmPaths;\n }\n }\n\n // Resolve the model URL.\n const modelUrl = await resourceLoader.resolveUri(config, mask.modelUri);\n let modelSession = this.modelSessions[modelUrl];\n\n // If the model session is not already cached, create a new session and cache.\n if (!modelSession) {\n // Allows the user to specify the execution providers to use. The default is the WASM provider.\n // TODO: Add and test support for other execution providers.\n const executionProviders = providers?.length ? providers : ['wasm'];\n const sessionOptions = { executionProviders };\n\n // First try to get the model binary either from cache or by fetching and caching it.\n // If that fails, fall back to the model URL.\n try {\n const modelBinary = await loadAndCacheFile(modelUrl);\n modelSession = await ort.InferenceSession.create(modelBinary, sessionOptions);\n } catch (error) {\n console.warn('Failed to load or cache model file. Using model URL.', error);\n modelSession = await ort.InferenceSession.create(modelUrl, sessionOptions);\n }\n }\n\n // Cache the model session.\n this.modelSessions[modelUrl] = modelSession;\n\n // Warmup the model with a dummy input to avoid latency when running the model for the first time.\n await this.warmupModel(modelSession, mask.inputSize, mask.modelRank);\n\n return modelSession;\n }\n\n /**\n * Warmup the model session with a dummy input to avoid latency when running the model for the first time.\n *\n * @param {ort.InferenceSession} session The model session.\n * @param {ResolutionConfig} inputSize The input size of the model.\n * @param {number} inputChannels The number of input channels (e.g., RGB is 3).\n * @param {ort.Tensor.Type} inputType The input tensor type.\n * @returns {Promise<void>} A promise that resolves when the model is warmed up.\n * @example\n * await warmupModel(session, inputSize, inputChannels, inputType);\n */\n public async warmupModel(\n session: ort.InferenceSession,\n inputSize: ResolutionConfig = { width: 1280, height: 720 },\n inputChannels = 3,\n inputType: ort.Tensor.Type = 'float32'\n ): Promise<void> {\n const numPixels = inputSize.height * inputSize.width;\n const dummyInputData = new Float32Array(inputChannels * numPixels).fill(0);\n const dummyInput = new ort.Tensor(inputType, dummyInputData, [\n 1,\n inputChannels,\n inputSize.height,\n inputSize.width,\n ]);\n const feed = { [session.inputNames[0]]: dummyInput };\n\n // Use an additional dummy tensor if the model expects a previous mask.\n if (inputChannels === 3) {\n const dummyMaskData = new Float32Array(numPixels).fill(0);\n const prevMaskTensor = new ort.Tensor(inputType, dummyMaskData, [\n 1,\n 1,\n inputSize.height,\n inputSize.width,\n ]);\n feed[session.inputNames[1]] = prevMaskTensor;\n }\n\n // Run the model with the dummy input to warm it up.\n await session.run(feed);\n }\n\n /**\n * Get the model session for the provided model URL.\n *\n * @param {string} modelUrl The model URL.\n * @returns {ort.InferenceSession} The model session.\n * @example\n * const session = getModelSession(modelUrl);\n */\n public getModelSession(modelUrl: string) {\n return this.modelSessions[modelUrl];\n }\n\n /**\n * Clear the model sessions cache.\n *\n * @example\n * modelManager.destroyModel();\n */\n public async destroyModel(modelUrl: string) {\n const session = this.modelSessions[modelUrl];\n if (session) {\n await session.release();\n delete this.modelSessions[modelUrl];\n }\n }\n \n}\n\nexport const modelManager = new ModelManager();","import * as ort from 'onnxruntime-web';\n\nimport { LadonOutput, MaskGenerator, PipelineConfig, resourceLoader } from '@webex/ladon-ts';\n\nimport { modelManager } from './model-manager';\n\nexport class LadonGenerator implements MaskGenerator {\n private lastResult: LadonOutput;\n private lastMask: ort.Tensor;\n private maskModel?: ort.InferenceSession;\n private lastMaskGenerationTime = 0;\n private output?: Float32Array;\n private modelUrl?: string;\n\n constructor(public readonly config: PipelineConfig) {\n const { height, width } = this.config.mask.outputSize;\n this.lastMask = new ort.Tensor('float32', new Float32Array(height * width), [\n 1,\n 1,\n height,\n width,\n ]);\n this.lastResult = {\n data: this.lastMask.data,\n facesAndLandmarks: { data: new Float32Array(0), dims: [] },\n gesture: new Float32Array(0),\n motion: 0,\n timestamp: 0,\n warm: false,\n };\n }\n\n public isLoaded(): boolean {\n return !!this.maskModel;\n }\n\n /**\n * This method preprocesses an input Uint8ClampedArray to a Float32Array\n * while maintaining memory efficiency by reusing a class-scoped output buffer.\n * If the model rank is 4 (e.g., newer tiny model), it sets an alpha channel value.\n *\n * @param {Uint8ClampedArray} input - The input data to be preprocessed\n * @param {Float32Array} alpha - The alpha channel data\n * @returns {Float32Array} - The processed data\n */\n private preprocess(input: Uint8ClampedArray, alpha: Float32Array): Float32Array {\n const { modelRank, inputSize, outputSize } = this.config.mask;\n const { height, width } = inputSize;\n const numImagePixels = height * width;\n\n // Initialize the output buffer if it is not already set\n this.output ??= new Float32Array(numImagePixels * modelRank);\n\n const numInputPixels = input.length / 4; // Divide by 4 for RGBA\n\n // Directly copy channels (assumes fixed order like BGR or RGB)\n for (let channel = 0; channel < 3; channel++) {\n for (let pixel = 0; pixel < numInputPixels; pixel++) {\n // Map input channels directly to output\n this.output[pixel + channel * numImagePixels] = input[pixel * 4 + (2 - channel)];\n }\n }\n\n // Scaling factors for width and height\n const widthScale = outputSize.width / width;\n const heightScale = outputSize.height / height;\n\n // Process alpha channel\n for (let x = 0; x < width; x++) {\n const nearestNeighborX = Math.floor(x * widthScale);\n for (let y = 0; y < height; y++) {\n const nearestNeighborY = Math.floor(y * heightScale);\n const maskIdx = nearestNeighborX + nearestNeighborY * outputSize.width;\n const outputIdx = x + y * width + 3 * numImagePixels;\n\n // Normalize and scale alpha to [0, 255]\n const normalizedValue = Math.min(Math.max(alpha[maskIdx], 0), 255);\n this.output[outputIdx] = normalizedValue;\n }\n }\n\n return this.output;\n }\n\n public getTimeSinceLastGeneration(): number {\n return Date.now() - this.lastMaskGenerationTime;\n }\n\n public async getLadonOutput(input: Uint8ClampedArray, timestamp: number): Promise<LadonOutput> {\n if (!this.maskModel) {\n throw new Error('[ladon-ts] Mask model not loaded.');\n }\n\n if (this.getTimeSinceLastGeneration() < this.config.mask.generationIntervalMs) {\n return {\n data: this.lastMask.data,\n facesAndLandmarks: this.lastResult.facesAndLandmarks,\n gesture: this.lastResult.gesture,\n motion: this.lastResult.motion,\n warm: false,\n timestamp,\n };\n }\n\n this.lastMaskGenerationTime = Date.now();\n\n const imageTensor = new ort.Tensor('float32', this.preprocess(input, this.lastMask.data), [\n 1,\n this.config.mask.modelRank,\n this.config.mask.inputSize.height,\n this.config.mask.inputSize.width,\n ]);\n\n const results = await this.maskModel.run({ input: imageTensor });\n this.lastMask = results.segmentation;\n\n this.lastResult = {\n data: this.lastMask.data ?? new Float32Array(0),\n facesAndLandmarks: {\n data: results.faces_and_landmarks?.data ?? new Float32Array(0),\n dims: results.faces_and_landmarks?.dims ?? ([] as readonly number[]),\n },\n gesture: results.gesture?.data ?? new Float32Array(0),\n motion: results.motion?.data[0] ?? 0,\n timestamp,\n warm: true,\n };\n\n return this.lastResult;\n }\n\n async load() {\n this.modelUrl = await resourceLoader.resolveUri(this.config, this.config.mask.modelUri);\n\n // Attempt to retrieve a preloaded InferenceSession from the shared resource manager.\n this.maskModel = modelManager.getModelSession(this.modelUrl);\n // If the model is not preloaded, load it from the provided model URL.\n this.maskModel ??= await modelManager.loadModel(this.config);\n\n if (!this.maskModel) {\n throw new Error('Failed to load the ONNX model.');\n }\n }\n\n public async postRender(): Promise<void> {\n // empty for local generator\n }\n\n /**\n * Destroys the model session and releases resources.\n * This method should be called when the generator is no longer needed.\n *\n * @returns A promise that resolves when the model is destroyed.\n */\n public async destroy(): Promise<void> {\n if (!this.modelUrl) {\n throw new Error('[ladon-ts] Generator teardown failed. Model URL is not defined.');\n }\n\n // Clear the model session from the cache.\n await modelManager.destroyModel(this.modelUrl);\n\n // Release the model session.\n this.modelUrl = undefined;\n this.maskModel = undefined;\n this.output = undefined;\n }\n}\n","import './shim';\nimport './console-overrides';\n\nimport { PipelineConfig, PreloadConfig } from '@webex/ladon-ts';\n\nimport { LadonGenerator } from './ladon-generator';\nimport { modelManager } from './model-manager';\n\n\nconst MAX_QUEUE_SIZE = 3;\nconst queue: { image: Uint8ClampedArray; timestamp: number }[] = [];\n\nlet preloadPromise: Promise<void> | null = null;\nlet generator: LadonGenerator;\nlet processing = false;\n\n\nasync function processQueue() {\n if (processing) return;\n processing = true;\n while (queue.length > 0) {\n const { image, timestamp } = queue.shift()!;\n await handleGenerate(image, timestamp);\n }\n setTimeout(() => {\n processing = false;\n }, 0);\n}\n\n\n// Message handler for worker\nself.addEventListener('message', async (event) => {\n const { type, config, image, timestamp } = event.data;\n\n try {\n switch (type) {\n case 'preload':\n if (config) {\n preloadPromise = handlePreload(config as PreloadConfig);\n await preloadPromise;\n }\n break;\n\n case 'init':\n if (config) {\n // Wait for preload to complete before initializing\n if (preloadPromise) {\n await preloadPromise;\n }\n await handleInit(config as PipelineConfig);\n }\n break;\n\n case 'generate':\n if (image) {\n if (queue.length >= MAX_QUEUE_SIZE) {\n // Drop the oldest frame and notify main thread\n const dropped = queue.shift();\n if (dropped) {\n postMessage({\n facesAndLandmarks: null,\n gesture: null,\n mask: null,\n motion: null,\n timestamp: dropped.timestamp,\n status: 'dropped',\n warm: false,\n });\n }\n }\n queue.push({ image, timestamp });\n processQueue();\n }\n break;\n\n case 'destroy':\n await handleDestroy();\n break;\n\n default:\n console.warn(\n `[ladon-ts] Worker generator recieved unknown message: ${JSON.stringify(\n event.data\n )}`\n );\n }\n } catch (error) {\n console.error(`[ladon-ts] Worker generator error handling message: ${error}`);\n postMessage({ status: 'error', error: error.message });\n }\n});\n\n// Handle preload event\nasync function handlePreload(config: PreloadConfig): Promise<void> {\n await modelManager.loadModel(config);\n postMessage({ status: 'preloaded' });\n}\n\n// Handle initialization\nasync function handleInit(config: PipelineConfig): Promise<void> {\n generator = new LadonGenerator(config);\n await generator.load();\n postMessage({ status: 'initialized' });\n}\n\n// Handle generate event with SharedArrayBuffer support\nasync function handleGenerate(image: Uint8ClampedArray | null, timestamp: number): Promise<void> {\n if (!generator || !generator.isLoaded()) {\n console.warn('[ladon-ts] Generator is not initialized');\n return;\n }\n\n if (!image) {\n console.warn('[ladon-ts] No valid input provided for generation');\n return;\n }\n\n // Run generator\n const maskResult = await generator.getLadonOutput(image, timestamp);\n\n postMessage({\n facesAndLandmarks: maskResult.facesAndLandmarks,\n gesture: maskResult.gesture,\n mask: maskResult.data, // Transfer mask directly if TypedArray\n motion: maskResult.motion,\n timestamp: maskResult.timestamp,\n status: 'generated',\n warm: maskResult.warm,\n });\n}\n\n// Handle destroy event\nasync function handleDestroy(): Promise<void> {\n if (generator) {\n await generator.destroy();\n } else {\n console.warn('[ladon-ts] No generator to destroy');\n }\n postMessage({ status: 'destroyed' });\n}\n"],"names":["args","o","e","r","l","s","d","url","u","fileUrl","cache","normalizedUrl","cachedResponse","response","contentType","fileBinary","cachedResponseWithHeaders","config","mask","providers","ort.env","wasmPaths","resourceLoader","error","modelUrl","modelSession","sessionOptions","modelBinary","ort.InferenceSession","session","inputSize","inputChannels","inputType","numPixels","dummyInputData","dummyInput","ort.Tensor","feed","dummyMaskData","prevMaskTensor","height","width","input","alpha","modelRank","outputSize","numImagePixels","numInputPixels","channel","pixel","widthScale","heightScale","x","nearestNeighborX","y","nearestNeighborY","maskIdx","outputIdx","normalizedValue","timestamp","imageTensor","results","_a","_b","_c","_d","image","event","type","dropped","maskResult"],"mappings":"oGAQC,KAAK,SAAoB,CACtB,QAAS,SAAS,MACtB,ECNA,MAAM,mBAAqB,QAAQ,IAC7B,oBAAsB,QAAQ,KAC9B,qBAAuB,QAAQ,MAErC,QAAQ,IAAM,IAAIA,IAAS,CACX,YAAA,CAAE,KAAM,MAAO,QAASA,EAAK,KAAK,GAAG,EAAG,SAAU,MAAO,EACrE,mBAAmB,GAAGA,CAAI,CAC9B,EAEA,QAAQ,KAAO,IAAIA,IAAS,CACZ,YAAA,CAAE,KAAM,MAAO,QAASA,EAAK,KAAK,GAAG,EAAG,SAAU,OAAQ,EACtE,oBAAoB,GAAGA,CAAI,CAC/B,EAEA,QAAQ,MAAQ,IAAIA,IAAS,CACb,YAAA,CAAE,KAAM,MAAO,QAASA,EAAK,KAAK,GAAG,EAAG,SAAU,QAAS,EACvE,qBAAqB,GAAGA,CAAI,CAChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,QACpB,KAAMA,EAAW,KACjB,OAAQA,EAAW,OACnB,UAAWA,EAAW,UACtB,OAAQ,YACR,KAAMA,EAAW,IAAA,CACpB,CACL,CAGA,eAAe,eAA+B,CACtC,UACA,MAAM,UAAU,QAAQ,EAExB,QAAQ,KAAK,oCAAoC,EAEzC,YAAA,CAAE,OAAQ,YAAa,CACvC"}
1
+ {"version":3,"file":"segmentation.js","sources":["../src/shim.ts","../src/console-overrides.ts","../../build/module/lib/util.js","../../build/module/lib/resource-loader.js","../src/util.ts","../src/model-manager.ts","../src/ladon-generator.ts","../src/segmentation.ts"],"sourcesContent":["/**\n * This file is used to provide a shim for the document object in a web worker.\n * The document object is not available in a web worker, so we need to provide a shim\n * to prevent errors when running the code in a web worker.\n * \n * See: https://github.com/vitejs/vite/issues/9879#issuecomment-1372112651\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(self.document as any) = {\n baseURI: location.origin\n};","/**\n * Override console methods to send logs to the main thread for display in the UI.\n */\n\nconst originalConsoleLog = console.log;\nconst originalConsoleWarn = console.warn;\nconst originalConsoleError = console.error;\n\nconsole.log = (...args) => {\n postMessage({ type: 'log', message: args.join(' '), severity: 'log' });\n originalConsoleLog(...args);\n};\n\nconsole.warn = (...args) => {\n postMessage({ type: 'log', message: args.join(' '), severity: 'warn' });\n originalConsoleWarn(...args);\n};\n\nconsole.error = (...args) => {\n postMessage({ type: 'log', message: args.join(' '), severity: 'error' });\n originalConsoleError(...args);\n};","var I = /* @__PURE__ */ ((o) => (o.Nearest = \"nearest\", o))(I || {});\nconst U = (o, n, u, r, e) => {\n const l = new Uint8ClampedArray(r * e * 4), p = n / r, y = u / e, s = n * 4;\n let a = 0;\n for (let t = 0; t < e; t++) {\n const f = Math.floor(t * y) * s;\n for (let c = 0; c < r; c++) {\n const m = f + Math.floor(c * p) * 4;\n l[a++] = o[m], l[a++] = o[m + 1], l[a++] = o[m + 2], l[a++] = o[m + 3];\n }\n }\n return l;\n};\nfunction A(o, n, u, r, e) {\n const l = new Uint8ClampedArray(r * e);\n if (n === r && u === e) {\n for (let s = 0; s < o.length; s++)\n l[s] = Math.min(Math.max(o[s], 0), 255);\n return l;\n }\n const p = (n - 1) / (r - 1), y = (u - 1) / (e - 1);\n for (let s = 0; s < e; s++)\n for (let a = 0; a < r; a++) {\n const t = p * a, f = y * s, c = Math.floor(t), m = Math.floor(f), S = Math.min(Math.ceil(t), n - 1), x = Math.min(Math.ceil(f), u - 1), w = t - c, i = f - m, M = o[m * n + c], h = o[m * n + S], k = o[x * n + c], P = o[x * n + S], E = M * (1 - w) * (1 - i) + h * w * (1 - i) + k * (1 - w) * i + P * w * i;\n l[s * r + a] = Math.min(Math.max(E, 0), 255);\n }\n return l;\n}\nfunction d(o, n, u, r, e) {\n const l = new Uint8ClampedArray(r * e), p = n / r, y = u / e, s = (t, f) => {\n if (t === 0) return 1;\n if (t < 0 && (t = -t), t < f) {\n const c = Math.PI * t;\n return f * Math.sin(c) * Math.sin(c / f) / (c * c);\n }\n return 0;\n }, a = 3;\n for (let t = 0; t < e; t++)\n for (let f = 0; f < r; f++) {\n const c = f * p, m = t * y, S = Math.floor(c), x = Math.floor(m);\n let w = 0, i = 0;\n for (let M = x - a + 1; M <= x + a; M++)\n for (let h = S - a + 1; h <= S + a; h++)\n if (h >= 0 && h < n && M >= 0 && M < u) {\n const k = o[M * n + h], P = s(c - h, a) * s(m - M, a);\n w += k * P, i += P;\n }\n l[t * r + f] = i !== 0 ? Math.round(w / i) : 0;\n }\n return l;\n}\nfunction L(o, n, u) {\n const r = o.createShader(n);\n if (!r)\n throw new Error(\"[ladon-ts] Error creating shader\");\n if (o.shaderSource(r, u), o.compileShader(r), !o.getShaderParameter(r, o.COMPILE_STATUS)) {\n const e = o.getShaderInfoLog(r) ?? \"unknown error compiling shader.\";\n throw new Error(\"[ladon-ts] \" + e);\n }\n return r;\n}\nfunction R(o, n, u) {\n const r = o.createProgram();\n if (!r)\n throw new Error(\"[ladon-ts] Error creating GPU program\");\n if (o.attachShader(r, n), o.attachShader(r, u), o.linkProgram(r), !o.getProgramParameter(r, o.LINK_STATUS)) {\n const e = o.getProgramInfoLog(r) ?? \"unknown error linking program.\";\n throw new Error(\"[ladon-ts] \" + e);\n }\n return r;\n}\nfunction C(o) {\n if (o.startsWith(\"blob:\"))\n return !0;\n try {\n return new URL(o), !0;\n } catch {\n return !1;\n }\n}\nconst T = (o, n) => !n || o.startsWith(\"http\") ? new URL(o).href : o ? n.replace(/\\/+$/, \"\") + \"/\" + o.replace(/^\\/+/, \"\") : n;\nexport {\n I as InterpolationMethod,\n A as bilinearUpsample,\n L as compileShader,\n C as isResolvedUri,\n d as lanczos3Upsample,\n R as linkProgram,\n U as resizeImage,\n T as toAbsoluteURI\n};\n//# sourceMappingURL=util.js.map\n","import { isResolvedUri as l, toAbsoluteURI as s } from \"./util.js\";\nclass t {\n constructor() {\n this.resolvedUriCache = /* @__PURE__ */ new Map();\n }\n /**\n * Resolves the full URL for a given asset. Non-file URIs are treated as paths and resolved\n * using the `toAbsoluteURI` method. If the assetUri is already resolved, or if it's found in\n * cache, it will be returned directly. If an assetUrlResolver function is provided in the\n * configuration, it will be used to resolve the URL if the assetUri is not fully qualified,\n * a blob URL, or in the cache.\n *\n * @param config - The preload configuration.\n * @param assetUri - The asset URI from the config.\n * @returns The resolved full URL.\n */\n async resolveUri(o, e) {\n if (!e)\n throw new Error(\"Asset URI is undefined.\");\n if (this.resolvedUriCache.has(e))\n return this.resolvedUriCache.get(e);\n let r;\n if (l(e) ? r = e : e.match(/\\.[a-z0-9]+$/i) ? typeof o.assetUrlResolver == \"function\" && (r = await o.assetUrlResolver(e, o)) : r = s(e, o.baseUrl), !r)\n throw new Error(`Failed to resolve asset URI: ${e}`);\n return this.resolvedUriCache.set(e, r), r;\n }\n}\nconst d = new t();\nexport {\n t as ResourceLoader,\n d as resourceLoader\n};\n//# sourceMappingURL=resource-loader.js.map\n","export { isResolvedUri, toAbsoluteURI } from '@webex/ladon-ts';\n\n/**\n * Helper to strip query params.\n *\n * @param url - The URL to strip query params from.\n * @returns The URL without query params.\n */\nfunction stripQueryParams(url: string): string {\n try {\n const u = new URL(url);\n u.search = '';\n return u.toString();\n } catch {\n return url;\n }\n}\n\n/**\n * Fetches a JavaScript module from the given URL, caches it in the 'ladon-cache' \n * Cache API if the URL is HTTP(S), and returns a Blob URL for use with APIs.\n * \n * @param url - The URL of the JavaScript module to fetch.\n * @returns A promise that resolves to a Blob URL for the fetched module.\n */\nexport async function loadAndCacheFile(fileUrl: string): Promise<ArrayBufferLike | Uint8Array> {\n const cache = await caches.open('ladon-cache');\n\n // Normalize the URL by stripping query parameters\n const normalizedUrl = stripQueryParams(fileUrl);\n\n // Try to get the file from cache using its full URL\n const cachedResponse = await cache.match(normalizedUrl);\n if (cachedResponse) {\n return cachedResponse.arrayBuffer();\n }\n\n // If not in cache, fetch and cache the file\n const response = await fetch(fileUrl);\n\n // Ensure the response is valid\n if (!response.ok) {\n throw new Error(`Failed to fetch file: ${fileUrl}`);\n }\n\n const contentType = response.headers.get('Content-Type') || 'binary/octet-stream';\n\n // Validate expected MIME types\n if (!contentType.includes('application/wasm') && !contentType.includes('binary/octet-stream')) {\n throw new Error(`Unexpected MIME type: ${contentType} for ${normalizedUrl}`);\n }\n\n const fileBinary = await response.arrayBuffer();\n\n // Cache the response with proper headers\n const cachedResponseWithHeaders = new Response(fileBinary, {\n headers: {\n 'Content-Type': contentType,\n 'Content-Length': fileBinary.byteLength.toString(),\n },\n });\n\n // Store the response in the cache using the full URL as the key\n await cache.put(normalizedUrl, cachedResponseWithHeaders);\n\n return fileBinary;\n}\n","import * as ort from 'onnxruntime-web';\nimport { PreloadConfig, ResolutionConfig, resourceLoader } from '@webex/ladon-ts';\n\nimport { loadAndCacheFile } from './util';\n\n// There is only a single WASM file for all WebAssembly binaries now.\nconst ONNX_WASM_FILENAME = 'ort-wasm-simd-threaded.wasm';\n\n/**\n * Resource manager used to load resources for the segmentation worker.\n */\nexport class ModelManager {\n private modelSessions: Record<string, ort.InferenceSession> = {};\n\n /**\n * Load the model using the provided configuration. This gets called by the worker when using\n * the worker generator.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the model is preloaded.\n */\n public async loadModel(config: PreloadConfig) {\n const { mask, executionProviders: providers } = config;\n\n // Lock to a single thread to avoid performance issues.\n ort.env.wasm.numThreads = 1;\n\n // Get the resolved paths for the WASM binary.\n const wasmPaths = await resourceLoader.resolveUri(config, config.wasmUri);\n\n if (wasmPaths) {\n try {\n ort.env.wasm.wasmBinary = await loadAndCacheFile(wasmPaths + ONNX_WASM_FILENAME);\n } catch (error) {\n console.warn('Failed to load or cache WASM file. Using WASM paths.', error);\n ort.env.wasm.wasmPaths = wasmPaths;\n }\n }\n\n // Resolve the model URL.\n const modelUrl = await resourceLoader.resolveUri(config, mask.modelUri);\n let modelSession = this.modelSessions[modelUrl];\n\n // If the model session is not already cached, create a new session and cache.\n if (!modelSession) {\n // Allows the user to specify the execution providers to use. The default is the WASM provider.\n // TODO: Add and test support for other execution providers.\n const executionProviders = providers?.length ? providers : ['wasm'];\n const sessionOptions = { executionProviders };\n\n // First try to get the model binary either from cache or by fetching and caching it.\n // If that fails, fall back to the model URL.\n try {\n const modelBinary = await loadAndCacheFile(modelUrl);\n modelSession = await ort.InferenceSession.create(modelBinary, sessionOptions);\n } catch (error) {\n console.warn('Failed to load or cache model file. Using model URL.', error);\n modelSession = await ort.InferenceSession.create(modelUrl, sessionOptions);\n }\n }\n\n // Cache the model session.\n this.modelSessions[modelUrl] = modelSession;\n\n // Warmup the model with a dummy input to avoid latency when running the model for the first time.\n await this.warmupModel(modelSession, mask.inputSize, mask.modelRank);\n\n return modelSession;\n }\n\n /**\n * Warmup the model session with a dummy input to avoid latency when running the model for the first time.\n *\n * @param {ort.InferenceSession} session The model session.\n * @param {ResolutionConfig} inputSize The input size of the model.\n * @param {number} inputChannels The number of input channels (e.g., RGB is 3).\n * @param {ort.Tensor.Type} inputType The input tensor type.\n * @returns {Promise<void>} A promise that resolves when the model is warmed up.\n * @example\n * await warmupModel(session, inputSize, inputChannels, inputType);\n */\n public async warmupModel(\n session: ort.InferenceSession,\n inputSize: ResolutionConfig = { width: 1280, height: 720 },\n inputChannels = 3,\n inputType: ort.Tensor.Type = 'float32'\n ): Promise<void> {\n const numPixels = inputSize.height * inputSize.width;\n const dummyInputData = new Float32Array(inputChannels * numPixels).fill(0);\n const dummyInput = new ort.Tensor(inputType, dummyInputData, [\n 1,\n inputChannels,\n inputSize.height,\n inputSize.width,\n ]);\n const feed = { [session.inputNames[0]]: dummyInput };\n\n // Use an additional dummy tensor if the model expects a previous mask.\n if (inputChannels === 3) {\n const dummyMaskData = new Float32Array(numPixels).fill(0);\n const prevMaskTensor = new ort.Tensor(inputType, dummyMaskData, [\n 1,\n 1,\n inputSize.height,\n inputSize.width,\n ]);\n feed[session.inputNames[1]] = prevMaskTensor;\n }\n\n // Run the model with the dummy input to warm it up.\n await session.run(feed);\n }\n\n /**\n * Get the model session for the provided model URL.\n *\n * @param {string} modelUrl The model URL.\n * @returns {ort.InferenceSession} The model session.\n * @example\n * const session = getModelSession(modelUrl);\n */\n public getModelSession(modelUrl: string) {\n return this.modelSessions[modelUrl];\n }\n\n /**\n * Clear the model sessions cache.\n *\n * @example\n * modelManager.destroyModel();\n */\n public async destroyModel(modelUrl: string) {\n const session = this.modelSessions[modelUrl];\n if (session) {\n await session.release();\n delete this.modelSessions[modelUrl];\n }\n }\n \n}\n\nexport const modelManager = new ModelManager();","import * as ort from 'onnxruntime-web';\n\nimport { LadonOutput, MaskGenerator, PipelineConfig, resourceLoader } from '@webex/ladon-ts';\n\nimport { modelManager } from './model-manager';\n\nexport class LadonGenerator implements MaskGenerator {\n private lastResult: LadonOutput;\n private lastMask: ort.Tensor;\n private maskModel?: ort.InferenceSession;\n private lastMaskGenerationTime = 0;\n private output?: Float32Array;\n private modelUrl?: string;\n\n constructor(public readonly config: PipelineConfig) {\n const { height, width } = this.config.mask.outputSize;\n this.lastMask = new ort.Tensor('float32', new Float32Array(height * width), [\n 1,\n 1,\n height,\n width,\n ]);\n this.lastResult = {\n data: this.lastMask.data,\n facesAndLandmarks: { data: new Float32Array(0), dims: [] },\n gesture: new Float32Array(0),\n motion: 0,\n timestamp: 0,\n warm: false,\n };\n }\n\n public isLoaded(): boolean {\n return !!this.maskModel;\n }\n\n /**\n * This method preprocesses an input Uint8ClampedArray to a Float32Array\n * while maintaining memory efficiency by reusing a class-scoped output buffer.\n * If the model rank is 4 (e.g., newer tiny model), it sets an alpha channel value.\n *\n * @param {Uint8ClampedArray} input - The input data to be preprocessed\n * @param {Float32Array} alpha - The alpha channel data\n * @returns {Float32Array} - The processed data\n */\n private preprocess(input: Uint8ClampedArray, alpha: Float32Array): Float32Array {\n const { modelRank, inputSize, outputSize } = this.config.mask;\n const { height, width } = inputSize;\n const numImagePixels = height * width;\n\n // Initialize the output buffer if it is not already set\n this.output ??= new Float32Array(numImagePixels * modelRank);\n\n const numInputPixels = input.length / 4; // Divide by 4 for RGBA\n\n // Directly copy channels (assumes fixed order like BGR or RGB)\n for (let channel = 0; channel < 3; channel++) {\n for (let pixel = 0; pixel < numInputPixels; pixel++) {\n // Map input channels directly to output\n this.output[pixel + channel * numImagePixels] = input[pixel * 4 + (2 - channel)];\n }\n }\n\n // Scaling factors for width and height\n const widthScale = outputSize.width / width;\n const heightScale = outputSize.height / height;\n\n // Process alpha channel\n for (let x = 0; x < width; x++) {\n const nearestNeighborX = Math.floor(x * widthScale);\n for (let y = 0; y < height; y++) {\n const nearestNeighborY = Math.floor(y * heightScale);\n const maskIdx = nearestNeighborX + nearestNeighborY * outputSize.width;\n const outputIdx = x + y * width + 3 * numImagePixels;\n\n // Normalize and scale alpha to [0, 255]\n const normalizedValue = Math.min(Math.max(alpha[maskIdx], 0), 255);\n this.output[outputIdx] = normalizedValue;\n }\n }\n\n return this.output;\n }\n\n public getTimeSinceLastGeneration(): number {\n return Date.now() - this.lastMaskGenerationTime;\n }\n\n public async getLadonOutput(input: Uint8ClampedArray, timestamp: number): Promise<LadonOutput> {\n if (!this.maskModel) {\n throw new Error('[ladon-ts] Mask model not loaded.');\n }\n\n if (this.getTimeSinceLastGeneration() < this.config.mask.generationIntervalMs) {\n return {\n data: this.lastMask.data,\n facesAndLandmarks: this.lastResult.facesAndLandmarks,\n gesture: this.lastResult.gesture,\n motion: this.lastResult.motion,\n warm: false,\n timestamp,\n };\n }\n\n this.lastMaskGenerationTime = Date.now();\n\n const imageTensor = new ort.Tensor('float32', this.preprocess(input, this.lastMask.data), [\n 1,\n this.config.mask.modelRank,\n this.config.mask.inputSize.height,\n this.config.mask.inputSize.width,\n ]);\n\n const results = await this.maskModel.run({ input: imageTensor });\n this.lastMask = results.segmentation;\n\n this.lastResult = {\n data: this.lastMask.data ?? new Float32Array(0),\n facesAndLandmarks: {\n data: results.faces_and_landmarks?.data ?? new Float32Array(0),\n dims: results.faces_and_landmarks?.dims ?? ([] as readonly number[]),\n },\n gesture: results.gesture?.data ?? new Float32Array(0),\n motion: results.motion?.data[0] ?? 0,\n timestamp,\n warm: true,\n };\n\n return this.lastResult;\n }\n\n async load() {\n this.modelUrl = await resourceLoader.resolveUri(this.config, this.config.mask.modelUri);\n\n // Attempt to retrieve a preloaded InferenceSession from the shared resource manager.\n this.maskModel = modelManager.getModelSession(this.modelUrl);\n // If the model is not preloaded, load it from the provided model URL.\n this.maskModel ??= await modelManager.loadModel(this.config);\n\n if (!this.maskModel) {\n throw new Error('Failed to load the ONNX model.');\n }\n }\n\n public async process(): Promise<void> {\n // empty for local generator\n }\n\n /**\n * Destroys the model session and releases resources.\n * This method should be called when the generator is no longer needed.\n *\n * @returns A promise that resolves when the model is destroyed.\n */\n public async destroy(): Promise<void> {\n if (!this.modelUrl) {\n throw new Error('[ladon-ts] Generator teardown failed. Model URL is not defined.');\n }\n\n // Clear the model session from the cache.\n await modelManager.destroyModel(this.modelUrl);\n\n // Release the model session.\n this.modelUrl = undefined;\n this.maskModel = undefined;\n this.output = undefined;\n }\n}\n","import './shim';\nimport './console-overrides';\n\nimport { PipelineConfig, PreloadConfig } from '@webex/ladon-ts';\n\nimport { LadonGenerator } from './ladon-generator';\nimport { modelManager } from './model-manager';\n\n\nconst MAX_QUEUE_SIZE = 3;\nconst queue: { image: Uint8ClampedArray; timestamp: number }[] = [];\n\nlet preloadPromise: Promise<void> | null = null;\nlet generator: LadonGenerator;\nlet processing = false;\n\n\nasync function processQueue() {\n if (processing) return;\n processing = true;\n while (queue.length > 0) {\n const { image, timestamp } = queue.shift()!;\n await handleGenerate(image, timestamp);\n }\n setTimeout(() => {\n processing = false;\n }, 0);\n}\n\n\n// Message handler for worker\nself.addEventListener('message', async (event) => {\n const { type, config, image, timestamp } = event.data;\n\n try {\n switch (type) {\n case 'preload':\n if (config) {\n preloadPromise = handlePreload(config as PreloadConfig);\n await preloadPromise;\n }\n break;\n\n case 'init':\n if (config) {\n // Wait for preload to complete before initializing\n if (preloadPromise) {\n await preloadPromise;\n }\n await handleInit(config as PipelineConfig);\n }\n break;\n\n case 'generate':\n if (image) {\n if (queue.length >= MAX_QUEUE_SIZE) {\n // Drop the oldest frame and notify main thread\n const dropped = queue.shift();\n if (dropped) {\n postMessage({\n facesAndLandmarks: null,\n gesture: null,\n mask: null,\n motion: null,\n timestamp: dropped.timestamp,\n status: 'dropped',\n warm: false,\n });\n }\n }\n queue.push({ image, timestamp });\n processQueue();\n }\n break;\n\n case 'destroy':\n await handleDestroy();\n break;\n\n default:\n console.warn(\n `[ladon-ts] Worker generator recieved unknown message: ${JSON.stringify(\n event.data\n )}`\n );\n }\n } catch (error) {\n console.error(`[ladon-ts] Worker generator error handling message: ${error}`);\n postMessage({ status: 'error', error: error.message });\n }\n});\n\n// Handle preload event\nasync function handlePreload(config: PreloadConfig): Promise<void> {\n await modelManager.loadModel(config);\n postMessage({ status: 'preloaded' });\n}\n\n// Handle initialization\nasync function handleInit(config: PipelineConfig): Promise<void> {\n generator = new LadonGenerator(config);\n await generator.load();\n postMessage({ status: 'initialized' });\n}\n\n// Handle generate event with SharedArrayBuffer support\nasync function handleGenerate(image: Uint8ClampedArray | null, timestamp: number): Promise<void> {\n if (!generator || !generator.isLoaded()) {\n console.warn('[ladon-ts] Generator is not initialized');\n return;\n }\n\n if (!image) {\n console.warn('[ladon-ts] No valid input provided for generation');\n return;\n }\n\n // Run generator\n const maskResult = await generator.getLadonOutput(image, timestamp);\n\n postMessage({\n facesAndLandmarks: maskResult.facesAndLandmarks,\n gesture: maskResult.gesture,\n mask: maskResult.data, // Transfer mask directly if TypedArray\n motion: maskResult.motion,\n timestamp: maskResult.timestamp,\n status: 'generated',\n warm: maskResult.warm,\n });\n}\n\n// Handle destroy event\nasync function handleDestroy(): Promise<void> {\n if (generator) {\n await generator.destroy();\n } else {\n console.warn('[ladon-ts] No generator to destroy');\n }\n postMessage({ status: 'destroyed' });\n}\n"],"names":["args","o","e","r","l","s","d","url","u","fileUrl","cache","normalizedUrl","cachedResponse","response","contentType","fileBinary","cachedResponseWithHeaders","config","mask","providers","ort.env","wasmPaths","resourceLoader","error","modelUrl","modelSession","sessionOptions","modelBinary","ort.InferenceSession","session","inputSize","inputChannels","inputType","numPixels","dummyInputData","dummyInput","ort.Tensor","feed","dummyMaskData","prevMaskTensor","height","width","input","alpha","modelRank","outputSize","numImagePixels","numInputPixels","channel","pixel","widthScale","heightScale","x","nearestNeighborX","y","nearestNeighborY","maskIdx","outputIdx","normalizedValue","timestamp","imageTensor","results","_a","_b","_c","_d","image","event","type","dropped","maskResult"],"mappings":"oGAQC,KAAK,SAAoB,CACtB,QAAS,SAAS,MACtB,ECNA,MAAM,mBAAqB,QAAQ,IAC7B,oBAAsB,QAAQ,KAC9B,qBAAuB,QAAQ,MAErC,QAAQ,IAAM,IAAIA,IAAS,CACX,YAAA,CAAE,KAAM,MAAO,QAASA,EAAK,KAAK,GAAG,EAAG,SAAU,MAAO,EACrE,mBAAmB,GAAGA,CAAI,CAC9B,EAEA,QAAQ,KAAO,IAAIA,IAAS,CACZ,YAA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KACJ,yDAAyD,KAAK,UAC1DQ,EAAM,IAAA,CACT,EACL,CAAA,QAEH5C,EAAO,CACJ,QAAA,MAAM,uDAAuDA,CAAK,EAAE,EAC5E,YAAY,CAAE,OAAQ,QAAS,MAAOA,EAAM,QAAS,CAAA,CAE7D,CAAC,EAGD,eAAe,cAAcN,EAAsC,CACzD,MAAA,aAAa,UAAUA,CAAM,EACvB,YAAA,CAAE,OAAQ,YAAa,CACvC,CAGA,eAAe,WAAWA,EAAuC,CACjD,UAAA,IAAI,eAAeA,CAAM,EACrC,MAAM,UAAU,KAAK,EACT,YAAA,CAAE,OAAQ,cAAe,CACzC,CAGA,eAAe,eAAeiD,EAAiCP,EAAkC,CAC7F,GAAI,CAAC,WAAa,CAAC,UAAU,WAAY,CACrC,QAAQ,KAAK,yCAAyC,EACtD,MAAA,CAGJ,GAAI,CAACO,EAAO,CACR,QAAQ,KAAK,mDAAmD,EAChE,MAAA,CAIJ,MAAMI,EAAa,MAAM,UAAU,eAAeJ,EAAOP,CAAS,EAEtD,YAAA,CACR,kBAAmBW,EAAW,kBAC9B,QAASA,EAAW,QACpB,KAAMA,EAAW,KACjB,OAAQA,EAAW,OACnB,UAAWA,EAAW,UACtB,OAAQ,YACR,KAAMA,EAAW,IAAA,CACpB,CACL,CAGA,eAAe,eAA+B,CACtC,UACA,MAAM,UAAU,QAAQ,EAExB,QAAQ,KAAK,oCAAoC,EAEzC,YAAA,CAAE,OAAQ,YAAa,CACvC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webex/ladon-ts",
3
- "version": "5.8.0",
3
+ "version": "5.9.1",
4
4
  "description": "WebexIntelligence computer vision library",
5
5
  "type": "module",
6
6
  "main": "build/module/index.js",